ppt-rs 0.2.12

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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Table part
//!
//! Represents table data embedded in slides with advanced formatting.
//!
//! # Features
//! - Cell merging (row span, column span)
//! - Text formatting (bold, italic, underline, strikethrough)
//! - Cell alignment (horizontal and vertical)
//! - Borders (all sides, individual sides)
//! - Background colors and gradients
//! - Font customization (size, color, family)
//! - Table styles

use super::base::{ContentType, Part, PartType};
use crate::core::{escape_xml, ToXml};
use crate::exc::PptxError;

/// Horizontal alignment
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HorizontalAlign {
    #[default]
    Left,
    Center,
    Right,
    Justify,
}

impl HorizontalAlign {
    pub fn as_str(&self) -> &'static str {
        match self {
            HorizontalAlign::Left => "l",
            HorizontalAlign::Center => "ctr",
            HorizontalAlign::Right => "r",
            HorizontalAlign::Justify => "just",
        }
    }
}

/// Vertical alignment
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalAlign {
    Top,
    #[default]
    Middle,
    Bottom,
}

impl VerticalAlign {
    pub fn as_str(&self) -> &'static str {
        match self {
            VerticalAlign::Top => "t",
            VerticalAlign::Middle => "ctr",
            VerticalAlign::Bottom => "b",
        }
    }
}

/// Border style
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BorderStyle {
    #[default]
    Solid,
    Dashed,
    Dotted,
    Double,
    None,
}

impl BorderStyle {
    pub fn as_str(&self) -> &'static str {
        match self {
            BorderStyle::Solid => "solid",
            BorderStyle::Dashed => "dash",
            BorderStyle::Dotted => "dot",
            BorderStyle::Double => "dbl",
            BorderStyle::None => "none",
        }
    }
}

/// Cell border
#[derive(Debug, Clone, Default)]
pub struct CellBorder {
    pub width: i32, // in EMU (12700 = 1pt)
    pub color: String,
    pub style: BorderStyle,
}

impl CellBorder {
    pub fn new(width_pt: f32, color: impl Into<String>) -> Self {
        CellBorder {
            width: (width_pt * 12700.0) as i32,
            color: color.into(),
            style: BorderStyle::Solid,
        }
    }

    pub fn style(mut self, style: BorderStyle) -> Self {
        self.style = style;
        self
    }

    pub fn to_xml(&self, tag: &str) -> String {
        if self.style == BorderStyle::None {
            return format!("<a:{}/>\n", tag);
        }
        format!(
            r#"<a:{} w="{}" cap="flat" cmpd="sng" algn="ctr">
              <a:solidFill><a:srgbClr val="{}"/></a:solidFill>
              <a:prstDash val="{}"/>
            </a:{}>"#,
            tag,
            self.width,
            self.color.trim_start_matches('#'),
            self.style.as_str(),
            tag
        )
    }
}

/// Cell borders (all four sides)
#[derive(Debug, Clone, Default)]
pub struct CellBorders {
    pub left: Option<CellBorder>,
    pub right: Option<CellBorder>,
    pub top: Option<CellBorder>,
    pub bottom: Option<CellBorder>,
}

impl CellBorders {
    pub fn all(border: CellBorder) -> Self {
        CellBorders {
            left: Some(border.clone()),
            right: Some(border.clone()),
            top: Some(border.clone()),
            bottom: Some(border),
        }
    }

    pub fn none() -> Self {
        let no_border = CellBorder {
            width: 0,
            color: String::new(),
            style: BorderStyle::None,
        };
        CellBorders {
            left: Some(no_border.clone()),
            right: Some(no_border.clone()),
            top: Some(no_border.clone()),
            bottom: Some(no_border),
        }
    }

    pub fn to_xml(&self) -> String {
        let mut xml = String::new();
        if let Some(ref b) = self.left {
            xml.push_str(&b.to_xml("lnL"));
        }
        if let Some(ref b) = self.right {
            xml.push_str(&b.to_xml("lnR"));
        }
        if let Some(ref b) = self.top {
            xml.push_str(&b.to_xml("lnT"));
        }
        if let Some(ref b) = self.bottom {
            xml.push_str(&b.to_xml("lnB"));
        }
        xml
    }
}

impl ToXml for CellBorders {
    fn to_xml(&self) -> String {
        CellBorders::to_xml(self)
    }
}

/// Cell margins
#[derive(Debug, Clone)]
pub struct CellMargins {
    pub left: i32, // in EMU
    pub right: i32,
    pub top: i32,
    pub bottom: i32,
}

impl Default for CellMargins {
    fn default() -> Self {
        CellMargins {
            left: 91440, // 0.1 inch
            right: 91440,
            top: 45720, // 0.05 inch
            bottom: 45720,
        }
    }
}

impl CellMargins {
    pub fn uniform(margin: i32) -> Self {
        CellMargins {
            left: margin,
            right: margin,
            top: margin,
            bottom: margin,
        }
    }
}

/// Table cell with advanced formatting
#[derive(Debug, Clone)]
pub struct TableCellPart {
    pub text: String,
    pub row_span: u32,
    pub col_span: u32,
    pub bold: bool,
    pub italic: bool,
    pub underline: bool,
    pub strikethrough: bool,
    pub background_color: Option<String>,
    pub text_color: Option<String>,
    pub font_size: Option<u32>,
    pub font_family: Option<String>,
    pub h_align: HorizontalAlign,
    pub v_align: VerticalAlign,
    pub borders: Option<CellBorders>,
    pub margins: Option<CellMargins>,
    pub is_merged: bool, // For cells that are part of a merge (not the anchor)
}

impl TableCellPart {
    /// Create a new table cell
    pub fn new(text: impl Into<String>) -> Self {
        TableCellPart {
            text: text.into(),
            row_span: 1,
            col_span: 1,
            bold: false,
            italic: false,
            underline: false,
            strikethrough: false,
            background_color: None,
            text_color: None,
            font_size: None,
            font_family: None,
            h_align: HorizontalAlign::default(),
            v_align: VerticalAlign::default(),
            borders: None,
            margins: None,
            is_merged: false,
        }
    }

    /// Create a merged placeholder cell (for cells covered by a span)
    pub fn merged() -> Self {
        let mut cell = Self::new("");
        cell.is_merged = true;
        cell
    }

    /// Set bold
    pub fn bold(mut self) -> Self {
        self.bold = true;
        self
    }

    /// Set italic
    pub fn italic(mut self) -> Self {
        self.italic = true;
        self
    }

    /// Set underline
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }

    /// Set strikethrough
    pub fn strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    /// Set background color
    pub fn background(mut self, color: impl Into<String>) -> Self {
        self.background_color = Some(color.into());
        self
    }

    /// Set text color
    pub fn color(mut self, color: impl Into<String>) -> Self {
        self.text_color = Some(color.into());
        self
    }

    /// Set font size (in points)
    pub fn font_size(mut self, size: u32) -> Self {
        self.font_size = Some(size);
        self
    }

    /// Set font family
    pub fn font(mut self, family: impl Into<String>) -> Self {
        self.font_family = Some(family.into());
        self
    }

    /// Set horizontal alignment
    pub fn align(mut self, align: HorizontalAlign) -> Self {
        self.h_align = align;
        self
    }

    /// Set vertical alignment
    pub fn valign(mut self, align: VerticalAlign) -> Self {
        self.v_align = align;
        self
    }

    /// Center text (horizontal and vertical)
    pub fn center(mut self) -> Self {
        self.h_align = HorizontalAlign::Center;
        self.v_align = VerticalAlign::Middle;
        self
    }

    /// Set row span
    pub fn row_span(mut self, span: u32) -> Self {
        self.row_span = span;
        self
    }

    /// Set column span
    pub fn col_span(mut self, span: u32) -> Self {
        self.col_span = span;
        self
    }

    /// Set all borders
    pub fn borders(mut self, borders: CellBorders) -> Self {
        self.borders = Some(borders);
        self
    }

    /// Set uniform border on all sides
    pub fn border(mut self, width_pt: f32, color: impl Into<String>) -> Self {
        self.borders = Some(CellBorders::all(CellBorder::new(width_pt, color)));
        self
    }

    /// Set cell margins
    pub fn margins(mut self, margins: CellMargins) -> Self {
        self.margins = Some(margins);
        self
    }

    /// Generate XML for this cell
    pub fn to_xml(&self) -> String {
        // Handle merged cells (placeholders)
        if self.is_merged {
            return r#"<a:tc hMerge="1"><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody><a:tcPr/></a:tc>"#.to_string();
        }

        let mut attrs = String::new();
        if self.row_span > 1 {
            attrs.push_str(&format!(r#" rowSpan="{}""#, self.row_span));
        }
        if self.col_span > 1 {
            attrs.push_str(&format!(r#" gridSpan="{}""#, self.col_span));
        }

        // Background fill
        let bg_xml = self
            .background_color
            .as_ref()
            .map(|c| {
                format!(
                    r#"<a:solidFill><a:srgbClr val="{}"/></a:solidFill>"#,
                    c.trim_start_matches('#')
                )
            })
            .unwrap_or_default();

        // Text run properties
        let mut rpr_attrs = String::new();
        if self.bold {
            rpr_attrs.push_str(r#" b="1""#);
        }
        if self.italic {
            rpr_attrs.push_str(r#" i="1""#);
        }
        if self.underline {
            rpr_attrs.push_str(r#" u="sng""#);
        }
        if self.strikethrough {
            rpr_attrs.push_str(r#" strike="sngStrike""#);
        }
        if let Some(size) = self.font_size {
            rpr_attrs.push_str(&format!(r#" sz="{}""#, size * 100));
        }

        // Text color
        let color_xml = self
            .text_color
            .as_ref()
            .map(|c| {
                format!(
                    r#"<a:solidFill><a:srgbClr val="{}"/></a:solidFill>"#,
                    c.trim_start_matches('#')
                )
            })
            .unwrap_or_default();

        // Font family
        let font_xml = self
            .font_family
            .as_ref()
            .map(|f| format!(r#"<a:latin typeface="{}"/>"#, f))
            .unwrap_or_default();

        // Paragraph alignment
        let p_align = format!(r#" algn="{}""#, self.h_align.as_str());

        // Cell properties
        let mut tcpr_attrs = format!(r#" anchor="{}""#, self.v_align.as_str());
        if let Some(ref m) = self.margins {
            tcpr_attrs.push_str(&format!(
                r#" marL="{}" marR="{}" marT="{}" marB="{}""#,
                m.left, m.right, m.top, m.bottom
            ));
        }

        // Borders
        let borders_xml = self
            .borders
            .as_ref()
            .map(|b| b.to_xml())
            .unwrap_or_default();

        format!(
            r#"<a:tc{}>
          <a:txBody>
            <a:bodyPr/>
            <a:lstStyle/>
            <a:p{}>
              <a:r>
                <a:rPr lang="en-US"{}>{}{}</a:rPr>
                <a:t>{}</a:t>
              </a:r>
            </a:p>
          </a:txBody>
          <a:tcPr{}>{}{}</a:tcPr>
        </a:tc>"#,
            attrs,
            p_align,
            rpr_attrs,
            color_xml,
            font_xml,
            escape_xml(&self.text),
            tcpr_attrs,
            borders_xml,
            bg_xml
        )
    }
}

impl ToXml for TableCellPart {
    fn to_xml(&self) -> String {
        TableCellPart::to_xml(self)
    }
}

/// Table row
#[derive(Debug, Clone)]
pub struct TableRowPart {
    pub cells: Vec<TableCellPart>,
    pub height: Option<i64>, // in EMU
}

impl TableRowPart {
    /// Create a new table row
    pub fn new(cells: Vec<TableCellPart>) -> Self {
        TableRowPart {
            cells,
            height: None,
        }
    }

    /// Set row height in EMU
    pub fn height(mut self, height: i64) -> Self {
        self.height = Some(height);
        self
    }

    /// Generate XML for this row
    pub fn to_xml(&self) -> String {
        let height_attr = self
            .height
            .map(|h| format!(r#" h="{}""#, h))
            .unwrap_or_default();

        let cells_xml: String = self
            .cells
            .iter()
            .map(|c| c.to_xml())
            .collect::<Vec<_>>()
            .join("\n        ");

        format!(
            r#"<a:tr{}>
        {}
      </a:tr>"#,
            height_attr, cells_xml
        )
    }
}

impl ToXml for TableRowPart {
    fn to_xml(&self) -> String {
        TableRowPart::to_xml(self)
    }
}

/// Table part for embedding in slides
#[derive(Debug, Clone)]
pub struct TablePart {
    pub rows: Vec<TableRowPart>,
    pub col_widths: Vec<i64>, // in EMU
    pub x: i64,
    pub y: i64,
    pub width: i64,
    pub height: i64,
}

impl TablePart {
    /// Create a new table part
    pub fn new() -> Self {
        TablePart {
            rows: vec![],
            col_widths: vec![],
            x: 914400,       // 1 inch
            y: 1828800,      // 2 inches
            width: 7315200,  // 8 inches
            height: 1828800, // 2 inches
        }
    }

    /// Add a row
    pub fn add_row(mut self, row: TableRowPart) -> Self {
        // Auto-calculate column widths if not set
        if self.col_widths.is_empty() && !row.cells.is_empty() {
            let col_count = row.cells.len();
            let col_width = self.width / col_count as i64;
            self.col_widths = vec![col_width; col_count];
        }
        self.rows.push(row);
        self
    }

    /// Set position
    pub fn position(mut self, x: i64, y: i64) -> Self {
        self.x = x;
        self.y = y;
        self
    }

    /// Set size
    pub fn size(mut self, width: i64, height: i64) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    /// Set column widths
    pub fn col_widths(mut self, widths: Vec<i64>) -> Self {
        self.col_widths = widths;
        self
    }

    /// Generate table XML for embedding in a slide
    pub fn to_slide_xml(&self, shape_id: usize) -> String {
        let grid_cols: String = self
            .col_widths
            .iter()
            .map(|w| format!(r#"<a:gridCol w="{}"/>"#, w))
            .collect::<Vec<_>>()
            .join("\n        ");

        let rows_xml: String = self
            .rows
            .iter()
            .map(|r| r.to_xml())
            .collect::<Vec<_>>()
            .join("\n      ");

        format!(
            r#"<p:graphicFrame>
  <p:nvGraphicFramePr>
    <p:cNvPr id="{}" name="Table {}"/>
    <p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr>
    <p:nvPr/>
  </p:nvGraphicFramePr>
  <p:xfrm>
    <a:off x="{}" y="{}"/>
    <a:ext cx="{}" cy="{}"/>
  </p:xfrm>
  <a:graphic>
    <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table">
      <a:tbl>
        <a:tblPr firstRow="1" bandRow="1">
          <a:tableStyleId>{{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}}</a:tableStyleId>
        </a:tblPr>
        <a:tblGrid>
        {}
        </a:tblGrid>
      {}
      </a:tbl>
    </a:graphicData>
  </a:graphic>
</p:graphicFrame>"#,
            shape_id, shape_id, self.x, self.y, self.width, self.height, grid_cols, rows_xml
        )
    }
}

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

impl Part for TablePart {
    fn path(&self) -> &str {
        "" // Tables are embedded in slides, not separate parts
    }

    fn part_type(&self) -> PartType {
        PartType::Slide // Tables are part of slides
    }

    fn content_type(&self) -> ContentType {
        ContentType::Xml
    }

    fn to_xml(&self) -> Result<String, PptxError> {
        Ok(self.to_slide_xml(2))
    }

    fn from_xml(_xml: &str) -> Result<Self, PptxError> {
        Ok(TablePart::new())
    }
}

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

    #[test]
    fn test_table_cell_new() {
        let cell = TableCellPart::new("Test");
        assert_eq!(cell.text, "Test");
        assert!(!cell.bold);
    }

    #[test]
    fn test_table_cell_formatting() {
        let cell = TableCellPart::new("Bold")
            .bold()
            .color("FF0000")
            .font_size(14);
        assert!(cell.bold);
        assert_eq!(cell.text_color, Some("FF0000".to_string()));
        assert_eq!(cell.font_size, Some(14));
    }

    #[test]
    fn test_table_cell_span() {
        let cell = TableCellPart::new("Merged").row_span(2).col_span(3);
        assert_eq!(cell.row_span, 2);
        assert_eq!(cell.col_span, 3);
    }

    #[test]
    fn test_table_row_new() {
        let row = TableRowPart::new(vec![TableCellPart::new("A"), TableCellPart::new("B")]);
        assert_eq!(row.cells.len(), 2);
    }

    #[test]
    fn test_table_part_new() {
        let table = TablePart::new()
            .add_row(TableRowPart::new(vec![
                TableCellPart::new("Header 1"),
                TableCellPart::new("Header 2"),
            ]))
            .add_row(TableRowPart::new(vec![
                TableCellPart::new("Data 1"),
                TableCellPart::new("Data 2"),
            ]));
        assert_eq!(table.rows.len(), 2);
        assert_eq!(table.col_widths.len(), 2);
    }

    #[test]
    fn test_table_to_xml() {
        let table = TablePart::new().add_row(TableRowPart::new(vec![TableCellPart::new("Test")]));
        let xml = table.to_slide_xml(5);
        assert!(xml.contains("p:graphicFrame"));
        assert!(xml.contains("a:tbl"));
        assert!(xml.contains("Test"));
    }
}