Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewichb93bcf9c6dbc
diff --git a/Cargo.lock b/Cargo.lock
index 8057bfb..698724e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -389,6 +389,20 @@ name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.2",
+]
[[package]]
name = "byteorder"
@@ -1174,6 +1188,15 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+[[package]]
+name = "font-types"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75382bc7392ef10aad10935f92fc3db36d2d4dad0e5d96d8d65e04f89a07ec39"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "fontconfig-parser"
version = "0.5.8"
@@ -2052,10 +2075,13 @@ name = "liteparse-docx"
version = "0.1.0"
dependencies = [
"bitflags 2.13.1",
+ "fontdb",
"log",
"quick-xml",
"rustc-hash",
"serde",
+ "serde_json",
+ "skrifa",
"thiserror 2.0.19",
"unicode-normalization",
"unicode-properties",
@@ -3385,6 +3411,17 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "read-fonts"
+version = "0.42.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c69341f5f744623061a258e9d06a0213783a89ec23b6efb88a1c0c4ed285559"
+dependencies = [
+ "bytemuck",
+ "font-types",
+ "once_cell",
+]
+
[[package]]
name = "reborrow"
version = "0.5.5"
@@ -4042,6 +4079,16 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
+[[package]]
+name = "skrifa"
+version = "0.45.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd5b090b1690f1c63a8659574ea987c557f1cc571e24dedcba89458f32d0ccb5"
+dependencies = [
+ "bytemuck",
+ "read-fonts",
+]
+
[[package]]
name = "slab"
version = "0.4.12"
diff --git a/crates/liteparse-docx/ATTRIBUTION.md b/crates/liteparse-docx/ATTRIBUTION.md
index a82ce66..92a8bf4 100644
--- a/crates/liteparse-docx/ATTRIBUTION.md
+++ b/crates/liteparse-docx/ATTRIBUTION.md
@@ -4,9 +4,12 @@ This crate is a vendored subset of **[dxpdf](https://github.com/nerdy-pro/dxpdf)
v0.4.0** by nerdy.pro, used under the MIT License (see `LICENSE`).
Upstream is a DOCX→PDF engine (`parse → resolve → layout → subset → paint`)
-built on Skia. We vendor only the first two stages, which contain no Skia
-references, so the result is pure Rust and builds on musl (rust-skia ships no
-musl prebuilts, and `skia-safe` on musl falls back to a ~1hr from-source build).
+built on Skia. We vendor `parse → resolve → layout`, with layout's one
+production Skia dependency (the `TextMeasurer`) rewritten over fontdb + skrifa,
+so the result is pure Rust and builds on musl (rust-skia ships no musl
+prebuilts, and `skia-safe` on musl falls back to a ~1hr from-source build).
+`subset` and `paint` are PDF-emission concerns and stay out — layout ends at
+`LayoutedPage` (draw commands), not a PDF.
## What was copied verbatim
@@ -15,24 +18,65 @@ src/docx/ src/model/
src/field/ src/render/resolve/
src/error.rs
src/render/{dimension,geometry,error}.rs
-src/render/layout/draw_command.rs (referenced by resolve::shape_visuals)
-src/render/emoji/cluster.rs (referenced by draw_command)
+src/render/layout/ (everything except measurer.rs and mod-decl edits;
+ the whole build/fragment/paragraph/section/table
+ pagination engine — vendored 2026-08-13)
+src/render/emoji/cluster.rs
+src/render/emoji/resolve.rs
+render/mod.rs sections: estimate_cursor_y, resolve_and_layout,
+ layout_document, measure_header_footer_clearance,
+ measure_header_bottom, measure_footer_extent
```
## What was changed
-1. `src/render/emf.rs` — **dropped**. The subset's only genuine `skia_safe`
- import; converts Windows metafiles for the painter, unreachable from the
- structure path.
-2. `src/render/fonts.rs` — **replaced with a shim.** Upstream is a Skia
- `FontRegistry`; only `TypefaceEntry` is named here (one field of
- `DrawCommand::Text`). This is the seam for a future harfrust+skrifa port.
-3. `src/lib.rs`, `src/render/mod.rs`, `src/render/layout/mod.rs`,
- `src/render/emoji/mod.rs` — **rewritten** to declare only the copied modules.
-4. Edition-2024 pattern fixes (`ref mut` in an implicit borrow) in
- `render/resolve/properties.rs` and `docx/parse/rel_rewrite.rs` — upstream
- pins an older toolchain.
-5. Unknown-element tolerance — see below.
+1. `src/render/emf.rs` — **dropped**. Converts Windows metafiles for the
+ painter, unreachable from the structure and layout paths.
+2. `src/render/fonts.rs` — **rewritten over fontdb** (was a Skia
+ `FontRegistry`; briefly a shim between the structure vendor and the layout
+ vendor). Same consumed surface (`build`/`resolve`/`resolve_exact`/
+ `resolve_system_only`/`preload`, `TypefaceEntry`, `FontStyle`), with the
+ resolution rules proven in spikes 6–8: embedded-first, exact, face-alias
+ index (PostScript names + weight-qualified face names, with upstream's
+ ambiguity rule and `merged_alias_weight`), style-suffix strip, the
+ metric/visual substitution table, generic, and an explicit `LAST_RESORT`
+ chain (`fontdb::Family::SansSerif` is not a reliable floor). Every
+ resolution records a `ResolveRule`; only embedded/exact/alias/suffix/
+ `Substitution(Metric)` claim cross-host reproducibility. Geometry is
+ deliberately host-dependent beyond that (decision 2026-08-13: no bundled
+ fonts, no checksum pinning).
+3. `src/render/layout/measurer.rs` — **rewritten over skrifa.** Measurement
+ arithmetic copied verbatim (cmap advance sum, §17.3.2.45 text scale,
+ §17.3.2.35 char spacing); unmapped codepoints take .notdef's advance
+ (zero-contribution was tried and disproved, spike 6). Underline offsets are
+ negative-below — skrifa's `post` value passes through untouched; upstream's
+ comment at its `measurer.rs:156` states the opposite of what its code does.
+ Emoji cluster advances are cmap-only (upstream's own fallback path) until a
+ harfrust shaper is wired; `emoji/{shape,raster}.rs` are not vendored.
+4. `src/render/emoji/resolve.rs` — one import swapped (`skia_safe::FontStyle`
+ → `crate::render::fonts::FontStyle`); its test helper builds a
+ `TypefaceEntry` from the fontdb registry instead of a Skia `FontMgr`.
+5. `src/lib.rs`, `src/render/mod.rs`, `src/render/emoji/mod.rs` —
+ **rewritten** to declare only the vendored modules;
+ `src/render/layout/mod.rs` is now upstream's verbatim.
+6. Edition-2024 pattern fixes (`ref mut` in an implicit borrow) in
+ `render/resolve/properties.rs`, `docx/parse/rel_rewrite.rs`,
+ `render/layout/fragment/collect.rs`, `render/layout/paragraph/mod.rs` —
+ upstream pins an older toolchain.
+7. Test-only constructor edits: `FontRegistry::new(skia_safe::FontMgr::new())`
+ → `FontRegistry::new()` across layout test modules.
+8. Unknown-element tolerance — see below.
+
+## Layout parity (measured 2026-08-13, macOS host)
+
+Against upstream dxpdf 0.4.0 with Skia, same 48-doc corpus + long documents:
+48/48 within one page, 41/48 exact; of the exact docs, 37 have identical full
+draw-command censuses and 32 identical per-page text/char counts (identical
+line breaking). Every page diff is +1 and confined to documents requesting
+fonts the host lacks (Calibri/Cambria/Aptos) — the two engines fall back to
+different faces (Helvetica 1.00 em vs Arial-metrics 1.15 em line height), which
+is a host-font-book fact, not measurer error. `civil_jury.docx`: 616 vs 615
+pages (0.16% at 615 pages — drift does not compound).
## Fail-open parsing (the main deliberate divergence)
diff --git a/crates/liteparse-docx/Cargo.toml b/crates/liteparse-docx/Cargo.toml
index 1d3ec6e..fed2b1f 100644
--- a/crates/liteparse-docx/Cargo.toml
+++ b/crates/liteparse-docx/Cargo.toml
@@ -15,6 +15,15 @@ zip = { version = "2", default-features = false, features = ["deflate"] }
thiserror = "2"
log = "0.4"
rustc-hash = "2"
+# C′ measurer stack (spikes 6–8): resolution via fontdb, metrics/advances via
+# skrifa. fontdb is pinned to the 0.22 line to match what resvg/usvg already
+# drag into the liteparse tree, so resolution behaviour matches what the spike
+# harness measured.
+fontdb = "0.22"
+skrifa = "0.45"
unicode-segmentation = "1.13"
unicode-properties = "0.1"
unicode-normalization = "0.1"
+
+[dev-dependencies]
+serde_json = "1"
diff --git a/crates/liteparse-docx/examples/layout_probe.rs b/crates/liteparse-docx/examples/layout_probe.rs
new file mode 100644
index 0000000..3ac8505
--- /dev/null
+++ b/crates/liteparse-docx/examples/layout_probe.rs
@@ -0,0 +1,175 @@
+//! Layout probe — the vendored (fontdb + skrifa) twin of spike 2's harness.
+//!
+//! Taps `liteparse_docx::render::resolve_and_layout` and emits the same JSON
+//! Lines shape as `bench/docx_layout_spike` (which runs upstream dxpdf with
+//! Skia), so the two joins directly: same document in, page counts and
+//! command censuses out, one row per file. Divergence between the two is the
+//! cost of the measurer swap plus resolution differences — spike 6/8 predict
+//! ~0 where the host has the fonts.
+//!
+//! ```text
+//! cargo run --release -p liteparse-docx --example layout_probe -- <file.docx>...
+//! ```
+
+use std::time::Instant;
+
+use liteparse_docx::render::layout::draw_command::DrawCommand;
+use liteparse_docx::render::resolve_and_layout;
+use serde_json::json;
+
+/// Running min/max over text positions, so we can check the coordinate
+/// convention (origin corner, y direction) rather than assume it.
+#[derive(Default)]
+struct Extent {
+ min_x: Option<f32>,
+ max_x: Option<f32>,
+ min_y: Option<f32>,
+ max_y: Option<f32>,
+}
+
+impl Extent {
+ fn add(&mut self, x: f32, y: f32) {
+ self.min_x = Some(self.min_x.map_or(x, |v: f32| v.min(x)));
+ self.max_x = Some(self.max_x.map_or(x, |v: f32| v.max(x)));
+ self.min_y = Some(self.min_y.map_or(y, |v: f32| v.min(y)));
+ self.max_y = Some(self.max_y.map_or(y, |v: f32| v.max(y)));
+ }
+}
+
+/// Per-document command census. Counting every variant (not just `Text`) is
+/// the point: `LinkAnnotation` and `Underline` are facts the PDF path has to
+/// infer geometrically today, so their presence is part of what we are
+/// grading.
+#[derive(Default)]
+struct Census {
+ text: u64,
+ chars: u64,
+ underline: u64,
+ line: u64,
+ image: u64,
+ emoji: u64,
+ rect: u64,
+ link: u64,
+ internal_link: u64,
+ named_dest: u64,
+ outline: u64,
+ path: u64,
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ if args.is_empty() {
+ eprintln!("usage: layout_probe <file.docx>...");
+ std::process::exit(2);
+ }
+
+ for path in &args {
+ println!("{}", serde_json::to_string(&run_one(path)).unwrap());
+ }
+}
+
+fn run_one(path: &str) -> serde_json::Value {
+ let data = match std::fs::read(path) {
+ Ok(d) => d,
+ Err(e) => {
+ return json!({ "path": path, "ok": false, "stage": "read", "error": e.to_string() });
+ }
+ };
+
+ let t0 = Instant::now();
+ // The vendored parser is fail-open (unknown elements, attribute values
+ // and namespace collisions degrade instead of aborting), so parse
+ // failures here are unexpected — report them loudly.
+ let doc = match liteparse_docx::docx::parse(&data) {
+ Ok(d) => d,
+ Err(e) => {
+ return json!({ "path": path, "ok": false, "stage": "parse", "error": e.to_string() });
+ }
+ };
+ let parse_ms = t0.elapsed().as_secs_f64() * 1000.0;
+
+ // `resolve_and_layout` panics rather than erroring on a font-less system
+ // (it `expect`s the system FontMgr to expose a typeface), and layout is
+ // young code we have never run at corpus scale. Catch panics so one bad
+ // document yields a row instead of killing the whole run.
+ let t1 = Instant::now();
+ let laid = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| resolve_and_layout(doc)));
+ let layout_ms = t1.elapsed().as_secs_f64() * 1000.0;
+
+ let (_resolved, pages) = match laid {
+ Ok(v) => v,
+ Err(_) => {
+ return json!({ "path": path, "ok": false, "stage": "layout", "error": "panic" });
+ }
+ };
+
+ let mut census = Census::default();
+ let mut extent = Extent::default();
+ let mut page_rows = Vec::new();
+
+ for page in &pages {
+ let mut page_text = 0u64;
+ let mut page_chars = 0u64;
+
+ for cmd in &page.commands {
+ match cmd {
+ DrawCommand::Text { position, text, .. } => {
+ census.text += 1;
+ page_text += 1;
+ let n = text.chars().count() as u64;
+ census.chars += n;
+ page_chars += n;
+ extent.add(position.x.raw(), position.y.raw());
+ }
+ DrawCommand::Underline { .. } => census.underline += 1,
+ DrawCommand::Line { .. } => census.line += 1,
+ DrawCommand::Image { .. } => census.image += 1,
+ DrawCommand::EmojiCluster { .. } => census.emoji += 1,
+ DrawCommand::Rect { .. } => census.rect += 1,
+ DrawCommand::LinkAnnotation { .. } => census.link += 1,
+ DrawCommand::InternalLink { .. } => census.internal_link += 1,
+ DrawCommand::NamedDestination { .. } => census.named_dest += 1,
+ DrawCommand::Outline(_) => census.outline += 1,
+ // No catch-all: the compiler confirming this match is
+ // exhaustive is how we know the census can't silently miss a
+ // command class.
+ DrawCommand::Path { .. } => census.path += 1,
+ }
+ }
+
+ page_rows.push(json!({
+ "w": page.page_size.width.raw(),
+ "h": page.page_size.height.raw(),
+ "text_cmds": page_text,
+ "chars": page_chars,
+ }));
+ }
+
+ json!({
+ "path": path,
+ "ok": true,
+ "pages": pages.len(),
+ "parse_ms": parse_ms,
+ "layout_ms": layout_ms,
+ "page_rows": page_rows,
+ "commands": {
+ "text": census.text,
+ "chars": census.chars,
+ "underline": census.underline,
+ "line": census.line,
+ "image": census.image,
+ "emoji": census.emoji,
+ "rect": census.rect,
+ "link": census.link,
+ "internal_link": census.internal_link,
+ "named_dest": census.named_dest,
+ "outline": census.outline,
+ "path": census.path,
+
+ },
+ "text_extent": {
+ "min_x": extent.min_x, "max_x": extent.max_x,
+ "min_y": extent.min_y, "max_y": extent.max_y,
+ },
+ })
+}
diff --git a/crates/liteparse-docx/src/render/emoji/mod.rs b/crates/liteparse-docx/src/render/emoji/mod.rs
index 3607317..55125bc 100644
--- a/crates/liteparse-docx/src/render/emoji/mod.rs
+++ b/crates/liteparse-docx/src/render/emoji/mod.rs
@@ -1,7 +1,10 @@
-//! Only `cluster`, the Skia-free half of dxpdf's emoji handling.
+//! The Skia-free half of dxpdf's emoji handling.
//!
-//! `raster`, `resolve` and `shape` drive Skia colour-font (COLR/CBDT) painting
-//! and are omitted. `cluster` is pure Unicode segmentation and is referenced by
-//! `layout::draw_command`.
+//! `cluster` is pure Unicode segmentation (UAX #29 / UTS #51). `resolve` picks
+//! a color emoji typeface through the `FontRegistry` — typeface *identity*
+//! only, no rasterization. `raster` and `shape` drive Skia colour-font
+//! painting upstream and are omitted; cluster advances fall back to the
+//! cmap-only path in `layout::measurer`.
pub mod cluster;
+pub mod resolve;
diff --git a/crates/liteparse-docx/src/render/emoji/resolve.rs b/crates/liteparse-docx/src/render/emoji/resolve.rs
new file mode 100644
index 0000000..50dd643
--- /dev/null
+++ b/crates/liteparse-docx/src/render/emoji/resolve.rs
@@ -0,0 +1,508 @@
+//! Host-OS color emoji typeface resolution.
+//!
+//! Given an optional requested emoji family (extracted from `<w:rFonts>` per
+//! OOXML §17.3.2.26), find the best color emoji typeface available on the
+//! host. The resolution chain is:
+//!
+//! 1. The requested family, if any.
+//! 2. The host OS's native color emoji families, in priority order.
+//!
+//! When nothing matches we return [`EmojiTypeface::Unavailable`] with the
+//! full attempted list so the caller can log loudly. We never bundle fonts
+//! and never fall back to a non-emoji typeface — substituting (e.g.) Arial
+//! for a missing color emoji font would produce visible junk, not a
+//! degradation the user can act on.
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+
+use crate::render::fonts::FontStyle;
+
+use crate::render::fonts::{FontRegistry, TypefaceEntry};
+
+// ─── ADTs ────────────────────────────────────────────────────────────────────
+
+/// Closed enum of color emoji families we recognize. Adding a variant is a
+/// code change — there is no free-form string path that lets arbitrary names
+/// flow into the pipeline.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum EmojiFamily {
+ /// Microsoft, ships with Windows. COLR/CPAL with outline base layer.
+ SegoeUiEmoji,
+ /// Apple, ships with macOS. sbix bitmap-only — no outline layer.
+ AppleColorEmoji,
+ /// Google, available on most Linux distros via `fonts-noto-color-emoji`.
+ /// CBDT bitmap-only.
+ NotoColorEmoji,
+ /// Twitter (open-sourced as Twemoji), packaged on some Linux distros.
+ /// COLR with outlines.
+ TwitterColorEmoji,
+ /// JoyPixels (formerly EmojiOne), proprietary set found on a few Linux
+ /// hosts with the appropriate package installed.
+ JoyPixels,
+ /// Legacy EmojiOne Color, kept for backwards compatibility on hosts
+ /// where the older package is still installed.
+ EmojiOneColor,
+}
+
+impl EmojiFamily {
+ /// The canonical OOXML / fontconfig family name for this emoji family.
+ pub const fn family_name(self) -> &'static str {
+ match self {
+ EmojiFamily::SegoeUiEmoji => "Segoe UI Emoji",
+ EmojiFamily::AppleColorEmoji => "Apple Color Emoji",
+ EmojiFamily::NotoColorEmoji => "Noto Color Emoji",
+ EmojiFamily::TwitterColorEmoji => "Twitter Color Emoji",
+ EmojiFamily::JoyPixels => "JoyPixels",
+ EmojiFamily::EmojiOneColor => "EmojiOne Color",
+ }
+ }
+
+ /// Per-OS fallback chain consulted when the requested family is missing.
+ /// Order is "most likely to be installed" descending.
+ pub const fn host_default() -> &'static [EmojiFamily] {
+ HOST_DEFAULT
+ }
+
+ /// Recognize a family name (case-insensitive) as a known emoji family.
+ /// Returns `None` for any non-emoji name — the caller can then treat the
+ /// run as ordinary text.
+ pub fn from_name_ci(name: &str) -> Option<EmojiFamily> {
+ match name.to_ascii_lowercase().as_str() {
+ "segoe ui emoji" => Some(EmojiFamily::SegoeUiEmoji),
+ "apple color emoji" => Some(EmojiFamily::AppleColorEmoji),
+ "noto color emoji" => Some(EmojiFamily::NotoColorEmoji),
+ "twitter color emoji" => Some(EmojiFamily::TwitterColorEmoji),
+ "joypixels" => Some(EmojiFamily::JoyPixels),
+ "emojione color" => Some(EmojiFamily::EmojiOneColor),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(target_os = "macos")]
+const HOST_DEFAULT: &[EmojiFamily] = &[EmojiFamily::AppleColorEmoji];
+
+#[cfg(target_os = "windows")]
+const HOST_DEFAULT: &[EmojiFamily] = &[EmojiFamily::SegoeUiEmoji];
+
+#[cfg(target_os = "linux")]
+const HOST_DEFAULT: &[EmojiFamily] = &[
+ EmojiFamily::NotoColorEmoji,
+ EmojiFamily::TwitterColorEmoji,
+ EmojiFamily::JoyPixels,
+ EmojiFamily::EmojiOneColor,
+];
+
+#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
+const HOST_DEFAULT: &[EmojiFamily] = &[];
+
+/// Outcome of looking up a color emoji typeface on the host.
+///
+/// `Resolved` carries the actual [`TypefaceEntry`] from the registry — same
+/// identity used by the rest of the renderer, so paint/cache lookups work.
+/// `Unavailable` carries the full list of families we tried, so callers can
+/// produce an actionable warning ("install fonts-noto-color-emoji").
+#[derive(Clone, Debug)]
+pub enum EmojiTypeface {
+ Resolved {
+ family: EmojiFamily,
+ entry: TypefaceEntry,
+ },
+ Unavailable {
+ attempted: Vec<EmojiFamily>,
+ },
+}
+
+// ─── Test seam ───────────────────────────────────────────────────────────────
+
+/// Lookup hook for `resolve`: given an [`EmojiFamily`], return the typeface
+/// from the host (or `None` if absent). Production wires this to
+/// [`FontRegistry::resolve_exact`] via [`RegistryLookup`]; tests can substitute
+/// a deterministic mock.
+pub trait EmojiTypefaceLookup {
+ fn lookup(&self, family: EmojiFamily) -> Option<TypefaceEntry>;
+}
+
+/// Production lookup adapter — bridges [`EmojiTypefaceLookup`] to
+/// [`FontRegistry::resolve_exact`]. Always queries `FontStyle::normal()`;
+/// emoji typefaces are not weighted/italicized in OOXML.
+pub struct RegistryLookup<'a> {
+ pub registry: &'a FontRegistry,
+}
+
+impl EmojiTypefaceLookup for RegistryLookup<'_> {
+ fn lookup(&self, family: EmojiFamily) -> Option<TypefaceEntry> {
+ // Bypass embedded fonts: Word's subsetter strips color glyph tables
+ // (sbix/CBDT/COLR/SVG) when embedding an emoji font, so a docx-
+ // embedded "Segoe UI Emoji" rasterizes as black blobs even though
+ // it carries the right family name. Only the host's typeface can
+ // be relied on to carry color glyphs.
+ self.registry
+ .resolve_system_only(family.family_name(), FontStyle::normal())
+ }
+}
+
+// ─── Resolution ──────────────────────────────────────────────────────────────
+
+/// Stateless resolution. Returns either the first successful match or
+/// `Unavailable` with the complete attempted list.
+///
+/// Order: requested family first (deduped against the host default chain),
+/// then [`EmojiFamily::host_default`] in declaration order.
+pub fn resolve(lookup: &impl EmojiTypefaceLookup, requested: Option<EmojiFamily>) -> EmojiTypeface {
+ let mut attempted: Vec<EmojiFamily> = Vec::new();
+
+ if let Some(family) = requested {
+ attempted.push(family);
+ if let Some(entry) = lookup.lookup(family) {
+ return EmojiTypeface::Resolved { family, entry };
+ }
+ }
+
+ for &family in EmojiFamily::host_default() {
+ if attempted.contains(&family) {
+ continue;
+ }
+ attempted.push(family);
+ if let Some(entry) = lookup.lookup(family) {
+ return EmojiTypeface::Resolved { family, entry };
+ }
+ }
+
+ EmojiTypeface::Unavailable { attempted }
+}
+
+// ─── Cached resolver (per-render) ────────────────────────────────────────────
+
+/// Per-render wrapper around an [`EmojiTypefaceLookup`] that dedupes
+/// resolution by the requested family. Cheap to clone the resulting
+/// [`EmojiTypeface`] (Skia typefaces are reference-counted internally).
+///
+/// Lifetime equals the host lookup's lifetime — typically the
+/// [`FontRegistry`]'s, i.e. one render.
+pub struct EmojiResolver<L: EmojiTypefaceLookup> {
+ lookup: L,
+ cache: RefCell<HashMap<Option<EmojiFamily>, EmojiTypeface>>,
+}
+
+impl<L: EmojiTypefaceLookup> EmojiResolver<L> {
+ pub fn new(lookup: L) -> Self {
+ Self {
+ lookup,
+ cache: RefCell::new(HashMap::new()),
+ }
+ }
+
+ pub fn resolve(&self, requested: Option<EmojiFamily>) -> EmojiTypeface {
+ if let Some(cached) = self.cache.borrow().get(&requested) {
+ return cached.clone();
+ }
+ let result = resolve(&self.lookup, requested);
+ self.cache.borrow_mut().insert(requested, result.clone());
+ result
+ }
+
+ pub fn cached_count(&self) -> usize {
+ self.cache.borrow().len()
+ }
+}
+
+// ─── Tests ───────────────────────────────────────────────────────────────────
+//
+// `rN_` names are the resolution cases this module was built against: host
+// default with no request, a request the host lacks (falls through), a host
+// with the Linux default installed, a host with no emoji font at all
+// (`Unavailable` carrying the full attempted list), lookup caching, and
+// `from_name_ci` accepting/rejecting family names case-insensitively.
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::fonts::{FontRegistry, TypefaceId, TypefaceOrigin};
+ use std::cell::Cell;
+
+ /// Build a real `TypefaceEntry` from any system font. Used by tests that
+ /// need the resolved variant to carry a real face handle.
+ fn any_typeface_entry() -> TypefaceEntry {
+ let registry = FontRegistry::new();
+ let id = registry
+ .db()
+ .faces()
+ .next()
+ .expect("system has no fonts — cannot run test")
+ .id;
+ TypefaceEntry {
+ id,
+ origin: TypefaceOrigin::System {
+ typeface_id: TypefaceId(id),
+ },
+ }
+ }
+
+ /// Mock that succeeds only for the families in `available`, counting
+ /// every lookup so caching tests can verify dedup.
+ struct MockLookup {
+ available: Vec<EmojiFamily>,
+ calls: Cell<usize>,
+ }
+
+ impl MockLookup {
+ fn new(available: Vec<EmojiFamily>) -> Self {
+ Self {
+ available,
+ calls: Cell::new(0),
+ }
+ }
+ }
+
+ impl EmojiTypefaceLookup for MockLookup {
+ fn lookup(&self, family: EmojiFamily) -> Option<TypefaceEntry> {
+ self.calls.set(self.calls.get() + 1);
+ if self.available.contains(&family) {
+ Some(any_typeface_entry())
+ } else {
+ None
+ }
+ }
+ }
+
+ // ─── Real-host tests (platform-conditional) ──────────────────────────────
+
+ /// R1 — macOS host with no requested family resolves to AppleColorEmoji.
+ /// Apple Color Emoji is always present on macOS, so no runtime guard.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn r1_macos_default_resolves_to_apple_color_emoji() {
+ let registry = FontRegistry::new();
+ let lookup = RegistryLookup {
+ registry: &registry,
+ };
+ let result = resolve(&lookup, None);
+ assert!(
+ matches!(
+ result,
+ EmojiTypeface::Resolved {
+ family: EmojiFamily::AppleColorEmoji,
+ ..
+ }
+ ),
+ "expected Resolved(AppleColorEmoji), got {result:?}"
+ );
+ }
+
+ /// R2 — macOS host, requested SegoeUiEmoji (Windows family) is missing,
+ /// falls through to AppleColorEmoji.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn r2_macos_falls_back_when_requested_missing() {
+ let registry = FontRegistry::new();
+ let lookup = RegistryLookup {
+ registry: &registry,
+ };
+ let result = resolve(&lookup, Some(EmojiFamily::SegoeUiEmoji));
+ assert!(
+ matches!(
+ result,
+ EmojiTypeface::Resolved {
+ family: EmojiFamily::AppleColorEmoji,
+ ..
+ }
+ ),
+ "expected fallback to AppleColorEmoji, got {result:?}"
+ );
+ }
+
+ /// R3 — Linux host with Noto Color Emoji installed resolves to
+ /// NotoColorEmoji. Skipped if Noto is absent (no font bundling — we
+ /// don't fail CI for hosts without the optional package).
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn r3_linux_noto_when_installed() {
+ let registry = FontRegistry::new();
+ let lookup = RegistryLookup {
+ registry: &registry,
+ };
+ if lookup.lookup(EmojiFamily::NotoColorEmoji).is_none() {
+ eprintln!("skipping R3: Noto Color Emoji not installed on this host");
+ return;
+ }
+ let result = resolve(&lookup, None);
+ assert!(
+ matches!(
+ result,
+ EmojiTypeface::Resolved {
+ family: EmojiFamily::NotoColorEmoji,
+ ..
+ }
+ ),
+ "expected Resolved(NotoColorEmoji), got {result:?}"
+ );
+ }
+
+ // ─── Mock-host tests (deterministic, run on every platform) ──────────────
+
+ /// R4 — Host with no emoji font: the result reports every family we
+ /// attempted, in order, so callers can produce an actionable warning.
+ #[test]
+ fn r4_unavailable_reports_full_attempted_chain() {
+ let mock = MockLookup::new(vec![]);
+ let result = resolve(&mock, Some(EmojiFamily::SegoeUiEmoji));
+ match result {
+ EmojiTypeface::Unavailable { attempted } => {
+ assert_eq!(attempted.first(), Some(&EmojiFamily::SegoeUiEmoji));
+ let host_chain: &[EmojiFamily] = EmojiFamily::host_default();
+ let host_set: std::collections::HashSet<_> = host_chain.iter().copied().collect();
+ let attempted_set: std::collections::HashSet<_> =
+ attempted.iter().copied().collect();
+ for fam in &host_set {
+ assert!(
+ attempted_set.contains(fam),
+ "host default chain member {fam:?} must appear in attempted list"
+ );
+ }
+ }
+ other => panic!("expected Unavailable, got {other:?}"),
+ }
+ }
+
+ /// R4b — Requested family in the host chain is not duplicated: order
+ /// preserves "requested first, then host chain minus requested".
+ #[test]
+ fn r4b_attempted_list_dedupes_requested() {
+ let mock = MockLookup::new(vec![]);
+ let requested = EmojiFamily::host_default()
+ .first()
+ .copied()
+ .unwrap_or(EmojiFamily::NotoColorEmoji);
+ let result = resolve(&mock, Some(requested));
+ match result {
+ EmojiTypeface::Unavailable { attempted } => {
+ let count = attempted.iter().filter(|&&f| f == requested).count();
+ assert_eq!(count, 1, "requested family must appear exactly once");
+ }
+ _ => panic!("expected Unavailable"),
+ }
+ }
+
+ /// R5 — Caching dedupes repeat lookups for the same requested family.
+ #[test]
+ fn r5_emoji_resolver_caches_repeated_calls() {
+ let mock = MockLookup::new(vec![]);
+ // Move ownership into the resolver so we can introspect call count
+ // through a shared Cell.
+ let calls_handle = std::rc::Rc::new(Cell::new(0usize));
+ struct CountingLookup {
+ calls: std::rc::Rc<Cell<usize>>,
+ }
+ impl EmojiTypefaceLookup for CountingLookup {
+ fn lookup(&self, _family: EmojiFamily) -> Option<TypefaceEntry> {
+ self.calls.set(self.calls.get() + 1);
+ None
+ }
+ }
+ drop(mock);
+
+ let resolver = EmojiResolver::new(CountingLookup {
+ calls: calls_handle.clone(),
+ });
+ // First call: every family in the resolution chain is queried.
+ let _ = resolver.resolve(None);
+ let after_first = calls_handle.get();
+ assert!(
+ after_first >= EmojiFamily::host_default().len(),
+ "first call must query every host default family, got {after_first} calls"
+ );
+ // Second call: cache hit, no additional lookups.
+ let _ = resolver.resolve(None);
+ assert_eq!(
+ calls_handle.get(),
+ after_first,
+ "EmojiResolver must dedupe repeat calls with the same `requested`"
+ );
+ assert_eq!(resolver.cached_count(), 1);
+ }
+
+ /// R5b — Different `requested` values are cached independently, each
+ /// requiring its own underlying chain walk.
+ #[test]
+ fn r5b_distinct_requests_cache_independently() {
+ let resolver = EmojiResolver::new(MockLookup::new(vec![]));
+ let _ = resolver.resolve(None);
+ let _ = resolver.resolve(Some(EmojiFamily::SegoeUiEmoji));
+ let _ = resolver.resolve(Some(EmojiFamily::AppleColorEmoji));
+ assert_eq!(resolver.cached_count(), 3);
+ }
+
+ /// R6 — Recognize the canonical Segoe UI Emoji name.
+ #[test]
+ fn r6_from_name_canonical() {
+ assert_eq!(
+ EmojiFamily::from_name_ci("Segoe UI Emoji"),
+ Some(EmojiFamily::SegoeUiEmoji)
+ );
+ }
+
+ /// R7 — Non-emoji names return None.
+ #[test]
+ fn r7_from_name_non_emoji_returns_none() {
+ assert_eq!(EmojiFamily::from_name_ci("Calibri"), None);
+ assert_eq!(EmojiFamily::from_name_ci(""), None);
+ assert_eq!(EmojiFamily::from_name_ci("Arial Unicode MS"), None);
+ }
+
+ /// R8 — Recognition is case-insensitive (OOXML font names are CI).
+ #[test]
+ fn r8_from_name_case_insensitive() {
+ assert_eq!(
+ EmojiFamily::from_name_ci("segoe ui emoji"),
+ Some(EmojiFamily::SegoeUiEmoji)
+ );
+ assert_eq!(
+ EmojiFamily::from_name_ci("APPLE COLOR EMOJI"),
+ Some(EmojiFamily::AppleColorEmoji)
+ );
+ assert_eq!(
+ EmojiFamily::from_name_ci("NoTo CoLoR eMoJi"),
+ Some(EmojiFamily::NotoColorEmoji)
+ );
+ }
+
+ // ─── Round-trip and shape invariants ────────────────────────────────────
+
+ /// Every family round-trips through `family_name` → `from_name_ci`.
+ #[test]
+ fn family_name_round_trip() {
+ for fam in [
+ EmojiFamily::SegoeUiEmoji,
+ EmojiFamily::AppleColorEmoji,
+ EmojiFamily::NotoColorEmoji,
+ EmojiFamily::TwitterColorEmoji,
+ EmojiFamily::JoyPixels,
+ EmojiFamily::EmojiOneColor,
+ ] {
+ assert_eq!(EmojiFamily::from_name_ci(fam.family_name()), Some(fam));
+ }
+ }
+
+ /// Resolution with `requested = Some(host_default[0])` and the host
+ /// providing it must short-circuit on the first lookup.
+ #[test]
+ fn requested_match_short_circuits_chain() {
+ let target = EmojiFamily::host_default()
+ .first()
+ .copied()
+ .unwrap_or(EmojiFamily::NotoColorEmoji);
+ let mock = MockLookup::new(vec![target]);
+ let result = resolve(&mock, Some(target));
+ assert!(matches!(
+ result,
+ EmojiTypeface::Resolved { family, .. } if family == target
+ ));
+ assert_eq!(
+ mock.calls.get(),
+ 1,
+ "must not query host chain after requested matches"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/fonts.rs b/crates/liteparse-docx/src/render/fonts.rs
index 70b4b67..849975d 100644
--- a/crates/liteparse-docx/src/render/fonts.rs
+++ b/crates/liteparse-docx/src/render/fonts.rs
@@ -1,15 +1,978 @@
-//! Font-handle placeholder for the Skia-free subset.
+//! Font resolution with per-render ownership (`FontRegistry`) — fontdb + skrifa.
//!
-//! Upstream this module is a 1300-line `FontRegistry` built on `skia_safe`.
-//! The structure path (`docx::parse` → `render::resolve`) never resolves a
-//! typeface; the only reference is `draw_command::DrawCommand::Text`, which
-//! names `TypefaceEntry` in one field.
+//! Upstream this module is a 1,300-line registry built on Skia's `FontMgr`.
+//! This is the C′ rewrite: same public surface as far as the layout engine
+//! consumes it, with resolution answered by `fontdb` and metrics/advances by
+//! `skrifa` (see `layout::measurer`). It is the one production seam between
+//! dxpdf's layout engine and Skia — everything else in `render/layout/` is
+//! vendored verbatim.
//!
-//! This is the seam where a real font handle lands if/when the layout stage is
-//! ported (harfrust + skrifa, per stage 2 of the native-office plan). Until
-//! then it is deliberately opaque and uninhabitable-by-accident: nothing in the
-//! structure path constructs one.
+//! The resolution rules and their ordering are not invented here: they were
+//! derived and measured in `bench/docx_layout_spike` (spikes 6–8, recorded in
+//! `NATIVE_OFFICE_PLAN.md`). Where both engines have the requested face,
+//! agreement with Skia is 99.8% on widths and bit-exact on line metrics; every
+//! divergence beyond that was a *resolution* difference, which is why this
+//! file is mostly resolution policy and hardly any arithmetic.
+//!
+//! ## Host-dependence (decision, 2026-08-13)
+//!
+//! Geometry from this registry is deliberately **host-dependent** for
+//! documents whose fonts the host lacks: no fonts are bundled and no checksum
+//! pinning is done. Spike 8 proved a family name does not pin a font (two
+//! "Caladea"s differ by ~7% in advances), so determinism would require
+//! shipping files — a cost the project declined. What this file guarantees
+//! instead is *visibility*: every resolution records which [`ResolveRule`]
+//! answered, and only `Embedded`, `Exact`, alias/suffix hits and
+//! `Substitution(Metric)` claim to be reproducible across hosts.
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::model::{EmbeddedFont, EmbeddedFontVariant};
+
+// ─── Public types ───────────────────────────────────────────────────────────
+
+/// Weight + slant, the two axes OOXML runs actually vary. Stands in for
+/// `skia_safe::FontStyle` in the vendored surface; deliberately minimal.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct FontStyle {
+ /// CSS-scale weight (400 normal, 700 bold). `FontCache`-style call sites
+ /// only ever produce those two, but the alias index can land in between.
+ pub weight: u16,
+ pub italic: bool,
+}
+
+impl FontStyle {
+ pub fn normal() -> Self {
+ Self {
+ weight: 400,
+ italic: false,
+ }
+ }
+ pub fn bold() -> Self {
+ Self {
+ weight: 700,
+ italic: false,
+ }
+ }
+ pub fn italic() -> Self {
+ Self {
+ weight: 400,
+ italic: true,
+ }
+ }
+ pub fn bold_italic() -> Self {
+ Self {
+ weight: 700,
+ italic: true,
+ }
+ }
+ pub fn from_flags(bold: bool, italic: bool) -> Self {
+ Self {
+ weight: if bold { 700 } else { 400 },
+ italic,
+ }
+ }
+}
+
+/// Stable id for an embedded font registered in the registry.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct EmbeddedFontId(u32);
+
+impl EmbeddedFontId {
+ pub fn raw(self) -> u32 {
+ self.0
+ }
+}
+
+/// Identity for a resolved face — wraps the `fontdb` id. Used as a cache key
+/// by the measurer's cluster-advance memo.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct TypefaceId(pub fontdb::ID);
+
+/// Single source of truth for "where did this typeface come from?".
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum TypefaceOrigin {
+ /// Resolved from a font embedded in the DOCX (`word/fonts/*.odttf`).
+ Embedded { id: EmbeddedFontId },
+ /// Resolved from the host font database — exact match, alias,
+ /// substitution, or fallback. See [`ResolveRule`] for which.
+ System { typeface_id: TypefaceId },
+}
+
+/// A resolved face handle. Carried by value in fragments and draw commands,
+/// so it stays small: the bytes live in the registry's `fontdb::Database` and
+/// are borrowed at measure time.
#[derive(Clone, Debug)]
pub struct TypefaceEntry {
- _private: (),
+ pub id: fontdb::ID,
+ pub origin: TypefaceOrigin,
+}
+
+/// Cache key for resolved typefaces — case-insensitive family + weight + slant.
+#[derive(Hash, Eq, PartialEq, Clone, Debug)]
+pub struct TypefaceKey {
+ pub family_lc: String,
+ pub weight: u16,
+ pub italic: bool,
+}
+
+impl TypefaceKey {
+ pub fn new(family: &str, style: FontStyle) -> Self {
+ Self {
+ family_lc: family.to_lowercase(),
+ weight: style.weight,
+ italic: style.italic,
+ }
+ }
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum RegisterError {
+ #[error("invalid embedded font data for '{family}' ({variant:?})")]
+ InvalidFontData {
+ family: String,
+ variant: EmbeddedFontVariant,
+ },
+}
+
+// ─── Resolution rules (spike 6/8 artifacts) ─────────────────────────────────
+
+/// Whether a substitute reproduces the original's *metrics* or merely its look.
+///
+/// This distinction is the whole point of the table, not a nicety. Spike 7
+/// measured the cost of getting it wrong: Helvetica standing in for Arial is
+/// metric-compatible in **advances** (so a width test sees nothing) and off by
+/// **+14.99% in line metrics** (1.0000 em vs 1.1499 em) — a one-directional
+/// bias that compounds down every page.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum SubstKind {
+ /// Designed as a drop-in: same upem, same advances, same line metrics.
+ /// Geometry is reproducible across hosts wherever the substitute exists.
+ Metric,
+ /// Similar design, different metrics. Better than a generic sans, but it
+ /// does **not** buy cross-host determinism, and the report says so.
+ Visual,
+}
+
+/// Which rule produced a resolution. Recorded per request so a consumer can
+/// say *why* geometry might differ on another host, not just that it might.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum ResolveRule {
+ /// The DOCX embedded the font; the bytes travel with the document.
+ Embedded,
+ /// fontdb matched the requested family outright.
+ Exact,
+ /// The face-alias index answered — a PostScript name
+ /// (`AvenirNext-Regular`) or a weight-qualified face name
+ /// (`Calibri Light`) resolved to its family.
+ Alias,
+ /// A trailing style word was stripped from the family name
+ /// (`Times New Roman Bold` → `Times New Roman`).
+ StyleSuffix,
+ /// The substitution table fired.
+ Substitution(SubstKind),
+ /// Nothing matched; the host's generic sans-serif answered. **This is the
+ /// non-deterministic case** — the answer is a property of the machine.
+ Generic,
+ /// Even the generic missed — see `LAST_RESORT`. Also host-specific, but
+ /// distinguished from `Generic` because reaching it means the host's
+ /// `sans-serif` alias points at a font that is not installed, which is a
+ /// fact about the *image* worth surfacing on its own.
+ LastResort,
+ /// No face at all (an empty font database).
+ None,
+}
+
+impl ResolveRule {
+ pub fn name(self) -> &'static str {
+ match self {
+ ResolveRule::Embedded => "embedded",
+ ResolveRule::Exact => "exact",
+ ResolveRule::Alias => "alias",
+ ResolveRule::StyleSuffix => "style_suffix",
+ ResolveRule::Substitution(SubstKind::Metric) => "substitution_metric",
+ ResolveRule::Substitution(SubstKind::Visual) => "substitution_visual",
+ ResolveRule::Generic => "generic",
+ ResolveRule::LastResort => "last_resort",
+ ResolveRule::None => "none",
+ }
+ }
+
+ /// Is the geometry this produced expected to be identical on another host
+ /// (that has the same document and the named fonts)? Only the rules that
+ /// pin an identity qualify; a visual substitute and a generic fallback
+ /// both give geometry that is a property of the machine.
+ pub fn deterministic(self) -> bool {
+ matches!(
+ self,
+ ResolveRule::Embedded
+ | ResolveRule::Exact
+ | ResolveRule::Alias
+ | ResolveRule::StyleSuffix
+ | ResolveRule::Substitution(SubstKind::Metric)
+ )
+ }
+}
+
+/// Trailing style words stripped by [`strip_style_suffix`]. Family names carry
+/// a baked style suffix often enough to matter ("Times New Roman Bold" as a
+/// *family*). Skia's `FontMgr` absorbs these; `fontdb`'s family match does
+/// not, and would silently substitute instead.
+///
+/// Deliberately excludes `roman` and `book`: "Times New Roman" and "Century
+/// Schoolbook" are families whose last word *is* a style word, and stripping
+/// it sends the query somewhere that does not exist. This cost spike 6 a run —
+/// the fix looked inert because it had quietly broken its own best case.
+/// `black` and `light` stay in only because stripping is attempted after an
+/// exact family match has already failed, so "Arial Black" is never reached by
+/// this path on a host that has it.
+const STYLE_SUFFIXES: &[&str] = &[
+ "bold", "italic", "oblique", "regular", "light", "medium", "semibold", "demibold", "black",
+ "heavy", "thin",
+];
+
+/// Strip trailing style words, e.g. `Times New Roman Bold` → `Times New Roman`.
+/// Never strips the whole name (`Roman` alone stays `Roman`) — a family that
+/// *is* a style word is a real family, not a suffix.
+fn strip_style_suffix(family: &str) -> Option<String> {
+ let mut words: Vec<&str> = family.split_whitespace().collect();
+ let mut stripped = false;
+ while words.len() > 1
+ && STYLE_SUFFIXES.contains(&words[words.len() - 1].to_lowercase().as_str())
+ {
+ words.pop();
+ stripped = true;
+ }
+ stripped.then(|| words.join(" "))
+}
+
+/// Requested family → ordered substitute candidates.
+///
+/// Consulted only after embedded / exact / alias / style-suffix have all
+/// failed — so a host that really has the font is never diverted here.
+/// Ordering within a row is deliberate: metric clones first, visual
+/// approximations last, so a host with the real clone installed never falls
+/// through to an approximation.
+///
+/// Deliberately **not** listed: Verdana, Tahoma, Consolas, Segoe UI (beyond
+/// Selawik), Wingdings, Bahnschrift, and the CJK families. No metric-
+/// compatible free clone exists, and inventing a `Visual` row for them would
+/// convert a visible "this host fell back to a generic" into an invisible
+/// wrong answer. Absent families must stay loud.
+///
+/// The URW / TeX Gyre rows are all `Visual`, and that was **measured, not
+/// assumed** (spike 8): the whole set is advance-compatible with the
+/// PostScript base 35 and line-metric-incompatible (every face reports
+/// `lh = 1.200 em` against 1.000 em for the originals). Same trap as
+/// Helvetica-for-Arial, one layer down.
+///
+/// Trap encoded in the table itself: `Helvetica` and `Arial` must not point at
+/// the same clones the same way round. Liberation Sans clones **Arial** (so it
+/// is `Metric` there) and merely resembles Helvetica (so it is `Visual` here).
+/// Getting these rows interchanged is the easiest mistake in this table and
+/// would be invisible on a host missing both.
+const SUBSTITUTIONS: &[(&str, &[(&str, SubstKind)])] = &[
+ // Microsoft ClearType set → Google's Chrome OS metric clones.
+ ("Calibri", &[("Carlito", SubstKind::Metric)]),
+ // Carlito has no Light cut; the regular is metric-compatible with Calibri
+ // proper, not with Calibri Light, so this is honestly a Visual match.
+ ("Calibri Light", &[("Carlito", SubstKind::Visual)]),
+ ("Cambria", &[("Caladea", SubstKind::Metric)]),
+ // Microsoft's own metric-compatible stand-in for Segoe UI.
+ ("Segoe UI", &[("Selawik", SubstKind::Metric)]),
+ (
+ "Arial",
+ &[
+ ("Liberation Sans", SubstKind::Metric),
+ ("Arimo", SubstKind::Metric),
+ ("Helvetica", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Times New Roman",
+ &[
+ ("Liberation Serif", SubstKind::Metric),
+ ("Tinos", SubstKind::Metric),
+ ],
+ ),
+ (
+ "Courier New",
+ &[
+ ("Liberation Mono", SubstKind::Metric),
+ ("Cousine", SubstKind::Metric),
+ ],
+ ),
+ (
+ "Georgia",
+ &[("Gelasio", SubstKind::Metric), ("Tinos", SubstKind::Visual)],
+ ),
+ // The PostScript base 35 and their URW / TeX Gyre clones. "Times" and
+ // "Helvetica" are the PostScript originals, *not* the Microsoft ones.
+ (
+ "Helvetica",
+ &[
+ ("Nimbus Sans", SubstKind::Visual),
+ ("TeX Gyre Heros", SubstKind::Visual),
+ ("Arial", SubstKind::Visual),
+ ("Liberation Sans", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Times",
+ &[
+ ("Nimbus Roman", SubstKind::Visual),
+ ("TeX Gyre Termes", SubstKind::Visual),
+ ("Liberation Serif", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Courier",
+ &[
+ ("Nimbus Mono PS", SubstKind::Visual),
+ ("TeX Gyre Cursor", SubstKind::Visual),
+ ("Liberation Mono", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Palatino",
+ &[
+ ("P052", SubstKind::Visual),
+ ("TeX Gyre Pagella", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Palatino Linotype",
+ &[
+ ("P052", SubstKind::Visual),
+ ("TeX Gyre Pagella", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Book Antiqua",
+ &[
+ ("P052", SubstKind::Visual),
+ ("TeX Gyre Pagella", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Century Schoolbook",
+ &[
+ ("C059", SubstKind::Visual),
+ ("TeX Gyre Schola", SubstKind::Visual),
+ ],
+ ),
+ (
+ "New Century Schoolbook",
+ &[
+ ("C059", SubstKind::Visual),
+ ("TeX Gyre Schola", SubstKind::Visual),
+ ],
+ ),
+ (
+ "Bookman Old Style",
+ &[
+ ("URW Bookman", SubstKind::Visual),
+ ("TeX Gyre Bonum", SubstKind::Visual),
+ ],
+ ),
+ // Century Gothic imitates ITC Avant Garde Gothic; URW Gothic clones Avant
+ // Garde, so it is a clone of the *ancestor*, not of Century Gothic.
+ (
+ "Century Gothic",
+ &[
+ ("URW Gothic", SubstKind::Visual),
+ ("TeX Gyre Adventor", SubstKind::Visual),
+ ],
+ ),
+ (
+ "AvantGarde",
+ &[
+ ("URW Gothic", SubstKind::Visual),
+ ("TeX Gyre Adventor", SubstKind::Visual),
+ ],
+ ),
+ ("ZapfChancery", &[("Z003", SubstKind::Visual)]),
+ ("Monotype Corsiva", &[("Z003", SubstKind::Visual)]),
+ ("Symbol", &[("Standard Symbols PS", SubstKind::Visual)]),
+ ("ZapfDingbats", &[("D050000L", SubstKind::Visual)]),
+];
+
+fn substitutes_for(family: &str) -> &'static [(&'static str, SubstKind)] {
+ let lookup = |name: &str| {
+ SUBSTITUTIONS
+ .iter()
+ .find(|(key, _)| key.eq_ignore_ascii_case(name))
+ .map(|(_, subs)| *subs)
+ };
+ // A face-qualified name ("Calibri Light Italic") should still reach its
+ // family's row when the suffix-stripped query itself found nothing.
+ lookup(family)
+ .or_else(|| lookup(&strip_style_suffix(family)?))
+ .unwrap_or(&[])
+}
+
+/// Last-resort families, tried in order before taking any face at all.
+///
+/// `fontdb::Family::SansSerif` is **not** a reliable floor. `load_system_fonts`
+/// parses fontconfig and *overwrites* fontdb's built-in default with whatever
+/// the host's `sans-serif` alias names first — so in a container without
+/// DejaVu installed, the generic query returns `None`. Spike 8's first Linux
+/// run hit exactly this: 7 requests resolved to nothing and silently left the
+/// statistics. Measuring with a wrong font is a visible, attributable error;
+/// measuring nothing is silent.
+const LAST_RESORT: &[&str] = &[
+ "DejaVu Sans",
+ "Liberation Sans",
+ "Arial",
+ "Helvetica",
+ "Noto Sans",
+ "FreeSans",
+];
+
+// ─── Face-alias index ───────────────────────────────────────────────────────
+
+/// Names beyond the family name under which a host face is reachable:
+/// PostScript names (`AvenirNext-Regular` — Word writes these into `w:rFonts`
+/// often enough to matter) and weight-qualified face names (`Calibri Light`).
+/// Skia's `FontMgr` matches both; `fontdb::Query` matches family names only,
+/// so without this index those requests would silently substitute.
+///
+/// Mirrors upstream's `FaceAliasIndex`, including the ambiguity rule: a name
+/// claimed by two *different* (family, weight) targets resolves to nothing
+/// rather than to whichever face enumerated first.
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct FaceAlias {
+ family: String,
+ weight: u16,
+}
+
+#[derive(Clone, Debug)]
+enum AliasEntry {
+ Unique(FaceAlias),
+ Ambiguous,
+}
+
+#[derive(Default)]
+struct FaceAliasIndex {
+ aliases: HashMap<String, AliasEntry>,
+}
+
+impl FaceAliasIndex {
+ fn build(db: &fontdb::Database) -> Self {
+ let mut index = Self::default();
+ for face in db.faces() {
+ // Weight-bearing aliases only, as upstream: width and slant
+ // aliases would need a fuller OpenType identity model.
+ if face.style != fontdb::Style::Normal || face.stretch != fontdb::Stretch::Normal {
+ // PostScript names are still unique per face; index them even
+ // for italic faces so `SomeFont-BoldItalic` resolves. The
+ // weight carried is the face's own; the caller re-queries by
+ // family so slant comes from the request.
+ index.insert_ps_only(face);
+ continue;
+ }
+ let Some((family, _)) = face.families.first() else {
+ continue;
+ };
+ let alias = FaceAlias {
+ family: family.clone(),
+ weight: face.weight.0,
+ };
+ if !face.post_script_name.trim().is_empty() {
+ index.insert_alias(&face.post_script_name, alias.clone());
+ }
+ for weight_name in canonical_weight_names(face.weight.0) {
+ index.insert_alias(&format!("{family} {weight_name}"), alias.clone());
+ }
+ }
+ index
+ }
+
+ fn insert_ps_only(&mut self, face: &fontdb::FaceInfo) {
+ let Some((family, _)) = face.families.first() else {
+ return;
+ };
+ if face.post_script_name.trim().is_empty() {
+ return;
+ }
+ let alias = FaceAlias {
+ family: family.clone(),
+ weight: face.weight.0,
+ };
+ self.insert_alias(&face.post_script_name, alias);
+ }
+
+ fn insert_alias(&mut self, name: &str, alias: FaceAlias) {
+ use std::collections::hash_map::Entry;
+ match self.aliases.entry(face_name_key(name)) {
+ Entry::Vacant(entry) => {
+ entry.insert(AliasEntry::Unique(alias));
+ }
+ Entry::Occupied(mut entry) => match entry.get() {
+ AliasEntry::Unique(existing) if existing == &alias => {}
+ AliasEntry::Unique(_) => {
+ entry.insert(AliasEntry::Ambiguous);
+ }
+ AliasEntry::Ambiguous => {}
+ },
+ }
+ }
+
+ fn resolve(&self, name: &str) -> Option<&FaceAlias> {
+ match self.aliases.get(&face_name_key(name))? {
+ AliasEntry::Unique(alias) => Some(alias),
+ AliasEntry::Ambiguous => None,
+ }
+ }
+}
+
+fn face_name_key(name: &str) -> String {
+ name.split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .to_lowercase()
+}
+
+fn canonical_weight_names(weight: u16) -> &'static [&'static str] {
+ match weight {
+ 100 => &["Thin", "Hairline"],
+ 200 => &["ExtraLight", "Extra Light", "UltraLight", "Ultra Light"],
+ 300 => &["Light"],
+ 400 => &["Regular", "Normal"],
+ 500 => &["Medium"],
+ 600 => &["Semibold", "SemiBold", "Semi Bold", "DemiBold", "Demi Bold"],
+ 700 => &["Bold"],
+ 800 => &["ExtraBold", "Extra Bold", "UltraBold", "Ultra Bold"],
+ 900 => &["Black", "Heavy"],
+ _ => &[],
+ }
+}
+
+/// Combine the weight a face *name* carries with the weight the run requested.
+///
+/// The requested weight is not really a weight — it is built from a
+/// `bold: bool`, so `NORMAL` carries no information and must not participate:
+/// taking `max` unconditionally would promote `"Calibri Light"` (342) back to
+/// plain Calibri at 400, discarding exactly the information the alias index
+/// exists to honour. A bold request still raises a light face.
+fn merged_alias_weight(alias_weight: u16, requested_weight: u16) -> u16 {
+ if requested_weight > 400 {
+ alias_weight.max(requested_weight)
+ } else {
+ alias_weight
+ }
+}
+
+// ─── FontRegistry ───────────────────────────────────────────────────────────
+
+#[derive(Debug, Clone)]
+struct EmbeddedRecord {
+ family: String,
+ variant: EmbeddedFontVariant,
+ face: Option<fontdb::ID>,
+}
+
+pub struct FontRegistry {
+ db: fontdb::Database,
+ embedded: Vec<EmbeddedRecord>,
+ embedded_index: HashMap<(String, EmbeddedFontVariant), EmbeddedFontId>,
+ aliases: FaceAliasIndex,
+ typefaces: RefCell<HashMap<TypefaceKey, TypefaceEntry>>,
+ /// Which rule answered, per cache key. Kept beside the memo rather than
+ /// derived later: by the time you hold a `fontdb::ID` the reason is gone.
+ rules: RefCell<HashMap<TypefaceKey, ResolveRule>>,
+}
+
+impl FontRegistry {
+ /// Registry over the host's fonts, without any embedded fonts.
+ pub fn new() -> Self {
+ let mut db = fontdb::Database::new();
+ db.load_system_fonts();
+ let aliases = FaceAliasIndex::build(&db);
+ Self {
+ db,
+ embedded: Vec::new(),
+ embedded_index: HashMap::new(),
+ aliases,
+ typefaces: RefCell::new(HashMap::new()),
+ rules: RefCell::new(HashMap::new()),
+ }
+ }
+
+ /// Build a registry, registering all embedded fonts and preloading the
+ /// requested family/style combinations.
+ ///
+ /// Fails with [`crate::render::error::RenderError::NoFontsAvailable`] when
+ /// no face exists at all. Checking here rather than at the point of use is
+ /// what lets [`Self::resolve`] return a `TypefaceEntry` rather than an
+ /// `Option`: the take-any-face arm of `resolve_uncached` is unreachable
+ /// for any registry this constructor returns.
+ pub fn build(
+ embedded: &[EmbeddedFont],
+ families: &[String],
+ ) -> Result<Self, crate::render::error::RenderError> {
+ let mut reg = Self::new();
+ for ef in embedded {
+ if let Err(err) = reg.register_embedded(&ef.family, ef.variant, ef.data.clone()) {
+ log::warn!("{err}");
+ }
+ }
+ if reg.db.faces().next().is_none() {
+ return Err(crate::render::error::RenderError::NoFontsAvailable);
+ }
+ // Alias index rebuilt after embedded registration so embedded
+ // PostScript names resolve too.
+ reg.aliases = FaceAliasIndex::build(&reg.db);
+ reg.preload(families);
+ Ok(reg)
+ }
+
+ pub fn db(&self) -> &fontdb::Database {
+ &self.db
+ }
+
+ pub fn embedded_font_count(&self) -> usize {
+ self.embedded.len()
+ }
+
+ pub fn cached_typeface_count(&self) -> usize {
+ self.typefaces.borrow().len()
+ }
+
+ /// Register an embedded font. Subsequent `resolve` calls for the same
+ /// family + variant return this face in preference to system resolution —
+ /// dxpdf registers embedded fonts ahead of system resolution, and spike 6
+ /// found the one embedded-font document in the corpus (Georgia) agreeing
+ /// only by luck without this ordering.
+ pub fn register_embedded(
+ &mut self,
+ family: &str,
+ variant: EmbeddedFontVariant,
+ bytes: Vec<u8>,
+ ) -> Result<EmbeddedFontId, RegisterError> {
+ let ids = self
+ .db
+ .load_font_source(fontdb::Source::Binary(Arc::new(bytes)));
+ let face = ids.first().copied();
+ if face.is_none() {
+ return Err(RegisterError::InvalidFontData {
+ family: family.to_string(),
+ variant,
+ });
+ }
+ let id = EmbeddedFontId(self.embedded.len() as u32);
+ self.embedded.push(EmbeddedRecord {
+ family: family.to_string(),
+ variant,
+ face,
+ });
+ self.embedded_index
+ .insert((family.to_lowercase(), variant), id);
+ log::debug!("registered embedded font '{}' {:?}", family, variant);
+ Ok(id)
+ }
+
+ /// Family + variant for a registered embedded font.
+ pub fn embedded_meta(&self, id: EmbeddedFontId) -> (&str, EmbeddedFontVariant) {
+ let r = &self.embedded[id.0 as usize];
+ (&r.family, r.variant)
+ }
+
+ /// Resolve a typeface by family + style. Embedded fonts win over system.
+ /// Cached after the first resolution; later calls are O(1).
+ pub fn resolve(&self, family: &str, style: FontStyle) -> TypefaceEntry {
+ let key = TypefaceKey::new(family, style);
+ if let Some(entry) = self.typefaces.borrow().get(&key) {
+ return entry.clone();
+ }
+ let (entry, rule) = self.resolve_uncached(family, style);
+ self.typefaces
+ .borrow_mut()
+ .insert(key.clone(), entry.clone());
+ self.rules.borrow_mut().insert(key, rule);
+ entry
+ }
+
+ /// The rule that answered for this request, resolving first if needed.
+ /// This is the host-dependence signal: anything other than a
+ /// [`ResolveRule::deterministic`] rule means the resulting geometry is a
+ /// property of this machine.
+ pub fn resolve_rule(&self, family: &str, style: FontStyle) -> ResolveRule {
+ let key = TypefaceKey::new(family, style);
+ if !self.rules.borrow().contains_key(&key) {
+ self.resolve(family, style);
+ }
+ self.rules
+ .borrow()
+ .get(&key)
+ .copied()
+ .unwrap_or(ResolveRule::None)
+ }
+
+ fn query(&self, families: &[fontdb::Family], style: FontStyle) -> Option<fontdb::ID> {
+ self.db.query(&fontdb::Query {
+ families,
+ weight: fontdb::Weight(style.weight),
+ stretch: fontdb::Stretch::Normal,
+ style: if style.italic {
+ fontdb::Style::Italic
+ } else {
+ fontdb::Style::Normal
+ },
+ })
+ }
+
+ fn resolve_uncached(&self, family: &str, style: FontStyle) -> (TypefaceEntry, ResolveRule) {
+ // 1. Embedded, by family + variant.
+ let variant = variant_for_style(style);
+ if let Some(&eid) = self.embedded_index.get(&(family.to_lowercase(), variant)) {
+ if let Some(face) = self.embedded[eid.0 as usize].face {
+ log::debug!("[font] '{}' {:?} → embedded #{}", family, style, eid.0);
+ return (
+ TypefaceEntry {
+ id: face,
+ origin: TypefaceOrigin::Embedded { id: eid },
+ },
+ ResolveRule::Embedded,
+ );
+ }
+ }
+
+ // 2. Exact family match. fontdb declines a family it does not have
+ // (unlike fontconfig-backed Skia, which substitutes), so a hit here is
+ // genuinely the requested family — no exactness guard needed.
+ if let Some(id) = self.query(&[fontdb::Family::Name(family)], style) {
+ return (system_entry(id), ResolveRule::Exact);
+ }
+
+ // 3. Face alias: PostScript name or weight-qualified face name.
+ // Resolve to a *family*, then re-query with the merged weight and the
+ // requested slant — a PostScript name names one specific face, so
+ // taking it directly would pin `-Regular` even when the run asked for
+ // bold.
+ if let Some(alias) = self.aliases.resolve(family) {
+ let merged = FontStyle {
+ weight: merged_alias_weight(alias.weight, style.weight),
+ italic: style.italic,
+ };
+ if let Some(id) = self.query(&[fontdb::Family::Name(&alias.family)], merged) {
+ log::debug!(
+ "[font] '{}' {:?} → face alias '{}' {:?}",
+ family,
+ style,
+ alias.family,
+ merged
+ );
+ return (system_entry(id), ResolveRule::Alias);
+ }
+ }
+
+ // 4. Style suffix baked into the family name. The requested
+ // bold/italic still applies, so "Times New Roman Bold" lands on the
+ // real TNR bold face.
+ if let Some(base) = strip_style_suffix(family) {
+ if let Some(id) = self.query(&[fontdb::Family::Name(&base)], style) {
+ log::debug!(
+ "[font] '{}' {:?} → suffix-stripped '{}'",
+ family,
+ style,
+ base
+ );
+ return (system_entry(id), ResolveRule::StyleSuffix);
+ }
+ }
+
+ // 5. Substitution table. Candidates in table order, so a host carrying
+ // the real clone never falls through to a visual approximation.
+ for (candidate, kind) in substitutes_for(family) {
+ if let Some(id) = self.query(&[fontdb::Family::Name(candidate)], style) {
+ log::debug!(
+ "[font] '{}' {:?} → substitute '{}' ({:?})",
+ family,
+ style,
+ candidate,
+ kind
+ );
+ return (system_entry(id), ResolveRule::Substitution(*kind));
+ }
+ }
+
+ // 6. Whatever this host calls sans-serif.
+ if let Some(id) = self.query(&[fontdb::Family::SansSerif], style) {
+ log::debug!("[font] '{}' {:?} → generic sans-serif", family, style);
+ return (system_entry(id), ResolveRule::Generic);
+ }
+
+ // 7. Family::SansSerif can itself resolve to nothing (see
+ // LAST_RESORT). Walk an explicit list, then take *any* face in the
+ // database — unreachable from `build`, which rejects an empty
+ // database up front.
+ for name in LAST_RESORT {
+ if let Some(id) = self.query(&[fontdb::Family::Name(name)], style) {
+ return (system_entry(id), ResolveRule::LastResort);
+ }
+ }
+ // Unreachable for a registry from `FontRegistry::build`, which rejects
+ // an empty font database up front so this arm always has something to
+ // return — the same contract upstream documents for its Skia
+ // `legacy_make_typeface` arm.
+ let f = self
+ .db
+ .faces()
+ .next()
+ .expect("FontRegistry::build guarantees a last-resort face");
+ (system_entry(f.id), ResolveRule::LastResort)
+ }
+
+ /// Resolve by exact family + style match only — embedded first, then the
+ /// host — or `None`. No substitutes, no default fallback: necessary for
+ /// the emoji pipeline, where substituting a non-emoji typeface for a
+ /// missing color emoji font is never correct.
+ pub fn resolve_exact(&self, family: &str, style: FontStyle) -> Option<TypefaceEntry> {
+ let variant = variant_for_style(style);
+ if let Some(&eid) = self.embedded_index.get(&(family.to_lowercase(), variant)) {
+ if let Some(face) = self.embedded[eid.0 as usize].face {
+ return Some(TypefaceEntry {
+ id: face,
+ origin: TypefaceOrigin::Embedded { id: eid },
+ });
+ }
+ }
+ self.query(&[fontdb::Family::Name(family)], style)
+ .map(system_entry)
+ }
+
+ /// Resolve from the host font system only — bypasses embedded fonts.
+ /// Used by the color emoji pipeline: Word's font subsetter strips color
+ /// glyph tables (sbix/CBDT/COLR/SVG) when embedding emoji fonts, so a
+ /// docx-embedded "Segoe UI Emoji" carries the right family name but no
+ /// color glyphs and must not satisfy emoji resolution.
+ pub fn resolve_system_only(&self, family: &str, style: FontStyle) -> Option<TypefaceEntry> {
+ let id = self.query(&[fontdb::Family::Name(family)], style)?;
+ // An embedded face is a Binary source; reject it here.
+ let info = self.db.face(id)?;
+ if matches!(info.source, fontdb::Source::Binary(_)) {
+ return None;
+ }
+ Some(system_entry(id))
+ }
+
+ /// Pre-resolve all four style variants for each family.
+ pub fn preload(&self, families: &[String]) {
+ let styles = [
+ FontStyle::normal(),
+ FontStyle::bold(),
+ FontStyle::italic(),
+ FontStyle::bold_italic(),
+ ];
+ for family in families {
+ for &style in &styles {
+ self.resolve(family, style);
+ }
+ }
+ }
+
+ /// Snapshot of all cached entries.
+ pub fn cached_entries(&self) -> Vec<(TypefaceKey, TypefaceEntry)> {
+ self.typefaces
+ .borrow()
+ .iter()
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect()
+ }
+}
+
+impl Default for FontRegistry {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+// ─── Helpers ────────────────────────────────────────────────────────────────
+
+fn variant_for_style(style: FontStyle) -> EmbeddedFontVariant {
+ let bold = style.weight >= 600;
+ match (bold, style.italic) {
+ (true, true) => EmbeddedFontVariant::BoldItalic,
+ (true, false) => EmbeddedFontVariant::Bold,
+ (false, true) => EmbeddedFontVariant::Italic,
+ (false, false) => EmbeddedFontVariant::Regular,
+ }
+}
+
+fn system_entry(id: fontdb::ID) -> TypefaceEntry {
+ TypefaceEntry {
+ id,
+ origin: TypefaceOrigin::System {
+ typeface_id: TypefaceId(id),
+ },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn style_suffix_strips_trailing_style_words() {
+ assert_eq!(
+ strip_style_suffix("Times New Roman Bold").as_deref(),
+ Some("Times New Roman")
+ );
+ assert_eq!(
+ strip_style_suffix("Foo Bold Italic").as_deref(),
+ Some("Foo")
+ );
+ // Families whose last word is a style word must survive.
+ assert_eq!(strip_style_suffix("Times New Roman"), None);
+ assert_eq!(strip_style_suffix("Century Schoolbook"), None);
+ // Never strip down to nothing.
+ assert_eq!(strip_style_suffix("Bold"), None);
+ }
+
+ #[test]
+ fn substitution_lookup_reaches_family_through_face_name() {
+ // "Calibri Light" has its own (Visual) row; "Calibri Light Italic"
+ // does not, and must reach a row via suffix stripping.
+ assert!(!substitutes_for("Calibri").is_empty());
+ assert!(!substitutes_for("Calibri Light Italic").is_empty());
+ assert!(substitutes_for("Comic Sans MS").is_empty());
+ }
+
+ #[test]
+ fn merged_weight_ignores_content_free_normal() {
+ // NORMAL carries no information — must not promote a Light face.
+ assert_eq!(merged_alias_weight(300, 400), 300);
+ // A bold request still raises a light face.
+ assert_eq!(merged_alias_weight(300, 700), 700);
+ assert_eq!(merged_alias_weight(900, 700), 900);
+ }
+
+ #[test]
+ fn resolve_is_total_and_records_a_rule() {
+ let reg = FontRegistry::new();
+ if reg.db.faces().next().is_none() {
+ return; // fontless CI host: nothing to assert against
+ }
+ let _ = reg.resolve("Definitely Not A Font 123", FontStyle::normal());
+ let rule = reg.resolve_rule("Definitely Not A Font 123", FontStyle::normal());
+ assert!(
+ !rule.deterministic(),
+ "an unknown family must be flagged host-dependent, got {rule:?}"
+ );
+ // And a real family (any first face) resolves Exact.
+ let first_family = reg
+ .db
+ .faces()
+ .next()
+ .and_then(|f| f.families.first().map(|(n, _)| n.clone()))
+ .unwrap();
+ let _ = reg.resolve(&first_family, FontStyle::normal());
+ assert_eq!(
+ reg.resolve_rule(&first_family, FontStyle::normal()).name(),
+ "exact"
+ );
+ }
}
diff --git a/crates/liteparse-docx/src/render/layout/build/block.rs b/crates/liteparse-docx/src/render/layout/build/block.rs
new file mode 100644
index 0000000..3eb6c5f
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/build/block.rs
@@ -0,0 +1,748 @@
+use std::rc::Rc;
+
+use crate::model::{self, Block, Paragraph};
+use crate::render::dimension::Pt;
+use crate::render::layout::fragment::{FontProps, Fragment, FragmentCtx, collect_fragments};
+use crate::render::layout::paragraph::DropCapInfo;
+use crate::render::layout::section::LayoutBlock;
+use crate::render::resolve::color::{ColorContext, RgbColor, resolve_color};
+use crate::render::resolve::conditional::CellConditionalFormatting;
+use crate::render::resolve::properties::{merge_paragraph_properties, merge_run_properties};
+use crate::render::resolve::styles::ResolvedStyle;
+
+use super::convert::{
+ paragraph_style_from_props, populate_image_data, populate_underline_metrics,
+ resolve_paragraph_defaults,
+};
+use super::floating::{AnchorFrame, extract_floating_images};
+use super::table::build_table;
+use super::{BuildContext, BuildState};
+
+/// Recursively process a single model block into a layout block.
+///
+/// Returns `None` for drop cap paragraphs (consumed by the next paragraph)
+/// and section breaks (already handled by resolve).
+pub(super) fn build_block(
+ block: &Block,
+ available_width: Pt,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+ pending_dropcap: &mut Option<DropCapInfo>,
+) -> Option<LayoutBlock> {
+ match block {
+ Block::Paragraph(p) => build_paragraph_block(p, ctx, state, pending_dropcap, None, None),
+ Block::Table(t) => {
+ let built = build_table(t, available_width, ctx, state);
+ Some(LayoutBlock::Table {
+ rows: built.rows,
+ col_widths: built.col_widths,
+ cell_spacing: built.cell_spacing,
+ border_config: built.border_config,
+ indent: built.indent,
+ alignment: built.alignment,
+ float_info: built.float_info,
+ style_id: t.properties.style_id.clone(),
+ })
+ }
+ Block::SectionBreak(_) => None,
+ }
+}
+
+// ── Paragraph building ──────────────────────────────────────────────────────
+
+/// Build a paragraph into a layout block.
+/// Handles drop cap detection (§17.3.1.11), list labels, floating images.
+/// For table cells, pass `table_style` and `cond` to apply table formatting cascade.
+pub(super) fn build_paragraph_block(
+ p: &Paragraph,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+ pending_dropcap: &mut Option<DropCapInfo>,
+ table_style: Option<&ResolvedStyle>,
+ cond: Option<&CellConditionalFormatting>,
+) -> Option<LayoutBlock> {
+ let (mut fragments, mut merged_props) = build_fragments(p, ctx, state, table_style, cond);
+ // Drain immediately: this paragraph owns exactly the references its own
+ // fragment collection recorded. Draining before the drop-cap early return
+ // below keeps them from leaking into the next paragraph's batch, and
+ // before `build_note_content` re-enters `build_fragments` (a footnote body
+ // may itself carry references) from mixing the two levels together.
+ let fn_refs = state.footnotes.take_pending();
+
+ // §17.9.22: inject list label if paragraph has a numbering reference.
+ super::list_label::inject_list_label(p, &mut fragments, &mut merged_props, ctx, state);
+
+ // §17.3.1.29: a paragraph with no runs still occupies one line — the
+ // paragraph mark (¶) has a font-sized line height. Inject a LineBreak
+ // so the layout phase treats it as a real line. Without this, an empty
+ // paragraph's fragments are split by `split_at_page_breaks` into a
+ // single empty page-chunk, which `section::layout_section` drops,
+ // collapsing the line to zero height.
+ //
+ // Table cells use §17.4.66 (trailing-empty-after-table is structural
+ // and suppressed) in `build_cell_blocks` — that skip runs before this
+ // function, so genuinely structural terminators never reach us.
+ // Headers/footers have their own injection in
+ // `build_header_footer_content` (§17.10.1) and do not call this.
+ if fragments.is_empty() {
+ let (family, mut size, ..) = resolve_paragraph_defaults(
+ p,
+ ctx.resolved,
+ table_style.is_some(),
+ state.shape_default_text_color,
+ state.shape_default_font_family.as_deref(),
+ );
+ if let Some(ref mrp) = p.mark_run_properties {
+ if let Some(fs) = mrp.font_size {
+ size = Pt::from(fs);
+ }
+ }
+ let line_height = ctx.measurer.default_line_height(&family, size);
+ fragments.push(Fragment::LineBreak { line_height });
+ }
+
+ // Word suppresses Hyperlink character style (blue/underline) for ToC
+ // entries in print view. Strip visual hyperlink styling but keep the
+ // click annotation URL.
+ //
+ // §17.7.4.9: identified by the resolved style's *primary style name*
+ // (`toc 1` … `toc 9`, locale-independent), not by the `w:styleId`
+ // spelling — a `starts_with("TOC")` test both over-matches (an unrelated
+ // user style `TOCustom`) and under-matches (producers that don't spell
+ // their ToC style IDs `TOC1`).
+ let is_toc_entry = p
+ .style_id
+ .as_ref()
+ .and_then(|id| ctx.resolved.styles.get(id))
+ .is_some_and(|s| s.is_toc_entry);
+ if is_toc_entry {
+ for frag in &mut fragments {
+ if let Fragment::Text {
+ font,
+ color,
+ hyperlink_url,
+ ..
+ } = frag
+ {
+ if hyperlink_url.is_some() {
+ *color = RgbColor::BLACK;
+ // Rare (TOC hyperlinks only); clones this fragment's shared
+ // font on write.
+ Rc::make_mut(font).underline = false;
+ }
+ }
+ }
+ }
+
+ // §17.3.1.11: detect drop cap paragraph.
+ if let Some(model::FrameKind::DropCap {
+ style,
+ lines,
+ h_space: dc_h_space,
+ }) = merged_props.frame_properties
+ {
+ let drop_cap_lines = lines;
+ let width: Pt = fragments.iter().map(|f| f.width()).sum();
+ let height: Pt = fragments.iter().map(|f| f.height()).fold(Pt::ZERO, Pt::max);
+ let ascent: Pt = fragments
+ .iter()
+ .map(|f| match f {
+ Fragment::Text { metrics, .. } => metrics.ascent,
+ _ => Pt::ZERO,
+ })
+ .fold(Pt::ZERO, Pt::max);
+ let h_space = dc_h_space.map(Pt::from).unwrap_or(Pt::ZERO);
+ let margin_mode = matches!(style, model::DropCap::Margin);
+ // The drop cap paragraph's own indent determines the x position.
+ // This includes indent_left + indent_first_line from the cascade.
+ let dc_indent_left = merged_props
+ .indentation
+ .and_then(|i| i.start)
+ .map(Pt::from)
+ .unwrap_or(Pt::ZERO);
+ let dc_indent_first = merged_props
+ .indentation
+ .and_then(|i| i.first_line)
+ .map(|fl| match fl {
+ model::FirstLineIndent::FirstLine(v) => Pt::from(v),
+ model::FirstLineIndent::Hanging(v) => -Pt::from(v),
+ model::FirstLineIndent::None => Pt::ZERO,
+ })
+ .unwrap_or(Pt::ZERO);
+ // §17.3.1.33: frame height from drop cap paragraph's exact line spacing.
+ let frame_height = merged_props
+ .spacing
+ .and_then(|s| s.line)
+ .and_then(|ls| match ls {
+ model::LineSpacing::Exact(v) => Some(Pt::from(v)),
+ _ => None,
+ });
+ // §17.3.2.19: position offset from the drop cap run.
+ let position_offset = fragments
+ .first()
+ .and_then(|f| match f {
+ Fragment::Text {
+ baseline_offset, ..
+ } => Some(*baseline_offset),
+ _ => None,
+ })
+ .unwrap_or(Pt::ZERO);
+ *pending_dropcap = Some(DropCapInfo {
+ fragments,
+ lines: drop_cap_lines,
+ ascent,
+ h_space,
+ width,
+ height,
+ margin_mode,
+ indent: dc_indent_left + dc_indent_first,
+ frame_height,
+ position_offset,
+ });
+ return None;
+ }
+
+ let outline = super::convert::paragraph_outline(p, &merged_props, state);
+ let mut style = paragraph_style_from_props(
+ &merged_props,
+ Pt::from(ctx.resolved.default_tab_stop),
+ state.shape_auto_fit,
+ super::convert::paragraph_locale(p, ctx.resolved),
+ outline,
+ );
+ style.style_id = p.style_id.clone();
+
+ // Attach pending drop cap to this paragraph.
+ if let Some(dc) = pending_dropcap.take() {
+ style.drop_cap = Some(dc);
+ }
+
+ let page_break_before = merged_props.page_break_before.unwrap_or(false);
+
+ // §17.11.12: render a body for each footnote this paragraph referenced.
+ // `collect_fragments` recorded them — id *and* the display number it
+ // emitted as the superscript — as it walked, so the body and the mark
+ // cannot disagree. Draining here also covers references nested inside
+ // hyperlinks, fields, and text boxes, which the previous flat scan of
+ // `p.content` missed entirely.
+ let mut para_footnotes = Vec::new();
+ for note in fn_refs {
+ if let Some(content) = ctx.resolved.footnotes.get(&note.id) {
+ let display = format!("{}", note.display);
+ let notes = build_note_content(&display, content, ctx, state);
+ for (_, frags, style) in notes {
+ para_footnotes.push((frags, style));
+ }
+ }
+ }
+
+ // §20.4.2.3: extract floating (anchor) images and shapes from this
+ // paragraph. Table cells emit their commands through `stack_blocks`,
+ // which shifts them into page coordinates, so anchors inside a cell use
+ // the stack frame. Body paragraphs emit in page-absolute coordinates.
+ let frame = if table_style.is_some() {
+ AnchorFrame::Stack
+ } else {
+ AnchorFrame::Page
+ };
+ let floating_images = extract_floating_images(p, ctx, state, frame);
+ let floating_shapes = super::floating::extract_floating_shapes(
+ p,
+ ctx,
+ state,
+ frame,
+ super::floating::ShapeAnchorClass::All,
+ );
+
+ Some(LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before,
+ footnotes: para_footnotes,
+ floating_images,
+ floating_shapes,
+ })
+}
+
+/// Build note content (footnotes or endnotes) with a display number prefix.
+pub(super) fn build_note_content(
+ display_num: &str,
+ content: &[Block],
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> Vec<(
+ String,
+ Vec<Fragment>,
+ crate::render::layout::paragraph::ParagraphStyle,
+)> {
+ // §17.3.1.19: a footnote or endnote body is not the document's main story,
+ // so nothing in it is an outline position. Suspended for the whole call and
+ // restored, for the same reason `build_header_footer_content` does it there
+ // rather than at the paragraph — a `Block::Table` in a note reaches the
+ // ordinary body builders.
+ let outer = std::mem::replace(
+ &mut state.outline,
+ crate::render::layout::build::OutlineCollector::Excluded,
+ );
+ let results = build_note_blocks(display_num, content, ctx, state);
+ state.outline = outer;
+ results
+}
+
+fn build_note_blocks(
+ display_num: &str,
+ content: &[Block],
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> Vec<(
+ String,
+ Vec<Fragment>,
+ crate::render::layout::paragraph::ParagraphStyle,
+)> {
+ let mut results = Vec::new();
+ for (i, block) in content.iter().enumerate() {
+ if let model::Block::Paragraph(p) = block {
+ let (mut frags, merged_props) = build_fragments(p, ctx, state, None, None);
+ // §17.11.12: a footnote body may itself carry references. We don't
+ // render nested footnote bodies (matching the previous behaviour),
+ // but the references must be drained so they aren't attributed to
+ // the paragraph that hosts this note.
+ let _ = state.footnotes.take_pending();
+
+ // Prepend display number to the first paragraph.
+ if i == 0 && !frags.is_empty() {
+ let num_text = format!("{} ", display_num);
+ // §17.8.3.2 / §17.3.2.14: fall back to the document-level spec
+ // defaults rather than restating a font name here.
+ let font = frags[0].font_props().cloned().unwrap_or_else(|| FontProps {
+ family: std::rc::Rc::from(super::SPEC_FALLBACK_FONT),
+ size: super::SPEC_DEFAULT_FONT_SIZE,
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ });
+ let ref_size =
+ font.size * crate::render::layout::fragment::SUPERSCRIPT_FONT_SIZE_RATIO;
+ let ref_font = FontProps {
+ size: ref_size,
+ ..font
+ };
+ let (w, m) = ctx.measurer.measure(&num_text, &ref_font);
+ frags.insert(
+ 0,
+ Fragment::Text {
+ text: Rc::from(num_text.as_str()),
+ font: Rc::new(ref_font),
+ color: RgbColor::BLACK,
+ shading: None,
+ border: None,
+ width: w,
+ trimmed_width: w,
+ metrics: m,
+ hyperlink_url: None,
+ baseline_offset: -(font.size
+ * crate::render::layout::fragment::NOTE_REF_BASELINE_OFFSET_RATIO),
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ },
+ );
+ }
+ let style = paragraph_style_from_props(
+ &merged_props,
+ Pt::from(ctx.resolved.default_tab_stop),
+ state.shape_auto_fit,
+ super::convert::paragraph_locale(p, ctx.resolved),
+ // §17.3.1.19: always `None` — the collector is suspended for
+ // this whole call. Asking rather than passing `None` keeps the
+ // heading decision in one place for every path.
+ super::convert::paragraph_outline(p, &merged_props, state),
+ );
+ results.push((display_num.to_string(), frags, style));
+ }
+ }
+ results
+}
+
+/// Collect endnotes from the resolved document.
+pub(super) fn collect_endnotes(
+ ctx: &BuildContext,
+ state: &mut BuildState,
+ endnotes: &mut Vec<(
+ String,
+ Vec<Fragment>,
+ crate::render::layout::paragraph::ParagraphStyle,
+ )>,
+) {
+ // IDs 0 and 1 are reserved for separator and continuation separator.
+ let mut en_ids: Vec<_> = ctx
+ .resolved
+ .endnotes
+ .keys()
+ .filter(|id| id.value() > 1)
+ .collect();
+ en_ids.sort_by_key(|id| id.value());
+ for (i, note_id) in en_ids.iter().enumerate() {
+ let display = crate::render::layout::fragment::to_roman_lower((i + 1) as u32);
+ if let Some(content) = ctx.resolved.endnotes.get(note_id) {
+ endnotes.extend(build_note_content(&display, content, ctx, state));
+ }
+ }
+}
+
+/// Build fragments and resolved paragraph properties for a paragraph.
+///
+/// Handles the full cascade: table style → conditional → paragraph style →
+/// doc defaults → fragment collection → image/underline population.
+pub(super) fn build_fragments(
+ para: &Paragraph,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+ table_style: Option<&ResolvedStyle>,
+ cond: Option<&CellConditionalFormatting>,
+) -> (Vec<Fragment>, model::ParagraphProperties) {
+ // §17.7.2: resolve paragraph defaults (direct → paragraph style).
+ // Doc defaults are deferred so table style/conditional can be inserted
+ // between paragraph style and doc defaults in the cascade.
+ let (default_family, mut default_size, mut default_color, mut merged_props, mut run_defaults) =
+ resolve_paragraph_defaults(
+ para,
+ ctx.resolved,
+ table_style.is_some(),
+ state.shape_default_text_color,
+ state.shape_default_font_family.as_deref(),
+ );
+
+ // §17.7.2: table conditional formatting — lower priority than paragraph style.
+ if let Some(c) = cond {
+ if let Some(ref pp) = c.paragraph_properties {
+ merge_paragraph_properties(&mut merged_props, pp);
+ }
+ }
+ // §17.7.2: table style paragraph properties — lower priority than conditional.
+ if let Some(ts) = table_style {
+ merge_paragraph_properties(&mut merged_props, &ts.paragraph);
+ }
+ // §17.7.2: doc defaults — lowest priority, deferred from resolve_paragraph_defaults.
+ if table_style.is_some() {
+ merge_paragraph_properties(&mut merged_props, &ctx.resolved.doc_defaults_paragraph);
+ }
+
+ // §17.7.2: table style run properties override Normal.
+ if let Some(ts) = table_style {
+ if let Some(fs) = ts.run.font_size {
+ default_size = Pt::from(fs);
+ run_defaults.font_size = Some(fs);
+ }
+ }
+
+ // §17.7.6: conditional run property overrides — higher priority than
+ // table style and paragraph style. Overlay (not merge): conditional
+ // values replace existing ones.
+ if let Some(c) = cond {
+ if let Some(ref rp) = c.run_properties {
+ // Overlay: for each Some field in rp, replace in run_defaults.
+ let mut overlay = rp.clone();
+ merge_run_properties(&mut overlay, &run_defaults);
+ run_defaults = overlay;
+ if let Some(fs) = run_defaults.font_size {
+ default_size = Pt::from(fs);
+ }
+ if let Some(color) = run_defaults.color {
+ default_color = resolve_color(color, ColorContext::Text);
+ }
+ }
+ }
+
+ let measure =
+ |text: &str, font: &FontProps| -> (Pt, crate::render::layout::fragment::TextMetrics) {
+ ctx.measurer.measure(text, font)
+ };
+
+ let frag_ctx = FragmentCtx {
+ default_family: &default_family,
+ default_size,
+ default_color,
+ resolved_styles: Some(&ctx.resolved.styles),
+ paragraph_run_defaults: Some(&run_defaults),
+ theme: ctx.resolved.theme.as_ref(),
+ measurer: Some(ctx.measurer),
+ auto_fit: state.shape_auto_fit,
+ };
+ let mut fragments = collect_fragments(
+ &para.content,
+ &frag_ctx,
+ None,
+ &measure,
+ &mut state.footnotes,
+ &mut state.endnote_counter,
+ state.field_ctx,
+ );
+ populate_image_data(&mut fragments, ctx.media());
+ populate_underline_metrics(&mut fragments, ctx.measurer);
+
+ (fragments, merged_props)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+
+ use super::*;
+ use crate::model::dimension::Dimension;
+ use crate::render::fonts::FontRegistry;
+ use crate::render::layout::measurer::TextMeasurer;
+ use crate::render::resolve::ResolvedDocument;
+
+ fn empty_resolved() -> ResolvedDocument {
+ ResolvedDocument {
+ sections: Vec::new(),
+ styles: HashMap::new(),
+ numbering: HashMap::new(),
+ font_families: Vec::new(),
+ media: HashMap::new(),
+ embedded_fonts: Vec::new(),
+ pic_bullets: HashMap::new(),
+ theme: None,
+ doc_defaults_paragraph: model::ParagraphProperties::default(),
+ doc_defaults_run: model::RunProperties::default(),
+ default_paragraph_style_id: None,
+ footnotes: HashMap::new(),
+ endnotes: HashMap::new(),
+ even_and_odd_headers: false,
+ default_tab_stop: Dimension::new(720),
+ }
+ }
+
+ fn para(content: Vec<model::Inline>) -> Paragraph {
+ Paragraph {
+ style_id: None,
+ properties: model::ParagraphProperties::default(),
+ mark_run_properties: None,
+ content,
+ rsids: model::ParagraphRevisionIds::default(),
+ }
+ }
+
+ fn text_run(s: &str) -> model::Inline {
+ model::Inline::TextRun(Box::new(model::TextRun {
+ style_id: None,
+ properties: model::RunProperties::default(),
+ content: vec![model::RunElement::Text(s.to_string())],
+ rsids: model::RevisionIds::default(),
+ }))
+ }
+
+ /// Run a closure with a live `BuildContext` + `BuildState`. A real Skia
+ /// measurer is used, so assertions below are structural — never on
+ /// platform-dependent metric values.
+ fn with_ctx<R>(
+ resolved: &ResolvedDocument,
+ f: impl FnOnce(&BuildContext, &mut BuildState) -> R,
+ ) -> R {
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved,
+ };
+ let mut state = BuildState::default();
+ f(&ctx, &mut state)
+ }
+
+ fn resolved_style(paragraph: model::ParagraphProperties) -> ResolvedStyle {
+ ResolvedStyle {
+ paragraph,
+ run: model::RunProperties::default(),
+ table: None,
+ table_style_overrides: Vec::new(),
+ is_toc_entry: false,
+ }
+ }
+
+ #[test]
+ fn section_break_produces_no_layout_block() {
+ let resolved = empty_resolved();
+ with_ctx(&resolved, |ctx, state| {
+ let block = Block::SectionBreak(Box::default());
+ let mut pending = None;
+ assert!(
+ build_block(&block, Pt::new(400.0), ctx, state, &mut pending).is_none(),
+ "section breaks are consumed by resolve, not laid out"
+ );
+ });
+ }
+
+ /// §17.3.1.29: a paragraph with no runs still occupies one line. Without an
+ /// injected `LineBreak` the fragment list is empty and `layout_section`
+ /// drops the paragraph, collapsing it to zero height.
+ #[test]
+ fn empty_paragraph_gets_a_line_break_fragment() {
+ let resolved = empty_resolved();
+ with_ctx(&resolved, |ctx, state| {
+ let mut pending = None;
+ let block = build_paragraph_block(&para(vec![]), ctx, state, &mut pending, None, None)
+ .expect("empty paragraph still lays out");
+ let LayoutBlock::Paragraph { fragments, .. } = block else {
+ panic!("expected a paragraph block");
+ };
+ assert!(
+ matches!(fragments.as_slice(), [Fragment::LineBreak { line_height }] if line_height.raw() > 0.0),
+ "exactly one LineBreak with a real height"
+ );
+ });
+ }
+
+ #[test]
+ fn paragraph_with_content_gets_no_injected_line_break() {
+ let resolved = empty_resolved();
+ with_ctx(&resolved, |ctx, state| {
+ let mut pending = None;
+ let block = build_paragraph_block(
+ &para(vec![text_run("hi")]),
+ ctx,
+ state,
+ &mut pending,
+ None,
+ None,
+ )
+ .expect("lays out");
+ let LayoutBlock::Paragraph { fragments, .. } = block else {
+ panic!("expected a paragraph block");
+ };
+ assert!(
+ !fragments
+ .iter()
+ .any(|f| matches!(f, Fragment::LineBreak { .. })),
+ "no LineBreak injected when the paragraph has runs"
+ );
+ });
+ }
+
+ /// §17.3.1.11: a drop-cap paragraph emits no block of its own — it is held
+ /// aside and attached to the *following* paragraph.
+ #[test]
+ fn drop_cap_paragraph_is_deferred_onto_the_next_paragraph() {
+ let resolved = empty_resolved();
+ with_ctx(&resolved, |ctx, state| {
+ let mut cap = para(vec![text_run("D")]);
+ cap.properties.frame_properties = Some(model::FrameKind::DropCap {
+ style: model::DropCap::Drop,
+ lines: 3,
+ h_space: None,
+ });
+
+ let mut pending = None;
+ assert!(
+ build_paragraph_block(&cap, ctx, state, &mut pending, None, None).is_none(),
+ "the drop-cap paragraph itself produces no block"
+ );
+ let held = pending
+ .as_ref()
+ .expect("drop cap held for the next paragraph");
+ assert_eq!(held.lines, 3, "line span carried through");
+
+ // The next paragraph consumes it.
+ let next = build_paragraph_block(
+ &para(vec![text_run("body")]),
+ ctx,
+ state,
+ &mut pending,
+ None,
+ None,
+ )
+ .expect("lays out");
+ let LayoutBlock::Paragraph { style, .. } = next else {
+ panic!("expected a paragraph block");
+ };
+ assert!(
+ style.drop_cap.is_some(),
+ "attached to the following paragraph"
+ );
+ assert!(pending.is_none(), "and taken, so it attaches only once");
+ });
+ }
+
+ /// §17.7.2 precedence inside a table cell: conditional formatting outranks
+ /// the table style, which outranks document defaults. Asserted on the
+ /// merged paragraph properties returned by `build_fragments`.
+ #[test]
+ fn conditional_formatting_outranks_table_style() {
+ let mut resolved = empty_resolved();
+ resolved.doc_defaults_paragraph.alignment = Some(model::Alignment::Start);
+ let table_style = resolved_style(model::ParagraphProperties {
+ alignment: Some(model::Alignment::Center),
+ ..Default::default()
+ });
+
+ with_ctx(&resolved, |ctx, state| {
+ // Table style alone.
+ let (_, props) = build_fragments(
+ &para(vec![text_run("x")]),
+ ctx,
+ state,
+ Some(&table_style),
+ None,
+ );
+ assert_eq!(
+ props.alignment,
+ Some(model::Alignment::Center),
+ "table style beats doc defaults"
+ );
+
+ // Conditional formatting on top of it.
+ let cond = CellConditionalFormatting {
+ cell_properties: None,
+ run_properties: None,
+ paragraph_properties: Some(model::ParagraphProperties {
+ alignment: Some(model::Alignment::End),
+ ..Default::default()
+ }),
+ };
+ let (_, props) = build_fragments(
+ &para(vec![text_run("x")]),
+ ctx,
+ state,
+ Some(&table_style),
+ Some(&cond),
+ );
+ assert_eq!(
+ props.alignment,
+ Some(model::Alignment::End),
+ "conditional formatting beats the table style"
+ );
+ });
+ }
+
+ /// The paragraph's own direct formatting outranks every table-level layer.
+ #[test]
+ fn direct_paragraph_properties_outrank_conditional_formatting() {
+ let resolved = empty_resolved();
+ let table_style = resolved_style(model::ParagraphProperties {
+ alignment: Some(model::Alignment::Center),
+ ..Default::default()
+ });
+ let cond = CellConditionalFormatting {
+ cell_properties: None,
+ run_properties: None,
+ paragraph_properties: Some(model::ParagraphProperties {
+ alignment: Some(model::Alignment::End),
+ ..Default::default()
+ }),
+ };
+
+ with_ctx(&resolved, |ctx, state| {
+ let mut p = para(vec![text_run("x")]);
+ p.properties.alignment = Some(model::Alignment::Both);
+ let (_, props) = build_fragments(&p, ctx, state, Some(&table_style), Some(&cond));
+ assert_eq!(
+ props.alignment,
+ Some(model::Alignment::Both),
+ "direct pPr wins over every table layer"
+ );
+ });
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/build/convert.rs b/crates/liteparse-docx/src/render/layout/build/convert.rs
new file mode 100644
index 0000000..d179247
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/build/convert.rs
@@ -0,0 +1,1216 @@
+use std::collections::HashMap;
+
+use crate::model::{self, FirstLineIndent, LineSpacing};
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtSize;
+use crate::render::layout::build::BuildState;
+use crate::render::layout::fragment::Fragment;
+use crate::render::layout::measurer::TextMeasurer;
+use crate::render::layout::paragraph::TabStopDef;
+use crate::render::layout::paragraph::{
+ BorderLine, LineSpacingRule, ParagraphBorderStyle, ParagraphStyle,
+};
+use crate::render::layout::table::{
+ CellBorderOverride, TableBorderConfig, TableBorderLine, TableBorderStyle,
+};
+use crate::render::resolve::ResolvedDocument;
+use crate::render::resolve::color::{ColorContext, RgbColor, resolve_color};
+use crate::render::resolve::fonts::effective_font;
+use crate::render::resolve::images::MediaEntry;
+use crate::render::resolve::properties::merge_paragraph_properties;
+
+use super::{BuildContext, SPEC_DEFAULT_FONT_SIZE, SPEC_FALLBACK_FONT};
+
+/// Resolve a paragraph's effective defaults.
+/// Cascade: direct → style → doc defaults.
+///
+/// Returns (font_family, font_size, color, merged_paragraph_props, run_defaults).
+///
+/// When `defer_doc_defaults` is true, doc defaults are NOT merged into the
+/// paragraph properties — the caller is responsible for merging them after
+/// inserting table style / conditional formatting in the cascade.
+pub(super) fn resolve_paragraph_defaults(
+ para: &model::Paragraph,
+ resolved: &ResolvedDocument,
+ defer_doc_defaults: bool,
+ // §20.1.4.1.17: base color / font family for a shape text box (from
+ // `wps:style/fontRef`). They sit *below* the style/run cascade — an
+ // explicit run or style value still wins. `None` uses the normal defaults.
+ base_color: Option<RgbColor>,
+ base_family: Option<&str>,
+) -> (
+ String,
+ Pt,
+ RgbColor,
+ model::ParagraphProperties,
+ model::RunProperties,
+) {
+ let mut para_props = para.properties.clone();
+ let mut run_defaults = resolved.doc_defaults_run.clone();
+
+ // Derive default font from: fontRef base → doc defaults → theme minor → spec.
+ let mut default_family = match base_family.filter(|s| !s.is_empty()) {
+ Some(f) => f.to_string(),
+ None => resolved
+ .theme
+ .as_ref()
+ .map(|t| t.minor_font.latin.as_str())
+ .filter(|s| !s.is_empty())
+ .unwrap_or(SPEC_FALLBACK_FONT)
+ .to_string(),
+ };
+ let mut default_size = resolved
+ .doc_defaults_run
+ .font_size
+ .map(Pt::from)
+ .unwrap_or(SPEC_DEFAULT_FONT_SIZE);
+ let mut default_color = base_color.unwrap_or(RgbColor::BLACK);
+
+ // §17.7.4.17: if no style is specified, use the default paragraph style.
+ let effective_style_id = para
+ .style_id
+ .as_ref()
+ .or(resolved.default_paragraph_style_id.as_ref());
+
+ if let Some(style_id) = effective_style_id {
+ if let Some(resolved_style) = resolved.styles.get(style_id) {
+ merge_paragraph_properties(&mut para_props, &resolved_style.paragraph);
+ run_defaults = resolved_style.run.clone();
+ }
+ }
+
+ // Merge doc defaults as lowest-priority fallback (unless deferred for table cascade).
+ if !defer_doc_defaults {
+ merge_paragraph_properties(&mut para_props, &resolved.doc_defaults_paragraph);
+ }
+
+ // Style's run font overrides document-level default.
+ if let Some(f) = effective_font(&run_defaults.fonts) {
+ default_family = f.to_string();
+ }
+ if let Some(fs) = run_defaults.font_size {
+ default_size = Pt::from(fs);
+ }
+ if let Some(c) = run_defaults.color {
+ default_color = resolve_color(c, ColorContext::Text);
+ }
+
+ (
+ default_family,
+ default_size,
+ default_color,
+ para_props,
+ run_defaults,
+ )
+}
+
+/// §17.3.2.20 / §17.7.2: the language in effect for a paragraph's own layout
+/// decisions.
+///
+/// The cascade is the paragraph **mark**'s `w:rPr`, then the paragraph style's
+/// run defaults, then `docDefaults` — the same order §17.7.2 resolves any other
+/// run property in, minus the runs themselves.
+///
+/// Leaving the runs out is deliberate, and is the one judgement call in
+/// threading locale. The decisions this answers belong to the *paragraph*: a
+/// §17.18.85 `decimal` stop is declared in `w:pPr/w:tabs`, and its zone may span
+/// several runs that each declare a different `w:lang` — there is no single
+/// run to ask. The paragraph mark is the nearest thing the file offers to
+/// "the language of this paragraph", and it is already what the §17.9.22 list
+/// label reads its formatting from, so the two agree.
+///
+/// Word itself is reported to take a decimal tab's separator from the host's
+/// regional settings rather than from the document at all, which a converter
+/// cannot reproduce and should not want to: the same file would render
+/// differently on two machines. This reading is deterministic and keyed to the
+/// document instead — but it is an assumption, not a verified match, and has
+/// never been checked against a Word render.
+pub(super) fn paragraph_locale(
+ para: &model::Paragraph,
+ resolved: &ResolvedDocument,
+) -> crate::render::resolve::locale::Locale {
+ let style_run = para
+ .style_id
+ .as_ref()
+ .or(resolved.default_paragraph_style_id.as_ref())
+ .and_then(|id| resolved.styles.get(id))
+ .map(|s| &s.run);
+
+ crate::render::resolve::locale::Locale::from_cascade(
+ [
+ para.mark_run_properties.as_ref(),
+ style_run,
+ Some(&resolved.doc_defaults_run),
+ ]
+ .into_iter()
+ .flatten(),
+ )
+}
+
+/// §17.3.1.19: this paragraph's PDF outline entry, if it is a heading.
+///
+/// `props` is the **cascaded** paragraph properties, so a level inherited from
+/// a heading style counts exactly as a direct `w:outlineLvl` does — which is
+/// the point: §17.3.1.19 is a paragraph property, and "is a heading" is not a
+/// question about style names. `OutlineLevel::from_ooxml` has already rejected
+/// value 9 ("body text"), so `None` here means "not a heading" for either
+/// reason.
+///
+/// Returns `None` for a heading with no text: the title is the only thing a
+/// reader can navigate by, and an untitled outline row points somewhere
+/// unnameable. Consuming a node ID for it would also leave a gap in the
+/// sequence, so the counter is only advanced once a heading is certain.
+pub(super) fn paragraph_outline(
+ para: &model::Paragraph,
+ props: &model::ParagraphProperties,
+ state: &mut BuildState,
+) -> Option<crate::render::layout::draw_command::OutlineHeading> {
+ let level = props.outline_level?;
+ let title = outline_title(&para.content);
+ if title.is_empty() {
+ return None;
+ }
+ // Reserved last, so a body-text paragraph or an untitled heading never
+ // consumes an ID and leaves a hole in the sequence.
+ let node_id = state.next_outline_node_id()?;
+ Some(crate::render::layout::draw_command::OutlineHeading {
+ node_id,
+ level,
+ title: std::rc::Rc::from(title.as_str()),
+ })
+}
+
+/// The text of a heading paragraph, as the outline should title it.
+///
+/// Runs are joined, and hyperlinks and field *results* are walked into, because
+/// all three are ordinary text as far as a reader is concerned — a title cut at
+/// the first formatting change would be wrong far more often than not.
+///
+/// The §17.9.22 list label is deliberately absent: it is injected at layout,
+/// not part of the paragraph, and both Word and LibreOffice title a numbered
+/// heading with its text alone (measured against the reference PDF attached to
+/// issue #90).
+fn outline_title(inlines: &[model::Inline]) -> String {
+ fn walk(inlines: &[model::Inline], out: &mut String) {
+ for inline in inlines {
+ match inline {
+ model::Inline::TextRun(run) => {
+ for element in &run.content {
+ if let model::RunElement::Text(text) = element {
+ out.push_str(text);
+ }
+ }
+ }
+ model::Inline::Symbol(sym) => {
+ out.push(char::from_u32(sym.char_code as u32).unwrap_or('\u{FFFD}'));
+ }
+ model::Inline::Hyperlink(link) => walk(&link.content, out),
+ model::Inline::Field(field) => walk(&field.content, out),
+ _ => {}
+ }
+ }
+ }
+ let mut out = String::new();
+ walk(inlines, &mut out);
+ out.trim().to_string()
+}
+
+pub(super) fn doc_font_family(ctx: &BuildContext) -> String {
+ ctx.resolved
+ .theme
+ .as_ref()
+ .map(|t| t.minor_font.latin.as_str())
+ .filter(|s| !s.is_empty())
+ .unwrap_or(SPEC_FALLBACK_FONT)
+ .to_string()
+}
+
+pub(super) fn doc_font_size(ctx: &BuildContext) -> Pt {
+ ctx.resolved
+ .doc_defaults_run
+ .font_size
+ .map(Pt::from)
+ .unwrap_or(SPEC_DEFAULT_FONT_SIZE)
+}
+
+/// Convert a model paragraph properties into a layout ParagraphStyle.
+///
+/// `auto_fit` is the §20.1.2.1.18 `a:normAutofit` shrink of the enclosing shape
+/// text body. It is carried onto the style rather than applied here: its
+/// `@lnSpcReduction` half has to reach the line height *after* §17.3.1.33
+/// resolution — see [`ShapeAutoFit::scale_line_height`](crate::render::layout::ShapeAutoFit::scale_line_height).
+/// [`ShapeAutoFit::NONE`](crate::render::layout::ShapeAutoFit::NONE) outside a
+/// shape text box.
+pub(super) fn paragraph_style_from_props(
+ props: &model::ParagraphProperties,
+ default_tab_stop: Pt,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+ locale: crate::render::resolve::locale::Locale,
+ outline: Option<crate::render::layout::draw_command::OutlineHeading>,
+) -> ParagraphStyle {
+ let indent_left = props
+ .indentation
+ .and_then(|i| i.start)
+ .map(Pt::from)
+ .unwrap_or(Pt::ZERO);
+ let indent_right = props
+ .indentation
+ .and_then(|i| i.end)
+ .map(Pt::from)
+ .unwrap_or(Pt::ZERO);
+ let indent_first_line = props
+ .indentation
+ .and_then(|i| i.first_line)
+ .map(|fl| match fl {
+ FirstLineIndent::FirstLine(v) => Pt::from(v),
+ FirstLineIndent::Hanging(v) => -Pt::from(v),
+ FirstLineIndent::None => Pt::ZERO,
+ })
+ .unwrap_or(Pt::ZERO);
+
+ // §17.3.1.33: when autoSpacing is true, use 14pt instead of explicit value.
+ let space_before = if props.spacing.and_then(|s| s.before_auto_spacing) == Some(true) {
+ Pt::new(14.0)
+ } else {
+ props
+ .spacing
+ .and_then(|s| s.before)
+ .map(Pt::from)
+ .unwrap_or(Pt::ZERO)
+ };
+ let space_after = if props.spacing.and_then(|s| s.after_auto_spacing) == Some(true) {
+ Pt::new(14.0)
+ } else {
+ props
+ .spacing
+ .and_then(|s| s.after)
+ .map(Pt::from)
+ .unwrap_or(Pt::ZERO)
+ };
+
+ // §17.3.1.33: line spacing defaults to single (auto, 240 twips = 1.0x).
+ let line_spacing = props
+ .spacing
+ .and_then(|s| s.line)
+ .map(|ls| match ls {
+ LineSpacing::Auto(v) => LineSpacingRule::Auto(Pt::from(v).raw() / 12.0),
+ LineSpacing::Exact(v) => LineSpacingRule::Exact(Pt::from(v)),
+ LineSpacing::AtLeast(v) => LineSpacingRule::AtLeast(Pt::from(v)),
+ })
+ .unwrap_or(LineSpacingRule::Auto(1.0));
+
+ // §17.3.1.38: convert tab stops to layout format.
+ // Clear entries are directives consumed during style merging, not layout stops.
+ let tabs: Vec<TabStopDef> = props
+ .tabs
+ .iter()
+ .filter(|t| t.alignment != model::TabAlignment::Clear)
+ .map(|t| TabStopDef {
+ position: Pt::from(t.position),
+ alignment: t.alignment,
+ leader: t.leader,
+ })
+ .collect();
+
+ ParagraphStyle {
+ auto_fit,
+ alignment: props.alignment.unwrap_or(model::Alignment::Start),
+ space_before,
+ space_after,
+ indent_left,
+ indent_right,
+ indent_first_line,
+ line_spacing,
+ tabs,
+ default_tab_stop,
+ locale,
+ outline,
+ drop_cap: None,
+ borders: resolve_paragraph_borders(props),
+ shading: props
+ .shading
+ .as_ref()
+ .map(|s| resolve_color(s.fill, ColorContext::Background)),
+ keep_next: props.keep_next.unwrap_or(false),
+ keep_lines: props.keep_lines.unwrap_or(false),
+ // §17.3.1.44: Word enables widow/orphan control by default.
+ widow_control: props.widow_control.unwrap_or(true),
+ contextual_spacing: props.contextual_spacing.unwrap_or(false),
+ style_id: None, // set by caller when available
+ page_floats: Vec::new(),
+ page_y: crate::render::dimension::Pt::ZERO,
+ page_x: crate::render::dimension::Pt::ZERO,
+ page_content_width: crate::render::dimension::Pt::ZERO,
+ }
+}
+
+/// §17.3.1.24: resolve paragraph borders.
+///
+/// Each side that arrives as `Some(Border { style: BorderStyle::None, .. })`
+/// is the spec's explicit "no border" override (`<w:top w:val="nil"/>` or
+/// `<w:top w:val="none"/>`, §17.18.2 ST_Border). The model preserves the
+/// `Some` so the §17.7.2 cascade can override an inherited side, but at
+/// the render boundary we drop the sentinel — otherwise an empty `<w:pBdr>`
+/// with all sides "nil" (Word's default for any paragraph cascade) would
+/// frame every paragraph in the document with a hairline rectangle.
+pub(super) fn resolve_paragraph_borders(
+ props: &model::ParagraphProperties,
+) -> Option<ParagraphBorderStyle> {
+ let pbdr = props.borders.as_ref()?;
+
+ let convert = |b: &model::Border| -> Option<BorderLine> {
+ if b.style.draws_nothing() {
+ return None;
+ }
+ Some(BorderLine {
+ width: Pt::from(b.width),
+ color: resolve_color(b.color, ColorContext::Text),
+ space: Pt::from(b.space),
+ })
+ };
+
+ let style = ParagraphBorderStyle {
+ top: pbdr.top.as_ref().and_then(convert),
+ bottom: pbdr.bottom.as_ref().and_then(convert),
+ left: pbdr.left.as_ref().and_then(convert),
+ right: pbdr.right.as_ref().and_then(convert),
+ };
+
+ if style.top.is_some()
+ || style.bottom.is_some()
+ || style.left.is_some()
+ || style.right.is_some()
+ {
+ Some(style)
+ } else {
+ None
+ }
+}
+
+/// Convert a model `Border` to a layout `TableBorderLine`.
+///
+/// §17.4.38 defines 26 border styles; the painter draws two. `Double` maps
+/// through, and the remaining 24 — `Dotted`, `Dashed`, `Triple`, `Wave`,
+/// `DashDotStroked`, the `ThinThick*` family and the rest — are approximated
+/// by a solid line of the declared width and colour. The approximation is
+/// bounded (position, thickness and colour are all preserved; only the stroke
+/// pattern is lost) but it is not free, so each distinct style is reported once
+/// per render via `state.warned_border_styles`.
+fn convert_model_border(b: &model::Border, state: &mut BuildState) -> TableBorderLine {
+ let style = match b.style {
+ model::BorderStyle::Double => TableBorderStyle::Double,
+ model::BorderStyle::Single => TableBorderStyle::Single,
+ other => {
+ if state.warned_border_styles.insert(other) {
+ log::warn!(
+ "[build] §17.4.38 border style {other:?} is not drawn; \
+ approximating with a single solid line"
+ );
+ }
+ TableBorderStyle::Single
+ }
+ };
+ TableBorderLine {
+ width: Pt::from(b.width),
+ color: resolve_color(b.color, ColorContext::Text),
+ style,
+ }
+}
+
+/// Convert a model cell border to a `CellBorderOverride`.
+///
+/// Three inputs, three outcomes ([MS-OI29500] §17.4.66):
+///
+/// | Markup | Result | Meaning |
+/// |---|---|---|
+/// | edge omitted | `None` | inherit: style → `tblPrEx` → table borders |
+/// | `val="none"` | `None` | **same as omitted** — the spec's cascade starts with *"if the cell border is omitted or none"* |
+/// | `val="nil"` | `Some(Suppress)` | draw nothing, and win the shared-edge conflict |
+/// | anything else | `Some(Border(..))` | that border, subject to conflict resolution |
+///
+/// `none` collapsing to `None` is the whole point: it makes an explicit
+/// `<w:top w:val="none"/>` behave as if the author had written nothing, which
+/// is what the spec says and the opposite of suppressing the edge.
+pub(super) fn convert_cell_border_override(
+ b: &Option<model::Border>,
+ state: &mut BuildState,
+) -> Option<CellBorderOverride> {
+ b.as_ref().and_then(|b| match b.style {
+ model::BorderStyle::Nil => Some(CellBorderOverride::Suppress),
+ model::BorderStyle::None => None,
+ _ => Some(CellBorderOverride::Border(convert_model_border(b, state))),
+ })
+}
+
+/// §17.4.38: merge direct table borders over style borders.
+/// Each edge in `direct` overrides the corresponding edge in `style`;
+/// unspecified edges (`None`) inherit from the style.
+pub(super) fn merge_table_borders(
+ direct: &model::TableBorders,
+ style: &model::TableBorders,
+) -> model::TableBorders {
+ model::TableBorders {
+ top: direct.top.or(style.top),
+ bottom: direct.bottom.or(style.bottom),
+ left: direct.left.or(style.left),
+ right: direct.right.or(style.right),
+ inside_h: direct.inside_h.or(style.inside_h),
+ inside_v: direct.inside_v.or(style.inside_v),
+ }
+}
+
+/// Convert model `TableBorders` to a layout `TableBorderConfig`.
+/// §17.4.38: borders with `val="none"` or `val="nil"` are suppressed.
+pub(super) fn convert_table_border_config(
+ b: &model::TableBorders,
+ state: &mut BuildState,
+) -> TableBorderConfig {
+ let mut convert = |border: &Option<model::Border>| -> Option<TableBorderLine> {
+ border.as_ref().and_then(|b| {
+ if b.style.draws_nothing() {
+ None
+ } else {
+ Some(convert_model_border(b, state))
+ }
+ })
+ };
+ TableBorderConfig {
+ top: convert(&b.top),
+ bottom: convert(&b.bottom),
+ left: convert(&b.left),
+ right: convert(&b.right),
+ inside_h: convert(&b.inside_h),
+ inside_v: convert(&b.inside_v),
+ }
+}
+
+/// Populate image data on Fragment::Image fragments from the media map.
+pub(super) fn populate_image_data(
+ fragments: &mut [Fragment],
+ media: &HashMap<model::RelId, MediaEntry>,
+) {
+ for frag in fragments.iter_mut() {
+ if let Fragment::Image {
+ rel_id, image_data, ..
+ } = frag
+ {
+ if image_data.is_none() {
+ if let Some(entry) = media.get(&model::RelId::new(rel_id.as_str())) {
+ *image_data = Some(entry.clone());
+ }
+ }
+ }
+ }
+}
+
+/// Remap PUA codepoints (0xF0xx) from legacy Symbol/Wingdings encoding
+/// to standard Unicode, and return a portable font to render them with.
+///
+/// OOXML stores Symbol/Wingdings characters as PUA codepoints. These are
+/// not portable across platforms — different OS font versions have different
+/// cmap coverage. The standard approach (used by LibreOffice, Google Docs)
+/// is to remap to Unicode equivalents from the official mapping tables:
+/// - Symbol: unicode.org/Public/MAPPINGS/VENDORS/ADOBE/symbol.txt
+/// - Wingdings: standard Microsoft Wingdings-to-Unicode mapping
+///
+/// Returns (remapped_text, font_family).
+pub(super) fn remap_legacy_font_chars(
+ text: &str,
+ font_family: &str,
+ fallback_family: &str,
+) -> (String, String) {
+ let is_symbol = font_family.eq_ignore_ascii_case("Symbol");
+ let is_wingdings = font_family.eq_ignore_ascii_case("Wingdings");
+
+ if !is_symbol && !is_wingdings {
+ let family = if font_family.is_empty() {
+ fallback_family
+ } else {
+ font_family
+ };
+ return (text.to_string(), family.to_string());
+ }
+
+ let mut remapped = String::with_capacity(text.len());
+ // True once a PUA codepoint is found that we have no Unicode mapping for.
+ // Such a character survives as a raw PUA scalar, which *only* the original
+ // legacy font can render — see the family choice below.
+ let mut unmapped_pua = false;
+
+ for ch in text.chars() {
+ let code = ch as u32;
+ if !LEGACY_PUA_RANGE.contains(&code) {
+ // Not legacy-encoded; pass through untouched.
+ remapped.push(ch);
+ continue;
+ }
+ let mapped = if is_symbol {
+ symbol_pua_to_unicode(code)
+ } else {
+ wingdings_pua_to_unicode(code)
+ };
+ match mapped {
+ Some(unicode) => remapped.push(unicode),
+ None => {
+ unmapped_pua = true;
+ remapped.push(ch);
+ }
+ }
+ }
+
+ // Font choice follows what actually happened to the text:
+ //
+ // * Everything mapped → the text is now standard Unicode, which the legacy
+ // font cannot render (Symbol/Wingdings carry no Unicode cmap). Switch to
+ // the document's fallback font; standard bullets (U+2022, U+25AA) and
+ // Greek are present in most text fonts.
+ // * Something didn't map → that character is still a PUA scalar, and the
+ // *only* font that can render it is the legacy one it came from. Keeping
+ // the original family renders correctly wherever the real Symbol /
+ // Wingdings face is installed; handing a PUA scalar to a text font is a
+ // guaranteed `.notdef` box.
+ let family = if unmapped_pua {
+ font_family
+ } else {
+ fallback_family
+ };
+ (remapped, family.to_string())
+}
+
+/// The PUA block Word uses for legacy symbol-font encodings: character code
+/// `0xNN` is stored as `0xF0NN` (§17.3.3.30 `w:sym`).
+const LEGACY_PUA_RANGE: std::ops::RangeInclusive<u32> = 0xF020..=0xF0FF;
+
+/// Symbol-font PUA codepoint → Unicode, per the Adobe mapping table
+/// (unicode.org/Public/MAPPINGS/VENDORS/ADOBE/symbol.txt).
+///
+/// `None` means "no mapping known" — deliberately distinct from "maps to
+/// itself", because the caller uses it to decide whether the remapped text can
+/// safely move to a Unicode text font.
+fn symbol_pua_to_unicode(code: u32) -> Option<char> {
+ // Greek is the Symbol font's primary content: the letter positions carry
+ // the alphabet, with four glyph-variant slots (theta1, sigma1, phi1,
+ // omega1) that do not follow the plain A–Z / a–z order.
+ const GREEK_UPPER: [char; 26] = [
+ '\u{0391}', // A Alpha
+ '\u{0392}', // B Beta
+ '\u{03A7}', // C Chi
+ '\u{0394}', // D Delta
+ '\u{0395}', // E Epsilon
+ '\u{03A6}', // F Phi
+ '\u{0393}', // G Gamma
+ '\u{0397}', // H Eta
+ '\u{0399}', // I Iota
+ '\u{03D1}', // J theta1 (GREEK THETA SYMBOL)
+ '\u{039A}', // K Kappa
+ '\u{039B}', // L Lambda
+ '\u{039C}', // M Mu
+ '\u{039D}', // N Nu
+ '\u{039F}', // O Omicron
+ '\u{03A0}', // P Pi
+ '\u{0398}', // Q Theta
+ '\u{03A1}', // R Rho
+ '\u{03A3}', // S Sigma
+ '\u{03A4}', // T Tau
+ '\u{03A5}', // U Upsilon
+ '\u{03C2}', // V sigma1 (FINAL SIGMA)
+ '\u{03A9}', // W Omega
+ '\u{039E}', // X Xi
+ '\u{03A8}', // Y Psi
+ '\u{0396}', // Z Zeta
+ ];
+ const GREEK_LOWER: [char; 26] = [
+ '\u{03B1}', // a alpha
+ '\u{03B2}', // b beta
+ '\u{03C7}', // c chi
+ '\u{03B4}', // d delta
+ '\u{03B5}', // e epsilon
+ '\u{03C6}', // f phi
+ '\u{03B3}', // g gamma
+ '\u{03B7}', // h eta
+ '\u{03B9}', // i iota
+ '\u{03D5}', // j phi1 (GREEK PHI SYMBOL)
+ '\u{03BA}', // k kappa
+ '\u{03BB}', // l lambda
+ '\u{03BC}', // m mu
+ '\u{03BD}', // n nu
+ '\u{03BF}', // o omicron
+ '\u{03C0}', // p pi
+ '\u{03B8}', // q theta
+ '\u{03C1}', // r rho
+ '\u{03C3}', // s sigma
+ '\u{03C4}', // t tau
+ '\u{03C5}', // u upsilon
+ '\u{03D6}', // v omega1 (GREEK PI SYMBOL)
+ '\u{03C9}', // w omega
+ '\u{03BE}', // x xi
+ '\u{03C8}', // y psi
+ '\u{03B6}', // z zeta
+ ];
+
+ Some(match code {
+ 0xF020 => '\u{0020}', // SPACE
+ 0xF021 => '\u{0021}', // EXCLAMATION MARK
+ 0xF025 => '\u{0025}', // PERCENT SIGN
+ 0xF028 => '\u{0028}', // LEFT PARENTHESIS
+ 0xF029 => '\u{0029}', // RIGHT PARENTHESIS
+ 0xF02B => '\u{002B}', // PLUS SIGN
+ 0xF02E => '\u{002E}', // FULL STOP
+ 0xF030..=0xF039 => char::from_u32(code - 0xF000)?, // DIGITS
+ 0xF03C => '\u{003C}', // LESS-THAN SIGN
+ 0xF03D => '\u{003D}', // EQUALS SIGN
+ 0xF03E => '\u{003E}', // GREATER-THAN SIGN
+ 0xF041..=0xF05A => GREEK_UPPER[(code - 0xF041) as usize],
+ 0xF05B => '\u{005B}', // LEFT SQUARE BRACKET
+ 0xF05D => '\u{005D}', // RIGHT SQUARE BRACKET
+ 0xF061..=0xF07A => GREEK_LOWER[(code - 0xF061) as usize],
+ 0xF07B => '\u{007B}', // LEFT CURLY BRACKET
+ 0xF07C => '\u{007C}', // VERTICAL LINE
+ 0xF07D => '\u{007D}', // RIGHT CURLY BRACKET
+ 0xF07E => '\u{223C}', // TILDE OPERATOR
+ 0xF0A0 => '\u{20AC}', // EURO SIGN
+ 0xF0A5 => '\u{221E}', // INFINITY
+ 0xF0A7 => '\u{2663}', // BLACK CLUB SUIT
+ 0xF0A8 => '\u{2666}', // BLACK DIAMOND SUIT
+ 0xF0A9 => '\u{2665}', // BLACK HEART SUIT
+ 0xF0AA => '\u{2660}', // BLACK SPADE SUIT
+ 0xF0AB => '\u{2194}', // LEFT RIGHT ARROW
+ 0xF0AC => '\u{2190}', // LEFTWARDS ARROW
+ 0xF0AD => '\u{2191}', // UPWARDS ARROW
+ 0xF0AE => '\u{2192}', // RIGHTWARDS ARROW
+ 0xF0AF => '\u{2193}', // DOWNWARDS ARROW
+ 0xF0B0 => '\u{00B0}', // DEGREE SIGN
+ 0xF0B1 => '\u{00B1}', // PLUS-MINUS SIGN
+ 0xF0B2 => '\u{2033}', // DOUBLE PRIME
+ 0xF0B3 => '\u{2265}', // GREATER-THAN OR EQUAL TO
+ 0xF0B4 => '\u{00D7}', // MULTIPLICATION SIGN
+ 0xF0B5 => '\u{221D}', // PROPORTIONAL TO
+ 0xF0B7 => '\u{2022}', // BULLET
+ 0xF0B8 => '\u{00F7}', // DIVISION SIGN
+ 0xF0B9 => '\u{2260}', // NOT EQUAL TO
+ 0xF0BA => '\u{2261}', // IDENTICAL TO
+ 0xF0BB => '\u{2248}', // ALMOST EQUAL TO
+ 0xF0BC => '\u{2026}', // HORIZONTAL ELLIPSIS
+ 0xF0C0 => '\u{2135}', // ALEF SYMBOL
+ 0xF0C1 => '\u{2111}', // BLACK-LETTER CAPITAL I
+ 0xF0C2 => '\u{211C}', // BLACK-LETTER CAPITAL R
+ 0xF0C3 => '\u{2118}', // SCRIPT CAPITAL P
+ 0xF0C5 => '\u{2297}', // CIRCLED TIMES
+ 0xF0C6 => '\u{2295}', // CIRCLED PLUS
+ 0xF0C7 => '\u{2205}', // EMPTY SET
+ 0xF0C8 => '\u{2229}', // INTERSECTION
+ 0xF0C9 => '\u{222A}', // UNION
+ 0xF0CB => '\u{2283}', // SUPERSET OF
+ 0xF0CC => '\u{2287}', // SUPERSET OF OR EQUAL TO
+ 0xF0CD => '\u{2284}', // NOT A SUBSET OF
+ 0xF0CE => '\u{2282}', // SUBSET OF
+ 0xF0CF => '\u{2286}', // SUBSET OF OR EQUAL TO
+ 0xF0D0 => '\u{2208}', // ELEMENT OF
+ 0xF0D1 => '\u{2209}', // NOT AN ELEMENT OF
+ 0xF0D5 => '\u{220F}', // N-ARY PRODUCT
+ 0xF0D6 => '\u{221A}', // SQUARE ROOT
+ 0xF0D7 => '\u{22C5}', // DOT OPERATOR
+ 0xF0D8 => '\u{00AC}', // NOT SIGN
+ 0xF0D9 => '\u{2227}', // LOGICAL AND
+ 0xF0DA => '\u{2228}', // LOGICAL OR
+ 0xF0E0 => '\u{21D0}', // LEFTWARDS DOUBLE ARROW
+ 0xF0E1 => '\u{21D1}', // UPWARDS DOUBLE ARROW
+ 0xF0E2 => '\u{21D2}', // RIGHTWARDS DOUBLE ARROW
+ 0xF0E3 => '\u{21D3}', // DOWNWARDS DOUBLE ARROW
+ 0xF0E4 => '\u{21D4}', // LEFT RIGHT DOUBLE ARROW
+ 0xF0E5 => '\u{2329}', // LEFT-POINTING ANGLE BRACKET
+ 0xF0F1 => '\u{232A}', // RIGHT-POINTING ANGLE BRACKET
+ 0xF0F2 => '\u{222B}', // INTEGRAL
+ _ => return None,
+ })
+}
+
+/// Wingdings PUA codepoint → Unicode, per the Microsoft Wingdings-to-Unicode
+/// table. `None` means "no mapping known" — see [`symbol_pua_to_unicode`].
+///
+/// Wingdings is a dingbat font with no canonical full mapping; this covers the
+/// glyphs that appear as list bullets, which is what routes through here.
+fn wingdings_pua_to_unicode(code: u32) -> Option<char> {
+ Some(match code {
+ 0xF021 => '\u{270E}', // LOWER RIGHT PENCIL
+ 0xF022 => '\u{2702}', // BLACK SCISSORS
+ 0xF023 => '\u{2701}', // UPPER BLADE SCISSORS
+ 0xF028 => '\u{1F4CB}', // CLIPBOARD
+ 0xF029 => '\u{1F4CB}', // CLIPBOARD
+ 0xF041 => '\u{FE4E}', // WAVY LOW LINE (approximate)
+ 0xF046 => '\u{1F44D}', // THUMBS UP SIGN
+ 0xF04A => '\u{263A}', // WHITE SMILING FACE
+ 0xF04C => '\u{2639}', // WHITE FROWNING FACE
+ 0xF06C => '\u{25CF}', // BLACK CIRCLE
+ 0xF06D => '\u{274D}', // SHADOWED WHITE CIRCLE
+ 0xF06E => '\u{25A0}', // BLACK SQUARE
+ 0xF06F => '\u{25A1}', // WHITE SQUARE
+ 0xF070 => '\u{25A1}', // WHITE SQUARE (alt)
+ 0xF071 => '\u{2751}', // LOWER RIGHT SHADOWED WHITE SQUARE
+ 0xF072 => '\u{2752}', // UPPER RIGHT SHADOWED WHITE SQUARE
+ 0xF073 => '\u{25C6}', // BLACK DIAMOND
+ 0xF074 => '\u{2756}', // BLACK DIAMOND MINUS WHITE X
+ 0xF076 => '\u{2756}', // BLACK DIAMOND MINUS WHITE X
+ 0xF09F => '\u{2708}', // AIRPLANE
+ 0xF0A1 => '\u{270C}', // VICTORY HAND
+ 0xF0A4 => '\u{261C}', // WHITE LEFT POINTING INDEX
+ 0xF0A5 => '\u{261E}', // WHITE RIGHT POINTING INDEX
+ 0xF0A7 => '\u{25AA}', // BLACK SMALL SQUARE
+ 0xF0A8 => '\u{25FB}', // WHITE MEDIUM SQUARE
+ 0xF0D5 => '\u{232B}', // ERASE TO THE LEFT
+ 0xF0D8 => '\u{27A2}', // THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD
+ 0xF0E8 => '\u{2B22}', // BLACK HEXAGON (approximate)
+ 0xF0F0 => '\u{2B1A}', // DOTTED SQUARE (approximate)
+ 0xF0FB => '\u{2718}', // HEAVY BALLOT X
+ 0xF0FC => '\u{2714}', // HEAVY CHECK MARK
+ 0xF0FE => '\u{2612}', // BALLOT BOX WITH X (approximate)
+ _ => return None,
+ })
+}
+
+/// Populate underline position/thickness from Skia font metrics.
+pub(super) fn populate_underline_metrics(fragments: &mut [Fragment], measurer: &TextMeasurer) {
+ for frag in fragments.iter_mut() {
+ if let Fragment::Text { font, .. } = frag {
+ if font.underline {
+ // Underlined runs only; `make_mut` clones the shared font so
+ // the metrics can be written back.
+ let fp = std::rc::Rc::make_mut(font);
+ let (pos, thickness) = measurer.underline_metrics(fp);
+ fp.underline_position = pos;
+ fp.underline_thickness = thickness;
+ }
+ }
+ }
+}
+
+/// Extract the display size for a picture bullet from its VML shape style.
+/// Falls back to 9pt × 9pt (common Word default for picture bullets).
+pub(super) fn pic_bullet_size(bullet: &model::NumPicBullet) -> PtSize {
+ let default = PtSize::new(Pt::new(9.0), Pt::new(9.0));
+ let shape = match bullet.pict.as_ref().and_then(|p| p.shapes().next()) {
+ Some(s) => s,
+ None => return default,
+ };
+
+ let w = shape
+ .common
+ .style
+ .width
+ .and_then(vml_style_length_to_pt)
+ .unwrap_or(default.width);
+ let h = shape
+ .common
+ .style
+ .height
+ .and_then(vml_style_length_to_pt)
+ .unwrap_or(default.height);
+ PtSize::new(w, h)
+}
+
+/// §14.1.2: convert a VML **style** measurement (`width`, `height`,
+/// `margin-left`, …) to points.
+///
+/// The absolute units come from [`model::VmlLength::to_absolute_points`], the
+/// one unit table shared with the parse layer. What this function adds is the
+/// policy for the units that table leaves unresolved, which is specific to
+/// style measurements:
+///
+/// * a **bare number** is EMU — the interpretation the model documents for
+/// this context (on a primitive's `from`/`to` the same bare number would
+/// instead be local coordinate units, which is why the rule can't live on
+/// the model type);
+/// * **`%`** and **`em`** are relative to a containing box or font size that
+/// isn't available here, so they yield `None` rather than a fabricated
+/// number. Returning the raw value — the previous behaviour — turned
+/// `width:50%` into 50pt.
+pub(super) fn vml_style_length_to_pt(len: model::VmlLength) -> Option<Pt> {
+ use crate::model::VmlLengthUnit;
+ if let Some(pt) = len.to_absolute_points() {
+ return Some(Pt::new(pt));
+ }
+ match len.unit {
+ VmlLengthUnit::None => Some(Pt::new(len.value as f32 / 914400.0 * 72.0)),
+ // Unresolvable without a containing box / font size.
+ VmlLengthUnit::Em | VmlLengthUnit::Percent => None,
+ // `to_absolute_points` already handled every absolute unit.
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::Dimension;
+ use crate::model::{Border, BorderStyle, Color, ParagraphBorders, ParagraphProperties};
+ use crate::render::resolve::color::rgb_from_u32;
+
+ /// An all-empty ResolvedDocument for exercising `resolve_paragraph_defaults`.
+ fn empty_resolved() -> ResolvedDocument {
+ use std::collections::HashMap;
+ ResolvedDocument {
+ sections: Vec::new(),
+ styles: HashMap::new(),
+ numbering: HashMap::new(),
+ font_families: Vec::new(),
+ media: HashMap::new(),
+ embedded_fonts: Vec::new(),
+ pic_bullets: HashMap::new(),
+ theme: None,
+ doc_defaults_paragraph: ParagraphProperties::default(),
+ doc_defaults_run: model::RunProperties::default(),
+ default_paragraph_style_id: None,
+ footnotes: HashMap::new(),
+ endnotes: HashMap::new(),
+ even_and_odd_headers: false,
+ default_tab_stop: Dimension::new(720),
+ }
+ }
+
+ fn bare_para() -> model::Paragraph {
+ model::Paragraph {
+ style_id: None,
+ properties: ParagraphProperties::default(),
+ mark_run_properties: None,
+ content: Vec::new(),
+ rsids: model::ParagraphRevisionIds::default(),
+ }
+ }
+
+ #[test]
+ fn shape_font_ref_base_color_and_family_apply_as_defaults() {
+ // §20.1.4.1.17: a shape's fontRef supplies the base text color / family
+ // used when the run/style specify none.
+ let resolved = empty_resolved();
+ let para = bare_para();
+
+ let (_, _, color, _, _) =
+ resolve_paragraph_defaults(&para, &resolved, false, Some(rgb_from_u32(0xFF0000)), None);
+ assert_eq!(color, rgb_from_u32(0xFF0000), "fontRef base color applies");
+
+ // Without a base, the default stays black (unchanged behavior).
+ let (_, _, black, _, _) = resolve_paragraph_defaults(&para, &resolved, false, None, None);
+ assert_eq!(black, rgb_from_u32(0x000000));
+
+ // Base family applies when set.
+ let (family, _, _, _, _) =
+ resolve_paragraph_defaults(&para, &resolved, false, None, Some("Foo Sans"));
+ assert_eq!(family, "Foo Sans");
+ }
+
+ fn border_with_style(style: BorderStyle) -> Border {
+ Border {
+ style,
+ width: Dimension::new(0),
+ space: Dimension::new(0),
+ color: Color::Auto,
+ }
+ }
+
+ /// §17.18.2: every side carrying `BorderStyle::None` (the parser's
+ /// landing for `<w:top w:val="nil"/>` and `<w:top w:val="none"/>`)
+ /// is dropped, even though the side's `Option<Border>` is `Some(_)`.
+ #[test]
+ fn paragraph_borders_explicit_none_yields_no_render_borders() {
+ let props = ParagraphProperties {
+ borders: Some(ParagraphBorders {
+ top: Some(border_with_style(BorderStyle::None)),
+ bottom: Some(border_with_style(BorderStyle::None)),
+ left: Some(border_with_style(BorderStyle::None)),
+ right: Some(border_with_style(BorderStyle::None)),
+ between: Some(border_with_style(BorderStyle::None)),
+ }),
+ ..Default::default()
+ };
+ assert!(
+ resolve_paragraph_borders(&props).is_none(),
+ "all-sides-nil pPr must produce no ParagraphBorderStyle"
+ );
+ }
+
+ /// One real side stays — the others (None) are still filtered.
+ #[test]
+ fn paragraph_borders_mixed_keeps_only_actual_sides() {
+ let props = ParagraphProperties {
+ borders: Some(ParagraphBorders {
+ top: Some(border_with_style(BorderStyle::Single)),
+ bottom: Some(border_with_style(BorderStyle::None)),
+ left: Some(border_with_style(BorderStyle::None)),
+ right: Some(border_with_style(BorderStyle::None)),
+ between: None,
+ }),
+ ..Default::default()
+ };
+ let resolved = resolve_paragraph_borders(&props).expect("top side must survive");
+ assert!(resolved.top.is_some());
+ assert!(resolved.bottom.is_none());
+ assert!(resolved.left.is_none());
+ assert!(resolved.right.is_none());
+ }
+
+ /// All-Single → carries through to render-side struct.
+ #[test]
+ fn paragraph_borders_all_single_round_trips() {
+ let props = ParagraphProperties {
+ borders: Some(ParagraphBorders {
+ top: Some(border_with_style(BorderStyle::Single)),
+ bottom: Some(border_with_style(BorderStyle::Single)),
+ left: Some(border_with_style(BorderStyle::Single)),
+ right: Some(border_with_style(BorderStyle::Single)),
+ between: None,
+ }),
+ ..Default::default()
+ };
+ let resolved = resolve_paragraph_borders(&props).expect("must produce Some");
+ assert!(resolved.top.is_some());
+ assert!(resolved.bottom.is_some());
+ assert!(resolved.left.is_some());
+ assert!(resolved.right.is_some());
+ }
+
+ /// No `<w:pBdr>` at all → no render-side borders.
+ #[test]
+ fn paragraph_borders_absent_yields_none() {
+ let props = ParagraphProperties::default();
+ assert!(resolve_paragraph_borders(&props).is_none());
+ }
+
+ // ── §17.3.3.30 legacy symbol-font PUA remapping ──────────────────────
+
+ /// The Symbol font's letter positions carry the Greek alphabet — its
+ /// primary content, and previously absent from the table entirely, so
+ /// every Greek character survived as a raw PUA scalar.
+ #[test]
+ fn symbol_pua_maps_the_greek_alphabet() {
+ // Plain alphabetical positions, spot-checked at both ends.
+ for (code, expected) in [
+ (0xF041, '\u{0391}'), // A → Alpha
+ (0xF044, '\u{0394}'), // D → Delta
+ (0xF05A, '\u{0396}'), // Z → Zeta
+ (0xF061, '\u{03B1}'), // a → alpha
+ (0xF06D, '\u{03BC}'), // m → mu
+ (0xF07A, '\u{03B6}'), // z → zeta
+ ] {
+ assert_eq!(symbol_pua_to_unicode(code), Some(expected), "U+{code:04X}");
+ }
+ }
+
+ /// Four Symbol slots hold glyph *variants* rather than the letter their
+ /// position would suggest — the easiest thing to get wrong when filling
+ /// in the alphabet mechanically.
+ #[test]
+ fn symbol_pua_greek_variant_slots_are_not_alphabetical() {
+ for (code, expected, what) in [
+ (0xF04A, '\u{03D1}', "J is theta1, not Iota-then-Kappa order"),
+ (0xF056, '\u{03C2}', "V is final sigma, not Upsilon+1"),
+ (0xF06A, '\u{03D5}', "j is phi1 (phi symbol)"),
+ (0xF076, '\u{03D6}', "v is omega1 (pi symbol), not omega"),
+ ] {
+ assert_eq!(symbol_pua_to_unicode(code), Some(expected), "{what}");
+ }
+ // The plain letters those variants are easily confused with.
+ assert_eq!(
+ symbol_pua_to_unicode(0xF051),
+ Some('\u{0398}'),
+ "Q is Theta"
+ );
+ assert_eq!(symbol_pua_to_unicode(0xF066), Some('\u{03C6}'), "f is phi");
+ assert_eq!(
+ symbol_pua_to_unicode(0xF077),
+ Some('\u{03C9}'),
+ "w is omega"
+ );
+ }
+
+ /// Adding the Greek ranges must not have displaced the punctuation and
+ /// math symbols that sit between them.
+ #[test]
+ fn symbol_pua_keeps_non_greek_mappings() {
+ for (code, expected) in [
+ (0xF05B, '\u{005B}'), // [ — just past uppercase Greek
+ (0xF05D, '\u{005D}'), // ]
+ (0xF07B, '\u{007B}'), // { — just past lowercase Greek
+ (0xF0B7, '\u{2022}'), // bullet
+ (0xF030, '\u{0030}'), // digit zero
+ (0xF0F2, '\u{222B}'), // integral
+ ] {
+ assert_eq!(symbol_pua_to_unicode(code), Some(expected), "U+{code:04X}");
+ }
+ }
+
+ /// An unmapped codepoint is `None`, not "maps to itself" — the caller
+ /// needs the distinction to choose a font.
+ #[test]
+ fn unmapped_pua_is_none() {
+ assert_eq!(symbol_pua_to_unicode(0xF0FF), None);
+ assert_eq!(wingdings_pua_to_unicode(0xF0FF), None);
+ }
+
+ /// When every PUA character maps, the text is standard Unicode and must
+ /// move to the fallback text font — the legacy face has no Unicode cmap.
+ #[test]
+ fn fully_mapped_text_switches_to_the_fallback_font() {
+ let (text, family) = remap_legacy_font_chars("\u{F0B7}", "Symbol", "Calibri");
+ assert_eq!(text, "\u{2022}", "bullet remapped");
+ assert_eq!(family, "Calibri");
+ }
+
+ /// Regression: an *unmapped* PUA character used to be handed to the
+ /// fallback text font anyway, which is a guaranteed `.notdef` box. The
+ /// only font that can render a surviving PUA scalar is the legacy face it
+ /// came from, so the original family must be kept.
+ #[test]
+ fn unmapped_pua_keeps_the_legacy_font() {
+ let (text, family) = remap_legacy_font_chars("\u{F0FF}", "Symbol", "Calibri");
+ assert_eq!(text, "\u{F0FF}", "unmapped codepoint survives unchanged");
+ assert_eq!(
+ family, "Symbol",
+ "keep the legacy face — it is the only one that can render this"
+ );
+ }
+
+ /// Mixed input: one unmapped character is enough to keep the legacy font,
+ /// because the family is a whole-string decision.
+ #[test]
+ fn one_unmapped_char_keeps_the_legacy_font_for_the_whole_label() {
+ let (_, family) = remap_legacy_font_chars("\u{F0B7}\u{F0FF}", "Symbol", "Calibri");
+ assert_eq!(family, "Symbol");
+ }
+
+ /// Non-legacy families are passed through untouched.
+ #[test]
+ fn non_legacy_family_is_untouched() {
+ let (text, family) = remap_legacy_font_chars("abc", "Arial", "Calibri");
+ assert_eq!(text, "abc");
+ assert_eq!(family, "Arial");
+ }
+
+ // ── §14.1.2 style-measurement policy ─────────────────────────────────
+
+ fn vml_len(value: f64, unit: model::VmlLengthUnit) -> model::VmlLength {
+ model::VmlLength { value, unit }
+ }
+
+ #[test]
+ fn style_length_passes_absolute_units_through() {
+ use model::VmlLengthUnit;
+ assert_eq!(
+ vml_style_length_to_pt(vml_len(9.0, VmlLengthUnit::Pt)),
+ Some(Pt::new(9.0))
+ );
+ assert_eq!(
+ vml_style_length_to_pt(vml_len(1.0, VmlLengthUnit::In)),
+ Some(Pt::new(72.0))
+ );
+ }
+
+ /// Regression: the two render-layer converters disagreed here — one read a
+ /// bare number as EMU, the other as points, so the same `width:9` meant
+ /// 0.0007pt in one code path and 9pt in the other. EMU is the rule the
+ /// model documents for `style` measurements.
+ #[test]
+ fn style_length_reads_a_bare_number_as_emu() {
+ let got = vml_style_length_to_pt(vml_len(914400.0, model::VmlLengthUnit::None))
+ .expect("unitless resolves in a style measurement");
+ assert!(
+ (got.raw() - 72.0).abs() < 1e-3,
+ "914400 EMU is one inch, got {}",
+ got.raw()
+ );
+ }
+
+ /// Regression: `%` and `em` used to fall through to the raw value, so
+ /// `width:50%` became 50pt. They are unresolvable here; the caller
+ /// substitutes its own default.
+ #[test]
+ fn style_length_rejects_units_needing_a_container() {
+ for unit in [model::VmlLengthUnit::Percent, model::VmlLengthUnit::Em] {
+ assert_eq!(
+ vml_style_length_to_pt(vml_len(50.0, unit)),
+ None,
+ "{unit:?} needs a containing box / font size"
+ );
+ }
+ }
+}
+
+#[cfg(test)]
+mod border_style_tests {
+ use super::*;
+
+ fn border(style: model::BorderStyle) -> model::Border {
+ model::Border {
+ style,
+ width: crate::model::dimension::Dimension::new(8),
+ color: model::Color::Auto,
+ space: crate::model::dimension::Dimension::new(0),
+ }
+ }
+
+ /// §17.4.38: only `Single` and `Double` are drawn; the other 24 styles are
+ /// approximated by a solid line of the declared width and colour.
+ #[test]
+ fn unsupported_styles_collapse_to_single_preserving_width_and_colour() {
+ let mut state = BuildState::default();
+ for style in [
+ model::BorderStyle::Dotted,
+ model::BorderStyle::Dashed,
+ model::BorderStyle::Triple,
+ model::BorderStyle::Wave,
+ model::BorderStyle::DashDotStroked,
+ model::BorderStyle::ThinThickLargeGap,
+ ] {
+ let line = convert_model_border(&border(style), &mut state);
+ assert_eq!(
+ line.style,
+ TableBorderStyle::Single,
+ "{style:?} should approximate as a single line"
+ );
+ assert_eq!(line.width, Pt::from(border(style).width), "width preserved");
+ }
+ }
+
+ #[test]
+ fn supported_styles_are_not_approximated() {
+ let mut state = BuildState::default();
+ assert_eq!(
+ convert_model_border(&border(model::BorderStyle::Double), &mut state).style,
+ TableBorderStyle::Double
+ );
+ assert_eq!(
+ convert_model_border(&border(model::BorderStyle::Single), &mut state).style,
+ TableBorderStyle::Single
+ );
+ assert!(
+ state.warned_border_styles.is_empty(),
+ "styles that render faithfully must not be reported as approximated"
+ );
+ }
+
+ /// Each distinct style is recorded once, so the warning fires once per
+ /// render instead of once per cell edge — thousands of lines for a large
+ /// table with dotted borders.
+ #[test]
+ fn each_unsupported_style_is_recorded_exactly_once() {
+ let mut state = BuildState::default();
+ for _ in 0..50 {
+ convert_model_border(&border(model::BorderStyle::Dotted), &mut state);
+ convert_model_border(&border(model::BorderStyle::Dashed), &mut state);
+ }
+ assert_eq!(
+ state.warned_border_styles.len(),
+ 2,
+ "one entry per distinct style, regardless of occurrence count"
+ );
+ assert!(
+ state
+ .warned_border_styles
+ .contains(&model::BorderStyle::Dotted)
+ );
+ assert!(
+ state
+ .warned_border_styles
+ .contains(&model::BorderStyle::Dashed)
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/build/floating.rs b/crates/liteparse-docx/src/render/layout/build/floating.rs
new file mode 100644
index 0000000..abba199
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/build/floating.rs
@@ -0,0 +1,2643 @@
+//! Extract floating (anchor) images and shapes from paragraph inlines, and
+//! resolve their positions in the caller-specified coordinate frame.
+
+use crate::model::{self, Paragraph};
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtSize;
+use crate::render::layout::section::{
+ FloatingImage, FloatingImageX, FloatingImageY, FloatingShape, PageParity,
+};
+use crate::render::resolve::shape_geometry::build_geometry;
+use crate::render::resolve::shape_visuals::resolve_shape_visuals;
+
+use super::convert::vml_style_length_to_pt;
+use super::{BuildContext, BuildState};
+
+/// Coordinate frame in which an anchor's position is resolved.
+///
+/// The choice of frame determines both the origin used as the zero of the
+/// horizontal axis and how §20.4.2 vertical references map onto the
+/// `FloatingImageY` ADT.
+///
+/// * `Page` — page-absolute coordinates. The horizontal origin is the page
+/// left edge and §20.4.2.10 `AnchorRelativeFrom` references resolve against
+/// the page's own margins. Callers use this frame when the emitted command
+/// is appended directly to the page command list without a further shift.
+///
+/// * `Stack` — relative to a stack frame origin (table cell top-left, or
+/// header/footer content-area top-left). All horizontal references collapse
+/// to the frame's left edge, and vertical offsets are stored as
+/// `RelativeToParagraph` so the stacker anchors them to the owning
+/// paragraph. Callers use this frame when the emitted command passes
+/// through `stack_blocks` and will be shifted by the caller into page
+/// coordinates.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum AnchorFrame {
+ Page,
+ Stack,
+}
+
+/// Filter applied at extraction time so a shape's vertical anchor type can
+/// route it through the correct frame.
+///
+/// Shapes whose vertical position is `paragraph`/`line` are paragraph-bound
+/// (their absolute y is a function of the host paragraph's y), so they
+/// travel on the owning paragraph through `stack_blocks`. Shapes with
+/// `page`/`margin` vertical anchors resolve to a fixed page-y and must
+/// bypass the stacker's per-paragraph anchoring — header/footer routes
+/// them through a separate page-level vec, similar to how floating images
+/// are split out.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum ShapeAnchorClass {
+ /// Take every wsp shape regardless of its vertical anchor. Used by
+ /// body paragraphs and table cells, where the legacy single-channel
+ /// behaviour is still in effect.
+ All,
+ /// Only shapes whose vertical anchor is `paragraph` or `line`.
+ ParagraphAnchored,
+ /// Only shapes whose vertical anchor is `page` / `margin` /
+ /// `topMargin` / `bottomMargin` / `insideMargin` / `outsideMargin`.
+ PageAnchored,
+}
+
+/// Extract floating (anchor) images from a paragraph's inlines.
+///
+/// Positions are resolved in the coordinate system implied by `frame`
+/// (see [`AnchorFrame`]).
+use crate::render::layout::{McBranch, live_mc_branch};
+
+fn find_anchor_images<'a>(
+ inlines: &'a [crate::model::Inline],
+ out: &mut Vec<&'a crate::model::Image>,
+) {
+ use crate::model::{GraphicContent, ImagePlacement, Inline};
+
+ for inline in inlines {
+ match inline {
+ // Images with a WordProcessingShape graphic are handled by
+ // `extract_floating_shapes`; skip them here so the shape
+ // branch owns their layout path end-to-end.
+ Inline::Image(img)
+ if matches!(img.placement, ImagePlacement::Anchor(_))
+ && !matches!(img.graphic, Some(GraphicContent::WordProcessingShape(_))) =>
+ {
+ out.push(img);
+ }
+ Inline::Hyperlink(link) => find_anchor_images(&link.content, out),
+ Inline::Field(f) => find_anchor_images(&f.content, out),
+ Inline::AlternateContent(ac) => match live_mc_branch(ac) {
+ McBranch::Choices(choices) => {
+ for choice in choices {
+ find_anchor_images(&choice.content, out);
+ }
+ }
+ McBranch::Fallback(fallback) => find_anchor_images(fallback, out),
+ McBranch::Neither => {}
+ },
+ _ => {}
+ }
+ }
+}
+
+pub(super) fn extract_floating_images(
+ para: &Paragraph,
+ ctx: &BuildContext,
+ state: &BuildState,
+ frame: AnchorFrame,
+) -> Vec<FloatingImage> {
+ use crate::model::ImagePlacement;
+
+ let mut anchor_imgs = Vec::new();
+ find_anchor_images(&para.content, &mut anchor_imgs);
+
+ let mut images = Vec::new();
+ for img in anchor_imgs {
+ let ImagePlacement::Anchor(ref anchor) = img.placement else {
+ continue;
+ };
+ let Some(rel_id) = crate::render::resolve::images::extract_image_rel_id(img) else {
+ continue;
+ };
+ let Some(image_data) = ctx.resolved.media.get(rel_id).cloned() else {
+ log::warn!(
+ "anchor image: rel_id={} missing from media table ({} entries)",
+ rel_id.as_str(),
+ ctx.resolved.media.len(),
+ );
+ continue;
+ };
+
+ let w = Pt::from(img.extent.width);
+ let h = Pt::from(img.extent.height);
+ let (x, y) = resolve_anchor_position(anchor, w, h, state, frame);
+
+ images.push(FloatingImage {
+ image_data,
+ size: PtSize::new(w, h),
+ src_rect: crate::render::resolve::images::extract_src_rect(img),
+ x,
+ y,
+ wrap_mode: crate::render::layout::section::WrapMode::from_model(&anchor.wrap),
+ dist_left: Pt::from(anchor.distance.left),
+ dist_right: Pt::from(anchor.distance.right),
+ behind_doc: anchor.behind_text,
+ });
+ }
+
+ // VML primitives that resolve to images (`<v:image>` or
+ // `<v:shape type="#_x0000_t75">` carrying `<v:imagedata>`) ride
+ // through the same `FloatingImage` channel as DrawingML images.
+ extract_vml_floating_images(&para.content, state, frame, ctx, &mut images);
+
+ images
+}
+
+// ── Floating shape extraction ──────────────────────────────────────────────
+
+/// Extract floating (anchor) DrawingML shapes from a paragraph's inlines,
+/// resolve their geometry + visuals, and compute their positions in the
+/// coordinate frame implied by `frame`. Pure: takes immutable references to
+/// `ctx` / `state`.
+fn find_anchor_shapes<'a>(
+ inlines: &'a [crate::model::Inline],
+ out: &mut Vec<&'a crate::model::Image>,
+) {
+ use crate::model::{GraphicContent, ImagePlacement, Inline};
+
+ for inline in inlines {
+ match inline {
+ Inline::Image(img)
+ if matches!(img.placement, ImagePlacement::Anchor(_))
+ && matches!(img.graphic, Some(GraphicContent::WordProcessingShape(_))) =>
+ {
+ out.push(img);
+ }
+ Inline::Hyperlink(link) => find_anchor_shapes(&link.content, out),
+ Inline::Field(f) => find_anchor_shapes(&f.content, out),
+ // MCE §M.1.2: shapes live inside the `<mc:Choice Requires="wps">`
+ // branch and the `<mc:Fallback>` carries the VML equivalent. The
+ // branch is chosen by `live_mc_branch`, the same call the image
+ // walker makes, so the two cannot disagree about which one the
+ // paragraph contains.
+ Inline::AlternateContent(ac) => match live_mc_branch(ac) {
+ McBranch::Choices(choices) => {
+ for choice in choices {
+ find_anchor_shapes(&choice.content, out);
+ }
+ }
+ McBranch::Fallback(fallback) => find_anchor_shapes(fallback, out),
+ McBranch::Neither => {}
+ },
+ _ => {}
+ }
+ }
+}
+
+pub(super) fn extract_floating_shapes(
+ para: &Paragraph,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+ frame: AnchorFrame,
+ restrict: ShapeAnchorClass,
+) -> Vec<FloatingShape> {
+ use crate::model::{GraphicContent, ImagePlacement};
+
+ let mut shape_imgs = Vec::new();
+ find_anchor_shapes(&para.content, &mut shape_imgs);
+
+ let mut shapes = Vec::new();
+ for img in shape_imgs {
+ let ImagePlacement::Anchor(ref anchor) = img.placement else {
+ continue;
+ };
+ // Filter by anchor class so each call site only sees the shapes whose
+ // vertical anchor matches the frame it's resolving in.
+ let class_match = match restrict {
+ ShapeAnchorClass::All => true,
+ ShapeAnchorClass::ParagraphAnchored => anchors_to_paragraph(anchor),
+ ShapeAnchorClass::PageAnchored => !anchors_to_paragraph(anchor),
+ };
+ if !class_match {
+ continue;
+ }
+ let wsp = match img.graphic.as_ref() {
+ Some(GraphicContent::WordProcessingShape(w)) => w,
+ _ => continue,
+ };
+ let shape_props = wsp.shape_properties.as_ref();
+ let geometry = match shape_props.and_then(|p| p.geometry.as_ref()) {
+ Some(g) => g,
+ None => continue, // No geometry → nothing to draw.
+ };
+
+ let w = Pt::from(img.extent.width);
+ let h = Pt::from(img.extent.height);
+ let extent = PtSize::new(w, h);
+
+ let shape_path = match build_geometry(geometry, extent) {
+ Some(p) => p,
+ None => continue, // Unimplemented preset or empty geometry.
+ };
+
+ let visuals = resolve_shape_visuals(
+ shape_props,
+ wsp.style_line_ref.as_ref(),
+ wsp.style_effect_ref.as_ref(),
+ wsp.style_fill_ref.as_ref(),
+ ctx.resolved.theme.as_ref(),
+ );
+
+ // §20.1.7.6 transform attributes (rotation/flip) live on the shape's
+ // `spPr/xfrm`; anchor position is independent.
+ let (rotation, flip_h, flip_v) = shape_props
+ .and_then(|p| p.transform.as_ref())
+ .map(|t| {
+ (
+ t.rotation
+ .unwrap_or_else(|| crate::model::dimension::Dimension::new(0)),
+ t.flip_h.unwrap_or(false),
+ t.flip_v.unwrap_or(false),
+ )
+ })
+ .unwrap_or((crate::model::dimension::Dimension::new(0), false, false));
+
+ let (x, y) = resolve_anchor_position(anchor, w, h, state, frame);
+
+ // §17.17.1: lay out the shape's text-box content (`wps:txbx`) into
+ // shape-local Pt commands. Both paragraph- and page-anchored shapes
+ // benefit from the typed sub-layout — the consumer shifts the
+ // commands by the shape's resolved origin (whether `RelativeToParagraph`
+ // or `Absolute`), so text always lands on the shape's fill.
+ let text_commands = build_shape_text_commands(wsp, extent, ctx, state);
+
+ shapes.push(FloatingShape {
+ x,
+ y,
+ size: extent,
+ rotation,
+ flip_h,
+ flip_v,
+ wrap_mode: crate::render::layout::section::WrapMode::from_model(&anchor.wrap),
+ dist_left: Pt::from(anchor.distance.left),
+ dist_right: Pt::from(anchor.distance.right),
+ behind_doc: anchor.behind_text,
+ paths: shape_path.paths,
+ fill: visuals.fill,
+ stroke: visuals.stroke,
+ effects: visuals.effects,
+ text_commands,
+ });
+ }
+
+ // VML primitives (`<v:rect>` and friends) coexist in the same
+ // paragraph and resolve to the same `FloatingShape` shape format.
+ // We append them here so both DrawingML and VML floats live in one
+ // ordered list passed downstream.
+ extract_vml_primitive_shapes(&para.content, state, frame, &mut shapes);
+
+ shapes
+}
+
+/// Walk the inlines for `Inline::Pict` containers and emit a
+/// [`FloatingShape`] for every renderable VML primitive variant.
+/// Phase B handles `<v:rect>`; later phases can extend this to
+/// `RoundRect`, `Oval`, `Line`, `PolyLine`, `Image`, and grouped
+/// children.
+///
+/// Position resolution uses [`vml_absolute_position`] — currently
+/// page-relative when `position:absolute` and `margin-left`/
+/// `margin-top` are present. The vorlage gray-bar pattern fits this
+/// shape exactly.
+/// Walk inlines for VML primitives that resolve to images
+/// (`<v:image>` or a `<v:shape type="#_x0000_t75">` whose only child
+/// is `<v:imagedata>`). Both forms reach this code path through
+/// `Inline::Pict.primitives`, including the `Inline::Pict` a live
+/// `<mc:Fallback>` carries — see [`live_mc_branch`].
+fn extract_vml_floating_images(
+ inlines: &[crate::model::Inline],
+ state: &BuildState,
+ frame: AnchorFrame,
+ ctx: &BuildContext,
+ out: &mut Vec<FloatingImage>,
+) {
+ use crate::model::Inline;
+ for inline in inlines {
+ match inline {
+ Inline::Pict(pict) => {
+ for primitive in &pict.primitives {
+ extract_vml_primitive_image(primitive, state, frame, ctx, out);
+ }
+ }
+ Inline::Hyperlink(link) => {
+ extract_vml_floating_images(&link.content, state, frame, ctx, out)
+ }
+ Inline::Field(f) => extract_vml_floating_images(&f.content, state, frame, ctx, out),
+ // §M.1.2: exactly one branch is live and [`live_mc_branch`] is the
+ // only thing that decides which. This arm used to be `{}` — a
+ // third answer, given by not answering — so a Choice we could not
+ // draw plus a Fallback holding a VML image left the anchor with no
+ // geometry at all while its text still reached the page.
+ Inline::AlternateContent(ac) => match live_mc_branch(ac) {
+ McBranch::Choices(choices) => {
+ for choice in choices {
+ extract_vml_floating_images(&choice.content, state, frame, ctx, out);
+ }
+ }
+ McBranch::Fallback(fallback) => {
+ extract_vml_floating_images(fallback, state, frame, ctx, out)
+ }
+ McBranch::Neither => {}
+ },
+ _ => {}
+ }
+ }
+}
+
+fn extract_vml_primitive_image(
+ primitive: &model::VmlPrimitive,
+ state: &BuildState,
+ frame: AnchorFrame,
+ ctx: &BuildContext,
+ out: &mut Vec<FloatingImage>,
+) {
+ use crate::model::VmlPrimitive;
+ match primitive {
+ VmlPrimitive::Image(img) => {
+ if let Some(fi) = build_vml_floating_image(&img.common, state, frame, ctx) {
+ out.push(fi);
+ }
+ }
+ // §14.1.2.19 — `<v:shape type="#_x0000_t75"><v:imagedata r:id=…/>`
+ // is the standard pre-DrawingML way to embed an image. We treat
+ // any VmlShape whose `image_data` is set and whose `text_box` is
+ // empty as image-bearing; shapes that *also* host text are handled
+ // elsewhere via the inline fragment collector.
+ VmlPrimitive::Shape(s) if s.common.image_data.is_some() && s.common.text_box.is_none() => {
+ if let Some(fi) = build_vml_floating_image(&s.common, state, frame, ctx) {
+ out.push(fi);
+ }
+ }
+ VmlPrimitive::Group(g) => {
+ for child in &g.children {
+ extract_vml_primitive_image(child, state, frame, ctx, out);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn build_vml_floating_image(
+ common: &model::VmlCommonAttrs,
+ state: &BuildState,
+ frame: AnchorFrame,
+ ctx: &BuildContext,
+) -> Option<FloatingImage> {
+ use crate::render::layout::section::WrapMode;
+
+ let rel_id = common.image_data.as_ref()?.rel_id.as_ref()?;
+ let image_data = ctx.resolved.media.get(rel_id).cloned()?;
+
+ let (page_x, y) = vml_absolute_position(&common.style)?;
+ // VML has no `inside`/`outside` equivalent — `margin-left` is one number.
+ let x = FloatingImageX::Absolute(match frame {
+ AnchorFrame::Page => page_x,
+ AnchorFrame::Stack => page_x - state.page_config.margins.left,
+ });
+
+ let width = common.style.width.and_then(vml_style_length_to_pt)?;
+ let height = common.style.height.and_then(vml_style_length_to_pt)?;
+ if width <= Pt::ZERO || height <= Pt::ZERO {
+ return None;
+ }
+
+ Some(FloatingImage {
+ image_data,
+ size: PtSize::new(width, height),
+ // VML crops (`v:imagedata` crop*) are a separate mechanism; not modelled.
+ src_rect: None,
+ x,
+ y: FloatingImageY::RelativeToParagraph(y),
+ wrap_mode: WrapMode::None,
+ dist_left: Pt::ZERO,
+ dist_right: Pt::ZERO,
+ behind_doc: false,
+ })
+}
+
+fn extract_vml_primitive_shapes(
+ inlines: &[crate::model::Inline],
+ state: &BuildState,
+ frame: AnchorFrame,
+ out: &mut Vec<FloatingShape>,
+) {
+ use crate::model::Inline;
+ for inline in inlines {
+ match inline {
+ Inline::Pict(pict) => {
+ for primitive in &pict.primitives {
+ extract_vml_primitive(primitive, state, frame, out);
+ }
+ }
+ Inline::Hyperlink(link) => {
+ extract_vml_primitive_shapes(&link.content, state, frame, out)
+ }
+ Inline::Field(f) => extract_vml_primitive_shapes(&f.content, state, frame, out),
+ // §M.1.2: `<mc:AlternateContent>` carries the same shape twice —
+ // modern DrawingML in `<mc:Choice>`, a VML fallback in
+ // `<mc:Fallback>` — so drawing both emits one rectangle twice.
+ // Skipping the element outright avoided that and created the
+ // opposite bug: a Choice we cannot draw left the Fallback's rect
+ // unrendered, which is the "future case" the note here used to
+ // anticipate. [`live_mc_branch`] is now that Choice-fed signal,
+ // and the same one `find_anchor_shapes` asks.
+ Inline::AlternateContent(ac) => match live_mc_branch(ac) {
+ McBranch::Choices(choices) => {
+ for choice in choices {
+ extract_vml_primitive_shapes(&choice.content, state, frame, out);
+ }
+ }
+ McBranch::Fallback(fallback) => {
+ extract_vml_primitive_shapes(fallback, state, frame, out)
+ }
+ McBranch::Neither => {}
+ },
+ _ => {}
+ }
+ }
+}
+
+fn extract_vml_primitive(
+ primitive: &model::VmlPrimitive,
+ state: &BuildState,
+ frame: AnchorFrame,
+ out: &mut Vec<FloatingShape>,
+) {
+ use crate::model::VmlPrimitive;
+ match primitive {
+ VmlPrimitive::Rect(r) => {
+ if let Some(shape) = build_vml_rect_shape(&r.common, state, frame) {
+ out.push(shape);
+ }
+ }
+ // §14.1.2.17 `<v:roundrect>`: rounded-corner variant. The
+ // corner radius is `arcsize * min(width, height) / 2` —
+ // small radii barely distinguish from a plain rect at typical
+ // doc resolutions, so for Tier 0 we render as a plain
+ // rectangle. The `arcsize` value survives in the model for a
+ // future rounded-path build.
+ VmlPrimitive::RoundRect(r) => {
+ if let Some(shape) = build_vml_rect_shape(&r.common, state, frame) {
+ out.push(shape);
+ }
+ }
+ // §14.1.2.9: groups carry their own coord system; we walk
+ // children so any absolute-positioned descendants reach the
+ // page. The local-coord transform (`coordsize`/`coordorigin`
+ // → page coords) for relative-positioned children is left
+ // for a future phase — most authored groups in headers and
+ // footers use absolute positioning and don't depend on it.
+ VmlPrimitive::Group(g) => {
+ for child in &g.children {
+ extract_vml_primitive(child, state, frame, out);
+ }
+ }
+ // Image variants don't produce a `FloatingShape` — they go
+ // through the parallel `extract_vml_floating_images` path
+ // and emit `FloatingImage` instead.
+ VmlPrimitive::Image(_) => {}
+ // Long-tail primitives modeled in Phase A but not yet
+ // emitted as shapes (oval/line/polyline/arc/curve). Phase D
+ // will dispatch them to `DrawCommand::Path` / `Line`. Their
+ // text-box content (where applicable) is still picked up by
+ // the inline fragment collector.
+ VmlPrimitive::Shape(_)
+ | VmlPrimitive::Oval(_)
+ | VmlPrimitive::Line(_)
+ | VmlPrimitive::PolyLine(_)
+ | VmlPrimitive::Arc(_)
+ | VmlPrimitive::Curve(_) => {}
+ }
+}
+
+/// Build a [`FloatingShape`] for a `<v:rect>`-like primitive whose
+/// `common` carries an absolute position + width/height in its
+/// `style`. Returns `None` when the spec-required attributes are
+/// absent so the rect can't be placed (in which case Word would
+/// silently skip it too).
+///
+/// The returned shape's `x` lives in the coordinate frame implied by
+/// `frame`: in `AnchorFrame::Stack` the downstream emitter (e.g.
+/// `render_footer`) adds `margins.left` back, so we subtract it here
+/// to keep the page-relative `margin-left` honest.
+fn build_vml_rect_shape(
+ common: &model::VmlCommonAttrs,
+ state: &BuildState,
+ frame: AnchorFrame,
+) -> Option<FloatingShape> {
+ use crate::render::geometry::PtOffset;
+ use crate::render::resolve::shape_geometry::{PathVerb, SubPath};
+
+ // Position via `position:absolute` + `margin-left/top`. VML's
+ // `margin-left` is page-relative when the shape's
+ // `mso-position-horizontal-relative` is `page` (the vorlage gray
+ // bar's case) — we don't model that style attribute yet, so
+ // assume page-relative and let phase D add the discriminator.
+ //
+ // In `AnchorFrame::Stack` the eventual emitter shifts every
+ // command by `margins.left` to convert stack→page; we subtract
+ // it from `x` up front so the round-trip preserves the
+ // page-relative offset.
+ let (page_x, y) = vml_absolute_position(&common.style)?;
+ // VML has no `inside`/`outside` equivalent — `margin-left` is one number.
+ let x = FloatingImageX::Absolute(match frame {
+ AnchorFrame::Page => page_x,
+ AnchorFrame::Stack => page_x - state.page_config.margins.left,
+ });
+
+ // Size via `style.width` / `style.height`. A rect with no extent
+ // can't meaningfully render.
+ let width = common.style.width.and_then(vml_style_length_to_pt)?;
+ let height = common.style.height.and_then(vml_style_length_to_pt)?;
+ if width <= Pt::ZERO || height <= Pt::ZERO {
+ return None;
+ }
+ let extent = PtSize::new(width, height);
+
+ // Fill resolution per §14.1.2.5: a `<v:fill>` child overrides
+ // `@fillcolor`. We honor solid fills natively and degrade
+ // gradient/tile/pattern/frame to `ResolvedFill::None` with a
+ // one-time log so the rest of the shape still renders.
+ let fill = resolve_vml_solid_fill(common);
+
+ // Build a closed-rectangle path in shape-local Pt. The painter
+ // applies the `(x, y)` and `size` to position the path.
+ let paths = vec![SubPath {
+ verbs: vec![
+ PathVerb::MoveTo(PtOffset::new(Pt::ZERO, Pt::ZERO)),
+ PathVerb::LineTo(PtOffset::new(extent.width, Pt::ZERO)),
+ PathVerb::LineTo(PtOffset::new(extent.width, extent.height)),
+ PathVerb::LineTo(PtOffset::new(Pt::ZERO, extent.height)),
+ PathVerb::Close,
+ ],
+ fill_mode: crate::model::PathFillMode::Norm,
+ stroked: matches!(common.stroked, Some(true)),
+ }];
+
+ // Vertical position resolution depends on the
+ // `mso-position-vertical-relative` style attribute:
+ // * `page`/`margin` → absolute page coordinates
+ // * `text`/`paragraph` (Word's default in body and footer) →
+ // relative to the owning paragraph
+ //
+ // Phase B only honors the latter (the vorlage gray-bar case);
+ // page-anchored vertical resolution lands in phase D when the
+ // full position resolver is wired in. Until then we treat the
+ // y offset as relative to the host paragraph — which matches
+ // Word's default and lets the footer rect render correctly.
+ let y_image = FloatingImageY::RelativeToParagraph(y);
+
+ Some(FloatingShape {
+ x,
+ y: y_image,
+ size: extent,
+ rotation: crate::model::dimension::Dimension::new(0),
+ flip_h: false,
+ flip_v: false,
+ // §14.1.2.16: VML rects don't usually wrap surrounding text
+ // — they sit at an absolute z-index. Treat them as wrapNone.
+ wrap_mode: crate::render::layout::section::WrapMode::None,
+ dist_left: Pt::ZERO,
+ dist_right: Pt::ZERO,
+ // §14.1.2 z-index drives layering. For Tier 0 we treat all
+ // VML primitives as non-behind-text (drawn in document order).
+ behind_doc: false,
+ paths,
+ fill,
+ stroke: None,
+ effects: vec![],
+ // VML rect text-box content is still picked up at the host paragraph
+ // y by the inline-fragment collector. Sub-layout into shape-local
+ // commands isn't wired for VML primitives yet.
+ text_commands: Vec::new(),
+ })
+}
+
+/// Shared anchor-position resolver used by both `extract_floating_images`
+/// and `extract_floating_shapes`. Returns `(x, y)` in the coordinate system
+/// implied by `frame`.
+///
+/// See [`AnchorFrame`] for the semantics of each frame. Both horizontal and
+/// vertical axes are resolved per §20.4.2.10 `AnchorRelativeFrom` when
+/// `frame = Page`; in `Stack` the frame origin collapses every horizontal
+/// reference to the frame's left edge (matching the body's left margin) and
+/// every vertical offset is carried as `RelativeToParagraph` so the stacker
+/// anchors the float to the owning paragraph.
+fn resolve_anchor_position(
+ anchor: &crate::model::AnchorProperties,
+ content_w: Pt,
+ content_h: Pt,
+ state: &BuildState,
+ frame: AnchorFrame,
+) -> (FloatingImageX, FloatingImageY) {
+ let x = resolve_anchor_x(anchor, content_w, state, frame);
+ let y = resolve_anchor_y(anchor, content_h, state, frame);
+ (x, y)
+}
+
+/// §20.4.3.4 `ST_RelFromH`: a horizontal strip of the sheet, expressed in the
+/// coordinates of the [`AnchorFrame`] that produced it.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct AnchorSpan {
+ /// x of the strip's left edge.
+ start: Pt,
+ /// Its width. Zero is legal and meaningful: a page with no left margin has
+ /// an empty `leftMargin` strip, and in [`AnchorFrame::Stack`] the
+ /// container's extent is simply not known here.
+ extent: Pt,
+}
+
+/// The region an anchor measures against — or, for the two references whose
+/// region depends on which page the object lands on, the pair it chooses from.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum HorizontalRegion {
+ /// The same strip on every page.
+ Fixed(AnchorSpan),
+ /// §20.4.3.4 `insideMargin` / `outsideMargin`: "inside" is the left margin
+ /// on an odd (recto) page and the right margin on an even one, so which
+ /// strip this names is a function of the page number.
+ Mirrored { odd: AnchorSpan, even: AnchorSpan },
+}
+
+impl HorizontalRegion {
+ /// The strip this reference names on a page of the given parity.
+ fn on(self, parity: PageParity) -> AnchorSpan {
+ match self {
+ Self::Fixed(span) => span,
+ Self::Mirrored { odd, even } => match parity {
+ PageParity::Odd => odd,
+ PageParity::Even => even,
+ },
+ }
+ }
+}
+
+/// The page as an [`AnchorFrame`] measures it — the input to
+/// [`horizontal_region`].
+///
+/// §20.4.3.4's references split in two, and that split is what makes `Stack`
+/// tractable:
+///
+/// * **Page-derived** — `page` and the four margin strips are pure functions of
+/// the sheet and its margins, so they are knowable in either frame;
+/// `page_left` is what carries them into frame coordinates.
+/// * **Container-derived** — `margin` and `column` name the area the object's
+/// *container* gives it. In `Page` that is the sheet's text area. In `Stack`
+/// the container is a table cell or a header whose extent never reaches this
+/// function, so the region collapses onto the frame origin. That collapse is
+/// pre-existing and deliberate (see [`AnchorFrame`]); giving it a real extent
+/// would move every header float.
+#[derive(Clone, Copy, Debug)]
+struct FrameGeometry {
+ /// x of the sheet's left edge. Zero in `Page`; `-margins.left` in `Stack`,
+ /// where the frame origin is the body's left margin and the caller adds
+ /// that margin back on the way into page coordinates.
+ page_left: Pt,
+ /// The sheet's own width, always real — the page exists in either frame.
+ page_width: Pt,
+ /// The sheet's own margins, likewise always real.
+ margin_left: Pt,
+ margin_right: Pt,
+ /// The container region, already in frame coordinates.
+ container: AnchorSpan,
+}
+
+impl FrameGeometry {
+ fn new(pc: &crate::render::layout::page::PageConfig, frame: AnchorFrame) -> Self {
+ let (margin_left, margin_right) = (pc.margins.left, pc.margins.right);
+ let page_width = pc.page_size.width;
+ let (page_left, container) = match frame {
+ AnchorFrame::Page => (
+ Pt::ZERO,
+ AnchorSpan {
+ start: margin_left,
+ extent: (page_width - margin_left - margin_right).max(Pt::ZERO),
+ },
+ ),
+ AnchorFrame::Stack => (
+ -margin_left,
+ AnchorSpan {
+ start: Pt::ZERO,
+ extent: Pt::ZERO,
+ },
+ ),
+ };
+ Self {
+ page_left,
+ page_width,
+ margin_left,
+ margin_right,
+ container,
+ }
+ }
+
+ /// §20.4.3.4 `page` — the whole sheet, margins included.
+ fn page(&self) -> AnchorSpan {
+ AnchorSpan {
+ start: self.page_left,
+ extent: self.page_width,
+ }
+ }
+
+ /// §20.4.3.4 `leftMargin` — the strip from the sheet's left edge to the
+ /// left margin edge. The margin *itself*, not the text area beside it.
+ fn left_margin(&self) -> AnchorSpan {
+ AnchorSpan {
+ start: self.page_left,
+ extent: self.margin_left,
+ }
+ }
+
+ /// §20.4.3.4 `rightMargin` — the mirror strip at the other edge.
+ fn right_margin(&self) -> AnchorSpan {
+ AnchorSpan {
+ start: self.page_left + self.page_width - self.margin_right,
+ extent: self.margin_right,
+ }
+ }
+}
+
+/// §20.4.3.4 `ST_RelFromH`: the region `from` names.
+///
+/// Total over `AnchorRelativeFrom` on purpose — there is deliberately no
+/// catch-all, so a new spec variant becomes a build error rather than another
+/// silent landing in the text area, which is how four distinct margin strips
+/// came to share one arm in the first place.
+fn horizontal_region(
+ from: crate::model::AnchorRelativeFrom,
+ geom: &FrameGeometry,
+) -> HorizontalRegion {
+ use crate::model::AnchorRelativeFrom as From;
+ use HorizontalRegion::{Fixed, Mirrored};
+
+ match from {
+ From::Page => Fixed(geom.page()),
+ // §20.4.3.4 `column` is the text column. With one column that is the
+ // text area; a multi-column section anchors its floats per column, and
+ // no float takes that path today.
+ From::Margin | From::Column => Fixed(geom.container),
+ From::LeftMargin => Fixed(geom.left_margin()),
+ From::RightMargin => Fixed(geom.right_margin()),
+ From::InsideMargin => Mirrored {
+ odd: geom.left_margin(),
+ even: geom.right_margin(),
+ },
+ From::OutsideMargin => Mirrored {
+ odd: geom.right_margin(),
+ even: geom.left_margin(),
+ },
+ // §20.4.3.4 `character` is not a region at all: it is the anchor's own
+ // position within the text run. Floats are extracted before that run is
+ // laid out, so the position does not exist here. Fall back to the text
+ // area — and say so, because a silent fallback is how this went
+ // unnoticed while sharing an arm with `margin`.
+ From::Character => {
+ log::warn!(
+ "anchor: relativeFrom=\"character\" needs the anchor's position in \
+ the run, which float extraction runs before — positioning \
+ against the text area instead"
+ );
+ Fixed(geom.container)
+ }
+ // §20.4.3.5-only values. One `AnchorRelativeFrom` serves both axes, so
+ // these are reachable only from a document that put a vertical
+ // reference on `wp:positionH`.
+ From::Paragraph | From::Line | From::TopMargin | From::BottomMargin => {
+ log::warn!(
+ "anchor: relativeFrom={from:?} is not a horizontal reference \
+ (§20.4.3.4) — positioning against the text area instead"
+ );
+ Fixed(geom.container)
+ }
+ }
+}
+
+/// Horizontal axis of `resolve_anchor_position`. Split out so the two axes
+/// can be read independently.
+///
+/// Parity reaches the result through *two* channels — the region
+/// (`insideMargin`/`outsideMargin`) and the alignment (`inside`/`outside`) —
+/// so rather than thread it through the arithmetic, the whole position is
+/// evaluated once per parity and the two readings handed to
+/// [`FloatingImageX::from_pages`]. An anchor that uses neither channel produces
+/// two equal readings and collapses back to `Absolute`, which is why a
+/// single-sided document carries no deferral at all.
+fn resolve_anchor_x(
+ anchor: &crate::model::AnchorProperties,
+ content_w: Pt,
+ state: &BuildState,
+ frame: AnchorFrame,
+) -> FloatingImageX {
+ use crate::model::{AnchorAlignment, AnchorPosition};
+
+ let geom = FrameGeometry::new(&state.page_config, frame);
+
+ let at = |parity: PageParity| -> Pt {
+ match &anchor.horizontal_position {
+ // §20.4.2.12: an offset is measured from the region's own left edge.
+ AnchorPosition::Offset {
+ relative_from,
+ offset,
+ } => horizontal_region(*relative_from, &geom).on(parity).start + Pt::from(*offset),
+ // §20.4.3.1: an alignment places the object within the region.
+ AnchorPosition::Align {
+ relative_from,
+ alignment,
+ } => {
+ let span = horizontal_region(*relative_from, &geom).on(parity);
+ let near = span.start;
+ let far = span.start + span.extent - content_w;
+ match alignment {
+ AnchorAlignment::Left => near,
+ AnchorAlignment::Right => far,
+ AnchorAlignment::Center => span.start + (span.extent - content_w) * 0.5,
+ // §20.4.3.1: "inside" is the binding edge — left on an odd
+ // (recto) page, right on an even one — and "outside" is the
+ // trimmed edge opposite it.
+ AnchorAlignment::Inside => match parity {
+ PageParity::Odd => near,
+ PageParity::Even => far,
+ },
+ AnchorAlignment::Outside => match parity {
+ PageParity::Odd => far,
+ PageParity::Even => near,
+ },
+ // §20.4.3.2 vertical alignments on `wp:positionH`. One
+ // `AnchorAlignment` serves both axes, so these are
+ // reachable only from a malformed document.
+ AnchorAlignment::Top | AnchorAlignment::Bottom => {
+ log::warn!(
+ "anchor: align={alignment:?} is not a horizontal alignment \
+ (§20.4.3.1) — placing at the region's left edge instead"
+ );
+ near
+ }
+ }
+ }
+ }
+ };
+
+ FloatingImageX::from_pages(at(PageParity::Odd), at(PageParity::Even))
+}
+
+/// Vertical axis of `resolve_anchor_position`. In `Stack` every offset is
+/// paragraph-relative because the stacker — not the anchor — decides the
+/// absolute page-y of the owning paragraph.
+fn resolve_anchor_y(
+ anchor: &crate::model::AnchorProperties,
+ content_h: Pt,
+ state: &BuildState,
+ frame: AnchorFrame,
+) -> FloatingImageY {
+ use crate::model::{AnchorAlignment, AnchorPosition, AnchorRelativeFrom};
+
+ let pc = &state.page_config;
+
+ match &anchor.vertical_position {
+ AnchorPosition::Offset {
+ relative_from,
+ offset,
+ } => match frame {
+ AnchorFrame::Stack => FloatingImageY::RelativeToParagraph(Pt::from(*offset)),
+ AnchorFrame::Page => match relative_from {
+ AnchorRelativeFrom::Page => FloatingImageY::Absolute(Pt::from(*offset)),
+ AnchorRelativeFrom::Margin => {
+ FloatingImageY::Absolute(pc.margins.top + Pt::from(*offset))
+ }
+ // §20.4.2.11: topMargin — offset from page top.
+ AnchorRelativeFrom::TopMargin => FloatingImageY::Absolute(Pt::from(*offset)),
+ // §20.4.2.11: bottomMargin — offset from bottom margin edge.
+ AnchorRelativeFrom::BottomMargin => FloatingImageY::Absolute(
+ pc.page_size.height - pc.margins.bottom + Pt::from(*offset),
+ ),
+ AnchorRelativeFrom::Paragraph | AnchorRelativeFrom::Line => {
+ FloatingImageY::RelativeToParagraph(Pt::from(*offset))
+ }
+ // §20.4.3.5 `insideMargin`/`outsideMargin`. The spec names them
+ // on the vertical axis without saying which strips they are —
+ // Word mirrors *left/right* for two-sided documents, not
+ // top/bottom — so no reading is derivable from source alone.
+ // Treated as `margin`, the long-standing fallback. Settling it
+ // needs a two-sided document with a float anchored
+ // inside/outside vertically, rendered by Word on both an odd
+ // and an even page; `FloatingImageX::PageParity` is already in
+ // place should the answer turn out to be "it mirrors".
+ AnchorRelativeFrom::InsideMargin | AnchorRelativeFrom::OutsideMargin => {
+ FloatingImageY::Absolute(pc.margins.top + Pt::from(*offset))
+ }
+ // §20.4.3.4-only values on `wp:positionV` — malformed.
+ AnchorRelativeFrom::Column
+ | AnchorRelativeFrom::Character
+ | AnchorRelativeFrom::LeftMargin
+ | AnchorRelativeFrom::RightMargin => {
+ log::warn!(
+ "anchor: relativeFrom={relative_from:?} is not a vertical \
+ reference (§20.4.3.5) — positioning against the margin box"
+ );
+ FloatingImageY::Absolute(pc.margins.top + Pt::from(*offset))
+ }
+ },
+ },
+ AnchorPosition::Align {
+ relative_from,
+ alignment,
+ } => {
+ // `Stack` has no resolved container extent at extraction time —
+ // the stacker decides the frame origin later — so there is no
+ // area to align within. Collapse to the paragraph origin, the
+ // same convention the `Offset` arm above uses. Emitting an
+ // `Absolute` page coordinate here would be doubly wrong: the
+ // caller shifts stack coordinates into page space afterwards,
+ // and with the frame's margins zeroed `Bottom`/`Center` resolve
+ // to negative y — off the top of the page.
+ if frame == AnchorFrame::Stack {
+ return FloatingImageY::RelativeToParagraph(Pt::ZERO);
+ }
+ let (margin_top, page_height, margin_bottom) =
+ (pc.margins.top, pc.page_size.height, pc.margins.bottom);
+ let (area_top, area_height) = match relative_from {
+ AnchorRelativeFrom::Page => (Pt::ZERO, page_height),
+ AnchorRelativeFrom::Margin => (
+ margin_top,
+ (page_height - margin_top - margin_bottom).max(Pt::ZERO),
+ ),
+ // §20.4.2.11: topMargin = area from page top to top margin edge.
+ AnchorRelativeFrom::TopMargin => (Pt::ZERO, margin_top),
+ // §20.4.2.11: bottomMargin = area from bottom margin edge to page bottom.
+ AnchorRelativeFrom::BottomMargin => (page_height - margin_bottom, margin_bottom),
+ // §20.4.3.5 `insideMargin`/`outsideMargin` — see the `Offset`
+ // arm above; treated as `margin` pending a Word reference.
+ // `paragraph`/`line` cannot align within an area the stacker
+ // has not placed yet, so they collapse onto it too.
+ AnchorRelativeFrom::InsideMargin
+ | AnchorRelativeFrom::OutsideMargin
+ | AnchorRelativeFrom::Paragraph
+ | AnchorRelativeFrom::Line => (
+ margin_top,
+ (page_height - margin_top - margin_bottom).max(Pt::ZERO),
+ ),
+ // §20.4.3.4-only values on `wp:positionV` — malformed.
+ AnchorRelativeFrom::Column
+ | AnchorRelativeFrom::Character
+ | AnchorRelativeFrom::LeftMargin
+ | AnchorRelativeFrom::RightMargin => {
+ log::warn!(
+ "anchor: relativeFrom={relative_from:?} is not a vertical \
+ reference (§20.4.3.5) — aligning within the margin box"
+ );
+ (
+ margin_top,
+ (page_height - margin_top - margin_bottom).max(Pt::ZERO),
+ )
+ }
+ };
+ let y_pos = match alignment {
+ AnchorAlignment::Top => area_top,
+ AnchorAlignment::Bottom => area_top + area_height - content_h,
+ AnchorAlignment::Center => area_top + (area_height - content_h) * 0.5,
+ // §20.4.3.2 `inside`/`outside`. Deliberately *not* given the
+ // page-parity treatment the horizontal axis gets: a two-sided
+ // document mirrors left and right, not top and bottom, so
+ // there is no reading of a vertical "inside" that source can
+ // derive. Aligned to the region's top, the long-standing
+ // fallback. Open on the same Word reference render as vertical
+ // `insideMargin`/`outsideMargin` above.
+ AnchorAlignment::Inside | AnchorAlignment::Outside => area_top,
+ // §20.4.3.1 horizontal alignments on `wp:positionV` —
+ // malformed, the same way round as the horizontal axis.
+ AnchorAlignment::Left | AnchorAlignment::Right => {
+ log::warn!(
+ "anchor: align={alignment:?} is not a vertical alignment \
+ (§20.4.3.2) — aligning to the region's top instead"
+ );
+ area_top
+ }
+ };
+ FloatingImageY::Absolute(y_pos)
+ }
+ }
+}
+
+// ── VML position helpers ───────────────────────────────────────────────────
+
+/// Search an inline (and AlternateContent fallback) for a VML text box with
+/// absolute positioning.
+pub(super) fn find_vml_absolute_position(inline: &model::Inline) -> Option<(Pt, Pt)> {
+ match inline {
+ model::Inline::Pict(pict) => find_vml_pos_in_pict(pict),
+ // Only the VML fallback carries an absolute position, and it is
+ // meaningful only when the fallback is the branch we render. A
+ // drawable Choice makes it inert, and consuming it anyway turns the
+ // fallback's origin into the header's and pushes paragraph-anchored
+ // content off-page.
+ model::Inline::AlternateContent(ac) => match crate::render::layout::live_mc_branch(ac) {
+ crate::render::layout::McBranch::Fallback(fallback) => {
+ fallback.iter().find_map(find_vml_absolute_position)
+ }
+ crate::render::layout::McBranch::Choices(_)
+ | crate::render::layout::McBranch::Neither => None,
+ },
+ _ => None,
+ }
+}
+
+fn find_vml_pos_in_pict(pict: &model::Pict) -> Option<(Pt, Pt)> {
+ for shape in pict.shapes() {
+ if shape.common.text_box.is_some() {
+ if let Some(pos) = vml_absolute_position(&shape.common.style) {
+ return Some(pos);
+ }
+ }
+ }
+ None
+}
+
+/// Extract absolute page-relative position from a VML shape style, in points.
+fn vml_absolute_position(style: &model::VmlStyle) -> Option<(Pt, Pt)> {
+ use crate::model::CssPosition;
+ if style.position != Some(CssPosition::Absolute) {
+ return None;
+ }
+ let x = style.margin_left.and_then(vml_style_length_to_pt)?;
+ let y = style.margin_top.and_then(vml_style_length_to_pt)?;
+ Some((x, y))
+}
+
+/// Compute the effective solid `ResolvedFill` for a VML primitive
+/// per §14.1.2.5. The `<v:fill>` child wins over `@fillcolor`. Only
+/// the `Solid` fill type is honored here; the others log once and
+/// degrade to `ResolvedFill::None` so the shape's outline / text
+/// content still renders.
+fn resolve_vml_solid_fill(
+ common: &model::VmlCommonAttrs,
+) -> crate::render::layout::draw_command::ResolvedFill {
+ use crate::model::{VmlColor, VmlFillType};
+ use crate::render::layout::draw_command::ResolvedFill;
+ use crate::render::resolve::drawing_color::Rgba;
+
+ let to_solid = |c: &VmlColor| -> Option<ResolvedFill> {
+ match c {
+ VmlColor::Rgb(r, g, b) => Some(ResolvedFill::Solid(Rgba {
+ r: *r as f32 / 255.0,
+ g: *g as f32 / 255.0,
+ b: *b as f32 / 255.0,
+ a: 1.0,
+ })),
+ // Named/system colors aren't yet resolved — fall through.
+ VmlColor::Named(_) => None,
+ }
+ };
+
+ if let Some(ref fill) = common.fill {
+ match fill.fill_type {
+ VmlFillType::Solid => {
+ if let Some(c) = fill.color.as_ref().and_then(to_solid) {
+ return c;
+ }
+ // Solid type with no `@color` — fall back to attribute.
+ }
+ VmlFillType::Gradient
+ | VmlFillType::GradientRadial
+ | VmlFillType::Tile
+ | VmlFillType::Frame
+ | VmlFillType::Pattern => {
+ log::warn!(
+ "vml: unsupported fill type {:?} — rendering as no-fill",
+ fill.fill_type
+ );
+ return ResolvedFill::None;
+ }
+ }
+ }
+
+ common
+ .fill_color
+ .as_ref()
+ .and_then(to_solid)
+ .unwrap_or(ResolvedFill::None)
+}
+
+/// True when the anchor's vertical position resolves relative to the host
+/// paragraph or line — the only case where the shape's eventual page-y is a
+/// function of `paragraph_top` rather than an absolute frame. The shape-text
+/// sub-layout assumes paragraph-relative placement (the stacker ties
+/// `text_commands` to the same `(fs.x, shape_y)` it uses for the path), so
+/// page-anchored shapes get their text emitted via the legacy inline-fragment
+/// collector instead. Tier 1 follow-up: extend the sub-layout to honor
+/// page/margin frames so all wsp shapes can use the typed path.
+fn anchors_to_paragraph(anchor: &crate::model::AnchorProperties) -> bool {
+ use crate::model::{AnchorPosition, AnchorRelativeFrom};
+ let relative_from = match &anchor.vertical_position {
+ AnchorPosition::Offset { relative_from, .. } => relative_from,
+ AnchorPosition::Align { relative_from, .. } => relative_from,
+ };
+ matches!(
+ relative_from,
+ AnchorRelativeFrom::Paragraph | AnchorRelativeFrom::Line
+ )
+}
+
+/// §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
+/// 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.
+pub(super) fn build_shape_text_commands(
+ wsp: &crate::model::WordProcessingShape,
+ extent: PtSize,
+ ctx: &BuildContext,
+ state: &BuildState,
+) -> Vec<crate::render::layout::draw_command::DrawCommand> {
+ if wsp.txbx_content.is_empty() {
+ 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 {
+ return Vec::new();
+ }
+
+ // §20.1.4.1.17: a wps:style/fontRef sets the shape's default text color and
+ // theme font collection for the text-box content. Resolved here and threaded
+ // through BuildState so the paragraph cascade uses them as the base (an
+ // explicit run/style color still wins).
+ let theme = ctx.resolved.theme.as_ref();
+ let (shape_default_text_color, shape_default_font_family) = match &wsp.style_font_ref {
+ Some(fr) => {
+ let color = fr.color.as_ref().map(|c| {
+ let dc = crate::render::resolve::drawing_color::DrawingColorContext::new(theme);
+ let rgba = crate::render::resolve::drawing_color::resolve_drawing_color(c, &dc);
+ crate::render::resolve::color::rgb_from_u32(rgba.to_rgb24())
+ });
+ let family = theme.and_then(|t| {
+ let fam = match fr.collection {
+ crate::model::FontCollectionIndex::Major => t.major_font.latin.clone(),
+ crate::model::FontCollectionIndex::Minor => t.minor_font.latin.clone(),
+ crate::model::FontCollectionIndex::None => String::new(),
+ };
+ (!fam.is_empty()).then_some(fam)
+ });
+ (color, family)
+ }
+ None => (None, None),
+ };
+
+ // §20.1.2.1.18: the shrink Word already computed for this body. Read once
+ // here and carried on the sub-state, so every size the cascade resolves
+ // inside the body — runs, list labels, field substitutions, blank lines —
+ // goes through it.
+ let auto_fit = crate::render::layout::ShapeAutoFit::from_body(
+ wsp.body_pr.as_ref().and_then(|bp| bp.auto_fit),
+ );
+
+ // Sub-state with the host's page dimensions and field context. Counters
+ // are reset so a footnote/list inside a shape body doesn't bump the
+ // outer counters.
+ let mut sub_state = BuildState {
+ // §17.3.1.19: a heading inside a text box is not a position in the
+ // document's main story — see `OutlineCollector`.
+ outline: crate::render::layout::build::OutlineCollector::Excluded,
+ shape_auto_fit: auto_fit,
+ page_config: state.page_config.clone(),
+ footnotes: Default::default(),
+ endnote_counter: 0,
+ list_counters: std::collections::HashMap::new(),
+ field_ctx: state.field_ctx,
+ shape_default_text_color,
+ shape_default_font_family,
+ // Its own set: this sub-state is built from a `&BuildState`, so the
+ // parent's set can't be borrowed mutably here. A border style used
+ // only inside a shape text box is therefore reported once per shape
+ // rather than once per render — bounded over-reporting in a rare case,
+ // preferred over making `state` mutable through ten signatures.
+ warned_border_styles: std::collections::HashSet::new(),
+ warned_row_cell_spacing: false,
+ };
+
+ let hf = super::build_header_footer_content(&wsp.txbx_content, ctx, &mut sub_state);
+ // §20.1.2.1.18: the body's own shrink also applies to the fallback line
+ // 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(
+ &hf.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. 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)]
+mod tests {
+ use super::find_vml_absolute_position;
+ use crate::model::dimension::Dimension;
+ use crate::model::geometry::{EdgeInsets, Size};
+ use crate::model::{
+ AlternateContent, AnchorPosition, AnchorProperties, AnchorRelativeFrom, DocProperties,
+ GraphicContent, Image, ImagePlacement, Inline, McChoice, McRequires, TextWrap,
+ WordProcessingShape,
+ };
+ use crate::render::layout::{McBranch, live_mc_branch};
+
+ /// A minimally-populated anchored `wps:wsp` shape (as `Inline::Image`).
+ fn anchored_wps_image() -> Image {
+ Image {
+ extent: Size::new(Dimension::new(0), Dimension::new(0)),
+ effect_extent: None,
+ doc_properties: DocProperties {
+ id: 1,
+ name: "shape".into(),
+ description: None,
+ hidden: None,
+ title: None,
+ },
+ graphic_frame_locks: None,
+ graphic: Some(GraphicContent::WordProcessingShape(WordProcessingShape {
+ cnv_pr: None,
+ shape_properties: None,
+ style_line_ref: None,
+ style_effect_ref: None,
+ style_fill_ref: None,
+ style_font_ref: None,
+ body_pr: None,
+ txbx_content: vec![],
+ })),
+ placement: ImagePlacement::Anchor(AnchorProperties {
+ distance: EdgeInsets::new(
+ Dimension::new(0),
+ Dimension::new(0),
+ Dimension::new(0),
+ Dimension::new(0),
+ ),
+ simple_pos: None,
+ use_simple_pos: None,
+ horizontal_position: AnchorPosition::Offset {
+ relative_from: AnchorRelativeFrom::Margin,
+ offset: Dimension::new(0),
+ },
+ vertical_position: AnchorPosition::Offset {
+ relative_from: AnchorRelativeFrom::Paragraph,
+ offset: Dimension::new(0),
+ },
+ wrap: TextWrap::None,
+ behind_text: false,
+ lock_anchor: false,
+ allow_overlap: true,
+ relative_height: 0,
+ layout_in_cell: None,
+ hidden: None,
+ }),
+ }
+ }
+
+ fn ac_with_wps_choice() -> AlternateContent {
+ AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::Image(Box::new(anchored_wps_image()))],
+ }],
+ // A non-empty fallback that would otherwise be searched.
+ fallback: Some(vec![Inline::InstrText(String::new())]),
+ }
+ }
+
+ #[test]
+ fn an_anchored_shape_in_a_choice_makes_that_choice_live() {
+ assert!(matches!(
+ live_mc_branch(&ac_with_wps_choice()),
+ McBranch::Choices(_)
+ ));
+ }
+
+ /// A Choice whose `Requires` we meet but whose content yields no anchored
+ /// object is not drawable. Liveness is a question about content: widening
+ /// it to a namespace check would light up this Choice and strand a
+ /// Fallback that is the only branch with anything to draw.
+ #[test]
+ fn a_choice_with_nothing_anchored_yields_to_the_fallback() {
+ let ac = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::InstrText(String::new())],
+ }],
+ fallback: Some(vec![Inline::InstrText(String::new())]),
+ };
+ assert!(matches!(live_mc_branch(&ac), McBranch::Fallback(_)));
+ }
+
+ #[test]
+ fn no_drawable_choice_and_no_fallback_is_neither() {
+ let ac = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::InstrText(String::new())],
+ }],
+ fallback: None,
+ };
+ assert!(matches!(live_mc_branch(&ac), McBranch::Neither));
+ }
+
+ /// An anchored *picture* is as live as an anchored shape. The suppression
+ /// sites used to ask a narrower question — "does a Choice hold a `wps:wsp`
+ /// shape?" — so a picture Choice was drawn as a float while its Fallback's
+ /// text was *also* collected inline: two branches of one element on one
+ /// page, which §M.1.2 does not allow.
+ #[test]
+ fn an_anchored_picture_in_a_choice_is_just_as_live_as_a_shape() {
+ let ac = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wpg],
+ content: vec![Inline::Image(Box::new(anchored_picture()))],
+ }],
+ fallback: Some(vec![Inline::InstrText(String::new())]),
+ };
+ assert!(matches!(live_mc_branch(&ac), McBranch::Choices(_)));
+ }
+
+ /// §M.1.2's content model for a branch is `drawing | pict`, so this shape
+ /// cannot come from a document — but the recursion has to be right anyway,
+ /// because every walker reads the same answer and an outer element that
+ /// disagreed with its inner one would put the two on different branches.
+ #[test]
+ fn a_nested_alternate_content_resolves_innermost_first() {
+ let nested = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::Image(Box::new(anchored_wps_image()))],
+ }],
+ fallback: None,
+ };
+ let outer = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::AlternateContent(nested)],
+ }],
+ fallback: Some(vec![Inline::InstrText(String::new())]),
+ };
+ assert!(matches!(live_mc_branch(&outer), McBranch::Choices(_)));
+ }
+
+ /// …and the converse: an inner element that draws nothing leaves the outer
+ /// Choice undrawable, so the outer Fallback goes live.
+ #[test]
+ fn a_nested_alternate_content_that_draws_nothing_frees_the_outer_fallback() {
+ let nested = AlternateContent {
+ choices: vec![],
+ fallback: Some(vec![Inline::InstrText(String::new())]),
+ };
+ let outer = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::AlternateContent(nested)],
+ }],
+ fallback: Some(vec![Inline::InstrText(String::new())]),
+ };
+ assert!(matches!(live_mc_branch(&outer), McBranch::Fallback(_)));
+ }
+
+ /// A `<w:pict>` holding one absolutely-positioned VML text box at
+ /// (100pt, 40pt) — a position `find_vml_absolute_position` will find, so a
+ /// test that expects `None` fails for the right reason rather than because
+ /// there was nothing to find.
+ fn positioned_vml_text_box() -> Inline {
+ use crate::model::{
+ CssPosition, Pict, VmlCommonAttrs, VmlLength, VmlLengthUnit, VmlPrimitive, VmlShape,
+ VmlStyle, VmlTextBox,
+ };
+
+ let pt = |value| {
+ Some(VmlLength {
+ value,
+ unit: VmlLengthUnit::Pt,
+ })
+ };
+ Inline::Pict(Pict {
+ shape_type: None,
+ primitives: vec![VmlPrimitive::Shape(VmlShape {
+ common: VmlCommonAttrs {
+ style: VmlStyle {
+ position: Some(CssPosition::Absolute),
+ margin_left: pt(100.0),
+ margin_top: pt(40.0),
+ ..VmlStyle::default()
+ },
+ text_box: Some(VmlTextBox {
+ style: VmlStyle::default(),
+ inset: None,
+ content: vec![],
+ }),
+ ..VmlCommonAttrs::default()
+ },
+ shape_type_ref: None,
+ vml_path: None,
+ })],
+ })
+ }
+
+ /// The probe finds a position when the pict is what the paragraph holds —
+ /// the precondition every suppression assertion below rests on.
+ #[test]
+ fn a_positioned_vml_text_box_has_an_absolute_position() {
+ assert!(find_vml_absolute_position(&positioned_vml_text_box()).is_some());
+ }
+
+ /// Regression: when the Choice is a DrawingML shape we render, the VML
+ /// fallback's absolute position must be ignored — otherwise it hijacks
+ /// the header origin and pushes paragraph-anchored content off-page.
+ #[test]
+ fn a_drawable_choice_suppresses_its_fallbacks_absolute_position() {
+ let mut ac = ac_with_wps_choice();
+ ac.fallback = Some(vec![positioned_vml_text_box()]);
+ assert!(find_vml_absolute_position(&Inline::AlternateContent(ac)).is_none());
+ }
+
+ /// …and when no Choice is drawable the fallback *is* the document, so its
+ /// position is the one to use. Suppressing here would leave a legacy
+ /// VML-only header with no origin at all.
+ #[test]
+ fn a_live_fallbacks_absolute_position_is_the_one_that_counts() {
+ let ac = AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![Inline::InstrText(String::new())],
+ }],
+ fallback: Some(vec![positioned_vml_text_box()]),
+ };
+ assert!(find_vml_absolute_position(&Inline::AlternateContent(ac)).is_some());
+ }
+
+ // ── §20.4.2.10 vertical anchor resolution ────────────────────────────
+
+ use super::{AnchorFrame, resolve_anchor_y};
+ use crate::model::AnchorAlignment;
+ use crate::render::dimension::Pt;
+ use crate::render::layout::build::BuildState;
+ use crate::render::layout::section::FloatingImageY;
+ use crate::render::layout::section::{FloatingImageX, PageParity};
+
+ fn default_state() -> BuildState {
+ BuildState {
+ page_config: Default::default(),
+ outline: Default::default(),
+ shape_auto_fit: crate::render::layout::ShapeAutoFit::NONE,
+ footnotes: Default::default(),
+ endnote_counter: 0,
+ list_counters: Default::default(),
+ field_ctx: Default::default(),
+ warned_border_styles: Default::default(),
+ warned_row_cell_spacing: false,
+ shape_default_text_color: None,
+ shape_default_font_family: None,
+ }
+ }
+
+ fn anchor_with_v(vertical_position: AnchorPosition) -> AnchorProperties {
+ let ImagePlacement::Anchor(mut a) = anchored_wps_image().placement else {
+ unreachable!("fixture is anchored")
+ };
+ a.vertical_position = vertical_position;
+ a
+ }
+
+ fn v_align(alignment: AnchorAlignment) -> AnchorProperties {
+ anchor_with_v(AnchorPosition::Align {
+ relative_from: AnchorRelativeFrom::Margin,
+ alignment,
+ })
+ }
+
+ /// Regression: the `Align` arm used to ignore `AnchorFrame`, returning an
+ /// `Absolute` *page* coordinate for stack-framed anchors. With the frame's
+ /// margins zeroed that put `Center`/`Bottom` at negative y — so an anchored
+ /// float in a table cell, header, or footer using `<wp:align>` rendered at
+ /// or above the top of the page instead of next to its paragraph.
+ #[test]
+ fn stack_frame_align_is_paragraph_relative() {
+ let state = default_state();
+ for alignment in [
+ AnchorAlignment::Top,
+ AnchorAlignment::Center,
+ AnchorAlignment::Bottom,
+ ] {
+ let y = resolve_anchor_y(
+ &v_align(alignment),
+ Pt::new(50.0),
+ &state,
+ AnchorFrame::Stack,
+ );
+ let FloatingImageY::RelativeToParagraph(offset) = y else {
+ panic!("{alignment:?} in Stack frame must be paragraph-relative");
+ };
+ assert_eq!(offset, Pt::ZERO, "{alignment:?} collapses to the paragraph");
+ }
+ }
+
+ /// The `Offset` arm already honored the frame — pinned so the two arms
+ /// can't drift apart again.
+ #[test]
+ fn stack_frame_offset_is_paragraph_relative() {
+ let anchor = anchor_with_v(AnchorPosition::Offset {
+ relative_from: AnchorRelativeFrom::Margin,
+ offset: Dimension::new(914400), // 1 inch in EMU
+ });
+ let y = resolve_anchor_y(&anchor, Pt::new(50.0), &default_state(), AnchorFrame::Stack);
+ let FloatingImageY::RelativeToParagraph(offset) = y else {
+ panic!("Offset in Stack frame must be paragraph-relative");
+ };
+ assert!((offset.raw() - 72.0).abs() < 1e-3, "1in = 72pt");
+ }
+
+ /// `Page` frame still resolves alignment against the real margin box.
+ /// Default page: 792pt tall, 72pt margins → content area 72..720.
+ #[test]
+ fn page_frame_align_resolves_against_margin_box() {
+ let state = default_state();
+ let content_h = Pt::new(50.0);
+ let cases = [
+ (AnchorAlignment::Top, 72.0),
+ (AnchorAlignment::Center, 72.0 + (648.0 - 50.0) * 0.5),
+ (AnchorAlignment::Bottom, 72.0 + 648.0 - 50.0),
+ ];
+ for (alignment, expected) in cases {
+ let y = resolve_anchor_y(&v_align(alignment), content_h, &state, AnchorFrame::Page);
+ let FloatingImageY::Absolute(got) = y else {
+ panic!("{alignment:?} in Page frame must be absolute");
+ };
+ assert!(
+ (got.raw() - expected).abs() < 1e-3,
+ "{alignment:?}: expected {expected}, got {}",
+ got.raw()
+ );
+ }
+ }
+
+ // ── §20.1.10.60 shape text-body anchoring ────────────────────────────
+
+ use super::build_shape_text_commands;
+ use crate::model::{
+ BodyProperties, Paragraph as ModelParagraph, ParagraphProperties, RunElement,
+ RunProperties, TextAnchoringType, TextRun,
+ };
+ use crate::render::fonts::FontRegistry;
+ use crate::render::geometry::PtSize;
+ use crate::render::layout::build::BuildContext;
+ use crate::render::layout::measurer::TextMeasurer;
+ use crate::render::resolve::ResolvedDocument;
+
+ fn empty_resolved() -> ResolvedDocument {
+ use std::collections::HashMap;
+ ResolvedDocument {
+ sections: Vec::new(),
+ styles: HashMap::new(),
+ numbering: HashMap::new(),
+ font_families: Vec::new(),
+ media: HashMap::new(),
+ embedded_fonts: Vec::new(),
+ pic_bullets: HashMap::new(),
+ theme: None,
+ doc_defaults_paragraph: ParagraphProperties::default(),
+ doc_defaults_run: RunProperties::default(),
+ default_paragraph_style_id: None,
+ footnotes: HashMap::new(),
+ endnotes: HashMap::new(),
+ even_and_odd_headers: false,
+ default_tab_stop: Dimension::new(720),
+ }
+ }
+
+ /// A shape whose text body is one short line, with the given `bodyPr`.
+ fn wsp_with_text(body_pr: Option<BodyProperties>) -> WordProcessingShape {
+ WordProcessingShape {
+ cnv_pr: None,
+ shape_properties: None,
+ style_line_ref: None,
+ style_effect_ref: None,
+ style_fill_ref: None,
+ style_font_ref: None,
+ body_pr,
+ txbx_content: vec![crate::model::Block::Paragraph(Box::new(ModelParagraph {
+ style_id: None,
+ properties: ParagraphProperties::default(),
+ mark_run_properties: None,
+ content: vec![Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::Text("hi".into())],
+ rsids: crate::model::RevisionIds::default(),
+ }))],
+ rsids: crate::model::ParagraphRevisionIds::default(),
+ }))],
+ }
+ }
+
+ fn body_pr(anchor: Option<TextAnchoringType>, inset_emu: i64) -> BodyProperties {
+ BodyProperties {
+ rotation: None,
+ vert_overflow: None,
+ vert: None,
+ wrap: None,
+ left_inset: Some(Dimension::new(inset_emu)),
+ top_inset: Some(Dimension::new(inset_emu)),
+ right_inset: Some(Dimension::new(inset_emu)),
+ bottom_inset: Some(Dimension::new(inset_emu)),
+ anchor,
+ auto_fit: None,
+ }
+ }
+
+ /// The y of the first emitted text command, in shape-local points.
+ fn shape_text_y(wsp: &WordProcessingShape, extent: PtSize) -> f32 {
+ let resolved = empty_resolved();
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let state = BuildState::default();
+ let commands = build_shape_text_commands(wsp, extent, &ctx, &state);
+ commands
+ .iter()
+ .find_map(|c| match c {
+ crate::render::layout::draw_command::DrawCommand::Text { position, .. } => {
+ Some(position.y.raw())
+ }
+ _ => None,
+ })
+ .expect("the shape body emits text")
+ }
+
+ /// §20.1.10.60: `anchor` places the body within the box `bIns` closes off.
+ /// `t` pins it under the top inset, `ctr` centres it in the box, `b` sits
+ /// it on the bottom inset.
+ ///
+ /// Every assertion is a *difference* between two runs. The emitted y is a
+ /// baseline, so its absolute value carries Skia's real ascent for whatever
+ /// font the host resolves — differencing cancels it out and leaves only the
+ /// anchoring this test is about.
+ #[test]
+ fn body_anchor_places_text_within_the_inset_box() {
+ // 50800 EMU = 4pt on every side of a 200x120pt shape, so the text box
+ // is 112pt tall.
+ const INSET: f32 = 4.0;
+ const BOX_HEIGHT: f32 = 120.0 - 2.0 * INSET;
+ let extent = PtSize::new(Pt::new(200.0), Pt::new(120.0));
+ let y = |anchor| shape_text_y(&wsp_with_text(Some(body_pr(Some(anchor), 50800))), extent);
+ let (top, centre, bottom) = (
+ y(TextAnchoringType::Top),
+ y(TextAnchoringType::Center),
+ y(TextAnchoringType::Bottom),
+ );
+
+ assert!(
+ top < centre && centre < bottom,
+ "t < ctr < b, got {top} / {centre} / {bottom}"
+ );
+ // Bottom-anchoring pushes the body down by the whole slack, centring by
+ // half of it — exactly a 1:2 ratio, whatever the line height is.
+ let (half, full) = (centre - top, bottom - top);
+ assert!(
+ (full - 2.0 * half).abs() < 1e-3,
+ "the centre offset is half the bottom offset, got {half} / {full}"
+ );
+ // And the slack is the box height less the one line in it, so the line
+ // height falls out of `full` — a real number to check the box against.
+ let line_height = BOX_HEIGHT - full;
+ assert!(
+ line_height > 0.0 && line_height < BOX_HEIGHT,
+ "one line fits inside the 112pt box, implied height {line_height}"
+ );
+ }
+
+ /// The top inset shifts the body one-for-one — which is what says the box
+ /// is measured from it, rather than the anchoring happening to land there.
+ #[test]
+ fn the_top_inset_shifts_a_top_anchored_body_one_for_one() {
+ let extent = PtSize::new(Pt::new(200.0), Pt::new(120.0));
+ let anchor = Some(TextAnchoringType::Top);
+ // 0 EMU vs 50800 EMU (4pt).
+ let flush = shape_text_y(&wsp_with_text(Some(body_pr(anchor, 0))), extent);
+ let inset = shape_text_y(&wsp_with_text(Some(body_pr(anchor, 50800))), extent);
+ assert!(
+ (inset - flush - 4.0).abs() < 1e-3,
+ "a 4pt top inset moves the body 4pt down, got {flush} → {inset}"
+ );
+ }
+
+ /// The bottom inset shifts a bottom-anchored body one-for-one — which is
+ /// what says `bIns` closes off the box, rather than the anchoring reaching
+ /// the shape's own bottom edge. The 1:2 centre/bottom ratio above holds
+ /// either way, so nothing else here would notice `bIns` being dropped.
+ #[test]
+ fn the_bottom_inset_shifts_a_bottom_anchored_body_one_for_one() {
+ let extent = PtSize::new(Pt::new(200.0), Pt::new(120.0));
+ let anchor = Some(TextAnchoringType::Bottom);
+ let flush = shape_text_y(&wsp_with_text(Some(body_pr(anchor, 0))), extent);
+ let inset = shape_text_y(&wsp_with_text(Some(body_pr(anchor, 50800))), extent);
+ // 4pt of bottom inset lifts the body 4pt; the 4pt of *top* inset the
+ // same fixture adds cannot reach a bottom-anchored body at all.
+ assert!(
+ (flush - inset - 4.0).abs() < 1e-3,
+ "a 4pt bottom inset lifts the body 4pt, got {flush} → {inset}"
+ );
+ }
+
+ /// No `bodyPr` at all keeps the §20.1.2.1.1 defaults — top anchoring under
+ /// a 45720 EMU top inset. This is the behaviour every shape had before
+ /// anchoring existed, so nothing that omits `anchor` moves.
+ #[test]
+ fn a_shape_without_body_properties_keeps_the_spec_defaults() {
+ let extent = PtSize::new(Pt::new(200.0), Pt::new(120.0));
+ let bare = shape_text_y(&wsp_with_text(None), extent);
+ let explicit = shape_text_y(
+ &wsp_with_text(Some(body_pr(Some(TextAnchoringType::Top), 45720))),
+ extent,
+ );
+ assert!(
+ (bare - explicit).abs() < 1e-3,
+ "an absent bodyPr matches the spec defaults spelled out, \
+ got {bare} vs {explicit}"
+ );
+ }
+
+ /// `@vertOverflow` defaults to `overflow` — and every `bodyPr` in the
+ /// corpus that names it says so explicitly — so a body taller than its box
+ /// is *not* clipped. It anchors to the top and overflows downward, which is
+ /// also what it did before anchoring existed: the change reaches only
+ /// bodies that fit. Centring an overflowing body would draw it above the
+ /// shape, over whatever sits there.
+ #[test]
+ fn an_overflowing_body_is_not_pushed_above_the_shape() {
+ // A 6pt-tall shape cannot hold a line of text at any font size.
+ let extent = PtSize::new(Pt::new(200.0), Pt::new(6.0));
+ let y = |anchor| shape_text_y(&wsp_with_text(Some(body_pr(Some(anchor), 50800))), extent);
+ let top = y(TextAnchoringType::Top);
+ for anchor in [TextAnchoringType::Center, TextAnchoringType::Bottom] {
+ assert!(
+ (y(anchor) - top).abs() < 1e-3,
+ "{anchor:?} on an overflowing body places as `t` does, got {} vs {top}",
+ y(anchor)
+ );
+ }
+ }
+
+ // ── MCE §M.1.2 branch selection ──────────────────────────────────────
+
+ use super::{find_anchor_images, find_anchor_shapes};
+ use crate::model::{Blip, BlipFill, BlipFillKind, NvPicProperties, Picture, RelId};
+
+ /// An anchored DrawingML *picture* — the other half of what an anchor can
+ /// hold, and the half `find_anchor_images` owns.
+ fn anchored_picture() -> Image {
+ let mut img = anchored_wps_image();
+ img.graphic = Some(GraphicContent::Picture(Picture {
+ nv_pic_pr: NvPicProperties {
+ cnv_pr: DocProperties {
+ id: 2,
+ name: "picture".into(),
+ description: None,
+ hidden: None,
+ title: None,
+ },
+ cnv_pic_pr: None,
+ },
+ blip_fill: BlipFill {
+ rotate_with_shape: None,
+ dpi: None,
+ blip: Some(Blip {
+ embed: Some(RelId::new("rId7")),
+ link: None,
+ compression: None,
+ }),
+ src_rect: None,
+ fill_kind: BlipFillKind::Unspecified,
+ },
+ shape_properties: None,
+ }));
+ img
+ }
+
+ /// `<mc:AlternateContent>` whose Choice holds `choice` and whose Fallback
+ /// holds `fallback`.
+ fn ac_of(choice: Vec<Inline>, fallback: Vec<Inline>) -> Inline {
+ Inline::AlternateContent(AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wpg],
+ content: choice,
+ }],
+ fallback: Some(fallback),
+ })
+ }
+
+ /// MCE §M.1.2 selects exactly one branch, so the two walkers — two halves
+ /// of one DrawingML extraction, split by graphic type — have to select the
+ /// same one. Here the Choice holds a picture and the Fallback a shape: ask
+ /// the image walker and the paragraph contains nothing, ask the shape
+ /// walker and it contains a shape from the *other* branch.
+ #[test]
+ fn both_anchor_walkers_read_the_same_alternate_content_branch() {
+ let content = vec![ac_of(
+ vec![Inline::Image(Box::new(anchored_picture()))],
+ vec![Inline::Image(Box::new(anchored_wps_image()))],
+ )];
+
+ let mut images = Vec::new();
+ find_anchor_images(&content, &mut images);
+ let mut shapes = Vec::new();
+ find_anchor_shapes(&content, &mut shapes);
+
+ assert_eq!(images.len(), 1, "the Choice's picture is live");
+ assert_eq!(
+ shapes.len(),
+ 0,
+ "the Fallback's shape is not — the Choice was selected"
+ );
+ }
+
+ /// The dominant shape of the element in the wild: a DrawingML Choice and a
+ /// VML Fallback. The Choice's picture must render; today the image walker
+ /// only ever looks in the Fallback, and the VML walkers skip
+ /// `AlternateContent` outright, so the picture reaches neither and the
+ /// anchor draws nothing at all.
+ #[test]
+ fn an_anchored_picture_in_a_choice_is_found() {
+ let content = vec![ac_of(
+ vec![Inline::Image(Box::new(anchored_picture()))],
+ vec![Inline::InstrText(String::new())],
+ )];
+
+ let mut images = Vec::new();
+ find_anchor_images(&content, &mut images);
+ assert_eq!(images.len(), 1, "the Choice's anchored picture is rendered");
+ }
+
+ /// With no renderable Choice the Fallback is live, for both walkers. This
+ /// is the branch the image walker used to take unconditionally, and it has
+ /// to keep working — a legacy VML-only anchor has nowhere else to come
+ /// from.
+ #[test]
+ fn an_unrenderable_choice_hands_the_document_to_the_fallback() {
+ let content = vec![ac_of(
+ vec![Inline::InstrText(String::new())],
+ vec![Inline::Image(Box::new(anchored_picture()))],
+ )];
+
+ let mut images = Vec::new();
+ find_anchor_images(&content, &mut images);
+ assert_eq!(images.len(), 1, "the Fallback's picture is live");
+ }
+
+ /// Regression guard for the case the shape walker already handled: a wps
+ /// Choice wins and its VML Fallback stays inert, so the same rectangle is
+ /// not drawn twice.
+ #[test]
+ fn a_wps_choice_still_suppresses_its_vml_fallback() {
+ let content = vec![ac_of(
+ vec![Inline::Image(Box::new(anchored_wps_image()))],
+ vec![Inline::Image(Box::new(anchored_picture()))],
+ )];
+
+ let mut images = Vec::new();
+ find_anchor_images(&content, &mut images);
+ let mut shapes = Vec::new();
+ find_anchor_shapes(&content, &mut shapes);
+
+ assert_eq!(shapes.len(), 1, "the Choice's shape renders");
+ assert_eq!(images.len(), 0, "the Fallback's picture does not");
+ }
+
+ // ── §20.4.3.4 horizontal anchor resolution ───────────────────────────
+ //
+ // The default page is US Letter with 1in margins: 612 x 792pt, text area
+ // 72..540. Every expectation below is written against those numbers.
+
+ use super::resolve_anchor_x;
+
+ /// One inch in EMU — the unit `wp:posOffset` is expressed in.
+ const INCH: i64 = 914400;
+
+ fn anchor_with_h(horizontal_position: AnchorPosition) -> AnchorProperties {
+ let ImagePlacement::Anchor(mut a) = anchored_wps_image().placement else {
+ unreachable!("fixture is anchored")
+ };
+ a.horizontal_position = horizontal_position;
+ a
+ }
+
+ fn h_offset(relative_from: AnchorRelativeFrom, offset: i64) -> AnchorProperties {
+ anchor_with_h(AnchorPosition::Offset {
+ relative_from,
+ offset: Dimension::new(offset),
+ })
+ }
+
+ fn h_align(relative_from: AnchorRelativeFrom, alignment: AnchorAlignment) -> AnchorProperties {
+ anchor_with_h(AnchorPosition::Align {
+ relative_from,
+ alignment,
+ })
+ }
+
+ /// `resolve_anchor_x` for a 100pt-wide object on a page of `parity`.
+ fn x_on(anchor: &AnchorProperties, frame: AnchorFrame, parity: PageParity) -> f32 {
+ resolve_anchor_x(anchor, Pt::new(100.0), &default_state(), frame)
+ .resolve(parity)
+ .raw()
+ }
+
+ /// The odd-page reading — which is *the* reading for every anchor that is
+ /// not `inside`/`outside`.
+ fn x_of(anchor: &AnchorProperties, frame: AnchorFrame) -> f32 {
+ x_on(anchor, frame, PageParity::Odd)
+ }
+
+ fn assert_x(got: f32, expected: f32, what: &str) {
+ assert!(
+ (got - expected).abs() < 1e-3,
+ "{what}: expected {expected}, got {got}"
+ );
+ }
+
+ /// §20.4.2.12: a `page`-relative offset is a page coordinate, so in the
+ /// page frame it passes through untouched.
+ #[test]
+ fn page_frame_page_relative_offset_is_a_page_coordinate() {
+ assert_x(
+ x_of(&h_offset(AnchorRelativeFrom::Page, INCH), AnchorFrame::Page),
+ 72.0,
+ "1in from the page's left edge",
+ );
+ }
+
+ /// A `margin`-relative offset is measured from the text area's left edge.
+ #[test]
+ fn page_frame_margin_relative_offset_starts_at_the_margin() {
+ assert_x(
+ x_of(
+ &h_offset(AnchorRelativeFrom::Margin, INCH),
+ AnchorFrame::Page,
+ ),
+ 144.0,
+ "1in past the 1in left margin",
+ );
+ }
+
+ /// In `Stack` the caller adds the body's left margin back, so a page
+ /// coordinate has to be pre-compensated or the round-trip double-counts.
+ #[test]
+ fn stack_frame_page_relative_offset_backs_out_the_left_margin() {
+ assert_x(
+ x_of(
+ &h_offset(AnchorRelativeFrom::Page, INCH),
+ AnchorFrame::Stack,
+ ),
+ 0.0,
+ "72pt page coordinate minus the 72pt margin the caller re-adds",
+ );
+ }
+
+ /// A margin-relative offset needs no compensation: the frame origin
+ /// already *is* the left margin.
+ #[test]
+ fn stack_frame_margin_relative_offset_is_frame_relative() {
+ assert_x(
+ x_of(
+ &h_offset(AnchorRelativeFrom::Margin, INCH),
+ AnchorFrame::Stack,
+ ),
+ 72.0,
+ "1in from the frame origin",
+ );
+ }
+
+ /// §20.4.3.1: `left`/`center`/`right` place the object inside the region
+ /// named by `relativeFrom` — here the 72..540 text area.
+ #[test]
+ fn page_frame_align_resolves_against_the_text_area() {
+ for (alignment, expected) in [
+ (AnchorAlignment::Left, 72.0),
+ (AnchorAlignment::Center, 72.0 + (468.0 - 100.0) * 0.5),
+ (AnchorAlignment::Right, 72.0 + 468.0 - 100.0),
+ ] {
+ let got = x_of(
+ &h_align(AnchorRelativeFrom::Margin, alignment),
+ AnchorFrame::Page,
+ );
+ assert_x(
+ got,
+ expected,
+ &format!("{alignment:?} within the text area"),
+ );
+ }
+ }
+
+ /// `page` aligns against the whole sheet, margins included.
+ #[test]
+ fn page_frame_page_align_resolves_against_the_whole_page() {
+ for (alignment, expected) in [
+ (AnchorAlignment::Left, 0.0),
+ (AnchorAlignment::Center, (612.0 - 100.0) * 0.5),
+ (AnchorAlignment::Right, 612.0 - 100.0),
+ ] {
+ let got = x_of(
+ &h_align(AnchorRelativeFrom::Page, alignment),
+ AnchorFrame::Page,
+ );
+ assert_x(got, expected, &format!("{alignment:?} within the page"));
+ }
+ }
+
+ /// `Stack` has no container extent at extraction time, so a margin-relative
+ /// alignment has nothing to align *within* and collapses onto the frame
+ /// origin. `Right`/`Center` therefore run negative by the object's own
+ /// width. Pinned because every new region has to keep respecting it —
+ /// giving one of them a real extent here would shift header floats.
+ #[test]
+ fn stack_frame_align_collapses_to_the_frame_origin() {
+ for (alignment, expected) in [
+ (AnchorAlignment::Left, 0.0),
+ (AnchorAlignment::Center, -50.0),
+ (AnchorAlignment::Right, -100.0),
+ ] {
+ let got = x_of(
+ &h_align(AnchorRelativeFrom::Margin, alignment),
+ AnchorFrame::Stack,
+ );
+ assert_x(got, expected, &format!("{alignment:?} in a stack frame"));
+ }
+ }
+
+ /// §20.4.3.4 `leftMargin` — the 0..72 strip, *not* the text area beside
+ /// it. A `left`-aligned object in it sits flush with the sheet's edge, and
+ /// an offset counts from that edge.
+ #[test]
+ fn left_margin_is_the_strip_from_the_page_edge_to_the_margin() {
+ let from = AnchorRelativeFrom::LeftMargin;
+ assert_x(
+ x_of(&h_offset(from, INCH), AnchorFrame::Page),
+ 72.0,
+ "1in from the sheet's left edge",
+ );
+ assert_x(
+ x_of(&h_align(from, AnchorAlignment::Left), AnchorFrame::Page),
+ 0.0,
+ "flush with the sheet's left edge",
+ );
+ // A 100pt object is wider than the 72pt strip, so right-aligning it
+ // hangs it past the margin edge — which is what Word draws.
+ assert_x(
+ x_of(&h_align(from, AnchorAlignment::Right), AnchorFrame::Page),
+ -28.0,
+ "right edge on the margin edge",
+ );
+ }
+
+ /// §20.4.3.4 `rightMargin` — the mirror strip, 540..612.
+ #[test]
+ fn right_margin_is_the_strip_from_the_margin_to_the_page_edge() {
+ let from = AnchorRelativeFrom::RightMargin;
+ assert_x(
+ x_of(&h_offset(from, INCH), AnchorFrame::Page),
+ 612.0,
+ "1in past the right margin edge, i.e. the sheet's right edge",
+ );
+ assert_x(
+ x_of(&h_align(from, AnchorAlignment::Left), AnchorFrame::Page),
+ 540.0,
+ "flush with the right margin edge",
+ );
+ }
+
+ /// §20.4.3.4 `insideMargin`/`outsideMargin` are page-parity dependent, and
+ /// the page a float lands on is not known at extraction time. The odd-page
+ /// reading — inside = left, outside = right — is the Tier-0 collapse, and
+ /// it is exact for the single-sided documents that are nearly all of them.
+ #[test]
+ fn parity_margins_take_their_odd_page_reading() {
+ let inside = x_of(
+ &h_align(AnchorRelativeFrom::InsideMargin, AnchorAlignment::Left),
+ AnchorFrame::Page,
+ );
+ let outside = x_of(
+ &h_align(AnchorRelativeFrom::OutsideMargin, AnchorAlignment::Left),
+ AnchorFrame::Page,
+ );
+ assert_x(inside, 0.0, "inside = the left margin on an odd page");
+ assert_x(outside, 540.0, "outside = the right margin on an odd page");
+ }
+
+ /// The deferred pair is a genuine mirror — whichever page the object lands
+ /// on, `inside` and `outside` name opposite strips. Worth pinning because
+ /// `assume_odd_page` reads only one half of it; the other half exists for
+ /// the parity resolution that replaces it, and nothing else would catch it
+ /// being built wrong.
+ #[test]
+ fn inside_and_outside_margins_mirror_each_other() {
+ use super::{FrameGeometry, HorizontalRegion::Mirrored, horizontal_region};
+
+ let geom = FrameGeometry::new(&default_state().page_config, AnchorFrame::Page);
+ let (
+ Mirrored {
+ odd: inside_odd,
+ even: inside_even,
+ },
+ Mirrored {
+ odd: outside_odd,
+ even: outside_even,
+ },
+ ) = (
+ horizontal_region(AnchorRelativeFrom::InsideMargin, &geom),
+ horizontal_region(AnchorRelativeFrom::OutsideMargin, &geom),
+ )
+ else {
+ panic!("both references are parity-dependent");
+ };
+
+ assert_eq!(inside_odd, outside_even, "inside on odd = outside on even");
+ assert_eq!(inside_even, outside_odd, "inside on even = outside on odd");
+ assert_ne!(inside_odd, inside_even, "the two pages differ");
+ }
+
+ /// §20.4.3.1: `inside` is the binding edge — left on an odd (recto) page,
+ /// right on an even one — and `outside` is the trimmed edge opposite it.
+ /// Both readings are carried, because the page is not known here.
+ #[test]
+ fn inside_and_outside_alignments_mirror_on_even_pages() {
+ let margin = AnchorRelativeFrom::Margin;
+ // Text area 72..540; a 100pt object is flush left at 72, flush right
+ // at 440.
+ for (alignment, odd, even) in [
+ (AnchorAlignment::Inside, 72.0, 440.0),
+ (AnchorAlignment::Outside, 440.0, 72.0),
+ ] {
+ let anchor = h_align(margin, alignment);
+ assert_x(
+ x_on(&anchor, AnchorFrame::Page, PageParity::Odd),
+ odd,
+ &format!("{alignment:?} on an odd page"),
+ );
+ assert_x(
+ x_on(&anchor, AnchorFrame::Page, PageParity::Even),
+ even,
+ &format!("{alignment:?} on an even page"),
+ );
+ }
+ }
+
+ /// The two parity channels compose: an `inside` alignment *within* an
+ /// `insideMargin` region mirrors through both at once, and must not
+ /// double-mirror back to the odd-page answer.
+ #[test]
+ fn a_mirrored_alignment_inside_a_mirrored_region_mirrors_once() {
+ let anchor = h_align(AnchorRelativeFrom::InsideMargin, AnchorAlignment::Inside);
+ // Odd: insideMargin = the 0..72 strip, inside-aligned = its left edge.
+ assert_x(
+ x_on(&anchor, AnchorFrame::Page, PageParity::Odd),
+ 0.0,
+ "odd",
+ );
+ // Even: insideMargin = the 540..612 strip, inside-aligned = its
+ // *right* edge, less the object's width.
+ assert_x(
+ x_on(&anchor, AnchorFrame::Page, PageParity::Even),
+ 540.0 + 72.0 - 100.0,
+ "even",
+ );
+ }
+
+ /// An anchor that uses neither parity channel collapses to `Absolute`, so
+ /// a single-sided document carries no deferral at all and every downstream
+ /// `resolve` is a no-op. This is what keeps the ADT from costing anything
+ /// on the documents that are nearly all of them.
+ #[test]
+ fn an_unmirrored_anchor_carries_no_deferral() {
+ for alignment in [
+ AnchorAlignment::Left,
+ AnchorAlignment::Center,
+ AnchorAlignment::Right,
+ ] {
+ let x = resolve_anchor_x(
+ &h_align(AnchorRelativeFrom::Margin, alignment),
+ Pt::new(100.0),
+ &default_state(),
+ AnchorFrame::Page,
+ );
+ assert!(
+ matches!(x, FloatingImageX::Absolute(_)),
+ "{alignment:?} is parity-independent, got {x:?}"
+ );
+ }
+ let mirrored = resolve_anchor_x(
+ &h_align(AnchorRelativeFrom::Margin, AnchorAlignment::Inside),
+ Pt::new(100.0),
+ &default_state(),
+ AnchorFrame::Page,
+ );
+ assert!(
+ matches!(mirrored, FloatingImageX::PageParity { .. }),
+ "inside is parity-dependent, got {mirrored:?}"
+ );
+ }
+
+ /// §20.4.3.4 `character` is the anchor's position in the text run, which
+ /// float extraction runs before. It falls back to the text area — the
+ /// behaviour it had while sharing a catch-all with `margin`, now reached by
+ /// a named arm that logs.
+ #[test]
+ fn character_relative_falls_back_to_the_text_area() {
+ let from = AnchorRelativeFrom::Character;
+ assert_x(
+ x_of(&h_offset(from, INCH), AnchorFrame::Page),
+ 144.0,
+ "offset",
+ );
+ assert_x(
+ x_of(&h_align(from, AnchorAlignment::Left), AnchorFrame::Page),
+ 72.0,
+ "align",
+ );
+ }
+
+ /// The margin strips are page-derived, so a header float can reach them:
+ /// `Stack` expresses them relative to the frame origin, and the caller's
+ /// `+ margins.left` shift lands them on the page coordinate they name.
+ #[test]
+ fn stack_frame_margin_strips_survive_the_round_trip_into_page_space() {
+ const BODY_MARGIN: f32 = 72.0;
+ for (from, page_x) in [
+ (AnchorRelativeFrom::LeftMargin, 0.0),
+ (AnchorRelativeFrom::RightMargin, 540.0),
+ ] {
+ let got = x_of(&h_align(from, AnchorAlignment::Left), AnchorFrame::Stack);
+ assert_x(
+ got + BODY_MARGIN,
+ page_x,
+ &format!("{from:?} after the caller's shift"),
+ );
+ }
+ }
+
+ // ── §14.1.2.5 VML fill resolution ────────────────────────────────────
+
+ use super::{build_vml_rect_shape, model, resolve_vml_solid_fill};
+ use crate::model::{VmlColor, VmlFill, VmlFillType, VmlLength, VmlLengthUnit, VmlNamedColor};
+ use crate::render::layout::draw_command::ResolvedFill;
+
+ fn solid_rgb(fill: &ResolvedFill) -> (f32, f32, f32) {
+ let ResolvedFill::Solid(c) = fill else {
+ panic!("expected a solid fill, got {fill:?}");
+ };
+ (c.r, c.g, c.b)
+ }
+
+ /// §14.1.2.5: the `<v:fill>` child element wins over `@fillcolor`.
+ #[test]
+ fn vml_fill_child_overrides_the_fillcolor_attribute() {
+ let common = model::VmlCommonAttrs {
+ fill_color: Some(VmlColor::Rgb(255, 0, 0)),
+ fill: Some(VmlFill {
+ fill_type: VmlFillType::Solid,
+ color: Some(VmlColor::Rgb(0, 255, 0)),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ assert_eq!(solid_rgb(&resolve_vml_solid_fill(&common)), (0.0, 1.0, 0.0));
+ }
+
+ /// With no child element the attribute is the whole story.
+ #[test]
+ fn vml_fillcolor_attribute_applies_without_a_fill_child() {
+ let common = model::VmlCommonAttrs {
+ fill_color: Some(VmlColor::Rgb(0, 0, 255)),
+ ..Default::default()
+ };
+ assert_eq!(solid_rgb(&resolve_vml_solid_fill(&common)), (0.0, 0.0, 1.0));
+ }
+
+ /// A `<v:fill type="solid"/>` carrying no `@color` is not an override —
+ /// it falls through to the attribute rather than blanking the shape.
+ #[test]
+ fn vml_solid_fill_without_a_color_falls_back_to_the_attribute() {
+ let common = model::VmlCommonAttrs {
+ fill_color: Some(VmlColor::Rgb(255, 0, 0)),
+ fill: Some(VmlFill {
+ fill_type: VmlFillType::Solid,
+ color: None,
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ assert_eq!(solid_rgb(&resolve_vml_solid_fill(&common)), (1.0, 0.0, 0.0));
+ }
+
+ /// A non-solid fill degrades to no-fill and — deliberately — does *not*
+ /// fall back to `@fillcolor`: the attribute is the gradient's own start
+ /// colour, so painting the shape flat in it would be worse than leaving
+ /// the outline and text to carry the shape.
+ #[test]
+ fn vml_non_solid_fills_degrade_to_no_fill_without_falling_back() {
+ for fill_type in [
+ VmlFillType::Gradient,
+ VmlFillType::GradientRadial,
+ VmlFillType::Tile,
+ VmlFillType::Frame,
+ VmlFillType::Pattern,
+ ] {
+ let common = model::VmlCommonAttrs {
+ fill_color: Some(VmlColor::Rgb(255, 0, 0)),
+ fill: Some(VmlFill {
+ fill_type,
+ color: Some(VmlColor::Rgb(0, 255, 0)),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ assert!(
+ matches!(resolve_vml_solid_fill(&common), ResolvedFill::None),
+ "{fill_type:?} must not paint",
+ );
+ }
+ }
+
+ /// Named colours are parsed but not yet resolved to RGB, so they leave the
+ /// shape unfilled rather than guessing.
+ #[test]
+ fn vml_named_colors_are_not_resolved_yet() {
+ let common = model::VmlCommonAttrs {
+ fill_color: Some(VmlColor::Named(VmlNamedColor::Black)),
+ ..Default::default()
+ };
+ assert!(matches!(
+ resolve_vml_solid_fill(&common),
+ ResolvedFill::None
+ ));
+ }
+
+ // ── §14.1.2.19 VML rect construction ─────────────────────────────────
+
+ fn vml_pt(value: f64) -> VmlLength {
+ VmlLength {
+ value,
+ unit: VmlLengthUnit::Pt,
+ }
+ }
+
+ /// A `position:absolute` rect at `(x, y)` sized `w x h`, all in points.
+ fn vml_rect(x: f64, y: f64, w: f64, h: f64) -> model::VmlCommonAttrs {
+ model::VmlCommonAttrs {
+ style: model::VmlStyle {
+ position: Some(crate::model::CssPosition::Absolute),
+ margin_left: Some(vml_pt(x)),
+ margin_top: Some(vml_pt(y)),
+ width: Some(vml_pt(w)),
+ height: Some(vml_pt(h)),
+ ..Default::default()
+ },
+ ..Default::default()
+ }
+ }
+
+ /// The path is a closed rectangle in *shape-local* points — the painter
+ /// applies `(x, y)`, so baking the position into the path would double it.
+ #[test]
+ fn vml_rect_is_a_closed_rectangle_in_shape_local_points() {
+ use crate::render::resolve::shape_geometry::PathVerb;
+
+ let shape = build_vml_rect_shape(
+ &vml_rect(30.0, 40.0, 200.0, 10.0),
+ &default_state(),
+ AnchorFrame::Page,
+ )
+ .expect("a positioned, sized rect builds");
+
+ assert_x(
+ shape.x.resolve(PageParity::Odd).raw(),
+ 30.0,
+ "page-frame x is the style's margin-left",
+ );
+ let FloatingImageY::RelativeToParagraph(y) = shape.y else {
+ panic!("VML rects anchor to the host paragraph");
+ };
+ assert_x(y.raw(), 40.0, "y is the style's margin-top");
+ assert_x(shape.size.width.raw(), 200.0, "width");
+ assert_x(shape.size.height.raw(), 10.0, "height");
+
+ let [sub] = &shape.paths[..] else {
+ panic!("one sub-path, got {}", shape.paths.len());
+ };
+ assert_eq!(sub.verbs.len(), 5, "4 corners + close");
+ assert!(matches!(sub.verbs[0], PathVerb::MoveTo(o) if o.x == Pt::ZERO && o.y == Pt::ZERO));
+ assert!(matches!(sub.verbs[4], PathVerb::Close));
+ }
+
+ /// Same round-trip as the DrawingML path: the stack emitter shifts by the
+ /// body's left margin, so the page-relative x is pre-compensated.
+ #[test]
+ fn stack_frame_vml_rect_backs_out_the_left_margin() {
+ let shape = build_vml_rect_shape(
+ &vml_rect(80.0, 0.0, 10.0, 10.0),
+ &default_state(),
+ AnchorFrame::Stack,
+ )
+ .expect("a positioned, sized rect builds");
+ assert_eq!(
+ shape.x,
+ FloatingImageX::Absolute(Pt::new(8.0)),
+ "80pt page x minus the 72pt margin"
+ );
+ }
+
+ /// Without `position:absolute` there is no position to honour, and a rect
+ /// with no extent cannot render — both drop out rather than emitting a
+ /// degenerate shape at the origin.
+ #[test]
+ fn vml_rect_needs_absolute_positioning_and_a_positive_extent() {
+ let mut unpositioned = vml_rect(30.0, 40.0, 200.0, 10.0);
+ unpositioned.style.position = None;
+ assert!(
+ build_vml_rect_shape(&unpositioned, &default_state(), AnchorFrame::Page).is_none(),
+ "no position:absolute"
+ );
+
+ for (w, h) in [(0.0, 10.0), (200.0, 0.0), (-5.0, 10.0)] {
+ assert!(
+ build_vml_rect_shape(
+ &vml_rect(30.0, 40.0, w, h),
+ &default_state(),
+ AnchorFrame::Page
+ )
+ .is_none(),
+ "{w} x {h} has no drawable area"
+ );
+ }
+ }
+
+ /// `@stroked` reaches the sub-path so the painter knows whether to outline.
+ #[test]
+ fn vml_rect_carries_the_stroked_flag_onto_its_path() {
+ for stroked in [None, Some(false), Some(true)] {
+ let mut common = vml_rect(0.0, 0.0, 10.0, 10.0);
+ common.stroked = stroked;
+ let shape =
+ build_vml_rect_shape(&common, &default_state(), AnchorFrame::Page).expect("builds");
+ assert_eq!(
+ shape.paths[0].stroked,
+ stroked == Some(true),
+ "stroked={stroked:?}"
+ );
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/build/list_label.rs b/crates/liteparse-docx/src/render/layout/build/list_label.rs
new file mode 100644
index 0000000..f5127a5
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/build/list_label.rs
@@ -0,0 +1,1252 @@
+//! List label injection — prepend bullet/number labels to paragraph fragments.
+//!
+//! §17.9.22: when a paragraph carries a numbering reference, resolve the label
+//! text (or picture bullet) and inject it as the first fragment, followed by a
+//! tab that advances to the body text indent position.
+
+use std::rc::Rc;
+
+use crate::model::{self, ParagraphProperties};
+use crate::render::dimension::Pt;
+use crate::render::layout::fragment::Fragment;
+
+use super::convert::{pic_bullet_size, remap_legacy_font_chars, resolve_paragraph_defaults};
+use super::{BuildContext, BuildState};
+
+/// Inject list label fragments into a paragraph if it has a numbering reference.
+///
+/// Updates `fragments` (prepends label + tab), `merged_props` (overrides indentation
+/// from the numbering level), and `state.list_counters` (increments/resets counters).
+pub(super) fn inject_list_label(
+ para: &model::Paragraph,
+ fragments: &mut Vec<Fragment>,
+ merged_props: &mut ParagraphProperties,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) {
+ let num_ref = match merged_props.numbering {
+ Some(ref nr) => nr,
+ None => return,
+ };
+
+ let num_id = model::NumId::new(num_ref.num_id);
+ let level = num_ref.level;
+
+ let levels = match ctx.resolved.numbering.get(&num_id) {
+ Some(levels) => levels,
+ None => return,
+ };
+
+ // Update counters: increment this level, reset deeper levels.
+ //
+ // The map holds the *current* (last-emitted) value, which is what
+ // `format_list_label` reads. §17.9.28 permits `w:start="0"` (and
+ // §17.9.27 `w:startOverride="0"`), so the first item must seed the
+ // counter with `start` directly — seeding `start - 1` and adding one
+ // underflows `u32` at zero, panicking debug builds and silently
+ // wrapping in release.
+ {
+ use std::collections::hash_map::Entry;
+ let counters = &mut state.list_counters;
+ match counters.entry((num_id, level)) {
+ Entry::Vacant(slot) => {
+ slot.insert(levels.get(level as usize).map(|l| l.start).unwrap_or(1));
+ }
+ Entry::Occupied(mut slot) => {
+ let next = slot.get().saturating_add(1);
+ slot.insert(next);
+ }
+ }
+ // Reset deeper levels.
+ let max_level = levels.len() as u8;
+ for deeper in (level + 1)..max_level {
+ counters.remove(&(num_id, deeper));
+ }
+ }
+
+ let level_def = levels.get(level as usize);
+
+ // §17.9.10: check for picture bullet before text label.
+ let pic_bullet_injected = level_def
+ .and_then(|l| l.lvl_pic_bullet_id)
+ .and_then(|pic_id| ctx.resolved.pic_bullets.get(&pic_id))
+ .and_then(|bullet| {
+ let rel_id = bullet
+ .pict
+ .as_ref()?
+ .shapes()
+ .next()?
+ .common
+ .image_data
+ .as_ref()?
+ .rel_id
+ .as_ref()?;
+ let image_bytes = ctx.media().get(rel_id)?;
+ // Size from VML shape style (width/height), default 9pt.
+ let size = pic_bullet_size(bullet);
+ let label_frag = Fragment::Image {
+ size,
+ rel_id: rel_id.as_str().to_string(),
+ image_data: Some(image_bytes.clone()),
+ src_rect: None,
+ };
+ Some((label_frag, size.height))
+ });
+
+ if let Some((label_frag, label_height)) = pic_bullet_injected {
+ let hanging = extract_hanging(level_def);
+ // §17.9.29: `Nothing` drops the separator entirely. `Tab` and `Space`
+ // both advance via a tab here — a picture bullet has no text font to emit
+ // a literal space with, and image-bullet + space is vanishingly rare.
+ let drop_separator =
+ level_def.map(|l| l.suffix) == Some(crate::model::LevelSuffix::Nothing);
+ if !drop_separator {
+ // §17.3.1.38: a leader on this separator is drawn in the
+ // formatting in effect at the tab. A picture bullet has no text
+ // run of its own, so the paragraph defaults *are* that formatting.
+ let (fam, size, color, _, _) =
+ resolve_paragraph_defaults(para, ctx.resolved, false, None, None);
+ let sep_font = crate::render::layout::fragment::font_props_from_run(
+ &model::RunProperties::default(),
+ &fam,
+ size,
+ state.shape_auto_fit,
+ );
+ let tab_frag = Fragment::Tab {
+ line_height: label_height,
+ font: Rc::new(sep_font),
+ color,
+ fitting_width: Some(hanging),
+ };
+ fragments.insert(0, tab_frag);
+ }
+ fragments.insert(0, label_frag);
+
+ if !drop_separator {
+ if let Some(lvl_left) = level_def
+ .and_then(|l| l.indentation.as_ref())
+ .and_then(|ind| ind.start)
+ {
+ merged_props.tabs.insert(
+ 0,
+ crate::model::TabStop {
+ position: lvl_left,
+ alignment: crate::model::TabAlignment::Left,
+ leader: crate::model::TabLeader::None,
+ },
+ );
+ }
+ }
+ } else {
+ inject_text_label(
+ para,
+ fragments,
+ merged_props,
+ ctx,
+ &state.list_counters,
+ levels,
+ level,
+ level_def,
+ state.shape_auto_fit,
+ );
+ }
+
+ // §17.9.23: numbering level pPr overrides the paragraph style.
+ // Only the paragraph's direct ind overrides the numbering level.
+ if let Some(lvl_ind) = levels
+ .get(level as usize)
+ .and_then(|l| l.indentation.as_ref())
+ {
+ let mut ind = *lvl_ind;
+ if let Some(direct) = para.properties.indentation {
+ if let Some(start) = direct.start {
+ ind.start = Some(start);
+ }
+ if let Some(end) = direct.end {
+ ind.end = Some(end);
+ }
+ if let Some(first_line) = direct.first_line {
+ ind.first_line = Some(first_line);
+ }
+ }
+ merged_props.indentation = Some(ind);
+ }
+}
+
+/// Inject a text label (non-picture bullet) into the paragraph fragments.
+#[allow(clippy::too_many_arguments)]
+fn inject_text_label(
+ para: &model::Paragraph,
+ fragments: &mut Vec<Fragment>,
+ merged_props: &mut ParagraphProperties,
+ ctx: &BuildContext,
+ counters: &std::collections::HashMap<(model::NumId, u8), u32>,
+ levels: &[crate::render::resolve::numbering::ResolvedNumberingLevel],
+ level: u8,
+ level_def: Option<&crate::render::resolve::numbering::ResolvedNumberingLevel>,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+) {
+ let num_id = model::NumId::new(merged_props.numbering.as_ref().unwrap().num_id);
+
+ let (default_family, default_size, default_color, _, paragraph_style_run) =
+ resolve_paragraph_defaults(para, ctx.resolved, false, None, None);
+
+ // §17.9.23 / §17.3.1.29: assemble the label's character-property
+ // cascade. Order matters — level rPr beats paragraph-mark rPr beats
+ // paragraph-style run defaults. Document defaults arrive below via
+ // `default_family`/`default_size` scalars consumed by
+ // `font_props_from_run`.
+ let cascade = ListLabelRunPropertyCascade {
+ level: level_def.and_then(|l| l.run_properties.as_ref()),
+ paragraph_mark: para.mark_run_properties.as_ref(),
+ paragraph_style: Some(&paragraph_style_run),
+ };
+
+ // §17.3.2.20: the label's language, read from the label's *own* cascade
+ // rather than the paragraph's — a `<w:lvl><w:rPr><w:lang>` is as much a
+ // property of the level as its font is, and §17.9.27's three text formats
+ // are the only thing that consults it. Document defaults close the cascade,
+ // the layer `default_family`/`default_size` carry for the other fields.
+ let locale = crate::render::resolve::locale::Locale::from_cascade(
+ cascade
+ .iter()
+ .chain(std::iter::once(&ctx.resolved.doc_defaults_run)),
+ );
+
+ let label_text = match crate::render::resolve::numbering::format_list_label(
+ levels, level, counters, num_id, locale,
+ ) {
+ Some(t) => t,
+ None => return,
+ };
+
+ // §17.3.2.6: color follows the same cascade as the font fields,
+ // resolved as a separate scalar because it isn't part of
+ // `FontProps`.
+ let label_color = cascade
+ .pick(|rp| rp.color)
+ .map(|c| {
+ crate::render::resolve::color::resolve_color(
+ c,
+ crate::render::resolve::color::ColorContext::Text,
+ )
+ })
+ .unwrap_or(default_color);
+
+ // Legacy Symbol/Wingdings remapping needs the cascade-resolved
+ // family before deciding whether to remap PUA codepoints back to
+ // their bullet glyphs.
+ let cascade_family = cascade
+ .iter()
+ .find_map(|rp| crate::render::resolve::fonts::effective_font(&rp.fonts))
+ .unwrap_or("");
+ let (label_text, label_family) =
+ remap_legacy_font_chars(&label_text, cascade_family, &default_family);
+
+ // Build the label font through the canonical path so every
+ // label-relevant field (underline, char_spacing, text_scale, etc.)
+ // flows from cascade.resolve() into `font_props_from_run`. After
+ // remapping, override the family if it changed.
+ let mut label_font = build_label_font_props(&cascade, &default_family, default_size, auto_fit);
+ if label_family != *label_font.family {
+ label_font.family = Rc::from(label_family.as_str());
+ }
+ // §17.3.2.40: populate underline metrics from font metrics now that
+ // the bool is settled — `populate_underline_metrics` (used by
+ // `build_fragments`) ran before label injection, so this fragment
+ // must populate its own metrics.
+ populate_label_underline_metrics(&mut label_font, ctx.measurer);
+
+ let (w, m) = ctx.measurer.measure(&label_text, &label_font);
+ let h = m.height();
+
+ let hanging = extract_hanging(level_def);
+ // §17.9.7: lvlJc controls label justification within the hanging indent area.
+ let jc = level_def.and_then(|l| l.justification);
+ let text_offset = match jc {
+ Some(crate::model::Alignment::End) => -w,
+ Some(crate::model::Alignment::Center) => w * -0.5,
+ _ => Pt::ZERO,
+ };
+ let label_width = w;
+ let label_frag = Fragment::Text {
+ text: Rc::from(label_text.as_str()),
+ font: Rc::new(label_font.clone()),
+ color: label_color,
+ shading: None,
+ border: None,
+ width: label_width,
+ trimmed_width: label_width,
+ metrics: m,
+ hyperlink_url: None,
+ baseline_offset: Pt::ZERO,
+ text_offset,
+ is_footnote_ref: false,
+ };
+ // §17.9.29: the separator between the label and the body text depends on the
+ // level's `suff`. Tab (default) advances to the body-text indent via a tab
+ // stop; Space emits a single space; Nothing puts the text flush against the
+ // label.
+ use crate::model::LevelSuffix;
+ match level_def.map(|l| l.suffix).unwrap_or_default() {
+ LevelSuffix::Tab => {
+ let tab_fitting = (hanging - label_width).max(Pt::ZERO);
+ fragments.insert(
+ 0,
+ Fragment::Tab {
+ line_height: h,
+ // §17.3.1.38: the label's own formatting is what a leader
+ // on this separator is drawn in.
+ font: Rc::new(label_font.clone()),
+ color: label_color,
+ fitting_width: Some(tab_fitting),
+ },
+ );
+ fragments.insert(0, label_frag);
+
+ // Implicit tab stop at numLvl.left so the tab lands at body text.
+ if let Some(lvl_left) = level_def
+ .and_then(|l| l.indentation.as_ref())
+ .and_then(|ind| ind.start)
+ {
+ merged_props.tabs.insert(
+ 0,
+ crate::model::TabStop {
+ position: lvl_left,
+ alignment: crate::model::TabAlignment::Left,
+ leader: crate::model::TabLeader::None,
+ },
+ );
+ }
+ }
+ LevelSuffix::Space => {
+ let (sw, sm) = ctx.measurer.measure(" ", &label_font);
+ fragments.insert(
+ 0,
+ Fragment::Text {
+ text: Rc::from(" "),
+ font: Rc::new(label_font.clone()),
+ color: label_color,
+ shading: None,
+ border: None,
+ width: sw,
+ trimmed_width: sw,
+ metrics: sm,
+ hyperlink_url: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ },
+ );
+ fragments.insert(0, label_frag);
+ }
+ LevelSuffix::Nothing => {
+ fragments.insert(0, label_frag);
+ }
+ }
+}
+
+/// Extract the hanging indent from a numbering level definition.
+fn extract_hanging(
+ level_def: Option<&crate::render::resolve::numbering::ResolvedNumberingLevel>,
+) -> Pt {
+ level_def
+ .and_then(|l| l.indentation.as_ref())
+ .and_then(|ind| ind.first_line)
+ .map(|fl| match fl {
+ model::FirstLineIndent::Hanging(v) => Pt::from(v),
+ _ => Pt::ZERO,
+ })
+ .unwrap_or(Pt::ZERO)
+}
+
+/// §17.9.23 — derive a label's [`FontProps`] from the resolved
+/// character-property cascade. Delegates to [`font_props_from_run`]
+/// so every label-relevant field (bold, italic, underline,
+/// char_spacing, text_scale, font family, font size) takes the same
+/// code path as ordinary text-run formatting. The returned
+/// [`FontProps`] still has `underline_position`/`underline_thickness`
+/// at zero — those come from font metrics and require a measurer.
+/// Use [`populate_label_underline_metrics`] to fill them.
+pub(super) fn build_label_font_props(
+ cascade: &ListLabelRunPropertyCascade<'_>,
+ default_family: &str,
+ default_size: Pt,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+) -> crate::render::layout::fragment::FontProps {
+ let effective = cascade.resolve();
+ crate::render::layout::fragment::font_props_from_run(
+ &effective,
+ default_family,
+ default_size,
+ auto_fit,
+ )
+}
+
+/// Populate `underline_position` and `underline_thickness` on a
+/// label's [`FontProps`] from the measurer's font metrics. No-op when
+/// the label is not underlined. Idempotent.
+pub(super) fn populate_label_underline_metrics(
+ font: &mut crate::render::layout::fragment::FontProps,
+ measurer: &crate::render::layout::measurer::TextMeasurer,
+) {
+ if font.underline {
+ let (pos, thickness) = measurer.underline_metrics(font);
+ font.underline_position = pos;
+ font.underline_thickness = thickness;
+ }
+}
+
+/// §17.9.23 / §17.3.1.29 — character-property cascade for a list
+/// label's text. Sources are listed in priority order (highest first);
+/// each field of the resolved properties is the topmost `Some` value
+/// across `level → paragraph_mark → paragraph_style`.
+///
+/// The cascade is the spec-defined chain: a `<w:lvl><w:rPr>` overrides
+/// the paragraph-mark `<w:pPr><w:rPr>`, which in turn overrides the
+/// paragraph style's run defaults. Document defaults and theme
+/// fallbacks come in below as scalar `default_family`/`default_size`
+/// values supplied to `font_props_from_run`.
+pub(super) struct ListLabelRunPropertyCascade<'a> {
+ /// `<w:lvl><w:rPr>` — top of the cascade (§17.9.23).
+ pub level: Option<&'a model::RunProperties>,
+ /// `<w:pPr><w:rPr>` — formatting on the paragraph mark, applied
+ /// where the level layer doesn't set a given field (§17.3.1.29).
+ pub paragraph_mark: Option<&'a model::RunProperties>,
+ /// Paragraph-style run defaults — bottom of the cascade.
+ pub paragraph_style: Option<&'a model::RunProperties>,
+}
+
+impl<'a> ListLabelRunPropertyCascade<'a> {
+ /// Iterate cascade sources in priority order, skipping `None`
+ /// layers. Used by `pick` and by callers that need direct access
+ /// to the cascade for non-`Copy` fields like `FontSet`.
+ pub(super) fn iter(&self) -> impl Iterator<Item = &'a model::RunProperties> + '_ {
+ [self.level, self.paragraph_mark, self.paragraph_style]
+ .into_iter()
+ .flatten()
+ }
+
+ /// Return the first `Some` value of a given field across the
+ /// cascade, or `None` when no layer sets it. Restricted to `Copy`
+ /// fields so the lookup is allocation-free; use `iter()` for fields
+ /// that require cloning (e.g. `FontSet`).
+ pub(super) fn pick<T: Copy>(
+ &self,
+ get: impl Fn(&model::RunProperties) -> Option<T>,
+ ) -> Option<T> {
+ self.iter().find_map(get)
+ }
+
+ /// Materialize a single effective `RunProperties` whose label-
+ /// relevant fields (those consumed by `font_props_from_run` plus
+ /// `color`) are picked from the highest-priority cascade source
+ /// that sets each field. Fields no source sets are left at their
+ /// default (`None` / empty `FontSet`) so downstream code can apply
+ /// paragraph-level fallbacks.
+ pub(super) fn resolve(&self) -> model::RunProperties {
+ // `FontSet` is non-`Copy`. Pick from the first cascade source
+ // whose font is explicitly set (any slot resolves under
+ // `effective_font`); otherwise leave empty so downstream
+ // `font_props_from_run` falls back to `default_family`.
+ let fonts = self
+ .iter()
+ .find(|rp| crate::render::resolve::fonts::effective_font(&rp.fonts).is_some())
+ .map(|rp| rp.fonts.clone())
+ .unwrap_or_default();
+
+ model::RunProperties {
+ fonts,
+ font_size: self.pick(|rp| rp.font_size),
+ bold: self.pick(|rp| rp.bold),
+ italic: self.pick(|rp| rp.italic),
+ underline: self.pick(|rp| rp.underline),
+ color: self.pick(|rp| rp.color),
+ spacing: self.pick(|rp| rp.spacing),
+ text_scale: self.pick(|rp| rp.text_scale),
+ ..Default::default()
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::{Dimension, HalfPoints, Twips};
+ use crate::model::{FontSet, FontSlot, RunProperties, TextScale, UnderlineStyle};
+
+ // ── §17.9.22 label emission ──────────────────────────────────────────
+ //
+ // The 16 tests below this block all exercise the property cascade. These
+ // exercise the path that *uses* it: counter arithmetic, the §17.9.29
+ // separator switch, §17.9.7 justification, and the hanging indent.
+
+ use crate::model::{
+ Alignment, FirstLineIndent, Indentation, LevelSuffix, NumId, NumberFormat,
+ NumberingReference,
+ };
+ use crate::render::fonts::FontRegistry;
+ use crate::render::layout::measurer::TextMeasurer;
+ use crate::render::resolve::ResolvedDocument;
+ use crate::render::resolve::numbering::ResolvedNumberingLevel;
+ use std::collections::HashMap;
+
+ fn level(format: NumberFormat, level_text: &str) -> ResolvedNumberingLevel {
+ ResolvedNumberingLevel {
+ format,
+ level_text: level_text.into(),
+ start: 1,
+ run_properties: None,
+ indentation: None,
+ justification: None,
+ lvl_pic_bullet_id: None,
+ suffix: LevelSuffix::Tab,
+ is_legal: false,
+ }
+ }
+
+ /// A decimal level whose label is just its own counter.
+ fn decimal_level() -> ResolvedNumberingLevel {
+ level(NumberFormat::Decimal, "%1")
+ }
+
+ fn resolved_with(levels: Vec<ResolvedNumberingLevel>) -> ResolvedDocument {
+ let mut numbering = HashMap::new();
+ numbering.insert(NumId::new(7), levels);
+ ResolvedDocument {
+ sections: Vec::new(),
+ styles: HashMap::new(),
+ numbering,
+ font_families: Vec::new(),
+ media: HashMap::new(),
+ embedded_fonts: Vec::new(),
+ pic_bullets: HashMap::new(),
+ theme: None,
+ doc_defaults_paragraph: ParagraphProperties::default(),
+ doc_defaults_run: RunProperties::default(),
+ default_paragraph_style_id: None,
+ footnotes: HashMap::new(),
+ endnotes: HashMap::new(),
+ even_and_odd_headers: false,
+ default_tab_stop: Dimension::new(720),
+ }
+ }
+
+ fn numbered_para() -> model::Paragraph {
+ model::Paragraph {
+ style_id: None,
+ properties: ParagraphProperties::default(),
+ mark_run_properties: None,
+ content: Vec::new(),
+ rsids: model::ParagraphRevisionIds::default(),
+ }
+ }
+
+ fn props_at(level: u8) -> ParagraphProperties {
+ ParagraphProperties {
+ numbering: Some(NumberingReference { num_id: 7, level }),
+ ..Default::default()
+ }
+ }
+
+ /// Run `inject_list_label` over a live measurer, returning the fragments it
+ /// prepended and the properties it rewrote.
+ fn inject(
+ resolved: &ResolvedDocument,
+ state: &mut BuildState,
+ level: u8,
+ ) -> (Vec<Fragment>, ParagraphProperties) {
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved,
+ };
+ let mut fragments = Vec::new();
+ let mut props = props_at(level);
+ inject_list_label(&numbered_para(), &mut fragments, &mut props, &ctx, state);
+ (fragments, props)
+ }
+
+ fn label_text(fragments: &[Fragment]) -> String {
+ match fragments.first() {
+ Some(Fragment::Text { text, .. }) => text.to_string(),
+ other => panic!("expected a label fragment, got {other:?}"),
+ }
+ }
+
+ /// §17.9.22: the counter seeds at `start` on the first item and advances by
+ /// one thereafter. Seeding `start - 1` and adding one is the shape that
+ /// underflows on `w:start="0"`, so this pins the seed as well as the step.
+ #[test]
+ fn the_counter_seeds_at_start_then_increments() {
+ let resolved = resolved_with(vec![decimal_level()]);
+ let mut state = BuildState::default();
+ let labels: Vec<String> = (0..3)
+ .map(|_| label_text(&inject(&resolved, &mut state, 0).0))
+ .collect();
+ assert_eq!(labels, ["1", "2", "3"]);
+ }
+
+ /// §17.9.28 permits `w:start="0"`, which the seed must survive — it
+ /// underflows `u32` if the counter is seeded one below `start`.
+ #[test]
+ fn a_zero_start_does_not_underflow() {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ start: 0,
+ ..decimal_level()
+ }]);
+ let mut state = BuildState::default();
+ let labels: Vec<String> = (0..2)
+ .map(|_| label_text(&inject(&resolved, &mut state, 0).0))
+ .collect();
+ assert_eq!(labels, ["0", "1"]);
+ }
+
+ /// §17.9.22: an item at one level restarts every level *below* it, so a
+ /// nested list numbers `1 / 1 / 2 / 1` rather than carrying the sub-counter
+ /// across. Levels *above* are untouched.
+ #[test]
+ fn a_deeper_level_restarts_when_its_parent_advances() {
+ // `%N` names level N−1's counter, not "this level's" — so the level-1
+ // template has to be `%2` to show its own number. With `%1` the test
+ // reads level 0's counter and passes against a broken reset.
+ let resolved = resolved_with(vec![decimal_level(), level(NumberFormat::Decimal, "%2")]);
+ let mut state = BuildState::default();
+
+ // Evaluated in order, each call advancing `state` — the sequence is
+ // the assertion.
+ let seen = vec![
+ label_text(&inject(&resolved, &mut state, 0).0), // "1"
+ label_text(&inject(&resolved, &mut state, 1).0), // "1" — first sub-item
+ label_text(&inject(&resolved, &mut state, 1).0), // "2"
+ label_text(&inject(&resolved, &mut state, 0).0), // "2" — resets level 1
+ label_text(&inject(&resolved, &mut state, 1).0), // "1" again
+ ];
+
+ assert_eq!(seen, ["1", "1", "2", "2", "1"]);
+ }
+
+ /// §17.9.29: `Tab` (the default) puts a tab after the label, `Space` a
+ /// literal space, `Nothing` neither.
+ #[test]
+ fn the_suffix_switch_picks_the_separator() {
+ for (suffix, expect) in [
+ (LevelSuffix::Tab, "tab"),
+ (LevelSuffix::Space, "space"),
+ (LevelSuffix::Nothing, "none"),
+ ] {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ suffix,
+ ..decimal_level()
+ }]);
+ let (fragments, _) = inject(&resolved, &mut BuildState::default(), 0);
+ assert_eq!(label_text(&fragments), "1", "{suffix:?}");
+
+ let got = match fragments.get(1) {
+ None => "none",
+ Some(Fragment::Tab { .. }) => "tab",
+ Some(Fragment::Text { text, .. }) if &**text == " " => "space",
+ other => panic!("{suffix:?} emitted {other:?}"),
+ };
+ assert_eq!(got, expect, "{suffix:?}");
+ }
+ }
+
+ /// §17.9.29: only the `Tab` suffix installs the implicit tab stop at the
+ /// level's `start` indent — a `Space`/`Nothing` label has no tab to land.
+ #[test]
+ fn only_a_tab_suffix_installs_the_implicit_tab_stop() {
+ for (suffix, expect_stop) in [
+ (LevelSuffix::Tab, true),
+ (LevelSuffix::Space, false),
+ (LevelSuffix::Nothing, false),
+ ] {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ suffix,
+ indentation: Some(Indentation {
+ start: Some(Dimension::new(720)),
+ ..Default::default()
+ }),
+ ..decimal_level()
+ }]);
+ let (_, props) = inject(&resolved, &mut BuildState::default(), 0);
+ assert_eq!(
+ props.tabs.iter().any(|t| t.position == Dimension::new(720)),
+ expect_stop,
+ "{suffix:?}"
+ );
+ }
+ }
+
+ /// §17.9.7 `lvlJc`: the label is placed by shifting it within the hanging
+ /// indent area — `start` not at all, `end` by its whole width, `center` by
+ /// half. Expressed as a ratio so the host font's metrics cancel.
+ #[test]
+ fn lvl_jc_offsets_the_label_by_its_own_width() {
+ let offset_for = |jc: Option<Alignment>| {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ justification: jc,
+ ..decimal_level()
+ }]);
+ let (fragments, _) = inject(&resolved, &mut BuildState::default(), 0);
+ match fragments.first() {
+ Some(Fragment::Text {
+ text_offset, width, ..
+ }) => (text_offset.raw(), width.raw()),
+ other => panic!("expected a label, got {other:?}"),
+ }
+ };
+
+ let (start, w) = offset_for(Some(Alignment::Start));
+ assert_eq!(start, 0.0, "start-justified labels are not shifted");
+ assert!(w > 0.0, "the label has a measured width");
+
+ let (end, _) = offset_for(Some(Alignment::End));
+ assert!((end + w).abs() < 1e-3, "end shifts left by the full width");
+
+ let (centre, _) = offset_for(Some(Alignment::Center));
+ assert!((centre + w * 0.5).abs() < 1e-3, "center shifts by half");
+
+ let (absent, _) = offset_for(None);
+ assert_eq!(absent, 0.0, "an absent lvlJc behaves as start");
+ }
+
+ /// §17.9.3: the tab after the label is asked to span the hanging indent
+ /// *less* what the label already occupies, so the body text lands at the
+ /// level's indent rather than one label-width past it.
+ #[test]
+ fn the_separator_tab_spans_the_hanging_indent_less_the_label() {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ indentation: Some(Indentation {
+ start: Some(Dimension::new(720)),
+ first_line: Some(FirstLineIndent::Hanging(Dimension::new(360))), // 18pt
+ ..Default::default()
+ }),
+ ..decimal_level()
+ }]);
+ let (fragments, _) = inject(&resolved, &mut BuildState::default(), 0);
+
+ let label_width = match &fragments[0] {
+ Fragment::Text { width, .. } => width.raw(),
+ other => panic!("expected a label, got {other:?}"),
+ };
+ match &fragments[1] {
+ Fragment::Tab { fitting_width, .. } => {
+ let got = fitting_width
+ .expect("the label tab carries a fitting width")
+ .raw();
+ assert!(
+ (got - (18.0 - label_width)).abs() < 1e-3,
+ "18pt hanging indent less a {label_width}pt label, got {got}"
+ );
+ }
+ other => panic!("expected the separator tab, got {other:?}"),
+ }
+ }
+
+ /// `extract_hanging` reads only the hanging case: a *first-line* indent is
+ /// not a hanging indent, and neither is an absent one. Reached through the
+ /// tab's fitting width, which is the only thing that consumes it.
+ #[test]
+ fn only_a_hanging_first_line_indent_is_a_hanging_indent() {
+ let fitting_for = |first_line: Option<FirstLineIndent>| {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ indentation: Some(Indentation {
+ first_line,
+ ..Default::default()
+ }),
+ ..decimal_level()
+ }]);
+ let (fragments, _) = inject(&resolved, &mut BuildState::default(), 0);
+ match &fragments[1] {
+ Fragment::Tab { fitting_width, .. } => fitting_width.unwrap().raw(),
+ other => panic!("expected the separator tab, got {other:?}"),
+ }
+ };
+
+ // A hanging indent gives the tab something to span; the other two
+ // clamp to zero, because `hanging - label_width` goes negative.
+ assert!(fitting_for(Some(FirstLineIndent::Hanging(Dimension::new(720)))) > 0.0);
+ assert_eq!(
+ fitting_for(Some(FirstLineIndent::FirstLine(Dimension::new(720)))),
+ 0.0
+ );
+ assert_eq!(fitting_for(Some(FirstLineIndent::None)), 0.0);
+ assert_eq!(fitting_for(None), 0.0);
+ }
+
+ /// §17.9.22: a paragraph with no numbering reference is left completely
+ /// alone — no label, no rewritten indentation, no counter touched.
+ #[test]
+ fn a_paragraph_without_numbering_is_untouched() {
+ let resolved = resolved_with(vec![decimal_level()]);
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let mut state = BuildState::default();
+ let mut fragments = Vec::new();
+ let mut props = ParagraphProperties::default();
+ inject_list_label(
+ &numbered_para(),
+ &mut fragments,
+ &mut props,
+ &ctx,
+ &mut state,
+ );
+
+ assert!(fragments.is_empty(), "no label injected");
+ assert!(props.indentation.is_none(), "indentation untouched");
+ assert!(state.list_counters.is_empty(), "no counter advanced");
+ }
+
+ /// §17.9.2: a `numId` with no definition is a dangling reference. It must
+ /// not inject a label *or* advance a counter — the paragraph simply is not
+ /// numbered.
+ #[test]
+ fn an_unknown_num_id_injects_nothing() {
+ let resolved = resolved_with(vec![decimal_level()]);
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let mut state = BuildState::default();
+ let mut fragments = Vec::new();
+ let mut props = ParagraphProperties {
+ numbering: Some(NumberingReference {
+ num_id: 999,
+ level: 0,
+ }),
+ ..Default::default()
+ };
+ inject_list_label(
+ &numbered_para(),
+ &mut fragments,
+ &mut props,
+ &ctx,
+ &mut state,
+ );
+
+ assert!(fragments.is_empty(), "no label injected");
+ assert!(state.list_counters.is_empty(), "no counter advanced");
+ }
+
+ /// §17.9.23: the level's indentation replaces the paragraph's, but the
+ /// paragraph's *direct* indentation still wins field by field.
+ #[test]
+ fn direct_paragraph_indentation_beats_the_level() {
+ let resolved = resolved_with(vec![ResolvedNumberingLevel {
+ indentation: Some(Indentation {
+ start: Some(Dimension::new(720)),
+ end: Some(Dimension::new(100)),
+ ..Default::default()
+ }),
+ ..decimal_level()
+ }]);
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let mut para = numbered_para();
+ para.properties.indentation = Some(Indentation {
+ start: Some(Dimension::new(1440)),
+ ..Default::default()
+ });
+ let mut fragments = Vec::new();
+ let mut props = props_at(0);
+ inject_list_label(
+ &para,
+ &mut fragments,
+ &mut props,
+ &ctx,
+ &mut BuildState::default(),
+ );
+
+ let ind = props.indentation.expect("the level supplies indentation");
+ assert_eq!(ind.start, Some(Dimension::new(1440)), "direct start wins");
+ assert_eq!(ind.end, Some(Dimension::new(100)), "level end survives");
+ }
+
+ fn rp_with_bold(b: bool) -> RunProperties {
+ RunProperties {
+ bold: Some(b),
+ ..Default::default()
+ }
+ }
+
+ fn rp_with_underline(u: UnderlineStyle) -> RunProperties {
+ RunProperties {
+ underline: Some(u),
+ ..Default::default()
+ }
+ }
+
+ fn rp_with_font(name: &str) -> RunProperties {
+ RunProperties {
+ fonts: FontSet {
+ ascii: FontSlot::from_name(name),
+ ..Default::default()
+ },
+ ..Default::default()
+ }
+ }
+
+ /// Highest-priority source wins when more than one layer sets the
+ /// same field.
+ #[test]
+ fn cascade_pick_level_overrides_mark_for_bold() {
+ let level = rp_with_bold(true);
+ let mark = rp_with_bold(false);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: Some(&mark),
+ paragraph_style: None,
+ };
+ assert_eq!(cascade.pick(|rp| rp.bold), Some(true));
+ }
+
+ /// When the level layer doesn't set a field, the next layer down
+ /// supplies it. §17.3.1.29.
+ #[test]
+ fn cascade_pick_falls_through_to_mark_when_level_field_absent() {
+ let level = rp_with_bold(true); // sets bold but NOT underline
+ let mark = rp_with_underline(UnderlineStyle::Single);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: Some(&mark),
+ paragraph_style: None,
+ };
+ assert_eq!(cascade.pick(|rp| rp.bold), Some(true));
+ assert_eq!(
+ cascade.pick(|rp| rp.underline),
+ Some(UnderlineStyle::Single)
+ );
+ }
+
+ /// Paragraph-style run defaults are the bottom layer — used only
+ /// when neither level nor mark sets a field.
+ #[test]
+ fn cascade_pick_falls_through_to_paragraph_style_when_others_absent() {
+ let style = rp_with_underline(UnderlineStyle::Double);
+ let cascade = ListLabelRunPropertyCascade {
+ level: None,
+ paragraph_mark: None,
+ paragraph_style: Some(&style),
+ };
+ assert_eq!(
+ cascade.pick(|rp| rp.underline),
+ Some(UnderlineStyle::Double)
+ );
+ }
+
+ /// No layer sets the field → `None`. Caller decides the default.
+ #[test]
+ fn cascade_pick_returns_none_when_no_source_sets_field() {
+ let level = rp_with_bold(true);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ assert_eq!(cascade.pick(|rp| rp.italic), None);
+ }
+
+ /// `iter()` skips `None` layers and preserves priority order.
+ #[test]
+ fn cascade_iter_skips_none_layers_in_order() {
+ let level = rp_with_bold(true);
+ let style = rp_with_bold(false);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None, // skipped
+ paragraph_style: Some(&style),
+ };
+ let bolds: Vec<_> = cascade.iter().map(|rp| rp.bold).collect();
+ assert_eq!(bolds, vec![Some(true), Some(false)]);
+ }
+
+ /// The key correctness property for the bug at hand: a level rPr
+ /// underline must surface in the resolved properties so
+ /// `font_props_from_run` reads it.
+ #[test]
+ fn cascade_resolve_materializes_underline_from_level() {
+ let level = rp_with_underline(UnderlineStyle::Single);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let effective = cascade.resolve();
+ assert_eq!(effective.underline, Some(UnderlineStyle::Single));
+ }
+
+ /// `FontSet` (non-`Copy`) cascade rule: the resolved `fonts` is
+ /// the first cascade source that has an explicitly set font slot.
+ #[test]
+ fn cascade_resolve_fonts_picks_first_explicit_source() {
+ let level = RunProperties::default(); // no fonts
+ let mark = rp_with_font("Verdana");
+ let style = rp_with_font("Arial");
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: Some(&mark),
+ paragraph_style: Some(&style),
+ };
+ let effective = cascade.resolve();
+ assert_eq!(effective.fonts.ascii.explicit.as_deref(), Some("Verdana"));
+ }
+
+ // ── §17.9.23 — `build_label_font_props` ──────────────────────────────
+ //
+ // The label's `FontProps` is built by passing the cascade-resolved
+ // `RunProperties` through `font_props_from_run`. These tests pin
+ // the spec-driven invariants the previous hand-rolled construction
+ // violated (notably: dropped underline, char_spacing, text_scale).
+
+ /// THE BUG: an underline in the level rPr (`<w:lvl><w:rPr><w:u/>`)
+ /// must surface as `font.underline = true`. Previously this code
+ /// path hardcoded `underline: false`.
+ #[test]
+ fn label_font_inherits_underline_from_level() {
+ let level = rp_with_underline(UnderlineStyle::Single);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(
+ font.underline,
+ "level rPr <w:u/> must become font.underline"
+ );
+ }
+
+ /// Cascade depth: when the level layer doesn't set underline but
+ /// the paragraph-mark rPr does, the label inherits the underline.
+ /// §17.3.1.29. (Previously broken: hand-rolled code never read
+ /// either layer's underline.)
+ #[test]
+ fn label_font_inherits_underline_from_mark_when_level_absent() {
+ let mark = rp_with_underline(UnderlineStyle::Single);
+ let cascade = ListLabelRunPropertyCascade {
+ level: None,
+ paragraph_mark: Some(&mark),
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(font.underline);
+ }
+
+ /// Explicit `<w:u w:val="none"/>` in the level must turn underline
+ /// OFF even if a lower cascade layer has it on — per spec, "none"
+ /// is an explicit override, not an "inherit" signal. The cascade
+ /// picks the level's `Some(None)` over the mark's `Some(Single)`,
+ /// and `font_props_from_run` collapses it to `underline = false`.
+ #[test]
+ fn label_font_underline_false_when_level_explicitly_none() {
+ let level = rp_with_underline(UnderlineStyle::None);
+ let mark = rp_with_underline(UnderlineStyle::Single);
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: Some(&mark),
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(
+ !font.underline,
+ "explicit UnderlineStyle::None must override lower layers"
+ );
+ }
+
+ /// `<w:spacing>` (char spacing) was silently dropped by the
+ /// hand-rolled construction. With cascade routing it must flow
+ /// into `FontProps::char_spacing`.
+ #[test]
+ fn label_font_inherits_char_spacing_from_level() {
+ let level = RunProperties {
+ spacing: Some(Dimension::<Twips>::new(40)),
+ ..Default::default()
+ };
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ // 40 twips = 2 pt.
+ assert!((font.char_spacing.raw() - 2.0).abs() < 1e-4);
+ }
+
+ /// `<w:w>` (text scale) was silently fixed to 1.0 in the
+ /// hand-rolled construction.
+ #[test]
+ fn label_font_inherits_text_scale_from_level() {
+ let level = RunProperties {
+ text_scale: Some(TextScale::new(150)),
+ ..Default::default()
+ };
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!((font.text_scale - 1.5).abs() < 1e-4);
+ }
+
+ /// Bold/italic/size pass through, with the cascade-resolved font
+ /// family taking precedence over `default_family`.
+ #[test]
+ fn label_font_pass_through_basic_fields() {
+ let level = RunProperties {
+ bold: Some(true),
+ italic: Some(true),
+ font_size: Some(Dimension::<HalfPoints>::new(24)), // 12 pt
+ fonts: FontSet {
+ ascii: FontSlot::from_name("Verdana"),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(10.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(font.bold);
+ assert!(font.italic);
+ assert_eq!(font.size.raw(), 12.0);
+ assert_eq!(&*font.family, "Verdana");
+ }
+
+ /// When no cascade layer sets a font, `default_family` wins.
+ #[test]
+ fn label_font_falls_back_to_default_family() {
+ let cascade = ListLabelRunPropertyCascade {
+ level: None,
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let font = build_label_font_props(
+ &cascade,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert_eq!(&*font.family, "Helvetica");
+ }
+
+ /// Empty cascade — resolve returns default (all `None` / empty).
+ #[test]
+ fn cascade_resolve_returns_defaults_when_cascade_empty() {
+ let cascade = ListLabelRunPropertyCascade {
+ level: None,
+ paragraph_mark: None,
+ paragraph_style: None,
+ };
+ let effective = cascade.resolve();
+ assert_eq!(effective, RunProperties::default());
+ }
+
+ /// All label-relevant fields composed across all three layers.
+ /// Documents the full set of fields the resolver pulls (any
+ /// future field becoming label-relevant should fail this test
+ /// until added).
+ #[test]
+ fn cascade_resolve_composes_all_label_fields() {
+ use crate::model::Color;
+
+ let level = RunProperties {
+ bold: Some(true),
+ underline: Some(UnderlineStyle::Single),
+ ..Default::default()
+ };
+ let mark = RunProperties {
+ italic: Some(true),
+ font_size: Some(Dimension::<HalfPoints>::new(24)),
+ spacing: Some(Dimension::<Twips>::new(40)),
+ ..Default::default()
+ };
+ let style = RunProperties {
+ color: Some(Color::Rgb(0x112233)),
+ text_scale: Some(TextScale::new(120)),
+ fonts: FontSet {
+ ascii: FontSlot::from_name("Calibri"),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let cascade = ListLabelRunPropertyCascade {
+ level: Some(&level),
+ paragraph_mark: Some(&mark),
+ paragraph_style: Some(&style),
+ };
+ let effective = cascade.resolve();
+ assert_eq!(effective.bold, Some(true), "from level");
+ assert_eq!(
+ effective.underline,
+ Some(UnderlineStyle::Single),
+ "from level"
+ );
+ assert_eq!(effective.italic, Some(true), "from mark");
+ assert_eq!(
+ effective.font_size,
+ Some(Dimension::<HalfPoints>::new(24)),
+ "from mark"
+ );
+ assert_eq!(
+ effective.spacing,
+ Some(Dimension::<Twips>::new(40)),
+ "from mark"
+ );
+ assert_eq!(effective.color, Some(Color::Rgb(0x112233)), "from style");
+ assert_eq!(
+ effective.text_scale,
+ Some(TextScale::new(120)),
+ "from style"
+ );
+ assert_eq!(
+ effective.fonts.ascii.explicit.as_deref(),
+ Some("Calibri"),
+ "from style (lowest source that sets fonts)"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/build/mod.rs b/crates/liteparse-docx/src/render/layout/build/mod.rs
new file mode 100644
index 0000000..e25471c
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/build/mod.rs
@@ -0,0 +1,499 @@
+//! Recursive tree-walk that converts a resolved document model into layout blocks.
+//!
+//! The document tree (Section → Block → Paragraph | Table → Cell → Block…) is
+//! processed by recursive descent. Each `Block::Table` recurses into its cells'
+//! content, which may contain nested tables.
+
+pub(super) mod block;
+pub(super) mod convert;
+pub(super) mod floating;
+pub(super) mod list_label;
+pub(super) mod table;
+
+use std::collections::HashMap;
+
+use crate::model::{self, Block};
+use crate::render::dimension::Pt;
+use crate::render::layout::fragment::Fragment;
+use crate::render::layout::measurer::TextMeasurer;
+use crate::render::layout::page::PageConfig;
+use crate::render::layout::paragraph::ParagraphStyle;
+use crate::render::layout::section::LayoutBlock;
+use crate::render::resolve::ResolvedDocument;
+use crate::render::resolve::images::MediaEntry;
+use crate::render::resolve::sections::ResolvedSection;
+
+use block::{build_block, build_fragments, collect_endnotes};
+use convert::{
+ doc_font_family, doc_font_size, paragraph_style_from_props, resolve_paragraph_defaults,
+};
+use floating::{AnchorFrame, extract_floating_images, find_vml_absolute_position};
+use table::build_table;
+
+/// §17.8.3.2: OOXML fallback font when no theme or doc defaults specify one.
+pub(super) const SPEC_FALLBACK_FONT: &str = "Times New Roman";
+/// §17.3.2.14: default font size (10pt = 20 half-points per ECMA-376 §17.3.2.14).
+pub(super) const SPEC_DEFAULT_FONT_SIZE: Pt = Pt::new(10.0);
+
+// ── Context ─────────────────────────────────────────────────────────────────
+
+/// Immutable context threaded through the recursive tree walk.
+pub struct BuildContext<'a> {
+ pub measurer: &'a TextMeasurer<'a>,
+ pub resolved: &'a ResolvedDocument,
+}
+
+impl BuildContext<'_> {
+ pub(super) fn media(&self) -> &HashMap<model::RelId, MediaEntry> {
+ &self.resolved.media
+ }
+}
+
+/// Mutable state threaded through the recursive tree walk.
+#[derive(Default)]
+pub struct BuildState {
+ /// Page configuration for the current section.
+ pub page_config: crate::render::layout::page::PageConfig,
+ /// §17.11.12: footnote display numbering plus the ordered record of which
+ /// notes each paragraph referenced. Advanced by `collect_fragments` and
+ /// drained per paragraph — see
+ /// [`FootnoteTracker`](crate::render::layout::fragment::FootnoteTracker).
+ pub footnotes: crate::render::layout::fragment::FootnoteTracker,
+ /// Sequential endnote display number (i, ii, iii...).
+ pub endnote_counter: u32,
+ /// Per-(numId, level) running counters for list labels.
+ pub list_counters: HashMap<(model::NumId, u8), u32>,
+ /// §17.3.1.19: the document outline being accumulated.
+ pub outline: OutlineCollector,
+ /// Field evaluation context (page number, total pages).
+ pub field_ctx: crate::render::layout::fragment::FieldContext,
+ /// §20.1.4.1.17: default text color for the current shape text box (from
+ /// `wps:style/fontRef`), applied as the base below the run/style cascade.
+ /// `None` outside a shape text box.
+ pub shape_default_text_color: Option<crate::render::resolve::color::RgbColor>,
+ /// §20.1.4.1.17: default font family for the current shape text box (the
+ /// theme major/minor collection selected by `fontRef@idx`). `None` outside
+ /// a shape text box.
+ pub shape_default_font_family: Option<String>,
+ /// §20.1.2.1.18: the `a:normAutofit` shrink in force for the current shape
+ /// text body — the scale Word computed and wrote into the file.
+ /// [`ShapeAutoFit::NONE`](crate::render::layout::ShapeAutoFit::NONE)
+ /// outside a shape text box, and for a body that declares
+ /// `noAutofit`/`spAutoFit`.
+ pub shape_auto_fit: crate::render::layout::ShapeAutoFit,
+ /// §17.4.38: border styles already reported as unsupported this render.
+ ///
+ /// The layout layer draws only `Single` and `Double`, so the other 24
+ /// `BorderStyle` variants are approximated by a solid line. Warning at
+ /// every call would emit one line per cell edge — thousands for a large
+ /// table — so each distinct style is reported once. Scoped to the render
+ /// (like `Measurer::warned_emoji`) rather than to the process, so a second
+ /// document still reports its own.
+ pub warned_border_styles: std::collections::HashSet<model::BorderStyle>,
+ /// §17.4.41 / §17.4.42: a row overrode the table's `tblCellSpacing`, which
+ /// layout applies per *table*, not per row. Reported once per render for
+ /// the same reason as `warned_border_styles`.
+ pub warned_row_cell_spacing: bool,
+}
+
+// ── Public entry point ──────────────────────────────────────────────────────
+
+/// Built section output — layout blocks.
+pub struct BuiltSection {
+ pub blocks: Vec<LayoutBlock>,
+}
+
+/// Build layout blocks for one section by recursing into its block tree.
+pub fn build_section_blocks(
+ section: &ResolvedSection,
+ config: &PageConfig,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> BuiltSection {
+ let mut pending_dropcap: Option<crate::render::layout::paragraph::DropCapInfo> = None;
+ let blocks: Vec<LayoutBlock> = section
+ .blocks
+ .iter()
+ .filter_map(|block| {
+ build_block(
+ block,
+ config.content_width(),
+ ctx,
+ state,
+ &mut pending_dropcap,
+ )
+ })
+ .collect();
+
+ BuiltSection { blocks }
+}
+
+/// §17.11.2: build the document's endnote content, rendered once at the end of
+/// the document.
+///
+/// Endnotes are **document-scoped**, not section-scoped: `ResolvedDocument`
+/// holds a single endnote map. Calling this per section would emit every
+/// endnote once per section, so it deliberately sits outside the section loop.
+pub fn build_document_endnotes(
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> Vec<(String, Vec<Fragment>, ParagraphStyle)> {
+ let mut endnotes = Vec::new();
+ collect_endnotes(ctx, state, &mut endnotes);
+ endnotes
+}
+
+/// Collected header/footer content with layout metadata.
+pub struct HeaderFooterContent {
+ /// Layout blocks (paragraphs and tables) for stacking.
+ pub blocks: Vec<LayoutBlock>,
+ /// Absolute page-relative position from a VML text box, if present.
+ pub absolute_position: Option<(Pt, Pt)>,
+ /// Floating (anchor) images from header/footer paragraphs.
+ ///
+ /// Images are collected outside the layout-block tree so the renderer
+ /// can split behindDoc and in-front-of-text images around the text
+ /// commands for correct z-ordering. Floating shapes, by contrast, ride
+ /// on `LayoutBlock::Paragraph.floating_shapes` so the stacker can anchor
+ /// them to the owning paragraph's y position.
+ pub floating_images: Vec<crate::render::layout::section::FloatingImage>,
+ /// Page-anchored floating shapes (vertical `relativeFrom` is
+ /// `page` / `margin` / `topMargin` / `bottomMargin` / etc.).
+ ///
+ /// Their `y` is `FloatingImageY::Absolute(...)` resolved in `Page`
+ /// frame, and the renderer emits them directly without applying the
+ /// header/footer stack shift — so a `<wp:positionV relativeFrom="page">`
+ /// shape in a footer (e.g. a "Seite X von Y" indicator pinned just
+ /// below the gray address bar) lands at its authored page-y.
+ /// Paragraph- / line-anchored shapes still travel on
+ /// `LayoutBlock::Paragraph.floating_shapes` so they follow the host
+ /// paragraph's y.
+ pub floating_shapes: Vec<crate::render::layout::section::FloatingShape>,
+}
+
+/// Build header/footer content from blocks.
+///
+/// Produces `LayoutBlock` entries for both paragraphs and tables, and
+/// extracts floating images separately (they are positioned page-relative
+/// rather than stack-relative).
+/// Lay out content that is **not** the document's main story: a header, a
+/// footer, or a shape text body.
+///
+/// §17.3.1.19: the outline collector is suspended for the whole call and
+/// restored after. Doing it here rather than at each paragraph is what makes it
+/// correct — a `Block::Table` in a header is handed to the *body* table
+/// builder, so its cell paragraphs reach the ordinary paragraph builder with
+/// the document's state. Guarding only the paragraph arm let a heading in a
+/// header table into the outline once per page the header was drawn on.
+///
+/// Save-and-restore rather than a fresh flag because the call nests: a shape
+/// text body inside a header goes through here twice.
+pub fn build_header_footer_content(
+ blocks: &[Block],
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> HeaderFooterContent {
+ let outer = std::mem::replace(&mut state.outline, OutlineCollector::Excluded);
+ let content = build_non_story_content(blocks, ctx, state);
+ state.outline = outer;
+ content
+}
+
+fn build_non_story_content(
+ blocks: &[Block],
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> HeaderFooterContent {
+ let mut layout_blocks = Vec::new();
+ let mut all_floating_images = Vec::new();
+ let mut all_page_anchored_shapes = Vec::new();
+ let mut absolute_position: Option<(Pt, Pt)> = None;
+
+ let available_width = state.page_config.content_width();
+
+ let block_count = blocks.len();
+ for (block_i, block) in blocks.iter().enumerate() {
+ match block {
+ Block::Paragraph(p) => {
+ let (mut frags, props) = build_fragments(p, ctx, state, None, None);
+ // §17.11.12: headers/footers don't render footnote bodies, but
+ // they must still drain — otherwise a reference inside one
+ // would be attributed to the next body paragraph.
+ let _ = state.footnotes.take_pending();
+ let style = paragraph_style_from_props(
+ &props,
+ Pt::from(ctx.resolved.default_tab_stop),
+ state.shape_auto_fit,
+ convert::paragraph_locale(p, ctx.resolved),
+ // §17.3.1.19: always `None` here — the collector is
+ // suspended for this whole call. Asking rather than passing
+ // `None` keeps one rule: whether a paragraph is a heading is
+ // decided in one place, for every path.
+ convert::paragraph_outline(p, &props, state),
+ );
+
+ // Check for VML absolute positioning in Pict inlines.
+ if absolute_position.is_none() {
+ for inline in &p.content {
+ if let Some(pos) = find_vml_absolute_position(inline) {
+ absolute_position = Some(pos);
+ break;
+ }
+ }
+ }
+ // §20.4.2.3: extract floating (anchor) images. Images are
+ // collected at the header/footer level and emitted by
+ // `render_header`/`render_footer` *outside* of `stack_blocks`
+ // — that's how z-ordering against the text (behindDoc) is
+ // implemented. Because the caller does not apply the stack
+ // shift to these commands, their coordinates must be
+ // page-absolute.
+ let para_floats = extract_floating_images(p, ctx, state, AnchorFrame::Page);
+ let has_float_images = !para_floats.is_empty();
+ all_floating_images.extend(para_floats);
+ // Shapes, by contrast, travel on the owning paragraph so
+ // `stack_blocks` can anchor them to the paragraph's y
+ // coordinate. `stack_blocks` emits every command in
+ // stack-frame-relative space and `render_footer` /
+ // `render_header` later shift the whole batch by
+ // `margins.left` — so shapes must be resolved in the stack
+ // frame (not page-absolute), otherwise `margins.left` would
+ // be applied twice. §17.10.1: z-ordering against the
+ // surrounding text in Tier 0 is paragraph-granular, matching
+ // the stack-frame emission order.
+ let paragraph_shapes = floating::extract_floating_shapes(
+ p,
+ ctx,
+ state,
+ AnchorFrame::Stack,
+ floating::ShapeAnchorClass::ParagraphAnchored,
+ );
+
+ // §17.10.1 / §20.4.2.10: shapes whose vertical position is
+ // page/margin-relative resolve to a fixed absolute y. They
+ // can't ride on the per-paragraph anchoring used by
+ // `paragraph_shapes`, so collect them at the
+ // header/footer level — `render_header`/`render_footer`
+ // emits them outside `stack_blocks` (no shift) so the
+ // resolved page-y is honored.
+ let page_anchored_shapes = floating::extract_floating_shapes(
+ p,
+ ctx,
+ state,
+ AnchorFrame::Page,
+ floating::ShapeAnchorClass::PageAnchored,
+ );
+ all_page_anchored_shapes.extend(page_anchored_shapes);
+
+ // §17.10.1: empty non-last paragraphs in headers/footers still
+ // occupy a line height (from the paragraph mark's font size).
+ //
+ // Exception: paragraphs whose only content is floating shape
+ // or image anchors are treated as zero-height anchors —
+ // Word positions the shape relative to the paragraph top,
+ // which must coincide with the preceding paragraph's bottom
+ // (otherwise the shape displaces text it should flank).
+ let has_floating_anchor = has_float_images || !paragraph_shapes.is_empty();
+ if frags.is_empty() && block_i + 1 < block_count && !has_floating_anchor {
+ let (family, mut size, ..) =
+ resolve_paragraph_defaults(p, ctx.resolved, false, None, None);
+ if let Some(ref mrp) = p.mark_run_properties {
+ if let Some(fs) = mrp.font_size {
+ size = Pt::from(fs);
+ }
+ }
+ let line_height = ctx.measurer.default_line_height(&family, size);
+ frags.push(Fragment::LineBreak { line_height });
+ }
+
+ layout_blocks.push(LayoutBlock::Paragraph {
+ fragments: frags,
+ style,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![], // handled separately above
+ floating_shapes: paragraph_shapes,
+ });
+ }
+ Block::Table(t) => {
+ let built = build_table(t, available_width, ctx, state);
+ layout_blocks.push(LayoutBlock::Table {
+ rows: built.rows,
+ col_widths: built.col_widths,
+ cell_spacing: built.cell_spacing,
+ border_config: built.border_config,
+ indent: built.indent,
+ alignment: built.alignment,
+ float_info: built.float_info,
+ style_id: t.properties.style_id.clone(),
+ });
+ }
+ Block::SectionBreak(_) => {}
+ }
+ }
+
+ HeaderFooterContent {
+ blocks: layout_blocks,
+ absolute_position,
+ floating_images: all_floating_images,
+ floating_shapes: all_page_anchored_shapes,
+ }
+}
+
+/// Default line height derived from document-level font settings.
+pub fn default_line_height(ctx: &BuildContext) -> Pt {
+ let family = doc_font_family(ctx);
+ let size = doc_font_size(ctx);
+ ctx.measurer.default_line_height(&family, size)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::Dimension;
+ use crate::render::fonts::FontRegistry;
+ use crate::render::layout::measurer::TextMeasurer;
+
+ fn empty_resolved() -> ResolvedDocument {
+ ResolvedDocument {
+ sections: Vec::new(),
+ styles: HashMap::new(),
+ numbering: HashMap::new(),
+ font_families: Vec::new(),
+ media: HashMap::new(),
+ embedded_fonts: Vec::new(),
+ pic_bullets: HashMap::new(),
+ theme: None,
+ doc_defaults_paragraph: model::ParagraphProperties::default(),
+ doc_defaults_run: model::RunProperties::default(),
+ default_paragraph_style_id: None,
+ footnotes: HashMap::new(),
+ endnotes: HashMap::new(),
+ even_and_odd_headers: false,
+ default_tab_stop: Dimension::new(720),
+ }
+ }
+
+ fn empty_para() -> Block {
+ Block::Paragraph(Box::new(model::Paragraph {
+ style_id: None,
+ properties: model::ParagraphProperties::default(),
+ mark_run_properties: None,
+ content: Vec::new(),
+ rsids: model::ParagraphRevisionIds::default(),
+ }))
+ }
+
+ fn line_break_counts(blocks: &[LayoutBlock]) -> Vec<usize> {
+ blocks
+ .iter()
+ .map(|b| match b {
+ LayoutBlock::Paragraph { fragments, .. } => fragments
+ .iter()
+ .filter(|f| matches!(f, Fragment::LineBreak { .. }))
+ .count(),
+ _ => 0,
+ })
+ .collect()
+ }
+
+ /// §17.10.1: an empty paragraph in a header/footer holds a line of height —
+ /// *except* the last one, which would otherwise push the whole stack.
+ #[test]
+ fn empty_header_paragraphs_hold_a_line_except_the_last() {
+ let resolved = empty_resolved();
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let mut state = BuildState::default();
+
+ let blocks = vec![empty_para(), empty_para(), empty_para()];
+ let hf = build_header_footer_content(&blocks, &ctx, &mut state);
+
+ assert_eq!(hf.blocks.len(), 3);
+ assert_eq!(
+ line_break_counts(&hf.blocks),
+ vec![1, 1, 0],
+ "the trailing empty paragraph contributes no line"
+ );
+ }
+
+ /// A single empty paragraph is also the last one, so it contributes nothing.
+ #[test]
+ fn a_lone_empty_header_paragraph_holds_no_line() {
+ let resolved = empty_resolved();
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let mut state = BuildState::default();
+
+ let hf = build_header_footer_content(&[empty_para()], &ctx, &mut state);
+ assert_eq!(line_break_counts(&hf.blocks), vec![0]);
+ }
+
+ /// Section breaks inside header/footer content are structural, not laid out.
+ #[test]
+ fn header_section_breaks_produce_no_blocks() {
+ let resolved = empty_resolved();
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved: &resolved,
+ };
+ let mut state = BuildState::default();
+
+ let blocks = vec![Block::SectionBreak(Box::default()), empty_para()];
+ let hf = build_header_footer_content(&blocks, &ctx, &mut state);
+ assert_eq!(hf.blocks.len(), 1, "only the paragraph survives");
+ }
+}
+
+/// §17.3.1.19: whether a build contributes to the PDF document outline.
+///
+/// A PDF structure node ID must be unique across the whole document, so the
+/// counter is document-wide — like `list_counters`, and for the same reason.
+/// The variant matters because a shape text body is laid out by a **fresh**
+/// `BuildState`: left `Collecting`, its counter would restart at 1 and hand out
+/// IDs already owned by body headings, silently retargeting their outline
+/// entries at the shape.
+///
+/// It is also the right answer independently. A heading inside a text box is
+/// not a position in the document's main story, which is what an outline
+/// enumerates — Word's own navigation pane leaves them out too.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OutlineCollector {
+ /// The document body. Holds how many headings it has taken IDs for.
+ Collecting(i32),
+ /// A sub-layout whose headings are not document positions.
+ Excluded,
+}
+
+impl Default for OutlineCollector {
+ fn default() -> Self {
+ Self::Collecting(0)
+ }
+}
+
+impl BuildState {
+ /// §17.3.1.19: reserve the next PDF structure node ID, or `None` when this
+ /// build contributes nothing to the outline.
+ pub fn next_outline_node_id(&mut self) -> Option<i32> {
+ match &mut self.outline {
+ OutlineCollector::Collecting(count) => {
+ // 1-based: `skia_safe::pdf::node_id` reserves 0 for "no node"
+ // and every negative value for artifacts, so a 0-based counter
+ // would silently leave the first heading unmarked.
+ *count += 1;
+ Some(*count)
+ }
+ OutlineCollector::Excluded => None,
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/build/table.rs b/crates/liteparse-docx/src/render/layout/build/table.rs
new file mode 100644
index 0000000..98f1d08
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/build/table.rs
@@ -0,0 +1,860 @@
+use crate::model::{self, Block, Table, TableCell};
+use crate::render::dimension::Pt;
+use crate::render::geometry;
+use crate::render::layout::paragraph::DropCapInfo;
+use crate::render::layout::section::LayoutBlock;
+use crate::render::layout::table::{
+ CellBorderConfig, CellBorderOverride, TableCellInput, TableRowInput, compute_column_widths,
+};
+use crate::render::resolve::color::{ColorContext, resolve_color};
+use crate::render::resolve::conditional::{
+ CellConditionalFormatting, CellGridPosition, resolve_cell_conditional,
+};
+use crate::render::resolve::styles::ResolvedStyle;
+
+use super::block::build_paragraph_block;
+use crate::render::layout::fragment::split_oversized_fragments;
+
+use super::convert::{
+ convert_cell_border_override, convert_table_border_config, merge_table_borders,
+};
+use super::{BuildContext, BuildState};
+
+/// Result of building a table from the model.
+pub(super) struct BuiltTable {
+ pub(super) rows: Vec<TableRowInput>,
+ /// Grid slots, already shrunk by `cell_spacing`.
+ pub(super) col_widths: Vec<Pt>,
+ /// §17.4.44 `tblCellSpacing` in points; zero when unset.
+ pub(super) cell_spacing: Pt,
+ pub(super) border_config: Option<crate::render::layout::table::TableBorderConfig>,
+ /// §17.4.51: table indentation from left margin.
+ pub(super) indent: Pt,
+ /// §17.4.28: table horizontal alignment (left/center/right).
+ pub(super) alignment: Option<model::Alignment>,
+ pub(super) float_info: Option<super::super::section::TableFloatInfo>,
+}
+
+/// §17.4.81: turn a parsed `trHeight` into a layout constraint.
+///
+/// `exact` pins the height, `atLeast` is a minimum, and `auto` **ignores `val`**
+/// — the row sizes to its content and carries no constraint at all, hence the
+/// `None`.
+///
+/// An omitted `hRule` never reaches here as `Auto`: the parse seam defaults it
+/// to `AtLeast`, matching Word ([MS-OI29500] §17.4.80(a)) rather than the
+/// standard's `auto`. That default is what makes returning `None` for `auto`
+/// safe — otherwise every Word row with a `trHeight` would lose its minimum.
+fn row_height_rule(
+ h: model::TableRowHeight,
+) -> Option<crate::render::layout::table::RowHeightRule> {
+ use crate::model::HeightRule;
+ use crate::render::layout::table::RowHeightRule;
+ match h.rule {
+ HeightRule::Exact => Some(RowHeightRule::Exact(Pt::from(h.value))),
+ HeightRule::AtLeast => Some(RowHeightRule::AtLeast(Pt::from(h.value))),
+ HeightRule::Auto => None,
+ }
+}
+
+/// §17.4.44: resolve `tblCellSpacing` to points.
+///
+/// `CT_TblWidth` allows `pct` and `auto`, and the spec says both **are ignored**
+/// for this element — only `dxa` carries a usable value. `nil` and an omitted
+/// element are zero, which is every table in the test corpora.
+fn resolve_cell_spacing(m: Option<model::TableMeasure>) -> Pt {
+ match m {
+ Some(model::TableMeasure::Twips(tw)) => Pt::from(tw).max(Pt::ZERO),
+ // Auto / Pct / Nil / absent.
+ _ => Pt::ZERO,
+ }
+}
+
+/// Carve one `cell_spacing` out of the grid so the slots plus one spacing add
+/// up to the table's own width, scaling the columns proportionally.
+///
+/// Clamped: a spacing at least as large as the table would leave nothing to
+/// scale, so the columns collapse to zero rather than going negative. Word
+/// caps the usable spacing well below that, but the file format does not.
+fn reserve_cell_spacing(col_widths: Vec<Pt>, cell_spacing: Pt) -> Vec<Pt> {
+ if cell_spacing <= Pt::ZERO || col_widths.is_empty() {
+ return col_widths;
+ }
+ let total: Pt = col_widths.iter().copied().sum();
+ if total <= cell_spacing {
+ return vec![Pt::ZERO; col_widths.len()];
+ }
+ let scale = (total - cell_spacing).raw() / total.raw();
+ col_widths.into_iter().map(|w| w * scale).collect()
+}
+
+/// Recursively build a table: resolve styles, conditional formatting, and
+/// recurse into each cell's content blocks.
+pub(super) fn build_table(
+ t: &Table,
+ available_width: Pt,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> BuiltTable {
+ // §17.4.14: grid column widths.
+ let num_cols = if t.grid.is_empty() {
+ t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0)
+ } else {
+ t.grid.len()
+ };
+ let grid_cols: Vec<Pt> = t.grid.iter().map(|g| Pt::from(g.width)).collect();
+
+ // §17.7.6: table style for conditional formatting, borders, cell margins.
+ let raw_table_style = t
+ .properties
+ .style_id
+ .as_ref()
+ .and_then(|sid| ctx.resolved.styles.get(sid));
+
+ // §17.4.42: default cell margins from table style cascade.
+ let style_cell_margins = raw_table_style
+ .and_then(|s| s.table.as_ref())
+ .and_then(|tp| tp.cell_margins);
+ // Per-edge merge: direct tblCellMar overrides style per-edge, with
+ // unspecified edges (value 0) falling back to the style's value.
+ // Word merges per-edge rather than replacing the entire set.
+ let default_cell_margins = match (t.properties.cell_margins, style_cell_margins) {
+ (Some(direct), Some(style)) => {
+ use crate::model::geometry::EdgeInsets;
+ Some(EdgeInsets {
+ top: if direct.top.raw() != 0 {
+ direct.top
+ } else {
+ style.top
+ },
+ bottom: if direct.bottom.raw() != 0 {
+ direct.bottom
+ } else {
+ style.bottom
+ },
+ left: if direct.left.raw() != 0 {
+ direct.left
+ } else {
+ style.left
+ },
+ right: if direct.right.raw() != 0 {
+ direct.right
+ } else {
+ style.right
+ },
+ })
+ }
+ (Some(direct), None) => Some(direct),
+ (None, Some(style)) => Some(style),
+ (None, None) => None,
+ };
+
+ // §17.4.63: resolve table width from tblW.
+ let is_auto_width = matches!(
+ t.properties.width,
+ None | Some(model::TableMeasure::Auto) | Some(model::TableMeasure::Nil)
+ );
+ let cell_margins_h = default_cell_margins
+ .map(|m| Pt::from(m.left) + Pt::from(m.right))
+ .unwrap_or(Pt::ZERO);
+ // §17.4.63 / Word heuristic: a full-width left-aligned table extends
+ // beyond the body content area by its cell margins so cell content
+ // aligns with surrounding paragraph text. Centered/right-aligned tables
+ // are positioned as a unit — extending them would just shift them out
+ // by half the margins, producing a width discrepancy when consecutive
+ // centered tables have different cell margins (cf. the stacked
+ // "Anhang: Sauberkeit" tables in the Volvo Annahme-Protokoll).
+ let extends_for_alignment = !matches!(
+ t.properties.alignment,
+ Some(model::Alignment::Center) | Some(model::Alignment::End)
+ );
+ let target_width = match t.properties.width {
+ Some(model::TableMeasure::Pct(pct)) => {
+ // §17.4.63: percentage in fiftieths of a percent. 5000 = 100%.
+ let ratio = pct.raw() as f32 / 5000.0;
+ let base = if pct.raw() >= 5000 && extends_for_alignment {
+ available_width + cell_margins_h
+ } else {
+ available_width
+ };
+ base * ratio
+ }
+ Some(model::TableMeasure::Twips(tw)) => Pt::from(tw),
+ _ => available_width, // auto/nil: use grid cols or available width
+ };
+ // §17.4.53: tblLayout controls whether columns may auto-resize to fit
+ // content; it does not override the preferred table width from tblW.
+ // Word scales grid column widths proportionally to match tblW in both
+ // fixed and auto layouts. Only when tblW is auto/nil do we keep the raw
+ // grid widths (no preferred width was specified).
+ let col_widths = if is_auto_width && !grid_cols.is_empty() {
+ grid_cols.clone()
+ } else {
+ compute_column_widths(&grid_cols, num_cols, target_width)
+ };
+ // §17.4.44: cell spacing is carved out of the table's own width rather than
+ // added to it — the spec calls it "the minimum amount of space which shall
+ // be left between all cells", not extra width. Reserving one spacing here
+ // and offsetting each cell by one in `measure_table_rows` yields exactly
+ // `cell_spacing` between adjacent cells *and* at both table edges.
+ let cell_spacing = resolve_cell_spacing(t.properties.cell_spacing);
+ let col_widths = reserve_cell_spacing(col_widths, cell_spacing);
+ let style_overrides = raw_table_style
+ .map(|s| s.table_style_overrides.as_slice())
+ .unwrap_or(&[]);
+ let tbl_look = t.properties.look.as_ref();
+ let row_band_size = t.properties.style_row_band_size.unwrap_or(1);
+ let col_band_size = t.properties.style_col_band_size.unwrap_or(1);
+ let num_rows = t.rows.len();
+
+ // §17.4.38: resolve table borders — merge direct properties over table style.
+ // Direct tblBorders may specify only a subset of edges (e.g. insideH=none);
+ // unspecified edges inherit from the table style. Computed up front so
+ // per-row tblPrEx merges (§17.4.61) below have a stable basis.
+ let style_borders = raw_table_style
+ .and_then(|s| s.table.as_ref())
+ .and_then(|tp| tp.borders.as_ref());
+ let tbl_borders = match (t.properties.borders.as_ref(), style_borders) {
+ (Some(direct), Some(style)) => Some(merge_table_borders(direct, style)),
+ (Some(direct), None) => Some(*direct),
+ (None, Some(style)) => Some(*style),
+ (None, None) => None,
+ };
+ let border_config = tbl_borders
+ .as_ref()
+ .map(|b| convert_table_border_config(b, state));
+
+ // Build rows by iterating cells and recursing into their content.
+ let rows: Vec<TableRowInput> = t
+ .rows
+ .iter()
+ .enumerate()
+ .map(|(row_idx, row)| {
+ let num_cells = row.cells.len();
+ let cells: Vec<TableCellInput> = row
+ .cells
+ .iter()
+ .enumerate()
+ .map(|(col_idx, cell)| {
+ let cond = resolve_cell_conditional(
+ &CellGridPosition {
+ row_idx,
+ col_idx,
+ num_rows,
+ num_cols: num_cells,
+ row_band_size,
+ col_band_size,
+ },
+ tbl_look,
+ style_overrides,
+ );
+
+ // Compute available width for nested content.
+ // §17.4.17: gridBefore offsets the row's first cell to the
+ // right by that many grid columns; subsequent spans accumulate.
+ let span = cell.properties.grid_span.unwrap_or(1) as usize;
+ let mut grid_start = row.properties.grid_before as usize;
+ for ci in 0..col_idx {
+ grid_start += row.cells[ci].properties.grid_span.unwrap_or(1) as usize;
+ }
+ // A row may address more grid columns than `tblGrid` declares —
+ // a `gridBefore` past the end, or simply more `<w:tc>` than
+ // `<w:gridCol>`. Both occur in real producer output and Word
+ // recovers from them. Clamp *both* ends: clamping only the end
+ // inverts the range and panics on the slice.
+ let grid_start = grid_start.min(col_widths.len());
+ let grid_end = (grid_start + span).min(col_widths.len());
+ let cell_width: Pt = col_widths[grid_start..grid_end].iter().copied().sum();
+ // Per-side cascade against the table default (see
+ // `build_table_cell` for the spec rationale): the horizontal
+ // padding contribution is the resolved left+right insets.
+ let table_default =
+ default_cell_margins.unwrap_or(crate::model::geometry::EdgeInsets::ZERO);
+ let resolved_h = match cell.properties.margins {
+ Some(partial) => partial.resolve_against(table_default),
+ None => table_default,
+ };
+ let cell_margins_h = Pt::from(resolved_h.left) + Pt::from(resolved_h.right);
+ let inner_width = (cell_width - cell_margins_h).max(Pt::ZERO);
+
+ build_table_cell(
+ cell,
+ raw_table_style,
+ default_cell_margins,
+ &cond,
+ inner_width,
+ ctx,
+ state,
+ )
+ })
+ .collect();
+
+ // Word/LibreOffice row-uniform content-area quirk — see
+ // `normalize_row_uniform_vertical_insets` for the spec gap and
+ // empirical evidence motivating this pass.
+ let mut cells = cells;
+ normalize_row_uniform_vertical_insets(&mut cells);
+
+ // §17.4.41 / §17.4.42: a row (or its `tblPrEx`) may override the
+ // table's `tblCellSpacing`. Layout applies spacing per *table* —
+ // the grid slots are shrunk once, up front — so a per-row value
+ // cannot be honoured without a per-row grid. Report it rather than
+ // dropping it silently; the parsed value stays on the model.
+ let row_spacing = row.properties.cell_spacing.or_else(|| {
+ row.property_exceptions
+ .as_ref()
+ .and_then(|e| e.cell_spacing)
+ });
+ if let Some(rs) = row_spacing {
+ if resolve_cell_spacing(Some(rs)) != cell_spacing && !state.warned_row_cell_spacing
+ {
+ state.warned_row_cell_spacing = true;
+ log::warn!(
+ "§17.4.41/§17.4.42: row-level tblCellSpacing overrides are not applied; \
+ using the table-level value ({cell_spacing:?})"
+ );
+ }
+ }
+
+ TableRowInput {
+ cells,
+ // §17.4.81: `exact` pins the height, `atLeast` is a minimum,
+ // and `auto` **ignores `val`** — the row sizes to its content,
+ // so it carries no constraint at all. An omitted `hRule`
+ // arrives as `AtLeast` (Word's default, set at the parse seam),
+ // which is why folding `auto` in with it used to be invisible:
+ // [MS-OE376] §2.4.77(c) notes Word requires `val = 0` whenever
+ // `hRule="auto"`, making `AtLeast(0)` a no-op on Word output.
+ // Other producers are not bound by that.
+ height_rule: row.properties.height.and_then(row_height_rule),
+ is_header: row.properties.is_header,
+ cant_split: row.properties.cant_split,
+ grid_before: row.properties.grid_before,
+ // §17.4.61: row-level tblPrEx.tblBorders — per-side
+ // override of the table's effective borders. We merge
+ // *at the model layer* (Option<Border> with style=None
+ // is preserved), then convert to layout — that keeps
+ // the spec's "specified as none" vs "not specified"
+ // distinction that converting first would erase.
+ border_overrides: row
+ .property_exceptions
+ .as_ref()
+ .and_then(|ex| ex.borders.as_ref())
+ .map(|over| {
+ let merged = match tbl_borders.as_ref() {
+ Some(table) => merge_table_borders(over, table),
+ None => *over,
+ };
+ convert_table_border_config(&merged, state)
+ }),
+ }
+ })
+ .collect();
+
+ // §17.4.58: floating table positioning.
+ let float_info = t.properties.positioning.as_ref().map(|pos| {
+ super::super::section::TableFloatInfo {
+ right_gap: pos.right_from_text.map(Pt::from).unwrap_or(Pt::ZERO),
+ bottom_gap: pos.bottom_from_text.map(Pt::from).unwrap_or(Pt::ZERO),
+ x_align: pos.x_align,
+ // §17.4.58: tblpY — absolute Y offset from the vertical anchor.
+ y_offset: pos.y.map(Pt::from).unwrap_or(Pt::ZERO),
+ // §17.4.58: default vertical anchor is "text".
+ vert_anchor: pos.vert_anchor.unwrap_or(crate::model::TableAnchor::Text),
+ // §17.4.57: tblOverlap controls collision behavior with
+ // other floats on the same page.
+ overlap: t.properties.overlap,
+ }
+ });
+
+ // §17.4.51: table indentation from left margin.
+ // For full-width left-aligned tables, MS Word shifts the table left
+ // by the default cell margin so cell content aligns with paragraph text.
+ let is_full_width = matches!(
+ t.properties.width,
+ Some(model::TableMeasure::Pct(pct)) if pct.raw() >= 5000
+ );
+ let is_left_aligned = !matches!(
+ t.properties.alignment,
+ Some(model::Alignment::Center) | Some(model::Alignment::End)
+ );
+ let indent = match t.properties.indent {
+ Some(model::TableMeasure::Twips(tw)) => Pt::from(tw),
+ _ if is_full_width && is_left_aligned => -default_cell_margins
+ .map(|m| Pt::from(m.left))
+ .unwrap_or(Pt::ZERO),
+ _ => Pt::ZERO,
+ };
+
+ BuiltTable {
+ rows,
+ col_widths,
+ cell_spacing,
+ border_config,
+ indent,
+ alignment: t.properties.alignment,
+ float_info,
+ }
+}
+
+/// Word/LibreOffice row layout quirk: top/bottom cell margins are normalized
+/// to the row-wide maximum across all cells in the row, while left/right stay
+/// per-cell.
+///
+/// # Spec relationship
+///
+/// ECMA-376 §17.4.42 (`tcMar`, "Single Table Cell Margins") defines the cell
+/// margin as a per-side exception over §17.4.44 (`tblCellMar`, the table-level
+/// default). Each side is a `CT_TblWidth` (§17.18.87), where `@type="dxa"
+/// @w="N"` is an explicit `N`-twip value. The spec is silent on how
+/// *neighbouring* cells in the same row interact when their per-cell margins
+/// disagree — there is no row-level "content area" concept defined in
+/// §17.4.78 (`tr`) or §17.4.79 (`trHeight`).
+///
+/// The de-facto behaviour of every mainstream renderer (Word and LibreOffice
+/// Writer in particular) is to compute a row-uniform content inset:
+///
+/// ```text
+/// row.uniform_top = max(cell.tcMar.top for cell in row)
+/// row.uniform_bottom = max(cell.tcMar.bottom for cell in row)
+/// ```
+///
+/// and to position every cell's content within that uniform inset regardless
+/// of the cell's own per-cell override. Without this pass, a cell with an
+/// explicit `tcMar.top=0` in a row whose siblings inherit a larger value sits
+/// flush against the row's top border while its neighbours sit padded — a
+/// positioning no mainstream editor produces.
+///
+/// # Empirical basis
+///
+/// Verified against the `Wohnungsübergabeprotokoll` sample (LibreOffice
+/// origin) by editing the DOCX directly and observing Word's render:
+///
+/// 1. Rewriting all `<w:tcMar><w:top w:w="0"/></w:tcMar>` to
+/// `<w:top w:w="1"/>` produced **byte-equivalent visual output** — Word
+/// is invariant to the literal value at this magnitude, ruling out
+/// "Word treats `w=0` as no-override" as the explanation.
+/// 2. Rewriting just one cell's `<w:tcMar>` to `<w:top w:w="500"/>` (≈ 25pt)
+/// pushed **every** cell in that row down by ~25pt, confirming the
+/// row-wide max(...) discipline.
+///
+/// # Scope
+///
+/// Only `top` and `bottom` are normalized. `left` and `right` stay per-cell
+/// because each column's content width is independent — there is no shared
+/// row-wide horizontal area in the de-facto layout, and editors do honour
+/// per-cell horizontal overrides.
+///
+/// Applied at the build layer (post per-side `<w:tcMar>`/`<w:tblCellMar>`
+/// cascade resolution) so downstream measure/emit/split code sees uniform
+/// vertical insets and needs no further changes.
+fn normalize_row_uniform_vertical_insets(cells: &mut [TableCellInput]) {
+ let max_top = cells.iter().fold(Pt::ZERO, |acc, c| acc.max(c.margins.top));
+ let max_bottom = cells
+ .iter()
+ .fold(Pt::ZERO, |acc, c| acc.max(c.margins.bottom));
+ for cell in cells {
+ cell.margins.top = max_top;
+ cell.margins.bottom = max_bottom;
+ }
+}
+
+/// Build a single table cell: resolve content blocks, margins, shading, borders.
+fn build_table_cell(
+ cell: &TableCell,
+ table_style: Option<&ResolvedStyle>,
+ style_cell_margins: Option<crate::model::geometry::EdgeInsets<crate::model::dimension::Twips>>,
+ cond: &CellConditionalFormatting,
+ inner_width: Pt,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> TableCellInput {
+ // §17.4.42: cell margins cascade *per side* against the pre-merged
+ // table default. A cell-level `<w:tcMar>` that specifies only some sides
+ // (e.g. `top`/`bottom` only — common in LibreOffice output) must inherit
+ // the remaining sides from `<w:tblCellMar>` rather than zeroing them out;
+ // collapsing missing sides to 0 produces text that hugs the cell borders
+ // instead of carrying the table's intended padding.
+ let table_default = style_cell_margins.unwrap_or(crate::model::geometry::EdgeInsets::ZERO);
+ let resolved_margins = match cell.properties.margins {
+ Some(partial) => partial.resolve_against(table_default),
+ None => table_default,
+ };
+ let cell_margins = geometry::PtEdgeInsets::new(
+ Pt::from(resolved_margins.top),
+ Pt::from(resolved_margins.right),
+ Pt::from(resolved_margins.bottom),
+ Pt::from(resolved_margins.left),
+ );
+
+ // §17.7.6: resolve cell shading. Priority: direct → conditional → none.
+ let shading = cell
+ .properties
+ .shading
+ .map(|s| resolve_color(s.fill, ColorContext::Background))
+ .or_else(|| {
+ cond.cell_properties
+ .as_ref()
+ .and_then(|tcp| tcp.shading.as_ref())
+ .map(|s| resolve_color(s.fill, ColorContext::Background))
+ });
+
+ // §17.4.66: cell borders cascade — direct cell borders (highest priority)
+ // → conditional formatting → table-level borders (resolved in layout).
+ let cond_borders = cond
+ .cell_properties
+ .as_ref()
+ .and_then(|tcp| tcp.borders.as_ref());
+ let direct_borders = cell.properties.borders.as_ref();
+
+ let cell_borders = match (direct_borders, cond_borders) {
+ (Some(db), _) => {
+ // Direct cell borders: highest priority. Fall through to
+ // conditional for edges not specified directly.
+ Some(CellBorderConfig {
+ top: convert_cell_border_override(&db.top, state).or_else(|| {
+ cond_borders.and_then(|cb| convert_cell_border_override(&cb.top, state))
+ }),
+ bottom: convert_cell_border_override(&db.bottom, state).or_else(|| {
+ cond_borders.and_then(|cb| convert_cell_border_override(&cb.bottom, state))
+ }),
+ left: convert_cell_border_override(&db.left, state).or_else(|| {
+ cond_borders.and_then(|cb| convert_cell_border_override(&cb.left, state))
+ }),
+ right: convert_cell_border_override(&db.right, state).or_else(|| {
+ cond_borders.and_then(|cb| convert_cell_border_override(&cb.right, state))
+ }),
+ })
+ }
+ (None, Some(cb)) => Some(CellBorderConfig {
+ top: convert_cell_border_override(&cb.top, state),
+ bottom: convert_cell_border_override(&cb.bottom, state),
+ left: convert_cell_border_override(&cb.left, state),
+ right: convert_cell_border_override(&cb.right, state),
+ }),
+ (None, None) => None,
+ };
+
+ // §17.4.84: vertical alignment — direct cell, conditional, or default top.
+ let valign = cell
+ .properties
+ .vertical_align
+ .or_else(|| {
+ cond.cell_properties
+ .as_ref()
+ .and_then(|tcp| tcp.vertical_align)
+ })
+ .map(|va| match va {
+ model::CellVerticalAlign::Bottom => crate::render::layout::table::CellVAlign::Bottom,
+ model::CellVerticalAlign::Center => crate::render::layout::table::CellVAlign::Center,
+ _ => crate::render::layout::table::CellVAlign::Top,
+ })
+ .unwrap_or(crate::render::layout::table::CellVAlign::Top);
+
+ // Estimate border insets to compute effective content width for
+ // character-level splitting of oversized fragments.
+ let border_w = |ovr: &Option<CellBorderOverride>| -> Pt {
+ match ovr {
+ Some(CellBorderOverride::Border(b)) => b.width,
+ _ => Pt::ZERO,
+ }
+ };
+ let border_inset_h = cell_borders
+ .as_ref()
+ .map(|cb| {
+ let bl = (border_w(&cb.left) - cell_margins.left).max(Pt::ZERO);
+ let br = (border_w(&cb.right) - cell_margins.right).max(Pt::ZERO);
+ bl + br
+ })
+ .unwrap_or(Pt::ZERO);
+ let content_width = (inner_width - border_inset_h).max(Pt::ZERO);
+
+ // Recurse into cell content blocks.
+ let cell_blocks =
+ build_cell_blocks(&cell.content, table_style, cond, content_width, ctx, state);
+
+ TableCellInput {
+ blocks: cell_blocks,
+ margins: cell_margins,
+ grid_span: cell.properties.grid_span.unwrap_or(1),
+ shading,
+ cell_borders,
+ vertical_merge: cell.properties.vertical_merge.map(|vm| match vm {
+ model::VerticalMerge::Restart => {
+ crate::render::layout::table::VerticalMergeState::Restart
+ }
+ model::VerticalMerge::Continue => {
+ crate::render::layout::table::VerticalMergeState::Continue
+ }
+ }),
+ vertical_align: valign,
+ }
+}
+
+/// Recursively build cell content blocks.
+///
+/// Paragraphs are resolved with table style + conditional overrides.
+/// Nested tables recurse via `build_table()` → `layout_table()`.
+fn build_cell_blocks(
+ content: &[Block],
+ table_style: Option<&ResolvedStyle>,
+ cond: &CellConditionalFormatting,
+ inner_width: Pt,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+) -> Vec<LayoutBlock> {
+ let mut blocks = Vec::new();
+ let mut pending_dropcap: Option<DropCapInfo> = None;
+
+ for (i, block) in content.iter().enumerate() {
+ match block {
+ Block::Paragraph(p) => {
+ // §17.4.66: every cell must end with a paragraph. When the
+ // last block is an empty paragraph following a table, it is
+ // structural — Word renders it with zero height.
+ if p.content.is_empty()
+ && i > 0
+ && matches!(content[i - 1], Block::Table(_))
+ && i == content.len() - 1
+ {
+ continue;
+ }
+ if let Some(lb) = build_paragraph_block(
+ p,
+ ctx,
+ state,
+ &mut pending_dropcap,
+ table_style,
+ Some(cond),
+ ) {
+ // Split oversized text fragments for narrow cells.
+ let lb = if let LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before,
+ footnotes,
+ floating_images,
+ floating_shapes,
+ } = lb
+ {
+ // Keep the owned vector when no split is needed.
+ let measure = |t: &str, f: &crate::render::layout::fragment::FontProps| {
+ ctx.measurer.measure(t, f)
+ };
+ let fragments =
+ split_oversized_fragments(&fragments, inner_width, Some(&measure))
+ .unwrap_or(fragments);
+ LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before,
+ footnotes,
+ floating_images,
+ floating_shapes,
+ }
+ } else {
+ lb
+ };
+ blocks.push(lb);
+ }
+ }
+ Block::Table(nested_t) => {
+ let built = build_table(nested_t, inner_width, ctx, state);
+ blocks.push(LayoutBlock::Table {
+ rows: built.rows,
+ col_widths: built.col_widths,
+ cell_spacing: built.cell_spacing,
+ border_config: built.border_config,
+ indent: built.indent,
+ alignment: built.alignment,
+ float_info: built.float_info,
+ style_id: nested_t.properties.style_id.clone(),
+ });
+ }
+ _ => {}
+ }
+ }
+
+ blocks
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::layout::table::{CellVAlign, TableCellInput};
+
+ fn cell_with_margins(top: f32, right: f32, bottom: f32, left: f32) -> TableCellInput {
+ TableCellInput {
+ blocks: vec![],
+ margins: geometry::PtEdgeInsets::new(
+ Pt::new(top),
+ Pt::new(right),
+ Pt::new(bottom),
+ Pt::new(left),
+ ),
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ /// Word/Writer row-uniform content-area normalization: when cells in a row
+ /// disagree on `tcMar.top` (or `bottom`), the row-wide *maximum* wins for
+ /// every cell. Verified empirically against MS Word — see
+ /// [`normalize_row_uniform_vertical_insets`] for the experimental
+ /// reproducer and spec references.
+ #[test]
+ fn row_uniform_picks_max_top_and_bottom_across_row() {
+ // Mirrors the Wohnungsübergabe "Keller" row: one cell with
+ // explicit zero top/bottom (the Keller cell after per-side tcMar
+ // cascade) and another with the inherited 57-twip table default
+ // (≈ 2.85 pt) — siblings without a tcMar override.
+ let mut cells = vec![
+ cell_with_margins(0.0, 5.4, 0.0, 5.15), // Keller-like
+ cell_with_margins(2.85, 5.4, 2.85, 5.15), // sibling with table default
+ cell_with_margins(0.0, 5.4, 0.0, 5.15), // another Keller-like
+ ];
+ normalize_row_uniform_vertical_insets(&mut cells);
+
+ for (i, cell) in cells.iter().enumerate() {
+ assert_eq!(
+ cell.margins.top.raw(),
+ 2.85,
+ "cell #{i}: every cell's top inset must equal the row-wide max"
+ );
+ assert_eq!(
+ cell.margins.bottom.raw(),
+ 2.85,
+ "cell #{i}: every cell's bottom inset must equal the row-wide max"
+ );
+ // Horizontal stays per-cell.
+ assert_eq!(cell.margins.left.raw(), 5.15, "left is per-cell");
+ assert_eq!(cell.margins.right.raw(), 5.4, "right is per-cell");
+ }
+ }
+
+ /// Mirrors the `_kellertop500` experiment: a single cell with a `tcMar.top`
+ /// far larger than its siblings becomes the row-wide max, so every cell —
+ /// including the ones with no override — picks up that large top inset.
+ /// In Word, this is observable as the entire row's content shifting down.
+ #[test]
+ fn row_uniform_one_large_cell_top_pushes_whole_row_down() {
+ let mut cells = vec![
+ cell_with_margins(25.0, 5.4, 0.0, 5.15), // Keller with top=25pt
+ cell_with_margins(2.85, 5.4, 2.85, 5.15), // small sibling
+ ];
+ normalize_row_uniform_vertical_insets(&mut cells);
+
+ assert_eq!(
+ cells[1].margins.top.raw(),
+ 25.0,
+ "sibling cell inherits the large top from the dominating cell"
+ );
+ // Bottom max is the smaller cell's 2.85 (Keller bottom stayed 0).
+ assert_eq!(cells[0].margins.bottom.raw(), 2.85);
+ }
+
+ #[test]
+ fn row_uniform_single_cell_row_is_noop() {
+ let mut cells = vec![cell_with_margins(2.85, 5.4, 2.85, 5.15)];
+ let before = cells[0].margins;
+ normalize_row_uniform_vertical_insets(&mut cells);
+ assert_eq!(cells[0].margins, before);
+ }
+
+ #[test]
+ fn row_uniform_handles_empty_row() {
+ let mut cells: Vec<TableCellInput> = vec![];
+ normalize_row_uniform_vertical_insets(&mut cells);
+ // No panic, no work done.
+ assert!(cells.is_empty());
+ }
+
+ /// §17.4.44: `CT_TblWidth` permits `pct` and `auto`, and the spec says both
+ /// are **ignored** for this element — only `dxa` carries a usable value.
+ /// Honouring a percentage here would scale the gap with the table width,
+ /// which is exactly what the spec rules out.
+ #[test]
+ fn cell_spacing_only_honours_dxa() {
+ use crate::model::dimension::Dimension;
+ assert_eq!(
+ resolve_cell_spacing(Some(model::TableMeasure::Twips(Dimension::new(240)))),
+ Pt::new(12.0),
+ "240 twips = 12pt"
+ );
+ for ignored in [
+ Some(model::TableMeasure::Pct(Dimension::new(2500))),
+ Some(model::TableMeasure::Auto),
+ Some(model::TableMeasure::Nil),
+ None,
+ ] {
+ assert_eq!(resolve_cell_spacing(ignored), Pt::ZERO, "{ignored:?}");
+ }
+ }
+
+ /// The spacing is carved *out of* the table, so the slots shrink by exactly
+ /// one spacing in total and keep their proportions.
+ #[test]
+ fn reserving_spacing_shrinks_the_grid_by_exactly_one_spacing() {
+ let widths = vec![Pt::new(60.0), Pt::new(40.0)];
+ let out = reserve_cell_spacing(widths, Pt::new(10.0));
+ let total: Pt = out.iter().copied().sum();
+ assert_eq!(total, Pt::new(90.0), "one spacing removed in total");
+ // Proportions preserved: 60:40 becomes 54:36.
+ assert_eq!(out[0], Pt::new(54.0));
+ assert_eq!(out[1], Pt::new(36.0));
+ }
+
+ /// Zero spacing must be a byte-for-byte no-op — every table that does not
+ /// set `tblCellSpacing` goes through this path.
+ #[test]
+ fn reserving_zero_spacing_leaves_the_grid_untouched() {
+ let widths = vec![Pt::new(60.0), Pt::new(40.0)];
+ assert_eq!(reserve_cell_spacing(widths.clone(), Pt::ZERO), widths);
+ }
+
+ /// A spacing at least as wide as the table leaves nothing to distribute.
+ /// Word caps the value long before this, but the file format does not, and
+ /// scaling by a negative factor would put cells at negative widths.
+ #[test]
+ fn spacing_wider_than_the_table_collapses_columns_rather_than_going_negative() {
+ let widths = vec![Pt::new(30.0), Pt::new(30.0)];
+ let out = reserve_cell_spacing(widths, Pt::new(60.0));
+ assert_eq!(out, vec![Pt::ZERO, Pt::ZERO]);
+ assert!(out.iter().all(|w| *w >= Pt::ZERO));
+ }
+
+ /// §17.4.81: `hRule="auto"` ignores `val`, so the row carries **no** height
+ /// constraint — it is not a zero-height minimum, and not a minimum of the
+ /// stated value either.
+ ///
+ /// Word writes `val="0"` alongside `hRule="auto"` ([MS-OE376] §2.4.77(c)),
+ /// which is why treating `auto` as `AtLeast(val)` was invisible on Word
+ /// output: `AtLeast(0)` constrains nothing. Other producers are not bound by
+ /// that, and a non-zero `val` under `auto` would have become a real minimum.
+ #[test]
+ fn auto_height_rule_carries_no_constraint() {
+ use crate::model::{HeightRule, TableRowHeight};
+ use crate::render::layout::table::RowHeightRule;
+ let to_layout = |rule, twips: i64| -> Option<RowHeightRule> {
+ row_height_rule(TableRowHeight {
+ value: crate::model::dimension::Dimension::new(twips),
+ rule,
+ })
+ };
+ assert!(
+ to_layout(HeightRule::Auto, 1000).is_none(),
+ "auto ignores val entirely"
+ );
+ assert!(matches!(
+ to_layout(HeightRule::AtLeast, 1000),
+ Some(RowHeightRule::AtLeast(_))
+ ));
+ assert!(matches!(
+ to_layout(HeightRule::Exact, 1000),
+ Some(RowHeightRule::Exact(_))
+ ));
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/cell.rs b/crates/liteparse-docx/src/render/layout/cell.rs
new file mode 100644
index 0000000..a341694
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/cell.rs
@@ -0,0 +1,217 @@
+//! Cell layout — narrows constraints by cell margins, lays out child blocks.
+//!
+//! Uses the shared `stack_blocks` function from `section.rs` so that table
+//! cells get the same features as body content (floating images, spacing
+//! collapse, contextual spacing, etc.).
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtEdgeInsets;
+
+use super::section::{CellLine, LayoutBlock, PageParity, stack_blocks};
+
+/// Result of laying out a cell.
+#[derive(Debug)]
+pub struct CellLayout {
+ /// Draw commands relative to the cell's top-left origin.
+ pub commands: Vec<super::draw_command::DrawCommand>,
+ /// Content height (without margins).
+ pub content_height: Pt,
+ /// §17.4.1 row-split cut model, in cell-content coordinates (i.e. *not*
+ /// shifted by the cell margins — the splitter adds `margin_top`). Empty for
+ /// a cell that can't be safely bisected; see [`CellLine`].
+ pub lines: Vec<CellLine>,
+}
+
+/// Lay out blocks inside a table cell.
+///
+/// Receives the full cell width (from column sizing), deflates by margins,
+/// lays out each block sequentially using `stack_blocks`, returns total
+/// content height.
+pub fn layout_cell(
+ blocks: &[LayoutBlock],
+ cell_width: Pt,
+ margins: &PtEdgeInsets,
+ default_line_height: Pt,
+ measure_text: super::paragraph::MeasureTextFn<'_>,
+) -> CellLayout {
+ let content_width = (cell_width - margins.horizontal()).max(Pt::ZERO);
+
+ // §20.4.3.1: a cell is measured before its table is paginated — a row can
+ // split across pages, and the split is decided from these measurements —
+ // so the page this cell lands on, and its parity, do not exist yet. An
+ // `inside`/`outside` float inside a table therefore takes the odd-page
+ // reading. That is the Tier-0 the page and header paths no longer need;
+ // removing it here means making cell measurement page-aware, which is a
+ // far larger change than the anchor resolution itself.
+ let result = stack_blocks(
+ blocks,
+ content_width,
+ default_line_height,
+ measure_text,
+ PageParity::Odd,
+ );
+
+ // Shift all commands by cell margins.
+ let commands = result
+ .commands
+ .into_iter()
+ .map(|mut cmd| {
+ cmd.shift(margins.left, margins.top);
+ cmd
+ })
+ .collect();
+
+ CellLayout {
+ commands,
+ content_height: result.height,
+ // Cut points stay in content coordinates; the shift above applies to
+ // draw commands only. `split.rs` accounts for `margin_top` when
+ // partitioning against them.
+ lines: result.lines,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::layout::draw_command::DrawCommand;
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str, width: f32) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn simple_block(text: &str, width: f32) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, width)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ #[test]
+ fn empty_cell_zero_height() {
+ let result = layout_cell(
+ &[],
+ Pt::new(200.0),
+ &PtEdgeInsets::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert_eq!(result.content_height.raw(), 0.0);
+ assert!(result.commands.is_empty());
+ }
+
+ #[test]
+ fn single_paragraph_in_cell() {
+ let blocks = vec![simple_block("hello", 30.0)];
+ let result = layout_cell(
+ &blocks,
+ Pt::new(200.0),
+ &PtEdgeInsets::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert_eq!(result.content_height.raw(), 14.0);
+ assert!(!result.commands.is_empty());
+ }
+
+ #[test]
+ fn margins_offset_content() {
+ let blocks = vec![simple_block("text", 30.0)];
+ let margins = PtEdgeInsets::new(
+ Pt::new(5.0), // top
+ Pt::new(10.0), // right
+ Pt::new(5.0), // bottom
+ Pt::new(10.0), // left
+ );
+ let result = layout_cell(&blocks, Pt::new(200.0), &margins, Pt::new(14.0), None);
+
+ // Text should be shifted right by left margin
+ if let Some(DrawCommand::Text { position, .. }) = result.commands.first() {
+ assert_eq!(position.x.raw(), 10.0, "left margin applied");
+ assert!(position.y.raw() >= 5.0, "top margin applied");
+ } else {
+ panic!("expected Text command");
+ }
+ }
+
+ #[test]
+ fn margins_narrow_available_width() {
+ // Cell is 100 wide, margins eat 60 (left=30, right=30), leaving 40 for content
+ // Two fragments of 30 each = 60 > 40, so they should wrap
+ let blocks = vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("aa ", 30.0), text_frag("bb", 30.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }];
+ let margins = PtEdgeInsets::new(Pt::ZERO, Pt::new(30.0), Pt::ZERO, Pt::new(30.0));
+ let result = layout_cell(&blocks, Pt::new(100.0), &margins, Pt::new(14.0), None);
+
+ // Should wrap to 2 lines → height = 28
+ assert_eq!(result.content_height.raw(), 28.0);
+ }
+
+ #[test]
+ fn two_paragraphs_stack_vertically() {
+ let blocks = vec![simple_block("first", 30.0), simple_block("second", 40.0)];
+ let result = layout_cell(
+ &blocks,
+ Pt::new(200.0),
+ &PtEdgeInsets::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert_eq!(result.content_height.raw(), 28.0, "14 + 14");
+
+ let text_cmds: Vec<_> = result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, text, .. } => Some((text.clone(), position.y)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(text_cmds.len(), 2);
+ assert!(
+ text_cmds[1].1 > text_cmds[0].1,
+ "second paragraph should be below first"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/float.rs b/crates/liteparse-docx/src/render/layout/float.rs
new file mode 100644
index 0000000..272a22d
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/float.rs
@@ -0,0 +1,341 @@
+//! Floating element layout — positioned outside the normal flow.
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtRect;
+
+/// §17.4.56 / §20.4.2: source of a floating element.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FloatSource {
+ /// §20.4.2: floating image — wraps text for all overlapping lines.
+ Image,
+ /// §20.4.2: floating DrawingML shape — wraps text for all overlapping
+ /// lines. Semantically identical to `Image` for line narrowing; kept
+ /// as a distinct variant so the stacker can detect shape-owned rects
+ /// when debugging.
+ Shape,
+ /// §17.4.56: floating table — only wraps text for the paragraph that
+ /// was active when the table was encountered. Subsequent paragraphs
+ /// clear below the table.
+ Table {
+ /// Block index of the paragraph that owns this floating table.
+ /// Only this paragraph (and earlier ones) should wrap around it.
+ owner_block_idx: usize,
+ },
+}
+
+impl FloatSource {
+ /// §17.4.57 — whether `tblOverlap` governs collisions with this float.
+ ///
+ /// It does not, for images and shapes. `tblOverlap` is defined purely
+ /// between *floating tables*: "whether the current table shall allow
+ /// other floating tables to overlap its extents". A table may still
+ /// visually overlap a floating image, and Word lets it.
+ ///
+ /// Named rather than spelled `matches!(.., Table { .. })` at the use
+ /// site because the interesting content is the spec rule, not the
+ /// pattern — the anchor resolver reads as "skip what tblOverlap
+ /// doesn't govern".
+ pub fn participates_in_table_overlap(&self) -> bool {
+ matches!(self, Self::Table { .. })
+ }
+}
+
+/// A floating element that affects text layout on the current page.
+#[derive(Debug, Clone)]
+pub struct ActiveFloat {
+ /// Absolute x position on page.
+ pub page_x: Pt,
+ /// Top of the float on the page.
+ pub page_y_start: Pt,
+ /// Bottom of the float on the page.
+ pub page_y_end: Pt,
+ /// Width of the float.
+ pub width: Pt,
+ /// Source of this float (image vs shape vs table).
+ pub source: FloatSource,
+ /// §20.4.2.20 ST_WrapText — which sides of the float text may flow on.
+ /// `Table` sources default to `BothSides`; images/shapes carry the
+ /// value from their `wrapSquare/Tight/Through` element.
+ pub wrap_text: WrapTextSide,
+}
+
+/// §20.4.2.20 ST_WrapText — side(s) of a float on which text may flow.
+///
+/// Duplicated in the layout layer to decouple it from the model enum so
+/// `float.rs` doesn't depend on `crate::model`; a `From` impl bridges the
+/// two.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WrapTextSide {
+ /// Text flows on both sides (default).
+ BothSides,
+ /// Text flows on the left only — float pushed to the right edge.
+ Left,
+ /// Text flows on the right only — float pushed to the left edge.
+ Right,
+ /// Text flows on the larger of the two sides.
+ Largest,
+}
+
+impl From<crate::model::WrapText> for WrapTextSide {
+ fn from(w: crate::model::WrapText) -> Self {
+ match w {
+ crate::model::WrapText::BothSides => Self::BothSides,
+ crate::model::WrapText::Left => Self::Left,
+ crate::model::WrapText::Right => Self::Right,
+ crate::model::WrapText::Largest => Self::Largest,
+ }
+ }
+}
+
+impl ActiveFloat {
+ /// Whether a given y-position overlaps this float's vertical range.
+ pub fn overlaps_y(&self, y: Pt) -> bool {
+ y >= self.page_y_start && y < self.page_y_end
+ }
+
+ /// The rectangle occupied by this float.
+ pub fn rect(&self) -> PtRect {
+ PtRect::from_xywh(
+ self.page_x,
+ self.page_y_start,
+ self.width,
+ self.page_y_end - self.page_y_start,
+ )
+ }
+}
+
+/// Compute how much the available width should be reduced on a given line
+/// due to active floating images.
+///
+/// Returns (indent_left, indent_right) — additional indentation to avoid floats.
+/// `line_y` is the top of the line, `line_height` is the line's height.
+/// A line overlaps a float if any part of the line's vertical range intersects
+/// the float's vertical range.
+pub fn float_adjustments(
+ floats: &[ActiveFloat],
+ line_y: Pt,
+ page_x: Pt,
+ content_width: Pt,
+) -> (Pt, Pt) {
+ float_adjustments_with_height(floats, line_y, Pt::ZERO, page_x, content_width)
+}
+
+/// Like `float_adjustments` but with explicit line height for overlap checking.
+///
+/// Honours §20.4.2.20 `wrap_text` per float:
+/// * `BothSides` — text may flow on either side; narrow the closer side.
+/// * `Left` — text only on the left; always push text to the left of the float.
+/// * `Right` — text only on the right; always push text to the right of the float.
+/// * `Largest` — text only on the side with more remaining width.
+pub fn float_adjustments_with_height(
+ floats: &[ActiveFloat],
+ line_y: Pt,
+ line_height: Pt,
+ page_x: Pt,
+ content_width: Pt,
+) -> (Pt, Pt) {
+ let mut indent_left = Pt::ZERO;
+ let mut indent_right = Pt::ZERO;
+ let line_bottom = line_y + line_height;
+
+ for float in floats {
+ // Check if any part of the line overlaps the float vertically.
+ if line_bottom <= float.page_y_start || line_y >= float.page_y_end {
+ continue;
+ }
+
+ let float_right_edge = float.page_x + float.width;
+ let content_right = page_x + content_width;
+ let left_shift = (float_right_edge - page_x).max(Pt::ZERO);
+ let right_shift = (content_right - float.page_x).max(Pt::ZERO);
+
+ // Choose the side to narrow per `wrap_text`.
+ // * `Left` → text on the left of the float → narrow from the right.
+ // * `Right` → text on the right of the float → narrow from the left.
+ // * `Largest` → keep the larger remaining side; narrow the smaller.
+ // * `BothSides`→ narrow the side the float is closer to.
+ let narrow_left = match float.wrap_text {
+ WrapTextSide::Right => true,
+ WrapTextSide::Left => false,
+ WrapTextSide::Largest => {
+ let left_remaining = float.page_x - page_x;
+ let right_remaining = content_right - float_right_edge;
+ left_remaining < right_remaining
+ }
+ WrapTextSide::BothSides => {
+ let content_center = page_x + content_width * 0.5;
+ let float_center = float.page_x + float.width * 0.5;
+ float_center < content_center
+ }
+ };
+
+ if narrow_left {
+ if left_shift > indent_left {
+ indent_left = left_shift;
+ }
+ } else if right_shift > indent_right {
+ indent_right = right_shift;
+ }
+ }
+
+ (indent_left, indent_right)
+}
+
+/// Remove floats that the cursor has passed below.
+pub fn prune_floats(floats: &mut Vec<ActiveFloat>, cursor_y: Pt) {
+ floats.retain(|f| cursor_y < f.page_y_end);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn no_floats_no_adjustment() {
+ let (l, r) = float_adjustments(&[], Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ assert_eq!(l.raw(), 0.0);
+ assert_eq!(r.raw(), 0.0);
+ }
+
+ #[test]
+ fn float_on_left_pushes_text_right() {
+ let floats = vec![ActiveFloat {
+ page_x: Pt::new(72.0), // at left margin
+ page_y_start: Pt::new(80.0),
+ page_y_end: Pt::new(200.0),
+ width: Pt::new(100.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ }];
+ let (l, r) = float_adjustments(&floats, Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ assert_eq!(l.raw(), 100.0, "push right by float width");
+ assert_eq!(r.raw(), 0.0);
+ }
+
+ #[test]
+ fn float_on_right_pushes_text_left() {
+ let floats = vec![ActiveFloat {
+ page_x: Pt::new(440.0), // near right margin
+ page_y_start: Pt::new(80.0),
+ page_y_end: Pt::new(200.0),
+ width: Pt::new(100.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ }];
+ let (l, r) = float_adjustments(&floats, Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ assert_eq!(l.raw(), 0.0);
+ assert!(r.raw() > 0.0, "should indent from right");
+ }
+
+ #[test]
+ fn float_not_overlapping_line_no_adjustment() {
+ let floats = vec![ActiveFloat {
+ page_x: Pt::new(72.0),
+ page_y_start: Pt::new(200.0),
+ page_y_end: Pt::new(300.0),
+ width: Pt::new(100.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ }];
+ let (l, r) = float_adjustments(&floats, Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ assert_eq!(l.raw(), 0.0, "line is above float");
+ assert_eq!(r.raw(), 0.0);
+ }
+
+ #[test]
+ fn prune_removes_passed_floats() {
+ let mut floats = vec![
+ ActiveFloat {
+ page_x: Pt::ZERO,
+ page_y_start: Pt::new(0.0),
+ page_y_end: Pt::new(100.0),
+ width: Pt::new(50.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ },
+ ActiveFloat {
+ page_x: Pt::ZERO,
+ page_y_start: Pt::new(0.0),
+ page_y_end: Pt::new(300.0),
+ width: Pt::new(50.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ },
+ ];
+ prune_floats(&mut floats, Pt::new(150.0));
+ assert_eq!(floats.len(), 1, "first float pruned, second still active");
+ }
+
+ #[test]
+ fn wrap_text_right_forces_narrow_from_left_even_if_float_is_right() {
+ // Float at right, wrap_text=Right → text flows on right of float,
+ // so line is narrowed from the LEFT (pushed right past the float).
+ let floats = vec![ActiveFloat {
+ page_x: Pt::new(440.0),
+ page_y_start: Pt::new(80.0),
+ page_y_end: Pt::new(200.0),
+ width: Pt::new(100.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::Right,
+ }];
+ let (l, r) = float_adjustments(&floats, Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ assert!(
+ l.raw() > 0.0,
+ "text on right of float means narrow from left"
+ );
+ assert_eq!(r.raw(), 0.0);
+ }
+
+ #[test]
+ fn wrap_text_left_forces_narrow_from_right_even_if_float_is_left() {
+ let floats = vec![ActiveFloat {
+ page_x: Pt::new(72.0),
+ page_y_start: Pt::new(80.0),
+ page_y_end: Pt::new(200.0),
+ width: Pt::new(100.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::Left,
+ }];
+ let (l, r) = float_adjustments(&floats, Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ assert_eq!(l.raw(), 0.0);
+ assert!(
+ r.raw() > 0.0,
+ "text on left of float means narrow from right"
+ );
+ }
+
+ #[test]
+ fn wrap_text_largest_picks_wider_remaining_side() {
+ // Float centered slightly left of center → right remaining is larger.
+ // `Largest` should keep text on the right (narrow from the left).
+ let floats = vec![ActiveFloat {
+ page_x: Pt::new(200.0),
+ page_y_start: Pt::new(80.0),
+ page_y_end: Pt::new(200.0),
+ width: Pt::new(50.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::Largest,
+ }];
+ let (l, r) = float_adjustments(&floats, Pt::new(100.0), Pt::new(72.0), Pt::new(468.0));
+ // Left remaining: 200-72 = 128; right remaining: (72+468) - (200+50) = 290.
+ // Right is larger → narrow from the left.
+ assert!(l.raw() > 0.0);
+ assert_eq!(r.raw(), 0.0);
+ }
+
+ #[test]
+ fn overlaps_y_boundary() {
+ let f = ActiveFloat {
+ page_x: Pt::ZERO,
+ page_y_start: Pt::new(100.0),
+ page_y_end: Pt::new(200.0),
+ width: Pt::new(50.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ };
+ assert!(!f.overlaps_y(Pt::new(99.0)));
+ assert!(f.overlaps_y(Pt::new(100.0)));
+ assert!(f.overlaps_y(Pt::new(150.0)));
+ assert!(!f.overlaps_y(Pt::new(200.0)));
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/fragment/collect.rs b/crates/liteparse-docx/src/render/layout/fragment/collect.rs
new file mode 100644
index 0000000..5abb845
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/fragment/collect.rs
@@ -0,0 +1,1686 @@
+use std::rc::Rc;
+
+use crate::model::{
+ Block, FieldCharType, Inline, NoteId, RunElement, RunProperties, TextRun, VerticalAlign,
+};
+use crate::render::dimension::Pt;
+use crate::render::emoji::cluster::EmojiCluster;
+use crate::render::geometry::PtSize;
+use crate::render::resolve::color::RgbColor;
+
+use super::segment::{InlineUnit, SegmentPiece, build_inline_units};
+use super::text::{
+ TextRunStyle, emit_emoji_or_fallback, emit_text_fragments, emit_text_words,
+ resolve_highlight_color,
+};
+use super::{
+ FontProps, Fragment, FragmentBorder, LinkTarget, SUBSCRIPT_HEIGHT_OFFSET_RATIO,
+ SUPERSCRIPT_ASCENT_OFFSET_RATIO, SUPERSCRIPT_FONT_SIZE_RATIO, TextMetrics, font_props_from_run,
+ to_roman_lower,
+};
+
+/// §17.11.12: a footnote reference recorded while walking a paragraph's inlines.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct RecordedFootnote {
+ /// The referenced note.
+ pub id: NoteId,
+ /// The sequential display number emitted as this reference's superscript.
+ pub display: u32,
+}
+
+/// §17.11.12: footnote numbering state threaded through fragment collection.
+///
+/// The display counter and the record of *which* notes were referenced advance
+/// at a single site (the private `record` method), so the footnote body a
+/// caller renders can never disagree with the superscript mark this walk
+/// emitted.
+///
+/// This replaced a design where the counter was advanced by this **recursive**
+/// walk (which descends into hyperlinks, non-substituted fields, MCE
+/// fallbacks, and VML text boxes) while callers re-derived the reference list
+/// from a **flat** scan of the paragraph's top-level inlines. The two walkers
+/// disagreed for any nested reference: its body was never emitted, and when it
+/// preceded a top-level reference the body's number no longer matched the mark.
+#[derive(Default, Debug)]
+pub struct FootnoteTracker {
+ /// Display number of the most recently emitted reference.
+ last_display: u32,
+ /// References recorded since the last [`FootnoteTracker::take_pending`].
+ pending: Vec<RecordedFootnote>,
+}
+
+impl FootnoteTracker {
+ /// Assign the next display number to `id`, record it, and return the number.
+ fn record(&mut self, id: NoteId) -> u32 {
+ self.last_display += 1;
+ self.pending.push(RecordedFootnote {
+ id,
+ display: self.last_display,
+ });
+ self.last_display
+ }
+
+ /// Take the references recorded since the last call, in encounter order.
+ ///
+ /// Every caller of [`collect_fragments`] must drain — including those that
+ /// don't render footnote bodies (headers/footers, footnote bodies
+ /// themselves). Otherwise their references leak into the next paragraph's
+ /// batch and are rendered against the wrong host.
+ pub fn take_pending(&mut self) -> Vec<RecordedFootnote> {
+ std::mem::take(&mut self.pending)
+ }
+}
+
+/// §17.3.2.4: convert a run-level [`crate::model::Border`] into a render-side
+/// [`FragmentBorder`], filtering out the spec's "no border" styles.
+///
+/// `<w:bdr w:val="nil"/>` and `<w:bdr w:val="none"/>` (§17.18.2 ST_Border) are
+/// kept apart by the model, because table border conflict resolution needs the
+/// difference — but a run border has no adjacent edge to conflict with, so here
+/// they are genuinely equivalent and `draws_nothing` covers both. The model
+/// preserves the explicit `Some` so it can override an inherited border in the
+/// §17.7.2 cascade; at the render boundary we drop it, otherwise the painter
+/// would draw a hairline box around every word.
+pub(super) fn run_border_to_fragment(
+ border: Option<&crate::model::Border>,
+) -> Option<FragmentBorder> {
+ let b = border?;
+ if b.style.draws_nothing() {
+ return None;
+ }
+ Some(FragmentBorder {
+ width: Pt::from(b.width),
+ color: crate::render::resolve::color::resolve_color(
+ b.color,
+ crate::render::resolve::color::ColorContext::Text,
+ ),
+ space: Pt::new(b.space.raw() as f32),
+ })
+}
+
+/// §17.7.2: resolve the effective styling of a single run by walking the
+/// cascade (direct → character style → paragraph run defaults), then
+/// translating to render-side `FontProps` + `TextRunStyle`.
+///
+/// This is the single source of truth for run-level styling. Both the
+/// per-run path (`Discrete TextRun`) and the per-segment-piece path
+/// (cross-run cluster reassembly via `segment.rs`) call it — for cross-
+/// run clusters, the *base run*'s styling drives the entire piece per
+/// the design in `fragment/segment.rs`.
+#[allow(clippy::too_many_arguments)] // the cascade has many independent inputs by spec
+fn resolve_run_styling<F>(
+ tr: &TextRun,
+ default_family: &str,
+ default_size: Pt,
+ default_color: RgbColor,
+ resolved_styles: Option<
+ &std::collections::HashMap<
+ crate::model::StyleId,
+ crate::render::resolve::styles::ResolvedStyle,
+ >,
+ >,
+ paragraph_run_defaults: Option<&RunProperties>,
+ theme: Option<&crate::model::Theme>,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+ measure_text: &F,
+) -> (FontProps, TextRunStyle)
+where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
+{
+ let mut effective_props = tr.properties.clone();
+ // §17.3.2.26: resolve theme font references before merging.
+ if let Some(th) = theme {
+ crate::render::resolve::fonts::resolve_font_set_themes(&mut effective_props.fonts, th);
+ }
+ if let (Some(style_id), Some(styles)) = (&tr.style_id, resolved_styles) {
+ if let Some(resolved_style) = styles.get(style_id) {
+ crate::render::resolve::properties::merge_run_properties(
+ &mut effective_props,
+ &resolved_style.run,
+ );
+ }
+ }
+ if let Some(para_run) = paragraph_run_defaults {
+ crate::render::resolve::properties::merge_run_properties(&mut effective_props, para_run);
+ }
+
+ let mut font = font_props_from_run(&effective_props, default_family, default_size, auto_fit);
+ let color = effective_props
+ .color
+ .map(|c| {
+ crate::render::resolve::color::resolve_color(
+ c,
+ crate::render::resolve::color::ColorContext::Text,
+ )
+ })
+ .unwrap_or(default_color);
+ // §17.3.2.32 / §17.3.2.15: shading or highlight as background.
+ let shading = effective_props
+ .shading
+ .as_ref()
+ .map(|s| {
+ crate::render::resolve::color::resolve_color(
+ s.fill,
+ crate::render::resolve::color::ColorContext::Background,
+ )
+ })
+ // §17.18.40: HighlightColor::None is the explicit "no highlight"
+ // override and yields no fill, so use `and_then` to thread the
+ // Option through.
+ .or_else(|| effective_props.highlight.and_then(resolve_highlight_color));
+
+ // §17.3.2.42: vertical alignment (super/sub).
+ let mut baseline_offset = match effective_props.vertical_align {
+ Some(VerticalAlign::Superscript) => {
+ let (_, base_m) = measure_text("X", &font);
+ font.size = font.size * SUPERSCRIPT_FONT_SIZE_RATIO;
+ -(base_m.ascent * SUPERSCRIPT_ASCENT_OFFSET_RATIO)
+ }
+ Some(VerticalAlign::Subscript) => {
+ let (_, base_m) = measure_text("X", &font);
+ font.size = font.size * SUPERSCRIPT_FONT_SIZE_RATIO;
+ base_m.height() * SUBSCRIPT_HEIGHT_OFFSET_RATIO
+ }
+ _ => Pt::ZERO,
+ };
+ // §17.3.2.19: w:position — vertical baseline offset in half-points.
+ if let Some(pos) = effective_props.position {
+ baseline_offset += Pt::from(pos);
+ }
+
+ // §17.3.2.4: run-level border (filtered to drop the no-border styles).
+ let border = run_border_to_fragment(effective_props.border.as_ref());
+
+ let text_style = TextRunStyle {
+ color,
+ shading,
+ border,
+ baseline_offset,
+ };
+ (font, text_style)
+}
+
+/// §17.16.4.1: context for evaluating dynamic fields (PAGE, NUMPAGES).
+#[derive(Clone, Copy, Default)]
+pub struct FieldContext {
+ /// Current page number (1-based).
+ pub page_number: Option<usize>,
+ /// Total page count in the document.
+ pub num_pages: Option<usize>,
+}
+
+/// §17.16.4.1: evaluate a parsed field instruction against the current context.
+/// Returns the substituted text for PAGE/NUMPAGES, or None for other fields
+/// or when no context is available.
+fn evaluate_field_instruction(
+ instruction: &crate::field::FieldInstruction,
+ ctx: FieldContext,
+) -> Option<String> {
+ match instruction {
+ crate::field::FieldInstruction::Page { .. } => ctx.page_number.map(|n| n.to_string()),
+ crate::field::FieldInstruction::NumPages { .. } => ctx.num_pages.map(|n| n.to_string()),
+ _ => None,
+ }
+}
+
+/// §17.16.19 MERGEFORMAT — source of formatting for a complex field's
+/// substituted dynamic value. Resolved when the `Separate` fldChar is
+/// reached so the lookup honors the OOXML "first result run wins" rule
+/// regardless of how the inline-units pre-pass packaged the result zone:
+/// an empty `<w:t></w:t>` placeholder run carries `<w:rPr>` but does not
+/// surface as its own unit (segment joining drops it as 0 chars), yet
+/// is still the spec's first-result-run for formatting purposes.
+#[derive(Clone, Copy)]
+pub(super) enum FieldFormatSource<'a> {
+ /// First TextRun encountered between `Separate` and the matching
+ /// `End` at the outer field's nesting level. Its `<w:rPr>` provides
+ /// font family, size, bold, italic, color per §17.16.19.
+ FirstResultRun(&'a TextRun),
+ /// No result TextRun is present at the outer level. The
+ /// substitution falls back to paragraph default font properties at
+ /// emission time.
+ ParagraphDefaults,
+}
+
+/// Locate the formatting source for the complex field whose `Separate`
+/// fldChar sits at `inlines[separate_idx]`. Walks raw inlines (not
+/// unit-packaged), tracking nesting via `Begin` / `End` counts, and
+/// returns at the first top-level `TextRun` or at the matching `End`,
+/// whichever comes first.
+///
+/// "Top level" = the depth of the field whose `Separate` triggered the
+/// lookup. Text runs that sit inside a nested field's own result zone
+/// belong to that nested field's substitution and are skipped — they
+/// are not the outer field's first result run.
+///
+/// Malformed input (no matching `End`) returns `ParagraphDefaults`
+/// rather than panicking.
+pub(super) fn resolve_field_format_source(
+ inlines: &[Inline],
+ separate_idx: usize,
+) -> FieldFormatSource<'_> {
+ let mut depth: i32 = 0;
+ for inline in &inlines[separate_idx + 1..] {
+ match inline {
+ Inline::FieldChar(fc) => match fc.field_char_type {
+ FieldCharType::Begin => depth += 1,
+ FieldCharType::End => {
+ if depth == 0 {
+ return FieldFormatSource::ParagraphDefaults;
+ }
+ depth -= 1;
+ }
+ FieldCharType::Separate => {
+ // Belongs to a nested field; the outer scan ignores it.
+ }
+ },
+ Inline::TextRun(tr) if depth == 0 => {
+ return FieldFormatSource::FirstResultRun(tr.as_ref());
+ }
+ _ => {}
+ }
+ }
+ FieldFormatSource::ParagraphDefaults
+}
+
+/// Emit the substituted text of a complex field using the formatting
+/// resolved at `Separate` (§17.16.19). When the source is
+/// [`FieldFormatSource::FirstResultRun`] the substitution inherits font
+/// family, size, bold, italic, color, etc. from that run's `<w:rPr>` —
+/// matching what Word renders when it updates a dynamic field in place.
+/// When no result run was present in the field zone the substitution
+/// falls back to paragraph defaults.
+#[allow(clippy::too_many_arguments)]
+fn emit_field_substitution<F>(
+ text: &str,
+ source: Option<&FieldFormatSource<'_>>,
+ default_family: &str,
+ default_size: Pt,
+ default_color: RgbColor,
+ resolved_styles: Option<
+ &std::collections::HashMap<
+ crate::model::StyleId,
+ crate::render::resolve::styles::ResolvedStyle,
+ >,
+ >,
+ paragraph_run_defaults: Option<&RunProperties>,
+ theme: Option<&crate::model::Theme>,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+ hyperlink_url: Option<&LinkTarget>,
+ measure_text: &F,
+ measurer: Option<&crate::render::layout::measurer::TextMeasurer<'_>>,
+ fragments: &mut Vec<Fragment>,
+) where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
+{
+ let (font, text_style) = match source {
+ Some(FieldFormatSource::FirstResultRun(tr)) => resolve_run_styling(
+ tr,
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults,
+ theme,
+ auto_fit,
+ measure_text,
+ ),
+ _ => (
+ FontProps {
+ family: Rc::from(default_family),
+ size: auto_fit.scale_font(default_size),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ },
+ TextRunStyle {
+ color: default_color,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ },
+ ),
+ };
+ emit_text_fragments(
+ text,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ measurer,
+ fragments,
+ );
+}
+
+/// Build a text fragment for a substituted field value, using the paragraph's
+/// default font properties.
+fn make_field_text_fragment<F>(
+ text: Rc<str>,
+ default_family: &str,
+ default_size: Pt,
+ default_color: crate::render::resolve::color::RgbColor,
+ measure_text: &F,
+) -> Fragment
+where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
+{
+ let font = FontProps {
+ family: Rc::from(default_family),
+ size: default_size,
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ };
+ let (w, m) = measure_text(&text, &font);
+ Fragment::Text {
+ text,
+ font: Rc::new(font),
+ color: default_color,
+ shading: None,
+ border: None,
+ width: w,
+ trimmed_width: w,
+ metrics: m,
+ hyperlink_url: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+}
+
+/// Invariant context threaded through all recursive `collect_fragments` calls.
+pub struct FragmentCtx<'a> {
+ pub default_family: &'a str,
+ pub default_size: Pt,
+ pub default_color: RgbColor,
+ pub resolved_styles: Option<
+ &'a std::collections::HashMap<
+ crate::model::StyleId,
+ crate::render::resolve::styles::ResolvedStyle,
+ >,
+ >,
+ pub paragraph_run_defaults: Option<&'a RunProperties>,
+ pub theme: Option<&'a crate::model::Theme>,
+ /// Measurer used by the emoji pipeline for typeface resolution and
+ /// raster-backend metrics. `None` disables the emoji path entirely —
+ /// callers without a font registry (most unit tests) pass `None` and
+ /// emoji codepoints flow through the existing text path unchanged.
+ pub measurer: Option<&'a crate::render::layout::measurer::TextMeasurer<'a>>,
+ /// §20.1.2.1.18: the `a:normAutofit` shrink of the enclosing shape text
+ /// body. [`ShapeAutoFit::NONE`] everywhere else.
+ ///
+ /// [`ShapeAutoFit::NONE`]: crate::render::layout::ShapeAutoFit::NONE
+ pub auto_fit: crate::render::layout::ShapeAutoFit,
+}
+
+/// Walk inline content and collect fragments.
+/// `measure_text` is a callback that measures text width/height/ascent for a given font.
+/// `resolved_styles` is used to look up character styles (w:rStyle) on text runs.
+///
+/// Returns fragments suitable for the line-fitting algorithm.
+pub fn collect_fragments<F>(
+ inlines: &[Inline],
+ ctx: &FragmentCtx<'_>,
+ hyperlink_url: Option<&LinkTarget>,
+ measure_text: &F,
+ footnotes: &mut FootnoteTracker,
+ endnote_counter: &mut u32,
+ field_ctx: FieldContext,
+) -> Vec<Fragment>
+where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics), // (width, metrics)
+{
+ let default_family = ctx.default_family;
+ let default_size = ctx.default_size;
+ let default_color = ctx.default_color;
+ let resolved_styles = ctx.resolved_styles;
+ let paragraph_run_defaults = ctx.paragraph_run_defaults;
+ let theme = ctx.theme;
+ let auto_fit = ctx.auto_fit;
+ let mut fragments = Vec::new();
+ let mut field_depth: i32 = 0; // tracks nested complex field state
+ let mut field_instr = String::new(); // accumulated instruction text for current complex field
+ // §17.16.19: field substitution state for complex fields.
+ // Pending = substitution text waiting for the first result TextRun's formatting.
+ // Emitted = substitution was rendered, skip remaining result TextRuns until End.
+ let mut field_sub_pending: Option<String> = None;
+ let mut field_sub_emitted = false;
+
+ // §17.16.19 MERGEFORMAT — pre-resolve formatting for each complex
+ // field's substitution against raw inlines, so empty placeholder
+ // result runs (`<w:t></w:t>` — swallowed by `build_inline_units`
+ // because they contribute 0 chars) still surface their `<w:rPr>`.
+ // One entry per `Separate` fldChar, consumed in order.
+ let field_format_sources: Vec<FieldFormatSource<'_>> = inlines
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, inl)| match inl {
+ Inline::FieldChar(fc) if matches!(fc.field_char_type, FieldCharType::Separate) => {
+ Some(resolve_field_format_source(inlines, idx))
+ }
+ _ => None,
+ })
+ .collect();
+ let mut field_format_idx: usize = 0;
+ let mut current_field_format: Option<FieldFormatSource<'_>> = None;
+ // Pre-pass: join consecutive text-only TextRuns into segments so
+ // UAX #29 grapheme clusters reassemble across `<w:rFonts>`-induced
+ // run splits (keycap `1️⃣`, ZWJ family, modifier sequence, …).
+ let units = build_inline_units(inlines);
+ for unit in units {
+ match unit {
+ InlineUnit::TextSegment(seg) => {
+ // Field state (mirrors the per-run logic below). Field chars
+ // appear as Discrete Inlines and break segment joining, so
+ // a TextSegment is always entirely inside one field zone.
+ if field_depth > 0 || field_sub_emitted {
+ continue;
+ }
+
+ // §17.16.19: pending substitution uses the segment's first run
+ // for formatting (per cross-run cluster cascade rule).
+ if let Some(sub) = field_sub_pending.take() {
+ let base_run = seg.char_runs()[0];
+ let (font, text_style) = resolve_run_styling(
+ base_run,
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults,
+ theme,
+ auto_fit,
+ measure_text,
+ );
+ field_sub_emitted = true;
+ emit_text_fragments(
+ &sub,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ ctx.measurer,
+ &mut fragments,
+ );
+ continue;
+ }
+
+ // Normal segment: classify and emit each piece using its
+ // own (or for emoji, base) run's resolved styling.
+ for piece in seg.classify() {
+ match piece {
+ SegmentPiece::Text { run, text } => {
+ let (font, text_style) = resolve_run_styling(
+ run,
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults,
+ theme,
+ auto_fit,
+ measure_text,
+ );
+ // Pre-classified text: bypass cluster::classify
+ // by going straight to the word-split path.
+ emit_text_words(
+ &text,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ &mut fragments,
+ );
+ }
+ SegmentPiece::Emoji {
+ base_run,
+ text,
+ presentation,
+ structure,
+ } => {
+ let (font, text_style) = resolve_run_styling(
+ base_run,
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults,
+ theme,
+ auto_fit,
+ measure_text,
+ );
+ if let Some(measurer) = ctx.measurer {
+ let cluster = EmojiCluster {
+ text: &text,
+ presentation,
+ structure,
+ };
+ emit_emoji_or_fallback(
+ &cluster,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ measurer,
+ &mut fragments,
+ );
+ } else {
+ // No measurer (test path): fall through to
+ // text — the cluster's codepoints survive
+ // in the PDF text stream verbatim.
+ emit_text_words(
+ &text,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ &mut fragments,
+ );
+ }
+ }
+ }
+ }
+ }
+ InlineUnit::Discrete(inline) => match inline {
+ Inline::TextRun(tr) => {
+ // A text-only TextRun would have been a TextSegment; this
+ // branch handles runs whose content includes Tab,
+ // LineBreak, PageBreak, ColumnBreak, or
+ // LastRenderedPageBreak.
+ if field_depth > 0 || field_sub_emitted {
+ continue;
+ }
+
+ let (font, text_style) = resolve_run_styling(
+ tr,
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults,
+ theme,
+ auto_fit,
+ measure_text,
+ );
+
+ if field_sub_pending.is_some() {
+ let sub = field_sub_pending.take().unwrap();
+ field_sub_emitted = true;
+ emit_text_fragments(
+ &sub,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ ctx.measurer,
+ &mut fragments,
+ );
+ } else {
+ for element in &tr.content {
+ match element {
+ RunElement::Text(text) => {
+ emit_text_fragments(
+ text,
+ &font,
+ &text_style,
+ hyperlink_url,
+ measure_text,
+ ctx.measurer,
+ &mut fragments,
+ );
+ }
+ RunElement::Tab => {
+ fragments.push(Fragment::Tab {
+ line_height: font.size,
+ // §17.3.1.38: a leader on this tab is
+ // drawn in the tab run's own formatting.
+ font: Rc::new(font.clone()),
+ color: text_style.color,
+ fitting_width: None,
+ });
+ }
+ RunElement::PositionTab(ptab) => {
+ fragments.push(Fragment::PTab {
+ align: ptab.alignment,
+ relative_to: ptab.relative_to,
+ leader: ptab.leader.into(),
+ line_height: font.size,
+ font: Rc::new(font.clone()),
+ color: text_style.color,
+ });
+ }
+ RunElement::LineBreak(_) => {
+ fragments.push(Fragment::LineBreak {
+ line_height: font.size,
+ });
+ }
+ RunElement::PageBreak => {
+ fragments.push(Fragment::PageBreak {
+ line_height: font.size,
+ });
+ }
+ RunElement::ColumnBreak => {
+ fragments.push(Fragment::ColumnBreak);
+ }
+ RunElement::LastRenderedPageBreak => {}
+ }
+ }
+ }
+ }
+ Inline::Image(img) => {
+ // Only render INLINE images as fragments.
+ // Anchor (floating) images are handled separately in build.rs.
+ if matches!(img.placement, crate::model::ImagePlacement::Inline { .. }) {
+ if let Some(rel_id) =
+ crate::render::resolve::images::extract_image_rel_id(img)
+ {
+ let w = Pt::from(img.extent.width);
+ let h = Pt::from(img.extent.height);
+ fragments.push(Fragment::Image {
+ size: PtSize::new(w, h),
+ rel_id: rel_id.as_str().to_string(),
+ image_data: None,
+ src_rect: crate::render::resolve::images::extract_src_rect(img),
+ });
+ }
+ }
+ }
+ Inline::Hyperlink(link) => {
+ // Preserve the external/internal kind as a closed ADT so
+ // the emitter routes external→URI and internal→GoTo without
+ // guessing from the string (§17.16.22).
+ // One allocation per `w:hyperlink`, shared by every word
+ // fragment inside it and every command they emit.
+ let target: Option<LinkTarget> = match &link.target {
+ crate::model::HyperlinkTarget::ExternalUrl(url) => {
+ Some(LinkTarget::External(Rc::from(url.as_str())))
+ }
+ crate::model::HyperlinkTarget::Internal { anchor } => {
+ Some(LinkTarget::Internal(Rc::from(anchor.as_str())))
+ }
+ // An unresolved rId (no matching relationship) has no link.
+ crate::model::HyperlinkTarget::ExternalRel(_) => None,
+ };
+ let mut sub = collect_fragments(
+ &link.content,
+ ctx,
+ target.as_ref(),
+ measure_text,
+ footnotes,
+ endnote_counter,
+ field_ctx,
+ );
+ fragments.append(&mut sub);
+ }
+ Inline::Field(field) => {
+ // §17.16.18: simple field — check for dynamic substitution.
+ let substituted = evaluate_field_instruction(&field.instruction, field_ctx);
+ if let Some(text) = substituted {
+ fragments.push(make_field_text_fragment(
+ Rc::from(text.as_str()),
+ default_family,
+ default_size,
+ default_color,
+ measure_text,
+ ));
+ } else {
+ let mut sub = collect_fragments(
+ &field.content,
+ ctx,
+ hyperlink_url,
+ measure_text,
+ footnotes,
+ endnote_counter,
+ field_ctx,
+ );
+ fragments.append(&mut sub);
+ }
+ }
+ Inline::FieldChar(fc) => {
+ // §17.16.18: complex field state machine:
+ // Begin → InstrText... → Separate → result runs → End
+ match fc.field_char_type {
+ FieldCharType::Begin => {
+ field_depth += 1;
+ field_instr.clear();
+ field_sub_pending = None;
+ field_sub_emitted = false;
+ }
+ FieldCharType::Separate => {
+ // §17.16.4.1: parse accumulated instruction, evaluate
+ // PAGE/NUMPAGES if field context is available.
+ if let Ok(parsed) = crate::field::parse(&field_instr) {
+ field_sub_pending = evaluate_field_instruction(&parsed, field_ctx);
+ }
+ // §17.16.19: bind the formatting source resolved
+ // against raw inlines, so the End fallback path
+ // can recover an empty placeholder run's rPr
+ // even though it was dropped by segment joining.
+ current_field_format =
+ field_format_sources.get(field_format_idx).copied();
+ field_format_idx += 1;
+ field_depth -= 1; // now collect result runs (unless substituted)
+ }
+ FieldCharType::End => {
+ // Substitution still pending at End: the unit
+ // stream never carried a result run (either the
+ // placeholder was empty and got swallowed by
+ // segment joining, or the field has no result
+ // content at all). Use the pre-resolved format
+ // source — §17.16.19 first-result-run when
+ // present, paragraph defaults otherwise.
+ if let Some(text) = field_sub_pending.take() {
+ emit_field_substitution(
+ &text,
+ current_field_format.as_ref(),
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults,
+ theme,
+ auto_fit,
+ hyperlink_url,
+ measure_text,
+ ctx.measurer,
+ &mut fragments,
+ );
+ }
+ current_field_format = None;
+ field_sub_emitted = false;
+ }
+ }
+ }
+ Inline::InstrText(text) => {
+ // Accumulate instruction text for complex field parsing.
+ if field_depth > 0 {
+ field_instr.push_str(text);
+ }
+ }
+ Inline::AlternateContent(ac) => {
+ use crate::render::layout::{McBranch, live_mc_branch};
+ // §M.1.2 / §17.17.1: only the live branch contributes, and
+ // `live_mc_branch` is the one place that decides which.
+ //
+ // A drawable Choice is drawn as float geometry by the
+ // floating extractor — and for a wps shape, its `txbx`
+ // contents are laid out into shape-local commands emitted
+ // on top of the shape's path. Walking the Fallback here as
+ // well would duplicate that text into the host paragraph at
+ // the wrong y.
+ //
+ // A live Fallback does come through here, and must: its VML
+ // geometry goes to the float walkers, its text box to this
+ // collector, landing at the host paragraph y as the Tier 0
+ // placeholder it has always been.
+ match live_mc_branch(ac) {
+ McBranch::Fallback(fallback) => {
+ let mut sub = collect_fragments(
+ fallback,
+ ctx,
+ hyperlink_url,
+ measure_text,
+ footnotes,
+ endnote_counter,
+ field_ctx,
+ );
+ fragments.append(&mut sub);
+ }
+ McBranch::Choices(_) | McBranch::Neither => {}
+ }
+ }
+ Inline::Symbol(sym) => {
+ let font = FontProps {
+ family: Rc::from(sym.font.as_str()),
+ size: default_size,
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ };
+ let ch = char::from_u32(sym.char_code as u32).unwrap_or('\u{FFFD}');
+ let text = ch.to_string();
+ let (w, m) = measure_text(&text, &font);
+ fragments.push(Fragment::Text {
+ text: Rc::from(text.as_str()),
+ font: Rc::new(font),
+ color: RgbColor::BLACK,
+ shading: None,
+ border: None,
+ width: w,
+ trimmed_width: w,
+ metrics: m,
+ hyperlink_url: hyperlink_url.cloned(),
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ });
+ }
+ // Bookmark target — emit as zero-width named destination.
+ Inline::BookmarkStart { name, .. } => {
+ fragments.push(Fragment::Bookmark { name: name.clone() });
+ }
+ // Non-visual inlines — skip
+ Inline::BookmarkEnd(_)
+ | Inline::Separator
+ | Inline::ContinuationSeparator
+ | Inline::FootnoteRefMark
+ | Inline::EndnoteRefMark => {}
+ // §17.11.12: footnote reference — render as superscript number.
+ Inline::FootnoteRef(note_id) => {
+ let num_text = format!("{}", footnotes.record(*note_id));
+ // §17.11.12: footnote reference uses superscript sizing.
+ let ref_size = default_size * super::SUPERSCRIPT_FONT_SIZE_RATIO;
+ let ref_font = FontProps {
+ family: std::rc::Rc::from(default_family),
+ size: ref_size,
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ };
+ let (w, m) = measure_text(&num_text, &ref_font);
+ // Raise the mark clear of the baseline (see the constant).
+ let baseline_offset = -(default_size * super::NOTE_REF_BASELINE_OFFSET_RATIO);
+ fragments.push(Fragment::Text {
+ text: Rc::from(num_text.as_str()),
+ font: Rc::new(ref_font),
+ color: default_color,
+ shading: None,
+ border: None,
+ width: w,
+ trimmed_width: w,
+ metrics: m,
+ hyperlink_url: None,
+ baseline_offset,
+ text_offset: Pt::ZERO,
+ // §17.11.12: tag so across-page splitting reserves this
+ // footnote on the page its reference mark lands on.
+ is_footnote_ref: true,
+ });
+ }
+ // §17.11.2: endnote reference — render as superscript Roman numeral.
+ Inline::EndnoteRef(_note_id) => {
+ *endnote_counter += 1;
+ let num_text = to_roman_lower(*endnote_counter);
+ let ref_size = default_size * super::SUPERSCRIPT_FONT_SIZE_RATIO;
+ let ref_font = FontProps {
+ family: std::rc::Rc::from(default_family),
+ size: ref_size,
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ };
+ let (w, m) = measure_text(&num_text, &ref_font);
+ let baseline_offset = -(default_size * super::NOTE_REF_BASELINE_OFFSET_RATIO);
+ fragments.push(Fragment::Text {
+ text: Rc::from(num_text.as_str()),
+ font: Rc::new(ref_font),
+ color: default_color,
+ shading: None,
+ border: None,
+ width: w,
+ trimmed_width: w,
+ metrics: m,
+ hyperlink_url: None,
+ baseline_offset,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ });
+ }
+ Inline::Pict(pict) => {
+ // Render text content from VML text-box-bearing
+ // primitives inline. Every primitive variant
+ // (`<v:shape>`, `<v:rect>`, `<v:roundrect>`,
+ // `<v:oval>`, …) admits a `<v:textbox>` child via
+ // `VmlCommonAttrs.text_box`; the previous code
+ // only walked the `Shape` variant and silently
+ // dropped text from rect / roundrect / oval text
+ // boxes (the case footer3.xml of the vorlage doc
+ // exercised — the gray bar is a `<v:rect>`).
+ //
+ // Does not handle absolute positioning — text
+ // appears inline with the surrounding paragraph.
+ for primitive in &pict.primitives {
+ let common = primitive.common();
+ if let Some(ref text_box) = common.text_box {
+ for block in &text_box.content {
+ if let Block::Paragraph(p) = block {
+ let pict_ctx = FragmentCtx {
+ default_family,
+ default_size,
+ default_color,
+ resolved_styles,
+ paragraph_run_defaults: p.mark_run_properties.as_ref(),
+ theme,
+ measurer: ctx.measurer,
+ auto_fit: ctx.auto_fit,
+ };
+ let mut sub = collect_fragments(
+ &p.content,
+ &pict_ctx,
+ hyperlink_url,
+ measure_text,
+ footnotes,
+ endnote_counter,
+ field_ctx,
+ );
+ fragments.append(&mut sub);
+ }
+ }
+ }
+ }
+ }
+ },
+ }
+ }
+
+ fragments
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::{Dimension, HalfPoints};
+ use crate::model::*;
+
+ /// Dummy measurer: width = text.len() * 6.0, ascent = 10.0, descent = 2.0
+ fn dummy_measure(text: &str, _font: &FontProps) -> (Pt, TextMetrics) {
+ (
+ Pt::new(text.len() as f32 * 6.0),
+ TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(2.0),
+ leading: Pt::ZERO,
+ },
+ )
+ }
+
+ fn default_ctx(size: f32) -> FragmentCtx<'static> {
+ FragmentCtx {
+ default_family: "Default",
+ default_size: Pt::new(size),
+ default_color: RgbColor::BLACK,
+ resolved_styles: None,
+ paragraph_run_defaults: None,
+ theme: None,
+ measurer: None,
+ auto_fit: crate::render::layout::ShapeAutoFit::NONE,
+ }
+ }
+
+ // ── §17.3.2.4 / §17.18.2 run-level border tri-state ─────────────────
+ //
+ // The cascade may carry a child run whose `<w:bdr w:val="nil"/>`
+ // (or "none") explicitly turns off an inherited border. The model
+ // preserves this as `Some(Border { style: nil-or-none, .. })`
+ // so the §17.7.2 merge can distinguish "explicit no border" from
+ // "field absent → inherit". At the render boundary we must drop the
+ // sentinel; otherwise the painter draws a hairline box around every
+ // word in any Word-saved doc (Word emits `<w:bdr w:val="nil"/>` in
+ // the default rPrDefault for the entire document).
+
+ fn border_with_style(style: BorderStyle) -> crate::model::Border {
+ crate::model::Border {
+ style,
+ width: Dimension::new(0),
+ space: Dimension::new(0),
+ color: crate::model::Color::Auto,
+ }
+ }
+
+ #[test]
+ fn run_border_absent_yields_no_fragment_border() {
+ assert!(run_border_to_fragment(None).is_none());
+ }
+
+ #[test]
+ fn run_border_explicit_none_yields_no_fragment_border() {
+ let b = border_with_style(BorderStyle::None);
+ assert!(
+ run_border_to_fragment(Some(&b)).is_none(),
+ "<w:bdr w:val=\"nil\"/> / \"none\" must NOT produce a render-side border"
+ );
+ }
+
+ #[test]
+ fn run_border_actual_style_yields_fragment_border() {
+ let b = border_with_style(BorderStyle::Single);
+ assert!(
+ run_border_to_fragment(Some(&b)).is_some(),
+ "explicit Single border must reach the painter"
+ );
+ }
+
+ fn text_run(text: &str) -> Inline {
+ Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::Text(text.into())],
+ rsids: RevisionIds::default(),
+ }))
+ }
+
+ fn text_run_with_font(text: &str, font: &str, size: i64) -> Inline {
+ Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties {
+ fonts: FontSet {
+ ascii: FontSlot::from_name(font),
+ ..Default::default()
+ },
+ font_size: Some(Dimension::<HalfPoints>::new(size)),
+ ..Default::default()
+ },
+ content: vec![RunElement::Text(text.into())],
+ rsids: RevisionIds::default(),
+ }))
+ }
+
+ #[test]
+ fn single_text_run() {
+ let inlines = vec![text_run("hello")];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ assert_eq!(frags[0].width().raw(), 30.0); // 5 * 6
+ assert_eq!(frags[0].height().raw(), 12.0);
+ }
+
+ #[test]
+ fn text_run_uses_run_font() {
+ let inlines = vec![text_run_with_font("hi", "Arial", 24)];
+ let ctx = default_ctx(10.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ if let Fragment::Text { font, .. } = &frags[0] {
+ assert_eq!(&*font.family, "Arial");
+ assert_eq!(font.size.raw(), 12.0); // 24 half-points = 12pt
+ } else {
+ panic!("expected Text fragment");
+ }
+ }
+
+ #[test]
+ fn tab_produces_tab_fragment() {
+ let inlines = vec![Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::Tab],
+ rsids: RevisionIds::default(),
+ }))];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ assert!(matches!(frags[0], Fragment::Tab { .. }));
+ }
+
+ #[test]
+ fn position_tab_produces_ptab_fragment() {
+ use crate::model::{PTabAlignment, PTabLeader, PTabRelativeTo, PositionTab};
+ let inlines = vec![Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::PositionTab(PositionTab {
+ alignment: PTabAlignment::Right,
+ relative_to: PTabRelativeTo::Margin,
+ leader: PTabLeader::Dot,
+ })],
+ rsids: RevisionIds::default(),
+ }))];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ assert!(matches!(
+ frags[0],
+ Fragment::PTab {
+ align: PTabAlignment::Right,
+ relative_to: PTabRelativeTo::Margin,
+ leader: crate::model::TabLeader::Dot,
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn line_break_produces_break_fragment() {
+ let inlines = vec![Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::LineBreak(BreakKind::TextWrapping)],
+ rsids: RevisionIds::default(),
+ }))];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ assert!(frags[0].is_line_break());
+ }
+
+ #[test]
+ fn hyperlink_recurses_into_content() {
+ let inlines = vec![Inline::Hyperlink(Hyperlink {
+ target: HyperlinkTarget::ExternalUrl("https://example.com".into()),
+ content: vec![text_run("click me")],
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 2, "split into 'click ' and 'me'");
+ if let Fragment::Text {
+ hyperlink_url,
+ text,
+ ..
+ } = &frags[0]
+ {
+ assert_eq!(&**text, "click ");
+ assert_eq!(
+ hyperlink_url,
+ &Some(LinkTarget::External("https://example.com".into()))
+ );
+ } else {
+ panic!("expected Text fragment");
+ }
+ }
+
+ #[test]
+ fn complex_field_skips_instructions_collects_result() {
+ // FieldChar::Begin -> InstrText("PAGE") -> FieldChar::Separate -> TextRun("3") -> FieldChar::End
+ let inlines = vec![
+ Inline::FieldChar(FieldChar {
+ field_char_type: FieldCharType::Begin,
+ dirty: None,
+ fld_lock: None,
+ }),
+ Inline::InstrText("PAGE".into()),
+ Inline::FieldChar(FieldChar {
+ field_char_type: FieldCharType::Separate,
+ dirty: None,
+ fld_lock: None,
+ }),
+ text_run("3"),
+ Inline::FieldChar(FieldChar {
+ field_char_type: FieldCharType::End,
+ dirty: None,
+ fld_lock: None,
+ }),
+ ];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ // Should only have the "3" result, not "PAGE"
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(&**text, "3");
+ }
+ }
+
+ #[test]
+ fn bookmarks_and_separators_skipped() {
+ let inlines = vec![
+ Inline::BookmarkStart {
+ id: BookmarkId::new(1),
+ name: "bm1".into(),
+ },
+ text_run("visible"),
+ Inline::BookmarkEnd(BookmarkId::new(1)),
+ Inline::Separator,
+ Inline::ContinuationSeparator,
+ Inline::FootnoteRefMark,
+ Inline::EndnoteRefMark,
+ // LastRenderedPageBreak is now inside RunElement, not Inline
+ ];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ // BookmarkStart produces a Bookmark fragment, text run produces a Text fragment.
+ assert_eq!(
+ frags.len(),
+ 2,
+ "bookmark + text run should produce fragments"
+ );
+ assert!(matches!(frags[0], Fragment::Bookmark { .. }));
+ assert!(matches!(frags[1], Fragment::Text { .. }));
+ }
+
+ #[test]
+ fn alternate_content_uses_fallback() {
+ let inlines = vec![Inline::AlternateContent(AlternateContent {
+ choices: vec![McChoice {
+ requires: vec![McRequires::Wps],
+ content: vec![text_run("choice")],
+ }],
+ fallback: Some(vec![text_run("fallback")]),
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(&**text, "fallback");
+ }
+ }
+
+ #[test]
+ fn empty_text_run_produces_no_fragment() {
+ let inlines = vec![Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::Text(String::new())],
+ rsids: RevisionIds::default(),
+ }))];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+ assert!(frags.is_empty());
+ }
+
+ #[test]
+ fn symbol_produces_text_fragment() {
+ let inlines = vec![Inline::Symbol(Symbol {
+ font: "Wingdings".into(),
+ char_code: 0x46, // 'F'
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { font, text, .. } = &frags[0] {
+ assert_eq!(&*font.family, "Wingdings");
+ assert_eq!(&**text, "F");
+ }
+ }
+
+ #[test]
+ fn simple_field_collects_content() {
+ let inlines = vec![Inline::Field(Field {
+ instruction: crate::field::FieldInstruction::Page {
+ switches: Default::default(),
+ },
+ content: vec![text_run("5")],
+ })];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 1);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(&**text, "5");
+ }
+ }
+
+ #[test]
+ fn multi_word_text_run_splits_into_fragments() {
+ let inlines = vec![text_run("hello world foo")];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext::default(),
+ );
+
+ assert_eq!(frags.len(), 3);
+ if let Fragment::Text { text, .. } = &frags[0] {
+ assert_eq!(&**text, "hello ");
+ }
+ if let Fragment::Text { text, .. } = &frags[1] {
+ assert_eq!(&**text, "world ");
+ }
+ if let Fragment::Text { text, .. } = &frags[2] {
+ assert_eq!(&**text, "foo");
+ }
+ }
+
+ // ── §17.16.19 MERGEFORMAT — field result format source ───────────────
+ //
+ // `resolve_field_format_source` walks raw inlines forward from a
+ // `Separate` fldChar to locate the formatting that should be applied
+ // to a substituted dynamic value (PAGE/NUMPAGES/...). Decoupling
+ // this from `build_inline_units` is the key correctness property:
+ // an empty `<w:t></w:t>` placeholder result run carries `<w:rPr>`
+ // but is swallowed by segment joining (it contributes 0 chars), so
+ // we cannot rely on units to surface it.
+
+ fn fld_char(kind: FieldCharType) -> Inline {
+ Inline::FieldChar(FieldChar {
+ field_char_type: kind,
+ dirty: None,
+ fld_lock: None,
+ })
+ }
+
+ fn bold_text_run(text: &str) -> Inline {
+ Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties {
+ bold: Some(true),
+ ..Default::default()
+ },
+ content: vec![RunElement::Text(text.into())],
+ rsids: RevisionIds::default(),
+ }))
+ }
+
+ /// Helper: pull `&TextRun` out of `FieldFormatSource::FirstResultRun`,
+ /// or panic with a descriptive message.
+ fn expect_first_run<'a>(src: FieldFormatSource<'a>) -> &'a TextRun {
+ match src {
+ FieldFormatSource::FirstResultRun(tr) => tr,
+ FieldFormatSource::ParagraphDefaults => {
+ panic!("expected FirstResultRun, got ParagraphDefaults")
+ }
+ }
+ }
+
+ /// Extract the concatenated text from a TextRun's content. Lets the
+ /// assertions read like prose without depending on `PartialEq` for
+ /// the `RunElement` ADT.
+ fn run_text(tr: &TextRun) -> String {
+ tr.content
+ .iter()
+ .filter_map(|e| match e {
+ RunElement::Text(t) => Some(t.as_str()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Canonical complex field shape with a non-empty result run.
+ /// Inline layout: `[Begin, InstrText, Separate, TextRun("3"), End]`.
+ #[test]
+ fn format_source_finds_text_run_after_separate() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate),
+ bold_text_run("3"),
+ fld_char(FieldCharType::End),
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ let tr = expect_first_run(src);
+ assert_eq!(run_text(tr), "3");
+ assert_eq!(tr.properties.bold, Some(true));
+ }
+
+ /// The original bug: an empty `<w:t></w:t>` placeholder result run
+ /// must still be discoverable as the format source, because its
+ /// `<w:rPr>` is the only place the substitution can find its
+ /// formatting.
+ #[test]
+ fn format_source_finds_empty_placeholder_result_run() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate),
+ bold_text_run(""), // empty placeholder, bold rPr
+ fld_char(FieldCharType::End),
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ let tr = expect_first_run(src);
+ assert!(run_text(tr).is_empty(), "expected empty text content");
+ assert_eq!(
+ tr.properties.bold,
+ Some(true),
+ "empty placeholder's bold rPr must be reachable"
+ );
+ }
+
+ /// §17.16.19 — the FIRST result run wins when multiple are present.
+ #[test]
+ fn format_source_uses_first_when_multiple_result_runs() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate),
+ bold_text_run("first"),
+ text_run("second"), // not bold
+ fld_char(FieldCharType::End),
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ let tr = expect_first_run(src);
+ assert_eq!(run_text(tr), "first");
+ assert_eq!(tr.properties.bold, Some(true));
+ }
+
+ /// `Separate` immediately followed by `End` — no result run exists,
+ /// so the resolver returns `ParagraphDefaults` and the substitution
+ /// will fall back to paragraph defaults at emission time.
+ #[test]
+ fn format_source_returns_defaults_for_empty_result_zone() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate),
+ fld_char(FieldCharType::End),
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ assert!(matches!(src, FieldFormatSource::ParagraphDefaults));
+ }
+
+ /// Text runs inside a NESTED field's own result zone belong to that
+ /// nested field's substitution, not the outer one's. The outer
+ /// resolver must skip them and look for runs at its own nesting
+ /// level — here, `outer_run` after the nested End.
+ #[test]
+ fn format_source_skips_runs_inside_nested_field() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin), // outer
+ Inline::InstrText("OUTER".into()),
+ fld_char(FieldCharType::Separate), // index 2
+ // ── nested field at depth 1 ──
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("INNER".into()),
+ fld_char(FieldCharType::Separate),
+ bold_text_run("inner-result"), // inside nested zone — skip
+ fld_char(FieldCharType::End),
+ // ── back at outer's level ──
+ bold_text_run("outer-result"), // this is the one we want
+ fld_char(FieldCharType::End),
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ let tr = expect_first_run(src);
+ assert_eq!(
+ run_text(tr),
+ "outer-result",
+ "must skip runs inside nested field"
+ );
+ }
+
+ /// Content past the matching `End` belongs to a later field (or to
+ /// the surrounding paragraph). The resolver stops at `End` and does
+ /// not leak formatting from outside.
+ #[test]
+ fn format_source_stops_at_matching_end() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate), // index 2
+ fld_char(FieldCharType::End),
+ bold_text_run("trailing"), // outside the field — must not be picked up
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ assert!(
+ matches!(src, FieldFormatSource::ParagraphDefaults),
+ "trailing run after End must not become the source"
+ );
+ }
+
+ /// Malformed inlines: no matching `End` after `Separate`. Treat as
+ /// "no result" rather than panicking or returning a partial result.
+ #[test]
+ fn format_source_handles_missing_end_gracefully() {
+ let inlines = vec![
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate), // index 2
+ // (no End — malformed)
+ ];
+ let src = resolve_field_format_source(&inlines, 2);
+ // No TextRun present and no End either — defaults is correct.
+ assert!(matches!(src, FieldFormatSource::ParagraphDefaults));
+ }
+
+ // ── End-to-end: empty-placeholder result run formatting ──────────────
+ //
+ // Mirrors the Fotodokumentation Test header structure:
+ // `Seite ` [Begin → InstrText("PAGE") → Separate → <w:t></w:t> bold → End]
+ // The substituted page number must inherit bold from the empty
+ // placeholder result run's `<w:rPr>`.
+
+ #[test]
+ fn page_field_with_empty_placeholder_inherits_bold() {
+ let inlines = vec![
+ bold_text_run("Seite "),
+ fld_char(FieldCharType::Begin),
+ Inline::InstrText("PAGE".into()),
+ fld_char(FieldCharType::Separate),
+ bold_text_run(""), // placeholder result with bold rPr
+ fld_char(FieldCharType::End),
+ ];
+ let ctx = default_ctx(12.0);
+ let frags = collect_fragments(
+ &inlines,
+ &ctx,
+ None,
+ &dummy_measure,
+ &mut FootnoteTracker::default(),
+ &mut 0,
+ FieldContext {
+ page_number: Some(7),
+ num_pages: None,
+ },
+ );
+ // Two visible text fragments: "Seite " and the substituted "7".
+ let texts: Vec<(&str, bool)> = frags
+ .iter()
+ .filter_map(|f| match f {
+ Fragment::Text { text, font, .. } => Some((text.as_ref(), font.bold)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ texts,
+ vec![("Seite ", true), ("7", true)],
+ "PAGE substitution must inherit bold from empty placeholder run"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/fragment/mod.rs b/crates/liteparse-docx/src/render/layout/fragment/mod.rs
new file mode 100644
index 0000000..12805f2
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/fragment/mod.rs
@@ -0,0 +1,514 @@
+//! Fragment conversion — transform Inline content into measured Fragments
+//! for the line-fitting algorithm.
+
+use std::rc::Rc;
+
+use crate::model::{PTabAlignment, PTabRelativeTo, RunProperties, TabLeader, UnderlineStyle};
+
+use crate::render::dimension::Pt;
+use crate::render::emoji::cluster::{EmojiPresentation, EmojiStructure};
+use crate::render::fonts::TypefaceEntry;
+use crate::render::geometry::{PtRect, PtSize};
+use crate::render::resolve::color::RgbColor;
+use crate::render::resolve::fonts::effective_font;
+use crate::render::resolve::images::MediaEntry;
+
+mod collect;
+mod segment;
+mod split;
+mod text;
+
+pub use collect::{
+ FieldContext, FootnoteTracker, FragmentCtx, RecordedFootnote, collect_fragments,
+};
+pub use split::split_oversized_fragments;
+
+// ── Superscript / subscript rendering constants ───────────────────────────────
+// §17.3.2.42: these ratios are "application-defined" per the spec; the values
+// below match Word's rendering as documented in the OpenXML SDK reference.
+
+/// Font size of super/subscript text as a fraction of the base font size.
+/// Also the size of a note reference mark and its body number (§17.11.12).
+pub(crate) const SUPERSCRIPT_FONT_SIZE_RATIO: f32 = 0.58;
+
+/// Superscript baseline shift: fraction of base ascent to raise the text by.
+pub(super) const SUPERSCRIPT_ASCENT_OFFSET_RATIO: f32 = 0.33;
+
+/// Subscript baseline shift: fraction of base character height to lower the text by.
+pub(super) const SUBSCRIPT_HEIGHT_OFFSET_RATIO: f32 = 0.08;
+
+/// §17.11.12: baseline shift for a footnote/endnote reference mark, and for
+/// the matching number prefixed to the note body — as a fraction of the base
+/// **font size**.
+///
+/// Deliberately *not* [`SUPERSCRIPT_ASCENT_OFFSET_RATIO`]: that one is a
+/// fraction of the measured *ascent* and carries a different value (0.33).
+/// Note marks are raised relative to the font size so the mark and its body
+/// number line up without a measurement round-trip.
+pub(crate) const NOTE_REF_BASELINE_OFFSET_RATIO: f32 = 0.4;
+
+/// Font properties needed for rendering a text fragment.
+#[derive(Clone, Debug)]
+pub struct FontProps {
+ pub family: Rc<str>,
+ pub size: Pt,
+ pub bold: bool,
+ pub italic: bool,
+ pub underline: bool,
+ pub char_spacing: Pt,
+ /// §17.3.2.45: horizontal character scale as a multiplier (1.0 = normal,
+ /// 0.8 = 80%, 1.5 = 150%). Applied to glyph advances during measure and
+ /// to the Skia font's `scale_x` during paint. Inter-character spacing
+ /// (`char_spacing`) is **not** scaled by this — the spec keeps the two
+ /// independent.
+ pub text_scale: f32,
+ /// Underline position from font metrics (positive = below baseline).
+ pub underline_position: Pt,
+ /// Underline thickness from font metrics.
+ pub underline_thickness: Pt,
+}
+
+/// Font metrics for a specific font at a specific size.
+/// Evaluated once by the measurer and carried through the pipeline.
+#[derive(Clone, Copy, Debug)]
+pub struct TextMetrics {
+ /// Distance from baseline to top of glyphs (positive upward).
+ pub ascent: Pt,
+ /// Distance from baseline to bottom of glyphs (positive downward).
+ pub descent: Pt,
+ /// §17.3.1.33: inter-line leading from the font's metrics.
+ /// Included in Auto line spacing base but not in glyph height.
+ pub leading: Pt,
+}
+
+impl TextMetrics {
+ /// Glyph height (ascent + descent) — used for baseline positioning.
+ pub fn height(&self) -> Pt {
+ self.ascent + self.descent
+ }
+
+ /// §17.3.1.33: full line height including leading — the base unit
+ /// that Auto line spacing multipliers scale.
+ pub fn line_height(&self) -> Pt {
+ self.ascent + self.descent + self.leading
+ }
+}
+
+/// §17.3.2.4: run-level border for rendering.
+#[derive(Clone, Copy, Debug)]
+pub struct FragmentBorder {
+ pub width: Pt,
+ pub color: RgbColor,
+ pub space: Pt,
+}
+
+/// The target of a hyperlink carried on a text fragment. Keeps the
+/// §17.16.22 external-vs-internal distinction (from `HyperlinkTarget`) as a
+/// closed ADT so the emitter routes each to the right PDF annotation
+/// (external → URI action, internal → GoTo a named destination) instead of
+/// re-deriving it from a URL-scheme string check.
+///
+/// The string is shared, for the same reason [`Fragment::Text`]'s `text` and
+/// `font` are: a `w:hyperlink` fragments into one `Fragment::Text` per *word*,
+/// each of which then emits its own annotation command. Owning the target
+/// would copy the URL once per word and again per command; sharing it copies
+/// once per link.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum LinkTarget {
+ /// A resolved external URI (`http:`, `mailto:`, `file:`, …).
+ External(Rc<str>),
+ /// An internal bookmark name (`w:hyperlink/@w:anchor`).
+ Internal(Rc<str>),
+}
+
+/// A measured fragment — the atomic unit for line fitting.
+#[derive(Clone, Debug)]
+pub enum Fragment {
+ Text {
+ text: Rc<str>,
+ /// Shared per run: all words of a run carry the same font properties,
+ /// so an `Rc` keeps the `Fragment::Text` variant small (a pointer, not
+ /// an embedded ~48-byte `FontProps`) and makes per-word clones a
+ /// refcount bump.
+ font: Rc<FontProps>,
+ color: RgbColor,
+ /// §17.3.2.32: run-level shading (background color behind text).
+ shading: Option<RgbColor>,
+ /// §17.3.2.4: run-level border (box around text).
+ border: Option<FragmentBorder>,
+ /// Full width including trailing whitespace (used for positioning).
+ width: Pt,
+ /// Width excluding trailing whitespace (used for line-break overflow checking).
+ /// Trailing whitespace is allowed to hang past the margin per Word behavior.
+ trimmed_width: Pt,
+ /// Font metrics (ascent + descent = text height).
+ metrics: TextMetrics,
+ /// Hyperlink target (external URI or internal bookmark), if this
+ /// fragment is inside a `w:hyperlink`. Named `hyperlink_url` for
+ /// historical reasons; carries the external/internal kind, not a bare
+ /// URL, so the emitter never has to guess from the string.
+ hyperlink_url: Option<LinkTarget>,
+ baseline_offset: Pt,
+ /// Horizontal offset for drawing text within the fragment width.
+ /// Used for right/center-justified list labels where the text is
+ /// positioned within a wider fragment. Default: Pt::ZERO.
+ text_offset: Pt,
+ /// §17.11.12: true if this is a footnote reference mark (the superscript
+ /// number). Rendered as ordinary text, but tagged so across-page
+ /// splitting can reserve each footnote on the page its mark lands on.
+ is_footnote_ref: bool,
+ },
+ Image {
+ size: PtSize,
+ rel_id: String,
+ image_data: Option<MediaEntry>,
+ /// §20.1.10.48 `a:srcRect` — fractional source crop in `[0, 1]`.
+ src_rect: Option<PtRect>,
+ },
+ /// One emoji grapheme cluster (UAX #29) classified as an emoji sequence
+ /// (UTS #51), to be rasterized at paint time via Skia's raster backend
+ /// and embedded as an inline PDF image, because Skia's PDF backend strips
+ /// the color glyph tables its raster backend honours. Classified by
+ /// `render::emoji::cluster`; becomes a `DrawCommand::EmojiCluster`.
+ Emoji {
+ /// Cluster text exactly as classified — one grapheme cluster, possibly
+ /// multi-codepoint (ZWJ, modifier, RIS, tag, keycap sequences).
+ text: String,
+ /// Color emoji typeface resolved upstream by the emoji resolver.
+ /// Frozen at fragment build so paint never re-resolves.
+ typeface: TypefaceEntry,
+ /// Font size at which to rasterize, in Pt.
+ size: Pt,
+ /// UTS #51 §2 presentation. `EmojiPresentation::Text` is preserved
+ /// (the rasterizer can still render it via the same color path) but
+ /// allows future paint-side decisions (e.g. monochrome over color).
+ presentation: EmojiPresentation,
+ /// UTS #51 §2 cluster structure. Carried for diagnostics + future
+ /// painter behaviour (skin-tone modifier substitution, etc.).
+ structure: EmojiStructure,
+ /// Measured advance from Skia raster metrics at `size`.
+ advance: Pt,
+ /// Font metrics from the resolved emoji typeface. Drives the
+ /// rasterized image's natural aspect ratio and the rect's vertical
+ /// extent in `line_emit::emit_line_commands` — NOT the line-height
+ /// contribution. Color emoji typefaces (Apple Color Emoji, Segoe UI
+ /// Emoji) carry tall ascents (≈1.25× font size) so their glyph art
+ /// fits, but bumping running-text line height by that amount makes
+ /// emoji-mixed lines visibly taller than text-only lines.
+ metrics: TextMetrics,
+ /// Metrics for line-height contribution, derived from the run's
+ /// font.size against the run-level typeface (not the emoji
+ /// typeface). Keeps the inline emoji "1em-tall" semantics so a
+ /// paragraph that mixes emoji and plain text lays out evenly.
+ /// The rasterized image still draws at its natural extent and may
+ /// overhang the line slightly.
+ line_metrics: TextMetrics,
+ /// Inherited from the run (super/subscript / `w:position`).
+ baseline_offset: Pt,
+ },
+ Tab {
+ line_height: Pt,
+ /// §17.3.1.38: formatting of the run holding the `<w:tab/>`. A tab
+ /// leader carries no formatting of its own — it is drawn in the
+ /// formatting in effect at the tab — so the leader emitter reads its
+ /// family and size from here rather than substituting a default.
+ font: Rc<FontProps>,
+ /// §17.3.1.38: text colour of the tab's run, for the same reason.
+ color: RgbColor,
+ /// Override minimum width for line fitting (default: MIN_TAB_WIDTH).
+ fitting_width: Option<Pt>,
+ },
+ /// §17.3.1.30: absolute-position tab. Its resolved position depends on the
+ /// line's geometry (margins / indents) and following content, so — like
+ /// [`Fragment::Tab`] — it occupies only a nominal width during line
+ /// fitting and is placed during line emission.
+ PTab {
+ align: PTabAlignment,
+ relative_to: PTabRelativeTo,
+ leader: TabLeader,
+ line_height: Pt,
+ /// §17.3.1.38: formatting of the run holding the `<w:ptab/>` — the
+ /// leader is drawn in it. See [`Fragment::Tab`].
+ font: Rc<FontProps>,
+ /// §17.3.1.38: text colour of the ptab's run.
+ color: RgbColor,
+ },
+ LineBreak {
+ line_height: Pt,
+ },
+ /// §17.3.3.1: column break — forces content to the next column.
+ ColumnBreak,
+ /// §17.3.3.1: page break — forces content to the next page.
+ PageBreak {
+ line_height: Pt,
+ },
+ /// Named destination (bookmark target) — zero-width marker.
+ Bookmark {
+ name: String,
+ },
+}
+
+impl Fragment {
+ pub fn width(&self) -> Pt {
+ match self {
+ Fragment::Text { width, .. } => *width,
+ Fragment::Image { size, .. } => size.width,
+ Fragment::Emoji { advance, .. } => *advance,
+ Fragment::Tab { fitting_width, .. } => fitting_width.unwrap_or(MIN_TAB_WIDTH),
+ Fragment::PTab { .. } => MIN_TAB_WIDTH,
+ Fragment::LineBreak { .. }
+ | Fragment::ColumnBreak
+ | Fragment::PageBreak { .. }
+ | Fragment::Bookmark { .. } => Pt::ZERO,
+ }
+ }
+
+ /// Width for overflow checking — excludes trailing whitespace on text fragments.
+ pub fn trimmed_width(&self) -> Pt {
+ match self {
+ Fragment::Text { trimmed_width, .. } => *trimmed_width,
+ other => other.width(),
+ }
+ }
+
+ pub fn height(&self) -> Pt {
+ match self {
+ Fragment::Text { metrics, .. } => metrics.height(),
+ Fragment::Image { size, .. } => size.height,
+ Fragment::Emoji { line_metrics, .. } => line_metrics.height(),
+ Fragment::Tab { line_height, .. }
+ | Fragment::PTab { line_height, .. }
+ | Fragment::LineBreak { line_height }
+ | Fragment::PageBreak { line_height } => *line_height,
+ Fragment::ColumnBreak | Fragment::Bookmark { .. } => Pt::ZERO,
+ }
+ }
+
+ pub fn is_line_break(&self) -> bool {
+ matches!(
+ self,
+ Fragment::LineBreak { .. } | Fragment::ColumnBreak | Fragment::PageBreak { .. }
+ )
+ }
+
+ /// §17.3.3.1: true if this fragment is a page break that forces
+ /// subsequent content to the next page.
+ pub fn is_page_break(&self) -> bool {
+ matches!(self, Fragment::PageBreak { .. })
+ }
+
+ /// Get font properties if this is a text fragment.
+ pub fn font_props(&self) -> Option<&FontProps> {
+ match self {
+ Fragment::Text { font, .. } => Some(font),
+ _ => None,
+ }
+ }
+}
+
+/// §17.3.1.37: minimum tab fragment width for line fitting.
+/// Tabs resolve to tab stops defined on the paragraph; this constant is only
+/// used as the fragment width during line breaking (actual tab position is
+/// computed during paragraph layout).
+pub const MIN_TAB_WIDTH: Pt = Pt::new(1.0);
+
+/// Extract font properties from RunProperties with a default font family fallback.
+///
+/// `auto_fit` is the §20.1.2.1.18 `a:normAutofit` shrink of the enclosing shape
+/// text body, applied to whichever size wins — the run's own or the inherited
+/// default — because the scale is a property of the *body*, not of any run in
+/// it. Every caller outside a shape text box passes
+/// [`ShapeAutoFit::NONE`](crate::render::layout::ShapeAutoFit::NONE); it is a
+/// parameter rather than a default so that a new call site has to say which it
+/// is.
+pub fn font_props_from_run(
+ rp: &RunProperties,
+ default_family: &str,
+ default_size: Pt,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+) -> FontProps {
+ let family = effective_font(&rp.fonts).unwrap_or(default_family);
+
+ let size = auto_fit.scale_font(rp.font_size.map(Pt::from).unwrap_or(default_size));
+
+ let char_spacing = rp.spacing.map(Pt::from).unwrap_or(Pt::ZERO);
+
+ let text_scale = rp.text_scale.map_or(1.0, |s| s.as_factor());
+
+ FontProps {
+ family: Rc::from(family),
+ size,
+ bold: rp.bold.unwrap_or(false),
+ italic: rp.italic.unwrap_or(false),
+ // §17.3.2.40: an actual underline style sets the bool. The model's
+ // tri-state — `None` (inherit), `Some(UnderlineStyle::None)`
+ // (explicit "no underline" override), `Some(_actual_style_)` —
+ // collapses here into "draw / don't draw"; only the third case
+ // draws.
+ underline: matches!(rp.underline, Some(s) if s != UnderlineStyle::None),
+ char_spacing,
+ text_scale,
+ // Populated by the measurer from Skia font metrics.
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }
+}
+
+/// Convert a number to lowercase Roman numerals.
+pub fn to_roman_lower(mut n: u32) -> String {
+ const VALS: [(u32, &str); 13] = [
+ (1000, "m"),
+ (900, "cm"),
+ (500, "d"),
+ (400, "cd"),
+ (100, "c"),
+ (90, "xc"),
+ (50, "l"),
+ (40, "xl"),
+ (10, "x"),
+ (9, "ix"),
+ (5, "v"),
+ (4, "iv"),
+ (1, "i"),
+ ];
+ let mut s = String::new();
+ for &(val, sym) in &VALS {
+ while n >= val {
+ s.push_str(sym);
+ n -= val;
+ }
+ }
+ s
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::UnderlineStyle;
+
+ #[test]
+ fn font_props_default_fallback() {
+ let rp = RunProperties::default();
+ let fp = font_props_from_run(
+ &rp,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert_eq!(&*fp.family, "Helvetica");
+ assert_eq!(fp.size.raw(), 12.0);
+ assert!(!fp.bold);
+ assert!(!fp.italic);
+ }
+
+ // ── §17.3.2.40 underline tri-state ─────────────────────────────────────
+ //
+ // `RunProperties::underline: Option<UnderlineStyle>` carries three states:
+ // * `None` — element absent; inherit (§17.7.2)
+ // * `Some(UnderlineStyle::None)` — `<w:u w:val="none"/>` explicit override
+ // * `Some(UnderlineStyle::Single)` … — actual underline style
+ // `font_props.underline` is the rendering-decision boolean: it must be
+ // `true` only when an actual underline style is in effect.
+
+ fn rp_with_underline(style: Option<UnderlineStyle>) -> RunProperties {
+ RunProperties {
+ underline: style,
+ ..RunProperties::default()
+ }
+ }
+
+ #[test]
+ fn font_props_underline_absent_is_false() {
+ let fp = font_props_from_run(
+ &rp_with_underline(None),
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(!fp.underline, "no <w:u> element → no underline");
+ }
+
+ #[test]
+ fn font_props_underline_explicit_none_is_false() {
+ let fp = font_props_from_run(
+ &rp_with_underline(Some(UnderlineStyle::None)),
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(
+ !fp.underline,
+ "<w:u w:val=\"none\"/> is the spec's explicit \"no underline\" \
+ override; font_props.underline must remain false"
+ );
+ }
+
+ #[test]
+ fn font_props_underline_single_is_true() {
+ let fp = font_props_from_run(
+ &rp_with_underline(Some(UnderlineStyle::Single)),
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(fp.underline, "<w:u w:val=\"single\"/> → underline drawn");
+ }
+
+ #[test]
+ fn font_props_text_scale_default_is_one() {
+ // §17.3.2.45: when <w:w> is absent the run renders at 100% width.
+ let fp = font_props_from_run(
+ &RunProperties::default(),
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert_eq!(fp.text_scale, 1.0);
+ }
+
+ #[test]
+ fn font_props_text_scale_compressed() {
+ // <w:w w:val="80"/> → 0.8× horizontal scale.
+ let rp = RunProperties {
+ text_scale: Some(crate::model::TextScale::new(80)),
+ ..RunProperties::default()
+ };
+ let fp = font_props_from_run(
+ &rp,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!((fp.text_scale - 0.8).abs() < f32::EPSILON);
+ }
+
+ #[test]
+ fn font_props_text_scale_expanded() {
+ // <w:w w:val="150"/> → 1.5× horizontal scale.
+ let rp = RunProperties {
+ text_scale: Some(crate::model::TextScale::new(150)),
+ ..RunProperties::default()
+ };
+ let fp = font_props_from_run(
+ &rp,
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!((fp.text_scale - 1.5).abs() < f32::EPSILON);
+ }
+
+ #[test]
+ fn font_props_underline_double_is_true() {
+ // Sanity: any non-`None` style sets the bool. A future renderer
+ // change to support distinct styles will replace this bool with
+ // an enum; for now, "any style other than None" → draw.
+ let fp = font_props_from_run(
+ &rp_with_underline(Some(UnderlineStyle::Double)),
+ "Helvetica",
+ Pt::new(12.0),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert!(fp.underline);
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/fragment/segment.rs b/crates/liteparse-docx/src/render/layout/fragment/segment.rs
new file mode 100644
index 0000000..436c121
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/fragment/segment.rs
@@ -0,0 +1,773 @@
+//! Cross-run grapheme cluster reassembly.
+//!
+//! Word splits a UAX #29 grapheme cluster across `<w:r>` runs whenever
+//! consecutive characters land in different `<w:rFonts>` slots
+//! (§17.3.2.26). The classic example is the keycap `1️⃣` — digit `1`
+//! lands in the `ascii` slot, `VS-16` + `U+20E3` land in the `hAnsi`
+//! slot, so Word emits three separate runs even though the user authored
+//! one emoji.
+//!
+//! This module pre-passes a paragraph's inline list, joining consecutive
+//! text-only runs into a flat string with per-character provenance, then
+//! classifies the joined string per UAX #29 + UTS #51 (via the existing
+//! `cluster` module). Each resulting [`SegmentPiece`] is either a single-
+//! run text span or a cross-run emoji cluster ready for the existing
+//! emit-fragments path.
+
+use unicode_segmentation::UnicodeSegmentation;
+
+use crate::model::{Inline, RunElement, TextRun};
+use crate::render::emoji::cluster::{self, EmojiPresentation, EmojiStructure, InlineCluster};
+
+// ─── Public ADTs ─────────────────────────────────────────────────────────────
+
+/// A maximal contiguous unit within a paragraph's inline list, after
+/// stripping run boundaries that don't carry semantic meaning.
+///
+/// Joining stops at:
+/// - Any inline that isn't a `Inline::TextRun` (Image, Hyperlink, Pict,
+/// FieldChar, InstrText, BookmarkStart/End, FootnoteRef, EndnoteRef,
+/// Symbol, Separator, AlternateContent, …).
+/// - Any `Inline::TextRun` whose `content` contains a `RunElement` other
+/// than `RunElement::Text` (Tab, PositionTab, LineBreak, PageBreak,
+/// ColumnBreak, LastRenderedPageBreak).
+///
+/// Both classes surface as `Discrete` so the existing dispatch in
+/// `collect_fragments` handles them unchanged.
+#[derive(Debug)]
+pub(super) enum InlineUnit<'a> {
+ /// One or more consecutive text-only `Inline::TextRun`s, joined into
+ /// a flat string with per-character provenance back to the originating
+ /// run.
+ TextSegment(JoinedTextSegment<'a>),
+ /// Anything else — a borrow into the original `Inline` tree.
+ Discrete(&'a Inline),
+}
+
+/// A flat text segment with per-character provenance.
+///
+/// Invariants:
+/// - `text.chars().count() == char_runs.len()`
+/// - `text` is C0-control-stripped (XML §2.1) except for TAB.
+/// - Every `char_runs[i]` is a stable reference into the parsed model.
+#[derive(Debug)]
+pub(super) struct JoinedTextSegment<'a> {
+ text: String,
+ /// One entry per `char` in `text`. Tracks which originating
+ /// [`TextRun`] produced that scalar.
+ char_runs: Vec<&'a TextRun>,
+}
+
+impl<'a> JoinedTextSegment<'a> {
+ /// Joined-and-stripped text. Used by tests to verify provenance and
+ /// by future paragraph-level diagnostics — kept as part of the public
+ /// API of this module.
+ #[allow(dead_code)]
+ pub(super) fn text(&self) -> &str {
+ &self.text
+ }
+
+ pub(super) fn char_runs(&self) -> &[&'a TextRun] {
+ &self.char_runs
+ }
+
+ /// Classify this segment per UAX #29 + UTS #51, splitting at run
+ /// boundaries within text spans and packaging emoji clusters
+ /// (possibly cross-run) as a single piece using the cluster's first
+ /// run as the base.
+ pub(super) fn classify(self) -> Vec<SegmentPiece<'a>> {
+ let mut out = Vec::new();
+ let mut buffer: Option<TextBuffer<'a>> = None;
+ let mut char_idx = 0usize;
+
+ for ic in cluster::classify(&self.text) {
+ match ic {
+ InlineCluster::Text(span) => {
+ // Walk graphemes inside this text span so we can
+ // split when the originating run changes.
+ for grapheme in UnicodeSegmentation::graphemes(span, true) {
+ let chars_in = grapheme.chars().count();
+ let run = self.char_runs[char_idx];
+ match buffer.as_mut() {
+ None => {
+ buffer = Some(TextBuffer {
+ run,
+ text: grapheme.to_string(),
+ });
+ }
+ Some(buf) if std::ptr::eq(buf.run, run) => {
+ buf.text.push_str(grapheme);
+ }
+ Some(_) => {
+ // Run boundary inside a text span — flush.
+ let prev = buffer.take().unwrap();
+ out.push(SegmentPiece::Text {
+ run: prev.run,
+ text: prev.text,
+ });
+ buffer = Some(TextBuffer {
+ run,
+ text: grapheme.to_string(),
+ });
+ }
+ }
+ char_idx += chars_in;
+ }
+ }
+ InlineCluster::Emoji(ec) => {
+ // Flush any pending text.
+ if let Some(prev) = buffer.take() {
+ out.push(SegmentPiece::Text {
+ run: prev.run,
+ text: prev.text,
+ });
+ }
+ let base_run = self.char_runs[char_idx];
+ let chars_in = ec.text.chars().count();
+ out.push(SegmentPiece::Emoji {
+ base_run,
+ text: ec.text.to_string(),
+ presentation: ec.presentation,
+ structure: ec.structure,
+ });
+ char_idx += chars_in;
+ }
+ }
+ }
+
+ if let Some(last) = buffer {
+ out.push(SegmentPiece::Text {
+ run: last.run,
+ text: last.text,
+ });
+ }
+
+ out
+ }
+}
+
+struct TextBuffer<'a> {
+ run: &'a TextRun,
+ text: String,
+}
+
+/// One classified piece of a [`JoinedTextSegment`] after applying UAX #29
+/// + UTS #51.
+///
+/// `Text` is split at run boundaries so each piece carries a single
+/// originating run; that run's properties drive the whole piece. `Emoji`
+/// is not split — a UAX #29 cluster is one visual unit at one size, so
+/// when it spans runs we use the base run's formatting (font-name hint
+/// per §17.3.2.26, color, baseline offset, font size).
+///
+/// The same first-run rule applies to a *text* grapheme that spans runs:
+/// `classify` attributes a whole grapheme to the run its first scalar came
+/// from, so a combining mark authored in a second run with different
+/// formatting silently takes the base character's instead. Deliberate — a
+/// grapheme is one glyph and cannot carry two colors — and it matches what
+/// Word draws, but it does mean run properties on a trailing mark are
+/// dropped rather than honored.
+#[derive(Debug)]
+pub(super) enum SegmentPiece<'a> {
+ Text {
+ run: &'a TextRun,
+ text: String,
+ },
+ Emoji {
+ base_run: &'a TextRun,
+ text: String,
+ presentation: EmojiPresentation,
+ structure: EmojiStructure,
+ },
+}
+
+// ─── Builder ─────────────────────────────────────────────────────────────────
+
+/// Walk a paragraph's inline list and produce [`InlineUnit`]s with
+/// consecutive text-only runs joined into [`JoinedTextSegment`]s.
+pub(super) fn build_inline_units(inlines: &[Inline]) -> Vec<InlineUnit<'_>> {
+ let mut out = Vec::new();
+ let mut buf = SegmentBuilder::default();
+
+ for inline in inlines {
+ match inline {
+ Inline::TextRun(tr) if is_text_only_run(tr) => {
+ for el in &tr.content {
+ if let RunElement::Text(s) = el {
+ buf.append(s, tr);
+ }
+ }
+ }
+ other => {
+ if let Some(seg) = buf.take() {
+ out.push(InlineUnit::TextSegment(seg));
+ }
+ out.push(InlineUnit::Discrete(other));
+ }
+ }
+ }
+
+ if let Some(seg) = buf.take() {
+ out.push(InlineUnit::TextSegment(seg));
+ }
+ out
+}
+
+fn is_text_only_run(tr: &TextRun) -> bool {
+ !tr.content.is_empty() && tr.content.iter().all(|e| matches!(e, RunElement::Text(_)))
+}
+
+#[derive(Default)]
+struct SegmentBuilder<'a> {
+ text: String,
+ char_runs: Vec<&'a TextRun>,
+}
+
+impl<'a> SegmentBuilder<'a> {
+ fn append(&mut self, raw: &str, run: &'a TextRun) {
+ // XML §2.1: strip C0 control chars (other than TAB) at segment
+ // build time. Matches the legacy `emit_text_fragments` contract.
+ for c in raw.chars() {
+ if c.is_control() && c != '\t' {
+ continue;
+ }
+ self.text.push(c);
+ self.char_runs.push(run);
+ }
+ }
+
+ fn take(&mut self) -> Option<JoinedTextSegment<'a>> {
+ if self.text.is_empty() {
+ return None;
+ }
+ Some(JoinedTextSegment {
+ text: std::mem::take(&mut self.text),
+ char_runs: std::mem::take(&mut self.char_runs),
+ })
+ }
+}
+
+// ─── Tests (Phase α.0 + α.1) ─────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::{RevisionIds, RunProperties, Symbol};
+
+ // ── Helpers ────────────────────────────────────────────────────────
+
+ fn text_run(text: &str) -> Inline {
+ Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: vec![RunElement::Text(text.into())],
+ rsids: RevisionIds::default(),
+ }))
+ }
+
+ fn run_with_elements(elements: Vec<RunElement>) -> Inline {
+ Inline::TextRun(Box::new(TextRun {
+ style_id: None,
+ properties: RunProperties::default(),
+ content: elements,
+ rsids: RevisionIds::default(),
+ }))
+ }
+
+ /// Any non-TextRun inline that breaks segment joining. We use Symbol
+ /// (small, simple) as the canonical "interrupter" in tests; the real
+ /// pipeline treats every non-TextRun inline the same way.
+ fn discrete_inline() -> Inline {
+ Inline::Symbol(Symbol {
+ font: "Wingdings".into(),
+ char_code: 0xF0FE,
+ })
+ }
+
+ fn extract_run(inline: &Inline) -> &TextRun {
+ match inline {
+ Inline::TextRun(tr) => tr,
+ _ => panic!("expected TextRun"),
+ }
+ }
+
+ fn segment_of<'a>(unit: &'a InlineUnit<'a>) -> &'a JoinedTextSegment<'a> {
+ match unit {
+ InlineUnit::TextSegment(s) => s,
+ other => panic!("expected TextSegment, got {other:?}"),
+ }
+ }
+
+ // ── Phase α.0: build_inline_units ──────────────────────────────────
+
+ /// A1 — single TextRun produces one segment whose char_runs all
+ /// point to that run.
+ #[test]
+ fn a1_single_text_run() {
+ let inlines = vec![text_run("hello")];
+ let r1 = extract_run(&inlines[0]);
+
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 1);
+ let seg = segment_of(&units[0]);
+ assert_eq!(seg.text(), "hello");
+ assert_eq!(seg.char_runs().len(), 5);
+ for &cr in seg.char_runs() {
+ assert!(std::ptr::eq(cr, r1));
+ }
+ }
+
+ /// A2 — two consecutive TextRuns join into one segment with
+ /// per-character provenance interleaved.
+ #[test]
+ fn a2_two_runs_join() {
+ let inlines = vec![text_run("ab"), text_run("cd")];
+ let r1 = extract_run(&inlines[0]);
+ let r2 = extract_run(&inlines[1]);
+
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 1);
+ let seg = segment_of(&units[0]);
+ assert_eq!(seg.text(), "abcd");
+ assert_eq!(seg.char_runs().len(), 4);
+ assert!(std::ptr::eq(seg.char_runs()[0], r1));
+ assert!(std::ptr::eq(seg.char_runs()[1], r1));
+ assert!(std::ptr::eq(seg.char_runs()[2], r2));
+ assert!(std::ptr::eq(seg.char_runs()[3], r2));
+ }
+
+ /// A3 — a non-TextRun inline (Symbol stands in for any of Image,
+ /// Hyperlink, Pict, FootnoteRef, …) breaks segment joining.
+ #[test]
+ fn a3_non_text_inline_breaks_join() {
+ let inlines = vec![text_run("ab"), discrete_inline(), text_run("cd")];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 3);
+ assert_eq!(segment_of(&units[0]).text(), "ab");
+ assert!(matches!(units[1], InlineUnit::Discrete(Inline::Symbol(_))));
+ assert_eq!(segment_of(&units[2]).text(), "cd");
+ }
+
+ /// A4 — a TextRun whose content contains a non-text element (Tab)
+ /// is treated as Discrete; subsequent text-only runs start a fresh
+ /// segment.
+ #[test]
+ fn a4_text_run_with_tab_is_discrete() {
+ let r1 = run_with_elements(vec![
+ RunElement::Text("a".into()),
+ RunElement::Tab,
+ RunElement::Text("b".into()),
+ ]);
+ let inlines = vec![text_run("hello"), r1, text_run("world")];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 3);
+ assert_eq!(segment_of(&units[0]).text(), "hello");
+ assert!(matches!(units[1], InlineUnit::Discrete(Inline::TextRun(_))));
+ assert_eq!(segment_of(&units[2]).text(), "world");
+ }
+
+ /// A5 — empty TextRun produces no segment.
+ #[test]
+ fn a5_empty_text_run_is_skipped() {
+ let inlines = vec![text_run("")];
+ let units = build_inline_units(&inlines);
+ assert!(units.is_empty(), "no segment from empty text");
+ }
+
+ /// A5b — purely-empty TextRun (no content elements) is treated as
+ /// not-text-only and surfaces as Discrete.
+ #[test]
+ fn a5b_no_content_text_run_is_discrete() {
+ let inlines = vec![run_with_elements(vec![])];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 1);
+ assert!(matches!(units[0], InlineUnit::Discrete(_)));
+ }
+
+ /// A6 — XML §2.1: C0 control chars (other than TAB) are stripped at
+ /// segment-build time. char_runs.len() reflects the cleaned text.
+ #[test]
+ fn a6_control_chars_stripped() {
+ let inlines = vec![text_run("\u{0001}hi\u{0002}")];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 1);
+ let seg = segment_of(&units[0]);
+ assert_eq!(seg.text(), "hi");
+ assert_eq!(seg.char_runs().len(), 2);
+ }
+
+ /// A6b — TAB chars in text are PRESERVED (legacy contract; tabs in
+ /// `RunElement::Text` are different from `RunElement::Tab`).
+ #[test]
+ fn a6b_tab_preserved_in_text() {
+ let inlines = vec![text_run("a\tb")];
+ let units = build_inline_units(&inlines);
+ let seg = segment_of(&units[0]);
+ assert_eq!(seg.text(), "a\tb");
+ }
+
+ /// A7 — three runs all with text → one segment with full
+ /// invariant `text.chars().count() == char_runs.len()`.
+ #[test]
+ fn a7_three_runs_invariant() {
+ let inlines = vec![text_run("ab"), text_run("c"), text_run("def")];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 1);
+ let seg = segment_of(&units[0]);
+ assert_eq!(seg.text().chars().count(), seg.char_runs().len());
+ assert_eq!(seg.text(), "abcdef");
+ }
+
+ /// A8 — a Hyperlink Inline breaks the join (hyperlink content is its
+ /// own scope handled via recursion at the emit site).
+ #[test]
+ fn a8_hyperlink_breaks_join() {
+ use crate::model::{Hyperlink, HyperlinkTarget};
+ let inlines = vec![
+ text_run("before "),
+ Inline::Hyperlink(Hyperlink {
+ target: HyperlinkTarget::ExternalUrl("https://example.com".into()),
+ content: vec![text_run("link")],
+ }),
+ text_run(" after"),
+ ];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 3);
+ assert_eq!(segment_of(&units[0]).text(), "before ");
+ assert!(matches!(
+ units[1],
+ InlineUnit::Discrete(Inline::Hyperlink(_))
+ ));
+ assert_eq!(segment_of(&units[2]).text(), " after");
+ }
+
+ /// A9 — Inline::FieldChar breaks the join (so the field state
+ /// machine sees each text segment as a distinct field-state zone).
+ #[test]
+ fn a9_field_char_breaks_join() {
+ use crate::model::{FieldChar, FieldCharType};
+ let inlines = vec![
+ text_run("page "),
+ Inline::FieldChar(FieldChar {
+ field_char_type: FieldCharType::Begin,
+ dirty: None,
+ fld_lock: None,
+ }),
+ text_run("instr"),
+ ];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 3);
+ assert_eq!(segment_of(&units[0]).text(), "page ");
+ assert!(matches!(
+ units[1],
+ InlineUnit::Discrete(Inline::FieldChar(_))
+ ));
+ assert_eq!(segment_of(&units[2]).text(), "instr");
+ }
+
+ // ── Phase α.1: JoinedTextSegment::classify ─────────────────────────
+
+ /// B1 — single-run "hello" → one Text piece.
+ #[test]
+ fn b1_single_run_text() {
+ let inlines = vec![text_run("hello")];
+ let r1 = extract_run(&inlines[0]);
+
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ match &pieces[0] {
+ SegmentPiece::Text { run, text } => {
+ assert!(std::ptr::eq(*run, r1));
+ assert_eq!(text, "hello");
+ }
+ other => panic!("expected Text, got {other:?}"),
+ }
+ }
+
+ /// B2 — two-run "ab" + "cd" → two Text pieces, one per run.
+ #[test]
+ fn b2_two_runs_split_text() {
+ let inlines = vec![text_run("ab"), text_run("cd")];
+ let r1 = extract_run(&inlines[0]);
+ let r2 = extract_run(&inlines[1]);
+
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 2);
+ match &pieces[0] {
+ SegmentPiece::Text { run, text } => {
+ assert!(std::ptr::eq(*run, r1));
+ assert_eq!(text, "ab");
+ }
+ _ => panic!(),
+ }
+ match &pieces[1] {
+ SegmentPiece::Text { run, text } => {
+ assert!(std::ptr::eq(*run, r2));
+ assert_eq!(text, "cd");
+ }
+ _ => panic!(),
+ }
+ }
+
+ /// B3 — keycap split as ["1", VS-16, U+20E3] → one Emoji piece.
+ /// **Direct fix for the user-visible keycap bug.**
+ #[test]
+ fn b3_cross_run_keycap_reassembles() {
+ let inlines = vec![text_run("1"), text_run("\u{FE0F}"), text_run("\u{20E3}")];
+ let r1 = extract_run(&inlines[0]);
+
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ match &pieces[0] {
+ SegmentPiece::Emoji {
+ base_run,
+ text,
+ presentation,
+ structure,
+ } => {
+ assert!(std::ptr::eq(*base_run, r1));
+ assert_eq!(text, "1\u{FE0F}\u{20E3}");
+ assert_eq!(*presentation, EmojiPresentation::Emoji);
+ assert!(matches!(
+ structure,
+ EmojiStructure::KeycapSequence { base: '1' }
+ ));
+ }
+ other => panic!("expected Emoji KeycapSequence, got {other:?}"),
+ }
+ }
+
+ /// B4 — ZWJ family split per emoji → one Emoji piece.
+ #[test]
+ fn b4_cross_run_zwj_family() {
+ let inlines = vec![
+ text_run("\u{1F468}"),
+ text_run("\u{200D}"),
+ text_run("\u{1F469}"),
+ text_run("\u{200D}"),
+ text_run("\u{1F467}"),
+ ];
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ match &pieces[0] {
+ SegmentPiece::Emoji {
+ text, structure, ..
+ } => {
+ assert_eq!(text, "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}");
+ assert!(matches!(structure, EmojiStructure::ZwjSequence));
+ }
+ _ => panic!(),
+ }
+ }
+
+ /// B5 — modifier sequence split as [👍, 🏿] → one Emoji piece.
+ #[test]
+ fn b5_cross_run_modifier_sequence() {
+ let inlines = vec![text_run("\u{1F44D}"), text_run("\u{1F3FF}")];
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ match &pieces[0] {
+ SegmentPiece::Emoji {
+ text, structure, ..
+ } => {
+ assert_eq!(text, "\u{1F44D}\u{1F3FF}");
+ assert!(matches!(
+ structure,
+ EmojiStructure::ModifierSequence {
+ base: '\u{1F44D}',
+ ..
+ }
+ ));
+ }
+ _ => panic!(),
+ }
+ }
+
+ /// B6 — mixed: ["hi 1", VS-16+U+20E3, " there"] → three pieces:
+ /// Text("hi "), Emoji("1️⃣"), Text(" there").
+ #[test]
+ fn b6_mixed_text_and_keycap() {
+ let inlines = vec![
+ text_run("hi 1"),
+ text_run("\u{FE0F}\u{20E3}"),
+ text_run(" there"),
+ ];
+ let r1 = extract_run(&inlines[0]);
+ let r3 = extract_run(&inlines[2]);
+
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 3);
+ match &pieces[0] {
+ SegmentPiece::Text { run, text } => {
+ assert!(std::ptr::eq(*run, r1));
+ assert_eq!(text, "hi ");
+ }
+ _ => panic!(),
+ }
+ match &pieces[1] {
+ SegmentPiece::Emoji {
+ base_run,
+ text,
+ structure,
+ ..
+ } => {
+ assert!(std::ptr::eq(*base_run, r1));
+ assert_eq!(text, "1\u{FE0F}\u{20E3}");
+ assert!(matches!(
+ structure,
+ EmojiStructure::KeycapSequence { base: '1' }
+ ));
+ }
+ _ => panic!(),
+ }
+ match &pieces[2] {
+ SegmentPiece::Text { run, text } => {
+ assert!(std::ptr::eq(*run, r3));
+ assert_eq!(text, " there");
+ }
+ _ => panic!(),
+ }
+ }
+
+ /// B7 — two distinct emoji "📞📧" in two runs → two Emoji pieces
+ /// (UAX #29 clusters: each emoji is its own grapheme).
+ #[test]
+ fn b7_adjacent_distinct_emojis() {
+ let inlines = vec![text_run("\u{1F4DE}"), text_run("\u{1F4E7}")];
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 2);
+ for p in &pieces {
+ assert!(matches!(p, SegmentPiece::Emoji { .. }));
+ }
+ }
+
+ /// B8 — combining mark cross-run: 'a' + U+0301 → one Text piece
+ /// (UAX #29 binds the combining mark).
+ #[test]
+ fn b8_cross_run_combining_mark() {
+ let inlines = vec![text_run("a"), text_run("\u{0301}")];
+ let r1 = extract_run(&inlines[0]);
+
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ match &pieces[0] {
+ SegmentPiece::Text { run, text } => {
+ assert!(std::ptr::eq(*run, r1));
+ assert_eq!(text, "a\u{0301}");
+ }
+ _ => panic!(),
+ }
+ }
+
+ /// B9 — RIS pair split: ["🇩", "🇪"] → one Emoji FlagSequence.
+ #[test]
+ fn b9_cross_run_ris_pair() {
+ let inlines = vec![text_run("\u{1F1E9}"), text_run("\u{1F1EA}")];
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ match &pieces[0] {
+ SegmentPiece::Emoji {
+ text, structure, ..
+ } => {
+ assert_eq!(text, "\u{1F1E9}\u{1F1EA}");
+ assert!(matches!(
+ structure,
+ EmojiStructure::FlagSequence(crate::render::emoji::cluster::FlagKind::Regional)
+ ));
+ }
+ _ => panic!(),
+ }
+ }
+
+ /// B10 — default-text codepoints (digits) NOT promoted: regression
+ /// for the digit fix. Single-run digits stay text.
+ #[test]
+ fn b10_digits_in_one_run_stay_text() {
+ let inlines = vec![text_run("Numbers: 1, 2, 3")];
+ let units = build_inline_units(&inlines);
+ let seg = match units.into_iter().next().unwrap() {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ let pieces = seg.classify();
+ assert_eq!(pieces.len(), 1);
+ assert!(matches!(pieces[0], SegmentPiece::Text { .. }));
+ }
+
+ /// B11 — field char between text-only runs has already produced a
+ /// segment break at A9; classification of each segment is independent.
+ #[test]
+ fn b11_field_char_isolates_segments() {
+ use crate::model::{FieldChar, FieldCharType};
+ let inlines = vec![
+ text_run("a"),
+ text_run("b"),
+ Inline::FieldChar(FieldChar {
+ field_char_type: FieldCharType::Begin,
+ dirty: None,
+ fld_lock: None,
+ }),
+ text_run("c"),
+ text_run("d"),
+ ];
+ let units = build_inline_units(&inlines);
+ assert_eq!(units.len(), 3);
+ // First segment "ab" classifies independently.
+ let seg1 = match &units[0] {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ assert_eq!(seg1.text(), "ab");
+ // Second segment "cd" classifies independently.
+ let seg2 = match &units[2] {
+ InlineUnit::TextSegment(s) => s,
+ _ => panic!(),
+ };
+ assert_eq!(seg2.text(), "cd");
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/fragment/split.rs b/crates/liteparse-docx/src/render/layout/fragment/split.rs
new file mode 100644
index 0000000..97fcfaf
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/fragment/split.rs
@@ -0,0 +1,250 @@
+//! Character-level splitting of over-wide text fragments.
+//!
+//! A word wider than the space available can't be broken at a normal break
+//! opportunity, so it is split into one fragment per character and the
+//! line-fitter breaks between them. Used for narrow table cells and deep
+//! indents.
+
+use std::rc::Rc;
+
+use super::{FontProps, Fragment, TextMetrics};
+use crate::render::dimension::Pt;
+
+/// Text measurement callback. Structurally identical to
+/// `paragraph::MeasureTextFn`, restated here so this module doesn't depend on
+/// the paragraph layer — callers in either layer pass the same closures.
+pub type MeasureFn<'a> = Option<&'a dyn Fn(&str, &FontProps) -> (Pt, TextMetrics)>;
+
+/// True for a text fragment that is both too wide and actually splittable.
+///
+/// The character *count* is what matters: a single character cannot be split
+/// however many bytes it occupies. An earlier byte-length (`text.len() > 1`)
+/// spelling of this test disagreed with the split itself for any non-ASCII
+/// single character — it reported "needs split", then split nothing, and the
+/// caller paid for a full clone of the fragment vector.
+fn needs_split(fragment: &Fragment, max_width: Pt) -> bool {
+ matches!(
+ fragment,
+ Fragment::Text { width, text, .. } if *width > max_width && text.chars().count() > 1
+ )
+}
+
+/// Split text fragments wider than `max_width` into per-character fragments.
+///
+/// Returns `None` when nothing needs splitting — the common case. That lets a
+/// caller holding an owned `Vec` keep it untouched, and a caller holding a
+/// slice hand back `Cow::Borrowed`; neither pays for a copy on the fast path.
+///
+/// Per-character widths come from `measure` when one is supplied. Without a
+/// measurer the fragment's width is divided evenly across its characters,
+/// which is only a positioning approximation — the total is preserved.
+pub fn split_oversized_fragments(
+ fragments: &[Fragment],
+ max_width: Pt,
+ measure: MeasureFn<'_>,
+) -> Option<Vec<Fragment>> {
+ // A non-positive budget can't be met by any split, and dividing by it
+ // below would be meaningless.
+ if max_width <= Pt::ZERO {
+ return None;
+ }
+ if !fragments.iter().any(|f| needs_split(f, max_width)) {
+ return None;
+ }
+
+ let mut result = Vec::with_capacity(fragments.len());
+ // Reusable buffer for single-character measurement (avoids a per-character
+ // heap allocation).
+ let mut ch_buf = [0u8; 4];
+ for frag in fragments {
+ let Fragment::Text {
+ text,
+ width,
+ font,
+ color,
+ shading,
+ border,
+ metrics,
+ hyperlink_url,
+ baseline_offset,
+ ..
+ } = frag
+ else {
+ result.push(frag.clone());
+ continue;
+ };
+ if !needs_split(frag, max_width) {
+ result.push(frag.clone());
+ continue;
+ }
+
+ let char_count = text.chars().count();
+ let per_char_fallback = *width / char_count as f32;
+ for ch in text.chars() {
+ let ch_str = ch.encode_utf8(&mut ch_buf);
+ let (w, char_metrics) = match measure {
+ Some(m) => m(ch_str, font),
+ None => (per_char_fallback, *metrics),
+ };
+ result.push(Fragment::Text {
+ text: Rc::from(&*ch_str),
+ font: font.clone(),
+ color: *color,
+ shading: *shading,
+ border: *border,
+ width: w,
+ trimmed_width: w,
+ metrics: char_metrics,
+ hyperlink_url: hyperlink_url.clone(),
+ baseline_offset: *baseline_offset,
+ text_offset: Pt::ZERO,
+ // Per-character split of an over-wide word — not a mark.
+ is_footnote_ref: false,
+ });
+ }
+ }
+ Some(result)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::resolve::color::RgbColor;
+
+ fn text_frag(text: &str, width: f32) -> Fragment {
+ Fragment::Text {
+ text: Rc::from(text),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn texts(frags: &[Fragment]) -> Vec<String> {
+ frags
+ .iter()
+ .map(|f| match f {
+ Fragment::Text { text, .. } => text.to_string(),
+ _ => panic!("expected Text fragment"),
+ })
+ .collect()
+ }
+
+ #[test]
+ fn splits_into_one_fragment_per_character() {
+ // "ab" at 60pt is wider than max_width=20pt → two 30pt characters
+ // (uniform fallback — no measurer provided).
+ let frags = vec![text_frag("ab", 60.0)];
+ let result = split_oversized_fragments(&frags, Pt::new(20.0), None).expect("splits");
+ assert_eq!(
+ texts(&result),
+ ["a", "b"],
+ "one fragment per character, in order"
+ );
+ for frag in &result {
+ let Fragment::Text { width, .. } = frag else {
+ unreachable!()
+ };
+ assert!((width.raw() - 30.0).abs() < 1e-4, "uniform fallback 60/2");
+ }
+ }
+
+ #[test]
+ fn measurer_supplies_per_character_widths() {
+ // A measurer that gives 'w' a wider advance than 'i' — the uniform
+ // fallback would give both the same width.
+ let measure = |t: &str, _: &FontProps| {
+ let w = if t == "w" { 40.0 } else { 10.0 };
+ (
+ Pt::new(w),
+ TextMetrics {
+ ascent: Pt::new(9.0),
+ descent: Pt::new(3.0),
+ leading: Pt::ZERO,
+ },
+ )
+ };
+ let frags = vec![text_frag("wi", 50.0)];
+ let result =
+ split_oversized_fragments(&frags, Pt::new(20.0), Some(&measure)).expect("splits");
+ let widths: Vec<f32> = result
+ .iter()
+ .map(|f| match f {
+ Fragment::Text { width, .. } => width.raw(),
+ _ => unreachable!(),
+ })
+ .collect();
+ assert_eq!(widths, [40.0, 10.0], "measured, not evenly divided");
+ // Metrics come from the measurer too, not the parent fragment.
+ let Fragment::Text { metrics, .. } = &result[0] else {
+ unreachable!()
+ };
+ assert_eq!(metrics.ascent.raw(), 9.0);
+ }
+
+ #[test]
+ fn nothing_to_split_returns_none() {
+ let frags = vec![text_frag("hi", 10.0)];
+ assert!(split_oversized_fragments(&frags, Pt::new(100.0), None).is_none());
+ }
+
+ #[test]
+ fn single_character_is_never_split() {
+ // Wider than max_width, but one character — nothing to break.
+ let frags = vec![text_frag("M", 200.0)];
+ assert!(split_oversized_fragments(&frags, Pt::new(10.0), None).is_none());
+ }
+
+ /// The character count, not the byte length, decides splittability. A
+ /// byte-length test reports "needs split" for these and then splits
+ /// nothing, costing the caller a pointless clone of the whole vector.
+ #[test]
+ fn multi_byte_single_character_is_never_split() {
+ for ch in ["é", "😀", "字"] {
+ let frags = vec![text_frag(ch, 200.0)];
+ assert!(
+ split_oversized_fragments(&frags, Pt::new(10.0), None).is_none(),
+ "{ch:?} is one character regardless of its byte length"
+ );
+ }
+ }
+
+ #[test]
+ fn non_positive_max_width_returns_none() {
+ let frags = vec![text_frag("ab", 60.0)];
+ assert!(split_oversized_fragments(&frags, Pt::ZERO, None).is_none());
+ assert!(split_oversized_fragments(&frags, Pt::new(-5.0), None).is_none());
+ }
+
+ #[test]
+ fn fragments_that_fit_pass_through_unchanged() {
+ let frags = vec![
+ text_frag("ab", 60.0), // splits
+ text_frag("ok", 5.0), // fits — must survive whole
+ ];
+ let result = split_oversized_fragments(&frags, Pt::new(20.0), None).expect("splits");
+ assert_eq!(texts(&result), ["a", "b", "ok"]);
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/fragment/text.rs b/crates/liteparse-docx/src/render/layout/fragment/text.rs
new file mode 100644
index 0000000..4524206
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/fragment/text.rs
@@ -0,0 +1,465 @@
+use std::rc::Rc;
+
+use crate::render::dimension::Pt;
+use crate::render::emoji::cluster::{self, EmojiCluster, InlineCluster};
+use crate::render::emoji::resolve::{EmojiFamily, EmojiTypeface};
+use crate::render::layout::measurer::TextMeasurer;
+use crate::render::resolve::color::RgbColor;
+
+use super::{FontProps, Fragment, FragmentBorder, LinkTarget, TextMetrics};
+
+/// §17.18.40 ST_HighlightColor: map highlight enum to RGB.
+/// These are the fixed palette colors defined in the OOXML spec.
+///
+/// Returns `None` for [`HighlightColor::None`] — the spec's explicit
+/// "no highlight" override (`<w:highlight w:val="none"/>`) — so the caller
+/// suppresses the background fill entirely rather than painting nothing
+/// special at the wrong layer.
+pub(super) fn resolve_highlight_color(hl: crate::model::HighlightColor) -> Option<RgbColor> {
+ use crate::model::HighlightColor;
+ Some(match hl {
+ HighlightColor::None => return None,
+ HighlightColor::Black => RgbColor { r: 0, g: 0, b: 0 },
+ HighlightColor::Blue => RgbColor { r: 0, g: 0, b: 255 },
+ HighlightColor::Cyan => RgbColor {
+ r: 0,
+ g: 255,
+ b: 255,
+ },
+ HighlightColor::DarkBlue => RgbColor { r: 0, g: 0, b: 139 },
+ HighlightColor::DarkCyan => RgbColor {
+ r: 0,
+ g: 139,
+ b: 139,
+ },
+ HighlightColor::DarkGray => RgbColor {
+ r: 169,
+ g: 169,
+ b: 169,
+ },
+ HighlightColor::DarkGreen => RgbColor { r: 0, g: 100, b: 0 },
+ HighlightColor::DarkMagenta => RgbColor {
+ r: 139,
+ g: 0,
+ b: 139,
+ },
+ HighlightColor::DarkRed => RgbColor { r: 139, g: 0, b: 0 },
+ HighlightColor::DarkYellow => RgbColor {
+ r: 139,
+ g: 139,
+ b: 0,
+ },
+ HighlightColor::Green => RgbColor { r: 0, g: 255, b: 0 },
+ HighlightColor::LightGray => RgbColor {
+ r: 211,
+ g: 211,
+ b: 211,
+ },
+ HighlightColor::Magenta => RgbColor {
+ r: 255,
+ g: 0,
+ b: 255,
+ },
+ HighlightColor::Red => RgbColor { r: 255, g: 0, b: 0 },
+ HighlightColor::White => RgbColor {
+ r: 255,
+ g: 255,
+ b: 255,
+ },
+ HighlightColor::Yellow => RgbColor {
+ r: 255,
+ g: 255,
+ b: 0,
+ },
+ })
+}
+
+/// Resolved styling for a single text fragment.
+pub(super) struct TextRunStyle {
+ pub color: RgbColor,
+ pub shading: Option<RgbColor>,
+ pub border: Option<FragmentBorder>,
+ pub baseline_offset: Pt,
+}
+
+/// Split text into word-level chunks for line breaking.
+/// Whitespace is kept attached to the preceding word: "hello world" → ["hello ", "world"].
+/// This allows the line fitter to break between fragments at word boundaries.
+fn split_into_words(text: &str) -> Vec<&str> {
+ let mut words = Vec::new();
+ let mut start = 0;
+
+ for (i, ch) in text.char_indices() {
+ match ch {
+ // Whitespace: include with the preceding word.
+ ' ' | '\t' => {
+ let end = i + ch.len_utf8();
+ if end > start {
+ words.push(&text[start..end]);
+ start = end;
+ }
+ }
+ // Hyphen/dash: break AFTER the hyphen (UAX #14).
+ // The hyphen stays with the preceding word.
+ '-' | '\u{2010}' | '\u{2012}' | '\u{2013}' | '\u{2014}' => {
+ let end = i + ch.len_utf8();
+ if end > start {
+ words.push(&text[start..end]);
+ start = end;
+ }
+ }
+ _ => {}
+ }
+ }
+
+ // Remaining text (last word without trailing space)
+ if start < text.len() {
+ words.push(&text[start..]);
+ }
+
+ words
+}
+
+/// Split text into word-level fragments and push to the output vec.
+///
+/// When `measurer` is `Some`, the text is first split into grapheme clusters
+/// (UAX #29) and each cluster is classified per UTS #51. Emoji clusters that
+/// resolve to a host color emoji typeface become [`Fragment::Emoji`]; clusters
+/// without a resolved typeface fall through to the text path with a one-time
+/// warning per cluster. When `measurer` is `None` (used by unit tests that
+/// don't construct a font registry), the input is passed straight to the
+/// existing word-split + measure path — preserving prior behaviour.
+pub(super) fn emit_text_fragments<F>(
+ text: &str,
+ font: &FontProps,
+ style: &TextRunStyle,
+ hyperlink_url: Option<&LinkTarget>,
+ measure_text: &F,
+ measurer: Option<&TextMeasurer<'_>>,
+ fragments: &mut Vec<Fragment>,
+) where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
+{
+ // §2.1 XML spec: C0 control characters (U+0000–U+001F) other than
+ // HT (U+0009), LF (U+000A), CR (U+000D) are invalid in XML but some
+ // producers embed LF/CR in w:t content. Strip all non-tab controls
+ // so they don't render as tofu/question-mark glyphs.
+ let cleaned: String = text
+ .chars()
+ .filter(|&c| !c.is_control() || c == '\t')
+ .collect();
+ if cleaned.is_empty() {
+ return;
+ }
+
+ let Some(measurer) = measurer else {
+ emit_text_words(
+ &cleaned,
+ font,
+ style,
+ hyperlink_url,
+ measure_text,
+ fragments,
+ );
+ return;
+ };
+
+ // Classify into clusters and route emoji clusters through the raster
+ // pipeline; text spans go through the existing word-split path.
+ for cluster in cluster::classify(&cleaned) {
+ match cluster {
+ InlineCluster::Text(span) => {
+ emit_text_words(span, font, style, hyperlink_url, measure_text, fragments);
+ }
+ InlineCluster::Emoji(emoji) => {
+ emit_emoji_or_fallback(
+ &emoji,
+ font,
+ style,
+ hyperlink_url,
+ measure_text,
+ measurer,
+ fragments,
+ );
+ }
+ }
+ }
+}
+
+/// Word-split + measure path. Identical to the prior body of
+/// [`emit_text_fragments`]; factored out so emoji-cluster fallback can reuse it.
+pub(super) fn emit_text_words<F>(
+ text: &str,
+ font: &FontProps,
+ style: &TextRunStyle,
+ hyperlink_url: Option<&LinkTarget>,
+ measure_text: &F,
+ fragments: &mut Vec<Fragment>,
+) where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
+{
+ if text.is_empty() {
+ return;
+ }
+ // Words within a run share their font properties: build one `Rc` per call
+ // and hand each fragment a cheap refcount bump instead of a ~48-byte copy.
+ let font = Rc::new(font.clone());
+ for word in split_into_words(text) {
+ let (w, m) = measure_text(word, &font);
+ let trimmed = word.trim_end();
+ let tw = if trimmed.len() < word.len() {
+ measure_text(trimmed, &font).0
+ } else {
+ w
+ };
+ fragments.push(Fragment::Text {
+ text: Rc::from(word),
+ font: Rc::clone(&font),
+ color: style.color,
+ shading: style.shading,
+ border: style.border,
+ width: w,
+ trimmed_width: tw,
+ metrics: m,
+ hyperlink_url: hyperlink_url.cloned(),
+ baseline_offset: style.baseline_offset,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ });
+ }
+}
+
+/// Resolve a host color emoji typeface for an emoji cluster and emit a
+/// [`Fragment::Emoji`]. On `Unavailable`, log a one-time warning and route
+/// the cluster through the text path so its codepoints still appear in the
+/// PDF text stream. The converter never ships emoji font bytes and never
+/// degrades silently: it consumes whatever color typeface the host provides,
+/// and logs when there is none so an operator can install one.
+pub(super) fn emit_emoji_or_fallback<F>(
+ cluster: &EmojiCluster<'_>,
+ font: &FontProps,
+ style: &TextRunStyle,
+ hyperlink_url: Option<&LinkTarget>,
+ measure_text: &F,
+ measurer: &TextMeasurer<'_>,
+ fragments: &mut Vec<Fragment>,
+) where
+ F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
+{
+ // §17.3.2.26: the run's font name acts as a hint. If it names a known
+ // color emoji family, prefer it; otherwise we fall through to the
+ // host-default chain (e.g. Calibri-tagged runs containing 📞 still
+ // resolve to Apple Color Emoji on macOS).
+ let requested = EmojiFamily::from_name_ci(&font.family);
+ match measurer.resolve_emoji(requested) {
+ EmojiTypeface::Resolved {
+ entry: typeface, ..
+ } => {
+ let (advance, metrics) =
+ measurer.measure_with_typeface(cluster.text, &typeface, font.size);
+ // Line-height contribution uses the run's text-font metrics so
+ // an inline emoji doesn't bloat the line. Color emoji typefaces
+ // have ≈1.25× ascent which would otherwise stretch every line
+ // that contains an emoji vs surrounding text-only lines.
+ let (_, line_metrics) = measure_text("X", font);
+ fragments.push(Fragment::Emoji {
+ text: cluster.text.to_string(),
+ typeface,
+ size: font.size,
+ presentation: cluster.presentation,
+ structure: cluster.structure,
+ advance,
+ metrics,
+ line_metrics,
+ baseline_offset: style.baseline_offset,
+ });
+ }
+ EmojiTypeface::Unavailable { attempted } => {
+ measurer.warn_emoji_unavailable_once(cluster.text, &attempted);
+ emit_text_words(
+ cluster.text,
+ font,
+ style,
+ hyperlink_url,
+ measure_text,
+ fragments,
+ );
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ── split_into_words ─────────────────────────────────────────────────
+
+ #[test]
+ fn split_single_word() {
+ assert_eq!(split_into_words("hello"), vec!["hello"]);
+ }
+
+ #[test]
+ fn split_two_words() {
+ assert_eq!(split_into_words("hello world"), vec!["hello ", "world"]);
+ }
+
+ #[test]
+ fn split_trailing_space() {
+ assert_eq!(split_into_words("hello "), vec!["hello "]);
+ }
+
+ #[test]
+ fn non_breaking_hyphen_stays_inside_word() {
+ assert_eq!(split_into_words("ID‑001"), vec!["ID‑001"]);
+ }
+
+ // ── L1, L2, L4: emoji cluster integration ────────────────────────────
+
+ use crate::render::emoji::cluster::EmojiPresentation;
+ use crate::render::fonts::FontRegistry;
+ use crate::render::layout::measurer::TextMeasurer;
+
+ use std::rc::Rc;
+
+ fn font(family: &str, size: f32) -> FontProps {
+ FontProps {
+ family: Rc::from(family),
+ size: Pt::new(size),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }
+ }
+
+ fn style() -> TextRunStyle {
+ TextRunStyle {
+ color: RgbColor::BLACK,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ }
+ }
+
+ /// L1 — Run "hi 📞" produces `[Text("hi "), Emoji(...)]` when an emoji
+ /// typeface is resolvable on the host. Skipped on hosts without one.
+ #[test]
+ fn l1_emoji_run_splits_into_text_and_emoji_fragments() {
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ // Bail if the host has no color emoji — Phase 3 is platform-aware.
+ use crate::render::emoji::resolve::EmojiTypeface;
+ if matches!(
+ measurer.resolve_emoji(None),
+ EmojiTypeface::Unavailable { .. }
+ ) {
+ eprintln!("skipping L1: no color emoji typeface on this host");
+ return;
+ }
+ let mut fragments = Vec::new();
+ let measure = |text: &str, fp: &FontProps| measurer.measure(text, fp);
+ emit_text_fragments(
+ "hi \u{1F4DE}",
+ &font("Calibri", 12.0),
+ &style(),
+ None,
+ &measure,
+ Some(&measurer),
+ &mut fragments,
+ );
+ assert_eq!(
+ fragments.len(),
+ 2,
+ "expected 2 fragments (Text + Emoji), got {fragments:#?}"
+ );
+ match &fragments[0] {
+ Fragment::Text { text, .. } => assert_eq!(&**text, "hi "),
+ other => panic!("first fragment must be Text, got {other:?}"),
+ }
+ match &fragments[1] {
+ Fragment::Emoji {
+ text,
+ presentation,
+ advance,
+ ..
+ } => {
+ assert_eq!(text, "\u{1F4DE}");
+ assert_eq!(*presentation, EmojiPresentation::Emoji);
+ // L2 — advance must be > 0 when the typeface is resolved.
+ assert!(
+ advance.raw() > 0.0,
+ "advance must be positive, got {advance}"
+ );
+ }
+ other => panic!("second fragment must be Emoji, got {other:?}"),
+ }
+ }
+
+ /// L4 — When `measurer` is `None` (no emoji pipeline available), emoji
+ /// codepoints flow through the existing text path unchanged. This matches
+ /// the no-bundle / no-silent-degradation policy: the codepoint is still
+ /// preserved in the PDF's text stream.
+ #[test]
+ fn l4_no_measurer_routes_emoji_through_text_path() {
+ let mut fragments = Vec::new();
+ let measure = |text: &str, _fp: &FontProps| {
+ (
+ Pt::new(text.len() as f32 * 6.0),
+ TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(2.0),
+ leading: Pt::ZERO,
+ },
+ )
+ };
+ emit_text_fragments(
+ "hi \u{1F4DE}",
+ &font("Calibri", 12.0),
+ &style(),
+ None,
+ &measure,
+ None,
+ &mut fragments,
+ );
+ // No measurer → the whole input is fed to the text path. There must
+ // be zero Emoji fragments and the original codepoint must appear in
+ // exactly one Text fragment.
+ for f in &fragments {
+ assert!(
+ !matches!(f, Fragment::Emoji { .. }),
+ "no emoji fragments must be produced when measurer is None"
+ );
+ }
+ let joined: String = fragments
+ .iter()
+ .filter_map(|f| match f {
+ Fragment::Text { text, .. } => Some(&**text),
+ _ => None,
+ })
+ .collect();
+ assert!(
+ joined.contains('\u{1F4DE}'),
+ "emoji codepoint must survive through the text path"
+ );
+ }
+
+ // ── split_into_words (existing tests) ────────────────────────────────
+
+ #[test]
+ fn split_multiple_words() {
+ assert_eq!(
+ split_into_words("the quick brown fox"),
+ vec!["the ", "quick ", "brown ", "fox"]
+ );
+ }
+
+ #[test]
+ fn split_empty() {
+ let result: Vec<&str> = split_into_words("");
+ assert!(result.is_empty());
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/header_footer.rs b/crates/liteparse-docx/src/render/layout/header_footer.rs
new file mode 100644
index 0000000..4ad15f6
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/header_footer.rs
@@ -0,0 +1,1027 @@
+//! Header/footer layout — render headers and footers on each page.
+//!
+//! Headers and footers are laid out in a separate constraint frame
+//! (between page edge and body margin), then their draw commands are
+//! prepended to each page's command list.
+//!
+//! Content is built per-page so that PAGE / NUMPAGES fields (§17.16.4.1)
+//! evaluate to the correct values on each page.
+
+use crate::model::Block;
+
+use crate::render::dimension::Pt;
+use crate::render::resolve::header_footer::{HeaderFooterKind, HeaderFooterSet};
+
+use super::build::{BuildContext, BuildState, HeaderFooterContent, build_header_footer_content};
+use super::draw_command::{DrawCommand, LayoutedPage};
+use super::page::PageConfig;
+use super::section::{PageParity, stack_blocks};
+
+/// Decide which slot of a `HeaderFooterSet` applies to a given page,
+/// per ECMA-376 §17.10.6 (`titlePg`) and §17.10.1
+/// (`evenAndOddHeaders`). Returns `None` when the spec says the page
+/// should have *no* header/footer (e.g. `titlePg` is set but the
+/// section has no `first` slot — Word leaves the title page blank
+/// rather than reusing `default`).
+///
+/// Inputs:
+/// * `set` — the section's resolved slots.
+/// * `first_in_section` — true on the first physical page of the
+/// section. The section that owns the page is the one this set
+/// came from.
+/// * `logical_page_number` — 1-based, with `pgNumType.start` applied;
+/// matches the value the `PAGE` field would render. Even/odd
+/// selection is on this number, not the physical doc-absolute page.
+/// * `title_pg` — the section's `<w:titlePg/>` flag.
+/// * `even_and_odd` — the document setting `<w:evenAndOddHeaders/>`.
+pub fn select_slot<T>(
+ set: &HeaderFooterSet<T>,
+ first_in_section: bool,
+ logical_page_number: usize,
+ title_pg: bool,
+ even_and_odd: bool,
+) -> Option<&T> {
+ if title_pg && first_in_section {
+ // Spec: title-page header is *its own* slot. If absent, the
+ // first page of the section has a blank header — we do not
+ // fall through to `default`.
+ return set.first.as_ref();
+ }
+ if even_and_odd && logical_page_number.is_multiple_of(2) {
+ // Same rule for even pages: the `even` slot is authoritative
+ // when the document opts in. Missing `even` → blank.
+ return set.even.as_ref();
+ }
+ set.default.as_ref()
+}
+
+/// Variant of [`select_slot`] that also tells the caller which kind of
+/// slot was chosen. Useful for diagnostics and for callers that need
+/// to bookkeep per-kind layout state (e.g. header-area heights).
+pub fn select_slot_with_kind<T>(
+ set: &HeaderFooterSet<T>,
+ first_in_section: bool,
+ logical_page_number: usize,
+ title_pg: bool,
+ even_and_odd: bool,
+) -> Option<(HeaderFooterKind, &T)> {
+ if title_pg && first_in_section {
+ return set.first.as_ref().map(|t| (HeaderFooterKind::First, t));
+ }
+ if even_and_odd && logical_page_number.is_multiple_of(2) {
+ return set.even.as_ref().map(|t| (HeaderFooterKind::Even, t));
+ }
+ set.default.as_ref().map(|t| (HeaderFooterKind::Default, t))
+}
+
+/// Vertical body boundaries for one physical page.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct PageBodyBounds {
+ /// Absolute y coordinate where body layout starts.
+ pub(crate) top: Pt,
+ /// Absolute y coordinate where body layout ends.
+ pub(crate) bottom: Pt,
+}
+
+impl PageBodyBounds {
+ pub(crate) fn height(self) -> Pt {
+ (self.bottom - self.top).max(Pt::ZERO)
+ }
+}
+
+/// Header/footer clearances measured independently for each OOXML slot.
+///
+/// The selected slot is resolved per physical section page using the same
+/// rules as header/footer drawing. An absent selected slot leaves the
+/// configured body margin unchanged rather than falling back to another slot.
+#[derive(Clone, Debug)]
+pub(crate) struct HeaderFooterClearance {
+ page_height: Pt,
+ configured_top: Pt,
+ configured_bottom: Pt,
+ headers: HeaderFooterSet<Pt>,
+ footers: HeaderFooterSet<Pt>,
+ title_pg: bool,
+ even_and_odd: bool,
+ logical_page_base: usize,
+}
+
+impl HeaderFooterClearance {
+ pub(crate) fn new(
+ config: &PageConfig,
+ headers: HeaderFooterSet<Pt>,
+ footers: HeaderFooterSet<Pt>,
+ title_pg: bool,
+ even_and_odd: bool,
+ logical_page_base: usize,
+ ) -> Self {
+ Self {
+ page_height: config.page_size.height,
+ configured_top: config.margins.top,
+ configured_bottom: config.margins.bottom,
+ headers,
+ footers,
+ title_pg,
+ even_and_odd,
+ logical_page_base,
+ }
+ }
+
+ pub(crate) fn uniform(config: &PageConfig) -> Self {
+ Self::new(
+ config,
+ HeaderFooterSet::default(),
+ HeaderFooterSet::default(),
+ false,
+ false,
+ 1,
+ )
+ }
+
+ pub(crate) fn for_page(&self, section_page_index: usize) -> PageBodyBounds {
+ let first_in_section = section_page_index == 0;
+ let logical_page_number = self.logical_page_base + section_page_index;
+ let top = select_slot(
+ &self.headers,
+ first_in_section,
+ logical_page_number,
+ self.title_pg,
+ self.even_and_odd,
+ )
+ .copied()
+ .unwrap_or(self.configured_top)
+ .max(self.configured_top);
+ let bottom_margin = select_slot(
+ &self.footers,
+ first_in_section,
+ logical_page_number,
+ self.title_pg,
+ self.even_and_odd,
+ )
+ .copied()
+ .unwrap_or(self.configured_bottom)
+ .max(self.configured_bottom);
+
+ PageBodyBounds {
+ top,
+ bottom: self.page_height - bottom_margin,
+ }
+ }
+}
+
+/// Header and footer slots for a section, plus the spec flags that
+/// drive per-page selection. Selection rules live in [`select_slot`];
+/// the layout step calls it once per page in `render_headers_footers`.
+pub struct HeaderFooterBlocks<'a> {
+ /// Section's three header slots (`default` / `first` / `even`).
+ pub headers: &'a HeaderFooterSet<Vec<Block>>,
+ /// Section's three footer slots.
+ pub footers: &'a HeaderFooterSet<Vec<Block>>,
+ /// `<w:titlePg/>` set on the section.
+ pub title_pg: bool,
+ /// Document-level `<w:evenAndOddHeaders/>`.
+ pub even_and_odd: bool,
+}
+
+/// Page numbering context for header/footer field evaluation.
+///
+/// `logical_page_base` is the value the `PAGE` field reports on the
+/// first page of this section. Per §17.6.12 it is determined by the
+/// section's `<w:pgNumType w:start="…"/>`, falling back to a continuation
+/// of the previous section's logical numbering (see
+/// [`next_logical_page_base`]). Even/odd header selection (§17.10.1)
+/// also operates on this number.
+pub struct PageRange {
+ /// 0-based index of the first page in this section within the document.
+ pub page_base: usize,
+ /// Logical (PAGE-field) value of the first page in this section.
+ pub logical_page_base: usize,
+ /// Total physical page count in the document. NUMPAGES uses this
+ /// value; it deliberately tracks physical, not logical, pages —
+ /// matches Word.
+ pub total_pages: usize,
+}
+
+/// §17.6.12 — compute the logical page number (PAGE-field value) of a
+/// section's first page. If the section sets `<w:pgNumType w:start>`,
+/// numbering resets to that value; otherwise it continues from the
+/// previous section.
+///
+/// `prev_logical_end` is the value the next page *would* have if
+/// numbering simply continued — i.e. one past the last logical page of
+/// the previous section. For the first section, callers pass `1` so
+/// the document starts at logical page 1 by default.
+pub fn next_logical_page_base(
+ prev_logical_end: usize,
+ page_number_type: Option<&crate::model::PageNumberType>,
+) -> usize {
+ page_number_type
+ .and_then(|pnt| pnt.start)
+ .map(|s| s as usize)
+ .unwrap_or(prev_logical_end)
+}
+
+/// Render headers and footers onto already-laid-out pages.
+///
+/// `hf_blocks` contains the raw DOCX header/footer blocks; content is
+/// rebuilt per-page so that field values (PAGE, NUMPAGES) are correct.
+pub fn render_headers_footers(
+ pages: &mut [LayoutedPage],
+ config: &PageConfig,
+ hf_blocks: &HeaderFooterBlocks<'_>,
+ ctx: &BuildContext,
+ state: &mut BuildState,
+ default_line_height: Pt,
+ page_range: &PageRange,
+) {
+ let content_width = config.content_width();
+
+ for (page_idx, page) in pages.iter_mut().enumerate() {
+ // Logical page number drives both PAGE-field rendering
+ // (§17.16.4.1) and even/odd header selection (§17.10.1).
+ let logical_page_number = page_range.logical_page_base + page_idx;
+ // §20.4.3.1: the same number that selects the even/odd header decides
+ // which way an `inside`/`outside` float mirrors.
+ let parity = PageParity::of_page(logical_page_number);
+ let first_in_section = page_idx == 0;
+
+ // §17.10.6 + §17.10.1: pick the slot that applies to this page.
+ // The selection is the same for header and footer; the spec
+ // doesn't admit asymmetry between the two.
+ let header_blocks = select_slot(
+ hf_blocks.headers,
+ first_in_section,
+ logical_page_number,
+ hf_blocks.title_pg,
+ hf_blocks.even_and_odd,
+ );
+ let footer_blocks = select_slot(
+ hf_blocks.footers,
+ first_in_section,
+ logical_page_number,
+ hf_blocks.title_pg,
+ hf_blocks.even_and_odd,
+ );
+
+ if let Some(blocks) = header_blocks {
+ // Set per-page field context for PAGE/NUMPAGES evaluation.
+ state.field_ctx = crate::render::layout::fragment::FieldContext {
+ page_number: Some(logical_page_number),
+ num_pages: Some(page_range.total_pages),
+ };
+
+ let hf = build_header_footer_content(blocks, ctx, state);
+ render_header(
+ page,
+ config,
+ &hf,
+ content_width,
+ default_line_height,
+ parity,
+ );
+ }
+
+ if let Some(blocks) = footer_blocks {
+ state.field_ctx = crate::render::layout::fragment::FieldContext {
+ page_number: Some(logical_page_number),
+ num_pages: Some(page_range.total_pages),
+ };
+
+ let hf = build_header_footer_content(blocks, ctx, state);
+ render_footer(
+ page,
+ config,
+ &hf,
+ content_width,
+ default_line_height,
+ parity,
+ );
+ }
+ }
+
+ // Reset field context after header/footer rendering.
+ state.field_ctx = crate::render::layout::fragment::FieldContext::default();
+}
+
+/// Render a single header onto a page.
+fn render_header(
+ page: &mut LayoutedPage,
+ config: &PageConfig,
+ hf: &HeaderFooterContent,
+ content_width: Pt,
+ default_line_height: Pt,
+ parity: PageParity,
+) {
+ if hf.blocks.is_empty() {
+ return;
+ }
+
+ let (offset_x, offset_y) = if let Some((abs_x, abs_y)) = hf.absolute_position {
+ (abs_x, abs_y)
+ } else {
+ (config.margins.left, config.header_margin)
+ };
+
+ let result = stack_blocks(&hf.blocks, content_width, default_line_height, None, parity);
+
+ let mut header_cmds: Vec<DrawCommand> = Vec::new();
+
+ // §20.4.2.3 @behindDoc=true: paint behind text — emit before text commands.
+ for fi in hf.floating_images.iter().filter(|fi| fi.behind_doc) {
+ let img_y = match fi.y {
+ super::section::FloatingImageY::Absolute(y) => y,
+ super::section::FloatingImageY::RelativeToParagraph(off) => offset_y + off,
+ };
+ header_cmds.push(DrawCommand::Image {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ }
+
+ // Text / table commands.
+ for mut cmd in result.commands {
+ cmd.shift(offset_x, offset_y);
+ header_cmds.push(cmd);
+ }
+
+ // §20.4.2.3 @behindDoc=false: paint in front of text — emit after text commands.
+ for fi in hf.floating_images.iter().filter(|fi| !fi.behind_doc) {
+ let img_y = match fi.y {
+ super::section::FloatingImageY::Absolute(y) => y,
+ super::section::FloatingImageY::RelativeToParagraph(off) => offset_y + off,
+ };
+ header_cmds.push(DrawCommand::Image {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ }
+ // Paragraph-anchored shapes ride through `result.commands` above (their
+ // y depends on the host paragraph). Page-anchored shapes were resolved
+ // in `Page` frame so their absolute y is authoritative — emit them here
+ // without applying the header's offset shift.
+ emit_page_anchored_shapes(&hf.floating_shapes, parity, &mut header_cmds);
+
+ // Prepend header commands before body content.
+ header_cmds.append(&mut page.commands);
+ page.commands = header_cmds;
+}
+
+/// Render a single footer onto a page.
+fn render_footer(
+ page: &mut LayoutedPage,
+ config: &PageConfig,
+ hf: &HeaderFooterContent,
+ content_width: Pt,
+ default_line_height: Pt,
+ parity: PageParity,
+) {
+ if hf.blocks.is_empty() {
+ return;
+ }
+
+ let result = stack_blocks(&hf.blocks, content_width, default_line_height, None, parity);
+
+ let footer_y = config.page_size.height - config.footer_margin - result.height;
+
+ // §20.4.2.3 @behindDoc=true: paint behind text.
+ for fi in hf.floating_images.iter().filter(|fi| fi.behind_doc) {
+ let img_y = match fi.y {
+ super::section::FloatingImageY::Absolute(y) => y,
+ super::section::FloatingImageY::RelativeToParagraph(off) => footer_y + off,
+ };
+ page.commands.push(DrawCommand::Image {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ }
+
+ for mut cmd in result.commands {
+ cmd.shift(config.margins.left, footer_y);
+ page.commands.push(cmd);
+ }
+
+ // §20.4.2.3 @behindDoc=false: paint in front of text.
+ for fi in hf.floating_images.iter().filter(|fi| !fi.behind_doc) {
+ let img_y = match fi.y {
+ super::section::FloatingImageY::Absolute(y) => y,
+ super::section::FloatingImageY::RelativeToParagraph(off) => footer_y + off,
+ };
+ page.commands.push(DrawCommand::Image {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ }
+ // Paragraph-anchored shapes ride through `result.commands` above (their
+ // y depends on the host paragraph). Page-anchored shapes were resolved
+ // in `Page` frame so their absolute y is authoritative — emit them here
+ // without applying the footer's stack shift.
+ emit_page_anchored_shapes(&hf.floating_shapes, parity, &mut page.commands);
+}
+
+/// Emit page-anchored floating shapes (§20.4.2.10 vertical anchor =
+/// `page` / `margin` / etc.) as Path + text commands at their absolute
+/// page coordinates. Mirrors the in-stacker emission in `stacker.rs`,
+/// but skipped here for clarity:
+/// no spacing collapse / paragraph anchoring, just absolute placement.
+fn emit_page_anchored_shapes(
+ shapes: &[super::section::FloatingShape],
+ parity: PageParity,
+ out: &mut Vec<DrawCommand>,
+) {
+ use super::section::FloatingImageY;
+ for fs in shapes {
+ let shape_y = match fs.y {
+ FloatingImageY::Absolute(y) => y,
+ // The extractor only routes Absolute-y shapes here; treat
+ // any RelativeToParagraph as an unreachable misroute and
+ // skip it rather than stacking on a non-existent paragraph.
+ FloatingImageY::RelativeToParagraph(_) => continue,
+ };
+ out.push(DrawCommand::Path {
+ origin: crate::render::geometry::PtOffset::new(fs.x.resolve(parity), shape_y),
+ rotation: fs.rotation,
+ flip_h: fs.flip_h,
+ flip_v: fs.flip_v,
+ extent: fs.size,
+ paths: fs.paths.clone(),
+ fill: fs.fill.clone(),
+ stroke: fs.stroke.clone(),
+ effects: fs.effects.clone(),
+ });
+ for mut cmd in fs.text_commands.iter().cloned() {
+ cmd.shift(fs.x.resolve(parity), shape_y);
+ out.push(cmd);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::geometry::{PtEdgeInsets, PtOffset, PtSize};
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::section::LayoutBlock;
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn make_hf(frags: Vec<Fragment>) -> HeaderFooterContent {
+ HeaderFooterContent {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: frags,
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ absolute_position: None,
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ fn text_frag(s: &str) -> Fragment {
+ let font = FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ };
+ Fragment::Text {
+ text: Rc::from(s),
+ font: Rc::new(font),
+ color: RgbColor::BLACK,
+ shading: None,
+ border: None,
+ width: Pt::new(40.0),
+ trimmed_width: Pt::new(40.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn test_config() -> PageConfig {
+ use crate::render::layout::page::ColumnGeometry;
+ PageConfig {
+ page_size: PtSize::new(Pt::new(612.0), Pt::new(792.0)),
+ margins: PtEdgeInsets::new(Pt::new(72.0), Pt::new(72.0), Pt::new(72.0), Pt::new(72.0)),
+ header_margin: Pt::new(36.0),
+ footer_margin: Pt::new(36.0),
+ columns: vec![ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: Pt::new(468.0),
+ }],
+ }
+ }
+
+ #[test]
+ fn no_header_footer_leaves_page_unchanged() {
+ let mut pages = [LayoutedPage::new(PtSize::new(
+ Pt::new(612.0),
+ Pt::new(792.0),
+ ))];
+ pages[0].commands.push(DrawCommand::Text {
+ text: "body".into(),
+ position: PtOffset::new(Pt::ZERO, Pt::ZERO),
+ font_family: Rc::from("T"),
+ font_size: Pt::new(12.0),
+ char_spacing: Pt::ZERO,
+ bold: false,
+ italic: false,
+ color: RgbColor::BLACK,
+ text_scale: 1.0,
+ });
+
+ let config = test_config();
+ // Direct call to render_header / render_footer with empty content.
+ let hf = HeaderFooterContent {
+ blocks: vec![],
+ absolute_position: None,
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ render_header(
+ &mut pages[0],
+ &config,
+ &hf,
+ config.content_width(),
+ Pt::new(14.0),
+ PageParity::Odd,
+ );
+ render_footer(
+ &mut pages[0],
+ &config,
+ &hf,
+ config.content_width(),
+ Pt::new(14.0),
+ PageParity::Odd,
+ );
+
+ assert_eq!(pages[0].commands.len(), 1, "no changes");
+ }
+
+ #[test]
+ fn header_prepended_to_page() {
+ let mut pages = [LayoutedPage::new(PtSize::new(
+ Pt::new(612.0),
+ Pt::new(792.0),
+ ))];
+ pages[0].commands.push(DrawCommand::Text {
+ text: "body".into(),
+ position: PtOffset::new(Pt::ZERO, Pt::ZERO),
+ font_family: Rc::from("T"),
+ font_size: Pt::new(12.0),
+ char_spacing: Pt::ZERO,
+ bold: false,
+ italic: false,
+ color: RgbColor::BLACK,
+ text_scale: 1.0,
+ });
+
+ let config = test_config();
+ let header = make_hf(vec![text_frag("Header")]);
+ render_header(
+ &mut pages[0],
+ &config,
+ &header,
+ config.content_width(),
+ Pt::new(14.0),
+ PageParity::Odd,
+ );
+
+ assert!(pages[0].commands.len() > 1);
+ // First command should be the header text
+ if let DrawCommand::Text { text, .. } = &pages[0].commands[0] {
+ assert_eq!(&**text, "Header");
+ }
+ }
+
+ #[test]
+ fn footer_appended_to_page() {
+ let mut pages = [LayoutedPage::new(PtSize::new(
+ Pt::new(612.0),
+ Pt::new(792.0),
+ ))];
+
+ let config = test_config();
+ let footer = make_hf(vec![text_frag("Footer")]);
+ render_footer(
+ &mut pages[0],
+ &config,
+ &footer,
+ config.content_width(),
+ Pt::new(14.0),
+ PageParity::Odd,
+ );
+
+ assert_eq!(pages[0].commands.len(), 1);
+ if let DrawCommand::Text { text, position, .. } = &pages[0].commands[0] {
+ assert_eq!(&**text, "Footer");
+ // Footer y should be near the bottom of the page.
+ assert!(position.y.raw() > 700.0, "footer y={}", position.y.raw());
+ }
+ }
+
+ #[test]
+ fn header_applied_to_all_pages() {
+ let mut pages = vec![
+ LayoutedPage::new(PtSize::new(Pt::new(612.0), Pt::new(792.0))),
+ LayoutedPage::new(PtSize::new(Pt::new(612.0), Pt::new(792.0))),
+ ];
+
+ let config = test_config();
+ let header = make_hf(vec![text_frag("H")]);
+ for page in pages.iter_mut() {
+ render_header(
+ page,
+ &config,
+ &header,
+ config.content_width(),
+ Pt::new(14.0),
+ PageParity::Odd,
+ );
+ }
+
+ // Both pages should have header
+ for page in &pages {
+ assert!(!page.commands.is_empty());
+ }
+ }
+
+ #[test]
+ fn header_y_position_uses_header_margin() {
+ let mut pages = [LayoutedPage::new(PtSize::new(
+ Pt::new(612.0),
+ Pt::new(792.0),
+ ))];
+ let config = test_config();
+ let header = make_hf(vec![text_frag("H")]);
+ render_header(
+ &mut pages[0],
+ &config,
+ &header,
+ config.content_width(),
+ Pt::new(14.0),
+ PageParity::Odd,
+ );
+
+ if let DrawCommand::Text { position, .. } = &pages[0].commands[0] {
+ // Header y should be near header_margin (36) + ascent
+ assert!(
+ position.y.raw() > 36.0 && position.y.raw() < 72.0,
+ "header y={} should be between header_margin and top margin",
+ position.y.raw()
+ );
+ }
+ }
+
+ #[test]
+ fn clearance_selects_first_even_and_default_bounds_per_page() {
+ let config = test_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: Some(Pt::new(90.0)),
+ first: Some(Pt::new(150.0)),
+ even: Some(Pt::new(110.0)),
+ },
+ HeaderFooterSet {
+ default: Some(Pt::new(80.0)),
+ first: Some(Pt::new(130.0)),
+ even: Some(Pt::new(100.0)),
+ },
+ true,
+ true,
+ 1,
+ );
+
+ assert_eq!(
+ clearance.for_page(0),
+ PageBodyBounds {
+ top: Pt::new(150.0),
+ bottom: Pt::new(662.0),
+ },
+ );
+ assert_eq!(
+ clearance.for_page(1),
+ PageBodyBounds {
+ top: Pt::new(110.0),
+ bottom: Pt::new(692.0),
+ },
+ );
+ assert_eq!(
+ clearance.for_page(2),
+ PageBodyBounds {
+ top: Pt::new(90.0),
+ bottom: Pt::new(712.0),
+ },
+ );
+ }
+
+ #[test]
+ fn clearance_uses_configured_margins_when_selected_slots_are_missing() {
+ let config = test_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: Some(Pt::new(120.0)),
+ first: None,
+ even: None,
+ },
+ HeaderFooterSet {
+ default: Some(Pt::new(100.0)),
+ first: None,
+ even: None,
+ },
+ true,
+ true,
+ 1,
+ );
+
+ assert_eq!(
+ clearance.for_page(0),
+ PageBodyBounds {
+ top: config.margins.top,
+ bottom: config.page_size.height - config.margins.bottom,
+ },
+ "missing first slots must not fall back to default",
+ );
+ assert_eq!(
+ clearance.for_page(1),
+ PageBodyBounds {
+ top: config.margins.top,
+ bottom: config.page_size.height - config.margins.bottom,
+ },
+ "missing even slots must not fall back to default",
+ );
+ }
+
+ #[test]
+ fn clearance_never_reduces_configured_page_margins() {
+ let config = test_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: Some(Pt::new(40.0)),
+ first: None,
+ even: None,
+ },
+ HeaderFooterSet {
+ default: Some(Pt::new(30.0)),
+ first: None,
+ even: None,
+ },
+ false,
+ false,
+ 1,
+ );
+
+ assert_eq!(
+ clearance.for_page(0),
+ PageBodyBounds {
+ top: config.margins.top,
+ bottom: config.page_size.height - config.margins.bottom,
+ },
+ );
+ }
+
+ /// Truth-table for `select_slot` covering ECMA-376 §17.10.6
+ /// (`titlePg`) and §17.10.1 (`evenAndOddHeaders`). Every test names
+ /// the rule it pins down; failures should pinpoint a specific
+ /// spec-rule violation.
+ mod selection {
+ use super::super::*;
+
+ /// Helper: a fully-populated set with marker strings so tests
+ /// can assert *which* slot was returned without reaching for
+ /// equality against block content.
+ fn full_set() -> HeaderFooterSet<&'static str> {
+ HeaderFooterSet {
+ default: Some("D"),
+ first: Some("F"),
+ even: Some("E"),
+ }
+ }
+
+ // §17.10.6 — titlePg ----------------------------------------
+
+ #[test]
+ fn title_page_with_first_slot_returns_first_on_page_one() {
+ let set = full_set();
+ assert_eq!(select_slot(&set, true, 1, true, false), Some(&"F"));
+ }
+
+ #[test]
+ fn title_page_without_first_slot_returns_none_not_default() {
+ // Spec literal + Word behavior: a missing `first` leaves
+ // the title page blank; it does NOT silently fall through
+ // to `default`.
+ let set = HeaderFooterSet::<&'static str> {
+ default: Some("D"),
+ first: None,
+ even: None,
+ };
+ assert_eq!(select_slot(&set, true, 1, true, false), None);
+ }
+
+ #[test]
+ fn title_page_flag_off_keeps_default_on_page_one() {
+ let set = full_set();
+ assert_eq!(select_slot(&set, true, 1, false, false), Some(&"D"));
+ }
+
+ #[test]
+ fn title_page_only_applies_to_first_page_of_section() {
+ // Even with `titlePg` on, page 2 of the section uses
+ // `default` (or `even` if the parity flag would apply,
+ // see combined-rule tests below).
+ let set = full_set();
+ assert_eq!(select_slot(&set, false, 2, true, false), Some(&"D"));
+ }
+
+ // §17.10.1 — evenAndOddHeaders ------------------------------
+
+ #[test]
+ fn even_and_odd_with_even_slot_returns_even_on_even_pages() {
+ let set = full_set();
+ assert_eq!(select_slot(&set, false, 2, false, true), Some(&"E"));
+ assert_eq!(select_slot(&set, false, 4, false, true), Some(&"E"));
+ }
+
+ #[test]
+ fn even_and_odd_without_even_slot_returns_none_not_default() {
+ let set = HeaderFooterSet::<&'static str> {
+ default: Some("D"),
+ first: None,
+ even: None,
+ };
+ assert_eq!(select_slot(&set, false, 2, false, true), None);
+ }
+
+ #[test]
+ fn even_and_odd_uses_default_on_odd_pages() {
+ let set = full_set();
+ assert_eq!(select_slot(&set, false, 1, false, true), Some(&"D"));
+ assert_eq!(select_slot(&set, false, 3, false, true), Some(&"D"));
+ }
+
+ #[test]
+ fn even_and_odd_flag_off_keeps_default_on_even_pages() {
+ // Without the document setting, the `even` slot is dead
+ // weight even on page 2.
+ let set = full_set();
+ assert_eq!(select_slot(&set, false, 2, false, false), Some(&"D"));
+ }
+
+ // Combined rules --------------------------------------------
+
+ #[test]
+ fn title_page_takes_precedence_over_even_and_odd_on_first_page() {
+ // titlePg with first_in_section=true wins outright, even
+ // when evenAndOddHeaders is on and the page is even.
+ let set = full_set();
+ assert_eq!(select_slot(&set, true, 2, true, true), Some(&"F"));
+ // Same rule with no `first` slot — still the title-page
+ // rule applies, returning None (not `even`).
+ let set2 = HeaderFooterSet::<&'static str> {
+ default: Some("D"),
+ first: None,
+ even: Some("E"),
+ };
+ assert_eq!(select_slot(&set2, true, 2, true, true), None);
+ }
+
+ #[test]
+ fn even_and_odd_governs_after_title_page_rule_is_satisfied() {
+ // first_in_section=false on page 2 with both flags on
+ // means the title-page rule no longer fires; even/odd
+ // does and returns `even`.
+ let set = full_set();
+ assert_eq!(select_slot(&set, false, 2, true, true), Some(&"E"));
+ }
+
+ // Universal fall-throughs -----------------------------------
+
+ #[test]
+ fn empty_set_returns_none_in_every_mode() {
+ let empty: HeaderFooterSet<&'static str> = HeaderFooterSet::default();
+ for &title_pg in &[false, true] {
+ for &even_and_odd in &[false, true] {
+ for &first in &[false, true] {
+ for page in 1..=3 {
+ assert_eq!(
+ select_slot(&empty, first, page, title_pg, even_and_odd),
+ None,
+ "empty set with title_pg={title_pg} even_and_odd={even_and_odd} \
+ first_in_section={first} page={page} must be None",
+ );
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn default_used_when_neither_flag_applies() {
+ let set = full_set();
+ assert_eq!(select_slot(&set, false, 1, false, false), Some(&"D"));
+ assert_eq!(select_slot(&set, false, 2, false, false), Some(&"D"));
+ assert_eq!(select_slot(&set, true, 5, false, false), Some(&"D"));
+ }
+
+ // §17.6.12 — pgNumType.start --------------------------------
+
+ #[test]
+ fn next_logical_page_base_continues_when_no_pg_num_type() {
+ // Section without `pgNumType` continues numbering from
+ // `prev_logical_end` (one past the previous section's last
+ // logical page).
+ assert_eq!(next_logical_page_base(1, None), 1);
+ assert_eq!(next_logical_page_base(7, None), 7);
+ }
+
+ #[test]
+ fn next_logical_page_base_uses_start_when_set() {
+ use crate::model::PageNumberType;
+ let pnt = PageNumberType {
+ format: None,
+ start: Some(5),
+ chap_style: None,
+ chap_sep: None,
+ };
+ // The continuation hint is overridden by the explicit start.
+ assert_eq!(next_logical_page_base(99, Some(&pnt)), 5);
+ }
+
+ #[test]
+ fn next_logical_page_base_falls_through_when_start_is_none() {
+ use crate::model::PageNumberType;
+ // pgNumType present but `start` not set — selection should
+ // ignore the (possibly non-default) format/chapStyle and
+ // continue numbering normally.
+ let pnt = PageNumberType {
+ format: None,
+ start: None,
+ chap_style: None,
+ chap_sep: None,
+ };
+ assert_eq!(next_logical_page_base(4, Some(&pnt)), 4);
+ }
+
+ // Variant returning the kind --------------------------------
+
+ #[test]
+ fn select_slot_with_kind_reports_the_chosen_slot() {
+ let set = full_set();
+ assert_eq!(
+ select_slot_with_kind(&set, true, 1, true, false),
+ Some((HeaderFooterKind::First, &"F")),
+ );
+ assert_eq!(
+ select_slot_with_kind(&set, false, 2, false, true),
+ Some((HeaderFooterKind::Even, &"E")),
+ );
+ assert_eq!(
+ select_slot_with_kind(&set, false, 3, false, true),
+ Some((HeaderFooterKind::Default, &"D")),
+ );
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/line.rs b/crates/liteparse-docx/src/render/layout/line.rs
new file mode 100644
index 0000000..a397d90
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/line.rs
@@ -0,0 +1,598 @@
+//! Line fitting — break fragments into lines that fit within a max width.
+
+use crate::render::dimension::Pt;
+use crate::render::layout::fragment::Fragment;
+
+/// A fitted line — a slice of fragments that fit within the available width.
+#[derive(Debug)]
+pub struct FittedLine {
+ /// Indices into the fragment list: [start, end).
+ pub start: usize,
+ pub end: usize,
+ /// Total width of all fragments in this line.
+ pub width: Pt,
+ /// Maximum height of any fragment in this line.
+ pub height: Pt,
+ /// Maximum height of text-only fragments on this line.
+ /// §17.3.1.33: Auto line spacing multiplier applies to text metrics,
+ /// not to inline image heights.
+ pub text_height: Pt,
+ /// Maximum ascent of any text fragment in this line.
+ pub ascent: Pt,
+ /// Whether this line ends with an explicit line break.
+ pub has_break: bool,
+}
+
+/// Break fragments into lines that fit within `max_width`.
+///
+/// Breaks at the last whitespace/hyphen boundary when a line overflows.
+/// A single fragment wider than `max_width` gets its own line (no infinite loop).
+///
+/// `first_line_width`: if provided, the first line uses this narrower width
+/// (e.g., to account for first-line indent). Subsequent lines use `max_width`.
+pub fn fit_lines(fragments: &[Fragment], max_width: Pt) -> Vec<FittedLine> {
+ fit_lines_with_first(
+ fragments,
+ max_width,
+ max_width,
+ crate::render::layout::paragraph::PTabGeometry {
+ max_width,
+ indent_left: Pt::ZERO,
+ indent_first_line: Pt::ZERO,
+ content_width: max_width,
+ float_left: Pt::ZERO,
+ float_right: Pt::ZERO,
+ },
+ )
+}
+
+/// Line fitting with separate first-line and remaining-line widths.
+///
+/// `ptab_geometry` is the paragraph geometry §17.3.1.30 position tabs resolve
+/// against. Fitting needs it because a tab whose alignment point lies behind
+/// the pen advances to the next line, and only fitting can create one.
+pub fn fit_lines_with_first(
+ fragments: &[Fragment],
+ first_line_width: Pt,
+ remaining_width: Pt,
+ ptab_geometry: crate::render::layout::paragraph::PTabGeometry,
+) -> Vec<FittedLine> {
+ if fragments.is_empty() {
+ return Vec::new();
+ }
+
+ let mut lines = Vec::new();
+ let mut line_start = 0;
+ let mut line_width = Pt::ZERO;
+ // §17.3.1.30: where the pen actually *is*, as opposed to how much width
+ // the line has accumulated. The two differ only across a position tab,
+ // which jumps the pen to its anchor while contributing a nominal width.
+ // Tracking it separately keeps `line_width` — and therefore every
+ // non-ptab paragraph's fitting — bit-for-bit unchanged.
+ let line_pen_start = |is_first_line: bool| {
+ ptab_geometry.indent_left
+ + if is_first_line {
+ ptab_geometry.indent_first_line
+ } else {
+ Pt::ZERO
+ }
+ };
+ let mut pen_x = line_pen_start(true);
+ // §17.3.1.30: `relativeTo="margin"` measures against the full text area,
+ // so once such a tab has placed content this line may legitimately use the
+ // space a paragraph's own right indent excludes. Until then the ordinary
+ // `content_width` bound applies.
+ let mut margin_span_active = false;
+ let mut line_height = Pt::ZERO;
+ let mut line_text_height = Pt::ZERO;
+ let mut line_ascent = Pt::ZERO;
+ let mut last_break_point = None; // index after which we can break
+
+ let mut i = 0;
+ while i < fragments.len() {
+ let frag = &fragments[i];
+
+ // Explicit line break — emit current line including the break fragment.
+ // LineBreak height already includes leading (from default_line_height).
+ if frag.is_line_break() {
+ line_height = line_height.max(frag.height());
+ line_text_height = line_text_height.max(frag.height());
+ lines.push(FittedLine {
+ start: line_start,
+ end: i + 1,
+ width: line_width,
+ height: line_height,
+ text_height: line_text_height,
+ ascent: line_ascent,
+ has_break: true,
+ });
+ line_start = i + 1;
+ line_width = Pt::ZERO;
+ pen_x = line_pen_start(lines.is_empty());
+ margin_span_active = false;
+ line_height = Pt::ZERO;
+ line_text_height = Pt::ZERO;
+ line_ascent = Pt::ZERO;
+ last_break_point = None;
+ i += 1;
+ continue;
+ }
+
+ // §17.3.1.30: a position tab whose alignment point lies behind the
+ // pen advances to that point on the *next* line. Decided here rather
+ // than at emission because it is a line break, and emission cannot
+ // create one.
+ if let Fragment::PTab {
+ align, relative_to, ..
+ } = frag
+ {
+ // Fitting cannot bound the zone by the line end the way emission
+ // does — the lines do not exist yet — so it scans to the end of the
+ // fragment list. Where the two disagree (a zone fitting then splits
+ // for width) emission is authoritative for the final x; this only
+ // decides whether the tab can be honoured on this line.
+ let end = crate::render::layout::paragraph::zone_end(fragments, i, fragments.len());
+ let placement = crate::render::layout::paragraph::resolve_ptab(
+ *align,
+ *relative_to,
+ ptab_geometry,
+ pen_x,
+ || crate::render::layout::paragraph::zone_width(fragments, i + 1, end),
+ );
+ match placement {
+ crate::render::layout::paragraph::PTabPlacement::Placed(at) => {
+ pen_x = at;
+ margin_span_active |=
+ matches!(relative_to, crate::model::PTabRelativeTo::Margin);
+ }
+ crate::render::layout::paragraph::PTabPlacement::AdvancesToNextLine { .. } => {
+ // Only break when doing so can help. A tab already first
+ // on its line would find the same anchor behind the same
+ // pen on the next one — acting on a condition the action
+ // cannot change is how this engine's pagination loops have
+ // historically become infinite.
+ if line_start < i {
+ let m = measure_range(fragments, line_start, i);
+ lines.push(FittedLine {
+ start: line_start,
+ end: i,
+ width: m.width,
+ height: m.height,
+ text_height: m.text_height,
+ ascent: m.ascent,
+ has_break: false,
+ });
+ line_start = i;
+ line_width = Pt::ZERO;
+ pen_x = line_pen_start(lines.is_empty());
+ margin_span_active = false;
+ line_height = Pt::ZERO;
+ line_text_height = Pt::ZERO;
+ line_ascent = Pt::ZERO;
+ last_break_point = None;
+ // Re-evaluate this tab against the fresh line.
+ continue;
+ }
+ }
+ }
+ }
+
+ let frag_width = frag.width();
+ let new_width = line_width + frag_width;
+
+ // Use first-line width for line 0, remaining width for subsequent lines.
+ let current_max = if lines.is_empty() {
+ first_line_width
+ } else {
+ remaining_width
+ };
+
+ // For overflow checking, use trimmed width — trailing whitespace on the
+ // last word is allowed to hang past the margin (standard Word behavior).
+ // The check uses: previous fragments' full widths + this fragment's trimmed width.
+ let check_width = line_width + frag.trimmed_width();
+
+ // Check if adding this fragment overflows. Once a margin-relative tab
+ // has placed content, the line's real right edge is the margin, and
+ // the pen — not the accumulated width sum — says where we are.
+ let overflows = if margin_span_active {
+ pen_x + frag.trimmed_width() > ptab_geometry.max_width
+ } else {
+ check_width > current_max
+ };
+ if overflows && line_start < i {
+ // Overflow — break at last break point, or before this fragment.
+ let break_at = last_break_point.unwrap_or(i);
+ let m = measure_range(fragments, line_start, break_at);
+ lines.push(FittedLine {
+ start: line_start,
+ end: break_at,
+ width: m.width,
+ height: m.height,
+ text_height: m.text_height,
+ ascent: m.ascent,
+ has_break: false,
+ });
+ line_start = break_at;
+ line_width = Pt::ZERO;
+ pen_x = line_pen_start(lines.is_empty());
+ margin_span_active = false;
+ line_height = Pt::ZERO;
+ line_text_height = Pt::ZERO;
+ line_ascent = Pt::ZERO;
+ last_break_point = None;
+ // Don't advance i — re-evaluate this fragment on the new line.
+ continue;
+ }
+
+ // If this is the first fragment on the line and it overflows,
+ // allow it (it will be the only fragment on this line). The
+ // paragraph renderer will clip/overflow as needed.
+ line_width = new_width;
+ // A position tab has already jumped the pen to its anchor; every other
+ // fragment advances it by its own width. Done here, after the overflow
+ // check, so the check sees the pen *at* this fragment rather than past it.
+ if !matches!(frag, Fragment::PTab { .. }) {
+ pen_x += frag_width;
+ }
+ line_height = line_height.max(frag.height());
+ // §17.3.1.33: text_height is the Auto line spacing base — use
+ // line_height() (includes leading) for text, glyph height for tabs.
+ match frag {
+ Fragment::Text { metrics, .. } => {
+ line_text_height = line_text_height.max(metrics.line_height());
+ line_ascent = line_ascent.max(metrics.ascent);
+ }
+ Fragment::Image { .. } => {} // images don't contribute to text_height
+ _ => {
+ line_text_height = line_text_height.max(frag.height());
+ }
+ }
+
+ // Track break opportunity: only after fragments that end with whitespace,
+ // or non-text fragments (tabs, images). Text fragments without trailing
+ // whitespace are mid-word continuations (e.g., a word split across runs)
+ // and must not be broken.
+ let is_break_point = match frag {
+ Fragment::Text { text, .. } => {
+ text.ends_with(' ') || text.ends_with('\t')
+ || text.ends_with('-')
+ || text.ends_with('\u{2010}') // hyphen
+ || text.ends_with('\u{2013}') // en-dash
+ || text.ends_with('\u{2014}') // em-dash
+ }
+ _ => true, // tabs, images, line breaks are always break points
+ };
+ if is_break_point {
+ last_break_point = Some(i + 1);
+ }
+
+ i += 1;
+ }
+
+ // Emit remaining fragments as the last line.
+ if line_start < fragments.len() {
+ lines.push(FittedLine {
+ start: line_start,
+ end: fragments.len(),
+ width: line_width,
+ height: line_height,
+ text_height: line_text_height,
+ ascent: line_ascent,
+ has_break: false,
+ });
+ }
+
+ lines
+}
+
+/// Measurements for a range of fragments.
+struct RangeMeasure {
+ width: Pt,
+ height: Pt,
+ text_height: Pt,
+ ascent: Pt,
+}
+
+/// Measure total width, max height, text height, and ascent for a range of fragments.
+fn measure_range(fragments: &[Fragment], start: usize, end: usize) -> RangeMeasure {
+ let mut m = RangeMeasure {
+ width: Pt::ZERO,
+ height: Pt::ZERO,
+ text_height: Pt::ZERO,
+ ascent: Pt::ZERO,
+ };
+ for frag in &fragments[start..end] {
+ m.width += frag.width();
+ m.height = m.height.max(frag.height());
+ match frag {
+ Fragment::Text { metrics, .. } => {
+ m.text_height = m.text_height.max(metrics.line_height());
+ m.ascent = m.ascent.max(metrics.ascent);
+ }
+ Fragment::Image { .. } => {}
+ _ => {
+ m.text_height = m.text_height.max(frag.height());
+ }
+ }
+ }
+ m
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::layout::fragment::{FontProps, TextMetrics};
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str, width: f32) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ #[test]
+ fn empty_fragments_no_lines() {
+ let lines = fit_lines(&[], Pt::new(100.0));
+ assert!(lines.is_empty());
+ }
+
+ #[test]
+ fn single_fragment_fits() {
+ let frags = vec![text_frag("hello", 30.0)];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].start, 0);
+ assert_eq!(lines[0].end, 1);
+ assert_eq!(lines[0].width.raw(), 30.0);
+ assert_eq!(lines[0].height.raw(), 14.0);
+ }
+
+ #[test]
+ fn two_fragments_fit_on_one_line() {
+ let frags = vec![text_frag("hello ", 35.0), text_frag("world", 30.0)];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].end, 2);
+ assert_eq!(lines[0].width.raw(), 65.0);
+ }
+
+ #[test]
+ fn overflow_breaks_at_boundary() {
+ let frags = vec![
+ text_frag("hello ", 60.0),
+ text_frag("world ", 60.0),
+ text_frag("end", 30.0),
+ ];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].start, 0);
+ assert_eq!(lines[0].end, 1); // "hello " on first line
+ assert_eq!(lines[1].start, 1);
+ assert_eq!(lines[1].end, 3); // "world " + "end" on second line
+ }
+
+ #[test]
+ fn non_breaking_hyphen_is_not_a_break_point() {
+ let frags = vec![
+ text_frag("prefix ", 45.0),
+ text_frag("ID‑", 20.0),
+ text_frag("001", 35.0),
+ ];
+ let lines = fit_lines(&frags, Pt::new(70.0));
+
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].end, 1);
+ assert_eq!(lines[1].start, 1);
+ assert_eq!(lines[1].end, 3);
+ }
+
+ #[test]
+ fn oversized_fragment_gets_own_line() {
+ let frags = vec![text_frag("verylongword", 200.0)];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 1, "oversized fragment still produces a line");
+ assert_eq!(lines[0].end, 1);
+ }
+
+ #[test]
+ fn line_break_forces_new_line() {
+ let frags = vec![
+ text_frag("before", 30.0),
+ Fragment::LineBreak {
+ line_height: Pt::new(14.0),
+ },
+ text_frag("after", 25.0),
+ ];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].end, 2); // "before" + line break
+ assert!(lines[0].has_break);
+ assert_eq!(lines[1].start, 2);
+ assert_eq!(lines[1].end, 3); // "after"
+ }
+
+ #[test]
+ fn exact_fit_no_overflow() {
+ let frags = vec![text_frag("a", 50.0), text_frag("b", 50.0)];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].width.raw(), 100.0);
+ }
+
+ #[test]
+ fn tab_uses_min_width_for_fitting() {
+ let frags = vec![
+ text_frag("text", 80.0),
+ Fragment::Tab {
+ line_height: Pt::new(14.0),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ fitting_width: None,
+ },
+ text_frag("more", 30.0),
+ ];
+ // 80 + 12 (MIN_TAB_WIDTH) = 92, still fits 100
+ // But + 30 = 122, doesn't fit
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 2);
+ }
+
+ #[test]
+ fn height_is_max_of_fragments() {
+ let frags = vec![
+ Fragment::Text {
+ text: "small".into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(10.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(20.0),
+ trimmed_width: Pt::new(20.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(9.0),
+ descent: Pt::new(3.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ },
+ Fragment::Text {
+ text: "big".into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(24.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(30.0),
+ trimmed_width: Pt::new(30.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(22.0),
+ descent: Pt::new(6.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ },
+ ];
+ let lines = fit_lines(&frags, Pt::new(100.0));
+
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0].height.raw(), 28.0, "max of 12 and 28");
+ assert_eq!(lines[0].ascent.raw(), 22.0, "max of 9 and 22");
+ }
+
+ #[test]
+ fn multiple_overflows_produce_multiple_lines() {
+ let frags = vec![
+ text_frag("a ", 40.0),
+ text_frag("b ", 40.0),
+ text_frag("c ", 40.0),
+ text_frag("d ", 40.0),
+ text_frag("e", 40.0),
+ ];
+ // max_width=70: "a " fits (40), +"b " = 80 > 70 → break
+ let lines = fit_lines(&frags, Pt::new(70.0));
+
+ assert!(lines.len() >= 3, "should produce at least 3 lines");
+ // Each line should have at most 1 fragment since 40+40=80 > 70
+ }
+
+ #[test]
+ fn first_line_narrower_than_remaining() {
+ // first_line_width=60, remaining_width=100.
+ // "a " (40pt) fits the narrow first line alone; "b " (40pt) + "c" (40pt)
+ // = 80pt fit together on the full 100pt remaining line.
+ let frags = vec![
+ text_frag("a ", 40.0),
+ text_frag("b ", 40.0),
+ text_frag("c", 40.0),
+ ];
+ let lines = fit_lines_with_first(
+ &frags,
+ Pt::new(60.0),
+ Pt::new(100.0),
+ crate::render::layout::paragraph::PTabGeometry {
+ max_width: Pt::new(100.0),
+ indent_left: Pt::ZERO,
+ indent_first_line: Pt::ZERO,
+ content_width: Pt::new(100.0),
+ float_left: Pt::ZERO,
+ float_right: Pt::ZERO,
+ },
+ );
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].end, 1, "only 'a ' fits the narrow first line");
+ assert_eq!(lines[1].start, 1);
+ assert_eq!(
+ lines[1].end, 3,
+ "'b ' + 'c' both fit on the full second line"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/measurer.rs b/crates/liteparse-docx/src/render/layout/measurer.rs
new file mode 100644
index 0000000..151ff6d
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/measurer.rs
@@ -0,0 +1,471 @@
+//! Text measurer — resolves text widths through a `FontRegistry`.
+//!
+//! C′ rewrite of upstream's Skia measurer over fontdb + skrifa. The
+//! measurement arithmetic is copied verbatim from upstream (`measure_str` is a
+//! cmap → sum-of-`hmtx`-advances walk with no shaping or kerning, then
+//! §17.3.2.45 `text_scale` on the advances and §17.3.2.35 `char_spacing` per
+//! character), so it cannot diverge; the things that could — font resolution
+//! and metric quantization — were measured in spikes 6–8:
+//!
+//! - widths agree with Skia to 99.82% exactly where both engines hold the
+//! same face, with no quantization divergence at any size;
+//! - line metrics (`ascent`/`descent`/`leading`, so line height and therefore
+//! pagination) are **bit-exact** against both CoreText- and FreeType-backed
+//! Skia — every corpus face resolves its metrics through `hhea`, and skrifa
+//! agrees with both platform scalers on all of them;
+//! - an unmapped codepoint contributes glyph 0's (.notdef) advance. The
+//! zero-contribution alternative was tried and *disproved* (spike 6): Skia
+//! has space-fallback handling of its own, and zeroing made parity worse.
+//!
+//! ## Sign conventions (the trap spike 7 hit)
+//!
+//! skrifa reports ascent positive-up and descent negative-down; [`TextMetrics`]
+//! stores ascent positive-up and descent positive-down, so descent is negated
+//! at this boundary. For underlines: upstream's comment claims Skia returns a
+//! negative-below value and that it negates to positive-below — **the comment
+//! has it backwards**. `SkFontMetrics::fUnderlinePosition` is positive below
+//! the baseline; upstream negates it, so `underline_metrics` actually returns
+//! a *negative-below* offset. skrifa's `post`-table `underlinePosition` is
+//! already negative-below, so matching upstream means passing it through
+//! untouched. (Diagnostic worth keeping: a 0%-exact comparison is never a font
+//! disagreement — some face would agree by chance. 0% means a sign or formula
+//! error on your own side.)
+//!
+//! ## Emoji
+//!
+//! Upstream shapes emoji clusters through Skia's HarfBuzz so ZWJ sequences
+//! measure to their ligated width. No shaper is wired here yet, so
+//! [`TextMeasurer::measure_with_typeface`] takes upstream's own documented
+//! fallback path — the cmap-only advance sum — for every cluster. A
+//! multi-codepoint sequence therefore over-measures relative to upstream by
+//! (n−1) glyph advances; acceptable for now, and the seam for a harfrust
+//! shaper is this one function.
+
+use std::cell::RefCell;
+use std::collections::{HashMap, HashSet};
+
+use rustc_hash::FxHashMap;
+use skrifa::MetadataProvider;
+use skrifa::instance::{LocationRef, Size};
+
+use crate::render::dimension::Pt;
+use crate::render::emoji::resolve::{EmojiFamily, EmojiResolver, EmojiTypeface, RegistryLookup};
+use crate::render::fonts::{FontRegistry, FontStyle, TypefaceEntry, TypefaceId};
+
+use super::fragment::{FontProps, TextMetrics};
+
+/// Per-(face, size) measurement state: the face's line metrics (constant for
+/// the slot), its underline metrics, and a memo of raw advance sums per
+/// distinct word seen. Keyed inside [`TextMeasurer`] by a stable slot index so
+/// the family string is hashed once per distinct (family, size, style), not
+/// once per call; the width memo is looked up by `&str` (via
+/// `Box<str>: Borrow<str>`) so a cache hit allocates nothing.
+struct FontSlot {
+ face: fontdb::ID,
+ size: Pt,
+ metrics: TextMetrics,
+ /// `post`-table underline (offset, thickness) in pt at `size`, already in
+ /// upstream's negative-below convention (i.e. skrifa's, untouched).
+ underline: Option<(f32, f32)>,
+ /// Raw advance sums (before `text_scale` / `char_spacing`), which depend
+ /// only on (face, size, text) — safe to reuse across runs that differ
+ /// only in scale or spacing.
+ widths: FxHashMap<Box<str>, f32>,
+}
+
+#[derive(Hash, Eq, PartialEq)]
+struct SlotKey {
+ family_lc: String,
+ /// Font size as raw bits for exact f32 hashing.
+ size_bits: u32,
+ bold: bool,
+ italic: bool,
+}
+
+/// Measures text using skrifa metrics for faces resolved through a
+/// [`FontRegistry`]. Holds per-instance memoization so repeated words cost a
+/// hash probe instead of a table walk.
+///
+/// Also owns the [`EmojiResolver`] for the same render, plus the warn-once
+/// dedup set for `Unavailable` clusters — mirroring upstream.
+pub struct TextMeasurer<'r> {
+ registry: &'r FontRegistry,
+ slots: RefCell<Vec<FontSlot>>,
+ slot_index: RefCell<HashMap<SlotKey, usize>>,
+ emoji_resolver: EmojiResolver<RegistryLookup<'r>>,
+ /// Per-render dedup set so we warn at most once per cluster about a
+ /// missing color emoji typeface.
+ warned_emoji: RefCell<HashSet<String>>,
+ /// Per-render memo of cluster advances from `measure_with_typeface`,
+ /// keyed by (face id, size in raw-f32 bits, cluster text).
+ emoji_advance_cache: RefCell<HashMap<(TypefaceId, u32, String), Pt>>,
+}
+
+impl<'r> TextMeasurer<'r> {
+ pub fn new(registry: &'r FontRegistry) -> Self {
+ Self {
+ registry,
+ slots: RefCell::new(Vec::new()),
+ slot_index: RefCell::new(HashMap::new()),
+ emoji_resolver: EmojiResolver::new(RegistryLookup { registry }),
+ warned_emoji: RefCell::new(HashSet::new()),
+ emoji_advance_cache: RefCell::new(HashMap::new()),
+ }
+ }
+
+ pub fn registry(&self) -> &'r FontRegistry {
+ self.registry
+ }
+
+ /// Slot for (family, size, bold, italic), resolving and reading the
+ /// face's metrics on first sight.
+ fn slot(&self, family: &str, size: Pt, bold: bool, italic: bool) -> usize {
+ let key = SlotKey {
+ family_lc: family.to_lowercase(),
+ size_bits: f32::from(size).to_bits(),
+ bold,
+ italic,
+ };
+ if let Some(&idx) = self.slot_index.borrow().get(&key) {
+ return idx;
+ }
+ let entry = self
+ .registry
+ .resolve(family, FontStyle::from_flags(bold, italic));
+ let slot = self.build_slot(entry.id, size);
+ let mut slots = self.slots.borrow_mut();
+ slots.push(slot);
+ let idx = slots.len() - 1;
+ self.slot_index.borrow_mut().insert(key, idx);
+ idx
+ }
+
+ fn build_slot(&self, face: fontdb::ID, size: Pt) -> FontSlot {
+ let px = f32::from(size);
+ let read = self.registry.db().with_face_data(face, |data, index| {
+ let font = skrifa::FontRef::from_index(data, index).ok()?;
+ let m = font.metrics(Size::new(px), LocationRef::default());
+ Some((
+ TextMetrics {
+ ascent: Pt::new(m.ascent),
+ // skrifa reports descent negative-down; TextMetrics wants
+ // positive-down.
+ descent: Pt::new(-m.descent),
+ leading: Pt::new(m.leading.max(0.0)),
+ },
+ m.underline.map(|u| (u.offset, u.thickness)),
+ ))
+ });
+ let (metrics, underline) = read.flatten().unwrap_or_else(|| {
+ log::warn!("face data unreadable for a resolved font; measuring as zero");
+ (
+ TextMetrics {
+ ascent: Pt::ZERO,
+ descent: Pt::ZERO,
+ leading: Pt::ZERO,
+ },
+ None,
+ )
+ });
+ FontSlot {
+ face,
+ size,
+ metrics,
+ underline,
+ widths: FxHashMap::default(),
+ }
+ }
+
+ /// Raw cmap advance sum for `text` at the slot's size — upstream's
+ /// `measure_str` equivalent (no shaping, no kerning). An unmapped
+ /// codepoint takes glyph 0 (.notdef), which is what a cmap lookup
+ /// genuinely yields — matching Skia rather than skipping the character.
+ fn raw_advance(&self, face: fontdb::ID, size: Pt, text: &str) -> f32 {
+ self.registry
+ .db()
+ .with_face_data(face, |data, index| {
+ let Ok(font) = skrifa::FontRef::from_index(data, index) else {
+ return 0.0;
+ };
+ let charmap = font.charmap();
+ let metrics =
+ font.glyph_metrics(Size::new(f32::from(size)), LocationRef::default());
+ let mut sum = 0.0f32;
+ for ch in text.chars() {
+ let gid = charmap.map(ch).unwrap_or(skrifa::GlyphId::NOTDEF);
+ sum += metrics.advance_width(gid).unwrap_or(0.0);
+ }
+ sum
+ })
+ .unwrap_or(0.0)
+ }
+
+ /// Measure a text string with the given font properties.
+ /// Returns (width, TextMetrics).
+ pub fn measure(&self, text: &str, font_props: &FontProps) -> (Pt, TextMetrics) {
+ let idx = self.slot(
+ &font_props.family,
+ font_props.size,
+ font_props.bold,
+ font_props.italic,
+ );
+ let (face, size, text_metrics, cached) = {
+ let slots = self.slots.borrow();
+ let s = &slots[idx];
+ (s.face, s.size, s.metrics, s.widths.get(text).copied())
+ };
+ let width = match cached {
+ Some(w) => w,
+ None => {
+ let w = self.raw_advance(face, size, text);
+ self.slots.borrow_mut()[idx]
+ .widths
+ .insert(Box::from(text), w);
+ w
+ }
+ };
+
+ // §17.3.2.45: scale the glyph advances horizontally per <w:w>.
+ // Applies to glyph widths only — character spacing (§17.3.2.35) is
+ // independent and is not scaled (the spec keeps the two separate so
+ // kerning in points is unchanged by character scale).
+ let scaled_width = Pt::new(width * font_props.text_scale);
+
+ // §17.3.2.35: include character spacing in the measured width so line
+ // fitting accounts for the extra inter-character space. Skip the
+ // char-count scan entirely in the common no-spacing case.
+ let spacing_extra = if font_props.char_spacing != Pt::ZERO {
+ font_props.char_spacing * (text.chars().count() as f32)
+ } else {
+ Pt::ZERO
+ };
+
+ (scaled_width + spacing_extra, text_metrics)
+ }
+
+ /// Query font metrics for underline positioning.
+ /// Returns (underline_position, underline_thickness) in points.
+ ///
+ /// The offset is **negative below the baseline** — see the module docs;
+ /// upstream's own comment states the opposite of what its code does, and
+ /// the parity harness proved the negative-below reading bit-exact.
+ pub fn underline_metrics(&self, font_props: &FontProps) -> (Pt, Pt) {
+ let idx = self.slot(
+ &font_props.family,
+ font_props.size,
+ font_props.bold,
+ font_props.italic,
+ );
+ let slots = self.slots.borrow();
+ let s = &slots[idx];
+ if s.underline.is_none() {
+ log::warn!(
+ "font '{}' ({:?}) missing underline metrics, using descent as fallback",
+ font_props.family,
+ font_props.size
+ );
+ }
+ // Fallback mirrors upstream: descent's magnitude, below the baseline
+ // (negative in this convention); thickness 1pt — the smallest visible
+ // line at 72dpi.
+ let position = Pt::new(
+ s.underline
+ .map(|(pos, _)| pos)
+ .unwrap_or(-s.metrics.descent.raw()),
+ );
+ let thickness = Pt::new(s.underline.map(|(_, t)| t).unwrap_or(1.0));
+ (position, thickness)
+ }
+
+ /// Get line height for the default font (used for empty paragraphs).
+ /// §17.3.1.33: includes leading so Auto line spacing scales the full
+ /// font-recommended height.
+ pub fn default_line_height(&self, family: &str, size: Pt) -> Pt {
+ let idx = self.slot(family, size, false, false);
+ let slots = self.slots.borrow();
+ let m = &slots[idx].metrics;
+ m.ascent + m.descent + m.leading
+ }
+
+ // ─── Emoji pipeline integration ────────────────────────────────────────
+
+ /// Resolve a color emoji typeface via the per-render [`EmojiResolver`].
+ /// Cached: repeat calls with the same `requested` family are O(1).
+ pub fn resolve_emoji(&self, requested: Option<EmojiFamily>) -> EmojiTypeface {
+ self.emoji_resolver.resolve(requested)
+ }
+
+ /// Measure a cluster directly against a resolved [`TypefaceEntry`],
+ /// bypassing the family-name lookup path. Used by the emoji pipeline,
+ /// which has already resolved the typeface and needs metrics at the
+ /// cluster's font size.
+ ///
+ /// Cmap-only — upstream's GSUB shaping fallback path, taken always here
+ /// until a harfrust shaper is wired in (see module docs).
+ pub fn measure_with_typeface(
+ &self,
+ text: &str,
+ typeface: &TypefaceEntry,
+ size: Pt,
+ ) -> (Pt, TextMetrics) {
+ let px = f32::from(size);
+ let text_metrics = self
+ .registry
+ .db()
+ .with_face_data(typeface.id, |data, index| {
+ let font = skrifa::FontRef::from_index(data, index).ok()?;
+ let m = font.metrics(Size::new(px), LocationRef::default());
+ Some(TextMetrics {
+ ascent: Pt::new(m.ascent),
+ descent: Pt::new(-m.descent),
+ leading: Pt::new(m.leading.max(0.0)),
+ })
+ })
+ .flatten()
+ .unwrap_or(TextMetrics {
+ ascent: Pt::ZERO,
+ descent: Pt::ZERO,
+ leading: Pt::ZERO,
+ });
+
+ let key = (TypefaceId(typeface.id), px.to_bits(), text.to_owned());
+ if let Some(&cached) = self.emoji_advance_cache.borrow().get(&key) {
+ return (cached, text_metrics);
+ }
+ let advance = Pt::new(self.raw_advance(typeface.id, size, text));
+ self.emoji_advance_cache.borrow_mut().insert(key, advance);
+ (advance, text_metrics)
+ }
+
+ /// Log a warning once per cluster when no color emoji typeface is
+ /// available on the host. The `attempted` list lets operators know
+ /// which packages to install (e.g. `fonts-noto-color-emoji` on Debian).
+ pub fn warn_emoji_unavailable_once(&self, cluster: &str, attempted: &[EmojiFamily]) {
+ let inserted = self.warned_emoji.borrow_mut().insert(cluster.to_string());
+ if inserted {
+ log::warn!(
+ "no color emoji typeface available for cluster {:?}; \
+ tried {:?}. Install a color emoji font on the host \
+ (e.g. fonts-noto-color-emoji) to render this cluster correctly.",
+ cluster,
+ attempted
+ );
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::rc::Rc;
+
+ fn fp_at_scale(scale: f32) -> FontProps {
+ FontProps {
+ family: Rc::from("Helvetica"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: scale,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }
+ }
+
+ #[test]
+ fn measure_scaled_width_is_proportional_to_text_scale() {
+ // §17.3.2.45: glyph advances scale linearly with <w:w>. A run at 80%
+ // must measure to 0.8× the width of the same text at 100%.
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+
+ let (w_100, _) = measurer.measure("scaling sample", &fp_at_scale(1.0));
+ let (w_80, _) = measurer.measure("scaling sample", &fp_at_scale(0.8));
+ let (w_150, _) = measurer.measure("scaling sample", &fp_at_scale(1.5));
+
+ // The relationship must hold even though the absolute value depends
+ // on which fallback font resolution picks on the test host.
+ if w_100.raw() <= 0.0 {
+ // A fontless CI host can't measure text — bail rather than
+ // assert; the text path is exercised by the corpus runs.
+ return;
+ }
+ assert!(
+ (w_80.raw() / w_100.raw() - 0.8).abs() < 0.01,
+ "80% scale must produce 0.8× width: 100%={}, 80%={}",
+ w_100.raw(),
+ w_80.raw(),
+ );
+ assert!(
+ (w_150.raw() / w_100.raw() - 1.5).abs() < 0.01,
+ "150% scale must produce 1.5× width: 100%={}, 150%={}",
+ w_100.raw(),
+ w_150.raw(),
+ );
+ }
+
+ #[test]
+ fn measure_char_spacing_not_scaled_by_text_scale() {
+ // §17.3.2.45 + §17.3.2.35: w:spacing (inter-character spacing)
+ // is independent of w:w. Doubling text_scale must NOT double
+ // the spacing contribution.
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+
+ let mut fp_scale_1 = fp_at_scale(1.0);
+ fp_scale_1.char_spacing = Pt::new(2.0);
+ let mut fp_scale_2 = fp_at_scale(2.0);
+ fp_scale_2.char_spacing = Pt::new(2.0);
+
+ let text = "abcde";
+ let (w1, _) = measurer.measure(text, &fp_scale_1);
+ let (w2, _) = measurer.measure(text, &fp_scale_2);
+
+ if w1.raw() <= 0.0 {
+ return;
+ }
+ // Spacing contribution = 5 chars × 2pt = 10pt at both scales.
+ // Glyph contribution doubles. So w2 - w1 should equal the glyph
+ // contribution at scale 1.0 (i.e. w1 minus the spacing extra).
+ let expected_glyph_w1 = w1.raw() - 10.0;
+ let observed_glyph_delta = w2.raw() - w1.raw();
+ assert!(
+ (observed_glyph_delta - expected_glyph_w1).abs() < 0.05,
+ "char_spacing must not be scaled by text_scale: \
+ w1={}, w2={}, expected glyph delta {}, observed {}",
+ w1.raw(),
+ w2.raw(),
+ expected_glyph_w1,
+ observed_glyph_delta,
+ );
+ }
+
+ #[test]
+ fn underline_position_is_negative_below_baseline() {
+ // The sign trap from spike 7: skrifa's post-table value passes
+ // through untouched, so for any real font the offset must come back
+ // negative (below the baseline).
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let (pos, thick) = measurer.underline_metrics(&fp_at_scale(1.0));
+ if thick.raw() == 1.0 && pos.raw() == 0.0 {
+ return; // fontless host fallback
+ }
+ assert!(
+ pos.raw() < 0.0,
+ "underline offset must be negative-below, got {}",
+ pos.raw()
+ );
+ assert!(thick.raw() > 0.0);
+ }
+
+ #[test]
+ fn default_line_height_is_metrics_sum() {
+ let registry = FontRegistry::new();
+ let measurer = TextMeasurer::new(&registry);
+ let dlh = measurer.default_line_height("Helvetica", Pt::new(12.0));
+ let (_, m) = measurer.measure("x", &fp_at_scale(1.0));
+ assert_eq!(dlh.raw(), (m.ascent + m.descent + m.leading).raw());
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/mod.rs b/crates/liteparse-docx/src/render/layout/mod.rs
index 57e2a75..52418d4 100644
--- a/crates/liteparse-docx/src/render/layout/mod.rs
+++ b/crates/liteparse-docx/src/render/layout/mod.rs
@@ -1,8 +1,469 @@
-//! Only the Skia-free part of dxpdf's layout stage.
+//! Flutter-inspired constraint-based layout engine.
//!
-//! `draw_command` is vendored because `resolve::shape_visuals` builds shape
-//! draw commands during resolve. The measurement/pagination modules
-//! (`build`, `line`, `measurer`, `page`, `paragraph`, `section`, `table`, …)
-//! are not: they are what stage 2 would port onto harfrust + skrifa.
+//! Core protocol: **constraints go down, sizes go up, parent sets position**.
+pub mod build;
+pub mod cell;
pub mod draw_command;
+pub mod float;
+pub mod fragment;
+pub mod header_footer;
+pub mod line;
+pub mod measurer;
+pub mod page;
+pub mod paragraph;
+pub mod section;
+pub mod table;
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::{PtEdgeInsets, PtSize};
+
+/// MCE §M.1.2: the branch of an `<mc:AlternateContent>` this renderer draws.
+///
+/// Exactly one branch is live. A consumer takes the first `<mc:Choice>` whose
+/// requirements it can meet and otherwise the `<mc:Fallback>`; it never takes
+/// both, because both describe the *same* object — the Choice in DrawingML,
+/// the Fallback in VML for clients that predate it.
+///
+/// Every walker that meets the element consults [`live_mc_branch`], so the
+/// answer is a property of the element rather than of who asked. Two
+/// predicates over one element is what produced the original double render,
+/// and a third walker that answered neither is what produced the *missing*
+/// render after it.
+///
+/// The `Fallback` arm deliberately does **not** split "float" from "inline".
+/// One VML fallback is routinely both, and by design: `extract_vml_primitive`
+/// draws a `<v:rect>`'s geometry and leaves its `text_commands` empty,
+/// `extract_vml_primitive_image` skips any shape that also hosts text, and the
+/// inline collector picks the text box up at the host paragraph. That division
+/// is by graphic role, not by branch, and it is exactly how a bare `<w:pict>`
+/// already renders — so a live Fallback goes to all of them and each takes the
+/// part it owns. Naming an owner per variant would look tidier and would drop
+/// the text of every VML rect that has one.
+pub(crate) enum McBranch<'a> {
+ /// The `<mc:Choice>` elements, in document order.
+ Choices(&'a [crate::model::McChoice]),
+ /// The `<mc:Fallback>`, reached only when no Choice carries anything we
+ /// can draw.
+ Fallback(&'a [crate::model::Inline]),
+ /// Choices we cannot draw, and no Fallback to fall back to.
+ Neither,
+}
+
+/// Pick the live branch of `ac`.
+///
+/// The test is **content-based**, not a `Requires` namespace check: a Choice
+/// may declare a namespace we nominally support and still hold nothing this
+/// renderer turns into geometry, and the honest question is whether we will
+/// actually draw it. What counts is an *anchor* — an anchored `wps:wsp` shape
+/// and an anchored picture are both `Inline::Image` with
+/// `ImagePlacement::Anchor`, so one question covers shapes and pictures alike
+/// and no walker has to ask a narrower version of it for itself.
+///
+/// Recurses through `Hyperlink`/`Field` wrappers and nested elements. §M.1.2's
+/// content model for a branch is `drawing | pict`, so a nested
+/// `<mc:AlternateContent>` cannot come from a document — but it can be built,
+/// and resolving it innermost-first is the only reading under which the outer
+/// answer stays consistent with the inner one.
+pub(crate) fn live_mc_branch(ac: &crate::model::AlternateContent) -> McBranch<'_> {
+ use crate::model::{ImagePlacement, Inline};
+
+ fn draws_an_anchor(inlines: &[Inline]) -> bool {
+ inlines.iter().any(|inline| match inline {
+ Inline::Image(img) => matches!(img.placement, ImagePlacement::Anchor(_)),
+ Inline::Hyperlink(link) => draws_an_anchor(&link.content),
+ Inline::Field(f) => draws_an_anchor(&f.content),
+ Inline::AlternateContent(inner) => {
+ matches!(live_mc_branch(inner), McBranch::Choices(_))
+ }
+ _ => false,
+ })
+ }
+
+ if ac.choices.iter().any(|c| draws_an_anchor(&c.content)) {
+ McBranch::Choices(&ac.choices)
+ } else {
+ match ac.fallback {
+ Some(ref fallback) => McBranch::Fallback(fallback),
+ None => McBranch::Neither,
+ }
+ }
+}
+
+/// §20.1.2.1.18: the uniform shrink `a:normAutofit` applies to one shape's text
+/// body — a multiplier on every font size in it, and one on every paragraph's
+/// line spacing.
+///
+/// Lives here rather than beside `BuildState` because both the block builder
+/// and the fragment layer apply it, and `fragment` must not depend on `build`.
+///
+/// [`ShapeAutoFit::NONE`] is the identity and is what every call site outside a
+/// shape text body passes. The functions that resolve a font size or a line
+/// spacing take it as an explicit *parameter* rather than reaching for a
+/// default, so that a new call site has to say which it is — a silently
+/// inherited `1.0` is how these attributes came to be dropped in the first
+/// place.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct ShapeAutoFit {
+ font_scale: f32,
+ line_spacing_scale: f32,
+}
+
+impl Default for ShapeAutoFit {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+
+impl ShapeAutoFit {
+ /// No shrink: the identity for both factors.
+ pub const NONE: Self = Self {
+ font_scale: 1.0,
+ line_spacing_scale: 1.0,
+ };
+
+ /// Read the shrink off a shape's `a:bodyPr`.
+ ///
+ /// Total over [`TextAutoFit`](crate::model::TextAutoFit) on purpose. Only
+ /// `normAutofit` carries a shrink: §20.1.2.1.16 `noAutofit` is the explicit
+ /// "do not", and §20.1.2.1.20 `spAutoFit` resizes the *shape* to its text,
+ /// which this sub-layout cannot do — it lays a body out inside an extent
+ /// the host already fixed. `spAutoFit` therefore degrades to no shrink,
+ /// which draws the text at its authored size rather than inventing a fit.
+ pub fn from_body(auto_fit: Option<crate::model::TextAutoFit>) -> Self {
+ use crate::model::TextAutoFit;
+
+ let Some(TextAutoFit::NormalAutoFit(na)) = auto_fit else {
+ return Self::NONE;
+ };
+ // Absent `@fontScale` is 100%; absent `@lnSpcReduction` is 0% *off*,
+ // hence a factor of 1. A negative or absurd value would invert or
+ // explode the layout, so both are clamped to a sane band rather than
+ // trusted — the file is untrusted input.
+ let font_scale = na
+ .font_scale
+ .map_or(1.0, |p| p.to_fraction())
+ .clamp(0.01, 10.0);
+ let line_spacing_scale =
+ (1.0 - na.line_spacing_reduction.map_or(0.0, |p| p.to_fraction())).clamp(0.01, 10.0);
+ Self {
+ font_scale,
+ line_spacing_scale,
+ }
+ }
+
+ /// Apply `@fontScale` to a resolved font size.
+ pub fn scale_font(self, size: Pt) -> Pt {
+ if self.font_scale == 1.0 {
+ size
+ } else {
+ Pt::new(size.raw() * self.font_scale)
+ }
+ }
+
+ /// Apply `@lnSpcReduction` to a line height that has already been resolved
+ /// against the paragraph's own §17.3.1.33 spacing rule.
+ ///
+ /// It must land *after* that resolution, not inside it. Folding the
+ /// reduction into an `Auto` multiplier looks equivalent and is not:
+ /// `resolve_line_height` floors `Auto` at the line's natural height, so a
+ /// multiplier below 1 is swallowed whole. That floor exists to stop a
+ /// user-authored multiplier from colliding glyph boxes — but crossing it is
+ /// precisely what `lnSpcReduction` is for. Word has already laid the body
+ /// out and decided the tightened text fits; the reduction is most of how it
+ /// made it fit.
+ pub fn scale_line_height(self, height: Pt) -> Pt {
+ if self.line_spacing_scale == 1.0 {
+ height
+ } else {
+ Pt::new(height.raw() * self.line_spacing_scale)
+ }
+ }
+}
+
+/// Box constraints passed from parent to child during layout.
+///
+/// Encodes the range of permissible widths and heights.
+/// A child's `perform_layout` must return a size within these bounds.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct BoxConstraints {
+ pub min_width: Pt,
+ pub max_width: Pt,
+ pub min_height: Pt,
+ pub max_height: Pt,
+}
+
+impl BoxConstraints {
+ /// Create constraints with explicit bounds.
+ pub fn new(min_width: Pt, max_width: Pt, min_height: Pt, max_height: Pt) -> Self {
+ debug_assert!(min_width.raw() <= max_width.raw());
+ debug_assert!(min_height.raw() <= max_height.raw());
+ Self {
+ min_width,
+ max_width,
+ min_height,
+ max_height,
+ }
+ }
+
+ /// Tight constraints — child must be exactly this size.
+ pub fn tight(size: PtSize) -> Self {
+ Self {
+ min_width: size.width,
+ max_width: size.width,
+ min_height: size.height,
+ max_height: size.height,
+ }
+ }
+
+ /// Tight width, loose height — child must be exactly this wide, any height up to max.
+ pub fn tight_width(width: Pt, max_height: Pt) -> Self {
+ Self {
+ min_width: width,
+ max_width: width,
+ min_height: Pt::ZERO,
+ max_height,
+ }
+ }
+
+ /// Loose constraints — child can be 0..max_size.
+ pub fn loose(max_size: PtSize) -> Self {
+ Self {
+ min_width: Pt::ZERO,
+ max_width: max_size.width,
+ min_height: Pt::ZERO,
+ max_height: max_size.height,
+ }
+ }
+
+ /// Unbounded constraints — child can be any size.
+ pub fn unbounded() -> Self {
+ Self {
+ min_width: Pt::ZERO,
+ max_width: Pt::INFINITY,
+ min_height: Pt::ZERO,
+ max_height: Pt::INFINITY,
+ }
+ }
+
+ /// Whether width is tight (min == max).
+ pub fn is_tight_width(&self) -> bool {
+ self.min_width == self.max_width
+ }
+
+ /// Whether height is tight (min == max).
+ pub fn is_tight_height(&self) -> bool {
+ self.min_height == self.max_height
+ }
+
+ /// Whether both axes are tight.
+ pub fn is_tight(&self) -> bool {
+ self.is_tight_width() && self.is_tight_height()
+ }
+
+ /// Intersect with another set of constraints — the result satisfies both.
+ /// Used when nesting containers that each impose their own limits.
+ pub fn enforce(&self, other: &BoxConstraints) -> BoxConstraints {
+ BoxConstraints {
+ min_width: self.min_width.max(other.min_width).min(self.max_width),
+ max_width: self.max_width.min(other.max_width).max(self.min_width),
+ min_height: self.min_height.max(other.min_height).min(self.max_height),
+ max_height: self.max_height.min(other.max_height).max(self.min_height),
+ }
+ }
+
+ /// Subtract edge insets from the constraints — shrinks the available space.
+ /// Used when adding padding, margins, or cell insets.
+ pub fn deflate(&self, edges: &PtEdgeInsets) -> BoxConstraints {
+ let h = edges.horizontal();
+ let v = edges.vertical();
+ BoxConstraints {
+ min_width: (self.min_width - h).max(Pt::ZERO),
+ max_width: (self.max_width - h).max(Pt::ZERO),
+ min_height: (self.min_height - v).max(Pt::ZERO),
+ max_height: (self.max_height - v).max(Pt::ZERO),
+ }
+ }
+
+ /// Clamp a size to fit within these constraints.
+ pub fn constrain(&self, size: PtSize) -> PtSize {
+ PtSize {
+ width: size.width.max(self.min_width).min(self.max_width),
+ height: size.height.max(self.min_height).min(self.max_height),
+ }
+ }
+
+ /// The maximum size allowed by these constraints.
+ pub fn biggest(&self) -> PtSize {
+ PtSize {
+ width: self.max_width,
+ height: self.max_height,
+ }
+ }
+
+ /// The minimum size allowed by these constraints.
+ pub fn smallest(&self) -> PtSize {
+ PtSize {
+ width: self.min_width,
+ height: self.min_height,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tight_constraints() {
+ let c = BoxConstraints::tight(PtSize::new(Pt::new(100.0), Pt::new(200.0)));
+ assert!(c.is_tight());
+ assert!(c.is_tight_width());
+ assert!(c.is_tight_height());
+ assert_eq!(c.min_width.raw(), 100.0);
+ assert_eq!(c.max_width.raw(), 100.0);
+ assert_eq!(c.min_height.raw(), 200.0);
+ assert_eq!(c.max_height.raw(), 200.0);
+ }
+
+ #[test]
+ fn tight_width_loose_height() {
+ let c = BoxConstraints::tight_width(Pt::new(300.0), Pt::new(500.0));
+ assert!(c.is_tight_width());
+ assert!(!c.is_tight_height());
+ assert_eq!(c.min_height.raw(), 0.0);
+ assert_eq!(c.max_height.raw(), 500.0);
+ }
+
+ #[test]
+ fn loose_constraints() {
+ let c = BoxConstraints::loose(PtSize::new(Pt::new(400.0), Pt::new(600.0)));
+ assert!(!c.is_tight());
+ assert_eq!(c.min_width.raw(), 0.0);
+ assert_eq!(c.max_width.raw(), 400.0);
+ assert_eq!(c.min_height.raw(), 0.0);
+ assert_eq!(c.max_height.raw(), 600.0);
+ }
+
+ #[test]
+ fn unbounded_constraints() {
+ let c = BoxConstraints::unbounded();
+ assert!(c.max_width.raw().is_infinite());
+ assert!(c.max_height.raw().is_infinite());
+ }
+
+ #[test]
+ fn biggest_and_smallest() {
+ let c = BoxConstraints::new(Pt::new(10.0), Pt::new(100.0), Pt::new(20.0), Pt::new(200.0));
+ assert_eq!(c.biggest(), PtSize::new(Pt::new(100.0), Pt::new(200.0)));
+ assert_eq!(c.smallest(), PtSize::new(Pt::new(10.0), Pt::new(20.0)));
+ }
+
+ #[test]
+ fn constrain_clamps_to_bounds() {
+ let c = BoxConstraints::new(Pt::new(50.0), Pt::new(200.0), Pt::new(50.0), Pt::new(200.0));
+ // Too small
+ let s1 = c.constrain(PtSize::new(Pt::new(10.0), Pt::new(10.0)));
+ assert_eq!(s1, PtSize::new(Pt::new(50.0), Pt::new(50.0)));
+
+ // Too big
+ let s2 = c.constrain(PtSize::new(Pt::new(999.0), Pt::new(999.0)));
+ assert_eq!(s2, PtSize::new(Pt::new(200.0), Pt::new(200.0)));
+
+ // Within bounds
+ let s3 = c.constrain(PtSize::new(Pt::new(100.0), Pt::new(100.0)));
+ assert_eq!(s3, PtSize::new(Pt::new(100.0), Pt::new(100.0)));
+ }
+
+ #[test]
+ fn deflate_shrinks_constraints() {
+ let c = BoxConstraints::tight(PtSize::new(Pt::new(400.0), Pt::new(600.0)));
+ let edges = PtEdgeInsets::new(
+ Pt::new(10.0), // top
+ Pt::new(20.0), // right
+ Pt::new(30.0), // bottom
+ Pt::new(40.0), // left
+ );
+ let d = c.deflate(&edges);
+
+ // width shrinks by left+right = 60
+ assert_eq!(d.max_width.raw(), 340.0);
+ // height shrinks by top+bottom = 40
+ assert_eq!(d.max_height.raw(), 560.0);
+ }
+
+ #[test]
+ fn deflate_does_not_go_negative() {
+ let c = BoxConstraints::tight(PtSize::new(Pt::new(10.0), Pt::new(10.0)));
+ let edges = PtEdgeInsets::new(
+ Pt::new(100.0),
+ Pt::new(100.0),
+ Pt::new(100.0),
+ Pt::new(100.0),
+ );
+ let d = c.deflate(&edges);
+ assert_eq!(d.max_width.raw(), 0.0);
+ assert_eq!(d.max_height.raw(), 0.0);
+ }
+
+ #[test]
+ fn enforce_intersects_constraints() {
+ let parent =
+ BoxConstraints::new(Pt::new(0.0), Pt::new(400.0), Pt::new(0.0), Pt::new(600.0));
+ let child = BoxConstraints::new(
+ Pt::new(100.0),
+ Pt::new(300.0),
+ Pt::new(50.0),
+ Pt::new(500.0),
+ );
+ let result = parent.enforce(&child);
+
+ assert_eq!(result.min_width.raw(), 100.0);
+ assert_eq!(result.max_width.raw(), 300.0);
+ assert_eq!(result.min_height.raw(), 50.0);
+ assert_eq!(result.max_height.raw(), 500.0);
+ }
+
+ #[test]
+ fn enforce_tight_parent_wins() {
+ let parent = BoxConstraints::tight(PtSize::new(Pt::new(200.0), Pt::new(300.0)));
+ let child = BoxConstraints::loose(PtSize::new(Pt::new(400.0), Pt::new(600.0)));
+ let result = parent.enforce(&child);
+
+ // Parent is tight — result should also be tight at parent's size
+ assert!(result.is_tight());
+ assert_eq!(result.max_width.raw(), 200.0);
+ assert_eq!(result.max_height.raw(), 300.0);
+ }
+
+ #[test]
+ fn enforce_wider_child_gets_clamped() {
+ let parent =
+ BoxConstraints::new(Pt::new(0.0), Pt::new(200.0), Pt::new(0.0), Pt::new(200.0));
+ let child = BoxConstraints::new(Pt::new(0.0), Pt::new(999.0), Pt::new(0.0), Pt::new(999.0));
+ let result = parent.enforce(&child);
+
+ assert_eq!(result.max_width.raw(), 200.0, "child can't exceed parent");
+ assert_eq!(result.max_height.raw(), 200.0);
+ }
+
+ // ── Constraint flow simulation ───────────────────────────────────────
+
+ #[test]
+ fn page_to_body_to_cell_cascade() {
+ // Simulate: Page (612x792) → margins (72 each) → table cell (200 wide, 20+20 margins)
+ let page = BoxConstraints::tight(PtSize::new(Pt::new(612.0), Pt::new(792.0)));
+ let margins = PtEdgeInsets::new(Pt::new(72.0), Pt::new(72.0), Pt::new(72.0), Pt::new(72.0));
+ let body = page.deflate(&margins);
+ assert_eq!(body.max_width.raw(), 468.0); // 612 - 144
+ assert_eq!(body.max_height.raw(), 648.0); // 792 - 144
+
+ // Table cell: tight width 200, loose height
+ let cell = BoxConstraints::tight_width(Pt::new(200.0), body.max_height);
+ let cell_padding =
+ PtEdgeInsets::new(Pt::new(5.0), Pt::new(10.0), Pt::new(5.0), Pt::new(10.0));
+ let cell_content = cell.deflate(&cell_padding);
+ assert_eq!(cell_content.max_width.raw(), 180.0); // 200 - 20
+ assert!(cell_content.is_tight_width());
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/page.rs b/crates/liteparse-docx/src/render/layout/page.rs
new file mode 100644
index 0000000..60adaeb
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/page.rs
@@ -0,0 +1,607 @@
+//! Page configuration — convert section properties to layout-ready config.
+
+use crate::model::{Columns, SectionProperties};
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::{PtEdgeInsets, PtSize};
+
+/// §17.6.13: default page width when w:pgSz is absent. Word uses US Letter (8.5 inches = 12240 twips).
+const SPEC_DEFAULT_PAGE_WIDTH: Pt = Pt::new(612.0);
+/// §17.6.13: default page height when w:pgSz is absent. Word uses US Letter (11 inches = 15840 twips).
+const SPEC_DEFAULT_PAGE_HEIGHT: Pt = Pt::new(792.0);
+/// §17.6.11: default page margin when w:pgMar is absent (1 inch = 1440 twips).
+const SPEC_DEFAULT_MARGIN: Pt = Pt::new(72.0);
+
+/// A single column's layout geometry.
+#[derive(Debug, Clone, Copy)]
+pub struct ColumnGeometry {
+ /// X offset of this column relative to the left page margin.
+ pub x_offset: Pt,
+ /// Available text width within this column.
+ pub width: Pt,
+}
+
+/// Page layout configuration in points.
+#[derive(Debug, Clone)]
+pub struct PageConfig {
+ pub page_size: PtSize,
+ pub margins: PtEdgeInsets,
+ pub header_margin: Pt,
+ pub footer_margin: Pt,
+ /// §17.6.4: column layout. Single-element vec for normal single-column.
+ pub columns: Vec<ColumnGeometry>,
+}
+
+impl Default for PageConfig {
+ fn default() -> Self {
+ let content_width = SPEC_DEFAULT_PAGE_WIDTH - SPEC_DEFAULT_MARGIN - SPEC_DEFAULT_MARGIN;
+ Self {
+ page_size: PtSize::new(SPEC_DEFAULT_PAGE_WIDTH, SPEC_DEFAULT_PAGE_HEIGHT),
+ margins: PtEdgeInsets::new(
+ SPEC_DEFAULT_MARGIN,
+ SPEC_DEFAULT_MARGIN,
+ SPEC_DEFAULT_MARGIN,
+ SPEC_DEFAULT_MARGIN,
+ ),
+ header_margin: SPEC_DEFAULT_MARGIN / 2.0,
+ footer_margin: SPEC_DEFAULT_MARGIN / 2.0,
+ columns: vec![ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: content_width,
+ }],
+ }
+ }
+}
+
+impl PageConfig {
+ /// Build from section properties, falling back to US Letter defaults.
+ pub fn from_section(sect: &SectionProperties) -> Self {
+ let mut cfg = Self::default();
+
+ if let Some(ref ps) = sect.page_size {
+ if let Some(w) = ps.width {
+ cfg.page_size.width = Pt::from(w);
+ }
+ if let Some(h) = ps.height {
+ cfg.page_size.height = Pt::from(h);
+ }
+ }
+
+ if let Some(ref pm) = sect.page_margins {
+ if let Some(t) = pm.top {
+ cfg.margins.top = Pt::from(t);
+ }
+ if let Some(r) = pm.right {
+ cfg.margins.right = Pt::from(r);
+ }
+ if let Some(b) = pm.bottom {
+ cfg.margins.bottom = Pt::from(b);
+ }
+ if let Some(l) = pm.left {
+ cfg.margins.left = Pt::from(l);
+ }
+ if let Some(h) = pm.header {
+ cfg.header_margin = Pt::from(h);
+ }
+ if let Some(f) = pm.footer {
+ cfg.footer_margin = Pt::from(f);
+ }
+ }
+
+ // §17.6.4: compute column geometry from the *clamped* text width, so a
+ // page whose margins exceed its width yields zero-width columns rather
+ // than negative ones.
+ cfg.columns = compute_columns(cfg.content_width(), &sect.columns);
+
+ cfg
+ }
+
+ /// Available width for body content (page width minus left and right
+ /// margins), never negative.
+ ///
+ /// The clamp is load-bearing, not defensive tidiness: margins wider than the
+ /// page are expressible in the file format, and a negative width flows
+ /// straight into `BoxConstraints::new`, whose `debug_assert!(min <= max)`
+ /// then fires — a panic through the public `convert()` API in debug builds,
+ /// and a negative-width layout in release. See also `compute_columns`,
+ /// which clamps the same quantity per column.
+ pub fn content_width(&self) -> Pt {
+ (self.page_size.width - self.margins.left - self.margins.right).max(Pt::ZERO)
+ }
+
+ /// Number of columns in this section.
+ pub fn num_columns(&self) -> usize {
+ self.columns.len()
+ }
+
+ /// Available height for body content (page height minus top and bottom
+ /// margins), never negative — same reasoning as [`PageConfig::content_width`].
+ pub fn content_height(&self) -> Pt {
+ (self.page_size.height - self.margins.top - self.margins.bottom).max(Pt::ZERO)
+ }
+}
+
+/// §17.6.4: default spacing between columns when `w:space` is omitted
+/// (720 twips = 0.5 inch).
+const DEFAULT_COLUMN_SPACE: Pt = Pt::new(36.0);
+
+/// Narrowest column worth laying out. Used only to bound a file-controlled
+/// column count — see [`clamp_column_count`].
+const MIN_COLUMN_WIDTH: Pt = Pt::new(1.0);
+
+/// §17.6.4: bound the requested column count by what the page can physically
+/// hold.
+///
+/// `w:num` is a file-controlled `u32` that both sizes an allocation and drives a
+/// loop, so it needs a ceiling. The ceiling is derived from the page rather than
+/// picked as a magic number: a column narrower than [`MIN_COLUMN_WIDTH`] cannot
+/// show anything, so a count implying narrower columns describes no layout a
+/// document could have meant.
+///
+/// **The gaps count.** `n` columns carry `n - 1` gaps of `space`, so the widest
+/// usable count solves
+/// `(content_width - space·(n-1)) / n >= MIN_COLUMN_WIDTH`, i.e.
+/// `n <= (content_width + space) / (MIN_COLUMN_WIDTH + space)`. **This is the
+/// only thing keeping the column width non-negative** — `compute_columns`
+/// deliberately does not clamp afterwards. Bounding on
+/// `content_width / MIN_COLUMN_WIDTH` alone ignores the gaps and still admits
+/// counts whose column width comes out **negative** — which is what made a
+/// 15-column section panic. Solving for the gaps is what makes the width
+/// non-negative *by construction* rather than by a later clamp.
+fn clamp_column_count(requested: u32, content_width: Pt, space: Pt) -> usize {
+ let requested = (requested as usize).max(1);
+ if content_width <= Pt::ZERO {
+ return 1;
+ }
+ let space = space.raw().max(0.0);
+ let max_by_page =
+ (((content_width.raw() + space) / (MIN_COLUMN_WIDTH.raw() + space)) as usize).max(1);
+ if requested > max_by_page {
+ log::warn!(
+ "§17.6.4: w:num={requested} does not fit a {content_width:?} text area at \
+ {space}pt spacing; clamped to {max_by_page}"
+ );
+ }
+ requested.min(max_by_page)
+}
+
+/// §17.6.4: compute column geometry from section column properties.
+///
+/// `w:num` is authoritative for the **count**: a row of `<w:col>` children
+/// shorter than `w:num` leaves the remaining columns at the default width
+/// rather than dropping them, and children beyond `w:num` are ignored.
+///
+/// Individual `<w:col>` widths apply only when the file **explicitly** opts out
+/// of equal widths. §17.6.4's `equalWidth` defaults to `true` when omitted, so
+/// an absent attribute means equal widths even if `<w:col>` children are
+/// present — Word writes `equalWidth="0"` whenever it means the individual
+/// definitions to win.
+///
+/// **Tier 0:** §17.6.4 `w:sep` — the vertical rule drawn between columns — is
+/// parsed onto `model::Columns::separator` but never drawn. Position and width
+/// of the columns themselves are unaffected; only the divider line is missing.
+fn compute_columns(content_width: Pt, columns: &Option<Columns>) -> Vec<ColumnGeometry> {
+ let single = || {
+ vec![ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: content_width,
+ }]
+ };
+
+ let cols = match columns {
+ Some(c) if c.count.unwrap_or(1) > 1 => c,
+ _ => return single(),
+ };
+
+ let default_space = cols.space.map(Pt::from).unwrap_or(DEFAULT_COLUMN_SPACE);
+ let num = clamp_column_count(cols.count.unwrap_or(1), content_width, default_space);
+ if num <= 1 {
+ return single();
+ }
+
+ // Individual definitions, only on an explicit `equalWidth="0"`.
+ if cols.equal_width == Some(false) && !cols.columns.is_empty() {
+ let mut result = Vec::with_capacity(num);
+ let mut x = Pt::ZERO;
+ for i in 0..num {
+ let def = cols.columns.get(i);
+ let w = def
+ .and_then(|d| d.width)
+ .map(Pt::from)
+ .unwrap_or(content_width / num as f32);
+ result.push(ColumnGeometry {
+ x_offset: x,
+ width: w,
+ });
+ if i + 1 < num {
+ let gap = def
+ .and_then(|d| d.space)
+ .map(Pt::from)
+ .unwrap_or(default_space);
+ x += w + gap;
+ }
+ }
+ return result;
+ }
+
+ // Equal-width columns.
+ let total_gap = default_space * (num as f32 - 1.0);
+ // No clamp here on purpose. `clamp_column_count` is the single guarantee
+ // that this is positive, and a second `.max(Pt::ZERO)` was demonstrably
+ // inert — removing it changed no test, because the bound already excludes
+ // every count that could make it negative. Two mechanisms for one invariant
+ // means the redundant one rots unnoticed; if the bound below ever changes,
+ // this is the line that breaks, and `column_count_never_yields_a_negative_width`
+ // is the test that catches it.
+ let col_width = (content_width - total_gap) / num as f32;
+ let mut result = Vec::with_capacity(num);
+ for i in 0..num {
+ let x = (col_width + default_space) * i as f32;
+ result.push(ColumnGeometry {
+ x_offset: x,
+ width: col_width,
+ });
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::dimension::{Dimension, Twips};
+ use crate::model::{PageMargins, PageSize};
+
+ #[test]
+ fn default_is_us_letter() {
+ let cfg = PageConfig::default();
+ assert_eq!(cfg.page_size.width.raw(), 612.0);
+ assert_eq!(cfg.page_size.height.raw(), 792.0);
+ assert_eq!(cfg.margins.top.raw(), 72.0);
+ }
+
+ #[test]
+ fn content_dimensions() {
+ let cfg = PageConfig::default();
+ assert_eq!(cfg.content_width().raw(), 468.0); // 612 - 72 - 72
+ assert_eq!(cfg.content_height().raw(), 648.0); // 792 - 72 - 72
+ }
+
+ #[test]
+ fn from_section_with_page_size() {
+ let sect = SectionProperties {
+ page_size: Some(PageSize {
+ width: Some(Dimension::<Twips>::new(12240)), // 8.5in = 612pt
+ height: Some(Dimension::<Twips>::new(15840)), // 11in = 792pt
+ orientation: None,
+ }),
+ ..Default::default()
+ };
+ let cfg = PageConfig::from_section(&sect);
+ assert_eq!(cfg.page_size.width.raw(), 612.0);
+ assert_eq!(cfg.page_size.height.raw(), 792.0);
+ }
+
+ #[test]
+ fn from_section_with_margins() {
+ let sect = SectionProperties {
+ page_margins: Some(PageMargins {
+ top: Some(Dimension::<Twips>::new(1440)), // 1in = 72pt
+ right: Some(Dimension::<Twips>::new(1440)),
+ bottom: Some(Dimension::<Twips>::new(1440)),
+ left: Some(Dimension::<Twips>::new(1440)),
+ header: Some(Dimension::<Twips>::new(720)), // 0.5in = 36pt
+ footer: Some(Dimension::<Twips>::new(720)),
+ gutter: None,
+ }),
+ ..Default::default()
+ };
+ let cfg = PageConfig::from_section(&sect);
+ assert_eq!(cfg.margins.top.raw(), 72.0);
+ assert_eq!(cfg.header_margin.raw(), 36.0);
+ }
+
+ #[test]
+ fn from_section_partial_uses_defaults() {
+ let sect = SectionProperties {
+ page_margins: Some(PageMargins {
+ top: Some(Dimension::<Twips>::new(2880)), // 2in = 144pt
+ right: None,
+ bottom: None,
+ left: None,
+ header: None,
+ footer: None,
+ gutter: None,
+ }),
+ ..Default::default()
+ };
+ let cfg = PageConfig::from_section(&sect);
+ assert_eq!(cfg.margins.top.raw(), 144.0, "custom top margin");
+ assert_eq!(cfg.margins.right.raw(), 72.0, "default right margin");
+ }
+
+ // ── §17.6.4 compute_columns ──────────────────────────────────────────
+
+ use crate::model::{ColumnDefinition, Columns};
+
+ fn cols_of(c: Columns) -> Vec<ColumnGeometry> {
+ compute_columns(Pt::new(468.0), &Some(c))
+ }
+
+ fn base() -> Columns {
+ Columns {
+ count: None,
+ space: None,
+ equal_width: None,
+ separator: None,
+ columns: vec![],
+ }
+ }
+
+ #[test]
+ fn no_columns_is_one_full_width_column() {
+ let g = compute_columns(Pt::new(468.0), &None);
+ assert_eq!(g.len(), 1);
+ assert_eq!(g[0].x_offset, Pt::ZERO);
+ assert_eq!(g[0].width, Pt::new(468.0));
+ // `w:num="1"` is the same thing stated explicitly.
+ let one = cols_of(Columns {
+ count: Some(1),
+ ..base()
+ });
+ assert_eq!(one.len(), 1);
+ assert_eq!(one[0].width, Pt::new(468.0));
+ }
+
+ /// Equal widths: gaps are `space × (n-1)`, the remainder splits evenly, and
+ /// each column starts one `width + space` after the previous.
+ #[test]
+ fn equal_width_columns_split_the_remainder_after_gaps() {
+ let g = cols_of(Columns {
+ count: Some(3),
+ ..base()
+ });
+ assert_eq!(g.len(), 3);
+ // 468 - 36*2 = 396; 396/3 = 132.
+ for c in &g {
+ assert_eq!(c.width, Pt::new(132.0));
+ }
+ assert_eq!(g[0].x_offset, Pt::ZERO);
+ assert_eq!(g[1].x_offset, Pt::new(168.0)); // 132 + 36
+ assert_eq!(g[2].x_offset, Pt::new(336.0));
+ // The last column ends exactly at the content edge.
+ assert_eq!(g[2].x_offset + g[2].width, Pt::new(468.0));
+ }
+
+ #[test]
+ fn explicit_space_overrides_the_default_gap() {
+ let g = cols_of(Columns {
+ count: Some(2),
+ space: Some(Dimension::<Twips>::new(1440)), // 72pt
+ ..base()
+ });
+ // 468 - 72 = 396; /2 = 198.
+ assert_eq!(g[0].width, Pt::new(198.0));
+ assert_eq!(g[1].x_offset, Pt::new(270.0)); // 198 + 72
+ }
+
+ /// §17.6.4: `equalWidth` defaults to **true**, so `<w:col>` children are
+ /// ignored unless the file explicitly opts out. Word writes
+ /// `equalWidth="0"` whenever it means them to win.
+ #[test]
+ fn col_children_are_ignored_unless_equal_width_is_explicitly_false() {
+ let children = vec![
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(1440)), // 72pt
+ space: None,
+ },
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(7200)), // 360pt
+ space: None,
+ },
+ ];
+ // Absent `equalWidth` → equal widths, children ignored.
+ let absent = cols_of(Columns {
+ count: Some(2),
+ columns: children.clone(),
+ ..base()
+ });
+ assert_eq!(absent[0].width, absent[1].width, "absent means equal");
+ assert_eq!(absent[0].width, Pt::new(216.0)); // (468-36)/2
+
+ // Explicit opt-out → the individual widths apply.
+ let opted_out = cols_of(Columns {
+ count: Some(2),
+ equal_width: Some(false),
+ columns: children,
+ ..base()
+ });
+ assert_eq!(opted_out[0].width, Pt::new(72.0));
+ assert_eq!(opted_out[1].width, Pt::new(360.0));
+ assert_eq!(opted_out[1].x_offset, Pt::new(108.0)); // 72 + 36 default gap
+ }
+
+ /// A per-column `w:space` overrides the default for that gap only, and the
+ /// final column contributes no trailing gap.
+ #[test]
+ fn per_column_space_applies_to_its_own_gap_only() {
+ let g = cols_of(Columns {
+ count: Some(3),
+ equal_width: Some(false),
+ columns: vec![
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(2000)), // 100pt
+ space: Some(Dimension::<Twips>::new(200)), // 10pt
+ },
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(2000)),
+ space: None, // falls back to the 36pt default
+ },
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(2000)),
+ space: Some(Dimension::<Twips>::new(9999)), // trailing: unused
+ },
+ ],
+ ..base()
+ });
+ assert_eq!(g[0].x_offset, Pt::ZERO);
+ assert_eq!(g[1].x_offset, Pt::new(110.0)); // 100 + 10
+ assert_eq!(g[2].x_offset, Pt::new(246.0)); // 110 + 100 + 36
+ }
+
+ /// §17.6.4: `w:num` is authoritative for the count. Fewer `<w:col>`
+ /// children than `w:num` leaves the remainder at the default width instead
+ /// of silently dropping columns.
+ #[test]
+ fn num_wins_when_col_children_are_missing_or_extra() {
+ let short = cols_of(Columns {
+ count: Some(3),
+ equal_width: Some(false),
+ columns: vec![ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(1440)), // 72pt
+ space: None,
+ }],
+ ..base()
+ });
+ assert_eq!(short.len(), 3, "w:num=3 yields three columns");
+ assert_eq!(short[0].width, Pt::new(72.0), "the declared one");
+ assert_eq!(short[1].width, Pt::new(156.0), "defaulted: 468/3");
+ assert_eq!(short[2].width, Pt::new(156.0));
+
+ let extra = cols_of(Columns {
+ count: Some(2),
+ equal_width: Some(false),
+ columns: vec![
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(1440)),
+ space: None,
+ },
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(1440)),
+ space: None,
+ },
+ ColumnDefinition {
+ width: Some(Dimension::<Twips>::new(1440)),
+ space: None,
+ },
+ ],
+ ..base()
+ });
+ assert_eq!(extra.len(), 2, "children beyond w:num are ignored");
+ }
+
+ /// `w:num` is a file-controlled `u32` that sizes an allocation. The ceiling
+ /// comes from the page, so the reservation can never exceed what the text
+ /// area could hold at `MIN_COLUMN_WIDTH`.
+ #[test]
+ fn absurd_column_counts_are_bounded_by_the_page() {
+ let g = cols_of(Columns {
+ count: Some(u32::MAX),
+ ..base()
+ });
+ assert!(
+ g.len() <= 468,
+ "468pt of text area at 1pt minimum caps the count, got {}",
+ g.len()
+ );
+ // A zero-width text area still yields a usable single column.
+ let degenerate = compute_columns(
+ Pt::ZERO,
+ &Some(Columns {
+ count: Some(u32::MAX),
+ ..base()
+ }),
+ );
+ assert_eq!(degenerate.len(), 1);
+ }
+
+ // ── E6#1: no route may produce a negative width ──────────────────────
+ //
+ // Three distinct routes reached the same defect, and only the first was in
+ // the original finding. All three ended at `BoxConstraints::new`'s
+ // `debug_assert!(min_width <= max_width)` — a panic through the public
+ // `convert()` API in debug builds, a negative-width layout in release.
+
+ /// Route 1: more columns than the text area can hold at the given spacing.
+ /// The old bound (`content_width / MIN_COLUMN_WIDTH`) ignored the gaps, so
+ /// 15 columns on Letter still produced `-25.9pt` each.
+ #[test]
+ fn column_count_never_yields_a_negative_width() {
+ for n in [2u32, 13, 14, 15, 16, 50, 1000, u32::MAX] {
+ let g = cols_of(Columns {
+ count: Some(n),
+ ..base()
+ });
+ assert!(!g.is_empty(), "n={n}");
+ for (i, c) in g.iter().enumerate() {
+ assert!(
+ c.width >= Pt::ZERO,
+ "n={n} col{i} width {:?} is negative",
+ c.width
+ );
+ }
+ }
+ }
+
+ /// Route 2: margins wider than the page. This one never reaches the column
+ /// arithmetic at all — a single-column section returns `content_width`
+ /// verbatim — so clamping inside `compute_columns` alone would have missed
+ /// it. `PageConfig::content_width` is where it has to be caught.
+ #[test]
+ fn margins_wider_than_the_page_clamp_to_zero_not_negative() {
+ let sect = SectionProperties {
+ page_size: Some(PageSize {
+ width: Some(Dimension::<Twips>::new(2000)), // 100pt
+ height: Some(Dimension::<Twips>::new(2000)),
+ orientation: None,
+ }),
+ page_margins: Some(PageMargins {
+ left: Some(Dimension::<Twips>::new(1440)), // 72pt
+ right: Some(Dimension::<Twips>::new(1440)), // 72pt — 144 > 100
+ top: Some(Dimension::<Twips>::new(1440)),
+ bottom: Some(Dimension::<Twips>::new(1440)),
+ header: None,
+ footer: None,
+ gutter: None,
+ }),
+ ..Default::default()
+ };
+ let cfg = PageConfig::from_section(&sect);
+ assert_eq!(cfg.content_width(), Pt::ZERO, "clamped, not -44pt");
+ assert_eq!(cfg.content_height(), Pt::ZERO);
+ assert!(cfg.columns.iter().all(|c| c.width >= Pt::ZERO));
+ }
+
+ /// Route 3: a spacing larger than the whole text area, at a column count
+ /// that would otherwise be perfectly ordinary.
+ #[test]
+ fn spacing_wider_than_the_page_yields_one_column_not_negative_ones() {
+ let g = cols_of(Columns {
+ count: Some(2),
+ space: Some(Dimension::<Twips>::new(20000)), // 1000pt on a 468pt area
+ ..base()
+ });
+ assert_eq!(g.len(), 1, "two columns cannot fit a 1000pt gap");
+ assert!(g[0].width >= Pt::ZERO);
+ }
+
+ /// The bound solves for the gaps, so every admitted count leaves each column
+ /// at least `MIN_COLUMN_WIDTH` — not merely non-negative. On Letter with the
+ /// default 36pt spacing that is 13 columns, one below the old sign-flip.
+ #[test]
+ fn admitted_counts_leave_every_column_usably_wide() {
+ let g = cols_of(Columns {
+ count: Some(13),
+ ..base()
+ });
+ assert_eq!(g.len(), 13);
+ for c in &g {
+ assert!(c.width >= MIN_COLUMN_WIDTH, "got {:?}", c.width);
+ }
+ // 14 is where the gaps consume the area, so the count is reduced.
+ let over = cols_of(Columns {
+ count: Some(14),
+ ..base()
+ });
+ assert_eq!(over.len(), 13, "clamped to what fits");
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/paragraph/borders.rs b/crates/liteparse-docx/src/render/layout/paragraph/borders.rs
new file mode 100644
index 0000000..12f452e
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/paragraph/borders.rs
@@ -0,0 +1,202 @@
+//! Paragraph border and shading rendering.
+
+use super::super::BoxConstraints;
+use super::super::draw_command::DrawCommand;
+use super::line_emit::resolve_line_height;
+use super::types::ParagraphStyle;
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtOffset;
+
+/// §17.3.1.24: which page segment of a paragraph is being emitted, i.e. which
+/// horizontal border edges and vertical spacing it owns. Side borders and
+/// shading span every segment; the top edge (and space above) belongs to the
+/// first segment, the bottom edge (and `space_after`) to the last.
+#[derive(Clone, Copy)]
+pub(super) enum SegmentEdges {
+ /// A whole, un-split paragraph — both edges.
+ Whole,
+ /// First of several segments — top edge only.
+ First,
+ /// Interior segment — neither edge.
+ Middle,
+ /// Final segment — bottom edge only.
+ Last,
+}
+
+impl SegmentEdges {
+ /// The segment kind for a `[first, last)` range flagged first/last.
+ pub(super) fn for_segment(is_first: bool, is_last: bool) -> Self {
+ match (is_first, is_last) {
+ (true, true) => Self::Whole,
+ (true, false) => Self::First,
+ (false, false) => Self::Middle,
+ (false, true) => Self::Last,
+ }
+ }
+
+ fn draw_top(self) -> bool {
+ matches!(self, Self::Whole | Self::First)
+ }
+
+ fn draw_bottom(self) -> bool {
+ matches!(self, Self::Whole | Self::Last)
+ }
+}
+
+/// Emit border and shading for a whole (un-split) paragraph, then advance the
+/// cursor for bottom border space, `space_after`, and the empty-paragraph
+/// minimum height. A thin wrapper over [`emit_segment_borders_and_shading`]
+/// with both edges drawn.
+pub(super) fn emit_paragraph_borders_and_shading(
+ commands: &mut Vec<DrawCommand>,
+ style: &ParagraphStyle,
+ constraints: &BoxConstraints,
+ cursor_y: Pt,
+ default_line_height: Pt,
+ no_lines: bool,
+) -> Pt {
+ emit_segment_borders_and_shading(
+ commands,
+ style,
+ constraints,
+ cursor_y,
+ default_line_height,
+ no_lines,
+ SegmentEdges::Whole,
+ )
+}
+
+/// §17.3.1.24/§17.3.1.31: emit border and shading for one page segment of a
+/// paragraph, returning the cursor after the segment's trailing spacing.
+///
+/// `content_bottom` is the y after the segment's last line. `edges` selects
+/// which horizontal border edges this segment owns (see [`SegmentEdges`]): side
+/// borders and shading span every segment, so a paragraph split across pages
+/// keeps a continuous box down each page, while the top/bottom edges and their
+/// spacing land only on the first/last segment. `SegmentEdges::Whole`
+/// reproduces the un-split geometry exactly.
+pub(super) fn emit_segment_borders_and_shading(
+ commands: &mut Vec<DrawCommand>,
+ style: &ParagraphStyle,
+ constraints: &BoxConstraints,
+ content_bottom: Pt,
+ default_line_height: Pt,
+ no_lines: bool,
+ edges: SegmentEdges,
+) -> Pt {
+ let draw_top = edges.draw_top();
+ let draw_bottom = edges.draw_bottom();
+ // §17.3.1.24: the border `space` is the distance between the border line and
+ // the text content; top/bottom border space expands the box vertically.
+ let border_space_top = style
+ .borders
+ .as_ref()
+ .and_then(|b| b.top.as_ref())
+ .map(|b| b.space)
+ .unwrap_or(Pt::ZERO);
+ let border_space_bottom = style
+ .borders
+ .as_ref()
+ .and_then(|b| b.bottom.as_ref())
+ .map(|b| b.space)
+ .unwrap_or(Pt::ZERO);
+ let para_left = style.indent_left;
+ let para_right = constraints.max_width - style.indent_right;
+ // The box top sits above the first line by the top border space on the first
+ // segment; a continuation segment's box starts flush at the segment top.
+ let box_top = if draw_top {
+ style.space_before - border_space_top
+ } else {
+ Pt::ZERO
+ };
+ let box_bottom = if draw_bottom {
+ content_bottom + border_space_bottom
+ } else {
+ content_bottom
+ };
+
+ // §17.3.1.31: render paragraph shading (fills the border area).
+ if let Some(bg_color) = style.shading {
+ commands.insert(
+ 0,
+ DrawCommand::Rect {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ para_left,
+ box_top,
+ para_right - para_left,
+ box_bottom - box_top,
+ ),
+ color: bg_color,
+ },
+ );
+ }
+
+ // §17.3.1.24: render paragraph borders at the indent edges. Top/bottom only
+ // on the owning segment; sides on every segment.
+ if let Some(ref borders) = style.borders {
+ if draw_top {
+ if let Some(ref top) = borders.top {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(para_left, box_top),
+ PtOffset::new(para_right, box_top),
+ ),
+ color: top.color,
+ width: top.width,
+ });
+ }
+ }
+ if draw_bottom {
+ if let Some(ref bottom) = borders.bottom {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(para_left, box_bottom),
+ PtOffset::new(para_right, box_bottom),
+ ),
+ color: bottom.color,
+ width: bottom.width,
+ });
+ }
+ }
+ if let Some(ref left) = borders.left {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(para_left, box_top),
+ PtOffset::new(para_left, box_bottom),
+ ),
+ color: left.color,
+ width: left.width,
+ });
+ }
+ if let Some(ref right) = borders.right {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(para_right, box_top),
+ PtOffset::new(para_right, box_bottom),
+ ),
+ color: right.color,
+ width: right.width,
+ });
+ }
+ }
+
+ // §17.3.1.24: only the final segment carries the bottom border space and
+ // space_after (§17.3.1.33).
+ let mut cursor_y = content_bottom;
+ if draw_bottom {
+ cursor_y = content_bottom + border_space_bottom + style.space_after;
+ }
+
+ // If no lines, still consume default height + spacing (whole-paragraph path).
+ if no_lines {
+ let line_h = resolve_line_height(
+ default_line_height,
+ default_line_height,
+ &style.line_spacing,
+ style.auto_fit,
+ );
+ cursor_y = style.space_before + line_h + style.space_after;
+ }
+
+ cursor_y
+}
diff --git a/crates/liteparse-docx/src/render/layout/paragraph/line_emit.rs b/crates/liteparse-docx/src/render/layout/paragraph/line_emit.rs
new file mode 100644
index 0000000..cacc23e
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/paragraph/line_emit.rs
@@ -0,0 +1,1428 @@
+//! Line placement, command emission, and related helpers.
+
+use std::rc::Rc;
+
+use super::super::draw_command::{DrawCommand, OutlineMark};
+use super::super::fragment::{Fragment, LinkTarget};
+use super::types::{LineSpacingRule, MeasureTextFn, ParagraphStyle, TabStopDef};
+use super::{LEADER_CHAR_WIDTH_FALLBACK, LineLayoutParams, LinePlacement};
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtOffset;
+
+/// Fit all fragments into lines, computing per-line float adjustments when
+/// active floats are present.
+///
+/// When `style.page_floats` is non-empty each line is fitted individually so
+/// the available width can vary depending on the line's absolute y position.
+/// When there are no floats a single call to `fit_lines_with_first` is used.
+pub(super) fn compute_line_placements(
+ fragments: &[Fragment],
+ style: &ParagraphStyle,
+ params: &LineLayoutParams,
+) -> Vec<LinePlacement> {
+ let content_width = params.content_width;
+ let first_line_adjustment = params.first_line_adjustment;
+ let drop_cap_indent = params.drop_cap_indent;
+ let drop_cap_lines = params.drop_cap_lines;
+ let default_line_height = params.default_line_height;
+ let ptab_geometry = PTabGeometry {
+ max_width: params.max_width,
+ indent_left: style.indent_left,
+ indent_first_line: style.indent_first_line,
+ content_width,
+ float_left: Pt::ZERO,
+ float_right: Pt::ZERO,
+ };
+ if style.page_floats.is_empty() {
+ // No floats — use standard line fitting.
+ let first_line_width = (content_width - first_line_adjustment).max(Pt::ZERO);
+ let remaining_width = if drop_cap_indent > Pt::ZERO {
+ content_width - drop_cap_indent
+ } else {
+ content_width
+ };
+ return super::super::line::fit_lines_with_first(
+ fragments,
+ first_line_width,
+ remaining_width,
+ ptab_geometry,
+ )
+ .into_iter()
+ .map(|line| LinePlacement {
+ line,
+ float_left: Pt::ZERO,
+ float_right: Pt::ZERO,
+ })
+ .collect();
+ }
+
+ // Active floats — fit one line at a time so available width can change.
+ let mut placements = Vec::new();
+ let mut frag_idx = 0;
+ let mut line_y = style.space_before;
+
+ while frag_idx < fragments.len() {
+ let abs_y = style.page_y + line_y;
+ let (fl, fr) = super::super::float::float_adjustments_with_height(
+ &style.page_floats,
+ abs_y,
+ default_line_height,
+ style.page_x,
+ style.page_content_width,
+ );
+ let float_reduction = fl + fr;
+ let available = (content_width - float_reduction).max(Pt::ZERO);
+
+ let is_first = placements.is_empty();
+ let dc_adj = if placements.len() < drop_cap_lines {
+ drop_cap_indent
+ } else {
+ Pt::ZERO
+ };
+ let line_width = if is_first {
+ (available - first_line_adjustment).max(Pt::ZERO)
+ } else {
+ (available - dc_adj).max(Pt::ZERO)
+ };
+
+ // Fit one line at this width. Each call fits exactly one line, so the
+ // geometry is *this* line's: its own float narrowing, and the
+ // first-line indent only when it really is the first.
+ let remaining = &fragments[frag_idx..];
+ let line_geometry = PTabGeometry {
+ indent_first_line: if is_first {
+ ptab_geometry.indent_first_line
+ } else {
+ Pt::ZERO
+ },
+ float_left: fl,
+ float_right: fr,
+ ..ptab_geometry
+ };
+ let fitted = super::super::line::fit_lines_with_first(
+ remaining,
+ line_width,
+ line_width,
+ line_geometry,
+ );
+ let fitted_line = if let Some(first) = fitted.into_iter().next() {
+ super::super::line::FittedLine {
+ start: first.start + frag_idx,
+ end: first.end + frag_idx,
+ width: first.width,
+ height: first.height,
+ text_height: first.text_height,
+ ascent: first.ascent,
+ has_break: first.has_break,
+ }
+ } else {
+ break;
+ };
+
+ let natural = if fitted_line.height > Pt::ZERO {
+ fitted_line.height
+ } else {
+ default_line_height
+ };
+ let text_h = if fitted_line.text_height > Pt::ZERO {
+ fitted_line.text_height
+ } else {
+ default_line_height
+ };
+ let lh = resolve_line_height(natural, text_h, &style.line_spacing, style.auto_fit);
+
+ frag_idx = fitted_line.end;
+ placements.push(LinePlacement {
+ line: fitted_line,
+ float_left: fl,
+ float_right: fr,
+ });
+ line_y += lh;
+ }
+ placements
+}
+
+fn stretchable_gap_after(fragments: &[Fragment], frag_idx: usize, line_end: usize) -> bool {
+ let Fragment::Text { text, .. } = &fragments[frag_idx] else {
+ return false;
+ };
+ text.ends_with(' ')
+ && fragments[frag_idx + 1..line_end]
+ .iter()
+ .any(|fragment| !matches!(fragment, Fragment::Bookmark { .. }))
+}
+
+fn line_has_justification_tab(fragments: &[Fragment], line_start: usize, line_end: usize) -> bool {
+ fragments[line_start..line_end].iter().any(|fragment| {
+ matches!(
+ fragment,
+ Fragment::Tab {
+ fitting_width: None,
+ ..
+ } | Fragment::PTab { .. }
+ ) || matches!(fragment, Fragment::Text { text, .. } if text.contains('\t'))
+ })
+}
+
+fn visible_line_width(fragments: &[Fragment], line: &super::super::line::FittedLine) -> Pt {
+ let last_visible = (line.start..line.end)
+ .rev()
+ .find(|&idx| !matches!(fragments[idx], Fragment::Bookmark { .. }));
+ (line.start..line.end)
+ .map(|idx| {
+ if Some(idx) == last_visible {
+ fragments[idx].trimmed_width()
+ } else {
+ fragments[idx].width()
+ }
+ })
+ .sum()
+}
+
+fn justification_extra_after(
+ fragments: &[Fragment],
+ line: &super::super::line::FittedLine,
+ line_idx: usize,
+ line_count: usize,
+ alignment: crate::model::Alignment,
+ line_has_tabs: bool,
+ remaining: Pt,
+) -> Pt {
+ if alignment != crate::model::Alignment::Both
+ || line.has_break
+ || line_idx + 1 == line_count
+ || line_has_tabs
+ || remaining <= Pt::ZERO
+ {
+ return Pt::ZERO;
+ }
+ let gaps = (line.start..line.end)
+ .filter(|&idx| stretchable_gap_after(fragments, idx, line.end))
+ .count();
+ if gaps == 0 {
+ Pt::ZERO
+ } else {
+ remaining / gaps as f32
+ }
+}
+
+fn distribution_unit_count(fragment: &Fragment, terminal: bool) -> usize {
+ match fragment {
+ Fragment::Text { text, .. } => {
+ if terminal {
+ text.trim_end().chars().count()
+ } else {
+ text.chars().count()
+ }
+ }
+ Fragment::Image { .. } | Fragment::Emoji { .. } => 1,
+ _ => 0,
+ }
+}
+
+fn distribution_gap_count_after(fragments: &[Fragment], frag_idx: usize, line_end: usize) -> usize {
+ let has_following_unit = fragments[frag_idx + 1..line_end]
+ .iter()
+ .any(|fragment| distribution_unit_count(fragment, false) > 0);
+ let units = distribution_unit_count(&fragments[frag_idx], !has_following_unit);
+ if has_following_unit {
+ units
+ } else {
+ units.saturating_sub(1)
+ }
+}
+
+fn distribution_extra_per_gap(
+ fragments: &[Fragment],
+ line: &super::super::line::FittedLine,
+ alignment: crate::model::Alignment,
+ line_has_tabs: bool,
+ remaining: Pt,
+) -> Pt {
+ if alignment != crate::model::Alignment::Distribute || line_has_tabs || remaining <= Pt::ZERO {
+ return Pt::ZERO;
+ }
+ let gaps = (line.start..line.end)
+ .map(|idx| distribution_gap_count_after(fragments, idx, line.end))
+ .sum::<usize>();
+ if gaps == 0 {
+ Pt::ZERO
+ } else {
+ remaining / gaps as f32
+ }
+}
+
+/// Emit `DrawCommand`s for all lines in a paragraph, advancing `cursor_y`
+/// by the total line height consumed.
+///
+/// Handles per-fragment shading, run borders, text, hyperlinks, underlines,
+/// images, tab stops (with leaders), bookmarks, and drop-cap indent offsets.
+#[allow(clippy::too_many_arguments)] // low-level emit primitive; inputs are cohesive
+pub(super) fn emit_line_commands(
+ commands: &mut Vec<DrawCommand>,
+ cursor_y: &mut Pt,
+ line_placements: &[LinePlacement],
+ line_range: std::ops::Range<usize>,
+ fragments: &[Fragment],
+ style: &ParagraphStyle,
+ params: &LineLayoutParams,
+ measure_text: MeasureTextFn<'_>,
+ // §17.3.1.14: false for the continuation of a paragraph split across pages.
+ // The caller knows; it cannot be inferred from `line_range`, because a
+ // continuation is re-fitted against its own page and starts again at 0.
+ is_first_segment: bool,
+) {
+ let content_width = params.content_width;
+ let first_line_adjustment = params.first_line_adjustment;
+ let drop_cap_indent = params.drop_cap_indent;
+ let drop_cap_lines = params.drop_cap_lines;
+ let default_line_height = params.default_line_height;
+ // §17.18.85: `bar` entries are paragraph decorations, not stops, so they
+ // are gathered here rather than reached from the `Fragment::Tab` arm — a
+ // bar draws on every line of the paragraph, including lines (and whole
+ // paragraphs) holding no tab character at all. Resolved once, outside the
+ // loop: the colour is a property of the paragraph and must not vary from
+ // line to line.
+ let has_bar_stop = style
+ .tabs
+ .iter()
+ .any(|ts| TabStopRole::of(ts.alignment) == TabStopRole::DrawsRule);
+ let bar_color = paragraph_bar_color(fragments);
+ // `line_idx` stays absolute within the paragraph (not the emitted range) so
+ // first-line indent (§17.3.1.12), drop caps (§17.3.1.11), and last-line
+ // justification (§17.3.1.13) resolve correctly when a paragraph is split
+ // across pages and only a sub-range of its lines is emitted here.
+ // §17.3.1.19: bracket this paragraph's commands so the PDF outline can point
+ // at it. Emitted here, around the whole emitted run, rather than per line:
+ // Skia derives an entry's destination from the union of the marks under its
+ // node, so one pair spanning the heading gives the top-left of its first
+ // line — exactly the point a reader expects to land on.
+ //
+ // Only the first segment emits it. `emit_line_commands` runs once per
+ // page-slice of a paragraph (§17.3.1.14), so a heading that splits across
+ // pages would otherwise open a second entry for its continuation — the
+ // entry belongs to the page the heading starts on. This rides the same
+ // `is_first_segment` flag that already decides `space_before` and the drop
+ // cap, for the same reason.
+ let outline = style.outline.as_ref().filter(|_| is_first_segment);
+ if let Some(heading) = outline {
+ commands.push(DrawCommand::Outline(OutlineMark::Begin(heading.clone())));
+ }
+
+ for line_idx in line_range {
+ let lp = &line_placements[line_idx];
+ let line = &lp.line;
+
+ // Drop cap lines get extra indent; after that, refit remaining lines at full width.
+ let dc_offset = if line_idx < drop_cap_lines {
+ drop_cap_indent
+ } else {
+ Pt::ZERO
+ };
+
+ // §17.4.58: per-line float left indent.
+ let float_offset = lp.float_left;
+
+ let indent = if line_idx == 0 {
+ style.indent_left + style.indent_first_line + dc_offset + float_offset
+ } else {
+ style.indent_left + dc_offset + float_offset
+ };
+
+ let natural_height = if line.height > Pt::ZERO {
+ line.height
+ } else {
+ default_line_height
+ };
+ let text_height = if line.text_height > Pt::ZERO {
+ line.text_height
+ } else {
+ default_line_height
+ };
+ let line_height = resolve_line_height(
+ natural_height,
+ text_height,
+ &style.line_spacing,
+ style.auto_fit,
+ );
+
+ // Alignment offset — computed relative to the line's available width.
+ let float_reduction = lp.float_left + lp.float_right;
+ let line_available = if line_idx == 0 {
+ (content_width - float_reduction - first_line_adjustment).max(Pt::ZERO)
+ } else {
+ (content_width - float_reduction - dc_offset).max(Pt::ZERO)
+ };
+ let remaining = (line_available - visible_line_width(fragments, line)).max(Pt::ZERO);
+ // §17.3.1.37: when a line contains tab characters, tab stops control
+ // horizontal positioning — paragraph alignment does not apply. Absolute
+ // position tabs (§17.3.1.30) place content explicitly for the same
+ // reason, so they suppress paragraph alignment too.
+ let line_has_tab_placement = fragments[line.start..line.end].iter().any(is_tab_like);
+ let align_offset = if line_has_tab_placement {
+ Pt::ZERO
+ } else {
+ match style.alignment {
+ crate::model::Alignment::Center => remaining * 0.5,
+ crate::model::Alignment::End => remaining,
+ crate::model::Alignment::Both
+ if !line.has_break && line_idx < line_placements.len() - 1 =>
+ {
+ Pt::ZERO
+ }
+ _ => Pt::ZERO,
+ }
+ };
+ let extra_per_gap = justification_extra_after(
+ fragments,
+ line,
+ line_idx,
+ line_placements.len(),
+ style.alignment,
+ line_has_justification_tab(fragments, line.start, line.end),
+ remaining,
+ );
+ let distribution_extra = distribution_extra_per_gap(
+ fragments,
+ line,
+ style.alignment,
+ line_has_justification_tab(fragments, line.start, line.end),
+ remaining,
+ );
+
+ let x_start = indent + align_offset;
+
+ // Before the content, so text wins wherever a rule and a glyph overlap.
+ if has_bar_stop {
+ emit_bar_rules(commands, &style.tabs, bar_color, *cursor_y, line_height);
+ }
+
+ // Emit text commands for this line
+ let mut x = x_start;
+ for (frag_idx, frag) in (line.start..line.end).zip(&fragments[line.start..line.end]) {
+ match frag {
+ Fragment::Text {
+ text,
+ font,
+ color,
+ shading,
+ border,
+ width,
+ metrics,
+ hyperlink_url,
+ baseline_offset,
+ text_offset,
+ ..
+ } => {
+ let extra_after = if stretchable_gap_after(fragments, frag_idx, line.end) {
+ extra_per_gap
+ } else {
+ Pt::ZERO
+ };
+ let distributed_width = distribution_extra
+ * distribution_gap_count_after(fragments, frag_idx, line.end) as f32;
+ let rendered_width = *width + extra_after + distributed_width;
+
+ // §17.3.2.32: render run-level shading behind text.
+ // Uses text bounds (ascent+descent), not full line height.
+ if let Some(bg_color) = shading {
+ let text_top = *cursor_y + line.ascent - metrics.ascent;
+ commands.push(DrawCommand::Rect {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ x,
+ text_top,
+ rendered_width,
+ metrics.height(),
+ ),
+ color: *bg_color,
+ });
+ }
+
+ // §17.3.2.4: render run-level border (box around text).
+ // Uses text bounds, not full line height.
+ if let Some(bdr) = border {
+ let text_top = *cursor_y + line.ascent - metrics.ascent;
+ let bx = x - bdr.space;
+ let by = text_top;
+ let bw = rendered_width + bdr.space * 2.0;
+ let bh = metrics.height();
+ let half = bdr.width * 0.5;
+ // Top
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(bx, by + half),
+ PtOffset::new(bx + bw, by + half),
+ ),
+ color: bdr.color,
+ width: bdr.width,
+ });
+ // Bottom
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(bx, by + bh - half),
+ PtOffset::new(bx + bw, by + bh - half),
+ ),
+ color: bdr.color,
+ width: bdr.width,
+ });
+ // Left
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(bx + half, by),
+ PtOffset::new(bx + half, by + bh),
+ ),
+ color: bdr.color,
+ width: bdr.width,
+ });
+ // Right
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(bx + bw - half, by),
+ PtOffset::new(bx + bw - half, by + bh),
+ ),
+ color: bdr.color,
+ width: bdr.width,
+ });
+ }
+
+ let y = *cursor_y + line.ascent + *baseline_offset;
+ commands.push(DrawCommand::Text {
+ position: PtOffset::new(x + *text_offset, y),
+ text: text.clone(),
+ font_family: font.family.clone(),
+ char_spacing: font.char_spacing + distribution_extra,
+ font_size: font.size,
+ bold: font.bold,
+ italic: font.italic,
+ color: *color,
+ text_scale: font.text_scale,
+ });
+
+ if let Some(link) = hyperlink_url {
+ let rect = crate::render::geometry::PtRect::from_xywh(
+ x,
+ *cursor_y,
+ rendered_width,
+ line_height,
+ );
+ // The external/internal kind is carried on the fragment
+ // (§17.16.22), so route by the ADT — no URL-scheme guess.
+ match link {
+ LinkTarget::External(url) => {
+ commands.push(DrawCommand::LinkAnnotation {
+ rect,
+ url: url.clone(),
+ })
+ }
+ LinkTarget::Internal(dest) => {
+ commands.push(DrawCommand::InternalLink {
+ rect,
+ destination: dest.clone(),
+ })
+ }
+ }
+ }
+
+ if font.underline {
+ // §17.3.2.40: underline position and thickness from font metrics.
+ // Skia provides underlinePosition (negative = below baseline)
+ // and underlineThickness.
+ let underline_y = y - font.underline_position;
+ let stroke_width = font.underline_thickness;
+ commands.push(DrawCommand::Underline {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(x, underline_y),
+ PtOffset::new(x + rendered_width, underline_y),
+ ),
+ color: *color,
+ width: stroke_width,
+ });
+ }
+
+ x += rendered_width;
+ }
+ Fragment::Image {
+ size,
+ image_data,
+ src_rect,
+ ..
+ } => {
+ if let Some(data) = image_data {
+ commands.push(DrawCommand::Image {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ x,
+ *cursor_y,
+ size.width,
+ size.height,
+ ),
+ image_data: data.clone(),
+ src_rect: *src_rect,
+ });
+ }
+ x += size.width
+ + distribution_extra
+ * distribution_gap_count_after(fragments, frag_idx, line.end) as f32;
+ }
+ Fragment::Emoji {
+ text,
+ typeface,
+ size,
+ presentation,
+ structure,
+ advance,
+ metrics,
+ line_metrics: _,
+ baseline_offset,
+ } => {
+ // Place the cluster's box so its top sits at the line
+ // baseline minus the typeface ascent, matching where text
+ // glyphs at the same baseline would sit.
+ let baseline_y = *cursor_y + line.ascent + *baseline_offset;
+ let top_y = baseline_y - metrics.ascent;
+ commands.push(DrawCommand::EmojiCluster {
+ rect: crate::render::geometry::PtRect::from_xywh(
+ x,
+ top_y,
+ *advance,
+ metrics.height(),
+ ),
+ text: text.clone(),
+ typeface: typeface.clone(),
+ size: *size,
+ presentation: *presentation,
+ structure: *structure,
+ });
+ x += *advance
+ + distribution_extra
+ * distribution_gap_count_after(fragments, frag_idx, line.end) as f32;
+ }
+ Fragment::Tab {
+ font: tab_font,
+ color: tab_color,
+ ..
+ } => {
+ // §17.3.1.37: resolve to the next tab stop.
+ // Tab stop positions are absolute from the paragraph's
+ // left edge, not relative to the text indent.
+ let (tab_pos, tab_stop) =
+ find_next_tab_stop(x, &style.tabs, line_available, style.default_tab_stop);
+
+ let new_x = if let Some(ts) = tab_stop {
+ // §17.3.1.37: this tab's *zone* is the content from
+ // here to the next tab (regular or position) or the
+ // line end, whichever comes first. §17.18.85 decides
+ // which point of that zone lands on the stop.
+ let end = zone_end(fragments, frag_idx, line.end);
+ let zone = &fragments[frag_idx + 1..end];
+ let offset = resolve_zone_anchor(
+ ts.alignment,
+ zone,
+ measure_text,
+ style.locale.decimal_separator(),
+ )
+ .offset(|| zone_width(fragments, frag_idx + 1, end));
+ // Never move the pen backwards: a zone wider than the
+ // space before its stop overflows to the right rather
+ // than overprinting what precedes it.
+ (tab_pos - offset).max(x)
+ } else {
+ tab_pos
+ };
+
+ // Emit leader characters between tab start and tab position.
+ if let Some(ts) = tab_stop {
+ emit_tab_leader(
+ commands,
+ LeaderStyle {
+ leader: ts.leader,
+ font: tab_font,
+ color: *tab_color,
+ },
+ x,
+ new_x,
+ *cursor_y + line.ascent,
+ measure_text,
+ );
+ }
+
+ x = new_x;
+ }
+ Fragment::PTab {
+ align,
+ relative_to,
+ leader,
+ font: tab_font,
+ color: tab_color,
+ ..
+ } => {
+ // §17.3.1.30: an absolute-position tab has no explicit
+ // stop; its anchor is derived from `relative_to` and the
+ // width of the zone it positions (this tab to the next tab
+ // or the line end).
+ let end = zone_end(fragments, frag_idx, line.end);
+ let geometry = PTabGeometry {
+ max_width: params.max_width,
+ indent_left: style.indent_left,
+ indent_first_line: style.indent_first_line,
+ content_width,
+ float_left: lp.float_left,
+ float_right: lp.float_right,
+ };
+ let new_x = match resolve_ptab(*align, *relative_to, geometry, x, || {
+ zone_width(fragments, frag_idx + 1, end)
+ }) {
+ PTabPlacement::Placed(at) => at,
+ PTabPlacement::AdvancesToNextLine { anchor_x } => {
+ if frag_idx == line.start {
+ // Fitting breaks the line before any tab whose
+ // anchor is behind the pen, so reaching here
+ // means the tab is already first on its line.
+ // Nothing has been drawn yet, so honouring the
+ // anchor cannot overprint — including when it
+ // sits left of `indent_left`, which is exactly
+ // what `relativeTo="margin"` asks for. The
+ // floor is the line's own left edge: a zone
+ // wider than its anchor has nowhere better to
+ // go, and advancing again would not move it.
+ anchor_x.max(Pt::ZERO)
+ } else {
+ // Defensive: fitting should have broken before
+ // this tab. If it did not, refusing to move
+ // backwards is the only safe answer.
+ anchor_x.max(x)
+ }
+ }
+ };
+
+ emit_tab_leader(
+ commands,
+ LeaderStyle {
+ leader: *leader,
+ font: tab_font,
+ color: *tab_color,
+ },
+ x,
+ new_x,
+ *cursor_y + line.ascent,
+ measure_text,
+ );
+
+ x = new_x;
+ }
+ Fragment::LineBreak { .. } | Fragment::ColumnBreak | Fragment::PageBreak { .. } => {
+ }
+ Fragment::Bookmark { name } => {
+ commands.push(DrawCommand::NamedDestination {
+ position: PtOffset::new(x, *cursor_y),
+ name: name.clone(),
+ });
+ }
+ }
+ }
+
+ *cursor_y += line_height;
+ }
+
+ if outline.is_some() {
+ commands.push(DrawCommand::Outline(OutlineMark::End));
+ }
+}
+
+/// True for fragments that place content by tab semantics — a regular tab
+/// stop (§17.3.1.37) or an absolute-position tab (§17.3.1.30). Both terminate
+/// a tab zone and suppress paragraph alignment for the line.
+fn is_tab_like(f: &Fragment) -> bool {
+ matches!(f, Fragment::Tab { .. } | Fragment::PTab { .. })
+}
+
+/// Index at which the zone opened by a tab at `tab_idx` ends: the next
+/// tab-like fragment or line break, or `limit`.
+///
+/// §17.3.1.37/§17.3.1.30: a tab positions the content up to the next tab, so
+/// every tab arm — regular, position, and the fitter's look-ahead — needs this
+/// same boundary. Emission passes the line end as `limit`; fitting, which has
+/// no lines yet, passes the fragment count.
+pub(crate) fn zone_end(fragments: &[Fragment], tab_idx: usize, limit: usize) -> usize {
+ fragments[tab_idx + 1..limit]
+ .iter()
+ .position(|f| is_tab_like(f) || f.is_line_break())
+ .map_or(limit, |offset| tab_idx + 1 + offset)
+}
+
+/// Total width of `fragments[start..end]`.
+///
+/// Always call this behind a thunk: `left`-aligned tabs anchor at the span
+/// start and never need it, and this walk is on the per-line hot path.
+pub(crate) fn zone_width(fragments: &[Fragment], start: usize, end: usize) -> Pt {
+ fragments[start..end].iter().map(|f| f.width()).sum()
+}
+
+/// §17.3.1.37: find the next tab stop position greater than `current_x`.
+/// Returns (position, optional tab stop definition).
+/// If no custom tab stop matches, falls back to the document's default tab-stop
+/// interval (§17.15.1.25 `w:defaultTabStop`, spec default 36pt / 0.5 inch).
+pub(super) fn find_next_tab_stop(
+ current_x: Pt,
+ tabs: &[TabStopDef],
+ line_width: Pt,
+ default_interval: Pt,
+) -> (Pt, Option<&TabStopDef>) {
+ // Find the first custom tab stop past current position. §17.18.85: a `bar`
+ // entry is a rule, not a stop, so a tab passes over it — skipping it here
+ // is what lets the pen reach the next real stop, or fall through to the
+ // default interval below when a bar is the only entry.
+ for ts in tabs {
+ if ts.position > current_x && TabStopRole::of(ts.alignment) == TabStopRole::PositionsContent
+ {
+ return (ts.position, Some(ts));
+ }
+ }
+
+ // No custom tab stop — use the document default interval. Guard against a
+ // zero/negative interval (a degenerate w:defaultTabStop) to avoid a stall.
+ let interval = if default_interval.raw() > 0.0 {
+ default_interval.raw()
+ } else {
+ 36.0
+ };
+ let next = ((current_x.raw() / interval).floor() + 1.0) * interval;
+ (Pt::new(next.min(line_width.raw())), None)
+}
+
+/// §17.3.1.30: the paragraph geometry a position tab resolves its anchor
+/// against.
+///
+/// Line *fitting* and line *emission* must agree about where a ptab puts
+/// content — fitting decides whether the tab can be honoured on this line,
+/// emission decides the exact x. Both derive it from this one struct through
+/// [`resolve_ptab`], so the two cannot drift apart.
+#[derive(Clone, Copy, Debug)]
+pub struct PTabGeometry {
+ /// Full constraint width, before paragraph indents. `relativeTo="margin"`
+ /// measures against this.
+ pub max_width: Pt,
+ /// Paragraph left indent. Line fitting seeds its pen here, matching where
+ /// emission starts a line — otherwise the two classify the same tab
+ /// differently and emission, unable to break, falls back to clamping.
+ pub indent_left: Pt,
+ /// §17.3.1.12 first-line indent, added to the seed on the first line only.
+ /// Callers that fit a single continuation line pass `Pt::ZERO`.
+ pub indent_first_line: Pt,
+ /// Constraint width net of indents. `relativeTo="indent"` measures against
+ /// `indent_left + content_width`, less the float narrowing below.
+ pub content_width: Pt,
+ /// §20.4.2: width stolen from this line's left by an overlapping float.
+ /// The indented region is narrower on such a line, so the tab's span must
+ /// follow it or the zone is positioned on top of the float.
+ pub float_left: Pt,
+ /// §20.4.2: width stolen from this line's right by an overlapping float.
+ pub float_right: Pt,
+}
+
+/// §17.3.1.30: outcome of resolving a position tab against the current pen.
+///
+/// The `AdvancesToNextLine` case is why this is an ADT rather than a `Pt`: it
+/// is a *line-breaking* outcome, not a coordinate, and collapsing it to
+/// `max(desired, pen)` is exactly the clamp that drew content off the page.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum PTabPlacement {
+ /// The alignment point is at or ahead of the pen; content starts here.
+ Placed(Pt),
+ /// The alignment point lies behind the pen. §17.3.1.30 advances the tab to
+ /// that location on the *next* line; `anchor_x` is where content will land
+ /// once it gets there.
+ AdvancesToNextLine { anchor_x: Pt },
+}
+
+/// §17.3.1.30: resolve a position tab against `pen_x` and its zone width.
+///
+/// `zone_width` yields the total width of the content this tab positions —
+/// from the tab to the next tab or the line end. It is a thunk because a
+/// `left` tab anchors at the span start and never needs it.
+pub fn resolve_ptab(
+ align: crate::model::PTabAlignment,
+ relative_to: crate::model::PTabRelativeTo,
+ geometry: PTabGeometry,
+ pen_x: Pt,
+ zone_width: impl FnOnce() -> Pt,
+) -> PTabPlacement {
+ use crate::model::{PTabAlignment, PTabRelativeTo};
+
+ // The reference span. x=0 is the constraint's left edge (the page/cell
+ // text margin); `content_width` is already net of paragraph indents, so
+ // the right indent edge sits at `indent_left + content_width`.
+ let (span_start, span_end) = match relative_to {
+ // `margin` names the page text margins, which a float does not move —
+ // the span is the same on every line of the paragraph.
+ PTabRelativeTo::Margin => (Pt::ZERO, geometry.max_width),
+ // `indent` names the indented region, which *is* narrower on a line an
+ // overlapping float steals width from. Exact Word behaviour here is
+ // unconfirmed; the line-local reading is chosen because it is the only
+ // one that cannot position a zone on top of the float.
+ PTabRelativeTo::Indent => (
+ geometry.indent_left + geometry.float_left,
+ geometry.indent_left + geometry.content_width - geometry.float_right,
+ ),
+ };
+ // The alignment picks the anchor within that span, and then which point of
+ // the zone lands on it — mirroring §17.18.85's tab-stop zone anchoring.
+ let anchor = match align {
+ PTabAlignment::Left => span_start,
+ PTabAlignment::Center => (span_start + span_end) * 0.5,
+ PTabAlignment::Right => span_end,
+ };
+ let anchor_x = match align {
+ PTabAlignment::Left => anchor,
+ PTabAlignment::Center => anchor - zone_width() * 0.5,
+ PTabAlignment::Right => anchor - zone_width(),
+ };
+
+ if anchor_x >= pen_x {
+ PTabPlacement::Placed(anchor_x)
+ } else {
+ PTabPlacement::AdvancesToNextLine { anchor_x }
+ }
+}
+
+/// §17.18.85: which point of a tab's *zone* — the content from the tab to the
+/// next tab or the line end — lands on the stop.
+///
+/// `Decimal` is why this is an enum rather than a fraction of the zone width:
+/// its anchor is a property of the zone's **text**, not of its geometry.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum ZoneAnchor {
+ /// The zone starts at the stop (`left`; also `bar` and `clear`, neither of
+ /// which repositions the content that follows).
+ Start,
+ /// The zone ends at the stop (`right`).
+ End,
+ /// The zone is centred on the stop (`center`).
+ Middle,
+ /// This offset into the zone lands on the stop (`decimal`).
+ At(Pt),
+}
+
+impl ZoneAnchor {
+ /// Distance from the zone's start to its anchor point. `zone_width` is a
+ /// thunk so a `Start` anchor — the overwhelmingly common case — never pays
+ /// for the O(zone) width sum.
+ fn offset(self, zone_width: impl FnOnce() -> Pt) -> Pt {
+ match self {
+ ZoneAnchor::Start => Pt::ZERO,
+ ZoneAnchor::End => zone_width(),
+ ZoneAnchor::Middle => zone_width() * 0.5,
+ ZoneAnchor::At(offset) => offset,
+ }
+ }
+}
+
+/// §17.18.85: the two exclusive roles an entry in `w:tabs` can have.
+///
+/// A `bar` entry is **not** a stop a tab character can land on. It names a
+/// column of the paragraph where a vertical rule is drawn — on every line,
+/// whether or not the paragraph contains a tab at all — and tabbing passes
+/// straight over it to the next real stop. Word's own tab dialog says as much:
+/// a bar tab does not position text.
+///
+/// The two roles want two different things from the same slice, and answering
+/// both from one `TabAlignment` match is what let a `bar` swallow a tab
+/// character *and* draw nothing. [`ZoneAnchor`] answers a question only a
+/// positioning stop has: where within its zone the content anchors.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum TabStopRole {
+ /// Positions the content that follows a tab character.
+ PositionsContent,
+ /// §17.18.85 `bar`: draws a vertical rule; invisible to a tab character.
+ DrawsRule,
+}
+
+impl TabStopRole {
+ /// Total over `TabAlignment` by construction — a new variant must state
+ /// its role here rather than inheriting a catch-all's.
+ fn of(alignment: crate::model::TabAlignment) -> Self {
+ use crate::model::TabAlignment;
+ match alignment {
+ TabAlignment::Left
+ | TabAlignment::Center
+ | TabAlignment::Right
+ | TabAlignment::Decimal
+ // §17.3.1.38 `clear` deletes a stop during style merge, so one
+ // reaching layout at all is inert. Leaving it a positioning stop
+ // keeps the `left` behaviour it has always had; giving it a rule
+ // would invent a mark the document never asked for.
+ | TabAlignment::Clear => Self::PositionsContent,
+ TabAlignment::Bar => Self::DrawsRule,
+ }
+ }
+}
+
+/// §17.18.85 gives the rule no weight and `w:tab` has no attribute for one.
+/// Word draws a hairline; 0.75pt is the same default this renderer already
+/// applies to an unspecified DrawingML outline, so the two agree instead of
+/// each inventing a number.
+const BAR_RULE_WIDTH: Pt = Pt::new(0.75);
+
+/// The colour a paragraph's bar rules take.
+///
+/// §17.3.1.38's rule for tab leaders — a decoration has no formatting of its
+/// own, it takes the formatting in effect — is the nearest precedent, but a bar
+/// rule has no owning run to read it from: it is drawn on lines holding no tab.
+/// Word keys it off the paragraph mark's run properties, which do not reach
+/// layout. The paragraph's first run is the closest thing that does, and taking
+/// it from the *paragraph* rather than from each line is what keeps one rule
+/// one colour when the paragraph wraps or splits across pages.
+fn paragraph_bar_color(fragments: &[Fragment]) -> crate::render::resolve::color::RgbColor {
+ fragments
+ .iter()
+ .find_map(|f| match f {
+ Fragment::Text { color, .. } => Some(*color),
+ _ => None,
+ })
+ .unwrap_or(crate::render::resolve::color::RgbColor::BLACK)
+}
+
+/// §17.18.85: draw every `bar` stop's rule across one line's vertical band.
+///
+/// The x is the stop's own position and owes nothing to the line — not to its
+/// content, its alignment offset, or its float indent — because a bar names a
+/// fixed column of the paragraph. Successive lines' bands abut, so the
+/// per-line segments read as one continuous rule.
+fn emit_bar_rules(
+ commands: &mut Vec<DrawCommand>,
+ tabs: &[TabStopDef],
+ color: crate::render::resolve::color::RgbColor,
+ line_top: Pt,
+ line_height: Pt,
+) {
+ for ts in tabs
+ .iter()
+ .filter(|ts| TabStopRole::of(ts.alignment) == TabStopRole::DrawsRule)
+ {
+ commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ PtOffset::new(ts.position, line_top),
+ PtOffset::new(ts.position, line_top + line_height),
+ ),
+ color,
+ width: BAR_RULE_WIDTH,
+ });
+ }
+}
+
+/// §17.18.85: resolve a tab stop's alignment into the zone anchor it implies.
+///
+/// Total over `TabAlignment` by construction — a new variant must state its
+/// anchor here rather than inheriting a catch-all's `left`.
+fn resolve_zone_anchor(
+ alignment: crate::model::TabAlignment,
+ zone: &[Fragment],
+ measure_text: MeasureTextFn<'_>,
+ separator: char,
+) -> ZoneAnchor {
+ use crate::model::TabAlignment;
+ match alignment {
+ // `clear` removes the stop (§17.3.1.38) and so never shifts what
+ // follows — exactly `left`'s placement.
+ TabAlignment::Left | TabAlignment::Clear => ZoneAnchor::Start,
+ TabAlignment::Right => ZoneAnchor::End,
+ TabAlignment::Center => ZoneAnchor::Middle,
+ TabAlignment::Decimal => decimal_anchor(zone, measure_text, separator),
+ // Unreachable in practice: `find_next_tab_stop` never hands back a
+ // rule stop, so no zone is ever anchored against one. Kept so the
+ // match stays total, and answering `Start` is the harmless reading if
+ // a future caller does reach it.
+ TabAlignment::Bar => ZoneAnchor::Start,
+ }
+}
+
+/// Offset of the first `separator` in `zone` — the paragraph's decimal
+/// character, per §17.3.2.20 `w:lang`, not a constant.
+///
+/// Falls back to [`ZoneAnchor::End`] when the zone contains none: Word
+/// right-aligns a separator-less decimal zone, which is what keeps a column of
+/// figures flush when one entry is a whole number. Left-aligning it instead
+/// would make that one entry stick out by its full width.
+fn decimal_anchor(
+ zone: &[Fragment],
+ measure_text: MeasureTextFn<'_>,
+ separator: char,
+) -> ZoneAnchor {
+ let mut before = Pt::ZERO;
+ for fragment in zone {
+ if let Fragment::Text {
+ text, font, width, ..
+ } = fragment
+ {
+ if let Some(byte_idx) = text.find(separator) {
+ let prefix = &text[..byte_idx];
+ let prefix_width = match measure_text {
+ Some(measure) => measure(prefix, font).0,
+ // No measurer (fitting-only paths): apportion the
+ // fragment's known width by character share. Approximate
+ // for proportional faces, but the alternative is ignoring
+ // the separator entirely.
+ None => {
+ let total = text.chars().count();
+ if total == 0 {
+ Pt::ZERO
+ } else {
+ *width * (prefix.chars().count() as f32 / total as f32)
+ }
+ }
+ };
+ return ZoneAnchor::At(before + prefix_width);
+ }
+ }
+ before += fragment.width();
+ }
+ ZoneAnchor::End
+}
+
+/// §17.3.1.38: how a tab leader is drawn.
+///
+/// A leader has no formatting of its own — it takes the formatting in effect
+/// at the tab, i.e. the `<w:rPr>` of the run carrying the `<w:tab/>` or
+/// `<w:ptab/>`. Bundling the three fields keeps them travelling together: the
+/// glyph, the font it is measured *and* drawn in, and its colour are one
+/// decision, and splitting them is how the hardcoded-Times-New-Roman default
+/// survived as long as it did.
+pub(super) struct LeaderStyle<'a> {
+ pub leader: crate::model::TabLeader,
+ pub font: &'a super::super::fragment::FontProps,
+ pub color: crate::render::resolve::color::RgbColor,
+}
+
+/// Emit leader characters (dots, hyphens, etc.) between tab start and end.
+pub(super) fn emit_tab_leader(
+ commands: &mut Vec<DrawCommand>,
+ style: LeaderStyle<'_>,
+ x_start: Pt,
+ x_end: Pt,
+ baseline_y: Pt,
+ measure_text: MeasureTextFn<'_>,
+) {
+ use crate::model::TabLeader;
+
+ let LeaderStyle {
+ leader,
+ font,
+ color,
+ } = style;
+ let leader_char = match leader {
+ TabLeader::Dot => ".",
+ TabLeader::Hyphen => "-",
+ TabLeader::Underscore => "_",
+ TabLeader::MiddleDot => "\u{00B7}",
+ TabLeader::Heavy => "_",
+ TabLeader::None => return,
+ };
+
+ let gap = x_end - x_start;
+ if gap <= Pt::ZERO {
+ return;
+ }
+
+ // Measure the leader glyph in the run's own font, so the repeat count
+ // matches the glyphs actually drawn below. Character spacing and text
+ // scaling are run-level effects on *text*, not on a fill pattern, so the
+ // measurement font drops them while keeping family/size/style.
+ let leader_font = super::super::fragment::FontProps {
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ ..font.clone()
+ };
+
+ let char_width = if let Some(m) = measure_text {
+ m(leader_char, &leader_font).0
+ } else {
+ LEADER_CHAR_WIDTH_FALLBACK
+ };
+
+ if char_width <= Pt::ZERO {
+ return;
+ }
+
+ let count = ((gap / char_width) as usize).min(500);
+ if count == 0 {
+ return;
+ }
+
+ let leader_text: String = leader_char.repeat(count);
+ let leader_width = char_width * count as f32;
+
+ // Right-align the leader dots within the gap (looks cleaner).
+ let leader_x = x_end - leader_width;
+
+ commands.push(DrawCommand::Text {
+ position: PtOffset::new(leader_x.max(x_start), baseline_y),
+ text: Rc::from(leader_text.as_str()),
+ font_family: leader_font.family,
+ char_spacing: Pt::ZERO,
+ font_size: leader_font.size,
+ bold: leader_font.bold,
+ italic: leader_font.italic,
+ color,
+ text_scale: 1.0,
+ });
+}
+
+/// §17.3.1.33: resolve the effective line height from the natural height
+/// and the line spacing rule.
+///
+/// For Auto mode, the multiplier applies only to text metrics — inline
+/// images use their natural height without scaling. The final line height
+/// is `max(text_height * multiplier, total_height)`.
+/// §17.3.1.33 line height for one line, then §20.1.2.1.18 `@lnSpcReduction`.
+///
+/// `auto_fit` is a parameter rather than something callers apply afterwards
+/// because four separate places resolve a line height — fitting, emission,
+/// the border box and the empty-paragraph path — and they must agree to the
+/// point. Owning the reduction here is what makes forgetting it impossible;
+/// applying it *after* the match is what lets it cross the `Auto` floor below,
+/// which is the whole point of the attribute (see
+/// [`ShapeAutoFit::scale_line_height`](crate::render::layout::ShapeAutoFit::scale_line_height)).
+pub(super) fn resolve_line_height(
+ natural: Pt,
+ text_height: Pt,
+ rule: &LineSpacingRule,
+ auto_fit: crate::render::layout::ShapeAutoFit,
+) -> Pt {
+ let resolved = match rule {
+ LineSpacingRule::Auto(multiplier) => {
+ let scaled_text = text_height * *multiplier;
+ // Use the scaled text height or the full natural height (which
+ // includes images), whichever is larger.
+ scaled_text.max(natural)
+ }
+ LineSpacingRule::Exact(h) => *h,
+ LineSpacingRule::AtLeast(min) => natural.max(*min),
+ };
+ auto_fit.scale_line_height(resolved)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ Fragment, PTabGeometry, PTabPlacement, ZoneAnchor, find_next_tab_stop, resolve_ptab,
+ resolve_zone_anchor,
+ };
+ use crate::model;
+ use crate::render::dimension::Pt;
+ use crate::render::layout::paragraph::TabStopDef;
+
+ // ── find_next_tab_stop ────────────────────────────────────────────────────
+
+ #[test]
+ fn default_interval_36pt_advances_half_inch() {
+ // No custom stops: land on the next multiple of the default interval.
+ let (pos, ts) = find_next_tab_stop(Pt::ZERO, &[], Pt::new(1000.0), Pt::new(36.0));
+ assert_eq!(pos.raw(), 36.0);
+ assert!(ts.is_none());
+ let (pos, _) = find_next_tab_stop(Pt::new(40.0), &[], Pt::new(1000.0), Pt::new(36.0));
+ assert_eq!(pos.raw(), 72.0);
+ }
+
+ #[test]
+ fn custom_default_interval_is_honored() {
+ // A custom w:defaultTabStop (e.g. 1440tw = 72pt / 1 inch) changes the grid.
+ let (pos, _) = find_next_tab_stop(Pt::ZERO, &[], Pt::new(1000.0), Pt::new(72.0));
+ assert_eq!(pos.raw(), 72.0);
+ let (pos, _) = find_next_tab_stop(Pt::new(80.0), &[], Pt::new(1000.0), Pt::new(72.0));
+ assert_eq!(pos.raw(), 144.0);
+ }
+
+ #[test]
+ fn zero_interval_falls_back_to_36pt() {
+ // A degenerate w:defaultTabStop of 0 must not stall the tab grid.
+ let (pos, _) = find_next_tab_stop(Pt::ZERO, &[], Pt::new(1000.0), Pt::ZERO);
+ assert_eq!(pos.raw(), 36.0);
+ }
+
+ #[test]
+ fn custom_tab_stop_preferred_over_default_grid() {
+ // A 72pt custom stop beats the 36pt default grid when the cursor is before it.
+ let tabs = vec![TabStopDef {
+ position: Pt::new(72.0),
+ alignment: model::TabAlignment::Left,
+ leader: model::TabLeader::None,
+ }];
+ let (pos, ts) = find_next_tab_stop(Pt::new(10.0), &tabs, Pt::new(1000.0), Pt::new(36.0));
+ assert_eq!(pos.raw(), 72.0, "custom stop wins over 36pt grid");
+ assert!(ts.is_some(), "custom TabStopDef returned");
+ }
+
+ #[test]
+ fn cursor_past_all_custom_stops_falls_back_to_default_grid() {
+ // All custom stops are behind the cursor — fall back to the default interval.
+ let tabs = vec![TabStopDef {
+ position: Pt::new(72.0),
+ alignment: model::TabAlignment::Left,
+ leader: model::TabLeader::None,
+ }];
+ // cursor=80 → floor(80/36)+1 = 2+1 = 3 → 3×36 = 108
+ let (pos, ts) = find_next_tab_stop(Pt::new(80.0), &tabs, Pt::new(1000.0), Pt::new(36.0));
+ assert_eq!(pos.raw(), 108.0, "default grid past the custom stop");
+ assert!(ts.is_none(), "no custom stop returned");
+ }
+
+ // ── ZoneAnchor (§17.18.85) ────────────────────────────────────────────────
+
+ /// A text fragment of known width, for anchor arithmetic.
+ fn text_fragment(text: &str, width: f32) -> Fragment {
+ use crate::render::layout::fragment::{FontProps, TextMetrics};
+ use std::rc::Rc;
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ shading: None,
+ border: None,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ #[test]
+ fn every_alignment_resolves_without_a_catch_all() {
+ // The point of the enum: each §17.18.85 value states its own anchor.
+ // `bar` and `clear` do not reposition following content, so they
+ // anchor at the zone start exactly as `left` does.
+ use model::TabAlignment::*;
+ for (alignment, expected) in [
+ (Left, ZoneAnchor::Start),
+ (Bar, ZoneAnchor::Start),
+ (Clear, ZoneAnchor::Start),
+ (Right, ZoneAnchor::End),
+ (Center, ZoneAnchor::Middle),
+ ] {
+ assert_eq!(
+ resolve_zone_anchor(alignment, &[], None, '.'),
+ expected,
+ "{alignment:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn a_start_anchor_never_sums_the_zone_width() {
+ // The thunk exists so the common case skips an O(zone) walk; if it is
+ // ever called for `Start` this panics.
+ let offset = ZoneAnchor::Start.offset(|| panic!("zone width computed for a Start anchor"));
+ assert_eq!(offset, Pt::ZERO);
+ }
+
+ #[test]
+ fn zone_anchor_offsets_are_measured_from_the_zone_start() {
+ let width = || Pt::new(80.0);
+ assert_eq!(ZoneAnchor::End.offset(width).raw(), 80.0);
+ assert_eq!(ZoneAnchor::Middle.offset(width).raw(), 40.0);
+ assert_eq!(ZoneAnchor::At(Pt::new(12.5)).offset(width).raw(), 12.5);
+ }
+
+ #[test]
+ fn a_decimal_zone_with_no_separator_anchors_at_its_end() {
+ let zone = [text_fragment("1234", 40.0)];
+ assert_eq!(
+ resolve_zone_anchor(model::TabAlignment::Decimal, &zone, None, '.'),
+ ZoneAnchor::End,
+ "right-align rather than left-align, so a whole number stays flush"
+ );
+ }
+
+ #[test]
+ fn a_decimal_zone_without_a_measurer_apportions_by_character_share() {
+ // "12.5" is 4 chars, 40pt wide; the 2-char prefix is half of it.
+ let zone = [text_fragment("12.5", 40.0)];
+ assert_eq!(
+ resolve_zone_anchor(model::TabAlignment::Decimal, &zone, None, '.'),
+ ZoneAnchor::At(Pt::new(20.0))
+ );
+ }
+
+ #[test]
+ fn a_decimal_anchor_accumulates_fragments_before_the_separator() {
+ // The separator can arrive in a later fragment; everything before it
+ // still counts toward the offset.
+ let zone = [text_fragment("12", 20.0), text_fragment(".5", 20.0)];
+ assert_eq!(
+ resolve_zone_anchor(model::TabAlignment::Decimal, &zone, None, '.'),
+ ZoneAnchor::At(Pt::new(20.0)),
+ "20pt of leading fragment + 0pt before the separator in the second"
+ );
+ }
+
+ // ── resolve_ptab (§17.3.1.30) ─────────────────────────────────────────────
+
+ fn ptab_geometry() -> PTabGeometry {
+ PTabGeometry {
+ max_width: Pt::new(400.0),
+ indent_left: Pt::ZERO,
+ indent_first_line: Pt::ZERO,
+ content_width: Pt::new(400.0),
+ float_left: Pt::ZERO,
+ float_right: Pt::ZERO,
+ }
+ }
+
+ #[test]
+ fn a_left_ptab_never_sums_its_zone() {
+ // `left` anchors at the span start, which does not depend on the zone
+ // at all — so the O(zone) walk must not run. Same guarantee as
+ // `ZoneAnchor::Start`, and the reason the width arrives as a thunk.
+ let placement = resolve_ptab(
+ model::PTabAlignment::Left,
+ model::PTabRelativeTo::Margin,
+ ptab_geometry(),
+ Pt::ZERO,
+ || panic!("zone width computed for a left position tab"),
+ );
+ assert_eq!(placement, PTabPlacement::Placed(Pt::ZERO));
+ }
+
+ #[test]
+ fn right_and_centre_ptabs_measure_the_zone_once() {
+ // The counterpart: these do depend on the zone, and each must call the
+ // thunk exactly once — not per alignment branch.
+ for (align, expected) in [
+ (model::PTabAlignment::Right, 300.0),
+ (model::PTabAlignment::Center, 150.0),
+ ] {
+ let calls = std::cell::Cell::new(0);
+ let placement = resolve_ptab(
+ align,
+ model::PTabRelativeTo::Margin,
+ ptab_geometry(),
+ Pt::ZERO,
+ || {
+ calls.set(calls.get() + 1);
+ Pt::new(100.0)
+ },
+ );
+ assert_eq!(
+ placement,
+ PTabPlacement::Placed(Pt::new(expected)),
+ "{align:?}"
+ );
+ assert_eq!(calls.get(), 1, "{align:?} measures the zone once");
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/paragraph/mod.rs b/crates/liteparse-docx/src/render/layout/paragraph/mod.rs
new file mode 100644
index 0000000..6bae640
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/paragraph/mod.rs
@@ -0,0 +1,2421 @@
+//! Paragraph layout — line fitting, alignment, spacing, borders, shading.
+//!
+//! Implements the LayoutBox protocol: receives BoxConstraints, returns PtSize,
+//! emits DrawCommands at absolute offsets during paint.
+
+mod borders;
+mod line_emit;
+
+// §17.3.1.30: line fitting needs the same position-tab resolution emission
+// uses, so the two cannot disagree about where a tab puts content.
+pub use line_emit::{PTabGeometry, PTabPlacement, resolve_ptab};
+pub(crate) use line_emit::{zone_end, zone_width};
+mod types;
+
+pub use types::*;
+
+use std::borrow::Cow;
+
+use super::BoxConstraints;
+use super::draw_command::DrawCommand;
+use super::fragment::Fragment;
+use crate::render::dimension::Pt;
+use crate::render::geometry::{PtOffset, PtRect, PtSize};
+
+use crate::render::layout::fragment::split_oversized_fragments;
+
+use borders::{SegmentEdges, emit_paragraph_borders_and_shading, emit_segment_borders_and_shading};
+use line_emit::{compute_line_placements, emit_line_commands, resolve_line_height};
+
+// ── Tab leader rendering constants ────────────────────────────────────────────
+
+/// Fallback width for a single leader character when no measurer is available (pt).
+const LEADER_CHAR_WIDTH_FALLBACK: Pt = Pt::new(4.0);
+
+/// A fitted line together with the per-line float adjustments that were active when it was placed.
+struct LinePlacement {
+ line: super::line::FittedLine,
+ /// Width stolen from the left by an active float.
+ float_left: Pt,
+ /// Width stolen from the right by an active float.
+ float_right: Pt,
+}
+
+/// Shared layout parameters threaded through `compute_line_placements` and
+/// `emit_line_commands`.
+struct LineLayoutParams {
+ content_width: Pt,
+ /// The full constraint width (page/cell text area between margins), before
+ /// paragraph indents are subtracted. §17.3.1.30 position tabs measured
+ /// `relativeTo="margin"` reference this, not the indented `content_width`.
+ max_width: Pt,
+ first_line_adjustment: Pt,
+ drop_cap_indent: Pt,
+ drop_cap_lines: usize,
+ default_line_height: Pt,
+}
+
+/// Clip inline images wider than `max_width` to the content box, cropping the
+/// horizontal overflow rather than scaling.
+///
+/// Per ECMA-376 §20.4.2.7, a `wp:inline` object's `wp:extent` is its *final*
+/// height and width — an inline object is **not** auto-scaled to fit its
+/// container. When it is wider than the containing table cell (§17.4.53: an
+/// autofit table at 100% width cannot grow its column), Word draws the image at
+/// full size and clips the overflow to the cell boundary.
+///
+/// The retained slice is the **left** part of the object. An inline object that
+/// is already wider than the line is placed at the line's start: justification
+/// (§17.3.1.13 `w:jc`) distributes only *spare* width, and an over-wide object
+/// leaves none — Word does not centre or right-shift it — so it overflows to
+/// the right and the cell clips that side. (Our own line fitter agrees: it
+/// clamps the alignment offset to `max(0)`.) We reproduce that by keeping the
+/// image's height and scale, setting its displayed width to `max_width`, and
+/// cropping the source to the left visible fraction, composed with any existing
+/// `a:srcRect` crop — no symmetric/centre crop, which would shift the pixels.
+///
+/// Returns `None` when nothing is oversized, so the common case borrows the
+/// input slice and allocates nothing.
+fn clip_oversized_images(fragments: &[Fragment], max_width: Pt) -> Option<Vec<Fragment>> {
+ let oversized =
+ |f: &Fragment| matches!(f, Fragment::Image { size, .. } if size.width > max_width);
+ if max_width <= Pt::ZERO || !fragments.iter().any(oversized) {
+ return None;
+ }
+ Some(
+ fragments
+ .iter()
+ .map(|f| match f {
+ Fragment::Image {
+ size,
+ rel_id,
+ image_data,
+ src_rect,
+ } if size.width > max_width => {
+ // Fraction of the object's width that survives the clip.
+ let visible = max_width.raw() / size.width.raw();
+ // Start from the existing crop (fraction of the source), or
+ // the whole image, then keep its left `visible` sub-fraction
+ // — same origin, narrower width (crop the right overflow).
+ let base = src_rect.unwrap_or_else(|| {
+ PtRect::from_xywh(Pt::ZERO, Pt::ZERO, Pt::new(1.0), Pt::new(1.0))
+ });
+ let cropped = PtRect::from_xywh(
+ base.origin.x,
+ base.origin.y,
+ Pt::new(base.size.width.raw() * visible),
+ base.size.height,
+ );
+ Fragment::Image {
+ // Height and scale are unchanged (§20.4.2.7); only the
+ // displayed width shrinks, showing the left, un-clipped
+ // part.
+ size: PtSize::new(max_width, size.height),
+ rel_id: rel_id.clone(),
+ image_data: image_data.clone(),
+ src_rect: Some(cropped),
+ }
+ }
+ other => other.clone(),
+ })
+ .collect(),
+ )
+}
+
+/// A paragraph whose lines have been fitted and measured, ready to emit.
+///
+/// The layout of a paragraph splits into two halves: *place* (fit fragments into
+/// lines and measure them — [`place_paragraph`]) and *emit* (produce
+/// `DrawCommand`s). The common case emits the whole paragraph at once
+/// ([`PlacedParagraph::emit_full`], wrapped by [`layout_paragraph`]). When a
+/// paragraph must break across a page boundary (§17.3.1.14 `keepLines`,
+/// §17.3.1.44 `widowControl`), the stacker emits sub-ranges of its lines at
+/// different page origins via [`PlacedParagraph::emit_split_segment`].
+///
+/// `line_placements` index into `fragments`, which is the *effective* fragment
+/// list after inline-image clipping (§20.4.2.7) and oversized-fragment
+/// splitting — hence the `Cow`, which borrows on the common no-transform path.
+pub(crate) struct PlacedParagraph<'a> {
+ fragments: Cow<'a, [Fragment]>,
+ line_placements: Vec<LinePlacement>,
+ params: LineLayoutParams,
+ style: &'a ParagraphStyle,
+ constraints: &'a BoxConstraints,
+ default_line_height: Pt,
+ measure_text: MeasureTextFn<'a>,
+ /// §17.3.1.11: precomputed baseline for the drop cap, if any.
+ drop_cap_baseline_y: Option<Pt>,
+ /// §17.3.1.33: resolved height of each fitted line, in line order. Lets the
+ /// stacker choose split points without re-measuring.
+ line_heights: Vec<Pt>,
+}
+
+/// Fit and measure a paragraph's lines without emitting draw commands — the
+/// "place" half of paragraph layout (see [`PlacedParagraph`]).
+pub(crate) fn place_paragraph<'a>(
+ fragments: &'a [Fragment],
+ constraints: &'a BoxConstraints,
+ style: &'a ParagraphStyle,
+ default_line_height: Pt,
+ measure_text: MeasureTextFn<'a>,
+) -> PlacedParagraph<'a> {
+ // §17.3.1.11: drop cap text frame.
+ // Drop mode: body text indented by drop cap position + width + hSpace.
+ // Margin mode: drop cap is in the margin, body text is NOT indented.
+ let drop_cap_indent = style
+ .drop_cap
+ .as_ref()
+ .filter(|dc| !dc.margin_mode)
+ .map(|dc| dc.indent + dc.width + dc.h_space)
+ .unwrap_or(Pt::ZERO);
+ let drop_cap_lines = style
+ .drop_cap
+ .as_ref()
+ .map(|dc| dc.lines as usize)
+ .unwrap_or(0);
+
+ // §17.3.1.24: border space is the distance between the border line and the text.
+ // Only the space reduces the text area, not the border line width.
+ let border_space_left = style
+ .borders
+ .as_ref()
+ .and_then(|b| b.left.as_ref())
+ .map(|b| b.space)
+ .unwrap_or(Pt::ZERO);
+ let border_space_right = style
+ .borders
+ .as_ref()
+ .and_then(|b| b.right.as_ref())
+ .map(|b| b.space)
+ .unwrap_or(Pt::ZERO);
+ let content_width = constraints.max_width
+ - style.indent_left
+ - style.indent_right
+ - border_space_left
+ - border_space_right;
+ // §17.3.1.12: first-line indent adjusts the first line's available width.
+ // Positive = narrower (indent), negative = wider (hanging indent).
+ // Drop cap indent also reduces width for the first N lines.
+ let first_line_adjustment = style.indent_first_line + drop_cap_indent;
+
+ // Effective fragments: clip inline images wider than the content box
+ // (§20.4.2.7 — Word clips rather than scales), then split oversized text
+ // fragments into per-character fragments for narrow-cell character-level
+ // breaking. `Cow` so the common path (nothing over-wide) borrows the input
+ // without cloning; only an actual transform materializes an owned `Vec`.
+ let min_avail = (content_width - first_line_adjustment).max(Pt::ZERO);
+ let effective: Cow<'a, [Fragment]> = {
+ let clipped: Cow<'a, [Fragment]> = match clip_oversized_images(fragments, content_width) {
+ Some(v) => Cow::Owned(v),
+ None => Cow::Borrowed(fragments),
+ };
+ // `split_oversized_fragments` returns `None` when nothing needs
+ // splitting, so the borrow survives the common case untouched — no
+ // mirrored predicate, and no clone.
+ match split_oversized_fragments(&clipped, min_avail, measure_text) {
+ Some(split) => Cow::Owned(split),
+ None => clipped,
+ }
+ };
+
+ let params = LineLayoutParams {
+ content_width,
+ max_width: constraints.max_width,
+ first_line_adjustment,
+ drop_cap_indent,
+ drop_cap_lines,
+ default_line_height,
+ };
+ // Per-line float adjustment: fit one line at a time, computing the available
+ // width for each line based on its absolute y position on the page.
+ let line_placements = compute_line_placements(&effective, style, &params);
+
+ // §17.3.1.11: compute the drop cap baseline.
+ // When frame_height is set (lineRule="exact"):
+ // baseline = frame_top + frame_height - descent + position_offset
+ // Otherwise fall back to aligning with the Nth body line's baseline.
+ let drop_cap_baseline_y = if let Some(ref dc) = style.drop_cap {
+ if let Some(fh) = dc.frame_height {
+ Some(style.space_before + fh + dc.position_offset)
+ } else {
+ let n = dc.lines.max(1) as usize;
+ let mut y = style.space_before;
+ for (i, lp) in line_placements.iter().enumerate().take(n) {
+ let natural = if lp.line.height > Pt::ZERO {
+ lp.line.height
+ } else {
+ default_line_height
+ };
+ let text_h = if lp.line.text_height > Pt::ZERO {
+ lp.line.text_height
+ } else {
+ default_line_height
+ };
+ let lh = resolve_line_height(natural, text_h, &style.line_spacing, style.auto_fit);
+ if i == n - 1 {
+ y += lp.line.ascent;
+ break;
+ }
+ y += lh;
+ }
+ Some(y)
+ }
+ } else {
+ None
+ };
+
+ // §17.3.1.33: resolve each line's height once, matching `emit_line_commands`.
+ let line_heights = line_placements
+ .iter()
+ .map(|lp| {
+ let natural = if lp.line.height > Pt::ZERO {
+ lp.line.height
+ } else {
+ default_line_height
+ };
+ let text_h = if lp.line.text_height > Pt::ZERO {
+ lp.line.text_height
+ } else {
+ default_line_height
+ };
+ resolve_line_height(natural, text_h, &style.line_spacing, style.auto_fit)
+ })
+ .collect();
+
+ PlacedParagraph {
+ fragments: effective,
+ line_placements,
+ params,
+ style,
+ constraints,
+ default_line_height,
+ measure_text,
+ drop_cap_baseline_y,
+ line_heights,
+ }
+}
+
+impl PlacedParagraph<'_> {
+ /// Number of fitted lines.
+ pub(crate) fn line_count(&self) -> usize {
+ self.line_placements.len()
+ }
+
+ /// §17.3.1.33: resolved height of line `i`.
+ pub(crate) fn line_height(&self, i: usize) -> Pt {
+ self.line_heights[i]
+ }
+
+ /// Number of leading lines that must stay together on the first segment
+ /// when this paragraph splits — the larger of:
+ ///
+ /// - §17.3.1.11 the drop-cap span (a split inside it tears the glyph), and
+ /// - §17.3.1.44 the float-wrapped run: every line up to and including the
+ /// last one narrowed by an active float. Keeping these on the first
+ /// segment guarantees the continuation is full-width, so the already-fitted
+ /// tail lines are reused correctly on the next page without re-wrapping.
+ pub(crate) fn unbreakable_prefix_lines(&self) -> usize {
+ let float_prefix = self
+ .line_placements
+ .iter()
+ .rposition(|lp| lp.float_left > Pt::ZERO || lp.float_right > Pt::ZERO)
+ .map_or(0, |i| i + 1);
+ self.params.drop_cap_lines.max(float_prefix)
+ }
+
+ /// §4 continuation re-fit: the effective fragments from line `from` onward,
+ /// cloned so the stacker can re-place the remainder against the next page's
+ /// floats and width (instead of reusing this page's placement). `from` must
+ /// be a valid line index (`< line_count()`).
+ pub(crate) fn fragments_from_line(&self, from: usize) -> Vec<Fragment> {
+ let start = self.line_placements[from].line.start;
+ self.fragments[start..].to_vec()
+ }
+
+ /// §17.11.12: number of footnote reference marks in lines `[first, last)`.
+ /// The stacker reserves this many footnotes (in document order) on the page
+ /// that segment lands on, so a footnote sits with its reference.
+ pub(crate) fn footnote_refs_in(&self, first: usize, last: usize) -> usize {
+ self.line_placements[first..last]
+ .iter()
+ .map(|lp| {
+ self.fragments[lp.line.start..lp.line.end]
+ .iter()
+ .filter(|f| {
+ matches!(
+ f,
+ Fragment::Text {
+ is_footnote_ref: true,
+ ..
+ }
+ )
+ })
+ .count()
+ })
+ .sum()
+ }
+
+ /// Render the drop cap glyphs at their precomputed baseline (§17.3.1.11).
+ /// Only the first segment of a split paragraph carries the drop cap.
+ fn emit_drop_cap(&self, commands: &mut Vec<DrawCommand>) {
+ if let (Some(dc), Some(baseline_y)) = (&self.style.drop_cap, self.drop_cap_baseline_y) {
+ // §17.3.1.11: position the drop cap using its own paragraph's indent.
+ // Drop mode: at the drop cap paragraph's indent (inside text area).
+ // Margin mode: in the page margin, to the left of text.
+ let dc_x = if dc.margin_mode {
+ dc.indent - dc.width - dc.h_space
+ } else {
+ dc.indent
+ };
+ for frag in &dc.fragments {
+ if let Fragment::Text {
+ text, font, color, ..
+ } = frag
+ {
+ commands.push(DrawCommand::Text {
+ position: PtOffset::new(dc_x, baseline_y),
+ text: text.clone(),
+ font_family: font.family.clone(),
+ char_spacing: font.char_spacing,
+ font_size: font.size,
+ bold: font.bold,
+ italic: font.italic,
+ color: *color,
+ text_scale: font.text_scale,
+ });
+ }
+ }
+ }
+ }
+
+ /// Emit the whole paragraph — drop cap, every line, and border/shading with
+ /// `space_before`/`space_after`. The common, non-split path.
+ pub(crate) fn emit_full(&self) -> ParagraphLayout {
+ let mut commands = Vec::new();
+ let mut cursor_y = self.style.space_before;
+
+ self.emit_drop_cap(&mut commands);
+
+ emit_line_commands(
+ &mut commands,
+ &mut cursor_y,
+ &self.line_placements,
+ 0..self.line_placements.len(),
+ &self.fragments,
+ self.style,
+ &self.params,
+ self.measure_text,
+ true,
+ );
+
+ // §17.3.1.24: paragraph border and shading coordinate system.
+ // Borders sit at the paragraph indent edges. The border `space` is the
+ // distance between the border line and the text content. Top/bottom
+ // border space expands the bordered area vertically.
+ cursor_y = emit_paragraph_borders_and_shading(
+ &mut commands,
+ self.style,
+ self.constraints,
+ cursor_y,
+ self.default_line_height,
+ self.line_placements.is_empty(),
+ );
+
+ ParagraphLayout {
+ commands,
+ size: PtSize::new(self.constraints.max_width, cursor_y),
+ }
+ }
+
+ /// §17.3.1.24: bottom border space this paragraph adds after its last line —
+ /// charged, with `space_after`, only on the final segment.
+ pub(crate) fn bottom_border_space(&self) -> Pt {
+ self.style
+ .borders
+ .as_ref()
+ .and_then(|b| b.bottom.as_ref())
+ .map(|b| b.space)
+ .unwrap_or(Pt::ZERO)
+ }
+
+ /// Emit lines `[first, last)` of a splittable paragraph as one page segment.
+ ///
+ /// The caller keeps the unbreakable prefix (see
+ /// [`unbreakable_prefix_lines`](Self::unbreakable_prefix_lines)) on the first
+ /// segment, so the drop cap and any float-wrapped lines stay intact.
+ /// `space_before` (§17.3.1.33) and the top border belong to the first
+ /// segment; `space_after` and the bottom border to the last; shading and side
+ /// borders span every segment (§17.3.1.24/§17.3.1.31). Commands are
+ /// positioned relative to the segment's own origin `(0, 0)`; the stacker
+ /// shifts them to the page.
+ pub(crate) fn emit_split_segment(
+ &self,
+ first: usize,
+ last: usize,
+ is_first_segment: bool,
+ is_last_segment: bool,
+ ) -> ParagraphLayout {
+ debug_assert!(
+ first < last && last <= self.line_placements.len(),
+ "split range {first}..{last} out of bounds for {} lines",
+ self.line_placements.len()
+ );
+ let mut commands = Vec::new();
+ // §17.3.1.33: only the first segment carries the paragraph's space_before.
+ let mut cursor_y = if is_first_segment {
+ self.style.space_before
+ } else {
+ Pt::ZERO
+ };
+
+ // §17.3.1.11: the drop cap belongs to the first segment (the stacker's
+ // guard keeps the whole drop-cap prefix there, so the glyph is intact).
+ if is_first_segment {
+ self.emit_drop_cap(&mut commands);
+ }
+
+ emit_line_commands(
+ &mut commands,
+ &mut cursor_y,
+ &self.line_placements,
+ first..last,
+ &self.fragments,
+ self.style,
+ &self.params,
+ self.measure_text,
+ is_first_segment,
+ );
+
+ // §17.3.1.24/§17.3.1.31: per-segment border/shading box; the top edge and
+ // space_before are on the first segment, the bottom edge and space_after
+ // on the last, sides and shading on every segment.
+ cursor_y = emit_segment_borders_and_shading(
+ &mut commands,
+ self.style,
+ self.constraints,
+ cursor_y,
+ self.default_line_height,
+ false,
+ SegmentEdges::for_segment(is_first_segment, is_last_segment),
+ );
+
+ ParagraphLayout {
+ commands,
+ size: PtSize::new(self.constraints.max_width, cursor_y),
+ }
+ }
+}
+
+/// Lay out a paragraph: fit fragments into lines, apply alignment and spacing.
+///
+/// Returns draw commands positioned relative to (0, 0). The caller positions
+/// the paragraph by adding its offset during the paint phase.
+pub fn layout_paragraph(
+ fragments: &[Fragment],
+ constraints: &BoxConstraints,
+ style: &ParagraphStyle,
+ default_line_height: Pt,
+ measure_text: MeasureTextFn<'_>,
+) -> ParagraphLayout {
+ place_paragraph(
+ fragments,
+ constraints,
+ style,
+ default_line_height,
+ measure_text,
+ )
+ .emit_full()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::{Alignment, PTabAlignment, PTabRelativeTo};
+ use crate::render::layout::fragment::{FontProps, LinkTarget, TextMetrics};
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str, width: f32) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn hyperlink_frag(text: &str, width: f32, url: &str) -> Fragment {
+ let mut fragment = text_frag(text, width);
+ if let Fragment::Text { hyperlink_url, .. } = &mut fragment {
+ *hyperlink_url = Some(LinkTarget::External(std::rc::Rc::from(url)));
+ }
+ fragment
+ }
+
+ fn underlined_text_frag(text: &str, width: f32) -> Fragment {
+ let mut fragment = text_frag(text, width);
+ if let Fragment::Text { font, .. } = &mut fragment {
+ Rc::make_mut(font).underline = true;
+ Rc::make_mut(font).underline_thickness = Pt::new(0.5);
+ }
+ fragment
+ }
+
+ fn body_constraints(width: f32) -> BoxConstraints {
+ BoxConstraints::new(Pt::ZERO, Pt::new(width), Pt::ZERO, Pt::new(1000.0))
+ }
+
+ fn image_frag(w: f32, h: f32) -> Fragment {
+ Fragment::Image {
+ size: PtSize::new(Pt::new(w), Pt::new(h)),
+ rel_id: "rId1".to_string(),
+ image_data: None,
+ src_rect: None,
+ }
+ }
+
+ fn clipped_src(frag: &Fragment) -> (PtSize, PtRect) {
+ match frag {
+ Fragment::Image { size, src_rect, .. } => (*size, src_rect.expect("crop applied")),
+ other => panic!("expected image, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn clip_oversized_image_crops_left_keeps_height_and_scale() {
+ // 200×100 image in a 100pt content box → keep the LEFT 50% of the
+ // width, full height. Height is UNCHANGED (not scaled) — a crop, not a
+ // fit — and the crop is left-anchored (origin.x stays 0), so the right
+ // overflow is what gets clipped, matching Word.
+ let frags = vec![image_frag(200.0, 100.0)];
+ let out = clip_oversized_images(&frags, Pt::new(100.0)).expect("clip");
+ let (size, crop) = clipped_src(&out[0]);
+ assert_eq!(size.width.raw(), 100.0);
+ assert_eq!(size.height.raw(), 100.0, "height must NOT change");
+ assert!(
+ (crop.origin.x.raw() - 0.0).abs() < 1e-4,
+ "left-anchored, not centred"
+ );
+ assert!((crop.size.width.raw() - 0.5).abs() < 1e-4);
+ assert!((crop.size.height.raw() - 1.0).abs() < 1e-4);
+ }
+
+ #[test]
+ fn clip_oversized_image_composes_with_existing_src_rect() {
+ // Image already cropped to [0.1, 0.9] (width 0.8); clipping to 50% keeps
+ // the left 0.4 of the source, at the existing origin.
+ let mut frag = image_frag(200.0, 100.0);
+ if let Fragment::Image { src_rect, .. } = &mut frag {
+ *src_rect = Some(PtRect::from_xywh(
+ Pt::new(0.1),
+ Pt::ZERO,
+ Pt::new(0.8),
+ Pt::new(1.0),
+ ));
+ }
+ let out = clip_oversized_images(&[frag], Pt::new(100.0)).expect("clip");
+ let crop = clipped_src(&out[0]).1;
+ assert!((crop.origin.x.raw() - 0.1).abs() < 1e-4);
+ assert!((crop.size.width.raw() - 0.4).abs() < 1e-4);
+ }
+
+ #[test]
+ fn clip_oversized_images_leaves_a_fitting_image_untouched() {
+ // Narrower than the content box → not oversized → borrow, no allocation.
+ let frags = vec![image_frag(163.0, 290.0)];
+ assert!(clip_oversized_images(&frags, Pt::new(499.0)).is_none());
+ }
+
+ #[test]
+ fn clip_oversized_images_ignores_wide_non_image_fragments() {
+ // Oversized text is handled by split_oversized_fragments, not here.
+ let frags = vec![text_frag("very wide text", 999.0)];
+ assert!(clip_oversized_images(&frags, Pt::new(100.0)).is_none());
+ }
+
+ #[test]
+ fn clip_oversized_images_guards_nonpositive_width() {
+ let frags = vec![image_frag(516.0, 290.0)];
+ assert!(clip_oversized_images(&frags, Pt::ZERO).is_none());
+ }
+
+ #[test]
+ fn empty_paragraph_has_default_height() {
+ let result = layout_paragraph(
+ &[],
+ &body_constraints(400.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+ assert_eq!(result.size.height.raw(), 14.0, "default line height");
+ assert!(result.commands.is_empty());
+ }
+
+ #[test]
+ fn single_line_produces_text_command() {
+ let frags = vec![text_frag("hello", 30.0)];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(result.commands.len(), 1);
+ if let DrawCommand::Text { text, position, .. } = &result.commands[0] {
+ assert_eq!(&**text, "hello");
+ assert_eq!(position.x.raw(), 0.0); // left aligned, no indent
+ }
+ }
+
+ #[test]
+ fn center_alignment_shifts_text() {
+ let frags = vec![text_frag("hi", 20.0)];
+ let style = ParagraphStyle {
+ alignment: Alignment::Center,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(100.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ if let DrawCommand::Text { position, .. } = &result.commands[0] {
+ assert_eq!(position.x.raw(), 40.0); // (100 - 20) / 2
+ }
+ }
+
+ #[test]
+ fn end_alignment_right_aligns() {
+ let frags = vec![text_frag("hi", 20.0)];
+ let style = ParagraphStyle {
+ alignment: Alignment::End,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(100.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ if let DrawCommand::Text { position, .. } = &result.commands[0] {
+ assert_eq!(position.x.raw(), 80.0); // 100 - 20
+ }
+ }
+
+ #[test]
+ fn literal_tab_text_preserves_center_and_end_alignment() {
+ let fragments = vec![text_frag("alpha\tbeta", 20.0)];
+ for (alignment, expected_x) in [(Alignment::Center, 20.0), (Alignment::End, 40.0)] {
+ let style = ParagraphStyle {
+ alignment,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[0] - expected_x).abs() < 0.01);
+ }
+ }
+
+ #[test]
+ fn structured_tab_zones_include_literal_tab_text() {
+ for (alignment, expected_xs) in [
+ (crate::model::TabAlignment::Right, [45.0, 55.0, 60.0]),
+ (crate::model::TabAlignment::Center, [62.5, 72.5, 77.5]),
+ ] {
+ let style = ParagraphStyle {
+ tabs: vec![TabStopDef {
+ position: Pt::new(80.0),
+ alignment,
+ leader: crate::model::TabLeader::None,
+ }],
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &[
+ Fragment::Tab {
+ line_height: Pt::new(14.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ fitting_width: Some(Pt::new(5.0)),
+ },
+ text_frag("alpha", 10.0),
+ text_frag("\t", 5.0),
+ text_frag("beta", 20.0),
+ ],
+ &body_constraints(100.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ let xs = text_xs(&result);
+ for (actual, expected) in xs.iter().zip(expected_xs) {
+ assert!((actual - expected).abs() < 0.01, "xs: {xs:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn both_alignment_expands_inter_word_gaps_on_soft_wrapped_lines() {
+ let mut fragments = vec![
+ text_frag("alpha ", 25.0),
+ hyperlink_frag("beta ", 25.0, "https://example.invalid"),
+ text_frag("gamma", 30.0),
+ ];
+ if let Fragment::Text { font, .. } = &mut fragments[0] {
+ Rc::make_mut(font).underline = true;
+ Rc::make_mut(font).underline_thickness = Pt::new(0.5);
+ }
+ let style = ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ let xs = text_xs(&result);
+ assert!(
+ (xs[1] - 35.0).abs() < 0.01,
+ "beta must receive the 10pt gap: {xs:?}"
+ );
+ assert!(
+ (xs[2] - 0.0).abs() < 0.01,
+ "final line must remain unexpanded: {xs:?}"
+ );
+
+ let underline = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Underline { line, .. } => Some(*line),
+ _ => None,
+ })
+ .expect("underlined first gap");
+ assert!((underline.end.x.raw() - 35.0).abs() < 0.01);
+
+ let link_rect = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::LinkAnnotation { rect, url }
+ if &**url == "https://example.invalid" =>
+ {
+ Some(*rect)
+ }
+ _ => None,
+ })
+ .expect("beta hyperlink annotation");
+ assert!((link_rect.origin.x.raw() - 35.0).abs() < 0.01);
+ assert!((link_rect.size.width.raw() - 25.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn non_http_external_link_emits_uri_annotation() {
+ // Regression: an external URL whose scheme isn't in the old
+ // http/https/mailto/ftp allowlist (here `file://`) must still be a URI
+ // LinkAnnotation, not misrouted to an internal GoTo. Routing is by the
+ // fragment's LinkTarget kind now, not a URL-scheme guess.
+ let mut frag = text_frag("doc", 20.0);
+ if let Fragment::Text { hyperlink_url, .. } = &mut frag {
+ *hyperlink_url = Some(LinkTarget::External("file://server/report.docx".into()));
+ }
+ let result = layout_paragraph(
+ &[frag],
+ &body_constraints(200.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+ assert!(
+ result.commands.iter().any(|c| matches!(
+ c,
+ DrawCommand::LinkAnnotation { url, .. } if &**url == "file://server/report.docx"
+ )),
+ "file:// external link must be a URI annotation"
+ );
+ assert!(
+ !result
+ .commands
+ .iter()
+ .any(|c| matches!(c, DrawCommand::InternalLink { .. })),
+ "external link must not be misrouted to an internal GoTo"
+ );
+ }
+
+ #[test]
+ fn internal_link_emits_goto_destination() {
+ let mut frag = text_frag("entry", 40.0);
+ if let Fragment::Text { hyperlink_url, .. } = &mut frag {
+ *hyperlink_url = Some(LinkTarget::Internal("_Toc123".into()));
+ }
+ let result = layout_paragraph(
+ &[frag],
+ &body_constraints(200.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+ assert!(
+ result.commands.iter().any(|c| matches!(
+ c,
+ DrawCommand::InternalLink { destination, .. } if &**destination == "_Toc123"
+ )),
+ "internal bookmark link must be a GoTo destination"
+ );
+ assert!(
+ !result
+ .commands
+ .iter()
+ .any(|c| matches!(c, DrawCommand::LinkAnnotation { .. })),
+ "internal link must not be emitted as an external URI"
+ );
+ }
+
+ #[test]
+ fn both_alignment_justifies_from_trimmed_line_width() {
+ let mut trailing = text_frag("beta ", 25.0);
+ if let Fragment::Text { trimmed_width, .. } = &mut trailing {
+ *trimmed_width = Pt::new(20.0);
+ }
+ let result = layout_paragraph(
+ &[
+ text_frag("alpha ", 25.0),
+ trailing,
+ text_frag("gamma", 30.0),
+ ],
+ &body_constraints(60.0),
+ &ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ },
+ Pt::new(14.0),
+ None,
+ );
+
+ let xs = text_xs(&result);
+ assert!(
+ (xs[1] - 40.0).abs() < 0.01,
+ "the visible first line is 45pt wide, so its gap must grow by 15pt: {xs:?}",
+ );
+ }
+
+ #[test]
+ fn distribute_alignment_spreads_characters_across_single_line() {
+ let result = layout_paragraph(
+ &[
+ text_frag("AB", 20.0),
+ hyperlink_frag("CD", 20.0, "https://example.invalid/distributed"),
+ ],
+ &body_constraints(60.0),
+ &ParagraphStyle {
+ alignment: Alignment::Distribute,
+ ..Default::default()
+ },
+ Pt::new(14.0),
+ None,
+ );
+
+ let texts = result
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text {
+ position,
+ char_spacing,
+ ..
+ } => Some((position.x.raw(), char_spacing.raw())),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ assert!((texts[0].0 - 0.0).abs() < 0.01);
+ assert!((texts[1].0 - 33.333).abs() < 0.01, "text runs: {texts:?}");
+ assert!((texts[0].1 - 6.667).abs() < 0.01, "text runs: {texts:?}");
+ assert!((texts[1].1 - 6.667).abs() < 0.01, "text runs: {texts:?}");
+
+ let link = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::LinkAnnotation { rect, url }
+ if &**url == "https://example.invalid/distributed" =>
+ {
+ Some(*rect)
+ }
+ _ => None,
+ })
+ .expect("distributed hyperlink");
+ assert!(((link.origin.x + link.size.width).raw() - 60.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn distribute_alignment_adds_to_existing_character_spacing() {
+ let mut first = text_frag("A", 10.0);
+ let mut second = text_frag("B", 10.0);
+ for fragment in [&mut first, &mut second] {
+ if let Fragment::Text { font, .. } = fragment {
+ Rc::make_mut(font).char_spacing = Pt::new(2.0);
+ }
+ }
+ let result = layout_paragraph(
+ &[first, second],
+ &body_constraints(30.0),
+ &ParagraphStyle {
+ alignment: Alignment::Distribute,
+ ..Default::default()
+ },
+ Pt::new(14.0),
+ None,
+ );
+ let texts = result
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text {
+ position,
+ char_spacing,
+ ..
+ } => Some((position.x.raw(), char_spacing.raw())),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ assert!((texts[0].1 - 12.0).abs() < 0.01, "text runs: {texts:?}");
+ assert!((texts[1].0 - 20.0).abs() < 0.01, "text runs: {texts:?}");
+ }
+
+ #[test]
+ fn distribute_alignment_keeps_tab_lines_at_natural_width() {
+ let result = layout_paragraph(
+ &[
+ text_frag("A", 10.0),
+ Fragment::Tab {
+ line_height: Pt::new(14.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ fitting_width: None,
+ },
+ text_frag("B", 10.0),
+ ],
+ &body_constraints(60.0),
+ &ParagraphStyle {
+ alignment: Alignment::Distribute,
+ ..Default::default()
+ },
+ Pt::new(14.0),
+ None,
+ );
+ let spacings = result
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { char_spacing, .. } => Some(*char_spacing),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ assert!(spacings.iter().all(|spacing| *spacing == Pt::ZERO));
+ }
+
+ #[test]
+ fn both_alignment_keeps_explicit_break_lines_at_natural_width() {
+ let style = ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ };
+ let fragments = vec![
+ underlined_text_frag("alpha ", 25.0),
+ text_frag("beta", 25.0),
+ Fragment::LineBreak {
+ line_height: Pt::new(14.0),
+ },
+ text_frag("gamma", 30.0),
+ ];
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[1] - 25.0).abs() < 0.01);
+ let underline = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Underline { line, .. } => Some(*line),
+ _ => None,
+ })
+ .expect("underlined explicit-break gap");
+ assert!((underline.end.x.raw() - 25.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn both_alignment_does_not_expand_nbsp_gaps() {
+ let style = ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ };
+ let fragments = vec![
+ underlined_text_frag("alpha\u{00a0}", 25.0),
+ text_frag("beta", 25.0),
+ text_frag("gamma", 30.0),
+ ];
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[1] - 25.0).abs() < 0.01);
+ let underline = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Underline { line, .. } => Some(*line),
+ _ => None,
+ })
+ .expect("underlined NBSP gap");
+ assert!((underline.end.x.raw() - 25.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn both_alignment_keeps_structured_tab_lines_at_natural_width() {
+ let style = ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ };
+ let fragments = vec![
+ underlined_text_frag("alpha ", 25.0),
+ Fragment::Tab {
+ line_height: Pt::new(14.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ fitting_width: None,
+ },
+ text_frag("beta ", 25.0),
+ text_frag("gamma", 30.0),
+ ];
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(70.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[1] - 36.0).abs() < 0.01);
+ let underline = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Underline { line, .. } => Some(*line),
+ _ => None,
+ })
+ .expect("underlined structured-tab gap");
+ assert!((underline.end.x.raw() - 25.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn both_alignment_justifies_after_list_label_separator() {
+ let result = layout_paragraph(
+ &[
+ text_frag("1.", 10.0),
+ Fragment::Tab {
+ line_height: Pt::new(14.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ fitting_width: Some(Pt::new(5.0)),
+ },
+ text_frag("alpha ", 20.0),
+ text_frag("beta ", 20.0),
+ text_frag("gamma", 30.0),
+ ],
+ &body_constraints(60.0),
+ &ParagraphStyle {
+ alignment: Alignment::Both,
+ tabs: vec![TabStopDef {
+ position: Pt::new(15.0),
+ alignment: crate::model::TabAlignment::Left,
+ leader: crate::model::TabLeader::None,
+ }],
+ ..Default::default()
+ },
+ Pt::new(14.0),
+ None,
+ );
+
+ let xs = text_xs(&result);
+ assert!(
+ (xs[2] - 40.0).abs() < 0.01,
+ "the first list-item line must justify after its synthetic label tab: {xs:?}",
+ );
+ }
+
+ #[test]
+ fn both_alignment_justifies_after_picture_bullet_separator() {
+ let result = layout_paragraph(
+ &[
+ image_frag(10.0, 10.0),
+ Fragment::Tab {
+ line_height: Pt::new(14.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ fitting_width: Some(Pt::new(5.0)),
+ },
+ text_frag("alpha ", 20.0),
+ text_frag("beta ", 20.0),
+ text_frag("gamma", 30.0),
+ ],
+ &body_constraints(60.0),
+ &ParagraphStyle {
+ alignment: Alignment::Both,
+ tabs: vec![TabStopDef {
+ position: Pt::new(15.0),
+ alignment: crate::model::TabAlignment::Left,
+ leader: crate::model::TabLeader::None,
+ }],
+ ..Default::default()
+ },
+ Pt::new(14.0),
+ None,
+ );
+
+ let xs = text_xs(&result);
+ assert!(
+ (xs[1] - 40.0).abs() < 0.01,
+ "the first picture-bullet line must justify after its synthetic tab: {xs:?}",
+ );
+ }
+
+ #[test]
+ fn both_alignment_keeps_literal_tab_text_lines_at_natural_width() {
+ let style = ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ };
+ let fragments = vec![
+ underlined_text_frag("alpha ", 25.0),
+ text_frag("\t", 5.0),
+ text_frag("beta ", 25.0),
+ text_frag("gamma", 30.0),
+ ];
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[2] - 30.0).abs() < 0.01);
+ let underline = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Underline { line, .. } => Some(*line),
+ _ => None,
+ })
+ .expect("underlined literal-tab gap");
+ assert!((underline.end.x.raw() - 25.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn both_alignment_stretches_hyperlink_run_without_changing_text_order() {
+ let style = ParagraphStyle {
+ alignment: Alignment::Both,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &[
+ text_frag("alpha", 10.0),
+ hyperlink_frag("beta ", 25.0, "https://example.invalid/stretched"),
+ text_frag("gamma ", 15.0),
+ text_frag("delta", 30.0),
+ ],
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[2] - 45.0).abs() < 0.01);
+ let text_runs: Vec<_> = result
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, .. } => Some(text.to_string()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(text_runs, ["alpha", "beta ", "gamma ", "delta"]);
+ let link_rect = result
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::LinkAnnotation { rect, url }
+ if &**url == "https://example.invalid/stretched" =>
+ {
+ Some(*rect)
+ }
+ _ => None,
+ })
+ .expect("stretched hyperlink annotation");
+ assert!((link_rect.origin.x.raw() - 10.0).abs() < 0.01);
+ assert!((link_rect.size.width.raw() - 35.0).abs() < 0.01);
+ }
+
+ #[test]
+ fn start_center_and_end_alignment_positions_are_unchanged() {
+ let fragments = vec![text_frag("alpha ", 25.0), text_frag("beta", 25.0)];
+ for (alignment, expected_x) in [
+ (Alignment::Start, 0.0),
+ (Alignment::Center, 5.0),
+ (Alignment::End, 10.0),
+ ] {
+ let style = ParagraphStyle {
+ alignment,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &fragments,
+ &body_constraints(60.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+ assert!((text_xs(&result)[0] - expected_x).abs() < 0.01);
+ }
+ }
+
+ #[test]
+ fn indentation_shifts_text() {
+ let frags = vec![text_frag("text", 40.0)];
+ let style = ParagraphStyle {
+ indent_left: Pt::new(36.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ if let DrawCommand::Text { position, .. } = &result.commands[0] {
+ assert_eq!(position.x.raw(), 36.0);
+ }
+ }
+
+ #[test]
+ fn first_line_indent() {
+ let frags = vec![text_frag("first ", 40.0), text_frag("second", 40.0)];
+ let style = ParagraphStyle {
+ indent_first_line: Pt::new(24.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ if let DrawCommand::Text { position, .. } = &result.commands[0] {
+ assert_eq!(position.x.raw(), 24.0, "first line indented");
+ }
+ }
+
+ #[test]
+ fn space_before_and_after() {
+ let frags = vec![text_frag("text", 30.0)];
+ let style = ParagraphStyle {
+ space_before: Pt::new(10.0),
+ space_after: Pt::new(8.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ // Height should be: space_before(10) + line_height(14) + space_after(8) = 32
+ assert_eq!(result.size.height.raw(), 32.0);
+
+ // Text y should include space_before
+ if let DrawCommand::Text { position, .. } = &result.commands[0] {
+ assert!(
+ position.y.raw() >= 10.0,
+ "y should account for space_before"
+ );
+ }
+ }
+
+ #[test]
+ fn line_spacing_exact() {
+ let frags = vec![text_frag("line1 ", 60.0), text_frag("line2", 60.0)];
+ let style = ParagraphStyle {
+ line_spacing: LineSpacingRule::Exact(Pt::new(20.0)),
+ ..Default::default()
+ };
+ // With max_width=80, they'll break into 2 lines
+ let result = layout_paragraph(&frags, &body_constraints(80.0), &style, Pt::new(14.0), None);
+
+ assert_eq!(result.size.height.raw(), 40.0, "2 lines * 20pt each");
+ }
+
+ #[test]
+ fn line_spacing_at_least_with_larger_natural() {
+ let frags = vec![text_frag("text", 30.0)];
+ let style = ParagraphStyle {
+ line_spacing: LineSpacingRule::AtLeast(Pt::new(10.0)),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ // Natural height is 14, at-least is 10 → should be 14
+ assert_eq!(result.size.height.raw(), 14.0);
+ }
+
+ #[test]
+ fn wrapping_produces_multiple_lines() {
+ let frags = vec![
+ text_frag("word1 ", 45.0),
+ text_frag("word2 ", 45.0),
+ text_frag("word3", 45.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(80.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+
+ // Should have 3 text commands (one per word, each on its own line)
+ let text_count = result
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(text_count, 3);
+ // Height: 3 lines * 14pt = 42pt
+ assert_eq!(result.size.height.raw(), 42.0);
+ }
+
+ fn text_ys(commands: &[DrawCommand]) -> Vec<f32> {
+ commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.y.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn emit_split_segment_partitions_full_emit() {
+ // Four words, each wrapping to its own 14pt line, with space_before and
+ // space_after so we can check they land on the right segments.
+ let frags = vec![
+ text_frag("word1 ", 45.0),
+ text_frag("word2 ", 45.0),
+ text_frag("word3 ", 45.0),
+ text_frag("word4", 45.0),
+ ];
+ let style = ParagraphStyle {
+ space_before: Pt::new(10.0),
+ space_after: Pt::new(6.0),
+ ..Default::default()
+ };
+ let constraints = body_constraints(80.0);
+ let placed = place_paragraph(&frags, &constraints, &style, Pt::new(14.0), None);
+ assert_eq!(placed.line_count(), 4);
+ assert_eq!(placed.unbreakable_prefix_lines(), 0, "no drop cap / floats");
+
+ let full = placed.emit_full();
+ let head = placed.emit_split_segment(0, 2, true, false);
+ let tail = placed.emit_split_segment(2, 4, false, true);
+
+ // Content preserved: 4 text commands total, 2 per segment.
+ assert_eq!(text_ys(&full.commands).len(), 4);
+ assert_eq!(text_ys(&head.commands).len(), 2);
+ assert_eq!(text_ys(&tail.commands).len(), 2);
+
+ // §17.3.1.33: the two segment heights reconstruct the whole height
+ // (space_before on the head, space_after on the tail, no double count).
+ assert_eq!(
+ (head.size.height + tail.size.height).raw(),
+ full.size.height.raw()
+ );
+
+ // The head reproduces the first lines verbatim; the tail reproduces the
+ // rest, shifted up by the head's height.
+ let full_ys = text_ys(&full.commands);
+ assert_eq!(text_ys(&head.commands).as_slice(), &full_ys[..2]);
+ for (i, y) in text_ys(&tail.commands).iter().enumerate() {
+ assert_eq!(*y + head.size.height.raw(), full_ys[2 + i]);
+ }
+ }
+
+ fn border(width: f32) -> BorderLine {
+ BorderLine {
+ width: Pt::new(width),
+ color: RgbColor::BLACK,
+ space: Pt::new(2.0),
+ }
+ }
+
+ /// (horizontal border lines, vertical border lines) in a segment.
+ fn classify_border_lines(commands: &[DrawCommand]) -> (usize, usize) {
+ let mut horizontal = 0;
+ let mut vertical = 0;
+ for c in commands {
+ if let DrawCommand::Line { line, .. } = c {
+ if (line.start.y.raw() - line.end.y.raw()).abs() < 1e-3 {
+ horizontal += 1;
+ } else if (line.start.x.raw() - line.end.x.raw()).abs() < 1e-3 {
+ vertical += 1;
+ }
+ }
+ }
+ (horizontal, vertical)
+ }
+
+ fn rect_count(commands: &[DrawCommand]) -> usize {
+ commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Rect { .. }))
+ .count()
+ }
+
+ fn horizontal_line_y(commands: &[DrawCommand]) -> Option<f32> {
+ commands.iter().find_map(|c| match c {
+ DrawCommand::Line { line, .. }
+ if (line.start.y.raw() - line.end.y.raw()).abs() < 1e-3 =>
+ {
+ Some(line.start.y.raw())
+ }
+ _ => None,
+ })
+ }
+
+ #[test]
+ fn float_wrapped_lines_form_an_unbreakable_prefix() {
+ // §17.3.1.44: an active float covering y[0,30) narrows the first three
+ // 14pt lines (y 0, 14, 28). Those float-wrapped lines must stay on the
+ // first segment so the full-width continuation reuses its fitted lines.
+ use crate::render::layout::float::{ActiveFloat, FloatSource, WrapTextSide};
+ let float = ActiveFloat {
+ page_x: Pt::ZERO,
+ page_y_start: Pt::ZERO,
+ page_y_end: Pt::new(30.0),
+ width: Pt::new(60.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ };
+ let style = ParagraphStyle {
+ page_floats: vec![float],
+ page_x: Pt::ZERO,
+ page_content_width: Pt::new(120.0),
+ ..Default::default()
+ };
+ let frags: Vec<Fragment> = (0..20)
+ .map(|i| text_frag(&format!("w{i} "), 20.0))
+ .collect();
+ let constraints = body_constraints(120.0);
+ let placed = place_paragraph(&frags, &constraints, &style, Pt::new(14.0), None);
+
+ assert!(placed.line_count() >= 4, "enough lines to clear the float");
+ assert_eq!(
+ placed.unbreakable_prefix_lines(),
+ 3,
+ "the three float-narrowed lines are the unbreakable prefix"
+ );
+ }
+
+ #[test]
+ fn split_segment_draws_border_box_per_page() {
+ // §17.3.1.24/§17.3.1.31: a bordered, shaded paragraph split across three
+ // pages keeps side borders and shading on every segment, the top border
+ // only on the first, and the bottom border only on the last.
+ let frags: Vec<Fragment> = (0..6)
+ .map(|i| text_frag(&format!("word{i} "), 100.0))
+ .collect();
+ let style = ParagraphStyle {
+ borders: Some(ParagraphBorderStyle {
+ top: Some(border(1.0)),
+ bottom: Some(border(1.0)),
+ left: Some(border(1.0)),
+ right: Some(border(1.0)),
+ }),
+ shading: Some(RgbColor::BLACK),
+ ..Default::default()
+ };
+ // Box wider than a word (with room for the 2pt side border spaces) so
+ // each word is its own line without triggering per-character splitting.
+ let constraints = body_constraints(120.0);
+ let placed = place_paragraph(&frags, &constraints, &style, Pt::new(14.0), None);
+ assert_eq!(
+ placed.unbreakable_prefix_lines(),
+ 0,
+ "bordered/shaded paragraphs split freely (no drop cap / floats)"
+ );
+ assert_eq!(placed.line_count(), 6);
+
+ let head = placed.emit_split_segment(0, 2, true, false);
+ let mid = placed.emit_split_segment(2, 4, false, false);
+ let tail = placed.emit_split_segment(4, 6, false, true);
+
+ // Shading fills every segment.
+ assert_eq!(rect_count(&head.commands), 1);
+ assert_eq!(rect_count(&mid.commands), 1);
+ assert_eq!(rect_count(&tail.commands), 1);
+
+ // Sides on every segment; top only first, bottom only last.
+ assert_eq!(
+ classify_border_lines(&head.commands),
+ (1, 2),
+ "first: top + sides"
+ );
+ assert_eq!(
+ classify_border_lines(&mid.commands),
+ (0, 2),
+ "middle: sides only"
+ );
+ assert_eq!(
+ classify_border_lines(&tail.commands),
+ (1, 2),
+ "last: bottom + sides"
+ );
+
+ // The first segment's horizontal edge sits above its text (the top
+ // border, with border space above space_before); the last segment's sits
+ // below its two lines (the bottom border).
+ assert!(horizontal_line_y(&head.commands).unwrap() < 0.0);
+ assert!(horizontal_line_y(&tail.commands).unwrap() > 28.0);
+ }
+
+ #[test]
+ fn resolve_line_height_auto_text_only() {
+ // Text-only line: multiplier applies to text_height.
+ assert_eq!(
+ resolve_line_height(
+ Pt::new(14.0),
+ Pt::new(14.0),
+ &LineSpacingRule::Auto(1.0),
+ crate::render::layout::ShapeAutoFit::NONE
+ )
+ .raw(),
+ 14.0
+ );
+ assert_eq!(
+ resolve_line_height(
+ Pt::new(14.0),
+ Pt::new(14.0),
+ &LineSpacingRule::Auto(1.5),
+ crate::render::layout::ShapeAutoFit::NONE
+ )
+ .raw(),
+ 21.0
+ );
+ }
+
+ #[test]
+ fn resolve_line_height_auto_image_line() {
+ // Image-only line: natural=325 (image), text_height=0 (no text).
+ // The multiplier does NOT inflate the image height.
+ let h = resolve_line_height(
+ Pt::new(325.0),
+ Pt::ZERO,
+ &LineSpacingRule::Auto(1.08),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert_eq!(h.raw(), 325.0, "image height should not be multiplied");
+ }
+
+ #[test]
+ fn resolve_line_height_auto_mixed_line() {
+ // Line with text (14pt) and image (100pt): multiplier scales text only.
+ // max(14*1.5=21, 100) = 100.
+ let h = resolve_line_height(
+ Pt::new(100.0),
+ Pt::new(14.0),
+ &LineSpacingRule::Auto(1.5),
+ crate::render::layout::ShapeAutoFit::NONE,
+ );
+ assert_eq!(h.raw(), 100.0, "image dominates");
+ }
+
+ #[test]
+ fn resolve_line_height_exact_overrides() {
+ assert_eq!(
+ resolve_line_height(
+ Pt::new(14.0),
+ Pt::new(14.0),
+ &LineSpacingRule::Exact(Pt::new(20.0)),
+ crate::render::layout::ShapeAutoFit::NONE,
+ )
+ .raw(),
+ 20.0
+ );
+ }
+
+ #[test]
+ fn resolve_line_height_at_least() {
+ assert_eq!(
+ resolve_line_height(
+ Pt::new(14.0),
+ Pt::new(14.0),
+ &LineSpacingRule::AtLeast(Pt::new(10.0)),
+ crate::render::layout::ShapeAutoFit::NONE,
+ )
+ .raw(),
+ 14.0,
+ "natural > minimum"
+ );
+ assert_eq!(
+ resolve_line_height(
+ Pt::new(8.0),
+ Pt::new(8.0),
+ &LineSpacingRule::AtLeast(Pt::new(10.0)),
+ crate::render::layout::ShapeAutoFit::NONE,
+ )
+ .raw(),
+ 10.0,
+ "minimum > natural"
+ );
+ }
+
+ // ── Absolute position tabs (§17.3.1.30) ──
+
+ fn ptab_frag(align: PTabAlignment, relative_to: PTabRelativeTo) -> Fragment {
+ Fragment::PTab {
+ align,
+ relative_to,
+ leader: crate::model::TabLeader::None,
+ line_height: Pt::new(12.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ }
+ }
+
+ /// Return the x positions of every emitted Text command, in order.
+ fn text_xs(result: &ParagraphLayout) -> Vec<f32> {
+ result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.x.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Return `(text, x, y)` for every emitted Text command, in order.
+ fn text_positions(result: &ParagraphLayout) -> Vec<(String, f32, f32)> {
+ result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { text, position, .. } => {
+ Some((text.to_string(), position.x.raw(), position.y.raw()))
+ }
+ _ => None,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn ptab_whose_anchor_is_passed_advances_to_the_next_line() {
+ // §17.3.1.30: when the alignment point has already been passed, the
+ // tab advances to that location on the *next* line.
+ //
+ // Reproduction from the branch review: everything fits the 400pt line
+ // by width (10 + 200 + 180 = 390), but the right ptab's anchor sits at
+ // 400 - 180 = 220, behind the pen at 300. Clamping drew "C" at
+ // 300..480 — 80pt off the page.
+ let frags = vec![
+ text_frag("A", 10.0),
+ ptab_frag(PTabAlignment::Center, PTabRelativeTo::Margin),
+ text_frag("B", 200.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Margin),
+ text_frag("C", 180.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 3, "no content dropped: {positions:?}");
+ let (_, c_x, c_y) = &positions[2];
+ let (_, _, a_y) = &positions[0];
+
+ assert!(
+ c_y > a_y,
+ "C advances to the next line rather than overflowing: {positions:?}"
+ );
+ assert_eq!(*c_x, 220.0, "and lands on its anchor: 400 - 180");
+ assert!(
+ c_x + 180.0 <= 400.0,
+ "C ends within the page: {}",
+ c_x + 180.0
+ );
+ }
+
+ #[test]
+ fn left_margin_ptab_pulls_back_to_the_margin_on_the_next_line() {
+ // §17.3.1.30: `left` + `relativeTo="margin"` anchors at the page
+ // margin (x=0). Reached from an indented paragraph the anchor is
+ // behind the pen, so — same rule — it advances to the next line
+ // rather than becoming the silent no-op `0.max(x)` produced.
+ let frags = vec![
+ text_frag("indented", 60.0),
+ ptab_frag(PTabAlignment::Left, PTabRelativeTo::Margin),
+ text_frag("at-margin", 40.0),
+ ];
+ let style = ParagraphStyle {
+ indent_left: Pt::new(100.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 2, "{positions:?}");
+ let (_, first_x, first_y) = &positions[0];
+ let (_, second_x, second_y) = &positions[1];
+
+ assert!(second_y > first_y, "advances to the next line");
+ assert_eq!(*second_x, 0.0, "and reaches the page margin");
+ assert!(*first_x >= 100.0, "the indented run is unaffected");
+ }
+
+ #[test]
+ fn a_ptab_at_the_line_start_places_rather_than_looping() {
+ // The progress guard: when the tab is already the first thing on its
+ // line, advancing to the next line cannot move the anchor any closer,
+ // so it places (clamped) and overflows instead. Acting on a condition
+ // the action cannot change is how the paginator bugs in this engine
+ // have historically become infinite loops.
+ // Three same-width runs, none individually oversized (so nothing is
+ // split), but a zone far wider than the centre anchor — the tab's
+ // desired x is negative and it is already at the line start.
+ let frags = vec![
+ ptab_frag(PTabAlignment::Center, PTabRelativeTo::Margin),
+ text_frag("one", 90.0),
+ text_frag("two", 90.0),
+ text_frag("three", 90.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(100.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(
+ positions.len(),
+ 3,
+ "every run is emitted, none dropped: {positions:?}"
+ );
+ assert!(
+ positions.iter().all(|(_, x, _)| *x >= 0.0),
+ "nothing is placed left of the line start: {positions:?}"
+ );
+ }
+
+ #[test]
+ fn fitting_and_emission_agree_about_the_pen_on_an_indented_line() {
+ // Fitting decides whether a ptab can be honoured on this line;
+ // emission decides its x. Both must start the line at the same place,
+ // or an indented paragraph gets classified one way and drawn another.
+ //
+ // The fitter seeded its pen at 0 while emission seeds it at the
+ // indent, so the two could classify the same tab differently. Here the
+ // right-margin anchor for a 150pt zone is 250: ahead of the fitter's
+ // pen (200) but behind emission's (300). The fitter therefore saw no
+ // reason to break, and emission — unable to break — clamped to 300,
+ // running B out to 450, past the 400pt margin B1 was meant to protect.
+ let frags = vec![
+ text_frag("A", 200.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Margin),
+ text_frag("B", 150.0),
+ ];
+ let style = ParagraphStyle {
+ indent_left: Pt::new(100.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 2, "{positions:?}");
+ assert!(
+ positions[1].2 > positions[0].2,
+ "B advances to the next line: {positions:?}"
+ );
+ assert_eq!(positions[1].1, 250.0, "and lands on its anchor: 400 - 150");
+ assert!(positions[1].1 + 150.0 <= 400.0, "B stays within the margin");
+ }
+
+ #[test]
+ fn a_margin_ptab_may_use_the_space_a_right_indent_excludes() {
+ // §17.3.1.30: `relativeTo="margin"` measures against the full text
+ // area, so its zone may occupy space the paragraph's own right indent
+ // excludes. Fitting bounds lines by `content_width` (net of indents),
+ // which wrapped such a line even though the content fits the margin
+ // region — leaving a stray leader on the short line.
+ //
+ // content_width = 400 - 100 (right indent) = 300, but A(50) + B(320)
+ // reaches only 400, exactly the margin.
+ let frags = vec![
+ text_frag("A", 50.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Margin),
+ text_frag("B", 320.0),
+ ];
+ let style = ParagraphStyle {
+ indent_right: Pt::new(100.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 2, "{positions:?}");
+ assert_eq!(
+ positions[0].2, positions[1].2,
+ "the line fits the margin region and must not wrap: {positions:?}"
+ );
+ assert_eq!(
+ positions[1].1, 80.0,
+ "B right-aligned at the margin: 400 - 320"
+ );
+ }
+
+ #[test]
+ fn an_indent_ptab_respects_the_lines_own_float_narrowing() {
+ // §17.3.1.30 + §20.4.2: `relativeTo="indent"` measures against the
+ // indented region, but that region is narrower on a line a float
+ // overlaps. Using the paragraph-level width right-aligned the zone to
+ // the paragraph's edge — on top of the float.
+ //
+ // A 60pt float occupies x 140..200 of a 200pt line, so the line's own
+ // right edge is 140 and a 40pt zone must end there, at x=100.
+ use crate::render::layout::float::{ActiveFloat, FloatSource, WrapTextSide};
+ let float = ActiveFloat {
+ page_x: Pt::new(140.0),
+ page_y_start: Pt::ZERO,
+ page_y_end: Pt::new(30.0),
+ width: Pt::new(60.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ };
+ let style = ParagraphStyle {
+ page_floats: vec![float],
+ page_x: Pt::ZERO,
+ page_content_width: Pt::new(200.0),
+ ..Default::default()
+ };
+ let frags = vec![
+ text_frag("A", 10.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Indent),
+ text_frag("B", 40.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(200.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 2, "{positions:?}");
+ assert_eq!(
+ positions[1].1, 100.0,
+ "B right-aligns to the line's own edge (140), not the paragraph's (200)"
+ );
+ assert!(
+ positions[1].1 + 40.0 <= 140.0,
+ "and therefore clears the float at 140: {positions:?}"
+ );
+ }
+
+ /// A float occupying `x0..x0+60` of a 200pt line for y `0..30`.
+ fn float_at(x0: f32) -> crate::render::layout::float::ActiveFloat {
+ use crate::render::layout::float::{ActiveFloat, FloatSource, WrapTextSide};
+ ActiveFloat {
+ page_x: Pt::new(x0),
+ page_y_start: Pt::ZERO,
+ page_y_end: Pt::new(30.0),
+ width: Pt::new(60.0),
+ source: FloatSource::Image,
+ wrap_text: WrapTextSide::BothSides,
+ }
+ }
+
+ fn style_with_float(x0: f32) -> ParagraphStyle {
+ ParagraphStyle {
+ page_floats: vec![float_at(x0)],
+ page_x: Pt::ZERO,
+ page_content_width: Pt::new(200.0),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn an_indent_ptab_follows_a_left_float_too() {
+ // The mirror of the right-float case: a float on the left moves the
+ // indented region's *start*, so a left-aligned indent ptab must anchor
+ // clear of it rather than at the paragraph's own left edge.
+ let frags = vec![
+ ptab_frag(PTabAlignment::Left, PTabRelativeTo::Indent),
+ text_frag("B", 40.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(200.0),
+ &style_with_float(0.0),
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 1, "{positions:?}");
+ assert_eq!(
+ positions[0].1, 60.0,
+ "B anchors past the float, not at the paragraph's left edge"
+ );
+ }
+
+ #[test]
+ fn a_margin_ptab_is_deliberately_unaffected_by_floats() {
+ // `margin` names the page text margins, which a float does not move.
+ // Only `indent` follows the line's narrowed region — pinning the
+ // difference so the two do not get "unified" later.
+ let frags = vec![
+ text_frag("A", 10.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Margin),
+ text_frag("B", 40.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(200.0),
+ &style_with_float(140.0),
+ Pt::new(14.0),
+ None,
+ );
+
+ let positions = text_positions(&result);
+ assert_eq!(positions.len(), 2, "{positions:?}");
+ assert_eq!(
+ positions[1].1, 160.0,
+ "right margin anchor stays at 200 — 200 - 40 — despite the float"
+ );
+ }
+
+ #[test]
+ fn ptab_three_region_header() {
+ // The canonical Word header: left ⟶ ptab(center) ⟶ center ⟶
+ // ptab(right) ⟶ right, all relative to the page margins.
+ let frags = vec![
+ text_frag("L", 10.0),
+ ptab_frag(PTabAlignment::Center, PTabRelativeTo::Margin),
+ text_frag("C", 20.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Margin),
+ text_frag("R", 30.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(100.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+
+ let xs = text_xs(&result);
+ assert_eq!(xs.len(), 3, "three text runs, no leaders");
+ assert_eq!(xs[0], 0.0, "left run at the left margin");
+ assert_eq!(xs[1], 40.0, "center run centered on 50 → 50 - 20/2");
+ assert_eq!(xs[2], 70.0, "right run ends at the right margin → 100 - 30");
+ }
+
+ #[test]
+ fn ptab_right_relative_to_indent() {
+ // relativeTo=indent uses [indent_left, content_width - indent_right].
+ let frags = vec![
+ text_frag("x", 10.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Indent),
+ text_frag("yy", 20.0),
+ ];
+ let style = ParagraphStyle {
+ indent_right: Pt::new(30.0),
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(100.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ let xs = text_xs(&result);
+ // span_end = 100 - 30 = 70; right run of width 20 ends there → 50.
+ assert_eq!(xs[1], 50.0, "right run ends at the right indent");
+ }
+
+ #[test]
+ fn ptab_suppresses_paragraph_alignment() {
+ // A line with a ptab is positioned by the ptab, not by the paragraph's
+ // alignment (§17.3.1.37 rationale) — the left run stays at the margin.
+ let frags = vec![
+ text_frag("L", 10.0),
+ ptab_frag(PTabAlignment::Right, PTabRelativeTo::Margin),
+ text_frag("R", 30.0),
+ ];
+ let style = ParagraphStyle {
+ alignment: Alignment::End,
+ ..Default::default()
+ };
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(100.0),
+ &style,
+ Pt::new(14.0),
+ None,
+ );
+
+ let xs = text_xs(&result);
+ assert_eq!(xs[0], 0.0, "left run not shifted by End alignment");
+ assert_eq!(xs[1], 70.0, "right run ends at the right margin");
+ }
+
+ // ── Decimal tab alignment (§17.18.85 `ST_TabJc` = decimal) ──
+ //
+ // A decimal stop aligns the *separator* on the stop, not an edge of the
+ // zone. These use a 10pt-per-character measurer so the expected x values
+ // are exact arithmetic rather than font-dependent.
+
+ /// Measure every character as 10pt wide, so a prefix's width is
+ /// `10 * prefix.chars().count()`.
+ fn ten_pt_per_char(text: &str, _f: &FontProps) -> (Pt, TextMetrics) {
+ (
+ Pt::new(10.0 * text.chars().count() as f32),
+ TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ )
+ }
+
+ fn decimal_stop_at(pos: f32) -> ParagraphStyle {
+ ParagraphStyle {
+ tabs: vec![TabStopDef {
+ position: Pt::new(pos),
+ alignment: crate::model::TabAlignment::Decimal,
+ leader: crate::model::TabLeader::None,
+ }],
+ ..Default::default()
+ }
+ }
+
+ /// Lay out `a<tab>zone` against a decimal stop at 100 and return the x of
+ /// the zone's text.
+ fn decimal_zone_x(zone: &str) -> f32 {
+ let measurer: &dyn Fn(&str, &FontProps) -> (Pt, TextMetrics) = &ten_pt_per_char;
+ let frags = vec![
+ text_frag("a", 10.0),
+ Fragment::Tab {
+ line_height: Pt::new(12.0),
+ font: leader_font("Test", 12.0),
+ color: RgbColor::BLACK,
+ fitting_width: None,
+ },
+ text_frag(zone, 10.0 * zone.chars().count() as f32),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(400.0),
+ &decimal_stop_at(100.0),
+ Pt::new(14.0),
+ Some(measurer),
+ );
+ *text_xs(&result).last().expect("zone text is emitted")
+ }
+
+ #[test]
+ fn decimal_tab_puts_the_separator_on_the_stop() {
+ // §17.18.85: the decimal separator lands on the stop, whatever the
+ // integer part's width. "1.5" has one char before the separator,
+ // "22.75" has two — so they start 10pt apart and their separators
+ // coincide at x=100.
+ assert_eq!(decimal_zone_x("1.5"), 90.0, "one char before the separator");
+ assert_eq!(
+ decimal_zone_x("22.75"),
+ 80.0,
+ "two chars before the separator"
+ );
+ assert_eq!(
+ decimal_zone_x("333.125"),
+ 70.0,
+ "three chars before the separator"
+ );
+ }
+
+ #[test]
+ fn decimal_tab_without_a_separator_right_aligns() {
+ // Word right-aligns a decimal-tabbed zone that has no separator —
+ // aligning its left edge would leave numeric columns ragged.
+ assert_eq!(
+ decimal_zone_x("1234"),
+ 60.0,
+ "4 chars ending at the stop → 100 - 40"
+ );
+ }
+
+ #[test]
+ fn decimal_tab_aligns_on_the_first_separator() {
+ // A version string has several; the first is the alignment point.
+ assert_eq!(decimal_zone_x("1.2.3"), 90.0);
+ }
+
+ #[test]
+ fn decimal_tab_never_moves_content_backwards() {
+ // The zone is wider than the stop, so honouring the separator would
+ // place text left of the current pen. Clamp, as right/center do.
+ assert_eq!(
+ decimal_zone_x("1234567890123.5"),
+ 10.0,
+ "separator would land at -30; clamped to the pen after 'a'"
+ );
+ }
+
+ // ── Tab leaders (§17.3.1.38) ──
+ //
+ // A leader carries no formatting of its own: §17.3.1.38 defines it as
+ // filling the tab with a character, and the character is drawn in the
+ // formatting in effect at the tab — i.e. the `<w:rPr>` of the run holding
+ // the `<w:tab/>`. These assert that, not the paragraph default.
+
+ /// Build a run font differing from every default, so a leader that
+ /// inherits it cannot pass by coincidence.
+ fn leader_font(family: &str, size: f32) -> Rc<FontProps> {
+ Rc::new(FontProps {
+ family: Rc::from(family),
+ size: Pt::new(size),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ })
+ }
+
+ fn dotted_stop_at(pos: f32) -> ParagraphStyle {
+ ParagraphStyle {
+ tabs: vec![TabStopDef {
+ position: Pt::new(pos),
+ alignment: crate::model::TabAlignment::Left,
+ leader: crate::model::TabLeader::Dot,
+ }],
+ ..Default::default()
+ }
+ }
+
+ /// The first Text command whose text is all leader dots.
+ fn leader_command(result: &ParagraphLayout) -> &DrawCommand {
+ result
+ .commands
+ .iter()
+ .find(|c| match c {
+ DrawCommand::Text { text, .. } => {
+ !text.is_empty() && text.chars().all(|c| c == '.')
+ }
+ _ => false,
+ })
+ .expect("a dotted tab stop must emit a leader command")
+ }
+
+ #[test]
+ fn tab_leader_inherits_the_run_font_and_colour() {
+ // §17.3.1.38: the leader is drawn in the tab run's own formatting.
+ // Previously it was hardcoded to Times New Roman / black.
+ let frags = vec![
+ text_frag("a", 10.0),
+ Fragment::Tab {
+ line_height: Pt::new(12.0),
+ font: leader_font("Georgia", 12.0),
+ color: RgbColor { r: 255, g: 0, b: 0 },
+ fitting_width: None,
+ },
+ text_frag("b", 10.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(200.0),
+ &dotted_stop_at(100.0),
+ Pt::new(14.0),
+ None,
+ );
+
+ match leader_command(&result) {
+ DrawCommand::Text {
+ font_family, color, ..
+ } => {
+ assert_eq!(
+ &**font_family, "Georgia",
+ "leader takes the run's family, not a hardcoded one"
+ );
+ assert_eq!(
+ *color,
+ RgbColor { r: 255, g: 0, b: 0 },
+ "leader takes the run's colour, not black"
+ );
+ }
+ _ => unreachable!("leader_command returns a Text command"),
+ }
+ }
+
+ #[test]
+ fn tab_leader_scales_with_the_run_font_size() {
+ // The old code sized the leader from the paragraph line height and
+ // capped it at 12pt, so a large run drew undersized leaders.
+ let frags = vec![
+ text_frag("a", 10.0),
+ Fragment::Tab {
+ line_height: Pt::new(24.0),
+ font: leader_font("Georgia", 24.0),
+ color: RgbColor::BLACK,
+ fitting_width: None,
+ },
+ text_frag("b", 10.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(200.0),
+ &dotted_stop_at(100.0),
+ Pt::new(28.0),
+ None,
+ );
+
+ match leader_command(&result) {
+ DrawCommand::Text { font_size, .. } => assert_eq!(
+ font_size.raw(),
+ 24.0,
+ "a 24pt run gets 24pt leader dots, not a 12pt cap"
+ ),
+ _ => unreachable!(),
+ }
+ }
+
+ #[test]
+ fn ptab_leader_inherits_the_run_font_and_colour() {
+ // Same rule on the §17.3.1.30 position-tab arm, which carries its
+ // leader on the fragment rather than on a tab stop.
+ let frags = vec![
+ text_frag("L", 10.0),
+ Fragment::PTab {
+ align: PTabAlignment::Right,
+ relative_to: PTabRelativeTo::Margin,
+ leader: crate::model::TabLeader::Dot,
+ line_height: Pt::new(12.0),
+ font: leader_font("Georgia", 18.0),
+ color: RgbColor { r: 0, g: 128, b: 0 },
+ },
+ text_frag("R", 30.0),
+ ];
+ let result = layout_paragraph(
+ &frags,
+ &body_constraints(200.0),
+ &ParagraphStyle::default(),
+ Pt::new(14.0),
+ None,
+ );
+
+ match leader_command(&result) {
+ DrawCommand::Text {
+ font_family,
+ font_size,
+ color,
+ ..
+ } => {
+ assert_eq!(&**font_family, "Georgia");
+ assert_eq!(font_size.raw(), 18.0);
+ assert_eq!(*color, RgbColor { r: 0, g: 128, b: 0 });
+ }
+ _ => unreachable!(),
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/paragraph/types.rs b/crates/liteparse-docx/src/render/layout/paragraph/types.rs
new file mode 100644
index 0000000..7a6c5b5
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/paragraph/types.rs
@@ -0,0 +1,230 @@
+//! Type definitions for paragraph layout.
+
+use crate::model::Alignment;
+
+use super::super::draw_command::DrawCommand;
+use super::super::fragment::Fragment;
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtSize;
+use crate::render::resolve::color::RgbColor;
+
+/// §17.3.1.38: a resolved tab stop for layout.
+#[derive(Clone, Debug)]
+pub struct TabStopDef {
+ /// Absolute position from paragraph left edge.
+ pub position: Pt,
+ /// §17.18.85 `ST_TabJc`: tab alignment (left, center, right, decimal).
+ pub alignment: crate::model::TabAlignment,
+ /// §17.18.86 `ST_TabTlc`: leader character (dot, hyphen, underscore, etc.).
+ pub leader: crate::model::TabLeader,
+}
+
+/// Configuration for paragraph layout.
+#[derive(Clone, Debug)]
+pub struct ParagraphStyle {
+ pub alignment: Alignment,
+ pub space_before: Pt,
+ pub space_after: Pt,
+ pub indent_left: Pt,
+ pub indent_right: Pt,
+ pub indent_first_line: Pt,
+ pub line_spacing: LineSpacingRule,
+ /// §20.1.2.1.18: the enclosing shape text body's `a:normAutofit` shrink.
+ /// [`ShapeAutoFit::NONE`](crate::render::layout::ShapeAutoFit::NONE) for
+ /// every paragraph outside one.
+ ///
+ /// Its `@lnSpcReduction` half is applied to the *resolved* line height, not
+ /// to `line_spacing` above; the reason is on
+ /// [`ShapeAutoFit::scale_line_height`](crate::render::layout::ShapeAutoFit::scale_line_height).
+ pub auto_fit: crate::render::layout::ShapeAutoFit,
+ /// §17.3.1.38: custom tab stops.
+ pub tabs: Vec<TabStopDef>,
+ /// §17.15.1.25: the default tab-stop interval, used when no custom tab stop
+ /// applies (from `w:settings/w:defaultTabStop`; spec default 720tw = 36pt).
+ pub default_tab_stop: Pt,
+ /// §17.3.2.20: the language in effect for this paragraph's own decisions —
+ /// today, only which character a §17.18.85 `decimal` stop aligns on.
+ ///
+ /// Resolved from the paragraph *mark*'s `w:rPr`, not from the runs inside
+ /// the paragraph: a decimal stop is a `w:pPr` property, and a zone whose
+ /// runs each declared their own `w:lang` would otherwise have no single
+ /// answer. See `build::convert::paragraph_locale`.
+ pub locale: crate::render::resolve::locale::Locale,
+ /// §17.3.1.19: this paragraph's PDF outline entry, when it is a heading.
+ ///
+ /// Carried on the style rather than derived at emission because the node ID
+ /// is assigned once, in document order, while the paragraph is built — see
+ /// [`OutlineHeading`](crate::render::layout::draw_command::OutlineHeading).
+ /// `None` for body text, and for every heading outside the document body
+ /// (headers, footers, notes), which are not positions in the document.
+ pub outline: Option<crate::render::layout::draw_command::OutlineHeading>,
+ /// Drop cap to render at the start of this paragraph.
+ pub drop_cap: Option<DropCapInfo>,
+ /// §17.3.1.24: paragraph borders.
+ pub borders: Option<ParagraphBorderStyle>,
+ /// §17.3.1.31: paragraph shading (background fill).
+ pub shading: Option<RgbColor>,
+ /// §17.3.1.15: keep this paragraph on the same page as the next.
+ pub keep_next: bool,
+ /// §17.3.1.14: keep all lines of this paragraph on one page where possible
+ /// (suppresses across-page splitting of the paragraph).
+ pub keep_lines: bool,
+ /// §17.3.1.44: when the paragraph *does* split, forbid a single line stranded
+ /// at the bottom (orphan) or top (widow) of a page. Word's default is on.
+ pub widow_control: bool,
+ /// §17.3.1.9: suppress spacing between paragraphs of the same style.
+ pub contextual_spacing: bool,
+ /// Style ID for contextual spacing comparison.
+ pub style_id: Option<crate::model::StyleId>,
+ /// Active floats for per-line width adjustment.
+ pub page_floats: Vec<super::super::float::ActiveFloat>,
+ /// Absolute y position of this paragraph on the page (for float overlap checks).
+ pub page_y: Pt,
+ /// Left margin x position (for float_adjustments computation).
+ pub page_x: Pt,
+ /// Total content width (for float_adjustments computation).
+ pub page_content_width: Pt,
+}
+
+/// Resolved paragraph border style for rendering.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ParagraphBorderStyle {
+ pub top: Option<BorderLine>,
+ pub bottom: Option<BorderLine>,
+ pub left: Option<BorderLine>,
+ pub right: Option<BorderLine>,
+}
+
+/// A single border line for rendering.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct BorderLine {
+ pub width: Pt,
+ pub color: RgbColor,
+ /// §17.3.1.24: space between border and text in points.
+ pub space: Pt,
+}
+
+/// Drop cap letter to float at the start of a paragraph.
+#[derive(Clone, Debug)]
+pub struct DropCapInfo {
+ /// The drop cap fragments (usually a single large letter).
+ pub fragments: Vec<Fragment>,
+ /// §17.3.1.11 @w:lines: number of body text lines the drop cap spans.
+ pub lines: u32,
+ /// Total width of the drop cap (measured).
+ pub width: Pt,
+ /// Total height of the drop cap (measured).
+ pub height: Pt,
+ /// Ascent of the drop cap font (for baseline positioning).
+ pub ascent: Pt,
+ /// §17.3.1.11 @w:hSpace: horizontal distance from surrounding text.
+ pub h_space: Pt,
+ /// §17.3.1.11: true = Margin mode (drop cap in margin), false = Drop mode (in text area).
+ pub margin_mode: bool,
+ /// Left indent of the drop cap paragraph (from its own style cascade).
+ pub indent: Pt,
+ /// Frame height from the drop cap paragraph's spacing (lineRule="exact").
+ pub frame_height: Option<Pt>,
+ /// §17.3.2.19: vertical baseline offset in points (negative = down).
+ pub position_offset: Pt,
+}
+
+impl ParagraphStyle {
+ /// Clone the style for layout, leaving `page_floats` empty.
+ ///
+ /// The caller always replaces `page_floats` with computed effective floats,
+ /// so cloning the (potentially large) source vec is wasted work.
+ pub fn clone_for_layout(&self) -> Self {
+ Self {
+ alignment: self.alignment,
+ space_before: self.space_before,
+ space_after: self.space_after,
+ indent_left: self.indent_left,
+ indent_right: self.indent_right,
+ indent_first_line: self.indent_first_line,
+ line_spacing: self.line_spacing,
+ auto_fit: self.auto_fit,
+ tabs: self.tabs.clone(),
+ default_tab_stop: self.default_tab_stop,
+ locale: self.locale,
+ outline: self.outline.clone(),
+ drop_cap: self.drop_cap.clone(),
+ borders: self.borders.clone(),
+ shading: self.shading,
+ keep_next: self.keep_next,
+ keep_lines: self.keep_lines,
+ widow_control: self.widow_control,
+ contextual_spacing: self.contextual_spacing,
+ style_id: self.style_id.clone(),
+ // Caller will replace these — skip cloning the vec.
+ page_floats: Vec::new(),
+ page_y: Pt::ZERO,
+ page_x: Pt::ZERO,
+ page_content_width: Pt::ZERO,
+ }
+ }
+}
+
+impl Default for ParagraphStyle {
+ fn default() -> Self {
+ Self {
+ alignment: Alignment::Start,
+ space_before: Pt::ZERO,
+ space_after: Pt::ZERO,
+ indent_left: Pt::ZERO,
+ indent_right: Pt::ZERO,
+ indent_first_line: Pt::ZERO,
+ auto_fit: crate::render::layout::ShapeAutoFit::NONE,
+ line_spacing: LineSpacingRule::Auto(1.0),
+ tabs: Vec::new(),
+ // §17.15.1.25: 720 twips = 36pt is the OOXML default interval.
+ default_tab_stop: Pt::new(36.0),
+ locale: crate::render::resolve::locale::Locale::English,
+ outline: None,
+ drop_cap: None,
+ borders: None,
+ shading: None,
+ keep_next: false,
+ keep_lines: false,
+ // §17.3.1.44: Word enables widow/orphan control by default.
+ widow_control: true,
+ contextual_spacing: false,
+ style_id: None,
+ page_floats: Vec::new(),
+ page_y: Pt::ZERO,
+ page_x: Pt::ZERO,
+ page_content_width: Pt::ZERO,
+ }
+ }
+}
+
+// Workaround for clippy: ParagraphStyle has many fields but they all map 1:1 to spec properties.
+// A builder pattern would add complexity without value here.
+
+/// Line spacing rules matching OOXML semantics.
+#[derive(Clone, Copy, Debug)]
+pub enum LineSpacingRule {
+ /// Proportional: multiplier on natural line height (1.0 = single, 1.5 = 1.5x, etc.)
+ Auto(f32),
+ /// Exact line height in points.
+ Exact(Pt),
+ /// Minimum line height in points.
+ AtLeast(Pt),
+}
+
+/// Result of laying out a paragraph.
+#[derive(Debug)]
+pub struct ParagraphLayout {
+ /// Draw commands positioned relative to the paragraph's top-left origin.
+ pub commands: Vec<DrawCommand>,
+ /// Total size consumed by this paragraph (including spacing).
+ pub size: PtSize,
+}
+
+/// Optional text measurement callback for accurate per-character splitting.
+pub type MeasureTextFn<'a> = Option<
+ &'a dyn Fn(
+ &str,
+ &super::super::fragment::FontProps,
+ ) -> (Pt, super::super::fragment::TextMetrics),
+>;
diff --git a/crates/liteparse-docx/src/render/layout/section/floating_table.rs b/crates/liteparse-docx/src/render/layout/section/floating_table.rs
new file mode 100644
index 0000000..7a29772
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/section/floating_table.rs
@@ -0,0 +1,630 @@
+//! §17.4.58 — page placement for a floating table that may span pages.
+//!
+//! When a `<w:tbl>` with `<w:tblpPr>` (a floating-table anchor) is taller
+//! than the available height on its anchor page, Word breaks it at row
+//! boundaries and continues the table on subsequent pages. The anchor's
+//! `tblpY` only positions the **first** slice; continuation slices start
+//! at the top of their pages' content area.
+//!
+//! This module owns the pure placement decision. Row splitting is handled
+//! upstream by [`crate::render::layout::table::layout_table_paginated`];
+//! we take its `Vec<TableSlice>` and assign each slice to a page slot.
+//!
+//! OOXML §17.4.58 specifies `tblpY` semantics for the anchor itself but
+//! does not formally describe overflow behavior. The continuation-at-top
+//! rule mirrors Microsoft Word's observable behavior and is the
+//! convention every consumer that handles overflow follows.
+//!
+//! Text wrapping (`<w:tblpPr>` floats register an [`ActiveFloat`]) is
+//! anchored to the **first** page only — text on continuation pages does
+//! not wrap, since the only content on those pages is the table itself.
+//! Encoded by the `Anchor`/`Continuation` enum split below.
+
+use crate::model::TableOverlap;
+use crate::render::dimension::Pt;
+use crate::render::layout::float::ActiveFloat;
+use crate::render::layout::table::TableSlice;
+
+/// §17.4.57 — outcome of resolving a floating table's requested
+/// anchor against prior floats on the same page.
+#[derive(Debug, PartialEq)]
+pub(super) enum FloatingTableAnchor {
+ /// The requested y is free of prior-float collision (or overlap
+ /// is permitted by `TableOverlap::Overlap`). Place the table at
+ /// this y on the current page.
+ OnCurrentPage(Pt),
+ /// `tblOverlap=Never` collision: the table was pushed below the
+ /// last conflicting float. `from`/`to` are kept for diagnostics.
+ Shifted { from: Pt, to: Pt },
+ /// A *collision-induced* shift pushed the table past `page_bottom`.
+ /// The caller must push a new page and re-resolve.
+ ///
+ /// Only ever returned when prior floats actually moved the anchor.
+ /// A table that overflows purely because it is taller than the body
+ /// is **not** a spillover — see [`resolve_floating_anchor`].
+ Spillover,
+}
+
+/// §17.4.57 — resolve a floating table's requested anchor y against
+/// prior `ActiveFloat`s registered for the current page.
+///
+/// - `overlap == Some(Never)`: iteratively push the anchor below any
+/// *floating table* whose y-range intersects `[anchor, anchor +
+/// height]`. If a shift happened *and* the shifted anchor would extend
+/// the table past `page_bottom`, return `Spillover`.
+/// - `overlap == Some(Overlap)` or `None` (the §17.4.57 default): the
+/// anchor is returned unchanged on the current page; overlap with
+/// prior floats is permitted.
+///
+/// `prior` is the page's whole float list, so it also holds image and
+/// shape floats. Those are skipped: §17.4.57 is defined between floating
+/// tables only, and a table is free to overlap a floating image
+/// ([`FloatSource::participates_in_table_overlap`]).
+///
+/// # Overflow is not spillover
+///
+/// `Spillover` is conditioned on `shifted_any`, and that condition is
+/// load-bearing rather than cosmetic. The caller answers `Spillover` by
+/// pushing a fresh page and calling back in; `push_new_page` clears the
+/// page's float list, so the retry sees `prior == []` and cannot shift.
+///
+/// Without the `shifted_any` guard, a table taller than the body area
+/// re-reports `Spillover` forever: `requested` collapses to the page
+/// top, and `page_top + height > page_bottom` holds on every page, so
+/// each iteration allocates one more `LayoutedPage` and retries. That
+/// is an unbounded loop — it was reachable from an ordinary document
+/// (a long table plus `<w:tblOverlap w:val="never"/>`) and ran until
+/// the OS killed the process.
+///
+/// A table that simply doesn't fit needs *pagination*, not relocation,
+/// so it is returned as `OnCurrentPage` and sliced at row boundaries by
+/// `layout_table_paginated_with_page_heights` — the same path the
+/// permitted-overlap case already takes. Pairing the guard with the
+/// cleared float list bounds the caller at one page push per table.
+pub(super) fn resolve_floating_anchor(
+ requested: Pt,
+ height: Pt,
+ overlap: Option<TableOverlap>,
+ prior: &[ActiveFloat],
+ page_bottom: Pt,
+) -> FloatingTableAnchor {
+ if !matches!(overlap, Some(TableOverlap::Never)) {
+ return FloatingTableAnchor::OnCurrentPage(requested);
+ }
+
+ let mut anchor = requested;
+ let mut shifted_any = false;
+ loop {
+ // Find the deepest `y_end` among floats whose range intersects
+ // [anchor, anchor + height]. One pass is enough only if floats
+ // are non-overlapping themselves; iterate to a fixed point.
+ let mut max_blocking_end: Option<Pt> = None;
+ for f in prior {
+ // §17.4.57 governs table-vs-table overlap only. `page_floats`
+ // also carries image and shape floats, which a floating table
+ // is free to overlap.
+ if !f.source.participates_in_table_overlap() {
+ continue;
+ }
+ let overlaps = anchor < f.page_y_end && anchor + height > f.page_y_start;
+ if overlaps {
+ let candidate = f.page_y_end;
+ max_blocking_end = Some(match max_blocking_end {
+ Some(prev) if prev >= candidate => prev,
+ _ => candidate,
+ });
+ }
+ }
+ match max_blocking_end {
+ None => break,
+ Some(new_anchor) => {
+ anchor = new_anchor;
+ shifted_any = true;
+ }
+ }
+ }
+
+ if !shifted_any {
+ // Nothing moved the anchor, so a fresh page would resolve to the
+ // same place. Overflow here is a pagination problem, not a
+ // placement one.
+ return FloatingTableAnchor::OnCurrentPage(anchor);
+ }
+
+ if anchor + height > page_bottom {
+ FloatingTableAnchor::Spillover
+ } else {
+ FloatingTableAnchor::Shifted {
+ from: requested,
+ to: anchor,
+ }
+ }
+}
+
+/// One page-slot in a floating table's multi-page placement plan. The
+/// enum distinguishes the two semantic roles a slice can play, so
+/// downstream code (text-wrap registration, debug logging) doesn't have
+/// to inspect the slice index.
+#[derive(Debug)]
+pub(super) enum FloatingTablePagePlacement {
+ /// First slice — drawn at the resolved `tblpY` anchor on the
+ /// anchoring page. Registers as an [`ActiveFloat`] so subsequent
+ /// body text wraps around it.
+ Anchor { y_start: Pt, slice: TableSlice },
+ /// Subsequent slice — drawn at the top of the next page's content
+ /// area. Does not register a float (no body content interleaves on
+ /// the continuation page).
+ Continuation { y_start: Pt, slice: TableSlice },
+}
+
+impl FloatingTablePagePlacement {
+ /// Page-local y where this slice draws. Test helper; the layout
+ /// path destructures the variant directly instead of going through
+ /// this accessor.
+ #[cfg(test)]
+ pub(super) fn y_start(&self) -> Pt {
+ match self {
+ Self::Anchor { y_start, .. } | Self::Continuation { y_start, .. } => *y_start,
+ }
+ }
+
+ /// Borrow the slice. Test helper for the planner's pass-through
+ /// invariants; the layout path destructures the variant.
+ #[cfg(test)]
+ pub(super) fn slice(&self) -> &TableSlice {
+ match self {
+ Self::Anchor { slice, .. } | Self::Continuation { slice, .. } => slice,
+ }
+ }
+}
+
+/// Multi-page placement plan for a floating table. Ordered: index 0 is
+/// the anchor page, indices 1..n are continuation pages.
+///
+/// Invariant: if `pages` is non-empty, `pages[0]` is always `Anchor`
+/// and every subsequent entry is `Continuation`. Constructed only via
+/// [`plan_floating_table_pages_with_page_tops`], which preserves this.
+#[derive(Debug)]
+pub(super) struct FloatingTablePlan {
+ pub(super) pages: Vec<FloatingTablePagePlacement>,
+}
+
+/// Map a sequence of paginated table slices to page placements.
+///
+/// - The first slice is wrapped in [`FloatingTablePagePlacement::Anchor`]
+/// at `anchor_y` (the resolved `tblpY`).
+/// - Every subsequent slice is wrapped in
+/// [`FloatingTablePagePlacement::Continuation`] at `continuation_y`
+/// (the top of the content area on continuation pages).
+/// - An empty input yields an empty plan (no pages).
+///
+/// This function is pure — no I/O, no global state, no measurement.
+/// Row-splitting and slice production are handled by
+/// `layout_table_paginated`; this function only assigns slices to
+/// page slots.
+pub(super) fn plan_floating_table_pages_with_page_tops(
+ slices: Vec<TableSlice>,
+ anchor_y: Pt,
+ mut page_top_for_index: impl FnMut(usize) -> Pt,
+) -> FloatingTablePlan {
+ let pages = slices
+ .into_iter()
+ .enumerate()
+ .map(|(idx, slice)| {
+ if idx == 0 {
+ FloatingTablePagePlacement::Anchor {
+ y_start: anchor_y,
+ slice,
+ }
+ } else {
+ FloatingTablePagePlacement::Continuation {
+ y_start: page_top_for_index(idx),
+ slice,
+ }
+ }
+ })
+ .collect();
+ FloatingTablePlan { pages }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::geometry::PtSize;
+ use crate::render::layout::float::{FloatSource, WrapTextSide};
+
+ fn slice(height: f32) -> TableSlice {
+ TableSlice {
+ commands: Vec::new(),
+ size: PtSize::new(Pt::new(100.0), Pt::new(height)),
+ }
+ }
+
+ fn float_at_source(y_start: f32, y_end: f32, source: FloatSource) -> ActiveFloat {
+ ActiveFloat {
+ page_x: Pt::ZERO,
+ page_y_start: Pt::new(y_start),
+ page_y_end: Pt::new(y_end),
+ width: Pt::new(100.0),
+ source,
+ wrap_text: WrapTextSide::BothSides,
+ }
+ }
+
+ /// A prior *table* float — the only kind §17.4.57 governs.
+ fn float_at(y_start: f32, y_end: f32) -> ActiveFloat {
+ float_at_source(y_start, y_end, FloatSource::Table { owner_block_idx: 0 })
+ }
+
+ /// Single-slice case (table fits on its anchor page). Placement is
+ /// a single `Anchor` at `anchor_y`.
+ #[test]
+ fn plan_single_slice_is_one_anchor_placement() {
+ let plan =
+ plan_floating_table_pages_with_page_tops(vec![slice(50.0)], Pt::new(100.0), |_| {
+ Pt::new(40.0)
+ });
+ assert_eq!(plan.pages.len(), 1);
+ assert!(matches!(
+ plan.pages[0],
+ FloatingTablePagePlacement::Anchor { .. }
+ ));
+ assert_eq!(plan.pages[0].y_start().raw(), 100.0);
+ }
+
+ /// Two-slice case (table overflows once). First at anchor, second
+ /// at continuation y.
+ #[test]
+ fn plan_two_slices_anchor_then_continuation() {
+ let plan = plan_floating_table_pages_with_page_tops(
+ vec![slice(700.0), slice(100.0)],
+ Pt::new(100.0),
+ |_| Pt::new(40.0),
+ );
+ assert_eq!(plan.pages.len(), 2);
+ assert!(matches!(
+ plan.pages[0],
+ FloatingTablePagePlacement::Anchor { .. }
+ ));
+ assert!(matches!(
+ plan.pages[1],
+ FloatingTablePagePlacement::Continuation { .. }
+ ));
+ assert_eq!(plan.pages[0].y_start().raw(), 100.0);
+ assert_eq!(plan.pages[1].y_start().raw(), 40.0);
+ }
+
+ /// N-slice case (n ≥ 3). Only the first slice is the Anchor;
+ /// every subsequent slice is a Continuation at `continuation_y`.
+ /// This pins the "no second anchor page" rule.
+ #[test]
+ fn plan_n_slices_only_first_is_anchor_page() {
+ let plan = plan_floating_table_pages_with_page_tops(
+ vec![slice(700.0), slice(700.0), slice(100.0)],
+ Pt::new(150.0),
+ |_| Pt::new(40.0),
+ );
+ assert_eq!(plan.pages.len(), 3);
+ let anchor_count = plan
+ .pages
+ .iter()
+ .filter(|p| matches!(p, FloatingTablePagePlacement::Anchor { .. }))
+ .count();
+ assert_eq!(anchor_count, 1, "at most one Anchor in a plan");
+ assert_eq!(plan.pages[0].y_start().raw(), 150.0);
+ for p in &plan.pages[1..] {
+ assert_eq!(p.y_start().raw(), 40.0);
+ assert!(matches!(p, FloatingTablePagePlacement::Continuation { .. }));
+ }
+ }
+
+ #[test]
+ fn continuation_slices_use_each_page_top_boundary() {
+ let plan = plan_floating_table_pages_with_page_tops(
+ vec![slice(50.0), slice(50.0), slice(50.0)],
+ Pt::new(100.0),
+ |page_index| match page_index {
+ 1 => Pt::new(40.0),
+ _ => Pt::new(60.0),
+ },
+ );
+
+ assert_eq!(plan.pages[0].y_start(), Pt::new(100.0));
+ assert_eq!(plan.pages[1].y_start(), Pt::new(40.0));
+ assert_eq!(plan.pages[2].y_start(), Pt::new(60.0));
+ }
+
+ /// Empty slice list → empty plan. Edge case: never happens via
+ /// `layout_table_paginated` (which returns at least one slice for
+ /// non-empty input), but guarded for safety.
+ #[test]
+ fn plan_empty_slices_returns_empty_plan() {
+ let plan =
+ plan_floating_table_pages_with_page_tops(Vec::new(), Pt::new(100.0), |_| Pt::new(40.0));
+ assert!(plan.pages.is_empty());
+ }
+
+ /// Slice contents (commands, size) are passed through intact —
+ /// the planner only assigns placement, never modifies the slice.
+ #[test]
+ fn plan_preserves_slice_size_through_placement() {
+ let plan = plan_floating_table_pages_with_page_tops(
+ vec![slice(123.4), slice(56.7)],
+ Pt::new(100.0),
+ |_| Pt::new(40.0),
+ );
+ assert_eq!(plan.pages[0].slice().size.height.raw(), 123.4);
+ assert_eq!(plan.pages[1].slice().size.height.raw(), 56.7);
+ }
+
+ // ── §17.4.57 — anchor resolution against prior floats ──────────────
+
+ /// Default behavior (`overlap == None`, the §17.4.57 default
+ /// `Overlap`): the anchor is returned unchanged even when prior
+ /// floats would intersect.
+ #[test]
+ fn anchor_accepts_overlap_when_overlap_permitted() {
+ let prior = vec![float_at(80.0, 130.0)];
+ let resolved =
+ resolve_floating_anchor(Pt::new(100.0), Pt::new(50.0), None, &prior, Pt::new(700.0));
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(100.0)));
+
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Overlap),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(100.0)));
+ }
+
+ /// No prior floats → no shifting, no spillover, returns
+ /// `OnCurrentPage` even with `Never`.
+ #[test]
+ fn anchor_no_priors_returns_requested_y() {
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &[],
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(100.0)));
+ }
+
+ /// `Never` + overlap with one float: shift the anchor to the
+ /// float's `y_end`. Spec §17.4.57 — two tables anchored on the
+ /// same page that both forbid overlap must be repositioned to
+ /// avoid drawing over each other.
+ #[test]
+ fn anchor_shifts_below_overlapping_float() {
+ let prior = vec![float_at(80.0, 130.0)];
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(
+ resolved,
+ FloatingTableAnchor::Shifted {
+ from: Pt::new(100.0),
+ to: Pt::new(130.0),
+ }
+ );
+ }
+
+ /// `Never` + anchor below all priors: no shift, returns
+ /// `OnCurrentPage`.
+ #[test]
+ fn anchor_below_priors_is_accepted_unchanged() {
+ let prior = vec![float_at(80.0, 130.0)];
+ let resolved = resolve_floating_anchor(
+ Pt::new(200.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(200.0)));
+ }
+
+ /// `Never` + multiple overlapping priors: anchor shifts past the
+ /// deepest blocking float, iterating until no overlap remains.
+ /// Tests the fixed-point iteration in the resolver.
+ #[test]
+ fn anchor_shifts_past_chain_of_floats() {
+ let prior = vec![
+ float_at(80.0, 130.0),
+ float_at(125.0, 180.0), // overlaps both the prior float and the shifted anchor
+ ];
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ // First iteration: anchor 100..150 collides with both floats.
+ // Shift to max y_end = 180 (the second float). Re-check from
+ // 180: no remaining collision.
+ assert_eq!(
+ resolved,
+ FloatingTableAnchor::Shifted {
+ from: Pt::new(100.0),
+ to: Pt::new(180.0),
+ }
+ );
+ }
+
+ /// `Never` + shifted anchor + height extends past page bottom →
+ /// `Spillover`. The caller pushes a new page and re-anchors.
+ #[test]
+ fn anchor_spillover_when_shift_exceeds_page_bottom() {
+ let prior = vec![float_at(80.0, 680.0)]; // huge prior float
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0), // 680 + 50 = 730 > 700
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::Spillover);
+ }
+
+ /// A table taller than the page body, with nothing to collide
+ /// with, is **not** a spillover.
+ ///
+ /// This is the termination guard. The caller answers `Spillover`
+ /// by pushing a fresh page and re-resolving; a fresh page has an
+ /// empty float list, so it would resolve to exactly this call and
+ /// report `Spillover` again — one `LayoutedPage` allocated per
+ /// iteration, forever, until the process is OOM-killed. Overflow
+ /// with no shift means "paginate me", not "move me".
+ #[test]
+ fn anchor_taller_than_page_is_not_spillover() {
+ let resolved = resolve_floating_anchor(
+ Pt::new(40.0),
+ Pt::new(2000.0), // far taller than the 700pt body
+ Some(TableOverlap::Never),
+ &[],
+ Pt::new(700.0),
+ );
+ assert_eq!(
+ resolved,
+ FloatingTableAnchor::OnCurrentPage(Pt::new(40.0)),
+ "overflow without a collision-induced shift must not spill"
+ );
+ }
+
+ /// Same guard, but with prior floats present that simply don't
+ /// block the anchor. `shifted_any` is still false, so the presence
+ /// of floats must not turn overflow into a spillover.
+ #[test]
+ fn anchor_taller_than_page_with_non_blocking_priors_is_not_spillover() {
+ // Float sits entirely above the requested anchor.
+ let prior = vec![float_at(10.0, 30.0)];
+ let resolved = resolve_floating_anchor(
+ Pt::new(40.0),
+ Pt::new(2000.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(40.0)));
+ }
+
+ /// The caller's retry is bounded: whatever spills on a populated
+ /// page resolves on the next one, because `push_new_page` clears
+ /// the float list. Re-resolving a spilled table against `&[]` must
+ /// therefore always terminate the loop — even when the table is
+ /// too tall for the fresh page too.
+ #[test]
+ fn spillover_retry_on_empty_page_always_terminates() {
+ let prior = vec![float_at(80.0, 680.0)];
+ let first = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(2000.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(first, FloatingTableAnchor::Spillover);
+
+ // What the caller does next: fresh page, empty float list,
+ // anchor collapsed to the page top.
+ let retry = resolve_floating_anchor(
+ Pt::new(40.0),
+ Pt::new(2000.0),
+ Some(TableOverlap::Never),
+ &[],
+ Pt::new(700.0),
+ );
+ assert!(
+ !matches!(retry, FloatingTableAnchor::Spillover),
+ "a second spillover would loop the caller forever"
+ );
+ }
+
+ /// §17.4.57 governs table-vs-table overlap only. Image and shape
+ /// floats sit in the same `page_floats` list, but a floating table
+ /// is free to overlap them, so they must not move the anchor.
+ #[test]
+ fn image_and_shape_floats_do_not_shift_the_anchor() {
+ for source in [FloatSource::Image, FloatSource::Shape] {
+ // Squarely overlapping the requested 100..150 band.
+ let prior = vec![float_at_source(80.0, 130.0, source)];
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(
+ resolved,
+ FloatingTableAnchor::OnCurrentPage(Pt::new(100.0)),
+ "{source:?} is not a floating table; tblOverlap must ignore it"
+ );
+ }
+ }
+
+ /// The sharp case: a table float and a *deeper* image float both
+ /// overlap. The anchor must land past the table only. Taking the
+ /// deepest of all floats would overshoot to 400.
+ #[test]
+ fn mixed_floats_shift_past_the_table_and_ignore_the_image() {
+ let prior = vec![
+ float_at(80.0, 130.0),
+ float_at_source(90.0, 400.0, FloatSource::Image),
+ ];
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(
+ resolved,
+ FloatingTableAnchor::Shifted {
+ from: Pt::new(100.0),
+ to: Pt::new(130.0),
+ },
+ "shift past the table's y_end (130), not the image's (400)"
+ );
+ }
+
+ /// An image float alone can no longer produce `Spillover`, since it
+ /// cannot shift the anchor in the first place.
+ #[test]
+ fn image_float_cannot_cause_spillover() {
+ let prior = vec![float_at_source(80.0, 680.0, FloatSource::Image)];
+ let resolved = resolve_floating_anchor(
+ Pt::new(100.0),
+ Pt::new(50.0), // 680 + 50 = 730 > 700 if the image counted
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(100.0)));
+ }
+
+ /// Edge: anchor at the exact `y_end` of a float is **not** an
+ /// overlap (touching edges are allowed). Returns `OnCurrentPage`
+ /// unchanged.
+ #[test]
+ fn anchor_at_prior_y_end_is_not_overlap() {
+ let prior = vec![float_at(80.0, 130.0)];
+ let resolved = resolve_floating_anchor(
+ Pt::new(130.0),
+ Pt::new(50.0),
+ Some(TableOverlap::Never),
+ &prior,
+ Pt::new(700.0),
+ );
+ assert_eq!(resolved, FloatingTableAnchor::OnCurrentPage(Pt::new(130.0)));
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/section/helpers.rs b/crates/liteparse-docx/src/render/layout/section/helpers.rs
new file mode 100644
index 0000000..0e57606
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/section/helpers.rs
@@ -0,0 +1,245 @@
+//! Private helper functions for section layout.
+
+use super::super::draw_command::{DrawCommand, LayoutedPage};
+use super::super::fragment::Fragment;
+use super::super::page::PageConfig;
+use super::super::paragraph::{ParagraphStyle, layout_paragraph};
+use super::{FOOTNOTE_SEPARATOR_GAP, FOOTNOTE_SEPARATOR_LINE_WIDTH, FOOTNOTE_SEPARATOR_RATIO};
+use crate::render::dimension::Pt;
+
+/// Split a fragment slice at break markers of a given kind.
+/// Returns a vec of slices; the break fragments themselves are excluded.
+fn split_at_breaks(fragments: &[Fragment], is_break: fn(&Fragment) -> bool) -> Vec<&[Fragment]> {
+ let has_break = fragments.iter().any(is_break);
+ if !has_break {
+ return vec![fragments];
+ }
+ let mut chunks = Vec::new();
+ let mut start = 0;
+ for (i, frag) in fragments.iter().enumerate() {
+ if is_break(frag) {
+ chunks.push(&fragments[start..i]);
+ start = i + 1;
+ }
+ }
+ chunks.push(&fragments[start..]);
+ chunks
+}
+
+/// Split a fragment slice at `Fragment::ColumnBreak` markers.
+/// Returns a vec of slices; the column break fragments themselves are excluded.
+pub(super) fn split_at_column_breaks(fragments: &[Fragment]) -> Vec<&[Fragment]> {
+ split_at_breaks(fragments, |f| matches!(f, Fragment::ColumnBreak))
+}
+
+/// §17.3.3.1: split a fragment slice at `Fragment::PageBreak` markers.
+/// Returns a vec of slices; the page break fragments themselves are excluded.
+pub(super) fn split_at_page_breaks(fragments: &[Fragment]) -> Vec<&[Fragment]> {
+ split_at_breaks(fragments, Fragment::is_page_break)
+}
+
+pub(super) fn render_page_footnotes(
+ page: &mut LayoutedPage,
+ config: &PageConfig,
+ footnotes: &[(&[Fragment], &ParagraphStyle)],
+ default_line_height: Pt,
+ measure_text: super::super::paragraph::MeasureTextFn<'_>,
+ separator_indent: Pt,
+ page_bottom: Pt,
+) {
+ let content_width = config.content_width();
+ let constraints = super::super::BoxConstraints::tight_width(content_width, Pt::INFINITY);
+ // Layout all footnotes to compute total height.
+ let mut footnote_layouts = Vec::new();
+ let mut total_height = FOOTNOTE_SEPARATOR_GAP; // separator line + gap above first note
+ for (frags, style) in footnotes {
+ let para = layout_paragraph(
+ frags,
+ &constraints,
+ style,
+ default_line_height,
+ measure_text,
+ );
+ total_height += para.size.height;
+ footnote_layouts.push(para);
+ }
+
+ let footnote_top = page_bottom - total_height;
+
+ // §17.11.23: separator line positioned per default paragraph indent.
+ let sep_x = config.margins.left + separator_indent;
+ let sep_width = content_width * FOOTNOTE_SEPARATOR_RATIO;
+ page.commands.push(DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ crate::render::geometry::PtOffset::new(sep_x, footnote_top),
+ crate::render::geometry::PtOffset::new(sep_x + sep_width, footnote_top),
+ ),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ width: FOOTNOTE_SEPARATOR_LINE_WIDTH,
+ });
+
+ // Render footnote paragraphs.
+ let mut cursor_y = footnote_top + FOOTNOTE_SEPARATOR_GAP;
+ for para in footnote_layouts {
+ for mut cmd in para.commands {
+ cmd.shift_y(cursor_y);
+ cmd.shift_x(config.margins.left);
+ page.commands.push(cmd);
+ }
+ cursor_y += para.size.height;
+ }
+}
+
+/// §17.4.28: compute the table's x offset based on alignment and indent.
+pub(super) fn table_x_offset(
+ alignment: Option<crate::model::Alignment>,
+ indent: Pt,
+ table_width: Pt,
+ content_width: Pt,
+ margin_left: Pt,
+) -> Pt {
+ use crate::model::Alignment;
+ match alignment {
+ Some(Alignment::Center) => margin_left + (content_width - table_width) * 0.5,
+ Some(Alignment::End) => margin_left + content_width - table_width,
+ _ => margin_left + indent,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::Alignment;
+
+ fn page_break() -> Fragment {
+ Fragment::PageBreak {
+ line_height: Pt::ZERO,
+ }
+ }
+
+ /// A distinguishable non-break fragment.
+ fn item(text: &str) -> Fragment {
+ Fragment::Bookmark { name: text.into() }
+ }
+
+ fn names(chunks: &[&[Fragment]]) -> Vec<Vec<String>> {
+ chunks
+ .iter()
+ .map(|c| {
+ c.iter()
+ .map(|f| match f {
+ Fragment::Bookmark { name, .. } => name.to_string(),
+ _ => "?".to_string(),
+ })
+ .collect()
+ })
+ .collect()
+ }
+
+ // ── §17.3.3.1 break chunking ─────────────────────────────────────────
+
+ #[test]
+ fn no_break_yields_the_whole_slice_as_one_chunk() {
+ let frags = vec![item("a"), item("b")];
+ assert_eq!(names(&split_at_page_breaks(&frags)), vec![vec!["a", "b"]]);
+ }
+
+ #[test]
+ fn a_break_splits_and_is_itself_excluded() {
+ let frags = vec![item("a"), page_break(), item("b")];
+ assert_eq!(
+ names(&split_at_page_breaks(&frags)),
+ vec![vec!["a"], vec!["b"]],
+ "the break fragment is dropped, not carried into either chunk"
+ );
+ }
+
+ /// A leading break must produce an *empty* first chunk, not be swallowed:
+ /// that empty chunk is what makes `<w:br type="page"/>` at the start of a
+ /// paragraph break *before* its content. `layout.rs` skips empty chunks
+ /// after acting on the break, so dropping it here would lose the break.
+ #[test]
+ fn a_leading_break_yields_an_empty_first_chunk() {
+ let frags = vec![page_break(), item("a")];
+ let chunks = split_at_page_breaks(&frags);
+ assert_eq!(chunks.len(), 2);
+ assert!(chunks[0].is_empty(), "empty chunk carries the break");
+ assert_eq!(names(&chunks)[1], vec!["a"]);
+ }
+
+ #[test]
+ fn a_trailing_break_yields_an_empty_last_chunk() {
+ let frags = vec![item("a"), page_break()];
+ let chunks = split_at_page_breaks(&frags);
+ assert_eq!(chunks.len(), 2);
+ assert_eq!(names(&chunks)[0], vec!["a"]);
+ assert!(chunks[1].is_empty());
+ }
+
+ /// Consecutive breaks each produce their own chunk boundary, so N breaks
+ /// yield N+1 chunks however they cluster.
+ #[test]
+ fn consecutive_breaks_each_yield_a_boundary() {
+ let frags = vec![item("a"), page_break(), page_break(), item("b")];
+ let chunks = split_at_page_breaks(&frags);
+ assert_eq!(chunks.len(), 3, "two breaks → three chunks");
+ assert!(chunks[1].is_empty(), "the gap between the two breaks");
+ }
+
+ /// Column and page breaks are split independently — a column break is not
+ /// a page boundary and vice versa.
+ #[test]
+ fn column_and_page_breaks_are_split_independently() {
+ let frags = vec![item("a"), Fragment::ColumnBreak, item("b")];
+ assert_eq!(
+ split_at_page_breaks(&frags).len(),
+ 1,
+ "a column break is not a page boundary"
+ );
+ assert_eq!(
+ names(&split_at_column_breaks(&frags)),
+ vec![vec!["a"], vec!["b"]]
+ );
+ }
+
+ // ── §17.4.28 table alignment ─────────────────────────────────────────
+
+ #[test]
+ fn table_x_offset_centers_and_right_aligns_within_the_content_area() {
+ let (indent, width, content, margin) =
+ (Pt::ZERO, Pt::new(100.0), Pt::new(400.0), Pt::new(72.0));
+ assert_eq!(
+ table_x_offset(Some(Alignment::Center), indent, width, content, margin).raw(),
+ 72.0 + 150.0,
+ );
+ assert_eq!(
+ table_x_offset(Some(Alignment::End), indent, width, content, margin).raw(),
+ 72.0 + 300.0,
+ );
+ }
+
+ #[test]
+ fn table_x_offset_applies_indent_when_left_aligned() {
+ let (width, content, margin) = (Pt::new(100.0), Pt::new(400.0), Pt::new(72.0));
+ for alignment in [None, Some(Alignment::Start), Some(Alignment::Both)] {
+ assert_eq!(
+ table_x_offset(alignment, Pt::new(20.0), width, content, margin).raw(),
+ 92.0,
+ "{alignment:?} places at margin + indent"
+ );
+ }
+ }
+
+ /// §17.4.51: `tblInd` is deliberately ignored for centered and right-
+ /// aligned tables — they are positioned as a unit within the content area,
+ /// matching Word. Pinned because nothing in the signature says so.
+ #[test]
+ fn table_x_offset_ignores_indent_when_centered_or_right_aligned() {
+ let (width, content, margin) = (Pt::new(100.0), Pt::new(400.0), Pt::new(72.0));
+ for alignment in [Alignment::Center, Alignment::End] {
+ let without = table_x_offset(Some(alignment), Pt::ZERO, width, content, margin);
+ let with = table_x_offset(Some(alignment), Pt::new(50.0), width, content, margin);
+ assert_eq!(without, with, "{alignment:?} ignores tblInd");
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/section/layout.rs b/crates/liteparse-docx/src/render/layout/section/layout.rs
new file mode 100644
index 0000000..7cd0b14
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/section/layout.rs
@@ -0,0 +1,2494 @@
+//! Core section layout — the `layout_section()` function and its private state types.
+
+use super::super::BoxConstraints;
+use super::super::draw_command::{DrawCommand, LayoutedPage};
+use super::super::float;
+use super::super::fragment::Fragment;
+use super::super::header_footer::{HeaderFooterClearance, PageBodyBounds};
+use super::super::page::PageConfig;
+use super::super::paragraph::{
+ ParagraphBorderStyle, ParagraphStyle, layout_paragraph, place_paragraph,
+};
+use super::super::table::{
+ TablePaginationHeights, layout_table, layout_table_paginated_with_page_heights,
+ measure_leading_table_group_height,
+};
+use super::FLOAT_DEDUP_EPSILON_PT;
+use super::FOOTNOTE_SEPARATOR_GAP;
+use super::floating_table::{
+ FloatingTableAnchor, FloatingTablePagePlacement, plan_floating_table_pages_with_page_tops,
+ resolve_floating_anchor,
+};
+use super::helpers::{
+ render_page_footnotes, split_at_column_breaks, split_at_page_breaks, table_x_offset,
+};
+use super::types::{
+ ContinuationState, FloatingImage, FloatingImageY, FloatingShape, LayoutBlock, PageParity,
+ WrapMode,
+};
+use crate::model::StyleId;
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtRect;
+
+// ── Layout context and mutable page state ────────────────────────────────────
+
+/// Read-only context passed to every section-layout helper.
+/// Bundles the parameters that are constant for the lifetime of a `layout_section` call.
+struct LayoutCtx<'cx> {
+ config: &'cx PageConfig,
+ clearance: &'cx HeaderFooterClearance,
+ measure_text: super::super::paragraph::MeasureTextFn<'cx>,
+ separator_indent: Pt,
+ default_line_height: Pt,
+}
+
+impl LayoutCtx<'_> {
+ fn page_bounds(&self, section_page_index: usize) -> PageBodyBounds {
+ self.clearance.for_page(section_page_index)
+ }
+}
+
+/// All mutable paging state threaded through `layout_section`.
+/// Extracted from the function to make ownership and page-break resets explicit.
+struct PageLayoutState<'doc> {
+ /// Fully laid-out pages emitted so far.
+ pages: Vec<LayoutedPage>,
+ /// The page currently being assembled.
+ current_page: LayoutedPage,
+ /// Current vertical cursor position on the page.
+ cursor_y: Pt,
+ /// 0-based physical page index within the current section.
+ page_index: usize,
+ /// §17.10.6: logical number of this section's first page, with
+ /// `w:pgNumType/@start` applied. With `page_index` it gives the current
+ /// page's logical number, and so the §20.4.3.1 parity an `inside`/
+ /// `outside` float mirrors on.
+ logical_page_base: usize,
+ /// Effective top boundary for the selected header slot on this page.
+ page_top: Pt,
+ /// §17.6.4: current column index (0-based).
+ current_col: usize,
+ /// §17.6.4: y at which columns start on the current page.
+ column_top: Pt,
+ /// Effective bottom boundary — reduced as footnotes are reserved.
+ bottom: Pt,
+ /// Footnotes accumulated for the current page.
+ page_footnotes: Vec<(
+ &'doc [super::super::fragment::Fragment],
+ &'doc ParagraphStyle,
+ )>,
+ /// §17.3.1.33: true until the structural first content block is placed.
+ first_on_section_page: bool,
+ /// §17.3.1.9: space_after of the previous paragraph for spacing collapse.
+ prev_space_after: Pt,
+ /// §17.3.1.9: style_id of the previous paragraph for contextual spacing.
+ prev_style_id: Option<StyleId>,
+ /// §17.3.1.24: borders of the previous paragraph for border grouping.
+ prev_borders: Option<ParagraphBorderStyle>,
+ /// Active floats on the current page (text wraps around these).
+ page_floats: Vec<float::ActiveFloat>,
+ /// Forward-scanned absolute floats from future paragraphs on this page.
+ current_page_abs_floats: Vec<float::ActiveFloat>,
+ /// True when `current_page_abs_floats` needs rebuilding (e.g. after a page break).
+ abs_floats_dirty: bool,
+ /// Index of the first block on the current page (for forward scanning).
+ page_start_block: usize,
+ /// §17.4.58: y-start of the most recent paragraph (floating-table anchor).
+ last_para_start_y: Pt,
+ /// §17.4.38: style_id of the previous table for adjacent border collapse.
+ prev_table_style_id: Option<StyleId>,
+ /// §17.3.3.1: an inline page break at the end of a paragraph defers the
+ /// page break to the start of the next block.
+ pending_page_break: bool,
+}
+
+impl<'doc> PageLayoutState<'doc> {
+ fn new(
+ config: &PageConfig,
+ continuation: Option<ContinuationState>,
+ bounds: PageBodyBounds,
+ logical_page_base: usize,
+ ) -> Self {
+ let (current_page, cursor_y) = match continuation {
+ Some(c) => (c.page, c.cursor_y),
+ None => (LayoutedPage::new(config.page_size), bounds.top),
+ };
+ PageLayoutState {
+ pages: Vec::new(),
+ column_top: cursor_y,
+ last_para_start_y: cursor_y,
+ current_page,
+ cursor_y,
+ page_index: 0,
+ logical_page_base,
+ page_top: bounds.top,
+ current_col: 0,
+ bottom: bounds.bottom,
+ page_footnotes: Vec::new(),
+ first_on_section_page: true,
+ prev_space_after: Pt::ZERO,
+ prev_style_id: None,
+ prev_borders: None,
+ page_floats: Vec::new(),
+ current_page_abs_floats: Vec::new(),
+ abs_floats_dirty: true,
+ page_start_block: 0,
+ prev_table_style_id: None,
+ pending_page_break: false,
+ }
+ }
+
+ /// Render accumulated footnotes onto the current page and clear the list.
+ /// §20.4.3.1: parity of the page currently being assembled.
+ fn parity(&self) -> PageParity {
+ PageParity::of_page(self.logical_page_base + self.page_index)
+ }
+
+ fn flush_footnotes(&mut self, ctx: &LayoutCtx<'_>) {
+ if !self.page_footnotes.is_empty() {
+ render_page_footnotes(
+ &mut self.current_page,
+ ctx.config,
+ &self.page_footnotes,
+ ctx.default_line_height,
+ ctx.measure_text,
+ ctx.separator_indent,
+ ctx.page_bounds(self.page_index).bottom,
+ );
+ self.page_footnotes.clear();
+ }
+ }
+
+ /// Commit the current page and start a fresh one, resetting all per-page state.
+ /// Callers that also need `prev_space_after = Pt::ZERO` must set that separately.
+ fn push_new_page(&mut self, block_idx: usize, ctx: &LayoutCtx<'_>) {
+ self.flush_footnotes(ctx);
+ self.pages.push(std::mem::replace(
+ &mut self.current_page,
+ LayoutedPage::new(ctx.config.page_size),
+ ));
+ self.page_index += 1;
+ let bounds = ctx.page_bounds(self.page_index);
+ self.page_top = bounds.top;
+ self.cursor_y = bounds.top;
+ self.column_top = bounds.top;
+ self.current_col = 0;
+ self.bottom = bounds.bottom;
+ self.page_start_block = block_idx;
+ self.abs_floats_dirty = true;
+ self.page_floats.clear();
+ }
+
+ /// Flush any remaining footnotes, push the last page, and return all pages.
+ fn finalize(mut self, ctx: &LayoutCtx<'_>) -> Vec<LayoutedPage> {
+ self.flush_footnotes(ctx);
+ self.pages.push(self.current_page);
+ self.pages
+ }
+
+ /// The floats affecting text at the current cursor on the current
+ /// page/column: registered page floats (§20.4.2) plus forward-scanned
+ /// absolute floats from upcoming blocks on this page (rebuilt once per page
+ /// while `abs_floats_dirty`), advancing the cursor past any full-width float
+ /// that blocks all text (§17.4.56). Shared by the main block loop and the
+ /// across-page split re-fit (§4) so a continuation wraps around whatever
+ /// floats live on *its* page, not the paragraph's starting page.
+ fn effective_floats_at_cursor(
+ &mut self,
+ blocks: &[LayoutBlock],
+ relocated_absolute_float_blocks: &std::collections::HashSet<usize>,
+ num_cols: usize,
+ space_before: Pt,
+ col_width: Pt,
+ ) -> Vec<float::ActiveFloat> {
+ let parity = self.parity();
+ // Forward-scan absolute floats from upcoming paragraphs on the current
+ // page. Only rescan when the page changes. The scan tracks inline
+ // column/page boundaries (`scan_inline_page_boundary`) so a float past
+ // an in-paragraph break isn't attributed to this page, and skips blocks
+ // whose absolute float has been relocated to a later page (#86's
+ // relocation replay), so wrapped text on the replayed page ignores it.
+ if self.abs_floats_dirty {
+ self.current_page_abs_floats.clear();
+ let mut scan_col = self.current_col;
+ for (fi_idx, future_block) in blocks[self.page_start_block..].iter().enumerate() {
+ let future_block_idx = self.page_start_block + fi_idx;
+ if relocated_absolute_float_blocks.contains(&future_block_idx) {
+ if fi_idx == 0 {
+ continue;
+ }
+ break;
+ }
+ if let LayoutBlock::Paragraph {
+ floating_images: fi_list,
+ page_break_before,
+ fragments,
+ ..
+ } = future_block
+ {
+ // Stop scanning at the next explicit page break (skip the
+ // first block — it may have triggered this page).
+ if *page_break_before && fi_idx > 0 {
+ break;
+ }
+ let boundary = scan_inline_page_boundary(fragments, &mut scan_col, num_cols);
+ if boundary != ForwardScanBoundary::BeforeParagraphFloat {
+ for fi in fi_list {
+ // §20.4.2.15/.18: only wrap-enabled modes narrow
+ // text. `TopAndBottom` is a block spacer and
+ // `None` is a pure overlay — matches the gate in
+ // `has_absolute_wrap_float` below.
+ if !fi.wrap_mode.registers_as_wrap_float() {
+ continue;
+ }
+ if let FloatingImageY::Absolute(img_y) = fi.y {
+ self.current_page_abs_floats.push(float::ActiveFloat {
+ page_x: fi.x.resolve(parity) - fi.dist_left,
+ page_y_start: img_y,
+ page_y_end: img_y + fi.size.height,
+ width: fi.size.width + fi.dist_left + fi.dist_right,
+ source: float::FloatSource::Image,
+ wrap_text: fi.wrap_mode.wrap_text().into(),
+ });
+ }
+ }
+ }
+ if boundary != ForwardScanBoundary::None {
+ break;
+ }
+ }
+ }
+ self.abs_floats_dirty = false;
+ }
+
+ // Merge page_floats with forward-scanned absolute floats (dedup). Only
+ // include absolute floats whose y range starts at or above the current
+ // cursor — floats below shouldn't affect text above.
+ let mut effective_floats = self.page_floats.clone();
+ let y_threshold = self.cursor_y + space_before;
+ let deduped: Vec<float::ActiveFloat> = self
+ .current_page_abs_floats
+ .iter()
+ .filter(|af| af.page_y_start <= y_threshold)
+ .filter(|af| {
+ !effective_floats.iter().any(|pf| {
+ (pf.page_x - af.page_x).raw().abs() < FLOAT_DEDUP_EPSILON_PT
+ && (pf.page_y_start - af.page_y_start).raw().abs() < FLOAT_DEDUP_EPSILON_PT
+ && (pf.page_y_end - af.page_y_end).raw().abs() < FLOAT_DEDUP_EPSILON_PT
+ })
+ })
+ .cloned()
+ .collect();
+ effective_floats.extend(deduped);
+
+ // §17.4.56: advance past any full-width float that blocks all text.
+ for ef in &effective_floats {
+ if ef.overlaps_y(self.cursor_y) && ef.width >= col_width {
+ self.cursor_y = self.cursor_y.max(ef.page_y_end);
+ }
+ }
+ float::prune_floats(&mut effective_floats, self.cursor_y);
+ effective_floats
+ }
+}
+
+struct ParagraphFloatCheckpoint {
+ command_count: usize,
+ page_floats: Vec<float::ActiveFloat>,
+ cursor_y: Pt,
+}
+
+struct PageReplayCheckpoint<'doc> {
+ current_page: LayoutedPage,
+ cursor_y: Pt,
+ page_index: usize,
+ page_top: Pt,
+ current_col: usize,
+ column_top: Pt,
+ bottom: Pt,
+ page_footnotes: Vec<(
+ &'doc [super::super::fragment::Fragment],
+ &'doc ParagraphStyle,
+ )>,
+ first_on_section_page: bool,
+ prev_space_after: Pt,
+ prev_style_id: Option<StyleId>,
+ prev_borders: Option<ParagraphBorderStyle>,
+ page_floats: Vec<float::ActiveFloat>,
+ current_page_abs_floats: Vec<float::ActiveFloat>,
+ abs_floats_dirty: bool,
+ page_start_block: usize,
+ last_para_start_y: Pt,
+ prev_table_style_id: Option<StyleId>,
+ pending_page_break: bool,
+}
+
+impl<'doc> PageReplayCheckpoint<'doc> {
+ fn capture(state: &PageLayoutState<'doc>) -> Self {
+ Self {
+ current_page: state.current_page.clone(),
+ cursor_y: state.cursor_y,
+ page_index: state.page_index,
+ page_top: state.page_top,
+ current_col: state.current_col,
+ column_top: state.column_top,
+ bottom: state.bottom,
+ page_footnotes: state.page_footnotes.clone(),
+ first_on_section_page: state.first_on_section_page,
+ prev_space_after: state.prev_space_after,
+ prev_style_id: state.prev_style_id.clone(),
+ prev_borders: state.prev_borders.clone(),
+ page_floats: state.page_floats.clone(),
+ current_page_abs_floats: state.current_page_abs_floats.clone(),
+ abs_floats_dirty: state.abs_floats_dirty,
+ page_start_block: state.page_start_block,
+ last_para_start_y: state.last_para_start_y,
+ prev_table_style_id: state.prev_table_style_id.clone(),
+ pending_page_break: state.pending_page_break,
+ }
+ }
+
+ fn restore(&self, state: &mut PageLayoutState<'doc>) {
+ state.current_page.clone_from(&self.current_page);
+ state.cursor_y = self.cursor_y;
+ state.page_index = self.page_index;
+ state.page_top = self.page_top;
+ state.current_col = self.current_col;
+ state.column_top = self.column_top;
+ state.bottom = self.bottom;
+ state.page_footnotes.clone_from(&self.page_footnotes);
+ state.first_on_section_page = self.first_on_section_page;
+ state.prev_space_after = self.prev_space_after;
+ state.prev_style_id.clone_from(&self.prev_style_id);
+ state.prev_borders.clone_from(&self.prev_borders);
+ state.page_floats.clone_from(&self.page_floats);
+ state
+ .current_page_abs_floats
+ .clone_from(&self.current_page_abs_floats);
+ state.abs_floats_dirty = self.abs_floats_dirty;
+ state.page_start_block = self.page_start_block;
+ state.last_para_start_y = self.last_para_start_y;
+ state
+ .prev_table_style_id
+ .clone_from(&self.prev_table_style_id);
+ state.pending_page_break = self.pending_page_break;
+ }
+}
+
+fn refresh_page_replay_checkpoint<'doc>(
+ state: &PageLayoutState<'doc>,
+ block_idx: usize,
+ checkpoint: &mut PageReplayCheckpoint<'doc>,
+ checkpoint_page_index: &mut usize,
+ replay_block_idx: &mut usize,
+) {
+ if state.page_index != *checkpoint_page_index {
+ *checkpoint = PageReplayCheckpoint::capture(state);
+ *checkpoint_page_index = state.page_index;
+ *replay_block_idx = block_idx;
+ }
+}
+
+impl ParagraphFloatCheckpoint {
+ fn capture(state: &PageLayoutState<'_>) -> Self {
+ Self {
+ command_count: state.current_page.commands.len(),
+ page_floats: state.page_floats.clone(),
+ cursor_y: state.cursor_y,
+ }
+ }
+
+ fn restore(&self, state: &mut PageLayoutState<'_>) {
+ state.current_page.commands.truncate(self.command_count);
+ state.page_floats.clone_from(&self.page_floats);
+ state.cursor_y = self.cursor_y;
+ }
+}
+
+/// §17.17.1 / §20.1.2.1.1: emit a floating shape's `wps:txbx` text over its
+/// fill. Each command is in shape-local coordinates; shift by the shape's
+/// resolved page origin `(fs.x, shape_y)`. Mirrors the stacker's shape-text
+/// emission (`section::stacker`) so body/page-anchored shapes render their text,
+/// not just the fill/stroke.
+fn emit_shape_text(state: &mut PageLayoutState<'_>, fs: &FloatingShape, shape_y: Pt) {
+ let parity = state.parity();
+ for mut cmd in fs.text_commands.iter().cloned() {
+ cmd.shift(fs.x.resolve(parity), shape_y);
+ state.current_page.commands.push(cmd);
+ }
+}
+
+fn register_paragraph_floats(
+ state: &mut PageLayoutState<'_>,
+ floating_images: &[FloatingImage],
+ floating_shapes: &[FloatingShape],
+ content_top: Pt,
+) {
+ let parity = state.parity();
+ for fi in floating_images {
+ let (y_start, y_end) = match fi.y {
+ FloatingImageY::RelativeToParagraph(offset) => {
+ (content_top + offset, content_top + offset + fi.size.height)
+ }
+ FloatingImageY::Absolute(img_y) => (img_y, img_y + fi.size.height),
+ };
+ if fi.is_wrap_top_and_bottom() {
+ let img_y = match fi.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => content_top + offset,
+ };
+ state.current_page.commands.push(DrawCommand::Image {
+ rect: PtRect::from_xywh(fi.x.resolve(parity), img_y, fi.size.width, fi.size.height),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ if y_end > state.cursor_y {
+ state.cursor_y = y_end;
+ }
+ } else if fi.wrap_mode.registers_as_wrap_float() {
+ let float_entry = float::ActiveFloat {
+ page_x: fi.x.resolve(parity) - fi.dist_left,
+ page_y_start: y_start,
+ page_y_end: y_end,
+ width: fi.size.width + fi.dist_left + fi.dist_right,
+ source: float::FloatSource::Image,
+ wrap_text: fi.wrap_mode.wrap_text().into(),
+ };
+ log::debug!(
+ "[layout] register image float: x={:.1} y={:.1}-{:.1} w={:.1}",
+ float_entry.page_x.raw(),
+ y_start.raw(),
+ y_end.raw(),
+ float_entry.width.raw()
+ );
+ state.page_floats.push(float_entry);
+ }
+ }
+
+ for fs in floating_shapes {
+ if matches!(fs.wrap_mode, WrapMode::None) {
+ continue;
+ }
+ let (y_start, y_end) = match fs.y {
+ FloatingImageY::RelativeToParagraph(offset) => {
+ (content_top + offset, content_top + offset + fs.size.height)
+ }
+ FloatingImageY::Absolute(y) => (y, y + fs.size.height),
+ };
+ if fs.is_wrap_top_and_bottom() {
+ let shape_y = match fs.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => content_top + offset,
+ };
+ state.current_page.commands.push(DrawCommand::Path {
+ origin: crate::render::geometry::PtOffset::new(fs.x.resolve(parity), shape_y),
+ rotation: fs.rotation,
+ flip_h: fs.flip_h,
+ flip_v: fs.flip_v,
+ extent: fs.size,
+ paths: fs.paths.clone(),
+ fill: fs.fill.clone(),
+ stroke: fs.stroke.clone(),
+ effects: fs.effects.clone(),
+ });
+ emit_shape_text(state, fs, shape_y);
+ if y_end > state.cursor_y {
+ state.cursor_y = y_end;
+ }
+ } else {
+ let float_entry = float::ActiveFloat {
+ page_x: fs.x.resolve(parity) - fs.dist_left,
+ page_y_start: y_start,
+ page_y_end: y_end,
+ width: fs.size.width + fs.dist_left + fs.dist_right,
+ source: float::FloatSource::Shape,
+ wrap_text: fs.wrap_mode.wrap_text().into(),
+ };
+ log::debug!(
+ "[layout] register shape float: x={:.1} y={:.1}-{:.1} w={:.1} mode={:?}",
+ float_entry.page_x.raw(),
+ y_start.raw(),
+ y_end.raw(),
+ float_entry.width.raw(),
+ fs.wrap_mode
+ );
+ state.page_floats.push(float_entry);
+ }
+ }
+}
+
+fn register_destination_paragraph_floats(
+ state: &mut PageLayoutState<'_>,
+ floating_images: &[FloatingImage],
+ floating_shapes: &[FloatingShape],
+ space_before: Pt,
+ col_width: Pt,
+) {
+ let content_top = state.cursor_y + space_before;
+ register_paragraph_floats(state, floating_images, floating_shapes, content_top);
+ for active_float in &state.page_floats {
+ if active_float.overlaps_y(state.cursor_y) && active_float.width >= col_width {
+ state.cursor_y = state.cursor_y.max(active_float.page_y_end);
+ }
+ }
+ float::prune_floats(&mut state.page_floats, state.cursor_y);
+}
+
+fn has_absolute_wrap_float(floating_images: &[FloatingImage]) -> bool {
+ floating_images.iter().any(|image| {
+ matches!(image.y, FloatingImageY::Absolute(_)) && image.wrap_mode.registers_as_wrap_float()
+ })
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum ForwardScanBoundary {
+ None,
+ BeforeParagraphFloat,
+ AfterParagraphFloat,
+}
+
+fn scan_inline_page_boundary(
+ fragments: &[super::super::fragment::Fragment],
+ current_col: &mut usize,
+ num_cols: usize,
+) -> ForwardScanBoundary {
+ for (index, fragment) in fragments.iter().enumerate() {
+ match fragment {
+ super::super::fragment::Fragment::PageBreak { .. } => {
+ let has_following_content = fragments[index + 1..].iter().any(|fragment| {
+ !matches!(fragment, super::super::fragment::Fragment::PageBreak { .. })
+ });
+ return if has_following_content {
+ ForwardScanBoundary::BeforeParagraphFloat
+ } else {
+ ForwardScanBoundary::AfterParagraphFloat
+ };
+ }
+ super::super::fragment::Fragment::ColumnBreak => {
+ if *current_col + 1 < num_cols {
+ *current_col += 1;
+ } else {
+ *current_col = 0;
+ return ForwardScanBoundary::BeforeParagraphFloat;
+ }
+ }
+ _ => {}
+ }
+ }
+
+ ForwardScanBoundary::None
+}
+
+fn mark_absolute_float_relocation(
+ paragraph_content_placed: bool,
+ moves_to_new_page: bool,
+ block_idx: usize,
+ replay_block_idx: usize,
+ floating_images: &[FloatingImage],
+ relocated_blocks: &mut std::collections::HashSet<usize>,
+) -> bool {
+ !paragraph_content_placed
+ && moves_to_new_page
+ && block_idx > replay_block_idx
+ && has_absolute_wrap_float(floating_images)
+ && relocated_blocks.insert(block_idx)
+}
+
+fn paragraph_keep_next(block: &LayoutBlock) -> bool {
+ matches!(block, LayoutBlock::Paragraph { style, .. } if style.keep_next)
+}
+
+fn starts_keep_next_chain(blocks: &[LayoutBlock], block_idx: usize) -> bool {
+ paragraph_keep_next(&blocks[block_idx])
+ && (block_idx == 0
+ || matches!(
+ blocks[block_idx],
+ LayoutBlock::Paragraph {
+ page_break_before: true,
+ ..
+ }
+ )
+ || !paragraph_keep_next(&blocks[block_idx - 1]))
+}
+
+fn keep_next_terminal_table(blocks: &[LayoutBlock], start: usize) -> Option<&LayoutBlock> {
+ let mut index = start;
+
+ while let Some(block) = blocks.get(index) {
+ match block {
+ LayoutBlock::Paragraph {
+ style,
+ page_break_before,
+ ..
+ } => {
+ if index > start && *page_break_before {
+ return None;
+ }
+ if !style.keep_next {
+ return None;
+ }
+ index += 1;
+ }
+ LayoutBlock::Table {
+ float_info: None, ..
+ } => return Some(block),
+ LayoutBlock::Table {
+ float_info: Some(_),
+ ..
+ } => return None,
+ }
+ }
+
+ None
+}
+
+fn fresh_page_contextual_space_before(
+ block: &LayoutBlock,
+ previous_style_id: &Option<StyleId>,
+) -> Pt {
+ let LayoutBlock::Paragraph { style, .. } = block else {
+ return Pt::ZERO;
+ };
+ let effective = style.clone_for_layout();
+ if effective.contextual_spacing
+ && effective.style_id.is_some()
+ && effective.style_id.as_ref() == previous_style_id.as_ref()
+ {
+ effective.space_before
+ } else {
+ Pt::ZERO
+ }
+}
+
+struct KeepNextGroupMeasurement {
+ body_height: Pt,
+ footnote_height: Pt,
+ has_footnotes: bool,
+}
+
+impl KeepNextGroupMeasurement {
+ fn total_height(&self, separator_already_reserved: bool) -> Pt {
+ self.body_height
+ + self.footnote_height
+ + if self.has_footnotes && !separator_already_reserved {
+ FOOTNOTE_SEPARATOR_GAP
+ } else {
+ Pt::ZERO
+ }
+ }
+}
+
+fn measure_keep_next_group(
+ blocks: &[LayoutBlock],
+ start: usize,
+ constraints: &BoxConstraints,
+ default_line_height: Pt,
+ measure_text: super::super::paragraph::MeasureTextFn<'_>,
+) -> Option<KeepNextGroupMeasurement> {
+ let mut measurement = KeepNextGroupMeasurement {
+ body_height: Pt::ZERO,
+ footnote_height: Pt::ZERO,
+ has_footnotes: false,
+ };
+ let mut previous_space_after = Pt::ZERO;
+ let mut previous_style_id = None;
+ let mut index = start;
+
+ while let Some(block) = blocks.get(index) {
+ match block {
+ LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before,
+ footnotes,
+ ..
+ } => {
+ if index > start && *page_break_before {
+ return None;
+ }
+ let effective = style.clone_for_layout();
+ let collapsed = if effective.contextual_spacing
+ && effective.style_id.is_some()
+ && effective.style_id == previous_style_id
+ {
+ previous_space_after + effective.space_before
+ } else {
+ previous_space_after.min(effective.space_before)
+ };
+ let layout = layout_paragraph(
+ fragments,
+ constraints,
+ &effective,
+ default_line_height,
+ measure_text,
+ );
+ measurement.body_height += layout.size.height - collapsed;
+ for (footnote_fragments, footnote_style) in footnotes {
+ let footnote = layout_paragraph(
+ footnote_fragments,
+ &BoxConstraints::tight_width(constraints.max_width, Pt::INFINITY),
+ footnote_style,
+ default_line_height,
+ measure_text,
+ );
+ measurement.footnote_height += footnote.size.height;
+ measurement.has_footnotes = true;
+ }
+ previous_space_after = effective.space_after;
+ previous_style_id = effective.style_id.clone();
+ if !effective.keep_next {
+ return Some(measurement);
+ }
+ index += 1;
+ }
+ LayoutBlock::Table { .. } => {
+ return Some(measurement);
+ }
+ }
+ }
+ None
+}
+
+/// §17.3.1.15 (keepNext tightening): can the paragraph that *starts* a keepNext
+/// chain be split so a widow-legal head stays on the current page while its tail
+/// travels to the fresh page with the rest of the group?
+///
+/// keepNext forbids a page break only *between* a paragraph and the next block —
+/// it does not pin the paragraph's earlier lines. So when the whole group would
+/// otherwise be moved to a fresh page (leaving the current page under-filled),
+/// a splittable leading paragraph can instead fill the current page and carry
+/// its `>= 2`-line tail onward: the caller has already checked the whole group
+/// fits on a fresh page, and the remainder after peeling a `>= 2`-line head is
+/// strictly smaller, so it still fits there and no keepNext boundary is broken.
+///
+/// True only for a body paragraph that can actually split — no keepLines
+/// (§17.3.1.14), no floating objects (they anchor to one page), footnotes only
+/// on an unbroken chunk, and enough lines to leave `>= 2` on each side under
+/// §17.3.1.44 widow control. A `false` result keeps the conservative
+/// whole-group move.
+fn leading_keep_next_paragraph_splittable(
+ block: &LayoutBlock,
+ constraints: &BoxConstraints,
+ default_line_height: Pt,
+ measure_text: super::super::paragraph::MeasureTextFn<'_>,
+) -> bool {
+ let LayoutBlock::Paragraph {
+ fragments,
+ style,
+ footnotes,
+ floating_images,
+ floating_shapes,
+ ..
+ } = block
+ else {
+ return false;
+ };
+ let effective = style.clone_for_layout();
+ // `single_chunk` is a whole-paragraph property, so it can be derived here
+ // exactly as the placement gate derives it from its loop state: both
+ // splitters are pure functions of the fragment list, and when the paragraph
+ // has more than one page chunk the flag is false regardless of column
+ // chunking.
+ let single_chunk =
+ split_at_page_breaks(fragments).len() == 1 && split_at_column_breaks(fragments).len() == 1;
+ if !paragraph_breakable(
+ &effective,
+ footnotes,
+ floating_images,
+ floating_shapes,
+ single_chunk,
+ ) {
+ return false;
+ }
+ let placed = place_paragraph(
+ fragments,
+ constraints,
+ &effective,
+ default_line_height,
+ measure_text,
+ );
+ // Widow control (§17.3.1.44) needs `>= 2` lines on each side of the break;
+ // without it a single-line head is legal. Deliberately stricter than the
+ // placement gate's flat `>= 2`: this predicts whether a split would yield a
+ // *useful* head, and under-predicting only costs a conservative move.
+ let min_lines = if effective.widow_control { 4 } else { 2 };
+ placed.line_count() >= min_lines
+}
+
+/// §17.3.1.14 / §17.3.1.15: the conditions under which a paragraph may be
+/// broken across a page or column boundary, shared by the placement gate
+/// (`can_split`) and the keepNext predictor above.
+///
+/// Extracted because the two disagreed: the predictor omitted the footnote
+/// condition, so a keepNext-chain head carrying footnotes across several
+/// page/column chunks was reported splittable, the whole-group move was
+/// skipped, and the placement path then refused to split it and fell back to
+/// atomic — legal output on an under-filled page, but not the pagination either
+/// side intended.
+///
+/// Line counts are **not** included. The gate needs `>= 2`; the predictor needs
+/// enough to leave a legal head *and* tail. Folding them together would either
+/// weaken the predictor or tighten the gate, so each keeps its own.
+fn paragraph_breakable(
+ style: &crate::render::layout::paragraph::ParagraphStyle,
+ footnotes: &[(
+ Vec<Fragment>,
+ crate::render::layout::paragraph::ParagraphStyle,
+ )],
+ floating_images: &[FloatingImage],
+ floating_shapes: &[FloatingShape],
+ single_chunk: bool,
+) -> bool {
+ if style.keep_lines || !floating_images.is_empty() || !floating_shapes.is_empty() {
+ return false;
+ }
+ // Footnotes are reserved per segment, but only for a single unbroken chunk:
+ // with explicit page/column breaks a reference's segment is ambiguous, so
+ // those paragraphs keep the atomic reservation.
+ footnotes.is_empty() || single_chunk
+}
+
+/// §17.3.1.14 / §17.3.1.44: how to break a paragraph across a page boundary.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ParagraphSplit {
+ /// Emit all lines on the current page (they fit, or must overflow because no
+ /// legal split exists and the paragraph already starts at the page top).
+ All,
+ /// Emit the first `head` lines here and carry the remaining `total - head`
+ /// to the next page. Invariants: `1 <= head < total`; under widow control,
+ /// additionally `head >= 2 && total - head >= 2`.
+ Break { head: usize },
+ /// No legal break at this fill level, and the paragraph does not start at the
+ /// page top — move the whole paragraph to the next page and re-decide there.
+ MoveWhole,
+}
+
+/// Decide how a paragraph whose first `n_fit` of `total` lines fit in the
+/// remaining space should break (§17.3.1.14 keepLines is handled by the caller,
+/// which only calls this for splittable paragraphs).
+///
+/// `widow_control` (§17.3.1.44) forbids leaving a single line stranded: a legal
+/// break keeps `>= 2` lines on each side. `at_page_top` is true when the
+/// paragraph begins at the very top of the page column; there, the remaining
+/// space already equals a full page, so "move whole" cannot help — a paragraph
+/// taller than a page must split ("where possible"), and one that cannot split
+/// legally is emitted whole and allowed to overflow. This guarantees the stacker
+/// always makes progress (never loops).
+fn decide_paragraph_split(
+ n_fit: usize,
+ total: usize,
+ widow_control: bool,
+ at_page_top: bool,
+) -> ParagraphSplit {
+ debug_assert!(total >= 1, "a paragraph has at least one line");
+ if n_fit >= total {
+ return ParagraphSplit::All;
+ }
+
+ // The paragraph does not fully fit; find the largest legal head.
+ let head = if widow_control {
+ // Leave >= 2 lines for the tail (widow) and keep >= 2 here (orphan).
+ let capped = n_fit.min(total.saturating_sub(2));
+ if capped >= 2 {
+ capped
+ } else {
+ 0 // no widow/orphan-legal break at this fill level
+ }
+ } else {
+ // Without widow control a single line on either side is allowed; place
+ // as many as fit, leaving at least one for the tail (n_fit < total, so
+ // n_fit <= total - 1 already holds).
+ n_fit
+ };
+
+ if head >= 1 {
+ return ParagraphSplit::Break { head };
+ }
+
+ // No legal break at this fill level.
+ if at_page_top {
+ // Remaining space is a full page and the paragraph still cannot fit or
+ // split legally — emit it whole and let it overflow.
+ ParagraphSplit::All
+ } else {
+ ParagraphSplit::MoveWhole
+ }
+}
+
+/// Place a splittable paragraph, breaking its lines across pages as needed.
+///
+/// The caller establishes splittability — see the `can_split` gate at the call
+/// site, which is the authority. It requires: no §17.3.1.14 `keepLines`, no
+/// floating images or shapes (those anchor to one page), `>= 2` fitted lines,
+/// and footnotes only within a single unbroken chunk (with explicit
+/// page/column breaks a reference→segment mapping is ambiguous, so those keep
+/// the atomic reservation).
+///
+/// Deliberately *not* required — each was allowed by a later change and this
+/// list is the historical trip hazard:
+/// - **Borders, shading and drop caps** split fine; they are drawn per segment
+/// (`emit_segment_borders_and_shading`).
+/// - **Multiple columns** split fine; §17.6.4 unequal-width columns work
+/// because each segment re-fits against its own column's width.
+///
+/// Each iteration fits as many remaining lines as the current page holds,
+/// applies §17.3.1.44 widow/orphan control via [`decide_paragraph_split`],
+/// emits that segment, and page-breaks to continue. `line_start` advances by
+/// `>= 1` on every emitted segment and a `MoveWhole` always lands on a fresh
+/// page where progress is forced, so the loop terminates.
+/// §17.11.23: reserve `footnotes` on the current page — measure each, subtract
+/// its height (and the separator gap for the first footnote on the page) from
+/// the available bottom, and queue it for rendering. Shared by the atomic
+/// placement path and the per-segment split path.
+fn reserve_footnotes<'doc>(
+ state: &mut PageLayoutState<'doc>,
+ ctx: &LayoutCtx<'_>,
+ content_width: Pt,
+ footnotes: &'doc [(Vec<Fragment>, ParagraphStyle)],
+) {
+ if footnotes.is_empty() {
+ return;
+ }
+ let fn_constraints = BoxConstraints::tight_width(content_width, Pt::INFINITY);
+ for (fn_frags, fn_style) in footnotes {
+ let fn_para = layout_paragraph(
+ fn_frags,
+ &fn_constraints,
+ fn_style,
+ ctx.default_line_height,
+ ctx.measure_text,
+ );
+ // Reserve separator space only for the first footnote on this page.
+ if state.page_footnotes.is_empty() {
+ state.bottom -= FOOTNOTE_SEPARATOR_GAP;
+ }
+ state.bottom -= fn_para.size.height;
+ state.page_footnotes.push((fn_frags, fn_style));
+ }
+}
+
+/// §17.6.4: advance the split cursor to the next column, or — when the last
+/// column is full — to the top of a fresh page. A fresh column, like a fresh
+/// page, offers the full column height, so the split fit treats both as "at the
+/// column top".
+fn advance_column_or_page(
+ state: &mut PageLayoutState<'_>,
+ block_idx: usize,
+ ctx: &LayoutCtx<'_>,
+ num_cols: usize,
+ para_start_y: &mut Pt,
+) {
+ if state.current_col + 1 < num_cols {
+ state.current_col += 1;
+ state.cursor_y = state.column_top;
+ } else {
+ state.push_new_page(block_idx, ctx);
+ }
+ *para_start_y = state.cursor_y;
+}
+
+#[allow(clippy::too_many_arguments)] // stacker state + placement inputs are cohesive
+fn emit_split_paragraph<'doc>(
+ state: &mut PageLayoutState<'doc>,
+ fragments: &[Fragment],
+ style: &ParagraphStyle,
+ block_idx: usize,
+ config: &PageConfig,
+ ctx: &LayoutCtx<'_>,
+ para_start_y: &mut Pt,
+ footnotes: &'doc [(Vec<Fragment>, ParagraphStyle)],
+ content_width: Pt,
+ blocks: &[LayoutBlock],
+ relocated_absolute_float_blocks: &std::collections::HashSet<usize>,
+) {
+ let num_cols = config.num_columns();
+ let col_x = |col: usize| config.margins.left + config.columns[col].x_offset;
+ let widow_control = style.widow_control;
+
+ // §4: the remainder to place on the current page, plus the style to place
+ // it with. Both are re-derived per page/column so a continuation wraps
+ // around whatever floats live on *its* page (not the paragraph's starting
+ // page) and uses that page's width. Owned so they can be re-sliced/re-styled
+ // across page breaks. The first page reuses the caller's `style` (which
+ // already carries the starting page's floats/width).
+ let mut remaining: Vec<Fragment> = fragments.to_vec();
+ let mut cont_style: ParagraphStyle = style.clone();
+ let mut first_segment = true;
+ // §17.11.12: footnotes reserved in document order; this many are placed.
+ let mut footnote_cursor = 0;
+
+ loop {
+ let col_width = config.columns[state.current_col].width;
+ let page_height = (state.bottom - state.page_top).max(Pt::ZERO);
+ let constraints = BoxConstraints::new(Pt::ZERO, col_width, Pt::ZERO, page_height);
+ let placed = place_paragraph(
+ &remaining,
+ &constraints,
+ &cont_style,
+ ctx.default_line_height,
+ ctx.measure_text,
+ );
+ let total = placed.line_count();
+ if total == 0 {
+ break;
+ }
+
+ // §17.6.4: a fresh column offers full height, like a fresh page.
+ let at_page_top = state.cursor_y <= state.column_top;
+ let avail = (state.bottom - state.cursor_y).max(Pt::ZERO);
+ // §17.3.1.24/§17.3.1.33: space_after and the bottom border space are
+ // only spent once, on the segment carrying the paragraph's last line.
+ let trailing_extra = cont_style.space_after + placed.bottom_border_space();
+
+ // Count how many of this placement's lines fit, charging space_before
+ // (first segment only, §17.3.1.33) and the trailing spacing on the last.
+ let mut used = if first_segment {
+ cont_style.space_before
+ } else {
+ Pt::ZERO
+ };
+ let mut n_fit = 0;
+ for i in 0..total {
+ let mut needed = used + placed.line_height(i);
+ if i + 1 == total {
+ needed += trailing_extra;
+ }
+ if needed > avail {
+ break;
+ }
+ used += placed.line_height(i);
+ n_fit += 1;
+ }
+
+ // §17.3.1.44 widow/orphan, then §17.3.1.11/§17.3.1.44 unbreakable-prefix
+ // clamp (drop cap / float-wrapped run kept intact on the first segment).
+ let head = match decide_paragraph_split(n_fit, total, widow_control, at_page_top) {
+ ParagraphSplit::All => Some(total),
+ ParagraphSplit::Break { head } => Some(head),
+ ParagraphSplit::MoveWhole => None,
+ }
+ .and_then(|head| {
+ prefix_adjusted_head(
+ head,
+ total,
+ placed.unbreakable_prefix_lines(),
+ first_segment,
+ at_page_top,
+ )
+ });
+
+ // No legal placement here: move the whole remainder to the next
+ // column/page and re-fit at the top (nothing emitted, so the drop cap
+ // and space_before are preserved for the real first segment).
+ let Some(head) = head else {
+ drop(placed);
+ advance_column_or_page(state, block_idx, ctx, num_cols, para_start_y);
+ cont_style = continuation_style(
+ state,
+ blocks,
+ style,
+ config,
+ relocated_absolute_float_blocks,
+ first_segment,
+ );
+ continue;
+ };
+
+ let is_last = head == total;
+ let segment = placed.emit_split_segment(0, head, first_segment, is_last);
+ if !(first_segment && is_last) {
+ log::debug!(
+ "[layout] paragraph split: {head}/{total} lines at y={:.1}",
+ state.cursor_y.raw()
+ );
+ }
+ let segment_x = col_x(state.current_col);
+ for mut cmd in segment.commands {
+ cmd.shift_y(state.cursor_y);
+ cmd.shift_x(segment_x);
+ state.current_page.commands.push(cmd);
+ }
+ state.cursor_y += segment.size.height;
+
+ // §17.11.12: reserve this segment's footnotes on the page its reference
+ // marks landed on, before any page break.
+ if !footnotes.is_empty() {
+ let refs = placed.footnote_refs_in(0, head);
+ let end = (footnote_cursor + refs).min(footnotes.len());
+ reserve_footnotes(state, ctx, content_width, &footnotes[footnote_cursor..end]);
+ footnote_cursor = end;
+ }
+
+ if is_last {
+ break;
+ }
+
+ // §4: carry the unplaced fragments to the next column/page and re-fit
+ // them there against that page's floats and width.
+ let next_remaining = placed.fragments_from_line(head);
+ drop(placed);
+ first_segment = false;
+ advance_column_or_page(state, block_idx, ctx, num_cols, para_start_y);
+ cont_style = continuation_style(
+ state,
+ blocks,
+ style,
+ config,
+ relocated_absolute_float_blocks,
+ first_segment,
+ );
+ remaining = next_remaining;
+ }
+}
+
+/// Build the paragraph style for a split segment after advancing to a new
+/// column/page (§4 continuation re-fit). Refreshes the float set for the new
+/// page (`effective_floats_at_cursor`, which may also advance the cursor past a
+/// full-width float) and repositions the paragraph. When something has already
+/// been emitted (`first_segment == false`), the continuation drops
+/// `space_before` (§17.3.1.33), the drop cap (§17.3.1.11), and the first-line
+/// indent (§17.3.1.12); a whole-paragraph move that emitted nothing keeps them
+/// for the eventual real first segment.
+fn continuation_style(
+ state: &mut PageLayoutState<'_>,
+ blocks: &[LayoutBlock],
+ style: &ParagraphStyle,
+ config: &PageConfig,
+ relocated_absolute_float_blocks: &std::collections::HashSet<usize>,
+ first_segment: bool,
+) -> ParagraphStyle {
+ let col = state.current_col;
+ let col_width = config.columns[col].width;
+ let page_x = config.margins.left + config.columns[col].x_offset;
+ let space_before = if first_segment {
+ style.space_before
+ } else {
+ Pt::ZERO
+ };
+ let floats = state.effective_floats_at_cursor(
+ blocks,
+ relocated_absolute_float_blocks,
+ config.num_columns(),
+ space_before,
+ col_width,
+ );
+ let mut cs = style.clone();
+ if !first_segment {
+ cs.drop_cap = None;
+ cs.indent_first_line = Pt::ZERO;
+ cs.space_before = Pt::ZERO;
+ }
+ cs.page_floats = floats;
+ cs.page_y = state.cursor_y;
+ cs.page_x = page_x;
+ cs.page_content_width = col_width;
+ cs
+}
+
+/// Constrain a chosen split `head` so it never falls inside the paragraph's
+/// unbreakable prefix (§17.3.1.11 drop cap and/or §17.3.1.44 float-wrapped run,
+/// the first `prefix_lines` lines). Breaking there would tear a drop-cap glyph
+/// or leave float-narrowed lines to be reused full-width on the next page.
+///
+/// Returns `Some(head)` — unchanged when it already clears the prefix — or
+/// `None` meaning "move the whole paragraph to a fresh page" (a break inside the
+/// prefix with room above). At the page top the prefix cannot move any higher,
+/// so it is emitted whole (`Some(prefix_lines)`) and allowed to overflow. The
+/// guard only applies to the first segment (the prefix lives at the start).
+fn prefix_adjusted_head(
+ head: usize,
+ remaining: usize,
+ prefix_lines: usize,
+ first_segment: bool,
+ at_page_top: bool,
+) -> Option<usize> {
+ let breaks_prefix =
+ first_segment && prefix_lines > 1 && head < prefix_lines && head < remaining;
+ if !breaks_prefix {
+ return Some(head);
+ }
+ if at_page_top {
+ Some(prefix_lines.min(remaining))
+ } else {
+ None
+ }
+}
+
+/// Where a section begins in the document's page sequence.
+///
+/// The three travel together because they answer one question — which page
+/// this section's first page *is*. `continuation` says whether it shares a
+/// page with the section before it, `clearance` how much of that page the
+/// header and footer take, and `logical_page_base` what §17.10.6 calls it.
+pub(crate) struct SectionStart<'a> {
+ /// §17.6.22: an in-progress page to continue on, for a `Continuous` break.
+ pub continuation: Option<ContinuationState>,
+ /// Header/footer clearances, selected per physical page in the section.
+ pub clearance: &'a HeaderFooterClearance,
+ /// §17.10.6: logical number of the section's first page, with
+ /// `w:pgNumType/@start` applied. Drives §20.4.3.1 float mirroring.
+ pub logical_page_base: usize,
+}
+
+/// Lay out a sequence of blocks into pages.
+///
+/// If `continuation` is provided, the section starts on the given page at the
+/// given cursor_y (for `SectionType::Continuous` sections).
+pub fn layout_section(
+ blocks: &[LayoutBlock],
+ config: &PageConfig,
+ measure_text: super::super::paragraph::MeasureTextFn<'_>,
+ separator_indent: Pt,
+ default_line_height: Pt,
+ continuation: Option<ContinuationState>,
+) -> Vec<LayoutedPage> {
+ let clearance = HeaderFooterClearance::uniform(config);
+ layout_section_with_clearance(
+ blocks,
+ config,
+ measure_text,
+ separator_indent,
+ default_line_height,
+ SectionStart {
+ continuation,
+ clearance: &clearance,
+ // A section laid out on its own starts at page 1 — the §17.10.6
+ // renumbering only exists across a document's section list.
+ logical_page_base: 1,
+ },
+ )
+}
+
+/// Lay out a sequence of blocks using header/footer clearances selected for
+/// each physical page in the section.
+pub(crate) fn layout_section_with_clearance(
+ blocks: &[LayoutBlock],
+ config: &PageConfig,
+ measure_text: super::super::paragraph::MeasureTextFn<'_>,
+ separator_indent: Pt,
+ default_line_height: Pt,
+ start: SectionStart<'_>,
+) -> Vec<LayoutedPage> {
+ let SectionStart {
+ continuation,
+ clearance,
+ logical_page_base,
+ } = start;
+ let content_width = config.content_width();
+ let num_cols = config.num_columns();
+
+ let ctx = LayoutCtx {
+ config,
+ clearance,
+ measure_text,
+ separator_indent,
+ default_line_height,
+ };
+ let mut state = PageLayoutState::new(
+ config,
+ continuation,
+ clearance.for_page(0),
+ logical_page_base,
+ );
+
+ // Column-aware constraints and x-offset for the current column.
+ let col_constraints = |col: usize, page_height: Pt| -> BoxConstraints {
+ let col_width = config.columns[col].width;
+ BoxConstraints::new(Pt::ZERO, col_width, Pt::ZERO, page_height)
+ };
+ let col_x = |col: usize| -> Pt { config.margins.left + config.columns[col].x_offset };
+
+ // A forward-scanned absolute float can later move to another page. Keep
+ // those owners out of the source page's next scan while replaying it.
+ let mut relocated_absolute_float_blocks = std::collections::HashSet::new();
+ let mut page_replay_state = PageReplayCheckpoint::capture(&state);
+ let mut checkpoint_page_index = state.page_index;
+ let mut replay_block_idx = 0;
+ let mut block_idx = 0;
+
+ 'blocks: while block_idx < blocks.len() {
+ let block = &blocks[block_idx];
+ // §17.3.3.1: a deferred inline page break from the previous block
+ // forces this block onto a new page.
+ if state.pending_page_break {
+ state.pending_page_break = false;
+ if state.cursor_y > state.page_top {
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ }
+ }
+ refresh_page_replay_checkpoint(
+ &state,
+ block_idx,
+ &mut page_replay_state,
+ &mut checkpoint_page_index,
+ &mut replay_block_idx,
+ );
+
+ match block {
+ LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before,
+ footnotes,
+ floating_images,
+ floating_shapes,
+ } => {
+ // §17.3.1.23: force a new page before this paragraph.
+ if *page_break_before && state.cursor_y > state.page_top {
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ }
+
+ if num_cols == 1
+ && starts_keep_next_chain(blocks, block_idx)
+ && state.page_floats.is_empty()
+ {
+ let constraints = col_constraints(
+ state.current_col,
+ (state.bottom - state.page_top).max(Pt::ZERO),
+ );
+ if let Some(group) = measure_keep_next_group(
+ blocks,
+ block_idx,
+ &constraints,
+ ctx.default_line_height,
+ ctx.measure_text,
+ ) {
+ let current_group_height =
+ group.total_height(!state.page_footnotes.is_empty());
+ let current_group_top = match &blocks[block_idx] {
+ LayoutBlock::Paragraph { style, .. }
+ if style.contextual_spacing
+ && style.style_id.is_some()
+ && style.style_id == state.prev_style_id =>
+ {
+ state.cursor_y - state.prev_space_after - style.space_before
+ }
+ LayoutBlock::Paragraph { style, .. } => {
+ state.cursor_y - state.prev_space_after.min(style.space_before)
+ }
+ LayoutBlock::Table { .. } => state.cursor_y,
+ };
+ let full_page_height = ctx.page_bounds(state.page_index + 1).height();
+ let fresh_page_group_height = group.total_height(false)
+ - fresh_page_contextual_space_before(
+ &blocks[block_idx],
+ &state.prev_style_id,
+ );
+ let should_move = match keep_next_terminal_table(blocks, block_idx) {
+ Some(LayoutBlock::Table {
+ rows,
+ col_widths,
+ cell_spacing,
+ border_config,
+ ..
+ }) if !rows.is_empty() => {
+ let current_available =
+ state.bottom - current_group_top - current_group_height;
+ let full_page_available =
+ full_page_height - fresh_page_group_height;
+ let leading_group_height = measure_leading_table_group_height(
+ rows,
+ col_widths,
+ *cell_spacing,
+ ctx.default_line_height,
+ border_config.as_ref(),
+ ctx.measure_text,
+ false,
+ );
+ leading_group_height.is_some_and(|height| {
+ height <= full_page_available && height > current_available
+ })
+ }
+ _ => {
+ // §17.3.1.15 (11.2): the group doesn't fit here
+ // but fits on a fresh page. Rather than move the
+ // whole group, let a splittable leading
+ // paragraph fill this page and carry its
+ // widow-legal tail onward — the remainder is
+ // strictly smaller than the (fresh-page-fitting)
+ // group, so the keepNext boundary stays intact.
+ // Only for paragraph terminals: a table terminal
+ // is excluded from the group measurement, so its
+ // leading row is not covered by that guarantee
+ // and keeps the whole-move (handled above).
+ fresh_page_group_height <= full_page_height
+ && current_group_top + current_group_height > state.bottom
+ && !leading_keep_next_paragraph_splittable(
+ &blocks[block_idx],
+ &constraints,
+ ctx.default_line_height,
+ ctx.measure_text,
+ )
+ }
+ };
+ if should_move && state.cursor_y > state.column_top {
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ }
+ }
+ }
+ refresh_page_replay_checkpoint(
+ &state,
+ block_idx,
+ &mut page_replay_state,
+ &mut checkpoint_page_index,
+ &mut replay_block_idx,
+ );
+
+ let mut effective_style = style.clone_for_layout();
+
+ // Log paragraph info.
+ let first_text = fragments
+ .iter()
+ .find_map(|f| {
+ if let super::super::fragment::Fragment::Text { text, .. } = f {
+ Some(&**text)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("");
+ log::debug!(
+ "[layout] block[{block_idx}] para style={:?} text={:?} cursor_y={:.1} col={} floats={} fwd_floats={}",
+ effective_style.style_id,
+ &first_text[..first_text.len().min(30)],
+ state.cursor_y.raw(),
+ state.current_col,
+ state.page_floats.len(),
+ state.current_page_abs_floats.len()
+ );
+
+ // §17.3.1.33: suppress space_before for the structural first
+ // paragraph of a section on its initial page.
+ if state.cursor_y <= state.column_top && state.first_on_section_page {
+ effective_style.space_before = Pt::ZERO;
+ }
+ // §17.3.1.24: paragraph border grouping — consecutive paragraphs
+ // with identical borders suppress interior top borders.
+ if effective_style.borders.is_some()
+ && effective_style.borders == state.prev_borders
+ {
+ if let Some(ref mut b) = effective_style.borders {
+ b.top = None;
+ }
+ }
+ // §17.3.1.9: spacing collapse (must happen before float registration).
+ if effective_style.contextual_spacing
+ && effective_style.style_id.is_some()
+ && effective_style.style_id == state.prev_style_id
+ {
+ state.cursor_y -= state.prev_space_after + effective_style.space_before;
+ } else {
+ let collapse = state.prev_space_after.min(effective_style.space_before);
+ state.cursor_y -= collapse;
+ }
+
+ // Register floating images (both relative and absolute).
+ // §20.4.2.18: wrapTopAndBottom images are emitted immediately
+ // and cursor_y advances past them — they act as block spacers.
+ // §20.4.2.10: paragraph-relative floats use the content area
+ // top (after space_before), not the total paragraph box top.
+ let float_checkpoint = ParagraphFloatCheckpoint::capture(&state);
+ let content_top = state.cursor_y + effective_style.space_before;
+ register_paragraph_floats(
+ &mut state,
+ floating_images,
+ floating_shapes,
+ content_top,
+ );
+
+ // Prune expired floats.
+ float::prune_floats(&mut state.page_floats, state.cursor_y);
+
+ // §20.4.2 / §17.4.56: floats affecting text at the cursor —
+ // registered page floats plus the boundary-/relocation-aware
+ // forward scan of upcoming blocks — advancing past any
+ // full-width blocker.
+ let col_width = config.columns[state.current_col].width;
+ let page_x = col_x(state.current_col);
+ let effective_floats = state.effective_floats_at_cursor(
+ blocks,
+ &relocated_absolute_float_blocks,
+ num_cols,
+ effective_style.space_before,
+ col_width,
+ );
+
+ effective_style.page_floats = effective_floats;
+ effective_style.page_y = state.cursor_y;
+ effective_style.page_x = page_x;
+ effective_style.page_content_width = col_width;
+
+ // §17.3.3.1: split paragraph at inline page breaks first,
+ // then §17.6.4: split each page-chunk at column breaks.
+ let page_chunks = split_at_page_breaks(fragments);
+ let mut para_start_y = state.cursor_y;
+ state.last_para_start_y = state.cursor_y;
+ // §17.4.56 (#86 relocation): true once any of this paragraph's
+ // content has been placed, so a later overflow relocates its
+ // absolute float instead of double-wrapping earlier text.
+ let mut paragraph_content_placed = false;
+ // §17.11.12: set once a split segment reserves this paragraph's
+ // footnotes per page, so the atomic after-loop reservation is
+ // skipped (avoids double-reserving).
+ let mut footnotes_reserved = false;
+
+ // §17.3.3.1: track whether an unresolved page break remains
+ // after processing all chunks, so it can be deferred to the
+ // next block.
+ let mut unresolved_page_break = false;
+
+ for (page_chunk_idx, page_chunk) in page_chunks.iter().enumerate() {
+ if page_chunk_idx > 0 {
+ unresolved_page_break = true;
+ }
+
+ // §17.3.3.1: skip empty chunks — they carry no renderable
+ // content. A page break whose leading or trailing side is
+ // empty simply means "nothing on this side of the break."
+ if page_chunk.is_empty() {
+ continue;
+ }
+
+ // §17.3.3.1: force a new page for non-empty chunks that
+ // follow a page break.
+ if unresolved_page_break {
+ if mark_absolute_float_relocation(
+ paragraph_content_placed,
+ true,
+ block_idx,
+ replay_block_idx,
+ floating_images,
+ &mut relocated_absolute_float_blocks,
+ ) {
+ page_replay_state.restore(&mut state);
+ block_idx = replay_block_idx;
+ continue 'blocks;
+ }
+ if !paragraph_content_placed {
+ float_checkpoint.restore(&mut state);
+ }
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ para_start_y = state.cursor_y;
+ if !paragraph_content_placed {
+ let col_width = config.columns[state.current_col].width;
+ register_destination_paragraph_floats(
+ &mut state,
+ floating_images,
+ floating_shapes,
+ effective_style.space_before,
+ col_width,
+ );
+ }
+ effective_style.page_y = state.cursor_y;
+ effective_style.page_x = col_x(state.current_col);
+ effective_style.page_content_width =
+ config.columns[state.current_col].width;
+ effective_style.page_floats = state.page_floats.clone();
+ }
+
+ let col_chunks = split_at_column_breaks(page_chunk);
+
+ for (chunk_idx, chunk) in col_chunks.iter().enumerate() {
+ // Advance to the next column for chunks after a column break.
+ if chunk_idx > 0 {
+ let starts_new_page = state.current_col + 1 >= num_cols;
+ if mark_absolute_float_relocation(
+ paragraph_content_placed,
+ starts_new_page,
+ block_idx,
+ replay_block_idx,
+ floating_images,
+ &mut relocated_absolute_float_blocks,
+ ) {
+ page_replay_state.restore(&mut state);
+ block_idx = replay_block_idx;
+ continue 'blocks;
+ }
+ if !paragraph_content_placed && starts_new_page {
+ float_checkpoint.restore(&mut state);
+ }
+ if !starts_new_page {
+ state.current_col += 1;
+ } else {
+ // All columns full — new page, reset to column 0.
+ state.push_new_page(block_idx, &ctx);
+ }
+ state.cursor_y = state.column_top;
+ if !paragraph_content_placed && starts_new_page {
+ let col_width = config.columns[state.current_col].width;
+ register_destination_paragraph_floats(
+ &mut state,
+ floating_images,
+ floating_shapes,
+ effective_style.space_before,
+ col_width,
+ );
+ }
+ effective_style.page_y = state.cursor_y;
+ effective_style.page_x = col_x(state.current_col);
+ effective_style.page_content_width =
+ config.columns[state.current_col].width;
+ if starts_new_page {
+ effective_style.page_floats = state.page_floats.clone();
+ }
+ }
+
+ let constraints = col_constraints(
+ state.current_col,
+ (state.bottom - state.page_top).max(Pt::ZERO),
+ );
+ let placed = place_paragraph(
+ chunk,
+ &constraints,
+ &effective_style,
+ ctx.default_line_height,
+ ctx.measure_text,
+ );
+
+ // §17.3.1.14: a paragraph may break across a page
+ // boundary when keepLines is unset. Borders/shading, drop
+ // caps, and lines wrapped around an active float are
+ // handled per segment (the float-wrapped run is kept on
+ // the first segment by the unbreakable-prefix guard, so
+ // the tail reuses its fitted lines). Paragraphs that own
+ // floating objects stay atomic (the object anchors to one
+ // page) and take the #86 relocation path in the `else`
+ // branch below. Footnotes are reserved per segment, but
+ // only for a single, unbroken chunk — with explicit
+ // page/column breaks their reference→segment mapping is
+ // ambiguous, so those keep the atomic reservation.
+ // §17.6.4: splitting re-fits the
+ // remainder against each column's own width
+ // (`emit_split_paragraph`), so unequal-width columns split
+ // correctly — no equal-width gate.
+ let single_chunk = page_chunks.len() == 1 && col_chunks.len() == 1;
+ let can_split = paragraph_breakable(
+ &effective_style,
+ footnotes,
+ floating_images,
+ floating_shapes,
+ single_chunk,
+ ) && placed.line_count() >= 2;
+
+ if can_split {
+ if !footnotes.is_empty() {
+ footnotes_reserved = true;
+ }
+ drop(placed);
+ emit_split_paragraph(
+ &mut state,
+ chunk,
+ &effective_style,
+ block_idx,
+ config,
+ &ctx,
+ &mut para_start_y,
+ footnotes,
+ content_width,
+ blocks,
+ &relocated_absolute_float_blocks,
+ );
+ } else {
+ let mut para = placed.emit_full();
+ // Column/page overflow: advance column, then page.
+ if state.cursor_y + para.size.height > state.bottom
+ && state.cursor_y > state.column_top
+ {
+ // `placed` (which borrows `effective_style`) is no
+ // longer needed; drop it before mutating the style
+ // and re-placing at the destination page, whose
+ // max_height differs and re-clamps the height.
+ drop(placed);
+ // #86: if this atomic paragraph owns an absolute
+ // wrap float and moves to a new page before any of
+ // its own content is placed, earlier source-page
+ // text may already have wrapped around that future
+ // float. Replay the page without it before placing
+ // the owner on its destination page.
+ let moves_to_new_page = state.current_col + 1 >= num_cols;
+ if mark_absolute_float_relocation(
+ paragraph_content_placed,
+ moves_to_new_page,
+ block_idx,
+ replay_block_idx,
+ floating_images,
+ &mut relocated_absolute_float_blocks,
+ ) {
+ page_replay_state.restore(&mut state);
+ block_idx = replay_block_idx;
+ continue 'blocks;
+ }
+ if !paragraph_content_placed {
+ float_checkpoint.restore(&mut state);
+ }
+ if state.current_col + 1 < num_cols {
+ state.current_col += 1;
+ state.cursor_y = state.column_top;
+ } else {
+ state.push_new_page(block_idx, &ctx);
+ }
+ let destination_para_start_y = state.cursor_y;
+ // Re-register this paragraph's own floats at the
+ // destination when none of its content has landed
+ // yet (§20.4.2).
+ if !paragraph_content_placed {
+ let col_width = config.columns[state.current_col].width;
+ register_destination_paragraph_floats(
+ &mut state,
+ floating_images,
+ floating_shapes,
+ effective_style.space_before,
+ col_width,
+ );
+ }
+ // Update para_start_y after page/column change so
+ // floating images use the correct position.
+ para_start_y = destination_para_start_y;
+ effective_style.page_y = state.cursor_y;
+ effective_style.page_x = col_x(state.current_col);
+ effective_style.page_content_width =
+ config.columns[state.current_col].width;
+ effective_style.page_floats = state.page_floats.clone();
+ let destination_constraints = col_constraints(
+ state.current_col,
+ (state.bottom - state.page_top).max(Pt::ZERO),
+ );
+ para = place_paragraph(
+ chunk,
+ &destination_constraints,
+ &effective_style,
+ ctx.default_line_height,
+ ctx.measure_text,
+ )
+ .emit_full();
+ }
+
+ log::debug!(
+ "[layout] page_chunk[{page_chunk_idx}] col_chunk[{chunk_idx}] placed at y={:.1} x={:.1} height={:.1}",
+ state.cursor_y.raw(),
+ col_x(state.current_col).raw(),
+ para.size.height.raw()
+ );
+ for mut cmd in para.commands {
+ cmd.shift_y(state.cursor_y);
+ cmd.shift_x(col_x(state.current_col));
+ state.current_page.commands.push(cmd);
+ }
+ state.cursor_y += para.size.height;
+ }
+ // #86: mark that content of this paragraph has landed
+ // (either split segments or the atomic block), so a
+ // later block's absolute-float overflow relocates rather
+ // than double-wrapping this already-placed text.
+ paragraph_content_placed |= !chunk.is_empty();
+ }
+ // The page break has been consumed by this non-empty chunk.
+ unresolved_page_break = false;
+ }
+
+ // §17.3.3.1: if the paragraph ended with a page break and
+ // no non-empty chunk followed, defer the break to the next block.
+ if unresolved_page_break {
+ state.pending_page_break = true;
+ }
+
+ state.first_on_section_page = false;
+ state.prev_borders = style.borders.clone();
+ state.prev_space_after = effective_style.space_after;
+ state.prev_style_id = effective_style.style_id.clone();
+ state.prev_table_style_id = None; // paragraph breaks adjacent table chain
+
+ // §20.4.2.3: emit non-wrapTopAndBottom floating images.
+ // (wrapTopAndBottom images were emitted immediately above.)
+ let parity = state.parity();
+ for fi in floating_images {
+ if fi.is_wrap_top_and_bottom() {
+ continue;
+ }
+ let img_y = match fi.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => {
+ para_start_y + effective_style.space_before + offset
+ }
+ };
+ state.current_page.commands.push(DrawCommand::Image {
+ rect: PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ }
+
+ // §20.4.2: emit floating DrawingML shapes after the
+ // paragraph's text so they paint on top (for `behindDoc=0`).
+ // `wrapTopAndBottom` shapes were emitted pre-layout along
+ // with their cursor advance — skip them here.
+ for fs in floating_shapes {
+ if fs.is_wrap_top_and_bottom() {
+ continue;
+ }
+ let shape_y = match fs.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => {
+ para_start_y + effective_style.space_before + offset
+ }
+ };
+ state.current_page.commands.push(DrawCommand::Path {
+ origin: crate::render::geometry::PtOffset::new(
+ fs.x.resolve(parity),
+ shape_y,
+ ),
+ rotation: fs.rotation,
+ flip_h: fs.flip_h,
+ flip_v: fs.flip_v,
+ extent: fs.size,
+ paths: fs.paths.clone(),
+ fill: fs.fill.clone(),
+ stroke: fs.stroke.clone(),
+ effects: fs.effects.clone(),
+ });
+ emit_shape_text(&mut state, fs, shape_y);
+ }
+
+ // Collect footnotes for this page and reduce the available
+ // bottom. A split paragraph already reserved them per segment
+ // (on the page each reference landed on), so skip here.
+ if !footnotes_reserved {
+ reserve_footnotes(&mut state, &ctx, content_width, footnotes);
+ }
+ }
+ LayoutBlock::Table {
+ rows,
+ col_widths,
+ cell_spacing,
+ border_config,
+ indent,
+ alignment,
+ float_info,
+ style_id,
+ } => {
+ // §17.4.58: floating table — render and register as a float so
+ // subsequent text wraps around it. Floating tables are absolutely
+ // positioned and do not participate in adjacent border collapse.
+ if let Some(fi) = float_info {
+ // Run an un-paginated layout once to get the table's
+ // width (for x positioning + alignment overrides) and
+ // total height (for the §17.4.58 page-push heuristic).
+ // The actual emission uses `layout_table_paginated`
+ // below so rows that overflow split across pages.
+ let table = layout_table(
+ rows,
+ col_widths,
+ *cell_spacing,
+ ctx.default_line_height,
+ border_config.as_ref(),
+ ctx.measure_text,
+ false,
+ );
+
+ // §17.4.28 / §17.4.51: compute table x position.
+ let table_x = table_x_offset(
+ *alignment,
+ *indent,
+ table.size.width,
+ content_width,
+ config.margins.left,
+ );
+ // §17.4.58: apply tblpXSpec horizontal alignment override.
+ let table_x = match fi.x_align {
+ Some(crate::model::TableXAlign::Center) => {
+ config.margins.left + (content_width - table.size.width) * 0.5
+ }
+ Some(crate::model::TableXAlign::Right) => {
+ config.margins.left + content_width - table.size.width
+ }
+ _ => table_x,
+ };
+
+ // §17.4.58: anchor-page heuristic — if the cursor isn't
+ // already at top of page and the table won't fit below
+ // it, push the table to the next page before resolving
+ // the anchor. This matches Word's "don't anchor on a
+ // page that's already mostly full" behavior.
+ if state.cursor_y + table.size.height > state.bottom
+ && state.cursor_y > state.page_top
+ {
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ }
+
+ // §17.4.58: resolve `tblpY` on the (possibly new)
+ // current page, then §17.4.57 resolve collisions with
+ // prior floats. On `Spillover`, push to next page and
+ // re-resolve with the new (empty) float list.
+ //
+ // This loop terminates because `Spillover` requires a
+ // collision-induced shift and `push_new_page` clears
+ // `page_floats`: the retry has no floats to collide
+ // with, so it cannot spill again. A table too tall for
+ // the body comes back as `OnCurrentPage` and is sliced
+ // by the pagination call below, never re-resolved.
+ let float_y_start = loop {
+ let requested_y = if fi.y_offset > Pt::ZERO {
+ let anchor_y = match fi.vert_anchor {
+ crate::model::TableAnchor::Text => {
+ state.last_para_start_y + fi.y_offset
+ }
+ crate::model::TableAnchor::Margin => state.page_top + fi.y_offset,
+ crate::model::TableAnchor::Page => fi.y_offset,
+ };
+ anchor_y.max(state.cursor_y)
+ } else {
+ state.cursor_y
+ };
+
+ match resolve_floating_anchor(
+ requested_y,
+ table.size.height,
+ fi.overlap,
+ &state.page_floats,
+ state.bottom,
+ ) {
+ FloatingTableAnchor::OnCurrentPage(y) => break y,
+ FloatingTableAnchor::Shifted { from, to } => {
+ log::debug!(
+ "[layout] shift float past prior (overlap=Never): {:.1} -> {:.1}",
+ from.raw(),
+ to.raw(),
+ );
+ break to;
+ }
+ FloatingTableAnchor::Spillover => {
+ log::debug!(
+ "[layout] float spill to next page (overlap=Never): block_idx={block_idx}",
+ );
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ // Loop: re-resolve on the fresh page (empty
+ // float list, cursor at the selected page top).
+ }
+ }
+ };
+
+ // Floating table breaks the adjacent table chain.
+ state.prev_table_style_id = None;
+
+ // §17.4.58: paginate at row boundaries when the table
+ // would overflow. First slice gets the anchor page's
+ // remaining height (`bottom - float_y_start`);
+ // continuation slices get the selected body height for
+ // each subsequent page.
+ let available_first = (state.bottom - float_y_start).max(Pt::ZERO);
+ let section_page_index = state.page_index;
+ let slices = layout_table_paginated_with_page_heights(
+ rows,
+ col_widths,
+ *cell_spacing,
+ ctx.default_line_height,
+ border_config.as_ref(),
+ ctx.measure_text,
+ TablePaginationHeights {
+ available_height: available_first,
+ suppress_first_row_top: false,
+ page_height_for_slice: |slice_index| {
+ ctx.page_bounds(section_page_index + slice_index).height()
+ },
+ },
+ );
+
+ // §17.4.58: anchor only the first slice; continuation
+ // slices flow at the top of subsequent pages. Encoded
+ // by the `Anchor` / `Continuation` enum variants in
+ // the placement plan.
+ let plan = plan_floating_table_pages_with_page_tops(
+ slices,
+ float_y_start,
+ |slice_index| ctx.page_bounds(section_page_index + slice_index).top,
+ );
+
+ let table_width = table.size.width;
+ for (page_idx, placement) in plan.pages.into_iter().enumerate() {
+ if page_idx > 0 {
+ state.push_new_page(block_idx, &ctx);
+ state.prev_space_after = Pt::ZERO;
+ }
+
+ let (y_start, slice, is_anchor) = match placement {
+ FloatingTablePagePlacement::Anchor { y_start, slice } => {
+ (y_start, slice, true)
+ }
+ FloatingTablePagePlacement::Continuation { y_start, slice } => {
+ (y_start, slice, false)
+ }
+ };
+ let slice_height = slice.size.height;
+
+ for mut cmd in slice.commands {
+ cmd.shift_y(y_start);
+ cmd.shift_x(table_x);
+ state.current_page.commands.push(cmd);
+ }
+
+ // §17.4.56 / §17.4.57: register every slice as a
+ // float on its respective page. The anchor slice
+ // drives text wrapping for body paragraphs that
+ // follow; continuation slices are registered so
+ // subsequent floating tables can see them during
+ // collision resolution (§17.4.57 `tblOverlap`).
+ log::debug!(
+ "[layout] register table float ({}): x={:.1} y={:.1}-{:.1} w={:.1} block_idx={block_idx}",
+ if is_anchor { "anchor" } else { "continuation" },
+ table_x.raw(),
+ y_start.raw(),
+ (y_start + slice_height).raw(),
+ (table_width + fi.right_gap).raw(),
+ );
+ state.page_floats.push(float::ActiveFloat {
+ page_x: table_x,
+ page_y_start: y_start,
+ page_y_end: y_start + slice_height,
+ width: table_width + fi.right_gap,
+ source: float::FloatSource::Table {
+ owner_block_idx: block_idx,
+ },
+ // §17.4.58: floating tables default to
+ // bothSides; no dedicated wrapText
+ // attribute exists for tables.
+ wrap_text: float::WrapTextSide::BothSides,
+ });
+ // Suppress unused warning when `is_anchor` is no
+ // longer the discriminant for registration.
+ let _ = is_anchor;
+ }
+ block_idx += 1;
+ continue;
+ }
+
+ // §17.4.38: consecutive non-floating tables with the same style
+ // are treated as one merged table — the second table's top border
+ // is suppressed so the shared edge is drawn once.
+ let suppress_top = style_id.is_some() && *style_id == state.prev_table_style_id;
+
+ // Non-floating table: paginated row-level splitting.
+ // §17.4.49 / §17.4.1: split at row boundaries, repeat headers.
+ let available = state.bottom - state.cursor_y;
+ let section_page_index = state.page_index;
+ let slices = layout_table_paginated_with_page_heights(
+ rows,
+ col_widths,
+ *cell_spacing,
+ ctx.default_line_height,
+ border_config.as_ref(),
+ ctx.measure_text,
+ TablePaginationHeights {
+ available_height: available,
+ suppress_first_row_top: suppress_top,
+ page_height_for_slice: |slice_index| {
+ ctx.page_bounds(section_page_index + slice_index).height()
+ },
+ },
+ );
+
+ // §17.4.28 / §17.4.51: compute table x position.
+ let table_width: Pt = col_widths.iter().copied().sum();
+ let table_x = table_x_offset(
+ *alignment,
+ *indent,
+ table_width,
+ content_width,
+ config.margins.left,
+ );
+
+ for (slice_idx, slice) in slices.into_iter().enumerate() {
+ if slice_idx > 0 {
+ // Continuation slice — start a new page.
+ state.push_new_page(block_idx, &ctx);
+ }
+ for mut cmd in slice.commands {
+ cmd.shift_y(state.cursor_y);
+ cmd.shift_x(table_x);
+ state.current_page.commands.push(cmd);
+ }
+ state.cursor_y += slice.size.height;
+ }
+ state.first_on_section_page = false;
+ state.prev_borders = None; // table breaks border grouping
+ state.prev_space_after = Pt::ZERO;
+ state.prev_style_id = None;
+ state.prev_table_style_id = style_id.clone();
+ }
+ }
+ block_idx += 1;
+ }
+
+ // Flush remaining footnotes and push the last page.
+ state.finalize(&ctx)
+}
+
+#[cfg(test)]
+mod keep_next_chain_tests {
+ use super::*;
+ use crate::render::layout::paragraph::ParagraphStyle;
+
+ fn paragraph(keep_next: bool, page_break_before: bool) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: Vec::new(),
+ style: ParagraphStyle {
+ keep_next,
+ ..Default::default()
+ },
+ page_break_before,
+ footnotes: Vec::new(),
+ floating_images: Vec::new(),
+ floating_shapes: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn page_break_before_starts_a_new_keep_next_chain() {
+ let blocks = [paragraph(true, false), paragraph(true, true)];
+
+ assert!(starts_keep_next_chain(&blocks, 1));
+ }
+}
+
+/// §17.3.1.14 / §17.3.1.15 — `paragraph_breakable`, the predicate shared by the
+/// placement gate and the keepNext predictor. Extracted precisely because the
+/// two had drifted apart on the footnote condition (E4a#3).
+#[cfg(test)]
+mod paragraph_breakable_tests {
+ use super::*;
+ use crate::render::layout::paragraph::ParagraphStyle;
+
+ fn footnote() -> (Vec<Fragment>, ParagraphStyle) {
+ (Vec::new(), ParagraphStyle::default())
+ }
+
+ fn plain() -> ParagraphStyle {
+ ParagraphStyle::default()
+ }
+
+ #[test]
+ fn a_plain_paragraph_is_breakable() {
+ assert!(paragraph_breakable(&plain(), &[], &[], &[], true));
+ assert!(paragraph_breakable(&plain(), &[], &[], &[], false));
+ }
+
+ #[test]
+ fn keep_lines_forbids_breaking() {
+ let style = ParagraphStyle {
+ keep_lines: true,
+ ..Default::default()
+ };
+ assert!(!paragraph_breakable(&style, &[], &[], &[], true));
+ }
+
+ /// **The condition the keepNext predictor was missing.** Footnotes are
+ /// reserved per segment, but only for a single unbroken chunk — with
+ /// explicit page/column breaks a reference's segment is ambiguous.
+ ///
+ /// Both directions matter: footnotes on one chunk stay breakable (or every
+ /// footnote-bearing paragraph would become atomic), and footnotes across
+ /// several chunks do not.
+ #[test]
+ fn footnotes_are_breakable_only_on_a_single_chunk() {
+ let notes = [footnote()];
+ assert!(
+ paragraph_breakable(&plain(), &notes, &[], &[], true),
+ "footnotes on one unbroken chunk may still split"
+ );
+ assert!(
+ !paragraph_breakable(&plain(), &notes, &[], &[], false),
+ "footnotes spanning page/column chunks keep the atomic reservation"
+ );
+ }
+
+ /// `single_chunk` is irrelevant without footnotes — it must not become a
+ /// blanket restriction on multi-chunk paragraphs.
+ #[test]
+ fn single_chunk_only_matters_when_footnotes_are_present() {
+ assert!(paragraph_breakable(&plain(), &[], &[], &[], false));
+ }
+
+ // ── The predictor's own derivation of `single_chunk` ─────────────────
+
+ use crate::render::geometry::PtSize;
+ use crate::render::layout::fragment::{FontProps, TextMetrics};
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(30.0),
+ trimmed_width: Pt::new(30.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn page_break() -> Fragment {
+ Fragment::PageBreak {
+ line_height: Pt::new(14.0),
+ }
+ }
+
+ /// Six wrapping lines, optionally interrupted by `brk`, optionally carrying
+ /// a footnote.
+ fn keep_next_head(brk: Option<Fragment>, with_footnote: bool) -> LayoutBlock {
+ let mut fragments: Vec<Fragment> = (0..3).map(|i| text_frag(&format!("L{i} "))).collect();
+ if let Some(b) = brk {
+ fragments.push(b);
+ }
+ fragments.extend((3..6).map(|i| text_frag(&format!("L{i} "))));
+ LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle {
+ keep_next: true,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes: if with_footnote {
+ vec![footnote()]
+ } else {
+ Vec::new()
+ },
+ floating_images: Vec::new(),
+ floating_shapes: Vec::new(),
+ }
+ }
+
+ fn splittable(block: &LayoutBlock) -> bool {
+ // Width 40 against 30pt fragments → one line each.
+ let constraints = BoxConstraints::loose(PtSize::new(Pt::new(40.0), Pt::new(1000.0)));
+ leading_keep_next_paragraph_splittable(block, &constraints, Pt::new(14.0), None)
+ }
+
+ /// The predictor must derive `single_chunk` itself, not assume it.
+ ///
+ /// A keepNext-chain head carrying footnotes **across a page break** is not
+ /// splittable: the placement gate will refuse it, so reporting it splittable
+ /// skips the whole-group move and then falls back to atomic anyway — an
+ /// under-filled page. Hard-coding `single_chunk = true` here is precisely
+ /// the bug this closes, and only this test sees it.
+ #[test]
+ fn footnote_bearing_head_with_an_internal_break_is_not_splittable() {
+ // §17.3.3.1 page break and §17.6.3 column break both end a chunk, so
+ // both must be consulted — the derivation is an `&&` of two splitters
+ // and testing only one leaves half of it unverified.
+ for (label, brk) in [
+ ("page break", page_break()),
+ ("column break", Fragment::ColumnBreak),
+ ] {
+ assert!(
+ !splittable(&keep_next_head(Some(brk), true)),
+ "footnotes + an internal {label} → atomic"
+ );
+ }
+ }
+
+ /// The controls, so the test above can't pass for the wrong reason: each
+ /// ingredient alone still permits a split.
+ #[test]
+ fn a_break_or_a_footnote_alone_still_permits_a_split() {
+ assert!(
+ splittable(&keep_next_head(None, true)),
+ "footnotes on a single chunk are fine"
+ );
+ assert!(
+ splittable(&keep_next_head(Some(page_break()), false)),
+ "a page break without footnotes is fine"
+ );
+ assert!(
+ splittable(&keep_next_head(Some(Fragment::ColumnBreak), false)),
+ "a column break without footnotes is fine"
+ );
+ assert!(
+ splittable(&keep_next_head(None, false)),
+ "plain multi-line head is splittable"
+ );
+ }
+}
+
+#[cfg(test)]
+mod paragraph_split_tests {
+ use super::{ParagraphSplit, decide_paragraph_split, prefix_adjusted_head};
+
+ // ── Whole paragraph fits ──────────────────────────────────────────────
+
+ #[test]
+ fn all_lines_fit_is_all() {
+ assert_eq!(
+ decide_paragraph_split(5, 5, true, false),
+ ParagraphSplit::All
+ );
+ // More space than needed also counts as fitting.
+ assert_eq!(
+ decide_paragraph_split(9, 5, true, false),
+ ParagraphSplit::All
+ );
+ }
+
+ // ── Widow/orphan control on (§17.3.1.44) ──────────────────────────────
+
+ #[test]
+ fn widow_control_keeps_two_lines_on_each_side() {
+ // 6 lines, 4 fit: place 4, carry 2 — both sides satisfy the >= 2 rule.
+ assert_eq!(
+ decide_paragraph_split(4, 6, true, false),
+ ParagraphSplit::Break { head: 4 }
+ );
+ }
+
+ #[test]
+ fn widow_control_caps_head_to_leave_a_non_widow_tail() {
+ // 4 lines, 3 fit: placing 3 would strand 1 (widow), so cap head to 2.
+ assert_eq!(
+ decide_paragraph_split(3, 4, true, false),
+ ParagraphSplit::Break { head: 2 }
+ );
+ }
+
+ #[test]
+ fn widow_control_rejects_single_orphan_line_and_moves_whole() {
+ // Only 1 line fits: an orphan. Not at page top → move the whole para.
+ assert_eq!(
+ decide_paragraph_split(1, 6, true, false),
+ ParagraphSplit::MoveWhole
+ );
+ }
+
+ #[test]
+ fn widow_control_three_line_paragraph_cannot_split() {
+ // No head in 1..=2 leaves >= 2 on both sides → move whole.
+ assert_eq!(
+ decide_paragraph_split(2, 3, true, false),
+ ParagraphSplit::MoveWhole
+ );
+ }
+
+ #[test]
+ fn widow_control_paragraph_taller_than_page_splits_two_by_two() {
+ // 10 lines, 4 fit per page: 4 / 4 / 2 across three pages.
+ assert_eq!(
+ decide_paragraph_split(4, 10, true, true),
+ ParagraphSplit::Break { head: 4 }
+ );
+ assert_eq!(
+ decide_paragraph_split(4, 6, true, true),
+ ParagraphSplit::Break { head: 4 }
+ );
+ assert_eq!(
+ decide_paragraph_split(4, 2, true, true),
+ ParagraphSplit::All
+ );
+ }
+
+ // ── Widow control off ─────────────────────────────────────────────────
+
+ #[test]
+ fn without_widow_control_a_single_line_may_split() {
+ assert_eq!(
+ decide_paragraph_split(1, 6, false, false),
+ ParagraphSplit::Break { head: 1 }
+ );
+ assert_eq!(
+ decide_paragraph_split(3, 4, false, false),
+ ParagraphSplit::Break { head: 3 }
+ );
+ }
+
+ #[test]
+ fn without_widow_control_nothing_fits_moves_whole() {
+ assert_eq!(
+ decide_paragraph_split(0, 4, false, false),
+ ParagraphSplit::MoveWhole
+ );
+ }
+
+ // ── Degenerate cases at the page top guarantee progress ────────────────
+
+ #[test]
+ fn at_page_top_unsplittable_paragraph_overflows_whole() {
+ // 3-line paragraph, only 2 fit even on a full page, widow control on:
+ // cannot split legally, already at the top → emit whole (overflow).
+ assert_eq!(
+ decide_paragraph_split(2, 3, true, true),
+ ParagraphSplit::All
+ );
+ }
+
+ #[test]
+ fn at_page_top_single_oversized_line_overflows_whole() {
+ // Even one line does not fit a full page → emit it and overflow.
+ assert_eq!(
+ decide_paragraph_split(0, 1, true, true),
+ ParagraphSplit::All
+ );
+ assert_eq!(
+ decide_paragraph_split(0, 3, false, true),
+ ParagraphSplit::All
+ );
+ }
+
+ // ── §17.3.1.11 drop-cap prefix guard ──────────────────────────────────
+
+ #[test]
+ fn drop_cap_head_clearing_the_prefix_is_unchanged() {
+ // head >= drop_cap_lines: the whole prefix is in the first segment.
+ assert_eq!(prefix_adjusted_head(5, 8, 3, true, true), Some(5));
+ // No drop cap.
+ assert_eq!(prefix_adjusted_head(2, 8, 0, true, false), Some(2));
+ // Single-line drop cap can't be split within.
+ assert_eq!(prefix_adjusted_head(1, 8, 1, true, false), Some(1));
+ // Not the first segment — the prefix is behind us.
+ assert_eq!(prefix_adjusted_head(1, 8, 3, false, false), Some(1));
+ // head == remaining is the whole paragraph (no break inside the prefix).
+ assert_eq!(prefix_adjusted_head(2, 2, 3, true, false), Some(2));
+ }
+
+ #[test]
+ fn drop_cap_break_inside_prefix_moves_whole_when_not_at_top() {
+ // head 2 < drop_cap_lines 3 → tearing the glyph; move the whole para.
+ assert_eq!(prefix_adjusted_head(2, 8, 3, true, false), None);
+ assert_eq!(prefix_adjusted_head(1, 8, 3, true, false), None);
+ }
+
+ #[test]
+ fn drop_cap_break_inside_prefix_overflows_whole_at_top() {
+ // At the page top the prefix can't move up: emit the whole prefix
+ // (drop_cap_lines) and let it overflow, keeping the glyph intact.
+ assert_eq!(prefix_adjusted_head(1, 8, 3, true, true), Some(3));
+ // A paragraph shorter than the prefix clamps to its line count.
+ assert_eq!(prefix_adjusted_head(1, 2, 3, true, true), Some(2));
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/section/mod.rs b/crates/liteparse-docx/src/render/layout/section/mod.rs
new file mode 100644
index 0000000..39403dd
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/section/mod.rs
@@ -0,0 +1,3385 @@
+//! Section layout — sequence blocks vertically into pages.
+//!
+//! Takes measured blocks (paragraphs with fragments, tables with cells),
+//! fits them into pages respecting page size and margins, handles page breaks.
+
+mod floating_table;
+mod helpers;
+mod layout;
+mod stacker;
+mod types;
+
+pub(crate) use layout::SectionStart;
+pub use layout::layout_section;
+pub(crate) use layout::layout_section_with_clearance;
+pub use stacker::{CellLine, StackResult, stack_blocks};
+pub use types::*;
+
+// ── Footnote rendering constants ─────────────────────────────────────────────
+
+/// §17.11.23: footnote separator width as a fraction of the content area.
+/// Word renders the separator at one-third of the text column width.
+const FOOTNOTE_SEPARATOR_RATIO: f32 = 0.33;
+
+/// Thickness of the footnote separator line (pt).
+const FOOTNOTE_SEPARATOR_LINE_WIDTH: crate::render::dimension::Pt =
+ crate::render::dimension::Pt::new(0.5);
+
+/// Vertical gap between the footnote separator and the first footnote paragraph.
+/// Also used as the initial height budget for the separator region (pt).
+const FOOTNOTE_SEPARATOR_GAP: crate::render::dimension::Pt = crate::render::dimension::Pt::new(4.0);
+
+// ── Float deduplication ───────────────────────────────────────────────────────
+
+/// Position tolerance for deduplicating floating images (pt).
+/// Two float entries within this distance on every axis are treated as identical.
+const FLOAT_DEDUP_EPSILON_PT: f32 = 0.1;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::dimension::Pt;
+ use crate::render::geometry::{PtEdgeInsets, PtSize};
+ use crate::render::layout::draw_command::DrawCommand;
+ use crate::render::layout::fragment::Fragment;
+ use crate::render::layout::fragment::{FontProps, TextMetrics};
+ use crate::render::layout::header_footer::HeaderFooterClearance;
+ use crate::render::layout::page::PageConfig;
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::table::{
+ TableBorderConfig, TableBorderLine, TableBorderStyle, TableCellInput, TableRowInput,
+ };
+ use crate::render::resolve::color::RgbColor;
+ use crate::render::resolve::header_footer::HeaderFooterSet;
+ use crate::render::resolve::images::MediaEntry;
+ use std::cell::Cell;
+ use std::rc::Rc;
+ use std::sync::{Mutex, Once};
+
+ struct TableWarningLogger;
+
+ thread_local! {
+ static CAPTURE_TABLE_WARNINGS: Cell<bool> = const { Cell::new(false) };
+ }
+
+ static TABLE_WARNING_LOGGER: TableWarningLogger = TableWarningLogger;
+ static TABLE_WARNING_LOGGER_INIT: Once = Once::new();
+ static TABLE_WARNINGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
+
+ impl log::Log for TableWarningLogger {
+ fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
+ metadata.level() <= log::Level::Warn
+ }
+
+ fn log(&self, record: &log::Record<'_>) {
+ if self.enabled(record.metadata())
+ && record.target().starts_with("dxpdf::render::layout::table")
+ && CAPTURE_TABLE_WARNINGS.with(Cell::get)
+ {
+ TABLE_WARNINGS
+ .lock()
+ .unwrap()
+ .push(record.args().to_string());
+ }
+ }
+
+ fn flush(&self) {}
+ }
+
+ fn capture_table_warnings<T>(run: impl FnOnce() -> T) -> (T, Vec<String>) {
+ TABLE_WARNING_LOGGER_INIT.call_once(|| {
+ log::set_logger(&TABLE_WARNING_LOGGER).unwrap();
+ log::set_max_level(log::LevelFilter::Warn);
+ });
+ TABLE_WARNINGS.lock().unwrap().clear();
+ CAPTURE_TABLE_WARNINGS.with(|capture| capture.set(true));
+ let result = run();
+ CAPTURE_TABLE_WARNINGS.with(|capture| capture.set(false));
+ let warnings = std::mem::take(&mut *TABLE_WARNINGS.lock().unwrap());
+ (result, warnings)
+ }
+
+ fn text_frag(text: &str, width: f32, height: f32) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(height * 0.7),
+ descent: Pt::new(height * 0.3),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn para_block(text: &str, width: f32) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, width, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ fn floating_image(wrap_mode: WrapMode, height: f32) -> FloatingImage {
+ FloatingImage {
+ image_data: MediaEntry {
+ data: std::sync::Arc::from([]),
+ format: crate::model::ImageFormat::Png,
+ },
+ size: PtSize::new(Pt::new(80.0), Pt::new(height)),
+ src_rect: None,
+ x: FloatingImageX::Absolute(Pt::new(10.0)),
+ y: FloatingImageY::RelativeToParagraph(Pt::ZERO),
+ wrap_mode,
+ dist_left: Pt::ZERO,
+ dist_right: Pt::ZERO,
+ behind_doc: false,
+ }
+ }
+
+ fn absolute_floating_image(wrap_mode: WrapMode, y: f32, height: f32) -> FloatingImage {
+ FloatingImage {
+ y: FloatingImageY::Absolute(Pt::new(y)),
+ ..floating_image(wrap_mode, height)
+ }
+ }
+
+ fn styled_para_block(text: &str, keep_next: bool, page_break_before: bool) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, 30.0, 14.0)],
+ style: ParagraphStyle {
+ keep_next,
+ ..Default::default()
+ },
+ page_break_before,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ fn one_column_table(rows: &[(&str, bool)]) -> LayoutBlock {
+ LayoutBlock::Table {
+ rows: rows
+ .iter()
+ .map(|(text, header)| TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![para_block(text, 30.0)],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: Some(*header),
+ cant_split: Some(true),
+ grid_before: 0,
+ border_overrides: None,
+ })
+ .collect(),
+ col_widths: vec![Pt::new(100.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: None,
+ style_id: None,
+ }
+ }
+
+ fn small_config() -> PageConfig {
+ use crate::render::layout::page::ColumnGeometry;
+ PageConfig {
+ page_size: PtSize::new(Pt::new(200.0), Pt::new(100.0)),
+ margins: PtEdgeInsets::new(Pt::new(10.0), Pt::new(10.0), Pt::new(10.0), Pt::new(10.0)),
+ header_margin: Pt::new(5.0),
+ footer_margin: Pt::new(5.0),
+ columns: vec![ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: Pt::new(180.0),
+ }],
+ }
+ }
+
+ /// A `TopAndBottom` float carrying both parity readings, so it emits an
+ /// `Image` command whose x is whatever the page resolved.
+ fn mirrored_floating_image(odd: f32, even: f32) -> FloatingImage {
+ FloatingImage {
+ x: FloatingImageX::PageParity {
+ odd: Pt::new(odd),
+ even: Pt::new(even),
+ },
+ ..floating_image(WrapMode::TopAndBottom, 10.0)
+ }
+ }
+
+ fn para_with_float(text: &str, float: FloatingImage, page_break_before: bool) -> LayoutBlock {
+ let LayoutBlock::Paragraph {
+ fragments,
+ style,
+ footnotes,
+ floating_shapes,
+ ..
+ } = para_block(text, 30.0)
+ else {
+ unreachable!("para_block builds a paragraph")
+ };
+ LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before,
+ footnotes,
+ floating_shapes,
+ floating_images: vec![float],
+ }
+ }
+
+ fn image_xs(page: &crate::render::layout::draw_command::LayoutedPage) -> Vec<f32> {
+ page.commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Image { rect, .. } => Some(rect.origin.x.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// §20.4.3.1: the whole point of deferring x past build. The same anchor
+ /// on two consecutive pages must resolve to the two different readings —
+ /// which is only observable end to end, because `resolve_anchor_x` can be
+ /// perfectly correct while the stacker still ignores what it produced.
+ #[test]
+ fn a_mirrored_float_resolves_per_page() {
+ let blocks = vec![
+ para_with_float("p1", mirrored_floating_image(11.0, 99.0), false),
+ para_with_float("p2", mirrored_floating_image(11.0, 99.0), true),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2, "the page break splits them");
+ assert_eq!(image_xs(&pages[0]), vec![11.0], "page 1 is odd");
+ assert_eq!(image_xs(&pages[1]), vec![99.0], "page 2 is even");
+ }
+
+ /// The parity follows the *logical* page number, so a section that
+ /// `w:pgNumType/@start` begins on an even page mirrors from its first
+ /// page — the same key §17.10.6 uses to pick the even header.
+ #[test]
+ fn parity_follows_the_logical_page_number_not_the_position() {
+ let blocks = vec![para_with_float(
+ "p1",
+ mirrored_floating_image(11.0, 99.0),
+ false,
+ )];
+ let clearance =
+ crate::render::layout::header_footer::HeaderFooterClearance::uniform(&small_config());
+ let pages = super::layout::layout_section_with_clearance(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ super::layout::SectionStart {
+ continuation: None,
+ clearance: &clearance,
+ logical_page_base: 2,
+ },
+ );
+
+ assert_eq!(
+ image_xs(&pages[0]),
+ vec![99.0],
+ "a section starting at logical page 2 starts even"
+ );
+ }
+
+ #[test]
+ fn empty_blocks_produces_one_empty_page() {
+ let pages = layout_section(&[], &small_config(), None, Pt::ZERO, Pt::new(14.0), None);
+ assert_eq!(pages.len(), 1);
+ assert!(pages[0].commands.is_empty());
+ }
+
+ #[test]
+ fn single_paragraph_on_one_page() {
+ let blocks = vec![para_block("hello", 30.0)];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 1);
+ let text_count = pages[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(text_count, 1);
+ }
+
+ // ── §17.3.1.14 keepLines / §17.3.1.44 widow-orphan: across-page splitting ──
+
+ /// A paragraph of `n` words, each ~100pt wide so two never share a line in
+ /// the 180pt content column — i.e. exactly `n` single-line rows.
+ fn multiline_para(n: usize, keep_lines: bool, widow_control: bool) -> LayoutBlock {
+ let fragments = (0..n)
+ .map(|i| text_frag(&format!("word{i} "), 100.0, 14.0))
+ .collect();
+ LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle {
+ keep_lines,
+ widow_control,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ fn text_count(commands: &[DrawCommand]) -> usize {
+ commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count()
+ }
+
+ fn two_column_config() -> PageConfig {
+ use crate::render::layout::page::ColumnGeometry;
+ PageConfig {
+ page_size: PtSize::new(Pt::new(200.0), Pt::new(100.0)),
+ margins: PtEdgeInsets::new(Pt::new(10.0), Pt::new(10.0), Pt::new(10.0), Pt::new(10.0)),
+ header_margin: Pt::new(5.0),
+ footer_margin: Pt::new(5.0),
+ columns: vec![
+ ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: Pt::new(85.0),
+ },
+ ColumnGeometry {
+ x_offset: Pt::new(95.0),
+ width: Pt::new(85.0),
+ },
+ ],
+ }
+ }
+
+ #[test]
+ fn paragraph_splits_across_columns() {
+ // §17.6.4: two 85pt columns, 80pt tall → 5 lines each. A 12-line
+ // paragraph fills column 0, then column 1, then spills to page 2.
+ let fragments: Vec<Fragment> = (0..12)
+ .map(|i| text_frag(&format!("word{i} "), 60.0, 14.0))
+ .collect();
+ let block = LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle {
+ widow_control: false,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let pages = layout_section(
+ &[block],
+ &two_column_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert!(pages.len() >= 2, "12 lines exceed two 5-line columns");
+ let xs: std::collections::BTreeSet<i32> = pages[0]
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.x.raw() as i32),
+ _ => None,
+ })
+ .collect();
+ assert!(xs.contains(&10), "column 0 text at x=10, got {xs:?}");
+ assert!(xs.contains(&105), "column 1 text at x=105, got {xs:?}");
+ }
+
+ fn border_line() -> crate::render::layout::paragraph::BorderLine {
+ crate::render::layout::paragraph::BorderLine {
+ width: Pt::new(1.0),
+ color: RgbColor::BLACK,
+ space: Pt::new(2.0),
+ }
+ }
+
+ #[test]
+ fn tall_paragraph_splits_across_pages() {
+ // 80pt content height / 14pt lines → 5 lines per page. Eight lines must
+ // span two pages, and widow control keeps >= 2 lines on each.
+ let blocks = vec![multiline_para(8, false, true)];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2, "eight lines should not fit on one page");
+ assert_eq!(
+ text_count(&pages[0].commands) + text_count(&pages[1].commands),
+ 8
+ );
+ assert!(
+ text_count(&pages[0].commands) >= 2 && text_count(&pages[1].commands) >= 2,
+ "§17.3.1.44: each side of the split keeps >= 2 lines, got {} + {}",
+ text_count(&pages[0].commands),
+ text_count(&pages[1].commands)
+ );
+ }
+
+ #[test]
+ fn keep_lines_prevents_split() {
+ // Same eight lines, but keepLines set: the paragraph is not split — it
+ // stays whole on the first page (overflowing) rather than paginating.
+ let blocks = vec![multiline_para(8, true, true)];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 1, "§17.3.1.14: keepLines forbids the split");
+ assert_eq!(text_count(&pages[0].commands), 8);
+ }
+
+ #[test]
+ fn widow_control_moves_unsplittable_paragraph_whole() {
+ // Page 1 holds three lines of para 1 (42pt), leaving ~38pt (< 3 lines).
+ // A 3-line paragraph cannot split without a widow, so it moves whole.
+ let blocks = vec![
+ multiline_para(3, false, true),
+ multiline_para(3, false, true),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2);
+ assert_eq!(
+ text_count(&pages[0].commands),
+ 3,
+ "only para 1 fits on page 1"
+ );
+ assert_eq!(
+ text_count(&pages[1].commands),
+ 3,
+ "para 2 moved whole to page 2"
+ );
+ }
+
+ #[test]
+ fn keep_next_paragraph_taller_than_page_still_splits() {
+ // §17.3.1.15: keepNext must not stop a paragraph taller than a page from
+ // splitting (it cannot be "kept with next" on one page regardless). All
+ // content is preserved and the following block trails it — no hang.
+ let fragments: Vec<Fragment> = (0..8)
+ .map(|i| text_frag(&format!("word{i} "), 100.0, 14.0))
+ .collect();
+ let keep = LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle {
+ keep_next: true,
+ widow_control: false,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let next = para_block("next", 40.0);
+ let pages = layout_section(
+ &[keep, next],
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert!(pages.len() >= 2, "the tall keepNext paragraph splits");
+ let total: usize = pages.iter().map(|p| text_count(&p.commands)).sum();
+ assert_eq!(total, 9, "all eight keepNext lines plus the next paragraph");
+ }
+
+ #[test]
+ fn bordered_paragraph_splits_across_pages() {
+ // §17.3.1.24: a bordered paragraph now splits (Phase C) instead of moving
+ // whole — the eight lines span two pages, and each page carries border
+ // draw commands (Line) for its segment of the box.
+ let mut block = multiline_para(8, false, true);
+ if let LayoutBlock::Paragraph { style, .. } = &mut block {
+ style.borders = Some(crate::render::layout::paragraph::ParagraphBorderStyle {
+ top: Some(border_line()),
+ bottom: Some(border_line()),
+ left: Some(border_line()),
+ right: Some(border_line()),
+ });
+ }
+ let pages = layout_section(
+ &[block],
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(
+ pages.len(),
+ 2,
+ "bordered paragraph should split, not overflow"
+ );
+ for page in &pages {
+ assert!(
+ page.commands
+ .iter()
+ .any(|c| matches!(c, DrawCommand::Line { .. })),
+ "each segment draws its part of the border box"
+ );
+ }
+ }
+
+ #[test]
+ fn without_widow_control_paragraph_splits_leaving_single_line() {
+ // Identical layout, but para 2 disables widow control: it now splits,
+ // leaving two lines on page 1 and a single (widow) line on page 2.
+ let blocks = vec![
+ multiline_para(3, false, true),
+ multiline_para(3, false, false),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2);
+ assert_eq!(
+ text_count(&pages[0].commands),
+ 5,
+ "para 1 (3) + first 2 lines of para 2"
+ );
+ assert_eq!(text_count(&pages[1].commands), 1, "the widow line");
+ }
+
+ /// A paragraph whose first `drop_cap_lines` lines are spanned by a drop cap.
+ fn dropcap_para(n: usize, drop_cap_lines: u32) -> LayoutBlock {
+ use crate::render::layout::paragraph::DropCapInfo;
+ let fragments = (0..n)
+ .map(|i| text_frag(&format!("b{i} "), 100.0, 14.0))
+ .collect();
+ let style = ParagraphStyle {
+ // Widow control off so the *natural* break would strand a single
+ // line — which, inside the drop-cap prefix, the guard must prevent.
+ widow_control: false,
+ drop_cap: Some(DropCapInfo {
+ fragments: vec![text_frag("§", 20.0, 30.0)],
+ lines: drop_cap_lines,
+ width: Pt::new(20.0),
+ height: Pt::new(30.0),
+ ascent: Pt::new(28.0),
+ h_space: Pt::ZERO,
+ margin_mode: false,
+ indent: Pt::ZERO,
+ frame_height: None,
+ position_offset: Pt::ZERO,
+ }),
+ ..Default::default()
+ };
+ LayoutBlock::Paragraph {
+ fragments,
+ style,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ fn page_has_dropcap_glyph(page: &crate::render::LayoutedPage) -> bool {
+ page.commands
+ .iter()
+ .any(|c| matches!(c, DrawCommand::Text { text, .. } if text.as_ref() == "§"))
+ }
+
+ fn footnote_ref_frag() -> Fragment {
+ let mut f = text_frag("1", 5.0, 8.0);
+ if let Fragment::Text {
+ is_footnote_ref, ..
+ } = &mut f
+ {
+ *is_footnote_ref = true;
+ }
+ f
+ }
+
+ fn page_has_text(page: &crate::render::LayoutedPage, needle: &str) -> bool {
+ page.commands
+ .iter()
+ .any(|c| matches!(c, DrawCommand::Text { text, .. } if text.as_ref() == needle))
+ }
+
+ #[test]
+ fn footnotes_reserve_on_the_page_of_their_reference() {
+ // §17.11.12: an eight-line paragraph with a footnote reference on line 0
+ // and another on line 7 splits across two pages; each footnote must land
+ // on the page carrying its reference, not both on one page.
+ let mut fragments = vec![text_frag("word0 ", 100.0, 14.0), footnote_ref_frag()];
+ for i in 1..8 {
+ fragments.push(text_frag(&format!("word{i} "), 100.0, 14.0));
+ }
+ fragments.push(footnote_ref_frag()); // reference on the last line
+ let footnotes = vec![
+ (
+ vec![text_frag("FNA", 30.0, 12.0)],
+ ParagraphStyle::default(),
+ ),
+ (
+ vec![text_frag("FNB", 30.0, 12.0)],
+ ParagraphStyle::default(),
+ ),
+ ];
+ let block = LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle {
+ widow_control: false,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes,
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let pages = layout_section(
+ &[block],
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert!(pages.len() >= 2, "the paragraph should split");
+ let last = pages.len() - 1;
+ assert!(
+ page_has_text(&pages[0], "FNA"),
+ "footnote A on its reference's page"
+ );
+ assert!(
+ !page_has_text(&pages[0], "FNB"),
+ "footnote B is not on page 1"
+ );
+ assert!(
+ page_has_text(&pages[last], "FNB"),
+ "footnote B on the last page with its reference"
+ );
+ }
+
+ #[test]
+ fn drop_cap_prefix_is_not_split_across_pages() {
+ // §17.3.1.11: page 1 leaves room for ~1 line after four lines of para 1.
+ // A naive break would put a single line of the drop-cap paragraph on
+ // page 1 and tear the 3-line drop cap. The guard moves the paragraph
+ // whole, so page 1 holds only para 1 and the drop cap lands intact later.
+ let blocks = vec![multiline_para(4, false, false), dropcap_para(6, 3)];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert!(pages.len() >= 2);
+ assert_eq!(
+ text_count(&pages[0].commands),
+ 4,
+ "only para 1 on page 1 — the drop-cap paragraph moved whole"
+ );
+ assert!(
+ !page_has_dropcap_glyph(&pages[0]),
+ "the drop cap must not appear on page 1"
+ );
+ // The drop cap lands on some later page, together with >= 3 body lines
+ // (its prefix), never stranded.
+ let cap_page = pages
+ .iter()
+ .find(|p| page_has_dropcap_glyph(p))
+ .expect("drop cap is emitted on some page");
+ // Body lines on the drop-cap page = text commands minus the glyph;
+ // the 3-line drop-cap prefix stays with the glyph (so > 3 text commands).
+ assert!(
+ text_count(&cap_page.commands) > 3,
+ "the drop-cap prefix (>= 3 lines) stays with the glyph"
+ );
+ }
+
+ #[test]
+ fn text_positioned_at_margins() {
+ let blocks = vec![para_block("hello", 30.0)];
+ let config = small_config();
+ let pages = layout_section(&blocks, &config, None, Pt::ZERO, Pt::new(14.0), None);
+
+ if let Some(DrawCommand::Text { position, .. }) = pages[0].commands.first() {
+ assert!(
+ position.x.raw() >= config.margins.left.raw(),
+ "x should be at least left margin"
+ );
+ assert!(
+ position.y.raw() >= config.margins.top.raw(),
+ "y should be at least top margin"
+ );
+ }
+ }
+
+ #[test]
+ fn page_break_when_content_overflows() {
+ // Page: 100pt tall, margins 10 each → 80pt content area
+ // Each paragraph: 14pt tall
+ // 6 paragraphs = 84pt > 80pt → should break to 2 pages
+ let blocks: Vec<_> = (0..6).map(|i| para_block(&format!("p{i}"), 30.0)).collect();
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2, "should overflow to 2 pages");
+
+ let page1_texts: Vec<_> = pages[0]
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { text, .. } => Some(text.clone()),
+ _ => None,
+ })
+ .collect();
+ let page2_texts: Vec<_> = pages[1]
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { text, .. } => Some(text.clone()),
+ _ => None,
+ })
+ .collect();
+
+ assert_eq!(page1_texts.len(), 5, "5 paras fit on page 1 (5*14=70 < 80)");
+ assert_eq!(page2_texts.len(), 1, "1 para on page 2");
+ }
+
+ #[test]
+ fn each_page_uses_its_selected_header_and_footer_clearance() {
+ let config = small_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ true,
+ false,
+ 1,
+ );
+ let blocks: Vec<_> = (0..5).map(|i| para_block(&format!("p{i}"), 30.0)).collect();
+
+ let pages = layout_section_with_clearance(
+ &blocks,
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ super::layout::SectionStart {
+ continuation: None,
+ clearance: &clearance,
+ logical_page_base: 1,
+ },
+ );
+
+ assert_eq!(pages.len(), 2, "page 2 must use the shorter default slots");
+ let page_texts = pages
+ .iter()
+ .map(|page| {
+ page.commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } => {
+ Some((text.to_string(), position.y))
+ }
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect::<Vec<_>>();
+
+ assert_eq!(
+ page_texts[0].len(),
+ 2,
+ "40pt first-page body fits two lines"
+ );
+ assert_eq!(
+ page_texts[1].len(),
+ 3,
+ "80pt default-page body fits the remainder"
+ );
+ assert!(
+ page_texts[1][0].1 < page_texts[0][0].1,
+ "page 2 body must start at the shorter default-header boundary",
+ );
+ }
+
+ #[test]
+ fn paragraph_moved_to_taller_page_is_relaid_before_following_block() {
+ let config = small_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ true,
+ false,
+ 1,
+ );
+ let moved = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("moved-{i} "), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let pages = layout_section_with_clearance(
+ &[para_block("before", 30.0), moved, para_block("after", 30.0)],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ super::layout::SectionStart {
+ continuation: None,
+ clearance: &clearance,
+ logical_page_base: 1,
+ },
+ );
+
+ assert_eq!(pages.len(), 2);
+ let moved_last_y = pages[1]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("moved-") => {
+ Some(position.y.raw())
+ }
+ _ => None,
+ })
+ .max_by(f32::total_cmp)
+ .expect("moved paragraph text");
+ let after_y = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.as_ref() == "after" => {
+ Some(position.y.raw())
+ }
+ _ => None,
+ })
+ .expect("following paragraph text");
+
+ assert!(
+ after_y > moved_last_y,
+ "following paragraph at {after_y:?} overlaps moved paragraph ending at {moved_last_y:?}",
+ );
+ }
+
+ #[test]
+ fn moved_paragraph_keeps_its_wrap_float_during_destination_relayout() {
+ let config = small_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ true,
+ false,
+ 1,
+ );
+ let moved = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("moved-{i}"), 80.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section_with_clearance(
+ &[para_block("before", 170.0), moved],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ super::layout::SectionStart {
+ continuation: None,
+ clearance: &clearance,
+ logical_page_base: 1,
+ },
+ );
+
+ assert_eq!(pages.len(), 2);
+ let first_moved_x = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("moved-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("moved paragraph text on page 2");
+ assert!(
+ first_moved_x >= Pt::new(90.0),
+ "moved text at {first_moved_x:?} overlaps its 10-90pt float",
+ );
+ }
+
+ #[test]
+ fn moved_absolute_float_relayouts_earlier_source_page_text() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2);
+ assert!(
+ !pages[0]
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. })),
+ "the relocated float must not remain on the source page"
+ );
+ assert!(
+ pages[1]
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. })),
+ "the relocated float must be emitted on the destination page"
+ );
+ let source_positions: Vec<_> = pages[0]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+
+ let owner_x = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("owner-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("owner text on destination page");
+ assert!(
+ owner_x >= Pt::new(90.0),
+ "moved owner text at {owner_x:?} overlaps its 10-90pt float"
+ );
+ }
+
+ #[test]
+ fn leading_inline_page_break_relayouts_source_page_after_float_relocation() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: std::iter::once(Fragment::PageBreak {
+ line_height: Pt::new(14.0),
+ })
+ .chain((0..2).map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0)))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2);
+ let source_positions: Vec<_> = pages[0]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+
+ let owner_x = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("owner-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("owner text on destination page");
+ assert!(
+ owner_x >= Pt::new(90.0),
+ "owner text at {owner_x:?} overlaps its 10-90pt float"
+ );
+ }
+
+ #[test]
+ fn column_break_page_transition_drops_forward_floats_from_previous_page() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: std::iter::once(Fragment::ColumnBreak)
+ .chain((0..4).map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0)))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 3);
+ let source_positions: Vec<_> = pages[1]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+ assert!(
+ pages[2]
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. })),
+ "the relocated float must be emitted on page 3"
+ );
+ }
+
+ #[test]
+ fn nonempty_column_break_does_not_leak_future_float_to_source_page() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: std::iter::once(text_frag("before", 170.0, 14.0))
+ .chain(std::iter::once(Fragment::ColumnBreak))
+ .chain((0..4).map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0)))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 3);
+ let before_x = pages[0]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.as_ref() == "before" => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("text before the column break on page 1");
+ assert_eq!(before_x, Pt::new(10.0));
+ let source_positions: Vec<_> = pages[1]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+ assert!(pages[..2].iter().all(|page| {
+ !page
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. }))
+ }));
+ assert_eq!(
+ pages[2]
+ .commands
+ .iter()
+ .filter(|command| matches!(command, DrawCommand::Image { .. }))
+ .count(),
+ 1
+ );
+ let owner_x = pages[2]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("owner-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("owner text on page 3");
+ assert!(owner_x >= Pt::new(90.0));
+ }
+
+ #[test]
+ fn leading_inline_column_break_relayouts_source_page_after_float_relocation() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: std::iter::once(Fragment::ColumnBreak)
+ .chain((0..2).map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0)))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 2);
+ let source_positions: Vec<_> = pages[0]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+ assert!(
+ !pages[0]
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. }))
+ );
+ assert_eq!(
+ pages[1]
+ .commands
+ .iter()
+ .filter(|command| matches!(command, DrawCommand::Image { .. }))
+ .count(),
+ 1
+ );
+ let owner_x = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("owner-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("owner text on page 2");
+ assert!(owner_x >= Pt::new(90.0));
+ }
+
+ #[test]
+ fn nonempty_page_break_does_not_leak_future_float_to_source_page() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: std::iter::once(text_frag("before", 170.0, 14.0))
+ .chain(std::iter::once(Fragment::PageBreak {
+ line_height: Pt::new(14.0),
+ }))
+ .chain((0..4).map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0)))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 3);
+ let before_x = pages[0]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.as_ref() == "before" => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("text before the page break on page 1");
+ assert_eq!(before_x, Pt::new(10.0));
+ let source_positions: Vec<_> = pages[1]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+ assert!(pages[..2].iter().all(|page| {
+ !page
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. }))
+ }));
+ assert_eq!(
+ pages[2]
+ .commands
+ .iter()
+ .filter(|command| matches!(command, DrawCommand::Image { .. }))
+ .count(),
+ 1
+ );
+ let owner_x = pages[2]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("owner-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("owner text on page 3");
+ assert!(owner_x >= Pt::new(90.0));
+ }
+
+ #[test]
+ fn same_page_column_break_preserves_page_float_state() {
+ use crate::render::layout::page::ColumnGeometry;
+
+ let mut config = small_config();
+ config.columns = vec![
+ ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: Pt::new(85.0),
+ },
+ ColumnGeometry {
+ x_offset: Pt::new(95.0),
+ width: Pt::new(85.0),
+ },
+ ];
+ let source = LayoutBlock::Paragraph {
+ fragments: vec![
+ text_frag("before", 70.0, 14.0),
+ Fragment::ColumnBreak,
+ text_frag("after", 70.0, 14.0),
+ ],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: vec![text_frag("owner", 70.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 1);
+ let before_x = pages[0]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.as_ref() == "before" => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .expect("text in the first column");
+ assert!(before_x >= Pt::new(90.0));
+ for expected in ["before", "after", "owner"] {
+ assert_eq!(
+ pages[0]
+ .commands
+ .iter()
+ .filter(|command| {
+ matches!(command, DrawCommand::Text { text, .. } if text.as_ref() == expected)
+ })
+ .count(),
+ 1
+ );
+ }
+ assert_eq!(
+ pages[0]
+ .commands
+ .iter()
+ .filter(|command| matches!(command, DrawCommand::Image { .. }))
+ .count(),
+ 1
+ );
+ }
+
+ #[test]
+ fn moved_absolute_float_replays_from_first_affected_page_two_paragraph() {
+ let config = small_config();
+ let source = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: true,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[para_block("before", 170.0), source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 3);
+ let source_positions: Vec<_> = pages[1]
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.starts_with("source-") => {
+ Some(position.x)
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(source_positions, vec![Pt::new(10.0); 4]);
+ assert!(
+ pages[2]
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. })),
+ "the relocated float must be emitted on page 3"
+ );
+ }
+
+ #[test]
+ fn moved_absolute_float_does_not_replay_page_start_paragraph() {
+ let config = small_config();
+ let filler = LayoutBlock::Paragraph {
+ fragments: (0..4)
+ .map(|i| text_frag(&format!("filler-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let page_start = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("page-start-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let source = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("source-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+ let owner = LayoutBlock::Paragraph {
+ fragments: (0..2)
+ .map(|i| text_frag(&format!("owner-{i}"), 170.0, 14.0))
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[filler, page_start, source, owner],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 3);
+ let page_start_commands = pages
+ .iter()
+ .flat_map(|page| &page.commands)
+ .filter(|command| {
+ matches!(
+ command,
+ DrawCommand::Text { text, .. } if text.starts_with("page-start-")
+ )
+ })
+ .count();
+ assert_eq!(page_start_commands, 2);
+ }
+
+ #[test]
+ fn moved_paragraph_relocates_top_and_bottom_float_to_destination_page() {
+ let config = small_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ HeaderFooterSet {
+ default: None,
+ first: Some(Pt::new(30.0)),
+ even: None,
+ },
+ true,
+ false,
+ 1,
+ );
+ let moved = LayoutBlock::Paragraph {
+ fragments: vec![text_frag("moved", 170.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![floating_image(WrapMode::TopAndBottom, 30.0)],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section_with_clearance(
+ &[para_block("before", 170.0), moved],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ super::layout::SectionStart {
+ continuation: None,
+ clearance: &clearance,
+ logical_page_base: 1,
+ },
+ );
+
+ assert_eq!(pages.len(), 2);
+ assert!(
+ !pages[0]
+ .commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Image { .. })),
+ "the moved paragraph must not leave its image on page 1",
+ );
+ let image_bottom = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Image { rect, .. } => Some(rect.origin.y + rect.size.height),
+ _ => None,
+ })
+ .expect("top-and-bottom image on page 2");
+ let text_y = pages[1]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Text { text, position, .. } if text.as_ref() == "moved" => {
+ Some(position.y)
+ }
+ _ => None,
+ })
+ .expect("moved paragraph text on page 2");
+ assert!(
+ text_y >= image_bottom,
+ "moved text at {text_y:?} must follow image ending at {image_bottom:?}",
+ );
+ }
+
+ #[test]
+ fn footnotes_render_from_the_selected_footer_boundary_once() {
+ let config = small_config();
+ let clearance = HeaderFooterClearance::new(
+ &config,
+ HeaderFooterSet::default(),
+ HeaderFooterSet {
+ default: Some(Pt::new(30.0)),
+ first: None,
+ even: None,
+ },
+ false,
+ false,
+ 1,
+ );
+ let block = LayoutBlock::Paragraph {
+ fragments: vec![text_frag("body", 30.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![(
+ vec![text_frag("footnote", 30.0, 14.0)],
+ ParagraphStyle::default(),
+ )],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section_with_clearance(
+ &[block],
+ &config,
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ super::layout::SectionStart {
+ continuation: None,
+ clearance: &clearance,
+ logical_page_base: 1,
+ },
+ );
+ let separator_y = pages[0]
+ .commands
+ .iter()
+ .find_map(|command| match command {
+ DrawCommand::Line { line, .. } => Some(line.start.y),
+ _ => None,
+ })
+ .expect("footnote separator");
+
+ assert_eq!(separator_y, Pt::new(52.0));
+ }
+
+ #[test]
+ fn page_size_set_on_layouted_page() {
+ let config = small_config();
+ let pages = layout_section(&[], &config, None, Pt::ZERO, Pt::new(14.0), None);
+ assert_eq!(pages[0].page_size, config.page_size);
+ }
+
+ #[test]
+ fn many_paragraphs_produce_multiple_pages() {
+ // 20 paragraphs at 14pt each = 280pt
+ // Content area = 80pt → need 4 pages (80/14 = 5.7 paras per page)
+ let blocks: Vec<_> = (0..20)
+ .map(|i| para_block(&format!("p{i}"), 30.0))
+ .collect();
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 4);
+ }
+
+ #[test]
+ fn table_on_page() {
+ let blocks = vec![LayoutBlock::Table {
+ rows: vec![TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("cell", 30.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }],
+ col_widths: vec![Pt::new(100.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: None,
+ style_id: None,
+ }];
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert_eq!(pages.len(), 1);
+
+ let text_count = pages[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(text_count, 1);
+ }
+
+ // ── §17.3.1.33 space_before suppression tests ──────────────────────
+
+ #[test]
+ fn space_before_suppressed_for_first_paragraph_of_section() {
+ let style = ParagraphStyle {
+ space_before: Pt::new(24.0),
+ ..Default::default()
+ };
+ let blocks = vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("heading", 50.0, 14.0)],
+ style,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }];
+ let config = small_config();
+ let pages = layout_section(&blocks, &config, None, Pt::ZERO, Pt::new(14.0), None);
+
+ // First paragraph on the section's initial page: space_before suppressed.
+ if let Some(DrawCommand::Text { position, .. }) = pages[0].commands.first() {
+ assert!(
+ position.y.raw() < config.margins.top.raw() + 24.0,
+ "space_before should be suppressed: y={}",
+ position.y.raw()
+ );
+ }
+ }
+
+ #[test]
+ fn space_before_preserved_for_page_break_before() {
+ let heading_style = ParagraphStyle {
+ space_before: Pt::new(24.0),
+ ..Default::default()
+ };
+
+ let blocks = vec![
+ para_block("first page", 30.0),
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("heading", 50.0, 14.0)],
+ style: heading_style,
+ page_break_before: true,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ ];
+ let config = small_config();
+ let pages = layout_section(&blocks, &config, None, Pt::ZERO, Pt::new(14.0), None);
+
+ assert!(pages.len() >= 2, "should have at least 2 pages");
+ let heading_y = pages[1]
+ .commands
+ .iter()
+ .find_map(|c| match c {
+ DrawCommand::Text { position, text, .. } if &**text == "heading" => {
+ Some(position.y)
+ }
+ _ => None,
+ })
+ .expect("heading should be on page 2");
+ // §17.3.1.33: space_before is preserved — pageBreakBefore paragraphs
+ // are not the structural first of the section.
+ assert!(
+ heading_y.raw() > config.margins.top.raw() + 20.0,
+ "space_before should be preserved for pageBreakBefore: y={}",
+ heading_y.raw(),
+ );
+ }
+
+ // ── §17.4.58 — floating-table page overflow ────────────────────────
+ //
+ // A floating table (`<w:tbl>` with `<w:tblpPr>`) that is taller than
+ // the available height on its anchor page must split at row
+ // boundaries and continue on the next page. Word draws the
+ // continuation at the top of the next page's content area; the
+ // `tblpY` anchor applies only to the first slice.
+
+ fn cell_with_text(text: &str) -> TableCellInput {
+ TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, 30.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ }
+ }
+
+ fn row_with_label(label: &str) -> TableRowInput {
+ TableRowInput {
+ cells: vec![cell_with_text(label)],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }
+ }
+
+ /// Build a floating table with `n` rows, anchored to the page at
+ /// `y_offset`. Used by overflow tests below.
+ fn floating_table_with_rows(n: usize, y_offset: f32) -> LayoutBlock {
+ LayoutBlock::Table {
+ rows: (0..n).map(|i| row_with_label(&format!("r{i}"))).collect(),
+ col_widths: vec![Pt::new(100.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: Some(super::TableFloatInfo {
+ right_gap: Pt::ZERO,
+ bottom_gap: Pt::ZERO,
+ x_align: None,
+ y_offset: Pt::new(y_offset),
+ vert_anchor: crate::model::TableAnchor::Page,
+ overlap: None,
+ }),
+ style_id: None,
+ }
+ }
+
+ /// Collect text strings emitted on each page, in order.
+ fn texts_per_page(
+ pages: &[crate::render::layout::draw_command::LayoutedPage],
+ ) -> Vec<Vec<String>> {
+ pages
+ .iter()
+ .map(|p| {
+ p.commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { text, .. } => Some(text.to_string()),
+ _ => None,
+ })
+ .collect()
+ })
+ .collect()
+ }
+
+ #[test]
+ fn keep_next_chain_moves_with_terminal_paragraph() {
+ let mut blocks: Vec<_> = (0..3)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.extend([
+ styled_para_block("heading", true, false),
+ styled_para_block("subheading", true, false),
+ styled_para_block("body", false, false),
+ ]);
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let last = per_page.last().unwrap();
+ assert!(last.iter().any(|text| text == "heading"));
+ assert!(last.iter().any(|text| text == "subheading"));
+ assert!(last.iter().any(|text| text == "body"));
+ }
+
+ #[test]
+ fn keep_next_fit_includes_group_footnotes() {
+ let mut blocks: Vec<_> = (0..3)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.extend([
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("heading", 30.0, 14.0)],
+ style: ParagraphStyle {
+ keep_next: true,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes: vec![(
+ vec![text_frag("footnote", 30.0, 14.0)],
+ ParagraphStyle::default(),
+ )],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ styled_para_block("body", false, false),
+ ]);
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let heading_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "heading"))
+ .expect("heading text");
+ let body_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "body"))
+ .expect("body text");
+
+ assert_eq!(
+ heading_page, body_page,
+ "footnote height must participate in keep-next fit checks",
+ );
+ }
+
+ #[test]
+ fn contextual_keep_next_chain_stays_when_collapsed_spacing_fits() {
+ let mut blocks: Vec<_> = (0..2)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ let style = ParagraphStyle {
+ keep_next: true,
+ contextual_spacing: true,
+ style_id: Some(crate::model::StyleId::new("contextual")),
+ space_before: Pt::new(10.0),
+ space_after: Pt::new(10.0),
+ ..Default::default()
+ };
+ blocks.extend([
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("heading", 30.0, 14.0)],
+ style: style.clone(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("body", 30.0, 14.0)],
+ style: ParagraphStyle {
+ keep_next: false,
+ ..style
+ },
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ ]);
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ assert_eq!(pages.len(), 1);
+ let texts = &texts_per_page(&pages)[0];
+ assert!(texts.iter().any(|text| text == "heading"));
+ assert!(texts.iter().any(|text| text == "body"));
+ }
+
+ #[test]
+ fn contextual_predecessor_allows_keep_next_table_chain_on_fresh_page() {
+ let style = ParagraphStyle {
+ keep_next: true,
+ contextual_spacing: true,
+ style_id: Some(crate::model::StyleId::new("contextual")),
+ space_before: Pt::new(20.0),
+ space_after: Pt::ZERO,
+ ..Default::default()
+ };
+ let mut blocks = vec![
+ para_block("fill", 30.0),
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("predecessor", 30.0, 14.0)],
+ style: ParagraphStyle {
+ keep_next: false,
+ ..style.clone()
+ },
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ ];
+ blocks.extend((0..4).map(|index| LayoutBlock::Paragraph {
+ fragments: vec![text_frag(&format!("chain{index}"), 30.0, 14.0)],
+ style: style.clone(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }));
+ blocks.push(one_column_table(&[("row0", false), ("row1", false)]));
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let heading_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "chain0"))
+ .unwrap();
+ let row0_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "row0"))
+ .unwrap();
+
+ assert_eq!(heading_page, row0_page);
+ }
+
+ #[test]
+ fn keep_next_heading_moves_with_first_table_row() {
+ for header in [false, true] {
+ let mut blocks: Vec<_> = (0..4)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.push(styled_para_block("heading", true, false));
+ blocks.push(one_column_table(&[
+ ("row0", header),
+ ("row1", false),
+ ("row2", false),
+ ]));
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let heading_page = per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == "heading"))
+ .unwrap();
+ let row_page = per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == "row0"))
+ .unwrap();
+ assert_eq!(heading_page, row_page);
+ }
+ }
+
+ #[test]
+ fn keep_next_does_not_move_heading_before_floating_table() {
+ let mut blocks = (0..4)
+ .map(|i| para_block(&format!("filler-{i}"), 30.0))
+ .collect::<Vec<_>>();
+ blocks.push(styled_para_block("heading", true, false));
+ blocks.push(floating_table_with_rows(1, 15.0));
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let heading_page = pages
+ .iter()
+ .position(|page| {
+ page.commands.iter().any(
+ |command| matches!(command, DrawCommand::Text { text, .. } if text.as_ref() == "heading"),
+ )
+ })
+ .expect("heading text");
+
+ assert_eq!(
+ heading_page, 0,
+ "a floating table must not act as the terminal block of a keep-next chain",
+ );
+ }
+
+ #[test]
+ fn keep_next_heading_moves_with_bordered_first_table_row() {
+ let mut blocks: Vec<_> = (0..3)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.push(styled_para_block("heading", true, false));
+ let mut table = one_column_table(&[
+ ("row0", false),
+ ("row1", false),
+ ("row2", false),
+ ("row3", false),
+ ]);
+ if let LayoutBlock::Table { border_config, .. } = &mut table {
+ *border_config = Some(TableBorderConfig {
+ top: None,
+ bottom: None,
+ left: None,
+ right: None,
+ inside_h: Some(TableBorderLine {
+ width: Pt::new(12.0),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ inside_v: None,
+ });
+ }
+ blocks.push(table);
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let heading_page = per_page
+ .iter()
+ .position(|p| p.iter().any(|text| text == "heading"))
+ .unwrap();
+ let row0_page = per_page
+ .iter()
+ .position(|p| p.iter().any(|text| text == "row0"))
+ .unwrap();
+
+ assert_eq!(heading_page, row0_page);
+ assert!(per_page.iter().skip(row0_page + 1).any(|page| {
+ page.iter()
+ .any(|text| text == "row1" || text == "row2" || text == "row3")
+ }));
+ }
+
+ #[test]
+ fn oversized_splittable_first_table_row_does_not_move_heading() {
+ let mut blocks: Vec<_> = (0..4)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.push(styled_para_block("heading", true, false));
+ blocks.push(LayoutBlock::Table {
+ rows: vec![TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: (0..12)
+ .flat_map(|i| {
+ [
+ text_frag(&format!("row0-{i}"), 30.0, 14.0),
+ Fragment::LineBreak {
+ line_height: Pt::new(14.0),
+ },
+ ]
+ })
+ .collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }],
+ col_widths: vec![Pt::new(100.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: None,
+ style_id: None,
+ });
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let heading_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "heading"))
+ .unwrap();
+ let first_row_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "row0-0"))
+ .unwrap();
+
+ assert!(heading_page < first_row_page);
+ let flattened: Vec<_> = per_page.into_iter().flatten().collect();
+ for index in 0..12 {
+ let needle = format!("row0-{index}");
+ assert_eq!(flattened.iter().filter(|text| *text == &needle).count(), 1);
+ }
+ }
+
+ #[test]
+ fn keep_next_heading_stays_before_oversized_leading_vmerge_group() {
+ let mut blocks: Vec<_> = (0..4)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.push(styled_para_block("heading", true, false));
+ blocks.push(LayoutBlock::Table {
+ rows: vec![
+ TableRowInput {
+ cells: vec![
+ TableCellInput {
+ blocks: (0..6)
+ .map(|i| para_block(&format!("restart-{i}"), 30.0))
+ .collect(),
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(
+ crate::render::layout::table::VerticalMergeState::Restart,
+ ),
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ },
+ TableCellInput {
+ blocks: vec![para_block("row0-peer", 30.0)],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ },
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ TableRowInput {
+ cells: vec![
+ TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(
+ crate::render::layout::table::VerticalMergeState::Continue,
+ ),
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ },
+ TableCellInput {
+ blocks: (0..2)
+ .map(|i| para_block(&format!("continuation-{i}"), 30.0))
+ .collect(),
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ },
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ TableRowInput {
+ cells: vec![
+ TableCellInput {
+ blocks: vec![para_block("after-merged", 30.0)],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ },
+ TableCellInput {
+ blocks: vec![para_block("after-peer", 30.0)],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: crate::render::layout::table::CellVAlign::Top,
+ },
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ ],
+ col_widths: vec![Pt::new(50.0), Pt::new(50.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: None,
+ style_id: None,
+ });
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ let heading_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "heading"))
+ .unwrap();
+ let restart_page = per_page
+ .iter()
+ .position(|page| page.iter().any(|text| text == "restart-0"))
+ .unwrap();
+
+ assert_eq!(heading_page, 0);
+ assert!(heading_page < restart_page);
+ let flattened: Vec<_> = per_page.into_iter().flatten().collect();
+ for text in [
+ "restart-0",
+ "restart-1",
+ "restart-2",
+ "restart-3",
+ "restart-4",
+ "restart-5",
+ "row0-peer",
+ "continuation-0",
+ "continuation-1",
+ "after-merged",
+ "after-peer",
+ ] {
+ assert_eq!(
+ flattened
+ .iter()
+ .filter(|candidate| *candidate == text)
+ .count(),
+ 1
+ );
+ }
+ }
+
+ #[test]
+ fn large_table_keep_next_preflight_does_not_probe_later_groups() {
+ let mut blocks: Vec<_> = (0..4)
+ .map(|i| para_block(&format!("fill{i}"), 30.0))
+ .collect();
+ blocks.push(styled_para_block("heading", true, false));
+ blocks.push(LayoutBlock::Table {
+ rows: (0..24)
+ .map(|i| row_with_label(&format!("row{i}")))
+ .collect(),
+ col_widths: vec![Pt::new(100.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: None,
+ style_id: None,
+ });
+
+ let (pages, warnings) = capture_table_warnings(|| {
+ layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ )
+ });
+
+ assert!(
+ warnings.is_empty(),
+ "unexpected table warnings: {warnings:?}"
+ );
+ let flattened: Vec<_> = texts_per_page(&pages).into_iter().flatten().collect();
+ assert_eq!(
+ flattened.iter().filter(|text| *text == "heading").count(),
+ 1
+ );
+ for index in 0..24 {
+ let needle = format!("row{index}");
+ assert_eq!(flattened.iter().filter(|text| *text == &needle).count(), 1);
+ }
+ }
+
+ #[test]
+ fn keep_next_does_not_force_an_entire_multi_page_table() {
+ let blocks = vec![
+ styled_para_block("heading", true, false),
+ one_column_table(&[
+ ("row0", true),
+ ("row1", false),
+ ("row2", false),
+ ("row3", false),
+ ("row4", false),
+ ("row5", false),
+ ]),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert!(pages.len() > 1);
+ assert!(
+ texts_per_page(&pages)[0]
+ .iter()
+ .any(|text| text == "heading")
+ );
+ }
+
+ #[test]
+ fn explicit_page_break_terminates_keep_next_group() {
+ let blocks = vec![
+ styled_para_block("heading", true, false),
+ styled_para_block("forced", false, true),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ assert!(per_page[0].iter().any(|text| text == "heading"));
+ assert!(per_page[1].iter().any(|text| text == "forced"));
+ }
+
+ #[test]
+ fn oversized_keep_next_chain_makes_progress_without_duplicates() {
+ let mut blocks = Vec::new();
+ for index in 0..6 {
+ blocks.push(styled_para_block(
+ &format!("chain{index}"),
+ index < 5,
+ false,
+ ));
+ }
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let flattened: Vec<_> = texts_per_page(&pages).into_iter().flatten().collect();
+ for index in 0..6 {
+ let needle = format!("chain{index}");
+ assert_eq!(flattened.iter().filter(|text| *text == &needle).count(), 1);
+ }
+ }
+
+ // ── §17.3.1.15 keepNext tightening (plan §11.2) ──────────────────────
+
+ /// A `keep_next` paragraph of `n` single-line rows (`{prefix}0..{prefix}{n}`),
+ /// each word wide enough that only one fits per 180pt column line.
+ fn multiline_keep_next(prefix: &str, n: usize) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: (0..n)
+ .map(|i| text_frag(&format!("{prefix}{i}"), 100.0, 14.0))
+ .collect(),
+ style: ParagraphStyle {
+ keep_next: true,
+ ..Default::default()
+ },
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ /// A 180×140pt content area (10 lines at 14pt), for multi-paragraph chains
+ /// that must still fit on a fresh page.
+ fn tall_config() -> PageConfig {
+ use crate::render::layout::page::ColumnGeometry;
+ PageConfig {
+ page_size: PtSize::new(Pt::new(200.0), Pt::new(160.0)),
+ margins: PtEdgeInsets::new(Pt::new(10.0), Pt::new(10.0), Pt::new(10.0), Pt::new(10.0)),
+ header_margin: Pt::new(5.0),
+ footer_margin: Pt::new(5.0),
+ columns: vec![ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: Pt::new(180.0),
+ }],
+ }
+ }
+
+ #[test]
+ fn splittable_leading_keep_next_paragraph_fills_current_page() {
+ // Two fill lines, then a 4-line keepNext paragraph + 1-line terminal
+ // (a 5-line group that fits a fresh page but not the 3 lines left here).
+ // The old whole-group move left this page with only the fill; the
+ // tightening splits the keepNext paragraph so its head fills the page,
+ // and its tail travels to the fresh page WITH the terminal (§17.3.1.15).
+ let mut blocks = vec![para_block("fill0", 100.0), para_block("fill1", 100.0)];
+ blocks.push(multiline_keep_next("kn", 4));
+ blocks.push(para_block("body", 100.0));
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ assert!(pages.len() >= 2);
+
+ // Page 1 is filled with the keepNext paragraph's head, not left blank.
+ assert!(
+ per_page[0].iter().any(|t| t == "kn0"),
+ "leading keepNext paragraph should fill the current page: {per_page:?}"
+ );
+ // The keepNext boundary holds: the paragraph's last line shares a page
+ // with the terminal block.
+ let kn_last = per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == "kn3"))
+ .expect("kn3 present");
+ let body = per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == "body"))
+ .expect("body present");
+ assert_eq!(
+ kn_last, body,
+ "keepNext binds the last line to the next block"
+ );
+ }
+
+ #[test]
+ fn keep_next_chain_leading_split_keeps_all_boundaries() {
+ // A multi-paragraph chain (leading kn 6 lines → middle kn 2 lines →
+ // terminal) that fits a fresh 10-line page but not the 5 lines left
+ // after the fill. The splittable leading paragraph fills the current
+ // page; the remainder is strictly smaller than the fresh-page-fitting
+ // group, so it lands intact on the next page with every keepNext
+ // boundary preserved.
+ let mut blocks: Vec<LayoutBlock> = (0..5)
+ .map(|i| para_block(&format!("fill{i}"), 100.0))
+ .collect();
+ blocks.push(multiline_keep_next("lead", 6));
+ blocks.push(multiline_keep_next("mid", 2));
+ blocks.push(para_block("term", 100.0));
+
+ let pages = layout_section(&blocks, &tall_config(), None, Pt::ZERO, Pt::new(14.0), None);
+ let per_page = texts_per_page(&pages);
+ assert!(pages.len() >= 2);
+
+ assert!(
+ per_page[0].iter().any(|t| t == "lead0"),
+ "leading paragraph head fills the current page: {per_page:?}"
+ );
+ // lead.last ↔ mid.first and mid.last ↔ term must each share a page.
+ let find = |needle: &str| {
+ per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == needle))
+ .unwrap_or_else(|| panic!("{needle} present: {per_page:?}"))
+ };
+ assert_eq!(find("lead5"), find("mid0"), "lead→mid boundary intact");
+ assert_eq!(find("mid1"), find("term"), "mid→term boundary intact");
+ }
+
+ #[test]
+ fn three_line_keep_next_paragraph_moves_whole_under_widow_control() {
+ // A 3-line keepNext paragraph cannot split (widow control needs >= 2
+ // lines on each side), so the tightening must NOT peel it — the whole
+ // group still moves to the fresh page.
+ let mut blocks = vec![para_block("fill0", 100.0), para_block("fill1", 100.0)];
+ blocks.push(multiline_keep_next("kn", 3));
+ blocks.push(para_block("body", 100.0));
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ assert!(pages.len() >= 2);
+ assert!(
+ !per_page[0].iter().any(|t| t == "kn0"),
+ "an unsplittable 3-line keepNext paragraph must move whole: {per_page:?}"
+ );
+ let kn_last = per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == "kn2"))
+ .unwrap();
+ let body = per_page
+ .iter()
+ .position(|p| p.iter().any(|t| t == "body"))
+ .unwrap();
+ assert_eq!(kn_last, body);
+ }
+
+ /// A floating table whose laid-out height exceeds the available
+ /// space on its anchor page must split at row boundaries. With the
+ /// 100pt-tall small_config and an anchor at y=15, 8 rows of ~14pt
+ /// (~112pt total) cannot fit in the 85pt below the anchor — at
+ /// least one row must spill to page 2.
+ #[test]
+ fn floating_table_splits_when_taller_than_anchor_page() {
+ let blocks = vec![floating_table_with_rows(8, 15.0)];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert!(
+ pages.len() >= 2,
+ "overflowing floating table must paginate: got {} pages",
+ pages.len()
+ );
+
+ // The 8 row labels must appear collectively across pages.
+ let per_page = texts_per_page(&pages);
+ let all: Vec<&String> = per_page.iter().flatten().collect();
+ for i in 0..8 {
+ let needle = format!("r{i}");
+ assert!(
+ all.iter().any(|t| t.as_str() == needle),
+ "row {needle} missing from output entirely",
+ );
+ }
+ }
+
+ /// Rows in a paginated floating table do not duplicate: each row
+ /// appears on exactly one page. (This is what fails in the bug —
+ /// the current code emits every row on the anchor page, then
+ /// later content also lands on the anchor page, producing visual
+ /// overdraw.)
+ #[test]
+ fn floating_table_split_rows_do_not_overlap_across_pages() {
+ let blocks = vec![floating_table_with_rows(8, 15.0)];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ let per_page = texts_per_page(&pages);
+ for i in 0..8 {
+ let needle = format!("r{i}");
+ let on_pages: Vec<usize> = per_page
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, page)| {
+ if page.iter().any(|t| t == &needle) {
+ Some(idx)
+ } else {
+ None
+ }
+ })
+ .collect();
+ assert_eq!(
+ on_pages.len(),
+ 1,
+ "row {needle} appeared on pages {on_pages:?}; floating-table rows must not be duplicated",
+ );
+ }
+ }
+
+ /// Build a floating table with `n` rows, anchored to the page at
+ /// `y_offset`, with an explicit `tblOverlap` value.
+ fn floating_table_with_rows_and_overlap(
+ n: usize,
+ y_offset: f32,
+ overlap: Option<crate::model::TableOverlap>,
+ ) -> LayoutBlock {
+ LayoutBlock::Table {
+ rows: (0..n).map(|i| row_with_label(&format!("r{i}"))).collect(),
+ col_widths: vec![Pt::new(100.0)],
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: Some(super::TableFloatInfo {
+ right_gap: Pt::ZERO,
+ bottom_gap: Pt::ZERO,
+ x_align: None,
+ y_offset: Pt::new(y_offset),
+ vert_anchor: crate::model::TableAnchor::Page,
+ overlap,
+ }),
+ style_id: None,
+ }
+ }
+
+ /// §17.4.57: two floating tables both declaring `tblOverlap=Never`
+ /// must not draw at overlapping y-positions on the same page. The
+ /// second table either slides down past the first or spills to
+ /// the next page.
+ ///
+ /// Setup: page 100pt tall, both tables anchored to the same y=15.
+ /// First table (3 rows) fits at y=15; second table (3 rows) with
+ /// Never must NOT draw on top of the first.
+ #[test]
+ fn floating_tables_never_overlap_when_both_set_never() {
+ use crate::model::TableOverlap;
+ let blocks = vec![
+ floating_table_with_rows_and_overlap(3, 15.0, Some(TableOverlap::Never)),
+ floating_table_with_rows_and_overlap(3, 15.0, Some(TableOverlap::Never)),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ // Collect (page_idx, x, y, text) for all rows.
+ let mut row_positions: Vec<(usize, f32, f32, String)> = Vec::new();
+ for (pi, page) in pages.iter().enumerate() {
+ for cmd in &page.commands {
+ if let DrawCommand::Text { text, position, .. } = cmd {
+ if text.starts_with('r') {
+ row_positions.push((
+ pi,
+ position.x.raw(),
+ position.y.raw(),
+ text.to_string(),
+ ));
+ }
+ }
+ }
+ }
+ // Group by page+x bucket; check no two row texts share the same y.
+ // (The bug emits both tables at y=15, so r0/r1/r2 from each table
+ // would land on identical y values.)
+ for i in 0..row_positions.len() {
+ for j in (i + 1)..row_positions.len() {
+ let (pi, xi, yi, ti) = &row_positions[i];
+ let (pj, xj, yj, tj) = &row_positions[j];
+ if pi == pj && (xi - xj).abs() < 1.0 && (yi - yj).abs() < 0.5 {
+ panic!(
+ "two row labels at same position on page {pi}: {ti:?} and {tj:?} both at y={yi}",
+ );
+ }
+ }
+ }
+ }
+
+ /// §17.4.57 governs table-vs-table overlap **only**. A floating
+ /// *image* across the anchor must not push a `tblOverlap=Never`
+ /// table down: the spec defines the setting as "whether the current
+ /// table shall allow other floating **tables** to overlap its
+ /// extents", and Word lets a table sit over an image.
+ ///
+ /// Self-calibrating: the same document is laid out twice, differing
+ /// only in whether the paragraph carries the image float. The table
+ /// must land in the identical place both times. Asserting equality
+ /// rather than a hard-coded y keeps the test honest if page metrics
+ /// or paragraph height ever change.
+ #[test]
+ fn never_overlap_table_is_not_shifted_by_a_floating_image() {
+ use crate::model::TableOverlap;
+
+ // The image spans y = 10..52, straight across the table's y=15
+ // anchor — so a resolver that counted it would shift to y=52.
+ let owner_with_image = LayoutBlock::Paragraph {
+ fragments: vec![text_frag("owner", 30.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![absolute_floating_image(
+ WrapMode::Square(crate::model::WrapText::BothSides),
+ 10.0,
+ 42.0,
+ )],
+ floating_shapes: vec![],
+ };
+ let owner_without_image = LayoutBlock::Paragraph {
+ fragments: vec![text_frag("owner", 30.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+
+ // (page index, y) of the first table row.
+ let first_row_at = |owner: LayoutBlock| -> (usize, f32) {
+ let blocks = vec![
+ owner,
+ floating_table_with_rows_and_overlap(3, 15.0, Some(TableOverlap::Never)),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ pages
+ .iter()
+ .enumerate()
+ .find_map(|(pi, page)| {
+ page.commands.iter().find_map(|cmd| match cmd {
+ DrawCommand::Text { text, position, .. } if &**text == "r0" => {
+ Some((pi, position.y.raw()))
+ }
+ _ => None,
+ })
+ })
+ .expect("first table row is drawn")
+ };
+
+ let (page_with, y_with) = first_row_at(owner_with_image);
+ let (page_without, y_without) = first_row_at(owner_without_image);
+
+ assert_eq!(
+ page_with, page_without,
+ "the image must not push the table onto another page"
+ );
+ assert!(
+ (y_with - y_without).abs() < 0.01,
+ "table moved from y={y_without} to y={y_with} because of an image float; \
+ tblOverlap does not govern images"
+ );
+ }
+
+ /// §17.4.57 default behavior (overlap omitted) — overlap is
+ /// permitted. Two tables at the same anchor on the same page
+ /// DO draw at overlapping y-positions. This is intentional.
+ #[test]
+ fn floating_tables_overlap_by_default() {
+ let blocks = vec![
+ floating_table_with_rows_and_overlap(3, 15.0, None),
+ floating_table_with_rows_and_overlap(3, 15.0, None),
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ // Both tables drawn on page 1; the test verifies that we
+ // don't accidentally shift when overlap is permitted.
+ assert!(!pages.is_empty());
+ let page1_rows: Vec<f32> = pages[0]
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { text, position, .. } if text.starts_with('r') => {
+ Some(position.y.raw())
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ page1_rows.len(),
+ 6,
+ "with overlap permitted, both tables draw on page 1: got {} row entries",
+ page1_rows.len()
+ );
+ }
+
+ /// The continuation slice starts at the top content area on page 2
+ /// (margin.top), not at the original `tblpY` anchor. §17.4.58 only
+ /// anchors the first slice; the continuation flows at the top of
+ /// each subsequent page. Behavioral check: the first text on page
+ /// 2 must sit *higher* on the page than the first text on page 1
+ /// (lower y), because page 1 starts at the anchor (>= margin.top)
+ /// and page 2 starts at margin.top exactly.
+ #[test]
+ fn floating_table_continuation_anchors_at_top_margin() {
+ let blocks = vec![floating_table_with_rows(8, 15.0)];
+ let config = small_config();
+ let pages = layout_section(&blocks, &config, None, Pt::ZERO, Pt::new(14.0), None);
+ assert!(pages.len() >= 2, "test precondition: expected overflow");
+
+ let first_text_y =
+ |page: &crate::render::layout::draw_command::LayoutedPage| -> Option<f32> {
+ page.commands.iter().find_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.y.raw()),
+ _ => None,
+ })
+ };
+ let y_p1 = first_text_y(&pages[0]).expect("page 1 must contain table content");
+ let y_p2 = first_text_y(&pages[1]).expect("page 2 must contain table content");
+ let anchor_y = 15.0;
+ let margin_top = config.margins.top.raw();
+ // Anchor sits at y=15 (> margin.top=10), so the page-1 baseline
+ // is offset by 5pt versus page 2's continuation baseline.
+ assert!(
+ y_p2 < y_p1,
+ "continuation (page 2 first y={y_p2}) must start above the anchor (page 1 first y={y_p1}); anchor={anchor_y}, margin.top={margin_top}",
+ );
+ // Sanity: page 2 first text is within the content area.
+ assert!(y_p2 >= margin_top - 1.0);
+ }
+
+ // ── §17.3.1.24 paragraph border grouping tests ─────────────────────
+
+ #[test]
+ fn identical_borders_suppress_second_top() {
+ use crate::render::layout::paragraph::{BorderLine, ParagraphBorderStyle};
+ let border = Some(ParagraphBorderStyle {
+ top: Some(BorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ space: Pt::new(1.0),
+ }),
+ bottom: None,
+ left: None,
+ right: None,
+ });
+ let style1 = ParagraphStyle {
+ borders: border.clone(),
+ ..Default::default()
+ };
+ let style2 = ParagraphStyle {
+ borders: border,
+ ..Default::default()
+ };
+
+ let blocks = vec![
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("para1", 30.0, 14.0)],
+ style: style1,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag("para2", 30.0, 14.0)],
+ style: style2,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ },
+ ];
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ // Count Line draw commands (border lines).
+ // Only the first paragraph should draw its top border; the second's
+ // top border is suppressed by §17.3.1.24 grouping.
+ let line_cmds: Vec<_> = pages[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Line { .. }))
+ .collect();
+ assert_eq!(
+ line_cmds.len(),
+ 1,
+ "only one top border line (grouped): got {}",
+ line_cmds.len()
+ );
+ }
+
+ // ── §4 continuation re-fit around a next-page float (plan §11.3) ─────
+
+ /// A paragraph carrying one absolute-positioned floating image (left side),
+ /// registered as a `Square` wrap float by the forward scan.
+ fn para_with_abs_left_float(text: &str, fx: f32, fy: f32, fw: f32, fh: f32) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, 20.0, 14.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![FloatingImage {
+ image_data: crate::render::resolve::images::MediaEntry {
+ data: std::sync::Arc::from(&[][..]),
+ format: crate::model::ImageFormat::Png,
+ },
+ size: PtSize::new(Pt::new(fw), Pt::new(fh)),
+ src_rect: None,
+ x: FloatingImageX::Absolute(Pt::new(fx)),
+ y: FloatingImageY::Absolute(Pt::new(fy)),
+ wrap_mode: WrapMode::Square(crate::model::WrapText::BothSides),
+ dist_left: Pt::ZERO,
+ dist_right: Pt::ZERO,
+ behind_doc: false,
+ }],
+ floating_shapes: vec![],
+ }
+ }
+
+ #[test]
+ fn continuation_re_fits_around_a_float_on_its_own_page() {
+ // §4/§11.3: a paragraph splits across a page boundary; a LATER block on
+ // the continuation page owns an absolute float in the top-left. The
+ // continuation's re-fit (not a reuse of the starting-page placement)
+ // must wrap its first lines around that float — they start at the
+ // float's right edge (x≈60), not the page margin (x=10).
+ //
+ // Layout (small_config: content x∈[10,190]? width 180, y∈[10,90]):
+ // - 3 one-line fills push the cursor to y=52 (below the float band).
+ // - P: 6 single-line words (100pt each → one per line at any width
+ // ≥100). Only ~2 fit below the fills on page 1; the rest continue.
+ // - Q: an absolute float x=10,y=10,w=50,h=40 → band y∈[10,50].
+ let float_block = para_with_abs_left_float("Q", 10.0, 10.0, 50.0, 40.0);
+ let mut blocks: Vec<LayoutBlock> = (0..3)
+ .map(|i| para_block(&format!("fill{i}"), 100.0))
+ .collect();
+ blocks.push(multiline_para(6, false, true));
+ blocks.push(float_block);
+
+ let pages = layout_section(
+ &blocks,
+ &small_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+ assert!(pages.len() >= 2, "paragraph must split across pages");
+
+ // First continuation line on page 2 is "word2" (2 words stayed on
+ // page 1). It sits in the float band, so it must be indented past the
+ // float's right edge.
+ let word2_x = pages[1]
+ .commands
+ .iter()
+ .find_map(|c| match c {
+ DrawCommand::Text { text, position, .. } if text.trim() == "word2" => {
+ Some(position.x.raw())
+ }
+ _ => None,
+ })
+ .expect("word2 on page 2");
+ assert!(
+ (word2_x - 60.0).abs() < 0.5,
+ "continuation must wrap around the next-page float (x≈60), got {word2_x}"
+ );
+ }
+
+ // ── §17.6.4 splitting across unequal-width columns (plan §11.4) ──────
+
+ /// Two columns of *unequal* width sharing one 200×100 page: col 0 is 100pt
+ /// wide at the left margin (x=10), col 1 is 70pt wide at x=120.
+ fn unequal_two_column_config() -> PageConfig {
+ use crate::render::layout::page::ColumnGeometry;
+ PageConfig {
+ page_size: PtSize::new(Pt::new(200.0), Pt::new(100.0)),
+ margins: PtEdgeInsets::new(Pt::new(10.0), Pt::new(10.0), Pt::new(10.0), Pt::new(10.0)),
+ header_margin: Pt::new(5.0),
+ footer_margin: Pt::new(5.0),
+ columns: vec![
+ ColumnGeometry {
+ x_offset: Pt::ZERO,
+ width: Pt::new(100.0),
+ },
+ ColumnGeometry {
+ x_offset: Pt::new(110.0),
+ width: Pt::new(70.0),
+ },
+ ],
+ }
+ }
+
+ #[test]
+ fn paragraph_splits_across_unequal_width_columns() {
+ // §11.4: the per-column re-fit (§11.3) removed the equal-width gate, so
+ // a paragraph now flows across columns of different widths. 8 single-
+ // line words (65pt → one per line in both the 100pt and 70pt columns);
+ // ~5 fit in col 0's 80pt height, the rest re-fit into col 1.
+ //
+ // Before the gate was lifted this paragraph was laid out atomically: at
+ // the column top it overflowed col 0 and never reached col 1.
+ let fragments: Vec<Fragment> = (0..8)
+ .map(|i| text_frag(&format!("w{i} "), 65.0, 14.0))
+ .collect();
+ let block = LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ };
+
+ let pages = layout_section(
+ &[block],
+ &unequal_two_column_config(),
+ None,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ );
+
+ // Collect (x, text) across every page.
+ let placed: Vec<(f32, String)> = pages
+ .iter()
+ .flat_map(|p| p.commands.iter())
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, text, .. } => {
+ Some((position.x.raw(), text.trim().to_string()))
+ }
+ _ => None,
+ })
+ .collect();
+
+ assert_eq!(
+ placed.len(),
+ 8,
+ "every word emitted exactly once: {placed:?}"
+ );
+ let in_col0 = placed
+ .iter()
+ .filter(|(x, _)| (*x - 10.0).abs() < 0.5)
+ .count();
+ let in_col1 = placed
+ .iter()
+ .filter(|(x, _)| (*x - 120.0).abs() < 0.5)
+ .count();
+ assert!(
+ in_col0 >= 2,
+ "col 0 (x≈10, 100pt wide) holds the head: {placed:?}"
+ );
+ assert!(
+ in_col1 >= 1,
+ "col 1 (x≈120, 70pt wide) holds the re-fit continuation: {placed:?}"
+ );
+ assert_eq!(
+ in_col0 + in_col1,
+ 8,
+ "all words land in one column or the other"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/section/stacker.rs b/crates/liteparse-docx/src/render/layout/section/stacker.rs
new file mode 100644
index 0000000..c4f0fd9
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/section/stacker.rs
@@ -0,0 +1,900 @@
+//! Shared block stacker — used by both page-level and cell-level layout.
+
+use super::super::draw_command::DrawCommand;
+use super::super::float;
+use super::super::paragraph::place_paragraph;
+use super::super::table::layout_table;
+use super::helpers::table_x_offset;
+use super::types::{FloatingImageY, LayoutBlock, PageParity};
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtRect;
+
+/// One fitted line of stacked cell content, recorded so a §17.4.1 row split can
+/// choose legal cut points from the paragraph structure rather than from raw
+/// draw commands.
+///
+/// Cutting a cell "after this line" flows it and everything below to the
+/// continuation page. Legality mirrors body across-page paragraph splitting:
+/// §17.3.1.14 keepLines and borders/shading/drop-cap paragraphs are never cut
+/// internally, §17.3.1.44 widow/orphan control forbids single-line segments of
+/// a paragraph, and §17.3.1.15 keepNext forbids a cut at a paragraph's trailing
+/// boundary. The [`stack_blocks`] producer leaves the line list empty for any
+/// cell it cannot safely bisect (nested table, floating object).
+#[derive(Debug, Clone)]
+pub struct CellLine {
+ /// Box top of this line, in cell-content coordinates (0 = content top,
+ /// before the cell margin shift applied by `layout_cell`).
+ pub top_y: Pt,
+ /// Index of the paragraph (block) this line belongs to. Lines of one
+ /// paragraph are contiguous and share widow/orphan and keepLines rules; a
+ /// cut may fall between two paragraphs freely (unless the earlier one is
+ /// keepNext).
+ pub para: usize,
+ /// §17.3.1.14 / §17.3.1.24 / §17.3.1.31 / §17.3.1.11: this line's paragraph
+ /// forbids interior splits — keepLines, or a bordered / shaded / drop-cap
+ /// paragraph whose box would be torn. Its lines may still be moved whole to
+ /// the continuation, but never divided among themselves.
+ pub interior_atomic: bool,
+ /// §17.3.1.44: widow/orphan control is active for this paragraph, so an
+ /// interior cut must leave `>= 2` of the paragraph's lines on each side.
+ pub widow_control: bool,
+ /// §17.3.1.15: this line's paragraph is kept with the following block, so a
+ /// cut at the paragraph's trailing boundary is illegal.
+ pub keep_next: bool,
+}
+
+/// Result of stacking blocks vertically.
+pub struct StackResult {
+ /// Draw commands positioned relative to the stacking origin (0,0).
+ pub commands: Vec<DrawCommand>,
+ /// Total height consumed by all blocks.
+ pub height: Pt,
+ /// Per-line cut model for §17.4.1 row splitting (cell-content coords).
+ /// Empty when the content cannot be safely bisected (nested table or
+ /// floating object present) — such cells move whole rather than split.
+ pub lines: Vec<CellLine>,
+}
+
+/// Stack blocks vertically within a fixed-width area.
+///
+/// This is the shared core used by both page-level layout (`layout_section`)
+/// and cell-level layout. It handles:
+/// - Paragraph layout with spacing collapse and space_before suppression
+/// - Table layout
+/// - Floating image registration and text wrapping
+///
+/// It does NOT handle page breaks, column breaks, or footnote collection —
+/// those are page-level concerns managed by `layout_section`.
+///
+/// `parity` resolves §20.4.3.1 `inside`/`outside` float positions, which mirror
+/// on the page the object lands on. Callers that know their page pass its
+/// parity; the table-cell path cannot (see [`layout_cell`]).
+///
+/// [`layout_cell`]: crate::render::layout::cell::layout_cell
+pub fn stack_blocks(
+ blocks: &[LayoutBlock],
+ content_width: Pt,
+ default_line_height: Pt,
+ measure_text: super::super::paragraph::MeasureTextFn<'_>,
+ parity: PageParity,
+) -> StackResult {
+ let constraints = super::super::BoxConstraints::tight_width(content_width, Pt::INFINITY);
+ let mut commands = Vec::new();
+ let mut cursor_y = Pt::ZERO;
+ let mut prev_space_after = Pt::ZERO;
+ let mut prev_style_id: Option<crate::model::StyleId> = None;
+ let mut page_floats: Vec<float::ActiveFloat> = Vec::new();
+ // §17.4.1 row-split model: one entry per fitted line, plus a flag that a
+ // block was encountered which makes the whole cell unsafe to bisect
+ // (nested table or floating object).
+ let mut cell_lines: Vec<CellLine> = Vec::new();
+ let mut splittable = true;
+
+ for (block_index, block) in blocks.iter().enumerate() {
+ match block {
+ LayoutBlock::Paragraph {
+ fragments,
+ style,
+ floating_images,
+ floating_shapes,
+ ..
+ } => {
+ let mut effective_style = style.clone_for_layout();
+
+ // Spacing collapse.
+ if effective_style.contextual_spacing
+ && effective_style.style_id.is_some()
+ && effective_style.style_id == prev_style_id
+ {
+ cursor_y -= prev_space_after + effective_style.space_before;
+ } else {
+ let collapse = prev_space_after.min(effective_style.space_before);
+ cursor_y -= collapse;
+ }
+
+ // Register floating images.
+ let content_top = cursor_y + effective_style.space_before;
+ // Where the paragraph would start with no `TopAndBottom` band,
+ // so the band's effect on the cursor can be told apart from it.
+ let pre_band_cursor = cursor_y;
+ // §20.4.2.18: `wrapTopAndBottom` floats occupy a band of their
+ // own above the paragraph and **stack** — each sits below the
+ // one before it, and the paragraph starts below the whole band.
+ // Tracks the band's running bottom so successive floats don't
+ // all resolve to `content_top` and draw on top of each other.
+ // Shared with the shape loop below, so a `TopAndBottom` image
+ // and shape on the same paragraph stack against each other too.
+ // `None` until the first one is placed, so a single float — and
+ // any negative `wp:posOffset` on it — is positioned exactly as
+ // before.
+ let mut band_bottom: Option<Pt> = None;
+ for fi in floating_images.iter() {
+ let (y_start, y_end) = match fi.y {
+ FloatingImageY::RelativeToParagraph(offset) => {
+ (content_top + offset, content_top + offset + fi.size.height)
+ }
+ FloatingImageY::Absolute(img_y) => (img_y, img_y + fi.size.height),
+ };
+ if fi.is_wrap_top_and_bottom() {
+ let img_y = match fi.y {
+ // Page-absolute floats are positioned by the anchor,
+ // not by the band.
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => {
+ let natural = content_top + offset;
+ match band_bottom {
+ Some(bottom) => natural.max(bottom),
+ None => natural,
+ }
+ }
+ };
+ commands.push(DrawCommand::Image {
+ rect: PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ let bottom = img_y + fi.size.height;
+ band_bottom = Some(match band_bottom {
+ Some(prev) => prev.max(bottom),
+ None => bottom,
+ });
+ if bottom > cursor_y {
+ cursor_y = bottom;
+ }
+ } else if fi.wrap_mode.registers_as_wrap_float() {
+ page_floats.push(float::ActiveFloat {
+ page_x: fi.x.resolve(parity) - fi.dist_left,
+ page_y_start: y_start,
+ page_y_end: y_end,
+ width: fi.size.width + fi.dist_left + fi.dist_right,
+ source: float::FloatSource::Image,
+ wrap_text: fi.wrap_mode.wrap_text().into(),
+ });
+ }
+ }
+
+ // §20.4.2: register floating shapes (DrawingML). Mirrors the
+ // image branch above: `TopAndBottom` emits now and advances
+ // the cursor; wrap-enabled modes (Square/Tight/Through) are
+ // registered as active floats so subsequent lines narrow
+ // around them. `None` shapes emit after the paragraph.
+ for fs in floating_shapes.iter() {
+ use crate::render::layout::section::WrapMode;
+ if matches!(fs.wrap_mode, WrapMode::None) {
+ continue;
+ }
+ let (y_start, y_end) = match fs.y {
+ FloatingImageY::RelativeToParagraph(offset) => {
+ (content_top + offset, content_top + offset + fs.size.height)
+ }
+ FloatingImageY::Absolute(y) => (y, y + fs.size.height),
+ };
+ if fs.is_wrap_top_and_bottom() {
+ // Same band as the images above — see `band_bottom`.
+ let shape_y = match fs.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => {
+ let natural = content_top + offset;
+ match band_bottom {
+ Some(bottom) => natural.max(bottom),
+ None => natural,
+ }
+ }
+ };
+ commands.push(DrawCommand::Path {
+ origin: crate::render::geometry::PtOffset::new(
+ fs.x.resolve(parity),
+ shape_y,
+ ),
+ rotation: fs.rotation,
+ flip_h: fs.flip_h,
+ flip_v: fs.flip_v,
+ extent: fs.size,
+ paths: fs.paths.clone(),
+ fill: fs.fill.clone(),
+ stroke: fs.stroke.clone(),
+ effects: fs.effects.clone(),
+ });
+ let bottom = shape_y + fs.size.height;
+ band_bottom = Some(match band_bottom {
+ Some(prev) => prev.max(bottom),
+ None => bottom,
+ });
+ if bottom > cursor_y {
+ cursor_y = bottom;
+ }
+ } else {
+ page_floats.push(float::ActiveFloat {
+ page_x: fs.x.resolve(parity) - fs.dist_left,
+ page_y_start: y_start,
+ page_y_end: y_end,
+ width: fs.size.width + fs.dist_left + fs.dist_right,
+ source: float::FloatSource::Shape,
+ wrap_text: fs.wrap_mode.wrap_text().into(),
+ });
+ }
+ }
+
+ // §20.4.2.18: the band was placed from `content_top`, which
+ // already includes `space_before`, and the cursor now sits at
+ // the band's bottom. `place_paragraph` applies `space_before`
+ // again inside the paragraph box, so without this the text is
+ // pushed a second `space_before` below the band it is supposed
+ // to sit directly beneath — contradicting the band comment
+ // above ("the paragraph starts below the whole band").
+ //
+ // Only when the band actually moved the cursor: a float with a
+ // negative `wp:posOffset` that resolves above the paragraph
+ // leaves the cursor alone and needs no correction.
+ if cursor_y > pre_band_cursor {
+ cursor_y -= effective_style.space_before;
+ }
+
+ float::prune_floats(&mut page_floats, cursor_y);
+
+ effective_style.page_floats = page_floats.clone();
+ effective_style.page_y = cursor_y;
+ effective_style.page_x = Pt::ZERO;
+ effective_style.page_content_width = content_width;
+
+ let placed = place_paragraph(
+ fragments,
+ &constraints,
+ &effective_style,
+ default_line_height,
+ measure_text,
+ );
+
+ // §17.4.1: record this paragraph's lines for the row-split cut
+ // model. A floating object anchored here makes the whole cell
+ // unsafe to bisect (per-line float offsets depend on absolute
+ // y); a paragraph whose box would tear (keepLines, borders,
+ // shading, drop cap) is kept internally atomic.
+ if !floating_images.is_empty() || !floating_shapes.is_empty() {
+ splittable = false;
+ } else if splittable {
+ let interior_atomic = effective_style.keep_lines
+ || effective_style.borders.is_some()
+ || effective_style.shading.is_some()
+ || effective_style.drop_cap.is_some();
+ let mut line_top = cursor_y + effective_style.space_before;
+ for i in 0..placed.line_count() {
+ cell_lines.push(CellLine {
+ top_y: line_top,
+ para: block_index,
+ interior_atomic,
+ widow_control: effective_style.widow_control,
+ keep_next: effective_style.keep_next,
+ });
+ line_top += placed.line_height(i);
+ }
+ }
+
+ let para = placed.emit_full();
+
+ for mut cmd in para.commands {
+ cmd.shift_y(cursor_y);
+ commands.push(cmd);
+ }
+
+ cursor_y += para.size.height;
+
+ // Emit non-wrapTopAndBottom floating images.
+ let para_content_top = cursor_y - para.size.height + effective_style.space_before;
+ for fi in floating_images {
+ if fi.is_wrap_top_and_bottom() {
+ continue;
+ }
+ let img_y = match fi.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => para_content_top + offset,
+ };
+ commands.push(DrawCommand::Image {
+ rect: PtRect::from_xywh(
+ fi.x.resolve(parity),
+ img_y,
+ fi.size.width,
+ fi.size.height,
+ ),
+ image_data: fi.image_data.clone(),
+ src_rect: fi.src_rect,
+ });
+ // Extend cursor to encompass the image so table cells
+ // expand to contain floating images.
+ let img_bottom = img_y + fi.size.height;
+ if img_bottom > cursor_y {
+ cursor_y = img_bottom;
+ }
+ }
+
+ // Emit floating shapes (DrawingML). `TopAndBottom` shapes
+ // were emitted pre-layout along with the `cursor_y` advance;
+ // skip them here. `None` + Square/Tight/Through emit now at
+ // their resolved anchor position (the shape's bounding rect
+ // is already registered as an active float for wrap modes).
+ for fs in floating_shapes {
+ if fs.is_wrap_top_and_bottom() {
+ continue;
+ }
+ let shape_y = match fs.y {
+ FloatingImageY::Absolute(y) => y,
+ FloatingImageY::RelativeToParagraph(offset) => para_content_top + offset,
+ };
+ commands.push(DrawCommand::Path {
+ origin: crate::render::geometry::PtOffset::new(
+ fs.x.resolve(parity),
+ shape_y,
+ ),
+ rotation: fs.rotation,
+ flip_h: fs.flip_h,
+ flip_v: fs.flip_v,
+ extent: fs.size,
+ paths: fs.paths.clone(),
+ fill: fs.fill.clone(),
+ stroke: fs.stroke.clone(),
+ effects: fs.effects.clone(),
+ });
+ // §17.17.1 / §20.1.2.1.1: shape's text-box content paints
+ // *over* the shape's fill — emit after the path. Each
+ // command is in shape-local coords; shift by the shape's
+ // resolved page origin.
+ for mut cmd in fs.text_commands.iter().cloned() {
+ cmd.shift(fs.x.resolve(parity), shape_y);
+ commands.push(cmd);
+ }
+ }
+
+ prev_space_after = effective_style.space_after;
+ prev_style_id = effective_style.style_id.clone();
+ }
+ LayoutBlock::Table {
+ rows,
+ col_widths,
+ cell_spacing,
+ border_config,
+ indent,
+ alignment,
+ ..
+ } => {
+ // §17.4.1: a nested table can't be cleanly bisected, so the
+ // enclosing cell must move whole (matches `build_row_groups`,
+ // which marks rows with nested tables non-splittable).
+ splittable = false;
+ // stack_blocks is used for table cells and header/footer —
+ // no adjacent table collapse in these contexts.
+ let table = layout_table(
+ rows,
+ col_widths,
+ *cell_spacing,
+ default_line_height,
+ border_config.as_ref(),
+ measure_text,
+ false,
+ );
+
+ let table_x = table_x_offset(
+ *alignment,
+ *indent,
+ table.size.width,
+ content_width,
+ Pt::ZERO,
+ );
+
+ for mut cmd in table.commands {
+ cmd.shift_y(cursor_y);
+ cmd.shift_x(table_x);
+ commands.push(cmd);
+ }
+
+ cursor_y += table.size.height;
+ prev_space_after = Pt::ZERO;
+ prev_style_id = None;
+ }
+ }
+ }
+
+ StackResult {
+ commands,
+ height: cursor_y,
+ lines: if splittable { cell_lines } else { Vec::new() },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::ImageFormat;
+ use crate::model::WrapText;
+ use crate::render::geometry::PtSize;
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::section::{FloatingImage, FloatingImageX, WrapMode};
+ use crate::render::resolve::images::MediaEntry;
+ use std::rc::Rc;
+
+ const LINE: f32 = 14.0;
+
+ fn image(height: f32, wrap: WrapMode, y: FloatingImageY) -> FloatingImage {
+ FloatingImage {
+ image_data: MediaEntry {
+ data: std::sync::Arc::from(&b""[..]),
+ format: ImageFormat::Png,
+ },
+ size: PtSize::new(Pt::new(50.0), Pt::new(height)),
+ src_rect: None,
+ x: FloatingImageX::Absolute(Pt::ZERO),
+ y,
+ wrap_mode: wrap,
+ dist_left: Pt::ZERO,
+ dist_right: Pt::ZERO,
+ behind_doc: false,
+ }
+ }
+
+ fn top_bottom(height: f32) -> FloatingImage {
+ image(
+ height,
+ WrapMode::TopAndBottom,
+ FloatingImageY::RelativeToParagraph(Pt::ZERO),
+ )
+ }
+
+ /// A one-word text fragment, so the paragraph produces a fitted line.
+ fn text_fragment() -> crate::render::layout::fragment::Fragment {
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ Fragment::Text {
+ text: Rc::from("word"),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ width: Pt::new(40.0),
+ trimmed_width: Pt::new(40.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn text_para(style: ParagraphStyle) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![text_fragment()],
+ style,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ fn para(style: ParagraphStyle, images: Vec<FloatingImage>) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![],
+ style,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: images,
+ floating_shapes: vec![],
+ }
+ }
+
+ fn styled(space_before: f32, space_after: f32, style_id: Option<&str>) -> ParagraphStyle {
+ ParagraphStyle {
+ space_before: Pt::new(space_before),
+ space_after: Pt::new(space_after),
+ style_id: style_id.map(crate::model::StyleId::new),
+ ..Default::default()
+ }
+ }
+
+ fn stack(blocks: &[LayoutBlock]) -> StackResult {
+ stack_blocks(blocks, Pt::new(400.0), Pt::new(LINE), None, PageParity::Odd)
+ }
+
+ fn image_ys(result: &StackResult) -> Vec<f32> {
+ result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Image { rect, .. } => Some(rect.origin.y.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ fn text_ys(result: &StackResult) -> Vec<f32> {
+ result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.y.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ // ── §20.4.2.18 wrapTopAndBottom ──────────────────────────────────────
+
+ /// Regression: the float anchor was computed once before the loop, so every
+ /// `wrapTopAndBottom` float on a paragraph resolved to the same y — two of
+ /// them drew on top of each other and the cursor advanced only to the
+ /// tallest. They occupy a band and must stack.
+ #[test]
+ fn multiple_top_and_bottom_floats_stack_instead_of_overlapping() {
+ let result = stack(&[para(
+ ParagraphStyle::default(),
+ vec![top_bottom(30.0), top_bottom(40.0)],
+ )]);
+ assert_eq!(
+ image_ys(&result),
+ vec![0.0, 30.0],
+ "the second float sits below the first"
+ );
+ assert!(
+ (result.height.raw() - (70.0 + LINE)).abs() < 1e-4,
+ "the cursor clears the whole band (30+40) plus the paragraph line, got {}",
+ result.height.raw()
+ );
+ }
+
+ /// A single float is positioned exactly as before the stacking fix.
+ #[test]
+ fn a_single_top_and_bottom_float_is_unchanged() {
+ let result = stack(&[para(ParagraphStyle::default(), vec![top_bottom(30.0)])]);
+ assert_eq!(image_ys(&result), vec![0.0]);
+ assert!((result.height.raw() - (30.0 + LINE)).abs() < 1e-4);
+ }
+
+ /// Page-absolute floats are placed by their anchor, not by the band.
+ #[test]
+ fn absolute_top_and_bottom_floats_are_not_stacked() {
+ let result = stack(&[para(
+ ParagraphStyle::default(),
+ vec![
+ image(
+ 20.0,
+ WrapMode::TopAndBottom,
+ FloatingImageY::Absolute(Pt::new(100.0)),
+ ),
+ image(
+ 20.0,
+ WrapMode::TopAndBottom,
+ FloatingImageY::Absolute(Pt::new(200.0)),
+ ),
+ ],
+ )]);
+ assert_eq!(image_ys(&result), vec![100.0, 200.0], "anchors are honored");
+ }
+
+ /// Wrap-mode floats don't occupy a band above the paragraph — they overlay
+ /// it and the text narrows around them — but the stacked height still grows
+ /// to contain the image, so a table cell expands rather than clipping it.
+ #[test]
+ fn wrapping_floats_extend_the_height_to_contain_the_image() {
+ let result = stack(&[para(
+ ParagraphStyle::default(),
+ vec![image(
+ 60.0,
+ WrapMode::Square(WrapText::BothSides),
+ FloatingImageY::RelativeToParagraph(Pt::ZERO),
+ )],
+ )]);
+ assert!(
+ (result.height.raw() - 60.0).abs() < 1e-4,
+ "height reaches the image bottom, got {}",
+ result.height.raw()
+ );
+ assert_eq!(image_ys(&result), vec![0.0], "anchored at the content top");
+ }
+
+ // ── §17.3.1.9 spacing collapse ───────────────────────────────────────
+
+ /// Adjacent paragraphs collapse to `min(prev_after, before)`, not the sum.
+ #[test]
+ fn adjacent_paragraph_spacing_collapses_to_the_minimum() {
+ let blocks = vec![
+ para(styled(0.0, 10.0, None), vec![]),
+ para(styled(6.0, 0.0, None), vec![]),
+ ];
+ // Two lines + both paragraphs' spacing, less the min(10, 6) = 6 overlap.
+ let expected = LINE + 10.0 + 6.0 + LINE - 6.0;
+ assert!(
+ (stack(&blocks).height.raw() - expected).abs() < 1e-4,
+ "expected {expected}, got {}",
+ stack(&blocks).height.raw()
+ );
+ }
+
+ /// §17.3.1.9: with `contextualSpacing` and a matching style id, the whole
+ /// `prev_after + before` gap is removed rather than collapsed.
+ #[test]
+ fn contextual_spacing_removes_the_gap_between_same_styled_paragraphs() {
+ let mut first = styled(0.0, 10.0, Some("ListParagraph"));
+ first.contextual_spacing = true;
+ let mut second = styled(6.0, 0.0, Some("ListParagraph"));
+ second.contextual_spacing = true;
+
+ let blocks = vec![para(first, vec![]), para(second, vec![])];
+ let expected = LINE + 10.0 + 6.0 + LINE - (10.0 + 6.0);
+ assert!(
+ (stack(&blocks).height.raw() - expected).abs() < 1e-4,
+ "expected {expected}, got {}",
+ stack(&blocks).height.raw()
+ );
+ }
+
+ /// A differing style id makes `contextualSpacing` inapplicable, so the
+ /// ordinary collapse applies instead.
+ #[test]
+ fn contextual_spacing_needs_a_matching_style_id() {
+ let mut first = styled(0.0, 10.0, Some("ListParagraph"));
+ first.contextual_spacing = true;
+ let mut second = styled(6.0, 0.0, Some("Other"));
+ second.contextual_spacing = true;
+
+ let blocks = vec![para(first, vec![]), para(second, vec![])];
+ let expected = LINE + 10.0 + 6.0 + LINE - 6.0;
+ assert!(
+ (stack(&blocks).height.raw() - expected).abs() < 1e-4,
+ "ordinary collapse, expected {expected}, got {}",
+ stack(&blocks).height.raw()
+ );
+ }
+
+ // ── §17.4.1 CellLine cut model ───────────────────────────────────────
+
+ /// One entry per fitted line, tagged with its owning block index.
+ #[test]
+ fn cell_lines_are_recorded_per_paragraph() {
+ let result = stack(&[
+ text_para(ParagraphStyle::default()),
+ text_para(ParagraphStyle::default()),
+ ]);
+ assert_eq!(result.lines.len(), 2, "one fitted line per paragraph");
+ assert_eq!(
+ result.lines.iter().map(|l| l.para).collect::<Vec<_>>(),
+ vec![0, 1],
+ "tagged with the owning block index"
+ );
+ }
+
+ /// A floating object anchored anywhere in the content makes the whole cell
+ /// unsafe to bisect — the cut model is withheld so the row moves whole.
+ #[test]
+ fn a_floating_object_withholds_the_cut_model() {
+ let result = stack(&[
+ text_para(ParagraphStyle::default()),
+ para(ParagraphStyle::default(), vec![top_bottom(20.0)]),
+ ]);
+ assert!(
+ result.lines.is_empty(),
+ "lines are withheld even though the first paragraph was safe"
+ );
+ }
+
+ /// §17.3.1.14 / §17.3.1.24: keepLines and bordered paragraphs may move
+ /// whole but never be divided internally.
+ #[test]
+ fn keep_lines_and_borders_mark_a_paragraph_interior_atomic() {
+ let keep = ParagraphStyle {
+ keep_lines: true,
+ ..Default::default()
+ };
+ let result = stack(&[text_para(ParagraphStyle::default()), text_para(keep)]);
+ assert_eq!(
+ result
+ .lines
+ .iter()
+ .map(|l| l.interior_atomic)
+ .collect::<Vec<_>>(),
+ vec![false, true]
+ );
+ }
+
+ // ── §20.4.2.15 wrapNone ──────────────────────────────────────────────
+
+ fn text_xs(result: &StackResult) -> Vec<f32> {
+ result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.x.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ fn wide_para(images: Vec<FloatingImage>) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: vec![text_fragment(), text_fragment(), text_fragment()],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: images,
+ floating_shapes: vec![],
+ }
+ }
+
+ fn sized_image(width: f32, wrap: WrapMode) -> FloatingImage {
+ let mut i = image(60.0, wrap, FloatingImageY::RelativeToParagraph(Pt::ZERO));
+ i.size = crate::render::geometry::PtSize::new(Pt::new(width), Pt::new(60.0));
+ i
+ }
+
+ /// Regression: a `wrapNone` image was registered as an active wrap float,
+ /// so text narrowed around a drawing that §20.4.2.15 says "shall not cause
+ /// text to wrap — it shall be displayed either in front of or behind the
+ /// text". A 200pt-wide float pushed the text from x=0 to x=200.
+ #[test]
+ fn wrap_none_image_does_not_reflow_text() {
+ let baseline = stack(&[wide_para(vec![])]);
+ let overlaid = stack(&[wide_para(vec![sized_image(200.0, WrapMode::None)])]);
+ assert_eq!(
+ text_xs(&overlaid),
+ text_xs(&baseline),
+ "a wrapNone image overlays the text and must not move it"
+ );
+ }
+
+ /// ...but it is still *drawn*, and still expands the stacked height so a
+ /// table cell contains it. Only the wrap registration was wrong.
+ #[test]
+ fn wrap_none_image_is_still_emitted() {
+ let result = stack(&[wide_para(vec![sized_image(200.0, WrapMode::None)])]);
+ assert_eq!(image_ys(&result), vec![0.0], "the image is painted");
+ assert!(
+ (result.height.raw() - 60.0).abs() < 1e-4,
+ "height still reaches the image bottom, got {}",
+ result.height.raw()
+ );
+ }
+
+ /// The wrap-enabled modes are unaffected — they still narrow the text.
+ #[test]
+ fn wrapping_modes_still_reflow_text() {
+ let baseline = stack(&[wide_para(vec![])]);
+ for wrap in [
+ WrapMode::Square(WrapText::BothSides),
+ WrapMode::Tight(WrapText::BothSides),
+ WrapMode::Through(WrapText::BothSides),
+ ] {
+ let wrapped = stack(&[wide_para(vec![sized_image(200.0, wrap)])]);
+ assert_ne!(
+ text_xs(&wrapped),
+ text_xs(&baseline),
+ "{wrap:?} must still narrow the line"
+ );
+ }
+ }
+
+ /// §20.4.2.18: the paragraph sits **directly** below the band.
+ ///
+ /// The band starts at `content_top` (`cursor_y + space_before`), so the
+ /// spacing is already spent by the time the float is placed;
+ /// `place_paragraph` then applies `space_before` again inside the paragraph
+ /// box. Text landed a second `space_before` below the band — 60.0 for a
+ /// 10pt space and a 30pt float, where the band ends at 40 and the baseline
+ /// belongs at 50.
+ #[test]
+ fn space_before_is_not_applied_twice_around_a_top_and_bottom_band() {
+ const SPACE: f32 = 10.0;
+ const FLOAT_H: f32 = 30.0;
+ const ASCENT: f32 = 10.0;
+
+ let block = LayoutBlock::Paragraph {
+ fragments: vec![text_fragment()],
+ style: styled(SPACE, 0.0, None),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![top_bottom(FLOAT_H)],
+ floating_shapes: vec![],
+ };
+ let result = stack(&[block]);
+
+ assert_eq!(
+ image_ys(&result),
+ vec![SPACE],
+ "the band still starts after space_before"
+ );
+ assert_eq!(
+ text_ys(&result),
+ vec![SPACE + FLOAT_H + ASCENT],
+ "the first line sits directly below the band, not a second space below it"
+ );
+ }
+
+ /// The control: with no band, `space_before` is applied exactly once, so
+ /// the fix must not have removed it outright.
+ #[test]
+ fn space_before_still_applies_without_a_band() {
+ const SPACE: f32 = 10.0;
+ const ASCENT: f32 = 10.0;
+ let result = stack(&[text_para(styled(SPACE, 0.0, None))]);
+ assert_eq!(text_ys(&result), vec![SPACE + ASCENT]);
+ }
+
+ /// A non-`TopAndBottom` float leaves the cursor alone, so it must not
+ /// trigger the correction either.
+ #[test]
+ fn a_square_wrap_float_does_not_change_paragraph_spacing() {
+ const SPACE: f32 = 10.0;
+ const ASCENT: f32 = 10.0;
+ let block = LayoutBlock::Paragraph {
+ fragments: vec![text_fragment()],
+ style: styled(SPACE, 0.0, None),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![image(
+ 30.0,
+ WrapMode::Square(WrapText::BothSides),
+ FloatingImageY::RelativeToParagraph(Pt::ZERO),
+ )],
+ floating_shapes: vec![],
+ };
+ let result = stack(&[block]);
+ assert_eq!(text_ys(&result), vec![SPACE + ASCENT]);
+ }
+
+ /// Two stacked floats consume the space once between them, not once per
+ /// float — the correction is applied after the whole band, not per float.
+ #[test]
+ fn stacked_band_consumes_space_before_only_once() {
+ const SPACE: f32 = 10.0;
+ const ASCENT: f32 = 10.0;
+ let block = LayoutBlock::Paragraph {
+ fragments: vec![text_fragment()],
+ style: styled(SPACE, 0.0, None),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![top_bottom(30.0), top_bottom(40.0)],
+ floating_shapes: vec![],
+ };
+ let result = stack(&[block]);
+ assert_eq!(image_ys(&result), vec![SPACE, SPACE + 30.0]);
+ assert_eq!(
+ text_ys(&result),
+ vec![SPACE + 70.0 + ASCENT],
+ "text sits below the 70pt band, with space_before counted once"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/section/types.rs b/crates/liteparse-docx/src/render/layout/section/types.rs
new file mode 100644
index 0000000..e779bc0
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/section/types.rs
@@ -0,0 +1,397 @@
+//! Pure data types for section layout.
+
+use super::super::draw_command::{LayoutedPage, ResolvedEffect, ResolvedFill, ResolvedStroke};
+use super::super::fragment::Fragment;
+use super::super::paragraph::ParagraphStyle;
+use super::super::table::TableRowInput;
+use crate::model::WrapText;
+use crate::model::dimension::{Dimension, SixtieThousandthDeg};
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtSize;
+use crate::render::resolve::images::MediaEntry;
+use crate::render::resolve::shape_geometry::SubPath;
+
+/// Layout-resolved text wrap mode for a floating drawing.
+///
+/// Derived from the model's `TextWrap` (§20.4.2.14-18) — carries the
+/// per-line side constraint (`wrap_text`) but strips distances, which are
+/// baked into the float's resolved page-coordinate rectangle before
+/// registration.
+///
+/// Tier 1 treats `Tight` and `Through` as spec-compliant placeholders: both
+/// take `Square`'s path exactly — registered as an active float
+/// ([`WrapMode::registers_as_wrap_float`]) and narrowing each line by the
+/// float's bounding rect and the side constraint, never by the polygon the
+/// two modes actually name. Full polygon-aware line fitting is deferred to
+/// Tier 2 and not yet designed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum WrapMode {
+ /// §20.4.2.15 wrapNone — no reflow; drawing paints over or under text.
+ None,
+ /// §20.4.2.17 wrapSquare — text wraps around drawing's bounding box.
+ Square(WrapText),
+ /// §20.4.2.16 wrapTight — text follows drawing's polygon outline.
+ Tight(WrapText),
+ /// §20.4.2.14 wrapThrough — text flows through polygon interior.
+ Through(WrapText),
+ /// §20.4.2.18 wrapTopAndBottom — text stops at drawing top and
+ /// resumes below drawing bottom.
+ TopAndBottom,
+}
+
+impl WrapMode {
+ /// Construct a layout wrap mode from a parsed `TextWrap`.
+ pub fn from_model(wrap: &crate::model::TextWrap) -> Self {
+ use crate::model::TextWrap as T;
+ match wrap {
+ T::None => Self::None,
+ T::Square { wrap_text, .. } => Self::Square(*wrap_text),
+ T::Tight { wrap_text, .. } => Self::Tight(*wrap_text),
+ T::Through { wrap_text, .. } => Self::Through(*wrap_text),
+ T::TopAndBottom { .. } => Self::TopAndBottom,
+ }
+ }
+
+ /// Whether the drawing participates in wrap-around text flow (i.e.,
+ /// should be registered as an active float). `None` and
+ /// `TopAndBottom` don't — None is purely overlay; TopAndBottom is
+ /// handled by advancing `cursor_y` past the drawing on emit.
+ pub fn registers_as_wrap_float(self) -> bool {
+ matches!(self, Self::Square(_) | Self::Tight(_) | Self::Through(_))
+ }
+
+ /// Side constraint for line narrowing. Returns `WrapText::BothSides`
+ /// for modes that don't have one (None / TopAndBottom).
+ pub fn wrap_text(self) -> WrapText {
+ match self {
+ Self::Square(w) | Self::Tight(w) | Self::Through(w) => w,
+ Self::None | Self::TopAndBottom => WrapText::BothSides,
+ }
+ }
+}
+
+/// §17.4.58: positioning data for a floating table.
+#[derive(Debug, Clone)]
+pub struct TableFloatInfo {
+ /// Gap between the table's right edge and surrounding text.
+ pub right_gap: Pt,
+ /// Gap between the table's bottom edge and surrounding text.
+ pub bottom_gap: Pt,
+ /// §17.4.58: horizontal alignment override (tblpXSpec).
+ pub x_align: Option<crate::model::TableXAlign>,
+ /// §17.4.58: absolute Y offset from the vertical anchor.
+ pub y_offset: Pt,
+ /// §17.4.58: vertical anchor reference (text / margin / page).
+ pub vert_anchor: crate::model::TableAnchor,
+ /// §17.4.57 `<w:tblOverlap>` — when present and set to `Never`,
+ /// the layout shifts this table down past prior floating tables
+ /// on the same page rather than letting them overlap. `None` /
+ /// `Some(Overlap)` mean overlap is permitted (the §17.4.57
+ /// default).
+ pub overlap: Option<crate::model::TableOverlap>,
+}
+
+/// A floating (anchor) image to be positioned absolutely on the page.
+#[derive(Clone)]
+pub struct FloatingImage {
+ pub image_data: MediaEntry,
+ pub size: PtSize,
+ /// §20.1.10.48 `a:srcRect` — fractional source crop in `[0, 1]`.
+ pub src_rect: Option<crate::render::geometry::PtRect>,
+ /// Horizontal position, possibly deferred to the page's parity.
+ pub x: FloatingImageX,
+ /// Resolved absolute y position on the page (may be relative to paragraph).
+ pub y: FloatingImageY,
+ /// §20.4.2.14-18: text wrap mode (drives float registration + cursor advance).
+ pub wrap_mode: WrapMode,
+ /// §20.4.2.3 distL/distR: horizontal distance from surrounding text.
+ pub dist_left: Pt,
+ pub dist_right: Pt,
+ /// §20.4.2.3 @behindDoc: image is painted behind document text.
+ pub behind_doc: bool,
+}
+
+impl FloatingImage {
+ /// §20.4.2.18 convenience — kept for call-site ergonomics during the
+ /// wrap-mode rollout. Equivalent to `matches!(self.wrap_mode, WrapMode::TopAndBottom)`.
+ pub fn is_wrap_top_and_bottom(&self) -> bool {
+ matches!(self.wrap_mode, WrapMode::TopAndBottom)
+ }
+}
+
+/// Vertical position for a floating image.
+#[derive(Clone, Copy)]
+pub enum FloatingImageY {
+ /// Absolute page position.
+ Absolute(Pt),
+ /// Relative to the paragraph's y position (offset added to cursor_y).
+ RelativeToParagraph(Pt),
+}
+
+/// §20.4.3.1: which side of a two-sided document a page falls on.
+///
+/// Keyed on the **logical** page number — the one `w:pgNumType/@start` shifts,
+/// and the one §17.10.6 `evenAndOddHeaders` already selects headers by. Sharing
+/// the key keeps a document self-consistent: the page that gets the "even"
+/// header mirrors the same way.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PageParity {
+ Odd,
+ Even,
+}
+
+impl PageParity {
+ /// From a 1-based logical page number.
+ pub fn of_page(logical_page_number: usize) -> Self {
+ if logical_page_number.is_multiple_of(2) {
+ Self::Even
+ } else {
+ Self::Odd
+ }
+ }
+}
+
+/// Horizontal position for a floating object.
+///
+/// `Absolute` is settled during build. `PageParity` cannot be: §20.4.3.1
+/// `inside`/`outside` — both as an alignment and as the `insideMargin` /
+/// `outsideMargin` references — mirror according to the page the object lands
+/// on, and floats are extracted *before* pagination. So the position is carried
+/// as both readings and resolved when a page is assigned.
+///
+/// This mirrors [`FloatingImageY::RelativeToParagraph`], which exists for the
+/// same reason on the other axis: a coordinate the build phase cannot know is
+/// deferred, not guessed.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum FloatingImageX {
+ /// The same x on every page.
+ Absolute(Pt),
+ /// Mirrored — which reading applies depends on the page's [`PageParity`].
+ PageParity { odd: Pt, even: Pt },
+}
+
+impl FloatingImageX {
+ /// Build from the two per-parity readings, collapsing to `Absolute` when
+ /// they agree.
+ ///
+ /// They agree for every anchor that is not `inside`/`outside`, which is
+ /// nearly all of them — so a document with no mirrored anchor carries no
+ /// deferral at all, and the resolver below is a no-op on it.
+ pub fn from_pages(odd: Pt, even: Pt) -> Self {
+ if odd == even {
+ Self::Absolute(odd)
+ } else {
+ Self::PageParity { odd, even }
+ }
+ }
+
+ /// The x this object takes on a page of the given parity.
+ pub fn resolve(self, parity: PageParity) -> Pt {
+ match self {
+ Self::Absolute(x) => x,
+ Self::PageParity { odd, even } => match parity {
+ PageParity::Odd => odd,
+ PageParity::Even => even,
+ },
+ }
+ }
+}
+
+/// A floating (anchor) DrawingML shape to be positioned absolutely on the
+/// page. The geometry is already evaluated into path-local Pt subpaths; the
+/// painter applies origin + rotation + flip.
+///
+/// Parallels `FloatingImage` — the stacker treats them the same way for
+/// placement, differing only in the emitted `DrawCommand` variant.
+#[derive(Clone)]
+pub struct FloatingShape {
+ /// Horizontal position of the shape's top-left, possibly deferred to the
+ /// page's parity.
+ pub x: FloatingImageX,
+ /// Resolved absolute y position on the page.
+ pub y: FloatingImageY,
+ /// Shape bounding-box size in Pt.
+ pub size: PtSize,
+ /// §20.1.7.6 @rot — rotation around the shape's center, in 60000ths
+ /// of a degree.
+ pub rotation: Dimension<SixtieThousandthDeg>,
+ /// §20.1.7.6 @flipH — mirror horizontally.
+ pub flip_h: bool,
+ /// §20.1.7.6 @flipV — mirror vertically.
+ pub flip_v: bool,
+ /// §20.4.2.14-18: text wrap mode.
+ pub wrap_mode: WrapMode,
+ /// §20.4.2.3 distL/distR — horizontal distance from surrounding text.
+ pub dist_left: Pt,
+ pub dist_right: Pt,
+ /// §20.4.2.3 @behindDoc — painted behind document text.
+ pub behind_doc: bool,
+ /// Path subpaths in shape-local Pt (already scaled into `size`).
+ pub paths: Vec<SubPath>,
+ /// Resolved fill.
+ pub fill: ResolvedFill,
+ /// Optional resolved stroke.
+ pub stroke: Option<ResolvedStroke>,
+ /// Resolved post-processing effects (painter may defer all in Tier 0).
+ pub effects: Vec<ResolvedEffect>,
+ /// §17.17.1 / §20.1.2.1.1: pre-laid-out commands for the shape's
+ /// text-box content (`wps:wsp/wps:txbx/w:txbxContent`). Each
+ /// command is in shape-local coordinates; the stacker shifts
+ /// them by the shape's resolved origin (plus body insets, pre-
+ /// applied during sub-layout) and emits them *after* the shape's
+ /// path so the text overlays the fill. Empty for shapes without
+ /// text-box content or whose anchor model isn't supported by the
+ /// sub-layout code yet (page-anchored vertical positions).
+ pub text_commands: Vec<crate::render::layout::draw_command::DrawCommand>,
+}
+
+impl FloatingShape {
+ /// §20.4.2.18 convenience — true when wrap_mode is `TopAndBottom`.
+ pub fn is_wrap_top_and_bottom(&self) -> bool {
+ matches!(self.wrap_mode, WrapMode::TopAndBottom)
+ }
+}
+
+/// A block ready for layout — either a paragraph or a table.
+///
+/// The `Paragraph` variant is intentionally larger than `Table` (it carries
+/// fragments, floats, and resolved style inline). Boxing would add an
+/// allocation per block without a measurable benefit for this codebase,
+/// where the Vec holding these is the dominant allocation.
+#[allow(clippy::large_enum_variant)]
+pub enum LayoutBlock {
+ Paragraph {
+ fragments: Vec<Fragment>,
+ style: ParagraphStyle,
+ /// §17.3.1.23: force a page break before this paragraph.
+ page_break_before: bool,
+ /// Footnotes referenced in this paragraph — rendered at page bottom.
+ footnotes: Vec<(Vec<Fragment>, ParagraphStyle)>,
+ /// §20.4.2.3: floating images anchored to this paragraph.
+ floating_images: Vec<FloatingImage>,
+ /// §14.5 / §20.1.2.2.35: floating DrawingML shapes anchored to this paragraph.
+ floating_shapes: Vec<FloatingShape>,
+ },
+ Table {
+ rows: Vec<TableRowInput>,
+ /// Grid slot widths, already shrunk by `cell_spacing` so the slots plus
+ /// one spacing sum to the table's own width.
+ col_widths: Vec<Pt>,
+ /// §17.4.44 `tblCellSpacing` resolved to points; zero when unset.
+ cell_spacing: Pt,
+ /// §17.4.38: resolved table border configuration.
+ border_config: Option<super::super::table::TableBorderConfig>,
+ /// §17.4.51: table indentation from left margin.
+ indent: Pt,
+ /// §17.4.28: table horizontal alignment.
+ alignment: Option<crate::model::Alignment>,
+ /// §17.4.58: floating table positioning — if present, text wraps around it.
+ float_info: Option<TableFloatInfo>,
+ /// §17.4.38: table style reference for adjacent table border collapse.
+ style_id: Option<crate::model::StyleId>,
+ },
+}
+
+/// §17.6.22: continuation state for `Continuous` section breaks.
+/// Allows a new section to continue on the current page.
+pub struct ContinuationState {
+ pub page: LayoutedPage,
+ pub cursor_y: Pt,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::TextWrap;
+ use crate::model::dimension::Emu;
+ use crate::model::geometry::EdgeInsets;
+
+ fn insets() -> EdgeInsets<Emu> {
+ EdgeInsets::new(
+ Dimension::new(0),
+ Dimension::new(0),
+ Dimension::new(0),
+ Dimension::new(0),
+ )
+ }
+
+ /// The model → layout seam must be **total**: every §20.4.2.14-18 wrap
+ /// type maps to a distinct `WrapMode`, and the per-line side constraint
+ /// survives the conversion (it is the only part of `TextWrap` layout
+ /// still needs — distances are baked into the resolved rect).
+ #[test]
+ fn from_model_maps_every_wrap_type() {
+ assert_eq!(WrapMode::from_model(&TextWrap::None), WrapMode::None);
+ assert_eq!(
+ WrapMode::from_model(&TextWrap::Square {
+ distance: insets(),
+ wrap_text: WrapText::Left,
+ }),
+ WrapMode::Square(WrapText::Left),
+ );
+ assert_eq!(
+ WrapMode::from_model(&TextWrap::Tight {
+ distance: insets(),
+ wrap_text: WrapText::Right,
+ polygon: None,
+ }),
+ WrapMode::Tight(WrapText::Right),
+ );
+ assert_eq!(
+ WrapMode::from_model(&TextWrap::Through {
+ distance: insets(),
+ wrap_text: WrapText::Largest,
+ polygon: None,
+ }),
+ WrapMode::Through(WrapText::Largest),
+ );
+ assert_eq!(
+ WrapMode::from_model(&TextWrap::TopAndBottom {
+ distance_top: Dimension::new(0),
+ distance_bottom: Dimension::new(0),
+ }),
+ WrapMode::TopAndBottom,
+ );
+ }
+
+ /// The predicate that decides whether a drawing narrows surrounding text.
+ /// §20.4.2.15 `wrapNone` is a pure overlay and §20.4.2.18 `wrapTopAndBottom`
+ /// is a block spacer — neither participates. Callers that bypassed this and
+ /// used a bare `else` instead let `wrapNone` images reflow text.
+ #[test]
+ fn only_wrap_enabled_modes_register_as_floats() {
+ for mode in [
+ WrapMode::Square(WrapText::BothSides),
+ WrapMode::Tight(WrapText::BothSides),
+ WrapMode::Through(WrapText::BothSides),
+ ] {
+ assert!(mode.registers_as_wrap_float(), "{mode:?} narrows text");
+ }
+ for mode in [WrapMode::None, WrapMode::TopAndBottom] {
+ assert!(
+ !mode.registers_as_wrap_float(),
+ "{mode:?} must not narrow text"
+ );
+ }
+ }
+
+ /// The side constraint round-trips for wrap-enabled modes; the modes that
+ /// have none report `BothSides`. That fallback is only meaningful because
+ /// non-registering modes never reach a line-narrowing call site — see
+ /// `only_wrap_enabled_modes_register_as_floats`.
+ #[test]
+ fn wrap_text_round_trips_and_defaults_to_both_sides() {
+ for side in [
+ WrapText::BothSides,
+ WrapText::Left,
+ WrapText::Right,
+ WrapText::Largest,
+ ] {
+ assert_eq!(WrapMode::Square(side).wrap_text(), side);
+ assert_eq!(WrapMode::Tight(side).wrap_text(), side);
+ assert_eq!(WrapMode::Through(side).wrap_text(), side);
+ }
+ assert_eq!(WrapMode::None.wrap_text(), WrapText::BothSides);
+ assert_eq!(WrapMode::TopAndBottom.wrap_text(), WrapText::BothSides);
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/borders.rs b/crates/liteparse-docx/src/render/layout/table/borders.rs
new file mode 100644
index 0000000..82edbf9
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/borders.rs
@@ -0,0 +1,1081 @@
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtRect;
+
+use super::types::{
+ CellBorderOverride, TableBorderConfig, TableBorderLine, TableBorderStyle, TableCellInput,
+};
+use crate::render::layout::draw_command::DrawCommand;
+
+/// One cell edge during and after §17.4.38 resolution.
+///
+/// Three states rather than `Option<TableBorderLine>`, because [MS-OI29500]
+/// §17.4.66 distinguishes "nothing said about this edge" from "declared
+/// `val="nil"`". The difference is entirely about **inheritance**: an omitted
+/// or `none` edge falls back to the table style, then `tblPrEx`, then
+/// `tblBorders`; `nil` declines that fallback and stays empty.
+///
+/// It is *not* about outranking the facing cell. `nil` removes this cell's
+/// border and nothing else — see [`resolve_border_conflict`].
+///
+/// The distinction survives resolution for one downstream reader: the page-split
+/// top-border restore in `emit.rs` may revive an `Absent` top but must not
+/// revive a `Suppressed` one. For painting they are identical, which is what
+/// [`CellEdge::line`] expresses.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(super) enum CellEdge {
+ /// Nothing said about this edge — or it was declared `val="none"`, which
+ /// §17.4.66 treats identically. Inherits, then yields.
+ Absent,
+ /// Declared `val="nil"`: no border here, and no inheritance either.
+ Suppressed,
+ /// A border to resolve against the opposing edge, and paint if it wins.
+ Line(TableBorderLine),
+}
+
+impl CellEdge {
+ /// The line to paint, if any. Both `Absent` and `Suppressed` paint nothing.
+ pub(super) fn line(self) -> Option<TableBorderLine> {
+ match self {
+ Self::Line(l) => Some(l),
+ Self::Absent | Self::Suppressed => None,
+ }
+ }
+
+ /// Whether two *resolved* edges paint the same thing.
+ ///
+ /// Not `==`: by this point the `Absent`/`Suppressed` distinction is not
+ /// observable to the painter, and letting it in would split a run of columns
+ /// that paints one continuous line. Callers asking "can one cell draw this
+ /// whole span in a single stroke?" mean *this* question.
+ pub(super) fn paints_same(self, other: Self) -> bool {
+ self.line() == other.line()
+ }
+}
+
+impl From<Option<TableBorderLine>> for CellEdge {
+ /// Table-level borders have no way to express `nil` — an edge is either
+ /// configured or not — so an absent one is `Absent`, never `Suppressed`.
+ fn from(b: Option<TableBorderLine>) -> Self {
+ match b {
+ Some(l) => Self::Line(l),
+ None => Self::Absent,
+ }
+ }
+}
+
+/// Resolved borders for one cell.
+#[derive(Clone)]
+pub(super) struct CellBorders {
+ pub(super) top: CellEdge,
+ pub(super) bottom: CellEdge,
+ pub(super) left: CellEdge,
+ pub(super) right: CellEdge,
+}
+
+/// §17.4.38 / §17.7.6: resolve effective borders for a cell.
+/// Per-cell borders (from conditional formatting) override table-level borders.
+/// Table-level insideH/insideV are mapped to cell edges based on position.
+///
+/// `cell_grid_col` is the cell's absolute starting grid column (accounting
+/// for the row's `gridBefore`); `cell_grid_span` is its `gridSpan` (≥1);
+/// `num_grid_cols` is the table-wide grid column count. Together these
+/// determine whether the cell is at the table's left or right edge — which
+/// matters because §17.4.17/§17.4.16 (`gridBefore`/`gridAfter`) can leave
+/// the row's first/last cell *not* at the table edge.
+pub(super) fn resolve_cell_effective_borders(
+ cell: &TableCellInput,
+ table_borders: Option<&TableBorderConfig>,
+ row_idx: usize,
+ cell_grid_col: usize,
+ cell_grid_span: usize,
+ num_rows: usize,
+ num_grid_cols: usize,
+) -> (CellEdge, CellEdge, CellEdge, CellEdge) {
+ // Start with table-level borders mapped to cell edges.
+ let tb = table_borders;
+ let is_first_row = row_idx == 0;
+ // `row_idx + 1 == num_rows`, not `row_idx == num_rows - 1`: the latter
+ // underflows on an empty table. No caller passes `num_rows == 0` today, but
+ // the parameter is free and the guard would live entirely in the callers.
+ let is_last_row = row_idx + 1 == num_rows;
+ let is_first_col = cell_grid_col == 0;
+ let is_last_col = cell_grid_col + cell_grid_span >= num_grid_cols;
+
+ let mut top: CellEdge = if is_first_row {
+ tb.and_then(|b| b.top)
+ } else {
+ tb.and_then(|b| b.inside_h)
+ }
+ .into();
+ let mut bottom: CellEdge = if is_last_row {
+ tb.and_then(|b| b.bottom)
+ } else {
+ tb.and_then(|b| b.inside_h)
+ }
+ .into();
+ let mut left: CellEdge = if is_first_col {
+ tb.and_then(|b| b.left)
+ } else {
+ tb.and_then(|b| b.inside_v)
+ }
+ .into();
+ let mut right: CellEdge = if is_last_col {
+ tb.and_then(|b| b.right)
+ } else {
+ tb.and_then(|b| b.inside_v)
+ }
+ .into();
+
+ // Per-cell overrides. Only `nil` and a real border reach here — an explicit
+ // `none` was mapped to "no override" upstream (§17.4.66: it inherits
+ // exactly like an omitted edge), so it correctly leaves the table-level
+ // border above untouched instead of erasing it.
+ if let Some(ref cb) = cell.cell_borders {
+ if let Some(v) = &cb.top {
+ top = resolve_override(v);
+ }
+ if let Some(v) = &cb.bottom {
+ bottom = resolve_override(v);
+ }
+ if let Some(v) = &cb.left {
+ left = resolve_override(v);
+ }
+ if let Some(v) = &cb.right {
+ right = resolve_override(v);
+ }
+ }
+
+ (top, bottom, left, right)
+}
+
+/// Resolve a border conflict between two competing borders on a shared edge.
+/// Returns the winning border (or `None` if both are `None`).
+///
+/// The algorithm is **not in ISO/IEC 29500-1** — the standard only says a method
+/// exists. It is spelled out in [MS-OI29500] §17.4.66 (`tcBorders`, note a),
+/// which is the authority for every step below:
+/// 1. An edge with no border yields to one that has it. `none` counts as
+/// no border, per *"If the conflicting table cell border is `none` (no
+/// border), then the opposing border shall be displayed."*
+/// 2. Weight = width in eighths of a point × style number. Higher wins.
+/// 3. Equal weight: the style **earlier in the spec's precedence list** wins —
+/// `Single` over `Double`. See `style_precedence_index`.
+/// 4. Equal style: darker colour wins (`R+B+2G`, then `B+2G`, then `G`).
+///
+/// **What `nil` does, and what it does not.** The note adds *"If the conflicting
+/// table cell border is `nil`, then no border shall be displayed"*, which reads
+/// as `nil` beating everything on the far side of the edge. It does not, and
+/// implementing it that way deleted borders Word draws. `nil` acts on **its own
+/// cell only**: it is how a cell declines the inheritance the note describes one
+/// step earlier (style → `tblPrEx` → `tblBorders`), which is the whole of its
+/// difference from `none`. The facing cell's border is untouched, so
+/// `Suppressed` yields here exactly like `Absent`.
+///
+/// Three independent facts in `IP 05 Trenches` fix the reading, and no evidence
+/// contradicts it:
+///
+/// * a cell declaring `<w:bottom w:val="single"/>` above one declaring
+/// `<w:top w:val="nil"/>` — Word draws the line, as does macOS's own DOCX
+/// renderer on the same markup;
+/// * a cell that *inherits* its bottom from `insideH`, faced by a `gridSpan=2`
+/// spacer cell whose `nil` was aimed at the neighbouring column — Word draws
+/// that line too, and it could not do otherwise: a cell paints one border
+/// across its whole width, so a wide cell's `nil` cannot punch a hole in the
+/// cell above it;
+/// * down the document's spacer columns the generator writes `nil` on **both**
+/// sides of every shared edge. Writing both is only necessary because one
+/// alone does not suppress.
+///
+/// `nil` is still not a no-op: with nothing facing it — a table's outer edge, or
+/// a facing cell that is also `nil` — declining inheritance is exactly what
+/// removes the border. Both halves are pinned by
+/// `tests/table_border_conflict.rs`.
+///
+/// **The comparison is a total order, and that is the point.** The caller feeds
+/// this (upper row's bottom, lower row's top) and (left cell's right, right
+/// cell's left), so a rule that stops at step 2 leaves the winner decided by
+/// *which side of the edge a border came from* — an implementation detail. Ties
+/// used to fall through to whichever argument came first, which meant an
+/// equal-weight 3pt single beat a 1pt double or lost to it depending on
+/// argument order, and of two equal borders differing only in colour the paler
+/// one won half the time. `resolve_border_conflict(a, b)` now always equals
+/// `resolve_border_conflict(b, a)`.
+///
+/// Suppression is still a *third* state, which is why the argument type is
+/// [`CellEdge`] and not `Option<TableBorderLine>`: when neither side paints,
+/// returning `Suppressed` rather than `Absent` keeps the two distinguishable for
+/// the caller — a suppressed edge must not be revived by the page-split
+/// top-border restore in `emit.rs`, whereas an absent one should be.
+pub(super) fn resolve_border_conflict(a: CellEdge, b: CellEdge) -> CellEdge {
+ match (a, b) {
+ (CellEdge::Line(la), CellEdge::Line(lb)) => {
+ match border_precedence(&la).cmp(&border_precedence(&lb)) {
+ std::cmp::Ordering::Less => b,
+ _ => a,
+ }
+ }
+ // One side paints: it does so regardless of what the other side says.
+ // A facing `nil` removed *its* border, not this one.
+ (CellEdge::Line(_), _) => a,
+ (_, CellEdge::Line(_)) => b,
+ // Neither side paints. Carry suppression forward so the page-split
+ // restore cannot revive an edge the author explicitly emptied.
+ (CellEdge::Suppressed, _) | (_, CellEdge::Suppressed) => CellEdge::Suppressed,
+ (CellEdge::Absent, CellEdge::Absent) => CellEdge::Absent,
+ }
+}
+
+/// Sort key for [MS-OI29500] §17.4.66 conflict resolution — greater wins.
+///
+/// Returns integers so the key is `Ord`: comparing `f32` weights directly would
+/// need `partial_cmp`, and a `NaN` width (unreachable, but the type permits it)
+/// would silently make the comparison non-transitive and reintroduce the
+/// order-dependence this exists to remove.
+///
+/// **Two fields are inverted, and for the same reason.** The spec states both
+/// style and colour as "lower value wins" rankings — earliest in the precedence
+/// list, and smallest brightness. This key is "greater wins", so each is
+/// subtracted from its type's maximum. Inverting one and not the other is the
+/// defect this layout is meant to make obvious.
+fn border_precedence(b: &TableBorderLine) -> (u32, u8, u32, u32, u32) {
+ let (l0, l1, l2) = colour_luminance(b);
+ (
+ // Weight in eighths of a point, rounded — the spec's `sz` unit.
+ (border_weight(b) * 8.0).round().max(0.0) as u32,
+ u8::MAX - style_precedence_index(b.style),
+ u32::MAX - l0,
+ u32::MAX - l1,
+ u32::MAX - l2,
+ )
+}
+
+/// [MS-OI29500] §17.4.66 style precedence: at equal weight, *"the higher of the
+/// two on this precedence list shall be displayed"*, the list being
+///
+/// > single, thick, double, dotted, dashed, dotDash, dotDotDash, triple,
+/// > thinThickSmallGap, … outset, inset
+///
+/// "Higher on the list" means **earlier**, so this returns the 0-based index
+/// into it and **lower wins** — `border_precedence` inverts it.
+///
+/// So `Single` beats `Double` at equal weight, which is worth stating plainly
+/// because the intuition runs the other way: a double border has the greater
+/// *style number* (3 vs 1) and therefore the greater weight at equal width, and
+/// it is easy to carry that ordering into the tie-break, where the spec
+/// reverses it. Equal weight means the single is three times wider — a 3pt
+/// solid line against two 0.33pt hairlines — and the spec prefers the single.
+///
+/// Only `Single` and `Double` reach layout (the other 24 §17.4.38 styles are
+/// approximated as `Single` — see `convert_model_border`), so only their two
+/// positions are modelled: single is first, double is third.
+fn style_precedence_index(style: TableBorderStyle) -> u8 {
+ match style {
+ TableBorderStyle::Single => 0,
+ TableBorderStyle::Double => 2,
+ }
+}
+
+/// [MS-OI29500] §17.4.66 darkness keys, compared in order: `R+B+2G`, then
+/// `B+2G`, then `G`. Lower is darker.
+fn colour_luminance(b: &TableBorderLine) -> (u32, u32, u32) {
+ let (r, g, bl) = (b.color.r as u32, b.color.g as u32, b.color.b as u32);
+ (r + bl + 2 * g, bl + 2 * g, g)
+}
+
+/// Emit all four borders for a cell as filled rectangles.
+/// Borders are drawn INWARD from the cell edge per OOXML.
+///
+/// Horizontal borders (top/bottom) own the corner squares — they span the
+/// full cell width. Vertical borders (left/right) fill only the space
+/// between the horizontals. This eliminates anti-aliasing gaps at corners
+/// that plagued the previous stroke-based approach.
+pub(super) fn emit_cell_borders(
+ commands: &mut Vec<DrawCommand>,
+ b: CellBorders,
+ cell_x: Pt,
+ cell_w: Pt,
+ row_y: Pt,
+ row_h: Pt,
+) {
+ // Resolution is over by now, so `Suppressed` and `Absent` are the same
+ // thing here: nothing to paint.
+ let (top, bottom, left, right) = (b.top.line(), b.bottom.line(), b.left.line(), b.right.line());
+ let top_w = top.map(|b| b.width).unwrap_or(Pt::ZERO);
+ let bot_w = bottom.map(|b| b.width).unwrap_or(Pt::ZERO);
+ let left_w = left.map(|b| b.width).unwrap_or(Pt::ZERO);
+ let right_w = right.map(|b| b.width).unwrap_or(Pt::ZERO);
+
+ // Horizontal borders: full cell width, covering corner squares.
+ if let Some(ref border) = top {
+ emit_border_rect(
+ commands,
+ border,
+ PtRect::from_xywh(cell_x, row_y, cell_w, top_w),
+ true,
+ );
+ }
+ if let Some(ref border) = bottom {
+ emit_border_rect(
+ commands,
+ border,
+ PtRect::from_xywh(cell_x, row_y + row_h - bot_w, cell_w, bot_w),
+ true,
+ );
+ }
+
+ // Vertical borders: between horizontal borders (no corner overlap).
+ let top_inset = if top.is_some() { top_w } else { Pt::ZERO };
+ let bot_inset = if bottom.is_some() { bot_w } else { Pt::ZERO };
+ let v_height = row_h - top_inset - bot_inset;
+ if v_height > Pt::ZERO {
+ if let Some(ref border) = left {
+ emit_border_rect(
+ commands,
+ border,
+ PtRect::from_xywh(cell_x, row_y + top_inset, left_w, v_height),
+ false,
+ );
+ }
+ if let Some(ref border) = right {
+ emit_border_rect(
+ commands,
+ border,
+ PtRect::from_xywh(
+ cell_x + cell_w - right_w,
+ row_y + top_inset,
+ right_w,
+ v_height,
+ ),
+ false,
+ );
+ }
+ }
+}
+
+/// [MS-OI29500] §17.4.66: border weight = width × style number, in points.
+///
+/// The spec states the rule in eighths of a point (`w:sz`), but every use is a
+/// *comparison* between two weights, and converting both to eighths scales both
+/// by the same 8 — so the factor cancels. Keeping it in points avoids implying
+/// that a unit conversion is load-bearing here. `border_precedence` scales to
+/// eighths once, where rounding to an integer sort key does depend on the unit.
+fn border_weight(b: &TableBorderLine) -> f32 {
+ let style_number = match b.style {
+ TableBorderStyle::Single => 1.0,
+ TableBorderStyle::Double => 3.0,
+ };
+ b.width.raw() * style_number
+}
+
+/// Width of the line this edge paints, or zero when it paints none — which
+/// includes a suppressed edge, since suppression reserves no space.
+pub(super) fn border_width(b: CellEdge) -> Pt {
+ b.line().map(|b| b.width).unwrap_or(Pt::ZERO)
+}
+
+fn resolve_override(ovr: &CellBorderOverride) -> CellEdge {
+ match ovr {
+ CellBorderOverride::Suppress => CellEdge::Suppressed,
+ // The cell's own `<w:tcBorders>` — the provenance that beats a facing
+ // `nil` in `resolve_border_conflict`.
+ CellBorderOverride::Border(line) => CellEdge::Line(*line),
+ }
+}
+
+/// Emit a border as filled rectangle(s).
+/// `is_horizontal` controls double-border sub-rect orientation.
+fn emit_border_rect(
+ commands: &mut Vec<DrawCommand>,
+ b: &TableBorderLine,
+ rect: PtRect,
+ is_horizontal: bool,
+) {
+ match b.style {
+ TableBorderStyle::Single => {
+ commands.push(DrawCommand::Rect {
+ rect,
+ color: b.color,
+ });
+ }
+ TableBorderStyle::Double => {
+ // §17.4.38: total = w:sz, each sub-line = sz/3, gap = sz/3.
+ let sub = b.width * (1.0 / 3.0);
+ if is_horizontal {
+ // Two horizontal sub-rects: top and bottom of the border area.
+ commands.push(DrawCommand::Rect {
+ rect: PtRect::from_xywh(rect.origin.x, rect.origin.y, rect.size.width, sub),
+ color: b.color,
+ });
+ commands.push(DrawCommand::Rect {
+ rect: PtRect::from_xywh(
+ rect.origin.x,
+ rect.origin.y + rect.size.height - sub,
+ rect.size.width,
+ sub,
+ ),
+ color: b.color,
+ });
+ } else {
+ // Two vertical sub-rects: left and right of the border area.
+ commands.push(DrawCommand::Rect {
+ rect: PtRect::from_xywh(rect.origin.x, rect.origin.y, sub, rect.size.height),
+ color: b.color,
+ });
+ commands.push(DrawCommand::Rect {
+ rect: PtRect::from_xywh(
+ rect.origin.x + rect.size.width - sub,
+ rect.origin.y,
+ sub,
+ rect.size.height,
+ ),
+ color: b.color,
+ });
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::render::dimension::Pt;
+ use crate::render::geometry::PtEdgeInsets;
+ use crate::render::layout::draw_command::DrawCommand;
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::section::LayoutBlock;
+ use crate::render::layout::table::{
+ CellVAlign, TableBorderConfig, TableBorderLine, TableBorderStyle, TableCellInput,
+ TableRowInput, layout_table,
+ };
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str, width: f32) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn simple_cell(text: &str) -> TableCellInput {
+ TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, 30.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ #[test]
+ fn borders_emit_lines() {
+ let rows = vec![TableRowInput {
+ cells: vec![simple_cell("a"), simple_cell("b")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(100.0), Pt::new(100.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&TableBorderConfig {
+ top: Some(TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ bottom: Some(TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ left: Some(TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ right: Some(TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ inside_h: Some(TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ inside_v: Some(TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ }),
+ None,
+ false,
+ );
+
+ // Borders are emitted as filled rects. Count border rects by
+ // excluding cell shading rects (which use non-BLACK colors or
+ // appear before borders in the command list).
+ let border_rect_count = result
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Rect { color, .. } if *color == RgbColor::BLACK))
+ .count();
+ // [MS-OI29500] §17.4.66: shared edges drawn once after conflict resolution.
+ // Top(2) + bottom(2) + left(1) + insideV(1) + right(1) = 7 border rects.
+ assert_eq!(border_rect_count, 7);
+ }
+
+ /// §17.4.61 tblPrEx — when a row carries a `tblBorders` override,
+ /// it fully replaces the table's tblBorders for *that row only*.
+ /// Here row 0 sets every side to "no border", row 1 doesn't.
+ /// The table-wide config has all sides set to single. Expectation:
+ /// row 0's cell contributes zero border rects, while row 1's cell
+ /// produces the usual top/left/right/bottom set.
+ #[test]
+ fn row_border_override_replaces_table_borders_for_that_row() {
+ let single = TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ };
+ let all_single = TableBorderConfig {
+ top: Some(single),
+ bottom: Some(single),
+ left: Some(single),
+ right: Some(single),
+ inside_h: Some(single),
+ inside_v: Some(single),
+ };
+ let no_borders = TableBorderConfig {
+ top: None,
+ bottom: None,
+ left: None,
+ right: None,
+ inside_h: None,
+ inside_v: None,
+ };
+ let rows = vec![
+ TableRowInput {
+ cells: vec![simple_cell("opt-out")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: Some(no_borders),
+ },
+ TableRowInput {
+ cells: vec![simple_cell("normal")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ ];
+ let col_widths = vec![Pt::new(100.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&all_single),
+ None,
+ false,
+ );
+
+ // Group border rects by their y position. The opt-out row is
+ // first (lower y), the normal row second. We know the order
+ // because layout_table walks rows top-down.
+ let border_rects: Vec<_> = result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Rect { rect, color } if *color == RgbColor::BLACK => Some(*rect),
+ _ => None,
+ })
+ .collect();
+
+ // No rect should sit entirely within row 0's vertical span —
+ // not the cell's top, not its sides, not its bottom (with row 1
+ // having a top border, conflict resolution gives row 0 a
+ // bottom from row 1's top, but that's drawn at the boundary,
+ // not inside row 0).
+ // We exercise this by asserting that no rect's *vertical*
+ // extent falls within (epsilon, row_0_height - epsilon) — the
+ // strict interior of row 0.
+ let row_0_height = Pt::new(14.0);
+ let interior_eps = Pt::new(0.1);
+ let interior_top = interior_eps;
+ let interior_bottom = row_0_height - interior_eps;
+ for rect in &border_rects {
+ let r_top = rect.origin.y;
+ let r_bottom = rect.origin.y + rect.size.height;
+ let entirely_inside = r_top >= interior_top && r_bottom <= interior_bottom;
+ assert!(
+ !entirely_inside,
+ "row 0 (border-override = all None) must not host a \
+ black border rect strictly inside its content area; got rect \
+ y=[{:.2}..{:.2}] (interior was ({:.2}..{:.2}))",
+ r_top.raw(),
+ r_bottom.raw(),
+ interior_top.raw(),
+ interior_bottom.raw(),
+ );
+ }
+ }
+}
+
+#[cfg(test)]
+mod conflict_tests {
+ use super::*;
+ use crate::render::resolve::color::RgbColor;
+
+ const BLACK: RgbColor = RgbColor { r: 0, g: 0, b: 0 };
+ const PALE: RgbColor = RgbColor {
+ r: 220,
+ g: 220,
+ b: 220,
+ };
+
+ fn line(width: f32, style: TableBorderStyle, color: RgbColor) -> TableBorderLine {
+ TableBorderLine {
+ width: Pt::new(width),
+ color,
+ style,
+ }
+ }
+
+ /// A representative spread: both styles, several widths, both colours.
+ fn sample_borders() -> Vec<TableBorderLine> {
+ let mut v = Vec::new();
+ for &w in &[0.5f32, 1.0, 2.0, 3.0, 6.0] {
+ for &s in &[TableBorderStyle::Single, TableBorderStyle::Double] {
+ for &c in &[BLACK, PALE] {
+ v.push(line(w, s, c));
+ }
+ }
+ }
+ v
+ }
+
+ /// **The property that matters.** The caller passes (upper row's bottom,
+ /// lower row's top) and (left cell's right, right cell's left), so a
+ /// resolution that depends on argument order makes the rendered border
+ /// depend on which *side of the edge* it was declared on.
+ ///
+ /// Before this was a total order, ties fell through to whichever argument
+ /// came first: an equal-weight 3pt single beat a 1pt double or lost to it
+ /// depending on the call, and of two borders differing only in colour the
+ /// paler one won half the time.
+ #[test]
+ fn resolution_is_independent_of_argument_order() {
+ let borders = sample_borders();
+ for a in &borders {
+ for b in &borders {
+ let ab = resolve_border_conflict(CellEdge::Line(*a), CellEdge::Line(*b));
+ let ba = resolve_border_conflict(CellEdge::Line(*b), CellEdge::Line(*a));
+ assert_eq!(
+ (ab.line().map(|x| (x.width, x.style, x.color))),
+ (ba.line().map(|x| (x.width, x.style, x.color))),
+ "order-dependent for {a:?} vs {b:?}"
+ );
+ }
+ }
+ }
+
+ /// Step 2 — the heavier border wins outright.
+ #[test]
+ fn heavier_weight_wins() {
+ let thin = line(0.5, TableBorderStyle::Single, BLACK);
+ let thick = line(2.0, TableBorderStyle::Single, BLACK);
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(thin), CellEdge::Line(thick))
+ .line()
+ .map(|b| b.width),
+ Some(Pt::new(2.0))
+ );
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(thick), CellEdge::Line(thin))
+ .line()
+ .map(|b| b.width),
+ Some(Pt::new(2.0))
+ );
+ }
+
+ /// Step 3 — equal weight, so position in the spec's precedence list decides,
+ /// and **`Single` wins**. 3pt single and 1pt double both weigh 3
+ /// (width × style number), which is exactly the tie the pre-E5b#2 code
+ /// resolved by argument position.
+ ///
+ /// This test previously asserted the opposite, and was mutation-checked in
+ /// that state — the code and the assertion shared one error, so no mutation
+ /// could expose it. [MS-OI29500] §17.4.66 orders the list
+ /// `single, thick, double, …` and displays *"the higher of the two on this
+ /// precedence list"*, i.e. the earlier one.
+ #[test]
+ fn equal_weight_prefers_the_earlier_style_in_the_precedence_list() {
+ let single = line(3.0, TableBorderStyle::Single, BLACK);
+ let double = line(1.0, TableBorderStyle::Double, BLACK);
+ assert_eq!(
+ border_weight(&single),
+ border_weight(&double),
+ "same weight"
+ );
+
+ for (a, b) in [(single, double), (double, single)] {
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(a), CellEdge::Line(b))
+ .line()
+ .map(|x| x.style),
+ Some(TableBorderStyle::Single),
+ "Single is earlier in the precedence list, so it wins at equal weight"
+ );
+ }
+ }
+
+ /// The tie-break must not leak into the *weight* comparison: a double
+ /// border of equal width still outweighs a single (style number 3 vs 1) and
+ /// wins at step 2, before precedence is consulted.
+ ///
+ /// Pins the two steps apart. Ranking `Single` above `Double` is only correct
+ /// as a tie-break; applied one step earlier it would invert every ordinary
+ /// single-vs-double edge in a table.
+ #[test]
+ fn precedence_does_not_override_weight() {
+ let single = line(1.0, TableBorderStyle::Single, BLACK);
+ let double = line(1.0, TableBorderStyle::Double, BLACK);
+ assert!(
+ border_weight(&double) > border_weight(&single),
+ "equal width, double is heavier"
+ );
+
+ for (a, b) in [(single, double), (double, single)] {
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(a), CellEdge::Line(b))
+ .line()
+ .map(|x| x.style),
+ Some(TableBorderStyle::Double),
+ "the heavier border wins outright, regardless of precedence"
+ );
+ }
+ }
+
+ /// Step 4 — equal weight and style, so the darker colour decides.
+ #[test]
+ fn equal_weight_and_style_prefers_the_darker_colour() {
+ let dark = line(1.0, TableBorderStyle::Single, BLACK);
+ let pale = line(1.0, TableBorderStyle::Single, PALE);
+ for (a, b) in [(dark, pale), (pale, dark)] {
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(a), CellEdge::Line(b))
+ .line()
+ .map(|x| x.color),
+ Some(BLACK),
+ "darker colour wins regardless of argument order"
+ );
+ }
+ }
+
+ /// The §17.4.66 darkness keys are compared in order `R+B+2G`, then `B+2G`,
+ /// then `G` — so two colours with the same total brightness are separated by
+ /// the later keys rather than by argument order.
+ #[test]
+ fn darkness_tie_breaks_on_the_secondary_keys() {
+ // R+B+2G equal (both 255*2 = 510... constructed to match), differing in
+ // the B+2G term.
+ let a = line(
+ 1.0,
+ TableBorderStyle::Single,
+ RgbColor { r: 100, g: 0, b: 0 },
+ );
+ let b = line(
+ 1.0,
+ TableBorderStyle::Single,
+ RgbColor { r: 0, g: 0, b: 100 },
+ );
+ assert_eq!(
+ colour_luminance(&a).0,
+ colour_luminance(&b).0,
+ "primary key ties"
+ );
+ // a has B+2G = 0, b has B+2G = 100 → a is "darker" by the second key.
+ let winner = resolve_border_conflict(CellEdge::Line(a), CellEdge::Line(b))
+ .line()
+ .expect("some");
+ assert_eq!(winner.color, RgbColor { r: 100, g: 0, b: 0 });
+ // And symmetric.
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(b), CellEdge::Line(a))
+ .line()
+ .map(|x| x.color),
+ Some(RgbColor { r: 100, g: 0, b: 0 })
+ );
+ }
+
+ /// Step 1 — an absent border yields to a present one, in both directions,
+ /// and two absent borders stay absent.
+ #[test]
+ fn absent_yields_to_present() {
+ let some = line(1.0, TableBorderStyle::Single, BLACK);
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Absent, CellEdge::Line(some))
+ .line()
+ .map(|b| b.width),
+ Some(Pt::new(1.0))
+ );
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Line(some), CellEdge::Absent)
+ .line()
+ .map(|b| b.width),
+ Some(Pt::new(1.0))
+ );
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Absent, CellEdge::Absent),
+ CellEdge::Absent
+ );
+ }
+
+ /// **`nil` does not reach across the edge.** [MS-OI29500] §17.4.66 says
+ /// *"If the conflicting table cell border is nil, then no border shall be
+ /// displayed"*, and read literally that is wrong: `nil` empties its own
+ /// cell's edge and leaves the facing cell's border alone. It loses from
+ /// either side and at any weight — even a hairline survives it.
+ ///
+ /// `IP 05 Trenches` is the reference. `<w:bottom w:val="single"/>` above
+ /// `<w:top w:val="nil"/>` draws in Word and in macOS's DOCX renderer; so
+ /// does an *inherited* bottom faced by a `gridSpan` spacer cell's `nil`, and
+ /// it must — a cell paints one border across its whole width, so a wide
+ /// cell's `nil` cannot punch a hole in the cell above it.
+ #[test]
+ fn nil_yields_to_the_facing_border() {
+ let hair = line(0.25, TableBorderStyle::Single, BLACK);
+ for (a, b) in [
+ (CellEdge::Suppressed, CellEdge::Line(hair)),
+ (CellEdge::Line(hair), CellEdge::Suppressed),
+ ] {
+ assert_eq!(
+ resolve_border_conflict(a, b).line(),
+ Some(hair),
+ "the facing border must survive the nil: {a:?} vs {b:?}"
+ );
+ }
+ }
+
+ /// …and yet `nil` is not a no-op, because it declined **inheritance**
+ /// upstream in `resolve_cell_effective_borders`. With nothing facing it —
+ /// another `nil`, or an edge nobody spoke for — nothing is painted, and the
+ /// result stays `Suppressed` rather than collapsing to `Absent`.
+ ///
+ /// That last part is load-bearing: `emit.rs` may revive an `Absent` top when
+ /// a row starts a page slice, and must not revive an emptied one.
+ #[test]
+ fn nil_stays_suppressed_when_nothing_faces_it() {
+ for (a, b) in [
+ (CellEdge::Suppressed, CellEdge::Absent),
+ (CellEdge::Absent, CellEdge::Suppressed),
+ (CellEdge::Suppressed, CellEdge::Suppressed),
+ ] {
+ assert_eq!(
+ resolve_border_conflict(a, b),
+ CellEdge::Suppressed,
+ "suppression must survive where nothing paints: {a:?} vs {b:?}"
+ );
+ }
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Absent, CellEdge::Absent),
+ CellEdge::Absent,
+ "…but two silent edges stay restorable"
+ );
+ }
+
+ /// The counterpart, and the half that is easy to get wrong when fixing the
+ /// other: an edge declared `none` is **not** suppression. §17.4.66 puts it
+ /// with the omitted case — *"If the conflicting table cell border is none
+ /// (no border), then the opposing border shall be displayed."*
+ ///
+ /// `none` never reaches the resolver as its own state; it arrives as
+ /// `Absent` because `convert_cell_border_override` maps it to "no override".
+ /// This test pins the consequence at the level the resolver sees.
+ #[test]
+ fn an_absent_edge_never_suppresses() {
+ let border = line(1.0, TableBorderStyle::Single, BLACK);
+ assert_eq!(
+ resolve_border_conflict(CellEdge::Absent, CellEdge::Line(border)),
+ CellEdge::Line(border),
+ "absent (which is what `none` becomes) must yield, not suppress"
+ );
+ }
+
+ /// Identical borders resolve to themselves — the reflexive case, which a
+ /// comparison built on `partial_cmp` of `f32` could get wrong.
+ #[test]
+ fn identical_borders_resolve_to_themselves() {
+ for b in sample_borders() {
+ let r = resolve_border_conflict(CellEdge::Line(b), CellEdge::Line(b))
+ .line()
+ .expect("some");
+ assert_eq!((r.width, r.style, r.color), (b.width, b.style, b.color));
+ }
+ }
+}
+
+/// §17.4.38 edge mapping: which of the six table-level borders each cell edge
+/// draws from, given the cell's position in the grid.
+#[cfg(test)]
+mod edge_mapping_tests {
+ use super::*;
+ use crate::render::geometry::PtEdgeInsets;
+ use crate::render::layout::table::CellVAlign;
+ use crate::render::resolve::color::RgbColor;
+
+ /// Every edge gets its own width, so a resolved border names the config
+ /// field it came from.
+ const TOP: f32 = 1.0;
+ const BOTTOM: f32 = 2.0;
+ const LEFT: f32 = 3.0;
+ const RIGHT: f32 = 4.0;
+ const INSIDE_H: f32 = 5.0;
+ const INSIDE_V: f32 = 6.0;
+
+ fn edge(width: f32) -> Option<TableBorderLine> {
+ Some(TableBorderLine {
+ width: Pt::new(width),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ })
+ }
+
+ fn config() -> TableBorderConfig {
+ TableBorderConfig {
+ top: edge(TOP),
+ bottom: edge(BOTTOM),
+ left: edge(LEFT),
+ right: edge(RIGHT),
+ inside_h: edge(INSIDE_H),
+ inside_v: edge(INSIDE_V),
+ }
+ }
+
+ fn plain_cell() -> TableCellInput {
+ TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ /// `(top, bottom, left, right)` widths, so a failure reads as which edges
+ /// were mis-mapped rather than as four separate assertions.
+ fn widths(
+ row_idx: usize,
+ grid_col: usize,
+ num_rows: usize,
+ num_grid_cols: usize,
+ ) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
+ let (t, b, l, r) = resolve_cell_effective_borders(
+ &plain_cell(),
+ Some(&config()),
+ row_idx,
+ grid_col,
+ 1,
+ num_rows,
+ num_grid_cols,
+ );
+ let w = |e: CellEdge| e.line().map(|e| e.width.raw());
+ (w(t), w(b), w(l), w(r))
+ }
+
+ /// A 3×3 grid: the corners take the outer borders, the middle takes
+ /// `insideH`/`insideV` on all four sides.
+ #[test]
+ fn outer_edges_use_outer_borders_and_interior_edges_use_inside() {
+ assert_eq!(
+ widths(0, 0, 3, 3),
+ (Some(TOP), Some(INSIDE_H), Some(LEFT), Some(INSIDE_V)),
+ "top-left cell"
+ );
+ assert_eq!(
+ widths(1, 1, 3, 3),
+ (
+ Some(INSIDE_H),
+ Some(INSIDE_H),
+ Some(INSIDE_V),
+ Some(INSIDE_V)
+ ),
+ "centre cell"
+ );
+ assert_eq!(
+ widths(2, 2, 3, 3),
+ (Some(INSIDE_H), Some(BOTTOM), Some(INSIDE_V), Some(RIGHT)),
+ "bottom-right cell"
+ );
+ }
+
+ /// A single-row, single-column table is both first and last on both axes,
+ /// so it takes all four outer borders and neither inside border.
+ #[test]
+ fn a_one_cell_table_takes_all_four_outer_borders() {
+ assert_eq!(
+ widths(0, 0, 1, 1),
+ (Some(TOP), Some(BOTTOM), Some(LEFT), Some(RIGHT))
+ );
+ }
+
+ /// E5b#7. `num_rows == 0` is unreachable through `layout_table` — it returns
+ /// early on empty input, and every other caller is inside a row loop — but
+ /// `num_rows` is a free parameter of a `pub(super)` function, so the
+ /// last-row test must not depend on a caller having checked it.
+ /// `row_idx == num_rows - 1` underflows here; `row_idx + 1 == num_rows`
+ /// answers "no row is the last row of an empty table".
+ #[test]
+ fn an_empty_table_does_not_underflow_the_last_row_check() {
+ assert_eq!(
+ widths(0, 0, 0, 3),
+ (Some(TOP), Some(INSIDE_H), Some(LEFT), Some(INSIDE_V))
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/emit.rs b/crates/liteparse-docx/src/render/layout/table/emit.rs
new file mode 100644
index 0000000..f6ba87a
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/emit.rs
@@ -0,0 +1,689 @@
+//! Table command emission — positions cells and emits border commands.
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtRect;
+
+use crate::render::layout::draw_command::DrawCommand;
+
+use super::borders::{CellBorders, CellEdge, border_width, emit_cell_borders};
+use super::grid::is_vmerge_continue;
+use super::types::{
+ CellVAlign, MeasuredRow, MeasuredTable, TableBorderLine, TableRowInput, VerticalMergeState,
+};
+
+/// Layered command buffers for table rendering: shading, content, borders.
+pub(super) struct TableCommandBuffers<'a> {
+ pub(super) commands: &'a mut Vec<DrawCommand>,
+ pub(super) content_commands: &'a mut Vec<DrawCommand>,
+ pub(super) border_commands: &'a mut Vec<DrawCommand>,
+}
+
+/// Emit draw commands for a range of measured rows.
+///
+/// `top_border_override`: if `Some`, the first row in the range gets this border
+/// as its top edge. Used for page-split tables where the measured top borders were
+/// suppressed (adjacent table collapse) or resolved away (conflict resolution),
+/// but the continuation slice still needs a visible top boundary.
+pub(super) fn emit_table_rows(
+ measured: &MeasuredTable,
+ rows: &[TableRowInput],
+ row_range: std::ops::Range<usize>,
+ cursor_y: &mut Pt,
+ bufs: &mut TableCommandBuffers<'_>,
+ top_border_override: Option<TableBorderLine>,
+) {
+ let num_rows = measured.rows.len();
+ let range_start = row_range.start;
+ for row_idx in row_range {
+ let mr = &measured.rows[row_idx];
+ let is_first_in_range = row_idx == range_start;
+ // Deliberately the *table's* row count, not the range's: this mirrors
+ // `measure_table_rows`' own condition for reserving `border_gap_below`
+ // (`row_idx + 1 < num_rows`), so the two always agree about whether a
+ // gap exists. A row that ends a page slice but not the table still has
+ // its reserved gap, and its bottom border belongs in it.
+ let has_reserved_bottom_gap = row_idx + 1 < num_rows;
+ emit_one_row(
+ mr,
+ &rows[row_idx],
+ cursor_y,
+ bufs,
+ if is_first_in_range {
+ top_border_override
+ } else {
+ None
+ },
+ has_reserved_bottom_gap,
+ Some((measured, rows, row_idx)),
+ );
+ }
+}
+
+/// Emit a custom `MeasuredRow` (produced by `split::split_row_at`). Unlike
+/// the range-based emit above, this takes a single already-built
+/// `MeasuredRow` and the matching `TableRowInput`. `vmerge_ctx` is always
+/// `None` here — split rows can't contain vMerge (the group is flagged
+/// not splittable if any cell is merged).
+pub(super) fn emit_split_row(
+ mr: &MeasuredRow,
+ row: &TableRowInput,
+ cursor_y: &mut Pt,
+ bufs: &mut TableCommandBuffers<'_>,
+ top_border_override: Option<TableBorderLine>,
+ has_reserved_bottom_gap: bool,
+) {
+ emit_one_row(
+ mr,
+ row,
+ cursor_y,
+ bufs,
+ top_border_override,
+ has_reserved_bottom_gap,
+ None,
+ );
+}
+
+fn emit_one_row(
+ mr: &MeasuredRow,
+ row: &TableRowInput,
+ cursor_y: &mut Pt,
+ bufs: &mut TableCommandBuffers<'_>,
+ top_border_override: Option<TableBorderLine>,
+ // Whether space was reserved below this row for its bottom border, so the
+ // border is drawn *under* the content rather than inset into it.
+ //
+ // Not a positional fact, which is why the two callers derive it
+ // differently and both are right: `emit_table_rows` repeats
+ // `measure_table_rows`' reservation condition, while a split row's halves
+ // carry their own (`split_row_at` zeroes the first half's gap — a cut edge
+ // has none — and passes the original's to the second).
+ has_reserved_bottom_gap: bool,
+ // For vMerge=Restart cells, resolve the full merged span height.
+ // `None` disables the lookup (used for split rows and for standalone
+ // emission paths that don't carry a merge context).
+ vmerge_ctx: Option<(&MeasuredTable, &[TableRowInput], usize)>,
+) {
+ // §17.4.44: the row's box starts one cell-spacing below the cursor; its
+ // content box is what remains. Both are zero-cost when no spacing is set.
+ let leading = mr.leading_gap;
+ let row_top = *cursor_y + leading;
+ let row_height = mr.height - leading;
+ for (cell_ci, (entry, cell_input)) in mr.entries.iter().zip(row.cells.iter()).enumerate() {
+ // §17.4.85: the merged span, used below for vAlign and here for
+ // shading. Hoisted above the shading so both read the same height —
+ // shading used `row_height` while vAlign used the span, so a shaded
+ // merged cell was coloured across its first row only.
+ let effective_h = if cell_input.vertical_merge == Some(VerticalMergeState::Restart) {
+ vmerge_ctx
+ .map(|(m, rs, row_idx)| merged_span_height(m, rs, row_idx, entry.grid_col))
+ .unwrap_or(row_height)
+ } else {
+ row_height
+ };
+
+ // §17.4.33 / §17.4.85: a merged cell's shading covers the whole span,
+ // and the `Continue` rows do not paint their own. Word treats the
+ // continuation cells as part of the `Restart` cell, so its `<w:shd>`
+ // governs the merged region; letting a continuation paint over the span
+ // would let a stale or differing `shd` on a row that has no independent
+ // existence win for that row.
+ if cell_input.vertical_merge != Some(VerticalMergeState::Continue) {
+ if let Some(color) = cell_input.shading {
+ bufs.commands.push(DrawCommand::Rect {
+ rect: PtRect::from_xywh(entry.cell_x, row_top, entry.cell_w, effective_h),
+ color,
+ });
+ }
+ }
+
+ // §17.4.38: restore the top border when this row starts a slice and the
+ // resolved top was removed by conflict resolution or adjacent-table
+ // collapse. An edge the author set to `nil` must NOT be restored — they
+ // asked for no border — and `CellEdge` already says which is which, so
+ // this reads the resolved edge instead of re-deriving intent from
+ // `cell_input`. That also fixes the `none` case for free: `none` now
+ // resolves to `Absent` and is restorable, where the old re-derivation
+ // lumped it in with `nil` and left a continuation slice with no top.
+ let cell_top = match mr.borders[cell_ci].top {
+ CellEdge::Absent => top_border_override.into(),
+ resolved => resolved,
+ };
+ let b_left = mr.borders[cell_ci].left;
+ let b_right = mr.borders[cell_ci].right;
+ let b_bottom = mr.borders[cell_ci].bottom;
+
+ let dx = (border_width(b_left) - cell_input.margins.left).max(Pt::ZERO);
+ let dy_border = (border_width(cell_top) - cell_input.margins.top).max(Pt::ZERO);
+
+ // §17.4.85: for vMerge=Restart cells, vAlign operates over the whole
+ // merged span (`effective_h`, computed above with the shading).
+ let content_h = entry.layout.content_height + cell_input.margins.vertical();
+ let dy_valign = match cell_input.vertical_align {
+ CellVAlign::Bottom => (effective_h - content_h - dy_border).max(Pt::ZERO),
+ CellVAlign::Center => ((effective_h - content_h - dy_border) * 0.5).max(Pt::ZERO),
+ CellVAlign::Top => Pt::ZERO,
+ };
+
+ for cmd in &entry.layout.commands {
+ let mut cmd = cmd.clone();
+ cmd.shift(entry.cell_x + dx, row_top + dy_border + dy_valign);
+ bufs.content_commands.push(cmd);
+ }
+
+ let continues_below = vmerge_ctx.is_some_and(|(_, rows, row_idx)| {
+ row_idx + 1 < rows.len() && is_vmerge_continue(&rows[row_idx + 1], entry.grid_col)
+ });
+ let bottom_border_gap = if has_reserved_bottom_gap {
+ if continues_below {
+ mr.border_gap_below
+ } else {
+ border_width(b_bottom)
+ }
+ } else {
+ Pt::ZERO
+ };
+ emit_cell_borders(
+ bufs.border_commands,
+ CellBorders {
+ top: cell_top,
+ bottom: b_bottom,
+ left: b_left,
+ right: b_right,
+ },
+ entry.cell_x,
+ entry.cell_w,
+ row_top,
+ row_height + bottom_border_gap,
+ );
+ }
+
+ *cursor_y += mr.height + mr.border_gap_below;
+}
+
+/// Total vertical space owned by a vMerge=Restart cell at `grid_col`.
+/// Includes the restart row's height and every `Continue` row below it,
+/// plus the `border_gap_below` of intermediate rows (the cell's own top/
+/// bottom borders between merged rows were suppressed in measurement, so
+/// the gap is driven by sibling columns only).
+fn merged_span_height(
+ measured: &MeasuredTable,
+ rows: &[TableRowInput],
+ start_row: usize,
+ grid_col: usize,
+) -> Pt {
+ // The span starts below its own leading gap; every row it swallows
+ // contributes that row's full height, gap included, because a merged cell
+ // covers the spacing between the rows it spans.
+ let mut total = measured.rows[start_row].height - measured.rows[start_row].leading_gap;
+ let mut row = start_row + 1;
+ while row < rows.len() && is_vmerge_continue(&rows[row], grid_col) {
+ total += measured.rows[row - 1].border_gap_below;
+ total += measured.rows[row].height;
+ row += 1;
+ }
+ total
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::render::geometry::{PtEdgeInsets, PtSize};
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::section::LayoutBlock;
+ use crate::render::layout::table::types::TableCellInput;
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ const GREY: RgbColor = RgbColor {
+ r: 200,
+ g: 200,
+ b: 200,
+ };
+
+ fn frag(text: &str) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(30.0),
+ trimmed_width: Pt::new(30.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn cell(
+ n_lines: usize,
+ vmerge: Option<VerticalMergeState>,
+ shading: Option<RgbColor>,
+ ) -> TableCellInput {
+ TableCellInput {
+ blocks: (0..n_lines)
+ .map(|i| LayoutBlock::Paragraph {
+ fragments: vec![frag(&format!("L{i}"))],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ })
+ .collect(),
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading,
+ cell_borders: None,
+ vertical_merge: vmerge,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ fn row(cells: Vec<TableCellInput>) -> TableRowInput {
+ TableRowInput {
+ cells,
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }
+ }
+
+ fn shading_rects(commands: &[DrawCommand]) -> Vec<(f32, f32)> {
+ commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Rect { rect, color } if *color == GREY => {
+ Some((rect.origin.y.raw(), rect.size.height.raw()))
+ }
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Two rows: col 0 is a shaded `Restart` over a `Continue`, col 1 carries
+ /// two 2-line cells so each row measures 28pt — a 56pt merged span.
+ fn merged_shading_table(continue_shading: Option<RgbColor>) -> Vec<TableRowInput> {
+ vec![
+ row(vec![
+ cell(1, Some(VerticalMergeState::Restart), Some(GREY)),
+ cell(2, None, None),
+ ]),
+ row(vec![
+ cell(0, Some(VerticalMergeState::Continue), continue_shading),
+ cell(2, None, None),
+ ]),
+ ]
+ }
+
+ /// §17.4.85 + §17.4.33: a shaded merged cell is shaded across the whole
+ /// span, not just its first row.
+ ///
+ /// The shading rect used `row_height` while vAlign used the span height, so
+ /// only the first row was coloured — the lower half of a shaded merged cell
+ /// rendered as unshaded background.
+ #[test]
+ fn shaded_vmerge_restart_cell_shades_the_whole_span() {
+ let rows = merged_shading_table(None);
+ let table = crate::render::layout::table::layout_table(
+ &rows,
+ &[Pt::new(50.0), Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ assert_eq!(table.size, PtSize::new(Pt::new(100.0), Pt::new(56.0)));
+ assert_eq!(
+ shading_rects(&table.commands),
+ vec![(0.0, 56.0)],
+ "one rect covering the full 56pt merged span"
+ );
+ }
+
+ /// A `Continue` cell does not paint its own shading: Word treats it as part
+ /// of the `Restart` cell, whose `<w:shd>` governs the merged region. Without
+ /// this the continuation would paint over the span rect for its own row.
+ #[test]
+ fn vmerge_continue_cell_does_not_paint_its_own_shading() {
+ let rows = merged_shading_table(Some(RgbColor { r: 1, g: 2, b: 3 }));
+ let table = crate::render::layout::table::layout_table(
+ &rows,
+ &[Pt::new(50.0), Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ // The span rect survives whole …
+ assert_eq!(shading_rects(&table.commands), vec![(0.0, 56.0)]);
+ // … and the continuation's own colour is never emitted.
+ assert!(
+ !table.commands.iter().any(|c| matches!(
+ c,
+ DrawCommand::Rect {
+ color: RgbColor { r: 1, g: 2, b: 3 },
+ ..
+ }
+ )),
+ "a Continue cell's shading must not override the merged cell's"
+ );
+ }
+
+ /// An unmerged shaded cell is unaffected — the fix must not widen every
+ /// cell's shading to some span.
+ #[test]
+ fn unmerged_shaded_cell_shades_only_its_own_row() {
+ let rows = vec![
+ row(vec![cell(1, None, Some(GREY))]),
+ row(vec![cell(1, None, None)]),
+ ];
+ let table = crate::render::layout::table::layout_table(
+ &rows,
+ &[Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+ assert_eq!(shading_rects(&table.commands), vec![(0.0, 14.0)]);
+ }
+
+ /// `merged_span_height` stops at the first row that does not continue *this*
+ /// grid column — the row below the span is not absorbed into it.
+ ///
+ /// Observed through the shading rect, since that (with vAlign) is what the
+ /// function feeds; it does not affect row heights. Rows 0-1 form the span
+ /// and split the restart cell's 14pt of content 7/7 (§17.4.85
+ /// distribution), so the span is 14pt while the table is 28pt. A walk that
+ /// ran past the `Continue` would shade all 28.
+ #[test]
+ fn merged_span_height_stops_at_the_first_non_continue_row() {
+ let rows = vec![
+ row(vec![cell(1, Some(VerticalMergeState::Restart), Some(GREY))]),
+ row(vec![cell(0, Some(VerticalMergeState::Continue), None)]),
+ row(vec![cell(1, None, None)]),
+ ];
+ let table = crate::render::layout::table::layout_table(
+ &rows,
+ &[Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ assert_eq!(
+ table.size.height,
+ Pt::new(28.0),
+ "span 14pt + row 2 at 14pt"
+ );
+ assert_eq!(
+ shading_rects(&table.commands),
+ vec![(0.0, 14.0)],
+ "the span ends at the Continue row; row 2 is not part of it"
+ );
+ }
+
+ // ── Buffer layering and the nil/override interaction (E5b#3) ─────────
+
+ const RED: RgbColor = RgbColor { r: 255, g: 0, b: 0 };
+
+ fn single(width: f32, color: RgbColor) -> TableBorderLine {
+ TableBorderLine {
+ width: Pt::new(width),
+ color,
+ style: crate::render::layout::table::types::TableBorderStyle::Single,
+ }
+ }
+
+ fn all_edges(line: TableBorderLine) -> crate::render::layout::table::TableBorderConfig {
+ crate::render::layout::table::TableBorderConfig {
+ top: Some(line),
+ bottom: Some(line),
+ left: Some(line),
+ right: Some(line),
+ inside_h: Some(line),
+ inside_v: Some(line),
+ }
+ }
+
+ /// Index of the first command matching `pred`.
+ fn index_of(cmds: &[DrawCommand], pred: impl Fn(&DrawCommand) -> bool) -> usize {
+ cmds.iter()
+ .position(pred)
+ .expect("expected command not emitted")
+ }
+
+ /// The three buffers concatenate as shading → content → borders, and that
+ /// order is load-bearing: a cell's background is painted before its
+ /// neighbours' borders, so a background can never cover a shared edge, and
+ /// text is never hidden under a background.
+ ///
+ /// Asserted on the *final* command list, which is what the painter walks —
+ /// the buffers themselves are an implementation detail.
+ #[test]
+ fn commands_layer_shading_then_content_then_borders() {
+ let rows = vec![row(vec![cell(1, None, Some(GREY))])];
+ let table = crate::render::layout::table::layout_table(
+ &rows,
+ &[Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&all_edges(single(1.0, RED))),
+ None,
+ false,
+ );
+
+ let shading = index_of(
+ &table.commands,
+ |c| matches!(c, DrawCommand::Rect { color, .. } if *color == GREY),
+ );
+ let text = index_of(&table.commands, |c| matches!(c, DrawCommand::Text { .. }));
+ let border = index_of(
+ &table.commands,
+ |c| matches!(c, DrawCommand::Rect { color, .. } if *color == RED),
+ );
+
+ assert!(
+ shading < text && text < border,
+ "expected shading({shading}) < content({text}) < borders({border})"
+ );
+ }
+
+ /// §17.4.38: a continuation slice restores a top border that *resolution*
+ /// removed — but never one the author removed with `<w:top w:val="nil"/>`.
+ ///
+ /// Both cells resolve to no top border, so both are candidates for the
+ /// override; only the one without an explicit nil may take it. Driving
+ /// `emit_table_rows` directly is what makes the two cases comparable in a
+ /// single row.
+ #[test]
+ fn top_border_override_skips_a_cell_that_explicitly_suppressed_its_top() {
+ use crate::render::layout::table::types::{CellBorderConfig, CellBorderOverride};
+
+ let nil_top = CellBorderConfig {
+ top: Some(CellBorderOverride::Suppress),
+ bottom: None,
+ left: None,
+ right: None,
+ };
+ let mut suppressed = cell(1, None, None);
+ suppressed.cell_borders = Some(nil_top);
+
+ // Cell 0 says "no top border, deliberately"; cell 1 says nothing.
+ let rows = vec![row(vec![suppressed, cell(1, None, None)])];
+ // No table borders at all, so both cells resolve `top: None`.
+ let measured = crate::render::layout::table::measure::measure_table_rows(
+ &rows,
+ &[Pt::new(50.0), Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+ assert!(
+ measured.rows[0]
+ .borders
+ .iter()
+ .all(|b| b.top.line().is_none()),
+ "both cells must resolve to no top border for this test to mean anything"
+ );
+
+ let mut commands = Vec::new();
+ let mut content = Vec::new();
+ let mut borders = Vec::new();
+ let mut cursor_y = Pt::ZERO;
+ emit_table_rows(
+ &measured,
+ &rows,
+ 0..1,
+ &mut cursor_y,
+ &mut TableCommandBuffers {
+ commands: &mut commands,
+ content_commands: &mut content,
+ border_commands: &mut borders,
+ },
+ Some(single(3.0, RED)),
+ );
+
+ let restored_xs: Vec<f32> = borders
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Rect { rect, color } if *color == RED => Some(rect.origin.x.raw()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ restored_xs,
+ vec![50.0],
+ "only cell 1 (x=50) takes the override; cell 0 asked for no top border"
+ );
+ }
+
+ /// The override applies only to the *first* row of the emitted range — a
+ /// continuation slice gets one restored top edge, not one per row.
+ #[test]
+ fn top_border_override_applies_only_to_the_first_row_of_the_range() {
+ let rows = vec![
+ row(vec![cell(1, None, None)]),
+ row(vec![cell(1, None, None)]),
+ ];
+ let measured = crate::render::layout::table::measure::measure_table_rows(
+ &rows,
+ &[Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ let mut commands = Vec::new();
+ let mut content = Vec::new();
+ let mut borders = Vec::new();
+ let mut cursor_y = Pt::ZERO;
+ emit_table_rows(
+ &measured,
+ &rows,
+ 0..2,
+ &mut cursor_y,
+ &mut TableCommandBuffers {
+ commands: &mut commands,
+ content_commands: &mut content,
+ border_commands: &mut borders,
+ },
+ Some(single(3.0, RED)),
+ );
+
+ let count = borders
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Rect { color, .. } if *color == RED))
+ .count();
+ assert_eq!(count, 1, "exactly one restored top edge, on row 0");
+ }
+
+ /// A row that ends a page slice but not the *table* keeps its reserved
+ /// bottom-border gap.
+ ///
+ /// `has_reserved_bottom_gap` is derived from the table's row count, not the
+ /// emitted range's — it has to be, because `measure_table_rows` reserves
+ /// `border_gap_below` on exactly that condition and `cursor_y` advances by
+ /// it. Deriving it per slice instead would inset the border into the last
+ /// row of every page, leaving the reserved gap empty.
+ ///
+ /// Three 14pt rows with 2pt inside borders, split so rows 0-1 land on the
+ /// first slice: row 1 ends that slice, and its border must still sit in the
+ /// gap below it (y = 30..32), not inside its content box.
+ #[test]
+ fn a_row_ending_a_slice_keeps_its_reserved_bottom_gap() {
+ let line = single(2.0, RED);
+ let borders = crate::render::layout::table::TableBorderConfig {
+ top: None,
+ bottom: Some(line),
+ left: None,
+ right: None,
+ inside_h: Some(line),
+ inside_v: None,
+ };
+ let rows: Vec<TableRowInput> = (0..3).map(|_| row(vec![cell(1, None, None)])).collect();
+ let slices = crate::render::layout::table::layout_table_paginated(
+ &rows,
+ &[Pt::new(50.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&borders),
+ None,
+ &crate::render::layout::table::TablePaginationConfig {
+ available_height: Pt::new(34.0),
+ page_height: Pt::new(34.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 2, "3 rows at 16pt each over a 34pt page");
+
+ let border_bands: Vec<(f32, f32)> = slices[0]
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Rect { rect, color } if *color == RED => Some((
+ rect.origin.y.raw(),
+ rect.origin.y.raw() + rect.size.height.raw(),
+ )),
+ _ => None,
+ })
+ .collect();
+
+ assert!(
+ border_bands.contains(&(30.0, 32.0)),
+ "row 1 ends the slice at y=30; its bottom border belongs in the \
+ reserved gap 30..32, got {border_bands:?}"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/grid.rs b/crates/liteparse-docx/src/render/layout/table/grid.rs
new file mode 100644
index 0000000..b9e2dbf
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/grid.rs
@@ -0,0 +1,621 @@
+use crate::render::dimension::Pt;
+
+use super::types::{
+ CellLayoutEntry, MeasuredTable, TableCellInput, TableRowInput, VerticalMergeState,
+};
+
+/// A group of rows that must stay together during page splitting.
+pub(super) struct RowGroup {
+ pub(super) start: usize,
+ pub(super) end: usize, // exclusive
+ pub(super) height: Pt,
+ /// §17.4.1: row content may be broken across pages. False if any row in
+ /// the group has `cantSplit`, if the group is a vMerge span (multiple
+ /// rows stacked here), or if any cell contains a nested table or floated
+ /// content that would be ambiguous to split.
+ pub(super) splittable: bool,
+}
+
+/// §17.4.14: compute column widths by scaling the declared `w:tblGrid` values
+/// to the available width.
+///
+/// A grid that is absent *or unusable* falls back to equal distribution. Both
+/// are the same situation: a grid summing to zero or less (every `w:gridCol`
+/// zero, or negative from a malformed file) carries no proportions to scale,
+/// and scaling it by any factor leaves every column at zero — cells laid out
+/// at zero width, with their content unreadable rather than merely misplaced.
+pub fn compute_column_widths(grid_cols: &[Pt], num_cols: usize, available_width: Pt) -> Vec<Pt> {
+ let total: Pt = grid_cols.iter().copied().sum();
+ if !grid_cols.is_empty() && total > Pt::ZERO {
+ let scale = available_width / total;
+ return grid_cols.iter().map(|w| *w * scale).collect();
+ }
+ // Prefer the caller's column count; fall back to the degenerate grid's own
+ // length so a zero-summing grid still yields one column per `w:gridCol`.
+ let n = if num_cols > 0 {
+ num_cols
+ } else {
+ grid_cols.len()
+ };
+ if n > 0 {
+ vec![available_width / n as f32; n]
+ } else {
+ Vec::new()
+ }
+}
+
+/// Build atomic row groups for pagination.
+///
+/// Groups are formed by: vMerge groups (Restart through consecutive Continue
+/// rows) and §17.4.1 cantSplit rows. Each group is an indivisible unit for
+/// page-break decisions.
+pub(super) fn build_row_groups(rows: &[TableRowInput], measured: &MeasuredTable) -> Vec<RowGroup> {
+ let mut groups = Vec::new();
+ let mut i = 0;
+ while i < rows.len() {
+ let start = i;
+ i = row_group_end(rows, start);
+ let height: Pt = measured.rows[start..i]
+ .iter()
+ .map(|mr| mr.height + mr.border_gap_below)
+ .sum();
+
+ // §17.4.1: a row may be split across pages unless it opts out via
+ // `cantSplit` or lives inside a vMerge span (grouping multiple rows).
+ // Nested tables inside cells aren't splittable either — the cell's
+ // commands would be hard to bisect cleanly.
+ let is_vmerge_span = i - start > 1;
+ let any_cant_split = rows[start..i].iter().any(|r| r.cant_split == Some(true));
+ let has_nested_table = rows[start..i]
+ .iter()
+ .flat_map(|r| r.cells.iter())
+ .any(cell_has_nested_table);
+ let splittable = !is_vmerge_span && !any_cant_split && !has_nested_table;
+
+ groups.push(RowGroup {
+ start,
+ end: i,
+ height,
+ splittable,
+ });
+ }
+ groups
+}
+
+/// Return the exclusive end of the paginator's atomic row group at `start`.
+pub(super) fn row_group_end(rows: &[TableRowInput], start: usize) -> usize {
+ let mut end = start + 1;
+ while end < rows.len()
+ && rows[end]
+ .cells
+ .iter()
+ .any(|cell| cell.vertical_merge == Some(VerticalMergeState::Continue))
+ {
+ end += 1;
+ }
+ end
+}
+
+fn cell_has_nested_table(cell: &TableCellInput) -> bool {
+ use crate::render::layout::section::LayoutBlock;
+ cell.blocks
+ .iter()
+ .any(|b| matches!(b, LayoutBlock::Table { .. }))
+}
+
+/// §17.4.85: grow the rows of each vertical merge group so the `Restart`
+/// cell's content fits within their combined height. The shortfall is spread
+/// **evenly** over the spanned rows.
+///
+/// Even distribution is a choice, not a spec rule, and ECMA-376 cannot settle
+/// it. All three places a rule would have to live were checked: §17.4.85
+/// `vMerge` defines which cells merge and carries no height language at all;
+/// §17.4.81 `trHeight`/`auto` defers to "the height required by its contents"
+/// without ever defining "contents" for a cell that spans rows; and §17.4.21
+/// `hideMark` — the spec's only row-height *rule* — says a row's height is
+/// "determined by the height of all glyphs in all cells in that row", without
+/// mentioning `vMerge`.
+///
+/// §17.4.21 constrains the answer without giving it. The model it describes is
+/// a **per-row maximum** over that row's cells, not a budget divided among
+/// rows, and even distribution (`overflow / rows`) is not expressible as a
+/// per-row maximum of anything — so of the candidates it is the one the spec's
+/// own sentence structurally disfavours. It does *not* follow that the restart
+/// row takes the excess: applied literally to a span, §17.4.21 sizes the
+/// restart row to the whole content while each `continue` row still carries its
+/// own end-of-cell mark, making the merged box taller than its content by the
+/// sum of the continue rows. No implementation does that, which is the tell
+/// that the sentence was written without merged cells in mind. The spec is
+/// silent by omission, not by implication.
+///
+/// So even distribution is disfavoured and last-row and first-row both remain
+/// open; last-row has the better structural argument (a single-pass
+/// top-to-bottom sizer can only enforce a span's total once the span closes)
+/// but no spec text. The choice is *observable* — it changes rendered output on
+/// one real corpus document — so settling it needs a Word-exported PDF of a
+/// two-row vertical merge whose restart cell overflows both rows. Until then
+/// the behaviour is pinned by `expand_spreads_overflow_across_the_merge_span`,
+/// so it cannot change silently.
+///
+/// A lone `Restart` with no `Continue` below it is not a span, and is sized by
+/// the normal row-height path in `measure_table_rows` instead.
+pub(super) fn expand_rows_for_vmerge(
+ rows: &[TableRowInput],
+ row_cell_layouts: &[Vec<CellLayoutEntry>],
+ row_heights: &mut [Pt],
+) {
+ for (row_idx, row) in rows.iter().enumerate() {
+ for (cell_ci, cell) in row.cells.iter().enumerate() {
+ if cell.vertical_merge != Some(VerticalMergeState::Restart) {
+ continue;
+ }
+
+ let entry = &row_cell_layouts[row_idx][cell_ci];
+ let content_h = entry.layout.content_height + cell.margins.vertical();
+
+ // Find last row in this merge group.
+ let mut last_merged_row = row_idx;
+ for (r, row_below) in rows.iter().enumerate().skip(row_idx + 1) {
+ if is_vmerge_continue(row_below, entry.grid_col) {
+ last_merged_row = r;
+ } else {
+ break;
+ }
+ }
+ if last_merged_row == row_idx {
+ continue;
+ }
+
+ // Distribute overflow evenly across all rows in the merge group.
+ let spanned: Pt = row_heights[row_idx..=last_merged_row].iter().copied().sum();
+ if content_h > spanned {
+ let overflow = content_h - spanned;
+ let num_rows = (last_merged_row - row_idx + 1) as f32;
+ let per_row = overflow / num_rows;
+ for h in &mut row_heights[row_idx..=last_merged_row] {
+ *h += per_row;
+ }
+ }
+ }
+ }
+}
+
+/// Find the cell in a row that covers the given absolute grid column index.
+///
+/// Returns `None` for grid columns inside the row's `gridBefore` / `gridAfter`
+/// regions (§17.4.17 / §17.4.16) — those columns have no cell in this row.
+pub(super) fn find_cell_at_grid_col(
+ row: &TableRowInput,
+ target_grid_col: usize,
+) -> Option<&TableCellInput> {
+ let mut col = row.grid_before as usize;
+ if target_grid_col < col {
+ return None;
+ }
+ for cell in &row.cells {
+ let span = cell.grid_span.max(1) as usize;
+ if target_grid_col < col + span {
+ return Some(cell);
+ }
+ col += span;
+ }
+ None
+}
+
+/// Check if the cell at `grid_col` in `row` is a vMerge Continue cell.
+pub(super) fn is_vmerge_continue(row: &TableRowInput, grid_col: usize) -> bool {
+ find_cell_at_grid_col(row, grid_col)
+ .is_some_and(|c| c.vertical_merge == Some(VerticalMergeState::Continue))
+}
+
+/// Return the cell index (not grid column) for the cell covering `grid_col`.
+/// Returns `None` for grid columns inside the row's gridBefore/gridAfter regions.
+pub(super) fn cell_index_at_grid_col(row: &TableRowInput, target_grid_col: usize) -> Option<usize> {
+ let mut col = row.grid_before as usize;
+ if target_grid_col < col {
+ return None;
+ }
+ for (i, cell) in row.cells.iter().enumerate() {
+ let span = cell.grid_span.max(1) as usize;
+ if target_grid_col < col + span {
+ return Some(i);
+ }
+ col += span;
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ── compute_column_widths ────────────────────────────────────────────
+
+ #[test]
+ fn equal_distribution_when_no_grid() {
+ let widths = compute_column_widths(&[], 3, Pt::new(300.0));
+ assert_eq!(widths.len(), 3);
+ assert_eq!(widths[0].raw(), 100.0);
+ assert_eq!(widths[1].raw(), 100.0);
+ assert_eq!(widths[2].raw(), 100.0);
+ }
+
+ #[test]
+ fn grid_cols_scaled_to_fit() {
+ let grid = vec![Pt::new(100.0), Pt::new(200.0)];
+ let widths = compute_column_widths(&grid, 2, Pt::new(600.0));
+ // Scale = 600/300 = 2.0
+ assert_eq!(widths[0].raw(), 200.0);
+ assert_eq!(widths[1].raw(), 400.0);
+ }
+
+ #[test]
+ fn grid_cols_already_fit() {
+ let grid = vec![Pt::new(150.0), Pt::new(150.0)];
+ let widths = compute_column_widths(&grid, 2, Pt::new(300.0));
+ assert_eq!(widths[0].raw(), 150.0);
+ assert_eq!(widths[1].raw(), 150.0);
+ }
+
+ #[test]
+ fn zero_cols_empty_result() {
+ let widths = compute_column_widths(&[], 0, Pt::new(300.0));
+ assert!(widths.is_empty());
+ }
+
+ /// §17.4.14: a grid that sums to zero carries no proportions, so it is
+ /// treated as absent. Scaling it instead leaves every column at zero and
+ /// every cell laying out at zero width.
+ #[test]
+ fn zero_summing_grid_falls_back_to_equal_distribution() {
+ let grid = vec![Pt::ZERO, Pt::ZERO, Pt::ZERO];
+ let widths = compute_column_widths(&grid, 3, Pt::new(300.0));
+ assert_eq!(
+ widths.iter().map(|w| w.raw()).collect::<Vec<_>>(),
+ vec![100.0, 100.0, 100.0]
+ );
+ }
+
+ /// Same for a negative total, which only a malformed file produces — the
+ /// old `scale = 1.0` fallback passed the negative widths straight through.
+ #[test]
+ fn negative_grid_total_falls_back_to_equal_distribution() {
+ let grid = vec![Pt::new(-40.0), Pt::new(10.0)];
+ let widths = compute_column_widths(&grid, 2, Pt::new(300.0));
+ assert_eq!(
+ widths.iter().map(|w| w.raw()).collect::<Vec<_>>(),
+ vec![150.0, 150.0],
+ "no column may come out negative"
+ );
+ }
+
+ /// With no caller column count, the degenerate grid's own length is used
+ /// so the table still has the right number of columns.
+ #[test]
+ fn zero_summing_grid_uses_its_own_length_when_num_cols_is_zero() {
+ let grid = vec![Pt::ZERO, Pt::ZERO];
+ let widths = compute_column_widths(&grid, 0, Pt::new(300.0));
+ assert_eq!(
+ widths.iter().map(|w| w.raw()).collect::<Vec<_>>(),
+ vec![150.0, 150.0]
+ );
+ }
+
+ // ── grid_before lookups ──────────────────────────────────────────────────────────────────────────────
+
+ use super::super::types::CellVAlign;
+ use crate::render::geometry::PtEdgeInsets;
+
+ fn empty_cell(grid_span: u32) -> TableCellInput {
+ TableCellInput {
+ blocks: Vec::new(),
+ margins: PtEdgeInsets::ZERO,
+ grid_span,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ fn row_with_offsets(cells: Vec<TableCellInput>, grid_before: u32) -> TableRowInput {
+ TableRowInput {
+ cells,
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before,
+ border_overrides: None,
+ }
+ }
+
+ #[test]
+ fn find_cell_skips_grid_before() {
+ // §17.4.17: gridBefore=1 means cell 0 starts at grid_col 1.
+ // §17.4.16: gridAfter=1 means the row leaves grid_col 3 empty.
+ let row = row_with_offsets(vec![empty_cell(1), empty_cell(1)], 1);
+ assert!(find_cell_at_grid_col(&row, 0).is_none());
+ assert!(find_cell_at_grid_col(&row, 1).is_some());
+ assert!(find_cell_at_grid_col(&row, 2).is_some());
+ assert!(find_cell_at_grid_col(&row, 3).is_none());
+ }
+
+ #[test]
+ fn cell_index_at_grid_col_skips_grid_before() {
+ let row = row_with_offsets(vec![empty_cell(1), empty_cell(1)], 1);
+ assert_eq!(cell_index_at_grid_col(&row, 0), None);
+ assert_eq!(cell_index_at_grid_col(&row, 1), Some(0));
+ assert_eq!(cell_index_at_grid_col(&row, 2), Some(1));
+ assert_eq!(cell_index_at_grid_col(&row, 3), None);
+ }
+
+ #[test]
+ fn find_cell_with_grid_span_after_grid_before() {
+ // gridBefore=2; one cell with span=2 should occupy grid cols 2 and 3.
+ let row = row_with_offsets(vec![empty_cell(2)], 2);
+ assert!(find_cell_at_grid_col(&row, 0).is_none());
+ assert!(find_cell_at_grid_col(&row, 1).is_none());
+ assert!(find_cell_at_grid_col(&row, 2).is_some());
+ assert!(find_cell_at_grid_col(&row, 3).is_some());
+ assert!(find_cell_at_grid_col(&row, 4).is_none());
+ }
+
+ // ── §17.4.85 row_group_end / §17.4.1 build_row_groups ────────────────
+ //
+ // These three functions decide every table page break and the whole
+ // vertical-merge height distribution, and had no direct tests — the hole
+ // a zero-height row was found hiding in.
+
+ use super::super::types::MeasuredRow;
+ use crate::render::layout::cell::CellLayout;
+ use crate::render::layout::section::LayoutBlock;
+
+ fn merged_cell(vmerge: Option<VerticalMergeState>) -> TableCellInput {
+ TableCellInput {
+ vertical_merge: vmerge,
+ ..empty_cell(1)
+ }
+ }
+
+ fn plain_row(cells: Vec<TableCellInput>) -> TableRowInput {
+ row_with_offsets(cells, 0)
+ }
+
+ /// A `MeasuredTable` carrying only the per-row heights `build_row_groups`
+ /// reads — `(height, border_gap_below)` pairs.
+ fn measured(rows: &[(f32, f32)]) -> MeasuredTable {
+ MeasuredTable {
+ rows: rows
+ .iter()
+ .map(|&(h, gap)| MeasuredRow {
+ entries: Vec::new(),
+ borders: Vec::new(),
+ height: Pt::new(h),
+ leading_gap: Pt::ZERO,
+ border_gap_below: Pt::new(gap),
+ })
+ .collect(),
+ table_width: Pt::new(100.0),
+ }
+ }
+
+ #[test]
+ fn row_group_end_is_one_row_when_nothing_continues() {
+ let rows = vec![
+ plain_row(vec![merged_cell(None)]),
+ plain_row(vec![merged_cell(None)]),
+ ];
+ assert_eq!(row_group_end(&rows, 0), 1);
+ assert_eq!(row_group_end(&rows, 1), 2, "last row still yields len");
+ }
+
+ #[test]
+ fn row_group_end_spans_consecutive_continue_rows() {
+ let rows = vec![
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Restart))]),
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Continue))]),
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Continue))]),
+ plain_row(vec![merged_cell(None)]),
+ ];
+ assert_eq!(row_group_end(&rows, 0), 3, "restart + two continues");
+ assert_eq!(row_group_end(&rows, 3), 4);
+ }
+
+ /// A `Continue` anywhere in the row extends the group — the merge need not
+ /// be in the first column.
+ #[test]
+ fn row_group_end_triggers_on_a_continue_in_any_column() {
+ let rows = vec![
+ plain_row(vec![merged_cell(None), merged_cell(None)]),
+ plain_row(vec![
+ merged_cell(None),
+ merged_cell(Some(VerticalMergeState::Continue)),
+ ]),
+ ];
+ assert_eq!(row_group_end(&rows, 0), 2);
+ }
+
+ #[test]
+ fn build_row_groups_treats_plain_rows_as_separate_splittable_groups() {
+ let rows = vec![
+ plain_row(vec![merged_cell(None)]),
+ plain_row(vec![merged_cell(None)]),
+ ];
+ let groups = build_row_groups(&rows, &measured(&[(20.0, 0.0), (30.0, 0.0)]));
+ assert_eq!(groups.len(), 2);
+ assert!(groups.iter().all(|g| g.splittable));
+ assert_eq!(groups[0].height.raw(), 20.0);
+ assert_eq!(groups[1].height.raw(), 30.0);
+ }
+
+ /// §17.4.38: the gap left for a row's bottom border counts toward the
+ /// group height, or a group would be judged to fit in less space than it
+ /// occupies.
+ #[test]
+ fn build_row_groups_height_includes_the_border_gap_below() {
+ let rows = vec![plain_row(vec![merged_cell(None)])];
+ let groups = build_row_groups(&rows, &measured(&[(20.0, 3.0)]));
+ assert_eq!(groups[0].height.raw(), 23.0);
+ }
+
+ /// §17.4.85: a merge span is indivisible, so its group covers every row
+ /// and is not splittable.
+ #[test]
+ fn build_row_groups_marks_a_vmerge_span_unsplittable() {
+ let rows = vec![
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Restart))]),
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Continue))]),
+ ];
+ let groups = build_row_groups(&rows, &measured(&[(20.0, 0.0), (20.0, 0.0)]));
+ assert_eq!(groups.len(), 1);
+ assert_eq!((groups[0].start, groups[0].end), (0, 2));
+ assert_eq!(groups[0].height.raw(), 40.0, "span height is the sum");
+ assert!(!groups[0].splittable);
+ }
+
+ /// §17.4.1 `cantSplit` — a single row can opt out on its own.
+ #[test]
+ fn build_row_groups_marks_a_cant_split_row_unsplittable() {
+ let mut row = plain_row(vec![merged_cell(None)]);
+ row.cant_split = Some(true);
+ let groups = build_row_groups(&[row], &measured(&[(20.0, 0.0)]));
+ assert!(!groups[0].splittable);
+ }
+
+ /// A nested table's commands can't be bisected cleanly, so its row is
+ /// atomic even without `cantSplit`.
+ #[test]
+ fn build_row_groups_marks_a_nested_table_row_unsplittable() {
+ let nested = TableCellInput {
+ blocks: vec![LayoutBlock::Table {
+ rows: Vec::new(),
+ col_widths: Vec::new(),
+ cell_spacing: Pt::ZERO,
+ border_config: None,
+ indent: Pt::ZERO,
+ alignment: None,
+ float_info: None,
+ style_id: None,
+ }],
+ ..empty_cell(1)
+ };
+ let groups = build_row_groups(&[plain_row(vec![nested])], &measured(&[(20.0, 0.0)]));
+ assert!(!groups[0].splittable);
+ }
+
+ // ── §17.4.85 expand_rows_for_vmerge ──────────────────────────────────
+
+ fn layout_entry(content_height: f32, grid_col: usize) -> CellLayoutEntry {
+ CellLayoutEntry {
+ layout: CellLayout {
+ commands: Vec::new(),
+ content_height: Pt::new(content_height),
+ lines: Vec::new(),
+ },
+ cell_x: Pt::ZERO,
+ cell_w: Pt::new(100.0),
+ grid_col,
+ }
+ }
+
+ /// The core §17.4.85 behaviour: when a `Restart` cell's content exceeds the
+ /// rows it spans, the shortfall is spread across them.
+ ///
+ /// Note this pins **even distribution**, which is what the code does and
+ /// not obviously what Word does — see `expand_rows_for_vmerge` for why
+ /// ECMA-376 cannot settle it and why even distribution is in fact the
+ /// candidate §17.4.21 structurally disfavours. This test will need updating
+ /// if a Word reference render settles it the other way; it exists to make
+ /// that a deliberate change rather than a silent one.
+ #[test]
+ fn expand_spreads_overflow_across_the_merge_span() {
+ let rows = vec![
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Restart))]),
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Continue))]),
+ ];
+ let layouts = vec![vec![layout_entry(84.0, 0)], vec![layout_entry(0.0, 0)]];
+ let mut heights = [Pt::new(14.0), Pt::new(14.0)];
+
+ expand_rows_for_vmerge(&rows, &layouts, &mut heights);
+
+ // 84pt of content over a 28pt span → 56pt spread over 2 rows.
+ assert_eq!(heights[0].raw(), 42.0);
+ assert_eq!(heights[1].raw(), 42.0);
+ assert_eq!(
+ heights[0].raw() + heights[1].raw(),
+ 84.0,
+ "the span must total the restart cell's content height"
+ );
+ }
+
+ #[test]
+ fn expand_leaves_heights_alone_when_the_content_already_fits() {
+ let rows = vec![
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Restart))]),
+ plain_row(vec![merged_cell(Some(VerticalMergeState::Continue))]),
+ ];
+ let layouts = vec![vec![layout_entry(10.0, 0)], vec![layout_entry(0.0, 0)]];
+ let mut heights = [Pt::new(30.0), Pt::new(30.0)];
+
+ expand_rows_for_vmerge(&rows, &layouts, &mut heights);
+
+ assert_eq!(heights[0].raw(), 30.0);
+ assert_eq!(heights[1].raw(), 30.0);
+ }
+
+ /// A `Restart` with nothing continuing under it is left completely alone —
+ /// the early return when the group is a single row.
+ ///
+ /// This is the companion to the fix in `measure.rs`: because this function
+ /// contributes nothing here, the row's height has to come from the normal
+ /// `max_height` path instead, or the row collapses to zero while still
+ /// drawing its content.
+ #[test]
+ fn expand_does_nothing_for_a_lone_restart() {
+ let rows = vec![plain_row(vec![merged_cell(Some(
+ VerticalMergeState::Restart,
+ ))])];
+ let layouts = vec![vec![layout_entry(84.0, 0)]];
+ let mut heights = [Pt::new(14.0)];
+
+ expand_rows_for_vmerge(&rows, &layouts, &mut heights);
+
+ assert_eq!(
+ heights[0].raw(),
+ 14.0,
+ "a one-row span is not expanded — measure.rs must size this row"
+ );
+ }
+
+ /// The span is tracked by **grid column**, not by cell index.
+ ///
+ /// §17.4.17 `gridBefore` is what makes those differ: the lower row's
+ /// *first* cell is a `Continue`, but it sits in grid column 1, so it does
+ /// not continue a merge that started in column 0. Indexing by cell
+ /// position instead would wrongly join them — and a test where the restart
+ /// happens to sit at `grid_col == cell_index` cannot tell the two apart.
+ #[test]
+ fn expand_matches_continues_by_grid_column_not_cell_index() {
+ let rows = vec![
+ plain_row(vec![
+ merged_cell(Some(VerticalMergeState::Restart)), // grid col 0
+ merged_cell(None), // grid col 1
+ ]),
+ // gridBefore=1: this row's cells[0] is at grid column 1, not 0.
+ row_with_offsets(vec![merged_cell(Some(VerticalMergeState::Continue))], 1),
+ ];
+ let layouts = vec![
+ vec![layout_entry(84.0, 0), layout_entry(0.0, 1)],
+ vec![layout_entry(0.0, 1)],
+ ];
+ let mut heights = [Pt::new(14.0), Pt::new(14.0)];
+
+ expand_rows_for_vmerge(&rows, &layouts, &mut heights);
+
+ assert_eq!(
+ [heights[0].raw(), heights[1].raw()],
+ [14.0, 14.0],
+ "the Continue is in column 1; column 0's restart has no continuation"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/measure.rs b/crates/liteparse-docx/src/render/layout/table/measure.rs
new file mode 100644
index 0000000..1235989
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/measure.rs
@@ -0,0 +1,874 @@
+//! Table measurement phase — cell layout and border resolution.
+
+use crate::render::dimension::Pt;
+
+use crate::render::layout::cell::{CellLayout, layout_cell};
+
+use super::borders::{
+ CellBorders, CellEdge, border_width, resolve_border_conflict, resolve_cell_effective_borders,
+};
+use super::grid::{cell_index_at_grid_col, expand_rows_for_vmerge, is_vmerge_continue};
+use super::types::{
+ CellLayoutEntry, MeasuredRow, MeasuredTable, RowHeightRule, TableBorderConfig, TableRowInput,
+ VerticalMergeState,
+};
+
+/// Measure all table rows: resolve borders, lay out cell content, compute heights.
+/// This is the shared measurement phase used by both `layout_table` (monolithic)
+/// and `layout_table_paginated` (page-splitting).
+///
+/// §17.4.38: `suppress_first_row_top` — when `true`, the top border of the first
+/// row is suppressed. Used for adjacent table border collapse: consecutive tables
+/// with the same style are treated as a single merged table, so the second table's
+/// top border would duplicate the first table's bottom border.
+pub(super) fn measure_table_rows(
+ rows: &[TableRowInput],
+ col_widths: &[Pt],
+ // §17.4.44 `tblCellSpacing`, already resolved to points. Zero for every
+ // table that does not set it, which is the overwhelming majority.
+ cell_spacing: Pt,
+ default_line_height: Pt,
+ borders: Option<&TableBorderConfig>,
+ measure_text: crate::render::layout::paragraph::MeasureTextFn<'_>,
+ suppress_first_row_top: bool,
+) -> MeasuredTable {
+ // §17.4.44: the slots were shrunk by one `cell_spacing` before they got
+ // here, so adding it back recovers the table's own outer width — the
+ // spacing is carved out of the table, not added to it.
+ let table_width: Pt = col_widths.iter().copied().sum::<Pt>() + cell_spacing;
+ let num_rows = rows.len();
+ let mut row_heights = Vec::with_capacity(num_rows);
+
+ // Pass 2a: resolve borders for every cell.
+ let mut resolved_borders: Vec<Vec<CellBorders>> = Vec::new();
+ {
+ let mut grid_indices: Vec<Vec<usize>> = Vec::new();
+ for (row_idx, row) in rows.iter().enumerate() {
+ let mut row_borders = Vec::new();
+ let mut row_grid = Vec::new();
+ // §17.4.17: gridBefore — the row's first cell starts at grid_col
+ // `grid_before`, leaving the leftmost columns empty.
+ let mut grid_idx = row.grid_before as usize;
+ // §17.4.61: a row may carry per-row border overrides
+ // (`<w:tblPrEx><w:tblBorders/></w:tblPrEx>`). When set,
+ // it's the *fully merged* effective table borders for this
+ // row — the build layer already overlaid the override on
+ // the table's own borders so the model-layer
+ // "explicitly none" vs "not specified" distinction is
+ // preserved during conversion. Use it verbatim; otherwise
+ // fall back to the table-wide config.
+ let row_table_borders = row.border_overrides.as_ref().or(borders);
+ for cell_input in row.cells.iter() {
+ let span = cell_input.grid_span.max(1) as usize;
+ let (mut b_top, mut b_bottom, b_left, b_right) = resolve_cell_effective_borders(
+ cell_input,
+ row_table_borders,
+ row_idx,
+ grid_idx,
+ span,
+ num_rows,
+ col_widths.len(),
+ );
+ if cell_input.vertical_merge == Some(VerticalMergeState::Continue) {
+ b_top = CellEdge::Absent;
+ }
+ if row_idx + 1 < num_rows && is_vmerge_continue(&rows[row_idx + 1], grid_idx) {
+ b_bottom = CellEdge::Absent;
+ }
+ row_borders.push(CellBorders {
+ top: b_top,
+ bottom: b_bottom,
+ left: b_left,
+ right: b_right,
+ });
+ row_grid.push(grid_idx);
+ grid_idx += cell_input.grid_span.max(1) as usize;
+ }
+ resolved_borders.push(row_borders);
+ grid_indices.push(row_grid);
+ }
+
+ // [MS-OI29500] §17.4.66: *"If the cell spacing is nonzero ... then all
+ // cell borders and outer table borders display."* With a gap between
+ // them, adjacent cells share no edge, so there is no conflict to
+ // resolve and every cell keeps its own four borders. Collapsing them
+ // here would delete borders that must be drawn, and drawing both sides
+ // of a collapsed edge would double every line.
+ let collapse_borders = cell_spacing <= Pt::ZERO;
+
+ // §17.4.66: conflict resolution at vertical shared edges (a cell's
+ // right vs. its right neighbour's left). Drawn once on the left cell.
+ for row_idx in 0..if collapse_borders { num_rows } else { 0 } {
+ let num_cells = rows[row_idx].cells.len();
+ for cell_ci in 0..num_cells.saturating_sub(1) {
+ let right = resolved_borders[row_idx][cell_ci].right;
+ let left = resolved_borders[row_idx][cell_ci + 1].left;
+ let winner = resolve_border_conflict(right, left);
+ resolved_borders[row_idx][cell_ci].right = winner;
+ resolved_borders[row_idx][cell_ci + 1].left = CellEdge::Absent;
+ }
+ }
+
+ // [MS-OI29500] §17.4.66: conflict resolution at horizontal shared edges (row R's
+ // bottom vs. row R+1's top). Resolved *per grid column* because a
+ // `gridSpan` cell in one row can face several cells in the other:
+ // • wide upper cell over several lower cells — resolving only the
+ // first lower cell (and nulling the rest) drops their borders;
+ // • wide lower cell under several upper cells — a nil spacer among
+ // them must not punch a gap through the lower cell's border.
+ //
+ // The whole edge is then drawn from *one* side (all upper bottoms, or
+ // all lower tops). This matters visually: an upper-row bottom sits in
+ // the inter-row gap while a lower-row top sits just below it, so
+ // splitting a single line between the two sides would offset segments
+ // by the border width. A cell paints one border across its width, so
+ // a side can own the edge only if each of its cells spans a run of
+ // columns whose resolved border is uniform; upper is preferred (it
+ // keeps the aligned-grid path and page-split top restoration valid).
+ let ncols = col_widths.len();
+ for upper in 0..if collapse_borders {
+ num_rows.saturating_sub(1)
+ } else {
+ 0
+ } {
+ let lower = upper + 1;
+
+ // Per-column resolved border for this inter-row edge.
+ let resolved: Vec<CellEdge> = (0..ncols)
+ .map(|gc| {
+ let edge = |row: usize, pick: fn(&CellBorders) -> CellEdge| {
+ cell_index_at_grid_col(&rows[row], gc)
+ .map(|ci| pick(&resolved_borders[row][ci]))
+ .unwrap_or(CellEdge::Absent)
+ };
+ resolve_border_conflict(edge(upper, |b| b.bottom), edge(lower, |b| b.top))
+ })
+ .collect();
+
+ // A row can paint the whole edge iff (a) it has a cell over every
+ // column that carries a border — a row whose `gridSpan` leaves a
+ // bordered column uncovered (its gridAfter gap) can't draw that
+ // column, so the other row must — and (b) each of its cells spans
+ // a uniform run of resolved columns (a cell paints one border
+ // across its width). Without (a), a partly-covered cell would draw
+ // its own top *and* the covering row its bottom → a doubled line.
+ let can_own = |row_idx: usize| -> bool {
+ let covers_bordered_cols = (0..ncols).all(|gc| {
+ resolved[gc].line().is_none()
+ || cell_index_at_grid_col(&rows[row_idx], gc).is_some()
+ });
+ covers_bordered_cols
+ && grid_indices[row_idx]
+ .iter()
+ .enumerate()
+ .all(|(ci, &start)| {
+ let span = rows[row_idx].cells[ci].grid_span.max(1) as usize;
+ let end = (start + span).min(ncols);
+ start >= end
+ || (start..end).all(|gc| resolved[gc].paints_same(resolved[start]))
+ })
+ };
+
+ if !can_own(upper) && can_own(lower) {
+ // Wide upper cell can't paint the mixed edge; draw it entirely
+ // from the finer lower row so the line stays at one y (e.g. a
+ // label cell right of a nil spacer under a gridSpan header).
+ for (ci, &start) in grid_indices[lower].iter().enumerate() {
+ let span = rows[lower].cells[ci].grid_span.max(1) as usize;
+ let end = (start + span).min(ncols);
+ if start < end {
+ resolved_borders[lower][ci].top = resolved[start];
+ }
+ }
+ for b in resolved_borders[upper].iter_mut() {
+ b.bottom = CellEdge::Absent;
+ }
+ } else {
+ // Upper row owns the edge: each upper cell paints its uniform
+ // run (a nil spacer above a gridSpan cell resolves to that
+ // cell's inherited border, so no gap), and lower tops it
+ // covers are cleared. Columns an upper cell can't paint
+ // uniformly (only reachable in the both-non-uniform fallback)
+ // fall through to the lower cell.
+ let mut covered = vec![false; ncols];
+ for (ci, &start) in grid_indices[upper].iter().enumerate() {
+ let span = rows[upper].cells[ci].grid_span.max(1) as usize;
+ let end = (start + span).min(ncols);
+ if start >= end {
+ continue;
+ }
+ if (start..end).all(|gc| resolved[gc].paints_same(resolved[start])) {
+ resolved_borders[upper][ci].bottom = resolved[start];
+ for c in covered.iter_mut().take(end).skip(start) {
+ *c = true;
+ }
+ } else {
+ resolved_borders[upper][ci].bottom = CellEdge::Absent;
+ }
+ }
+ for (ci, &start) in grid_indices[lower].iter().enumerate() {
+ let span = rows[lower].cells[ci].grid_span.max(1) as usize;
+ let end = (start + span).min(ncols);
+ if start >= end {
+ continue;
+ }
+ if (start..end).any(|gc| covered[gc]) {
+ // Any column already painted from above → defer the
+ // whole cell so a partly-covered span can't double up.
+ resolved_borders[lower][ci].top = CellEdge::Absent;
+ } else if (start..end).all(|gc| resolved[gc].paints_same(resolved[start])) {
+ resolved_borders[lower][ci].top = resolved[start];
+ } else {
+ resolved_borders[lower][ci].top = CellEdge::Absent;
+ }
+ }
+ }
+ }
+
+ // §17.4.38: suppress first-row top borders for adjacent table collapse.
+ if suppress_first_row_top && !resolved_borders.is_empty() {
+ for b in &mut resolved_borders[0] {
+ b.top = CellEdge::Absent;
+ }
+ }
+ }
+
+ // Pass 2b: lay out each cell.
+ let mut row_cell_layouts: Vec<Vec<CellLayoutEntry>> = Vec::new();
+
+ for (row_idx, row) in rows.iter().enumerate() {
+ let mut entries = Vec::new();
+ let mut max_height = Pt::ZERO;
+ // §17.4.17: gridBefore — first cell offset.
+ let mut grid_idx = row.grid_before as usize;
+
+ for (cell_ci, cell) in row.cells.iter().enumerate() {
+ let span = cell.grid_span.max(1) as usize;
+ // Defensive clamp: malformed DOCX where gridBefore + spans + gridAfter
+ // exceed the grid would otherwise panic in the slice index below.
+ // Both ends need clamping — clamping only `grid_end` inverts the
+ // range (`start > end`), which panics just as an out-of-bounds end
+ // would. Mirrors the same clamp in `build/table.rs`.
+ let grid_start = grid_idx.min(col_widths.len());
+ let grid_end = (grid_start + span).min(col_widths.len());
+ // §17.4.44: the grid slots were already shrunk so they sum to
+ // `table_width - cell_spacing`; offsetting every cell by one
+ // spacing and taking one off its width then leaves exactly
+ // `cell_spacing` between adjacent cells *and* at both table edges,
+ // without changing the table's own width. A `gridSpan` cell
+ // absorbs the interior gaps it covers, which is what a merged cell
+ // should do.
+ let slots: Pt = col_widths[grid_start..grid_end].iter().copied().sum();
+ let cell_w: Pt = (slots - cell_spacing).max(Pt::ZERO);
+ let cell_x: Pt = col_widths[..grid_start].iter().copied().sum::<Pt>() + cell_spacing;
+
+ let b = &resolved_borders[row_idx][cell_ci];
+ let extra_left = (border_width(b.left) - cell.margins.left).max(Pt::ZERO);
+ let extra_right = (border_width(b.right) - cell.margins.right).max(Pt::ZERO);
+ let layout_w = (cell_w - extra_left - extra_right).max(Pt::ZERO);
+
+ let is_continue = cell.vertical_merge == Some(VerticalMergeState::Continue);
+ let layout = if is_continue {
+ CellLayout {
+ commands: Vec::new(),
+ content_height: Pt::ZERO,
+ lines: Vec::new(),
+ }
+ } else {
+ layout_cell(
+ &cell.blocks,
+ layout_w,
+ &cell.margins,
+ default_line_height,
+ measure_text,
+ )
+ };
+
+ // §17.4.85: a merged cell's height is normally decided by
+ // `expand_rows_for_vmerge` over the whole span, not here — folding a
+ // `Restart` cell's full content into its *first* row would double-count
+ // it against the rows below.
+ //
+ // Unless the span is a span of one. A `Restart` with no `Continue`
+ // under it is an ordinary cell, and `expand_rows_for_vmerge` skips it
+ // (it returns early when the group is a single row), so if this branch
+ // skipped it too the row would get **no** height from any path while
+ // still emitting its content — following blocks then draw on top of
+ // the table. Word treats a restart with nothing continuing as a plain
+ // cell, which is what this reproduces.
+ let continues_below =
+ row_idx + 1 < num_rows && is_vmerge_continue(&rows[row_idx + 1], grid_idx);
+ let is_lone_restart =
+ cell.vertical_merge == Some(VerticalMergeState::Restart) && !continues_below;
+ if cell.vertical_merge.is_none() || is_lone_restart {
+ max_height = max_height.max(layout.content_height + cell.margins.vertical());
+ }
+
+ entries.push(CellLayoutEntry {
+ layout,
+ cell_x,
+ cell_w,
+ grid_col: grid_idx,
+ });
+ grid_idx += span;
+ }
+
+ match row.height_rule {
+ Some(RowHeightRule::AtLeast(min_h)) => max_height = max_height.max(min_h),
+ Some(RowHeightRule::Exact(h)) => max_height = h,
+ None => {}
+ }
+
+ // §17.4.44: the row's box reserves its own leading gap, mirroring the
+ // horizontal inset above — `emit_one_row` places content one spacing
+ // below the cursor, so consecutive rows end up exactly `cell_spacing`
+ // apart. `RowHeightRule` is applied to the *content* height first, so a
+ // `trHeight` still means the height of the row's content, not of the
+ // content plus a gap the author never asked for.
+ row_heights.push(max_height + cell_spacing);
+ row_cell_layouts.push(entries);
+ }
+
+ // §17.4.85: distribute vMerge overflow.
+ expand_rows_for_vmerge(rows, &row_cell_layouts, &mut row_heights);
+
+ // Compute border gaps and assemble measured rows.
+ let measured_rows: Vec<MeasuredRow> = row_cell_layouts
+ .into_iter()
+ .zip(resolved_borders)
+ .zip(row_heights.iter())
+ .enumerate()
+ .map(|(row_idx, ((entries, borders), &height))| {
+ // With cell spacing there is no shared edge to reserve room for:
+ // every cell draws its own bottom border inside its own box, and
+ // the gap between rows is the spacing itself.
+ let border_gap_below = if row_idx + 1 < num_rows && cell_spacing <= Pt::ZERO {
+ borders
+ .iter()
+ .map(|b| border_width(b.bottom))
+ .fold(Pt::ZERO, Pt::max)
+ } else {
+ Pt::ZERO
+ };
+ MeasuredRow {
+ entries,
+ borders,
+ height,
+ leading_gap: cell_spacing,
+ border_gap_below,
+ }
+ })
+ .collect();
+
+ MeasuredTable {
+ rows: measured_rows,
+ table_width,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::borders::CellEdge;
+ use super::super::types::{
+ CellBorderConfig, CellBorderOverride, CellVAlign, TableBorderConfig, TableBorderLine,
+ TableBorderStyle, TableCellInput, TableRowInput,
+ };
+ use super::measure_table_rows;
+ use crate::render::dimension::Pt;
+ use crate::render::geometry::PtEdgeInsets;
+ use crate::render::resolve::color::RgbColor;
+
+ fn single(w: f32) -> TableBorderLine {
+ TableBorderLine {
+ width: Pt::new(w),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }
+ }
+
+ /// A table style like `Tabellenraster`: every side plus insideH/insideV.
+ fn all_single() -> TableBorderConfig {
+ let s = single(0.5);
+ TableBorderConfig {
+ top: Some(s),
+ bottom: Some(s),
+ left: Some(s),
+ right: Some(s),
+ inside_h: Some(s),
+ inside_v: Some(s),
+ }
+ }
+
+ fn cb(top: Option<CellBorderOverride>, bottom: Option<CellBorderOverride>) -> CellBorderConfig {
+ CellBorderConfig {
+ top,
+ bottom,
+ left: None,
+ right: None,
+ }
+ }
+
+ fn cell(span: u32, borders: Option<CellBorderConfig>) -> TableCellInput {
+ TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: span,
+ shading: None,
+ cell_borders: borders,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ fn row(cells: Vec<TableCellInput>) -> TableRowInput {
+ TableRowInput {
+ cells,
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }
+ }
+
+ /// [MS-OI29500] §17.4.66 regression: a `gridSpan` upper cell facing several
+ /// lower cells must not drop the later cells' top borders (previously only
+ /// the first lower cell was resolved and the rest nulled), and the whole
+ /// shared edge must be drawn from a single side so the line does not split
+ /// across two y positions. Mirrors the real doc's
+ /// `[spacer | Function: | Qualitätssicherung]` row under a `gridSpan` header.
+ ///
+ /// Non-uniformity comes from a **heavier border on one column**, not from a
+ /// `nil`. It used to come from a nil, which worked only while nil resolved
+ /// to "absent": now that nil suppresses (§17.4.66), a nil under the wide
+ /// cell makes its run uniformly suppressed and the upper row owns the edge —
+ /// the opposite branch, so the configuration no longer reaches the bug this
+ /// test exists for. Suppression is covered separately by
+ /// `nil_suppresses_across_a_gridspan_mismatch`.
+ #[test]
+ fn wide_upper_cell_draws_whole_edge_from_lower_row() {
+ let s = single(0.5);
+ let heavy = single(2.0);
+ let rows = vec![
+ // Row 0: gridSpan=2 header over spacer+Function, then two single
+ // cells over the Qualitätssicherung span. All bottoms inherit.
+ row(vec![cell(2, None), cell(1, None), cell(1, None)]),
+ // Row 1: [spacer | Function (heavy top) | Q (gridSpan=2)]. The heavy
+ // top on column 1 alone makes the wide upper cell's run non-uniform.
+ row(vec![
+ cell(1, None),
+ cell(1, Some(cb(Some(CellBorderOverride::Border(heavy)), None))),
+ cell(2, None),
+ ]),
+ ];
+ let cols = vec![Pt::new(100.0); 4];
+ let m = measure_table_rows(
+ &rows,
+ &cols,
+ Pt::ZERO,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ // Whole edge drawn from the lower row → every upper bottom cleared,
+ // so Function and Qualitätssicherung tops share one y position.
+ for b in &m.rows[0].borders {
+ assert_eq!(
+ b.bottom,
+ CellEdge::Absent,
+ "upper bottoms cleared (edge owned below)"
+ );
+ }
+ assert_eq!(
+ m.rows[1].borders[0].top.line(),
+ Some(s),
+ "spacer column keeps the inherited insideH"
+ );
+ assert_eq!(
+ m.rows[1].borders[1].top.line(),
+ Some(heavy),
+ "Function keeps its heavier top border across the gridSpan mismatch"
+ );
+ assert_eq!(
+ m.rows[1].borders[2].top.line(),
+ Some(s),
+ "Qualitätssicherung top drawn from the same (lower) side as Function"
+ );
+ }
+
+ /// §17.4.66 step 0 across a `gridSpan` mismatch: a `nil` bottom on a wide
+ /// upper cell suppresses the columns it spans that fall back to the table —
+ /// but **not** the column where the lower cell has a border of its own,
+ /// which survives and is drawn from below. One nil bottom therefore resolves to two different
+ /// answers along its own width, which is exactly the case that forces the
+ /// per-column resolution this pass does.
+ ///
+ /// This is the configuration `wide_upper_cell_draws_whole_edge_from_lower_row`
+ /// used to carry, kept here for what it now demonstrates.
+ #[test]
+ fn nil_suppresses_across_a_gridspan_mismatch() {
+ let s = single(0.5);
+ let rows = vec![
+ row(vec![
+ cell(2, Some(cb(None, Some(CellBorderOverride::Suppress)))),
+ cell(1, None),
+ cell(1, None),
+ ]),
+ row(vec![
+ cell(1, Some(cb(Some(CellBorderOverride::Suppress), None))),
+ cell(1, Some(cb(Some(CellBorderOverride::Border(s)), None))),
+ cell(2, None),
+ ]),
+ ];
+ let cols = vec![Pt::new(100.0); 4];
+ let m = measure_table_rows(
+ &rows,
+ &cols,
+ Pt::ZERO,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ // The nil bottom spans columns 0-1 and resolves differently on each:
+ // column 0 faces another nil and stays suppressed, column 1 faces
+ // Function's *declared* top and loses to it. A cell paints one border
+ // across its width, so that split hands the whole edge to the lower row.
+ for b in &m.rows[0].borders {
+ assert_eq!(
+ b.bottom,
+ CellEdge::Absent,
+ "upper bottoms cleared — the nil span is not uniform, so the edge is owned below"
+ );
+ }
+ assert_eq!(
+ m.rows[1].borders[0].top,
+ CellEdge::Suppressed,
+ "column 0: nil against nil stays suppressed"
+ );
+ assert_eq!(
+ m.rows[1].borders[1].top.line(),
+ Some(s),
+ "column 1: Function has a top of its own, so the nil above does not erase it"
+ );
+ // Columns outside the nil span keep the inherited insideH, drawn from
+ // the same (lower) side so the line sits at one y.
+ assert_eq!(m.rows[1].borders[2].top.line(), Some(s));
+ }
+
+ /// A cell can paint one border across its whole span when every column under
+ /// it *paints the same thing* — not when every column resolved to the same
+ /// `CellEdge`. `Absent` and `Suppressed` both paint nothing, so a run
+ /// mixing them is uniform; comparing with `==` would split it and hand the
+ /// edge to the other row for no visible reason.
+ ///
+ /// Built so the two columns differ **only** in that: with no `insideH` to
+ /// inherit, column 0 resolves to `Suppressed` (the lower cell wrote `nil`)
+ /// and column 1 to `Absent` (nobody said anything). Neither paints.
+ ///
+ /// The upper cell must end up owning the edge, and carrying `Suppressed`
+ /// while doing so — `emit.rs` restores an `Absent` top at a page split and
+ /// must not restore an emptied one, so which of the two lands there is a
+ /// real distinction, not bookkeeping.
+ #[test]
+ fn a_uniform_run_is_not_split_by_absent_versus_suppressed() {
+ let hair = single(0.5);
+ let borders = TableBorderConfig {
+ top: Some(hair),
+ bottom: Some(hair),
+ left: Some(hair),
+ right: Some(hair),
+ // Nothing to inherit on the inter-row edge — so the only states in
+ // play there are `Absent` and `Suppressed`.
+ inside_h: None,
+ inside_v: Some(hair),
+ };
+ let rows = vec![
+ // One wide cell saying nothing about its bottom.
+ row(vec![cell(2, None)]),
+ // Column 0 writes `nil`; column 1 says nothing.
+ row(vec![
+ cell(1, Some(cb(Some(CellBorderOverride::Suppress), None))),
+ cell(1, None),
+ ]),
+ ];
+ let cols = vec![Pt::new(100.0), Pt::new(100.0)];
+ let m = measure_table_rows(
+ &rows,
+ &cols,
+ Pt::ZERO,
+ Pt::new(10.0),
+ Some(&borders),
+ None,
+ false,
+ );
+
+ assert_eq!(
+ m.rows[0].borders[0].bottom,
+ CellEdge::Suppressed,
+ "the wide cell owns the whole edge, carrying the suppression"
+ );
+ assert_eq!(
+ m.rows[1].borders[0].top,
+ CellEdge::Absent,
+ "so the lower row's tops are cleared"
+ );
+ assert_eq!(m.rows[1].borders[1].top, CellEdge::Absent);
+ }
+
+ /// §17.4.66: a `nil` among the cells on one side of an edge **cannot** punch
+ /// a gap through a wide `gridSpan` cell facing it. The wide cell inherits
+ /// `insideH` for its whole width and paints one border across it; a
+ /// neighbour's `nil` empties only that neighbour's own edge.
+ ///
+ /// This is `IP 05 Trenches`' `Date/Time:` cell with the sides swapped — the
+ /// real document has the wide spacer cell *below*, its `nil` aimed at the
+ /// narrow spacer column, and the label cell above still draws the bottom it
+ /// inherited. The assertion here was inverted twice: once when `nil`
+ /// wrongly collapsed to "absent" (so it also wrongly *inherited*), and once
+ /// when `nil` was made to win the conflict outright. Declining inheritance
+ /// and overruling the neighbour are different powers; `nil` has only the
+ /// first.
+ #[test]
+ fn nil_spacer_cannot_punch_a_gap_through_a_wide_facing_cell() {
+ let s = single(0.5);
+ let rows = vec![
+ // Row 0: [inherits single | nil spacer | inherits single].
+ row(vec![
+ cell(1, None),
+ cell(1, Some(cb(None, Some(CellBorderOverride::Suppress)))),
+ cell(1, None),
+ ]),
+ // Row 1: one gridSpan=3 cell inheriting insideH as its top.
+ row(vec![cell(3, None)]),
+ ];
+ let cols = vec![Pt::new(100.0), Pt::new(100.0), Pt::new(100.0)];
+ let m = measure_table_rows(
+ &rows,
+ &cols,
+ Pt::ZERO,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ // Every column resolves to the same line, so the edge is uniform and one
+ // side paints it whole. The nil column is not a hole in it.
+ assert_eq!(
+ m.rows[0].borders[1].bottom.line(),
+ Some(s),
+ "the wide cell below still supplies this column's border"
+ );
+ assert_eq!(m.rows[0].borders[0].bottom.line(), Some(s));
+ assert_eq!(m.rows[0].borders[2].bottom.line(), Some(s));
+ // …and it is drawn exactly once, from the upper row.
+ assert_eq!(m.rows[1].borders[0].top.line(), None);
+ }
+
+ /// [MS-OI29500] §17.4.66 regression: an upper `gridSpan` cell that leaves the last
+ /// column uncovered (its gridAfter gap) must not "own" the edge, or a
+ /// lower cell straddling that boundary would draw its own top over the
+ /// upper bottom → a doubled line. Mirrors the real doc's `gridSpan=9`
+ /// section row above the `Observations` (`gridSpan=2`) header.
+ #[test]
+ fn upper_grid_after_gap_yields_edge_to_lower_row() {
+ let s = single(0.5);
+ let rows = vec![
+ // Row 0: one gridSpan=2 cell over cols 0-1; col 2 is its gridAfter.
+ row(vec![cell(2, None)]),
+ // Row 1: [cell | gridSpan=2 cell straddling covered col 1 + col 2].
+ row(vec![cell(1, None), cell(2, None)]),
+ ];
+ let cols = vec![Pt::new(100.0); 3];
+ let m = measure_table_rows(
+ &rows,
+ &cols,
+ Pt::ZERO,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ // Upper can't cover col 2, so the lower row owns the whole edge:
+ // its bottom is cleared (no doubling), the lower tops carry the line.
+ assert_eq!(
+ m.rows[0].borders[0].bottom.line(),
+ None,
+ "upper bottom cleared so the straddling lower cell isn't doubled"
+ );
+ assert_eq!(m.rows[1].borders[0].top.line(), Some(s));
+ assert_eq!(m.rows[1].borders[1].top.line(), Some(s));
+ }
+
+ /// Aligned grids keep the pre-existing "upper cell owns the shared edge"
+ /// behaviour: the lower cell's top is cleared, the upper bottom carries it.
+ #[test]
+ fn aligned_grid_upper_cell_owns_horizontal_edge() {
+ let s = single(0.5);
+ let rows = vec![
+ row(vec![cell(1, None), cell(1, None)]),
+ row(vec![cell(1, None), cell(1, None)]),
+ ];
+ let cols = vec![Pt::new(100.0), Pt::new(100.0)];
+ let m = measure_table_rows(
+ &rows,
+ &cols,
+ Pt::ZERO,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+ for ci in 0..2 {
+ assert_eq!(m.rows[0].borders[ci].bottom.line(), Some(s));
+ assert_eq!(m.rows[1].borders[ci].top.line(), None);
+ }
+ }
+
+ /// §17.4.44 geometry. The invariant that matters is a *uniform* gap: exactly
+ /// one `cell_spacing` between adjacent cells **and** at both table edges,
+ /// with the table's own width unchanged.
+ ///
+ /// Slots are pre-shrunk by `reserve_cell_spacing` (build side), so this
+ /// feeds slots summing to `width - spacing` and checks the resulting edges.
+ #[test]
+ fn cell_spacing_leaves_a_uniform_gap_and_keeps_the_table_width() {
+ let spacing = Pt::new(10.0);
+ // Table is 100pt wide; slots therefore sum to 90.
+ let slots = vec![Pt::new(45.0), Pt::new(45.0)];
+ let rows = vec![row(vec![cell(1, None), cell(1, None)])];
+ let m = measure_table_rows(
+ &rows,
+ &slots,
+ spacing,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ assert_eq!(
+ m.table_width,
+ Pt::new(100.0),
+ "spacing comes out of the table"
+ );
+
+ let e = &m.rows[0].entries;
+ let left_edge = e[0].cell_x;
+ let gap_between = e[1].cell_x - (e[0].cell_x + e[0].cell_w);
+ let right_edge = m.table_width - (e[1].cell_x + e[1].cell_w);
+ assert_eq!(left_edge, spacing, "gap at the table's left edge");
+ assert_eq!(gap_between, spacing, "gap between adjacent cells");
+ assert_eq!(right_edge, spacing, "gap at the table's right edge");
+ }
+
+ /// A `gridSpan` cell absorbs the interior gaps it covers — it is one cell,
+ /// so the spacing between the columns it spans belongs to it.
+ #[test]
+ fn a_gridspan_cell_absorbs_the_gaps_it_covers() {
+ let spacing = Pt::new(10.0);
+ let slots = vec![Pt::new(30.0); 3]; // 90 + 10 spacing = 100 wide
+ let rows = vec![
+ row(vec![cell(3, None)]),
+ row(vec![cell(1, None), cell(1, None), cell(1, None)]),
+ ];
+ let m = measure_table_rows(
+ &rows,
+ &slots,
+ spacing,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ let wide = &m.rows[0].entries[0];
+ let narrow = &m.rows[1].entries;
+ assert_eq!(wide.cell_x, spacing);
+ assert_eq!(wide.cell_w, Pt::new(80.0), "spans 90 of slot minus one gap");
+ // The wide cell covers both interior gaps plus the two narrow cells
+ // between them, so its right edge matches the last narrow cell's.
+ assert_eq!(
+ wide.cell_x + wide.cell_w,
+ narrow[2].cell_x + narrow[2].cell_w
+ );
+ }
+
+ /// Vertically the rule is the same: one spacing between row boxes, and one
+ /// above the first row. The row's own height carries its leading gap.
+ #[test]
+ fn cell_spacing_separates_rows_vertically() {
+ let spacing = Pt::new(6.0);
+ let slots = vec![Pt::new(94.0)];
+ let rows = vec![row(vec![cell(1, None)]), row(vec![cell(1, None)])];
+ let m = measure_table_rows(
+ &rows,
+ &slots,
+ spacing,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ );
+
+ for r in &m.rows {
+ assert_eq!(r.leading_gap, spacing);
+ assert_eq!(
+ r.border_gap_below,
+ Pt::ZERO,
+ "no shared edge to reserve for once cells are separated"
+ );
+ }
+ // These cells are empty, so the whole of each row's height is the
+ // reserved gap — added exactly once per row, not once per cell.
+ for r in &m.rows {
+ assert_eq!(r.height, spacing);
+ }
+ }
+
+ /// [MS-OI29500] §17.4.66: *"If the cell spacing is nonzero ... then all cell
+ /// borders and outer table borders display."* Separated cells share no edge,
+ /// so conflict resolution is skipped and **both** sides keep their border —
+ /// where collapsing would have kept one and cleared the other.
+ #[test]
+ fn nonzero_cell_spacing_disables_border_collapsing() {
+ let slots = vec![Pt::new(45.0), Pt::new(45.0)];
+ let rows = vec![
+ row(vec![cell(1, None), cell(1, None)]),
+ row(vec![cell(1, None), cell(1, None)]),
+ ];
+ let measure = |spacing: Pt| {
+ measure_table_rows(
+ &rows,
+ &slots,
+ spacing,
+ Pt::new(10.0),
+ Some(&all_single()),
+ None,
+ false,
+ )
+ };
+
+ // Collapsed (no spacing): the right/left pair resolves to one border on
+ // the left cell, and the shared horizontal edge is owned by one row.
+ let collapsed = measure(Pt::ZERO);
+ assert!(collapsed.rows[0].borders[1].left.line().is_none());
+ assert!(collapsed.rows[1].borders[0].top.line().is_none());
+
+ // Spaced: every cell keeps all four of its own borders.
+ let spaced = measure(Pt::new(8.0));
+ for r in &spaced.rows {
+ for b in &r.borders {
+ assert!(b.left.line().is_some(), "left kept");
+ assert!(b.right.line().is_some(), "right kept");
+ assert!(b.top.line().is_some(), "top kept");
+ assert!(b.bottom.line().is_some(), "bottom kept");
+ }
+ }
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/mod.rs b/crates/liteparse-docx/src/render/layout/table/mod.rs
new file mode 100644
index 0000000..2ad53ac
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/mod.rs
@@ -0,0 +1,2246 @@
+//! Table layout — 3-pass column sizing, cell layout, border rendering.
+//!
+//! Pass 1: Compute column widths from grid definitions or equal distribution.
+//! Pass 2: Lay out each cell with tight width constraints, determine row heights.
+//! Pass 3: Position cells and emit border commands.
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::PtSize;
+
+mod borders;
+mod emit;
+mod grid;
+mod measure;
+mod split;
+mod types;
+
+pub use grid::compute_column_widths;
+pub use types::*;
+
+use emit::{TableCommandBuffers, emit_split_row, emit_table_rows};
+use grid::{build_row_groups, row_group_end};
+use measure::measure_table_rows;
+use split::{RowCutInput, find_row_cut, split_row_at};
+
+/// Measure the first atomic paginator row group without emitting table commands.
+///
+/// The following row is included only to resolve the group's shared bottom
+/// border; later rows and groups are neither measured nor paginated.
+pub(crate) fn measure_leading_table_group_height(
+ rows: &[TableRowInput],
+ col_widths: &[Pt],
+ // §17.4.44 `tblCellSpacing`, resolved to points (zero when unset). The grid
+ // slots must already be shrunk by this amount — see
+ // `build/table.rs::reserve_cell_spacing`.
+ cell_spacing: Pt,
+ default_line_height: Pt,
+ borders: Option<&TableBorderConfig>,
+ measure_text: super::paragraph::MeasureTextFn<'_>,
+ suppress_first_row_top: bool,
+) -> Option<Pt> {
+ if rows.is_empty() || col_widths.is_empty() {
+ return None;
+ }
+
+ let group_end = row_group_end(rows, 0);
+ let measured_end = (group_end + 1).min(rows.len());
+ let measured = measure_table_rows(
+ &rows[..measured_end],
+ col_widths,
+ cell_spacing,
+ default_line_height,
+ borders,
+ measure_text,
+ suppress_first_row_top,
+ );
+
+ Some(
+ measured.rows[..group_end]
+ .iter()
+ .map(|row| row.height + row.border_gap_below)
+ .sum(),
+ )
+}
+
+/// Lay out a table: compute column widths, lay out cells, emit borders.
+///
+/// §17.4.38: `suppress_first_row_top` suppresses the top border of the first row
+/// for adjacent table border collapse.
+pub fn layout_table(
+ rows: &[TableRowInput],
+ col_widths: &[Pt],
+ // §17.4.44 `tblCellSpacing`, resolved to points (zero when unset). The grid
+ // slots must already be shrunk by this amount — see
+ // `build/table.rs::reserve_cell_spacing`.
+ cell_spacing: Pt,
+ default_line_height: Pt,
+ borders: Option<&TableBorderConfig>,
+ measure_text: super::paragraph::MeasureTextFn<'_>,
+ suppress_first_row_top: bool,
+) -> TableLayout {
+ if rows.is_empty() || col_widths.is_empty() {
+ return TableLayout {
+ commands: Vec::new(),
+ size: PtSize::ZERO,
+ };
+ }
+
+ let measured = measure_table_rows(
+ rows,
+ col_widths,
+ cell_spacing,
+ default_line_height,
+ borders,
+ measure_text,
+ suppress_first_row_top,
+ );
+
+ let mut commands = Vec::new();
+ let mut content_commands = Vec::new();
+ let mut border_commands = Vec::new();
+ let mut cursor_y = Pt::ZERO;
+
+ // Monolithic table: no top border override needed — borders are resolved correctly.
+ emit_table_rows(
+ &measured,
+ rows,
+ 0..measured.rows.len(),
+ &mut cursor_y,
+ &mut TableCommandBuffers {
+ commands: &mut commands,
+ content_commands: &mut content_commands,
+ border_commands: &mut border_commands,
+ },
+ None,
+ );
+
+ commands.append(&mut content_commands);
+ commands.append(&mut border_commands);
+
+ TableLayout {
+ commands,
+ // §17.4.44: each row reserves its own leading gap, so the only one left
+ // to add is the trailing gap at the table's bottom edge.
+ size: PtSize::new(measured.table_width, cursor_y + cell_spacing),
+ }
+}
+
+/// One page-slice of a table, produced by `layout_table_paginated`.
+#[derive(Debug)]
+pub struct TableSlice {
+ /// Draw commands positioned relative to this slice's top-left origin (0,0).
+ pub commands: Vec<super::draw_command::DrawCommand>,
+ /// Size of this slice.
+ pub size: PtSize,
+}
+
+/// Pagination parameters for `layout_table_paginated`.
+pub struct TablePaginationConfig {
+ /// Available height on the first page.
+ pub available_height: Pt,
+ /// Full page height for continuation pages.
+ pub page_height: Pt,
+ /// Whether to suppress the first row's top border (adjacent table collapse).
+ pub suppress_first_row_top: bool,
+}
+
+pub(crate) struct TablePaginationHeights<F> {
+ pub(crate) available_height: Pt,
+ pub(crate) suppress_first_row_top: bool,
+ pub(crate) page_height_for_slice: F,
+}
+
+/// Lay out a table with page splitting at row boundaries.
+///
+/// §17.4.49: header rows repeat on each continuation page.
+/// §17.4.1: `cantSplit` rows are kept together (moved to next page if needed).
+///
+/// Returns one `TableSlice` per page.
+pub fn layout_table_paginated(
+ rows: &[TableRowInput],
+ col_widths: &[Pt],
+ // §17.4.44 `tblCellSpacing`, resolved to points (zero when unset). The grid
+ // slots must already be shrunk by this amount — see
+ // `build/table.rs::reserve_cell_spacing`.
+ cell_spacing: Pt,
+ default_line_height: Pt,
+ borders: Option<&TableBorderConfig>,
+ measure_text: super::paragraph::MeasureTextFn<'_>,
+ pagination: &TablePaginationConfig,
+) -> Vec<TableSlice> {
+ let page_height = pagination.page_height;
+ layout_table_paginated_with_page_heights(
+ rows,
+ col_widths,
+ cell_spacing,
+ default_line_height,
+ borders,
+ measure_text,
+ TablePaginationHeights {
+ available_height: pagination.available_height,
+ suppress_first_row_top: pagination.suppress_first_row_top,
+ page_height_for_slice: |_| page_height,
+ },
+ )
+}
+
+pub(crate) fn layout_table_paginated_with_page_heights(
+ rows: &[TableRowInput],
+ col_widths: &[Pt],
+ // §17.4.44 `tblCellSpacing`, resolved to points (zero when unset). The grid
+ // slots must already be shrunk by this amount — see
+ // `build/table.rs::reserve_cell_spacing`.
+ cell_spacing: Pt,
+ default_line_height: Pt,
+ borders: Option<&TableBorderConfig>,
+ measure_text: super::paragraph::MeasureTextFn<'_>,
+ pagination: TablePaginationHeights<impl FnMut(usize) -> Pt>,
+) -> Vec<TableSlice> {
+ let TablePaginationHeights {
+ available_height,
+ suppress_first_row_top,
+ mut page_height_for_slice,
+ } = pagination;
+ if rows.is_empty() || col_widths.is_empty() {
+ return vec![TableSlice {
+ commands: Vec::new(),
+ size: PtSize::ZERO,
+ }];
+ }
+
+ let measured = measure_table_rows(
+ rows,
+ col_widths,
+ cell_spacing,
+ default_line_height,
+ borders,
+ measure_text,
+ suppress_first_row_top,
+ );
+
+ // §17.4.49: contiguous header rows from index 0.
+ let header_count = rows
+ .iter()
+ .take_while(|r| r.is_header == Some(true))
+ .count();
+ let header_height: Pt = measured.rows[..header_count]
+ .iter()
+ .map(|mr| mr.height + mr.border_gap_below)
+ .sum();
+
+ let groups = build_row_groups(rows, &measured);
+
+ // Each slice is a list of items to emit in order: either a range of
+ // measured rows (the common case) or a custom (split) row with its own
+ // MeasuredRow data.
+ let mut slices: Vec<Vec<SliceItem>> = Vec::new();
+ let mut current_slice: Vec<SliceItem> = Vec::new();
+ let mut remaining = available_height;
+
+ for group in &groups {
+ if group.height <= remaining {
+ current_slice.push(SliceItem::Range(group.start..group.end));
+ remaining -= group.height;
+ continue;
+ }
+
+ // §17.4.49: header rows are atomic with respect to splitting — they
+ // must remain intact so the same row content can repeat verbatim on
+ // continuation slices. Non-header rows fall through to the normal
+ // §17.4.1 split path.
+ let is_header = group.start < header_count;
+
+ // Doesn't fit. Try to split (§17.4.1) before spilling the whole
+ // group to the next page. Only non-header single-row groups are
+ // splittable — vMerge spans and cantSplit rows set `splittable=false`.
+ if !is_header && group.splittable && group.end - group.start == 1 {
+ let row_idx = group.start;
+ let cut_input = RowCutInput {
+ mr: &measured.rows[row_idx],
+ row: &rows[row_idx],
+ available: remaining,
+ };
+ if let Some(cut) = find_row_cut(&cut_input) {
+ let parts = split_row_at(&measured.rows[row_idx], &cut);
+ current_slice.push(SliceItem::Split {
+ row_idx,
+ mr: parts.first,
+ });
+ slices.push(std::mem::take(&mut current_slice));
+ // New page: start with header rows (if any).
+ remaining = page_height_for_slice(slices.len());
+ if header_count > 0 {
+ current_slice.push(SliceItem::Range(0..header_count));
+ remaining -= header_height;
+ }
+
+ // Iteratively place the continuation, splitting again each
+ // time it exceeds the new page's remaining space.
+ let mut pending = parts.second;
+ loop {
+ if pending.height <= remaining {
+ remaining -= pending.height;
+ current_slice.push(SliceItem::Continuation {
+ row_idx,
+ mr: pending,
+ });
+ break;
+ }
+ let sub_cut_input = RowCutInput {
+ mr: &pending,
+ row: &rows[row_idx],
+ available: remaining,
+ };
+ match find_row_cut(&sub_cut_input) {
+ Some(sub_cut) => {
+ let sub = split_row_at(&pending, &sub_cut);
+ current_slice.push(SliceItem::Continuation {
+ row_idx,
+ mr: sub.first,
+ });
+ slices.push(std::mem::take(&mut current_slice));
+ remaining = page_height_for_slice(slices.len());
+ if header_count > 0 {
+ current_slice.push(SliceItem::Range(0..header_count));
+ remaining -= header_height;
+ }
+ pending = sub.second;
+ }
+ None => {
+ // Not even one line of the continuation fits.
+ // This should be rare — a row taller than a
+ // full page of content. Emit it anyway and log.
+ log::warn!(
+ "[table] row {} continuation ({:.1}pt) exceeds \
+ page content height ({:.1}pt available)",
+ row_idx,
+ pending.height.raw(),
+ remaining.raw(),
+ );
+ current_slice.push(SliceItem::Continuation {
+ row_idx,
+ mr: pending,
+ });
+ break;
+ }
+ }
+ }
+ continue;
+ }
+ }
+
+ // No split possible — move the whole group to the next page, but only
+ // if the next page is actually roomier than what is left here.
+ //
+ // A group taller than a whole page never fits anywhere. Advancing
+ // unconditionally then abandons `current_slice` while it is still
+ // empty — the caller turns that empty leading slice into a page push,
+ // so a table starting at the top of a page emitted a **blank page**
+ // and the group overflowed the next one just the same (the warning
+ // below fired either way). Same shape as the E4c floating-table
+ // spillover: acting on a condition the action cannot change.
+ //
+ // Comparing against the *post-header* room is what makes this exact —
+ // repeating headers can leave a fresh page with less usable space than
+ // the current one, and in that case staying put overflows by less.
+ // `slices.len() + 1` because this decision happens *before* the push
+ // that would append the current slice — the index being queried is the
+ // page the group would move onto, not the one it is leaving.
+ let next_page_height = page_height_for_slice(slices.len() + 1);
+ let next_remaining = if !is_header && header_count > 0 {
+ next_page_height - header_height
+ } else {
+ next_page_height
+ };
+ if next_remaining > remaining {
+ slices.push(std::mem::take(&mut current_slice));
+ remaining = next_page_height;
+ // §17.4.49: prepend the repeating header rows only when this group
+ // sits past the headers. When advancing because a header row itself
+ // doesn't fit, the row is part of the table's first appearance —
+ // emitting `Range(0..header_count)` here would duplicate it.
+ if !is_header && header_count > 0 {
+ current_slice.push(SliceItem::Range(0..header_count));
+ remaining -= header_height;
+ }
+ }
+ if group.height > remaining {
+ log::warn!(
+ "[table] row group {}-{} ({:.1}pt) exceeds page height ({:.1}pt available)",
+ group.start,
+ group.end,
+ group.height.raw(),
+ remaining.raw(),
+ );
+ }
+ current_slice.push(SliceItem::Range(group.start..group.end));
+ remaining -= group.height;
+ }
+ slices.push(current_slice);
+
+ // §17.4.38: the table's outer top border, used to restore the top edge
+ // on continuation page slices where border conflict resolution or adjacent
+ // table collapse removed it.
+ let outer_top_border = borders.and_then(|b| b.top);
+
+ // Emit draw commands for each slice.
+ let last_slice_idx = slices.len().saturating_sub(1);
+ slices
+ .iter()
+ .enumerate()
+ .map(|(slice_idx, items)| {
+ let mut commands = Vec::new();
+ let mut content_commands = Vec::new();
+ let mut border_commands = Vec::new();
+ let mut cursor_y = Pt::ZERO;
+ for (item_idx, item) in items.iter().enumerate() {
+ // First item on each continuation slice (slice_idx > 0) needs
+ // its top border restored if it was resolved away. The first
+ // slice does NOT get an override — `suppress_first_row_top`
+ // semantics are preserved there.
+ let top_override = if slice_idx > 0 && item_idx == 0 {
+ outer_top_border
+ } else {
+ None
+ };
+ match item {
+ SliceItem::Range(range) => {
+ emit_table_rows(
+ &measured,
+ rows,
+ range.clone(),
+ &mut cursor_y,
+ &mut TableCommandBuffers {
+ commands: &mut commands,
+ content_commands: &mut content_commands,
+ border_commands: &mut border_commands,
+ },
+ top_override,
+ );
+ }
+ SliceItem::Split { row_idx, mr } | SliceItem::Continuation { row_idx, mr } => {
+ // A split half's bottom border sits in a reserved gap
+ // only when something follows it on *this* slice. The
+ // last item on a page ends at a cut or page edge, where
+ // `split_row_at` reserved no gap, so the border is
+ // inset into the row instead.
+ let has_reserved_bottom_gap = item_idx + 1 < items.len();
+ emit_split_row(
+ mr,
+ &rows[*row_idx],
+ &mut cursor_y,
+ &mut TableCommandBuffers {
+ commands: &mut commands,
+ content_commands: &mut content_commands,
+ border_commands: &mut border_commands,
+ },
+ top_override,
+ has_reserved_bottom_gap,
+ );
+ }
+ }
+ }
+ commands.append(&mut content_commands);
+ commands.append(&mut border_commands);
+ // §17.4.44: the trailing gap belongs to the table's bottom *edge*,
+ // so only the final slice gets it — an intermediate slice ends at a
+ // page cut, not at the table's edge. Without this a table that
+ // happens to paginate loses the bottom gap that the same table
+ // keeps when it fits on one page (see the monolithic path above).
+ let trailing_gap = if slice_idx == last_slice_idx {
+ cell_spacing
+ } else {
+ Pt::ZERO
+ };
+ TableSlice {
+ commands,
+ size: PtSize::new(measured.table_width, cursor_y + trailing_gap),
+ }
+ })
+ .collect()
+}
+
+/// One item inside a page slice's emit list.
+enum SliceItem {
+ /// Emit the contiguous range of measured rows (normal case).
+ Range(std::ops::Range<usize>),
+ /// Emit a partial row (first half) at the bottom of a page. Shares the
+ /// row's `TableRowInput` with `row_idx` but carries partitioned
+ /// commands and modified borders.
+ Split {
+ row_idx: usize,
+ mr: types::MeasuredRow,
+ },
+ /// Emit the continuation (second half) of a split row at the top of a
+ /// continuation page.
+ Continuation {
+ row_idx: usize,
+ mr: types::MeasuredRow,
+ },
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::draw_command::DrawCommand;
+ use super::*;
+ use crate::render::geometry::PtEdgeInsets;
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::section::LayoutBlock;
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str, width: f32) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(width),
+ trimmed_width: Pt::new(width),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ fn simple_cell(text: &str) -> TableCellInput {
+ TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag(text, 30.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }
+ }
+
+ // ── layout_table ─────────────────────────────────────────────────────
+
+ #[test]
+ fn empty_table() {
+ let result = layout_table(&[], &[], Pt::ZERO, Pt::new(14.0), None, None, false);
+ assert!(result.commands.is_empty());
+ assert_eq!(result.size, PtSize::ZERO);
+ }
+
+ #[test]
+ fn single_cell_table() {
+ let rows = vec![TableRowInput {
+ cells: vec![simple_cell("hello")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(200.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ assert_eq!(result.size.width.raw(), 200.0);
+ assert_eq!(result.size.height.raw(), 14.0);
+
+ let text_count = result
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(text_count, 1);
+ }
+
+ #[test]
+ fn two_by_two_table() {
+ let rows = vec![
+ TableRowInput {
+ cells: vec![simple_cell("a"), simple_cell("b")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ TableRowInput {
+ cells: vec![simple_cell("c"), simple_cell("d")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ ];
+ let col_widths = vec![Pt::new(100.0), Pt::new(100.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ assert_eq!(result.size.width.raw(), 200.0);
+ assert_eq!(result.size.height.raw(), 28.0); // 2 rows * 14pt
+
+ let text_count = result
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(text_count, 4);
+ }
+
+ #[test]
+ fn row_height_is_max_of_cells() {
+ // Cell A has 1 line (14pt), Cell B has 2 lines (28pt) because text wraps
+ let rows = vec![TableRowInput {
+ cells: vec![
+ simple_cell("short"),
+ TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("long ", 60.0), text_frag("text", 60.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ },
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ // Column B is only 80 wide, so "long " + "text" (120) wraps
+ let col_widths = vec![Pt::new(200.0), Pt::new(80.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ assert_eq!(result.size.height.raw(), 28.0, "row height = tallest cell");
+ }
+
+ #[test]
+ fn min_row_height_respected() {
+ let rows = vec![TableRowInput {
+ cells: vec![simple_cell("x")],
+ height_rule: Some(RowHeightRule::AtLeast(Pt::new(40.0))),
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(200.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ assert_eq!(
+ result.size.height.raw(),
+ 40.0,
+ "min height > content height"
+ );
+ }
+
+ #[test]
+ fn cell_shading_emits_rect() {
+ let rows = vec![TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("x", 10.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: Some(RgbColor {
+ r: 200,
+ g: 200,
+ b: 200,
+ }),
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(100.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ let rect_count = result
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Rect { .. }))
+ .count();
+ assert_eq!(rect_count, 1, "shading produces a Rect command");
+ }
+
+ #[test]
+ fn grid_span_widens_cell() {
+ let rows = vec![TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("spanning", 30.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 2, // spans both columns
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(100.0), Pt::new(100.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ // Cell gets full 200pt width, text should still render
+ assert_eq!(result.size.width.raw(), 200.0);
+ let text_count = result
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(text_count, 1);
+ }
+
+ /// Helper: collect all Text command x-positions in command order.
+ fn text_x_positions(commands: &[DrawCommand]) -> Vec<f32> {
+ commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.x.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn grid_before_offsets_first_cell_x() {
+ // §17.4.17: gridBefore=1 + wBefore skips the first grid column. With
+ // a 4-column grid [10, 100, 200, 10] and a row with gridBefore=1 and
+ // gridAfter=1, the two cells must occupy columns 1 and 2 — not 0 and 1.
+ let rows = vec![TableRowInput {
+ cells: vec![simple_cell("A"), simple_cell("B")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 1,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(10.0), Pt::new(100.0), Pt::new(200.0), Pt::new(10.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ let xs = text_x_positions(&result.commands);
+ assert_eq!(xs.len(), 2, "two text fragments expected");
+ assert_eq!(xs[0], 10.0, "first cell starts at col 1's left edge (10pt)");
+ assert_eq!(
+ xs[1], 110.0,
+ "second cell starts after col 1 (10 + 100 = 110pt)"
+ );
+
+ // The table's overall width is unchanged by gridBefore/gridAfter —
+ // they only leave whitespace within rows.
+ assert_eq!(result.size.width.raw(), 320.0);
+ }
+
+ /// §17.4.16: a row whose cells don't reach the last grid column leaves the
+ /// remainder empty — the `gridAfter` region — without stretching into it.
+ ///
+ /// The row declares no `gridAfter`: layout derives the right edge from
+ /// `grid_before` plus the cells' spans, so the trailing gap is a
+ /// *consequence* of the cells, not a separate input. (This test previously
+ /// set a `grid_after` field that no layout code read, so it asserted the
+ /// same positions whether the field was right, wrong, or absent.)
+ #[test]
+ fn row_shorter_than_the_grid_leaves_the_trailing_columns_empty() {
+ // Shaded cells so the emitted rects expose each cell's *width* — text
+ // x-positions alone cannot see a cell stretching rightward, since the
+ // second cell's x is fixed by the first cell's grid column either way.
+ let shaded = |text: &str| TableCellInput {
+ shading: Some(RgbColor {
+ r: 200,
+ g: 200,
+ b: 200,
+ }),
+ ..simple_cell(text)
+ };
+ let rows = vec![TableRowInput {
+ cells: vec![shaded("X"), shaded("Y")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(10.0), Pt::new(100.0), Pt::new(200.0), Pt::new(10.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ let xs = text_x_positions(&result.commands);
+ assert_eq!(xs, vec![0.0, 10.0], "cells sit at grid columns 0 and 1");
+
+ // Each cell occupies exactly its own column — not the 210pt of unused
+ // grid to the right.
+ let rects: Vec<(f32, f32)> = result
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Rect { rect, .. } => {
+ Some((rect.origin.x.raw(), rect.size.width.raw()))
+ }
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ rects,
+ vec![(0.0, 10.0), (10.0, 100.0)],
+ "cells must not stretch into the trailing grid columns"
+ );
+
+ // The table still spans the whole declared grid; the gap is empty, not
+ // removed.
+ assert_eq!(result.size.width.raw(), 320.0);
+ }
+
+ /// §17.4.17 + §17.4.38: a row inset from **both** table edges takes
+ /// `inside_v` on both sides, never the outer `left`/`right`.
+ ///
+ /// `grid_before = 1` moves the first cell off the left edge; the two cells
+ /// then span only grid columns 1–2 of 4, so the last one stops short of the
+ /// right edge as well. Distinct widths identify which border was applied —
+ /// `left`/`right` are 4pt, `inside_v` is 1pt — so a single 4pt rect
+ /// anywhere in the output means an outer border leaked onto an interior
+ /// edge.
+ ///
+ /// The right-edge half of this used to be spelled `grid_after: 1` on a
+ /// field no layout code read; it is the cells' spans that place that edge.
+ #[test]
+ fn row_inset_from_both_edges_uses_inside_v_on_both_sides() {
+ let rows = vec![TableRowInput {
+ cells: vec![simple_cell("A"), simple_cell("B")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 1,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(10.0), Pt::new(50.0), Pt::new(50.0), Pt::new(10.0)];
+ let borders = TableBorderConfig {
+ top: None,
+ bottom: None,
+ left: Some(TableBorderLine {
+ width: Pt::new(4.0),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ right: Some(TableBorderLine {
+ width: Pt::new(4.0),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ inside_h: None,
+ inside_v: Some(TableBorderLine {
+ width: Pt::new(1.0),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ }),
+ };
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&borders),
+ None,
+ false,
+ );
+
+ // Vertical border rects have width equal to the border thickness
+ // (depth) and height >= 1. Find any 4pt-thick border rect.
+ let has_thick_vertical = result.commands.iter().any(|c| match c {
+ DrawCommand::Rect { rect, color } if *color == RgbColor::BLACK => {
+ rect.size.width.raw() == 4.0 && rect.size.height.raw() > 1.0
+ }
+ _ => false,
+ });
+ assert!(
+ !has_thick_vertical,
+ "no 4pt-thick vertical border should appear: gridBefore/gridAfter \
+ mean cells aren't at the table's left/right edges, so left/right \
+ borders are not applied"
+ );
+
+ // Inside_v (1pt) should appear at the boundary between cell A and cell B.
+ let has_inside_v = result.commands.iter().any(|c| match c {
+ DrawCommand::Rect { rect, color } if *color == RgbColor::BLACK => {
+ rect.size.width.raw() == 1.0
+ }
+ _ => false,
+ });
+ assert!(
+ has_inside_v,
+ "1pt inside_v border between cells must appear"
+ );
+ }
+
+ #[test]
+ fn vmerge_across_rows_with_different_grid_before() {
+ // §17.4.85 + §17.4.17: a cell at grid_col 1 in row A (gridBefore=1)
+ // can merge vertically with a Continue cell at grid_col 1 in row B
+ // (gridBefore=0) — the merge is per absolute grid column. Row B's
+ // cell at grid_col 0 has no above-cell (it's in row A's gridBefore
+ // region) and must layout independently.
+ let row_a = TableRowInput {
+ cells: vec![
+ TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("Restart", 30.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(VerticalMergeState::Restart),
+ vertical_align: CellVAlign::Top,
+ },
+ simple_cell("header"),
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 1,
+ border_overrides: None,
+ };
+ let row_b = TableRowInput {
+ cells: vec![
+ simple_cell("row1col0"),
+ TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(VerticalMergeState::Continue),
+ vertical_align: CellVAlign::Top,
+ },
+ simple_cell("row1col2"),
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ };
+ let col_widths = vec![Pt::new(50.0), Pt::new(100.0), Pt::new(150.0)];
+ let result = layout_table(
+ &[row_a, row_b],
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ let position_of = |needle: &str| -> Option<(f32, f32)> {
+ result.commands.iter().find_map(|c| match c {
+ DrawCommand::Text { position, text, .. } if text.as_ref() == needle => {
+ Some((position.x.raw(), position.y.raw()))
+ }
+ _ => None,
+ })
+ };
+
+ let (restart_x, _) = position_of("Restart").expect("Restart text present");
+ let (header_x, header_y) = position_of("header").expect("header text present");
+ let (col0_x, col0_y) = position_of("row1col0").expect("row1col0 text present");
+ let (col2_x, _) = position_of("row1col2").expect("row1col2 text present");
+
+ // Row A respects gridBefore=1: first cell at col 1's left edge (50pt).
+ assert_eq!(restart_x, 50.0, "Restart cell starts at grid col 1");
+ assert_eq!(header_x, 150.0, "header cell starts at grid col 2 (50+100)");
+
+ // Row B has its own grid_before=0 — the col-0 cell exists and lays
+ // out independently. The col-1 cell is a Continue (no content).
+ // Row B's col-2 cell is unaffected by the merge.
+ assert_eq!(col0_x, 0.0, "row1col0 starts at grid col 0");
+ assert_eq!(col2_x, 150.0, "row1col2 starts at grid col 2 (50+100)");
+
+ // Row B's col-0 cell sits in row 2 (y > 0); it's not stretched by
+ // the vMerge happening at col 1.
+ assert!(col0_y > 0.0, "row1col0 is on the second row");
+ assert_eq!(
+ col0_y,
+ header_y + 14.0,
+ "row1col0 sits exactly one row-height below the row 0 header"
+ );
+ }
+
+ #[test]
+ fn cell_margins_affect_layout() {
+ let rows = vec![TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("text", 30.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::new(
+ Pt::new(5.0),
+ Pt::new(10.0),
+ Pt::new(5.0),
+ Pt::new(10.0),
+ ),
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(200.0)];
+ let result = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ // Row height = content(14) + top(5) + bottom(5) = 24
+ assert_eq!(result.size.height.raw(), 24.0);
+
+ // Text should be offset by left margin
+ if let Some(DrawCommand::Text { position, .. }) = result.commands.first() {
+ assert_eq!(position.x.raw(), 10.0, "left margin");
+ }
+ }
+
+ #[test]
+ fn suppress_first_row_top_removes_top_borders() {
+ let border_line = TableBorderLine {
+ width: Pt::new(0.5),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ };
+ let borders = TableBorderConfig {
+ top: Some(border_line),
+ bottom: Some(border_line),
+ left: Some(border_line),
+ right: Some(border_line),
+ inside_h: None,
+ inside_v: None,
+ };
+ let rows = vec![TableRowInput {
+ cells: vec![simple_cell("a")],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }];
+ let col_widths = vec![Pt::new(100.0)];
+
+ // Without suppression: top border present.
+ let normal = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&borders),
+ None,
+ false,
+ );
+ let normal_borders: Vec<_> = normal
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Rect { color, .. } if *color == RgbColor::BLACK))
+ .collect();
+
+ // With suppression: top border removed.
+ let suppressed = layout_table(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&borders),
+ None,
+ true,
+ );
+ let suppressed_borders: Vec<_> = suppressed
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Rect { color, .. } if *color == RgbColor::BLACK))
+ .collect();
+
+ // Normal has 4 borders (top, bottom, left, right).
+ assert_eq!(normal_borders.len(), 4, "all 4 borders present");
+ // Suppressed has 3 borders (bottom, left, right — no top).
+ assert_eq!(suppressed_borders.len(), 3, "top border suppressed");
+ }
+
+ #[test]
+ fn vmerge_outer_border_crosses_sibling_horizontal_border_gap() {
+ let border = TableBorderLine {
+ width: Pt::new(1.0),
+ color: RgbColor::BLACK,
+ style: TableBorderStyle::Single,
+ };
+ let borders = TableBorderConfig {
+ top: Some(border),
+ bottom: Some(border),
+ left: Some(border),
+ right: Some(border),
+ inside_h: Some(border),
+ inside_v: Some(border),
+ };
+ let merged_cell = |state| TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(state),
+ vertical_align: CellVAlign::Top,
+ };
+ let rows = vec![
+ TableRowInput {
+ cells: vec![
+ simple_cell("recipient"),
+ merged_cell(VerticalMergeState::Restart),
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ TableRowInput {
+ cells: vec![
+ simple_cell("recipient bank"),
+ merged_cell(VerticalMergeState::Continue),
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 2,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ },
+ ];
+
+ let result = layout_table(
+ &rows,
+ &[Pt::new(100.0), Pt::new(100.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ Some(&borders),
+ None,
+ false,
+ );
+ let mut right_edge_segments: Vec<_> = result
+ .commands
+ .iter()
+ .filter_map(|command| match command {
+ DrawCommand::Rect { rect, color }
+ if *color == RgbColor::BLACK
+ && rect.origin.x.raw() == 199.0
+ && rect.size.width.raw() == 1.0 =>
+ {
+ Some(*rect)
+ }
+ _ => None,
+ })
+ .collect();
+ right_edge_segments.sort_by(|a, b| a.origin.y.raw().total_cmp(&b.origin.y.raw()));
+
+ let first_end = right_edge_segments[0].origin.y + right_edge_segments[0].size.height;
+ let continuation_start = right_edge_segments[1].origin.y;
+ assert_eq!(
+ first_end, continuation_start,
+ "a vertically merged outer border must cross the inter-row border band"
+ );
+ }
+
+ #[test]
+ fn valign_bottom_on_vmerge_restart_uses_span_height() {
+ // §17.4.85 + §17.4.84: vAlign on a vMerge=Restart cell should
+ // apply across the whole merged span, not just the first row.
+ //
+ // Table: 2 rows × 2 cols.
+ // Row 0: [restart "Total", top-align "header"]
+ // Row 1: [continue, top-align "value"]
+ // Default single-line height is 14pt per row → span = 28pt.
+ // Restart cell has bottom alignment, content height 14pt → text
+ // should sit 14pt below the cell's top, i.e. inside row 1.
+ let row0 = TableRowInput {
+ cells: vec![
+ TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: vec![text_frag("Total", 20.0)],
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(VerticalMergeState::Restart),
+ vertical_align: CellVAlign::Bottom,
+ },
+ simple_cell("header"),
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ };
+ let row1 = TableRowInput {
+ cells: vec![
+ TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(VerticalMergeState::Continue),
+ vertical_align: CellVAlign::Top,
+ },
+ simple_cell("value"),
+ ],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ };
+ let col_widths = vec![Pt::new(100.0), Pt::new(100.0)];
+ let result = layout_table(
+ &[row0, row1],
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ // Text position for "Total" comes first (row 0, cell 0).
+ let total_y = result
+ .commands
+ .iter()
+ .find_map(|c| match c {
+ DrawCommand::Text { position, text, .. } if text.as_ref() == "Total" => {
+ Some(position.y.raw())
+ }
+ _ => None,
+ })
+ .expect("Total text present");
+ let header_y = result
+ .commands
+ .iter()
+ .find_map(|c| match c {
+ DrawCommand::Text { position, text, .. } if text.as_ref() == "header" => {
+ Some(position.y.raw())
+ }
+ _ => None,
+ })
+ .expect("header text present");
+
+ // "header" is top-aligned in row 0; "Total" should be bottom-
+ // aligned across the 2-row span, so roughly one row-height below.
+ assert!(
+ total_y > header_y + 10.0,
+ "Total (bottom-valigned merged) should sit well below header (top-valigned row 0): \
+ total_y={total_y}, header_y={header_y}"
+ );
+ }
+
+ // ── Row splitting (§17.4.1) ──────────────────────────────────────────
+
+ /// Build a single-row table with one cell whose paragraph contains
+ /// `n_lines` narrow text fragments that wrap to separate lines.
+ fn tall_row(n_lines: usize) -> TableRowInput {
+ // Width=30 for each fragment; cell content width ≈ 40 ⇒ each
+ // fragment wraps to its own line (default line height 14pt).
+ let fragments: Vec<Fragment> = (0..n_lines)
+ .map(|i| text_frag(&format!("L{i} "), 30.0))
+ .collect();
+ TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments,
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }
+ }
+
+ /// A paragraph of `n_lines` narrow fragments (each wraps to its own 14pt
+ /// line) carrying `style`, for in-cell split tests.
+ fn styled_para(n_lines: usize, style: ParagraphStyle) -> LayoutBlock {
+ LayoutBlock::Paragraph {
+ fragments: (0..n_lines)
+ .map(|i| text_frag(&format!("L{i} "), 30.0))
+ .collect(),
+ style,
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }
+ }
+
+ /// A single-cell, single-column row whose cell holds `blocks`.
+ fn one_cell_row(blocks: Vec<LayoutBlock>) -> TableRowInput {
+ TableRowInput {
+ cells: vec![TableCellInput {
+ blocks,
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }
+ }
+
+ /// Number of `Text` draw commands in a slice (one per fitted line here).
+ fn slice_line_count(slice: &TableSlice) -> usize {
+ slice
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count()
+ }
+
+ #[test]
+ fn splittable_row_breaks_across_pages() {
+ // Row with 6 lines (84pt). Available = 50pt on page 1 ⇒ only ~3
+ // lines fit. The row should split: first slice has ~3 lines,
+ // second slice has the rest.
+ let rows = vec![tall_row(6)];
+ let col_widths = vec![Pt::new(40.0)];
+ let slices = layout_table_paginated(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(50.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert!(
+ slices.len() >= 2,
+ "expected at least 2 slices, got {}",
+ slices.len()
+ );
+
+ let text_y = |slice: &TableSlice| -> Vec<f32> {
+ slice
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.y.raw()),
+ _ => None,
+ })
+ .collect()
+ };
+
+ let s0 = text_y(&slices[0]);
+ let s1 = text_y(&slices[1]);
+ assert!(!s0.is_empty(), "slice 0 should contain some lines");
+ assert!(!s1.is_empty(), "slice 1 should contain continuation lines");
+ assert_eq!(
+ s0.len() + s1.len(),
+ 6,
+ "every line should be emitted exactly once across slices"
+ );
+ // Slice 1's lines should sit near the top (near y=0) since we
+ // rebased them.
+ let min_s1_y = s1.iter().copied().fold(f32::INFINITY, f32::min);
+ assert!(
+ min_s1_y < 20.0,
+ "slice 1 top text should be near y=0, was {min_s1_y}"
+ );
+ }
+
+ #[test]
+ fn cant_split_row_moves_whole_to_next_page() {
+ // cantSplit=true ⇒ entire row moves when it doesn't fit.
+ let mut row = tall_row(6);
+ row.cant_split = Some(true);
+ let rows = vec![row];
+ let col_widths = vec![Pt::new(40.0)];
+ let slices = layout_table_paginated(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(50.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert_eq!(slices.len(), 2, "should still produce 2 slices");
+ // Slice 0 is empty (or at most has no text); all 6 lines land on slice 1.
+ let count0 = slices[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ let count1 = slices[1]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(count0, 0, "first slice has no text with cantSplit");
+ assert_eq!(count1, 6, "all 6 lines on second slice");
+ }
+
+ #[test]
+ fn splittable_row_spans_three_or_more_pages() {
+ // Row with 15 lines (≈210pt at 14pt line height).
+ // Page 1 has 50pt → ~3 lines fit.
+ // Page 2 and on have ~70pt → ~5 lines fit each.
+ // Expected: 3+ slices, every line emitted exactly once.
+ let rows = vec![tall_row(15)];
+ let col_widths = vec![Pt::new(40.0)];
+ let slices = layout_table_paginated(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(50.0),
+ page_height: Pt::new(70.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert!(
+ slices.len() >= 3,
+ "expected ≥3 slices for a 15-line row split across pages, got {}",
+ slices.len()
+ );
+
+ // Every original line should appear exactly once across all slices.
+ let total_lines: usize = slices
+ .iter()
+ .map(|s| {
+ s.commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count()
+ })
+ .sum();
+ assert_eq!(
+ total_lines, 15,
+ "all 15 lines should be emitted across the slices exactly once"
+ );
+ }
+
+ #[test]
+ fn vmerge_span_is_not_split_mid_cell() {
+ // A vMerge span must stay atomic even when its content would split.
+ let row0 = TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: (0..4).map(|i| text_frag(&format!("L{i} "), 30.0)).collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(VerticalMergeState::Restart),
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ };
+ let row1 = TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![],
+ margins: PtEdgeInsets::ZERO,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: Some(VerticalMergeState::Continue),
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ };
+ let col_widths = vec![Pt::new(40.0)];
+ let slices = layout_table_paginated(
+ &[row0, row1],
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(30.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ // Should still page: the merge group doesn't fit on page 1, so it
+ // moves intact to page 2 — never split mid-cell.
+ let count0 = slices[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(count0, 0, "vMerge span must not split across pages");
+ }
+
+ /// Regression: a table whose every row has `tblHeader=1` (a Word template
+ /// pattern, e.g. the trailing "Anhang" tables in the Volvo Annahme-Protokoll)
+ /// must still respect `available_height`. The previous implementation
+ /// unconditionally added every header row to the first slice, overflowing
+ /// the page when the table arrived near the bottom of a stacked page.
+ #[test]
+ fn all_header_rows_paginate_when_exceeding_available() {
+ let mut r0 = tall_row(2);
+ r0.is_header = Some(true);
+ r0.cant_split = Some(true);
+ let mut r1 = tall_row(2);
+ r1.is_header = Some(true);
+ r1.cant_split = Some(true);
+ let mut r2 = tall_row(2);
+ r2.is_header = Some(true);
+ r2.cant_split = Some(true);
+
+ let rows = vec![r0, r1, r2];
+ let col_widths = vec![Pt::new(40.0)];
+
+ // Available 30pt fits at most one row; the remaining rows must spill.
+ let slices = layout_table_paginated(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(30.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert!(
+ slices.len() >= 2,
+ "expected ≥2 slices, got {}",
+ slices.len()
+ );
+ assert!(
+ slices[0].size.height <= Pt::new(30.0),
+ "slice 0 height {:.1}pt exceeds available 30pt — header rows \
+ ignoring the fitting check",
+ slices[0].size.height.raw()
+ );
+
+ // Each header row appears exactly once — no double-emission, since
+ // an all-header table has no "subsequent" rows to head.
+ let total_text: usize = slices
+ .iter()
+ .map(|s| {
+ s.commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count()
+ })
+ .sum();
+ assert_eq!(total_text, 6, "all rows emitted exactly once");
+ }
+
+ /// Regression: when `available_height` is zero (cursor at the page
+ /// bottom), an all-header table must produce an empty first slice and
+ /// emit content on a fresh continuation page.
+ #[test]
+ fn all_header_rows_with_no_space_advances_page() {
+ let mut r0 = tall_row(2);
+ r0.is_header = Some(true);
+ r0.cant_split = Some(true);
+
+ let rows = vec![r0];
+ let col_widths = vec![Pt::new(40.0)];
+
+ let slices = layout_table_paginated(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::ZERO,
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert_eq!(slices.len(), 2, "empty first slice + content slice");
+ let count0 = slices[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ let count1 = slices[1]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(count0, 0, "first slice empty when no space available");
+ assert_eq!(count1, 2, "all content moves to continuation");
+ }
+
+ /// Regression: when a non-header row triggers a page break, header rows
+ /// must still be re-emitted at the top of the continuation slice.
+ #[test]
+ fn header_repeats_on_continuation_when_body_overflows() {
+ let mut header = tall_row(1); // 14pt
+ header.is_header = Some(true);
+ header.cant_split = Some(true);
+ let body0 = tall_row(2); // 28pt
+ let mut body1 = tall_row(2); // 28pt
+ body1.cant_split = Some(true);
+
+ let rows = vec![header, body0, body1];
+ let col_widths = vec![Pt::new(40.0)];
+
+ // Available 50pt: header (14) + body0 (28) = 42 fits; body1 (28) spills.
+ let slices = layout_table_paginated(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(50.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert_eq!(slices.len(), 2);
+ let count0 = slices[0]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ let count1 = slices[1]
+ .commands
+ .iter()
+ .filter(|c| matches!(c, DrawCommand::Text { .. }))
+ .count();
+ assert_eq!(count0, 3, "slice 0: header (1) + body0 (2)");
+ assert_eq!(count1, 3, "slice 1: header repeated (1) + body1 (2)");
+ }
+
+ #[test]
+ fn continuation_slices_use_their_own_page_heights() {
+ let rows = (0..4)
+ .map(|_| {
+ let mut row = tall_row(2);
+ row.cant_split = Some(true);
+ row
+ })
+ .collect::<Vec<_>>();
+ let col_widths = vec![Pt::new(40.0)];
+
+ let slices = layout_table_paginated_with_page_heights(
+ &rows,
+ &col_widths,
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ TablePaginationHeights {
+ available_height: Pt::new(30.0),
+ suppress_first_row_top: false,
+ page_height_for_slice: |slice_index| match slice_index {
+ 1 => Pt::new(30.0),
+ _ => Pt::new(60.0),
+ },
+ },
+ );
+
+ let row_counts = slices
+ .iter()
+ .map(|slice| {
+ slice
+ .commands
+ .iter()
+ .filter(|command| matches!(command, DrawCommand::Text { .. }))
+ .count()
+ / 2
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(row_counts, vec![1, 1, 2]);
+ }
+
+ // ── §17.4.85 lone vMerge=Restart ─────────────────────────────────────
+
+ /// A `Restart` cell with no `Continue` row under it is an ordinary cell.
+ ///
+ /// It used to fall through *both* height paths: `measure_table_rows`
+ /// skipped every merged cell (deferring to the span calculation) and
+ /// `expand_rows_for_vmerge` returned early because the "span" is one row.
+ /// The row therefore got zero height while still emitting its content, so
+ /// whatever followed the table drew on top of it.
+ ///
+ /// Asserted against the unmerged control rather than a literal, so the
+ /// test states the actual rule — a lone restart behaves like no merge at
+ /// all — instead of pinning today's line height.
+ #[test]
+ fn lone_vmerge_restart_row_gets_the_same_height_as_an_unmerged_cell() {
+ let build = |vmerge: Option<VerticalMergeState>| {
+ let mut row = tall_row(3);
+ row.cells[0].vertical_merge = vmerge;
+ layout_table(
+ &[row],
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ )
+ };
+
+ let lone_restart = build(Some(VerticalMergeState::Restart));
+ let control = build(None);
+
+ assert!(
+ control.size.height > Pt::ZERO,
+ "control must have real height for this test to mean anything"
+ );
+ assert_eq!(
+ lone_restart.size.height, control.size.height,
+ "a restart with nothing continuing below it is an ordinary cell"
+ );
+ }
+
+ /// The companion guard: a *genuine* merge span must still take its height
+ /// from `expand_rows_for_vmerge` across the whole span. Folding a
+ /// `Restart` cell into its first row unconditionally — the naive fix for
+ /// the case above — double-counts it against the rows below and inflates
+ /// the table.
+ #[test]
+ fn genuine_vmerge_span_height_is_not_double_counted() {
+ let mut restart = tall_row(6); // 6 lines ≈ 84pt of content
+ restart.cells[0].vertical_merge = Some(VerticalMergeState::Restart);
+ let mut cont = tall_row(0);
+ cont.cells[0].vertical_merge = Some(VerticalMergeState::Continue);
+
+ let result = layout_table(
+ &[restart, cont],
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ );
+
+ // The span is exactly the restart cell's content: 6 lines × 14pt.
+ assert!(
+ (result.size.height.raw() - 84.0).abs() < 0.01,
+ "merged span should total the restart cell's content height (84pt), got {}",
+ result.size.height.raw()
+ );
+ }
+
+ // ── §17.4.1 page advance must gain space ─────────────────────────────
+
+ /// A row group taller than a whole page fits nowhere, so advancing to a
+ /// fresh page cannot help — it only abandons an empty leading slice, which
+ /// the section layer turns into a blank page.
+ ///
+ /// `available_height == page_height` models the table starting at the top
+ /// of a page, which is exactly when the old code emitted the blank.
+ #[test]
+ fn oversized_group_at_page_top_does_not_emit_an_empty_leading_slice() {
+ let mut row = tall_row(20); // ≈ 280pt
+ row.cant_split = Some(true);
+
+ let slices = layout_table_paginated(
+ &[row],
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(100.0),
+ page_height: Pt::new(100.0), // a fresh page is no roomier
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert_eq!(slices.len(), 1, "no page to gain, so no page to push");
+ assert!(
+ !slices[0].commands.is_empty(),
+ "the single slice must carry the content, not be an abandoned empty"
+ );
+ }
+
+ /// The converse, so the fix can't be "never advance": when the table
+ /// starts part-way down a page, a fresh page *is* roomier and the group
+ /// must still move.
+ #[test]
+ fn oversized_group_still_advances_when_the_next_page_is_roomier() {
+ let mut row = tall_row(5); // ≈ 70pt
+ row.cant_split = Some(true);
+
+ let slices = layout_table_paginated(
+ &[row],
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(30.0), // little left here
+ page_height: Pt::new(100.0), // but a full page next
+ suppress_first_row_top: false,
+ },
+ );
+
+ assert_eq!(slices.len(), 2, "advancing gains 70pt, so it must advance");
+ assert!(
+ slices[0].commands.is_empty(),
+ "leading slice is the advance"
+ );
+ assert!(!slices[1].commands.is_empty());
+ }
+
+ // ── In-cell paragraph splitting semantics (§17.3.1.14/.15/.44) ───────
+
+ #[test]
+ fn widow_control_keeps_two_cell_lines_on_each_side_of_a_split() {
+ // §17.3.1.44: a 6-line cell paragraph where 5 lines would fit must not
+ // strand a single-line widow — the split leaves 4 on page 1 and 2 on
+ // page 2 (not 5 + 1).
+ let rows = vec![one_cell_row(vec![styled_para(
+ 6,
+ ParagraphStyle::default(),
+ )])];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(75.0), // 5 lines fit geometrically
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 2);
+ assert_eq!(slice_line_count(&slices[0]), 4, "orphan side keeps >= 2");
+ assert_eq!(slice_line_count(&slices[1]), 2, "widow side keeps >= 2");
+ }
+
+ #[test]
+ fn without_widow_control_a_cell_paragraph_may_strand_one_line() {
+ // Same geometry, widow control off (§17.3.1.44 disabled) ⇒ the cell
+ // splits as far as it fits: 5 lines on page 1, 1 on page 2. This is the
+ // behaviour the widow-control test above suppresses.
+ let style = ParagraphStyle {
+ widow_control: false,
+ ..Default::default()
+ };
+ let rows = vec![one_cell_row(vec![styled_para(6, style)])];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(75.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 2);
+ assert_eq!(slice_line_count(&slices[0]), 5);
+ assert_eq!(slice_line_count(&slices[1]), 1);
+ }
+
+ #[test]
+ fn keep_lines_cell_paragraph_moves_whole_instead_of_splitting() {
+ // §17.3.1.14: a keepLines paragraph is never divided. Only 3 of its 6
+ // lines fit on page 1, but rather than split it moves whole to page 2
+ // (which can hold all 6).
+ let style = ParagraphStyle {
+ keep_lines: true,
+ ..Default::default()
+ };
+ let rows = vec![one_cell_row(vec![styled_para(6, style)])];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(50.0), // 3 lines would fit
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 2);
+ assert_eq!(
+ slice_line_count(&slices[0]),
+ 0,
+ "keepLines: nothing splits off"
+ );
+ assert_eq!(slice_line_count(&slices[1]), 6, "whole paragraph moved");
+ }
+
+ #[test]
+ fn cell_splits_at_paragraph_boundary_when_neither_paragraph_can_split() {
+ // Two 3-line paragraphs: neither can split under widow control (a
+ // 3-line paragraph has no ≥2/≥2 cut). With 4 lines of room the cell
+ // must break at the *paragraph boundary* — 3 lines (para A) on page 1,
+ // 3 (para B) on page 2 — not mid-paragraph.
+ let rows = vec![one_cell_row(vec![
+ styled_para(3, ParagraphStyle::default()),
+ styled_para(3, ParagraphStyle::default()),
+ ])];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(60.0), // room for ~4 lines
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 2);
+ assert_eq!(slice_line_count(&slices[0]), 3, "para A stays intact");
+ assert_eq!(slice_line_count(&slices[1]), 3, "para B stays intact");
+ }
+
+ #[test]
+ fn keep_next_forbids_splitting_a_cell_at_that_paragraph_boundary() {
+ // §17.3.1.15: para A is keepNext, so the cell may not break between A
+ // and B. Neither 3-line paragraph can split internally (widow control),
+ // so — unlike the boundary test above — the whole cell moves to page 2.
+ let keep_next = ParagraphStyle {
+ keep_next: true,
+ ..Default::default()
+ };
+ let rows = vec![one_cell_row(vec![
+ styled_para(3, keep_next),
+ styled_para(3, ParagraphStyle::default()),
+ ])];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(60.0),
+ page_height: Pt::new(200.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 2);
+ assert_eq!(
+ slice_line_count(&slices[0]),
+ 0,
+ "keepNext binds A to B: the boundary cut is illegal, cell moves whole"
+ );
+ assert_eq!(slice_line_count(&slices[1]), 6);
+ }
+
+ #[test]
+ fn cell_paragraph_split_across_three_pages_never_widows() {
+ // §17.3.1.44 must hold at *every* break, not just the first. An 11-line
+ // cell paragraph over pages that each hold 5 lines splits 5/4/2 — never
+ // the 5/5/1 a naive re-split would produce.
+ let rows = vec![one_cell_row(vec![styled_para(
+ 11,
+ ParagraphStyle::default(),
+ )])];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(75.0),
+ page_height: Pt::new(75.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert!(
+ slices.len() >= 3,
+ "expected >= 3 slices, got {}",
+ slices.len()
+ );
+ let counts: Vec<usize> = slices.iter().map(slice_line_count).collect();
+ assert_eq!(counts.iter().sum::<usize>(), 11, "every line emitted once");
+ assert!(
+ counts.iter().all(|&c| c >= 2),
+ "no single-line widow/orphan segment: {counts:?}"
+ );
+ }
+
+ /// §17.4.44: the bottom-edge gap belongs to the table, not to the page it
+ /// happens to land on. The monolithic path adds it (`cursor_y +
+ /// cell_spacing`); the paginated path did not, so the *same table* kept or
+ /// lost its bottom gap depending only on whether it fitted on one page.
+ ///
+ /// Asserted against absolute values and against the **monolithic** path,
+ /// which is a genuinely separate code path. Comparing one paginated layout
+ /// to another cannot see this: a mutation that drops the gap drops it from
+ /// both sides and the comparison still holds.
+ ///
+ /// Empty cells make the arithmetic exact — each row's whole height is its
+ /// own reserved leading gap (see
+ /// `measure::tests::cell_spacing_separates_rows_vertically`), so two rows
+ /// are `2 × spacing` of content plus one trailing gap.
+ #[test]
+ fn cell_spacing_bottom_edge_gap_survives_pagination() {
+ let spacing = Pt::new(6.0);
+ let rows = vec![one_cell_row(vec![]), one_cell_row(vec![])];
+ let widths = [Pt::new(94.0)];
+
+ let whole = layout_table(&rows, &widths, spacing, Pt::new(14.0), None, None, false);
+ assert_eq!(
+ whole.size.height,
+ spacing * 3.0,
+ "two leading gaps plus the table's own bottom edge"
+ );
+
+ let split = layout_table_paginated(
+ &rows,
+ &widths,
+ spacing,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: spacing * 1.5,
+ page_height: spacing * 1.5,
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(split.len(), 2, "precondition: the table paginated");
+ assert_eq!(
+ split[0].size.height, spacing,
+ "an intermediate slice ends at a page cut, not at the table's edge"
+ );
+ assert_eq!(
+ split[1].size.height,
+ spacing * 2.0,
+ "the final slice owns the trailing gap"
+ );
+
+ let total: Pt = split.iter().map(|s| s.size.height).sum();
+ assert_eq!(
+ total, whole.size.height,
+ "a paginated table owns the same total height as the same table \
+ laid out whole"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/split.rs b/crates/liteparse-docx/src/render/layout/table/split.rs
new file mode 100644
index 0000000..d4da09a
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/split.rs
@@ -0,0 +1,939 @@
+//! Row splitting for page pagination.
+//!
+//! §17.4.1: a row without `cantSplit` may have its content broken across
+//! page boundaries. This module derives safe cut points from a row's
+//! already-laid-out cell commands and partitions those commands into a
+//! first slice (stays on the current page) and a second slice (flows to
+//! the next page). Both halves preserve the cell's top/bottom margins so
+//! the text doesn't collide with the cut-edge border.
+
+use crate::render::dimension::Pt;
+use crate::render::layout::draw_command::DrawCommand;
+use crate::render::layout::section::CellLine;
+
+use super::borders::CellBorders;
+use super::types::{CellLayoutEntry, MeasuredRow, TableRowInput};
+
+/// Options for finding a row cut.
+pub(super) struct RowCutInput<'a> {
+ pub(super) mr: &'a MeasuredRow,
+ pub(super) row: &'a TableRowInput,
+ /// Space available for the row on the current page, measured from the
+ /// row's top edge.
+ pub(super) available: Pt,
+}
+
+/// Per-cell split decision: where to partition the commands and how far
+/// to shift the tail commands so the continuation half has the cell's
+/// natural top margin.
+struct CellCut {
+ /// Partition threshold: commands with primary-Y strictly less than
+ /// this value stay on the first half (cell-box coordinates).
+ content_cut_y: Pt,
+ /// Partition threshold for the [`CellLine`] cut model, in cell-content
+ /// coordinates (i.e. `content_cut_y - margin_top`): lines whose box top is
+ /// strictly less stay on the first half.
+ line_cut_y: Pt,
+ /// Amount by which second-half commands (and continuation line tops) are
+ /// shifted up so that the first surviving line lands at the continuation
+ /// cell's natural top margin.
+ shift: Pt,
+}
+
+impl CellCut {
+ /// "Don't split" sentinel — all commands and lines stay on the first half.
+ fn keep_all() -> Self {
+ Self {
+ content_cut_y: Pt::new(f32::INFINITY),
+ line_cut_y: Pt::new(f32::INFINITY),
+ shift: Pt::ZERO,
+ }
+ }
+}
+
+/// Aggregate split decision for a whole row.
+pub(super) struct SplitCut {
+ /// Row-level first-half height (max across cells of per-cell first
+ /// half heights). Each cell's visible box in the first half extends
+ /// from the row top to this Y.
+ first_half_height: Pt,
+ /// One per cell, in the same order as `row.cells`.
+ cells: Vec<CellCut>,
+}
+
+/// Pick a row cut that fits in `available`, honoring each cell's top and
+/// bottom margins so the cut-edge border gets the natural padding Word
+/// preserves on split cells.
+///
+/// Returns `None` when no cell has at least one line that fits within
+/// `available - margins.vertical()`.
+pub(super) fn find_row_cut(input: &RowCutInput<'_>) -> Option<SplitCut> {
+ let mut cells: Vec<CellCut> = Vec::with_capacity(input.row.cells.len());
+ let mut first_half_height = Pt::ZERO;
+ let mut any_fits = false;
+ // Cells that can't be split text-wise (too few baselines or
+ // image/shape-only cells) force the row to leave room for their full
+ // visible height on the first half; otherwise their content (image,
+ // path, etc.) would overflow the cut-edge border.
+ let mut non_splittable_heights: Vec<Pt> = Vec::with_capacity(input.row.cells.len());
+
+ for (entry, cell) in input.mr.entries.iter().zip(&input.row.cells) {
+ match cut_for_cell(
+ entry,
+ cell.margins.top,
+ cell.margins.bottom,
+ input.available,
+ ) {
+ Some((cut, half_h)) => {
+ any_fits = true;
+ if half_h > first_half_height {
+ first_half_height = half_h;
+ }
+ cells.push(cut);
+ non_splittable_heights.push(Pt::ZERO);
+ }
+ None => {
+ cells.push(CellCut::keep_all());
+ // Cell's natural visible height (content + vertical margins)
+ // must fit on the first half — we can't cut through an
+ // image or shape.
+ let required = entry.layout.content_height + cell.margins.top + cell.margins.bottom;
+ non_splittable_heights.push(required);
+ }
+ }
+ }
+
+ if !any_fits {
+ return None;
+ }
+
+ // Raise first_half_height so every non-splittable cell fits. If that
+ // exceeds `available`, splitting isn't safe — caller should spill the
+ // whole row to the next page.
+ let non_splittable_max = non_splittable_heights
+ .iter()
+ .copied()
+ .fold(Pt::ZERO, Pt::max);
+ if non_splittable_max > first_half_height {
+ first_half_height = non_splittable_max;
+ }
+ if first_half_height > input.available {
+ return None;
+ }
+ Some(SplitCut {
+ first_half_height,
+ cells,
+ })
+}
+
+/// For a single cell, choose the largest legal prefix of lines that fits in
+/// `available`, honoring the cell paragraphs' §17.3.1.14 keepLines,
+/// §17.3.1.44 widow/orphan control, and §17.3.1.15 keepNext — the same policy
+/// body across-page splitting applies. Returns the `CellCut` and the first-half
+/// height this cell needs: the retained content plus the cell's top and bottom
+/// margins, so the cut edge gets the natural padding Word preserves (variant 2
+/// of the OOXML split-edge options; §17.4.40 re-applied at the cut edge).
+///
+/// Returns `None` when the cell exposes no legal cut point within `available`
+/// (empty/one-line, image/shape-only, keepLines, or every fitting cut would
+/// strand a widow) — the caller then keeps the cell whole on the first half.
+fn cut_for_cell(
+ entry: &CellLayoutEntry,
+ margin_top: Pt,
+ margin_bottom: Pt,
+ available: Pt,
+) -> Option<(CellCut, Pt)> {
+ // Space available for the content between both margins, since the first
+ // half reproduces the cell's natural layout (top margin, retained lines,
+ // bottom margin) — same as a non-split cell rendering those lines.
+ let budget = available - margin_top - margin_bottom;
+ if budget <= Pt::ZERO {
+ return None;
+ }
+
+ let cont_top = largest_legal_cut(&entry.layout.lines, budget)?;
+ // Load-bearing for **termination**, not tidiness.
+ //
+ // `cont_top` becomes this cell's `shift`, and `split_row_at` derives
+ // `second.height = mr.height - max(shift)`. `mod.rs`'s continuation loop
+ // re-splits `second` until it fits, so a cut with `shift == 0` would hand
+ // back a continuation identical to its input and spin forever. This check
+ // is what makes "`find_row_cut` returned `Some`" imply "the row strictly
+ // shrank", which is the loop's whole termination argument.
+ //
+ // Today it is unreachable: `largest_legal_cut` returns a line's `top_y`,
+ // and the stacker emits strictly increasing tops, so offset 0 never comes
+ // back for a real cell. That makes this a backstop for an invariant owned
+ // by another module rather than by this one — keep it, and note that only
+ // `zero_offset_cut_is_rejected_so_the_shift_is_never_zero` covers it,
+ // because it builds the degenerate entry by hand. Nothing routed through
+ // `measure_table_rows` can.
+ if cont_top <= Pt::ZERO {
+ return None;
+ }
+
+ // `cont_top` is the box top of the first continuation line, in cell-content
+ // coordinates — equivalently the content height the first half retains.
+ // Shifting the continuation up by it lands its first line at the cell's top
+ // margin; the partition threshold sits at `margin_top + cont_top` (draw
+ // commands are margin-shifted, the cut model is not).
+ let shift = cont_top;
+ let half_h = cont_top + margin_top + margin_bottom;
+ Some((
+ CellCut {
+ content_cut_y: margin_top + cont_top,
+ line_cut_y: cont_top,
+ shift,
+ },
+ half_h,
+ ))
+}
+
+/// The largest legal cut offset (`cont_top`, cell-content coords) not exceeding
+/// `budget`: the most content the first half may retain while leaving a
+/// spec-legal split point. A cut "after line L" keeps `lines[0..=L]` and flows
+/// the rest to the continuation.
+///
+/// Legality (§17.3.1.14 / §17.3.1.44 / §17.3.1.15):
+/// - **interior** (L and L+1 share a paragraph): illegal if the paragraph is
+/// internally atomic (keepLines / bordered / shaded / drop cap); otherwise,
+/// under widow control, both sides must keep `>= 2` of the paragraph's lines.
+/// - **boundary** (L and L+1 are different paragraphs): legal unless the earlier
+/// paragraph is keepNext (bound to the block that follows).
+///
+/// Line box tops increase monotonically, so the scan stops once a candidate
+/// exceeds `budget`.
+fn largest_legal_cut(lines: &[CellLine], budget: Pt) -> Option<Pt> {
+ let n = lines.len();
+ if n < 2 {
+ return None;
+ }
+ let mut best: Option<Pt> = None;
+ for l in 0..n - 1 {
+ let a = &lines[l];
+ let b = &lines[l + 1];
+ let cont_top = b.top_y;
+ if cont_top > budget {
+ break;
+ }
+ let legal = if a.para == b.para {
+ if a.interior_atomic {
+ false
+ } else if a.widow_control {
+ let first = lines.iter().position(|x| x.para == a.para).unwrap_or(l);
+ let last = lines.iter().rposition(|x| x.para == a.para).unwrap_or(l);
+ let head = l + 1 - first; // this paragraph's lines kept
+ let tail = last - l; // this paragraph's lines continued
+ head >= 2 && tail >= 2
+ } else {
+ true
+ }
+ } else {
+ !a.keep_next
+ };
+ if legal {
+ best = Some(best.map_or(cont_top, |x: Pt| x.max(cont_top)));
+ }
+ }
+ best
+}
+
+/// A row cut into two halves. Each half is a full `MeasuredRow` ready to
+/// pass to `emit_one_row`.
+pub(super) struct SplitRow {
+ pub(super) first: MeasuredRow,
+ pub(super) second: MeasuredRow,
+}
+
+/// Split a row using `cut`. Each cell's commands are partitioned at the
+/// cell's own `content_cut_y`; the tail is shifted so its first line
+/// lands at the cell's natural `margin_top + ascent` in the
+/// continuation.
+///
+/// Borders: Word preserves the full border box on each half. First half
+/// keeps all original borders. Second half inherits a top border from
+/// the original top if set, otherwise falls back to the original bottom
+/// (same inside-horizontal style used by conflict resolution on
+/// mid-table rows).
+pub(super) fn split_row_at(mr: &MeasuredRow, cut: &SplitCut) -> SplitRow {
+ let first_h = cut.first_half_height;
+ // The largest shift across cells is the amount of content consumed by
+ // the first half. Whatever's left in the original row height is what
+ // the continuation needs to render (top/bottom margins are already
+ // included in `mr.height`, so no additional padding is needed).
+ let max_shift = cut.cells.iter().map(|c| c.shift).fold(Pt::ZERO, Pt::max);
+ let second_h = (mr.height - max_shift).max(Pt::ZERO);
+
+ let mut first_entries: Vec<CellLayoutEntry> = Vec::with_capacity(mr.entries.len());
+ let mut second_entries: Vec<CellLayoutEntry> = Vec::with_capacity(mr.entries.len());
+
+ for (entry, cc) in mr.entries.iter().zip(cut.cells.iter()) {
+ let (first_cmds, second_cmds) =
+ partition_commands(&entry.layout.commands, cc.content_cut_y, cc.shift);
+ // Partition the cut model too, rebasing the continuation's line tops by
+ // the same shift, so a further split of the continuation (mod.rs's
+ // iterative loop) re-evaluates §17.3.1.44 widow control against the
+ // lines that actually remain.
+ let (first_lines, second_lines) =
+ partition_lines(&entry.layout.lines, cc.line_cut_y, cc.shift);
+ first_entries.push(CellLayoutEntry {
+ layout: crate::render::layout::cell::CellLayout {
+ commands: first_cmds,
+ content_height: entry.layout.content_height.min(first_h),
+ lines: first_lines,
+ },
+ cell_x: entry.cell_x,
+ cell_w: entry.cell_w,
+ grid_col: entry.grid_col,
+ });
+ second_entries.push(CellLayoutEntry {
+ layout: crate::render::layout::cell::CellLayout {
+ commands: second_cmds,
+ content_height: (entry.layout.content_height - cc.shift).max(Pt::ZERO),
+ lines: second_lines,
+ },
+ cell_x: entry.cell_x,
+ cell_w: entry.cell_w,
+ grid_col: entry.grid_col,
+ });
+ }
+
+ let first_borders: Vec<CellBorders> = mr.borders.to_vec();
+ let second_borders: Vec<CellBorders> = mr
+ .borders
+ .iter()
+ .map(|b| CellBorders {
+ // The continuation's top is the *cut* edge the split invented, not
+ // the author's top edge, so it takes the row's bottom border
+ // whenever the original top paints nothing. That deliberately
+ // includes a suppressed top: `nil` on the row's own top edge says
+ // nothing about a boundary that only exists because of the split.
+ top: if b.top.line().is_some() {
+ b.top
+ } else {
+ b.bottom
+ },
+ bottom: b.bottom,
+ left: b.left,
+ right: b.right,
+ })
+ .collect();
+
+ SplitRow {
+ // §17.4.44: both halves are row boxes placed against a cursor, so each
+ // keeps the original leading gap — the continuation sits one spacing
+ // below the top of the table area on its page, exactly as the first
+ // half sits one spacing below the row above it.
+ first: MeasuredRow {
+ entries: first_entries,
+ borders: first_borders,
+ height: first_h,
+ leading_gap: mr.leading_gap,
+ border_gap_below: Pt::ZERO,
+ },
+ second: MeasuredRow {
+ entries: second_entries,
+ borders: second_borders,
+ height: second_h,
+ leading_gap: mr.leading_gap,
+ border_gap_below: mr.border_gap_below,
+ },
+ }
+}
+
+/// Split a command list at `cut_y`. Commands whose primary Y < `cut_y`
+/// go to the first half; the rest land in the second half shifted up by
+/// `shift` so they start at the continuation cell's natural top margin.
+fn partition_commands(
+ commands: &[DrawCommand],
+ cut_y: Pt,
+ shift: Pt,
+) -> (Vec<DrawCommand>, Vec<DrawCommand>) {
+ let mut first = Vec::new();
+ let mut second = Vec::new();
+ for cmd in commands {
+ if command_primary_y(cmd) < cut_y {
+ first.push(cmd.clone());
+ } else {
+ let mut c = cmd.clone();
+ c.shift_y(-shift);
+ second.push(c);
+ }
+ }
+ (first, second)
+}
+
+/// Partition the [`CellLine`] cut model at `cut_y` (cell-content coords).
+/// Lines whose box top is `< cut_y` stay on the first half; the rest form the
+/// continuation, with their tops rebased up by `shift` so the model tracks the
+/// continuation's own coordinates for any further split.
+fn partition_lines(lines: &[CellLine], cut_y: Pt, shift: Pt) -> (Vec<CellLine>, Vec<CellLine>) {
+ let mut first = Vec::new();
+ let mut second = Vec::new();
+ for line in lines {
+ if line.top_y < cut_y {
+ first.push(line.clone());
+ } else {
+ let mut l = line.clone();
+ l.top_y -= shift;
+ second.push(l);
+ }
+ }
+ (first, second)
+}
+
+/// The Y used to decide which side of the cut a command belongs to. For
+/// `Text` we use the baseline; for rect/line/image we use the top edge.
+fn command_primary_y(cmd: &DrawCommand) -> Pt {
+ match cmd {
+ DrawCommand::Text { position, .. } | DrawCommand::NamedDestination { position, .. } => {
+ position.y
+ }
+ DrawCommand::Underline { line, .. } | DrawCommand::Line { line, .. } => line.start.y,
+ DrawCommand::Image { rect, .. }
+ | DrawCommand::EmojiCluster { rect, .. }
+ | DrawCommand::Rect { rect, .. }
+ | DrawCommand::LinkAnnotation { rect, .. }
+ | DrawCommand::InternalLink { rect, .. } => rect.origin.y,
+ DrawCommand::Path { origin, .. } => origin.y,
+ // §17.3.1.19: a marked-content boundary has no y of its own. It takes
+ // the top of the cell so it stays with the first half of a split — a
+ // heading whose paragraph splits keeps its outline entry on the page
+ // it starts on, which is the same rule the paragraph splitter applies.
+ DrawCommand::Outline(_) => Pt::ZERO,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::borders::CellEdge;
+ use super::*;
+ use crate::render::geometry::PtEdgeInsets;
+ use crate::render::layout::fragment::{FontProps, Fragment, TextMetrics};
+ use crate::render::layout::paragraph::ParagraphStyle;
+ use crate::render::layout::section::LayoutBlock;
+ use crate::render::layout::table::types::{CellVAlign, TableCellInput};
+ use crate::render::resolve::color::RgbColor;
+ use std::rc::Rc;
+
+ fn text_frag(text: &str) -> Fragment {
+ Fragment::Text {
+ text: text.into(),
+ font: Rc::new(FontProps {
+ family: Rc::from("Test"),
+ size: Pt::new(12.0),
+ bold: false,
+ italic: false,
+ underline: false,
+ char_spacing: Pt::ZERO,
+ text_scale: 1.0,
+ underline_position: Pt::ZERO,
+ underline_thickness: Pt::ZERO,
+ }),
+ color: RgbColor::BLACK,
+ width: Pt::new(30.0),
+ trimmed_width: Pt::new(30.0),
+ metrics: TextMetrics {
+ ascent: Pt::new(10.0),
+ descent: Pt::new(4.0),
+ leading: Pt::ZERO,
+ },
+ hyperlink_url: None,
+ shading: None,
+ border: None,
+ baseline_offset: Pt::ZERO,
+ text_offset: Pt::ZERO,
+ is_footnote_ref: false,
+ }
+ }
+
+ /// One cell, `n` lines (each fragment wraps to its own line at width 40).
+ fn row_n_lines(n: usize, margin: f32) -> TableRowInput {
+ let m = PtEdgeInsets::new(
+ Pt::new(margin),
+ Pt::new(margin),
+ Pt::new(margin),
+ Pt::new(margin),
+ );
+ TableRowInput {
+ cells: vec![TableCellInput {
+ blocks: vec![LayoutBlock::Paragraph {
+ fragments: (0..n).map(|i| text_frag(&format!("L{i} "))).collect(),
+ style: ParagraphStyle::default(),
+ page_break_before: false,
+ footnotes: vec![],
+ floating_images: vec![],
+ floating_shapes: vec![],
+ }],
+ margins: m,
+ grid_span: 1,
+ shading: None,
+ cell_borders: None,
+ vertical_merge: None,
+ vertical_align: CellVAlign::Top,
+ }],
+ height_rule: None,
+ is_header: None,
+ cant_split: None,
+ grid_before: 0,
+ border_overrides: None,
+ }
+ }
+
+ fn measure(rows: &[TableRowInput]) -> super::super::types::MeasuredTable {
+ super::super::measure::measure_table_rows(
+ rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ false,
+ )
+ }
+
+ /// **The termination invariant** for `mod.rs`'s continuation loop.
+ ///
+ /// That loop re-splits the continuation half until it fits, so it only
+ /// terminates if every accepted cut strictly shrinks the row. Here that
+ /// property is asserted directly, across a grid of line counts, available
+ /// heights straddling the line-height and widow-control boundaries, and
+ /// cell margins large enough to swallow the budget.
+ ///
+ /// If this ever fails, `layout_table_paginated` hangs — the same class of
+ /// defect as the floating-table spillover loop (E4c).
+ #[test]
+ fn every_accepted_cut_strictly_shrinks_the_row() {
+ for n_lines in [2usize, 3, 5, 12] {
+ for avail in [1.0f32, 5.0, 13.9, 14.0, 14.1, 27.9, 28.0, 100.0, 1000.0] {
+ for margin in [0.0f32, 3.0, 20.0] {
+ let rows = vec![row_n_lines(n_lines, margin)];
+ let measured = measure(&rows);
+ let input = RowCutInput {
+ mr: &measured.rows[0],
+ row: &rows[0],
+ available: Pt::new(avail),
+ };
+ let Some(cut) = find_row_cut(&input) else {
+ continue;
+ };
+ let parts = split_row_at(&measured.rows[0], &cut);
+ assert!(
+ parts.second.height < measured.rows[0].height,
+ "cut made no progress (lines={n_lines} avail={avail} \
+ margin={margin}): {:.2} -> {:.2}",
+ measured.rows[0].height.raw(),
+ parts.second.height.raw(),
+ );
+ }
+ }
+ }
+ }
+
+ /// The mechanism behind the invariant: an accepted cut always carries a
+ /// strictly positive shift, because `cut_for_cell` rejects `cont_top == 0`.
+ /// `split_row_at` subtracts `max(shift)` from the row height, so a zero
+ /// shift would return the continuation unchanged.
+ #[test]
+ fn accepted_cuts_carry_a_positive_shift() {
+ let rows = vec![row_n_lines(6, 0.0)];
+ let measured = measure(&rows);
+ let cut = find_row_cut(&RowCutInput {
+ mr: &measured.rows[0],
+ row: &rows[0],
+ available: Pt::new(60.0),
+ })
+ .expect("a 6-line row must be splittable at 60pt");
+ let max_shift = cut.cells.iter().map(|c| c.shift).fold(Pt::ZERO, Pt::max);
+ assert!(
+ max_shift > Pt::ZERO,
+ "shift must be positive or the continuation loop cannot progress"
+ );
+ }
+
+ /// The `cont_top <= 0` guard, exercised directly.
+ ///
+ /// It cannot be reached through `measure_table_rows`: the stacker emits
+ /// strictly increasing line tops, so `largest_legal_cut` never returns 0
+ /// for a real cell. Deleting the guard therefore breaks no test that goes
+ /// through the normal path — which is exactly why this one bypasses it and
+ /// hands `cut_for_cell` a synthetic entry whose two lines share `top_y = 0`.
+ ///
+ /// Accepting that cut would give `shift == 0`, and `mod.rs`'s continuation
+ /// loop would re-split an unchanged row forever. The guard backstops a
+ /// stacker invariant this module cannot enforce, so its test must not
+ /// depend on that invariant holding.
+ #[test]
+ fn zero_offset_cut_is_rejected_so_the_shift_is_never_zero() {
+ let flat_line = |para: usize| CellLine {
+ top_y: Pt::ZERO,
+ para,
+ interior_atomic: false,
+ widow_control: false,
+ keep_next: false,
+ };
+ let lines = vec![flat_line(0), flat_line(1)];
+
+ // The cut model does offer offset 0 as "legal" ...
+ assert_eq!(
+ largest_legal_cut(&lines, Pt::new(100.0)),
+ Some(Pt::ZERO),
+ "two lines sharing a top expose a zero-offset cut"
+ );
+
+ // ... and `cut_for_cell` must refuse it anyway.
+ let entry = CellLayoutEntry {
+ layout: crate::render::layout::cell::CellLayout {
+ commands: Vec::new(),
+ content_height: Pt::new(28.0),
+ lines,
+ },
+ cell_x: Pt::ZERO,
+ cell_w: Pt::new(40.0),
+ grid_col: 0,
+ };
+ assert!(
+ cut_for_cell(&entry, Pt::ZERO, Pt::ZERO, Pt::new(100.0)).is_none(),
+ "a zero-offset cut must be rejected - accepting it gives shift == 0 \
+ and the continuation loop never progresses"
+ );
+ }
+
+ /// A single line offers no cut at all (`n < 2`), so an unsplittable row
+ /// spills whole rather than looping.
+ #[test]
+ fn fewer_than_two_lines_yields_no_cut() {
+ assert_eq!(largest_legal_cut(&[], Pt::new(100.0)), None);
+ let one = vec![CellLine {
+ top_y: Pt::ZERO,
+ para: 0,
+ interior_atomic: false,
+ widow_control: false,
+ keep_next: false,
+ }];
+ assert_eq!(largest_legal_cut(&one, Pt::new(100.0)), None);
+ }
+
+ /// End-to-end bound: a 40-line row on a page that fits two lines produces
+ /// 20 slices and halts. Pins that the loop consumes lines rather than
+ /// merely shrinking by an epsilon.
+ #[test]
+ fn iterative_continuation_split_halts_with_a_bounded_slice_count() {
+ use crate::render::layout::table::{TablePaginationConfig, layout_table_paginated};
+
+ let rows = vec![row_n_lines(40, 0.0)];
+ let slices = layout_table_paginated(
+ &rows,
+ &[Pt::new(40.0)],
+ Pt::ZERO,
+ Pt::new(14.0),
+ None,
+ None,
+ &TablePaginationConfig {
+ available_height: Pt::new(28.0), // exactly two 14pt lines
+ page_height: Pt::new(28.0),
+ suppress_first_row_top: false,
+ },
+ );
+ assert_eq!(slices.len(), 20, "40 lines at 2 per page");
+ }
+
+ // ── Cut correctness (E5b#4) ──────────────────────────────────────────
+ //
+ // The tests above pin *termination*. These pin what the cut actually
+ // produces: which lines land on each side, where the partition boundary
+ // falls, that both halves keep their margins, and that a continuation
+ // inherits a visible top edge.
+
+ /// Text of every `Text` command, in order.
+ fn texts(cmds: &[DrawCommand]) -> Vec<String> {
+ cmds.iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { text, .. } => Some(text.to_string()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Baseline y of every `Text` command, in order.
+ fn baselines(cmds: &[DrawCommand]) -> Vec<f32> {
+ cmds.iter()
+ .filter_map(|c| match c {
+ DrawCommand::Text { position, .. } => Some(position.y.raw()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// A 6-line cell cut with room for 4 lines splits 4 / 2, and each line
+ /// appears on exactly one side — no duplication, no loss.
+ ///
+ /// The cut model and the draw commands are partitioned by *separate*
+ /// thresholds (`line_cut_y` in content coordinates, `content_cut_y` in
+ /// cell-box coordinates, differing by the top margin), so the two can
+ /// disagree. Asserting the actual line texts is what catches that.
+ #[test]
+ fn cut_partitions_lines_without_duplicating_or_dropping_any() {
+ let rows = vec![row_n_lines(6, 0.0)];
+ let measured = measure(&rows);
+ let cut = find_row_cut(&RowCutInput {
+ mr: &measured.rows[0],
+ row: &rows[0],
+ available: Pt::new(4.0 * 14.0),
+ })
+ .expect("6 lines with room for 4 must be splittable");
+ let parts = split_row_at(&measured.rows[0], &cut);
+
+ let first = texts(&parts.first.entries[0].layout.commands);
+ let second = texts(&parts.second.entries[0].layout.commands);
+
+ assert_eq!(first.len() + second.len(), 6, "no line lost or duplicated");
+ assert_eq!(first, vec!["L0 ", "L1 ", "L2 ", "L3 "]);
+ assert_eq!(second, vec!["L4 ", "L5 "]);
+ }
+
+ /// §17.4.40: the continuation's first line sits at the cell's natural top
+ /// margin, not at the cut offset — the tail is shifted up by exactly the
+ /// content the first half retained, so the cut edge keeps its padding.
+ #[test]
+ fn continuation_first_line_is_rebased_to_the_cell_top() {
+ let rows = vec![row_n_lines(6, 0.0)];
+ let measured = measure(&rows);
+ let cut = find_row_cut(&RowCutInput {
+ mr: &measured.rows[0],
+ row: &rows[0],
+ available: Pt::new(4.0 * 14.0),
+ })
+ .expect("splittable");
+ let parts = split_row_at(&measured.rows[0], &cut);
+
+ let before = baselines(&measured.rows[0].entries[0].layout.commands);
+ let first = baselines(&parts.first.entries[0].layout.commands);
+ let second = baselines(&parts.second.entries[0].layout.commands);
+
+ assert_eq!(
+ first,
+ before[..4],
+ "first half keeps its original baselines"
+ );
+ // The tail is shifted up by the retained content height (4 lines).
+ let shift = before[4] - second[0];
+ assert!(
+ (shift - 4.0 * 14.0).abs() < 0.01,
+ "tail shifted by the retained content height, got {shift}"
+ );
+ assert_eq!(
+ second[0], before[0],
+ "the continuation's first line lands where the original first line did"
+ );
+ }
+
+ /// The continuation's line *model* is rebased by the same shift as its
+ /// commands, so a further split re-evaluates §17.3.1.44 widow control
+ /// against the lines that actually remain rather than stale offsets.
+ #[test]
+ fn continuation_line_model_is_rebased_with_the_commands() {
+ let rows = vec![row_n_lines(6, 0.0)];
+ let measured = measure(&rows);
+ let cut = find_row_cut(&RowCutInput {
+ mr: &measured.rows[0],
+ row: &rows[0],
+ available: Pt::new(4.0 * 14.0),
+ })
+ .expect("splittable");
+ let parts = split_row_at(&measured.rows[0], &cut);
+
+ let second_lines = &parts.second.entries[0].layout.lines;
+ assert_eq!(second_lines.len(), 2, "two lines continue");
+ assert_eq!(
+ second_lines[0].top_y,
+ Pt::ZERO,
+ "the continuation's first line starts at content offset 0"
+ );
+ assert_eq!(parts.first.entries[0].layout.lines.len(), 4);
+ }
+
+ /// `partition_lines` uses a strict `<`, so a line whose top sits exactly on
+ /// the threshold belongs to the **continuation**. That boundary is what
+ /// makes the retained height equal `cont_top` rather than overshooting by a
+ /// line; getting it backwards would put `cont_top`'s own line on both the
+ /// first half and the continuation's height budget.
+ #[test]
+ fn a_line_exactly_at_the_threshold_goes_to_the_continuation() {
+ let line_at = |top: f32, para: usize| CellLine {
+ top_y: Pt::new(top),
+ para,
+ interior_atomic: false,
+ widow_control: false,
+ keep_next: false,
+ };
+ let lines = vec![line_at(0.0, 0), line_at(14.0, 0), line_at(28.0, 0)];
+ let (first, second) = partition_lines(&lines, Pt::new(14.0), Pt::new(14.0));
+
+ assert_eq!(first.len(), 1, "only the line strictly above the cut stays");
+ assert_eq!(second.len(), 2);
+ assert_eq!(
+ second[0].top_y,
+ Pt::ZERO,
+ "the threshold line becomes the continuation's first, rebased to 0"
+ );
+ assert_eq!(second[1].top_y, Pt::new(14.0));
+ }
+
+ /// §17.4.40: both halves preserve the cell's vertical margins, which is the
+ /// stated reason the cut keeps `margin_top + margin_bottom` in its height
+ /// budget — text must not collide with the cut-edge border.
+ #[test]
+ fn both_halves_account_for_the_cell_margins() {
+ const MARGIN: f32 = 5.0;
+ let rows = vec![row_n_lines(6, MARGIN)];
+ let measured = measure(&rows);
+ // Room for 2 lines of content plus both margins.
+ let available = Pt::new(2.0 * 14.0 + 2.0 * MARGIN);
+ let cut = find_row_cut(&RowCutInput {
+ mr: &measured.rows[0],
+ row: &rows[0],
+ available,
+ })
+ .expect("splittable with margins");
+ let parts = split_row_at(&measured.rows[0], &cut);
+
+ assert!(
+ parts.first.height <= available,
+ "first half ({:.1}) must fit the space it was given ({:.1})",
+ parts.first.height.raw(),
+ available.raw()
+ );
+ // The retained content is 2 lines; the half is that plus both margins.
+ assert!(
+ (parts.first.height.raw() - (2.0 * 14.0 + 2.0 * MARGIN)).abs() < 0.01,
+ "first-half height is retained content + both margins, got {:.1}",
+ parts.first.height.raw()
+ );
+ assert!(
+ parts.second.height > Pt::ZERO,
+ "the continuation keeps real height"
+ );
+ }
+
+ /// A continuation inherits a visible top edge: `top: b.top.or(b.bottom)`.
+ /// Without the fallback a row whose top border was resolved away (the
+ /// common mid-table case, where the edge is drawn as the row above's
+ /// bottom) would continue onto the next page with no top line at all.
+ #[test]
+ fn continuation_inherits_a_top_border_from_the_original_bottom() {
+ let bottom = super::super::types::TableBorderLine {
+ width: Pt::new(2.0),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ style: super::super::types::TableBorderStyle::Single,
+ };
+ let mut mr = measure(&[row_n_lines(6, 0.0)]).rows.pop().expect("one row");
+ mr.borders[0] = CellBorders {
+ // Absent, not Suppressed: resolved away by conflict resolution, not
+ // by an author `nil` — the fallback applies to both, but this test
+ // is about the conflict-resolution case.
+ top: CellEdge::Absent,
+ bottom: CellEdge::Line(bottom),
+ left: CellEdge::Absent,
+ right: CellEdge::Absent,
+ };
+ let rows = [row_n_lines(6, 0.0)];
+ let cut = find_row_cut(&RowCutInput {
+ mr: &mr,
+ row: &rows[0],
+ available: Pt::new(4.0 * 14.0),
+ })
+ .expect("splittable");
+ let parts = split_row_at(&mr, &cut);
+
+ assert!(
+ parts.first.borders[0].top.line().is_none(),
+ "the first half keeps the original borders verbatim"
+ );
+ assert_eq!(
+ parts.second.borders[0].top.line().map(|b| b.width),
+ Some(Pt::new(2.0)),
+ "the continuation falls back to the original bottom for its top edge"
+ );
+ }
+
+ /// An explicit top border is *not* replaced by the bottom — `or` must not
+ /// become an unconditional overwrite.
+ #[test]
+ fn continuation_keeps_an_explicit_top_border() {
+ let thin = super::super::types::TableBorderLine {
+ width: Pt::new(1.0),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ style: super::super::types::TableBorderStyle::Single,
+ };
+ let thick = super::super::types::TableBorderLine {
+ width: Pt::new(4.0),
+ ..thin
+ };
+ let mut mr = measure(&[row_n_lines(6, 0.0)]).rows.pop().expect("one row");
+ mr.borders[0] = CellBorders {
+ top: CellEdge::Line(thin),
+ bottom: CellEdge::Line(thick),
+ left: CellEdge::Absent,
+ right: CellEdge::Absent,
+ };
+ let rows = [row_n_lines(6, 0.0)];
+ let cut = find_row_cut(&RowCutInput {
+ mr: &mr,
+ row: &rows[0],
+ available: Pt::new(4.0 * 14.0),
+ })
+ .expect("splittable");
+ let parts = split_row_at(&mr, &cut);
+
+ assert_eq!(
+ parts.second.borders[0].top.line().map(|b| b.width),
+ Some(Pt::new(1.0)),
+ "an existing top border wins over the bottom fallback"
+ );
+ }
+
+ /// The command partition boundary, exercised directly.
+ ///
+ /// It cannot be reached through real layout: `command_primary_y` uses a
+ /// text command's *baseline* (box top + ascent) while `content_cut_y` is a
+ /// box top, so no text command ever lands exactly on the threshold —
+ /// flipping `<` to `<=` breaks no end-to-end test. Rect-shaped commands
+ /// (cell shading, images, paragraph borders) *are* keyed on their top edge,
+ /// so the boundary is reachable in principle; this pins it with synthetic
+ /// commands rather than relying on metrics that happen to avoid it.
+ ///
+ /// A command exactly at the threshold belongs to the continuation, matching
+ /// `partition_lines` — the two must agree or the halves disagree about what
+ /// they contain.
+ #[test]
+ fn a_command_exactly_at_the_threshold_goes_to_the_continuation() {
+ use crate::render::geometry::PtRect;
+ let rect_at = |y: f32| DrawCommand::Rect {
+ rect: PtRect::from_xywh(Pt::ZERO, Pt::new(y), Pt::new(10.0), Pt::new(2.0)),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ };
+ let cmds = vec![rect_at(0.0), rect_at(14.0), rect_at(28.0)];
+
+ let (first, second) = partition_commands(&cmds, Pt::new(14.0), Pt::new(14.0));
+
+ let ys = |v: &[DrawCommand]| -> Vec<f32> {
+ v.iter()
+ .map(|c| match c {
+ DrawCommand::Rect { rect, .. } => rect.origin.y.raw(),
+ _ => unreachable!(),
+ })
+ .collect()
+ };
+ assert_eq!(
+ ys(&first),
+ vec![0.0],
+ "only the command strictly above the cut stays"
+ );
+ assert_eq!(
+ ys(&second),
+ vec![0.0, 14.0],
+ "the threshold command continues, rebased by the shift"
+ );
+ }
+}
diff --git a/crates/liteparse-docx/src/render/layout/table/types.rs b/crates/liteparse-docx/src/render/layout/table/types.rs
new file mode 100644
index 0000000..ae8ad56
--- /dev/null
+++ b/crates/liteparse-docx/src/render/layout/table/types.rs
@@ -0,0 +1,175 @@
+//! Type definitions for table layout.
+
+use crate::render::dimension::Pt;
+use crate::render::geometry::{PtEdgeInsets, PtSize};
+use crate::render::resolve::color::RgbColor;
+
+use crate::render::layout::cell::CellLayout;
+use crate::render::layout::draw_command::DrawCommand;
+
+/// §17.4.81: row height rule.
+#[derive(Clone, Copy, Debug)]
+pub enum RowHeightRule {
+ /// Row height is at least this value; grows to fit content.
+ AtLeast(Pt),
+ /// Row height is exactly this value; content may clip.
+ Exact(Pt),
+}
+
+/// A table row for layout.
+pub struct TableRowInput {
+ pub cells: Vec<TableCellInput>,
+ /// §17.4.81: row height constraint.
+ pub height_rule: Option<RowHeightRule>,
+ /// §17.4.49: row repeats as header on each continuation page.
+ pub is_header: Option<bool>,
+ /// §17.4.1: if true, row cannot be split across pages.
+ pub cant_split: Option<bool>,
+ /// §17.4.17: number of grid columns to skip at the row's start. The first
+ /// cell's leftmost grid column is `grid_before`, not 0.
+ ///
+ /// There is deliberately no `grid_after` counterpart. §17.4.16 `gridAfter`
+ /// is *derivable* — the row's right edge is `grid_before` plus the sum of
+ /// its cells' `grid_span`s — and every consumer here works from that
+ /// running grid column already, including the border resolution that
+ /// decides whether the last cell sits at the table edge (`insideV`) or not.
+ /// The model keeps `gridAfter` as parsed (`model::TableRowProperties`);
+ /// carrying it into layout added a field nothing read.
+ pub grid_before: u32,
+ /// §17.4.61 `<w:tblPrEx><w:tblBorders/></w:tblPrEx>` — per-row
+ /// override of the table-level `tblBorders`. When set, each side
+ /// independently replaces the corresponding side of the table's
+ /// `TableBorderConfig` for this row only; sides absent from the
+ /// override fall through to the table's value.
+ ///
+ /// Note that an override side of `None` means "explicitly no
+ /// border" (Word's `<w:top w:val="none"/>`) — the parser converts
+ /// `val="none"` to `None` here, matching the layout's invariant
+ /// that `None` is "draw nothing" everywhere else in this module.
+ pub border_overrides: Option<TableBorderConfig>,
+}
+
+/// §17.4.84: cell vertical alignment.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum CellVAlign {
+ Top,
+ Center,
+ Bottom,
+}
+
+/// A single cell for layout.
+pub struct TableCellInput {
+ pub blocks: Vec<crate::render::layout::section::LayoutBlock>,
+ pub margins: PtEdgeInsets,
+ /// Number of grid columns this cell spans (gridSpan, default 1).
+ pub grid_span: u32,
+ /// Background color for cell shading.
+ pub shading: Option<RgbColor>,
+ /// §17.7.6: per-cell resolved borders from conditional formatting.
+ pub cell_borders: Option<CellBorderConfig>,
+ /// §17.4.85: vertical merge state.
+ pub vertical_merge: Option<VerticalMergeState>,
+ /// §17.4.84: vertical alignment of content within the cell.
+ pub vertical_align: CellVAlign,
+}
+
+/// §17.4.85: vertical merge state for a cell.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum VerticalMergeState {
+ /// This cell starts a new vertical merge group.
+ Restart,
+ /// This cell continues from the cell above (content is skipped).
+ Continue,
+}
+
+/// §17.7.6: a border override for a single cell edge.
+///
+/// There is deliberately **no variant for `val="none"`**. Per [MS-OI29500]
+/// §17.4.66 an explicit `none` is indistinguishable from an omitted edge — both
+/// inherit and both yield — so `convert_cell_border_override` maps it to
+/// `Option::None` and it never reaches here. Only `nil`, which suppresses,
+/// needs to be represented.
+#[derive(Clone, Copy, Debug)]
+pub enum CellBorderOverride {
+ /// §17.18.2 `val="nil"`: draw nothing on this edge *and* win the conflict
+ /// against whatever the adjacent cell declares.
+ Suppress,
+ /// A specific border line on this edge.
+ Border(TableBorderLine),
+}
+
+/// Per-cell border configuration (resolved from conditional formatting).
+/// `None` = no override (use table-level default for this edge).
+#[derive(Clone, Debug)]
+pub struct CellBorderConfig {
+ pub top: Option<CellBorderOverride>,
+ pub bottom: Option<CellBorderOverride>,
+ pub left: Option<CellBorderOverride>,
+ pub right: Option<CellBorderOverride>,
+}
+
+/// Resolved table border configuration.
+#[derive(Clone, Debug)]
+pub struct TableBorderConfig {
+ pub top: Option<TableBorderLine>,
+ pub bottom: Option<TableBorderLine>,
+ pub left: Option<TableBorderLine>,
+ pub right: Option<TableBorderLine>,
+ pub inside_h: Option<TableBorderLine>,
+ pub inside_v: Option<TableBorderLine>,
+}
+
+/// A single table border line.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct TableBorderLine {
+ pub width: Pt,
+ pub color: RgbColor,
+ /// §17.4.38: border style (single, double, etc.)
+ pub style: TableBorderStyle,
+}
+
+/// Supported table border styles.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TableBorderStyle {
+ Single,
+ Double,
+}
+
+/// Result of laying out a table.
+#[derive(Debug)]
+pub struct TableLayout {
+ /// Draw commands positioned relative to the table's top-left origin.
+ pub commands: Vec<DrawCommand>,
+ /// Total size of the table.
+ pub size: PtSize,
+}
+
+/// Per-row measurement data from the table measurement phase.
+/// Contains everything needed to emit draw commands for this row.
+pub(super) struct MeasuredRow {
+ pub(super) entries: Vec<CellLayoutEntry>,
+ pub(super) borders: Vec<super::borders::CellBorders>,
+ /// Total vertical space the row owns, **including** `leading_gap`.
+ pub(super) height: Pt,
+ /// §17.4.44: cell spacing reserved above this row's content, so the gap to
+ /// the row above is exactly one `tblCellSpacing`. Zero without spacing,
+ /// which is every table that does not set it.
+ pub(super) leading_gap: Pt,
+ /// §17.4.38: maximum bottom border width for gap between this row and the next.
+ pub(super) border_gap_below: Pt,
+}
+
+/// Result of the table measurement phase.
+pub(super) struct MeasuredTable {
+ pub(super) rows: Vec<MeasuredRow>,
+ pub(super) table_width: Pt,
+}
+
+/// Per-cell layout result with positioning info from pass 2.
+pub(super) struct CellLayoutEntry {
+ pub(super) layout: CellLayout,
+ pub(super) cell_x: Pt,
+ pub(super) cell_w: Pt,
+ /// Starting grid column index (for vMerge neighbor lookup).
+ pub(super) grid_col: usize,
+}
diff --git a/crates/liteparse-docx/src/render/mod.rs b/crates/liteparse-docx/src/render/mod.rs
index c345e2c..02ee39b 100644
--- a/crates/liteparse-docx/src/render/mod.rs
+++ b/crates/liteparse-docx/src/render/mod.rs
@@ -1,13 +1,12 @@
-//! Skia-free half of dxpdf's render pipeline.
+//! Skia-free render pipeline: resolve → layout.
//!
-//! Upstream this module is `resolve → layout → subset → paint`. Only `resolve`
-//! is vendored: it flattens style inheritance (`basedOn` chains, docDefaults,
-//! theme font refs, table conditional formatting) and numbering (abstract +
-//! instance + `lvlOverride`/`startOverride`), which is everything the structure
-//! path needs. `layout`, `subset` and `painter` are Skia-bound and omitted.
-//!
-//! `dimension`, `geometry`, `error`, `layout::draw_command` and
-//! `emoji::cluster` come along because `resolve` refers to them.
+//! Upstream this module is `resolve → layout → subset → paint`. Vendored here
+//! are `resolve` (style/numbering cascade — everything the structure path
+//! needs) and, as of the C′ port, `layout` — dxpdf's full pagination engine
+//! with its Skia `TextMeasurer` swapped for fontdb + skrifa
+//! (`layout::measurer`, `fonts`). `subset` and `painter` are PDF-emission
+//! concerns and stay out; that is why `render()` / PDF output do not exist
+//! here and layout ends at [`layout::draw_command::LayoutedPage`].
pub mod dimension;
pub mod emoji;
@@ -16,3 +15,400 @@ pub mod fonts;
pub mod geometry;
pub mod layout;
pub mod resolve;
+
+use crate::model::Document;
+
+use crate::model::Block;
+use crate::render::layout::build::{
+ BuildContext, BuildState, build_document_endnotes, build_section_blocks, default_line_height,
+};
+use crate::render::layout::draw_command::LayoutedPage;
+use crate::render::layout::header_footer::{
+ HeaderFooterBlocks, HeaderFooterClearance, PageRange, render_headers_footers,
+};
+use crate::render::layout::page::PageConfig;
+use crate::render::layout::section::layout_section_with_clearance;
+use crate::render::resolve::ResolvedDocument;
+use crate::render::resolve::header_footer::HeaderFooterSet;
+
+/// Estimate where the content on `page` ends, so a `Continuous` section
+/// (§17.6.22) knows where to resume on the same page.
+///
+/// The match is **exhaustive on purpose**: a `_ => continue` arm silently gives
+/// any unlisted variant zero height, and the following section then paints over
+/// it. That is how `EmojiCluster` and `Path` came to be ignored — a paragraph
+/// containing only an emoji resumed at `margins.top`, drawing the next
+/// section's text inside the emoji's box. Adding a variant should break this
+/// build, not the output.
+fn estimate_cursor_y(
+ page: &layout::draw_command::LayoutedPage,
+ config: &layout::page::PageConfig,
+) -> dimension::Pt {
+ use layout::draw_command::DrawCommand;
+ let mut max_y = config.margins.top;
+ for cmd in &page.commands {
+ let bottom = match cmd {
+ // Baseline plus a full font size approximates the descender.
+ DrawCommand::Text {
+ position,
+ font_size,
+ ..
+ } => position.y + *font_size,
+ // A segment may run in either direction; take the lower end.
+ DrawCommand::Underline { line, .. } | DrawCommand::Line { line, .. } => {
+ line.start.y.max(line.end.y)
+ }
+ DrawCommand::Image { rect, .. }
+ | DrawCommand::EmojiCluster { rect, .. }
+ | DrawCommand::Rect { rect, .. } => rect.origin.y + rect.size.height,
+ // `extent` is the shape's unrotated bounding box; a rotation can
+ // reach slightly past it, which is within this function's remit.
+ DrawCommand::Path { origin, extent, .. } => origin.y + extent.height,
+ // §17.3.1.19: draws nothing, so it consumes no vertical space.
+ DrawCommand::Outline(_) => continue,
+ // Annotations mark content that is already accounted for by the
+ // command underneath them, and a named destination is a point.
+ // Neither adds extent of its own.
+ DrawCommand::LinkAnnotation { .. }
+ | DrawCommand::InternalLink { .. }
+ | DrawCommand::NamedDestination { .. } => continue,
+ };
+ if bottom > max_y {
+ max_y = bottom;
+ }
+ }
+ max_y
+}
+
+/// Resolve and lay out a document without painting to PDF.
+/// Uses a real FontMgr for text measurement.
+pub fn resolve_and_layout(doc: Document) -> (ResolvedDocument, Vec<LayoutedPage>) {
+ let resolved = resolve::resolve(doc);
+ // A debug/test helper: it always loads the host's fonts, so the font-less
+ // case `build` guards against cannot arise on any host with fonts.
+ let registry = fonts::FontRegistry::build(&resolved.embedded_fonts, &resolved.font_families)
+ .expect("the host exposes at least one font face");
+ let pages = layout_document(&resolved, &registry);
+ (resolved, pages)
+}
+
+/// Lay out a resolved document using fontdb + skrifa font metrics resolved
+/// through the supplied [`fonts::FontRegistry`].
+pub fn layout_document(
+ resolved: &ResolvedDocument,
+ registry: &fonts::FontRegistry,
+) -> Vec<LayoutedPage> {
+ let measurer = layout::measurer::TextMeasurer::new(registry);
+ let ctx = BuildContext {
+ measurer: &measurer,
+ resolved,
+ };
+ let mut state = BuildState::default();
+ let dlh = default_line_height(&ctx);
+ let mut all_pages = Vec::new();
+ let mut last_config = PageConfig::default();
+ // Per-section metadata for deferred header/footer rendering.
+ // Carries the section's resolved slot sets, `<w:titlePg/>` flag,
+ // and logical page number of the section's first page (§17.6.12);
+ // the global `<w:evenAndOddHeaders/>` setting is read once below.
+ struct SectionHfInfo<'a> {
+ page_range: std::ops::Range<usize>,
+ config: PageConfig,
+ headers: &'a crate::render::resolve::header_footer::HeaderFooterSet<Vec<Block>>,
+ footers: &'a crate::render::resolve::header_footer::HeaderFooterSet<Vec<Block>>,
+ title_pg: bool,
+ logical_page_base: usize,
+ }
+ let mut section_hf: Vec<SectionHfInfo> = Vec::new();
+ // §17.6.12: logical PAGE numbering accumulates across sections,
+ // resetting wherever a section sets `pgNumType.start`. Document
+ // starts at logical 1 unless the first section overrides it.
+ let mut next_logical: usize = 1;
+
+ // §17.11.23: footnote separator indent from default paragraph style.
+ let separator_indent = resolved
+ .default_paragraph_style_id
+ .as_ref()
+ .and_then(|id| resolved.styles.get(id))
+ .and_then(|s| s.paragraph.indentation)
+ .and_then(|ind| ind.first_line)
+ .map(|fl| match fl {
+ crate::model::FirstLineIndent::FirstLine(v) => dimension::Pt::from(v),
+ _ => dimension::Pt::ZERO,
+ })
+ .unwrap_or(dimension::Pt::ZERO);
+
+ // §17.6.22: track continuation state for `Continuous` section breaks.
+ let mut pending_continuation: Option<layout::section::ContinuationState> = None;
+ let even_and_odd = resolved.even_and_odd_headers;
+
+ // Phase 1: layout all sections to determine total page count.
+ for (section_idx, section) in resolved.sections.iter().enumerate() {
+ let config = PageConfig::from_section(&section.properties);
+ state.page_config = config.clone();
+ let logical_page_base = layout::header_footer::next_logical_page_base(
+ next_logical,
+ section.properties.page_number_type.as_ref(),
+ );
+ let clearance = measure_header_footer_clearance(
+ &config,
+ section,
+ &ctx,
+ &mut state,
+ dlh,
+ even_and_odd,
+ logical_page_base,
+ );
+
+ let built = build_section_blocks(section, &config, &ctx, &mut state);
+ let measure_fn = |text: &str,
+ font: &layout::fragment::FontProps|
+ -> (dimension::Pt, layout::fragment::TextMetrics) {
+ measurer.measure(text, font)
+ };
+
+ // §17.6.22: continuous sections continue on the current page.
+ let continuation =
+ if section.properties.section_type == Some(crate::model::SectionType::Continuous) {
+ pending_continuation.take()
+ } else {
+ pending_continuation = None;
+ None
+ };
+
+ let mut pages = layout_section_with_clearance(
+ &built.blocks,
+ &config,
+ Some(&measure_fn),
+ separator_indent,
+ dlh,
+ layout::section::SectionStart {
+ continuation,
+ clearance: &clearance,
+ logical_page_base,
+ },
+ );
+
+ last_config = config.clone();
+
+ // Check if the NEXT section is continuous — if so, save the last page
+ // as continuation state instead of appending it.
+ // (Peek ahead by checking the section index.)
+ let next_is_continuous = resolved.sections.get(section_idx + 1).is_some_and(|next| {
+ next.properties.section_type == Some(crate::model::SectionType::Continuous)
+ });
+
+ if next_is_continuous && !pages.is_empty() {
+ let last_page = pages.pop().unwrap();
+ let cursor_y = estimate_cursor_y(&last_page, &last_config);
+ pending_continuation = Some(layout::section::ContinuationState {
+ page: last_page,
+ cursor_y,
+ });
+ }
+
+ let page_start = all_pages.len();
+ all_pages.append(&mut pages);
+ let pages_in_section = all_pages.len() - page_start;
+ next_logical = logical_page_base + pages_in_section;
+ section_hf.push(SectionHfInfo {
+ page_range: page_start..all_pages.len(),
+ config,
+ headers: &section.headers,
+ footers: &section.footers,
+ title_pg: section.properties.title_page.unwrap_or(false),
+ logical_page_base,
+ });
+ }
+
+ // §17.11.2: endnotes are document-scoped — built once, after every section,
+ // so a multi-section document doesn't repeat them per section.
+ let all_endnotes = build_document_endnotes(&ctx, &mut state);
+
+ // Phase 2: render headers/footers with correct NUMPAGES (total page count).
+ let total_pages = all_pages.len();
+ for info in &section_hf {
+ state.page_config = info.config.clone();
+ render_headers_footers(
+ &mut all_pages[info.page_range.clone()],
+ &info.config,
+ &HeaderFooterBlocks {
+ headers: info.headers,
+ footers: info.footers,
+ title_pg: info.title_pg,
+ even_and_odd,
+ },
+ &ctx,
+ &mut state,
+ dlh,
+ &PageRange {
+ page_base: info.page_range.start,
+ logical_page_base: info.logical_page_base,
+ total_pages,
+ },
+ );
+ }
+
+ // Render endnotes on a new page at the end of the document.
+ if !all_endnotes.is_empty() {
+ let measure_fn = |text: &str,
+ font: &layout::fragment::FontProps|
+ -> (dimension::Pt, layout::fragment::TextMetrics) {
+ measurer.measure(text, font)
+ };
+ let mut endnote_page = LayoutedPage::new(last_config.page_size);
+ let content_width = last_config.content_width();
+ let constraints =
+ layout::BoxConstraints::tight_width(content_width, dimension::Pt::INFINITY);
+ let mut cursor_y = last_config.margins.top;
+
+ // Separator line.
+ let sep_width = content_width * 0.33;
+ let sep_x = last_config.margins.left + separator_indent;
+ endnote_page
+ .commands
+ .push(layout::draw_command::DrawCommand::Line {
+ line: crate::render::geometry::PtLineSegment::new(
+ crate::render::geometry::PtOffset::new(sep_x, cursor_y),
+ crate::render::geometry::PtOffset::new(sep_x + sep_width, cursor_y),
+ ),
+ color: crate::render::resolve::color::RgbColor::BLACK,
+ width: dimension::Pt::new(0.5),
+ });
+ cursor_y += dimension::Pt::new(4.0);
+
+ for (_, frags, style) in &all_endnotes {
+ let para = layout::paragraph::layout_paragraph(
+ frags,
+ &constraints,
+ style,
+ dlh,
+ Some(&measure_fn),
+ );
+ for mut cmd in para.commands {
+ cmd.shift_y(cursor_y);
+ cmd.shift_x(last_config.margins.left);
+ endnote_page.commands.push(cmd);
+ }
+ cursor_y += para.size.height;
+ }
+ all_pages.push(endnote_page);
+ }
+
+ if all_pages.is_empty() {
+ all_pages.push(LayoutedPage::new(PageConfig::default().page_size));
+ }
+
+ all_pages
+}
+
+/// Measure each populated header/footer slot independently so pagination can
+/// reserve the slot selected for each physical page.
+fn measure_header_footer_clearance(
+ config: &PageConfig,
+ section: &crate::render::resolve::sections::ResolvedSection,
+ ctx: &layout::build::BuildContext,
+ state: &mut BuildState,
+ default_line_height: dimension::Pt,
+ even_and_odd: bool,
+ logical_page_base: usize,
+) -> HeaderFooterClearance {
+ let headers =
+ HeaderFooterSet {
+ default: section.headers.default.as_deref().map(|blocks| {
+ measure_header_bottom(blocks, config, ctx, state, default_line_height)
+ }),
+ first: section.headers.first.as_deref().map(|blocks| {
+ measure_header_bottom(blocks, config, ctx, state, default_line_height)
+ }),
+ even: section.headers.even.as_deref().map(|blocks| {
+ measure_header_bottom(blocks, config, ctx, state, default_line_height)
+ }),
+ };
+ let footers =
+ HeaderFooterSet {
+ default: section.footers.default.as_deref().map(|blocks| {
+ measure_footer_extent(blocks, config, ctx, state, default_line_height)
+ }),
+ first: section.footers.first.as_deref().map(|blocks| {
+ measure_footer_extent(blocks, config, ctx, state, default_line_height)
+ }),
+ even: section.footers.even.as_deref().map(|blocks| {
+ measure_footer_extent(blocks, config, ctx, state, default_line_height)
+ }),
+ };
+
+ HeaderFooterClearance::new(
+ config,
+ headers,
+ footers,
+ section.properties.title_page.unwrap_or(false),
+ even_and_odd,
+ logical_page_base,
+ )
+}
+
+fn measure_header_bottom(
+ blocks: &[crate::model::Block],
+ config: &PageConfig,
+ ctx: &layout::build::BuildContext,
+ state: &mut BuildState,
+ default_line_height: dimension::Pt,
+) -> dimension::Pt {
+ let hf = layout::build::build_header_footer_content(blocks, ctx, state);
+ // Height only — no float x is read here, so the parity is immaterial.
+ let result = layout::section::stack_blocks(
+ &hf.blocks,
+ config.content_width(),
+ default_line_height,
+ None,
+ layout::section::PageParity::Odd,
+ );
+ let blocks_bottom = config.header_margin + result.height;
+ let floats_bottom = hf
+ .floating_images
+ .iter()
+ .filter(|fi| fi.is_wrap_top_and_bottom())
+ .map(|fi| {
+ let y = match fi.y {
+ layout::section::FloatingImageY::Absolute(y) => y,
+ layout::section::FloatingImageY::RelativeToParagraph(off) => {
+ config.header_margin + off
+ }
+ };
+ y + fi.size.height
+ })
+ .fold(dimension::Pt::ZERO, |a, b| a.max(b));
+ blocks_bottom.max(floats_bottom)
+}
+
+fn measure_footer_extent(
+ blocks: &[crate::model::Block],
+ config: &PageConfig,
+ ctx: &layout::build::BuildContext,
+ state: &mut BuildState,
+ default_line_height: dimension::Pt,
+) -> dimension::Pt {
+ let hf = layout::build::build_header_footer_content(blocks, ctx, state);
+ // Height only — no float x is read here, so the parity is immaterial.
+ let result = layout::section::stack_blocks(
+ &hf.blocks,
+ config.content_width(),
+ default_line_height,
+ None,
+ layout::section::PageParity::Odd,
+ );
+ let blocks_extent = config.footer_margin + result.height;
+ let floats_extent = hf
+ .floating_images
+ .iter()
+ .filter(|fi| fi.is_wrap_top_and_bottom())
+ .map(|fi| match fi.y {
+ layout::section::FloatingImageY::Absolute(y) => config.page_size.height - y,
+ layout::section::FloatingImageY::RelativeToParagraph(off) => {
+ config.footer_margin + off + fi.size.height
+ }
+ })
+ .fold(dimension::Pt::ZERO, |a, b| a.max(b));
+ blocks_extent.max(floats_extent)
+}