Merge branch 'ppt95-text' into ppt95-shapes

# Conflicts:
#	crates/ppt-binary/README.md
#	crates/ppt-binary/src/lib.rs
#	crates/ppt-binary/src/ppt95.rs
#	crates/ppt-binary/src/ppt95/tests.rs
This commit is contained in:
kiwi4boy committed 2026-11-20 00:29:58 -05:00
commit cfd19dcf87
5 files changed
+494 -69

No files matched your search

+23 -20
View File
@@ -43,26 +43,29 @@ 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 and lines read too: all 24 of PowerPoint 95's shapes (rectangle,
rounded rectangle, ellipse, diamond, the two triangles, parallelogram, trapezoid, hexagon,
octagon, plus, five-point star, the arrow and the thick arrow in their four directions, home plate,
cube, balloon and seal) as DrawingML presets with their adjust values (the trapezoid, wide at the
top in PowerPoint 95, as its own outline, so its text stays upright), each with its fill (or
none), its line (or none) with its colour, its width (the six line styles, 1 to 10 pt) and its
dots or dashes, and its shadow with the shadow's colour, offset and transparency; and lines from
their start to their end, with their arrowheads. A shape code no probe showed reads as a
rectangle. PowerPoint 95 measures angles counter-clockwise, DrawingML clockwise, so each is
negated. A shape's geometry holds its outline as drawn, quarter-turns and mirror included, so its
angle and flips come from there (a box turned by an odd number of quarter-turns is turned back);
the rectangle, rounded rectangle and ellipse take the angle the user set. A shape that draws
nothing but text is a text box. Freeforms read as custom paths through their points, in their
box, with their format's fill, line and shadow, and open ones with their arrowheads. Groups read as
groups of their members, which keep their places on the slide (PowerPoint 95 can't turn or flip
a group), nested up to 32 deep. Pictures, 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 and lines
read too: all 24 of PowerPoint 95's shapes (rectangle, rounded rectangle, ellipse, diamond, the
two triangles, parallelogram, trapezoid, hexagon, octagon, plus, five-point star, the arrow and
the thick arrow in their four directions, home plate, cube, balloon and seal) as DrawingML presets
with their adjust values (the trapezoid, wide at the top in PowerPoint 95, as its own outline, so
its text stays upright), each with its fill (or none), its line (or none) with its colour, its
width (the six line styles, 1 to 10 pt) and its dots or dashes, and its shadow with the shadow's
colour, offset and transparency; and lines from their start to their end, with their arrowheads.
A shape code no probe showed reads as a rectangle. PowerPoint 95 measures angles
counter-clockwise, DrawingML clockwise, so each is negated. A shape's geometry holds its outline
as drawn, quarter-turns and mirror included, so its angle and flips come from there (a box turned
by an odd number of quarter-turns is turned back); the rectangle, rounded rectangle and ellipse
take the angle the user set. A shape that draws nothing but text is a text box; a shape's text is
read as a text box's is. Freeforms read as custom paths through their points, in their box, with
their format's fill, line and shadow, and open ones with their arrowheads. Groups read as groups
of their members, which keep their places on the slide (PowerPoint 95 can't turn or flip a
group), nested up to 32 deep. Pictures and notes come later.
The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from:
its layouts and placeholders. The file's masters then place and style the placeholders that
+4 -4
View File
@@ -8,10 +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, placeholders and text
//! boxes with formatted text, and shapes and lines with their fill, line and shadow; their
//! 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, placeholders
//! and text boxes with formatted, anchored text, and shapes and lines with their fill, line and
//! shadow; their pictures and notes are not read yet.
//! 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)]
+48 -10
View File
@@ -7,8 +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, text
//! boxes, shapes, lines, freeforms and groups, with the text and its character and paragraph
//! formatting ([`text`]).
//! boxes, shapes, lines, freeforms and groups, with the text, its character and paragraph
//! formatting (spacing and justified alignment included) and its anchoring ([`text`]).
//!
//! A page's object list (3000) holds shapes (3008), placeholders (3010, which add a 3011 atom: the
//! type, the size, then the index), lines (3014), freeforms (3016) and groups (3001). A shape or
@@ -41,8 +41,11 @@
//! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path
//! does.
//!
//! Not read yet: 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: pictures and notes.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -258,6 +261,8 @@ struct Object {
ph: Option<Placeholder>,
xfrm: Xfrm,
text: Option<TextBody>,
/// The ruler slot its text names.
ruler: Option<u32>,
/// A shape's preset (a rectangle for a shape code no probe showed): `None` for a placeholder.
geom: Option<Geom>,
/// How a shape or line is drawn (a placeholder's is left to its layout).
@@ -319,7 +324,16 @@ impl Reader<'_> {
return None;
}
let members = self.list(&r.child(rt::LIST)?, depth + 1);
Some(Object { placeholder: false, ph: None, xfrm: Xfrm::default(), text: None, geom: None, look: Look::none(), kind: Kind::Group(members) })
Some(Object {
placeholder: false,
ph: None,
xfrm: Xfrm::default(),
text: None,
ruler: None,
geom: None,
look: Look::none(),
kind: Kind::Group(members),
})
}
}
@@ -348,7 +362,7 @@ fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option<Object> {
shape::arrowheads(&mut look.line, &heads);
}
let geom = Some(Geom::Preset { name: "line".into(), adj: vec![] });
Some(Object { placeholder: false, ph: None, xfrm, text: None, geom, look, kind: Kind::Line })
Some(Object { placeholder: false, ph: None, xfrm, text: None, ruler: None, geom, look, kind: Kind::Line })
}
/// A freeform: its points as a path in its box, drawn as its format says (1 pt in the scheme's
@@ -371,8 +385,10 @@ fn freeform(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
shape::arrowheads(&mut look.line, &heads);
}
let geom = Some(shape::freeform_path(&points, sides, closed));
let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), true));
Some(Object { placeholder: false, ph: None, xfrm: xfrm_of(sides, size), text, geom, look, kind: Kind::Freeform })
let container = r.child(rt::TEXT);
let text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), true));
let ruler = container.and_then(|c| text::ruler_slot(&c));
Some(Object { placeholder: false, ph: None, xfrm: xfrm_of(sides, size), text, ruler, geom, look, kind: Kind::Freeform })
}
/// A 3035 atom's points: a u16 count, then x and y as i32s. No more than the record holds, nor
@@ -409,7 +425,9 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
};
Some(Placeholder { kind: ph_type(a.u8(0)?)?, idx: a.u32(4).unwrap_or(0), size, ..Default::default() })
});
let text = r.child(rt::TEXT).and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none()));
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));
let (mut geom, mut look) = (None, Look::none());
if !placeholder {
geom = code.map(|c| shape::geometry(c, g.i32(4), &mut xfrm));
@@ -417,7 +435,7 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
look = shape::look(&f, scheme);
}
}
Some(Object { placeholder, ph, xfrm, text, geom, look, kind: Kind::Shape })
Some(Object { placeholder, ph, xfrm, text, ruler, geom, look, kind: Kind::Shape })
}
/// An object as a shape: a placeholder of a known type; a text box when it draws nothing but its
@@ -540,10 +558,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<PhType> = vec![];
// The rulers of the master's title and body, which give their styles' margins.
let (mut title_ruler, mut body_ruler) = (None, None);
for o in Reader::page(&env, &scheme, size, &m.rec) {
if o.placeholder {
if let Some(kind) = o.ph.as_ref().map(|ph| ph.kind).filter(|k| !placed.iter().any(|d| same_family(*d, *k))) {
placed.push(kind);
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()));
}
@@ -553,6 +578,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));
}
+293 -11
View File
@@ -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, Geom, 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<u8> {
environment_with(&[])
}
/// The Environment, with `styles` (the master's text styles' container) when given.
fn environment_with(styles: &[Vec<u8>]) -> Vec<u8> {
let fonts = container(
2005,
0x19,
@@ -148,7 +153,58 @@ fn environment() -> Vec<u8> {
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<u8> {
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<u8>]) -> Vec<u8> {
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<u8> {
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<u8> {
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<u8> {
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<u8>], para_runs: &[Vec<u8>], ruler: u32, rect: [i32; 4], body: u32) -> Vec<u8> {
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<u8>],
para_runs: &[Vec<u8>],
ruler: u32,
rect: [i32; 4],
body: u32,
flags: u32,
anchor: u32,
) -> Vec<u8> {
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<u8> {
/// A `PowerPoint Document` stream: root 3 holding the Document and a type-10 atom.
fn stream_of(atom: Vec<u8>, slides: &[Vec<u8>], masters: &[Vec<u8>]) -> Vec<u8> {
stream_with(atom, slides, masters, environment())
}
fn stream_with(atom: Vec<u8>, slides: &[Vec<u8>], masters: &[Vec<u8>], environment: Vec<u8>) -> Vec<u8> {
let list = |tag: u32, items: &[Vec<u8>]| {
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<u8>, slides: &[Vec<u8>], masters: &[Vec<u8>]) -> Vec<u8>
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<u8>| 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 and no format of its own is a text box with no fill or line; one without text
@@ -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();
@@ -1270,6 +1471,34 @@ fn hostile_angles_never_panic() {
}
}
/// The text of a drawn shape and of a freeform keeps its anchoring, wrap, spacing and justified
/// alignment, as a text box's does.
#[test]
fn drawn_shapes_text_keeps_its_anchoring_and_spacing() {
let bx = [-576, -576, 576, 576];
let t = || text_flagged(b"A", &[plain(2)], &[spaced_run(2, false, 0, 3, 0, [150, -12, 50])], 1, bx, BODY, 1, 0x13);
let ellipse = container(rt::SHAPE, 0x13, &[coded_geometry(2, 0, bx, 0), format(PLAIN), t()]);
let square = [(-576, -576), (576, -576), (576, 576), (-576, 576)];
let freeform =
container(rt::FREEFORM, 0x13, &[freeform_atom(bx, 4, true), rec(rt::ARROWHEADS, 0, 0, &[0, 0]), format(PLAIN), points_atom(4, &square), t()]);
let p = deck_of(vec![ellipse, freeform], &[]);
let shapes = &p.slides[0].shapes;
assert_eq!(shapes.len(), 2);
for s in shapes {
assert!(!s.text_box, "{}", s.name);
let b = body_of(s);
assert_eq!((b.body.anchor, b.body.anchor_ctr, b.body.wrap), (Some(Anchor::Middle), Some(false), Some(false)), "{}", s.name);
let para = &b.paragraphs[0].props;
assert_eq!(para.align, Some(Align::Justify), "{}", s.name);
assert_eq!(
(para.line_spacing, para.space_before, para.space_after),
(Some(Spacing::Pct(1.5)), Some(Spacing::Pts(12.0)), Some(Spacing::Pct(0.5))),
"{}",
s.name
);
}
}
/// A freeform's 3017 atom: its box twice, the point count, and the closed flag in the low byte
/// of the last word, with something else above it.
fn freeform_atom(bx: [i32; 4], count: u32, closed: bool) -> Vec<u8> {
@@ -1551,6 +1780,59 @@ fn check_sample(name: &str, p: &Presentation) {
}
"align" => assert_eq!(paras(0, 0).iter().map(|p| p.props.align).collect::<Vec<_>>(), [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 = &paras(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 = &paras(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));
+126 -24
View File
@@ -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<Option<String>>,
rulers: Vec<Option<Ruler>>,
/// The master's text styles by text type: each level's character and paragraph formatting.
styles: Vec<Option<[(CharRun, ParaRun); LEVELS]>>,
}
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<u32>) -> Option<ListStyle> {
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<u32> {
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<T>(list: &Rec, kind: u32, read: impl Fn(&Rec) -> Option<T>) -> Vec<Option<T>> {
@@ -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<i32>,
before: Option<i32>,
after: Option<i32>,
}
/// 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<ParaRun> = 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<i32>, 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, &para_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() }