A fast, helpful, and open-source document parser
wip
Logan Markewich5cc0abee2327
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/mod.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/mod.rsindex ab69b95..943ae42 100644--- a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/mod.rs+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/mod.rs@@ -67,6 +67,31 @@ pub enum PathVerb {Close,}+/// §20.1.9.11's angle constants, in the `@stAng`/`@swAng` unit (60000ths of a+/// degree). `QUARTER` is the spec's `cd4`, `HALF` its `cd2`, `THREE_QUARTER`+/// its `3cd4` — named here because a preset generator writes them literally+/// where a `custGeom` would reference the guide.+pub mod turn {+ pub const NONE: i64 = 0;+ pub const QUARTER: i64 = 5_400_000;+ pub const HALF: i64 = 10_800_000;+ pub const THREE_QUARTER: i64 = 16_200_000;+}++/// One `<a:arcTo>`: a sweep of `swing` starting at `start`, from wherever the+/// pen already is.+///+/// The angles pass through in OOXML's own units — the painter applies them+/// directly to a clockwise-from-3-o'clock parametrisation, so converting here+/// would only invite a second conversion downstream.+pub(crate) fn arc(rx: Pt, ry: Pt, start: i64, swing: i64) -> PathVerb {+ PathVerb::ArcTo {+ radii: PtSize::new(rx, ry),+ start_angle: Dimension::new(start),+ swing_angle: Dimension::new(swing),+ }+}+/// Build a `ShapePath` for a parsed `ShapeGeometry` given the shape's/// rendered extent.///diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/ellipse.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/ellipse.rsnew file mode 100644index 0000000..b138356--- /dev/null+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/ellipse.rs@@ -0,0 +1,105 @@+//! §20.1.9.18 `ellipse` preset — the ellipse inscribed in the shape's+//! bounding box, drawn as two half-turn arcs.+//!+//! Two arcs rather than one full sweep because the spec writes it that way,+//! and because a 360° `swAng` starting and ending at the same point is exactly+//! the case an arc flattener has to special-case. Splitting at the left and+//! right quadrants leaves two unambiguous half turns.+//!+//! The shape has **no adjustment**: an ellipse is fully determined by its box.++use crate::model::PathFillMode;+use crate::render::dimension::Pt;+use crate::render::geometry::{PtOffset, PtRect, PtSize};+use crate::render::resolve::shape_geometry::{PathVerb, ShapePath, SubPath, arc, turn};++/// cos 45° = sin 45°, the half-diagonal factor the spec's `idx`/`idy` guides+/// evaluate to (`cos wd2 2700000`, `sin hd2 2700000`).+const COS_45: f32 = std::f32::consts::FRAC_1_SQRT_2;++pub fn build(extent: PtSize) -> ShapePath {+ let (rx, ry) = (+ Pt::new(extent.width.raw() * 0.5),+ Pt::new(extent.height.raw() * 0.5),+ );++ let verbs = vec![+ // Start at the left quadrant (9 o'clock), sweep over the top to the+ // right quadrant, then back underneath.+ PathVerb::MoveTo(PtOffset::new(Pt::ZERO, ry)),+ arc(rx, ry, turn::HALF, turn::HALF),+ arc(rx, ry, turn::NONE, turn::HALF),+ PathVerb::Close,+ ];++ // §20.1.9.18's `<rect l="il" t="it" r="ir" b="ib"/>`: the rectangle+ // inscribed at 45°, not the bounding box — text in an ellipse has to clear+ // the curve on all four sides.+ let (ix, iy) = (rx.raw() * COS_45, ry.raw() * COS_45);+ ShapePath {+ paths: vec![SubPath {+ verbs,+ fill_mode: PathFillMode::Norm,+ stroked: true,+ }],+ text_rect: Some(PtRect::from_xywh(+ Pt::new(rx.raw() - ix),+ Pt::new(ry.raw() - iy),+ Pt::new(ix * 2.0),+ Pt::new(iy * 2.0),+ )),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_outline_is_two_half_turns_from_the_left_quadrant() {+ let p = build(PtSize::new(Pt::new(200.0), Pt::new(100.0)));+ let verbs = &p.paths[0].verbs;+ assert_eq!(verbs.len(), 4);+ let PathVerb::MoveTo(start) = verbs[0] else {+ panic!("an ellipse starts with a moveTo")+ };+ // The pen starts at 9 o'clock: x = 0, y = half the height.+ assert_eq!(start, PtOffset::new(Pt::ZERO, Pt::new(50.0)));+ let mut swept = 0i64;+ for verb in verbs {+ if let PathVerb::ArcTo {+ radii, swing_angle, ..+ } = verb+ {+ // Radii are half the box, not the box — a whole-extent radius+ // draws an ellipse twice the shape's size.+ assert_eq!(*radii, PtSize::new(Pt::new(100.0), Pt::new(50.0)));+ swept += swing_angle.raw();+ }+ }+ assert_eq!(swept, 21_600_000, "the two arcs must close the figure");+ }++ #[test]+ fn the_text_rectangle_is_inscribed_not_the_bounding_box() {+ // Using the bounding box would let text sit in the corners, outside+ // the curve entirely.+ let p = build(PtSize::new(Pt::new(200.0), Pt::new(100.0)));+ let tr = p.text_rect.unwrap();+ assert!(tr.size.width.raw() < 200.0 && tr.size.height.raw() < 100.0);+ // Centred on the shape.+ assert!(+ ((tr.origin.x.raw() + tr.size.width.raw() * 0.5) - 100.0).abs() < 0.01,+ "the inscribed rect shares the ellipse's centre"+ );+ assert!(((tr.origin.y.raw() + tr.size.height.raw() * 0.5) - 50.0).abs() < 0.01);+ }++ #[test]+ fn a_zero_dimension_still_builds() {+ // `build_geometry` only rejects a shape that is zero in *both*+ // dimensions, so a degenerate ellipse must not panic here.+ let p = build(PtSize::new(Pt::new(40.0), Pt::ZERO));+ assert_eq!(p.paths.len(), 1);+ }+}diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rsindex baaa76e..854f917 100644--- a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs@@ -8,9 +8,19 @@//! Tier 0 supports only `line` and `rect` — the minimum to validate the//! pipeline end-to-end. Tier 1 adds the common ~20 shapes; Tier 2 adds the//! remaining ~60; Tier 3 completes the spec's ~200.+//!+//! `roundRect`, `ellipse` and `straightConnector1` are here ahead of the rest+//! of tier 1 because the PPTX paint census counted what their absence costs:+//! of 5,848 corpus shapes that put ink on a slide, `rect`/`line`/`custGeom`+//! build 62.9% and these three take that to 87.1%. The shortfall is not spread+//! evenly — it is every rounded panel and every bullet dot — so shipping fills+//! without them drops a fifth of the ink *selectively*, which reads as a layout+//! bug rather than as missing coverage.+mod ellipse;mod line;mod rect;+mod round_rect;use crate::model::{PresetGeometryDef, PresetShapeType};use crate::render::geometry::PtSize;@@ -21,8 +31,13 @@ use super::ShapePath;/// implemented; the call site is expected to log.pub fn build_preset(def: &PresetGeometryDef, extent: PtSize) -> Option<ShapePath> {match def.preset {- PresetShapeType::Line => Some(line::build(extent)),+ // §20.1.9.18: `straightConnector1` is a `line` — the connector's+ // endpoints are its own box's corners, and the flips in `a:xfrm` are+ // what point it the other way.+ PresetShapeType::Line | PresetShapeType::StraightConnector1 => Some(line::build(extent)),PresetShapeType::Rect => Some(rect::build(extent)),+ PresetShapeType::RoundRect => Some(round_rect::build(&def.adjust_values, extent)),+ PresetShapeType::Ellipse => Some(ellipse::build(extent)),_ => {log::warn!("shape_geometry: preset {:?} not yet implemented",diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/round_rect.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/round_rect.rsnew file mode 100644index 0000000..7066fee--- /dev/null+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/round_rect.rs@@ -0,0 +1,154 @@+//! §20.1.9.18 `roundRect` preset — a rectangle whose four corners are+//! quarter-circle arcs of one shared radius.+//!+//! The radius is the shape's single adjustment, and it is *not* a length: the+//! spec's `avLst` carries `adj` as a fraction of the **shortest side**+//!+//! ```text+//! <gd name="a" fmla="pin 0 adj 50000"/>+//! <gd name="x1" fmla="*/ ss a 100000"/>+//! ```+//!+//! so a wide banner and a tall panel with the same `adj` get the same corner,+//! and clamping at 50000 is what stops a large `adj` from turning the two arcs+//! of a side inside out. `adj` defaults to 16667 (≈1/6 of the short side) when+//! the file declares no `avLst`, which is the common case: PowerPoint only+//! writes one when the user has dragged the corner handle.++use crate::model::{GeomGuide, PathFillMode};+use crate::render::dimension::Pt;+use crate::render::geometry::{PtOffset, PtRect, PtSize};+use crate::render::resolve::shape_geometry::guides::{GuideContext, evaluate_guides};+use crate::render::resolve::shape_geometry::{PathVerb, ShapePath, SubPath, arc, turn};++/// The spec's default corner adjustment, used when the shape declares no+/// `<a:avLst>` — 16667 hundred-thousandths of the shortest side.+const DEFAULT_ADJ: f64 = 16_667.0;++/// §20.1.9.18's `pin 0 adj 50000`: half the shortest side is the largest+/// corner that still leaves a straight edge between two arcs.+const MAX_ADJ: f64 = 50_000.0;++pub fn build(adjust: &[GeomGuide], extent: PtSize) -> ShapePath {+ let (w, h) = (extent.width, extent.height);+ let r = corner_radius(adjust, extent);++ // Each corner starts where the previous edge ended and sweeps a quarter+ // turn clockwise, so the four `stAng`s are the spec's cd2 / 3cd4 / 0 / cd4+ // in that order. Angles are OOXML's own units, unconverted — the painter+ // consumes them directly.+ let verbs = vec![+ PathVerb::MoveTo(PtOffset::new(Pt::ZERO, r)),+ arc(r, r, turn::HALF, turn::QUARTER),+ PathVerb::LineTo(PtOffset::new(w - r, Pt::ZERO)),+ arc(r, r, turn::THREE_QUARTER, turn::QUARTER),+ PathVerb::LineTo(PtOffset::new(w, h - r)),+ arc(r, r, turn::NONE, turn::QUARTER),+ PathVerb::LineTo(PtOffset::new(r, h)),+ arc(r, r, turn::QUARTER, turn::QUARTER),+ PathVerb::Close,+ ];++ ShapePath {+ paths: vec![SubPath {+ verbs,+ fill_mode: PathFillMode::Norm,+ stroked: true,+ }],+ // §20.1.9.18's `<rect l="x1" t="y1" r="x2" b="y2"/>`: text clears the+ // corners rather than the bounding box.+ text_rect: Some(PtRect::from_xywh(r, r, w - r - r, h - r - r)),+ }+}++/// `x1` — the corner radius in Pt.+///+/// Read through the guide evaluator rather than by pattern-matching the+/// formula string, so `<a:gd name="adj" fmla="val 25000"/>` and any equivalent+/// expression resolve the same way.+fn corner_radius(adjust: &[GeomGuide], extent: PtSize) -> Pt {+ let ctx = GuideContext::new(extent.width.raw() as f64, extent.height.raw() as f64);+ let adj = evaluate_guides(adjust, ctx)+ .get("adj")+ .copied()+ .unwrap_or(DEFAULT_ADJ)+ .clamp(0.0, MAX_ADJ);+ let shortest = extent.width.raw().min(extent.height.raw()).max(0.0);+ Pt::new(shortest * (adj as f32) / 100_000.0)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn adj(value: i64) -> Vec<GeomGuide> {+ vec![GeomGuide {+ name: "adj".to_string(),+ formula: format!("val {value}"),+ }]+ }++ fn radius(path: &ShapePath) -> f32 {+ let PathVerb::MoveTo(p) = path.paths[0].verbs[0] else {+ panic!("a roundRect starts with a moveTo")+ };+ p.y.raw()+ }++ #[test]+ fn corners_are_a_fraction_of_the_shortest_side() {+ // A wide shape and a tall one with the same `adj` get the same corner:+ // `ss`, not `w` or `h`, is what the spec measures against — taking the+ // width would round a 400x40 banner into a lozenge.+ let wide = build(&adj(25_000), PtSize::new(Pt::new(400.0), Pt::new(40.0)));+ let tall = build(&adj(25_000), PtSize::new(Pt::new(40.0), Pt::new(400.0)));+ assert_eq!(radius(&wide), 10.0);+ assert_eq!(radius(&tall), 10.0);+ }++ #[test]+ fn no_adjust_list_takes_the_spec_default() {+ // The common case — PowerPoint writes an `avLst` only once the corner+ // handle has been dragged.+ let p = build(&[], PtSize::new(Pt::new(120.0), Pt::new(60.0)));+ assert!((radius(&p) - 60.0 * 0.16667).abs() < 0.01);+ }++ #[test]+ fn an_oversized_adjustment_is_pinned_at_half_the_short_side() {+ // `pin 0 adj 50000`. Past half, two corners of the same side would+ // overlap and the outline would fold through itself.+ let p = build(&adj(90_000), PtSize::new(Pt::new(200.0), Pt::new(100.0)));+ assert_eq!(radius(&p), 50.0);+ let flat = build(&adj(-5_000), PtSize::new(Pt::new(200.0), Pt::new(100.0)));+ assert_eq!(radius(&flat), 0.0);+ }++ #[test]+ fn the_outline_is_four_arcs_joined_by_four_edges() {+ let p = build(&adj(10_000), PtSize::new(Pt::new(200.0), Pt::new(100.0)));+ let verbs = &p.paths[0].verbs;+ assert_eq!(verbs.len(), 9);+ let arcs = verbs+ .iter()+ .filter(|v| matches!(v, PathVerb::ArcTo { .. }))+ .count();+ assert_eq!(arcs, 4, "one quarter turn per corner");+ assert!(matches!(verbs[8], PathVerb::Close));+ // Every corner turns the same way, a quarter at a time — a sign slip on+ // one of them cuts the corner off instead of rounding it.+ for verb in verbs {+ if let PathVerb::ArcTo { swing_angle, .. } = verb {+ assert_eq!(swing_angle.raw(), 5_400_000);+ }+ }+ }++ #[test]+ fn the_text_rectangle_clears_the_corners() {+ let p = build(&adj(20_000), PtSize::new(Pt::new(200.0), Pt::new(100.0)));+ let tr = p.text_rect.unwrap();+ assert_eq!(tr.origin, PtOffset::new(Pt::new(20.0), Pt::new(20.0)));+ assert_eq!(tr.size, PtSize::new(Pt::new(160.0), Pt::new(60.0)));+ }+}diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.tomlindex 29168fd..94ffe6c 100644--- a/crates/liteparse/Cargo.toml+++ b/crates/liteparse/Cargo.toml@@ -26,6 +26,14 @@ required-features = ["pptx-native"]name = "pptx_layout_probe"required-features = ["pptx-native"]+[[example]]+name = "pptx_paint_census"+required-features = ["pptx-native"]++[[example]]+name = "pptx_raster_dump"+required-features = ["pptx-native"]+[features]default = ["tesseract", "docx-native", "pptx-native"]oar-ocr = ["dep:oar-ocr"]diff --git a/crates/liteparse/src/office/pptx.rs b/crates/liteparse/src/office/pptx.rsindex 2968374..57a1956 100644--- a/crates/liteparse/src/office/pptx.rs+++ b/crates/liteparse/src/office/pptx.rs@@ -97,7 +97,8 @@ pub fn emit_with_sources(/// Both rungs are keyed by part *path* and rebuilt once per path, never once/// per slide. Every previous PPTX probe records this discipline because a deck/// with 60 slides sharing 3 layouts otherwise reparses those layouts 60 times.-pub(crate) struct Deck {+#[doc(hidden)]+pub struct Deck {master_geo: HashMap<String, PlaceholderGeometry>,layout_geo: HashMap<String, PlaceholderGeometry>,master_text: HashMap<String, (PlaceholderTextStyles, DeckTextDefaults)>,@@ -118,8 +119,9 @@ pub(crate) struct Deck {/// `TextItem` is only a faithful box for the markdown a reader sees if both/// came out of the same resolution. Two copies of this setup would compile,/// run, and disagree silently.-pub(crate) struct PreparedSlide<'d> {- pub(crate) shapes: Vec<Shape>,+#[doc(hidden)]+pub struct PreparedSlide<'d> {+ pub shapes: Vec<Shape>,layout_text: Option<&'d PlaceholderTextStyles>,master_text: Option<&'d PlaceholderTextStyles>,deck_defaults: &'d DeckTextDefaults,@@ -128,7 +130,7 @@ pub(crate) struct PreparedSlide<'d> {impl<'d> PreparedSlide<'d> {/// The slide-level text cascade (rungs 4-7). Rung 2, the shape's own/// `a:lstStyle`, is layered on per text body by the caller.- pub(crate) fn cascade(&self) -> TextCascade<'d> {+ pub fn cascade(&self) -> TextCascade<'d> {TextCascade {shape: None,layout: self.layout_text,@@ -139,7 +141,7 @@ impl<'d> PreparedSlide<'d> {}impl Deck {- pub(crate) fn new(pkg: &PresentationPackage) -> Self {+ pub fn new(pkg: &PresentationPackage) -> Self {// Rung 7. A deck whose presentation.xml will not parse still// resolves through the earlier rungs, so this degrades to empty// rather than failing the deck.@@ -163,7 +165,7 @@ impl Deck {////// `None` when the shape tree will not parse — fail-open, the same slide/// is skipped by every walk.- pub(crate) fn prepare(&mut self, slide: &pptx::SlideParts) -> Option<PreparedSlide<'_>> {+ pub fn prepare(&mut self, slide: &pptx::SlideParts) -> Option<PreparedSlide<'_>> {self.prime(slide);let mut shapes = pptx::parse_shape_tree(&slide.slide.xml).ok()?;@@ -290,7 +292,13 @@ struct SlideCtx<'a> {/// A group is one unit. Its children are emitted in their own reading order/// within it, so a two-column group does not interleave with unrelated shapes/// elsewhere on the slide.-pub(crate) fn reading_order(shapes: &[Shape]) -> Vec<&Shape> {+///+/// Public — and `doc(hidden)` — so that a probe or census can measure *this*+/// order rather than a copy of it. A duplicate that drifted by one tie-break+/// would report the production traversal as correct while measuring a+/// different one.+#[doc(hidden)]+pub fn reading_order(shapes: &[Shape]) -> Vec<&Shape> {let mut v: Vec<&Shape> = shapes.iter().filter(|s| !is_chrome(s.placeholder.as_ref()))@@ -312,7 +320,8 @@ pub(crate) fn reading_order(shapes: &[Shape]) -> Vec<&Shape> {v}-pub(crate) fn is_title(ph: Option<&Placeholder>) -> bool {+#[doc(hidden)]+pub fn is_title(ph: Option<&Placeholder>) -> bool {matches!(ph.map(|p| p.kind),Some(PlaceholderKind::Title | PlaceholderKind::CtrTitle)@@ -327,7 +336,8 @@ pub(crate) fn is_title(ph: Option<&Placeholder>) -> bool {/// Dropping them wholesale is the conservative choice for now because a/// length test would also admit genuine repeated footer chrome on every/// slide of a 60-slide deck; revisit with a measurement, not a guess.-fn is_chrome(ph: Option<&Placeholder>) -> bool {+#[doc(hidden)]+pub fn is_chrome(ph: Option<&Placeholder>) -> bool {matches!(ph.map(|p| p.kind),Some(diff --git a/crates/liteparse/src/office/pptx_layout.rs b/crates/liteparse/src/office/pptx_layout.rsindex a9bc5a4..8044f2a 100644--- a/crates/liteparse/src/office/pptx_layout.rs+++ b/crates/liteparse/src/office/pptx_layout.rs@@ -37,6 +37,17 @@//! Reading order and the text cascade both come from [`super::pptx`], through//! `Deck::prepare`, so a `TextItem` is a box for exactly the text the markdown//! emitter saw, resolved the same way.+//!+//! # Two walks, one prepare+//!+//! Text is emitted in reading order; **fills and outlines are emitted in+//! document order**, by [`paint_shapes`], because §19.3.1.45 makes document+//! order z-order and the paint census measured 29.1% of the corpus pairs where+//! that difference is observable coming out the wrong way round under reading+//! order. The two walks share one `Deck::prepare`, so they cannot disagree+//! about a rectangle or a cascade; what they deliberately do not share is the+//! chrome filter, the traversal order, and the placement mechanism — a text+//! body is bracketed, a path places itself.use liteparse_ooxml::model::{Alignment, Theme};use liteparse_ooxml::pptx::{@@ -48,7 +59,7 @@ use liteparse_ooxml::render::fonts::FontRegistry;use liteparse_ooxml::render::geometry::{PtOffset, PtSize};use liteparse_ooxml::render::layout::ShapeAutoFit;use liteparse_ooxml::render::layout::draw_command::{- DrawCommand, LayoutedPage, ShapeTransform, TransformMark,+ DrawCommand, LayoutedPage, ResolvedFill, ShapeTransform, TransformMark,};use liteparse_ooxml::render::layout::fragment::{Fragment, emit_run_fragments, font_props_from_run,@@ -59,6 +70,10 @@ use liteparse_ooxml::render::layout::section::LayoutBlock;use liteparse_ooxml::render::layout::shape_body::{layout_shape_body, measure_shape_body};use liteparse_ooxml::render::resolve::color::RgbColor;use liteparse_ooxml::render::resolve::fonts::resolve_font_set_themes;+use liteparse_ooxml::render::resolve::shape_geometry::build_geometry;+use liteparse_ooxml::render::resolve::shape_visuals::resolve_shape_visuals;++use std::collections::HashMap;use crate::error::LiteParseError;use crate::office::docx_layout;@@ -113,6 +128,18 @@ pub struct SlideGeometry {/// emitter places the *frame* in reading order, which is a weaker claim/// than a per-run box.pub unplaced_diagram_bodies: usize,+ /// Shapes the paint walk emitted a [`DrawCommand::Path`] for.+ pub painted_shapes: usize,+ /// Shapes that resolve to a fill or a stroke but whose geometry this pass+ /// cannot build — an unimplemented preset, or none declared. Their text is+ /// still laid out; only their ink is missing.+ pub unpainted_shapes: usize,+ /// Painted shapes whose `<a:ln>` names no colour of its own, so the shared+ /// resolver defaults it to black where DrawingML would inherit+ /// `p:style/a:lnRef`. The census put this at 7.7% of strokes; it is the one+ /// place this pass paints something *wrong* rather than painting nothing,+ /// and it is counted rather than hidden until `p:style` is parsed.+ pub outlines_defaulted_black: usize,}/// Where one text body's items landed on its slide — a shape's, or a single@@ -133,6 +160,15 @@ pub struct ShapePlacement {pub shrunk: bool,/// Half-open range into the page's `text_items`.pub items: std::ops::Range<usize>,+ /// Index into the page's `commands` of the `Transform(Begin)` that placed+ /// this box.+ ///+ /// An explicit link, not an ordinal one. The command list also carries the+ /// paint walk's shapes — four in five of which have no text body at all —+ /// so "the *n*th bracket is the *n*th placement" was only ever true by+ /// accident of the text walk running alone, and a check built on it would+ /// silently stop testing anything the moment a second producer appeared.+ pub bracket: usize,}/// Which layout path a [`ShapePlacement`] came from.@@ -160,13 +196,13 @@ pub fn slides_to_pages(}fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeometry {- // Parsed once per deck. `pkg.theme` is the first master's theme — a- // multi-master deck loses the per-master theme, which `pptx::walk` already- // documents as a known limit of the package walk rather than of this pass.- let theme = pkg- .theme- .as_ref()- .and_then(|bytes| liteparse_ooxml::docx::parse::theme::parse_theme(bytes).ok());+ // Parsed once per *theme part*, not once per deck and not once per slide.+ // A deck-wide theme was tolerable while the theme only supplied fonts; a+ // fill resolves its colour through the theme's colour matrix, and a slide+ // under a second master would then take a real, wrong colour from the+ // first master's palette — which is worse than no colour at all, because+ // nothing about the output says it came from the wrong place.+ let mut themes: HashMap<String, Option<Theme>> = HashMap::new();let measurer = TextMeasurer::new(registry);let (slide_w, slide_h) = pkg.info.slide_size_pt();@@ -183,19 +219,23 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeomeplaced_table_cells: 0,unplaced_table_cells: 0,unplaced_diagram_bodies: 0,+ painted_shapes: 0,+ unpainted_shapes: 0,+ outlines_defaulted_black: 0,};for (idx, slide) in pkg.slides.iter().enumerate() {let mut items = Vec::new();let mut placements = Vec::new();let mut commands = Vec::new();+ let theme = slide_theme(pkg, slide, &mut themes);// A slide whose shape tree will not parse still yields a page. Page// count must equal slide count — a consumer indexes pages by slide.if let Some(prepared) = deck.prepare(slide) {let cascade = prepared.cascade();let mut ctx = ShapeCtx {cascade,- theme: theme.as_ref(),+ theme,measurer: &measurer,registry,items: &mut items,@@ -204,7 +244,13 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeomeplaced_table_cells: &mut out.placed_table_cells,unplaced_table_cells: &mut out.unplaced_table_cells,unplaced_diagram_bodies: &mut out.unplaced_diagram_bodies,+ painted_shapes: &mut out.painted_shapes,+ unpainted_shapes: &mut out.unpainted_shapes,+ outlines_defaulted_black: &mut out.outlines_defaulted_black,};+ // Two walks over one `prepare`, in the order the raster wants+ // them. See [`paint_shape`] for why they cannot be one walk.+ paint_shapes(&prepared.shapes, &mut ctx);for shape in reading_order(&prepared.shapes) {layout_shape(shape, &mut ctx);}@@ -251,6 +297,9 @@ struct ShapeCtx<'a, 'r> {placed_table_cells: &'a mut usize,unplaced_table_cells: &'a mut usize,unplaced_diagram_bodies: &'a mut usize,+ painted_shapes: &'a mut usize,+ unpainted_shapes: &'a mut usize,+ outlines_defaulted_black: &'a mut usize,}impl ShapeCtx<'_, '_> {@@ -262,13 +311,139 @@ impl ShapeCtx<'_, '_> {/// bracket is the *only* place a slide coordinate is introduced, and the/// two consumers cannot drift apart by one of them shifting and the other/// not.- fn push_bracketed(&mut self, placement: ShapeTransform, commands: Vec<DrawCommand>) {+ /// Returns the index of the `Begin` mark, which is the placement's link+ /// back into the command list.+ fn push_bracketed(&mut self, placement: ShapeTransform, commands: Vec<DrawCommand>) -> usize {+ let at = self.commands.len();self.commands.push(DrawCommand::Transform(TransformMark::Begin(placement)));self.commands.extend(commands);self.commands.push(DrawCommand::Transform(TransformMark::End));+ at+ }+}++/// Paint every shape on the slide, in document order.+///+/// **A second traversal, and it has to be.** The text walk uses+/// [`reading_order`], which sorts shapes into bands and drops chrome; both+/// halves are right for reading and wrong for painting. §19.3.1.45 makes+/// document order z-order, and the paint census found that of the 1,263 corpus+/// pairs where two fills overlap — i.e. where paint order is observable at all+/// — reading order sequences **368 (29.1%)** the wrong way round, on 7.3% of+/// slides. A backdrop panel authored last and read first would paint over the+/// content it belongs under.+///+/// The two walks share one `Deck::prepare`, so the rectangles and the cascade+/// they see are the same ones by construction. What is *not* shared is the+/// chrome filter: this walk paints chrome, the text walk still drops it, and+/// the 347 chrome shapes that carry text are a divergence this step leaves+/// open rather than closes (see the module-level note in the plan).+fn paint_shapes(shapes: &[Shape], ctx: &mut ShapeCtx<'_, '_>) {+ for shape in shapes {+ paint_shape(shape, ctx);+ if let ShapeKind::Group(group) = &shape.kind {+ // A group's own `grpSpPr` fill is not lowered to `ShapeProperties`+ // at all, so a group paints nothing itself — its children carry+ // every fill, in their own declaration order.+ paint_shapes(&group.children, ctx);+ }+ }+}++/// One shape's fill and outline as a [`DrawCommand::Path`], if it puts ink on+/// the slide.+///+/// Unlike a text body this needs no bracket: `Path` carries its own+/// origin/rotation/flip/extent and the painter composes them, so the shape is+/// self-placing. That also lets it carry the two flips, which a text bracket+/// deliberately does not — §20.1.7.6 mirrors a shape's *geometry*, and+/// PowerPoint does not mirror the text inside it.+fn paint_shape(shape: &Shape, ctx: &mut ShapeCtx<'_, '_>) {+ let Some(props) = shape_properties(shape) else {+ return;+ };+ // `p:style`'s `fillRef`/`lnRef`/`effectRef` are not parsed yet, so the+ // three style arguments are `None` and 3,381 corpus shapes with no `spPr`+ // fill element resolve to nothing. That is an *under*-paint: visible, but+ // never misleading.+ let visuals = resolve_shape_visuals(Some(props), None, None, None, ctx.theme);+ let paints = !matches!(visuals.fill, ResolvedFill::None) || visuals.stroke.is_some();+ if !paints {+ return;+ }++ let Some(slide_rect) = shape.slide_rect else {+ *ctx.unpainted_shapes += 1;+ return;+ };+ // The *bounding* box, not the raw rect: `pptx::geometry` composes group+ // transforms into `slide_rect`, and a rotated or skewed child's ink lives+ // in the box that composition produced.+ let box_ = slide_rect.bounding_box();+ let extent = PtSize {+ width: emu_to_pt(box_.size.width.raw()),+ height: emu_to_pt(box_.size.height.raw()),+ };+ let Some(geometry) = props.geometry.as_ref() else {+ *ctx.unpainted_shapes += 1;+ return;+ };+ let Some(path) = build_geometry(geometry, extent) else {+ // An unimplemented preset. Counted, never approximated by its bounding+ // box: a `rect` drawn where a `cloud` was asked for is a wrong slide,+ // not a coarse one.+ *ctx.unpainted_shapes += 1;+ return;+ };++ if visuals.stroke.is_some() && props.outline.as_ref().is_some_and(|o| o.fill.is_none()) {+ *ctx.outlines_defaulted_black += 1;}+ *ctx.painted_shapes += 1;+ ctx.commands.push(DrawCommand::Path {+ origin: PtOffset::new(+ emu_to_pt(box_.origin.x.raw()),+ emu_to_pt(box_.origin.y.raw()),+ ),+ rotation: slide_rect.rotation,+ flip_h: slide_rect.flip_h,+ flip_v: slide_rect.flip_v,+ extent,+ paths: path.paths,+ fill: visuals.fill,+ stroke: visuals.stroke,+ effects: visuals.effects,+ });+}++/// The `spPr` a shape paints from. Groups and graphic frames have none of+/// their own — a table's cell fills are `a:tcPr`, which this pass does not+/// paint yet.+fn shape_properties(shape: &Shape) -> Option<&liteparse_ooxml::model::ShapeProperties> {+ match &shape.kind {+ ShapeKind::AutoShape(sp) => sp.properties.as_ref(),+ ShapeKind::Connector(c) => c.properties.as_ref(),+ ShapeKind::Picture(p) => p.shape_properties.as_ref(),+ ShapeKind::Group(_) | ShapeKind::GraphicFrame(_) => None,+ }+}++/// The theme governing one slide, parsed once per theme *part*.+fn slide_theme<'a>(+ pkg: &PresentationPackage,+ slide: &pptx::SlideParts,+ cache: &'a mut HashMap<String, Option<Theme>>,+) -> Option<&'a Theme> {+ let path = slide.theme_path.clone()?;+ cache+ .entry(path)+ .or_insert_with(|| {+ pkg.theme_for(slide)+ .and_then(|bytes| liteparse_ooxml::docx::parse::theme::parse_theme(bytes).ok())+ })+ .as_ref()}fn layout_shape(shape: &Shape, ctx: &mut ShapeCtx<'_, '_>) {@@ -349,7 +524,7 @@ fn layout_text_shape(shape: &Shape, body: &TextBody, ctx: &mut ShapeCtx<'_, '_>)}let frame = Frame::new(slide_rect, extent);- ctx.push_bracketed(frame.place((0.0, 0.0), extent), commands.clone());+ let bracket = ctx.push_bracketed(frame.place((0.0, 0.0), extent), commands.clone());let items = commands_to_items(commands, extent, ctx);let first_item = ctx.items.len();frame.push_items(items, (0.0, 0.0), ctx.items);@@ -365,6 +540,7 @@ fn layout_text_shape(shape: &Shape, body: &TextBody, ctx: &mut ShapeCtx<'_, '_>)rotation: frame.item_rotation(),shrunk: auto_fit != ShapeAutoFit::NONE,items: first_item..ctx.items.len(),+ bracket,});}@@ -617,7 +793,7 @@ fn layout_table(shape: &Shape, table: &pptx::Table, ctx: &mut ShapeCtx<'_, '_>)continue;}let offset = (cell.left.raw(), row_edges[cell.row].raw());- ctx.push_bracketed(frame.place(offset, extent), commands.clone());+ let bracket = ctx.push_bracketed(frame.place(offset, extent), commands.clone());let items = commands_to_items(commands, extent, ctx);let first_item = ctx.items.len();frame.push_items(items, offset, ctx.items);@@ -638,6 +814,7 @@ fn layout_table(shape: &Shape, table: &pptx::Table, ctx: &mut ShapeCtx<'_, '_>)rotation: frame.item_rotation(),shrunk: false,items: first_item..ctx.items.len(),+ bracket,});}}