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
//! C FFI for fz_text - MicroPDF compatible text handling
//!
//! Provides FFI bindings for text buffer and text span operations.

use super::{Handle, HandleStore, safe_helpers};
use crate::fitz::geometry::Matrix;
use crate::fitz::text::Text;
use std::sync::{Arc, LazyLock};

/// Text storage
pub static TEXTS: LazyLock<HandleStore<Text>> = LazyLock::new(HandleStore::default);

/// Create a new empty text object
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_text(_ctx: Handle) -> Handle {
    let text = Text::new();
    TEXTS.insert(text)
}

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

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

/// Show a single glyph
///
/// # Safety
/// Caller must ensure font is a valid handle.
#[unsafe(no_mangle)]
pub extern "C" fn fz_show_glyph(
    _ctx: Handle,
    text: Handle,
    font: Handle,
    transform: super::geometry::fz_matrix,
    glyph: i32,
    unicode: i32,
    wmode: i32,
) {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(mut guard) = t.lock() {
            // Get font from handle
            if let Some(f) = super::font::FONTS.get(font) {
                if let Ok(font_guard) = f.lock() {
                    let matrix = Matrix::new(
                        transform.a,
                        transform.b,
                        transform.c,
                        transform.d,
                        transform.e,
                        transform.f,
                    );

                    // Clone the font and wrap in Arc for the Text API
                    let font_arc = Arc::new(font_guard.clone());

                    guard.show_glyph(
                        font_arc,
                        matrix,
                        glyph,
                        unicode,
                        wmode != 0,
                        0,                                      // bidi_level
                        crate::fitz::text::BidiDirection::Ltr,  // markup_dir
                        crate::fitz::text::TextLanguage::Unset, // language
                    );
                }
            }
        }
    }
}

/// Show a string of text
///
/// # Safety
/// Caller must ensure string is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_show_string(
    _ctx: Handle,
    text: Handle,
    font: Handle,
    transform: super::geometry::fz_matrix,
    string: *const std::ffi::c_char,
    wmode: i32,
) {
    let s = match safe_helpers::c_str_to_str(string) {
        Some(s) => s,
        None => return,
    };

    if let Some(t) = TEXTS.get(text) {
        if let Ok(mut guard) = t.lock() {
            // Get font from handle
            if let Some(f) = super::font::FONTS.get(font) {
                if let Ok(font_guard) = f.lock() {
                    let matrix = Matrix::new(
                        transform.a,
                        transform.b,
                        transform.c,
                        transform.d,
                        transform.e,
                        transform.f,
                    );

                    // Clone the font and wrap in Arc for the Text API
                    let font_arc = Arc::new(font_guard.clone());

                    let _ = guard.show_string(
                        font_arc,
                        matrix,
                        s,
                        wmode != 0,
                        0,                                      // bidi_level
                        crate::fitz::text::BidiDirection::Ltr,  // markup_dir
                        crate::fitz::text::TextLanguage::Unset, // language
                    );
                }
            }
        }
    }
}

/// Get bounding box of text
#[unsafe(no_mangle)]
pub extern "C" fn fz_bound_text(
    _ctx: Handle,
    text: Handle,
    stroke: Handle,
    transform: super::geometry::fz_matrix,
) -> super::geometry::fz_rect {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(guard) = t.lock() {
            let matrix = Matrix::new(
                transform.a,
                transform.b,
                transform.c,
                transform.d,
                transform.e,
                transform.f,
            );

            // Get stroke state if provided
            let stroke_opt = if stroke != 0 {
                super::path::STROKE_STATES
                    .get(stroke)
                    .and_then(|s| s.lock().ok().map(|guard| guard.clone()))
            } else {
                None
            };

            let bounds = guard.bounds(stroke_opt.as_ref(), &matrix);

            return super::geometry::fz_rect {
                x0: bounds.x0,
                y0: bounds.y0,
                x1: bounds.x1,
                y1: bounds.y1,
            };
        }
    }

    super::geometry::fz_rect {
        x0: 0.0,
        y0: 0.0,
        x1: 0.0,
        y1: 0.0,
    }
}

/// Clone text object
#[unsafe(no_mangle)]
pub extern "C" fn fz_clone_text(_ctx: Handle, text: Handle) -> Handle {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(guard) = t.lock() {
            let cloned = guard.clone();
            return TEXTS.insert(cloned);
        }
    }
    0
}

/// Get text language
///
/// # Safety
/// Caller must ensure buf points to writable memory of at least 8 bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_text_language(
    _ctx: Handle,
    text: Handle,
    buf: *mut std::ffi::c_char,
    len: i32,
) -> i32 {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(_guard) = t.lock() {
            // Get language tag (e.g., "en" for English)
            let lang = "en"; // Default to English
            return safe_helpers::str_to_c_buffer(lang, buf, len);
        }
    }

    0
}

/// Set text language
///
/// # Safety
/// Caller must ensure lang is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_set_text_language(_ctx: Handle, text: Handle, lang: *const std::ffi::c_char) {
    if let Some(lang_str) = safe_helpers::c_str_to_str(lang) {
        if let Some(t) = TEXTS.get(text) {
            if let Ok(mut guard) = t.lock() {
                let language = crate::fitz::text::TextLanguage::from_string(lang_str);
                guard.set_language(language);
            }
        }
    }
}

/// Get number of spans in text
#[unsafe(no_mangle)]
pub extern "C" fn fz_text_count_spans(_ctx: Handle, text: Handle) -> i32 {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(guard) = t.lock() {
            return guard.span_count() as i32;
        }
    }
    0
}

/// Get number of items in text
#[unsafe(no_mangle)]
pub extern "C" fn fz_text_count_items(_ctx: Handle, text: Handle) -> i32 {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(guard) = t.lock() {
            return guard.item_count() as i32;
        }
    }
    0
}

/// Clear all text
#[unsafe(no_mangle)]
pub extern "C" fn fz_clear_text(_ctx: Handle, text: Handle) {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(mut guard) = t.lock() {
            guard.clear();
        }
    }
}

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

/// Check if text is empty
#[unsafe(no_mangle)]
pub extern "C" fn fz_text_is_empty(_ctx: Handle, text: Handle) -> i32 {
    if let Some(t) = TEXTS.get(text) {
        if let Ok(guard) = t.lock() {
            return if guard.item_count() == 0 { 1 } else { 0 };
        }
    }
    1
}

/// Text walk callback function type
/// Callback receives: user arg, font handle, trm matrix, unicode char, glyph id
type TextWalkCallback = extern "C" fn(
    *mut std::ffi::c_void,
    Handle,
    *const super::geometry::fz_matrix,
    i32,
    i32,
) -> i32;

/// Walk through text items invoking callback for each glyph
#[unsafe(no_mangle)]
pub extern "C" fn fz_text_walk(
    _ctx: Handle,
    text: Handle,
    callback: *const std::ffi::c_void,
    arg: *mut std::ffi::c_void,
) -> i32 {
    if callback.is_null() {
        return 0;
    }

    if let Some(txt) = TEXTS.get(text) {
        if let Ok(guard) = txt.lock() {
            // Cast callback pointer to function pointer
            let cb: TextWalkCallback = unsafe { std::mem::transmute(callback) };

            // Walk through all spans
            for span in guard.spans() {
                // Get or create a font handle for this span's font
                // Clone the Arc contents to create a new Font
                let font_handle = super::font::FONTS.insert((*span.font).clone());

                // Convert trm matrix to FFI format
                let trm = super::geometry::fz_matrix {
                    a: span.trm.a,
                    b: span.trm.b,
                    c: span.trm.c,
                    d: span.trm.d,
                    e: span.trm.e,
                    f: span.trm.f,
                };

                // Walk through all items in this span
                for item in span.items() {
                    // Call the callback for this glyph
                    let result = cb(arg, font_handle, &trm, item.ucs, item.gid);
                    if result == 0 {
                        return 0; // Callback requested termination
                    }
                }
            }
            return 1;
        }
    }
    0
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fitz::font::Font;

    #[test]
    fn test_new_text() {
        let text_handle = fz_new_text(0);
        assert_ne!(text_handle, 0);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_keep_text() {
        let text_handle = fz_new_text(0);
        let kept = fz_keep_text(0, text_handle);
        assert_eq!(kept, text_handle);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_clone_text() {
        let text_handle = fz_new_text(0);
        let cloned = fz_clone_text(0, text_handle);
        assert_ne!(cloned, 0);
        fz_drop_text(0, cloned);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_bound_text() {
        let text_handle = fz_new_text(0);
        let bounds = fz_bound_text(
            0,
            text_handle,
            0,
            super::super::geometry::fz_matrix::identity(),
        );
        // Empty text should return Rect::EMPTY (infinite bounds)
        assert_eq!(bounds.x0, f32::INFINITY);
        assert_eq!(bounds.y0, f32::INFINITY);
        assert_eq!(bounds.x1, f32::NEG_INFINITY);
        assert_eq!(bounds.y1, f32::NEG_INFINITY);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_count_spans() {
        let text_handle = fz_new_text(0);
        let count = fz_text_count_spans(0, text_handle);
        assert_eq!(count, 0); // Empty text has no spans
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_count_items() {
        let text_handle = fz_new_text(0);
        let count = fz_text_count_items(0, text_handle);
        assert_eq!(count, 0); // Empty text has no items
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_clear_text() {
        let text_handle = fz_new_text(0);
        fz_clear_text(0, text_handle);
        let count = fz_text_count_items(0, text_handle);
        assert_eq!(count, 0);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_text_language() {
        let text_handle = fz_new_text(0);
        let mut buf = [0i8; 8];
        let len = fz_text_language(0, text_handle, buf.as_mut_ptr(), 8);
        assert!(len > 0);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_set_text_language() {
        let text_handle = fz_new_text(0);
        fz_set_text_language(0, text_handle, c"en".as_ptr());
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_show_string() {
        let font = Font::new("Test");
        let font_handle = super::super::font::FONTS.insert(font);

        let text_handle = fz_new_text(0);
        fz_show_string(
            0,
            text_handle,
            font_handle,
            super::super::geometry::fz_matrix::identity(),
            c"Hello".as_ptr(),
            0,
        );

        fz_drop_text(0, text_handle);
        super::super::font::FONTS.remove(font_handle);
    }

    #[test]
    fn test_show_string_null() {
        let font = Font::new("Test");
        let font_handle = super::super::font::FONTS.insert(font);
        let text_handle = fz_new_text(0);
        fz_show_string(
            0,
            text_handle,
            font_handle,
            super::super::geometry::fz_matrix::identity(),
            std::ptr::null(),
            0,
        );
        fz_drop_text(0, text_handle);
        super::super::font::FONTS.remove(font_handle);
    }

    #[test]
    fn test_show_glyph() {
        let font = Font::new("Test");
        let font_handle = super::super::font::FONTS.insert(font);
        let text_handle = fz_new_text(0);
        fz_show_glyph(
            0,
            text_handle,
            font_handle,
            super::super::geometry::fz_matrix::identity(),
            65,
            65,
            0,
        );
        assert_eq!(fz_text_count_items(0, text_handle), 1);
        fz_drop_text(0, text_handle);
        super::super::font::FONTS.remove(font_handle);
    }

    #[test]
    fn test_bound_text_with_stroke() {
        let text_handle = fz_new_text(0);
        let stroke_handle = super::super::path::fz_new_stroke_state(0);
        let bounds = fz_bound_text(
            0,
            text_handle,
            stroke_handle,
            super::super::geometry::fz_matrix::identity(),
        );
        assert_eq!(bounds.x0, f32::INFINITY);
        assert_eq!(bounds.y0, f32::INFINITY);
        fz_drop_text(0, text_handle);
        super::super::path::fz_drop_stroke_state(0, stroke_handle);
    }

    #[test]
    fn test_text_language_null_buf() {
        let text_handle = fz_new_text(0);
        let r = fz_text_language(0, text_handle, std::ptr::null_mut(), 8);
        assert!(r <= 0);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_set_text_language_null() {
        let text_handle = fz_new_text(0);
        fz_set_text_language(0, text_handle, std::ptr::null());
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_text_is_valid() {
        let text_handle = fz_new_text(0);
        assert_eq!(fz_text_is_valid(0, text_handle), 1);
        assert_eq!(fz_text_is_valid(0, 99999), 0);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_text_is_empty() {
        let text_handle = fz_new_text(0);
        assert_eq!(fz_text_is_empty(0, text_handle), 1);
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_text_walk_null_callback() {
        let text_handle = fz_new_text(0);
        assert_eq!(
            fz_text_walk(0, text_handle, std::ptr::null(), std::ptr::null_mut()),
            0
        );
        fz_drop_text(0, text_handle);
    }

    #[test]
    fn test_show_glyph_invalid() {
        fz_show_glyph(
            0,
            99999,
            0,
            super::super::geometry::fz_matrix::identity(),
            65,
            65,
            0,
        );
    }

    #[test]
    fn test_clone_text_invalid() {
        assert_eq!(fz_clone_text(0, 0), 0);
    }
}