ppt-rs 0.2.37

Create, read, and update PowerPoint 2007+ (.pptx) files with rich formatting, bullet styles, themes, and templates.
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
//! CLI commands implementation

use crate::generator;
use std::fs;
use std::path::PathBuf;

pub struct CreateCommand;
pub struct FromMarkdownCommand;
pub struct FromHtmlCommand;
pub struct InfoCommand;
pub struct ValidateCommand;

/// Options for [`FromHtmlCommand::execute`].
#[derive(Debug, Clone)]
pub struct FromHtmlOptions<'a> {
    pub input: &'a str,
    pub output: &'a str,
    pub title: Option<&'a str>,
    pub max_slides: usize,
    pub max_bullets: usize,
    pub no_images: bool,
    pub no_tables: bool,
    pub no_code: bool,
}

impl CreateCommand {
    pub fn execute(
        output: &str,
        title: Option<&str>,
        slides: usize,
        template: Option<&str>,
    ) -> Result<(), String> {
        // Create output directory if needed
        if let Some(parent) = PathBuf::from(output).parent()
            && !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("Failed to create directory: {e}"))?;
            }

        let title = title.unwrap_or("Presentation");

        let pptx_data = if let Some(template_path) = template {
            let slide_list: Vec<_> = (1..=slides)
                .map(|i| generator::SlideContent::new(&format!("Slide {i}")).add_bullet("Content"))
                .collect();
            let settings = generator::PresentationSettings::new().template(template_path);
            generator::create_pptx_with_settings(title, &slide_list, Some(settings))
                .map_err(|e| format!("Failed to generate PPTX from template: {e}"))?
        } else {
            generator::create_pptx(title, slides)
                .map_err(|e| format!("Failed to generate PPTX: {e}"))?
        };

        // Write to file
        fs::write(output, pptx_data).map_err(|e| format!("Failed to write file: {e}"))?;

        Ok(())
    }
}

impl FromMarkdownCommand {
    pub fn execute(input: &str, output: &str, title: Option<&str>) -> Result<(), String> {
        // Read markdown file
        let md_content =
            fs::read_to_string(input).map_err(|e| format!("Failed to read markdown file: {e}"))?;

        // Parse markdown into slides using enhanced parser
        let slides = super::markdown::parse_markdown(&md_content)?;

        if slides.is_empty() {
            return Err("No slides found in markdown file".to_string());
        }

        // Create output directory if needed
        if let Some(parent) = PathBuf::from(output).parent()
            && !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("Failed to create directory: {e}"))?;
            }

        let title = title.unwrap_or("Presentation from Markdown");

        // Generate PPTX with content
        let pptx_data = generator::create_pptx_with_content(title, slides)
            .map_err(|e| format!("Failed to generate PPTX: {e}"))?;

        // Write to file
        fs::write(output, pptx_data).map_err(|e| format!("Failed to write file: {e}"))?;

        Ok(())
    }
}

impl FromHtmlCommand {
    pub fn execute(opts: FromHtmlOptions<'_>) -> Result<(), String> {
        let FromHtmlOptions {
            input,
            output,
            title,
            max_slides,
            max_bullets,
            no_images,
            no_tables,
            no_code,
        } = opts;
        // Read HTML file
        let html_content =
            std::fs::read_to_string(input).map_err(|e| format!("Failed to read HTML file: {e}"))?;

        // Build options
        let options = crate::import::HtmlParseOptions::new()
            .max_slides(max_slides)
            .max_bullets(max_bullets)
            .include_images(!no_images)
            .include_tables(!no_tables)
            .include_code(!no_code);

        // Parse HTML into slides
        let slides = crate::import::parse_html_with_options(&html_content, options)?;

        if slides.is_empty() {
            return Err("No slides found in HTML file".to_string());
        }

        // Create output directory if needed
        if let Some(parent) = PathBuf::from(output).parent()
            && !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("Failed to create directory: {e}"))?;
            }

        let title = title.unwrap_or("Presentation from HTML");

        // Generate PPTX with content
        let pptx_data = generator::create_pptx_with_content(title, slides)
            .map_err(|e| format!("Failed to generate PPTX: {e}"))?;

        // Write to file
        fs::write(output, pptx_data).map_err(|e| format!("Failed to write file: {e}"))?;

        Ok(())
    }
}

impl InfoCommand {
    pub fn execute(file: &str) -> Result<(), String> {
        let metadata = fs::metadata(file).map_err(|e| format!("File not found: {e}"))?;

        let size = metadata.len();
        let modified = metadata
            .modified()
            .ok()
            .and_then(|t| t.elapsed().ok())
            .map(|d| format!("{d:?} ago"))
            .unwrap_or_else(|| "unknown".to_string());

        println!("File Information");
        println!("================");
        println!("Path:     {file}");
        println!("Size:     {size} bytes");
        println!("Modified: {modified}");
        let is_file = metadata.is_file();
        println!("Is file:  {is_file}");

        // Try to read and parse as XML
        if let Ok(content) = fs::read_to_string(file)
            && content.starts_with("<?xml") {
                println!("\nPresentation Information");
                println!("========================");
                if let Some(title_start) = content.find("<title>")
                    && let Some(title_end) = content[title_start + 7..].find("</title>") {
                        let title = &content[title_start + 7..title_start + 7 + title_end];
                        println!("Title: {title}");
                    }
                if let Some(slides_start) = content.find("count=\"") {
                    let search_from = slides_start + 7;
                    if let Some(slides_end) = content[search_from..].find("\"") {
                        let count_str = &content[search_from..search_from + slides_end];
                        println!("Slides: {count_str}");
                    }
                }
            }

        Ok(())
    }
}

pub struct DiffCommand;

impl DiffCommand {
    /// Compare two PPTX files semantically. Returns Ok when equal.
    pub fn execute(old: &str, new: &str, json: bool) -> Result<(), String> {
        let diff = crate::compare_pptx_paths(old, new)
            .map_err(|e| format!("Failed to compare presentations: {e}"))?;

        if json {
            Self::print_json(old, new, &diff);
        } else {
            Self::print_human(old, new, &diff);
        }

        if diff.is_equal() {
            Ok(())
        } else {
            Err(diff.summary())
        }
    }

    fn print_human(old: &str, new: &str, diff: &crate::PresentationDiff) {
        println!("Semantic diff");
        println!("{}", "=".repeat(60));
        println!("Old:  {old}");
        println!("New:  {new}");
        println!("Result: {}", diff.summary());

        if let Some((before, after)) = &diff.title_changed {
            println!("\nPresentation title: {before:?} → {after:?}");
        }

        for change in &diff.slide_changes {
            match change {
                crate::SlideChange::Added { index, slide } => {
                    println!("\n+ Slide {} added: {:?}", index + 1, slide.title);
                }
                crate::SlideChange::Removed { index, slide } => {
                    println!("\n- Slide {} removed: {:?}", index + 1, slide.title);
                }
                crate::SlideChange::Modified {
                    index,
                    before,
                    after,
                    fields,
                } => {
                    println!(
                        "\n~ Slide {} modified: {:?} → {:?}",
                        index + 1,
                        before.title,
                        after.title
                    );
                    for field in fields {
                        println!("    {field:?}");
                    }
                }
            }
        }

        if diff.is_equal() {
            println!("\n✓ No semantic differences");
        } else {
            println!("\n✗ Presentations differ semantically");
        }
    }

    fn print_json(old: &str, new: &str, diff: &crate::PresentationDiff) {
        println!("{{");
        println!("  \"old\": {},", json_string(old));
        println!("  \"new\": {},", json_string(new));
        println!("  \"equal\": {},", diff.is_equal());
        println!("  \"summary\": {},", json_string(&diff.summary()));
        match &diff.title_changed {
            Some((before, after)) => {
                println!("  \"title_changed\": {{");
                println!("    \"before\": {},", json_string(before));
                println!("    \"after\": {}", json_string(after));
                println!("  }},");
            }
            None => println!("  \"title_changed\": null,"),
        }
        println!("  \"slide_changes\": [");
        for (i, change) in diff.slide_changes.iter().enumerate() {
            let comma = if i + 1 < diff.slide_changes.len() {
                ","
            } else {
                ""
            };
            match change {
                crate::SlideChange::Added { index, slide } => {
                    println!(
                        "    {{\"kind\": \"added\", \"index\": {index}, \"title\": {}}}{comma}",
                        json_string(&slide.title)
                    );
                }
                crate::SlideChange::Removed { index, slide } => {
                    println!(
                        "    {{\"kind\": \"removed\", \"index\": {index}, \"title\": {}}}{comma}",
                        json_string(&slide.title)
                    );
                }
                crate::SlideChange::Modified { index, fields, .. } => {
                    println!(
                        "    {{\"kind\": \"modified\", \"index\": {index}, \"fields\": {fields:?}}}{comma}"
                    );
                }
            }
        }
        println!("  ]");
        println!("}}");
    }
}

pub struct BatchCommand;

impl BatchCommand {
    /// Convert every Markdown/HTML file in a directory to separate `.pptx` files.
    pub fn execute(
        input_dir: &str,
        output_dir: &str,
        template: Option<&str>,
    ) -> Result<Vec<crate::BatchResult>, String> {
        let mut options = crate::BatchOptions::new(output_dir);
        if let Some(path) = template {
            options = options.with_template(path);
        }
        crate::run_directory(std::path::Path::new(input_dir), &options)
            .map_err(|e| format!("Batch conversion failed: {e}"))
    }
}

impl ValidateCommand {
    /// Validate a PPTX file and report structured package issues.
    pub fn execute(file: &str, json: bool) -> Result<(), String> {
        let bytes = fs::read(file).map_err(|e| format!("Failed to read file: {e}"))?;
        let report = crate::core::validate_package_bytes(&bytes);

        if json {
            Self::print_json(file, &report);
        } else {
            Self::print_human(file, &report);
        }

        if report.is_valid() {
            Ok(())
        } else {
            Err(format!(
                "Validation failed with {} error(s), {} warning(s)",
                report.error_count(),
                report.warning_count()
            ))
        }
    }

    fn print_human(file: &str, report: &crate::core::PackageValidationReport) {
        use crate::core::ValidationSeverity;

        println!("Validating PPTX file: {file}");
        println!("{}", "=".repeat(60));
        println!(
            "Summary: {} error(s), {} warning(s)",
            report.error_count(),
            report.warning_count()
        );

        if report.issues.is_empty() {
            println!("\n✓ Validation PASSED — no issues found");
            return;
        }

        println!();
        for issue in &report.issues {
            let severity = match issue.severity {
                ValidationSeverity::Error => "ERROR",
                ValidationSeverity::Warning => "WARNING",
            };
            let path = issue.path.as_deref().unwrap_or("-");
            println!("[{severity}] {:?}  {path}", issue.category);
            println!("  {}", issue.message);
        }

        if report.is_valid() {
            println!("\n✓ Validation PASSED (warnings only)");
        } else {
            println!("\n✗ Validation FAILED");
        }
    }

    fn print_json(file: &str, report: &crate::core::PackageValidationReport) {
        use crate::core::ValidationSeverity;

        println!("{{");
        println!("  \"file\": {},", json_string(file));
        println!("  \"valid\": {},", report.is_valid());
        println!("  \"error_count\": {},", report.error_count());
        println!("  \"warning_count\": {},", report.warning_count());
        println!("  \"issues\": [");
        for (i, issue) in report.issues.iter().enumerate() {
            let severity = match issue.severity {
                ValidationSeverity::Error => "error",
                ValidationSeverity::Warning => "warning",
            };
            let path = issue
                .path
                .as_deref()
                .map(json_string)
                .unwrap_or_else(|| "null".to_string());
            let comma = if i + 1 < report.issues.len() { "," } else { "" };
            println!("    {{");
            println!("      \"severity\": \"{severity}\",");
            println!("      \"category\": \"{:?}\",", issue.category);
            println!("      \"path\": {path},");
            println!("      \"message\": {}", json_string(&issue.message));
            println!("    }}{comma}");
        }
        println!("  ]");
        println!("}}");
    }
}

fn json_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;

    #[test]
    fn test_create_command() {
        let output = "/tmp/test_presentation.pptx";
        let result = CreateCommand::execute(output, Some("Test"), 3, None);
        assert!(result.is_ok());
        assert!(Path::new(output).exists());

        // Cleanup
        let _ = fs::remove_file(output);
    }

    #[test]
    fn test_escape_xml() {
        use crate::core::escape_xml;
        assert_eq!(escape_xml("a & b"), "a &amp; b");
        assert_eq!(escape_xml("<tag>"), "&lt;tag&gt;");
        assert_eq!(escape_xml("\"quoted\""), "&quot;quoted&quot;");
    }
}