A fast, helpful, and open-source document parser
pptx wip
Logan Markewich14189a023dfa
diff --git a/README.md b/README.mdindex 4f53e23..f3b55b2 100644--- a/README.md+++ b/README.md@@ -483,6 +483,34 @@ choco install libreoffice-fresh> _On Windows, you may need to add LibreOffice's program directory (usually `C:\Program Files\LibreOffice\program`) to your PATH._+#### Fonts (optional, affects DOCX geometry)++DOCX files carry no coordinates, so LiteParse lays them out itself and measures the+glyphs to decide where each word lands. A bounding box is therefore only as accurate+as the font behind it — when a document asks for a font you don't have, the measure+falls back to a generic sans and coordinates shift, differently on different machines.+Text and structure are unaffected; this only matters for visual citations, screenshot+highlighting, or cross-host geometry comparisons.++```bash+./scripts/install-fonts.sh # metric clones + common open fonts+./scripts/install-fonts.sh --metric # metric clones only+./scripts/install-fonts.sh --dry-run # print the commands, install nothing+```++Installs only freely-redistributable fonts: metric-compatible clones of the Microsoft+faces (Carlito for Calibri, Caladea for Cambria, Liberation/Croscore for Arial, Times+New Roman and Courier New), plus common open families like Open Sans, Lato and Roboto.+The clones share the originals' advance widths exactly, so geometry becomes+reproducible on any host with the same set.++It does not install Calibri, Aptos, Corbel or Franklin Gothic — those are+Microsoft-licensed. The clones cover Calibri and Cambria exactly; the others have no+free metric equivalent and stay approximate without Microsoft Office installed.++> _On a 45-document corpus this took the share of text measured against a generic+> fallback from 64% to 14%._+#### Images (native support)- **Formats**: `.jpg`, `.jpeg`, `.png`, `.gif`, `.bmp`, `.tiff`, `.webp`, `.svg`diff --git a/crates/liteparse-ooxml/src/render/layout/build/floating.rs b/crates/liteparse-ooxml/src/render/layout/build/floating.rsindex 5a12af6..9336c33 100644--- a/crates/liteparse-ooxml/src/render/layout/build/floating.rs+++ b/crates/liteparse-ooxml/src/render/layout/build/floating.rs@@ -1146,68 +1146,17 @@ fn anchors_to_paragraph(anchor: &crate::model::AnchorProperties) -> bool {)}-/// §20.1.10.60 `ST_TextAnchoringType`: where a shape's text body sits inside-/// the box its insets leave.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum BodyAnchor {- Top,- Center,- Bottom,-}--impl BodyAnchor {- /// Total over `TextAnchoringType`, with the §20.1.2.1.1 default for an- /// absent attribute.- fn resolve(anchor: Option<crate::model::TextAnchoringType>) -> Self {- use crate::model::TextAnchoringType as T;- match anchor {- None | Some(T::Top) => Self::Top,- Some(T::Center) => Self::Center,- Some(T::Bottom) => Self::Bottom,- // §20.1.10.60 `just`/`dist` stretch the *inter-line* spacing to- // fill the box, which this sub-layout has no line-level control- // over. Degrading to `Top` is the closest honest reading: a- // justified body also begins at the top, it simply is not- // stretched to reach the bottom.- Some(anchor @ (T::Justified | T::Distributed)) => {- log::warn!(- "shape text: anchor={anchor:?} distributes lines to fill the body \- (§20.1.10.60), which is not modelled — anchoring to the top instead"- );- Self::Top- }- }- }-- /// How far below the top inset a `text_height`-tall body sits in a- /// `box_height`-tall box.- ///- /// The slack is floored at zero, so a body taller than its box anchors to- /// the top and overflows *downward* whatever the attribute says.- /// `@vertOverflow` defaults to `overflow` — Word draws overflowing shape- /// text rather than clipping it — and centring a body that does not fit- /// would put its first lines above the shape, over whatever sits there. So- /// the choice here is only ever about where the spare room goes. A body- /// that asks for `clip` is trimmed afterwards, in `overflow_keeps`, not by- /// moving it.- fn offset(self, box_height: Pt, text_height: Pt) -> Pt {- let slack = (box_height - text_height).max(Pt::ZERO);- match self {- Self::Top => Pt::ZERO,- Self::Center => slack * 0.5,- Self::Bottom => slack,- }- }-}-/// §17.17.1 / §20.1.2.1.1: lay out a shape's `wps:txbx/w:txbxContent` into/// shape-local draw commands. Output is in shape-local Pt with origin at the/// shape's top-left; the stacker shifts by `(fs.x, shape_y)` when emitting,/// so the text appears inside the shape's bounding box on top of the fill.///-/// Body insets (§20.1.2.1.1 lIns/tIns/rIns/bIns) deflate the box the body is-/// laid out in, and §20.1.10.60 `anchor` places it within that box. The-/// function also runs a fresh `BuildState` for list/footnote counters so the+/// This is the DOCX-shaped **front** half: it turns `w:txbxContent` into+/// `LayoutBlock`s and resolves the `wps:style/fontRef` defaults. The placement+/// half — insets, anchor, `@vertOverflow` — is format-neutral DrawingML and+/// lives in [`crate::render::layout::shape_body`], shared with the PPTX path.+///+/// The function runs a fresh `BuildState` for list/footnote counters so the/// shape's interior doesn't pollute the outer document; `field_ctx` is copied/// so PAGE/NUMPAGES inside a shape's text body still resolve against the host/// page.@@ -1221,23 +1170,11 @@ pub(super) fn build_shape_text_commands(return Vec::new();}- // §20.1.2.1.1 spec defaults: 91440 EMU horizontal, 45720 EMU vertical.- let default_lr = Pt::new(91440.0 / 12700.0); // ≈ 7.2pt- let default_tb = Pt::new(45720.0 / 12700.0); // ≈ 3.6pt- let (left_inset, top_inset, right_inset, bot_inset) =- wsp.body_pr- .as_ref()- .map_or((default_lr, default_tb, default_lr, default_tb), |bp| {- (- bp.left_inset.map_or(default_lr, Pt::from),- bp.top_inset.map_or(default_tb, Pt::from),- bp.right_inset.map_or(default_lr, Pt::from),- bp.bottom_inset.map_or(default_tb, Pt::from),- )- });-- let content_width = (extent.width - left_inset - right_inset).max(Pt::ZERO);- if content_width <= Pt::ZERO {+ // Checked up front so a body with no room to wrap in costs nothing — the+ // shared placement half checks it again, which is cheap and pure, and+ // keeps the bail *before* the fontRef/theme work below rather than after.+ let insets = crate::render::layout::shape_body::BodyInsets::resolve(wsp.body_pr.as_ref());+ if insets.content_width(extent) <= Pt::ZERO {return Vec::new();}@@ -1303,80 +1240,13 @@ pub(super) fn build_shape_text_commands(// height, which is what an empty paragraph and an image-only line fall back// to — otherwise a shrunk body would keep full-size blank lines.let line_height = auto_fit.scale_font(super::default_line_height(ctx));- // Shape text is laid out at *build* time, before the shape is placed on a- // page, so a §20.4.3.1 `inside`/`outside` float nested inside a shape's- // text box has no parity to resolve against and takes the odd-page- // reading. The same structural limit as the table-cell path in- // `layout_cell`, and rarer still.- let result = crate::render::layout::section::stack_blocks(++ crate::render::layout::shape_body::layout_shape_body(&hf.blocks,- content_width,+ extent,+ wsp.body_pr.as_ref(),line_height,- None,- PageParity::Odd,- );-- // §20.1.10.60: `bIns` closes off the bottom of the box the body sits in,- // and `anchor` decides where in that box it sits. Both were previously- // dropped, which pinned every body to the top.- let content_height = (extent.height - top_inset - bot_inset).max(Pt::ZERO);- let anchor = BodyAnchor::resolve(wsp.body_pr.as_ref().and_then(|bp| bp.anchor));- let body_top = top_inset + anchor.offset(content_height, result.height);-- // `@vertOverflow` decides what happens to the part of the body that does- // not fit. `Overflow` — the spec default, and the only value the corpus- // asks for — keeps everything, so the common path is untouched.- let overflow = wsp- .body_pr- .as_ref()- .and_then(|bp| bp.vert_overflow)- .unwrap_or_default();- let box_bottom = top_inset + content_height;-- let mut commands = Vec::with_capacity(result.commands.len());- for mut cmd in result.commands {- cmd.shift(left_inset, body_top);- if !overflow_keeps(overflow, &cmd, box_bottom) {- continue;- }- commands.push(cmd);- }- commands-}--/// Whether `@vertOverflow` keeps `cmd`, given the bottom of the body's box.-///-/// 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.-fn overflow_keeps(- overflow: crate::model::TextVertOverflow,- cmd: &crate::render::layout::draw_command::DrawCommand,- box_bottom: Pt,-) -> bool {- use crate::model::TextVertOverflow;-- match overflow {- TextVertOverflow::Overflow => true,- // `ellipsis` is `clip` plus an indicator on the last visible line.- // Choosing that line and refitting it around the ellipsis glyph is a- // decision this sub-layout does not make, so the indicator is dropped- // and the clipping is honoured — the same text as `clip`, which is far- // closer to Word than not clipping at all.- TextVertOverflow::Clip | TextVertOverflow::Ellipsis => cmd- .vertical_span()- .is_none_or(|(_, bottom)| bottom <= box_bottom),- }+ )}#[cfg(test)]diff --git a/crates/liteparse-ooxml/src/render/layout/fragment/mod.rs b/crates/liteparse-ooxml/src/render/layout/fragment/mod.rsindex 12805f2..dc5945f 100644--- a/crates/liteparse-ooxml/src/render/layout/fragment/mod.rs+++ b/crates/liteparse-ooxml/src/render/layout/fragment/mod.rs@@ -354,6 +354,50 @@ pub fn font_props_from_run(}}+/// Measure one run of text into word-level [`Fragment::Text`]s and append them+/// to `fragments`.+///+/// The format-neutral entry to the fragment builder. The DOCX path reaches the+/// same code through `collect_fragments`, which additionally resolves+/// highlight, run borders, fields, footnote marks and the §17.3.2 run cascade —+/// none of which a DrawingML run has. What both paths must share is the part+/// below that: **where the words break** and **how they are measured**. A+/// second word-splitter would wrap the same sentence differently in a PPTX text+/// box than in a DOCX one, and no test would catch it because neither output is+/// wrong on its own.+///+/// Control characters other than tab are stripped, and emoji clusters are+/// classified and routed to the raster path, exactly as for DOCX.+pub fn emit_run_fragments(+ text: &str,+ font: &FontProps,+ color: RgbColor,+ hyperlink: Option<&LinkTarget>,+ measurer: &crate::render::layout::measurer::TextMeasurer<'_>,+ fragments: &mut Vec<Fragment>,+) {+ let style = text::TextRunStyle {+ color,+ // A DrawingML run carries no §17.3.2.32 shading, no §17.3.2.4 run+ // border, and no baseline shift that this path resolves — `a:rPr`+ // expresses super/subscript as `@baseline`, which the caller applies to+ // the size rather than to the fragment.+ shading: None,+ border: None,+ baseline_offset: Pt::ZERO,+ };+ let measure = |t: &str, f: &FontProps| measurer.measure(t, f);+ text::emit_text_fragments(+ text,+ font,+ &style,+ hyperlink,+ &measure,+ Some(measurer),+ fragments,+ );+}+/// Convert a number to lowercase Roman numerals.pub fn to_roman_lower(mut n: u32) -> String {const VALS: [(u32, &str); 13] = [diff --git a/crates/liteparse-ooxml/src/render/layout/mod.rs b/crates/liteparse-ooxml/src/render/layout/mod.rsindex 52418d4..a560a43 100644--- a/crates/liteparse-ooxml/src/render/layout/mod.rs+++ b/crates/liteparse-ooxml/src/render/layout/mod.rs@@ -13,6 +13,7 @@ pub mod measurer;pub mod page;pub mod paragraph;pub mod section;+pub mod shape_body;pub mod table;use crate::render::dimension::Pt;diff --git a/crates/liteparse-ooxml/src/render/layout/shape_body.rs b/crates/liteparse-ooxml/src/render/layout/shape_body.rsnew file mode 100644index 0000000..3c7bbbc--- /dev/null+++ b/crates/liteparse-ooxml/src/render/layout/shape_body.rs@@ -0,0 +1,320 @@+//! §20.1.2.1.1 / §20.1.10.60: laying a DrawingML text body out inside the+//! rectangle a shape gives it.+//!+//! This is the **format-neutral half** of what `build/floating.rs` does for a+//! `wps:txbx`. Everything here reads `a:bodyPr` and a `Vec<LayoutBlock>` and+//! names no `w:` type, because `a:bodyPr` is DrawingML: a PPTX `p:txBody` and a+//! DOCX `wps:txbx` declare insets, anchor, autofit and overflow with the same+//! element and the same defaults. Only the *front* half — turning markup into+//! `LayoutBlock`s — differs per format, so only that stayed behind.+//!+//! Output is **shape-local Pt with origin at the shape's top-left**. The caller+//! shifts it onto the page (DOCX: the stacker, by `(fs.x, shape_y)`; PPTX: by+//! the shape's `slide_rect` origin).++use crate::render::dimension::Pt;+use crate::render::geometry::PtSize;+use crate::render::layout::draw_command::DrawCommand;+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.+const DEFAULT_INSET_LR: f32 = 91440.0 / 12700.0; // ≈ 7.2pt+const DEFAULT_INSET_TB: f32 = 45720.0 / 12700.0; // ≈ 3.6pt++/// The four §20.1.2.1.1 insets, with defaults applied.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct BodyInsets {+ pub left: Pt,+ pub top: Pt,+ pub right: Pt,+ pub bottom: Pt,+}++impl BodyInsets {+ /// Read the insets off an `a:bodyPr`, substituting the spec default for+ /// each attribute that is absent.+ ///+ /// Insets are **signed** in the schema (`ST_Coordinate32`) and are not+ /// clamped here, matching the parser's deliberate choice not to clamp them.+ /// A negative inset inflates the body past its box, which is what Word+ /// draws.+ pub fn resolve(body_pr: Option<&crate::model::BodyProperties>) -> Self {+ let default_lr = Pt::new(DEFAULT_INSET_LR);+ let default_tb = Pt::new(DEFAULT_INSET_TB);+ match body_pr {+ None => Self {+ left: default_lr,+ top: default_tb,+ right: default_lr,+ bottom: default_tb,+ },+ Some(bp) => Self {+ left: bp.left_inset.map_or(default_lr, Pt::from),+ top: bp.top_inset.map_or(default_tb, Pt::from),+ right: bp.right_inset.map_or(default_lr, Pt::from),+ bottom: bp.bottom_inset.map_or(default_tb, Pt::from),+ },+ }+ }++ /// Width left for the body after the horizontal insets, floored at zero.+ pub fn content_width(&self, extent: PtSize) -> Pt {+ (extent.width - self.left - self.right).max(Pt::ZERO)+ }++ /// Height left for the body after the vertical insets, floored at zero.+ pub fn content_height(&self, extent: PtSize) -> Pt {+ (extent.height - self.top - self.bottom).max(Pt::ZERO)+ }+}++/// §20.1.10.60 `ST_TextAnchoringType`: where a shape's text body sits inside+/// the box its insets leave.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum BodyAnchor {+ Top,+ Center,+ Bottom,+}++impl BodyAnchor {+ /// Total over `TextAnchoringType`, with the §20.1.2.1.1 default for an+ /// absent attribute.+ pub fn resolve(anchor: Option<crate::model::TextAnchoringType>) -> Self {+ use crate::model::TextAnchoringType as T;+ match anchor {+ None | Some(T::Top) => Self::Top,+ Some(T::Center) => Self::Center,+ Some(T::Bottom) => Self::Bottom,+ // §20.1.10.60 `just`/`dist` stretch the *inter-line* spacing to+ // fill the box, which this sub-layout has no line-level control+ // over. Degrading to `Top` is the closest honest reading: a+ // justified body also begins at the top, it simply is not+ // stretched to reach the bottom.+ Some(anchor @ (T::Justified | T::Distributed)) => {+ log::warn!(+ "shape text: anchor={anchor:?} distributes lines to fill the body \+ (§20.1.10.60), which is not modelled — anchoring to the top instead"+ );+ Self::Top+ }+ }+ }++ /// How far below the top inset a `text_height`-tall body sits in a+ /// `box_height`-tall box.+ ///+ /// The slack is floored at zero, so a body taller than its box anchors to+ /// the top and overflows *downward* whatever the attribute says.+ /// `@vertOverflow` defaults to `overflow` — Word draws overflowing shape+ /// text rather than clipping it — and centring a body that does not fit+ /// would put its first lines above the shape, over whatever sits there. So+ /// the choice here is only ever about where the spare room goes. A body+ /// that asks for `clip` is trimmed afterwards, in `overflow_keeps`, not by+ /// moving it.+ pub fn offset(self, box_height: Pt, text_height: Pt) -> Pt {+ let slack = (box_height - text_height).max(Pt::ZERO);+ match self {+ Self::Top => Pt::ZERO,+ Self::Center => slack * 0.5,+ Self::Bottom => slack,+ }+ }+}++/// Lay `blocks` out inside a shape of size `extent`, honouring the body's+/// insets, anchor and `@vertOverflow`.+///+/// Returns shape-local Pt draw commands with origin at the shape's top-left.+/// Returns empty when the insets leave no width to wrap in.+///+/// `line_height` is the fallback line height for content that does not state+/// one (empty paragraphs, image-only lines). The caller is responsible for+/// having already applied any `@fontScale` shrink to it — the same shrink must+/// reach the fragments themselves, which are built before this is called.+///+/// Parity is `Odd`: shape text is laid out before the shape is placed, so a+/// §20.4.3.1 `inside`/`outside` float nested in the body has no parity to+/// resolve against. The same structural limit as the table-cell path.+pub fn layout_shape_body(+ blocks: &[LayoutBlock],+ extent: PtSize,+ body_pr: Option<&crate::model::BodyProperties>,+ line_height: Pt,+) -> Vec<DrawCommand> {+ let insets = BodyInsets::resolve(body_pr);+ let content_width = insets.content_width(extent);+ if content_width <= Pt::ZERO {+ return Vec::new();+ }++ let result = crate::render::layout::section::stack_blocks(+ blocks,+ content_width,+ line_height,+ None,+ PageParity::Odd,+ );++ // §20.1.10.60: `bIns` closes off the bottom of the box the body sits in,+ // and `anchor` decides where in that box it sits.+ let content_height = insets.content_height(extent);+ let anchor = BodyAnchor::resolve(body_pr.and_then(|bp| bp.anchor));+ let body_top = insets.top + anchor.offset(content_height, result.height);++ // `@vertOverflow` decides what happens to the part of the body that does+ // not fit. `Overflow` — the spec default — keeps everything, so the common+ // path is untouched.+ let overflow = body_pr.and_then(|bp| bp.vert_overflow).unwrap_or_default();+ let box_bottom = insets.top + content_height;++ let mut commands = Vec::with_capacity(result.commands.len());+ for mut cmd in result.commands {+ cmd.shift(insets.left, body_top);+ if !overflow_keeps(overflow, &cmd, box_bottom) {+ continue;+ }+ commands.push(cmd);+ }+ commands+}++/// Whether `@vertOverflow` keeps `cmd`, given the bottom of the body's box.+///+/// 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.+fn overflow_keeps(+ overflow: crate::model::TextVertOverflow,+ cmd: &DrawCommand,+ box_bottom: Pt,+) -> bool {+ use crate::model::TextVertOverflow;++ match overflow {+ TextVertOverflow::Overflow => true,+ // `ellipsis` is `clip` plus an indicator on the last visible line.+ // Choosing that line and refitting it around the ellipsis glyph is a+ // decision this sub-layout does not make, so the indicator is dropped+ // and the clipping is honoured — the same text as `clip`, which is far+ // closer to Word than not clipping at all.+ TextVertOverflow::Clip | TextVertOverflow::Ellipsis => cmd+ .vertical_span()+ .is_none_or(|(_, bottom)| bottom <= box_bottom),+ }+}++#[cfg(test)]+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.+ fn body_pr() -> BodyProperties {+ BodyProperties {+ rotation: None,+ vert: None,+ wrap: None,+ left_inset: None,+ top_inset: None,+ right_inset: None,+ bottom_inset: None,+ anchor: None,+ vert_overflow: None,+ auto_fit: None,+ }+ }++ #[test]+ fn absent_bodypr_takes_spec_default_insets() {+ let insets = BodyInsets::resolve(None);+ assert_eq!(insets.left, Pt::new(DEFAULT_INSET_LR));+ assert_eq!(insets.top, Pt::new(DEFAULT_INSET_TB));+ assert_eq!(insets.right, Pt::new(DEFAULT_INSET_LR));+ assert_eq!(insets.bottom, Pt::new(DEFAULT_INSET_TB));+ }++ #[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.+ let insets = BodyInsets::resolve(Some(&body_pr()));+ assert_eq!(insets, BodyInsets::resolve(None));+ }++ #[test]+ fn content_box_floors_at_zero() {+ let insets = BodyInsets::resolve(None);+ let tiny = PtSize {+ width: Pt::new(1.0),+ height: Pt::new(1.0),+ };+ assert_eq!(insets.content_width(tiny), Pt::ZERO);+ assert_eq!(insets.content_height(tiny), Pt::ZERO);+ }++ #[test]+ fn anchor_defaults_to_top_and_degrades_justified() {+ assert_eq!(BodyAnchor::resolve(None), BodyAnchor::Top);+ assert_eq!(+ BodyAnchor::resolve(Some(TextAnchoringType::Center)),+ BodyAnchor::Center+ );+ assert_eq!(+ BodyAnchor::resolve(Some(TextAnchoringType::Justified)),+ BodyAnchor::Top+ );+ assert_eq!(+ BodyAnchor::resolve(Some(TextAnchoringType::Distributed)),+ BodyAnchor::Top+ );+ }++ #[test]+ fn anchor_offset_splits_slack_and_floors_at_zero() {+ let box_h = Pt::new(100.0);+ assert_eq!(BodyAnchor::Top.offset(box_h, Pt::new(40.0)), Pt::ZERO);+ assert_eq!(+ BodyAnchor::Center.offset(box_h, Pt::new(40.0)),+ Pt::new(30.0)+ );+ assert_eq!(+ BodyAnchor::Bottom.offset(box_h, Pt::new(40.0)),+ Pt::new(60.0)+ );+ // Overfull body anchors to the top whatever the attribute says.+ assert_eq!(BodyAnchor::Bottom.offset(box_h, Pt::new(160.0)), Pt::ZERO);+ }++ #[test]+ fn zero_width_body_lays_out_nothing() {+ let tiny = PtSize {+ width: Pt::new(2.0),+ height: Pt::new(50.0),+ };+ assert!(layout_shape_body(&[], tiny, None, Pt::new(12.0)).is_empty());+ }++ #[test]+ fn overflow_default_keeps_everything() {+ assert_eq!(TextVertOverflow::default(), TextVertOverflow::Overflow);+ }+}diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.tomlindex 31ce271..29168fd 100644--- a/crates/liteparse/Cargo.toml+++ b/crates/liteparse/Cargo.toml@@ -22,6 +22,10 @@ required-features = ["docx-native"]name = "pptx_blocks"required-features = ["pptx-native"]+[[example]]+name = "pptx_layout_probe"+required-features = ["pptx-native"]+[features]default = ["tesseract", "docx-native", "pptx-native"]oar-ocr = ["dep:oar-ocr"]diff --git a/crates/liteparse/src/office/mod.rs b/crates/liteparse/src/office/mod.rsindex 0569514..8b2cbaf 100644--- a/crates/liteparse/src/office/mod.rs+++ b/crates/liteparse/src/office/mod.rs@@ -12,12 +12,18 @@#[cfg(feature = "docx-native")]pub mod docx;-#[cfg(feature = "docx-native")]+// Gated on `office-native`, not `docx-native`: `layout_to_pages` and its+// helpers are format-neutral over `&[LayoutedPage]` — only `page_column_counts`+// reads the DOCX model — and the PPTX geometry pass converts through them so+// the two formats cannot disagree on how a baseline becomes a box.+#[cfg(feature = "office-native")]pub mod docx_layout;#[cfg(feature = "office-native")]pub(crate) mod inline;#[cfg(feature = "pptx-native")]pub mod pptx;+#[cfg(feature = "pptx-native")]+pub mod pptx_layout;/// The input's bytes when it is a `.docx` the native path should try, `None`/// otherwise. Path inputs are matched on extension only (`.doc`/`.docm`/@@ -40,3 +46,23 @@ pub(crate) fn docx_bytes(input: &crate::types::PdfInput) -> Option<std::borrow::.then_some(std::borrow::Cow::Borrowed(b.as_slice())),}}++/// The input's bytes when it is a `.pptx` the native path should try, `None`+/// otherwise. Mirrors [`docx_bytes`]: extension-matched for paths (`.ppt`,+/// `.pptm`, `.potx` stay on the conversion path), container-sniffed for bytes.+#[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+pub(crate) fn pptx_bytes(input: &crate::types::PdfInput) -> Option<std::borrow::Cow<'_, [u8]>> {+ use crate::types::PdfInput;+ match input {+ PdfInput::Path(p) => {+ let ext = std::path::Path::new(p).extension()?;+ if !ext.eq_ignore_ascii_case("pptx") {+ return None;+ }+ std::fs::read(p).ok().map(std::borrow::Cow::Owned)+ }+ PdfInput::Bytes(b) => (crate::conversion::guess_extension_from_data(b).as_deref()+ == Some("pptx"))+ .then_some(std::borrow::Cow::Borrowed(b.as_slice())),+ }+}diff --git a/crates/liteparse/src/office/pptx.rs b/crates/liteparse/src/office/pptx.rsindex a55ecfa..2968374 100644--- a/crates/liteparse/src/office/pptx.rs+++ b/crates/liteparse/src/office/pptx.rs@@ -56,6 +56,15 @@ pub struct EmitOptions {pub enum BlockSource {/// Body content of slide `n`, zero-based.Slide(usize),+ /// SmartArt text on slide `n`, zero-based.+ ///+ /// Distinguished from [`BlockSource::Slide`] because the text is not in the+ /// slide part at all — the `p:graphicFrame` holds only `dgm:relIds` and the+ /// content lives in `ppt/diagrams/data*.xml`, laid out by the diagram's own+ /// algorithm. The frame has a rectangle; the runs inside it do not, so a+ /// consumer that needs per-run geometry has to know these blocks cannot+ /// supply it.+ Diagram(usize),/// Speaker notes attached to slide `n`, zero-based.Notes(usize),}@@ -88,72 +97,116 @@ pub fn emit_with_sources(/// Both rungs are keyed by part *path* and rebuilt once per path, never once/// per slide. Every previous PPTX probe records this discipline because a deck/// with 60 slides sharing 3 layouts otherwise reparses those layouts 60 times.-struct Deck {+pub(crate) struct Deck {master_geo: HashMap<String, PlaceholderGeometry>,layout_geo: HashMap<String, PlaceholderGeometry>,master_text: HashMap<String, (PlaceholderTextStyles, DeckTextDefaults)>,layout_text: HashMap<String, PlaceholderTextStyles>,default_text_style: ListStyle,+ /// The rung-7-only defaults a slide falls back to when its master has no+ /// entry. Stored on the deck rather than built as a local in the walk so+ /// that [`PreparedSlide`] can borrow it and every walk builds the *same*+ /// `TextCascade` — see [`Deck::prepare`].+ fallback_defaults: DeckTextDefaults,+}++/// One slide's shapes with their geometry composed and their text cascade+/// assembled — everything a walk needs before it visits a shape.+///+/// This exists so that the markdown walk and the geometry walk cannot drift.+/// They must agree on the composed rectangles and on the cascade, because a+/// `TextItem` is only a faithful box for the markdown a reader sees if both+/// came out of the same resolution. Two copies of this setup would compile,+/// run, and disagree silently.+pub(crate) struct PreparedSlide<'d> {+ pub(crate) shapes: Vec<Shape>,+ layout_text: Option<&'d PlaceholderTextStyles>,+ master_text: Option<&'d PlaceholderTextStyles>,+ deck_defaults: &'d DeckTextDefaults,+}++impl<'d> PreparedSlide<'d> {+ /// The slide-level text cascade (rungs 4-7). Rung 2, the shape's own+ /// `a:lstStyle`, is layered on per text body by the caller.+ pub(crate) fn cascade(&self) -> TextCascade<'d> {+ TextCascade {+ shape: None,+ layout: self.layout_text,+ master: self.master_text,+ deck: Some(self.deck_defaults),+ }+ }}impl Deck {- fn new(pkg: &PresentationPackage) -> Self {+ pub(crate) fn new(pkg: &PresentationPackage) -> Self {+ // Rung 7. A deck whose presentation.xml will not parse still+ // resolves through the earlier rungs, so this degrades to empty+ // rather than failing the deck.+ let default_text_style =+ pptx::parse_default_text_style(&pkg.presentation.xml).unwrap_or_default();Self {master_geo: HashMap::new(),layout_geo: HashMap::new(),master_text: HashMap::new(),layout_text: HashMap::new(),- // Rung 7. A deck whose presentation.xml will not parse still- // resolves through the earlier rungs, so this degrades to empty- // rather than failing the deck.- default_text_style: pptx::parse_default_text_style(&pkg.presentation.xml)- .unwrap_or_default(),+ fallback_defaults: DeckTextDefaults {+ master_styles: TextStyles::default(),+ default_text_style: default_text_style.clone(),+ },+ default_text_style,}}+ /// Prime the cascades for this slide's layout/master, parse its shape+ /// tree, and compose its geometry.+ ///+ /// `None` when the shape tree will not parse — fail-open, the same slide+ /// is skipped by every walk.+ pub(crate) fn prepare(&mut self, slide: &pptx::SlideParts) -> Option<PreparedSlide<'_>> {+ self.prime(slide);++ let mut shapes = pptx::parse_shape_tree(&slide.slide.xml).ok()?;+ let layout_geo = slide+ .layout+ .as_ref()+ .and_then(|l| self.layout_geo.get(&l.path));+ // Cascade before composition: a placeholder has no rectangle to+ // compose until it has inherited one.+ pptx::apply_inherited_geometry(&mut shapes, layout_geo, MatchRule::Idx);+ pptx::apply_slide_geometry(&mut shapes);++ let master = slide+ .master+ .as_ref()+ .and_then(|m| self.master_text.get(&m.path));+ Some(PreparedSlide {+ shapes,+ layout_text: slide+ .layout+ .as_ref()+ .and_then(|l| self.layout_text.get(&l.path)),+ master_text: master.map(|(p, _)| p),+ deck_defaults: master.map_or(&self.fallback_defaults, |(_, d)| d),+ })+ }+fn emit(&mut self, pkg: &PresentationPackage, opts: EmitOptions) -> Vec<(Block, BlockSource)> {let mut out = Vec::new();for (idx, slide) in pkg.slides.iter().enumerate() {- self.prime(slide);-- let Ok(mut shapes) = pptx::parse_shape_tree(&slide.slide.xml) else {+ let Some(prepared) = self.prepare(slide) else {continue;};- let layout_geo = slide- .layout- .as_ref()- .and_then(|l| self.layout_geo.get(&l.path));- // Cascade before composition: a placeholder has no rectangle to- // compose until it has inherited one.- pptx::apply_inherited_geometry(&mut shapes, layout_geo, MatchRule::Idx);- pptx::apply_slide_geometry(&mut shapes);-- let fallback = DeckTextDefaults {- master_styles: TextStyles::default(),- default_text_style: self.default_text_style.clone(),- };- let master = slide- .master- .as_ref()- .and_then(|m| self.master_text.get(&m.path));- let cascade = TextCascade {- shape: None,- layout: slide- .layout- .as_ref()- .and_then(|l| self.layout_text.get(&l.path)),- master: master.map(|(p, _)| p),- deck: Some(master.map_or(&fallback, |(_, d)| d)),- };+ let shapes = &prepared.shapes;let mut ctx = SlideCtx {- cascade,+ cascade: prepared.cascade(),part: &slide.slide,package: &pkg.package,opts,};- for shape in reading_order(&shapes) {+ for shape in reading_order(shapes) {emit_shape(shape, &mut ctx, &mut out, BlockSource::Slide(idx));}@@ -237,7 +290,7 @@ struct SlideCtx<'a> {/// A group is one unit. Its children are emitted in their own reading order/// within it, so a two-column group does not interleave with unrelated shapes/// elsewhere on the slide.-fn reading_order(shapes: &[Shape]) -> Vec<&Shape> {+pub(crate) fn reading_order(shapes: &[Shape]) -> Vec<&Shape> {let mut v: Vec<&Shape> = shapes.iter().filter(|s| !is_chrome(s.placeholder.as_ref()))@@ -259,7 +312,7 @@ fn reading_order(shapes: &[Shape]) -> Vec<&Shape> {v}-fn is_title(ph: Option<&Placeholder>) -> bool {+pub(crate) fn is_title(ph: Option<&Placeholder>) -> bool {matches!(ph.map(|p| p.kind),Some(PlaceholderKind::Title | PlaceholderKind::CtrTitle)@@ -574,6 +627,10 @@ fn emit_diagram(let Ok(bodies) = pptx::parse_diagram_text(xml) else {return;};+ let src = match src {+ BlockSource::Slide(n) | BlockSource::Diagram(n) => BlockSource::Diagram(n),+ BlockSource::Notes(n) => BlockSource::Notes(n),+ };for body in &bodies {emit_text_body(body, None, ctx, out, src);}diff --git a/crates/liteparse/src/office/pptx_layout.rs b/crates/liteparse/src/office/pptx_layout.rsnew file mode 100644index 0000000..c377a57--- /dev/null+++ b/crates/liteparse/src/office/pptx_layout.rs@@ -0,0 +1,609 @@+//! Per-run PPTX geometry: `p:txBody` → measured lines → [`TextItem`]s.+//!+//! [`super::pptx`] needs only shape rectangles, and PPTX hands those over+//! directly — `<a:off>`/`<a:ext>` are absolute EMU and `pptx::geometry` has+//! already composed group coordinate spaces into `Shape::slide_rect`. **Below+//! the shape there are no coordinates at all.** A paragraph does not say where+//! its lines fall, and a run does not say how wide it is; both are derived by+//! 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.+//!+//! What is genuinely new here, and what the census said each would cost:+//!+//! | 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 |+//!+//! Rotation is applied here rather than inside the shared converter because+//! `DrawCommand::Text` carries no rotation field — it is emitted pre-shifted but+//! un-rotated, and the DOCX painter rotates the whole shape instead. Adding one+//! would touch an enum that is matched exhaustively across the vendored crate by+//! design. Each shape is therefore converted on its own and its items are+//! rotated about the shape centre on the way onto the slide.+//!+//! Reading order and the text cascade both come from [`super::pptx`], through+//! `Deck::prepare`, so a `TextItem` is a box for exactly the text the markdown+//! emitter saw, resolved the same way.++use liteparse_ooxml::model::{Alignment, Theme};+use liteparse_ooxml::pptx::{+ self, PresentationPackage, ResolvedTextStyle, Shape, ShapeKind, Spacing, TextBody, TextCascade,+ TextParagraph,+};+use liteparse_ooxml::render::dimension::Pt;+use liteparse_ooxml::render::fonts::FontRegistry;+use liteparse_ooxml::render::geometry::PtSize;+use liteparse_ooxml::render::layout::ShapeAutoFit;+use liteparse_ooxml::render::layout::draw_command::LayoutedPage;+use liteparse_ooxml::render::layout::fragment::{+ Fragment, emit_run_fragments, font_props_from_run,+};+use liteparse_ooxml::render::layout::measurer::TextMeasurer;+use liteparse_ooxml::render::layout::paragraph::{LineSpacingRule, ParagraphStyle};+use liteparse_ooxml::render::layout::section::LayoutBlock;+use liteparse_ooxml::render::layout::shape_body::layout_shape_body;+use liteparse_ooxml::render::resolve::color::RgbColor;+use liteparse_ooxml::render::resolve::fonts::resolve_font_set_themes;++use crate::error::LiteParseError;+use crate::office::docx_layout;+use crate::office::pptx::{Deck, is_title, reading_order};+use crate::types::{Page, TextItem};++/// EMU per point (§20.1.2.1: 914400 EMU/inch ÷ 72 pt/inch).+const EMU_PER_POINT: f32 = 12700.0;++/// §20.1.10.60 `@rot` is in 60000ths of a degree.+const ANGLE_UNITS_PER_DEGREE: f32 = 60000.0;++/// What a deck's geometry pass produced, plus what it could not place.+///+/// The counters are not diagnostics — they are the honest half of the result.+/// Two content classes carry text that this pass does not yet position, and a+/// consumer that saw only `pages` would read their absence as "the slide had no+/// such text" rather than "this pass cannot place it yet".+pub struct SlideGeometry {+ /// One page per slide, in presentation order. Page count always equals+ /// slide count, so a page index is a slide index.+ pub pages: Vec<Page>,+ /// Per page, the shape each run of items came from. Parallel to `pages`.+ ///+ /// Derived geometry has no external oracle — PPTX declares no coordinate+ /// below the shape, so there is nothing to diff a line box against. The+ /// one check that *is* available is that a shape's text lands inside the+ /// box that shape gave it, and that requires knowing which shape each item+ /// came from. Kept on the result rather than recomputed by a probe because+ /// a probe that re-derived the association would be re-deriving the thing+ /// under test.+ pub placements: Vec<Vec<ShapePlacement>>,+ /// Table cells carrying text. Their rectangles come from `a:gridCol`+ /// prefix sums and `a:tr@h`, not from a shape rect, which is a second+ /// layout path — and `a:tcPr` (cell margins, per-cell anchor) is not+ /// parsed at all today, so laying them out against spec defaults would put+ /// every cell's text at the wrong inset.+ pub unplaced_table_cells: usize,+ /// SmartArt text bodies. The frame has a rect, but the text lives in+ /// `ppt/diagrams/data*.xml` with its own layout algorithm; the markdown+ /// emitter places the *frame* in reading order, which is a weaker claim+ /// than a per-run box.+ pub unplaced_diagram_bodies: usize,+}++/// Where one text shape's items landed on its slide.+pub struct ShapePlacement {+ /// The shape's unrotated rectangle in slide Pt: `(x, y, width, height)`.+ pub rect: (f32, f32, f32, f32),+ /// Counter-clockwise degrees, matching [`TextItem::rotation`].+ pub rotation: f32,+ /// Whether the body's `a:normAutofit` shrinks it (`@fontScale` < 100%).+ pub shrunk: bool,+ /// Half-open range into the page's `text_items`.+ pub items: std::ops::Range<usize>,+}++/// Lay every slide out and return one [`Page`] per slide.+///+/// `registry` must be the registry the caller intends to measure with; it is+/// threaded to both the measurer used here and the converter, which re-measures+/// to recover each item's box. Passing two different registries would produce+/// boxes that do not match the layout that placed them.+pub fn slides_to_pages(+ data: &[u8],+ registry: &FontRegistry,+) -> Result<SlideGeometry, LiteParseError> {+ let pkg = pptx::walk(data)+ .map_err(|e| LiteParseError::Conversion(format!("pptx parse failed: {e}")))?;+ Ok(layout_deck(&pkg, registry))+}++fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeometry {+ // Parsed once per deck. `pkg.theme` is the first master's theme — a+ // multi-master deck loses the per-master theme, which `pptx::walk` already+ // documents as a known limit of the package walk rather than of this pass.+ let theme = pkg+ .theme+ .as_ref()+ .and_then(|bytes| liteparse_ooxml::docx::parse::theme::parse_theme(bytes).ok());++ let measurer = TextMeasurer::new(registry);+ let (slide_w, slide_h) = pkg.info.slide_size_pt();+ let page_size = PtSize {+ width: Pt::new(slide_w as f32),+ height: Pt::new(slide_h as f32),+ };++ let mut deck = Deck::new(pkg);+ let mut out = SlideGeometry {+ pages: Vec::with_capacity(pkg.slides.len()),+ placements: Vec::with_capacity(pkg.slides.len()),+ unplaced_table_cells: 0,+ unplaced_diagram_bodies: 0,+ };++ for (idx, slide) in pkg.slides.iter().enumerate() {+ let mut items = Vec::new();+ let mut placements = Vec::new();+ // A slide whose shape tree will not parse still yields a page. Page+ // count must equal slide count — a consumer indexes pages by slide.+ if let Some(prepared) = deck.prepare(slide) {+ let cascade = prepared.cascade();+ let mut ctx = ShapeCtx {+ cascade,+ theme: theme.as_ref(),+ measurer: &measurer,+ registry,+ items: &mut items,+ placements: &mut placements,+ unplaced_table_cells: &mut out.unplaced_table_cells,+ unplaced_diagram_bodies: &mut out.unplaced_diagram_bodies,+ };+ for shape in reading_order(&prepared.shapes) {+ layout_shape(shape, &mut ctx);+ }+ }++ out.placements.push(placements);+ let content_bounds = union_bounds(&items);+ out.pages.push(Page {+ page_number: idx + 1,+ page_width: page_size.width.raw(),+ page_height: page_size.height.raw(),+ content_bounds,+ text_items: items,+ graphics: Vec::new(),+ vector_graphics: None,+ struct_nodes: Vec::new(),+ image_refs: Vec::new(),+ annotations: None,+ form_fields: None,+ structure_tree: None,+ });+ }++ out+}++struct ShapeCtx<'a, 'r> {+ cascade: TextCascade<'a>,+ theme: Option<&'a Theme>,+ measurer: &'a TextMeasurer<'r>,+ registry: &'a FontRegistry,+ items: &'a mut Vec<TextItem>,+ placements: &'a mut Vec<ShapePlacement>,+ unplaced_table_cells: &'a mut usize,+ unplaced_diagram_bodies: &'a mut usize,+}++fn layout_shape(shape: &Shape, ctx: &mut ShapeCtx<'_, '_>) {+ match &shape.kind {+ ShapeKind::AutoShape(sp) => {+ if let Some(body) = &sp.text {+ layout_text_shape(shape, body, ctx);+ }+ }+ ShapeKind::Group(group) => {+ // Children carry composed `slide_rect`s already, so a group needs+ // no coordinate work here — only the same reading order the+ // markdown emitter applies within it.+ for child in reading_order(&group.children) {+ layout_shape(child, ctx);+ }+ }+ ShapeKind::GraphicFrame(frame) => match &frame.payload {+ pptx::GraphicFramePayload::Table(table) => {+ *ctx.unplaced_table_cells += table+ .rows+ .iter()+ .flat_map(|r| r.cells.iter())+ .filter(|c| c.text.as_ref().is_some_and(|t| !t.is_empty()))+ .count();+ }+ pptx::GraphicFramePayload::Diagram { .. } => *ctx.unplaced_diagram_bodies += 1,+ pptx::GraphicFramePayload::Unsupported { .. } => {}+ },+ ShapeKind::Picture(_) | ShapeKind::Connector(_) => {}+ }+}++/// Lay one shape's text body out inside its rectangle and append the resulting+/// 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.+ let Some(slide_rect) = shape.slide_rect else {+ return;+ };+ let extent = PtSize {+ width: emu_to_pt(slide_rect.rect.size.width.raw()),+ height: emu_to_pt(slide_rect.rect.size.height.raw()),+ };+ if extent.width <= Pt::ZERO || extent.height <= Pt::ZERO {+ return;+ }++ let title = is_title(shape.placeholder.as_ref());+ // Rung 2 is the shape's own list style, exactly as the markdown emitter+ // layers it on.+ let cascade = TextCascade {+ shape: Some(&body.list_style),+ ..ctx.cascade+ };+ let auto_fit = ShapeAutoFit::from_body(body.body_pr.as_ref().and_then(|bp| bp.auto_fit));+ let default_family = theme_family(ctx.theme, title);++ let mut blocks = Vec::with_capacity(body.paragraphs.len());+ for para in &body.paragraphs {+ let resolved = cascade.resolve(¶.properties, shape.placeholder.as_ref());+ blocks.push(paragraph_block(+ para,+ &resolved,+ &default_family,+ auto_fit,+ ctx,+ ));+ }++ // The fallback height for a line that states none — an empty paragraph+ // between two bullets. Scaled by the body's own shrink, for the same reason+ // the DOCX path scales it: otherwise a shrunk body keeps full-size blanks.+ let line_height = auto_fit.scale_font(+ ctx.measurer+ .default_line_height(&default_family, spec_default_size()),+ );++ let commands = layout_shape_body(&blocks, extent, body.body_pr.as_ref(), line_height);+ if commands.is_empty() {+ return;+ }++ // Convert through the DOCX path's own `DrawCommand` → `TextItem` code, on a+ // synthetic page the size of the shape, so the two formats agree on how a+ // baseline becomes a box (ascent above, descent below, width re-measured).+ let shape_page = LayoutedPage {+ commands,+ page_size: extent,+ block_starts: Vec::new(),+ };+ let converted = docx_layout::layout_to_pages(&[shape_page], ctx.registry, false, false);+ let Some(page) = converted.pages.into_iter().next() else {+ return;+ };++ let origin_x = emu_to_pt(slide_rect.rect.origin.x.raw()).raw();+ let origin_y = emu_to_pt(slide_rect.rect.origin.y.raw()).raw();+ // OOXML `@rot` is clockwise-positive; `TextItem::rotation` is+ // counter-clockwise degrees.+ let rot_deg = slide_rect.rotation.raw() as f32 / ANGLE_UNITS_PER_DEGREE;+ let rotate = rot_deg != 0.0;+ let (cx, cy) = (extent.width.raw() * 0.5, extent.height.raw() * 0.5);+ let (sin, cos) = (rot_deg.to_radians().sin(), rot_deg.to_radians().cos());++ let first_item = ctx.items.len();+ for mut item in page.text_items {+ if rotate {+ // Rotate the box's top-left about the shape centre, in shape-local+ // space, then translate. The item keeps its unrotated width and+ // height and states its angle, matching how the PDF path reports a+ // rotated run — a rotated AABB would silently widen every box.+ let (dx, dy) = (item.x - cx, item.y - cy);+ item.x = cx + dx * cos - dy * sin;+ item.y = cy + dx * sin + dy * cos;+ item.rotation = -rot_deg;+ }+ item.x += origin_x;+ item.y += origin_y;+ ctx.items.push(item);+ }++ ctx.placements.push(ShapePlacement {+ rect: (origin_x, origin_y, extent.width.raw(), extent.height.raw()),+ rotation: -rot_deg,+ shrunk: auto_fit != ShapeAutoFit::NONE,+ items: first_item..ctx.items.len(),+ });+}++/// One `a:p` as a [`LayoutBlock::Paragraph`], with every run measured.+fn paragraph_block(+ para: &TextParagraph,+ resolved: &ResolvedTextStyle,+ default_family: &str,+ auto_fit: ShapeAutoFit,+ ctx: &mut ShapeCtx<'_, '_>,+) -> LayoutBlock {+ let mut fragments = Vec::new();+ collect_run_fragments(+ ¶.content,+ resolved,+ default_family,+ auto_fit,+ ctx,+ &mut fragments,+ );++ LayoutBlock::Paragraph {+ fragments,+ style: paragraph_style(resolved, auto_fit),+ page_break_before: false,+ footnotes: Vec::new(),+ floating_images: Vec::new(),+ floating_shapes: Vec::new(),+ }+}++fn collect_run_fragments(+ inlines: &[liteparse_ooxml::model::Inline],+ resolved: &ResolvedTextStyle,+ default_family: &str,+ auto_fit: ShapeAutoFit,+ ctx: &mut ShapeCtx<'_, '_>,+ fragments: &mut Vec<Fragment>,+) {+ use liteparse_ooxml::model::{Inline, RunElement};++ for inline in inlines {+ match inline {+ Inline::TextRun(run) => {+ let mut props = run.properties.clone();+ resolved.apply_to_run(&mut props);+ // The cascade resolves size but has no font rung, so a run that+ // named `+mn-lt` still carries a `ThemeFontRef` here and a run+ // that named nothing carries neither. Resolve the reference,+ // then let `font_props_from_run` fall back to the theme face+ // for the 26.3% that named no family at all.+ if let Some(theme) = ctx.theme {+ resolve_font_set_themes(&mut props.fonts, theme);+ }+ let font = font_props_from_run(+ &props,+ default_family,+ // `apply_to_run` guarantees a size — `run_defaults.font_size`+ // is always `Some` — so this is unreachable in practice and+ // is the §20.1.2.1 spec default rather than a guess.+ spec_default_size(),+ auto_fit,+ );+ let color = RgbColor { r: 0, g: 0, b: 0 };+ for element in &run.content {+ match element {+ RunElement::Text(text) => {+ emit_run_fragments(text, &font, color, None, ctx.measurer, fragments)+ }+ RunElement::Tab => fragments.push(Fragment::Tab {+ line_height: font.size,+ font: std::rc::Rc::new(font.clone()),+ color,+ fitting_width: None,+ }),+ RunElement::LineBreak(_) => fragments.push(Fragment::LineBreak {+ line_height: font.size,+ }),+ _ => {}+ }+ }+ }+ Inline::Hyperlink(link) => {+ collect_run_fragments(+ &link.content,+ resolved,+ default_family,+ auto_fit,+ ctx,+ fragments,+ );+ }+ _ => {}+ }+ }+}++fn paragraph_style(resolved: &ResolvedTextStyle, auto_fit: ShapeAutoFit) -> ParagraphStyle {+ let size = resolved+ .run_defaults+ .font_size+ .map(Pt::from)+ .unwrap_or_else(spec_default_size);++ ParagraphStyle {+ alignment: resolved.alignment.unwrap_or(Alignment::Start),+ space_before: spacing_to_pt(resolved.space_before, size),+ space_after: spacing_to_pt(resolved.space_after, size),+ // §21.1.2.2.7 `@marL` is the left edge of the whole paragraph and+ // `@indent` is the first line's offset from it — the same split as+ // §17.3.1.12's `left`/`firstLine`, and a hanging indent is negative in+ // both. So these map across directly.+ indent_left: resolved.margin_left.map(Pt::from).unwrap_or(Pt::ZERO),+ indent_right: resolved.margin_right.map(Pt::from).unwrap_or(Pt::ZERO),+ indent_first_line: resolved.indent.map(Pt::from).unwrap_or(Pt::ZERO),+ line_spacing: match resolved.line_spacing {+ // `a:spcPct` is a multiple of the line's natural height, which is+ // exactly what `Auto` means here.+ Some(Spacing::Percent(p)) => LineSpacingRule::Auto(p.to_fraction()),+ // `a:spcPts` is an absolute height, and DrawingML treats it as a+ // minimum rather than a cap.+ Some(Spacing::Points(p)) => LineSpacingRule::AtLeast(Pt::new(p.to_points_f32())),+ None => LineSpacingRule::Auto(1.0),+ },+ auto_fit,+ default_tab_stop: resolved+ .default_tab_size+ .map(Pt::from)+ .unwrap_or(Pt::new(36.0)),+ ..ParagraphStyle::default()+ }+}++/// `a:spcBef`/`a:spcAft` as a height.+///+/// The percentage form is a percentage **of the font size**, not of the line+/// box — §21.1.2.2.9 defines it against the text size — so it needs the+/// paragraph's resolved size to become a length.+fn spacing_to_pt(spacing: Option<Spacing>, size: Pt) -> Pt {+ match spacing {+ Some(Spacing::Percent(p)) => Pt::new(size.raw() * p.to_fraction()),+ Some(Spacing::Points(p)) => Pt::new(p.to_points_f32()),+ None => Pt::ZERO,+ }+}++/// The theme face a run falls back to when it names no family: `+mj-lt` for a+/// title, `+mn-lt` for everything else (§20.1.4.1.24/§20.1.4.1.26).+///+/// Falls through to the measurer's own generic handling when the deck has no+/// theme or the theme names no latin face — which is host-dependent, and is+/// reported as such by the probe's `ResolveRule` histogram rather than hidden.+fn theme_family(theme: Option<&Theme>, title: bool) -> String {+ let latin = theme.map(|t| {+ if title {+ t.major_font.latin.clone()+ } else {+ t.minor_font.latin.clone()+ }+ });+ match latin {+ Some(f) if !f.is_empty() => f,+ _ => "Arial".to_string(),+ }+}++/// §21.1.2.2.10: the size a run takes when nothing in the cascade supplies one.+/// Matches `pptx::textcascade`'s own spec-default rung (1800 hundredths = 18pt).+fn spec_default_size() -> Pt {+ Pt::new(18.0)+}++fn emu_to_pt(emu: i64) -> Pt {+ Pt::new(emu as f32 / EMU_PER_POINT)+}++fn union_bounds(items: &[TextItem]) -> Option<crate::types::Rect> {+ let first = items.first()?;+ let mut left = first.x;+ let mut top = first.y;+ let mut right = first.x + first.width;+ let mut bottom = first.y + first.height;+ for item in items.iter().skip(1) {+ left = left.min(item.x);+ top = top.min(item.y);+ right = right.max(item.x + item.width);+ bottom = bottom.max(item.y + item.height);+ }+ Some(crate::types::Rect {+ x: left,+ y: top,+ width: right - left,+ height: bottom - top,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use liteparse_ooxml::model::{ThemeFontScheme, dimension::Dimension};++ fn theme_with(major: &str, minor: &str) -> Theme {+ Theme {+ major_font: ThemeFontScheme {+ latin: major.to_string(),+ ..Default::default()+ },+ minor_font: ThemeFontScheme {+ latin: minor.to_string(),+ ..Default::default()+ },+ ..Default::default()+ }+ }++ #[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.+ let theme = theme_with("Georgia", "Verdana");+ assert_eq!(theme_family(Some(&theme), true), "Georgia");+ assert_eq!(theme_family(Some(&theme), false), "Verdana");+ }++ #[test]+ fn theme_font_falls_back_when_absent_or_empty() {+ assert_eq!(theme_family(None, false), "Arial");+ let empty = theme_with("", "");+ assert_eq!(theme_family(Some(&empty), true), "Arial");+ }++ #[test]+ fn percent_spacing_is_a_fraction_of_the_font_size() {+ // §21.1.2.2.9 measures `a:spcPct` against the text size, not the line+ // box. Reading it as a line multiple would scale every gap by the+ // wrong base.+ let size = Pt::new(20.0);+ // 50000 thousandths of a percent = 50%.+ let half = Spacing::Percent(Dimension::new(50_000));+ assert_eq!(spacing_to_pt(Some(half), size), Pt::new(10.0));+ assert_eq!(spacing_to_pt(None, size), Pt::ZERO);+ }++ #[test]+ fn points_spacing_is_absolute() {+ // `a:spcPts` is in hundredths of a point.+ let pts = Spacing::Points(Dimension::new(1_200));+ assert_eq!(spacing_to_pt(Some(pts), Pt::new(20.0)), Pt::new(12.0));+ }++ #[test]+ fn emu_converts_at_12700_per_point() {+ assert_eq!(emu_to_pt(914_400), Pt::new(72.0));+ assert_eq!(emu_to_pt(0), Pt::ZERO);+ }++ #[test]+ fn union_bounds_spans_every_item() {+ let item = |x: f32, y: f32, w: f32, h: f32| TextItem {+ x,+ y,+ width: w,+ height: h,+ ..TextItem::default()+ };+ assert!(union_bounds(&[]).is_none());+ let r = union_bounds(&[item(10.0, 20.0, 5.0, 5.0), item(3.0, 40.0, 2.0, 2.0)]).unwrap();+ assert_eq!((r.x, r.y), (3.0, 20.0));+ assert_eq!((r.width, r.height), (12.0, 22.0));+ }+}diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex a894b0d..c875170 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -406,6 +406,41 @@ impl LiteParse {}}+ // Native PPTX path, same contract as the DOCX one above: engine+ // failures fall through to LibreOffice, an unsupported option is a hard+ // error rather than a silent engine swap.+ #[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+ if self.config.office_native {+ if let Some(reason) = self.native_pptx_ineligible_reason() {+ if crate::office::pptx_bytes(&input).is_some() {+ return Err(LiteParseError::Config(format!(+ "`{reason}` is not supported by the native PPTX path; \+ disable it, or set office_native = false \+ (CLI: --no-office-native) to parse via the conversion path"+ )));+ }+ } else if let Some(bytes) = crate::office::pptx_bytes(&input) {+ match self.try_parse_pptx_native(&bytes) {+ Ok(Some(result)) => {+ let total =+ web_time::Instant::now().duration_since(t0).as_secs_f64() * 1000.0;+ log(&format!("[liteparse] native pptx total: {:.1}ms", total));+ return Ok(result);+ }+ Ok(None) => {+ log(+ "[liteparse] office_native: text-sparse pptx, falling back to conversion path for OCR",+ );+ }+ Err(e) => {+ log(&format!(+ "[liteparse] office_native failed ({e}); falling back to conversion path"+ ));+ }+ }+ }+ }+#[cfg(not(target_arch = "wasm32"))]let (validated_input, _guard) =conversion::resolve_pdf_input(input, self.config.password.as_deref(), false).await?;@@ -790,6 +825,173 @@ impl LiteParse {}}+ /// Config options the native PPTX path cannot honor. Hitting one with+ /// `office_native` on is a hard `Config` error, not a fallback.+ ///+ /// Two entries are PPTX-specific and are here because the alternative is+ /// silent under-delivery:+ ///+ /// * `extract_images` — the PPTX reader does not extract media at all yet+ /// (`ShapeKind::Picture` emits nothing), so an enabled flag would hand+ /// back an empty list rather than the deck's pictures.+ /// * `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`.+ ///+ /// `image_mode` is deliberately *not* here. Pictures already emit nothing+ /// on the markdown path this ships beside, so a placeholder-mode parse gets+ /// exactly what the (benchmarked) emitter has always produced; promoting+ /// that long-standing content gap to a hard error would reject the default+ /// config.+ #[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+ fn native_pptx_ineligible_reason(&self) -> Option<&'static str> {+ let c = &self.config;+ if c.extract_form_fields {+ Some("extract_form_fields")+ } else if c.extract_structure_tree {+ Some("extract_structure_tree")+ } else if c.extract_vector_graphics {+ Some("extract_vector_graphics")+ } else if c.crop_box.is_some() {+ Some("crop_box")+ } else if c.skip_diagonal_text {+ Some("skip_diagonal_text")+ } else if c.effective_extract_images() {+ Some("extract_images")+ } else if c.extract_annotations {+ Some("extract_annotations")+ } else {+ None+ }+ }++ /// Run the native PPTX pipeline. Contract matches the DOCX sibling:+ /// `Ok(None)` is an eligible fallback (text-sparse deck with OCR on), and+ /// panics map to `Err` so the caller degrades to LibreOffice.+ #[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+ fn try_parse_pptx_native(&self, data: &[u8]) -> Result<Option<ParseResult>, LiteParseError> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ self.parse_pptx_native_inner(data)+ }))+ .unwrap_or_else(|_| {+ Err(LiteParseError::Conversion(+ "native pptx layout panicked".to_string(),+ ))+ })+ }++ #[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+ fn parse_pptx_native_inner(&self, data: &[u8]) -> Result<Option<ParseResult>, LiteParseError> {+ use crate::office::{pptx, pptx_layout};++ // A deck embeds no fonts, so unlike the DOCX path there is nothing to+ // register — but the registry must still be the *same* one the geometry+ // pass measures with, since the converter re-measures each item.+ let registry = liteparse_ooxml::render::fonts::FontRegistry::build(&[], &[])+ .map_err(|e| LiteParseError::Conversion(format!("font registry: {e}")))?;+ let geo = pptx_layout::slides_to_pages(data, ®istry)?;++ if self.config.ocr_enabled {+ let total_chars: usize = geo+ .pages+ .iter()+ .flat_map(|p| &p.text_items)+ .map(|i| i.text.trim().len())+ .sum();+ if total_chars < Self::NATIVE_TEXT_SPARSE_CHARS {+ return Ok(None);+ }+ }++ let tagged = pptx::emit_with_sources(+ 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).+ notes: true,+ },+ )?;+ let n_pages = geo.pages.len();+ let page_blocks = split_pptx_blocks_by_page(&tagged, n_pages);+ let outline = pptx_slide_outline(&page_blocks);+ let all_blocks: Vec<crate::markdown_layout::Block> =+ tagged.into_iter().map(|(b, _)| b).collect();++ let complexity: Vec<Option<crate::ocr_merge::PageComplexityStats>> =+ if self.config.include_complexity {+ geo.pages+ .iter()+ .enumerate()+ .map(|(i, p)| {+ let tables = page_blocks[i]+ .iter()+ .filter(|b| {+ matches!(+ b,+ crate::markdown_layout::Block::Table { .. }+ | crate::markdown_layout::Block::MergedTable { .. }+ )+ })+ .count();+ // No image rects: the reader does not place pictures+ // yet. A slide's column count is 1 — PPTX has no+ // section columns, and shapes are not columns.+ Some(crate::ocr_merge::calculate_native_page_complexity(+ p,+ &[],+ tables,+ 1,+ ))+ })+ .collect()+ } else {+ vec![None; n_pages]+ };++ // 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);+ }++ Ok(Some(self.parse_from_native_blocks(+ pages,+ page_blocks,+ (!page_filtered).then_some(all_blocks),+ outline,+ Vec::new(),+ page_stats,+ )))+ }+/// Run the native DOCX pipeline. `Ok(None)` means "eligible fallback":/// the document is text-sparse and OCR is enabled, so the conversion path/// (which can OCR embedded images) serves the caller better. Panics from@@ -1232,6 +1434,76 @@ impl LiteParse {}}+/// Distribute a deck's blocks across slides.+///+/// Trivial next to the DOCX sibling, and for a structural reason: a DOCX block+/// has to be *located* by the layout stage, because a paragraph's page is+/// whatever pagination decided. A `BlockSource` already names its slide — the+/// index is intrinsic, not recovered — so this is a bucket sort.+///+/// All three sources land on the same page. Notes and SmartArt contribute no+/// `TextItem`s (their text is not on the slide, and a diagram's runs have no+/// rectangle), but they *are* content of that slide and belong in its markdown.+/// Concatenating the buckets reproduces the doc-level markdown exactly, since+/// the emitter already walks slides in presentation order.+#[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+fn split_pptx_blocks_by_page(+ tagged: &[(+ crate::markdown_layout::Block,+ crate::office::pptx::BlockSource,+ )],+ n_pages: usize,+) -> Vec<Vec<crate::markdown_layout::Block>> {+ use crate::office::pptx::BlockSource;++ let mut out = vec![Vec::new(); n_pages];+ for (block, src) in tagged {+ let idx = match src {+ BlockSource::Slide(n) | BlockSource::Notes(n) | BlockSource::Diagram(n) => *n,+ };+ // A slide the geometry pass skipped still has a page, so this only+ // guards against a deck whose emitter and layout disagree on slide+ // count — which would be a bug, not a document property.+ if let Some(bucket) = out.get_mut(idx) {+ bucket.push(block.clone());+ }+ }+ out+}++/// The document outline, one entry per slide title.+///+/// Every entry is level 1. PPTX has no heading hierarchy — `outlineLvl` is a+/// DOCX concept and a body placeholder's indent level is a bullet depth, not a+/// rank — so a flat outline is the honest shape, matching the emitter's own+/// `TITLE_HEADING_LEVEL`.+///+/// `y_pdf` is `None`. The DOCX path fills it from the first text command inside+/// an outline bracket; here the title's position is knowable but the outline is+/// derived from blocks rather than from draw commands, and a slide title is+/// found by its page, not by scrolling to an offset within it.+#[cfg(all(feature = "pptx-native", not(target_arch = "wasm32")))]+fn pptx_slide_outline(page_blocks: &[Vec<crate::markdown_layout::Block>]) -> Vec<OutlineTarget> {+ use crate::markdown_layout::Block;++ let mut out = Vec::new();+ for (idx, blocks) in page_blocks.iter().enumerate() {+ for block in blocks {+ if let Block::Heading { level, text } = block+ && !text.trim().is_empty()+ {+ out.push(OutlineTarget {+ level: *level,+ title: text.clone(),+ page_index: idx as i32,+ y_pdf: None,+ });+ }+ }+ }+ out+}+/// Distribute the emitted blocks across pages using the layout's block→page/// map. A forward cursor plus `max` keeps the per-page lists a partition of/// the input in its original order — concatenating them reproduces thediff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rsindex f80979f..8f6f373 100644--- a/crates/liteparse/tests/integration_test.rs+++ b/crates/liteparse/tests/integration_test.rs@@ -564,3 +564,100 @@ async fn test_parse_docx_native_complexity_integration() {.expect("native parse succeeds");assert!(parsed.pages.iter().all(|p| p.complexity.is_none()));}++/// 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 rest pins the contract the geometry pass added: one page per slide, real+/// boxes on every page, and an outline built from slide titles.+#[cfg(feature = "pptx-native")]+#[tokio::test]+#[serial]+async fn test_parse_pptx_native_integration() {+ let path = "../../bench/pptx_corpus/staging/cloudviper_workshop__19687752.pptx";+ let lit = LiteParse::new(LiteParseConfig {+ output_format: liteparse::config::OutputFormat::Markdown,+ quiet: true,+ ..Default::default()+ });+ let parsed = lit.parse(path).await.expect("native parse succeeds");++ let data = std::fs::read(path).expect("fixture readable");+ let blocks = liteparse::office::pptx::pptx_to_blocks(+ &data,+ liteparse::office::pptx::EmitOptions {+ // Mirrors the defaults the parse above ran with: `extract_links` is+ // on by default, and the native path always emits notes.+ links: true,+ notes: true,+ },+ )+ .expect("blocks");+ let expected = liteparse::markdown_layout::render_blocks(&blocks);+ assert_eq!(+ parsed.text, expected,+ "native pipeline markdown must match the emitter byte-for-byte"+ );++ // A slide is a page — the counts cannot drift, because a `BlockSource`+ // indexes pages directly.+ assert_eq!(parsed.pages.len(), 25, "one page per slide");+ assert!(+ parsed+ .pages+ .iter()+ .all(|p| p.page_width > 0.0 && p.page_height > 0.0),+ "real slide dimensions"+ );++ let items: usize = parsed.pages.iter().map(|p| p.text_items.len()).sum();+ assert!(items > 500, "per-run geometry present: {items} items");+ assert!(+ parsed+ .pages+ .iter()+ .flat_map(|p| &p.text_items)+ .all(|i| i.width > 0.0 || i.text.trim().is_empty()),+ "no degenerate boxes on visible text"+ );+ assert!(+ !parsed.outline.is_empty(),+ "outline built from slide titles"+ );+ assert!(+ parsed.outline.iter().all(|o| o.level == 1),+ "PPTX has no heading hierarchy, so every outline entry is level 1"+ );+}++/// A config the native PPTX path cannot honor is a hard error, not a silent+/// swap to LibreOffice — the user picks the engine, the engine never picks for+/// them. `extract_images` is the PPTX-specific entry: the reader emits nothing+/// for `ShapeKind::Picture`, so honoring the flag would mean handing back an+/// empty list.+#[cfg(feature = "pptx-native")]+#[tokio::test]+#[serial]+async fn test_pptx_native_unsupported_config_is_hard_error() {+ let lit = LiteParse::new(LiteParseConfig {+ extract_images: true,+ quiet: true,+ ..Default::default()+ });+ let msg = match lit+ .parse("../../bench/pptx_corpus/staging/cloudviper_workshop__19687752.pptx")+ .await+ {+ Err(e) => e.to_string(),+ Ok(_) => panic!("unsupported option must not silently fall back"),+ };+ assert!(+ msg.contains("extract_images") && msg.contains("native PPTX"),+ "error names the option and the engine: {msg}"+ );+}diff --git a/docs/src/content/docs/liteparse/guides/multi-format.mdx b/docs/src/content/docs/liteparse/guides/multi-format.mdxindex 0cfdd45..4d330d9 100644--- a/docs/src/content/docs/liteparse/guides/multi-format.mdx+++ b/docs/src/content/docs/liteparse/guides/multi-format.mdx@@ -47,6 +47,45 @@ choco install libreoffice-fresh> On Windows, you may need to add the LibreOffice CLI directory (typically `C:\Program Files\LibreOffice\program`) to your PATH and restart.+### Fonts (optional, affects DOCX geometry)++DOCX files carry no coordinates — not for a page, a line, or a character. LiteParse+lays the document out itself, measuring the actual glyphs to decide where every word+lands. So a bounding box is only as accurate as the font behind it.++When a document asks for a font you don't have, LiteParse falls back to a generic+sans. Text and structure are unaffected — headings, lists, tables and reading order+are read from the file, not from the layout — but bounding-box coordinates shift, and+they shift differently on different machines. That matters if you use+[visual citations](/liteparse/guides/visual-citations), highlight regions on a+screenshot, or compare geometry across hosts.++```bash+./scripts/install-fonts.sh # metric clones + common open fonts+./scripts/install-fonts.sh --metric # metric clones only+./scripts/install-fonts.sh --dry-run # print the commands, install nothing+```++The script installs only freely-redistributable fonts, of two kinds:++- **Metric-compatible clones** of the Microsoft fonts — Carlito for Calibri, Caladea+ for Cambria, Liberation/Croscore for Arial, Times New Roman and Courier New. These+ have the original's advance widths glyph for glyph, so text measured against them+ lands where the real font would have put it. This is the half that makes geometry+ *reproducible*, not merely plausible.+- **Common open fonts** that real documents use — Open Sans, Lato, Roboto, Montserrat+ and similar. Matched exactly, no substitution involved.++It does **not** install Calibri, Aptos, Corbel or Franklin Gothic themselves — those+are licensed by Microsoft and aren't ours to distribute. For Calibri and Cambria that+costs nothing, since the clones above stand in exactly. For Aptos, Corbel and Franklin+Gothic no free metric clone exists, so documents using them stay approximate unless+you have Microsoft Office installed.++On a 45-document corpus, running the script took the share of text measured against a+generic fallback from **64% to 14%**, with the remainder dominated by those+Microsoft-only faces.+## UsageOnce the dependencies are installed, just pass any supported file to `lit parse`: