diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index b7d0620e4..4ec03ae78 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -47,8 +47,13 @@ and text boxes, each with its box and its text: paragraphs with their level, ali character and the indents of the text's ruler, and runs with their font, size, bold, italic, underline and colour (an RGB or a colour scheme slot). The text is Windows-1252. The master's placeholders set where the default master's placeholders go, and its date, footer and slide number -those of every layout. Shapes without text, the shapes' own fill and line, pictures, notes and the -master's text styles come later. +those of every layout. Shapes and lines read too: PowerPoint 95's twelve shapes (rectangle, +rounded rectangle, ellipse, diamond, the two triangles, parallelogram, trapezoid, hexagon, +octagon, plus and five-point star) as DrawingML presets with their adjust values, each with its +fill and line colour (or none), its shadow, its angle and a horizontal flip, and lines from their +start to their end. A shape that draws nothing but text is a text box. Line widths and styles, +vertical flips and shadow offsets are not read yet (lines draw 1 pt wide, as PowerPoint 95 drew +them, and shadows fall 6 pt right and down); groups and freeforms are skipped. 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/geom.rs b/crates/ppt-binary/src/geom.rs index 52206018a..94d2768eb 100644 --- a/crates/ppt-binary/src/geom.rs +++ b/crates/ppt-binary/src/geom.rs @@ -170,18 +170,22 @@ pub fn is_connector(shape_type: u16) -> bool { pub fn geometry(shape_type: u16, props: &Props) -> Geom { if let Some(name) = preset_name(shape_type).filter(|n| craft_drawingml::preset::build(n, 100.0, 100.0, &[]).is_some()) { let mut adj = vec![]; - // A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the - // shorter side in DrawingML. if shape_type == 2 && let Some(v) = props.get(prop::ADJUST_VALUE) { - adj.push(f64::from(v as i32).clamp(0.0, 10800.0) / 21600.0 * 100_000.0); + adj.push(round_rect_adjust(v as i32)); } return Geom::Preset { name: name.into(), adj }; } custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default() } +/// A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the shorter +/// side in DrawingML. +pub(crate) fn round_rect_adjust(v: i32) -> f64 { + f64::from(v).clamp(0.0, 10800.0) / 21600.0 * 100_000.0 +} + /// Segments followed at most in one path. const MAX_SEGMENTS: usize = 1 << 16; /// Vertices used at most in one path. The path text is copied into every shape that inherits the diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index b54f63e1f..8637b778a 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -9,8 +9,9 @@ //! //! PowerPoint 95 files (a different record framing, learned from files PowerPoint 95 wrote) read //! as far as their slide size, masters with their colour schemes, backgrounds and placeholder -//! boxes, and slides with their order, master, layout type, background, and placeholders and text -//! boxes with formatted text; their other shapes, pictures and notes are not read yet. +//! boxes, and slides with their order, master, layout type, background, placeholders and text +//! boxes with formatted text, and shapes and lines with their fill, line and shadow; their +//! pictures and notes are not read yet. //! PowerPoint 4.0 and earlier are refused as too old. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index fa7e5b35f..5756cf051 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -6,34 +6,42 @@ //! (a type-3 root holding the Document, 1000), with no edit chain or persist directory. //! //! 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 and -//! text boxes with the text and its character and paragraph formatting ([`text`]). +//! 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`]). //! -//! A page's object list (3000) holds shapes (3008) and placeholders (3010, which add a 3011 atom: -//! the type, the size, then the index). Each has its geometry (3009): the box as left, top, right -//! and bottom in master units (576 per inch) measured from the slide's centre, then the angle in -//! sixteenths of a degree. 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 placeholder of any other type keeps its text as a text box. The -//! master's placeholders place the caller's default master's, and the footer row places every -//! layout's, as the PowerPoint 97 path does. +//! 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 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 the angle in sixteenths of a degree. +//! A turned shape keeps its unturned box. A line holds 3015: its start and end points, in the same +//! units. Shapes and lines have a format (3005) with their fill, line, shadow and horizontal flip +//! ([`shape`]). A shape that draws nothing but its text is a text box. //! -//! Not read yet: shapes without text, and shapes' own fill, line and shadow; 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). +//! 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 +//! placeholder of any other type keeps its text as a text box. The master's placeholders place the +//! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path +//! does. +//! +//! Not read yet: line widths and styles, vertical flips and shadow offsets (no probe changed them); +//! 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). use std::collections::{HashMap, HashSet}; use std::sync::Arc; use craft_pptx::{ - Background, ColorRef, Defaults, Fill, 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, Size, + Slide, SlideId, TextBody, Xfrm, }; use crate::convert::{Scheme, layout_kind, layout_table, page_side, place_placeholder, same_family, scheme_theme}; use crate::record::u32_at; +use shape::Look; use text::Env; +mod shape; mod text; /// Record types. @@ -55,6 +63,8 @@ mod rt { pub const GEOMETRY: u32 = 3009; pub const PLACEHOLDER: u32 = 3010; pub const PLACEHOLDER_ATOM: u32 = 3011; + pub const LINE: u32 = 3014; + pub const LINE_ATOM: u32 = 3015; pub const TEXT: u32 = 4001; } @@ -70,7 +80,7 @@ const MAX_MASTERS: usize = 256; const MAX_OBJECTS: usize = 1 << 14; /// Master units (576 per inch) per point. const MU: f64 = 8.0; -/// The fill colour's fourth byte when the colour is the RGB given, not a scheme slot. +/// A colour's fourth byte when the colour is the RGB given, not a scheme slot. const RGB_GIVEN: u8 = 0xFE; /// PowerPoint 95's default colour scheme, for a slide or master without one. @@ -196,9 +206,7 @@ fn background(rec: &Rec, scheme: &Scheme) -> Option { if format.u8(12)? == 0xFF { return Some(Fill::None); } - let (r, g, b, index) = (format.u8(20)?, format.u8(21)?, format.u8(22)?, format.u8(23)?); - let color = if index == RGB_GIVEN { Rgba::rgb(r, g, b) } else { *scheme.get(usize::from(index))? }; - Some(Fill::solid(ColorRef::rgb(color))) + Some(Fill::solid(ColorRef::rgb(shape::color(&format, 20, scheme)?))) } /// A PowerPoint 95 placeholder number as a placeholder type. PowerPoint 95 numbers them its own @@ -224,25 +232,59 @@ struct Object { ph: Option, xfrm: Xfrm, text: Option, + /// A shape's preset: `None` for a placeholder, or a shape code no probe showed. + 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, } -/// The shapes and placeholders of a page's object list. +/// 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)).take(MAX_OBJECTS) + 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) } -/// A shape or placeholder: its box, from master units about the slide's centre to points from -/// its top left corner, its placeholder atom and its text. -fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { - let g = r.child(rt::GEOMETRY)?; - let sides = [g.i32(12)?, g.i32(16)?, g.i32(20)?, g.i32(24)?]; - let [l, t, right, b] = sides; +/// A box from master units about the slide's centre (left, top, right, bottom, either way round) +/// to points from its top left corner. +fn xfrm_of([l, t, right, b]: [i32; 4], size: Size) -> Xfrm { let x = |v: i32| f64::from(v) / MU + size.width / 2.0; let y = |v: i32| f64::from(v) / MU + size.height / 2.0; + Xfrm { x: x(l).min(x(right)), y: y(t).min(y(b)), w: (x(right) - x(l)).abs(), h: (y(b) - y(t)).abs(), rot: 0.0, flip_h: false, flip_v: false } +} + +/// A line: the box its ends span, flipped so that it runs from its start to its end, drawn as its +/// format says (in the scheme's text and lines colour without one). +fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option { + let a = r.child(rt::LINE_ATOM)?; + let (x1, y1, x2, y2) = (a.i32(0)?, a.i32(4)?, a.i32(8)?, a.i32(12)?); + let mut xfrm = xfrm_of([x1, y1, x2, y2], size); + (xfrm.flip_h, xfrm.flip_v) = (x2 < x1, y2 < y1); + let mut look = match r.child(rt::FORMAT) { + Some(f) => shape::look(&f, scheme), + None => Look { line: shape::line_of(scheme[1]), ..Look::none() }, + }; + // A line has no inside to fill, and its direction is in its ends. + (look.fill, look.flip_h) = (Fill::None, false); + let geom = Some(Geom::Preset { name: "line".into(), adj: vec![] }); + Some(Object { placeholder: false, ph: None, xfrm, text: None, geom, look, line: true }) +} + +/// A shape, placeholder or line: its box, its placeholder atom, its text, and a shape's preset and +/// look. +fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { + if r.kind == rt::LINE { + return line(r, scheme, size); + } + let g = r.child(rt::GEOMETRY)?; + let sides = [g.i32(12)?, g.i32(16)?, g.i32(20)?, g.i32(24)?]; + let mut xfrm = xfrm_of(sides, size); // The box is the unturned one; the angle is in sixteenths of a degree. - let rot = g.i32(28).map_or(0.0, |v| (f64::from(v) / 16.0).rem_euclid(360.0)); - let xfrm = - Xfrm { x: x(l).min(x(right)), y: y(t).min(y(b)), w: (x(right) - x(l)).abs(), h: (y(b) - y(t)).abs(), rot, flip_h: false, flip_v: false }; + xfrm.rot = g.i32(28).map_or(0.0, |v| (f64::from(v) / 16.0).rem_euclid(360.0)); let placeholder = r.kind == rt::PLACEHOLDER; let ph = r.child(rt::PLACEHOLDER_ATOM).filter(|_| placeholder).and_then(|a| { let size = match a.u8(1) { @@ -253,22 +295,55 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { Some(Placeholder { kind: ph_type(a.u8(0)?)?, idx: a.u32(4).unwrap_or(0), size, ..Default::default() }) }); let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); - Some(Object { placeholder, ph, xfrm, text }) + let (mut geom, mut look) = (None, Look::none()); + if !placeholder { + // The shape code is the low byte: PowerPoint 95 sets bits above it on some shapes (0x60 on + // the trapezoid). + if let Some((preset, upside_down)) = g.u8(0).and_then(|c| shape::preset(c as i8, g.i32(4), xfrm.w, xfrm.h)) { + geom = Some(preset); + xfrm.flip_v = upside_down; + } + if let Some(f) = r.child(rt::FORMAT) { + look = shape::look(&f, scheme); + } + xfrm.flip_h = look.flip_h; + } + Some(Object { placeholder, ph, xfrm, text, geom, look, line: false }) } -/// An object as a shape: a placeholder of a known type, else a text box when it has text (a shape -/// with no text is not read yet). A placeholder of an unknown type keeps its text as a text box. +/// An object as a shape: a placeholder of a known type; a text box when it draws nothing but its +/// text, or has text and a shape code no probe showed; else a shape or line that draws something. +/// One that draws nothing, or has an unknown code and no text, is left out. A placeholder of an +/// unknown type keeps its text as a text box. fn shape(p: &mut Presentation, o: Object) -> Option { let Some(ph) = o.ph else { - let text = o.text.filter(|t| !t.is_empty())?; + let text = o.text.filter(|t| !t.is_empty()); + if text.is_some() && (!o.look.drawn() || o.geom.is_none()) { + let mut xfrm = o.xfrm; + (xfrm.flip_h, xfrm.flip_v) = (false, false); + return Some(Shape { + id: ShapeId(p.alloc_id()?), + name: "Text Box".into(), + xfrm: Some(xfrm), + text_box: true, + fill: Some(Fill::None), + line: Some(Line::none()), + text, + ..Default::default() + }); + } + let geom = o.geom.filter(|_| o.look.drawn())?; + let id = p.alloc_id()?; + let Look { fill, line, shadow, .. } = o.look; return Some(Shape { - id: ShapeId(p.alloc_id()?), - name: "Text Box".into(), + id: ShapeId(id), + name: if o.line { format!("Line {id}") } else { format!("Shape {id}") }, xfrm: Some(o.xfrm), - text_box: true, - fill: Some(Fill::None), - line: Some(Line::none()), - text: Some(text), + geom, + fill: Some(fill), + line: Some(line), + effects: shadow.map(|s| Effects { outer_shadow: Some(s), ..Default::default() }), + text, ..Default::default() }); }; diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs new file mode 100644 index 000000000..51d343d70 --- /dev/null +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -0,0 +1,110 @@ +//! PowerPoint 95 shapes: the shape code of a geometry record (3009) as a DrawingML preset, and a +//! format record (3005) as fill, line and shadow, learned from files PowerPoint 95 wrote and the +//! slides it rendered from them. +//! +//! The shape code is the [MS-ODRAW] shape type less 4, so the [`geom`] table names its preset; the +//! adjust value after it is a coordinate in the shape's 21600-unit square, as OfficeArt's are. +//! +//! A format record holds the line (+0 0xFF for none, +4 its colour), the fill (+12 0xFF for none, +//! +20 its colour) and the shadow (+24 its colour, +28 0x00 when on and 0xFF when off), then the +//! angle at +48 and a horizontal flip at +52. Each colour is R, G, B and an index: 0xFE for the RGB +//! itself, else a slot of the colour scheme. + +use craft_pptx::style::Shadow; +use craft_pptx::{ColorRef, Fill, Geom, Line, Rgba}; + +use super::{RGB_GIVEN, Rec}; +use crate::convert::Scheme; +use crate::geom; + +/// The width of every line PowerPoint 95 drew in the probes' renderings, in points (8 master +/// units); no probe set another, so the format's width field is not known yet. +const LINE_WIDTH: f64 = 1.0; +/// How far a shadow falls right and down, in points. The probes turned shadows on and off but +/// never moved one, so the offset is not read: this is the 48 units (6 pt) every probe's format +/// holds at +36 and +40, where the offset most likely is. +const SHADOW_OFFSET: f64 = 6.0; + +/// How a shape is drawn. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Look { + pub fill: Fill, + pub line: Line, + pub shadow: Option, + pub flip_h: bool, +} + +impl Look { + /// Nothing drawn: what a shape with no format record shows. + pub(super) fn none() -> Look { + Look { fill: Fill::None, line: Line::none(), shadow: None, flip_h: false } + } + + /// Whether the shape draws anything of its own (its text aside). + pub(super) fn drawn(&self) -> bool { + self.fill != Fill::None || self.line != Line::none() || self.shadow.is_some() + } +} + +/// A format record's colour at `at`: R, G, B, then 0xFE or a slot of `scheme`. +pub(super) fn color(format: &Rec, at: usize, scheme: &Scheme) -> Option { + let (r, g, b, index) = (format.u8(at)?, format.u8(at + 1)?, format.u8(at + 2)?, format.u8(at + 3)?); + if index == RGB_GIVEN { Some(Rgba::rgb(r, g, b)) } else { scheme.get(usize::from(index)).copied() } +} + +/// A line of `color` as PowerPoint 95 draws it. +pub(super) fn line_of(color: Rgba) -> Line { + Line::solid(ColorRef::rgb(color), LINE_WIDTH) +} + +/// A format record as fill, line, shadow and flip. A part whose flag or colour is cut off or names +/// no scheme slot is not drawn. +pub(super) fn look(format: &Rec, scheme: &Scheme) -> Look { + let on = |flag: usize, at: usize| format.u8(flag).filter(|&f| f != 0xFF).and_then(|_| color(format, at, scheme)); + let shadow = format.u8(28).filter(|&f| f == 0).and_then(|_| color(format, 24, scheme)).map(|c| Shadow { + color: ColorRef::rgb(c), + blur: 0.0, + dist: SHADOW_OFFSET.hypot(SHADOW_OFFSET), + dir: 45.0, + inner: false, + sx: 1.0, + sy: 1.0, + kx: 0.0, + ky: 0.0, + align: String::new(), + rotate_with_shape: false, + }); + Look { + fill: on(12, 20).map_or(Fill::None, |c| Fill::solid(ColorRef::rgb(c))), + line: on(0, 4).map_or_else(Line::none, line_of), + shadow, + flip_h: format.u8(52).is_some_and(|f| f != 0), + } +} + +/// The preset for a shape code with its adjust value, in a box `w` × `h` points, and whether it is +/// drawn upside down from the preset. `None` for a code no probe showed. +/// +/// An OfficeArt adjust value is a coordinate in the shape's 21600-unit square, stretched to the box +/// on each axis; a DrawingML one is a 100000 fraction of the width (the triangle's apex) or of the +/// shorter side. PowerPoint 95's trapezoid is wide at the top, DrawingML's at the bottom. +pub(super) fn preset(code: i8, adjust: Option, w: f64, h: f64) -> Option<(Geom, bool)> { + if !(-3..=8).contains(&code) { + return None; + } + let kind = u16::try_from(i16::from(code) + 4).ok()?; + let name = geom::preset_name(kind)?; + let fraction = |v: i32, max: f64| f64::from(v).clamp(0.0, max) / 21600.0 * 100_000.0; + // A horizontal inset: a share of the width, as a share of the shorter side. + let ss = w.min(h); + let across = |v: i32, max: f64| if ss > 0.0 && w.is_finite() { fraction(v, max) * w / ss } else { fraction(v, max) }; + let adj = adjust.and_then(|v| match kind { + 2 => Some(geom::round_rect_adjust(v)), + 5 => Some(fraction(v, 21600.0)), + 7 => Some(across(v, 21600.0)), + 8 | 9 => Some(across(v, 10800.0)), + 10 | 11 => Some(fraction(v, 10800.0)), + _ => None, + }); + Some((Geom::Preset { name: name.into(), adj: adj.into_iter().collect() }, kind == 8)) +} diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 740be190a..2fed4b413 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -3,7 +3,7 @@ #![allow(clippy::unwrap_used)] use craft_pptx::text::{Align, Bullet}; -use craft_pptx::{Background, ColorRef, Fill, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, TextBody}; +use craft_pptx::{Background, ColorRef, Fill, Geom, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, TextBody}; use super::rt; use crate::tests::{AppDefaults, build}; @@ -470,7 +470,7 @@ fn title_and_subtitle_placeholders_keep_their_text() { let title = placeholder_95(0x0F, 0, 0, [-2448, -720, 2448, 0], Some(simple_text(b"Title text", [-2448, -720, 2448, 0], BODY))); let sub = placeholder_95(0x10, 1, 1, [-2016, 288, 2016, 1392], Some(simple_text(b"Sub text", [-2016, 288, 2016, 1392], BODY))); let p = deck_of(vec![title, sub], &[]); - let shapes = &p.slides[0].shapes; + let Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; assert_eq!(texts(&p), ["Title text", "Sub text"]); let ph: Vec<_> = shapes.iter().map(|s| s.ph.clone().unwrap()).collect(); assert_eq!((ph[0].kind, ph[0].idx, ph[0].size.as_deref()), (PhType::CtrTitle, 0, None)); @@ -566,9 +566,9 @@ fn paragraphs_keep_their_alignment() { assert_eq!(aligns, [Some(Align::Left), Some(Align::Center), Some(Align::Right), None]); } -/// A shape with text is a text box with no fill or line of its own; a shape without text isn't -/// read yet; a placeholder of a type PowerPoint 95 isn't known to write keeps its text as a text -/// box. +/// A shape with text and no format of its own is a text box with no fill or line; one without text +/// draws nothing and is left out; a placeholder of a type PowerPoint 95 isn't known to write keeps +/// its text as a text box. #[test] fn a_shape_with_text_is_a_text_box() { let bx = [-2362, -1613, -518, -1325]; @@ -705,6 +705,249 @@ fn hostile_text_never_panics() { } } +/// A geometry record with its shape code word, adjust value, box and angle. +fn coded_geometry(code: u32, adjust: i32, bx: [i32; 4], rot: i32) -> Vec { + let mut b = le32(&[code, adjust as u32, 0]); + b.extend(bx.iter().chain(&[rot]).flat_map(|v| v.to_le_bytes())); + b.extend_from_slice(&le32(&[code, 0])); + rec(3009, 0, 0, &b) +} + +/// How a test shape is drawn: line and fill colours (R, G, B, then 0xFE or a scheme slot; `None` +/// for none), the shadow's colour when it has one, and the horizontal flip. +#[derive(Clone, Copy)] +struct Format { + line: Option<[u8; 4]>, + fill: Option<[u8; 4]>, + shadow: Option<[u8; 4]>, + flip_h: bool, +} + +/// PowerPoint 95's defaults: lines in slot 1, fills in slot 4, no shadow. +const PLAIN: Format = Format { line: Some([0, 0, 0, 1]), fill: Some([0, 0, 0, 4]), shadow: None, flip_h: false }; + +fn format(f: Format) -> Vec { + let mut b = vec![0u8; 56]; + b[0] = if f.line.is_some() { 0 } else { 0xFF }; + b[4..8].copy_from_slice(&f.line.unwrap_or([0, 0, 0, 1])); + b[12] = if f.fill.is_some() { 0 } else { 0xFF }; + b[13] = 1; + b[20..24].copy_from_slice(&f.fill.unwrap_or([0, 0, 0, 4])); + b[24..28].copy_from_slice(&f.shadow.unwrap_or([0, 0, 0, 1])); + b[28] = if f.shadow.is_some() { 0 } else { 0xFF }; + b[29] = 1; + b[36] = 48; + b[40] = 48; + b[52] = u8::from(f.flip_h); + rec(rt::FORMAT, 1, 0, &b) +} + +/// A shape of `code` with its adjust value, box, angle and format. +fn autoshape(code: i32, adjust: i32, bx: [i32; 4], rot: i32, f: Format) -> Vec { + container(rt::SHAPE, 0x13, &[coded_geometry(code as u32, adjust, bx, rot), format(f)]) +} + +/// A line from (x1, y1) to (x2, y2), with its format when given. +fn line_95(ends: [i32; 4], f: Option) -> Vec { + let mut kids = vec![rec(rt::LINE_ATOM, 0, 0, &ends.iter().flat_map(|v| v.to_le_bytes()).collect::>()), rec(3007, 0, 0, &[0, 0])]; + kids.extend(f.map(format)); + container(rt::LINE, 0x13, &kids) +} + +fn preset_of(s: &Shape) -> (&str, &[f64]) { + match &s.geom { + Geom::Preset { name, adj } => (name, adj), + Geom::Custom { .. } => ("custom", &[]), + } +} + +fn rgb(r: u8, g: u8, b: u8) -> ColorRef { + ColorRef::rgb(Rgba::rgb(r, g, b)) +} + +/// Each shape code PowerPoint 95 wrote is its preset, with its adjust value in DrawingML terms (the +/// probes' adjust values are DrawingML's defaults on a square). The trapezoid, wide at the top in +/// PowerPoint 95, is DrawingML's turned upside down; the bits above its code's low byte don't +/// change the code. +#[test] +fn shape_codes_are_presets_with_their_adjust_values() { + let sq = [0, 0, 1152, 1152]; + let cases: [(i32, i32, &str, &[f64]); 12] = [ + (-3, 0, "rect", &[]), + (-2, 2700, "roundRect", &[12_500.0]), + (-1, 0, "ellipse", &[]), + (0, 0, "diamond", &[]), + (1, 10800, "triangle", &[50_000.0]), + (2, 0, "rtTriangle", &[]), + (3, 5400, "parallelogram", &[25_000.0]), + (0x6004, 5400, "trapezoid", &[25_000.0]), + (5, 5400, "hexagon", &[25_000.0]), + (6, 6326, "octagon", &[6326.0 / 21600.0 * 100_000.0]), + (7, 5400, "plus", &[25_000.0]), + (8, 0, "star5", &[]), + ]; + let p = deck_of(cases.iter().map(|(code, adj, ..)| autoshape(*code, *adj, sq, 0, PLAIN)).collect(), &[]); + let Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; + assert_eq!(shapes.len(), 12); + for (s, (code, _, name, adj)) in shapes.iter().zip(cases) { + assert_eq!(preset_of(s), (name, adj), "code {code}"); + assert_eq!(boxed(s), (360.0, 270.0, 144.0, 144.0)); + assert_eq!(s.xfrm.unwrap().flip_v, name == "trapezoid", "{name}"); + assert!(!s.text_box && s.ph.is_none()); + assert!(craft_drawingml::preset::build(name, 144.0, 144.0, adj).is_some()); + } + // An inset across a box twice as wide as it is tall is twice the share of its shorter side. + let p = deck_of(vec![autoshape(3, 5400, [0, 0, 1152, 576], 0, PLAIN), autoshape(-2, 99_999, sq, 0, PLAIN)], &[]); + assert_eq!(preset_of(&p.slides[0].shapes[0]), ("parallelogram", &[50_000.0][..])); + assert_eq!(preset_of(&p.slides[0].shapes[1]), ("roundRect", &[50_000.0][..]), "a corner past half the side is half"); +} + +/// A shape's fill (an RGB or a slot of the slide's scheme, or none), its line colour (or none) at +/// PowerPoint 95's 1 pt, and its shadow when on. +#[test] +fn shapes_keep_their_fill_line_and_shadow() { + let bx = [0, 0, 1152, 576]; + let red = Format { fill: Some([0xFF, 0, 0, 0xFE]), ..PLAIN }; + let blue_line = Format { line: Some([0, 0, 0xFF, 0xFE]), ..PLAIN }; + let no_fill = Format { fill: None, ..PLAIN }; + let no_line = Format { line: None, ..PLAIN }; + let shadow = Format { shadow: Some([0x80, 0x80, 0x80, 0xFE]), ..PLAIN }; + let p = deck_of([PLAIN, red, blue_line, no_fill, no_line, shadow].into_iter().map(|f| autoshape(-3, 0, bx, 0, f)).collect(), &[]); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 6); + // The default: slot 4 (fills) and slot 1 (text and lines) of the slide's scheme. + assert_eq!(s[0].fill, Some(Fill::solid(rgb(0, 0xCC, 0x99)))); + assert_eq!(s[0].line, Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0))); + assert_eq!(s[0].effects, None); + assert_eq!(s[1].fill, Some(Fill::solid(rgb(0xFF, 0, 0)))); + assert_eq!(s[2].line, Some(craft_pptx::Line::solid(rgb(0, 0, 0xFF), 1.0))); + assert_eq!(s[3].fill, Some(Fill::None)); + assert_eq!(s[3].line, s[0].line); + assert_eq!(s[4].line, Some(craft_pptx::Line::none())); + let sh = s[5].effects.as_ref().and_then(|e| e.outer_shadow.clone()).unwrap(); + assert_eq!((sh.color, sh.dir, sh.blur), (rgb(0x80, 0x80, 0x80), 45.0, 0.0)); + assert!((sh.dist - 6.0 * 2f64.sqrt()).abs() < 1e-9); + + // A slot of the slide's own scheme. + let mut spec = SlideSpec::new(0x100, 16); + spec.scheme[4] = 0x123456; + spec.objects = vec![autoshape(-1, 0, bx, 0, PLAIN)]; + let p = deck(&[spec]); + assert_eq!(p.slides[0].shapes[0].fill, Some(Fill::solid(rgb(0x12, 0x34, 0x56)))); + + // A shape with no fill, line or shadow draws nothing and is left out; with text it is a text + // box. A filled one with text keeps the text. + let none = Format { fill: None, line: None, ..PLAIN }; + let with_text = |f: Format| container(rt::SHAPE, 0x13, &[coded_geometry(-1i32 as u32, 0, bx, 0), format(f), simple_text(b"Hi", bx, BODY)]); + let p = deck_of(vec![autoshape(-1, 0, bx, 0, none), with_text(none), with_text(red)], &[]); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 2); + assert!(s[0].text_box && s[0].fill == Some(Fill::None)); + assert!(!s[1].text_box); + assert_eq!((preset_of(&s[1]).0, body_of(&s[1]).text(), s[1].fill.clone()), ("ellipse", "Hi".into(), Some(Fill::solid(rgb(0xFF, 0, 0))))); +} + +/// A turned shape keeps its unturned box and its angle; a flipped one is flipped across. +#[test] +fn shapes_keep_their_angle_and_flip() { + let bx = [-2304, -1584, -1152, -1008]; + let p = deck_of(vec![autoshape(-3, 0, bx, 480, PLAIN), autoshape(2, 0, bx, 0, Format { flip_h: true, ..PLAIN })], &[]); + let x: Vec<_> = p.slides[0].shapes.iter().map(|s| s.xfrm.unwrap()).collect(); + assert_eq!((x[0].x, x[0].y, x[0].w, x[0].h, x[0].rot, x[0].flip_h), (72.0, 72.0, 144.0, 72.0, 30.0, false)); + assert_eq!((x[1].rot, x[1].flip_h, x[1].flip_v), (0.0, true, false)); +} + +/// A line spans the box of its ends and is flipped to run from its start to its end, in its +/// format's colour (the scheme's text and lines colour without one), never filled. +#[test] +fn lines_keep_their_ends_and_direction() { + let blue = Format { line: Some([0, 0, 0xFF, 0xFE]), ..PLAIN }; + let p = deck_of( + vec![ + line_95([-2304, -1584, -576, -432], Some(PLAIN)), + line_95([-576, -1584, -2304, -432], Some(blue)), + line_95([-576, -432, -2304, -1584], None), + line_95([0, 0, 576, 0], Some(Format { line: None, ..PLAIN })), + ], + &[], + ); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 3, "a line with no line draws nothing"); + for l in s { + assert_eq!(preset_of(l).0, "line"); + assert_eq!(boxed(l), (72.0, 72.0, 216.0, 144.0)); + assert_eq!(l.fill, Some(Fill::None)); + } + let flips: Vec<_> = s.iter().map(|l| (l.xfrm.unwrap().flip_h, l.xfrm.unwrap().flip_v)).collect(); + assert_eq!(flips, [(false, false), (true, false), (true, true)]); + assert_eq!(s[0].line, Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0))); + assert_eq!(s[1].line, Some(craft_pptx::Line::solid(rgb(0, 0, 0xFF), 1.0))); + assert_eq!(s[2].line, s[0].line); +} + +/// A shape code no probe showed is left out, or kept as a text box when it has text. +#[test] +fn unknown_shape_codes_are_skipped() { + let bx = [0, 0, 576, 576]; + let mut objects: Vec<_> = [-4, 9, 0x7F, -128, 0x6009, -100].iter().map(|&c| autoshape(c, 0, bx, 0, PLAIN)).collect(); + objects.push(container(rt::SHAPE, 0x13, &[coded_geometry(42, 0, bx, 0), format(PLAIN), simple_text(b"Kept", bx, BODY)])); + let p = deck_of(objects, &[]); + let s = &p.slides[0].shapes; + assert_eq!(s.len(), 1); + assert!(s[0].text_box); + assert_eq!(body_of(&s[0]).text(), "Kept"); +} + +/// Damaged shapes and lines never panic: truncated geometry, format and line records, huge +/// values, and every word of a page of them set to hostile values or cut. +#[test] +fn hostile_shapes_never_panic() { + let bx = [0, 0, 576, 576]; + let cut = |r: Vec, keep: usize| { + let mut r = r; + r.truncate(16 + keep); + r[8..12].copy_from_slice(&(keep as u32).to_le_bytes()); + r + }; + let mut objects = vec![]; + for keep in [0, 3, 8, 13, 21, 25, 29, 53] { + objects.push(container(rt::SHAPE, 0x13, &[coded_geometry(1, 10800, bx, 0), cut(format(PLAIN), keep)])); + objects.push(container(rt::SHAPE, 0x13, &[cut(coded_geometry(1, 10800, bx, 0), keep), format(PLAIN)])); + objects.push(container(rt::LINE, 0x13, &[cut(rec(rt::LINE_ATOM, 0, 0, &le32(&[0, 0, 8, 8])), keep.min(16))])); + } + let huge = Format { line: Some([0, 0, 0, 0xFD]), fill: Some([9, 9, 9, 200]), shadow: Some([1, 1, 1, 8]), flip_h: true }; + objects.push(autoshape(5, i32::MAX, [i32::MIN, i32::MIN, i32::MAX, i32::MAX], i32::MIN, huge)); + objects.push(autoshape(3, i32::MIN, [0, 0, 0, 0], i32::MAX, PLAIN)); + objects.push(line_95([i32::MIN, i32::MAX, i32::MAX, i32::MIN], Some(huge))); + let p = deck_of(objects.clone(), &[]); + for s in &p.slides[0].shapes { + let x = s.xfrm.unwrap(); + assert!(x.w.is_finite() && x.h.is_finite() && x.rot.is_finite()); + if let Geom::Preset { adj, .. } = &s.geom { + assert!(adj.iter().all(|a| a.is_finite())); + } + } + + let mut s = SlideSpec::new(0x100, 0); + s.objects = + vec![autoshape(4, 5400, bx, 480, Format { shadow: Some([0, 0, 0, 2]), flip_h: true, ..PLAIN }), line_95([0, 0, 576, 288], Some(PLAIN))]; + let stream = stream_of(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], &[autoshape(-1, 0, bx, 0, PLAIN)])]); + for at in (0..stream.len() - 4).step_by(4) { + for v in [0u32, 1, 0xFE, 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. +const SHAPE_PRESETS: [&str; 12] = + ["rect", "roundRect", "ellipse", "diamond", "triangle", "rtTriangle", "parallelogram", "trapezoid", "hexagon", "octagon", "plus", "star5"]; + /// What one PowerPoint 95 sample shows, by its case name ([`powerpoint_95_samples`]). fn check_sample(name: &str, p: &Presentation) { // Every master places the defaults' title and body, and the footer row on every layout. @@ -766,6 +1009,53 @@ fn check_sample(name: &str, p: &Presentation) { // The automation reported 1295, 1367.5, 4610 × 720 twips. assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); } + _ => check_shape_sample(name, p), + } +} + +/// What one PowerPoint 95 shape sample shows, by its case name. +fn check_shape_sample(name: &str, p: &Presentation) { + let Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; + match name { + "base" => assert!(shapes.is_empty()), + "shapes" => { + let names: Vec<_> = shapes.iter().map(|s| preset_of(s).0).collect(); + assert_eq!(names, SHAPE_PRESETS); + } + _ if name.strip_prefix("shape").and_then(|n| n.parse::().ok()).is_some_and(|n| (1..=12).contains(&n)) => { + let n: usize = name[5..].parse().unwrap(); + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0), (1, SHAPE_PRESETS[n - 1]), "{name}"); + assert_eq!(s.xfrm.unwrap().flip_v, n == 8, "{name}"); + // AddShape(n, 5760, 3960, 2880, 2880) in twips: 2 in square at 4 in, 2.75 in. + assert_eq!(boxed(s), (288.0, 198.0, 144.0, 144.0), "{name}"); + } + "rect" | "fill" | "fill2" | "linecolor" | "nofill" | "shadow" | "rotate" | "flip" => { + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0), (1, "rect"), "{name}"); + // AddShape(1, 1440, 1440, 2880, 1440) in twips. + assert_eq!(boxed(s), (72.0, 72.0, 144.0, 72.0), "{name}"); + let fill = match name { + "fill" => Fill::solid(rgb(0xFF, 0, 0)), + "fill2" => Fill::solid(rgb(0, 0xFF, 0)), + "nofill" => Fill::None, + _ => Fill::solid(rgb(0, 0xCC, 0x99)), + }; + assert_eq!(s.fill, Some(fill), "{name}"); + let line = if name == "linecolor" { rgb(0, 0, 0xFF) } else { rgb(0, 0, 0) }; + assert_eq!(s.line, Some(craft_pptx::Line::solid(line, 1.0)), "{name}"); + assert_eq!(s.effects.is_some(), name == "shadow", "{name}"); + let x = s.xfrm.unwrap(); + assert_eq!((x.rot, x.flip_h, x.flip_v), (if name == "rotate" { 30.0 } else { 0.0 }, name == "flip", false), "{name}"); + } + "line" => { + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0), (1, "line")); + // AddLine(1440, 1440, 4320, 2880): from 1 in, 1 in to 4 in, 3 in. + assert_eq!(boxed(s), (72.0, 72.0, 216.0, 144.0)); + assert_eq!((s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v), (false, false)); + assert_eq!(s.line, Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0))); + } _ => {} } }