mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-19 09:01:14 +01:00
Add craft-ppt-binary: DeckCraft's PowerPoint 97-2003 reader on craft-cfb and craft-pptx (#2316)
* 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>
This commit is contained in:
16 files changed
+5293
No files matched your search
@@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files |
|
||||
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
|
||||
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
|
||||
| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 |
|
||||
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
|
||||
Generated
+13
@@ -2969,6 +2969,19 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ppt-binary"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-drawingml",
|
||||
"craft-pptx",
|
||||
"image",
|
||||
"log",
|
||||
"miniz_oxide 0.8.9",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pptx"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -161,6 +161,7 @@ craft-opc = { path = "crates/opc" }
|
||||
craft-openpgp = { path = "crates/openpgp" }
|
||||
craft-ora = { path = "crates/ora" }
|
||||
craft-pptx = { path = "crates/pptx" }
|
||||
craft-ppt-binary = { path = "crates/ppt-binary" }
|
||||
craft-penpot = { path = "crates/penpot" }
|
||||
craft-pcraft-format = { path = "crates/pcraft-format" }
|
||||
craft-pcraft-bundle = { path = "crates/pcraft-bundle" }
|
||||
|
||||
@@ -324,6 +324,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
- [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL,
|
||||
DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a
|
||||
job in millimetres, plus the Silhouette device queries and reply parsers. No I/O.
|
||||
- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`;
|
||||
[MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader.
|
||||
- [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation:
|
||||
masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations,
|
||||
comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "craft-ppt-binary"
|
||||
description = "Reader for the PowerPoint 97-2003 binary file format (.ppt, .pot, .pps; [MS-PPT], [MS-ODRAW]) into the craft-pptx presentation model, on craft-cfb."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-cfb = { workspace = true }
|
||||
craft-drawingml = { workspace = true }
|
||||
craft-pptx = { workspace = true }
|
||||
log = { workspace = true }
|
||||
miniz_oxide = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Pictures in the tests: a PNG to embed, and the BMP a DIB blip becomes.
|
||||
image = { version = "0.25", default-features = false, features = ["png", "bmp"] }
|
||||
@@ -0,0 +1,40 @@
|
||||
# craft-ppt-binary
|
||||
|
||||
Reader for the PowerPoint 97-2003 binary file format (`.ppt`, `.pot` and `.pps`) into the
|
||||
`craft-pptx` presentation model. It is DeckCraft's reader, on `craft-cfb` for the compound file.
|
||||
Import only: there is no `.ppt` writer.
|
||||
|
||||
| Document | Used for |
|
||||
|---|---|
|
||||
| [MS-PPT] PowerPoint (.ppt) Binary File Format (Microsoft Open Specifications) | the Current User stream, the edit chain and persist directories, documents, masters, slides, notes, text and its styles, headers and footers |
|
||||
| [MS-ODRAW] Office Drawing Binary File Formats | shapes, their property tables and geometry, the BLIP store and its pictures |
|
||||
| [MS-CFB] Compound File Binary File Format | through `craft-cfb` |
|
||||
|
||||
```rust
|
||||
// Not a compound file: an error, never a panic.
|
||||
assert!(!craft_ppt_binary::sniff(b"not a .ppt"));
|
||||
assert!(craft_ppt_binary::import(b"not a .ppt", &craft_pptx::Plain).is_err());
|
||||
```
|
||||
|
||||
- `sniff(bytes)`, `import(bytes, &defaults)` and `import_checked(bytes, &defaults)`, which also
|
||||
names the slides the file lists but whose objects are gone.
|
||||
- Main masters become masters, with their colour scheme, fonts, text styles, background and
|
||||
decorative shapes. Title masters become layouts of their main master.
|
||||
- Slides keep their shapes (preset and freeform geometry, groups, rotation and flips), fills,
|
||||
lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF and WMF), tables (as groups of shapes, the
|
||||
way the file stores them), and text with the master's styles resolved into it, along with
|
||||
fields, numbering, headers and footers, notes, and hidden slides.
|
||||
- Damaged files read as far as they can: a broken edit chain falls back to a scan of the edits,
|
||||
and unknown or damaged records are skipped. Sizes, counts, nesting and picture decoding are
|
||||
bounded.
|
||||
- Password-protected files are refused (`PptError::Encrypted`), as are PowerPoint 95 and earlier
|
||||
files (`PptError::TooOld`).
|
||||
|
||||
The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from:
|
||||
its layouts and placeholders. The file's masters then place and style the placeholders that
|
||||
master has. With `craft_pptx::Plain` (one blank layout, no placeholders), the slides still read
|
||||
with their own boxes.
|
||||
|
||||
The reader was written for DeckCraft (storytold/deckcraft#1137); the history of
|
||||
`crates/ppt-binary` names its authors. Its tests build `.ppt` files from records; no file made
|
||||
by PowerPoint is used.
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Pictures ([MS-ODRAW] §2.2.32–2.2.45): the drawing group's blip store lists every picture
|
||||
//! (`FBSE`), either holding its blip or pointing into the `Pictures` stream. Shapes name a picture
|
||||
//! by its 1-based index in the store.
|
||||
|
||||
use crate::doc::rt;
|
||||
use crate::record::Rec;
|
||||
|
||||
/// Largest picture inflated from a compressed metafile.
|
||||
const MAX_INFLATED: usize = 64 << 20;
|
||||
/// Most bytes all of a file's pictures may decode to together: 2 GiB, the total a `.pptx` package
|
||||
/// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt`
|
||||
/// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could.
|
||||
/// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0.
|
||||
const MAX_TOTAL: usize = 2 << 30;
|
||||
// A zero or tiny budget would drop every picture without a word, and the shift above can wrap on
|
||||
// a 32-bit target (wasm32) without any error, so the build checks it on every target.
|
||||
const _: () = assert!(MAX_TOTAL >= MAX_INFLATED);
|
||||
|
||||
/// A decoded picture: file extension, content type and bytes as a file of that type.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Picture {
|
||||
pub ext: &'static str,
|
||||
pub content_type: &'static str,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The blip store: each entry's blip record, decoded only when a shape first asks for it, every
|
||||
/// entry at most once, and all of them together within [`MAX_TOTAL`] bytes.
|
||||
pub struct Store<'a> {
|
||||
entries: Vec<Option<Rec<'a>>>,
|
||||
budget: usize,
|
||||
}
|
||||
|
||||
impl<'a> Store<'a> {
|
||||
pub fn new(dgg: Option<Rec<'a>>, pictures_stream: &'a [u8]) -> Self {
|
||||
let entries = match dgg.and_then(|d| d.child(rt::BSTORE)) {
|
||||
Some(bstore) => bstore.children().map(|r| if r.kind == rt::FBSE { fbse(&r, pictures_stream) } else { None }).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
Store { entries, budget: MAX_TOTAL }
|
||||
}
|
||||
|
||||
/// The picture at `index` (0-based; shapes use 1-based ids), taken out of the store. `None`
|
||||
/// for an entry that is empty, can't be read, was taken already, or would pass the budget.
|
||||
pub fn take(&mut self, index: usize) -> Option<Picture> {
|
||||
let blip = self.entries.get_mut(index)?.take()?;
|
||||
self.decode_charged(&blip)
|
||||
}
|
||||
|
||||
/// A blip held in a shape's own property ([MS-ODRAW] §2.2.37: a complex `fillBlip` or `pib`
|
||||
/// whose extra bytes are the blip record itself), decoded within the same budget.
|
||||
pub fn decode_inline(&mut self, bytes: &[u8]) -> Option<Picture> {
|
||||
let blip = Rec::at(bytes, 0).filter(|r| (0xF018..=0xF117).contains(&r.kind))?;
|
||||
self.decode_charged(&blip)
|
||||
}
|
||||
|
||||
/// Decode `blip` and take its size from the budget. A compressed metafile is also charged
|
||||
/// its compressed bytes, which inflating reads whatever it produces, and one that fails to
|
||||
/// inflate is charged what the inflate may have produced before failing: many entries pointing
|
||||
/// at one damaged stream (or one that inflates to nothing) would otherwise each inflate it again
|
||||
/// for free.
|
||||
fn decode_charged(&mut self, blip: &Rec) -> Option<Picture> {
|
||||
let bounds = inflate_bounds(blip, self.budget);
|
||||
let pic = decode(blip, self.budget);
|
||||
let cost = match (&pic, bounds) {
|
||||
(Some(p), Some((input, _))) => input.saturating_add(p.data.len()),
|
||||
(Some(p), None) => p.data.len(),
|
||||
(None, Some((input, output))) => input.saturating_add(output),
|
||||
(None, None) => 0,
|
||||
};
|
||||
self.budget = self.budget.saturating_sub(cost);
|
||||
pic
|
||||
}
|
||||
}
|
||||
|
||||
/// For a compressed metafile (EMF or WMF, with one UID or, for instances 0x3D5 and 0x217, two):
|
||||
/// the compressed bytes inflating it reads, and the most bytes it may produce so that both
|
||||
/// together stay within `limit`. `None` for any other blip, or when the compressed bytes alone
|
||||
/// pass `limit`.
|
||||
fn inflate_bounds(b: &Rec, limit: usize) -> Option<(usize, usize)> {
|
||||
if !matches!(b.kind, 0xF01A | 0xF01B) {
|
||||
return None;
|
||||
}
|
||||
let uids = if matches!(b.instance, 0x3D5 | 0x217) { 32 } else { 16 };
|
||||
let h = b.data.get(uids..uids + 34)?;
|
||||
let size = crate::record::u32_at(h, 0)? as usize;
|
||||
if *h.get(32)? != 0 {
|
||||
return None;
|
||||
}
|
||||
let input = b.data.get(uids + 34..)?.len();
|
||||
let output = limit.checked_sub(input)?;
|
||||
Some((input, size.min(MAX_INFLATED).min(output)))
|
||||
}
|
||||
|
||||
fn fbse<'a>(r: &Rec<'a>, pictures: &'a [u8]) -> Option<Rec<'a>> {
|
||||
// btWin32, btMacOS, rgbUid[16], tag, size, cRef, foDelay, unused, cbName, unused, unused.
|
||||
let size = r.u32(20)? as usize;
|
||||
let offset = r.u32(28)? as usize;
|
||||
let name_len = usize::from(r.u8(33)?);
|
||||
if size == 0 {
|
||||
return None;
|
||||
}
|
||||
let embedded_at = 36usize.checked_add(name_len)?;
|
||||
if r.data.len() > embedded_at { Rec::at(r.data, embedded_at) } else { Rec::at(pictures, offset) }
|
||||
}
|
||||
|
||||
/// Decode one blip record into at most `limit` bytes.
|
||||
pub fn decode(b: &Rec, limit: usize) -> Option<Picture> {
|
||||
// The instance says whether a second UID follows the first.
|
||||
let (kind, two_uids): (u16, bool) = match b.instance {
|
||||
0x3D4 | 0x216 | 0x542 | 0x46A | 0x6E2 | 0x6E0 | 0x7A8 | 0x6E4 => (b.kind, false),
|
||||
0x3D5 | 0x217 | 0x543 | 0x46B | 0x6E3 | 0x6E1 | 0x7A9 | 0x6E5 => (b.kind, true),
|
||||
_ => (b.kind, false),
|
||||
};
|
||||
let uids = if two_uids { 32 } else { 16 };
|
||||
// The bytes a picture is copied from, refused before copying when they (plus `extra` bytes of
|
||||
// header to add) would pass the budget.
|
||||
let within = |bytes: &'_ [u8], extra: usize| bytes.len().checked_add(extra).is_some_and(|n| n <= limit);
|
||||
let bitmap = || b.data.get(uids + 1..).filter(|d| within(d, 0)).map(<[u8]>::to_vec);
|
||||
match kind {
|
||||
// EMF, WMF: a metafile header then (usually deflated) data.
|
||||
0xF01A | 0xF01B => {
|
||||
let h = b.data.get(uids..uids + 34)?;
|
||||
let size = crate::record::u32_at(h, 0)? as usize;
|
||||
let compressed = *h.get(32)? == 0;
|
||||
let body = b.data.get(uids + 34..)?;
|
||||
let data = if compressed {
|
||||
miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(body, inflate_bounds(b, limit)?.1).ok()?
|
||||
} else {
|
||||
body.get(..size.min(body.len())).filter(|d| within(d, 0))?.to_vec()
|
||||
};
|
||||
let (ext, content_type) = if kind == 0xF01A { ("emf", "image/x-emf") } else { ("wmf", "image/x-wmf") };
|
||||
Some(Picture { ext, content_type, data })
|
||||
}
|
||||
// Bitmaps: a one-byte tag then the file.
|
||||
0xF01D | 0xF02A => Some(Picture { ext: "jpg", content_type: "image/jpeg", data: bitmap()? }),
|
||||
0xF01E => Some(Picture { ext: "png", content_type: "image/png", data: bitmap()? }),
|
||||
0xF029 => Some(Picture { ext: "tif", content_type: "image/tiff", data: bitmap()? }),
|
||||
0xF01F => Some(Picture { ext: "bmp", content_type: "image/bmp", data: dib_to_bmp(b.data.get(uids + 1..).filter(|d| within(d, 14))?)? }),
|
||||
// PICT (Macintosh) has no decoder here.
|
||||
_ => None,
|
||||
}
|
||||
.filter(|p| p.data.len() <= limit)
|
||||
}
|
||||
|
||||
/// A device-independent bitmap with the 14-byte file header a `.bmp` needs in front.
|
||||
fn dib_to_bmp(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
let header = crate::record::u32_at(dib, 0)? as usize;
|
||||
let (bits, compression, used) = if header == 12 {
|
||||
(usize::from(crate::record::u16_at(dib, 10)?), 0, 0)
|
||||
} else {
|
||||
(usize::from(crate::record::u16_at(dib, 14)?), crate::record::u32_at(dib, 16)?, crate::record::u32_at(dib, 32)? as usize)
|
||||
};
|
||||
let entry = if header == 12 { 3 } else { 4 };
|
||||
// The colour table: up to 2^bits entries (all of them when biClrUsed is 0) for 8 bits or
|
||||
// fewer; biClrUsed entries, an optional table, for more.
|
||||
let colors = match bits {
|
||||
0..=8 if used > 0 => used.min(1 << bits),
|
||||
0..=8 => 1 << bits,
|
||||
_ => used,
|
||||
};
|
||||
// BI_BITFIELDS with the 40-byte header: three masks follow it.
|
||||
let masks = if compression == 3 && header == 40 { 12 } else { 0 };
|
||||
let offset = 14usize.checked_add(header)?.checked_add(colors.checked_mul(entry)?)?.checked_add(masks)?;
|
||||
let file_len = 14usize.checked_add(dib.len())?;
|
||||
// Pixels starting past the end are no bitmap.
|
||||
if offset > file_len {
|
||||
return None;
|
||||
}
|
||||
let total = u32::try_from(file_len).ok()?;
|
||||
let mut out = Vec::with_capacity(dib.len() + 14);
|
||||
out.extend_from_slice(b"BM");
|
||||
out.extend_from_slice(&total.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(&u32::try_from(offset).ok()?.to_le_bytes());
|
||||
out.extend_from_slice(dib);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use crate::record::build::*;
|
||||
|
||||
fn decode_all(b: &Rec) -> Option<Picture> {
|
||||
decode(b, usize::MAX)
|
||||
}
|
||||
|
||||
/// Many entries pointing at one deflated metafile decode within the shared budget, each
|
||||
/// at most once.
|
||||
#[test]
|
||||
fn the_store_decodes_lazily_within_a_budget() {
|
||||
let wmf = vec![7u8; 1000];
|
||||
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
|
||||
let mut header = vec![0u8; 34];
|
||||
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
|
||||
let pictures = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat());
|
||||
let mut fbse = vec![0u8; 36];
|
||||
fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes());
|
||||
let entries: Vec<Vec<u8>> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect();
|
||||
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]);
|
||||
let mut store = Store::new(Rec::at(&dgg, 0), &pictures);
|
||||
store.budget = 2500;
|
||||
assert_eq!(store.take(0).map(|p| p.data.len()), Some(1000));
|
||||
assert!(store.take(0).is_none(), "taken already");
|
||||
assert!(store.take(1).is_some());
|
||||
assert!(store.take(2).is_none(), "past the budget");
|
||||
assert!(store.take(99).is_none());
|
||||
}
|
||||
|
||||
/// A compressed metafile that fails to inflate still costs the budget what it may have
|
||||
/// inflated, so entries pointing at one damaged stream can't each inflate it again for free.
|
||||
#[test]
|
||||
fn a_failed_inflate_is_charged_to_the_budget() {
|
||||
let mut header = vec![0u8; 34];
|
||||
header[..4].copy_from_slice(&1000u32.to_le_bytes());
|
||||
let damaged = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &[0x78, 0x9C, 0xFF, 0xFF]].concat());
|
||||
let mut fbse = vec![0u8; 36];
|
||||
fbse[20..24].copy_from_slice(&(damaged.len() as u32).to_le_bytes());
|
||||
let entries: Vec<Vec<u8>> = (0..3).map(|_| atom(rt::FBSE, 3, &fbse)).collect();
|
||||
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 3, &entries)]);
|
||||
let mut store = Store::new(Rec::at(&dgg, 0), &damaged);
|
||||
store.budget = 2500;
|
||||
assert!(store.take(0).is_none());
|
||||
assert_eq!(store.budget, 1496, "1000 bytes it may have inflated and the 4 it read");
|
||||
assert!(store.take(1).is_none());
|
||||
assert!(store.take(2).is_none());
|
||||
assert_eq!(store.budget, 0, "the last attempt is charged what was left");
|
||||
// A picture that isn't a compressed metafile costs nothing when it can't be read.
|
||||
let mut store = Store::new(None, &[]);
|
||||
store.budget = 10;
|
||||
assert!(store.decode_inline(&atom(0xF01E, 0x6E0, &[0; 4])).is_none());
|
||||
assert_eq!(store.budget, 10);
|
||||
}
|
||||
|
||||
/// A compressed metafile that inflates to nothing (a declared size of 0 and a run of empty
|
||||
/// stored blocks, here with a bad checksum) still costs the bytes it makes the inflate read, so
|
||||
/// many entries pointing at it run out of budget instead of each reading it again for free.
|
||||
#[test]
|
||||
fn inflating_is_charged_the_compressed_bytes() {
|
||||
let mut z = vec![0x78, 0x01];
|
||||
for _ in 0..200 {
|
||||
z.extend_from_slice(&[0x00, 0x00, 0x00, 0xFF, 0xFF]);
|
||||
}
|
||||
z.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF, 1, 2, 3, 4]);
|
||||
let empty = atom(0xF01B, 0x216, &[&[0u8; 16][..], &[0u8; 34], &z].concat());
|
||||
let mut fbse = vec![0u8; 36];
|
||||
fbse[20..24].copy_from_slice(&(empty.len() as u32).to_le_bytes());
|
||||
let entries: Vec<Vec<u8>> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect();
|
||||
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]);
|
||||
let mut store = Store::new(Rec::at(&dgg, 0), &empty);
|
||||
store.budget = 2 * z.len() + 10;
|
||||
assert!(store.take(0).is_none());
|
||||
assert_eq!(store.budget, z.len() + 10);
|
||||
assert!(store.take(1).is_none());
|
||||
assert_eq!(store.budget, 10);
|
||||
// Too little left for its compressed bytes: not inflated, and nothing charged.
|
||||
assert!(store.take(2).is_none());
|
||||
assert_eq!(store.budget, 10);
|
||||
// One that inflates is charged its compressed bytes as well as what they inflate to.
|
||||
let wmf = vec![7u8; 100];
|
||||
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
|
||||
let mut header = vec![0u8; 34];
|
||||
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
|
||||
let blip = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat());
|
||||
let mut store = Store::new(None, &[]);
|
||||
store.budget = 1000;
|
||||
assert_eq!(store.decode_inline(&blip).map(|p| p.data.len()), Some(100));
|
||||
assert_eq!(store.budget, 1000 - 100 - z.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_png_and_deflated_metafiles() {
|
||||
let png = [&[0u8; 17][..], b"\x89PNG..."].concat();
|
||||
let p = decode_all(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap()).unwrap();
|
||||
assert_eq!((p.ext, &p.data[..4]), ("png", &b"\x89PNG"[..]));
|
||||
// Over the remaining budget: refused before it is copied.
|
||||
assert!(decode(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap(), 6).is_none());
|
||||
|
||||
let wmf = b"\x01\x00\x09\x00\x00\x03 a tiny metafile".to_vec();
|
||||
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
|
||||
let mut header = vec![0u8; 34];
|
||||
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
|
||||
header[28..32].copy_from_slice(&(z.len() as u32).to_le_bytes());
|
||||
let body = [&[0u8; 16][..], &header, &z].concat();
|
||||
let p = decode_all(&Rec::at(&atom(0xF01B, 0x216, &body), 0).unwrap()).unwrap();
|
||||
assert_eq!((p.ext, p.data), ("wmf", wmf));
|
||||
// Damaged deflate data is no picture rather than a panic.
|
||||
let bad = [&[0u8; 16][..], &header, &[1, 2, 3]].concat();
|
||||
assert!(decode_all(&Rec::at(&atom(0xF01A, 0x3D4, &bad), 0).unwrap()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dib_becomes_a_bmp_the_image_crate_reads() {
|
||||
// 1×1, 24-bit.
|
||||
let mut dib = vec![0u8; 40];
|
||||
dib[0] = 40;
|
||||
dib[4] = 1;
|
||||
dib[8] = 1;
|
||||
dib[12] = 1;
|
||||
dib[14] = 24;
|
||||
dib.extend_from_slice(&[0, 0, 255, 0]);
|
||||
let body = [&[0u8; 17][..], &dib].concat();
|
||||
let p = decode_all(&Rec::at(&atom(0xF01F, 0x7A8, &body), 0).unwrap()).unwrap();
|
||||
assert_eq!(&p.data[..2], b"BM");
|
||||
assert_eq!(u32::from_le_bytes(p.data[10..14].try_into().unwrap()), 54);
|
||||
let img = image::load_from_memory_with_format(&p.data, image::ImageFormat::Bmp).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (1, 1));
|
||||
assert_eq!(img.get_pixel(0, 0).0, [255, 0, 0, 255]);
|
||||
}
|
||||
|
||||
/// The pixels start after the colour table: biClrUsed entries for more than 8 bits (none when
|
||||
/// it is 0), at most 2^bits for fewer, and a table running past the DIB is no picture.
|
||||
#[test]
|
||||
fn a_dib_colour_table_is_sized_by_its_bit_depth() {
|
||||
let dib = |bits: u16, used: u32, extra: usize| {
|
||||
let mut d = vec![0u8; 40];
|
||||
d[0] = 40;
|
||||
d[14..16].copy_from_slice(&bits.to_le_bytes());
|
||||
d[32..36].copy_from_slice(&used.to_le_bytes());
|
||||
d.resize(40 + extra, 0);
|
||||
d
|
||||
};
|
||||
let offset = |b: &[u8]| dib_to_bmp(b).map(|bmp| u32::from_le_bytes(bmp[10..14].try_into().unwrap()));
|
||||
assert_eq!(offset(&dib(24, 0, 4)), Some(54));
|
||||
assert_eq!(offset(&dib(24, 300, 1204)), Some(54 + 1200), "more than 256 entries for 24 bits");
|
||||
assert_eq!(offset(&dib(8, 300, 1028)), Some(54 + 1024), "8 bits: at most 256");
|
||||
assert_eq!(offset(&dib(4, 0, 68)), Some(54 + 64));
|
||||
assert_eq!(offset(&dib(24, 300, 100)), None, "the table runs past the DIB");
|
||||
assert_eq!(offset(&dib(32, u32::MAX, 0)), None);
|
||||
}
|
||||
|
||||
/// JPEG (RGB and CMYK), TIFF and a PNG with a second UID: the instance says how many UIDs come
|
||||
/// before the tag byte, and the bytes after it are the file.
|
||||
#[test]
|
||||
fn decodes_each_bitmap_kind() {
|
||||
let file = b"the picture file";
|
||||
for (kind, instance, uids, ext) in [
|
||||
(0xF01D, 0x46A, 16, "jpg"),
|
||||
(0xF01D, 0x46B, 32, "jpg"),
|
||||
(0xF02A, 0x6E2, 16, "jpg"),
|
||||
(0xF029, 0x6E4, 16, "tif"),
|
||||
(0xF029, 0x6E5, 32, "tif"),
|
||||
(0xF01E, 0x6E1, 32, "png"),
|
||||
] {
|
||||
let body = [&vec![0xAAu8; uids][..], &[0xFF], file].concat();
|
||||
let p = decode_all(&Rec::at(&atom(kind, instance, &body), 0).unwrap()).unwrap();
|
||||
assert_eq!((p.ext, p.data.as_slice()), (ext, &file[..]), "{kind:#x}/{instance:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile stored without compression (compression byte 0xFE) is copied as it is, up to its
|
||||
/// stated size; with two UIDs the header starts 32 bytes in.
|
||||
#[test]
|
||||
fn decodes_an_uncompressed_metafile() {
|
||||
let emf = b"\x01\x00\x00\x00 an enhanced metafile".to_vec();
|
||||
let mut header = vec![0u8; 34];
|
||||
header[..4].copy_from_slice(&(emf.len() as u32).to_le_bytes());
|
||||
header[28..32].copy_from_slice(&(emf.len() as u32).to_le_bytes());
|
||||
header[32] = 0xFE;
|
||||
for (instance, uids) in [(0x3D4, 16), (0x3D5, 32)] {
|
||||
let body = [&vec![0u8; uids][..], &header, &emf, b"trailing"].concat();
|
||||
let p = decode_all(&Rec::at(&atom(0xF01A, instance, &body), 0).unwrap()).unwrap();
|
||||
assert_eq!((p.ext, &p.data), ("emf", &emf));
|
||||
}
|
||||
}
|
||||
|
||||
/// A metafile whose inflated size (with its compressed bytes) would pass the remaining budget is refused, compressed or not.
|
||||
#[test]
|
||||
fn a_metafile_over_the_budget_is_refused() {
|
||||
let wmf = vec![9u8; 4000];
|
||||
let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6);
|
||||
let mut header = vec![0u8; 34];
|
||||
header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes());
|
||||
let deflated = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat());
|
||||
// The budget covers the compressed bytes read as well as the bytes they inflate to.
|
||||
assert!(decode(&Rec::at(&deflated, 0).unwrap(), 3999 + z.len()).is_none());
|
||||
assert_eq!(decode(&Rec::at(&deflated, 0).unwrap(), 4000 + z.len()).map(|p| p.data.len()), Some(4000));
|
||||
header[32] = 0xFE;
|
||||
let raw = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &wmf].concat());
|
||||
assert!(decode(&Rec::at(&raw, 0).unwrap(), 3999).is_none());
|
||||
assert!(decode(&Rec::at(&raw, 0).unwrap(), 4000).is_some());
|
||||
}
|
||||
|
||||
/// An FBSE may hold its blip itself, after its name, instead of pointing into the Pictures
|
||||
/// stream.
|
||||
#[test]
|
||||
fn a_blip_inside_its_fbse_is_read() {
|
||||
let png = [&[0u8; 17][..], b"\x89PNG inside"].concat();
|
||||
let blip = atom(0xF01E, 0x6E0, &png);
|
||||
let name = "p".encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>();
|
||||
let mut fbse = [0u8; 36];
|
||||
fbse[20..24].copy_from_slice(&(blip.len() as u32).to_le_bytes());
|
||||
fbse[33] = name.len() as u8;
|
||||
let entry = atom(rt::FBSE, 6, &[&fbse[..], &name, &blip].concat());
|
||||
let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 1, &[entry])]);
|
||||
// The Pictures stream is empty: the blip can only come from the FBSE.
|
||||
let mut store = Store::new(Rec::at(&dgg, 0), &[]);
|
||||
let p = store.take(0).unwrap();
|
||||
assert_eq!((p.ext, &p.data[..]), ("png", &b"\x89PNG inside"[..]));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,390 @@
|
||||
//! The document structure of the `PowerPoint Document` stream ([MS-PPT] §2.1–2.4): the current
|
||||
//! user's pointer to the last edit, the chain of edits with their persist directories (which map
|
||||
//! object ids to stream offsets, newer edits winning), the document container and the lists of
|
||||
//! masters, slides and notes.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
|
||||
use crate::PptError;
|
||||
use crate::record::{Rec, Records};
|
||||
|
||||
pub mod rt {
|
||||
//! Record types used here ([MS-PPT] §2.13.24, [MS-ODRAW] §2.1.4).
|
||||
pub const DOCUMENT: u16 = 0x03E8;
|
||||
pub const DOCUMENT_ATOM: u16 = 0x03E9;
|
||||
pub const SLIDE: u16 = 0x03EE;
|
||||
pub const SLIDE_ATOM: u16 = 0x03EF;
|
||||
pub const NOTES: u16 = 0x03F0;
|
||||
pub const NOTES_ATOM: u16 = 0x03F1;
|
||||
pub const ENVIRONMENT: u16 = 0x03F2;
|
||||
pub const SLIDE_PERSIST_ATOM: u16 = 0x03F3;
|
||||
pub const MAIN_MASTER: u16 = 0x03F8;
|
||||
pub const SLIDE_SHOW_SLIDE_INFO: u16 = 0x03F9;
|
||||
pub const DRAWING_GROUP: u16 = 0x040B;
|
||||
pub const DRAWING: u16 = 0x040C;
|
||||
pub const COLOR_SCHEME: u16 = 0x07F0;
|
||||
pub const LIST: u16 = 0x07D0;
|
||||
pub const PROG_TAGS: u16 = 0x1388;
|
||||
pub const PROG_BINARY_TAG: u16 = 0x138A;
|
||||
pub const BINARY_TAG_DATA: u16 = 0x138B;
|
||||
pub const STYLE_TEXT_PROP9: u16 = 0x0FAC;
|
||||
pub const OUTLINE_TEXT_PROPS9: u16 = 0x0FAE;
|
||||
pub const OUTLINE_TEXT_PROPS_HEADER: u16 = 0x0FAF;
|
||||
pub const FONT_COLLECTION: u16 = 0x07D5;
|
||||
pub const OUTLINE_TEXT_REF: u16 = 0x0F9E;
|
||||
pub const TEXT_HEADER: u16 = 0x0F9F;
|
||||
pub const TEXT_CHARS: u16 = 0x0FA0;
|
||||
pub const STYLE_TEXT_PROP: u16 = 0x0FA1;
|
||||
pub const TEXT_MASTER_STYLE: u16 = 0x0FA3;
|
||||
pub const TEXT_CF_EXCEPTION: u16 = 0x0FA4;
|
||||
pub const TEXT_PF_EXCEPTION: u16 = 0x0FA5;
|
||||
pub const TEXT_RULER: u16 = 0x0FA6;
|
||||
pub const TEXT_BYTES: u16 = 0x0FA8;
|
||||
pub const FONT_ENTITY: u16 = 0x0FB7;
|
||||
pub const CSTRING: u16 = 0x0FBA;
|
||||
pub const SLIDE_NUMBER_MC: u16 = 0x0FD8;
|
||||
pub const HEADERS_FOOTERS: u16 = 0x0FD9;
|
||||
pub const HEADERS_FOOTERS_ATOM: u16 = 0x0FDA;
|
||||
pub const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
|
||||
pub const USER_EDIT: u16 = 0x0FF5;
|
||||
pub const CURRENT_USER: u16 = 0x0FF6;
|
||||
pub const DATETIME_MC: u16 = 0x0FF7;
|
||||
pub const GENERIC_DATE_MC: u16 = 0x0FF8;
|
||||
pub const PLACEHOLDER_ATOM: u16 = 0x0BC3;
|
||||
pub const PERSIST_DIRECTORY: u16 = 0x1772;
|
||||
pub const CRYPT_SESSION: u16 = 0x2F14;
|
||||
|
||||
pub const DGG_CONTAINER: u16 = 0xF000;
|
||||
pub const BSTORE: u16 = 0xF001;
|
||||
pub const DG_CONTAINER: u16 = 0xF002;
|
||||
pub const SPGR_CONTAINER: u16 = 0xF003;
|
||||
pub const SP_CONTAINER: u16 = 0xF004;
|
||||
pub const FBSE: u16 = 0xF007;
|
||||
pub const FSPGR: u16 = 0xF009;
|
||||
pub const FSP: u16 = 0xF00A;
|
||||
pub const FOPT: u16 = 0xF00B;
|
||||
pub const CLIENT_TEXTBOX: u16 = 0xF00D;
|
||||
pub const CHILD_ANCHOR: u16 = 0xF00F;
|
||||
pub const CLIENT_ANCHOR: u16 = 0xF010;
|
||||
pub const CLIENT_DATA: u16 = 0xF011;
|
||||
pub const SECONDARY_FOPT: u16 = 0xF121;
|
||||
pub const TERTIARY_FOPT: u16 = 0xF122;
|
||||
}
|
||||
|
||||
/// `headerToken` of a `CurrentUserAtom` for an encrypted document.
|
||||
const ENCRYPTED_TOKEN: u32 = 0xF3D1_C4DF;
|
||||
/// `headerToken` of an unencrypted PowerPoint 97+ document.
|
||||
const PLAIN_TOKEN: u32 = 0xE391_C05F;
|
||||
/// Edits followed at most along the `offsetLastEdit` chain.
|
||||
const MAX_EDITS: usize = 4096;
|
||||
|
||||
/// A master, slide or notes page as listed in a `SlideListWithTextContainer`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Listed<'a> {
|
||||
/// The container (`SlideContainer`, `MainMasterContainer`, `NotesContainer`).
|
||||
pub rec: Rec<'a>,
|
||||
/// The id other records use for it (`SlideAtom.masterIdRef`, `NotesAtom.slideIdRef`).
|
||||
pub slide_id: u32,
|
||||
/// The outline text stored in the list after its `SlidePersistAtom` (placeholders point at it
|
||||
/// with an `OutlineTextRefAtom`).
|
||||
pub outline: Vec<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
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
//! OfficeArt drawings ([MS-ODRAW]) as `.ppt` stores them: a tree of shape group containers and
|
||||
//! shape containers, each shape with its `FSP` (type, id, flags), property tables (`FOPT`),
|
||||
//! anchor and client records (placeholder, text).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::doc::rt;
|
||||
use crate::record::{MAX_DEPTH, Rec};
|
||||
|
||||
/// Property ids ([MS-ODRAW] §2.3).
|
||||
pub mod prop {
|
||||
pub const ROTATION: u16 = 0x0004;
|
||||
pub const TEXT_LEFT: u16 = 0x0081;
|
||||
pub const TEXT_TOP: u16 = 0x0082;
|
||||
pub const TEXT_RIGHT: u16 = 0x0083;
|
||||
pub const TEXT_BOTTOM: u16 = 0x0084;
|
||||
pub const WRAP_TEXT: u16 = 0x0085;
|
||||
pub const ANCHOR_TEXT: u16 = 0x0087;
|
||||
pub const CROP_TOP: u16 = 0x0100;
|
||||
pub const CROP_BOTTOM: u16 = 0x0101;
|
||||
pub const CROP_LEFT: u16 = 0x0102;
|
||||
pub const CROP_RIGHT: u16 = 0x0103;
|
||||
pub const PIB: u16 = 0x0104;
|
||||
pub const GEO_LEFT: u16 = 0x0140;
|
||||
pub const GEO_TOP: u16 = 0x0141;
|
||||
pub const GEO_RIGHT: u16 = 0x0142;
|
||||
pub const GEO_BOTTOM: u16 = 0x0143;
|
||||
pub const SHAPE_PATH: u16 = 0x0144;
|
||||
pub const VERTICES: u16 = 0x0145;
|
||||
pub const SEGMENT_INFO: u16 = 0x0146;
|
||||
pub const ADJUST_VALUE: u16 = 0x0147;
|
||||
pub const FILL_TYPE: u16 = 0x0180;
|
||||
pub const FILL_COLOR: u16 = 0x0181;
|
||||
pub const FILL_OPACITY: u16 = 0x0182;
|
||||
pub const FILL_BACK_COLOR: u16 = 0x0183;
|
||||
pub const FILL_BACK_OPACITY: u16 = 0x0184;
|
||||
pub const FILL_BLIP: u16 = 0x0186;
|
||||
pub const FILL_ANGLE: u16 = 0x018B;
|
||||
pub const FILL_FOCUS: u16 = 0x018C;
|
||||
pub const FILL_BOOLS: u16 = 0x01BF;
|
||||
pub const LINE_COLOR: u16 = 0x01C0;
|
||||
pub const LINE_OPACITY: u16 = 0x01C1;
|
||||
pub const LINE_WIDTH: u16 = 0x01CB;
|
||||
pub const LINE_STYLE: u16 = 0x01CD;
|
||||
pub const LINE_DASHING: u16 = 0x01CE;
|
||||
pub const LINE_START_ARROW: u16 = 0x01D0;
|
||||
pub const LINE_END_ARROW: u16 = 0x01D1;
|
||||
pub const LINE_START_ARROW_WIDTH: u16 = 0x01D2;
|
||||
pub const LINE_START_ARROW_LENGTH: u16 = 0x01D3;
|
||||
pub const LINE_END_ARROW_WIDTH: u16 = 0x01D4;
|
||||
pub const LINE_END_ARROW_LENGTH: u16 = 0x01D5;
|
||||
pub const LINE_JOIN: u16 = 0x01D6;
|
||||
pub const LINE_CAP: u16 = 0x01D7;
|
||||
pub const LINE_BOOLS: u16 = 0x01FF;
|
||||
pub const SHADOW_COLOR: u16 = 0x0201;
|
||||
pub const SHADOW_OPACITY: u16 = 0x0204;
|
||||
pub const SHADOW_OFFSET_X: u16 = 0x0205;
|
||||
pub const SHADOW_OFFSET_Y: u16 = 0x0206;
|
||||
pub const SHADOW_BOOLS: u16 = 0x023F;
|
||||
pub const HSP_MASTER: u16 = 0x0301;
|
||||
pub const NAME: u16 = 0x0380;
|
||||
pub const DESCRIPTION: u16 = 0x0381;
|
||||
pub const GROUP_BOOLS: u16 = 0x03BF;
|
||||
}
|
||||
|
||||
/// UTF-16 units kept of a string property.
|
||||
pub const MAX_STRING: usize = 4096;
|
||||
|
||||
/// Distinct properties one set keeps. Ids are 14 bits, so a file's tables could name about 16K of
|
||||
/// them, and every shape copies the drawing defaults' and its master shape's sets into its own:
|
||||
/// unbounded, that is shapes × 16K. [MS-ODRAW] defines a few hundred properties and a real shape
|
||||
/// or the drawing defaults set tens of them. Entries past the limit are still read (their complex
|
||||
/// data keeps its place) but not kept.
|
||||
pub const MAX_PROPS: usize = 1024;
|
||||
|
||||
/// One property value: the 32-bit operand and, for complex properties, the extra bytes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PropVal<'a> {
|
||||
pub op: u32,
|
||||
pub complex: Option<&'a [u8]>,
|
||||
}
|
||||
|
||||
/// A shape's merged property tables (primary first; secondary and tertiary fill gaps).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Props<'a> {
|
||||
map: HashMap<u16, PropVal<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Props<'a> {
|
||||
/// Read one `FOPT` body: `count` 6-byte entries then the complex data in entry order. Entries
|
||||
/// already present are kept (the caller adds the most specific table first).
|
||||
pub fn add_table(&mut self, r: &Rec<'a>) {
|
||||
let count = usize::from(r.instance);
|
||||
let mut complex_at = count.saturating_mul(6);
|
||||
for i in 0..count {
|
||||
let (Some(id), Some(op)) = (r.u16(i * 6), r.u32(i * 6 + 2)) else { break };
|
||||
let is_complex = id & 0x8000 != 0;
|
||||
let pid = id & 0x3FFF;
|
||||
let complex = if is_complex {
|
||||
let len = op as usize;
|
||||
let data = r.data.get(complex_at..complex_at.saturating_add(len).min(r.data.len()));
|
||||
complex_at = complex_at.saturating_add(len);
|
||||
data
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.fill_gap(pid, PropVal { op, complex });
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill gaps from another set (a master shape's or the drawing defaults).
|
||||
pub fn inherit(&mut self, other: &Props<'a>) {
|
||||
for (k, v) in &other.map {
|
||||
self.fill_gap(*k, *v);
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `v` for `id` where this set doesn't say it already. A boolean property word ([MS-ODRAW]:
|
||||
/// the last id of each 64-id group) holds sixteen flags, each with its own `fUse` bit 16
|
||||
/// places up, so it is merged flag by flag: a shape that sets only `fNoFillHitTest` still
|
||||
/// inherits `fFilled` from its master or the defaults.
|
||||
fn fill_gap(&mut self, id: u16, v: PropVal<'a>) {
|
||||
let full = self.map.len() >= MAX_PROPS;
|
||||
match self.map.get_mut(&id) {
|
||||
None if full => {}
|
||||
None => {
|
||||
self.map.insert(id, v);
|
||||
}
|
||||
Some(have) if id & 0x3F == 0x3F => {
|
||||
let unset = !(have.op >> 16) & 0xFFFF;
|
||||
let take = (v.op >> 16) & unset;
|
||||
have.op |= take << 16;
|
||||
have.op = (have.op & !take) | (v.op & take);
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a simple (non-complex) property.
|
||||
pub fn set(&mut self, id: u16, op: u32) {
|
||||
self.map.insert(id, PropVal { op, complex: None });
|
||||
}
|
||||
|
||||
pub fn get(&self, id: u16) -> Option<u32> {
|
||||
self.map.get(&id).map(|v| v.op)
|
||||
}
|
||||
|
||||
pub fn complex(&self, id: u16) -> Option<&'a [u8]> {
|
||||
self.map.get(&id).and_then(|v| v.complex)
|
||||
}
|
||||
|
||||
/// A 16.16 fixed-point value.
|
||||
pub fn fixed(&self, id: u16) -> Option<f64> {
|
||||
self.get(id).map(|v| f64::from(v as i32) / 65536.0)
|
||||
}
|
||||
|
||||
/// A boolean from a bool-property word: bit `bit` holds the value, bit `bit + 16` says it is set.
|
||||
pub fn flag(&self, id: u16, bit: u32) -> Option<bool> {
|
||||
let v = self.get(id)?;
|
||||
(v & (1 << (bit + 16)) != 0).then_some(v & (1 << bit) != 0)
|
||||
}
|
||||
|
||||
/// A UTF-16 string property (names, alt text), at most [`MAX_STRING`] units: a master shape's
|
||||
/// name is copied into every shape that inherits it.
|
||||
pub fn string(&self, id: u16) -> Option<String> {
|
||||
let b = self.complex(id)?;
|
||||
let units: Vec<u16> = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take(MAX_STRING).take_while(|&u| u != 0).collect();
|
||||
Some(String::from_utf16_lossy(&units)).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// An `IMsoArray` property: element size and the elements' bytes.
|
||||
pub fn array(&self, id: u16) -> Option<(usize, &'a [u8])> {
|
||||
let b = self.complex(id)?;
|
||||
let n = usize::from(crate::record::u16_at(b, 0)?);
|
||||
let size = crate::record::u16_at(b, 4)?;
|
||||
// 0xFFF0 marks 4-byte elements stored as two 2-byte halves.
|
||||
let size = if size == 0xFFF0 { 4 } else { usize::from(size) };
|
||||
if size == 0 {
|
||||
return None;
|
||||
}
|
||||
let body = b.get(6..)?;
|
||||
let len = n.saturating_mul(size).min(body.len() / size * size);
|
||||
Some((size, body.get(..len)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// An anchor rectangle in its own coordinate units: master units for a client anchor, the parent
|
||||
/// group's units for a child anchor.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Anchor {
|
||||
pub left: f64,
|
||||
pub top: f64,
|
||||
pub right: f64,
|
||||
pub bottom: f64,
|
||||
}
|
||||
|
||||
/// The placeholder a shape stands for (`OEPlaceholderAtom`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Placeholder {
|
||||
pub position: u32,
|
||||
/// `PlaceholderEnum`.
|
||||
pub kind: u8,
|
||||
}
|
||||
|
||||
/// One shape of a drawing, before conversion.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RawShape<'a> {
|
||||
/// `MSOSPT` shape type.
|
||||
pub shape_type: u16,
|
||||
pub spid: u32,
|
||||
pub flip_h: bool,
|
||||
pub flip_v: bool,
|
||||
pub patriarch: bool,
|
||||
pub deleted: bool,
|
||||
pub props: Props<'a>,
|
||||
pub anchor: Option<Anchor>,
|
||||
/// For a group: the child coordinate rectangle (`FSPGR`).
|
||||
pub group_rect: Option<Anchor>,
|
||||
pub children: Vec<RawShape<'a>>,
|
||||
pub is_group: bool,
|
||||
pub placeholder: Option<Placeholder>,
|
||||
/// The records of the shape's text box (`OfficeArtClientTextbox`).
|
||||
pub text: Option<Rec<'a>>,
|
||||
}
|
||||
|
||||
/// The top-level shapes and the background shape of a `DrawingContainer`.
|
||||
pub struct Drawing<'a> {
|
||||
pub shapes: Vec<RawShape<'a>>,
|
||||
pub background: Option<RawShape<'a>>,
|
||||
}
|
||||
|
||||
/// Read the drawing of a slide, master or notes container.
|
||||
pub fn drawing<'a>(container: &Rec<'a>) -> Drawing<'a> {
|
||||
let mut out = Drawing { shapes: vec![], background: None };
|
||||
let Some(dg) = container.child(rt::DRAWING).and_then(|d| d.child(rt::DG_CONTAINER)) else { return out };
|
||||
// The background is the container's own shape (`OfficeArtDgContainer.shape`, [MS-ODRAW]
|
||||
// 2.2.13), not one found by its fBackground flag.
|
||||
if let Some(bg) = dg.child(rt::SP_CONTAINER) {
|
||||
out.background = Some(shape(&bg));
|
||||
}
|
||||
if let Some(top) = dg.child(rt::SPGR_CONTAINER) {
|
||||
// The first shape of the top group is the patriarch, standing for the drawing itself.
|
||||
out.shapes = group_children(&top, 0).into_iter().filter(|s| !s.patriarch).collect();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn group_children<'a>(gr: &Rec<'a>, depth: usize) -> Vec<RawShape<'a>> {
|
||||
if depth > MAX_DEPTH {
|
||||
return vec![];
|
||||
}
|
||||
let mut out = vec![];
|
||||
for r in gr.children() {
|
||||
match r.kind {
|
||||
rt::SP_CONTAINER => out.push(shape(&r)),
|
||||
rt::SPGR_CONTAINER => {
|
||||
let mut kids = r.children();
|
||||
// A group container's first shape describes the group itself.
|
||||
let Some(head) = kids.next().filter(|h| h.kind == rt::SP_CONTAINER) else { continue };
|
||||
let mut g = shape(&head);
|
||||
g.is_group = true;
|
||||
g.children = group_children(&r, depth + 1).into_iter().skip(1).collect();
|
||||
out.push(g);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn rect_i32(r: &Rec) -> Option<Anchor> {
|
||||
Some(Anchor { left: f64::from(r.i32(0)?), top: f64::from(r.i32(4)?), right: f64::from(r.i32(8)?), bottom: f64::from(r.i32(12)?) })
|
||||
}
|
||||
|
||||
fn shape<'a>(sp: &Rec<'a>) -> RawShape<'a> {
|
||||
let mut s = RawShape {
|
||||
shape_type: 0,
|
||||
spid: 0,
|
||||
flip_h: false,
|
||||
flip_v: false,
|
||||
patriarch: false,
|
||||
deleted: false,
|
||||
props: Props::default(),
|
||||
anchor: None,
|
||||
group_rect: None,
|
||||
children: vec![],
|
||||
is_group: false,
|
||||
placeholder: None,
|
||||
text: None,
|
||||
};
|
||||
// Tables in specificity order: primary (the last one first), then secondary and tertiary.
|
||||
let mut primary: Vec<Rec> = vec![];
|
||||
let mut tables: Vec<Rec> = vec![];
|
||||
for r in sp.children() {
|
||||
match r.kind {
|
||||
rt::FSP => {
|
||||
s.shape_type = r.instance;
|
||||
s.spid = r.u32(0).unwrap_or(0);
|
||||
let f = r.u32(4).unwrap_or(0);
|
||||
s.patriarch = f & 0x4 != 0;
|
||||
s.deleted = f & 0x8 != 0;
|
||||
s.flip_h = f & 0x40 != 0;
|
||||
s.flip_v = f & 0x80 != 0;
|
||||
}
|
||||
rt::FOPT => primary.push(r),
|
||||
rt::SECONDARY_FOPT | rt::TERTIARY_FOPT => tables.push(r),
|
||||
rt::FSPGR => s.group_rect = rect_i32(&r),
|
||||
rt::CHILD_ANCHOR => s.anchor = rect_i32(&r),
|
||||
rt::CLIENT_ANCHOR => {
|
||||
s.anchor = if r.data.len() >= 16 {
|
||||
// RectStruct: top, left, right, bottom.
|
||||
(|| {
|
||||
Some(Anchor {
|
||||
top: f64::from(r.i32(0)?),
|
||||
left: f64::from(r.i32(4)?),
|
||||
right: f64::from(r.i32(8)?),
|
||||
bottom: f64::from(r.i32(12)?),
|
||||
})
|
||||
})()
|
||||
} else {
|
||||
// SmallRectStruct: top, left, right, bottom.
|
||||
(|| {
|
||||
Some(Anchor {
|
||||
top: f64::from(r.i16(0)?),
|
||||
left: f64::from(r.i16(2)?),
|
||||
right: f64::from(r.i16(4)?),
|
||||
bottom: f64::from(r.i16(6)?),
|
||||
})
|
||||
})()
|
||||
};
|
||||
}
|
||||
rt::CLIENT_DATA => {
|
||||
if let Some(p) = r.child(rt::PLACEHOLDER_ATOM) {
|
||||
s.placeholder = Some(Placeholder { position: p.u32(0).unwrap_or(0), kind: p.u8(4).unwrap_or(0) });
|
||||
}
|
||||
}
|
||||
rt::CLIENT_TEXTBOX => s.text = Some(r),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for t in primary.iter().rev().chain(&tables) {
|
||||
s.props.add_table(t);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The drawing-wide default properties (`OfficeArtDggContainer`'s `FOPT`).
|
||||
pub fn default_props<'a>(dgg: Option<Rec<'a>>) -> Props<'a> {
|
||||
let mut p = Props::default();
|
||||
if let Some(dgg) = dgg {
|
||||
for t in dgg.children().filter(|r| matches!(r.kind, rt::FOPT | rt::SECONDARY_FOPT | rt::TERTIARY_FOPT)) {
|
||||
p.add_table(&t);
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use crate::record::build::*;
|
||||
|
||||
pub fn fopt(entries: &[(u16, u32)], complex: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![];
|
||||
for (id, op) in entries {
|
||||
b.extend_from_slice(&id.to_le_bytes());
|
||||
b.extend_from_slice(&op.to_le_bytes());
|
||||
}
|
||||
b.extend_from_slice(complex);
|
||||
atom(rt::FOPT, entries.len() as u16, &b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_properties_and_complex_strings() {
|
||||
let name: Vec<u8> = "Logo\0".encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let t = fopt(&[(prop::FILL_COLOR, 0x0011_2233), (0x8000 | prop::NAME, name.len() as u32), (prop::FILL_BOOLS, 0x0010_0000)], &name);
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
assert_eq!(p.get(prop::FILL_COLOR), Some(0x0011_2233));
|
||||
assert_eq!(p.string(prop::NAME).as_deref(), Some("Logo"));
|
||||
assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false));
|
||||
assert_eq!(p.flag(prop::LINE_BOOLS, 3), None);
|
||||
}
|
||||
|
||||
/// A boolean word inherits the flags it doesn't set (storytold/deckcraft#1137 review): a text box that sets only
|
||||
/// `fNoFillHitTest` (bit 4 is `fFilled`, bit 0 `fNoFillHitTest`) still gets "not filled"
|
||||
/// from below, and its own flags win over the inherited ones.
|
||||
#[test]
|
||||
fn boolean_properties_merge_flag_by_flag() {
|
||||
let mut p = Props::default();
|
||||
p.set(prop::FILL_BOOLS, 0x0001_0001); // fNoFillHitTest = true; fFilled not said
|
||||
p.set(prop::LINE_BOOLS, 0x0008_0008); // fLine = true
|
||||
let mut below = Props::default();
|
||||
below.set(prop::FILL_BOOLS, 0x0011_0000); // fFilled = false, fNoFillHitTest = false
|
||||
below.set(prop::LINE_BOOLS, 0x0008_0000); // fLine = false
|
||||
p.inherit(&below);
|
||||
assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false));
|
||||
assert_eq!(p.flag(prop::FILL_BOOLS, 0), Some(true));
|
||||
assert_eq!(p.flag(prop::LINE_BOOLS, 3), Some(true));
|
||||
// The same merge applies between a shape's own tables.
|
||||
let t = fopt(&[(prop::FILL_BOOLS, 0x0001_0001)], &[]);
|
||||
let t2 = fopt(&[(prop::FILL_BOOLS, 0x0010_0010)], &[]);
|
||||
let mut q = Props::default();
|
||||
q.add_table(&Rec::at(&t, 0).unwrap());
|
||||
q.add_table(&Rec::at(&t2, 0).unwrap());
|
||||
assert_eq!(q.flag(prop::FILL_BOOLS, 4), Some(true));
|
||||
assert_eq!(q.flag(prop::FILL_BOOLS, 0), Some(true));
|
||||
// Non-boolean properties still keep the first value.
|
||||
let mut r = Props::default();
|
||||
r.set(prop::FILL_COLOR, 1);
|
||||
let mut s = Props::default();
|
||||
s.set(prop::FILL_COLOR, 2);
|
||||
r.inherit(&s);
|
||||
assert_eq!(r.get(prop::FILL_COLOR), Some(1));
|
||||
}
|
||||
|
||||
/// A string property longer than [`MAX_STRING`] units is cut there.
|
||||
#[test]
|
||||
fn a_long_string_property_is_capped() {
|
||||
let name: Vec<u8> = "x".repeat(10_000).encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let t = fopt(&[(0x8000 | prop::NAME, name.len() as u32)], &name);
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
assert_eq!(p.string(prop::NAME).map(|s| s.len()), Some(MAX_STRING));
|
||||
}
|
||||
|
||||
/// A table naming more than [`MAX_PROPS`] properties keeps that many, and still reads the
|
||||
/// complex data after them and the records after it.
|
||||
#[test]
|
||||
fn a_property_set_keeps_at_most_max_props() {
|
||||
let mut entries: Vec<(u16, u32)> = (0..MAX_PROPS as u16 + 100).map(|i| (0x1000 + i, u32::from(i))).collect();
|
||||
let name: Vec<u8> = "Kept\0".encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
entries.insert(0, (0x8000 | prop::NAME, name.len() as u32));
|
||||
let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat());
|
||||
let anchor = atom(rt::CHILD_ANCHOR, 0, &[1i32, 2, 3, 4].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let sp = container(rt::SP_CONTAINER, 0, &[fsp, fopt(&entries, &name), anchor]);
|
||||
let s = shape(&Rec::at(&sp, 0).unwrap());
|
||||
assert_eq!(s.props.map.len(), MAX_PROPS);
|
||||
assert_eq!(s.props.string(prop::NAME).as_deref(), Some("Kept"));
|
||||
assert_eq!(s.props.get(0x1000), Some(0));
|
||||
assert_eq!(s.props.get(0x1000 + MAX_PROPS as u16), None, "past the limit");
|
||||
assert_eq!(s.anchor, Some(Anchor { left: 1.0, top: 2.0, right: 3.0, bottom: 4.0 }));
|
||||
// Inheriting can't pass the limit either.
|
||||
let mut p = Props::default();
|
||||
p.set(prop::FILL_COLOR, 1);
|
||||
p.inherit(&s.props);
|
||||
assert_eq!(p.map.len(), MAX_PROPS);
|
||||
}
|
||||
|
||||
/// A shape's later primary property table wins over its earlier one, and both over its
|
||||
/// secondary table.
|
||||
#[test]
|
||||
fn the_last_primary_table_wins() {
|
||||
let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat());
|
||||
let secondary = {
|
||||
let mut b = vec![];
|
||||
for (id, op) in [(prop::FILL_COLOR, 3u32), (prop::LINE_COLOR, 3)] {
|
||||
b.extend_from_slice(&id.to_le_bytes());
|
||||
b.extend_from_slice(&op.to_le_bytes());
|
||||
}
|
||||
atom(rt::SECONDARY_FOPT, 2, &b)
|
||||
};
|
||||
let sp = container(
|
||||
rt::SP_CONTAINER,
|
||||
0,
|
||||
&[fsp, secondary, fopt(&[(prop::FILL_COLOR, 1), (prop::LINE_WIDTH, 1)], &[]), fopt(&[(prop::FILL_COLOR, 2)], &[])],
|
||||
);
|
||||
let s = shape(&Rec::at(&sp, 0).unwrap());
|
||||
assert_eq!((s.props.get(prop::FILL_COLOR), s.props.get(prop::LINE_WIDTH), s.props.get(prop::LINE_COLOR)), (Some(2), Some(1), Some(3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complex_length_past_the_record_is_clipped() {
|
||||
let t = fopt(&[(0x8000 | prop::NAME, 0xFFFF_FFFF), (0x8000 | prop::DESCRIPTION, 10)], b"A\0");
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
assert_eq!(p.string(prop::NAME).as_deref(), Some("A"));
|
||||
assert_eq!(p.complex(prop::DESCRIPTION), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_groups_anchors_and_placeholders() {
|
||||
let fsp = |t: u16, id: u32, flags: u32| atom(rt::FSP, t, &[id.to_le_bytes(), flags.to_le_bytes()].concat());
|
||||
let small =
|
||||
|t: i16, l: i16, r: i16, b: i16| atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let child =
|
||||
|l: i32, t: i32, r: i32, b: i32| atom(rt::CHILD_ANCHOR, 0, &[l, t, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
|
||||
let ph = container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, 0x0D, 0, 0, 0])]);
|
||||
let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]);
|
||||
let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0xA00), small(10, 20, 300, 80), ph]);
|
||||
let group = container(
|
||||
rt::SPGR_CONTAINER,
|
||||
0,
|
||||
&[
|
||||
container(
|
||||
rt::SP_CONTAINER,
|
||||
0,
|
||||
&[
|
||||
atom(rt::FSPGR, 1, &[0i32, 0, 100, 100].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>()),
|
||||
fsp(0, 1026, 0x201),
|
||||
small(100, 100, 200, 200),
|
||||
],
|
||||
),
|
||||
container(rt::SP_CONTAINER, 0, &[fsp(3, 1027, 0x40), child(0, 0, 50, 50)]),
|
||||
],
|
||||
);
|
||||
let drawing = container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &[container(rt::SPGR_CONTAINER, 0, &[patriarch, title, group])])]);
|
||||
let slide = container(rt::SLIDE, 0, &[drawing]);
|
||||
let d = super::drawing(&Rec::at(&slide, 0).unwrap());
|
||||
assert_eq!(d.shapes.len(), 2);
|
||||
let t = &d.shapes[0];
|
||||
assert_eq!(t.placeholder.unwrap().kind, 0x0D);
|
||||
assert_eq!(t.anchor, Some(Anchor { left: 20.0, top: 10.0, right: 300.0, bottom: 80.0 }));
|
||||
let g = &d.shapes[1];
|
||||
assert!(g.is_group);
|
||||
assert_eq!(g.children.len(), 1);
|
||||
assert!(g.children[0].flip_h);
|
||||
assert_eq!(g.group_rect.unwrap().right, 100.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Shape geometry: OfficeArt shape types (`MSOSPT`, [MS-ODRAW] §2.4.24) as DrawingML preset
|
||||
//! names, and freeform paths from the vertices and segment properties (§2.3.6).
|
||||
|
||||
use craft_pptx::{CustomPath, Geom};
|
||||
|
||||
use crate::draw::{Props, prop};
|
||||
|
||||
/// The preset for a shape type, `None` for a freeform (`msosptNotPrimitive`) or a type with no
|
||||
/// preset counterpart.
|
||||
pub fn preset_name(shape_type: u16) -> Option<&'static str> {
|
||||
Some(match shape_type {
|
||||
1 | 75 | 202 | 201 => "rect",
|
||||
2 => "roundRect",
|
||||
3 => "ellipse",
|
||||
4 => "diamond",
|
||||
5 => "triangle",
|
||||
6 => "rtTriangle",
|
||||
7 => "parallelogram",
|
||||
8 => "trapezoid",
|
||||
9 => "hexagon",
|
||||
10 => "octagon",
|
||||
11 => "plus",
|
||||
12 => "star5",
|
||||
13 | 14 => "rightArrow",
|
||||
15 => "homePlate",
|
||||
16 => "cube",
|
||||
17 => "wedgeRoundRectCallout",
|
||||
18 => "star16",
|
||||
19 => "arc",
|
||||
20 => "line",
|
||||
21 => "plaque",
|
||||
22 => "can",
|
||||
23 => "donut",
|
||||
32 => "straightConnector1",
|
||||
33 => "bentConnector2",
|
||||
34 => "bentConnector3",
|
||||
35 => "bentConnector4",
|
||||
36 => "bentConnector5",
|
||||
37 => "curvedConnector2",
|
||||
38 => "curvedConnector3",
|
||||
39 => "curvedConnector4",
|
||||
40 => "curvedConnector5",
|
||||
41 | 178 => "callout1",
|
||||
42 => "callout2",
|
||||
43 => "callout3",
|
||||
44 | 179 => "accentCallout1",
|
||||
45 => "accentCallout2",
|
||||
46 => "accentCallout3",
|
||||
47 | 180 => "borderCallout1",
|
||||
48 => "borderCallout2",
|
||||
49 => "borderCallout3",
|
||||
50 | 181 => "accentBorderCallout1",
|
||||
51 => "accentBorderCallout2",
|
||||
52 => "accentBorderCallout3",
|
||||
53 => "ribbon",
|
||||
54 => "ribbon2",
|
||||
55 => "chevron",
|
||||
56 => "pentagon",
|
||||
57 => "noSmoking",
|
||||
58 => "star8",
|
||||
59 => "star16",
|
||||
60 => "star32",
|
||||
61 => "wedgeRectCallout",
|
||||
62 => "wedgeRoundRectCallout",
|
||||
63 => "wedgeEllipseCallout",
|
||||
64 => "wave",
|
||||
65 => "foldedCorner",
|
||||
66 => "leftArrow",
|
||||
67 => "downArrow",
|
||||
68 => "upArrow",
|
||||
69 => "leftRightArrow",
|
||||
70 => "upDownArrow",
|
||||
71 => "irregularSeal1",
|
||||
72 => "irregularSeal2",
|
||||
73 => "lightningBolt",
|
||||
74 => "heart",
|
||||
76 => "quadArrow",
|
||||
77 => "leftArrowCallout",
|
||||
78 => "rightArrowCallout",
|
||||
79 => "upArrowCallout",
|
||||
80 => "downArrowCallout",
|
||||
81 => "leftRightArrowCallout",
|
||||
82 => "upDownArrowCallout",
|
||||
83 => "quadArrowCallout",
|
||||
84 => "bevel",
|
||||
85 => "leftBracket",
|
||||
86 => "rightBracket",
|
||||
87 => "leftBrace",
|
||||
88 => "rightBrace",
|
||||
89 => "leftUpArrow",
|
||||
90 => "bentUpArrow",
|
||||
91 => "bentArrow",
|
||||
92 => "star24",
|
||||
93 => "stripedRightArrow",
|
||||
94 => "notchedRightArrow",
|
||||
95 => "blockArc",
|
||||
96 => "smileyFace",
|
||||
97 => "verticalScroll",
|
||||
98 => "horizontalScroll",
|
||||
99 | 100 => "circularArrow",
|
||||
101 => "uturnArrow",
|
||||
102 => "curvedRightArrow",
|
||||
103 => "curvedLeftArrow",
|
||||
104 => "curvedUpArrow",
|
||||
105 => "curvedDownArrow",
|
||||
106 => "cloudCallout",
|
||||
107 => "ellipseRibbon",
|
||||
108 => "ellipseRibbon2",
|
||||
109 => "flowChartProcess",
|
||||
110 => "flowChartDecision",
|
||||
111 => "flowChartInputOutput",
|
||||
112 => "flowChartPredefinedProcess",
|
||||
113 => "flowChartInternalStorage",
|
||||
114 => "flowChartDocument",
|
||||
115 => "flowChartMultidocument",
|
||||
116 => "flowChartTerminator",
|
||||
117 => "flowChartPreparation",
|
||||
118 => "flowChartManualInput",
|
||||
119 => "flowChartManualOperation",
|
||||
120 => "flowChartConnector",
|
||||
121 => "flowChartPunchedCard",
|
||||
122 => "flowChartPunchedTape",
|
||||
123 => "flowChartSummingJunction",
|
||||
124 => "flowChartOr",
|
||||
125 => "flowChartCollate",
|
||||
126 => "flowChartSort",
|
||||
127 => "flowChartExtract",
|
||||
128 => "flowChartMerge",
|
||||
129 => "flowChartOfflineStorage",
|
||||
130 => "flowChartOnlineStorage",
|
||||
131 => "flowChartMagneticTape",
|
||||
132 => "flowChartMagneticDisk",
|
||||
133 => "flowChartMagneticDrum",
|
||||
134 => "flowChartDisplay",
|
||||
135 => "flowChartDelay",
|
||||
176 => "flowChartAlternateProcess",
|
||||
177 => "flowChartOffpageConnector",
|
||||
182 => "leftRightUpArrow",
|
||||
183 => "sun",
|
||||
184 => "moon",
|
||||
185 => "bracketPair",
|
||||
186 => "bracePair",
|
||||
187 => "star4",
|
||||
188 => "doubleWave",
|
||||
189 => "actionButtonBlank",
|
||||
190 => "actionButtonHome",
|
||||
191 => "actionButtonHelp",
|
||||
192 => "actionButtonInformation",
|
||||
193 => "actionButtonForwardNext",
|
||||
194 => "actionButtonBackPrevious",
|
||||
195 => "actionButtonEnd",
|
||||
196 => "actionButtonBeginning",
|
||||
197 => "actionButtonReturn",
|
||||
198 => "actionButtonDocument",
|
||||
199 => "actionButtonSound",
|
||||
200 => "actionButtonMovie",
|
||||
// WordArt text shapes (24–31, 136–175) draw their text as plain text in a rectangle.
|
||||
24..=31 | 136..=175 => "rect",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a shape type is a connector.
|
||||
pub fn is_connector(shape_type: u16) -> bool {
|
||||
(32..=40).contains(&shape_type)
|
||||
}
|
||||
|
||||
/// The geometry of a shape: its preset (checked against the presets `craft_drawingml` draws, with a
|
||||
/// rounded rectangle's corner carried over), else its freeform path, else a rectangle.
|
||||
pub fn geometry(shape_type: u16, props: &Props) -> Geom {
|
||||
if let Some(name) = preset_name(shape_type).filter(|n| craft_drawingml::preset::build(n, 100.0, 100.0, &[]).is_some()) {
|
||||
let mut adj = vec![];
|
||||
// A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the
|
||||
// shorter side in DrawingML.
|
||||
if shape_type == 2
|
||||
&& let Some(v) = props.get(prop::ADJUST_VALUE)
|
||||
{
|
||||
adj.push(f64::from(v as i32).clamp(0.0, 10800.0) / 21600.0 * 100_000.0);
|
||||
}
|
||||
return Geom::Preset { name: name.into(), adj };
|
||||
}
|
||||
custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Segments followed at most in one path.
|
||||
const MAX_SEGMENTS: usize = 1 << 16;
|
||||
/// Vertices used at most in one path. The path text is copied into every shape that inherits the
|
||||
/// vertices from a master shape, so it stays a bounded size.
|
||||
const MAX_POINTS: usize = 8192;
|
||||
|
||||
/// A freeform's path in its geometry box.
|
||||
fn custom_path(props: &Props) -> Option<Vec<CustomPath>> {
|
||||
let (size, verts) = props.array(prop::VERTICES)?;
|
||||
let points: Vec<(f64, f64)> = match size {
|
||||
8 => verts
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.take(MAX_POINTS)
|
||||
.map(|c| (f64::from(i32::from_le_bytes([c[0], c[1], c[2], c[3]])), f64::from(i32::from_le_bytes([c[4], c[5], c[6], c[7]]))))
|
||||
.collect(),
|
||||
4 => verts
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.take(MAX_POINTS)
|
||||
.map(|c| (f64::from(i16::from_le_bytes([c[0], c[1]])), f64::from(i16::from_le_bytes([c[2], c[3]]))))
|
||||
.collect(),
|
||||
_ => return None,
|
||||
};
|
||||
if points.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let left = f64::from(props.get(prop::GEO_LEFT).unwrap_or(0) as i32);
|
||||
let top = f64::from(props.get(prop::GEO_TOP).unwrap_or(0) as i32);
|
||||
let right = f64::from(props.get(prop::GEO_RIGHT).unwrap_or(21600) as i32);
|
||||
let bottom = f64::from(props.get(prop::GEO_BOTTOM).unwrap_or(21600) as i32);
|
||||
let (w, h) = ((right - left).abs().max(1.0), (bottom - top).abs().max(1.0));
|
||||
let mut pts = points.iter().map(|(x, y)| (x - left, y - top));
|
||||
let mut d = String::new();
|
||||
let mut push = |cmd: &str, ps: &[(f64, f64)]| {
|
||||
d.push_str(cmd);
|
||||
for (x, y) in ps {
|
||||
d.push_str(&format!(" {x} {y}"));
|
||||
}
|
||||
d.push(' ');
|
||||
};
|
||||
match props.array(prop::SEGMENT_INFO) {
|
||||
// An empty segment list is no segments ([MS-ODRAW] shapePath: it applies unless the list
|
||||
// is "neither NULL nor empty").
|
||||
Some((2, segs)) if !segs.is_empty() => {
|
||||
for c in segs.as_chunks::<2>().0.iter().take(MAX_SEGMENTS) {
|
||||
let v = u16::from_le_bytes(*c);
|
||||
let count = usize::from(v & 0x1FFF);
|
||||
match v >> 13 {
|
||||
// lineTo
|
||||
0 => {
|
||||
for _ in 0..count.max(1) {
|
||||
let Some(p) = pts.next() else { break };
|
||||
push("L", &[p]);
|
||||
}
|
||||
}
|
||||
// curveTo: three points per segment
|
||||
1 => {
|
||||
for _ in 0..count.max(1) {
|
||||
let ps: Vec<_> = pts.by_ref().take(3).collect();
|
||||
if ps.len() < 3 {
|
||||
break;
|
||||
}
|
||||
push("C", &ps);
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
let Some(p) = pts.next() else { break };
|
||||
push("M", &[p]);
|
||||
}
|
||||
3 => push("Z", &[]),
|
||||
4 => break,
|
||||
// Escapes (MSOPATHESCAPEINFO: escape code in bits 8–12, point count in bits
|
||||
// 0–7). They aren't drawn as curves, but they use up their points, and the
|
||||
// segments after them start where they end.
|
||||
5 => {
|
||||
let n = usize::from(v & 0xFF);
|
||||
let code = (v >> 8) & 0x1F;
|
||||
let mut last = None;
|
||||
for _ in 0..n {
|
||||
last = pts.next().or(last);
|
||||
}
|
||||
match code {
|
||||
// Extension: more points for the escape that follows. Fill and line
|
||||
// colours: a colour pair, not a place. NoFill, NoLine and the Bézier
|
||||
// editing hints: no points.
|
||||
0x00 | 0x0A..=0x16 => {}
|
||||
// Elliptical quadrants run from point to point and a quadratic Bézier
|
||||
// ends on its last point: a line there keeps the path's place.
|
||||
0x07..=0x09 => {
|
||||
if let Some(p) = last {
|
||||
push("L", &[p]);
|
||||
}
|
||||
}
|
||||
// Angle ellipses and arcs end at a point computed from their angles or
|
||||
// radial vectors, not at one of their vertices: the path stops rather
|
||||
// than go on from the wrong place. So does any other escape.
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
// Client escapes mean what the writing application says: the path stops
|
||||
// unless one has no points.
|
||||
6 if v & 0xFF != 0 => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// No segments: shapePath says how the vertices join (MSOSHAPEPATH), by default
|
||||
// msoshapeLinesClosed.
|
||||
_ => {
|
||||
let shape_path = props.get(prop::SHAPE_PATH).unwrap_or(1);
|
||||
if let Some(p) = pts.next() {
|
||||
push("M", &[p]);
|
||||
}
|
||||
if matches!(shape_path, 2 | 3) {
|
||||
loop {
|
||||
let ps: Vec<_> = pts.by_ref().take(3).collect();
|
||||
if ps.len() < 3 {
|
||||
break;
|
||||
}
|
||||
push("C", &ps);
|
||||
}
|
||||
} else {
|
||||
for p in pts {
|
||||
push("L", &[p]);
|
||||
}
|
||||
}
|
||||
if matches!(shape_path, 1 | 3) {
|
||||
push("Z", &[]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let d = d.trim_end().to_string();
|
||||
if !d.starts_with('M') {
|
||||
return None;
|
||||
}
|
||||
Some(vec![CustomPath { w, h, d, ..Default::default() }])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use crate::record::Rec;
|
||||
use crate::record::build::atom;
|
||||
|
||||
fn props(entries: &[(u16, u32)], complex: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![];
|
||||
for (id, op) in entries {
|
||||
b.extend_from_slice(&id.to_le_bytes());
|
||||
b.extend_from_slice(&op.to_le_bytes());
|
||||
}
|
||||
b.extend_from_slice(complex);
|
||||
atom(crate::doc::rt::FOPT, entries.len() as u16, &b)
|
||||
}
|
||||
|
||||
fn array(size: u16, elems: &[u8]) -> Vec<u8> {
|
||||
let n = (elems.len() / usize::from(size)) as u16;
|
||||
[&n.to_le_bytes()[..], &n.to_le_bytes(), &size.to_le_bytes(), elems].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_mapped_preset_is_one_craft_drawingml_draws() {
|
||||
for t in 0..=255u16 {
|
||||
if let Some(name) = preset_name(t) {
|
||||
assert!(craft_drawingml::preset::build(name, 100.0, 100.0, &[]).is_some(), "type {t}: {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_freeform_triangle() {
|
||||
let verts: Vec<u8> = [(0i16, 100i16), (50, 0), (100, 100)].iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect();
|
||||
// moveTo, lineTo ×2, close, end
|
||||
let segs: Vec<u8> = [0x4000u16, 0x0002, 0x6001, 0x8000].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let v = array(4, &verts);
|
||||
let s = array(2, &segs);
|
||||
let t = props(
|
||||
&[
|
||||
(prop::GEO_RIGHT, 100),
|
||||
(prop::GEO_BOTTOM, 100),
|
||||
(0x8000 | prop::VERTICES, v.len() as u32),
|
||||
(0x8000 | prop::SEGMENT_INFO, s.len() as u32),
|
||||
],
|
||||
&[v, s].concat(),
|
||||
);
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") };
|
||||
assert_eq!(paths[0].d, "M 0 100 L 50 0 L 100 100 Z");
|
||||
assert_eq!((paths[0].w, paths[0].h), (100.0, 100.0));
|
||||
}
|
||||
|
||||
/// A freeform with more vertices than [`MAX_POINTS`] draws through the first of them only.
|
||||
#[test]
|
||||
fn a_path_uses_at_most_max_points() {
|
||||
let verts: Vec<u8> = (0..20_000u32).flat_map(|i| [(i as i16 % 100).to_le_bytes(), 0i16.to_le_bytes()].concat()).collect();
|
||||
let v = array(4, &verts);
|
||||
let t = props(&[(0x8000 | prop::VERTICES, v.len() as u32)], &v);
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") };
|
||||
let d = &paths[0].d;
|
||||
assert_eq!(d.matches('M').count() + d.matches('L').count(), MAX_POINTS);
|
||||
}
|
||||
|
||||
fn freeform(verts: &[(i16, i16)], segs: Option<&[u16]>, extra: &[(u16, u32)]) -> Geom {
|
||||
let verts: Vec<u8> = verts.iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect();
|
||||
let v = array(4, &verts);
|
||||
let mut entries = vec![(prop::GEO_RIGHT, 100), (prop::GEO_BOTTOM, 100), (0x8000 | prop::VERTICES, v.len() as u32)];
|
||||
entries.extend_from_slice(extra);
|
||||
let mut complex = v;
|
||||
if let Some(segs) = segs {
|
||||
let s = array(2, &segs.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
|
||||
entries.push((0x8000 | prop::SEGMENT_INFO, s.len() as u32));
|
||||
complex.extend_from_slice(&s);
|
||||
}
|
||||
let t = props(&entries, &complex);
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
geometry(0, &p)
|
||||
}
|
||||
|
||||
fn path_of(g: Geom) -> String {
|
||||
let Geom::Custom { paths } = g else { panic!("not custom: {g:?}") };
|
||||
paths[0].d.clone()
|
||||
}
|
||||
|
||||
/// An escape segment uses up its points and the path goes on from where it ends: after
|
||||
/// elliptical quadrants or a quadratic Bézier, from their last point; an arc ends at a point
|
||||
/// worked out from its radial vectors, so the path stops there rather than draw the next line
|
||||
/// from the point before the arc.
|
||||
#[test]
|
||||
fn path_escapes_end_where_they_end() {
|
||||
let verts = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (50, 60)];
|
||||
let escape = |code: u16, n: u16| (5u16 << 13) | (code << 8) | n;
|
||||
// moveTo, escape ArcTo (3) over 4 points, lineTo, end.
|
||||
assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(3, 4), 0x0001, 0x8000]), &[])), "M 0 0");
|
||||
// moveTo, two elliptical quadrants (7), lineTo, end.
|
||||
let verts = [(0, 0), (10, 10), (20, 0), (50, 60)];
|
||||
assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(7, 2), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0 L 50 60");
|
||||
// A colour escape uses its point but doesn't move the path.
|
||||
assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(0x15, 1), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0");
|
||||
}
|
||||
|
||||
/// Without segments, shapePath says how the vertices join: closed lines by default, open
|
||||
/// lines, or Bézier curves three points at a time. An empty segment list is no segments.
|
||||
#[test]
|
||||
fn shape_path_joins_vertices_without_segments() {
|
||||
let tri = [(0, 100), (50, 0), (100, 100)];
|
||||
assert_eq!(path_of(freeform(&tri, None, &[])), "M 0 100 L 50 0 L 100 100 Z");
|
||||
assert_eq!(path_of(freeform(&tri, Some(&[]), &[])), "M 0 100 L 50 0 L 100 100 Z");
|
||||
assert_eq!(path_of(freeform(&tri, None, &[(prop::SHAPE_PATH, 0)])), "M 0 100 L 50 0 L 100 100");
|
||||
let curve = [(0, 0), (10, 0), (20, 10), (20, 20)];
|
||||
assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 2)])), "M 0 0 C 10 0 20 10 20 20");
|
||||
assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 3)])), "M 0 0 C 10 0 20 10 20 20 Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_rectangle_keeps_its_corner() {
|
||||
let t = props(&[(prop::ADJUST_VALUE, 5400)], &[]);
|
||||
let mut p = Props::default();
|
||||
p.add_table(&Rec::at(&t, 0).unwrap());
|
||||
assert_eq!(geometry(2, &p), Geom::Preset { name: "roundRect".into(), adj: vec![25000.0] });
|
||||
assert_eq!(geometry(9999, &Props::default()), Geom::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Legacy PowerPoint 97–2003 import (`.ppt`, `.pot`, `.pps`), written from Microsoft's public
|
||||
//! Open Specifications: [MS-PPT] (the presentation records) and [MS-ODRAW] (the shapes and
|
||||
//! pictures), on `craft-cfb` for the compound file ([MS-CFB]).
|
||||
//!
|
||||
//! [`import`] reads a presentation leniently into a [`craft_pptx::Presentation`]: unknown records
|
||||
//! are skipped, damaged ones are left out, and every size, count and depth is bounded. The caller's
|
||||
//! [`Defaults`] supply each master's layouts and placeholders, which the file's masters then
|
||||
//! place and style. There is no `.ppt` writer.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[cfg(doctest)]
|
||||
#[doc = include_str!("../README.md")]
|
||||
struct ReadmeExamples;
|
||||
|
||||
mod blip;
|
||||
mod convert;
|
||||
mod doc;
|
||||
mod draw;
|
||||
mod geom;
|
||||
mod record;
|
||||
mod text;
|
||||
|
||||
use craft_cfb::{CompoundFile, Error as CfbError};
|
||||
use craft_pptx::{Defaults, Presentation};
|
||||
|
||||
/// Name of the stream holding the presentation.
|
||||
const DOCUMENT_STREAM: &str = "PowerPoint Document";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PptError {
|
||||
#[error("not a PowerPoint 97-2003 presentation")]
|
||||
NotPpt,
|
||||
#[error("the presentation is password-protected")]
|
||||
Encrypted,
|
||||
#[error("the presentation was made by PowerPoint 95 or earlier")]
|
||||
TooOld,
|
||||
#[error("the presentation is damaged: {0}")]
|
||||
Damaged(String),
|
||||
}
|
||||
|
||||
/// Does this look like a PowerPoint 97–2003 file (a compound file with a `PowerPoint Document`
|
||||
/// stream)?
|
||||
pub fn sniff(bytes: &[u8]) -> bool {
|
||||
craft_cfb::sniff(bytes) && CompoundFile::open(bytes).is_ok_and(|f| f.has_stream(DOCUMENT_STREAM))
|
||||
}
|
||||
|
||||
/// Read a `.ppt` / `.pot` / `.pps` file. `defaults` gives the master each of the file's masters
|
||||
/// starts from, and the one used when the file has none it can read.
|
||||
pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result<Presentation, PptError> {
|
||||
import_checked(bytes, defaults).map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// [`import`], plus the slides the file lists but whose objects couldn't be found, so they are not
|
||||
/// in the presentation.
|
||||
pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec<String>), PptError> {
|
||||
let file = CompoundFile::open(bytes).map_err(|e| match e {
|
||||
CfbError::NotCfb => PptError::NotPpt,
|
||||
other => PptError::Damaged(other.to_string()),
|
||||
})?;
|
||||
// No stream is longer than the file holding it: a larger stated size is damage, refused
|
||||
// before anything is allocated for it.
|
||||
let cap = bytes.len() as u64;
|
||||
let stream = file.read_path_capped(DOCUMENT_STREAM, cap).map_err(|e| match e {
|
||||
CfbError::NotFound(_) => PptError::NotPpt,
|
||||
other => PptError::Damaged(other.to_string()),
|
||||
})?;
|
||||
let current_user = file.read_path_capped("Current User", cap).unwrap_or_default();
|
||||
// A damaged or missing picture stream costs the pictures, not the presentation.
|
||||
let pictures = file.read_path_capped("Pictures", cap).unwrap_or_default();
|
||||
let d = doc::read(¤t_user, &stream)?;
|
||||
Ok((convert::convert(&d, &pictures, defaults), d.lost.clone()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,186 @@
|
||||
//! The record framing shared by [MS-PPT] and [MS-ODRAW]: an 8-byte header (version, instance,
|
||||
//! type, length) followed by `len` bytes, which for a container (version `0xF`) are more records.
|
||||
|
||||
/// The little-endian `u16` at `at`, if `b` holds it.
|
||||
pub(crate) fn u16_at(b: &[u8], at: usize) -> Option<u16> {
|
||||
let s = b.get(at..at.checked_add(2)?)?;
|
||||
Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]))
|
||||
}
|
||||
|
||||
/// The little-endian `u32` at `at`, if `b` holds it.
|
||||
pub(crate) fn u32_at(b: &[u8], at: usize) -> Option<u32> {
|
||||
let s = b.get(at..at.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?]))
|
||||
}
|
||||
|
||||
/// Containers nest at most this deep; deeper input is treated as damaged and skipped.
|
||||
pub const MAX_DEPTH: usize = 32;
|
||||
|
||||
/// One record over borrowed bytes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Rec<'a> {
|
||||
pub ver: u8,
|
||||
pub instance: u16,
|
||||
pub kind: u16,
|
||||
/// The record's body (after the header), clipped to the input.
|
||||
pub data: &'a [u8],
|
||||
/// Offset of the header in the slice it was read from.
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
impl<'a> Rec<'a> {
|
||||
/// The record whose header starts at `at`, its body clipped to `bytes` (a truncated last record
|
||||
/// keeps what is there).
|
||||
pub fn at(bytes: &'a [u8], at: usize) -> Option<Rec<'a>> {
|
||||
let vi = u16_at(bytes, at)?;
|
||||
let kind = u16_at(bytes, at.checked_add(2)?)?;
|
||||
let len = u32_at(bytes, at.checked_add(4)?)? as usize;
|
||||
let start = at.checked_add(8)?;
|
||||
let end = start.saturating_add(len).min(bytes.len());
|
||||
Some(Rec { ver: (vi & 0xF) as u8, instance: vi >> 4, kind, data: bytes.get(start..end)?, offset: at })
|
||||
}
|
||||
|
||||
pub fn is_container(&self) -> bool {
|
||||
self.ver == 0xF
|
||||
}
|
||||
|
||||
/// The records inside this one; none for an atom.
|
||||
pub fn children(&self) -> Records<'a> {
|
||||
Records::new(if self.is_container() { self.data } else { &[] })
|
||||
}
|
||||
|
||||
/// The first child of type `kind`.
|
||||
pub fn child(&self, kind: u16) -> Option<Rec<'a>> {
|
||||
self.children().find(|r| r.kind == kind)
|
||||
}
|
||||
|
||||
/// Every child of type `kind`.
|
||||
pub fn children_of(&self, kind: u16) -> impl Iterator<Item = Rec<'a>> {
|
||||
self.children().filter(move |r| r.kind == kind)
|
||||
}
|
||||
|
||||
pub fn u8(&self, at: usize) -> Option<u8> {
|
||||
self.data.get(at).copied()
|
||||
}
|
||||
pub fn u16(&self, at: usize) -> Option<u16> {
|
||||
u16_at(self.data, at)
|
||||
}
|
||||
pub fn i16(&self, at: usize) -> Option<i16> {
|
||||
self.u16(at).map(|v| v as i16)
|
||||
}
|
||||
pub fn u32(&self, at: usize) -> Option<u32> {
|
||||
u32_at(self.data, at)
|
||||
}
|
||||
pub fn i32(&self, at: usize) -> Option<i32> {
|
||||
self.u32(at).map(|v| v as i32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterates the records laid end to end in a byte slice.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Records<'a> {
|
||||
bytes: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Records<'a> {
|
||||
pub fn new(bytes: &'a [u8]) -> Self {
|
||||
Records { bytes, at: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Records<'a> {
|
||||
type Item = Rec<'a>;
|
||||
fn next(&mut self) -> Option<Rec<'a>> {
|
||||
let r = Rec::at(self.bytes, self.at)?;
|
||||
// Always advance by at least the header, so a zero-length record can't stall the walk.
|
||||
self.at = self.at.checked_add(8)?.checked_add(r.data.len())?;
|
||||
Some(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// A little-endian reader over a record body for the variable-length structures (text
|
||||
/// exceptions, style runs): every read is checked and a short body ends the walk.
|
||||
pub struct Cursor<'a> {
|
||||
pub b: &'a [u8],
|
||||
pub at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Cursor<'a> {
|
||||
pub fn new(b: &'a [u8]) -> Self {
|
||||
Cursor { b, at: 0 }
|
||||
}
|
||||
/// Bytes left to read.
|
||||
pub fn remaining(&self) -> usize {
|
||||
self.b.len().saturating_sub(self.at)
|
||||
}
|
||||
pub fn u8(&mut self) -> Option<u8> {
|
||||
let v = *self.b.get(self.at)?;
|
||||
self.at += 1;
|
||||
Some(v)
|
||||
}
|
||||
pub fn u16(&mut self) -> Option<u16> {
|
||||
let v = u16_at(self.b, self.at)?;
|
||||
self.at += 2;
|
||||
Some(v)
|
||||
}
|
||||
pub fn i16(&mut self) -> Option<i16> {
|
||||
self.u16().map(|v| v as i16)
|
||||
}
|
||||
pub fn u32(&mut self) -> Option<u32> {
|
||||
let v = u32_at(self.b, self.at)?;
|
||||
self.at += 4;
|
||||
Some(v)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod build {
|
||||
//! Writing records, for tests that build `.ppt` files.
|
||||
|
||||
pub fn atom(kind: u16, instance: u16, body: &[u8]) -> Vec<u8> {
|
||||
head(0, kind, instance, body)
|
||||
}
|
||||
|
||||
pub fn container(kind: u16, instance: u16, children: &[Vec<u8>]) -> Vec<u8> {
|
||||
head(0xF, kind, instance, &children.concat())
|
||||
}
|
||||
|
||||
fn head(ver: u16, kind: u16, instance: u16, body: &[u8]) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity(body.len() + 8);
|
||||
v.extend_from_slice(&(ver | (instance << 4)).to_le_bytes());
|
||||
v.extend_from_slice(&kind.to_le_bytes());
|
||||
v.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
v.extend_from_slice(body);
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::build::*;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn walks_nested_records() {
|
||||
let c = container(0x03E8, 0, &[atom(0x03E9, 0, &[1, 2, 3, 4]), atom(0x0FA0, 2, &[9; 6])]);
|
||||
let r = Rec::at(&c, 0).unwrap();
|
||||
assert!(r.is_container());
|
||||
let kids: Vec<_> = r.children().collect();
|
||||
assert_eq!(kids.len(), 2);
|
||||
assert_eq!(kids[1].instance, 2);
|
||||
assert_eq!(r.child(0x03E9).unwrap().u32(0), Some(0x0403_0201));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_zero_length_records_end_the_walk() {
|
||||
let mut c = atom(0x1, 0, &[]).repeat(3);
|
||||
c.extend_from_slice(&[0xF, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2]);
|
||||
let all: Vec<_> = Records::new(&c).collect();
|
||||
assert_eq!(all.len(), 4);
|
||||
assert_eq!(all[3].data, &[1, 2]);
|
||||
assert!(Records::new(&[1, 2, 3]).next().is_none());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,755 @@
|
||||
//! Text in `.ppt` ([MS-PPT] §2.9): characters in a `TextCharsAtom` (UTF-16) or `TextBytesAtom`
|
||||
//! (Latin-1), formatting as runs of paragraph exceptions (`TextPFException`) and character
|
||||
//! exceptions (`TextCFException`) over the master's per-level text styles.
|
||||
|
||||
use crate::doc::rt;
|
||||
use crate::record::{Cursor, Rec};
|
||||
|
||||
/// A colour as text formatting stores it: an RGB value or an index into the colour scheme.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TextColor {
|
||||
Rgb(u8, u8, u8),
|
||||
Scheme(u8),
|
||||
}
|
||||
|
||||
fn color_index(c: &mut Cursor) -> Option<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)
|
||||
}
|
||||
|
||||
/// Tab stops kept per paragraph exception or ruler. Every entry is still read past, so the fields
|
||||
/// after the list stay aligned; the rest are dropped, since each paragraph copies the list.
|
||||
const MAX_TABS: usize = 64;
|
||||
|
||||
fn read_tabs(c: &mut Cursor) -> Option<Vec<(i16, u16)>> {
|
||||
let n = c.u16()?;
|
||||
let mut v = Vec::with_capacity(usize::from(n).min(MAX_TABS));
|
||||
for _ in 0..n {
|
||||
let tab = (c.i16()?, c.u16()?);
|
||||
if v.len() < MAX_TABS {
|
||||
v.push(tab);
|
||||
}
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// A `TextCFException`.
|
||||
pub fn read_cf(c: &mut Cursor) -> Option<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",
|
||||
0x10 => "ea1ChsPlain",
|
||||
0x11 => "ea1ChsPeriod",
|
||||
0x12 => "circleNumDbPlain",
|
||||
0x13 => "circleNumWdWhitePlain",
|
||||
0x14 => "circleNumWdBlackPlain",
|
||||
0x15 => "ea1ChtPlain",
|
||||
0x16 => "ea1ChtPeriod",
|
||||
0x17 => "arabic1Minus",
|
||||
0x18 => "arabic2Minus",
|
||||
0x19 => "hebrew2Minus",
|
||||
0x1A => "ea1JpnKorPlain",
|
||||
0x1B => "ea1JpnKorPeriod",
|
||||
0x1C => "arabicDbPlain",
|
||||
0x1D => "arabicDbPeriod",
|
||||
0x1E => "thaiAlphaPeriod",
|
||||
0x1F => "thaiAlphaParenR",
|
||||
0x20 => "thaiAlphaParenBoth",
|
||||
0x21 => "thaiNumPeriod",
|
||||
0x22 => "thaiNumParenR",
|
||||
0x23 => "thaiNumParenBoth",
|
||||
0x24 => "hindiAlphaPeriod",
|
||||
0x25 => "hindiNumPeriod",
|
||||
0x26 => "ea1JpnChsDbPeriod",
|
||||
0x27 => "hindiNumParenR",
|
||||
0x28 => "hindiAlpha1Period",
|
||||
_ => "arabicPeriod",
|
||||
}
|
||||
}
|
||||
|
||||
/// Text types (`TextHeaderAtom.textType`).
|
||||
pub mod ty {
|
||||
pub const TITLE: u32 = 0;
|
||||
pub const BODY: u32 = 1;
|
||||
pub const NOTES: u32 = 2;
|
||||
pub const OTHER: u32 = 4;
|
||||
pub const CENTER_BODY: u32 = 5;
|
||||
pub const CENTER_TITLE: u32 = 6;
|
||||
pub const HALF_BODY: u32 = 7;
|
||||
pub const QUARTER_BODY: u32 = 8;
|
||||
}
|
||||
|
||||
/// One master text style: up to five levels of paragraph and character formatting.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LevelStyles {
|
||||
pub levels: Vec<(Pf, Cf)>,
|
||||
}
|
||||
|
||||
/// A `TextMasterStyleAtom` body.
|
||||
pub fn read_master_style(r: &Rec) -> LevelStyles {
|
||||
let mut c = Cursor::new(r.data);
|
||||
let mut out = LevelStyles::default();
|
||||
let Some(n) = c.u16() else { return out };
|
||||
for i in 0..usize::from(n.min(5)) {
|
||||
// From the centre-body type on, each level names itself (TextMasterStyleLevel.level).
|
||||
let level = if u32::from(r.instance) >= ty::CENTER_BODY {
|
||||
let Some(l) = c.u16() else { break };
|
||||
usize::from(l)
|
||||
} else {
|
||||
i
|
||||
};
|
||||
let Some(pf) = read_pf(&mut c) else { break };
|
||||
let Some(cf) = read_cf(&mut c) else { break };
|
||||
// Only five levels exist; one naming another is read past.
|
||||
if level >= 5 {
|
||||
continue;
|
||||
}
|
||||
if out.levels.len() <= level {
|
||||
out.levels.resize(level + 1, Default::default());
|
||||
}
|
||||
if let Some(slot) = out.levels.get_mut(level) {
|
||||
*slot = (pf, cf);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The text styles in effect for a master: the document defaults plus the master's styles by text
|
||||
/// type.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct StyleSheet {
|
||||
pub default_pf: Pf,
|
||||
pub default_cf: Cf,
|
||||
/// Indexed by text type (0–8).
|
||||
pub types: Vec<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");
|
||||
}
|
||||
|
||||
/// The East Asian, bidi, Thai and Hindi schemes (0x10–0x28) have DrawingML names of their
|
||||
/// own; only an unknown value falls back to "1.".
|
||||
#[test]
|
||||
fn every_numbering_scheme_has_its_drawingml_name() {
|
||||
assert_eq!(auto_number_scheme(0x10), "ea1ChsPlain");
|
||||
assert_eq!(auto_number_scheme(0x13), "circleNumWdWhitePlain");
|
||||
assert_eq!(auto_number_scheme(0x19), "hebrew2Minus");
|
||||
assert_eq!(auto_number_scheme(0x26), "ea1JpnChsDbPeriod");
|
||||
assert_eq!(auto_number_scheme(0x28), "hindiAlpha1Period");
|
||||
let names: std::collections::HashSet<_> = (0..=0x28).map(auto_number_scheme).collect();
|
||||
assert_eq!(names.len(), 0x29, "each value its own scheme");
|
||||
assert_eq!(auto_number_scheme(0x29), "arabicPeriod");
|
||||
}
|
||||
|
||||
/// From the centre-body type on, a master style level names its level: it is stored there,
|
||||
/// and a level past the fifth is read past.
|
||||
#[test]
|
||||
fn master_style_levels_go_where_they_say() {
|
||||
let level = |l: u16, size: u16| [&l.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, size, [0, 0, 0])].concat();
|
||||
let body = [&3u16.to_le_bytes()[..], &level(2, 20), &level(7, 30), &level(0, 40)].concat();
|
||||
let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::CENTER_BODY as u16, &body);
|
||||
let st = read_master_style(&Rec::at(&rec, 0).unwrap());
|
||||
let sizes: Vec<_> = st.levels.iter().map(|(_, cf)| cf.size).collect();
|
||||
assert_eq!(sizes, [Some(40), None, Some(20)]);
|
||||
// Before it, levels are in order.
|
||||
let body = [&1u16.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, 12, [0, 0, 0])].concat();
|
||||
let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::BODY as u16, &body);
|
||||
assert_eq!(read_master_style(&Rec::at(&rec, 0).unwrap()).levels[0].1.size, Some(12));
|
||||
}
|
||||
|
||||
/// A paragraph exception with many tab stops keeps the first [`MAX_TABS`] and reads the
|
||||
/// fields after the list where they are.
|
||||
#[test]
|
||||
fn tab_stops_are_capped_and_read_past() {
|
||||
let mut b = ((1u32 << 20) | (1 << 21)).to_le_bytes().to_vec(); // tabStops + textDirection
|
||||
b.extend_from_slice(&1000u16.to_le_bytes());
|
||||
for i in 0..1000u16 {
|
||||
b.extend_from_slice(&(i as i16).to_le_bytes());
|
||||
b.extend_from_slice(&1u16.to_le_bytes());
|
||||
}
|
||||
b.extend_from_slice(&0x1234u16.to_le_bytes()); // textDirection
|
||||
b.push(0xAB);
|
||||
let mut c = Cursor::new(&b);
|
||||
let pf = read_pf(&mut c).unwrap();
|
||||
let tabs = pf.tabs.unwrap();
|
||||
assert_eq!(tabs.len(), MAX_TABS);
|
||||
assert_eq!(tabs[MAX_TABS - 1], (MAX_TABS as i16 - 1, 1));
|
||||
assert_eq!(c.u8(), Some(0xAB), "the cursor stopped past textDirection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_exceptions_in_mask_order() {
|
||||
let pf = read_pf(&mut Cursor::new(&pf_bytes(1, true))).unwrap();
|
||||
assert_eq!(pf.has_bullet, Some(true));
|
||||
assert_eq!(pf.align, Some(1));
|
||||
assert_eq!(pf.bullet_has_font, None);
|
||||
let cf = read_cf(&mut Cursor::new(&cf_bytes(true, 3, 28, [1, 2, 3]))).unwrap();
|
||||
assert_eq!((cf.bold, cf.italic, cf.font, cf.size, cf.color), (Some(true), None, Some(3), Some(28), Some(TextColor::Rgb(1, 2, 3))));
|
||||
// A mask promising more than the bytes hold reads nothing.
|
||||
assert!(read_cf(&mut Cursor::new(&0x0007_0000u32.to_le_bytes())).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_text_block_with_runs() {
|
||||
let chars: Vec<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)));
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user