Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewiche9d38593777e
diff --git a/Cargo.lock b/Cargo.lock
index a1dc9a9..4d2817a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2105,7 +2105,6 @@ dependencies = [
"ssf-rs",
"thiserror 2.0.19",
"tiny-skia",
- "unicode-normalization",
"unicode-properties",
"unicode-segmentation",
"zip",
diff --git a/crates/liteparse-ooxml/Cargo.toml b/crates/liteparse-ooxml/Cargo.toml
index 31fadca..d702bd2 100644
--- a/crates/liteparse-ooxml/Cargo.toml
+++ b/crates/liteparse-ooxml/Cargo.toml
@@ -13,24 +13,18 @@ quick-xml = { version = "0.39", features = ["serialize"] }
serde = { version = "1", features = ["derive"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
thiserror = "2"
-# XLSX number formatting (§18.8.31). A faithful port of SheetJS's `ssf`, which
-# is what makes it worth taking as a dependency: the reference implementation is
-# JS, so a port can be diffed against its origin rather than only against a
-# spec reading. Apache-2.0, one transitive dep (`regex`).
+# XLSX number-format rendering (ECMA-376 §18.8.31); a port of SheetJS's `ssf`.
ssf-rs = "0.1"
log = "0.4"
rustc-hash = "2"
-# C′ measurer stack (spikes 6–8): resolution via fontdb, metrics/advances via
-# skrifa. fontdb is pinned to the 0.22 line to match what resvg/usvg already
-# drag into the liteparse tree, so resolution behaviour matches what the spike
-# harness measured.
+# Text measurement: font resolution via fontdb, metrics/advances via skrifa.
+# fontdb is pinned to the 0.22 line resvg/usvg already bring into the tree.
fontdb = "0.22"
skrifa = "0.45"
unicode-segmentation = "1.13"
unicode-properties = "0.1"
-unicode-normalization = "0.1"
# `raster` feature only — pinned to the tiny-skia line resvg 0.44 already
-# drags into the liteparse tree, so the feature adds ~no supply chain.
+# brings into the tree.
tiny-skia = { version = "0.11", optional = true }
image = { version = "0.25", optional = true, default-features = false, features = [
"png",
diff --git a/crates/liteparse-ooxml/examples/layout_probe.rs b/crates/liteparse-ooxml/examples/layout_probe.rs
index 1d3735b..b5d6e65 100644
--- a/crates/liteparse-ooxml/examples/layout_probe.rs
+++ b/crates/liteparse-ooxml/examples/layout_probe.rs
@@ -134,6 +134,7 @@ fn run_one(path: &str) -> serde_json::Value {
// 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,
+ DrawCommand::Float(_) => {}
// No catch-all: the compiler confirming this match is
// exhaustive is how we know the census can't silently miss a
// command class.
diff --git a/crates/liteparse-ooxml/src/docx/parse/body.rs b/crates/liteparse-ooxml/src/docx/parse/body.rs
index 6b261f0..02edd8e 100644
--- a/crates/liteparse-ooxml/src/docx/parse/body.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/body.rs
@@ -48,10 +48,9 @@ struct DocXml {
// ── Conversion ────────────────────────────────────────────────────────────
-/// Conversion context. Previously carried a pre-pass iterator of parsed
-/// drawings/picts; now empty, since drawings and picts are serde-parsed
-/// inline. Kept as a type for future extensibility (e.g., if a later phase
-/// needs cross-node state during conversion).
+/// Conversion context, threaded through the body walk. Currently empty —
+/// drawings and picts are serde-parsed inline — but kept as a type so a
+/// later phase can add cross-node state without changing every call site.
pub(crate) struct ConvertCtx {
_private: (),
}
@@ -620,7 +619,7 @@ mod tests {
#[test]
fn ins_content_is_rendered() {
// Tracked insertions are part of the final document — their runs must
- // survive (previously `<w:ins>` hit the `Other` catch-all and vanished).
+ // survive, not fall into the `Other` catch-all.
assert_eq!(
para_text(r#"<w:p xmlns:w="x"><w:ins><w:r><w:t>kept</w:t></w:r></w:ins></w:p>"#),
"kept"
@@ -788,11 +787,11 @@ mod tests {
);
}
- /// Regression: a `<w:tr>` whose `<w:tc>` cells are interleaved with
- /// cell-level `<w:sdt>` (CT_SdtCell) wrappers must (a) parse — the old
- /// `Vec<TableCellXml>` field reported a duplicate `tc` when cells were
- /// non-contiguous — and (b) recover every cell, including the ones nested
- /// inside `<w:sdtContent>`.
+ /// A `<w:tr>` whose `<w:tc>` cells are interleaved with cell-level
+ /// `<w:sdt>` (CT_SdtCell) wrappers must (a) parse — a plain
+ /// `Vec<TableCellXml>` field would report a duplicate `tc` when cells
+ /// are non-contiguous — and (b) recover every cell, including the ones
+ /// nested inside `<w:sdtContent>`.
#[test]
fn row_with_interspersed_sdt_cells_recovers_all_cells() {
let xml = r#"
@@ -833,8 +832,8 @@ mod tests {
}
/// A `<w:customXml>` row wrapper (CT_CustomXmlRow) inside `<w:tbl>` must
- /// have its nested `<w:tr>` rows recovered — the element is `customXml`,
- /// not `customXmlIns`/etc., so the wrong rename previously dropped them.
+ /// have its nested `<w:tr>` rows recovered — the element name is
+ /// `customXml`, not `customXmlIns`/etc.
#[test]
fn table_with_custom_xml_row_wrapper_recovers_rows() {
let xml = r#"
diff --git a/crates/liteparse-ooxml/src/docx/parse/body_schema.rs b/crates/liteparse-ooxml/src/docx/parse/body_schema.rs
index 742b750..7340ba8 100644
--- a/crates/liteparse-ooxml/src/docx/parse/body_schema.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/body_schema.rs
@@ -726,8 +726,8 @@ mod tests {
#[test]
fn ptab_dispatches_as_run_child() {
- // The whole reason for the fix: `<w:ptab>` must be a recognized run
- // child, not an unknown-variant deserialize error.
+ // `<w:ptab>` must be a recognized run child, not an unknown-variant
+ // deserialize error.
let r: RunXml = quick_xml::de::from_str(
r#"<r><t>a</t><ptab relativeTo="margin" alignment="right" leader="none"/><t>b</t></r>"#,
)
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/anchor.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/anchor.rs
index 4eb234a..d5d58eb 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/anchor.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/anchor.rs
@@ -229,14 +229,24 @@ pub(crate) struct InlineXml {
pub graphic: Option<GraphicXml>,
}
+/// Build the T/R/B/L distance rectangle shared by `distT/B/L/R` attributes.
+fn dist_edge_insets(
+ t: Option<Dimension<Emu>>,
+ b: Option<Dimension<Emu>>,
+ l: Option<Dimension<Emu>>,
+ r: Option<Dimension<Emu>>,
+) -> EdgeInsets<Emu> {
+ EdgeInsets::new(
+ t.unwrap_or_default(),
+ r.unwrap_or_default(),
+ b.unwrap_or_default(),
+ l.unwrap_or_default(),
+ )
+}
+
impl InlineXml {
pub(crate) fn into_image(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> Image {
- let distance = EdgeInsets::new(
- self.dist_t.unwrap_or_default(),
- self.dist_r.unwrap_or_default(),
- self.dist_b.unwrap_or_default(),
- self.dist_l.unwrap_or_default(),
- );
+ let distance = dist_edge_insets(self.dist_t, self.dist_b, self.dist_l, self.dist_r);
Image {
extent: Size::new(self.extent.cx, self.extent.cy),
effect_extent: self.effect_extent.map(Into::into),
@@ -278,11 +288,10 @@ pub(crate) struct AnchorXml {
pub dist_r: Option<Dimension<Emu>>,
#[serde(rename = "@simplePos", default)]
pub simple_pos_attr: Option<AttrBool>,
- // §20.4.2.3 marks these four `use="required"`, but a single nonconformant
- // `<wp:anchor>` (some third-party / hand-edited producers omit them) would
- // otherwise fail deserialization and abort the whole-document parse. Accept
- // them as optional and apply Word's effective defaults at the `into_image`
- // seam — matching `layout_in_cell` / `hidden`, which are already lenient.
+ // §20.4.2.3 marks these four `use="required"`, but a nonconformant
+ // `<wp:anchor>` that omits one would otherwise abort the whole-document
+ // parse. Accept them as optional and apply Word's effective defaults in
+ // `into_image`, matching `layout_in_cell` / `hidden` below.
#[serde(
rename = "@relativeHeight",
default,
@@ -566,12 +575,7 @@ impl From<StWrapText> for WrapText {
impl AnchorXml {
pub(crate) fn into_image(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> Image {
- let distance = EdgeInsets::new(
- self.dist_t.unwrap_or_default(),
- self.dist_r.unwrap_or_default(),
- self.dist_b.unwrap_or_default(),
- self.dist_l.unwrap_or_default(),
- );
+ let distance = dist_edge_insets(self.dist_t, self.dist_b, self.dist_l, self.dist_r);
let simple_pos = self.simple_pos.map(|s| Offset::new(s.x, s.y));
let use_simple_pos = self.simple_pos_attr.map(|b| b.0);
let horizontal_position = position(self.pos_h);
@@ -721,11 +725,9 @@ mod tests {
assert_eq!(effect.b.unwrap().raw(), 48);
}
+ /// A negative extent must not fail the whole document; it degrades to
+ /// zero instead, and the sibling axis stays untouched.
#[test]
- /// Upstream rejected a negative extent, failing the whole document over a
- /// shape's size. We degrade it to zero instead — but the guard it existed
- /// for still holds: a negative extent must never become a real size, and
- /// the sibling axis must survive untouched.
fn negative_decimal_extent_degrades_to_zero() {
let parsed: ExtentXml = quick_xml::de::from_str(r#"<extent cx="-1.5" cy="100"/>"#)
.expect("a negative extent must not fail the parse");
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/color.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/color.rs
index 99dfb2e..34fada4 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/color.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/color.rs
@@ -3,12 +3,8 @@
//! Each color-choice element (`srgbClr`, `scRgbClr`, `hslClr`, `sysClr`,
//! `schemeClr`, `prstClr`) carries attributes for its base color plus an
//! ordered list of color-transform children (`tint`, `shade`, `alpha`, etc.).
-//!
-//! During Phase 5A these schemas are additive — consumers (fill, stroke,
-//! effect) still use the procedural `drawing/color.rs` parser. When those
-//! parsers migrate in Phase 5B+, they will switch to `DrawingColorXml`.
-#![allow(dead_code, clippy::large_enum_variant)]
+#![allow(clippy::large_enum_variant)]
use serde::Deserialize;
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/effect.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/effect.rs
index 8059c52..6e31099 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/effect.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/effect.rs
@@ -3,7 +3,7 @@
//! Flat `<a:effectLst>` with eight child effect types, preserving document
//! order. Consumes `DrawingColorXml` and `DrawingFillXml`.
-#![allow(dead_code, clippy::large_enum_variant)]
+#![allow(clippy::large_enum_variant)]
use serde::Deserialize;
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/fill.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/fill.rs
index a584bfe..6688787 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/fill.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/fill.rs
@@ -4,8 +4,6 @@
//! `grpFill`. Each variant has its own attribute/child grammar. Consumes
//! `DrawingColorXml` from the color schema.
-#![allow(dead_code, clippy::large_enum_variant)]
-
use serde::Deserialize;
use crate::docx::dimension::{Dimension, Emu, SixtieThousandthDeg, ThousandthPercent};
@@ -34,8 +32,8 @@ pub enum DrawingFillXml {
BlipFill(BlipFillXml),
#[serde(rename = "pattFill")]
PattFill(PattFillXml),
- /// Catch-all for unmodelled OOXML elements. Vendoring divergence from
- /// dxpdf: upstream fails the whole document on an unknown element.
+ /// Catch-all for unmodelled fill elements, so an unknown element
+ /// degrades gracefully instead of failing the whole document.
#[serde(other)]
Other,
}
@@ -46,8 +44,7 @@ pub struct Empty {}
impl From<DrawingFillXml> for DrawingFill {
fn from(f: DrawingFillXml) -> Self {
match f {
- // An unmodelled fill element degrades to no fill, matching the
- // existing treatment of an ill-formed solidFill below.
+ // An unmodelled fill element degrades to no fill.
DrawingFillXml::Other => Self::None,
DrawingFillXml::NoFill(_) => Self::None,
DrawingFillXml::GrpFill(_) => Self::Group,
@@ -56,8 +53,7 @@ impl From<DrawingFillXml> for DrawingFill {
Some(c) => Self::Solid(c),
None => Self::None,
},
- // Ill-formed solidFill with no color — degrade to None per
- // legacy parser.
+ // No color present — degrade to None.
None => Self::None,
},
DrawingFillXml::GradFill(g) => Self::Gradient(g.into()),
@@ -233,8 +229,8 @@ impl From<GradFillXml> for GradientFill {
} else if let Some(path) = x.path {
GradientShadeProperties::Path {
// An omitted `@path` still denotes a path (radial-family)
- // gradient; default to `circle`, which is what the shade
- // currently resolves to downstream (Radial).
+ // gradient; default to `circle`, which resolves as Radial
+ // downstream.
path_type: path
.path_type
.map(Into::into)
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/geometry.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/geometry.rs
index 30269f7..4dda273 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/geometry.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/geometry.rs
@@ -5,7 +5,7 @@
//! `AdjCoord` attributes are either decimal integers or guide-name
//! references, resolved by a custom `Deserialize` that tries integer first.
-#![allow(dead_code, clippy::large_enum_variant)]
+#![allow(clippy::large_enum_variant)]
use serde::{Deserialize, Deserializer};
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/mod.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/mod.rs
index 47f1f94..2ce6a6c 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/mod.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/mod.rs
@@ -1,7 +1,5 @@
//! Serde schema types for DrawingML (§20) — one submodule per primitive
-//! family. Schemas are additive during Phase 5: they coexist with the
-//! procedural parsers in `drawing/` and will progressively replace them
-//! as higher-level container parsers are migrated in later sub-phases.
+//! family.
pub mod anchor;
pub mod color;
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 96896ce..14ff0d7 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/shape.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/shape.rs
@@ -561,10 +561,9 @@ pub(crate) struct WspXml {
// ── wps:style (§20.1.4.1.4 CT_ShapeStyle) ─────────────────────────────────
//
-// References into the theme's style matrices. Only `effectRef` is consumed
-// today; the other siblings (`lnRef`, `fillRef`, `fontRef`) are siblings
-// whose schema differs (`fontRef/@idx` is a string enum, not a number), so
-// they're silently skipped via serde's default unknown-element behavior.
+// References into the theme's style matrices (line, fill, effect, font).
+// `fontRef` has a different schema from the other three: `@idx` is a string
+// enum (`ST_FontCollectionIndex`), not a numeric matrix index.
#[derive(Debug, Deserialize, Default)]
pub(crate) struct ShapeStyleXml {
@@ -1170,7 +1169,4 @@ mod tests {
assert_eq!(fr.collection, FontCollectionIndex::Minor);
assert!(fr.color.is_some(), "fontRef text color captured");
}
-
- // ── Picture spPr wiring (now that shape schema exists) ──
- // (We don't re-wire picture.rs here; that's a follow-up edit.)
}
diff --git a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/stroke.rs b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/stroke.rs
index f089ee0..11af07b 100644
--- a/crates/liteparse-ooxml/src/docx/parse/drawing/schema/stroke.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/drawing/schema/stroke.rs
@@ -4,8 +4,6 @@
//! optional children for fill, dash, join, and head/tail arrows. Consumes
//! `DrawingFillXml` from the fill schema.
-#![allow(dead_code, clippy::large_enum_variant)]
-
use serde::Deserialize;
use crate::docx::dimension::{Dimension, Emu, ThousandthPercent};
@@ -320,7 +318,6 @@ impl From<OutlineXml> for Outline {
| LnChildXml::GradFill(_)
| LnChildXml::BlipFill(_)
| LnChildXml::PattFill(_) => {
- // Wrap the raw variant into a DrawingFillXml for conversion.
let f = match child {
LnChildXml::NoFill(e) => DrawingFillXml::NoFill(e),
LnChildXml::GrpFill(e) => DrawingFillXml::GrpFill(e),
diff --git a/crates/liteparse-ooxml/src/docx/parse/mod.rs b/crates/liteparse-ooxml/src/docx/parse/mod.rs
index 49878b9..a73c97c 100644
--- a/crates/liteparse-ooxml/src/docx/parse/mod.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/mod.rs
@@ -260,10 +260,9 @@ pub fn parse(data: &[u8]) -> Result<Document> {
/// reference that key.
/// * **Hyperlink rels** — `External(rId)` targets are rewritten to
/// `External(URL)` using *this part's* relationships, not the
-/// document's. Pre-fix the hyperlink resolution pass used
-/// `doc_rels` for every part, which silently re-targeted any
-/// header/footer/note hyperlink whose rId happened to mean
-/// something different in the document's own rels.
+/// document's — an rId in a header/footer/note means nothing in the
+/// document's own rels, so resolving against `doc_rels` would
+/// silently re-target the link.
///
/// Other relationship types (font tables, OLE objects, custom XML, …)
/// are not modeled in the block tree yet and are skipped.
diff --git a/crates/liteparse-ooxml/src/docx/parse/numbering.rs b/crates/liteparse-ooxml/src/docx/parse/numbering.rs
index 8755648..8158bf9 100644
--- a/crates/liteparse-ooxml/src/docx/parse/numbering.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/numbering.rs
@@ -289,10 +289,9 @@ mod tests {
use super::*;
#[test]
- /// Upstream failed the document on a non-integer id. We drop the
- /// definition instead — but the guard it existed for still holds, and is
- /// the important part: `"1.0"` must never be silently accepted *as* id 1,
- /// which would shadow the real abstract numbering 1 and renumber lists.
+ /// A non-integer id is dropped rather than parsed: `"1.0"` must never be
+ /// silently accepted *as* id 1, which would shadow the real abstract
+ /// numbering 1 and renumber lists.
fn non_integer_numbering_ids_are_dropped_never_coerced() {
let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="1.0"/></w:numbering>"#;
let defs = parse_numbering(xml).expect("a bad id must not fail the document");
@@ -399,7 +398,7 @@ mod tests {
#[test]
fn start_override_without_lvl_is_captured() {
// A `<w:lvlOverride>` may carry only `<w:startOverride>` (no `<w:lvl>`);
- // the old filter_map dropped such overrides entirely.
+ // such overrides must still be captured, not dropped.
let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:num w:numId="3">
<w:abstractNumId w:val="1"/>
diff --git a/crates/liteparse-ooxml/src/docx/parse/primitives/colors.rs b/crates/liteparse-ooxml/src/docx/parse/primitives/colors.rs
index 669f86c..284e94c 100644
--- a/crates/liteparse-ooxml/src/docx/parse/primitives/colors.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/primitives/colors.rs
@@ -6,7 +6,7 @@
//! - [`RgbHexU32`] — ST_HexColorRGB (§20.1.10.41): strictly a 6-digit RGB hex.
//! Used where the spec disallows "auto".
//!
-//! Both fail deserialization on malformed input (strict per plan §Decisions).
+//! Both fail deserialization on malformed input rather than guessing.
use serde::{Deserialize, Deserializer};
diff --git a/crates/liteparse-ooxml/src/docx/parse/primitives/lenient.rs b/crates/liteparse-ooxml/src/docx/parse/primitives/lenient.rs
index 6bd6997..c455c37 100644
--- a/crates/liteparse-ooxml/src/docx/parse/primitives/lenient.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/primitives/lenient.rs
@@ -1,13 +1,9 @@
//! Tolerant deserializers for OOXML simple-type (`ST_*`) attribute values.
//!
-//! Vendoring divergence from dxpdf, and a standing requirement of this copy:
-//! **one bad attribute value must not fail the whole document.**
-//!
-//! Upstream models each `ST_*` simple type as a plain serde enum, so an
-//! unrecognized value (a newer spec revision, a producer quirk, or plain
-//! corruption) aborts the entire parse. That is the same fail-closed pattern
-//! that cost us 4% of the `docx_files` corpus via unknown *elements*; unknown
-//! *values* are the other half of it.
+//! One bad attribute value must not fail the whole document. dxpdf models
+//! each `ST_*` simple type as a plain serde enum, so an unrecognized value
+//! (a newer spec revision, a producer quirk, or plain corruption) aborts the
+//! entire parse; these helpers swallow that failure instead.
//!
//! ECMA-376 §17.17 treats an invalid attribute value as if the attribute were
//! absent, so the correct degradation is "unspecified", not "some other value".
@@ -16,7 +12,7 @@
//!
//! These helpers only apply where absence is representable. Required
//! attributes with no meaningful "unspecified" state are handled at their own
-//! definition instead — see `ATTRIBUTION.md`.
+//! definition instead.
use serde::Deserialize;
use serde::de::value::Error as ValueError;
diff --git a/crates/liteparse-ooxml/src/docx/parse/primitives/st_enums.rs b/crates/liteparse-ooxml/src/docx/parse/primitives/st_enums.rs
index 727a0be..4b126bf 100644
--- a/crates/liteparse-ooxml/src/docx/parse/primitives/st_enums.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/primitives/st_enums.rs
@@ -2,10 +2,10 @@
//!
//! Each schema enum mirrors an OOXML spec-defined simple type. `From<St…>`
//! implementations convert the schema enum into the matching model type.
-//! Unknown string values fail deserialization (plan §Decisions: strict) — the
-//! one exception is `StNumberFormat`, a large extensible value space (~60 spec
-//! values) whose unsupported members must degrade rather than fail the parse
-//! (see its `#[serde(other)]` variant).
+//! Unknown string values fail deserialization (strict) — the one exception
+//! is `StNumberFormat`, a large extensible value space (~60 spec values)
+//! whose unsupported members must degrade rather than fail the parse (see
+//! its `#[serde(other)]` variant).
//!
//! Alphabetically ordered by schema type name. Layered as:
//!
diff --git a/crates/liteparse-ooxml/src/docx/parse/primitives/toggles.rs b/crates/liteparse-ooxml/src/docx/parse/primitives/toggles.rs
index b88f6e0..3dfeef2 100644
--- a/crates/liteparse-ooxml/src/docx/parse/primitives/toggles.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/primitives/toggles.rs
@@ -4,9 +4,9 @@
//! presence alone asserts the property. With `@val`, the spec lists
//! `true`/`1`/`on` and `false`/`0`/`off` as the valid values.
//!
-//! Per plan §Decisions, `OnOff` is the single spec-driven exception to
-//! strict enum handling: unknown `@val` values resolve to `true` rather than
-//! failing deserialization, matching legacy Word's tolerant toggle behavior.
+//! `OnOff` is deliberately lenient: unknown `@val` values resolve to `true`
+//! rather than failing deserialization, matching Word's tolerant toggle
+//! behavior.
//!
//! [`AttrBool`] is the attribute-level counterpart: a plain boolean
//! attribute like `@rotWithShape="1"` that reads as a string and maps
diff --git a/crates/liteparse-ooxml/src/docx/parse/primitives/units.rs b/crates/liteparse-ooxml/src/docx/parse/primitives/units.rs
index 6636769..1c39fa5 100644
--- a/crates/liteparse-ooxml/src/docx/parse/primitives/units.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/primitives/units.rs
@@ -11,12 +11,9 @@ use crate::model::dimension::{Dimension, Unit};
/// Optional non-negative measurement. A value that is unparseable **or**
/// negative degrades to `None` — "unspecified", so the style cascade supplies
-/// the value — rather than failing the document.
-///
-/// Vendoring divergence from dxpdf, which errors on both. One malformed
-/// measurement anywhere in a file should not cost the whole parse; note that
-/// upstream's behaviour meant a real document with `w:before="-100"` was
-/// unreadable rather than merely imprecise.
+/// the value — rather than failing the document. dxpdf errors on both cases;
+/// here, one malformed measurement (e.g. `w:before="-100"`) must not cost
+/// the whole parse.
pub(crate) fn deserialize_optional_nonnegative_dimension<'de, D, U>(
deserializer: D,
) -> Result<Option<Dimension<U>>, D::Error>
@@ -101,10 +98,8 @@ mod tests {
);
}
- /// Upstream rejected these outright, taking the whole document with them.
- /// We degrade to `None` instead — but the original guard still holds: a
- /// negative fraction must never be silently truncated to `0`, which would
- /// masquerade as an explicitly-specified zero rather than "unspecified".
+ /// A negative fraction must degrade to `None`, not be silently truncated
+ /// to `0` — that would masquerade as an explicit zero.
#[test]
fn negative_fractions_are_unspecified_for_optional_nonnegative_dimensions() {
for raw in ["-0.1", "-0.49"] {
diff --git a/crates/liteparse-ooxml/src/docx/parse/properties/schema/mod.rs b/crates/liteparse-ooxml/src/docx/parse/properties/schema/mod.rs
index 6f07976..4fdbad4 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/mod.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/mod.rs
@@ -3,15 +3,6 @@
//! Schema types carry the `Xml` suffix and are `pub(crate)` — never exported
//! from `docx::`. They mirror OOXML grammar; `From<_Xml> for ModelType`
//! conversions live alongside each schema.
-//!
-//! During Phase 2 these coexist with the legacy event-driven parsers in
-//! `parse/properties/*.rs`. Phase 4 (body) completes the migration by
-//! consuming these schemas directly and retiring the legacy parsers. Until
-//! then, the module is dead code to cargo; the allow attribute below
-//! suppresses the warning — every struct is reachable via `From` impls and
-//! tested in-module.
-
-#![allow(dead_code)]
pub mod border;
pub mod cnf_style;
diff --git a/crates/liteparse-ooxml/src/docx/parse/properties/schema/paragraph.rs b/crates/liteparse-ooxml/src/docx/parse/properties/schema/paragraph.rs
index 1067b39..0955395 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/paragraph.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/paragraph.rs
@@ -111,13 +111,6 @@ struct ValString {
val: String,
}
-#[derive(Clone, Copy, Debug, Deserialize)]
-#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))]
-struct ValAttr<T> {
- #[serde(rename = "@val")]
- val: T,
-}
-
/// `<w:ind>` — indentation. Legacy `@left`/`@right` alias `@start`/`@end`.
/// `@firstLine` and `@hanging` are mutually exclusive; when both present,
/// hanging wins per renderer convention (legacy parser matched this).
@@ -377,8 +370,8 @@ impl PPrXml {
}
None => (None, None),
};
- // rStyle inside pPr/rPr applies to the paragraph mark only; the
- // legacy parser discards this style id too.
+ // rStyle inside pPr/rPr applies to the paragraph mark only and is
+ // not routed anywhere; it is intentionally discarded.
let section_properties = self.sect_pr.map(Into::into);
@@ -592,10 +585,9 @@ mod tests {
assert_eq!(p.auto_space_dn, Some(true));
}
- /// Upstream asserted that an unknown `@val` is a hard error, which meant a
- /// single bad attribute anywhere took down the whole document. We
- /// deliberately reversed that: the alignment is treated as unspecified, so
- /// it inherits from the style chain exactly as if `<w:jc>` were absent.
+ /// An unknown `@val` must not be a hard parse error: the alignment is
+ /// treated as unspecified so it inherits from the style chain exactly
+ /// as if `<w:jc>` were absent.
#[test]
fn unknown_jc_is_unspecified_not_an_error() {
let r = parse(r#"<pPr><jc val="bogus"/></pPr>"#);
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 564fe17..5b1fc26 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
@@ -117,9 +117,8 @@ pub(crate) struct RPrXml {
bdr: Option<BorderXml>,
}
-/// `<w:u w:val="..."/>` — underline. Unlike other ST-enum wrappers we can't
-/// use a bare `ValAttr<StUnderline>` because the attribute is optional; an
-/// underline element with no `@val` means "Single" per §17.3.2.40.
+/// `<w:u w:val="..."/>` — underline. `@val` is optional: an underline
+/// element with no `@val` means "Single" per §17.3.2.40.
#[derive(Clone, Copy, Debug, Deserialize)]
pub(crate) struct UnderlineXml {
#[serde(
@@ -149,13 +148,6 @@ pub(crate) struct ValString {
val: String,
}
-#[derive(Clone, Copy, Debug, Deserialize)]
-#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))]
-pub(crate) struct ValAttr<T> {
- #[serde(rename = "@val")]
- val: T,
-}
-
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(bound(deserialize = "U: Unit"))]
struct NonNegativeDimensionVal<U: Unit> {
@@ -407,9 +399,8 @@ mod tests {
}
#[test]
- /// Upstream rejected a negative font size, failing the whole document.
- /// We treat it as unspecified so the size inherits from the style chain —
- /// but it must still never be accepted as a real size.
+ /// A negative font size is invalid; it must be treated as unspecified so
+ /// the size inherits from the style chain rather than failing the parse.
fn negative_decimal_font_size_is_unspecified() {
let (rp, _) = parse(r#"<rPr><sz val="-1.5"/></rPr>"#);
assert_eq!(rp.font_size, None);
diff --git a/crates/liteparse-ooxml/src/docx/parse/properties/schema/table.rs b/crates/liteparse-ooxml/src/docx/parse/properties/schema/table.rs
index 02e48d1..bc29141 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/table.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/table.rs
@@ -535,13 +535,6 @@ struct ValString {
val: String,
}
-#[derive(Clone, Copy, Debug, Deserialize)]
-#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))]
-pub(crate) struct ValAttr<T> {
- #[serde(rename = "@val")]
- val: T,
-}
-
use crate::docx::parse::primitives::AttrBool;
#[cfg(test)]
@@ -575,8 +568,8 @@ mod tests {
}
#[test]
- /// Upstream failed the whole table on a negative width; we drop the width
- /// and keep the table.
+ /// A negative table width must not fail the whole table; the width is
+ /// dropped instead.
fn negative_decimal_table_width_does_not_fail_the_table() {
let parsed: TblPrXml = quick_xml::de::from_str(
r#"<tblPr><tblW w="-1.5" type="dxa"/><jc val="center"/></tblPr>"#,
diff --git a/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs b/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs
index f7adc81..72a1d26 100644
--- a/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs
@@ -711,9 +711,9 @@ mod tests {
#[test]
fn rewrites_image_inside_alternate_content_choice() {
- // Regression for the fix: the renderer prefers a supported <mc:Choice>
- // over <mc:Fallback>, so image rIds inside a choice must be rewritten
- // too — previously only the fallback was walked.
+ // The renderer prefers a supported <mc:Choice> over <mc:Fallback>, so
+ // image rIds inside a choice must be rewritten too, not just the
+ // fallback.
let ac = AlternateContent {
choices: vec![McChoice {
requires: vec![McRequires::Wps],
diff --git a/crates/liteparse-ooxml/src/docx/parse/styles.rs b/crates/liteparse-ooxml/src/docx/parse/styles.rs
index 444f2d0..7098d08 100644
--- a/crates/liteparse-ooxml/src/docx/parse/styles.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/styles.rs
@@ -7,7 +7,6 @@ use crate::docx::error::Result;
use crate::docx::model::*;
use crate::docx::parse::properties::schema::paragraph::PPrXml;
use crate::docx::parse::properties::schema::run::RPrXml;
-use crate::docx::parse::properties::schema::section::SectPrXml;
use crate::docx::parse::properties::schema::table::{TblPrXml, TcPrXml, TrPrXml};
use crate::docx::parse::serde_xml::from_xml;
@@ -214,10 +213,6 @@ struct ValString {
use crate::docx::parse::primitives::AttrBool;
-// Suppress unused warnings on schema-private fields used only via serde.
-#[allow(dead_code)]
-const _: Option<SectPrXml> = None;
-
// ── schema → model conversion ────────────────────────────────────────────
impl From<StylesXml> for StyleSheet {
diff --git a/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs b/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs
index 40d8572..9a8b7a6 100644
--- a/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/theme/mod.rs
@@ -386,9 +386,6 @@ mod tests {
/// 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>
diff --git a/crates/liteparse-ooxml/src/docx/parse/vml/color.rs b/crates/liteparse-ooxml/src/docx/parse/vml/color.rs
index 04617d8..dc35265 100644
--- a/crates/liteparse-ooxml/src/docx/parse/vml/color.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/vml/color.rs
@@ -4,10 +4,9 @@ use crate::docx::model::*;
/// Parse a VML color value (§14.1.2.1): `#RRGGBB`, `RRGGBB` hex, or named color.
///
-/// Returns `None` for an unrecognized value; every call site treats a color as
-/// optional (an unparseable `fillcolor` simply means "no color"), so this
-/// mirrors the sibling `parse_style`/`parse_formula`/`parse_length` helpers
-/// rather than raising a document-fatal error.
+/// Returns `None` for an unrecognized value rather than an error: every call
+/// site treats a color as optional, so an unparseable `fillcolor` simply
+/// means "no color" (matching the sibling `parse_style`/`parse_length` helpers).
pub(super) fn parse_color(s: &str) -> Option<VmlColor> {
let hex = s.strip_prefix('#').unwrap_or(s);
if hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
diff --git a/crates/liteparse-ooxml/src/docx/parse/vml/schema.rs b/crates/liteparse-ooxml/src/docx/parse/vml/schema.rs
index e58d075..066b949 100644
--- a/crates/liteparse-ooxml/src/docx/parse/vml/schema.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/vml/schema.rs
@@ -6,7 +6,7 @@
//! color names/hex) are reused from `vml::{style, color, path_commands,
//! formulas}` as pure `&str` → value parsers.
-#![allow(dead_code, clippy::large_enum_variant)]
+#![allow(clippy::large_enum_variant)]
use serde::Deserialize;
@@ -89,6 +89,7 @@ pub(crate) enum VmlPrimitiveXml {
/// but `$value` collects *every* child — this variant lets serde
/// absorb the duplicate match without erroring.
#[serde(rename = "shapetype")]
+ #[allow(dead_code, reason = "captured for serde routing only, see into_model")]
ShapeType(Box<ShapeTypeXml>),
/// Unknown / unsupported VML element. Dropped at conversion time.
#[serde(other)]
@@ -181,7 +182,7 @@ impl From<FillXml> for crate::docx::model::VmlFill {
color2: x.color2.as_deref().and_then(parse_color),
opacity: x.opacity.as_deref().and_then(|s| {
// VML opacity admits "0.5" or "32768f" (fixed-point fraction
- // of 65536). For phase C we accept the float form.
+ // of 65536). Only the plain float form is handled here.
s.parse::<f32>().ok()
}),
src: x.src,
@@ -293,18 +294,20 @@ pub(crate) struct ShapeXml {
impl ShapeXml {
fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlShape {
+ let common = CommonAttrsXml {
+ id: self.id,
+ style: self.style,
+ fillcolor: self.fillcolor,
+ stroked: self.stroked,
+ stroke: self.stroke,
+ textbox: self.textbox,
+ wrap: self.wrap,
+ imagedata: self.imagedata,
+ fill: self.fill,
+ }
+ .into_model(ctx);
VmlShape {
- common: crate::model::VmlCommonAttrs {
- id: self.id.map(VmlShapeId::new),
- style: parse_style(self.style),
- fill_color: self.fillcolor.as_deref().and_then(parse_color),
- stroked: self.stroked.map(|b| b.0),
- stroke: self.stroke.map(Into::into),
- text_box: self.textbox.map(|t| t.into_model(ctx)),
- wrap: self.wrap.map(Into::into),
- image_data: self.imagedata.map(Into::into),
- fill: self.fill.map(Into::into),
- },
+ common,
shape_type_ref: self
.ty
.map(|s| VmlShapeId::new(s.strip_prefix('#').unwrap_or(&s))),
@@ -318,15 +321,11 @@ impl ShapeXml {
/// VML §14.1.2.16 `<v:rect>`.
///
-/// Common attrs are inlined here (rather than via
-/// `#[serde(flatten)]` on a `CommonAttrsXml`) because quick-xml's
-/// serde drops the deeply-nested `<v:textbox><w:txbxContent>...`
-/// when the field carrying `<v:textbox>` lives behind a flatten
-/// boundary — the rect's textbox content silently vanishes. Inlining
-/// keeps every child element on the same struct level so it parses
-/// faithfully. The other primitives keep `flatten` because they
-/// don't host text-box content in practice (or do but were simpler
-/// to wire that way).
+/// Common attrs are inlined here (rather than via `#[serde(flatten)]`
+/// on `CommonAttrsXml`) because quick-xml's serde drops deeply-nested
+/// `<v:textbox><w:txbxContent>...` content when the field carrying
+/// `<v:textbox>` lives behind a flatten boundary. Inlining keeps every
+/// child element at the same struct level so it parses correctly.
#[derive(Deserialize)]
pub(crate) struct RectXml {
#[serde(rename = "@id", default)]
@@ -352,17 +351,18 @@ pub(crate) struct RectXml {
impl RectXml {
fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlRect {
VmlRect {
- common: VmlCommonAttrs {
- id: self.id.map(VmlShapeId::new),
- style: parse_style(self.style),
- fill_color: self.fillcolor.as_deref().and_then(parse_color),
- stroked: self.stroked.map(|b| b.0),
- stroke: self.stroke.map(Into::into),
- text_box: self.textbox.map(|t| t.into_model(ctx)),
- wrap: self.wrap.map(Into::into),
- image_data: self.imagedata.map(Into::into),
- fill: self.fill.map(Into::into),
- },
+ common: CommonAttrsXml {
+ id: self.id,
+ style: self.style,
+ fillcolor: self.fillcolor,
+ stroked: self.stroked,
+ stroke: self.stroke,
+ textbox: self.textbox,
+ wrap: self.wrap,
+ imagedata: self.imagedata,
+ fill: self.fill,
+ }
+ .into_model(ctx),
}
}
}
@@ -1204,11 +1204,9 @@ mod tests {
#[test]
fn rect_textbox_content_is_populated() {
- // Regression for the gray-bar text bug: `<v:rect>` with a
- // `<v:textbox><w:txbxContent>` should reach the model with
- // its inner paragraphs intact, just like `<v:shape>` does.
- // The `flatten` indirection on `RectXml.common` was dropping
- // the inner content when this test was first added.
+ // Regression: `<v:rect>` with a `<v:textbox><w:txbxContent>` must
+ // reach the model with its inner paragraphs intact, just like
+ // `<v:shape>` does — see the `flatten` note on `RectXml`.
use crate::docx::model::VmlPrimitive;
let p = parse(
r#"<pict>
diff --git a/crates/liteparse-ooxml/src/model/types/drawing_color.rs b/crates/liteparse-ooxml/src/model/types/drawing_color.rs
index c089dd0..7ac2cdd 100644
--- a/crates/liteparse-ooxml/src/model/types/drawing_color.rs
+++ b/crates/liteparse-ooxml/src/model/types/drawing_color.rs
@@ -181,11 +181,10 @@ pub enum SchemeColorVal {
/// 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.
+/// A non-identity map is common (e.g. a master swapping `bg2`/`tx2`, or even
+/// `bg1`/`tx1`), so inferring the convention instead of reading it produces a
+/// wrong colour rather than a missing one — confidently-legible text in the
+/// wrong hue rather than 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.
@@ -206,8 +205,7 @@ pub struct ColorMap {
}
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.
+ /// The identity mapping used when a master declares no `p:clrMap`.
fn default() -> Self {
Self {
bg1: SchemeColorVal::Lt1,
diff --git a/crates/liteparse-ooxml/src/model/types/table.rs b/crates/liteparse-ooxml/src/model/types/table.rs
index 643a671..642d2c9 100644
--- a/crates/liteparse-ooxml/src/model/types/table.rs
+++ b/crates/liteparse-ooxml/src/model/types/table.rs
@@ -129,15 +129,14 @@ pub struct TableRowProperties {
/// §17.4.42: row-level override of the table's `tblCellSpacing`.
pub cell_spacing: Option<TableMeasure>,
/// §17.4.86: preferred width of the leading space before the first cell.
- /// Note: when present and divergent from the corresponding `tblGrid` columns'
- /// summed widths, treated as informational only — column widths are not
- /// overridden per row in this implementation; a `warn!` is logged on mismatch.
+ /// Parsed for round-trip fidelity; layout derives column widths from
+ /// `tblGrid` and does not use this value.
pub w_before: Option<TableMeasure>,
/// §17.4.16: number of grid columns to skip after the last cell of the row.
/// Default 0 when omitted from `<w:trPr>`.
pub grid_after: u32,
/// §17.4.85: preferred width of the trailing space after the last cell.
- /// Same width-override caveat as `w_before`.
+ /// Same as `w_before`: parsed but not used by layout.
pub w_after: Option<TableMeasure>,
}
diff --git a/crates/liteparse-ooxml/src/model/types/theme.rs b/crates/liteparse-ooxml/src/model/types/theme.rs
index 7361671..9687c8f 100644
--- a/crates/liteparse-ooxml/src/model/types/theme.rs
+++ b/crates/liteparse-ooxml/src/model/types/theme.rs
@@ -16,15 +16,9 @@ pub struct Theme {
/// §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.
+ /// then 0-based here). A shape's `<a:fillRef>` never reaches it, so a
+ /// `bgRef` resolved against `fill_styles` instead would silently render
+ /// with no background.
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
@@ -53,43 +47,6 @@ pub struct ThemeColorScheme {
pub followed_hyperlink: u32,
}
-impl ThemeColorScheme {
- /// Resolve a theme color index to an RGB value.
- pub fn resolve(&self, idx: ThemeColorIndex) -> u32 {
- match idx {
- ThemeColorIndex::Dark1 => self.dark1,
- ThemeColorIndex::Light1 => self.light1,
- ThemeColorIndex::Dark2 => self.dark2,
- ThemeColorIndex::Light2 => self.light2,
- ThemeColorIndex::Accent1 => self.accent1,
- ThemeColorIndex::Accent2 => self.accent2,
- ThemeColorIndex::Accent3 => self.accent3,
- ThemeColorIndex::Accent4 => self.accent4,
- ThemeColorIndex::Accent5 => self.accent5,
- ThemeColorIndex::Accent6 => self.accent6,
- ThemeColorIndex::Hyperlink => self.hyperlink,
- ThemeColorIndex::FollowedHyperlink => self.followed_hyperlink,
- }
- }
-}
-
-/// Index into the theme color scheme (ST_ThemeColor).
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub enum ThemeColorIndex {
- Dark1,
- Light1,
- Dark2,
- Light2,
- Accent1,
- Accent2,
- Accent3,
- Accent4,
- Accent5,
- Accent6,
- Hyperlink,
- FollowedHyperlink,
-}
-
#[derive(Clone, Debug, Default)]
pub struct ThemeFontScheme {
pub latin: String,
@@ -161,39 +118,3 @@ pub enum ScriptTag {
/// Unrecognized script code — preserved as-is.
Other(Box<str>),
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn resolve_maps_each_index_to_its_slot() {
- // Distinct value per slot catches an accidental field swap in `resolve`.
- let cs = ThemeColorScheme {
- dark1: 1,
- light1: 2,
- dark2: 3,
- light2: 4,
- accent1: 5,
- accent2: 6,
- accent3: 7,
- accent4: 8,
- accent5: 9,
- accent6: 10,
- hyperlink: 11,
- followed_hyperlink: 12,
- };
- assert_eq!(cs.resolve(ThemeColorIndex::Dark1), 1);
- assert_eq!(cs.resolve(ThemeColorIndex::Light1), 2);
- assert_eq!(cs.resolve(ThemeColorIndex::Dark2), 3);
- assert_eq!(cs.resolve(ThemeColorIndex::Light2), 4);
- assert_eq!(cs.resolve(ThemeColorIndex::Accent1), 5);
- assert_eq!(cs.resolve(ThemeColorIndex::Accent2), 6);
- assert_eq!(cs.resolve(ThemeColorIndex::Accent3), 7);
- assert_eq!(cs.resolve(ThemeColorIndex::Accent4), 8);
- assert_eq!(cs.resolve(ThemeColorIndex::Accent5), 9);
- assert_eq!(cs.resolve(ThemeColorIndex::Accent6), 10);
- assert_eq!(cs.resolve(ThemeColorIndex::Hyperlink), 11);
- assert_eq!(cs.resolve(ThemeColorIndex::FollowedHyperlink), 12);
- }
-}
diff --git a/crates/liteparse-ooxml/src/model/types/vml.rs b/crates/liteparse-ooxml/src/model/types/vml.rs
index 6842ac6..e5ff00c 100644
--- a/crates/liteparse-ooxml/src/model/types/vml.rs
+++ b/crates/liteparse-ooxml/src/model/types/vml.rs
@@ -1148,9 +1148,8 @@ mod tests {
}
/// Units that need a containing box, a font size, or the attribute's own
- /// context are `None` — never a fabricated number. Three separate
- /// converters previously each invented their own answer here, and they
- /// disagreed: a bare number was EMU in one and points in the others.
+ /// context are `None` — never a fabricated number, since a bare number's
+ /// meaning (EMU vs. points) depends on which attribute it came from.
#[test]
fn context_dependent_units_are_unresolved() {
for unit in [
diff --git a/crates/liteparse-ooxml/src/pptx/cascade.rs b/crates/liteparse-ooxml/src/pptx/cascade.rs
index b5a05b1..6f4f62b 100644
--- a/crates/liteparse-ooxml/src/pptx/cascade.rs
+++ b/crates/liteparse-ooxml/src/pptx/cascade.rs
@@ -7,65 +7,47 @@
//!
//! [`pptx::shapes`]: crate::pptx::shapes
//!
-//! ## The match rule is not the same at each rung
+//! ## The match rule is not the same at each level of the chain
//!
-//! This is the one thing to get right, and the corpus is unambiguous about it
-//! (census over all 45 decks, 1,804 shapes declaring no `xfrm`):
+//! - **Slide → layout**: match `@idx`.
+//! - **Layout → master** and **notes slide → notes master**: match a
+//! collapsed `@type` (see [`PlaceholderKind::collapsed_for_master`]).
//!
-//! | rung | rule | result |
-//! |---|---|---|
-//! | slide → layout | **`@idx`** | **737 / 737** matched |
-//! | layout → master | **collapsed `@type`** | 192 / 207 matched |
-//! | notes slide → notes master | **collapsed `@type`** | 800 / 860 matched |
-//!
-//! `@idx` at the first rung is not merely sufficient, it is *right where type
-//! would be wrong*: on 2 of the 737 the slide declares a bare `<p:ph idx="0"/>`
+//! `@idx` at the slide→layout level is not merely sufficient, it is *right
+//! where type would be wrong*: a slide can declare a bare `<p:ph idx="0"/>`
//! — which materializes as `body` per §19.7.10's default — while the layout
//! placeholder it points at is a `title`. The author's shape *is* the title;
-//! matching on type would have missed it or, worse, matched some other body
-//! placeholder. **Match on idx and do not second-guess it with type.**
+//! matching on type would miss it or match some other body placeholder
+//! instead. **Match on idx and do not second-guess it with type.**
//!
-//! At the second and third rungs `@idx` is not usable — a master holds one
-//! `body` placeholder for every body-ish layout placeholder, and their `idx`
-//! values are unrelated — so the type is collapsed through
+//! At the master level `@idx` is not usable — a master holds one `body`
+//! placeholder for every body-ish layout placeholder, and their `idx` values
+//! are unrelated — so the type is collapsed through
//! [`PlaceholderKind::collapsed_for_master`] first.
//!
-//! ## The misses are properties of the documents, not of the rule
-//!
-//! Both were chased rather than assumed, because a match rate below 1.0 is
-//! exactly how a wrong rule would look:
-//!
-//! - **15 layout misses** are all `p:hf`-family placeholders — `dt`, `ftr`,
-//! `sldNum` (§19.3.1.28) — on layouts whose master declares no counterpart
-//! at all. A master that turns those chrome elements off simply has no such
-//! shape, so there is nothing to inherit from and no rectangle we could
-//! invent that would not be a guess.
-//! - **60 notes misses** are all from one deck whose `notesMaster1.xml` has a
-//! literally empty `spTree` — no shapes of any kind. Same conclusion.
-//!
-//! So the cascade is a *total* function over everything the file gives it
-//! something to resolve against, and the residue is honest `None` rather than
-//! a guessed rectangle. That is the same rule the rest of this vendor follows:
-//! an invented value is silent corruption.
+//! An unmatched placeholder (e.g. a layout `dt`/`ftr`/`sldNum` chrome
+//! placeholder whose master declares no counterpart, or an empty notes
+//! master `spTree`) has nothing to inherit from. The cascade leaves it
+//! `None` rather than inventing a rectangle — an invented value would be
+//! silent corruption.
//!
-//! ## Three simplifications, each measured rather than assumed
+//! ## Three simplifications this module relies on
//!
-//! - **Transforms are never partial.** Across every layout and master
-//! placeholder on the corpus, `<a:off>` and `<a:ext>` either both appear or
-//! neither does — 0 counterexamples. So inheritance is whole-transform, and
-//! the per-property walk (`left`/`top`/`width`/`height` each resolving
-//! independently, as python-pptx does it) buys nothing here.
-//! - **No placeholder is ever nested inside a `p:grpSp`** — 0 across all 2,980
-//! corpus shape trees, on both sides of every rung. That matters more than it
-//! looks: a nested placeholder's transform lives in its group's child
-//! coordinate space, so inheriting one into or out of a group would silently
-//! mix coordinate spaces. This module therefore only ever reads and writes
-//! top-level shapes, and a nested placeholder is left untouched rather than
-//! resolved into the wrong space.
-//! - **Rotation must ride along.** 195 inheritable placeholder transforms carry
-//! a non-`None` `@rot`, so dropping rotation on inheritance would silently
-//! un-rotate them. Whole-transform inheritance gets this for free; a
-//! hand-rolled offset/extent copy would not have.
+//! - **Transforms are never partial.** A layout or master placeholder's
+//! `<a:off>` and `<a:ext>` either both appear or neither does. So
+//! inheritance is whole-transform, not a per-property walk
+//! (`left`/`top`/`width`/`height` each resolving independently, as
+//! python-pptx does it).
+//! - **No placeholder is ever nested inside a `p:grpSp`.** A nested
+//! placeholder's transform would live in its group's child coordinate
+//! space, so inheriting one into or out of a group would silently mix
+//! coordinate spaces. This module therefore only ever reads and writes
+//! top-level shapes, and a nested placeholder (should one ever occur) is
+//! left untouched rather than resolved into the wrong space.
+//! - **Rotation must ride along.** An inheritable placeholder transform can
+//! carry a non-`None` `@rot`, so dropping rotation on inheritance would
+//! silently un-rotate it. Whole-transform inheritance gets this for free;
+//! a hand-rolled offset/extent copy would not.
use std::collections::HashMap;
@@ -79,8 +61,7 @@ use super::shapes::{Background, Placeholder, PlaceholderKind, Shape};
/// How a placeholder finds its counterpart on the part above it.
///
-/// The two rungs genuinely differ; see the module docs for the measurement
-/// that establishes each.
+/// The rule genuinely differs by level; see the module docs for why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchRule {
/// Slide → layout, and notes slide → its own layout if one ever exists:
@@ -96,7 +77,7 @@ pub enum MatchRule {
///
/// Build the master's first and pass it to the layout's, so that a slide
/// placeholder pointing at a layout placeholder that itself declares no
-/// `xfrm` still resolves in one lookup. Both rungs are pre-flattened here
+/// `xfrm` still resolves in one lookup. Both levels are pre-flattened here
/// rather than walked per shape.
#[derive(Clone, Debug, Default)]
pub struct PlaceholderGeometry {
@@ -106,10 +87,9 @@ pub struct PlaceholderGeometry {
impl PlaceholderGeometry {
/// Index a master or notes master — the top of the chain, with nothing
- /// above it to inherit from.
- ///
- /// On the corpus **no master placeholder lacks an `xfrm`**, so the chain
- /// always terminates in a real rectangle rather than running off the top.
+ /// above it to inherit from. A master placeholder is expected to always
+ /// declare its own `xfrm`, so the chain terminates in a real rectangle
+ /// rather than running off the top.
pub fn from_master(shapes: &[Shape]) -> Self {
Self::index(shapes, None, MatchRule::CollapsedKind)
}
@@ -134,9 +114,8 @@ impl PlaceholderGeometry {
}
}
- /// True when this part supplies no inheritable geometry at all — an empty
- /// `spTree`, or one with no placeholders. Real: one corpus notes master is
- /// exactly this.
+ /// True when this part supplies no inheritable geometry at all — an
+ /// empty `spTree`, or one with no placeholders.
pub fn is_empty(&self) -> bool {
self.by_idx.is_empty() && self.by_kind.is_empty()
}
@@ -144,8 +123,8 @@ impl PlaceholderGeometry {
fn index(shapes: &[Shape], parent: Option<&PlaceholderGeometry>, rule: MatchRule) -> Self {
let mut out = Self::default();
// Top-level only, deliberately: see the module docs on coordinate
- // spaces. Nested placeholders do not occur on the corpus, and if one
- // ever does, ignoring it is the safe failure.
+ // spaces. If a nested placeholder ever occurs, ignoring it is the
+ // safe failure.
for shape in shapes {
let Some(ph) = &shape.placeholder else {
continue;
@@ -156,9 +135,10 @@ impl PlaceholderGeometry {
else {
continue;
};
- // First in document order wins. 4 corpus layouts declare the same
- // `@idx` twice; PowerPoint's own resolution is first-wins, and more
- // to the point a stable rule beats a HashMap-order coin flip.
+ // First in document order wins, matching PowerPoint's own
+ // resolution when a layout declares the same `@idx` twice — and
+ // more to the point, a stable rule beats a HashMap-order coin
+ // flip.
out.by_idx.entry(ph.idx).or_insert(transform);
out.by_kind
.entry(ph.kind.collapsed_for_master())
@@ -178,22 +158,12 @@ pub struct CascadeStats {
/// Placeholders that had no `xfrm` and found no counterpart. Stays `None`
/// rather than becoming a guessed rectangle.
pub unresolved: usize,
- /// Non-placeholder shapes with no `xfrm`. The shape walk measured this as
- /// **0 on the whole corpus** and `pptx_shape_probe` fails the build if it
- /// ever stops being 0, so a non-zero count here means that invariant broke
- /// and the cascade is not the thing to fix.
+ /// Non-placeholder shapes with no `xfrm`. This should never happen — a
+ /// non-placeholder always carries its own geometry — so a non-zero count
+ /// here points at a bug upstream of this module, not in it.
pub orphans: usize,
}
-impl CascadeStats {
- fn absorb(&mut self, other: CascadeStats) {
- self.declared += other.declared;
- self.inherited += other.inherited;
- self.unresolved += other.unresolved;
- self.orphans += other.orphans;
- }
-}
-
/// Fill in `transform` for every top-level placeholder in `shapes` that
/// declares none, from `source` under `rule`.
///
@@ -231,28 +201,6 @@ pub fn apply_inherited_geometry(
stats
}
-/// Resolve a slide's shapes against its layout and master in one call, and its
-/// notes' shapes against the notes master.
-///
-/// The indexes are the caller's to cache: layouts and masters repeat across
-/// every slide in a deck, so rebuilding them per slide is the one obvious way
-/// to make this quadratic. Hence the primitives above are public and this is a
-/// convenience over already-built indexes rather than over raw parts.
-pub fn apply_slide(
- slide_shapes: &mut [Shape],
- layout: Option<&PlaceholderGeometry>,
- notes_shapes: &mut [Shape],
- notes_master: Option<&PlaceholderGeometry>,
-) -> CascadeStats {
- let mut stats = apply_inherited_geometry(slide_shapes, layout, MatchRule::Idx);
- stats.absorb(apply_inherited_geometry(
- notes_shapes,
- notes_master,
- MatchRule::CollapsedKind,
- ));
- stats
-}
-
// ── Background (§19.3.1.1) ───────────────────────────────────────────────────
//
// A second, much simpler cascade sharing the same slide → layout → master
@@ -260,11 +208,12 @@ pub fn apply_slide(
// 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.
+/// Which level of the chain 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.
+/// Carried so a caller (or test) can verify which level actually resolved
+/// rather than trusting that the whole chain was consulted — a cascade that
+/// quietly stopped checking the master could still resolve most slides and
+/// look like it worked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackgroundSource {
Slide,
@@ -274,14 +223,13 @@ pub enum BackgroundSource {
/// 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.
+/// First declaration down the chain wins. Returns `None` only when no part
+/// in the chain declares one, which should be rare — every slide is
+/// expected to resolve a background through at least its master.
///
/// 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
+/// geometry levels 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
@@ -304,19 +252,18 @@ pub fn resolve_background<'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`]), not the deck's first — a slide
+/// whose master is not the deck's first would otherwise resolve a `bgRef`
+/// against the wrong theme's style matrix.
///
/// [`PresentationPackage::theme_for`]: crate::pptx::PresentationPackage::theme_for
/// `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.
/// `media` must be the [`PartMedia`] of the part the background was resolved
-/// *from* — the [`BackgroundSource`] rung, which is the slide's own on 58
-/// corpus slides, its layout's on 95 and its master's on 1,125. Passing the
-/// slide's own table for a master's photograph is the inherited-`rId1` trap:
-/// a real image, from the wrong relationship.
+/// *from* — the [`BackgroundSource`] level. Passing the slide's own table
+/// for a master's photograph is the inherited-`rId1` trap: a real image,
+/// from the wrong relationship.
pub fn background_fill(
bg: &Background,
theme: Option<&Theme>,
@@ -394,9 +341,9 @@ mod tests {
assert!(slide[0].transform_inherited);
}
- /// The 2-of-737 case: a bare `<p:ph/>` materializes as `body` idx 0 but
- /// points at the layout's *title*. Matching on type instead of idx would
- /// get this wrong, which is why the rule ignores type entirely.
+ /// A bare `<p:ph/>` materializes as `body` idx 0 but can point at the
+ /// layout's *title*. Matching on type instead of idx would get this
+ /// wrong, which is why the rule ignores type entirely.
#[test]
fn idx_match_ignores_a_disagreeing_type() {
let layout = part(&[
@@ -420,14 +367,14 @@ mod tests {
);
}
- /// Two rungs in one lookup: the layout placeholder itself has no `xfrm`.
+ /// Two levels in one lookup: the layout placeholder itself has no `xfrm`.
#[test]
fn layout_folds_the_master_in_before_the_slide_asks() {
let master = part(&[("body", "9", Some(xfrm(700, 800, 70, 80)))]);
let master_index = PlaceholderGeometry::from_master(&master);
// Layout body placeholder: no xfrm of its own, and idx 1 — unrelated
- // to the master's idx 9, which is why this rung matches on type.
+ // to the master's idx 9, which is why this level matches on type.
let layout = part(&[("body", "1", None)]);
let layout_index = PlaceholderGeometry::from_layout(&layout, Some(&master_index));
@@ -439,7 +386,7 @@ mod tests {
}
/// `subTitle`, `obj`, `tbl` and friends all collapse onto the master's
- /// single `body`; without the collapse this rung finds nothing.
+ /// single `body`; without the collapse this level finds nothing.
#[test]
fn layout_to_master_collapses_body_ish_types() {
let master = part(&[("body", "1", Some(xfrm(700, 800, 70, 80)))]);
@@ -457,8 +404,9 @@ mod tests {
}
}
- /// The 15 `dt`/`ftr` layout placeholders: nothing to match, so nothing is
- /// invented. A guessed rectangle would be silent corruption.
+ /// A `dt`/`ftr` layout placeholder with no master counterpart: nothing
+ /// to match, so nothing is invented. A guessed rectangle would be
+ /// silent corruption.
#[test]
fn an_unmatched_placeholder_stays_none() {
let master = part(&[("title", "0", Some(xfrm(100, 200, 10, 20)))]);
@@ -504,8 +452,8 @@ mod tests {
assert!(!slide[0].transform_inherited);
}
- /// 4 corpus layouts declare `@idx` twice. First in document order wins —
- /// a stable rule, not a HashMap-iteration coin flip.
+ /// A layout can declare `@idx` twice. First in document order wins — a
+ /// stable rule, not a HashMap-iteration coin flip.
#[test]
fn duplicate_idx_resolves_first_in_document_order() {
let layout = part(&[
@@ -519,8 +467,8 @@ mod tests {
assert_eq!(offset_of(&slide[0]).unwrap().x, emu(111));
}
- /// Rotation is part of the inherited rectangle — 195 corpus placeholders
- /// carry one, and dropping it silently un-rotates them.
+ /// Rotation is part of the inherited rectangle, and dropping it would
+ /// silently un-rotate the shape.
#[test]
fn rotation_rides_along_with_the_inherited_transform() {
let shapes = parse_shape_tree(
@@ -603,23 +551,19 @@ mod tests {
}
}
- /// 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.
+ /// A background chain with no declaration anywhere must resolve to
+ /// `None`, 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.
+ /// `fillStyleLst[1000]`. Routing a background `bgRef` at the shape
+ /// path's `fillStyleLst` is a real, common mistake, not an edge case.
/// 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.
+ /// 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 {
@@ -646,8 +590,8 @@ mod tests {
0x00BB00
);
- // Below 1001 the shape matrix is correct — the spec allows both forms
- // even though the corpus only ever writes the offset one.
+ // Below 1001 the shape matrix is correct — the spec allows both
+ // forms, even though the 1000-offset one is by far the more common.
let bg3 = Background::Reference(StyleMatrixRef {
idx: 2,
color: None,
diff --git a/crates/liteparse-ooxml/src/pptx/geometry.rs b/crates/liteparse-ooxml/src/pptx/geometry.rs
index 9e36fc3..051200b 100644
--- a/crates/liteparse-ooxml/src/pptx/geometry.rs
+++ b/crates/liteparse-ooxml/src/pptx/geometry.rs
@@ -18,33 +18,29 @@
//! Frames compose down the tree, so this is an affine map accumulated
//! pre-order — which is exactly the order [`Shape::visit`] documents.
//!
-//! ## What the corpus says this has to handle
+//! ## Invariants the mapping relies on
//!
-//! Census over the 45-deck corpus (`pptx_geometry_census`), 9,272 top-level
-//! slide shapes and 3,704 inside a group:
-//!
-//! | question | answer | consequence |
-//! |---|---|---|
-//! | is the child space ever absent or partial? | **0 / 0 / 0** — `chOff`, `chExt`, and the xor are all never missing on 575 groups | the mapping is a **total function**; no defaulting rules, and a missing term is a bug rather than a case |
-//! | is `chExt` ever zero? | **0** | the divide is safe — but it is still guarded, because a zero would produce infinities that propagate silently |
-//! | is the scale ever not 1? | **342 of 575 (59%)** | the scale is load-bearing, not a rounding term |
-//! | is it ever non-uniform? | **154 (27%)**, `sx/sy` differing by up to 2.18x | two scalars, never one |
-//! | how extreme does it get? | **1961x** — a 1696x2204 EMU child space onto a 3.3M x 4.1M rect | dropping the scale does not nudge those shapes, it collapses them to invisibility |
-//! | how many *text* shapes are affected? | 457 inside groups, **111 under a non-unit scale** | 111 are wrong by a factor today, 346 by an offset |
-//! | do groups rotate? | **28**, of which **3** contain a rotated child | angle composition is real but rare |
-//! | do groups flip? | **7** | must be modelled: a flip mirrors the child space, changing the *sign* of the map |
-//! | do shapes flip? | 497, but only **9 carry text** | flips are a picture/connector concern |
-//! | is rotation ever oblique? | **302 of 759** (132 with text) | the angle must be carried; an axis-aligned box alone loses the reading direction |
-//! | is `chExt` a clip? | **no** — 102 children legally sit outside it | never treat it as bounds |
+//! - The child space (`chOff`/`chExt`) is always fully declared on a group
+//! that has one, so the mapping is a **total function** — a missing term
+//! is a bug, not a case to default.
+//! - `chExt` can in principle be zero and must still be guarded: dividing by
+//! it would produce an infinity that propagates silently otherwise.
+//! - The scale is routinely not 1, and not uniform between axes, so it must
+//! be carried as two scalars — dropping it does not merely nudge a shape's
+//! position, it can collapse the shape to invisibility.
+//! - Groups and shapes both rotate and flip, independently of each other; a
+//! flip mirrors the child space, changing the *sign* of the map.
+//! - `chExt` is not a clip — children can legally sit outside it, so it must
+//! never be treated as bounds.
//!
//! ## Why the output is a separate field
//!
-//! [`Shape::slide_rect`] is filled here; `Shape::transform` keeps the declared
-//! child-space values. The two are different facts about the document, the same
-//! way [`Shape::transform_inherited`] and `SizeSource` distinguish a resolved
-//! value from a fallen-back one. It also keeps `bench/pptx_corpus/geometry_probe.py`
-//! honest: it checks declared EMU against the source XML, and would have nothing
-//! to check against if this pass overwrote them.
+//! [`Shape::slide_rect`] is filled here; `Shape::transform` keeps the
+//! declared child-space values. The two are different facts about the
+//! document, the same way [`Shape::transform_inherited`] and `SizeSource`
+//! distinguish a resolved value from a fallen-back one — and it lets a
+//! consumer diff resolved geometry against the declared EMU in the source
+//! XML.
use crate::model::dimension::{Dimension, Emu, SixtieThousandthDeg};
use crate::model::geometry::{Offset, Rect, Size};
@@ -57,9 +53,9 @@ const FULL_TURN: i64 = 21_600_000;
/// A shape's resolved position on the slide.
///
/// `rect` is the **unrotated** box: the rectangle the shape would occupy with
-/// `rotation` at zero. Rotation is carried beside it rather than folded into an
-/// axis-aligned bounding box, because 132 corpus shapes carry text at an oblique
-/// angle and their reading direction is not recoverable from a bbox. A consumer
+/// `rotation` at zero. Rotation is carried beside it rather than folded into
+/// an axis-aligned bounding box, because a shape's reading direction is not
+/// recoverable from a bbox once it's rotated to an oblique angle. A consumer
/// that only wants a bbox can call [`SlideRect::bounding_box`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SlideRect {
@@ -72,11 +68,9 @@ pub struct SlideRect {
/// True when an enclosing group rotated the shape while a *non-uniform*
/// scale was in effect. The composed map is then a genuine skew, which
/// `rotation` + `rect` cannot express exactly, so this records that the
- /// values are the closest similarity rather than the exact map.
- ///
- /// Measured at **0** on the corpus. It exists so that if a deck ever hits
- /// the case, the probe says so instead of the numbers being quietly a few
- /// EMU wrong.
+ /// values are the closest similarity rather than the exact map. Rare in
+ /// practice, but flagged rather than silently approximated when it does
+ /// occur.
pub skewed: bool,
}
@@ -114,12 +108,11 @@ pub struct GeometryStats {
pub unpositioned: usize,
/// Groups whose frame was composed onto children.
pub groups: usize,
- /// Groups declaring a transform but no child space. The corpus says 0; a
- /// non-zero here means a deck exists that the census did not predict, and
- /// the identity child space used as a fallback is a guess.
+ /// Groups declaring a transform but no child space. Should be rare in
+ /// practice; the identity child space used as a fallback is a guess.
pub groups_without_child_space: usize,
- /// Groups whose `chExt` is zero in an axis. The corpus says 0; the scale
- /// falls back to 1 rather than producing an infinity.
+ /// Groups whose `chExt` is zero in an axis. The scale falls back to 1
+ /// rather than producing an infinity.
pub groups_with_zero_child_extent: usize,
/// See [`SlideRect::skewed`].
pub skewed: usize,
@@ -475,9 +468,8 @@ mod tests {
assert_eq!(rect_of(&kids(&shapes)[0]), (10, 10, 50, 50));
}
- /// The corpus case that matters: a tiny child space blown up onto a
- /// slide-sized rectangle. Getting this wrong does not shift the shape, it
- /// makes it invisible.
+ /// A tiny child space blown up onto a slide-sized rectangle. Getting
+ /// this wrong does not shift the shape, it makes it invisible.
#[test]
fn non_unit_scale_multiplies_position_and_size() {
let mut shapes = tree(&grp(
@@ -492,7 +484,7 @@ mod tests {
#[test]
fn non_uniform_scale_uses_both_axes() {
- // x scales by 2, y by 4 — 27% of corpus groups scale non-uniformly.
+ // x scales by 2, y by 4 — the two axes must be tracked independently.
let mut shapes = tree(&grp(
(0, 0, 2000, 4000),
Some((0, 0, 1000, 1000)),
@@ -685,8 +677,8 @@ mod tests {
}
/// Rotation under a non-uniform scale is a genuine skew, which a rect plus
- /// an angle cannot express. It does not occur on the corpus, so the
- /// contract is that it is *flagged*, not that it is exact.
+ /// an angle cannot express. Rare in practice; the contract is that it is
+ /// *flagged*, not that it is exact.
#[test]
fn rotation_under_non_uniform_scale_is_flagged_as_skewed() {
let inner = grp(
diff --git a/crates/liteparse-ooxml/src/pptx/media.rs b/crates/liteparse-ooxml/src/pptx/media.rs
index f62847a..7f31400 100644
--- a/crates/liteparse-ooxml/src/pptx/media.rs
+++ b/crates/liteparse-ooxml/src/pptx/media.rs
@@ -3,37 +3,32 @@
//! ## Why this is keyed two ways
//!
//! A blip names its image with an `r:embed`, and an `r:id` is scoped to the
-//! part that writes it: a slide's `rId1`, its layout's `rId1` and its master's
-//! `rId1` are three unrelated relationships, and on this corpus they routinely
-//! name three different images. So the painter needs a **per-part** table
-//! ([`PartMedia`]), or an inherited picture silently acquires whatever the
-//! slide's `rId1` happens to point at — a real photograph, from the wrong
-//! relationship, which no "did it resolve?" gate can see.
+//! part that writes it: a slide's `rId1`, its layout's `rId1` and its
+//! master's `rId1` are unrelated relationships that can each point at a
+//! different image. The painter therefore needs a **per-part** table
+//! ([`PartMedia`]) — otherwise an inherited picture could silently pick up
+//! whatever the slide's `rId1` happens to name instead of its own target.
//!
-//! The *bytes*, on the other hand, are shared. One logo referenced by 60
+//! The *bytes*, on the other hand, are shared: one logo referenced from many
//! slides is one media part, and [`MediaEntry`]'s `Arc` identity is what the
-//! painter's bitmap cache keys on, so each part must become exactly one `Arc`
-//! however many relationships point at it. Hence `by_path` under `by_part`:
-//! the first deduplicates bytes, the second scopes ids.
+//! painter's bitmap cache keys on, so each part must become exactly one
+//! `Arc` no matter how many relationships point at it. Hence `by_path`
+//! nested under `by_part`: the first deduplicates bytes, the second scopes
+//! ids.
//!
//! ## Nothing is read until something asks for it
//!
-//! `PackageContents` holds the whole zip, and the corpus's media is 378 MB
-//! across 45 decks — of which the deck-wide totals are misleading, because
-//! 139 `.svg` and 23 `.wdp` parts are never a blip target at all (Office
-//! writes them as alternatives and effect backups). Copying every media part
-//! into an `Arc` up front would pay for all of them. Resolution is therefore
-//! lazy per path, and a part that no blip reaches is never copied.
-//!
-//! A **negative** result is cached too, as `None`. A missing or undecodable
-//! target is a property of the package, not of the caller asking, so the
-//! second of 60 references must not re-walk the zip to rediscover it.
+//! Media parts (fonts, SVG alternatives, effect backups) can be large and
+//! most are never a blip target. Resolution is lazy per path — a part that
+//! no blip reaches is never copied into memory — and a missing or
+//! undecodable target is cached as `None` so repeated references don't
+//! re-walk the zip to rediscover it.
use std::collections::HashMap;
use std::sync::Arc;
use crate::docx::relationships::{RelationshipType, TargetMode};
-use crate::model::{ImageFormat, RelId};
+use crate::model::ImageFormat;
use crate::render::resolve::images::{MediaEntry, PartMedia};
use super::package::{Part, PresentationPackage};
@@ -48,8 +43,8 @@ pub struct MediaCache {
by_part: HashMap<String, PartMedia>,
/// Handed out for a part that does not exist — a slide with no reachable
/// master, say. A borrowable empty table rather than an `Option` so that
- /// every paint site takes the same code path, and "this rung has no media"
- /// cannot accidentally become "resolve against whatever is in scope".
+ /// every paint site takes the same code path, and "no media here" cannot
+ /// accidentally fall back to "resolve against whatever is in scope".
empty: PartMedia,
}
@@ -94,11 +89,10 @@ impl MediaCache {
/// One media part's bytes, read and format-detected at most once.
///
/// Format detection goes through [`ImageFormat::detect`], which tries the
- /// extension and *then* the magic bytes. That fallback is load-bearing
- /// here rather than defensive: 21 corpus blips point at `.jfif` parts,
- /// which are byte-for-byte JPEG and which an extension-only reading drops.
- /// Undecodable formats (EMF/WMF/SVG) are still entered — the painter is
- /// the layer that knows what it can rasterize, and a resolver that hid
+ /// extension and then falls back to the magic bytes — needed because
+ /// some `.jfif` parts are byte-for-byte JPEG and extension-only sniffing
+ /// misses them. Undecodable formats (EMF/WMF/SVG) are still entered: the
+ /// painter is the layer that knows what it can rasterize, and hiding
/// them here would report them as missing images instead of unsupported
/// ones.
fn load(
@@ -126,24 +120,6 @@ impl MediaCache {
.and_then(|p| self.by_part.get(p))
.unwrap_or(&self.empty)
}
-
- /// How many distinct media parts have been read into memory. Reported by
- /// the probe so that "the deck has images" and "the painter reached them"
- /// stay separate claims.
- pub fn parts_loaded(&self) -> usize {
- self.by_path.values().filter(|v| v.is_some()).count()
- }
-
- /// Package paths a relationship named that the package does not contain.
- pub fn parts_missing(&self) -> usize {
- self.by_path.values().filter(|v| v.is_none()).count()
- }
-}
-
-/// Look one `r:embed` up in a part's table. A thin helper so callers do not
-/// have to build a [`RelId`] to ask.
-pub fn media_entry<'a>(media: &'a PartMedia, embed: &str) -> Option<&'a MediaEntry> {
- media.get(&RelId::new(embed))
}
#[cfg(test)]
@@ -152,9 +128,9 @@ mod tests {
#[test]
fn jfif_extension_falls_through_to_magic_bytes() {
- // The 21-reference case: an extension OOXML §M.1.1 does not list, over
- // bytes that are plainly JPEG. Extension-only detection returns
- // `Unknown` and the painter drops the image.
+ // `.jfif` is an extension OOXML §M.1.1 does not list, over bytes that
+ // are plainly JPEG. Extension-only detection would return `Unknown`
+ // and the painter would drop the image.
let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F'];
assert_eq!(
ImageFormat::detect("ppt/media/image7.jfif", &jpeg),
diff --git a/crates/liteparse-ooxml/src/pptx/mod.rs b/crates/liteparse-ooxml/src/pptx/mod.rs
index 3136e92..b68d655 100644
--- a/crates/liteparse-ooxml/src/pptx/mod.rs
+++ b/crates/liteparse-ooxml/src/pptx/mod.rs
@@ -8,7 +8,7 @@
//! `<a:off>`/`<a:ext>` in EMU against a fixed `<p:sldSz>`. So the hard part
//! here is not layout, it is the placeholder cascade — a shape that omits
//! `<a:xfrm>` inherits position and size from its layout, which inherits
-//! from its master, and the match rule differs at each rung.
+//! from its master, and the match rule differs at each level of that chain.
pub mod cascade;
pub mod geometry;
@@ -20,7 +20,7 @@ pub mod textcascade;
pub use cascade::{
BackgroundSource, CascadeStats, MatchRule, PlaceholderGeometry, apply_inherited_geometry,
- apply_slide, background_fill, resolve_background,
+ background_fill, resolve_background,
};
pub use geometry::{GeometryStats, SlideRect, apply_slide_geometry};
pub use media::MediaCache;
diff --git a/crates/liteparse-ooxml/src/pptx/package.rs b/crates/liteparse-ooxml/src/pptx/package.rs
index 7dd3fce..7028aec 100644
--- a/crates/liteparse-ooxml/src/pptx/package.rs
+++ b/crates/liteparse-ooxml/src/pptx/package.rs
@@ -71,9 +71,8 @@ impl Part {
///
/// `layout` and `master` are `Option` because the cascade must degrade
/// rather than fail: a slide with no reachable layout still has its own
-/// directly-applied text and geometry, and refusing to parse it would be
-/// the fail-closed behaviour this vendor has already had to retire four
-/// times (see `ATTRIBUTION.md`).
+/// directly-applied text and geometry, and refusing to parse it would
+/// throw away content that is otherwise recoverable.
#[derive(Clone, Debug)]
pub struct SlideParts {
pub slide: Part,
@@ -83,34 +82,33 @@ pub struct SlideParts {
/// 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.
+ /// A path rather than bytes because a theme is shared by every slide
+ /// under its master; cloning the XML per slide would duplicate it once
+ /// per slide instead of once per master.
pub theme_path: Option<String>,
}
/// The whole deck, walked but not yet understood.
///
/// Deliberately neither `Clone` nor `Debug`: it owns every media part, so a
-/// clone copies the whole deck's images (390 MB across the corpus) and a
-/// debug-print dumps them.
+/// clone would copy the whole deck's images and a debug-print would dump
+/// them.
pub struct PresentationPackage {
pub info: PresentationInfo,
- /// `ppt/presentation.xml` itself, kept because it is the outermost rung of
- /// the **text** cascade: `p:defaultTextStyle` lives here and is the only
- /// source a non-placeholder shape can reach. 2,144 of the corpus runs that
- /// declare no size resolve against it.
+ /// `ppt/presentation.xml` itself, kept because it is the outermost level
+ /// of the **text** cascade: `p:defaultTextStyle` lives here and is the
+ /// only source a non-placeholder shape can reach when it declares no
+ /// size of its own.
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.
///
/// 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.
+ /// adequate for colour**: a deck can reach more than one theme from its
+ /// slides, and a `<p:bgRef>` background resolved out of the theme's
+ /// style matrix would come from the wrong theme — 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`].
@@ -127,8 +125,8 @@ pub fn walk(data: &[u8]) -> Result<PresentationPackage> {
// The presentation part is reached through the package root rels rather
// than assumed to be `ppt/presentation.xml`. The path is conventional,
- // not mandated, and the 9 docProps-less decks in the corpus are already
- // proof that "every producer follows convention" is a bad bet.
+ // not mandated by the spec, so producers that deviate would otherwise
+ // break parsing.
let root_rels = load_rels(&package, "");
let pres_path = root_rels
.find_by_type(&RelationshipType::OfficeDocument)
@@ -189,8 +187,8 @@ pub fn walk(data: &[u8]) -> Result<PresentationPackage> {
.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.
+ // way the master is — a deck can reach more than one theme, so it
+ // must not be resolved once for the whole deck.
let theme_path = master
.as_ref()
.and_then(|m| m.resolve_rel_of_type(&RelationshipType::Theme));
@@ -214,8 +212,9 @@ pub fn walk(data: &[u8]) -> Result<PresentationPackage> {
}
}
- // 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.
+ // Retained for font resolution, which is stable enough across masters
+ // to use a single theme for. See the field docs for why colour must not
+ // use it.
let theme = slides
.iter()
.find_map(|s| s.theme_path.as_deref())
@@ -284,26 +283,21 @@ fn load_rels(package: &PackageContents, part_path: &str) -> Relationships {
}
// ---------------------------------------------------------------------------
-// The presentation part is parsed by hand, NOT with serde. This is the one
-// place in the vendor that departs from the serde-schema convention, and the
-// reason is a hard limitation rather than taste:
+// The presentation part is parsed by hand, NOT with serde.
//
// quick-xml's serde layer matches attributes on their **local name with the
-// namespace prefix dropped** (the same property `serde_xml.rs` documents for
-// *elements*). `<p:sldId id="322" r:id="rId2"/>` therefore presents two
-// attributes both named `id`, and deserializing it fails with
-// `duplicate field @id` — which is exactly what the corpus reported, 45/45.
+// namespace prefix dropped**. `<p:sldId id="322" r:id="rId2"/>` therefore
+// presents two attributes both named `id`, and deserializing it fails with
+// `duplicate field @id`.
//
// There is no serde spelling that distinguishes them: `#[serde(rename =
// "@r:id")]` never matches because the prefix is already gone, and
-// `alias = "@id"` would bind the *numeric slide id* to the relationship id —
-// silent corruption, the class `ATTRIBUTION.md` records as this vendor's
-// recurring trap. (`blip@r:embed` gets away with its alias only because no
-// competing `@embed` exists on that element.)
+// `alias = "@id"` would bind the *numeric slide id* to the relationship id,
+// silently corrupting it. (`blip@r:embed` gets away with its alias only
+// because no competing `@embed` exists on that element.)
//
// So the r:id-bearing lists are read with a namespace-aware reader that
-// compares the *qualified* name. The presentation part is small and flat, so
-// the cost is ~50 lines and it stays confined to this module.
+// compares the *qualified* name, confined to this module.
//
// The same collision exists on `p:sldMasterId` and `p:sldLayoutId`; anything
// added later that reads those must come through here, not through serde.
@@ -397,8 +391,8 @@ mod tests {
/// The regression this module exists for. `p:sldId` carries both `@id`
/// and `@r:id`; quick-xml's serde layer drops namespace prefixes on
- /// attributes, so a serde schema sees `duplicate field @id` and the
- /// whole deck fails to parse (observed: 45/45 of the corpus).
+ /// attributes, so a serde schema would see `duplicate field @id` and
+ /// fail to parse.
///
/// Two things must hold, and the second is the one that matters: the
/// r:id must be read, AND the numeric `@id` must never stand in for it.
diff --git a/crates/liteparse-ooxml/src/pptx/shapes.rs b/crates/liteparse-ooxml/src/pptx/shapes.rs
index d4b6cd8..70ce932 100644
--- a/crates/liteparse-ooxml/src/pptx/shapes.rs
+++ b/crates/liteparse-ooxml/src/pptx/shapes.rs
@@ -14,33 +14,26 @@
//! first, because both key off [`Placeholder`], which only exists once shapes
//! are typed.
//!
-//! ## What the corpus says this has to handle
+//! ## What this module has to handle
//!
-//! Census over the 45-deck corpus, all 2,980 shape trees (slides, layouts,
-//! masters, notes slides, notes masters):
+//! The shape-tree children are `p:sp` (a text-bearing shape), `p:pic`
+//! (never carries text), `p:cxnSp` (a connector — never carries text,
+//! geometry only), `p:grpSp` (nests to arbitrary depth) and
+//! `p:graphicFrame` (table, diagram, OLE object or chart).
//!
-//! | child | count | note |
-//! |---|---|---|
-//! | `p:sp` | 15,906 | 14,957 carry a text body |
-//! | `p:pic` | 2,418 | never carries text |
-//! | `p:cxnSp` | 845 | never carries text — connectors are geometry only |
-//! | `p:grpSp` | 695 | nests to **depth 5** |
-//! | `p:graphicFrame` | 102 | diagram 53, table 36, ole 11, chartex 3 |
-//! | `mc:AlternateContent` | 10 | see below |
+//! Two invariants this module and its cascade depend on:
//!
-//! Two invariants worth asserting rather than assuming, both measured:
-//!
-//! - **Every shape lacking an `xfrm` carries a `p:ph`** — 2,422 `p:sp` and 3
-//! `p:pic`, with no counterexample of any kind. So the placeholder cascade is
-//! exactly the missing-geometry case, with no second fallback needed.
-//! [`Shape::needs_inherited_geometry`] names it, and `pptx_shape_probe`
-//! fails if a deck ever breaks it. Note the 3 pictures: they are why this
+//! - **Every shape lacking an `xfrm` carries a `p:ph`**, with no
+//! counterexample of any kind — including pictures, which is why this
//! module models `p:pic` itself instead of reusing the DOCX `PictureXml`,
-//! which has no slot for a placeholder — see [`PicXml`].
-//! - **`p:graphicFrame` positions itself with `<p:xfrm>`, not `<a:xfrm>` —
-//! 102 of 102.** Different namespace and a different parent element, so it
-//! does *not* arrive through [`SpPrXml`] like every other shape's transform.
-//! Missing this yields graphic frames silently stacked at the origin.
+//! which has no slot for a placeholder (see [`PicXml`]). So the
+//! placeholder cascade is exactly the missing-geometry case, with no
+//! second fallback needed. [`Shape::needs_inherited_geometry`] names it,
+//! and `pptx_shape_probe` fails if a deck ever breaks it.
+//! - **`p:graphicFrame` positions itself with `<p:xfrm>`, not `<a:xfrm>`.**
+//! Different namespace and a different parent element, so it does *not*
+//! arrive through [`SpPrXml`] like every other shape's transform. Missing
+//! this yields graphic frames silently stacked at the origin.
use serde::Deserialize;
@@ -99,7 +92,7 @@ pub struct Shape {
/// the source XML.
pub slide_rect: Option<SlideRect>,
/// §19.3.1.46 `p:style` — the shape's references into the theme's style
- /// matrices, when it declares one. 2,181 of the corpus's 17,024 shapes do.
+ /// matrices, when it declares one.
///
/// On [`Shape`] rather than on each [`ShapeKind`] variant because all three
/// kinds that can carry one (`p:sp`, `p:cxnSp`, `p:pic`) carry the *same*
@@ -114,9 +107,9 @@ pub struct Shape {
/// §20.1.4.1.4 `a:CT_ShapeStyle` — the four theme-matrix references a
/// `p:style` holds.
///
-/// The spec requires all four children, and the corpus agrees exactly (2,181
-/// of each), but they are modelled as `Option` because a file that omits one
-/// should lose that reference and not the whole shape.
+/// The spec requires all four children, but they are modelled as `Option`
+/// because a file that omits one should lose that reference and not the
+/// whole shape.
///
/// Deliberately *not* four loose fields on [`Shape`] the way
/// [`crate::model::WordProcessingShape`] carries them: there they arrived one
@@ -125,12 +118,12 @@ pub struct Shape {
#[derive(Clone, Debug, Default)]
pub struct ShapeStyle {
/// `a:lnRef` — the theme line style. Supplies the outline's colour when
- /// `a:ln` declares none (179 corpus shapes, today's black default) and the
- /// **entire** outline when there is no `a:ln` at all (312).
+ /// `a:ln` declares none, and the **entire** outline when there is no
+ /// `a:ln` at all.
pub line_ref: Option<StyleMatrixRef>,
/// `a:fillRef` — the theme fill style, used only when `spPr` declares no
- /// fill element of its own. 631 corpus shapes inherit through it, of which
- /// 335 name `idx="0"` and therefore inherit *nothing*.
+ /// fill element of its own. `idx="0"` is a legal value here and means
+ /// inherit *nothing*.
pub fill_ref: Option<StyleMatrixRef>,
/// `a:effectRef` — the theme effect style, consulted when the direct
/// `a:effectLst` is absent or empty.
@@ -139,9 +132,9 @@ pub struct ShapeStyle {
/// collection.
///
/// Parsed here but **not yet consumed**: it belongs to the text cascade,
- /// not the paint walk, and wiring it into one and not the other would make
- /// the markdown emitter and the geometry pass disagree about a run's
- /// colour. 2,181 corpus shapes declare one.
+ /// not the paint walk, and wiring it into one and not the other would
+ /// make the markdown emitter and the geometry pass disagree about a
+ /// run's colour.
pub font_ref: Option<FontReference>,
}
@@ -160,9 +153,9 @@ impl Shape {
/// True when this shape declares no transform of its own and therefore
/// depends on the placeholder cascade for its position and size.
///
- /// On the corpus this is true for 2,422 shapes and every one of them is a
- /// placeholder, which is what makes the cascade a total function over this
- /// set rather than a best-effort one.
+ /// Every shape observed with no transform is a placeholder, which is
+ /// what makes the cascade a total function over this set rather than a
+ /// best-effort one.
pub fn needs_inherited_geometry(&self) -> bool {
self.transform.is_none()
}
@@ -212,12 +205,11 @@ pub enum ShapeKind {
/// read through this module's own [`PicXml`], which adds the placeholder
/// PresentationML allows and WordprocessingML has no concept of.
Picture(Box<Picture>),
- /// §19.3.1.19 `p:cxnSp` — a connector. Carries no text in any of the 845
- /// corpus instances; kept because it is real geometry a layout pass and a
- /// screenshot both need.
+ /// §19.3.1.19 `p:cxnSp` — a connector. Never carries text; kept because
+ /// it is real geometry a layout pass and a screenshot both need.
Connector(Box<Connector>),
- /// §19.3.1.22 `p:grpSp`. Boxed: `Group` is by far the largest variant
- /// (~880 B), and there are 16.5k shapes on the corpus.
+ /// §19.3.1.22 `p:grpSp`. Boxed: `Group` is by far the largest variant,
+ /// and shape trees can hold thousands of shapes.
Group(Box<Group>),
/// §19.3.1.21 `p:graphicFrame`.
GraphicFrame(Box<GraphicFrame>),
@@ -227,8 +219,8 @@ pub enum ShapeKind {
#[derive(Clone, Debug, Default)]
pub struct AutoShape {
pub properties: Option<ShapeProperties>,
- /// `p:txBody`. Absent on 949 of 15,906 corpus shapes — a shape with no
- /// text body is not the same as one with an empty body.
+ /// `p:txBody`. Can be absent — a shape with no text body is not the
+ /// same as one with an empty body.
pub text: Option<TextBody>,
/// `p:cNvSpPr/@txBox` — the shape is a plain text box rather than a
/// preset-geometry shape that happens to have text.
@@ -267,7 +259,7 @@ pub struct Group {
pub child_offset: Option<Offset<Emu>>,
/// `a:chExt` — the extent of the child coordinate space.
pub child_extent: Option<Size<Emu>>,
- /// In document order, which is z-order. Nests to depth 5 on the corpus.
+ /// In document order, which is z-order. Groups can nest.
pub children: Vec<Shape>,
}
@@ -280,24 +272,22 @@ pub struct GraphicFrame {
/// What a graphic frame actually holds, keyed by `a:graphicData/@uri`.
#[derive(Clone, Debug)]
pub enum GraphicFramePayload {
- /// A DrawingML table (`a:tbl`) — 36 of 102 corpus frames.
+ /// A DrawingML table (`a:tbl`).
Table(Box<Table>),
- /// SmartArt (53 corpus frames), which does not hold its own content: the
- /// frame carries only `dgm:relIds`, and the text lives in the data part
- /// that `@r:dm` points at (`ppt/diagrams/data*.xml`). Resolving the
- /// relationship needs the owning [`Part`](crate::pptx::Part), which this
- /// layer does not have, so the id is surfaced for the caller to resolve.
+ /// SmartArt, which does not hold its own content: the frame carries
+ /// only `dgm:relIds`, and the text lives in the data part that `@r:dm`
+ /// points at (`ppt/diagrams/data*.xml`). Resolving the relationship
+ /// needs the owning [`Part`](crate::pptx::Part), which this layer does
+ /// not have, so the id is surfaced for the caller to resolve.
///
- /// Worth its own variant rather than `Unsupported`: on the corpus all 53
- /// parts carry text, 12,102 characters of it, and a shape walk alone can
- /// never see any of it.
+ /// Worth its own variant rather than `Unsupported`: diagram data parts
+ /// routinely carry real text that a shape walk alone can never see.
Diagram { data_rel: String },
- /// Embedded OLE (11) or a chart (2) — payloads we genuinely do not read.
+ /// Embedded OLE or a chart — payloads we genuinely do not read.
///
- /// Kept as a typed variant rather than dropped so that a caller can emit a
- /// placeholder and a probe can *count* what is being lost. Silently
- /// discarding them would make the gap invisible, which is the failure mode
- /// this vendor has been bitten by repeatedly.
+ /// Kept as a typed variant rather than dropped so that a caller can emit
+ /// a placeholder and a probe can *count* what is being lost. Silently
+ /// discarding them would make the gap invisible.
Unsupported { uri: String },
}
@@ -315,7 +305,7 @@ pub struct Table {
pub grid: Vec<Dimension<Emu>>,
pub rows: Vec<TableRow>,
/// `a:tblPr/@firstRow` — the table style paints row 0 as a header. The
- /// only header signal PPTX gives; 15 of 36 corpus tables set it.
+ /// only header signal PPTX gives.
pub first_row: bool,
pub first_col: bool,
pub band_row: bool,
@@ -324,8 +314,8 @@ pub struct Table {
/// §21.1.3.18 `a:tr`.
#[derive(Clone, Debug, Default)]
pub struct TableRow {
- /// `@h` — declared row height. Present on 221 of 221 corpus rows, and it
- /// is a *minimum*: the rendered row grows to fit its content.
+ /// `@h` — declared row height. A *minimum*: the rendered row grows to
+ /// fit its content.
pub height: Option<Dimension<Emu>>,
pub cells: Vec<TableCell>,
}
@@ -343,7 +333,7 @@ pub struct TableCell {
pub h_merge: bool,
/// `@vMerge` — this cell is absorbed by a vertical merge above it.
pub v_merge: bool,
- /// `a:tcPr`, the text-relevant half. Declared on 603 of 608 corpus cells.
+ /// `a:tcPr`, the text-relevant half.
pub properties: TableCellProperties,
}
@@ -360,13 +350,13 @@ impl TableCell {
///
/// Fills, borders (`a:lnL`/`lnR`/`lnT`/`lnB`/`lnTlToBr`/`lnBlToTr`) and
/// `@horzOverflow` are deliberately absent: the first two are paint, and the
-/// third is declared 0 times on the corpus. `@anchorCtr` is likewise unread —
-/// it centres the text *block* horizontally, which this model has no way to
-/// express, and no corpus cell sets it.
+/// third is essentially never used in practice. `@anchorCtr` is likewise
+/// unread — it centres the text *block* horizontally, which this model has
+/// no way to express.
///
-/// **A cell's own `a:bodyPr` is not an alternative source.** All 603 corpus
-/// cells carry one and every one of them is bare — no attributes, no children —
-/// because §21.1.3.16 puts the insets and the anchor here instead.
+/// **A cell's own `a:bodyPr` is not an alternative source.** §21.1.3.16
+/// puts the insets and the anchor here on `a:tcPr` instead, so a cell's
+/// `a:bodyPr` is expected to be bare.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TableCellProperties {
/// `@marL`, in EMU. `None` is the §21.1.3.17 default of 91440.
@@ -379,11 +369,11 @@ pub struct TableCellProperties {
pub bottom_margin: Option<Dimension<Emu>>,
/// `@anchor` — where the text sits vertically in the cell.
///
- /// **Not a rare attribute**: 326 of 603 corpus cells declare a non-top
- /// anchor (324 `ctr`, 2 `b`). Ignoring it tops every cell's text.
+ /// **Not a rare attribute**: a non-top anchor is common. Ignoring it
+ /// tops every cell's text.
pub anchor: Option<TextAnchoringType>,
- /// `@vert` — vertical text. Declared 0 times on the corpus, and carried
- /// only so a consumer can tell "horizontal" from "not modelled".
+ /// `@vert` — vertical text. Rare in practice, and carried only so a
+ /// consumer can tell "horizontal" from "not modelled".
pub vert: Option<TextVerticalType>,
}
@@ -422,18 +412,17 @@ impl TableCellProperties {
///
/// Both attributes are optional in the file and both have spec defaults that
/// the cascade depends on, so they are materialized here rather than left as
-/// `Option` for every consumer to re-derive. On the corpus `@type` is absent
-/// 639 times and `@idx` 1,866 times, so neither default is hypothetical.
+/// `Option` for every consumer to re-derive. Both defaults are exercised
+/// routinely, not just hypothetical fallbacks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Placeholder {
/// `@type`, defaulting to `body` per §19.7.10.
pub kind: PlaceholderKind,
/// `@idx`, defaulting to 0 per §19.7.10.
///
- /// **`u32`, not a narrower integer.** The corpus contains `idx` values of
- /// exactly 4294967295 (`u32::MAX`) — 137 of them across 13 of 45 decks.
- /// It is a legal `xsd:unsignedInt`, so anything narrower silently wraps or
- /// hard-fails on more than a quarter of real decks.
+ /// **`u32`, not a narrower integer.** `idx="4294967295"` (`u32::MAX`) is
+ /// a legal `xsd:unsignedInt` value and appears in real decks; anything
+ /// narrower would silently wrap or hard-fail on it.
pub idx: u32,
}
@@ -441,7 +430,7 @@ pub struct Placeholder {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum PlaceholderKind {
Title,
- /// The `@type` default, and the most common value on the corpus.
+ /// The `@type` default, and the most common value in practice.
#[default]
Body,
CtrTitle,
@@ -468,7 +457,7 @@ pub enum PlaceholderKind {
impl PlaceholderKind {
/// The layout→master match rule, per python-pptx's 14-entry collapse map.
///
- /// The three rungs of the cascade do **not** match the same way: slide →
+ /// The cascade does **not** match the same way at every level: slide →
/// layout matches on `idx`, but layout → master matches on *type*, and
/// only after collapsing the many body-ish types onto `body`. A master
/// holds no `pic` or `tbl` placeholder to match against, so without this
@@ -498,18 +487,16 @@ impl PlaceholderKind {
///
/// [`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.**
+/// Every slide is expected to resolve to an effective background of some
+/// kind, whether declared directly or inherited through the chain.
#[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.
+ /// Its `EG_EffectProperties` sibling is **not** modelled: 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),
@@ -600,27 +587,28 @@ pub fn parse_single_object(data: &[u8]) -> Result<Option<Shape>> {
///
/// [`parse_slide_part`] already returns this as
/// [`SlidePart::show_inherited_shapes`], and that is what every *walk* should
-/// use. This exists for the one caller that needs the attribute **without** the
-/// shape tree: the deck-wide tally of inherited text has to know which slides
-/// really draw a rung, and it visits every slide before either walk begins.
-/// Deserializing 1,278 slide parts a second time to read one boolean measured
-/// at +7.5% on the corpus's end-to-end markdown run; this measures at nothing.
+/// use. This exists for the one caller that needs the attribute **without**
+/// the shape tree: a deck-wide tally of inherited text has to know which
+/// slides actually show an inherited layer, and visits every slide before
+/// either walk begins. Deserializing every slide part a second time just to
+/// read one boolean is measurably more expensive than this targeted read.
///
/// The duplication is deliberate and is fenced by
/// `cheap_reader_agrees_with_the_full_parse`, which asserts the two answers
/// match on the same bytes — a second reader of an attribute is only safe while
/// something fails when they disagree.
///
-/// Defaults to **true**, per the schema, and on anything it cannot read: a part
-/// whose XML is malformed is the full parse's problem to report, and answering
-/// "shows its rungs" here keeps the failure in one place.
+/// Defaults to **true**, per the schema, and on anything it cannot read: a
+/// part whose XML is malformed is the full parse's problem to report, and
+/// answering "shows its inherited shapes" here keeps the failure in one
+/// place.
pub fn shows_inherited_shapes(data: &[u8]) -> bool {
let mut reader = quick_xml::Reader::from_reader(data);
let mut buf = Vec::new();
loop {
// The root element is the first `Start` — `Empty` cannot be it, since a
// `p:sld` with no `p:cSld` is still not self-closing in any producer,
- // and an empty root has no rungs to draw anyway.
+ // and an empty root has no inherited shapes to draw anyway.
match reader.read_event_into(&mut buf) {
Ok(quick_xml::events::Event::Start(e)) => {
// The true-family is `AttrBool`'s, spelled the same way on
@@ -649,10 +637,10 @@ pub fn shows_inherited_shapes(data: &[u8]) -> bool {
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.
+ /// declared here", **not** "no background" — the value is inherited,
+ /// and resolving it is [`crate::pptx::cascade::resolve_background`]'s
+ /// job. Most slides inherit their background from the master rather
+ /// than declaring their own.
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.
@@ -662,16 +650,14 @@ pub struct SlidePart {
/// that element's entire content is "inherit".
pub color_map: Option<ColorMap>,
/// §19.2.1.32 `p:sld/@showMasterSp` and §19.3.1.39 `p:sldLayout`'s — "draw
- /// the shapes the rung above this one supplies". Defaults to **true**, per
- /// both elements' schema.
+ /// the shapes the part above this one supplies". Defaults to **true**,
+ /// per both elements' schema.
///
/// A `bool` rather than an `Option`, because unlike `background` and
/// `color_map` this attribute does not cascade: it is a statement about
/// *this* part's own rendering, and a slide that says nothing shows its
- /// layout's shapes whatever the layout says about the master's.
- ///
- /// Corpus: 25 of 415 layouts and 4 of 1,278 slides opt out. A master's root
- /// has no such attribute and always reads `true`.
+ /// layout's shapes whatever the layout says about the master's. A
+ /// master's root has no such attribute and always reads `true`.
pub show_inherited_shapes: bool,
}
@@ -719,9 +705,8 @@ pub fn parse_slide_part(data: &[u8]) -> Result<SlidePart> {
// ── Schema ───────────────────────────────────────────────────────────────────
//
-// As in `pptx::text`, coverage is driven by a census over the 45-deck corpus
-// rather than by reading §19.3 front to back: every element and attribute below
-// appears in at least one real deck.
+// As in `pptx::text`, coverage is driven by what real decks actually use
+// rather than by reading §19.3 front to back.
#[derive(Deserialize)]
struct SlidePartXml {
@@ -842,8 +827,8 @@ impl ClrMapXml {
}
/// §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).
+/// (inherit) and `a:overrideClrMapping` (a full CT_ColorMapping stated
+/// locally).
#[derive(Deserialize)]
struct ClrMapOvrXml {
#[serde(rename = "overrideClrMapping", default)]
@@ -927,22 +912,23 @@ enum ShapeTreeChildXml {
/// measurement rather than chosen up front.
///
/// Strict MCE says: use a `Choice` only if you understand every namespace in
-/// its `@Requires`, else fall through to `Fallback`. We understand none of the
-/// four the corpus uses (`v`, `p14`, `cx1`, `a14`), so that rule always picks
-/// `Fallback`. It is the right rule for a *renderer* — the fallback is what an
-/// old viewer is meant to draw — and the wrong one for a text extractor,
-/// because the fallback is routinely a **rasterized picture of the content**.
+/// its `@Requires`, else fall through to `Fallback`. We understand none of
+/// the namespaces PowerPoint commonly requires (`v`, `p14`, `cx1`, `a14`),
+/// so that rule always picks `Fallback`. It is the right rule for a
+/// *renderer* — the fallback is what an old viewer is meant to draw — and
+/// the wrong one for a text extractor, because the fallback is routinely a
+/// **rasterized picture of the content**.
///
-/// The corpus case that caught it: a slide equation is written as
+/// The case that motivates this: a slide equation can be written as
/// `mc:Choice Requires="a14"` holding a `p:sp` whose paragraph interleaves
-/// `<a14:m><m:oMath>` blocks with real `<a:r>` runs, beside an `mc:Fallback`
-/// holding a `p:pic` of the same equation. Preferring the fallback dropped the
-/// two `<a:t> = </a:t>` runs between the math blocks — a 2-character corpus
-/// recall miss, invisible until OMML was split out of the denominator.
+/// `<a14:m><m:oMath>` blocks with real `<a:r>` runs, beside an
+/// `mc:Fallback` holding a `p:pic` of the same equation. Preferring the
+/// fallback drops the `<a:r>` runs between the math blocks — real text a
+/// renderer doesn't need but an extractor does.
///
/// Comparing text also handles the opposite case without a second rule:
-/// `mc:Choice` holding a `p:contentPart` (ink, 5 on the corpus) lowers to
-/// nothing, so its `p:pic` fallback wins on its own merits.
+/// `mc:Choice` holding a `p:contentPart` (ink) lowers to nothing, so its
+/// `p:pic` fallback wins on its own merits.
#[derive(Deserialize, Default)]
struct AlternateContentXml {
#[serde(rename = "Choice", default)]
@@ -1084,15 +1070,14 @@ impl PhXml {
/// §19.3.1.37 `p:pic`.
///
-/// Mirrors the shared `PictureXml` field for field — same `CT_Picture`, and the
-/// corpus confirms `nvPicPr` and `blipFill` are present on 2,437 of 2,437 — but
+/// Mirrors the shared `PictureXml` field for field — same `CT_Picture` — but
/// adds the one thing PresentationML has and WordprocessingML does not: a
/// picture can be a **placeholder**.
///
-/// Reusing `PictureXml` directly costs the `p:ph` on 55 corpus pictures, 3 of
-/// which declare no `xfrm` at all and therefore have no geometry from any other
-/// source. Those 3 are the entire reason the "every shape without an `xfrm` is a
-/// placeholder" invariant appeared to break when this walk first ran.
+/// Reusing `PictureXml` directly would lose the `p:ph`, and some
+/// placeholder pictures declare no `xfrm` at all and therefore have no
+/// geometry from any other source — which is why "every shape without an
+/// `xfrm` is a placeholder" only holds when pictures carry `p:ph` too.
#[derive(Debug, Deserialize)]
struct PicXml {
#[serde(rename = "nvPicPr")]
@@ -1152,8 +1137,7 @@ struct NvGrpSpPrXml {
/// §19.3.1.23 `p:grpSpPr` — `a:xfrm` + `EG_FillProperties` +
/// `EG_EffectProperties` + `a:scene3d`. There is deliberately no `ln` field:
-/// the schema gives a group no outline, which is why a census of the corpus
-/// finds an `a:ln` on 0 of 695 groups. The six fill members route through
+/// the schema gives a group no outline. The six fill members route through
/// [`pick_fill`], the same collapse `SpPrXml` and `p:bgPr` use.
#[derive(Debug, Deserialize, Default)]
struct GrpSpPrXml {
@@ -1637,8 +1621,8 @@ mod tests {
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.
+ /// A master can swap `bg2`/`tx2`, which is the whole reason this
+ /// element cannot be inferred.
#[test]
fn swapped_clr_map_is_read() {
let p = part(
@@ -1655,8 +1639,8 @@ mod tests {
}
/// `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.
+ /// default map here would shadow the master's real one on every slide
+ /// that carries the element.
#[test]
fn master_clr_mapping_override_is_inherit_not_default() {
let p = part(r#"<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>"#);
@@ -1707,10 +1691,9 @@ mod tests {
assert!(matches!(shapes[2].kind, ShapeKind::AutoShape(_)));
}
- /// The 2422/2422 corpus invariant, in miniature: no xfrm means `None`, not
- /// a rectangle at the origin. Inventing (0,0) here would put every
- /// unresolved placeholder in the top-left corner and look like a layout
- /// bug rather than a missing cascade.
+ /// No xfrm means `None`, not a rectangle at the origin. Inventing (0,0)
+ /// here would put every unresolved placeholder in the top-left corner
+ /// and look like a layout bug rather than a missing cascade.
#[test]
fn missing_xfrm_is_none_not_origin() {
let shapes = tree(&sp(r#"<p:spPr/><p:txBody><a:p/></p:txBody>"#));
@@ -1730,9 +1713,9 @@ mod tests {
}
/// §19.3.1.46. All four references, with the `phClr` substitute each one
- /// carries — the substitute is the load-bearing half, since every theme
- /// matrix entry on the corpus is written in terms of `phClr` and resolves
- /// to black without it.
+ /// carries — the substitute is the load-bearing half, since theme matrix
+ /// entries are routinely written in terms of `phClr` and resolve to
+ /// black without it.
#[test]
fn shape_style_lowers_all_four_references() {
let shapes = tree(&sp(r#"<p:spPr/><p:style>
@@ -1746,9 +1729,8 @@ mod tests {
assert_eq!(ln.idx, 2);
assert!(ln.color.is_some(), "the phClr substitute must survive");
assert_eq!(style.fill_ref.as_ref().expect("fillRef").idx, 1);
- // §20.1.4.2.19: 0 is the no-reference sentinel and is kept as declared,
- // not normalised away — 335 corpus `fillRef`s rely on the resolver
- // seeing it.
+ // §20.1.4.2.19: 0 is the no-reference sentinel and is kept as
+ // declared, not normalised away — the resolver needs to see it.
assert_eq!(style.effect_ref.as_ref().expect("effectRef").idx, 0);
assert!(style.font_ref.is_some(), "parsed, though unused for now");
}
@@ -1762,26 +1744,26 @@ mod tests {
assert!(shapes[0].style.is_none());
}
- /// `p:ph@idx` reaches exactly `u32::MAX` in 13 of the 45 corpus decks.
- /// A narrower integer wraps or hard-fails on all of them.
+ /// `p:ph@idx` can legally reach `u32::MAX`. A narrower integer would
+ /// wrap or hard-fail on it.
#[test]
fn placeholder_idx_holds_u32_max() {
- let shapes = tree(&format!(
+ let shapes = tree(
r#"<p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/>
- <p:nvPr><p:ph type="body" idx="4294967295"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>"#
- ));
+ <p:nvPr><p:ph type="body" idx="4294967295"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>"#,
+ );
assert_eq!(shapes[0].placeholder.as_ref().unwrap().idx, u32::MAX);
}
- /// §19.7.10 defaults. Both are absent on thousands of corpus shapes, and
- /// the cascade matches on them, so leaving them as `Option` would push the
+ /// §19.7.10 defaults. Both attributes are routinely absent, and the
+ /// cascade matches on them, so leaving them as `Option` would push the
/// same defaulting into every consumer.
#[test]
fn placeholder_defaults_to_body_index_zero() {
- let shapes = tree(&format!(
+ let shapes = tree(
r#"<p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/>
- <p:nvPr><p:ph/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>"#
- ));
+ <p:nvPr><p:ph/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>"#,
+ );
let ph = shapes[0].placeholder.as_ref().expect("placeholder");
assert_eq!(ph.kind, PlaceholderKind::Body);
assert_eq!(ph.idx, 0);
@@ -1789,13 +1771,13 @@ mod tests {
/// An unrecognised `@type` must not silently become `Body`: that would make
/// a typo indistinguishable from a real body placeholder and let it match
- /// the wrong master rung.
+ /// the wrong master placeholder.
#[test]
fn unknown_placeholder_type_is_distinguishable_from_body() {
- let shapes = tree(&format!(
+ let shapes = tree(
r#"<p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/>
- <p:nvPr><p:ph type="bogus"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>"#
- ));
+ <p:nvPr><p:ph type="bogus"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp>"#,
+ );
assert_eq!(
shapes[0].placeholder.as_ref().unwrap().kind,
PlaceholderKind::Unknown
@@ -1817,9 +1799,9 @@ mod tests {
}
}
- /// A graphic frame positions itself with `<p:xfrm>` as a direct child, not
- /// through `spPr` — 102/102 on the corpus. Reading it via `SpPrXml` finds
- /// nothing and stacks every table at the origin.
+ /// A graphic frame positions itself with `<p:xfrm>` as a direct child,
+ /// not through `spPr`. Reading it via `SpPrXml` finds nothing and
+ /// stacks every table at the origin.
#[test]
fn graphic_frame_transform_comes_from_p_xfrm() {
let shapes = tree(
@@ -1869,9 +1851,8 @@ mod tests {
assert!(table.rows[0].cells[1].is_absorbed());
}
- /// `a:tcPr` is where a cell's text placement lives, and it is not a rare
- /// element: 603 of 608 corpus cells declare one, 375 of them with a
- /// non-default margin and 326 with a non-top anchor.
+ /// `a:tcPr` is where a cell's text placement lives, and it is not a
+ /// rare element: non-default margins and non-top anchors are common.
#[test]
fn cell_properties_are_read_off_tc_pr() {
let shapes = tree(
@@ -1937,7 +1918,7 @@ mod tests {
assert!(bp.rotation.is_none() && bp.wrap.is_none() && bp.auto_fit.is_none());
}
- /// SmartArt/OLE/chart frames are 66 of 102 on the corpus. Typing them as
+ /// SmartArt/OLE/chart frames are unsupported payloads. Typing them as
/// `Unsupported` rather than dropping them keeps the gap countable.
#[test]
fn unsupported_graphic_frame_payload_keeps_its_uri() {
@@ -1984,7 +1965,7 @@ mod tests {
}
/// §19.3.1.23 — the group's own fill, which is what a member's `a:grpFill`
- /// inherits. 82 corpus groups declare a `solidFill` here.
+ /// inherits.
#[test]
fn group_fill_is_lowered() {
let shapes = tree(&format!(
@@ -2069,10 +2050,10 @@ mod tests {
);
}
- /// The corpus case that forced the rule: a `Requires="a14"` Choice holds
- /// the equation's real text runs, its Fallback holds a rasterized picture
- /// of the same equation. MCE says take the Fallback; that silently drops
- /// the text.
+ /// The case that forced the rule: a `Requires="a14"` Choice holds the
+ /// equation's real text runs, its Fallback holds a rasterized picture
+ /// of the same equation. MCE says take the Fallback; that silently
+ /// drops the text.
#[test]
fn alternate_content_prefers_the_branch_with_more_text() {
let shapes = tree(&format!(
@@ -2117,10 +2098,10 @@ mod tests {
assert_eq!(shapes.len(), 1, "exactly one branch survives");
}
- /// A `p:pic` can be a placeholder — 55 on the corpus — and 3 of them
- /// declare no `xfrm`, so the cascade is their only source of geometry.
- /// Reusing the DOCX `PictureXml`, which has no `p:nvPr`, drops this
- /// silently: the picture still parses, it just loses its position.
+ /// A `p:pic` can be a placeholder, and can declare no `xfrm` of its
+ /// own, so the cascade is its only source of geometry. Reusing the DOCX
+ /// `PictureXml`, which has no `p:nvPr`, drops this silently: the
+ /// picture still parses, it just loses its position.
#[test]
fn picture_placeholder_survives() {
let shapes = tree(
@@ -2175,8 +2156,7 @@ mod tests {
assert!(auto.is_text_box);
}
- /// A part with no `p:cSld` is empty, not an error — the fail-open posture
- /// this vendor has settled on four times over.
+ /// A part with no `p:cSld` is empty, not an error.
#[test]
fn part_without_a_shape_tree_is_empty_not_an_error() {
let xml =
@@ -2227,9 +2207,9 @@ mod tests {
}
/// `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.
+ /// cosmetic index: it selects the theme's *background* fill matrix.
+ /// Clamping or defaulting it here would push the bug down into the
+ /// resolver.
#[test]
fn bg_ref_keeps_its_thousand_offset_index() {
let part =
@@ -2351,7 +2331,7 @@ mod tests {
}
/// The schema default is `true`, and it is the *absence* of the attribute
- /// that carries it — a part that says nothing inherits its rung's shapes.
+ /// that carries it — a part that says nothing inherits the shapes above it.
#[test]
fn show_master_sp_defaults_to_true() {
assert!(show_inherited(""));
diff --git a/crates/liteparse-ooxml/src/pptx/text.rs b/crates/liteparse-ooxml/src/pptx/text.rs
index 2d43437..e210d0b 100644
--- a/crates/liteparse-ooxml/src/pptx/text.rs
+++ b/crates/liteparse-ooxml/src/pptx/text.rs
@@ -12,8 +12,7 @@
//!
//! A slide shape's text body is `<p:txBody>` (PresentationML); a table cell's
//! and a graphic frame's is `<a:txBody>` (DrawingML). Both are `CT_TextBody`
-//! with identical children, so one schema type serves both. On the corpus:
-//! `p:txBody` in 45/45 decks, `a:txBody` in 14/45.
+//! with identical children, so one schema type serves both.
//!
//! quick-xml's serde layer matches on the local name with the prefix dropped
//! (the property `pptx::package` documents the hard way for `r:id`), so both
@@ -28,7 +27,7 @@
//! because resolving it requires the placeholder cascade — shape `a:lstStyle`
//! → layout placeholder → master `p:txStyles` → presentation
//! `defaultTextStyle` — which is a separate step with a different match rule
-//! per rung. Run properties *are* lowered to [`model::RunProperties`]
+//! at each level. Run properties *are* lowered to [`model::RunProperties`]
//! immediately: every field there is `Option`, so it is already the right
//! carrier for unresolved direct formatting, and the cascade fills the `None`s
//! later via `FragmentCtx::paragraph_run_defaults`.
@@ -55,9 +54,9 @@ pub const MAX_LIST_LEVEL: u8 = 9;
///
/// Deliberately not `AttrBool` and not serde's `bool`:
///
-/// - serde's `bool` accepts only `"true"`/`"false"`, so `b="1"` — which is how
-/// PowerPoint writes it, in 44 of 45 corpus decks — would silently read as
-/// absent and lose every bold run.
+/// - serde's `bool` accepts only `"true"`/`"false"`, so `b="1"` — which is
+/// how PowerPoint actually writes it — would silently read as absent and
+/// lose every bold run.
/// - `AttrBool` maps anything unrecognised to `false`. Here that would be an
/// *explicit off* that overrides an inherited value, so a typo'd attribute
/// would strip bold that the master legitimately supplies.
@@ -87,7 +86,7 @@ pub struct TextBody {
/// verbatim with the DOCX textbox path.
pub body_pr: Option<BodyProperties>,
/// §21.1.2.4.12 `a:lstStyle` — this shape's own per-level overrides, the
- /// innermost rung of the cascade.
+ /// innermost level of the cascade.
pub list_style: ListStyle,
pub paragraphs: Vec<TextParagraph>,
}
@@ -235,9 +234,9 @@ pub enum Bullet {
},
}
-/// §20.1.10.61 ST_TextAutonumberScheme. Only the schemes the corpus actually
-/// uses are named; the rest round-trip through `Other` so an unrecognised
-/// scheme degrades to a plain number rather than killing the parse.
+/// §20.1.10.61 ST_TextAutonumberScheme. Only the schemes seen in practice
+/// are named; the rest round-trip through `Other` so an unrecognised scheme
+/// degrades to a plain number rather than killing the parse.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AutoNumberScheme {
/// `1.` `2.` `3.`
@@ -292,10 +291,10 @@ pub fn parse_text_body(data: &[u8]) -> Result<TextBody> {
/// §19.3.1.52 `p:txStyles` — a master's three whole-part text styles.
///
-/// The outer two rungs of the text cascade are *not* placeholder shapes.
+/// The outer two levels of the text cascade are *not* placeholder shapes.
/// A master carries one `p:txStyles` for the whole part, and a placeholder
/// reaches the right child by its **kind**, not by matching a shape. See
-/// [`pptx::textcascade`] for the routing and the corpus measurement behind it.
+/// [`pptx::textcascade`] for the routing.
///
/// [`pptx::textcascade`]: crate::pptx::textcascade
#[derive(Clone, Debug, Default)]
@@ -319,9 +318,9 @@ impl TextStyles {
/// Takes `p:sldMaster`'s bytes rather than the `p:txStyles` element, matching
/// [`parse_shape_tree`]: callers hold parts, not subtrees.
///
-/// A master with no `p:txStyles` yields an empty [`TextStyles`] rather than an
-/// error — the fail-open posture of this vendor. On the corpus all 70 masters
-/// declare one, so an empty result means something is genuinely unusual.
+/// A master with no `p:txStyles` yields an empty [`TextStyles`] rather than
+/// an error — masters routinely declare one, so an empty result means
+/// something is genuinely unusual, not a normal case to special-case around.
///
/// [`parse_shape_tree`]: crate::pptx::parse_shape_tree
pub fn parse_text_styles(data: &[u8]) -> Result<TextStyles> {
@@ -336,15 +335,13 @@ pub fn parse_text_styles(data: &[u8]) -> Result<TextStyles> {
///
/// SmartArt is the one payload whose content is not in the slide at all: the
/// `p:graphicFrame` carries only `dgm:relIds`, and `@r:dm` points here. A
-/// shape-tree walk therefore cannot see any of it — on the corpus that is
-/// **53 parts, all 53 carrying text, 12,102 characters**, which made it the
+/// shape-tree walk therefore cannot see any of it, which made SmartArt the
/// largest single content gap for a native reader.
///
/// Returns one [`TextBody`] per `dgm:pt` that has one, in document order.
-/// Nothing is filtered: the corpus says every text-bearing point is untyped
-/// (334 of 334), so the `doc` and `pres` presentation nodes contribute nothing
-/// and there is no duplication to guard against — 2 repeated strings across
-/// the whole corpus, both genuine.
+/// Nothing is filtered by node type: text-bearing points are untyped in
+/// practice, so the `doc` and `pres` presentation nodes contribute nothing
+/// and there is no duplication to guard against.
///
/// The caller resolves the relationship, because relationship resolution needs
/// the owning [`Part`](crate::pptx::Part) and this layer only sees bytes.
@@ -385,11 +382,11 @@ struct DiagramPtXml {
/// Parse `p:defaultTextStyle` out of a **whole `ppt/presentation.xml` part**.
///
-/// The outermost rung, and the only one a non-placeholder shape can reach:
-/// 2,144 of the 2,301 corpus runs on non-placeholder shapes that declare no
-/// size get it from here, so this is not a rare fallback.
+/// The outermost level, and the only one a non-placeholder shape can reach:
+/// most non-placeholder runs that declare no size get it from here, so this
+/// is not a rare fallback.
///
-/// Absent yields an empty [`ListStyle`]; 45 of 45 corpus decks declare one.
+/// Absent yields an empty [`ListStyle`].
pub fn parse_default_text_style(data: &[u8]) -> Result<ListStyle> {
let xml: PresentationStylesXml = serde_xml::from_xml(data)?;
Ok(xml
@@ -400,9 +397,8 @@ pub fn parse_default_text_style(data: &[u8]) -> Result<ListStyle> {
// ── Schema ───────────────────────────────────────────────────────────────────
//
-// Field coverage is driven by a census over the 45-deck corpus rather than by
-// reading the spec front to back: every element and attribute below appears in
-// at least one real deck. Anything absent from the corpus is left to serde's
+// Field coverage is driven by what real decks actually use rather than by
+// reading the spec front to back. Anything not modelled is left to serde's
// unknown-field tolerance, matching the fail-open posture ATTRIBUTION.md
// records for the DOCX vendor.
@@ -619,9 +615,9 @@ struct BreakXml {
r_pr: Option<TextCharPropertiesXml>,
}
-/// §21.1.2.2.4 `a:fld` — a text field (slide number, date, …). Present in
-/// 44/45 corpus decks, so dropping it would silently lose the footer line on
-/// nearly every deck.
+/// §21.1.2.2.4 `a:fld` — a text field (slide number, date, …). Common in
+/// footer placeholders, so dropping it would silently lose the footer line
+/// on most decks.
///
/// The element carries both a `@type` instruction and an `a:t` holding the
/// value PowerPoint last rendered. We take the cached `a:t`: it is what the
@@ -807,7 +803,7 @@ impl SpacingXml {
fn into_model(self) -> Option<Spacing> {
// §20.1.10.65 is a choice, but a producer emitting both should not
// pick arbitrarily — percent is the PowerPoint-authored default and
- // the one the corpus actually carries (42/45 decks).
+ // by far the more common of the two in practice.
if let Some(pct) = self.spc_pct.and_then(|v| v.val) {
return Some(Spacing::Percent(pct));
}
@@ -948,8 +944,8 @@ struct TextCharPropertiesXml {
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.
+ /// than re-declared — an srgb-only local type would silently drop every
+ /// run whose colour is a scheme reference rather than a literal RGB.
#[serde(rename = "solidFill", default)]
solid_fill: Option<SolidFillXml>,
#[serde(rename = "latin", default)]
@@ -1103,9 +1099,9 @@ impl TextFontXml {
}
}
-/// §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.
+/// §20.1.10.82 ST_TextUnderlineType — a large enum of which only the common
+/// values are modelled. Unlisted values fall through `lenient::opt_attr` to
+/// `None` (= inherit), per ECMA-376 §17.17.
#[derive(Clone, Copy, Debug, Deserialize)]
enum StTextUnderlineType {
#[serde(rename = "none")]
@@ -1216,8 +1212,8 @@ mod tests {
assert_eq!(b.paragraphs[0].text(), "one\ntwo");
}
- /// `a:fld` appears in 44/45 corpus decks; dropping it loses the footer
- /// line almost everywhere.
+ /// `a:fld` is common in footer placeholders; dropping it loses the
+ /// footer line almost everywhere it's used.
#[test]
fn field_emits_its_cached_value() {
let b = body(r#"<a:p><a:fld id="{1}" type="slidenum"><a:t>7</a:t></a:fld></a:p>"#);
@@ -1387,9 +1383,9 @@ mod tests {
}
/// 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.
+ /// and the master's `p:clrMap`, neither of which is a property of the
+ /// run. Dropping it here would read downstream as "no colour declared"
+ /// and paint the run black.
#[test]
fn scheme_color_is_carried_unresolved() {
let b = body(
diff --git a/crates/liteparse-ooxml/src/pptx/textcascade.rs b/crates/liteparse-ooxml/src/pptx/textcascade.rs
index f133eb0..8d02357 100644
--- a/crates/liteparse-ooxml/src/pptx/textcascade.rs
+++ b/crates/liteparse-ooxml/src/pptx/textcascade.rs
@@ -8,19 +8,17 @@
//!
//! It is the sibling of [`pptx::cascade`], which does the same job for
//! geometry, and it reuses that module's [`MatchRule`] verbatim. It differs
-//! from it in three ways that a shared implementation would have got wrong,
-//! each measured on the 45-deck corpus before any of this was written.
+//! from it in three ways that a shared implementation would have got wrong.
//!
//! [`pptx::cascade`]: crate::pptx::cascade
//!
//! ## 1. The merge is per-property, not whole-value
//!
//! Geometry inherits a whole `Transform2D` because a transform is never
-//! partial — 0 counterexamples on the corpus. Text is the opposite: **5,954
-//! layout `a:lstStyle` levels supply a size *and* other properties, and 5,232
-//! supply properties but no size.** A rung that answers "bold" and stays silent
-//! on "size" is the common case, so every property resolves independently and
-//! the walk continues past a rung that answered partially.
+//! partial. Text is the opposite: a layout `a:lstStyle` level routinely
+//! supplies some properties but not others — bold and silence on size is
+//! the common case — so every property resolves independently and the walk
+//! continues past a rung that answered partially.
//!
//! That merge is [`merge_run_properties`], vendored for DOCX and field-complete
//! (its `merge_run_all_fields_covered` test is the guard). Text inheritance in
@@ -45,42 +43,37 @@
//! `defaultTextStyle` is simply deck-wide.
//!
//! **Rung 5 is the one that would have been dropped.** It looks redundant
-//! beside rung 6, and python-pptx's documented chain omits it. The corpus says
-//! otherwise: of the 150 master placeholders carrying their own size, **742
-//! level-values disagree with what `p:txStyles` says and only 29 agree** —
-//! including a `bodyStyle` reading 32pt against `p:txStyles`' 14pt. Skipping
-//! this rung would not have been a rounding error, it would have been 2.3x
-//! wrong on real slides.
+//! beside rung 6, and python-pptx's documented chain omits it. In practice
+//! a master placeholder's own size routinely disagrees with what
+//! `p:txStyles` says for the same kind — sometimes by a wide margin (e.g. a
+//! `bodyStyle` reading 32pt against `p:txStyles`' 14pt) — so skipping this
+//! rung would produce real, not just cosmetic, size errors.
//!
-//! ## 3. Non-placeholder shapes are 41% of the need and no matcher can see them
+//! ## 3. Non-placeholder shapes are a large fraction of the need and no matcher can see them
//!
-//! 2,301 of the 5,566 size-less corpus runs sit on shapes with **no `p:ph` at
-//! all**, so rungs 4-6 do not exist for them. Their chain was traced end to end
-//! rather than assumed, and it closes exactly:
+//! A great many size-less runs sit on shapes with **no `p:ph` at all**, so
+//! rungs 4-6 do not exist for them. Their chain was traced end to end
+//! rather than assumed, and closes on exactly three suppliers:
//!
-//! | supplier | runs |
-//! |---|---|
-//! | shape's own `a:lstStyle` (rung 3) | 123 |
-//! | presentation `defaultTextStyle` (rung 7) | 2,144 |
-//! | nothing — spec default (rung 8) | 34 |
-//!
-//! The 34 are from exactly 2 decks whose `p:defaultTextStyle` declares no
-//! size at level 1. That residue is *classified*, not a mystery, and
-//! [`SizeSource::SpecDefault`] is how it stays visible.
+//! - the shape's own `a:lstStyle` (rung 3)
+//! - the presentation's `defaultTextStyle` (rung 7) — by far the largest
+//! supplier for this population
+//! - nothing, landing on the spec default (rung 8) — [`SizeSource::SpecDefault`]
+//! is how that residue stays visible rather than a silent guess
//!
//! **The theme rung does not exist.** §20.1.6.7's `a:objectDefaults` is the
-//! obvious place for a non-placeholder shape's text defaults, and 91 corpus
-//! themes declare one (10 `a:spDef`, 8 `a:txDef`). **Not one supplies a font
-//! size.** So it is not implemented — measured, not assumed, and recorded here
-//! so the next reader does not re-derive it.
+//! obvious place for a non-placeholder shape's text defaults, but decks that
+//! declare one do not use it to supply a font size in practice. So it is
+//! not implemented, and that is a deliberate, measured omission rather than
+//! an oversight.
//!
//! ## The chain terminates
//!
-//! For placeholders it terminates before the spec default ever applies: all
-//! 3,463 corpus (kind, level) pairs a slide actually uses are covered by the
-//! master's `p:txStyles`, and all 70 masters declare all three children with a
-//! size at level 1. As with geometry's "no master placeholder lacks an
-//! `xfrm`", the top of the chain is real.
+//! For placeholders it terminates before the spec default ever applies:
+//! every (kind, level) pair a slide actually uses is expected to be
+//! covered by the master's `p:txStyles`, and every master is expected to
+//! declare all three children with a size at level 1. As with geometry's
+//! "no master placeholder lacks an `xfrm`", the top of the chain is real.
use std::collections::HashMap;
@@ -94,9 +87,9 @@ use super::text::{Bullet, ListStyle, Spacing, TextParagraphProperties, TextStyle
/// §21.1.2.2.9 — `a:defRPr/@sz` defaults to 1800, i.e. 18pt.
///
-/// Only reachable when every rung above stays silent; on the corpus that is 34
-/// runs in 2 decks. Emitting it is right, but a consumer that wants to know
-/// should read [`SizeSource`] rather than compare against this constant.
+/// Only reachable when every rung above stays silent, which should be rare.
+/// Emitting it is right, but a consumer that wants to know should read
+/// [`SizeSource`] rather than compare against this constant.
pub const SPEC_DEFAULT_FONT_SIZE: Dimension<HalfPoints> = Dimension::new(36);
/// Which `p:txStyles` child a placeholder kind reads (rung 6).
@@ -114,7 +107,6 @@ pub enum TextStyleClass {
}
impl TextStyleClass {
- /// The corpus exercises all three: 868 title, 714 body, 348 other.
pub fn of(kind: PlaceholderKind) -> Self {
use PlaceholderKind::*;
match kind {
@@ -146,9 +138,9 @@ impl TextStyleClass {
/// It does **not** pre-flatten the two rungs the way `PlaceholderGeometry`
/// does. Flattening is only sound when a rung either answers or does not;
/// here a rung answers *some* properties, so folding the master into the
-/// layout would lose which of the two supplied what, and rung 5's 742
-/// disagreements are exactly the values that would be silently misattributed.
-/// The walk visits both in order instead.
+/// layout would lose which of the two supplied what — and rung 5's
+/// disagreements with `p:txStyles` are exactly the values that would be
+/// silently misattributed. The walk visits both in order instead.
///
/// [`PlaceholderGeometry`]: crate::pptx::cascade::PlaceholderGeometry
#[derive(Clone, Debug, Default)]
@@ -174,8 +166,8 @@ impl PlaceholderTextStyles {
if style.is_empty() {
continue;
}
- // First in document order wins, as in the geometry cascade: 4
- // corpus layouts declare the same `@idx` twice, and a stable rule
+ // First in document order wins, as in the geometry cascade: a
+ // layout can declare the same `@idx` twice, and a stable rule
// beats a `HashMap`-iteration coin flip.
out.by_idx.entry(ph.idx).or_insert_with(|| style.clone());
out.by_kind
@@ -244,8 +236,8 @@ pub enum SizeSource {
MasterTextStyles,
/// Rung 7.
DefaultTextStyle,
- /// Rung 8 — nothing in the document supplied one. 34 corpus runs across 2
- /// decks. A non-trivial count here means a rung is not being reached.
+ /// Rung 8 — nothing in the document supplied one. Should be rare; a
+ /// non-trivial count here means a rung is not being reached.
SpecDefault,
}
@@ -477,7 +469,7 @@ mod tests {
assert_eq!(r.size_source, SizeSource::SpecDefault);
}
- /// The 2,144-run path: a non-placeholder shape reaches `defaultTextStyle`
+ /// The common non-placeholder path: a shape reaches `defaultTextStyle`
/// and nothing between.
#[test]
fn a_non_placeholder_shape_reaches_default_text_style() {
@@ -537,7 +529,7 @@ mod tests {
}
/// The layout rung matches on `@idx` and ignores `@type`, exactly as the
- /// geometry cascade does — the same 2-of-737 bare-`<p:ph/>` case.
+ /// geometry cascade does — the same bare-`<p:ph/>` case.
#[test]
fn the_layout_rung_matches_idx_not_type() {
let layout_shapes = part(&[
@@ -557,8 +549,8 @@ mod tests {
assert_eq!(r.size_source, SizeSource::LayoutPlaceholder);
}
- /// Rung 5, the one that looks redundant. 742 corpus level-values disagree
- /// with `p:txStyles`; the master placeholder must win.
+ /// Rung 5, the one that looks redundant. A master placeholder's own
+ /// size can disagree with `p:txStyles`; the master placeholder must win.
#[test]
fn the_master_placeholder_rung_beats_tx_styles() {
let master_shapes = part(&[("body", "1", r#"<a:defRPr sz="3200"/>"#)]);
@@ -647,8 +639,8 @@ mod tests {
}
/// The finding that separates this cascade from the geometry one: a rung
- /// answers *some* properties and the walk continues past it for the rest.
- /// 5,232 corpus layout levels supply properties but no size.
+ /// answers *some* properties and the walk continues past it for the
+ /// rest. A layout level supplying properties but no size is common.
#[test]
fn a_partial_rung_does_not_stop_the_walk() {
// Layout says bold and centred, but nothing about size.
@@ -863,7 +855,7 @@ mod tests {
}
/// Duplicate `@idx`: first in document order wins, matching the geometry
- /// cascade's rule on the same 4 corpus layouts.
+ /// cascade's rule.
#[test]
fn duplicate_idx_resolves_first_in_document_order() {
let shapes = part(&[
diff --git a/crates/liteparse-ooxml/src/render/emoji/cluster.rs b/crates/liteparse-ooxml/src/render/emoji/cluster.rs
index fcad327..67a5c17 100644
--- a/crates/liteparse-ooxml/src/render/emoji/cluster.rs
+++ b/crates/liteparse-ooxml/src/render/emoji/cluster.rs
@@ -362,10 +362,9 @@ mod tests {
// ─── Default-text emoji codepoint regression tests ───────────────────────
//
// Per UTS #51 emoji-data.txt: digits 0-9, '#', '*' have Emoji=YES with
- // default-text presentation. A prior version of the classifier returned
- // them as `InlineCluster::Emoji` with `presentation: Text`, which still
- // routed them through the color emoji rasterizer downstream — corrupting
- // page numbers, IBANs, dates, and any other digit-bearing text.
+ // default-text presentation. Classifying them as `InlineCluster::Emoji`
+ // would route them through the color emoji rasterizer downstream,
+ // corrupting page numbers, IBANs, dates, and any other digit-bearing text.
/// Standalone digit must be plain text — no rasterization.
#[test]
diff --git a/crates/liteparse-ooxml/src/render/error.rs b/crates/liteparse-ooxml/src/render/error.rs
index 07516c1..c578c36 100644
--- a/crates/liteparse-ooxml/src/render/error.rs
+++ b/crates/liteparse-ooxml/src/render/error.rs
@@ -2,18 +2,13 @@
/// Errors that can occur during rendering.
///
-/// There is exactly one, and it is the only condition the pipeline cannot
-/// render its way out of. Emptiness is deliberately *not* one: a document with
-/// no content produces a single blank page (`render::layout_document`), which
-/// is what Word does — so the `EmptyDocument` variant this type used to carry
-/// was not merely unconstructed, it contradicted the behaviour the pipeline
-/// had chosen.
+/// An empty document is not an error: it produces a single blank page
+/// (`render::layout_document`), matching Word's behavior.
#[derive(Debug)]
pub enum RenderError {
/// The host font system exposes no typeface at all, so there is nothing to
/// fall back to when a requested family cannot be resolved. Seen on
- /// container images built without any fonts installed, and with a
- /// deliberately empty `FontMgr`.
+ /// container images built without any fonts installed.
NoFontsAvailable,
}
diff --git a/crates/liteparse-ooxml/src/render/fonts.rs b/crates/liteparse-ooxml/src/render/fonts.rs
index a776bea..4ba5391 100644
--- a/crates/liteparse-ooxml/src/render/fonts.rs
+++ b/crates/liteparse-ooxml/src/render/fonts.rs
@@ -1,29 +1,25 @@
//! Font resolution with per-render ownership (`FontRegistry`) — fontdb + skrifa.
//!
-//! Upstream this module is a 1,300-line registry built on Skia's `FontMgr`.
-//! This is the C′ rewrite: same public surface as far as the layout engine
-//! consumes it, with resolution answered by `fontdb` and metrics/advances by
-//! `skrifa` (see `layout::measurer`). It is the one production seam between
-//! dxpdf's layout engine and Skia — everything else in `render/layout/` is
-//! vendored verbatim.
+//! Same public surface as the upstream Skia-based registry, but resolution
+//! is answered by `fontdb` and metrics/advances by `skrifa` (see
+//! `layout::measurer`). It is the one seam between dxpdf's layout engine and
+//! Skia — everything else in `render/layout/` is vendored verbatim.
//!
-//! The resolution rules and their ordering are not invented here: they were
-//! derived and measured in `bench/docx_layout_spike` (spikes 6–8, recorded in
-//! `NATIVE_OFFICE_PLAN.md`). Where both engines have the requested face,
-//! agreement with Skia is 99.8% on widths and bit-exact on line metrics; every
-//! divergence beyond that was a *resolution* difference, which is why this
-//! file is mostly resolution policy and hardly any arithmetic.
+//! Where both engines have the requested face, results agree closely on
+//! widths and are bit-exact on line metrics; divergences beyond that trace to
+//! a *resolution* difference, which is why this file is mostly resolution
+//! policy and hardly any arithmetic.
//!
-//! ## Host-dependence (decision, 2026-08-13)
+//! ## Host-dependence
//!
//! Geometry from this registry is deliberately **host-dependent** for
//! documents whose fonts the host lacks: no fonts are bundled and no checksum
-//! pinning is done. Spike 8 proved a family name does not pin a font (two
-//! "Caladea"s differ by ~7% in advances), so determinism would require
-//! shipping files — a cost the project declined. What this file guarantees
-//! instead is *visibility*: every resolution records which [`ResolveRule`]
-//! answered, and only `Embedded`, `Exact`, alias/suffix hits and
-//! `Substitution(Metric)` claim to be reproducible across hosts.
+//! pinning is done. A family name does not pin a font (two "Caladea"s can
+//! differ by several percent in advances), so determinism would require
+//! shipping font files — a cost the project declined. What this file
+//! guarantees instead is *visibility*: every resolution records which
+//! [`ResolveRule`] answered, and only `Embedded`, `Exact`, alias/suffix hits
+//! and `Substitution(Metric)` claim to be reproducible across hosts.
use std::cell::RefCell;
use std::collections::HashMap;
@@ -80,12 +76,6 @@ impl FontStyle {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EmbeddedFontId(u32);
-impl EmbeddedFontId {
- pub fn raw(self) -> u32 {
- self.0
- }
-}
-
/// Identity for a resolved face — wraps the `fontdb` id. Used as a cache key
/// by the measurer's cluster-advance memo.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
@@ -155,15 +145,14 @@ pub enum RegisterError {
},
}
-// ─── Resolution rules (spike 6/8 artifacts) ─────────────────────────────────
+// ─── Resolution rules ───────────────────────────────────────────────────────
/// Whether a substitute reproduces the original's *metrics* or merely its look.
///
-/// This distinction is the whole point of the table, not a nicety. Spike 7
-/// measured the cost of getting it wrong: Helvetica standing in for Arial is
-/// metric-compatible in **advances** (so a width test sees nothing) and off by
-/// **+14.99% in line metrics** (1.0000 em vs 1.1499 em) — a one-directional
-/// bias that compounds down every page.
+/// This distinction is the whole point of the table, not a nicety: Helvetica
+/// standing in for Arial is metric-compatible in **advances** (so a width
+/// test sees nothing) but off by **+14.99% in line metrics** (1.0000 em vs
+/// 1.1499 em) — a one-directional bias that compounds down every page.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SubstKind {
/// Designed as a drop-in: same upem, same advances, same line metrics.
@@ -241,8 +230,7 @@ impl ResolveRule {
///
/// Deliberately excludes `roman` and `book`: "Times New Roman" and "Century
/// Schoolbook" are families whose last word *is* a style word, and stripping
-/// it sends the query somewhere that does not exist. This cost spike 6 a run —
-/// the fix looked inert because it had quietly broken its own best case.
+/// it sends the query somewhere that does not exist.
/// `black` and `light` stay in only because stripping is attempted after an
/// exact family match has already failed, so "Arial Black" is never reached by
/// this path on a host that has it.
@@ -281,9 +269,9 @@ fn suffix_weight(word: &str) -> Option<u16> {
/// A request for 600 becomes 100, the lightest weight in the file.
///
/// Where several style words are stripped, the **rightmost** weight-bearing
-/// one wins. Real names put the specific word last ("Open Sans Light"), and
-/// the only corpus case with two ("Albert Sans Regular Light") is a mangled
-/// name where Light is the operative half.
+/// one wins. Real names put the specific word last ("Open Sans Light"); a
+/// mangled name with two ("Albert Sans Regular Light") treats Light as the
+/// operative half.
fn strip_style_suffix(family: &str) -> Option<(String, Option<u16>)> {
let mut words: Vec<&str> = family.split_whitespace().collect();
let mut stripped = false;
@@ -313,11 +301,10 @@ fn strip_style_suffix(family: &str) -> Option<(String, Option<u16>)> {
/// convert a visible "this host fell back to a generic" into an invisible
/// wrong answer. Absent families must stay loud.
///
-/// The URW / TeX Gyre rows are all `Visual`, and that was **measured, not
-/// assumed** (spike 8): the whole set is advance-compatible with the
-/// PostScript base 35 and line-metric-incompatible (every face reports
-/// `lh = 1.200 em` against 1.000 em for the originals). Same trap as
-/// Helvetica-for-Arial, one layer down.
+/// The URW / TeX Gyre rows are all `Visual`: the whole set is
+/// advance-compatible with the PostScript base 35 but line-metric-incompatible
+/// (every face reports `lh = 1.200 em` against 1.000 em for the originals).
+/// Same trap as Helvetica-for-Arial, one layer down.
///
/// Trap encoded in the table itself: `Helvetica` and `Arial` must not point at
/// the same clones the same way round. Liberation Sans clones **Arial** (so it
@@ -620,8 +607,6 @@ fn merged_alias_weight(alias_weight: u16, requested_weight: u16) -> u16 {
#[derive(Debug, Clone)]
struct EmbeddedRecord {
- family: String,
- variant: EmbeddedFontVariant,
face: Option<fontdb::ID>,
}
@@ -684,19 +669,9 @@ impl FontRegistry {
&self.db
}
- pub fn embedded_font_count(&self) -> usize {
- self.embedded.len()
- }
-
- pub fn cached_typeface_count(&self) -> usize {
- self.typefaces.borrow().len()
- }
-
/// Register an embedded font. Subsequent `resolve` calls for the same
- /// family + variant return this face in preference to system resolution —
- /// dxpdf registers embedded fonts ahead of system resolution, and spike 6
- /// found the one embedded-font document in the corpus (Georgia) agreeing
- /// only by luck without this ordering.
+ /// family + variant return this face in preference to system resolution,
+ /// matching dxpdf's own ordering.
pub fn register_embedded(
&mut self,
family: &str,
@@ -714,23 +689,13 @@ impl FontRegistry {
});
}
let id = EmbeddedFontId(self.embedded.len() as u32);
- self.embedded.push(EmbeddedRecord {
- family: family.to_string(),
- variant,
- face,
- });
+ self.embedded.push(EmbeddedRecord { face });
self.embedded_index
.insert((family.to_lowercase(), variant), id);
log::debug!("registered embedded font '{}' {:?}", family, variant);
Ok(id)
}
- /// Family + variant for a registered embedded font.
- pub fn embedded_meta(&self, id: EmbeddedFontId) -> (&str, EmbeddedFontVariant) {
- let r = &self.embedded[id.0 as usize];
- (&r.family, r.variant)
- }
-
/// Resolve a typeface by family + style. Embedded fonts win over system.
/// Cached after the first resolution; later calls are O(1).
pub fn resolve(&self, family: &str, style: FontStyle) -> TypefaceEntry {
@@ -827,9 +792,9 @@ impl FontRegistry {
//
// The *query* keeps the run's own style, deliberately: feeding the
// stripped weight into it would change which face a static family
- // resolves to, corpus-wide, on a step whose whole warrant is variable
- // fonts. The stripped weight goes only to the variation coordinate,
- // where it can affect nothing that does not carry an axis.
+ // resolves to, on a step whose whole warrant is variable fonts. The
+ // stripped weight goes only to the variation coordinate, where it
+ // can affect nothing that does not carry an axis.
if let Some((base, suffix_wght)) = strip_style_suffix(family)
&& let Some(id) = self.query(&[fontdb::Family::Name(&base)], style)
{
@@ -938,15 +903,6 @@ impl FontRegistry {
}
}
}
-
- /// Snapshot of all cached entries.
- pub fn cached_entries(&self) -> Vec<(TypefaceKey, TypefaceEntry)> {
- self.typefaces
- .borrow()
- .iter()
- .map(|(k, v)| (k.clone(), v.clone()))
- .collect()
- }
}
impl Default for FontRegistry {
@@ -1030,7 +986,7 @@ mod tests {
strip_style_suffix("Open Sans Light"),
Some(("Open Sans".to_string(), Some(300)))
);
- // Rightmost weight word wins: this mangled name is in the corpus.
+ // Rightmost weight word wins on a mangled multi-word name too.
assert_eq!(
strip_style_suffix("Albert Sans Regular Light"),
Some(("Albert Sans".to_string(), Some(300)))
diff --git a/crates/liteparse-ooxml/src/render/layout/build/convert.rs b/crates/liteparse-ooxml/src/render/layout/build/convert.rs
index d82978b..6b751fa 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/convert.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/convert.rs
@@ -105,26 +105,16 @@ pub(super) fn resolve_paragraph_defaults(
}
/// §17.3.2.20 / §17.7.2: the language in effect for a paragraph's own layout
-/// decisions.
+/// decisions (e.g. the separator of a §17.18.85 `decimal` tab stop).
///
/// The cascade is the paragraph **mark**'s `w:rPr`, then the paragraph style's
-/// run defaults, then `docDefaults` — the same order §17.7.2 resolves any other
-/// run property in, minus the runs themselves.
-///
-/// Leaving the runs out is deliberate, and is the one judgement call in
-/// threading locale. The decisions this answers belong to the *paragraph*: a
-/// §17.18.85 `decimal` stop is declared in `w:pPr/w:tabs`, and its zone may span
-/// several runs that each declare a different `w:lang` — there is no single
-/// run to ask. The paragraph mark is the nearest thing the file offers to
-/// "the language of this paragraph", and it is already what the §17.9.22 list
-/// label reads its formatting from, so the two agree.
-///
-/// Word itself is reported to take a decimal tab's separator from the host's
-/// regional settings rather than from the document at all, which a converter
-/// cannot reproduce and should not want to: the same file would render
-/// differently on two machines. This reading is deterministic and keyed to the
-/// document instead — but it is an assumption, not a verified match, and has
-/// never been checked against a Word render.
+/// run defaults, then `docDefaults` — the same order §17.7.2 uses for any run
+/// property, minus the runs. Runs are excluded deliberately: a decimal tab zone
+/// may span several runs with differing `w:lang`, so there is no single run to
+/// ask; the paragraph mark is the file's closest thing to "the language of this
+/// paragraph", and is also what the §17.9.22 list label reads. Keying to the
+/// document (rather than the host's regional settings, as Word reportedly does)
+/// keeps the render deterministic across machines.
pub(super) fn paragraph_locale(
para: &model::Paragraph,
resolved: &ResolvedDocument,
@@ -188,8 +178,7 @@ pub(super) fn paragraph_outline(
///
/// The §17.9.22 list label is deliberately absent: it is injected at layout,
/// not part of the paragraph, and both Word and LibreOffice title a numbered
-/// heading with its text alone (measured against the reference PDF attached to
-/// issue #90).
+/// heading with its text alone.
fn outline_title(inlines: &[model::Inline]) -> String {
fn walk(inlines: &[model::Inline], out: &mut String) {
for inline in inlines {
diff --git a/crates/liteparse-ooxml/src/render/layout/build/floating.rs b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
index c68a327..ebb9963 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/floating.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
@@ -50,8 +50,8 @@ pub(super) enum AnchorFrame {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ShapeAnchorClass {
/// Take every wsp shape regardless of its vertical anchor. Used by
- /// body paragraphs and table cells, where the legacy single-channel
- /// behaviour is still in effect.
+ /// body paragraphs and table cells, which route all shapes through one
+ /// channel.
All,
/// Only shapes whose vertical anchor is `paragraph` or `line`.
ParagraphAnchored,
@@ -60,12 +60,11 @@ pub(super) enum ShapeAnchorClass {
PageAnchored,
}
-/// Extract floating (anchor) images from a paragraph's inlines.
-///
-/// Positions are resolved in the coordinate system implied by `frame`
-/// (see [`AnchorFrame`]).
use crate::render::layout::{McBranch, live_mc_branch};
+/// Collect anchored inline images (excluding `wps:wsp` shapes, which
+/// `find_anchor_shapes` owns), recursing through hyperlinks, fields, and the
+/// live MCE branch.
fn find_anchor_images<'a>(
inlines: &'a [crate::model::Inline],
out: &mut Vec<&'a crate::model::Image>,
@@ -99,6 +98,8 @@ fn find_anchor_images<'a>(
}
}
+/// Extract floating (anchor) images from a paragraph's inlines, with positions
+/// resolved in the coordinate system implied by `frame` (see [`AnchorFrame`]).
pub(super) fn extract_floating_images(
para: &Paragraph,
ctx: &BuildContext,
@@ -154,10 +155,8 @@ pub(super) fn extract_floating_images(
// ── Floating shape extraction ──────────────────────────────────────────────
-/// Extract floating (anchor) DrawingML shapes from a paragraph's inlines,
-/// resolve their geometry + visuals, and compute their positions in the
-/// coordinate frame implied by `frame`. Pure: takes immutable references to
-/// `ctx` / `state`.
+/// Collect anchored inline images whose graphic is a `wps:wsp` shape,
+/// recursing through hyperlinks, fields, and the live MCE branch.
fn find_anchor_shapes<'a>(
inlines: &'a [crate::model::Inline],
out: &mut Vec<&'a crate::model::Image>,
@@ -293,7 +292,6 @@ pub(super) fn extract_floating_shapes(
wrap_mode: crate::render::layout::section::WrapMode::from_model(&anchor.wrap),
dist_left: Pt::from(anchor.distance.left),
dist_right: Pt::from(anchor.distance.right),
- behind_doc: anchor.behind_text,
paths: shape_path.paths,
fill: visuals.fill,
stroke: visuals.stroke,
@@ -311,16 +309,6 @@ pub(super) fn extract_floating_shapes(
shapes
}
-/// Walk the inlines for `Inline::Pict` containers and emit a
-/// [`FloatingShape`] for every renderable VML primitive variant.
-/// Phase B handles `<v:rect>`; later phases can extend this to
-/// `RoundRect`, `Oval`, `Line`, `PolyLine`, `Image`, and grouped
-/// children.
-///
-/// Position resolution uses [`vml_absolute_position`] — currently
-/// page-relative when `position:absolute` and `margin-left`/
-/// `margin-top` are present. The vorlage gray-bar pattern fits this
-/// shape exactly.
/// Walk inlines for VML primitives that resolve to images
/// (`<v:image>` or a `<v:shape type="#_x0000_t75">` whose only child
/// is `<v:imagedata>`). Both forms reach this code path through
@@ -345,11 +333,9 @@ fn extract_vml_floating_images(
extract_vml_floating_images(&link.content, state, frame, ctx, out)
}
Inline::Field(f) => extract_vml_floating_images(&f.content, state, frame, ctx, out),
- // §M.1.2: exactly one branch is live and [`live_mc_branch`] is the
- // only thing that decides which. This arm used to be `{}` — a
- // third answer, given by not answering — so a Choice we could not
- // draw plus a Fallback holding a VML image left the anchor with no
- // geometry at all while its text still reached the page.
+ // §M.1.2: exactly one branch is live; [`live_mc_branch`] decides
+ // which. Must recurse into it — skipping the element would drop a
+ // Fallback VML image whose Choice we could not draw.
Inline::AlternateContent(ac) => match live_mc_branch(ac) {
McBranch::Choices(choices) => {
for choice in choices {
@@ -456,13 +442,11 @@ fn extract_vml_primitive_shapes(
}
Inline::Field(f) => extract_vml_primitive_shapes(&f.content, state, frame, out),
// §M.1.2: `<mc:AlternateContent>` carries the same shape twice —
- // modern DrawingML in `<mc:Choice>`, a VML fallback in
- // `<mc:Fallback>` — so drawing both emits one rectangle twice.
- // Skipping the element outright avoided that and created the
- // opposite bug: a Choice we cannot draw left the Fallback's rect
- // unrendered, which is the "future case" the note here used to
- // anticipate. [`live_mc_branch`] is now that Choice-fed signal,
- // and the same one `find_anchor_shapes` asks.
+ // DrawingML in `<mc:Choice>`, VML in `<mc:Fallback>`. Draw only the
+ // live branch: drawing both would emit one rectangle twice, and
+ // skipping the element would drop a Fallback rect whose Choice we
+ // cannot draw. [`live_mc_branch`] picks the branch, the same one
+ // `find_anchor_shapes` asks.
Inline::AlternateContent(ac) => match live_mc_branch(ac) {
McBranch::Choices(choices) => {
for choice in choices {
@@ -492,23 +476,20 @@ fn extract_vml_primitive(
out.push(shape);
}
}
- // §14.1.2.17 `<v:roundrect>`: rounded-corner variant. The
- // corner radius is `arcsize * min(width, height) / 2` —
- // small radii barely distinguish from a plain rect at typical
- // doc resolutions, so for Tier 0 we render as a plain
- // rectangle. The `arcsize` value survives in the model for a
- // future rounded-path build.
+ // §14.1.2.17 `<v:roundrect>`: rounded-corner variant. Small corner
+ // radii barely distinguish from a plain rect at typical doc
+ // resolutions, so render as a plain rectangle; `arcsize` survives in
+ // the model for a future rounded-path build.
VmlPrimitive::RoundRect(r) => {
if let Some(shape) = build_vml_rect_shape(&r.common, state, frame) {
out.push(shape);
}
}
- // §14.1.2.9: groups carry their own coord system; we walk
- // children so any absolute-positioned descendants reach the
- // page. The local-coord transform (`coordsize`/`coordorigin`
- // → page coords) for relative-positioned children is left
- // for a future phase — most authored groups in headers and
- // footers use absolute positioning and don't depend on it.
+ // §14.1.2.9: groups carry their own coord system; walk children so
+ // absolute-positioned descendants reach the page. The local-coord
+ // transform (`coordsize`/`coordorigin` → page coords) for
+ // relative-positioned children is not implemented — most authored
+ // groups in headers/footers use absolute positioning.
VmlPrimitive::Group(g) => {
for child in &g.children {
extract_vml_primitive(child, state, frame, out);
@@ -518,11 +499,9 @@ fn extract_vml_primitive(
// through the parallel `extract_vml_floating_images` path
// and emit `FloatingImage` instead.
VmlPrimitive::Image(_) => {}
- // Long-tail primitives modeled in Phase A but not yet
- // emitted as shapes (oval/line/polyline/arc/curve). Phase D
- // will dispatch them to `DrawCommand::Path` / `Line`. Their
- // text-box content (where applicable) is still picked up by
- // the inline fragment collector.
+ // Primitives modeled but not yet emitted as shapes
+ // (oval/line/polyline/arc/curve). Their text-box content, where
+ // applicable, is still picked up by the inline fragment collector.
VmlPrimitive::Shape(_)
| VmlPrimitive::Oval(_)
| VmlPrimitive::Line(_)
@@ -550,16 +529,13 @@ fn build_vml_rect_shape(
use crate::render::geometry::PtOffset;
use crate::render::resolve::shape_geometry::{PathVerb, SubPath};
- // Position via `position:absolute` + `margin-left/top`. VML's
- // `margin-left` is page-relative when the shape's
- // `mso-position-horizontal-relative` is `page` (the vorlage gray
- // bar's case) — we don't model that style attribute yet, so
- // assume page-relative and let phase D add the discriminator.
+ // Position via `position:absolute` + `margin-left/top`. VML's `margin-left`
+ // is page-relative when `mso-position-horizontal-relative` is `page`; that
+ // style attribute isn't modelled, so assume page-relative.
//
- // In `AnchorFrame::Stack` the eventual emitter shifts every
- // command by `margins.left` to convert stack→page; we subtract
- // it from `x` up front so the round-trip preserves the
- // page-relative offset.
+ // In `AnchorFrame::Stack` the eventual emitter shifts every command by
+ // `margins.left` to convert stack→page; subtract it from `x` up front so
+ // the round-trip preserves the page-relative offset.
let (page_x, y) = vml_absolute_position(&common.style)?;
// VML has no `inside`/`outside` equivalent — `margin-left` is one number.
let x = FloatingImageX::Absolute(match frame {
@@ -596,17 +572,11 @@ fn build_vml_rect_shape(
stroked: matches!(common.stroked, Some(true)),
}];
- // Vertical position resolution depends on the
- // `mso-position-vertical-relative` style attribute:
- // * `page`/`margin` → absolute page coordinates
- // * `text`/`paragraph` (Word's default in body and footer) →
- // relative to the owning paragraph
- //
- // Phase B only honors the latter (the vorlage gray-bar case);
- // page-anchored vertical resolution lands in phase D when the
- // full position resolver is wired in. Until then we treat the
- // y offset as relative to the host paragraph — which matches
- // Word's default and lets the footer rect render correctly.
+ // Vertical position depends on `mso-position-vertical-relative`:
+ // `page`/`margin` → absolute page coordinates, `text`/`paragraph`
+ // (Word's default in body and footer) → relative to the owning paragraph.
+ // Only the paragraph-relative case is honored; the y offset is treated as
+ // relative to the host paragraph, matching Word's default.
let y_image = FloatingImageY::RelativeToParagraph(y);
Some(FloatingShape {
@@ -621,9 +591,6 @@ fn build_vml_rect_shape(
wrap_mode: crate::render::layout::section::WrapMode::None,
dist_left: Pt::ZERO,
dist_right: Pt::ZERO,
- // §14.1.2 z-index drives layering. For Tier 0 we treat all
- // VML primitives as non-behind-text (drawn in document order).
- behind_doc: false,
paths,
fill,
stroke: None,
@@ -935,15 +902,10 @@ fn resolve_anchor_y(
AnchorRelativeFrom::Paragraph | AnchorRelativeFrom::Line => {
FloatingImageY::RelativeToParagraph(Pt::from(*offset))
}
- // §20.4.3.5 `insideMargin`/`outsideMargin`. The spec names them
- // on the vertical axis without saying which strips they are —
- // Word mirrors *left/right* for two-sided documents, not
- // top/bottom — so no reading is derivable from source alone.
- // Treated as `margin`, the long-standing fallback. Settling it
- // needs a two-sided document with a float anchored
- // inside/outside vertically, rendered by Word on both an odd
- // and an even page; `FloatingImageX::PageParity` is already in
- // place should the answer turn out to be "it mirrors".
+ // §20.4.3.5 `insideMargin`/`outsideMargin`: the spec names them
+ // on the vertical axis without saying which strips they are
+ // (Word mirrors left/right for two-sided documents, not
+ // top/bottom), so treat them as `margin`.
AnchorRelativeFrom::InsideMargin | AnchorRelativeFrom::OutsideMargin => {
FloatingImageY::Absolute(pc.margins.top + Pt::from(*offset))
}
@@ -1144,9 +1106,9 @@ fn resolve_vml_solid_fill(
/// function of `paragraph_top` rather than an absolute frame. The shape-text
/// sub-layout assumes paragraph-relative placement (the stacker ties
/// `text_commands` to the same `(fs.x, shape_y)` it uses for the path), so
-/// page-anchored shapes get their text emitted via the legacy inline-fragment
-/// collector instead. Tier 1 follow-up: extend the sub-layout to honor
-/// page/margin frames so all wsp shapes can use the typed path.
+/// page-anchored shapes get their text emitted via the inline-fragment
+/// collector instead. TODO: extend the sub-layout to honor page/margin frames
+/// so all wsp shapes can use the typed path.
fn anchors_to_paragraph(anchor: &crate::model::AnchorProperties) -> bool {
use crate::model::{AnchorPosition, AnchorRelativeFrom};
let relative_from = match &anchor.vertical_position {
@@ -2145,8 +2107,8 @@ mod tests {
/// §20.4.3.4 `insideMargin`/`outsideMargin` are page-parity dependent, and
/// the page a float lands on is not known at extraction time. The odd-page
- /// reading — inside = left, outside = right — is the Tier-0 collapse, and
- /// it is exact for the single-sided documents that are nearly all of them.
+ /// reading — inside = left, outside = right — is the collapse used here,
+ /// and it is exact for single-sided documents.
#[test]
fn parity_margins_take_their_odd_page_reading() {
let inside = x_of(
diff --git a/crates/liteparse-ooxml/src/render/layout/build/list_label.rs b/crates/liteparse-ooxml/src/render/layout/build/list_label.rs
index 47ff611..f423576 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/list_label.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/list_label.rs
@@ -185,7 +185,13 @@ fn inject_text_label(
level_def: Option<&crate::render::resolve::numbering::ResolvedNumberingLevel>,
auto_fit: crate::render::layout::ShapeAutoFit,
) {
- let num_id = model::NumId::new(merged_props.numbering.as_ref().unwrap().num_id);
+ let Some(num_id) = merged_props
+ .numbering
+ .as_ref()
+ .map(|n| model::NumId::new(n.num_id))
+ else {
+ return;
+ };
let (default_family, default_size, default_color, _, paragraph_style_run) =
resolve_paragraph_defaults(para, ctx.resolved, false, None, None);
@@ -971,8 +977,7 @@ mod tests {
assert_eq!(bolds, vec![Some(true), Some(false)]);
}
- /// The key correctness property for the bug at hand: a level rPr
- /// underline must surface in the resolved properties so
+ /// A level rPr underline must surface in the resolved properties so
/// `font_props_from_run` reads it.
#[test]
fn cascade_resolve_materializes_underline_from_level() {
@@ -1005,13 +1010,12 @@ mod tests {
// ── §17.9.23 — `build_label_font_props` ──────────────────────────────
//
// The label's `FontProps` is built by passing the cascade-resolved
- // `RunProperties` through `font_props_from_run`. These tests pin
- // the spec-driven invariants the previous hand-rolled construction
- // violated (notably: dropped underline, char_spacing, text_scale).
+ // `RunProperties` through `font_props_from_run`. These tests pin the
+ // spec-driven invariants (underline, char_spacing, text_scale must flow
+ // through, not be dropped).
- /// THE BUG: an underline in the level rPr (`<w:lvl><w:rPr><w:u/>`)
- /// must surface as `font.underline = true`. Previously this code
- /// path hardcoded `underline: false`.
+ /// An underline in the level rPr (`<w:lvl><w:rPr><w:u/>`) must surface as
+ /// `font.underline = true`.
#[test]
fn label_font_inherits_underline_from_level() {
let level = rp_with_underline(UnderlineStyle::Single);
@@ -1034,8 +1038,7 @@ mod tests {
/// Cascade depth: when the level layer doesn't set underline but
/// the paragraph-mark rPr does, the label inherits the underline.
- /// §17.3.1.29. (Previously broken: hand-rolled code never read
- /// either layer's underline.)
+ /// §17.3.1.29.
#[test]
fn label_font_inherits_underline_from_mark_when_level_absent() {
let mark = rp_with_underline(UnderlineStyle::Single);
@@ -1079,9 +1082,7 @@ mod tests {
);
}
- /// `<w:spacing>` (char spacing) was silently dropped by the
- /// hand-rolled construction. With cascade routing it must flow
- /// into `FontProps::char_spacing`.
+ /// `<w:spacing>` (char spacing) must flow into `FontProps::char_spacing`.
#[test]
fn label_font_inherits_char_spacing_from_level() {
let level = RunProperties {
@@ -1103,8 +1104,7 @@ mod tests {
assert!((font.char_spacing.raw() - 2.0).abs() < 1e-4);
}
- /// `<w:w>` (text scale) was silently fixed to 1.0 in the
- /// hand-rolled construction.
+ /// `<w:w>` (text scale) must flow into `FontProps::text_scale`.
#[test]
fn label_font_inherits_text_scale_from_level() {
let level = RunProperties {
diff --git a/crates/liteparse-ooxml/src/render/layout/build/mod.rs b/crates/liteparse-ooxml/src/render/layout/build/mod.rs
index bfe152d..589af91 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/mod.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/mod.rs
@@ -269,8 +269,8 @@ fn build_non_story_content(
// `margins.left` — so shapes must be resolved in the stack
// frame (not page-absolute), otherwise `margins.left` would
// be applied twice. §17.10.1: z-ordering against the
- // surrounding text in Tier 0 is paragraph-granular, matching
- // the stack-frame emission order.
+ // surrounding text is paragraph-granular, matching the
+ // stack-frame emission order.
let paragraph_shapes = floating::extract_floating_shapes(
p,
ctx,
@@ -284,7 +284,7 @@ fn build_non_story_content(
// can't ride on the per-paragraph anchoring used by
// `paragraph_shapes`, so collect them at the
// header/footer level — `render_header`/`render_footer`
- // emits them outside `stack_blocks` (no shift) so the
+ // emit them outside `stack_blocks` (no shift) so the
// resolved page-y is honored.
let page_anchored_shapes = floating::extract_floating_shapes(
p,
diff --git a/crates/liteparse-ooxml/src/render/layout/build/table.rs b/crates/liteparse-ooxml/src/render/layout/build/table.rs
index ac6d36a..ce0d262 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/table.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/table.rs
@@ -160,10 +160,9 @@ pub(super) fn build_table(
// §17.4.63 / Word heuristic: a full-width left-aligned table extends
// beyond the body content area by its cell margins so cell content
// aligns with surrounding paragraph text. Centered/right-aligned tables
- // are positioned as a unit — extending them would just shift them out
- // by half the margins, producing a width discrepancy when consecutive
- // centered tables have different cell margins (cf. the stacked
- // "Anhang: Sauberkeit" tables in the Volvo Annahme-Protokoll).
+ // are positioned as a unit — extending them would shift them out by half
+ // the margins, so consecutive centered tables with different cell margins
+ // would render at different widths.
let extends_for_alignment = !matches!(
t.properties.alignment,
Some(model::Alignment::Center) | Some(model::Alignment::End)
@@ -289,9 +288,8 @@ pub(super) fn build_table(
})
.collect();
- // Word/LibreOffice row-uniform content-area quirk — see
- // `normalize_row_uniform_vertical_insets` for the spec gap and
- // empirical evidence motivating this pass.
+ // Word/LibreOffice normalize top/bottom cell margins to the
+ // row-wide max — see `normalize_row_uniform_vertical_insets`.
let mut cells = cells;
normalize_row_uniform_vertical_insets(&mut cells);
@@ -318,14 +316,8 @@ pub(super) fn build_table(
TableRowInput {
cells,
- // §17.4.81: `exact` pins the height, `atLeast` is a minimum,
- // and `auto` **ignores `val`** — the row sizes to its content,
- // so it carries no constraint at all. An omitted `hRule`
- // arrives as `AtLeast` (Word's default, set at the parse seam),
- // which is why folding `auto` in with it used to be invisible:
- // [MS-OE376] §2.4.77(c) notes Word requires `val = 0` whenever
- // `hRule="auto"`, making `AtLeast(0)` a no-op on Word output.
- // Other producers are not bound by that.
+ // §17.4.81: see `row_height_rule` — `auto` carries no
+ // constraint, `exact`/`atLeast` map through.
height_rule: row.properties.height.and_then(row_height_rule),
is_header: row.properties.is_header,
cant_split: row.properties.cant_split,
@@ -397,57 +389,21 @@ pub(super) fn build_table(
}
}
-/// Word/LibreOffice row layout quirk: top/bottom cell margins are normalized
-/// to the row-wide maximum across all cells in the row, while left/right stay
-/// per-cell.
+/// Normalize each cell's top/bottom margin to the row-wide maximum; left/right
+/// stay per-cell.
///
-/// # Spec relationship
+/// ECMA-376 §17.4.42 (`tcMar`) defines a per-side cell margin as an exception
+/// over §17.4.44 (`tblCellMar`), but is silent on how neighbouring cells in a
+/// row interact when their vertical margins disagree. Word and LibreOffice both
+/// position every cell's content within a row-uniform inset
+/// (`max(top)` / `max(bottom)` across the row); without this pass a cell with
+/// `tcMar.top=0` beside siblings inheriting a larger default would sit flush
+/// against the top border while its neighbours sit padded.
///
-/// ECMA-376 §17.4.42 (`tcMar`, "Single Table Cell Margins") defines the cell
-/// margin as a per-side exception over §17.4.44 (`tblCellMar`, the table-level
-/// default). Each side is a `CT_TblWidth` (§17.18.87), where `@type="dxa"
-/// @w="N"` is an explicit `N`-twip value. The spec is silent on how
-/// *neighbouring* cells in the same row interact when their per-cell margins
-/// disagree — there is no row-level "content area" concept defined in
-/// §17.4.78 (`tr`) or §17.4.79 (`trHeight`).
-///
-/// The de-facto behaviour of every mainstream renderer (Word and LibreOffice
-/// Writer in particular) is to compute a row-uniform content inset:
-///
-/// ```text
-/// row.uniform_top = max(cell.tcMar.top for cell in row)
-/// row.uniform_bottom = max(cell.tcMar.bottom for cell in row)
-/// ```
-///
-/// and to position every cell's content within that uniform inset regardless
-/// of the cell's own per-cell override. Without this pass, a cell with an
-/// explicit `tcMar.top=0` in a row whose siblings inherit a larger value sits
-/// flush against the row's top border while its neighbours sit padded — a
-/// positioning no mainstream editor produces.
-///
-/// # Empirical basis
-///
-/// Verified against the `Wohnungsübergabeprotokoll` sample (LibreOffice
-/// origin) by editing the DOCX directly and observing Word's render:
-///
-/// 1. Rewriting all `<w:tcMar><w:top w:w="0"/></w:tcMar>` to
-/// `<w:top w:w="1"/>` produced **byte-equivalent visual output** — Word
-/// is invariant to the literal value at this magnitude, ruling out
-/// "Word treats `w=0` as no-override" as the explanation.
-/// 2. Rewriting just one cell's `<w:tcMar>` to `<w:top w:w="500"/>` (≈ 25pt)
-/// pushed **every** cell in that row down by ~25pt, confirming the
-/// row-wide max(...) discipline.
-///
-/// # Scope
-///
-/// Only `top` and `bottom` are normalized. `left` and `right` stay per-cell
-/// because each column's content width is independent — there is no shared
-/// row-wide horizontal area in the de-facto layout, and editors do honour
-/// per-cell horizontal overrides.
-///
-/// Applied at the build layer (post per-side `<w:tcMar>`/`<w:tblCellMar>`
-/// cascade resolution) so downstream measure/emit/split code sees uniform
-/// vertical insets and needs no further changes.
+/// Only top/bottom are normalized: each column's content width is independent,
+/// and editors do honour per-cell left/right overrides. Applied post per-side
+/// cascade resolution so downstream measure/emit/split code sees uniform
+/// vertical insets.
fn normalize_row_uniform_vertical_insets(cells: &mut [TableCellInput]) {
let max_top = cells.iter().fold(Pt::ZERO, |acc, c| acc.max(c.margins.top));
let max_bottom = cells
@@ -700,21 +656,17 @@ mod tests {
}
}
- /// Word/Writer row-uniform content-area normalization: when cells in a row
- /// disagree on `tcMar.top` (or `bottom`), the row-wide *maximum* wins for
- /// every cell. Verified empirically against MS Word — see
- /// [`normalize_row_uniform_vertical_insets`] for the experimental
- /// reproducer and spec references.
+ /// Row-uniform normalization: when cells in a row disagree on `tcMar.top`
+ /// (or `bottom`), the row-wide *maximum* wins for every cell. See
+ /// [`normalize_row_uniform_vertical_insets`] for the spec references.
#[test]
fn row_uniform_picks_max_top_and_bottom_across_row() {
- // Mirrors the Wohnungsübergabe "Keller" row: one cell with
- // explicit zero top/bottom (the Keller cell after per-side tcMar
- // cascade) and another with the inherited 57-twip table default
- // (≈ 2.85 pt) — siblings without a tcMar override.
+ // One cell with explicit zero top/bottom and another with the inherited
+ // 57-twip table default (≈ 2.85 pt).
let mut cells = vec![
- cell_with_margins(0.0, 5.4, 0.0, 5.15), // Keller-like
+ cell_with_margins(0.0, 5.4, 0.0, 5.15),
cell_with_margins(2.85, 5.4, 2.85, 5.15), // sibling with table default
- cell_with_margins(0.0, 5.4, 0.0, 5.15), // another Keller-like
+ cell_with_margins(0.0, 5.4, 0.0, 5.15),
];
normalize_row_uniform_vertical_insets(&mut cells);
@@ -735,14 +687,13 @@ mod tests {
}
}
- /// Mirrors the `_kellertop500` experiment: a single cell with a `tcMar.top`
- /// far larger than its siblings becomes the row-wide max, so every cell —
- /// including the ones with no override — picks up that large top inset.
- /// In Word, this is observable as the entire row's content shifting down.
+ /// A single cell with a `tcMar.top` far larger than its siblings becomes
+ /// the row-wide max, so every cell — including ones with no override — picks
+ /// up that large top inset (in Word, the whole row's content shifts down).
#[test]
fn row_uniform_one_large_cell_top_pushes_whole_row_down() {
let mut cells = vec![
- cell_with_margins(25.0, 5.4, 0.0, 5.15), // Keller with top=25pt
+ cell_with_margins(25.0, 5.4, 0.0, 5.15), // dominating cell, top=25pt
cell_with_margins(2.85, 5.4, 2.85, 5.15), // small sibling
];
normalize_row_uniform_vertical_insets(&mut cells);
@@ -752,7 +703,7 @@ mod tests {
25.0,
"sibling cell inherits the large top from the dominating cell"
);
- // Bottom max is the smaller cell's 2.85 (Keller bottom stayed 0).
+ // Bottom max is the smaller cell's 2.85 (first cell's bottom stayed 0).
assert_eq!(cells[0].margins.bottom.raw(), 2.85);
}
diff --git a/crates/liteparse-ooxml/src/render/layout/cell.rs b/crates/liteparse-ooxml/src/render/layout/cell.rs
index a341694..1e6db6f 100644
--- a/crates/liteparse-ooxml/src/render/layout/cell.rs
+++ b/crates/liteparse-ooxml/src/render/layout/cell.rs
@@ -36,13 +36,11 @@ pub fn layout_cell(
) -> CellLayout {
let content_width = (cell_width - margins.horizontal()).max(Pt::ZERO);
- // §20.4.3.1: a cell is measured before its table is paginated — a row can
- // split across pages, and the split is decided from these measurements —
- // so the page this cell lands on, and its parity, do not exist yet. An
- // `inside`/`outside` float inside a table therefore takes the odd-page
- // reading. That is the Tier-0 the page and header paths no longer need;
- // removing it here means making cell measurement page-aware, which is a
- // far larger change than the anchor resolution itself.
+ // §20.4.3.1: a cell is measured before its table is paginated (the row
+ // split is decided from these measurements), so the page this cell lands on
+ // and its parity do not exist yet. An `inside`/`outside` float inside a
+ // table therefore takes the odd-page reading; resolving it correctly would
+ // require making cell measurement page-aware.
let result = stack_blocks(
blocks,
content_width,
diff --git a/crates/liteparse-ooxml/src/render/layout/draw_command.rs b/crates/liteparse-ooxml/src/render/layout/draw_command.rs
index ed7db9e..8cac5e2 100644
--- a/crates/liteparse-ooxml/src/render/layout/draw_command.rs
+++ b/crates/liteparse-ooxml/src/render/layout/draw_command.rs
@@ -16,9 +16,8 @@ use crate::render::resolve::shape_geometry::SubPath;
///
/// `node_id` is assigned at **layout** time and carried here rather than
/// recomputed at paint. The painter and the structure-tree builder both walk
-/// the same command stream, and two counters that agree only by argument is
-/// exactly the shape that produced this codebase's MCE double-render and then
-/// the missing render after it. One field, read twice.
+/// the same command stream, so a single assigned id read by both cannot drift
+/// the way two independently-recomputed counters would.
#[derive(Debug, Clone)]
pub struct OutlineHeading {
/// PDF structure node ID. Unique per document and **1-based**:
@@ -163,10 +162,7 @@ pub enum DrawCommand {
/// is what keeps a run of text over a cell-shading image readable.
///
/// `true` for an XLSX floating picture, where the relation inverts:
- /// Excel draws a picture on top of the grid *and* its values, and a
- /// corpus census put painted glyphs on 618 of 2,114 placements
- /// (29.2%, 245 workbooks) — a banner with the sheet's text bleeding
- /// through it, not a rare artifact.
+ /// Excel draws a picture on top of the grid *and* its cell values.
float: bool,
},
/// One emoji grapheme cluster placed at `rect`. The painter rasterizes
diff --git a/crates/liteparse-ooxml/src/render/layout/float.rs b/crates/liteparse-ooxml/src/render/layout/float.rs
index 272a22d..9b406f3 100644
--- a/crates/liteparse-ooxml/src/render/layout/float.rs
+++ b/crates/liteparse-ooxml/src/render/layout/float.rs
@@ -1,7 +1,6 @@
//! Floating element layout — positioned outside the normal flow.
use crate::render::dimension::Pt;
-use crate::render::geometry::PtRect;
/// §17.4.56 / §20.4.2: source of a floating element.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -30,11 +29,6 @@ impl FloatSource {
/// between *floating tables*: "whether the current table shall allow
/// other floating tables to overlap its extents". A table may still
/// visually overlap a floating image, and Word lets it.
- ///
- /// Named rather than spelled `matches!(.., Table { .. })` at the use
- /// site because the interesting content is the spec rule, not the
- /// pattern — the anchor resolver reads as "skip what tblOverlap
- /// doesn't govern".
pub fn participates_in_table_overlap(&self) -> bool {
matches!(self, Self::Table { .. })
}
@@ -92,16 +86,6 @@ impl ActiveFloat {
pub fn overlaps_y(&self, y: Pt) -> bool {
y >= self.page_y_start && y < self.page_y_end
}
-
- /// The rectangle occupied by this float.
- pub fn rect(&self) -> PtRect {
- PtRect::from_xywh(
- self.page_x,
- self.page_y_start,
- self.width,
- self.page_y_end - self.page_y_start,
- )
- }
}
/// Compute how much the available width should be reduced on a given line
diff --git a/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs b/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs
index 686977e..86d0af2 100644
--- a/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs
+++ b/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs
@@ -33,14 +33,10 @@ pub struct RecordedFootnote {
/// The display counter and the record of *which* notes were referenced advance
/// at a single site (the private `record` method), so the footnote body a
/// caller renders can never disagree with the superscript mark this walk
-/// emitted.
-///
-/// This replaced a design where the counter was advanced by this **recursive**
-/// walk (which descends into hyperlinks, non-substituted fields, MCE
-/// fallbacks, and VML text boxes) while callers re-derived the reference list
-/// from a **flat** scan of the paragraph's top-level inlines. The two walkers
-/// disagreed for any nested reference: its body was never emitted, and when it
-/// preceded a top-level reference the body's number no longer matched the mark.
+/// emitted. This matters because the walk is recursive (it descends into
+/// hyperlinks, non-substituted fields, MCE fallbacks, and VML text boxes), so a
+/// caller that re-derived the reference list from a flat scan of top-level
+/// inlines would miss nested references and misnumber the bodies.
#[derive(Default, Debug)]
pub struct FootnoteTracker {
/// Display number of the most recently emitted reference.
@@ -212,14 +208,49 @@ pub struct FieldContext {
/// §17.16.4.1: evaluate a parsed field instruction against the current context.
/// Returns the substituted text for PAGE/NUMPAGES, or None for other fields
/// or when no context is available.
+///
+/// Evaluation is delegated to the single canonical evaluator
+/// [`crate::field::evaluate`], so numeric-format switches Word honors on these
+/// fields (`\* ROMAN`, `\* Upper`, `\# 0`, `\* MERGEFORMAT`, …) are applied
+/// here too — the previous hand-rolled `to_string()` ignored them.
+///
+/// The match is deliberately restricted to `Page` / `NumPages`: those are the
+/// only instructions whose inputs (the current page number and total page
+/// count) are deterministically known at layout time and fully populated in the
+/// layout-side [`FieldContext`]. Every other instruction is returned as `None`
+/// so it falls back to the cached result Word stored in the document. That
+/// fallback is mandatory for correctness:
+/// * Time/environment-dependent fields (DATE, TIME, CREATEDATE, AUTHOR,
+/// FILENAME, …) must never be recomputed at parse time — output has to stay
+/// deterministic. `field::evaluate` reads these from context members we
+/// leave unset, so it would already yield `Unevaluable`; but gating by
+/// variant makes the guarantee structural rather than relying on empty
+/// context.
+/// * Stateful / self-substituting fields (HYPERLINK, SEQ, IF, SYMBOL, EQ)
+/// evaluate *unconditionally* in `field::evaluate` (they don't depend on
+/// the members we omit), so letting them through would replace their
+/// cached result with a recomputed value — a regression. The variant gate
+/// is what prevents that.
fn evaluate_field_instruction(
instruction: &crate::field::FieldInstruction,
ctx: FieldContext,
) -> Option<String> {
match instruction {
- crate::field::FieldInstruction::Page { .. } => ctx.page_number.map(|n| n.to_string()),
- crate::field::FieldInstruction::NumPages { .. } => ctx.num_pages.map(|n| n.to_string()),
- _ => None,
+ crate::field::FieldInstruction::Page { .. }
+ | crate::field::FieldInstruction::NumPages { .. } => {}
+ _ => return None,
+ }
+ // Only the page-count members are populated; every date/author/bookmark/
+ // merge member stays at its `None`/empty default, so any field reaching a
+ // path that consults them evaluates to `Unevaluable` → cached fallback.
+ let feval_ctx = crate::field::FieldContext {
+ page_number: ctx.page_number.map(|n| n as u32),
+ total_pages: ctx.num_pages.map(|n| n as u32),
+ ..Default::default()
+ };
+ match crate::field::evaluate(instruction, &feval_ctx) {
+ crate::field::FieldValue::Text(s) => Some(s),
+ crate::field::FieldValue::Number(_) | crate::field::FieldValue::Unevaluable => None,
}
}
@@ -950,11 +981,8 @@ where
// primitives inline. Every primitive variant
// (`<v:shape>`, `<v:rect>`, `<v:roundrect>`,
// `<v:oval>`, …) admits a `<v:textbox>` child via
- // `VmlCommonAttrs.text_box`; the previous code
- // only walked the `Shape` variant and silently
- // dropped text from rect / roundrect / oval text
- // boxes (the case footer3.xml of the vorlage doc
- // exercised — the gray bar is a `<v:rect>`).
+ // `VmlCommonAttrs.text_box`, so walk all of them, not
+ // just `<v:shape>`.
//
// Does not handle absolute positioning — text
// appears inline with the surrounding paragraph.
@@ -1423,6 +1451,117 @@ mod tests {
}
}
+ // ── §17.16.4.1 field substitution via the canonical evaluator ─────────
+ //
+ // `evaluate_field_instruction` delegates to `crate::field::evaluate` for
+ // PAGE / NUMPAGES only. These cover the byte-A/B'd plain-arabic path, the
+ // format-switch path the old hand-rolled match ignored, and the
+ // deterministic cached-result fallback for time-dependent fields.
+
+ /// Plain ` PAGE ` with a context substitutes the arabic page number
+ /// verbatim (no switch → no reformatting). This is the byte-A/B'd path.
+ #[test]
+ fn simple_page_field_substitutes_plain_arabic() {
+ let inlines = vec![Inline::Field(Field {
+ instruction: crate::field::FieldInstruction::Page {
+ switches: Default::default(),
+ },
+ // Cached result differs from the live page so we can tell which won.
+ content: vec![text_run("999")],
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext {
+ page_number: Some(7),
+ num_pages: None,
+ },
+ );
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(&**text, "7", "live PAGE value must win, plain arabic");
+ } else {
+ panic!("expected Text fragment");
+ }
+ }
+
+ /// ` PAGE \* ROMAN ` applies the general-format switch — the win the old
+ /// hand-rolled `to_string()` match could not produce.
+ #[test]
+ fn simple_page_field_applies_roman_switch() {
+ let inlines = vec![Inline::Field(Field {
+ instruction: crate::field::FieldInstruction::Page {
+ switches: crate::field::CommonSwitches {
+ format: Some("ROMAN".into()),
+ ..Default::default()
+ },
+ },
+ content: vec![text_run("cached")],
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext {
+ page_number: Some(7),
+ num_pages: None,
+ },
+ );
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(&**text, "VII", "PAGE \\* ROMAN must format as roman");
+ } else {
+ panic!("expected Text fragment");
+ }
+ }
+
+ /// A DATE field is time-dependent: it must NOT be evaluated at parse time.
+ /// The variant gate returns None, so the cached result Word stored is what
+ /// renders — keeping output deterministic.
+ #[test]
+ fn date_field_falls_back_to_cached_result() {
+ let inlines = vec![Inline::Field(Field {
+ instruction: crate::field::FieldInstruction::Date {
+ format: None,
+ switches: Default::default(),
+ },
+ // Single unsplittable token so the cached result is one fragment.
+ content: vec![text_run("cachedDate")],
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ // Page context is present, but that must not tempt DATE evaluation.
+ FieldContext {
+ page_number: Some(3),
+ num_pages: Some(3),
+ },
+ );
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(
+ &**text, "cachedDate",
+ "DATE must render its cached result, never a recomputed date"
+ );
+ } else {
+ panic!("expected Text fragment");
+ }
+ }
+
#[test]
fn multi_word_text_run_splits_into_fragments() {
let inlines = vec![text_run("hello world foo")];
@@ -1640,7 +1779,7 @@ mod tests {
// ── End-to-end: empty-placeholder result run formatting ──────────────
//
- // Mirrors the Fotodokumentation Test header structure:
+ // Header structure:
// `Seite ` [Begin → InstrText("PAGE") → Separate → <w:t></w:t> bold → End]
// The substituted page number must inherit bold from the empty
// placeholder result run's `<w:rPr>`.
diff --git a/crates/liteparse-ooxml/src/render/layout/fragment/segment.rs b/crates/liteparse-ooxml/src/render/layout/fragment/segment.rs
index 436c121..3b5cd13 100644
--- a/crates/liteparse-ooxml/src/render/layout/fragment/segment.rs
+++ b/crates/liteparse-ooxml/src/render/layout/fragment/segment.rs
@@ -59,9 +59,7 @@ pub(super) struct JoinedTextSegment<'a> {
}
impl<'a> JoinedTextSegment<'a> {
- /// Joined-and-stripped text. Used by tests to verify provenance and
- /// by future paragraph-level diagnostics — kept as part of the public
- /// API of this module.
+ /// Joined-and-stripped text. Used by tests to verify provenance.
#[allow(dead_code)]
pub(super) fn text(&self) -> &str {
&self.text
@@ -247,7 +245,7 @@ impl<'a> SegmentBuilder<'a> {
}
}
-// ─── Tests (Phase α.0 + α.1) ─────────────────────────────────────────────────
+// ─── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
@@ -520,7 +518,6 @@ mod tests {
}
/// B3 — keycap split as ["1", VS-16, U+20E3] → one Emoji piece.
- /// **Direct fix for the user-visible keycap bug.**
#[test]
fn b3_cross_run_keycap_reassembles() {
let inlines = vec![text_run("1"), text_run("\u{FE0F}"), text_run("\u{20E3}")];
diff --git a/crates/liteparse-ooxml/src/render/layout/fragment/split.rs b/crates/liteparse-ooxml/src/render/layout/fragment/split.rs
index 97fcfaf..210fac9 100644
--- a/crates/liteparse-ooxml/src/render/layout/fragment/split.rs
+++ b/crates/liteparse-ooxml/src/render/layout/fragment/split.rs
@@ -17,11 +17,9 @@ pub type MeasureFn<'a> = Option<&'a dyn Fn(&str, &FontProps) -> (Pt, TextMetrics
/// True for a text fragment that is both too wide and actually splittable.
///
-/// The character *count* is what matters: a single character cannot be split
-/// however many bytes it occupies. An earlier byte-length (`text.len() > 1`)
-/// spelling of this test disagreed with the split itself for any non-ASCII
-/// single character — it reported "needs split", then split nothing, and the
-/// caller paid for a full clone of the fragment vector.
+/// Tests the character *count*, not the byte length: a single character cannot
+/// be split however many bytes it occupies, and a byte-length test would report
+/// "needs split" for a multi-byte single character that then splits into nothing.
fn needs_split(fragment: &Fragment, max_width: Pt) -> bool {
matches!(
fragment,
diff --git a/crates/liteparse-ooxml/src/render/layout/fragment/text.rs b/crates/liteparse-ooxml/src/render/layout/fragment/text.rs
index 4524206..fef3cca 100644
--- a/crates/liteparse-ooxml/src/render/layout/fragment/text.rs
+++ b/crates/liteparse-ooxml/src/render/layout/fragment/text.rs
@@ -186,8 +186,8 @@ pub(super) fn emit_text_fragments<F>(
}
}
-/// Word-split + measure path. Identical to the prior body of
-/// [`emit_text_fragments`]; factored out so emoji-cluster fallback can reuse it.
+/// Word-split + measure path, shared by [`emit_text_fragments`] and the
+/// emoji-cluster fallback.
pub(super) fn emit_text_words<F>(
text: &str,
font: &FontProps,
diff --git a/crates/liteparse-ooxml/src/render/layout/header_footer.rs b/crates/liteparse-ooxml/src/render/layout/header_footer.rs
index e0a93cb..959ee1a 100644
--- a/crates/liteparse-ooxml/src/render/layout/header_footer.rs
+++ b/crates/liteparse-ooxml/src/render/layout/header_footer.rs
@@ -10,7 +10,7 @@
use crate::model::Block;
use crate::render::dimension::Pt;
-use crate::render::resolve::header_footer::{HeaderFooterKind, HeaderFooterSet};
+use crate::render::resolve::header_footer::HeaderFooterSet;
use super::build::{BuildContext, BuildState, HeaderFooterContent, build_header_footer_content};
use super::draw_command::{DrawCommand, LayoutedPage};
@@ -55,25 +55,6 @@ pub fn select_slot<T>(
set.default.as_ref()
}
-/// Variant of [`select_slot`] that also tells the caller which kind of
-/// slot was chosen. Useful for diagnostics and for callers that need
-/// to bookkeep per-kind layout state (e.g. header-area heights).
-pub fn select_slot_with_kind<T>(
- set: &HeaderFooterSet<T>,
- first_in_section: bool,
- logical_page_number: usize,
- title_pg: bool,
- even_and_odd: bool,
-) -> Option<(HeaderFooterKind, &T)> {
- if title_pg && first_in_section {
- return set.first.as_ref().map(|t| (HeaderFooterKind::First, t));
- }
- if even_and_odd && logical_page_number.is_multiple_of(2) {
- return set.even.as_ref().map(|t| (HeaderFooterKind::Even, t));
- }
- set.default.as_ref().map(|t| (HeaderFooterKind::Default, t))
-}
-
/// Vertical body boundaries for one physical page.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PageBodyBounds {
@@ -1008,24 +989,5 @@ mod tests {
};
assert_eq!(next_logical_page_base(4, Some(&pnt)), 4);
}
-
- // Variant returning the kind --------------------------------
-
- #[test]
- fn select_slot_with_kind_reports_the_chosen_slot() {
- let set = full_set();
- assert_eq!(
- select_slot_with_kind(&set, true, 1, true, false),
- Some((HeaderFooterKind::First, &"F")),
- );
- assert_eq!(
- select_slot_with_kind(&set, false, 2, false, true),
- Some((HeaderFooterKind::Even, &"E")),
- );
- assert_eq!(
- select_slot_with_kind(&set, false, 3, false, true),
- Some((HeaderFooterKind::Default, &"D")),
- );
- }
}
}
diff --git a/crates/liteparse-ooxml/src/render/layout/line.rs b/crates/liteparse-ooxml/src/render/layout/line.rs
index a397d90..24a1ad5 100644
--- a/crates/liteparse-ooxml/src/render/layout/line.rs
+++ b/crates/liteparse-ooxml/src/render/layout/line.rs
@@ -67,8 +67,8 @@ pub fn fit_lines_with_first(
// §17.3.1.30: where the pen actually *is*, as opposed to how much width
// the line has accumulated. The two differ only across a position tab,
// which jumps the pen to its anchor while contributing a nominal width.
- // Tracking it separately keeps `line_width` — and therefore every
- // non-ptab paragraph's fitting — bit-for-bit unchanged.
+ // Tracking it separately leaves `line_width` — and therefore fitting of
+ // every paragraph without a position tab — unchanged.
let line_pen_start = |is_first_line: bool| {
ptab_geometry.indent_left
+ if is_first_line {
@@ -146,11 +146,9 @@ pub fn fit_lines_with_first(
matches!(relative_to, crate::model::PTabRelativeTo::Margin);
}
crate::render::layout::paragraph::PTabPlacement::AdvancesToNextLine { .. } => {
- // Only break when doing so can help. A tab already first
- // on its line would find the same anchor behind the same
- // pen on the next one — acting on a condition the action
- // cannot change is how this engine's pagination loops have
- // historically become infinite.
+ // Only break when doing so can help: a tab already first on
+ // its line would find the same anchor behind the same pen on
+ // the next line, so breaking would loop forever.
if line_start < i {
let m = measure_range(fragments, line_start, i);
lines.push(FittedLine {
diff --git a/crates/liteparse-ooxml/src/render/layout/measurer.rs b/crates/liteparse-ooxml/src/render/layout/measurer.rs
index 0b3ced0..f1d488d 100644
--- a/crates/liteparse-ooxml/src/render/layout/measurer.rs
+++ b/crates/liteparse-ooxml/src/render/layout/measurer.rs
@@ -1,45 +1,28 @@
//! Text measurer — resolves text widths through a `FontRegistry`.
//!
-//! C′ rewrite of upstream's Skia measurer over fontdb + skrifa. The
-//! measurement arithmetic is copied verbatim from upstream (`measure_str` is a
-//! cmap → sum-of-`hmtx`-advances walk with no shaping or kerning, then
-//! §17.3.2.45 `text_scale` on the advances and §17.3.2.35 `char_spacing` per
-//! character), so it cannot diverge; the things that could — font resolution
-//! and metric quantization — were measured in spikes 6–8:
+//! A port of the upstream (dxpdf) Skia measurer over fontdb + skrifa. The
+//! measurement arithmetic matches upstream: `measure_str` is a cmap →
+//! sum-of-`hmtx`-advances walk with no shaping or kerning, then §17.3.2.45
+//! `text_scale` on the advances and §17.3.2.35 `char_spacing` per character. An
+//! unmapped codepoint contributes glyph 0's (.notdef) advance, which is what a
+//! cmap lookup yields and what Skia does.
//!
-//! - widths agree with Skia to 99.82% exactly where both engines hold the
-//! same face, with no quantization divergence at any size;
-//! - line metrics (`ascent`/`descent`/`leading`, so line height and therefore
-//! pagination) are **bit-exact** against both CoreText- and FreeType-backed
-//! Skia — every corpus face resolves its metrics through `hhea`, and skrifa
-//! agrees with both platform scalers on all of them;
-//! - an unmapped codepoint contributes glyph 0's (.notdef) advance. The
-//! zero-contribution alternative was tried and *disproved* (spike 6): Skia
-//! has space-fallback handling of its own, and zeroing made parity worse.
-//!
-//! ## Sign conventions (the trap spike 7 hit)
+//! ## Sign conventions
//!
//! skrifa reports ascent positive-up and descent negative-down; [`TextMetrics`]
-//! stores ascent positive-up and descent positive-down, so descent is negated
-//! at this boundary. For underlines: upstream's comment claims Skia returns a
-//! negative-below value and that it negates to positive-below — **the comment
-//! has it backwards**. `SkFontMetrics::fUnderlinePosition` is positive below
-//! the baseline; upstream negates it, so `underline_metrics` actually returns
-//! a *negative-below* offset. skrifa's `post`-table `underlinePosition` is
-//! already negative-below, so matching upstream means passing it through
-//! untouched. (Diagnostic worth keeping: a 0%-exact comparison is never a font
-//! disagreement — some face would agree by chance. 0% means a sign or formula
-//! error on your own side.)
+//! stores both positive, so descent is negated at this boundary. The underline
+//! offset is stored **negative below the baseline**: skrifa's `post`-table
+//! `underlinePosition` is already negative-below and is passed through
+//! untouched. (Upstream's own comment describes the opposite of what its code
+//! does; the negative-below reading is the one that matches its output.)
//!
//! ## Emoji
//!
-//! Upstream shapes emoji clusters through Skia's HarfBuzz so ZWJ sequences
-//! measure to their ligated width. No shaper is wired here yet, so
-//! [`TextMeasurer::measure_with_typeface`] takes upstream's own documented
-//! fallback path — the cmap-only advance sum — for every cluster. A
-//! multi-codepoint sequence therefore over-measures relative to upstream by
-//! (n−1) glyph advances; acceptable for now, and the seam for a harfrust
-//! shaper is this one function.
+//! Upstream shapes emoji clusters through HarfBuzz so ZWJ sequences measure to
+//! their ligated width. No shaper is wired here, so
+//! [`TextMeasurer::measure_with_typeface`] uses the cmap-only advance sum for
+//! every cluster; a multi-codepoint sequence therefore over-measures by (n−1)
+//! glyph advances. Wiring a shaper is scoped to that one function.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
@@ -117,10 +100,6 @@ impl<'r> TextMeasurer<'r> {
}
}
- pub fn registry(&self) -> &'r FontRegistry {
- self.registry
- }
-
/// Slot for (family, size, bold, italic), resolving and reading the
/// face's metrics on first sight.
fn slot(&self, family: &str, size: Pt, bold: bool, italic: bool) -> usize {
@@ -258,9 +237,7 @@ impl<'r> TextMeasurer<'r> {
/// Query font metrics for underline positioning.
/// Returns (underline_position, underline_thickness) in points.
///
- /// The offset is **negative below the baseline** — see the module docs;
- /// upstream's own comment states the opposite of what its code does, and
- /// the parity harness proved the negative-below reading bit-exact.
+ /// The offset is **negative below the baseline** — see the module docs.
pub fn underline_metrics(&self, font_props: &FontProps) -> (Pt, Pt) {
let idx = self.slot(
&font_props.family,
@@ -312,8 +289,8 @@ impl<'r> TextMeasurer<'r> {
/// which has already resolved the typeface and needs metrics at the
/// cluster's font size.
///
- /// Cmap-only — upstream's GSUB shaping fallback path, taken always here
- /// until a harfrust shaper is wired in (see module docs).
+ /// Cmap-only — the no-shaping fallback path, taken always here until a
+ /// shaper is wired in (see module docs).
pub fn measure_with_typeface(
&self,
text: &str,
@@ -456,9 +433,8 @@ mod tests {
#[test]
fn underline_position_is_negative_below_baseline() {
- // The sign trap from spike 7: skrifa's post-table value passes
- // through untouched, so for any real font the offset must come back
- // negative (below the baseline).
+ // skrifa's post-table value passes through untouched, so for any real
+ // font the offset must come back negative (below the baseline).
let registry = FontRegistry::new();
let measurer = TextMeasurer::new(&registry);
let (pos, thick) = measurer.underline_metrics(&fp_at_scale(1.0));
diff --git a/crates/liteparse-ooxml/src/render/layout/mod.rs b/crates/liteparse-ooxml/src/render/layout/mod.rs
index a560a43..9725820 100644
--- a/crates/liteparse-ooxml/src/render/layout/mod.rs
+++ b/crates/liteparse-ooxml/src/render/layout/mod.rs
@@ -24,23 +24,18 @@ use crate::render::geometry::{PtEdgeInsets, PtSize};
/// Exactly one branch is live. A consumer takes the first `<mc:Choice>` whose
/// requirements it can meet and otherwise the `<mc:Fallback>`; it never takes
/// both, because both describe the *same* object — the Choice in DrawingML,
-/// the Fallback in VML for clients that predate it.
-///
-/// Every walker that meets the element consults [`live_mc_branch`], so the
-/// answer is a property of the element rather than of who asked. Two
-/// predicates over one element is what produced the original double render,
-/// and a third walker that answered neither is what produced the *missing*
-/// render after it.
+/// the Fallback in VML for clients that predate it. Every walker that meets the
+/// element consults [`live_mc_branch`], so the answer is a property of the
+/// element rather than of who asked; that keeps the branch decision consistent
+/// across the several walkers and avoids double- or missing-render bugs.
///
/// The `Fallback` arm deliberately does **not** split "float" from "inline".
-/// One VML fallback is routinely both, and by design: `extract_vml_primitive`
-/// draws a `<v:rect>`'s geometry and leaves its `text_commands` empty,
+/// One VML fallback is routinely both: `extract_vml_primitive` draws a
+/// `<v:rect>`'s geometry and leaves its `text_commands` empty,
/// `extract_vml_primitive_image` skips any shape that also hosts text, and the
-/// inline collector picks the text box up at the host paragraph. That division
-/// is by graphic role, not by branch, and it is exactly how a bare `<w:pict>`
-/// already renders — so a live Fallback goes to all of them and each takes the
-/// part it owns. Naming an owner per variant would look tidier and would drop
-/// the text of every VML rect that has one.
+/// inline collector picks the text box up at the host paragraph. The division
+/// is by graphic role, not by branch — the same way a bare `<w:pict>` renders —
+/// so a live Fallback goes to all of them and each takes the part it owns.
pub(crate) enum McBranch<'a> {
/// The `<mc:Choice>` elements, in document order.
Choices(&'a [crate::model::McChoice]),
@@ -55,17 +50,15 @@ pub(crate) enum McBranch<'a> {
///
/// The test is **content-based**, not a `Requires` namespace check: a Choice
/// may declare a namespace we nominally support and still hold nothing this
-/// renderer turns into geometry, and the honest question is whether we will
-/// actually draw it. What counts is an *anchor* — an anchored `wps:wsp` shape
-/// and an anchored picture are both `Inline::Image` with
-/// `ImagePlacement::Anchor`, so one question covers shapes and pictures alike
-/// and no walker has to ask a narrower version of it for itself.
+/// renderer turns into geometry, and what matters is whether we will actually
+/// draw it. What counts is an *anchor* — an anchored `wps:wsp` shape and an
+/// anchored picture are both `Inline::Image` with `ImagePlacement::Anchor`, so
+/// one test covers shapes and pictures alike.
///
/// Recurses through `Hyperlink`/`Field` wrappers and nested elements. §M.1.2's
/// content model for a branch is `drawing | pict`, so a nested
-/// `<mc:AlternateContent>` cannot come from a document — but it can be built,
-/// and resolving it innermost-first is the only reading under which the outer
-/// answer stays consistent with the inner one.
+/// `<mc:AlternateContent>` cannot come from a document, but resolving it
+/// innermost-first keeps the outer answer consistent with the inner one.
pub(crate) fn live_mc_branch(ac: &crate::model::AlternateContent) -> McBranch<'_> {
use crate::model::{ImagePlacement, Inline};
@@ -98,12 +91,10 @@ pub(crate) fn live_mc_branch(ac: &crate::model::AlternateContent) -> McBranch<'_
/// Lives here rather than beside `BuildState` because both the block builder
/// and the fragment layer apply it, and `fragment` must not depend on `build`.
///
-/// [`ShapeAutoFit::NONE`] is the identity and is what every call site outside a
-/// shape text body passes. The functions that resolve a font size or a line
-/// spacing take it as an explicit *parameter* rather than reaching for a
-/// default, so that a new call site has to say which it is — a silently
-/// inherited `1.0` is how these attributes came to be dropped in the first
-/// place.
+/// [`ShapeAutoFit::NONE`] is the identity, passed by every call site outside a
+/// shape text body. The functions that resolve a font size or line spacing take
+/// it as an explicit *parameter* rather than defaulting, so a new call site must
+/// state which it means and cannot silently inherit `1.0`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShapeAutoFit {
font_scale: f32,
diff --git a/crates/liteparse-ooxml/src/render/layout/page.rs b/crates/liteparse-ooxml/src/render/layout/page.rs
index 60adaeb..e85b119 100644
--- a/crates/liteparse-ooxml/src/render/layout/page.rs
+++ b/crates/liteparse-ooxml/src/render/layout/page.rs
@@ -138,16 +138,14 @@ const MIN_COLUMN_WIDTH: Pt = Pt::new(1.0);
/// show anything, so a count implying narrower columns describes no layout a
/// document could have meant.
///
-/// **The gaps count.** `n` columns carry `n - 1` gaps of `space`, so the widest
+/// The gaps count: `n` columns carry `n - 1` gaps of `space`, so the widest
/// usable count solves
/// `(content_width - space·(n-1)) / n >= MIN_COLUMN_WIDTH`, i.e.
-/// `n <= (content_width + space) / (MIN_COLUMN_WIDTH + space)`. **This is the
-/// only thing keeping the column width non-negative** — `compute_columns`
+/// `n <= (content_width + space) / (MIN_COLUMN_WIDTH + space)`. This bound is
+/// **the only thing keeping the column width non-negative** — `compute_columns`
/// deliberately does not clamp afterwards. Bounding on
-/// `content_width / MIN_COLUMN_WIDTH` alone ignores the gaps and still admits
-/// counts whose column width comes out **negative** — which is what made a
-/// 15-column section panic. Solving for the gaps is what makes the width
-/// non-negative *by construction* rather than by a later clamp.
+/// `content_width / MIN_COLUMN_WIDTH` alone ignores the gaps and admits counts
+/// whose column width comes out negative.
fn clamp_column_count(requested: u32, content_width: Pt, space: Pt) -> usize {
let requested = (requested as usize).max(1);
if content_width <= Pt::ZERO {
@@ -177,9 +175,9 @@ fn clamp_column_count(requested: u32, content_width: Pt, space: Pt) -> usize {
/// present — Word writes `equalWidth="0"` whenever it means the individual
/// definitions to win.
///
-/// **Tier 0:** §17.6.4 `w:sep` — the vertical rule drawn between columns — is
-/// parsed onto `model::Columns::separator` but never drawn. Position and width
-/// of the columns themselves are unaffected; only the divider line is missing.
+/// §17.6.4 `w:sep` — the vertical rule drawn between columns — is parsed onto
+/// `model::Columns::separator` but not yet drawn. Column position and width are
+/// unaffected; only the divider line is missing.
fn compute_columns(content_width: Pt, columns: &Option<Columns>) -> Vec<ColumnGeometry> {
let single = || {
vec![ColumnGeometry {
@@ -226,13 +224,10 @@ fn compute_columns(content_width: Pt, columns: &Option<Columns>) -> Vec<ColumnGe
// Equal-width columns.
let total_gap = default_space * (num as f32 - 1.0);
- // No clamp here on purpose. `clamp_column_count` is the single guarantee
- // that this is positive, and a second `.max(Pt::ZERO)` was demonstrably
- // inert — removing it changed no test, because the bound already excludes
- // every count that could make it negative. Two mechanisms for one invariant
- // means the redundant one rots unnoticed; if the bound below ever changes,
- // this is the line that breaks, and `column_count_never_yields_a_negative_width`
- // is the test that catches it.
+ // No clamp here on purpose: `clamp_column_count` is the single guarantee
+ // that this is non-negative, since its bound excludes every count that could
+ // make the width negative. A second `.max(Pt::ZERO)` here would be a
+ // redundant invariant that rots unnoticed.
let col_width = (content_width - total_gap) / num as f32;
let mut result = Vec::with_capacity(num);
for i in 0..num {
@@ -514,12 +509,12 @@ mod tests {
assert_eq!(degenerate.len(), 1);
}
- // ── E6#1: no route may produce a negative width ──────────────────────
+ // ── No route may produce a negative width ────────────────────────────
//
- // Three distinct routes reached the same defect, and only the first was in
- // the original finding. All three ended at `BoxConstraints::new`'s
- // `debug_assert!(min_width <= max_width)` — a panic through the public
- // `convert()` API in debug builds, a negative-width layout in release.
+ // Three distinct routes can reach the same defect. All three end at
+ // `BoxConstraints::new`'s `debug_assert!(min_width <= max_width)` — a panic
+ // through the public `convert()` API in debug builds, a negative-width
+ // layout in release.
/// Route 1: more columns than the text area can hold at the given spacing.
/// The old bound (`content_width / MIN_COLUMN_WIDTH`) ignored the gaps, so
diff --git a/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs b/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs
index 30187d0..62bd425 100644
--- a/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs
+++ b/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs
@@ -373,20 +373,21 @@ pub(super) fn emit_line_commands(
_ => Pt::ZERO,
}
};
+ let line_has_just_tab = line_has_justification_tab(fragments, line.start, line.end);
let extra_per_gap = justification_extra_after(
fragments,
line,
line_idx,
line_placements.len(),
style.alignment,
- line_has_justification_tab(fragments, line.start, line.end),
+ line_has_just_tab,
remaining,
);
let distribution_extra = distribution_extra_per_gap(
fragments,
line,
style.alignment,
- line_has_justification_tab(fragments, line.start, line.end),
+ line_has_just_tab,
remaining,
);
@@ -823,8 +824,8 @@ pub struct PTabGeometry {
/// §17.3.1.30: outcome of resolving a position tab against the current pen.
///
/// The `AdvancesToNextLine` case is why this is an ADT rather than a `Pt`: it
-/// is a *line-breaking* outcome, not a coordinate, and collapsing it to
-/// `max(desired, pen)` is exactly the clamp that drew content off the page.
+/// is a *line-breaking* outcome, not a coordinate. Collapsing it to
+/// `max(desired, pen)` clamps content off the page instead of wrapping it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PTabPlacement {
/// The alignment point is at or ahead of the pen; content starts here.
@@ -1084,8 +1085,7 @@ fn decimal_anchor(
/// at the tab, i.e. the `<w:rPr>` of the run carrying the `<w:tab/>` or
/// `<w:ptab/>`. Bundling the three fields keeps them travelling together: the
/// glyph, the font it is measured *and* drawn in, and its colour are one
-/// decision, and splitting them is how the hardcoded-Times-New-Roman default
-/// survived as long as it did.
+/// decision.
pub(super) struct LeaderStyle<'a> {
pub leader: crate::model::TabLeader,
pub font: &'a super::super::fragment::FontProps,
@@ -1166,20 +1166,17 @@ pub(super) fn emit_tab_leader(
});
}
-/// §17.3.1.33: resolve the effective line height from the natural height
-/// and the line spacing rule.
+/// §17.3.1.33 line height for one line, then §20.1.2.1.18 `@lnSpcReduction`.
///
/// For Auto mode, the multiplier applies only to text metrics — inline
/// images use their natural height without scaling. The final line height
/// is `max(text_height * multiplier, total_height)`.
-/// §17.3.1.33 line height for one line, then §20.1.2.1.18 `@lnSpcReduction`.
///
/// `auto_fit` is a parameter rather than something callers apply afterwards
/// because four separate places resolve a line height — fitting, emission,
/// the border box and the empty-paragraph path — and they must agree to the
-/// point. Owning the reduction here is what makes forgetting it impossible;
-/// applying it *after* the match is what lets it cross the `Auto` floor below,
-/// which is the whole point of the attribute (see
+/// point. Applying the reduction here (not after the match) is what lets it
+/// cross the `Auto` floor below, which is the point of the attribute (see
/// [`ShapeAutoFit::scale_line_height`](crate::render::layout::ShapeAutoFit::scale_line_height)).
pub(super) fn resolve_line_height(
natural: Pt,
diff --git a/crates/liteparse-ooxml/src/render/layout/paragraph/mod.rs b/crates/liteparse-ooxml/src/render/layout/paragraph/mod.rs
index 6bae640..652fe86 100644
--- a/crates/liteparse-ooxml/src/render/layout/paragraph/mod.rs
+++ b/crates/liteparse-ooxml/src/render/layout/paragraph/mod.rs
@@ -2310,8 +2310,8 @@ mod tests {
#[test]
fn tab_leader_inherits_the_run_font_and_colour() {
- // §17.3.1.38: the leader is drawn in the tab run's own formatting.
- // Previously it was hardcoded to Times New Roman / black.
+ // §17.3.1.38: the leader is drawn in the tab run's own formatting,
+ // not a hardcoded default.
let frags = vec![
text_frag("a", 10.0),
Fragment::Tab {
@@ -2350,8 +2350,8 @@ mod tests {
#[test]
fn tab_leader_scales_with_the_run_font_size() {
- // The old code sized the leader from the paragraph line height and
- // capped it at 12pt, so a large run drew undersized leaders.
+ // §17.3.1.38: the leader is sized from the tab run's font, not from
+ // the paragraph line height (and not capped).
let frags = vec![
text_frag("a", 10.0),
Fragment::Tab {
diff --git a/crates/liteparse-ooxml/src/render/layout/paragraph/types.rs b/crates/liteparse-ooxml/src/render/layout/paragraph/types.rs
index 7a6c5b5..0cc85ce 100644
--- a/crates/liteparse-ooxml/src/render/layout/paragraph/types.rs
+++ b/crates/liteparse-ooxml/src/render/layout/paragraph/types.rs
@@ -198,9 +198,6 @@ impl Default for ParagraphStyle {
}
}
-// Workaround for clippy: ParagraphStyle has many fields but they all map 1:1 to spec properties.
-// A builder pattern would add complexity without value here.
-
/// Line spacing rules matching OOXML semantics.
#[derive(Clone, Copy, Debug)]
pub enum LineSpacingRule {
diff --git a/crates/liteparse-ooxml/src/render/layout/section/layout.rs b/crates/liteparse-ooxml/src/render/layout/section/layout.rs
index 52f555c..ad09ca4 100644
--- a/crates/liteparse-ooxml/src/render/layout/section/layout.rs
+++ b/crates/liteparse-ooxml/src/render/layout/section/layout.rs
@@ -223,8 +223,8 @@ impl<'doc> PageLayoutState<'doc> {
// page. Only rescan when the page changes. The scan tracks inline
// column/page boundaries (`scan_inline_page_boundary`) so a float past
// an in-paragraph break isn't attributed to this page, and skips blocks
- // whose absolute float has been relocated to a later page (#86's
- // relocation replay), so wrapped text on the replayed page ignores it.
+ // whose absolute float has been relocated to a later page (relocation
+ // replay), so wrapped text on the replayed page ignores it.
if self.abs_floats_dirty {
self.current_page_abs_floats.clear();
let mut scan_col = self.current_col;
@@ -1557,7 +1557,7 @@ pub(crate) fn layout_section_with_clearance(
let page_chunks = split_at_page_breaks(fragments);
let mut para_start_y = state.cursor_y;
state.last_para_start_y = state.cursor_y;
- // §17.4.56 (#86 relocation): true once any of this paragraph's
+ // §17.4.56: true once any of this paragraph's
// content has been placed, so a later overflow relocates its
// absolute float instead of double-wrapping earlier text.
let mut paragraph_content_placed = false;
@@ -1687,7 +1687,7 @@ pub(crate) fn layout_section_with_clearance(
// the first segment by the unbreakable-prefix guard, so
// the tail reuses its fitted lines). Paragraphs that own
// floating objects stay atomic (the object anchors to one
- // page) and take the #86 relocation path in the `else`
+ // page) and take the relocation path in the `else`
// branch below. Footnotes are reserved per segment, but
// only for a single, unbroken chunk — with explicit
// page/column breaks their reference→segment mapping is
@@ -1734,7 +1734,7 @@ pub(crate) fn layout_section_with_clearance(
// and re-placing at the destination page, whose
// max_height differs and re-clamps the height.
drop(placed);
- // #86: if this atomic paragraph owns an absolute
+ // If this atomic paragraph owns an absolute
// wrap float and moves to a new page before any of
// its own content is placed, earlier source-page
// text may already have wrapped around that future
@@ -1814,7 +1814,7 @@ pub(crate) fn layout_section_with_clearance(
}
state.cursor_y += para.size.height;
}
- // #86: mark that content of this paragraph has landed
+ // Mark that content of this paragraph has landed
// (either split segments or the atomic block), so a
// later block's absolute-float overflow relocates rather
// than double-wrapping this already-placed text.
@@ -2102,9 +2102,6 @@ pub(crate) fn layout_section_with_clearance(
// attribute exists for tables.
wrap_text: float::WrapTextSide::BothSides,
});
- // Suppress unused warning when `is_anchor` is no
- // longer the discriminant for registration.
- let _ = is_anchor;
}
block_idx += 1;
continue;
@@ -2203,7 +2200,7 @@ mod keep_next_chain_tests {
/// §17.3.1.14 / §17.3.1.15 — `paragraph_breakable`, the predicate shared by the
/// placement gate and the keepNext predictor. Extracted precisely because the
-/// two had drifted apart on the footnote condition (E4a#3).
+/// two had drifted apart on the footnote condition.
#[cfg(test)]
mod paragraph_breakable_tests {
use super::*;
diff --git a/crates/liteparse-ooxml/src/render/layout/section/mod.rs b/crates/liteparse-ooxml/src/render/layout/section/mod.rs
index fbfe581..ffcbd4a 100644
--- a/crates/liteparse-ooxml/src/render/layout/section/mod.rs
+++ b/crates/liteparse-ooxml/src/render/layout/section/mod.rs
@@ -561,8 +561,8 @@ mod tests {
#[test]
fn bordered_paragraph_splits_across_pages() {
- // §17.3.1.24: a bordered paragraph now splits (Phase C) instead of moving
- // whole — the eight lines span two pages, and each page carries border
+ // §17.3.1.24: a bordered paragraph splits instead of moving whole —
+ // the eight lines span two pages, and each page carries border
// draw commands (Line) for its segment of the box.
let mut block = multiline_para(8, false, true);
if let LayoutBlock::Paragraph { style, .. } = &mut block {
@@ -2970,15 +2970,10 @@ mod tests {
let mut row_positions: Vec<(usize, f32, f32, String)> = Vec::new();
for (pi, page) in pages.iter().enumerate() {
for cmd in &page.commands {
- if let DrawCommand::Text { text, position, .. } = cmd {
- if text.starts_with('r') {
- row_positions.push((
- pi,
- position.x.raw(),
- position.y.raw(),
- text.to_string(),
- ));
- }
+ if let DrawCommand::Text { text, position, .. } = cmd
+ && text.starts_with('r')
+ {
+ row_positions.push((pi, position.x.raw(), position.y.raw(), text.to_string()));
}
}
}
diff --git a/crates/liteparse-ooxml/src/render/layout/section/types.rs b/crates/liteparse-ooxml/src/render/layout/section/types.rs
index e779bc0..e4444ab 100644
--- a/crates/liteparse-ooxml/src/render/layout/section/types.rs
+++ b/crates/liteparse-ooxml/src/render/layout/section/types.rs
@@ -18,12 +18,10 @@ use crate::render::resolve::shape_geometry::SubPath;
/// baked into the float's resolved page-coordinate rectangle before
/// registration.
///
-/// Tier 1 treats `Tight` and `Through` as spec-compliant placeholders: both
-/// take `Square`'s path exactly — registered as an active float
-/// ([`WrapMode::registers_as_wrap_float`]) and narrowing each line by the
-/// float's bounding rect and the side constraint, never by the polygon the
-/// two modes actually name. Full polygon-aware line fitting is deferred to
-/// Tier 2 and not yet designed.
+/// `Tight` and `Through` currently take `Square`'s path exactly — registered
+/// as an active float ([`WrapMode::registers_as_wrap_float`]) and narrowing
+/// each line by the float's bounding rect and the side constraint, not by the
+/// polygon those two modes name. Polygon-aware line fitting is not implemented.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WrapMode {
/// §20.4.2.15 wrapNone — no reflow; drawing paints over or under text.
@@ -112,8 +110,7 @@ pub struct FloatingImage {
}
impl FloatingImage {
- /// §20.4.2.18 convenience — kept for call-site ergonomics during the
- /// wrap-mode rollout. Equivalent to `matches!(self.wrap_mode, WrapMode::TopAndBottom)`.
+ /// §20.4.2.18 convenience — true when `wrap_mode` is `TopAndBottom`.
pub fn is_wrap_top_and_bottom(&self) -> bool {
matches!(self.wrap_mode, WrapMode::TopAndBottom)
}
@@ -224,15 +221,13 @@ pub struct FloatingShape {
/// §20.4.2.3 distL/distR — horizontal distance from surrounding text.
pub dist_left: Pt,
pub dist_right: Pt,
- /// §20.4.2.3 @behindDoc — painted behind document text.
- pub behind_doc: bool,
/// Path subpaths in shape-local Pt (already scaled into `size`).
pub paths: Vec<SubPath>,
/// Resolved fill.
pub fill: ResolvedFill,
/// Optional resolved stroke.
pub stroke: Option<ResolvedStroke>,
- /// Resolved post-processing effects (painter may defer all in Tier 0).
+ /// Resolved post-processing effects (the painter may defer them).
pub effects: Vec<ResolvedEffect>,
/// §17.17.1 / §20.1.2.1.1: pre-laid-out commands for the shape's
/// text-box content (`wps:wsp/wps:txbx/w:txbxContent`). Each
diff --git a/crates/liteparse-ooxml/src/render/layout/shape_body.rs b/crates/liteparse-ooxml/src/render/layout/shape_body.rs
index 9b2edf7..19035a9 100644
--- a/crates/liteparse-ooxml/src/render/layout/shape_body.rs
+++ b/crates/liteparse-ooxml/src/render/layout/shape_body.rs
@@ -20,10 +20,9 @@ use crate::render::layout::section::{LayoutBlock, PageParity};
/// §20.1.2.1.1 spec defaults for an absent inset: 91440 EMU horizontal,
/// 45720 EMU vertical.
///
-/// Materializing these is not optional. `BodyProperties` keeps an absent
-/// attribute as `None` rather than substituting the default, so a consumer that
-/// reads the field directly lays the body out at the full shape width — which
-/// on the PPTX corpus is 47.2% of text shapes, every one of them wrong.
+/// Applying these is required for correctness: `BodyProperties` keeps an absent
+/// attribute as `None` rather than substituting the default, so reading the
+/// field directly would lay the body out at the full shape width.
const DEFAULT_INSET_LR: f32 = 91440.0 / 12700.0; // ≈ 7.2pt
const DEFAULT_INSET_TB: f32 = 45720.0 / 12700.0; // ≈ 3.6pt
@@ -225,16 +224,13 @@ pub fn layout_shape_body(
/// Total over [`TextVertOverflow`] with no catch-all, so a new value of the
/// attribute has to state its own behaviour here.
///
-/// **This drops whole commands, which is a line-granular approximation of what
-/// Word does.** Word clips at the pixel, so a line straddling the box edge
-/// shows its top sliver; here it disappears. Real clipping needs a canvas clip
-/// that survives into paint, and draw commands are flattened into one flat
-/// per-page list with no scoping — so it would mean a new `DrawCommand`
-/// wrapper variant and an arm in every consumer. Dropping is the safe
-/// direction (`clip`'s contract is that nothing paints outside the box), and
-/// no corpus document asks for `clip` at all — 4 explicit `overflow`, 10
-/// `bodyPr` with the attribute absent, zero `clip` or `ellipsis` — so this is
-/// worth revisiting only once a real document needs the sliver.
+/// **This drops whole commands, a line-granular approximation of what Word
+/// does.** Word clips at the pixel, so a line straddling the box edge shows its
+/// top sliver; here it disappears. Real clipping needs a canvas clip that
+/// survives into paint, but draw commands are flattened into one flat per-page
+/// list with no scoping, so it would mean a new `DrawCommand` wrapper variant
+/// and an arm in every consumer. Dropping is the safe direction: `clip`'s
+/// contract is that nothing paints outside the box.
fn overflow_keeps(
overflow: crate::model::TextVertOverflow,
cmd: &DrawCommand,
@@ -260,8 +256,7 @@ mod tests {
use super::*;
use crate::model::{BodyProperties, TextAnchoringType, TextVertOverflow};
- /// An `a:bodyPr` that is *present* but declares no insets — the shape the
- /// PPTX corpus is full of.
+ /// An `a:bodyPr` that is *present* but declares no insets.
fn body_pr() -> BodyProperties {
BodyProperties {
rotation: None,
@@ -288,9 +283,8 @@ mod tests {
#[test]
fn present_bodypr_with_absent_attrs_still_takes_defaults() {
- // The case that matters: `a:bodyPr` is declared on 100% of PPTX text
- // shapes, but half of them declare no insets. Reading the `None` as
- // zero would widen the body by 14.4pt.
+ // A present `a:bodyPr` that declares no insets must still take the spec
+ // defaults; reading the `None` as zero would widen the body by 14.4pt.
let insets = BodyInsets::resolve(Some(&body_pr()));
assert_eq!(insets, BodyInsets::resolve(None));
}
diff --git a/crates/liteparse-ooxml/src/render/layout/table/borders.rs b/crates/liteparse-ooxml/src/render/layout/table/borders.rs
index 82edbf9..e8edd3f 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/borders.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/borders.rs
@@ -10,14 +10,13 @@ use crate::render::layout::draw_command::DrawCommand;
///
/// Three states rather than `Option<TableBorderLine>`, because [MS-OI29500]
/// §17.4.66 distinguishes "nothing said about this edge" from "declared
-/// `val="nil"`". The difference is entirely about **inheritance**: an omitted
-/// or `none` edge falls back to the table style, then `tblPrEx`, then
-/// `tblBorders`; `nil` declines that fallback and stays empty.
+/// `val="nil"`". The difference is about **inheritance**: an omitted or `none`
+/// edge falls back to the table style, then `tblPrEx`, then `tblBorders`; `nil`
+/// declines that fallback and stays empty. It does *not* outrank the facing
+/// cell — `nil` removes this cell's border and nothing else (see
+/// [`resolve_border_conflict`]).
///
-/// It is *not* about outranking the facing cell. `nil` removes this cell's
-/// border and nothing else — see [`resolve_border_conflict`].
-///
-/// The distinction survives resolution for one downstream reader: the page-split
+/// The distinction survives resolution for one reader: the page-split
/// top-border restore in `emit.rs` may revive an `Absent` top but must not
/// revive a `Suppressed` one. For painting they are identical, which is what
/// [`CellEdge::line`] expresses.
@@ -151,61 +150,34 @@ pub(super) fn resolve_cell_effective_borders(
/// Resolve a border conflict between two competing borders on a shared edge.
/// Returns the winning border (or `None` if both are `None`).
///
-/// The algorithm is **not in ISO/IEC 29500-1** — the standard only says a method
-/// exists. It is spelled out in [MS-OI29500] §17.4.66 (`tcBorders`, note a),
-/// which is the authority for every step below:
+/// The algorithm is not in ISO/IEC 29500-1 — the standard only says a method
+/// exists. It is spelled out in [MS-OI29500] §17.4.66 (`tcBorders`, note a):
/// 1. An edge with no border yields to one that has it. `none` counts as
-/// no border, per *"If the conflicting table cell border is `none` (no
-/// border), then the opposing border shall be displayed."*
+/// no border.
/// 2. Weight = width in eighths of a point × style number. Higher wins.
-/// 3. Equal weight: the style **earlier in the spec's precedence list** wins —
+/// 3. Equal weight: the style earlier in the spec's precedence list wins —
/// `Single` over `Double`. See `style_precedence_index`.
/// 4. Equal style: darker colour wins (`R+B+2G`, then `B+2G`, then `G`).
///
-/// **What `nil` does, and what it does not.** The note adds *"If the conflicting
-/// table cell border is `nil`, then no border shall be displayed"*, which reads
-/// as `nil` beating everything on the far side of the edge. It does not, and
-/// implementing it that way deleted borders Word draws. `nil` acts on **its own
-/// cell only**: it is how a cell declines the inheritance the note describes one
-/// step earlier (style → `tblPrEx` → `tblBorders`), which is the whole of its
-/// difference from `none`. The facing cell's border is untouched, so
-/// `Suppressed` yields here exactly like `Absent`.
-///
-/// Three independent facts in `IP 05 Trenches` fix the reading, and no evidence
-/// contradicts it:
-///
-/// * a cell declaring `<w:bottom w:val="single"/>` above one declaring
-/// `<w:top w:val="nil"/>` — Word draws the line, as does macOS's own DOCX
-/// renderer on the same markup;
-/// * a cell that *inherits* its bottom from `insideH`, faced by a `gridSpan=2`
-/// spacer cell whose `nil` was aimed at the neighbouring column — Word draws
-/// that line too, and it could not do otherwise: a cell paints one border
-/// across its whole width, so a wide cell's `nil` cannot punch a hole in the
-/// cell above it;
-/// * down the document's spacer columns the generator writes `nil` on **both**
-/// sides of every shared edge. Writing both is only necessary because one
-/// alone does not suppress.
-///
-/// `nil` is still not a no-op: with nothing facing it — a table's outer edge, or
-/// a facing cell that is also `nil` — declining inheritance is exactly what
-/// removes the border. Both halves are pinned by
-/// `tests/table_border_conflict.rs`.
+/// `nil` acts on its own cell only: it declines the inheritance in step 0
+/// (style → `tblPrEx` → `tblBorders`), which is its whole difference from
+/// `none`, but does not remove the facing cell's border. The note's literal
+/// wording (*"If the conflicting table cell border is `nil`, then no border
+/// shall be displayed"*) would delete borders Word draws — a cell paints one
+/// border across its whole width, so a wide cell's `nil` cannot punch a hole in
+/// the cell above it. So `Suppressed` yields here exactly like `Absent`. `nil`
+/// is still not a no-op: with nothing facing it (a table's outer edge, or a
+/// facing `nil`) declining inheritance is what removes the border.
///
-/// **The comparison is a total order, and that is the point.** The caller feeds
-/// this (upper row's bottom, lower row's top) and (left cell's right, right
-/// cell's left), so a rule that stops at step 2 leaves the winner decided by
-/// *which side of the edge a border came from* — an implementation detail. Ties
-/// used to fall through to whichever argument came first, which meant an
-/// equal-weight 3pt single beat a 1pt double or lost to it depending on
-/// argument order, and of two equal borders differing only in colour the paler
-/// one won half the time. `resolve_border_conflict(a, b)` now always equals
-/// `resolve_border_conflict(b, a)`.
+/// The comparison is a **total order** so the result is independent of argument
+/// order: the caller feeds (upper row's bottom, lower row's top) and (left
+/// cell's right, right cell's left), and the winner must not depend on which
+/// side of the edge a border came from.
///
-/// Suppression is still a *third* state, which is why the argument type is
-/// [`CellEdge`] and not `Option<TableBorderLine>`: when neither side paints,
-/// returning `Suppressed` rather than `Absent` keeps the two distinguishable for
-/// the caller — a suppressed edge must not be revived by the page-split
-/// top-border restore in `emit.rs`, whereas an absent one should be.
+/// Suppression is a third state — the reason the argument type is [`CellEdge`],
+/// not `Option<TableBorderLine>`. When neither side paints, returning
+/// `Suppressed` rather than `Absent` keeps them distinguishable: a suppressed
+/// edge must not be revived by the page-split top-border restore in `emit.rs`.
pub(super) fn resolve_border_conflict(a: CellEdge, b: CellEdge) -> CellEdge {
match (a, b) {
(CellEdge::Line(la), CellEdge::Line(lb)) => {
@@ -229,14 +201,11 @@ pub(super) fn resolve_border_conflict(a: CellEdge, b: CellEdge) -> CellEdge {
///
/// Returns integers so the key is `Ord`: comparing `f32` weights directly would
/// need `partial_cmp`, and a `NaN` width (unreachable, but the type permits it)
-/// would silently make the comparison non-transitive and reintroduce the
-/// order-dependence this exists to remove.
+/// would make the comparison non-transitive and reintroduce order-dependence.
///
-/// **Two fields are inverted, and for the same reason.** The spec states both
-/// style and colour as "lower value wins" rankings — earliest in the precedence
-/// list, and smallest brightness. This key is "greater wins", so each is
-/// subtracted from its type's maximum. Inverting one and not the other is the
-/// defect this layout is meant to make obvious.
+/// Style and colour are both spec-ranked as "lower value wins" (earliest in the
+/// precedence list, smallest brightness). This key is "greater wins", so each is
+/// subtracted from its type's maximum.
fn border_precedence(b: &TableBorderLine) -> (u32, u8, u32, u32, u32) {
let (l0, l1, l2) = colour_luminance(b);
(
@@ -258,12 +227,9 @@ fn border_precedence(b: &TableBorderLine) -> (u32, u8, u32, u32, u32) {
/// "Higher on the list" means **earlier**, so this returns the 0-based index
/// into it and **lower wins** — `border_precedence` inverts it.
///
-/// So `Single` beats `Double` at equal weight, which is worth stating plainly
-/// because the intuition runs the other way: a double border has the greater
-/// *style number* (3 vs 1) and therefore the greater weight at equal width, and
-/// it is easy to carry that ordering into the tie-break, where the spec
-/// reverses it. Equal weight means the single is three times wider — a 3pt
-/// solid line against two 0.33pt hairlines — and the spec prefers the single.
+/// So `Single` beats `Double` at equal weight (note the intuition runs the other
+/// way: a double border has the greater style number, 3 vs 1, so at equal weight
+/// the single is three times wider, and the spec prefers it).
///
/// Only `Single` and `Double` reach layout (the other 24 §17.4.38 styles are
/// approximated as `Single` — see `convert_model_border`), so only their two
@@ -698,15 +664,10 @@ mod conflict_tests {
v
}
- /// **The property that matters.** The caller passes (upper row's bottom,
- /// lower row's top) and (left cell's right, right cell's left), so a
- /// resolution that depends on argument order makes the rendered border
- /// depend on which *side of the edge* it was declared on.
- ///
- /// Before this was a total order, ties fell through to whichever argument
- /// came first: an equal-weight 3pt single beat a 1pt double or lost to it
- /// depending on the call, and of two borders differing only in colour the
- /// paler one won half the time.
+ /// The caller passes (upper row's bottom, lower row's top) and (left cell's
+ /// right, right cell's left), so a resolution that depends on argument order
+ /// would make the rendered border depend on which side of the edge it was
+ /// declared on.
#[test]
fn resolution_is_independent_of_argument_order() {
let borders = sample_borders();
@@ -744,12 +705,7 @@ mod conflict_tests {
/// Step 3 — equal weight, so position in the spec's precedence list decides,
/// and **`Single` wins**. 3pt single and 1pt double both weigh 3
- /// (width × style number), which is exactly the tie the pre-E5b#2 code
- /// resolved by argument position.
- ///
- /// This test previously asserted the opposite, and was mutation-checked in
- /// that state — the code and the assertion shared one error, so no mutation
- /// could expose it. [MS-OI29500] §17.4.66 orders the list
+ /// (width × style number). [MS-OI29500] §17.4.66 orders the list
/// `single, thick, double, …` and displays *"the higher of the two on this
/// precedence list"*, i.e. the earlier one.
#[test]
@@ -875,17 +831,13 @@ mod conflict_tests {
);
}
- /// **`nil` does not reach across the edge.** [MS-OI29500] §17.4.66 says
- /// *"If the conflicting table cell border is nil, then no border shall be
- /// displayed"*, and read literally that is wrong: `nil` empties its own
- /// cell's edge and leaves the facing cell's border alone. It loses from
- /// either side and at any weight — even a hairline survives it.
- ///
- /// `IP 05 Trenches` is the reference. `<w:bottom w:val="single"/>` above
- /// `<w:top w:val="nil"/>` draws in Word and in macOS's DOCX renderer; so
- /// does an *inherited* bottom faced by a `gridSpan` spacer cell's `nil`, and
- /// it must — a cell paints one border across its whole width, so a wide
- /// cell's `nil` cannot punch a hole in the cell above it.
+ /// `nil` does not reach across the edge. [MS-OI29500] §17.4.66 says *"If the
+ /// conflicting table cell border is nil, then no border shall be displayed"*,
+ /// and read literally that is wrong: `nil` empties its own cell's edge and
+ /// leaves the facing cell's border alone. It loses from either side and at
+ /// any weight — even a hairline survives it, because a cell paints one border
+ /// across its whole width and so a wide cell's `nil` cannot punch a hole in
+ /// the cell above it.
#[test]
fn nil_yields_to_the_facing_border() {
let hair = line(0.25, TableBorderStyle::Single, BLACK);
@@ -1065,12 +1017,12 @@ mod edge_mapping_tests {
);
}
- /// E5b#7. `num_rows == 0` is unreachable through `layout_table` — it returns
- /// early on empty input, and every other caller is inside a row loop — but
- /// `num_rows` is a free parameter of a `pub(super)` function, so the
- /// last-row test must not depend on a caller having checked it.
- /// `row_idx == num_rows - 1` underflows here; `row_idx + 1 == num_rows`
- /// answers "no row is the last row of an empty table".
+ /// `num_rows == 0` is unreachable through `layout_table` (it returns early on
+ /// empty input, and every other caller is inside a row loop), but `num_rows`
+ /// is a free parameter of a `pub(super)` function, so the last-row check must
+ /// not depend on a caller having validated it. `row_idx == num_rows - 1`
+ /// underflows here; `row_idx + 1 == num_rows` answers "no row is the last row
+ /// of an empty table".
#[test]
fn an_empty_table_does_not_underflow_the_last_row_check() {
assert_eq!(
diff --git a/crates/liteparse-ooxml/src/render/layout/table/emit.rs b/crates/liteparse-ooxml/src/render/layout/table/emit.rs
index 0b37428..3e15c02 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/emit.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/emit.rs
@@ -109,10 +109,9 @@ fn emit_one_row(
let row_top = *cursor_y + leading;
let row_height = mr.height - leading;
for (cell_ci, (entry, cell_input)) in mr.entries.iter().zip(row.cells.iter()).enumerate() {
- // §17.4.85: the merged span, used below for vAlign and here for
- // shading. Hoisted above the shading so both read the same height —
- // shading used `row_height` while vAlign used the span, so a shaded
- // merged cell was coloured across its first row only.
+ // §17.4.85: the merged span height, used below for both vAlign and
+ // shading — the two must read the same height or a shaded merged cell
+ // is coloured across its first row only.
let effective_h = if cell_input.vertical_merge == Some(VerticalMergeState::Restart) {
vmerge_ctx
.map(|(m, rs, row_idx)| merged_span_height(m, rs, row_idx, entry.grid_col))
@@ -138,12 +137,10 @@ fn emit_one_row(
// §17.4.38: restore the top border when this row starts a slice and the
// resolved top was removed by conflict resolution or adjacent-table
- // collapse. An edge the author set to `nil` must NOT be restored — they
- // asked for no border — and `CellEdge` already says which is which, so
- // this reads the resolved edge instead of re-deriving intent from
- // `cell_input`. That also fixes the `none` case for free: `none` now
- // resolves to `Absent` and is restorable, where the old re-derivation
- // lumped it in with `nil` and left a continuation slice with no top.
+ // collapse. An edge the author set to `nil` must NOT be restored (they
+ // asked for no border), so this reads the resolved `CellEdge` — which
+ // already distinguishes `Absent` (restorable, includes `none`) from
+ // `Suppressed` — instead of re-deriving intent from `cell_input`.
let cell_top = match mr.borders[cell_ci].top {
CellEdge::Absent => top_border_override.into(),
resolved => resolved,
@@ -450,7 +447,7 @@ mod tests {
);
}
- // ── Buffer layering and the nil/override interaction (E5b#3) ─────────
+ // ── Buffer layering and the nil/override interaction ─────────────────
const RED: RgbColor = RgbColor { r: 255, g: 0, b: 0 };
diff --git a/crates/liteparse-ooxml/src/render/layout/table/grid.rs b/crates/liteparse-ooxml/src/render/layout/table/grid.rs
index b9e2dbf..b1da532 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/grid.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/grid.rs
@@ -107,35 +107,12 @@ fn cell_has_nested_table(cell: &TableCellInput) -> bool {
/// cell's content fits within their combined height. The shortfall is spread
/// **evenly** over the spanned rows.
///
-/// Even distribution is a choice, not a spec rule, and ECMA-376 cannot settle
-/// it. All three places a rule would have to live were checked: §17.4.85
-/// `vMerge` defines which cells merge and carries no height language at all;
-/// §17.4.81 `trHeight`/`auto` defers to "the height required by its contents"
-/// without ever defining "contents" for a cell that spans rows; and §17.4.21
-/// `hideMark` — the spec's only row-height *rule* — says a row's height is
-/// "determined by the height of all glyphs in all cells in that row", without
-/// mentioning `vMerge`.
-///
-/// §17.4.21 constrains the answer without giving it. The model it describes is
-/// a **per-row maximum** over that row's cells, not a budget divided among
-/// rows, and even distribution (`overflow / rows`) is not expressible as a
-/// per-row maximum of anything — so of the candidates it is the one the spec's
-/// own sentence structurally disfavours. It does *not* follow that the restart
-/// row takes the excess: applied literally to a span, §17.4.21 sizes the
-/// restart row to the whole content while each `continue` row still carries its
-/// own end-of-cell mark, making the merged box taller than its content by the
-/// sum of the continue rows. No implementation does that, which is the tell
-/// that the sentence was written without merged cells in mind. The spec is
-/// silent by omission, not by implication.
-///
-/// So even distribution is disfavoured and last-row and first-row both remain
-/// open; last-row has the better structural argument (a single-pass
-/// top-to-bottom sizer can only enforce a span's total once the span closes)
-/// but no spec text. The choice is *observable* — it changes rendered output on
-/// one real corpus document — so settling it needs a Word-exported PDF of a
-/// two-row vertical merge whose restart cell overflows both rows. Until then
-/// the behaviour is pinned by `expand_spreads_overflow_across_the_merge_span`,
-/// so it cannot change silently.
+/// Even distribution is a choice, not a spec rule: ECMA-376 defines which cells
+/// merge (§17.4.85) and how a plain row's height is decided (§17.4.21, a per-row
+/// maximum over that row's cells) but says nothing about how a merged cell's
+/// overflow is apportioned among the rows it spans. The behaviour is
+/// observable, so it is pinned by
+/// `expand_spreads_overflow_across_the_merge_span` and must not change silently.
///
/// A lone `Restart` with no `Continue` below it is not a span, and is sized by
/// the normal row-height path in `measure_table_rows` instead.
@@ -361,10 +338,6 @@ mod tests {
}
// ── §17.4.85 row_group_end / §17.4.1 build_row_groups ────────────────
- //
- // These three functions decide every table page break and the whole
- // vertical-merge height distribution, and had no direct tests — the hole
- // a zero-height row was found hiding in.
use super::super::types::MeasuredRow;
use crate::render::layout::cell::CellLayout;
@@ -521,12 +494,9 @@ mod tests {
/// The core §17.4.85 behaviour: when a `Restart` cell's content exceeds the
/// rows it spans, the shortfall is spread across them.
///
- /// Note this pins **even distribution**, which is what the code does and
- /// not obviously what Word does — see `expand_rows_for_vmerge` for why
- /// ECMA-376 cannot settle it and why even distribution is in fact the
- /// candidate §17.4.21 structurally disfavours. This test will need updating
- /// if a Word reference render settles it the other way; it exists to make
- /// that a deliberate change rather than a silent one.
+ /// This pins **even distribution**, which ECMA-376 does not mandate (see
+ /// `expand_rows_for_vmerge`); the test exists so any change to that choice
+ /// is deliberate rather than silent.
#[test]
fn expand_spreads_overflow_across_the_merge_span() {
let rows = vec![
@@ -564,12 +534,9 @@ mod tests {
}
/// A `Restart` with nothing continuing under it is left completely alone —
- /// the early return when the group is a single row.
- ///
- /// This is the companion to the fix in `measure.rs`: because this function
- /// contributes nothing here, the row's height has to come from the normal
- /// `max_height` path instead, or the row collapses to zero while still
- /// drawing its content.
+ /// the early return when the group is a single row. Its height must then
+ /// come from the normal `max_height` path in `measure_table_rows`, or the
+ /// row would collapse to zero while still drawing its content.
#[test]
fn expand_does_nothing_for_a_lone_restart() {
let rows = vec![plain_row(vec![merged_cell(Some(
diff --git a/crates/liteparse-ooxml/src/render/layout/table/measure.rs b/crates/liteparse-ooxml/src/render/layout/table/measure.rs
index 1235989..61f0df1 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/measure.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/measure.rs
@@ -386,7 +386,7 @@ mod tests {
}
}
- /// A table style like `Tabellenraster`: every side plus insideH/insideV.
+ /// A table style with every side plus insideH/insideV.
fn all_single() -> TableBorderConfig {
let s = single(0.5);
TableBorderConfig {
@@ -431,30 +431,25 @@ mod tests {
}
}
- /// [MS-OI29500] §17.4.66 regression: a `gridSpan` upper cell facing several
- /// lower cells must not drop the later cells' top borders (previously only
- /// the first lower cell was resolved and the rest nulled), and the whole
- /// shared edge must be drawn from a single side so the line does not split
- /// across two y positions. Mirrors the real doc's
- /// `[spacer | Function: | Qualitätssicherung]` row under a `gridSpan` header.
+ /// [MS-OI29500] §17.4.66: a `gridSpan` upper cell facing several lower cells
+ /// must not drop the later cells' top borders, and the whole shared edge
+ /// must be drawn from a single side so the line does not split across two y
+ /// positions.
///
- /// Non-uniformity comes from a **heavier border on one column**, not from a
- /// `nil`. It used to come from a nil, which worked only while nil resolved
- /// to "absent": now that nil suppresses (§17.4.66), a nil under the wide
- /// cell makes its run uniformly suppressed and the upper row owns the edge —
- /// the opposite branch, so the configuration no longer reaches the bug this
- /// test exists for. Suppression is covered separately by
- /// `nil_suppresses_across_a_gridspan_mismatch`.
+ /// Non-uniformity here comes from a **heavier border on one column**, not
+ /// from a `nil` (a `nil` under the wide cell would make its run uniformly
+ /// suppressed and hand the edge to the upper row — the opposite branch,
+ /// covered by `nil_suppresses_across_a_gridspan_mismatch`).
#[test]
fn wide_upper_cell_draws_whole_edge_from_lower_row() {
let s = single(0.5);
let heavy = single(2.0);
let rows = vec![
- // Row 0: gridSpan=2 header over spacer+Function, then two single
- // cells over the Qualitätssicherung span. All bottoms inherit.
+ // Row 0: gridSpan=2 header over cols 0-1, then two single cells over
+ // cols 2-3. All bottoms inherit.
row(vec![cell(2, None), cell(1, None), cell(1, None)]),
- // Row 1: [spacer | Function (heavy top) | Q (gridSpan=2)]. The heavy
- // top on column 1 alone makes the wide upper cell's run non-uniform.
+ // Row 1: [spacer | heavy top | gridSpan=2]. The heavy top on column
+ // 1 alone makes the wide upper cell's run non-uniform.
row(vec![
cell(1, None),
cell(1, Some(cb(Some(CellBorderOverride::Border(heavy)), None))),
@@ -473,7 +468,7 @@ mod tests {
);
// Whole edge drawn from the lower row → every upper bottom cleared,
- // so Function and Qualitätssicherung tops share one y position.
+ // so columns 1 and 2 tops share one y position.
for b in &m.rows[0].borders {
assert_eq!(
b.bottom,
@@ -489,24 +484,21 @@ mod tests {
assert_eq!(
m.rows[1].borders[1].top.line(),
Some(heavy),
- "Function keeps its heavier top border across the gridSpan mismatch"
+ "column 1 keeps its heavier top border across the gridSpan mismatch"
);
assert_eq!(
m.rows[1].borders[2].top.line(),
Some(s),
- "Qualitätssicherung top drawn from the same (lower) side as Function"
+ "column 2 top drawn from the same (lower) side as column 1"
);
}
/// §17.4.66 step 0 across a `gridSpan` mismatch: a `nil` bottom on a wide
/// upper cell suppresses the columns it spans that fall back to the table —
/// but **not** the column where the lower cell has a border of its own,
- /// which survives and is drawn from below. One nil bottom therefore resolves to two different
- /// answers along its own width, which is exactly the case that forces the
- /// per-column resolution this pass does.
- ///
- /// This is the configuration `wide_upper_cell_draws_whole_edge_from_lower_row`
- /// used to carry, kept here for what it now demonstrates.
+ /// which survives and is drawn from below. One nil bottom therefore resolves
+ /// to two different answers along its own width, which is exactly the case
+ /// that forces the per-column resolution this pass does.
#[test]
fn nil_suppresses_across_a_gridspan_mismatch() {
let s = single(0.5);
@@ -534,8 +526,8 @@ mod tests {
);
// The nil bottom spans columns 0-1 and resolves differently on each:
- // column 0 faces another nil and stays suppressed, column 1 faces
- // Function's *declared* top and loses to it. A cell paints one border
+ // column 0 faces another nil and stays suppressed, column 1 faces the
+ // lower cell's *declared* top and loses to it. A cell paints one border
// across its width, so that split hands the whole edge to the lower row.
for b in &m.rows[0].borders {
assert_eq!(
@@ -552,7 +544,7 @@ mod tests {
assert_eq!(
m.rows[1].borders[1].top.line(),
Some(s),
- "column 1: Function has a top of its own, so the nil above does not erase it"
+ "column 1: the lower cell has a top of its own, so the nil above does not erase it"
);
// Columns outside the nil span keep the inherited insideH, drawn from
// the same (lower) side so the line sits at one y.
@@ -624,14 +616,10 @@ mod tests {
/// `insideH` for its whole width and paints one border across it; a
/// neighbour's `nil` empties only that neighbour's own edge.
///
- /// This is `IP 05 Trenches`' `Date/Time:` cell with the sides swapped — the
- /// real document has the wide spacer cell *below*, its `nil` aimed at the
- /// narrow spacer column, and the label cell above still draws the bottom it
- /// inherited. The assertion here was inverted twice: once when `nil`
- /// wrongly collapsed to "absent" (so it also wrongly *inherited*), and once
- /// when `nil` was made to win the conflict outright. Declining inheritance
- /// and overruling the neighbour are different powers; `nil` has only the
- /// first.
+ /// Declining inheritance and overruling the neighbour are different powers;
+ /// `nil` has only the first. A `nil` that wrongly collapsed to `Absent`
+ /// would also wrongly inherit; a `nil` made to win the conflict outright
+ /// would erase the facing border. Neither is correct.
#[test]
fn nil_spacer_cannot_punch_a_gap_through_a_wide_facing_cell() {
let s = single(0.5);
@@ -669,11 +657,10 @@ mod tests {
assert_eq!(m.rows[1].borders[0].top.line(), None);
}
- /// [MS-OI29500] §17.4.66 regression: an upper `gridSpan` cell that leaves the last
- /// column uncovered (its gridAfter gap) must not "own" the edge, or a
- /// lower cell straddling that boundary would draw its own top over the
- /// upper bottom → a doubled line. Mirrors the real doc's `gridSpan=9`
- /// section row above the `Observations` (`gridSpan=2`) header.
+ /// [MS-OI29500] §17.4.66: an upper `gridSpan` cell that leaves the last
+ /// column uncovered (its gridAfter gap) must not "own" the edge, or a lower
+ /// cell straddling that boundary would draw its own top over the upper
+ /// bottom → a doubled line.
#[test]
fn upper_grid_after_gap_yields_edge_to_lower_row() {
let s = single(0.5);
diff --git a/crates/liteparse-ooxml/src/render/layout/table/mod.rs b/crates/liteparse-ooxml/src/render/layout/table/mod.rs
index 2ad53ac..5186a51 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/mod.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/mod.rs
@@ -335,10 +335,8 @@ pub(crate) fn layout_table_paginated_with_page_heights(
// A group taller than a whole page never fits anywhere. Advancing
// unconditionally then abandons `current_slice` while it is still
// empty — the caller turns that empty leading slice into a page push,
- // so a table starting at the top of a page emitted a **blank page**
- // and the group overflowed the next one just the same (the warning
- // below fired either way). Same shape as the E4c floating-table
- // spillover: acting on a condition the action cannot change.
+ // so a table starting at the top of a page would emit a blank page and
+ // overflow the next one just the same. Only advance when it gains room.
//
// Comparing against the *post-header* room is what makes this exact —
// repeating headers can leave a fresh page with less usable space than
@@ -842,9 +840,7 @@ mod tests {
///
/// The row declares no `gridAfter`: layout derives the right edge from
/// `grid_before` plus the cells' spans, so the trailing gap is a
- /// *consequence* of the cells, not a separate input. (This test previously
- /// set a `grid_after` field that no layout code read, so it asserted the
- /// same positions whether the field was right, wrong, or absent.)
+ /// consequence of the cells, not a separate input.
#[test]
fn row_shorter_than_the_grid_leaves_the_trailing_columns_empty() {
// Shaded cells so the emitted rects expose each cell's *width* — text
@@ -911,10 +907,7 @@ mod tests {
/// right edge as well. Distinct widths identify which border was applied —
/// `left`/`right` are 4pt, `inside_v` is 1pt — so a single 4pt rect
/// anywhere in the output means an outer border leaked onto an interior
- /// edge.
- ///
- /// The right-edge half of this used to be spelled `grid_after: 1` on a
- /// field no layout code read; it is the cells' spans that place that edge.
+ /// edge. The right edge is placed by the cells' spans, not a `gridAfter`.
#[test]
fn row_inset_from_both_edges_uses_inside_v_on_both_sides() {
let rows = vec![TableRowInput {
@@ -1866,11 +1859,10 @@ mod tests {
/// A `Restart` cell with no `Continue` row under it is an ordinary cell.
///
- /// It used to fall through *both* height paths: `measure_table_rows`
- /// skipped every merged cell (deferring to the span calculation) and
- /// `expand_rows_for_vmerge` returned early because the "span" is one row.
- /// The row therefore got zero height while still emitting its content, so
- /// whatever followed the table drew on top of it.
+ /// Both height paths skip a genuine merged cell (`measure_table_rows` defers
+ /// to the span calculation, `expand_rows_for_vmerge` returns early for a
+ /// one-row "span"), so a lone restart must be sized by the normal path or it
+ /// gets zero height while still emitting content.
///
/// Asserted against the unmerged control rather than a literal, so the
/// test states the actual rule — a lone restart behaves like no merge at
@@ -1941,7 +1933,7 @@ mod tests {
/// the section layer turns into a blank page.
///
/// `available_height == page_height` models the table starting at the top
- /// of a page, which is exactly when the old code emitted the blank.
+ /// of a page, the case where advancing would emit the blank.
#[test]
fn oversized_group_at_page_top_does_not_emit_an_empty_leading_slice() {
let mut row = tall_row(20); // ≈ 280pt
@@ -2191,9 +2183,8 @@ mod tests {
/// lost its bottom gap depending only on whether it fitted on one page.
///
/// Asserted against absolute values and against the **monolithic** path,
- /// which is a genuinely separate code path. Comparing one paginated layout
- /// to another cannot see this: a mutation that drops the gap drops it from
- /// both sides and the comparison still holds.
+ /// which is a genuinely separate code path — comparing one paginated layout
+ /// to another would drop the gap from both sides and miss the regression.
///
/// Empty cells make the arithmetic exact — each row's whole height is its
/// own reserved leading gap (see
diff --git a/crates/liteparse-ooxml/src/render/layout/table/split.rs b/crates/liteparse-ooxml/src/render/layout/table/split.rs
index 12fb372..8147edb 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/split.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/split.rs
@@ -152,22 +152,14 @@ fn cut_for_cell(
}
let cont_top = largest_legal_cut(&entry.layout.lines, budget)?;
- // Load-bearing for **termination**, not tidiness.
- //
- // `cont_top` becomes this cell's `shift`, and `split_row_at` derives
- // `second.height = mr.height - max(shift)`. `mod.rs`'s continuation loop
- // re-splits `second` until it fits, so a cut with `shift == 0` would hand
- // back a continuation identical to its input and spin forever. This check
- // is what makes "`find_row_cut` returned `Some`" imply "the row strictly
- // shrank", which is the loop's whole termination argument.
- //
- // Today it is unreachable: `largest_legal_cut` returns a line's `top_y`,
- // and the stacker emits strictly increasing tops, so offset 0 never comes
- // back for a real cell. That makes this a backstop for an invariant owned
- // by another module rather than by this one — keep it, and note that only
- // `zero_offset_cut_is_rejected_so_the_shift_is_never_zero` covers it,
- // because it builds the degenerate entry by hand. Nothing routed through
- // `measure_table_rows` can.
+ // Load-bearing for termination. `cont_top` becomes this cell's `shift`, and
+ // `split_row_at` derives `second.height = mr.height - max(shift)`; `mod.rs`'s
+ // continuation loop re-splits `second` until it fits, so a cut with
+ // `shift == 0` would hand back an identical continuation and spin forever.
+ // This guard makes "`find_row_cut` returned `Some`" imply "the row strictly
+ // shrank". It is unreachable through real layout (the stacker emits strictly
+ // increasing line tops, so `largest_legal_cut` never returns 0), but backs an
+ // invariant this module cannot enforce itself.
if cont_top <= Pt::ZERO {
return None;
}
@@ -507,8 +499,7 @@ mod tests {
/// heights straddling the line-height and widow-control boundaries, and
/// cell margins large enough to swallow the budget.
///
- /// If this ever fails, `layout_table_paginated` hangs — the same class of
- /// defect as the floating-table spillover loop (E4c).
+ /// If this ever fails, `layout_table_paginated` hangs.
#[test]
fn every_accepted_cut_strictly_shrinks_the_row() {
for n_lines in [2usize, 3, 5, 12] {
@@ -645,7 +636,7 @@ mod tests {
assert_eq!(slices.len(), 20, "40 lines at 2 per page");
}
- // ── Cut correctness (E5b#4) ──────────────────────────────────────────
+ // ── Cut correctness ──────────────────────────────────────────────────
//
// The tests above pin *termination*. These pin what the cut actually
// produces: which lines land on each side, where the partition boundary
diff --git a/crates/liteparse-ooxml/src/render/layout/table/types.rs b/crates/liteparse-ooxml/src/render/layout/table/types.rs
index ae8ad56..ae6157a 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/types.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/types.rs
@@ -29,23 +29,18 @@ pub struct TableRowInput {
/// cell's leftmost grid column is `grid_before`, not 0.
///
/// There is deliberately no `grid_after` counterpart. §17.4.16 `gridAfter`
- /// is *derivable* — the row's right edge is `grid_before` plus the sum of
- /// its cells' `grid_span`s — and every consumer here works from that
- /// running grid column already, including the border resolution that
- /// decides whether the last cell sits at the table edge (`insideV`) or not.
- /// The model keeps `gridAfter` as parsed (`model::TableRowProperties`);
- /// carrying it into layout added a field nothing read.
+ /// is derivable — the row's right edge is `grid_before` plus the sum of its
+ /// cells' `grid_span`s — and every consumer here works from that running
+ /// grid column already, including the border resolution that decides whether
+ /// the last cell sits at the table edge (`insideV`) or not.
pub grid_before: u32,
- /// §17.4.61 `<w:tblPrEx><w:tblBorders/></w:tblPrEx>` — per-row
- /// override of the table-level `tblBorders`. When set, each side
- /// independently replaces the corresponding side of the table's
- /// `TableBorderConfig` for this row only; sides absent from the
- /// override fall through to the table's value.
+ /// §17.4.61 `<w:tblPrEx><w:tblBorders/></w:tblPrEx>` — per-row override of
+ /// the table-level `tblBorders`. When set, each side independently replaces
+ /// the corresponding side of the table's `TableBorderConfig` for this row
+ /// only; sides absent from the override fall through to the table's value.
///
- /// Note that an override side of `None` means "explicitly no
- /// border" (Word's `<w:top w:val="none"/>`) — the parser converts
- /// `val="none"` to `None` here, matching the layout's invariant
- /// that `None` is "draw nothing" everywhere else in this module.
+ /// An override side of `None` means "explicitly no border" (`val="none"`),
+ /// matching this module's invariant that `None` is "draw nothing".
pub border_overrides: Option<TableBorderConfig>,
}
diff --git a/crates/liteparse-ooxml/src/render/mod.rs b/crates/liteparse-ooxml/src/render/mod.rs
index ec5acb9..723313f 100644
--- a/crates/liteparse-ooxml/src/render/mod.rs
+++ b/crates/liteparse-ooxml/src/render/mod.rs
@@ -2,11 +2,11 @@
//!
//! Upstream this module is `resolve → layout → subset → paint`. Vendored here
//! are `resolve` (style/numbering cascade — everything the structure path
-//! needs) and, as of the C′ port, `layout` — dxpdf's full pagination engine
-//! with its Skia `TextMeasurer` swapped for fontdb + skrifa
-//! (`layout::measurer`, `fonts`). `subset` and `painter` are PDF-emission
-//! concerns and stay out; that is why `render()` / PDF output do not exist
-//! here and layout ends at [`layout::draw_command::LayoutedPage`].
+//! needs) and `layout` — dxpdf's pagination engine with its Skia
+//! `TextMeasurer` swapped for fontdb + skrifa (`layout::measurer`, `fonts`).
+//! `subset` and `painter` are PDF-emission concerns and stay out; that is why
+//! `render()` / PDF output do not exist here and layout ends at
+//! [`layout::draw_command::LayoutedPage`].
pub mod dimension;
pub mod emoji;
diff --git a/crates/liteparse-ooxml/src/render/raster.rs b/crates/liteparse-ooxml/src/render/raster.rs
index 11cff8f..f6a2e1a 100644
--- a/crates/liteparse-ooxml/src/render/raster.rs
+++ b/crates/liteparse-ooxml/src/render/raster.rs
@@ -1,14 +1,13 @@
//! Rasterize [`LayoutedPage`] draw commands to RGBA bitmaps — tiny-skia +
//! skrifa, no Skia proper.
//!
-//! liteparse addition (no upstream equivalent; upstream rasterizes through
-//! `painter.rs` + Skia, which the C′ vendor dropped). This module is the
-//! "rasterise from layout draw-commands directly" option from
-//! `NATIVE_OFFICE_PLAN.md`: because glyph placement re-derives pen advances
-//! from the same [`FontRegistry`]/skrifa faces the layout measured with, the
-//! raster is in the *same coordinate space* as the native `TextItem` geometry
-//! by construction — which is what makes highlight-on-screenshot safe, the
-//! thing the LibreOffice screenshot path could never guarantee.
+//! liteparse addition with no upstream equivalent (upstream rasterizes
+//! through `painter.rs` + Skia, which this vendor drops). Because glyph
+//! placement re-derives pen advances from the same [`FontRegistry`]/skrifa
+//! faces the layout measured with, the raster is in the *same coordinate
+//! space* as the native `TextItem` geometry by construction — which is what
+//! makes highlight-on-screenshot safe, something a rendered-image screenshot
+//! path could never guarantee.
//!
//! Fidelity tiers, mirroring the vendored painter's own tiering:
//! - **Rendered faithfully**: text (monochrome outlines), underlines, lines,
@@ -72,15 +71,10 @@ pub struct RasterPage {
///
/// A DOCX or PPTX page is bounded by its own page setup and never comes near
/// this. A *spreadsheet* page is not: the XLSX geometry pass deliberately
-/// never splits width (an unclipped row is the native path's whole advantage
-/// over LibreOffice's column-clipping), so page width is whatever the sheet
-/// writes. The paint census measured that tail across 103,014 pages — 99.4%
-/// land under 32 MP, 594 are above it, and the worst single page is 861,149 pt
-/// wide: 2,960 MP, ≈12 GB of RGBA. Without a clamp those pages do not render
-/// slowly, they fail to allocate.
-///
-/// The bound is deliberately at the census's own 32 MP bucket boundary so the
-/// clamp is inert for 99.4% of pages rather than a routine downscale.
+/// never splits width (an unclipped row keeps the native path's advantage
+/// over column-clipped conversion), so page width is whatever the sheet
+/// writes, and an extreme sheet can reach many gigabytes of RGBA. Without a
+/// clamp those pages do not render slowly, they fail to allocate.
pub const MAX_PAGE_PIXELS: u64 = 32_000_000;
/// The scale [`rasterize_page`] will actually use for a `page_w_pt` ×
@@ -173,9 +167,8 @@ pub fn rasterize_page(
// < Float (images that declared themselves above the flow)
//
// The last layer is the exception a producer can ask for, and it exists
- // because for one format the approximation below is not rare but the
- // norm: an XLSX picture floats over the grid *and* its values, and a
- // corpus census found painted glyphs on 29.2% of placements. Everything
+ // because for one format covering the flow is not rare but the norm: an
+ // XLSX picture routinely floats over the grid *and* its values. Everything
// a DOCX layout emits stays `float: false` and keeps the flow order.
//
// Cost of the approximation: a deliberately in-front float that does not
@@ -1113,8 +1106,8 @@ mod tests {
}
/// The clamp must be inert for every page that already fits, or it is a
- /// silent quality regression on 99.4% of the corpus rather than a
- /// backstop for the 0.6%. Letter at 150 DPI is 1.6 MP.
+ /// silent quality regression on ordinary pages rather than a backstop for
+ /// extreme ones. Letter at 150 DPI is 1.6 MP.
#[test]
fn a_page_that_fits_keeps_the_scale_it_asked_for() {
let requested = 150.0 / 72.0;
@@ -1124,11 +1117,11 @@ mod tests {
assert_eq!(effective_scale(612.0, 792.0, edge), edge);
}
- /// The census's worst page: `A1:XFD131` written out, 861,149 pt wide.
- /// At 150 DPI that is 7.3e9 px / ≈12 GB of RGBA, so the unclamped
- /// allocation is the failure mode, not the render time.
+ /// A full-width unclipped sheet row can be extremely wide; at 150 DPI an
+ /// 861,149pt-wide page is ≈12 GB of RGBA, so the unclamped allocation is
+ /// the failure mode, not the render time.
#[test]
- fn the_widest_sheet_in_the_corpus_is_clamped_under_the_ceiling() {
+ fn an_extremely_wide_sheet_is_clamped_under_the_ceiling() {
let (w, h) = (861_149.0_f32, 1_965.0_f32);
let scale = effective_scale(w, h, 150.0 / 72.0);
assert!(scale < 150.0 / 72.0, "a 2,960 MP page must be clamped");
diff --git a/crates/liteparse-ooxml/src/render/resolve/color.rs b/crates/liteparse-ooxml/src/render/resolve/color.rs
index 75e77fc..1d822d5 100644
--- a/crates/liteparse-ooxml/src/render/resolve/color.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/color.rs
@@ -1,6 +1,6 @@
//! Color resolution — Color::Auto to RGB, theme color index to RGB.
-use crate::model::{Color, ThemeColorIndex, ThemeColorScheme};
+use crate::model::Color;
/// Resolved RGB color (0xRRGGBB).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -39,11 +39,6 @@ pub fn resolve_color(color: Color, context: ColorContext) -> RgbColor {
}
}
-/// Resolve a theme color index to RGB via the color scheme.
-pub fn resolve_theme_color(index: ThemeColorIndex, scheme: &ThemeColorScheme) -> RgbColor {
- rgb_from_u32(scheme.resolve(index))
-}
-
/// Convert a packed u32 (0xRRGGBB) to RgbColor.
pub fn rgb_from_u32(v: u32) -> RgbColor {
RgbColor {
@@ -112,48 +107,4 @@ mod tests {
let c = resolve_color(Color::Auto, ColorContext::Background);
assert_eq!(c, RgbColor::WHITE);
}
-
- #[test]
- fn resolve_theme_color_accent1() {
- let scheme = ThemeColorScheme {
- accent1: 0x4472C4,
- ..Default::default()
- };
- let c = resolve_theme_color(ThemeColorIndex::Accent1, &scheme);
- assert_eq!(
- c,
- RgbColor {
- r: 0x44,
- g: 0x72,
- b: 0xC4
- }
- );
- }
-
- #[test]
- fn resolve_theme_color_dark1() {
- let scheme = ThemeColorScheme {
- dark1: 0x000000,
- ..Default::default()
- };
- let c = resolve_theme_color(ThemeColorIndex::Dark1, &scheme);
- assert_eq!(c, RgbColor::BLACK);
- }
-
- #[test]
- fn resolve_theme_color_hyperlink() {
- let scheme = ThemeColorScheme {
- hyperlink: 0x0563C1,
- ..Default::default()
- };
- let c = resolve_theme_color(ThemeColorIndex::Hyperlink, &scheme);
- assert_eq!(
- c,
- RgbColor {
- r: 0x05,
- g: 0x63,
- b: 0xC1
- }
- );
- }
}
diff --git a/crates/liteparse-ooxml/src/render/resolve/conditional.rs b/crates/liteparse-ooxml/src/render/resolve/conditional.rs
index e259d68..3cf04fe 100644
--- a/crates/liteparse-ooxml/src/render/resolve/conditional.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/conditional.rs
@@ -40,10 +40,9 @@ pub struct CellGridPosition {
///
/// `wholeTable` is not positional — it applies to every cell — so it is not
/// produced by `applicable_regions`, which answers "which *positional* regions
-/// is this cell in?". Seeding the chain with it here keeps that function honest
-/// and reuses the existing overlay machinery unchanged, so the positional
-/// precedence (including D1's banding fix) is untouched: `wholeTable` simply
-/// sits underneath.
+/// is this cell in?". Seeding the chain with it here reuses the existing
+/// overlay machinery unchanged, leaving the positional precedence untouched:
+/// `wholeTable` simply sits underneath.
///
/// The table-level half — a `wholeTable` override's `tblPr` (borders, cell
/// margins) — is folded into `ResolvedStyle::table` during style resolution,
@@ -97,6 +96,12 @@ fn applicable_regions(
) -> Vec<TableStyleOverrideType> {
let mut regions = Vec::new();
+ // A 0×N or N×0 grid has no cells; bail before the `num_rows - 1` /
+ // `num_cols - 1` arithmetic below can underflow.
+ if num_rows == 0 || num_cols == 0 {
+ return regions;
+ }
+
// §17.4.56: tblLook flags. When absent, all regions are active.
let first_row_active = look.and_then(|l| l.first_row).unwrap_or(true);
let last_row_active = look.and_then(|l| l.last_row).unwrap_or(true);
@@ -512,7 +517,7 @@ mod tests {
);
}
- // ── wholeTable base layer (§17.7.6, backlog Unit 5) ──────────────
+ // ── wholeTable base layer (§17.7.6) ──────────────────────────────
fn pos(row_idx: usize, col_idx: usize) -> CellGridPosition {
CellGridPosition {
@@ -626,8 +631,8 @@ mod tests {
);
}
- /// D1 fixed horizontal-over-vertical banding precedence (§17.7.6). Adding a
- /// base layer beneath both must not disturb it.
+ /// §17.7.6: horizontal banding outranks vertical. Adding a base layer
+ /// beneath both must not disturb that precedence.
#[test]
fn whole_table_does_not_disturb_banding_precedence() {
let overrides = vec![
diff --git a/crates/liteparse-ooxml/src/render/resolve/images.rs b/crates/liteparse-ooxml/src/render/resolve/images.rs
index 21f6b99..7cfe7d3 100644
--- a/crates/liteparse-ooxml/src/render/resolve/images.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/images.rs
@@ -22,14 +22,12 @@ pub struct MediaEntry {
/// The media one package part can reach, keyed by the `r:embed` ids **that
/// part itself declares**.
///
-/// Per part, not per package, and that is the load-bearing half rather than a
-/// caching detail. A slide, its layout and its master each carry their own
-/// `.rels`, and `rId1` in all three routinely names three different images —
-/// so an inherited picture resolved against the *slide's* table returns a real
-/// photograph from the wrong relationship. That is the same failure class as
-/// `bgRef@idx` reading `fillStyleLst` and as a deck-wide theme colouring a
-/// second master's slides: a well-typed answer that is wrong, and invisible to
-/// any gate that only asks whether resolution succeeded.
+/// Per part, not per package. A slide, its layout and its master each carry
+/// their own `.rels`, and `rId1` in all three routinely names three different
+/// images — so an inherited picture resolved against the *slide's* table would
+/// return a real photograph from the wrong relationship: a well-typed answer
+/// that is wrong, and invisible to any check that only asks whether resolution
+/// succeeded.
///
/// A missing key means "this part declares no such relationship, or it points
/// outside the package" (`r:link`), which the caller reports rather than
@@ -270,8 +268,8 @@ mod tests {
#[test]
fn src_rect_converts_thousandth_percent_crop() {
- // Real values from the IP-05 header logo: top/right/bottom crop, no
- // left. Thousandths of a percent → fractions of the natural extent.
+ // Top/right/bottom crop, no left. Thousandths of a percent → fractions
+ // of the natural extent.
let mut img = make_image_with_blip("rId1");
if let Some(GraphicContent::Picture(pic)) = img.graphic.as_mut() {
pic.blip_fill.src_rect = Some(RelativeRect {
diff --git a/crates/liteparse-ooxml/src/render/resolve/locale.rs b/crates/liteparse-ooxml/src/render/resolve/locale.rs
index dc0e9a2..1bc4541 100644
--- a/crates/liteparse-ooxml/src/render/resolve/locale.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/locale.rs
@@ -24,8 +24,7 @@ use crate::model::RunProperties;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Locale {
/// English, in any region — the one language whose number words this engine
- /// spells. Also the answer for a document that declares no language at all,
- /// which is what every document was assumed to be before `w:lang` was read.
+ /// spells. Also the answer for a document that declares no language at all.
#[default]
English,
/// A recognised language that writes a decimal **comma**: German, French,
@@ -38,12 +37,10 @@ pub enum Locale {
PointDecimal,
/// A tag whose primary subtag is not in the table below.
///
- /// It answers every question exactly as [`Locale::English`] does, on
- /// purpose: before `w:lang` was read, *every* document got a decimal point
- /// and English number words, so an unfamiliar tag has to keep rendering as
- /// it does today rather than silently losing content to a degrade. It is a
- /// separate variant because it is a different *fact* — it logs, so an
- /// unhandled language is visible rather than silently assumed English.
+ /// Answers every question exactly as [`Locale::English`] does, so an
+ /// unfamiliar tag keeps rendering with a decimal point and English number
+ /// words rather than silently losing content. A separate variant so it can
+ /// log — an unhandled language stays visible rather than assumed English.
Unrecognised,
}
@@ -128,8 +125,7 @@ impl Locale {
_ => {
log::warn!(
"w:lang: unhandled language tag {tag:?} (§17.3.2.20) — \
- assuming a decimal point and English number words, which \
- is what every document got before locale was read"
+ assuming a decimal point and English number words"
);
Locale::Unrecognised
}
@@ -162,7 +158,7 @@ mod tests {
#[test]
fn the_corpus_languages_classify_as_they_should() {
- // Every tag `test-files/` and `test-cases/` actually declares.
+ // Representative comma-decimal and English tags.
for tag in ["de-AT", "de-DE", "pl-PL", "it-IT", "ca-ES", "fr-FR"] {
assert_eq!(Locale::from_tag(tag), Locale::CommaDecimal, "{tag}");
}
diff --git a/crates/liteparse-ooxml/src/render/resolve/numbering.rs b/crates/liteparse-ooxml/src/render/resolve/numbering.rs
index 8adca9a..22a6dd2 100644
--- a/crates/liteparse-ooxml/src/render/resolve/numbering.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/numbering.rs
@@ -126,10 +126,9 @@ pub fn format_list_label(
/// §17.18.59 `ST_NumberFormat`: render one counter.
///
-/// Total over `NumberFormat` — the `_ =>` arm this replaced answered
-/// `n.to_string()` for every format it did not implement, which is right for
-/// none of them: it printed a digit where `none` asks for nothing, and it hid
-/// `cardinalText` and `ordinalText` behind an answer that looked deliberate.
+/// Matched exhaustively rather than with a catch-all, so each format renders
+/// what the spec asks for — a digit where a digit is meant, nothing where
+/// `none` is meant — instead of a blanket `n.to_string()`.
///
/// `locale` decides only the three language-dependent formats; the rest are
/// the same in every language, which is why they take it without using it.
@@ -164,8 +163,7 @@ fn format_number(n: u32, fmt: NumberFormat, locale: Locale) -> String {
///
/// US English convention, which is what Word writes: tens and units joined by a
/// hyphen, scale groups by a space, and **no** "and" before the final group.
-/// Each word capitalised. Unverified against a Word render; recorded here
-/// rather than guessed at each call site.
+/// Each word capitalised.
fn to_cardinal_text(n: u32) -> String {
const UNITS: [&str; 20] = [
"Zero",
@@ -719,8 +717,7 @@ mod tests {
}
}
- /// §17.18.59: neither `bullet` nor `none` renders the counter. The `_ =>`
- /// arm this replaced printed the digit for both.
+ /// §17.18.59: neither `bullet` nor `none` renders the counter.
#[test]
fn formats_that_render_no_counter_render_nothing() {
assert_eq!(format_number(7, NumberFormat::Bullet, Locale::English), "");
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/custom.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/custom.rs
index 8e500ec..16ec515 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/custom.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/custom.rs
@@ -55,10 +55,8 @@ pub fn build_custom(geom: &CustomGeometry, extent: PtSize) -> Option<ShapePath>
fn build_subpath(geom: &CustomGeometry, path: &PathDef, extent: PtSize) -> Option<SubPath> {
// §20.1.9.15 @w/@h: "If this attribute is omitted, then a value of 0 is
// implied" — which names the shape's own coordinate space, not an empty
- // path (see `path_space`). This is what makes the preset table work at
- // all: 270 of the spec's 320 preset paths omit both attributes, and none
- // of those 270 uses a literal coordinate, so every value in them is a
- // guide resolved against this context.
+ // path (see `path_space`). Most preset paths omit both attributes and use
+ // only guides, so they resolve against this context.
let path_w = path_space(path.w.raw() as f64, extent.width.raw() as f64);
let path_h = path_space(path.h.raw() as f64, extent.height.raw() as f64);
let ctx = GuideContext::new(path_w, path_h);
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs
index 3c8022f..4a83d7b 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/mod.rs
@@ -6,14 +6,9 @@
//! for all 187 of them and [`build_preset`] runs it through the
//! `<a:custGeom>` evaluator.
//!
-//! Four shapes (`rect`, `line`/`straightConnector1`, `roundRect`, `ellipse`)
-//! did have hand-written generators, from before the table existed. A
-//! differential against the table retired them: `rect`, `line` and `ellipse`
-//! produced the identical path, and `roundRect` produced the identical path
-//! with a *wrong* text rect — the hand version inset it by the full corner
-//! radius where §20.1.9.22 insets it by 29.289% of that (`il = x1 * 29289 /
-//! 100000`, the sagitta of a 45° arc). One source of truth is worth the
-//! ~0.5µs per shape the table path costs over a bespoke one.
+//! Note the §20.1.9.22 `roundRect` text rect is inset by 29.289% of the corner
+//! radius (`il = x1 * 29289 / 100000`, the sagitta of a 45° arc), not by the
+//! full radius — the table gets this right where a naive generator would not.
//!
//! A preset returns `None` only when §20.1.9.18 does not define the name at
//! all, i.e. `PresetShapeType::Other`. Callers log once and skip the shape;
@@ -71,8 +66,7 @@ mod tests {
#[test]
fn table_preset_dispatches() {
- // Star12 has no generator of its own and never will: it comes from the
- // vendored spec table like every other shape outside the four above.
+ // Star12 comes from the vendored spec table like every other shape.
let p = build_preset(
&def(PresetShapeType::Star12),
PtSize::new(Pt::new(10.0), Pt::new(20.0)),
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/table.rs b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/table.rs
index f76aee2..4b18880 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/table.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_geometry/presets/table.rs
@@ -102,8 +102,8 @@ fn table() -> &'static HashMap<PresetShapeType, CustomGeometry> {
/// absent from the table (`PresetShapeType::Other` for a name the spec has no
/// definition for).
/// Borrowed whenever the shape declares no `<a:avLst>` of its own, which is
-/// the common case — the whole definition is then shared, not copied per
-/// shape. This is the difference between ~50ns and ~600ns per shape built.
+/// the common case — the whole definition is then shared rather than cloned
+/// per shape.
pub fn resolve<'a>(
preset: &PresetShapeType,
adjust_values: &[GeomGuide],
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
index 375154f..702a614 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
@@ -57,8 +57,8 @@ pub struct ResolvedVisuals {
/// `None` for a shape at the top of a tree, and for every DOCX caller. It
/// arrives resolved rather than as a `DrawingFill` for two reasons: the
/// group's fill resolves in the group's own colour context, which is the one
-/// place it is correct to resolve it, and a group with 776 children resolves
-/// once instead of 776 times.
+/// place it is correct to resolve it, and a large group resolves its fill once
+/// instead of once per child.
pub fn resolve_shape_visuals(
props: Option<&ShapeProperties>,
style_line_ref: Option<&StyleMatrixRef>,
@@ -85,9 +85,8 @@ 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).
// A `grpFill` is a *declared* fill, so it wins over a `fillRef` even when
- // the group hands back nothing: 269 corpus shapes declare both, and
- // falling through to the theme on an unanswered group would paint them a
- // colour the file never asks for.
+ // the group hands back nothing: falling through to the theme on an
+ // unanswered group would paint a colour the file never asks for.
let fill = match props.fill.as_ref() {
Some(f) => resolve_fill(f, ctx, media, group_fill),
None => resolve_theme_fill(style_fill_ref, theme, ctx, media),
@@ -105,9 +104,8 @@ pub fn resolve_shape_visuals(
let stroke = match props.outline.as_ref() {
Some(o) => resolve_outline(o, theme_ln, ctx, &ln_ctx),
// No `<a:ln>` at all: the `lnRef` is the whole outline, not just its
- // defaults. 312 corpus shapes are in this case and PowerPoint strokes
- // every one of them, so declining here is a missing outline rather
- // than a conservative one.
+ // defaults. PowerPoint strokes these, so declining here would be a
+ // missing outline rather than a conservative one.
None => theme_ln.and_then(|t| resolve_outline(t, None, &ln_ctx, &ln_ctx)),
};
@@ -169,12 +167,10 @@ fn resolve_theme_fill(
/// **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.
+/// `bgFillStyleLst[idx - 1001]`**. Backgrounds routinely use `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.
///
/// Kept as a separate entry point rather than a branch inside
/// `resolve_theme_fill` so that a shape's `<a:fillRef>` — which has no
@@ -318,9 +314,8 @@ pub fn resolve_fill(
/// caller can act on:
///
/// * **no `a:blip` child** — an empty picture placeholder ("click to add
-/// picture"). 157 on the PPTX corpus, every one of them in a layout or
-/// master, and painting anything for them would stamp a phantom frame on
-/// every slide under that rung.
+/// picture"), typically in a layout or master; painting anything would stamp
+/// a phantom frame on every slide that inherits it.
/// * **`r:link`** — the image lives outside the package; there are no bytes to
/// draw and never will be from this file alone.
/// * **an `r:embed` the part does not declare**, or one whose target is
@@ -328,8 +323,7 @@ pub fn resolve_fill(
/// * **`a:tile`** — the image repeats rather than stretching. Returned as
/// `None` on purpose: painting a tile stretched is a *wrong* slide in
/// exactly the way an unbuildable preset drawn as its bounding box would be,
-/// and the corpus has **zero** of them, so strictness here costs nothing and
-/// keeps the first real one from rendering silently wrong.
+/// so strictness here keeps the first real one from rendering silently wrong.
///
/// The crop goes through [`relative_rect_to_fraction`], shared with the
/// picture path, so a cropped fill and a cropped picture cannot diverge.
@@ -804,7 +798,7 @@ mod tests {
}
/// A theme line style whose colour is the `phClr` placeholder, which is how
- /// every one of the corpus's `lnStyleLst` entries is written.
+ /// `lnStyleLst` entries are normally written.
fn theme_with_phclr_line(width_emu: i64) -> Theme {
use crate::model::DrawingColor;
Theme {
@@ -821,8 +815,8 @@ mod tests {
}
/// §20.1.4.1.22: an `<a:ln>` that names no colour takes the theme line
- /// style's, recoloured by the `lnRef`'s own `phClr` substitute — 179 corpus
- /// shapes, every one of which used to be painted black.
+ /// style's, recoloured by the `lnRef`'s own `phClr` substitute — otherwise
+ /// it would be painted black.
#[test]
fn colourless_outline_takes_its_colour_from_the_line_ref() {
use crate::model::DrawingColor;
@@ -858,8 +852,8 @@ mod tests {
assert!(!v.stroke_color_defaulted);
}
- /// No `<a:ln>` at all: the `lnRef` is the whole outline. 312 corpus shapes,
- /// which PowerPoint strokes and this resolver used to leave bare.
+ /// No `<a:ln>` at all: the `lnRef` is the whole outline, which PowerPoint
+ /// strokes.
#[test]
fn line_ref_supplies_the_whole_outline_when_there_is_no_ln() {
use crate::model::DrawingColor;
@@ -1143,9 +1137,8 @@ mod tests {
}
/// With no group to inherit from, a `grpFill` is still a *declared* fill:
- /// it resolves to nothing rather than falling through to the `fillRef`.
- /// 269 corpus shapes declare both, and the fall-through would paint every
- /// one of them a colour the file never asks for.
+ /// it resolves to nothing rather than falling through to the `fillRef`,
+ /// which would paint a colour the file never asks for.
#[test]
fn unanswered_grp_fill_does_not_fall_through_to_fill_ref() {
let theme = ph_theme();
@@ -1267,9 +1260,9 @@ mod tests {
#[test]
fn blip_embed_absent_from_this_parts_table_is_not_painted() {
- // The inherited-`rId1` trap, as a unit test: a layout picture's id
- // looked up in the *slide's* table must resolve to nothing rather than
- // to whatever that table happens to hold under the same id.
+ // A layout picture's rId looked up in the *slide's* media table must
+ // resolve to nothing rather than to whatever that table happens to
+ // hold under the same id.
let media = media_with("rId1");
let fill = blip_fill(Some("rId9"), BlipFillKind::Unspecified);
assert!(matches!(
@@ -1280,8 +1273,8 @@ mod tests {
#[test]
fn blip_fill_with_no_blip_child_is_an_empty_placeholder() {
- // 157 on the PPTX corpus, all in layouts and masters: "click to add
- // picture". Correctly paints nothing.
+ // "Click to add picture" placeholder (layouts and masters): correctly
+ // paints nothing.
let fill = blip_fill(None, BlipFillKind::Unspecified);
assert!(matches!(
resolve_blip_fill(&fill, Some(&media_with("rId1"))),
diff --git a/crates/liteparse-ooxml/src/render/resolve/styles.rs b/crates/liteparse-ooxml/src/render/resolve/styles.rs
index 756c99e..10e1cec 100644
--- a/crates/liteparse-ooxml/src/render/resolve/styles.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/styles.rs
@@ -38,11 +38,11 @@ pub struct ResolvedStyle {
/// Deliberately excludes `TOC Heading` (the heading *above* a ToC, not an
/// entry) and `toc` with no level, neither of which is an entry style.
fn is_toc_entry_name(name: &str) -> bool {
- // OOXML style names compare case-insensitively.
- let rest = if name.len() >= 4 && name[..4].eq_ignore_ascii_case("toc ") {
- &name[4..]
- } else {
- return false;
+ // OOXML style names compare case-insensitively. `get` rather than a
+ // direct slice: byte 4 may not be a char boundary in a malformed name.
+ let rest = match name.get(..4) {
+ Some(prefix) if prefix.eq_ignore_ascii_case("toc ") => &name[4..],
+ _ => return false,
};
matches!(rest.parse::<u8>(), Ok(1..=9))
}
@@ -504,8 +504,9 @@ mod tests {
"toc 10",
"toc 1x",
"table of contents",
- "TOCustom", // the false positive the old styleId prefix test hit
+ "TOCustom", // a styleId-prefix match would false-positive here
"",
+ "tocç 1", // byte 4 lands inside `ç`: must miss, not panic
] {
assert!(
!is_toc_entry_name(name),
diff --git a/crates/liteparse-ooxml/src/xlsx/drawings.rs b/crates/liteparse-ooxml/src/xlsx/drawings.rs
index 7177f06..9a8c3d1 100644
--- a/crates/liteparse-ooxml/src/xlsx/drawings.rs
+++ b/crates/liteparse-ooxml/src/xlsx/drawings.rs
@@ -4,43 +4,36 @@
//! A worksheet references at most one drawing part (`<drawing r:id>`); the
//! part holds a list of *anchors* (ECMA-376 §20.5), each placing one object —
//! a picture, a shape, a chart frame, or a group — against the grid. This
-//! module reads **pictures** and **text-bearing shapes**: the corpus census
-//! (1,248 workbooks) found 2,276 `xdr:pic`, 386 chart frames, and — among
-//! ~29k `xdr:sp` — 1,637 visible shapes carrying real text (137k chars of
-//! titles, form labels, and instructions invisible to the grid). Charts have
-//! no image bytes to extract and stay out of scope.
+//! module reads **pictures** and **text-bearing shapes**. Charts have no
+//! image bytes to extract and stay out of scope.
//!
-//! Census-driven decisions (`xlsx_shapetext_census`, see plan doc):
+//! Decisions for shapes:
//!
-//! * **`hidden="1"` shapes are skipped.** 1,004 of the corpus's 2,641
-//! text-bearing shapes are legacy form controls (`name="Check Box N"`,
-//! zero-extent, stacked option labels like `YES`/`NO`/`UNKNOWN`) that
-//! Excel itself never renders.
-//! * **`mc:Fallback` subtrees are skipped** — the PPTX shape walk's
-//! prefer-Choice rule, third format it applies to. Neither branch is a
-//! superset (Choice-only reads +119 shapes, −0.8% chars vs Fallback-only),
-//! and reading *both* — what this parser did before it knew about MCE —
-//! double-places every picture that appears in each branch.
-//! * **`cxnSp` text is not read**: zero corpus occurrences. Likewise
-//! `a:hlinkClick`/`a:fld` resolution (7 and 4 shapes corpus-wide).
+//! * **`hidden="1"` shapes are skipped.** These are almost always legacy
+//! form controls (`name="Check Box N"`, zero-extent, stacked option labels
+//! like `YES`/`NO`/`UNKNOWN`) that Excel itself never renders.
+//! * **`mc:Fallback` subtrees are skipped** — the same prefer-Choice rule
+//! used by the PPTX shape walk. Reading both branches double-places any
+//! object that appears in each.
+//! * **`cxnSp` text and `a:hlinkClick`/`a:fld` resolution are not read** —
+//! both are schema-legal but effectively unused in practice.
//!
-//! Census-driven decisions for pictures:
+//! Decisions for pictures:
//!
//! * **All three anchor kinds are read.** `oneCellAnchor` is the majority
-//! (19,228 against 9,157 `twoCellAnchor`), so treating the two-cell form as
-//! canonical would misplace most of the population. `absoluteAnchor` holds
-//! exactly 1 corpus picture but costs ~10 lines.
-//! * **A grouped picture inherits its group's anchor.** 161 of 2,276 pictures
-//! sit inside `xdr:grpSp`, whose children carry their own EMU offsets
-//! relative to a child coordinate space. Composing those matrices is the
-//! PPTX group-geometry problem again; here every picture found anywhere in
-//! an anchor's subtree is placed at the anchor's box. The bytes are exact,
-//! the box is the group's — an approximation the geometry pass records.
-//! * **`r:embed` resolves against the drawing part's own rels** — the same
-//! per-part scoping rule every other OOXML reader in this crate has had to
-//! learn. When a `blip` also carries an SVG extension, `r:embed` is the
-//! raster fallback and is what we take; an SVG-only blip has no `r:embed`
-//! and yields nothing, matching the PPTX figure policy.
+//! form in practice, so treating the two-cell form as canonical would
+//! misplace most pictures. `absoluteAnchor` is rare but cheap to support.
+//! * **A grouped picture inherits its group's anchor.** A picture inside
+//! `xdr:grpSp` carries its own EMU offset relative to a child coordinate
+//! space. Composing those matrices is the same problem as PPTX group
+//! geometry; every picture found anywhere in an anchor's subtree is placed
+//! at the anchor's box by default, refined to a fraction of that box when
+//! [`compose_grouped_pics`] can resolve the group's transform.
+//! * **`r:embed` resolves against the drawing part's own rels** — the
+//! per-part scoping rule every OOXML reader in this crate follows. When a
+//! `blip` also carries an SVG extension, `r:embed` is the raster fallback
+//! and is what we take; an SVG-only blip has no `r:embed` and yields
+//! nothing, matching the PPTX figure policy.
use std::sync::Arc;
@@ -195,14 +188,13 @@ struct OpenShape {
/// Flat text rescue for OMML equation bodies.
///
-/// 56 corpus shapes (6 workbooks, engineering calculators) hold their text
-/// in `a14:m` math — `m:oMath` trees whose glyphs sit in `m:t` runs the
-/// structured text model does not know, so the body lowers to empty. This
-/// collects every `t`-element's text in document order into one run per
-/// `a:p` (`m:t` and `a:t` both strip to `t` under `local_name`, which is
-/// exactly the reading the shape-text census counted). Math *structure* —
-/// fractions, sub/superscripts — flattens to its glyph sequence; recorded,
-/// not hidden. Returns `None` when no text is found at all.
+/// A shape may hold its text in `a14:m` math — `m:oMath` trees whose glyphs
+/// sit in `m:t` runs the structured text model does not know, so the body
+/// lowers to empty. This collects every `t`-element's text in document order
+/// into one run per `a:p` (`m:t` and `a:t` both strip to `t` under
+/// `local_name`). Math *structure* — fractions, sub/superscripts — flattens
+/// to its glyph sequence; recorded, not hidden. Returns `None` when no text
+/// is found at all.
fn flat_math_body(txbody: &[u8]) -> Option<crate::pptx::text::TextBody> {
use crate::model::{Inline, RunElement, TextRun};
use crate::pptx::text::{TextBody, TextParagraph};
@@ -316,10 +308,9 @@ pub(crate) fn parse_drawing(data: &[u8]) -> Result<DrawingContent> {
let name = local_name(qname.as_ref());
let empty = matches!(event, Event::Empty(_));
match name {
- // MCE: keep the Choice branch, skip the Fallback — the
- // PPTX shape walk's rule. Reading both (what this parser
- // did before it knew about MCE) double-places any object
- // that appears in each branch.
+ // MCE: keep the Choice branch, skip the Fallback.
+ // Reading both double-places any object that appears in
+ // each branch.
b"Fallback" if !empty => {
let end = e.to_end().into_owned();
reader
@@ -479,7 +470,7 @@ pub(crate) fn parse_drawing(data: &[u8]) -> Result<DrawingContent> {
if let Some(rel_id) = rel_id {
out.pics.push(RawPic {
anchor,
- name: name.clone(),
+ name,
rel_id,
frac: None,
anchor_idx: anchors.len(),
@@ -549,13 +540,12 @@ pub(crate) fn parse_drawing(data: &[u8]) -> Result<DrawingContent> {
/// is exactly the anchor's ink slice. Parsing that one slice through the
/// shared shape tree and running [`crate::pptx::apply_slide_geometry`] yields
/// each descendant pic's box in the drawing's EMU space — the same
-/// composition, over the same root bounding box, that `AnchorMap` places the
-/// group's ink with, so pictures and their group's fills land in one frame by
-/// construction. The corpus says the chain is complete (every group declares
-/// `chOff`/`chExt`, every grouped pic an `off`/`ext`, zero rotations); the
-/// fail-open path — parse failure, count or `r:embed` sequence disagreement
-/// between this tree and the streaming walk, a degenerate root box — keeps
-/// the group-box approximation that was previously the rule.
+/// composition, over the same root bounding box, that places the group's ink,
+/// so pictures and their group's fills land in one frame by construction.
+/// The fail-open path — parse failure, a count or `r:embed` sequence
+/// disagreement between this tree and the streaming walk, a degenerate root
+/// box — falls back to the group-box approximation (the anchor's box, not a
+/// fraction of it).
fn compose_grouped_pics(out: &mut DrawingContent) {
let mut composed: Vec<(usize, [f64; 4])> = Vec::new();
for ink in &out.ink {
@@ -848,7 +838,7 @@ mod tests {
assert!((fh - 0.5).abs() < 1e-9, "fh {fh}");
}
- /// Depth 2 is the corpus majority (111 of 212): both child spaces fold.
+ /// Nested groups: both child spaces fold.
#[test]
fn nested_groups_compose_through_both_child_spaces() {
let xml = format!(
@@ -938,8 +928,7 @@ mod tests {
);
}
- /// A chart frame is not a picture and yields nothing — the census's 386
- /// `graphicFrame`s are recorded as out of scope, not silently absorbed.
+ /// A chart frame is not a picture and yields nothing.
#[test]
fn a_chart_frame_yields_no_picture() {
let xml = format!(
@@ -997,7 +986,7 @@ second line"
}
/// `hidden="1"` marks a legacy form control (checkbox option labels and
- /// friends) that Excel never renders — 1,004 of them in the corpus.
+ /// friends) that Excel never renders.
#[test]
fn a_hidden_shape_is_a_form_control_and_is_skipped() {
let xml = format!(
@@ -1011,7 +1000,7 @@ second line"
assert!(parse_drawing(xml.as_bytes()).unwrap().shapes.is_empty());
}
- /// A whitespace-only body carries no content; the census counted 4,454.
+ /// A whitespace-only body carries no content.
#[test]
fn a_whitespace_only_body_is_skipped() {
let xml = format!(
@@ -1053,8 +1042,7 @@ second line"
}
/// MCE: the Choice branch wins, the Fallback is skipped — an object in
- /// both branches yields ONE placement, not two. This was a live bug for
- /// pictures (~12 phantom placements corpus-wide) before shapes arrived.
+ /// both branches yields ONE placement, not two.
#[test]
fn mce_prefers_choice_and_never_reads_both_branches() {
let xml = format!(
@@ -1094,8 +1082,8 @@ second line"
assert_eq!(content.shapes[0].body.plain_text(), "𝑛=𝑑1/6");
}
- /// The census's zero: a connector's text (schema-legal, corpus-absent)
- /// is not read, and its presence does not disturb a sibling text shape.
+ /// A connector's text is schema-legal but not read here, and its
+ /// presence does not disturb a sibling text shape.
#[test]
fn a_connector_yields_no_text_shape() {
let xml = format!(
@@ -1112,9 +1100,9 @@ second line"
use crate::pptx::shapes::ShapeKind;
- /// A textless filled rectangle — the population the text channel
- /// rightly drops (6,359 on the corpus) — survives on the ink channel,
- /// fill and geometry intact, under the anchor it was placed by.
+ /// A textless filled rectangle — dropped by the text channel — survives
+ /// on the ink channel, fill and geometry intact, under the anchor it was
+ /// placed by.
#[test]
fn a_textless_filled_shape_reaches_ink_but_not_shapes() {
let xml = format!(
diff --git a/crates/liteparse-ooxml/src/xlsx/mod.rs b/crates/liteparse-ooxml/src/xlsx/mod.rs
index bb81c54..37f9edc 100644
--- a/crates/liteparse-ooxml/src/xlsx/mod.rs
+++ b/crates/liteparse-ooxml/src/xlsx/mod.rs
@@ -5,16 +5,8 @@
//! Unlike those two, nothing here is vendored: SpreadsheetML has no DOCX
//! counterpart in dxpdf, so the whole reader is new code against ECMA-376 §18.
//!
-//! # What this replaces
-//!
-//! Today an `.xlsx` goes through LibreOffice → PDF → grid projection, and the
-//! measured cost of that is not subtle. Across 218 real workbooks (63 research
-//! + 150 finance), that path emits **zero markdown table rows** and clips every
-//! cell at its rendered column width — `"Mosaic tree and shrub (>50%) …"`
-//! becomes `"Mosaic tr"`, destroyed before projection ever sees it, with a
-//! cell-text recall of 0.77 macro / 0.66–0.73 micro as the ceiling.
-//!
-//! A workbook states its grid explicitly. There is nothing to reverse-engineer.
+//! A workbook states its grid explicitly, so this reader parses cells and
+//! styles directly rather than going through a rendered layout.
//!
//! # Shape
//!
@@ -66,6 +58,16 @@ use crate::docx::error::Result;
use crate::docx::relationships::TargetMode;
use crate::docx::zip::{part_directory, resolve_target};
+/// A picture anchored to a sheet, still pending resolution of its media part.
+/// `(sheet index, anchor, crop fraction, name, media part path)`.
+type PendingPic = (
+ usize,
+ drawings::PicAnchor,
+ Option<[f64; 4]>,
+ Option<String>,
+ String,
+);
+
/// A workbook read end to end.
pub struct Workbook {
/// Sheets in tab order, including hidden ones (see [`Sheet::visible`]) and
@@ -83,9 +85,8 @@ pub struct Workbook {
/// layer also needs `fill_styles`/`line_styles` (for `a:fillRef`/
/// `a:lnRef` on floating shapes) and the font scheme, which is why the
/// full part is kept rather than the scheme alone. `None` when the
- /// workbook ships no theme part (0.6% of the corpus), which makes every
- /// `theme=` reference resolve to the consumer's default rather than to
- /// black.
+ /// workbook ships no theme part, which makes every `theme=` reference
+ /// resolve to the consumer's default rather than to black.
pub theme: Option<crate::model::Theme>,
/// Serial dates count from 1904-01-01 rather than 1899-12-30.
pub date1904: bool,
@@ -101,9 +102,8 @@ pub struct Workbook {
/// Everything below that degrades: an unparseable sheet is skipped with a
/// warning, a missing styles part means every cell is `General`, and a missing
/// shared-string table means string cells resolve to nothing. A workbook is
-/// almost never wholly broken, and refusing the whole file because one sheet is
-/// malformed is the fail-closed behaviour this vendor has already had to
-/// retire repeatedly.
+/// almost never wholly broken, so one malformed sheet should not fail the
+/// whole file.
pub fn read(data: &[u8]) -> Result<Workbook> {
let mut pkg = walk(data)?;
@@ -130,13 +130,7 @@ pub fn read(data: &[u8]) -> Result<Workbook> {
// Pictures found while walking the sheets, resolved down to a media part
// path. The bytes move out of the package afterwards, when the immutable
// borrows this loop holds are gone.
- let mut pending_pics: Vec<(
- usize,
- drawings::PicAnchor,
- Option<[f64; 4]>,
- Option<String>,
- String,
- )> = Vec::new();
+ let mut pending_pics: Vec<PendingPic> = Vec::new();
for entry in &pkg.sheets {
if !entry.is_worksheet {
non_worksheet_sheets.push(entry.name.clone());
@@ -148,8 +142,7 @@ pub fn read(data: &[u8]) -> Result<Workbook> {
match sheet::parse(&entry.name, entry.visible, xml) {
Ok(mut s) => {
// A hyperlink's `r:id` is scoped to the sheet part that wrote
- // it — the same per-part rule the PPTX blip work established —
- // so resolution has to happen here, where the entry's own
+ // it, so resolution has to happen here, where the entry's own
// relationships are still in hand.
for h in &mut s.hyperlinks {
h.url = h
diff --git a/crates/liteparse-ooxml/src/xlsx/numfmt.rs b/crates/liteparse-ooxml/src/xlsx/numfmt.rs
index d3a308b..1a921c9 100644
--- a/crates/liteparse-ooxml/src/xlsx/numfmt.rs
+++ b/crates/liteparse-ooxml/src/xlsx/numfmt.rs
@@ -1,12 +1,10 @@
//! Number formatting — the seam [`Workbook::format_code`] left open.
//!
//! A cell stores `0.155`; the sheet shows `15.5%`. The gap between the two is
-//! ECMA-376 §18.8.31's format grammar, and the finance-slice census said it is
-//! not a small one: **50.0% of documents need multi-section `pos;neg;zero;text`
-//! dispatch**, 36.0% need quoted literals, 34.9% need `_` skip-width padding,
-//! 23.2% `?` placeholders, 23.0% `*` fill, 14.4% `[Red]`. Excel's Accounting
-//! code — `_("$"* #,##0.00_);…` in 99 documents — exercises five of those at
-//! once.
+//! ECMA-376 §18.8.31's format grammar: multi-section `pos;neg;zero;text`
+//! dispatch, quoted literals, `_` skip-width padding, `?` placeholders, `*`
+//! fill, and `[Red]` condition brackets are all in common use. Excel's
+//! Accounting code — `_("$"* #,##0.00_);…` — exercises five of those at once.
//!
//! So the interpreter is [`ssf_rs`], a port of SheetJS's `ssf`, and this module
//! is only the adapter: which of [`CellValue`]'s six shapes gets fed to it,
@@ -80,12 +78,10 @@ pub fn render(code: &str, value: &CellValue, date1904: bool) -> Result<String, S
/// The detection is on the **output**, not the input, and the difference is
/// load-bearing: `1.23e-7` under `0.00` is `"0.00"` in both implementations,
/// because the rounding discards the mantissa before the splice can go wrong.
-/// Rejecting every out-of-range magnitude would have broken those, which the
-/// oracle diff duly reported.
+/// Rejecting every out-of-range magnitude would break those cases too.
///
-/// The corpus reaches an out-of-range magnitude in **1,436 cells across 9 of
-/// 1,178 workbooks**, so the guard is not hypothetical and is also not the
-/// common path.
+/// Out-of-range magnitudes are rare but real, so the guard is not
+/// hypothetical, and it is also not the common path.
fn is_spliced_exponent(n: f64, code: &str, out: &str) -> bool {
let mag = n.abs();
if n == 0.0 || !n.is_finite() || (1e-6..1e21).contains(&mag) {
@@ -190,11 +186,11 @@ fn bool_text(b: bool) -> &'static str {
///
/// A code with no sections and no `@` — `0.00`, `#,##0` — leaves a string
/// alone, which is both Excel's behaviour and the reason a shared string used
-/// 40,000 times is not run through the interpreter 40,000 times. Anything with
+/// many times is not run through the interpreter for each use. Anything with
/// a `;` in it goes to the interpreter, because the *fourth* section is the
/// text section and an **empty** one blanks the cell: `#,##0.00;;;` displays
-/// nothing at all, and a `@`-check alone would have rendered the string. The
-/// oracle diff caught exactly that, on three corpus codes.
+/// nothing at all, and a `@`-check alone would have rendered the string
+/// instead.
fn render_text(code: &str, text: &str) -> String {
if code == GENERAL || (!code.contains('@') && !code.contains(';')) {
return text.to_string();
@@ -202,15 +198,14 @@ fn render_text(code: &str, text: &str) -> String {
let out = ssf_rs::format(code, &Value::Text(text.to_string()), false)
.unwrap_or_else(|_| text.to_string());
let out = strip_nan(code, out, Some(text));
- // `ssf-rs` 0.1 truncates the text at the fill character when `*`'s fill
- // char also occurs in the text: `@*.` renders `"1. kvartal:"` as `"1."`.
- // (`@* ` is unaffected — the defect is per fill char, and `.` is the one
- // the corpus hits.) A section with `@` places the text verbatim, so an
- // output that lost it is a wrong answer, not a presentation choice; fall
- // back to the raw text — keep the data, lose the fill. Detect on the
- // output, not the input: same rule as the `NaN` guard above, and for the
- // same reason (the first version of that guard rejected inputs and
- // regressed 1,100 correct renders).
+ // `ssf-rs` truncates the text at the fill character when `*`'s fill char
+ // also occurs in the text: `@*.` renders `"1. kvartal:"` as `"1."`. A
+ // section with `@` places the text verbatim, so an output that lost it
+ // is a wrong answer, not a presentation choice; fall back to the raw
+ // text — keep the data, lose the fill. Detect on the output, not the
+ // input, for the same reason as the `NaN` guard below: rejecting on the
+ // input would also reject correct renders that merely contain the fill
+ // character.
if code.contains('*') && code.contains('@') && !out.contains(text) {
return text.to_string();
}
@@ -227,17 +222,16 @@ fn render_text(code: &str, text: &str) -> String {
///
/// Gated on the `*` that leaks it, and on the code not writing `NaN` as a
/// literal — and then applied **only outside the value's own text**, because a
-/// blind `replace` is a data-loss bug waiting for the right cell. The Zenodo
-/// corpus supplied that cell: a conference named `NaNA`, in a paper title, and
-/// an ungated strip shortens it to `A`. Skipping the repair whenever the source
-/// contains `NaN` would be the opposite error — it leaves the leak in the one
-/// title that has both.
+/// blind `replace` is a data-loss bug waiting for the right cell: a source
+/// string containing the literal substring `NaN` (e.g. a title with
+/// "NaNA" in it) must keep it, while the interpreter's own leaked `NaN`
+/// around it must go.
///
/// `protect` is the source text a text cell renders from; a number has none,
/// and only renders `NaN` when the value itself is one.
///
-/// **4 cells in 24M** hit the real leak; the guard is here because a cell
-/// reading `NaN` is not a presentation defect, it is a wrong answer.
+/// This is rare but real; the guard is here because a cell reading `NaN` is
+/// not a presentation defect, it is a wrong answer.
fn strip_nan(code: &str, out: String, protect: Option<&str>) -> String {
if !out.contains("NaN") || code.contains("NaN") || !code.contains('*') {
return out;
@@ -308,11 +302,7 @@ impl Workbook {
/// byte for byte**. Verifying on the output is what makes the substitution
/// safe to do at all — [`render`]'s two repairs are both gated on the `*`
/// the substitution removes, so a sentinel render can legitimately differ,
- /// and when it does the answer is `None` rather than a guess. Over the
- /// 1,248-workbook corpus: 193,244 cells carry a `*` code, 181,117 (93.7%)
- /// recover an offset, 12,123 declare the fill in a section this value does
- /// not use, and **4 diverge** — the same four `@*.` cells
- /// [`strip_nan`] documents.
+ /// and when it does the answer is `None` rather than a guess.
///
/// `None` also for the overwhelming majority of cells, whose code has no
/// `*` at all; that case costs one `contains` and no render.
@@ -332,11 +322,11 @@ impl Workbook {
let mut marks = rendered.match_indices(FILL_SENTINEL);
let (at, _) = marks.next()?;
// More than one active fill would need more than one split point, and
- // the painter has one gap to give. The corpus holds none.
+ // the caller has one gap to give.
if marks.next().is_some() {
return None;
}
- let mut stripped = rendered.clone();
+ let mut stripped = rendered;
stripped.remove(at);
(stripped == plain).then_some(at)
}
@@ -388,24 +378,24 @@ mod tests {
render(code, &CellValue::Number(n), false).unwrap()
}
- /// The six mechanisms the finance-slice census named, each at the value
- /// that exercises it. Failing any one of these is a whole class of the
- /// corpus rendering wrong, not a rounding difference.
+ /// The core mechanisms of the format grammar, each at the value that
+ /// exercises it. Failing any one of these is a whole class of documents
+ /// rendering wrong, not a rounding difference.
#[test]
fn the_censused_mechanisms_render() {
- // multi-section dispatch: 50.0% of documents
+ // multi-section dispatch
let acct = r#"_("$"* #,##0.00_);_("$"* \("$"* #,##0.00\);_("$"* "-"??_);_(@_)"#;
assert_eq!(num(acct, 1234.5678), " $1,234.57 ");
assert_eq!(num(acct, -1234.5678), " $($1,234.57)");
// zero section: `"-"??` is the accounting dash, padded to two digits
assert_eq!(num(acct, 0.0), " $- ");
- // quoted literal: 36.0%
+ // quoted literal
assert_eq!(num(r#"0.00"kg""#, 1234.5678), "1234.57kg");
- // skip-width `_)`: 34.9% — one space, not a dropped character
+ // skip-width `_)` — one space, not a dropped character
assert_eq!(num("0.00_);(0.00)", 1234.5678), "1234.57 ");
- // `[Red]` is consumed, never emitted: 14.4%
+ // `[Red]` is consumed, never emitted
assert_eq!(num(r"#,##0.0;[Red]\-#,##0.0;0", -1234.5678), "-1,234.6");
- // comma scaling: 0.2% of docs, but silently 1000x wrong if unhandled
+ // comma scaling — silently 1000x wrong if unhandled
assert_eq!(num("#,##0.00,,", 45000.25), "0.05");
// suppressed sections render empty rather than falling back
assert_eq!(num("0;;", -1234.5678), "");
@@ -471,8 +461,7 @@ mod tests {
/// The fourth section governs text even when it is empty, and empty means
/// the cell displays nothing. Skipping the interpreter for codes without
- /// `@` renders the string instead — three corpus codes, found by the
- /// SheetJS diff rather than by reading the spec.
+ /// `@` renders the string instead, which is wrong for this case.
#[test]
fn an_empty_fourth_section_blanks_text() {
assert_eq!(render_text(";;;", "NO"), "");
@@ -484,25 +473,25 @@ mod tests {
}
/// The port leaks its `*`-repeat count into the string when there is no
- /// column width to fill. Four corpus cells, found by the oracle diff.
+ /// column width to fill.
#[test]
fn a_leaked_nan_is_removed_but_a_literal_one_is_kept() {
assert_eq!(render_text("@*.", "Vareforbrug"), "Vareforbrug.");
assert_eq!(render_text(r#"@" NaN""#, "x"), "x NaN");
- // The Zenodo counterexample: a conference called NaNA, under a fill
- // code. An ungated strip shortens the title.
+ // A title that legitimately contains "NaN" as a substring, under a
+ // fill code. An ungated strip would shorten the title.
assert_eq!(
render_text("@*.", "Networking and Network Applications (NaNA)"),
"Networking and Network Applications (NaNA)."
);
}
- /// The upstream defect the emitter's recall gate caught: `ssf-rs` 0.1
- /// truncates the text at the fill character when it also occurs in the
- /// text — `@*.` on `"1. kvartal:"` came back `"1."`. The guard keeps the
- /// data and drops the fill, and must not disturb the two behaviours next
- /// to it: an intact render keeps its fill, and the empty fourth section
- /// still blanks (no `@` in that code, so the guard stays out of its way).
+ /// An upstream `ssf-rs` defect: it truncates the text at the fill
+ /// character when the character also occurs in the text — `@*.` on
+ /// `"1. kvartal:"` came back `"1."`. The guard keeps the data and drops
+ /// the fill, and must not disturb the two behaviours next to it: an
+ /// intact render keeps its fill, and the empty fourth section still
+ /// blanks (no `@` in that code, so the guard stays out of its way).
#[test]
fn a_fill_char_inside_the_text_does_not_truncate_it() {
assert_eq!(render_text("@*.", "1. kvartal:"), "1. kvartal:");
diff --git a/crates/liteparse-ooxml/src/xlsx/package.rs b/crates/liteparse-ooxml/src/xlsx/package.rs
index 011ed3a..9a1fefb 100644
--- a/crates/liteparse-ooxml/src/xlsx/package.rs
+++ b/crates/liteparse-ooxml/src/xlsx/package.rs
@@ -43,14 +43,14 @@ pub struct WorkbookPackage {
pub sheets: Vec<SheetEntry>,
pub shared_strings_xml: Option<Vec<u8>>,
pub styles_xml: Option<Vec<u8>>,
- /// `xl/theme/theme1.xml`, present in 99.4% of corpus workbooks. Needed
- /// only for colour: 29.8% of the colours `styles.xml` defines are
- /// `theme=` references, which resolve to nothing without it.
+ /// `xl/theme/theme1.xml`. Needed only for colour: a meaningful share of
+ /// the colours `styles.xml` defines are `theme=` references, which
+ /// resolve to nothing without it.
pub theme_xml: Option<Vec<u8>>,
/// `<workbookPr date1904="1"/>`: the epoch serial dates count from. Excel
- /// for Mac wrote 1904-based workbooks for years and 123 of the corpus's
- /// 1,089 workbooks come from Mac Excel, so this is not a historical
- /// curiosity — reading it wrong shifts every date by 1,462 days.
+ /// for Mac wrote 1904-based workbooks for years, so this is not a
+ /// historical curiosity — reading it wrong shifts every date in the file
+ /// by 1,462 days.
pub date1904: bool,
/// The raw container, kept for drawings and media the emitter may reach.
pub package: PackageContents,
@@ -279,8 +279,8 @@ mod tests {
assert_eq!(parse_workbook(xml.as_bytes()).unwrap().sheets.len(), 1);
}
- /// 123 of the 1,089 corpus workbooks are Mac Excel; getting this wrong
- /// shifts every date in them by 1,462 days.
+ /// Mac Excel workbooks use the 1904 epoch; getting this wrong shifts
+ /// every date in them by 1,462 days.
#[test]
fn the_1904_epoch_flag_is_read() {
assert!(parse_workbook(WORKBOOK.as_bytes()).unwrap().date1904);
diff --git a/crates/liteparse-ooxml/src/xlsx/sheet.rs b/crates/liteparse-ooxml/src/xlsx/sheet.rs
index acac8d0..b3967a5 100644
--- a/crates/liteparse-ooxml/src/xlsx/sheet.rs
+++ b/crates/liteparse-ooxml/src/xlsx/sheet.rs
@@ -1,14 +1,14 @@
//! A worksheet part (`xl/worksheets/sheetN.xml`, §18.3): the cell grid, the
//! row/column metrics the grid is drawn on, and the merges that break it.
//!
-//! Streamed rather than deserialized. Sheets are the bulk of a workbook — 50.3M
-//! cells across the 1,089-workbook finance corpus, single sheets past 32 MB —
-//! and this is the one part where the reader's memory profile is decided.
+//! Streamed rather than deserialized. Sheets are the bulk of a workbook — a
+//! single sheet can hold tens of millions of cells and exceed 32 MB — and
+//! this is the one part where the reader's memory profile is decided.
//!
//! Two allocation decisions follow from that and are load-bearing:
//!
//! * **Shared strings are not resolved here.** A cell keeps its index into the
-//! shared-string table. The table exists precisely so a string used 40,000
+//! shared-string table. The table exists precisely so a string used many
//! times is stored once; resolving eagerly would undo that. See
//! [`crate::xlsx::Workbook::cell_text`].
//! * **Value-less cells are dropped from [`Row::cells`].** `<c r="A1" s="7"/>`
@@ -21,19 +21,17 @@
//!
//! # The paint side-channel
//!
-//! `xlsx_unvalued_paint_census` over the 1,248-workbook corpus: **57.6% of all
-//! declared paint reaches the file and not a reader built on valued cells
-//! alone**, in three carriers — value-less styled cells, `<row customFormat>`
-//! and `<col style>`. [`Row::styled_blanks`], [`Row::style`] and
-//! [`ColInfo::style`] are those three, and they exist for the raster; nothing
-//! that reads text sees them.
+//! A meaningful share of a workbook's declared paint never reaches a reader
+//! built on valued cells alone — it lives in three carriers: value-less
+//! styled cells, `<row customFormat>` and `<col style>`.
+//! [`Row::styled_blanks`], [`Row::style`] and [`ColInfo::style`] are those
+//! three, and they exist for the raster; nothing that reads text sees them.
//!
//! `styled_blanks` is pruned at `</row>`: a row with no valued cell is not a
//! row any consumer of this reader emits, so its blanks are unreachable ink
//! and are dropped rather than stored. That prune is also the memory bound —
-//! it is what keeps the pre-formatted-region sheets (thousands of blank rows
-//! past the data, class C of the census, 41.7% of all paint) from being held
-//! at all.
+//! it is what keeps a sheet with a large pre-formatted region (thousands of
+//! blank-but-styled rows past the data) from being held at all.
use quick_xml::Reader;
use quick_xml::events::Event;
@@ -75,8 +73,8 @@ pub struct Cell {
pub style: Option<u32>,
pub value: CellValue,
/// The cell holds an `<f>`. The formula text itself is not kept — the
- /// cached `<v>` is what renders, and 49.3% of corpus workbooks have
- /// formulas, so storing their source would be pure weight.
+ /// cached `<v>` is what renders, so storing the source would be pure
+ /// weight.
pub has_formula: bool,
}
@@ -101,8 +99,7 @@ pub struct Row {
/// `<row s=… customFormat="1">`: a format for every cell of the row that
/// states none of its own. Recorded **only** under `customFormat`, which
/// is the attribute that says the `s=` is meant rather than inherited
- /// (§18.3.1.73); 33,562 rows in the corpus declare one, carrying 482,334
- /// cells of paint.
+ /// (§18.3.1.73).
pub style: Option<u32>,
/// Cells in written order, which is ascending column order in every
/// producer seen. Sparse: absent columns are absent.
@@ -128,8 +125,7 @@ pub struct ColInfo {
pub custom_width: bool,
/// `<col style=…>`: a format for every cell of the span that states none
/// of its own, and none through its row. Paint only, like
- /// [`Row::styled_blanks`]: 8,372 corpus spans declare one, carrying
- /// 163,350 cells of ink.
+ /// [`Row::styled_blanks`].
pub style: Option<u32>,
}
@@ -180,8 +176,7 @@ pub struct Sheet {
pub default_row_height: Option<f64>,
pub cols: Vec<ColInfo>,
pub rows: Vec<Row>,
- /// Present in 80.7% of real workbooks, which is why they are read by the
- /// first version of this reader rather than deferred.
+ /// Merged cell ranges, common enough to read directly rather than defer.
pub merges: Vec<RangeRef>,
pub hyperlinks: Vec<Hyperlink>,
/// `<pane ySplit=… state="frozen">`: rows frozen at the top. A direct
@@ -194,16 +189,16 @@ pub struct Sheet {
/// `<sheetView showGridLines=…>`, from the first view only. `None` means
/// the file did not say, which is Excel's default of *visible* — read it
/// through [`Sheet::gridlines_visible`] rather than unwrapping to
- /// `false`. It matters to the raster and nothing else: 12.1% of corpus
- /// sheets declare neither a fill nor a border anywhere, so gridlines are
- /// the only ink holding their numbers in a grid.
+ /// `false`. It matters to the raster and nothing else: a sheet with no
+ /// fill or border anywhere relies on gridlines as the only ink holding
+ /// its numbers in a grid.
pub show_gridlines: Option<bool>,
/// `<drawing r:id>`: the sheet's DrawingML part, scoped to the sheet's
/// own relationships. At most one per §18.3.1.36.
pub drawing_rel_id: Option<String>,
/// Pictures placed over the grid, resolved by [`crate::xlsx::read`] from
- /// the drawing part — empty until then, and empty for the 69% of corpus
- /// workbooks whose sheets draw nothing.
+ /// the drawing part — empty until then, and empty for a sheet that draws
+ /// nothing.
pub pics: Vec<crate::xlsx::drawings::SheetPic>,
/// Visible text-bearing shapes floating over the grid, from the same
/// drawing part as `pics`. Titles, form labels, instructions — content
@@ -230,11 +225,6 @@ impl Sheet {
self.merges.iter().find(|m| m.start == at)
}
- /// The merge covering `at`, anchor or not.
- pub fn merge_covering(&self, at: CellRef) -> Option<&RangeRef> {
- self.merges.iter().find(|m| m.contains(at))
- }
-
/// Are the sheet's gridlines drawn? Undeclared means yes (§18.3.1.87).
pub fn gridlines_visible(&self) -> bool {
self.show_gridlines.unwrap_or(true)
@@ -499,10 +489,9 @@ fn finish_cell(pending: PendingCell, raw: &str, row: &mut Option<Row>, sheet: &m
let value = match pending.kind.as_str() {
"inlineStr" => pending.text.map(CellValue::Text),
// An empty body is a styled-but-blank cell that the producer happened
- // to write as `<c …></c>` rather than `<c …/>`. Not corruption, and
- // counting it as a dangling index would report 480 fake anomalies on
- // one corpus workbook — which is exactly what it did before this
- // distinction existed.
+ // to write as `<c …></c>` rather than `<c …/>`. Not corruption —
+ // counting it as a dangling index would report a false anomaly for
+ // every one of these.
"s" if raw.trim().is_empty() => None,
"s" => match raw.trim().parse::<u32>() {
Ok(i) => Some(CellValue::SharedString(i)),
@@ -675,9 +664,9 @@ mod tests {
assert_eq!(s.stats.empty_styled_cells, 1);
}
- /// The memory bound and the class-C rule in one: a row with no value is
- /// emitted by nobody, so its blanks are dropped rather than stored — for
- /// the row written `<c/>`-style and for the one written `<c></c>`.
+ /// A row with no value is emitted by nobody, so its blanks are dropped
+ /// rather than stored — for the row written `<c/>`-style and for the one
+ /// written `<c></c>`.
#[test]
fn a_valueless_row_keeps_its_metrics_and_drops_its_blanks() {
let xml = r#"<worksheet><sheetData>
@@ -787,7 +776,7 @@ mod tests {
/// `<c t="s"></c>` — a blank cell a producer wrote with an explicit close
/// tag instead of self-closing. It is styled-but-blank, not a broken
- /// index; one corpus workbook has 480 of them.
+ /// index.
#[test]
fn an_empty_shared_string_cell_is_blank_not_dangling() {
let xml = r#"<worksheet><sheetData><row r="1">
@@ -829,13 +818,12 @@ mod tests {
}
#[test]
- fn merge_lookup_distinguishes_the_anchor_from_the_covered_cells() {
+ fn merge_lookup_finds_only_the_anchor_cell() {
let s = sheet();
let a1 = parse_cell("A1").unwrap();
let b1 = parse_cell("B1").unwrap();
assert!(s.merge_anchored_at(a1).is_some());
assert!(s.merge_anchored_at(b1).is_none());
- assert!(s.merge_covering(b1).is_some());
}
#[test]
diff --git a/crates/liteparse-ooxml/src/xlsx/styles.rs b/crates/liteparse-ooxml/src/xlsx/styles.rs
index 7d5151a..0a2d8ab 100644
--- a/crates/liteparse-ooxml/src/xlsx/styles.rs
+++ b/crates/liteparse-ooxml/src/xlsx/styles.rs
@@ -19,16 +19,15 @@
//!
//! Fills, borders and font colours are read for the raster (a bbox consumer
//! never asks what colour a cell is). Every one of them names its colour
-//! through the same four-way `CT_Color` indirection, and the corpus shares
-//! them out unevenly enough that skipping any one of the four is visible —
-//! `xlsx_paint_census` over 1,248 workbooks: `indexed=` 49.5% of definitions,
-//! `theme=` 29.8%, `rgb=` 16.5%, `auto=` 4.2%.
+//! through the same four-way `CT_Color` indirection (`rgb=`, `theme=`,
+//! `indexed=`, `auto=`), and skipping any one of the four is visible in real
+//! workbooks.
//!
-//! Two things about that table are load-bearing:
+//! Two things about that indirection are load-bearing:
//!
-//! * **`indexed=` is mostly not the palette.** 93.2% of its uses are 64/65/8
-//! — "the default colour" — so [`INDEXED_PALETTE`] is a vendored constant
-//! for a 6.8% tail rather than a subsystem. It cannot be *skipped*: 4.6% of
+//! * **`indexed=` is mostly not the palette.** Most uses are 64/65/8 —
+//! "the default colour" — so [`INDEXED_PALETTE`] is a vendored constant
+//! for the rest rather than a subsystem. It cannot be *skipped*: some
//! workbooks override it with their own `<indexedColors>`.
//! * **`theme=` indices are not `clrScheme` order.** SpreadsheetML swaps
//! 0↔1 and 2↔3 (0 = lt1/background, 1 = dk1/text). Getting it backwards
@@ -47,10 +46,6 @@ use crate::xlsx::xml::{attr, attr_bool, attr_parse, local_name};
/// The format code applied when a cell names no style at all.
pub const GENERAL: &str = "General";
-/// Custom format ids start here (§18.8.30); anything below with no builtin
-/// entry is reserved and Excel does not write it.
-pub const FIRST_CUSTOM_FORMAT_ID: u32 = 164;
-
/// ECMA-376 §18.8.30 builtin number formats.
///
/// Ids 23–36 and 41–44 are absent on purpose: the spec reserves them or makes
@@ -221,8 +216,10 @@ impl ColorRef {
/// and every corpus value writes `FF`.
fn parse_argb(hex: &str) -> Option<[u8; 3]> {
let hex = hex.trim();
+ // `get` rather than a direct slice: byte 2 may not be a char boundary
+ // when a multi-byte character happens to give an 8-byte value.
let body = match hex.len() {
- 8 => &hex[2..],
+ 8 => hex.get(2..)?,
6 => hex,
_ => return None,
};
@@ -239,11 +236,8 @@ fn parse_argb(hex: &str) -> Option<[u8; 3]> {
/// and for single-direction stripes (one line in four is light, one in two is
/// dark). It is an approximation for the crosshatches, where the two stroke
/// directions overlap: `lightGrid` is taken as two light stripes less their
-/// intersection, and the trellises as their dark counterparts. That
-/// approximation reaches **no corpus cell** — every one of the 323 hatched
-/// cells across 1,248 workbooks is `gray0625` (210), `lightHorizontal` (63),
-/// `lightGray` (39), `gray125` (6), `darkGray` (3) or `lightUp` (2), all of
-/// which have exact fractions.
+/// intersection, and the trellises as their dark counterparts. Crosshatches
+/// are rare in practice, so the approximation is seldom exercised.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HatchPattern {
Gray0625,
@@ -303,9 +297,8 @@ impl HatchPattern {
/// §18.18.55 `ST_PatternType`, collapsed to what a painter does about it.
///
-/// The collapse is measured rather than lazy: of 2,386,621 filled cells in
-/// the corpus, **2,386,298 (100.0%) are `solid`** — every other pattern type
-/// put together is 323 cells. Those 323 do not get a pattern engine; they get
+/// The overwhelming majority of filled cells use `solid`; every other
+/// pattern type is rare. Those do not get a pattern engine; they get
/// [`HatchPattern::coverage`], which is one blend rather than a tiled bitmap.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PatternType {
@@ -350,9 +343,8 @@ impl Fill {
/// §18.18.3 `ST_BorderStyle`.
///
/// The full enum is kept — reading `dashDot` as `none` would erase an edge —
-/// but the corpus makes clear what has to be *right*: thin 91.6%, hair 4.3%,
-/// medium 3.9% are 99.8% of 42,885,045 declared edges, and everything
-/// dashed/dotted together is under 0.05%.
+/// but `thin`, `hair` and `medium` dominate real workbooks; dashed and dotted
+/// styles are rare.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BorderStyle {
#[default]
@@ -420,8 +412,8 @@ impl BorderStyle {
/// which Excel draws as two strokes with a stroke-wide gap between them —
/// three pen widths of cell, not one. A painter that reserved only
/// `width_pt` for it would overlap the neighbouring edge's inset, and one
- /// that drew a single stroke would render 27,300 corpus edges (0.1%, and
- /// more than every dashed style put together) as a plain thin line.
+ /// that drew a single stroke would render every `double` edge as a plain
+ /// thin line.
pub fn extent_pt(self) -> f32 {
match self {
BorderStyle::Double => self.width_pt() * 3.0,
@@ -612,8 +604,8 @@ pub struct Styles {
fonts: Vec<Font>,
fills: Vec<Fill>,
borders: Vec<Border>,
- /// `<indexedColors>` when the file replaces the legacy palette — 4.6% of
- /// corpus workbooks do. `None` means [`INDEXED_PALETTE`] stands.
+ /// `<indexedColors>` when the file replaces the legacy palette. `None`
+ /// means [`INDEXED_PALETTE`] stands.
indexed_colors: Option<Vec<[u8; 3]>>,
}
@@ -950,8 +942,7 @@ impl Styles {
/// — `auto="1"`, `indexed=64`/`65`, an unresolvable theme index — because
/// the default differs by consumer: automatic text is black, an automatic
/// background is white, and collapsing them here would paint white text
- /// on white cells. The census makes that concrete: 35.1% of colour-
- /// carrying cells name an automatic colour.
+ /// on white cells. Automatic colours are common enough that this matters.
///
/// The theme mapping is the one that is easy to get wrong.
/// SpreadsheetML's indices are **not** `<a:clrScheme>` document order:
@@ -998,9 +989,9 @@ impl Styles {
/// `<indexedColors>` when it declares one, else [`INDEXED_PALETTE`].
///
/// 64 and 65 (system foreground/background) and anything past the table
- /// are `None`: they are automatic, not stored colours. That pair is
- /// 89.4% of every `indexed=` in the corpus, which is why the palette
- /// itself is a small tail rather than the main path.
+ /// are `None`: they are automatic, not stored colours. That pair is most
+ /// `indexed=` uses in practice, which is why the palette itself is a
+ /// small tail rather than the main path.
pub fn indexed_color(&self, index: u32) -> Option<[u8; 3]> {
let i = index as usize;
match self.indexed_colors.as_deref() {
@@ -1015,7 +1006,7 @@ impl Styles {
}
}
- /// Does the file replace the legacy palette? 4.6% of corpus workbooks do.
+ /// Does the file replace the legacy palette?
pub fn overrides_indexed_palette(&self) -> bool {
self.indexed_colors.is_some()
}
@@ -1052,9 +1043,9 @@ impl Styles {
/// black (negative), leaving hue and saturation alone.
///
/// The HSL round-trip matters rather than a straight RGB lerp: a themed
-/// accent tinted in RGB drifts toward grey as it lightens, and the corpus
-/// tints accents constantly — banded table styles are a single accent at four
-/// tints, and drift makes the bands read as different colours.
+/// accent tinted in RGB drifts toward grey as it lightens. Banded table
+/// styles are a single accent at several tints, and drift would make the
+/// bands read as different colours.
fn apply_tint(base: [u8; 3], tint: f64) -> [u8; 3] {
if tint == 0.0 || !tint.is_finite() {
return base;
@@ -1125,6 +1116,16 @@ fn hsl_to_rgb(h: f64, s: f64, l: f64) -> [u8; 3] {
mod tests {
use super::*;
+ #[test]
+ fn parse_argb_rejects_malformed_input_without_panicking() {
+ assert_eq!(parse_argb("FF12AB34"), Some([0x12, 0xAB, 0x34]));
+ assert_eq!(parse_argb("12AB34"), Some([0x12, 0xAB, 0x34]));
+ // 8 bytes but byte 2 lands inside `é`: must return None, not panic.
+ assert_eq!(parse_argb("aé12345"), None);
+ assert_eq!(parse_argb("nothex!!"), None);
+ assert_eq!(parse_argb(""), None);
+ }
+
const STYLES: &str = r#"<?xml version="1.0"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<numFmts count="2">
@@ -1396,8 +1397,8 @@ mod tests {
}
/// Without the theme part, a themed colour is *automatic* rather than
- /// black — resolving it to black would paint white-on-black cells in the
- /// 0.6% of workbooks that ship no theme.
+ /// black — resolving it to black would paint white-on-black cells in a
+ /// workbook that ships no theme.
#[test]
fn a_themed_colour_with_no_theme_is_automatic() {
assert_eq!(
@@ -1412,9 +1413,9 @@ mod tests {
);
}
- /// "Accent1, Lighter 40%" — the single most common tint in the corpus,
- /// since it is what every banded table style is built from. Excel
- /// renders `4472C4` at `tint=0.4` as `8EA9DB`.
+ /// "Accent1, Lighter 40%" — a very common tint, since it is what every
+ /// banded table style is built from. Excel renders `4472C4` at
+ /// `tint=0.4` as `8EA9DB`.
///
/// Matched to ±1 per channel rather than exactly: Excel converts through
/// an *integer* HLS space (luminance in 0..240 steps), so its answer is
@@ -1448,9 +1449,10 @@ mod tests {
assert_eq!(tinted(0.0), [0x44, 0x72, 0xC4]);
}
- /// 93.2% of `indexed=` is 64/65/8 — the automatic sentinels and black.
- /// Resolving 64 to palette-position-64 (which does not exist) or to
- /// black would repaint a third of the corpus's colour-carrying cells.
+ /// `indexed=` is overwhelmingly 64/65/8 in practice — the automatic
+ /// sentinels and black. Resolving 64 to palette-position-64 (which does
+ /// not exist) or to black would repaint most colour-carrying cells
+ /// wrong.
#[test]
fn the_automatic_indexed_sentinels_resolve_to_nothing() {
let s = styles();
@@ -1482,8 +1484,8 @@ mod tests {
assert_eq!(parse_argb("nope"), None);
}
- /// The three styles that are 99.8% of the corpus's edges must differ in
- /// width, or every table reads as one weight.
+ /// The three most common border styles must differ in width, or every
+ /// table reads as one weight.
#[test]
fn border_widths_separate_the_three_common_styles() {
assert!(BorderStyle::Hair.width_pt() < BorderStyle::Thin.width_pt());
diff --git a/crates/liteparse-ooxml/src/xlsx/text.rs b/crates/liteparse-ooxml/src/xlsx/text.rs
index c7d46d6..dbada9f 100644
--- a/crates/liteparse-ooxml/src/xlsx/text.rs
+++ b/crates/liteparse-ooxml/src/xlsx/text.rs
@@ -1,23 +1,18 @@
//! Rich text: the `<si>` / `<is>` grammar (§18.4.8, §18.4.12) shared by the
//! shared-string table and by inline strings written straight into a sheet.
//!
-//! Two things here are not obvious from the schema and both were measured on
-//! the corpus rather than assumed:
+//! Two things here are not obvious from the schema:
//!
//! * **`<rPh>` must be stripped.** An `<si>` may carry phonetic runs —
//! *furigana*, the ruby Excel draws above a Japanese cell (§18.4.6). Their
//! `<t>` elements sit at the same depth as the real ones, so a reader that
//! concatenates every `<t>` emits `一般競争入札イッパンキョウソウニュウサツ`:
-//! the content immediately followed by its own pronunciation. This exact bug
-//! cost the XLSX baseline oracle 0.021 macro recall across a cohort of
-//! Japanese workbooks before it was found. 44.2% of real workbooks have rich
-//! text, so this path is not an edge case.
+//! the content immediately followed by its own pronunciation. Rich text is
+//! common in real workbooks, so this path is not an edge case.
//!
-//! * **Runs are kept, not flattened.** `calamine` concatenates `<r><t>` and
-//! discards every `<rPr>`; that is the single largest recall penalty the
-//! LibreOffice baseline measured (−0.067 on workbooks with rich text) and
-//! throwing the emphasis away here would give it up before the emitter ever
-//! sees it.
+//! * **Runs are kept, not flattened.** A reader that concatenates `<r><t>`
+//! and discards every `<rPr>` throws away emphasis (bold, italic, size,
+//! font) before the emitter ever sees it.
use quick_xml::Reader;
use quick_xml::events::{BytesStart, Event};
@@ -195,7 +190,7 @@ pub(crate) fn read_rich_text<R: BufRead>(
if !run_text.is_empty() {
out.runs.push(TextRun {
text: std::mem::take(&mut run_text),
- props: props.clone(),
+ props: std::mem::take(&mut props),
});
}
}
diff --git a/crates/liteparse-ooxml/src/xlsx/xml.rs b/crates/liteparse-ooxml/src/xlsx/xml.rs
index 2ca80ed..c052f43 100644
--- a/crates/liteparse-ooxml/src/xlsx/xml.rs
+++ b/crates/liteparse-ooxml/src/xlsx/xml.rs
@@ -12,9 +12,9 @@
//! value is `" "`. The event reader does not trim, so it never has the
//! problem.
//!
-//! * **Size.** Sheets are the bulk of a workbook — 50.3M cells across the
-//! 1,089-workbook finance corpus, with single sheets past 32 MB. serde
-//! materializes an intermediate `Vec` per element; streaming does not.
+//! * **Size.** Sheets are the bulk of a workbook, with single sheets running
+//! past 32 MB. serde materializes an intermediate `Vec` per element;
+//! streaming does not.
use quick_xml::events::{BytesCData, BytesRef, BytesStart, BytesText};
@@ -62,8 +62,8 @@ pub(crate) fn attr_parse<T: std::str::FromStr>(e: &BytesStart<'_>, want: &[u8])
attr(e, want)?.trim().parse().ok()
}
-/// Read a boolean attribute with OOXML's four spellings (§22.9.2.7:
-/// `1`/`0`/`true`/`false`).
+/// Read a boolean attribute, accepting OOXML's `1`/`0`/`true`/`false`
+/// (§22.9.2.7) plus the `on`/`off` some producers write.
pub(crate) fn attr_bool(e: &BytesStart<'_>, want: &[u8], default: bool) -> bool {
match attr(e, want).as_deref() {
Some("1" | "true" | "on") => true,
diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.toml
index c3e5f52..7c81d32 100644
--- a/crates/liteparse/Cargo.toml
+++ b/crates/liteparse/Cargo.toml
@@ -74,9 +74,9 @@ oar-ocr-webgpu = ["oar-ocr", "oar-ocr/webgpu"]
oar-ocr-openvino = ["oar-ocr", "oar-ocr/openvino"]
tesseract = ["dep:tesseract-rs"]
# Native office structure reading (no LibreOffice, no projection).
-# `office-native` is an internal marker enabled by every native-office reader, so code shared
-# between them (office::inline, the `apply_link` re-export) has one cfg to
-# name instead of an `any(...)` list that grows with each format.
+# `office-native` is an internal marker enabled by every native-office reader,
+# so code shared between them (the `apply_link` re-export, native complexity)
+# has one cfg to name instead of an `any(...)` list that grows per format.
office-native = []
docx-native = ["dep:liteparse-ooxml", "liteparse-ooxml/raster", "office-native"]
pptx-native = ["dep:liteparse-ooxml", "liteparse-ooxml/raster", "office-native"]
@@ -118,7 +118,7 @@ regex = "1"
# `office::xlsx` tests build minimal workbooks in memory, same pin as
# liteparse-ooxml's own reader tests.
zip = { version = "2", default-features = false, features = ["deflate"] }
-# `bold_census` only. Same pins as liteparse-ooxml's C′ measurer stack, so the
-# example inspects faces through exactly the types the render path resolves to.
+# `bold_census` example only. Same pins as liteparse-ooxml's font-measurement
+# stack, so the example inspects faces through the types the render path uses.
fontdb = "0.22"
skrifa = "0.45"
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index dd905d9..16a7d6c 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -256,11 +256,11 @@ impl Default for LiteParseConfig {
}
}
-/// Returns the default number of OCR workers: CPU cores - 1, minimum 1.
fn default_true() -> bool {
true
}
+/// Returns the default number of OCR workers: CPU cores - 1, minimum 1.
fn default_num_workers() -> usize {
std::thread::available_parallelism()
.map(|n| n.get().saturating_sub(1).max(1))
diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rs
index ca5390a..ff2485e 100644
--- a/crates/liteparse/src/lib.rs
+++ b/crates/liteparse/src/lib.rs
@@ -48,7 +48,7 @@ pub mod ocr;
#[doc(hidden)]
pub mod ocr_merge;
-/// Native readers for office formats (DOCX today), bypassing LibreOffice.
+/// Native readers for office formats (DOCX, PPTX, XLSX), bypassing LibreOffice.
pub mod office;
#[doc(hidden)]
pub mod output;
diff --git a/crates/liteparse/src/markdown_layout/blocks.rs b/crates/liteparse/src/markdown_layout/blocks.rs
index e58a5f8..4deb728 100644
--- a/crates/liteparse/src/markdown_layout/blocks.rs
+++ b/crates/liteparse/src/markdown_layout/blocks.rs
@@ -106,18 +106,6 @@ impl Cell {
}
}
-impl From<&str> for Cell {
- fn from(s: &str) -> Self {
- Cell::new(s)
- }
-}
-
-impl From<String> for Cell {
- fn from(s: String) -> Self {
- Cell::new(s)
- }
-}
-
/// Resolve a `ParaAccum` to a `Block::Paragraph`. When the paragraph was
/// uniformly styled across all lines, return the raw text with block-level
/// `bold`/`italic` flags set so the renderer wraps it once. Otherwise return
diff --git a/crates/liteparse/src/office/docx.rs b/crates/liteparse/src/office/docx.rs
index 8a79dc5..4d516f6 100644
--- a/crates/liteparse/src/office/docx.rs
+++ b/crates/liteparse/src/office/docx.rs
@@ -3,8 +3,8 @@
//! Deliberately avoids the vendored crate's `render::layout` stage: structure
//! alone — headings, lists, emphasis, merged cells, notes — is recoverable
//! without a layout engine, and layout is where the font/measurement
-//! dependencies live. Geometry is a separate concern (see `NATIVE_OFFICE_PLAN.md`
-//! stage 2); this module produces no bounding boxes.
+//! dependencies live. Geometry is a separate concern (see `docx_layout`); this
+//! module produces no bounding boxes.
//!
//! What `resolve()` hands us is *not* fully cascaded: it walks `basedOn` chains
//! and flattens numbering (including `lvlOverride`/`startOverride`), but leaves
@@ -108,9 +108,8 @@ pub fn emit_with_sources(doc: &ResolvedDocument, opts: EmitOptions) -> Vec<(Bloc
// Note bodies are appended after the document, behind a rule. Emit *all* of
// them, not just those whose reference we walked past: notes are frequently
// referenced from headers, footers and textboxes, and content-completeness
- // is what matters here (spike 4 measured `present` 0.568 → 0.921 from this
- // one choice). Note ids 0 and 1 are the separator and continuationSeparator
- // — chrome, never real content.
+ // is what matters here. Note ids 0 and 1 are the separator and
+ // continuationSeparator — chrome, never real content.
let mut notes = Vec::new();
for map in [&doc.footnotes, &doc.endnotes] {
let mut ids: Vec<NoteId> = map.keys().copied().filter(|i| i.value() > 1).collect();
@@ -158,8 +157,8 @@ struct Emitter<'a> {
box_depth: u8,
}
-/// Nesting depth past which a text box's interior is not walked. No corpus
-/// document nests at all; this only bounds a pathological or cyclic file.
+/// Nesting depth past which a text box's interior is not walked. Bounds a
+/// pathological or cyclic file; real documents do not nest text boxes.
const MAX_TEXT_BOX_DEPTH: u8 = 4;
impl<'a> Emitter<'a> {
@@ -399,10 +398,8 @@ impl<'a> Emitter<'a> {
/// Run text inside a choice is already rendered by whichever branch the
/// layout picked, and popping a figure id here would desync the queue,
/// which pairs the nth structure occurrence with the nth *drawn* placement
- /// and does not walk `mc:AlternateContent` at all. No corpus document has a
- /// picture inside one (0 of 32 elements across 165 documents), so this
- /// costs nothing measurable and keeps the figure pairing provably
- /// unchanged.
+ /// and does not walk `mc:AlternateContent` at all. A picture inside one
+ /// does not occur in practice, so this keeps the figure pairing unchanged.
fn harvest_boxes(&mut self, content: &[Inline]) {
for inline in content {
match inline {
@@ -484,9 +481,8 @@ impl<'a> Emitter<'a> {
// flattened too: heading text feeds the outline and anchors.
let text: String = chunks.iter().map(|c| c.text.as_str()).collect();
out.push(Block::Heading {
- // Emitted as declared. A dense 1..N remap was measured on the
- // 48-doc corpus and lost 39 of 66 heading rules; see the
- // "heading levels" note in NATIVE_OFFICE_PLAN.md.
+ // The declared outline level, not a remapped one: a dense 1..N
+ // remap discards the author's intended heading ranks.
level: OutlineLevel::value(lvl).clamp(1, 6),
text: self.escape(text.trim()),
});
diff --git a/crates/liteparse/src/office/docx_layout.rs b/crates/liteparse/src/office/docx_layout.rs
index 88f7e14..7d26f6b 100644
--- a/crates/liteparse/src/office/docx_layout.rs
+++ b/crates/liteparse/src/office/docx_layout.rs
@@ -1,20 +1,20 @@
//! `LayoutedPage` draw commands → [`Page`]/[`TextItem`] geometry.
//!
-//! The stage-2 tap (see `NATIVE_OFFICE_PLAN.md`): the vendored layout engine
-//! ends at per-page [`DrawCommand`] streams in Pt with a top-left origin —
-//! already liteparse viewport space, no unit conversion and no y-flip. What a
-//! `Text` command does *not* carry is a bounding box: `position` is the
-//! baseline origin and there is no width field. Both come from re-measuring
-//! with the same [`TextMeasurer`]/[`FontRegistry`] the layout ran with, which
-//! reproduces the engine's own advances bit-for-bit.
+//! The vendored layout engine ends at per-page [`DrawCommand`] streams in Pt
+//! with a top-left origin — already liteparse viewport space, no unit
+//! conversion and no y-flip. What a `Text` command does *not* carry is a
+//! bounding box: `position` is the baseline origin and there is no width field.
+//! Both come from re-measuring with the same [`TextMeasurer`]/[`FontRegistry`]
+//! the layout ran with, which reproduces the engine's own advances
+//! bit-for-bit.
//!
//! Facts that are geometric inferences on the PDF path arrive here as data:
//! `LinkAnnotation` → [`TextItem::link`], `Outline` marks →
//! [`OutlineTarget`]s, `Image` commands → [`ExtractedImage`]s with the
-//! *original* embedded bytes (see [`collect_images`]). One deliberate v1 gap,
-//! documented in the plan: `TextItem::strike` stays `false` (the vendored
-//! layout never draws strikethrough lines — markdown strike comes from the
-//! block emitter's cascade, which reads the source instead of geometry).
+//! *original* embedded bytes (see [`collect_images`]). `TextItem::strike` stays
+//! `false`: the vendored layout never draws strikethrough lines, and markdown
+//! strike comes from the block emitter's cascade, which reads the source
+//! instead of geometry.
use std::collections::{HashMap, VecDeque};
diff --git a/crates/liteparse/src/office/figures.rs b/crates/liteparse/src/office/figures.rs
index c6744da..cc68516 100644
--- a/crates/liteparse/src/office/figures.rs
+++ b/crates/liteparse/src/office/figures.rs
@@ -1,20 +1,16 @@
//! The figure/image sink shared by the native office paths.
//!
//! Assigns figure ids and accumulates the bytes behind them, document-wide.
-//! Grown in `office/pptx.rs` and moved here unchanged when the XLSX path
-//! needed the same dedup; the id *scope* is the one generalization — PPTX
-//! passes `p{page}` (a slide is a page), XLSX passes `s{sheet}` (a sheet's
-//! pictures stay numbered together however its rows paginate).
+//! The id *scope* is the one thing callers vary: PPTX passes `p{page}` (a slide
+//! is a page), XLSX passes `s{sheet}` (a sheet's pictures stay numbered
+//! together however its rows paginate).
//!
-//! Ids follow the platform extractor's `{scope}_{n}` naming, 1-based, so
-//! `img_{id}.{ext}` file names line up with the PDF and DOCX paths'.
+//! Ids are `{scope}_{n}`, 1-based, so `img_{id}.{ext}` file names line up with
+//! the PDF and DOCX paths'.
//!
-//! **`n` counts in reading order, not draw order.** Draw order is available —
-//! it is source order — but using it would mean a second walk purely to
-//! number things, and reading order is the order the `![](…)` refs appear in
-//! the markdown, so a reader scanning down the page sees `_1` before `_2`.
-//! The platform's caveat about index drift (its extractor increments even for
-//! images it skips) already means these indices are names, not positions.
+//! `n` counts in reading order (the order the `![](…)` refs appear in the
+//! markdown), so a reader scanning down the page sees `_1` before `_2`. These
+//! indices are names, not positions.
use std::collections::HashMap;
@@ -26,10 +22,9 @@ use crate::types::{ExtractedImage, Rect};
pub(crate) struct FigureSink {
pub(crate) images: Vec<ExtractedImage>,
/// Same source allocation ⇒ same bytes. Free dedup for the repeated-logo
- /// case — on the PPTX corpus, 3,602 placements behind 1,322 distinct
- /// images — because both readers pool media bytes per package path, so a
- /// part referenced twice shares one buffer and hits here rather than in
- /// the hash map below.
+ /// case: both readers pool media bytes per package path, so a part
+ /// referenced twice shares one buffer and hits here rather than in the hash
+ /// map below.
by_ptr: HashMap<usize, usize>,
/// Distinct rels can still hold identical bytes; hash → candidate
/// canonical indices, confirmed by full compare like the DOCX path's.
@@ -94,13 +89,10 @@ impl FigureSink {
}
None => {
let bytes = std::sync::Arc::new(data.to_vec());
- // The *natural* size of the image, not the placed box —
- // `bbox` already carries the placement. A crop is not applied
- // to either: `src_rect` describes a visible sub-rectangle the
- // bytes still contain, and 44% of PPTX corpus pictures
- // declare one, so re-encoding to honour it would re-encode
- // nearly half the corpus to change a number no consumer
- // reads.
+ // The natural size of the image, not the placed box — `bbox`
+ // already carries the placement. An `src_rect` crop is not
+ // applied: it describes a visible sub-rectangle the bytes still
+ // contain, and no consumer reads the cropped dimensions.
let (width, height) =
image::ImageReader::new(std::io::Cursor::new(bytes.as_slice()))
.with_guessed_format()
diff --git a/crates/liteparse/src/office/pptx.rs b/crates/liteparse/src/office/pptx.rs
index 6bf69df..a32f106 100644
--- a/crates/liteparse/src/office/pptx.rs
+++ b/crates/liteparse/src/office/pptx.rs
@@ -5,12 +5,8 @@
//! already composed group coordinate spaces into `Shape::slide_rect`. That
//! changes the shape of the problem: DOCX has no coordinates so its emitter
//! walks the document in source order, while here **source order is z-order and
-//! disagrees with reading order on 48.9% of slides** (measured by
-//! `pptx_emit_census`). Ordering is therefore a decision this module makes, not
-//! one the file makes for it.
-//!
-//! The design below follows that census throughout; where a rule looks
-//! arbitrary it is usually a corpus measurement, and the comment says which.
+//! disagrees with reading order** on a large fraction of slides. Ordering is
+//! therefore a decision this module makes, not one the file makes for it.
use liteparse_ooxml::model::{ColorMap, Inline, RunElement};
use liteparse_ooxml::pptx::{
@@ -46,10 +42,9 @@ pub struct EmitOptions {
/// Render external hyperlinks as `[text](url)`. Mirrors
/// `LiteParseConfig::extract_links`, which the PDF path honors too.
pub links: bool,
- /// Emit speaker notes after each slide's body. The census measured 222k
- /// characters of notes against 149k for all slide body text, and
- /// LibreOffice renders none of it, so this is the single largest content
- /// difference between the native and converted paths.
+ /// Emit speaker notes after each slide's body. Notes carry a large amount
+ /// of text that the LibreOffice conversion path renders none of, so this is
+ /// the single largest content difference between the two paths.
pub notes: bool,
/// Emit `Block::Figure` refs for the deck's pictures. Mirrors the PDF and
/// DOCX gate, `image_mode != Off`.
@@ -133,9 +128,9 @@ pub fn emit_with_sources(data: &[u8], opts: EmitOptions) -> Result<NativeDeck, L
/// Per-deck caches for the two cascades.
///
-/// Both rungs are keyed by part *path* and rebuilt once per path, never once
-/// per slide. Every previous PPTX probe records this discipline because a deck
-/// with 60 slides sharing 3 layouts otherwise reparses those layouts 60 times.
+/// Both rungs (layout, master) are keyed by part *path* and rebuilt once per
+/// path, never once per slide: many slides share a handful of layouts, which
+/// would otherwise be reparsed once per slide.
#[doc(hidden)]
pub struct Deck {
master_geo: HashMap<String, PlaceholderGeometry>,
@@ -163,7 +158,7 @@ pub struct Deck {
master_shapes: HashMap<String, Vec<Shape>>,
layout_shapes: HashMap<String, Vec<Shape>>,
/// §19.3.1.39 `p:sldLayout/@showMasterSp` — whether slides under this
- /// layout draw the master's shapes. 25 of the corpus's 415 layouts say no.
+ /// layout draw the master's shapes.
layout_shows_master: HashMap<String, bool>,
/// Image relationships per part, over one shared pool of bytes. On the
/// deck for the same reason the other rungs are: a layout's media table is
@@ -205,17 +200,15 @@ pub struct PreparedSlide<'d> {
///
/// Still **uncoloured**: turning it into a fill needs the theme of this
/// slide's own master, which the emitter does not load and the geometry
- /// 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.
+ /// pass does. `None` means no part in the chain declared one.
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.
+ /// carried as `Option` rather than defaulted here so a probe can tell
+ /// "stated" from "assumed".
pub color_map: Option<ColorMap>,
/// The master's and then the layout's own shapes, in the order they paint:
/// **under** everything in `shapes`, master first. Empty when the rung
@@ -235,11 +228,9 @@ pub struct PreparedSlide<'d> {
///
/// **This is a filtered list, and the filter is the point.** A layout shape
/// is drawn on every slide that uses the layout, so emitting its text
- /// per-slide reprints the deck's furniture once per page: the census found
- /// 371 occurrences behind just 43 distinct strings, one of them a speaker
- /// banner landing on 47 slides and another the literal `‹#›` of a slide
- /// number. [`Deck::keeps_inherited_text`] admits only the strings that land
- /// on exactly one slide of the deck — 29 of the 371 — which is what makes
+ /// per-slide reprints the deck's furniture (speaker banners, `‹#›` slide
+ /// numbers) once per page. [`Deck::keeps_inherited_text`] admits only the
+ /// strings that land on exactly one slide of the deck, which is what makes
/// this a content fix rather than a letterhead regression.
///
/// Both walks read it, and neither re-derives it: the markdown a reader
@@ -251,25 +242,20 @@ pub struct PreparedSlide<'d> {
///
/// Unfiltered, and that is the difference from `inherited_text` beside it.
/// The furniture rule there exists because reprinting a layout's speaker
- /// banner on all 47 slides that use the layout is a worse markdown than
- /// omitting it. A repeated *picture* has an answer that repeated text does
- /// not: the dedup contract gives every placement its own `name`, points
- /// them all at one canonical `path`, and `rewrite_duplicate_image_refs`
- /// resolves the refs — so 3,602 corpus placements cost 1,322 files.
- ///
- /// The conversion path this replaces already emits them, which is what
- /// settles it: LibreOffice flattens the master into every page, so
- /// `--no-office-native` prints 53 refs from 4 files on `bud_cnos` where
- /// this path printed none. Emitting them is parity, not noise.
+ /// banner on every slide that uses it is worse markdown than omitting it. A
+ /// repeated *picture* has an answer that repeated text does not: the dedup
+ /// contract gives every placement its own `name`, points them all at one
+ /// canonical `path`, and `rewrite_duplicate_image_refs` resolves the refs.
+ /// The LibreOffice conversion path this replaces flattens the master into
+ /// every page and emits these too, so emitting them is parity, not noise.
pub inherited_figures: [Vec<&'d Shape>; 2],
/// Whether each arm of `inherited` is empty because it was **declined**
/// rather than because the part had nothing to give: `[master, layout]`,
/// parallel to `inherited`.
///
/// The distinction is the whole reason `@showMasterSp` is parsed. Both
- /// cases paint nothing, so without this a deck that correctly honoured 25
- /// opt-outs and a deck whose layout parse silently failed would report the
- /// same numbers.
+ /// cases paint nothing, so without this a deck that correctly honoured an
+ /// opt-out and a deck whose layout parse silently failed would look alike.
pub declined: [bool; 2],
/// The slide's own `r:embed` table, and its master's and layout's in the
/// same `[master, layout]` order as `inherited`.
@@ -280,11 +266,10 @@ pub struct PreparedSlide<'d> {
/// single merged table would paint real photographs in the wrong places.
pub media: &'d PartMedia,
pub inherited_media: [&'d PartMedia; 2],
- /// The table for the part the **background** came from, which is the
- /// master's on 1,125 corpus slides and the slide's own on 58. Carried
- /// separately rather than derived by the caller, because the rung is
- /// already known here (`BackgroundSource`) and re-deriving it at the paint
- /// site is how the two would drift.
+ /// The table for the part the **background** came from. Carried separately
+ /// rather than derived by the caller, because the rung is already known
+ /// here (`BackgroundSource`) and re-deriving it at the paint site is how
+ /// the two would drift.
pub background_media: &'d PartMedia,
layout_text: Option<&'d PlaceholderTextStyles>,
master_text: Option<&'d PlaceholderTextStyles>,
@@ -346,8 +331,8 @@ impl Deck {
/// [`pptx::shows_inherited_shapes`] rather than by deserializing the slide:
/// a slide that declines a rung draws none of its text, so counting its
/// occurrences would push a string off the "lands on one slide" rule and
- /// silently drop content. Getting it from a second `parse_slide_part` per
- /// slide measured at +7.5% on the corpus's markdown run, for one boolean.
+ /// silently drop content. Reading the one boolean this cheap way avoids a
+ /// second full `parse_slide_part` per slide.
fn index_inherited_text(&mut self, pkg: &PresentationPackage) {
for slide in &pkg.slides {
self.prime(slide);
@@ -367,13 +352,10 @@ impl Deck {
/// Whether an inherited string is content rather than furniture.
///
- /// **Lands on exactly one slide of the deck.** Measured against the
- /// alternative — "comes from a rung part that exactly one slide draws",
- /// which needs no string keying — on the 45-deck corpus: the two keep the
- /// same 29 occurrences, and the rung rule additionally emits 10 the text
- /// rule rejects. All 10 are furniture, and one of them is an authoring note
- /// to whoever edits the deck ("Glegoo is een niet-Windows-Font…"), which is
- /// as clear a statement as the corpus can make about which axis is right.
+ /// **Content lands on exactly one slide of the deck.** Keying on the string
+ /// rather than on "comes from a part exactly one slide draws" is
+ /// deliberate: the coarser part-based rule additionally keeps template
+ /// furniture (e.g. authoring notes) that the string rule correctly rejects.
fn keeps_inherited_text(&self, key: &str) -> bool {
self.inherited_text_counts.get(key) == Some(&1)
}
@@ -693,8 +675,6 @@ impl Deck {
/// applied here rather than at paint time so that the cache holds exactly what
/// the painter may draw. Top-level only, matching
/// `PlaceholderGeometry::index`: a placeholder never appears inside a group.
-///
-/// Corpus: 1,567 of 4,432 layout shapes and 179 of 395 master shapes survive.
fn inherited_shapes(shapes: &[Shape]) -> Vec<Shape> {
let mut kept: Vec<Shape> = shapes
.iter()
@@ -712,20 +692,16 @@ fn inherited_shapes(shapes: &[Shape]) -> Vec<Shape> {
/// The blip fill a shape carries as its *picture*, if it is one.
///
-/// Two shapes qualify and the second is the one the census had to find:
+/// Two shapes qualify:
///
/// * `p:pic` — §19.3.1.37, the picture frame, whose image is its own
/// `p:blipFill` sibling of `spPr` rather than an `spPr` fill.
/// * **a `p:sp` with a blip fill and no text** — a picture in all but name.
-/// One corpus deck (`twinning_the_results_reviewed`) declares *zero* `p:pic`
-/// and puts all 37 of its images on 56 such shapes, so a `p:pic`-only rule
-/// takes that deck from the conversion path's 45 refs and 29 files to
-/// nothing at all.
+/// Some decks declare no `p:pic` at all and put every image on such shapes,
+/// so a `p:pic`-only rule would miss them entirely.
///
-/// The text test is what separates the two populations, and it separates them
-/// almost perfectly: 140 of 141 slide-level blip-filled `p:sp`s carry no text
-/// (pictures), while 27 of 29 layout-level ones do (a template banner *behind*
-/// a heading, which is a backdrop and not a figure).
+/// The text test separates the two populations: a textless blip-filled `p:sp`
+/// is a picture, while a blip *behind* a heading is a backdrop, not a figure.
fn picture_fill(shape: &Shape) -> Option<&liteparse_ooxml::model::BlipFill> {
match &shape.kind {
ShapeKind::Picture(pic) => Some(&pic.blip_fill),
@@ -782,10 +758,9 @@ struct SlideCtx<'a> {
/// Order a slide's top-level shapes for reading: **title first, then
/// geometric** (top-to-bottom in 0.25 in bands, left-to-right within a band).
///
-/// Both halves are load-bearing and the census measured each. Source order
-/// alone puts the title somewhere other than first on 95 slides; geometric
-/// order alone still does on 41, because authors routinely place a kicker, a
-/// caption or a logo strip above the title. Together: **0**.
+/// Both halves are load-bearing. Source order alone misplaces the title when
+/// it is not authored first; geometric order alone misplaces it when a kicker,
+/// caption or logo strip sits above it. Together they put it first reliably.
///
/// Chrome is dropped rather than sorted — a slide number in a corner otherwise
/// perturbs the order without a reader ever caring.
@@ -823,7 +798,7 @@ fn reading_key(shape: &Shape) -> (bool, i64, i64) {
// A shape with no rectangle cannot be placed. Sorting it last
// keeps it in the output — dropping content to keep a sort total
// is never the right trade — while leaving positioned shapes in
- // their proper order. The census measured 0 of these.
+ // their proper order.
None => (i64::MAX, i64::MAX),
};
(!is_title(shape.placeholder.as_ref()), band, x)
@@ -859,10 +834,10 @@ pub struct Reading<'a> {
///
/// **One sort, not two passes.** An inherited shape is a backdrop in *paint*
/// order — that is why the paint walk draws the rungs before the slide — but it
-/// is not a backdrop in *reading* order: `waterun`'s inherited subtitle sits
-/// under the slide's title and reads there. Appending the rungs and sorting
-/// once puts each string where it appears on the page, which is the only
-/// ordering claim this module ever makes.
+/// is not a backdrop in *reading* order: an inherited subtitle sits under the
+/// slide's title and reads there. Appending the rungs and sorting once puts
+/// each string where it appears on the page, which is the only ordering claim
+/// this module ever makes.
///
/// The slide's own shapes are inserted first, so on a tie — same band, same x —
/// the slide's text reads before the template's. `sort_by_key` is stable, so
@@ -909,9 +884,7 @@ pub fn slide_reading_order<'a>(prepared: &'a PreparedSlide<'_>) -> Vec<Reading<'
/// shapes come out of `inherited_shapes` with their group transforms already
/// composed — so a leaf carries its own rectangle and needs no parent.
///
-/// The key joins the paragraphs a reader would see, and is what
-/// `bench/pptx_corpus/inherited_text_census.py` counts, so the census's numbers
-/// and this module's are about the same strings.
+/// The key joins the paragraphs a reader would see.
fn collect_text_shapes<'a>(shapes: &'a [Shape], out: &mut Vec<(&'a Shape, String)>) {
for shape in shapes {
match &shape.kind {
@@ -935,9 +908,8 @@ fn collect_text_shapes<'a>(shapes: &'a [Shape], out: &mut Vec<(&'a Shape, String
}
}
ShapeKind::Group(group) => collect_text_shapes(&group.children, out),
- // A `p:graphicFrame`'s table is a second gap of a different shape —
- // 2 of them in layout parts against 237 `p:sp`s — and folding the
- // two would make neither number act on.
+ // A `p:graphicFrame`'s table is a separate, rarer gap; the
+ // inherited-text rule does not cover it.
_ => {}
}
}
@@ -972,12 +944,10 @@ pub fn is_title(ph: Option<&Placeholder>) -> bool {
/// The date / footer / slide-number family.
///
-/// Note this drops ~7k characters the census found in `dt` and `ftr`
-/// placeholders, which average 50 and 56 characters — far too long to be a
-/// date or a page number, so some authors are reusing them for real text.
-/// Dropping them wholesale is the conservative choice for now because a
-/// length test would also admit genuine repeated footer chrome on every
-/// slide of a 60-slide deck; revisit with a measurement, not a guess.
+/// This drops any real text some authors reuse `dt`/`ftr` placeholders for.
+/// Dropping wholesale is the conservative choice: a length test to rescue that
+/// text would also admit genuine repeated footer chrome on every slide.
+// TODO: distinguish reused-for-content date/footer placeholders from chrome.
#[doc(hidden)]
pub fn is_chrome(ph: Option<&Placeholder>) -> bool {
matches!(
@@ -1108,9 +1078,9 @@ fn emit_text_body(
let chunks = chunks_of(para, &resolved, ctx);
let (text, bold, italic) = render_chunks(&chunks, true);
if text.is_empty() {
- // 1,114 empty paragraphs on the corpus. They are blank-line
- // separators inside a text box, and emitting them as empty blocks
- // would put stray blank paragraphs through `render_blocks`.
+ // Empty paragraphs are blank-line separators inside a text box;
+ // emitting them as blocks would put stray blank paragraphs through
+ // `render_blocks`.
continue;
}
@@ -1140,12 +1110,11 @@ fn emit_text_body(
/// The bullet a paragraph resolves to, as `(ordered, marker)`, or `None` when
/// it is not a list item at all.
///
-/// **68.6% of non-empty paragraphs are not list items** on the corpus — 44.7%
-/// resolve to an explicit `buNone` and 23.9% to no bullet. The `buNone` share
-/// is the reason this consults the resolved style rather than the paragraph:
-/// `buNone` exists precisely to override an inherited bullet, so an emitter
-/// reading only the master's list style would turn 3,890 plain paragraphs into
-/// list items.
+/// Most non-empty paragraphs are not list items — many resolve to an explicit
+/// `buNone`. That is the reason this consults the resolved style rather than
+/// the paragraph: `buNone` exists precisely to override an inherited bullet, so
+/// an emitter reading only the master's list style would turn plain paragraphs
+/// into list items.
fn list_marker(
bullet: Option<&Bullet>,
level: u8,
@@ -1153,11 +1122,11 @@ fn list_marker(
) -> Option<(bool, String)> {
match bullet? {
Bullet::None => None,
- // The glyph is nearly always from a symbol font — `\u{f0b7}` in
- // Wingdings is the commonest bullet in the corpus — and is meaningless
- // as text. `render_blocks` prints the marker verbatim, so passing the
- // codepoint through would put a private-use character in the markdown.
- // Every bullet character therefore normalises to `-`.
+ // The glyph is nearly always from a symbol font (e.g. `\u{f0b7}` in
+ // Wingdings) and is meaningless as text. `render_blocks` prints the
+ // marker verbatim, so passing the codepoint through would put a
+ // private-use character in the markdown. Every bullet character
+ // therefore normalises to `-`.
Bullet::Character { .. } => Some((false, "-".into())),
Bullet::AutoNumber { scheme, start_at } => {
let n = counters
@@ -1171,11 +1140,8 @@ fn list_marker(
}
}
-/// Render an auto-number in its declared scheme.
-///
-/// Four schemes appear on the corpus (`ArabicPeriod` 102, `AlphaLcParenR` 8,
-/// `AlphaLcPeriod` 5, `ArabicParenR` 2) but all nine are cheap to support, and
-/// `Other` degrades to a plain number rather than guessing.
+/// Render an auto-number in its declared scheme. All nine schemes are cheap to
+/// support; `Other` degrades to a plain number rather than guessing.
fn format_autonumber(scheme: &AutoNumberScheme, n: u32) -> String {
use AutoNumberScheme as S;
match scheme {
@@ -1247,9 +1213,8 @@ fn roman(n: u32) -> String {
/// set, while `MergedTable` follows HTML and expects it to be *absent*. So
/// absorbed cells are dropped and the origin cell carries the span.
///
-/// Merges are rare here — 8 colspan and 6 rowspan cells across the whole
-/// corpus, against DOCX where they were the single biggest win. The variant is
-/// reused because it costs nothing, not because PPTX needs it.
+/// Merges are rare in PPTX; the [`Block::MergedTable`] variant is reused
+/// because it costs nothing, not because PPTX needs it.
fn emit_table(
table: &Table,
ctx: &mut SlideCtx<'_>,
@@ -1274,10 +1239,9 @@ fn emit_table(
if rows.iter().all(|r| r.is_empty()) {
return;
}
- // `firstRow` is PPTX's only header signal and is set on 15 of 36 corpus
- // tables. When absent we claim no header rather than promoting row 0:
- // `MergedTable` renders a headerless table as a pipe table with an empty
- // header, which is what the DOCX path does for the same case.
+ // `firstRow` is PPTX's only header signal. When absent we claim no header
+ // rather than promoting row 0: `MergedTable` renders a headerless table as
+ // a pipe table with an empty header, matching the DOCX path.
let header_rows = usize::from(table.first_row);
out.push((Block::MergedTable { rows, header_rows }, src));
}
@@ -1312,8 +1276,8 @@ fn cell_text(body: Option<&TextBody>, ctx: &mut SlideCtx<'_>) -> String {
/// Emit a SmartArt diagram's text, in the graphic frame's place.
///
-/// The largest single content gap a shape-tree walk has: 53 corpus parts, all
-/// 53 carrying text, 12,102 characters that no walk of the slide can reach.
+/// A large content gap for a plain shape-tree walk: the text lives in the
+/// diagram data part and no walk of the slide's shapes can reach it.
///
/// Emitted as paragraphs at the frame's position in reading order, which is
/// the part geometry buys us — a document-order reader can only append the
@@ -1351,10 +1315,9 @@ fn emit_diagram(
/// Emit a notes slide's body.
///
-/// Only the `body` placeholder. The census measured 222,109 characters there
-/// against 1,420 characters everywhere else on notes slides, almost all of it a
-/// slide number — so this needs no heuristic, and the `sldImg` thumbnail
-/// carries no text at all.
+/// Only the `body` placeholder. Nearly all real notes text lives there; the
+/// other placeholders carry only a slide number, and the `sldImg` thumbnail no
+/// text at all — so this needs no heuristic.
fn emit_notes(
shapes: &[Shape],
ctx: &mut SlideCtx<'_>,
@@ -1409,8 +1372,7 @@ fn walk_inlines(
match el {
RunElement::Text(t) => text.push_str(t),
RunElement::Tab => text.push('\t'),
- // `a:br` is a hard break inside one text box. 250
- // paragraphs on the corpus have one, and `Block`'s
+ // `a:br` is a hard break inside one text box. `Block`'s
// single-line `text` cannot hold it, so it becomes a
// space rather than being dropped or splitting the
// paragraph into two unrelated blocks.
@@ -1465,9 +1427,9 @@ mod tests {
#[test]
fn explicit_bu_none_is_not_a_list_item() {
- // 44.7% of corpus paragraphs land here. `buNone` exists to override an
- // inherited bullet, so treating "has a resolved bullet" as "is a list"
- // would turn 3,890 plain paragraphs into list items.
+ // `buNone` exists to override an inherited bullet, so treating "has a
+ // resolved bullet" as "is a list" would turn plain paragraphs into
+ // list items.
let mut c = HashMap::new();
assert!(list_marker(Some(&Bullet::None), 0, &mut c).is_none());
}
@@ -1480,8 +1442,8 @@ mod tests {
#[test]
fn symbol_font_bullet_never_reaches_the_markdown() {
- // Wingdings' private-use codepoint is the commonest bullet in the
- // corpus and is meaningless as text; `render_blocks` would print it.
+ // Wingdings' private-use codepoint is a common bullet and is
+ // meaningless as text; `render_blocks` would print it.
let mut c = HashMap::new();
let bullet = Bullet::Character {
char: "\u{f0b7}".into(),
@@ -1552,8 +1514,8 @@ mod tests {
}
assert!(!is_chrome(ph(PlaceholderKind::Title).as_ref()));
assert!(!is_chrome(ph(PlaceholderKind::Body).as_ref()));
- // 59% of corpus slide text sits on shapes with no placeholder, so the
- // absent case must never be chrome.
+ // Much slide text sits on shapes with no placeholder, so the absent
+ // case must never be chrome.
assert!(!is_chrome(None));
}
@@ -1601,9 +1563,7 @@ mod tests {
)
}
- /// The key is the string the census counts: paragraphs joined by newline,
- /// blank ones skipped. A key that drifted from the census's would make
- /// every number in the plan's write-up about a different population.
+ /// The key is paragraphs joined by newline, blank ones skipped.
#[test]
fn the_key_joins_the_paragraphs_a_reader_would_see() {
let shapes = tree(&text_shape(
@@ -1640,8 +1600,8 @@ mod tests {
}
/// A picture or a connector carries no `p:txBody`, and an empty one is not
- /// a string — neither may enter the tally, or the counts stop matching the
- /// census and a blank shape starts competing for a "lands on one slide".
+ /// a string — neither may enter the tally, or a blank shape would compete
+ /// for a "lands on one slide" slot.
#[test]
fn shapes_with_nothing_to_say_are_not_counted() {
let shapes = tree(&format!(
@@ -1680,8 +1640,8 @@ mod tests {
}
/// Inherited text is a backdrop in *paint* order and not in *reading*
- /// order: `waterun`'s inherited strapline sits above the slide's own first
- /// line and reads there, which one sort over both trees gives for free.
+ /// order: an inherited strapline sits above the slide's own first line and
+ /// reads there, which one sort over both trees gives for free.
#[test]
fn inherited_text_reads_where_it_sits_on_the_page() {
let defaults = DeckTextDefaults::default();
@@ -1763,8 +1723,8 @@ mod tests {
)
}
- /// The census's rule, in the two directions it has to hold: a `p:pic` is a
- /// picture, and so is a blip-filled shape that says nothing.
+ /// The rule in the two directions it has to hold: a `p:pic` is a picture,
+ /// and so is a blip-filled shape that says nothing.
#[test]
fn a_pic_and_a_textless_blip_filled_shape_are_both_pictures() {
let shapes = tree(&format!(
@@ -1776,8 +1736,7 @@ mod tests {
}
/// The other half of the same rule, and the half that keeps it honest: a
- /// blip behind text is a backdrop, and the text is the content. 27 of the
- /// corpus's 29 layout-level blip-filled shapes are exactly this.
+ /// blip behind text is a backdrop, and the text is the content.
#[test]
fn a_blip_behind_text_is_a_backdrop_not_a_figure() {
let shapes = tree(&blip_filled_sp(2, "rId2", &["a heading over a photo"]));
@@ -1795,10 +1754,9 @@ mod tests {
assert!(picture_fill(&shapes[0]).is_none());
}
- /// A rung's pictures reach the reading order, and they arrive flagged as
- /// figures — `inherited_text_laid_out` keys on that flag, so a picture
- /// counted as inherited *text* would corrupt the metric that step's A/B
- /// rests on.
+ /// A rung's pictures reach the reading order flagged as figures —
+ /// `inherited_text_laid_out` keys on that flag, so a picture counted as
+ /// inherited *text* would corrupt that count.
#[test]
fn inherited_pictures_read_as_figures() {
let defaults = DeckTextDefaults::default();
diff --git a/crates/liteparse/src/office/pptx_layout.rs b/crates/liteparse/src/office/pptx_layout.rs
index 309dcaa..f902049 100644
--- a/crates/liteparse/src/office/pptx_layout.rs
+++ b/crates/liteparse/src/office/pptx_layout.rs
@@ -8,24 +8,24 @@
//! measuring the text and wrapping it inside the rectangle the shape gives it.
//!
//! That derivation is not written here. `render::layout` already does it for
-//! DOCX text boxes, and the layout census established that the reusable part
-//! reaches further than expected: `stack_blocks` names no `w:` type, and
-//! `shape_body::layout_shape_body` — carved out of the DOCX text-box path for
-//! this — does insets, anchor and `@vertOverflow` off a plain `a:bodyPr`, which
-//! is DrawingML and identical in both formats. So this module is an **adapter**:
-//! it turns a `TextParagraph` plus its resolved text style into the
-//! `LayoutBlock`s that stack expects, and hands the resulting draw commands to
-//! the same `DrawCommand` → `TextItem` converter the DOCX path uses.
+//! DOCX text boxes, and the reusable part reaches further than expected:
+//! `stack_blocks` names no `w:` type, and `shape_body::layout_shape_body` —
+//! carved out of the DOCX text-box path for this — does insets, anchor and
+//! `@vertOverflow` off a plain `a:bodyPr`, which is DrawingML and identical in
+//! both formats. So this module is an **adapter**: it turns a `TextParagraph`
+//! plus its resolved text style into the `LayoutBlock`s that stack expects, and
+//! hands the resulting draw commands to the same `DrawCommand` → `TextItem`
+//! converter the DOCX path uses.
//!
-//! What is genuinely new here, and what the census said each would cost:
+//! What is genuinely new here, and why each cannot be assumed:
//!
//! | input | why it cannot be assumed |
//! |---|---|
-//! | theme font default | **26.3% of runs name no font.** DrawingML's answer is `+mn-lt`/`+mj-lt`; guessing the host default puts a quarter of the corpus in the wrong face *and* the wrong width |
-//! | `a:bodyPr` insets | declared on 100% of text shapes, and **47.2% differ from the spec default** |
-//! | `a:bodyPr` anchor | **27.7% are not `top`** |
-//! | `a:normAutofit` | only **3.4%** actually shrink, but the most aggressive is to **25%** — a body laid out at 4x its intended size is not a subtle error |
-//! | shape rotation | **5.3% of text shapes, 148 at a right angle.** The DOCX path hardcodes `rotation = 0.0`, which is honest for a page and is not honest here |
+//! | theme font default | many runs name no font. DrawingML's answer is `+mn-lt`/`+mj-lt`; guessing the host default gives the wrong face *and* the wrong width |
+//! | `a:bodyPr` insets | declared on every text shape, and often differ from the spec default |
+//! | `a:bodyPr` anchor | frequently not `top` |
+//! | `a:normAutofit` | rarely shrinks, but when it does it can go as low as 25% — a body laid out at 4x its intended size is not a subtle error |
+//! | shape rotation | a minority of text shapes rotate, some at a right angle. The DOCX path hardcodes `rotation = 0.0`, which is honest for a page and not here |
//!
//! Rotation is applied here rather than inside the shared converter because
//! `DrawCommand::Text` carries no rotation field — it is emitted pre-shifted but
@@ -42,12 +42,12 @@
//!
//! Text is emitted in reading order; **fills and outlines are emitted in
//! document order**, by [`paint_shapes`], because §19.3.1.45 makes document
-//! order z-order and the paint census measured 29.1% of the corpus pairs where
-//! that difference is observable coming out the wrong way round under reading
-//! order. The two walks share one `Deck::prepare`, so they cannot disagree
-//! about a rectangle or a cascade; what they deliberately do not share is the
-//! chrome filter, the traversal order, and the placement mechanism — a text
-//! body is bracketed, a path places itself.
+//! order z-order and reading order sequences a significant fraction of
+//! overlapping fills the wrong way round. The two walks share one
+//! `Deck::prepare`, so they cannot disagree about a rectangle or a cascade;
+//! what they deliberately do not share is the chrome filter, the traversal
+//! order, and the placement mechanism — a text body is bracketed, a path
+//! places itself.
use liteparse_ooxml::model::dimension::Dimension;
use liteparse_ooxml::model::{
@@ -151,14 +151,12 @@ pub struct SlideGeometry {
/// parsed it also counted every outline whose colour was sitting in the
/// theme, unread.
pub outlines_defaulted_black: usize,
- /// Shapes carrying a `p:style` that the paint walk consulted. 2,181 on the
- /// corpus, of which 1,744 are on slides and the rest on layouts and
- /// masters.
+ /// Shapes carrying a `p:style` that the paint walk consulted.
pub shapes_with_style: usize,
/// Shapes whose fill came from the theme's `fillStyleLst` via `a:fillRef`,
/// because `spPr` declared no fill element at all. Counted after
- /// resolution, so an `idx="0"` reference — 335 corpus shapes, more than
- /// half of those that inherit — is not counted here.
+ /// resolution, so an `idx="0"` reference (the "no reference" sentinel) is
+ /// not counted here.
pub fills_from_style_ref: usize,
/// Shapes stroked entirely from the theme's `lnStyleLst`, having no
/// `<a:ln>` of their own. This is ink the pass did not put down before,
@@ -170,9 +168,8 @@ pub struct SlideGeometry {
/// than the index.
///
/// The honest residue of the two counters above. Without it a theme that
- /// resolves to an empty matrix is indistinguishable from a corpus that
- /// never asked, and the difference is a shape PowerPoint paints and we do
- /// not.
+ /// resolves to an empty matrix is indistinguishable from input that never
+ /// asked, and the difference is a shape PowerPoint paints and we do not.
pub style_refs_unresolved: usize,
/// Per page, the command index of the full-slide background
/// [`DrawCommand::Path`], when one was emitted. Parallel to `pages`.
@@ -187,28 +184,27 @@ pub struct SlideGeometry {
/// Slides that emitted a full-slide background [`DrawCommand::Path`].
pub painted_backgrounds: usize,
/// Slides whose resolved background is deliberately transparent
- /// (`<a:noFill/>`, 36 on the corpus). Not a gap: nothing is the correct
- /// paint, and it is separated from the next two so that "no ink" and
- /// "could not make ink" stay different claims.
+ /// (`<a:noFill/>`). Not a gap: nothing is the correct paint, and it is
+ /// separated from the next two so that "no ink" and "could not make ink"
+ /// stay different claims.
pub transparent_backgrounds: usize,
- /// Slides that declare a background this pass cannot colour: `blip` (63 on
- /// the corpus), `pattern`, or a `bgRef` into a matrix entry of one of
- /// those kinds. Distinguished from the transparent case on the *declared*
- /// arm, because `resolve_fill` collapses all of them to
+ /// Slides that declare a background this pass cannot colour: `blip`,
+ /// `pattern`, or a `bgRef` into a matrix entry of one of those kinds.
+ /// Distinguished from the transparent case on the *declared* arm, because
+ /// `resolve_fill` collapses all of them to
/// [`ResolvedFill::None`] — so the resolved fill alone would report a
/// missing photograph as a slide that correctly has no backdrop.
pub unrenderable_backgrounds: usize,
/// Slides where no part in the slide → layout → master chain declares a
- /// background at all. 0 on the corpus, so any number here is a signal
- /// about the package rather than a normal outcome.
+ /// background at all. Normally zero, 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.
+ /// a shape-level text colour this pass does not parse.
pub runs_colour_defaulted: usize,
/// Shapes painted from a *layout* or *master* part rather than the slide's
/// own tree — the panels, rules and logo strips a deck authors once and
@@ -224,53 +220,49 @@ pub struct SlideGeometry {
/// — the same class as `unpainted_shapes`, counted separately for the same
/// reason as above.
pub inherited_shapes_unpainted: usize,
- /// Occurrences of an inherited shape that **carries text at all**: 371 on
- /// the corpus, of which 292 are a master's and 79 a layout's.
+ /// Occurrences of an inherited shape that **carries text at all**.
///
- /// Not a gap, and not a target. The census behind
- /// `bench/pptx_corpus/inherited_text_census.py` found only **43 distinct
- /// strings** under those 371 occurrences — a layout shape is drawn on every
+ /// Not a gap, and not a target. Far fewer distinct strings sit under these
+ /// occurrences than the count suggests — a layout shape is drawn on every
/// slide that uses the layout, so one speaker banner authored once lands on
- /// 47 pages, and 151 of the occurrences are the literal `‹#›` of a slide
+ /// many pages, and many occurrences are the literal `‹#›` of a slide
/// number. This counts the population; `inherited_text_laid_out` counts the
/// part of it a reader gets.
pub inherited_shapes_with_text: usize,
/// Occurrences of inherited text this pass **did** lay out: the strings
- /// that land on exactly one slide of their deck, 29 of the 371 on the
- /// corpus. See [`PreparedSlide::inherited_text`] for the rule and what it
- /// was measured against.
+ /// that land on exactly one slide of their deck. See
+ /// [`PreparedSlide::inherited_text`] for the rule.
///
/// Counted in the text walk rather than the paint walk, so it is an
/// occurrence of *emitted* text and not of a shape that happened to paint.
- /// The residue — 342 — is furniture, and dropping it is the feature.
+ /// The residue is furniture, and dropping it is the feature.
///
/// [`PreparedSlide::inherited_text`]: crate::office::pptx::PreparedSlide::inherited_text
pub inherited_text_laid_out: usize,
- /// Slides that decline an inherited rung via `@showMasterSp="0"` — 4 slides
- /// declining their layout's shapes and, through 25 layouts, the slides that
- /// decline their master's. Counted because "painted nothing here" and
- /// "asked to paint nothing here" are different claims.
+ /// Slides that decline an inherited rung via `@showMasterSp="0"`. Counted
+ /// because "painted nothing here" and "asked to paint nothing here" are
+ /// different claims.
pub slides_declining_layout: usize,
pub slides_declining_master: usize,
/// `p:pic` shapes the paint walk reached, on any rung.
pub pictures_seen: usize,
/// Pictures whose blip resolves to no image: an empty picture placeholder
- /// (157 on the corpus, all in layouts and masters — correct, not a gap),
- /// an external `r:link`, or media with no decoder (39 EMF/WMF references).
+ /// (all in layouts and masters — correct, not a gap), an external `r:link`,
+ /// or media with no decoder (EMF/WMF references).
///
/// Pooled deliberately with the correct cases, because the *ratio* is the
/// claim this pass can make honestly; splitting it further would need the
/// resolver to report a reason, which is its own change.
pub pictures_unresolved: usize,
/// Pictures that declare no `prstGeom` and took the schema's implicit
- /// `rect`. 41 on the corpus.
+ /// `rect`.
pub pictures_implicit_rect: usize,
/// Shapes painted with an image fill — pictures and `spPr` blip fills
/// together. The number that says the emitter put photographs on slides,
/// as opposed to merely resolving them.
pub blips_painted: usize,
- /// Slides whose background is an image this pass now paints. Carved out of
- /// `unrenderable_backgrounds`, which was 63 before this step.
+ /// Slides whose background is an image this pass paints. Carved out of
+ /// `unrenderable_backgrounds`.
pub blip_backgrounds_painted: usize,
/// Shapes whose `spPr` fill is `a:grpFill` and which took a real fill from
/// an enclosing group (§20.1.8.35).
@@ -299,7 +291,8 @@ pub struct ShapePlacement {
/// Not decoration: a table cell's rectangle is *derived* (grid prefix sums,
/// grown rows) where a shape's is *declared*, so the two have different
/// failure modes and a check that pooled them would let a cell-only bug —
- /// a dropped `a:tcPr` anchor, say — hide inside 4,938 correct shapes.
+ /// a dropped `a:tcPr` anchor, say — hide inside the far larger set of
+ /// correct shapes.
pub kind: PlacementKind,
/// The box's unrotated rectangle in slide Pt: `(x, y, width, height)`.
pub rect: (f32, f32, f32, f32),
@@ -475,10 +468,8 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
// only for markdown a reader actually gets, so the two walks take
// the same traversal or the claim is not true.
for read in pptx_emit::slide_reading_order(&prepared) {
- // `!figure`: the same list now also carries the rungs'
- // pictures, which this counter does not name and must not
- // absorb — its value is the A/B anchor for the inherited-text
- // step (29 on the corpus).
+ // `!figure`: the same list also carries the rungs' pictures,
+ // which this counter does not name and must not absorb.
if read.rung.is_some() && !read.figure {
*ctx.inherited_text_laid_out += 1;
}
@@ -657,9 +648,8 @@ impl ShapeCtx<'_, '_> {
/// re-derived here: [`Deck::prepare`] resolves which of slide/layout/master
/// wins, and [`pptx::background_fill`] is the single place that knows a
/// `bgRef@idx` of 1001 selects `bgFillStyleLst[0]` and not `fillStyleLst`.
-/// `ctx.theme` is this slide's own master's theme, which is what makes the
-/// 31 corpus slides that resolve a `bgRef` under a second master come out in
-/// their own palette.
+/// `ctx.theme` is this slide's own master's theme, which is what makes a slide
+/// resolving a `bgRef` under a second master come out in its own palette.
///
/// [`Deck::prepare`]: crate::office::pptx::Deck::prepare
fn paint_background(
@@ -678,9 +668,9 @@ fn paint_background(
// tell them apart: `resolve_fill` collapses blip, pattern and `grpFill`
// to `None` alongside a genuine `<a:noFill/>`. Splitting them on the
// *declared* arm is the difference between "this slide has no
- // backdrop, correctly" (36 on the corpus) and "this slide's photograph
- // backdrop is missing" (63) — reporting the second as the first is
- // exactly the silent-wrongness this pass counts its way out of.
+ // backdrop, correctly" and "this slide's photograph backdrop is
+ // missing" — reporting the second as the first is exactly the
+ // silent-wrongness this pass counts its way out of.
if matches!(bg, pptx::Background::Properties(DrawingFill::None)) {
*ctx.transparent_backgrounds += 1;
} else {
@@ -726,19 +716,17 @@ fn paint_background(
/// **A second traversal, and it has to be.** The text walk uses
/// [`reading_order`], which sorts shapes into bands and drops chrome; both
/// halves are right for reading and wrong for painting. §19.3.1.45 makes
-/// document order z-order, and the paint census found that of the 1,263 corpus
-/// pairs where two fills overlap — i.e. where paint order is observable at all
-/// — reading order sequences **368 (29.1%)** the wrong way round, on 7.3% of
-/// slides. A backdrop panel authored last and read first would paint over the
-/// content it belongs under.
+/// document order z-order, and where two fills overlap reading order sequences
+/// a meaningful share of them the wrong way round. A backdrop panel authored
+/// last and read first would paint over the content it belongs under.
///
/// The two walks share one `Deck::prepare`, so the rectangles and the cascade
/// they see are the same ones by construction. What is *not* shared is the
/// chrome filter: this walk paints chrome, the text walk still drops it, and
-/// the 347 chrome shapes that carry text are a divergence this step leaves
-/// open rather than closes (see the module-level note in the plan).
-/// `group_fill` is the fill the *enclosing* group offers its members, already
-/// resolved and already chain-collapsed — see [`group_fill_for`].
+/// chrome shapes that carry text are a divergence this step leaves open rather
+/// than closes. `group_fill` is the fill the *enclosing* group offers its
+/// members, already resolved and already chain-collapsed — see
+/// [`group_fill_for`].
fn paint_shapes(
shapes: &[Shape],
from: Source<'_>,
@@ -766,8 +754,8 @@ fn paint_shapes(
///
/// * the group names a fill → that, resolved in this part's colour context
/// * the group's own fill is `a:grpFill` → whatever its parent offered,
-/// passed straight through (6 corpus groups, carrying 414 shapes between
-/// them, so the chain is load-bearing rather than theoretical)
+/// passed straight through (the chain is load-bearing: nested groups carry
+/// many shapes between them)
/// * the group names `a:noFill`, or no fill at all → `None`. The spec's
/// "inherit nothing"; a member is then correctly unpainted.
fn group_fill_for(
@@ -806,17 +794,17 @@ fn paint_shape(
return;
};
// Counted before the paint decision, not after: the text is missing
- // whether or not the shape also puts ink down, and a 237-shape gap that
- // only reported itself on shapes that happened to have a fill would be a
- // number that under-reports exactly where it matters.
+ // whether or not the shape also puts ink down, and a gap that only reported
+ // itself on shapes that happened to have a fill would under-report exactly
+ // where it matters.
if from.rung == Rung::Inherited && shape_text_len(shape) > 0 {
*ctx.inherited_shapes_with_text += 1;
}
// §19.3.1.46 `p:style` — the theme-matrix references this shape inherits
- // its fill and outline from when `spPr` declares none of its own. 2,181
- // corpus shapes carry one; `a:fontRef` is deliberately not consulted here,
- // because a run colour resolved in the paint walk and not in the text
- // cascade would make the two disagree.
+ // its fill and outline from when `spPr` declares none of its own.
+ // `a:fontRef` is deliberately not consulted here, because a run colour
+ // resolved in the paint walk and not in the text cascade would make the two
+ // disagree.
let style = shape.style.as_ref();
let mut visuals = resolve_shape_visuals(
Some(props),
@@ -845,8 +833,7 @@ fn paint_shape(
let fill_from_ref = props.fill.is_none() && !matches!(visuals.fill, ResolvedFill::None);
let stroke_from_ref = props.outline.is_none() && visuals.stroke.is_some();
// A reference that named a matrix entry and came back empty. `idx == 0` is
- // the spec's "no reference" sentinel — 335 corpus `fillRef`s use it — and
- // is not a miss.
+ // the spec's "no reference" sentinel and is not a miss.
let asked = |r: Option<&StyleMatrixRef>| r.is_some_and(|r| r.idx != 0);
let missed_fill = props.fill.is_none()
&& asked(style.and_then(|s| s.fill_ref.as_ref()))
@@ -874,8 +861,8 @@ fn paint_shape(
let blip = resolve_blip_fill(&pic.blip_fill, Some(from.media));
if matches!(blip, ResolvedFill::None) {
// An empty picture placeholder, an `r:link`, or media we cannot
- // decode (39 EMF/WMF references on the corpus). Counted rather
- // than silently falling back to the frame's own fill.
+ // decode (EMF/WMF). Counted rather than silently falling back to
+ // the frame's own fill.
*ctx.pictures_unresolved += 1;
} else {
visuals.fill = blip;
@@ -899,7 +886,7 @@ fn paint_shape(
height: emu_to_pt(box_.size.height.raw()),
};
// §19.3.1.37: a picture frame with no `prstGeom` is a rectangle — the
- // image fills its box. 41 corpus pictures declare none.
+ // image fills its box.
//
// This is **not** the "never approximate an unbuildable preset by its
// bounding box" rule being relaxed. That rule is about a `cloud` we cannot
@@ -963,9 +950,8 @@ fn paint_shape(
/// How much text an inherited shape carries that this pass will not lay out.
///
-/// Only `p:sp` bodies are counted. A `p:graphicFrame`'s table is a second gap
-/// of a different shape, and 2 of them appear in layout parts against 237
-/// `p:sp`s — folding the two would make the number harder to act on, not more
+/// Only `p:sp` bodies are counted. A `p:graphicFrame`'s table is a separate,
+/// rarer gap; folding the two would make the number harder to act on, not more
/// complete.
fn shape_text_len(shape: &Shape) -> usize {
let ShapeKind::AutoShape(sp) = &shape.kind else {
@@ -1032,9 +1018,8 @@ fn layout_shape(shape: &Shape, ctx: &mut ShapeCtx<'_, '_>) {
/// items, translated and rotated onto the slide.
fn layout_text_shape(shape: &Shape, body: &TextBody, ctx: &mut ShapeCtx<'_, '_>) {
// A shape with no rectangle cannot be laid out at all: there is nothing to
- // wrap inside. The geometry pass measured 0 of these across the corpus, and
- // the markdown emitter still emits such a shape's text — so this is a
- // geometry gap for that shape, not a content drop.
+ // wrap inside. The markdown emitter still emits such a shape's text — so
+ // this is a geometry gap for that shape, not a content drop.
let Some(slide_rect) = shape.slide_rect else {
return;
};
@@ -1048,10 +1033,9 @@ fn layout_text_shape(shape: &Shape, body: &TextBody, ctx: &mut ShapeCtx<'_, '_>)
// §20.1.9.18: the shape's box is not its *text* box. Every preset carries
// an `<a:rect>` naming where its text goes, and for anything that is not a
// plain rectangle that rectangle is inset — a `roundRect` by the sagitta of
- // its corner arc, a `cloud` by a third of its width in each direction. 310
- // of the corpus's 4,969 laid-out bodies sit in one, keeping a mean 78% of
- // the room they are given today; all 310 shrink and none grows, so this
- // only ever wraps text sooner, never later.
+ // its corner arc, a `cloud` by a third of its width in each direction. The
+ // inset rect is always smaller than the box, so this only ever wraps text
+ // sooner, never later.
let body_box = body_rect(shape, extent);
let body_extent = body_box.size;
let offset = (body_box.origin.x.raw(), body_box.origin.y.raw());
@@ -1125,16 +1109,15 @@ fn layout_text_shape(shape: &Shape, body: &TextBody, ctx: &mut ShapeCtx<'_, '_>)
/// geometry a few lines earlier. The two cannot share: the painter builds in
/// `slide_rect.bounding_box()`, because a rotated child's ink lives in the box
/// group composition produced, while text is laid out in `slide_rect.rect` and
-/// turned about the frame's centre afterwards. On 187 of the corpus's
-/// laid-out bodies those two extents differ, and a shared build would give one
-/// of the two walks a rectangle scaled for the other. The build itself is
-/// ~0.5µs of guide evaluation.
+/// turned about the frame's centre afterwards. Those two extents differ for a
+/// rotated shape, and a shared build would give one of the two walks a
+/// rectangle scaled for the other. The build itself is cheap.
///
-/// Falls back to the full box in three cases, none of which occurs on the
-/// corpus but each of which is a silent text drop if taken literally:
+/// Falls back to the full box in three cases, each a silent text drop if taken
+/// literally:
///
-/// * no geometry declared (886 bodies — the schema's default is a rectangle,
-/// whose text rect *is* the box, so the fallback is also the right answer),
+/// * no geometry declared (the schema's default is a rectangle, whose text
+/// rect *is* the box, so the fallback is also the right answer),
/// * an unbuildable preset, i.e. a name §20.1.9.18 does not define,
/// * a degenerate rect. A body given no width lays nothing out, and dropping a
/// shape's text on a guide that evaluated to zero would be a worse answer
@@ -1300,17 +1283,16 @@ impl Frame {
/// same anchor as an `a:bodyPr` — so everything below the rectangle is the
/// shape path's code.
///
-/// Two corpus facts decide the derivation, and both contradict the obvious
+/// Two facts decide the derivation, and both contradict the obvious
/// implementation:
///
-/// - **The frame's `@cx` is not the table's width.** It agrees with the grid on
-/// 26 of 36 corpus tables; the other 10 are two decks whose producer writes a
-/// constant 236.2pt for every frame, up to 4x wrong. The grid is authoritative
-/// and the frame supplies only the origin.
-/// - **`a:tr@h` is a minimum, not a height** (§21.1.3.18). 16 corpus rows
-/// declare `h="0"`, which under a literal reading stacks every cell of the
-/// table at its top edge. So each row is grown to its tallest cell, which is
-/// why cells must be measured before any of them can be placed.
+/// - **The frame's `@cx` is not the table's width.** Some producers write a
+/// constant frame width for every table, up to 4x wrong. The grid is
+/// authoritative and the frame supplies only the origin.
+/// - **`a:tr@h` is a minimum, not a height** (§21.1.3.18). A row may declare
+/// `h="0"`, which under a literal reading stacks every cell of the table at
+/// its top edge. So each row is grown to its tallest cell, which is why cells
+/// must be measured before any of them can be placed.
fn layout_table(shape: &Shape, table: &pptx::Table, ctx: &mut ShapeCtx<'_, '_>) {
let text_cells = || {
table
@@ -1450,8 +1432,8 @@ fn prefix_edges(lengths: impl Iterator<Item = Pt>) -> Vec<Pt> {
/// §21.1.3.18: each row's declared `@h` raised to fit its tallest cell.
///
/// `@h` is a **minimum**, and treating it as the height is not a rounding
-/// error: 16 corpus rows declare `h="0"`, which stacks every cell of those
-/// tables at the table's top edge.
+/// error: a row declaring `h="0"` would stack every cell of the table at its
+/// top edge.
///
/// A row-spanning cell is deliberately excluded from its row's growth. Its
/// content is shared across every row it covers, so charging the whole height
@@ -1805,9 +1787,8 @@ mod tests {
#[test]
fn theme_font_splits_title_from_body() {
- // The rung that covers the census's 26.3% of runs naming no font.
- // Getting the halves the wrong way round is invisible in markdown and
- // wrong in every width.
+ // The rung that covers runs naming no font. Getting the halves the
+ // wrong way round is invisible in markdown and wrong in every width.
let theme = theme_with("Georgia", "Verdana");
assert_eq!(theme_family(Some(&theme), true), "Georgia");
assert_eq!(theme_family(Some(&theme), false), "Verdana");
@@ -1881,10 +1862,9 @@ mod tests {
#[test]
fn zero_declared_height_is_grown_not_taken_literally() {
- // 16 corpus rows declare `h="0"`. Taken literally every row edge is
- // zero and the whole table collapses onto its top edge — text that is
- // still inside the frame, and therefore invisible to a containment
- // check.
+ // A row declaring `h="0"` taken literally makes every row edge zero and
+ // the whole table collapses onto its top edge — text that is still
+ // inside the frame, and therefore invisible to a containment check.
let grown = grown_row_heights(&[Pt::ZERO, Pt::ZERO], &[cell(0, 1, 18.0), cell(1, 1, 24.0)]);
assert_eq!(grown, vec![Pt::new(18.0), Pt::new(24.0)]);
let edges = prefix_edges(grown.into_iter());
@@ -2043,9 +2023,9 @@ mod tests {
/// §20.1.9.22: a `roundRect`'s text rect is inset by 29.289% of its corner
/// radius — the sagitta of the 45° arc — on every side. With the default
- /// 16.667% adjustment on a 100x100 box that is 4.88pt, and the point of the
- /// test is that it is *neither* zero (the rect's answer) nor the full
- /// 16.667pt radius (what the retired hand-written generator returned).
+ /// 16.667% adjustment on a 100x100 box that is 4.88pt; the point of the
+ /// test is that it is *neither* zero (a plain rect's answer) nor the full
+ /// 16.667pt radius.
#[test]
fn a_round_rect_lays_its_body_out_inside_its_corner_arcs() {
let r = body_rect(
@@ -2074,7 +2054,7 @@ mod tests {
assert_eq!((r.size.width.raw(), r.size.height.raw()), (100.0, 60.0));
}
- /// 886 corpus bodies declare no geometry at all. The schema's default is a
+ /// A body may declare no geometry at all. The schema's default is a
/// rectangle, so the whole box is the right answer and not merely a
/// fallback — laying such a body out in nothing would drop its text.
#[test]
diff --git a/crates/liteparse/src/office/xlsx.rs b/crates/liteparse/src/office/xlsx.rs
index d82f4a4..2d1f3a7 100644
--- a/crates/liteparse/src/office/xlsx.rs
+++ b/crates/liteparse/src/office/xlsx.rs
@@ -1,31 +1,23 @@
//! XLSX → [`Block`], reading the workbook grid directly instead of rendering
-//! it through LibreOffice.
-//!
-//! The conversion path's measured failure is not layout, it is *destruction*:
-//! LibreOffice clips every cell at its rendered column width before the PDF
-//! exists, and emits **zero markdown table rows across 218 corpus workbooks**.
+//! it through LibreOffice (which clips cells at their rendered column width).
//! A workbook states its grid explicitly, so unlike DOCX (no geometry) and
-//! PPTX (reading order), the emitter's job here is mostly to not ruin what the
-//! file already says.
+//! PPTX (reading order), the emitter mostly needs to preserve what the file
+//! already says.
//!
-//! Every rule below that looks arbitrary is a corpus measurement from
-//! `xlsx_emit_census` (1,248 workbooks, 5,439 non-empty visible sheets):
+//! Emission rules:
//!
-//! * **Merges are the common case, not the tail** — 68.9% of sheets carry at
-//! least one, so [`Block::MergedTable`] is the only table variant emitted
-//! and the plain-grid degeneration to a pipe table is the renderer's call.
-//! * **Rows and columns are emitted sparse.** The bbox is a lie at the tail
-//! (a stray cell puts one sheet's bbox at 1,048,576 rows); rows the file
-//! does not write do not become table rows, and columns with no cell
-//! anywhere are compacted out. Nothing a cell says is dropped — only
-//! positions where no cell exists.
-//! * **A leading full-width merge is a title, not a row** — 42.1% of sheets
-//! open with one. Emitting it as a table row buries the sheet's content
-//! title; it becomes a [`Block::Paragraph`] above the table.
-//! * **Hidden sheets and hidden rows are emitted.** They hold 0.66% and
-//! 0.09% of all cells; the text is real, the spreadsheet merely folds it
-//! from view, and an extraction pipeline that silently loses it has no way
-//! to say so. This diverges from what Excel prints on purpose.
+//! * **Merges are common**, so [`Block::MergedTable`] is the only table
+//! variant emitted; the degeneration to a plain pipe table is the
+//! renderer's call.
+//! * **Rows and columns are emitted sparse.** Rows the file does not write do
+//! not become table rows, and columns with no cell anywhere are compacted
+//! out — a stray cell can otherwise put a sheet's bbox at row 1,048,576.
+//! Nothing a cell says is dropped, only positions where no cell exists.
+//! * **A leading full-width merge is a title, not a row**: it becomes a
+//! [`Block::Paragraph`] above the table rather than a buried table row.
+//! * **Hidden sheets and hidden rows are emitted.** The text is real; the
+//! spreadsheet merely folds it from view. This deliberately diverges from
+//! what Excel prints.
//!
//! Cell text goes into [`Cell`] **unescaped**, the same contract as the DOCX
//! and PPTX table emitters: `render_blocks` escapes per dialect (`|` for pipe
@@ -61,9 +53,9 @@ pub(crate) const SHEET_HEADING_LEVEL: u8 = 1;
const BANNER_MIN_WIDTH_FRACTION: f64 = 0.6;
const BANNER_MIN_COLS: usize = 3;
-/// Frozen panes freeze title junk along with the header (the corpus histogram
-/// runs to 19); a freeze deeper than this many *grid* rows stops being a
-/// header declaration and the other signals decide instead.
+/// A freeze deeper than this many grid rows tends to include title junk along
+/// with the header, so it stops being read as a header declaration and the
+/// other signals decide instead.
const FROZEN_HEADER_MAX_ROWS: usize = 5;
/// What the emitter should produce beyond the always-on structure.
@@ -81,9 +73,8 @@ pub struct EmitOptions {
pub images: bool,
/// Paint the grid: fill `NativeXlsx::layouts` with the gridlines, cell
/// fills and cell borders behind the text. Off by default and read only
- /// by `xlsx_layout` — a parse wants `TextItem`s, and painting one corpus
- /// sheet can be a quarter-million rects nobody would look at. The
- /// screenshot path turns it on.
+ /// by `xlsx_layout` — a parse wants `TextItem`s, and painting a sheet can
+ /// be hundreds of thousands of rects. The screenshot path turns it on.
pub paint: bool,
}
@@ -159,10 +150,9 @@ pub fn emit_workbook(wb: &Workbook, opts: EmitOptions) -> NativeWorkbook {
}
/// A sheet's pictures in reading order — sorted by anchor cell, top-left
-/// first, with the (single corpus) absolute anchor sorting after every cell
-/// anchor. This order is the id order: the geometry pass numbers
-/// `s{sheet}_{n}` walking the same list, so a `![](…)` ref and its
-/// `ExtractedImage` cannot disagree.
+/// first, with absolute anchors sorting after every cell anchor. This order
+/// is the id order: the geometry pass numbers `s{sheet}_{n}` walking the same
+/// list, so a `![](…)` ref and its `ExtractedImage` cannot disagree.
pub(crate) fn ordered_pics(sheet: &Sheet) -> Vec<&SheetPic> {
let mut pics: Vec<&SheetPic> = sheet.pics.iter().collect();
pics.sort_by_key(|p| match p.anchor.from_cell() {
@@ -221,17 +211,15 @@ pub fn ordered_shapes(sheet: &Sheet) -> Vec<&SheetShape> {
/// The paragraph blocks for a sheet's floating text shapes, split at the
/// grid: `(before the table, after the table)`.
///
-/// The census (plan doc, floating text-shape entry) measured where shapes
-/// anchor: 33% sit *above* the sheet's first written row, and the eye check
-/// says those are titles and section navigation — emitting them after the
-/// table would bury every title under its own data. Everything else follows
-/// the figures precedent: shapes float *over* the grid, so interleaving with
-/// specific rows would be false precision, and they emit after the table,
-/// before the figure refs.
+/// A shape anchored above the sheet's first written row is treated as a title
+/// and emitted before the table, so it is not buried under its own data.
+/// Everything else follows the figures precedent: shapes float over the grid,
+/// so interleaving with specific rows would be false precision — they emit
+/// after the table, before the figure refs.
///
-/// Census-scoped non-goals: bullets (7 shapes corpus-wide) emit as plain
-/// paragraphs; `a:hlinkClick` (7) keeps its text and drops the link, which
-/// would need the drawing part's rels threaded through the reader.
+/// Non-goals: bullets emit as plain paragraphs; `a:hlinkClick` keeps its text
+/// and drops the link, which would need the drawing part's rels threaded
+/// through the reader.
pub(crate) fn shape_blocks(sheet: &Sheet) -> (Vec<Block>, Vec<Block>) {
let first_row = first_written_row(sheet);
let mut above = Vec::new();
@@ -295,9 +283,8 @@ fn shape_chunks(para: &TextParagraph) -> Vec<Chunk> {
match el {
RunElement::Text(t) => text.push_str(t),
RunElement::Tab => text.push('\t'),
- // `a:br` inside one paragraph; `Block`'s
- // single-line text cannot hold it (the PPTX
- // path's rule, same reason).
+ // `Block`'s single-line text cannot hold an `a:br`,
+ // so it collapses to a space (as on the PPTX path).
RunElement::LineBreak(_) => text.push(' '),
_ => {}
}
@@ -343,18 +330,17 @@ pub(crate) struct SheetPlan<'a> {
/// but §18.3.1.4 does not require it). Banner rows included.
pub(crate) rows: Vec<(&'a Row, Vec<&'a GridCell>)>,
/// Retained columns: every column that holds at least one cell. Wholly
- /// empty columns inside the bbox carry no text and are compacted out —
- /// padding 16,384 pipes onto every row of a sheet whose stray formatting
- /// touched column XFD is the failure this prevents.
+ /// empty columns inside the bbox carry no text and are compacted out, so a
+ /// stray cell in column XFD does not pad every row with 16,384 pipes.
pub(crate) cols: Vec<u32>,
pub(crate) plans: Vec<MergePlan>,
pub(crate) anchors: HashMap<(u32, u32), usize>,
/// Emitted-row index → merges whose clamped range includes that row.
cover: HashMap<u32, Vec<usize>>,
/// Text folded into each merge (pass A): every covered cell's text, the
- /// anchor's own first. A *valued* cell under a neighbour's merge is a
- /// producer bug Excel never writes — folding keeps its text, because
- /// "absorbed" must never mean "silently gone".
+ /// anchor's own first. A valued cell under a neighbour's merge is a
+ /// producer bug Excel never writes; folding keeps its text so "absorbed"
+ /// never means "silently gone".
merge_text: Vec<Vec<String>>,
/// Plan index of each leading banner row, in row order. `len()` is the
/// number of leading rows emitted as paragraphs instead of table rows.
@@ -429,8 +415,7 @@ impl<'a> SheetPlan<'a> {
let max_col = *plan.cols.last().unwrap();
// Plan the merges against the emitted grid. First-wins on a shared
- // anchor: overlapping merges are invalid and Excel repairs them on
- // open.
+ // anchor: overlapping merges are invalid and Excel repairs them.
for m in &sheet.merges {
let Some((p, _rowspan)) = plan_merge(m, &row_indices, &plan.cols, max_row, max_col)
else {
@@ -467,8 +452,8 @@ impl<'a> SheetPlan<'a> {
}
// Banners: leading rows whose every valued cell sits inside one
- // shallow near-full-width merge anchored on that row. 42.1% of sheets
- // open with one; it reads as a title and is emitted as one.
+ // shallow near-full-width merge anchored on that row. Such a row reads
+ // as a title and is emitted as one.
let min_banner_cols =
BANNER_MIN_COLS.max((width as f64 * BANNER_MIN_WIDTH_FRACTION) as usize);
for (row, cells) in &plan.rows {
@@ -695,8 +680,8 @@ impl<'a> SheetPlan<'a> {
/// Clamp a merge to the emitted grid and count its spans in emitted units.
/// `None` means the merge touches no emitted row or retained column and
-/// renders as nothing. The rowspan is returned for the census-facing tests;
-/// emission recounts spans per slice.
+/// renders as nothing. The rowspan is returned for tests; emission recounts
+/// spans per slice.
fn plan_merge(
m: &xlsx::RangeRef,
row_indices: &[u32],
@@ -760,13 +745,12 @@ fn banner_plan(
/// How many leading grid rows are headers.
///
-/// The signals, in order of how explicitly the file states them (census
-/// coverage in parens):
-/// 1. Frozen panes covering 1–5 grid rows (18.8% of sheets freeze, but the
-/// freeze includes banner junk — deeper freezes fall through).
-/// 2. `<autoFilter>` whose range starts on the first grid row (5.0%).
-/// 3. First grid row entirely bold with ≥2 cells (12.7%).
-/// 4. Type transition: first grid row has no numbers, second does (14.3%).
+/// The signals, in order of how explicitly the file states them:
+/// 1. Frozen panes covering 1–[`FROZEN_HEADER_MAX_ROWS`] grid rows (a deeper
+/// freeze includes banner junk and falls through).
+/// 2. `<autoFilter>` whose range starts on the first grid row.
+/// 3. First grid row entirely bold with ≥2 cells.
+/// 4. Type transition: first grid row has no numbers, second does.
fn header_rows(wb: &Workbook, sheet: &Sheet, grid: &[(&Row, Vec<&GridCell>)]) -> usize {
if grid.is_empty() {
return 0;
@@ -904,8 +888,8 @@ pub(crate) mod tests {
assert_eq!(rows[2], vec![Cell::new("3"), Cell::new("4")]);
}
- /// The census: 37.1% of merges anchor on a value-less cell. The span must
- /// still occupy its place, or every row below shifts left.
+ /// A merge can anchor on a value-less cell. The span must still occupy its
+ /// place, or every row below shifts left.
#[test]
fn a_valueless_anchor_still_claims_its_span() {
let blocks = blocks_of(
@@ -947,8 +931,8 @@ pub(crate) mod tests {
assert_eq!(rows[1], vec![Cell::new("3"), Cell::new("")]);
}
- /// The 42.1%: a leading near-full-width shallow merge is a title, emitted
- /// as a paragraph above the table rather than buried as a row.
+ /// A leading near-full-width shallow merge is a title, emitted as a
+ /// paragraph above the table rather than buried as a row.
#[test]
fn a_leading_full_width_merge_is_a_banner_paragraph() {
let blocks = blocks_of(
@@ -1032,8 +1016,8 @@ pub(crate) mod tests {
assert_eq!(header_rows, 1);
}
- /// The corpus freezes run to 19 rows — a freeze that deep is a viewport
- /// choice, not a header declaration, and the other signals decide.
+ /// A very deep freeze is a viewport choice, not a header declaration, so
+ /// the other signals decide.
#[test]
fn a_deep_freeze_is_not_a_header() {
let rows_xml: String = (1..=10)
@@ -1246,8 +1230,8 @@ pub(crate) mod tests {
<row r="4"><c r="A4" t="inlineStr"><is><t>b</t></is></c><c r="B4"><v>2</v></c></row>
</sheetData><drawing r:id="rId7"/></worksheet>"#;
- /// The census's placement rule: a shape anchored above the first written
- /// row is a title and must not be buried under its own table.
+ /// A shape anchored above the first written row is a title and must not be
+ /// buried under its own table.
#[test]
fn a_shape_above_the_grid_emits_before_the_table() {
let blocks = shape_blocks_of(
@@ -1276,8 +1260,8 @@ pub(crate) mod tests {
);
}
- /// 54 corpus shapes sit on sheets with no written cells — today those
- /// sheets emit nothing at all; the shape is the sheet's only content.
+ /// A shape can sit on a sheet with no written cells, where it is the
+ /// sheet's only content.
#[test]
fn a_shape_on_an_empty_sheet_is_its_only_content() {
let blocks = shape_blocks_of(
diff --git a/crates/liteparse/src/office/xlsx_layout.rs b/crates/liteparse/src/office/xlsx_layout.rs
index a6b1a40..c5676b2 100644
--- a/crates/liteparse/src/office/xlsx_layout.rs
+++ b/crates/liteparse/src/office/xlsx_layout.rs
@@ -3,33 +3,27 @@
//! Unlike DOCX (a layout engine) and PPTX (a cascade), XLSX geometry is
//! *stated*: the file declares every column width and row height, so this
//! pass is unit conversion plus pagination — no fonts, no measurement, no
-//! host dependence. Every constant traces to `xlsx_geometry_census` over the
-//! 1,248-workbook corpus.
+//! host dependence.
//!
-//! The **paint** built on top of it does measure, and that is a deliberate
-//! divergence between the two consumers of one read rather than a crack in
-//! the claim above: a raster has to decide where a glyph lands and where a
-//! string stops, and a `TextItem` does not. Nothing the measurer returns
+//! The **paint** built on top of it does measure, but that stays a private
+//! detail of the raster: a raster has to decide where a glyph lands and where
+//! a string stops, and a `TextItem` does not. Nothing the measurer returns
//! reaches a [`Page`] — the items are byte-identical with and without a font
-//! registry, and a test says so. Constants:
+//! registry (a test enforces this). Rules:
//!
//! * **Packed, not canvas.** Item positions honour the emitted grid (rows
//! the file wrote, columns holding at least one cell), the same sparse
-//! rule as the emitter. Honouring declared positions instead puts one
-//! sheet's canvas at 16,777,274 pt tall (a stray cell on row 1,048,576);
-//! packed and canvas differ by >2× on only 256 of 5,606 sheets.
-//! * **Pages are Letter-height, content-width.** At 792 pt, 49% of sheets
-//! paginate (a sheet is not a page: the corpus median workbook is 4 pages,
-//! the largest 6,612) — but 67.5% of sheets are *wider* than Letter, so
-//! width is never split: the page takes the content's width and a
-//! downstream consumer sees an unclipped row, which is the native path's
-//! whole advantage over LibreOffice.
-//! * **Geometry inputs are declared, not guessed**: 100% of sheets state
-//! `defaultRowHeight`, 97% of retained columns have a declared width. The
-//! 8.43-unit / 15 pt fallbacks carry the remainder.
-//! * **A merge cut by a page break** (1.05% of merges) keeps its item on the
-//! anchor's page, clamped to that page's rows — mirroring the block
-//! slicer, where the continuation is an empty spanning cell.
+//! rule as the emitter. Honouring declared positions instead can put a
+//! sheet's canvas millions of points tall (a stray cell on row 1,048,576).
+//! * **Pages are Letter-height, content-width.** Rows paginate at 792 pt, but
+//! width is never split: the page takes the content's width so a downstream
+//! consumer sees an unclipped row, which is the native path's advantage
+//! over LibreOffice.
+//! * **Geometry inputs are declared, not guessed.** The 8.43-unit column /
+//! 15 pt row fallbacks carry the few cells that state nothing.
+//! * **A merge cut by a page break** keeps its item on the anchor's page,
+//! clamped to that page's rows — mirroring the block slicer, where the
+//! continuation is an empty spanning cell.
//!
//! An item's rectangle is the **cell box** (inset by the cell padding the
//! pixel formula bakes in), not a measured text box: the file states no
@@ -69,8 +63,7 @@ use crate::types::{ExtractedImage, OutlineTarget, Page, Rect, TextItem};
const MDW: f64 = 7.0;
const PAD_PX: f64 = 5.0;
const PX_TO_PT: f64 = 72.0 / 96.0;
-/// Excel's fallbacks when the file declares nothing (3% of retained columns,
-/// 0% of corpus sheets for row height).
+/// Excel's fallbacks when the file declares no width or height.
const DEFAULT_COL_WIDTH: f64 = 8.43;
const DEFAULT_ROW_HEIGHT_PT: f64 = 15.0;
@@ -87,8 +80,8 @@ const MIN_PAGE_WIDTH: f32 = 612.0;
const TEXT_INSET: f32 = (PAD_PX / 2.0 * PX_TO_PT) as f32;
/// Excel's gridline grey, and one device pixel of it at 96 DPI. Gridlines are
-/// not decoration: 12.1% of corpus sheets declare neither a fill nor a border
-/// anywhere, so this is the only ink holding their numbers in a grid.
+/// not decoration: a sheet that declares neither a fill nor a border anywhere
+/// has only these lines holding its numbers in a grid.
const GRIDLINE_COLOR: RgbColor = RgbColor {
r: 0xD0,
g: 0xD7,
@@ -133,8 +126,7 @@ pub struct NativeXlsx {
/// — the same contract the picture ordinal carries.
///
/// The rectangle is the shape's box, which is *not* where its text is:
- /// the items inside it are stacked evenly rather than laid out. That gap
- /// is what this field exists to let a census measure.
+ /// the items inside it are stacked evenly rather than laid out.
pub shape_rects: Vec<(usize, Rect)>,
/// The paint of each page, aligned with `pages`: gridlines, cell fills
/// and cell borders as [`DrawCommand::Rect`]s, then the cell text as
@@ -145,12 +137,12 @@ pub struct NativeXlsx {
///
/// Command order carries no z-order here: the rasterizer paints in fixed
/// passes (`Path` → `Rect` → `Image` → ink), so a picture always covers
- /// the grid beneath it and cell text always covers the picture. Excel
- /// floats a picture above cell text, so that last relation is inverted —
- /// see the overlap census for how often it can be seen.
+ /// the grid beneath it and cell text always covers the picture. A picture
+ /// with `float: true` overrides that so it draws above cell text, matching
+ /// Excel.
pub layouts: Vec<LayoutedPage>,
/// What the text pass met, summed over the workbook. Zero when nothing
- /// was painted; read by the corpus gate, not by `parser.rs`.
+ /// was painted; read by the corpus recall gate, not by `parser.rs`.
pub text_stats: TextPaintStats,
}
@@ -449,8 +441,8 @@ pub fn workbook_to_pages(
src_rect: None,
// Excel floats a picture above the grid *and* its values,
// so this is the one producer that opts out of the
- // painter's flow order — without it 29.2% of corpus
- // placements have cell text drawn through them.
+ // painter's flow order; otherwise cell text draws through
+ // the picture.
float: true,
});
}
@@ -512,14 +504,13 @@ pub fn workbook_to_pages(
// content is a picture — or a shape — has no grid to paint
// and still has something to draw.
//
- // The floating drawing layer, in Excel's z-order: shape
- // fills and outlines, then shape text, both bracketed into
- // the rasterizer's `Float` pass so they draw over the grid
- // *and* the cell values (the same relation pictures already
- // claim via their flag), then the pictures on top. Within
- // the layer the approximation is the PPTX painter's: all
- // fills before all text, so an overlapping shape's box never
- // covers a neighbour's words.
+ // The floating drawing layer, in Excel's z-order: shape fills
+ // and outlines, then shape text, both wrapped in a `Float`
+ // bracket so they draw over the grid *and* the cell values
+ // (the same relation pictures claim via their flag), then the
+ // pictures on top. Within the layer all fills paint before all
+ // text, so an overlapping shape's box never covers a
+ // neighbour's words.
use liteparse_ooxml::render::layout::draw_command::FloatMark;
if !ink_cmds_per_page[i].is_empty() {
layout.commands.push(DrawCommand::Float(FloatMark::Begin));
@@ -546,9 +537,8 @@ pub fn workbook_to_pages(
/// One `TextItem` per non-empty shape paragraph, stacked evenly inside the
/// shape's box — the same fidelity contract as a cell's item (the box is
/// real, the intra-box line layout is not attempted). Font facts come from
-/// the paragraph's first run: 99.5% of corpus shape runs declare `sz`, and a
-/// theme-referenced face (no explicit name) stays `None` like an unstyled
-/// cell would.
+/// the paragraph's first run; a theme-referenced face (no explicit name)
+/// stays `None` like an unstyled cell would.
fn shape_text_items(shape: &SheetShape, rect: &Rect, out: &mut Vec<TextItem>) {
let paras: Vec<&liteparse_ooxml::pptx::TextParagraph> = shape
.body
@@ -589,30 +579,22 @@ fn shape_text_items(shape: &SheetShape, rect: &Rect, out: &mut Vec<TextItem>) {
/// One floating text shape's body as page-absolute [`DrawCommand`]s.
///
-/// This is the *paint* half of a shape, and it is a real §20.1.10.60
-/// sub-layout — the same [`layout_shape_body`] the PPTX shape and DOCX
-/// textbox paths use, so insets, measured wrapping, `a:pPr/@algn`, the
-/// anchor and `@vertOverflow` all apply. The `TextItem`s beside it stay the
-/// even stack `shape_text_items` builds, and the two deliberately disagree
-/// about where a *line* falls inside the box.
+/// This is the *paint* half of a shape: a real §20.1.10.60 sub-layout via the
+/// same [`layout_shape_body`] the PPTX shape and DOCX textbox paths use, so
+/// insets, measured wrapping, `a:pPr/@algn`, the anchor and `@vertOverflow`
+/// all apply. The `TextItem`s beside it stay the even stack
+/// `shape_text_items` builds, and the two deliberately disagree about where a
+/// *line* falls inside the box.
///
-/// That split is the same one the cell path already makes — an item is the
-/// cell box, the painted glyphs are measured inside it — and it is what keeps
-/// this module's host-independence claim intact: items come from declared
-/// geometry and need no registry, paint measures and does. Feeding items from
-/// the layout instead would make a plain parse depend on the host's fonts for
-/// 154 corpus workbooks, which is a far larger price than the disagreement.
+/// That split is the same one the cell path makes — an item is the box, the
+/// painted glyphs are measured inside it — and it keeps items host-independent:
+/// they come from declared geometry and need no font registry, while paint
+/// measures and does. Feeding items from the layout instead would make a plain
+/// parse depend on the host's fonts.
///
-/// The layout census (1,637 shapes) is what bought the sub-layout rather than
-/// painting the stack: 61.5% anchor non-top, 34.8% of paragraphs wrap (2.29x
-/// the line count the stack draws), 51.1% declare an alignment the stack
-/// cannot express, and the first line moves by more than 24pt on 19.2% of
-/// shapes.
-///
-/// Run colour and theme faces resolve against the workbook's full `Theme` —
-/// the shape-visuals census measured 5,041 of 5,902 runs declaring a colour,
-/// 52% of them `schemeClr`, which is what made keeping the whole theme (not
-/// just its colour scheme) worth it.
+/// Run colour and theme faces resolve against the workbook's full `Theme`
+/// (not just its colour scheme), because a shape run's colour is often a
+/// `schemeClr` reference.
fn shape_commands(
shape: &SheetShape,
rect: &Rect,
@@ -628,10 +610,9 @@ fn shape_commands(
let body_pr = shape.body.body_pr.as_ref();
let auto_fit = ShapeAutoFit::from_body(body_pr.and_then(|b| b.auto_fit));
- // Rung 3 only. A sheet shape has no layout, master or deck above it, so
- // the cascade's other rungs are genuinely absent rather than unwired —
- // and rung 2 (the paragraph's own `a:pPr`) plus the spec default is what
- // `resolve` seeds itself with.
+ // A sheet shape has no layout, master or deck above it, so only the
+ // shape's own list style is supplied; the paragraph's `a:pPr` and the spec
+ // default are what `resolve` seeds itself with.
let cascade = TextCascade {
shape: Some(&shape.body.list_style),
layout: None,
@@ -667,15 +648,13 @@ fn shape_commands(
});
}
- // The insets cliff. `layout_shape_body` returns *nothing* when the left
- // and right insets leave no width to wrap in, and the §20.1.2.1.1
- // defaults are 7.2pt a side — so every shape narrower than 14.4pt paints
- // empty. That is **6.5% of corpus shapes (106)**, and they are not
- // decorative: they are the narrow vertical marker labels a timeline is
- // made of. Excel draws them, overflowing the box rather than vanishing,
- // so the horizontal insets are dropped for exactly those shapes. The
- // clamp lives here rather than in the shared sub-layout because it is a
- // statement about this producer's boxes, not about §20.1.10.60.
+ // `layout_shape_body` returns nothing when the left and right insets leave
+ // no width to wrap in, and the §20.1.2.1.1 defaults are 7.2pt a side — so
+ // a shape narrower than 14.4pt would paint empty. Excel draws such a shape,
+ // overflowing the box rather than vanishing, so the horizontal insets are
+ // dropped for exactly those shapes. The clamp lives here rather than in the
+ // shared sub-layout because it is about this producer's boxes, not about
+ // §20.1.10.60.
let extent = PtSize::new(Pt::new(rect.width), Pt::new(rect.height));
let squeezed = BodyInsets::resolve(body_pr).content_width(extent) <= Pt::ZERO;
let unsqueezed;
@@ -733,12 +712,10 @@ impl AnchorMap {
target: &Rect,
) -> Option<Self> {
let (bw, bh) = (base.size.width.raw() as f64, base.size.height.raw() as f64);
- // A box that is zero in *both* axes is a point — 540 corpus shapes,
- // one workbook, all legacy `Line NNN` leftovers — and a point has no
- // ink. A box that is zero in *one* axis is a flat line (every
- // horizontal connector declares `cy="0"`), and Excel draws those:
- // the degenerate axis collapses (scale 0) instead of vetoing the
- // whole tree.
+ // A box zero in *both* axes is a point and has no ink. A box zero in
+ // *one* axis is a flat line (every horizontal connector declares
+ // `cy="0"`), which Excel draws: the degenerate axis collapses
+ // (scale 0) instead of vetoing the whole tree.
if bw <= 0.0 && bh <= 0.0 {
return None;
}
@@ -798,10 +775,10 @@ fn ink_commands(
match root.slide_rect {
Some(sr) => {
// The anchor covers the object as *seen* — its rotated bounding
- // box, not its unrotated rect. 88 corpus shapes are vertical
- // lines rotated a quarter turn into horizontal ones, whose
- // unrotated rect is zero-width; scaling through it collapses
- // them, scaling through the bounding box does not.
+ // box, not its unrotated rect. A vertical line rotated a quarter
+ // turn into a horizontal one has a zero-width unrotated rect;
+ // scaling through it collapses the line, scaling through the
+ // bounding box does not.
let Some(map) = AnchorMap::new(sr.bounding_box(), rect) else {
return;
};
@@ -948,8 +925,8 @@ fn paint_ink_shape(
style.and_then(|s| s.effect_ref.as_ref()),
style.and_then(|s| s.fill_ref.as_ref()),
ctx,
- // No `PartMedia`: a blip fill on an XLSX shape (4 on the corpus)
- // resolves to nothing and the shape paints its outline alone.
+ // No `PartMedia`: a blip fill on an XLSX shape resolves to nothing and
+ // the shape paints its outline alone.
None,
group_fill,
);
@@ -1047,9 +1024,7 @@ fn shape_fragments(
/// A shape run's declared colour, resolved against the workbook's theme —
/// the XLSX twin of the PPTX path's `run_color`, minus the `p:clrMap` (a
-/// workbook has no master to remap `bg1`/`tx1` through) and minus the
-/// counters (the corpus census already sized both branches: 5,041 of 5,902
-/// runs declare, 52% of them `schemeClr`).
+/// workbook has no master to remap `bg1`/`tx1` through).
///
/// Alpha is dropped, as it is on the PPTX side: `DrawCommand::Text` carries
/// an opaque colour, and solid is a smaller error than the black it
@@ -1150,8 +1125,7 @@ fn fill_split_of(
/// Blending is also what makes a hatch safe to paint at all: slot 1 of every
/// styles part is `gray125` with a black `fg` — Excel's "no fill" placeholder
/// — and at 12.5% coverage it lands as the light grey Excel shows rather than
-/// the black a solid reading would give it. 323 corpus cells are hatched, 210
-/// of them `gray0625`.
+/// the black a solid reading would give it.
fn fill_color(wb: &Workbook, fill: &liteparse_ooxml::xlsx::Fill) -> Option<RgbColor> {
let fg = fill.fg.and_then(|c| wb.resolve_color(c))?;
match fill.pattern {
@@ -1184,7 +1158,7 @@ fn fill_color(wb: &Workbook, fill: &liteparse_ooxml::xlsx::Fill) -> Option<RgbCo
///
/// Value-less styled cells come from the paint side-channel and are treated
/// exactly like a cell's own `s=`; the ones on columns the packed grid
-/// compacted out are dropped here (class C's column half).
+/// compacted out are dropped here.
fn row_paint_styles(
row: &Row,
cells: &[&liteparse_ooxml::xlsx::Cell],
@@ -1293,13 +1267,12 @@ fn push_border(
/// `pen` one stroke's thickness; `horizontal` says which way the edge runs.
/// Three shapes come out of here:
///
-/// * a continuous edge is one rect — the shape every edge had before;
+/// * a continuous edge is one rect;
/// * a `double` edge is two pens with a pen-wide gap, filling the band
-/// [`BorderStyle::extent_pt`] reserves for it. 27,300 corpus edges, more
-/// than every broken style put together;
+/// [`BorderStyle::extent_pt`] reserves for it;
/// * a broken edge is one rect per "on" run of
/// [`BorderStyle::dash_pattern`], the last clipped to the cell rather than
-/// allowed to overhang it. 14,094 corpus edges.
+/// allowed to overhang it.
///
/// The dash phase restarts at each cell, so a row of dashed cells shows a
/// stroke at every boundary rather than one pattern running across it. Excel
@@ -1318,11 +1291,10 @@ fn push_edge(
let c = color(edge);
// One stroke: `at` runs along the edge, `off` across it.
//
- // A zero-*length* run still paints, and the corpus insists on it: a hidden
- // column is a retained column of zero width, and its cells' horizontal
- // edges were zero-area rects before this walk existed. Dropping them looks
- // like a tidy-up and is a silent 1,230-rect change on one corpus sheet.
- // Only a negative run — which the dash walk cannot produce — is skipped.
+ // A zero-*length* run still paints: a hidden column is a retained column
+ // of zero width, and its cells' horizontal edges are zero-area rects that
+ // must not be dropped. Only a negative run — which the dash walk cannot
+ // produce — is skipped.
let mut stroke = |at: f64, run: f64, off: f64| {
if run < 0.0 {
return;
@@ -1362,13 +1334,10 @@ fn push_edge(
/// The cell's diagonal, as one stroked line per declared direction.
///
-/// A `Line` rather than a `Rect` because a rect cannot express a diagonal —
-/// and the recorded objection to `Line`, that it "paints in the Ink pass, over
-/// everything", is only half right. It does paint over the fills and borders,
-/// which is where a diagonal belongs; and it paints *under* the cell's text so
-/// long as it is emitted before it, which the paint walk does. The whole class
-/// is **2 corpus edges in 1 workbook**, and it is here because the note
-/// explaining its absence was longer than the code.
+/// A `Line` rather than a `Rect` because a rect cannot express a diagonal. It
+/// paints in the Ink pass, over the fills and borders (where a diagonal
+/// belongs) but under the cell's text, so long as it is emitted before the
+/// text — which the paint walk does.
fn push_diagonal(
out: &mut Vec<DrawCommand>,
wb: &Workbook,
@@ -1416,20 +1385,18 @@ const DEFAULT_FONT_SIZE: f32 = 11.0;
/// §18.8.1: one `indent` step is three characters' worth of the cell's font.
const INDENT_STEP: &str = " ";
-/// What the text pass did with the overflow it met, per the four rules Excel
-/// applies — the counters the corpus gate reads back against the paint
-/// census's independent predictions (12.8% clipped, 6.1% spilled, 2.0%
-/// hashed, 6.9% wrapped).
+/// What the text pass did with the overflow it met, per Excel's overflow
+/// rules. Counters the corpus recall gate reads back; not consumed by
+/// `parser.rs`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextPaintStats {
/// Cells that painted at least one line.
pub cells: u64,
/// Cells with text that painted nothing: the fit left no character at
/// all, which is a hidden (zero-width) column or a number in a column too
- /// narrow for one `#`. Named rather than silent — `cells + blank` is what
- /// the recall oracle must equal.
+ /// narrow for one `#`. Tracked so `cells + blank` covers every text cell.
pub blank: u64,
- /// Cells whose style declares `wrapText`. The census's denominator.
+ /// Cells whose style declares `wrapText`.
pub wrap_declared: u64,
/// Cells whose text actually broke over more than one line — a declared
/// wrap on a string that fits does not.
@@ -1438,9 +1405,9 @@ pub struct TextPaintStats {
pub spilled: u64,
/// Overflowing cells whose *declared* right neighbour is unwritten but
/// whose *packed* one is not: the spill Excel would do and this pass
- /// cannot, because the empty column between them is compacted out of the
- /// page. The size of the one divergence between this pass's grid and
- /// Excel's that the text rules can see.
+ /// cannot, because the empty column between them is compacted out. This is
+ /// the one divergence between this pass's grid and Excel's that the text
+ /// rules can see.
pub spill_lost_to_packing: u64,
/// Cells whose text was cut because the room ran out.
pub clipped: u64,
@@ -1593,28 +1560,6 @@ fn occupied_columns(
occupied
}
-/// One cell's text as [`DrawCommand::Text`]s, one per line.
-///
-/// The rules are Excel's, and each carries the census number that justified
-/// building it (paint census, 1,247 workbooks):
-///
-/// * **`wrapText` or an embedded newline** (6.9% + 76,952 cells) breaks over
-/// lines inside the box.
-/// * **Text wider than its box spills** into the run of empty neighbours in
-/// the direction its alignment points (6.1% of unwrapped text cells), and is
-/// **clipped** where a written neighbour stops it (12.8%) — the case a
-/// painter that just draws the string at its origin turns into overlapping
-/// mush.
-/// * **A number wider than its column becomes `#######`** (2.0% of unwrapped
-/// numeric cells). Numbers never spill; that is Excel's rule, not a
-/// simplification.
-/// * **`General` is "numbers right, text left"** — the alignment nobody
-/// declares, and the reason a spreadsheet reads as a table.
-///
-/// The clip is at a character boundary rather than mid-glyph: the command
-/// stream has no clip bracket, and adding one to paint half a glyph would put
-/// a variant in front of every consumer that matches on `DrawCommand`.
-#[allow(clippy::too_many_arguments)]
/// One line of a cell's text, placed on its baseline in page coordinates.
fn text_cmd(line: &str, fp: &FontProps, color: RgbColor, x: f64, baseline: f64) -> DrawCommand {
DrawCommand::Text {
@@ -1633,6 +1578,20 @@ fn text_cmd(line: &str, fp: &FontProps, color: RgbColor, x: f64, baseline: f64)
}
}
+/// One cell's text as [`DrawCommand::Text`]s, one per line, per Excel's rules:
+///
+/// * **`wrapText` or an embedded newline** breaks over lines inside the box.
+/// * **Text wider than its box spills** into the run of empty neighbours in
+/// the direction its alignment points, and is **clipped** where a written
+/// neighbour stops it.
+/// * **A number wider than its column becomes `#######`**. Numbers never
+/// spill; that is Excel's rule, not a simplification.
+/// * **`General` is "numbers right, text left"** — the alignment nobody
+/// declares, and the reason a spreadsheet reads as a table.
+///
+/// The clip is at a character boundary rather than mid-glyph: the command
+/// stream has no clip bracket, and adding one to paint half a glyph would put
+/// a variant in front of every consumer that matches on `DrawCommand`.
#[allow(clippy::too_many_arguments)]
fn paint_cell_text(
out: &mut Vec<DrawCommand>,
@@ -1783,12 +1742,10 @@ fn paint_cell_text(
/// One attribute with three meanings: `1..=90` is degrees **counter-clockwise**,
/// `91..=180` is `value - 90` degrees **clockwise**, and `255` is not a
/// rotation at all — it is Excel's *stacked* text, upright glyphs one under the
-/// next. Paint census, 1,247 workbooks / 1,902 rotated cells, and the corpus
-/// declares only five values: 951 at `90`, 40 at `180`, 184 at `60`, 48 at
-/// `45`, 679 stacked.
+/// next.
#[derive(Clone, Copy, Debug, PartialEq)]
enum CellRotation {
- /// No rotation, and 99.994% of text cells.
+ /// No rotation; the overwhelming majority of text cells.
None,
/// Degrees counter-clockwise from the cell's own baseline; negative for
/// the `91..=180` clockwise spellings.
@@ -1815,9 +1772,9 @@ fn cell_rotation(align: &Alignment) -> CellRotation {
/// A `W × H` box laid along θ covers `W·|cos θ| + H·|sin θ|` of the cell's
/// width and `W·|sin θ| + H·|cos θ|` of its height, so a quarter turn may run
/// the cell's whole *height* and an oblique angle gets whichever of the two
-/// constraints binds first. `H` is one line, which is what the corpus's angled
-/// cells are: a rotated header is a single string, and wrapping and *then*
-/// rotating would need the line count before the length that decides it.
+/// constraints binds first. `H` is one line: a rotated header is a single
+/// string, and wrapping and *then* rotating would need the line count before
+/// the length that decides it.
fn rotated_run_length(theta_deg: f64, b: &CellBox, line_h: f64) -> f64 {
let (s, c) = theta_deg.to_radians().sin_cos();
let (s, c) = (s.abs(), c.abs());
@@ -1867,18 +1824,16 @@ fn block_bounds(
/// shared painter with [`MARGIN`] already in them and are shifted off it, which
/// is cheaper than teaching every `text_cmd` call site a second origin.
///
-/// **Alignment does not rotate with the text, and that is measured rather than
-/// assumed.** The obvious model — the alignment frame turns with the glyphs, so
-/// a 90° cell's `horizontal` runs up the column — is wrong: rendering a probe
-/// workbook of every rotation × `vertical` × `horizontal` combination through
-/// LibreOffice puts `horizontal` on the page's x axis and `vertical` on its y
-/// axis at every angle, quarter turn included. So the text is laid out flush,
-/// its finished block is measured, and *the block's upright bounding box* is
-/// what the two alignments place inside the cell's inset rect. Centre-on-centre
-/// then does the rest: `place_transform` turns the local box about its own
-/// centre before translating, so putting the local centre on the bounding box's
-/// centre lands the rotated block exactly where the alignment put it, at any
-/// angle and with no case split per quadrant.
+/// **Alignment does not rotate with the text**: Excel keeps `horizontal` on
+/// the page's x axis and `vertical` on its y axis at every angle, quarter turn
+/// included — not the intuitive model where a 90° cell's `horizontal` runs up
+/// the column. So the text is laid out flush, its finished block is measured,
+/// and *the block's upright bounding box* is what the two alignments place
+/// inside the cell's inset rect. Centre-on-centre then does the rest:
+/// `place_transform` turns the local box about its own centre before
+/// translating, so putting the local centre on the bounding box's centre lands
+/// the rotated block where the alignment put it, at any angle and with no case
+/// split per quadrant.
///
/// **A rotated cell does not spill**: Excel keeps angled text inside its own
/// cell, so the room the flat path would grow into is passed as zero and the
@@ -1942,9 +1897,9 @@ fn paint_rotated_cell_text(
// spoken for — the same two constraints `rotated_run_length` solves, read
// the other way round. A wrapped cell is the only one that can exceed it,
// and a quarter-turned one that did would run its lines out across the
- // whole sheet rather than down its own column: 3 corpus cells wrap on an
- // 8 pt column. Lines past it are cut, which is the cross-axis twin of the
- // clip the flat path applies along the baseline.
+ // whole sheet rather than down its own column. Lines past it are cut,
+ // which is the cross-axis twin of the clip the flat path applies along the
+ // baseline.
let (s, c) = theta_deg.to_radians().sin_cos();
let (s, c) = (s.abs(), c.abs());
let cross_max = if c < 1e-9 {
@@ -2026,7 +1981,7 @@ fn paint_rotated_cell_text(
/// is expressed as one: the string becomes one character per line and the flat
/// painter lays it out, which is what keeps the alignment, the font and the
/// vertical placement the cell's own. Excel breaks between characters, not
-/// grapheme clusters, and every stacked cell in the corpus is ASCII.
+/// grapheme clusters.
///
/// The lines are cut to what the row is tall enough to hold, the vertical twin
/// of the horizontal clip: 40 stacked glyphs in a 15 pt row would otherwise
@@ -2167,12 +2122,11 @@ impl SheetGeometry {
/// page.
///
/// Position is packed, **extent is canvas**: a two-cell anchor's corners
- /// are measured over the *declared* grid (`canvas`), because the corpus
- /// says the packed difference is a lie — 818 of 2,126 pictures anchor
+ /// are measured over the *declared* grid (`canvas`). Many pictures anchor
/// across rows or columns the packed grid does not have (a logo floating
- /// right of the data, a photo below the table) and collapse to 1 pt
- /// slivers under a packed reading. The top-left still snaps to the
- /// packed corner so the picture sits next to the text it belongs with.
+ /// right of the data, a photo below the table) and would collapse to 1 pt
+ /// slivers under a packed reading. The top-left still snaps to the packed
+ /// corner so the picture sits next to the text it belongs with.
fn place_pic(
&self,
cols: &[u32],
@@ -2243,8 +2197,8 @@ impl SheetGeometry {
}
/// Greedy pagination over emitted rows: break before the row that would
- /// overflow the page, never breaking an empty page (a row taller than
- /// the page — the corpus max is 410 pt — gets a page to itself).
+ /// overflow the page, never breaking an empty page (a row taller than the
+ /// page gets a page to itself).
fn page_ranges(&self) -> Vec<Range<usize>> {
let n = self.y_off.len() - 1;
let mut ranges = Vec::new();
@@ -2263,35 +2217,24 @@ impl SheetGeometry {
ranges
}
- /// One page's paint: gridlines under fills under borders, every one of
- /// them a [`DrawCommand::Rect`] so the raster's Shading pass keeps them in
+ /// One page's paint: gridlines under fills under borders, each a
+ /// [`DrawCommand::Rect`] so the raster's Shading pass keeps them in
/// emission order (its pass order is fixed — `Path` < `Rect` < `Image` <
- /// `Line`/`Text` — so three variants would be three *layers*, in the wrong
- /// sequence).
- ///
- /// The population is the census's classes A + B + D + E: valued cells,
- /// the value-less styled cells the reader keeps in [`Row::styled_blanks`],
- /// `<row customFormat>` and `<col style>`. That is 15.9% of all declared
- /// paint on top of the 42.4% a valued-cells-only painter sees, and every
- /// unit of it lands on a cell box the geometry pass has already placed —
- /// no page changes size, no `TextItem` moves. Class C (paint on cells
- /// outside the packed grid, 41.7%) is dropped by design: honouring it
- /// means inventing the rows and columns to hang it on, which is the canvas
- /// explosion this pass exists to prevent, and Excel does not print it
- /// either.
+ /// `Line`/`Text`). Diagonals are the exception: a `Rect` cannot express
+ /// one, so they are `Line`s in the Ink pass.
///
- /// Three approximations, each with its number:
+ /// The painted population is valued cells plus the value-less styled cells
+ /// the reader keeps in [`Row::styled_blanks`], `<row customFormat>` and
+ /// `<col style>`. Each lands on a cell box the geometry pass already
+ /// placed, so no page changes size and no `TextItem` moves. Paint on cells
+ /// outside the packed grid is dropped: honouring it means inventing the
+ /// rows and columns to hang it on (the canvas explosion this pass exists
+ /// to prevent), and Excel does not print it either.
///
- /// * **Only `solid` fills paint.** 100.0% of filled corpus cells are
- /// solid; the hatch branch is skipped rather than approximated because
- /// slot 1 of every styles part is `gray125` — Excel's "no fill"
- /// placeholder, usually with a black `fg` — and painting it solid would
- /// black out sheets that asked for nothing.
- /// * **Dashed edges paint solid** (0.2% of edges), the same trade
- /// [`BorderStyle`](liteparse_ooxml::xlsx::BorderStyle) already made by
- /// keeping the full enum rather than mapping the tail to `None`.
- /// * **Diagonals are not drawn**: a `Rect` cannot express one, and the
- /// variant that could (`Line`) paints in the Ink pass, over everything.
+ /// A solid fill paints its colour; a hatch paints its coverage blend (see
+ /// [`fill_color`]); gradient and no-fill paint nothing. An automatic `fg`
+ /// is the consumer's background and is not painted, so it does not cover
+ /// the gridlines it sits on.
///
/// Merged regions paint per cell rather than as one box. Excel writes the
/// covered cells with the merge's own style, so the fill is right; the
@@ -2916,10 +2859,10 @@ mod tests {
);
}
- /// The census's classes B, D and E — the 15.9% of declared paint that a
- /// valued-cells-only painter cannot see. A styled blank paints its own
- /// cell, `<row customFormat>` paints the row's retained columns, and
- /// `<col style>` paints its span; the cascade is cell > row > column.
+ /// Paint that a valued-cells-only painter cannot see: a styled blank
+ /// paints its own cell, `<row customFormat>` paints the row's retained
+ /// columns, and `<col style>` paints its span; the cascade is
+ /// cell > row > column.
#[test]
fn blanks_and_row_and_column_formats_all_paint() {
let nx = painted(
@@ -2931,10 +2874,9 @@ mod tests {
</sheetData></worksheet>"#,
);
let r = rects(&nx.layouts[0]);
- // Row 1: A1 takes the column's blue (class E), B1's own style wins and
- // is the `gray125` placeholder, which blends rather than covering
- // (class B). Row 2: the row's yellow on both columns (class D), with
- // B2's own blue overriding it.
+ // Row 1: A1 takes the column's blue, B1's own style wins and is the
+ // `gray125` placeholder, which blends rather than covering. Row 2: the
+ // row's yellow on both columns, with B2's own blue overriding it.
assert_eq!(r.len(), 4, "{r:?}");
assert_eq!((r[0].1, r[0].4), (MARGIN, BLUE));
assert!((r[0].2 - 56.25).abs() < 1e-4, "the column's own width");
@@ -3014,8 +2956,7 @@ mod tests {
}
/// `double` is two strokes and a gap, filling the three-pen band
- /// `extent_pt` reserves — not one thin line, which is what 27,300 corpus
- /// edges were painted as before.
+ /// `extent_pt` reserves — not one thin line.
#[test]
fn a_double_edge_paints_two_strokes_with_a_gap() {
let nx = one_cell(2);
@@ -3413,8 +3354,8 @@ mod tests {
}
/// The doc-level block stream from the geometry pass must equal the
- /// emitter's, figures included — the emitter is what the corpus gates
- /// score, and the CLI ships the geometry pass's.
+ /// emitter's, figures included — the two share one plan, and the CLI ships
+ /// the geometry pass's.
#[test]
fn doc_blocks_match_the_emitter_with_figures_on() {
let sheet = r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>
@@ -3662,9 +3603,8 @@ mod tests {
.collect()
}
- /// The carrier gap closed: a textless filled rectangle — dropped by the
- /// text channel, invisible before this step — paints as a `Path` in a
- /// `Float` bracket, and the item stream never hears about it.
+ /// A textless filled rectangle — dropped by the text channel — paints as a
+ /// `Path` in a `Float` bracket, and the item stream never hears about it.
#[test]
fn a_textless_filled_shape_paints_a_path_and_adds_no_item() {
let anchor = r#"<xdr:oneCellAnchor>
@@ -3711,9 +3651,9 @@ mod tests {
}
/// A grouped child paints in its share of the anchor box: the group's
- /// `chOff`/`chExt` map the child's declared quarter onto a quarter of
- /// the page rect. 3,547 corpus inked shapes are inside a group; without
- /// this mapping every one of them would smear across the full anchor.
+ /// `chOff`/`chExt` map the child's declared quarter onto a quarter of the
+ /// page rect. Without this mapping a grouped shape smears across the full
+ /// anchor.
#[test]
fn a_grouped_child_paints_in_its_share_of_the_anchor_box() {
let anchor = r#"<xdr:oneCellAnchor>
@@ -3770,8 +3710,7 @@ mod tests {
}
/// A flat line — every horizontal connector declares `cy="0"` — still
- /// strokes; a zero-extent *point* (540 corpus shapes, all legacy
- /// `Line NNN` leftovers) paints nothing.
+ /// strokes; a zero-extent *point* paints nothing.
#[test]
fn a_flat_line_strokes_and_a_point_does_not() {
let line = |ext: &str| {
@@ -3799,9 +3738,9 @@ mod tests {
);
}
- /// A vertical line rotated a quarter turn into a horizontal one — 88
- /// corpus shapes — still paints: its unrotated rect is zero-width, and
- /// only the rotated *bounding box* meaningfully maps onto the anchor.
+ /// A vertical line rotated a quarter turn into a horizontal one still
+ /// paints: its unrotated rect is zero-width, and only the rotated
+ /// *bounding box* meaningfully maps onto the anchor.
#[test]
fn a_quarter_rotated_flat_line_still_paints() {
let anchor = r#"<xdr:twoCellAnchor>
@@ -3838,7 +3777,7 @@ mod tests {
}
/// A declared run colour reaches the painted text — red glyphs, not the
- /// black default. 5,041 of 5,902 corpus runs declare one.
+ /// black default.
#[test]
fn a_declared_run_colour_reaches_the_painted_text() {
let anchor = r#"<xdr:oneCellAnchor>
@@ -3899,9 +3838,8 @@ mod tests {
}
/// A sentence too wide for its box paints as several measured lines while
- /// the item stays the single unmeasured stack entry. This is the whole
- /// shape of step 5b: paint is a layout, items are not, and the census
- /// says 34.8% of corpus paragraphs are on this path.
+ /// the item stays the single unmeasured stack entry: paint is a layout,
+ /// items are not.
#[test]
fn shape_text_wraps_in_the_paint_and_not_in_the_items() {
// 72 x 72 pt box, a sentence far wider than 72pt at 12pt Calibri.
@@ -3938,8 +3876,8 @@ mod tests {
assert_eq!(shape_items.len(), 1, "the item side is still one paragraph");
}
- /// `anchor="ctr"` moves the painted body down the box — 61.5% of corpus
- /// shapes, and the reason the even stack could not be painted as-is.
+ /// `anchor="ctr"` moves the painted body down the box — the reason the
+ /// even stack could not be painted as-is.
#[test]
fn a_centred_anchor_moves_the_painted_body_and_not_the_item() {
let shape = |anchor: &str| {
@@ -4035,8 +3973,8 @@ mod tests {
}
/// A box narrower than the two default 7.2pt insets still paints. Without
- /// the clamp `layout_shape_body` returns nothing at all, which is 6.5% of
- /// corpus shapes — the narrow marker labels a timeline is made of.
+ /// the clamp `layout_shape_body` returns nothing at all — the narrow
+ /// vertical marker labels a timeline is made of would vanish.
#[test]
fn a_box_narrower_than_its_insets_still_paints() {
// 114300 EMU = 9pt wide, against 14.4pt of default horizontal inset.
@@ -4274,9 +4212,8 @@ mod tests {
}
}
- /// The 12.8% / 6.1% pair from the paint census, as one fixture: the same
- /// oversized string clips against a written neighbour and spills past an
- /// empty one.
+ /// Clip and spill in one fixture: the same oversized string clips against
+ /// a written neighbour and spills past an empty one.
#[test]
fn overflow_spills_into_an_empty_neighbour_and_clips_against_a_written_one() {
let long = "the quick brown fox jumps over the lazy dog";
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 3d1803e..d95c012 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -831,19 +831,14 @@ impl LiteParse {
}
}
- /// Config the native DOCX path cannot honor — these force the conversion
- /// path so the caller still gets what they asked for. `doc_meta` is not
- /// in the list: it is `None` for converted inputs already, and the native
- /// path keeps that rule.
- #[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]
/// Config options the native DOCX path cannot honor. Hitting one with
/// `office_native` on is a hard `Config` error, not a fallback — see the
- /// check in `parse_input`. Supported and deliberately absent from this
- /// list: `extract_images` (native media bytes), `extract_xfa_packets`
- /// (honestly empty — DOCX has no XFA), `extract_annotations` (hyperlink +
- /// internal-link rects merged to `link` annotations), and
- /// `include_complexity` (native facts; see
- /// `calculate_native_page_complexity`).
+ /// check in `parse_input`. Deliberately absent (the native path honors
+ /// these): `extract_images`, `extract_xfa_packets` (empty — DOCX has no
+ /// XFA), `extract_annotations` (hyperlink/internal-link rects as `link`
+ /// annotations), `include_complexity`, and `doc_meta` (`None`, as on the
+ /// conversion path).
+ #[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]
fn native_docx_ineligible_reason(&self) -> Option<&'static str> {
let c = &self.config;
if c.extract_form_fields {
@@ -864,19 +859,10 @@ impl LiteParse {
/// Config options the native PPTX path cannot honor. Hitting one with
/// `office_native` on is a hard `Config` error, not a fallback.
///
- /// One entry is PPTX-specific and is here because the alternative is
- /// silent under-delivery:
- ///
- /// * `extract_annotations` — the geometry adapter builds fragments with no
- /// `LinkTarget`, so there are no link rects to merge. Markdown links
- /// (`extract_links`) are unaffected: those come from the emitter, which
- /// does resolve `a:hlinkClick`.
- ///
- /// `extract_images` **was** here, for as long as `ShapeKind::Picture`
- /// emitted nothing. It now extracts, so the flag is honored rather than
- /// rejected; `image_mode` never was here, which meant a default-config
- /// parse silently produced no `![](…)` refs where the conversion path
- /// produced 2,719 across the corpus. Both are now the same answer.
+ /// `extract_annotations` is PPTX-specific: the geometry adapter builds
+ /// fragments with no `LinkTarget`, so there are no link rects to merge.
+ /// Markdown links (`extract_links`) are unaffected — those come from the
+ /// emitter, which resolves `a:hlinkClick`.
#[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]
fn native_pptx_ineligible_reason(&self) -> Option<&'static str> {
let c = &self.config;
@@ -900,17 +886,10 @@ impl LiteParse {
/// Config options the native XLSX path cannot honor. Hitting one with
/// `office_native` on is a hard `Config` error, not a fallback.
///
- /// One entry is XLSX-specific:
- ///
- /// * `extract_annotations` — hyperlinks reach `TextItem::link`, but no
- /// `DocumentAnnotation` list is built (same v1 state the PPTX path
- /// started in).
- ///
- /// `extract_images` / `image_mode = embed` **were** here, for as long as
- /// the reader ignored `xl/drawings`. The drawing layer's pictures now
- /// extract (charts and drawing shapes remain out of scope — a chart has
- /// no image bytes and either engine's conversion path also extracts none
- /// for it), so both flags are honored rather than rejected.
+ /// `extract_annotations` is XLSX-specific: hyperlinks reach
+ /// `TextItem::link`, but no `DocumentAnnotation` list is built. Images
+ /// are honored — the drawing layer's pictures extract, though charts and
+ /// drawing shapes carry no image bytes and are out of scope.
#[cfg(all(feature = "xlsx-native", not(target_arch = "wasm32")))]
fn native_xlsx_ineligible_reason(&self) -> Option<&'static str> {
let c = &self.config;
@@ -1016,31 +995,8 @@ impl LiteParse {
// Page selection mirrors the other native paths: `target_pages`
// filters by 1-based number, then `max_pages` truncates. The outline
// stays whole-document.
- let mut selected: Vec<((Page, Vec<crate::markdown_layout::Block>), _)> = nx
- .pages
- .into_iter()
- .zip(nx.page_blocks)
- .zip(complexity)
- .collect();
- let mut page_filtered = false;
- if let Some(targets) = self.resolve_target_pages()? {
- let keep: std::collections::HashSet<usize> =
- targets.iter().map(|p| *p as usize).collect();
- selected.retain(|((p, _), _)| keep.contains(&p.page_number));
- page_filtered = true;
- }
- if selected.len() > self.config.max_pages {
- selected.truncate(self.config.max_pages);
- page_filtered = true;
- }
- let mut pages = Vec::with_capacity(selected.len());
- let mut page_blocks = Vec::with_capacity(selected.len());
- let mut page_stats = Vec::with_capacity(selected.len());
- for ((p, b), s) in selected {
- pages.push(p);
- page_blocks.push(b);
- page_stats.push(s);
- }
+ let (pages, page_blocks, page_stats, page_filtered) =
+ self.select_native_pages(nx.pages, nx.page_blocks, complexity)?;
let mut result = self.parse_from_native_blocks(
pages,
@@ -1113,11 +1069,9 @@ impl LiteParse {
data,
pptx::EmitOptions {
links: self.config.extract_links,
- // Speaker notes are the single largest content difference
- // between this path and the converted one — LibreOffice's PDF
- // export renders 0.5% of them. They land in the slide's
- // markdown and contribute no `TextItem`s, because the text
- // genuinely is not on the slide (user, 2026-08-17).
+ // Speaker notes land in the slide's markdown and contribute
+ // no `TextItem`s: the text is not on the slide itself. The
+ // LibreOffice conversion path drops nearly all of them.
notes: true,
figures: want_figures,
images: want_images,
@@ -1165,31 +1119,8 @@ impl LiteParse {
// Page selection mirrors the PDF and DOCX paths: `target_pages` filters
// by 1-based number, then `max_pages` truncates. A slide *is* a page,
// so a page number is a slide number.
- let mut selected: Vec<((Page, Vec<crate::markdown_layout::Block>), _)> = geo
- .pages
- .into_iter()
- .zip(page_blocks)
- .zip(complexity)
- .collect();
- let mut page_filtered = false;
- if let Some(targets) = self.resolve_target_pages()? {
- let keep: std::collections::HashSet<usize> =
- targets.iter().map(|p| *p as usize).collect();
- selected.retain(|((p, _), _)| keep.contains(&p.page_number));
- page_filtered = true;
- }
- if selected.len() > self.config.max_pages {
- selected.truncate(self.config.max_pages);
- page_filtered = true;
- }
- let mut pages = Vec::with_capacity(selected.len());
- let mut page_blocks = Vec::with_capacity(selected.len());
- let mut page_stats = Vec::with_capacity(selected.len());
- for ((p, b), s) in selected {
- pages.push(p);
- page_blocks.push(b);
- page_stats.push(s);
- }
+ let (pages, page_blocks, page_stats, page_filtered) =
+ self.select_native_pages(geo.pages, page_blocks, complexity)?;
let mut result = self.parse_from_native_blocks(
pages,
@@ -1202,8 +1133,8 @@ impl LiteParse {
// Same post-passes as the PDF and DOCX paths, same order: duplicate
// figure refs point at the canonical name, then only canonical files
- // are written. A deck leans on these harder than a document does —
- // 3,602 corpus placements resolve to 1,322 files.
+ // are written. Decks reuse images heavily, so this dedup matters more
+ // here than for documents.
if self.config.output_format == crate::config::OutputFormat::Markdown {
rewrite_duplicate_image_refs(&mut result.pages, &mut result.text, &result.images);
}
@@ -1341,31 +1272,8 @@ impl LiteParse {
// 1-based page number, then `max_pages` truncates. The outline stays
// whole-document, as it does on the PDF path. A page selection also
// narrows the doc-level text to the surviving pages' blocks.
- let mut selected: Vec<((Page, Vec<crate::markdown_layout::Block>), _)> = native
- .pages
- .into_iter()
- .zip(page_blocks)
- .zip(complexity)
- .collect();
- let mut page_filtered = false;
- if let Some(targets) = self.resolve_target_pages()? {
- let keep: std::collections::HashSet<usize> =
- targets.iter().map(|p| *p as usize).collect();
- selected.retain(|((p, _), _)| keep.contains(&p.page_number));
- page_filtered = true;
- }
- if selected.len() > self.config.max_pages {
- selected.truncate(self.config.max_pages);
- page_filtered = true;
- }
- let mut pages = Vec::with_capacity(selected.len());
- let mut page_blocks = Vec::with_capacity(selected.len());
- let mut page_stats = Vec::with_capacity(selected.len());
- for ((p, b), s) in selected {
- pages.push(p);
- page_blocks.push(b);
- page_stats.push(s);
- }
+ let (pages, page_blocks, page_stats, page_filtered) =
+ self.select_native_pages(native.pages, page_blocks, complexity)?;
let mut result = self.parse_from_native_blocks(
pages,
@@ -1457,11 +1365,10 @@ impl LiteParse {
let page_count = layouted.len() as u32;
// A zero-page layout is an engine failure, not an empty document:
// every reader here gives a sheet, a slide or a section at least one
- // page, so nothing to draw means nothing was read. Degrading is the
- // only useful answer — one corpus workbook has 12 KB of junk ahead of
- // its local headers, which this reader walks to zero sheets and
- // LibreOffice recovers. Returning "page 1 out of range (0 pages)"
- // instead would hand the caller a range error it cannot act on.
+ // page, so nothing to draw means nothing was read. Degrade to the
+ // conversion path (LibreOffice may recover a malformed file) rather
+ // than return a "page 1 out of range (0 pages)" the caller cannot act
+ // on.
if page_count == 0 {
return Err(LiteParseError::Conversion(format!(
"native layout produced no {noun}"
@@ -1613,6 +1520,50 @@ impl LiteParse {
/// structure path; the per-page markdown is the paged *view* of the same
/// blocks. `None` (page-filtered parse) falls back to joining the
/// surviving pages.
+ /// Page selection shared by the native DOCX, PPTX and XLSX paths:
+ /// `target_pages` filters by 1-based page number, then `max_pages`
+ /// truncates. Returns the aligned `(pages, page_blocks, page_stats)`
+ /// triple plus whether any filtering occurred — callers drop the
+ /// doc-level `all_blocks` when it did.
+ #[cfg(all(feature = "office-native", not(target_arch = "wasm32")))]
+ fn select_native_pages(
+ &self,
+ pages: Vec<Page>,
+ page_blocks: Vec<Vec<crate::markdown_layout::Block>>,
+ complexity: Vec<Option<crate::ocr_merge::PageComplexityStats>>,
+ ) -> Result<
+ (
+ Vec<Page>,
+ Vec<Vec<crate::markdown_layout::Block>>,
+ Vec<Option<crate::ocr_merge::PageComplexityStats>>,
+ bool,
+ ),
+ LiteParseError,
+ > {
+ let mut selected: Vec<((Page, Vec<crate::markdown_layout::Block>), _)> =
+ pages.into_iter().zip(page_blocks).zip(complexity).collect();
+ let mut page_filtered = false;
+ if let Some(targets) = self.resolve_target_pages()? {
+ let keep: std::collections::HashSet<usize> =
+ targets.iter().map(|p| *p as usize).collect();
+ selected.retain(|((p, _), _)| keep.contains(&p.page_number));
+ page_filtered = true;
+ }
+ if selected.len() > self.config.max_pages {
+ selected.truncate(self.config.max_pages);
+ page_filtered = true;
+ }
+ let mut pages = Vec::with_capacity(selected.len());
+ let mut page_blocks = Vec::with_capacity(selected.len());
+ let mut page_stats = Vec::with_capacity(selected.len());
+ for ((p, b), s) in selected {
+ pages.push(p);
+ page_blocks.push(b);
+ page_stats.push(s);
+ }
+ Ok((pages, page_blocks, page_stats, page_filtered))
+ }
+
#[cfg(all(feature = "office-native", not(target_arch = "wasm32")))]
fn parse_from_native_blocks(
&self,
diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rs
index 556dbce..670bc88 100644
--- a/crates/liteparse/tests/integration_test.rs
+++ b/crates/liteparse/tests/integration_test.rs
@@ -105,8 +105,8 @@ async fn test_parse_bytes_office_integration() {
// `sample3.doc` is a renamed Word 2007+ (.docx) file, so byte input has no
// extension to go on and the container sniff routes it down the native
// DOCX path when that feature is on. Native pagination is host-dependent
- // (font substitution can spill a page — see NATIVE_OFFICE_PLAN.md), so
- // assert a page range rather than pinning LibreOffice's exact count.
+ // (font substitution can spill a page), so assert a page range rather than
+ // pinning LibreOffice's exact count.
let fixture_path = "../../integration_tests_data/sample3.doc";
let lit = LiteParse::new(LiteParseConfig::default());
let data = tokio::fs::read(fixture_path)
@@ -299,8 +299,7 @@ async fn test_annotation_text_complexity_reason() {
/// Native DOCX path end-to-end: real geometry per page, links as data, and
/// doc-level markdown byte-identical to the pure structure path
-/// (`docx_to_blocks` → `render_blocks`) — the invariant that pins the
-/// docx_rules_eval corpus score.
+/// (`docx_to_blocks` → `render_blocks`).
///
/// The byte-identity holds under the default `image_mode` because this
/// fixture's only images are header decorations, which the body walk never
@@ -362,9 +361,7 @@ async fn test_parse_docx_native_integration() {
/// The fixture's two callouts are `<wp:inline>` `wps:wsp` shapes wrapped in an
/// `mc:AlternateContent` whose `mc:Fallback` is a VML `v:textbox` carrying
/// **the same text** — so the walk must commit to one branch or emit the box
-/// twice. Before the text-box tap, the structure walk descended into neither
-/// and 1,213 chars of instructional prose were absent from native markdown
-/// while the LibreOffice path kept them.
+/// twice.
#[cfg(feature = "docx-native")]
#[tokio::test]
#[serial]
@@ -619,10 +616,8 @@ async fn test_parse_docx_native_complexity_integration() {
/// Native PPTX path end-to-end.
///
/// The load-bearing assertion is the byte-identity between `parsed.text` and
-/// the emitter's own output: `office/pptx.rs` is what the corpus content-recall
-/// number (0.9256 vs anydoc's 0.9250) was measured on, and the wiring must not
-/// perturb it. If this fails, the recorded score no longer describes what the
-/// CLI produces.
+/// the emitter's own output: content recall is measured against
+/// `office/pptx.rs`, so the wiring must not perturb what it produces.
///
/// The rest pins the contract the geometry pass added: one page per slide, real
/// boxes on every page, and an outline built from slide titles.