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
//! Glyph Rasterization
//!
//! Converts glyph outlines to pixmaps for rendering text in PDFs.
//!
//! Supports:
//! - TrueType/OpenType fonts
//! - Type1 PostScript fonts
//! - CFF (Compact Font Format) fonts
//! - Glyph caching for performance

use crate::fitz::error::{Error, Result};
use crate::fitz::geometry::{Matrix, Point, Rect};
use crate::fitz::path::Path;
use crate::fitz::pixmap::Pixmap;
use crate::fitz::render::Rasterizer;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Glyph identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GlyphId(pub u16);

impl GlyphId {
    pub fn new(id: u16) -> Self {
        Self(id)
    }

    pub fn value(&self) -> u16 {
        self.0
    }
}

/// Glyph metrics
#[derive(Debug, Clone, Copy)]
pub struct GlyphMetrics {
    /// Glyph advance width
    pub advance_width: f32,
    /// Glyph advance height (for vertical writing)
    pub advance_height: f32,
    /// Left side bearing
    pub lsb: f32,
    /// Top side bearing (for vertical writing)
    pub tsb: f32,
    /// Bounding box
    pub bbox: Rect,
}

impl Default for GlyphMetrics {
    fn default() -> Self {
        Self {
            advance_width: 1.0,
            advance_height: 1.0,
            lsb: 0.0,
            tsb: 0.0,
            bbox: Rect::new(0.0, 0.0, 1.0, 1.0),
        }
    }
}

/// Glyph outline as a path
#[derive(Debug, Clone)]
pub struct GlyphOutline {
    /// Glyph identifier
    pub gid: GlyphId,
    /// Glyph path
    pub path: Path,
    /// Glyph metrics
    pub metrics: GlyphMetrics,
}

impl GlyphOutline {
    /// Create a new glyph outline
    pub fn new(gid: GlyphId, path: Path, metrics: GlyphMetrics) -> Self {
        Self { gid, path, metrics }
    }

    /// Transform the glyph outline by a matrix
    pub fn transform(&mut self, ctm: &Matrix) {
        self.path.transform(|p| ctm.transform_point(p));

        let p0 = ctm.transform_point(Point::new(0.0, 0.0));
        let p1 = ctm.transform_point(Point::new(self.metrics.advance_width, 0.0));
        self.metrics.advance_width = (p1.x - p0.x).abs();

        let p2 = ctm.transform_point(Point::new(0.0, self.metrics.advance_height));
        self.metrics.advance_height = (p2.y - p0.y).abs();

        // Transform bbox
        let bbox = self.metrics.bbox;
        let corners = [
            ctm.transform_point(Point::new(bbox.x0, bbox.y0)),
            ctm.transform_point(Point::new(bbox.x1, bbox.y0)),
            ctm.transform_point(Point::new(bbox.x1, bbox.y1)),
            ctm.transform_point(Point::new(bbox.x0, bbox.y1)),
        ];

        let min_x = corners.iter().map(|p| p.x).fold(f32::INFINITY, f32::min);
        let min_y = corners.iter().map(|p| p.y).fold(f32::INFINITY, f32::min);
        let max_x = corners
            .iter()
            .map(|p| p.x)
            .fold(f32::NEG_INFINITY, f32::max);
        let max_y = corners
            .iter()
            .map(|p| p.y)
            .fold(f32::NEG_INFINITY, f32::max);

        self.metrics.bbox = Rect::new(min_x, min_y, max_x, max_y);
    }
}

/// Glyph cache key
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct GlyphCacheKey {
    gid: GlyphId,
    size: u32,      // Font size in 1/64ths of a point
    subpixel_x: u8, // Subpixel position (0-63)
    subpixel_y: u8, // Subpixel position (0-63)
}

/// Glyph cache
pub struct GlyphCache {
    /// Cached glyph pixmaps
    cache: Arc<Mutex<HashMap<GlyphCacheKey, Arc<Pixmap>>>>,
    /// Maximum cache size in bytes
    max_size: usize,
    /// Current cache size in bytes
    current_size: Arc<Mutex<usize>>,
}

impl GlyphCache {
    /// Create a new glyph cache
    pub fn new(max_size_mb: usize) -> Self {
        Self {
            cache: Arc::new(Mutex::new(HashMap::new())),
            max_size: max_size_mb * 1024 * 1024,
            current_size: Arc::new(Mutex::new(0)),
        }
    }

    /// Get a glyph from the cache
    pub fn get(
        &self,
        gid: GlyphId,
        size: f32,
        subpixel_x: f32,
        subpixel_y: f32,
    ) -> Option<Arc<Pixmap>> {
        let key = GlyphCacheKey {
            gid,
            size: (size * 64.0) as u32,
            subpixel_x: (subpixel_x * 64.0) as u8,
            subpixel_y: (subpixel_y * 64.0) as u8,
        };

        self.cache.lock().unwrap().get(&key).cloned()
    }

    /// Insert a glyph into the cache
    pub fn insert(
        &self,
        gid: GlyphId,
        size: f32,
        subpixel_x: f32,
        subpixel_y: f32,
        pixmap: Pixmap,
    ) {
        let key = GlyphCacheKey {
            gid,
            size: (size * 64.0) as u32,
            subpixel_x: (subpixel_x * 64.0) as u8,
            subpixel_y: (subpixel_y * 64.0) as u8,
        };

        let pixmap_size = pixmap.samples().len();
        let pixmap = Arc::new(pixmap);

        // Check cache size
        let mut current = self.current_size.lock().unwrap();
        if *current + pixmap_size > self.max_size {
            // Simple eviction: clear entire cache
            // A better strategy would be LRU
            self.clear();
            *current = 0;
        }

        self.cache.lock().unwrap().insert(key, pixmap);
        *current += pixmap_size;
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.lock().unwrap().clear();
        *self.current_size.lock().unwrap() = 0;
    }

    /// Get cache statistics
    pub fn stats(&self) -> (usize, usize, usize) {
        let cache = self.cache.lock().unwrap();
        let size = *self.current_size.lock().unwrap();
        (cache.len(), size, self.max_size)
    }
}

impl Default for GlyphCache {
    fn default() -> Self {
        Self::new(16) // 16 MB default
    }
}

/// Glyph rasterizer
pub struct GlyphRasterizer {
    /// Pixel rasterizer
    rasterizer: Rasterizer,
    /// Glyph cache
    cache: GlyphCache,
}

impl GlyphRasterizer {
    /// Create a new glyph rasterizer
    pub fn new() -> Self {
        // Create a reasonable default rasterizer size
        let clip = Rect::new(0.0, 0.0, 1024.0, 1024.0);
        Self {
            rasterizer: Rasterizer::new(1024, 1024, clip),
            cache: GlyphCache::default(),
        }
    }

    /// Create glyph rasterizer with custom cache size
    pub fn with_cache_size(cache_size_mb: usize) -> Self {
        let clip = Rect::new(0.0, 0.0, 1024.0, 1024.0);
        Self {
            rasterizer: Rasterizer::new(1024, 1024, clip),
            cache: GlyphCache::new(cache_size_mb),
        }
    }

    /// Rasterize a glyph outline to a pixmap
    pub fn rasterize_glyph(
        &self,
        outline: &GlyphOutline,
        font_size: f32,
        subpixel_x: f32,
        subpixel_y: f32,
    ) -> Result<Pixmap> {
        // Check cache first
        if let Some(pixmap) = self
            .cache
            .get(outline.gid, font_size, subpixel_x, subpixel_y)
        {
            return Ok((*pixmap).clone());
        }

        // Calculate glyph transformation matrix
        let scale = font_size / 1000.0; // Assuming 1000 units per em (standard)
        let ctm = Matrix::new(
            scale, 0.0, 0.0, -scale, // Flip Y axis (PDF coordinates)
            subpixel_x, subpixel_y,
        );

        // Calculate pixmap dimensions
        let bbox = outline.metrics.bbox;
        let transformed_bbox = bbox.transform(&ctm);

        let width = (transformed_bbox.width().ceil() as i32).max(1);
        let height = (transformed_bbox.height().ceil() as i32).max(1);

        // Create destination pixmap (grayscale + alpha)
        let mut pixmap = Pixmap::new(None, width, height, true)?;

        // Rasterize the glyph path
        let colorspace = crate::fitz::colorspace::Colorspace::device_gray();
        let color = vec![1.0]; // White glyph
        let alpha = 1.0;

        self.rasterizer.fill_path(
            &outline.path,
            false, // Non-zero winding rule
            &ctm,
            &colorspace,
            &color,
            alpha,
            &mut pixmap,
        );

        // Cache the result
        self.cache.insert(
            outline.gid,
            font_size,
            subpixel_x,
            subpixel_y,
            pixmap.clone(),
        );

        Ok(pixmap)
    }

    /// Rasterize multiple glyphs (for performance)
    pub fn rasterize_glyphs(
        &self,
        outlines: &[&GlyphOutline],
        font_size: f32,
    ) -> Result<Vec<Pixmap>> {
        outlines
            .iter()
            .map(|outline| self.rasterize_glyph(outline, font_size, 0.0, 0.0))
            .collect()
    }

    /// Clear the glyph cache
    pub fn clear_cache(&self) {
        self.cache.clear();
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> (usize, usize, usize) {
        self.cache.stats()
    }
}

impl Default for GlyphRasterizer {
    fn default() -> Self {
        Self::new()
    }
}

/// Helper: Create a simple glyph outline for a rectangle (for missing glyphs)
pub fn create_missing_glyph_outline(gid: GlyphId, advance: f32) -> GlyphOutline {
    let mut path = Path::new();

    // Draw a simple rectangle as "missing glyph" indicator
    let width = advance * 0.8;
    let height = advance * 1.0;
    let margin = advance * 0.1;

    path.move_to(Point::new(margin, margin));
    path.line_to(Point::new(width, margin));
    path.line_to(Point::new(width, height));
    path.line_to(Point::new(margin, height));
    path.close();

    // Inner rectangle (hollow)
    let inner_margin = margin * 2.0;
    path.move_to(Point::new(inner_margin, inner_margin));
    path.line_to(Point::new(width - inner_margin, inner_margin));
    path.line_to(Point::new(width - inner_margin, height - inner_margin));
    path.line_to(Point::new(inner_margin, height - inner_margin));
    path.close();

    let metrics = GlyphMetrics {
        advance_width: advance,
        advance_height: height,
        lsb: margin,
        tsb: margin,
        bbox: Rect::new(margin, margin, width, height),
    };

    GlyphOutline::new(gid, path, metrics)
}

/// TrueType glyph loader (simplified)
pub struct TrueTypeLoader {
    /// Font data
    data: Vec<u8>,
    /// Units per em
    units_per_em: u16,
    /// Glyph count
    num_glyphs: u16,
}

impl TrueTypeLoader {
    /// Create a new TrueType loader from font data
    pub fn new(data: Vec<u8>) -> Result<Self> {
        if data.len() < 12 {
            return Err(Error::Generic("Invalid TrueType font data".into()));
        }

        let face = ttf_parser::Face::parse(&data, 0)
            .map_err(|e| Error::Generic(format!("Failed to parse TrueType font: {}", e)))?;

        let units_per_em = face.units_per_em();
        let num_glyphs = face.number_of_glyphs();

        Ok(Self {
            data,
            units_per_em,
            num_glyphs,
        })
    }

    /// Get the number of glyphs in the font
    pub fn num_glyphs(&self) -> u16 {
        self.num_glyphs
    }

    /// Get units per em
    pub fn units_per_em(&self) -> u16 {
        self.units_per_em
    }

    /// Load a glyph outline by ID
    pub fn load_glyph(&self, gid: GlyphId) -> Result<GlyphOutline> {
        let face = ttf_parser::Face::parse(&self.data, 0)
            .map_err(|e| Error::Generic(format!("Failed to parse font: {}", e)))?;

        let ttf_gid = ttf_parser::GlyphId(gid.value());

        let mut path = Path::new();
        struct OutlineBuilder<'a> {
            path: &'a mut Path,
        }
        impl ttf_parser::OutlineBuilder for OutlineBuilder<'_> {
            fn move_to(&mut self, x: f32, y: f32) {
                self.path.move_to(Point::new(x, y));
            }
            fn line_to(&mut self, x: f32, y: f32) {
                self.path.line_to(Point::new(x, y));
            }
            fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
                self.path.quad_to(Point::new(x1, y1), Point::new(x, y));
            }
            fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
                self.path.curve_to(
                    Point::new(x1, y1),
                    Point::new(x2, y2),
                    Point::new(x, y),
                );
            }
            fn close(&mut self) {
                self.path.close();
            }
        }

        let mut builder = OutlineBuilder { path: &mut path };
        let bbox_opt = face.outline_glyph(ttf_gid, &mut builder);

        let metrics = self.glyph_metrics(gid)?;

        let glyph_bbox = if let Some(bbox) = bbox_opt {
            Rect::new(
                bbox.x_min as f32,
                bbox.y_min as f32,
                bbox.x_max as f32,
                bbox.y_max as f32,
            )
        } else {
            metrics.bbox
        };

        Ok(GlyphOutline::new(
            gid,
            path,
            GlyphMetrics {
                bbox: glyph_bbox,
                ..metrics
            },
        ))
    }

    /// Get glyph metrics
    pub fn glyph_metrics(&self, gid: GlyphId) -> Result<GlyphMetrics> {
        let face = ttf_parser::Face::parse(&self.data, 0)
            .map_err(|e| Error::Generic(format!("Failed to parse font: {}", e)))?;

        let ttf_gid = ttf_parser::GlyphId(gid.value());
        let upem = self.units_per_em as f32;

        let advance_width = face
            .glyph_hor_advance(ttf_gid)
            .map(|a| a as f32)
            .unwrap_or(upem);

        let advance_height = face
            .glyph_ver_advance(ttf_gid)
            .map(|a| a as f32)
            .unwrap_or(upem);

        let lsb = face
            .glyph_hor_side_bearing(ttf_gid)
            .map(|b| b as f32)
            .unwrap_or(0.0);

        let tsb = face
            .glyph_ver_side_bearing(ttf_gid)
            .map(|b| b as f32)
            .unwrap_or(0.0);

        let bbox = face
            .glyph_bounding_box(ttf_gid)
            .map(|b| {
                Rect::new(
                    b.x_min as f32,
                    b.y_min as f32,
                    b.x_max as f32,
                    b.y_max as f32,
                )
            })
            .unwrap_or(Rect::new(0.0, 0.0, advance_width, upem));

        Ok(GlyphMetrics {
            advance_width,
            advance_height,
            lsb,
            tsb,
            bbox,
        })
    }
}

/// Type1 glyph loader (simplified)
pub struct Type1Loader {
    /// Font data
    data: Vec<u8>,
}

impl Type1Loader {
    /// Create a new Type1 loader from font data
    pub fn new(data: Vec<u8>) -> Result<Self> {
        // Check for Type1 signature
        if data.len() < 16 {
            return Err(Error::Generic("Invalid Type1 font data".into()));
        }

        // Type1 fonts start with "%!PS-AdobeFont" or "%!FontType1"
        let header = String::from_utf8_lossy(&data[0..14.min(data.len())]);
        if !header.starts_with("%!") {
            return Err(Error::Generic("Invalid Type1 signature".into()));
        }

        Ok(Self { data })
    }

    /// Load a glyph outline by name
    pub fn load_glyph_by_name(&self, name: &str) -> Result<GlyphOutline> {
        Err(Error::Unsupported(format!(
            "Type1 charstring interpretation for glyph '{}' requires a PostScript interpreter \
             which is not yet available; use TrueType/OpenType fonts instead",
            name
        )))
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_glyph_id() {
        let gid = GlyphId::new(42);
        assert_eq!(gid.value(), 42);
    }

    #[test]
    fn test_glyph_metrics_default() {
        let metrics = GlyphMetrics::default();
        assert_eq!(metrics.advance_width, 1.0);
        assert_eq!(metrics.lsb, 0.0);
    }

    #[test]
    fn test_glyph_cache_creation() {
        let cache = GlyphCache::new(16);
        let (count, size, max) = cache.stats();
        assert_eq!(count, 0);
        assert_eq!(size, 0);
        assert_eq!(max, 16 * 1024 * 1024);
    }

    #[test]
    fn test_glyph_cache_insert_get() {
        let cache = GlyphCache::new(16);
        let pixmap = Pixmap::new(None, 10, 10, true).unwrap();
        let gid = GlyphId::new(42);

        cache.insert(gid, 12.0, 0.0, 0.0, pixmap);

        let retrieved = cache.get(gid, 12.0, 0.0, 0.0);
        assert!(retrieved.is_some());

        let (count, _, _) = cache.stats();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_glyph_cache_clear() {
        let cache = GlyphCache::new(16);
        let pixmap = Pixmap::new(None, 10, 10, true).unwrap();

        cache.insert(GlyphId::new(1), 12.0, 0.0, 0.0, pixmap);
        cache.clear();

        let (count, size, _) = cache.stats();
        assert_eq!(count, 0);
        assert_eq!(size, 0);
    }

    #[test]
    fn test_create_missing_glyph_outline() {
        let gid = GlyphId::new(0);
        let outline = create_missing_glyph_outline(gid, 500.0);

        assert_eq!(outline.gid, gid);
        assert_eq!(outline.metrics.advance_width, 500.0);
        assert!(!outline.path.elements().is_empty());
    }

    #[test]
    fn test_glyph_rasterizer_creation() {
        let rasterizer = GlyphRasterizer::new();
        let (count, _, _) = rasterizer.cache_stats();
        assert_eq!(count, 0);
    }

    #[test]
    fn test_glyph_rasterizer_with_cache_size() {
        let rasterizer = GlyphRasterizer::with_cache_size(32);
        let (_, _, max) = rasterizer.cache_stats();
        assert_eq!(max, 32 * 1024 * 1024);
    }
}