mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 18:23:52 -06:00
* #239: open PowerPoint 97-2003 .ppt/.pot/.pps files
New crate deckcraft-ppt (L3), written from the public [MS-CFB], [MS-PPT]
and [MS-ODRAW] Open Specifications: a compound-file reader (ported from
FilmCraft's clean-room reader), the edit chain and persist directory, and
the OfficeArt drawings. Main masters become masters (colours, fonts, text
styles, background, decorations), title masters become layouts; slides
keep their shapes (presets, freeforms, groups, rotation, flips), fills,
lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF, WMF), text with the
master styles resolved into it, fields, notes and hidden flags.
Import only: an opened .ppt has no save path, so Save asks for a new
name. A .pps from the system starts the slide show. File dialogs, drag
and drop, the web shell and the macOS, Windows and Linux file
associations offer the three extensions. Tests build .ppt files from
records and sweep hostile input.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* #239: address review: budget picture decoding, read each persist directory once, macOS .pot/.pps types
- Pictures decode lazily, when a shape first uses them, each at most once and all
within a shared 4 GiB budget: many store entries pointing at one deflated blob
can no longer ask for unbounded memory.
- A persist directory named by many edits is read once.
- Info.plist declares com.microsoft.powerpoint.pot and .pps alongside .ppt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* #239: address review: check the picture budget before copying bitmap data
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* #239: build against current main
- convert.rs: set `flip: None` on imported gradients. `Gradient` gained the field in
ad97533a; None is what an unflipped gradient was before.
- tests.rs: split `imports_a_presentation` into one check per section (title, picture,
group, text box, master) for the workspace `cognitive_complexity` lint (6ddd2fb8).
The assertions are unchanged.
- Cargo.lock: deckcraft-ppt takes the workspace version, 0.15.0.
* #239: keep the picture budget on 32-bit targets
`MAX_TOTAL` was `4 << 30` as a `usize`. On wasm32 that is 2^32, which wraps to 0
without any error, so the web build's picture budget was zero and every .ppt
picture was dropped. Use the address space as the limit there. A compile-time
assertion that the budget holds at least one picture keeps it from happening
again on any target: the CI wasm step (`cargo check`) now fails if it does.
* #239: read past the character fields PowerPoint 2002 and later add
A TextCFException can end with pp10runid (mask bit 20), newEAFontRef (24),
csFontRef (25) and pp11ext (26), after `position`. read_cf stopped at
`position`, so in a StyleTextPropAtom the next run's count and mask were read
from the leftover bytes, and every later run got garbage formatting or the
walk ended. Master text styles go through the same reader. The fields are
read past and not used. The test has a run carrying all four followed by a
bold 18 pt run, which now reads as written.
* #239: convert each listed object once and index notes pages
Nothing stopped a slide list from naming one persist object many times, and
each listing converted its whole drawing again: a 100k-shape slide listed
180k times fits in about 10 MB and makes 1.8e10 shapes. An object is now
listed once across the slide, master and notes lists (PowerPoint never lists
one twice), and a repeat is logged and skipped. Notes pages are looked up
through a map built once, instead of a scan per slide (slides x notes). The
first matching page still wins.
* #239: find formatting runs by binary search
paragraphs() found the run at a position (rposition) and the next run start
(find) by scanning the run starts for every run, break and field, so text
cost grew with chars x runs. The starts are a running sum and never
decrease, so both lookups are now partition_point. Measured in a debug
build, 640k one-character runs (about 6 MB of file): 75 s before, about 2 s
after. The test uses a 20 s bound, like render's pathgrad budget test.
* #239: cap decoded pictures at the .pptx package total
The picture budget was 4 GiB, so a few MB of small deflated metafiles, each
inflating to 64 MiB, could make the import hold 4 GiB. A .pptx package may
inflate to 2 GiB in total (deckcraft-pptx opc MAX_TOTAL), and pictures are
the only part of a .ppt this crate inflates, so use the same 2 GiB. That also
fits a 32-bit usize, which replaces the wasm32 special case. This is a limit
change, so there is no new test: the budget test
(the_store_decodes_lazily_within_a_budget) and the compile-time check that
the budget holds a picture still cover it.
* #239: fall back to the first main master the same way every time
A slide naming a master that doesn't exist fell back to the lowest index in
the masters HashMap. A title master is stored with its main master's index,
so the two tied and the HashMap's random order picked one: the same file got
the "Title Master" layout on some opens and the main master's on others. The
fallback now considers main masters only. The test opens such a deck 30
times; before the fix it took the title master's layout within those opens.
* #239: try the edit scan before calling a file too old
Any Current User token other than the plain or encrypted one, including none
at all from a truncated record, returned TooOld at once. A PowerPoint 97 file
with a damaged Current User stream was reported as "made by PowerPoint 95 or
earlier", and the UserEditAtom scan meant for a missing stream never ran.
[MS-PPT] allows only those two tokens, so an unknown one can't tell a damaged
file from an older format. The scan now runs, and TooOld is returned only when
it finds no edit record behind an unknown token.
* #239: read persist directories within one stream's worth of words
dirs_seen only skips a directory named at the same offset again. Directories
nested inside one another, each named by its own UserEditAtom, were each read
to the end of the stream: MAX_EDITS x the stream. In a debug build, 4095 such
edits over a 64 MiB stream took about 48 s. All directories now share a budget
of stream.len() / 4 words. Real directories are separate records inside the
stream, so they always fit. The hostile case stops in milliseconds and is
reported as damaged.
* #239: check two additions on input-derived sizes
- cfb.rs: the mini sector end `at + MINI_SECTOR_SIZE` was unchecked. On a
32-bit target (wasm32), a sector number near 0x03FF_FFFF puts `at` at the
top of usize, so the add panics in a debug build and wraps in release.
- text.rs: the style-run total `chars.len() as u32 + 1` truncated and could
overflow past u32::MAX characters. It now saturates.
Neither case can be reached in a native test (one needs a 32-bit target, the
other more than 4 GiB of text), so there is no new test. The `+ 1`s in
convert.rs paragraphs() that the review also named are bounded by the text
length and can't overflow, so they are unchanged.
* #239: gaps: name every loss in the .ppt Impact line
The Impact line said old decks "open and read correctly" and named only
motion and links, while the Evidence above it also lists sounds and video,
degraded tables, OLE objects, charts and WordArt, and missing PICT pictures.
(CodeRabbit's open note on docs/gaps.md.)
* #239: ppt: a sector chain that revisits a sector is an error
read_chain stopped at the stream's size, so a FAT loop shorter than the stream returned the
looped sectors again as the stream's bytes. It now tracks visited sectors and fails on a revisit,
and reserves the stream's size (capped at the file length) up front.
a_looping_chain_stops expected the repeated bytes; it now expects the error (eliets2's review).
* #239: ppt: slide shapes inherit from their own master's shapes
Master shape properties were remembered by shape id alone, so a later master (a title master,
or a second main master) that reused a shape id replaced the first master's entry, and slides
inherited fill and line from the wrong master. They are now keyed by master slide id and shape id,
and a shape's hspMaster is looked up in its slide's master, then a title master's main master.
Notes pages have no imported master, so they inherit nothing.
PowerPoint gives shapes file-unique ids, so this takes a damaged or generated file (eliets2's
review).
* #239: ppt: drop the unused fBackground field
RawShape.background was set from the FSP flag but never read: the background shape is the
drawing container's own shape (OfficeArtDgContainer.shape, [MS-ODRAW] 2.2.13), which drawing()
already takes. The comment there now says so (eliets2's review).
* #239: ppt: shadowed text keeps its shadow
TextCFException's shadow bit was read and merged but never reached the run. A shadowed run now
gets a shadow in the colour scheme's shadow colour, at the distance and direction of the app's own
Text Shadow command, with no blur (the record has none). Emboss has no counterpart in the model,
so its field is gone and the loss is listed in the docs (eliets2's review).
* #239: the .pps show-on-open test opens a real 97-2003 file
a_ppsx_from_the_system_starts_the_show saved a .pptx under the name "Old talk.pps", so it went
through the PPTX path and never reached the legacy importer. crates/ppt/tests/fixtures/old-talk.pps
is a one-slide .pps built from records by the ppt tests (rebuilt with DECKCRAFT_WRITE_PPT_FIXTURE=1,
checked on every run), attributed CC0 like the other generated fixtures, and the UI test opens it
(eliets2's review).
* #239: docs: one date, the full list of losses, .pot in the README
From eliets2's review:
- README names .ppt/.pot/.pps and says the import has no writer (Save asks for a new name).
- The parity-checklist row lists the same losses as docs/gaps.md, now with text emboss, and the
checklist gets a status line for the change.
- The ROADMAP progress row, the architecture and file-format change rows and every header carry
one date (2026-11-09), so the progress row sits at the top in order; the ROADMAP gets its
status line.
- docs/gaps.md says why there is no real-deck corpus in the repo (no PowerPoint-made files) and
where one would live.
* #239: ppt: test mini streams, 4096-byte sectors and the DIFAT chain
The compound-file test builder only made version-3 files with 512-byte sectors, no mini stream
and every FAT sector in the header, so read_mini_chain, 4096-byte sectors and the DIFAT chain never
ran. build_with takes the sector shift and the mini stream cutoff, and lists FAT sectors past the
header's 109 in DIFAT sectors; build is build_with(streams, 9, 0), so existing tests see the same
layout. Three tests read streams back through each path (eliets2's review).
* #239: ppt: test every picture kind, two-UID blips and blips inside the FBSE
The blip tests covered PNG, deflated WMF and DIB only. New tests decode JPEG (RGB and CMYK), TIFF
and PNG with one and two UIDs, an uncompressed EMF with each UID count, a metafile over the budget
(compressed or not), and a blip held inside its FBSE rather than in the Pictures stream. All
passed as written (eliets2's review).
* #239: ppt: placeholder text held only in the slide list is imported
A shape's client text box may hold just an OutlineTextRefAtom, with no TextHeaderAtom ([MS-PPT]
OfficeArtClientTextbox): the text lives in the slide list, and that is the usual form for slide
placeholders. read_block returned None without a header, so text_block never reached its
outline fallback and the placeholder came in empty. A block with a reference and no header is
now returned for the caller to follow.
placeholder_text_can_come_from_the_slide_list covers the reference alone (it failed before this
change) and a header with a reference; the test document builder can put outline blocks in the
slide list (streams_with_outline). Found writing the test eliets2's review asked for.
* #239: ppt: test newer edits and the two other encryption signs
doc::read had tests for one edit and the Current User token only. a_later_edit_replaces_a_slide
adds an edit whose persist directory gives the slide a new object; the newer slide is imported and
the master from the older directory is kept. encryption_is_found_in_the_edit_and_the_persist_directory
covers an edit record long enough for encryptSessionPersistIdRef and a CryptSession object named
by a later edit. Both passed as written (eliets2's review).
* #239: ppt: test title masters and slides that follow nothing
No test made a slide of a title master or a slide with the follow-master flags off. The new test
checks that a title master becomes a "Title Master" layout with its own background and shapes
and without the master's shapes, that its slide uses that layout and follows its background, and
that a slide with all three flags off keeps its own background and colour scheme and hides the
master's shapes. It passed as written (eliets2's review).
* #239: ppt: merge boolean properties flag by flag
A boolean property word holds sixteen flags, each with its own fUse bit.
Props::inherit and add_table kept the whole word from the most specific
set, so a placeholder or text box that set only fNoFillHitTest lost the
inherited "not filled" and "no line" and was drawn with a fill and an
outline. Merge those words per flag instead (#1137 review, issue 1).
* #239: ppt: recover a broken edit chain and report lost slides
An edit whose previous-edit offset points back at itself (or anywhere
that isn't an edit) cut the older edits off, and with them the persist
directories holding the slides: such a file opened as an empty deck
with no warning. When the chain doesn't end at offset 0, read every
edit's persist directory in the stream, newest first, filling only what
the chain left unset.
Slides the slide list names but whose objects are still missing are now
returned by deckcraft_ppt::import_checked and reported like a damaged
.pptx: lostSlides, a "(Repaired)" copy and the CLI warning
(#1137 review, issue 3).
* #239: ppt: picture frames, inline picture fills, gradients, footers, numbering
The remaining differences from LibreOffice in the #1137 stress test:
- Picture frames (and OLE frames) that say nothing about fill or line
start with neither, as placeholders and text boxes do, instead of the
drawing defaults' fill.
- A pib or fillBlip held in the property's own complex bytes (fBid) is
decoded within the picture budget: table cells with a picture fill
showed a plain colour.
- Shaded fills put the back colour at fillFocus ([MS-ODRAW]), and the
linear angle follows how LibreOffice writes and reads it (0 degrees
from the top): the linear gradient was reversed, the radial inside out.
- HeadersFooters (the slide's, else the document's) add the date,
footer and slide number placeholders; the master's footer placement,
alignment, size and colour reach every layout.
- Numbering from the document's ___PPT9 tag (OutlineTextProps9, pp9rt
in the runs' fontStyle) turns bulleted paragraphs into numbered ones.
- Wingdings diamonds draw as a diamond, not a dot.
* #239: ppt: read CString records up to their first NUL
Header/footer text and the ___PPT9 tag name were decoded from the whole
CString body. A writer that ends the string with a NUL would put the NUL
into the footer text and make the tag name fail to match, losing the
numbering. Stop at the first NUL, as the font names already do.
---------
Co-authored-by: kiwi4boy <kiwi4boy@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: keithcsqueensu <92232107+keithcsqueensu@users.noreply.github.com>
Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
662 lines
23 KiB
Rust
662 lines
23 KiB
Rust
//! Text in `.ppt` ([MS-PPT] §2.9): characters in a `TextCharsAtom` (UTF-16) or `TextBytesAtom`
|
||
//! (Latin-1), formatting as runs of paragraph exceptions (`TextPFException`) and character
|
||
//! exceptions (`TextCFException`) over the master's per-level text styles.
|
||
|
||
use crate::doc::rt;
|
||
use crate::record::{Cursor, Rec};
|
||
|
||
/// A colour as text formatting stores it: an RGB value or an index into the colour scheme.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum TextColor {
|
||
Rgb(u8, u8, u8),
|
||
Scheme(u8),
|
||
}
|
||
|
||
fn color_index(c: &mut Cursor) -> Option<Option<TextColor>> {
|
||
let (r, g, b, i) = (c.u8()?, c.u8()?, c.u8()?, c.u8()?);
|
||
Some(match i {
|
||
0xFE => Some(TextColor::Rgb(r, g, b)),
|
||
0..=7 => Some(TextColor::Scheme(i)),
|
||
_ => None,
|
||
})
|
||
}
|
||
|
||
/// Paragraph formatting; `None` fields are not set at this level.
|
||
#[derive(Clone, Debug, Default, PartialEq)]
|
||
pub struct Pf {
|
||
pub has_bullet: Option<bool>,
|
||
pub bullet_has_font: Option<bool>,
|
||
pub bullet_has_color: Option<bool>,
|
||
pub bullet_has_size: Option<bool>,
|
||
pub bullet_char: Option<u16>,
|
||
pub bullet_font: Option<u16>,
|
||
/// Positive: percent of the text size; negative: absolute size in points.
|
||
pub bullet_size: Option<i16>,
|
||
pub bullet_color: Option<TextColor>,
|
||
/// 0 left, 1 centre, 2 right, 3 justify, 4 distributed, 5 Thai distributed, 6 justify low.
|
||
pub align: Option<u16>,
|
||
/// Positive: percent of a line; negative: master units (−8 per point).
|
||
pub line_spacing: Option<i16>,
|
||
pub space_before: Option<i16>,
|
||
pub space_after: Option<i16>,
|
||
/// Master units from the text box's left edge.
|
||
pub left_margin: Option<u16>,
|
||
pub indent: Option<u16>,
|
||
pub default_tab: Option<u16>,
|
||
pub tabs: Option<Vec<(i16, u16)>>,
|
||
}
|
||
|
||
impl Pf {
|
||
/// Overlay `o`'s set fields on this one.
|
||
pub fn apply(&mut self, o: &Pf) {
|
||
macro_rules! over {
|
||
($($f:ident),*) => { $( if o.$f.is_some() { self.$f.clone_from(&o.$f); } )* };
|
||
}
|
||
over!(
|
||
has_bullet,
|
||
bullet_has_font,
|
||
bullet_has_color,
|
||
bullet_has_size,
|
||
bullet_char,
|
||
bullet_font,
|
||
bullet_size,
|
||
bullet_color,
|
||
align,
|
||
line_spacing,
|
||
space_before,
|
||
space_after,
|
||
left_margin,
|
||
indent,
|
||
default_tab,
|
||
tabs
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Character formatting; `None` fields are not set at this level.
|
||
#[derive(Clone, Debug, Default, PartialEq)]
|
||
pub struct Cf {
|
||
pub bold: Option<bool>,
|
||
pub italic: Option<bool>,
|
||
pub underline: Option<bool>,
|
||
pub shadow: Option<bool>,
|
||
pub font: Option<u16>,
|
||
pub ea_font: Option<u16>,
|
||
pub symbol_font: Option<u16>,
|
||
/// Points.
|
||
pub size: Option<u16>,
|
||
pub color: Option<TextColor>,
|
||
/// Superscript (positive) or subscript (negative) offset, percent of the size.
|
||
pub position: Option<i16>,
|
||
/// `pp9rt`: the index of the paragraph's PowerPoint 2000 formatting (numbering) in the text's
|
||
/// `StyleTextProp9Atom`.
|
||
pub pp9rt: Option<u8>,
|
||
}
|
||
|
||
impl Cf {
|
||
pub fn apply(&mut self, o: &Cf) {
|
||
macro_rules! over {
|
||
($($f:ident),*) => { $( if o.$f.is_some() { self.$f = o.$f; } )* };
|
||
}
|
||
over!(bold, italic, underline, shadow, font, ea_font, symbol_font, size, color, position, pp9rt);
|
||
}
|
||
}
|
||
|
||
fn bit(m: u32, b: u32) -> bool {
|
||
m & (1 << b) != 0
|
||
}
|
||
|
||
/// A `TextPFException`.
|
||
pub fn read_pf(c: &mut Cursor) -> Option<Pf> {
|
||
let m = c.u32()?;
|
||
let mut pf = Pf::default();
|
||
if m & 0xF != 0 {
|
||
let flags = c.u16()?;
|
||
for (b, slot) in [(0, &mut pf.has_bullet), (1, &mut pf.bullet_has_font), (2, &mut pf.bullet_has_color), (3, &mut pf.bullet_has_size)] {
|
||
if bit(m, b) {
|
||
*slot = Some(flags & (1 << b) != 0);
|
||
}
|
||
}
|
||
}
|
||
if bit(m, 7) {
|
||
pf.bullet_char = Some(c.u16()?);
|
||
}
|
||
if bit(m, 4) {
|
||
pf.bullet_font = Some(c.u16()?);
|
||
}
|
||
if bit(m, 6) {
|
||
pf.bullet_size = Some(c.i16()?);
|
||
}
|
||
if bit(m, 5) {
|
||
pf.bullet_color = color_index(c)?;
|
||
}
|
||
if bit(m, 11) {
|
||
pf.align = Some(c.u16()?);
|
||
}
|
||
if bit(m, 12) {
|
||
pf.line_spacing = Some(c.i16()?);
|
||
}
|
||
if bit(m, 13) {
|
||
pf.space_before = Some(c.i16()?);
|
||
}
|
||
if bit(m, 14) {
|
||
pf.space_after = Some(c.i16()?);
|
||
}
|
||
if bit(m, 8) {
|
||
pf.left_margin = Some(c.u16()?);
|
||
}
|
||
if bit(m, 10) {
|
||
pf.indent = Some(c.u16()?);
|
||
}
|
||
if bit(m, 15) {
|
||
pf.default_tab = Some(c.u16()?);
|
||
}
|
||
if bit(m, 20) {
|
||
pf.tabs = Some(read_tabs(c)?);
|
||
}
|
||
if bit(m, 16) {
|
||
c.u16()?; // fontAlign
|
||
}
|
||
if m & (0x7 << 17) != 0 {
|
||
c.u16()?; // wrapFlags
|
||
}
|
||
if bit(m, 21) {
|
||
c.u16()?; // textDirection
|
||
}
|
||
Some(pf)
|
||
}
|
||
|
||
fn read_tabs(c: &mut Cursor) -> Option<Vec<(i16, u16)>> {
|
||
let n = c.u16()?;
|
||
let mut v = Vec::with_capacity(usize::from(n).min(64));
|
||
for _ in 0..n {
|
||
v.push((c.i16()?, c.u16()?));
|
||
}
|
||
Some(v)
|
||
}
|
||
|
||
/// A `TextCFException`.
|
||
pub fn read_cf(c: &mut Cursor) -> Option<Cf> {
|
||
let m = c.u32()?;
|
||
let mut cf = Cf::default();
|
||
// fontStyle is present when any of bold, italic, underline, shadow, fehint, kumi, emboss or
|
||
// fHasStyle is in the mask.
|
||
if m & 0x3EB7 != 0 {
|
||
let s = c.u16()?;
|
||
// Emboss (bit 9) has no counterpart in the model; docs/gaps.md lists it.
|
||
for (b, slot) in [(0, &mut cf.bold), (1, &mut cf.italic), (2, &mut cf.underline), (4, &mut cf.shadow)] {
|
||
if bit(m, b) {
|
||
*slot = Some(s & (1 << b) != 0);
|
||
}
|
||
}
|
||
// fHasStyle (bits 10–13) says pp9rt, the same four bits of fontStyle, is given.
|
||
if m & 0x3C00 != 0 {
|
||
cf.pp9rt = Some(((s >> 10) & 0xF) as u8);
|
||
}
|
||
}
|
||
if bit(m, 16) {
|
||
cf.font = Some(c.u16()?);
|
||
}
|
||
if bit(m, 21) {
|
||
cf.ea_font = Some(c.u16()?);
|
||
}
|
||
if bit(m, 22) {
|
||
c.u16()?; // ansiFontRef
|
||
}
|
||
if bit(m, 23) {
|
||
cf.symbol_font = Some(c.u16()?);
|
||
}
|
||
if bit(m, 17) {
|
||
cf.size = Some(c.u16()?);
|
||
}
|
||
if bit(m, 18) {
|
||
cf.color = color_index(c)?;
|
||
}
|
||
if bit(m, 19) {
|
||
cf.position = Some(c.i16()?);
|
||
}
|
||
// The fields PowerPoint 2002 and later add are not used, but they must be read past: the next
|
||
// run's count and mask follow them, so stopping short garbles every later run's formatting.
|
||
if bit(m, 20) {
|
||
c.u32()?; // pp10runid (4 bits) and unused (28 bits)
|
||
}
|
||
if bit(m, 24) {
|
||
c.u16()?; // newEAFontRef
|
||
}
|
||
if bit(m, 25) {
|
||
c.u16()?; // csFontRef
|
||
}
|
||
if bit(m, 26) {
|
||
c.u32()?; // pp11ext
|
||
}
|
||
Some(cf)
|
||
}
|
||
|
||
/// A paragraph's PowerPoint 2000 formatting (`TextPFException9`): its automatic numbering.
|
||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||
pub struct Pf9 {
|
||
/// `fBulletHasAutoNumber` with `bulletAutoNumberScheme`: the scheme and the first number.
|
||
pub auto_number: Option<(u16, i16)>,
|
||
}
|
||
|
||
/// The entries of a `StyleTextProp9Atom` ([MS-PPT] §2.9.33): each a `TextPFException9`, a
|
||
/// `TextCFException9` and a `TextSIException`, indexed by the runs' `pp9rt`. Reading stops at an
|
||
/// entry with a field this reader can't size, keeping the entries before it.
|
||
pub fn read_style9(b: &[u8]) -> Vec<Pf9> {
|
||
let mut c = Cursor::new(b);
|
||
let mut out = vec![];
|
||
// pp9rt has four bits, so sixteen entries are all a run can name.
|
||
while out.len() < 16 && c.remaining() > 0 {
|
||
let Some(pf9) = read_pf9(&mut c) else { break };
|
||
out.push(pf9);
|
||
// TextCFException9: the extension fields of a character mask.
|
||
let Some(m) = c.u32() else { break };
|
||
if m & !((1 << 20) | (1 << 24) | (1 << 25) | (1 << 26)) != 0 {
|
||
break;
|
||
}
|
||
let ok = (!bit(m, 20) || c.u32().is_some())
|
||
&& (!bit(m, 24) || c.u16().is_some())
|
||
&& (!bit(m, 25) || c.u16().is_some())
|
||
&& (!bit(m, 26) || c.u32().is_some());
|
||
// TextSIException: spelling, language, alternate language, bidi, pp10 extension, smart tags.
|
||
if !ok || read_si(&mut c).is_none() {
|
||
break;
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
fn read_pf9(c: &mut Cursor) -> Option<Pf9> {
|
||
let m = c.u32()?;
|
||
if bit(m, 23) {
|
||
c.i16()?; // bulletBlipRef
|
||
}
|
||
let has_auto = if bit(m, 25) { Some(c.u16()? != 0) } else { None };
|
||
let scheme = if bit(m, 24) { Some((c.u16()?, c.i16()?)) } else { None };
|
||
if bit(m, 26) {
|
||
c.u32()?; // pp10 extension
|
||
}
|
||
Some(Pf9 { auto_number: if has_auto == Some(true) { Some(scheme.unwrap_or((3, 1))) } else { None } })
|
||
}
|
||
|
||
fn read_si(c: &mut Cursor) -> Option<()> {
|
||
let m = c.u32()?;
|
||
if m & !0x027F != 0 {
|
||
return None;
|
||
}
|
||
for b in [0, 1, 2, 6] {
|
||
if bit(m, b) {
|
||
c.u16()?;
|
||
}
|
||
}
|
||
if bit(m, 5) {
|
||
c.u32()?; // pp10runid and reserved
|
||
}
|
||
if bit(m, 9) {
|
||
let n = c.u32()?;
|
||
for _ in 0..n {
|
||
c.u32()?;
|
||
}
|
||
}
|
||
Some(())
|
||
}
|
||
|
||
/// The DrawingML numbering scheme of a `TextAutoNumberSchemeEnum` value.
|
||
pub fn auto_number_scheme(v: u16) -> &'static str {
|
||
match v {
|
||
0 => "alphaLcPeriod",
|
||
1 => "alphaUcPeriod",
|
||
2 => "arabicParenR",
|
||
4 => "romanLcParenBoth",
|
||
5 => "romanLcParenR",
|
||
6 => "romanLcPeriod",
|
||
7 => "romanUcPeriod",
|
||
8 => "alphaLcParenBoth",
|
||
9 => "alphaLcParenR",
|
||
10 => "alphaUcParenBoth",
|
||
11 => "alphaUcParenR",
|
||
12 => "arabicParenBoth",
|
||
13 => "arabicPlain",
|
||
14 => "romanUcParenBoth",
|
||
15 => "romanUcParenR",
|
||
_ => "arabicPeriod",
|
||
}
|
||
}
|
||
|
||
/// Text types (`TextHeaderAtom.textType`).
|
||
pub mod ty {
|
||
pub const TITLE: u32 = 0;
|
||
pub const BODY: u32 = 1;
|
||
pub const NOTES: u32 = 2;
|
||
pub const OTHER: u32 = 4;
|
||
pub const CENTER_BODY: u32 = 5;
|
||
pub const CENTER_TITLE: u32 = 6;
|
||
pub const HALF_BODY: u32 = 7;
|
||
pub const QUARTER_BODY: u32 = 8;
|
||
}
|
||
|
||
/// One master text style: up to five levels of paragraph and character formatting.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct LevelStyles {
|
||
pub levels: Vec<(Pf, Cf)>,
|
||
}
|
||
|
||
/// A `TextMasterStyleAtom` body.
|
||
pub fn read_master_style(r: &Rec) -> LevelStyles {
|
||
let mut c = Cursor::new(r.data);
|
||
let mut out = LevelStyles::default();
|
||
let Some(n) = c.u16() else { return out };
|
||
for _ in 0..n.min(5) {
|
||
// From the centre-body type on, each level names itself.
|
||
if u32::from(r.instance) >= ty::CENTER_BODY && c.u16().is_none() {
|
||
break;
|
||
}
|
||
let Some(pf) = read_pf(&mut c) else { break };
|
||
let Some(cf) = read_cf(&mut c) else { break };
|
||
out.levels.push((pf, cf));
|
||
}
|
||
out
|
||
}
|
||
|
||
/// The text styles in effect for a master: the document defaults plus the master's styles by text
|
||
/// type.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct StyleSheet {
|
||
pub default_pf: Pf,
|
||
pub default_cf: Cf,
|
||
/// Indexed by text type (0–8).
|
||
pub types: Vec<Option<LevelStyles>>,
|
||
}
|
||
|
||
impl StyleSheet {
|
||
/// Read the defaults of the document environment and, over them, a master's styles.
|
||
pub fn new(environment: Option<Rec>, master: Option<&Rec>) -> Self {
|
||
let mut s = StyleSheet { types: vec![None; 9], ..Default::default() };
|
||
if let Some(env) = environment {
|
||
if let Some(pf) = env.child(rt::TEXT_PF_EXCEPTION).and_then(|r| read_pf(&mut Cursor { b: r.data, at: 2 })) {
|
||
s.default_pf = pf;
|
||
}
|
||
if let Some(cf) = env.child(rt::TEXT_CF_EXCEPTION).and_then(|r| read_cf(&mut Cursor::new(r.data))) {
|
||
s.default_cf = cf;
|
||
}
|
||
for r in env.children_of(rt::TEXT_MASTER_STYLE) {
|
||
if let Some(slot) = s.types.get_mut(usize::from(r.instance)) {
|
||
*slot = Some(read_master_style(&r));
|
||
}
|
||
}
|
||
}
|
||
if let Some(m) = master {
|
||
for r in m.children_of(rt::TEXT_MASTER_STYLE) {
|
||
if let Some(slot) = s.types.get_mut(usize::from(r.instance)) {
|
||
*slot = Some(read_master_style(&r));
|
||
}
|
||
}
|
||
}
|
||
s
|
||
}
|
||
|
||
/// The formatting of text type `ty` at outline level `level`: defaults, then the base type's
|
||
/// level 1 and level, then this type's.
|
||
pub fn resolve(&self, ty: u32, level: u8) -> (Pf, Cf) {
|
||
let (mut pf, mut cf) = (self.default_pf.clone(), self.default_cf.clone());
|
||
let base = match ty {
|
||
ty::CENTER_TITLE => Some(ty::TITLE),
|
||
ty::CENTER_BODY | ty::HALF_BODY | ty::QUARTER_BODY => Some(ty::BODY),
|
||
_ => None,
|
||
};
|
||
for t in base.into_iter().chain(std::iter::once(ty)) {
|
||
let Some(Some(st)) = self.types.get(t as usize) else { continue };
|
||
for l in [0usize, usize::from(level)] {
|
||
if let Some((p, c)) = st.levels.get(l) {
|
||
pf.apply(p);
|
||
cf.apply(c);
|
||
}
|
||
if level == 0 {
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
(pf, cf)
|
||
}
|
||
}
|
||
|
||
/// A field inside text: its character position and kind.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum FieldKind {
|
||
SlideNumber,
|
||
DateTime,
|
||
}
|
||
|
||
/// A block of text with its formatting runs.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct TextBlock {
|
||
pub text_type: u32,
|
||
pub chars: Vec<u16>,
|
||
/// (character count, indent level, paragraph exception).
|
||
pub para_runs: Vec<(u32, u8, Pf)>,
|
||
/// (character count, character exception).
|
||
pub char_runs: Vec<(u32, Cf)>,
|
||
/// Ruler overrides per level: (left margin, indent) in master units.
|
||
pub ruler: [(Option<u16>, Option<u16>); 5],
|
||
pub fields: Vec<(u32, FieldKind)>,
|
||
/// An `OutlineTextRefAtom`: the text is the n-th outline block of the slide list entry.
|
||
pub outline_ref: Option<u32>,
|
||
/// The slide list's outline block this text was read from.
|
||
pub outline_index: Option<usize>,
|
||
}
|
||
|
||
/// Read a text block from a run of records starting at its `TextHeaderAtom` (inside a client text
|
||
/// box, or in the slide list). Stops at the next header or slide persist atom. A client text box
|
||
/// may hold only an `OutlineTextRefAtom` ([MS-PPT] OfficeArtClientTextbox), with no header: that
|
||
/// is still a block, so the caller can follow the reference.
|
||
pub fn read_block<'a>(records: impl Iterator<Item = Rec<'a>>) -> Option<TextBlock> {
|
||
let mut b = TextBlock::default();
|
||
let mut started = false;
|
||
let mut style: Option<Rec> = None;
|
||
for r in records {
|
||
match r.kind {
|
||
rt::TEXT_HEADER if started => break,
|
||
rt::SLIDE_PERSIST_ATOM => break,
|
||
rt::TEXT_HEADER => {
|
||
started = true;
|
||
b.text_type = r.u32(0).unwrap_or(ty::OTHER);
|
||
}
|
||
rt::TEXT_CHARS => b.chars = r.data.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(),
|
||
rt::TEXT_BYTES => b.chars = r.data.iter().map(|&c| u16::from(c)).collect(),
|
||
rt::STYLE_TEXT_PROP => style = Some(r),
|
||
rt::TEXT_RULER => b.ruler = read_ruler(&r),
|
||
rt::OUTLINE_TEXT_REF => b.outline_ref = r.u32(0),
|
||
rt::SLIDE_NUMBER_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::SlideNumber))),
|
||
rt::DATETIME_MC | rt::GENERIC_DATE_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::DateTime))),
|
||
_ => {}
|
||
}
|
||
}
|
||
if !started && b.outline_ref.is_none() {
|
||
return None;
|
||
}
|
||
if let Some(st) = style {
|
||
// Text past u32::MAX characters can't be addressed by the runs; saturate rather than wrap.
|
||
read_style_runs(&st, u32::try_from(b.chars.len()).unwrap_or(u32::MAX).saturating_add(1), &mut b);
|
||
}
|
||
Some(b)
|
||
}
|
||
|
||
/// The paragraph runs then the character runs of a `StyleTextPropAtom`; each set covers the text
|
||
/// plus one (the final paragraph mark).
|
||
fn read_style_runs(r: &Rec, total: u32, b: &mut TextBlock) {
|
||
let mut c = Cursor::new(r.data);
|
||
let mut covered = 0u32;
|
||
while covered < total {
|
||
let Some(n) = c.u32() else { return };
|
||
let Some(level) = c.u16() else { return };
|
||
let Some(pf) = read_pf(&mut c) else { return };
|
||
b.para_runs.push((n, level.min(8) as u8, pf));
|
||
covered = covered.saturating_add(n.max(1));
|
||
}
|
||
covered = 0;
|
||
while covered < total {
|
||
let Some(n) = c.u32() else { return };
|
||
let Some(cf) = read_cf(&mut c) else { return };
|
||
b.char_runs.push((n, cf));
|
||
covered = covered.saturating_add(n.max(1));
|
||
}
|
||
}
|
||
|
||
fn read_ruler(r: &Rec) -> [(Option<u16>, Option<u16>); 5] {
|
||
let mut out = [(None, None); 5];
|
||
let mut c = Cursor::new(r.data);
|
||
let Some(m) = c.u32() else { return out };
|
||
if bit(m, 1) && c.u16().is_none() {
|
||
return out;
|
||
}
|
||
if bit(m, 0) && c.u16().is_none() {
|
||
return out;
|
||
}
|
||
if bit(m, 2) && read_tabs(&mut c).is_none() {
|
||
return out;
|
||
}
|
||
for (l, slot) in out.iter_mut().enumerate() {
|
||
let l = l as u32;
|
||
if bit(m, 3 + l) {
|
||
slot.0 = c.u16();
|
||
}
|
||
if bit(m, 8 + l) {
|
||
slot.1 = c.u16();
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
#[cfg(test)]
|
||
pub(crate) mod tests {
|
||
#![allow(clippy::unwrap_used)]
|
||
|
||
use super::*;
|
||
use crate::record::build::*;
|
||
|
||
/// A PF exception with alignment and bullets on or off.
|
||
pub fn pf_bytes(align: u16, bullet: bool) -> Vec<u8> {
|
||
let mut v = (0x0000_0801u32).to_le_bytes().to_vec(); // hasBullet + align
|
||
v.extend_from_slice(&u16::from(bullet).to_le_bytes());
|
||
v.extend_from_slice(&align.to_le_bytes());
|
||
v
|
||
}
|
||
|
||
/// A CF exception with bold, a font, a size and an RGB colour.
|
||
pub fn cf_bytes(bold: bool, font: u16, size: u16, rgb: [u8; 3]) -> Vec<u8> {
|
||
let mut v = (0x0007_0001u32).to_le_bytes().to_vec(); // bold + typeface + size + color
|
||
v.extend_from_slice(&u16::from(bold).to_le_bytes());
|
||
v.extend_from_slice(&font.to_le_bytes());
|
||
v.extend_from_slice(&size.to_le_bytes());
|
||
v.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 0xFE]);
|
||
v
|
||
}
|
||
|
||
/// The `StyleTextProp9Atom` entries as PowerPoint writes them: three, the second numbered "1."
|
||
/// from 1. Short or unknown data keeps the entries read before it.
|
||
#[test]
|
||
fn reads_numbering_entries() {
|
||
let mut b = vec![0u8; 12];
|
||
b.extend_from_slice(&[0, 0, 0, 3, 1, 0, 3, 0, 1, 0]);
|
||
b.extend_from_slice(&[0; 8]);
|
||
b.extend_from_slice(&[0; 12]);
|
||
let e = read_style9(&b);
|
||
assert_eq!(e.iter().map(|p| p.auto_number).collect::<Vec<_>>(), [None, Some((3, 1)), None]);
|
||
assert_eq!(read_style9(b.get(..20).unwrap()).len(), 1);
|
||
assert_eq!(read_style9(b.get(..22).unwrap()).len(), 2);
|
||
assert_eq!(read_style9(&[0xFF; 64]).len(), 1);
|
||
assert!(read_style9(&[]).is_empty());
|
||
assert_eq!(auto_number_scheme(3), "arabicPeriod");
|
||
assert_eq!(auto_number_scheme(0), "alphaLcPeriod");
|
||
}
|
||
|
||
#[test]
|
||
fn reads_exceptions_in_mask_order() {
|
||
let pf = read_pf(&mut Cursor::new(&pf_bytes(1, true))).unwrap();
|
||
assert_eq!(pf.has_bullet, Some(true));
|
||
assert_eq!(pf.align, Some(1));
|
||
assert_eq!(pf.bullet_has_font, None);
|
||
let cf = read_cf(&mut Cursor::new(&cf_bytes(true, 3, 28, [1, 2, 3]))).unwrap();
|
||
assert_eq!((cf.bold, cf.italic, cf.font, cf.size, cf.color), (Some(true), None, Some(3), Some(28), Some(TextColor::Rgb(1, 2, 3))));
|
||
// A mask promising more than the bytes hold reads nothing.
|
||
assert!(read_cf(&mut Cursor::new(&0x0007_0000u32.to_le_bytes())).is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn reads_a_text_block_with_runs() {
|
||
let chars: Vec<u8> = "Hi\rthere".encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||
let mut style = vec![];
|
||
for (n, lvl) in [(3u32, 0u16), (6, 1)] {
|
||
style.extend_from_slice(&n.to_le_bytes());
|
||
style.extend_from_slice(&lvl.to_le_bytes());
|
||
style.extend_from_slice(&pf_bytes(0, lvl == 1));
|
||
}
|
||
for n in [2u32, 7] {
|
||
style.extend_from_slice(&n.to_le_bytes());
|
||
style.extend_from_slice(&cf_bytes(n == 2, 0, 20, [0, 0, 0]));
|
||
}
|
||
let recs = [
|
||
atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()),
|
||
atom(rt::TEXT_CHARS, 0, &chars),
|
||
atom(rt::STYLE_TEXT_PROP, 0, &style),
|
||
atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()),
|
||
]
|
||
.concat();
|
||
let b = read_block(crate::record::Records::new(&recs)).unwrap();
|
||
assert_eq!(b.text_type, ty::BODY);
|
||
assert_eq!(String::from_utf16_lossy(&b.chars), "Hi\rthere");
|
||
assert_eq!(b.para_runs.len(), 2);
|
||
assert_eq!(b.para_runs[1].1, 1);
|
||
assert_eq!(b.char_runs.len(), 2);
|
||
assert_eq!(b.char_runs[0].1.bold, Some(true));
|
||
}
|
||
|
||
/// A CF exception with only the fields PowerPoint 2002 and later add after `position`:
|
||
/// pp10runid (bit 20), newEAFontRef (bit 24), csFontRef (bit 25) and pp11ext (bit 26).
|
||
fn cf_later_fields() -> Vec<u8> {
|
||
let mut v = (1u32 << 20 | 1 << 24 | 1 << 25 | 1 << 26).to_le_bytes().to_vec();
|
||
v.extend_from_slice(&0x0000_0003u32.to_le_bytes()); // pp10runid + unused
|
||
v.extend_from_slice(&7u16.to_le_bytes()); // newEAFontRef
|
||
v.extend_from_slice(&8u16.to_le_bytes()); // csFontRef
|
||
v.extend_from_slice(&0u32.to_le_bytes()); // pp11ext
|
||
v
|
||
}
|
||
|
||
#[test]
|
||
fn later_character_fields_are_read_past() {
|
||
let bytes = cf_later_fields();
|
||
let mut c = Cursor::new(&bytes);
|
||
assert!(read_cf(&mut c).is_some());
|
||
assert!(c.u8().is_none(), "the cursor stopped inside the exception");
|
||
|
||
// A run carrying those fields, then a bold 18 pt run: the second must read as written.
|
||
let chars: Vec<u8> = "abcd".encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||
let mut style = vec![];
|
||
style.extend_from_slice(&5u32.to_le_bytes());
|
||
style.extend_from_slice(&0u16.to_le_bytes());
|
||
style.extend_from_slice(&pf_bytes(0, false));
|
||
style.extend_from_slice(&2u32.to_le_bytes());
|
||
style.extend_from_slice(&cf_later_fields());
|
||
style.extend_from_slice(&3u32.to_le_bytes());
|
||
style.extend_from_slice(&cf_bytes(true, 1, 18, [0, 0, 0]));
|
||
let recs = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &chars), atom(rt::STYLE_TEXT_PROP, 0, &style)].concat();
|
||
let b = read_block(crate::record::Records::new(&recs)).unwrap();
|
||
assert_eq!(b.char_runs.len(), 2, "{:?}", b.char_runs);
|
||
let (n, cf) = &b.char_runs[1];
|
||
assert_eq!((*n, cf.bold, cf.font, cf.size), (3, Some(true), Some(1), Some(18)));
|
||
}
|
||
|
||
#[test]
|
||
fn styles_inherit_from_level_one_and_the_base_type() {
|
||
let mut s = StyleSheet { types: vec![None; 9], ..Default::default() };
|
||
let lvl = |size: u16, align: u16| (Pf { align: Some(align), ..Default::default() }, Cf { size: Some(size), ..Default::default() });
|
||
s.types[ty::BODY as usize] = Some(LevelStyles { levels: vec![lvl(32, 0), (Pf::default(), Cf { size: Some(28), ..Default::default() })] });
|
||
s.types[ty::CENTER_BODY as usize] = Some(LevelStyles { levels: vec![(Pf { align: Some(1), ..Default::default() }, Cf::default())] });
|
||
let (pf, cf) = s.resolve(ty::CENTER_BODY, 1);
|
||
assert_eq!(cf.size, Some(28));
|
||
assert_eq!(pf.align, Some(1));
|
||
let (pf, cf) = s.resolve(ty::BODY, 0);
|
||
assert_eq!((pf.align, cf.size), (Some(0), Some(32)));
|
||
}
|
||
}
|