Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewichc7f6c9fa06bf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 45e2457..c185d6f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -49,7 +49,12 @@ jobs:
if: runner.os == 'Linux'
run: |
sudo apt-get update
- sudo apt-get install -y libtesseract-dev libleptonica-dev
+ # Fonts: liteparse-docx layout tests need real font faces — 25 of
+ # them fail in a fontless environment (measurer, list_label,
+ # floating, build::block). Liberation + DejaVu is the set the musl
+ # test run validated; macOS/Windows runners ship system fonts.
+ sudo apt-get install -y libtesseract-dev libleptonica-dev \
+ fonts-liberation fonts-dejavu-core
- name: Install system dependencies (macOS)
if: runner.os == 'macOS'
diff --git a/crates/liteparse-docx/ATTRIBUTION.md b/crates/liteparse-docx/ATTRIBUTION.md
index 150ea64..631bd78 100644
--- a/crates/liteparse-docx/ATTRIBUTION.md
+++ b/crates/liteparse-docx/ATTRIBUTION.md
@@ -113,7 +113,7 @@ pages (0.16% at 615 pages — drift does not compound).
**Upstream fails closed at every level. We fail open.** A single malformed
value anywhere in a file must never cost the whole document — that is a
-standing requirement of this copy, not a one-off fix. Three distinct classes,
+standing requirement of this copy, not a one-off fix. Four distinct classes,
all of which upstream treats as fatal:
| class | upstream | here |
@@ -121,6 +121,24 @@ all of which upstream treats as fatal:
| **unknown elements** (`commentReference`, …) | aborts document | `#[serde(other)]` catch-all, element skipped |
| **unknown attribute *values*** (`w:jc val="bogus"`) | aborts document | `lenient::` deserializers → unspecified |
| **malformed scalars** (colours, measurements, ids) | aborts document | dropped / spec default |
+| **namespace collisions** (`w:shadow` vs `w14:shadow`) | aborts document (`duplicate field`) | extension-namespace elements stripped pre-parse |
+
+### Namespace collisions (`serde_xml.rs`)
+
+quick-xml's serde layer matches fields on prefix-stripped local names, so a
+Word 2010+ extension element (`<w14:shadow>`, a DrawingML text effect) lands
+on the same field as its transitional namesake (`<w:shadow>`, the §17.3.2.31
+boolean). Non-adjacent in one parent → fatal `duplicate field`; alone → the
+extension element *silently deserializes into the transitional field* (an
+attribute-only `<w14:shadow …>` reads as toggle-ON — corruption, no error).
+
+`from_xml` therefore strips every element with a `w14`/`w15`/`w16*` prefix
+before deserialization (gated on a cheap `<w14:`-marker scan so clean parts
+pay nothing). Attributes (`w14:paraId`) are untouched. None of these
+namespaces are modeled, so nothing is lost. **Duplicate-tolerance/last-wins is
+deliberately NOT the fix** — it would let an unrelated extension element
+overwrite a real property, the same silent-corruption trap as inventing
+default colours.
The mechanism lives in `docx/parse/primitives/lenient.rs`:
diff --git a/crates/liteparse-docx/src/docx/parse/serde_xml.rs b/crates/liteparse-docx/src/docx/parse/serde_xml.rs
index 5b5bd3c..bb12202 100644
--- a/crates/liteparse-docx/src/docx/parse/serde_xml.rs
+++ b/crates/liteparse-docx/src/docx/parse/serde_xml.rs
@@ -1,11 +1,190 @@
//! Shared helpers for serde-driven OOXML parsers.
+use quick_xml::events::Event;
+use quick_xml::{Reader, Writer};
use serde::de::DeserializeOwned;
use crate::docx::error::Result;
+/// Wordprocessing extension-namespace prefixes (Word 2010+, `w14`/`w15`/
+/// `w16*`) whose *elements* are stripped before deserialization.
+///
+/// quick-xml's serde layer matches struct fields on local names with the
+/// namespace prefix dropped, so `<w14:shadow>` (a DrawingML text effect)
+/// lands on the same field as `<w:shadow>` (the §17.3.2.31 boolean). That
+/// collision either fails the whole part with `duplicate field` when both
+/// appear in one parent, or — worse — silently deserializes the extension
+/// element into the transitional field when only the extension is present
+/// (an attribute-only `<w14:shadow …>` reads as toggle-on). None of these
+/// namespaces are modeled, so their elements are dropped wholesale rather
+/// than matched namespace-aware; last-wins duplicate tolerance is
+/// deliberately NOT the fix (it would let an unrelated extension element
+/// overwrite a real property).
+///
+/// Matching is by prefix, not by declared namespace URI — every known
+/// producer uses these conventional prefixes (they are what documents list
+/// in `mc:Ignorable`, which is itself prefix-based). Attributes
+/// (`w14:paraId`, `w14:textId`) are left untouched: their local names do
+/// not collide with modeled attributes, and stripping them would churn
+/// every modern Word document for no gain.
+const EXTENSION_ELEMENT_PREFIXES: &[&[u8]] = &[
+ b"w14",
+ b"w15",
+ b"w16",
+ b"w16se",
+ b"w16cid",
+ b"w16cex",
+ b"w16sdtdh",
+ b"w16du",
+];
+
+/// Cheap gate for the filter pass: element-start markers for the prefixes
+/// above (`<w16` covers the whole `w16*` family). Attribute occurrences
+/// (` w14:paraId=`) do not match, so parts that only carry extension
+/// *attributes* — i.e. most modern Word parts — skip the filter entirely.
+const EXTENSION_ELEMENT_MARKERS: &[&[u8]] = &[b"<w14:", b"<w15:", b"<w16"];
+
/// Deserialize an OOXML part into a schema type, mapping quick-xml's error
/// into the crate's `ParseError`.
pub fn from_xml<T: DeserializeOwned>(data: &[u8]) -> Result<T> {
+ if EXTENSION_ELEMENT_MARKERS
+ .iter()
+ .any(|m| contains_subslice(data, m))
+ {
+ let filtered = strip_extension_elements(data)?;
+ return Ok(quick_xml::de::from_reader(filtered.as_slice())?);
+ }
Ok(quick_xml::de::from_reader(data)?)
}
+
+fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
+ haystack.windows(needle.len()).any(|w| w == needle)
+}
+
+fn is_extension_element(name: quick_xml::name::QName) -> bool {
+ name.prefix()
+ .is_some_and(|p| EXTENSION_ELEMENT_PREFIXES.contains(&p.as_ref()))
+}
+
+/// Re-emit the part with every extension-namespace element subtree removed.
+/// All other events pass through verbatim (text stays in its escaped form,
+/// so the round-trip does not re-escape anything).
+fn strip_extension_elements(data: &[u8]) -> Result<Vec<u8>> {
+ let mut reader = Reader::from_reader(data);
+ let mut writer = Writer::new(Vec::with_capacity(data.len()));
+ let mut buf = Vec::new();
+ let mut skip_buf = Vec::new();
+ loop {
+ let ev = reader
+ .read_event_into(&mut buf)
+ .map_err(quick_xml::DeError::from)?;
+ match ev {
+ Event::Eof => break,
+ Event::Start(ref e) if is_extension_element(e.name()) => {
+ let end = e.to_end().into_owned();
+ reader
+ .read_to_end_into(end.name(), &mut skip_buf)
+ .map_err(quick_xml::DeError::from)?;
+ }
+ Event::Empty(ref e) if is_extension_element(e.name()) => {}
+ ev => writer.write_event(ev)?,
+ }
+ buf.clear();
+ }
+ Ok(writer.into_inner())
+}
+
+#[cfg(test)]
+mod tests {
+ use serde::Deserialize;
+
+ use super::*;
+ use crate::docx::parse::primitives::OnOff;
+
+ #[derive(Debug, Deserialize)]
+ struct Props {
+ #[serde(rename = "shadow", default)]
+ shadow: Vec<OnOff>,
+ #[serde(rename = "b", default)]
+ b: Vec<OnOff>,
+ }
+
+ /// The `worldbank.docx` shape: `w:shadow` and `w14:shadow` in one parent,
+ /// non-adjacent, so serde sees the local name `shadow` twice and errors
+ /// with `duplicate field`. The filter must keep the transitional element
+ /// and drop the extension one.
+ #[test]
+ fn w14_collision_with_transitional_element_is_resolved() {
+ let xml = r#"<rPr xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml">
+ <shadow val="0"/>
+ <b/>
+ <w14:shadow w14:blurRad="0" w14:dist="0"><w14:srgbClr w14:val="000000"/></w14:shadow>
+ </rPr>"#;
+ let p: Props = from_xml(xml.as_bytes()).expect("collision must not be fatal");
+ assert_eq!(p.shadow, vec![OnOff(false)], "w:shadow val=0 must survive");
+ assert_eq!(p.b, vec![OnOff(true)]);
+ }
+
+ /// A lone `w14:shadow` (no transitional sibling) previously deserialized
+ /// into the `shadow` field as toggle-ON — silent corruption, no error.
+ #[test]
+ fn lone_w14_element_does_not_impersonate_transitional_field() {
+ let xml = r#"<rPr><w14:shadow w14:blurRad="50800" w14:dist="38100"/></rPr>"#;
+ let p: Props = from_xml(xml.as_bytes()).unwrap();
+ assert!(
+ p.shadow.is_empty(),
+ "extension element must not set the boolean"
+ );
+ }
+
+ /// Extension *attributes* are untouched — the filter only strips elements,
+ /// and parts with only attribute occurrences must skip the filter pass.
+ #[test]
+ fn extension_attributes_pass_through() {
+ #[derive(Debug, Deserialize)]
+ struct Para {
+ #[serde(rename = "@paraId", default)]
+ para_id: Option<String>,
+ #[serde(rename = "b", default)]
+ b: Vec<OnOff>,
+ }
+ let xml = r#"<p w14:paraId="12AB34CD"><b/></p>"#;
+ let p: Para = from_xml(xml.as_bytes()).unwrap();
+ assert_eq!(p.para_id.as_deref(), Some("12AB34CD"));
+ assert_eq!(p.b, vec![OnOff(true)]);
+ }
+
+ /// Escaped text must survive the filter round-trip in its escaped form.
+ #[test]
+ fn filter_preserves_escaped_text() {
+ #[derive(Debug, Deserialize)]
+ struct T {
+ #[serde(rename = "t")]
+ t: String,
+ }
+ let xml = r#"<r><w14:glow w14:rad="0"/><t>a &amp; b &lt; c</t></r>"#;
+ let p: T = from_xml(xml.as_bytes()).unwrap();
+ assert_eq!(p.t, "a & b < c");
+ }
+
+ /// `w16*` family prefixes are covered by the `<w16` marker and the exact
+ /// prefix list; unrelated prefixes (`wp14`) are not stripped.
+ #[test]
+ fn w16_family_stripped_wp14_kept() {
+ #[derive(Debug, Deserialize)]
+ struct T {
+ #[serde(rename = "sizeRelH", default)]
+ size_rel_h: Option<String>,
+ #[serde(rename = "shadow", default)]
+ shadow: Vec<OnOff>,
+ }
+ let xml = r#"<x>
+ <w16se:symEx w16se:font="Wingdings"/>
+ <shadow/>
+ <wp14:sizeRelH>keep</wp14:sizeRelH>
+ </x>"#;
+ let p: T = from_xml(xml.as_bytes()).unwrap();
+ assert_eq!(p.size_rel_h.as_deref(), Some("keep"));
+ assert_eq!(p.shadow, vec![OnOff(true)]);
+ }
+}
diff --git a/crates/liteparse-docx/src/render/raster.rs b/crates/liteparse-docx/src/render/raster.rs
new file mode 100644
index 0000000..5d5b35d
--- /dev/null
+++ b/crates/liteparse-docx/src/render/raster.rs
@@ -0,0 +1,668 @@
+//! Rasterize [`LayoutedPage`] draw commands to RGBA bitmaps — tiny-skia +
+//! skrifa, no Skia proper.
+//!
+//! liteparse addition (no upstream equivalent; upstream rasterizes through
+//! `painter.rs` + Skia, which the C′ vendor dropped). This module is the
+//! "rasterise from layout draw-commands directly" option from
+//! `NATIVE_OFFICE_PLAN.md`: because glyph placement re-derives pen advances
+//! from the same [`FontRegistry`]/skrifa faces the layout measured with, the
+//! raster is in the *same coordinate space* as the native `TextItem` geometry
+//! by construction — which is what makes highlight-on-screenshot safe, the
+//! thing the LibreOffice screenshot path could never guarantee.
+//!
+//! Fidelity tiers, mirroring the vendored painter's own tiering:
+//! - **Rendered faithfully**: text (monochrome outlines), underlines, lines,
+//! rects, images (PNG/JPEG/GIF/BMP/TIFF/WebP incl. `src_rect` crops), shape
+//! paths with solid fills and solid/dashed strokes.
+//! - **Approximated**: gradient fills collapse to their mean stop color
+//! (logged once); emoji clusters draw monochrome outlines when the resolved
+//! face has them, else nothing.
+//! - **Skipped**: blip/pattern fills, effects (shadow/glow), EMF/WMF/SVG
+//! media (no decoder — same set `collect_images` skips), color glyph
+//! tables. Each skip logs once per process, never per command.
+//!
+//! The output is plain `{rgba, width, height}` so consumers need no tiny-skia
+//! types; the buffer is effectively straight (non-premultiplied) RGBA because
+//! every page starts from opaque white, so composited alpha is always 255.
+
+use std::sync::Once;
+
+use skrifa::MetadataProvider;
+use skrifa::instance::{LocationRef, Size};
+use skrifa::outline::{DrawSettings, OutlinePen};
+use tiny_skia::{
+ Color, FillRule, LineCap, LineJoin, Paint, PathBuilder, Pixmap, PixmapPaint, Shader, Stroke,
+ StrokeDash, Transform,
+};
+
+use crate::model::{ImageFormat, PathFillMode};
+use crate::render::dimension::Pt;
+use crate::render::fonts::{FontRegistry, FontStyle, TypefaceEntry};
+use crate::render::geometry::{PtOffset, PtRect};
+use crate::render::layout::draw_command::{
+ DrawCommand, LayoutedPage, ResolvedDashPattern, ResolvedFill, ResolvedLineCap,
+ ResolvedLineJoin, ResolvedStroke,
+};
+use crate::render::resolve::color::RgbColor;
+use crate::render::resolve::drawing_color::Rgba;
+use crate::render::resolve::images::MediaEntry;
+use crate::render::resolve::shape_geometry::{PathVerb, SubPath};
+
+/// One rasterized page. `rgba` is `width * height * 4` bytes, row-major,
+/// fully opaque (see module docs).
+pub struct RasterPage {
+ pub rgba: Vec<u8>,
+ pub width: u32,
+ pub height: u32,
+ /// Page size in Pt, for consumers that scale pixel coordinates back to
+ /// viewport space.
+ pub page_width_pt: f32,
+ pub page_height_pt: f32,
+}
+
+/// Rasterize one page at `scale` device pixels per Pt (`dpi / 72`).
+///
+/// `registry` must be the registry the layout ran with — resolution rules are
+/// per-registry state, and a different registry could pick different faces
+/// than the ones the line breaks were measured against.
+pub fn rasterize_page(
+ page: &LayoutedPage,
+ registry: &FontRegistry,
+ scale: f32,
+) -> Result<RasterPage, String> {
+ let page_w = page.page_size.width.raw();
+ let page_h = page.page_size.height.raw();
+ let px_w = (page_w * scale).round().max(1.0) as u32;
+ let px_h = (page_h * scale).round().max(1.0) as u32;
+ let mut pixmap =
+ Pixmap::new(px_w, px_h).ok_or_else(|| format!("cannot allocate {px_w}x{px_h} pixmap"))?;
+ pixmap.fill(Color::WHITE);
+
+ // Page Pt → device px. Every path below is built in page-Pt coordinates
+ // and handed to tiny-skia with this transform (possibly pre-concatenated
+ // with a shape-local placement), so there is exactly one scaling site.
+ let device = Transform::from_scale(scale, scale);
+
+ // Layered passes, each in stream order. `DrawCommand` carries no z-order
+ // and §20.4.2.3 `behindDoc` is honored by emission position only *within*
+ // a header/footer run — a body-anchored behind-doc shape lands mid-stream
+ // after the header's text and would paint over it in one sequential pass
+ // (upstream's Skia painter has the same artifact). The layering encodes
+ // what the flags mean in practice:
+ //
+ // Shape (floats: banners, watermarks — usually behind-doc)
+ // < Shading (highlight/cell-shading rects, tied to the text flow)
+ // < Media (placed images; inline ones must beat cell shading)
+ // < Ink (glyphs, rules, borders)
+ //
+ // Cost of the approximation: a deliberately in-front float no longer
+ // covers text/shading — rare, and its fill still paints. A shape's own
+ // text-box text is emitted as separate `Text` commands, so it stays over
+ // its fill in the ink pass.
+ for pass in [
+ RasterPass::Shape,
+ RasterPass::Shading,
+ RasterPass::Media,
+ RasterPass::Ink,
+ ] {
+ for cmd in &page.commands {
+ if raster_pass(cmd) != Some(pass) {
+ continue;
+ }
+ match cmd {
+ DrawCommand::Text {
+ position,
+ text,
+ font_family,
+ char_spacing,
+ font_size,
+ bold,
+ italic,
+ color,
+ text_scale,
+ } => {
+ let entry =
+ registry.resolve(font_family, FontStyle::from_flags(*bold, *italic));
+ draw_text_run(
+ &mut pixmap,
+ registry,
+ &entry,
+ text,
+ *position,
+ *font_size,
+ *text_scale,
+ *char_spacing,
+ rgb_color(*color),
+ device,
+ );
+ }
+ DrawCommand::Underline { line, color, width }
+ | DrawCommand::Line { line, color, width } => {
+ let mut pb = PathBuilder::new();
+ pb.move_to(line.start.x.raw(), line.start.y.raw());
+ pb.line_to(line.end.x.raw(), line.end.y.raw());
+ if let Some(path) = pb.finish() {
+ let stroke = Stroke {
+ width: width.raw().max(0.2),
+ ..Stroke::default()
+ };
+ pixmap.stroke_path(&path, &solid(rgb_color(*color)), &stroke, device, None);
+ }
+ }
+ DrawCommand::Rect { rect, color } => {
+ if let Some(r) = skia_rect(rect) {
+ pixmap.fill_rect(r, &solid(rgb_color(*color)), device, None);
+ }
+ }
+ DrawCommand::Image {
+ rect,
+ image_data,
+ src_rect,
+ } => {
+ draw_image(&mut pixmap, image_data, rect, src_rect.as_ref(), device);
+ }
+ DrawCommand::EmojiCluster {
+ rect,
+ text,
+ typeface,
+ size,
+ ..
+ } => {
+ draw_emoji_fallback(&mut pixmap, registry, typeface, text, rect, *size, device);
+ }
+ DrawCommand::Path {
+ origin,
+ rotation,
+ flip_h,
+ flip_v,
+ extent,
+ paths,
+ fill,
+ stroke,
+ effects: _, // shadow/glow: skipped at this tier
+ } => {
+ // Shape-local Pt → page Pt: flips and rotation happen about
+ // the shape's center, then the shape lands at `origin`.
+ let (cx, cy) = (extent.width.raw() / 2.0, extent.height.raw() / 2.0);
+ let mut place = Transform::from_translate(origin.x.raw(), origin.y.raw());
+ let deg = rotation.raw() as f32 / 60_000.0;
+ if deg != 0.0 {
+ place = place.pre_concat(Transform::from_rotate_at(deg, cx, cy));
+ }
+ if *flip_h || *flip_v {
+ let (sx, sy) = (
+ if *flip_h { -1.0 } else { 1.0 },
+ if *flip_v { -1.0 } else { 1.0 },
+ );
+ place = place
+ .pre_concat(Transform::from_translate(cx, cy))
+ .pre_concat(Transform::from_scale(sx, sy))
+ .pre_concat(Transform::from_translate(-cx, -cy));
+ }
+ let transform = device.pre_concat(place);
+ for sub in paths {
+ draw_subpath(&mut pixmap, sub, fill, stroke.as_ref(), transform);
+ }
+ }
+ // Non-drawing commands: link/destination/outline metadata
+ // (`raster_pass` returns `None` for these, so this arm is
+ // unreachable and exists for exhaustiveness).
+ DrawCommand::LinkAnnotation { .. }
+ | DrawCommand::InternalLink { .. }
+ | DrawCommand::NamedDestination { .. }
+ | DrawCommand::Outline(_) => {}
+ }
+ }
+ }
+
+ Ok(RasterPage {
+ rgba: pixmap.take(),
+ width: px_w,
+ height: px_h,
+ page_width_pt: page_w,
+ page_height_pt: page_h,
+ })
+}
+
+/// Which paint layer a command belongs to (see the layering comment in
+/// [`rasterize_page`]). `None` = not painted.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum RasterPass {
+ /// Anchored shape geometry (floats — banners, watermarks).
+ Shape,
+ /// Highlight and cell/paragraph shading rects.
+ Shading,
+ /// Placed raster images.
+ Media,
+ /// Glyphs, emoji, underlines, table/border lines.
+ Ink,
+}
+
+fn raster_pass(cmd: &DrawCommand) -> Option<RasterPass> {
+ match cmd {
+ DrawCommand::Path { .. } => Some(RasterPass::Shape),
+ DrawCommand::Rect { .. } => Some(RasterPass::Shading),
+ DrawCommand::Image { .. } => Some(RasterPass::Media),
+ DrawCommand::Text { .. }
+ | DrawCommand::Underline { .. }
+ | DrawCommand::Line { .. }
+ | DrawCommand::EmojiCluster { .. } => Some(RasterPass::Ink),
+ DrawCommand::LinkAnnotation { .. }
+ | DrawCommand::InternalLink { .. }
+ | DrawCommand::NamedDestination { .. }
+ | DrawCommand::Outline(_) => None,
+ }
+}
+
+// ─── Text ───────────────────────────────────────────────────────────────────
+
+/// skrifa outline pen writing into a tiny-skia path builder.
+///
+/// skrifa emits glyph-local coordinates y-up; the page is y-down, so y is
+/// negated about the baseline. `sx` carries §17.3.2.45 horizontal scale so
+/// stretched text stretches its glyphs, not just its advances (upstream's
+/// painter does the same via `Font::set_scale_x`).
+struct GlyphPen<'a> {
+ pb: &'a mut PathBuilder,
+ x: f32,
+ baseline_y: f32,
+ sx: f32,
+}
+
+impl OutlinePen for GlyphPen<'_> {
+ fn move_to(&mut self, x: f32, y: f32) {
+ self.pb.move_to(self.x + x * self.sx, self.baseline_y - y);
+ }
+ fn line_to(&mut self, x: f32, y: f32) {
+ self.pb.line_to(self.x + x * self.sx, self.baseline_y - y);
+ }
+ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
+ self.pb.quad_to(
+ self.x + cx0 * self.sx,
+ self.baseline_y - cy0,
+ self.x + x * self.sx,
+ self.baseline_y - y,
+ );
+ }
+ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
+ self.pb.cubic_to(
+ self.x + cx0 * self.sx,
+ self.baseline_y - cy0,
+ self.x + cx1 * self.sx,
+ self.baseline_y - cy1,
+ self.x + x * self.sx,
+ self.baseline_y - y,
+ );
+ }
+ fn close(&mut self) {
+ self.pb.close();
+ }
+}
+
+/// Draw one `Text` command: cmap walk, glyph outlines onto one path, single
+/// fill. The pen advance per char is `advance(gid) * text_scale +
+/// char_spacing` — the same arithmetic [`TextMeasurer::measure`] sums, so ink
+/// lands inside the measured extent by construction.
+///
+/// [`TextMeasurer::measure`]: crate::render::layout::measurer::TextMeasurer::measure
+#[allow(clippy::too_many_arguments)]
+fn draw_text_run(
+ pixmap: &mut Pixmap,
+ registry: &FontRegistry,
+ entry: &TypefaceEntry,
+ text: &str,
+ position: PtOffset,
+ font_size: Pt,
+ text_scale: f32,
+ char_spacing: Pt,
+ color: Color,
+ device: Transform,
+) {
+ let path = registry.db().with_face_data(entry.id, |data, index| {
+ let font = skrifa::FontRef::from_index(data, index).ok()?;
+ let charmap = font.charmap();
+ let outlines = font.outline_glyphs();
+ let metrics = font.glyph_metrics(Size::new(font_size.raw()), LocationRef::default());
+
+ let mut pb = PathBuilder::new();
+ let mut pen_x = position.x.raw();
+ for ch in text.chars() {
+ let gid = charmap.map(ch).unwrap_or(skrifa::GlyphId::NOTDEF);
+ if let Some(glyph) = outlines.get(gid) {
+ let mut pen = GlyphPen {
+ pb: &mut pb,
+ x: pen_x,
+ baseline_y: position.y.raw(),
+ sx: text_scale,
+ };
+ let settings =
+ DrawSettings::unhinted(Size::new(font_size.raw()), LocationRef::default());
+ // A malformed glyph program draws nothing; the advance below
+ // still moves the pen so the rest of the run stays aligned.
+ let _ = glyph.draw(settings, &mut pen);
+ }
+ pen_x += metrics.advance_width(gid).unwrap_or(0.0) * text_scale + char_spacing.raw();
+ }
+ pb.finish()
+ });
+ if let Some(Some(path)) = path {
+ // Non-zero winding is the convention for TrueType/CFF outlines.
+ pixmap.fill_path(&path, &solid(color), FillRule::Winding, device, None);
+ }
+}
+
+/// Monochrome fallback for an emoji cluster: draw the resolved face's
+/// outlines if it has any. Color glyph tables (COLR/CBDT/sbix) are not
+/// rendered at this tier; faces that carry only those draw nothing.
+fn draw_emoji_fallback(
+ pixmap: &mut Pixmap,
+ registry: &FontRegistry,
+ typeface: &TypefaceEntry,
+ text: &str,
+ rect: &PtRect,
+ size: Pt,
+ device: Transform,
+) {
+ static EMOJI_ONCE: Once = Once::new();
+ let drew = registry.db().with_face_data(typeface.id, |data, index| {
+ let font = skrifa::FontRef::from_index(data, index).ok()?;
+ let outlines = font.outline_glyphs();
+ let charmap = font.charmap();
+ let m = font.metrics(Size::new(size.raw()), LocationRef::default());
+ let metrics = font.glyph_metrics(Size::new(size.raw()), LocationRef::default());
+ let baseline_y = rect.origin.y.raw() + m.ascent;
+
+ let mut pb = PathBuilder::new();
+ let mut pen_x = rect.origin.x.raw();
+ for ch in text.chars() {
+ let Some(gid) = charmap.map(ch) else { continue };
+ if let Some(glyph) = outlines.get(gid) {
+ let mut pen = GlyphPen {
+ pb: &mut pb,
+ x: pen_x,
+ baseline_y,
+ sx: 1.0,
+ };
+ let settings =
+ DrawSettings::unhinted(Size::new(size.raw()), LocationRef::default());
+ let _ = glyph.draw(settings, &mut pen);
+ }
+ pen_x += metrics.advance_width(gid).unwrap_or(0.0);
+ }
+ pb.finish()
+ });
+ match drew {
+ Some(Some(path)) => {
+ pixmap.fill_path(&path, &solid(Color::BLACK), FillRule::Winding, device, None);
+ }
+ _ => EMOJI_ONCE.call_once(|| {
+ log::info!("emoji cluster face has no outline glyphs; clusters render blank");
+ }),
+ }
+}
+
+// ─── Images ─────────────────────────────────────────────────────────────────
+
+fn draw_image(
+ pixmap: &mut Pixmap,
+ media: &MediaEntry,
+ rect: &PtRect,
+ src_rect: Option<&PtRect>,
+ device: Transform,
+) {
+ static VECTOR_ONCE: Once = Once::new();
+ match media.format {
+ ImageFormat::Emf | ImageFormat::Wmf | ImageFormat::Svg | ImageFormat::Unknown => {
+ VECTOR_ONCE.call_once(|| {
+ log::info!("EMF/WMF/SVG media are not rasterized; placements render blank");
+ });
+ return;
+ }
+ _ => {}
+ }
+ let Ok(decoded) = image::load_from_memory(&media.data) else {
+ log::warn!(
+ "undecodable {:?} media ({} bytes)",
+ media.format,
+ media.data.len()
+ );
+ return;
+ };
+ let mut rgba = decoded.to_rgba8();
+
+ // §20.1.10.48 srcRect: fractional crop of the natural extent, applied
+ // before stretching into `rect`.
+ if let Some(crop) = src_rect {
+ let (w, h) = (rgba.width() as f32, rgba.height() as f32);
+ let x = (crop.origin.x.raw() * w).round().clamp(0.0, w) as u32;
+ let y = (crop.origin.y.raw() * h).round().clamp(0.0, h) as u32;
+ let cw = (crop.size.width.raw() * w).round().max(1.0) as u32;
+ let ch = (crop.size.height.raw() * h).round().max(1.0) as u32;
+ let cw = cw.min(rgba.width().saturating_sub(x)).max(1);
+ let ch = ch.min(rgba.height().saturating_sub(y)).max(1);
+ rgba = image::imageops::crop_imm(&rgba, x, y, cw, ch).to_image();
+ }
+
+ let (iw, ih) = (rgba.width(), rgba.height());
+ // tiny-skia sources are premultiplied RGBA.
+ let mut data = rgba.into_raw();
+ for px in data.chunks_exact_mut(4) {
+ let a = px[3] as u16;
+ if a != 255 {
+ px[0] = ((px[0] as u16 * a) / 255) as u8;
+ px[1] = ((px[1] as u16 * a) / 255) as u8;
+ px[2] = ((px[2] as u16 * a) / 255) as u8;
+ }
+ }
+ let Some(size) = tiny_skia::IntSize::from_wh(iw, ih) else {
+ return;
+ };
+ let Some(src) = Pixmap::from_vec(data, size) else {
+ return;
+ };
+
+ let sx = rect.size.width.raw() / iw as f32;
+ let sy = rect.size.height.raw() / ih as f32;
+ if sx <= 0.0 || sy <= 0.0 {
+ return;
+ }
+ let transform = device.pre_concat(
+ Transform::from_translate(rect.origin.x.raw(), rect.origin.y.raw())
+ .pre_concat(Transform::from_scale(sx, sy)),
+ );
+ let paint = PixmapPaint {
+ quality: tiny_skia::FilterQuality::Bilinear,
+ ..PixmapPaint::default()
+ };
+ pixmap.draw_pixmap(0, 0, src.as_ref(), &paint, transform, None);
+}
+
+// ─── Shape paths ────────────────────────────────────────────────────────────
+
+fn draw_subpath(
+ pixmap: &mut Pixmap,
+ sub: &SubPath,
+ fill: &ResolvedFill,
+ stroke: Option<&ResolvedStroke>,
+ transform: Transform,
+) {
+ let Some(path) = build_path(sub) else { return };
+
+ if sub.fill_mode != PathFillMode::None {
+ if let Some(paint) = fill_paint(fill) {
+ pixmap.fill_path(&path, &paint, FillRule::EvenOdd, transform, None);
+ }
+ }
+ if sub.stroked
+ && let Some(s) = stroke
+ && s.color.a > 0.0
+ && s.width.raw() > 0.0
+ {
+ let stroke = Stroke {
+ width: s.width.raw(),
+ line_cap: match s.cap {
+ ResolvedLineCap::Butt => LineCap::Butt,
+ ResolvedLineCap::Round => LineCap::Round,
+ ResolvedLineCap::Square => LineCap::Square,
+ },
+ line_join: match s.join {
+ ResolvedLineJoin::Round => LineJoin::Round,
+ ResolvedLineJoin::Bevel => LineJoin::Bevel,
+ ResolvedLineJoin::Miter => LineJoin::Miter,
+ },
+ dash: match &s.dash {
+ ResolvedDashPattern::Solid => None,
+ ResolvedDashPattern::Dashes(d) => {
+ let mut v: Vec<f32> = d.iter().map(|p| p.raw()).collect();
+ // tiny-skia requires an even-length dash array.
+ if v.len() % 2 == 1 {
+ v.extend_from_within(..);
+ }
+ StrokeDash::new(v, 0.0)
+ }
+ },
+ ..Stroke::default()
+ };
+ pixmap.stroke_path(&path, &solid(rgba_color(s.color)), &stroke, transform, None);
+ }
+}
+
+fn build_path(sub: &SubPath) -> Option<tiny_skia::Path> {
+ let mut pb = PathBuilder::new();
+ // Arc cursor tracking: ArcTo starts at the current point without an
+ // implicit move, so remember where the pen is.
+ let mut cursor: Option<(f32, f32)> = None;
+ for verb in &sub.verbs {
+ match verb {
+ PathVerb::MoveTo(p) => {
+ pb.move_to(p.x.raw(), p.y.raw());
+ cursor = Some((p.x.raw(), p.y.raw()));
+ }
+ PathVerb::LineTo(p) => {
+ pb.line_to(p.x.raw(), p.y.raw());
+ cursor = Some((p.x.raw(), p.y.raw()));
+ }
+ PathVerb::QuadTo(c, p) => {
+ pb.quad_to(c.x.raw(), c.y.raw(), p.x.raw(), p.y.raw());
+ cursor = Some((p.x.raw(), p.y.raw()));
+ }
+ PathVerb::CubicTo(c0, c1, p) => {
+ pb.cubic_to(
+ c0.x.raw(),
+ c0.y.raw(),
+ c1.x.raw(),
+ c1.y.raw(),
+ p.x.raw(),
+ p.y.raw(),
+ );
+ cursor = Some((p.x.raw(), p.y.raw()));
+ }
+ PathVerb::ArcTo {
+ radii,
+ start_angle,
+ swing_angle,
+ } => {
+ let Some((sx, sy)) = cursor else { continue };
+ let rx = radii.width.raw();
+ let ry = radii.height.raw();
+ if rx <= 0.0 || ry <= 0.0 {
+ continue;
+ }
+ // OOXML angles: 0° = 3 o'clock, positive = clockwise — which
+ // in y-down page space is the standard parametric direction,
+ // so p(θ) = center + (rx cos θ, ry sin θ) needs no sign flip.
+ let th0 = (start_angle.raw() as f32 / 60_000.0).to_radians();
+ let swing = (swing_angle.raw() as f32 / 60_000.0).to_radians();
+ let (cx, cy) = (sx - rx * th0.cos(), sy - ry * th0.sin());
+ // Polyline approximation, ≤5° per segment: sub-pixel error at
+ // raster scale for any radius that fits on a page.
+ let steps = ((swing.abs().to_degrees() / 5.0).ceil() as usize).max(1);
+ let mut end = (sx, sy);
+ for i in 1..=steps {
+ let th = th0 + swing * (i as f32 / steps as f32);
+ end = (cx + rx * th.cos(), cy + ry * th.sin());
+ pb.line_to(end.0, end.1);
+ }
+ cursor = Some(end);
+ }
+ PathVerb::Close => {
+ pb.close();
+ }
+ }
+ }
+ pb.finish()
+}
+
+/// Tier-0 fill: solid faithfully; gradient as the mean stop color (logged
+/// once); blip/pattern skipped (logged once). Inventing pixels quietly is the
+/// silent-corruption trap; a one-time log keeps the approximation loud.
+fn fill_paint(fill: &ResolvedFill) -> Option<Paint<'static>> {
+ static GRADIENT_ONCE: Once = Once::new();
+ static TEXTURE_ONCE: Once = Once::new();
+ match fill {
+ ResolvedFill::None => None,
+ ResolvedFill::Solid(c) => (c.a > 0.0).then(|| solid(rgba_color(*c))),
+ ResolvedFill::Gradient(g) => {
+ GRADIENT_ONCE.call_once(|| {
+ log::info!("gradient fills approximate as their mean stop color");
+ });
+ if g.stops.is_empty() {
+ return None;
+ }
+ let n = g.stops.len() as f32;
+ let (mut r, mut gr, mut b, mut a) = (0.0, 0.0, 0.0, 0.0);
+ for s in &g.stops {
+ r += s.color.r;
+ gr += s.color.g;
+ b += s.color.b;
+ a += s.color.a;
+ }
+ let c = Rgba {
+ r: r / n,
+ g: gr / n,
+ b: b / n,
+ a: a / n,
+ };
+ (c.a > 0.0).then(|| solid(rgba_color(c)))
+ }
+ ResolvedFill::Blip(_) | ResolvedFill::Pattern(_) => {
+ TEXTURE_ONCE.call_once(|| {
+ log::info!("blip/pattern fills are not rasterized; interiors render unfilled");
+ });
+ None
+ }
+ }
+}
+
+// ─── Small helpers ──────────────────────────────────────────────────────────
+
+fn solid(color: Color) -> Paint<'static> {
+ Paint {
+ shader: Shader::SolidColor(color),
+ anti_alias: true,
+ ..Paint::default()
+ }
+}
+
+fn rgb_color(c: RgbColor) -> Color {
+ Color::from_rgba8(c.r, c.g, c.b, 255)
+}
+
+fn rgba_color(c: Rgba) -> Color {
+ Color::from_rgba(
+ c.r.clamp(0.0, 1.0),
+ c.g.clamp(0.0, 1.0),
+ c.b.clamp(0.0, 1.0),
+ c.a.clamp(0.0, 1.0),
+ )
+ .unwrap_or(Color::BLACK)
+}
+
+fn skia_rect(r: &PtRect) -> Option<tiny_skia::Rect> {
+ tiny_skia::Rect::from_xywh(
+ r.origin.x.raw(),
+ r.origin.y.raw(),
+ r.size.width.raw(),
+ r.size.height.raw(),
+ )
+}
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index 3c5d05e..504a71d 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -137,7 +137,9 @@ struct ParseCommand {
#[arg(long)]
keep_headers_footers: bool,
- /// Include all PDF annotations as page-scoped structured JSON/API data.
+ /// Include document annotations as page-scoped structured JSON/API data
+ /// (PDF annotations; on the native DOCX path, hyperlinks and internal
+ /// links as `link` annotations).
#[arg(long)]
extract_annotations: bool,
@@ -281,7 +283,9 @@ struct BatchParseCommand {
#[arg(long)]
extract_vector_graphics: bool,
- /// Include all PDF annotations as page-scoped structured JSON/API data.
+ /// Include document annotations as page-scoped structured JSON/API data
+ /// (PDF annotations; on the native DOCX path, hyperlinks and internal
+ /// links as `link` annotations).
#[arg(long)]
extract_annotations: bool,
/// Include AcroForm widget fields and values as page-scoped structured data.
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index bbafe13..09ce54b 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -270,6 +270,161 @@ pub(crate) fn calculate_page_complexity(
})
}
+/// Native-office analogue of [`calculate_page_complexity`] +
+/// [`calculate_layout_complexity`] in one: the facts a PDF object walk digs
+/// out arrive here as source-document data. `image_rects` are the page's
+/// placed media rects (viewport pt), `table_count` the page's table blocks,
+/// `column_count` the section-declared column count.
+///
+/// Deliberate divergences from the PDF pair, all following from "the source
+/// states it":
+/// - `uncovered_vector_area` is `Some(0.0)` when no cheaper predicate fired —
+/// text painted as vector outlines cannot exist on this path (every glyph
+/// the layout draws is in the text stream), so the area is a known zero,
+/// not an unmeasured `None`.
+/// - No `AnnotationText` reason: there are no PDF annotations to paint text.
+/// - `ruled_table_coverage` stays 0.0 and `text_table_run_count` 0: blocks
+/// carry no geometry, and the ruled/borderless split is a PDF-detector
+/// concept — `ruled_table_count` carries the (exact) table count and drives
+/// `TableLikely` on its own.
+/// - `figure_count`/`figure_coverage` count placed images rather than
+/// vector-graphic clusters — the closest native analogue.
+#[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]
+pub(crate) fn calculate_native_page_complexity(
+ page: &Page,
+ image_rects: &[crate::types::Rect],
+ table_count: usize,
+ column_count: usize,
+) -> PageComplexityStats {
+ let pw = page.page_width;
+ let ph = page.page_height;
+ let page_area = pw * ph;
+
+ // Same "usable text only" filter as the PDF path. Native text should
+ // never trip it, but sharing the predicate keeps the two paths honest.
+ let text_length: usize = page
+ .text_items
+ .iter()
+ .filter(|item| !is_unusable_native(item))
+ .map(|item| item.text.len())
+ .sum();
+
+ // Same filters as the PDF path's `image_bounds(MIN_IMAGE_SIZE_PT, ∞)` +
+ // full-page split: tiny decorations dropped, full-page backgrounds
+ // excluded from inline-figure coverage but remembered as the scan signal.
+ let sized: Vec<&crate::types::Rect> = image_rects
+ .iter()
+ .filter(|r| r.width >= MIN_IMAGE_SIZE_PT && r.height >= MIN_IMAGE_SIZE_PT)
+ .collect();
+ let is_full_page = |r: &crate::types::Rect| {
+ r.width > pw * MAX_IMAGE_PAGE_COVERAGE && r.height > ph * MAX_IMAGE_PAGE_COVERAGE
+ };
+ let full_page_image = sized.iter().any(|r| is_full_page(r));
+ let counted: Vec<&crate::types::Rect> =
+ sized.iter().copied().filter(|r| !is_full_page(r)).collect();
+ let has_images = !counted.is_empty();
+
+ let (image_area_sum, largest_image_area) =
+ counted.iter().fold((0.0_f32, 0.0_f32), |(sum, max), r| {
+ let area = r.width.max(0.0) * r.height.max(0.0);
+ (sum + area, max.max(area))
+ });
+ let (image_coverage, largest_image_coverage) = if page_area > 0.0 {
+ (
+ (image_area_sum / page_area).min(1.0),
+ (largest_image_area / page_area).min(1.0),
+ )
+ } else {
+ (0.0, 0.0)
+ };
+ let text_bbox_area: f32 = page
+ .text_items
+ .iter()
+ .filter(|item| !is_unusable_native(item))
+ .map(|item| item.width * item.height)
+ .sum();
+ let text_coverage = if page_area > 0.0 {
+ text_bbox_area / page_area
+ } else {
+ 0.0
+ };
+
+ let sparse_text = text_length < 2000 && text_coverage < 0.15;
+ // Native text comes straight from the source XML — a garbled result would
+ // be an engine bug, not a font-encoding casualty. Run the shared detector
+ // anyway so the two paths can never silently diverge on the predicate.
+ let is_garbled = page_is_garbled(page);
+
+ let mut reasons = Vec::new();
+ if text_length < 20 {
+ reasons.push(if full_page_image {
+ ComplexityReason::Scanned
+ } else {
+ ComplexityReason::NoText
+ });
+ } else if sparse_text {
+ reasons.push(ComplexityReason::SparseText);
+ }
+ if has_images {
+ reasons.push(ComplexityReason::EmbeddedImages);
+ }
+ if is_garbled {
+ reasons.push(ComplexityReason::Garbled);
+ }
+ let needs_ocr = !reasons.is_empty();
+ let uncovered_vector_area = (!needs_ocr).then_some(0.0);
+
+ // Layout half. `figure` coverage from ALL placed images (the PDF layout
+ // half counts every figure region, full-page ones included).
+ let all_image_area: f32 = image_rects
+ .iter()
+ .map(|r| r.width.max(0.0) * r.height.max(0.0))
+ .sum();
+ let figure_coverage = if page_area > 0.0 && all_image_area > 0.0 {
+ (all_image_area / page_area).min(1.0)
+ } else {
+ 0.0
+ };
+ let column_count = column_count.max(1);
+ let mut layout_reasons = Vec::new();
+ if column_count >= 2 {
+ layout_reasons.push(LayoutComplexityReason::MultiColumn);
+ }
+ if table_count > 0 {
+ layout_reasons.push(LayoutComplexityReason::TableLikely);
+ }
+ if figure_coverage >= DENSE_GRAPHICS_MIN_COVERAGE {
+ layout_reasons.push(LayoutComplexityReason::DenseGraphics);
+ }
+ let layout = LayoutComplexityStats {
+ column_count,
+ ruled_table_count: table_count,
+ ruled_table_coverage: 0.0,
+ text_table_run_count: 0,
+ figure_count: image_rects.len(),
+ figure_coverage,
+ is_complex: !layout_reasons.is_empty(),
+ reasons: layout_reasons,
+ };
+
+ PageComplexityStats {
+ page_number: page.page_number,
+ text_length,
+ text_coverage,
+ has_substantial_images: has_images,
+ image_block_count: counted.len(),
+ image_coverage,
+ largest_image_coverage,
+ full_page_image,
+ uncovered_vector_area,
+ is_garbled,
+ page_area,
+ needs_ocr,
+ reasons,
+ layout: Some(layout),
+ }
+}
+
/// Why a page's layout is expected to be hard to reconstruct faithfully.
/// Orthogonal to `ComplexityReason`: none of these imply OCR — they signal
/// that the text-only path may mangle reading order or structure, so a caller
@@ -1026,6 +1181,130 @@ mod tests {
assert_eq!(count_columns(&leaf(0), 0), 0);
}
+ #[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]
+ mod native {
+ use super::super::*;
+ use crate::types::Rect;
+
+ fn item(text: &str, x: f32, y: f32, w: f32, h: f32) -> TextItem {
+ TextItem {
+ text: text.to_string(),
+ x,
+ y,
+ width: w,
+ height: h,
+ ..TextItem::default()
+ }
+ }
+
+ fn page(items: Vec<TextItem>) -> Page {
+ Page {
+ page_number: 1,
+ page_width: 612.0,
+ page_height: 792.0,
+ content_bounds: None,
+ 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,
+ }
+ }
+
+ fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect {
+ Rect {
+ x,
+ y,
+ width: w,
+ height: h,
+ }
+ }
+
+ #[test]
+ fn text_dense_page_is_simple_with_known_zero_vector_area() {
+ // 40 wide items -> text_length >= 20 and coverage >= 15%.
+ let items: Vec<TextItem> = (0..40)
+ .map(|i| item("some meaningful text", 40.0, 20.0 * i as f32, 500.0, 18.0))
+ .collect();
+ let stats = calculate_native_page_complexity(&page(items), &[], 0, 1);
+ assert!(!stats.needs_ocr);
+ assert!(stats.reasons.is_empty());
+ // Known zero, not unmeasured: vector text cannot exist natively.
+ assert_eq!(stats.uncovered_vector_area, Some(0.0));
+ let layout = stats.layout.expect("native stats always carry layout");
+ assert_eq!(layout.column_count, 1);
+ assert!(!layout.is_complex);
+ }
+
+ #[test]
+ fn tables_columns_and_images_drive_layout_reasons() {
+ let items = vec![item(
+ "cell text and more cell text",
+ 40.0,
+ 40.0,
+ 500.0,
+ 700.0,
+ )];
+ // One large inline figure (not full-page).
+ let figures = [rect(100.0, 100.0, 400.0, 300.0)];
+ let stats = calculate_native_page_complexity(&page(items), &figures, 2, 2);
+ assert!(
+ stats.reasons.contains(&ComplexityReason::EmbeddedImages),
+ "sized inline image counts"
+ );
+ let layout = stats.layout.unwrap();
+ assert_eq!(layout.ruled_table_count, 2);
+ assert_eq!(layout.column_count, 2);
+ assert!(
+ layout
+ .reasons
+ .contains(&LayoutComplexityReason::TableLikely)
+ );
+ assert!(
+ layout
+ .reasons
+ .contains(&LayoutComplexityReason::MultiColumn)
+ );
+ assert!(
+ layout
+ .reasons
+ .contains(&LayoutComplexityReason::DenseGraphics),
+ "400x300 over 612x792 is ~25% coverage"
+ );
+ assert!(layout.is_complex);
+ }
+
+ #[test]
+ fn full_page_image_with_no_text_reads_as_scanned() {
+ let figures = [rect(0.0, 0.0, 612.0, 792.0)];
+ let stats = calculate_native_page_complexity(&page(Vec::new()), &figures, 0, 1);
+ assert!(stats.reasons.contains(&ComplexityReason::Scanned));
+ assert!(stats.full_page_image);
+ assert_eq!(
+ stats.image_block_count, 0,
+ "full-page background is not an inline figure"
+ );
+ // The cheap predicate fired, so the (zero) vector walk is skipped,
+ // mirroring the PDF flow's None.
+ assert_eq!(stats.uncovered_vector_area, None);
+ }
+
+ #[test]
+ fn tiny_decorations_are_ignored() {
+ let items: Vec<TextItem> = (0..40)
+ .map(|i| item("some meaningful text", 40.0, 20.0 * i as f32, 500.0, 18.0))
+ .collect();
+ // A 10pt icon: below MIN_IMAGE_SIZE_PT on both axes.
+ let figures = [rect(40.0, 40.0, 10.0, 10.0)];
+ let stats = calculate_native_page_complexity(&page(items), &figures, 0, 1);
+ assert!(!stats.has_substantial_images);
+ assert!(!stats.needs_ocr);
+ }
+ }
+
#[test]
fn test_polygon_rotation_horizontal() {
let p = [[0.0, 0.0], [100.0, 0.0], [100.0, 20.0], [0.0, 20.0]];
diff --git a/crates/liteparse/src/office/docx_layout.rs b/crates/liteparse/src/office/docx_layout.rs
index d02e778..328422d 100644
--- a/crates/liteparse/src/office/docx_layout.rs
+++ b/crates/liteparse/src/office/docx_layout.rs
@@ -23,7 +23,9 @@ use liteparse_docx::render::layout::draw_command::{DrawCommand, LayoutedPage, Ou
use liteparse_docx::render::layout::fragment::FontProps;
use liteparse_docx::render::layout::measurer::TextMeasurer;
-use crate::types::{ExtractedImage, OutlineTarget, Page, Rect, TextItem, WordBox};
+use crate::types::{
+ DocumentAnnotation, ExtractedImage, OutlineTarget, Page, Rect, TextItem, WordBox,
+};
/// Everything the native pipeline taps out of a laid-out document.
pub struct NativeLayout {
@@ -54,6 +56,7 @@ pub fn layout_to_pages(
layouted: &[LayoutedPage],
registry: &FontRegistry,
emit_word_boxes: bool,
+ extract_annotations: bool,
) -> NativeLayout {
let measurer = TextMeasurer::new(registry);
let mut pages = Vec::with_capacity(layouted.len());
@@ -64,6 +67,11 @@ pub fn layout_to_pages(
let page_height = lp.page_size.height.raw();
let mut text_items: Vec<TextItem> = Vec::new();
let mut links: Vec<(Rect, String)> = Vec::new();
+ // (target identity, uri, per-word rect) in stream order; one
+ // `w:hyperlink`'s words share one `Rc` target, so pointer identity
+ // groups the words of a hyperlink instance without comparing URLs
+ // (two links to the same URL stay two annotations).
+ let mut link_spans: Vec<(usize, Option<String>, Rect)> = Vec::new();
// Indices into `outline` whose heading bracket is still open and has
// no y yet — resolved by the first Text command inside the bracket.
let mut open_headings: Vec<usize> = Vec::new();
@@ -154,14 +162,37 @@ pub fn layout_to_pages(
});
}
DrawCommand::LinkAnnotation { rect, url } => {
- links.push((
+ let r = Rect {
+ x: rect.origin.x.raw(),
+ y: rect.origin.y.raw(),
+ width: rect.size.width.raw(),
+ height: rect.size.height.raw(),
+ };
+ if extract_annotations {
+ link_spans.push((
+ std::rc::Rc::as_ptr(url) as *const u8 as usize,
+ Some(url.to_string()),
+ r.clone(),
+ ));
+ }
+ links.push((r, url.to_string()));
+ }
+ // Internal links (TOC entries, cross-refs to bookmarks) become
+ // uri-less `link` annotations — the same shape a GoTo link has
+ // on the PDF path, where the LibreOffice-converted document
+ // yields link annotations with no URI. They deliberately do
+ // NOT set `TextItem::link` or emit markdown links: bookmark
+ // anchors don't exist in the output document.
+ DrawCommand::InternalLink { rect, destination } if extract_annotations => {
+ link_spans.push((
+ std::rc::Rc::as_ptr(destination) as *const u8 as usize,
+ None,
Rect {
x: rect.origin.x.raw(),
y: rect.origin.y.raw(),
width: rect.size.width.raw(),
height: rect.size.height.raw(),
},
- url.to_string(),
));
}
DrawCommand::Outline(mark) => match mark {
@@ -182,6 +213,10 @@ pub fn layout_to_pages(
// never strikethrough; TextItem has no underline field and
// strike detection over border/separator lines would only
// false-positive. Images/paths/rects: deferred (module docs).
+ // NamedDestination is the bookmark *target* marker; nothing in
+ // the ParseResult contract can hold it (the PDF path drops
+ // GoTo destinations the same way — annotations carry only the
+ // source rects).
DrawCommand::Underline { .. }
| DrawCommand::Line { .. }
| DrawCommand::Rect { .. }
@@ -193,6 +228,7 @@ pub fn layout_to_pages(
}
assign_links(&mut text_items, &links);
+ let annotations = extract_annotations.then(|| merge_link_annotations(&link_spans));
for &b in &lp.block_starts {
block_pages
@@ -212,7 +248,7 @@ pub fn layout_to_pages(
vector_graphics: None,
struct_nodes: Vec::new(),
image_refs: Vec::new(),
- annotations: None,
+ annotations,
form_fields: None,
structure_tree: None,
});
@@ -281,6 +317,75 @@ fn assign_links(items: &mut [TextItem], links: &[(Rect, String)]) {
}
}
+/// Fold per-word link rects into annotation-shaped [`DocumentAnnotation`]s.
+///
+/// Spans arrive in stream (reading) order; a run of consecutive spans sharing
+/// one target identity is one hyperlink instance and becomes ONE annotation —
+/// `rect` is the union, `quadpoint_rects` hold one merged rect per laid-out
+/// line, matching the PDF path's quadpoint convention for multi-line links.
+/// Word rects of one line share the line box (same top and height from
+/// `cursor_y`/`line_height`), so a new line is detected by the vertical seam.
+fn merge_link_annotations(spans: &[(usize, Option<String>, Rect)]) -> Vec<DocumentAnnotation> {
+ /// Two same-line rects never differ vertically; this only absorbs f32
+ /// noise, not layout differences.
+ const LINE_EPSILON: f32 = 0.01;
+
+ let mut out = Vec::new();
+ let mut i = 0;
+ while i < spans.len() {
+ let target = spans[i].0;
+ let mut j = i;
+ while j < spans.len() && spans[j].0 == target {
+ j += 1;
+ }
+
+ let mut quads: Vec<Rect> = Vec::new();
+ for (_, _, r) in &spans[i..j] {
+ match quads.last_mut() {
+ Some(q)
+ if (q.y - r.y).abs() <= LINE_EPSILON
+ && (q.height - r.height).abs() <= LINE_EPSILON =>
+ {
+ let x0 = q.x.min(r.x);
+ let x1 = (q.x + q.width).max(r.x + r.width);
+ q.x = x0;
+ q.width = x1 - x0;
+ }
+ _ => quads.push(r.clone()),
+ }
+ }
+ let rect = quads.iter().skip(1).fold(quads[0].clone(), |acc, r| {
+ let x0 = acc.x.min(r.x);
+ let y0 = acc.y.min(r.y);
+ let x1 = (acc.x + acc.width).max(r.x + r.width);
+ let y1 = (acc.y + acc.height).max(r.y + r.height);
+ Rect {
+ x: x0,
+ y: y0,
+ width: x1 - x0,
+ height: y1 - y0,
+ }
+ });
+ // A single-line link needs no quadpoints beyond its rect — PDFium
+ // reports quadpoints there too, but one redundant rect adds noise for
+ // the consumer; multi-line is where quadpoints carry information.
+ let quadpoint_rects = if quads.len() > 1 { quads } else { Vec::new() };
+
+ out.push(DocumentAnnotation {
+ subtype: "link".to_string(),
+ contents: None,
+ created: None,
+ modified: None,
+ title: None,
+ rect: Some(rect),
+ quadpoint_rects,
+ uri: spans[i].1.clone(),
+ });
+ i = j;
+ }
+ out
+}
+
/// Native images tapped from the draw-command stream.
pub struct NativeImages {
/// One entry per surfaced placement, in (page, draw-order). Duplicate
@@ -422,6 +527,95 @@ pub fn collect_images(layouted: &[LayoutedPage]) -> NativeImages {
NativeImages { images, figure_ids }
}
+/// Placed-media rects per page, for the native complexity stats. Every
+/// `Image` command counts regardless of media format — EMF/SVG placements are
+/// visual content even though [`collect_images`] skips their bytes.
+pub fn image_rects_per_page(layouted: &[LayoutedPage]) -> Vec<Vec<Rect>> {
+ layouted
+ .iter()
+ .map(|lp| {
+ lp.commands
+ .iter()
+ .filter_map(|cmd| match cmd {
+ DrawCommand::Image { rect, .. } => Some(Rect {
+ x: rect.origin.x.raw(),
+ y: rect.origin.y.raw(),
+ width: rect.size.width.raw(),
+ height: rect.size.height.raw(),
+ }),
+ _ => None,
+ })
+ .collect()
+ })
+ .collect()
+}
+
+/// Section-declared column count per physical page (§17.6.4 `w:cols`), for
+/// the native complexity stats.
+///
+/// The join reuses the `block_starts` channel: a flattened body-block index
+/// locates its section by cumulative section length (the same flattening
+/// `emit_with_sources` tags blocks with), and `block_pages` says which page
+/// each block started on. A page hosting blocks from several sections (a
+/// `Continuous` break) takes the max. Pages with no block start — pure
+/// continuation pages — inherit the previous page's count, and anything
+/// before the first anchored block falls back to 1.
+pub fn page_column_counts(
+ resolved: &liteparse_docx::render::resolve::ResolvedDocument,
+ block_pages: &HashMap<usize, usize>,
+ n_pages: usize,
+) -> Vec<usize> {
+ let sections: Vec<(usize, usize)> = resolved
+ .sections
+ .iter()
+ .map(|s| {
+ let cols = s
+ .properties
+ .columns
+ .as_ref()
+ .and_then(|c| c.count)
+ .unwrap_or(1)
+ .max(1) as usize;
+ (s.blocks.len(), cols)
+ })
+ .collect();
+ column_counts_from_sections(&sections, block_pages, n_pages)
+}
+
+/// Pure core of [`page_column_counts`]: `sections` is `(block count, column
+/// count)` per section, in document order.
+fn column_counts_from_sections(
+ sections: &[(usize, usize)],
+ block_pages: &HashMap<usize, usize>,
+ n_pages: usize,
+) -> Vec<usize> {
+ // Flat-index boundary each section ends at.
+ let mut sec_end = Vec::with_capacity(sections.len());
+ let mut cum = 0usize;
+ for (len, _) in sections {
+ cum += len;
+ sec_end.push(cum);
+ }
+ let section_of = |flat: usize| sec_end.partition_point(|&end| end <= flat);
+
+ let mut cols = vec![0usize; n_pages];
+ for (&flat, &page) in block_pages {
+ let s = section_of(flat);
+ if let (Some(slot), Some(&(_, c))) = (cols.get_mut(page), sections.get(s)) {
+ *slot = (*slot).max(c);
+ }
+ }
+ let mut prev = 1usize;
+ for c in &mut cols {
+ if *c == 0 {
+ *c = prev;
+ } else {
+ prev = *c;
+ }
+ }
+ cols
+}
+
fn union_bounds(items: &[TextItem]) -> Option<Rect> {
let mut it = items.iter();
let first = it.next()?;
@@ -497,6 +691,7 @@ mod tests {
&[page(vec![text_cmd(72.0, 100.0, "Hello", 12.0)])],
&reg,
true,
+ false,
);
let item = &out.pages[0].text_items[0];
assert_eq!(item.x, 72.0);
@@ -510,6 +705,7 @@ mod tests {
&[page(vec![text_cmd(0.0, 100.0, "ab cd", 12.0)])],
&reg,
true,
+ false,
);
let words = &out2.pages[0].text_items[0].words;
assert_eq!(words.len(), 2);
@@ -553,6 +749,7 @@ mod tests {
])],
&reg,
false,
+ false,
);
let items = &out.pages[0].text_items;
assert_eq!(items[0].link.as_deref(), Some("https://example.com"));
@@ -587,6 +784,7 @@ mod tests {
])],
&reg,
false,
+ false,
);
assert_eq!(out.outline.len(), 1);
let t = &out.outline[0];
@@ -603,9 +801,144 @@ mod tests {
p0.block_starts = vec![3, 4];
let mut p1 = page(vec![]);
p1.block_starts = vec![4, 5];
- let out = layout_to_pages(&[p0, p1], &reg, false);
+ let out = layout_to_pages(&[p0, p1], &reg, false, false);
assert_eq!(out.block_pages[&3], 0);
assert_eq!(out.block_pages[&4], 0, "duplicate takes the earliest page");
assert_eq!(out.block_pages[&5], 1);
}
+
+ fn link_rect(x: f32, y: f32, w: f32, h: f32) -> PtRect {
+ PtRect::from_xywh(Pt::new(x), Pt::new(y), Pt::new(w), Pt::new(h))
+ }
+
+ /// One two-line hyperlink (one shared `Rc` target, three word rects) must
+ /// become ONE annotation whose rect is the union and whose quadpoints
+ /// carry one merged rect per line.
+ #[test]
+ fn multi_line_hyperlink_merges_to_one_annotation() {
+ let reg = registry();
+ let url: Rc<str> = Rc::from("https://example.com");
+ let out = layout_to_pages(
+ &[page(vec![
+ DrawCommand::LinkAnnotation {
+ rect: link_rect(72.0, 100.0, 30.0, 14.0),
+ url: Rc::clone(&url),
+ },
+ DrawCommand::LinkAnnotation {
+ rect: link_rect(105.0, 100.0, 40.0, 14.0),
+ url: Rc::clone(&url),
+ },
+ DrawCommand::LinkAnnotation {
+ rect: link_rect(72.0, 114.0, 25.0, 14.0),
+ url: Rc::clone(&url),
+ },
+ ])],
+ &reg,
+ false,
+ true,
+ );
+ let anns = out.pages[0].annotations.as_ref().unwrap();
+ assert_eq!(anns.len(), 1);
+ let a = &anns[0];
+ assert_eq!(a.subtype, "link");
+ assert_eq!(a.uri.as_deref(), Some("https://example.com"));
+ let r = a.rect.clone().unwrap();
+ assert_eq!((r.x, r.y), (72.0, 100.0));
+ assert_eq!((r.width, r.height), (73.0, 28.0));
+ assert_eq!(a.quadpoint_rects.len(), 2, "one merged rect per line");
+ assert_eq!(a.quadpoint_rects[0].width, 73.0);
+ assert_eq!(a.quadpoint_rects[1].width, 25.0);
+ }
+
+ /// Two hyperlinks to the SAME url are distinct `Rc` targets and must stay
+ /// two annotations; a single-line link carries no redundant quadpoints.
+ #[test]
+ fn distinct_hyperlink_instances_stay_separate_annotations() {
+ let reg = registry();
+ let out = layout_to_pages(
+ &[page(vec![
+ DrawCommand::LinkAnnotation {
+ rect: link_rect(72.0, 100.0, 30.0, 14.0),
+ url: Rc::from("https://example.com"),
+ },
+ DrawCommand::LinkAnnotation {
+ rect: link_rect(200.0, 100.0, 30.0, 14.0),
+ url: Rc::from("https://example.com"),
+ },
+ ])],
+ &reg,
+ false,
+ true,
+ );
+ let anns = out.pages[0].annotations.as_ref().unwrap();
+ assert_eq!(anns.len(), 2);
+ assert!(anns.iter().all(|a| a.quadpoint_rects.is_empty()));
+ }
+
+ /// Internal links (TOC/cross-refs) become uri-less `link` annotations —
+ /// the GoTo shape — and never attach `TextItem::link`.
+ #[test]
+ fn internal_links_become_uriless_annotations() {
+ let reg = registry();
+ let out = layout_to_pages(
+ &[page(vec![
+ text_cmd(72.0, 100.0, "See chapter 3", 12.0),
+ DrawCommand::InternalLink {
+ rect: link_rect(72.0, 88.0, 80.0, 14.0),
+ destination: Rc::from("_Toc123"),
+ },
+ ])],
+ &reg,
+ false,
+ true,
+ );
+ let anns = out.pages[0].annotations.as_ref().unwrap();
+ assert_eq!(anns.len(), 1);
+ assert_eq!(anns[0].subtype, "link");
+ assert_eq!(anns[0].uri, None);
+ assert_eq!(
+ out.pages[0].text_items[0].link, None,
+ "internal anchors must not become TextItem links"
+ );
+ }
+
+ /// Section columns land on the pages their blocks start on; a page hosting
+ /// two sections (Continuous break) takes the max; pure continuation pages
+ /// inherit the previous page's count; leading unanchored pages default 1.
+ #[test]
+ fn column_counts_join_sections_to_pages() {
+ // Section 0: 3 blocks, 2 columns. Section 1: 2 blocks, 1 column.
+ let sections = [(3usize, 2usize), (2, 1)];
+ let block_pages: HashMap<usize, usize> =
+ [(0, 0), (2, 1), (3, 1), (4, 2)].into_iter().collect();
+ assert_eq!(
+ column_counts_from_sections(&sections, &block_pages, 5),
+ vec![2, 2, 1, 1, 1],
+ "page 1 mixes both sections (max), pages 3-4 inherit"
+ );
+
+ // No block anchored before page 1: leading page falls back to 1.
+ let late: HashMap<usize, usize> = [(0, 1)].into_iter().collect();
+ assert_eq!(
+ column_counts_from_sections(&sections, &late, 3),
+ vec![1, 2, 2]
+ );
+ }
+
+ /// Flag off: `annotations` stays `None` (disabled ≠ enabled-but-empty),
+ /// and pages with the flag on but no links report `Some([])`.
+ #[test]
+ fn annotations_none_when_disabled_some_empty_when_enabled() {
+ let reg = registry();
+ let cmds = vec![text_cmd(72.0, 100.0, "plain", 12.0)];
+ let off = layout_to_pages(&[page(cmds.clone())], &reg, false, false);
+ assert!(off.pages[0].annotations.is_none());
+ let on = layout_to_pages(&[page(cmds)], &reg, false, true);
+ assert!(
+ on.pages[0]
+ .annotations
+ .as_ref()
+ .is_some_and(|v| v.is_empty())
+ );
+ }
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index a696d37..1d764b7 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -767,21 +767,20 @@ impl LiteParse {
#[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]
/// Config options the native DOCX path cannot honor. Hitting one with
/// `office_native` on is a hard `Config` error, not a fallback — see the
- /// check in `parse_input`. `extract_images` (native media bytes) and
- /// `extract_xfa_packets` (honestly empty — DOCX has no XFA) are
- /// supported and deliberately absent from this list.
+ /// check in `parse_input`. Supported and deliberately absent from this
+ /// list: `extract_images` (native media bytes), `extract_xfa_packets`
+ /// (honestly empty — DOCX has no XFA), `extract_annotations` (hyperlink +
+ /// internal-link rects merged to `link` annotations), and
+ /// `include_complexity` (native facts; see
+ /// `calculate_native_page_complexity`).
fn native_docx_ineligible_reason(&self) -> Option<&'static str> {
let c = &self.config;
- if c.extract_annotations {
- Some("extract_annotations")
- } else if c.extract_form_fields {
+ 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.include_complexity {
- Some("include_complexity")
} else if c.crop_box.is_some() {
Some("crop_box")
} else if c.skip_diagonal_text {
@@ -829,8 +828,12 @@ impl LiteParse {
)
.map_err(|e| LiteParseError::Conversion(format!("font registry: {e}")))?;
let layouted = liteparse_docx::render::layout_document(&resolved, &registry);
- let native =
- docx_layout::layout_to_pages(&layouted, &registry, self.config.emit_word_boxes);
+ let native = docx_layout::layout_to_pages(
+ &layouted,
+ &registry,
+ self.config.emit_word_boxes,
+ self.config.extract_annotations,
+ );
if self.config.ocr_enabled {
let total_chars: usize = native
@@ -875,24 +878,71 @@ impl LiteParse {
let all_blocks: Vec<crate::markdown_layout::Block> =
tagged.into_iter().map(|(b, _)| b).collect();
+ // Per-page complexity from native facts: placed-media rects, the
+ // page's table blocks (exact, not detected), and the section-declared
+ // column count — see `calculate_native_page_complexity` for the
+ // documented divergences from the PDF pair.
+ let complexity: Vec<Option<crate::ocr_merge::PageComplexityStats>> =
+ if self.config.include_complexity {
+ let col_counts =
+ docx_layout::page_column_counts(&resolved, &native.block_pages, n_pages);
+ let img_rects = docx_layout::image_rects_per_page(&layouted);
+ native
+ .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();
+ Some(crate::ocr_merge::calculate_native_page_complexity(
+ p,
+ img_rects.get(i).map(Vec::as_slice).unwrap_or(&[]),
+ tables,
+ col_counts[i],
+ ))
+ })
+ .collect()
+ } else {
+ vec![None; n_pages]
+ };
+
// Page selection, mirroring the PDF path: `target_pages` filters by
// 1-based page number, then `max_pages` truncates. The outline stays
// whole-document, as it does on the PDF path. A page selection also
// narrows the doc-level text to the surviving pages' blocks.
- let mut selected: Vec<(Page, Vec<crate::markdown_layout::Block>)> =
- native.pages.into_iter().zip(page_blocks).collect();
+ let mut selected: Vec<((Page, Vec<crate::markdown_layout::Block>), _)> = native
+ .pages
+ .into_iter()
+ .zip(page_blocks)
+ .zip(complexity)
+ .collect();
let mut page_filtered = false;
if let Some(targets) = self.resolve_target_pages()? {
let keep: std::collections::HashSet<usize> =
targets.iter().map(|p| *p as usize).collect();
- selected.retain(|(p, _)| keep.contains(&p.page_number));
+ 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 (pages, page_blocks): (Vec<_>, Vec<_>) = selected.into_iter().unzip();
+ let mut pages = Vec::with_capacity(selected.len());
+ let mut page_blocks = Vec::with_capacity(selected.len());
+ let mut page_stats = Vec::with_capacity(selected.len());
+ for ((p, b), s) in selected {
+ pages.push(p);
+ page_blocks.push(b);
+ page_stats.push(s);
+ }
let mut result = self.parse_from_native_blocks(
pages,
@@ -900,6 +950,7 @@ impl LiteParse {
(!page_filtered).then_some(all_blocks),
native.outline,
images,
+ page_stats,
);
// Same post-passes as the PDF path, same order: duplicate figure refs
@@ -1021,12 +1072,14 @@ impl LiteParse {
all_blocks: Option<Vec<crate::markdown_layout::Block>>,
outline: Vec<OutlineTarget>,
images: Vec<crate::types::ExtractedImage>,
+ page_stats: Vec<Option<crate::ocr_merge::PageComplexityStats>>,
) -> ParseResult {
let markdown_out = self.config.output_format == crate::config::OutputFormat::Markdown;
let parsed_pages: Vec<ParsedPage> = pages
.into_iter()
.zip(page_blocks)
- .map(|(p, blocks)| {
+ .zip(page_stats)
+ .map(|((p, blocks), stats)| {
let text = native_page_text(&p.text_items);
let markdown = if markdown_out {
crate::markdown_layout::render_blocks(&blocks)
@@ -1052,8 +1105,8 @@ impl LiteParse {
figures: Vec::new(),
struct_nodes: Vec::new(),
image_refs: Vec::new(),
- complexity: None,
- annotations: None,
+ complexity: stats,
+ annotations: p.annotations,
form_fields: None,
structure_tree: None,
}
diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rs
index 0719e21..f80979f 100644
--- a/crates/liteparse/tests/integration_test.rs
+++ b/crates/liteparse/tests/integration_test.rs
@@ -424,3 +424,143 @@ async fn test_parse_docx_native_images_integration() {
);
}
}
+
+/// Native annotation extraction: per-word hyperlink rects merge to one
+/// `link` annotation per hyperlink instance (uri set), and internal links
+/// (TOC/cross-refs) surface as uri-less `link` annotations — the GoTo shape
+/// the LibreOffice-converted path produces for the same documents.
+#[cfg(feature = "docx-native")]
+#[tokio::test]
+#[serial]
+async fn test_parse_docx_native_annotations_integration() {
+ let lit = LiteParse::new(LiteParseConfig {
+ extract_annotations: true,
+ quiet: true,
+ ..Default::default()
+ });
+
+ // External hyperlinks.
+ let parsed = lit
+ .parse("../../docx_files/legal/uk_parl_media_bill_ia.docx")
+ .await
+ .expect("native parse succeeds");
+ let anns: Vec<_> = parsed
+ .pages
+ .iter()
+ .flat_map(|p| p.annotations.as_deref().expect("enabled flag → Some"))
+ .collect();
+ assert!(!anns.is_empty(), "hyperlinks surface as annotations");
+ assert!(anns.iter().all(|a| a.subtype == "link"));
+ assert!(
+ anns.iter().all(|a| a.uri.is_some()),
+ "this doc has only external links"
+ );
+ for a in &anns {
+ let r = a.rect.as_ref().expect("every link has a rect");
+ assert!(r.width > 0.0 && r.height > 0.0);
+ }
+ // Word-grain rects must have been merged: fewer annotations than linked
+ // words (this doc has 83 per-word link rects).
+ assert!(
+ anns.len() < 40,
+ "per-word rects merged into per-hyperlink annotations, got {}",
+ anns.len()
+ );
+
+ // Internal links: uri-less `link` annotations.
+ let parsed = lit
+ .parse("../../docx_files/legal/courts_8th_civil_jury.docx")
+ .await
+ .expect("native parse succeeds");
+ let internal = parsed
+ .pages
+ .iter()
+ .flat_map(|p| p.annotations.as_deref().unwrap_or_default())
+ .filter(|a| a.uri.is_none())
+ .count();
+ assert!(
+ internal > 0,
+ "internal links surface as uri-less annotations"
+ );
+
+ // Flag off: `annotations` stays None on every page.
+ let lit_off = LiteParse::new(LiteParseConfig {
+ quiet: true,
+ ..Default::default()
+ });
+ let parsed = lit_off
+ .parse("../../docx_files/legal/uk_parl_media_bill_ia.docx")
+ .await
+ .expect("native parse succeeds");
+ assert!(parsed.pages.iter().all(|p| p.annotations.is_none()));
+}
+
+/// Native complexity: layout signals come from source facts — the
+/// section-declared column count and the page's actual table blocks — not
+/// from geometric detection.
+#[cfg(feature = "docx-native")]
+#[tokio::test]
+#[serial]
+async fn test_parse_docx_native_complexity_integration() {
+ let lit = LiteParse::new(LiteParseConfig {
+ include_complexity: true,
+ quiet: true,
+ ..Default::default()
+ });
+
+ // This doc's first page declares 2- and 3-column sections (§17.6.4).
+ let parsed = lit
+ .parse("../../docx_files/financial/cfpb_credit_dispute_letter.docx")
+ .await
+ .expect("native parse succeeds");
+ let stats: Vec<_> = parsed
+ .pages
+ .iter()
+ .map(|p| {
+ p.complexity
+ .as_ref()
+ .expect("flag on → stats on every page")
+ })
+ .collect();
+ let layouts: Vec<_> = stats
+ .iter()
+ .map(|c| c.layout.as_ref().expect("native stats carry layout"))
+ .collect();
+ assert!(
+ layouts.iter().any(|l| l.column_count >= 2),
+ "section-declared multi-column surfaces"
+ );
+ // Native text is never vector-outline text: the area is a known zero
+ // (or None when a cheaper predicate fired), never a positive value.
+ assert!(
+ stats
+ .iter()
+ .all(|c| c.uncovered_vector_area.unwrap_or(0.0) == 0.0)
+ );
+
+ // Table pages report TableLikely from actual table blocks.
+ let parsed = lit
+ .parse("../../docx_files/enterprise/nitaac_sow_template.docx")
+ .await
+ .expect("native parse succeeds");
+ assert!(
+ parsed.pages.iter().any(|p| {
+ p.complexity
+ .as_ref()
+ .and_then(|c| c.layout.as_ref())
+ .is_some_and(|l| l.ruled_table_count > 0)
+ }),
+ "table blocks drive the table-likely signal"
+ );
+
+ // Flag off: no complexity on any page.
+ let lit_off = LiteParse::new(LiteParseConfig {
+ quiet: true,
+ ..Default::default()
+ });
+ let parsed = lit_off
+ .parse("../../docx_files/financial/cfpb_credit_dispute_letter.docx")
+ .await
+ .expect("native parse succeeds");
+ assert!(parsed.pages.iter().all(|p| p.complexity.is_none()));
+}