From 60d7a16ccc9d8882b5b725847231cecbe95b1977 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 21:55:10 -0500 Subject: [PATCH 1/8] ppt-binary: read PowerPoint 95 placeholders and text (#2317, step 2) PowerPoint 95 slides now hold their placeholders and text boxes, each with its box (converted from master units about the slide's centre) and its text: paragraphs with their level, alignment, bullet character and the indents of the text's ruler, and runs with their font, size, bold, italic, underline and colour, decoded as Windows-1252. Placeholder types use PowerPoint 95's own numbering. The master's placeholders place the default master's, and its footer row every layout's, through the overlay the PowerPoint 97 path uses, now shared. Run tables and text are bounded by the text they cover. --- Cargo.lock | 1 + crates/ppt-binary/Cargo.toml | 1 + crates/ppt-binary/README.md | 10 +- crates/ppt-binary/src/convert.rs | 72 ++-- crates/ppt-binary/src/lib.rs | 7 +- crates/ppt-binary/src/ppt95.rs | 150 ++++++++- crates/ppt-binary/src/ppt95/tests.rs | 477 ++++++++++++++++++++++++++- crates/ppt-binary/src/ppt95/text.rs | 315 ++++++++++++++++++ 8 files changed, 976 insertions(+), 57 deletions(-) create mode 100644 crates/ppt-binary/src/ppt95/text.rs diff --git a/Cargo.lock b/Cargo.lock index 3c7c6a1e9..26e401dc9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2978,6 +2978,7 @@ name = "craft-ppt-binary" version = "0.1.0" dependencies = [ "craft-cfb", + "craft-codepage", "craft-drawingml", "craft-pptx", "image", diff --git a/crates/ppt-binary/Cargo.toml b/crates/ppt-binary/Cargo.toml index aa64c6cc7..e3c7ed32f 100644 --- a/crates/ppt-binary/Cargo.toml +++ b/crates/ppt-binary/Cargo.toml @@ -12,6 +12,7 @@ workspace = true [dependencies] craft-cfb = { workspace = true } +craft-codepage = { workspace = true } craft-drawingml = { workspace = true } craft-pptx = { workspace = true } log = { workspace = true } diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 5972b2eb4..b7d0620e4 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -41,8 +41,14 @@ one feature per file, and the public [MS-PPT] numbering where the records keep i So far a PowerPoint 95 file imports with its slide size, its masters (each the caller's default master wearing the file's colour scheme, and its background when that isn't the scheme's), and its slides in order with their master, layout type and, when a slide doesn't follow the master's, -its own background: a solid colour, or none when the slide's background has no fill. The slides are empty: shapes, placeholders and their text, pictures and -notes come later. +its own background: a solid colour, or none when the slide's background has no fill. Slides hold +their placeholders (title, body, centred title, subtitle, and the date, footer and slide number) +and text boxes, each with its box and its text: paragraphs with their level, alignment, bullet +character and the indents of the text's ruler, and runs with their font, size, bold, italic, +underline and colour (an RGB or a colour scheme slot). The text is Windows-1252. The master's +placeholders set where the default master's placeholders go, and its date, footer and slide number +those of every layout. Shapes without text, the shapes' own fill and line, pictures, notes and the +master's text styles come later. The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: its layouts and placeholders. The file's masters then place and style the placeholders that diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs index 3501f2260..9e6fa2089 100644 --- a/crates/ppt-binary/src/convert.rs +++ b/crates/ppt-binary/src/convert.rs @@ -177,6 +177,41 @@ pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Pr cx.p } +/// A main master's placeholder of `kind` at `x`: the box of the default master's placeholder of +/// the same family. The footer row (date, footer, slide number) sits in the same place on every +/// layout, with the master's look: `look` gives its first paragraph, whose alignment and first +/// run's size and colour the master's and layouts' footer placeholders take. `look` is called only +/// for the footer row, and only when the default master has such a placeholder. +pub(crate) fn place_placeholder(master: &mut Master, kind: PhType, x: Xfrm, look: impl FnOnce() -> Option) { + let Some(s) = master.shapes.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) else { return }; + s.xfrm = Some(x); + if matches!(kind, PhType::Date | PhType::Footer | PhType::SlideNum) { + let look = look(); + 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); + } + } + } + } +} + /// A master's first layout of each layout type, and its first layout. pub(crate) type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option); @@ -267,37 +302,10 @@ impl<'a> Ctx<'a> { 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); - } - } - } - } + if let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) { + place_placeholder(&mut master, kind, x, || { + self.shape(raw, &scope, 0, TOP).and_then(|c| c.text).and_then(|t| t.paragraphs.into_iter().next()) + }); } continue; } @@ -1148,7 +1156,7 @@ fn ph_type(kind: u8) -> Option { }) } -fn same_family(a: PhType, b: PhType) -> bool { +pub(crate) fn same_family(a: PhType, b: PhType) -> bool { let title = |t| matches!(t, PhType::Title | PhType::CtrTitle); a == b || (title(a) && title(b)) } diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index c973a6d8f..b54f63e1f 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -8,9 +8,10 @@ //! place and style. There is no `.ppt` writer. //! //! PowerPoint 95 files (a different record framing, learned from files PowerPoint 95 wrote) read -//! as far as their slide size, masters with their colour schemes and backgrounds, and slides with -//! their order, master, layout type and background; their shapes, text, pictures and notes are -//! not read yet, so the slides are empty. PowerPoint 4.0 and earlier are refused as too old. +//! as far as their slide size, masters with their colour schemes, backgrounds and placeholder +//! boxes, and slides with their order, master, layout type, background, and placeholders and text +//! boxes with formatted text; their other shapes, pictures and notes are not read yet. +//! PowerPoint 4.0 and earlier are refused as too old. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index f44fd5002..fa7e5b35f 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -6,16 +6,35 @@ //! (a type-3 root holding the Document, 1000), with no edit chain or persist directory. //! //! Read so far: the slide size, the masters with their colour schemes and backgrounds, and the -//! slides in order with their master, layout type and background. Shapes, text, pictures and -//! notes are not read yet, so slides come out empty. +//! slides in order with their master, layout type and background, holding their placeholders and +//! text boxes with the text and its character and paragraph formatting ([`text`]). +//! +//! A page's object list (3000) holds shapes (3008) and placeholders (3010, which add a 3011 atom: +//! the type, the size, then the index). Each has its geometry (3009): the box as left, top, right +//! and bottom in master units (576 per inch) measured from the slide's centre, then the angle in +//! sixteenths of a degree. PowerPoint 95 numbers placeholders its own way: on the master 1 title, +//! 2 body, 6 date, 7 slide number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred +//! title and 0x10 subtitle. A placeholder of any other type keeps its text as a text box. The +//! master's placeholders place the caller's default master's, and the footer row places every +//! layout's, as the PowerPoint 97 path does. +//! +//! Not read yet: shapes without text, and shapes' own fill, line and shadow; pictures; notes; and +//! the master's text styles, so the levels of the default master's styles stay as they are (the +//! slide text carries its own formatting in full). use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use craft_pptx::{Background, ColorRef, Defaults, Fill, LayoutType, Master, Presentation, Rgba, Size, Slide, SlideId}; +use craft_pptx::{ + Background, ColorRef, Defaults, Fill, LayoutType, Line, Master, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, Size, Slide, SlideId, + TextBody, Xfrm, +}; -use crate::convert::{Scheme, layout_kind, layout_table, page_side, scheme_theme}; +use crate::convert::{Scheme, layout_kind, layout_table, page_side, place_placeholder, same_family, scheme_theme}; use crate::record::u32_at; +use text::Env; + +mod text; /// Record types. mod rt { @@ -33,6 +52,10 @@ mod rt { pub const OBJECTS: u32 = 3000; pub const FORMAT: u32 = 3005; pub const SHAPE: u32 = 3008; + pub const GEOMETRY: u32 = 3009; + pub const PLACEHOLDER: u32 = 3010; + pub const PLACEHOLDER_ATOM: u32 = 3011; + pub const TEXT: u32 = 4001; } /// "No instance". @@ -43,6 +66,10 @@ const MAX_SLIDES: usize = 1 << 16; /// Masters read at most. Each becomes a copy of the caller's default master with its layouts, so /// the cap is lower than for slides; PowerPoint 95 writes one. const MAX_MASTERS: usize = 256; +/// Objects read from one slide or master at most. +const MAX_OBJECTS: usize = 1 << 14; +/// Master units (576 per inch) per point. +const MU: f64 = 8.0; /// The fill colour's fourth byte when the colour is the RGB given, not a scheme slot. const RGB_GIVEN: u8 = 0xFE; @@ -63,6 +90,8 @@ const DEFAULT_SCHEME: Scheme = [ pub struct Rec<'a> { pub kind: u32, pub instance: u32, + /// The fourth word: a per-type tag, which tells some records of one type apart. + pub tag: u32, /// The body, clipped to the input (a truncated last record keeps what is there). pub data: &'a [u8], } @@ -70,11 +99,10 @@ pub struct Rec<'a> { impl<'a> Rec<'a> { pub fn at(bytes: &'a [u8], at: usize) -> Option> { let word = |k: usize| u32_at(bytes, at.checked_add(k * 4)?); - // The fourth word, a tag, isn't needed yet; it must be there for the header to be whole. - let (kind, instance, len, _tag) = (word(0)?, word(1)?, word(2)?, word(3)?); + let (kind, instance, len, tag) = (word(0)?, word(1)?, word(2)?, word(3)?); let start = at.checked_add(16)?; let end = start.saturating_add(len as usize).min(bytes.len()); - Some(Rec { kind, instance, data: bytes.get(start..end)? }) + Some(Rec { kind, instance, tag, data: bytes.get(start..end)? }) } /// The body read as records. Only called on the types that are containers; the walk never @@ -173,6 +201,90 @@ fn background(rec: &Rec, scheme: &Scheme) -> Option { Some(Fill::solid(ColorRef::rgb(color))) } +/// A PowerPoint 95 placeholder number as a placeholder type. PowerPoint 95 numbers them its own +/// way, not as [MS-PPT] does: 1 to 8 on the master, 0x0C and up on slides. +fn ph_type(kind: u8) -> Option { + Some(match kind { + 0x01 | 0x0C => PhType::Title, + 0x02 | 0x0D => PhType::Body, + 0x06 => PhType::Date, + 0x07 => PhType::SlideNum, + 0x08 => PhType::Footer, + 0x0F => PhType::CtrTitle, + 0x10 => PhType::SubTitle, + _ => return None, + }) +} + +/// One object of a page's list, read but not given an id yet. +struct Object { + /// A placeholder (3010), whether or not its type is known. + placeholder: bool, + /// The placeholder it is, when its type is known. + ph: Option, + xfrm: Xfrm, + text: Option, +} + +/// The shapes and placeholders of a page's object list. +fn objects<'a>(page: &Rec<'a>) -> impl Iterator> { + page.child(rt::OBJECTS).into_iter().flat_map(|l| l.children()).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)).take(MAX_OBJECTS) +} + +/// A shape or placeholder: its box, from master units about the slide's centre to points from +/// its top left corner, its placeholder atom and its text. +fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { + let g = r.child(rt::GEOMETRY)?; + let sides = [g.i32(12)?, g.i32(16)?, g.i32(20)?, g.i32(24)?]; + let [l, t, right, b] = sides; + let x = |v: i32| f64::from(v) / MU + size.width / 2.0; + let y = |v: i32| f64::from(v) / MU + size.height / 2.0; + // The box is the unturned one; the angle is in sixteenths of a degree. + let rot = g.i32(28).map_or(0.0, |v| (f64::from(v) / 16.0).rem_euclid(360.0)); + let xfrm = + Xfrm { x: x(l).min(x(right)), y: y(t).min(y(b)), w: (x(right) - x(l)).abs(), h: (y(b) - y(t)).abs(), rot, flip_h: false, flip_v: false }; + let placeholder = r.kind == rt::PLACEHOLDER; + let ph = r.child(rt::PLACEHOLDER_ATOM).filter(|_| placeholder).and_then(|a| { + let size = match a.u8(1) { + Some(1) => Some("half".into()), + Some(2) => Some("quarter".into()), + _ => None, + }; + Some(Placeholder { kind: ph_type(a.u8(0)?)?, idx: a.u32(4).unwrap_or(0), size, ..Default::default() }) + }); + let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); + Some(Object { placeholder, ph, xfrm, text }) +} + +/// An object as a shape: a placeholder of a known type, else a text box when it has text (a shape +/// with no text is not read yet). A placeholder of an unknown type keeps its text as a text box. +fn shape(p: &mut Presentation, o: Object) -> Option { + let Some(ph) = o.ph else { + let text = o.text.filter(|t| !t.is_empty())?; + return Some(Shape { + id: ShapeId(p.alloc_id()?), + name: "Text Box".into(), + xfrm: Some(o.xfrm), + text_box: true, + fill: Some(Fill::None), + line: Some(Line::none()), + text: Some(text), + ..Default::default() + }); + }; + let name = match ph.kind { + PhType::Title | PhType::CtrTitle => "Title", + PhType::SubTitle => "Subtitle", + PhType::Date => "Date", + PhType::Footer => "Footer", + PhType::SlideNum => "Slide Number", + _ => "Text", + }; + // An empty placeholder draws nothing (its prompt shows only while editing). + let text = Some(o.text.unwrap_or_default()); + Some(Shape { id: ShapeId(p.alloc_id()?), name: name.into(), xfrm: Some(o.xfrm), ph: Some(ph), text, ..Default::default() }) +} + /// Build the presentation from a PowerPoint 95 Document container. pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let atom = document.child(rt::DOCUMENT_ATOM); @@ -181,6 +293,8 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let mut p = Presentation { slide_size: size, default_text_style: app.default_text_style(), next_id: 256, ..Default::default() }; p.notes_size = Size::new(page_side(field(8), 540.0), page_side(field(12), 720.0)); + let env = Env::new(document); + // The lists are told apart by what they hold, in whatever order they come. let (mut slides, mut masters) = (vec![], vec![]); for list in document.children().filter(|r| r.kind == rt::LIST) { @@ -201,6 +315,22 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let index = p.masters.len(); // The scheme's background is what the master shows anyway. master.background = background(&m.rec, &scheme).filter(|f| *f != Fill::solid(ColorRef::rgb(scheme[0]))).map(|fill| Background::Fill { fill }); + // The master's placeholders set where new slides' placeholders go: the first of each + // family places the default master's. Its other objects are the master's own shapes. + let mut placed: Vec = vec![]; + for o in objects(&m.rec).filter_map(|r| object(&r, &env, &scheme, size)) { + if o.placeholder { + if let Some(kind) = o.ph.as_ref().map(|ph| ph.kind).filter(|k| !placed.iter().any(|d| same_family(*d, *k))) { + placed.push(kind); + let text = o.text; + place_placeholder(&mut master, kind, o.xfrm, || text.and_then(|t| t.paragraphs.into_iter().next())); + } + continue; + } + if let Some(s) = shape(&mut p, o) { + master.shapes.push(s); + } + } p.masters.push(Arc::new(master)); by_id.entry(m.id).or_insert((index, scheme)); } @@ -220,7 +350,11 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let scheme = s.scheme.unwrap_or(master_scheme); let background = if s.follow_background { None } else { background(&s.rec, &scheme).map(|fill| Background::Fill { fill }) }; let Some(id) = p.alloc_id() else { break }; - p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, show_master_shapes: true, ..Default::default() })); + let mut shapes = vec![]; + for o in objects(&s.rec).filter_map(|r| object(&r, &env, &scheme, size)) { + shapes.extend(shape(&mut p, o)); + } + p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: true, ..Default::default() })); } p } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 530241648..740be190a 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2,7 +2,8 @@ //! by PowerPoint), and an optional check over real ones named by `CRAFT_PPT95_SAMPLES`. #![allow(clippy::unwrap_used)] -use craft_pptx::{Background, ColorRef, Fill, LayoutType, Presentation, Rgba, SchemeSlot}; +use craft_pptx::text::{Align, Bullet}; +use craft_pptx::{Background, ColorRef, Fill, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, TextBody}; use super::rt; use crate::tests::{AppDefaults, build}; @@ -63,11 +64,13 @@ struct SlideSpec { fill: [u8; 4], filled: bool, scheme: [u32; 8], + /// The slide's object list. + objects: Vec>, } impl SlideSpec { fn new(id: u32, layout: u32) -> SlideSpec { - SlideSpec { id, master: MASTER, layout, follow_background: true, fill: [0, 0, 0, 0], filled: true, scheme: DEFAULT } + SlideSpec { id, master: MASTER, layout, follow_background: true, fill: [0, 0, 0, 0], filled: true, scheme: DEFAULT, objects: vec![] } } } @@ -81,12 +84,16 @@ fn slide(s: &SlideSpec) -> Vec { rec(rt::LAYOUT, 1, 0, &le32(&[s.layout, 0, 0])), container(rt::SCHEME, 0x78, &[scheme_atom(0, s.scheme)]), background_shape(s.fill, s.filled), - container(rt::OBJECTS, 0x14, &[]), + container(rt::OBJECTS, 0x14, &s.objects), ], ) } fn master(id: u32, scheme: [u32; 8], fill: [u8; 4]) -> Vec { + master_with(id, scheme, fill, &[]) +} + +fn master_with(id: u32, scheme: [u32; 8], fill: [u8; 4], objects: &[Vec]) -> Vec { container( rt::MAIN_MASTER, 0x10, @@ -98,11 +105,155 @@ fn master(id: u32, scheme: [u32; 8], fill: [u8; 4]) -> Vec { rec(rt::LAYOUT, 1, 0, &[1, 0, 0, 0, 1, 2, 6, 8, 7, 0, 0, 0]), container(rt::SCHEME, 0x78, &[scheme_atom(0, scheme)]), background_shape(fill, true), - container(rt::OBJECTS, 0x14, &[]), + container(rt::OBJECTS, 0x14, objects), ], ) } +/// A slot list's terminator: what comes before it is slot `n`. +fn slot_end(n: u32) -> Vec { + rec(2017, 0, n, &[]) +} + +/// A `FontEntityAtom` (a LOGFONT) naming `face`, in Windows-1252 bytes. +fn font(face: &[u8]) -> Vec { + let mut b = vec![0u8; 60]; + b[16..20].copy_from_slice(&400u32.to_le_bytes()); + b[28..28 + face.len()].copy_from_slice(face); + container(4022, 9, &[rec(4023, 0, 0, &b)]) +} + +/// A ruler: each level's left margin and first-line indent in master units. +fn ruler(levels: [(i32, i32); 5]) -> Vec { + let mut b: Vec = levels.iter().flat_map(|(l, f)| [l.to_le_bytes(), f.to_le_bytes()].concat()).collect(); + b.extend_from_slice(&le32(&[3, 576, 0])); + container(4069, 9, &[rec(4019, 0, 0, &b), rec(4070, 0, 0, &[])]) +} + +/// The body ruler (slot 0) and a wide one (slot 3, after an empty slot 2). +const BODY_RULER: [(i32, i32); 5] = [(216, 0), (468, 288), (720, 576), (1008, 864), (1296, 1152)]; +const WIDE_RULER: [(i32, i32); 5] = [(576, 288), (828, 648), (1044, 900), (1260, 1116), (1476, 1332)]; + +/// The Environment: fonts Times New Roman, Arial, Courier New and "Café" by slot, and the rulers: +/// the body's, a plain one, an empty slot and a wide one. +fn environment() -> Vec { + let fonts = container( + 2005, + 0x19, + &[font(b"Times New Roman"), slot_end(0), font(b"Arial"), slot_end(1), font(b"Courier New"), slot_end(2), font(b"Caf\xE9"), slot_end(3)], + ); + let plain = [(0, 0), (288, 288), (576, 576), (864, 864), (1152, 1152)]; + let rulers = container( + 4016, + 0x18, + &[ruler(BODY_RULER), slot_end(0), ruler(plain), slot_end(1), rec(2018, 0, 0, &[]), slot_end(2), ruler(WIDE_RULER), slot_end(3)], + ); + container(1010, 0x15, &[rulers, fonts, container(2005, 0x1A, &[])]) +} + +/// A character run: length, font slot, size in points, style bits (1 bold, 2 italic, +/// 4 underline) and colour (R, G, B, then 0xFE or a scheme slot). +fn char_run(len: u32, font: u16, size: u16, style: u16, color: [u8; 4]) -> Vec { + let mut b = vec![0u8; 44]; + b[0..4].copy_from_slice(&len.to_le_bytes()); + b[4..8].copy_from_slice(&0x0FE2u32.to_le_bytes()); + b[20..22].copy_from_slice(&font.to_le_bytes()); + b[24..26].copy_from_slice(&size.to_le_bytes()); + b[28..30].copy_from_slice(&style.to_le_bytes()); + b[30..34].copy_from_slice(&color); + b +} + +/// A plain character run: Times New Roman 24 pt in the scheme's text colour. +fn plain(len: u32) -> Vec { + char_run(len, 0, 24, 0, [0, 0, 0, 1]) +} + +/// A paragraph run: length, bullet on, bullet character, alignment (0 left, 1 centre, 2 right) +/// and level (0-based). +fn para_run(len: u32, bullet: bool, bullet_char: u8, align: u8, level: u8) -> Vec { + let mut b = vec![0u8; 72]; + b[0..4].copy_from_slice(&len.to_le_bytes()); + b[4..8].copy_from_slice(&0x0FE3u32.to_le_bytes()); + b[20] = u8::from(bullet); + b[26] = bullet_char; + b[32] = 100; + b[44] = level; + b[48] = align; + b +} + +/// The text body on slides, and on the master's placeholders. +const BODY: u32 = 4002; +const MASTER_BODY: u32 = 4068; + +/// A text container: header, then the body with its text atom (the text rectangle `rect`), ruler +/// slot and runs. The run tables are 2028 containers each holding one 2030 atom of entries. +fn text(chars: &[u8], char_runs: &[Vec], para_runs: &[Vec], ruler: u32, rect: [i32; 4], body: u32) -> Vec { + let mut atom = le32(&[4, 5, 3, 0xFFFF_8000, 0]); + atom.extend(rect.iter().flat_map(|v| v.to_le_bytes())); + let table = |tag: u32, entries: &[u8]| container(2028, tag, &[rec(2030, 0, tag, entries)]); + let runs = container( + 4064, + 0, + &[rec(2030, 0, 0x35, chars), table(0x2F, &char_runs.concat()), table(0x30, ¶_runs.concat()), table(0x31, &[0; 24]), rec(4013, 0, 0, &[])], + ); + container(4001, 0x1E, &[rec(4000, 0, 0, &[0; 16]), container(body, 0, &[rec(4003, 0, 0, &atom), rec(4021, 0, 0, &le32(&[ruler])), runs])]) +} + +/// Text in one paragraph run and one plain character run, inset 58 × 29 units in `bx`. +fn simple_text(chars: &[u8], bx: [i32; 4], body: u32) -> Vec { + let n = chars.len() as u32 + 1; + text(chars, &[plain(n)], &[para_run(n, false, 0x95, 0, 0)], 1, [bx[0] + 58, bx[1] + 29, bx[2] - 58, bx[3] - 29], body) +} + +/// A shape's geometry: a rectangle at `bx` (left, top, right, bottom about the slide's centre), +/// turned `rot` sixteenths of a degree. +fn geometry(bx: [i32; 4], rot: i32) -> Vec { + let mut b = le32(&[(-3i32) as u32, 0, 0]); + b.extend(bx.iter().chain(&[rot]).flat_map(|v| v.to_le_bytes())); + b.extend_from_slice(&le32(&[(-3i32) as u32, 1])); + rec(3009, 0, 0, &b) +} + +/// A shape (3008), with text when `text` is given. +fn shape_95(bx: [i32; 4], text: Option>) -> Vec { + let mut kids = vec![geometry(bx, 0)]; + kids.extend(text); + container(rt::SHAPE, 0x13, &kids) +} + +/// A placeholder (3010) of PowerPoint 95 type `kind`, size (0 full, 1 half, 2 quarter) and index. +fn placeholder_95(kind: u8, size: u8, index: u32, bx: [i32; 4], text: Option>) -> Vec { + let mut atom = vec![kind, size, 0, 0]; + atom.extend_from_slice(&index.to_le_bytes()); + let mut kids = vec![rec(3011, 0, 0, &atom), geometry(bx, 0)]; + kids.extend(text); + container(3010, 0x13, &kids) +} + +/// One slide holding `objects` (its scheme's title colour 0x112233), on a master holding +/// `master_objects`. +fn deck_of(objects: Vec>, master_objects: &[Vec]) -> Presentation { + let mut s = SlideSpec::new(0x100, 16); + s.scheme[3] = 0x112233; + s.objects = objects; + import(&stream_of(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], master_objects)])).unwrap() +} + +fn body_of(s: &Shape) -> &TextBody { + s.text.as_ref().unwrap() +} + +fn texts(p: &Presentation) -> Vec { + p.slides[0].shapes.iter().map(|s| body_of(s).text()).collect() +} + +fn boxed(s: &Shape) -> (f64, f64, f64, f64) { + let x = s.xfrm.unwrap(); + (x.x, x.y, x.w, x.h) +} + fn document_atom(w: u32, h: u32, slides: u32) -> Vec { let mut b = le32(&[w, h, h, w, 0x0001_0000, 0, 0, 0, slides, 5, 10]); b.truncate(44); @@ -119,7 +270,7 @@ fn stream_of(atom: Vec, slides: &[Vec], masters: &[Vec]) -> Vec let document = container( rt::DOCUMENT, 0, - &[atom, container(1010, 0x15, &[]), list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], + &[atom, environment(), list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], ); container(rt::ROOT, 0, &[document, rec(10, 0, 0, &le32(&[1, 0x100]))]) } @@ -311,6 +462,314 @@ fn hostile_powerpoint_95_streams_never_panic() { assert_eq!(p.masters.len(), super::MAX_MASTERS); } +/// A title slide: the centred title and subtitle placeholders with their text, index, size and +/// box (from master units about the centre to points from the top left), and the text rectangle +/// as insets. +#[test] +fn title_and_subtitle_placeholders_keep_their_text() { + let title = placeholder_95(0x0F, 0, 0, [-2448, -720, 2448, 0], Some(simple_text(b"Title text", [-2448, -720, 2448, 0], BODY))); + let sub = placeholder_95(0x10, 1, 1, [-2016, 288, 2016, 1392], Some(simple_text(b"Sub text", [-2016, 288, 2016, 1392], BODY))); + let p = deck_of(vec![title, sub], &[]); + let shapes = &p.slides[0].shapes; + assert_eq!(texts(&p), ["Title text", "Sub text"]); + let ph: Vec<_> = shapes.iter().map(|s| s.ph.clone().unwrap()).collect(); + assert_eq!((ph[0].kind, ph[0].idx, ph[0].size.as_deref()), (PhType::CtrTitle, 0, None)); + assert_eq!((ph[1].kind, ph[1].idx, ph[1].size.as_deref()), (PhType::SubTitle, 1, Some("half"))); + assert_eq!(boxed(&shapes[0]), (54.0, 180.0, 612.0, 90.0)); + assert_eq!(boxed(&shapes[1]), (108.0, 306.0, 504.0, 138.0)); + let b = &body_of(&shapes[0]).body; + assert_eq!((b.inset_l, b.inset_t, b.inset_r, b.inset_b), (Some(7.25), Some(3.625), Some(7.25), Some(3.625))); + assert!(!shapes[0].text_box); + + // The other types, each an empty placeholder (no text container), which draws nothing. + let kinds = [ + (0x0C, PhType::Title), + (0x0D, PhType::Body), + (1, PhType::Title), + (2, PhType::Body), + (6, PhType::Date), + (7, PhType::SlideNum), + (8, PhType::Footer), + ]; + let p = deck_of(kinds.iter().map(|(k, _)| placeholder_95(*k, 0, 0, [0, 0, 100, 100], None)).collect(), &[]); + let got: Vec<_> = p.slides[0].shapes.iter().map(|s| s.ph_type().unwrap()).collect(); + assert_eq!(got, kinds.map(|(_, t)| t)); + assert!(p.slides[0].shapes.iter().all(|s| body_of(s).paragraphs.is_empty())); +} + +/// A bulleted body: paragraphs split at `\r`, each with its level, bullet character and the +/// margins its level has in the text's ruler. +#[test] +fn a_bulleted_body_keeps_levels_bullets_and_margins() { + let chars = b"One\rTwo\rThree\rFour"; + let runs = [para_run(4, true, 0x95, 0, 0), para_run(4, true, 0x96, 0, 1), para_run(6, true, b'*', 0, 2), para_run(5, false, 0x95, 0, 0)]; + let body = text(chars, &[plain(19)], &runs, 0, [0; 4], BODY); + let p = deck_of(vec![placeholder_95(0x0D, 0, 1, [-2448, -912, 2448, 1680], Some(body))], &[]); + let paras = &body_of(&p.slides[0].shapes[0]).paragraphs; + assert_eq!(paras.iter().map(Paragraph::text).collect::>(), ["One", "Two", "Three", "Four"]); + assert_eq!(paras.iter().map(|p| p.level).collect::>(), [0, 1, 2, 0]); + let bullet = |c: &str| Some(Bullet::Char { char: c.into() }); + assert_eq!(paras.iter().map(|p| p.props.bullet.clone()).collect::>(), [bullet("•"), bullet("–"), bullet("*"), Some(Bullet::None)]); + // Ruler slot 0: level 1 at 216 units with its first line at 0, level 2 at 468 and 288. + assert_eq!((paras[0].props.margin_left, paras[0].props.indent), (Some(27.0), Some(-27.0))); + assert_eq!((paras[1].props.margin_left, paras[1].props.indent), (Some(58.5), Some(-22.5))); + + // Slot 3 follows an empty slot (2018): slots are counted by their ends, not by the rulers. + let wide = text(b"One", &[plain(4)], &[para_run(4, true, 0x95, 0, 0)], 3, [0; 4], BODY); + let p = deck_of(vec![placeholder_95(0x0D, 0, 1, [0, 0, 100, 100], Some(wide))], &[]); + let para = &body_of(&p.slides[0].shapes[0]).paragraphs[0]; + assert_eq!((para.props.margin_left, para.props.indent), (Some(72.0), Some(-36.0))); + // The empty slot, or one past the table, gives no margins. + for slot in [2, 99] { + let t = text(b"One", &[plain(4)], &[para_run(4, true, 0x95, 0, 0)], slot, [0; 4], BODY); + let p = deck_of(vec![placeholder_95(0x0D, 0, 1, [0, 0, 100, 100], Some(t))], &[]); + assert_eq!(body_of(&p.slides[0].shapes[0]).paragraphs[0].props.margin_left, None); + } +} + +/// Character runs: bold, italic and underline bits, the font by slot, the size, and an RGB or a +/// scheme slot of the slide's scheme as the colour. +#[test] +fn character_runs_keep_their_formatting() { + let runs = [ + char_run(4, 0, 24, 1, [0, 0, 0, 1]), + char_run(4, 1, 24, 2, [0, 0, 0, 1]), + char_run(4, 2, 40, 4, [0xFF, 0, 0, 0xFE]), + char_run(5, 99, 0, 7, [0, 0, 0, 3]), + ]; + let body = text(b"BoldItalUndrLast", &runs, &[para_run(17, false, 0, 0, 0)], 1, [0; 4], BODY); + let p = deck_of(vec![shape_95([-2362, -1613, -518, -1325], Some(body))], &[]); + let runs = &body_of(&p.slides[0].shapes[0]).paragraphs[0].runs; + assert_eq!(runs.iter().map(|r| r.text.as_str()).collect::>(), ["Bold", "Ital", "Undr", "Last"]); + let r: Vec<_> = runs.iter().map(|r| &r.props).collect(); + assert_eq!([r[0].bold, r[1].bold, r[2].bold, r[3].bold], [Some(true), Some(false), Some(false), Some(true)]); + assert_eq!([r[0].italic, r[1].italic, r[3].italic], [Some(false), Some(true), Some(true)]); + assert_eq!([r[1].underline.as_deref(), r[2].underline.as_deref()], [Some("none"), Some("sng")]); + assert_eq!( + r.iter().map(|r| r.font.as_deref()).collect::>(), + [Some("Times New Roman"), Some("Arial"), Some("Courier New"), None], + "an unknown font slot leaves the font to the master" + ); + assert_eq!(r.iter().map(|r| r.size).collect::>(), [Some(24.0), Some(24.0), Some(40.0), None]); + let solid = |c: Rgba| Some(Fill::solid(ColorRef::rgb(c))); + assert_eq!(r[0].fill, solid(Rgba::rgb(0, 0, 0))); + assert_eq!(r[2].fill, solid(Rgba::rgb(0xFF, 0, 0))); + assert_eq!(r[3].fill, solid(Rgba::rgb(0x11, 0x22, 0x33)), "slot 3 of the slide's own scheme"); +} + +#[test] +fn paragraphs_keep_their_alignment() { + let runs = [para_run(2, false, 0, 0, 0), para_run(2, false, 0, 1, 0), para_run(2, false, 0, 2, 0), para_run(2, false, 0, 9, 0)]; + let body = text(b"L\rC\rR\rX", &[plain(8)], &runs, 1, [0; 4], BODY); + let p = deck_of(vec![shape_95([0, 0, 1000, 1000], Some(body))], &[]); + let aligns: Vec<_> = body_of(&p.slides[0].shapes[0]).paragraphs.iter().map(|p| p.props.align).collect(); + assert_eq!(aligns, [Some(Align::Left), Some(Align::Center), Some(Align::Right), None]); +} + +/// A shape with text is a text box with no fill or line of its own; a shape without text isn't +/// read yet; a placeholder of a type PowerPoint 95 isn't known to write keeps its text as a text +/// box. +#[test] +fn a_shape_with_text_is_a_text_box() { + let bx = [-2362, -1613, -518, -1325]; + let p = deck_of( + vec![ + shape_95(bx, Some(simple_text(b"Box", bx, BODY))), + shape_95([0, 0, 100, 100], None), + placeholder_95(0x42, 0, 3, bx, Some(simple_text(b"Odd", bx, BODY))), + ], + &[], + ); + assert_eq!(texts(&p), ["Box", "Odd"]); + let s = &p.slides[0].shapes[0]; + assert!(s.text_box && s.ph.is_none()); + assert_eq!((s.fill.clone(), s.line.clone()), (Some(Fill::None), Some(craft_pptx::Line::none()))); + assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); + assert!(p.slides[0].shapes[1].text_box && p.slides[0].shapes[1].ph.is_none()); + + // The box is the unturned one; the angle is in sixteenths of a degree. + let turned = container(rt::SHAPE, 0x13, &[geometry(bx, 480), simple_text(b"Box", bx, BODY)]); + let p = deck_of(vec![turned], &[]); + let x = p.slides[0].shapes[0].xfrm.unwrap(); + assert_eq!((x.x, x.w, x.rot), (64.75, 230.5, 30.0)); +} + +/// The master's placeholders place the default master's (title and body), and the footer row +/// places every layout's too, with the master's alignment and size. The first of each family +/// counts; the master's other objects are its own shapes. +#[test] +fn master_placeholders_move_the_layout_boxes() { + let date_text = text(b"*", &[char_run(2, 0, 14, 0, [0, 0, 0, 1])], &[para_run(2, false, 0, 1, 0)], 1, [0; 4], MASTER_BODY); + let title_box = [-2448, -1776, 2448, -1056]; + let objects = [ + placeholder_95(1, 0, 0, title_box, Some(simple_text(b"Click to edit Master title style", title_box, MASTER_BODY))), + placeholder_95(2, 0, 1, [-2448, -912, 2448, 1680], None), + placeholder_95(6, 1, 2, [-2448, 1776, -1248, 2064], Some(date_text)), + // A second title, and a placeholder of an unknown type: neither places anything. + placeholder_95(1, 0, 5, [0, 0, 8, 8], None), + placeholder_95(0x42, 0, 6, [0, 0, 8, 8], Some(simple_text(b"Odd", [0, 0, 8, 8], MASTER_BODY))), + shape_95([-200, -200, 200, 200], Some(simple_text(b"Logo", [-200, -200, 200, 200], BODY))), + ]; + let p = deck_of(vec![], &objects); + let m = &p.masters[0]; + let on = |shapes: &[Shape], kind: PhType| shapes.iter().find(|s| s.ph_type() == Some(kind)).map(boxed); + assert_eq!(on(&m.shapes, PhType::Title), Some((54.0, 48.0, 612.0, 90.0))); + assert_eq!(on(&m.shapes, PhType::Body), Some((54.0, 156.0, 612.0, 324.0))); + assert_eq!(on(&m.shapes, PhType::Date), Some((54.0, 492.0, 150.0, 36.0))); + // The defaults' footer, which the file doesn't place, stays where it was. + assert_eq!(on(&m.shapes, PhType::Footer), Some((0.33 * 720.0, 0.92 * 540.0, 0.34 * 720.0, 0.05 * 540.0))); + for l in &m.layouts { + assert_eq!(on(&l.shapes, PhType::Date), Some((54.0, 492.0, 150.0, 36.0)), "{}", l.name); + let date = l.shapes.iter().find(|s| s.ph_type() == Some(PhType::Date)).unwrap(); + let level = body_of(date).list_style.level(0).unwrap(); + assert_eq!((level.para.align, level.run.size), (Some(Align::Center), Some(14.0))); + } + let own: Vec<_> = m.shapes.iter().filter(|s| s.ph.is_none()).map(|s| body_of(s).text()).collect(); + assert_eq!(own, ["Logo"]); +} + +/// The characters, a font's face and a bullet character are Windows-1252, 0x80–0x9F included. +#[test] +fn text_is_windows_1252() { + let chars = b"caf\xE9 \x80 \x93q\x94 \x85"; + let n = chars.len() as u32 + 1; + let body = text(chars, &[char_run(n, 3, 24, 0, [0, 0, 0, 1])], &[para_run(n, true, 0xA7, 0, 0)], 1, [0; 4], BODY); + let p = deck_of(vec![shape_95([0, 0, 1000, 1000], Some(body))], &[]); + let para = &body_of(&p.slides[0].shapes[0]).paragraphs[0]; + assert_eq!(para.text(), "café € \u{201C}q\u{201D} \u{2026}"); + assert_eq!(para.runs[0].props.font.as_deref(), Some("Café")); + assert_eq!(para.props.bullet, Some(Bullet::Char { char: "§".into() })); +} + +/// Damaged text never panics and stays bounded: runs past the text, huge run lengths and counts, +/// truncated entries, control characters, empty text, and a character atom past the cap. +#[test] +fn hostile_text_never_panics() { + let bx = [0, 0, 1000, 1000]; + let one = |body: Vec| { + let p = deck_of(vec![shape_95(bx, Some(body))], &[]); + p.slides[0].shapes.first().and_then(|s| s.text.clone()) + }; + // Runs past the text: the text is all there, in one paragraph. + let t = one(text(b"Hi", &[plain(1000)], &[para_run(u32::MAX, true, 0, 7, 200)], 1, [0; 4], BODY)).unwrap(); + assert_eq!(t.text(), "Hi"); + assert_eq!(t.paragraphs[0].level, 4, "the level is capped at PowerPoint 95's fifth"); + // Many zero-length runs: no more are read than the text has characters (plus its end). + let many = vec![plain(0); 100_000]; + let t = one(text(b"abc", &many, &vec![para_run(0, false, 0, 0, 0); 50_000], 1, [0; 4], BODY)).unwrap(); + assert_eq!(t.text(), "abc"); + // A truncated entry is not read; the text keeps no formatting from it. + let mut cut = plain(4); + cut.truncate(43); + let t = one(text(b"abc", &[cut], &[], 1, [0; 4], BODY)).unwrap(); + assert_eq!((t.text(), t.paragraphs[0].runs[0].props.size), ("abc".into(), None)); + // Control characters are dropped; a vertical tab is a line break. + let t = one(text(b"a\x01\x0Bb\t", &[], &[], 1, [0; 4], BODY)).unwrap(); + assert_eq!(t.text(), "a\u{b}b\t"); + // Empty text: an empty text box is not a shape, and a placeholder keeps its empty paragraphs. + assert_eq!(one(text(b"", &[], &[], 1, [0; 4], BODY)), None); + assert_eq!(one(text(b"\r\r", &[], &[], 1, [0; 4], BODY)), None); + let p = deck_of(vec![placeholder_95(0x0D, 0, 1, bx, Some(text(b"\r\r", &[], &[], 1, [0; 4], BODY)))], &[]); + assert_eq!(body_of(&p.slides[0].shapes[0]).paragraphs.len(), 3); + // A text container with no body, and one whose text rectangle is outside the box. + assert!(one(container(4001, 0x1E, &[rec(4000, 0, 0, &[0; 16])])).is_none()); + let t = one(text(b"x", &[], &[], u32::MAX, [i32::MIN, i32::MAX, i32::MIN, i32::MAX], BODY)).unwrap(); + assert_eq!((t.body.inset_l, t.body.inset_t), (None, None)); + // Characters past the cap are not read. + let big = vec![b'x'; super::text::MAX_CHARS + 10]; + let t = one(text(&big, &[], &[], 1, [0; 4], BODY)).unwrap(); + assert_eq!(t.text().len(), super::text::MAX_CHARS); + + // Every word of a slide with text and placeholders set to hostile values, and cuts. + let mut s = SlideSpec::new(0x100, 0); + let two = text( + b"One\rTwo", + &[plain(4), char_run(4, 2, 40, 7, [1, 2, 3, 0xFE])], + &[para_run(4, true, 0x95, 1, 1), para_run(4, false, 0, 2, 0)], + 0, + [10, 10, 990, 990], + BODY, + ); + s.objects = vec![shape_95(bx, Some(two)), placeholder_95(0x0C, 0, 0, bx, Some(simple_text(b"T", bx, BODY)))]; + let objects = [placeholder_95(6, 0, 2, bx, Some(simple_text(b"*", bx, MASTER_BODY)))]; + let stream = stream_of(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], &objects)]); + for at in (0..stream.len() - 4).step_by(4) { + for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF] { + let mut d = stream.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let _ = import(&d); + } + } + for cut in (0..stream.len()).step_by(3) { + let _ = import(&stream[..cut]); + } +} + +/// What one PowerPoint 95 sample shows, by its case name ([`powerpoint_95_samples`]). +fn check_sample(name: &str, p: &Presentation) { + // Every master places the defaults' title and body, and the footer row on every layout. + let m = &p.masters[0]; + let on = |shapes: &[Shape], kind: PhType| shapes.iter().find(|s| s.ph_type() == Some(kind)).map(boxed); + assert_eq!(on(&m.shapes, PhType::Title), Some((54.0, 48.0, 612.0, 90.0)), "{name}"); + assert_eq!(on(&m.layouts[0].shapes, PhType::SlideNum), on(&m.shapes, PhType::SlideNum), "{name}"); + // The text cases' slide text: the first slide's text box, or the second slide's placeholders. + let shapes = |i: usize| &p.slides[i].shapes; + let paras = |i: usize, j: usize| &body_of(&shapes(i)[j]).paragraphs; + let first_run = |i: usize, j: usize| ¶s(i, j)[0].runs[0]; + match name { + "twoslides" => assert_eq!(p.slides.len(), 2), + "title" => { + assert_eq!(layout_kind(p, 1), LayoutType::Title); + assert_eq!( + shapes(1).iter().map(|s| (s.ph_type(), body_of(s).text())).collect::>(), + [(Some(PhType::CtrTitle), "Title text".into()), (Some(PhType::SubTitle), "Sub text".into())] + ); + } + "layout3" => assert_eq!(layout_kind(p, 1), LayoutType::TwoContent), + "background" => assert_eq!(p.slides[0].background, solid(0xFF, 0, 0)), + "bullets" | "indent3" => { + assert_eq!(body_of(&shapes(1)[0]).text(), "Head"); + assert_eq!(paras(1, 1).iter().map(|p| p.level).collect::>(), [0, 1, 0], "{name}"); + assert_eq!(paras(1, 1)[1].props.bullet, Some(Bullet::Char { char: "–".into() }), "{name}"); + } + "flat3" => assert!(paras(1, 1).iter().all(|p| (p.level, &p.props.bullet) == (0, &Some(Bullet::Char { char: "•".into() })))), + "bulletchar" => assert!(paras(1, 1).iter().all(|p| p.props.bullet == Some(Bullet::Char { char: "*".into() }))), + "nobullet" => assert!(paras(1, 1).iter().all(|p| p.props.bullet == Some(Bullet::None))), + "margins" => { + let p = ¶s(1, 1)[0].props; + assert_eq!((p.margin_left, p.indent), (Some(72.0), Some(-36.0))); + } + "bold" | "italic" | "underline" => { + let runs = ¶s(0, 0)[0].runs; + assert_eq!(runs.iter().map(|r| r.text.as_str()).collect::>(), [&body_of(&shapes(0)[0]).text()[..4], " plain"]); + let flags = |r: &craft_pptx::Run| (r.props.bold, r.props.italic, r.props.underline.as_deref() == Some("sng")); + let on = match name { + "bold" => (Some(true), Some(false), false), + "italic" => (Some(false), Some(true), false), + _ => (Some(false), Some(false), true), + }; + assert_eq!((flags(&runs[0]), flags(&runs[1])), (on, (Some(false), Some(false), false)), "{name}"); + } + "points40" => assert_eq!(first_run(0, 0).props.size, Some(40.0)), + "fontname" => assert_eq!(first_run(0, 0).props.font.as_deref(), Some("Courier New")), + "fontcolor" => assert_eq!(first_run(0, 0).props.fill, Some(Fill::solid(ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))))), + "center" | "left" | "right" => { + let align = + [("left", Align::Left), ("center", Align::Center), ("right", Align::Right)].into_iter().find(|(n, _)| *n == name).map(|(_, a)| a); + assert_eq!(paras(0, 0)[0].props.align, align, "{name}"); + } + "align" => assert_eq!(paras(0, 0).iter().map(|p| p.props.align).collect::>(), [Some(Align::Left), Some(Align::Right)]), + "twopara" => assert_eq!(body_of(&shapes(0)[0]).text(), "One\nTwo"), + "textbox" => { + let s = &shapes(0)[0]; + assert_eq!((body_of(s).text(), s.text_box, s.ph.is_none()), ("Box".into(), true, true)); + // The automation reported 1295, 1367.5, 4610 × 720 twips. + assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); + } + _ => {} + } +} + /// Real PowerPoint 95 files, when `CRAFT_PPT95_SAMPLES` names a directory of them (they are not in /// the repository). Each imports with the slide count its DocumentAtom gives, at 10 × 7.5 in. #[test] @@ -330,13 +789,7 @@ fn powerpoint_95_samples() { let count = super::document(&stream).and_then(|d| d.child(rt::DOCUMENT_ATOM)).and_then(|a| a.u32(32)).unwrap(); assert_eq!(p.slides.len(), count as usize, "{name}"); assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0), "{name}"); - match name.as_str() { - "twoslides" => assert_eq!(p.slides.len(), 2), - "title" => assert_eq!(layout_kind(&p, 1), LayoutType::Title), - "layout3" => assert_eq!(layout_kind(&p, 1), LayoutType::TwoContent), - "background" => assert_eq!(p.slides[0].background, solid(0xFF, 0, 0)), - _ => {} - } + check_sample(&name, &p); seen += 1; } eprintln!("read {seen} PowerPoint 95 samples"); diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs new file mode 100644 index 000000000..d3d97dba7 --- /dev/null +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -0,0 +1,315 @@ +//! PowerPoint 95 text: a shape's text container (4001) and the document's font and ruler tables, +//! learned from files PowerPoint 95 wrote. +//! +//! A text container holds a header (4000) and a body: 4002 on slides, 4068 on the master's +//! placeholders. The body holds a text atom (4003: the text type, then the text rectangle), a +//! ruler reference (4021) and the runs (4064). The runs are the characters (2030 tagged 0x35, +//! Windows-1252 bytes, `\r` between paragraphs), then three 2028 containers, each holding a 2030 +//! atom of fixed-size entries: character runs (tag 0x2f, 44 bytes), paragraph runs (0x30, 72 +//! bytes) and one entry for the whole text (0x31, not read). Each set of runs covers the text and +//! one more character, the last paragraph's end. +//! +//! The Environment (1010) holds the fonts (2005) and the rulers (4016) as lists of slots: each +//! slot is what comes before a 2017 record, and an empty slot holds a 2018. A run's font and a +//! text's ruler are slot numbers. + +use craft_pptx::text::{Align, Anchor, BodyProps, Bullet, ParaProps, RunKind}; +use craft_pptx::{ColorRef, Fill, Paragraph, Rgba, Run, RunProps, TextBody}; + +use super::{MU, RGB_GIVEN, Rec}; +use crate::convert::Scheme; + +/// Record types. +mod rt { + pub const ENVIRONMENT: u32 = 1010; + pub const SLOT_END: u32 = 2017; + pub const FONTS: u32 = 2005; + pub const RUN_TABLE: u32 = 2028; + pub const ATOM: u32 = 2030; + pub const RULERS: u32 = 4016; + pub const RULER_ATOM: u32 = 4019; + pub const RULER_REF: u32 = 4021; + pub const FONT: u32 = 4022; + pub const FONT_ATOM: u32 = 4023; + pub const TEXT_BODY: u32 = 4002; + pub const TEXT_ATOM: u32 = 4003; + pub const RUNS: u32 = 4064; + pub const MASTER_TEXT_BODY: u32 = 4068; + pub const RULER: u32 = 4069; +} + +/// The fourth words telling a text's atoms apart. +mod tag { + pub const CHARS: u32 = 0x35; + pub const CHAR_RUNS: u32 = 0x2F; + pub const PARA_RUNS: u32 = 0x30; +} + +const CHAR_RUN: usize = 44; +const PARA_RUN: usize = 72; +/// Characters read from one text at most: far beyond what PowerPoint 95 puts in a shape, so a +/// huge character atom can't make a huge text body. +pub(super) const MAX_CHARS: usize = 1 << 20; +/// Font and ruler slots read at most. +const MAX_SLOTS: usize = 4096; +/// Indent levels: PowerPoint 95 has five. +const LEVELS: usize = 5; + +/// Each level's left margin and first-line indent, in master units from the text's left edge. +type Ruler = [(i32, i32); LEVELS]; + +/// What text in the document draws on: the font faces and rulers, by slot. +#[derive(Default)] +pub(super) struct Env { + fonts: Vec>, + rulers: Vec>, +} + +impl Env { + pub(super) fn new(document: &Rec) -> Env { + let Some(environment) = document.child(rt::ENVIRONMENT) else { return Env::default() }; + // There may be more than one font list; the first that holds fonts is the table. + let fonts = environment + .children() + .filter(|r| r.kind == rt::FONTS) + .map(|list| slots(&list, rt::FONT, |f| f.child(rt::FONT_ATOM).map(|a| face(&a)))) + .find(|f| f.iter().any(Option::is_some)) + .unwrap_or_default(); + let rulers = + environment.child(rt::RULERS).map(|list| slots(&list, rt::RULER, |r| r.child(rt::RULER_ATOM).map(|a| ruler(&a)))).unwrap_or_default(); + Env { fonts, rulers } + } +} + +/// A slot list's entries of `kind`, read by `read`: an entry is the slot of the 2017 records +/// before it. +fn slots(list: &Rec, kind: u32, read: impl Fn(&Rec) -> Option) -> Vec> { + let mut out = vec![]; + let mut current = None; + for r in list.children() { + if r.kind == rt::SLOT_END { + if out.len() >= MAX_SLOTS { + break; + } + out.push(current.take()); + } else if r.kind == kind && current.is_none() { + current = read(&r); + } + } + out +} + +/// A `FontEntityAtom`'s face: a LOGFONT, whose name is the NUL-terminated Windows-1252 bytes from +/// +28. +fn face(a: &Rec) -> String { + let name = a.data.get(28..).unwrap_or(&[]); + name.iter().take(32).take_while(|&&b| b != 0).map(|&b| craft_codepage::cp1252(b)).collect() +} + +/// A ruler atom: each level's left margin, then its first-line indent, as i32s. +fn ruler(a: &Rec) -> Ruler { + let mut out = [(0, 0); LEVELS]; + for (i, level) in out.iter_mut().enumerate() { + *level = (a.i32(i * 8).unwrap_or(0), a.i32(i * 8 + 4).unwrap_or(0)); + } + out +} + +/// A character run: its length and the formatting it gives in full. +struct CharRun { + len: u32, + font: u16, + size: u16, + style: u16, + color: [u8; 4], +} + +/// A paragraph run. +struct ParaRun { + len: u32, + bullet: bool, + bullet_char: u8, + align: u8, + level: u8, +} + +fn u16_at(b: &[u8], at: usize) -> u16 { + crate::record::u16_at(b, at).unwrap_or(0) +} + +fn u32_at(b: &[u8], at: usize) -> u32 { + crate::record::u32_at(b, at).unwrap_or(0) +} + +/// A run table's entries of `size` bytes, read while they cover less than `total` characters, so +/// there are at most `total` of them. +fn entries<'a>(runs: &Rec<'a>, kind: u32, size: usize, total: u32) -> Vec<&'a [u8]> { + let mut out = vec![]; + let mut covered = 0u32; + let tables = runs.children().filter(|r| r.kind == rt::RUN_TABLE && r.tag == kind); + for atom in tables.flat_map(|t| t.children().filter(|a| a.kind == rt::ATOM)) { + for e in atom.data.chunks_exact(size) { + if covered >= total { + return out; + } + covered = covered.saturating_add(u32_at(e, 0).max(1)); + out.push(e); + } + } + out +} + +/// Where each run starts: a running sum of their lengths, so never decreasing. +fn starts(lens: impl Iterator) -> Vec { + let mut at = 0usize; + lens.map(|n| { + let s = at; + at = at.saturating_add(n as usize); + s + }) + .collect() +} + +/// The run holding character `i`. +fn run_at(starts: &[usize], i: usize) -> Option { + starts.partition_point(|&s| s <= i).checked_sub(1) +} + +/// A shape's text. `shape` is its box (left, top, right, bottom in master units), from which the +/// text rectangle gives the insets. `None` when the container holds no text body. +pub(super) fn text_body(container: &Rec, env: &Env, scheme: &Scheme, shape: Option<[i32; 4]>, text_box: bool) -> Option { + let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?; + let runs = body.child(rt::RUNS); + let chars: Vec = runs + .and_then(|r| r.children().find(|a| a.kind == rt::ATOM && a.tag == tag::CHARS)) + .map(|a| a.data.iter().take(MAX_CHARS).map(|&b| craft_codepage::cp1252(b)).collect()) + .unwrap_or_default(); + // The runs cover the text and its last paragraph's end. + let total = u32::try_from(chars.len()).unwrap_or(u32::MAX).saturating_add(1); + let char_runs: Vec = runs + .map(|r| entries(&r, tag::CHAR_RUNS, CHAR_RUN, total)) + .unwrap_or_default() + .into_iter() + .map(|e| CharRun { + len: u32_at(e, 0), + font: u16_at(e, 20), + size: u16_at(e, 24), + style: u16_at(e, 28), + color: [e.get(30), e.get(31), e.get(32), e.get(33)].map(|b| b.copied().unwrap_or(0)), + }) + .collect(); + let para_runs: Vec = runs + .map(|r| entries(&r, tag::PARA_RUNS, PARA_RUN, total)) + .unwrap_or_default() + .into_iter() + .map(|e| ParaRun { + len: u32_at(e, 0), + bullet: e.get(20).is_some_and(|&b| b != 0), + bullet_char: e.get(26).copied().unwrap_or(0), + align: e.get(48).copied().unwrap_or(0), + level: e.get(44).copied().unwrap_or(0), + }) + .collect(); + let ruler = body.child(rt::RULER_REF).and_then(|r| r.u32(0)).and_then(|i| env.rulers.get(i as usize)).copied().flatten(); + + let mut props = BodyProps::default(); + if let (Some(atom), Some([l, t, r, b])) = (body.child(rt::TEXT_ATOM), shape) { + // The text rectangle, inside the shape's box. + let inset = |from: i32, to: Option, sign: f64| { + to.map(|to| (f64::from(to) - f64::from(from)) * sign / MU).filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) + }; + props.inset_l = inset(l, atom.i32(20), 1.0); + props.inset_t = inset(t, atom.i32(24), 1.0); + props.inset_r = inset(r, atom.i32(28), -1.0); + props.inset_b = inset(b, atom.i32(32), -1.0); + } + if text_box { + props.anchor = Some(Anchor::Top); + props.wrap = Some(true); + } + Some(TextBody { body: props, paragraphs: paragraphs(&chars, &char_runs, ¶_runs, ruler.as_ref(), env, scheme), ..Default::default() }) +} + +fn paragraphs(chars: &[char], char_runs: &[CharRun], para_runs: &[ParaRun], ruler: Option<&Ruler>, env: &Env, scheme: &Scheme) -> Vec { + let total = chars.len(); + let para_starts = starts(para_runs.iter().map(|r| r.len)); + let char_starts = starts(char_runs.iter().map(|r| r.len)); + let props_at = |i: usize| run_at(&char_starts, i).and_then(|k| char_runs.get(k)).map(|r| run_props(r, env, scheme)).unwrap_or_default(); + let mut out = vec![]; + let mut start = 0usize; + loop { + let end = chars.get(start..).and_then(|rest| rest.iter().position(|&c| c == '\r')).map_or(total, |e| start + e); + let pr = run_at(¶_starts, start).and_then(|i| para_runs.get(i)); + let level = pr.map_or(0, |r| r.level.min(LEVELS as u8 - 1)); + let mut para = Paragraph { level, props: para_props(pr, ruler.and_then(|r| r.get(usize::from(level)))), ..Default::default() }; + let mut i = start; + while i < end { + let props = props_at(i); + if chars.get(i) == Some(&'\u{b}') { + para.runs.push(Run { text: String::new(), props, kind: RunKind::Break }); + i += 1; + continue; + } + // A text run: up to the next format change, line 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 && chars.get(j) != Some(&'\u{b}') { + j += 1; + } + let j = j.max(i + 1); + let text: String = chars.get(i..j).unwrap_or(&[]).iter().filter(|&&c| c >= ' ' || c == '\t').collect(); + para.runs.push(Run::with(text, props)); + i = j; + } + para.end_props = props_at(start); + para.normalize(); + out.push(para); + if end >= total { + break; + } + start = end + 1; + } + out +} + +/// A character run's formatting, which PowerPoint 95 gives in full: font, size, bold, italic, +/// underline and colour (an RGB, or a slot of the colour scheme). +fn run_props(r: &CharRun, env: &Env, scheme: &Scheme) -> RunProps { + let [red, g, b, index] = r.color; + let color = if index == RGB_GIVEN { Some(Rgba::rgb(red, g, b)) } else { scheme.get(usize::from(index)).copied() }; + RunProps { + font: env.fonts.get(usize::from(r.font)).cloned().flatten().filter(|f| !f.is_empty()), + size: Some(f64::from(r.size)).filter(|s| (1.0..=4000.0).contains(s)), + bold: Some(r.style & 1 != 0), + italic: Some(r.style & 2 != 0), + underline: Some(if r.style & 4 != 0 { "sng" } else { "none" }.into()), + fill: color.map(|c| Fill::solid(ColorRef::rgb(c))), + ..Default::default() + } +} + +/// A paragraph run's alignment and bullet, and the margins its level has in the text's ruler. +fn para_props(r: Option<&ParaRun>, level: Option<&(i32, i32)>) -> ParaProps { + let mut p = ParaProps::default(); + if let Some(r) = r { + p.align = match r.align { + 0 => Some(Align::Left), + 1 => Some(Align::Center), + 2 => Some(Align::Right), + _ => None, + }; + p.bullet = Some(if r.bullet { + let c = if r.bullet_char >= 0x20 { craft_codepage::cp1252(r.bullet_char) } else { '•' }; + Bullet::Char { char: c.to_string() } + } else { + Bullet::None + }); + } + if let Some(&(left, first)) = level { + // Bounded, so a hostile ruler can't push text off any page. + let (left, first) = ((f64::from(left) / MU).clamp(0.0, 4000.0), (f64::from(first) / MU).clamp(0.0, 4000.0)); + p.margin_left = Some(left); + p.indent = Some(first - left); + } + p +} From 07b7c8b8fb1cf674aeb1504fee7ef6e4612d23fd Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 00:25:00 -0500 Subject: [PATCH 2/8] ppt-binary: PowerPoint 95 master text styles, anchoring, spacing and justified text Paragraph runs give line spacing, space before and space after at +52, +56 and +60: a percentage of a line, or minus a size in points. Alignment 3 is justified. The text atom's +8 byte holds the anchoring (top, middle or bottom, and whether it is centred across) and its +4 flags word wrap. The Environment's 4052 atoms, one per text type, hold the master's styles, five levels each laid out as the runs are; the title, body and other ones become the master's styles, with the margins of the ruler the master's title and body name. All of this was learned from files PowerPoint 95 wrote. --- crates/ppt-binary/README.md | 14 +- crates/ppt-binary/src/lib.rs | 7 +- crates/ppt-binary/src/ppt95.rs | 39 +++- crates/ppt-binary/src/ppt95/tests.rs | 276 +++++++++++++++++++++++++-- crates/ppt-binary/src/ppt95/text.rs | 150 ++++++++++++--- 5 files changed, 436 insertions(+), 50 deletions(-) diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index b7d0620e4..c5838de3d 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -43,12 +43,14 @@ master wearing the file's colour scheme, and its background when that isn't the its slides in order with their master, layout type and, when a slide doesn't follow the master's, its own background: a solid colour, or none when the slide's background has no fill. Slides hold their placeholders (title, body, centred title, subtitle, and the date, footer and slide number) -and text boxes, each with its box and its text: paragraphs with their level, alignment, bullet -character and the indents of the text's ruler, and runs with their font, size, bold, italic, -underline and colour (an RGB or a colour scheme slot). The text is Windows-1252. The master's -placeholders set where the default master's placeholders go, and its date, footer and slide number -those of every layout. Shapes without text, the shapes' own fill and line, pictures, notes and the -master's text styles come later. +and text boxes, each with its box and its text: the text's anchoring (top, middle or bottom, and +whether it's centred across) and word wrap, paragraphs with their level, alignment (justified +included), line spacing, space before and after (in lines or points), bullet character and the +indents of the text's ruler, and runs with their font, size, bold, italic, underline and colour +(an RGB or a colour scheme slot). The text is Windows-1252. The master's placeholders set where the +default master's placeholders go, and its date, footer and slide number those of every layout. The +master's text styles become its title, body and other styles, level by level. Shapes without text, +the shapes' own fill and line, pictures and notes come later. The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: its layouts and placeholders. The file's masters then place and style the placeholders that diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index b54f63e1f..eda093501 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -8,9 +8,10 @@ //! place and style. There is no `.ppt` writer. //! //! PowerPoint 95 files (a different record framing, learned from files PowerPoint 95 wrote) read -//! as far as their slide size, masters with their colour schemes, backgrounds and placeholder -//! boxes, and slides with their order, master, layout type, background, and placeholders and text -//! boxes with formatted text; their other shapes, pictures and notes are not read yet. +//! as far as their slide size, masters with their colour schemes, backgrounds, placeholder boxes +//! and text styles, and slides with their order, master, layout type, background, and placeholders +//! and text boxes with formatted, anchored text; their other shapes, pictures and notes are not +//! read yet. //! PowerPoint 4.0 and earlier are refused as too old. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index fa7e5b35f..a86bef2ae 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -7,7 +7,8 @@ //! //! Read so far: the slide size, the masters with their colour schemes and backgrounds, and the //! slides in order with their master, layout type and background, holding their placeholders and -//! text boxes with the text and its character and paragraph formatting ([`text`]). +//! text boxes with the text, its character and paragraph formatting (spacing and justified +//! alignment included) and its anchoring ([`text`]). //! //! A page's object list (3000) holds shapes (3008) and placeholders (3010, which add a 3011 atom: //! the type, the size, then the index). Each has its geometry (3009): the box as left, top, right @@ -18,9 +19,11 @@ //! master's placeholders place the caller's default master's, and the footer row places every //! layout's, as the PowerPoint 97 path does. //! -//! Not read yet: shapes without text, and shapes' own fill, line and shadow; pictures; notes; and -//! the master's text styles, so the levels of the default master's styles stay as they are (the -//! slide text carries its own formatting in full). +//! The master's text styles (the Environment's 4052 atoms, one per text type) become the master's +//! title, body and other styles. Slide text carries its own formatting in full, so these matter +//! for text added later. +//! +//! Not read yet: shapes without text, and shapes' own fill, line and shadow; pictures; and notes. use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -224,6 +227,8 @@ struct Object { ph: Option, xfrm: Xfrm, text: Option, + /// The ruler slot its text names. + ruler: Option, } /// The shapes and placeholders of a page's object list. @@ -252,8 +257,10 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { }; Some(Placeholder { kind: ph_type(a.u8(0)?)?, idx: a.u32(4).unwrap_or(0), size, ..Default::default() }) }); - let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); - Some(Object { placeholder, ph, xfrm, text }) + let container = r.child(rt::TEXT); + let text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none())); + let ruler = container.and_then(|c| text::ruler_slot(&c)); + Some(Object { placeholder, ph, xfrm, text, ruler }) } /// An object as a shape: a placeholder of a known type, else a text box when it has text (a shape @@ -318,10 +325,17 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { // The master's placeholders set where new slides' placeholders go: the first of each // family places the default master's. Its other objects are the master's own shapes. let mut placed: Vec = vec![]; + // The rulers of the master's title and body, which give their styles' margins. + let (mut title_ruler, mut body_ruler) = (None, None); for o in objects(&m.rec).filter_map(|r| object(&r, &env, &scheme, size)) { if o.placeholder { if let Some(kind) = o.ph.as_ref().map(|ph| ph.kind).filter(|k| !placed.iter().any(|d| same_family(*d, *k))) { placed.push(kind); + match kind { + PhType::Title => title_ruler = o.ruler, + PhType::Body => body_ruler = o.ruler, + _ => {} + } let text = o.text; place_placeholder(&mut master, kind, o.xfrm, || text.and_then(|t| t.paragraphs.into_iter().next())); } @@ -331,6 +345,19 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { master.shapes.push(s); } } + // The master's text styles replace the defaults' first five levels. + for (style, ty, ruler) in [ + (&mut master.title_style, text::TITLE, title_ruler), + (&mut master.body_style, text::BODY, body_ruler), + (&mut master.other_style, text::OTHER, None), + ] { + let Some(read) = text::master_style(&env, &scheme, ty, ruler) else { continue }; + for level in 0..5u8 { + if let Some(l) = read.level(level) { + style.set(level, l.clone()); + } + } + } p.masters.push(Arc::new(master)); by_id.entry(m.id).or_insert((index, scheme)); } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 740be190a..d38dc3e70 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2,7 +2,7 @@ //! by PowerPoint), and an optional check over real ones named by `CRAFT_PPT95_SAMPLES`. #![allow(clippy::unwrap_used)] -use craft_pptx::text::{Align, Bullet}; +use craft_pptx::text::{Align, Anchor, Bullet, ListStyle, Spacing}; use craft_pptx::{Background, ColorRef, Fill, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, TextBody}; use super::rt; @@ -137,6 +137,11 @@ const WIDE_RULER: [(i32, i32); 5] = [(576, 288), (828, 648), (1044, 900), (1260, /// The Environment: fonts Times New Roman, Arial, Courier New and "Café" by slot, and the rulers: /// the body's, a plain one, an empty slot and a wide one. fn environment() -> Vec { + environment_with(&[]) +} + +/// The Environment, with `styles` (the master's text styles' container) when given. +fn environment_with(styles: &[Vec]) -> Vec { let fonts = container( 2005, 0x19, @@ -148,7 +153,58 @@ fn environment() -> Vec { 0x18, &[ruler(BODY_RULER), slot_end(0), ruler(plain), slot_end(1), rec(2018, 0, 0, &[]), slot_end(2), ruler(WIDE_RULER), slot_end(3)], ); - container(1010, 0x15, &[rulers, fonts, container(2005, 0x1A, &[])]) + let mut kids = vec![rulers, fonts, container(2005, 0x1A, &[])]; + kids.extend_from_slice(styles); + container(1010, 0x15, &kids) +} + +/// One level of a master style: font slot, size, style bits, colour; bullet, bullet character, +/// alignment, line spacing, space before and after. +#[derive(Clone, Copy)] +struct Level { + font: u16, + size: u16, + style: u16, + color: [u8; 4], + bullet: bool, + bullet_char: u8, + align: u8, + spacing: [i32; 3], +} + +const LEVEL: Level = Level { font: 0, size: 24, style: 0, color: [0, 0, 0, 1], bullet: false, bullet_char: 0x95, align: 0, spacing: [100, 0, 0] }; + +/// A master style atom (4052): five levels of character formatting from +16 (24 bytes each), then +/// five of paragraph formatting from +160 (52 bytes each), with the anchoring at +8. +fn style_atom(levels: [Level; 5], anchor: u8) -> Vec { + let mut b = vec![0u8; 472]; + b[8] = anchor; + b[12] = 0x1F; + for (i, l) in levels.iter().enumerate() { + let c = 16 + i * 24; + b[c..c + 2].copy_from_slice(&l.font.to_le_bytes()); + b[c + 2] = 2; + b[c + 4..c + 6].copy_from_slice(&l.size.to_le_bytes()); + b[c + 8..c + 10].copy_from_slice(&l.style.to_le_bytes()); + b[c + 10..c + 14].copy_from_slice(&l.color); + let p = 160 + i * 52; + b[p] = u8::from(l.bullet); + b[p + 6] = l.bullet_char; + b[p + 12] = 100; + b[p + 24] = i as u8; + b[p + 28] = l.align; + for (k, v) in l.spacing.iter().enumerate() { + b[p + 32 + k * 4..p + 36 + k * 4].copy_from_slice(&v.to_le_bytes()); + } + } + rec(4052, 0, 0, &b) +} + +/// The master's text styles (1028): a 1029 atom, then the style atoms in text-type order. +fn styles(atoms: &[Vec]) -> Vec { + let mut kids = vec![rec(1029, 0, 0, &[1, 1, 1, 1, 1, 0, 0, 0, 0, 0x0C])]; + kids.extend_from_slice(atoms); + container(1028, 0x2A, &kids) } /// A character run: length, font slot, size in points, style bits (1 bold, 2 italic, @@ -169,10 +225,19 @@ fn plain(len: u32) -> Vec { char_run(len, 0, 24, 0, [0, 0, 0, 1]) } -/// A paragraph run: length, bullet on, bullet character, alignment (0 left, 1 centre, 2 right) -/// and level (0-based). +/// A paragraph run: length, bullet on, bullet character, alignment (0 left, 1 centre, 2 right, +/// 3 justified) and level (0-based), single spaced with no space before or after. fn para_run(len: u32, bullet: bool, bullet_char: u8, align: u8, level: u8) -> Vec { + spaced_run(len, bullet, bullet_char, align, level, [100, 0, 0]) +} + +/// A paragraph run with its line spacing, space before and space after: a percentage of a line, +/// or minus a size in points. +fn spaced_run(len: u32, bullet: bool, bullet_char: u8, align: u8, level: u8, spacing: [i32; 3]) -> Vec { let mut b = vec![0u8; 72]; + for (k, v) in spacing.iter().enumerate() { + b[52 + k * 4..56 + k * 4].copy_from_slice(&v.to_le_bytes()); + } b[0..4].copy_from_slice(&len.to_le_bytes()); b[4..8].copy_from_slice(&0x0FE3u32.to_le_bytes()); b[20] = u8::from(bullet); @@ -190,7 +255,23 @@ const MASTER_BODY: u32 = 4068; /// A text container: header, then the body with its text atom (the text rectangle `rect`), ruler /// slot and runs. The run tables are 2028 containers each holding one 2030 atom of entries. fn text(chars: &[u8], char_runs: &[Vec], para_runs: &[Vec], ruler: u32, rect: [i32; 4], body: u32) -> Vec { - let mut atom = le32(&[4, 5, 3, 0xFFFF_8000, 0]); + text_flagged(chars, char_runs, para_runs, ruler, rect, body, 5, 3) +} + +/// A text container whose text atom has the flags `flags` at +4 (bit 2 word wrap) and the +/// anchoring `anchor` at +8. +#[allow(clippy::too_many_arguments)] +fn text_flagged( + chars: &[u8], + char_runs: &[Vec], + para_runs: &[Vec], + ruler: u32, + rect: [i32; 4], + body: u32, + flags: u32, + anchor: u32, +) -> Vec { + let mut atom = le32(&[4, flags, anchor, 0xFFFF_8000, 0]); atom.extend(rect.iter().flat_map(|v| v.to_le_bytes())); let table = |tag: u32, entries: &[u8]| container(2028, tag, &[rec(2030, 0, tag, entries)]); let runs = container( @@ -262,6 +343,10 @@ fn document_atom(w: u32, h: u32, slides: u32) -> Vec { /// A `PowerPoint Document` stream: root 3 holding the Document and a type-10 atom. fn stream_of(atom: Vec, slides: &[Vec], masters: &[Vec]) -> Vec { + stream_with(atom, slides, masters, environment()) +} + +fn stream_with(atom: Vec, slides: &[Vec], masters: &[Vec], environment: Vec) -> Vec { let list = |tag: u32, items: &[Vec]| { let mut kids = vec![rec(2001, 0, 0, &le32(&[items.len() as u32]))]; kids.extend_from_slice(items); @@ -270,7 +355,7 @@ fn stream_of(atom: Vec, slides: &[Vec], masters: &[Vec]) -> Vec let document = container( rt::DOCUMENT, 0, - &[atom, environment(), list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], + &[atom, environment, list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], ); container(rt::ROOT, 0, &[document, rec(10, 0, 0, &le32(&[1, 0x100]))]) } @@ -559,11 +644,122 @@ fn character_runs_keep_their_formatting() { #[test] fn paragraphs_keep_their_alignment() { - let runs = [para_run(2, false, 0, 0, 0), para_run(2, false, 0, 1, 0), para_run(2, false, 0, 2, 0), para_run(2, false, 0, 9, 0)]; - let body = text(b"L\rC\rR\rX", &[plain(8)], &runs, 1, [0; 4], BODY); + let runs = [ + para_run(2, false, 0, 0, 0), + para_run(2, false, 0, 1, 0), + para_run(2, false, 0, 2, 0), + para_run(2, false, 0, 3, 0), + para_run(2, false, 0, 9, 0), + ]; + let body = text(b"L\rC\rR\rJ\rX", &[plain(10)], &runs, 1, [0; 4], BODY); let p = deck_of(vec![shape_95([0, 0, 1000, 1000], Some(body))], &[]); let aligns: Vec<_> = body_of(&p.slides[0].shapes[0]).paragraphs.iter().map(|p| p.props.align).collect(); - assert_eq!(aligns, [Some(Align::Left), Some(Align::Center), Some(Align::Right), None]); + assert_eq!(aligns, [Some(Align::Left), Some(Align::Center), Some(Align::Right), Some(Align::Justify), None]); +} + +/// Line spacing, space before and space after: a percentage of a line when positive, minus a +/// size in points when negative; hostile sizes are bounded. +#[test] +fn paragraphs_keep_their_spacing() { + let runs = [ + spaced_run(2, false, 0, 0, 0, [150, 50, 0]), + spaced_run(2, false, 0, 0, 0, [-36, -12, -6]), + spaced_run(2, false, 0, 0, 0, [i32::MAX, i32::MIN, -1]), + ]; + let body = text(b"A\rB\rC", &[plain(6)], &runs, 1, [0; 4], BODY); + let p = deck_of(vec![shape_95([0, 0, 1000, 1000], Some(body))], &[]); + let got: Vec<_> = + body_of(&p.slides[0].shapes[0]).paragraphs.iter().map(|p| (p.props.line_spacing, p.props.space_before, p.props.space_after)).collect(); + assert_eq!( + got, + [ + (Some(Spacing::Pct(1.5)), Some(Spacing::Pct(0.5)), Some(Spacing::Pct(0.0))), + (Some(Spacing::Pts(36.0)), Some(Spacing::Pts(12.0)), Some(Spacing::Pts(6.0))), + (Some(Spacing::Pct(100.0)), Some(Spacing::Pts(4000.0)), Some(Spacing::Pts(1.0))), + ] + ); +} + +/// The text atom's +8 anchoring: bits 4–5 top, middle or bottom, bit 1 clear for centred +/// across; an unknown vertical code leaves the anchoring alone. Its +4 bit 2 is word wrap. +#[test] +fn text_keeps_its_anchoring_and_wrap() { + let bx = [0, 0, 1000, 1000]; + let anchored = |flags: u32, anchor: u32, placeholder: bool| { + let t = text_flagged(b"A", &[plain(2)], &[para_run(2, false, 0, 0, 0)], 1, [0; 4], BODY, flags, anchor); + let o = if placeholder { placeholder_95(0x0D, 0, 1, bx, Some(t)) } else { shape_95(bx, Some(t)) }; + let b = body_of(&deck_of(vec![o], &[]).slides[0].shapes[0]).body.clone(); + (b.anchor, b.anchor_ctr, b.wrap) + }; + assert_eq!(anchored(5, 0x03, false), (Some(Anchor::Top), Some(false), Some(true))); + assert_eq!(anchored(5, 0x13, false), (Some(Anchor::Middle), Some(false), Some(true))); + assert_eq!(anchored(5, 0x23, false), (Some(Anchor::Bottom), Some(false), Some(true))); + assert_eq!(anchored(5, 0x01, false), (Some(Anchor::Top), Some(true), Some(true))); + assert_eq!(anchored(5, 0x11, true), (Some(Anchor::Middle), Some(true), Some(true))); + assert_eq!(anchored(5, 0x21, true), (Some(Anchor::Bottom), Some(true), Some(true))); + assert_eq!(anchored(1, 0x03, false), (Some(Anchor::Top), Some(false), Some(false)), "no word wrap"); + // An unknown code: a text box keeps its top anchoring, a placeholder its master's. + assert_eq!(anchored(5, 0xF3, false), (Some(Anchor::Top), None, Some(true))); + assert_eq!(anchored(4, 0xF3, true), (None, None, Some(true))); +} + +/// The master's text styles (the Environment's 4052 atoms, by text type) become its title, body +/// and other styles: each level's font, size, bold, colour, bullet, alignment and spacing, with +/// the margins of the ruler its placeholder names. +#[test] +fn the_masters_text_styles_are_read() { + let title = Level { font: 1, size: 44, style: 1, color: [0, 0, 0, 3], align: 1, ..LEVEL }; + let body: [Level; 5] = std::array::from_fn(|i| Level { + size: [32, 28, 24, 20, 20][i], + bullet: true, + bullet_char: if i % 2 == 1 { 0x96 } else { 0x95 }, + spacing: [100, 20, 0], + ..LEVEL + }); + let notes = Level { size: 12, ..LEVEL }; + let other = Level { color: [0xFF, 0, 0, 0xFE], align: 3, spacing: [150, -12, -6], ..LEVEL }; + let atoms = [style_atom([title; 5], 0x13), style_atom(body, 3), style_atom([notes; 5], 3), style_atom([notes; 5], 3), style_atom([other; 5], 3)]; + let master_objects = [ + placeholder_95(1, 0, 0, [-2448, -1776, 2448, -1056], Some(text(b"T", &[plain(2)], &[para_run(2, false, 0, 1, 0)], 1, [0; 4], MASTER_BODY))), + placeholder_95(2, 0, 1, [-2448, -912, 2448, 1680], Some(text(b"B", &[plain(2)], &[para_run(2, true, 0x95, 0, 0)], 0, [0; 4], MASTER_BODY))), + ]; + let mut scheme = DEFAULT; + scheme[3] = 0x112233; + let stream = |env: Vec| stream_with(document_atom(5760, 4320, 0), &[], &[master_with(MASTER, scheme, [0; 4], &master_objects)], env); + let p = import(&stream(environment_with(&[styles(&atoms)]))).unwrap(); + let m = &p.masters[0]; + + let t = m.title_style.level(0).unwrap(); + assert_eq!((t.run.font.as_deref(), t.run.size, t.run.bold), (Some("Arial"), Some(44.0), Some(true))); + assert_eq!(t.run.fill, Some(Fill::solid(ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0x33)))), "slot 3 of the master's scheme"); + assert_eq!((t.para.align, t.para.bullet.clone()), (Some(Align::Center), Some(Bullet::None))); + // The plain ruler (slot 1) the master title names: no margin at level 1. + assert_eq!((t.para.margin_left, t.para.indent), (Some(0.0), Some(0.0))); + + let sizes: Vec<_> = (0..5).map(|l| m.body_style.level(l).unwrap().run.size).collect(); + assert_eq!(sizes, [Some(32.0), Some(28.0), Some(24.0), Some(20.0), Some(20.0)]); + let b = m.body_style.level(1).unwrap(); + assert_eq!(b.para.bullet, Some(Bullet::Char { char: "–".into() })); + assert_eq!((b.para.line_spacing, b.para.space_before), (Some(Spacing::Pct(1.0)), Some(Spacing::Pct(0.2)))); + // The body ruler (slot 0) the master body names: level 2 at 468 units, first line at 288. + assert_eq!((b.para.margin_left, b.para.indent), (Some(58.5), Some(-22.5))); + + let o = m.other_style.level(0).unwrap(); + assert_eq!((o.run.size, o.run.fill.clone()), (Some(24.0), Some(Fill::solid(ColorRef::rgb(Rgba::rgb(0xFF, 0, 0)))))); + assert_eq!((o.para.align, o.para.line_spacing, o.para.space_after), (Some(Align::Justify), Some(Spacing::Pct(1.5)), Some(Spacing::Pts(6.0)))); + assert_eq!(o.para.margin_left, None, "other text has no master placeholder, so no ruler"); + + // Without styles, or with a truncated atom, the defaults' styles stay as they are. + let plain_master = import(&stream(environment())).unwrap(); + let defaults = |p: &Presentation| -> [ListStyle; 3] { + let m = &p.masters[0]; + [m.title_style.clone(), m.body_style.clone(), m.other_style.clone()] + }; + assert_ne!(defaults(&p), defaults(&plain_master)); + let mut cut = style_atom([title; 5], 0x13); + cut.truncate(16 + 400); + let cut = import(&stream(environment_with(&[styles(&[cut])]))).unwrap(); + assert_eq!(defaults(&cut), defaults(&plain_master)); } /// A shape with text is a text box with no fill or line of its own; a shape without text isn't @@ -691,8 +887,13 @@ fn hostile_text_never_panics() { BODY, ); s.objects = vec![shape_95(bx, Some(two)), placeholder_95(0x0C, 0, 0, bx, Some(simple_text(b"T", bx, BODY)))]; - let objects = [placeholder_95(6, 0, 2, bx, Some(simple_text(b"*", bx, MASTER_BODY)))]; - let stream = stream_of(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], &objects)]); + let objects = [ + placeholder_95(6, 0, 2, bx, Some(simple_text(b"*", bx, MASTER_BODY))), + placeholder_95(2, 0, 1, bx, Some(text(b"B", &[plain(2)], &[spaced_run(2, true, 0x95, 3, 0, [150, -12, 20])], 0, [0; 4], MASTER_BODY))), + ]; + let level = Level { spacing: [150, -36, 20], align: 3, ..LEVEL }; + let env = environment_with(&[styles(&[style_atom([level; 5], 0x13), style_atom([level; 5], 0x21)])]); + let stream = stream_with(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], &objects)], env); for at in (0..stream.len() - 4).step_by(4) { for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF] { let mut d = stream.clone(); @@ -760,6 +961,59 @@ fn check_sample(name: &str, p: &Presentation) { } "align" => assert_eq!(paras(0, 0).iter().map(|p| p.props.align).collect::>(), [Some(Align::Left), Some(Align::Right)]), "twopara" => assert_eq!(body_of(&shapes(0)[0]).text(), "One\nTwo"), + _ => check_text_extras(name, p), + } +} + +/// The round 8 samples: spacing, justified text, anchoring, word wrap and the master's styles. +fn check_text_extras(name: &str, p: &Presentation) { + let m = &p.masters[0]; + let shapes = |i: usize| &p.slides[i].shapes; + let paras = |i: usize, j: usize| &body_of(&shapes(i)[j]).paragraphs; + match name { + "ls15" | "ls2" | "lspts" | "sb1" | "sbpts" | "sa05" | "sapts" => { + let p = ¶s(0, 0)[0].props; + let want = match name { + "ls15" => (Spacing::Pct(1.5), Spacing::Pct(0.5), Spacing::Pct(0.0)), + "ls2" => (Spacing::Pct(2.0), Spacing::Pct(0.5), Spacing::Pct(0.0)), + "lspts" => (Spacing::Pts(36.0), Spacing::Pct(0.5), Spacing::Pct(0.0)), + "sb1" => (Spacing::Pct(1.0), Spacing::Pct(1.0), Spacing::Pct(0.0)), + "sbpts" => (Spacing::Pct(1.0), Spacing::Pts(12.0), Spacing::Pct(0.0)), + "sa05" => (Spacing::Pct(1.0), Spacing::Pct(0.5), Spacing::Pct(0.5)), + _ => (Spacing::Pct(1.0), Spacing::Pct(0.5), Spacing::Pts(6.0)), + }; + assert_eq!((p.line_spacing, p.space_before, p.space_after), (Some(want.0), Some(want.1), Some(want.2)), "{name}"); + } + "justify" => assert!(paras(0, 0).iter().all(|p| p.props.align == Some(Align::Justify))), + "atop" | "amid" | "abot" | "atopc" | "amidc" | "abotc" | "btop" | "bmid" | "bbot" | "bmidc" => { + let s = if name.starts_with('a') { &shapes(0)[0] } else { &shapes(1)[1] }; + let b = &body_of(s).body; + let v = if name.contains("mid") { + Anchor::Middle + } else if name.contains("bot") { + Anchor::Bottom + } else { + Anchor::Top + }; + assert_eq!((b.anchor, b.anchor_ctr), (Some(v), Some(name.ends_with('c'))), "{name}"); + } + "anowrap" => assert_eq!(body_of(&shapes(0)[0]).body.wrap, Some(false)), + "gmbase" | "gmtitle" | "gmtleft" | "gmbsize" | "gmbjust" | "gmbspace" => { + let (t, b) = (m.title_style.level(0).unwrap(), m.body_style.level(1).unwrap()); + let title = if name == "gmtitle" { (Some(54.0), Some(true)) } else { (Some(44.0), Some(false)) }; + assert_eq!((t.run.size, t.run.bold), title, "{name}"); + assert_eq!(t.para.align, Some(if name == "gmtleft" { Align::Left } else { Align::Center }), "{name}"); + assert_eq!(b.run.size, Some(if name == "gmbsize" { 36.0 } else { 28.0 }), "{name}"); + assert_eq!(b.para.bullet, Some(Bullet::Char { char: "–".into() }), "{name}"); + assert_eq!(b.para.align, Some(if name == "gmbjust" { Align::Justify } else { Align::Left }), "{name}"); + let spacing = if name == "gmbspace" { (Spacing::Pct(1.5), Spacing::Pts(6.0)) } else { (Spacing::Pct(1.0), Spacing::Pct(0.0)) }; + assert_eq!((b.para.line_spacing, b.para.space_after), (Some(spacing.0), Some(spacing.1)), "{name}"); + assert_eq!(b.para.space_before, Some(Spacing::Pct(0.2)), "{name}"); + // The slide's body carries the same formatting as the master's level. + let level2 = ¶s(1, 1)[1]; + assert_eq!((level2.level, level2.runs[0].props.size), (1, b.run.size), "{name}"); + assert_eq!(level2.props.line_spacing, b.para.line_spacing, "{name}"); + } "textbox" => { let s = &shapes(0)[0]; assert_eq!((body_of(s).text(), s.text_box, s.ph.is_none()), ("Box".into(), true, true)); diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index d3d97dba7..cb0035722 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -7,13 +7,17 @@ //! Windows-1252 bytes, `\r` between paragraphs), then three 2028 containers, each holding a 2030 //! atom of fixed-size entries: character runs (tag 0x2f, 44 bytes), paragraph runs (0x30, 72 //! bytes) and one entry for the whole text (0x31, not read). Each set of runs covers the text and -//! one more character, the last paragraph's end. +//! one more character, the last paragraph's end. The text atom's +4 flags hold word wrap (bit 2), +//! and its +8 byte the anchoring: bits 4–5 top, middle or bottom, bit 1 clear for centred across. //! //! The Environment (1010) holds the fonts (2005) and the rulers (4016) as lists of slots: each //! slot is what comes before a 2017 record, and an empty slot holds a 2018. A run's font and a -//! text's ruler are slot numbers. +//! text's ruler are slot numbers. It also holds the master's text styles: a 1028 container of +//! 4052 atoms, one per text type (0 title, 1 body, 2 notes, 4 other), each five levels of +//! character formatting (24 bytes from +16) and five of paragraph formatting (52 bytes from +//! +160), laid out as in the runs. Slide text carries its formatting in full, as copies of these. -use craft_pptx::text::{Align, Anchor, BodyProps, Bullet, ParaProps, RunKind}; +use craft_pptx::text::{Align, Anchor, BodyProps, Bullet, LevelStyle, ListStyle, ParaProps, RunKind, Spacing}; use craft_pptx::{ColorRef, Fill, Paragraph, Rgba, Run, RunProps, TextBody}; use super::{MU, RGB_GIVEN, Rec}; @@ -36,6 +40,8 @@ mod rt { pub const RUNS: u32 = 4064; pub const MASTER_TEXT_BODY: u32 = 4068; pub const RULER: u32 = 4069; + pub const STYLES: u32 = 1028; + pub const STYLE: u32 = 4052; } /// The fourth words telling a text's atoms apart. @@ -47,6 +53,21 @@ mod tag { const CHAR_RUN: usize = 44; const PARA_RUN: usize = 72; +/// Where a character run's formatting starts (its font), and a paragraph run's (its bullet flag). +const CHAR_AT: usize = 20; +const PARA_AT: usize = 20; +/// A master style's levels: character formatting from +16, 24 bytes each, and paragraph +/// formatting from +160, 52 bytes each. +const STYLE_CHARS: usize = 16; +const STYLE_CHAR: usize = 24; +const STYLE_PARAS: usize = 160; +const STYLE_PARA: usize = 52; +/// The master styles read: text types 0 to 8. +const STYLE_TYPES: usize = 9; +/// The text types whose styles the master's title, body and other styles take. +pub(super) const TITLE: usize = 0; +pub(super) const BODY: usize = 1; +pub(super) const OTHER: usize = 4; /// Characters read from one text at most: far beyond what PowerPoint 95 puts in a shape, so a /// huge character atom can't make a huge text body. pub(super) const MAX_CHARS: usize = 1 << 20; @@ -63,6 +84,8 @@ type Ruler = [(i32, i32); LEVELS]; pub(super) struct Env { fonts: Vec>, rulers: Vec>, + /// The master's text styles by text type: each level's character and paragraph formatting. + styles: Vec>, } impl Env { @@ -77,10 +100,40 @@ impl Env { .unwrap_or_default(); let rulers = environment.child(rt::RULERS).map(|list| slots(&list, rt::RULER, |r| r.child(rt::RULER_ATOM).map(|a| ruler(&a)))).unwrap_or_default(); - Env { fonts, rulers } + let styles = environment + .child(rt::STYLES) + .map(|list| list.children().filter(|r| r.kind == rt::STYLE).take(STYLE_TYPES).map(|r| style(&r)).collect()) + .unwrap_or_default(); + Env { fonts, rulers, styles } } } +/// A master style atom's five levels, when the atom holds them all. +fn style(r: &Rec) -> Option<[(CharRun, ParaRun); LEVELS]> { + let b = r.data.get(..STYLE_PARAS + LEVELS * STYLE_PARA)?; + Some(std::array::from_fn(|i| (char_run(b, STYLE_CHARS + i * STYLE_CHAR, 0), para_run(b, STYLE_PARAS + i * STYLE_PARA, 0)))) +} + +/// The master's style for text type `ty` as a list style. `ruler` is the ruler slot of the +/// master's placeholder holding that text, which gives each level's margins. `None` when the +/// file has no such style. +pub(super) fn master_style(env: &Env, scheme: &Scheme, ty: usize, ruler: Option) -> Option { + let levels = env.styles.get(ty)?.as_ref()?; + let ruler = ruler.and_then(|i| env.rulers.get(i as usize)).copied().flatten(); + let mut ls = ListStyle::default(); + for (i, (c, p)) in (0u8..).zip(levels) { + let para = para_props(Some(p), ruler.as_ref().and_then(|r| r.get(usize::from(i)))); + ls.set(i, LevelStyle { para, run: run_props(c, env, scheme) }); + } + Some(ls) +} + +/// The ruler slot a text container's body names. +pub(super) fn ruler_slot(container: &Rec) -> Option { + let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?; + body.child(rt::RULER_REF)?.u32(0) +} + /// A slot list's entries of `kind`, read by `read`: an entry is the slot of the 2017 records /// before it. fn slots(list: &Rec, kind: u32, read: impl Fn(&Rec) -> Option) -> Vec> { @@ -116,6 +169,7 @@ fn ruler(a: &Rec) -> Ruler { } /// A character run: its length and the formatting it gives in full. +#[derive(Clone, Copy)] struct CharRun { len: u32, font: u16, @@ -125,12 +179,44 @@ struct CharRun { } /// A paragraph run. +#[derive(Clone, Copy)] struct ParaRun { len: u32, bullet: bool, bullet_char: u8, align: u8, level: u8, + /// Line spacing, space before and after: a percentage of a line, or minus a size in points. + line: Option, + before: Option, + after: Option, +} + +/// A character run's formatting from `at` (its font): font, size, style bits, then the colour. +fn char_run(e: &[u8], at: usize, len: u32) -> CharRun { + CharRun { + len, + font: u16_at(e, at), + size: u16_at(e, at + 4), + style: u16_at(e, at + 8), + color: [0, 1, 2, 3].map(|k| e.get(at + 10 + k).copied().unwrap_or(0)), + } +} + +/// A paragraph run's formatting from `at` (its bullet flag): the bullet character at +6, the +/// level at +24, the alignment at +28, then line spacing, space before and space after. +fn para_run(e: &[u8], at: usize, len: u32) -> ParaRun { + let i32_at = |k: usize| crate::record::u32_at(e, at + k).map(|v| v as i32); + ParaRun { + len, + bullet: e.get(at).is_some_and(|&b| b != 0), + bullet_char: e.get(at + 6).copied().unwrap_or(0), + level: e.get(at + 24).copied().unwrap_or(0), + align: e.get(at + 28).copied().unwrap_or(0), + line: i32_at(32), + before: i32_at(36), + after: i32_at(40), + } } fn u16_at(b: &[u8], at: usize) -> u16 { @@ -190,30 +276,39 @@ pub(super) fn text_body(container: &Rec, env: &Env, scheme: &Scheme, shape: Opti .map(|r| entries(&r, tag::CHAR_RUNS, CHAR_RUN, total)) .unwrap_or_default() .into_iter() - .map(|e| CharRun { - len: u32_at(e, 0), - font: u16_at(e, 20), - size: u16_at(e, 24), - style: u16_at(e, 28), - color: [e.get(30), e.get(31), e.get(32), e.get(33)].map(|b| b.copied().unwrap_or(0)), - }) + .map(|e| char_run(e, CHAR_AT, u32_at(e, 0))) .collect(); let para_runs: Vec = runs .map(|r| entries(&r, tag::PARA_RUNS, PARA_RUN, total)) .unwrap_or_default() .into_iter() - .map(|e| ParaRun { - len: u32_at(e, 0), - bullet: e.get(20).is_some_and(|&b| b != 0), - bullet_char: e.get(26).copied().unwrap_or(0), - align: e.get(48).copied().unwrap_or(0), - level: e.get(44).copied().unwrap_or(0), - }) + .map(|e| para_run(e, PARA_AT, u32_at(e, 0))) .collect(); let ruler = body.child(rt::RULER_REF).and_then(|r| r.u32(0)).and_then(|i| env.rulers.get(i as usize)).copied().flatten(); let mut props = BodyProps::default(); - if let (Some(atom), Some([l, t, r, b])) = (body.child(rt::TEXT_ATOM), shape) { + if text_box { + props.anchor = Some(Anchor::Top); + props.wrap = Some(true); + } + let atom = body.child(rt::TEXT_ATOM); + if let Some(flags) = atom.and_then(|a| a.u8(4)) { + props.wrap = Some(flags & 4 != 0); + } + if let Some(a) = atom.and_then(|a| a.u8(8)) { + // Bits 4–5: top, middle or bottom; bit 1 clear: centred across. Bit 0 is always set. + let anchor = match (a >> 4) & 3 { + 0 => Some(Anchor::Top), + 1 => Some(Anchor::Middle), + 2 => Some(Anchor::Bottom), + _ => None, + }; + if anchor.is_some() { + props.anchor = anchor; + props.anchor_ctr = Some(a & 2 == 0); + } + } + if let (Some(atom), Some([l, t, r, b])) = (atom, shape) { // The text rectangle, inside the shape's box. let inset = |from: i32, to: Option, sign: f64| { to.map(|to| (f64::from(to) - f64::from(from)) * sign / MU).filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) @@ -223,10 +318,6 @@ pub(super) fn text_body(container: &Rec, env: &Env, scheme: &Scheme, shape: Opti props.inset_r = inset(r, atom.i32(28), -1.0); props.inset_b = inset(b, atom.i32(32), -1.0); } - if text_box { - props.anchor = Some(Anchor::Top); - props.wrap = Some(true); - } Some(TextBody { body: props, paragraphs: paragraphs(&chars, &char_runs, ¶_runs, ruler.as_ref(), env, scheme), ..Default::default() }) } @@ -288,7 +379,14 @@ fn run_props(r: &CharRun, env: &Env, scheme: &Scheme) -> RunProps { } } -/// A paragraph run's alignment and bullet, and the margins its level has in the text's ruler. +/// A paragraph run's spacing: a percentage of a line when positive, else minus a size in points. +/// Bounded, so a hostile value can't push text off any page. +fn spacing(v: i32) -> Spacing { + if v >= 0 { Spacing::Pct((f64::from(v) / 100.0).min(100.0)) } else { Spacing::Pts((-f64::from(v)).min(4000.0)) } +} + +/// A paragraph run's alignment, spacing and bullet, and the margins its level has in the text's +/// ruler. fn para_props(r: Option<&ParaRun>, level: Option<&(i32, i32)>) -> ParaProps { let mut p = ParaProps::default(); if let Some(r) = r { @@ -296,8 +394,12 @@ fn para_props(r: Option<&ParaRun>, level: Option<&(i32, i32)>) -> ParaProps { 0 => Some(Align::Left), 1 => Some(Align::Center), 2 => Some(Align::Right), + 3 => Some(Align::Justify), _ => None, }; + p.line_spacing = r.line.map(spacing); + p.space_before = r.before.map(spacing); + p.space_after = r.after.map(spacing); p.bullet = Some(if r.bullet { let c = if r.bullet_char >= 0x20 { craft_codepage::cp1252(r.bullet_char) } else { '•' }; Bullet::Char { char: c.to_string() } From e031ad06a051d9156ee4b1ad167728b56e682e96 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 00:53:23 -0500 Subject: [PATCH 3/8] ppt95: bound the paragraphs and runs text makes; a centred master title takes its ruler Each paragraph is about 4 KB and each run about 2 KB, so a text atom of nothing but paragraph or line breaks made gigabytes from a megabyte of file. The document's text now makes at most 65,536 of them together and leaves the rest out, with a warning. A master's title placeholder of type 0x0F (a centred title) is in the title family, but only a plain title set the title style's ruler. --- crates/ppt-binary/src/ppt95.rs | 2 +- crates/ppt-binary/src/ppt95/tests.rs | 35 ++++++++++++++++++++++++++++ crates/ppt-binary/src/ppt95/text.rs | 27 ++++++++++++++++++++- 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 3ce2f6ad8..ae4e1f088 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -339,7 +339,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { if let Some(kind) = o.ph.as_ref().map(|ph| ph.kind).filter(|k| !placed.iter().any(|d| same_family(*d, *k))) { placed.push(kind); match kind { - PhType::Title => title_ruler = o.ruler, + PhType::Title | PhType::CtrTitle => title_ruler = o.ruler, PhType::Body => body_ruler = o.ruler, _ => {} } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 97261870c..e948b700b 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -799,6 +799,25 @@ fn the_masters_text_styles_are_read() { assert_eq!(defaults(&cut), defaults(&plain_master)); } +/// A master whose title placeholder is a centred title (PowerPoint 95 type 0x0F) gives the title +/// style its ruler's margins, as a plain title does. +#[test] +fn a_masters_centred_title_gives_the_title_style_its_ruler() { + let title = placeholder_95( + 0x0F, + 0, + 0, + [-2448, -1776, 2448, -1056], + Some(text(b"T", &[plain(2)], &[para_run(2, false, 0, 1, 0)], 3, [0; 4], MASTER_BODY)), + ); + let atoms = [style_atom([LEVEL; 5], 0x13)]; + let stream = + stream_with(document_atom(5760, 4320, 0), &[], &[master_with(MASTER, DEFAULT, [0; 4], &[title])], environment_with(&[styles(&atoms)])); + let t = import(&stream).unwrap().masters[0].title_style.level(0).cloned().unwrap(); + // The wide ruler (slot 3): level 1 at 576 units, its first line at 288. + assert_eq!((t.para.margin_left, t.para.indent), (Some(72.0), Some(-36.0))); +} + /// A shape with text is a text box with no fill or line of its own; a shape without text isn't /// read yet; a placeholder of a type PowerPoint 95 isn't known to write keeps its text as a text /// box. @@ -876,6 +895,22 @@ fn text_is_windows_1252() { /// Damaged text never panics and stays bounded: runs past the text, huge run lengths and counts, /// truncated entries, control characters, empty text, and a character atom past the cap. +/// Paragraphs and runs are about 4 and 2 KB each, so the document's text makes at most +/// [`super::text::MAX_TEXT_ITEMS`] of them together, across all its shapes; text past that is +/// left out. +#[test] +fn text_makes_a_bounded_number_of_paragraphs_and_runs() { + let bx = [0, 0, 1000, 1000]; + // 40,000 one-letter paragraphs, a paragraph and a run each: 80,000 items in one shape. + let many = [b'a', 13].repeat(40_000); + let p = deck_of(vec![shape_95(bx, Some(simple_text(&many, bx, BODY))), shape_95(bx, Some(simple_text(b"after", bx, BODY)))], &[]); + let items: usize = p.slides[0].shapes.iter().filter_map(|s| s.text.as_ref()).flat_map(|t| &t.paragraphs).map(|para| 1 + para.runs.len()).sum(); + assert_eq!(items, super::text::MAX_TEXT_ITEMS); + let first = body_of(&p.slides[0].shapes[0]); + assert_eq!((first.paragraphs.len(), first.paragraphs[0].runs[0].text.as_str()), (super::text::MAX_TEXT_ITEMS / 2, "a")); + assert!(!texts(&p).iter().any(|t| t == "after"), "the budget is the document's, not each shape's"); +} + #[test] fn hostile_text_never_panics() { let bx = [0, 0, 1000, 1000]; diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index cb0035722..0059dad56 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -17,6 +17,8 @@ //! character formatting (24 bytes from +16) and five of paragraph formatting (52 bytes from //! +160), laid out as in the runs. Slide text carries its formatting in full, as copies of these. +use std::cell::Cell; + use craft_pptx::text::{Align, Anchor, BodyProps, Bullet, LevelStyle, ListStyle, ParaProps, RunKind, Spacing}; use craft_pptx::{ColorRef, Fill, Paragraph, Rgba, Run, RunProps, TextBody}; @@ -71,6 +73,10 @@ pub(super) const OTHER: usize = 4; /// Characters read from one text at most: far beyond what PowerPoint 95 puts in a shape, so a /// huge character atom can't make a huge text body. pub(super) const MAX_CHARS: usize = 1 << 20; +/// Paragraphs and runs made from the whole document's text at most. Each is about 2 to 4 KB, so +/// a text of nothing but paragraph or line breaks would otherwise make gigabytes from a megabyte +/// of file. That is far more than any PowerPoint 95 file probed holds. +pub(super) const MAX_TEXT_ITEMS: usize = 1 << 16; /// Font and ruler slots read at most. const MAX_SLOTS: usize = 4096; /// Indent levels: PowerPoint 95 has five. @@ -86,9 +92,22 @@ pub(super) struct Env { rulers: Vec>, /// The master's text styles by text type: each level's character and paragraph formatting. styles: Vec>, + /// Paragraphs and runs made so far, against [`MAX_TEXT_ITEMS`]. + items: Cell, } impl Env { + /// Counts one more paragraph or run; `false` once the document's text has made + /// [`MAX_TEXT_ITEMS`], when the rest of its text is left out. + fn take_item(&self) -> bool { + let n = self.items.get(); + if n == MAX_TEXT_ITEMS { + log::warn!("ppt: PowerPoint 95 text passes {MAX_TEXT_ITEMS} paragraphs and runs; the rest is left out"); + } + self.items.set(n.saturating_add(1)); + n < MAX_TEXT_ITEMS + } + pub(super) fn new(document: &Rec) -> Env { let Some(environment) = document.child(rt::ENVIRONMENT) else { return Env::default() }; // There may be more than one font list; the first that holds fonts is the table. @@ -104,7 +123,7 @@ impl Env { .child(rt::STYLES) .map(|list| list.children().filter(|r| r.kind == rt::STYLE).take(STYLE_TYPES).map(|r| style(&r)).collect()) .unwrap_or_default(); - Env { fonts, rulers, styles } + Env { fonts, rulers, styles, items: Cell::new(0) } } } @@ -329,12 +348,18 @@ fn paragraphs(chars: &[char], char_runs: &[CharRun], para_runs: &[ParaRun], rule let mut out = vec![]; let mut start = 0usize; loop { + if !env.take_item() { + break; + } let end = chars.get(start..).and_then(|rest| rest.iter().position(|&c| c == '\r')).map_or(total, |e| start + e); let pr = run_at(¶_starts, start).and_then(|i| para_runs.get(i)); let level = pr.map_or(0, |r| r.level.min(LEVELS as u8 - 1)); let mut para = Paragraph { level, props: para_props(pr, ruler.and_then(|r| r.get(usize::from(level)))), ..Default::default() }; let mut i = start; while i < end { + if !env.take_item() { + break; + } let props = props_at(i); if chars.get(i) == Some(&'\u{b}') { para.runs.push(Run { text: String::new(), props, kind: RunKind::Break }); From bf729d6d0207cd64fab0730a0d4b42b8ca819131 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 01:01:49 -0500 Subject: [PATCH 4/8] ppt95: skip runs of no characters; the font table is the first list with a face A zero-length run counted as one character of coverage, so a few of them used up the runs read and a real run after them was never reached. A font list whose only face atom was cut short gave an empty face and still won over a later list with real faces. --- crates/ppt-binary/src/ppt95/tests.rs | 28 +++++++++++++++++++++++++++- crates/ppt-binary/src/ppt95/text.rs | 11 ++++++++--- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index af2e8237e..902c97d47 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -660,6 +660,32 @@ fn a_bulleted_body_keeps_levels_bullets_and_margins() { /// Character runs: bold, italic and underline bits, the font by slot, the size, and an RGB or a /// scheme slot of the slide's scheme as the colour. +/// A run of no characters is skipped: it neither formats the text nor uses up the runs read, so a +/// run after it still formats the text. +#[test] +fn zero_length_runs_are_skipped() { + let runs = [plain(0), plain(0), plain(0), plain(0), char_run(4, 1, 40, 1, [0, 0, 0, 1])]; + let body = text(b"abc", &runs, &[para_run(0, false, 0, 2, 0), para_run(4, false, 0, 1, 0)], 1, [0; 4], BODY); + let p = deck_of(vec![shape_95([-2362, -1613, -518, -1325], Some(body))], &[]); + let para = &body_of(&p.slides[0].shapes[0]).paragraphs[0]; + let r = ¶.runs[0].props; + assert_eq!((para.runs[0].text.as_str(), r.font.as_deref(), r.size, r.bold), ("abc", Some("Arial"), Some(40.0), Some(true))); + assert_eq!(para.props.align, Some(Align::Center)); +} + +/// The font table is the first font list holding a face: a list whose only face is cut short +/// gives way to a later one. +#[test] +fn the_font_table_is_the_first_list_with_a_face() { + let cut = container(4022, 9, &[rec(4023, 0, 0, &[0; 8])]); + let lists = [container(2005, 0x19, &[cut, slot_end(0)]), container(2005, 0x19, &[font(b"Arial"), slot_end(0)])]; + let mut s = SlideSpec::new(0x100, 16); + s.objects = vec![shape_95([-2362, -1613, -518, -1325], Some(simple_text(b"Hi", [-2362, -1613, -518, -1325], BODY)))]; + let stream = stream_with(document_atom(5760, 4320, 1), &[slide(&s)], &[master(MASTER, DEFAULT, [0; 4])], container(1010, 0x15, &lists)); + let p = import(&stream).unwrap(); + assert_eq!(body_of(&p.slides[0].shapes[0]).paragraphs[0].runs[0].props.font.as_deref(), Some("Arial")); +} + #[test] fn character_runs_keep_their_formatting() { let runs = [ @@ -931,7 +957,7 @@ fn hostile_text_never_panics() { let t = one(text(b"Hi", &[plain(1000)], &[para_run(u32::MAX, true, 0, 7, 200)], 1, [0; 4], BODY)).unwrap(); assert_eq!(t.text(), "Hi"); assert_eq!(t.paragraphs[0].level, 4, "the level is capped at PowerPoint 95's fifth"); - // Many zero-length runs: no more are read than the text has characters (plus its end). + // Many zero-length runs: skipped, and the text is all there. let many = vec![plain(0); 100_000]; let t = one(text(b"abc", &many, &vec![para_run(0, false, 0, 0, 0); 50_000], 1, [0; 4], BODY)).unwrap(); assert_eq!(t.text(), "abc"); diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index 0059dad56..eb6bbf0bc 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -110,12 +110,12 @@ impl Env { pub(super) fn new(document: &Rec) -> Env { let Some(environment) = document.child(rt::ENVIRONMENT) else { return Env::default() }; - // There may be more than one font list; the first that holds fonts is the table. + // There may be more than one font list; the first that holds a face is the table. let fonts = environment .children() .filter(|r| r.kind == rt::FONTS) .map(|list| slots(&list, rt::FONT, |f| f.child(rt::FONT_ATOM).map(|a| face(&a)))) - .find(|f| f.iter().any(Option::is_some)) + .find(|f| f.iter().flatten().any(|face| !face.is_empty())) .unwrap_or_default(); let rulers = environment.child(rt::RULERS).map(|list| slots(&list, rt::RULER, |r| r.child(rt::RULER_ATOM).map(|a| ruler(&a)))).unwrap_or_default(); @@ -257,7 +257,12 @@ fn entries<'a>(runs: &Rec<'a>, kind: u32, size: usize, total: u32) -> Vec<&'a [u if covered >= total { return out; } - covered = covered.saturating_add(u32_at(e, 0).max(1)); + // A run of no characters formats nothing, so it is skipped rather than counted. + let len = u32_at(e, 0); + if len == 0 { + continue; + } + covered = covered.saturating_add(len); out.push(e); } } From c9eba77824e20094f4aaa825f1e487e05f0abaca Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 01:49:15 -0500 Subject: [PATCH 5/8] ppt-binary: a paragraph's end mark keeps the formatting at its CR, on both paths Both paths gave a paragraph's end mark the formatting of its first character. PowerPoint reads it from the character run at the CR (or at the text's end for the last paragraph): a .ppt PowerPoint 16 saved, with 'AB\rCD' at 24 pt and only the first CR at 40, opens with that paragraph's endParaRPr at 40. PowerPoint 95 gives the CR a run of its own when it differs, so its path reads the same position. --- crates/ppt-binary/src/convert.rs | 4 +++- crates/ppt-binary/src/ppt95/tests.rs | 23 +++++++++++++++++++++ crates/ppt-binary/src/ppt95/text.rs | 4 +++- crates/ppt-binary/src/tests.rs | 30 ++++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 2 deletions(-) diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs index 9e6fa2089..fc2098534 100644 --- a/crates/ppt-binary/src/convert.rs +++ b/crates/ppt-binary/src/convert.rs @@ -939,7 +939,9 @@ impl<'a> Ctx<'a> { para.runs.push(Run::with(String::from_utf16_lossy(&units), props)); i = j; } - para.end_props = first; + // The paragraph mark's own formatting, as PowerPoint reads it: the character run at the + // CR, or at the text's end for the last paragraph. + para.end_props = self.run_props(&cf_at(end), &scope.scheme); para.normalize(); out.push(para); if end >= total { diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 902c97d47..2e3b0ba82 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -686,6 +686,23 @@ fn the_font_table_is_the_first_list_with_a_face() { assert_eq!(body_of(&p.slides[0].shapes[0]).paragraphs[0].runs[0].props.font.as_deref(), Some("Arial")); } +/// A paragraph's end mark keeps the formatting of the character run at its CR, which PowerPoint 95 +/// gives a run of its own when it differs (`endmark`, `endmark2`): not that of the paragraph's +/// first character. +#[test] +fn a_paragraphs_end_mark_keeps_the_formatting_at_its_cr() { + let end_sizes = |runs: &[(u32, u16)]| { + let runs: Vec<_> = runs.iter().map(|&(n, size)| char_run(n, 0, size, 0, [0, 0, 0, 1])).collect(); + let body = text(b"AB\rCD", &runs, &[para_run(5, false, 0, 0, 0)], 1, [0; 4], BODY); + let p = deck_of(vec![shape_95([-2362, -1613, -518, -1325], Some(body))], &[]); + body_of(&p.slides[0].shapes[0]).paragraphs.iter().map(|para| para.end_props.size).collect::>() + }; + // What PowerPoint 95 wrote for "AB\rCD" at 40 pt with A and C at 24, and at 24 with the first + // CR at 40. + assert_eq!(end_sizes(&[(1, 24), (2, 40), (1, 24), (1, 40)]), [Some(40.0), Some(40.0)]); + assert_eq!(end_sizes(&[(2, 24), (1, 40), (2, 24)]), [Some(40.0), Some(24.0)]); +} + #[test] fn character_runs_keep_their_formatting() { let runs = [ @@ -1025,6 +1042,12 @@ fn check_sample(name: &str, p: &Presentation) { let paras = |i: usize, j: usize| &body_of(&shapes(i)[j]).paragraphs; let first_run = |i: usize, j: usize| ¶s(i, j)[0].runs[0]; match name { + // "AB\rCD" at 40 pt with A and C at 24; at 24 with the first CR at 40 (Font.Points). + "endmark" | "endmark2" => { + let ends: Vec<_> = body_of(&p.slides[0].shapes[0]).paragraphs.iter().map(|q| q.end_props.size).collect(); + let want = if name == "endmark" { [Some(40.0), Some(40.0)] } else { [Some(40.0), Some(24.0)] }; + assert_eq!(ends, want, "{name}"); + } "twoslides" => assert_eq!(p.slides.len(), 2), "title" => { assert_eq!(layout_kind(p, 1), LayoutType::Title); diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index eb6bbf0bc..3e31e8b71 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -382,7 +382,9 @@ fn paragraphs(chars: &[char], char_runs: &[CharRun], para_runs: &[ParaRun], rule para.runs.push(Run::with(text, props)); i = j; } - para.end_props = props_at(start); + // The paragraph mark's own formatting: the character run at the CR (PowerPoint 95 gives + // it one of its own when it differs), or the last run for the last paragraph. + para.end_props = props_at(end); para.normalize(); out.push(para); if end >= total { diff --git a/crates/ppt-binary/src/tests.rs b/crates/ppt-binary/src/tests.rs index 7a9c6b286..29741127f 100644 --- a/crates/ppt-binary/src/tests.rs +++ b/crates/ppt-binary/src/tests.rs @@ -723,6 +723,36 @@ fn a_shadowed_run_keeps_its_shadow() { assert!(runs[1].props.shadow.is_none()); } +/// A paragraph's end mark keeps the formatting of the character run at its CR, not of the +/// paragraph's first character, as PowerPoint reads a .ppt PowerPoint saved: "AB\rCD" at 40 pt +/// with A and C at 24 ends each paragraph at 40; at 24 with only the first CR at 40, its first +/// paragraph ends at 40 and its second at 24. +#[test] +fn a_paragraphs_end_mark_keeps_the_formatting_at_its_cr() { + let end_sizes = |runs: &[(u32, u16)]| { + let mut style = vec![]; + style.extend_from_slice(&6u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + for (n, size) in runs { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&0x2_0000u32.to_le_bytes()); // mask: size + style.extend_from_slice(&size.to_le_bytes()); + } + let tb = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2049, 0xA00), anchor(0, 0, 1000, 1000), text_box(4, "AB\rCD", &[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(); + p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs.iter().map(|para| para.end_props.size).collect::>() + }; + assert_eq!(end_sizes(&[(1, 24), (2, 40), (1, 24), (2, 40)]), [Some(40.0), Some(40.0)]); + assert_eq!(end_sizes(&[(2, 24), (1, 40), (3, 24)]), [Some(40.0), Some(24.0)]); +} + /// `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. From f09e70f2810c598ada437b0feb549882d43705de Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:11:02 -0500 Subject: [PATCH 6/8] ppt-binary: a PowerPoint 95 slide cut off after its header is left out and named as lost PowerPoint 95 writes a slide's SlideAtom first. A slide record without one is what a file cut just after the slide's header leaves; it read as a blank slide, and import_checked reported nothing lost. It is now left out, as the PowerPoint 97 path leaves out the slides it lost, and named by its position. --- crates/ppt-binary/README.md | 3 ++- crates/ppt-binary/src/lib.rs | 2 +- crates/ppt-binary/src/ppt95.rs | 27 +++++++++++++++++++++------ crates/ppt-binary/src/ppt95/tests.rs | 13 +++++++++---- 4 files changed, 33 insertions(+), 12 deletions(-) diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 862cb6411..f8ee21861 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -38,7 +38,8 @@ PowerPoint 95 (7.0) files use the same compound file and many of the same record 16-byte record header and a single record tree with no edit chain. A file whose `PowerPoint Document` stream starts with that tree is read on its own path; anything else takes the PowerPoint 97 path. The tree's Document must hold its DocumentAtom, which counts the slides; -`import_checked` names the slides that count says a cut-short file is missing ("slide 3"). What +`import_checked` names the slides a cut-short file is missing ("slide 3"): those the count says it +should hold, and any cut off after its header, which is left out. What was learned of the format came from files PowerPoint 95 itself wrote, one feature per file, and the public [MS-PPT] numbering where the records keep it. diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index 6a06c658d..e1c52ef6e 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -78,7 +78,7 @@ pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presenta // PowerPoint 97 path, which refuses older formats as too old. if let Some(document) = ppt95::document(&stream) { let p = ppt95::convert(&document, defaults); - let lost = ppt95::lost(&document, &p); + let lost = ppt95::lost(&document); return Ok((p, lost)); } let current_user = file.read_path_capped("Current User", cap).unwrap_or_default(); diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 59b598199..a8c2540db 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -130,13 +130,28 @@ pub fn document(stream: &[u8]) -> Option> { Some(document) } -/// The slides the DocumentAtom counts but the file doesn't hold, by position ("slide 3"): what a -/// truncated file lost. Empty for a whole file. -pub fn lost(document: &Rec, p: &Presentation) -> Vec { +/// Whether a slide record holds what PowerPoint 95 writes first in every slide, its SlideAtom +/// (1007). One without it kept nothing (a file cut short just after the slide's header): it is left +/// out and named as lost. +fn kept(slide: &Rec) -> bool { + slide.child(rt::SLIDE_ATOM).is_some() +} + +/// The slides a truncated or damaged file lost, by position ("slide 3"): those listed without their +/// SlideAtom, and those the DocumentAtom counts past the ones listed. Empty for a whole file. +pub fn lost(document: &Rec) -> Vec { let count = document.child(rt::DOCUMENT_ATOM).and_then(|a| a.u32(SLIDE_COUNT)).map_or(0, |c| c as usize); - let read = p.slides.len(); + let listed: Vec = document + .children() + .filter(|r| r.kind == rt::LIST) + .flat_map(|list| list.children().filter(|r| r.kind == rt::SLIDE)) + .take(MAX_SLIDES) + .map(|r| kept(&r)) + .collect(); + let empty = listed.iter().enumerate().filter(|(_, k)| !**k).map(|(i, _)| i + 1); // At most as many as could have been read, so a damaged count can't make a huge list. - (read + 1..=count.min(read + MAX_SLIDES)).map(|n| format!("slide {n}")).collect() + let missing = listed.len() + 1..=count.min(listed.len() + MAX_SLIDES); + empty.chain(missing).map(|n| format!("slide {n}")).collect() } /// What a slide or master says about itself. @@ -231,7 +246,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { } let layouts: Vec<_> = p.masters.iter().map(|m| layout_table(m, &HashSet::new())).collect(); - for s in &slides { + for s in slides.iter().filter(|s| kept(&s.rec)) { // An unknown master is the first one. let (index, master_scheme) = by_id.get(&s.master_id).copied().unwrap_or((0, masters.first().and_then(|m| m.scheme).unwrap_or(DEFAULT_SCHEME))); diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 204ea5703..3d782f5a3 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -344,8 +344,7 @@ fn hostile_powerpoint_95_streams_never_panic() { assert_eq!(p.slides.len(), 1); assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0), "an out-of-range size falls back"); // Many slides stop at the limit. - let empty = rec(rt::SLIDE, NONE, 0x10, &[]); - let many = vec![empty; super::MAX_SLIDES + 5]; + let many = vec![slide(&SlideSpec::new(0x100, 0)); super::MAX_SLIDES + 5]; let p = import(&stream_of(document_atom(5760, 4320, 0), &many, &[])).unwrap(); assert_eq!(p.slides.len(), super::MAX_SLIDES); // Many masters stop at their own, lower limit: each is a copy of the default master. @@ -354,8 +353,9 @@ fn hostile_powerpoint_95_streams_never_panic() { assert_eq!(p.masters.len(), super::MAX_MASTERS); } -/// A file holding fewer slides than its DocumentAtom counts names the missing ones by position; -/// a whole file names none. +/// A file holding fewer slides than its DocumentAtom counts names the missing ones by position, +/// and so does one cut just after a slide's header, which leaves that slide out; a whole file +/// names none. #[test] fn slides_the_count_says_are_missing_are_named() { let one = slide(&SlideSpec::new(0x100, 16)); @@ -366,6 +366,11 @@ fn slides_the_count_says_are_missing_are_named() { assert!(checked(1).1.is_empty()); // A huge count names no more slides than the reader could have read. assert_eq!(checked(u32::MAX).1.len(), super::MAX_SLIDES); + // Two slides, the stream cut just after the second one's header (its stated length kept). + let two = stream_of(document_atom(5760, 4320, 2), &[one.clone(), one.clone()], &[]); + let second = two.windows(one.len()).rposition(|w| w == one).unwrap(); + let (p, lost) = crate::import_checked(&file_of(&two[..second + 16]), &AppDefaults).unwrap(); + assert_eq!((p.slides.len(), lost), (1, vec!["slide 2".to_string()])); } /// Real PowerPoint 95 files, when `CRAFT_PPT95_SAMPLES` names a directory of them (they are not in From ed6d273e05b3d0541595b01e16ebb451b8e4fcce Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:13:09 -0500 Subject: [PATCH 7/8] ppt-binary: an empty footer gives its look from its end mark; cap point spacing at DrawingML's The footer row's look came from its first run, so an empty footer, date or slide number placeholder (no runs once normalized) gave none. It now falls back to the paragraph's end mark. This is the shared helper, so both paths take it. PowerPoint 95 point spacing was capped at 4000 pt, but DrawingML holds at most 1584 and the writer clamps to that, so a larger value changed on export. It is now capped at 1584. --- crates/ppt-binary/src/convert.rs | 10 +++++----- crates/ppt-binary/src/ppt95/tests.rs | 16 +++++++++++++++- crates/ppt-binary/src/ppt95/text.rs | 6 +++++- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs index fc2098534..4c87cb996 100644 --- a/crates/ppt-binary/src/convert.rs +++ b/crates/ppt-binary/src/convert.rs @@ -180,7 +180,8 @@ pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Pr /// A main master's placeholder of `kind` at `x`: the box of the default master's placeholder of /// the same family. The footer row (date, footer, slide number) sits in the same place on every /// layout, with the master's look: `look` gives its first paragraph, whose alignment and first -/// run's size and colour the master's and layouts' footer placeholders take. `look` is called only +/// run's size and colour (its end mark's, when it is empty) the master's and layouts' footer +/// placeholders take. `look` is called only /// for the footer row, and only when the default master has such a placeholder. pub(crate) fn place_placeholder(master: &mut Master, kind: PhType, x: Xfrm, look: impl FnOnce() -> Option) { let Some(s) = master.shapes.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) else { return }; @@ -191,10 +192,9 @@ pub(crate) fn place_placeholder(master: &mut Master, kind: PhType, x: Xfrm, look 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()); - } + let first = p.runs.first().map_or(&p.end_props, |r| &r.props); + level.run.size = first.size.or(level.run.size); + level.run.fill = first.fill.clone().or(level.run.fill.take()); t.list_style.set(0, level); } }; diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 83d8c132e..02b109760 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -763,7 +763,7 @@ fn paragraphs_keep_their_spacing() { [ (Some(Spacing::Pct(1.5)), Some(Spacing::Pct(0.5)), Some(Spacing::Pct(0.0))), (Some(Spacing::Pts(36.0)), Some(Spacing::Pts(12.0)), Some(Spacing::Pts(6.0))), - (Some(Spacing::Pct(100.0)), Some(Spacing::Pts(4000.0)), Some(Spacing::Pts(1.0))), + (Some(Spacing::Pct(100.0)), Some(Spacing::Pts(1584.0)), Some(Spacing::Pts(1.0))), ] ); } @@ -931,6 +931,20 @@ fn master_placeholders_move_the_layout_boxes() { assert_eq!(own, ["Logo"]); } +/// An empty footer on the master still gives every layout's footer its size and colour: those of +/// its end mark. +#[test] +fn an_empty_footer_keeps_its_look() { + let empty = text(b"", &[char_run(1, 0, 10, 0, [0xFF, 0, 0, 0xFE])], &[para_run(1, false, 0, 2, 0)], 1, [0; 4], MASTER_BODY); + let p = deck_of(vec![], &[placeholder_95(8, 1, 2, [-816, 1776, 816, 2064], Some(empty))]); + for l in &p.masters[0].layouts { + let footer = l.shapes.iter().find(|s| s.ph_type() == Some(PhType::Footer)).unwrap(); + let level = body_of(footer).list_style.level(0).unwrap(); + assert_eq!((level.para.align, level.run.size), (Some(Align::Right), Some(10.0)), "{}", l.name); + assert_eq!(level.run.fill, Some(Fill::solid(ColorRef::rgb(Rgba::rgb(0xFF, 0, 0)))), "{}", l.name); + } +} + /// The characters, a font's face and a bullet character are Windows-1252, 0x80–0x9F included. #[test] fn text_is_windows_1252() { diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index 3e31e8b71..a1af4afd9 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -411,10 +411,14 @@ fn run_props(r: &CharRun, env: &Env, scheme: &Scheme) -> RunProps { } } +/// The most points of spacing DrawingML holds (its `spcPts` reaches 158400 hundredths), as the +/// writer clamps it, so an imported value survives export. +const MAX_SPACING_PTS: f64 = 1584.0; + /// A paragraph run's spacing: a percentage of a line when positive, else minus a size in points. /// Bounded, so a hostile value can't push text off any page. fn spacing(v: i32) -> Spacing { - if v >= 0 { Spacing::Pct((f64::from(v) / 100.0).min(100.0)) } else { Spacing::Pts((-f64::from(v)).min(4000.0)) } + if v >= 0 { Spacing::Pct((f64::from(v) / 100.0).min(100.0)) } else { Spacing::Pts((-f64::from(v)).min(MAX_SPACING_PTS)) } } /// A paragraph run's alignment, spacing and bullet, and the margins its level has in the text's From b122ba51dd96a93ffae18bc2fa539d19ad2ebcf1 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:23:13 -0500 Subject: [PATCH 8/8] ppt-binary: a PowerPoint 95 slide whose SlideAtom was cut short is lost too A stream cut just after the SlideAtom's header left an atom with no body, which counted as kept: the slide read blank and nothing was named lost. A slide is now kept only when its atom gives its id and its master's. --- crates/ppt-binary/src/ppt95.rs | 6 +++--- crates/ppt-binary/src/ppt95/tests.rs | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index a8c2540db..ae5d33207 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -131,10 +131,10 @@ pub fn document(stream: &[u8]) -> Option> { } /// Whether a slide record holds what PowerPoint 95 writes first in every slide, its SlideAtom -/// (1007). One without it kept nothing (a file cut short just after the slide's header): it is left -/// out and named as lost. +/// (1007), whole enough to give the slide's id and its master's. One without it kept nothing (a +/// file cut short just after the slide's header, or the atom's): it is left out and named as lost. fn kept(slide: &Rec) -> bool { - slide.child(rt::SLIDE_ATOM).is_some() + slide.child(rt::SLIDE_ATOM).and_then(|a| a.u32(4)).is_some() } /// The slides a truncated or damaged file lost, by position ("slide 3"): those listed without their diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 3d782f5a3..6588266ca 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -371,6 +371,11 @@ fn slides_the_count_says_are_missing_are_named() { let second = two.windows(one.len()).rposition(|w| w == one).unwrap(); let (p, lost) = crate::import_checked(&file_of(&two[..second + 16]), &AppDefaults).unwrap(); assert_eq!((p.slides.len(), lost), (1, vec!["slide 2".to_string()])); + // Cut just after its SlideAtom's header, or partway into the atom: still lost. + for cut in [32, 36] { + let (p, lost) = crate::import_checked(&file_of(&two[..second + cut]), &AppDefaults).unwrap(); + assert_eq!((p.slides.len(), lost), (1, vec!["slide 2".to_string()]), "cut at {cut}"); + } } /// Real PowerPoint 95 files, when `CRAFT_PPT95_SAMPLES` names a directory of them (they are not in