Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewich7af7082b6a69
diff --git a/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs b/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
index 6b5b2a1..564fe17 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
@@ -181,6 +181,9 @@ impl RPrXml {
underline: self.u.and_then(resolve_underline),
strike: resolve_strike(self.strike, self.dstrike),
color: self.color.and_then(|c| c.val).map(Into::into),
+ // WordprocessingML has no `a:solidFill` on `w:rPr`; DrawingML text
+ // sets this instead of `color`.
+ drawing_color: None,
highlight: self.highlight.map(Into::into),
shading: self.shd.map(Into::into),
vertical_align: self.vert_align.map(Into::into),
diff --git a/crates/liteparse-ooxml/src/model/types/drawing_color.rs b/crates/liteparse-ooxml/src/model/types/drawing_color.rs
index 2628136..c089dd0 100644
--- a/crates/liteparse-ooxml/src/model/types/drawing_color.rs
+++ b/crates/liteparse-ooxml/src/model/types/drawing_color.rs
@@ -169,6 +169,86 @@ pub enum SchemeColorVal {
Lt2,
}
+// ── CT_ColorMapping (§19.3.1.6) ─────────────────────────────────────────────
+
+/// §19.3.1.6 `p:clrMap` — a slide master's mapping from the *host* slot names
+/// (`bg1`/`tx1`/…) onto the theme's own slots (`dk1`/`lt1`/…).
+///
+/// This is the PresentationML answer to the question
+/// [`crate::render::resolve::drawing_color::BgTxConvention`] answers for Word:
+/// what does `<a:schemeClr val="tx1"/>` actually point at? Word infers it from
+/// an assumed background brightness (§17.3.1.31); PowerPoint states it, per
+/// master, and a master is free to state the swapped form — which is how a
+/// dark-backgrounded design keeps `tx1` meaning "readable text".
+///
+/// On the 45-deck corpus, 30 of 70 slide masters declare a non-identity map
+/// (all of them swapping `bg2`/`tx2`; exactly one also swaps `bg1`/`tx1`), so
+/// inferring instead of reading is a wrong colour on 22 of 45 decks, not a
+/// missing one — the failure mode that renders as confidently-legible text in
+/// the wrong hue rather than as an obvious gap.
+///
+/// The four theme-side names (`dk1`/`lt1`/`dk2`/`lt2`) are *not* mapped: they
+/// already name the scheme directly and §19.3.1.6 has no slot for them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ColorMap {
+ pub bg1: SchemeColorVal,
+ pub tx1: SchemeColorVal,
+ pub bg2: SchemeColorVal,
+ pub tx2: SchemeColorVal,
+ pub accent1: SchemeColorVal,
+ pub accent2: SchemeColorVal,
+ pub accent3: SchemeColorVal,
+ pub accent4: SchemeColorVal,
+ pub accent5: SchemeColorVal,
+ pub accent6: SchemeColorVal,
+ pub hlink: SchemeColorVal,
+ pub folink: SchemeColorVal,
+}
+
+impl Default for ColorMap {
+ /// The mapping a master gets when it declares no `p:clrMap`, which is also
+ /// the one 40 of the corpus's 70 masters declare explicitly.
+ fn default() -> Self {
+ Self {
+ bg1: SchemeColorVal::Lt1,
+ tx1: SchemeColorVal::Dk1,
+ bg2: SchemeColorVal::Lt2,
+ tx2: SchemeColorVal::Dk2,
+ accent1: SchemeColorVal::Accent1,
+ accent2: SchemeColorVal::Accent2,
+ accent3: SchemeColorVal::Accent3,
+ accent4: SchemeColorVal::Accent4,
+ accent5: SchemeColorVal::Accent5,
+ accent6: SchemeColorVal::Accent6,
+ hlink: SchemeColorVal::Hlink,
+ folink: SchemeColorVal::FolHlink,
+ }
+ }
+}
+
+impl ColorMap {
+ /// Apply the mapping. Names with no slot in `p:clrMap` — the theme-side
+ /// four and `phClr` — pass through untouched, which is what makes this
+ /// safe to apply unconditionally at the head of scheme resolution.
+ pub fn map(self, name: SchemeColorVal) -> SchemeColorVal {
+ match name {
+ SchemeColorVal::Bg1 => self.bg1,
+ SchemeColorVal::Tx1 => self.tx1,
+ SchemeColorVal::Bg2 => self.bg2,
+ SchemeColorVal::Tx2 => self.tx2,
+ SchemeColorVal::Accent1 => self.accent1,
+ SchemeColorVal::Accent2 => self.accent2,
+ SchemeColorVal::Accent3 => self.accent3,
+ SchemeColorVal::Accent4 => self.accent4,
+ SchemeColorVal::Accent5 => self.accent5,
+ SchemeColorVal::Accent6 => self.accent6,
+ SchemeColorVal::Hlink => self.hlink,
+ SchemeColorVal::FolHlink => self.folink,
+ other => other,
+ }
+ }
+}
+
// ── ST_SystemColorVal (§20.1.10.57) ─────────────────────────────────────────
/// §20.1.10.57 ST_SystemColorVal — OS-defined color name.
diff --git a/crates/liteparse-ooxml/src/model/types/run_properties.rs b/crates/liteparse-ooxml/src/model/types/run_properties.rs
index e8fc885..9d45372 100644
--- a/crates/liteparse-ooxml/src/model/types/run_properties.rs
+++ b/crates/liteparse-ooxml/src/model/types/run_properties.rs
@@ -3,6 +3,7 @@
use crate::model::dimension::{Dimension, HalfPoints, Twips};
use super::color::Color;
+use super::drawing_color::DrawingColor;
use super::formatting::{Border, Shading};
/// Run properties — only fields explicitly present in the XML are `Some`.
@@ -15,6 +16,18 @@ pub struct RunProperties {
pub underline: Option<UnderlineStyle>,
pub strike: Option<StrikeStyle>,
pub color: Option<Color>,
+ /// §21.1.2.3.9 `a:rPr/a:solidFill` — DrawingML's text colour, which
+ /// `color` cannot express: [`Color`] is `Rgb | Auto`, while a run in a
+ /// slide is most often a *scheme* reference carrying transforms
+ /// (`<a:schemeClr val="tx1"><a:lumMod val="65000"/></a:schemeClr>`).
+ /// Resolving it needs the theme and the master's colour map, neither of
+ /// which the parser has, so the reference is carried unresolved and the
+ /// consumer resolves it — see `office::pptx_layout::collect_run_fragments`.
+ ///
+ /// Word never sets this; DrawingML never sets `color`. They are separate
+ /// fields rather than one because both must survive the same cascade and
+ /// neither can be lowered into the other without losing information.
+ pub drawing_color: Option<DrawingColor>,
pub highlight: Option<HighlightColor>,
pub shading: Option<Shading>,
pub vertical_align: Option<VerticalAlign>,
diff --git a/crates/liteparse-ooxml/src/pptx/cascade.rs b/crates/liteparse-ooxml/src/pptx/cascade.rs
index deeb44d..08ddc63 100644
--- a/crates/liteparse-ooxml/src/pptx/cascade.rs
+++ b/crates/liteparse-ooxml/src/pptx/cascade.rs
@@ -69,7 +69,7 @@
use std::collections::HashMap;
-use crate::model::{Theme, Transform2D};
+use crate::model::{ColorMap, 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};
@@ -308,8 +308,15 @@ pub fn resolve_background<'a>(
/// 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);
+/// `color_map` is the slide's effective §19.3.1.6 map, without which a
+/// `<a:schemeClr val="bg1"/>` backdrop under a swapped master resolves to the
+/// wrong end of the theme's light/dark pair.
+pub fn background_fill(
+ bg: &Background,
+ theme: Option<&Theme>,
+ color_map: Option<ColorMap>,
+) -> ResolvedFill {
+ let ctx = DrawingColorContext::new(theme).with_color_map(color_map);
match bg {
Background::Properties(fill) => resolve_fill(fill, &ctx),
Background::Reference(r) => resolve_background_fill(r, theme, &ctx),
@@ -584,7 +591,7 @@ mod tests {
] {
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);
+ assert_eq!(solid_rgb(&background_fill(bg, None, None)), want_rgb);
}
}
@@ -616,14 +623,20 @@ mod tests {
idx: 1001,
color: None,
});
- assert_eq!(solid_rgb(&background_fill(&bg, Some(&theme))), 0x00AA00);
+ assert_eq!(
+ solid_rgb(&background_fill(&bg, Some(&theme), None)),
+ 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);
+ assert_eq!(
+ solid_rgb(&background_fill(&bg2, Some(&theme), None)),
+ 0x00BB00
+ );
// Below 1001 the shape matrix is correct — the spec allows both forms
// even though the corpus only ever writes the offset one.
@@ -631,7 +644,10 @@ mod tests {
idx: 2,
color: None,
});
- assert_eq!(solid_rgb(&background_fill(&bg3, Some(&theme))), 0xBB0000);
+ assert_eq!(
+ solid_rgb(&background_fill(&bg3, Some(&theme), None)),
+ 0xBB0000
+ );
}
/// `idx=0` is §20.1.4.2.19's no-reference sentinel: no background, as
@@ -643,7 +659,7 @@ mod tests {
color: None,
});
assert!(matches!(
- background_fill(&bg, Some(&Theme::default())),
+ background_fill(&bg, Some(&Theme::default()), None),
ResolvedFill::None
));
}
@@ -661,7 +677,7 @@ mod tests {
color: None,
});
assert!(matches!(
- background_fill(&bg, Some(&theme)),
+ background_fill(&bg, Some(&theme), None),
ResolvedFill::None
));
}
diff --git a/crates/liteparse-ooxml/src/pptx/shapes.rs b/crates/liteparse-ooxml/src/pptx/shapes.rs
index 5d901b9..0d926b3 100644
--- a/crates/liteparse-ooxml/src/pptx/shapes.rs
+++ b/crates/liteparse-ooxml/src/pptx/shapes.rs
@@ -47,11 +47,12 @@ use serde::Deserialize;
use crate::model::dimension::{Dimension, Emu};
use crate::model::geometry::{Offset, Size};
use crate::model::{
- BodyProperties, DocProperties, DrawingFill, NvPicProperties, Picture, ShapeProperties,
- StyleMatrixRef, TextAnchoringType, TextVerticalType, Transform2D,
+ BodyProperties, ColorMap, DocProperties, DrawingFill, NvPicProperties, Picture,
+ ShapeProperties, StyleMatrixRef, TextAnchoringType, TextVerticalType, Transform2D,
};
use crate::docx::error::Result;
+use crate::docx::parse::drawing::schema::color::StSchemeColorVal;
use crate::docx::parse::drawing::schema::fill::BlipFillXml;
use crate::docx::parse::drawing::schema::picture::{CNvPicPrXml, CNvPrXml};
use crate::docx::parse::drawing::schema::shape::{
@@ -504,14 +505,30 @@ pub struct SlidePart {
/// Only 58 of the corpus's 1,278 slides declare their own; 1,125 inherit
/// from the master.
pub background: Option<Background>,
+ /// §19.3.1.6 `p:clrMap` (master) or §19.3.1.7 `p:clrMapOvr`'s
+ /// `a:overrideClrMapping` (slide/layout), when *this* part states one.
+ ///
+ /// `None` means "not stated here" and inherits, exactly like `background`
+ /// — and a `p:clrMapOvr` holding `a:masterClrMapping` is a `None`, because
+ /// that element's entire content is "inherit".
+ pub color_map: Option<ColorMap>,
}
/// 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)?;
+ // The colour map is a sibling of `p:cSld`, not a child, so it survives a
+ // part with no shape tree at all.
+ let color_map = part
+ .clr_map
+ .or_else(|| part.clr_map_ovr.and_then(|o| o.override_clr_mapping))
+ .map(ClrMapXml::into_color_map);
let Some(c_sld) = part.c_sld else {
- return Ok(SlidePart::default());
+ return Ok(SlidePart {
+ color_map,
+ ..Default::default()
+ });
};
Ok(SlidePart {
shapes: c_sld
@@ -519,6 +536,7 @@ pub fn parse_slide_part(data: &[u8]) -> Result<SlidePart> {
.map(|t| lower_children(t.children))
.unwrap_or_default(),
background: c_sld.bg.and_then(Background::from_xml),
+ color_map,
})
}
@@ -532,6 +550,122 @@ pub fn parse_slide_part(data: &[u8]) -> Result<SlidePart> {
struct SlidePartXml {
#[serde(rename = "cSld", default)]
c_sld: Option<CSldXml>,
+ /// §19.3.1.6, on `p:sldMaster` only.
+ #[serde(rename = "clrMap", default)]
+ clr_map: Option<ClrMapXml>,
+ /// §19.3.1.7, on `p:sld` and `p:sldLayout` only. Never both, since no
+ /// part's content model allows the two elements together.
+ #[serde(rename = "clrMapOvr", default)]
+ clr_map_ovr: Option<ClrMapOvrXml>,
+}
+
+/// §19.3.1.6 CT_ColorMapping. Every attribute is *required* by the schema, but
+/// each is read as optional and defaulted individually: a master missing one is
+/// malformed, and per §17.17 the honest reading of a missing/invalid value is
+/// the default mapping rather than a rejected deck.
+#[derive(Deserialize)]
+struct ClrMapXml {
+ #[serde(
+ rename = "@bg1",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ bg1: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@tx1",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ tx1: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@bg2",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ bg2: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@tx2",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ tx2: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@accent1",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ accent1: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@accent2",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ accent2: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@accent3",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ accent3: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@accent4",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ accent4: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@accent5",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ accent5: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@accent6",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ accent6: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@hlink",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ hlink: Option<StSchemeColorVal>,
+ #[serde(
+ rename = "@folHlink",
+ default,
+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
+ )]
+ fol_hlink: Option<StSchemeColorVal>,
+}
+
+impl ClrMapXml {
+ fn into_color_map(self) -> ColorMap {
+ let d = ColorMap::default();
+ ColorMap {
+ bg1: self.bg1.map_or(d.bg1, Into::into),
+ tx1: self.tx1.map_or(d.tx1, Into::into),
+ bg2: self.bg2.map_or(d.bg2, Into::into),
+ tx2: self.tx2.map_or(d.tx2, Into::into),
+ accent1: self.accent1.map_or(d.accent1, Into::into),
+ accent2: self.accent2.map_or(d.accent2, Into::into),
+ accent3: self.accent3.map_or(d.accent3, Into::into),
+ accent4: self.accent4.map_or(d.accent4, Into::into),
+ accent5: self.accent5.map_or(d.accent5, Into::into),
+ accent6: self.accent6.map_or(d.accent6, Into::into),
+ hlink: self.hlink.map_or(d.hlink, Into::into),
+ folink: self.fol_hlink.map_or(d.folink, Into::into),
+ }
+ }
+}
+
+/// §19.3.1.7 CT_ColorMappingOverride — a choice of `a:masterClrMapping`
+/// (inherit, and the only form the corpus's 41 overrides actually use) and
+/// `a:overrideClrMapping` (a full CT_ColorMapping stated locally).
+#[derive(Deserialize)]
+struct ClrMapOvrXml {
+ #[serde(rename = "overrideClrMapping", default)]
+ override_clr_mapping: Option<ClrMapXml>,
}
#[derive(Deserialize)]
@@ -1245,6 +1379,7 @@ fn lower_table(tbl: TblXml) -> Table {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::model::SchemeColorVal;
/// Wraps a shape-tree fragment in a namespace-declaring slide part, which
/// is what `parse_shape_tree` expects — prefixes must resolve in the
@@ -1265,6 +1400,58 @@ mod tests {
parse_shape_tree(xml.as_bytes()).expect("parses")
}
+ /// A whole part (not just a shape tree), for the elements that hang off
+ /// `p:sldMaster`/`p:sld` rather than off `p:cSld`.
+ fn part(inner: &str) -> SlidePart {
+ let xml = format!(
+ r#"<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
+ xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
+ <p:cSld><p:spTree/></p:cSld>
+ {inner}
+ </p:sldMaster>"#
+ );
+ parse_slide_part(xml.as_bytes()).expect("parses")
+ }
+
+ /// The mapping 30 of the corpus's 70 masters state: `bg2`/`tx2` swapped,
+ /// which is the whole reason this element cannot be inferred.
+ #[test]
+ fn swapped_clr_map_is_read() {
+ let p = part(
+ r#"<p:clrMap bg1="lt1" tx1="dk1" bg2="dk2" tx2="lt2" accent1="accent1"
+ accent2="accent2" accent3="accent3" accent4="accent4"
+ accent5="accent5" accent6="accent6" hlink="hlink"
+ folHlink="folHlink"/>"#,
+ );
+ let map = p.color_map.expect("stated");
+ assert_eq!(map.tx2, SchemeColorVal::Lt2);
+ assert_eq!(map.bg2, SchemeColorVal::Dk2);
+ // Untouched slots still map the default way.
+ assert_eq!(map.tx1, SchemeColorVal::Dk1);
+ }
+
+ /// `a:masterClrMapping` *is* "inherit", so it must parse to `None` — a
+ /// default map here would shadow the master's real one on all 2,053
+ /// corpus slides that carry the element.
+ #[test]
+ fn master_clr_mapping_override_is_inherit_not_default() {
+ let p = part(r#"<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>"#);
+ assert_eq!(p.color_map, None);
+ }
+
+ #[test]
+ fn override_clr_mapping_states_a_map() {
+ let p = part(
+ r#"<p:clrMapOvr><a:overrideClrMapping bg1="dk1" tx1="lt1" bg2="lt2" tx2="dk2"
+ accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4"
+ accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>
+ </p:clrMapOvr>"#,
+ );
+ let map = p.color_map.expect("stated");
+ assert_eq!(map.tx1, SchemeColorVal::Lt1);
+ assert_eq!(map.bg1, SchemeColorVal::Dk1);
+ }
+
fn sp(inner: &str) -> String {
format!(
r#"<p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>
diff --git a/crates/liteparse-ooxml/src/pptx/text.rs b/crates/liteparse-ooxml/src/pptx/text.rs
index 2338357..2d43437 100644
--- a/crates/liteparse-ooxml/src/pptx/text.rs
+++ b/crates/liteparse-ooxml/src/pptx/text.rs
@@ -37,11 +37,13 @@ use serde::Deserialize;
use crate::model::dimension::{Dimension, Emu, HundredthPoints, ThousandthPercent};
use crate::model::{
- Alignment, BodyProperties, BreakKind, Color, FontSlot, Hyperlink, HyperlinkTarget, Inline,
- RelId, RunElement, RunProperties, StrikeStyle, TextRun, ThemeFontRef, UnderlineStyle,
+ Alignment, BodyProperties, BreakKind, FontSlot, Hyperlink, HyperlinkTarget, Inline, RelId,
+ RunElement, RunProperties, StrikeStyle, TextRun, ThemeFontRef, UnderlineStyle,
};
use crate::docx::error::Result;
+use crate::docx::parse::drawing::schema::color::to_drawing_color;
+use crate::docx::parse::drawing::schema::fill::SolidFillXml;
use crate::docx::parse::drawing::schema::shape::BodyPrXml;
use crate::docx::parse::serde_xml;
@@ -944,6 +946,10 @@ struct TextCharPropertiesXml {
deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"
)]
baseline: Option<Dimension<ThousandthPercent>>,
+ /// §21.1.2.3.9. The DOCX schema's `solidFill` is the same §20.1.8.54
+ /// element with the same `EG_ColorChoice` child, so it is shared rather
+ /// than re-declared — the srgb-only local copy this replaces silently
+ /// dropped the 3,437 corpus runs whose colour is a scheme reference.
#[serde(rename = "solidFill", default)]
solid_fill: Option<SolidFillXml>,
#[serde(rename = "latin", default)]
@@ -964,7 +970,12 @@ impl TextCharPropertiesXml {
italic: self.i,
underline: self.u.map(Into::into),
strike: self.strike.map(Into::into),
- color: self.solid_fill.and_then(SolidFillXml::into_color),
+ // Unresolved on purpose: a scheme reference needs the theme *and*
+ // the master's `p:clrMap`, which live at the slide, not here.
+ drawing_color: self
+ .solid_fill
+ .and_then(|f| f.color)
+ .and_then(to_drawing_color),
// `@spc` is hundredths of a point; `w:spacing` is twips.
spacing: self.spc.map(|s| Dimension::new((s.raw() * 20) / 100)),
kerning: self.kern.map(|k| k.to_half_points()),
@@ -1092,31 +1103,6 @@ impl TextFontXml {
}
}
-/// A `solidFill` carrying either a literal sRGB value or a theme colour.
-///
-/// Theme colours are **not** resolved here: `a:schemeClr` needs the theme's
-/// colour map plus any `phClr` substitution, which the cascade supplies.
-/// Returning `None` for them means "inherit", which is the safe reading —
-/// inventing black would be the silent corruption ATTRIBUTION.md warns about.
-#[derive(Debug, Deserialize, Default)]
-struct SolidFillXml {
- #[serde(rename = "srgbClr", default)]
- srgb_clr: Option<SrgbClrXml>,
-}
-
-impl SolidFillXml {
- fn into_color(self) -> Option<Color> {
- let raw = self.srgb_clr?.val?;
- u32::from_str_radix(raw.trim(), 16).ok().map(Color::Rgb)
- }
-}
-
-#[derive(Debug, Deserialize, Default)]
-struct SrgbClrXml {
- #[serde(rename = "@val", default)]
- val: Option<String>,
-}
-
/// §20.1.10.82 ST_TextUnderlineType — a large enum of which the corpus uses a
/// handful. Unlisted values fall through `lenient::opt_attr` to `None`
/// (= inherit), per ECMA-376 §17.17.
@@ -1400,14 +1386,34 @@ mod tests {
assert_eq!(b.paragraphs[0].text(), "one two");
}
- /// A theme colour needs the colour map and any `phClr` substitution, so
- /// it stays unresolved. Inventing black here would be silent corruption.
+ /// A theme colour is *carried*, not resolved: `schemeClr` needs the theme
+ /// and the master's `p:clrMap`, neither of which is a property of the run.
+ /// It used to be dropped here, which read downstream as "no colour
+ /// declared" and painted 3,437 corpus runs black.
#[test]
- fn scheme_color_stays_unresolved_rather_than_defaulting_to_black() {
+ fn scheme_color_is_carried_unresolved() {
let b = body(
r#"<a:p><a:r><a:rPr><a:solidFill><a:schemeClr val="tx1"/></a:solidFill></a:rPr><a:t>x</a:t></a:r></a:p>"#,
);
- assert_eq!(run_props(&b, 0, 0).color, None);
+ assert!(matches!(
+ run_props(&b, 0, 0).drawing_color,
+ Some(crate::model::DrawingColor::Scheme {
+ name: crate::model::SchemeColorVal::Tx1,
+ ..
+ })
+ ));
+ }
+
+ /// The transforms are the reason a `Color` could not carry this: a tinted
+ /// scheme reference is a colour *expression*, not a value.
+ #[test]
+ fn scheme_color_keeps_its_transforms() {
+ let b = body(
+ r#"<a:p><a:r><a:rPr><a:solidFill><a:schemeClr val="accent1"><a:lumMod val="65000"/></a:schemeClr></a:solidFill></a:rPr><a:t>x</a:t></a:r></a:p>"#,
+ );
+ let props = run_props(&b, 0, 0);
+ let color = props.drawing_color.as_ref().expect("colour");
+ assert_eq!(color.transforms().len(), 1);
}
#[test]
@@ -1415,7 +1421,20 @@ mod tests {
let b = body(
r#"<a:p><a:r><a:rPr><a:solidFill><a:srgbClr val="FF6600"/></a:solidFill></a:rPr><a:t>x</a:t></a:r></a:p>"#,
);
- assert_eq!(run_props(&b, 0, 0).color, Some(Color::Rgb(0xFF6600)));
+ assert!(matches!(
+ run_props(&b, 0, 0).drawing_color,
+ Some(crate::model::DrawingColor::Srgb { rgb: 0xFF6600, .. })
+ ));
+ }
+
+ /// `w:rPr`'s colour field stays Word's. Setting both would give the
+ /// cascade two sources of truth for one property.
+ #[test]
+ fn drawingml_does_not_populate_the_word_color_field() {
+ let b = body(
+ r#"<a:p><a:r><a:rPr><a:solidFill><a:srgbClr val="FF6600"/></a:solidFill></a:rPr><a:t>x</a:t></a:r></a:p>"#,
+ );
+ assert_eq!(run_props(&b, 0, 0).color, None);
}
/// `cap="none"` is an explicit off, which the cascade must be able to
diff --git a/crates/liteparse-ooxml/src/render/layout/build/floating.rs b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
index 9336c33..4952dfc 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/floating.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
@@ -244,7 +244,11 @@ pub(super) fn extract_floating_shapes(
wsp.style_line_ref.as_ref(),
wsp.style_effect_ref.as_ref(),
wsp.style_fill_ref.as_ref(),
- ctx.resolved.theme.as_ref(),
+ // Word has no `p:clrMap`; scheme names keep resolving through
+ // `BgTxConvention`.
+ &crate::render::resolve::drawing_color::DrawingColorContext::new(
+ ctx.resolved.theme.as_ref(),
+ ),
);
// §20.1.7.6 transform attributes (rotation/flip) live on the shape's
diff --git a/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs b/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs
index aad282d..4e18aca 100644
--- a/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/drawing_color.rs
@@ -28,7 +28,7 @@
//! Alpha transforms act on the alpha channel only (§20.1.2.3.1/2/3).
use crate::model::dimension::{Dimension, SixtieThousandthDeg, ThousandthPercent};
-use crate::model::{ColorTransform, DrawingColor, SchemeColorVal, Theme};
+use crate::model::{ColorMap, ColorTransform, DrawingColor, SchemeColorVal, Theme};
/// RGBA with per-channel `f32` in `[0, 1]`.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -90,6 +90,9 @@ pub struct DrawingColorContext<'a> {
/// style-matrix fill referenced via `<a:fillRef>`. `None` outside that
/// context (body `phClr` has no concrete color and falls back to black).
pub placeholder: Option<Rgba>,
+ /// §19.3.1.6: the slide's effective `p:clrMap`. `None` for Word, which has
+ /// no such element and falls back to `bg_tx_convention`'s guess.
+ pub color_map: Option<ColorMap>,
}
impl<'a> DrawingColorContext<'a> {
@@ -98,6 +101,15 @@ impl<'a> DrawingColorContext<'a> {
theme,
bg_tx_convention: BgTxConvention::LightBackground,
placeholder: None,
+ color_map: None,
+ }
+ }
+
+ /// Return a copy of this context with a PresentationML colour map installed.
+ pub fn with_color_map(self, map: Option<ColorMap>) -> Self {
+ Self {
+ color_map: map,
+ ..self
}
}
@@ -149,6 +161,15 @@ fn resolve_scheme(name: SchemeColorVal, ctx: &DrawingColorContext<'_>) -> Rgba {
Some(t) => t,
None => return Rgba::BLACK,
};
+ // §19.3.1.6: when the host *states* the mapping, it replaces the guess.
+ // `ColorMap::map` passes `dk1`/`lt1`/`dk2`/`lt2` and `phClr` through, so
+ // the arms below still see every name they saw before — a mapped `tx1`
+ // simply arrives as the `Dk1` (or `Lt1`) it resolves to, and the
+ // `BgTxConvention` arms become unreachable rather than wrong.
+ let name = match ctx.color_map {
+ Some(map) => map.map(name),
+ None => name,
+ };
let scheme = &theme.color_scheme;
let rgb = match (name, ctx.bg_tx_convention) {
(SchemeColorVal::Dk1, _) => scheme.dark1,
@@ -444,6 +465,7 @@ mod tests {
theme: None,
bg_tx_convention: BgTxConvention::LightBackground,
placeholder: None,
+ color_map: None,
}
}
@@ -452,6 +474,7 @@ mod tests {
theme: Some(theme),
bg_tx_convention: BgTxConvention::LightBackground,
placeholder: None,
+ color_map: None,
}
}
@@ -525,6 +548,39 @@ mod tests {
assert_eq!(r.to_rgb24(), 0xFFFFFF);
}
+ /// A stated `p:clrMap` beats the inferred Word convention. Without this,
+ /// a dark-backgrounded master's `tx1` title resolves to the theme's *dark*
+ /// colour and paints black on black.
+ #[test]
+ fn color_map_overrides_the_bg_tx_convention() {
+ let theme = sample_theme();
+ let ctx = DrawingColorContext::new(Some(&theme)).with_color_map(Some(ColorMap {
+ tx1: SchemeColorVal::Lt1,
+ bg1: SchemeColorVal::Dk1,
+ ..ColorMap::default()
+ }));
+ let c = resolve_drawing_color(
+ &DrawingColor::Scheme {
+ name: SchemeColorVal::Tx1,
+ transforms: Vec::new(),
+ },
+ &ctx,
+ );
+ assert_eq!(c.to_rgb24(), theme.color_scheme.light1);
+ }
+
+ /// The map must not touch the theme-side names — §19.3.1.6 has no slot for
+ /// them, and rewriting one would break every `dk1` in the corpus.
+ #[test]
+ fn color_map_passes_theme_side_names_through() {
+ let map = ColorMap {
+ tx1: SchemeColorVal::Lt1,
+ ..ColorMap::default()
+ };
+ assert_eq!(map.map(SchemeColorVal::Dk1), SchemeColorVal::Dk1);
+ assert_eq!(map.map(SchemeColorVal::PhClr), SchemeColorVal::PhClr);
+ }
+
#[test]
fn scheme_tx1_maps_to_lt1_on_dark_bg() {
let theme = sample_theme();
@@ -532,6 +588,7 @@ mod tests {
theme: Some(&theme),
bg_tx_convention: BgTxConvention::DarkBackground,
placeholder: None,
+ color_map: None,
};
let c = DrawingColor::Scheme {
name: SchemeColorVal::Tx1,
diff --git a/crates/liteparse-ooxml/src/render/resolve/properties.rs b/crates/liteparse-ooxml/src/render/resolve/properties.rs
index 9abb7ac..c1d2627 100644
--- a/crates/liteparse-ooxml/src/render/resolve/properties.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/properties.rs
@@ -34,6 +34,7 @@ pub fn merge_run_properties(target: &mut RunProperties, base: &RunProperties) {
underline,
strike,
color,
+ drawing_color,
highlight,
shading,
vertical_align,
@@ -217,6 +218,10 @@ mod tests {
bold: Some(true),
italic: Some(true),
font_size: Some(Dimension::<HalfPoints>::new(24)),
+ drawing_color: Some(DrawingColor::Srgb {
+ rgb: 0x00FF00,
+ transforms: Vec::new(),
+ }),
color: Some(Color::Rgb(0xFF0000)),
..Default::default()
};
@@ -344,6 +349,10 @@ mod tests {
underline: Some(UnderlineStyle::Single),
strike: Some(StrikeStyle::Single),
color: Some(Color::Rgb(0)),
+ drawing_color: Some(DrawingColor::Srgb {
+ rgb: 0,
+ transforms: Vec::new(),
+ }),
highlight: Some(HighlightColor::Yellow),
shading: Some(Shading {
fill: Color::Rgb(0),
@@ -385,6 +394,7 @@ mod tests {
assert!(target.underline.is_some());
assert!(target.strike.is_some());
assert!(target.color.is_some());
+ assert!(target.drawing_color.is_some());
assert!(target.highlight.is_some());
assert!(target.shading.is_some());
assert!(target.vertical_align.is_some());
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
index fefafc3..6919dba 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
@@ -36,20 +36,25 @@ pub struct ResolvedVisuals {
/// a present-but-empty `<a:effectLst/>` on spPr falls through to the theme
/// effect style. Only when the direct effectLst has children do we treat it
/// as an explicit override.
+///
+/// Takes the whole [`DrawingColorContext`] rather than a bare `theme` because
+/// the theme is no longer the only thing a scheme colour resolves through:
+/// PresentationML states its `bg1`/`tx1` mapping in the master's §19.3.1.6
+/// `p:clrMap`, and a shape fill has to see the same map its text does.
pub fn resolve_shape_visuals(
props: Option<&ShapeProperties>,
style_line_ref: Option<&StyleMatrixRef>,
style_effect_ref: Option<&StyleMatrixRef>,
style_fill_ref: Option<&StyleMatrixRef>,
- theme: Option<&Theme>,
+ ctx: &DrawingColorContext<'_>,
) -> ResolvedVisuals {
- let ctx = DrawingColorContext::new(theme);
+ let theme = ctx.theme;
let props = match props {
Some(p) => p,
None => {
// No spPr, but a bare `<wps:style>` may still carry a fillRef.
return ResolvedVisuals {
- fill: resolve_theme_fill(style_fill_ref, theme, &ctx),
+ fill: resolve_theme_fill(style_fill_ref, theme, ctx),
stroke: None,
effects: Vec::new(),
};
@@ -59,15 +64,15 @@ pub fn resolve_shape_visuals(
// §20.1.4.1.13: a direct spPr fill wins; otherwise fall back to the theme
// fill style referenced by `<a:fillRef>` (recolored by its phClr).
let fill = match props.fill.as_ref() {
- Some(f) => resolve_fill(f, &ctx),
- None => resolve_theme_fill(style_fill_ref, theme, &ctx),
+ Some(f) => resolve_fill(f, ctx),
+ None => resolve_theme_fill(style_fill_ref, theme, ctx),
};
let theme_ln = theme_line_style(style_line_ref, theme);
let stroke = props
.outline
.as_ref()
- .and_then(|o| resolve_outline(o, theme_ln, &ctx));
+ .and_then(|o| resolve_outline(o, theme_ln, ctx));
let direct_effects = props
.effect_list
@@ -75,9 +80,9 @@ pub fn resolve_shape_visuals(
.map(|el| el.effects.as_slice())
.unwrap_or(&[]);
let effects = if !direct_effects.is_empty() {
- resolve_effects(direct_effects, &ctx)
+ resolve_effects(direct_effects, ctx)
} else {
- resolve_theme_effects(style_effect_ref, theme, &ctx)
+ resolve_theme_effects(style_effect_ref, theme, ctx)
};
ResolvedVisuals {
@@ -468,7 +473,7 @@ mod tests {
#[test]
fn empty_props_resolves_to_none_visuals() {
- let v = resolve_shape_visuals(None, None, None, None, None);
+ let v = resolve_shape_visuals(None, None, None, None, &DrawingColorContext::new(None));
assert!(matches!(v.fill, ResolvedFill::None));
assert!(v.stroke.is_none());
assert!(v.effects.is_empty());
@@ -484,7 +489,13 @@ mod tests {
None,
None,
);
- let v = resolve_shape_visuals(Some(&props), None, None, None, None);
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(None),
+ );
let ResolvedFill::Solid(c) = v.fill else {
panic!()
};
@@ -508,7 +519,13 @@ mod tests {
tail_end: None,
};
let props = shape_props(None, Some(outline), None);
- let v = resolve_shape_visuals(Some(&props), None, None, None, None);
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(None),
+ );
let s = v.stroke.unwrap();
assert_eq!(s.width, Pt::new(0.75));
assert_eq!(s.color.to_rgb24(), 0x0000FF);
@@ -534,7 +551,13 @@ mod tests {
tail_end: None,
};
let props = shape_props(None, Some(outline), None);
- let v = resolve_shape_visuals(Some(&props), None, None, None, None);
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(None),
+ );
let s = v.stroke.unwrap();
assert_eq!(s.width, Pt::new(0.75));
assert_eq!(s.color, Rgba::BLACK);
@@ -557,7 +580,13 @@ mod tests {
tail_end: None,
};
let props = shape_props(None, Some(outline), None);
- let v = resolve_shape_visuals(Some(&props), None, None, None, None);
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(None),
+ );
assert!(v.stroke.is_none());
}
@@ -607,7 +636,13 @@ mod tests {
idx: 2,
color: None,
};
- let v = resolve_shape_visuals(Some(&props), Some(&ln_ref), None, None, Some(&theme));
+ let v = resolve_shape_visuals(
+ Some(&props),
+ Some(&ln_ref),
+ None,
+ None,
+ &DrawingColorContext::new(Some(&theme)),
+ );
let s = v.stroke.unwrap();
assert_eq!(s.width, Pt::new(2.0));
assert_eq!(s.color.to_rgb24(), 0xD99F34);
@@ -643,7 +678,13 @@ mod tests {
idx: 1,
color: None,
};
- let v = resolve_shape_visuals(Some(&props), None, Some(&er), None, Some(&theme));
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ Some(&er),
+ None,
+ &DrawingColorContext::new(Some(&theme)),
+ );
assert_eq!(v.effects.len(), 1);
}
@@ -690,7 +731,13 @@ mod tests {
idx: 1,
color: None,
};
- let v = resolve_shape_visuals(Some(&props), None, Some(&er), None, Some(&theme));
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ Some(&er),
+ None,
+ &DrawingColorContext::new(Some(&theme)),
+ );
let ResolvedEffect::OuterShadow {
blur_radius, color, ..
} = &v.effects[0];
@@ -722,7 +769,13 @@ mod tests {
effects: vec![Effect::OuterShdw(sh)],
}),
);
- let v = resolve_shape_visuals(Some(&props), None, None, None, None);
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(None),
+ );
assert_eq!(v.effects.len(), 1);
let ResolvedEffect::OuterShadow {
blur_radius,
@@ -759,7 +812,13 @@ mod tests {
};
// No direct spPr fill → the theme fill referenced by fillRef supplies it.
let props = shape_props(None, None, None);
- let v = resolve_shape_visuals(Some(&props), None, None, Some(&fill_ref), Some(&theme));
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ Some(&fill_ref),
+ &DrawingColorContext::new(Some(&theme)),
+ );
let ResolvedFill::Solid(c) = v.fill else {
panic!("expected solid theme fill, got {:?}", v.fill);
};
@@ -784,7 +843,13 @@ mod tests {
None,
None,
);
- let v = resolve_shape_visuals(Some(&props), None, None, Some(&fill_ref), Some(&theme));
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ Some(&fill_ref),
+ &DrawingColorContext::new(Some(&theme)),
+ );
let ResolvedFill::Solid(c) = v.fill else {
panic!("expected solid fill");
};
@@ -799,7 +864,13 @@ mod tests {
color: None,
};
let props = shape_props(None, None, None);
- let v = resolve_shape_visuals(Some(&props), None, None, Some(&fill_ref), Some(&theme));
+ let v = resolve_shape_visuals(
+ Some(&props),
+ None,
+ None,
+ Some(&fill_ref),
+ &DrawingColorContext::new(Some(&theme)),
+ );
assert!(matches!(v.fill, ResolvedFill::None));
}
}
diff --git a/crates/liteparse/src/office/pptx.rs b/crates/liteparse/src/office/pptx.rs
index 1dd19ed..a07cc34 100644
--- a/crates/liteparse/src/office/pptx.rs
+++ b/crates/liteparse/src/office/pptx.rs
@@ -12,7 +12,7 @@
//! The design below follows that census throughout; where a rule looks
//! arbitrary it is usually a corpus measurement, and the comment says which.
-use liteparse_ooxml::model::{Inline, RunElement, RunProperties, StrikeStyle};
+use liteparse_ooxml::model::{ColorMap, Inline, RunElement, RunProperties, StrikeStyle};
use liteparse_ooxml::pptx::{
self, AutoNumberScheme, Background, BackgroundSource, Bullet, DeckTextDefaults,
GraphicFramePayload, ListStyle, MatchRule, Placeholder, PlaceholderGeometry, PlaceholderKind,
@@ -111,6 +111,11 @@ pub struct Deck {
/// is not the same as "no background": see [`pptx::resolve_background`].
master_bg: HashMap<String, Option<Background>>,
layout_bg: HashMap<String, Option<Background>>,
+ /// §19.3.1.6 `p:clrMap` per master and §19.3.1.7 `p:clrMapOvr` per layout,
+ /// cached beside the background for the same reason. `None` means the part
+ /// states no map of its own.
+ master_clr_map: HashMap<String, Option<ColorMap>>,
+ layout_clr_map: HashMap<String, Option<ColorMap>>,
default_text_style: ListStyle,
/// The rung-7-only defaults a slide falls back to when its master has no
/// entry. Stored on the deck rather than built as a local in the walk so
@@ -142,6 +147,15 @@ pub struct PreparedSlide<'d> {
/// pass does. `None` means no part in the chain declared one, which does
/// not happen on the corpus (0 of 1,278) and is therefore a signal.
pub background: Option<(BackgroundSource, Background)>,
+ /// §19.3.1.6 the colour map in force on this slide, resolved down the same
+ /// slide → layout → master chain as `background`.
+ ///
+ /// `None` means no part in the chain stated one, in which case
+ /// [`ColorMap::default`] — the spec's identity mapping — applies; it is
+ /// carried as `Option` rather than defaulted here so that the probe can
+ /// tell "stated" from "assumed", which is exactly the 30-of-70 masters the
+ /// census found.
+ pub color_map: Option<ColorMap>,
layout_text: Option<&'d PlaceholderTextStyles>,
master_text: Option<&'d PlaceholderTextStyles>,
deck_defaults: &'d DeckTextDefaults,
@@ -174,6 +188,8 @@ impl Deck {
layout_text: HashMap::new(),
master_bg: HashMap::new(),
layout_bg: HashMap::new(),
+ master_clr_map: HashMap::new(),
+ layout_clr_map: HashMap::new(),
fallback_defaults: DeckTextDefaults {
master_styles: TextStyles::default(),
default_text_style: default_text_style.clone(),
@@ -206,6 +222,26 @@ impl Deck {
.and_then(Option::as_ref),
)
.map(|(src, bg)| (src, bg.clone()));
+ // Nearest rung wins, and a `p:clrMapOvr/a:masterClrMapping` parses to
+ // `None`, which is what makes "inherit" fall through correctly here.
+ let color_map = part
+ .color_map
+ .or_else(|| {
+ slide
+ .layout
+ .as_ref()
+ .and_then(|l| self.layout_clr_map.get(&l.path))
+ .copied()
+ .flatten()
+ })
+ .or_else(|| {
+ slide
+ .master
+ .as_ref()
+ .and_then(|m| self.master_clr_map.get(&m.path))
+ .copied()
+ .flatten()
+ });
let layout_geo = slide
.layout
.as_ref()
@@ -222,6 +258,7 @@ impl Deck {
Some(PreparedSlide {
shapes,
background,
+ color_map,
layout_text: slide
.layout
.as_ref()
@@ -272,6 +309,8 @@ impl Deck {
let part = pptx::parse_slide_part(&master.xml).unwrap_or_default();
let shapes = part.shapes;
self.master_bg.insert(master.path.clone(), part.background);
+ self.master_clr_map
+ .insert(master.path.clone(), part.color_map);
self.master_geo.insert(
master.path.clone(),
PlaceholderGeometry::from_master(&shapes),
@@ -298,6 +337,8 @@ impl Deck {
let part = pptx::parse_slide_part(&layout.xml).unwrap_or_default();
let mut shapes = part.shapes;
self.layout_bg.insert(layout.path.clone(), part.background);
+ self.layout_clr_map
+ .insert(layout.path.clone(), part.color_map);
pptx::apply_inherited_geometry(&mut shapes, master_geo, MatchRule::CollapsedKind);
self.layout_geo.insert(
layout.path.clone(),
diff --git a/crates/liteparse/src/office/pptx_layout.rs b/crates/liteparse/src/office/pptx_layout.rs
index 5875e0c..5b7160e 100644
--- a/crates/liteparse/src/office/pptx_layout.rs
+++ b/crates/liteparse/src/office/pptx_layout.rs
@@ -51,7 +51,7 @@
use liteparse_ooxml::model::dimension::Dimension;
use liteparse_ooxml::model::{
- Alignment, DrawingFill, PresetGeometryDef, PresetShapeType, ShapeGeometry, Theme,
+ Alignment, ColorMap, DrawingFill, PresetGeometryDef, PresetShapeType, ShapeGeometry, Theme,
};
use liteparse_ooxml::pptx::{
self, PresentationPackage, ResolvedTextStyle, Shape, ShapeKind, Spacing, TextBody, TextCascade,
@@ -71,7 +71,8 @@ use liteparse_ooxml::render::layout::measurer::TextMeasurer;
use liteparse_ooxml::render::layout::paragraph::{LineSpacingRule, ParagraphStyle};
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::color::{RgbColor, rgb_from_u32};
+use liteparse_ooxml::render::resolve::drawing_color::{DrawingColorContext, resolve_drawing_color};
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;
@@ -171,6 +172,22 @@ pub struct SlideGeometry {
/// background at all. 0 on the corpus, so any number here is a signal
/// about the package rather than a normal outcome.
pub undeclared_backgrounds: usize,
+ /// Runs whose colour came from a declared `a:solidFill` on some rung of
+ /// the text cascade.
+ pub runs_colour_declared: usize,
+ /// Runs with no colour anywhere in the cascade, painted black by §21.1.2.3
+ /// default. The remaining gap here is `p:style/a:fontRef`, which supplies
+ /// a shape-level text colour this pass does not parse — 2,043 of the
+ /// corpus's 2,181 `p:style` elements carry one.
+ pub runs_colour_defaulted: usize,
+ /// Runs whose resolved colour is **exactly the colour of the slide's own
+ /// background**, i.e. text that cannot be read.
+ ///
+ /// The gate this step exists for. It over-counts by design — a run over an
+ /// opaque shape fill is legible whatever the backdrop says — so the number
+ /// is a ceiling on invisibility, and the claim it supports is the
+ /// direction it moved, not its absolute value.
+ pub runs_invisible_on_background: usize,
}
/// Where one text body's items landed on its slide — a shape's, or a single
@@ -258,6 +275,9 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
transparent_backgrounds: 0,
unrenderable_backgrounds: 0,
undeclared_backgrounds: 0,
+ runs_colour_declared: 0,
+ runs_colour_defaulted: 0,
+ runs_invisible_on_background: 0,
};
for (idx, slide) in pkg.slides.iter().enumerate() {
@@ -273,6 +293,7 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
let mut ctx = ShapeCtx {
cascade,
theme,
+ color_map: prepared.color_map,
measurer: &measurer,
registry,
items: &mut items,
@@ -288,6 +309,10 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
transparent_backgrounds: &mut out.transparent_backgrounds,
unrenderable_backgrounds: &mut out.unrenderable_backgrounds,
undeclared_backgrounds: &mut out.undeclared_backgrounds,
+ background_rgb: None,
+ runs_colour_declared: &mut out.runs_colour_declared,
+ runs_colour_defaulted: &mut out.runs_colour_defaulted,
+ runs_invisible_on_background: &mut out.runs_invisible_on_background,
};
// Two walks over one `prepare`, in the order the raster wants
// them. See [`paint_shape`] for why they cannot be one walk. The
@@ -331,6 +356,11 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
struct ShapeCtx<'a, 'r> {
cascade: TextCascade<'a>,
theme: Option<&'a Theme>,
+ /// §19.3.1.6 the slide's effective colour map, resolved by
+ /// [`Deck::prepare`]. Every scheme colour on the slide — run, shape fill,
+ /// outline, background — goes through this one value, which is the point:
+ /// the three paths must not disagree about what `tx1` names.
+ color_map: Option<ColorMap>,
measurer: &'a TextMeasurer<'r>,
registry: &'a FontRegistry,
items: &'a mut Vec<TextItem>,
@@ -348,6 +378,12 @@ struct ShapeCtx<'a, 'r> {
transparent_backgrounds: &'a mut usize,
unrenderable_backgrounds: &'a mut usize,
undeclared_backgrounds: &'a mut usize,
+ /// The slide backdrop's resolved sRGB, filled in by `paint_background`
+ /// before either walk runs. Only the invisible-text count reads it.
+ background_rgb: Option<u32>,
+ runs_colour_declared: &'a mut usize,
+ runs_colour_defaulted: &'a mut usize,
+ runs_invisible_on_background: &'a mut usize,
}
impl ShapeCtx<'_, '_> {
@@ -403,7 +439,7 @@ fn paint_background(
*ctx.undeclared_backgrounds += 1;
return None;
};
- let fill = pptx::background_fill(bg, ctx.theme);
+ let fill = pptx::background_fill(bg, ctx.theme, ctx.color_map);
if matches!(fill, ResolvedFill::None) {
// Two very different slides land here, and the resolved fill cannot
// tell them apart: `resolve_fill` collapses blip, pattern and `grpFill`
@@ -429,6 +465,9 @@ fn paint_background(
page_size,
)?;
*ctx.painted_backgrounds += 1;
+ if let ResolvedFill::Solid(rgba) = fill {
+ ctx.background_rgb = Some(rgba.to_rgb24());
+ }
let at = ctx.commands.len();
ctx.commands.push(DrawCommand::Path {
origin: PtOffset::new(Pt::ZERO, Pt::ZERO),
@@ -490,7 +529,13 @@ fn paint_shape(shape: &Shape, ctx: &mut ShapeCtx<'_, '_>) {
// 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 visuals = resolve_shape_visuals(
+ Some(props),
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(ctx.theme).with_color_map(ctx.color_map),
+ );
let paints = !matches!(visuals.fill, ResolvedFill::None) || visuals.stroke.is_some();
if !paints {
return;
@@ -1044,6 +1089,47 @@ fn paragraph_block(
}
}
+/// §21.1.2.3.9 `a:rPr/a:solidFill` → the sRGB the painter draws with.
+///
+/// The colour arrives here already merged down the whole text cascade — run,
+/// shape `a:lstStyle`, layout/master placeholder, master `p:txStyles`,
+/// presentation `defaultTextStyle` — because `drawing_color` is an ordinary
+/// `Option` field of [`RunProperties`] and rides `merge_run_properties` like
+/// every other one. What could not ride the cascade is the *resolution*: a
+/// `schemeClr` needs this slide's theme and its master's `p:clrMap`, and
+/// neither is a property of the run.
+///
+/// Alpha is dropped: `DrawCommand::Text` carries an opaque `RgbColor`, so a
+/// half-transparent run paints solid. That is a smaller error than the black
+/// it replaces, and it is the same simplification the fill path made.
+///
+/// Black on no declaration is the §21.1.2.3 default, *not* a guess — but the
+/// count still separates the two, because the runs that land here are exactly
+/// the ones `p:style/a:fontRef` would colour.
+fn run_color(
+ props: &liteparse_ooxml::model::RunProperties,
+ ctx: &mut ShapeCtx<'_, '_>,
+) -> RgbColor {
+ let rgb = match props.drawing_color.as_ref() {
+ Some(declared) => {
+ *ctx.runs_colour_declared += 1;
+ let dc = DrawingColorContext::new(ctx.theme).with_color_map(ctx.color_map);
+ resolve_drawing_color(declared, &dc).to_rgb24()
+ }
+ None => {
+ *ctx.runs_colour_defaulted += 1;
+ 0x000000
+ }
+ };
+ // Counted for *both* branches on purpose: a defaulted-black run on a dark
+ // backdrop is the exact failure this step exists to remove, and checking
+ // only the declared branch would report it as fixed.
+ if ctx.background_rgb == Some(rgb) {
+ *ctx.runs_invisible_on_background += 1;
+ }
+ rgb_from_u32(rgb)
+}
+
fn collect_run_fragments(
inlines: &[liteparse_ooxml::model::Inline],
resolved: &ResolvedTextStyle,
@@ -1076,7 +1162,7 @@ fn collect_run_fragments(
spec_default_size(),
auto_fit,
);
- let color = RgbColor { r: 0, g: 0, b: 0 };
+ let color = run_color(&props, ctx);
for element in &run.content {
match element {
RunElement::Text(text) => {