Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewichb8a8636a8330
diff --git a/crates/liteparse-ooxml/examples/layout_probe.rs b/crates/liteparse-ooxml/examples/layout_probe.rs
index d333f85..1d3735b 100644
--- a/crates/liteparse-ooxml/examples/layout_probe.rs
+++ b/crates/liteparse-ooxml/examples/layout_probe.rs
@@ -53,6 +53,7 @@ struct Census {
internal_link: u64,
named_dest: u64,
outline: u64,
+ transform: u64,
path: u64,
}
@@ -130,6 +131,9 @@ fn run_one(path: &str) -> serde_json::Value {
DrawCommand::InternalLink { .. } => census.internal_link += 1,
DrawCommand::NamedDestination { .. } => census.named_dest += 1,
DrawCommand::Outline(_) => census.outline += 1,
+ // PPTX-only placement bracket; a DOCX layout emits none, so a
+ // non-zero count here means this probe was pointed at a slide.
+ DrawCommand::Transform(_) => census.transform += 1,
// No catch-all: the compiler confirming this match is
// exhaustive is how we know the census can't silently miss a
// command class.
@@ -164,6 +168,7 @@ fn run_one(path: &str) -> serde_json::Value {
"internal_link": census.internal_link,
"named_dest": census.named_dest,
"outline": census.outline,
+ "transform": census.transform,
"path": census.path,
},
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/shape.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/shape.rs
index 7e89330..50fe13a 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/shape.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/shape.rs
@@ -90,7 +90,10 @@ impl From<SpPrXml> for ShapeProperties {
}
}
-fn pick_fill(
+/// Collapse the six mutually-exclusive `EG_FillProperties` members into one
+/// [`DrawingFill`]. Shared with PresentationML's §19.3.1.2 `<p:bgPr>`, which
+/// has the same fill content model.
+pub(crate) fn pick_fill(
no: Option<super::fill::Empty>,
grp: Option<super::fill::Empty>,
solid: Option<super::fill::SolidFillXml>,
diff --git a/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs b/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs
index d7859ec..40d8572 100644
--- a/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs
@@ -46,6 +46,10 @@ struct ThemeElementsXml {
struct FmtSchemeXml {
#[serde(rename = "fillStyleLst", default)]
fill_style_lst: Option<FillStyleLstXml>,
+ /// §20.1.4.1.7 bgFillStyleLst — same content model as `fillStyleLst`,
+ /// separate matrix. Only `<p:bgRef idx="1001+">` reads it.
+ #[serde(rename = "bgFillStyleLst", default)]
+ bg_fill_style_lst: Option<FillStyleLstXml>,
#[serde(rename = "lnStyleLst", default)]
ln_style_lst: Option<LnStyleLstXml>,
#[serde(rename = "effectStyleLst", default)]
@@ -206,6 +210,9 @@ impl From<ThemeXml> for Theme {
if let Some(list) = fmt.fill_style_lst {
theme.fill_styles = list.fills.into_iter().map(Into::into).collect();
}
+ if let Some(list) = fmt.bg_fill_style_lst {
+ theme.bg_fill_styles = list.fills.into_iter().map(Into::into).collect();
+ }
if let Some(list) = fmt.ln_style_lst {
theme.line_styles = list.lines.into_iter().map(Outline::from).collect();
}
@@ -375,6 +382,50 @@ mod tests {
));
}
+ /// `bgFillStyleLst` is a **separate matrix** from `fillStyleLst`, reached
+ /// only by a §19.3.1.3 `<p:bgRef idx="1001+">`. Parsing them into one list
+ /// would be worse than not parsing it: every PPTX background would resolve
+ /// to a shape fill of the same index, silently and plausibly.
+ ///
+ /// All 115 themes on the PPTX corpus declare both lists, with 3 entries
+ /// each.
+ #[test]
+ fn bg_fill_style_lst_is_a_separate_matrix_from_fill_style_lst() {
+ let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:fmtScheme>
+ <a:fillStyleLst>
+ <a:solidFill><a:srgbClr val="AA0000"/></a:solidFill>
+ </a:fillStyleLst>
+ <a:bgFillStyleLst>
+ <a:solidFill><a:srgbClr val="00AA00"/></a:solidFill>
+ <a:gradFill><a:gsLst>
+ <a:gs pos="0"><a:schemeClr val="phClr"/></a:gs>
+ </a:gsLst><a:lin ang="5400000"/></a:gradFill>
+ </a:bgFillStyleLst>
+ </a:fmtScheme></a:themeElements></a:theme>"#;
+ let theme = parse_theme(xml.as_bytes()).unwrap();
+ assert_eq!(theme.fill_styles.len(), 1);
+ assert_eq!(theme.bg_fill_styles.len(), 2);
+ assert!(matches!(
+ &theme.bg_fill_styles[1],
+ crate::docx::model::DrawingFill::Gradient(_)
+ ));
+ }
+
+ /// A theme with no `bgFillStyleLst` leaves the list empty rather than
+ /// borrowing `fillStyleLst`, so a `bgRef` against it resolves to nothing
+ /// instead of to a shape fill.
+ #[test]
+ fn absent_bg_fill_style_lst_does_not_fall_back_to_fill_styles() {
+ let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:fmtScheme>
+ <a:fillStyleLst>
+ <a:solidFill><a:srgbClr val="AA0000"/></a:solidFill>
+ </a:fillStyleLst>
+ </a:fmtScheme></a:themeElements></a:theme>"#;
+ let theme = parse_theme(xml.as_bytes()).unwrap();
+ assert_eq!(theme.fill_styles.len(), 1);
+ assert!(theme.bg_fill_styles.is_empty());
+ }
+
#[test]
fn sys_clr_uses_last_clr() {
let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:clrScheme>
diff --git a/crates/liteparse-ooxml/src/model/types/theme.rs b/crates/liteparse-ooxml/src/model/types/theme.rs
index c989626..7361671 100644
--- a/crates/liteparse-ooxml/src/model/types/theme.rs
+++ b/crates/liteparse-ooxml/src/model/types/theme.rs
@@ -13,6 +13,19 @@ pub struct Theme {
/// `fill_styles[0]`. `phClr` inside the fill is substituted by the ref's
/// color at resolve time.
pub fill_styles: Vec<DrawingFill>,
+ /// §20.1.4.1.7 bgFillStyleLst — the *background* fill matrix, a list
+ /// distinct from [`Self::fill_styles`] and reached only through a
+ /// §19.3.1.3 `<p:bgRef>` whose `idx` is 1001 or greater (`idx - 1000`,
+ /// then 0-based here). A shape's `<a:fillRef>` never reaches it.
+ ///
+ /// Parsed because the corpus leaves no choice: **all 440 `bgRef`
+ /// backgrounds across the 45-deck PPTX corpus use `idx="1001"`, and not
+ /// one uses `fillStyleLst`.** Resolving those against `fill_styles` — a
+ /// 3-entry list — is an out-of-range lookup that yields `None` and
+ /// renders every one of them with no background at all, silently. All
+ /// 115 corpus themes declare a 3-entry `bgFillStyleLst`, so with this
+ /// field the same 440 resolve.
+ pub bg_fill_styles: Vec<DrawingFill>,
/// §20.1.4.1.21 lnStyleLst — theme line styles referenced via
/// `<a:lnRef idx="N">`. 0-based in storage — `lnRef idx="1"` is
/// `line_styles[0]`.
diff --git a/crates/liteparse-ooxml/src/pptx/cascade.rs b/crates/liteparse-ooxml/src/pptx/cascade.rs
index ecc60fe..deeb44d 100644
--- a/crates/liteparse-ooxml/src/pptx/cascade.rs
+++ b/crates/liteparse-ooxml/src/pptx/cascade.rs
@@ -69,9 +69,12 @@
use std::collections::HashMap;
-use crate::model::Transform2D;
+use crate::model::{Theme, Transform2D};
+use crate::render::layout::draw_command::ResolvedFill;
+use crate::render::resolve::drawing_color::DrawingColorContext;
+use crate::render::resolve::shape_visuals::{resolve_background_fill, resolve_fill};
-use super::shapes::{Placeholder, PlaceholderKind, Shape};
+use super::shapes::{Background, Placeholder, PlaceholderKind, Shape};
/// How a placeholder finds its counterpart on the part above it.
///
@@ -249,6 +252,70 @@ pub fn apply_slide(
stats
}
+// ── Background (§19.3.1.1) ───────────────────────────────────────────────────
+//
+// A second, much simpler cascade sharing the same slide → layout → master
+// chain. It needs none of the machinery above because a background is not
+// matched to a counterpart — there is at most one per part, so the rule is
+// "the nearest part that declares one wins" and no index is required.
+
+/// Which rung supplied a resolved background.
+///
+/// Carried because it is the probe's gate: the corpus split is **master 1,125
+/// / layout 95 / slide 58**, and a cascade that quietly stopped consulting the
+/// master would still resolve 153 slides and look like it worked.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BackgroundSource {
+ Slide,
+ Layout,
+ Master,
+}
+
+/// Resolve the background in force on a slide.
+///
+/// First declaration down the chain wins. Returns `None` only when no part in
+/// the chain declares one — which **does not happen on the corpus** (0 of
+/// 1,278), so a `None` here is a signal worth looking at rather than a normal
+/// outcome.
+///
+/// Note the arguments are each part's *own* background, i.e.
+/// [`SlidePart::background`], not an already-inherited one. Unlike the
+/// geometry rungs there is nothing to pre-flatten: the chain is three
+/// pointers and a slide is resolved in three comparisons.
+///
+/// [`SlidePart::background`]: crate::pptx::SlidePart::background
+pub fn resolve_background<'a>(
+ slide: Option<&'a Background>,
+ layout: Option<&'a Background>,
+ master: Option<&'a Background>,
+) -> Option<(BackgroundSource, &'a Background)> {
+ slide
+ .map(|b| (BackgroundSource::Slide, b))
+ .or_else(|| layout.map(|b| (BackgroundSource::Layout, b)))
+ .or_else(|| master.map(|b| (BackgroundSource::Master, b)))
+}
+
+/// Turn a resolved [`Background`] into a painter-ready fill.
+///
+/// **The single correct way to colour a background**, and it exists as one
+/// function precisely so that no caller has to remember which of the two arms
+/// takes the 1000-offset style-matrix path. Dispatching by hand is how a
+/// `bgRef` ends up in [`resolve_fill`] and silently comes back `None`.
+///
+/// `theme` must be the theme of *this slide's own master*
+/// ([`PresentationPackage::theme_for`]), not the deck's first. 31 corpus
+/// slides resolve a `bgRef` under a non-first master, and the deck-wide theme
+/// gives them a real fill from the wrong matrix.
+///
+/// [`PresentationPackage::theme_for`]: crate::pptx::PresentationPackage::theme_for
+pub fn background_fill(bg: &Background, theme: Option<&Theme>) -> ResolvedFill {
+ let ctx = DrawingColorContext::new(theme);
+ match bg {
+ Background::Properties(fill) => resolve_fill(fill, &ctx),
+ Background::Reference(r) => resolve_background_fill(r, theme, &ctx),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -472,4 +539,130 @@ mod tests {
assert_eq!(stats.orphans, 1);
assert_eq!(stats.unresolved, 0);
}
+
+ // ── Background ───────────────────────────────────────────────────────
+
+ use crate::model::{DrawingColor, DrawingFill, StyleMatrixRef};
+
+ fn srgb(rgb: u32) -> DrawingFill {
+ DrawingFill::Solid(DrawingColor::Srgb {
+ rgb,
+ transforms: Vec::new(),
+ })
+ }
+
+ fn solid(rgb: u32) -> Background {
+ Background::Properties(srgb(rgb))
+ }
+
+ /// Recover a 0xRRGGBB value from a resolved fill. `Rgba` is float
+ /// channels in 0..=1, so this rounds back to 8-bit rather than comparing
+ /// floats.
+ fn solid_rgb(f: &ResolvedFill) -> u32 {
+ match f {
+ ResolvedFill::Solid(c) => {
+ let ch = |v: f32| (v * 255.0).round() as u32;
+ (ch(c.r) << 16) | (ch(c.g) << 8) | ch(c.b)
+ }
+ other => panic!("expected a solid fill, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn nearest_declared_background_wins() {
+ let (s, l, m) = (solid(0x111111), solid(0x222222), solid(0x333333));
+ for (slide, layout, master, want_src, want_rgb) in [
+ (
+ Some(&s),
+ Some(&l),
+ Some(&m),
+ BackgroundSource::Slide,
+ 0x111111,
+ ),
+ (None, Some(&l), Some(&m), BackgroundSource::Layout, 0x222222),
+ (None, None, Some(&m), BackgroundSource::Master, 0x333333),
+ ] {
+ let (src, bg) = resolve_background(slide, layout, master).expect("resolves");
+ assert_eq!(src, want_src);
+ assert_eq!(solid_rgb(&background_fill(bg, None)), want_rgb);
+ }
+ }
+
+ /// The corpus has no slide without a background, so `None` is a signal
+ /// rather than a normal outcome — but it must still be `None` and not a
+ /// guessed white.
+ #[test]
+ fn a_chain_declaring_nothing_resolves_to_none() {
+ assert!(resolve_background(None, None, None).is_none());
+ }
+
+ /// **The regression test for the bug this work was built around.**
+ ///
+ /// §19.3.1.3: a `bgRef@idx` of 1001 selects `bgFillStyleLst[0]`, not
+ /// `fillStyleLst[1000]`. Every one of the 440 `bgRef` backgrounds on the
+ /// corpus uses exactly 1001, so routing them at the shape path's
+ /// `fillStyleLst` is not an edge case — it silently blanks 100% of them.
+ /// The two lists here hold different colours precisely so that a wrong
+ /// route returns a *wrong colour* rather than nothing, and is caught even
+ /// if `fillStyleLst` were long enough to be indexable.
+ #[test]
+ fn bg_ref_1001_reads_the_background_matrix_not_the_shape_matrix() {
+ let theme = Theme {
+ fill_styles: vec![srgb(0xAA0000), srgb(0xBB0000), srgb(0xCC0000)],
+ bg_fill_styles: vec![srgb(0x00AA00), srgb(0x00BB00)],
+ ..Theme::default()
+ };
+ let bg = Background::Reference(StyleMatrixRef {
+ idx: 1001,
+ color: None,
+ });
+ assert_eq!(solid_rgb(&background_fill(&bg, Some(&theme))), 0x00AA00);
+
+ // 1002 walks the same list, not off the end of the shape matrix.
+ let bg2 = Background::Reference(StyleMatrixRef {
+ idx: 1002,
+ color: None,
+ });
+ assert_eq!(solid_rgb(&background_fill(&bg2, Some(&theme))), 0x00BB00);
+
+ // Below 1001 the shape matrix is correct — the spec allows both forms
+ // even though the corpus only ever writes the offset one.
+ let bg3 = Background::Reference(StyleMatrixRef {
+ idx: 2,
+ color: None,
+ });
+ assert_eq!(solid_rgb(&background_fill(&bg3, Some(&theme))), 0xBB0000);
+ }
+
+ /// `idx=0` is §20.1.4.2.19's no-reference sentinel: no background, as
+ /// opposed to an out-of-range index.
+ #[test]
+ fn bg_ref_zero_is_no_background() {
+ let bg = Background::Reference(StyleMatrixRef {
+ idx: 0,
+ color: None,
+ });
+ assert!(matches!(
+ background_fill(&bg, Some(&Theme::default())),
+ ResolvedFill::None
+ ));
+ }
+
+ /// An index past the end of the background matrix must resolve to nothing
+ /// rather than wrap around or panic.
+ #[test]
+ fn bg_ref_past_the_end_resolves_to_none() {
+ let theme = Theme {
+ bg_fill_styles: vec![srgb(0x00AA00)],
+ ..Theme::default()
+ };
+ let bg = Background::Reference(StyleMatrixRef {
+ idx: 1009,
+ color: None,
+ });
+ assert!(matches!(
+ background_fill(&bg, Some(&theme)),
+ ResolvedFill::None
+ ));
+ }
}
diff --git a/crates/liteparse-ooxml/src/pptx/mod.rs b/crates/liteparse-ooxml/src/pptx/mod.rs
index ce51d0c..6b8634e 100644
--- a/crates/liteparse-ooxml/src/pptx/mod.rs
+++ b/crates/liteparse-ooxml/src/pptx/mod.rs
@@ -18,13 +18,15 @@ pub mod text;
pub mod textcascade;
pub use cascade::{
- CascadeStats, MatchRule, PlaceholderGeometry, apply_inherited_geometry, apply_slide,
+ BackgroundSource, CascadeStats, MatchRule, PlaceholderGeometry, apply_inherited_geometry,
+ apply_slide, background_fill, resolve_background,
};
pub use geometry::{GeometryStats, SlideRect, apply_slide_geometry};
pub use package::{EMU_PER_POINT, Part, PresentationInfo, PresentationPackage, SlideParts, walk};
pub use shapes::{
- AutoShape, Connector, GraphicFrame, GraphicFramePayload, Group, Placeholder, PlaceholderKind,
- Shape, ShapeKind, Table, TableCell, TableCellProperties, TableRow, parse_shape_tree, visit_all,
+ AutoShape, Background, Connector, GraphicFrame, GraphicFramePayload, Group, Placeholder,
+ PlaceholderKind, Shape, ShapeKind, SlidePart, Table, TableCell, TableCellProperties, TableRow,
+ parse_shape_tree, parse_slide_part, visit_all,
};
pub use text::{
AutoNumberScheme, Bullet, ListStyle, Spacing, TextBody, TextParagraph, TextParagraphProperties,
diff --git a/crates/liteparse-ooxml/src/pptx/package.rs b/crates/liteparse-ooxml/src/pptx/package.rs
index bcb1905..7dd3fce 100644
--- a/crates/liteparse-ooxml/src/pptx/package.rs
+++ b/crates/liteparse-ooxml/src/pptx/package.rs
@@ -80,6 +80,13 @@ pub struct SlideParts {
pub layout: Option<Part>,
pub master: Option<Part>,
pub notes: Option<Part>,
+ /// Package path of the theme reached through *this slide's own* master,
+ /// for [`PresentationPackage::themes`].
+ ///
+ /// A path rather than bytes because a theme is shared by every slide under
+ /// its master; cloning the XML per slide would copy it ~28 times on the
+ /// corpus's largest deck.
+ pub theme_path: Option<String>,
}
/// The whole deck, walked but not yet understood.
@@ -96,8 +103,18 @@ pub struct PresentationPackage {
pub presentation: Part,
/// Slides in **presentation order** — `<p:sldIdLst>`, not part order.
pub slides: Vec<SlideParts>,
- /// `ppt/theme/themeN.xml` for the first master, when present.
+ /// `ppt/theme/themeN.xml` for the **first** master, when present.
+ ///
+ /// Adequate for font resolution, which is what it was added for. **Not
+ /// adequate for colour**: 12 of the 45 corpus decks reach more than one
+ /// theme from their slides, covering 138 slides, and 31 of those resolve a
+ /// `<p:bgRef>` background out of the theme's style matrix — which would
+ /// come from the wrong theme, and therefore silently the wrong colour.
+ /// Use [`Self::theme_for`] wherever the answer is a colour.
pub theme: Option<Vec<u8>>,
+ /// Every theme in the package, keyed by normalized part path. Indexed by
+ /// [`SlideParts::theme_path`].
+ pub themes: std::collections::HashMap<String, Vec<u8>>,
/// The notes master, shared by every notes slide.
pub notes_master: Option<Part>,
/// Raw media parts, keyed by normalized package path.
@@ -171,33 +188,61 @@ pub fn walk(data: &[u8]) -> Result<PresentationPackage> {
.resolve_rel_of_type(&RelationshipType::NotesSlide)
.and_then(|p| load_part(&package, &p));
+ // The theme hangs off the master, so it is per-slide in exactly the
+ // way the master is. Resolved here rather than once for the deck: 12
+ // corpus decks reach more than one.
+ let theme_path = master
+ .as_ref()
+ .and_then(|m| m.resolve_rel_of_type(&RelationshipType::Theme));
+
slides.push(SlideParts {
slide,
layout,
master,
notes,
+ theme_path,
});
}
- // Theme comes off the first master. Decks with multiple masters can
- // carry multiple themes; resolving per-master is a colour-fidelity
- // concern deferred until `phClr` substitution lands.
+ let mut themes = std::collections::HashMap::new();
+ for path in slides.iter().filter_map(|s| s.theme_path.clone()) {
+ if let std::collections::hash_map::Entry::Vacant(e) = themes.entry(path)
+ && let Some(bytes) = package.get_part(e.key())
+ {
+ let bytes = bytes.to_vec();
+ e.insert(bytes);
+ }
+ }
+
+ // Retained for font resolution, which does not vary by master in any way
+ // the corpus shows. See the field docs for why colour must not use it.
let theme = slides
.iter()
- .find_map(|s| s.master.as_ref())
- .and_then(|m| m.resolve_rel_of_type(&RelationshipType::Theme))
- .and_then(|p| package.get_part(&p).map(|b| b.to_vec()));
+ .find_map(|s| s.theme_path.as_deref())
+ .and_then(|p| themes.get(p).cloned());
Ok(PresentationPackage {
info,
presentation: pres,
slides,
theme,
+ themes,
notes_master,
package,
})
}
+impl PresentationPackage {
+ /// The theme XML governing one slide, following its own master.
+ ///
+ /// Prefer this to [`Self::theme`] for anything colour-valued.
+ pub fn theme_for(&self, slide: &SlideParts) -> Option<&[u8]> {
+ self.themes
+ .get(slide.theme_path.as_deref()?)
+ .map(|v| &v[..])
+ }
+}
+
impl Part {
fn resolve_rel_of_type(&self, ty: &RelationshipType) -> Option<String> {
let rel = self.rels.find_by_type(ty)?;
diff --git a/crates/liteparse-ooxml/src/pptx/shapes.rs b/crates/liteparse-ooxml/src/pptx/shapes.rs
index 27e3288..5d901b9 100644
--- a/crates/liteparse-ooxml/src/pptx/shapes.rs
+++ b/crates/liteparse-ooxml/src/pptx/shapes.rs
@@ -47,15 +47,16 @@ use serde::Deserialize;
use crate::model::dimension::{Dimension, Emu};
use crate::model::geometry::{Offset, Size};
use crate::model::{
- BodyProperties, DocProperties, NvPicProperties, Picture, ShapeProperties, TextAnchoringType,
- TextVerticalType, Transform2D,
+ BodyProperties, DocProperties, DrawingFill, NvPicProperties, Picture, ShapeProperties,
+ StyleMatrixRef, TextAnchoringType, TextVerticalType, Transform2D,
};
use crate::docx::error::Result;
use crate::docx::parse::drawing::schema::fill::BlipFillXml;
use crate::docx::parse::drawing::schema::picture::{CNvPicPrXml, CNvPrXml};
use crate::docx::parse::drawing::schema::shape::{
- ExtXml, OffXml, SpPrXml, StTextAnchoringType, StTextVerticalType, XfrmXml,
+ ExtXml, OffXml, SpPrXml, StTextAnchoringType, StTextVerticalType, StyleMatrixRefXml, XfrmXml,
+ pick_fill,
};
use crate::docx::parse::serde_xml;
@@ -418,6 +419,58 @@ impl PlaceholderKind {
}
}
+/// §19.3.1.1 `<p:bg>` — the background of one slide, layout or master.
+///
+/// The two arms are the element's own `xsd:choice` and they resolve against
+/// different things, which is why this is an enum rather than a struct with
+/// two `Option`s: [`Self::Properties`] is self-contained, while
+/// [`Self::Reference`] is an index into the *theme*, and under a convention
+/// that is not the one a shape's `<a:fillRef>` uses. See
+/// [`resolve_background_fill`] for that trap.
+///
+/// [`resolve_background_fill`]: crate::render::resolve::shape_visuals::resolve_background_fill
+///
+/// Corpus (45 decks, 1,278 slides, counting the *effective* background after
+/// inheritance): 739 `bgPr` solid, 63 `bgPr` blip, 36 `bgPr` none, 440
+/// `bgRef`. **Zero slides resolve to no background at all.**
+#[derive(Clone, Debug)]
+pub enum Background {
+ /// §19.3.1.2 `<p:bgPr>` — an explicit fill.
+ ///
+ /// Its `EG_EffectProperties` sibling is **not** modelled: 579 corpus
+ /// backgrounds carry an `<a:effectLst>`, and the rasterizer renders no
+ /// effects at this tier, so keeping the field would only misreport
+ /// coverage. `a:scene3d`/`a:sp3d` and `@shadeToTitle` are dropped for the
+ /// same reason.
+ Properties(DrawingFill),
+ /// §19.3.1.3 `<p:bgRef>` — an index into the theme's style matrix.
+ Reference(StyleMatrixRef),
+}
+
+impl Background {
+ fn from_xml(x: BgXml) -> Option<Self> {
+ // §19.3.1.1 is a choice, so at most one arm is present. `bgPr` is
+ // checked first only to give a malformed both-present element a
+ // deterministic reading.
+ if let Some(pr) = x.bg_pr {
+ // A `<p:bgPr>` with no recognized fill child is malformed (the
+ // spec requires one). Treat it as "declares nothing" so the
+ // cascade keeps looking upward, rather than as an opaque
+ // transparent background that would mask the master's.
+ return pick_fill(
+ pr.no_fill,
+ pr.grp_fill,
+ pr.solid_fill,
+ pr.grad_fill,
+ pr.blip_fill,
+ pr.patt_fill,
+ )
+ .map(Background::Properties);
+ }
+ x.bg_ref.map(|r| Background::Reference(r.into()))
+ }
+}
+
// ── Entry point ──────────────────────────────────────────────────────────────
/// Parse the shape tree out of a slide, layout, master or notes-slide part.
@@ -429,12 +482,44 @@ impl PlaceholderKind {
///
/// A part with no shape tree yields an empty `Vec` rather than an error: the
/// fail-open posture `ATTRIBUTION.md` records for this vendor.
+///
+/// Reads only `p:spTree`. Callers that also need the part's background — the
+/// painter does; the markdown emitter does not — want [`parse_slide_part`],
+/// which returns both from a single deserialization.
pub fn parse_shape_tree(data: &[u8]) -> Result<Vec<Shape>> {
+ Ok(parse_slide_part(data)?.shapes)
+}
+
+/// A `p:cSld`'s two payloads: its shape tree and its background.
+///
+/// One struct rather than two entry points because both come out of the same
+/// `p:cSld`, and parsing the part twice to get them would double the cost of
+/// the deck walk for a field that is one element wide.
+#[derive(Clone, Debug, Default)]
+pub struct SlidePart {
+ pub shapes: Vec<Shape>,
+ /// §19.3.1.1 `<p:bg>`, when *this* part declares one. `None` means "not
+ /// declared here", **not** "no background" — the value is inherited, and
+ /// resolving it is [`crate::pptx::cascade::resolve_background`]'s job.
+ /// Only 58 of the corpus's 1,278 slides declare their own; 1,125 inherit
+ /// from the master.
+ pub background: Option<Background>,
+}
+
+/// Parse a slide, layout, master or notes-slide part into its shapes and its
+/// own (uninherited) background.
+pub fn parse_slide_part(data: &[u8]) -> Result<SlidePart> {
let part: SlidePartXml = serde_xml::from_xml(data)?;
- let Some(tree) = part.c_sld.and_then(|c| c.sp_tree) else {
- return Ok(Vec::new());
+ let Some(c_sld) = part.c_sld else {
+ return Ok(SlidePart::default());
};
- Ok(lower_children(tree.children))
+ Ok(SlidePart {
+ shapes: c_sld
+ .sp_tree
+ .map(|t| lower_children(t.children))
+ .unwrap_or_default(),
+ background: c_sld.bg.and_then(Background::from_xml),
+ })
}
// ── Schema ───────────────────────────────────────────────────────────────────
@@ -451,10 +536,43 @@ struct SlidePartXml {
#[derive(Deserialize)]
struct CSldXml {
+ /// §19.3.1.1 — precedes `spTree` in the content model.
+ #[serde(rename = "bg", default)]
+ bg: Option<BgXml>,
#[serde(rename = "spTree", default)]
sp_tree: Option<SpTreeXml>,
}
+/// §19.3.1.1 CT_Background — `xsd:choice` of `bgPr` and `bgRef`.
+#[derive(Deserialize)]
+struct BgXml {
+ #[serde(rename = "bgPr", default)]
+ bg_pr: Option<BgPrXml>,
+ #[serde(rename = "bgRef", default)]
+ bg_ref: Option<StyleMatrixRefXml>,
+}
+
+/// §19.3.1.2 CT_BackgroundProperties.
+///
+/// The six fill members are spelled out and routed through the DrawingML
+/// [`pick_fill`] rather than re-derived, because this is the same
+/// `EG_FillProperties` group `<a:spPr>` carries — see [`SpPrXml`].
+#[derive(Deserialize, Default)]
+struct BgPrXml {
+ #[serde(rename = "noFill", default)]
+ no_fill: Option<crate::docx::parse::drawing::schema::fill::Empty>,
+ #[serde(rename = "solidFill", default)]
+ solid_fill: Option<crate::docx::parse::drawing::schema::fill::SolidFillXml>,
+ #[serde(rename = "gradFill", default)]
+ grad_fill: Option<crate::docx::parse::drawing::schema::fill::GradFillXml>,
+ #[serde(rename = "blipFill", default)]
+ blip_fill: Option<crate::docx::parse::drawing::schema::fill::BlipFillXml>,
+ #[serde(rename = "pattFill", default)]
+ patt_fill: Option<crate::docx::parse::drawing::schema::fill::PattFillXml>,
+ #[serde(rename = "grpFill", default)]
+ grp_fill: Option<crate::docx::parse::drawing::schema::fill::Empty>,
+}
+
#[derive(Deserialize, Default)]
struct SpTreeXml {
/// Members interleave freely and their order **is** z-order, so they are
@@ -1583,4 +1701,101 @@ mod tests {
));
assert_eq!(shapes.len(), 1);
}
+
+ // ── Background (§19.3.1.1) ───────────────────────────────────────────
+
+ /// Same namespace scaffolding as [`tree`], but with a `p:bg` sibling
+ /// ahead of the shape tree, which is where the content model puts it.
+ fn part_with_bg(bg: &str) -> SlidePart {
+ let xml = format!(
+ r#"<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
+ xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
+ xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
+ <p:cSld>
+ {bg}
+ <p:spTree>
+ <p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>
+ <p:grpSpPr/>
+ </p:spTree>
+ </p:cSld>
+ </p:sld>"#
+ );
+ parse_slide_part(xml.as_bytes()).expect("parses")
+ }
+
+ #[test]
+ fn bg_pr_solid_fill_is_read() {
+ let part = part_with_bg(
+ r#"<p:bg><p:bgPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>
+ <a:effectLst/></p:bgPr></p:bg>"#,
+ );
+ match part.background {
+ Some(Background::Properties(DrawingFill::Solid(_))) => {}
+ other => panic!("expected a solid bgPr, got {other:?}"),
+ }
+ }
+
+ /// `bgRef@idx` must survive as declared. 1001 is not a typo and not a
+ /// cosmetic index: it selects the theme's *background* fill matrix, and
+ /// every `bgRef` on the corpus uses it. Clamping or defaulting it here
+ /// would push the bug down into the resolver.
+ #[test]
+ fn bg_ref_keeps_its_thousand_offset_index() {
+ let part =
+ part_with_bg(r#"<p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg>"#);
+ match part.background {
+ Some(Background::Reference(r)) => {
+ assert_eq!(r.idx, 1001);
+ assert!(r.color.is_some(), "the phClr substitute must survive");
+ }
+ other => panic!("expected a bgRef, got {other:?}"),
+ }
+ }
+
+ /// A part that declares no background yields `None`, which the cascade
+ /// reads as "look further up" — not as "transparent".
+ #[test]
+ fn absent_bg_is_none() {
+ assert!(part_with_bg("").background.is_none());
+ }
+
+ /// A `<p:bgPr>` with no fill child is malformed. It must read as "declares
+ /// nothing" so the cascade keeps walking, rather than as an opaque
+ /// nothing that would mask the master's real background.
+ #[test]
+ fn bg_pr_without_a_fill_declares_nothing() {
+ let part = part_with_bg(r#"<p:bg><p:bgPr><a:effectLst/></p:bgPr></p:bg>"#);
+ assert!(part.background.is_none());
+ }
+
+ /// `<a:noFill>` is a real declaration — an explicitly transparent
+ /// background — and must be distinguishable from the absent case above.
+ #[test]
+ fn bg_pr_no_fill_is_a_declaration_not_an_absence() {
+ let part = part_with_bg(r#"<p:bg><p:bgPr><a:noFill/></p:bgPr></p:bg>"#);
+ assert!(matches!(
+ part.background,
+ Some(Background::Properties(DrawingFill::None))
+ ));
+ }
+
+ /// The background lives beside the shape tree, so reading one must not
+ /// cost the other.
+ #[test]
+ fn background_and_shapes_come_from_one_parse() {
+ let xml = r#"<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
+ xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
+ <p:cSld>
+ <p:bg><p:bgPr><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill></p:bgPr></p:bg>
+ <p:spTree>
+ <p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>
+ <p:grpSpPr/>
+ <p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
+ <p:spPr/></p:sp>
+ </p:spTree>
+ </p:cSld></p:sld>"#;
+ let part = parse_slide_part(xml.as_bytes()).expect("parses");
+ assert_eq!(part.shapes.len(), 1);
+ assert!(part.background.is_some());
+ }
}
diff --git a/crates/liteparse-ooxml/src/render/layout/draw_command.rs b/crates/liteparse-ooxml/src/render/layout/draw_command.rs
index 4656860..b372958 100644
--- a/crates/liteparse-ooxml/src/render/layout/draw_command.rs
+++ b/crates/liteparse-ooxml/src/render/layout/draw_command.rs
@@ -53,6 +53,53 @@ pub enum OutlineMark {
End,
}
+/// §20.1.7.6 `a:xfrm`: the placement that maps one shape's local coordinates
+/// onto the page.
+///
+/// The fields are exactly [`DrawCommand::Path`]'s placement fields, and mean
+/// the same thing — flips and rotation happen about the shape's centre, then
+/// the shape lands at `origin` — so a consumer builds the same matrix for both
+/// and `raster.rs` does.
+#[derive(Debug, Clone)]
+pub struct ShapeTransform {
+ /// Top-left placement anchor in page coordinates.
+ pub origin: PtOffset,
+ /// Rotation in 60000ths of a degree, clockwise, about the shape's centre.
+ pub rotation: Dimension<SixtieThousandthDeg>,
+ /// Mirror horizontally before placement.
+ pub flip_h: bool,
+ /// Mirror vertically before placement.
+ pub flip_v: bool,
+ /// Shape-local size — the box the bracketed commands were laid out in.
+ pub extent: PtSize,
+}
+
+/// The boundaries of one shape's commands, and the placement that puts them on
+/// the page.
+///
+/// **Commands between `Begin` and `End` are in shape-local Pt**, with the
+/// origin at the shape's top-left — the space `shape_body::layout_shape_body`
+/// emits in. A consumer that ignores the bracket reads them as page
+/// coordinates and places every one of them at the top-left corner.
+///
+/// A bracket rather than a field on [`DrawCommand::Text`] for the reason
+/// [`OutlineMark`] is one: `Text` is constructed at ~100 sites across this
+/// crate, so a field means editing every one of them to pass a value only PPTX
+/// ever sets. This variant is emitted by the PPTX path alone — the DOCX
+/// stacker shifts a text box's commands onto the page and rotates nothing, so
+/// its pages contain no brackets and are unaffected by this variant existing.
+///
+/// Nesting is flat: PPTX composes group transforms into `Shape::slide_rect`
+/// before layout, so each shape (or table cell) opens and closes its own
+/// bracket and none contains another.
+#[derive(Debug, Clone)]
+pub enum TransformMark {
+ /// Opens a shape-local coordinate space.
+ Begin(ShapeTransform),
+ /// Closes it, restoring page coordinates.
+ End,
+}
+
/// A positioned drawing command — absolute page coordinates.
#[derive(Debug, Clone)]
pub enum DrawCommand {
@@ -134,6 +181,9 @@ pub enum DrawCommand {
/// §17.3.1.19: brackets one heading paragraph's commands so the PDF
/// outline can point at it. Draws nothing.
Outline(OutlineMark),
+ /// §20.1.7.6: brackets one shape's commands with the placement that maps
+ /// them onto the page. Draws nothing. PPTX only — see [`TransformMark`].
+ Transform(TransformMark),
/// §20.1.8 shape draw command — a resolved geometry with fill, stroke,
/// and optional effects. `paths` are in shape-local Pt; the painter
/// applies the placement transform (origin/rotation/flip).
@@ -304,6 +354,18 @@ impl DrawCommand {
// destination is derived from the commands it brackets, which do
// get shifted.
DrawCommand::Outline(_) => {}
+ // The bracket's origin is the *only* page coordinate in the run it
+ // opens: the commands inside it are shape-local, so shifting them
+ // as well would apply the offset twice. Nothing shifts a bracketed
+ // page today — PPTX builds its pages in slide coordinates and the
+ // DOCX stacker, which is what calls `shift`, emits no brackets —
+ // so this arm keeps the two halves consistent rather than serving
+ // a live caller.
+ DrawCommand::Transform(TransformMark::Begin(t)) => {
+ t.origin.x += dx;
+ t.origin.y += dy;
+ }
+ DrawCommand::Transform(TransformMark::End) => {}
}
}
@@ -343,6 +405,11 @@ impl DrawCommand {
| DrawCommand::InternalLink { .. }
| DrawCommand::NamedDestination { .. }
| DrawCommand::Outline(_) => None,
+ // Reporting the bracket's own band would be reporting it in a
+ // different space from the commands it brackets, which report
+ // theirs shape-locally. The one caller (`@vertOverflow="clip"`)
+ // works inside a single shape's body, where no bracket exists yet.
+ DrawCommand::Transform(_) => None,
}
}
@@ -496,9 +563,52 @@ mod tests {
// there is nothing for `shift` to move. `shift_leaves_a_marker_be`
// asserts that directly rather than through this helper.
DrawCommand::Outline(_) => unreachable!("markers are tested separately"),
+ // §20.1.7.6: a bracket's origin *is* a coordinate and does shift,
+ // but its `End` half has none, so the pair is tested on its own in
+ // `shift_moves_only_a_brackets_origin`.
+ DrawCommand::Transform(_) => unreachable!("brackets are tested separately"),
}
}
+ /// The bracket carries the one page coordinate in the run it opens, so
+ /// `shift` must move it — and must leave `End` alone, which has none.
+ #[test]
+ fn shift_moves_only_a_brackets_origin() {
+ let placement = ShapeTransform {
+ origin: PtOffset::new(Pt::new(10.0), Pt::new(20.0)),
+ rotation: Dimension::new(60_000),
+ flip_h: false,
+ flip_v: false,
+ extent: PtSize::new(Pt::new(4.0), Pt::new(6.0)),
+ };
+ let mut begin = DrawCommand::Transform(TransformMark::Begin(placement));
+ begin.shift(Pt::new(DX), Pt::new(DY));
+ let DrawCommand::Transform(TransformMark::Begin(moved)) = &begin else {
+ unreachable!()
+ };
+ assert_eq!(
+ (moved.origin.x.raw(), moved.origin.y.raw()),
+ (10.0 + DX, 20.0 + DY)
+ );
+ // The bracketed commands are shape-local, so the box they were laid
+ // out in must not move with the placement.
+ assert_eq!(
+ (moved.extent.width.raw(), moved.extent.height.raw()),
+ (4.0, 6.0)
+ );
+ assert_eq!(moved.rotation.raw(), 60_000, "shifting is not rotating");
+
+ let mut end = DrawCommand::Transform(TransformMark::End);
+ let before = format!("{end:?}");
+ end.shift(Pt::new(DX), Pt::new(DY));
+ assert_eq!(format!("{end:?}"), before);
+
+ // Neither half paints, and neither may report a band: the commands
+ // they bracket report theirs in a different (shape-local) space.
+ assert_eq!(begin.vertical_span(), None);
+ assert_eq!(end.vertical_span(), None);
+ }
+
/// The only variant `one_of_each` cannot carry, because it has no origin to
/// compare. Shifting it must leave it alone — the destination its outline
/// entry gets is derived from the commands it brackets, which *are* shifted.
diff --git a/crates/liteparse-ooxml/src/render/layout/table/split.rs b/crates/liteparse-ooxml/src/render/layout/table/split.rs
index d4da09a..3d13f5e 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/split.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/split.rs
@@ -401,6 +401,11 @@ fn command_primary_y(cmd: &DrawCommand) -> Pt {
// heading whose paragraph splits keeps its outline entry on the page
// it starts on, which is the same rule the paragraph splitter applies.
DrawCommand::Outline(_) => Pt::ZERO,
+ // §20.1.7.6: a placement marker. A DOCX table's cell commands never
+ // contain one, so this arm exists for exhaustiveness; taking the top
+ // of the cell keeps a bracket with the half its shape starts in, the
+ // same rule the outline marker follows.
+ DrawCommand::Transform(_) => Pt::ZERO,
}
}
diff --git a/crates/liteparse-ooxml/src/render/mod.rs b/crates/liteparse-ooxml/src/render/mod.rs
index a7ccfd9..0161de3 100644
--- a/crates/liteparse-ooxml/src/render/mod.rs
+++ b/crates/liteparse-ooxml/src/render/mod.rs
@@ -68,6 +68,9 @@ fn estimate_cursor_y(
DrawCommand::Path { origin, extent, .. } => origin.y + extent.height,
// §17.3.1.19: draws nothing, so it consumes no vertical space.
DrawCommand::Outline(_) => continue,
+ // §20.1.7.6: a placement marker, and one this function never sees
+ // — it runs over DOCX section pages, which carry no brackets.
+ DrawCommand::Transform(_) => continue,
// Annotations mark content that is already accounted for by the
// command underneath them, and a named destination is a point.
// Neither adds extent of its own.
diff --git a/crates/liteparse-ooxml/src/render/raster.rs b/crates/liteparse-ooxml/src/render/raster.rs
index 5d5b35d..16f316d 100644
--- a/crates/liteparse-ooxml/src/render/raster.rs
+++ b/crates/liteparse-ooxml/src/render/raster.rs
@@ -41,7 +41,7 @@ use crate::render::fonts::{FontRegistry, FontStyle, TypefaceEntry};
use crate::render::geometry::{PtOffset, PtRect};
use crate::render::layout::draw_command::{
DrawCommand, LayoutedPage, ResolvedDashPattern, ResolvedFill, ResolvedLineCap,
- ResolvedLineJoin, ResolvedStroke,
+ ResolvedLineJoin, ResolvedStroke, TransformMark,
};
use crate::render::resolve::color::RgbColor;
use crate::render::resolve::drawing_color::Rgba;
@@ -105,10 +105,26 @@ pub fn rasterize_page(
RasterPass::Media,
RasterPass::Ink,
] {
+ // The shape-local → page transform opened by the innermost
+ // `DrawCommand::Transform` bracket, or the identity outside one.
+ // Tracked per pass, and updated *before* the pass filter: every pass
+ // walks the whole command list, so a bracket skipped as "not my pass"
+ // would leave the pass that does paint inside it in the wrong space.
+ let mut local = Transform::identity();
for cmd in &page.commands {
+ if let DrawCommand::Transform(mark) = cmd {
+ local = match mark {
+ TransformMark::Begin(t) => {
+ place_transform(t.origin, t.rotation, t.flip_h, t.flip_v, t.extent)
+ }
+ TransformMark::End => Transform::identity(),
+ };
+ continue;
+ }
if raster_pass(cmd) != Some(pass) {
continue;
}
+ let device = device.pre_concat(local);
match cmd {
DrawCommand::Text {
position,
@@ -181,25 +197,9 @@ pub fn rasterize_page(
stroke,
effects: _, // shadow/glow: skipped at this tier
} => {
- // Shape-local Pt → page Pt: flips and rotation happen about
- // the shape's center, then the shape lands at `origin`.
- let (cx, cy) = (extent.width.raw() / 2.0, extent.height.raw() / 2.0);
- let mut place = Transform::from_translate(origin.x.raw(), origin.y.raw());
- let deg = rotation.raw() as f32 / 60_000.0;
- if deg != 0.0 {
- place = place.pre_concat(Transform::from_rotate_at(deg, cx, cy));
- }
- if *flip_h || *flip_v {
- let (sx, sy) = (
- if *flip_h { -1.0 } else { 1.0 },
- if *flip_v { -1.0 } else { 1.0 },
- );
- place = place
- .pre_concat(Transform::from_translate(cx, cy))
- .pre_concat(Transform::from_scale(sx, sy))
- .pre_concat(Transform::from_translate(-cx, -cy));
- }
- let transform = device.pre_concat(place);
+ let transform = device.pre_concat(place_transform(
+ *origin, *rotation, *flip_h, *flip_v, *extent,
+ ));
for sub in paths {
draw_subpath(&mut pixmap, sub, fill, stroke.as_ref(), transform);
}
@@ -210,7 +210,8 @@ pub fn rasterize_page(
DrawCommand::LinkAnnotation { .. }
| DrawCommand::InternalLink { .. }
| DrawCommand::NamedDestination { .. }
- | DrawCommand::Outline(_) => {}
+ | DrawCommand::Outline(_)
+ | DrawCommand::Transform(_) => {}
}
}
}
@@ -250,10 +251,46 @@ fn raster_pass(cmd: &DrawCommand) -> Option<RasterPass> {
DrawCommand::LinkAnnotation { .. }
| DrawCommand::InternalLink { .. }
| DrawCommand::NamedDestination { .. }
- | DrawCommand::Outline(_) => None,
+ | DrawCommand::Outline(_)
+ // Handled before this filter runs — a bracket belongs to no single
+ // pass, it changes the space every pass paints the run in.
+ | DrawCommand::Transform(_) => None,
}
}
+/// Shape-local Pt → page Pt: flips and rotation happen about the shape's
+/// centre, then the shape lands at `origin`.
+///
+/// Shared by [`DrawCommand::Path`], which carries these fields inline, and by
+/// the [`TransformMark`] bracket, which carries the same five for a run of
+/// commands. One function so a bracketed text body and a shape's own geometry
+/// cannot land in different places on the same slide.
+fn place_transform(
+ origin: PtOffset,
+ rotation: crate::model::dimension::Dimension<crate::model::dimension::SixtieThousandthDeg>,
+ flip_h: bool,
+ flip_v: bool,
+ extent: crate::render::geometry::PtSize,
+) -> Transform {
+ let (cx, cy) = (extent.width.raw() / 2.0, extent.height.raw() / 2.0);
+ let mut place = Transform::from_translate(origin.x.raw(), origin.y.raw());
+ let deg = rotation.raw() as f32 / 60_000.0;
+ if deg != 0.0 {
+ place = place.pre_concat(Transform::from_rotate_at(deg, cx, cy));
+ }
+ if flip_h || flip_v {
+ let (sx, sy) = (
+ if flip_h { -1.0 } else { 1.0 },
+ if flip_v { -1.0 } else { 1.0 },
+ );
+ place = place
+ .pre_concat(Transform::from_translate(cx, cy))
+ .pre_concat(Transform::from_scale(sx, sy))
+ .pre_concat(Transform::from_translate(-cx, -cy));
+ }
+ place
+}
+
// ─── Text ───────────────────────────────────────────────────────────────────
/// skrifa outline pen writing into a tiny-skia path builder.
@@ -666,3 +703,120 @@ fn skia_rect(r: &PtRect) -> Option<tiny_skia::Rect> {
r.size.height.raw(),
)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::Dimension;
+ use crate::render::geometry::PtSize;
+ use crate::render::layout::draw_command::ShapeTransform;
+
+ /// A page with one black rect, wrapped in `bracket`.
+ fn bracketed_rect(bracket: ShapeTransform, rect: PtRect) -> LayoutedPage {
+ LayoutedPage {
+ commands: vec![
+ DrawCommand::Transform(TransformMark::Begin(bracket)),
+ DrawCommand::Rect {
+ rect,
+ color: RgbColor { r: 0, g: 0, b: 0 },
+ },
+ DrawCommand::Transform(TransformMark::End),
+ ],
+ page_size: PtSize::new(Pt::new(100.0), Pt::new(100.0)),
+ block_starts: Vec::new(),
+ }
+ }
+
+ fn place(origin: (f32, f32), deg: f32, extent: (f32, f32)) -> ShapeTransform {
+ ShapeTransform {
+ origin: PtOffset::new(Pt::new(origin.0), Pt::new(origin.1)),
+ rotation: Dimension::new((deg * 60_000.0) as i64),
+ flip_h: false,
+ flip_v: false,
+ extent: PtSize::new(Pt::new(extent.0), Pt::new(extent.1)),
+ }
+ }
+
+ fn rect(x: f32, y: f32, w: f32, h: f32) -> PtRect {
+ PtRect::from_xywh(Pt::new(x), Pt::new(y), Pt::new(w), Pt::new(h))
+ }
+
+ /// Is the pixel at Pt `(x, y)` inked? Rasterized at 1 px/Pt, so the two
+ /// coordinate systems coincide.
+ fn inked(raster: &RasterPage, x: usize, y: usize) -> bool {
+ let i = (y * raster.width as usize + x) * 4;
+ raster.rgba[i] < 128
+ }
+
+ /// A bracketed command is in *shape-local* Pt: a rect at the local origin
+ /// must land where the bracket puts it, and nothing must land at the page
+ /// origin — which is exactly where a painter that ignored the bracket
+ /// would draw it.
+ #[test]
+ fn a_bracket_places_the_commands_it_opens() {
+ let page = bracketed_rect(
+ place((50.0, 50.0), 0.0, (20.0, 20.0)),
+ rect(0.0, 0.0, 10.0, 10.0),
+ );
+ let r = rasterize_page(&page, &FontRegistry::new(), 1.0).expect("raster");
+ assert!(inked(&r, 55, 55), "the rect lands at the bracket's origin");
+ assert!(!inked(&r, 5, 5), "and not at the page origin");
+ }
+
+ /// Rotation is about the shape's centre, not its origin — the same rule
+ /// `DrawCommand::Path` states. A quarter turn takes the body's top strip
+ /// to its right-hand one.
+ #[test]
+ fn a_bracket_rotates_about_the_shape_centre() {
+ let page = bracketed_rect(
+ place((50.0, 50.0), 90.0, (20.0, 20.0)),
+ rect(0.0, 0.0, 20.0, 10.0),
+ );
+ let r = rasterize_page(&page, &FontRegistry::new(), 1.0).expect("raster");
+ assert!(
+ inked(&r, 65, 60),
+ "top strip turned into the right-hand one"
+ );
+ assert!(!inked(&r, 55, 60), "the left half is now empty");
+ }
+
+ /// Every pass walks the whole command list, so bracket state has to be
+ /// tracked in each of them: a rect (shading pass) and a path (shape pass)
+ /// inside one bracket must both be placed by it.
+ #[test]
+ fn every_pass_honours_the_bracket() {
+ let mut page = bracketed_rect(
+ place((50.0, 50.0), 0.0, (20.0, 20.0)),
+ rect(0.0, 0.0, 10.0, 10.0),
+ );
+ let square = SubPath {
+ verbs: vec![
+ PathVerb::MoveTo(PtOffset::new(Pt::new(0.0), Pt::new(10.0))),
+ PathVerb::LineTo(PtOffset::new(Pt::new(10.0), Pt::new(10.0))),
+ PathVerb::LineTo(PtOffset::new(Pt::new(10.0), Pt::new(20.0))),
+ PathVerb::LineTo(PtOffset::new(Pt::new(0.0), Pt::new(20.0))),
+ PathVerb::Close,
+ ],
+ fill_mode: PathFillMode::Norm,
+ stroked: false,
+ };
+ page.commands.insert(
+ 2,
+ DrawCommand::Path {
+ origin: PtOffset::new(Pt::ZERO, Pt::ZERO),
+ rotation: Dimension::new(0),
+ flip_h: false,
+ flip_v: false,
+ extent: PtSize::new(Pt::new(20.0), Pt::new(20.0)),
+ paths: vec![square],
+ fill: ResolvedFill::Solid(Rgba::BLACK),
+ stroke: None,
+ effects: Vec::new(),
+ },
+ );
+ let r = rasterize_page(&page, &FontRegistry::new(), 1.0).expect("raster");
+ assert!(inked(&r, 55, 55), "shading pass placed by the bracket");
+ assert!(inked(&r, 55, 65), "shape pass placed by the bracket too");
+ assert!(!inked(&r, 5, 15), "neither drew at the page origin");
+ }
+}
diff --git a/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs b/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs
index 4d0b4d5..aad282d 100644
--- a/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs
@@ -474,6 +474,7 @@ mod tests {
major_font: ThemeFontScheme::default(),
minor_font: ThemeFontScheme::default(),
fill_styles: vec![],
+ bg_fill_styles: vec![],
line_styles: vec![],
effect_styles: vec![],
}
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
index b66dc30..fefafc3 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
@@ -117,6 +117,49 @@ fn resolve_theme_fill(
resolve_fill(fill, &fill_ctx)
}
+/// §19.3.1.3: resolve a slide/layout/master `<p:bgRef>` against the theme.
+///
+/// **Deliberately not [`resolve_theme_fill`].** A `bgRef` indexes a different
+/// matrix under a different convention: `idx` 1..=999 selects
+/// `fillStyleLst[idx - 1]`, while **1001 and above select
+/// `bgFillStyleLst[idx - 1001]`**. Routing a `bgRef` through the shape path
+/// would look up index 1000 of a 3-entry list, miss, and return
+/// [`ResolvedFill::None`] — a slide with no background rather than an error.
+/// Every one of the 440 `bgRef` backgrounds on the PPTX corpus uses
+/// `idx="1001"`, so that miss would have been the *only* outcome, on 100% of
+/// them.
+///
+/// Kept as a separate entry point rather than a branch inside
+/// `resolve_theme_fill` so that a shape's `<a:fillRef>` — which has no
+/// 1000-offset form — cannot start silently accepting one.
+pub fn resolve_background_fill(
+ bg_ref: &StyleMatrixRef,
+ theme: Option<&Theme>,
+ ctx: &DrawingColorContext<'_>,
+) -> ResolvedFill {
+ // §20.1.4.2.19: 0 is the no-reference sentinel, here meaning "no
+ // background" rather than "inherit".
+ if bg_ref.idx == 0 {
+ return ResolvedFill::None;
+ }
+ let Some(theme) = theme else {
+ return ResolvedFill::None;
+ };
+ let fill = if bg_ref.idx > 1000 {
+ theme.bg_fill_styles.get((bg_ref.idx as usize) - 1001)
+ } else {
+ theme.fill_styles.get((bg_ref.idx as usize) - 1)
+ };
+ let Some(fill) = fill else {
+ return ResolvedFill::None;
+ };
+ let fill_ctx = match bg_ref.color.as_ref() {
+ Some(c) => ctx.with_placeholder(resolve_drawing_color(c, ctx)),
+ None => *ctx,
+ };
+ resolve_fill(fill, &fill_ctx)
+}
+
/// Look up a theme line style by its 1-based `lnRef` index.
fn theme_line_style<'a>(
style_line_ref: Option<&StyleMatrixRef>,
diff --git a/crates/liteparse/src/office/docx_layout.rs b/crates/liteparse/src/office/docx_layout.rs
index 32a807d..8144419 100644
--- a/crates/liteparse/src/office/docx_layout.rs
+++ b/crates/liteparse/src/office/docx_layout.rs
@@ -217,13 +217,22 @@ pub fn layout_to_pages(
// the ParseResult contract can hold it (the PDF path drops
// GoTo destinations the same way — annotations carry only the
// source rects).
+ //
+ // `Transform` is the PPTX placement bracket. This converter is
+ // only ever handed body-local pages — the DOCX stacker emits
+ // no brackets, and `pptx_layout` converts one shape body at a
+ // time and applies the placement to the items itself — so a
+ // bracket reaching here would mean a slide-wide page was
+ // converted without its placements, which is a caller bug this
+ // arm cannot repair.
DrawCommand::Underline { .. }
| DrawCommand::Line { .. }
| DrawCommand::Rect { .. }
| DrawCommand::Image { .. }
| DrawCommand::Path { .. }
| DrawCommand::InternalLink { .. }
- | DrawCommand::NamedDestination { .. } => {}
+ | DrawCommand::NamedDestination { .. }
+ | DrawCommand::Transform(_) => {}
}
}
diff --git a/crates/liteparse/src/office/pptx_layout.rs b/crates/liteparse/src/office/pptx_layout.rs
index ee70814..a9bc5a4 100644
--- a/crates/liteparse/src/office/pptx_layout.rs
+++ b/crates/liteparse/src/office/pptx_layout.rs
@@ -45,9 +45,11 @@ use liteparse_ooxml::pptx::{
};
use liteparse_ooxml::render::dimension::Pt;
use liteparse_ooxml::render::fonts::FontRegistry;
-use liteparse_ooxml::render::geometry::PtSize;
+use liteparse_ooxml::render::geometry::{PtOffset, PtSize};
use liteparse_ooxml::render::layout::ShapeAutoFit;
-use liteparse_ooxml::render::layout::draw_command::LayoutedPage;
+use liteparse_ooxml::render::layout::draw_command::{
+ DrawCommand, LayoutedPage, ShapeTransform, TransformMark,
+};
use liteparse_ooxml::render::layout::fragment::{
Fragment, emit_run_fragments, font_props_from_run,
};
@@ -79,6 +81,16 @@ pub struct SlideGeometry {
/// One page per slide, in presentation order. Page count always equals
/// slide count, so a page index is a slide index.
pub pages: Vec<Page>,
+ /// The same slides as draw commands rather than boxes — one page per
+ /// slide, parallel to `pages`, ready for `render::raster::rasterize_page`.
+ ///
+ /// Not a second derivation: each shape contributes the *same*
+ /// `layout_shape_body` output that became its [`TextItem`]s, bracketed by
+ /// the `DrawCommand::Transform` that places it on the slide. So a
+ /// screenshot and the geometry it would highlight come from one layout, by
+ /// construction — which is the property the LibreOffice screenshot path
+ /// could never offer.
+ pub layouts: Vec<LayoutedPage>,
/// Per page, the shape each run of items came from. Parallel to `pages`.
///
/// Derived geometry has no external oracle — PPTX declares no coordinate
@@ -166,6 +178,7 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
let mut deck = Deck::new(pkg);
let mut out = SlideGeometry {
pages: Vec::with_capacity(pkg.slides.len()),
+ layouts: Vec::with_capacity(pkg.slides.len()),
placements: Vec::with_capacity(pkg.slides.len()),
placed_table_cells: 0,
unplaced_table_cells: 0,
@@ -175,6 +188,7 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
for (idx, slide) in pkg.slides.iter().enumerate() {
let mut items = Vec::new();
let mut placements = Vec::new();
+ let mut commands = Vec::new();
// 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) {
@@ -185,6 +199,7 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
measurer: &measurer,
registry,
items: &mut items,
+ commands: &mut commands,
placements: &mut placements,
placed_table_cells: &mut out.placed_table_cells,
unplaced_table_cells: &mut out.unplaced_table_cells,
@@ -196,6 +211,13 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
}
out.placements.push(placements);
+ out.layouts.push(LayoutedPage {
+ commands,
+ page_size,
+ // A DOCX-only side-channel: it indexes the flattened body blocks a
+ // page starts, and a slide is one page with no such flattening.
+ block_starts: Vec::new(),
+ });
let content_bounds = union_bounds(&items);
out.pages.push(Page {
page_number: idx + 1,
@@ -222,12 +244,33 @@ struct ShapeCtx<'a, 'r> {
measurer: &'a TextMeasurer<'r>,
registry: &'a FontRegistry,
items: &'a mut Vec<TextItem>,
+ /// The slide's draw commands, in slide coordinates once each shape's run
+ /// is read through the bracket that opens it.
+ commands: &'a mut Vec<DrawCommand>,
placements: &'a mut Vec<ShapePlacement>,
placed_table_cells: &'a mut usize,
unplaced_table_cells: &'a mut usize,
unplaced_diagram_bodies: &'a mut usize,
}
+impl ShapeCtx<'_, '_> {
+ /// Add one body's commands to the slide, wrapped in the bracket that
+ /// places them.
+ ///
+ /// `commands` stay in the body-local space `layout_shape_body` emitted
+ /// them in — the same values that go on to become [`TextItem`]s — so the
+ /// 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>) {
+ self.commands
+ .push(DrawCommand::Transform(TransformMark::Begin(placement)));
+ self.commands.extend(commands);
+ self.commands
+ .push(DrawCommand::Transform(TransformMark::End));
+ }
+}
+
fn layout_shape(shape: &Shape, ctx: &mut ShapeCtx<'_, '_>) {
match &shape.kind {
ShapeKind::AutoShape(sp) => {
@@ -306,6 +349,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 items = commands_to_items(commands, extent, ctx);
let first_item = ctx.items.len();
frame.push_items(items, (0.0, 0.0), ctx.items);
@@ -363,6 +407,11 @@ struct Frame {
centre: (f32, f32),
/// Clockwise degrees, as the file declares them.
rot_deg: f32,
+ /// The same angle unconverted, for the draw-command bracket — which takes
+ /// 60000ths of a degree, exactly as `a:xfrm@rot` states them.
+ rotation: liteparse_ooxml::model::dimension::Dimension<
+ liteparse_ooxml::model::dimension::SixtieThousandthDeg,
+ >,
}
impl Frame {
@@ -376,6 +425,47 @@ impl Frame {
// OOXML `@rot` is clockwise-positive; `TextItem::rotation` is
// counter-clockwise degrees.
rot_deg: slide_rect.rotation.raw() as f32 / ANGLE_UNITS_PER_DEGREE,
+ rotation: slide_rect.rotation,
+ }
+ }
+
+ /// The placement bracket for a box of size `extent` whose top-left sits at
+ /// `offset` within this frame.
+ ///
+ /// A rotation about the *frame's* centre is not a rotation about the
+ /// box's, and a table is where the difference shows: every cell turns with
+ /// the table, so charging each one its own centre would fan them apart.
+ /// A rigid motion decomposes, though — rotate the box about its own centre
+ /// by the frame's angle, then put that centre where the frame's rotation
+ /// sends it — and the second half is all this computes. For a shape,
+ /// `offset` is `(0, 0)` and the two centres coincide, so it reduces to the
+ /// frame origin.
+ ///
+ /// **Flips are deliberately not carried.** `a:xfrm@flipH/@flipV` mirror a
+ /// shape's *geometry*; PowerPoint does not mirror the text inside it, and
+ /// the item path ignores them for the same reason.
+ fn place(&self, offset: (f32, f32), extent: PtSize) -> ShapeTransform {
+ let (half_w, half_h) = (extent.width.raw() * 0.5, extent.height.raw() * 0.5);
+ let (cx, cy) = (offset.0 + half_w, offset.1 + half_h);
+ let (rx, ry) = if self.rot_deg == 0.0 {
+ (cx, cy)
+ } else {
+ let (sin, cos) = self.rot_deg.to_radians().sin_cos();
+ let (dx, dy) = (cx - self.centre.0, cy - self.centre.1);
+ (
+ self.centre.0 + dx * cos - dy * sin,
+ self.centre.1 + dx * sin + dy * cos,
+ )
+ };
+ ShapeTransform {
+ origin: PtOffset::new(
+ Pt::new(self.origin.0 + rx - half_w),
+ Pt::new(self.origin.1 + ry - half_h),
+ ),
+ rotation: self.rotation,
+ flip_h: false,
+ flip_v: false,
+ extent,
}
}
@@ -526,8 +616,9 @@ fn layout_table(shape: &Shape, table: &pptx::Table, ctx: &mut ShapeCtx<'_, '_>)
if commands.is_empty() {
continue;
}
- let items = commands_to_items(commands, extent, ctx);
let offset = (cell.left.raw(), row_edges[cell.row].raw());
+ 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);
if ctx.items.len() == first_item {
@@ -943,6 +1034,82 @@ mod tests {
assert_eq!(grown_row_heights(&declared, &[cell(7, 1, 99.0)]), declared);
}
+ // ── the placement bracket ────────────────────────────────────────────
+
+ fn frame(x: f32, y: f32, w: f32, h: f32, deg: f32) -> Frame {
+ use liteparse_ooxml::model::geometry::{Offset, Rect, Size};
+ let emu = |pt: f32| Dimension::new((pt * EMU_PER_POINT) as i64);
+ let slide_rect = liteparse_ooxml::pptx::SlideRect {
+ rect: Rect::new(Offset::new(emu(x), emu(y)), Size::new(emu(w), emu(h))),
+ rotation: Dimension::new((deg * ANGLE_UNITS_PER_DEGREE) as i64),
+ flip_h: false,
+ flip_v: false,
+ skewed: false,
+ };
+ Frame::new(slide_rect, size(w, h))
+ }
+
+ fn size(w: f32, h: f32) -> PtSize {
+ PtSize {
+ width: Pt::new(w),
+ height: Pt::new(h),
+ }
+ }
+
+ /// An unrotated shape's bracket is its own rectangle — the commands inside
+ /// it are body-local, so the origin is where the body starts.
+ #[test]
+ fn an_unrotated_shape_brackets_at_its_own_origin() {
+ let placed = frame(100.0, 50.0, 200.0, 80.0, 0.0).place((0.0, 0.0), size(200.0, 80.0));
+ assert_eq!(
+ (placed.origin.x.raw(), placed.origin.y.raw()),
+ (100.0, 50.0)
+ );
+ assert_eq!(placed.rotation.raw(), 0);
+ assert_eq!(placed.extent.width, Pt::new(200.0));
+ }
+
+ /// A rotated shape turns about its own centre, so its origin does not move
+ /// — only the space inside the bracket rotates. Rotating the origin as
+ /// well would slide every rotated body off its shape.
+ #[test]
+ fn a_rotated_shape_keeps_its_origin() {
+ let placed = frame(100.0, 50.0, 200.0, 80.0, 90.0).place((0.0, 0.0), size(200.0, 80.0));
+ assert_eq!(
+ (placed.origin.x.raw(), placed.origin.y.raw()),
+ (100.0, 50.0)
+ );
+ assert_eq!(placed.rotation.raw(), 5_400_000, "the bracket carries @rot");
+ }
+
+ /// A cell turns with its **table**: its centre lands where the frame's
+ /// rotation sends it. Charging each cell its own centre would leave every
+ /// cell in place and fan the table apart instead of turning it.
+ #[test]
+ fn a_cell_rotates_about_the_frame_centre_not_its_own() {
+ // A 40x20 cell in the top-left of a 200x80 frame: centre (20, 10)
+ // against the frame's (100, 40). A quarter turn sends the offset
+ // (-80, -30) to (30, -80), so the cell's centre lands at (130, -40)
+ // and its box origin half a cell up and left of that.
+ let placed = frame(0.0, 0.0, 200.0, 80.0, 90.0).place((0.0, 0.0), size(40.0, 20.0));
+ assert_eq!(
+ (placed.origin.x.raw(), placed.origin.y.raw()),
+ (110.0, -50.0)
+ );
+
+ // Unrotated, the same cell is simply at its offset in the frame.
+ let flat = frame(0.0, 0.0, 200.0, 80.0, 0.0).place((5.0, 7.0), size(40.0, 20.0));
+ assert_eq!((flat.origin.x.raw(), flat.origin.y.raw()), (5.0, 7.0));
+ }
+
+ /// §20.1.7.6 flips mirror a shape's *geometry*; PowerPoint does not mirror
+ /// the text inside it, and the item path ignores them for the same reason.
+ #[test]
+ fn a_bracket_never_carries_a_flip() {
+ let placed = frame(0.0, 0.0, 10.0, 10.0, 0.0).place((0.0, 0.0), size(10.0, 10.0));
+ assert!(!placed.flip_h && !placed.flip_v);
+ }
+
#[test]
fn union_bounds_spans_every_item() {
let item = |x: f32, y: f32, w: f32, h: f32| TextItem {