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
mod parse;
mod parse_accum;
mod xml_capture;
mod xml_gen;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_add_api;
#[cfg(test)]
mod tests_enhanced;
use crate::enums::shapes::MsoAutoShapeType;
use crate::enums::shapes::MsoConnectorType;
use crate::error::{PptxError, PptxResult};
use crate::shapes::Shape;
use crate::units::{Emu, ShapeId};
pub(crate) use xml_gen::shape_name_for_prst;
/// A collection of shapes parsed from a slide's `<p:spTree>` element.
#[derive(Debug, Clone, Default)]
pub struct ShapeTree {
pub shapes: Vec<Shape>,
/// When enabled, `insert_shape_xml()` skips re-parsing the full XML tree
/// and directly appends before the closing `</p:spTree>` tag. This is a
/// performance optimization for bulk shape additions.
turbo_add_enabled: bool,
}
impl ShapeTree {
/// Parse shapes from slide XML (the full `<p:sld>` or similar element).
///
/// Extracts all shape elements from the `<p:spTree>` within `<p:cSld>`.
///
/// # Errors
///
/// Returns `PptxError` if the XML cannot be parsed.
pub fn from_slide_xml(xml: &[u8]) -> PptxResult<Self> {
let shapes = parse::parse_shapes_from_slide_xml(xml)?;
Ok(Self {
shapes,
turbo_add_enabled: false,
})
}
/// Iterate over all shapes.
pub fn iter(&self) -> impl Iterator<Item = &Shape> {
self.shapes.iter()
}
/// Number of shapes.
#[must_use]
pub fn len(&self) -> usize {
self.shapes.len()
}
/// Whether the shape tree is empty.
#[must_use]
pub fn is_empty(&self) -> bool {
self.shapes.is_empty()
}
/// Get whether turbo add mode is enabled.
#[must_use]
pub const fn turbo_add_enabled(&self) -> bool {
self.turbo_add_enabled
}
/// Set whether turbo add mode is enabled.
///
/// When enabled, `insert_shape_xml()` skips validation/re-parsing and
/// directly appends before the closing `</p:spTree>` tag.
pub fn set_turbo_add_enabled(&mut self, enabled: bool) {
self.turbo_add_enabled = enabled;
}
/// Find the maximum shape ID currently in use.
#[must_use]
pub fn max_shape_id(&self) -> ShapeId {
self.shapes
.iter()
.map(super::Shape::shape_id)
.max()
.unwrap_or(ShapeId(0))
}
/// Count how many existing shapes have a name starting with the given prefix.
///
/// Used to generate auto-incremented shape names like "Rectangle 3".
fn count_shapes_with_prefix(&self, prefix: &str) -> u32 {
let count = self
.shapes
.iter()
.filter(|s| s.name().starts_with(prefix))
.count();
// usize→u32: shape count will never exceed u32::MAX in practice
u32::try_from(count).unwrap_or(u32::MAX)
}
/// Add an auto shape with preset geometry to the slide XML.
///
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_shape(
slide_xml: &[u8],
auto_shape_type: MsoAutoShapeType,
left: Emu,
top: Emu,
width: Emu,
height: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let prst = auto_shape_type.to_xml_str();
let base_name = shape_name_for_prst(prst);
let count = tree.count_shapes_with_prefix(base_name) + 1;
let name = format!("{base_name} {count}");
let xml = Self::new_autoshape_xml(shape_id, &name, left, top, width, height, prst);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Add a textbox shape to the slide XML.
///
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_textbox(
slide_xml: &[u8],
left: Emu,
top: Emu,
width: Emu,
height: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let count = tree.count_shapes_with_prefix("TextBox") + 1;
let name = format!("TextBox {count}");
let xml = Self::new_textbox_xml(shape_id, &name, left, top, width, height);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Add a picture shape to the slide XML.
///
/// `image_r_id` is the relationship ID linking the slide to the image part.
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_picture(
slide_xml: &[u8],
image_r_id: &str,
left: Emu,
top: Emu,
width: Emu,
height: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let count = tree.count_shapes_with_prefix("Picture") + 1;
let name = format!("Picture {count}");
let xml = Self::new_picture_xml(shape_id, &name, "", image_r_id, left, top, width, height);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Add a table to the slide XML.
///
/// Creates a `<p:graphicFrame>` containing a table with the given number of rows and columns.
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_table(
slide_xml: &[u8],
rows: u32,
cols: u32,
left: Emu,
top: Emu,
width: Emu,
height: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let count = tree.count_shapes_with_prefix("Table") + 1;
let name = format!("Table {count}");
let xml = Self::new_table_xml(shape_id, &name, rows, cols, left, top, width, height);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Add a connector shape to the slide XML.
///
/// The connector is placed using begin/end coordinates. The method computes
/// the bounding box (left, top, width, height) and flip flags from the coordinates.
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_connector(
slide_xml: &[u8],
connector_type: MsoConnectorType,
begin_x: Emu,
begin_y: Emu,
end_x: Emu,
end_y: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let count = tree.count_shapes_with_prefix("Connector") + 1;
let name = format!("Connector {count}");
let prst = connector_type.to_xml_str();
// Compute bounding box and flip flags from begin/end coordinates
let (left, width, flip_h) = if begin_x.0 <= end_x.0 {
(begin_x, Emu(end_x.0 - begin_x.0), false)
} else {
(end_x, Emu(begin_x.0 - end_x.0), true)
};
let (top, height, flip_v) = if begin_y.0 <= end_y.0 {
(begin_y, Emu(end_y.0 - begin_y.0), false)
} else {
(end_y, Emu(begin_y.0 - end_y.0), true)
};
let xml = Self::new_connector_xml_with_flip(
shape_id, &name, left, top, width, height, prst, flip_h, flip_v,
);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Add an empty group shape to the slide XML.
///
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_group_shape(
slide_xml: &[u8],
left: Emu,
top: Emu,
width: Emu,
height: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let count = tree.count_shapes_with_prefix("Group") + 1;
let name = format!("Group {count}");
let xml = Self::new_group_shape_xml(shape_id, &name, left, top, width, height);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Insert a shape XML fragment into an existing slide XML blob.
///
/// Inserts the given shape XML as a child of `<p:spTree>`, just before
/// the closing `</p:spTree>` tag.
pub(crate) fn insert_shape_xml(slide_xml: &[u8], shape_xml: &str) -> PptxResult<Vec<u8>> {
let slide_str = String::from_utf8_lossy(slide_xml).to_string();
slide_str.find("</p:spTree>").map_or_else(
|| {
Err(PptxError::InvalidXml(
"slide XML does not contain </p:spTree>".to_string(),
))
},
|pos| {
let mut updated = String::with_capacity(slide_str.len() + shape_xml.len());
updated.push_str(&slide_str[..pos]);
updated.push_str(shape_xml);
updated.push_str(&slide_str[pos..]);
Ok(updated.into_bytes())
},
)
}
/// Add a movie (video) shape to the slide XML.
///
/// `video_r_id` is the relationship ID for the external video link.
/// `poster_r_id` is the relationship ID for the embedded poster frame image.
/// Auto-assigns `shape_id` and name. Returns the updated slide XML bytes.
///
/// # Errors
///
/// Returns `PptxError` if the slide XML cannot be parsed or modified.
pub fn add_movie(
slide_xml: &[u8],
video_r_id: &str,
poster_r_id: &str,
left: Emu,
top: Emu,
width: Emu,
height: Emu,
) -> PptxResult<Vec<u8>> {
let tree = Self::from_slide_xml(slide_xml)?;
let shape_id = ShapeId(tree.max_shape_id().0 + 1);
let count = tree.count_shapes_with_prefix("Movie") + 1;
let name = format!("Movie {count}");
let xml = Self::new_movie_xml(
shape_id,
&name,
video_r_id,
poster_r_id,
left,
top,
width,
height,
);
Self::insert_shape_xml(slide_xml, &xml)
}
/// Return the first shape that is a title placeholder.
///
/// Looks for placeholders with type "title" or `"ctrTitle"`.
#[must_use]
pub fn title(&self) -> Option<&Shape> {
self.shapes.iter().find(|s| match s {
Shape::AutoShape(a) => a
.placeholder
.as_ref()
.is_some_and(super::placeholder::PlaceholderFormat::is_title),
Shape::Picture(p) => p
.placeholder
.as_ref()
.is_some_and(super::placeholder::PlaceholderFormat::is_title),
Shape::GraphicFrame(g) => g
.placeholder
.as_ref()
.is_some_and(super::placeholder::PlaceholderFormat::is_title),
_ => false,
})
}
/// Return all shapes that are placeholders.
#[must_use]
pub fn placeholders(&self) -> Vec<&Shape> {
self.shapes.iter().filter(|s| s.is_placeholder()).collect()
}
}