Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewich8c8393f7cfeb
diff --git a/crates/liteparse-ooxml/src/docx/parse/mod.rs b/crates/liteparse-ooxml/src/docx/parse/mod.rs
index af01321..49878b9 100644
--- a/crates/liteparse-ooxml/src/docx/parse/mod.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/mod.rs
@@ -332,10 +332,10 @@ fn resolve_hyperlinks_in_inlines(
match inline {
Inline::Hyperlink(link) => {
// Resolve an unresolved relationship id to its actual URL.
- if let HyperlinkTarget::ExternalRel(ref rel_id) = link.target {
- if let Some(rel) = rels.find_by_id(rel_id.as_str()) {
- link.target = HyperlinkTarget::ExternalUrl(rel.target.clone());
- }
+ if let HyperlinkTarget::ExternalRel(ref rel_id) = link.target
+ && let Some(rel) = rels.find_by_id(rel_id.as_str())
+ {
+ link.target = HyperlinkTarget::ExternalUrl(rel.target.clone());
}
// Recurse into hyperlink content.
resolve_hyperlinks_in_inlines(&mut link.content, rels);
diff --git a/crates/liteparse-ooxml/src/docx/parse/numbering.rs b/crates/liteparse-ooxml/src/docx/parse/numbering.rs
index 94d2525..8755648 100644
--- a/crates/liteparse-ooxml/src/docx/parse/numbering.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/numbering.rs
@@ -230,13 +230,13 @@ impl From<LvlXml> for NumberingLevelDefinition {
let (indentation, run_properties) = extract_level_properties(x.p_pr, x.r_pr);
Self {
level: x.ilvl,
- format: x.num_fmt.map(|v| NumberFormat::from(v)),
+ format: x.num_fmt.map(NumberFormat::from),
level_text: x.lvl_text.map(|v| v.val).unwrap_or_default(),
start: x.start,
justification: x.lvl_jc.map(Alignment::from),
indentation,
run_properties,
- lvl_pic_bullet_id: x.lvl_pic_bullet_id.map(|v| NumPicBulletId::new(v)),
+ lvl_pic_bullet_id: x.lvl_pic_bullet_id.map(NumPicBulletId::new),
suffix: x.suff.map(LevelSuffix::from).unwrap_or_default(),
is_legal: x.is_lgl.map(|OnOff(b)| b).unwrap_or(false),
}
@@ -255,7 +255,7 @@ fn extract_level_properties(
fn convert_num(n: NumXml) -> NumberingInstance {
let abstract_num_id = n
.abstract_num_id
- .map(|v| AbstractNumId::new(v))
+ .map(AbstractNumId::new)
.unwrap_or_else(|| {
log::warn!(
"numbering instance numId={:?} has no abstractNumId; defaulting to 0",
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 8cb769a..1067b39 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/paragraph.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/paragraph.rs
@@ -398,7 +398,7 @@ impl PPrXml {
contextual_spacing: last_toggle(self.contextual_spacing),
bidi: last_toggle(self.bidi),
word_wrap: last_toggle(self.word_wrap),
- outline_level: self.outline_lvl.and_then(|v| OutlineLevel::from_ooxml(v)),
+ outline_level: self.outline_lvl.and_then(OutlineLevel::from_ooxml),
text_alignment: self.text_alignment.map(TextAlignment::from),
cnf_style: self.cnf_style.map(CnfStyle::from),
frame_properties: self.frame_pr.map(FrameKind::from),
@@ -418,7 +418,7 @@ impl PPrXml {
fn numbering_ref(x: NumPrXml) -> Option<NumberingReference> {
let num_id = x.num_id?;
Some(NumberingReference {
- num_id: num_id,
+ num_id,
level: x.ilvl.unwrap_or(0),
})
}
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 e8c2752..6b5b2a1 100644
--- a/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/properties/schema/run.rs
@@ -199,7 +199,7 @@ impl RPrXml {
position: self.position,
lang: self.lang.map(Into::into),
border: self.bdr.map(Into::into),
- text_scale: self.char_scale.map(|v| TextScale::new(v)),
+ text_scale: self.char_scale.map(TextScale::new),
};
(props, style_id)
}
diff --git a/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs b/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs
index d520c4b..f7adc81 100644
--- a/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs
+++ b/crates/liteparse-ooxml/src/docx/parse/rel_rewrite.rs
@@ -249,13 +249,13 @@ fn rewrite_vml_image_data(data: &mut VmlImageData, remap: &HashMap<RelId, RelId>
/// reason) the URL won't match any rId in `remap` and this is a
/// no-op.
fn rewrite_in_hyperlink_target(target: &mut HyperlinkTarget, remap: &HashMap<RelId, RelId>) {
- if let HyperlinkTarget::ExternalRel(id) = target {
- if let Some(new) = remap.get(id) {
- // For a subordinate part the remap resolves a hyperlink rId directly
- // to its external URL (see `load_part_rel_remap`), so the target
- // becomes a resolved URL rather than another rId.
- *target = HyperlinkTarget::ExternalUrl(new.as_str().to_string());
- }
+ if let HyperlinkTarget::ExternalRel(id) = target
+ && let Some(new) = remap.get(id)
+ {
+ // For a subordinate part the remap resolves a hyperlink rId directly
+ // to its external URL (see `load_part_rel_remap`), so the target
+ // becomes a resolved URL rather than another rId.
+ *target = HyperlinkTarget::ExternalUrl(new.as_str().to_string());
}
}
diff --git a/crates/liteparse-ooxml/src/pptx/cascade.rs b/crates/liteparse-ooxml/src/pptx/cascade.rs
new file mode 100644
index 0000000..ecc60fe
--- /dev/null
+++ b/crates/liteparse-ooxml/src/pptx/cascade.rs
@@ -0,0 +1,475 @@
+//! The placeholder cascade — inherited geometry (§19.3.1.36 `p:ph`).
+//!
+//! A slide shape that omits `<a:xfrm>` is not at the origin; it is a
+//! **placeholder** taking its rectangle from the corresponding placeholder on
+//! its layout, which may in turn take it from the master. [`pptx::shapes`]
+//! deliberately leaves that as `transform: None`, and this module fills it in.
+//!
+//! [`pptx::shapes`]: crate::pptx::shapes
+//!
+//! ## The match rule is not the same at each rung
+//!
+//! 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`):
+//!
+//! | 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"/>`
+//! — 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.**
+//!
+//! 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
+//! [`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.
+//!
+//! ## Three simplifications, each measured rather than assumed
+//!
+//! - **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.
+
+use std::collections::HashMap;
+
+use crate::model::Transform2D;
+
+use super::shapes::{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.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MatchRule {
+ /// Slide → layout, and notes slide → its own layout if one ever exists:
+ /// match `@idx` exactly, ignoring `@type`.
+ Idx,
+ /// Layout → master, notes slide → notes master: match `@type` after
+ /// collapsing through [`PlaceholderKind::collapsed_for_master`].
+ CollapsedKind,
+}
+
+/// The inheritable geometry of one part, with that part's *own* inheritance
+/// already folded in.
+///
+/// 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
+/// rather than walked per shape.
+#[derive(Clone, Debug, Default)]
+pub struct PlaceholderGeometry {
+ by_idx: HashMap<u32, Transform2D>,
+ by_kind: HashMap<PlaceholderKind, Transform2D>,
+}
+
+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.
+ pub fn from_master(shapes: &[Shape]) -> Self {
+ Self::index(shapes, None, MatchRule::CollapsedKind)
+ }
+
+ /// Index a layout, resolving each of its own no-`xfrm` placeholders against
+ /// `master` first.
+ ///
+ /// `master` is `Option` because [`SlideParts::master`] is — a slide whose
+ /// master is unreachable still has a usable layout, and the fail-open
+ /// posture applies here as everywhere else in this vendor.
+ ///
+ /// [`SlideParts::master`]: crate::pptx::SlideParts::master
+ pub fn from_layout(shapes: &[Shape], master: Option<&PlaceholderGeometry>) -> Self {
+ Self::index(shapes, master, MatchRule::CollapsedKind)
+ }
+
+ /// The transform a placeholder with these properties should inherit.
+ pub fn lookup(&self, ph: &Placeholder, rule: MatchRule) -> Option<Transform2D> {
+ match rule {
+ MatchRule::Idx => self.by_idx.get(&ph.idx).copied(),
+ MatchRule::CollapsedKind => self.by_kind.get(&ph.kind.collapsed_for_master()).copied(),
+ }
+ }
+
+ /// 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.
+ pub fn is_empty(&self) -> bool {
+ self.by_idx.is_empty() && self.by_kind.is_empty()
+ }
+
+ 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.
+ for shape in shapes {
+ let Some(ph) = &shape.placeholder else {
+ continue;
+ };
+ let Some(transform) = shape
+ .transform
+ .or_else(|| parent.and_then(|p| p.lookup(ph, rule)))
+ 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.
+ out.by_idx.entry(ph.idx).or_insert(transform);
+ out.by_kind
+ .entry(ph.kind.collapsed_for_master())
+ .or_insert(transform);
+ }
+ out
+ }
+}
+
+/// What one [`apply_inherited_geometry`] pass did, for probes and diagnostics.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct CascadeStats {
+ /// Shapes that already declared their own `xfrm` and were left alone.
+ pub declared: usize,
+ /// Placeholders that had no `xfrm` and got one from the part above.
+ pub inherited: usize,
+ /// 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.
+ 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`.
+///
+/// Mutates in place and sets [`Shape::transform_inherited`] on everything it
+/// touches, so a later consumer can still tell an inherited rectangle from a
+/// declared one.
+///
+/// `source` is `Option` so the caller does not have to special-case a missing
+/// layout, master or notes master; `None` resolves nothing and reports it,
+/// which is the correct outcome for a deck whose notes master is empty.
+pub fn apply_inherited_geometry(
+ shapes: &mut [Shape],
+ source: Option<&PlaceholderGeometry>,
+ rule: MatchRule,
+) -> CascadeStats {
+ let mut stats = CascadeStats::default();
+ for shape in shapes.iter_mut() {
+ if shape.transform.is_some() {
+ stats.declared += 1;
+ continue;
+ }
+ let Some(ph) = shape.placeholder.clone() else {
+ stats.orphans += 1;
+ continue;
+ };
+ match source.and_then(|s| s.lookup(&ph, rule)) {
+ Some(transform) => {
+ shape.transform = Some(transform);
+ shape.transform_inherited = true;
+ stats.inherited += 1;
+ }
+ None => stats.unresolved += 1,
+ }
+ }
+ 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
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::{Dimension, Emu};
+ use crate::model::geometry::{Offset, Size};
+ use crate::pptx::parse_shape_tree;
+
+ fn xfrm(x: i64, y: i64, cx: i64, cy: i64) -> String {
+ format!(r#"<a:xfrm><a:off x="{x}" y="{y}"/><a:ext cx="{cx}" cy="{cy}"/></a:xfrm>"#)
+ }
+
+ /// A part holding one `p:sp` per `(type, idx, xfrm)` triple.
+ fn part(shapes: &[(&str, &str, Option<String>)]) -> Vec<Shape> {
+ let body: String = shapes
+ .iter()
+ .map(|(ty, idx, x)| {
+ let ph = match (*ty, *idx) {
+ ("", "") => "<p:ph/>".to_string(),
+ ("", i) => format!(r#"<p:ph idx="{i}"/>"#),
+ (t, "") => format!(r#"<p:ph type="{t}"/>"#),
+ (t, i) => format!(r#"<p:ph type="{t}" idx="{i}"/>"#),
+ };
+ format!(
+ r#"<p:sp><p:nvSpPr><p:cNvPr id="1" name="s"/><p:nvPr>{ph}</p:nvPr></p:nvSpPr>
+ <p:spPr>{}</p:spPr></p:sp>"#,
+ x.clone().unwrap_or_default()
+ )
+ })
+ .collect();
+ parse_shape_tree(
+ format!(
+ r#"<p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>{body}</p:spTree></p:cSld></p:sld>"#
+ )
+ .as_bytes(),
+ )
+ .expect("parses")
+ }
+
+ fn offset_of(s: &Shape) -> Option<Offset<Emu>> {
+ s.transform.and_then(|t| t.offset)
+ }
+
+ fn emu(v: i64) -> Dimension<Emu> {
+ Dimension::new(v)
+ }
+
+ #[test]
+ fn slide_inherits_from_layout_by_idx() {
+ let layout = part(&[
+ ("title", "0", Some(xfrm(100, 200, 10, 20))),
+ ("body", "1", Some(xfrm(300, 400, 30, 40))),
+ ]);
+ let index = PlaceholderGeometry::from_layout(&layout, None);
+
+ let mut slide = part(&[("body", "1", None)]);
+ let stats = apply_inherited_geometry(&mut slide, Some(&index), MatchRule::Idx);
+
+ assert_eq!(stats.inherited, 1);
+ assert_eq!(stats.unresolved, 0);
+ assert_eq!(offset_of(&slide[0]).unwrap().x, emu(300));
+ 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.
+ #[test]
+ fn idx_match_ignores_a_disagreeing_type() {
+ let layout = part(&[
+ ("title", "0", Some(xfrm(100, 200, 10, 20))),
+ ("body", "1", Some(xfrm(300, 400, 30, 40))),
+ ]);
+ let index = PlaceholderGeometry::from_layout(&layout, None);
+
+ let mut slide = part(&[("", "", None)]);
+ assert_eq!(
+ slide[0].placeholder.as_ref().unwrap().kind,
+ PlaceholderKind::Body
+ );
+ assert_eq!(slide[0].placeholder.as_ref().unwrap().idx, 0);
+
+ apply_inherited_geometry(&mut slide, Some(&index), MatchRule::Idx);
+ assert_eq!(
+ offset_of(&slide[0]).unwrap().x,
+ emu(100),
+ "took the title's box"
+ );
+ }
+
+ /// Two rungs 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.
+ let layout = part(&[("body", "1", None)]);
+ let layout_index = PlaceholderGeometry::from_layout(&layout, Some(&master_index));
+
+ let mut slide = part(&[("body", "1", None)]);
+ let stats = apply_inherited_geometry(&mut slide, Some(&layout_index), MatchRule::Idx);
+
+ assert_eq!(stats.inherited, 1);
+ assert_eq!(offset_of(&slide[0]).unwrap().y, emu(800));
+ }
+
+ /// `subTitle`, `obj`, `tbl` and friends all collapse onto the master's
+ /// single `body`; without the collapse this rung finds nothing.
+ #[test]
+ fn layout_to_master_collapses_body_ish_types() {
+ let master = part(&[("body", "1", Some(xfrm(700, 800, 70, 80)))]);
+ let master_index = PlaceholderGeometry::from_master(&master);
+
+ for ty in ["subTitle", "obj", "tbl", "chart", "pic", "dgm"] {
+ let mut layout = part(&[(ty, "5", None)]);
+ let stats = apply_inherited_geometry(
+ &mut layout,
+ Some(&master_index),
+ MatchRule::CollapsedKind,
+ );
+ assert_eq!(stats.inherited, 1, "{ty} should collapse onto body");
+ assert_eq!(offset_of(&layout[0]).unwrap().x, emu(700));
+ }
+ }
+
+ /// The 15 `dt`/`ftr` layout placeholders: 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)))]);
+ let master_index = PlaceholderGeometry::from_master(&master);
+
+ let mut layout = part(&[("ftr", "11", None)]);
+ let stats =
+ apply_inherited_geometry(&mut layout, Some(&master_index), MatchRule::CollapsedKind);
+
+ assert_eq!(stats.unresolved, 1);
+ assert_eq!(stats.inherited, 0);
+ assert!(layout[0].transform.is_none());
+ assert!(!layout[0].transform_inherited);
+ }
+
+ /// The empty-notesMaster deck. `None` and "present but empty" must behave
+ /// the same, and neither may panic.
+ #[test]
+ fn an_empty_or_absent_source_resolves_nothing() {
+ let empty = PlaceholderGeometry::from_master(&[]);
+ assert!(empty.is_empty());
+
+ for source in [Some(&empty), None] {
+ let mut notes = part(&[("sldImg", "0", None), ("body", "1", None)]);
+ let stats = apply_inherited_geometry(&mut notes, source, MatchRule::CollapsedKind);
+ assert_eq!(stats.unresolved, 2);
+ assert!(notes.iter().all(|s| s.transform.is_none()));
+ }
+ }
+
+ /// A declared transform always wins; the cascade only fills holes.
+ #[test]
+ fn a_declared_transform_is_never_overwritten() {
+ let layout = part(&[("body", "1", Some(xfrm(100, 200, 10, 20)))]);
+ let index = PlaceholderGeometry::from_layout(&layout, None);
+
+ let mut slide = part(&[("body", "1", Some(xfrm(999, 999, 99, 99)))]);
+ let stats = apply_inherited_geometry(&mut slide, Some(&index), MatchRule::Idx);
+
+ assert_eq!(stats.declared, 1);
+ assert_eq!(stats.inherited, 0);
+ assert_eq!(offset_of(&slide[0]).unwrap().x, emu(999));
+ 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.
+ #[test]
+ fn duplicate_idx_resolves_first_in_document_order() {
+ let layout = part(&[
+ ("body", "1", Some(xfrm(111, 111, 11, 11))),
+ ("body", "1", Some(xfrm(222, 222, 22, 22))),
+ ]);
+ let index = PlaceholderGeometry::from_layout(&layout, None);
+
+ let mut slide = part(&[("body", "1", None)]);
+ apply_inherited_geometry(&mut slide, Some(&index), MatchRule::Idx);
+ 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.
+ #[test]
+ fn rotation_rides_along_with_the_inherited_transform() {
+ let shapes = parse_shape_tree(
+ br#"<p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>
+ <p:sp><p:nvSpPr><p:cNvPr id="1" name="s"/><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr>
+ <p:spPr><a:xfrm rot="-4320000"><a:off x="1" y="2"/><a:ext cx="3" cy="4"/></a:xfrm></p:spPr></p:sp>
+ </p:spTree></p:cSld></p:sld>"#,
+ )
+ .unwrap();
+ let index = PlaceholderGeometry::from_layout(&shapes, None);
+
+ let mut slide = part(&[("body", "1", None)]);
+ apply_inherited_geometry(&mut slide, Some(&index), MatchRule::Idx);
+ let t = slide[0].transform.unwrap();
+ assert_eq!(t.rotation.map(|r| r.raw()), Some(-4320000));
+ assert_eq!(t.extent.map(|e: Size<Emu>| e.width), Some(emu(3)));
+ }
+
+ /// A non-placeholder with no geometry is counted, not silently resolved:
+ /// the shape walk asserts there are none on the corpus, so a non-zero
+ /// count here points at that invariant, not at this module.
+ #[test]
+ fn a_non_placeholder_without_geometry_is_an_orphan() {
+ let mut shapes = parse_shape_tree(
+ br#"<p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>
+ <p:sp><p:nvSpPr><p:cNvPr id="1" name="s"/></p:nvSpPr><p:spPr/></p:sp>
+ </p:spTree></p:cSld></p:sld>"#,
+ )
+ .unwrap();
+ let stats = apply_inherited_geometry(&mut shapes, None, MatchRule::Idx);
+ assert_eq!(stats.orphans, 1);
+ assert_eq!(stats.unresolved, 0);
+ }
+}
diff --git a/crates/liteparse-ooxml/src/pptx/mod.rs b/crates/liteparse-ooxml/src/pptx/mod.rs
index 11b416f..b309256 100644
--- a/crates/liteparse-ooxml/src/pptx/mod.rs
+++ b/crates/liteparse-ooxml/src/pptx/mod.rs
@@ -10,10 +10,14 @@
//! `<a:xfrm>` inherits position and size from its layout, which inherits
//! from its master, and the match rule differs at each rung.
+pub mod cascade;
pub mod package;
pub mod shapes;
pub mod text;
+pub use cascade::{
+ CascadeStats, MatchRule, PlaceholderGeometry, apply_inherited_geometry, apply_slide,
+};
pub use package::{EMU_PER_POINT, Part, PresentationInfo, PresentationPackage, SlideParts, walk};
pub use shapes::{
AutoShape, Connector, GraphicFrame, GraphicFramePayload, Group, Placeholder, PlaceholderKind,
diff --git a/crates/liteparse-ooxml/src/pptx/package.rs b/crates/liteparse-ooxml/src/pptx/package.rs
index 3364c57..a783a92 100644
--- a/crates/liteparse-ooxml/src/pptx/package.rs
+++ b/crates/liteparse-ooxml/src/pptx/package.rs
@@ -296,10 +296,8 @@ fn parse_presentation(data: &[u8]) -> Result<PresentationXml> {
b"notesSz" => out.notes_size = size_attrs(e),
_ => {}
},
- Event::End(ref e) => {
- if local_name(e.name().as_ref()) == b"sldIdLst" {
- in_slide_id_lst = false;
- }
+ Event::End(ref e) if local_name(e.name().as_ref()) == b"sldIdLst" => {
+ in_slide_id_lst = false;
}
_ => {}
}
diff --git a/crates/liteparse-ooxml/src/pptx/shapes.rs b/crates/liteparse-ooxml/src/pptx/shapes.rs
index 27c3a8e..d204579 100644
--- a/crates/liteparse-ooxml/src/pptx/shapes.rs
+++ b/crates/liteparse-ooxml/src/pptx/shapes.rs
@@ -72,6 +72,15 @@ pub struct Shape {
/// `None` means the file declares no geometry, **not** that the shape sits
/// at the origin. It is resolved later by the placeholder cascade.
pub transform: Option<Transform2D>,
+ /// True once [`crate::pptx::cascade`] has filled `transform` in from a
+ /// layout or master placeholder, rather than the file declaring it here.
+ ///
+ /// Kept because "declared" and "inherited" are different facts about the
+ /// document even though they produce the same rectangle: the geometry
+ /// probe excludes inherited shapes from its source-EMU check (there is no
+ /// source EMU to check against), and a debug dump that cannot tell them
+ /// apart makes a bad cascade look like a bad file.
+ pub transform_inherited: bool,
pub kind: ShapeKind,
}
@@ -818,6 +827,7 @@ fn lower_sp(sp: SpXml) -> Shape {
non_visual: doc_properties(cnv_pr),
placeholder: nv_pr.and_then(|nv| nv.ph).map(PhXml::into_model),
transform: properties.as_ref().and_then(|p| p.transform),
+ transform_inherited: false,
kind: ShapeKind::AutoShape(Box::new(AutoShape {
properties,
text: sp.tx_body.map(TextBodyXml::into_model),
@@ -841,6 +851,7 @@ fn lower_pic(pic: PicXml) -> Shape {
.and_then(|nv| nv.ph)
.map(PhXml::into_model),
transform,
+ transform_inherited: false,
kind: ShapeKind::Picture(Box::new(Picture {
nv_pic_pr: NvPicProperties {
cnv_pr: non_visual,
@@ -858,6 +869,7 @@ fn lower_cxn(cxn: CxnSpXml) -> Shape {
non_visual: doc_properties(cxn.nv_cxn_sp_pr.map(|nv| nv.cnv_pr)),
placeholder: None,
transform: properties.as_ref().and_then(|p| p.transform),
+ transform_inherited: false,
kind: ShapeKind::Connector(Box::new(Connector { properties })),
}
}
@@ -869,6 +881,7 @@ fn lower_grp(grp: GrpSpXml) -> Shape {
non_visual: doc_properties(grp.nv_grp_sp_pr.map(|nv| nv.cnv_pr)),
placeholder: None,
transform,
+ transform_inherited: false,
kind: ShapeKind::Group(Box::new(Group {
properties: None,
child_offset: xfrm
@@ -898,6 +911,7 @@ fn lower_graphic_frame(gf: GraphicFrameXml) -> Shape {
non_visual: doc_properties(gf.nv_graphic_frame_pr.map(|nv| nv.cnv_pr)),
placeholder: None,
transform: gf.xfrm.map(Into::into),
+ transform_inherited: false,
kind: ShapeKind::GraphicFrame(Box::new(GraphicFrame { payload })),
}
}
diff --git a/crates/liteparse-ooxml/src/render/fonts.rs b/crates/liteparse-ooxml/src/render/fonts.rs
index 849975d..cda7ef5 100644
--- a/crates/liteparse-ooxml/src/render/fonts.rs
+++ b/crates/liteparse-ooxml/src/render/fonts.rs
@@ -727,17 +727,17 @@ impl FontRegistry {
fn resolve_uncached(&self, family: &str, style: FontStyle) -> (TypefaceEntry, ResolveRule) {
// 1. Embedded, by family + variant.
let variant = variant_for_style(style);
- if let Some(&eid) = self.embedded_index.get(&(family.to_lowercase(), variant)) {
- if let Some(face) = self.embedded[eid.0 as usize].face {
- log::debug!("[font] '{}' {:?} → embedded #{}", family, style, eid.0);
- return (
- TypefaceEntry {
- id: face,
- origin: TypefaceOrigin::Embedded { id: eid },
- },
- ResolveRule::Embedded,
- );
- }
+ if let Some(&eid) = self.embedded_index.get(&(family.to_lowercase(), variant))
+ && let Some(face) = self.embedded[eid.0 as usize].face
+ {
+ log::debug!("[font] '{}' {:?} → embedded #{}", family, style, eid.0);
+ return (
+ TypefaceEntry {
+ id: face,
+ origin: TypefaceOrigin::Embedded { id: eid },
+ },
+ ResolveRule::Embedded,
+ );
}
// 2. Exact family match. fontdb declines a family it does not have
@@ -772,16 +772,16 @@ impl FontRegistry {
// 4. Style suffix baked into the family name. The requested
// bold/italic still applies, so "Times New Roman Bold" lands on the
// real TNR bold face.
- if let Some(base) = strip_style_suffix(family) {
- if let Some(id) = self.query(&[fontdb::Family::Name(&base)], style) {
- log::debug!(
- "[font] '{}' {:?} → suffix-stripped '{}'",
- family,
- style,
- base
- );
- return (system_entry(id), ResolveRule::StyleSuffix);
- }
+ if let Some(base) = strip_style_suffix(family)
+ && let Some(id) = self.query(&[fontdb::Family::Name(&base)], style)
+ {
+ log::debug!(
+ "[font] '{}' {:?} → suffix-stripped '{}'",
+ family,
+ style,
+ base
+ );
+ return (system_entry(id), ResolveRule::StyleSuffix);
}
// 5. Substitution table. Candidates in table order, so a host carrying
@@ -832,13 +832,13 @@ impl FontRegistry {
/// missing color emoji font is never correct.
pub fn resolve_exact(&self, family: &str, style: FontStyle) -> Option<TypefaceEntry> {
let variant = variant_for_style(style);
- if let Some(&eid) = self.embedded_index.get(&(family.to_lowercase(), variant)) {
- if let Some(face) = self.embedded[eid.0 as usize].face {
- return Some(TypefaceEntry {
- id: face,
- origin: TypefaceOrigin::Embedded { id: eid },
- });
- }
+ if let Some(&eid) = self.embedded_index.get(&(family.to_lowercase(), variant))
+ && let Some(face) = self.embedded[eid.0 as usize].face
+ {
+ return Some(TypefaceEntry {
+ id: face,
+ origin: TypefaceOrigin::Embedded { id: eid },
+ });
}
self.query(&[fontdb::Family::Name(family)], style)
.map(system_entry)
diff --git a/crates/liteparse-ooxml/src/render/layout/build/block.rs b/crates/liteparse-ooxml/src/render/layout/build/block.rs
index 3eb6c5f..bb2d873 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/block.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/block.rs
@@ -92,10 +92,10 @@ pub(super) fn build_paragraph_block(
state.shape_default_text_color,
state.shape_default_font_family.as_deref(),
);
- if let Some(ref mrp) = p.mark_run_properties {
- if let Some(fs) = mrp.font_size {
- size = Pt::from(fs);
- }
+ if let Some(ref mrp) = p.mark_run_properties
+ && let Some(fs) = mrp.font_size
+ {
+ size = Pt::from(fs);
}
let line_height = ctx.measurer.default_line_height(&family, size);
fragments.push(Fragment::LineBreak { line_height });
@@ -123,13 +123,12 @@ pub(super) fn build_paragraph_block(
hyperlink_url,
..
} = frag
+ && hyperlink_url.is_some()
{
- if hyperlink_url.is_some() {
- *color = RgbColor::BLACK;
- // Rare (TOC hyperlinks only); clones this fragment's shared
- // font on write.
- Rc::make_mut(font).underline = false;
- }
+ *color = RgbColor::BLACK;
+ // Rare (TOC hyperlinks only); clones this fragment's shared
+ // font on write.
+ Rc::make_mut(font).underline = false;
}
}
}
@@ -417,10 +416,10 @@ pub(super) fn build_fragments(
);
// §17.7.2: table conditional formatting — lower priority than paragraph style.
- if let Some(c) = cond {
- if let Some(ref pp) = c.paragraph_properties {
- merge_paragraph_properties(&mut merged_props, pp);
- }
+ if let Some(c) = cond
+ && let Some(ref pp) = c.paragraph_properties
+ {
+ merge_paragraph_properties(&mut merged_props, pp);
}
// §17.7.2: table style paragraph properties — lower priority than conditional.
if let Some(ts) = table_style {
@@ -432,28 +431,28 @@ pub(super) fn build_fragments(
}
// §17.7.2: table style run properties override Normal.
- if let Some(ts) = table_style {
- if let Some(fs) = ts.run.font_size {
- default_size = Pt::from(fs);
- run_defaults.font_size = Some(fs);
- }
+ if let Some(ts) = table_style
+ && let Some(fs) = ts.run.font_size
+ {
+ default_size = Pt::from(fs);
+ run_defaults.font_size = Some(fs);
}
// §17.7.6: conditional run property overrides — higher priority than
// table style and paragraph style. Overlay (not merge): conditional
// values replace existing ones.
- if let Some(c) = cond {
- if let Some(ref rp) = c.run_properties {
- // Overlay: for each Some field in rp, replace in run_defaults.
- let mut overlay = rp.clone();
- merge_run_properties(&mut overlay, &run_defaults);
- run_defaults = overlay;
- if let Some(fs) = run_defaults.font_size {
- default_size = Pt::from(fs);
- }
- if let Some(color) = run_defaults.color {
- default_color = resolve_color(color, ColorContext::Text);
- }
+ if let Some(c) = cond
+ && let Some(ref rp) = c.run_properties
+ {
+ // Overlay: for each Some field in rp, replace in run_defaults.
+ let mut overlay = rp.clone();
+ merge_run_properties(&mut overlay, &run_defaults);
+ run_defaults = overlay;
+ if let Some(fs) = run_defaults.font_size {
+ default_size = Pt::from(fs);
+ }
+ if let Some(color) = run_defaults.color {
+ default_color = resolve_color(color, ColorContext::Text);
}
}
diff --git a/crates/liteparse-ooxml/src/render/layout/build/convert.rs b/crates/liteparse-ooxml/src/render/layout/build/convert.rs
index d179247..d82978b 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/convert.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/convert.rs
@@ -72,11 +72,11 @@ pub(super) fn resolve_paragraph_defaults(
.as_ref()
.or(resolved.default_paragraph_style_id.as_ref());
- if let Some(style_id) = effective_style_id {
- if let Some(resolved_style) = resolved.styles.get(style_id) {
- merge_paragraph_properties(&mut para_props, &resolved_style.paragraph);
- run_defaults = resolved_style.run.clone();
- }
+ if let Some(style_id) = effective_style_id
+ && let Some(resolved_style) = resolved.styles.get(style_id)
+ {
+ merge_paragraph_properties(&mut para_props, &resolved_style.paragraph);
+ run_defaults = resolved_style.run.clone();
}
// Merge doc defaults as lowest-priority fallback (unless deferred for table cascade).
@@ -493,12 +493,10 @@ pub(super) fn populate_image_data(
if let Fragment::Image {
rel_id, image_data, ..
} = frag
+ && image_data.is_none()
+ && let Some(entry) = media.get(&model::RelId::new(rel_id.as_str()))
{
- if image_data.is_none() {
- if let Some(entry) = media.get(&model::RelId::new(rel_id.as_str())) {
- *image_data = Some(entry.clone());
- }
- }
+ *image_data = Some(entry.clone());
}
}
}
@@ -771,15 +769,15 @@ fn wingdings_pua_to_unicode(code: u32) -> Option<char> {
/// Populate underline position/thickness from Skia font metrics.
pub(super) fn populate_underline_metrics(fragments: &mut [Fragment], measurer: &TextMeasurer) {
for frag in fragments.iter_mut() {
- if let Fragment::Text { font, .. } = frag {
- if font.underline {
- // Underlined runs only; `make_mut` clones the shared font so
- // the metrics can be written back.
- let fp = std::rc::Rc::make_mut(font);
- let (pos, thickness) = measurer.underline_metrics(fp);
- fp.underline_position = pos;
- fp.underline_thickness = thickness;
- }
+ if let Fragment::Text { font, .. } = frag
+ && font.underline
+ {
+ // Underlined runs only; `make_mut` clones the shared font so
+ // the metrics can be written back.
+ let fp = std::rc::Rc::make_mut(font);
+ let (pos, thickness) = measurer.underline_metrics(fp);
+ fp.underline_position = pos;
+ fp.underline_thickness = thickness;
}
}
}
diff --git a/crates/liteparse-ooxml/src/render/layout/build/floating.rs b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
index abba199..5a12af6 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/floating.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
@@ -1052,10 +1052,10 @@ pub(super) fn find_vml_absolute_position(inline: &model::Inline) -> Option<(Pt,
fn find_vml_pos_in_pict(pict: &model::Pict) -> Option<(Pt, Pt)> {
for shape in pict.shapes() {
- if shape.common.text_box.is_some() {
- if let Some(pos) = vml_absolute_position(&shape.common.style) {
- return Some(pos);
- }
+ if shape.common.text_box.is_some()
+ && let Some(pos) = vml_absolute_position(&shape.common.style)
+ {
+ return Some(pos);
}
}
None
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 f5127a5..47ff611 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/list_label.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/list_label.rs
@@ -122,20 +122,19 @@ pub(super) fn inject_list_label(
}
fragments.insert(0, label_frag);
- if !drop_separator {
- if let Some(lvl_left) = level_def
+ if !drop_separator
+ && let Some(lvl_left) = level_def
.and_then(|l| l.indentation.as_ref())
.and_then(|ind| ind.start)
- {
- merged_props.tabs.insert(
- 0,
- crate::model::TabStop {
- position: lvl_left,
- alignment: crate::model::TabAlignment::Left,
- leader: crate::model::TabLeader::None,
- },
- );
- }
+ {
+ merged_props.tabs.insert(
+ 0,
+ crate::model::TabStop {
+ position: lvl_left,
+ alignment: crate::model::TabAlignment::Left,
+ leader: crate::model::TabLeader::None,
+ },
+ );
}
} else {
inject_text_label(
diff --git a/crates/liteparse-ooxml/src/render/layout/build/mod.rs b/crates/liteparse-ooxml/src/render/layout/build/mod.rs
index 7c43679..bfe152d 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/mod.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/mod.rs
@@ -307,10 +307,10 @@ fn build_non_story_content(
if frags.is_empty() && block_i + 1 < block_count && !has_floating_anchor {
let (family, mut size, ..) =
resolve_paragraph_defaults(p, ctx.resolved, false, None, None);
- if let Some(ref mrp) = p.mark_run_properties {
- if let Some(fs) = mrp.font_size {
- size = Pt::from(fs);
- }
+ if let Some(ref mrp) = p.mark_run_properties
+ && let Some(fs) = mrp.font_size
+ {
+ size = Pt::from(fs);
}
let line_height = ctx.measurer.default_line_height(&family, size);
frags.push(Fragment::LineBreak { line_height });
diff --git a/crates/liteparse-ooxml/src/render/layout/build/table.rs b/crates/liteparse-ooxml/src/render/layout/build/table.rs
index 98f1d08..ac6d36a 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/table.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/table.rs
@@ -305,15 +305,15 @@ pub(super) fn build_table(
.as_ref()
.and_then(|e| e.cell_spacing)
});
- if let Some(rs) = row_spacing {
- if resolve_cell_spacing(Some(rs)) != cell_spacing && !state.warned_row_cell_spacing
- {
- state.warned_row_cell_spacing = true;
- log::warn!(
- "§17.4.41/§17.4.42: row-level tblCellSpacing overrides are not applied; \
+ if let Some(rs) = row_spacing
+ && resolve_cell_spacing(Some(rs)) != cell_spacing
+ && !state.warned_row_cell_spacing
+ {
+ state.warned_row_cell_spacing = true;
+ log::warn!(
+ "§17.4.41/§17.4.42: row-level tblCellSpacing overrides are not applied; \
using the table-level value ({cell_spacing:?})"
- );
- }
+ );
}
TableRowInput {
diff --git a/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs b/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs
index 5abb845..686977e 100644
--- a/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs
+++ b/crates/liteparse-ooxml/src/render/layout/fragment/collect.rs
@@ -132,13 +132,13 @@ where
if let Some(th) = theme {
crate::render::resolve::fonts::resolve_font_set_themes(&mut effective_props.fonts, th);
}
- if let (Some(style_id), Some(styles)) = (&tr.style_id, resolved_styles) {
- if let Some(resolved_style) = styles.get(style_id) {
- crate::render::resolve::properties::merge_run_properties(
- &mut effective_props,
- &resolved_style.run,
- );
- }
+ if let (Some(style_id), Some(styles)) = (&tr.style_id, resolved_styles)
+ && let Some(resolved_style) = styles.get(style_id)
+ {
+ crate::render::resolve::properties::merge_run_properties(
+ &mut effective_props,
+ &resolved_style.run,
+ );
}
if let Some(para_run) = paragraph_run_defaults {
crate::render::resolve::properties::merge_run_properties(&mut effective_props, para_run);
@@ -678,19 +678,18 @@ where
Inline::Image(img) => {
// Only render INLINE images as fragments.
// Anchor (floating) images are handled separately in build.rs.
- if matches!(img.placement, crate::model::ImagePlacement::Inline { .. }) {
- if let Some(rel_id) =
+ if matches!(img.placement, crate::model::ImagePlacement::Inline { .. })
+ && let Some(rel_id) =
crate::render::resolve::images::extract_image_rel_id(img)
- {
- let w = Pt::from(img.extent.width);
- let h = Pt::from(img.extent.height);
- fragments.push(Fragment::Image {
- size: PtSize::new(w, h),
- rel_id: rel_id.as_str().to_string(),
- image_data: None,
- src_rect: crate::render::resolve::images::extract_src_rect(img),
- });
- }
+ {
+ let w = Pt::from(img.extent.width);
+ let h = Pt::from(img.extent.height);
+ fragments.push(Fragment::Image {
+ size: PtSize::new(w, h),
+ rel_id: rel_id.as_str().to_string(),
+ image_data: None,
+ src_rect: crate::render::resolve::images::extract_src_rect(img),
+ });
}
}
Inline::Hyperlink(link) => {
diff --git a/crates/liteparse-ooxml/src/render/layout/paragraph/borders.rs b/crates/liteparse-ooxml/src/render/layout/paragraph/borders.rs
index 12f452e..c90dd56 100644
--- a/crates/liteparse-ooxml/src/render/layout/paragraph/borders.rs
+++ b/crates/liteparse-ooxml/src/render/layout/paragraph/borders.rs
@@ -134,29 +134,25 @@ pub(super) fn emit_segment_borders_and_shading(
// §17.3.1.24: render paragraph borders at the indent edges. Top/bottom only
// on the owning segment; sides on every segment.
if let Some(ref borders) = style.borders {
- if draw_top {
- if let Some(ref top) = borders.top {
- commands.push(DrawCommand::Line {
- line: crate::render::geometry::PtLineSegment::new(
- PtOffset::new(para_left, box_top),
- PtOffset::new(para_right, box_top),
- ),
- color: top.color,
- width: top.width,
- });
- }
+ if draw_top && let Some(ref top) = borders.top {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(para_left, box_top),
+ PtOffset::new(para_right, box_top),
+ ),
+ color: top.color,
+ width: top.width,
+ });
}
- if draw_bottom {
- if let Some(ref bottom) = borders.bottom {
- commands.push(DrawCommand::Line {
- line: crate::render::geometry::PtLineSegment::new(
- PtOffset::new(para_left, box_bottom),
- PtOffset::new(para_right, box_bottom),
- ),
- color: bottom.color,
- width: bottom.width,
- });
- }
+ if draw_bottom && let Some(ref bottom) = borders.bottom {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(para_left, box_bottom),
+ PtOffset::new(para_right, box_bottom),
+ ),
+ color: bottom.color,
+ width: bottom.width,
+ });
}
if let Some(ref left) = borders.left {
commands.push(DrawCommand::Line {
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 cacc23e..3cf59ca 100644
--- a/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs
+++ b/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs
@@ -1052,26 +1052,25 @@ fn decimal_anchor(
if let Fragment::Text {
text, font, width, ..
} = fragment
+ && let Some(byte_idx) = text.find(separator)
{
- if let Some(byte_idx) = text.find(separator) {
- let prefix = &text[..byte_idx];
- let prefix_width = match measure_text {
- Some(measure) => measure(prefix, font).0,
- // No measurer (fitting-only paths): apportion the
- // fragment's known width by character share. Approximate
- // for proportional faces, but the alternative is ignoring
- // the separator entirely.
- None => {
- let total = text.chars().count();
- if total == 0 {
- Pt::ZERO
- } else {
- *width * (prefix.chars().count() as f32 / total as f32)
- }
+ let prefix = &text[..byte_idx];
+ let prefix_width = match measure_text {
+ Some(measure) => measure(prefix, font).0,
+ // No measurer (fitting-only paths): apportion the
+ // fragment's known width by character share. Approximate
+ // for proportional faces, but the alternative is ignoring
+ // the separator entirely.
+ None => {
+ let total = text.chars().count();
+ if total == 0 {
+ Pt::ZERO
+ } else {
+ *width * (prefix.chars().count() as f32 / total as f32)
}
- };
- return ZoneAnchor::At(before + prefix_width);
- }
+ }
+ };
+ return ZoneAnchor::At(before + prefix_width);
}
before += fragment.width();
}
diff --git a/crates/liteparse-ooxml/src/render/layout/section/layout.rs b/crates/liteparse-ooxml/src/render/layout/section/layout.rs
index 6db6b94..368dd7d 100644
--- a/crates/liteparse-ooxml/src/render/layout/section/layout.rs
+++ b/crates/liteparse-ooxml/src/render/layout/section/layout.rs
@@ -1500,10 +1500,9 @@ pub(crate) fn layout_section_with_clearance(
// with identical borders suppress interior top borders.
if effective_style.borders.is_some()
&& effective_style.borders == state.prev_borders
+ && let Some(ref mut b) = effective_style.borders
{
- if let Some(ref mut b) = effective_style.borders {
- b.top = None;
- }
+ b.top = None;
}
// §17.3.1.9: spacing collapse (must happen before float registration).
if effective_style.contextual_spacing
diff --git a/crates/liteparse-ooxml/src/render/layout/table/emit.rs b/crates/liteparse-ooxml/src/render/layout/table/emit.rs
index f6ba87a..0b37428 100644
--- a/crates/liteparse-ooxml/src/render/layout/table/emit.rs
+++ b/crates/liteparse-ooxml/src/render/layout/table/emit.rs
@@ -127,13 +127,13 @@ fn emit_one_row(
// governs the merged region; letting a continuation paint over the span
// would let a stale or differing `shd` on a row that has no independent
// existence win for that row.
- if cell_input.vertical_merge != Some(VerticalMergeState::Continue) {
- if let Some(color) = cell_input.shading {
- bufs.commands.push(DrawCommand::Rect {
- rect: PtRect::from_xywh(entry.cell_x, row_top, entry.cell_w, effective_h),
- color,
- });
- }
+ if cell_input.vertical_merge != Some(VerticalMergeState::Continue)
+ && let Some(color) = cell_input.shading
+ {
+ bufs.commands.push(DrawCommand::Rect {
+ rect: PtRect::from_xywh(entry.cell_x, row_top, entry.cell_w, effective_h),
+ color,
+ });
}
// §17.4.38: restore the top border when this row starts a slice and the
diff --git a/crates/liteparse-ooxml/src/render/resolve/fonts.rs b/crates/liteparse-ooxml/src/render/resolve/fonts.rs
index d9dce52..3a9569e 100644
--- a/crates/liteparse-ooxml/src/render/resolve/fonts.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/fonts.rs
@@ -94,10 +94,10 @@ pub fn resolve_font_set_themes(fonts: &mut FontSet, theme: &crate::model::Theme)
&mut fonts.east_asian,
&mut fonts.complex_script,
] {
- if let Some(ref tf) = slot.theme {
- if let Some(name) = resolve_theme_font_ref(tf, theme) {
- slot.explicit = Some(name);
- }
+ if let Some(ref tf) = slot.theme
+ && let Some(name) = resolve_theme_font_ref(tf, theme)
+ {
+ slot.explicit = Some(name);
}
}
}
diff --git a/crates/liteparse-ooxml/src/render/resolve/styles.rs b/crates/liteparse-ooxml/src/render/resolve/styles.rs
index cba67c3..756c99e 100644
--- a/crates/liteparse-ooxml/src/render/resolve/styles.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/styles.rs
@@ -106,10 +106,10 @@ fn resolve_one(
}
// Resolve parent first (if any).
- if let Some(ref parent_id) = style.based_on {
- if !resolved.contains_key(parent_id) {
- resolve_one(parent_id, sheet, theme, resolved, visiting);
- }
+ if let Some(ref parent_id) = style.based_on
+ && !resolved.contains_key(parent_id)
+ {
+ resolve_one(parent_id, sheet, theme, resolved, visiting);
}
// Start with own properties.
@@ -123,12 +123,12 @@ fn resolve_one(
// §17.7.2: table property inheritance — cell margins from parent table styles.
let mut table = style.table_properties.clone();
// Merge from resolved parent (if it exists and was successfully resolved).
- if let Some(ref parent_id) = style.based_on {
- if let Some(parent_resolved) = resolved.get(parent_id) {
- merge_paragraph_properties(&mut para, &parent_resolved.paragraph);
- merge_run_properties(&mut run, &parent_resolved.run);
- merge_table_properties(&mut table, &parent_resolved.table);
- }
+ if let Some(ref parent_id) = style.based_on
+ && let Some(parent_resolved) = resolved.get(parent_id)
+ {
+ merge_paragraph_properties(&mut para, &parent_resolved.paragraph);
+ merge_run_properties(&mut run, &parent_resolved.run);
+ merge_table_properties(&mut table, &parent_resolved.table);
}
// §17.7.2: doc defaults are NOT merged here — they are merged by the