litchi 0.0.1

High-performance parser for Microsoft Office, OpenDocument, and Apple iWork file formats with unified API
Documentation
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
// WMF to SVG converter with SIMD acceleration
//
// Converts Windows Metafile vector graphics to SVG while extracting embedded raster images

use super::parser::{WmfParser, WmfRecord};
use crate::common::error::{Error, Result};
use crate::images::svg::*;
use crate::ole::binary::read_i16_le;
use rayon::prelude::*;

/// WMF to SVG converter
pub struct WmfSvgConverter {
    parser: WmfParser,
}

impl WmfSvgConverter {
    /// Create a new WMF to SVG converter
    pub fn new(parser: WmfParser) -> Self {
        Self { parser }
    }

    /// Convert WMF to SVG
    ///
    /// Processes WMF records in parallel and generates SVG with vector graphics
    /// and embedded raster images.
    pub fn convert_to_svg(&self) -> Result<String> {
        let width = self.parser.width() as f64;
        let height = self.parser.height() as f64;

        let mut builder = SvgBuilder::new(width, height);

        // WMF coordinates are in logical units, set viewBox appropriately
        builder = builder.with_viewbox(0.0, 0.0, width, height);

        // Process records in parallel
        let elements: Vec<SvgElement> = self
            .parser
            .records
            .par_iter()
            .filter_map(|record| self.process_record(record).ok().flatten())
            .collect();

        for element in elements {
            builder.add_element(element);
        }

        Ok(builder.build())
    }

    /// Convert WMF to SVG bytes
    pub fn convert_to_svg_bytes(&self) -> Result<Vec<u8>> {
        Ok(self.convert_to_svg()?.into_bytes())
    }

    /// Process a single WMF record
    fn process_record(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        match record.function {
            // Rectangle
            0x041B => self.parse_rectangle(record),
            // Ellipse
            0x0418 => self.parse_ellipse(record),
            // Polygon
            0x0324 => self.parse_polygon(record),
            // Polyline
            0x0325 => self.parse_polyline(record),
            // Arc
            0x0817 => self.parse_arc(record),
            // Pie
            0x081A => self.parse_pie(record),
            // Chord
            0x0830 => self.parse_chord(record),
            // StretchDIB (embedded bitmap)
            0x0F43 => self.parse_stretchdib(record),
            // DIBStretchBlt
            0x0B41 => self.parse_dibstretchblt(record),
            // DIBBitBlt
            0x0940 => self.parse_dibbitblt(record),
            // RoundRect
            0x061C => self.parse_roundrect(record),
            // LineTo
            0x0213 => self.parse_lineto(record),
            _ => Ok(None),
        }
    }

    /// Parse META_RECTANGLE record
    fn parse_rectangle(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 8 {
            return Ok(None);
        }

        // WMF uses 16-bit coordinates in big-endian (words)
        let bottom = read_i16_le(&record.params, 0).unwrap_or(0) as f64;
        let right = read_i16_le(&record.params, 2).unwrap_or(0) as f64;
        let top = read_i16_le(&record.params, 4).unwrap_or(0) as f64;
        let left = read_i16_le(&record.params, 6).unwrap_or(0) as f64;

        Ok(Some(SvgElement::Rect(SvgRect {
            x: left,
            y: top,
            width: right - left,
            height: bottom - top,
            fill: None,
            stroke: Some("#000000".to_string()),
            stroke_width: 1.0,
        })))
    }

    /// Parse META_ELLIPSE record
    fn parse_ellipse(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 8 {
            return Ok(None);
        }

        let bottom = read_i16_le(&record.params, 0).unwrap_or(0) as f64;
        let right = read_i16_le(&record.params, 2).unwrap_or(0) as f64;
        let top = read_i16_le(&record.params, 4).unwrap_or(0) as f64;
        let left = read_i16_le(&record.params, 6).unwrap_or(0) as f64;

        let cx = (left + right) / 2.0;
        let cy = (top + bottom) / 2.0;
        let rx = (right - left) / 2.0;
        let ry = (bottom - top) / 2.0;

        Ok(Some(SvgElement::Ellipse(SvgEllipse {
            cx,
            cy,
            rx,
            ry,
            fill: None,
            stroke: Some("#000000".to_string()),
            stroke_width: 1.0,
        })))
    }

    /// Parse META_POLYGON record
    fn parse_polygon(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 2 {
            return Ok(None);
        }

        let count = read_i16_le(&record.params, 0).unwrap_or(0) as usize;

        if record.params.len() < 2 + count * 4 {
            return Ok(None);
        }

        let mut commands = Vec::with_capacity(count + 1);

        // Parse points in parallel batches for better performance
        let points: Vec<(f64, f64)> = (0..count)
            .into_par_iter()
            .map(|i| {
                let offset = 2 + i * 4;
                let x = read_i16_le(&record.params, offset).unwrap_or(0) as f64;
                let y = read_i16_le(&record.params, offset + 2).unwrap_or(0) as f64;
                (x, y)
            })
            .collect();

        for (i, (x, y)) in points.into_iter().enumerate() {
            if i == 0 {
                commands.push(PathCommand::MoveTo { x, y });
            } else {
                commands.push(PathCommand::LineTo { x, y });
            }
        }

        commands.push(PathCommand::ClosePath);

        Ok(Some(SvgElement::Path(
            SvgPath::new(commands)
                .with_stroke("#000000".to_string())
                .with_fill("none".to_string()),
        )))
    }

    /// Parse META_POLYLINE record
    fn parse_polyline(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 2 {
            return Ok(None);
        }

        let count = read_i16_le(&record.params, 0).unwrap_or(0) as usize;

        if record.params.len() < 2 + count * 4 {
            return Ok(None);
        }

        let mut commands = Vec::with_capacity(count);

        // SIMD-friendly parallel processing
        let points: Vec<(f64, f64)> = (0..count)
            .into_par_iter()
            .map(|i| {
                let offset = 2 + i * 4;
                let x = read_i16_le(&record.params, offset).unwrap_or(0) as f64;
                let y = read_i16_le(&record.params, offset + 2).unwrap_or(0) as f64;
                (x, y)
            })
            .collect();

        for (i, (x, y)) in points.into_iter().enumerate() {
            if i == 0 {
                commands.push(PathCommand::MoveTo { x, y });
            } else {
                commands.push(PathCommand::LineTo { x, y });
            }
        }

        Ok(Some(SvgElement::Path(
            SvgPath::new(commands)
                .with_stroke("#000000".to_string())
                .with_fill("none".to_string()),
        )))
    }

    /// Parse META_ARC record
    fn parse_arc(&self, _record: &WmfRecord) -> Result<Option<SvgElement>> {
        // Arc conversion requires trigonometric calculations
        // Placeholder for future implementation
        Ok(None)
    }

    /// Parse META_PIE record
    fn parse_pie(&self, _record: &WmfRecord) -> Result<Option<SvgElement>> {
        // Pie chart slice
        Ok(None)
    }

    /// Parse META_CHORD record
    fn parse_chord(&self, _record: &WmfRecord) -> Result<Option<SvgElement>> {
        // Chord shape
        Ok(None)
    }

    /// Parse META_ROUNDRECT record
    fn parse_roundrect(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 12 {
            return Ok(None);
        }

        let corner_height = read_i16_le(&record.params, 0).unwrap_or(0) as f64;
        let corner_width = read_i16_le(&record.params, 2).unwrap_or(0) as f64;
        let bottom = read_i16_le(&record.params, 4).unwrap_or(0) as f64;
        let right = read_i16_le(&record.params, 6).unwrap_or(0) as f64;
        let top = read_i16_le(&record.params, 8).unwrap_or(0) as f64;
        let left = read_i16_le(&record.params, 10).unwrap_or(0) as f64;

        let rx = corner_width / 2.0;
        let ry = corner_height / 2.0;

        // Create rounded rectangle using path with arcs
        let commands = vec![
            PathCommand::MoveTo { x: left + rx, y: top },
            PathCommand::LineTo { x: right - rx, y: top },
            PathCommand::Arc {
                rx,
                ry,
                x_axis_rotation: 0.0,
                large_arc: false,
                sweep: true,
                x: right,
                y: top + ry,
            },
            PathCommand::LineTo { x: right, y: bottom - ry },
            PathCommand::Arc {
                rx,
                ry,
                x_axis_rotation: 0.0,
                large_arc: false,
                sweep: true,
                x: right - rx,
                y: bottom,
            },
            PathCommand::LineTo { x: left + rx, y: bottom },
            PathCommand::Arc {
                rx,
                ry,
                x_axis_rotation: 0.0,
                large_arc: false,
                sweep: true,
                x: left,
                y: bottom - ry,
            },
            PathCommand::LineTo { x: left, y: top + ry },
            PathCommand::Arc {
                rx,
                ry,
                x_axis_rotation: 0.0,
                large_arc: false,
                sweep: true,
                x: left + rx,
                y: top,
            },
            PathCommand::ClosePath,
        ];

        Ok(Some(SvgElement::Path(
            SvgPath::new(commands)
                .with_stroke("#000000".to_string())
                .with_fill("none".to_string()),
        )))
    }

    /// Parse META_LINETO record
    fn parse_lineto(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 4 {
            return Ok(None);
        }

        let y = read_i16_le(&record.params, 0).unwrap_or(0) as f64;
        let x = read_i16_le(&record.params, 2).unwrap_or(0) as f64;

        Ok(Some(SvgElement::Path(
            SvgPath::new(vec![
                PathCommand::MoveTo { x: 0.0, y: 0.0 },
                PathCommand::LineTo { x, y },
            ])
            .with_stroke("#000000".to_string()),
        )))
    }

    /// Parse META_STRETCHDIB record
    fn parse_stretchdib(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        // Extract DIB and convert to PNG for embedding
        if record.params.len() < 20 {
            return Ok(None);
        }

        // Parse destination rectangle (simplified)
        let dest_height = read_i16_le(&record.params, 6).unwrap_or(0) as f64;
        let dest_width = read_i16_le(&record.params, 8).unwrap_or(0) as f64;
        let dest_y = read_i16_le(&record.params, 10).unwrap_or(0) as f64;
        let dest_x = read_i16_le(&record.params, 12).unwrap_or(0) as f64;

        // Try to extract DIB data
        if let Ok(png_data) = self.extract_and_convert_dib(&record.params[20..]) {
            return Ok(Some(SvgElement::Image(SvgImage::from_png_data(
                dest_x,
                dest_y,
                dest_width,
                dest_height,
                &png_data,
            ))));
        }

        Ok(None)
    }

    /// Parse META_DIBSTRETCHBLT record
    fn parse_dibstretchblt(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 20 {
            return Ok(None);
        }

        // Similar to StretchDIB but with different parameter layout
        if let Ok(png_data) = self.extract_and_convert_dib(&record.params[18..]) {
            let dest_x = read_i16_le(&record.params, 6).unwrap_or(0) as f64;
            let dest_y = read_i16_le(&record.params, 8).unwrap_or(0) as f64;
            let dest_width = read_i16_le(&record.params, 10).unwrap_or(0) as f64;
            let dest_height = read_i16_le(&record.params, 12).unwrap_or(0) as f64;

            return Ok(Some(SvgElement::Image(SvgImage::from_png_data(
                dest_x,
                dest_y,
                dest_width,
                dest_height,
                &png_data,
            ))));
        }

        Ok(None)
    }

    /// Parse META_DIBBITBLT record
    fn parse_dibbitblt(&self, record: &WmfRecord) -> Result<Option<SvgElement>> {
        if record.params.len() < 16 {
            return Ok(None);
        }

        if let Ok(png_data) = self.extract_and_convert_dib(&record.params[14..]) {
            let dest_x = read_i16_le(&record.params, 4).unwrap_or(0) as f64;
            let dest_y = read_i16_le(&record.params, 6).unwrap_or(0) as f64;
            let width = read_i16_le(&record.params, 8).unwrap_or(0) as f64;
            let height = read_i16_le(&record.params, 10).unwrap_or(0) as f64;

            return Ok(Some(SvgElement::Image(SvgImage::from_png_data(
                dest_x,
                dest_y,
                width,
                height,
                &png_data,
            ))));
        }

        Ok(None)
    }

    /// Extract and convert DIB to PNG
    fn extract_and_convert_dib(&self, dib_data: &[u8]) -> Result<Vec<u8>> {
        if dib_data.len() < 40 {
            return Err(Error::ParseError("DIB data too small".into()));
        }

        // Construct BMP from DIB
        let file_size = 14u32 + dib_data.len() as u32;
        let pixel_data_offset = 14u32 + 40u32;

        let mut bmp_data = Vec::with_capacity(file_size as usize);
        bmp_data.extend_from_slice(b"BM");
        bmp_data.extend_from_slice(&file_size.to_le_bytes());
        bmp_data.extend_from_slice(&[0u8; 4]);
        bmp_data.extend_from_slice(&pixel_data_offset.to_le_bytes());
        bmp_data.extend_from_slice(dib_data);

        // Load and re-encode as PNG
        let img = image::load_from_memory(&bmp_data)
            .map_err(|e| Error::ParseError(format!("Failed to load DIB: {}", e)))?;

        let mut png_data = Vec::new();
        let mut cursor = std::io::Cursor::new(&mut png_data);
        img.write_to(&mut cursor, image::ImageFormat::Png)
            .map_err(|e| Error::ParseError(format!("Failed to encode PNG: {}", e)))?;

        Ok(png_data)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_wmf_svg_converter_creation() {
        // Test requires valid WMF data
        // Placeholder for future tests
    }
}