diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 2792508ba..5736b1778 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -59,7 +59,10 @@ rectangle. PowerPoint 95 measures angles counter-clockwise, DrawingML clockwise, negated. A shape's geometry holds its outline as drawn, quarter-turns and mirror included, so its angle and flips come from there (a box turned by an odd number of quarter-turns is turned back); the rectangle, rounded rectangle and ellipse take the angle the user set. A shape that draws -nothing but text is a text box. Groups and freeforms are skipped. Pictures, notes and the master's text styles come later. +nothing but text is a text box. Freeforms read as custom paths through their points, in their +box, with their format's fill, line and shadow, and open ones with their arrowheads. Groups read as +groups of their members, which keep their places on the slide (PowerPoint 95 can't turn or flip +a group), nested up to 32 deep. Pictures, notes and the master's text styles come later. The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: its layouts and placeholders. The file's masters then place and style the placeholders that diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 005ab7955..797c68e3a 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -7,18 +7,33 @@ //! //! Read so far: the slide size, the masters with their colour schemes and backgrounds, and the //! slides in order with their master, layout type and background, holding their placeholders, text -//! boxes, shapes and lines, with the text and its character and paragraph formatting ([`text`]). +//! boxes, shapes, lines, freeforms and groups, with the text and its character and paragraph +//! formatting ([`text`]). //! //! A page's object list (3000) holds shapes (3008), placeholders (3010, which add a 3011 atom: the -//! type, the size, then the index) and lines (3014). A shape or placeholder has its geometry -//! (3009): the shape code (its low byte; the byte above orients the outline) and its adjust value, -//! the box as left, top, right and bottom in master units (576 per inch) measured from the slide's -//! centre, then what is left of the angle after whole quarter-turns, in sixteenths of a degree, -//! counter-clockwise. A line holds 3015: its start and end points, in the same units, and 3007: -//! its arrowheads. Shapes and lines have a format (3005) with their fill, line width, dashes and -//! colour, and shadow with its offset ([`shape`]). The 24 shapes of the object model read as -//! DrawingML presets, turned and flipped as drawn; a code no probe showed is a rectangle. A shape -//! that draws nothing but its text is a text box. +//! type, the size, then the index), lines (3014), freeforms (3016) and groups (3001). A shape or +//! placeholder has its geometry (3009): the shape code (its low byte; the byte above orients the +//! outline) and its adjust value, the box as left, top, right and bottom in master units (576 per +//! inch) measured from the slide's centre, then what is left of the angle after whole +//! quarter-turns, in sixteenths of a degree, counter-clockwise. A line holds 3015: its start and +//! end points, in the same units, and 3007: its arrowheads. Shapes and lines have a format (3005) +//! with their fill, line width, dashes and colour, and shadow with its offset ([`shape`]). The 24 +//! shapes of the object model read as DrawingML presets, turned and flipped as drawn; a code no +//! probe showed is a rectangle. A shape that draws nothing but its text is a text box. +//! +//! A freeform holds 3017: its box (left, top, right, bottom, as a shape's), the same box again, +//! the point count and, in its low byte, 1 when it is closed; 3007, its arrowheads; its format; and +//! 3035, its points: a u16 count, then x and y as i32s, in master units from the slide's centre. A +//! closed freeform leaves out the point that repeats its first. It reads as a custom path in its +//! box ([`shape::freeform_path`]). The format's angle is not read for freeforms: no probe turned or +//! flipped one, and the two boxes of 3017 matched in every file PowerPoint 95 wrote. +//! +//! A group (3001) holds a 3002 atom and a list (2000) whose count (2001) is followed by its +//! members, read as the page's objects are, groups included. Its members keep their places on the +//! slide; the group has no box or transform of its own (PowerPoint 95 can't turn or flip one), so +//! it reads as a group whose box is the union of its members' and whose child space is that same +//! box. Groups deeper than [`MAX_DEPTH`] are left out, and members count towards the page's object +//! cap. //! //! PowerPoint 95 numbers placeholders its own way: on the master 1 title, 2 body, 6 date, 7 slide //! number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred title and 0x10 subtitle. A @@ -26,16 +41,15 @@ //! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path //! does. //! -//! Not read yet: groups and freeforms, which are skipped; pictures; notes; and the master's text -//! styles, so the levels of the default master's styles stay as they are (the slide text carries -//! its own formatting in full). +//! Not read yet: pictures; notes; and the master's text styles, so the levels of the default +//! master's styles stay as they are (the slide text carries its own formatting in full). use std::collections::{HashMap, HashSet}; use std::sync::Arc; use craft_pptx::{ - Background, ColorRef, Defaults, Effects, Fill, Geom, LayoutType, Line, Master, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, Size, - Slide, SlideId, TextBody, Xfrm, + Background, ColorRef, Defaults, Effects, Fill, Geom, LayoutType, Line, Master, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, + ShapeKind, Size, Slide, SlideId, TextBody, Xfrm, }; use crate::convert::{Scheme, layout_kind, layout_table, page_side, place_placeholder, same_family, scheme_theme}; @@ -60,6 +74,7 @@ mod rt { pub const LIST: u32 = 2000; pub const COLOR_SCHEME: u32 = 2031; pub const OBJECTS: u32 = 3000; + pub const GROUP: u32 = 3001; pub const FORMAT: u32 = 3005; pub const SHAPE: u32 = 3008; pub const GEOMETRY: u32 = 3009; @@ -68,6 +83,9 @@ mod rt { pub const LINE: u32 = 3014; pub const ARROWHEADS: u32 = 3007; pub const LINE_ATOM: u32 = 3015; + pub const FREEFORM: u32 = 3016; + pub const FREEFORM_ATOM: u32 = 3017; + pub const POINTS: u32 = 3035; pub const TEXT: u32 = 4001; } @@ -79,8 +97,13 @@ const MAX_SLIDES: usize = 1 << 16; /// Masters read at most. Each becomes a copy of the caller's default master with its layouts, so /// the cap is lower than for slides; PowerPoint 95 writes one. const MAX_MASTERS: usize = 256; -/// Objects read from one slide or master at most. +/// Objects read from one slide or master at most, group members included. const MAX_OBJECTS: usize = 1 << 14; +/// Groups nest at most this deep, as the PowerPoint 97 path's containers do; deeper ones are left +/// out, so a damaged file can't make the conversion recurse without bound. +const MAX_DEPTH: usize = crate::record::MAX_DEPTH; +/// Points read from one freeform at most, as for the PowerPoint 97 path's freeforms. +const MAX_POINTS: usize = 8192; /// Master units (576 per inch) per point. const MU: f64 = 8.0; /// A colour's fourth byte when the colour is the RGB given, not a scheme slot. @@ -239,17 +262,65 @@ struct Object { geom: Option, /// How a shape or line is drawn (a placeholder's is left to its layout). look: Look, - /// A line (3014), not a shape. - line: bool, + kind: Kind, } -/// The shapes, placeholders and lines of a page's object list. -fn objects<'a>(page: &Rec<'a>) -> impl Iterator> { - page.child(rt::OBJECTS) - .into_iter() - .flat_map(|l| l.children()) - .filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER | rt::LINE)) - .take(MAX_OBJECTS) +/// What an object is, beyond its box, text, geometry and look. +enum Kind { + /// A shape (3008) or placeholder (3010). + Shape, + /// A line (3014). + Line, + /// A freeform (3016). + Freeform, + /// A group (3001) and its members. + Group(Vec), +} + +/// Reads a page's objects, counting them against [`MAX_OBJECTS`] across its groups. +struct Reader<'e> { + env: &'e Env, + scheme: &'e Scheme, + size: Size, + /// Objects still to be read on this page. + left: usize, +} + +impl Reader<'_> { + /// The objects of a page's object list. + fn page(env: &Env, scheme: &Scheme, size: Size, page: &Rec) -> Vec { + let mut reader = Reader { env, scheme, size, left: MAX_OBJECTS }; + page.child(rt::OBJECTS).map(|l| reader.list(&l, 0)).unwrap_or_default() + } + + /// The shapes, placeholders, lines, freeforms and groups of a list `depth` groups down. + fn list(&mut self, list: &Rec, depth: usize) -> Vec { + let mut out = vec![]; + for r in list.children().filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER | rt::LINE | rt::FREEFORM | rt::GROUP)) { + let Some(left) = self.left.checked_sub(1) else { + log::warn!("ppt: a PowerPoint 95 page has more than {MAX_OBJECTS} objects; the rest are left out"); + break; + }; + self.left = left; + out.extend(match r.kind { + rt::GROUP => self.group(&r, depth), + rt::FREEFORM => freeform(&r, self.env, self.scheme, self.size), + _ => object(&r, self.env, self.scheme, self.size), + }); + } + out + } + + /// A group `depth` groups down, with its members read as the page's objects are. The walk + /// recurses once per group, so a group nested deeper than [`MAX_DEPTH`] is left out. + fn group(&mut self, r: &Rec, depth: usize) -> Option { + if depth >= MAX_DEPTH { + log::warn!("ppt: PowerPoint 95 groups nest deeper than {MAX_DEPTH}; the deeper ones are left out"); + return None; + } + let members = self.list(&r.child(rt::LIST)?, depth + 1); + Some(Object { placeholder: false, ph: None, xfrm: Xfrm::default(), text: None, geom: None, look: Look::none(), kind: Kind::Group(members) }) + } } /// A box from master units about the slide's centre (left, top, right, bottom, either way round) @@ -277,7 +348,38 @@ fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option { shape::arrowheads(&mut look.line, &heads); } let geom = Some(Geom::Preset { name: "line".into(), adj: vec![] }); - Some(Object { placeholder: false, ph: None, xfrm, text: None, geom, look, line: true }) + Some(Object { placeholder: false, ph: None, xfrm, text: None, geom, look, kind: Kind::Line }) +} + +/// A freeform: its points as a path in its box, drawn as its format says (1 pt in the scheme's +/// text and lines colour without one), with its arrowheads when it is open. One of fewer than two +/// points draws nothing and is left out; one flagged closed with fewer than three is drawn open. +fn freeform(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { + let a = r.child(rt::FREEFORM_ATOM)?; + let sides = [a.i32(0)?, a.i32(4)?, a.i32(8)?, a.i32(12)?]; + let points = r.child(rt::POINTS).map(|p| points(&p)).unwrap_or_default(); + if points.len() < 2 { + return None; + } + // Only the low byte is the flag: PowerPoint 95 leaves whatever was there in the bytes above. + let closed = a.u8(36) == Some(1) && points.len() >= 3; + let mut look = match r.child(rt::FORMAT) { + Some(f) => shape::look(&f, scheme), + None => Look { line: shape::line_of(scheme[1], None), ..Look::none() }, + }; + if let Some(heads) = r.child(rt::ARROWHEADS).filter(|_| !closed && look.line != Line::none()) { + shape::arrowheads(&mut look.line, &heads); + } + let geom = Some(shape::freeform_path(&points, sides, closed)); + let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), true)); + Some(Object { placeholder: false, ph: None, xfrm: xfrm_of(sides, size), text, geom, look, kind: Kind::Freeform }) +} + +/// A 3035 atom's points: a u16 count, then x and y as i32s. No more than the record holds, nor +/// than [`MAX_POINTS`]. +fn points(r: &Rec) -> Vec<(i32, i32)> { + let count = crate::record::u16_at(r.data, 0).map_or(0, usize::from); + (0..count.min(MAX_POINTS)).map_while(|i| Some((r.i32(2 + i * 8)?, r.i32(6 + i * 8)?))).collect() } /// A shape, placeholder or line: its box, its placeholder atom, its text, and a shape's preset and @@ -315,13 +417,16 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { look = shape::look(&f, scheme); } } - Some(Object { placeholder, ph, xfrm, text, geom, look, line: false }) + Some(Object { placeholder, ph, xfrm, text, geom, look, kind: Kind::Shape }) } /// An object as a shape: a placeholder of a known type; a text box when it draws nothing but its /// text; else a shape or line that draws something. One that draws nothing is left out. A /// placeholder of an unknown type keeps its text as a text box. fn shape(p: &mut Presentation, o: Object) -> Option { + if let Kind::Group(members) = o.kind { + return group(p, members); + } let Some(ph) = o.ph else { let text = o.text.filter(|t| !t.is_empty()); if text.is_some() && !o.look.drawn() { @@ -343,7 +448,11 @@ fn shape(p: &mut Presentation, o: Object) -> Option { let Look { fill, line, shadow, .. } = o.look; return Some(Shape { id: ShapeId(id), - name: if o.line { format!("Line {id}") } else { format!("Shape {id}") }, + name: match o.kind { + Kind::Line => format!("Line {id}"), + Kind::Freeform => format!("Freeform {id}"), + _ => format!("Shape {id}"), + }, xfrm: Some(o.xfrm), geom, fill: Some(fill), @@ -366,6 +475,38 @@ fn shape(p: &mut Presentation, o: Object) -> Option { Some(Shape { id: ShapeId(p.alloc_id()?), name: name.into(), xfrm: Some(o.xfrm), ph: Some(ph), text, ..Default::default() }) } +/// A group of the shapes its members are, in the box they span, which is also its child space, so +/// the members keep their places on the slide. A group none of whose members draws anything is +/// left out. +/// +/// A nested group recurses here directly, not through [`shape`], whose frame is far larger: the +/// recursion is bounded by [`MAX_DEPTH`], and each level should cost the stack little. +fn group(p: &mut Presentation, members: Vec) -> Option { + let id = p.alloc_id()?; + let mut children = Vec::with_capacity(members.len()); + for m in members { + let s = match m.kind { + Kind::Group(inner) => group(p, inner), + _ => shape(p, m), + }; + children.extend(s); + } + let mut boxes = children.iter().filter_map(|c| c.xfrm); + let first = boxes.next()?; + let (mut l, mut t, mut r, mut b) = (first.x, first.y, first.x + first.w, first.y + first.h); + for x in boxes { + (l, t, r, b) = (l.min(x.x), t.min(x.y), r.max(x.x + x.w), b.max(x.y + x.h)); + } + let xfrm = Xfrm::new(l, t, r - l, b - t); + Some(Shape { + id: ShapeId(id), + name: format!("Group {id}"), + xfrm: Some(xfrm), + kind: ShapeKind::Group { children, child: xfrm }, + ..Default::default() + }) +} + /// Build the presentation from a PowerPoint 95 Document container. pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let atom = document.child(rt::DOCUMENT_ATOM); @@ -399,7 +540,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { // The master's placeholders set where new slides' placeholders go: the first of each // family places the default master's. Its other objects are the master's own shapes. let mut placed: Vec = vec![]; - for o in objects(&m.rec).filter_map(|r| object(&r, &env, &scheme, size)) { + for o in Reader::page(&env, &scheme, size, &m.rec) { if o.placeholder { if let Some(kind) = o.ph.as_ref().map(|ph| ph.kind).filter(|k| !placed.iter().any(|d| same_family(*d, *k))) { placed.push(kind); @@ -432,7 +573,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let background = if s.follow_background { None } else { background(&s.rec, &scheme).map(|fill| Background::Fill { fill }) }; let Some(id) = p.alloc_id() else { break }; let mut shapes = vec![]; - for o in objects(&s.rec).filter_map(|r| object(&r, &env, &scheme, size)) { + for o in Reader::page(&env, &scheme, size, &s.rec) { shapes.extend(shape(&mut p, o)); } p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: true, ..Default::default() })); diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs index 01fccdb6e..ffdec1a66 100644 --- a/crates/ppt-binary/src/ppt95/shape.rs +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -24,7 +24,7 @@ //! rectangle, rounded rectangle and ellipse (codes −3 to −1, whose byte above is the sign) and //! placeholders take their angle from the format, and the quarter-turns from the difference //! ([`orient`]); flips don't change their outlines. A line's 3007 atom holds its arrowheads -//! ([`arrowheads`]). +//! ([`arrowheads`]). A freeform's points become a custom path in its box ([`freeform_path`]). use craft_pptx::style::{Dash, LineEnd, Shadow}; use craft_pptx::{ColorRef, ColorTransform, CustomPath, Fill, Geom, Line, Rgba, Xfrm}; @@ -193,6 +193,24 @@ fn trapezoid_top(adjust: Option) -> Geom { Geom::Custom { paths: vec![CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] } } +/// A freeform's points as a path in its box `sides` (left, top, right and bottom, either way +/// round), all in master units from the slide's centre: a move to the first point, lines to the +/// rest, and a close when `closed`. The path's size is the box's (at least one unit each way, so a +/// flat freeform still has a coordinate space), its points measured from the box's top left. +pub(super) fn freeform_path(points: &[(i32, i32)], [l, t, r, b]: [i32; 4], closed: bool) -> Geom { + let (left, top) = (f64::from(l.min(r)), f64::from(t.min(b))); + let (w, h) = ((f64::from(r) - f64::from(l)).abs().max(1.0), (f64::from(b) - f64::from(t)).abs().max(1.0)); + let mut d = String::new(); + for (i, &(x, y)) in points.iter().enumerate() { + let cmd = if i == 0 { "M" } else { " L" }; + d.push_str(&format!("{cmd} {} {}", f64::from(x) - left, f64::from(y) - top)); + } + if closed { + d.push_str(" Z"); + } + Geom::Custom { paths: vec![CustomPath { w, h, d, ..Default::default() }] } +} + /// The share of its square a balloon's body takes, from the top; the tail reaches the bottom. const BALLOON_BODY: f64 = 5.0 / 6.0; diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 04d103cb8..9d41014c1 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1270,6 +1270,227 @@ fn hostile_angles_never_panic() { } } +/// A freeform's 3017 atom: its box twice, the point count, and the closed flag in the low byte +/// of the last word, with something else above it. +fn freeform_atom(bx: [i32; 4], count: u32, closed: bool) -> Vec { + let mut b: Vec = bx.iter().chain(&bx).flat_map(|v| v.to_le_bytes()).collect(); + b.extend_from_slice(&count.to_le_bytes()); + b.extend_from_slice(&[u8::from(closed), 0xAD, 0xB3, 0x02]); + rec(rt::FREEFORM_ATOM, 0, 0, &b) +} + +/// A 3035 atom: `count`, then the points. +fn points_atom(count: u16, points: &[(i32, i32)]) -> Vec { + let mut b = count.to_le_bytes().to_vec(); + b.extend(points.iter().flat_map(|(x, y)| x.to_le_bytes().into_iter().chain(y.to_le_bytes()))); + rec(rt::POINTS, NONE, 0x1D, &b) +} + +/// A freeform (3016) in `bx` through `points`, closed or open, with its arrowheads and format. +fn freeform_95(bx: [i32; 4], points: &[(i32, i32)], closed: bool, heads: [u8; 2], f: Option) -> Vec { + let mut kids = vec![freeform_atom(bx, points.len() as u32, closed), rec(rt::ARROWHEADS, 0, 0, &heads)]; + kids.extend(f.map(format)); + kids.push(points_atom(points.len() as u16, points)); + container(rt::FREEFORM, 0x13, &kids) +} + +/// A group (3001) of `members`. +fn group_95(members: &[Vec]) -> Vec { + let mut list = vec![rec(2001, 0, 0, &(members.len() as u32).to_le_bytes())]; + list.extend_from_slice(members); + container(rt::GROUP, 0x13, &[rec(3002, 0, 0, &[0xD9, 0x8A, 0x06, 0x00]), container(rt::LIST, 0xF, &list)]) +} + +fn path_of(s: &Shape) -> (f64, f64, &str) { + let Geom::Custom { paths } = &s.geom else { panic!("{} is not a path", s.name) }; + (paths[0].w, paths[0].h, &paths[0].d) +} + +fn group_members(s: &Shape) -> &[Shape] { + let craft_pptx::ShapeKind::Group { children, child } = &s.kind else { panic!("{} is not a group", s.name) }; + assert_eq!(Some(*child), s.xfrm, "a group's child space is its own box"); + children +} + +/// The probes' open triangle and closed square, in master units from the slide's centre. +const TRIANGLE_BOX: [i32; 4] = [-2304, -1584, -1152, -432]; +const TRIANGLE: [(i32, i32); 3] = [(-2304, -1584), (-1152, -1584), (-1728, -432)]; +const SQUARE: [(i32, i32); 4] = [(-2304, -1584), (-1152, -1584), (-1152, -432), (-2304, -432)]; + +/// A freeform is a path through its points in its box: open, unfilled and with its arrowheads; +/// closed, filled and without them. +#[test] +fn freeforms_are_paths() { + let open = Format { fill: None, ..PLAIN }; + let p = deck_of( + vec![ + freeform_95(TRIANGLE_BOX, &TRIANGLE, false, [0, 4], Some(open)), + freeform_95(TRIANGLE_BOX, &SQUARE, true, [0, 4], Some(PLAIN)), + freeform_95(TRIANGLE_BOX, &TRIANGLE, false, [1, 0], None), + ], + &[], + ); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 3); + for f in s { + assert!(f.name.starts_with("Freeform"), "{}", f.name); + assert_eq!(boxed(f), (72.0, 72.0, 144.0, 144.0)); + } + assert_eq!(path_of(&s[0]), (1152.0, 1152.0, "M 0 0 L 1152 0 L 576 1152")); + assert_eq!(s[0].fill, Some(Fill::None)); + let line = s[0].line.clone().unwrap(); + assert_eq!((line.fill, line.head, line.tail.map(|t| t.kind)), (Some(Fill::solid(rgb(0, 0, 0))), None, Some("stealth".into()))); + + assert_eq!(path_of(&s[1]), (1152.0, 1152.0, "M 0 0 L 1152 0 L 1152 1152 L 0 1152 Z")); + assert_eq!(s[1].fill, Some(Fill::solid(rgb(0x00, 0xCC, 0x99)))); + let line = s[1].line.clone().unwrap(); + assert_eq!((line.head, line.tail), (None, None), "a closed freeform has no ends"); + + // Without a format: 1 pt in the scheme's text and lines colour, unfilled. + assert_eq!(s[2].fill, Some(Fill::None)); + let line = s[2].line.clone().unwrap(); + assert_eq!((line.width, line.head.map(|h| h.kind)), (Some(1.0), Some("triangle".into()))); +} + +/// A freeform reads no more points than [`super::MAX_POINTS`], nor than its record holds whatever +/// its count says; one of fewer than two points draws nothing, a closed flag on two points draws +/// it open, and a flat box still has a path space. +#[test] +fn freeform_points_are_bounded() { + let many: Vec<(i32, i32)> = (0..10_000).map(|i| (i % 100, i / 100)).collect(); + let bx = [0, 0, 100, 100]; + let with_count = |count: u16, points: &[(i32, i32)]| { + container(rt::FREEFORM, 0x13, &[freeform_atom(bx, u32::from(count), true), format(PLAIN), points_atom(count, points)]) + }; + let p = deck_of( + vec![ + freeform_95(bx, &many, false, [0, 0], Some(PLAIN)), + with_count(9, &TRIANGLE), + with_count(2, &SQUARE), + with_count(0, &SQUARE), + freeform_95(bx, &[(5, 5)], true, [0, 0], Some(PLAIN)), + freeform_95(bx, &[], true, [0, 0], Some(PLAIN)), + container(rt::FREEFORM, 0x13, &[freeform_atom(bx, 3, true), format(PLAIN)]), + freeform_95([0, 0, 0, 576], &[(0, 0), (0, 576)], false, [0, 0], Some(PLAIN)), + ], + &[], + ); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 4, "freeforms of fewer than two points are left out"); + let d = path_of(&s[0]).2; + assert_eq!(d.matches('M').count() + d.matches('L').count(), super::MAX_POINTS); + assert_eq!(path_of(&s[1]).2, "M -2304 -1584 L -1152 -1584 L -1728 -432 Z", "the count is cut to the points held"); + assert_eq!(path_of(&s[2]).2, "M -2304 -1584 L -1152 -1584", "two points are drawn open"); + assert_eq!(path_of(&s[3]), (1.0, 576.0, "M 0 0 L 0 576")); + assert_eq!(boxed(&s[3]), (360.0, 270.0, 0.0, 72.0)); +} + +/// A group is one shape spanning its members, whose child space is its own box, so its members, +/// shapes, lines and freeforms alike, stay where they would be ungrouped. +#[test] +fn groups_span_their_members() { + let red = Format { fill: Some([0xFF, 0, 0, 0xFE]), ..PLAIN }; + let members = [ + autoshape(-3, 0, [-2304, -1584, -1728, -1008], 0, red), + line_95([-1440, -1296, -864, -1008], Some(PLAIN)), + freeform_95(TRIANGLE_BOX, &TRIANGLE, false, [0, 0], Some(PLAIN)), + ]; + let ungrouped = deck_of(members.to_vec(), &[]); + let p = deck_of(vec![group_95(&members)], &[]); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 1); + assert!(s[0].name.starts_with("Group")); + let m = group_members(&s[0]); + assert_eq!(m.iter().map(boxed).collect::>(), ungrouped.slides[0].shapes.iter().map(boxed).collect::>()); + assert_eq!(boxed(&m[0]), (72.0, 72.0, 72.0, 72.0)); + assert_eq!(boxed(&m[1]), (180.0, 108.0, 72.0, 36.0)); + assert_eq!(boxed(&s[0]), (72.0, 72.0, 180.0, 144.0)); + assert_eq!((preset_of(&m[0]).0, preset_of(&m[1]).0, preset_of(&m[2]).0), ("rect", "line", "custom")); + assert_eq!(m[0].fill, Some(Fill::solid(rgb(0xFF, 0, 0)))); + + // A group of nothing drawn is left out, and one in a master is the master's shape. + let p = deck_of(vec![group_95(&[]), group_95(&[autoshape(-3, 0, [0, 0, 8, 8], 0, Format { line: None, fill: None, ..PLAIN })])], &[]); + assert!(p.slides[0].shapes.is_empty()); + let p = deck_of(vec![], &[group_95(&members)]); + assert_eq!(p.masters[0].shapes.iter().filter(|s| matches!(s.kind, craft_pptx::ShapeKind::Group { .. })).count(), 1); +} + +/// A group in a group: the probe's rectangle and ellipse, grouped with a triangle. +#[test] +fn groups_nest() { + let inner = group_95(&[autoshape(-3, 0, [-2304, -1584, -1728, -1008], 0, PLAIN), autoshape(-1, 0, [-1440, -1296, -864, -1008], 0, PLAIN)]); + let p = deck_of(vec![group_95(&[inner, autoshape(1, 10800, [-576, -1584, 0, -1008], 0, PLAIN)])], &[]); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 1); + let outer = group_members(&s[0]); + assert_eq!(boxed(&s[0]), (72.0, 72.0, 288.0, 72.0)); + assert_eq!(outer.len(), 2); + let inner = group_members(&outer[0]); + assert_eq!(boxed(&outer[0]), (72.0, 72.0, 180.0, 72.0)); + assert_eq!(inner.iter().map(|s| preset_of(s).0).collect::>(), ["rect", "ellipse"]); + assert_eq!((preset_of(&outer[1]).0, boxed(&outer[1])), ("triangle", (288.0, 72.0, 72.0, 72.0))); +} + +/// Groups nested 1000 deep read [`super::MAX_DEPTH`] of them and leave the rest out, without +/// recursing further, on a stack of 1 MiB (a Windows main thread's); members count towards the +/// page's object cap. +#[test] +fn groups_are_bounded() { + let rect = autoshape(-3, 0, [0, 0, 576, 576], 0, PLAIN); + let mut g = group_95(std::slice::from_ref(&rect)); + for _ in 1..1000 { + g = group_95(&[rect.clone(), g]); + } + let p = std::thread::Builder::new().stack_size(1 << 20).spawn(move || deck_of(vec![g], &[])).unwrap().join().unwrap(); + let (mut depth, mut s) = (0, &p.slides[0].shapes[0]); + loop { + depth += 1; + let m = group_members(s); + match m.iter().find(|c| matches!(c.kind, craft_pptx::ShapeKind::Group { .. })) { + Some(inner) => s = inner, + None => break, + } + } + assert_eq!(depth, super::MAX_DEPTH); + + let line = line_95([0, 0, 8, 8], None); + let many = vec![line; super::MAX_OBJECTS + 10]; + let p = deck_of(vec![group_95(&many), line_95([0, 0, 8, 8], None)], &[]); + let s = &p.slides[0].shapes; + assert_eq!((s.len(), group_members(&s[0]).len()), (1, super::MAX_OBJECTS - 1)); +} + +/// Damaged freeforms and groups never panic: every word of a page of them set to hostile values, +/// or the page cut anywhere. +#[test] +fn hostile_freeforms_and_groups_never_panic() { + let huge = [i32::MIN, i32::MAX, i32::MAX, i32::MIN]; + let p = deck_of(vec![freeform_95(huge, &[(i32::MIN, i32::MAX), (i32::MAX, i32::MIN), (0, 0)], true, [0xFF, 0xFF], Some(PLAIN))], &[]); + let (w, h, d) = path_of(&p.slides[0].shapes[0]); + assert!(w.is_finite() && h.is_finite() && !d.contains("inf") && !d.contains("NaN")); + + let mut s = SlideSpec::new(0x100, 0); + s.objects = vec![group_95(&[ + freeform_95(TRIANGLE_BOX, &TRIANGLE, false, [4, 1], Some(PLAIN)), + group_95(&[line_95([0, 0, 576, 288], Some(PLAIN)), autoshape(-1, 0, [0, 0, 576, 576], 0, PLAIN)]), + ])]; + let stream = stream_of( + document_atom(5760, 4320, 1), + &[slide(&s)], + &[master_with(MASTER, DEFAULT, [0; 4], &[group_95(&[freeform_95(TRIANGLE_BOX, &SQUARE, true, [0, 0], None)])])], + ); + for at in (0..stream.len() - 4).step_by(4) { + for v in [0u32, 1, 2, 0xBB8, 0xBC8, 0x7D0, 0x7FFF_FFFF, 0xFFFF_FFFF] { + let mut d = stream.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let _ = import(&d); + } + } + for cut in 0..stream.len() { + let _ = import(&stream[..cut]); + } +} + /// The presets of the object model's shape types 1 to 12, as PowerPoint 95 rendered them ("custom" for /// the trapezoid, which has its own outline). const SHAPE_PRESETS: [&str; 12] = @@ -1518,6 +1739,42 @@ fn check_drawn_sample(name: &str, shapes: &[Shape]) { assert_eq!((line.head, line.tail), want, "{name}"); assert_eq!((line.width, line.fill), (Some(1.0), Some(Fill::solid(black))), "{name}"); } + _ => check_object_sample(name, shapes), + } +} + +/// What one PowerPoint 95 sample of a freeform or group shows, by its case name. +fn check_object_sample(name: &str, shapes: &[Shape]) { + // AddShape(1, 1440, 1440, 1440, 1440) and AddShape(3, 3600, 2160, 1440, 720) in twips, and the + // third, AddShape(5, 5760, 1440, 1440, 1440): where they were before they were grouped. + let (rect, ellipse, triangle) = ((72.0, 72.0, 72.0, 72.0), (180.0, 108.0, 72.0, 36.0), (288.0, 72.0, 72.0, 72.0)); + match name { + "freeform" | "freeform-closed" | "freeform-filled" => { + let s = &shapes[0]; + assert_eq!((shapes.len(), boxed(s)), (1, (72.0, 72.0, 144.0, 144.0)), "{name}"); + let (fill, d) = if name == "freeform" { + (Fill::None, "M 0 0 L 1152 0 L 576 1152") + } else { + (Fill::solid(rgb(0x00, 0xCC, 0x99)), "M 0 0 L 1152 0 L 1152 1152 L 0 1152 Z") + }; + assert_eq!((path_of(s), s.fill.clone()), ((1152.0, 1152.0, d), Some(fill)), "{name}"); + assert_eq!(s.line.as_ref().and_then(|l| l.fill.clone()), Some(Fill::solid(rgb(0, 0, 0))), "{name}"); + } + "group" | "group-rot" => { + assert_eq!(shapes.len(), 1, "{name}"); + let m = group_members(&shapes[0]); + assert_eq!(m.iter().map(|s| (preset_of(s).0, boxed(s))).collect::>(), [("rect", rect), ("ellipse", ellipse)], "{name}"); + assert_eq!(m[0].fill, Some(Fill::solid(rgb(0xFF, 0, 0))), "{name}"); + assert_eq!((boxed(&shapes[0]), shapes[0].xfrm.unwrap().rot), ((72.0, 72.0, 180.0, 72.0), 0.0), "{name}"); + } + "group-nested" => { + assert_eq!(shapes.len(), 1); + let outer = group_members(&shapes[0]); + assert_eq!((outer.len(), boxed(&shapes[0])), (2, (72.0, 72.0, 288.0, 72.0))); + let inner = group_members(&outer[0]); + assert_eq!(inner.iter().map(boxed).collect::>(), [rect, ellipse]); + assert_eq!((preset_of(&outer[1]).0, boxed(&outer[1])), ("triangle", triangle)); + } _ => {} } }