mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
* ppt-binary: 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. From storytold/deckcraft@0aef89cb1a (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@9e575ccecc (storytold/deckcraft#1137). * ppt-binary: address review: check the picture budget before copying bitmap data From storytold/deckcraft@470a429392 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@a0ececefeb (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@4fd930ce1a (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@773af639c9 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@b3aa0983bd (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@b70b022362 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@a9cefff8b8 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@60942d5950 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@3869c3dc51 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@5799048d88 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@b58c354246 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@2b0940bff5 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@7ad2f5152b (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@afd57f47e0 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@ab5cf618e1 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@f511a2a66b (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@212788b693 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@fe8023b9c2 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@bf8ec603f3 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@f0b8525cc6 (storytold/deckcraft#1137). * ppt-binary: 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). From storytold/deckcraft@a41bf545e7 (storytold/deckcraft#1137). * ppt-binary: 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 (storytold/deckcraft#1137 review, issue 1). From storytold/deckcraft@79ae833152 (storytold/deckcraft#1137). * ppt-binary: 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 (storytold/deckcraft#1137 review, issue 3). From storytold/deckcraft@135674101f (storytold/deckcraft#1137). * ppt-binary: picture frames, inline picture fills, gradients, footers, numbering The remaining differences from LibreOffice in the storytold/deckcraft#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. From storytold/deckcraft@24437bd075 (storytold/deckcraft#1137). * ppt-binary: 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. From storytold/deckcraft@110e1420fd (storytold/deckcraft#1137). * ppt-binary: on craft-cfb and craft-pptx (the move from DeckCraft) What the move from storytold/deckcraft#1137 changes; the commits before this one are that PR's crates/ppt as it is on its branch, without its manifest. - craft-cfb replaces the crate's own compound-file reader (cfb.rs, 552 lines). Streams are read capped at the file's length, as before. Its six tests (looping chains, mini streams, version 4 sectors, the DIFAT) are covered by craft-cfb's own. The byte helpers move to record.rs. Test files are written by craft-cfb's writer. - deckcraft-model, deckcraft-color and deckcraft-geom become craft-pptx and craft-drawingml, the same types (storytold/deckcraft#2179, storytold/deckcraft#2180 and #792's plan). A gradient now states its shape and rotate-with-shape explicitly, as craft-drawingml's are optional. - DeckCraft's default master (defaults::build_master and blank_presentation) becomes the caller's craft_pptx::Defaults: import(bytes, &defaults), as craft_pptx::import takes. The file's masters take the default master's layouts and placeholders, then the file's theme, placeholder boxes and styles. The tests use a default master with title, body and footer placeholders and the seven layouts .ppt layout types map to; a new test reads with craft_pptx::Plain. - The two tests that drive DeckCraft's engine (open and save, lost slides in the app) stay in DeckCraft. - The fixture's rebuild variable is CRAFT_WRITE_PPT_FIXTURE; old-talk.pps is unchanged and gets its ATTRIBUTION row. Bare #1137 references in comments name storytold/deckcraft#1137. - README, crate README (doctested) and the workspace entry. * ppt-binary: bound text, strings, paths and repeated work from hostile files Tab stops keep the first 64 entries while still reading past the rest, string properties stop at 4096 units, and a freeform path uses at most 8192 vertices, since each of these is copied into every paragraph or inheriting shape. An outline block in the slide list is the text of one shape only; a second reference keeps the shape's own text. The fallback master and each master's layout per type are found once before the slides are converted, a shape's primary property tables are collected without inserting at the front, and a compressed metafile that fails to inflate is charged to the picture budget. * ppt-binary: review fixes for footers, rulers, title masters, paths and numbering A slide's own headers and footers record (instance 0) now wins over the document's, and a text box that points at an outline block keeps the margins and indents of its own ruler. A slide list entry whose object is not a slide is reported as lost. Title masters place their layout's placeholders from their own placeholder boxes, adding any the title layout lacks, and copy only placeholders from an earlier title layout. Slides that don't name a title master no longer pick its layout. Freeform paths skip the points of escape segments, and without segments follow shapePath (closed lines by default, open lines or curves). DIB colour tables are sized by bit depth and refused when they run past the bitmap. Numbering schemes 0x10 to 0x28 map to their DrawingML names, master style levels go to the level they name, and a broken edit chain reads the newest edits rather than the oldest. The nested persist directory test now checks the file is reported damaged, the footer test fails when a layout has no slide number, and the README says tables come in as groups of shapes. * ppt-binary: second review round: failed pictures, title layouts, notes, arcs and property tables Inflating a compressed metafile is now charged its compressed bytes as well as its output, and is refused when those bytes alone pass the remaining budget, so many entries pointing at one stream that inflates to nothing can't each read it again for free. A title master's layout starts only from the defaults' own title layout, not one made for an earlier title master. A notes page shared by two slide records with the same slide id goes to the first only. After elliptical quadrants or a quadratic Bezier escape a path goes on from their last point; after an arc or angle ellipse, whose end isn't one of its vertices, the path stops rather than draw from the wrong place. A property set keeps at most 1024 distinct properties, so copying the drawing defaults into each shape costs a bounded amount. * ppt-binary: take each main master's title-layout base once; test outline notes A title master's layout starts from the placeholders of the defaults' title layout. They are now taken once, when the main master is made, instead of rebuilding the set of title-master layouts and rescanning the master's layouts for every title master, which was quadratic in title masters. A notes page whose body text is in the notes list's outline block also goes to one slide only. --------- Co-authored-by: Oliwier Kulczycki <oleknuso282@gmail.com> Co-authored-by: kiwi4boy <kiwi4boy@gmail.com>
391 lines
17 KiB
Rust
391 lines
17 KiB
Rust
//! The document structure of the `PowerPoint Document` stream ([MS-PPT] §2.1–2.4): the current
|
||
//! user's pointer to the last edit, the chain of edits with their persist directories (which map
|
||
//! object ids to stream offsets, newer edits winning), the document container and the lists of
|
||
//! masters, slides and notes.
|
||
|
||
use std::collections::{HashMap, HashSet, VecDeque};
|
||
|
||
use crate::PptError;
|
||
use crate::record::{Rec, Records};
|
||
|
||
pub mod rt {
|
||
//! Record types used here ([MS-PPT] §2.13.24, [MS-ODRAW] §2.1.4).
|
||
pub const DOCUMENT: u16 = 0x03E8;
|
||
pub const DOCUMENT_ATOM: u16 = 0x03E9;
|
||
pub const SLIDE: u16 = 0x03EE;
|
||
pub const SLIDE_ATOM: u16 = 0x03EF;
|
||
pub const NOTES: u16 = 0x03F0;
|
||
pub const NOTES_ATOM: u16 = 0x03F1;
|
||
pub const ENVIRONMENT: u16 = 0x03F2;
|
||
pub const SLIDE_PERSIST_ATOM: u16 = 0x03F3;
|
||
pub const MAIN_MASTER: u16 = 0x03F8;
|
||
pub const SLIDE_SHOW_SLIDE_INFO: u16 = 0x03F9;
|
||
pub const DRAWING_GROUP: u16 = 0x040B;
|
||
pub const DRAWING: u16 = 0x040C;
|
||
pub const COLOR_SCHEME: u16 = 0x07F0;
|
||
pub const LIST: u16 = 0x07D0;
|
||
pub const PROG_TAGS: u16 = 0x1388;
|
||
pub const PROG_BINARY_TAG: u16 = 0x138A;
|
||
pub const BINARY_TAG_DATA: u16 = 0x138B;
|
||
pub const STYLE_TEXT_PROP9: u16 = 0x0FAC;
|
||
pub const OUTLINE_TEXT_PROPS9: u16 = 0x0FAE;
|
||
pub const OUTLINE_TEXT_PROPS_HEADER: u16 = 0x0FAF;
|
||
pub const FONT_COLLECTION: u16 = 0x07D5;
|
||
pub const OUTLINE_TEXT_REF: u16 = 0x0F9E;
|
||
pub const TEXT_HEADER: u16 = 0x0F9F;
|
||
pub const TEXT_CHARS: u16 = 0x0FA0;
|
||
pub const STYLE_TEXT_PROP: u16 = 0x0FA1;
|
||
pub const TEXT_MASTER_STYLE: u16 = 0x0FA3;
|
||
pub const TEXT_CF_EXCEPTION: u16 = 0x0FA4;
|
||
pub const TEXT_PF_EXCEPTION: u16 = 0x0FA5;
|
||
pub const TEXT_RULER: u16 = 0x0FA6;
|
||
pub const TEXT_BYTES: u16 = 0x0FA8;
|
||
pub const FONT_ENTITY: u16 = 0x0FB7;
|
||
pub const CSTRING: u16 = 0x0FBA;
|
||
pub const SLIDE_NUMBER_MC: u16 = 0x0FD8;
|
||
pub const HEADERS_FOOTERS: u16 = 0x0FD9;
|
||
pub const HEADERS_FOOTERS_ATOM: u16 = 0x0FDA;
|
||
pub const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
|
||
pub const USER_EDIT: u16 = 0x0FF5;
|
||
pub const CURRENT_USER: u16 = 0x0FF6;
|
||
pub const DATETIME_MC: u16 = 0x0FF7;
|
||
pub const GENERIC_DATE_MC: u16 = 0x0FF8;
|
||
pub const PLACEHOLDER_ATOM: u16 = 0x0BC3;
|
||
pub const PERSIST_DIRECTORY: u16 = 0x1772;
|
||
pub const CRYPT_SESSION: u16 = 0x2F14;
|
||
|
||
pub const DGG_CONTAINER: u16 = 0xF000;
|
||
pub const BSTORE: u16 = 0xF001;
|
||
pub const DG_CONTAINER: u16 = 0xF002;
|
||
pub const SPGR_CONTAINER: u16 = 0xF003;
|
||
pub const SP_CONTAINER: u16 = 0xF004;
|
||
pub const FBSE: u16 = 0xF007;
|
||
pub const FSPGR: u16 = 0xF009;
|
||
pub const FSP: u16 = 0xF00A;
|
||
pub const FOPT: u16 = 0xF00B;
|
||
pub const CLIENT_TEXTBOX: u16 = 0xF00D;
|
||
pub const CHILD_ANCHOR: u16 = 0xF00F;
|
||
pub const CLIENT_ANCHOR: u16 = 0xF010;
|
||
pub const CLIENT_DATA: u16 = 0xF011;
|
||
pub const SECONDARY_FOPT: u16 = 0xF121;
|
||
pub const TERTIARY_FOPT: u16 = 0xF122;
|
||
}
|
||
|
||
/// `headerToken` of a `CurrentUserAtom` for an encrypted document.
|
||
const ENCRYPTED_TOKEN: u32 = 0xF3D1_C4DF;
|
||
/// `headerToken` of an unencrypted PowerPoint 97+ document.
|
||
const PLAIN_TOKEN: u32 = 0xE391_C05F;
|
||
/// Edits followed at most along the `offsetLastEdit` chain.
|
||
const MAX_EDITS: usize = 4096;
|
||
|
||
/// A master, slide or notes page as listed in a `SlideListWithTextContainer`.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Listed<'a> {
|
||
/// The container (`SlideContainer`, `MainMasterContainer`, `NotesContainer`).
|
||
pub rec: Rec<'a>,
|
||
/// The id other records use for it (`SlideAtom.masterIdRef`, `NotesAtom.slideIdRef`).
|
||
pub slide_id: u32,
|
||
/// The outline text stored in the list after its `SlidePersistAtom` (placeholders point at it
|
||
/// with an `OutlineTextRefAtom`).
|
||
pub outline: Vec<Records<'a>>,
|
||
}
|
||
|
||
/// The parsed structure of a `.ppt`.
|
||
pub struct Doc<'a> {
|
||
pub document: Rec<'a>,
|
||
pub masters: Vec<Listed<'a>>,
|
||
pub slides: Vec<Listed<'a>>,
|
||
pub notes: Vec<Listed<'a>>,
|
||
/// Slides the slide list names but whose objects couldn't be found: what a damaged file lost.
|
||
pub lost: Vec<String>,
|
||
}
|
||
|
||
/// Read the structure from the `Current User` and `PowerPoint Document` streams.
|
||
pub fn read<'a>(current_user: &[u8], stream: &'a [u8]) -> Result<Doc<'a>, PptError> {
|
||
let damaged = |s: &str| PptError::Damaged(s.to_string());
|
||
// The current user names the newest edit; without it (some writers omit the stream), scan
|
||
// for the last UserEditAtom in the stream.
|
||
let mut edit_at = None;
|
||
// [MS-PPT] allows only the two tokens. Any other value (or none, in a truncated record) is a
|
||
// damaged PowerPoint 97 file or an older format; only the scan below can tell which.
|
||
let mut unknown_token = false;
|
||
if let Some(cu) = Rec::at(current_user, 0).filter(|r| r.kind == rt::CURRENT_USER) {
|
||
match cu.u32(4) {
|
||
Some(ENCRYPTED_TOKEN) => return Err(PptError::Encrypted),
|
||
Some(PLAIN_TOKEN) => edit_at = cu.u32(8).map(|v| v as usize),
|
||
_ => unknown_token = true,
|
||
}
|
||
}
|
||
let edit_at = match edit_at.filter(|&at| Rec::at(stream, at).is_some_and(|r| r.kind == rt::USER_EDIT)) {
|
||
Some(at) => at,
|
||
None => match Records::new(stream).filter(|r| r.kind == rt::USER_EDIT).last() {
|
||
Some(r) => r.offset,
|
||
None if unknown_token => return Err(PptError::TooOld),
|
||
None => return Err(damaged("no edit record")),
|
||
},
|
||
};
|
||
// Walk the edits newest first; the first entry seen for a persist id wins.
|
||
let mut persist: HashMap<u32, usize> = HashMap::new();
|
||
let mut doc_ref = None;
|
||
let mut seen = HashSet::new();
|
||
// Many edits may name one persist directory; it is read once (its first reading wins anyway).
|
||
let mut dirs_seen = HashSet::new();
|
||
// All directories together are read within one stream's worth of words. Real directories
|
||
// don't overlap, so they fit. Hostile ones nested inside each other would otherwise each be
|
||
// read to the end of the stream, once per edit (MAX_EDITS × the stream).
|
||
let mut words = stream.len() / 4;
|
||
let mut at = edit_at;
|
||
// The chain ends at an edit whose previous offset is 0. Ending anywhere else (a loop, an
|
||
// offset that isn't an edit, too many edits) means older edits were cut off.
|
||
let mut broken = true;
|
||
for _ in 0..MAX_EDITS {
|
||
if !seen.insert(at) {
|
||
break;
|
||
}
|
||
let Some(edit) = Rec::at(stream, at).filter(|r| r.kind == rt::USER_EDIT) else { break };
|
||
if doc_ref.is_none() {
|
||
doc_ref = edit.u32(16);
|
||
// An encryptSessionPersistIdRef follows only in encrypted documents.
|
||
if edit.data.len() >= 32 {
|
||
return Err(PptError::Encrypted);
|
||
}
|
||
}
|
||
if let Some(dir) =
|
||
edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY)
|
||
{
|
||
read_persist_directory(dir.data, &mut persist, &mut words);
|
||
}
|
||
match edit.u32(8) {
|
||
Some(0) => {
|
||
broken = false;
|
||
break;
|
||
}
|
||
None => break,
|
||
Some(prev) => at = prev as usize,
|
||
}
|
||
}
|
||
if broken {
|
||
// Recover what the cut-off edits held: every edit in the stream, newest (last written)
|
||
// first, fills only the persist ids the chain left unset. Past MAX_EDITS, the newest are
|
||
// kept: they are the ones that win.
|
||
log::warn!("ppt: the edit history is broken; reading every edit in the stream");
|
||
let mut edits: VecDeque<Rec> = VecDeque::with_capacity(MAX_EDITS.min(64));
|
||
for edit in Records::new(stream).filter(|r| r.kind == rt::USER_EDIT) {
|
||
if edits.len() == MAX_EDITS {
|
||
edits.pop_front();
|
||
}
|
||
edits.push_back(edit);
|
||
}
|
||
for edit in edits.into_iter().rev() {
|
||
if let Some(dir) =
|
||
edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY)
|
||
{
|
||
read_persist_directory(dir.data, &mut persist, &mut words);
|
||
}
|
||
}
|
||
}
|
||
let lookup = |id: u32| persist.get(&id).and_then(|&o| Rec::at(stream, o));
|
||
let document = doc_ref.and_then(lookup).filter(|r| r.kind == rt::DOCUMENT).ok_or_else(|| damaged("no document container"))?;
|
||
if lookup_kind(&persist, stream, rt::CRYPT_SESSION) {
|
||
return Err(PptError::Encrypted);
|
||
}
|
||
let mut doc = Doc { document, masters: vec![], slides: vec![], notes: vec![], lost: vec![] };
|
||
// Each object is listed once. PowerPoint never lists one twice, and a hostile file that lists a
|
||
// big drawing many times would otherwise have it converted again for every listing (shapes ×
|
||
// listings, from linear input).
|
||
let mut listed = HashSet::new();
|
||
for list in document.children_of(rt::SLIDE_LIST_WITH_TEXT) {
|
||
let out = match list.instance {
|
||
0 => &mut doc.slides,
|
||
1 => &mut doc.masters,
|
||
2 => &mut doc.notes,
|
||
_ => continue,
|
||
};
|
||
let mut current: Option<Listed> = None;
|
||
for r in list.children() {
|
||
if r.kind == rt::SLIDE_PERSIST_ATOM {
|
||
if let Some(l) = current.take() {
|
||
out.push(l);
|
||
}
|
||
let (Some(pid), Some(slide_id)) = (r.u32(0), r.u32(12)) else { continue };
|
||
match lookup(pid) {
|
||
// The slide list names slides; anything else there is a slide the file lost.
|
||
Some(rec) if list.instance == 0 && rec.kind != rt::SLIDE => {
|
||
log::warn!("ppt: slide persist id {pid} is not a slide");
|
||
doc.lost.push(format!("slide {slide_id}"));
|
||
}
|
||
Some(rec) if !listed.insert(rec.offset) => log::warn!("ppt: persist id {pid} is listed again; skipped"),
|
||
Some(rec) => current = Some(Listed { rec, slide_id, outline: vec![] }),
|
||
None => {
|
||
log::warn!("ppt: slide persist id {pid} has no object");
|
||
if list.instance == 0 {
|
||
doc.lost.push(format!("slide {slide_id}"));
|
||
}
|
||
}
|
||
}
|
||
} else if r.kind == rt::TEXT_HEADER
|
||
&& let Some(l) = current.as_mut()
|
||
{
|
||
// An outline text block starts at its header and runs to the next header or persist atom.
|
||
let rest = list.data.get(r.offset..).unwrap_or(&[]);
|
||
l.outline.push(Records::new(rest));
|
||
}
|
||
}
|
||
if let Some(l) = current.take() {
|
||
out.push(l);
|
||
}
|
||
}
|
||
Ok(doc)
|
||
}
|
||
|
||
/// Read one persist directory into `persist`, taking each word read from `words`.
|
||
fn read_persist_directory(b: &[u8], persist: &mut HashMap<u32, usize>, words: &mut usize) {
|
||
let mut c = crate::record::Cursor::new(b);
|
||
let mut next = |c: &mut crate::record::Cursor| {
|
||
*words = words.checked_sub(1)?;
|
||
c.u32()
|
||
};
|
||
while let Some(head) = next(&mut c) {
|
||
let first = head & 0x000F_FFFF;
|
||
let count = head >> 20;
|
||
for k in 0..count {
|
||
let Some(off) = next(&mut c) else { return };
|
||
persist.entry(first.saturating_add(k)).or_insert(off as usize);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn lookup_kind(persist: &HashMap<u32, usize>, stream: &[u8], kind: u16) -> bool {
|
||
persist.values().any(|&o| Rec::at(stream, o).is_some_and(|r| r.kind == kind))
|
||
}
|
||
|
||
/// The `DocumentAtom`: slide and notes sizes in master units (576 per inch), first slide number.
|
||
pub struct DocumentAtom {
|
||
pub slide_w: i32,
|
||
pub slide_h: i32,
|
||
pub notes_w: i32,
|
||
pub notes_h: i32,
|
||
pub first_slide_number: u16,
|
||
}
|
||
|
||
impl Doc<'_> {
|
||
pub fn document_atom(&self) -> Option<DocumentAtom> {
|
||
let a = self.document.child(rt::DOCUMENT_ATOM)?;
|
||
Some(DocumentAtom {
|
||
slide_w: a.i32(0)?,
|
||
slide_h: a.i32(4)?,
|
||
notes_w: a.i32(8)?,
|
||
notes_h: a.i32(12)?,
|
||
first_slide_number: a.u16(32).unwrap_or(1),
|
||
})
|
||
}
|
||
}
|
||
|
||
/// The `SlideAtom` of a slide or master.
|
||
#[derive(Clone, Copy, Debug, Default)]
|
||
pub struct SlideAtom {
|
||
/// `SlideLayoutType`.
|
||
pub geom: u32,
|
||
pub master_id: u32,
|
||
pub follow_master_objects: bool,
|
||
pub follow_master_scheme: bool,
|
||
pub follow_master_background: bool,
|
||
}
|
||
|
||
pub fn slide_atom(container: &Rec) -> SlideAtom {
|
||
let Some(a) = container.child(rt::SLIDE_ATOM) else {
|
||
return SlideAtom { follow_master_objects: true, follow_master_scheme: true, follow_master_background: true, ..Default::default() };
|
||
};
|
||
let flags = a.u16(20).unwrap_or(0x7);
|
||
SlideAtom {
|
||
geom: a.u32(0).unwrap_or(0),
|
||
master_id: a.u32(12).unwrap_or(0),
|
||
follow_master_objects: flags & 0x1 != 0,
|
||
follow_master_scheme: flags & 0x2 != 0,
|
||
follow_master_background: flags & 0x4 != 0,
|
||
}
|
||
}
|
||
|
||
/// Font names by index (`FontCollectionContainer` in the environment).
|
||
pub fn fonts(doc: &Doc) -> Vec<String> {
|
||
let Some(coll) = doc.document.child(rt::ENVIRONMENT).and_then(|e| e.child(rt::FONT_COLLECTION)) else { return vec![] };
|
||
coll.children_of(rt::FONT_ENTITY)
|
||
.map(|f| {
|
||
let units: Vec<u16> = (0..32).filter_map(|i| f.u16(i * 2)).take_while(|&u| u != 0).collect();
|
||
String::from_utf16_lossy(&units)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// What a `HeadersFootersContainer` ([MS-PPT] §2.4.15.1 and §2.5.16) says the footer row
|
||
/// shows: the date (today's in a format, or fixed text), the slide number and the footer text.
|
||
#[derive(Clone, Debug, Default, PartialEq)]
|
||
pub struct HeadersFooters {
|
||
/// `formatId`: 0–12, the date format.
|
||
pub format: u16,
|
||
pub date: bool,
|
||
/// The date is fixed text (`fHasUserDate`) rather than today's.
|
||
pub user_date: bool,
|
||
pub slide_number: bool,
|
||
pub footer: bool,
|
||
pub date_text: String,
|
||
pub footer_text: String,
|
||
}
|
||
|
||
/// The UTF-16 units of a `CString` body, up to its first NUL: the record has no terminator, but a
|
||
/// writer that adds one would otherwise put a NUL into the text, or make a tag name fail to match.
|
||
fn cstring_units(b: &[u8]) -> impl Iterator<Item = u16> + '_ {
|
||
b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|&u| u != 0)
|
||
}
|
||
|
||
/// The slides' headers and footers in `container`, from its `HeadersFootersContainer` of
|
||
/// `instance`: 3 in the document (`SlideHeadersFootersContainer`, for every slide), 0 in a slide or
|
||
/// main master (`PerSlideHeadersFootersContainer`, its own).
|
||
pub fn headers_footers(container: &Rec, instance: u16) -> Option<HeadersFooters> {
|
||
let hf = container.children().find(|r| r.kind == rt::HEADERS_FOOTERS && r.instance == instance)?;
|
||
let atom = hf.child(rt::HEADERS_FOOTERS_ATOM)?;
|
||
let flags = atom.u16(2)?;
|
||
let text = |instance: u16| {
|
||
hf.children()
|
||
.find(|r| r.kind == rt::CSTRING && r.instance == instance)
|
||
.map(|r| String::from_utf16_lossy(&cstring_units(r.data).collect::<Vec<u16>>()))
|
||
.unwrap_or_default()
|
||
};
|
||
Some(HeadersFooters {
|
||
format: atom.u16(0).unwrap_or(0),
|
||
date: flags & 0x01 != 0,
|
||
user_date: flags & 0x04 != 0,
|
||
slide_number: flags & 0x08 != 0,
|
||
footer: flags & 0x20 != 0,
|
||
date_text: text(0),
|
||
footer_text: text(2),
|
||
})
|
||
}
|
||
|
||
/// The PowerPoint 2000 paragraph formatting of the slides' outline text ([MS-PPT] §2.4.22.10,
|
||
/// the document's `___PPT9` tag): by slide id and text type, one `StyleTextProp9Atom` for each of
|
||
/// the slide's outline blocks of that type, in order.
|
||
pub fn outline_numbering(document: &Rec) -> HashMap<(u32, u32), Vec<Vec<crate::text::Pf9>>> {
|
||
let mut out: HashMap<(u32, u32), Vec<Vec<crate::text::Pf9>>> = HashMap::new();
|
||
let tags = document.child(rt::LIST).and_then(|l| l.child(rt::PROG_TAGS));
|
||
let Some(tags) = tags else { return out };
|
||
let ppt9 = tags
|
||
.children_of(rt::PROG_BINARY_TAG)
|
||
.find(|tag| tag.child(rt::CSTRING).is_some_and(|name| cstring_units(name.data).eq("___PPT9".encode_utf16())));
|
||
let Some(data) = ppt9.and_then(|t| t.child(rt::BINARY_TAG_DATA)) else { return out };
|
||
// The tag's data is an atom whose body holds records.
|
||
for props in Records::new(data.data).filter(|r| r.kind == rt::OUTLINE_TEXT_PROPS9) {
|
||
let mut header = None;
|
||
for r in props.children() {
|
||
if r.kind == rt::OUTLINE_TEXT_PROPS_HEADER {
|
||
header = r.u32(0).zip(r.u32(4));
|
||
} else if r.kind == rt::STYLE_TEXT_PROP9
|
||
&& let Some(key) = header.take()
|
||
{
|
||
out.entry(key).or_default().push(crate::text::read_style9(r.data));
|
||
}
|
||
}
|
||
}
|
||
out
|
||
}
|