diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 1b6105f24..5805271e0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos | `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files | | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | +| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | | `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index a91d9773a..0d6507970 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2969,6 +2969,19 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ppt-binary" +version = "0.1.0" +dependencies = [ + "craft-cfb", + "craft-drawingml", + "craft-pptx", + "image", + "log", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + [[package]] name = "craft-pptx" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c36973b4a..a278beb41 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -161,6 +161,7 @@ craft-opc = { path = "crates/opc" } craft-openpgp = { path = "crates/openpgp" } craft-ora = { path = "crates/ora" } craft-pptx = { path = "crates/pptx" } +craft-ppt-binary = { path = "crates/ppt-binary" } craft-penpot = { path = "crates/penpot" } craft-pcraft-format = { path = "crates/pcraft-format" } craft-pcraft-bundle = { path = "crates/pcraft-bundle" } diff --git a/README.md b/README.md index c4dabafb6..951298091 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL, DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a job in millimetres, plus the Silhouette device queries and reply parsers. No I/O. +- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`; + [MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader. - [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation: masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations, comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`. diff --git a/crates/ppt-binary/Cargo.toml b/crates/ppt-binary/Cargo.toml new file mode 100644 index 000000000..897aad8a4 --- /dev/null +++ b/crates/ppt-binary/Cargo.toml @@ -0,0 +1,23 @@ +[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." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-cfb = { workspace = true } +craft-drawingml = { workspace = true } +craft-pptx = { workspace = true } +log = { workspace = true } +miniz_oxide = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +# Pictures in the tests: a PNG to embed, and the BMP a DIB blip becomes. +image = { version = "0.25", default-features = false, features = ["png", "bmp"] } diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md new file mode 100644 index 000000000..d1bbdd24e --- /dev/null +++ b/crates/ppt-binary/README.md @@ -0,0 +1,40 @@ +# craft-ppt-binary + +Reader for the PowerPoint 97-2003 binary file format (`.ppt`, `.pot` and `.pps`) into the +`craft-pptx` presentation model. It is DeckCraft's reader, on `craft-cfb` for the compound file. +Import only: there is no `.ppt` writer. + +| Document | Used for | +|---|---| +| [MS-PPT] PowerPoint (.ppt) Binary File Format (Microsoft Open Specifications) | the Current User stream, the edit chain and persist directories, documents, masters, slides, notes, text and its styles, headers and footers | +| [MS-ODRAW] Office Drawing Binary File Formats | shapes, their property tables and geometry, the BLIP store and its pictures | +| [MS-CFB] Compound File Binary File Format | through `craft-cfb` | + +```rust +// Not a compound file: an error, never a panic. +assert!(!craft_ppt_binary::sniff(b"not a .ppt")); +assert!(craft_ppt_binary::import(b"not a .ppt", &craft_pptx::Plain).is_err()); +``` + +- `sniff(bytes)`, `import(bytes, &defaults)` and `import_checked(bytes, &defaults)`, which also + names the slides the file lists but whose objects are gone. +- Main masters become masters, with their colour scheme, fonts, text styles, background and + decorative shapes. Title masters become layouts of their main master. +- Slides keep their shapes (preset and freeform geometry, groups, rotation and flips), fills, + lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF and WMF), tables (as groups of shapes, the + way the file stores them), and text with the master's styles resolved into it, along with + fields, numbering, headers and footers, notes, and hidden slides. +- 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 + files (`PptError::TooOld`). + +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 +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. diff --git a/crates/ppt-binary/src/blip.rs b/crates/ppt-binary/src/blip.rs new file mode 100644 index 000000000..56b6abaec --- /dev/null +++ b/crates/ppt-binary/src/blip.rs @@ -0,0 +1,404 @@ +//! Pictures ([MS-ODRAW] §2.2.32–2.2.45): the drawing group's blip store lists every picture +//! (`FBSE`), either holding its blip or pointing into the `Pictures` stream. Shapes name a picture +//! by its 1-based index in the store. + +use crate::doc::rt; +use crate::record::Rec; + +/// Largest picture inflated from a compressed metafile. +const MAX_INFLATED: usize = 64 << 20; +/// Most bytes all of a file's pictures may decode to together: 2 GiB, the total a `.pptx` package +/// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt` +/// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could. +/// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0. +const MAX_TOTAL: usize = 2 << 30; +// A zero or tiny budget would drop every picture without a word, and the shift above can wrap on +// a 32-bit target (wasm32) without any error, so the build checks it on every target. +const _: () = assert!(MAX_TOTAL >= MAX_INFLATED); + +/// A decoded picture: file extension, content type and bytes as a file of that type. +#[derive(Clone, Debug, PartialEq)] +pub struct Picture { + pub ext: &'static str, + pub content_type: &'static str, + pub data: Vec, +} + +/// The blip store: each entry's blip record, decoded only when a shape first asks for it, every +/// entry at most once, and all of them together within [`MAX_TOTAL`] bytes. +pub struct Store<'a> { + entries: Vec>>, + budget: usize, +} + +impl<'a> Store<'a> { + pub fn new(dgg: Option>, pictures_stream: &'a [u8]) -> Self { + let entries = match dgg.and_then(|d| d.child(rt::BSTORE)) { + Some(bstore) => bstore.children().map(|r| if r.kind == rt::FBSE { fbse(&r, pictures_stream) } else { None }).collect(), + None => vec![], + }; + Store { entries, budget: MAX_TOTAL } + } + + /// The picture at `index` (0-based; shapes use 1-based ids), taken out of the store. `None` + /// for an entry that is empty, can't be read, was taken already, or would pass the budget. + pub fn take(&mut self, index: usize) -> Option { + let blip = self.entries.get_mut(index)?.take()?; + self.decode_charged(&blip) + } + + /// A blip held in a shape's own property ([MS-ODRAW] §2.2.37: a complex `fillBlip` or `pib` + /// whose extra bytes are the blip record itself), decoded within the same budget. + pub fn decode_inline(&mut self, bytes: &[u8]) -> Option { + let blip = Rec::at(bytes, 0).filter(|r| (0xF018..=0xF117).contains(&r.kind))?; + self.decode_charged(&blip) + } + + /// Decode `blip` and take its size from the budget. A compressed metafile is also charged + /// its compressed bytes, which inflating reads whatever it produces, and one that fails to + /// inflate is charged what the inflate may have produced before failing: many entries pointing + /// at one damaged stream (or one that inflates to nothing) would otherwise each inflate it again + /// for free. + fn decode_charged(&mut self, blip: &Rec) -> Option { + let bounds = inflate_bounds(blip, self.budget); + let pic = decode(blip, self.budget); + let cost = match (&pic, bounds) { + (Some(p), Some((input, _))) => input.saturating_add(p.data.len()), + (Some(p), None) => p.data.len(), + (None, Some((input, output))) => input.saturating_add(output), + (None, None) => 0, + }; + self.budget = self.budget.saturating_sub(cost); + pic + } +} + +/// For a compressed metafile (EMF or WMF, with one UID or, for instances 0x3D5 and 0x217, two): +/// the compressed bytes inflating it reads, and the most bytes it may produce so that both +/// together stay within `limit`. `None` for any other blip, or when the compressed bytes alone +/// pass `limit`. +fn inflate_bounds(b: &Rec, limit: usize) -> Option<(usize, usize)> { + if !matches!(b.kind, 0xF01A | 0xF01B) { + return None; + } + let uids = if matches!(b.instance, 0x3D5 | 0x217) { 32 } else { 16 }; + let h = b.data.get(uids..uids + 34)?; + let size = crate::record::u32_at(h, 0)? as usize; + if *h.get(32)? != 0 { + return None; + } + let input = b.data.get(uids + 34..)?.len(); + let output = limit.checked_sub(input)?; + Some((input, size.min(MAX_INFLATED).min(output))) +} + +fn fbse<'a>(r: &Rec<'a>, pictures: &'a [u8]) -> Option> { + // btWin32, btMacOS, rgbUid[16], tag, size, cRef, foDelay, unused, cbName, unused, unused. + let size = r.u32(20)? as usize; + let offset = r.u32(28)? as usize; + let name_len = usize::from(r.u8(33)?); + if size == 0 { + return None; + } + let embedded_at = 36usize.checked_add(name_len)?; + if r.data.len() > embedded_at { Rec::at(r.data, embedded_at) } else { Rec::at(pictures, offset) } +} + +/// Decode one blip record into at most `limit` bytes. +pub fn decode(b: &Rec, limit: usize) -> Option { + // The instance says whether a second UID follows the first. + let (kind, two_uids): (u16, bool) = match b.instance { + 0x3D4 | 0x216 | 0x542 | 0x46A | 0x6E2 | 0x6E0 | 0x7A8 | 0x6E4 => (b.kind, false), + 0x3D5 | 0x217 | 0x543 | 0x46B | 0x6E3 | 0x6E1 | 0x7A9 | 0x6E5 => (b.kind, true), + _ => (b.kind, false), + }; + let uids = if two_uids { 32 } else { 16 }; + // The bytes a picture is copied from, refused before copying when they (plus `extra` bytes of + // header to add) would pass the budget. + let within = |bytes: &'_ [u8], extra: usize| bytes.len().checked_add(extra).is_some_and(|n| n <= limit); + let bitmap = || b.data.get(uids + 1..).filter(|d| within(d, 0)).map(<[u8]>::to_vec); + match kind { + // EMF, WMF: a metafile header then (usually deflated) data. + 0xF01A | 0xF01B => { + let h = b.data.get(uids..uids + 34)?; + let size = crate::record::u32_at(h, 0)? as usize; + let compressed = *h.get(32)? == 0; + let body = b.data.get(uids + 34..)?; + let data = if compressed { + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(body, inflate_bounds(b, limit)?.1).ok()? + } else { + body.get(..size.min(body.len())).filter(|d| within(d, 0))?.to_vec() + }; + let (ext, content_type) = if kind == 0xF01A { ("emf", "image/x-emf") } else { ("wmf", "image/x-wmf") }; + Some(Picture { ext, content_type, data }) + } + // Bitmaps: a one-byte tag then the file. + 0xF01D | 0xF02A => Some(Picture { ext: "jpg", content_type: "image/jpeg", data: bitmap()? }), + 0xF01E => Some(Picture { ext: "png", content_type: "image/png", data: bitmap()? }), + 0xF029 => Some(Picture { ext: "tif", content_type: "image/tiff", data: bitmap()? }), + 0xF01F => Some(Picture { ext: "bmp", content_type: "image/bmp", data: dib_to_bmp(b.data.get(uids + 1..).filter(|d| within(d, 14))?)? }), + // PICT (Macintosh) has no decoder here. + _ => None, + } + .filter(|p| p.data.len() <= limit) +} + +/// A device-independent bitmap with the 14-byte file header a `.bmp` needs in front. +fn dib_to_bmp(dib: &[u8]) -> Option> { + let header = crate::record::u32_at(dib, 0)? as usize; + let (bits, compression, used) = if header == 12 { + (usize::from(crate::record::u16_at(dib, 10)?), 0, 0) + } else { + (usize::from(crate::record::u16_at(dib, 14)?), crate::record::u32_at(dib, 16)?, crate::record::u32_at(dib, 32)? as usize) + }; + let entry = if header == 12 { 3 } else { 4 }; + // The colour table: up to 2^bits entries (all of them when biClrUsed is 0) for 8 bits or + // fewer; biClrUsed entries, an optional table, for more. + let colors = match bits { + 0..=8 if used > 0 => used.min(1 << bits), + 0..=8 => 1 << bits, + _ => used, + }; + // BI_BITFIELDS with the 40-byte header: three masks follow it. + let masks = if compression == 3 && header == 40 { 12 } else { 0 }; + let offset = 14usize.checked_add(header)?.checked_add(colors.checked_mul(entry)?)?.checked_add(masks)?; + let file_len = 14usize.checked_add(dib.len())?; + // Pixels starting past the end are no bitmap. + if offset > file_len { + return None; + } + let total = u32::try_from(file_len).ok()?; + let mut out = Vec::with_capacity(dib.len() + 14); + out.extend_from_slice(b"BM"); + out.extend_from_slice(&total.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&u32::try_from(offset).ok()?.to_le_bytes()); + out.extend_from_slice(dib); + Some(out) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + fn decode_all(b: &Rec) -> Option { + decode(b, usize::MAX) + } + + /// Many entries pointing at one deflated metafile decode within the shared budget, each + /// at most once. + #[test] + fn the_store_decodes_lazily_within_a_budget() { + let wmf = vec![7u8; 1000]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let pictures = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes()); + let entries: Vec> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &pictures); + store.budget = 2500; + assert_eq!(store.take(0).map(|p| p.data.len()), Some(1000)); + assert!(store.take(0).is_none(), "taken already"); + assert!(store.take(1).is_some()); + assert!(store.take(2).is_none(), "past the budget"); + assert!(store.take(99).is_none()); + } + + /// A compressed metafile that fails to inflate still costs the budget what it may have + /// inflated, so entries pointing at one damaged stream can't each inflate it again for free. + #[test] + fn a_failed_inflate_is_charged_to_the_budget() { + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&1000u32.to_le_bytes()); + let damaged = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &[0x78, 0x9C, 0xFF, 0xFF]].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(damaged.len() as u32).to_le_bytes()); + let entries: Vec> = (0..3).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 3, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &damaged); + store.budget = 2500; + assert!(store.take(0).is_none()); + assert_eq!(store.budget, 1496, "1000 bytes it may have inflated and the 4 it read"); + assert!(store.take(1).is_none()); + assert!(store.take(2).is_none()); + assert_eq!(store.budget, 0, "the last attempt is charged what was left"); + // A picture that isn't a compressed metafile costs nothing when it can't be read. + let mut store = Store::new(None, &[]); + store.budget = 10; + assert!(store.decode_inline(&atom(0xF01E, 0x6E0, &[0; 4])).is_none()); + assert_eq!(store.budget, 10); + } + + /// A compressed metafile that inflates to nothing (a declared size of 0 and a run of empty + /// stored blocks, here with a bad checksum) still costs the bytes it makes the inflate read, so + /// many entries pointing at it run out of budget instead of each reading it again for free. + #[test] + fn inflating_is_charged_the_compressed_bytes() { + let mut z = vec![0x78, 0x01]; + for _ in 0..200 { + z.extend_from_slice(&[0x00, 0x00, 0x00, 0xFF, 0xFF]); + } + z.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF, 1, 2, 3, 4]); + let empty = atom(0xF01B, 0x216, &[&[0u8; 16][..], &[0u8; 34], &z].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(empty.len() as u32).to_le_bytes()); + let entries: Vec> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &empty); + store.budget = 2 * z.len() + 10; + assert!(store.take(0).is_none()); + assert_eq!(store.budget, z.len() + 10); + assert!(store.take(1).is_none()); + assert_eq!(store.budget, 10); + // Too little left for its compressed bytes: not inflated, and nothing charged. + assert!(store.take(2).is_none()); + assert_eq!(store.budget, 10); + // One that inflates is charged its compressed bytes as well as what they inflate to. + let wmf = vec![7u8; 100]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let blip = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + let mut store = Store::new(None, &[]); + store.budget = 1000; + assert_eq!(store.decode_inline(&blip).map(|p| p.data.len()), Some(100)); + assert_eq!(store.budget, 1000 - 100 - z.len()); + } + + #[test] + fn decodes_png_and_deflated_metafiles() { + let png = [&[0u8; 17][..], b"\x89PNG..."].concat(); + let p = decode_all(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap()).unwrap(); + assert_eq!((p.ext, &p.data[..4]), ("png", &b"\x89PNG"[..])); + // Over the remaining budget: refused before it is copied. + assert!(decode(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap(), 6).is_none()); + + let wmf = b"\x01\x00\x09\x00\x00\x03 a tiny metafile".to_vec(); + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + header[28..32].copy_from_slice(&(z.len() as u32).to_le_bytes()); + let body = [&[0u8; 16][..], &header, &z].concat(); + let p = decode_all(&Rec::at(&atom(0xF01B, 0x216, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, p.data), ("wmf", wmf)); + // Damaged deflate data is no picture rather than a panic. + let bad = [&[0u8; 16][..], &header, &[1, 2, 3]].concat(); + assert!(decode_all(&Rec::at(&atom(0xF01A, 0x3D4, &bad), 0).unwrap()).is_none()); + } + + #[test] + fn a_dib_becomes_a_bmp_the_image_crate_reads() { + // 1×1, 24-bit. + let mut dib = vec![0u8; 40]; + dib[0] = 40; + dib[4] = 1; + dib[8] = 1; + dib[12] = 1; + dib[14] = 24; + dib.extend_from_slice(&[0, 0, 255, 0]); + let body = [&[0u8; 17][..], &dib].concat(); + let p = decode_all(&Rec::at(&atom(0xF01F, 0x7A8, &body), 0).unwrap()).unwrap(); + assert_eq!(&p.data[..2], b"BM"); + assert_eq!(u32::from_le_bytes(p.data[10..14].try_into().unwrap()), 54); + let img = image::load_from_memory_with_format(&p.data, image::ImageFormat::Bmp).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (1, 1)); + assert_eq!(img.get_pixel(0, 0).0, [255, 0, 0, 255]); + } + + /// The pixels start after the colour table: biClrUsed entries for more than 8 bits (none when + /// it is 0), at most 2^bits for fewer, and a table running past the DIB is no picture. + #[test] + fn a_dib_colour_table_is_sized_by_its_bit_depth() { + let dib = |bits: u16, used: u32, extra: usize| { + let mut d = vec![0u8; 40]; + d[0] = 40; + d[14..16].copy_from_slice(&bits.to_le_bytes()); + d[32..36].copy_from_slice(&used.to_le_bytes()); + d.resize(40 + extra, 0); + d + }; + let offset = |b: &[u8]| dib_to_bmp(b).map(|bmp| u32::from_le_bytes(bmp[10..14].try_into().unwrap())); + assert_eq!(offset(&dib(24, 0, 4)), Some(54)); + assert_eq!(offset(&dib(24, 300, 1204)), Some(54 + 1200), "more than 256 entries for 24 bits"); + assert_eq!(offset(&dib(8, 300, 1028)), Some(54 + 1024), "8 bits: at most 256"); + assert_eq!(offset(&dib(4, 0, 68)), Some(54 + 64)); + assert_eq!(offset(&dib(24, 300, 100)), None, "the table runs past the DIB"); + assert_eq!(offset(&dib(32, u32::MAX, 0)), None); + } + + /// JPEG (RGB and CMYK), TIFF and a PNG with a second UID: the instance says how many UIDs come + /// before the tag byte, and the bytes after it are the file. + #[test] + fn decodes_each_bitmap_kind() { + let file = b"the picture file"; + for (kind, instance, uids, ext) in [ + (0xF01D, 0x46A, 16, "jpg"), + (0xF01D, 0x46B, 32, "jpg"), + (0xF02A, 0x6E2, 16, "jpg"), + (0xF029, 0x6E4, 16, "tif"), + (0xF029, 0x6E5, 32, "tif"), + (0xF01E, 0x6E1, 32, "png"), + ] { + let body = [&vec![0xAAu8; uids][..], &[0xFF], file].concat(); + let p = decode_all(&Rec::at(&atom(kind, instance, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, p.data.as_slice()), (ext, &file[..]), "{kind:#x}/{instance:#x}"); + } + } + + /// A metafile stored without compression (compression byte 0xFE) is copied as it is, up to its + /// stated size; with two UIDs the header starts 32 bytes in. + #[test] + fn decodes_an_uncompressed_metafile() { + let emf = b"\x01\x00\x00\x00 an enhanced metafile".to_vec(); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(emf.len() as u32).to_le_bytes()); + header[28..32].copy_from_slice(&(emf.len() as u32).to_le_bytes()); + header[32] = 0xFE; + for (instance, uids) in [(0x3D4, 16), (0x3D5, 32)] { + let body = [&vec![0u8; uids][..], &header, &emf, b"trailing"].concat(); + let p = decode_all(&Rec::at(&atom(0xF01A, instance, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, &p.data), ("emf", &emf)); + } + } + + /// A metafile whose inflated size (with its compressed bytes) would pass the remaining budget is refused, compressed or not. + #[test] + fn a_metafile_over_the_budget_is_refused() { + let wmf = vec![9u8; 4000]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let deflated = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + // The budget covers the compressed bytes read as well as the bytes they inflate to. + assert!(decode(&Rec::at(&deflated, 0).unwrap(), 3999 + z.len()).is_none()); + assert_eq!(decode(&Rec::at(&deflated, 0).unwrap(), 4000 + z.len()).map(|p| p.data.len()), Some(4000)); + header[32] = 0xFE; + let raw = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &wmf].concat()); + assert!(decode(&Rec::at(&raw, 0).unwrap(), 3999).is_none()); + assert!(decode(&Rec::at(&raw, 0).unwrap(), 4000).is_some()); + } + + /// An FBSE may hold its blip itself, after its name, instead of pointing into the Pictures + /// stream. + #[test] + fn a_blip_inside_its_fbse_is_read() { + let png = [&[0u8; 17][..], b"\x89PNG inside"].concat(); + let blip = atom(0xF01E, 0x6E0, &png); + let name = "p".encode_utf16().flat_map(u16::to_le_bytes).collect::>(); + let mut fbse = [0u8; 36]; + fbse[20..24].copy_from_slice(&(blip.len() as u32).to_le_bytes()); + fbse[33] = name.len() as u8; + let entry = atom(rt::FBSE, 6, &[&fbse[..], &name, &blip].concat()); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 1, &[entry])]); + // The Pictures stream is empty: the blip can only come from the FBSE. + let mut store = Store::new(Rec::at(&dgg, 0), &[]); + let p = store.take(0).unwrap(); + assert_eq!((p.ext, &p.data[..]), ("png", &b"\x89PNG inside"[..])); + } +} diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs new file mode 100644 index 000000000..f7897cdbb --- /dev/null +++ b/crates/ppt-binary/src/convert.rs @@ -0,0 +1,1181 @@ +//! Building a `craft_pptx` presentation from the parsed `.ppt` structure. +//! +//! Each main master becomes a master: the caller's default master (its layouts and placeholders), +//! with the file's colours, fonts, text styles, background and decorative shapes, and the file's +//! placeholder boxes on the placeholders the default master has. A title master becomes a layout +//! of its main master. Slide shapes keep their own boxes, and their text carries its formatting +//! resolved against the master's text styles, so it draws the same whatever the layouts hold. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use craft_pptx::style::{Dash, LineCap, LineEnd, LineJoin, PictureFill, PictureMode, Shadow}; +use craft_pptx::text::{Align, Anchor as TextAnchor, AutoFit, BodyProps, Bullet, LevelStyle, ListStyle, ParaProps, RunKind, Spacing, TabStop}; +use craft_pptx::{ + Background, ColorRef, Defaults, Effects, Fill, Layout, LayoutId, LayoutType, Line, Master, MediaId, Paragraph, PhType, Placeholder, Presentation, + Run, RunProps, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, TextBody, Theme, Xfrm, +}; +use craft_pptx::{ColorTransform, Rgba, SchemeSlot}; + +use crate::doc::{self, Doc, Listed, rt}; +use crate::draw::{self, Props, RawShape, prop}; +use crate::geom; +use crate::record::{MAX_DEPTH, Rec}; +use crate::text::{self, Cf, FieldKind, Pf, StyleSheet, TextBlock, TextColor, ty}; + +/// Master units (576 per inch) per point. +const MU: f64 = 8.0; +/// EMUs per point. +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]; + +const DEFAULT_SCHEME: Scheme = [ + Rgba::rgb(0xFF, 0xFF, 0xFF), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0x80, 0x80, 0x80), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0xBB, 0xE0, 0xE3), + Rgba::rgb(0x33, 0x33, 0x99), + Rgba::rgb(0, 0x99, 0x99), + Rgba::rgb(0x99, 0xCC, 0x00), +]; + +fn scheme_of(container: &Rec) -> Option { + let r = container.children_of(rt::COLOR_SCHEME).find(|r| r.instance == 1)?; + let mut s = DEFAULT_SCHEME; + for (i, c) in s.iter_mut().enumerate() { + *c = Rgba::rgb(r.u8(i * 4)?, r.u8(i * 4 + 1)?, r.u8(i * 4 + 2)?); + } + Some(s) +} + +/// What converting one drawing needs besides the shapes. +struct Scope<'s, 'a> { + scheme: Scheme, + styles: &'s StyleSheet, + /// The slide list's outline text, for placeholders that point at it. + outline: &'s [crate::record::Records<'a>], + /// Each outline block's numbering (`StyleTextProp9Atom` entries), by outline index. + numbering: &'s [Option>], + /// The outline blocks a shape has taken already. Each block is one shape's text: a second + /// shape pointing at it keeps its own, so a big block can't be copied into every shape. + used_outline: RefCell>, + master: bool, + /// Where `hspMaster` shape ids are looked up: the slide's master, then a title master's main + /// master. + masters: Chain, +} + +/// Master slide ids, nearest first. +type Chain = [Option; 2]; + +struct Ctx<'a> { + p: Presentation, + fonts: Vec, + blips: crate::blip::Store<'a>, + media: HashMap>, + /// Pictures held in a shape's own property, by where their bytes start, so a master shape's + /// picture inherited by many slides is added once. + inline_media: HashMap>, + /// The slides' outline numbering, by slide id and text type ([`doc::outline_numbering`]). + numbering: HashMap<(u32, u32), Vec>>, + defaults: Props<'a>, + /// Master shapes by master slide id and shape id, for slide shapes that inherit from one + /// (`hspMaster`). Keyed by master too, so a shape id repeated in another master can't replace + /// this master's shape. + master_props: HashMap<(u32, u32), Props<'a>>, + /// The caller's defaults: the master each of the file's masters starts from. + app: &'a dyn Defaults, + /// Notes pages converted already. Distinct slides can share a slide id, and so a notes page: + /// it goes to the first of them only, so its text isn't copied into every one. + used_notes: HashSet, +} + +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)); + // 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.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 { + p, + fonts: doc::fonts(d), + blips: crate::blip::Store::new(dgg, pictures), + media: HashMap::new(), + inline_media: HashMap::new(), + numbering: doc::outline_numbering(&d.document), + defaults: draw::default_props(dgg), + master_props: HashMap::new(), + app, + used_notes: HashSet::new(), + }; + let environment = d.document.child(rt::ENVIRONMENT); + if let Some(hf) = doc::headers_footers(&d.document, 3) { + cx.p.header_footer = craft_pptx::HeaderFooter { + date: hf.date, + slide_number: hf.slide_number, + footer: hf.footer, + footer_text: hf.footer_text, + date_text: if hf.user_date { hf.date_text } else { String::new() }, + date_format: format!("datetime{}", hf.format.min(12) + 1), + ..Default::default() + }; + } + + // Main masters first, then title masters as layouts of theirs. + let mut masters: HashMap = HashMap::new(); + for m in d.masters.iter().filter(|m| m.rec.kind == rt::MAIN_MASTER) { + if let Some(info) = cx.main_master(m, environment, size) { + masters.insert(m.slide_id, info); + } + } + if cx.p.masters.is_empty() { + let m = cx.default_master(size, None); + cx.p.masters.push(Arc::new(m)); + } + for m in d.masters.iter().filter(|m| m.rec.kind == rt::SLIDE) { + cx.title_master(m, &mut masters); + } + + // Each slide's notes page, by the slide id its NotesAtom names (the first one wins), built once: + // a scan per slide would be slides × notes pages. + let mut notes_of: HashMap = HashMap::new(); + for (i, n) in d.notes.iter().enumerate() { + if n.rec.kind == rt::NOTES + && let Some(id) = n.rec.child(rt::NOTES_ATOM).and_then(|a| a.u32(0)) + { + notes_of.entry(id).or_insert(i); + } + } + // An unknown master falls back to the first main master. Title masters share their main + // master's index, so including them would tie, and HashMap order would pick the winner. Found + // once, as is each master's layout for each layout type: a search per slide would be slides × + // masters (or layouts). A title master's layout is only for the slides that name it. + let first_main = masters.values().filter(|m| m.layout.is_none()).min_by_key(|m| m.index).cloned(); + let title_layouts: HashSet = masters.values().filter_map(|m| m.layout).collect(); + let layouts: Vec = cx.p.masters.iter().map(|m| layout_table(m, &title_layouts)).collect(); + let find = Find { masters: &masters, first_main: first_main.as_ref(), layouts: &layouts, notes_of: ¬es_of }; + for s in &d.slides { + if s.rec.kind != rt::SLIDE { + continue; + } + if let Some(slide) = cx.slide(d, s, &find) { + cx.p.slides.push(Arc::new(slide)); + } + } + cx.p +} + +/// A master's first layout of each layout type, and its first layout. +type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option); + +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); + for l in layouts { + // Layout types are few, so the list stays short. + if !kinds.iter().any(|(k, _)| *k == l.kind) { + kinds.push((l.kind, l.id)); + } + } + (kinds, first) +} + +/// What a slide's master, layout and notes page are looked up in. +struct Find<'f> { + masters: &'f HashMap, + first_main: Option<&'f MasterInfo>, + layouts: &'f [LayoutTable], + notes_of: &'f HashMap, +} + +/// A converted master: where it went and what its slides inherit. +#[derive(Clone)] +struct MasterInfo { + index: usize, + scheme: Scheme, + styles: Arc, + /// A layout made for a title master; slides of that title master use it. + layout: Option, + /// This master's slide id, then its main master's for a title master. + ids: Chain, + /// The placeholders of the defaults' title layout, taken before any title master adds layouts + /// of its own: what each title master's layout starts from. Empty when there is none. + title_base: Arc>, +} + +impl<'a> Ctx<'a> { + fn alloc(&mut self) -> Option { + self.p.alloc_id() + } + + /// The caller's default master for slides of `size`, with ids above every id handed out so + /// far. With `theme`, the master wears it and is named after it. + fn default_master(&mut self, size: Size, theme: Option) -> Master { + let (mut master, last) = self.app.master(size, self.p.next_id); + self.p.next_id = self.p.next_id.max(last); + if let Some(theme) = theme { + master.name = theme.name.clone(); + master.theme = theme; + } + master + } + + fn main_master(&mut self, m: &Listed<'a>, environment: Option>, size: Size) -> Option { + let scheme = scheme_of(&m.rec).unwrap_or(DEFAULT_SCHEME); + let styles = Arc::new(StyleSheet::new(environment, Some(&m.rec))); + let theme = self.theme(&scheme, &styles); + let mut master = self.default_master(size, Some(theme)); + let drawing = draw::drawing(&m.rec); + self.remember_master_props(m.slide_id, &drawing.shapes, 0); + let ids = [Some(m.slide_id), None]; + let scope = + Scope { scheme, styles: &styles, outline: &m.outline, numbering: &[], used_outline: Default::default(), master: true, masters: ids }; + master.background = drawing.background.as_ref().and_then(|b| self.background(b, &scope)); + for raw in &drawing.shapes { + if let Some(ph) = raw.placeholder.filter(|p| p.kind != 0) { + // The master's placeholders set where new slides' placeholders go. + if let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) + && let Some(s) = master.shapes.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) + { + s.xfrm = Some(x); + // The footer row sits in the same place on every layout, with the master's look: + // its first paragraph's alignment and its first run's size and colour. + if matches!(kind, PhType::Date | PhType::Footer | PhType::SlideNum) { + let look = self.shape(raw, &scope, 0, TOP).and_then(|c| c.text).and_then(|t| t.paragraphs.into_iter().next()); + let style = |t: &mut TextBody| { + if let Some(p) = &look { + let mut level = t.list_style.level(0).cloned().unwrap_or_default(); + level.para.align = p.props.align.or(level.para.align); + if let Some(run) = p.runs.first() { + level.run.size = run.props.size.or(level.run.size); + level.run.fill = run.props.fill.clone().or(level.run.fill.take()); + } + t.list_style.set(0, level); + } + }; + if let Some(t) = s.text.as_mut() { + style(t); + } + for l in &mut master.layouts { + for ls in l.shapes.iter_mut().filter(|ls| ls.ph_type() == Some(kind)) { + ls.xfrm = Some(x); + if let Some(t) = ls.text.as_mut() { + style(t); + } + } + } + } + } + continue; + } + if let Some(s) = self.shape(raw, &scope, 0, TOP) { + master.shapes.push(s); + } + } + master.title_style = self.list_style(&styles, ty::TITLE, &scheme); + master.body_style = self.list_style(&styles, ty::BODY, &scheme); + master.other_style = self.list_style(&styles, ty::OTHER, &scheme); + let title_base = master + .layouts + .iter() + .find(|l| l.kind == LayoutType::Title) + .map(|l| l.shapes.iter().filter(|s| s.ph.is_some()).cloned().collect()) + .unwrap_or_default(); + let index = self.p.masters.len(); + self.p.masters.push(Arc::new(master)); + Some(MasterInfo { index, scheme, styles, layout: None, ids, title_base: Arc::new(title_base) }) + } + + /// A title master: a layout of its main master holding its background and shapes. + fn title_master(&mut self, m: &Listed<'a>, masters: &mut HashMap) { + let atom = doc::slide_atom(&m.rec); + let Some(parent) = masters.get(&atom.master_id).cloned() else { return }; + let scheme = if atom.follow_master_scheme { parent.scheme } else { scheme_of(&m.rec).unwrap_or(parent.scheme) }; + let Some(id) = self.alloc() else { return }; + let drawing = draw::drawing(&m.rec); + self.remember_master_props(m.slide_id, &drawing.shapes, 0); + let ids = [Some(m.slide_id), parent.ids[0]]; + let scope = Scope { + scheme, + styles: &parent.styles, + outline: &m.outline, + numbering: &[], + used_outline: Default::default(), + master: true, + masters: ids, + }; + let background = if atom.follow_master_background { None } else { drawing.background.as_ref().and_then(|b| self.background(b, &scope)) }; + let shapes: Vec = + drawing.shapes.iter().filter(|r| r.placeholder.is_none_or(|p| p.kind == 0)).filter_map(|r| self.shape(r, &scope, 0, TOP)).collect(); + // Its placeholders follow the main master's own title layout (from the defaults, taken once + // when the main master was made), with ids of their own. A layout made for an earlier title + // master holds that one's shapes and placeholder boxes, so it is never the base. + let mut placeholders = Vec::with_capacity(parent.title_base.len()); + for mut s in parent.title_base.iter().cloned() { + let Some(id) = self.alloc() else { break }; + s.id = ShapeId(id); + placeholders.push(s); + } + // The title master's own placeholders say where its slides' placeholders go, as a main + // master's do; one the title layout lacks is added. + for raw in &drawing.shapes { + let Some(ph) = raw.placeholder.filter(|p| p.kind != 0) else { continue }; + let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) else { continue }; + if let Some(s) = placeholders.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) { + s.xfrm = Some(x); + continue; + } + let Some(id) = self.alloc() else { break }; + placeholders.push(Shape { + id: ShapeId(id), + name: raw.props.string(prop::NAME).unwrap_or_else(|| default_name(raw)), + xfrm: Some(x), + ph: Some(Placeholder { kind, idx: ph.position, ..Default::default() }), + text: Some(TextBody::default()), + ..Default::default() + }); + } + let Some(master) = self.p.masters.get_mut(parent.index) else { return }; + Arc::make_mut(master).layouts.push(Layout { + id: LayoutId(id), + name: "Title Master".into(), + kind: LayoutType::Title, + shapes: shapes.into_iter().chain(placeholders).collect(), + background, + show_master_shapes: atom.follow_master_objects, + ..Default::default() + }); + masters.insert(m.slide_id, MasterInfo { layout: Some(LayoutId(id)), scheme, ids, ..parent }); + } + + fn remember_master_props(&mut self, master: u32, shapes: &[RawShape<'a>], depth: usize) { + if depth > MAX_DEPTH { + return; + } + for s in shapes { + self.master_props.insert((master, s.spid), s.props.clone()); + self.remember_master_props(master, &s.children, depth + 1); + } + } + + /// 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); + } + } + 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(); + } + if let Some(f) = styles.resolve(ty::BODY, 0).1.font.and_then(|i| self.fonts.get(usize::from(i))) { + t.fonts.minor.latin = f.clone(); + } + t + } + + fn list_style(&self, styles: &StyleSheet, text_type: u32, scheme: &Scheme) -> ListStyle { + let mut ls = ListStyle::default(); + for level in 0..5u8 { + let (pf, cf) = styles.resolve(text_type, level); + let run = self.run_props(&cf, scheme); + let para = self.para_props(&pf, scheme, run.size.unwrap_or(18.0)); + ls.set(level, LevelStyle { para, run }); + } + ls + } + + fn slide(&mut self, d: &Doc<'a>, s: &Listed<'a>, find: &Find) -> Option { + let atom = doc::slide_atom(&s.rec); + let info = find.masters.get(&atom.master_id).or(find.first_main).cloned(); + let (index, master_scheme, styles, title_layout, ids) = match &info { + Some(m) => (m.index, m.scheme, m.styles.clone(), m.layout, m.ids), + None => (0, DEFAULT_SCHEME, Arc::new(StyleSheet::new(d.document.child(rt::ENVIRONMENT), None)), None, [None; 2]), + }; + let scheme = if atom.follow_master_scheme { master_scheme } else { scheme_of(&s.rec).unwrap_or(master_scheme) }; + let layout = title_layout.or_else(|| { + let kind = layout_kind(atom.geom); + let (kinds, first) = find.layouts.get(index)?; + kinds.iter().find(|(k, _)| *k == kind).map(|(_, id)| *id).or(*first) + })?; + let id = SlideId(self.alloc()?); + let drawing = draw::drawing(&s.rec); + // The n-th outline block of a text type takes the n-th numbering entry for that type. + let mut seen: HashMap = HashMap::new(); + let numbering: Vec>> = s + .outline + .iter() + .map(|block| { + let tt = block.clone().next().filter(|h| h.kind == rt::TEXT_HEADER).and_then(|h| h.u32(0))?; + let k = seen.entry(tt).or_insert(0); + let n = *k; + *k += 1; + self.numbering.get(&(s.slide_id, tt)).and_then(|v| v.get(n)).cloned() + }) + .collect(); + let scope = Scope { + scheme, + styles: &styles, + outline: &s.outline, + numbering: &numbering, + used_outline: Default::default(), + master: false, + masters: ids, + }; + let background = if atom.follow_master_background { None } else { drawing.background.as_ref().and_then(|b| self.background(b, &scope)) }; + let mut shapes: Vec = drawing.shapes.iter().filter_map(|r| self.shape(r, &scope, 0, TOP)).collect(); + // The slide's own headers and footers, else the document's for every slide. + if let Some(hf) = doc::headers_footers(&s.rec, 0).or_else(|| doc::headers_footers(&d.document, 3)) { + self.footers(&mut shapes, &hf); + } + let hidden = s.rec.child(rt::SLIDE_SHOW_SLIDE_INFO).and_then(|i| i.u16(10)).is_some_and(|f| f & 0x4 != 0); + let notes = find + .notes_of + .get(&s.slide_id) + .filter(|&&i| self.used_notes.insert(i)) + .and_then(|&i| d.notes.get(i)) + .map(|n| self.notes(n, &styles, scheme)) + .unwrap_or_default(); + Some(Slide { id, layout, shapes, background, hidden, show_master_shapes: atom.follow_master_objects, notes, ..Default::default() }) + } + + /// The date, footer and slide number placeholders `hf` turns on, for those the slide doesn't + /// hold itself. They take their place and look from the layout and master. + fn footers(&mut self, shapes: &mut Vec, hf: &doc::HeadersFooters) { + let field = |text: &str, field: String| TextBody { + paragraphs: vec![Paragraph { + runs: vec![Run { text: text.into(), props: Default::default(), kind: RunKind::Field { field } }], + ..Default::default() + }], + ..Default::default() + }; + let wanted = [ + (PhType::Date, hf.date, "Date Placeholder"), + (PhType::Footer, hf.footer && !hf.footer_text.is_empty(), "Footer Placeholder"), + (PhType::SlideNum, hf.slide_number, "Slide Number Placeholder"), + ]; + for (kind, on, name) in wanted { + if !on || shapes.iter().any(|s| s.ph_type() == Some(kind)) { + continue; + } + let text = match kind { + PhType::SlideNum => field("‹#›", "slidenum".into()), + PhType::Date if hf.user_date => TextBody::from_text(&hf.date_text), + // formatId 0–12 are the thirteen date formats, in DrawingML's order. + PhType::Date => field("", format!("datetime{}", hf.format.min(12) + 1)), + _ => TextBody::from_text(&hf.footer_text), + }; + let Some(id) = self.alloc() else { return }; + shapes.push(Shape { + id: ShapeId(id), + name: name.into(), + ph: Some(Placeholder { kind, ..Default::default() }), + text: Some(text), + ..Default::default() + }); + } + } + + /// The text of a notes page's notes placeholder. + fn notes(&mut self, n: &Listed<'a>, styles: &StyleSheet, scheme: Scheme) -> TextBody { + let drawing = draw::drawing(&n.rec); + // Notes masters aren't imported, so there are no master shapes to inherit from. + let scope = + Scope { scheme, styles, outline: &n.outline, numbering: &[], used_outline: Default::default(), master: false, masters: [None; 2] }; + for raw in &drawing.shapes { + let Some(block) = self.text_block(raw, &scope) else { continue }; + // The notes body placeholder; a slide number or header placeholder on the page isn't notes. + let is_notes = match raw.placeholder.filter(|p| p.kind != 0) { + Some(p) => matches!(p.kind, 0x06 | 0x0C), + None => block.text_type == ty::NOTES, + }; + if is_notes { + let mut body = self.text_body(&block, &scope, &raw.props); + body.body = BodyProps::default(); + return body; + } + } + TextBody::default() + } + + fn background(&mut self, raw: &RawShape<'a>, scope: &Scope) -> Option { + let props = self.props_of(raw, scope, false); + let fill = self.fill(&props, scope, true)?; + Some(Background::Fill { fill }) + } + + /// The shape's properties with what it inherits: its master shape's, then (for placeholders, + /// text boxes and picture frames) no fill and no line, then the drawing defaults. + fn props_of(&self, raw: &RawShape<'a>, scope: &Scope, unfilled: bool) -> Props<'a> { + let mut props = raw.props.clone(); + let inherited = + props.get(prop::HSP_MASTER).and_then(|spid| scope.masters.iter().flatten().find_map(|&master| self.master_props.get(&(master, spid)))); + if let Some(m) = inherited { + props.inherit(m); + } + if unfilled { + props.inherit(&no_fill_no_line()); + } + props.inherit(&self.defaults); + props + } + + fn shape(&mut self, raw: &RawShape<'a>, scope: &Scope, depth: usize, map: Map) -> Option { + if raw.deleted || depth > MAX_DEPTH { + return None; + } + let ph = raw.placeholder.filter(|p| p.kind != 0); + let text_box = raw.shape_type == 202; + // A picture frame (also an OLE object's frame) shows its picture with no fill or line of + // its own unless it says so; the drawing defaults' fill would cover a transparent picture. + let picture_frame = raw.shape_type == PICTURE_FRAME; + let props = self.props_of(raw, scope, ph.is_some() || text_box || picture_frame); + let rot = props.fixed(prop::ROTATION).unwrap_or(0.0); + let anchor = raw.anchor?; + let mut s = Shape { + id: ShapeId(self.alloc()?), + name: props.string(prop::NAME).unwrap_or_else(|| default_name(raw)), + xfrm: Some(xfrm(&anchor, map, rot, raw.flip_h, raw.flip_v)), + descr: props.string(prop::DESCRIPTION).unwrap_or_default(), + hidden: props.flag(prop::GROUP_BOOLS, 1).unwrap_or(false), + ..Default::default() + }; + if raw.is_group { + // Children are placed in slide points; the group's child space is its own box. + let at = s.xfrm.unwrap_or_default(); + let inner = Map::into_group(&at, &raw.group_rect.unwrap_or(anchor)); + let children = raw.children.iter().filter_map(|c| self.shape(c, scope, depth + 1, inner)).collect(); + let child = Xfrm::new(at.x, at.y, at.w, at.h); + s.kind = ShapeKind::Group { children, child }; + return Some(s); + } + if !scope.master + && let Some(ph) = ph + && let Some(kind) = ph_type(ph.kind) + { + s.ph = Some(Placeholder { kind, idx: ph.position, ..Default::default() }); + } + s.geom = geom::geometry(raw.shape_type, &props); + if geom::is_connector(raw.shape_type) { + s.kind = ShapeKind::Connector { start: None, end: None }; + } + // A picture: a picture frame, or any shape showing a picture (an OLE object's preview). + if let Some(media) = self.picture(&props, prop::PIB) { + let crop = |id| props.fixed(id).unwrap_or(0.0).clamp(-1.0, 1.0); + s.kind = ShapeKind::Picture { + fill: PictureFill { + media, + crop: [crop(prop::CROP_LEFT), crop(prop::CROP_TOP), crop(prop::CROP_RIGHT), crop(prop::CROP_BOTTOM)], + ..Default::default() + }, + }; + } + s.fill = Some(self.fill(&props, scope, false).unwrap_or(Fill::None)); + s.line = Some(self.line(&props, scope)); + if let Some(shadow) = self.shadow(&props, scope) { + s.effects = Some(Effects { outer_shadow: Some(shadow), ..Default::default() }); + } + if let Some(block) = self.text_block(raw, scope) { + s.text = Some(self.text_body(&block, scope, &props)); + } else if ph.is_some() { + // An empty placeholder draws nothing (its prompt shows only while editing). + s.text = Some(TextBody::default()); + } + Some(s) + } + + /// The picture a `pib` or `fillBlip` property names: a blip store entry (1-based), or a blip + /// held in the property's own complex bytes. + fn picture(&mut self, props: &Props<'a>, id: u16) -> Option { + let Some(bytes) = props.complex(id) else { + return props.get(id).filter(|&i| i > 0).and_then(|i| self.media(i as usize)); + }; + let key = bytes.as_ptr() as usize; + if let Some(m) = self.inline_media.get(&key) { + return *m; + } + let n = self.inline_media.len() + 1; + let id = self.blips.decode_inline(bytes).and_then(|pic| self.p.add_media(&format!("inline{n}.{}", pic.ext), pic.content_type, pic.data)); + self.inline_media.insert(key, id); + id + } + + fn media(&mut self, pib: usize) -> Option { + if let Some(m) = self.media.get(&pib) { + return *m; + } + let id = + self.blips.take(pib.wrapping_sub(1)).and_then(|pic| self.p.add_media(&format!("image{pib}.{}", pic.ext), pic.content_type, pic.data)); + self.media.insert(pib, id); + id + } + + fn color(&self, v: u32, props: &Props, scope: &Scope, depth: u8) -> Rgba { + let [r, g, b, flags] = v.to_le_bytes(); + if flags & 0x08 != 0 { + return scope.scheme.get(usize::from(r)).copied().unwrap_or(Rgba::BLACK); + } + if flags & 0x10 != 0 { + // A system colour index; the high ones stand for the shape's own fill and line colours. + let other = match r { + 0xF0 => Some(prop::FILL_COLOR), + 0xF1 => Some(prop::LINE_COLOR), + 0xF3 => Some(prop::FILL_BACK_COLOR), + _ => None, + }; + return match other.and_then(|id| props.get(id)) { + Some(o) if depth < 2 => self.color(o, props, scope, depth + 1), + _ => Rgba::BLACK, + }; + } + if flags & 0x01 != 0 { + return Rgba::BLACK; + } + Rgba::rgb(r, g, b) + } + + fn color_ref(&self, id: u16, fallback: u32, opacity: Option, props: &Props, scope: &Scope) -> ColorRef { + let c = ColorRef::rgb(self.color(props.get(id).unwrap_or(fallback), props, scope, 0)); + match opacity.and_then(|o| props.fixed(o)).filter(|a| *a < 1.0) { + Some(a) => c.with(ColorTransform::Alpha((a.clamp(0.0, 1.0) * 100_000.0) as i32)), + None => c, + } + } + + fn fill(&mut self, props: &Props<'a>, scope: &Scope, background: bool) -> Option { + if !background && !props.flag(prop::FILL_BOOLS, 4).unwrap_or(true) { + return None; + } + let fg = self.color_ref(prop::FILL_COLOR, 0x00FF_FFFF, Some(prop::FILL_OPACITY), props, scope); + let bg = self.color_ref(prop::FILL_BACK_COLOR, 0x00FF_FFFF, Some(prop::FILL_BACK_OPACITY), props, scope); + Some(match props.get(prop::FILL_TYPE).unwrap_or(0) { + // Texture (tiled) and picture (stretched). + t @ (2 | 3) => match self.picture(props, prop::FILL_BLIP) { + Some(media) => { + let mode = if t == 2 { + PictureMode::Tile { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, flip: String::new(), align: "tl".into() } + } else { + PictureMode::default() + }; + Fill::Picture(PictureFill { media, mode, ..Default::default() }) + } + None => Fill::solid(fg), + }, + // Gradients. + t @ 4..=8 => { + use craft_pptx::style::{Gradient, GradientShape}; + let focus = props.get(prop::FILL_FOCUS).map_or(0, |v| v as i32).clamp(-100, 100); + let stops = gradient_stops(focus, &fg, &bg); + let shape = if matches!(t, 5 | 6) { + // Position 0 is the centre (the focus rectangle), 1 the shape's edge. + GradientShape::Path { path: if t == 5 { "rect".into() } else { "shape".into() }, focus: [0.5, 0.5, 0.5, 0.5] } + } else { + GradientShape::Linear { angle: linear_angle(props.fixed(prop::FILL_ANGLE).unwrap_or(0.0)), scaled: false } + }; + Fill::Gradient(Gradient { stops, shape: Some(shape), flip: None, rotate_with_shape: Some(true), tile: [0.0; 4] }) + } + 9 => Fill::Background, + _ => Fill::solid(fg), + }) + } + + fn line(&self, props: &Props, scope: &Scope) -> Line { + if !props.flag(prop::LINE_BOOLS, 3).unwrap_or(true) { + return Line::none(); + } + let width = props.get(prop::LINE_WIDTH).map_or(9525.0, f64::from) / EMU; + let mut l = Line::solid(self.color_ref(prop::LINE_COLOR, 0, Some(prop::LINE_OPACITY), props, scope), width); + l.dash = Some(Dash::Preset { + name: match props.get(prop::LINE_DASHING).unwrap_or(0) { + 1 => "sysDash", + 2 => "sysDot", + 3 => "sysDashDot", + 4 => "sysDashDotDot", + 5 => "dot", + 6 => "dash", + 7 => "lgDash", + 8 => "dashDot", + 9 => "lgDashDot", + 10 => "lgDashDotDot", + _ => "solid", + } + .into(), + }); + l.compound = props.get(prop::LINE_STYLE).map(|v| match v { + 1 => craft_pptx::style::Compound::Double, + 2 => craft_pptx::style::Compound::ThickThin, + 3 => craft_pptx::style::Compound::ThinThick, + 4 => craft_pptx::style::Compound::Triple, + _ => craft_pptx::style::Compound::Single, + }); + l.join = props.get(prop::LINE_JOIN).map(|v| match v { + 0 => LineJoin::Bevel, + 1 => LineJoin::Miter, + _ => LineJoin::Round, + }); + l.cap = props.get(prop::LINE_CAP).map(|v| match v { + 0 => LineCap::Round, + 1 => LineCap::Square, + _ => LineCap::Flat, + }); + let end = |kind: u16, w: u16, len: u16| { + let k = match props.get(kind).unwrap_or(0) { + 1 => "triangle", + 2 => "stealth", + 3 => "diamond", + 4 => "oval", + 5 => "arrow", + _ => return None, + }; + let size = |v: Option| match v { + Some(0) => "sm", + Some(2) => "lg", + _ => "med", + }; + Some(LineEnd { kind: k.into(), w: size(props.get(w)).into(), len: size(props.get(len)).into() }) + }; + l.head = end(prop::LINE_START_ARROW, prop::LINE_START_ARROW_WIDTH, prop::LINE_START_ARROW_LENGTH); + l.tail = end(prop::LINE_END_ARROW, prop::LINE_END_ARROW_WIDTH, prop::LINE_END_ARROW_LENGTH); + l + } + + fn shadow(&self, props: &Props, scope: &Scope) -> Option { + if !props.flag(prop::SHADOW_BOOLS, 1).unwrap_or(false) { + return None; + } + let dx = props.get(prop::SHADOW_OFFSET_X).map_or(25400.0, |v| f64::from(v as i32)) / EMU; + let dy = props.get(prop::SHADOW_OFFSET_Y).map_or(25400.0, |v| f64::from(v as i32)) / EMU; + Some(Shadow { + color: self.color_ref(prop::SHADOW_COLOR, 0x0080_8080, Some(prop::SHADOW_OPACITY), props, scope), + 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, + }) + } + + /// The text block of a shape: its own, or the slide list's outline block it points at. A text + /// box holding the reference may also hold its own ruler ([MS-PPT] OfficeArtClientTextbox: + /// `OutlineTextRefAtom` then an optional `TextRulerAtom`); the margins and indents it sets + /// win over the block's. + fn text_block(&self, raw: &RawShape<'a>, scope: &Scope) -> Option { + let tb = raw.text?; + let own = text::read_block(tb.children())?; + let own_ruler = own.ruler; + match own.outline_ref { + Some(i) if own.chars.is_empty() && scope.used_outline.borrow_mut().insert(i as usize) => scope + .outline + .get(i as usize) + .and_then(|r| text::read_block(r.clone())) + .map(|mut b| { + b.outline_index = Some(i as usize); + for ((lm, ind), (own_lm, own_ind)) in b.ruler.iter_mut().zip(own_ruler) { + *lm = own_lm.or(*lm); + *ind = own_ind.or(*ind); + } + b + }) + .or(Some(own)), + _ => Some(own), + } + } + + fn text_body(&self, block: &TextBlock, scope: &Scope, props: &Props) -> TextBody { + let inset = |id, d: f64| props.get(id).map_or(d, |v| f64::from(v as i32) / EMU).max(0.0); + let body = BodyProps { + inset_l: Some(inset(prop::TEXT_LEFT, 7.2)), + inset_t: Some(inset(prop::TEXT_TOP, 3.6)), + inset_r: Some(inset(prop::TEXT_RIGHT, 7.2)), + inset_b: Some(inset(prop::TEXT_BOTTOM, 3.6)), + anchor: Some(match props.get(prop::ANCHOR_TEXT).unwrap_or(0) { + // middle, middle centred + 1 | 4 => TextAnchor::Middle, + // bottom, bottom centred, and their baseline forms + 2 | 5 | 7 | 9 => TextAnchor::Bottom, + _ => TextAnchor::Top, + }), + anchor_ctr: Some(matches!(props.get(prop::ANCHOR_TEXT), Some(3 | 4 | 5 | 8 | 9))), + wrap: Some(props.get(prop::WRAP_TEXT) != Some(2)), + autofit: Some(AutoFit::None), + ..Default::default() + }; + TextBody { body, paragraphs: self.paragraphs(block, scope), ..Default::default() } + } + + fn paragraphs(&self, block: &TextBlock, scope: &Scope) -> Vec { + let chars = &block.chars; + let total = chars.len(); + let fields: HashMap = block.fields.iter().map(|(p, k)| (*p as usize, *k)).collect(); + // Where each formatting run starts. + let starts = |counts: &mut dyn Iterator| -> Vec { + let mut at = 0usize; + counts + .map(|n| { + let s = at; + at = at.saturating_add(n as usize); + s + }) + .collect() + }; + let para_starts = starts(&mut block.para_runs.iter().map(|r| r.0)); + let char_starts = starts(&mut block.char_runs.iter().map(|r| r.0)); + // The starts never decrease (a running sum), so both lookups are binary searches. A scan per + // run, break and field made text with many runs quadratic: 1M one-character runs, about 10 MB + // of file, took minutes. + let run_at = |starts: &[usize], i: usize| starts.partition_point(|&s| s <= i).checked_sub(1); + let mut out = vec![]; + let mut start = 0usize; + loop { + let end = chars.get(start..).and_then(|rest| rest.iter().position(|&c| c == 0x0D)).map_or(total, |e| start + e); + let (level, pf_exc) = run_at(¶_starts, start).and_then(|i| block.para_runs.get(i)).map_or((0, None), |r| (r.1, Some(&r.2))); + let (mut pf, base_cf) = scope.styles.resolve(block.text_type, level); + if let Some((lm, ind)) = block.ruler.get(usize::from(level)) { + if lm.is_some() { + pf.left_margin = *lm; + } + if ind.is_some() { + pf.indent = *ind; + } + } + if let Some(e) = pf_exc { + pf.apply(e); + } + let cf_at = |i: usize| -> Cf { + let mut cf = base_cf.clone(); + if let Some(e) = run_at(&char_starts, i).and_then(|k| block.char_runs.get(k)) { + cf.apply(&e.1); + } + cf + }; + let first_cf = cf_at(start); + let first = self.run_props(&first_cf, &scope.scheme); + let mut para = Paragraph { level, props: self.para_props(&pf, &scope.scheme, first.size.unwrap_or(18.0)), ..Default::default() }; + // A bulleted paragraph whose PowerPoint 2000 formatting numbers it. + if matches!(para.props.bullet, Some(Bullet::Char { .. })) + && let Some((scheme, start_at)) = block + .outline_index + .and_then(|i| scope.numbering.get(i)) + .and_then(Option::as_ref) + .zip(first_cf.pp9rt) + .and_then(|(entries, i)| entries.get(usize::from(i))) + .and_then(|e| e.auto_number) + { + para.props.bullet = + Some(Bullet::AutoNum { scheme: text::auto_number_scheme(scheme).into(), start_at: u32::try_from(start_at).unwrap_or(1).max(1) }); + } + let mut i = start; + while i < end { + let props = self.run_props(&cf_at(i), &scope.scheme); + let c = chars.get(i).copied().unwrap_or(0); + if let Some(k) = fields.get(&i) { + let field = match k { + FieldKind::SlideNumber => "slidenum", + FieldKind::DateTime => "datetime1", + }; + para.runs.push(Run { + text: if *k == FieldKind::SlideNumber { "‹#›".into() } else { String::new() }, + props, + kind: RunKind::Field { field: field.into() }, + }); + i += 1; + continue; + } + if c == 0x0B { + para.runs.push(Run { text: String::new(), props, kind: RunKind::Break }); + i += 1; + continue; + } + // A text run: up to the next format change, field, break or the paragraph's end. + let next_change = char_starts.get(char_starts.partition_point(|&s| s <= i)).copied().unwrap_or(end).min(end); + let mut j = i; + while j < next_change && !fields.contains_key(&j) && chars.get(j) != Some(&0x0B) { + j += 1; + } + let j = j.max(i + 1); + let units: Vec = chars.get(i..j).unwrap_or(&[]).iter().copied().filter(|&u| u >= 0x20 || u == 0x09).collect(); + para.runs.push(Run::with(String::from_utf16_lossy(&units), props)); + i = j; + } + para.end_props = first; + para.normalize(); + out.push(para); + if end >= total { + break; + } + start = end + 1; + } + out + } + + fn run_props(&self, cf: &Cf, scheme: &Scheme) -> RunProps { + let font = |i: Option| i.and_then(|i| self.fonts.get(usize::from(i))).filter(|f| !f.is_empty()).cloned(); + RunProps { + font: font(cf.font).or_else(|| self.fonts.first().cloned()), + font_ea: font(cf.ea_font), + font_sym: font(cf.symbol_font), + size: cf.size.map(f64::from).filter(|s| (1.0..=4000.0).contains(s)), + bold: Some(cf.bold.unwrap_or(false)), + italic: Some(cf.italic.unwrap_or(false)), + underline: Some(if cf.underline.unwrap_or(false) { "sng" } else { "none" }.into()), + baseline: cf.position.filter(|p| *p != 0).map(|p| f64::from(p) / 100.0), + fill: cf.color.map(|c| Fill::solid(ColorRef::rgb(text_color(c, scheme)))), + shadow: cf.shadow.filter(|&on| on).map(|_| text_shadow(scheme)), + ..Default::default() + } + } + + fn para_props(&self, pf: &Pf, scheme: &Scheme, text_size: f64) -> ParaProps { + let spacing = |v: i16| if v >= 0 { Spacing::Pct(f64::from(v) / 100.0) } else { Spacing::Pts(-f64::from(v) / MU) }; + let margin = f64::from(pf.left_margin.unwrap_or(0)) / MU; + let indent = f64::from(pf.indent.unwrap_or(0)) / MU; + let bullet = if pf.has_bullet == Some(true) { + let c = pf.bullet_char.filter(|&c| c >= 0x20).unwrap_or(0x2022); + Bullet::Char { char: char::from_u32(u32::from(c)).unwrap_or('•').to_string() } + } else { + Bullet::None + }; + let has_bullet = matches!(bullet, Bullet::Char { .. }); + ParaProps { + align: Some(match pf.align.unwrap_or(0) { + 1 => Align::Center, + 2 => Align::Right, + 3 | 5 => Align::Justify, + 4 => Align::Distributed, + 6 => Align::JustLow, + _ => Align::Left, + }), + margin_left: Some(margin), + indent: Some(indent - margin), + line_spacing: Some(spacing(pf.line_spacing.unwrap_or(100))), + space_before: Some(spacing(pf.space_before.unwrap_or(0))), + space_after: Some(spacing(pf.space_after.unwrap_or(0))), + bullet: Some(bullet), + bullet_font: if has_bullet && pf.bullet_has_font == Some(true) { + pf.bullet_font.and_then(|i| self.fonts.get(usize::from(i))).cloned() + } else { + None + }, + bullet_color: if has_bullet && pf.bullet_has_color == Some(true) { + pf.bullet_color.map(|c| ColorRef::rgb(text_color(c, scheme))) + } else { + None + }, + bullet_size: if has_bullet && pf.bullet_has_size == Some(true) { + pf.bullet_size.map(|v| if v > 0 { f64::from(v) / 100.0 } else { -f64::from(v) / text_size.max(1.0) }).map(|v| v.clamp(0.25, 4.0)) + } else { + None + }, + default_tab: pf.default_tab.map(|t| f64::from(t) / MU), + tabs: pf.tabs.as_ref().map(|t| { + t.iter() + .map(|(pos, kind)| TabStop { + pos: f64::from(*pos) / MU, + align: match kind { + 1 => "ctr", + 2 => "r", + 3 => "dec", + _ => "l", + } + .into(), + }) + .collect() + }), + ..Default::default() + } + } +} + +fn text_color(c: TextColor, scheme: &Scheme) -> Rgba { + match c { + TextColor::Rgb(r, g, b) => Rgba::rgb(r, g, b), + TextColor::Scheme(i) => scheme.get(usize::from(i)).copied().unwrap_or(Rgba::BLACK), + } +} + +/// A text shadow in the colour scheme's shadow colour. The record holds only the on/off bit, so +/// the distance and direction are the app's own Text Shadow command's (`format.textShadow`); with +/// no blur in the record, none is added. +fn text_shadow(scheme: &Scheme) -> Shadow { + Shadow { + color: ColorRef::rgb(scheme.get(2).copied().unwrap_or(Rgba::rgb(0x80, 0x80, 0x80))), + blur: 0.0, + dist: 2.0, + dir: 45.0, + inner: false, + sx: 1.0, + sy: 1.0, + kx: 0.0, + ky: 0.0, + align: String::new(), + rotate_with_shape: false, + } +} + +/// A shaded fill's stops ([MS-ODRAW] `fillFocus`: the position of the last colour, the back +/// colour). Focus 0 starts at the back colour and ends at the fill colour, ±100 the other way; in +/// between, the back colour sits at that point with the fill colour at both ends. +fn gradient_stops(focus: i32, fg: &ColorRef, bg: &ColorRef) -> Vec { + use craft_pptx::style::GradientStop; + let stop = |pos: f64, c: &ColorRef| GradientStop { pos, color: c.clone() }; + match focus { + 0 => vec![stop(0.0, bg), stop(1.0, fg)], + 100 | -100 => vec![stop(0.0, fg), stop(1.0, bg)], + f => vec![stop(0.0, fg), stop(f64::from(f.abs()) / 100.0, bg), stop(1.0, fg)], + } +} + +/// The DrawingML angle (0° runs left to right, turning clockwise) of a linear fill's `fillAngle`, +/// for stops from [`gradient_stops`]: the gradient starts on the left at -90°, the top at -180°, +/// the right at -270°, turning clockwise as the angle falls. 0° starts at the top too: that is how +/// LibreOffice reads it, and how it writes a top-to-bottom gradient. +fn linear_angle(a: f64) -> f64 { + if a == 0.0 { 90.0 } else { (270.0 - a).rem_euclid(360.0) } +} + +/// `msosptPictureFrame`. +const PICTURE_FRAME: u16 = 75; + +fn no_fill_no_line<'a>() -> Props<'a> { + let mut p = Props::default(); + p.set(prop::FILL_BOOLS, 0x0010_0000); // fFilled set to false + p.set(prop::LINE_BOOLS, 0x0008_0000); // fLine set to false + p +} + +/// Maps anchor coordinates to slide points: master units at the top level, a group's child units +/// inside it (`x * sx + ox`). +#[derive(Clone, Copy, Debug)] +struct Map { + sx: f64, + sy: f64, + ox: f64, + oy: f64, +} + +const TOP: Map = Map { sx: 1.0 / MU, sy: 1.0 / MU, ox: 0.0, oy: 0.0 }; + +impl Map { + /// The map for the children of a group placed at `at` (points) whose child space is `rect`. + fn into_group(at: &Xfrm, rect: &draw::Anchor) -> Map { + let (w, h) = (rect.right - rect.left, rect.bottom - rect.top); + let sx = if w.abs() > f64::EPSILON { at.w / w } else { 0.0 }; + let sy = if h.abs() > f64::EPSILON { at.h / h } else { 0.0 }; + Map { sx, sy, ox: at.x - rect.left * sx, oy: at.y - rect.top * sy } + } +} + +/// A box in points from an anchor. A shape turned by 45–135° or 225–315° stores the box of its +/// turned outline: swap it back. +fn xfrm(a: &draw::Anchor, m: Map, rot: f64, flip_h: bool, flip_v: bool) -> Xfrm { + let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; + let (l, t, r, b) = (finite(a.left * m.sx + m.ox), finite(a.top * m.sy + m.oy), finite(a.right * m.sx + m.ox), finite(a.bottom * m.sy + m.oy)); + let (mut x, mut y, mut w, mut h) = (l.min(r), t.min(b), (r - l).abs(), (b - t).abs()); + let rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 }; + if (45.0..135.0).contains(&rot) || (225.0..315.0).contains(&rot) { + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + std::mem::swap(&mut w, &mut h); + x = cx - w / 2.0; + y = cy - h / 2.0; + } + Xfrm { x, y, w, h, rot, flip_h, flip_v } +} + +fn default_name(raw: &RawShape) -> String { + match raw.shape_type { + 75 => "Picture".into(), + 202 => "Text Box".into(), + 20 => "Line".into(), + _ if raw.is_group => "Group".into(), + _ => format!("Shape {}", raw.spid & 0x3FF), + } +} + +/// `PlaceholderEnum` as a placeholder type. +fn ph_type(kind: u8) -> Option { + Some(match kind { + 0x01 | 0x0D | 0x11 => PhType::Title, + 0x03 | 0x0F => PhType::CtrTitle, + 0x04 | 0x10 => PhType::SubTitle, + 0x02 | 0x06 | 0x0C | 0x0E | 0x12 => PhType::Body, + 0x07 => PhType::Date, + 0x08 => PhType::SlideNum, + 0x09 => PhType::Footer, + 0x0A => PhType::Header, + 0x05 | 0x0B => PhType::SlideImage, + 0x13 | 0x19 => PhType::Obj, + 0x14 => PhType::Chart, + 0x15 => PhType::Table, + 0x16 => PhType::ClipArt, + 0x17 => PhType::Diagram, + 0x18 => PhType::Media, + 0x1A => PhType::Picture, + _ => return None, + }) +} + +fn same_family(a: PhType, b: PhType) -> bool { + let title = |t| matches!(t, PhType::Title | PhType::CtrTitle); + a == b || (title(a) && title(b)) +} + +/// `SlideLayoutType` as a layout type. +fn layout_kind(geom: u32) -> LayoutType { + match geom { + 0 => LayoutType::Title, + 7 => LayoutType::TitleOnly, + 8 | 9 | 10 | 11 | 13 | 14 => LayoutType::TwoContent, + 16 => LayoutType::Blank, + 17 => LayoutType::VerticalTitleAndText, + 18 => LayoutType::TitleAndVerticalText, + _ => LayoutType::TitleAndContent, + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + /// [MS-ODRAW] `fillFocus` is where the back colour sits; LibreOffice draws 0° from the top + /// (storytold/deckcraft#1137 review: the linear gradient's colours were reversed, the radial one inside out). + #[test] + fn shaded_fills_put_the_back_colour_at_the_focus() { + let (fg, bg) = (ColorRef::rgb(Rgba::rgb(255, 0, 0)), ColorRef::rgb(Rgba::rgb(0, 0, 255))); + let at = |stops: &[craft_pptx::style::GradientStop]| stops.iter().map(|s| (s.pos, s.color == fg)).collect::>(); + assert_eq!(at(&gradient_stops(0, &fg, &bg)), [(0.0, false), (1.0, true)]); + assert_eq!(at(&gradient_stops(100, &fg, &bg)), [(0.0, true), (1.0, false)]); + assert_eq!(at(&gradient_stops(-50, &fg, &bg)), [(0.0, true), (0.5, false), (1.0, true)]); + // 0° and -180° start at the top, -90° on the left, -270° on the right, -315° at the + // bottom right (DrawingML: 90° runs top to bottom, 0° left to right). + for (a, dm) in [(0.0, 90.0), (-90.0, 0.0), (-180.0, 90.0), (-270.0, 180.0), (-315.0, 225.0), (-45.0, 315.0)] { + assert_eq!(linear_angle(a), dm, "{a}"); + } + } +} diff --git a/crates/ppt-binary/src/doc.rs b/crates/ppt-binary/src/doc.rs new file mode 100644 index 000000000..d0aa46f0e --- /dev/null +++ b/crates/ppt-binary/src/doc.rs @@ -0,0 +1,390 @@ +//! The document structure of the `PowerPoint Document` stream ([MS-PPT] §2.1–2.4): the current +//! user's pointer to the last edit, the chain of edits with their persist directories (which map +//! object ids to stream offsets, newer edits winning), the document container and the lists of +//! masters, slides and notes. + +use std::collections::{HashMap, HashSet, VecDeque}; + +use crate::PptError; +use crate::record::{Rec, Records}; + +pub mod rt { + //! Record types used here ([MS-PPT] §2.13.24, [MS-ODRAW] §2.1.4). + pub const DOCUMENT: u16 = 0x03E8; + pub const DOCUMENT_ATOM: u16 = 0x03E9; + pub const SLIDE: u16 = 0x03EE; + pub const SLIDE_ATOM: u16 = 0x03EF; + pub const NOTES: u16 = 0x03F0; + pub const NOTES_ATOM: u16 = 0x03F1; + pub const ENVIRONMENT: u16 = 0x03F2; + pub const SLIDE_PERSIST_ATOM: u16 = 0x03F3; + pub const MAIN_MASTER: u16 = 0x03F8; + pub const SLIDE_SHOW_SLIDE_INFO: u16 = 0x03F9; + pub const DRAWING_GROUP: u16 = 0x040B; + pub const DRAWING: u16 = 0x040C; + pub const COLOR_SCHEME: u16 = 0x07F0; + pub const LIST: u16 = 0x07D0; + pub const PROG_TAGS: u16 = 0x1388; + pub const PROG_BINARY_TAG: u16 = 0x138A; + pub const BINARY_TAG_DATA: u16 = 0x138B; + pub const STYLE_TEXT_PROP9: u16 = 0x0FAC; + pub const OUTLINE_TEXT_PROPS9: u16 = 0x0FAE; + pub const OUTLINE_TEXT_PROPS_HEADER: u16 = 0x0FAF; + pub const FONT_COLLECTION: u16 = 0x07D5; + pub const OUTLINE_TEXT_REF: u16 = 0x0F9E; + pub const TEXT_HEADER: u16 = 0x0F9F; + pub const TEXT_CHARS: u16 = 0x0FA0; + pub const STYLE_TEXT_PROP: u16 = 0x0FA1; + pub const TEXT_MASTER_STYLE: u16 = 0x0FA3; + pub const TEXT_CF_EXCEPTION: u16 = 0x0FA4; + pub const TEXT_PF_EXCEPTION: u16 = 0x0FA5; + pub const TEXT_RULER: u16 = 0x0FA6; + pub const TEXT_BYTES: u16 = 0x0FA8; + pub const FONT_ENTITY: u16 = 0x0FB7; + pub const CSTRING: u16 = 0x0FBA; + pub const SLIDE_NUMBER_MC: u16 = 0x0FD8; + pub const HEADERS_FOOTERS: u16 = 0x0FD9; + pub const HEADERS_FOOTERS_ATOM: u16 = 0x0FDA; + pub const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0; + pub const USER_EDIT: u16 = 0x0FF5; + pub const CURRENT_USER: u16 = 0x0FF6; + pub const DATETIME_MC: u16 = 0x0FF7; + pub const GENERIC_DATE_MC: u16 = 0x0FF8; + pub const PLACEHOLDER_ATOM: u16 = 0x0BC3; + pub const PERSIST_DIRECTORY: u16 = 0x1772; + pub const CRYPT_SESSION: u16 = 0x2F14; + + pub const DGG_CONTAINER: u16 = 0xF000; + pub const BSTORE: u16 = 0xF001; + pub const DG_CONTAINER: u16 = 0xF002; + pub const SPGR_CONTAINER: u16 = 0xF003; + pub const SP_CONTAINER: u16 = 0xF004; + pub const FBSE: u16 = 0xF007; + pub const FSPGR: u16 = 0xF009; + pub const FSP: u16 = 0xF00A; + pub const FOPT: u16 = 0xF00B; + pub const CLIENT_TEXTBOX: u16 = 0xF00D; + pub const CHILD_ANCHOR: u16 = 0xF00F; + pub const CLIENT_ANCHOR: u16 = 0xF010; + pub const CLIENT_DATA: u16 = 0xF011; + pub const SECONDARY_FOPT: u16 = 0xF121; + pub const TERTIARY_FOPT: u16 = 0xF122; +} + +/// `headerToken` of a `CurrentUserAtom` for an encrypted document. +const ENCRYPTED_TOKEN: u32 = 0xF3D1_C4DF; +/// `headerToken` of an unencrypted PowerPoint 97+ document. +const PLAIN_TOKEN: u32 = 0xE391_C05F; +/// Edits followed at most along the `offsetLastEdit` chain. +const MAX_EDITS: usize = 4096; + +/// A master, slide or notes page as listed in a `SlideListWithTextContainer`. +#[derive(Clone, Debug)] +pub struct Listed<'a> { + /// The container (`SlideContainer`, `MainMasterContainer`, `NotesContainer`). + pub rec: Rec<'a>, + /// The id other records use for it (`SlideAtom.masterIdRef`, `NotesAtom.slideIdRef`). + pub slide_id: u32, + /// The outline text stored in the list after its `SlidePersistAtom` (placeholders point at it + /// with an `OutlineTextRefAtom`). + pub outline: Vec>, +} + +/// The parsed structure of a `.ppt`. +pub struct Doc<'a> { + pub document: Rec<'a>, + pub masters: Vec>, + pub slides: Vec>, + pub notes: Vec>, + /// Slides the slide list names but whose objects couldn't be found: what a damaged file lost. + pub lost: Vec, +} + +/// Read the structure from the `Current User` and `PowerPoint Document` streams. +pub fn read<'a>(current_user: &[u8], stream: &'a [u8]) -> Result, PptError> { + let damaged = |s: &str| PptError::Damaged(s.to_string()); + // The current user names the newest edit; without it (some writers omit the stream), scan + // for the last UserEditAtom in the stream. + let mut edit_at = None; + // [MS-PPT] allows only the two tokens. Any other value (or none, in a truncated record) is a + // damaged PowerPoint 97 file or an older format; only the scan below can tell which. + let mut unknown_token = false; + if let Some(cu) = Rec::at(current_user, 0).filter(|r| r.kind == rt::CURRENT_USER) { + match cu.u32(4) { + Some(ENCRYPTED_TOKEN) => return Err(PptError::Encrypted), + Some(PLAIN_TOKEN) => edit_at = cu.u32(8).map(|v| v as usize), + _ => unknown_token = true, + } + } + let edit_at = match edit_at.filter(|&at| Rec::at(stream, at).is_some_and(|r| r.kind == rt::USER_EDIT)) { + Some(at) => at, + None => match Records::new(stream).filter(|r| r.kind == rt::USER_EDIT).last() { + Some(r) => r.offset, + None if unknown_token => return Err(PptError::TooOld), + None => return Err(damaged("no edit record")), + }, + }; + // Walk the edits newest first; the first entry seen for a persist id wins. + let mut persist: HashMap = HashMap::new(); + let mut doc_ref = None; + let mut seen = HashSet::new(); + // Many edits may name one persist directory; it is read once (its first reading wins anyway). + let mut dirs_seen = HashSet::new(); + // All directories together are read within one stream's worth of words. Real directories + // don't overlap, so they fit. Hostile ones nested inside each other would otherwise each be + // read to the end of the stream, once per edit (MAX_EDITS × the stream). + let mut words = stream.len() / 4; + let mut at = edit_at; + // The chain ends at an edit whose previous offset is 0. Ending anywhere else (a loop, an + // offset that isn't an edit, too many edits) means older edits were cut off. + let mut broken = true; + for _ in 0..MAX_EDITS { + if !seen.insert(at) { + break; + } + let Some(edit) = Rec::at(stream, at).filter(|r| r.kind == rt::USER_EDIT) else { break }; + if doc_ref.is_none() { + doc_ref = edit.u32(16); + // An encryptSessionPersistIdRef follows only in encrypted documents. + if edit.data.len() >= 32 { + return Err(PptError::Encrypted); + } + } + if let Some(dir) = + edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY) + { + read_persist_directory(dir.data, &mut persist, &mut words); + } + match edit.u32(8) { + Some(0) => { + broken = false; + break; + } + None => break, + Some(prev) => at = prev as usize, + } + } + if broken { + // Recover what the cut-off edits held: every edit in the stream, newest (last written) + // first, fills only the persist ids the chain left unset. Past MAX_EDITS, the newest are + // kept: they are the ones that win. + log::warn!("ppt: the edit history is broken; reading every edit in the stream"); + let mut edits: VecDeque = VecDeque::with_capacity(MAX_EDITS.min(64)); + for edit in Records::new(stream).filter(|r| r.kind == rt::USER_EDIT) { + if edits.len() == MAX_EDITS { + edits.pop_front(); + } + edits.push_back(edit); + } + for edit in edits.into_iter().rev() { + if let Some(dir) = + edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY) + { + read_persist_directory(dir.data, &mut persist, &mut words); + } + } + } + let lookup = |id: u32| persist.get(&id).and_then(|&o| Rec::at(stream, o)); + let document = doc_ref.and_then(lookup).filter(|r| r.kind == rt::DOCUMENT).ok_or_else(|| damaged("no document container"))?; + if lookup_kind(&persist, stream, rt::CRYPT_SESSION) { + return Err(PptError::Encrypted); + } + let mut doc = Doc { document, masters: vec![], slides: vec![], notes: vec![], lost: vec![] }; + // Each object is listed once. PowerPoint never lists one twice, and a hostile file that lists a + // big drawing many times would otherwise have it converted again for every listing (shapes × + // listings, from linear input). + let mut listed = HashSet::new(); + for list in document.children_of(rt::SLIDE_LIST_WITH_TEXT) { + let out = match list.instance { + 0 => &mut doc.slides, + 1 => &mut doc.masters, + 2 => &mut doc.notes, + _ => continue, + }; + let mut current: Option = None; + for r in list.children() { + if r.kind == rt::SLIDE_PERSIST_ATOM { + if let Some(l) = current.take() { + out.push(l); + } + let (Some(pid), Some(slide_id)) = (r.u32(0), r.u32(12)) else { continue }; + match lookup(pid) { + // The slide list names slides; anything else there is a slide the file lost. + Some(rec) if list.instance == 0 && rec.kind != rt::SLIDE => { + log::warn!("ppt: slide persist id {pid} is not a slide"); + doc.lost.push(format!("slide {slide_id}")); + } + Some(rec) if !listed.insert(rec.offset) => log::warn!("ppt: persist id {pid} is listed again; skipped"), + Some(rec) => current = Some(Listed { rec, slide_id, outline: vec![] }), + None => { + log::warn!("ppt: slide persist id {pid} has no object"); + if list.instance == 0 { + doc.lost.push(format!("slide {slide_id}")); + } + } + } + } else if r.kind == rt::TEXT_HEADER + && let Some(l) = current.as_mut() + { + // An outline text block starts at its header and runs to the next header or persist atom. + let rest = list.data.get(r.offset..).unwrap_or(&[]); + l.outline.push(Records::new(rest)); + } + } + if let Some(l) = current.take() { + out.push(l); + } + } + Ok(doc) +} + +/// Read one persist directory into `persist`, taking each word read from `words`. +fn read_persist_directory(b: &[u8], persist: &mut HashMap, words: &mut usize) { + let mut c = crate::record::Cursor::new(b); + let mut next = |c: &mut crate::record::Cursor| { + *words = words.checked_sub(1)?; + c.u32() + }; + while let Some(head) = next(&mut c) { + let first = head & 0x000F_FFFF; + let count = head >> 20; + for k in 0..count { + let Some(off) = next(&mut c) else { return }; + persist.entry(first.saturating_add(k)).or_insert(off as usize); + } + } +} + +fn lookup_kind(persist: &HashMap, stream: &[u8], kind: u16) -> bool { + persist.values().any(|&o| Rec::at(stream, o).is_some_and(|r| r.kind == kind)) +} + +/// The `DocumentAtom`: slide and notes sizes in master units (576 per inch), first slide number. +pub struct DocumentAtom { + pub slide_w: i32, + pub slide_h: i32, + pub notes_w: i32, + pub notes_h: i32, + pub first_slide_number: u16, +} + +impl Doc<'_> { + pub fn document_atom(&self) -> Option { + let a = self.document.child(rt::DOCUMENT_ATOM)?; + Some(DocumentAtom { + slide_w: a.i32(0)?, + slide_h: a.i32(4)?, + notes_w: a.i32(8)?, + notes_h: a.i32(12)?, + first_slide_number: a.u16(32).unwrap_or(1), + }) + } +} + +/// The `SlideAtom` of a slide or master. +#[derive(Clone, Copy, Debug, Default)] +pub struct SlideAtom { + /// `SlideLayoutType`. + pub geom: u32, + pub master_id: u32, + pub follow_master_objects: bool, + pub follow_master_scheme: bool, + pub follow_master_background: bool, +} + +pub fn slide_atom(container: &Rec) -> SlideAtom { + let Some(a) = container.child(rt::SLIDE_ATOM) else { + return SlideAtom { follow_master_objects: true, follow_master_scheme: true, follow_master_background: true, ..Default::default() }; + }; + let flags = a.u16(20).unwrap_or(0x7); + SlideAtom { + geom: a.u32(0).unwrap_or(0), + master_id: a.u32(12).unwrap_or(0), + follow_master_objects: flags & 0x1 != 0, + follow_master_scheme: flags & 0x2 != 0, + follow_master_background: flags & 0x4 != 0, + } +} + +/// Font names by index (`FontCollectionContainer` in the environment). +pub fn fonts(doc: &Doc) -> Vec { + let Some(coll) = doc.document.child(rt::ENVIRONMENT).and_then(|e| e.child(rt::FONT_COLLECTION)) else { return vec![] }; + coll.children_of(rt::FONT_ENTITY) + .map(|f| { + let units: Vec = (0..32).filter_map(|i| f.u16(i * 2)).take_while(|&u| u != 0).collect(); + String::from_utf16_lossy(&units) + }) + .collect() +} + +/// What a `HeadersFootersContainer` ([MS-PPT] §2.4.15.1 and §2.5.16) says the footer row +/// shows: the date (today's in a format, or fixed text), the slide number and the footer text. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct HeadersFooters { + /// `formatId`: 0–12, the date format. + pub format: u16, + pub date: bool, + /// The date is fixed text (`fHasUserDate`) rather than today's. + pub user_date: bool, + pub slide_number: bool, + pub footer: bool, + pub date_text: String, + pub footer_text: String, +} + +/// The UTF-16 units of a `CString` body, up to its first NUL: the record has no terminator, but a +/// writer that adds one would otherwise put a NUL into the text, or make a tag name fail to match. +fn cstring_units(b: &[u8]) -> impl Iterator + '_ { + b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|&u| u != 0) +} + +/// The slides' headers and footers in `container`, from its `HeadersFootersContainer` of +/// `instance`: 3 in the document (`SlideHeadersFootersContainer`, for every slide), 0 in a slide or +/// main master (`PerSlideHeadersFootersContainer`, its own). +pub fn headers_footers(container: &Rec, instance: u16) -> Option { + let hf = container.children().find(|r| r.kind == rt::HEADERS_FOOTERS && r.instance == instance)?; + let atom = hf.child(rt::HEADERS_FOOTERS_ATOM)?; + let flags = atom.u16(2)?; + let text = |instance: u16| { + hf.children() + .find(|r| r.kind == rt::CSTRING && r.instance == instance) + .map(|r| String::from_utf16_lossy(&cstring_units(r.data).collect::>())) + .unwrap_or_default() + }; + Some(HeadersFooters { + format: atom.u16(0).unwrap_or(0), + date: flags & 0x01 != 0, + user_date: flags & 0x04 != 0, + slide_number: flags & 0x08 != 0, + footer: flags & 0x20 != 0, + date_text: text(0), + footer_text: text(2), + }) +} + +/// The PowerPoint 2000 paragraph formatting of the slides' outline text ([MS-PPT] §2.4.22.10, +/// the document's `___PPT9` tag): by slide id and text type, one `StyleTextProp9Atom` for each of +/// the slide's outline blocks of that type, in order. +pub fn outline_numbering(document: &Rec) -> HashMap<(u32, u32), Vec>> { + let mut out: HashMap<(u32, u32), Vec>> = HashMap::new(); + let tags = document.child(rt::LIST).and_then(|l| l.child(rt::PROG_TAGS)); + let Some(tags) = tags else { return out }; + let ppt9 = tags + .children_of(rt::PROG_BINARY_TAG) + .find(|tag| tag.child(rt::CSTRING).is_some_and(|name| cstring_units(name.data).eq("___PPT9".encode_utf16()))); + let Some(data) = ppt9.and_then(|t| t.child(rt::BINARY_TAG_DATA)) else { return out }; + // The tag's data is an atom whose body holds records. + for props in Records::new(data.data).filter(|r| r.kind == rt::OUTLINE_TEXT_PROPS9) { + let mut header = None; + for r in props.children() { + if r.kind == rt::OUTLINE_TEXT_PROPS_HEADER { + header = r.u32(0).zip(r.u32(4)); + } else if r.kind == rt::STYLE_TEXT_PROP9 + && let Some(key) = header.take() + { + out.entry(key).or_default().push(crate::text::read_style9(r.data)); + } + } + } + out +} diff --git a/crates/ppt-binary/src/draw.rs b/crates/ppt-binary/src/draw.rs new file mode 100644 index 000000000..2b1e8ec79 --- /dev/null +++ b/crates/ppt-binary/src/draw.rs @@ -0,0 +1,522 @@ +//! OfficeArt drawings ([MS-ODRAW]) as `.ppt` stores them: a tree of shape group containers and +//! shape containers, each shape with its `FSP` (type, id, flags), property tables (`FOPT`), +//! anchor and client records (placeholder, text). + +use std::collections::HashMap; + +use crate::doc::rt; +use crate::record::{MAX_DEPTH, Rec}; + +/// Property ids ([MS-ODRAW] §2.3). +pub mod prop { + pub const ROTATION: u16 = 0x0004; + pub const TEXT_LEFT: u16 = 0x0081; + pub const TEXT_TOP: u16 = 0x0082; + pub const TEXT_RIGHT: u16 = 0x0083; + pub const TEXT_BOTTOM: u16 = 0x0084; + pub const WRAP_TEXT: u16 = 0x0085; + pub const ANCHOR_TEXT: u16 = 0x0087; + pub const CROP_TOP: u16 = 0x0100; + pub const CROP_BOTTOM: u16 = 0x0101; + pub const CROP_LEFT: u16 = 0x0102; + pub const CROP_RIGHT: u16 = 0x0103; + pub const PIB: u16 = 0x0104; + pub const GEO_LEFT: u16 = 0x0140; + pub const GEO_TOP: u16 = 0x0141; + pub const GEO_RIGHT: u16 = 0x0142; + pub const GEO_BOTTOM: u16 = 0x0143; + pub const SHAPE_PATH: u16 = 0x0144; + pub const VERTICES: u16 = 0x0145; + pub const SEGMENT_INFO: u16 = 0x0146; + pub const ADJUST_VALUE: u16 = 0x0147; + pub const FILL_TYPE: u16 = 0x0180; + pub const FILL_COLOR: u16 = 0x0181; + pub const FILL_OPACITY: u16 = 0x0182; + pub const FILL_BACK_COLOR: u16 = 0x0183; + pub const FILL_BACK_OPACITY: u16 = 0x0184; + pub const FILL_BLIP: u16 = 0x0186; + pub const FILL_ANGLE: u16 = 0x018B; + pub const FILL_FOCUS: u16 = 0x018C; + pub const FILL_BOOLS: u16 = 0x01BF; + pub const LINE_COLOR: u16 = 0x01C0; + pub const LINE_OPACITY: u16 = 0x01C1; + pub const LINE_WIDTH: u16 = 0x01CB; + pub const LINE_STYLE: u16 = 0x01CD; + pub const LINE_DASHING: u16 = 0x01CE; + pub const LINE_START_ARROW: u16 = 0x01D0; + pub const LINE_END_ARROW: u16 = 0x01D1; + pub const LINE_START_ARROW_WIDTH: u16 = 0x01D2; + pub const LINE_START_ARROW_LENGTH: u16 = 0x01D3; + pub const LINE_END_ARROW_WIDTH: u16 = 0x01D4; + pub const LINE_END_ARROW_LENGTH: u16 = 0x01D5; + pub const LINE_JOIN: u16 = 0x01D6; + pub const LINE_CAP: u16 = 0x01D7; + pub const LINE_BOOLS: u16 = 0x01FF; + pub const SHADOW_COLOR: u16 = 0x0201; + pub const SHADOW_OPACITY: u16 = 0x0204; + pub const SHADOW_OFFSET_X: u16 = 0x0205; + pub const SHADOW_OFFSET_Y: u16 = 0x0206; + pub const SHADOW_BOOLS: u16 = 0x023F; + pub const HSP_MASTER: u16 = 0x0301; + pub const NAME: u16 = 0x0380; + pub const DESCRIPTION: u16 = 0x0381; + pub const GROUP_BOOLS: u16 = 0x03BF; +} + +/// UTF-16 units kept of a string property. +pub const MAX_STRING: usize = 4096; + +/// Distinct properties one set keeps. Ids are 14 bits, so a file's tables could name about 16K of +/// them, and every shape copies the drawing defaults' and its master shape's sets into its own: +/// unbounded, that is shapes × 16K. [MS-ODRAW] defines a few hundred properties and a real shape +/// or the drawing defaults set tens of them. Entries past the limit are still read (their complex +/// data keeps its place) but not kept. +pub const MAX_PROPS: usize = 1024; + +/// One property value: the 32-bit operand and, for complex properties, the extra bytes. +#[derive(Clone, Copy, Debug)] +pub struct PropVal<'a> { + pub op: u32, + pub complex: Option<&'a [u8]>, +} + +/// A shape's merged property tables (primary first; secondary and tertiary fill gaps). +#[derive(Clone, Debug, Default)] +pub struct Props<'a> { + map: HashMap>, +} + +impl<'a> Props<'a> { + /// Read one `FOPT` body: `count` 6-byte entries then the complex data in entry order. Entries + /// already present are kept (the caller adds the most specific table first). + pub fn add_table(&mut self, r: &Rec<'a>) { + let count = usize::from(r.instance); + let mut complex_at = count.saturating_mul(6); + for i in 0..count { + let (Some(id), Some(op)) = (r.u16(i * 6), r.u32(i * 6 + 2)) else { break }; + let is_complex = id & 0x8000 != 0; + let pid = id & 0x3FFF; + let complex = if is_complex { + let len = op as usize; + let data = r.data.get(complex_at..complex_at.saturating_add(len).min(r.data.len())); + complex_at = complex_at.saturating_add(len); + data + } else { + None + }; + self.fill_gap(pid, PropVal { op, complex }); + } + } + + /// Fill gaps from another set (a master shape's or the drawing defaults). + pub fn inherit(&mut self, other: &Props<'a>) { + for (k, v) in &other.map { + self.fill_gap(*k, *v); + } + } + + /// Add `v` for `id` where this set doesn't say it already. A boolean property word ([MS-ODRAW]: + /// the last id of each 64-id group) holds sixteen flags, each with its own `fUse` bit 16 + /// places up, so it is merged flag by flag: a shape that sets only `fNoFillHitTest` still + /// inherits `fFilled` from its master or the defaults. + fn fill_gap(&mut self, id: u16, v: PropVal<'a>) { + let full = self.map.len() >= MAX_PROPS; + match self.map.get_mut(&id) { + None if full => {} + None => { + self.map.insert(id, v); + } + Some(have) if id & 0x3F == 0x3F => { + let unset = !(have.op >> 16) & 0xFFFF; + let take = (v.op >> 16) & unset; + have.op |= take << 16; + have.op = (have.op & !take) | (v.op & take); + } + Some(_) => {} + } + } + + /// Set a simple (non-complex) property. + pub fn set(&mut self, id: u16, op: u32) { + self.map.insert(id, PropVal { op, complex: None }); + } + + pub fn get(&self, id: u16) -> Option { + self.map.get(&id).map(|v| v.op) + } + + pub fn complex(&self, id: u16) -> Option<&'a [u8]> { + self.map.get(&id).and_then(|v| v.complex) + } + + /// A 16.16 fixed-point value. + pub fn fixed(&self, id: u16) -> Option { + self.get(id).map(|v| f64::from(v as i32) / 65536.0) + } + + /// A boolean from a bool-property word: bit `bit` holds the value, bit `bit + 16` says it is set. + pub fn flag(&self, id: u16, bit: u32) -> Option { + let v = self.get(id)?; + (v & (1 << (bit + 16)) != 0).then_some(v & (1 << bit) != 0) + } + + /// A UTF-16 string property (names, alt text), at most [`MAX_STRING`] units: a master shape's + /// name is copied into every shape that inherits it. + pub fn string(&self, id: u16) -> Option { + let b = self.complex(id)?; + let units: Vec = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take(MAX_STRING).take_while(|&u| u != 0).collect(); + Some(String::from_utf16_lossy(&units)).filter(|s| !s.is_empty()) + } + + /// An `IMsoArray` property: element size and the elements' bytes. + pub fn array(&self, id: u16) -> Option<(usize, &'a [u8])> { + let b = self.complex(id)?; + let n = usize::from(crate::record::u16_at(b, 0)?); + let size = crate::record::u16_at(b, 4)?; + // 0xFFF0 marks 4-byte elements stored as two 2-byte halves. + let size = if size == 0xFFF0 { 4 } else { usize::from(size) }; + if size == 0 { + return None; + } + let body = b.get(6..)?; + let len = n.saturating_mul(size).min(body.len() / size * size); + Some((size, body.get(..len)?)) + } +} + +/// An anchor rectangle in its own coordinate units: master units for a client anchor, the parent +/// group's units for a child anchor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Anchor { + pub left: f64, + pub top: f64, + pub right: f64, + pub bottom: f64, +} + +/// The placeholder a shape stands for (`OEPlaceholderAtom`). +#[derive(Clone, Copy, Debug)] +pub struct Placeholder { + pub position: u32, + /// `PlaceholderEnum`. + pub kind: u8, +} + +/// One shape of a drawing, before conversion. +#[derive(Clone, Debug)] +pub struct RawShape<'a> { + /// `MSOSPT` shape type. + pub shape_type: u16, + pub spid: u32, + pub flip_h: bool, + pub flip_v: bool, + pub patriarch: bool, + pub deleted: bool, + pub props: Props<'a>, + pub anchor: Option, + /// For a group: the child coordinate rectangle (`FSPGR`). + pub group_rect: Option, + pub children: Vec>, + pub is_group: bool, + pub placeholder: Option, + /// The records of the shape's text box (`OfficeArtClientTextbox`). + pub text: Option>, +} + +/// The top-level shapes and the background shape of a `DrawingContainer`. +pub struct Drawing<'a> { + pub shapes: Vec>, + pub background: Option>, +} + +/// Read the drawing of a slide, master or notes container. +pub fn drawing<'a>(container: &Rec<'a>) -> Drawing<'a> { + let mut out = Drawing { shapes: vec![], background: None }; + let Some(dg) = container.child(rt::DRAWING).and_then(|d| d.child(rt::DG_CONTAINER)) else { return out }; + // The background is the container's own shape (`OfficeArtDgContainer.shape`, [MS-ODRAW] + // 2.2.13), not one found by its fBackground flag. + if let Some(bg) = dg.child(rt::SP_CONTAINER) { + out.background = Some(shape(&bg)); + } + if let Some(top) = dg.child(rt::SPGR_CONTAINER) { + // The first shape of the top group is the patriarch, standing for the drawing itself. + out.shapes = group_children(&top, 0).into_iter().filter(|s| !s.patriarch).collect(); + } + out +} + +fn group_children<'a>(gr: &Rec<'a>, depth: usize) -> Vec> { + if depth > MAX_DEPTH { + return vec![]; + } + let mut out = vec![]; + for r in gr.children() { + match r.kind { + rt::SP_CONTAINER => out.push(shape(&r)), + rt::SPGR_CONTAINER => { + let mut kids = r.children(); + // A group container's first shape describes the group itself. + let Some(head) = kids.next().filter(|h| h.kind == rt::SP_CONTAINER) else { continue }; + let mut g = shape(&head); + g.is_group = true; + g.children = group_children(&r, depth + 1).into_iter().skip(1).collect(); + out.push(g); + } + _ => {} + } + } + out +} + +fn rect_i32(r: &Rec) -> Option { + Some(Anchor { left: f64::from(r.i32(0)?), top: f64::from(r.i32(4)?), right: f64::from(r.i32(8)?), bottom: f64::from(r.i32(12)?) }) +} + +fn shape<'a>(sp: &Rec<'a>) -> RawShape<'a> { + let mut s = RawShape { + shape_type: 0, + spid: 0, + flip_h: false, + flip_v: false, + patriarch: false, + deleted: false, + props: Props::default(), + anchor: None, + group_rect: None, + children: vec![], + is_group: false, + placeholder: None, + text: None, + }; + // Tables in specificity order: primary (the last one first), then secondary and tertiary. + let mut primary: Vec = vec![]; + let mut tables: Vec = vec![]; + for r in sp.children() { + match r.kind { + rt::FSP => { + s.shape_type = r.instance; + s.spid = r.u32(0).unwrap_or(0); + let f = r.u32(4).unwrap_or(0); + s.patriarch = f & 0x4 != 0; + s.deleted = f & 0x8 != 0; + s.flip_h = f & 0x40 != 0; + s.flip_v = f & 0x80 != 0; + } + rt::FOPT => primary.push(r), + rt::SECONDARY_FOPT | rt::TERTIARY_FOPT => tables.push(r), + rt::FSPGR => s.group_rect = rect_i32(&r), + rt::CHILD_ANCHOR => s.anchor = rect_i32(&r), + rt::CLIENT_ANCHOR => { + s.anchor = if r.data.len() >= 16 { + // RectStruct: top, left, right, bottom. + (|| { + Some(Anchor { + top: f64::from(r.i32(0)?), + left: f64::from(r.i32(4)?), + right: f64::from(r.i32(8)?), + bottom: f64::from(r.i32(12)?), + }) + })() + } else { + // SmallRectStruct: top, left, right, bottom. + (|| { + Some(Anchor { + top: f64::from(r.i16(0)?), + left: f64::from(r.i16(2)?), + right: f64::from(r.i16(4)?), + bottom: f64::from(r.i16(6)?), + }) + })() + }; + } + rt::CLIENT_DATA => { + if let Some(p) = r.child(rt::PLACEHOLDER_ATOM) { + s.placeholder = Some(Placeholder { position: p.u32(0).unwrap_or(0), kind: p.u8(4).unwrap_or(0) }); + } + } + rt::CLIENT_TEXTBOX => s.text = Some(r), + _ => {} + } + } + for t in primary.iter().rev().chain(&tables) { + s.props.add_table(t); + } + s +} + +/// The drawing-wide default properties (`OfficeArtDggContainer`'s `FOPT`). +pub fn default_props<'a>(dgg: Option>) -> Props<'a> { + let mut p = Props::default(); + if let Some(dgg) = dgg { + for t in dgg.children().filter(|r| matches!(r.kind, rt::FOPT | rt::SECONDARY_FOPT | rt::TERTIARY_FOPT)) { + p.add_table(&t); + } + } + p +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + pub fn fopt(entries: &[(u16, u32)], complex: &[u8]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + b.extend_from_slice(complex); + atom(rt::FOPT, entries.len() as u16, &b) + } + + #[test] + fn reads_properties_and_complex_strings() { + let name: Vec = "Logo\0".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let t = fopt(&[(prop::FILL_COLOR, 0x0011_2233), (0x8000 | prop::NAME, name.len() as u32), (prop::FILL_BOOLS, 0x0010_0000)], &name); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.get(prop::FILL_COLOR), Some(0x0011_2233)); + assert_eq!(p.string(prop::NAME).as_deref(), Some("Logo")); + assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false)); + assert_eq!(p.flag(prop::LINE_BOOLS, 3), None); + } + + /// A boolean word inherits the flags it doesn't set (storytold/deckcraft#1137 review): a text box that sets only + /// `fNoFillHitTest` (bit 4 is `fFilled`, bit 0 `fNoFillHitTest`) still gets "not filled" + /// from below, and its own flags win over the inherited ones. + #[test] + fn boolean_properties_merge_flag_by_flag() { + let mut p = Props::default(); + p.set(prop::FILL_BOOLS, 0x0001_0001); // fNoFillHitTest = true; fFilled not said + p.set(prop::LINE_BOOLS, 0x0008_0008); // fLine = true + let mut below = Props::default(); + below.set(prop::FILL_BOOLS, 0x0011_0000); // fFilled = false, fNoFillHitTest = false + below.set(prop::LINE_BOOLS, 0x0008_0000); // fLine = false + p.inherit(&below); + assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false)); + assert_eq!(p.flag(prop::FILL_BOOLS, 0), Some(true)); + assert_eq!(p.flag(prop::LINE_BOOLS, 3), Some(true)); + // The same merge applies between a shape's own tables. + let t = fopt(&[(prop::FILL_BOOLS, 0x0001_0001)], &[]); + let t2 = fopt(&[(prop::FILL_BOOLS, 0x0010_0010)], &[]); + let mut q = Props::default(); + q.add_table(&Rec::at(&t, 0).unwrap()); + q.add_table(&Rec::at(&t2, 0).unwrap()); + assert_eq!(q.flag(prop::FILL_BOOLS, 4), Some(true)); + assert_eq!(q.flag(prop::FILL_BOOLS, 0), Some(true)); + // Non-boolean properties still keep the first value. + let mut r = Props::default(); + r.set(prop::FILL_COLOR, 1); + let mut s = Props::default(); + s.set(prop::FILL_COLOR, 2); + r.inherit(&s); + assert_eq!(r.get(prop::FILL_COLOR), Some(1)); + } + + /// A string property longer than [`MAX_STRING`] units is cut there. + #[test] + fn a_long_string_property_is_capped() { + let name: Vec = "x".repeat(10_000).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let t = fopt(&[(0x8000 | prop::NAME, name.len() as u32)], &name); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.string(prop::NAME).map(|s| s.len()), Some(MAX_STRING)); + } + + /// A table naming more than [`MAX_PROPS`] properties keeps that many, and still reads the + /// complex data after them and the records after it. + #[test] + fn a_property_set_keeps_at_most_max_props() { + let mut entries: Vec<(u16, u32)> = (0..MAX_PROPS as u16 + 100).map(|i| (0x1000 + i, u32::from(i))).collect(); + let name: Vec = "Kept\0".encode_utf16().flat_map(u16::to_le_bytes).collect(); + entries.insert(0, (0x8000 | prop::NAME, name.len() as u32)); + let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat()); + let anchor = atom(rt::CHILD_ANCHOR, 0, &[1i32, 2, 3, 4].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let sp = container(rt::SP_CONTAINER, 0, &[fsp, fopt(&entries, &name), anchor]); + let s = shape(&Rec::at(&sp, 0).unwrap()); + assert_eq!(s.props.map.len(), MAX_PROPS); + assert_eq!(s.props.string(prop::NAME).as_deref(), Some("Kept")); + assert_eq!(s.props.get(0x1000), Some(0)); + assert_eq!(s.props.get(0x1000 + MAX_PROPS as u16), None, "past the limit"); + assert_eq!(s.anchor, Some(Anchor { left: 1.0, top: 2.0, right: 3.0, bottom: 4.0 })); + // Inheriting can't pass the limit either. + let mut p = Props::default(); + p.set(prop::FILL_COLOR, 1); + p.inherit(&s.props); + assert_eq!(p.map.len(), MAX_PROPS); + } + + /// A shape's later primary property table wins over its earlier one, and both over its + /// secondary table. + #[test] + fn the_last_primary_table_wins() { + let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat()); + let secondary = { + let mut b = vec![]; + for (id, op) in [(prop::FILL_COLOR, 3u32), (prop::LINE_COLOR, 3)] { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + atom(rt::SECONDARY_FOPT, 2, &b) + }; + let sp = container( + rt::SP_CONTAINER, + 0, + &[fsp, secondary, fopt(&[(prop::FILL_COLOR, 1), (prop::LINE_WIDTH, 1)], &[]), fopt(&[(prop::FILL_COLOR, 2)], &[])], + ); + let s = shape(&Rec::at(&sp, 0).unwrap()); + assert_eq!((s.props.get(prop::FILL_COLOR), s.props.get(prop::LINE_WIDTH), s.props.get(prop::LINE_COLOR)), (Some(2), Some(1), Some(3))); + } + + #[test] + fn a_complex_length_past_the_record_is_clipped() { + let t = fopt(&[(0x8000 | prop::NAME, 0xFFFF_FFFF), (0x8000 | prop::DESCRIPTION, 10)], b"A\0"); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.string(prop::NAME).as_deref(), Some("A")); + assert_eq!(p.complex(prop::DESCRIPTION), None); + } + + #[test] + fn reads_groups_anchors_and_placeholders() { + let fsp = |t: u16, id: u32, flags: u32| atom(rt::FSP, t, &[id.to_le_bytes(), flags.to_le_bytes()].concat()); + let small = + |t: i16, l: i16, r: i16, b: i16| atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let child = + |l: i32, t: i32, r: i32, b: i32| atom(rt::CHILD_ANCHOR, 0, &[l, t, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let ph = container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, 0x0D, 0, 0, 0])]); + let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]); + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0xA00), small(10, 20, 300, 80), ph]); + let group = container( + rt::SPGR_CONTAINER, + 0, + &[ + container( + rt::SP_CONTAINER, + 0, + &[ + atom(rt::FSPGR, 1, &[0i32, 0, 100, 100].iter().flat_map(|v| v.to_le_bytes()).collect::>()), + fsp(0, 1026, 0x201), + small(100, 100, 200, 200), + ], + ), + container(rt::SP_CONTAINER, 0, &[fsp(3, 1027, 0x40), child(0, 0, 50, 50)]), + ], + ); + let drawing = container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &[container(rt::SPGR_CONTAINER, 0, &[patriarch, title, group])])]); + let slide = container(rt::SLIDE, 0, &[drawing]); + let d = super::drawing(&Rec::at(&slide, 0).unwrap()); + assert_eq!(d.shapes.len(), 2); + let t = &d.shapes[0]; + assert_eq!(t.placeholder.unwrap().kind, 0x0D); + assert_eq!(t.anchor, Some(Anchor { left: 20.0, top: 10.0, right: 300.0, bottom: 80.0 })); + let g = &d.shapes[1]; + assert!(g.is_group); + assert_eq!(g.children.len(), 1); + assert!(g.children[0].flip_h); + assert_eq!(g.group_rect.unwrap().right, 100.0); + } +} diff --git a/crates/ppt-binary/src/geom.rs b/crates/ppt-binary/src/geom.rs new file mode 100644 index 000000000..52206018a --- /dev/null +++ b/crates/ppt-binary/src/geom.rs @@ -0,0 +1,454 @@ +//! Shape geometry: OfficeArt shape types (`MSOSPT`, [MS-ODRAW] §2.4.24) as DrawingML preset +//! names, and freeform paths from the vertices and segment properties (§2.3.6). + +use craft_pptx::{CustomPath, Geom}; + +use crate::draw::{Props, prop}; + +/// The preset for a shape type, `None` for a freeform (`msosptNotPrimitive`) or a type with no +/// preset counterpart. +pub fn preset_name(shape_type: u16) -> Option<&'static str> { + Some(match shape_type { + 1 | 75 | 202 | 201 => "rect", + 2 => "roundRect", + 3 => "ellipse", + 4 => "diamond", + 5 => "triangle", + 6 => "rtTriangle", + 7 => "parallelogram", + 8 => "trapezoid", + 9 => "hexagon", + 10 => "octagon", + 11 => "plus", + 12 => "star5", + 13 | 14 => "rightArrow", + 15 => "homePlate", + 16 => "cube", + 17 => "wedgeRoundRectCallout", + 18 => "star16", + 19 => "arc", + 20 => "line", + 21 => "plaque", + 22 => "can", + 23 => "donut", + 32 => "straightConnector1", + 33 => "bentConnector2", + 34 => "bentConnector3", + 35 => "bentConnector4", + 36 => "bentConnector5", + 37 => "curvedConnector2", + 38 => "curvedConnector3", + 39 => "curvedConnector4", + 40 => "curvedConnector5", + 41 | 178 => "callout1", + 42 => "callout2", + 43 => "callout3", + 44 | 179 => "accentCallout1", + 45 => "accentCallout2", + 46 => "accentCallout3", + 47 | 180 => "borderCallout1", + 48 => "borderCallout2", + 49 => "borderCallout3", + 50 | 181 => "accentBorderCallout1", + 51 => "accentBorderCallout2", + 52 => "accentBorderCallout3", + 53 => "ribbon", + 54 => "ribbon2", + 55 => "chevron", + 56 => "pentagon", + 57 => "noSmoking", + 58 => "star8", + 59 => "star16", + 60 => "star32", + 61 => "wedgeRectCallout", + 62 => "wedgeRoundRectCallout", + 63 => "wedgeEllipseCallout", + 64 => "wave", + 65 => "foldedCorner", + 66 => "leftArrow", + 67 => "downArrow", + 68 => "upArrow", + 69 => "leftRightArrow", + 70 => "upDownArrow", + 71 => "irregularSeal1", + 72 => "irregularSeal2", + 73 => "lightningBolt", + 74 => "heart", + 76 => "quadArrow", + 77 => "leftArrowCallout", + 78 => "rightArrowCallout", + 79 => "upArrowCallout", + 80 => "downArrowCallout", + 81 => "leftRightArrowCallout", + 82 => "upDownArrowCallout", + 83 => "quadArrowCallout", + 84 => "bevel", + 85 => "leftBracket", + 86 => "rightBracket", + 87 => "leftBrace", + 88 => "rightBrace", + 89 => "leftUpArrow", + 90 => "bentUpArrow", + 91 => "bentArrow", + 92 => "star24", + 93 => "stripedRightArrow", + 94 => "notchedRightArrow", + 95 => "blockArc", + 96 => "smileyFace", + 97 => "verticalScroll", + 98 => "horizontalScroll", + 99 | 100 => "circularArrow", + 101 => "uturnArrow", + 102 => "curvedRightArrow", + 103 => "curvedLeftArrow", + 104 => "curvedUpArrow", + 105 => "curvedDownArrow", + 106 => "cloudCallout", + 107 => "ellipseRibbon", + 108 => "ellipseRibbon2", + 109 => "flowChartProcess", + 110 => "flowChartDecision", + 111 => "flowChartInputOutput", + 112 => "flowChartPredefinedProcess", + 113 => "flowChartInternalStorage", + 114 => "flowChartDocument", + 115 => "flowChartMultidocument", + 116 => "flowChartTerminator", + 117 => "flowChartPreparation", + 118 => "flowChartManualInput", + 119 => "flowChartManualOperation", + 120 => "flowChartConnector", + 121 => "flowChartPunchedCard", + 122 => "flowChartPunchedTape", + 123 => "flowChartSummingJunction", + 124 => "flowChartOr", + 125 => "flowChartCollate", + 126 => "flowChartSort", + 127 => "flowChartExtract", + 128 => "flowChartMerge", + 129 => "flowChartOfflineStorage", + 130 => "flowChartOnlineStorage", + 131 => "flowChartMagneticTape", + 132 => "flowChartMagneticDisk", + 133 => "flowChartMagneticDrum", + 134 => "flowChartDisplay", + 135 => "flowChartDelay", + 176 => "flowChartAlternateProcess", + 177 => "flowChartOffpageConnector", + 182 => "leftRightUpArrow", + 183 => "sun", + 184 => "moon", + 185 => "bracketPair", + 186 => "bracePair", + 187 => "star4", + 188 => "doubleWave", + 189 => "actionButtonBlank", + 190 => "actionButtonHome", + 191 => "actionButtonHelp", + 192 => "actionButtonInformation", + 193 => "actionButtonForwardNext", + 194 => "actionButtonBackPrevious", + 195 => "actionButtonEnd", + 196 => "actionButtonBeginning", + 197 => "actionButtonReturn", + 198 => "actionButtonDocument", + 199 => "actionButtonSound", + 200 => "actionButtonMovie", + // WordArt text shapes (24–31, 136–175) draw their text as plain text in a rectangle. + 24..=31 | 136..=175 => "rect", + _ => return None, + }) +} + +/// Whether a shape type is a connector. +pub fn is_connector(shape_type: u16) -> bool { + (32..=40).contains(&shape_type) +} + +/// The geometry of a shape: its preset (checked against the presets `craft_drawingml` draws, with a +/// rounded rectangle's corner carried over), else its freeform path, else a rectangle. +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); + } + return Geom::Preset { name: name.into(), adj }; + } + custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default() +} + +/// Segments followed at most in one path. +const MAX_SEGMENTS: usize = 1 << 16; +/// Vertices used at most in one path. The path text is copied into every shape that inherits the +/// vertices from a master shape, so it stays a bounded size. +const MAX_POINTS: usize = 8192; + +/// A freeform's path in its geometry box. +fn custom_path(props: &Props) -> Option> { + let (size, verts) = props.array(prop::VERTICES)?; + let points: Vec<(f64, f64)> = match size { + 8 => verts + .as_chunks::<8>() + .0 + .iter() + .take(MAX_POINTS) + .map(|c| (f64::from(i32::from_le_bytes([c[0], c[1], c[2], c[3]])), f64::from(i32::from_le_bytes([c[4], c[5], c[6], c[7]])))) + .collect(), + 4 => verts + .as_chunks::<4>() + .0 + .iter() + .take(MAX_POINTS) + .map(|c| (f64::from(i16::from_le_bytes([c[0], c[1]])), f64::from(i16::from_le_bytes([c[2], c[3]])))) + .collect(), + _ => return None, + }; + if points.is_empty() { + return None; + } + let left = f64::from(props.get(prop::GEO_LEFT).unwrap_or(0) as i32); + let top = f64::from(props.get(prop::GEO_TOP).unwrap_or(0) as i32); + let right = f64::from(props.get(prop::GEO_RIGHT).unwrap_or(21600) as i32); + let bottom = f64::from(props.get(prop::GEO_BOTTOM).unwrap_or(21600) as i32); + let (w, h) = ((right - left).abs().max(1.0), (bottom - top).abs().max(1.0)); + let mut pts = points.iter().map(|(x, y)| (x - left, y - top)); + let mut d = String::new(); + let mut push = |cmd: &str, ps: &[(f64, f64)]| { + d.push_str(cmd); + for (x, y) in ps { + d.push_str(&format!(" {x} {y}")); + } + d.push(' '); + }; + match props.array(prop::SEGMENT_INFO) { + // An empty segment list is no segments ([MS-ODRAW] shapePath: it applies unless the list + // is "neither NULL nor empty"). + Some((2, segs)) if !segs.is_empty() => { + for c in segs.as_chunks::<2>().0.iter().take(MAX_SEGMENTS) { + let v = u16::from_le_bytes(*c); + let count = usize::from(v & 0x1FFF); + match v >> 13 { + // lineTo + 0 => { + for _ in 0..count.max(1) { + let Some(p) = pts.next() else { break }; + push("L", &[p]); + } + } + // curveTo: three points per segment + 1 => { + for _ in 0..count.max(1) { + let ps: Vec<_> = pts.by_ref().take(3).collect(); + if ps.len() < 3 { + break; + } + push("C", &ps); + } + } + 2 => { + let Some(p) = pts.next() else { break }; + push("M", &[p]); + } + 3 => push("Z", &[]), + 4 => break, + // Escapes (MSOPATHESCAPEINFO: escape code in bits 8–12, point count in bits + // 0–7). They aren't drawn as curves, but they use up their points, and the + // segments after them start where they end. + 5 => { + let n = usize::from(v & 0xFF); + let code = (v >> 8) & 0x1F; + let mut last = None; + for _ in 0..n { + last = pts.next().or(last); + } + match code { + // Extension: more points for the escape that follows. Fill and line + // colours: a colour pair, not a place. NoFill, NoLine and the Bézier + // editing hints: no points. + 0x00 | 0x0A..=0x16 => {} + // Elliptical quadrants run from point to point and a quadratic Bézier + // ends on its last point: a line there keeps the path's place. + 0x07..=0x09 => { + if let Some(p) = last { + push("L", &[p]); + } + } + // Angle ellipses and arcs end at a point computed from their angles or + // radial vectors, not at one of their vertices: the path stops rather + // than go on from the wrong place. So does any other escape. + _ => break, + } + } + // Client escapes mean what the writing application says: the path stops + // unless one has no points. + 6 if v & 0xFF != 0 => break, + _ => {} + } + } + } + // No segments: shapePath says how the vertices join (MSOSHAPEPATH), by default + // msoshapeLinesClosed. + _ => { + let shape_path = props.get(prop::SHAPE_PATH).unwrap_or(1); + if let Some(p) = pts.next() { + push("M", &[p]); + } + if matches!(shape_path, 2 | 3) { + loop { + let ps: Vec<_> = pts.by_ref().take(3).collect(); + if ps.len() < 3 { + break; + } + push("C", &ps); + } + } else { + for p in pts { + push("L", &[p]); + } + } + if matches!(shape_path, 1 | 3) { + push("Z", &[]); + } + } + } + let d = d.trim_end().to_string(); + if !d.starts_with('M') { + return None; + } + Some(vec![CustomPath { w, h, d, ..Default::default() }]) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::Rec; + use crate::record::build::atom; + + fn props(entries: &[(u16, u32)], complex: &[u8]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + b.extend_from_slice(complex); + atom(crate::doc::rt::FOPT, entries.len() as u16, &b) + } + + fn array(size: u16, elems: &[u8]) -> Vec { + let n = (elems.len() / usize::from(size)) as u16; + [&n.to_le_bytes()[..], &n.to_le_bytes(), &size.to_le_bytes(), elems].concat() + } + + #[test] + fn every_mapped_preset_is_one_craft_drawingml_draws() { + for t in 0..=255u16 { + if let Some(name) = preset_name(t) { + assert!(craft_drawingml::preset::build(name, 100.0, 100.0, &[]).is_some(), "type {t}: {name}"); + } + } + } + + #[test] + fn reads_a_freeform_triangle() { + let verts: Vec = [(0i16, 100i16), (50, 0), (100, 100)].iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect(); + // moveTo, lineTo ×2, close, end + let segs: Vec = [0x4000u16, 0x0002, 0x6001, 0x8000].iter().flat_map(|v| v.to_le_bytes()).collect(); + let v = array(4, &verts); + let s = array(2, &segs); + let t = props( + &[ + (prop::GEO_RIGHT, 100), + (prop::GEO_BOTTOM, 100), + (0x8000 | prop::VERTICES, v.len() as u32), + (0x8000 | prop::SEGMENT_INFO, s.len() as u32), + ], + &[v, s].concat(), + ); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") }; + assert_eq!(paths[0].d, "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!((paths[0].w, paths[0].h), (100.0, 100.0)); + } + + /// A freeform with more vertices than [`MAX_POINTS`] draws through the first of them only. + #[test] + fn a_path_uses_at_most_max_points() { + let verts: Vec = (0..20_000u32).flat_map(|i| [(i as i16 % 100).to_le_bytes(), 0i16.to_le_bytes()].concat()).collect(); + let v = array(4, &verts); + let t = props(&[(0x8000 | prop::VERTICES, v.len() as u32)], &v); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") }; + let d = &paths[0].d; + assert_eq!(d.matches('M').count() + d.matches('L').count(), MAX_POINTS); + } + + fn freeform(verts: &[(i16, i16)], segs: Option<&[u16]>, extra: &[(u16, u32)]) -> Geom { + let verts: Vec = verts.iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect(); + let v = array(4, &verts); + let mut entries = vec![(prop::GEO_RIGHT, 100), (prop::GEO_BOTTOM, 100), (0x8000 | prop::VERTICES, v.len() as u32)]; + entries.extend_from_slice(extra); + let mut complex = v; + if let Some(segs) = segs { + let s = array(2, &segs.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + entries.push((0x8000 | prop::SEGMENT_INFO, s.len() as u32)); + complex.extend_from_slice(&s); + } + let t = props(&entries, &complex); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + geometry(0, &p) + } + + fn path_of(g: Geom) -> String { + let Geom::Custom { paths } = g else { panic!("not custom: {g:?}") }; + paths[0].d.clone() + } + + /// An escape segment uses up its points and the path goes on from where it ends: after + /// elliptical quadrants or a quadratic Bézier, from their last point; an arc ends at a point + /// worked out from its radial vectors, so the path stops there rather than draw the next line + /// from the point before the arc. + #[test] + fn path_escapes_end_where_they_end() { + let verts = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (50, 60)]; + let escape = |code: u16, n: u16| (5u16 << 13) | (code << 8) | n; + // moveTo, escape ArcTo (3) over 4 points, lineTo, end. + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(3, 4), 0x0001, 0x8000]), &[])), "M 0 0"); + // moveTo, two elliptical quadrants (7), lineTo, end. + let verts = [(0, 0), (10, 10), (20, 0), (50, 60)]; + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(7, 2), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0 L 50 60"); + // A colour escape uses its point but doesn't move the path. + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(0x15, 1), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0"); + } + + /// Without segments, shapePath says how the vertices join: closed lines by default, open + /// lines, or Bézier curves three points at a time. An empty segment list is no segments. + #[test] + fn shape_path_joins_vertices_without_segments() { + let tri = [(0, 100), (50, 0), (100, 100)]; + assert_eq!(path_of(freeform(&tri, None, &[])), "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!(path_of(freeform(&tri, Some(&[]), &[])), "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!(path_of(freeform(&tri, None, &[(prop::SHAPE_PATH, 0)])), "M 0 100 L 50 0 L 100 100"); + let curve = [(0, 0), (10, 0), (20, 10), (20, 20)]; + assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 2)])), "M 0 0 C 10 0 20 10 20 20"); + assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 3)])), "M 0 0 C 10 0 20 10 20 20 Z"); + } + + #[test] + fn a_rounded_rectangle_keeps_its_corner() { + let t = props(&[(prop::ADJUST_VALUE, 5400)], &[]); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(geometry(2, &p), Geom::Preset { name: "roundRect".into(), adj: vec![25000.0] }); + assert_eq!(geometry(9999, &Props::default()), Geom::default()); + } +} diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs new file mode 100644 index 000000000..b9b2fa315 --- /dev/null +++ b/crates/ppt-binary/src/lib.rs @@ -0,0 +1,76 @@ +//! Legacy PowerPoint 97–2003 import (`.ppt`, `.pot`, `.pps`), written from Microsoft's public +//! Open Specifications: [MS-PPT] (the presentation records) and [MS-ODRAW] (the shapes and +//! pictures), on `craft-cfb` for the compound file ([MS-CFB]). +//! +//! [`import`] reads a presentation leniently into a [`craft_pptx::Presentation`]: unknown records +//! 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. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeExamples; + +mod blip; +mod convert; +mod doc; +mod draw; +mod geom; +mod record; +mod text; + +use craft_cfb::{CompoundFile, Error as CfbError}; +use craft_pptx::{Defaults, Presentation}; + +/// Name of the stream holding the presentation. +const DOCUMENT_STREAM: &str = "PowerPoint Document"; + +#[derive(Debug, thiserror::Error)] +pub enum PptError { + #[error("not a PowerPoint 97-2003 presentation")] + NotPpt, + #[error("the presentation is password-protected")] + Encrypted, + #[error("the presentation was made by PowerPoint 95 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)? +pub fn sniff(bytes: &[u8]) -> bool { + craft_cfb::sniff(bytes) && CompoundFile::open(bytes).is_ok_and(|f| f.has_stream(DOCUMENT_STREAM)) +} + +/// Read a `.ppt` / `.pot` / `.pps` file. `defaults` gives the master each of the file's masters +/// starts from, and the one used when the file has none it can read. +pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result { + import_checked(bytes, defaults).map(|(p, _)| p) +} + +/// [`import`], plus the slides the file lists but whose objects couldn't be found, so they are not +/// in the presentation. +pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec), PptError> { + let file = CompoundFile::open(bytes).map_err(|e| match e { + CfbError::NotCfb => PptError::NotPpt, + other => PptError::Damaged(other.to_string()), + })?; + // No stream is longer than the file holding it: a larger stated size is damage, refused + // before anything is allocated for it. + let cap = bytes.len() as u64; + let stream = file.read_path_capped(DOCUMENT_STREAM, cap).map_err(|e| match e { + CfbError::NotFound(_) => PptError::NotPpt, + other => PptError::Damaged(other.to_string()), + })?; + 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(); + let d = doc::read(¤t_user, &stream)?; + Ok((convert::convert(&d, &pictures, defaults), d.lost.clone())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ppt-binary/src/record.rs b/crates/ppt-binary/src/record.rs new file mode 100644 index 000000000..62655e2be --- /dev/null +++ b/crates/ppt-binary/src/record.rs @@ -0,0 +1,186 @@ +//! The record framing shared by [MS-PPT] and [MS-ODRAW]: an 8-byte header (version, instance, +//! type, length) followed by `len` bytes, which for a container (version `0xF`) are more records. + +/// The little-endian `u16` at `at`, if `b` holds it. +pub(crate) fn u16_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(u16::from_le_bytes([*s.first()?, *s.get(1)?])) +} + +/// The little-endian `u32` at `at`, if `b` holds it. +pub(crate) fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?])) +} + +/// Containers nest at most this deep; deeper input is treated as damaged and skipped. +pub const MAX_DEPTH: usize = 32; + +/// One record over borrowed bytes. +#[derive(Clone, Copy, Debug)] +pub struct Rec<'a> { + pub ver: u8, + pub instance: u16, + pub kind: u16, + /// The record's body (after the header), clipped to the input. + pub data: &'a [u8], + /// Offset of the header in the slice it was read from. + pub offset: usize, +} + +impl<'a> Rec<'a> { + /// The record whose header starts at `at`, its body clipped to `bytes` (a truncated last record + /// keeps what is there). + pub fn at(bytes: &'a [u8], at: usize) -> Option> { + let vi = u16_at(bytes, at)?; + let kind = u16_at(bytes, at.checked_add(2)?)?; + let len = u32_at(bytes, at.checked_add(4)?)? as usize; + let start = at.checked_add(8)?; + let end = start.saturating_add(len).min(bytes.len()); + Some(Rec { ver: (vi & 0xF) as u8, instance: vi >> 4, kind, data: bytes.get(start..end)?, offset: at }) + } + + pub fn is_container(&self) -> bool { + self.ver == 0xF + } + + /// The records inside this one; none for an atom. + pub fn children(&self) -> Records<'a> { + Records::new(if self.is_container() { self.data } else { &[] }) + } + + /// The first child of type `kind`. + pub fn child(&self, kind: u16) -> Option> { + self.children().find(|r| r.kind == kind) + } + + /// Every child of type `kind`. + pub fn children_of(&self, kind: u16) -> impl Iterator> { + self.children().filter(move |r| r.kind == kind) + } + + pub fn u8(&self, at: usize) -> Option { + self.data.get(at).copied() + } + pub fn u16(&self, at: usize) -> Option { + u16_at(self.data, at) + } + pub fn i16(&self, at: usize) -> Option { + self.u16(at).map(|v| v as i16) + } + 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) + } +} + +/// Iterates the records laid end to end in a byte slice. +#[derive(Clone, Debug)] +pub struct Records<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> Records<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Records { bytes, at: 0 } + } +} + +impl<'a> Iterator for Records<'a> { + type Item = Rec<'a>; + fn next(&mut self) -> Option> { + let r = Rec::at(self.bytes, self.at)?; + // Always advance by at least the header, so a zero-length record can't stall the walk. + self.at = self.at.checked_add(8)?.checked_add(r.data.len())?; + Some(r) + } +} + +/// A little-endian reader over a record body for the variable-length structures (text +/// exceptions, style runs): every read is checked and a short body ends the walk. +pub struct Cursor<'a> { + pub b: &'a [u8], + pub at: usize, +} + +impl<'a> Cursor<'a> { + pub fn new(b: &'a [u8]) -> Self { + Cursor { b, at: 0 } + } + /// Bytes left to read. + pub fn remaining(&self) -> usize { + self.b.len().saturating_sub(self.at) + } + pub fn u8(&mut self) -> Option { + let v = *self.b.get(self.at)?; + self.at += 1; + Some(v) + } + pub fn u16(&mut self) -> Option { + let v = u16_at(self.b, self.at)?; + self.at += 2; + Some(v) + } + pub fn i16(&mut self) -> Option { + self.u16().map(|v| v as i16) + } + pub fn u32(&mut self) -> Option { + let v = u32_at(self.b, self.at)?; + self.at += 4; + Some(v) + } +} + +#[cfg(test)] +pub(crate) mod build { + //! Writing records, for tests that build `.ppt` files. + + pub fn atom(kind: u16, instance: u16, body: &[u8]) -> Vec { + head(0, kind, instance, body) + } + + pub fn container(kind: u16, instance: u16, children: &[Vec]) -> Vec { + head(0xF, kind, instance, &children.concat()) + } + + fn head(ver: u16, kind: u16, instance: u16, body: &[u8]) -> Vec { + let mut v = Vec::with_capacity(body.len() + 8); + v.extend_from_slice(&(ver | (instance << 4)).to_le_bytes()); + v.extend_from_slice(&kind.to_le_bytes()); + v.extend_from_slice(&(body.len() as u32).to_le_bytes()); + v.extend_from_slice(body); + v + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::build::*; + use super::*; + + #[test] + fn walks_nested_records() { + let c = container(0x03E8, 0, &[atom(0x03E9, 0, &[1, 2, 3, 4]), atom(0x0FA0, 2, &[9; 6])]); + let r = Rec::at(&c, 0).unwrap(); + assert!(r.is_container()); + let kids: Vec<_> = r.children().collect(); + assert_eq!(kids.len(), 2); + assert_eq!(kids[1].instance, 2); + assert_eq!(r.child(0x03E9).unwrap().u32(0), Some(0x0403_0201)); + } + + #[test] + fn truncated_and_zero_length_records_end_the_walk() { + let mut c = atom(0x1, 0, &[]).repeat(3); + c.extend_from_slice(&[0xF, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2]); + let all: Vec<_> = Records::new(&c).collect(); + assert_eq!(all.len(), 4); + assert_eq!(all[3].data, &[1, 2]); + assert!(Records::new(&[1, 2, 3]).next().is_none()); + } +} diff --git a/crates/ppt-binary/src/tests.rs b/crates/ppt-binary/src/tests.rs new file mode 100644 index 000000000..55ed55396 --- /dev/null +++ b/crates/ppt-binary/src/tests.rs @@ -0,0 +1,1245 @@ +//! End-to-end tests over `.ppt` files built here from records (never files made by PowerPoint). +#![allow(clippy::unwrap_used)] + +use craft_pptx::text::{Align, Bullet, RunKind}; +use craft_pptx::{ + Background, Defaults, Fill, Layout, LayoutId, LayoutType, Master, MasterId, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, ShapeKind, + Size, Slide, TextBody, Xfrm, +}; + +use crate::doc::rt; +use crate::draw::prop; +use crate::record::build::{atom, container}; +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; + +impl Defaults for AppDefaults { + fn master(&self, size: Size, after: u32) -> (Master, u32) { + let next = std::cell::Cell::new(after); + let id = || { + next.set(next.get() + 1); + next.get() + }; + let (w, h) = (size.width, size.height); + let ph = |kind: PhType, name: &str, x: [f64; 4]| Shape { + id: ShapeId(id()), + name: name.into(), + xfrm: Some(Xfrm::new(x[0] * w, x[1] * h, x[2] * w, x[3] * h)), + ph: Some(Placeholder { kind, ..Default::default() }), + text: Some(TextBody::default()), + ..Default::default() + }; + let title = || ph(PhType::Title, "Title", [0.06, 0.05, 0.88, 0.17]); + let footers = || { + vec![ + ph(PhType::Date, "Date", [0.06, 0.92, 0.22, 0.05]), + ph(PhType::Footer, "Footer", [0.33, 0.92, 0.34, 0.05]), + ph(PhType::SlideNum, "Slide Number", [0.72, 0.92, 0.22, 0.05]), + ] + }; + let mut shapes = vec![title(), ph(PhType::Body, "Text", [0.06, 0.25, 0.88, 0.62])]; + shapes.extend(footers()); + let kinds = [ + (LayoutType::Title, "Title Slide"), + (LayoutType::TitleAndContent, "Title and Content"), + (LayoutType::TitleOnly, "Title Only"), + (LayoutType::TwoContent, "Two Content"), + (LayoutType::VerticalTitleAndText, "Vertical Title and Text"), + (LayoutType::TitleAndVerticalText, "Title and Vertical Text"), + (LayoutType::Blank, "Blank"), + ]; + let layouts = kinds + .into_iter() + .map(|(kind, name)| { + let mut l: Vec = if kind == LayoutType::Blank { vec![] } else { vec![title()] }; + l.extend(footers()); + Layout { id: LayoutId(id()), name: name.into(), kind, shapes: l, show_master_shapes: true, ..Default::default() } + }) + .collect(); + let master = Master { id: MasterId(id()), name: "Default".into(), shapes, layouts, ..Default::default() }; + (master, next.get()) + } +} + +fn import(bytes: &[u8]) -> Result { + crate::import(bytes, &AppDefaults) +} + +fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), crate::PptError> { + crate::import_checked(bytes, &AppDefaults) +} + +/// A version 3 compound file holding `streams` at its root. +fn build(streams: &[(&str, &[u8])]) -> Vec { + craft_cfb::write_streams(craft_cfb::Version::V3, streams).unwrap() +} + +/// With no default master of the caller's, a file's masters still read: the plain master has no +/// placeholders for the file's to place, and the slides keep their own. +#[test] +fn plain_defaults_still_read_the_file() { + let p = crate::import(&file(), &craft_pptx::Plain).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Hello\nWorld"); + assert!(p.layout(p.slides[0].layout).is_some()); +} + +fn le32(v: &[u32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +fn fopt(entries: &[(u16, u32)]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + atom(rt::FOPT, entries.len() as u16, &b) +} + +fn fsp(shape_type: u16, spid: u32, flags: u32) -> Vec { + atom(rt::FSP, shape_type, &le32(&[spid, flags])) +} + +/// A client anchor in master units: top, left, right, bottom. +fn anchor(t: i16, l: i16, r: i16, b: i16) -> Vec { + atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()) +} + +fn text_box(text_type: u32, text: &str, extra: &[Vec]) -> Vec { + let mut kids = vec![atom(rt::TEXT_HEADER, 0, &text_type.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16(text))]; + kids.extend_from_slice(extra); + container(rt::CLIENT_TEXTBOX, 0, &kids) +} + +fn placeholder(kind: u8) -> Vec { + container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, kind, 0, 0, 0])]) +} + +fn drawing(background: Option>, shapes: &[Vec]) -> Vec { + let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]); + let mut tree = vec![patriarch]; + tree.extend_from_slice(shapes); + let mut dg = vec![container(rt::SPGR_CONTAINER, 0, &tree)]; + dg.extend(background); + container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &dg)]) +} + +fn solid_background(rgb: u32) -> Vec { + container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0x400 | 0x800), fopt(&[(prop::FILL_COLOR, rgb), (prop::FILL_BOOLS, 0x0010_0010)])]) +} + +fn slide_atom(geom: u32, master_id: u32, flags: u16) -> Vec { + let mut b = geom.to_le_bytes().to_vec(); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(&le32(&[master_id, 0])); + b.extend_from_slice(&flags.to_le_bytes()); + b.extend_from_slice(&[0; 2]); + atom(rt::SLIDE_ATOM, 0, &b) +} + +/// A master text style with one level: a paragraph and a character exception. +fn master_style(instance: u16, pf: &[u8], cf: &[u8]) -> Vec { + atom(rt::TEXT_MASTER_STYLE, instance, &[&1u16.to_le_bytes()[..], pf, cf].concat()) +} + +const MASTER_ID: u32 = 0x8000_0001; +const SLIDE_ID: u32 = 256; +const TITLE_MASTER_ID: u32 = 0x8000_0002; + +fn master() -> Vec { + master_with(&[]) +} + +/// The test master with `shapes` after its decoration. +fn master_with(shapes: &[Vec]) -> Vec { + // Background, text, shadow, title, fill, accent, hyperlink, followed hyperlink. + let scheme: Vec = [0xFFFFFFu32, 0x000000, 0x808080, 0x000099, 0x00CC00, 0x0000FF, 0x00FF00, 0xFF0000] + .iter() + .flat_map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 0]) + .collect(); + let decoration = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 1026, 0xA00), + fopt(&[(prop::FILL_COLOR, 0x0800_0004), (prop::FILL_BOOLS, 0x0010_0010), (prop::LINE_BOOLS, 0x0008_0000)]), + anchor(0, 0, 5760, 400), + ], + ); + container( + rt::MAIN_MASTER, + 0, + &[ + slide_atom(1, 0, 0), + atom(rt::COLOR_SCHEME, 1, &scheme), + master_style(0, &pf_bytes(1, false), &cf_bytes(true, 0, 44, [0x11, 0x22, 0x33])), + master_style(1, &pf_bytes(0, true), &cf_bytes(false, 0, 28, [0, 0, 0])), + drawing(Some(solid_background(0x0000_00FF)), &[&[decoration][..], shapes].concat()), + ], + ) +} + +fn slide() -> Vec { + let title = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 2049, 0xA00), fopt(&[(prop::ANCHOR_TEXT, 1)]), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Hello\rWorld", &[])], + ); + let picture = container(rt::SP_CONTAINER, 0, &[fsp(75, 2050, 0xA00), fopt(&[(prop::PIB, 1)]), anchor(1600, 800, 2400, 2400)]); + let group = container( + rt::SPGR_CONTAINER, + 0, + &[ + container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &le32(&[0, 0, 1000, 1000])), fsp(0, 2051, 0x201), anchor(1600, 3000, 4000, 3200)]), + container( + rt::SP_CONTAINER, + 0, + &[ + fsp(3, 2052, 0x2), + fopt(&[(prop::FILL_COLOR, 0x0000_FF00), (prop::LINE_WIDTH, 25400)]), + atom(rt::CHILD_ANCHOR, 0, &le32(&[500, 0, 1000, 500])), + ], + ), + ], + ); + // "Page *": the star is a slide number field. The first four characters are bold. + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(2, false)); + for (n, bold) in [(4u32, true), (3, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(bold, 1, 12, [0xAB, 0xCD, 0xEF])); + } + let footer = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(202, 2053, 0xA00), + anchor(4000, 500, 2000, 4200), + text_box(4, "Page *", &[atom(rt::STYLE_TEXT_PROP, 0, &style), atom(rt::SLIDE_NUMBER_MC, 0, &5u32.to_le_bytes())]), + ], + ); + // A hidden slide (SlideShowSlideInfoAtom fHidden). + let mut info = vec![0u8; 16]; + info[10] = 0x4; + container( + rt::SLIDE, + 0, + &[slide_atom(1, MASTER_ID, 0x7), atom(rt::SLIDE_SHOW_SLIDE_INFO, 0, &info), drawing(None, &[title, picture, group, footer])], + ) +} + +fn notes() -> Vec { + let number = container(rt::SP_CONTAINER, 0, &[fsp(1, 3073, 0xA00), anchor(0, 0, 100, 100), placeholder(0x08), text_box(2, "*", &[])]); + let body = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 3074, 0xA00), anchor(100, 0, 4000, 4000), placeholder(0x0C), text_box(2, "Say hello\rThen wave", &[])], + ); + container(rt::NOTES, 0, &[atom(rt::NOTES_ATOM, 0, &le32(&[SLIDE_ID, 0])), drawing(None, &[number, body])]) +} + +fn png() -> Vec { + let mut buf = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut buf, image::ImageFormat::Png).unwrap(); + buf.into_inner() +} + +/// The streams of a one-slide presentation, with `edit` choosing the current user's header token. +fn streams(token: u32) -> (Vec, Vec, Vec) { + streams_listing(token, 1) +} + +/// The test document with its slide listed `times` times in the slide list. +fn streams_listing(token: u32, times: usize) -> (Vec, Vec, Vec) { + streams_of(token, times, slide(), None) +} + +/// The test document with `slide` as its slide and, when given, a title master (persist id 5, +/// slide id `TITLE_MASTER_ID`) listed after the main master. +fn streams_of(token: u32, times: usize, slide: Vec, title_master: Option>) -> (Vec, Vec, Vec) { + streams_with_outline(token, times, slide, title_master, &[]) +} + +/// As [`streams_of`], with `outline` (text blocks: header, characters, styles) following the +/// slide's persist atom in the slide list. +fn streams_with_outline(token: u32, times: usize, slide: Vec, title_master: Option>, outline: &[Vec]) -> (Vec, Vec, Vec) { + streams_with_document(token, times, master(), slide, title_master, outline, &[]) +} + +/// As [`streams_with_outline`], with `master` as the main master and `extra` records at the end of +/// the document container. +fn streams_with_document( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_master: Option>, + outline: &[Vec], + extra: &[Vec], +) -> (Vec, Vec, Vec) { + streams_with_title_masters(token, times, master, slide, title_master.into_iter().collect(), outline, extra) +} + +/// As [`streams_with_document`], with any number of title masters: persist ids 5 on, slide ids +/// `TITLE_MASTER_ID` on. +fn streams_with_title_masters( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_masters: Vec>, + outline: &[Vec], + extra: &[Vec], +) -> (Vec, Vec, Vec) { + streams_with_notes(token, times, master, slide, title_masters, outline, extra, notes(), &[]) +} + +/// As [`streams_with_title_masters`], with `notes` as the notes page (persist id 4) and +/// `notes_outline` following its persist atom in the notes list. +#[allow(clippy::too_many_arguments)] +fn streams_with_notes( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_masters: Vec>, + outline: &[Vec], + extra: &[Vec], + notes: Vec, + notes_outline: &[Vec], +) -> (Vec, Vec, Vec) { + let pictures = atom(0xF01E, 0x6E0, &[&[0u8; 17][..], &png()].concat()); + let mut fbse = vec![0u8; 36]; + fbse[0] = 6; + fbse[1] = 6; + fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes()); + let bstore = container(rt::BSTORE, 1, &[atom(rt::FBSE, 6, &fbse)]); + let mut font = utf16("Arial"); + font.resize(68, 0); + let mut wing = utf16("Wingdings"); + wing.resize(68, 0); + let mut doc_atom = le32(&[5760, 4320, 4320, 5760, 1, 2, 0, 0]); + doc_atom.extend_from_slice(&1u16.to_le_bytes()); + doc_atom.resize(40, 0); + let persist = |id: u32| { + atom( + rt::SLIDE_PERSIST_ATOM, + 0, + &le32(&[ + id, + 0, + 0, + if id == 2 { + MASTER_ID + } else if id >= 5 { + TITLE_MASTER_ID + (id - 5) + } else if id == 3 { + SLIDE_ID + } else { + SLIDE_ID + 1 + }, + 0, + ]), + ) + }; + let parts = [ + atom(rt::DOCUMENT_ATOM, 0, &doc_atom), + container(rt::ENVIRONMENT, 0, &[container(rt::FONT_COLLECTION, 0, &[atom(rt::FONT_ENTITY, 0, &font), atom(rt::FONT_ENTITY, 1, &wing)])]), + container(rt::DRAWING_GROUP, 0, &[container(rt::DGG_CONTAINER, 0, &[bstore])]), + container( + rt::SLIDE_LIST_WITH_TEXT, + 1, + &(0..=title_masters.len() as u32).map(|k| persist(if k == 0 { 2 } else { 4 + k })).collect::>(), + ), + container(rt::SLIDE_LIST_WITH_TEXT, 0, &[vec![persist(3); times], outline.to_vec()].concat()), + container(rt::SLIDE_LIST_WITH_TEXT, 2, &[vec![persist(4)], notes_outline.to_vec()].concat()), + ]; + let document = container(rt::DOCUMENT, 0, &[&parts[..], extra].concat()); + let mut stream = vec![]; + let mut offsets = vec![]; + let parts: Vec> = [document, master, slide, notes].into_iter().chain(title_masters).collect(); + for part in &parts { + offsets.push(stream.len() as u32); + stream.extend_from_slice(part); + } + let dir_at = stream.len() as u32; + let mut dir = vec![1u32 | ((parts.len() as u32) << 20)]; + dir.extend_from_slice(&offsets); + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&dir))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, 0, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let current_user = atom(rt::CURRENT_USER, 0, &le32(&[0x14, token, edit_at, 0, 0])); + (current_user, stream, pictures) +} + +fn file_with(token: u32) -> Vec { + let (cu, doc, pics) = streams(token); + build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]) +} + +fn file() -> Vec { + file_with(0xE391_C05F) +} + +#[test] +fn imports_a_presentation() { + let bytes = file(); + assert!(crate::sniff(&bytes)); + let p = import(&bytes).unwrap(); + assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0)); + assert_eq!(p.slides.len(), 1); + let s = &p.slides[0]; + assert!(s.hidden); + assert_eq!(s.notes.text(), "Say hello\nThen wave"); + check_title_placeholder(s); + check_picture(&p, s); + check_group(s); + check_text_box(s); + check_master(&p, s); +} + +fn check_title_placeholder(s: &Slide) { + // The title placeholder: its box, its text and the master's title style. + let title = &s.shapes[0]; + assert_eq!(title.ph_type(), Some(PhType::Title)); + let x = title.xfrm.unwrap(); + assert_eq!((x.x, x.y, x.w, x.h), (62.5, 50.0, 595.0, 100.0)); + assert_eq!(title.fill, Some(Fill::None)); + let t = title.text.as_ref().unwrap(); + assert_eq!(t.text(), "Hello\nWorld"); + assert_eq!(t.body.anchor, Some(craft_pptx::text::Anchor::Middle)); + let p0 = &t.paragraphs[0]; + assert_eq!(p0.props.align, Some(Align::Center)); + assert_eq!(p0.props.bullet, Some(Bullet::None)); + let r = &p0.runs[0].props; + assert_eq!((r.size, r.bold, r.font.as_deref()), (Some(44.0), Some(true), Some("Arial"))); + assert_eq!(r.fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0x33))))); + assert_eq!(s.title(), "Hello\nWorld"); +} + +fn check_picture(p: &Presentation, s: &Slide) { + // The picture. + let ShapeKind::Picture { fill } = &s.shapes[1].kind else { panic!("not a picture: {:?}", s.shapes[1].kind) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!(media.content_type, "image/png"); + assert!(media.data.starts_with(b"\x89PNG")); +} + +fn check_group(s: &Slide) { + // The group: children in slide points, the child space the group's own box. + let g = &s.shapes[2]; + let ShapeKind::Group { children, child } = &g.kind else { panic!("not a group") }; + let gx = g.xfrm.unwrap(); + assert_eq!((gx.x, gx.y, gx.w, gx.h), (375.0, 200.0, 125.0, 200.0)); + assert_eq!((child.x, child.y, child.w, child.h), (gx.x, gx.y, gx.w, gx.h)); + let e = children[0].xfrm.unwrap(); + assert_eq!((e.x, e.y, e.w, e.h, e.flip_h), (437.5, 200.0, 62.5, 100.0, false)); + assert_eq!(children[0].geom.preset_name(), Some("ellipse")); + assert_eq!(children[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xFF, 0))))); + assert_eq!(children[0].line.as_ref().and_then(|l| l.width), Some(2.0)); +} + +fn check_text_box(s: &Slide) { + // The text box: runs split at the format change, the star a slide number field. + let tb = s.shapes[3].text.as_ref().unwrap(); + let runs = &tb.paragraphs[0].runs; + assert_eq!(tb.paragraphs[0].props.align, Some(Align::Right)); + assert_eq!(runs.len(), 3, "{runs:?}"); + assert_eq!((runs[0].text.as_str(), runs[0].props.bold), ("Page", Some(true))); + assert_eq!((runs[1].text.as_str(), runs[1].props.bold), (" ", Some(false))); + assert_eq!(runs[2].kind, RunKind::Field { field: "slidenum".into() }); + assert_eq!(runs[0].props.font.as_deref(), Some("Wingdings")); + assert_eq!(s.shapes[3].fill, Some(Fill::None)); +} + +fn check_master(p: &Presentation, s: &Slide) { + // The master: its background, colours and decoration. + let m = &p.masters[0]; + assert_eq!(m.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))) })); + assert_eq!(m.theme.colors.get(craft_pptx::SchemeSlot::Accent1), Rgba::rgb(0, 0xCC, 0)); + assert!(m.shapes.iter().any(|sh| sh.ph.is_none() && sh.fill == Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xCC, 0)))))); + assert_eq!(m.title_style.level(0).and_then(|l| l.run.size), Some(44.0)); + assert!(p.layout(s.layout).is_some()); +} + +/// A slide listed many times is one slide: a hostile file can't make the importer convert one +/// big drawing again for every listing (180k listings of a 100k-shape slide fit in ~10 MB). +#[test] +fn a_slide_listed_again_is_imported_once() { + let (cu, doc, pics) = streams_listing(0xE391_C05F, 3); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + let p = import(&bytes).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!( + p.slides[0].notes.text(), + "Say hello +Then wave" + ); +} + +/// Two slide records with the same slide id share its notes page, which goes to the first only: +/// converting it again for each would copy its text into every one. +#[test] +fn a_notes_page_goes_to_one_slide() { + let again = container(rt::SLIDE_LIST_WITH_TEXT, 0, &[atom(rt::SLIDE_PERSIST_ATOM, 0, &le32(&[6, 0, 0, SLIDE_ID, 0]))]); + let (_, mut stream, pics) = streams_with_document(0xE391_C05F, 1, master(), slide(), None, &[], &[again]); + let first_edit = stream.len() as u32 - 36; + // Persist id 6: a second copy of the slide. + let copy_at = stream.len() as u32; + stream.extend_from_slice(&slide()); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[6 | (1 << 20), copy_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 7]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 2); + assert_eq!(p.slides[0].notes.text(), "Say hello\nThen wave"); + assert_eq!(p.slides[1].notes.text(), ""); +} + +/// As [`a_notes_page_goes_to_one_slide`], with the notes body's text in the notes list's outline +/// block: that block, too, is copied into the first slide's notes only. +#[test] +fn a_notes_pages_outline_text_goes_to_one_slide() { + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 3074, 0xA00), + anchor(100, 0, 4000, 4000), + placeholder(0x0C), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ); + let notes = container(rt::NOTES, 0, &[atom(rt::NOTES_ATOM, 0, &le32(&[SLIDE_ID, 0])), drawing(None, &[body])]); + let outline = [atom(rt::TEXT_HEADER, 0, &2u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("From the outline"))]; + let again = container(rt::SLIDE_LIST_WITH_TEXT, 0, &[atom(rt::SLIDE_PERSIST_ATOM, 0, &le32(&[6, 0, 0, SLIDE_ID, 0]))]); + let (_, mut stream, pics) = streams_with_notes(0xE391_C05F, 1, master(), slide(), vec![], &[], &[again], notes, &outline); + let first_edit = stream.len() as u32 - 36; + let copy_at = stream.len() as u32; + stream.extend_from_slice(&slide()); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[6 | (1 << 20), copy_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 7]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 2); + assert_eq!(p.slides[0].notes.text(), "From the outline"); + assert_eq!(p.slides[1].notes.text(), ""); +} + +/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to +/// scan the run starts from the beginning, so the cost grew with runs²: in a debug build these 640k +/// one-character runs (about 6 MB of file) took 75 s that way, and take about 2 s with binary search. +#[test] +fn many_character_runs_are_not_quadratic() { + const N: usize = 640_000; + let text: String = (0..N).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect(); + let mut style = vec![]; + style.extend_from_slice(&(N as u32 + 1).to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&0u32.to_le_bytes()); // a paragraph exception with no fields + for _ in 0..=N { + style.extend_from_slice(&1u32.to_le_bytes()); + style.extend_from_slice(&0u32.to_le_bytes()); // a character exception with no fields + } + let shape = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2060, 0xA00), anchor(0, 0, 1000, 1000), text_box(1, &text, &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[shape])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + let t = std::time::Instant::now(); + let p = import(&bytes).unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs; + assert_eq!(runs.iter().filter(|r| r.kind == RunKind::Break).count(), N / 2); +} + +/// A slide naming a master that doesn't exist falls back to the first main master, every time. The +/// fallback used to be the lowest index in a HashMap where a title master ties with its main +/// master, so the slide took the "Title Master" layout on some opens and not on others. +#[test] +fn a_slide_with_an_unknown_master_falls_back_the_same_way_every_time() { + let title_master = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[])]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, 0x8000_0099, 0x7), drawing(None, &[])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, Some(title_master)); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + for _ in 0..30 { + let p = import(&bytes).unwrap(); + assert_eq!(p.masters[0].layouts.iter().filter(|l| l.name == "Title Master").count(), 1, "the title master became a layout"); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_ne!(layout.name, "Title Master"); + } +} + +/// A damaged Current User record doesn't make a PowerPoint 97 file "too old": the newest edit is +/// found by scanning the document stream instead. A file with no edit record at all, behind a +/// token that isn't PowerPoint 97's, is still reported as too old. +#[test] +fn a_damaged_current_user_falls_back_to_the_scan() { + let (cu, doc, pics) = streams(0xE391_C05F); + let open = |cu: &[u8], doc: &[u8]| import(&build(&[("Current User", cu), ("PowerPoint Document", doc), ("Pictures", &pics)])); + // Truncated after the header and two bytes, so the token can't be read. + let truncated = atom(rt::CURRENT_USER, 0, &[0x14, 0]); + assert_eq!(open(&truncated, &doc).unwrap().slides.len(), 1); + // A corrupted token. + let corrupted = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xDEAD_BEEF, 0, 0, 0])); + assert_eq!(open(&corrupted, &doc).unwrap().slides.len(), 1); + assert!(matches!(open(&corrupted, &atom(rt::DOCUMENT_ATOM, 0, &[0; 40])), Err(crate::PptError::TooOld))); + // An intact token that points at no edit still gets the scan, and a stream without one is damaged. + assert!(matches!(open(&cu, &atom(rt::DOCUMENT_ATOM, 0, &[0; 40])), Err(crate::PptError::Damaged(_)))); +} + +/// Persist directories nested inside one another are not each read to the end of the stream. A chain +/// of edits, each naming a directory header 8 bytes after the last one, made every edit reparse the +/// rest of the stream (4095 edits × the filler): about 48 s for this 64 MiB stream in a debug build. +/// Within the shared budget it takes milliseconds, and the file is reported as damaged. +#[test] +fn nested_persist_directories_are_read_within_the_stream() { + const FILLER: usize = 1 << 26; + const EDITS: u32 = 4095; + let (_, mut stream, _) = streams(0xE391_C05F); + let mut prev = stream.len() as u32 - 36; // the test document's own UserEditAtom (8 + 28 bytes) + let base = stream.len() as u32; + for _ in 0..EDITS { + // A PersistDirectoryAtom header whose length runs past the end (clipped to the stream). + stream.extend_from_slice(&0u16.to_le_bytes()); + stream.extend_from_slice(&rt::PERSIST_DIRECTORY.to_le_bytes()); + stream.extend_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + } + stream.resize(stream.len() + FILLER, 0); + for k in 0..EDITS { + let at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, prev, base + 8 * k, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + prev = at; + } + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, prev, 0, 0])); + // The streams are read directly: the test file builder can't hold a stream this size. + let t = std::time::Instant::now(); + let r = crate::doc::read(&cu, &stream); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + assert!(matches!(r, Err(crate::PptError::Damaged(_)))); +} + +#[test] +fn an_encrypted_presentation_says_so() { + assert!(matches!(import(&file_with(0xF3D1_C4DF)), Err(crate::PptError::Encrypted))); +} + +#[test] +fn other_files_are_not_ppt() { + assert!(!crate::sniff(b"PK\x03\x04")); + assert!(!crate::sniff(&build(&[("WordDocument", b"x")]))); + assert!(matches!(import(b"not a presentation"), Err(crate::PptError::NotPpt))); + assert!(matches!(import(&build(&[("Workbook", b"x")])), Err(crate::PptError::NotPpt))); +} + +/// Damaged input never panics, loops or allocates without bound: every 4-byte word of the +/// document stream set to hostile values, and truncations of it. +#[test] +fn hostile_documents_never_panic() { + let (cu, doc, pics) = streams(0xE391_C05F); + for at in (0..doc.len().saturating_sub(4)).step_by(3) { + for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF, 0x0000_FFFF, 0xF00F_000F] { + let mut d = doc.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let f = build(&[("Current User", &cu), ("PowerPoint Document", &d), ("Pictures", &pics)]); + let _ = import(&f); + } + } + for cut in (0..doc.len()).step_by(7) { + let f = build(&[("Current User", &cu), ("PowerPoint Document", &doc[..cut]), ("Pictures", &pics[..cut.min(pics.len())])]); + let _ = import(&f); + } +} + +/// A slide shape that inherits from a master shape (`hspMaster`) takes it from its own master. +/// Master shapes used to be remembered by shape id alone, so a title master reusing the main +/// master's shape id (here 1026, red instead of the scheme's green) replaced it for every slide. +#[test] +fn a_master_shape_id_is_looked_up_in_the_slides_own_master() { + let red = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 1026, 0xA00), fopt(&[(prop::FILL_COLOR, 0x0000_00FF), (prop::FILL_BOOLS, 0x0010_0010)]), anchor(0, 0, 100, 100)], + ); + let title_master = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[red])]); + let inheriting = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), fopt(&[(prop::HSP_MASTER, 1026)]), anchor(0, 0, 100, 100)]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[inheriting])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, Some(title_master)); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides[0].shapes[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xCC, 0))))); +} + +/// A run's shadow bit (TextCFException fontStyle bit 4) gives the run a shadow in the colour +/// scheme's shadow colour (grey in the test scheme). It used to be read and then dropped. +#[test] +fn a_shadowed_run_keeps_its_shadow() { + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + for (n, shadow) in [(3u32, true), (4, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&0x10u32.to_le_bytes()); // mask: shadow + style.extend_from_slice(&(if shadow { 0x10u16 } else { 0 }).to_le_bytes()); + } + let tb = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2049, 0xA00), anchor(0, 0, 1000, 1000), text_box(4, "Hi you", &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[tb])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs; + assert_eq!(runs[0].text, "Hi "); + let shadow = runs[0].props.shadow.as_ref().expect("the first run is shadowed"); + assert_eq!(shadow.color, craft_pptx::ColorRef::rgb(Rgba::rgb(0x80, 0x80, 0x80))); + assert!(runs[1].props.shadow.is_none()); +} + +/// `tests/fixtures/old-talk.pps`: a one-slide `.pps` built here from records, for applications' +/// tests that need real 97–2003 bytes (DeckCraft's show-on-open test). Run this test with +/// `CRAFT_WRITE_PPT_FIXTURE=1` to rebuild the file after changing the builders. +#[test] +fn the_pps_fixture_is_a_built_presentation() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/old-talk.pps"); + if std::env::var_os("CRAFT_WRITE_PPT_FIXTURE").is_some() { + let title = + container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Old talk", &[])]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + std::fs::write(path, build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + } + let p = import(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(p.slides.len(), 1); + assert!(!p.slides[0].hidden); + let title = p.slides[0].shapes[0].text.as_ref().unwrap(); + assert_eq!(title.paragraphs[0].runs[0].text, "Old talk"); +} + +/// A placeholder whose client text box holds only an `OutlineTextRefAtom` takes its text and +/// formatting from that block of the slide list ([MS-PPT] OfficeArtClientTextbox allows the +/// reference alone). A text box that also has a header but no characters falls back the same way. +#[test] +fn placeholder_text_can_come_from_the_slide_list() { + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); // the text and its closing paragraph mark + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(1, false)); + for (n, bold) in [(2u32, true), (5, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(bold, 0, 40, [0x12, 0x34, 0x56])); + } + let outline = [ + atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &utf16("Hi all")), + atom(rt::STYLE_TEXT_PROP, 0, &style), + atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &utf16("Second block")), + ]; + let reference = |n: u32| atom(rt::OUTLINE_TEXT_REF, 0, &n.to_le_bytes()); + let only_ref = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), container(rt::CLIENT_TEXTBOX, 0, &[reference(0)])], + ); + let header_and_ref = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2050, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), reference(1)]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[only_ref, header_and_ref])]); + let (cu, doc, pics) = streams_with_outline(0xE391_C05F, 1, slide, None, &outline); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let shapes = &p.slides[0].shapes; + let title = shapes[0].text.as_ref().expect("the title has the outline text"); + let runs = &title.paragraphs[0].runs; + assert_eq!((runs[0].text.as_str(), runs[0].props.bold), ("Hi", Some(true))); + assert_eq!((runs[1].text.as_str(), runs[1].props.bold), (" all", Some(false))); + assert_eq!(runs[0].props.size, Some(40.0)); + assert_eq!(title.paragraphs[0].props.align, Some(Align::Center)); + let body = shapes[1].text.as_ref().expect("the body has the second block"); + assert_eq!(body.paragraphs[0].runs[0].text, "Second block"); +} + +/// The newest edit wins: a later edit's persist directory that gives the slide's persist id a new +/// slide replaces the old one. +#[test] +fn a_later_edit_replaces_a_slide() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let first_edit = stream.len() as u32 - 36; // the test document's UserEditAtom (8 + 28 bytes) + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Edited", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + // Persist id 3 (the slide) only. + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[3 | (1 << 20), slide_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs[0].text, "Edited"); + // The master, from the first edit's directory, is still there. + assert_eq!(p.masters.len(), 1); +} + +/// An edit whose "previous edit" points back at itself cuts the older edits off the chain, and +/// with them the document, master and notes (storytold/deckcraft#1137 review: such a file opened as an empty deck). +/// Every edit in the stream is read instead, the newest still winning. +#[test] +fn a_broken_edit_chain_is_recovered_from_every_edit() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Edited", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[3 | (1 << 20), slide_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, edit_at, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let (p, lost) = import_checked(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs[0].text, "Edited"); + assert_eq!(p.masters.len(), 1); + assert!(lost.is_empty(), "{lost:?}"); +} + +/// A slide the list names but whose object is gone is reported as lost, so an application can +/// say so instead of opening a deck that silently misses it. +#[test] +fn a_slide_without_its_object_is_reported_lost() { + let (cu, mut stream, pics) = streams(0xE391_C05F); + // The persist directory (ids 1–4: document, master, slide, notes) ends just before the + // 36-byte edit; point the slide's entry past the end of the stream. + let slide_entry = stream.len() - 36 - 8; + stream[slide_entry..slide_entry + 4].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)]); + let (p, lost) = import_checked(&bytes).unwrap(); + assert!(p.slides.is_empty()); + assert_eq!(lost, vec![format!("slide {SLIDE_ID}")]); +} + +/// Two more signs of an encrypted file besides the Current User token: an edit record long enough +/// to hold `encryptSessionPersistIdRef`, and a `CryptSession` object in the persist directory. +#[test] +fn encryption_is_found_in_the_edit_and_the_persist_directory() { + let open = |doc: &[u8], pics: &[u8]| { + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, doc.len() as u32 - 36, 0, 0])); + import(&build(&[("Current User", &cu), ("PowerPoint Document", doc), ("Pictures", pics)])) + }; + let (_, stream, pics) = streams(0xE391_C05F); + assert!(open(&stream, &pics).is_ok()); + // The edit record with a fifth reference: 28 bytes become 32. The Current User points at the + // new last record, 40 bytes from the end. + let mut long_edit = stream.clone(); + let edit_at = long_edit.len() - 36; + long_edit.truncate(edit_at); + let mut edit = le32(&[0, 0x0300_03F4, 0, 0, 1, 5]); + edit[12..16].copy_from_slice(&stream[edit_at + 8 + 12..edit_at + 8 + 16]); // offsetPersistDirectory + edit.extend_from_slice(&[0; 4]); + edit.extend_from_slice(&6u32.to_le_bytes()); // encryptSessionPersistIdRef + long_edit.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at as u32, 0, 0])); + let r = import(&build(&[("Current User", &cu), ("PowerPoint Document", &long_edit), ("Pictures", &pics)])); + assert!(matches!(r, Err(crate::PptError::Encrypted)), "{:?}", r.err()); + // A CryptSession container given a persist id by a later edit. + let mut crypt = stream.clone(); + let first_edit = crypt.len() as u32 - 36; + let session_at = crypt.len() as u32; + crypt.extend_from_slice(&container(rt::CRYPT_SESSION, 0, &[atom(0x0FFF, 0, &[0; 8])])); + let dir_at = crypt.len() as u32; + crypt.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[9 | (1 << 20), session_at]))); + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 9]); + edit.extend_from_slice(&[0; 4]); + crypt.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + assert!(matches!(open(&crypt, &pics), Err(crate::PptError::Encrypted))); +} + +/// A colour scheme record whose fill colour (index 4) is `fill`, the rest as the test master's. +fn scheme_with_fill(fill: [u8; 3]) -> Vec { + let mut colors: Vec = [0xFFFFFFu32, 0x000000, 0x808080, 0x000099, 0, 0x0000FF, 0x00FF00, 0xFF0000] + .iter() + .flat_map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 0]) + .collect(); + colors[16..19].copy_from_slice(&fill); + atom(rt::COLOR_SCHEME, 1, &colors) +} + +/// A shape filled with the scheme's fill colour. +fn scheme_filled(spid: u32) -> Vec { + container( + rt::SP_CONTAINER, + 0, + &[fsp(1, spid, 0xA00), fopt(&[(prop::FILL_COLOR, 0x0800_0004), (prop::FILL_BOOLS, 0x0010_0010)]), anchor(0, 0, 100, 100)], + ) +} + +/// A title master becomes a layout of its main master, with its own background and shapes, and +/// without the master's shapes when it doesn't follow them. A slide of the title master uses that +/// layout. A slide that follows nothing keeps its own background and scheme and hides the +/// master's shapes. +#[test] +fn title_masters_and_slides_that_dont_follow_the_master() { + let title_master = + container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x0), drawing(Some(solid_background(0x0000_FF00)), &[scheme_filled(3000)])]); + let on_title = container(rt::SLIDE, 0, &[slide_atom(0, TITLE_MASTER_ID, 0x7), drawing(None, &[])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, on_title, Some(title_master)); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_eq!(layout.name, "Title Master"); + assert_eq!(layout.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xFF, 0))) })); + assert!(!layout.show_master_shapes); + assert!(layout.shapes.iter().any(|sh| sh.ph.is_none()), "the title master's own shape"); + assert_eq!(p.slides[0].background, None, "the slide follows its master's background"); + + let alone = container( + rt::SLIDE, + 0, + &[slide_atom(1, MASTER_ID, 0x0), scheme_with_fill([0x11, 0x22, 0xCC]), drawing(Some(solid_background(0x0000_00FF)), &[scheme_filled(2049)])], + ); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, alone, None); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let s = &p.slides[0]; + assert_eq!(s.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))) })); + assert!(!s.show_master_shapes); + assert_eq!(s.shapes[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0xCC)))), "the slide's own scheme"); +} + +fn open_streams((cu, doc, pics): (Vec, Vec, Vec)) -> Presentation { + import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap() +} + +/// A picture frame that says nothing about its fill or line draws neither (storytold/deckcraft#1137 review): the +/// drawing defaults' fill would cover a picture's transparent parts, or an OLE chart's preview. +#[test] +fn a_picture_frame_has_no_fill_or_line_of_its_own() { + let p = import(&file()).unwrap(); + let picture = &p.slides[0].shapes[1]; + assert!(matches!(picture.kind, ShapeKind::Picture { .. })); + assert_eq!(picture.fill, Some(Fill::None)); + assert_eq!(picture.line.as_ref().map(|l| l.fill.clone()), Some(Some(Fill::None))); +} + +/// A picture fill whose blip is held in the shape's own `fillBlip` property (complex, with fBid), +/// as table cells with a picture have it (storytold/deckcraft#1137 review), shows that picture. +#[test] +fn a_picture_held_in_the_fill_property_is_read() { + let blip = atom(0xF01E, 0x6E0, &[&[0u8; 17][..], &png()].concat()); + let mut entries = vec![]; + for (id, op) in [(prop::FILL_TYPE, 3u32), (0xC000 | prop::FILL_BLIP, blip.len() as u32), (prop::FILL_BOOLS, 0x0010_0010)] { + entries.extend_from_slice(&id.to_le_bytes()); + entries.extend_from_slice(&op.to_le_bytes()); + } + entries.extend_from_slice(&blip); + let cell = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), atom(rt::FOPT, 3, &entries), anchor(400, 500, 2000, 1200)]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[cell])]); + let p = open_streams(streams_of(0xE391_C05F, 1, slide, None)); + let Some(Fill::Picture(fill)) = &p.slides[0].shapes[0].fill else { panic!("{:?}", p.slides[0].shapes[0].fill) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert!(media.data.starts_with(b"\x89PNG")); +} + +/// The headers and footers the document sets for its slides (storytold/deckcraft#1137 review: the date, footer and +/// slide number were missing) become the slide's footer placeholders, placed and styled as the +/// master's are on every layout. +#[test] +fn headers_and_footers_become_footer_placeholders() { + let cstring = |instance: u16, s: &str| atom(rt::CSTRING, instance, &utf16(s)); + // fHasDate | fHasUserDate | fHasSlideNumber | fHasFooter. The footer string ends in a NUL, as + // some writers add one: the text stops there. + let flags: u16 = 0x01 | 0x04 | 0x08 | 0x20; + let hf = container( + rt::HEADERS_FOOTERS, + 3, + &[ + atom(rt::HEADERS_FOOTERS_ATOM, 0, &[&0u16.to_le_bytes()[..], &flags.to_le_bytes()].concat()), + cstring(0, "26 May 2004"), + cstring(2, "Workshop\0"), + ], + ); + // The master's slide number placeholder: bottom right, right-aligned 10 pt text. + let mut style = vec![]; + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(2, false)); + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&cf_bytes(false, 0, 10, [1, 2, 3])); + let number = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 1030, 0xA00), anchor(4000, 5000, 5700, 4300), placeholder(0x08), text_box(4, "*", &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master_with(&[number]), slide(), None, &[], &[hf])); + let shapes = &p.slides[0].shapes; + let of = |k: PhType| shapes.iter().find(|s| s.ph_type() == Some(k)).unwrap_or_else(|| panic!("no {k:?}")); + assert_eq!(of(PhType::Date).text.as_ref().unwrap().text(), "26 May 2004"); + assert_eq!(of(PhType::Footer).text.as_ref().unwrap().text(), "Workshop"); + let runs = &of(PhType::SlideNum).text.as_ref().unwrap().paragraphs[0].runs; + assert!(matches!(&runs[0].kind, RunKind::Field { field } if field == "slidenum")); + assert!(p.header_footer.slide_number && p.header_footer.footer && p.header_footer.date); + // Every layout's slide number sits where the master's does, with its look. + let master = &p.masters[0]; + for l in &master.layouts { + let n = l.shapes.iter().find(|s| s.ph_type() == Some(PhType::SlideNum)).unwrap_or_else(|| panic!("no slide number on {}", l.name)); + let x = n.xfrm.unwrap(); + assert_eq!((x.x, x.y), (5000.0 / 8.0, 4000.0 / 8.0), "{}", l.name); + let level = n.text.as_ref().unwrap().list_style.level(0).unwrap(); + assert_eq!((level.para.align, level.run.size), (Some(Align::Right), Some(10.0))); + } +} + +/// Numbered paragraphs (storytold/deckcraft#1137 review: drawn with the bullet character) take their numbering from +/// the document's `___PPT9` tag: the slide's outline block of that text type, and the entry the +/// run's `pp9rt` names. The tag's name ends in a NUL here, as some writers add one. +#[test] +fn outline_numbering_from_the_ppt9_tag() { + // Entry 0: nothing. Entry 1: numbered, "1." (scheme 3), from 4. + let mut prop9 = vec![0u8; 12]; + prop9.extend_from_slice(&0x0300_0000u32.to_le_bytes()); + prop9.extend_from_slice(&1u16.to_le_bytes()); + prop9.extend_from_slice(&3u16.to_le_bytes()); + prop9.extend_from_slice(&4i16.to_le_bytes()); + prop9.extend_from_slice(&[0; 8]); + let tag_data = [atom(rt::OUTLINE_TEXT_PROPS_HEADER, 1, &le32(&[SLIDE_ID, 1])), atom(rt::STYLE_TEXT_PROP9, 0, &prop9)]; + let tag = container( + rt::PROG_BINARY_TAG, + 0, + &[atom(rt::CSTRING, 0, &utf16("___PPT9\0")), atom(rt::BINARY_TAG_DATA, 0, &container(rt::OUTLINE_TEXT_PROPS9, 0, &tag_data))], + ); + let list = container(rt::LIST, 0, &[container(rt::PROG_TAGS, 0, &[tag])]); + // Two bulleted paragraphs: the second's run names entry 1 (pp9rt in fontStyle bits 10–13). + let pp9rt = |i: u16| [&0x0000_0400u32.to_le_bytes()[..], &(i << 10).to_le_bytes()].concat(); + let mut style = vec![]; + style.extend_from_slice(&8u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, true)); + for (n, i) in [(4u32, 0u16), (4, 1)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&pp9rt(i)); + } + let outline = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("One\rTwo")), atom(rt::STYLE_TEXT_PROP, 0, &style)]; + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2049, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[body])]); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master(), slide, None, &outline, &[list])); + let paras = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs; + assert!(matches!(paras[0].props.bullet, Some(Bullet::Char { .. })), "{:?}", paras[0].props.bullet); + assert_eq!(paras[1].props.bullet, Some(Bullet::AutoNum { scheme: "arabicPeriod".into(), start_at: 4 })); +} + +/// An outline block is one shape's text. A second shape pointing at the same block keeps its own +/// (here none), so a hostile file can't copy one big block into every shape of the slide. +#[test] +fn an_outline_block_is_used_by_one_shape() { + let outline = [atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("Shared"))]; + let referring = |spid: u32| { + container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, spid, 0xA00), + anchor(400, 500, 5260, 1200), + placeholder(0x0D), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ) + }; + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[referring(2049), referring(2050)])]); + let p = open_streams(streams_with_outline(0xE391_C05F, 1, slide, None, &outline)); + let texts: Vec = p.slides[0].shapes.iter().map(|s| s.text.as_ref().unwrap().text()).collect(); + assert_eq!(texts, ["Shared", ""]); +} + +fn open_plain((cu, doc, pics): (Vec, Vec, Vec)) -> Presentation { + crate::import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]), &craft_pptx::Plain).unwrap() +} + +/// A footer-only `HeadersFootersContainer` of `instance` with `footer` as its text. +fn footer_record(instance: u16, footer: &str) -> Vec { + container( + rt::HEADERS_FOOTERS, + instance, + &[atom(rt::HEADERS_FOOTERS_ATOM, 0, &[&0u16.to_le_bytes()[..], &0x20u16.to_le_bytes()].concat()), atom(rt::CSTRING, 2, &utf16(footer))], + ) +} + +/// A slide's own headers and footers (`PerSlideHeadersFootersContainer`, instance 0) win over the +/// document's for every slide (instance 3). Only the document's used to be looked for. +#[test] +fn a_slides_own_footer_wins_over_the_documents() { + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[]), footer_record(0, "This slide")]); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master(), slide, None, &[], &[footer_record(3, "Every slide")])); + let footer = p.slides[0].shapes.iter().find(|s| s.ph_type() == Some(PhType::Footer)).expect("a footer"); + assert_eq!(footer.text.as_ref().unwrap().text(), "This slide"); + assert_eq!(p.header_footer.footer_text, "Every slide"); +} + +/// A text box that points at an outline block keeps its own `TextRulerAtom`: the margin it sets +/// (one inch at level 1) wins over the block's. It used to be dropped with the reference. +#[test] +fn a_text_boxs_own_ruler_applies_to_its_outline_text() { + let outline = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("Indented"))]; + let ruler = atom(rt::TEXT_RULER, 0, &[&(1u32 << 3).to_le_bytes()[..], &576u16.to_le_bytes()].concat()); + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2049, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes()), ruler]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[body])]); + let p = open_streams(streams_with_outline(0xE391_C05F, 1, slide, None, &outline)); + let t = p.slides[0].shapes[0].text.as_ref().unwrap(); + assert_eq!(t.text(), "Indented"); + assert_eq!(t.paragraphs[0].props.margin_left, Some(72.0)); +} + +/// A slide list entry whose object isn't a slide (here the notes page) is a lost slide, not a +/// slide silently left out. +#[test] +fn a_slide_entry_naming_another_object_is_reported_lost() { + let (cu, mut stream, pics) = streams(0xE391_C05F); + // The persist directory's last two entries (the slide's, then the notes page's) end just + // before the 36-byte edit: point the slide's at the notes page. + let end = stream.len() - 36; + let notes_at: [u8; 4] = stream[end - 4..end].try_into().unwrap(); + stream[end - 8..end - 4].copy_from_slice(¬es_at); + let (p, lost) = import_checked(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert!(p.slides.is_empty()); + assert_eq!(lost, vec![format!("slide {SLIDE_ID}")]); +} + +/// A title master with a centred title and a subtitle placeholder, `extra` shapes after them. +fn title_master_with(extra: &[Vec]) -> Vec { + let ph = + |spid: u32, kind: u8, a: [i16; 4]| container(rt::SP_CONTAINER, 0, &[fsp(1, spid, 0xA00), anchor(a[0], a[1], a[2], a[3]), placeholder(kind)]); + let shapes = [vec![ph(3001, 0x0F, [1000, 600, 5160, 2000]), ph(3002, 0x10, [2200, 1200, 4540, 3200])], extra.to_vec()].concat(); + container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &shapes)]) +} + +/// The first "Title Master" layout of `p`'s first master. +fn title_layout(p: &Presentation) -> &Layout { + p.masters[0].layouts.iter().find(|l| l.name == "Title Master").expect("the title master's layout") +} + +/// A title master's placeholders place its layout's, as a main master's place the master's: the +/// title takes its box, and the subtitle the default title layout lacks is added. With the plain +/// defaults (no placeholders at all) both are added. +#[test] +fn a_title_masters_placeholders_place_its_layouts() { + let boxes = |l: &Layout| { + let at = |f: &dyn Fn(PhType) -> bool| { + let x = l.shapes.iter().find(|s| s.ph_type().is_some_and(f)).and_then(|s| s.xfrm).unwrap_or_else(|| panic!("{:?}", l.shapes)); + (x.x, x.y, x.w, x.h) + }; + (at(&|t| matches!(t, PhType::Title | PhType::CtrTitle)), at(&|t| t == PhType::SubTitle)) + }; + let expected = ((75.0, 125.0, 570.0, 125.0), (150.0, 275.0, 417.5, 125.0)); + let p = open_streams(streams_of(0xE391_C05F, 1, slide(), Some(title_master_with(&[])))); + assert_eq!(boxes(title_layout(&p)), expected); + let p = open_plain(streams_of(0xE391_C05F, 1, slide(), Some(title_master_with(&[])))); + assert_eq!(boxes(title_layout(&p)), expected); +} + +/// A second title master's layout takes nothing from the first title master's layout: not its own +/// shapes, and not its placeholders or their boxes. With the plain defaults (no title layout of +/// theirs) it holds only its own placeholder, where it puts it. +#[test] +fn a_second_title_master_doesnt_copy_the_firsts_shapes() { + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 4001, 0xA00), anchor(200, 400, 2000, 800), placeholder(0x0F)]); + let second = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[title])]); + let p = + open_plain(streams_with_title_masters(0xE391_C05F, 1, master(), slide(), vec![title_master_with(&[scheme_filled(3003)]), second], &[], &[])); + let layouts: Vec<&Layout> = p.masters[0].layouts.iter().filter(|l| l.name == "Title Master").collect(); + assert_eq!(layouts.len(), 2); + assert_eq!(layouts[0].shapes.iter().filter(|s| s.ph.is_none()).count(), 1); + assert_eq!(layouts[1].shapes.len(), 1, "only its own placeholder: {:?}", layouts[1].shapes); + let x = layouts[1].shapes[0].xfrm.unwrap(); + assert_eq!((layouts[1].shapes[0].ph_type(), x.x, x.y, x.w, x.h), (Some(PhType::CtrTitle), 50.0, 25.0, 200.0, 75.0)); +} + +/// A title slide of the main master takes an ordinary layout, not the one made for a title +/// master: that one is for the slides that name the title master. +#[test] +fn a_title_masters_layout_is_only_for_its_own_slides() { + let on_main = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[])]); + let p = open_plain(streams_of(0xE391_C05F, 1, on_main, Some(title_master_with(&[])))); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_eq!(layout.name, "Blank"); +} + +/// When the edit chain is broken and the stream holds more edits than are read, the newest are the +/// ones read: here the newest edit replaces the slide, behind 4095 edits with no directory. +#[test] +fn a_broken_chain_reads_the_newest_edits() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let first_edit = stream.len() - 36; + let offsets: Vec = + (0..4).map(|i| u32::from_le_bytes(stream[first_edit - 16 + 4 * i..first_edit - 12 + 4 * i].try_into().unwrap())).collect(); + // Edits that point at themselves and name the document as their directory. + let junk_at = stream.len() as u32; + for _ in 0..4095 { + let at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, at, 0, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + } + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Newest", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[1 | (4 << 20), offsets[0], offsets[1], slide_at, offsets[3]]))); + let mut edit = le32(&[0, 0x0300_03F4, first_edit as u32, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, junk_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Newest"); +} diff --git a/crates/ppt-binary/src/text.rs b/crates/ppt-binary/src/text.rs new file mode 100644 index 000000000..5c2be1e31 --- /dev/null +++ b/crates/ppt-binary/src/text.rs @@ -0,0 +1,755 @@ +//! Text in `.ppt` ([MS-PPT] §2.9): characters in a `TextCharsAtom` (UTF-16) or `TextBytesAtom` +//! (Latin-1), formatting as runs of paragraph exceptions (`TextPFException`) and character +//! exceptions (`TextCFException`) over the master's per-level text styles. + +use crate::doc::rt; +use crate::record::{Cursor, Rec}; + +/// A colour as text formatting stores it: an RGB value or an index into the colour scheme. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextColor { + Rgb(u8, u8, u8), + Scheme(u8), +} + +fn color_index(c: &mut Cursor) -> Option> { + let (r, g, b, i) = (c.u8()?, c.u8()?, c.u8()?, c.u8()?); + Some(match i { + 0xFE => Some(TextColor::Rgb(r, g, b)), + 0..=7 => Some(TextColor::Scheme(i)), + _ => None, + }) +} + +/// Paragraph formatting; `None` fields are not set at this level. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Pf { + pub has_bullet: Option, + pub bullet_has_font: Option, + pub bullet_has_color: Option, + pub bullet_has_size: Option, + pub bullet_char: Option, + pub bullet_font: Option, + /// Positive: percent of the text size; negative: absolute size in points. + pub bullet_size: Option, + pub bullet_color: Option, + /// 0 left, 1 centre, 2 right, 3 justify, 4 distributed, 5 Thai distributed, 6 justify low. + pub align: Option, + /// Positive: percent of a line; negative: master units (−8 per point). + pub line_spacing: Option, + pub space_before: Option, + pub space_after: Option, + /// Master units from the text box's left edge. + pub left_margin: Option, + pub indent: Option, + pub default_tab: Option, + pub tabs: Option>, +} + +impl Pf { + /// Overlay `o`'s set fields on this one. + pub fn apply(&mut self, o: &Pf) { + macro_rules! over { + ($($f:ident),*) => { $( if o.$f.is_some() { self.$f.clone_from(&o.$f); } )* }; + } + over!( + has_bullet, + bullet_has_font, + bullet_has_color, + bullet_has_size, + bullet_char, + bullet_font, + bullet_size, + bullet_color, + align, + line_spacing, + space_before, + space_after, + left_margin, + indent, + default_tab, + tabs + ); + } +} + +/// Character formatting; `None` fields are not set at this level. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Cf { + pub bold: Option, + pub italic: Option, + pub underline: Option, + pub shadow: Option, + pub font: Option, + pub ea_font: Option, + pub symbol_font: Option, + /// Points. + pub size: Option, + pub color: Option, + /// Superscript (positive) or subscript (negative) offset, percent of the size. + pub position: Option, + /// `pp9rt`: the index of the paragraph's PowerPoint 2000 formatting (numbering) in the text's + /// `StyleTextProp9Atom`. + pub pp9rt: Option, +} + +impl Cf { + pub fn apply(&mut self, o: &Cf) { + macro_rules! over { + ($($f:ident),*) => { $( if o.$f.is_some() { self.$f = o.$f; } )* }; + } + over!(bold, italic, underline, shadow, font, ea_font, symbol_font, size, color, position, pp9rt); + } +} + +fn bit(m: u32, b: u32) -> bool { + m & (1 << b) != 0 +} + +/// A `TextPFException`. +pub fn read_pf(c: &mut Cursor) -> Option { + let m = c.u32()?; + let mut pf = Pf::default(); + if m & 0xF != 0 { + let flags = c.u16()?; + for (b, slot) in [(0, &mut pf.has_bullet), (1, &mut pf.bullet_has_font), (2, &mut pf.bullet_has_color), (3, &mut pf.bullet_has_size)] { + if bit(m, b) { + *slot = Some(flags & (1 << b) != 0); + } + } + } + if bit(m, 7) { + pf.bullet_char = Some(c.u16()?); + } + if bit(m, 4) { + pf.bullet_font = Some(c.u16()?); + } + if bit(m, 6) { + pf.bullet_size = Some(c.i16()?); + } + if bit(m, 5) { + pf.bullet_color = color_index(c)?; + } + if bit(m, 11) { + pf.align = Some(c.u16()?); + } + if bit(m, 12) { + pf.line_spacing = Some(c.i16()?); + } + if bit(m, 13) { + pf.space_before = Some(c.i16()?); + } + if bit(m, 14) { + pf.space_after = Some(c.i16()?); + } + if bit(m, 8) { + pf.left_margin = Some(c.u16()?); + } + if bit(m, 10) { + pf.indent = Some(c.u16()?); + } + if bit(m, 15) { + pf.default_tab = Some(c.u16()?); + } + if bit(m, 20) { + pf.tabs = Some(read_tabs(c)?); + } + if bit(m, 16) { + c.u16()?; // fontAlign + } + if m & (0x7 << 17) != 0 { + c.u16()?; // wrapFlags + } + if bit(m, 21) { + c.u16()?; // textDirection + } + Some(pf) +} + +/// Tab stops kept per paragraph exception or ruler. Every entry is still read past, so the fields +/// after the list stay aligned; the rest are dropped, since each paragraph copies the list. +const MAX_TABS: usize = 64; + +fn read_tabs(c: &mut Cursor) -> Option> { + let n = c.u16()?; + let mut v = Vec::with_capacity(usize::from(n).min(MAX_TABS)); + for _ in 0..n { + let tab = (c.i16()?, c.u16()?); + if v.len() < MAX_TABS { + v.push(tab); + } + } + Some(v) +} + +/// A `TextCFException`. +pub fn read_cf(c: &mut Cursor) -> Option { + let m = c.u32()?; + let mut cf = Cf::default(); + // fontStyle is present when any of bold, italic, underline, shadow, fehint, kumi, emboss or + // fHasStyle is in the mask. + if m & 0x3EB7 != 0 { + let s = c.u16()?; + // Emboss (bit 9) has no counterpart in the model; docs/gaps.md lists it. + for (b, slot) in [(0, &mut cf.bold), (1, &mut cf.italic), (2, &mut cf.underline), (4, &mut cf.shadow)] { + if bit(m, b) { + *slot = Some(s & (1 << b) != 0); + } + } + // fHasStyle (bits 10–13) says pp9rt, the same four bits of fontStyle, is given. + if m & 0x3C00 != 0 { + cf.pp9rt = Some(((s >> 10) & 0xF) as u8); + } + } + if bit(m, 16) { + cf.font = Some(c.u16()?); + } + if bit(m, 21) { + cf.ea_font = Some(c.u16()?); + } + if bit(m, 22) { + c.u16()?; // ansiFontRef + } + if bit(m, 23) { + cf.symbol_font = Some(c.u16()?); + } + if bit(m, 17) { + cf.size = Some(c.u16()?); + } + if bit(m, 18) { + cf.color = color_index(c)?; + } + if bit(m, 19) { + cf.position = Some(c.i16()?); + } + // The fields PowerPoint 2002 and later add are not used, but they must be read past: the next + // run's count and mask follow them, so stopping short garbles every later run's formatting. + if bit(m, 20) { + c.u32()?; // pp10runid (4 bits) and unused (28 bits) + } + if bit(m, 24) { + c.u16()?; // newEAFontRef + } + if bit(m, 25) { + c.u16()?; // csFontRef + } + if bit(m, 26) { + c.u32()?; // pp11ext + } + Some(cf) +} + +/// A paragraph's PowerPoint 2000 formatting (`TextPFException9`): its automatic numbering. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Pf9 { + /// `fBulletHasAutoNumber` with `bulletAutoNumberScheme`: the scheme and the first number. + pub auto_number: Option<(u16, i16)>, +} + +/// The entries of a `StyleTextProp9Atom` ([MS-PPT] §2.9.33): each a `TextPFException9`, a +/// `TextCFException9` and a `TextSIException`, indexed by the runs' `pp9rt`. Reading stops at an +/// entry with a field this reader can't size, keeping the entries before it. +pub fn read_style9(b: &[u8]) -> Vec { + let mut c = Cursor::new(b); + let mut out = vec![]; + // pp9rt has four bits, so sixteen entries are all a run can name. + while out.len() < 16 && c.remaining() > 0 { + let Some(pf9) = read_pf9(&mut c) else { break }; + out.push(pf9); + // TextCFException9: the extension fields of a character mask. + let Some(m) = c.u32() else { break }; + if m & !((1 << 20) | (1 << 24) | (1 << 25) | (1 << 26)) != 0 { + break; + } + let ok = (!bit(m, 20) || c.u32().is_some()) + && (!bit(m, 24) || c.u16().is_some()) + && (!bit(m, 25) || c.u16().is_some()) + && (!bit(m, 26) || c.u32().is_some()); + // TextSIException: spelling, language, alternate language, bidi, pp10 extension, smart tags. + if !ok || read_si(&mut c).is_none() { + break; + } + } + out +} + +fn read_pf9(c: &mut Cursor) -> Option { + let m = c.u32()?; + if bit(m, 23) { + c.i16()?; // bulletBlipRef + } + let has_auto = if bit(m, 25) { Some(c.u16()? != 0) } else { None }; + let scheme = if bit(m, 24) { Some((c.u16()?, c.i16()?)) } else { None }; + if bit(m, 26) { + c.u32()?; // pp10 extension + } + Some(Pf9 { auto_number: if has_auto == Some(true) { Some(scheme.unwrap_or((3, 1))) } else { None } }) +} + +fn read_si(c: &mut Cursor) -> Option<()> { + let m = c.u32()?; + if m & !0x027F != 0 { + return None; + } + for b in [0, 1, 2, 6] { + if bit(m, b) { + c.u16()?; + } + } + if bit(m, 5) { + c.u32()?; // pp10runid and reserved + } + if bit(m, 9) { + let n = c.u32()?; + for _ in 0..n { + c.u32()?; + } + } + Some(()) +} + +/// The DrawingML numbering scheme of a `TextAutoNumberSchemeEnum` value. +pub fn auto_number_scheme(v: u16) -> &'static str { + match v { + 0 => "alphaLcPeriod", + 1 => "alphaUcPeriod", + 2 => "arabicParenR", + 4 => "romanLcParenBoth", + 5 => "romanLcParenR", + 6 => "romanLcPeriod", + 7 => "romanUcPeriod", + 8 => "alphaLcParenBoth", + 9 => "alphaLcParenR", + 10 => "alphaUcParenBoth", + 11 => "alphaUcParenR", + 12 => "arabicParenBoth", + 13 => "arabicPlain", + 14 => "romanUcParenBoth", + 15 => "romanUcParenR", + 0x10 => "ea1ChsPlain", + 0x11 => "ea1ChsPeriod", + 0x12 => "circleNumDbPlain", + 0x13 => "circleNumWdWhitePlain", + 0x14 => "circleNumWdBlackPlain", + 0x15 => "ea1ChtPlain", + 0x16 => "ea1ChtPeriod", + 0x17 => "arabic1Minus", + 0x18 => "arabic2Minus", + 0x19 => "hebrew2Minus", + 0x1A => "ea1JpnKorPlain", + 0x1B => "ea1JpnKorPeriod", + 0x1C => "arabicDbPlain", + 0x1D => "arabicDbPeriod", + 0x1E => "thaiAlphaPeriod", + 0x1F => "thaiAlphaParenR", + 0x20 => "thaiAlphaParenBoth", + 0x21 => "thaiNumPeriod", + 0x22 => "thaiNumParenR", + 0x23 => "thaiNumParenBoth", + 0x24 => "hindiAlphaPeriod", + 0x25 => "hindiNumPeriod", + 0x26 => "ea1JpnChsDbPeriod", + 0x27 => "hindiNumParenR", + 0x28 => "hindiAlpha1Period", + _ => "arabicPeriod", + } +} + +/// Text types (`TextHeaderAtom.textType`). +pub mod ty { + pub const TITLE: u32 = 0; + pub const BODY: u32 = 1; + pub const NOTES: u32 = 2; + pub const OTHER: u32 = 4; + pub const CENTER_BODY: u32 = 5; + pub const CENTER_TITLE: u32 = 6; + pub const HALF_BODY: u32 = 7; + pub const QUARTER_BODY: u32 = 8; +} + +/// One master text style: up to five levels of paragraph and character formatting. +#[derive(Clone, Debug, Default)] +pub struct LevelStyles { + pub levels: Vec<(Pf, Cf)>, +} + +/// A `TextMasterStyleAtom` body. +pub fn read_master_style(r: &Rec) -> LevelStyles { + let mut c = Cursor::new(r.data); + let mut out = LevelStyles::default(); + let Some(n) = c.u16() else { return out }; + for i in 0..usize::from(n.min(5)) { + // From the centre-body type on, each level names itself (TextMasterStyleLevel.level). + let level = if u32::from(r.instance) >= ty::CENTER_BODY { + let Some(l) = c.u16() else { break }; + usize::from(l) + } else { + i + }; + let Some(pf) = read_pf(&mut c) else { break }; + let Some(cf) = read_cf(&mut c) else { break }; + // Only five levels exist; one naming another is read past. + if level >= 5 { + continue; + } + if out.levels.len() <= level { + out.levels.resize(level + 1, Default::default()); + } + if let Some(slot) = out.levels.get_mut(level) { + *slot = (pf, cf); + } + } + out +} + +/// The text styles in effect for a master: the document defaults plus the master's styles by text +/// type. +#[derive(Clone, Debug, Default)] +pub struct StyleSheet { + pub default_pf: Pf, + pub default_cf: Cf, + /// Indexed by text type (0–8). + pub types: Vec>, +} + +impl StyleSheet { + /// Read the defaults of the document environment and, over them, a master's styles. + pub fn new(environment: Option, master: Option<&Rec>) -> Self { + let mut s = StyleSheet { types: vec![None; 9], ..Default::default() }; + if let Some(env) = environment { + if let Some(pf) = env.child(rt::TEXT_PF_EXCEPTION).and_then(|r| read_pf(&mut Cursor { b: r.data, at: 2 })) { + s.default_pf = pf; + } + if let Some(cf) = env.child(rt::TEXT_CF_EXCEPTION).and_then(|r| read_cf(&mut Cursor::new(r.data))) { + s.default_cf = cf; + } + for r in env.children_of(rt::TEXT_MASTER_STYLE) { + if let Some(slot) = s.types.get_mut(usize::from(r.instance)) { + *slot = Some(read_master_style(&r)); + } + } + } + if let Some(m) = master { + for r in m.children_of(rt::TEXT_MASTER_STYLE) { + if let Some(slot) = s.types.get_mut(usize::from(r.instance)) { + *slot = Some(read_master_style(&r)); + } + } + } + s + } + + /// The formatting of text type `ty` at outline level `level`: defaults, then the base type's + /// level 1 and level, then this type's. + pub fn resolve(&self, ty: u32, level: u8) -> (Pf, Cf) { + let (mut pf, mut cf) = (self.default_pf.clone(), self.default_cf.clone()); + let base = match ty { + ty::CENTER_TITLE => Some(ty::TITLE), + ty::CENTER_BODY | ty::HALF_BODY | ty::QUARTER_BODY => Some(ty::BODY), + _ => None, + }; + for t in base.into_iter().chain(std::iter::once(ty)) { + let Some(Some(st)) = self.types.get(t as usize) else { continue }; + for l in [0usize, usize::from(level)] { + if let Some((p, c)) = st.levels.get(l) { + pf.apply(p); + cf.apply(c); + } + if level == 0 { + break; + } + } + } + (pf, cf) + } +} + +/// A field inside text: its character position and kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FieldKind { + SlideNumber, + DateTime, +} + +/// A block of text with its formatting runs. +#[derive(Clone, Debug, Default)] +pub struct TextBlock { + pub text_type: u32, + pub chars: Vec, + /// (character count, indent level, paragraph exception). + pub para_runs: Vec<(u32, u8, Pf)>, + /// (character count, character exception). + pub char_runs: Vec<(u32, Cf)>, + /// Ruler overrides per level: (left margin, indent) in master units. + pub ruler: [(Option, Option); 5], + pub fields: Vec<(u32, FieldKind)>, + /// An `OutlineTextRefAtom`: the text is the n-th outline block of the slide list entry. + pub outline_ref: Option, + /// The slide list's outline block this text was read from. + pub outline_index: Option, +} + +/// Read a text block from a run of records starting at its `TextHeaderAtom` (inside a client text +/// box, or in the slide list). Stops at the next header or slide persist atom. A client text box +/// may hold only an `OutlineTextRefAtom` ([MS-PPT] OfficeArtClientTextbox), with no header: that +/// is still a block, so the caller can follow the reference. +pub fn read_block<'a>(records: impl Iterator>) -> Option { + let mut b = TextBlock::default(); + let mut started = false; + let mut style: Option = None; + for r in records { + match r.kind { + rt::TEXT_HEADER if started => break, + rt::SLIDE_PERSIST_ATOM => break, + rt::TEXT_HEADER => { + started = true; + b.text_type = r.u32(0).unwrap_or(ty::OTHER); + } + rt::TEXT_CHARS => b.chars = r.data.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(), + rt::TEXT_BYTES => b.chars = r.data.iter().map(|&c| u16::from(c)).collect(), + rt::STYLE_TEXT_PROP => style = Some(r), + rt::TEXT_RULER => b.ruler = read_ruler(&r), + rt::OUTLINE_TEXT_REF => b.outline_ref = r.u32(0), + rt::SLIDE_NUMBER_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::SlideNumber))), + rt::DATETIME_MC | rt::GENERIC_DATE_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::DateTime))), + _ => {} + } + } + if !started && b.outline_ref.is_none() { + return None; + } + if let Some(st) = style { + // Text past u32::MAX characters can't be addressed by the runs; saturate rather than wrap. + read_style_runs(&st, u32::try_from(b.chars.len()).unwrap_or(u32::MAX).saturating_add(1), &mut b); + } + Some(b) +} + +/// The paragraph runs then the character runs of a `StyleTextPropAtom`; each set covers the text +/// plus one (the final paragraph mark). +fn read_style_runs(r: &Rec, total: u32, b: &mut TextBlock) { + let mut c = Cursor::new(r.data); + let mut covered = 0u32; + while covered < total { + let Some(n) = c.u32() else { return }; + let Some(level) = c.u16() else { return }; + let Some(pf) = read_pf(&mut c) else { return }; + b.para_runs.push((n, level.min(8) as u8, pf)); + covered = covered.saturating_add(n.max(1)); + } + covered = 0; + while covered < total { + let Some(n) = c.u32() else { return }; + let Some(cf) = read_cf(&mut c) else { return }; + b.char_runs.push((n, cf)); + covered = covered.saturating_add(n.max(1)); + } +} + +fn read_ruler(r: &Rec) -> [(Option, Option); 5] { + let mut out = [(None, None); 5]; + let mut c = Cursor::new(r.data); + let Some(m) = c.u32() else { return out }; + if bit(m, 1) && c.u16().is_none() { + return out; + } + if bit(m, 0) && c.u16().is_none() { + return out; + } + if bit(m, 2) && read_tabs(&mut c).is_none() { + return out; + } + for (l, slot) in out.iter_mut().enumerate() { + let l = l as u32; + if bit(m, 3 + l) { + slot.0 = c.u16(); + } + if bit(m, 8 + l) { + slot.1 = c.u16(); + } + } + out +} + +#[cfg(test)] +pub(crate) mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + /// A PF exception with alignment and bullets on or off. + pub fn pf_bytes(align: u16, bullet: bool) -> Vec { + let mut v = (0x0000_0801u32).to_le_bytes().to_vec(); // hasBullet + align + v.extend_from_slice(&u16::from(bullet).to_le_bytes()); + v.extend_from_slice(&align.to_le_bytes()); + v + } + + /// A CF exception with bold, a font, a size and an RGB colour. + pub fn cf_bytes(bold: bool, font: u16, size: u16, rgb: [u8; 3]) -> Vec { + let mut v = (0x0007_0001u32).to_le_bytes().to_vec(); // bold + typeface + size + color + v.extend_from_slice(&u16::from(bold).to_le_bytes()); + v.extend_from_slice(&font.to_le_bytes()); + v.extend_from_slice(&size.to_le_bytes()); + v.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 0xFE]); + v + } + + /// The `StyleTextProp9Atom` entries as PowerPoint writes them: three, the second numbered "1." + /// from 1. Short or unknown data keeps the entries read before it. + #[test] + fn reads_numbering_entries() { + let mut b = vec![0u8; 12]; + b.extend_from_slice(&[0, 0, 0, 3, 1, 0, 3, 0, 1, 0]); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(&[0; 12]); + let e = read_style9(&b); + assert_eq!(e.iter().map(|p| p.auto_number).collect::>(), [None, Some((3, 1)), None]); + assert_eq!(read_style9(b.get(..20).unwrap()).len(), 1); + assert_eq!(read_style9(b.get(..22).unwrap()).len(), 2); + assert_eq!(read_style9(&[0xFF; 64]).len(), 1); + assert!(read_style9(&[]).is_empty()); + assert_eq!(auto_number_scheme(3), "arabicPeriod"); + assert_eq!(auto_number_scheme(0), "alphaLcPeriod"); + } + + /// The East Asian, bidi, Thai and Hindi schemes (0x10–0x28) have DrawingML names of their + /// own; only an unknown value falls back to "1.". + #[test] + fn every_numbering_scheme_has_its_drawingml_name() { + assert_eq!(auto_number_scheme(0x10), "ea1ChsPlain"); + assert_eq!(auto_number_scheme(0x13), "circleNumWdWhitePlain"); + assert_eq!(auto_number_scheme(0x19), "hebrew2Minus"); + assert_eq!(auto_number_scheme(0x26), "ea1JpnChsDbPeriod"); + assert_eq!(auto_number_scheme(0x28), "hindiAlpha1Period"); + let names: std::collections::HashSet<_> = (0..=0x28).map(auto_number_scheme).collect(); + assert_eq!(names.len(), 0x29, "each value its own scheme"); + assert_eq!(auto_number_scheme(0x29), "arabicPeriod"); + } + + /// From the centre-body type on, a master style level names its level: it is stored there, + /// and a level past the fifth is read past. + #[test] + fn master_style_levels_go_where_they_say() { + let level = |l: u16, size: u16| [&l.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, size, [0, 0, 0])].concat(); + let body = [&3u16.to_le_bytes()[..], &level(2, 20), &level(7, 30), &level(0, 40)].concat(); + let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::CENTER_BODY as u16, &body); + let st = read_master_style(&Rec::at(&rec, 0).unwrap()); + let sizes: Vec<_> = st.levels.iter().map(|(_, cf)| cf.size).collect(); + assert_eq!(sizes, [Some(40), None, Some(20)]); + // Before it, levels are in order. + let body = [&1u16.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, 12, [0, 0, 0])].concat(); + let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::BODY as u16, &body); + assert_eq!(read_master_style(&Rec::at(&rec, 0).unwrap()).levels[0].1.size, Some(12)); + } + + /// A paragraph exception with many tab stops keeps the first [`MAX_TABS`] and reads the + /// fields after the list where they are. + #[test] + fn tab_stops_are_capped_and_read_past() { + let mut b = ((1u32 << 20) | (1 << 21)).to_le_bytes().to_vec(); // tabStops + textDirection + b.extend_from_slice(&1000u16.to_le_bytes()); + for i in 0..1000u16 { + b.extend_from_slice(&(i as i16).to_le_bytes()); + b.extend_from_slice(&1u16.to_le_bytes()); + } + b.extend_from_slice(&0x1234u16.to_le_bytes()); // textDirection + b.push(0xAB); + let mut c = Cursor::new(&b); + let pf = read_pf(&mut c).unwrap(); + let tabs = pf.tabs.unwrap(); + assert_eq!(tabs.len(), MAX_TABS); + assert_eq!(tabs[MAX_TABS - 1], (MAX_TABS as i16 - 1, 1)); + assert_eq!(c.u8(), Some(0xAB), "the cursor stopped past textDirection"); + } + + #[test] + fn reads_exceptions_in_mask_order() { + let pf = read_pf(&mut Cursor::new(&pf_bytes(1, true))).unwrap(); + assert_eq!(pf.has_bullet, Some(true)); + assert_eq!(pf.align, Some(1)); + assert_eq!(pf.bullet_has_font, None); + let cf = read_cf(&mut Cursor::new(&cf_bytes(true, 3, 28, [1, 2, 3]))).unwrap(); + assert_eq!((cf.bold, cf.italic, cf.font, cf.size, cf.color), (Some(true), None, Some(3), Some(28), Some(TextColor::Rgb(1, 2, 3)))); + // A mask promising more than the bytes hold reads nothing. + assert!(read_cf(&mut Cursor::new(&0x0007_0000u32.to_le_bytes())).is_none()); + } + + #[test] + fn reads_a_text_block_with_runs() { + let chars: Vec = "Hi\rthere".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut style = vec![]; + for (n, lvl) in [(3u32, 0u16), (6, 1)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&lvl.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, lvl == 1)); + } + for n in [2u32, 7] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(n == 2, 0, 20, [0, 0, 0])); + } + let recs = [ + atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &chars), + atom(rt::STYLE_TEXT_PROP, 0, &style), + atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), + ] + .concat(); + let b = read_block(crate::record::Records::new(&recs)).unwrap(); + assert_eq!(b.text_type, ty::BODY); + assert_eq!(String::from_utf16_lossy(&b.chars), "Hi\rthere"); + assert_eq!(b.para_runs.len(), 2); + assert_eq!(b.para_runs[1].1, 1); + assert_eq!(b.char_runs.len(), 2); + assert_eq!(b.char_runs[0].1.bold, Some(true)); + } + + /// A CF exception with only the fields PowerPoint 2002 and later add after `position`: + /// pp10runid (bit 20), newEAFontRef (bit 24), csFontRef (bit 25) and pp11ext (bit 26). + fn cf_later_fields() -> Vec { + let mut v = (1u32 << 20 | 1 << 24 | 1 << 25 | 1 << 26).to_le_bytes().to_vec(); + v.extend_from_slice(&0x0000_0003u32.to_le_bytes()); // pp10runid + unused + v.extend_from_slice(&7u16.to_le_bytes()); // newEAFontRef + v.extend_from_slice(&8u16.to_le_bytes()); // csFontRef + v.extend_from_slice(&0u32.to_le_bytes()); // pp11ext + v + } + + #[test] + fn later_character_fields_are_read_past() { + let bytes = cf_later_fields(); + let mut c = Cursor::new(&bytes); + assert!(read_cf(&mut c).is_some()); + assert!(c.u8().is_none(), "the cursor stopped inside the exception"); + + // A run carrying those fields, then a bold 18 pt run: the second must read as written. + let chars: Vec = "abcd".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut style = vec![]; + style.extend_from_slice(&5u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&cf_later_fields()); + style.extend_from_slice(&3u32.to_le_bytes()); + style.extend_from_slice(&cf_bytes(true, 1, 18, [0, 0, 0])); + let recs = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &chars), atom(rt::STYLE_TEXT_PROP, 0, &style)].concat(); + let b = read_block(crate::record::Records::new(&recs)).unwrap(); + assert_eq!(b.char_runs.len(), 2, "{:?}", b.char_runs); + let (n, cf) = &b.char_runs[1]; + assert_eq!((*n, cf.bold, cf.font, cf.size), (3, Some(true), Some(1), Some(18))); + } + + #[test] + fn styles_inherit_from_level_one_and_the_base_type() { + let mut s = StyleSheet { types: vec![None; 9], ..Default::default() }; + let lvl = |size: u16, align: u16| (Pf { align: Some(align), ..Default::default() }, Cf { size: Some(size), ..Default::default() }); + s.types[ty::BODY as usize] = Some(LevelStyles { levels: vec![lvl(32, 0), (Pf::default(), Cf { size: Some(28), ..Default::default() })] }); + s.types[ty::CENTER_BODY as usize] = Some(LevelStyles { levels: vec![(Pf { align: Some(1), ..Default::default() }, Cf::default())] }); + let (pf, cf) = s.resolve(ty::CENTER_BODY, 1); + assert_eq!(cf.size, Some(28)); + assert_eq!(pf.align, Some(1)); + let (pf, cf) = s.resolve(ty::BODY, 0); + assert_eq!((pf.align, cf.size), (Some(0), Some(32))); + } +} diff --git a/crates/ppt-binary/tests/fixtures/old-talk.pps b/crates/ppt-binary/tests/fixtures/old-talk.pps new file mode 100644 index 000000000..9c5d02004 Binary files /dev/null and b/crates/ppt-binary/tests/fixtures/old-talk.pps differ