micropdf 0.17.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
//! C FFI for fz_font - MicroPDF compatible font handling
//!
//! Provides FFI bindings for font loading and glyph operations.

use super::{Handle, HandleStore, safe_helpers};
use crate::fitz::font::Font;
use std::sync::LazyLock;

/// Font storage
pub static FONTS: LazyLock<HandleStore<Font>> = LazyLock::new(HandleStore::default);

/// Create a new font
///
/// # Safety
/// Caller must ensure name is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_font(
    _ctx: Handle,
    name: *const std::ffi::c_char,
    _is_bold: i32,
    _is_italic: i32,
    _font_file: Handle,
) -> Handle {
    let font_name = match safe_helpers::c_str_to_str(name) {
        Some(s) => s,
        None => return 0,
    };

    let font = Font::new(font_name);
    FONTS.insert(font)
}

/// Create a new font from data
///
/// # Safety
/// Caller must ensure data points to readable memory of at least len bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_font_from_memory(
    _ctx: Handle,
    name: *const std::ffi::c_char,
    data: *const u8,
    len: i32,
    index: i32,
    _use_glyph_bbox: i32,
) -> Handle {
    if data.is_null() || len <= 0 {
        return 0;
    }

    let font_name = safe_helpers::c_str_to_str(name).unwrap_or("Unknown");

    // Read font data
    let font_data = match safe_helpers::copy_from_ptr(data, len as usize) {
        Some(data) => data,
        None => return 0,
    };

    // Create font from data
    let font = Font::from_data(font_name, &font_data, index as usize);
    match font {
        Ok(f) => FONTS.insert(f),
        Err(_) => 0,
    }
}

/// Create a new font from file
///
/// # Safety
/// Caller must ensure path is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_font_from_file(
    _ctx: Handle,
    name: *const std::ffi::c_char,
    path: *const std::ffi::c_char,
    index: i32,
    _use_glyph_bbox: i32,
) -> Handle {
    let path_str = match safe_helpers::c_str_to_str(path) {
        Some(s) => s,
        None => return 0,
    };

    let font_name = safe_helpers::c_str_to_str(name).unwrap_or("Unknown");

    // Read font file
    match std::fs::read(path_str) {
        Ok(data) => match Font::from_data(font_name, &data, index as usize) {
            Ok(f) => FONTS.insert(f),
            Err(_) => 0,
        },
        Err(_) => 0,
    }
}

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

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

/// Get font name
///
/// # Safety
/// Caller must ensure buf points to writable memory of at least 64 bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_name(_ctx: Handle, font: Handle, buf: *mut std::ffi::c_char, size: i32) {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            let name = guard.name();
            safe_helpers::str_to_c_buffer(name, buf, size);
        }
    }
}

/// Check if font is bold
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_is_bold(_ctx: Handle, font: Handle) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return i32::from(guard.is_bold());
        }
    }
    0
}

/// Check if font is italic
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_is_italic(_ctx: Handle, font: Handle) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return i32::from(guard.is_italic());
        }
    }
    0
}

/// Check if font is serif
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_is_serif(_ctx: Handle, font: Handle) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return i32::from(guard.is_serif());
        }
    }
    0
}

/// Check if font is monospaced
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_is_monospaced(_ctx: Handle, font: Handle) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return i32::from(guard.is_monospace());
        }
    }
    0
}

/// Encode character to glyph ID
#[unsafe(no_mangle)]
pub extern "C" fn fz_encode_character(_ctx: Handle, font: Handle, unicode: i32) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return guard.encode_character(unicode as u32) as i32;
        }
    }
    0
}

/// Encode character with fallback
#[unsafe(no_mangle)]
pub extern "C" fn fz_encode_character_with_fallback(
    _ctx: Handle,
    font: Handle,
    unicode: i32,
    _script: i32,
    _language: i32,
    out_font: *mut Handle,
) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            let glyph = guard.encode_character(unicode as u32);

            // Set output font to same font
            safe_helpers::write_ptr(font, out_font);

            return glyph as i32;
        }
    }
    0
}

/// Get glyph advance width
#[unsafe(no_mangle)]
pub extern "C" fn fz_advance_glyph(_ctx: Handle, font: Handle, glyph: i32, _wmode: i32) -> f32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return guard.glyph_advance(glyph as u16);
        }
    }
    0.0
}

/// Get glyph bounding box
#[unsafe(no_mangle)]
pub extern "C" fn fz_bound_glyph(
    _ctx: Handle,
    font: Handle,
    glyph: i32,
    _transform: super::geometry::fz_matrix,
) -> super::geometry::fz_rect {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            let bbox = guard.glyph_bbox(glyph as u16);
            return super::geometry::fz_rect {
                x0: bbox.x0,
                y0: bbox.y0,
                x1: bbox.x1,
                y1: bbox.y1,
            };
        }
    }
    super::geometry::fz_rect {
        x0: 0.0,
        y0: 0.0,
        x1: 0.0,
        y1: 0.0,
    }
}

/// Get font bbox
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_bbox(_ctx: Handle, font: Handle) -> super::geometry::fz_rect {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            let bbox = guard.bbox();
            return super::geometry::fz_rect {
                x0: bbox.x0,
                y0: bbox.y0,
                x1: bbox.x1,
                y1: bbox.y1,
            };
        }
    }
    super::geometry::fz_rect {
        x0: 0.0,
        y0: 0.0,
        x1: 0.0,
        y1: 0.0,
    }
}

/// Outline glyph (extract vector path)
#[unsafe(no_mangle)]
pub extern "C" fn fz_outline_glyph(
    _ctx: Handle,
    font: Handle,
    glyph: i32,
    _transform: super::geometry::fz_matrix,
) -> Handle {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            let path = guard.outline_glyph(glyph as u16);
            return super::path::PATHS.insert(path);
        }
    }
    0
}

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

/// Clone a font (increase ref count)
#[unsafe(no_mangle)]
pub extern "C" fn fz_clone_font(_ctx: Handle, font: Handle) -> Handle {
    fz_keep_font(_ctx, font)
}

/// Get font ascender height
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_ascender(_ctx: Handle, font: Handle) -> f32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return guard.ascender();
        }
    }
    0.0
}

/// Get font descender height
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_descender(_ctx: Handle, font: Handle) -> f32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return guard.descender();
        }
    }
    0.0
}

/// Get glyph name
#[unsafe(no_mangle)]
pub extern "C" fn fz_glyph_name(
    _ctx: Handle,
    font: Handle,
    glyph: i32,
    buf: *mut std::ffi::c_char,
    size: i32,
) {
    if buf.is_null() || size <= 0 {
        return;
    }

    // Look up name from the font's glyph name table if available,
    // otherwise fall back to the Adobe Glyph List for standard names.
    // The Font struct stores charmap (unicode → glyph ID) but not the
    // reverse glyph-name table, so we rely on the AGL fallback.
    let name = adobe_glyph_name(glyph as u16);
    let bytes = name.as_bytes();
    let copy_len = bytes.len().min((size - 1) as usize);

    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), buf as *mut u8, copy_len);
        *buf.add(copy_len) = 0;
    }
}

/// Map glyph IDs to Adobe Glyph List names for common characters
fn adobe_glyph_name(gid: u16) -> String {
    match gid {
        0 => ".notdef".to_string(),
        0x20 => "space".to_string(),
        0x21 => "exclam".to_string(),
        0x22 => "quotedbl".to_string(),
        0x23 => "numbersign".to_string(),
        0x24 => "dollar".to_string(),
        0x25 => "percent".to_string(),
        0x26 => "ampersand".to_string(),
        0x27 => "quotesingle".to_string(),
        0x28 => "parenleft".to_string(),
        0x29 => "parenright".to_string(),
        0x2A => "asterisk".to_string(),
        0x2B => "plus".to_string(),
        0x2C => "comma".to_string(),
        0x2D => "hyphen".to_string(),
        0x2E => "period".to_string(),
        0x2F => "slash".to_string(),
        0x30..=0x39 => {
            const DIGITS: [&str; 10] = [
                "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
            ];
            DIGITS[(gid - 0x30) as usize].to_string()
        }
        0x3A => "colon".to_string(),
        0x3B => "semicolon".to_string(),
        0x3C => "less".to_string(),
        0x3D => "equal".to_string(),
        0x3E => "greater".to_string(),
        0x3F => "question".to_string(),
        0x40 => "at".to_string(),
        0x41..=0x5A => String::from(char::from(gid as u8)),
        0x5B => "bracketleft".to_string(),
        0x5C => "backslash".to_string(),
        0x5D => "bracketright".to_string(),
        0x5E => "asciicircum".to_string(),
        0x5F => "underscore".to_string(),
        0x60 => "grave".to_string(),
        0x61..=0x7A => String::from(char::from(gid as u8)),
        0x7B => "braceleft".to_string(),
        0x7C => "bar".to_string(),
        0x7D => "braceright".to_string(),
        0x7E => "asciitilde".to_string(),
        _ => format!("uni{:04X}", gid),
    }
}

/// Check if font is embedded
#[unsafe(no_mangle)]
pub extern "C" fn fz_font_is_embedded(_ctx: Handle, font: Handle) -> i32 {
    if let Some(f) = FONTS.get(font) {
        if let Ok(guard) = f.lock() {
            return if guard.is_embedded() { 1 } else { 0 };
        }
    }
    0
}

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

    #[test]
    fn test_new_font() {
        let font_handle = fz_new_font(0, c"Helvetica".as_ptr(), 0, 0, 0);
        assert_ne!(font_handle, 0);
        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_new_font_null_name() {
        let font_handle = fz_new_font(0, std::ptr::null(), 0, 0, 0);
        assert_eq!(font_handle, 0);
    }

    #[test]
    fn test_keep_font() {
        let font_handle = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let kept = fz_keep_font(0, font_handle);
        assert_eq!(kept, font_handle);
        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_font_name() {
        let font_handle = fz_new_font(0, c"Times".as_ptr(), 0, 0, 0);
        let mut buf = [0i8; 64];
        fz_font_name(0, font_handle, buf.as_mut_ptr(), 64);

        let name = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()).to_str().unwrap() };
        assert_eq!(name, "Times");

        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_font_properties() {
        let font_handle = fz_new_font(0, c"Courier".as_ptr(), 1, 1, 0);

        // These will return default values since we're not loading actual font files
        let _is_bold = fz_font_is_bold(0, font_handle);
        let _is_italic = fz_font_is_italic(0, font_handle);
        let _is_serif = fz_font_is_serif(0, font_handle);
        let _is_monospaced = fz_font_is_monospaced(0, font_handle);

        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_encode_character() {
        let font_handle = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);

        // Encode 'A' (65)
        let glyph = fz_encode_character(0, font_handle, 65);
        assert!(glyph >= 0);

        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_advance_glyph() {
        let font_handle = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let glyph = fz_encode_character(0, font_handle, 65);

        let advance = fz_advance_glyph(0, font_handle, glyph, 0);
        assert!(advance >= 0.0);

        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_bound_glyph() {
        let font_handle = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let glyph = fz_encode_character(0, font_handle, 65);

        let bbox = fz_bound_glyph(
            0,
            font_handle,
            glyph,
            super::super::geometry::fz_matrix::identity(),
        );
        // Valid bounding box should have x1 > x0
        assert!(bbox.x1 >= bbox.x0);

        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_font_bbox() {
        let font_handle = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);

        let bbox = fz_font_bbox(0, font_handle);
        assert!(bbox.x1 >= bbox.x0);
        assert!(bbox.y1 >= bbox.y0);

        fz_drop_font(0, font_handle);
    }

    #[test]
    fn test_new_font_from_memory() {
        let font_data = b"Fake font data";
        let font_handle = fz_new_font_from_memory(
            0,
            c"Test".as_ptr(),
            font_data.as_ptr(),
            font_data.len() as i32,
            0,
            0,
        );
        if font_handle != 0 {
            fz_drop_font(0, font_handle);
        }
    }

    #[test]
    fn test_new_font_from_memory_null_data() {
        assert_eq!(
            fz_new_font_from_memory(0, c"Test".as_ptr(), std::ptr::null(), 10, 0, 0),
            0
        );
        assert_eq!(
            fz_new_font_from_memory(0, c"Test".as_ptr(), b"x".as_ptr(), 0, 0, 0),
            0
        );
    }

    #[test]
    fn test_new_font_from_memory_null_name() {
        let data = b"fake";
        let h = fz_new_font_from_memory(0, std::ptr::null(), data.as_ptr(), 4, 0, 0);
        if h != 0 {
            fz_drop_font(0, h);
        }
    }

    #[test]
    fn test_drop_font() {
        let h = fz_new_font(0, c"DropTest".as_ptr(), 0, 0, 0);
        fz_drop_font(0, h);
        assert_eq!(fz_font_is_valid(0, h), 0);
    }

    #[test]
    fn test_font_name_null_buf() {
        let h = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        fz_font_name(0, h, std::ptr::null_mut(), 64);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_encode_character_invalid_handle() {
        assert_eq!(fz_encode_character(0, 0, 65), 0);
        assert_eq!(fz_encode_character(0, 99999, 65), 0);
    }

    #[test]
    fn test_encode_character_with_fallback() {
        let h = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let mut out_font = 0u64;
        let glyph = fz_encode_character_with_fallback(0, h, 65, 0, 0, &mut out_font as *mut u64);
        assert!(glyph >= 0);
        assert_eq!(out_font, h);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_encode_character_with_fallback_invalid() {
        let mut out = 0u64;
        assert_eq!(
            fz_encode_character_with_fallback(0, 0, 65, 0, 0, &mut out),
            0
        );
    }

    #[test]
    fn test_advance_glyph_invalid() {
        assert!((fz_advance_glyph(0, 0, 0, 0) - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_bound_glyph_invalid() {
        let bbox = fz_bound_glyph(0, 0, 0, super::super::geometry::fz_matrix::identity());
        assert_eq!(bbox.x0, 0.0);
        assert_eq!(bbox.y0, 0.0);
    }

    #[test]
    fn test_font_bbox_invalid() {
        let bbox = fz_font_bbox(0, 0);
        assert_eq!(bbox.x0, 0.0);
    }

    #[test]
    fn test_outline_glyph() {
        let h = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let glyph = fz_encode_character(0, h, 65);
        let path = fz_outline_glyph(0, h, glyph, super::super::geometry::fz_matrix::identity());
        if path != 0 {
            super::super::path::PATHS.remove(path);
        }
        fz_drop_font(0, h);
    }

    #[test]
    fn test_outline_glyph_invalid() {
        assert_eq!(
            fz_outline_glyph(0, 0, 0, super::super::geometry::fz_matrix::identity()),
            0
        );
    }

    #[test]
    fn test_font_is_valid() {
        let h = fz_new_font(0, c"Valid".as_ptr(), 0, 0, 0);
        assert_eq!(fz_font_is_valid(0, h), 1);
        assert_eq!(fz_font_is_valid(0, 0), 0);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_clone_font() {
        let h = fz_new_font(0, c"Clone".as_ptr(), 0, 0, 0);
        let c = fz_clone_font(0, h);
        assert_eq!(c, h);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_font_ascender_descender() {
        let h = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let _a = fz_font_ascender(0, h);
        let _d = fz_font_descender(0, h);
        assert_eq!(fz_font_ascender(0, 0), 0.0);
        assert_eq!(fz_font_descender(0, 0), 0.0);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_font_is_embedded() {
        let h = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let _e = fz_font_is_embedded(0, h);
        assert_eq!(fz_font_is_embedded(0, 0), 0);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_glyph_name() {
        let h = fz_new_font(0, c"Arial".as_ptr(), 0, 0, 0);
        let mut buf = [0i8; 64];
        fz_glyph_name(0, h, 65, buf.as_mut_ptr(), 64);
        fz_glyph_name(0, h, 0, buf.as_mut_ptr(), 64);
        fz_glyph_name(0, h, 0x20, buf.as_mut_ptr(), 64);
        fz_glyph_name(0, h, 65, std::ptr::null_mut(), 64);
        fz_glyph_name(0, h, 65, buf.as_mut_ptr(), 0);
        fz_drop_font(0, h);
    }

    #[test]
    fn test_keep_font_returns_handle() {
        let h = fz_new_font(0, c"K".as_ptr(), 0, 0, 0);
        assert_eq!(fz_keep_font(0, h), h);
        fz_drop_font(0, h);
    }
}