From c7c00cc101f1932b93fd24b65f7cb9cdc9bc003d Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 22:20:40 -0500 Subject: [PATCH 01/10] ppt-binary: read PowerPoint 95 shapes and lines (#2317, step 3) PowerPoint 95's twelve shape codes now read as DrawingML presets with their adjust values, and lines from their 3015 ends with flips for their direction. The 3005 format gives each its fill and line colour (an RGB or a scheme slot, or none), its shadow and a horizontal flip; the angle comes from 3009 as before. A shape that draws nothing but text stays a text box, and shapes of unknown codes without text are skipped. The trapezoid is flipped vertically, as PowerPoint 95 draws it wide at the top. Line widths and styles, vertical flips and shadow offsets are not read yet. --- crates/ppt-binary/README.md | 9 +- crates/ppt-binary/src/geom.rs | 10 +- crates/ppt-binary/src/lib.rs | 5 +- crates/ppt-binary/src/ppt95.rs | 155 ++++++++++---- crates/ppt-binary/src/ppt95/shape.rs | 110 ++++++++++ crates/ppt-binary/src/ppt95/tests.rs | 300 ++++++++++++++++++++++++++- 6 files changed, 537 insertions(+), 52 deletions(-) create mode 100644 crates/ppt-binary/src/ppt95/shape.rs 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))); + } _ => {} } } From e6c282e9428926bf2f38d4088da39b71ca1be580 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 22:49:03 -0500 Subject: [PATCH 02/10] ppt-binary: PowerPoint 95 line styles, dashes, arrowheads, flips and quarter-turn rotation PowerPoint 95 shapes now take their angle and both flips from the format record (3005 +48 and +52) rather than the geometry, which holds the outline as drawn: whole quarter-turns are folded into its box, so a box turned an odd number of them is turned back about its centre. Lines read their width from the line style (1 to 10 pt), their dots and dashes, and on lines the start and end arrowheads from the 3007 atom. The shadow colour comes from +30, with the scheme's shadow slot by default. The trapezoid, wide at the top, is now its own outline instead of a flipped preset, so a user's flip applies on top. Shadow offsets are still fixed at 6 pt. --- crates/ppt-binary/README.md | 13 +- crates/ppt-binary/src/ppt95.rs | 45 ++-- crates/ppt-binary/src/ppt95/shape.rs | 121 ++++++--- crates/ppt-binary/src/ppt95/tests.rs | 356 ++++++++++++++++++++++++--- 4 files changed, 445 insertions(+), 90 deletions(-) diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 4ec03ae78..662f66ea8 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -49,11 +49,14 @@ underline and colour (an RGB or a colour scheme slot). The text is Windows-1252. placeholders set where the default master's placeholders go, and its date, footer and slide number 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. +octagon, plus and five-point star) as DrawingML presets with their adjust values (the trapezoid, +wide at the top in PowerPoint 95, as its own outline), each with its fill (or none), its line +(or none) with its colour, its width (the six line styles, 1 to 10 pt) and its dots or dashes, +its shadow and the shadow's colour, its angle and its horizontal and vertical flips; and lines +from their start to their end, with their arrowheads. A shape turned by whole quarter-turns +keeps its unturned box. A shape that draws nothing but text is a text box. Shadow offsets are +not read yet (shadows fall 6 pt right and down, as in every file PowerPoint 95 wrote); 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/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 5756cf051..66635868f 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -12,10 +12,11 @@ //! 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. +//! 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. 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, shadow, angle and flips ([`shape`]); a box turned by an odd number +//! of quarter-turns is turned back. A shape that draws nothing but its text is a text box. //! //! 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 @@ -23,10 +24,9 @@ //! 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). +//! Not read yet: shadow offsets (no probe could move one); 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; @@ -64,6 +64,7 @@ mod rt { pub const PLACEHOLDER: u32 = 3010; pub const PLACEHOLDER_ATOM: u32 = 3011; pub const LINE: u32 = 3014; + pub const ARROWHEADS: u32 = 3007; pub const LINE_ATOM: u32 = 3015; pub const TEXT: u32 = 4001; } @@ -258,7 +259,7 @@ fn xfrm_of([l, t, right, b]: [i32; 4], size: Size) -> Xfrm { } /// 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). +/// format says (1 pt in the scheme's text and lines colour without one), with its arrowheads. 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)?); @@ -266,10 +267,13 @@ fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option { (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() }, + None => Look { line: shape::line_of(scheme[1], None), ..Look::none() }, }; // A line has no inside to fill, and its direction is in its ends. - (look.fill, look.flip_h) = (Fill::None, false); + (look.fill, look.flip_h, look.flip_v) = (Fill::None, false, false); + if let Some(heads) = r.child(rt::ARROWHEADS).filter(|_| look.line != Line::none()) { + 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 }) } @@ -283,8 +287,10 @@ 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 mut xfrm = xfrm_of(sides, size); - // The box is the unturned one; the angle is in sixteenths of a degree. - xfrm.rot = g.i32(28).map_or(0.0, |v| (f64::from(v) / 16.0).rem_euclid(360.0)); + let format = r.child(rt::FORMAT); + // The angle the user set is the format's; the geometry's is what quarter-turns leave of it. + let drawn = g.i32(28).unwrap_or(0); + shape::orient(&mut xfrm, drawn, format.and_then(|f| f.i32(48)).unwrap_or(drawn)); let placeholder = r.kind == rt::PLACEHOLDER; let ph = r.child(rt::PLACEHOLDER_ATOM).filter(|_| placeholder).and_then(|a| { let size = match a.u8(1) { @@ -297,16 +303,13 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); 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) { + // The shape code is the low byte: the bits above it orient the outline as drawn (0x60 on a + // new trapezoid), which the format's angle and flips already say. + geom = g.u8(0).and_then(|c| shape::preset(c as i8, g.i32(4), xfrm.w, xfrm.h)); + if let Some(f) = format { look = shape::look(&f, scheme); } - xfrm.flip_h = look.flip_h; + (xfrm.flip_h, xfrm.flip_v) = (look.flip_h, look.flip_v); } Some(Object { placeholder, ph, xfrm, text, geom, look, line: false }) } diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs index 51d343d70..ebe4e0c66 100644 --- a/crates/ppt-binary/src/ppt95/shape.rs +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -1,29 +1,37 @@ //! 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. +//! format record (3005) as fill, line, shadow, angle and flips, 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. +//! A format record holds the line (+0 0xFF for none, +1 its dash style, +3 its style less one, +//! which sets its width, +4 its colour), the fill (+12 0xFF for none, +20 its colour) and the +//! shadow (+28 0x00 when on and 0xFF when off, +30 its colour), then the angle the user set at +48 +//! (sixteenths of a degree) and the flips at +52 (bit 1 horizontal, bit 2 vertical). Each colour is +//! R, G, B and an index: 0xFE for the RGB itself, else a slot of the colour scheme. +//! +//! The geometry record holds the outline as drawn: whole quarter-turns of the angle are folded into +//! orientation bits above its shape code, its box and its own angle, which is only what is left +//! over. So the angle comes from the format, and the box is turned back by the quarter-turns +//! between the two ([`orient`]). A line's 3007 atom holds its arrowheads ([`arrowheads`]). -use craft_pptx::style::Shadow; -use craft_pptx::{ColorRef, Fill, Geom, Line, Rgba}; +use craft_pptx::style::{Dash, LineEnd, Shadow}; +use craft_pptx::{ColorRef, CustomPath, Fill, Geom, Line, Rgba, Xfrm}; 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. +/// The widths of line styles 1 to 6 (the format holds the style less one), in points: the pens +/// PowerPoint 95 drew them with were 8, 16, 32, 48, 64 and 80 master units wide. +const LINE_WIDTHS: [f64; 6] = [1.0, 2.0, 4.0, 6.0, 8.0, 10.0]; +/// How far a shadow falls right and down, in points. The offset can't be set through the object +/// model, so no probe moved it: this is the 48 units (6 pt) every probe's format holds at +36 and +/// +40, where the offset most likely is, and they are not read. const SHADOW_OFFSET: f64 = 6.0; +/// A whole turn in sixteenths of a degree. +const TURN: i64 = 360 * 16; /// How a shape is drawn. #[derive(Clone, Debug, PartialEq)] @@ -32,12 +40,13 @@ pub(super) struct Look { pub line: Line, pub shadow: Option, pub flip_h: bool, + pub flip_v: 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 } + Look { fill: Fill::None, line: Line::none(), shadow: None, flip_h: false, flip_v: false } } /// Whether the shape draws anything of its own (its text aside). @@ -52,16 +61,41 @@ pub(super) fn color(format: &Rec, at: usize, scheme: &Scheme) -> Option { 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 line of `color` in the style and dashes of `format`: 1 pt and solid without one, or for a +/// style or dash value no probe showed. +pub(super) fn line_of(color: Rgba, format: Option<&Rec>) -> Line { + let width = format.and_then(|f| f.u8(3)).and_then(|s| LINE_WIDTHS.get(usize::from(s))).copied().unwrap_or(1.0); + let mut line = Line::solid(ColorRef::rgb(color), width); + let dash = match format.and_then(|f| f.u8(1)) { + Some(1) => Some("sysDot"), + Some(2) => Some("dash"), + Some(3) => Some("lgDash"), + Some(4) => Some("dashDot"), + _ => None, + }; + line.dash = dash.map(|name| Dash::Preset { name: name.into() }); + line } -/// 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. +/// A line's arrowheads from its 3007 atom: +0 the start's, +1 the end's. 4 is a small swept-back +/// head, 1 a longer and wider one; 0, and any value no probe showed, is none. +pub(super) fn arrowheads(line: &mut Line, atom: &Rec) { + let end = |v: Option| { + let (kind, size) = match v? { + 4 => ("stealth", "med"), + 1 => ("triangle", "lg"), + _ => return None, + }; + Some(LineEnd { kind: kind.into(), w: size.into(), len: size.into() }) + }; + (line.head, line.tail) = (end(atom.u8(0)), end(atom.u8(1))); +} + +/// A format record as fill, line, shadow and flips (the angle is read with the box, [`orient`]). 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 { + let shadow = format.u8(28).filter(|&f| f == 0).and_then(|_| color(format, 30, scheme)).map(|c| Shadow { color: ColorRef::rgb(c), blur: 0.0, dist: SHADOW_OFFSET.hypot(SHADOW_OFFSET), @@ -74,25 +108,54 @@ pub(super) fn look(format: &Rec, scheme: &Scheme) -> Look { align: String::new(), rotate_with_shape: false, }); + let flips = format.u8(52).unwrap_or(0); 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), + line: on(0, 4).map_or_else(Line::none, |c| line_of(c, Some(format))), shadow, - flip_h: format.u8(52).is_some_and(|f| f != 0), + flip_h: flips & 1 != 0, + flip_v: flips & 2 != 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. +/// Give `xfrm`, the geometry record's box, the angle `turn` the user set, given the angle `drawn` +/// the geometry record holds (both in sixteenths of a degree). The quarter-turns between them are +/// folded into the drawn box: after an odd number of them it is the turned box, so its width and +/// height are swapped back about its centre. +pub(super) fn orient(xfrm: &mut Xfrm, drawn: i32, turn: i32) { + let quarter = TURN / 4; + let quarters = (i64::from(turn) - i64::from(drawn) + quarter / 2).div_euclid(quarter).rem_euclid(4); + if quarters % 2 == 1 { + let (cx, cy) = (xfrm.x + xfrm.w / 2.0, xfrm.y + xfrm.h / 2.0); + (xfrm.w, xfrm.h) = (xfrm.h, xfrm.w); + (xfrm.x, xfrm.y) = (cx - xfrm.w / 2.0, cy - xfrm.h / 2.0); + } + xfrm.rot = (i64::from(turn).rem_euclid(TURN) as f64) / 16.0; +} + +/// PowerPoint 95's trapezoid: wide at the top, each bottom corner inset by the adjust value (0 to +/// half the side, a quarter by default) in the shape's 21600-unit square. The same outline the +/// PowerPoint 97 path gives the trapezoid (storytold/craft-libs#2492), to be shared once that lands. +fn trapezoid(adjust: Option) -> Geom { + let a = adjust.unwrap_or(5400).clamp(0, 10800); + let d = format!("M 0 0 L {a} 21600 L {} 21600 L 21600 0 Z", 21600 - a); + Geom::Custom { paths: vec![CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] } +} + +/// The geometry for a shape code with its adjust value, in a box `w` × `h` points: a preset, or +/// the trapezoid's own outline. `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)> { +/// shorter side. +pub(super) fn preset(code: i8, adjust: Option, w: f64, h: f64) -> Option { if !(-3..=8).contains(&code) { return None; } let kind = u16::try_from(i16::from(code) + 4).ok()?; + if kind == 8 { + return Some(trapezoid(adjust)); + } 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. @@ -102,9 +165,9 @@ pub(super) fn preset(code: i8, adjust: Option, w: f64, h: f64) -> Option<(G 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)), + 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)) + Some(Geom::Preset { name: name.into(), adj: adj.into_iter().collect() }) } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 2fed4b413..ae9dedcac 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -714,46 +714,73 @@ fn coded_geometry(code: u32, adjust: i32, bx: [i32; 4], rot: i32) -> Vec { } /// 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. +/// for none), the shadow's colour when it has one, the flips (bit 1 horizontal, bit 2 vertical), +/// the line's style byte (its style less one) and dash byte, and the angle the user set. #[derive(Clone, Copy)] struct Format { line: Option<[u8; 4]>, fill: Option<[u8; 4]>, shadow: Option<[u8; 4]>, - flip_h: bool, + flips: u8, + style: u8, + dash: u8, + turn: i32, } -/// 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 }; +/// PowerPoint 95's defaults: lines in slot 1, fills in slot 4, no shadow (its colour in slot 2). +const PLAIN: Format = Format { line: Some([0, 0, 0, 1]), fill: Some([0, 0, 0, 4]), shadow: None, flips: 0, style: 0, dash: 0, turn: 0 }; fn format(f: Format) -> Vec { let mut b = vec![0u8; 56]; b[0] = if f.line.is_some() { 0 } else { 0xFF }; + b[1] = f.dash; + b[3] = f.style; 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])); + // +24 stays slot 1 whatever the shadow is, as PowerPoint 95 writes it. + b[24..28].copy_from_slice(&[0, 0, 0, 1]); b[28] = if f.shadow.is_some() { 0 } else { 0xFF }; b[29] = 1; + b[30..34].copy_from_slice(&f.shadow.unwrap_or([0, 0, 0, 2])); b[36] = 48; b[40] = 48; - b[52] = u8::from(f.flip_h); + b[48..52].copy_from_slice(&f.turn.to_le_bytes()); + b[52] = f.flips; rec(rt::FORMAT, 1, 0, &b) } -/// A shape of `code` with its adjust value, box, angle and format. +/// A shape of `code` with its adjust value, box, angle and format, its angle less than a quarter +/// turn, so the geometry and the format agree. 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)]) + drawn_shape(code, adjust, bx, rot, Format { turn: rot, ..f }) +} + +/// A shape whose geometry holds `drawn`, the box and angle as drawn, and whose format holds the +/// angle the user set. +fn drawn_shape(code: i32, adjust: i32, drawn: [i32; 4], rot: i32, f: Format) -> Vec { + container(rt::SHAPE, 0x13, &[coded_geometry(code as u32, adjust, drawn, 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])]; + arrow_line(ends, [0, 0], f) +} + +/// A line with its arrowhead atom (start, end). +fn arrow_line(ends: [i32; 4], heads: [u8; 2], f: Option) -> Vec { + let mut kids = vec![rec(rt::LINE_ATOM, 0, 0, &ends.iter().flat_map(|v| v.to_le_bytes()).collect::>()), rec(rt::ARROWHEADS, 0, 0, &heads)]; kids.extend(f.map(format)); container(rt::LINE, 0x13, &kids) } +/// PowerPoint 95's trapezoid outline with bottom corners inset by `a`. +fn trapezoid_95(a: i32) -> Geom { + let d = format!("M 0 0 L {a} 21600 L {} 21600 L 21600 0 Z", 21600 - a); + Geom::Custom { paths: vec![craft_pptx::CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] } +} + fn preset_of(s: &Shape) -> (&str, &[f64]) { match &s.geom { Geom::Preset { name, adj } => (name, adj), @@ -766,9 +793,9 @@ fn rgb(r: u8, g: u8, b: u8) -> ColorRef { } /// 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. +/// probes' adjust values are DrawingML's defaults on a square), except the trapezoid, which has its +/// own outline ([`trapezoids_are_wide_at_the_top`]); 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]; @@ -780,7 +807,7 @@ fn shape_codes_are_presets_with_their_adjust_values() { (1, 10800, "triangle", &[50_000.0]), (2, 0, "rtTriangle", &[]), (3, 5400, "parallelogram", &[25_000.0]), - (0x6004, 5400, "trapezoid", &[25_000.0]), + (0x6004, 5400, "custom", &[]), (5, 5400, "hexagon", &[25_000.0]), (6, 6326, "octagon", &[6326.0 / 21600.0 * 100_000.0]), (7, 5400, "plus", &[25_000.0]), @@ -792,9 +819,9 @@ fn shape_codes_are_presets_with_their_adjust_values() { 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.xfrm.unwrap().flip_v, "{name}"); assert!(!s.text_box && s.ph.is_none()); - assert!(craft_drawingml::preset::build(name, 144.0, 144.0, adj).is_some()); + assert!(name == "custom" || 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)], &[]); @@ -825,7 +852,7 @@ fn shapes_keep_their_fill_line_and_shadow() { 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_eq!((sh.color, sh.dir, sh.blur), (rgb(0x80, 0x80, 0x80), 45.0, 0.0), "the shadow's colour is at +30, not +24"); assert!((sh.dist - 6.0 * 2f64.sqrt()).abs() < 1e-9); // A slot of the slide's own scheme. @@ -851,7 +878,7 @@ fn shapes_keep_their_fill_line_and_shadow() { #[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 p = deck_of(vec![autoshape(-3, 0, bx, 480, PLAIN), autoshape(2, 0, bx, 0, Format { flips: 1, ..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)); @@ -915,7 +942,15 @@ fn hostile_shapes_never_panic() { 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 }; + let huge = Format { + line: Some([0, 0, 0, 0xFD]), + fill: Some([9, 9, 9, 200]), + shadow: Some([1, 1, 1, 8]), + flips: 0xFF, + style: 0xFF, + dash: 0xFF, + turn: i32::MIN, + }; 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))); @@ -929,8 +964,10 @@ fn hostile_shapes_never_panic() { } 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))]; + s.objects = vec![ + autoshape(4, 5400, bx, 480, Format { shadow: Some([0, 0, 0, 2]), flips: 3, ..PLAIN }), + arrow_line([0, 0, 576, 288], [4, 1], 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] { @@ -944,9 +981,160 @@ fn hostile_shapes_never_panic() { } } -/// The presets of the object model's shape types 1 to 12, as PowerPoint 95 rendered them. +/// The angle is the one the format holds. The geometry holds the outline as drawn, whole +/// quarter-turns folded into its box: after an odd number of them its box is the turned one, so it +/// is turned back about its centre. Less than a quarter turn, or a half turn, leaves it as it is. +#[test] +fn quarter_turns_are_turned_back() { + // A 2 in × 1 in rectangle at 1 in, 1 in; turned a quarter, it is drawn 1 in × 2 in about the + // same centre (as the rot90wide probe). + let (wide, tall) = ([-2304, -1584, -1152, -1008], [-2016, -1872, -1440, -720]); + let turned = |drawn: [i32; 4], drawn_rot: i32, turn: i32| drawn_shape(-3, 0, drawn, drawn_rot, Format { turn, ..PLAIN }); + let p = deck_of( + vec![ + turned(wide, 480, 480), + turned(tall, 0, 1440), + turned(wide, 0, 2880), + turned(tall, 0, 4320), + turned(tall, 0, -1440), + turned(wide, 480, 3360), + turned(tall, 480, 1920), + drawn_shape(2, 0, wide, 1920, Format { turn: 1920, ..PLAIN }), + turned(wide, 0, 480), + ], + &[], + ); + let got: Vec<_> = p.slides[0].shapes.iter().map(|s| (boxed(s), s.xfrm.unwrap().rot)).collect(); + let flat = (72.0, 72.0, 144.0, 72.0); + assert_eq!( + got, + [(flat, 30.0), (flat, 90.0), (flat, 180.0), (flat, 270.0), (flat, 270.0), (flat, 210.0), (flat, 120.0), (flat, 120.0), (flat, 30.0)] + ); +} + +/// The flips are the format's +52: bit 1 horizontal, bit 2 vertical. The orientation bits above +/// the geometry's shape code don't flip it. +#[test] +fn flips_come_from_the_format() { + let bx = [0, 0, 576, 576]; + let cases = [(2, 1), (2, 2), (2, 3), (0x1002, 0), (0x3002, 2), (1, 0xFC)]; + let p = deck_of(cases.iter().map(|&(code, flips)| autoshape(code, 0, bx, 0, Format { flips, ..PLAIN })).collect(), &[]); + let flips: Vec<_> = p.slides[0].shapes.iter().map(|s| (s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v)).collect(); + assert_eq!(flips, [(true, false), (false, true), (true, true), (false, false), (false, true), (false, false)]); +} + +/// PowerPoint 95's trapezoid is wide at the top: its own outline, its bottom corners inset by the +/// adjust value (up to half the side). A flip the user set flips it as any other shape. +#[test] +fn trapezoids_are_wide_at_the_top() { + let sq = [0, 0, 1152, 1152]; + let p = deck_of( + vec![ + autoshape(0x6004, 5400, sq, 0, PLAIN), + autoshape(0x6004, 2700, sq, 0, PLAIN), + autoshape(0x6004, 20_000, sq, 0, PLAIN), + autoshape(0x6004, -5, sq, 0, PLAIN), + autoshape(4, 5400, sq, 0, Format { flips: 2, ..PLAIN }), + ], + &[], + ); + let s = &p.slides[0].shapes; + let got: Vec<_> = s.iter().map(|s| (s.geom.clone(), s.xfrm.unwrap().flip_v)).collect(); + let want = [(5400, false), (2700, false), (10800, false), (0, false), (5400, true)].map(|(a, v)| (trapezoid_95(a), v)); + assert_eq!(got, want); + assert_eq!(boxed(&s[0]), (360.0, 270.0, 144.0, 144.0)); +} + +/// The line's style sets its width, 1 to 10 pt; its dash style dots or dashes it. Values no probe +/// showed are a 1 pt solid line. +#[test] +fn lines_keep_their_width_and_dashes() { + let bx = [0, 0, 576, 576]; + let styles = [0u8, 1, 2, 3, 4, 5, 6, 0xFF]; + let p = deck_of(styles.iter().map(|&style| autoshape(-3, 0, bx, 0, Format { style, ..PLAIN })).collect(), &[]); + let widths: Vec<_> = p.slides[0].shapes.iter().map(|s| s.line.as_ref().and_then(|l| l.width)).collect(); + assert_eq!(widths, [1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 1.0, 1.0].map(Some)); + + let dashes = [0u8, 1, 2, 3, 4, 5, 0xFF]; + let mut objects: Vec<_> = dashes.iter().map(|&dash| autoshape(-3, 0, bx, 0, Format { dash, ..PLAIN })).collect(); + objects.push(line_95([0, 0, 576, 0], Some(Format { dash: 2, style: 3, ..PLAIN }))); + let p = deck_of(objects, &[]); + let got: Vec<_> = p.slides[0].shapes.iter().map(|s| s.line.as_ref().and_then(|l| l.dash.clone())).collect(); + let preset = |n: &str| Some(craft_pptx::style::Dash::Preset { name: n.into() }); + assert_eq!(got, [None, preset("sysDot"), preset("dash"), preset("lgDash"), preset("dashDot"), None, None, preset("dash")]); + let line = p.slides[0].shapes[7].line.clone().unwrap(); + assert_eq!((line.width, line.fill), (Some(6.0), Some(Fill::solid(rgb(0, 0, 0))))); +} + +/// A shadow is in its own colour at +30: an RGB, or a slot of the scheme (slot 2, the shadow +/// colour, by default). +#[test] +fn shadows_keep_their_colour() { + let bx = [0, 0, 576, 576]; + let mut spec = SlideSpec::new(0x100, 16); + spec.scheme[2] = 0x445566; + spec.objects = vec![ + autoshape(-3, 0, bx, 0, Format { shadow: Some([0xFF, 0, 0, 0xFE]), ..PLAIN }), + autoshape(-3, 0, bx, 0, Format { shadow: Some([0, 0, 0, 2]), ..PLAIN }), + autoshape(-3, 0, bx, 0, Format { shadow: Some([0, 0, 0, 200]), fill: None, line: None, ..PLAIN }), + ]; + let p = deck(&[spec]); + let s = &p.slides[0].shapes; + let colours: Vec<_> = s.iter().map(|s| s.effects.as_ref().and_then(|e| e.outer_shadow.as_ref()).map(|sh| sh.color.clone())).collect(); + assert_eq!(colours, [Some(rgb(0xFF, 0, 0)), Some(rgb(0x44, 0x55, 0x66))], "a shadow of no slot draws nothing"); +} + +/// A line's 3007 atom gives its start (DrawingML's head) and end (tail) arrowheads: 4 a small +/// swept-back head, 1 a larger one; other values none. A cut atom keeps what is there. +#[test] +fn lines_keep_their_arrowheads() { + let ends = [0, 0, 1152, 0]; + let cases: [[u8; 2]; 7] = [[0, 0], [0, 4], [4, 0], [4, 4], [0, 1], [1, 9], [7, 0xFF]]; + let mut objects: Vec<_> = cases.iter().map(|&h| arrow_line(ends, h, Some(PLAIN))).collect(); + objects.push(arrow_line(ends, [4, 4], None)); + objects.push(container(rt::LINE, 0x13, &[rec(rt::LINE_ATOM, 0, 0, &le32(&[0, 0, 8, 8])), rec(rt::ARROWHEADS, 0, 0, &[4]), format(PLAIN)])); + let p = deck_of(objects, &[]); + let end = |kind: &str, size: &str| Some(craft_pptx::style::LineEnd { kind: kind.into(), w: size.into(), len: size.into() }); + let (none, stealth, big) = (None, end("stealth", "med"), end("triangle", "lg")); + let got: Vec<_> = p.slides[0].shapes.iter().map(|s| s.line.as_ref().map(|l| (l.head.clone(), l.tail.clone())).unwrap()).collect(); + assert_eq!( + got, + [ + (none.clone(), none.clone()), + (none.clone(), stealth.clone()), + (stealth.clone(), none.clone()), + (stealth.clone(), stealth.clone()), + (none.clone(), big.clone()), + (big, none.clone()), + (none.clone(), none.clone()), + (stealth.clone(), stealth.clone()), + (stealth, none), + ] + ); +} + +/// Hostile angles, flips and line bytes never panic, and every angle is finite and in 0..360. +#[test] +fn hostile_angles_never_panic() { + let bx = [i32::MIN, i32::MIN, i32::MAX, i32::MAX]; + let mut objects = vec![]; + for (drawn, turn) in [(i32::MIN, i32::MAX), (i32::MAX, i32::MIN), (0, i32::MIN), (i32::MAX, i32::MAX), (-1, 1)] { + objects.push(drawn_shape(8, i32::MAX, bx, drawn, Format { turn, flips: 0xFF, style: 0x80, dash: 0x80, ..PLAIN })); + } + objects.push(arrow_line([i32::MIN, 0, i32::MAX, 0], [0xFF, 0x80], Some(Format { style: 0xFF, dash: 0xFF, ..PLAIN }))); + let p = deck_of(objects, &[]); + assert_eq!(p.slides[0].shapes.len(), 6); + for s in &p.slides[0].shapes { + let x = s.xfrm.unwrap(); + assert!([x.x, x.y, x.w, x.h].iter().all(|v| v.is_finite())); + assert!((0.0..360.0).contains(&x.rot), "{}", x.rot); + } +} + +/// 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] = - ["rect", "roundRect", "ellipse", "diamond", "triangle", "rtTriangle", "parallelogram", "trapezoid", "hexagon", "octagon", "plus", "star5"]; + ["rect", "roundRect", "ellipse", "diamond", "triangle", "rtTriangle", "parallelogram", "custom", "hexagon", "octagon", "plus", "star5"]; /// What one PowerPoint 95 sample shows, by its case name ([`powerpoint_95_samples`]). fn check_sample(name: &str, p: &Presentation) { @@ -1016,6 +1204,11 @@ fn check_sample(name: &str, p: &Presentation) { /// 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 }; + let flips = |s: &Shape| (s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v); + // AddShape(n, 5760, 3960, 2880, 2880) in twips: 2 in square at 4 in, 2.75 in. + let square = (288.0, 198.0, 144.0, 144.0); + // AddShape(n, 1440, 1440, 2880, 1440) in twips. + let wide = (72.0, 72.0, 144.0, 72.0); match name { "base" => assert!(shapes.is_empty()), "shapes" => { @@ -1026,15 +1219,57 @@ fn check_shape_sample(name: &str, p: &Presentation) { 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}"); + if n == 8 { + // Wide at the top, as PowerPoint 95 drew it, with no flip of its own. + assert_eq!(s.geom, trapezoid_95(5400)); + } + assert_eq!(flips(s), (false, false), "{name}"); + assert_eq!(boxed(s), square, "{name}"); } - "rect" | "fill" | "fill2" | "linecolor" | "nofill" | "shadow" | "rotate" | "flip" => { + "vflip" => { + // AddShape(5) is the isosceles triangle. + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), flips(s)), (1, "triangle", wide, (false, true))); + } + "rectvflip" | "rthflip" | "rtvflip" | "rtboth" | "rtrot" | "trapvflip" | "traphflip" => { + let s = &shapes[0]; + let kind = match name { + "rectvflip" => "rect", + "trapvflip" | "traphflip" => "custom", + _ => "rtTriangle", + }; + assert_eq!((shapes.len(), preset_of(s).0, boxed(s)), (1, kind, square), "{name}"); + if kind == "custom" { + assert_eq!(s.geom, trapezoid_95(5400)); + } + let want = match name { + "rthflip" | "traphflip" => (true, false), + "rtboth" => (true, true), + "rtrot" => (false, false), + _ => (false, true), + }; + assert_eq!(flips(s), want, "{name}"); + assert_eq!(s.xfrm.unwrap().rot, if name == "rtrot" { 90.0 } else { 0.0 }, "{name}"); + } + "rot120wide" => { + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), s.xfrm.unwrap().rot), (1, "rtTriangle", wide, 120.0)); + } + _ => check_drawn_sample(name, shapes), + } +} + +/// What one PowerPoint 95 sample of a rectangle's or line's look shows, by its case name. +fn check_drawn_sample(name: &str, shapes: &[Shape]) { + let flips = |s: &Shape| (s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v); + let black = rgb(0, 0, 0); + // AddShape(n, 1440, 1440, 2880, 1440) in twips. + let wide = (72.0, 72.0, 144.0, 72.0); + match name { + "rect" | "fill" | "fill2" | "linecolor" | "nofill" | "shadow" | "rotate" | "flip" | "lineoff" | "shadowcolor" | "rot90wide" => { 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}"); + assert_eq!(boxed(s), wide, "{name}"); let fill = match name { "fill" => Fill::solid(rgb(0xFF, 0, 0)), "fill2" => Fill::solid(rgb(0, 0xFF, 0)), @@ -1042,19 +1277,70 @@ fn check_shape_sample(name: &str, p: &Presentation) { _ => 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}"); + let line = match name { + "lineoff" => craft_pptx::Line::none(), + "linecolor" => craft_pptx::Line::solid(rgb(0, 0, 0xFF), 1.0), + _ => craft_pptx::Line::solid(black.clone(), 1.0), + }; + assert_eq!(s.line, Some(line), "{name}"); + let shadow = s.effects.as_ref().and_then(|e| e.outer_shadow.as_ref()).map(|sh| sh.color.clone()); + let want = match name { + // The scheme's shadow colour, and the red the object model set (BGR 255). + "shadow" => Some(rgb(0x96, 0x96, 0x96)), + "shadowcolor" => Some(rgb(0xFF, 0, 0)), + _ => None, + }; + assert_eq!(shadow, want, "{name}"); + let rot = match name { + "rotate" => 30.0, + "rot90wide" => 90.0, + _ => 0.0, + }; + assert_eq!((s.xfrm.unwrap().rot, flips(s)), (rot, (name == "flip", false)), "{name}"); + } + _ if name.starts_with("lstyle") || name.starts_with("dash") => { + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0, boxed(s)), (1, "rect", wide), "{name}"); + let line = s.line.clone().unwrap(); + let (width, dash) = match name { + "lstyle2" => (2.0, None), + "lstyle3" => (4.0, None), + "lstyle4" => (6.0, None), + "lstyle5" => (8.0, None), + "lstyle6" => (10.0, None), + "dash1" => (1.0, Some("sysDot")), + "dash2" => (1.0, Some("dash")), + "dash3" => (1.0, Some("lgDash")), + "dash4" => (1.0, Some("dashDot")), + _ => return, + }; + let dash = dash.map(|n| craft_pptx::style::Dash::Preset { name: n.into() }); + assert_eq!((line.width, line.dash, line.fill), (Some(width), dash, Some(Fill::solid(black))), "{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))); + assert_eq!(flips(s), (false, false)); + assert_eq!(s.line, Some(craft_pptx::Line::solid(black, 1.0))); + } + "linebase" | "arrow1" | "arrow2" | "arrow3" | "arrow4" => { + let s = &shapes[0]; + // AddLine(1440, 1440, 4320, 0): 3 in across from 1 in, 1 in. + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), flips(s)), (1, "line", (72.0, 72.0, 216.0, 0.0), (false, false)), "{name}"); + let end = |kind: &str, size: &str| Some(craft_pptx::style::LineEnd { kind: kind.into(), w: size.into(), len: size.into() }); + let stealth = end("stealth", "med"); + let want = match name { + "arrow1" => (None, stealth), + "arrow2" => (stealth, None), + "arrow3" => (stealth.clone(), stealth), + "arrow4" => (None, end("triangle", "lg")), + _ => (None, None), + }; + let line = s.line.clone().unwrap(); + assert_eq!((line.head, line.tail), want, "{name}"); + assert_eq!((line.width, line.fill), (Some(1.0), Some(Fill::solid(black))), "{name}"); } _ => {} } From c8e440d125a931f87eed25f8559b19615aed684f Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 23:13:46 -0500 Subject: [PATCH 03/10] ppt-binary: PowerPoint 95 rotation direction, orientation bits, the other 12 autoshapes and shadow offset PowerPoint 95 measures angles counter-clockwise, so every angle is now negated into DrawingML's clockwise rot. For shape codes of 0 and up the transform comes from the geometry alone: the byte above the code holds counter-clockwise quarter-turns and a horizontal mirror made after them, which become a clockwise rot and a horizontal flip, with the box turned back after an odd number of quarters. The rectangle, rounded rectangle and ellipse keep taking the angle from the format, without flips. A mirrored trapezoid is the outline wide at the top, turned a half-turn further and unflipped, so its text stays upright; otherwise it is the trapezoid preset. Codes 9 to 14, the object model's shapes 13 to 24, read as right arrows (the arrow and thick arrow, in all four directions), home plate, cube, balloon and seal, with adjust values matched to what PowerPoint 95 drew. A code no probe showed is a rectangle with its fill, line and text. The shadow now falls by the format's offset at +36 and +40, clamped to 10 in, and is half transparent when +29 says so. The sample check compares each straight outline against the polygon in the rendering PowerPoint 95 saved beside its file. --- crates/ppt-binary/README.md | 21 +- crates/ppt-binary/src/ppt95.rs | 49 ++-- crates/ppt-binary/src/ppt95/shape.rs | 239 +++++++++++------ crates/ppt-binary/src/ppt95/tests.rs | 378 +++++++++++++++++++++++---- 4 files changed, 526 insertions(+), 161 deletions(-) diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 662f66ea8..2792508ba 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -47,16 +47,19 @@ 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 and lines read too: PowerPoint 95's twelve shapes (rectangle, +those of every layout. Shapes and lines read too: all 24 of PowerPoint 95's 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 (the trapezoid, -wide at the top in PowerPoint 95, as its own outline), each with its fill (or none), its line -(or none) with its colour, its width (the six line styles, 1 to 10 pt) and its dots or dashes, -its shadow and the shadow's colour, its angle and its horizontal and vertical flips; and lines -from their start to their end, with their arrowheads. A shape turned by whole quarter-turns -keeps its unturned box. A shape that draws nothing but text is a text box. Shadow offsets are -not read yet (shadows fall 6 pt right and down, as in every file PowerPoint 95 wrote); groups and -freeforms are skipped. Pictures, notes and the master's text styles come later. +octagon, plus, five-point star, the arrow and the thick arrow in their four directions, home plate, +cube, balloon and seal) as DrawingML presets with their adjust values (the trapezoid, wide at the +top in PowerPoint 95, as its own outline, so its text stays upright), each with its fill (or +none), its line (or none) with its colour, its width (the six line styles, 1 to 10 pt) and its +dots or dashes, and its shadow with the shadow's colour, offset and transparency; and lines from +their start to their end, with their arrowheads. A shape code no probe showed reads as a +rectangle. PowerPoint 95 measures angles counter-clockwise, DrawingML clockwise, so each is +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. 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 66635868f..005ab7955 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -11,12 +11,14 @@ //! //! 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 what is left of the angle after -//! whole quarter-turns, in sixteenths of a degree. 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, shadow, angle and flips ([`shape`]); a box turned by an odd number -//! of quarter-turns is turned back. A shape that draws nothing but its text is a text box. +//! (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. //! //! 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 @@ -24,9 +26,9 @@ //! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path //! does. //! -//! Not read yet: shadow offsets (no probe could move one); 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: 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; @@ -233,7 +235,7 @@ struct Object { ph: Option, xfrm: Xfrm, text: Option, - /// A shape's preset: `None` for a placeholder, or a shape code no probe showed. + /// A shape's preset (a rectangle for a shape code no probe showed): `None` for a placeholder. geom: Option, /// How a shape or line is drawn (a placeholder's is left to its layout). look: Look, @@ -269,8 +271,8 @@ fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option { Some(f) => shape::look(&f, scheme), None => Look { line: shape::line_of(scheme[1], None), ..Look::none() }, }; - // A line has no inside to fill, and its direction is in its ends. - (look.fill, look.flip_h, look.flip_v) = (Fill::None, false, false); + // A line has no inside to fill. + look.fill = Fill::None; if let Some(heads) = r.child(rt::ARROWHEADS).filter(|_| look.line != Line::none()) { shape::arrowheads(&mut look.line, &heads); } @@ -288,10 +290,15 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { let sides = [g.i32(12)?, g.i32(16)?, g.i32(20)?, g.i32(24)?]; let mut xfrm = xfrm_of(sides, size); let format = r.child(rt::FORMAT); - // The angle the user set is the format's; the geometry's is what quarter-turns leave of it. - let drawn = g.i32(28).unwrap_or(0); - shape::orient(&mut xfrm, drawn, format.and_then(|f| f.i32(48)).unwrap_or(drawn)); let placeholder = r.kind == rt::PLACEHOLDER; + // The shape code is the low byte; for codes of 0 and up the byte above it orients the outline. + let code = g.u8(0).map(|c| c as i8); + let drawn = g.i32(28).unwrap_or(0); + match code { + Some(c) if c >= 0 && !placeholder => shape::orient_drawn(&mut xfrm, g.u8(1).unwrap_or(0), drawn), + // The angle the user set is the format's; the geometry's is what quarter-turns leave of it. + _ => shape::orient(&mut xfrm, drawn, format.and_then(|f| f.i32(48)).unwrap_or(drawn)), + } let ph = r.child(rt::PLACEHOLDER_ATOM).filter(|_| placeholder).and_then(|a| { let size = match a.u8(1) { Some(1) => Some("half".into()), @@ -303,25 +310,21 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); let (mut geom, mut look) = (None, Look::none()); if !placeholder { - // The shape code is the low byte: the bits above it orient the outline as drawn (0x60 on a - // new trapezoid), which the format's angle and flips already say. - geom = g.u8(0).and_then(|c| shape::preset(c as i8, g.i32(4), xfrm.w, xfrm.h)); + geom = code.map(|c| shape::geometry(c, g.i32(4), &mut xfrm)); if let Some(f) = format { look = shape::look(&f, scheme); } - (xfrm.flip_h, xfrm.flip_v) = (look.flip_h, look.flip_v); } Some(Object { placeholder, ph, xfrm, text, geom, look, line: false }) } /// 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. +/// 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 { let Some(ph) = o.ph else { let text = o.text.filter(|t| !t.is_empty()); - if text.is_some() && (!o.look.drawn() || o.geom.is_none()) { + if text.is_some() && !o.look.drawn() { let mut xfrm = o.xfrm; (xfrm.flip_h, xfrm.flip_v) = (false, false); return Some(Shape { diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs index ebe4e0c66..01fccdb6e 100644 --- a/crates/ppt-binary/src/ppt95/shape.rs +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -1,37 +1,52 @@ //! PowerPoint 95 shapes: the shape code of a geometry record (3009) as a DrawingML preset, and a -//! format record (3005) as fill, line, shadow, angle and flips, learned from files PowerPoint 95 -//! wrote and the slides it rendered from them. +//! 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. +//! The shape code is the low byte of the geometry's first word, the [MS-ODRAW] shape type less 4, +//! so the [`geom`] table names its preset: −3 to 8 are the object model's shapes 1 to 12, and 9 +//! to 14 its shapes 13 to 24 (an arrow and a thick arrow, which turn and mirror into the other +//! three directions, a home plate, a cube, a balloon and a seal). The adjust value after it is a +//! coordinate in the shape's 21600-unit square, as OfficeArt's are. A code no probe showed is a +//! rectangle. //! //! A format record holds the line (+0 0xFF for none, +1 its dash style, +3 its style less one, //! which sets its width, +4 its colour), the fill (+12 0xFF for none, +20 its colour) and the -//! shadow (+28 0x00 when on and 0xFF when off, +30 its colour), then the angle the user set at +48 -//! (sixteenths of a degree) and the flips at +52 (bit 1 horizontal, bit 2 vertical). Each colour is -//! R, G, B and an index: 0xFE for the RGB itself, else a slot of the colour scheme. +//! shadow (+28 0x00 when on and 0xFF when off, +29 2 when semi-transparent, +30 its colour, +36 and +//! +40 how far it falls right and down in master units), then the angle the user set at +48 and +//! the flips the user set at +52. Each colour is R, G, B and an index: 0xFE for the RGB itself, +//! else a slot of the colour scheme. //! -//! The geometry record holds the outline as drawn: whole quarter-turns of the angle are folded into -//! orientation bits above its shape code, its box and its own angle, which is only what is left -//! over. So the angle comes from the format, and the box is turned back by the quarter-turns -//! between the two ([`orient`]). A line's 3007 atom holds its arrowheads ([`arrowheads`]). +//! Angles are in sixteenths of a degree and run counter-clockwise, where DrawingML's run clockwise. +//! The geometry record holds the outline as drawn: for a shape code of 0 and up, the byte above it +//! holds whole counter-clockwise quarter-turns in bits 4 and 5 and a horizontal mirror, made after +//! the turn, in bit 6; its own angle is what is left over, and its box is the outline's turned +//! box. That is all a shape needs ([`orient_drawn`]), the user's angle and flips included. The +//! 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`]). use craft_pptx::style::{Dash, LineEnd, Shadow}; -use craft_pptx::{ColorRef, CustomPath, Fill, Geom, Line, Rgba, Xfrm}; +use craft_pptx::{ColorRef, ColorTransform, CustomPath, Fill, Geom, Line, Rgba, Xfrm}; -use super::{RGB_GIVEN, Rec}; +use super::{MU, RGB_GIVEN, Rec}; use crate::convert::Scheme; use crate::geom; /// The widths of line styles 1 to 6 (the format holds the style less one), in points: the pens /// PowerPoint 95 drew them with were 8, 16, 32, 48, 64 and 80 master units wide. const LINE_WIDTHS: [f64; 6] = [1.0, 2.0, 4.0, 6.0, 8.0, 10.0]; -/// How far a shadow falls right and down, in points. The offset can't be set through the object -/// model, so no probe moved it: this is the 48 units (6 pt) every probe's format holds at +36 and -/// +40, where the offset most likely is, and they are not read. -const SHADOW_OFFSET: f64 = 6.0; -/// A whole turn in sixteenths of a degree. +/// How far a shadow falls right and down without a full format, in master units: 6 pt, the +/// default every new shape has. +const SHADOW_OFFSET: i32 = 48; +/// The farthest a shadow falls on either axis, in master units (10 in, wider than any slide), so a +/// damaged offset can't send it off to infinity. +const MAX_SHADOW_OFFSET: i32 = 5760; +/// A semi-transparent shadow's opacity, in DrawingML's 100000ths. +const SEMI_TRANSPARENT: i32 = 50_000; +/// A whole turn and a quarter-turn in sixteenths of a degree. const TURN: i64 = 360 * 16; +const QUARTER: i64 = TURN / 4; /// How a shape is drawn. #[derive(Clone, Debug, PartialEq)] @@ -39,14 +54,12 @@ pub(super) struct Look { pub fill: Fill, pub line: Line, pub shadow: Option, - pub flip_h: bool, - pub flip_v: 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, flip_v: false } + Look { fill: Fill::None, line: Line::none(), shadow: None } } /// Whether the shape draws anything of its own (its text aside). @@ -91,15 +104,30 @@ pub(super) fn arrowheads(line: &mut Line, atom: &Rec) { (line.head, line.tail) = (end(atom.u8(0)), end(atom.u8(1))); } -/// A format record as fill, line, shadow and flips (the angle is read with the box, [`orient`]). A part whose flag or colour is cut off -/// or names no scheme slot is not drawn. +/// A format record as fill, line and shadow (the angle and flips are read with the box, +/// [`orient`] and [`orient_drawn`]). 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, 30, scheme)).map(|c| Shadow { - color: ColorRef::rgb(c), + let shadow = format.u8(28).filter(|&f| f == 0).and_then(|_| color(format, 30, scheme)).map(|c| shadow_of(format, c)); + Look { + fill: on(12, 20).map_or(Fill::None, |c| Fill::solid(ColorRef::rgb(c))), + line: on(0, 4).map_or_else(Line::none, |c| line_of(c, Some(format))), + shadow, + } +} + +/// A shadow of `color` falling as far as the format's +36 (right) and +40 (down) say, in master +/// units, semi-transparent when +29 is 2: a distance and a direction clockwise from the right. +fn shadow_of(format: &Rec, color: Rgba) -> Shadow { + let offset = |at: usize| f64::from(format.i32(at).unwrap_or(SHADOW_OFFSET).clamp(-MAX_SHADOW_OFFSET, MAX_SHADOW_OFFSET)) / MU; + let (dx, dy) = (offset(36), offset(40)); + let color = ColorRef::rgb(color); + Shadow { + color: if format.u8(29) == Some(2) { color.with(ColorTransform::Alpha(SEMI_TRANSPARENT)) } else { color }, blur: 0.0, - dist: SHADOW_OFFSET.hypot(SHADOW_OFFSET), - dir: 45.0, + dist: dx.hypot(dy), + dir: dy.atan2(dx).to_degrees().rem_euclid(360.0), inner: false, sx: 1.0, sy: 1.0, @@ -107,67 +135,130 @@ pub(super) fn look(format: &Rec, scheme: &Scheme) -> Look { ky: 0.0, align: String::new(), rotate_with_shape: false, - }); - let flips = format.u8(52).unwrap_or(0); - Look { - fill: on(12, 20).map_or(Fill::None, |c| Fill::solid(ColorRef::rgb(c))), - line: on(0, 4).map_or_else(Line::none, |c| line_of(c, Some(format))), - shadow, - flip_h: flips & 1 != 0, - flip_v: flips & 2 != 0, } } -/// Give `xfrm`, the geometry record's box, the angle `turn` the user set, given the angle `drawn` -/// the geometry record holds (both in sixteenths of a degree). The quarter-turns between them are -/// folded into the drawn box: after an odd number of them it is the turned box, so its width and -/// height are swapped back about its centre. +/// Swap a box's width and height about its centre: from a box turned a quarter to the unturned. +fn turn_back(xfrm: &mut Xfrm) { + let (cx, cy) = (xfrm.x + xfrm.w / 2.0, xfrm.y + xfrm.h / 2.0); + (xfrm.w, xfrm.h) = (xfrm.h, xfrm.w); + (xfrm.x, xfrm.y) = (cx - xfrm.w / 2.0, cy - xfrm.h / 2.0); +} + +/// A counter-clockwise angle in sixteenths of a degree as DrawingML's clockwise degrees, 0 to 360. +fn clockwise(ccw: i64) -> f64 { + ((-ccw).rem_euclid(TURN) as f64) / 16.0 +} + +/// Give `xfrm`, the geometry record's box, the counter-clockwise angle `turn` the user set, given +/// the angle `drawn` the geometry record holds (both in sixteenths of a degree): for shapes whose +/// geometry has no orientation bits. The quarter-turns between the two are folded into the drawn +/// box: after an odd number of them it is the turned box, so it is turned back about its centre. pub(super) fn orient(xfrm: &mut Xfrm, drawn: i32, turn: i32) { - let quarter = TURN / 4; - let quarters = (i64::from(turn) - i64::from(drawn) + quarter / 2).div_euclid(quarter).rem_euclid(4); + let quarters = (i64::from(turn) - i64::from(drawn) + QUARTER / 2).div_euclid(QUARTER).rem_euclid(4); if quarters % 2 == 1 { - let (cx, cy) = (xfrm.x + xfrm.w / 2.0, xfrm.y + xfrm.h / 2.0); - (xfrm.w, xfrm.h) = (xfrm.h, xfrm.w); - (xfrm.x, xfrm.y) = (cx - xfrm.w / 2.0, cy - xfrm.h / 2.0); + turn_back(xfrm); } - xfrm.rot = (i64::from(turn).rem_euclid(TURN) as f64) / 16.0; + xfrm.rot = clockwise(i64::from(turn)); } -/// PowerPoint 95's trapezoid: wide at the top, each bottom corner inset by the adjust value (0 to -/// half the side, a quarter by default) in the shape's 21600-unit square. The same outline the -/// PowerPoint 97 path gives the trapezoid (storytold/craft-libs#2492), to be shared once that lands. -fn trapezoid(adjust: Option) -> Geom { +/// Give `xfrm`, the geometry record's box, the transform the orientation bits `bits` (the byte +/// above a shape code of 0 and up) and the geometry's own angle `drawn` say: the preset turned +/// `(bits >> 4) & 3` quarter-turns counter-clockwise, then mirrored across when bit 0x40 is set, +/// then turned by `drawn`, counter-clockwise, about the box's centre. The box is the outline's +/// after the quarter-turns, so after an odd number of them it is turned back. +/// +/// DrawingML flips first and then turns clockwise. Without the mirror that is no flip and the +/// whole angle negated. With it, a mirror after a counter-clockwise turn by `q` is the same as a +/// clockwise turn by `q` after the mirror, so it is a horizontal flip, turned clockwise by `q` +/// less `drawn`. +pub(super) fn orient_drawn(xfrm: &mut Xfrm, bits: u8, drawn: i32) { + let quarters = i64::from((bits >> 4) & 3) * QUARTER; + let mirror = bits & 0x40 != 0; + if bits & 0x10 != 0 { + turn_back(xfrm); + } + let ccw = if mirror { i64::from(drawn) - quarters } else { quarters + i64::from(drawn) }; + xfrm.rot = clockwise(ccw); + (xfrm.flip_h, xfrm.flip_v) = (mirror, false); +} + +/// PowerPoint 95's trapezoid flipped top to bottom, as its default is drawn: wide at the top, each +/// bottom corner inset by the adjust value (0 to half the side, a quarter by default) in the +/// shape's 21600-unit square. The same outline the PowerPoint 97 path gives the trapezoid +/// (storytold/craft-libs#2492), to be shared once that lands. +fn trapezoid_top(adjust: Option) -> Geom { let a = adjust.unwrap_or(5400).clamp(0, 10800); let d = format!("M 0 0 L {a} 21600 L {} 21600 L 21600 0 Z", 21600 - a); Geom::Custom { paths: vec![CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] } } -/// The geometry for a shape code with its adjust value, in a box `w` × `h` points: a preset, or -/// the trapezoid's own outline. `None` for a code no probe showed. +/// 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; + +/// The geometry for a shape code with its adjust value, in `xfrm`, the box already turned and +/// flipped ([`orient`], [`orient_drawn`]): a preset, or the trapezoid's own outline. A code no +/// probe showed is a rectangle. /// /// 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. -pub(super) fn preset(code: i8, adjust: Option, w: f64, h: f64) -> Option { - if !(-3..=8).contains(&code) { - return None; - } - let kind = u16::try_from(i16::from(code) + 4).ok()?; - if kind == 8 { - return Some(trapezoid(adjust)); - } - 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. +/// on each axis; a DrawingML one is a 100000 fraction of the width (the triangle's apex), the +/// height or the shorter side. Where PowerPoint 95 has no adjust value for a part, the proportion +/// is the one it drew: the arrow's shaft is half the height, the thick arrow's three quarters. +/// +/// Two shapes change `xfrm`. A mirrored trapezoid (its default) is the outline wide at the top, +/// unflipped and turned a half-turn further: a horizontal flip is a vertical one turned a +/// half-turn, and the vertical one is in the outline, so its text stays upright. The balloon's box +/// is its body only, as DrawingML's callout's is, its tail reaching out below ([`balloon`]). +pub(super) fn geometry(code: i8, adjust: Option, xfrm: &mut Xfrm) -> Geom { + let kind = u16::try_from(i16::from(code) + 4).ok().filter(|_| (-3..=14).contains(&code)); + let Some(name) = kind.and_then(geom::preset_name) else { + log::warn!("ppt: PowerPoint 95 shape code {code} is not known; read as a rectangle"); + return Geom::Preset { name: "rect".into(), adj: vec![] }; + }; + let (w, h) = (xfrm.w, xfrm.h); + let fraction = |v: i32, max: i32| f64::from(v.clamp(0, max)) / 21600.0 * 100_000.0; + // A horizontal length: 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)), - 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() }) + let across = |v: i32, max: i32| if ss > 0.0 && w.is_finite() { fraction(v, max) * w / ss } else { fraction(v, max) }; + // The length from a horizontal coordinate to the right side. + let to_right = |v: i32| across(21600 - v.clamp(0, 21600), 21600); + let adj: Vec = match (kind, adjust) { + (Some(8), _) if xfrm.flip_h => { + xfrm.flip_h = false; + xfrm.rot = (xfrm.rot + 180.0) % 360.0; + return trapezoid_top(adjust); + } + (Some(13), _) => vec![50_000.0, to_right(adjust.unwrap_or(10800))], + (Some(14), _) => vec![75_000.0, to_right(adjust.unwrap_or(10800))], + (Some(17), _) => return balloon(adjust, xfrm), + (_, None) => vec![], + (Some(2), Some(v)) => vec![geom::round_rect_adjust(v)], + (Some(5 | 16), Some(v)) => vec![fraction(v, 21600)], + (Some(7), Some(v)) => vec![across(v, 21600)], + (Some(8 | 9), Some(v)) => vec![across(v, 10800)], + (Some(10 | 11), Some(v)) => vec![fraction(v, 10800)], + (Some(15), Some(v)) => vec![to_right(v)], + _ => vec![], + }; + Geom::Preset { name: name.into(), adj } +} + +/// The balloon: a rounded body over the top five sixths of its square, with a tail from its bottom +/// edge to the square's bottom at the adjust value across (1800, a twelfth, by default). As in +/// DrawingML's callout, its box becomes the body, moved along the shape's own vertical axis so the +/// body stays where it was drawn, and the tail's tip is given from the body's centre. +fn balloon(adjust: Option, xfrm: &mut Xfrm) -> Geom { + let tip = f64::from(adjust.unwrap_or(1800).clamp(0, 21600)) / 21600.0; + let (w, h) = (xfrm.w, xfrm.h); + let body = h * BALLOON_BODY; + // The body's centre is (h − body) / 2 above the box's, on the shape's own axis, turned with it. + let (sin, cos) = xfrm.rot.to_radians().sin_cos(); + let up = (h - body) / 2.0; + let (cx, cy) = (xfrm.x + w / 2.0 + up * sin, xfrm.y + h / 2.0 - up * cos); + (xfrm.x, xfrm.y, xfrm.h) = (cx - w / 2.0, cy - body / 2.0, body); + // The corners are rounded a sixth of the square's shorter side. + let ss = w.min(body); + let radius = if ss > 0.0 && ss.is_finite() { w.min(h) / 6.0 / ss * 100_000.0 } else { 16_667.0 }; + let below = (1.0 / BALLOON_BODY - 0.5) * 100_000.0; + Geom::Preset { name: "wedgeRoundRectCallout".into(), adj: vec![(tip - 0.5) * 100_000.0, below, radius] } } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index ae9dedcac..04d103cb8 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -587,11 +587,11 @@ fn a_shape_with_text_is_a_text_box() { assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); assert!(p.slides[0].shapes[1].text_box && p.slides[0].shapes[1].ph.is_none()); - // The box is the unturned one; the angle is in sixteenths of a degree. + // The box is the unturned one; the angle is in sixteenths of a degree, counter-clockwise. let turned = container(rt::SHAPE, 0x13, &[geometry(bx, 480), simple_text(b"Box", bx, BODY)]); let p = deck_of(vec![turned], &[]); let x = p.slides[0].shapes[0].xfrm.unwrap(); - assert_eq!((x.x, x.w, x.rot), (64.75, 230.5, 30.0)); + assert_eq!((x.x, x.w, x.rot), (64.75, 230.5, 330.0)); } /// The master's placeholders place the default master's (title and body), and the footer row @@ -714,21 +714,26 @@ fn coded_geometry(code: u32, adjust: i32, bx: [i32; 4], rot: i32) -> Vec { } /// 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, the flips (bit 1 horizontal, bit 2 vertical), -/// the line's style byte (its style less one) and dash byte, and the angle the user set. +/// for none), the shadow's colour when it has one, its offset right and down and whether it is +/// semi-transparent, the flips the user set (bit 1 horizontal, bit 2 vertical), the line's style +/// byte (its style less one) and dash byte, and the angle the user set. #[derive(Clone, Copy)] struct Format { line: Option<[u8; 4]>, fill: Option<[u8; 4]>, shadow: Option<[u8; 4]>, + offset: [i32; 2], + semi: bool, flips: u8, style: u8, dash: u8, turn: i32, } -/// PowerPoint 95's defaults: lines in slot 1, fills in slot 4, no shadow (its colour in slot 2). -const PLAIN: Format = Format { line: Some([0, 0, 0, 1]), fill: Some([0, 0, 0, 4]), shadow: None, flips: 0, style: 0, dash: 0, turn: 0 }; +/// PowerPoint 95's defaults: lines in slot 1, fills in slot 4, no shadow (its colour in slot 2, +/// 6 pt right and down). +const PLAIN: Format = + Format { line: Some([0, 0, 0, 1]), fill: Some([0, 0, 0, 4]), shadow: None, offset: [48, 48], semi: false, flips: 0, style: 0, dash: 0, turn: 0 }; fn format(f: Format) -> Vec { let mut b = vec![0u8; 56]; @@ -742,10 +747,10 @@ fn format(f: Format) -> Vec { // +24 stays slot 1 whatever the shadow is, as PowerPoint 95 writes it. b[24..28].copy_from_slice(&[0, 0, 0, 1]); b[28] = if f.shadow.is_some() { 0 } else { 0xFF }; - b[29] = 1; + b[29] = if f.semi { 2 } else { 1 }; b[30..34].copy_from_slice(&f.shadow.unwrap_or([0, 0, 0, 2])); - b[36] = 48; - b[40] = 48; + b[36..40].copy_from_slice(&f.offset[0].to_le_bytes()); + b[40..44].copy_from_slice(&f.offset[1].to_le_bytes()); b[48..52].copy_from_slice(&f.turn.to_le_bytes()); b[52] = f.flips; rec(rt::FORMAT, 1, 0, &b) @@ -874,14 +879,26 @@ fn shapes_keep_their_fill_line_and_shadow() { 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. +/// A turned shape keeps its unturned box and its angle, which PowerPoint 95 measures +/// counter-clockwise and DrawingML clockwise: 30° there is 330° here. The flips the user set don't +/// flip a shape: what is drawn is in its geometry ([`orientation_bits_turn_and_mirror`]). #[test] -fn shapes_keep_their_angle_and_flip() { +fn rotation_runs_counter_clockwise() { let bx = [-2304, -1584, -1152, -1008]; - let p = deck_of(vec![autoshape(-3, 0, bx, 480, PLAIN), autoshape(2, 0, bx, 0, Format { flips: 1, ..PLAIN })], &[]); + let p = deck_of( + vec![ + autoshape(-3, 0, bx, 480, PLAIN), + autoshape(2, 0, bx, 0, Format { flips: 1, ..PLAIN }), + autoshape(9, 10800, bx, 480, PLAIN), + autoshape(-1, 0, bx, 0, Format { flips: 3, ..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)); + 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, 330.0, false)); + assert_eq!((x[1].rot, x[1].flip_h, x[1].flip_v), (0.0, false, false)); + assert_eq!((x[2].rot, x[2].flip_h, x[2].flip_v), (330.0, false, false), "the arrowrot30 probe: the tip moves up"); + assert_eq!((x[3].rot, x[3].flip_h, x[3].flip_v), (0.0, false, false)); } /// A line spans the box of its ends and is flipped to run from its start to its end, in its @@ -912,17 +929,23 @@ fn lines_keep_their_ends_and_direction() { 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. +/// A shape code no probe showed is a rectangle with its fill, line and text, whatever the bits +/// above it. #[test] -fn unknown_shape_codes_are_skipped() { +fn unknown_shape_codes_are_rectangles() { 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(); + let red = Format { fill: Some([0xFF, 0, 0, 0xFE]), ..PLAIN }; + let mut objects: Vec<_> = [-4, 15, 0x7F, -128, 0x6015, -100].iter().map(|&c| autoshape(c, 0, bx, 0, red)).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"); + assert_eq!(s.len(), 7); + for s in &s[..6] { + assert_eq!((preset_of(s), s.fill.clone(), s.text_box), (("rect", &[][..]), Some(Fill::solid(rgb(0xFF, 0, 0))), false)); + assert_eq!(s.line, Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0))); + assert_eq!(boxed(s), (360.0, 270.0, 72.0, 72.0)); + } + assert_eq!((preset_of(&s[6]).0, s[6].text_box, body_of(&s[6]).text()), ("rect", false, "Kept".into())); } /// Damaged shapes and lines never panic: truncated geometry, format and line records, huge @@ -946,6 +969,8 @@ fn hostile_shapes_never_panic() { line: Some([0, 0, 0, 0xFD]), fill: Some([9, 9, 9, 200]), shadow: Some([1, 1, 1, 8]), + offset: [i32::MIN, i32::MAX], + semi: true, flips: 0xFF, style: 0xFF, dash: 0xFF, @@ -981,9 +1006,10 @@ fn hostile_shapes_never_panic() { } } -/// The angle is the one the format holds. The geometry holds the outline as drawn, whole +/// A rectangle's angle is the one the format holds. The geometry holds the outline as drawn, whole /// quarter-turns folded into its box: after an odd number of them its box is the turned one, so it /// is turned back about its centre. Less than a quarter turn, or a half turn, leaves it as it is. +/// Angles run counter-clockwise, so each is negated. #[test] fn quarter_turns_are_turned_back() { // A 2 in × 1 in rectangle at 1 in, 1 in; turned a quarter, it is drawn 1 in × 2 in about the @@ -999,6 +1025,7 @@ fn quarter_turns_are_turned_back() { turned(tall, 0, -1440), turned(wide, 480, 3360), turned(tall, 480, 1920), + // A right triangle at 120° keeps its unturned box and the angle (the rot120wide probe). drawn_shape(2, 0, wide, 1920, Format { turn: 1920, ..PLAIN }), turned(wide, 0, 480), ], @@ -1008,43 +1035,155 @@ fn quarter_turns_are_turned_back() { let flat = (72.0, 72.0, 144.0, 72.0); assert_eq!( got, - [(flat, 30.0), (flat, 90.0), (flat, 180.0), (flat, 270.0), (flat, 270.0), (flat, 210.0), (flat, 120.0), (flat, 120.0), (flat, 30.0)] + [(flat, 330.0), (flat, 270.0), (flat, 180.0), (flat, 90.0), (flat, 90.0), (flat, 150.0), (flat, 240.0), (flat, 240.0), (flat, 330.0)] ); } -/// The flips are the format's +52: bit 1 horizontal, bit 2 vertical. The orientation bits above -/// the geometry's shape code don't flip it. +/// For shape codes of 0 and up the byte above the code orients the outline: bits 4 and 5 turn it +/// counter-clockwise by quarters, then bit 6 mirrors it across. In DrawingML (flip first, then turn +/// clockwise) a turn by q is a clockwise turn by −q, and a mirror after it a horizontal flip turned +/// clockwise by q. After an odd number of quarters the box drawn is the turned one, and is turned +/// back. The format's angle and flips don't count for these shapes: the geometry is what is drawn. #[test] -fn flips_come_from_the_format() { - let bx = [0, 0, 576, 576]; - let cases = [(2, 1), (2, 2), (2, 3), (0x1002, 0), (0x3002, 2), (1, 0xFC)]; - let p = deck_of(cases.iter().map(|&(code, flips)| autoshape(code, 0, bx, 0, Format { flips, ..PLAIN })).collect(), &[]); - let flips: Vec<_> = p.slides[0].shapes.iter().map(|s| (s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v)).collect(); - assert_eq!(flips, [(true, false), (false, true), (true, true), (false, false), (false, true), (false, false)]); +fn orientation_bits_turn_and_mirror() { + // 1 in × 2 in as drawn: unturned, 2 in × 1 in. + let tall = [-2016, -1872, -1440, -720]; + let flat = (72.0, 72.0, 144.0, 72.0); + let upright = (108.0, 36.0, 72.0, 144.0); + // The user's flips and angle are what PowerPoint 95 wrote for these: rtrot, rthflip, rtvflip, + // rtboth, rthfliprot, and the arrows' up, left and down (shape14 to shape16). + type Box = (f64, f64, f64, f64); + let cases: [(u32, i32, u8, f64, bool, Box); 8] = [ + (0x00, 0, 0, 0.0, false, upright), + (0x10, 1440, 1, 270.0, false, flat), + (0x20, 0, 3, 180.0, false, upright), + (0x30, 0, 2, 90.0, false, flat), + (0x40, 0, 0, 0.0, true, upright), + (0x50, 0, 0, 90.0, true, flat), + (0x60, 1440, 1, 180.0, true, upright), + (0x70, 0, 0, 270.0, true, flat), + ]; + for code in [2, 9] { + let shapes = + cases.iter().map(|&(bits, turn, flips, ..)| drawn_shape(code | (bits << 8) as i32, 10800, tall, 0, Format { turn, flips, ..PLAIN })); + let p = deck_of(shapes.collect(), &[]); + for (s, (bits, _, _, rot, flip_h, bx)) in p.slides[0].shapes.iter().zip(cases) { + let x = s.xfrm.unwrap(); + assert_eq!((x.rot, x.flip_h, x.flip_v, boxed(s)), (rot, flip_h, false, bx), "code {code} bits {bits:#x}"); + } + } + // What is left of the angle turns after the mirror: bits 0x50 and 30° counter-clockwise is a + // mirror turned 90° − 30° clockwise; without the mirror, 120° counter-clockwise. + let p = deck_of(vec![drawn_shape(0x5002, 0, tall, 480, PLAIN), drawn_shape(0x1002, 0, tall, 480, PLAIN)], &[]); + let x: Vec<_> = p.slides[0].shapes.iter().map(|s| s.xfrm.unwrap()).map(|x| (x.rot, x.flip_h, x.w, x.h)).collect(); + assert_eq!(x, [(60.0, true, 144.0, 72.0), (240.0, false, 144.0, 72.0)]); } -/// PowerPoint 95's trapezoid is wide at the top: its own outline, its bottom corners inset by the -/// adjust value (up to half the side). A flip the user set flips it as any other shape. +/// The trapezoid's own outline, wide at the bottom, is DrawingML's `trapezoid`; PowerPoint 95's +/// new trapezoid is that mirrored and turned a half-turn (0x60), a vertical flip. Whenever the +/// transform holds a mirror it is the outline wide at the top, unflipped and turned a half-turn +/// further, so its text stays upright; its bottom corners are inset by the adjust value (up to half +/// the side). The user's flips don't count: shape8, traphflip and trapvflip. #[test] fn trapezoids_are_wide_at_the_top() { let sq = [0, 0, 1152, 1152]; let p = deck_of( vec![ autoshape(0x6004, 5400, sq, 0, PLAIN), - autoshape(0x6004, 2700, sq, 0, PLAIN), + autoshape(0x6004, 2700, sq, 0, Format { flips: 1, ..PLAIN }), autoshape(0x6004, 20_000, sq, 0, PLAIN), autoshape(0x6004, -5, sq, 0, PLAIN), autoshape(4, 5400, sq, 0, Format { flips: 2, ..PLAIN }), + autoshape(0x2004, 5400, sq, 0, PLAIN), + autoshape(0x4004, 5400, sq, 0, PLAIN), + autoshape(0x6004, 5400, sq, 480, PLAIN), + autoshape(4, 2700, [0, 0, 1152, 576], 0, PLAIN), ], &[], ); let s = &p.slides[0].shapes; - let got: Vec<_> = s.iter().map(|s| (s.geom.clone(), s.xfrm.unwrap().flip_v)).collect(); - let want = [(5400, false), (2700, false), (10800, false), (0, false), (5400, true)].map(|(a, v)| (trapezoid_95(a), v)); + let got: Vec<_> = s.iter().map(|s| (s.geom.clone(), s.xfrm.unwrap().rot, s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v)).collect(); + let preset = |a: f64| Geom::Preset { name: "trapezoid".into(), adj: vec![a] }; + let want = [ + (trapezoid_95(5400), 0.0), + (trapezoid_95(2700), 0.0), + (trapezoid_95(10800), 0.0), + (trapezoid_95(0), 0.0), + (preset(25_000.0), 0.0), + (preset(25_000.0), 180.0), + (trapezoid_95(5400), 180.0), + (trapezoid_95(5400), 330.0), + // An inset across a box twice as wide as it is tall is twice the share of its shorter side. + (preset(25_000.0), 0.0), + ] + .map(|(g, rot)| (g, rot, false, false)); assert_eq!(got, want); assert_eq!(boxed(&s[0]), (360.0, 270.0, 144.0, 144.0)); } +/// The object model's shapes 13 to 24 are codes 9 to 14: the arrow and the thick arrow (DrawingML's +/// right arrow, its shaft half and three quarters of the height, the adjust value where its head +/// starts), the home plate (where its point starts), the cube (its depth), the balloon and the seal. +/// The adjust values and proportions are those PowerPoint 95 drew (shape13, shape17 and shape21 to +/// shape24). +#[test] +fn the_other_autoshapes_are_presets() { + let sq = [0, 0, 1152, 1152]; + let cases: [(i32, i32, &str, &[f64]); 6] = [ + (9, 10800, "rightArrow", &[50_000.0, 50_000.0]), + (10, 10800, "rightArrow", &[75_000.0, 50_000.0]), + (11, 14400, "homePlate", &[100_000.0 / 3.0]), + (12, 5400, "cube", &[25_000.0]), + (13, 1800, "wedgeRoundRectCallout", &[-100_000.0 * 5.0 / 12.0, 70_000.0, 20_000.0]), + (14, 0, "star16", &[]), + ]; + let p = deck_of(cases.iter().map(|(code, adj, ..)| autoshape(*code, *adj, sq, 0, PLAIN)).collect(), &[]); + let shapes = &p.slides[0].shapes; + assert_eq!(shapes.len(), 6); + for (s, (code, _, name, adj)) in shapes.iter().zip(cases) { + let (got, got_adj) = preset_of(s); + assert_eq!(got, name, "code {code}"); + assert_eq!(got_adj.len(), adj.len(), "code {code}"); + assert!(got_adj.iter().zip(adj).all(|(a, b)| (a - b).abs() < 1e-6), "code {code}: {got_adj:?}"); + assert!(craft_drawingml::preset::build(name, 144.0, 144.0, adj).is_some()); + // The balloon's box is its body, the top five sixths. + let want = if code == 13 { (360.0, 270.0, 144.0, 120.0) } else { (360.0, 270.0, 144.0, 144.0) }; + assert_eq!(boxed(s), want, "code {code}"); + } + // A head across a box twice as wide as it is tall is twice the share of its shorter side; an + // adjust value past the side is clamped. + let wide = [0, 0, 1152, 576]; + let p = deck_of(vec![autoshape(9, 10800, wide, 0, PLAIN), autoshape(11, -7, wide, 0, PLAIN), autoshape(12, 99_999, sq, 0, PLAIN)], &[]); + let s = &p.slides[0].shapes; + assert_eq!(preset_of(&s[0]), ("rightArrow", &[50_000.0, 100_000.0][..])); + assert_eq!(preset_of(&s[1]), ("homePlate", &[200_000.0][..])); + assert_eq!(preset_of(&s[2]), ("cube", &[100_000.0][..])); + // A balloon turned a quarter counter-clockwise: its body is left of the square's centre. + let p = deck_of(vec![autoshape(0x100D, 1800, sq, 0, PLAIN)], &[]); + let x = p.slides[0].shapes[0].xfrm.unwrap(); + assert_eq!((x.rot, x.w, x.h), (270.0, 144.0, 120.0)); + assert!((x.x + x.w / 2.0 - 420.0).abs() < 1e-9 && (x.y + x.h / 2.0 - 342.0).abs() < 1e-9, "{x:?}"); +} + +/// A shadow falls as far as the format's +36 and +40 say (master units, right and down; 6 pt each +/// by default), as a distance and a direction clockwise from the right, and is half transparent +/// when +29 is 2 (shadow, shadowoff1, shadowoff2). An absurd offset is clamped to 10 in. +#[test] +fn shadows_keep_their_offset_and_transparency() { + let bx = [0, 0, 576, 576]; + let on = |offset: [i32; 2], semi: bool| autoshape(-3, 0, bx, 0, Format { shadow: Some([0, 0, 0, 0xFE]), offset, semi, ..PLAIN }); + let p = deck_of(vec![on([48, 48], false), on([24, 80], false), on([-40, -16], true), on([i32::MIN, i32::MAX], false), on([0, 0], false)], &[]); + let got: Vec<_> = p.slides[0].shapes.iter().map(|s| s.effects.as_ref().and_then(|e| e.outer_shadow.clone()).unwrap()).collect(); + let want = [(6.0, 6.0), (3.0, 10.0), (-5.0, -2.0), (-720.0, 720.0), (0.0, 0.0)]; + for (sh, (dx, dy)) in got.iter().zip(want) { + let (x, y) = (sh.dist * sh.dir.to_radians().cos(), sh.dist * sh.dir.to_radians().sin()); + assert!((x - dx).abs() < 1e-9 && (y - dy).abs() < 1e-9, "{dx}, {dy}: {} at {}", sh.dist, sh.dir); + assert!((0.0..360.0).contains(&sh.dir)); + } + assert_eq!(got[0].color, rgb(0, 0, 0)); + assert_eq!(got[2].color, rgb(0, 0, 0).with(craft_pptx::ColorTransform::Alpha(50_000))); +} + /// The line's style sets its width, 1 to 10 pt; its dash style dots or dashes it. Values no probe /// showed are a 1 pt solid line. #[test] @@ -1226,34 +1365,70 @@ fn check_shape_sample(name: &str, p: &Presentation) { assert_eq!(flips(s), (false, false), "{name}"); assert_eq!(boxed(s), square, "{name}"); } - "vflip" => { - // AddShape(5) is the isosceles triangle. + _ if name.strip_prefix("shape").and_then(|n| n.parse::().ok()).is_some_and(|n| (13..=24).contains(&n)) => { + let n: usize = name[5..].parse().unwrap(); let s = &shapes[0]; - assert_eq!((shapes.len(), preset_of(s).0, boxed(s), flips(s)), (1, "triangle", wide, (false, true))); + let kind = ["homePlate", "cube", "wedgeRoundRectCallout", "star16"] + .get(n.saturating_sub(21)) + .filter(|_| n > 20) + .copied() + .unwrap_or("rightArrow"); + assert_eq!((shapes.len(), preset_of(s).0), (1, kind), "{name}"); + // Right, up, left and down: the up arrow turned a quarter counter-clockwise, the left one + // mirrored, the down one turned three quarters and mirrored. + let (rot, flip_h) = match n { + 14 | 18 => (270.0, false), + 15 | 19 => (0.0, true), + 16 | 20 => (270.0, true), + _ => (0.0, false), + }; + assert_eq!((s.xfrm.unwrap().rot, flips(s)), (rot, (flip_h, false)), "{name}"); + let want = if n == 23 { (288.0, 198.0, 144.0, 120.0) } else { square }; + assert_eq!(boxed(s), want, "{name}"); } - "rectvflip" | "rthflip" | "rtvflip" | "rtboth" | "rtrot" | "trapvflip" | "traphflip" => { + "vflip" => { + // AddShape(5) is the isosceles triangle; flipped, it is drawn mirrored and turned a half. + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), flips(s), s.xfrm.unwrap().rot), (1, "triangle", wide, (true, false), 180.0)); + } + "rectvflip" | "rthflip" | "rtvflip" | "rtboth" | "rtrot" | "rtrotb" | "rthfliprot" | "trapvflip" | "traphflip" => { let s = &shapes[0]; let kind = match name { "rectvflip" => "rect", - "trapvflip" | "traphflip" => "custom", + "traphflip" => "custom", + "trapvflip" => "trapezoid", _ => "rtTriangle", }; - assert_eq!((shapes.len(), preset_of(s).0, boxed(s)), (1, kind, square), "{name}"); + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), flips(s)), (1, kind, square, (false, false)), "{name}"); if kind == "custom" { assert_eq!(s.geom, trapezoid_95(5400)); } - let want = match name { - "rthflip" | "traphflip" => (true, false), - "rtboth" => (true, true), - "rtrot" => (false, false), - _ => (false, true), + // The right triangle's flips and turns are all turns of it. + let rot = match name { + "rthflip" | "rtrot" | "rtrotb" => 270.0, + "rtboth" | "rthfliprot" => 180.0, + "rtvflip" => 90.0, + _ => 0.0, }; - assert_eq!(flips(s), want, "{name}"); - assert_eq!(s.xfrm.unwrap().rot, if name == "rtrot" { 90.0 } else { 0.0 }, "{name}"); + assert_eq!(s.xfrm.unwrap().rot, rot, "{name}"); } "rot120wide" => { let s = &shapes[0]; - assert_eq!((shapes.len(), preset_of(s).0, boxed(s), s.xfrm.unwrap().rot), (1, "rtTriangle", wide, 120.0)); + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), s.xfrm.unwrap().rot), (1, "rtTriangle", wide, 240.0)); + } + "arrowrot30" => { + let s = &shapes[0]; + assert_eq!((shapes.len(), preset_of(s).0, boxed(s), s.xfrm.unwrap().rot), (1, "rightArrow", (288.0, 198.0, 144.0, 72.0), 330.0)); + } + "shadowoff1" | "shadowoff2" => { + let s = &shapes[0]; + let sh = s.effects.as_ref().and_then(|e| e.outer_shadow.clone()).unwrap(); + let (dx, dy) = (sh.dist * sh.dir.to_radians().cos(), sh.dist * sh.dir.to_radians().sin()); + // 3 pt right and 10 pt down; 5 pt left, 2 pt up and semi-transparent. + let (want, semi) = if name == "shadowoff1" { ((3.0, 10.0), false) } else { ((-5.0, -2.0), true) }; + assert!((dx - want.0).abs() < 1e-9 && (dy - want.1).abs() < 1e-9, "{name}: {dx}, {dy}"); + assert_eq!(sh.color.mods.contains(&craft_pptx::ColorTransform::Alpha(50_000)), semi, "{name}"); + assert_eq!((preset_of(s).0, boxed(s)), ("rect", (144.0, 144.0, 216.0, 144.0)), "{name}"); } _ => check_drawn_sample(name, shapes), } @@ -1291,12 +1466,13 @@ fn check_drawn_sample(name: &str, shapes: &[Shape]) { _ => None, }; assert_eq!(shadow, want, "{name}"); + // Turned counter-clockwise; a rectangle's flip doesn't change it. let rot = match name { - "rotate" => 30.0, - "rot90wide" => 90.0, + "rotate" => 330.0, + "rot90wide" => 270.0, _ => 0.0, }; - assert_eq!((s.xfrm.unwrap().rot, flips(s)), (rot, (name == "flip", false)), "{name}"); + assert_eq!((s.xfrm.unwrap().rot, flips(s)), (rot, (false, false)), "{name}"); } _ if name.starts_with("lstyle") || name.starts_with("dash") => { let s = &shapes[0]; @@ -1346,12 +1522,101 @@ fn check_drawn_sample(name: &str, shapes: &[Shape]) { } } +/// The polygons of a placeable WMF (its META_POLYGON records) in points on the slide: the WMF +/// PowerPoint 95 saved a slide as is in master units about the slide's centre, y down. +fn wmf_polygons(b: &[u8]) -> Vec> { + let word = |at: usize| b.get(at..at + 2).map(|w| i16::from_le_bytes([w[0], w[1]])); + let mut polygons = vec![]; + // The placeable header (22 bytes), then the standard one (18). + let mut at = 40; + while let (Some(size), Some(func)) = (b.get(at..at + 4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])), word(at + 4)) { + if size < 3 { + break; + } + if func == 0x0324 { + let n = word(at + 6).unwrap_or(0).max(0) as usize; + let point = |i: usize| Some((f64::from(word(at + 8 + 4 * i)?) / 8.0 + 360.0, f64::from(word(at + 10 + 4 * i)?) / 8.0 + 270.0)); + polygons.push((0..n).filter_map(point).collect()); + } + at += size as usize * 2; + } + polygons +} + +/// The corners of a shape's outline on the slide, for the presets whose outline is straight lines +/// (and the trapezoid's own outline): each flipped about the box's centre, then turned clockwise +/// about it, as DrawingML draws it. `None` for an outline with curves. +fn outline_corners(s: &Shape) -> Option> { + const STRAIGHT: [&str; 6] = ["rect", "rtTriangle", "triangle", "rightArrow", "trapezoid", "homePlate"]; + let x = s.xfrm?; + let local: Vec<(f64, f64)> = match &s.geom { + Geom::Preset { name, adj } if STRAIGHT.contains(&name.as_str()) => { + let g = craft_drawingml::preset::build(name, x.w, x.h, adj)?; + g.outline().elements().iter().filter_map(|e| e.end_point()).map(|p| (p.x, p.y)).collect() + } + Geom::Custom { paths } => { + let p = paths.first()?; + let v: Vec = p.d.split_whitespace().filter_map(|t| t.parse().ok()).collect(); + v.as_chunks::<2>().0.iter().map(|[u, v]| (u * x.w / p.w, v * x.h / p.h)).collect() + } + _ => return None, + }; + let (sin, cos) = x.rot.to_radians().sin_cos(); + let (cx, cy) = (x.x + x.w / 2.0, x.y + x.h / 2.0); + Some( + local + .into_iter() + .map(|(u, v)| { + let (mut dx, mut dy) = (u - x.w / 2.0, v - x.h / 2.0); + if x.flip_h { + dx = -dx; + } + if x.flip_v { + dy = -dy; + } + (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) + }) + .collect(), + ) +} + +/// Whether every corner of the model's outline is near a vertex of the polygon PowerPoint 95 drew, +/// and every vertex near a corner. The pen is drawn inside the frame, so the polygon sits half a +/// line width inside the outline, and its vertices are rounded to whole units. +fn outline_matches(corners: &[(f64, f64)], polygon: &[(f64, f64)], width: f64) -> bool { + let tol = width / 2.0 + 1.0; + let near = |a: &(f64, f64), set: &[(f64, f64)]| set.iter().any(|b| (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol); + polygon.len() >= 3 && corners.iter().all(|c| near(c, polygon)) && polygon.iter().all(|p| near(p, corners)) +} + +/// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a +/// straight outline matches a polygon PowerPoint 95 drew. The number of shapes checked. +fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { + let polygons = wmf_polygons(wmf); + let Some(slide) = p.slides.first() else { return 0 }; + let mut checked = 0; + for s in &slide.shapes { + let Some(corners) = outline_corners(s) else { continue }; + // A rectangle may be drawn as a rectangle record, not a polygon; a dashed line is drawn + // dash by dash. + if (polygons.is_empty() && preset_of(s).0 == "rect") || s.line.as_ref().is_some_and(|l| l.dash.is_some()) { + continue; + } + let width = s.line.as_ref().and_then(|l| l.width).unwrap_or(1.0); + let near = polygons.iter().min_by_key(|poly| poly.len().abs_diff(corners.len())); + assert!(polygons.iter().any(|poly| outline_matches(&corners, poly, width)), "{name}: {corners:?} is not drawn; nearest {near:?}"); + checked += 1; + } + checked +} + /// Real PowerPoint 95 files, when `CRAFT_PPT95_SAMPLES` names a directory of them (they are not in -/// the repository). Each imports with the slide count its DocumentAtom gives, at 10 × 7.5 in. +/// the repository). Each imports with the slide count its DocumentAtom gives, at 10 × 7.5 in, and +/// its shapes' outlines match the rendering PowerPoint 95 saved beside it, if any. #[test] fn powerpoint_95_samples() { let Some(dir) = std::env::var_os("CRAFT_PPT95_SAMPLES") else { return }; - let mut seen = 0; + let (mut seen, mut outlines) = (0, 0); for entry in std::fs::read_dir(&dir).unwrap() { let path = entry.unwrap().path(); if path.extension().is_none_or(|e| !e.eq_ignore_ascii_case("ppt")) { @@ -1366,8 +1631,11 @@ fn powerpoint_95_samples() { assert_eq!(p.slides.len(), count as usize, "{name}"); assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0), "{name}"); check_sample(&name, &p); + if let Ok(wmf) = std::fs::read(path.with_extension("wmf")) { + outlines += check_outlines(&name, &p, &wmf); + } seen += 1; } - eprintln!("read {seen} PowerPoint 95 samples"); + eprintln!("read {seen} PowerPoint 95 samples, {outlines} outlines checked against their renderings"); assert!(seen > 0); } From 79127c3c5a4e6f7a3f1063cb3be57fa5ae196066 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 23:34:47 -0500 Subject: [PATCH 04/10] ppt-binary: PowerPoint 95 freeforms and groups Freeforms (3016) now read as custom paths in their box: a move to the first point and lines to the rest from the 3035 points, closed when the low byte of the 3017 flag is 1, with the fill, line and shadow of their format and, when open, the arrowheads of their 3007 atom. Points are capped at 8192 and never read past their record; a freeform of fewer than two points is left out. Their format's angle is not read. Groups (3001) read as groups of their members, which keep their absolute slide places: the group's box is the union of its members' and is also its child space. Members are read as the page's objects are, groups included, nested at most 32 deep, and count towards the page's object cap. --- crates/ppt-binary/README.md | 5 +- crates/ppt-binary/src/ppt95.rs | 201 +++++++++++++++++---- crates/ppt-binary/src/ppt95/shape.rs | 20 ++- crates/ppt-binary/src/ppt95/tests.rs | 257 +++++++++++++++++++++++++++ 4 files changed, 451 insertions(+), 32 deletions(-) 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)); + } _ => {} } } From ec51aa9d1cf1e863f8fa5ea3a4fc41e4989c2770 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 00:38:13 -0500 Subject: [PATCH 05/10] ppt-binary: slides with their own scheme in the PowerPoint 95 shape tests don't follow the master's Two tests gave a slide its own colours while it still followed the master's scheme; since the slide box's flags are read, PowerPoint 95 marks such a slide as not following. --- crates/ppt-binary/src/ppt95/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index d6e04e12e..f5ff88c48 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1101,6 +1101,7 @@ fn shapes_keep_their_fill_line_and_shadow() { // A slot of the slide's own scheme. let mut spec = SlideSpec::new(0x100, 16); spec.scheme[4] = 0x123456; + spec.follow_scheme = false; 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)))); @@ -1450,6 +1451,7 @@ fn shadows_keep_their_colour() { let bx = [0, 0, 576, 576]; let mut spec = SlideSpec::new(0x100, 16); spec.scheme[2] = 0x445566; + spec.follow_scheme = false; spec.objects = vec![ autoshape(-3, 0, bx, 0, Format { shadow: Some([0xFF, 0, 0, 0xFE]), ..PLAIN }), autoshape(-3, 0, bx, 0, Format { shadow: Some([0, 0, 0, 2]), ..PLAIN }), From 1cf315b637977fe6de030157d1011d6dae8ac8ef Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 01:12:08 -0500 Subject: [PATCH 06/10] ppt95: text insets follow the unturned box; a balloon's text ends at its body A shape turned a quarter before its text was typed holds its box and its text rectangle turned (probes rot90thentext and rot90arrowtext). The shape's box is turned back, so the insets now move to the unturned box's edges with it. A balloon's box is its body, so its bottom inset is now measured from the body's bottom (balloontext). The samples test now reads the slide size from each file's DocumentAtom, matches outlines vertex by vertex in order, reads rectangle records as outlines too, and fails on a rendering it can't read. Tests that skipped their checks on a missing slide or shape now fail instead. --- crates/ppt-binary/README.md | 5 +- crates/ppt-binary/src/ppt95.rs | 23 +++- crates/ppt-binary/src/ppt95/shape.rs | 9 ++ crates/ppt-binary/src/ppt95/tests.rs | 150 ++++++++++++++++++++++++--- 4 files changed, 168 insertions(+), 19 deletions(-) diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index f368bdd6e..069a5bdb0 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -68,7 +68,10 @@ counter-clockwise, DrawingML clockwise, so each is negated. A shape's geometry h 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; a shape's text is -read as a text box's is. Freeforms read as custom paths through their points, in their box, with +read as a text box's is, its text rectangle measured from the edges of the shape's unturned box (a +balloon's, its body). PowerPoint 95 keeps the text of a shape turned before it was typed upright; +the text's own angle isn't read yet, so that text turns with its shape. 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 and notes come later. diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 53b1b7032..18a0efe8d 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -447,11 +447,23 @@ 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 container = r.child(rt::TEXT); - let text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); + let mut text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); + // The text rectangle is measured from the edges of the box as the geometry holds it; the + // shape's are those of the unturned box. + if let Some(t) = text.as_mut() { + unturn_insets(&mut t.body, shape::quarter_turns(&xfrm, drawn)); + } let ruler = container.and_then(|c| text::ruler_slot(&c)); let (mut geom, mut look) = (None, Look::none()); if !placeholder { + let height = xfrm.h; geom = code.map(|c| shape::geometry(c, g.i32(4), &mut xfrm)); + // A balloon's box is its body, above its tail: the text's bottom edge stays where it was. + if let Some(b) = text.as_mut().map(|t| &mut t.body) + && let Some(inset) = b.inset_b + { + b.inset_b = Some((inset - (height - xfrm.h)).max(0.0)); + } if let Some(f) = format { look = shape::look(&f, scheme); } @@ -459,6 +471,15 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { Some(Object { placeholder, ph, xfrm, text, ruler, geom, look, kind: Kind::Shape }) } +/// Insets measured from the edges of a box `quarters` quarter-turns clockwise from the shape's +/// unturned one, as insets from the unturned box's edges. Left, top, right and bottom are in +/// clockwise order, so the unturned box's edge `i` is the turned box's edge `i + quarters`. +fn unturn_insets(b: &mut craft_pptx::text::BodyProps, quarters: usize) { + let turned = [b.inset_l, b.inset_t, b.inset_r, b.inset_b]; + let edge = |i: usize| turned[(i + quarters) % 4]; + [b.inset_l, b.inset_t, b.inset_r, b.inset_b] = [edge(0), edge(1), edge(2), edge(3)]; +} + /// 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. diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs index ffdec1a66..f64efff32 100644 --- a/crates/ppt-binary/src/ppt95/shape.rs +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -145,6 +145,15 @@ fn turn_back(xfrm: &mut Xfrm) { (xfrm.x, xfrm.y) = (cx - xfrm.w / 2.0, cy - xfrm.h / 2.0); } +/// The quarter-turns clockwise, 0 to 3, that take the unturned box `xfrm` gives (after [`orient`] or +/// [`orient_drawn`]) to the box the geometry record holds: `xfrm`'s angle less the geometry's own, +/// `drawn`, which the record's box doesn't include. +pub(super) fn quarter_turns(xfrm: &Xfrm, drawn: i32) -> usize { + let cw = (xfrm.rot - clockwise(i64::from(drawn))).rem_euclid(360.0); + // 0 to 4 quarters, 4 being a whole turn. + [0, 1, 2, 3, 0][((cw / 90.0).round() as usize).min(4)] +} + /// A counter-clockwise angle in sixteenths of a degree as DrawingML's clockwise degrees, 0 to 360. fn clockwise(ccw: i64) -> f64 { ((-ccw).rem_euclid(TURN) as f64) / 16.0 diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index dabeaf67b..2cba277f8 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -601,7 +601,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 Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; + let shapes = &p.slides[0].shapes; 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)); @@ -1127,7 +1127,7 @@ fn shape_codes_are_presets_with_their_adjust_values() { (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 }; + let shapes = &p.slides[0].shapes; assert_eq!(shapes.len(), 12); for (s, (code, _, name, adj)) in shapes.iter().zip(cases) { assert_eq!(preset_of(s), (name, adj), "code {code}"); @@ -1376,6 +1376,7 @@ fn orientation_bits_turn_and_mirror() { let shapes = cases.iter().map(|&(bits, turn, flips, ..)| drawn_shape(code | (bits << 8) as i32, 10800, tall, 0, Format { turn, flips, ..PLAIN })); let p = deck_of(shapes.collect(), &[]); + assert_eq!(p.slides[0].shapes.len(), cases.len(), "code {code}"); for (s, (bits, _, _, rot, flip_h, bx)) in p.slides[0].shapes.iter().zip(cases) { let x = s.xfrm.unwrap(); assert_eq!((x.rot, x.flip_h, x.flip_v, boxed(s)), (rot, flip_h, false, bx), "code {code} bits {bits:#x}"); @@ -1484,6 +1485,7 @@ fn shadows_keep_their_offset_and_transparency() { let p = deck_of(vec![on([48, 48], false), on([24, 80], false), on([-40, -16], true), on([i32::MIN, i32::MAX], false), on([0, 0], false)], &[]); let got: Vec<_> = p.slides[0].shapes.iter().map(|s| s.effects.as_ref().and_then(|e| e.outer_shadow.clone()).unwrap()).collect(); let want = [(6.0, 6.0), (3.0, 10.0), (-5.0, -2.0), (-720.0, 720.0), (0.0, 0.0)]; + assert_eq!(got.len(), want.len()); for (sh, (dx, dy)) in got.iter().zip(want) { let (x, y) = (sh.dist * sh.dir.to_radians().cos(), sh.dist * sh.dir.to_radians().sin()); assert!((x - dx).abs() < 1e-9 && (y - dy).abs() < 1e-9, "{dx}, {dy}: {} at {}", sh.dist, sh.dir); @@ -1582,6 +1584,44 @@ fn hostile_angles_never_panic() { /// The text of a drawn shape and of a freeform keeps its anchoring, wrap, spacing and justified /// alignment, as a text box's does. +/// The text rectangle is measured from the edges of the box the geometry holds. A shape turned a +/// quarter before its text was typed holds its box turned (as `rot90thentext` and +/// `rot90arrowtext` showed), so its insets move to the unturned box's edges; a balloon's box is its +/// body, so its text's bottom inset is measured from the body's bottom (as `balloontext` showed). +#[test] +fn text_insets_follow_the_unturned_box() { + // A text rectangle `insets` (left, top, right, bottom, in master units) inside `bx`. + let text_in = |[l, t, r, b]: [i32; 4], [il, it, ir, ib]: [i32; 4]| { + text(b"Hi", &[plain(3)], &[para_run(3, false, 0, 0, 0)], 1, [l + il, t + it, r - ir, b - ib], BODY) + }; + let shape = |code: i32, bx: [i32; 4], turn: i32, insets: [i32; 4]| { + container(rt::SHAPE, 0x13, &[coded_geometry(code as u32, 1800, bx, 0), format(Format { turn, ..PLAIN }), text_in(bx, insets)]) + }; + let tall = [-288, -576, 288, 576]; + let p = deck_of( + vec![ + // A rectangle turned a quarter counter-clockwise, its box held turned. + shape(-3, tall, 1440, [66, 37, 66, 37]), + // An up arrow: a right arrow turned a quarter, its head at the turned box's top. + shape(9 | 0x1000, tall, 0, [209, 329, 208, 37]), + // Unturned: the insets stay where they are. + shape(-3, [-576, -288, 576, 288], 0, [66, 37, 66, 37]), + // A balloon in a 144 pt square: its body is the top 120 pt. + shape(13, [-576, -576, 576, 576], 0, [121, 91, 121, 307]), + ], + &[], + ); + let insets: Vec<_> = p.slides[0] + .shapes + .iter() + .map(|s| { + let b = &body_of(s).body; + (b.inset_l.unwrap(), b.inset_t.unwrap(), b.inset_r.unwrap(), b.inset_b.unwrap()) + }) + .collect(); + assert_eq!(insets, [(4.625, 8.25, 4.625, 8.25), (4.625, 26.125, 41.125, 26.0), (8.25, 4.625, 8.25, 4.625), (15.125, 11.375, 15.125, 14.375)]); +} + #[test] fn drawn_shapes_text_keeps_its_anchoring_and_spacing() { let bx = [-576, -576, 576, 576]; @@ -1956,14 +1996,55 @@ fn check_text_extras(name: &str, p: &Presentation) { } } +/// The text rectangles of the PowerPoint 95 samples with text in a turned shape or a balloon; false +/// for any other sample. +fn check_text_frame_sample(name: &str, shapes: &[Shape]) -> bool { + // AddShape(n, 1440, 1440, 2880, 1440) in twips. + let wide = (72.0, 72.0, 144.0, 72.0); + let insets = |s: &Shape| { + let b = &body_of(s).body; + (b.inset_l.unwrap(), b.inset_t.unwrap(), b.inset_r.unwrap(), b.inset_b.unwrap()) + }; + match name { + // A rectangle with text, then the same turned 90° after its text was typed: PowerPoint 95 + // keeps the box unturned and the text turns with it (4003 +16), insets 66 × 37 units. + "recttext" | "rot90text" => { + assert_eq!((boxed(&shapes[0]), insets(&shapes[0])), (wide, (8.25, 4.625, 8.25, 4.625)), "{name}"); + } + // Turned 90° before its text was typed: the box and the text rectangle are held turned + // (and the text upright), so the insets move to the unturned box's edges, the turned + // box's left becoming the top. + "rot90thentext" => { + let x = shapes[0].xfrm.unwrap(); + assert_eq!((x.rot, x.w, x.h), (270.0, 144.0, 72.0)); + assert_eq!(insets(&shapes[0]), (4.625, 8.25, 4.625, 8.25)); + } + // An up arrow with text: a right arrow turned a quarter, whose head (the turned box's top, + // 329 units in) is the unturned box's right. + "rot90arrowtext" => assert_eq!(insets(&shapes[0]), (4.625, 26.125, 41.125, 26.0)), + // A balloon's box is its body (the square's top 120 of 144 pt); its text's bottom edge, + // 307 units above the square's, is 14.375 pt above the body's. + "balloontext" => { + assert_eq!(boxed(&shapes[0]), (288.0, 198.0, 144.0, 120.0)); + assert_eq!(insets(&shapes[0]), (15.125, 11.375, 15.125, 14.375)); + } + _ => return false, + } + true +} + /// What one PowerPoint 95 shape sample shows, by its case name. fn check_shape_sample(name: &str, p: &Presentation) { + // Every sample comes here; one with no slide has no shapes to check. let Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; let flips = |s: &Shape| (s.xfrm.unwrap().flip_h, s.xfrm.unwrap().flip_v); // AddShape(n, 5760, 3960, 2880, 2880) in twips: 2 in square at 4 in, 2.75 in. let square = (288.0, 198.0, 144.0, 144.0); // AddShape(n, 1440, 1440, 2880, 1440) in twips. let wide = (72.0, 72.0, 144.0, 72.0); + if check_text_frame_sample(name, shapes) { + return; + } match name { "base" => assert!(shapes.is_empty()), "shapes" => { @@ -2174,9 +2255,10 @@ fn check_object_sample(name: &str, shapes: &[Shape]) { } } -/// The polygons of a placeable WMF (its META_POLYGON records) in points on the slide: the WMF -/// PowerPoint 95 saved a slide as is in master units about the slide's centre, y down. -fn wmf_polygons(b: &[u8]) -> Vec> { +/// The polygons of a placeable WMF (its META_POLYGON records, and its META_RECTANGLE records as +/// four corners) in points on a slide of size `slide`: the WMF PowerPoint 95 saved a slide as is in +/// master units about the slide's centre, y down. +fn wmf_polygons(b: &[u8], slide: craft_pptx::Size) -> Vec> { let word = |at: usize| b.get(at..at + 2).map(|w| i16::from_le_bytes([w[0], w[1]])); let mut polygons = vec![]; // The placeable header (22 bytes), then the standard one (18). @@ -2185,11 +2267,18 @@ fn wmf_polygons(b: &[u8]) -> Vec> { if size < 3 { break; } + let pt = |x: i16, y: i16| (f64::from(x) / 8.0 + slide.width / 2.0, f64::from(y) / 8.0 + slide.height / 2.0); if func == 0x0324 { let n = word(at + 6).unwrap_or(0).max(0) as usize; - let point = |i: usize| Some((f64::from(word(at + 8 + 4 * i)?) / 8.0 + 360.0, f64::from(word(at + 10 + 4 * i)?) / 8.0 + 270.0)); + let point = |i: usize| Some(pt(word(at + 8 + 4 * i)?, word(at + 10 + 4 * i)?)); polygons.push((0..n).filter_map(point).collect()); } + // Its parameters are in reverse order: bottom, right, top, left. + if func == 0x041B + && let (Some(bottom), Some(right), Some(top), Some(left)) = (word(at + 6), word(at + 8), word(at + 10), word(at + 12)) + { + polygons.push(vec![pt(left, top), pt(right, top), pt(right, bottom), pt(left, bottom)]); + } at += size as usize * 2; } polygons @@ -2232,26 +2321,50 @@ fn outline_corners(s: &Shape) -> Option> { ) } -/// Whether every corner of the model's outline is near a vertex of the polygon PowerPoint 95 drew, -/// and every vertex near a corner. The pen is drawn inside the frame, so the polygon sits half a -/// line width inside the outline, and its vertices are rounded to whole units. +/// Whether the model's outline and the polygon PowerPoint 95 drew have the same vertices in the same +/// order, from any vertex and in either direction. The pen is drawn inside the frame, so the +/// polygon sits half a line width inside the outline, and its vertices are rounded to whole units. fn outline_matches(corners: &[(f64, f64)], polygon: &[(f64, f64)], width: f64) -> bool { let tol = width / 2.0 + 1.0; - let near = |a: &(f64, f64), set: &[(f64, f64)]| set.iter().any(|b| (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol); - polygon.len() >= 3 && corners.iter().all(|c| near(c, polygon)) && polygon.iter().all(|p| near(p, corners)) + let same = |a: &(f64, f64), b: &(f64, f64)| (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol; + // Each vertex once: no repeats in a row, and no closing repeat of the first. + let ring = |v: &[(f64, f64)]| { + let mut out: Vec<(f64, f64)> = vec![]; + for p in v { + if out.last().is_none_or(|q| !same(p, q)) { + out.push(*p); + } + } + if out.len() > 1 && same(&out[0], &out[out.len() - 1]) { + out.pop(); + } + out + }; + let (a, b) = (ring(corners), ring(polygon)); + let n = a.len(); + n >= 3 && b.len() == n && (0..n).any(|k| (0..n).all(|i| same(&a[i], &b[(k + i) % n])) || (0..n).all(|i| same(&a[i], &b[(k + n - i) % n]))) +} + +/// The outline check compares vertices in order: from any vertex, either way round, with or +/// without a closing repeat, but a crossed contour through the same vertices is not a match. +#[test] +fn outlines_match_in_order() { + let square = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + assert!(outline_matches(&square, &[(10.0, 10.0), (10.0, 0.0), (0.0, 0.0), (0.0, 10.0), (10.0, 10.0)], 1.0)); + assert!(!outline_matches(&square, &[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)], 1.0)); + assert!(!outline_matches(&square, &square[..3], 1.0)); } /// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a /// straight outline matches a polygon PowerPoint 95 drew. The number of shapes checked. fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { - let polygons = wmf_polygons(wmf); + let polygons = wmf_polygons(wmf, p.slide_size); let Some(slide) = p.slides.first() else { return 0 }; let mut checked = 0; for s in &slide.shapes { let Some(corners) = outline_corners(s) else { continue }; - // A rectangle may be drawn as a rectangle record, not a polygon; a dashed line is drawn - // dash by dash. - if (polygons.is_empty() && preset_of(s).0 == "rect") || s.line.as_ref().is_some_and(|l| l.dash.is_some()) { + // A dashed line is drawn dash by dash. + if s.line.as_ref().is_some_and(|l| l.dash.is_some()) { continue; } let width = s.line.as_ref().and_then(|l| l.width).unwrap_or(1.0); @@ -2300,8 +2413,11 @@ fn powerpoint_95_samples() { let side = |at: usize| f64::from(atom.u32(at).unwrap()) / 8.0; assert_eq!((p.slide_size.width, p.slide_size.height), (side(0), side(4)), "{name}"); check_sample(&name, &p); - if let Ok(wmf) = std::fs::read(path.with_extension("wmf")) { - outlines += check_outlines(&name, &p, &wmf); + // The rendering is optional; one that is there but can't be read is a failure. + match std::fs::read(path.with_extension("wmf")) { + Ok(wmf) => outlines += check_outlines(&name, &p, &wmf), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => panic!("{name}.wmf: {e}"), } seen += 1; } From 883fafe72a22f97a47af7019c5d4898c5d3c24d1 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:05:01 -0500 Subject: [PATCH 07/10] ppt95: text in a turned box keeps its own angle PowerPoint 95 lays a shape's text out in the box the geometry holds, turned by the text's own angle (4003 +16, the geometry's own angle in every probe). Quarter-turns folded into that box don't turn the text: a shape turned a quarter before its text was typed draws it upright, and one turned on to 120 degrees after that draws it at 30 (probes wrap-before, wrap-mix, wrap-arrow, with word wrap set in the Text Anchor dialog). When the shape's box is turned back, its text is now upright at that angle, with its insets on the held box's edges. That replaces remapping the insets: in PowerPoint 16, upright text with these insets breaks into the same lines at the same places as PowerPoint 95's renderings, while remapped insets put an up arrow's text 18 pt off. A balloon's body cut is taken from whichever edge of the held box its tail is on. --- crates/ppt-binary/README.md | 11 ++-- crates/ppt-binary/src/ppt95.rs | 35 +++++------ crates/ppt-binary/src/ppt95/shape.rs | 2 +- crates/ppt-binary/src/ppt95/tests.rs | 93 +++++++++++++++++++--------- crates/ppt-binary/src/ppt95/text.rs | 7 +++ 5 files changed, 95 insertions(+), 53 deletions(-) diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 069a5bdb0..43bca4c0a 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -68,10 +68,13 @@ counter-clockwise, DrawingML clockwise, so each is negated. A shape's geometry h 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; a shape's text is -read as a text box's is, its text rectangle measured from the edges of the shape's unturned box (a -balloon's, its body). PowerPoint 95 keeps the text of a shape turned before it was typed upright; -the text's own angle isn't read yet, so that text turns with its shape. Freeforms read as custom -paths through their points, in their box, with +read as a text box's is. PowerPoint 95 lays it out in the box the geometry holds, turned by the +text's own angle, so the text of a shape turned before it was typed stays upright: such text is +`upright`, at its own angle, with its insets on that box's edges (a balloon's measured from its +body). A preset with a text rectangle of its own, such as an arrow's shaft, applies the insets +inside that rectangle, where PowerPoint 95 measures them from the whole box, so such text can sit +off from where PowerPoint 95 puts it. 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 and notes come later. diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 18a0efe8d..537c0f878 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -448,21 +448,29 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { }); let container = r.child(rt::TEXT); let mut text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); - // The text rectangle is measured from the edges of the box as the geometry holds it; the - // shape's are those of the unturned box. - if let Some(t) = text.as_mut() { - unturn_insets(&mut t.body, shape::quarter_turns(&xfrm, drawn)); + // PowerPoint 95 lays a shape's text out in the box the geometry holds, turned by the text's own + // angle (4003 +16, the geometry's own angle in every probe): quarter-turns folded into that box + // don't turn the text. When the shape's box was turned back, the text is upright on the slide, + // at that angle, with its insets on the held box's edges by name, as PowerPoint lays out + // `upright` text (checked in PowerPoint 16 against PowerPoint 95's renderings). + let quarters = shape::quarter_turns(&xfrm, drawn); + if let Some(t) = text.as_mut().filter(|_| quarters != 0) { + let angle = container.and_then(|c| text::angle(&c)).unwrap_or(drawn); + t.body.upright = Some(true); + t.body.rot = Some(shape::clockwise(i64::from(angle))).filter(|r| *r != 0.0); } let ruler = container.and_then(|c| text::ruler_slot(&c)); let (mut geom, mut look) = (None, Look::none()); if !placeholder { let height = xfrm.h; geom = code.map(|c| shape::geometry(c, g.i32(4), &mut xfrm)); - // A balloon's box is its body, above its tail: the text's bottom edge stays where it was. - if let Some(b) = text.as_mut().map(|t| &mut t.body) - && let Some(inset) = b.inset_b - { - b.inset_b = Some((inset - (height - xfrm.h)).max(0.0)); + // A balloon's box is its body, above its tail: the text's edge there stays where it was. The + // cut is the shape's bottom, which is the held box's edge `quarters` on from the bottom. + if let Some(b) = text.as_mut().map(|t| &mut t.body).filter(|_| height != xfrm.h) { + let inset = [&mut b.inset_l, &mut b.inset_t, &mut b.inset_r, &mut b.inset_b].into_iter().nth((3 + quarters) % 4); + if let Some(inset) = inset { + *inset = inset.map(|v| (v - (height - xfrm.h)).max(0.0)); + } } if let Some(f) = format { look = shape::look(&f, scheme); @@ -471,15 +479,6 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { Some(Object { placeholder, ph, xfrm, text, ruler, geom, look, kind: Kind::Shape }) } -/// Insets measured from the edges of a box `quarters` quarter-turns clockwise from the shape's -/// unturned one, as insets from the unturned box's edges. Left, top, right and bottom are in -/// clockwise order, so the unturned box's edge `i` is the turned box's edge `i + quarters`. -fn unturn_insets(b: &mut craft_pptx::text::BodyProps, quarters: usize) { - let turned = [b.inset_l, b.inset_t, b.inset_r, b.inset_b]; - let edge = |i: usize| turned[(i + quarters) % 4]; - [b.inset_l, b.inset_t, b.inset_r, b.inset_b] = [edge(0), edge(1), edge(2), edge(3)]; -} - /// 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. diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs index f64efff32..b2ef866df 100644 --- a/crates/ppt-binary/src/ppt95/shape.rs +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -155,7 +155,7 @@ pub(super) fn quarter_turns(xfrm: &Xfrm, drawn: i32) -> usize { } /// A counter-clockwise angle in sixteenths of a degree as DrawingML's clockwise degrees, 0 to 360. -fn clockwise(ccw: i64) -> f64 { +pub(super) fn clockwise(ccw: i64) -> f64 { ((-ccw).rem_euclid(TURN) as f64) / 16.0 } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index f0870a3ac..891340064 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1601,42 +1601,65 @@ fn hostile_angles_never_panic() { /// The text of a drawn shape and of a freeform keeps its anchoring, wrap, spacing and justified /// alignment, as a text box's does. -/// The text rectangle is measured from the edges of the box the geometry holds. A shape turned a -/// quarter before its text was typed holds its box turned (as `rot90thentext` and -/// `rot90arrowtext` showed), so its insets move to the unturned box's edges; a balloon's box is its -/// body, so its text's bottom inset is measured from the body's bottom (as `balloontext` showed). +/// PowerPoint 95 lays a shape's text out in the box the geometry holds, turned by the text's own +/// angle (4003 +16): a shape turned a quarter before its text was typed holds its box turned and +/// draws its text upright (`wrap-before`, `rot90arrowtext`), one turned on to 120° after that draws +/// it at the 30° its geometry holds (`wrap-mix`), and one turned after its text was typed turns +/// its text with it (`wrap-after`). The insets stay on the held box's edges, as PowerPoint lays +/// out `upright` text. A balloon's box is its body, so the inset at its bottom is measured from +/// the body (`balloontext`). #[test] -fn text_insets_follow_the_unturned_box() { - // A text rectangle `insets` (left, top, right, bottom, in master units) inside `bx`. - let text_in = |[l, t, r, b]: [i32; 4], [il, it, ir, ib]: [i32; 4]| { - text(b"Hi", &[plain(3)], &[para_run(3, false, 0, 0, 0)], 1, [l + il, t + it, r - ir, b - ib], BODY) +fn text_in_a_turned_box_keeps_its_own_angle() { + // A text rectangle `insets` (left, top, right, bottom, in master units) inside `bx`, drawn at + // `angle` (sixteenths of a degree, counter-clockwise). + let text_in = |[l, t, r, b]: [i32; 4], [il, it, ir, ib]: [i32; 4], angle: i32| { + let mut t = text(b"Hi", &[plain(3)], &[para_run(3, false, 0, 0, 0)], 1, [l + il, t + it, r - ir, b - ib], BODY); + let at = t.windows(4).position(|w| w == 4003u32.to_le_bytes()).unwrap() + 16 + 16; + t[at..at + 4].copy_from_slice(&angle.to_le_bytes()); + t }; - let shape = |code: i32, bx: [i32; 4], turn: i32, insets: [i32; 4]| { - container(rt::SHAPE, 0x13, &[coded_geometry(code as u32, 1800, bx, 0), format(Format { turn, ..PLAIN }), text_in(bx, insets)]) + let shape = |code: i32, bx: [i32; 4], drawn: i32, turn: i32, insets: [i32; 4]| { + container(rt::SHAPE, 0x13, &[coded_geometry(code as u32, 1800, bx, drawn), format(Format { turn, ..PLAIN }), text_in(bx, insets, drawn)]) }; - let tall = [-288, -576, 288, 576]; + let (tall, wide) = ([-288, -576, 288, 576], [-576, -288, 576, 288]); let p = deck_of( vec![ - // A rectangle turned a quarter counter-clockwise, its box held turned. - shape(-3, tall, 1440, [66, 37, 66, 37]), - // An up arrow: a right arrow turned a quarter, its head at the turned box's top. - shape(9 | 0x1000, tall, 0, [209, 329, 208, 37]), - // Unturned: the insets stay where they are. - shape(-3, [-576, -288, 576, 288], 0, [66, 37, 66, 37]), + // A rectangle turned a quarter counter-clockwise before its text: its box held turned. + shape(-3, tall, 0, 1440, [66, 37, 66, 37]), + // The same turned on to 120°: the geometry holds the 30° left over. + shape(-3, tall, 480, 1920, [66, 37, 66, 37]), + // An up arrow: a right arrow turned a quarter, its head at the held box's top. + shape(9 | 0x1000, tall, 0, 0, [209, 329, 208, 37]), + // Turned after its text: the geometry holds the box unturned and the whole angle. + shape(-3, wide, 1440, 1440, [66, 37, 66, 37]), // A balloon in a 144 pt square: its body is the top 120 pt. - shape(13, [-576, -576, 576, 576], 0, [121, 91, 121, 307]), + shape(13, [-576, -576, 576, 576], 0, 0, [121, 91, 121, 307]), ], &[], ); - let insets: Vec<_> = p.slides[0] + let got: Vec<_> = p.slides[0] .shapes .iter() .map(|s| { let b = &body_of(s).body; - (b.inset_l.unwrap(), b.inset_t.unwrap(), b.inset_r.unwrap(), b.inset_b.unwrap()) + (s.xfrm.unwrap().rot, b.upright, b.rot, (b.inset_l.unwrap(), b.inset_t.unwrap(), b.inset_r.unwrap(), b.inset_b.unwrap())) }) .collect(); - assert_eq!(insets, [(4.625, 8.25, 4.625, 8.25), (4.625, 26.125, 41.125, 26.0), (8.25, 4.625, 8.25, 4.625), (15.125, 11.375, 15.125, 14.375)]); + assert_eq!( + got, + [ + (270.0, Some(true), None, (8.25, 4.625, 8.25, 4.625)), + (240.0, Some(true), Some(330.0), (8.25, 4.625, 8.25, 4.625)), + (270.0, Some(true), None, (26.125, 41.125, 26.0, 4.625)), + (270.0, None, None, (8.25, 4.625, 8.25, 4.625)), + (0.0, None, None, (15.125, 11.375, 15.125, 14.375)), + ] + ); + // A balloon turned a quarter counter-clockwise: its body is cut from the shape's bottom, the + // held box's right, where its tail is. + let p = deck_of(vec![shape(13 | 0x1000, [-576, -576, 576, 576], 0, 0, [91, 121, 307, 121])], &[]); + let b = &body_of(&p.slides[0].shapes[0]).body; + assert_eq!((b.upright, b.inset_l, b.inset_t, b.inset_r, b.inset_b), (Some(true), Some(11.375), Some(15.125), Some(14.375), Some(15.125))); } #[test] @@ -2019,8 +2042,8 @@ fn check_text_extras(name: &str, p: &Presentation) { } } -/// The text rectangles of the PowerPoint 95 samples with text in a turned shape or a balloon; false -/// for any other sample. +/// The text of the PowerPoint 95 samples with text in a turned shape or a balloon: its insets and +/// whether it is drawn upright; false for any other sample. fn check_text_frame_sample(name: &str, shapes: &[Shape]) -> bool { // AddShape(n, 1440, 1440, 2880, 1440) in twips. let wide = (72.0, 72.0, 144.0, 72.0); @@ -2028,23 +2051,33 @@ fn check_text_frame_sample(name: &str, shapes: &[Shape]) -> bool { let b = &body_of(s).body; (b.inset_l.unwrap(), b.inset_t.unwrap(), b.inset_r.unwrap(), b.inset_b.unwrap()) }; + let upright = |s: &Shape| (body_of(s).body.upright, body_of(s).body.rot); match name { // A rectangle with text, then the same turned 90° after its text was typed: PowerPoint 95 // keeps the box unturned and the text turns with it (4003 +16), insets 66 × 37 units. "recttext" | "rot90text" => { assert_eq!((boxed(&shapes[0]), insets(&shapes[0])), (wide, (8.25, 4.625, 8.25, 4.625)), "{name}"); } - // Turned 90° before its text was typed: the box and the text rectangle are held turned - // (and the text upright), so the insets move to the unturned box's edges, the turned - // box's left becoming the top. + // Turned 90° before its text was typed: the box and the text rectangle are held turned and + // the text is drawn upright, its insets on the held box's edges. "rot90thentext" => { let x = shapes[0].xfrm.unwrap(); assert_eq!((x.rot, x.w, x.h), (270.0, 144.0, 72.0)); - assert_eq!(insets(&shapes[0]), (4.625, 8.25, 4.625, 8.25)); + assert_eq!((upright(&shapes[0]), insets(&shapes[0])), ((Some(true), None), (8.25, 4.625, 8.25, 4.625))); } - // An up arrow with text: a right arrow turned a quarter, whose head (the turned box's top, - // 329 units in) is the unturned box's right. - "rot90arrowtext" => assert_eq!(insets(&shapes[0]), (4.625, 26.125, 41.125, 26.0)), + // An up arrow with text: a right arrow turned a quarter, its head at the held box's top + // (329 units in), its text upright. + "rot90arrowtext" | "wrap-arrow" => { + assert_eq!((upright(&shapes[0]), insets(&shapes[0])), ((Some(true), None), (26.125, 41.125, 26.0, 4.625)), "{name}"); + } + // Wrapping text (the Text Anchor dialog's word wrap): drawn upright in the held box when + // turned before it was typed, turned with the shape when turned after, and at the 30° the + // geometry holds when turned a quarter, typed, then turned on to 120° (`rotmix2` likewise). + // Turned 30°, typed, then on to 90° (`rotmix`), the geometry holds the box unturned and the + // whole angle, and the text turns with the shape. + "wrap-none" | "wrap-after" | "rotmix" | "rot30text" => assert_eq!(upright(&shapes[0]), (None, None), "{name}"), + "wrap-before" => assert_eq!(upright(&shapes[0]), (Some(true), None)), + "wrap-mix" | "rotmix2" => assert_eq!(upright(&shapes[0]), (Some(true), Some(330.0)), "{name}"), // A balloon's box is its body (the square's top 120 of 144 pt); its text's bottom edge, // 307 units above the square's, is 14.375 pt above the body's. "balloontext" => { diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index 3e31e8b71..4e79ac8ac 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -147,6 +147,13 @@ pub(super) fn master_style(env: &Env, scheme: &Scheme, ty: usize, ruler: Option< Some(ls) } +/// The angle a text container's text is drawn at (4003 +16), counter-clockwise in sixteenths of a +/// degree: the geometry's own angle in every probe, whatever quarter-turns its box holds. +pub(super) fn angle(container: &Rec) -> Option { + let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?; + body.child(rt::TEXT_ATOM)?.i32(16) +} + /// The ruler slot a text container's body names. pub(super) fn ruler_slot(container: &Rec) -> Option { let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?; From ebd664b8beeab50e78ed53daa41effbc8507eeca Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:14:43 -0500 Subject: [PATCH 08/10] ppt95 tests: read each WMF record within its size; drop only repeated outline vertices The samples test's WMF reader took a polygon's points and a rectangle's sides at fixed offsets, so a record shorter than its count read on into the next one. Each record is now sliced to its stated size and skipped when its values don't fit. The outline matcher merged neighbouring vertices within the pen's tolerance before comparing, so a narrow rectangle drawn with a wide pen lost the corners of its short edges. Only exact repeats are dropped now; the tolerance is for the comparison. --- crates/ppt-binary/src/ppt95/tests.rs | 73 ++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 19 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 127270b1f..f16e187b6 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2328,27 +2328,32 @@ fn check_object_sample(name: &str, shapes: &[Shape]) { /// four corners) in points on a slide of size `slide`: the WMF PowerPoint 95 saved a slide as is in /// master units about the slide's centre, y down. fn wmf_polygons(b: &[u8], slide: craft_pptx::Size) -> Vec> { - let word = |at: usize| b.get(at..at + 2).map(|w| i16::from_le_bytes([w[0], w[1]])); let mut polygons = vec![]; // The placeable header (22 bytes), then the standard one (18). let mut at = 40; - while let (Some(size), Some(func)) = (b.get(at..at + 4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])), word(at + 4)) { - if size < 3 { - break; - } + // Each record is read only within its size (in 16-bit words), so a short one can't take its + // values from the next. + while let Some(size) = b.get(at..at + 4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]]) as usize) { + let Some(rec) = b.get(at..at + size * 2).filter(|_| size >= 3) else { break }; + let word = |i: usize| rec.get(i..i + 2).map(|w| i16::from_le_bytes([w[0], w[1]])); let pt = |x: i16, y: i16| (f64::from(x) / 8.0 + slide.width / 2.0, f64::from(y) / 8.0 + slide.height / 2.0); - if func == 0x0324 { - let n = word(at + 6).unwrap_or(0).max(0) as usize; - let point = |i: usize| Some(pt(word(at + 8 + 4 * i)?, word(at + 10 + 4 * i)?)); - polygons.push((0..n).filter_map(point).collect()); + match word(4).map(|f| f as u16) { + // META_POLYGON: a count, then that many points; one whose points don't fit is skipped. + Some(0x0324) => { + let n = word(6).unwrap_or(0).max(0) as usize; + if 8 + 4 * n <= rec.len() { + polygons.push((0..n).filter_map(|i| Some(pt(word(8 + 4 * i)?, word(10 + 4 * i)?))).collect()); + } + } + // META_RECTANGLE: bottom, right, top and left, in that order. + Some(0x041B) => { + if let (Some(bottom), Some(right), Some(top), Some(left)) = (word(6), word(8), word(10), word(12)) { + polygons.push(vec![pt(left, top), pt(right, top), pt(right, bottom), pt(left, bottom)]); + } + } + _ => {} } - // Its parameters are in reverse order: bottom, right, top, left. - if func == 0x041B - && let (Some(bottom), Some(right), Some(top), Some(left)) = (word(at + 6), word(at + 8), word(at + 10), word(at + 12)) - { - polygons.push(vec![pt(left, top), pt(right, top), pt(right, bottom), pt(left, bottom)]); - } - at += size as usize * 2; + at += size * 2; } polygons } @@ -2396,15 +2401,18 @@ fn outline_corners(s: &Shape) -> Option> { fn outline_matches(corners: &[(f64, f64)], polygon: &[(f64, f64)], width: f64) -> bool { let tol = width / 2.0 + 1.0; let same = |a: &(f64, f64), b: &(f64, f64)| (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol; - // Each vertex once: no repeats in a row, and no closing repeat of the first. + // Each vertex once: no repeats in a row, and no closing repeat of the first. Only a vertex + // repeated is dropped; the pen's tolerance is for comparing the two outlines, not for merging + // the close corners of a narrow one. + let repeat = |a: &(f64, f64), b: &(f64, f64)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6; let ring = |v: &[(f64, f64)]| { let mut out: Vec<(f64, f64)> = vec![]; for p in v { - if out.last().is_none_or(|q| !same(p, q)) { + if out.last().is_none_or(|q| !repeat(p, q)) { out.push(*p); } } - if out.len() > 1 && same(&out[0], &out[out.len() - 1]) { + if out.len() > 1 && repeat(&out[0], &out[out.len() - 1]) { out.pop(); } out @@ -2422,6 +2430,33 @@ fn outlines_match_in_order() { assert!(outline_matches(&square, &[(10.0, 10.0), (10.0, 0.0), (0.0, 0.0), (0.0, 10.0), (10.0, 10.0)], 1.0)); assert!(!outline_matches(&square, &[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)], 1.0)); assert!(!outline_matches(&square, &square[..3], 1.0)); + // A 2 pt-wide rectangle drawn with a 1 pt pen: the drawn corners sit half a point inside, and + // its short edges' corners are within the tolerance of each other but stay four vertices. + let narrow = [(0.0, 0.0), (2.0, 0.0), (2.0, 10.0), (0.0, 10.0)]; + assert!(outline_matches(&narrow, &[(0.5, 0.5), (1.5, 0.5), (1.5, 9.5), (0.5, 9.5)], 1.0)); +} + +/// The WMF reader takes each record's values from within its own size: a polygon whose points +/// don't fit, and a rectangle cut short, are skipped rather than read from the next record. +#[test] +fn the_wmf_reader_stays_in_each_record() { + let record = |func: u16, words: &[i16]| { + let mut r = ((3 + words.len()) as u32).to_le_bytes().to_vec(); + r.extend_from_slice(&func.to_le_bytes()); + r.extend(words.iter().flat_map(|w| w.to_le_bytes())); + r + }; + let wmf = |records: &[Vec]| { + let mut b = vec![0u8; 40]; + b.extend(records.concat()); + b.extend(record(0, &[])); + wmf_polygons(&b, craft_pptx::Size::new(720.0, 540.0)) + }; + // A polygon of 2 points that says it has 3, and a rectangle without its left. + assert!(wmf(&[record(0x0324, &[3, 0, 0, 8, 8]), record(0x041B, &[8, 8, 0])]).is_empty()); + // Whole, both read. + let got = wmf(&[record(0x0324, &[3, 0, 0, 8, 8, 16, 0]), record(0x041B, &[8, 8, 0, 0])]); + assert_eq!(got, [vec![(360.0, 270.0), (361.0, 271.0), (362.0, 270.0)], vec![(360.0, 270.0), (361.0, 270.0), (361.0, 271.0), (360.0, 271.0)]]); } /// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a From 05121acf295daf90197c42556aad54c67aa2100d Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:37:52 -0500 Subject: [PATCH 09/10] ppt95: decide upright text from the shape's final angle Whether a shape's text is upright was decided from the quarter-turns before shape::geometry ran, but geometry gives a mirrored trapezoid a half-turn of its own, so its text turned upside down with it. The text is now upright, at its own angle, whenever the shape ends at any other angle. Probes of trapezoids turned and flipped before and after their text was typed all end at the text's own angle, as PowerPoint 95 drew them. --- crates/ppt-binary/src/ppt95.rs | 22 ++++++++++++---------- crates/ppt-binary/src/ppt95/tests.rs | 11 +++++++++++ 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 15d7bdad6..65ab6ff77 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -463,17 +463,8 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { }); let container = r.child(rt::TEXT); let mut text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); - // PowerPoint 95 lays a shape's text out in the box the geometry holds, turned by the text's own - // angle (4003 +16, the geometry's own angle in every probe): quarter-turns folded into that box - // don't turn the text. When the shape's box was turned back, the text is upright on the slide, - // at that angle, with its insets on the held box's edges by name, as PowerPoint lays out - // `upright` text (checked in PowerPoint 16 against PowerPoint 95's renderings). + // The quarter-turns between the box the geometry holds and the shape's own. let quarters = shape::quarter_turns(&xfrm, drawn); - if let Some(t) = text.as_mut().filter(|_| quarters != 0) { - let angle = container.and_then(|c| text::angle(&c)).unwrap_or(drawn); - t.body.upright = Some(true); - t.body.rot = Some(shape::clockwise(i64::from(angle))).filter(|r| *r != 0.0); - } let ruler = container.and_then(|c| text::ruler_slot(&c)); let (mut geom, mut look) = (None, Look::none()); if !placeholder { @@ -491,6 +482,17 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { look = shape::look(&f, scheme); } } + // PowerPoint 95 lays a shape's text out in the box the geometry holds, turned by the text's own + // angle (4003 +16, the geometry's own angle in every probe): quarter-turns folded into that box + // don't turn the text. When the shape ends up at another angle (its box turned back, or the + // half-turn a mirrored trapezoid takes), the text is upright on the slide, at its own angle, + // with its insets on the held box's edges by name, as PowerPoint lays out `upright` text + // (checked in PowerPoint 16 against PowerPoint 95's renderings). + let angle = shape::clockwise(i64::from(container.and_then(|c| text::angle(&c)).unwrap_or(drawn))); + if let Some(t) = text.as_mut().filter(|_| (xfrm.rot - angle).rem_euclid(360.0) != 0.0) { + t.body.upright = Some(true); + t.body.rot = Some(angle).filter(|r| *r != 0.0); + } Some(Object { placeholder, ph, xfrm, text, ruler, geom, look, kind: Kind::Shape }) } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index e47b0b2a9..69f90f293 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1668,6 +1668,11 @@ fn text_in_a_turned_box_keeps_its_own_angle() { (0.0, None, None, (15.125, 11.375, 15.125, 14.375)), ] ); + // A mirrored trapezoid (orientation bits 0x40) takes a half-turn as its own outline; its text, + // at its own angle of 0, stays upright rather than turning with it. + let p = deck_of(vec![shape(4 | 0x4000, wide, 0, 0, [66, 37, 66, 37])], &[]); + let (x, b) = (p.slides[0].shapes[0].xfrm.unwrap(), &body_of(&p.slides[0].shapes[0]).body); + assert_eq!((x.rot, x.flip_h, b.upright, b.rot), (180.0, false, Some(true), None)); // A balloon turned a quarter counter-clockwise: its body is cut from the shape's bottom, the // held box's right, where its tail is. let p = deck_of(vec![shape(13 | 0x1000, [-576, -576, 576, 576], 0, 0, [91, 121, 307, 121])], &[]); @@ -2090,6 +2095,12 @@ fn check_text_frame_sample(name: &str, shapes: &[Shape]) -> bool { // whole angle, and the text turns with the shape. "wrap-none" | "wrap-after" | "rotmix" | "rot30text" => assert_eq!(upright(&shapes[0]), (None, None), "{name}"), "wrap-before" => assert_eq!(upright(&shapes[0]), (Some(true), None)), + // Trapezoids with text, turned or flipped before or after it was typed: the shape ends at the + // text's own angle, upright or upside down as PowerPoint 95 drew it, so nothing more is set. + "traptext" | "trap180before" | "traptexthflip" | "traptextvflip" | "traptexthflipafter" | "trap180after" | "traptextvflipafter" => { + let rot = if matches!(name, "trap180after" | "traptextvflipafter") { 180.0 } else { 0.0 }; + assert_eq!((shapes[0].xfrm.unwrap().rot, upright(&shapes[0])), (rot, (None, None)), "{name}"); + } "wrap-mix" | "rotmix2" => assert_eq!(upright(&shapes[0]), (Some(true), Some(330.0)), "{name}"), // A balloon's box is its body (the square's top 120 of 144 pt); its text's bottom edge, // 307 units above the square's, is 14.375 pt above the body's. From 8f14a19169fd42880747e633523436ecccad02f9 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:56:26 -0500 Subject: [PATCH 10/10] ppt95: share the trapezoid outline with the PowerPoint 97 path #2492 landed, so the PowerPoint 95 path's copy of OfficeArt's trapezoid outline now uses geom::trapezoid. A negative adjust value is 0 on both. --- crates/ppt-binary/src/geom.rs | 2 +- crates/ppt-binary/src/ppt95/shape.rs | 9 +++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/ppt-binary/src/geom.rs b/crates/ppt-binary/src/geom.rs index b6e793ed1..4616cdd0c 100644 --- a/crates/ppt-binary/src/geom.rs +++ b/crates/ppt-binary/src/geom.rs @@ -196,7 +196,7 @@ const TRAPEZOID: u16 = 8; /// bottom edge inset by `adjust` (5400 unless the file says otherwise) at each end. PowerPoint /// writes the shape the same way when it saves a `.ppt` trapezoid as `.pptx`. A preset flipped /// upright would turn the shape's text upside down. -fn trapezoid(adjust: Option) -> Geom { +pub(crate) fn trapezoid(adjust: Option) -> Geom { let a = adjust.map_or(5400, |v| (v as i32).clamp(0, 10800)); let d = format!("M 0 0 L {a} 21600 L {} 21600 L 21600 0 Z", 21600 - a); Geom::Custom { paths: vec![CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] } diff --git a/crates/ppt-binary/src/ppt95/shape.rs b/crates/ppt-binary/src/ppt95/shape.rs index 91481291f..d8b53b1e5 100644 --- a/crates/ppt-binary/src/ppt95/shape.rs +++ b/crates/ppt-binary/src/ppt95/shape.rs @@ -193,13 +193,10 @@ pub(super) fn orient_drawn(xfrm: &mut Xfrm, bits: u8, drawn: i32) { } /// PowerPoint 95's trapezoid flipped top to bottom, as its default is drawn: wide at the top, each -/// bottom corner inset by the adjust value (0 to half the side, a quarter by default) in the -/// shape's 21600-unit square. The same outline the PowerPoint 97 path gives the trapezoid -/// (storytold/craft-libs#2492), to be shared once that lands. +/// bottom corner inset by the adjust value (0 to half the side, a quarter by default). The outline +/// the PowerPoint 97 path gives OfficeArt's trapezoid; a negative adjust value is 0, as there. fn trapezoid_top(adjust: Option) -> Geom { - let a = adjust.unwrap_or(5400).clamp(0, 10800); - let d = format!("M 0 0 L {a} 21600 L {} 21600 L 21600 0 Z", 21600 - a); - Geom::Custom { paths: vec![CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] } + geom::trapezoid(adjust.map(|v| u32::try_from(v).unwrap_or(0))) } /// A freeform's points as a path in its box `sides` (left, top, right and bottom, either way