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
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
/// Unified PowerPoint presentation module.
///
/// This module provides a unified API for working with PowerPoint presentations in both
/// legacy (.ppt) and modern (.pptx) formats. The format is automatically detected
/// and handled transparently.
///
/// # Architecture
///
/// The module provides a format-agnostic API following the python-pptx design:
/// - `Presentation`: The main presentation API (auto-detects format)
/// - `Slide`: Individual slide with shapes and content
/// - `Shape`: Shape elements on slides
///
/// # Example
///
/// ```rust,no_run
/// use litchi::Presentation;
///
/// // Open any PowerPoint presentation (.ppt or .pptx) - format auto-detected
/// let pres = Presentation::open("presentation.ppt")?;
///
/// // Extract all text
/// let text = pres.text()?;
/// println!("Presentation text: {}", text);
///
/// // Get slide count
/// let count = pres.slide_count()?;
/// println!("Slides: {}", count);
///
/// // Access slides
/// for (i, slide) in pres.slides()?.iter().enumerate() {
///     println!("Slide {}: {}", i + 1, slide.text()?);
/// }
/// # Ok::<(), litchi::common::Error>(())
/// ```
use crate::common::{Error, Result};

#[cfg(feature = "ole")]
use crate::ole;

#[cfg(feature = "ooxml")]
use crate::ooxml;

use std::fs::File;
use std::io::{Cursor, Read, Seek};
use std::path::Path;

/// Extracted data from a PPTX slide (to avoid lifetime issues).
#[derive(Debug, Clone)]
pub struct PptxSlideData {
    pub text: String,
    pub name: Option<String>,
}

/// Extracted data from a PPT slide (to avoid lifetime issues).
#[derive(Debug, Clone)]
pub struct PptSlideData {
    pub text: String,
    pub slide_number: usize,
    pub shape_count: usize,
}

/// A PowerPoint presentation that can be either .ppt or .pptx format.
///
/// This enum wraps the format-specific implementations and provides
/// a unified API. Users typically don't interact with this enum directly,
/// but instead use the methods on `Presentation`.
enum PresentationImpl {
    /// Legacy .ppt format
    #[cfg(feature = "ole")]
    Ppt(ole::ppt::Presentation),
    /// Modern .pptx format
    #[cfg(feature = "ooxml")]
    Pptx(Box<ooxml::pptx::Presentation<'static>>),
}

/// A PowerPoint presentation.
///
/// This is the main entry point for working with PowerPoint presentations.
/// It automatically detects whether the file is .ppt or .pptx format
/// and provides a unified API.
///
/// Not intended to be constructed directly. Use `Presentation::open()` to
/// open a presentation.
///
/// # Examples
///
/// ```rust,no_run
/// use litchi::Presentation;
///
/// // Open a presentation (format auto-detected)
/// let pres = Presentation::open("slides.ppt")?;
///
/// // Get slide count
/// let count = pres.slide_count()?;
/// println!("Slides: {}", count);
///
/// // Extract text
/// let text = pres.text()?;
/// println!("{}", text);
/// # Ok::<(), litchi::common::Error>(())
/// ```
pub struct Presentation {
    /// The underlying format-specific implementation
    inner: PresentationImpl,
    /// PPTX package storage that must outlive the Presentation reference.
    ///
    /// This field is prefixed with `_` because it's not directly accessed,
    /// but it MUST be kept to maintain memory safety. The `inner` PresentationImpl::Pptx
    /// variant holds a reference with extended lifetime to data owned by this Box.
    /// Dropping this would invalidate those references (use-after-free).
    ///
    /// Only used for PPTX files; None for PPT files.
    #[cfg(feature = "ooxml")]
    _package: Option<Box<ooxml::pptx::Package>>,
}

impl Presentation {
    /// Open a PowerPoint presentation from a file path.
    ///
    /// The file format (.ppt or .pptx) is automatically detected by examining
    /// the file header. You don't need to specify the format explicitly.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the PowerPoint presentation
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// // Open a .ppt file
    /// let pres1 = Presentation::open("legacy.ppt")?;
    ///
    /// // Open a .pptx file
    /// let pres2 = Presentation::open("modern.pptx")?;
    ///
    /// // Both work the same way
    /// println!("Pres 1: {} slides", pres1.slide_count()?);
    /// println!("Pres 2: {} slides", pres2.slide_count()?);
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        
        // Try to detect the format by reading the file header
        let mut file = File::open(path)?;
        let format = detect_presentation_format(&mut file)?;
        
        // Open with the appropriate parser
        match format {
            #[cfg(feature = "ole")]
            PresentationFormat::Ppt => {
                let mut package = ole::ppt::Package::open(path)
                    .map_err(Error::from)?;
                let pres = package.presentation()
                    .map_err(Error::from)?;
                
                Ok(Self {
                    inner: PresentationImpl::Ppt(pres),
                    #[cfg(feature = "ooxml")]
                    _package: None,
                })
            }
            #[cfg(not(feature = "ole"))]
            PresentationFormat::Ppt => {
                Err(Error::FeatureDisabled("ole".to_string()))
            }
            #[cfg(feature = "ooxml")]
            PresentationFormat::Pptx => {
                let package = Box::new(ooxml::pptx::Package::open(path)
                    .map_err(Error::from)?);
                
                // SAFETY: We're using unsafe here to extend the lifetime of the presentation
                // reference. This is safe because we're storing the package in the same
                // struct, ensuring it lives as long as the presentation reference.
                let pres_ref = unsafe {
                    let pkg_ptr = &*package as *const ooxml::pptx::Package;
                    let pres = (*pkg_ptr).presentation()
                        .map_err(Error::from)?;
                    std::mem::transmute::<ooxml::pptx::Presentation<'_>, ooxml::pptx::Presentation<'static>>(pres)
                };
                
                Ok(Self {
                    inner: PresentationImpl::Pptx(Box::new(pres_ref)),
                    _package: Some(package),
                })
            }
            #[cfg(not(feature = "ooxml"))]
            PresentationFormat::Pptx => {
                Err(Error::FeatureDisabled("ooxml".to_string()))
            }
        }
    }

    /// Create a Presentation from a byte buffer.
    ///
    /// This method is optimized for parsing presentations from memory, such as
    /// from network traffic or in-memory caches, without creating temporary files.
    /// It automatically detects the format (.ppt or .pptx) from the byte signature.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The presentation bytes
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    /// use std::fs;
    ///
    /// // From owned bytes (e.g., network data)
    /// let data = fs::read("presentation.ppt")?;
    /// let pres = Presentation::from_bytes(data)?;
    /// println!("Slides: {}", pres.slide_count()?);
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    ///
    /// # Performance Notes
    ///
    /// - For .ppt files (OLE2): Parses directly from the buffer with minimal copying
    /// - For .pptx files (ZIP): Efficient decompression without file I/O overhead
    /// - Ideal for network data, streams, or in-memory content
    /// - No temporary files created
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        // Detect format from byte signature
        let format = detect_presentation_format_from_bytes(&bytes)?;
        
        match format {
            #[cfg(feature = "ole")]
            PresentationFormat::Ppt => {
                // For OLE2, create cursor from bytes
                let cursor = Cursor::new(bytes);
                
                let mut package = ole::ppt::Package::from_reader(cursor)
                    .map_err(Error::from)?;
                let pres = package.presentation()
                    .map_err(Error::from)?;
                
                Ok(Self {
                    inner: PresentationImpl::Ppt(pres),
                    #[cfg(feature = "ooxml")]
                    _package: None,
                })
            }
            #[cfg(not(feature = "ole"))]
            PresentationFormat::Ppt => {
                Err(Error::FeatureDisabled("ole".to_string()))
            }
            #[cfg(feature = "ooxml")]
            PresentationFormat::Pptx => {
                // For OOXML/ZIP, Cursor<Vec<u8>> implements Read + Seek
                let cursor = Cursor::new(bytes);
                
                let package = Box::new(ooxml::pptx::Package::from_reader(cursor)
                    .map_err(Error::from)?);
                
                // SAFETY: Same lifetime extension as in `open()`
                let pres_ref = unsafe {
                    let pkg_ptr = &*package as *const ooxml::pptx::Package;
                    let pres = (*pkg_ptr).presentation()
                        .map_err(Error::from)?;
                    std::mem::transmute::<ooxml::pptx::Presentation<'_>, ooxml::pptx::Presentation<'static>>(pres)
                };
                
                Ok(Self {
                    inner: PresentationImpl::Pptx(Box::new(pres_ref)),
                    _package: Some(package),
                })
            }
            #[cfg(not(feature = "ooxml"))]
            PresentationFormat::Pptx => {
                Err(Error::FeatureDisabled("ooxml".to_string()))
            }
        }
    }

    /// Get all text content from the presentation.
    ///
    /// This extracts all text from all slides in the presentation.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.ppt")?;
    /// let text = pres.text()?;
    /// println!("{}", text);
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn text(&self) -> Result<String> {
        match &self.inner {
            #[cfg(feature = "ole")]
            PresentationImpl::Ppt(pres) => {
                pres.text().map_err(Error::from)
            }
            #[cfg(feature = "ooxml")]
            PresentationImpl::Pptx(pres) => {
                // PPTX presentations need to extract text from all slides
                let slides = pres.slides().map_err(Error::from)?;
                let mut texts = Vec::new();
                for slide in slides {
                    if let Ok(text) = slide.text() && !text.is_empty() {
                        texts.push(text);
                    }
                }
                Ok(texts.join("\n\n"))
            }
        }
    }

    /// Get the number of slides in the presentation.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.ppt")?;
    /// let count = pres.slide_count()?;
    /// println!("Slides: {}", count);
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn slide_count(&self) -> Result<usize> {
        match &self.inner {
            #[cfg(feature = "ole")]
            PresentationImpl::Ppt(pres) => {
                Ok(pres.slide_count())
            }
            #[cfg(feature = "ooxml")]
            PresentationImpl::Pptx(pres) => {
                pres.slide_count().map_err(Error::from)
            }
        }
    }

    /// Get the slides in the presentation.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.ppt")?;
    /// for slide in pres.slides()? {
    ///     println!("Slide: {}", slide.text()?);
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn slides(&self) -> Result<Vec<Slide>> {
        match &self.inner {
            #[cfg(feature = "ole")]
            PresentationImpl::Ppt(pres) => {
                // Extract slide data to avoid lifetime issues
                let ppt_slides = pres.slides().map_err(Error::from)?;
                ppt_slides.iter()
                    .map(|s| {
                        let text = s.text().map_err(Error::from)?.to_string();
                        let slide_number = s.slide_number();
                        let shape_count = s.shape_count().unwrap_or(0);
                        Ok(Slide::Ppt(PptSlideData {
                            text,
                            slide_number,
                            shape_count,
                        }))
                    })
                    .collect()
            }
            #[cfg(feature = "ooxml")]
            PresentationImpl::Pptx(pres) => {
                let slides = pres.slides()
                    .map_err(Error::from)?;
                // Extract slide data immediately to avoid lifetime issues
                slides.iter()
                    .map(|s| {
                        let text = s.text().map_err(Error::from)?;
                        let name = s.name().ok();
                        Ok(Slide::Pptx(PptxSlideData { text, name }))
                    })
                    .collect()
            }
        }
    }

    /// Get the slide width in EMUs (English Metric Units).
    ///
    /// Only available for .pptx format. Returns None for .ppt files.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.pptx")?;
    /// if let Some(width) = pres.slide_width()? {
    ///     println!("Slide width: {} EMUs", width);
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn slide_width(&self) -> Result<Option<i64>> {
        match &self.inner {
            #[cfg(feature = "ole")]
            PresentationImpl::Ppt(_) => Ok(None),
            #[cfg(feature = "ooxml")]
            PresentationImpl::Pptx(pres) => {
                pres.slide_width().map_err(Error::from)
            }
        }
    }

    /// Get the slide height in EMUs (English Metric Units).
    ///
    /// Only available for .pptx format. Returns None for .ppt files.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.pptx")?;
    /// if let Some(height) = pres.slide_height()? {
    ///     println!("Slide height: {} EMUs", height);
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn slide_height(&self) -> Result<Option<i64>> {
        match &self.inner {
            #[cfg(feature = "ole")]
            PresentationImpl::Ppt(_) => Ok(None),
            #[cfg(feature = "ooxml")]
            PresentationImpl::Pptx(pres) => {
                pres.slide_height().map_err(Error::from)
            }
        }
    }
}

/// A slide in a PowerPoint presentation.
pub enum Slide {
    /// Legacy PPT slide with extracted data
    Ppt(PptSlideData),
    /// Modern PPTX slide with extracted data
    Pptx(PptxSlideData),
}

impl Slide {
    /// Get the text content of the slide.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.ppt")?;
    /// for slide in pres.slides()? {
    ///     println!("Slide text: {}", slide.text()?);
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn text(&self) -> Result<String> {
        match self {
            Slide::Ppt(data) => Ok(data.text.clone()),
            Slide::Pptx(data) => Ok(data.text.clone()),
        }
    }

    /// Get the slide number (1-based).
    ///
    /// Only available for .ppt format. Returns None for .pptx files.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.ppt")?;
    /// for slide in pres.slides()? {
    ///     if let Some(num) = slide.number() {
    ///         println!("Slide number: {}", num);
    ///     }
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn number(&self) -> Option<usize> {
        match self {
            Slide::Ppt(data) => Some(data.slide_number),
            Slide::Pptx(_) => None,
        }
    }

    /// Get the number of shapes on the slide.
    ///
    /// Only available for .ppt format. Returns None for .pptx files.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.ppt")?;
    /// for slide in pres.slides()? {
    ///     if let Some(count) = slide.shape_count() {
    ///         println!("Shapes: {}", count);
    ///     }
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn shape_count(&self) -> Option<usize> {
        match self {
            Slide::Ppt(data) => Some(data.shape_count),
            Slide::Pptx(_) => None,
        }
    }

    /// Get the slide name.
    ///
    /// Only available for .pptx format. Returns None for .ppt files.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use litchi::Presentation;
    ///
    /// let pres = Presentation::open("presentation.pptx")?;
    /// for slide in pres.slides()? {
    ///     if let Some(name) = slide.name()? {
    ///         println!("Slide name: {}", name);
    ///     }
    /// }
    /// # Ok::<(), litchi::common::Error>(())
    /// ```
    pub fn name(&self) -> Result<Option<String>> {
        match self {
            Slide::Ppt(_) => Ok(None),
            Slide::Pptx(data) => Ok(data.name.clone()),
        }
    }
}

/// Presentation format detection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PresentationFormat {
    /// Legacy .ppt format (OLE2)
    Ppt,
    /// Modern .pptx format (OOXML/ZIP)
    Pptx,
}

/// Detect the presentation format by reading the file header.
///
/// This function reads the first few bytes of the file to determine if it's
/// an OLE2 file (.ppt) or a ZIP file (.pptx).
fn detect_presentation_format<R: Read + Seek>(reader: &mut R) -> Result<PresentationFormat> {
    use std::io::SeekFrom;

    // Read the first 8 bytes
    let mut header = [0u8; 8];
    reader.read_exact(&mut header)?;
    
    // Reset to the beginning
    reader.seek(SeekFrom::Start(0))?;

    detect_presentation_format_from_signature(&header)
}

/// Detect the presentation format from a byte buffer.
///
/// This is optimized for in-memory detection without seeking.
#[inline]
fn detect_presentation_format_from_bytes(bytes: &[u8]) -> Result<PresentationFormat> {
    if bytes.len() < 4 {
        return Err(Error::InvalidFormat("File too small to determine format".to_string()));
    }
    
    detect_presentation_format_from_signature(&bytes[0..8.min(bytes.len())])
}

/// Detect format from the signature bytes.
#[inline]
fn detect_presentation_format_from_signature(header: &[u8]) -> Result<PresentationFormat> {
    // Check for OLE2 signature (D0 CF 11 E0 A1 B1 1A E1)
    if header.len() >= 4 && header[0..4] == [0xD0, 0xCF, 0x11, 0xE0] {
        return Ok(PresentationFormat::Ppt);
    }

    // Check for ZIP signature (PK\x03\x04)
    if header.len() >= 4 && header[0..4] == [0x50, 0x4B, 0x03, 0x04] {
        return Ok(PresentationFormat::Pptx);
    }

    Err(Error::NotOfficeFile)
}