Merge pull request #2495 from keithcsqueensu/ppt95-shapes

craft-ppt-binary: read PowerPoint 95 shapes and lines (#2317, step 3)
This commit is contained in:
FredApps
2026-11-21 02:41:26 +07:00
committed by GitHub
7 changed files with 1969 additions and 66 deletions
+23 -2
View File
@@ -56,8 +56,29 @@ included), line spacing, space before and after (in lines or points), bullet cha
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. The
master's text styles become its title, body and other styles, level by level. Shapes without text,
the shapes' own fill and line, pictures and notes come later.
master's text styles become its title, body and other styles, level by level. 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, 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; a shape's text is
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.
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
+8 -4
View File
@@ -172,18 +172,22 @@ 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
}
/// `msosptTrapezoid`. It has no preset: DrawingML's `trapezoid` is wide at the bottom, OfficeArt's
/// at the top.
const TRAPEZOID: u16 = 8;
@@ -192,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<u32>) -> Geom {
pub(crate) fn trapezoid(adjust: Option<u32>) -> 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() }] }
+6 -5
View File
@@ -9,11 +9,12 @@
//!
//! 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, placeholder boxes
//! and text styles, and slides with their order, master, layout type, background, and placeholders
//! and text boxes with formatted, anchored text; their other shapes, pictures and notes are not
//! read yet. Older formats aren't read: a compound file in neither framing is refused as too old
//! when its current user record has neither of [MS-PPT]'s tokens and it has no edit record, and a
//! file that isn't a compound file is not a presentation.
//! and text styles, and slides with their order, master, layout type, background, placeholders
//! and text boxes with formatted, anchored text, and shapes and lines with their fill, line and
//! shadow; their pictures and notes are not read yet. Older formats aren't read: a compound file
//! in neither framing is refused as too old when its current user record has neither of
//! [MS-PPT]'s tokens and it has no edit record, and a file that isn't a compound file is not a
//! presentation.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
+300 -45
View File
@@ -6,37 +6,61 @@
//! (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, its character and paragraph formatting (spacing and justified
//! alignment included) and its anchoring ([`text`]).
//! slides in order with their master, layout type and background, holding their placeholders, text
//! boxes, shapes, lines, freeforms and groups, with the text, its character and paragraph
//! formatting (spacing and justified alignment included) and its anchoring ([`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), 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
//! 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.
//!
//! The master's text styles (the Environment's 4052 atoms, one per text type) become the master's
//! title, body and other styles. Slide text carries its own formatting in full, so these matter
//! for text added later.
//!
//! Not read yet: shapes without text, and shapes' own fill, line and shadow; pictures; and notes.
//! Not read yet: pictures and notes.
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,
ShapeKind, 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.
@@ -53,11 +77,18 @@ 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;
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 FREEFORM: u32 = 3016;
pub const FREEFORM_ATOM: u32 = 3017;
pub const POINTS: u32 = 3035;
pub const TEXT: u32 = 4001;
}
@@ -71,11 +102,16 @@ const SLIDE_COUNT: usize = 32;
/// 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;
/// 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.
@@ -235,9 +271,7 @@ fn background(rec: &Rec, scheme: &Scheme) -> Option<Fill> {
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
@@ -265,26 +299,160 @@ struct Object {
text: Option<TextBody>,
/// The ruler slot its text names.
ruler: Option<u32>,
/// A shape's preset (a rectangle for a shape code no probe showed): `None` for a placeholder.
geom: Option<Geom>,
/// How a shape or line is drawn (a placeholder's is left to its layout).
look: Look,
kind: Kind,
}
/// The shapes and placeholders of a page's object list.
fn objects<'a>(page: &Rec<'a>) -> impl Iterator<Item = Rec<'a>> {
page.child(rt::OBJECTS).into_iter().flat_map(|l| l.children()).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)).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<Object>),
}
/// 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<Object> {
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;
/// 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<Object> {
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<Object> {
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<Object> {
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,
ruler: 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)
/// 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;
// 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 { 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 (1 pt in the scheme's text and lines colour without one), with its arrowheads.
fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option<Object> {
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], None), ..Look::none() },
};
// 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);
}
let geom = Some(Geom::Preset { name: "line".into(), adj: vec![] });
Some(Object { placeholder: false, ph: None, xfrm, text: None, ruler: 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<Object> {
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 container = r.child(rt::TEXT);
let text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), true));
let ruler = container.and_then(|c| text::ruler_slot(&c));
Some(Object { placeholder: false, ph: None, xfrm: xfrm_of(sides, size), text, ruler, 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
/// look.
fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
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);
let format = r.child(rt::FORMAT);
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()),
@@ -294,24 +462,79 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
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 quarter-turns between the box the geometry holds and the shape's own.
let quarters = shape::quarter_turns(&xfrm, drawn);
let ruler = container.and_then(|c| text::ruler_slot(&c));
Some(Object { placeholder, ph, xfrm, text, ruler })
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 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);
}
}
// 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 })
}
/// 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; 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<Shape> {
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())?;
let text = o.text.filter(|t| !t.is_empty());
if text.is_some() && !o.look.drawn() {
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: match o.kind {
Kind::Line => format!("Line {id}"),
Kind::Freeform => format!("Freeform {id}"),
_ => 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()
});
};
@@ -328,6 +551,38 @@ fn shape(p: &mut Presentation, o: Object) -> Option<Shape> {
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<Object>) -> Option<Shape> {
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);
@@ -363,7 +618,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation {
let mut placed: Vec<PhType> = vec![];
// The rulers of the master's title and body, which give their styles' margins.
let (mut title_ruler, mut body_ruler) = (None, None);
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);
@@ -416,7 +671,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: s.follow_objects, ..Default::default() }));
+290
View File
@@ -0,0 +1,290 @@
//! 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 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, +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.
//!
//! 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`]). 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};
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 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)]
pub(super) struct Look {
pub fill: Fill,
pub line: Line,
pub shadow: Option<Shadow>,
}
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 }
}
/// 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<Rgba> {
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` 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 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<u8>| {
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 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_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: dx.hypot(dy),
dir: dy.atan2(dx).to_degrees().rem_euclid(360.0),
inner: false,
sx: 1.0,
sy: 1.0,
kx: 0.0,
ky: 0.0,
align: String::new(),
rotate_with_shape: false,
}
}
/// 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);
}
/// 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.
pub(super) 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 quarters = (i64::from(turn) - i64::from(drawn) + QUARTER / 2).div_euclid(QUARTER).rem_euclid(4);
if quarters % 2 == 1 {
turn_back(xfrm);
}
xfrm.rot = clockwise(i64::from(turn));
}
/// 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). The outline
/// the PowerPoint 97 path gives OfficeArt's trapezoid; a negative adjust value is 0, as there.
fn trapezoid_top(adjust: Option<i32>) -> Geom {
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
/// 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;
/// 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), 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<i32>, xfrm: &mut Xfrm) -> Geom {
let kind = u16::try_from(i16::from(code) + 4).ok().filter(|_| (-3..=14).contains(&code));
// PowerPoint 95's trapezoid unmirrored is DrawingML's preset, wide at the bottom; the PowerPoint
// 97 path's table has no preset for it, OfficeArt's being wide at the top.
let Some(name) = kind.and_then(|k| if k == 8 { Some("trapezoid") } else { geom::preset_name(k) }) 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: 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<f64> = 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<i32>, 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] }
}
File diff suppressed because it is too large Load Diff
+7
View File
@@ -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<i32> {
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<u32> {
let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?;