diff --git a/crates/ppt-binary/Cargo.toml b/crates/ppt-binary/Cargo.toml index 897aad8a4..aa64c6cc7 100644 --- a/crates/ppt-binary/Cargo.toml +++ b/crates/ppt-binary/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-ppt-binary" -description = "Reader for the PowerPoint 97-2003 binary file format (.ppt, .pot, .pps; [MS-PPT], [MS-ODRAW]) into the craft-pptx presentation model, on craft-cfb." +description = "Reader for the PowerPoint 97-2003 binary file format (.ppt, .pot, .pps; [MS-PPT], [MS-ODRAW]), and the start of PowerPoint 95, into the craft-pptx presentation model, on craft-cfb." version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index d1bbdd24e..330682ea7 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -27,9 +27,23 @@ assert!(craft_ppt_binary::import(b"not a .ppt", &craft_pptx::Plain).is_err()); - Damaged files read as far as they can: a broken edit chain falls back to a scan of the edits, and unknown or damaged records are skipped. Sizes, counts, nesting and picture decoding are bounded. -- Password-protected files are refused (`PptError::Encrypted`), as are PowerPoint 95 and earlier +- Password-protected files are refused (`PptError::Encrypted`), as are PowerPoint 4.0 and earlier files (`PptError::TooOld`). +## PowerPoint 95 + +PowerPoint 95 (7.0) files use the same compound file and many of the same record numbers, but a +16-byte record header and a single record tree with no edit chain. A file whose `PowerPoint +Document` stream starts with that tree is read on its own path; anything else takes the +PowerPoint 97 path. What was learned of the format came from files PowerPoint 95 itself wrote, +one feature per file, and the public [MS-PPT] numbering where the records keep it. + +So far a PowerPoint 95 file imports with its slide size, its masters (each the caller's default +master wearing the file's colour scheme, and its background when that isn't the scheme's), and +its slides in order with their master, layout type and, when a slide doesn't follow the master's, +its solid background. The slides are empty: shapes, placeholders and their text, 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 master has. With `craft_pptx::Plain` (one blank layout, no placeholders), the slides still read @@ -37,4 +51,5 @@ with their own boxes. The reader was written for DeckCraft (storytold/deckcraft#1137); the history of `crates/ppt-binary` names its authors. Its tests build `.ppt` files from records; no file made -by PowerPoint is used. +by PowerPoint is used. One optional test reads real PowerPoint 95 files from the directory +`CRAFT_PPT95_SAMPLES` names, and does nothing when it is unset; no such file is in the repository. diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs index f7897cdbb..3501f2260 100644 --- a/crates/ppt-binary/src/convert.rs +++ b/crates/ppt-binary/src/convert.rs @@ -31,7 +31,7 @@ const EMU: f64 = 12700.0; /// The eight colours of a `.ppt` colour scheme: background, text, shadow, title text, fill, /// accent, accent and hyperlink, accent and followed hyperlink. -type Scheme = [Rgba; 8]; +pub(crate) type Scheme = [Rgba; 8]; const DEFAULT_SCHEME: Scheme = [ Rgba::rgb(0xFF, 0xFF, 0xFF), @@ -95,14 +95,17 @@ struct Ctx<'a> { used_notes: HashSet, } +/// A page side in master units as points, else `fallback` when it is missing or out of range. +pub(crate) fn page_side(v: Option, fallback: f64) -> f64 { + v.map(|v| f64::from(v) / MU).filter(|v| v.is_finite() && *v >= 1.0 && *v <= 56.0 * 72.0).unwrap_or(fallback) +} + pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Presentation { let atom = d.document_atom(); - let side = - |v: Option, fallback: f64| v.map(|v| f64::from(v) / MU).filter(|v| v.is_finite() && *v >= 1.0 && *v <= 56.0 * 72.0).unwrap_or(fallback); - let size = Size::new(side(atom.as_ref().map(|a| a.slide_w), 720.0), side(atom.as_ref().map(|a| a.slide_h), 540.0)); + let size = Size::new(page_side(atom.as_ref().map(|a| a.slide_w), 720.0), page_side(atom.as_ref().map(|a| a.slide_h), 540.0)); // Ids above 256, as a new presentation's are. let mut p = Presentation { slide_size: size, default_text_style: app.default_text_style(), next_id: 256, ..Default::default() }; - p.notes_size = Size::new(side(atom.as_ref().map(|a| a.notes_w), 540.0), side(atom.as_ref().map(|a| a.notes_h), 720.0)); + p.notes_size = Size::new(page_side(atom.as_ref().map(|a| a.notes_w), 540.0), page_side(atom.as_ref().map(|a| a.notes_h), 720.0)); p.first_slide_number = atom.as_ref().map_or(1, |a| u32::from(a.first_slide_number)); let dgg = d.document.child(rt::DRAWING_GROUP).and_then(|g| g.child(rt::DGG_CONTAINER)); let mut cx = Ctx { @@ -175,9 +178,9 @@ pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Pr } /// A master's first layout of each layout type, and its first layout. -type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option); +pub(crate) type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option); -fn layout_table(m: &Master, skip: &HashSet) -> LayoutTable { +pub(crate) fn layout_table(m: &Master, skip: &HashSet) -> LayoutTable { let mut kinds: Vec<(LayoutType, LayoutId)> = vec![]; let layouts = m.layouts.iter().filter(|l| !skip.contains(&l.id)); let first = layouts.clone().next().map(|l| l.id); @@ -198,6 +201,26 @@ struct Find<'f> { notes_of: &'f HashMap, } +/// A theme named "Imported" carrying a `.ppt` colour scheme's eight colours. +pub(crate) fn scheme_theme(scheme: &Scheme) -> Theme { + let mut t = Theme { name: "Imported".into(), ..Default::default() }; + for (slot, i) in [ + (SchemeSlot::Lt1, 0), + (SchemeSlot::Dk1, 1), + (SchemeSlot::Lt2, 2), + (SchemeSlot::Dk2, 3), + (SchemeSlot::Accent1, 4), + (SchemeSlot::Accent2, 5), + (SchemeSlot::Hlink, 6), + (SchemeSlot::FolHlink, 7), + ] { + if let Some(c) = scheme.get(i) { + t.colors.set(slot, *c); + } + } + t +} + /// A converted master: where it went and what its slides inherit. #[derive(Clone)] struct MasterInfo { @@ -370,21 +393,7 @@ impl<'a> Ctx<'a> { /// A theme carrying the master's colours and fonts, so shapes added later match the deck. fn theme(&self, scheme: &Scheme, styles: &StyleSheet) -> Theme { - let mut t = Theme { name: "Imported".into(), ..Default::default() }; - for (slot, i) in [ - (SchemeSlot::Lt1, 0), - (SchemeSlot::Dk1, 1), - (SchemeSlot::Lt2, 2), - (SchemeSlot::Dk2, 3), - (SchemeSlot::Accent1, 4), - (SchemeSlot::Accent2, 5), - (SchemeSlot::Hlink, 6), - (SchemeSlot::FolHlink, 7), - ] { - if let Some(c) = scheme.get(i) { - t.colors.set(slot, *c); - } - } + let mut t = scheme_theme(scheme); if let Some(f) = styles.resolve(ty::TITLE, 0).1.font.and_then(|i| self.fonts.get(usize::from(i))) { t.fonts.major.latin = f.clone(); } @@ -1145,7 +1154,7 @@ fn same_family(a: PhType, b: PhType) -> bool { } /// `SlideLayoutType` as a layout type. -fn layout_kind(geom: u32) -> LayoutType { +pub(crate) fn layout_kind(geom: u32) -> LayoutType { match geom { 0 => LayoutType::Title, 7 => LayoutType::TitleOnly, diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index b9b2fa315..729219837 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -6,6 +6,11 @@ //! are skipped, damaged ones are left out, and every size, count and depth is bounded. The caller's //! [`Defaults`] supply each master's layouts and placeholders, which the file's masters then //! place and style. There is no `.ppt` writer. +//! +//! 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 and backgrounds, and slides with +//! their order, master, layout type and background; their shapes, text, pictures and notes are +//! not read yet, so the slides are empty. PowerPoint 4.0 and earlier are refused as too old. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -18,6 +23,7 @@ mod convert; mod doc; mod draw; mod geom; +mod ppt95; mod record; mod text; @@ -33,14 +39,14 @@ pub enum PptError { NotPpt, #[error("the presentation is password-protected")] Encrypted, - #[error("the presentation was made by PowerPoint 95 or earlier")] + #[error("the presentation was made by PowerPoint 4.0 or earlier")] TooOld, #[error("the presentation is damaged: {0}")] Damaged(String), } -/// Does this look like a PowerPoint 97–2003 file (a compound file with a `PowerPoint Document` -/// stream)? +/// Does this look like a PowerPoint 95 or 97–2003 file (a compound file with a `PowerPoint +/// Document` stream)? pub fn sniff(bytes: &[u8]) -> bool { craft_cfb::sniff(bytes) && CompoundFile::open(bytes).is_ok_and(|f| f.has_stream(DOCUMENT_STREAM)) } @@ -65,6 +71,11 @@ pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presenta CfbError::NotFound(_) => PptError::NotPpt, other => PptError::Damaged(other.to_string()), })?; + // PowerPoint 95 writes one tree of 16-byte-header records; anything else takes the + // PowerPoint 97 path, which refuses older formats as too old. + if let Some(document) = ppt95::document(&stream) { + return Ok((ppt95::convert(&document, defaults), vec![])); + } let current_user = file.read_path_capped("Current User", cap).unwrap_or_default(); // A damaged or missing picture stream costs the pictures, not the presentation. let pictures = file.read_path_capped("Pictures", cap).unwrap_or_default(); diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs new file mode 100644 index 000000000..e1757aa95 --- /dev/null +++ b/crates/ppt-binary/src/ppt95.rs @@ -0,0 +1,238 @@ +//! PowerPoint 95 (PowerPoint 7.0) presentations, learned from files PowerPoint 95 wrote. +//! +//! Its records have a 16-byte header: u32 type, u32 instance (0xFFFF for none), u32 body length +//! and a u32 fourth word (a tag). There is no container flag: a container's body is records, and +//! the reader knows which types those are. A saved `PowerPoint Document` stream is one record tree +//! (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. Shapes, text, pictures and +//! notes are not read yet, so slides come out empty. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use craft_pptx::{Background, ColorRef, Defaults, Fill, LayoutType, Master, Presentation, Rgba, Size, Slide, SlideId}; + +use crate::convert::{Scheme, layout_kind, layout_table, page_side, scheme_theme}; +use crate::record::u32_at; + +/// Record types. +mod rt { + pub const ROOT: u32 = 3; + pub const DOCUMENT: u32 = 1000; + pub const DOCUMENT_ATOM: u32 = 1001; + pub const SLIDE_BOX: u32 = 1005; + pub const SLIDE: u32 = 1006; + pub const SLIDE_ATOM: u32 = 1007; + pub const SCHEME: u32 = 1012; + pub const LAYOUT: u32 = 1015; + pub const MAIN_MASTER: u32 = 1016; + pub const LIST: u32 = 2000; + pub const COLOR_SCHEME: u32 = 2031; + pub const OBJECTS: u32 = 3000; + pub const FORMAT: u32 = 3005; + pub const SHAPE: u32 = 3008; +} + +/// "No instance". +const NO_INSTANCE: u32 = 0xFFFF; +/// Slides, and masters, read at most: beyond any real presentation, so a file of empty slide +/// records can't make an unbounded presentation. +const MAX_SLIDES: usize = 1 << 16; +/// The fill 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. +const DEFAULT_SCHEME: Scheme = [ + Rgba::rgb(0xFF, 0xFF, 0xFF), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0x96, 0x96, 0x96), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0x00, 0xCC, 0x99), + Rgba::rgb(0x33, 0x33, 0xCC), + Rgba::rgb(0xCC, 0xCC, 0xFF), + Rgba::rgb(0xB2, 0xB2, 0xB2), +]; + +/// One record over borrowed bytes. +#[derive(Clone, Copy, Debug)] +pub struct Rec<'a> { + pub kind: u32, + pub instance: u32, + /// The body, clipped to the input (a truncated last record keeps what is there). + pub data: &'a [u8], +} + +impl<'a> Rec<'a> { + pub fn at(bytes: &'a [u8], at: usize) -> Option> { + let word = |k: usize| u32_at(bytes, at.checked_add(k * 4)?); + // The fourth word, a tag, isn't needed yet; it must be there for the header to be whole. + let (kind, instance, len, _tag) = (word(0)?, word(1)?, word(2)?, word(3)?); + let start = at.checked_add(16)?; + let end = start.saturating_add(len as usize).min(bytes.len()); + Some(Rec { kind, instance, data: bytes.get(start..end)? }) + } + + /// The body read as records. Only called on the types that are containers; the walk never + /// recurses, so nesting depth can't grow the stack. + pub fn children(&self) -> Records<'a> { + Records { bytes: self.data, at: 0 } + } + + pub fn child(&self, kind: u32) -> Option> { + self.children().find(|r| r.kind == kind) + } + + pub fn u8(&self, at: usize) -> Option { + self.data.get(at).copied() + } + + pub fn u32(&self, at: usize) -> Option { + u32_at(self.data, at) + } + + pub fn i32(&self, at: usize) -> Option { + self.u32(at).map(|v| v as i32) + } +} + +/// The records laid end to end in a byte slice. +#[derive(Clone, Debug)] +pub struct Records<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> Iterator for Records<'a> { + type Item = Rec<'a>; + fn next(&mut self) -> Option> { + let r = Rec::at(self.bytes, self.at)?; + // Always past the header, so a zero-length record can't stall the walk. + self.at = self.at.checked_add(16)?.checked_add(r.data.len())?; + Some(r) + } +} + +/// The Document container of a PowerPoint 95 `PowerPoint Document` stream: the stream starts with +/// a type-3 record whose first child is a Document (1000) with no instance. `None` for anything +/// else, PowerPoint 97 files included (their 8-byte headers don't read this way). +pub fn document(stream: &[u8]) -> Option> { + let root = Rec::at(stream, 0).filter(|r| r.kind == rt::ROOT)?; + root.children().next().filter(|d| d.kind == rt::DOCUMENT && d.instance == NO_INSTANCE) +} + +/// What a slide or master says about itself. +struct Page<'a> { + rec: Rec<'a>, + /// Its id (a master's is what its slides name). + id: u32, + master_id: u32, + /// The [MS-PPT] `SlideLayoutType` number. + layout: Option, + follow_background: bool, + scheme: Option, +} + +fn page(rec: Rec<'_>) -> Page<'_> { + let atom = rec.child(rt::SLIDE_ATOM); + Page { + rec, + id: atom.and_then(|a| a.u32(0)).unwrap_or(0), + master_id: atom.and_then(|a| a.u32(4)).unwrap_or(0), + layout: rec.child(rt::LAYOUT).and_then(|l| l.u32(0)), + follow_background: rec.child(rt::SLIDE_BOX).and_then(|b| b.u8(20)).is_none_or(|f| f != 0), + scheme: rec.child(rt::SCHEME).and_then(|s| s.child(rt::COLOR_SCHEME)).map(|s| scheme_of(&s)), + } +} + +/// A `ColorSchemeAtom`: a count, then that many RGBX colours (the first eight are used). +fn scheme_of(r: &Rec) -> Scheme { + let mut s = DEFAULT_SCHEME; + let count = r.u32(0).map_or(0, |c| c.min(8) as usize); + for (i, c) in s.iter_mut().enumerate().take(count) { + if let (Some(red), Some(g), Some(b)) = (r.u8(4 + i * 4), r.u8(5 + i * 4), r.u8(6 + i * 4)) { + *c = Rgba::rgb(red, g, b); + } + } + s +} + +/// The fill of a page's background shape: its own shape before the object list. +fn background(rec: &Rec, scheme: &Scheme) -> Option { + let shape = rec.children().take_while(|r| r.kind != rt::OBJECTS).find(|r| r.kind == rt::SHAPE)?; + let format = shape.child(rt::FORMAT)?; + 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))) +} + +/// 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); + let field = |at: usize| atom.and_then(|a| a.i32(at)); + let size = Size::new(page_side(field(0), 720.0), page_side(field(4), 540.0)); + let mut p = Presentation { slide_size: size, default_text_style: app.default_text_style(), next_id: 256, ..Default::default() }; + p.notes_size = Size::new(page_side(field(8), 540.0), page_side(field(12), 720.0)); + + // The lists are told apart by what they hold, in whatever order they come. + let (mut slides, mut masters) = (vec![], vec![]); + for list in document.children().filter(|r| r.kind == rt::LIST) { + for r in list.children() { + match r.kind { + rt::SLIDE if slides.len() < MAX_SLIDES => slides.push(page(r)), + rt::MAIN_MASTER if masters.len() < MAX_SLIDES => masters.push(page(r)), + _ => {} + } + } + } + + // Each master: the caller's default master with the file's colours and background. + let mut by_id: HashMap = HashMap::new(); + for m in &masters { + let scheme = m.scheme.unwrap_or(DEFAULT_SCHEME); + let mut master = default_master(&mut p, app, size, Some(scheme)); + let index = p.masters.len(); + // The scheme's background is what the master shows anyway. + master.background = background(&m.rec, &scheme).filter(|f| *f != Fill::solid(ColorRef::rgb(scheme[0]))).map(|fill| Background::Fill { fill }); + p.masters.push(Arc::new(master)); + by_id.entry(m.id).or_insert((index, scheme)); + } + if p.masters.is_empty() { + let m = default_master(&mut p, app, size, None); + p.masters.push(Arc::new(m)); + } + + let layouts: Vec<_> = p.masters.iter().map(|m| layout_table(m, &HashSet::new())).collect(); + for s in &slides { + // An unknown master is the first one. + let (index, master_scheme) = + by_id.get(&s.master_id).copied().unwrap_or((0, masters.first().and_then(|m| m.scheme).unwrap_or(DEFAULT_SCHEME))); + let Some((kinds, first)) = layouts.get(index) else { continue }; + let kind: Option = s.layout.map(layout_kind); + let Some(layout) = kind.and_then(|k| kinds.iter().find(|(lk, _)| *lk == k).map(|(_, id)| *id)).or(*first) else { continue }; + let scheme = s.scheme.unwrap_or(master_scheme); + 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 }; + p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, show_master_shapes: true, ..Default::default() })); + } + p +} + +/// The caller's default master, with ids above those handed out so far, wearing `scheme`. +fn default_master(p: &mut Presentation, app: &dyn Defaults, size: Size, scheme: Option) -> Master { + let (mut master, last) = app.master(size, p.next_id); + p.next_id = p.next_id.max(last); + if let Some(scheme) = scheme { + let theme = scheme_theme(&scheme); + master.name = theme.name.clone(); + master.theme = theme; + } + master +} + +#[cfg(test)] +mod tests; diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs new file mode 100644 index 000000000..0a3bd8e0d --- /dev/null +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -0,0 +1,340 @@ +//! PowerPoint 95 files built here from records, written from the format notes (never files made +//! by PowerPoint), and an optional check over real ones named by `CRAFT_PPT95_SAMPLES`. +#![allow(clippy::unwrap_used)] + +use craft_pptx::{Background, ColorRef, Fill, LayoutType, Presentation, Rgba, SchemeSlot}; + +use super::rt; +use crate::tests::{AppDefaults, build}; + +const MASTER: u32 = 0x8000_0000; +const NONE: u32 = 0xFFFF; + +/// A record: type, instance, length, fourth word, body. +fn rec(kind: u32, instance: u32, tag: u32, body: &[u8]) -> Vec { + let mut v = Vec::with_capacity(body.len() + 16); + for w in [kind, instance, body.len() as u32, tag] { + v.extend_from_slice(&w.to_le_bytes()); + } + v.extend_from_slice(body); + v +} + +fn container(kind: u32, tag: u32, children: &[Vec]) -> Vec { + rec(kind, NONE, tag, &children.concat()) +} + +fn le32(v: &[u32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +const DEFAULT: [u32; 8] = [0xFFFFFF, 0x000000, 0x969696, 0x000000, 0x00CC99, 0x3333CC, 0xCCCCFF, 0xB2B2B2]; + +/// A `ColorSchemeAtom` of eight colours given as 0xRRGGBB. +fn scheme_atom(tag: u32, colors: [u32; 8]) -> Vec { + let mut b = le32(&[8]); + for c in colors { + b.extend_from_slice(&[(c >> 16) as u8, (c >> 8) as u8, c as u8, 0]); + } + rec(rt::COLOR_SCHEME, 0, tag, &b) +} + +/// The page's background shape, filled with R, G, B and an index byte (0xFE: the RGB itself). +fn background_shape(fill: [u8; 4], filled: bool) -> Vec { + let geometry = rec(3009, 0, 0, &le32(&[(-3i32) as u32, 0, 0, (-2880i32) as u32, (-2160i32) as u32, 2880, 2160, 0, (-3i32) as u32, 0])); + let mut format = vec![0u8; 56]; + format[12] = if filled { 0 } else { 0xFF }; + format[20..24].copy_from_slice(&fill); + container(rt::SHAPE, 0x1C, &[geometry, rec(rt::FORMAT, 1, 0, &format)]) +} + +/// The slide box: the slide rectangle, then whether it follows the master background. +fn slide_box(follow_background: bool) -> Vec { + let mut b = le32(&[(-2880i32) as u32, (-2160i32) as u32, 2880, 2160]); + b.extend_from_slice(&[1, 1, 0, 0, u8::from(follow_background), 0, 0, 0]); + rec(rt::SLIDE_BOX, 1, 0, &b) +} + +struct SlideSpec { + id: u32, + master: u32, + layout: u32, + follow_background: bool, + fill: [u8; 4], + filled: bool, + scheme: [u32; 8], +} + +impl SlideSpec { + fn new(id: u32, layout: u32) -> SlideSpec { + SlideSpec { id, master: MASTER, layout, follow_background: true, fill: [0, 0, 0, 0], filled: true, scheme: DEFAULT } + } +} + +fn slide(s: &SlideSpec) -> Vec { + container( + rt::SLIDE, + 0x10, + &[ + rec(rt::SLIDE_ATOM, 0, 0, &le32(&[s.id, s.master])), + slide_box(s.follow_background), + rec(rt::LAYOUT, 1, 0, &le32(&[s.layout, 0, 0])), + container(rt::SCHEME, 0x78, &[scheme_atom(0, s.scheme)]), + background_shape(s.fill, s.filled), + container(rt::OBJECTS, 0x14, &[]), + ], + ) +} + +fn master(id: u32, scheme: [u32; 8], fill: [u8; 4]) -> Vec { + container( + rt::MAIN_MASTER, + 0x10, + &[ + rec(rt::SLIDE_ATOM, 0, 0, &le32(&[id, 0])), + slide_box(true), + // A scheme preset, which isn't the master's scheme. + scheme_atom(0x37, [0x0000FF, 0xFFFFFF, 0, 0xFFFF00, 0xFF9900, 0x00FFFF, 0xFF0033, 0x969696]), + rec(rt::LAYOUT, 1, 0, &[1, 0, 0, 0, 1, 2, 6, 8, 7, 0, 0, 0]), + container(rt::SCHEME, 0x78, &[scheme_atom(0, scheme)]), + background_shape(fill, true), + container(rt::OBJECTS, 0x14, &[]), + ], + ) +} + +fn document_atom(w: u32, h: u32, slides: u32) -> Vec { + let mut b = le32(&[w, h, h, w, 0x0001_0000, 0, 0, 0, slides, 5, 10]); + b.truncate(44); + rec(rt::DOCUMENT_ATOM, 4, 0, &b) +} + +/// A `PowerPoint Document` stream: root 3 holding the Document and a type-10 atom. +fn stream_of(atom: Vec, slides: &[Vec], masters: &[Vec]) -> Vec { + let list = |tag: u32, items: &[Vec]| { + let mut kids = vec![rec(2001, 0, 0, &le32(&[items.len() as u32]))]; + kids.extend_from_slice(items); + container(rt::LIST, tag, &kids) + }; + let document = container( + rt::DOCUMENT, + 0, + &[atom, container(1010, 0x15, &[]), list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], + ); + container(rt::ROOT, 0, &[document, rec(10, 0, 0, &le32(&[1, 0x100]))]) +} + +fn header() -> Vec { + let mut h = b"Microsoft (R) PowerPoint (R) Windows \0".to_vec(); + h.extend_from_slice(&le32(&[7, 0x3F0, 0xE391_C05F])); + h.extend_from_slice(&[1, 0]); + h.resize(57, 0); + h +} + +fn file_of(stream: &[u8]) -> Vec { + build(&[("PowerPoint Document", stream), ("Header", &header()), ("Current User", &[0; 5])]) +} + +fn import(stream: &[u8]) -> Result { + crate::import(&file_of(stream), &AppDefaults) +} + +fn deck(slides: &[SlideSpec]) -> Presentation { + let s: Vec> = slides.iter().map(slide).collect(); + import(&stream_of(document_atom(5760, 4320, s.len() as u32), &s, &[master(MASTER, DEFAULT, [0, 0, 0, 0])])).unwrap() +} + +fn layout_kind(p: &Presentation, i: usize) -> LayoutType { + p.layout(p.slides[i].layout).unwrap().1.kind +} + +fn solid(r: u8, g: u8, b: u8) -> Option { + Some(Background::Fill { fill: Fill::solid(ColorRef::rgb(Rgba::rgb(r, g, b))) }) +} + +#[test] +fn a_powerpoint_95_tree_is_detected_and_read() { + let bytes = file_of(&stream_of(document_atom(5760, 4320, 1), &[slide(&SlideSpec::new(0x100, 16))], &[master(MASTER, DEFAULT, [0; 4])])); + assert!(crate::sniff(&bytes)); + let (p, lost) = crate::import_checked(&bytes, &AppDefaults).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.masters.len(), 1); + assert!(lost.is_empty()); + assert!(p.slides[0].shapes.is_empty()); +} + +/// A stream that is neither framing still says the file is too old, and a PowerPoint 97 file reads +/// as before. +#[test] +fn other_framings_keep_the_powerpoint_97_path() { + let mut not95 = stream_of(document_atom(5760, 4320, 0), &[], &[]); + not95[0] = 4; + let unknown_token = crate::record::build::atom(crate::doc::rt::CURRENT_USER, 0, &le32(&[0x14, 0xDEAD_BEEF, 0, 0, 0])); + let f = build(&[("PowerPoint Document", ¬95), ("Current User", &unknown_token)]); + let e = crate::import(&f, &AppDefaults).unwrap_err(); + assert!(matches!(e, crate::PptError::TooOld)); + assert_eq!(e.to_string(), "the presentation was made by PowerPoint 4.0 or earlier"); + // The Document must be the root's first child, with no instance. + let mut wrong_instance = stream_of(document_atom(5760, 4320, 0), &[], &[]); + wrong_instance[20..24].copy_from_slice(&0u32.to_le_bytes()); + assert!(super::document(&wrong_instance).is_none()); + + let p = crate::import(&crate::tests::file(), &AppDefaults).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Hello\nWorld"); +} + +#[test] +fn slides_keep_their_order_and_the_size() { + let p = deck(&[SlideSpec::new(0x100, 16), SlideSpec::new(0x101, 0), SlideSpec::new(0x102, 8)]); + assert_eq!(p.slides.len(), 3); + assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0)); + assert_eq!((p.notes_size.width, p.notes_size.height), (540.0, 720.0)); + assert_eq!([layout_kind(&p, 0), layout_kind(&p, 1), layout_kind(&p, 2)], [LayoutType::Blank, LayoutType::Title, LayoutType::TwoContent]); + + let p = import(&stream_of(document_atom(4608, 3456, 1), &[slide(&SlideSpec::new(0x100, 16))], &[])).unwrap(); + assert_eq!((p.slide_size.width, p.slide_size.height), (576.0, 432.0)); + assert_eq!(p.masters.len(), 1, "the defaults' master when the file has none"); + assert_eq!(p.slides.len(), 1); +} + +#[test] +fn layout_types_map_to_layouts() { + let p = + deck(&[SlideSpec::new(0x100, 0), SlideSpec::new(0x101, 7), SlideSpec::new(0x102, 1), SlideSpec::new(0x103, 16), SlideSpec::new(0x104, 99)]); + let kinds: Vec<_> = (0..5).map(|i| layout_kind(&p, i)).collect(); + assert_eq!(kinds, [LayoutType::Title, LayoutType::TitleOnly, LayoutType::TitleAndContent, LayoutType::Blank, LayoutType::TitleAndContent]); +} + +/// Each slide takes the master it names; an unknown id takes the first master. +#[test] +fn slides_link_to_their_master() { + let green = [0xFFFFFF, 0, 0x808080, 0, 0x00FF00, 0x3333CC, 0xCCCCFF, 0xB2B2B2]; + let masters = [master(MASTER, DEFAULT, [0; 4]), master(MASTER + 1, green, [0; 4])]; + let mut on_second = SlideSpec::new(0x100, 16); + on_second.master = MASTER + 1; + let mut unknown = SlideSpec::new(0x101, 16); + unknown.master = 0x1234; + let p = import(&stream_of(document_atom(5760, 4320, 2), &[slide(&on_second), slide(&unknown)], &masters)).unwrap(); + assert_eq!(p.masters.len(), 2); + let master_of = |i: usize| p.layout(p.slides[i].layout).unwrap().0.id; + assert_eq!(master_of(0), p.masters[1].id); + assert_eq!(master_of(1), p.masters[0].id); +} + +/// The master's theme comes from its scheme (under 1012), not the presets beside it. +#[test] +fn the_masters_scheme_is_its_theme() { + let scheme = [0x102030, 0x405060, 0x708090, 0xA0B0C0, 0x112233, 0x445566, 0x778899, 0xAABBCC]; + let p = import(&stream_of(document_atom(5760, 4320, 0), &[], &[master(MASTER, scheme, [0; 4])])).unwrap(); + let c = &p.masters[0].theme.colors; + assert_eq!(c.get(SchemeSlot::Lt1), Rgba::rgb(0x10, 0x20, 0x30)); + assert_eq!(c.get(SchemeSlot::Dk1), Rgba::rgb(0x40, 0x50, 0x60)); + assert_eq!(c.get(SchemeSlot::Accent1), Rgba::rgb(0x11, 0x22, 0x33)); + assert_eq!(c.get(SchemeSlot::FolHlink), Rgba::rgb(0xAA, 0xBB, 0xCC)); + assert_eq!(p.masters[0].background, None, "the scheme's background colour is the master's anyway"); + + let red = import(&stream_of(document_atom(5760, 4320, 0), &[], &[master(MASTER, scheme, [0xFF, 0, 0, 0xFE])])).unwrap(); + assert_eq!(red.masters[0].background, solid(0xFF, 0, 0)); +} + +#[test] +fn a_slide_that_doesnt_follow_the_master_keeps_its_background() { + let mut rgb = SlideSpec::new(0x100, 16); + rgb.follow_background = false; + rgb.fill = [0xFF, 0, 0, 0xFE]; + // A scheme slot (4, fills) of the slide's own scheme. + let mut slot = SlideSpec::new(0x101, 16); + slot.follow_background = false; + slot.fill = [0, 0, 0, 4]; + slot.scheme[4] = 0x123456; + // Following the master, its own background shape is not used. + let mut follows = SlideSpec::new(0x102, 16); + follows.fill = [0, 0xFF, 0, 0xFE]; + let mut unfilled = SlideSpec::new(0x103, 16); + unfilled.follow_background = false; + unfilled.filled = false; + let p = deck(&[rgb, slot, follows, unfilled]); + assert_eq!(p.slides[0].background, solid(0xFF, 0, 0)); + assert_eq!(p.slides[1].background, solid(0x12, 0x34, 0x56)); + assert_eq!(p.slides[2].background, None); + assert_eq!(p.slides[3].background, Some(Background::Fill { fill: Fill::None })); +} + +/// Damaged input never panics or grows without bound: every word set to hostile values, +/// truncations, deep nesting and huge counts. +#[test] +fn hostile_powerpoint_95_streams_never_panic() { + let mut s = SlideSpec::new(0x100, 0); + s.follow_background = false; + s.fill = [0, 0, 0, 7]; + let stream = stream_of(document_atom(5760, 4320, 1), &[slide(&s)], &[master(MASTER, DEFAULT, [0; 4])]); + for at in (0..stream.len() - 4).step_by(4) { + for v in [0u32, 1, 3, 1000, 0xFFFF, 0x7FFF_FFFF, 0xFFFF_FFFF] { + let mut d = stream.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let _ = import(&d); + } + } + for cut in 0..stream.len() { + let _ = import(&stream[..cut]); + } + // A length past the end of the stream: the body is clipped to what is there. + let mut long = stream.clone(); + long[8..12].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + assert_eq!(import(&long).unwrap().slides.len(), 1); + // Deep nesting: lists inside lists, which the reader doesn't descend into. + let mut deep = slide(&SlideSpec::new(0x100, 0)); + for _ in 0..2_000 { + deep = container(rt::LIST, 0xA, &[deep]); + } + assert_eq!(import(&stream_of(document_atom(5760, 4320, 1), &[deep], &[])).unwrap().slides.len(), 0); + // Huge counts: the document's slide count, the list count and a scheme's count are not sizes. + let mut huge = SlideSpec::new(0x100, 0); + huge.scheme = DEFAULT; + let mut d = stream_of(document_atom(u32::MAX, u32::MAX, u32::MAX), &[slide(&huge)], &[]); + let count = rec(2001, 0, 0, &le32(&[1])); + let at = d.windows(count.len()).position(|w| w == count).unwrap(); + d[at + 16..at + 20].copy_from_slice(&u32::MAX.to_le_bytes()); + let p = import(&d).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0), "an out-of-range size falls back"); + // Many slides stop at the limit. + let empty = rec(rt::SLIDE, NONE, 0x10, &[]); + let many = vec![empty; super::MAX_SLIDES + 5]; + let p = import(&stream_of(document_atom(5760, 4320, 0), &many, &[])).unwrap(); + assert_eq!(p.slides.len(), super::MAX_SLIDES); +} + +/// 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. +#[test] +fn powerpoint_95_samples() { + let Some(dir) = std::env::var_os("CRAFT_PPT95_SAMPLES") else { return }; + let mut seen = 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")) { + continue; + } + let name = path.file_stem().unwrap().to_string_lossy().into_owned(); + let bytes = std::fs::read(&path).unwrap(); + let p = crate::import(&bytes, &AppDefaults).unwrap_or_else(|e| panic!("{name}: {e}")); + let file = craft_cfb::CompoundFile::open(&bytes).unwrap(); + let stream = file.read_path_capped("PowerPoint Document", bytes.len() as u64).unwrap(); + let count = super::document(&stream).and_then(|d| d.child(rt::DOCUMENT_ATOM)).and_then(|a| a.u32(32)).unwrap(); + assert_eq!(p.slides.len(), count as usize, "{name}"); + assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0), "{name}"); + match name.as_str() { + "twoslides" => assert_eq!(p.slides.len(), 2), + "title" => assert_eq!(layout_kind(&p, 1), LayoutType::Title), + "layout3" => assert_eq!(layout_kind(&p, 1), LayoutType::TwoContent), + "background" => assert_eq!(p.slides[0].background, solid(0xFF, 0, 0)), + _ => {} + } + seen += 1; + } + eprintln!("read {seen} PowerPoint 95 samples"); + assert!(seen > 0); +} diff --git a/crates/ppt-binary/src/tests.rs b/crates/ppt-binary/src/tests.rs index 55ed55396..7a9c6b286 100644 --- a/crates/ppt-binary/src/tests.rs +++ b/crates/ppt-binary/src/tests.rs @@ -15,7 +15,7 @@ use crate::text::tests::{cf_bytes, pf_bytes}; /// A default master as an application gives one: title, body and footer placeholders on the /// master, and the layouts `.ppt` layout types map to, each with its placeholders. The `.ppt` /// masters place and style these. -struct AppDefaults; +pub(crate) struct AppDefaults; impl Defaults for AppDefaults { fn master(&self, size: Size, after: u32) -> (Master, u32) { @@ -74,7 +74,7 @@ fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), crate::Pp } /// A version 3 compound file holding `streams` at its root. -fn build(streams: &[(&str, &[u8])]) -> Vec { +pub(crate) fn build(streams: &[(&str, &[u8])]) -> Vec { craft_cfb::write_streams(craft_cfb::Version::V3, streams).unwrap() } @@ -390,7 +390,7 @@ fn file_with(token: u32) -> Vec { build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]) } -fn file() -> Vec { +pub(crate) fn file() -> Vec { file_with(0xE391_C05F) }