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); }