office_oxide 0.1.1

The fastest Office document processing library — DOCX, XLSX, PPTX, DOC, XLS, PPT
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
//! PPTX creation (write) module.
//!
//! Provides a builder API for creating PPTX files from scratch.
//!
//! # Example
//!
//! ```rust,no_run
//! use office_oxide::pptx::write::{PptxWriter, Run};
//!
//! let mut writer = PptxWriter::new();
//! writer.add_slide()
//!     .set_title("Hello")
//!     .add_text("World")
//!     .add_rich_text(&[
//!         Run::new("Bold").bold(),
//!         Run::new(" and ").into(),
//!         Run::new("red").color("FF0000"),
//!     ])
//!     .add_bullet_list(&["First", "Second", "Third"])
//!     .add_text_box("Note", 1_000_000, 5_000_000, 3_000_000, 500_000);
//! writer.save("output.pptx").unwrap();
//! ```

use std::io::{Seek, Write};
use std::path::Path;

use quick_xml::Writer;
use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event};

use crate::core::opc::{OpcWriter, PartName};
use crate::core::relationships::rel_types;

use super::Result;

// ---------------------------------------------------------------------------
// Content types
// ---------------------------------------------------------------------------

const CT_PRESENTATION: &str =
    "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml";
const CT_SLIDE: &str = "application/vnd.openxmlformats-officedocument.presentationml.slide+xml";
const CT_SLIDE_LAYOUT: &str =
    "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml";
const CT_SLIDE_MASTER: &str =
    "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml";

// ---------------------------------------------------------------------------
// Namespaces
// ---------------------------------------------------------------------------

use crate::core::xml::ns::{DRAWING_ML_STR as NS_DML, PML_STR as NS_PML, R_STR as NS_REL};

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A styled text run for a PPTX paragraph.
///
/// # Example
/// ```rust,no_run
/// use office_oxide::pptx::write::Run;
///
/// let r = Run::new("Highlighted").bold().color("FFCC00").font_size(18.0);
/// ```
#[derive(Debug, Clone, Default)]
pub struct Run {
    /// The text content of this run.
    pub text: String,
    /// Apply bold weight.
    pub bold: bool,
    /// Apply italic style.
    pub italic: bool,
    /// Apply single underline.
    pub underline: bool,
    /// Apply strikethrough.
    pub strikethrough: bool,
    /// 6-char hex color string, e.g. `"FF0000"` (no leading `#`).
    pub color: Option<String>,
    /// Font size in points, e.g. `18.0`.
    pub font_size_pt: Option<f64>,
    /// Font name, e.g. `"Calibri"`.
    pub font_name: Option<String>,
}

impl Run {
    /// Create a plain text run.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ..Default::default()
        }
    }

    /// Enable bold weight.
    pub fn bold(mut self) -> Self {
        self.bold = true;
        self
    }
    /// Enable italic style.
    pub fn italic(mut self) -> Self {
        self.italic = true;
        self
    }
    /// Enable single underline.
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }
    /// Enable strikethrough.
    pub fn strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    /// Font color as a 6-char hex string (no `#`).
    pub fn color(mut self, hex: impl Into<String>) -> Self {
        self.color = Some(hex.into());
        self
    }

    /// Font size in points.
    pub fn font_size(mut self, pt: f64) -> Self {
        self.font_size_pt = Some(pt);
        self
    }

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

    fn has_rpr(&self) -> bool {
        self.bold
            || self.italic
            || self.underline
            || self.strikethrough
            || self.color.is_some()
            || self.font_size_pt.is_some()
            || self.font_name.is_some()
    }
}

impl From<&str> for Run {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl From<String> for Run {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

// ---------------------------------------------------------------------------
// Internal body content model
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
enum BodyItem {
    Text(String),
    RichText(Vec<Run>),
    BulletList(Vec<String>),
    /// Free-floating text box: (runs, x_emu, y_emu, cx_emu, cy_emu)
    TextBox(Vec<Run>, i64, i64, i64, i64),
    /// Embedded image: (data, format, x_emu, y_emu, cx_emu, cy_emu)
    Image(Vec<u8>, crate::ir::ImageFormat, i64, i64, u64, u64),
}

// ---------------------------------------------------------------------------
// SlideData
// ---------------------------------------------------------------------------

/// Data for a single slide being constructed.
#[derive(Debug, Clone)]
pub struct SlideData {
    /// The slide title (if set).
    pub title: Option<String>,
    body_items: Vec<BodyItem>,
}

impl SlideData {
    fn new() -> Self {
        Self {
            title: None,
            body_items: Vec::new(),
        }
    }

    /// Set the slide title. Overwrites any previously set title.
    pub fn set_title(&mut self, title: &str) -> &mut Self {
        self.title = Some(title.to_string());
        self
    }

    /// Add a plain text paragraph to the body area.
    pub fn add_text(&mut self, text: &str) -> &mut Self {
        self.body_items.push(BodyItem::Text(text.to_string()));
        self
    }

    /// Add a paragraph of styled [`Run`]s to the body area.
    pub fn add_rich_text(&mut self, runs: &[Run]) -> &mut Self {
        self.body_items.push(BodyItem::RichText(runs.to_vec()));
        self
    }

    /// Add a bullet list to the body area.
    pub fn add_bullet_list(&mut self, items: &[&str]) -> &mut Self {
        let owned: Vec<String> = items.iter().map(|s| s.to_string()).collect();
        self.body_items.push(BodyItem::BulletList(owned));
        self
    }

    /// Add a free-floating text box at an absolute position.
    ///
    /// All dimensions are in EMU (English Metric Units).
    /// 1 inch = 914 400 EMU; 1 cm ≈ 360 000 EMU.
    pub fn add_text_box(&mut self, text: &str, x: i64, y: i64, cx: i64, cy: i64) -> &mut Self {
        self.body_items
            .push(BodyItem::TextBox(vec![Run::new(text)], x, y, cx, cy));
        self
    }

    /// Add a free-floating text box with styled [`Run`]s.
    pub fn add_rich_text_box(
        &mut self,
        runs: &[Run],
        x: i64,
        y: i64,
        cx: i64,
        cy: i64,
    ) -> &mut Self {
        self.body_items
            .push(BodyItem::TextBox(runs.to_vec(), x, y, cx, cy));
        self
    }

    /// Embed an image at an absolute position on the slide.
    ///
    /// All coordinates are in EMU (English Metric Units; 914 400 EMU = 1 inch).
    pub fn add_image(
        &mut self,
        data: Vec<u8>,
        format: crate::ir::ImageFormat,
        x: i64,
        y: i64,
        cx: u64,
        cy: u64,
    ) -> &mut Self {
        self.body_items
            .push(BodyItem::Image(data, format, x, y, cx, cy));
        self
    }

    fn has_placeholder_body(&self) -> bool {
        self.body_items
            .iter()
            .any(|i| !matches!(i, BodyItem::TextBox(..) | BodyItem::Image(..)))
    }
}

// ---------------------------------------------------------------------------
// PptxWriter
// ---------------------------------------------------------------------------

/// Builder for creating PPTX files from scratch.
pub struct PptxWriter {
    slides: Vec<SlideData>,
    /// Presentation width in EMU (default: 12 192 000 — standard 16:9).
    cx: u64,
    /// Presentation height in EMU (default: 6 858 000 — standard 16:9).
    cy: u64,
}

impl PptxWriter {
    /// Create a new empty PPTX writer.
    pub fn new() -> Self {
        Self {
            slides: Vec::new(),
            cx: 12_192_000,
            cy: 6_858_000,
        }
    }

    /// Override the presentation canvas size (in EMU).
    ///
    /// Call before adding slides. 914 400 EMU = 1 inch.
    pub fn set_presentation_size(&mut self, cx: u64, cy: u64) -> &mut Self {
        self.cx = cx;
        self.cy = cy;
        self
    }

    /// Add a new slide and return a mutable reference for configuration.
    pub fn add_slide(&mut self) -> &mut SlideData {
        self.slides.push(SlideData::new());
        self.slides.last_mut().expect("just pushed")
    }

    /// Add a slide and return its 0-based index (for use with index-based API).
    pub fn add_slide_get_index(&mut self) -> usize {
        self.slides.push(SlideData::new());
        self.slides.len() - 1
    }

    /// Set the slide title by slide index.
    pub fn slide_set_title(&mut self, slide: usize, title: &str) {
        if let Some(s) = self.slides.get_mut(slide) {
            s.set_title(title);
        }
    }

    /// Add a plain text paragraph to the slide body by slide index.
    pub fn slide_add_text(&mut self, slide: usize, text: &str) {
        if let Some(s) = self.slides.get_mut(slide) {
            s.add_text(text);
        }
    }

    /// Embed an image on a slide by slide index.
    pub fn slide_add_image(
        &mut self,
        slide: usize,
        data: Vec<u8>,
        format: crate::ir::ImageFormat,
        x: i64,
        y: i64,
        cx: u64,
        cy: u64,
    ) {
        if let Some(s) = self.slides.get_mut(slide) {
            s.add_image(data, format, x, y, cx, cy);
        }
    }

    /// Save the presentation to a file path.
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let opc = OpcWriter::create(path)?;
        self.write_opc(opc)?;
        Ok(())
    }

    /// Write the presentation to any `Write + Seek` destination.
    pub fn write_to<W: Write + Seek>(&self, writer: W) -> Result<()> {
        let opc = OpcWriter::new(writer)?;
        self.write_opc(opc)?;
        Ok(())
    }

    fn write_opc<W: Write + Seek>(&self, mut opc: OpcWriter<W>) -> Result<()> {
        let pres_part = PartName::new("/ppt/presentation.xml")?;
        let master_part = PartName::new("/ppt/slideMasters/slideMaster1.xml")?;
        let layout_part = PartName::new("/ppt/slideLayouts/slideLayout1.xml")?;

        opc.add_package_rel(rel_types::OFFICE_DOCUMENT, "ppt/presentation.xml");
        opc.add_part_rel(&pres_part, rel_types::SLIDE_MASTER, "slideMasters/slideMaster1.xml");

        let mut slide_parts = Vec::with_capacity(self.slides.len());
        for i in 0..self.slides.len() {
            let idx = i + 1;
            let slide_part = PartName::new(&format!("/ppt/slides/slide{idx}.xml"))?;
            opc.add_part_rel(&pres_part, rel_types::SLIDE, &format!("slides/slide{idx}.xml"));
            slide_parts.push(slide_part);
        }

        opc.add_part_rel(&master_part, rel_types::SLIDE_LAYOUT, "../slideLayouts/slideLayout1.xml");

        let pres_xml = generate_presentation_xml(self.slides.len(), self.cx, self.cy);
        opc.add_part(&pres_part, CT_PRESENTATION, &pres_xml)?;

        let master_xml = generate_slide_master_xml();
        opc.add_part(&master_part, CT_SLIDE_MASTER, &master_xml)?;

        let layout_xml = generate_slide_layout_xml();
        opc.add_part(&layout_part, CT_SLIDE_LAYOUT, &layout_xml)?;

        let mut global_img_idx = 1u32;
        for (i, slide) in self.slides.iter().enumerate() {
            let slide_part = &slide_parts[i];

            // rId1 = slide layout
            opc.add_part_rel(
                slide_part,
                rel_types::SLIDE_LAYOUT,
                "../slideLayouts/slideLayout1.xml",
            );

            // rId2+ = one per embedded image
            let mut img_rids: Vec<(String, i64, i64, u64, u64)> = Vec::new();
            for item in &slide.body_items {
                if let BodyItem::Image(data, fmt, x, y, cx, cy) = item {
                    let rid = format!("rId{}", img_rids.len() + 2);
                    let ext = fmt.extension();
                    opc.add_part_rel(
                        slide_part,
                        rel_types::IMAGE,
                        &format!("../media/image{global_img_idx}.{ext}"),
                    );
                    let media_part =
                        PartName::new(&format!("/ppt/media/image{global_img_idx}.{ext}"))?;
                    opc.add_part(&media_part, fmt.content_type(), data)?;
                    img_rids.push((rid, *x, *y, *cx, *cy));
                    global_img_idx += 1;
                }
            }

            let slide_xml = generate_slide_xml(slide, &img_rids);
            opc.add_part(slide_part, CT_SLIDE, &slide_xml)?;
        }

        opc.finish()?;
        Ok(())
    }
}

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

// ---------------------------------------------------------------------------
// XML generation helpers
// ---------------------------------------------------------------------------

fn write_decl(w: &mut Writer<Vec<u8>>) {
    w.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), Some("yes"))))
        .expect("write decl");
}

fn write_text_element(w: &mut Writer<Vec<u8>>, tag: &str, text: &str) {
    w.write_event(Event::Start(BytesStart::new(tag)))
        .expect("write start");
    w.write_event(Event::Text(BytesText::new(text)))
        .expect("write text");
    w.write_event(Event::End(BytesEnd::new(tag)))
        .expect("write end");
}

fn write_empty(w: &mut Writer<Vec<u8>>, tag: &str) {
    w.write_event(Event::Empty(BytesStart::new(tag)))
        .expect("write empty");
}

fn pml_root(tag: &str) -> BytesStart<'_> {
    let mut elem = BytesStart::new(tag);
    elem.push_attribute(("xmlns:p", NS_PML));
    elem.push_attribute(("xmlns:a", NS_DML));
    elem.push_attribute(("xmlns:r", NS_REL));
    elem
}

fn write_nv_grp_sp_pr(w: &mut Writer<Vec<u8>>) {
    w.write_event(Event::Start(BytesStart::new("p:nvGrpSpPr")))
        .expect("write");
    let mut cnv_pr = BytesStart::new("p:cNvPr");
    cnv_pr.push_attribute(("id", "1"));
    cnv_pr.push_attribute(("name", ""));
    w.write_event(Event::Empty(cnv_pr)).expect("write");
    write_empty(w, "p:cNvGrpSpPr");
    write_empty(w, "p:nvPr");
    w.write_event(Event::End(BytesEnd::new("p:nvGrpSpPr")))
        .expect("write");
}

// Write a DrawingML run (<a:r>) with optional rPr.
fn write_dml_run(w: &mut Writer<Vec<u8>>, run: &Run) {
    w.write_event(Event::Start(BytesStart::new("a:r")))
        .expect("write");

    if run.has_rpr() {
        let mut rpr = BytesStart::new("a:rPr");
        rpr.push_attribute(("lang", "en-US"));
        rpr.push_attribute(("dirty", "0"));
        if run.bold {
            rpr.push_attribute(("b", "1"));
        }
        if run.italic {
            rpr.push_attribute(("i", "1"));
        }
        if run.underline {
            rpr.push_attribute(("u", "sng"));
        }
        if run.strikethrough {
            rpr.push_attribute(("strike", "sngStrike"));
        }
        if let Some(pt) = run.font_size_pt {
            // DrawingML stores size in hundredths of a point
            let hundredths = (pt * 100.0).round() as u32;
            rpr.push_attribute(("sz", hundredths.to_string().as_str()));
        }

        if run.color.is_some() || run.font_name.is_some() {
            w.write_event(Event::Start(rpr)).expect("write rPr start");

            if let Some(ref hex) = run.color {
                w.write_event(Event::Start(BytesStart::new("a:solidFill")))
                    .expect("write");
                let mut clr = BytesStart::new("a:srgbClr");
                clr.push_attribute(("val", hex.as_str()));
                w.write_event(Event::Empty(clr)).expect("write");
                w.write_event(Event::End(BytesEnd::new("a:solidFill")))
                    .expect("write");
            }

            if let Some(ref name) = run.font_name {
                let mut latin = BytesStart::new("a:latin");
                latin.push_attribute(("typeface", name.as_str()));
                w.write_event(Event::Empty(latin)).expect("write");
            }

            w.write_event(Event::End(BytesEnd::new("a:rPr")))
                .expect("write rPr end");
        } else {
            w.write_event(Event::Empty(rpr)).expect("write rPr empty");
        }
    }

    write_text_element(w, "a:t", &run.text);
    w.write_event(Event::End(BytesEnd::new("a:r")))
        .expect("write");
}

// ---------------------------------------------------------------------------
// presentation.xml
// ---------------------------------------------------------------------------

fn generate_presentation_xml(slide_count: usize, cx: u64, cy: u64) -> Vec<u8> {
    let mut w = Writer::new(Vec::new());
    write_decl(&mut w);

    w.write_event(Event::Start(pml_root("p:presentation")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:sldMasterIdLst")))
        .expect("write");
    let mut master_id = BytesStart::new("p:sldMasterId");
    master_id.push_attribute(("id", "2147483648"));
    master_id.push_attribute(("r:id", "rId1"));
    w.write_event(Event::Empty(master_id)).expect("write");
    w.write_event(Event::End(BytesEnd::new("p:sldMasterIdLst")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:sldIdLst")))
        .expect("write");
    for i in 0..slide_count {
        let slide_id_val = 256 + i as u32;
        let r_id = format!("rId{}", i + 2);
        let mut slide_id = BytesStart::new("p:sldId");
        slide_id.push_attribute(("id", slide_id_val.to_string().as_str()));
        slide_id.push_attribute(("r:id", r_id.as_str()));
        w.write_event(Event::Empty(slide_id)).expect("write");
    }
    w.write_event(Event::End(BytesEnd::new("p:sldIdLst")))
        .expect("write");

    let mut sld_sz = BytesStart::new("p:sldSz");
    sld_sz.push_attribute(("cx", cx.to_string().as_str()));
    sld_sz.push_attribute(("cy", cy.to_string().as_str()));
    w.write_event(Event::Empty(sld_sz)).expect("write");

    w.write_event(Event::End(BytesEnd::new("p:presentation")))
        .expect("write");
    w.into_inner()
}

// ---------------------------------------------------------------------------
// slideMasters/slideMaster1.xml
// ---------------------------------------------------------------------------

fn generate_slide_master_xml() -> Vec<u8> {
    let mut w = Writer::new(Vec::new());
    write_decl(&mut w);

    w.write_event(Event::Start(pml_root("p:sldMaster")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:cSld")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:spTree")))
        .expect("write");
    write_nv_grp_sp_pr(&mut w);
    write_empty(&mut w, "p:grpSpPr");
    w.write_event(Event::End(BytesEnd::new("p:spTree")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:cSld")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:sldLayoutIdLst")))
        .expect("write");
    let mut layout_id = BytesStart::new("p:sldLayoutId");
    layout_id.push_attribute(("id", "2147483649"));
    layout_id.push_attribute(("r:id", "rId1"));
    w.write_event(Event::Empty(layout_id)).expect("write");
    w.write_event(Event::End(BytesEnd::new("p:sldLayoutIdLst")))
        .expect("write");

    w.write_event(Event::End(BytesEnd::new("p:sldMaster")))
        .expect("write");
    w.into_inner()
}

// ---------------------------------------------------------------------------
// slideLayouts/slideLayout1.xml
// ---------------------------------------------------------------------------

fn generate_slide_layout_xml() -> Vec<u8> {
    let mut w = Writer::new(Vec::new());
    write_decl(&mut w);

    let mut root = pml_root("p:sldLayout");
    root.push_attribute(("type", "blank"));
    w.write_event(Event::Start(root)).expect("write");
    w.write_event(Event::Start(BytesStart::new("p:cSld")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:spTree")))
        .expect("write");
    write_nv_grp_sp_pr(&mut w);
    write_empty(&mut w, "p:grpSpPr");
    w.write_event(Event::End(BytesEnd::new("p:spTree")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:cSld")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:sldLayout")))
        .expect("write");
    w.into_inner()
}

// ---------------------------------------------------------------------------
// slides/slideN.xml
// ---------------------------------------------------------------------------

fn generate_slide_xml(slide: &SlideData, img_rids: &[(String, i64, i64, u64, u64)]) -> Vec<u8> {
    let mut w = Writer::new(Vec::new());
    write_decl(&mut w);

    w.write_event(Event::Start(pml_root("p:sld")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:cSld")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:spTree")))
        .expect("write");

    write_nv_grp_sp_pr(&mut w);
    write_empty(&mut w, "p:grpSpPr");

    let mut next_id: u32 = 2;

    if let Some(ref title) = slide.title {
        write_title_shape(&mut w, next_id, title);
        next_id += 1;
    }

    if slide.has_placeholder_body() {
        let placeholder_items: Vec<&BodyItem> = slide
            .body_items
            .iter()
            .filter(|i| !matches!(i, BodyItem::TextBox(..) | BodyItem::Image(..)))
            .collect();
        write_body_shape(&mut w, next_id, &placeholder_items);
        next_id += 1;
    }

    // Free-floating text boxes
    for item in &slide.body_items {
        if let BodyItem::TextBox(runs, x, y, cx, cy) = item {
            write_text_box_shape(&mut w, next_id, runs, *x, *y, *cx, *cy);
            next_id += 1;
        }
    }

    // Embedded images
    for (rid, x, y, cx, cy) in img_rids {
        write_pic_shape(&mut w, next_id, rid, *x, *y, *cx, *cy);
        next_id += 1;
    }

    w.write_event(Event::End(BytesEnd::new("p:spTree")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:cSld")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:sld")))
        .expect("write");

    w.into_inner()
}

fn write_title_shape(w: &mut Writer<Vec<u8>>, id: u32, title: &str) {
    let id_str = id.to_string();
    w.write_event(Event::Start(BytesStart::new("p:sp")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:nvSpPr")))
        .expect("write");
    let mut cnv_pr = BytesStart::new("p:cNvPr");
    cnv_pr.push_attribute(("id", id_str.as_str()));
    cnv_pr.push_attribute(("name", "Title 1"));
    w.write_event(Event::Empty(cnv_pr)).expect("write");
    w.write_event(Event::Start(BytesStart::new("p:cNvSpPr")))
        .expect("write");
    let mut locks = BytesStart::new("a:spLocks");
    locks.push_attribute(("noGrp", "1"));
    w.write_event(Event::Empty(locks)).expect("write");
    w.write_event(Event::End(BytesEnd::new("p:cNvSpPr")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:nvPr")))
        .expect("write");
    let mut ph = BytesStart::new("p:ph");
    ph.push_attribute(("type", "title"));
    w.write_event(Event::Empty(ph)).expect("write");
    w.write_event(Event::End(BytesEnd::new("p:nvPr")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:nvSpPr")))
        .expect("write");

    write_empty(w, "p:spPr");

    w.write_event(Event::Start(BytesStart::new("p:txBody")))
        .expect("write");
    write_empty(w, "a:bodyPr");
    write_plain_paragraph(w, title);
    w.write_event(Event::End(BytesEnd::new("p:txBody")))
        .expect("write");

    w.write_event(Event::End(BytesEnd::new("p:sp")))
        .expect("write");
}

fn write_body_shape(w: &mut Writer<Vec<u8>>, id: u32, items: &[&BodyItem]) {
    let id_str = id.to_string();
    w.write_event(Event::Start(BytesStart::new("p:sp")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:nvSpPr")))
        .expect("write");
    let mut cnv_pr = BytesStart::new("p:cNvPr");
    cnv_pr.push_attribute(("id", id_str.as_str()));
    cnv_pr.push_attribute(("name", "Body 2"));
    w.write_event(Event::Empty(cnv_pr)).expect("write");
    w.write_event(Event::Start(BytesStart::new("p:cNvSpPr")))
        .expect("write");
    let mut locks = BytesStart::new("a:spLocks");
    locks.push_attribute(("noGrp", "1"));
    w.write_event(Event::Empty(locks)).expect("write");
    w.write_event(Event::End(BytesEnd::new("p:cNvSpPr")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("p:nvPr")))
        .expect("write");
    let mut ph = BytesStart::new("p:ph");
    ph.push_attribute(("type", "body"));
    ph.push_attribute(("idx", "1"));
    w.write_event(Event::Empty(ph)).expect("write");
    w.write_event(Event::End(BytesEnd::new("p:nvPr")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:nvSpPr")))
        .expect("write");

    write_empty(w, "p:spPr");

    w.write_event(Event::Start(BytesStart::new("p:txBody")))
        .expect("write");
    write_empty(w, "a:bodyPr");

    for item in items {
        match item {
            BodyItem::Text(text) => write_plain_paragraph(w, text),
            BodyItem::RichText(runs) => write_rich_paragraph(w, runs),
            BodyItem::BulletList(bullets) => {
                for bullet in bullets {
                    write_bullet_paragraph(w, bullet);
                }
            },
            BodyItem::TextBox(..) | BodyItem::Image(..) => {}, // handled separately
        }
    }

    w.write_event(Event::End(BytesEnd::new("p:txBody")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:sp")))
        .expect("write");
}

fn write_text_box_shape(
    w: &mut Writer<Vec<u8>>,
    id: u32,
    runs: &[Run],
    x: i64,
    y: i64,
    cx: i64,
    cy: i64,
) {
    let id_str = id.to_string();
    let name = format!("TextBox {id}");

    w.write_event(Event::Start(BytesStart::new("p:sp")))
        .expect("write");

    // nvSpPr — non-visual properties (txBox=1 = free-floating text box)
    w.write_event(Event::Start(BytesStart::new("p:nvSpPr")))
        .expect("write");
    let mut cnv_pr = BytesStart::new("p:cNvPr");
    cnv_pr.push_attribute(("id", id_str.as_str()));
    cnv_pr.push_attribute(("name", name.as_str()));
    w.write_event(Event::Empty(cnv_pr)).expect("write");
    let mut cnv_sp_pr = BytesStart::new("p:cNvSpPr");
    cnv_sp_pr.push_attribute(("txBox", "1"));
    w.write_event(Event::Empty(cnv_sp_pr)).expect("write");
    write_empty(w, "p:nvPr");
    w.write_event(Event::End(BytesEnd::new("p:nvSpPr")))
        .expect("write");

    // spPr — shape properties with position and size
    w.write_event(Event::Start(BytesStart::new("p:spPr")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("a:xfrm")))
        .expect("write");
    let mut off = BytesStart::new("a:off");
    off.push_attribute(("x", x.to_string().as_str()));
    off.push_attribute(("y", y.to_string().as_str()));
    w.write_event(Event::Empty(off)).expect("write");
    let mut ext = BytesStart::new("a:ext");
    ext.push_attribute(("cx", cx.to_string().as_str()));
    ext.push_attribute(("cy", cy.to_string().as_str()));
    w.write_event(Event::Empty(ext)).expect("write");
    w.write_event(Event::End(BytesEnd::new("a:xfrm")))
        .expect("write");

    let mut geom = BytesStart::new("a:prstGeom");
    geom.push_attribute(("prst", "rect"));
    w.write_event(Event::Start(geom)).expect("write");
    write_empty(w, "a:avLst");
    w.write_event(Event::End(BytesEnd::new("a:prstGeom")))
        .expect("write");

    w.write_event(Event::End(BytesEnd::new("p:spPr")))
        .expect("write");

    // txBody
    w.write_event(Event::Start(BytesStart::new("p:txBody")))
        .expect("write");
    let mut body_pr = BytesStart::new("a:bodyPr");
    body_pr.push_attribute(("wrap", "square"));
    w.write_event(Event::Empty(body_pr)).expect("write");
    write_rich_paragraph(w, runs);
    w.write_event(Event::End(BytesEnd::new("p:txBody")))
        .expect("write");

    w.write_event(Event::End(BytesEnd::new("p:sp")))
        .expect("write");
}

fn write_pic_shape(w: &mut Writer<Vec<u8>>, id: u32, rid: &str, x: i64, y: i64, cx: u64, cy: u64) {
    let id_str = id.to_string();
    let name = format!("Image {id}");

    w.write_event(Event::Start(BytesStart::new("p:pic")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:nvPicPr")))
        .expect("write");
    let mut cnv_pr = BytesStart::new("p:cNvPr");
    cnv_pr.push_attribute(("id", id_str.as_str()));
    cnv_pr.push_attribute(("name", name.as_str()));
    w.write_event(Event::Empty(cnv_pr)).expect("write");
    write_empty(w, "p:cNvPicPr");
    write_empty(w, "p:nvPr");
    w.write_event(Event::End(BytesEnd::new("p:nvPicPr")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:blipFill")))
        .expect("write");
    let mut blip = BytesStart::new("a:blip");
    blip.push_attribute(("r:embed", rid));
    w.write_event(Event::Empty(blip)).expect("write");
    w.write_event(Event::Start(BytesStart::new("a:stretch")))
        .expect("write");
    write_empty(w, "a:fillRect");
    w.write_event(Event::End(BytesEnd::new("a:stretch")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:blipFill")))
        .expect("write");

    w.write_event(Event::Start(BytesStart::new("p:spPr")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("a:xfrm")))
        .expect("write");
    let mut off = BytesStart::new("a:off");
    off.push_attribute(("x", x.to_string().as_str()));
    off.push_attribute(("y", y.to_string().as_str()));
    w.write_event(Event::Empty(off)).expect("write");
    let mut ext = BytesStart::new("a:ext");
    ext.push_attribute(("cx", cx.to_string().as_str()));
    ext.push_attribute(("cy", cy.to_string().as_str()));
    w.write_event(Event::Empty(ext)).expect("write");
    w.write_event(Event::End(BytesEnd::new("a:xfrm")))
        .expect("write");
    let mut geom = BytesStart::new("a:prstGeom");
    geom.push_attribute(("prst", "rect"));
    w.write_event(Event::Start(geom)).expect("write");
    write_empty(w, "a:avLst");
    w.write_event(Event::End(BytesEnd::new("a:prstGeom")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("p:spPr")))
        .expect("write");

    w.write_event(Event::End(BytesEnd::new("p:pic")))
        .expect("write");
}

fn write_plain_paragraph(w: &mut Writer<Vec<u8>>, text: &str) {
    w.write_event(Event::Start(BytesStart::new("a:p")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("a:r")))
        .expect("write");
    write_text_element(w, "a:t", text);
    w.write_event(Event::End(BytesEnd::new("a:r")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("a:p")))
        .expect("write");
}

fn write_rich_paragraph(w: &mut Writer<Vec<u8>>, runs: &[Run]) {
    w.write_event(Event::Start(BytesStart::new("a:p")))
        .expect("write");
    for run in runs {
        write_dml_run(w, run);
    }
    w.write_event(Event::End(BytesEnd::new("a:p")))
        .expect("write");
}

fn write_bullet_paragraph(w: &mut Writer<Vec<u8>>, text: &str) {
    w.write_event(Event::Start(BytesStart::new("a:p")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("a:pPr")))
        .expect("write");
    let mut bu = BytesStart::new("a:buChar");
    bu.push_attribute(("char", "\u{2022}"));
    w.write_event(Event::Empty(bu)).expect("write");
    w.write_event(Event::End(BytesEnd::new("a:pPr")))
        .expect("write");
    w.write_event(Event::Start(BytesStart::new("a:r")))
        .expect("write");
    write_text_element(w, "a:t", text);
    w.write_event(Event::End(BytesEnd::new("a:r")))
        .expect("write");
    w.write_event(Event::End(BytesEnd::new("a:p")))
        .expect("write");
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pptx::PptxDocument;
    use std::io::Cursor;

    fn roundtrip(writer: PptxWriter) -> PptxDocument {
        let mut buf = Cursor::new(Vec::new());
        writer.write_to(&mut buf).unwrap();
        buf.set_position(0);
        PptxDocument::from_reader(buf).unwrap()
    }

    #[test]
    fn rich_runs_roundtrip() {
        let mut writer = PptxWriter::new();
        writer
            .add_slide()
            .set_title("Test")
            .add_rich_text(&[Run::new("Bold").bold(), Run::new(" red").color("FF0000")]);
        let doc = roundtrip(writer);
        let text = doc.plain_text();
        assert!(text.contains("Bold"));
        assert!(text.contains("red"));
    }

    #[test]
    fn text_box_roundtrip() {
        let mut writer = PptxWriter::new();
        writer
            .add_slide()
            .add_text_box("Floating note", 1_000_000, 5_000_000, 3_000_000, 500_000);
        let doc = roundtrip(writer);
        let text = doc.plain_text();
        assert!(text.contains("Floating note"));
    }

    #[test]
    fn set_presentation_size_written() {
        let mut writer = PptxWriter::new();
        writer.set_presentation_size(9_144_000, 6_858_000);
        writer.add_slide().add_text("test");
        let mut buf = Cursor::new(Vec::new());
        writer.write_to(&mut buf).unwrap();
        let bytes = buf.into_inner();
        let cursor = Cursor::new(bytes.clone());
        let mut zip = zip::ZipArchive::new(cursor).unwrap();
        let mut entry = zip.by_name("ppt/presentation.xml").unwrap();
        let mut xml = String::new();
        std::io::Read::read_to_string(&mut entry, &mut xml).unwrap();
        assert!(xml.contains("cx=\"9144000\""), "expected cx in presentation.xml");
    }

    #[test]
    fn add_image_embeds_media_part() {
        use crate::ir::ImageFormat;
        // Minimal 1x1 PNG
        let png_bytes: Vec<u8> = vec![
            0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
            0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, // IHDR length + type
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1x1
            0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, // bit depth, color, crc
            0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, // IDAT
            0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2, 0x21,
            0xbc, 0x33, // crc
            0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, // IEND
        ];
        let mut writer = PptxWriter::new();
        writer
            .add_slide()
            .add_image(png_bytes, ImageFormat::Png, 0, 0, 3_000_000, 2_000_000);
        let mut buf = Cursor::new(Vec::new());
        writer.write_to(&mut buf).unwrap();
        let bytes = buf.into_inner();
        let cursor = Cursor::new(bytes);
        let mut zip = zip::ZipArchive::new(cursor).unwrap();
        assert!(zip.by_name("ppt/media/image1.png").is_ok(), "media part missing");
    }

    #[test]
    fn rich_text_box_roundtrip() {
        let mut writer = PptxWriter::new();
        writer.add_slide().add_rich_text_box(
            &[
                Run::new("Big").font_size(24.0).bold(),
                Run::new(" label").italic(),
            ],
            500_000,
            500_000,
            4_000_000,
            800_000,
        );
        let doc = roundtrip(writer);
        let text = doc.plain_text();
        assert!(text.contains("Big"));
        assert!(text.contains("label"));
    }
}