A fast, helpful, and open-source document parser
wip
Logan Markewichba2a1962f90f
diff --git a/.github/workflows/release-crates.yml b/.github/workflows/release-crates.ymlindex 2e42439..e833374 100644--- a/.github/workflows/release-crates.yml+++ b/.github/workflows/release-crates.yml@@ -67,6 +67,10 @@ jobs:}publish_if_new liteparse-pdfium-syspublish_if_new liteparse-pdfium+ # Must precede liteparse: it is a path dependency of the `docx-native`+ # feature, and cargo refuses to publish a crate whose path deps are+ # unpublished — optional or not.+ publish_if_new liteparse-docxpublish_if_new liteparseenv:CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}diff --git a/Cargo.lock b/Cargo.lockindex 2887c22..8057bfb 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2024,6 +2024,7 @@ dependencies = ["file-format","flate2","image",+ "liteparse-docx","liteparse-pdfium","liteparse-pdfium-sys","lopdf",@@ -2046,6 +2047,22 @@ dependencies = ["web-time",]+[[package]]+name = "liteparse-docx"+version = "0.1.0"+dependencies = [+ "bitflags 2.13.1",+ "log",+ "quick-xml",+ "rustc-hash",+ "serde",+ "thiserror 2.0.19",+ "unicode-normalization",+ "unicode-properties",+ "unicode-segmentation",+ "zip",+]+[[package]]name = "liteparse-napi"version = "2.11.0"@@ -3113,6 +3130,16 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"+[[package]]+name = "quick-xml"+version = "0.39.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e"+dependencies = [+ "memchr",+ "serde",+]+[[package]]name = "quinn"version = "0.11.11"diff --git a/Cargo.toml b/Cargo.tomlindex 32b4e71..a221706 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,6 +4,7 @@ members = ["crates/pdfium-sys","crates/pdfium","crates/liteparse",+ "crates/liteparse-docx","crates/liteparse-napi","crates/liteparse-python","crates/liteparse-wasm",diff --git a/crates/liteparse-docx/ATTRIBUTION.md b/crates/liteparse-docx/ATTRIBUTION.mdnew file mode 100644index 0000000..a82ce66--- /dev/null+++ b/crates/liteparse-docx/ATTRIBUTION.md@@ -0,0 +1,89 @@+# Attribution++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).++## What was copied verbatim++```+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)+```++## 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.++## Fail-open parsing (the main deliberate divergence)++**Upstream fails closed at every level. We fail open.** A single malformed+value anywhere in a file must never cost the whole document — that is a+standing requirement of this copy, not a one-off fix. Three distinct classes,+all of which upstream treats as fatal:++| class | upstream | here |+|---|---|---|+| **unknown elements** (`commentReference`, …) | aborts document | `#[serde(other)]` catch-all, element skipped |+| **unknown attribute *values*** (`w:jc val="bogus"`) | aborts document | `lenient::` deserializers → unspecified |+| **malformed scalars** (colours, measurements, ids) | aborts document | dropped / spec default |++The mechanism lives in `docx/parse/primitives/lenient.rs`:++- `opt_attr` — `Option<T>` attribute → `None`. ECMA-376 §17.17 says an invalid+ value is treated as absent, and absent means *inherit from the style chain*,+ so this is both the spec-correct and the least-destructive degradation.+- `opt_val_attr` — same for `<w:x w:val="…"/>` elements; collapses the+ `ValAttr<T>` wrapper so the field is plain `Option<T>`.+- `or_default` — required attributes whose type has a *spec* default.+- `nonneg_or_default` — required non-negative measurements → zero, keeping the+ non-negativity guard.++Two rules that are easy to get wrong and were both hit during the port:++1. **Never invent a value to keep an infallible `From`.** Where the model has+ no "unspecified" variant (colours, adjust handles, gradient stops) the+ conversion was made fallible and callers drop the item. Substituting black+ or zero would be silent corruption.+2. **`AttrValueDeserializer` must coerce, not just visit strings.** serde's own+ string deserializer refuses to produce an integer, so routing numeric+ attributes through it would silently turn every *valid* `gridSpan`, `numId`,+ `ilvl` and `outlineLvl` into `None` — corrupting documents rather than+ merely being strict. Its unit tests guard exactly this.++Upstream tests that asserted the strict behaviour were rewritten to assert the+new contract *plus* the guarantee they originally protected (e.g. `"1.0"` is+dropped as a numbering id, but must still never be coerced to `1`).++### Verifying++```+cargo test -p liteparse-docx+cargo build -p liteparse-docx --example parse_probe+python3 bench/docx_native_spike/fuzz_attribute_values.py --mode all+```++The fuzz harness corrupts every attribute value in the `docx_files` corpus+(623k values) and requires all 48 documents to still parse.++Keeping this list current matters: it is what makes a future re-sync against a+newer dxpdf tractable.diff --git a/crates/liteparse-docx/Cargo.toml b/crates/liteparse-docx/Cargo.tomlnew file mode 100644index 0000000..1d3ec6e--- /dev/null+++ b/crates/liteparse-docx/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "liteparse-docx"+version = "0.1.0"+edition.workspace = true+license = "MIT"+repository.workspace = true+description = "Native DOCX structure reader (vendored Skia-free subset of dxpdf)"+publish = true++[dependencies]+bitflags = "2"+quick-xml = { version = "0.39", features = ["serialize"] }+serde = { version = "1", features = ["derive"] }+zip = { version = "2", default-features = false, features = ["deflate"] }+thiserror = "2"+log = "0.4"+rustc-hash = "2"+unicode-segmentation = "1.13"+unicode-properties = "0.1"+unicode-normalization = "0.1"diff --git a/crates/liteparse-docx/LICENSE b/crates/liteparse-docx/LICENSEnew file mode 100644index 0000000..6a65b8a--- /dev/null+++ b/crates/liteparse-docx/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 nerdy.pro++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/crates/liteparse-docx/examples/parse_probe.rs b/crates/liteparse-docx/examples/parse_probe.rsnew file mode 100644index 0000000..8b0e419--- /dev/null+++ b/crates/liteparse-docx/examples/parse_probe.rs@@ -0,0 +1,9 @@+fn main() {+ for path in std::env::args().skip(1) {+ let bytes = std::fs::read(&path).unwrap();+ match liteparse_docx::docx::parse(&bytes) {+ Ok(_) => println!("OK {path}"),+ Err(e) => println!("FAIL {path}: {e}"),+ }+ }+}diff --git a/crates/liteparse-docx/src/docx/error.rs b/crates/liteparse-docx/src/docx/error.rsnew file mode 100644index 0000000..a2b5a74--- /dev/null+++ b/crates/liteparse-docx/src/docx/error.rs@@ -0,0 +1,32 @@+use thiserror::Error;++/// All errors that can occur during DOCX parsing.+#[derive(Debug, Error)]+pub enum ParseError {+ #[error("failed to read ZIP archive: {0}")]+ Zip(#[from] zip::result::ZipError),++ #[error("failed to deserialize XML: {0}")]+ XmlDeserialize(#[from] quick_xml::DeError),++ #[error("invalid UTF-8 in XML content: {0}")]+ Utf8(#[from] std::str::Utf8Error),++ #[error("I/O error: {0}")]+ Io(#[from] std::io::Error),++ #[error("missing required part: {0}")]+ MissingPart(String),++ #[error("invalid attribute value '{value}' for '{attr}': {reason}")]+ InvalidAttributeValue {+ attr: String,+ value: String,+ reason: String,+ },++ #[error("invalid integer: {0}")]+ ParseInt(#[from] std::num::ParseIntError),+}++pub type Result<T> = std::result::Result<T, ParseError>;diff --git a/crates/liteparse-docx/src/docx/mod.rs b/crates/liteparse-docx/src/docx/mod.rsnew file mode 100644index 0000000..b848935--- /dev/null+++ b/crates/liteparse-docx/src/docx/mod.rs@@ -0,0 +1,32 @@+//! OOXML DOCX parser.+//!+//! Parses a `.docx` file (ZIP of XML) into a single, fully-resolved [`model::Document`]+//! struct. All style inheritance is resolved, all relationships are dereferenced,+//! and all types are ADTs — no unparsed strings, no invalid states.++pub mod dimension {+ pub use crate::model::dimension::*;+}+pub mod geometry {+ pub use crate::model::geometry::*;+}+pub mod model {+ pub use crate::model::*;+}++pub mod error;+pub mod parse;+pub mod relationships;+pub(crate) mod whitespace_workaround;+pub mod zip;++/// Parse a DOCX file from raw bytes into a fully resolved `Document`.+///+/// This is the main entry point. It:+/// 1. Extracts the ZIP archive+/// 2. Parses and resolves styles, numbering, theme, and settings+/// 3. Parses the document body, headers, footers, footnotes, and endnotes+/// 4. Assembles everything into a single `Document` struct+pub fn parse(data: &[u8]) -> error::Result<model::Document> {+ parse::parse(data)+}diff --git a/crates/liteparse-docx/src/docx/parse/body.rs b/crates/liteparse-docx/src/docx/parse/body.rsnew file mode 100644index 0000000..6b261f0--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/body.rs@@ -0,0 +1,853 @@+//! Parser for document body content: blocks (paragraphs, tables, section breaks)+//! and inline content (text runs, images, hyperlinks, fields, etc.).+//!+//! Single-pass serde over the full document. Drawings and VML picts are+//! serde-parsed inline via `DrawingXml` / `PictXml`; they produce their+//! model values (`Image` / `Pict`) during the `convert_container` walk via+//! the `ConvertCtx`.+//!+//! No style resolution or property merging — output is raw parsed data.++use crate::docx::error::Result;+use crate::docx::model::*;+use crate::docx::parse::body_schema::*;+use crate::docx::parse::serde_xml::from_xml;+use crate::docx::whitespace_workaround::restore_whitespace_sentinels;++/// Parse `w:document > w:body`, returning blocks and final section properties.+pub fn parse_body(data: &[u8]) -> Result<(Vec<Block>, SectionProperties)> {+ if data.is_empty() {+ return Ok((Vec::new(), SectionProperties::default()));+ }+ let doc: DocXml = from_xml(data)?;+ let mut ctx = ConvertCtx::new();+ let (blocks, final_section) = convert_container(doc.body.children, &mut ctx);+ Ok((blocks, final_section.unwrap_or_default()))+}++/// Parse a body-level XML part (header, footer, footnote body, etc.) into blocks.+pub fn parse_blocks(data: &[u8]) -> Result<Vec<Block>> {+ if data.is_empty() {+ return Ok(Vec::new());+ }+ let container: BlockContainerXml = from_xml(data)?;+ let mut ctx = ConvertCtx::new();+ let (blocks, _) = convert_container(container.children, &mut ctx);+ Ok(blocks)+}++// ── Top-level document schema wrapper ────────────────────────────────────++use serde::Deserialize;++/// Thin wrapper for `<w:document>` — just extracts `<w:body>`.+#[derive(Deserialize)]+struct DocXml {+ body: BlockContainerXml,+}++// ── Conversion ────────────────────────────────────────────────────────────++/// Conversion context. Previously carried a pre-pass iterator of parsed+/// drawings/picts; now empty, since drawings and picts are serde-parsed+/// inline. Kept as a type for future extensibility (e.g., if a later phase+/// needs cross-node state during conversion).+pub(crate) struct ConvertCtx {+ _private: (),+}++impl ConvertCtx {+ pub(crate) fn new() -> Self {+ Self { _private: () }+ }+}++/// Convert a list of block-level children into `(Vec<Block>, Option<SectionProperties>)`.+/// The section properties, if returned, are for a trailing `<w:sectPr>` at+/// this level — the final section for `<w:body>`, or one that appears inside+/// a table cell (§17.6.17).+pub(crate) fn convert_container(+ children: Vec<BlockChildXml>,+ ctx: &mut ConvertCtx,+) -> (Vec<Block>, Option<SectionProperties>) {+ let mut blocks = Vec::new();+ let mut final_section = None;+ for child in children {+ match child {+ BlockChildXml::Paragraph(p) => {+ let (para, sect_after) = convert_paragraph(*p, ctx);+ blocks.push(Block::Paragraph(Box::new(para)));+ if let Some(sp) = sect_after {+ blocks.push(Block::SectionBreak(Box::new(sp)));+ }+ }+ BlockChildXml::Table(t) => {+ blocks.push(Block::Table(Box::new(convert_table(*t, ctx))));+ }+ BlockChildXml::SectPr(sp) => {+ final_section = Some(SectionProperties::from(*sp));+ }+ BlockChildXml::Sdt(sdt) => {+ // Flatten SDT wrapper — treat its content as block-level.+ if let Some(content) = sdt.content {+ let (nested_blocks, nested_sect) = convert_container(content.children, ctx);+ blocks.extend(nested_blocks);+ if nested_sect.is_some() {+ final_section = nested_sect;+ }+ }+ }+ // Block-level markers and ignored elements — renderer doesn't use them.+ BlockChildXml::BookmarkStart(_)+ | BlockChildXml::BookmarkEnd(_)+ | BlockChildXml::CommentRangeStart(_)+ | BlockChildXml::CommentRangeEnd(_)+ | BlockChildXml::ProofErr(_)+ | BlockChildXml::Other => {}+ }+ }+ (blocks, final_section)+}++fn convert_paragraph(p: ParaXml, ctx: &mut ConvertCtx) -> (Paragraph, Option<SectionProperties>) {+ let rsids = ParagraphRevisionIds {+ r: hex_rsid(p.rsid_r.as_deref()),+ r_default: hex_rsid(p.rsid_r_default.as_deref()),+ p: hex_rsid(p.rsid_p.as_deref()),+ r_pr: hex_rsid(p.rsid_r_pr.as_deref()),+ del: hex_rsid(p.rsid_del.as_deref()),+ };++ // pPr may appear as either the dedicated field OR inside $value (serde+ // collects all matching children; since `pPr` is named on the struct+ // *and* in the enum, serde prefers the dedicated field — but just in+ // case, we merge from both sources).+ let p_pr = p.p_pr.or_else(|| {+ p.content.iter().find_map(|c| {+ if let ParaChildXml::PPr(pp) = c {+ Some((**pp).clone())+ } else {+ None+ }+ })+ });++ let parsed_p_pr = p_pr.map(|pp| pp.split());+ let (style_id, properties, mark_run_properties, section_properties) = match parsed_p_pr {+ Some(pp) => (+ pp.style_id,+ pp.properties,+ pp.run_properties,+ pp.section_properties,+ ),+ None => (None, ParagraphProperties::default(), None, None),+ };++ let content = convert_para_children(p.content, ctx);++ (+ Paragraph {+ style_id,+ properties,+ mark_run_properties,+ content,+ rsids,+ },+ section_properties,+ )+}++/// Flatten a `RunXml`'s children into zero-or-more `Inline`s and append to+/// the parent content. Text / tab / br / cr / lastRenderedPageBreak are+/// accumulated into one `Inline::TextRun`; sibling inlines flush the accumulator+/// and append independently.+fn extend_from_run(r: RunXml, out: &mut Vec<Inline>, ctx: &mut ConvertCtx) {+ let rsids = RevisionIds {+ r: hex_rsid(r.rsid_r.as_deref()),+ r_pr: hex_rsid(r.rsid_r_pr.as_deref()),+ del: hex_rsid(r.rsid_del.as_deref()),+ };+ let (props, style_id) = r.r_pr.map(|rp| rp.split()).unwrap_or_default();++ let mut acc: Vec<RunElement> = Vec::new();+ let flush = |acc: &mut Vec<RunElement>, out: &mut Vec<Inline>| {+ if !acc.is_empty() {+ out.push(Inline::TextRun(Box::new(TextRun {+ style_id: style_id.clone(),+ properties: props.clone(),+ content: std::mem::take(acc),+ rsids,+ })));+ }+ };++ for child in r.content {+ match child {+ // Unmodelled run-level element (e.g. commentReference) — skipped.+ RunChildXml::Other => {}+ RunChildXml::Text(t) => {+ acc.push(RunElement::Text(restore_whitespace_sentinels(&t.content)))+ }+ RunChildXml::DelText(t) => {+ acc.push(RunElement::Text(restore_whitespace_sentinels(&t.content)))+ }+ RunChildXml::Tab => acc.push(RunElement::Tab),+ RunChildXml::PTab(p) => acc.push(RunElement::PositionTab(p.into())),+ RunChildXml::Br(br) => acc.push(run_break(br)),+ RunChildXml::Cr => acc.push(RunElement::LineBreak(BreakKind::TextWrapping)),+ RunChildXml::SoftHyphen => {} // optional hyphen — only visible if line breaks here; we don't hyphenate+ RunChildXml::NoBreakHyphen => acc.push(RunElement::Text("\u{2011}".to_string())),+ RunChildXml::LastRenderedPageBreak => acc.push(RunElement::LastRenderedPageBreak),+ RunChildXml::Drawing(d) => {+ flush(&mut acc, out);+ if let Some(img) = drawing_to_image(d, ctx) {+ out.push(Inline::Image(Box::new(img)));+ }+ }+ RunChildXml::Pict(p) => {+ flush(&mut acc, out);+ out.push(Inline::Pict(p.into_model(ctx)));+ }+ RunChildXml::Sym(s) => {+ flush(&mut acc, out);+ let char_code = u16::from_str_radix(&s.char, 16).unwrap_or_else(|_| {+ log::warn!("sym: invalid hex char code {:?}; using 0", s.char);+ 0+ });+ out.push(Inline::Symbol(Symbol {+ font: s.font,+ char_code,+ }));+ }+ RunChildXml::InstrText(t) => {+ flush(&mut acc, out);+ out.push(Inline::InstrText(restore_whitespace_sentinels(&t.content)));+ }+ RunChildXml::FldChar(fc) => {+ // An unrecognized fldCharType carries no usable meaning (it+ // delimits begin/separate/end), so drop the marker entirely.+ let Some(ty) = fc.fld_char_type else { continue };+ flush(&mut acc, out);+ out.push(Inline::FieldChar(FieldChar {+ field_char_type: FieldCharType::from(ty),+ dirty: fc.dirty.map(|b| b.0),+ fld_lock: fc.fld_lock.map(|b| b.0),+ }));+ }+ RunChildXml::FootnoteRef(n) => {+ // A reference with no usable id resolves to no note.+ let Some(id) = n.id else { continue };+ flush(&mut acc, out);+ out.push(Inline::FootnoteRef(NoteId::new(id)));+ }+ RunChildXml::EndnoteRef(n) => {+ let Some(id) = n.id else { continue };+ flush(&mut acc, out);+ out.push(Inline::EndnoteRef(NoteId::new(id)));+ }+ RunChildXml::FootnoteRefMark => {+ flush(&mut acc, out);+ out.push(Inline::FootnoteRefMark);+ }+ RunChildXml::EndnoteRefMark => {+ flush(&mut acc, out);+ out.push(Inline::EndnoteRefMark);+ }+ RunChildXml::Separator => {+ flush(&mut acc, out);+ out.push(Inline::Separator);+ }+ RunChildXml::ContinuationSeparator => {+ flush(&mut acc, out);+ out.push(Inline::ContinuationSeparator);+ }+ RunChildXml::AlternateContent(ac) => {+ flush(&mut acc, out);+ out.push(Inline::AlternateContent(convert_alt_content(ac, ctx)));+ }+ RunChildXml::RPr(_) => {} // already captured via r.r_pr+ }+ }+ flush(&mut acc, out);+}++fn run_break(br: BrXml) -> RunElement {+ use crate::docx::parse::body_schema::StBrType;+ match br.ty {+ Some(StBrType::Page) => RunElement::PageBreak,+ Some(StBrType::Column) => RunElement::ColumnBreak,+ _ => {+ let clear = br.clear.map(BreakClear::from).unwrap_or(BreakClear::None);+ if clear != BreakClear::None {+ RunElement::LineBreak(BreakKind::Clear(clear))+ } else {+ RunElement::LineBreak(BreakKind::TextWrapping)+ }+ }+ }+}++/// Convert a sequence of paragraph-level children (`EG_PContent`) into inline+/// content. Shared by `<w:p>`, `<w:hyperlink>`, and `<w:fldSimple>`, and used+/// recursively to flatten revision/structural wrappers.+///+/// Revision handling is the "accept all changes" (final) view: insert-side+/// wrappers (`<w:ins>`, `<w:moveTo>`) and structural wrappers (`<w:smartTag>`,+/// `<w:customXml>`) are flattened in place and rendered; delete-side wrappers+/// (`<w:del>`, `<w:moveFrom>`) are dropped along with their content. Nested+/// wrappers re-apply the same rules — e.g. a `<w:del>` inside a `<w:ins>` is+/// still dropped.+fn convert_para_children(children: Vec<ParaChildXml>, ctx: &mut ConvertCtx) -> Vec<Inline> {+ let mut content = Vec::new();+ append_para_children(children, &mut content, ctx);+ content+}++fn append_para_children(+ children: Vec<ParaChildXml>,+ content: &mut Vec<Inline>,+ ctx: &mut ConvertCtx,+) {+ for child in children {+ match child {+ ParaChildXml::Run(r) => extend_from_run(r, content, ctx),+ ParaChildXml::Hyperlink(h) => {+ content.push(Inline::Hyperlink(convert_hyperlink(h, ctx)));+ }+ ParaChildXml::FldSimple(f) => {+ content.push(Inline::Field(convert_fld_simple(f, ctx)));+ }+ ParaChildXml::BookmarkStart(b) => content.push(Inline::BookmarkStart {+ id: BookmarkId::new(b.id),+ name: b.name,+ }),+ ParaChildXml::BookmarkEnd(b) => {+ content.push(Inline::BookmarkEnd(BookmarkId::new(b.id)));+ }+ // Insert-side revision + structural wrappers: flatten and render.+ ParaChildXml::Ins(w)+ | ParaChildXml::MoveTo(w)+ | ParaChildXml::SmartTag(w)+ | ParaChildXml::CustomXml(w) => append_para_children(w.content, content, ctx),+ // Delete-side revision wrappers: content is deleted — drop it.+ ParaChildXml::Del(_) | ParaChildXml::MoveFrom(_) => {}+ ParaChildXml::PPr(_) => {} // already captured on the parent+ ParaChildXml::Other => {}+ }+ }+}++fn convert_hyperlink(h: HyperlinkXml, ctx: &mut ConvertCtx) -> Hyperlink {+ let target = if let Some(id) = h.r_id {+ HyperlinkTarget::ExternalRel(RelId::new(id))+ } else {+ HyperlinkTarget::Internal {+ anchor: h.anchor.unwrap_or_default(),+ }+ };+ let content = convert_para_children(h.content, ctx);+ Hyperlink { target, content }+}++fn convert_fld_simple(f: FldSimpleXml, ctx: &mut ConvertCtx) -> Field {+ let instruction = match crate::field::parse(&f.instr) {+ Ok(i) => i,+ Err(e) => {+ log::warn!("failed to parse field instruction {:?}: {}", f.instr, e);+ crate::field::FieldInstruction::Unknown {+ field_type: String::new(),+ raw: f.instr.clone(),+ }+ }+ };+ let content = convert_para_children(f.content, ctx);+ Field {+ instruction,+ content,+ }+}++fn convert_alt_content(a: AltContentXml, ctx: &mut ConvertCtx) -> AlternateContent {+ let choices = a+ .choices+ .into_iter()+ .filter_map(|c| {+ // §M.2.2: @Requires is a space-separated list of namespace prefixes;+ // the choice is usable only if we understand *all* of them. A single+ // unknown token drops the whole choice (falling through to the next+ // choice or the fallback).+ let requires: Vec<McRequires> = c+ .requires+ .split_whitespace()+ .map(mc_requires)+ .collect::<Option<_>>()?;+ let content = convert_mc_content(c.content, ctx);+ Some(McChoice { requires, content })+ })+ .collect();+ let fallback = a.fallback.map(|f| convert_mc_content(f.content, ctx));+ AlternateContent { choices, fallback }+}++fn mc_requires(s: &str) -> Option<McRequires> {+ match s {+ "wps" => Some(McRequires::Wps),+ "wpg" => Some(McRequires::Wpg),+ "wpc" => Some(McRequires::Wpc),+ "wpi" => Some(McRequires::Wpi),+ "m" => Some(McRequires::Math),+ "a14" => Some(McRequires::A14),+ "w14" => Some(McRequires::W14),+ "w15" => Some(McRequires::W15),+ "w16" => Some(McRequires::W16),+ other => {+ log::warn!("mc:Choice: unsupported Requires {:?}", other);+ None+ }+ }+}++fn convert_mc_content(items: Vec<McContentXml>, ctx: &mut ConvertCtx) -> Vec<Inline> {+ let mut out = Vec::new();+ for i in items {+ match i {+ McContentXml::Other => {}+ McContentXml::Drawing(d) => {+ if let Some(img) = drawing_to_image(d, ctx) {+ out.push(Inline::Image(Box::new(img)));+ }+ }+ McContentXml::Pict(p) => {+ out.push(Inline::Pict(p.into_model(ctx)));+ }+ }+ }+ out+}++/// Convert a serde-parsed `<w:drawing>` into the model's `Image`. Returns+/// `None` when neither `<wp:inline>` nor `<wp:anchor>` is present.+fn drawing_to_image(+ d: crate::docx::parse::body_schema::DrawingXml,+ ctx: &mut ConvertCtx,+) -> Option<Image> {+ if let Some(inline) = d.inline {+ return Some(inline.into_image(ctx));+ }+ d.anchor.map(|a| a.into_image(ctx))+}++fn convert_table(t: TableXml, ctx: &mut ConvertCtx) -> Table {+ let (properties, _style_id) = t.tbl_pr.map(|tp| tp.split()).unwrap_or_default();+ let grid = t+ .tbl_grid+ .map(|g| {+ g.cols+ .into_iter()+ .map(|c| GridColumn {+ width: c.w.unwrap_or_default(),+ })+ .collect()+ })+ .unwrap_or_default();+ let rows = collect_table_rows(t.children)+ .into_iter()+ .map(|r| convert_table_row(r, ctx))+ .collect();+ Table {+ properties,+ grid,+ rows,+ }+}++/// Walk `<w:tbl>`'s direct children and flatten out every `<w:tr>`,+/// recursing through revision-tracking, custom-XML, and SDT row wrappers.+/// Range markers, proofreading errors, permission ranges, and the+/// `tblPr`/`tblGrid` duplicates produced by `$value` are dropped — they+/// have no rendered effect at table level. Document order is preserved.+fn collect_table_rows(children: Vec<TableChildXml>) -> Vec<TableRowXml> {+ let mut rows = Vec::with_capacity(children.len());+ for child in children {+ match child {+ TableChildXml::Row(r) => rows.push(*r),+ TableChildXml::Sdt(s) => {+ if let Some(content) = s.content {+ rows.extend(collect_table_rows(content.children));+ }+ }+ TableChildXml::Ins(rt)+ | TableChildXml::Del(rt)+ | TableChildXml::MoveFrom(rt)+ | TableChildXml::MoveTo(rt) => rows.extend(rt.rows),+ TableChildXml::CustomXml(cx) => {+ rows.extend(collect_table_rows(cx.children));+ }+ TableChildXml::BookmarkStart(_)+ | TableChildXml::BookmarkEnd(_)+ | TableChildXml::CommentRangeStart(_)+ | TableChildXml::CommentRangeEnd(_)+ | TableChildXml::ProofErr(_)+ | TableChildXml::PermStart(_)+ | TableChildXml::PermEnd(_)+ | TableChildXml::TblPr(_)+ | TableChildXml::TblGrid(_)+ | TableChildXml::Other => {}+ }+ }+ rows+}++fn convert_table_row(r: TableRowXml, ctx: &mut ConvertCtx) -> TableRow {+ let rsids = TableRowRevisionIds {+ r: hex_rsid(r.rsid_r.as_deref()),+ r_pr: hex_rsid(r.rsid_r_pr.as_deref()),+ del: hex_rsid(r.rsid_del.as_deref()),+ tr: hex_rsid(r.rsid_tr.as_deref()),+ };+ let properties = r.tr_pr.map(TableRowProperties::from).unwrap_or_default();+ let property_exceptions = r.tbl_pr_ex.map(Into::into);+ let cells = collect_row_cells(r.children)+ .into_iter()+ .map(|c| convert_table_cell(c, ctx))+ .collect();+ TableRow {+ properties,+ cells,+ rsids,+ property_exceptions,+ }+}++/// Walk a `<w:tr>`'s direct children and flatten out every `<w:tc>`,+/// recursing through cell-level SDT (`<w:sdt>`) and custom-XML wrappers.+/// Range markers, proofreading errors, permission ranges, and the+/// `tblPrEx`/`trPr` duplicates produced by `$value` are dropped — they have+/// no rendered effect at cell level. Document order is preserved. Mirrors+/// `collect_table_rows` one level down.+fn collect_row_cells(children: Vec<RowChildXml>) -> Vec<TableCellXml> {+ let mut cells = Vec::with_capacity(children.len());+ for child in children {+ match child {+ RowChildXml::Cell(c) => cells.push(*c),+ RowChildXml::Sdt(s) => {+ if let Some(content) = s.content {+ cells.extend(collect_row_cells(content.children));+ }+ }+ RowChildXml::CustomXml(cx) => {+ cells.extend(collect_row_cells(cx.children));+ }+ RowChildXml::BookmarkStart(_)+ | RowChildXml::BookmarkEnd(_)+ | RowChildXml::CommentRangeStart(_)+ | RowChildXml::CommentRangeEnd(_)+ | RowChildXml::ProofErr(_)+ | RowChildXml::PermStart(_)+ | RowChildXml::PermEnd(_)+ | RowChildXml::TblPrEx(_)+ | RowChildXml::TrPr(_)+ | RowChildXml::Other => {}+ }+ }+ cells+}++fn convert_table_cell(c: TableCellXml, ctx: &mut ConvertCtx) -> TableCell {+ let properties = c.tc_pr.map(TableCellProperties::from).unwrap_or_default();+ let (content, _final_sect) = convert_container(c.content, ctx);+ TableCell {+ properties,+ content,+ }+}++// ── helpers ──────────────────────────────────────────────────────────────++fn hex_rsid(s: Option<&str>) -> Option<RevisionSaveId> {+ s.and_then(RevisionSaveId::from_hex)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Collect all rendered text from a converted inline sequence, recursing+ /// into hyperlinks and fields.+ fn collect_text(inlines: &[Inline]) -> String {+ let mut s = String::new();+ for inl in inlines {+ match inl {+ Inline::TextRun(r) => {+ for el in &r.content {+ if let RunElement::Text(t) = el {+ s.push_str(t);+ }+ }+ }+ Inline::Hyperlink(h) => s.push_str(&collect_text(&h.content)),+ Inline::Field(f) => s.push_str(&collect_text(&f.content)),+ _ => {}+ }+ }+ s+ }++ /// Parse a `<w:p>` and return the concatenated rendered text.+ fn para_text(xml: &str) -> String {+ let p: ParaXml = quick_xml::de::from_str(xml).unwrap();+ let mut ctx = ConvertCtx::new();+ let (para, _) = convert_paragraph(p, &mut ctx);+ collect_text(¶.content)+ }++ /// Parse a `<w:p>` and return the run-elements of its first `TextRun`.+ fn first_run_elements(xml: &str) -> Vec<RunElement> {+ let p: ParaXml = quick_xml::de::from_str(xml).unwrap();+ let mut ctx = ConvertCtx::new();+ let (para, _) = convert_paragraph(p, &mut ctx);+ para.content+ .into_iter()+ .find_map(|i| match i {+ Inline::TextRun(r) => Some(r.content),+ _ => None,+ })+ .unwrap_or_default()+ }++ // ── Revision & structural wrappers (accept-all-changes / final view) ──++ #[test]+ fn ins_content_is_rendered() {+ // Tracked insertions are part of the final document — their runs must+ // survive (previously `<w:ins>` hit the `Other` catch-all and vanished).+ assert_eq!(+ para_text(r#"<w:p xmlns:w="x"><w:ins><w:r><w:t>kept</w:t></w:r></w:ins></w:p>"#),+ "kept"+ );+ }++ #[test]+ fn del_content_is_dropped() {+ // Tracked deletions are not in the final document — drop them.+ assert_eq!(+ para_text(+ r#"<w:p xmlns:w="x"><w:del><w:r><w:delText>gone</w:delText></w:r></w:del></w:p>"#+ ),+ ""+ );+ }++ #[test]+ fn del_nested_in_ins_is_still_dropped() {+ // Nested wrappers re-apply the rules: text inserted then deleted is+ // deleted; the surrounding insertion is kept.+ assert_eq!(+ para_text(+ r#"<w:p xmlns:w="x"><w:ins>+ <w:r><w:t>A</w:t></w:r>+ <w:del><w:r><w:delText>B</w:delText></w:r></w:del>+ <w:r><w:t>C</w:t></w:r>+ </w:ins></w:p>"#+ ),+ "AC"+ );+ }++ #[test]+ fn move_to_rendered_move_from_dropped() {+ assert_eq!(+ para_text(r#"<w:p xmlns:w="x"><w:moveTo><w:r><w:t>here</w:t></w:r></w:moveTo></w:p>"#),+ "here"+ );+ assert_eq!(+ para_text(+ r#"<w:p xmlns:w="x"><w:moveFrom><w:r><w:t>away</w:t></w:r></w:moveFrom></w:p>"#+ ),+ ""+ );+ }++ #[test]+ fn smart_tag_and_inline_custom_xml_are_flattened() {+ assert_eq!(+ para_text(+ r#"<w:p xmlns:w="x"><w:smartTag><w:r><w:t>date</w:t></w:r></w:smartTag></w:p>"#+ ),+ "date"+ );+ assert_eq!(+ para_text(+ r#"<w:p xmlns:w="x"><w:customXml><w:r><w:t>tagged</w:t></w:r></w:customXml></w:p>"#+ ),+ "tagged"+ );+ }++ #[test]+ fn ins_wrapping_a_hyperlink_keeps_the_link_text() {+ assert_eq!(+ para_text(+ r#"<w:p xmlns:w="x"><w:ins>+ <w:hyperlink w:anchor="a"><w:r><w:t>link</w:t></w:r></w:hyperlink>+ </w:ins></w:p>"#+ ),+ "link"+ );+ }++ // ── run_break ────────────────────────────────────────────────────────++ #[test]+ fn br_type_page_and_column() {+ assert!(matches!(+ first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br type="page"/></w:r></w:p>"#)+ .as_slice(),+ [RunElement::PageBreak]+ ));+ assert!(matches!(+ first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br type="column"/></w:r></w:p>"#)+ .as_slice(),+ [RunElement::ColumnBreak]+ ));+ }++ #[test]+ fn br_plain_is_text_wrapping_line_break() {+ assert!(matches!(+ first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br/></w:r></w:p>"#).as_slice(),+ [RunElement::LineBreak(BreakKind::TextWrapping)]+ ));+ }++ #[test]+ fn br_clear_all_is_clearing_line_break() {+ assert!(matches!(+ first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br clear="all"/></w:r></w:p>"#)+ .as_slice(),+ [RunElement::LineBreak(BreakKind::Clear(BreakClear::All))]+ ));+ }++ // ── mc:Choice Requires ───────────────────────────────────────────────++ #[test]+ fn mc_requires_known_and_unknown() {+ assert_eq!(mc_requires("wps"), Some(McRequires::Wps));+ assert_eq!(mc_requires("w14"), Some(McRequires::W14));+ // Unknown / unsupported token → None (choice is dropped, fallback used).+ assert_eq!(mc_requires("nope"), None);+ // `mc_requires` maps a *single* token; a space-separated list is split by+ // `convert_alt_content` (see `alt_content_requires_*` below), so a raw+ // multi-token string is not a valid single token.+ assert_eq!(mc_requires("wps w14"), None);+ }++ #[test]+ fn alt_content_multi_token_requires_is_kept_when_all_known() {+ // §M.2.2: a space-separated Requires with every token understood keeps+ // the choice (previously the whole choice was dropped).+ let xml = r#"<w:r xmlns:w="x" xmlns:mc="m">+ <mc:AlternateContent>+ <mc:Choice Requires="wps w14"><w:drawing/></mc:Choice>+ <mc:Fallback/>+ </mc:AlternateContent>+ </w:r>"#;+ let r: RunXml = quick_xml::de::from_str(xml).unwrap();+ let mut out = Vec::new();+ let mut ctx = ConvertCtx::new();+ extend_from_run(r, &mut out, &mut ctx);+ let Some(Inline::AlternateContent(ac)) = out.into_iter().next() else {+ panic!("expected AlternateContent");+ };+ assert_eq!(ac.choices.len(), 1, "multi-token choice kept");+ assert_eq!(+ ac.choices[0].requires,+ vec![McRequires::Wps, McRequires::W14]+ );+ }++ #[test]+ fn alt_content_choice_with_unknown_token_is_dropped() {+ let xml = r#"<w:r xmlns:w="x" xmlns:mc="m">+ <mc:AlternateContent>+ <mc:Choice Requires="wps nope"><w:drawing/></mc:Choice>+ <mc:Fallback/>+ </mc:AlternateContent>+ </w:r>"#;+ let r: RunXml = quick_xml::de::from_str(xml).unwrap();+ let mut out = Vec::new();+ let mut ctx = ConvertCtx::new();+ extend_from_run(r, &mut out, &mut ctx);+ let Some(Inline::AlternateContent(ac)) = out.into_iter().next() else {+ panic!("expected AlternateContent");+ };+ assert!(+ ac.choices.is_empty(),+ "choice with an unknown token dropped"+ );+ }++ /// Regression: a `<w:tr>` whose `<w:tc>` cells are interleaved with+ /// cell-level `<w:sdt>` (CT_SdtCell) wrappers must (a) parse — the old+ /// `Vec<TableCellXml>` field reported a duplicate `tc` when cells were+ /// non-contiguous — and (b) recover every cell, including the ones nested+ /// inside `<w:sdtContent>`.+ #[test]+ fn row_with_interspersed_sdt_cells_recovers_all_cells() {+ let xml = r#"+ <w:tr xmlns:w="x">+ <w:trPr/>+ <w:tc><w:p/></w:tc>+ <w:tc><w:p/></w:tc>+ <w:sdt>+ <w:sdtPr/>+ <w:sdtContent><w:tc><w:p/></w:tc></w:sdtContent>+ </w:sdt>+ <w:sdt>+ <w:sdtContent><w:tc><w:p/></w:tc></w:sdtContent>+ </w:sdt>+ <w:tc><w:p/></w:tc>+ </w:tr>+ "#;+ let row: TableRowXml = quick_xml::de::from_str(xml).expect("row must parse");+ assert!(row.tr_pr.is_some(), "trPr still captured on the parent");+ let cells = collect_row_cells(row.children);+ assert_eq!(cells.len(), 5, "3 bare + 2 sdt-wrapped cells recovered");+ }++ /// Nested `<w:customXml>` cell wrapper (CT_CustomXmlCell) also flattens.+ #[test]+ fn row_with_custom_xml_cell_wrapper_recovers_cells() {+ let xml = r#"+ <w:tr xmlns:w="x">+ <w:tc><w:p/></w:tc>+ <w:customXml>+ <w:tc><w:p/></w:tc>+ <w:tc><w:p/></w:tc>+ </w:customXml>+ </w:tr>+ "#;+ let row: TableRowXml = quick_xml::de::from_str(xml).expect("row must parse");+ assert_eq!(collect_row_cells(row.children).len(), 3);+ }++ /// A `<w:customXml>` row wrapper (CT_CustomXmlRow) inside `<w:tbl>` must+ /// have its nested `<w:tr>` rows recovered — the element is `customXml`,+ /// not `customXmlIns`/etc., so the wrong rename previously dropped them.+ #[test]+ fn table_with_custom_xml_row_wrapper_recovers_rows() {+ let xml = r#"+ <w:tbl xmlns:w="x">+ <w:tblPr/>+ <w:tblGrid><w:gridCol w:w="100"/></w:tblGrid>+ <w:tr><w:tc><w:p/></w:tc></w:tr>+ <w:customXml>+ <w:tr><w:tc><w:p/></w:tc></w:tr>+ </w:customXml>+ </w:tbl>+ "#;+ let tbl: TableXml = quick_xml::de::from_str(xml).expect("table must parse");+ assert_eq!(collect_table_rows(tbl.children).len(), 2);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/body_schema.rs b/crates/liteparse-docx/src/docx/parse/body_schema.rsnew file mode 100644index 0000000..742b750--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/body_schema.rs@@ -0,0 +1,740 @@+//! Serde schema for `<w:body>` / `<w:hdr>` / `<w:ftr>` / `<w:footnote>` contents.+//!+//! The body grammar is mixed-content: paragraphs contain runs, hyperlinks,+//! fields, and bookmarks in arbitrary order; runs themselves contain text,+//! tabs, breaks, drawings, pictures, and field characters in arbitrary order.+//! We use `#[serde(rename = "$value")]` + untagged enums to preserve order,+//! then flatten to the model's `Vec<Inline>` in `From` impls.+//!+//! `<w:drawing>` and `<w:pict>` sub-trees are handed to the legacy DrawingML+//! and VML parsers via a two-pass approach (see `parse/body.rs`); the schema+//! treats them as placeholders and the merge step fills them in.+//!+//! Serde deserializes into many fields that are only read during the+//! `From`-style conversion in `body.rs`; the `allow(dead_code)` silences+//! the spurious warnings.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::dimension::{Dimension, Twips};+use crate::docx::parse::primitives::st_enums::{+ StBrClear, StFldCharType, StPTabAlignment, StPTabLeader, StPTabRelativeTo,+};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;+use crate::docx::parse::properties::schema::paragraph::PPrXml;+use crate::docx::parse::properties::schema::run::RPrXml;+use crate::docx::parse::properties::schema::section::SectPrXml;+use crate::docx::parse::properties::schema::table::{TblPrExXml, TblPrXml, TcPrXml, TrPrXml};++// ── root-level ─────────────────────────────────────────────────────────────++/// Top-level container (body / header / footer / footnote / endnote body).+#[derive(Deserialize, Default)]+pub(crate) struct BlockContainerXml {+ #[serde(rename = "$value", default)]+ pub children: Vec<BlockChildXml>,+}++/// Union of direct children of a body-level container. Most variants beyond+/// paragraph/table/sectPr are structural elements (bookmarks, comment range+/// markers, proofing errors, SDT wrappers) that OOXML allows at block level+/// but the renderer discards. We model them so serde can skip them cleanly.+#[derive(Deserialize)]+pub(crate) enum BlockChildXml {+ #[serde(rename = "p")]+ Paragraph(Box<ParaXml>),+ #[serde(rename = "tbl")]+ Table(Box<TableXml>),+ #[serde(rename = "sectPr")]+ SectPr(Box<SectPrXml>),+ /// Block-level bookmark start (spans multiple blocks).+ #[serde(rename = "bookmarkStart")]+ BookmarkStart(BookmarkStartXml),+ #[serde(rename = "bookmarkEnd")]+ BookmarkEnd(BookmarkEndXml),+ /// Comment range markers — ignored.+ #[serde(rename = "commentRangeStart")]+ CommentRangeStart(BookmarkEndXml),+ #[serde(rename = "commentRangeEnd")]+ CommentRangeEnd(BookmarkEndXml),+ /// Proofing error markers — ignored.+ #[serde(rename = "proofErr")]+ ProofErr(IgnoredXml),+ /// Structured document tag wrappers — contents are treated as blocks.+ #[serde(rename = "sdt")]+ Sdt(Box<SdtBlockXml>),+ /// Catch-all for other OOXML elements we don't yet model.+ #[serde(other)]+ Other,+}++/// Placeholder type for elements we accept but don't process.+#[derive(Deserialize, Default)]+pub(crate) struct IgnoredXml {}++/// `<w:sdt>` block-level structured document tag — extract the content+/// from `<w:sdtContent>` and treat it as block-level children.+#[derive(Deserialize, Default)]+pub(crate) struct SdtBlockXml {+ #[serde(rename = "sdtContent", default)]+ pub content: Option<SdtBlockContentXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct SdtBlockContentXml {+ #[serde(rename = "$value", default)]+ pub children: Vec<BlockChildXml>,+}++// ── paragraph ──────────────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+pub(crate) struct ParaXml {+ #[serde(rename = "@rsidR", default)]+ pub rsid_r: Option<String>,+ #[serde(rename = "@rsidRDefault", default)]+ pub rsid_r_default: Option<String>,+ #[serde(rename = "@rsidP", default)]+ pub rsid_p: Option<String>,+ #[serde(rename = "@rsidRPr", default)]+ pub rsid_r_pr: Option<String>,+ #[serde(rename = "@rsidDel", default)]+ pub rsid_del: Option<String>,++ #[serde(rename = "pPr", default)]+ pub p_pr: Option<PPrXml>,+ #[serde(rename = "$value", default)]+ pub content: Vec<ParaChildXml>,+}++/// Children of `<w:p>` excluding `<w:pPr>` (which is captured separately).+/// This is `EG_PContent` — also the content model of `<w:hyperlink>`,+/// `<w:fldSimple>`, and the revision/structural wrappers below.+///+/// OOXML wraps run content in revision-tracking (`ins`/`del`/`moveFrom`/+/// `moveTo`) and structural (`smartTag`/`customXml`) elements. These are+/// modelled so `convert_para_children` can flatten them: insert-side and+/// structural wrappers are rendered, delete-side wrappers are dropped (an+/// "accept all changes" / final view). Remaining annotation elements+/// (proofErr, permStart/End, commentRange*, sdt, ...) hit the `Other`+/// catch-all and are discarded cleanly.+#[derive(Deserialize)]+pub(crate) enum ParaChildXml {+ #[serde(rename = "r")]+ Run(RunXml),+ #[serde(rename = "hyperlink")]+ Hyperlink(HyperlinkXml),+ #[serde(rename = "fldSimple")]+ FldSimple(FldSimpleXml),+ #[serde(rename = "bookmarkStart")]+ BookmarkStart(BookmarkStartXml),+ #[serde(rename = "bookmarkEnd")]+ BookmarkEnd(BookmarkEndXml),+ /// §17.13.5.18 `<w:ins>` — insert-side revision wrapper; content is kept.+ #[serde(rename = "ins")]+ Ins(RunTrackChangeXml),+ /// §17.13.5.14 `<w:del>` — delete-side revision wrapper; content is dropped.+ #[serde(rename = "del")]+ Del(RunTrackChangeXml),+ /// §17.13.5.22 `<w:moveTo>` — destination side of a move; content is kept.+ #[serde(rename = "moveTo")]+ MoveTo(RunTrackChangeXml),+ /// §17.13.5.19 `<w:moveFrom>` — source side of a move; content is dropped.+ #[serde(rename = "moveFrom")]+ MoveFrom(RunTrackChangeXml),+ /// §17.5.1.9 `<w:smartTag>` — structural run wrapper; content is flattened.+ #[serde(rename = "smartTag")]+ SmartTag(RunTrackChangeXml),+ /// §17.5.1.6 `<w:customXml>` (CT_CustomXmlRun) — content is flattened.+ #[serde(rename = "customXml")]+ CustomXml(RunTrackChangeXml),+ /// `<w:pPr>` is captured on `ParaXml` directly, but serde's untagged+ /// enum still has to handle it if it appears in `$value` ordering.+ #[serde(rename = "pPr")]+ PPr(Box<PPrXml>),+ #[serde(other)]+ Other,+}++/// A run-level revision (`ins`/`del`/`moveFrom`/`moveTo`, CT_RunTrackChange)+/// or structural (`smartTag`/`customXml`) wrapper. Its content model is+/// `EG_PContent` — the same children as `<w:p>` — so it nests recursively.+/// The paragraph-level analogue of `RowTrackChangeXml`. Any `customXmlPr`+/// child is absorbed by `$value` and ignored via `ParaChildXml::Other`.+#[derive(Deserialize, Default)]+pub(crate) struct RunTrackChangeXml {+ #[serde(rename = "$value", default)]+ pub content: Vec<ParaChildXml>,+}++// ── run ────────────────────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+pub(crate) struct RunXml {+ #[serde(rename = "@rsidR", default)]+ pub rsid_r: Option<String>,+ #[serde(rename = "@rsidRPr", default)]+ pub rsid_r_pr: Option<String>,+ #[serde(rename = "@rsidDel", default)]+ pub rsid_del: Option<String>,++ #[serde(rename = "rPr", default)]+ pub r_pr: Option<RPrXml>,+ #[serde(rename = "$value", default)]+ pub content: Vec<RunChildXml>,+}++/// Children of `<w:r>`. Includes both "run element" kinds (text, tab, break+/// — collected into a single `TextRun`) and "sibling inline" kinds (drawing,+/// pict, sym, etc. — each becomes its own `Inline` at the parent level).+#[derive(Deserialize)]+pub(crate) enum RunChildXml {+ #[serde(rename = "t")]+ Text(TextXml),+ #[serde(rename = "delText")]+ DelText(TextXml),+ #[serde(rename = "tab")]+ Tab,+ #[serde(rename = "ptab")]+ PTab(PTabXml),+ #[serde(rename = "br")]+ Br(BrXml),+ #[serde(rename = "cr")]+ Cr,+ #[serde(rename = "softHyphen")]+ SoftHyphen,+ #[serde(rename = "noBreakHyphen")]+ NoBreakHyphen,+ #[serde(rename = "lastRenderedPageBreak")]+ LastRenderedPageBreak,+ #[serde(rename = "drawing")]+ Drawing(DrawingXml),+ #[serde(rename = "pict")]+ Pict(crate::docx::parse::vml::schema::PictXml),+ #[serde(rename = "sym")]+ Sym(SymXml),+ #[serde(rename = "instrText")]+ InstrText(TextXml),+ #[serde(rename = "fldChar")]+ FldChar(FldCharXml),+ #[serde(rename = "footnoteReference")]+ FootnoteRef(NoteRefXml),+ #[serde(rename = "endnoteReference")]+ EndnoteRef(NoteRefXml),+ #[serde(rename = "footnoteRef")]+ FootnoteRefMark,+ #[serde(rename = "endnoteRef")]+ EndnoteRefMark,+ #[serde(rename = "separator")]+ Separator,+ #[serde(rename = "continuationSeparator")]+ ContinuationSeparator,+ #[serde(rename = "AlternateContent")]+ AlternateContent(AltContentXml),+ /// `<w:rPr>` captured separately; included here for serde ordering.+ #[serde(rename = "rPr")]+ RPr(Box<RPrXml>),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++// ── inline sub-types ───────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+pub(crate) struct TextXml {+ #[serde(rename = "@xml:space", default)]+ pub space: Option<String>,+ #[serde(rename = "$text", default)]+ pub content: String,+}++#[derive(Deserialize, Default)]+pub(crate) struct BrXml {+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub ty: Option<StBrType>,+ #[serde(+ rename = "@clear",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub clear: Option<StBrClear>,+}++#[derive(Deserialize, Clone, Copy, Debug)]+#[serde(rename_all = "camelCase")]+pub(crate) enum StBrType {+ Page,+ Column,+ TextWrapping,+}++/// §17.3.1.30 `<w:ptab>` — absolute-position tab. All three attributes are+/// required by the schema; we default leniently (left / indent / none) so a+/// malformed run does not abort the whole parse.+#[derive(Deserialize)]+pub(crate) struct PTabXml {+ #[serde(+ rename = "@alignment",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub alignment: StPTabAlignment,+ #[serde(+ rename = "@relativeTo",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub relative_to: StPTabRelativeTo,+ #[serde(+ rename = "@leader",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub leader: StPTabLeader,+}++impl From<PTabXml> for crate::docx::model::PositionTab {+ fn from(x: PTabXml) -> Self {+ Self {+ alignment: x.alignment.into(),+ relative_to: x.relative_to.into(),+ leader: x.leader.into(),+ }+ }+}++#[derive(Deserialize, Default)]+pub(crate) struct SymXml {+ #[serde(rename = "@font", default)]+ pub font: String,+ /// Hex string like `"F0A2"` — parsed to u16 at From time.+ #[serde(rename = "@char", default)]+ pub char: String,+}++#[derive(Deserialize)]+pub(crate) struct FldCharXml {+ #[serde(+ rename = "@fldCharType",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub fld_char_type: Option<StFldCharType>,+ #[serde(rename = "@dirty", default)]+ pub dirty: Option<AttrBool>,+ #[serde(rename = "@fldLock", default)]+ pub fld_lock: Option<AttrBool>,+}++#[derive(Deserialize)]+pub(crate) struct NoteRefXml {+ /// An unusable id references nothing, so the marker is dropped.+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub id: Option<i64>,+}++#[derive(Deserialize)]+pub(crate) struct BookmarkStartXml {+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub id: i64,+ #[serde(rename = "@name", default)]+ pub name: String,+}++#[derive(Deserialize)]+pub(crate) struct BookmarkEndXml {+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub id: i64,+}++/// `<w:drawing>` wrapper — contains exactly one `<wp:inline>` or+/// `<wp:anchor>` child (both modelled in `drawing/schema/anchor.rs`).+#[derive(Deserialize)]+pub(crate) struct DrawingXml {+ #[serde(rename = "inline", default)]+ pub inline: Option<crate::docx::parse::drawing::schema::anchor::InlineXml>,+ #[serde(rename = "anchor", default)]+ pub anchor: Option<crate::docx::parse::drawing::schema::anchor::AnchorXml>,+}++// ── hyperlink ──────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct HyperlinkXml {+ #[serde(rename = "@id", default)]+ pub r_id: Option<String>,+ #[serde(rename = "@anchor", default)]+ pub anchor: Option<String>,+ #[serde(rename = "$value", default)]+ pub content: Vec<ParaChildXml>,+}++// ── simple field ───────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct FldSimpleXml {+ #[serde(rename = "@instr", default)]+ pub instr: String,+ #[serde(rename = "$value", default)]+ pub content: Vec<ParaChildXml>,+}++// ── alternate content ──────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+pub(crate) struct AltContentXml {+ #[serde(rename = "Choice", default)]+ pub choices: Vec<ChoiceXml>,+ #[serde(rename = "Fallback", default)]+ pub fallback: Option<FallbackXml>,+}++#[derive(Deserialize)]+pub(crate) struct ChoiceXml {+ #[serde(rename = "@Requires", default)]+ pub requires: String,+ #[serde(rename = "$value", default)]+ pub content: Vec<McContentXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct FallbackXml {+ #[serde(rename = "$value", default)]+ pub content: Vec<McContentXml>,+}++/// Legacy parser only supports `drawing` and `pict` inside mc:Choice /+/// mc:Fallback — other children are ignored.+#[derive(Deserialize)]+pub(crate) enum McContentXml {+ #[serde(rename = "drawing")]+ Drawing(DrawingXml),+ #[serde(rename = "pict")]+ Pict(crate::docx::parse::vml::schema::PictXml),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++// ── table ──────────────────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+pub(crate) struct TableXml {+ #[serde(rename = "tblPr", default)]+ pub tbl_pr: Option<TblPrXml>,+ #[serde(rename = "tblGrid", default)]+ pub tbl_grid: Option<TblGridXml>,+ /// All direct children of `<w:tbl>` in document order. `<w:tblPr>` and+ /// `<w:tblGrid>` are also captured here (serde's `$value` collects every+ /// child) and must be ignored when extracting rows; the dedicated+ /// `tbl_pr` / `tbl_grid` fields above are canonical.+ #[serde(rename = "$value", default)]+ pub children: Vec<TableChildXml>,+}++/// Direct children of `<w:tbl>` modelled per ECMA-376 §17.4.38 (CT_Tbl).+///+/// After `<w:tblPr>` and `<w:tblGrid>`, OOXML's content model is a+/// `<xsd:choice>` repeated 0..* (`EG_ContentRowContent`): `<w:tr>`,+/// `<w:customXml>` (CT_CustomXmlRow), `<w:sdt>` (CT_SdtRow), or+/// EG_RunLevelElts (proofErr/permStart/permEnd; ins/del/moveFrom/moveTo as+/// CT_RowTrackChange; EG_RangeMarkupElements: bookmarkStart/End,+/// commentRange*; EG_MathContent). Modelling every spec-defined variant+/// lets row extraction recurse into wrappers; non-row variants are dropped+/// during conversion since they have no rendered effect at table level.+#[derive(Deserialize)]+pub(crate) enum TableChildXml {+ /// `<w:tr>` — a table row.+ #[serde(rename = "tr")]+ Row(Box<TableRowXml>),+ /// `<w:sdt>` — table-level structured document tag (CT_SdtRow).+ #[serde(rename = "sdt")]+ Sdt(Box<SdtRowXml>),+ /// `<w:ins>` revision-tracked inserted rows (CT_RowTrackChange).+ #[serde(rename = "ins")]+ Ins(Box<RowTrackChangeXml>),+ /// `<w:del>` revision-tracked deleted rows.+ #[serde(rename = "del")]+ Del(Box<RowTrackChangeXml>),+ /// `<w:moveFrom>` / `<w:moveTo>` revision-tracked moved rows.+ #[serde(rename = "moveFrom")]+ MoveFrom(Box<RowTrackChangeXml>),+ #[serde(rename = "moveTo")]+ MoveTo(Box<RowTrackChangeXml>),+ /// `<w:customXml>` — row-level custom-XML wrapper (CT_CustomXmlRow).+ #[serde(rename = "customXml")]+ CustomXml(Box<CustomXmlRowXml>),+ /// Range markup — bookmarks and comment ranges may span multiple rows.+ #[serde(rename = "bookmarkStart")]+ BookmarkStart(BookmarkStartXml),+ #[serde(rename = "bookmarkEnd")]+ BookmarkEnd(BookmarkEndXml),+ #[serde(rename = "commentRangeStart")]+ CommentRangeStart(BookmarkEndXml),+ #[serde(rename = "commentRangeEnd")]+ CommentRangeEnd(BookmarkEndXml),+ /// Proofreading and permission markers — ignored.+ #[serde(rename = "proofErr")]+ ProofErr(IgnoredXml),+ #[serde(rename = "permStart")]+ PermStart(IgnoredXml),+ #[serde(rename = "permEnd")]+ PermEnd(IgnoredXml),+ /// `<w:tblPr>` / `<w:tblGrid>` are captured on the parent directly;+ /// these variants exist only so `$value` can absorb the duplicate+ /// match. Compare with `ParaChildXml::PPr`.+ #[serde(rename = "tblPr")]+ TblPr(Box<TblPrXml>),+ #[serde(rename = "tblGrid")]+ TblGrid(Box<TblGridXml>),+ /// Catch-all for unmodelled OOXML elements (e.g., math content,+ /// `customXml*RangeStart/End`).+ #[serde(other)]+ Other,+}++/// CT_SdtRow §17.5.2.30 — `<w:sdt>` at table level. Wrapped rows live in+/// `<w:sdtContent>` (CT_SdtContentRow).+#[derive(Deserialize, Default)]+pub(crate) struct SdtRowXml {+ #[serde(rename = "sdtContent", default)]+ pub content: Option<SdtRowContentXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct SdtRowContentXml {+ #[serde(rename = "$value", default)]+ pub children: Vec<TableChildXml>,+}++/// CT_RowTrackChange §17.13.5.16/.7/.22 — used for `<w:ins>` / `<w:del>` /+/// `<w:moveFrom>` / `<w:moveTo>` at table level. Per the spec, contains+/// only `<w:tr>` children plus the inherited revision attributes.+#[derive(Deserialize, Default)]+pub(crate) struct RowTrackChangeXml {+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub id: Option<i64>,+ #[serde(rename = "@author", default)]+ pub author: Option<String>,+ #[serde(rename = "@date", default)]+ pub date: Option<String>,+ #[serde(rename = "tr", default)]+ pub rows: Vec<TableRowXml>,+}++/// CT_CustomXmlRow §17.5.1.5–.9 — recursive wrapper whose content model+/// mirrors CT_Tbl's row-level choice group, hence `Vec<TableChildXml>`.+#[derive(Deserialize, Default)]+pub(crate) struct CustomXmlRowXml {+ #[serde(rename = "customXmlPr", default)]+ pub custom_xml_pr: Option<IgnoredXml>,+ #[serde(rename = "$value", default)]+ pub children: Vec<TableChildXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct TblGridXml {+ #[serde(rename = "gridCol", default)]+ pub cols: Vec<GridColXml>,+}++#[derive(Deserialize)]+pub(crate) struct GridColXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub w: Option<Dimension<Twips>>,+}++#[derive(Deserialize, Default)]+pub(crate) struct TableRowXml {+ #[serde(rename = "@rsidR", default)]+ pub rsid_r: Option<String>,+ #[serde(rename = "@rsidRPr", default)]+ pub rsid_r_pr: Option<String>,+ #[serde(rename = "@rsidDel", default)]+ pub rsid_del: Option<String>,+ #[serde(rename = "@rsidTr", default)]+ pub rsid_tr: Option<String>,++ /// §17.4.61 `<w:tblPrEx>` — per-row exceptions to table-level+ /// properties. Spec mandates that when present, it appears *before*+ /// `<w:trPr>` inside `<w:tr>`. Also absorbed by `$value` below (via+ /// `RowChildXml::TblPrEx`); this dedicated field is canonical.+ #[serde(rename = "tblPrEx", default)]+ pub tbl_pr_ex: Option<TblPrExXml>,+ #[serde(rename = "trPr", default)]+ pub tr_pr: Option<TrPrXml>,+ /// All direct children of `<w:tr>` in document order. `<w:tc>` cells may+ /// be interleaved with `<w:sdt>` / `<w:customXml>` wrappers (each of+ /// which nests further cells), so — like `<w:tbl>` — the row cannot use a+ /// plain `Vec<TableCellXml>`: `quick_xml` reports a duplicate `tc` field+ /// when cells are non-contiguous. Cells are flattened out during+ /// conversion by `collect_row_cells`.+ #[serde(rename = "$value", default)]+ pub children: Vec<RowChildXml>,+}++/// Direct children of `<w:tr>` modelled per ECMA-376 §17.4 (CT_Row).+///+/// After `<w:tblPrEx>` and `<w:trPr>`, the content model is the+/// `EG_ContentCellContent` group repeated 0..*: `<w:tc>` (CT_Tc),+/// `<w:customXml>` (CT_CustomXmlCell), `<w:sdt>` (CT_SdtCell), or+/// EG_RunLevelElts (proofErr/permStart/permEnd) and EG_RangeMarkupElements+/// (bookmarkStart/End, commentRange*). The wrappers nest further cells;+/// non-cell variants are dropped during conversion since they have no+/// rendered effect at row level. Mirrors `TableChildXml`.+#[derive(Deserialize)]+pub(crate) enum RowChildXml {+ /// `<w:tc>` — a table cell.+ #[serde(rename = "tc")]+ Cell(Box<TableCellXml>),+ /// `<w:sdt>` — cell-level structured document tag (CT_SdtCell).+ #[serde(rename = "sdt")]+ Sdt(Box<SdtCellXml>),+ /// `<w:customXml>` — cell-level custom-XML wrapper (CT_CustomXmlCell).+ #[serde(rename = "customXml")]+ CustomXml(Box<CustomXmlCellXml>),+ /// Range markup — bookmarks and comment ranges may span multiple cells.+ #[serde(rename = "bookmarkStart")]+ BookmarkStart(BookmarkStartXml),+ #[serde(rename = "bookmarkEnd")]+ BookmarkEnd(BookmarkEndXml),+ #[serde(rename = "commentRangeStart")]+ CommentRangeStart(BookmarkEndXml),+ #[serde(rename = "commentRangeEnd")]+ CommentRangeEnd(BookmarkEndXml),+ /// Proofreading and permission markers — ignored.+ #[serde(rename = "proofErr")]+ ProofErr(IgnoredXml),+ #[serde(rename = "permStart")]+ PermStart(IgnoredXml),+ #[serde(rename = "permEnd")]+ PermEnd(IgnoredXml),+ /// `<w:tblPrEx>` / `<w:trPr>` are captured on the parent directly; these+ /// variants exist only so `$value` can absorb the duplicate match.+ /// Compare with `TableChildXml::TblPr`.+ #[serde(rename = "tblPrEx")]+ TblPrEx(Box<TblPrExXml>),+ #[serde(rename = "trPr")]+ TrPr(Box<TrPrXml>),+ /// Catch-all for unmodelled OOXML elements (e.g., math content).+ #[serde(other)]+ Other,+}++/// CT_SdtCell §17.5.2 — `<w:sdt>` at cell level. Wrapped cells live in+/// `<w:sdtContent>` (CT_SdtContentCell); the cell-level analogue of+/// `SdtRowXml`.+#[derive(Deserialize, Default)]+pub(crate) struct SdtCellXml {+ #[serde(rename = "sdtContent", default)]+ pub content: Option<SdtCellContentXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct SdtCellContentXml {+ #[serde(rename = "$value", default)]+ pub children: Vec<RowChildXml>,+}++/// CT_CustomXmlCell §17.5.1 — recursive wrapper whose content model+/// mirrors CT_Row's cell-level choice group, hence `Vec<RowChildXml>`; the+/// cell-level analogue of `CustomXmlRowXml`.+#[derive(Deserialize, Default)]+pub(crate) struct CustomXmlCellXml {+ #[serde(rename = "customXmlPr", default)]+ pub custom_xml_pr: Option<IgnoredXml>,+ #[serde(rename = "$value", default)]+ pub children: Vec<RowChildXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct TableCellXml {+ #[serde(rename = "tcPr", default)]+ pub tc_pr: Option<TcPrXml>,+ #[serde(rename = "$value", default)]+ pub content: Vec<BlockChildXml>,+}++// ── helpers ────────────────────────────────────────────────────────────────++pub(crate) use crate::docx::parse::primitives::AttrBool;++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::{PTabAlignment, PTabLeader, PTabRelativeTo, PositionTab};++ fn ptab(xml: &str) -> PositionTab {+ let x: PTabXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn ptab_center_margin() {+ let p = ptab(r#"<ptab relativeTo="margin" alignment="center" leader="none"/>"#);+ assert_eq!(p.alignment, PTabAlignment::Center);+ assert_eq!(p.relative_to, PTabRelativeTo::Margin);+ assert_eq!(p.leader, PTabLeader::None);+ }++ #[test]+ fn ptab_right_margin_with_dot_leader() {+ let p = ptab(r#"<ptab relativeTo="margin" alignment="right" leader="dot"/>"#);+ assert_eq!(p.alignment, PTabAlignment::Right);+ assert_eq!(p.relative_to, PTabRelativeTo::Margin);+ assert_eq!(p.leader, PTabLeader::Dot);+ }++ #[test]+ fn ptab_defaults_are_lenient() {+ // All three attributes are required by the schema; a malformed run+ // that omits them defaults to left / indent / none instead of failing.+ let p = ptab(r#"<ptab/>"#);+ assert_eq!(p.alignment, PTabAlignment::Left);+ assert_eq!(p.relative_to, PTabRelativeTo::Indent);+ assert_eq!(p.leader, PTabLeader::None);+ }++ #[test]+ fn ptab_dispatches_as_run_child() {+ // The whole reason for the fix: `<w:ptab>` must be a recognized run+ // child, not an unknown-variant deserialize error.+ let r: RunXml = quick_xml::de::from_str(+ r#"<r><t>a</t><ptab relativeTo="margin" alignment="right" leader="none"/><t>b</t></r>"#,+ )+ .unwrap();+ assert!(+ r.content.iter().any(|c| matches!(c, RunChildXml::PTab(_))),+ "run content should contain a PTab child"+ );+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/mod.rs b/crates/liteparse-docx/src/docx/parse/drawing/mod.rsnew file mode 100644index 0000000..8facf0b--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/mod.rs@@ -0,0 +1,9 @@+//! DrawingML parsing — fully serde-based.+//!+//! See [`schema`] for the type-by-type schemas (color, fill, stroke, effect,+//! geometry, picture, shape, anchor, inline). Consumers (body, numbering,+//! notes) call the top-level `InlineXml::into_image(ctx)` /+//! `AnchorXml::into_image(ctx)` / `PictureXml` / `WspXml::into_model(ctx)`+//! entry points directly.++pub mod schema;diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/anchor.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/anchor.rsnew file mode 100644index 0000000..4eb234a--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/anchor.rs@@ -0,0 +1,1021 @@+//! DrawingML outer wrappers: `<wp:inline>` and `<wp:anchor>` → `Image`.+//!+//! These are the entry points from body content — `<w:drawing>` wraps exactly+//! one of these. They share most children (`extent`, `effectExtent`, `docPr`,+//! `cNvGraphicFramePr`, `graphic`) and differ in placement-specific children:+//! inline has just `distT/B/L/R`, while anchor adds position, wrap, and+//! z-ordering.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::dimension::{Dimension, Emu};+use crate::docx::geometry::{EdgeInsets, Offset, Size};+use crate::docx::model::{+ AnchorAlignment, AnchorPosition, AnchorProperties, AnchorRelativeFrom, DocProperties,+ GraphicContent, GraphicFrameLocks, Image, ImagePlacement, TextWrap, WrapPolygon, WrapText,+};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++use super::fill::AttrBool;+use super::picture::PictureXml;+use super::shape::WspXml;++// ── Shared bits ───────────────────────────────────────────────────────────++/// `<wp:extent cx=".." cy=".."/>` — positive size in EMU.+#[derive(Debug, Deserialize)]+pub struct ExtentXml {+ #[serde(+ rename = "@cx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub cx: Dimension<Emu>,+ #[serde(+ rename = "@cy",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub cy: Dimension<Emu>,+}++/// `<wp:effectExtent l=".." t=".." r=".." b=".."/>` — drawing overflow.+#[derive(Debug, Deserialize)]+pub struct EffectExtentXml {+ #[serde(+ rename = "@l",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub l: Option<Dimension<Emu>>,+ #[serde(+ rename = "@t",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub t: Option<Dimension<Emu>>,+ #[serde(+ rename = "@r",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub r: Option<Dimension<Emu>>,+ #[serde(+ rename = "@b",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub b: Option<Dimension<Emu>>,+}++impl From<EffectExtentXml> for EdgeInsets<Emu> {+ fn from(x: EffectExtentXml) -> Self {+ Self::new(+ x.t.unwrap_or_default(),+ x.r.unwrap_or_default(),+ x.b.unwrap_or_default(),+ x.l.unwrap_or_default(),+ )+ }+}++/// `<wp:docPr>` — inline-image variant (distinct from `<pic:cNvPr>`).+#[derive(Debug, Deserialize)]+pub struct DocPrXml {+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub id: Option<u32>,+ #[serde(rename = "@name", default)]+ pub name: Option<String>,+ #[serde(rename = "@descr", default)]+ pub descr: Option<String>,+ #[serde(rename = "@hidden", default)]+ pub hidden: Option<AttrBool>,+ #[serde(rename = "@title", default)]+ pub title: Option<String>,+}++impl From<DocPrXml> for DocProperties {+ fn from(x: DocPrXml) -> Self {+ Self {+ id: x.id.unwrap_or(0),+ name: x.name.unwrap_or_default(),+ description: x.descr,+ hidden: x.hidden.map(|b| b.0),+ title: x.title,+ }+ }+}++/// `<wp:cNvGraphicFramePr>` — wraps `<a:graphicFrameLocks>`.+#[derive(Debug, Deserialize)]+pub struct CNvGraphicFramePrXml {+ #[serde(rename = "graphicFrameLocks", default)]+ pub locks: Option<GraphicFrameLocksXml>,+}++#[derive(Debug, Deserialize)]+pub struct GraphicFrameLocksXml {+ #[serde(rename = "@noChangeAspect", default)]+ pub no_change_aspect: Option<AttrBool>,+ #[serde(rename = "@noDrilldown", default)]+ pub no_drilldown: Option<AttrBool>,+ #[serde(rename = "@noGrp", default)]+ pub no_grp: Option<AttrBool>,+ #[serde(rename = "@noMove", default)]+ pub no_move: Option<AttrBool>,+ #[serde(rename = "@noResize", default)]+ pub no_resize: Option<AttrBool>,+ #[serde(rename = "@noSelect", default)]+ pub no_select: Option<AttrBool>,+}++impl From<CNvGraphicFramePrXml> for GraphicFrameLocks {+ fn from(x: CNvGraphicFramePrXml) -> Self {+ x.locks+ .map(|l| Self {+ no_change_aspect: l.no_change_aspect.map(|b| b.0),+ no_drilldown: l.no_drilldown.map(|b| b.0),+ no_grp: l.no_grp.map(|b| b.0),+ no_move: l.no_move.map(|b| b.0),+ no_resize: l.no_resize.map(|b| b.0),+ no_select: l.no_select.map(|b| b.0),+ })+ .unwrap_or(Self {+ no_change_aspect: None,+ no_drilldown: None,+ no_grp: None,+ no_move: None,+ no_resize: None,+ no_select: None,+ })+ }+}++/// `<a:graphic>` → `<a:graphicData>` → `<pic:pic>` or `<wps:wsp>`.+#[derive(Deserialize)]+pub(crate) struct GraphicXml {+ #[serde(rename = "graphicData", default)]+ pub(crate) data: Option<GraphicDataXml>,+}++#[derive(Deserialize)]+pub(crate) struct GraphicDataXml {+ #[serde(rename = "pic", default)]+ pub(crate) pic: Option<PictureXml>,+ #[serde(rename = "wsp", default)]+ pub(crate) wsp: Option<WspXml>,+}++impl GraphicXml {+ fn into_content(+ self,+ ctx: &mut crate::docx::parse::body::ConvertCtx,+ ) -> Option<GraphicContent> {+ let data = self.data?;+ if let Some(pic) = data.pic {+ Some(GraphicContent::Picture(pic.into()))+ } else {+ data.wsp+ .map(|w| GraphicContent::WordProcessingShape(w.into_model(ctx)))+ }+ }+}++// ── Inline ────────────────────────────────────────────────────────────────++/// `<wp:inline>` — inline drawing.+#[derive(Deserialize)]+pub(crate) struct InlineXml {+ #[serde(+ rename = "@distT",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_t: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distB",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_b: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distL",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_l: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distR",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_r: Option<Dimension<Emu>>,++ #[serde(rename = "extent")]+ pub extent: ExtentXml,+ #[serde(rename = "effectExtent", default)]+ pub effect_extent: Option<EffectExtentXml>,+ #[serde(rename = "docPr")]+ pub doc_pr: DocPrXml,+ #[serde(rename = "cNvGraphicFramePr", default)]+ pub cnv_gfp: Option<CNvGraphicFramePrXml>,+ #[serde(rename = "graphic", default)]+ pub graphic: Option<GraphicXml>,+}++impl InlineXml {+ pub(crate) fn into_image(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> Image {+ let distance = EdgeInsets::new(+ self.dist_t.unwrap_or_default(),+ self.dist_r.unwrap_or_default(),+ self.dist_b.unwrap_or_default(),+ self.dist_l.unwrap_or_default(),+ );+ Image {+ extent: Size::new(self.extent.cx, self.extent.cy),+ effect_extent: self.effect_extent.map(Into::into),+ doc_properties: self.doc_pr.into(),+ graphic_frame_locks: self.cnv_gfp.map(Into::into),+ graphic: self.graphic.and_then(|g| g.into_content(ctx)),+ placement: ImagePlacement::Inline { distance },+ }+ }+}++// ── Anchor ────────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct AnchorXml {+ #[serde(+ rename = "@distT",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_t: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distB",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_b: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distL",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_l: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distR",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_r: Option<Dimension<Emu>>,+ #[serde(rename = "@simplePos", default)]+ pub simple_pos_attr: Option<AttrBool>,+ // §20.4.2.3 marks these four `use="required"`, but a single nonconformant+ // `<wp:anchor>` (some third-party / hand-edited producers omit them) would+ // otherwise fail deserialization and abort the whole-document parse. Accept+ // them as optional and apply Word's effective defaults at the `into_image`+ // seam — matching `layout_in_cell` / `hidden`, which are already lenient.+ #[serde(+ rename = "@relativeHeight",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub relative_height: Option<u32>,+ #[serde(rename = "@behindDoc", default)]+ pub behind_doc: Option<AttrBool>,+ #[serde(rename = "@locked", default)]+ pub locked: Option<AttrBool>,+ #[serde(rename = "@allowOverlap", default)]+ pub allow_overlap: Option<AttrBool>,+ #[serde(rename = "@layoutInCell", default)]+ pub layout_in_cell: Option<AttrBool>,+ #[serde(rename = "@hidden", default)]+ pub hidden: Option<AttrBool>,++ #[serde(rename = "simplePos", default)]+ pub simple_pos: Option<SimplePosXml>,+ #[serde(rename = "positionH", default)]+ pub pos_h: Option<PositionXml>,+ #[serde(rename = "positionV", default)]+ pub pos_v: Option<PositionXml>,++ // Wrap variants — at most one present.+ #[serde(rename = "wrapNone", default)]+ pub wrap_none: Option<super::fill::Empty>,+ #[serde(rename = "wrapSquare", default)]+ pub wrap_square: Option<WrapSquareXml>,+ #[serde(rename = "wrapTight", default)]+ pub wrap_tight: Option<WrapTightThroughXml>,+ #[serde(rename = "wrapThrough", default)]+ pub wrap_through: Option<WrapTightThroughXml>,+ #[serde(rename = "wrapTopAndBottom", default)]+ pub wrap_top_and_bottom: Option<WrapTopAndBottomXml>,++ #[serde(rename = "extent")]+ pub extent: ExtentXml,+ #[serde(rename = "effectExtent", default)]+ pub effect_extent: Option<EffectExtentXml>,+ #[serde(rename = "docPr")]+ pub doc_pr: DocPrXml,+ #[serde(rename = "cNvGraphicFramePr", default)]+ pub cnv_gfp: Option<CNvGraphicFramePrXml>,+ #[serde(rename = "graphic", default)]+ pub graphic: Option<GraphicXml>,+}++#[derive(Debug, Deserialize)]+pub struct SimplePosXml {+ #[serde(+ rename = "@x",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub x: Dimension<Emu>,+ #[serde(+ rename = "@y",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub y: Dimension<Emu>,+}++/// `<wp:positionH>` or `<wp:positionV>` — one of `<wp:posOffset>` or+/// `<wp:align>`.+#[derive(Debug, Deserialize)]+pub struct PositionXml {+ #[serde(+ rename = "@relativeFrom",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub relative_from: Option<StRelFrom>,+ #[serde(rename = "posOffset", default)]+ pub pos_offset: Option<PosOffsetXml>,+ #[serde(rename = "align", default)]+ pub align: Option<AlignXml>,+}++#[derive(Debug, Deserialize)]+pub struct PosOffsetXml {+ #[serde(rename = "$text", default)]+ pub value: String,+}++#[derive(Debug, Deserialize)]+pub struct AlignXml {+ #[serde(+ rename = "$text",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub value: Option<StAnchorAlignment>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StRelFrom {+ Page,+ Margin,+ Column,+ Character,+ Paragraph,+ Line,+ InsideMargin,+ OutsideMargin,+ TopMargin,+ BottomMargin,+ LeftMargin,+ RightMargin,+}++impl From<StRelFrom> for AnchorRelativeFrom {+ fn from(s: StRelFrom) -> Self {+ use StRelFrom as X;+ match s {+ X::Page => Self::Page,+ X::Margin => Self::Margin,+ X::Column => Self::Column,+ X::Character => Self::Character,+ X::Paragraph => Self::Paragraph,+ X::Line => Self::Line,+ X::InsideMargin => Self::InsideMargin,+ X::OutsideMargin => Self::OutsideMargin,+ X::TopMargin => Self::TopMargin,+ X::BottomMargin => Self::BottomMargin,+ X::LeftMargin => Self::LeftMargin,+ X::RightMargin => Self::RightMargin,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StAnchorAlignment {+ Left,+ Center,+ Right,+ Inside,+ Outside,+ Top,+ Bottom,+}++impl From<StAnchorAlignment> for AnchorAlignment {+ fn from(s: StAnchorAlignment) -> Self {+ use StAnchorAlignment as X;+ match s {+ X::Left => Self::Left,+ X::Center => Self::Center,+ X::Right => Self::Right,+ X::Inside => Self::Inside,+ X::Outside => Self::Outside,+ X::Top => Self::Top,+ X::Bottom => Self::Bottom,+ }+ }+}++#[derive(Debug, Deserialize)]+pub struct WrapSquareXml {+ #[serde(+ rename = "@wrapText",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub wrap_text: StWrapText,+ #[serde(+ rename = "@distT",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_t: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distB",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_b: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distL",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_l: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distR",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_r: Option<Dimension<Emu>>,+}++#[derive(Debug, Deserialize)]+pub struct WrapTightThroughXml {+ #[serde(+ rename = "@wrapText",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub wrap_text: StWrapText,+ #[serde(+ rename = "@distL",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_l: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distR",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_r: Option<Dimension<Emu>>,+ #[serde(rename = "wrapPolygon", default)]+ pub polygon: Option<WrapPolygonXml>,+}++#[derive(Debug, Deserialize)]+pub struct WrapTopAndBottomXml {+ #[serde(+ rename = "@distT",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_t: Option<Dimension<Emu>>,+ #[serde(+ rename = "@distB",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub dist_b: Option<Dimension<Emu>>,+}++#[derive(Debug, Deserialize)]+pub struct WrapPolygonXml {+ #[serde(rename = "@edited", default)]+ pub edited: Option<AttrBool>,+ #[serde(rename = "start", default)]+ pub start: Option<Point2DXml>,+ #[serde(rename = "lineTo", default)]+ pub line_to: Vec<Point2DXml>,+}++#[derive(Debug, Deserialize)]+pub struct Point2DXml {+ #[serde(+ rename = "@x",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub x: Dimension<Emu>,+ #[serde(+ rename = "@y",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub y: Dimension<Emu>,+}++#[derive(Clone, Copy, Debug, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StWrapText {+ #[default]+ BothSides,+ Left,+ Right,+ Largest,+}++impl From<StWrapText> for WrapText {+ fn from(s: StWrapText) -> Self {+ match s {+ StWrapText::BothSides => Self::BothSides,+ StWrapText::Left => Self::Left,+ StWrapText::Right => Self::Right,+ StWrapText::Largest => Self::Largest,+ }+ }+}++impl AnchorXml {+ pub(crate) fn into_image(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> Image {+ let distance = EdgeInsets::new(+ self.dist_t.unwrap_or_default(),+ self.dist_r.unwrap_or_default(),+ self.dist_b.unwrap_or_default(),+ self.dist_l.unwrap_or_default(),+ );+ let simple_pos = self.simple_pos.map(|s| Offset::new(s.x, s.y));+ let use_simple_pos = self.simple_pos_attr.map(|b| b.0);+ let horizontal_position = position(self.pos_h);+ let vertical_position = position(self.pos_v);+ let wrap = pick_wrap(+ self.wrap_none,+ self.wrap_square,+ self.wrap_tight,+ self.wrap_through,+ self.wrap_top_and_bottom,+ );+ Image {+ extent: Size::new(self.extent.cx, self.extent.cy),+ effect_extent: self.effect_extent.map(Into::into),+ doc_properties: self.doc_pr.into(),+ graphic_frame_locks: self.cnv_gfp.map(Into::into),+ graphic: self.graphic.and_then(|g| g.into_content(ctx)),+ placement: ImagePlacement::Anchor(AnchorProperties {+ distance,+ simple_pos,+ use_simple_pos,+ horizontal_position,+ vertical_position,+ wrap,+ // Word's effective defaults when the (spec-required) attrs are+ // absent: in front of text, unlocked, overlap allowed, z-order 0.+ behind_text: self.behind_doc.map(|b| b.0).unwrap_or(false),+ lock_anchor: self.locked.map(|b| b.0).unwrap_or(false),+ allow_overlap: self.allow_overlap.map(|b| b.0).unwrap_or(true),+ relative_height: self.relative_height.unwrap_or(0),+ layout_in_cell: self.layout_in_cell.map(|b| b.0),+ hidden: self.hidden.map(|b| b.0),+ }),+ }+ }+}++fn position(p: Option<PositionXml>) -> AnchorPosition {+ // Fallback to page+left when nothing is specified.+ let Some(p) = p else {+ return AnchorPosition::Align {+ relative_from: AnchorRelativeFrom::Page,+ alignment: AnchorAlignment::Left,+ };+ };+ let rel = p.relative_from.map_or(AnchorRelativeFrom::Page, Into::into);+ if let Some(a) = p.align {+ return AnchorPosition::Align {+ relative_from: rel,+ alignment: a.value.map_or(AnchorAlignment::Left, Into::into),+ };+ }+ if let Some(o) = p.pos_offset {+ let offset = o.value.trim().parse::<i64>().unwrap_or_else(|_| {+ log::warn!("posOffset: invalid EMU offset {:?}; using 0", o.value);+ 0+ });+ return AnchorPosition::Offset {+ relative_from: rel,+ offset: Dimension::new(offset),+ };+ }+ AnchorPosition::Offset {+ relative_from: rel,+ offset: Dimension::new(0),+ }+}++fn pick_wrap(+ none: Option<super::fill::Empty>,+ square: Option<WrapSquareXml>,+ tight: Option<WrapTightThroughXml>,+ through: Option<WrapTightThroughXml>,+ top_and_bottom: Option<WrapTopAndBottomXml>,+) -> TextWrap {+ if none.is_some() {+ return TextWrap::None;+ }+ if let Some(s) = square {+ return TextWrap::Square {+ distance: EdgeInsets::new(+ s.dist_t.unwrap_or_default(),+ s.dist_r.unwrap_or_default(),+ s.dist_b.unwrap_or_default(),+ s.dist_l.unwrap_or_default(),+ ),+ wrap_text: s.wrap_text.into(),+ };+ }+ if let Some(t) = tight {+ return TextWrap::Tight {+ distance: EdgeInsets::new(+ Dimension::new(0),+ t.dist_r.unwrap_or_default(),+ Dimension::new(0),+ t.dist_l.unwrap_or_default(),+ ),+ wrap_text: t.wrap_text.into(),+ polygon: t.polygon.and_then(polygon),+ };+ }+ if let Some(th) = through {+ return TextWrap::Through {+ distance: EdgeInsets::new(+ Dimension::new(0),+ th.dist_r.unwrap_or_default(),+ Dimension::new(0),+ th.dist_l.unwrap_or_default(),+ ),+ wrap_text: th.wrap_text.into(),+ polygon: th.polygon.and_then(polygon),+ };+ }+ if let Some(tb) = top_and_bottom {+ return TextWrap::TopAndBottom {+ distance_top: tb.dist_t.unwrap_or_default(),+ distance_bottom: tb.dist_b.unwrap_or_default(),+ };+ }+ TextWrap::None+}++fn polygon(p: WrapPolygonXml) -> Option<WrapPolygon> {+ let start = p.start?;+ Some(WrapPolygon {+ edited: p.edited.map(|b| b.0),+ start: Offset::new(start.x, start.y),+ line_to: p+ .line_to+ .into_iter()+ .map(|pt| Offset::new(pt.x, pt.y))+ .collect(),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn effect_extent_preserves_signed_decimal_values() {+ let effect: EffectExtentXml =+ quick_xml::de::from_str(r#"<effectExtent l="-12.0" t="-24" r="36" b="48"/>"#).unwrap();+ assert_eq!(effect.l.unwrap().raw(), -12);+ assert_eq!(effect.t.unwrap().raw(), -24);+ assert_eq!(effect.r.unwrap().raw(), 36);+ assert_eq!(effect.b.unwrap().raw(), 48);+ }++ #[test]+ /// Upstream rejected a negative extent, failing the whole document over a+ /// shape's size. We degrade it to zero instead — but the guard it existed+ /// for still holds: a negative extent must never become a real size, and+ /// the sibling axis must survive untouched.+ fn negative_decimal_extent_degrades_to_zero() {+ let parsed: ExtentXml = quick_xml::de::from_str(r#"<extent cx="-1.5" cy="100"/>"#)+ .expect("a negative extent must not fail the parse");+ assert_eq!(parsed.cx.raw(), 0, "negative extent must not become a size");+ assert_eq!(parsed.cy.raw(), 100, "the valid axis must be unaffected");+ }++ fn parse_inline(xml: &str) -> Image {+ let wrapped = format!(+ r#"<wrap xmlns:wp="urn:wp" xmlns:a="urn:a" xmlns:r="urn:r" xmlns:pic="urn:pic" xmlns:wps="urn:wps" xmlns:w="urn:w">{}</wrap>"#,+ xml+ );+ #[derive(Deserialize)]+ struct Wrap {+ inline: InlineXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ w.inline.into_image(&mut ctx)+ }++ fn parse_anchor(xml: &str) -> Image {+ let wrapped = format!(+ r#"<wrap xmlns:wp="urn:wp" xmlns:a="urn:a" xmlns:r="urn:r" xmlns:pic="urn:pic" xmlns:wps="urn:wps" xmlns:w="urn:w">{}</wrap>"#,+ xml+ );+ #[derive(Deserialize)]+ struct Wrap {+ anchor: AnchorXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ w.anchor.into_image(&mut ctx)+ }++ #[test]+ fn inline_with_picture() {+ let img = parse_inline(+ r#"<inline distT="0" distB="0" distL="0" distR="0">+ <extent cx="914400" cy="457200"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="1" name="image1"/>+ <cNvGraphicFramePr><graphicFrameLocks noChangeAspect="1"/></cNvGraphicFramePr>+ <graphic>+ <graphicData>+ <pic>+ <nvPicPr><cNvPr id="1" name="Pic1"/></nvPicPr>+ <blipFill><blip r:embed="rId1"/></blipFill>+ </pic>+ </graphicData>+ </graphic>+ </inline>"#,+ );+ assert_eq!(img.extent.width.raw(), 914400);+ assert_eq!(img.extent.height.raw(), 457200);+ assert_eq!(img.doc_properties.name, "image1");+ assert!(matches!(img.placement, ImagePlacement::Inline { .. }));+ assert!(matches!(img.graphic, Some(GraphicContent::Picture(_))));+ }++ #[test]+ fn inline_without_effect_extent_defaults_to_none() {+ let img = parse_inline(+ r#"<inline>+ <extent cx="100" cy="100"/>+ <docPr id="2" name="bare"/>+ <graphic><graphicData/></graphic>+ </inline>"#,+ );+ assert!(img.effect_extent.is_none());+ assert!(img.graphic.is_none());+ }++ #[test]+ fn anchor_with_offset_positions_and_square_wrap() {+ let img = parse_anchor(+ r#"<anchor distT="0" distB="0" distL="114300" distR="114300"+ simplePos="0" relativeHeight="251659264"+ behindDoc="0" locked="0" allowOverlap="1">+ <simplePos x="0" y="0"/>+ <positionH relativeFrom="column">+ <posOffset>1524000</posOffset>+ </positionH>+ <positionV relativeFrom="paragraph">+ <posOffset>762000</posOffset>+ </positionV>+ <wrapSquare wrapText="bothSides"/>+ <extent cx="914400" cy="457200"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="3" name="float"/>+ <graphic><graphicData><pic>+ <nvPicPr><cNvPr id="3" name="P3"/></nvPicPr>+ <blipFill><blip r:embed="rId3"/></blipFill>+ </pic></graphicData></graphic>+ </anchor>"#,+ );+ let ImagePlacement::Anchor(a) = &img.placement else {+ panic!("expected Anchor");+ };+ assert_eq!(a.relative_height, 251_659_264);+ assert!(!a.behind_text);+ assert!(a.allow_overlap);+ match a.horizontal_position {+ AnchorPosition::Offset {+ relative_from,+ offset,+ } => {+ assert_eq!(relative_from, AnchorRelativeFrom::Column);+ assert_eq!(offset.raw(), 1_524_000);+ }+ other => panic!("expected Offset, got {other:?}"),+ }+ match a.vertical_position {+ AnchorPosition::Offset { offset, .. } => assert_eq!(offset.raw(), 762_000),+ other => panic!("expected Offset, got {other:?}"),+ }+ match &a.wrap {+ TextWrap::Square { wrap_text, .. } => assert_eq!(*wrap_text, WrapText::BothSides),+ other => panic!("expected Square, got {other:?}"),+ }+ }++ #[test]+ fn anchor_with_align_positions() {+ let img = parse_anchor(+ r#"<anchor distT="0" distB="0" distL="0" distR="0"+ simplePos="0" relativeHeight="1"+ behindDoc="0" locked="0" allowOverlap="1">+ <simplePos x="0" y="0"/>+ <positionH relativeFrom="page"><align>center</align></positionH>+ <positionV relativeFrom="page"><align>top</align></positionV>+ <wrapNone/>+ <extent cx="100" cy="100"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="4" name="centered"/>+ <graphic><graphicData/></graphic>+ </anchor>"#,+ );+ let ImagePlacement::Anchor(a) = &img.placement else {+ panic!("expected Anchor");+ };+ match a.horizontal_position {+ AnchorPosition::Align {+ relative_from,+ alignment,+ } => {+ assert_eq!(relative_from, AnchorRelativeFrom::Page);+ assert_eq!(alignment, AnchorAlignment::Center);+ }+ other => panic!("expected Align, got {other:?}"),+ }+ assert!(matches!(a.wrap, TextWrap::None));+ }++ #[test]+ fn anchor_with_tight_wrap_and_polygon() {+ let img = parse_anchor(+ r#"<anchor distT="0" distB="0" distL="0" distR="0"+ simplePos="0" relativeHeight="2"+ behindDoc="0" locked="0" allowOverlap="1">+ <simplePos x="0" y="0"/>+ <positionH relativeFrom="column"><posOffset>0</posOffset></positionH>+ <positionV relativeFrom="paragraph"><posOffset>0</posOffset></positionV>+ <wrapTight wrapText="bothSides">+ <wrapPolygon edited="0">+ <start x="0" y="0"/>+ <lineTo x="100" y="0"/>+ <lineTo x="100" y="100"/>+ <lineTo x="0" y="100"/>+ </wrapPolygon>+ </wrapTight>+ <extent cx="100" cy="100"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="5" name="tight"/>+ <graphic><graphicData/></graphic>+ </anchor>"#,+ );+ let ImagePlacement::Anchor(a) = &img.placement else {+ panic!("expected Anchor");+ };+ match &a.wrap {+ TextWrap::Tight {+ polygon: Some(p), ..+ } => {+ assert_eq!(p.line_to.len(), 3);+ assert_eq!(p.start.x.raw(), 0);+ assert_eq!(p.edited, Some(false));+ }+ other => panic!("expected Tight with polygon, got {other:?}"),+ }+ }++ #[test]+ fn anchor_with_top_and_bottom_wrap() {+ let img = parse_anchor(+ r#"<anchor distT="0" distB="0" distL="0" distR="0"+ simplePos="0" relativeHeight="3"+ behindDoc="0" locked="0" allowOverlap="1">+ <simplePos x="0" y="0"/>+ <positionH relativeFrom="margin"><posOffset>0</posOffset></positionH>+ <positionV relativeFrom="paragraph"><posOffset>0</posOffset></positionV>+ <wrapTopAndBottom distT="181610" distB="181610"/>+ <extent cx="100" cy="100"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="6" name="tb"/>+ <graphic><graphicData/></graphic>+ </anchor>"#,+ );+ let ImagePlacement::Anchor(a) = &img.placement else {+ panic!("expected Anchor");+ };+ match &a.wrap {+ TextWrap::TopAndBottom {+ distance_top,+ distance_bottom,+ } => {+ assert_eq!(distance_top.raw(), 181_610);+ assert_eq!(distance_bottom.raw(), 181_610);+ }+ other => panic!("expected TopAndBottom, got {other:?}"),+ }+ }++ #[test]+ fn anchor_behind_text_flag() {+ let img = parse_anchor(+ r#"<anchor distT="0" distB="0" distL="0" distR="0"+ simplePos="0" relativeHeight="1"+ behindDoc="1" locked="0" allowOverlap="0">+ <simplePos x="0" y="0"/>+ <positionH relativeFrom="page"><align>right</align></positionH>+ <positionV relativeFrom="page"><align>bottom</align></positionV>+ <wrapNone/>+ <extent cx="1" cy="1"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="7" name="watermark"/>+ <graphic><graphicData/></graphic>+ </anchor>"#,+ );+ let ImagePlacement::Anchor(a) = &img.placement else {+ panic!();+ };+ assert!(a.behind_text);+ assert!(!a.allow_overlap);+ }++ #[test]+ fn anchor_missing_required_flags_uses_word_defaults() {+ // §20.4.2.3 marks relativeHeight/behindDoc/locked/allowOverlap required,+ // but a nonconformant anchor that omits them must still parse — a single+ // bad anchor must not abort the whole-document parse — falling back to+ // Word's effective defaults.+ let img = parse_anchor(+ r#"<anchor distT="0" distB="0" distL="0" distR="0">+ <positionH relativeFrom="column"><posOffset>0</posOffset></positionH>+ <positionV relativeFrom="paragraph"><posOffset>0</posOffset></positionV>+ <wrapNone/>+ <extent cx="100" cy="100"/>+ <docPr id="9" name="lenient"/>+ <graphic><graphicData/></graphic>+ </anchor>"#,+ );+ let ImagePlacement::Anchor(a) = &img.placement else {+ panic!("expected Anchor");+ };+ assert!(!a.behind_text, "behindDoc defaults to false");+ assert!(!a.lock_anchor, "locked defaults to false");+ assert!(a.allow_overlap, "allowOverlap defaults to true");+ assert_eq!(a.relative_height, 0, "relativeHeight defaults to 0");+ }++ #[test]+ fn wsp_graphic_content() {+ let img = parse_inline(+ r#"<inline>+ <extent cx="100" cy="100"/>+ <effectExtent l="0" t="0" r="0" b="0"/>+ <docPr id="8" name="shape"/>+ <graphic><graphicData>+ <wsp>+ <cNvPr id="8" name="S8"/>+ <spPr><prstGeom prst="rect"/></spPr>+ <bodyPr/>+ </wsp>+ </graphicData></graphic>+ </inline>"#,+ );+ assert!(matches!(+ img.graphic,+ Some(GraphicContent::WordProcessingShape(_))+ ));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/color.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/color.rsnew file mode 100644index 0000000..99dfb2e--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/color.rs@@ -0,0 +1,1039 @@+//! DrawingML color schema (§20.1.2.3 EG_ColorChoice).+//!+//! Each color-choice element (`srgbClr`, `scRgbClr`, `hslClr`, `sysClr`,+//! `schemeClr`, `prstClr`) carries attributes for its base color plus an+//! ordered list of color-transform children (`tint`, `shade`, `alpha`, etc.).+//!+//! During Phase 5A these schemas are additive — consumers (fill, stroke,+//! effect) still use the procedural `drawing/color.rs` parser. When those+//! parsers migrate in Phase 5B+, they will switch to `DrawingColorXml`.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::dimension::{Dimension, SixtieThousandthDeg, ThousandthPercent};+use crate::docx::model::{+ ColorTransform, DrawingColor, PresetColorVal, SchemeColorVal, SystemColorVal,+};+use crate::docx::parse::primitives::colors::RgbHexU32;++// ── Top-level choice ──────────────────────────────────────────────────────++/// §20.1.2.3 EG_ColorChoice — exactly one of six color representations.+#[derive(Debug, Deserialize)]+pub enum DrawingColorXml {+ #[serde(rename = "srgbClr")]+ Srgb(SrgbClrXml),+ #[serde(rename = "scRgbClr")]+ ScRgb(ScRgbClrXml),+ #[serde(rename = "hslClr")]+ Hsl(HslClrXml),+ #[serde(rename = "sysClr")]+ Sys(SysClrXml),+ #[serde(rename = "schemeClr")]+ Scheme(SchemeClrXml),+ #[serde(rename = "prstClr")]+ Prst(PrstClrXml),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++/// Convert a color-choice element, or `None` if it is one we don't model.+///+/// Vendoring divergence from dxpdf: upstream is an infallible `From`, which is+/// only possible while every color element is known. With an `Other` catch-all+/// there is no honest `DrawingColor` to return for an unknown element — the+/// model has no "unspecified" variant — and inventing one (black) would be+/// silent corruption. Callers drop the color instead.+pub(crate) fn to_drawing_color(c: DrawingColorXml) -> Option<DrawingColor> {+ Some(match c {+ DrawingColorXml::Other => return None,+ DrawingColorXml::Srgb(x) => DrawingColor::Srgb {+ rgb: x.val?.0,+ transforms: convert_transforms(x.transforms),+ },+ DrawingColorXml::ScRgb(x) => DrawingColor::ScRgb {+ r: x.r,+ g: x.g,+ b: x.b,+ transforms: convert_transforms(x.transforms),+ },+ DrawingColorXml::Hsl(x) => DrawingColor::Hsl {+ hue: x.hue,+ sat: x.sat,+ lum: x.lum,+ transforms: convert_transforms(x.transforms),+ },+ DrawingColorXml::Sys(x) => DrawingColor::Sys {+ name: x.val?.into(),+ last_clr: x.last_clr.map(|c| c.0),+ transforms: convert_transforms(x.transforms),+ },+ DrawingColorXml::Scheme(x) => DrawingColor::Scheme {+ name: x.val?.into(),+ transforms: convert_transforms(x.transforms),+ },+ DrawingColorXml::Prst(x) => DrawingColor::Prst {+ name: x.val?.into(),+ transforms: convert_transforms(x.transforms),+ },+ })+}++// ── Base color variants ───────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct SrgbClrXml {+ /// §20.1.10.41 ST_HexColorRGB — 6 hex digits.+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub val: Option<RgbHexU32>,+ #[serde(rename = "$value", default)]+ pub transforms: Vec<ColorTransformXml>,+}++#[derive(Debug, Deserialize)]+pub struct ScRgbClrXml {+ #[serde(+ rename = "@r",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub r: Dimension<ThousandthPercent>,+ #[serde(+ rename = "@g",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub g: Dimension<ThousandthPercent>,+ #[serde(+ rename = "@b",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub b: Dimension<ThousandthPercent>,+ #[serde(rename = "$value", default)]+ pub transforms: Vec<ColorTransformXml>,+}++#[derive(Debug, Deserialize)]+pub struct HslClrXml {+ #[serde(+ rename = "@hue",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub hue: Dimension<SixtieThousandthDeg>,+ #[serde(+ rename = "@sat",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub sat: Dimension<ThousandthPercent>,+ #[serde(+ rename = "@lum",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub lum: Dimension<ThousandthPercent>,+ #[serde(rename = "$value", default)]+ pub transforms: Vec<ColorTransformXml>,+}++#[derive(Debug, Deserialize)]+pub struct SysClrXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub val: Option<StSystemColorVal>,+ #[serde(+ rename = "@lastClr",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub last_clr: Option<RgbHexU32>,+ #[serde(rename = "$value", default)]+ pub transforms: Vec<ColorTransformXml>,+}++#[derive(Debug, Deserialize)]+pub struct SchemeClrXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub val: Option<StSchemeColorVal>,+ #[serde(rename = "$value", default)]+ pub transforms: Vec<ColorTransformXml>,+}++#[derive(Debug, Deserialize)]+pub struct PrstClrXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub val: Option<StPresetColorVal>,+ #[serde(rename = "$value", default)]+ pub transforms: Vec<ColorTransformXml>,+}++// ── Color transforms (§20.1.2.3.*) ────────────────────────────────────────++/// Ordered list of transform children; each element is its own variant.+#[derive(Debug, Deserialize)]+pub enum ColorTransformXml {+ // Parameterless transforms — deserialize from empty elements.+ #[serde(rename = "comp")]+ Comp,+ #[serde(rename = "inv")]+ Inv,+ #[serde(rename = "gray")]+ Gray,+ #[serde(rename = "gamma")]+ Gamma,+ #[serde(rename = "invGamma")]+ InvGamma,++ // Percentage-valued (thousandth-percent)+ #[serde(rename = "tint")]+ Tint(PctVal),+ #[serde(rename = "shade")]+ Shade(PctVal),+ #[serde(rename = "alpha")]+ Alpha(PctVal),+ #[serde(rename = "alphaOff")]+ AlphaOff(PctVal),+ #[serde(rename = "alphaMod")]+ AlphaMod(PctVal),+ #[serde(rename = "hueMod")]+ HueMod(PctVal),+ #[serde(rename = "sat")]+ Sat(PctVal),+ #[serde(rename = "satOff")]+ SatOff(PctVal),+ #[serde(rename = "satMod")]+ SatMod(PctVal),+ #[serde(rename = "lum")]+ Lum(PctVal),+ #[serde(rename = "lumOff")]+ LumOff(PctVal),+ #[serde(rename = "lumMod")]+ LumMod(PctVal),+ #[serde(rename = "red")]+ Red(PctVal),+ #[serde(rename = "redOff")]+ RedOff(PctVal),+ #[serde(rename = "redMod")]+ RedMod(PctVal),+ #[serde(rename = "green")]+ Green(PctVal),+ #[serde(rename = "greenOff")]+ GreenOff(PctVal),+ #[serde(rename = "greenMod")]+ GreenMod(PctVal),+ #[serde(rename = "blue")]+ Blue(PctVal),+ #[serde(rename = "blueOff")]+ BlueOff(PctVal),+ #[serde(rename = "blueMod")]+ BlueMod(PctVal),++ // Angle-valued (60000ths of a degree)+ #[serde(rename = "hue")]+ Hue(AngleVal),+ #[serde(rename = "hueOff")]+ HueOff(AngleVal),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++#[derive(Debug, Deserialize)]+pub struct PctVal {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub val: Dimension<ThousandthPercent>,+}++#[derive(Debug, Deserialize)]+pub struct AngleVal {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub val: Dimension<SixtieThousandthDeg>,+}++fn convert_transforms(xs: Vec<ColorTransformXml>) -> Vec<ColorTransform> {+ xs.into_iter().filter_map(to_color_transform).collect()+}++/// Convert one color transform, or `None` for an element we don't model.+///+/// Dropping an unknown transform is the right degradation: transforms compose+/// in document order, so omitting one leaves the others applied rather than+/// discarding the whole color.+fn to_color_transform(c: ColorTransformXml) -> Option<ColorTransform> {+ use ColorTransform as Self_;+ use ColorTransformXml as X;+ Some(match c {+ X::Other => return None,+ X::Comp => Self_::Comp,+ X::Inv => Self_::Inv,+ X::Gray => Self_::Gray,+ X::Gamma => Self_::Gamma,+ X::InvGamma => Self_::InvGamma,+ X::Tint(v) => Self_::Tint(v.val),+ X::Shade(v) => Self_::Shade(v.val),+ X::Alpha(v) => Self_::Alpha(v.val),+ X::AlphaOff(v) => Self_::AlphaOff(v.val),+ X::AlphaMod(v) => Self_::AlphaMod(v.val),+ X::HueMod(v) => Self_::HueMod(v.val),+ X::Sat(v) => Self_::Sat(v.val),+ X::SatOff(v) => Self_::SatOff(v.val),+ X::SatMod(v) => Self_::SatMod(v.val),+ X::Lum(v) => Self_::Lum(v.val),+ X::LumOff(v) => Self_::LumOff(v.val),+ X::LumMod(v) => Self_::LumMod(v.val),+ X::Red(v) => Self_::Red(v.val),+ X::RedOff(v) => Self_::RedOff(v.val),+ X::RedMod(v) => Self_::RedMod(v.val),+ X::Green(v) => Self_::Green(v.val),+ X::GreenOff(v) => Self_::GreenOff(v.val),+ X::GreenMod(v) => Self_::GreenMod(v.val),+ X::Blue(v) => Self_::Blue(v.val),+ X::BlueOff(v) => Self_::BlueOff(v.val),+ X::BlueMod(v) => Self_::BlueMod(v.val),+ X::Hue(v) => Self_::Hue(v.val),+ X::HueOff(v) => Self_::HueOff(v.val),+ })+}++// ── ST enums ──────────────────────────────────────────────────────────────++/// §20.1.10.54 ST_SchemeColorVal — theme color slot.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StSchemeColorVal {+ Bg1,+ Tx1,+ Bg2,+ Tx2,+ Accent1,+ Accent2,+ Accent3,+ Accent4,+ Accent5,+ Accent6,+ Hlink,+ FolHlink,+ PhClr,+ Dk1,+ Lt1,+ Dk2,+ Lt2,+}++impl From<StSchemeColorVal> for SchemeColorVal {+ fn from(s: StSchemeColorVal) -> Self {+ match s {+ StSchemeColorVal::Bg1 => Self::Bg1,+ StSchemeColorVal::Tx1 => Self::Tx1,+ StSchemeColorVal::Bg2 => Self::Bg2,+ StSchemeColorVal::Tx2 => Self::Tx2,+ StSchemeColorVal::Accent1 => Self::Accent1,+ StSchemeColorVal::Accent2 => Self::Accent2,+ StSchemeColorVal::Accent3 => Self::Accent3,+ StSchemeColorVal::Accent4 => Self::Accent4,+ StSchemeColorVal::Accent5 => Self::Accent5,+ StSchemeColorVal::Accent6 => Self::Accent6,+ StSchemeColorVal::Hlink => Self::Hlink,+ StSchemeColorVal::FolHlink => Self::FolHlink,+ StSchemeColorVal::PhClr => Self::PhClr,+ StSchemeColorVal::Dk1 => Self::Dk1,+ StSchemeColorVal::Lt1 => Self::Lt1,+ StSchemeColorVal::Dk2 => Self::Dk2,+ StSchemeColorVal::Lt2 => Self::Lt2,+ }+ }+}++/// §20.1.10.57 ST_SystemColorVal. `3d*` variants need explicit rename+/// because `rename_all="camelCase"` would produce `threeDDkShadow`, not the+/// spec value `3dDkShadow`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StSystemColorVal {+ ScrollBar,+ Background,+ ActiveCaption,+ InactiveCaption,+ Menu,+ Window,+ WindowFrame,+ MenuText,+ WindowText,+ CaptionText,+ ActiveBorder,+ InactiveBorder,+ AppWorkspace,+ Highlight,+ HighlightText,+ BtnFace,+ BtnShadow,+ GrayText,+ BtnText,+ InactiveCaptionText,+ BtnHighlight,+ #[serde(rename = "3dDkShadow")]+ ThreeDDkShadow,+ #[serde(rename = "3dLight")]+ ThreeDLight,+ InfoText,+ InfoBk,+ HotLight,+ GradientActiveCaption,+ GradientInactiveCaption,+ MenuHighlight,+ MenuBar,+}++impl From<StSystemColorVal> for SystemColorVal {+ fn from(s: StSystemColorVal) -> Self {+ use StSystemColorVal as X;+ match s {+ X::ScrollBar => Self::ScrollBar,+ X::Background => Self::Background,+ X::ActiveCaption => Self::ActiveCaption,+ X::InactiveCaption => Self::InactiveCaption,+ X::Menu => Self::Menu,+ X::Window => Self::Window,+ X::WindowFrame => Self::WindowFrame,+ X::MenuText => Self::MenuText,+ X::WindowText => Self::WindowText,+ X::CaptionText => Self::CaptionText,+ X::ActiveBorder => Self::ActiveBorder,+ X::InactiveBorder => Self::InactiveBorder,+ X::AppWorkspace => Self::AppWorkspace,+ X::Highlight => Self::Highlight,+ X::HighlightText => Self::HighlightText,+ X::BtnFace => Self::BtnFace,+ X::BtnShadow => Self::BtnShadow,+ X::GrayText => Self::GrayText,+ X::BtnText => Self::BtnText,+ X::InactiveCaptionText => Self::InactiveCaptionText,+ X::BtnHighlight => Self::BtnHighlight,+ X::ThreeDDkShadow => Self::ThreeDDkShadow,+ X::ThreeDLight => Self::ThreeDLight,+ X::InfoText => Self::InfoText,+ X::InfoBk => Self::InfoBk,+ X::HotLight => Self::HotLight,+ X::GradientActiveCaption => Self::GradientActiveCaption,+ X::GradientInactiveCaption => Self::GradientInactiveCaption,+ X::MenuHighlight => Self::MenuHighlight,+ X::MenuBar => Self::MenuBar,+ }+ }+}++/// §20.1.10.47 ST_PresetColorVal — 140+ named colors.+///+/// All variants match `rename_all="camelCase"` since the OOXML spec uses+/// camelCase consistently for this palette.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPresetColorVal {+ AliceBlue,+ AntiqueWhite,+ Aqua,+ Aquamarine,+ Azure,+ Beige,+ Bisque,+ Black,+ BlanchedAlmond,+ Blue,+ BlueViolet,+ Brown,+ BurlyWood,+ CadetBlue,+ Chartreuse,+ Chocolate,+ Coral,+ CornflowerBlue,+ Cornsilk,+ Crimson,+ Cyan,+ DarkBlue,+ DarkCyan,+ DarkGoldenrod,+ DarkGray,+ DarkGreen,+ DarkGrey,+ DarkKhaki,+ DarkMagenta,+ DarkOliveGreen,+ DarkOrange,+ DarkOrchid,+ DarkRed,+ DarkSalmon,+ DarkSeaGreen,+ DarkSlateBlue,+ DarkSlateGray,+ DarkSlateGrey,+ DarkTurquoise,+ DarkViolet,+ DeepPink,+ DeepSkyBlue,+ DimGray,+ DimGrey,+ DkBlue,+ DkCyan,+ DkGoldenrod,+ DkGray,+ DkGreen,+ DkGrey,+ DkKhaki,+ DkMagenta,+ DkOliveGreen,+ DkOrange,+ DkOrchid,+ DkRed,+ DkSalmon,+ DkSeaGreen,+ DkSlateBlue,+ DkSlateGray,+ DkSlateGrey,+ DkTurquoise,+ DkViolet,+ DodgerBlue,+ Firebrick,+ FloralWhite,+ ForestGreen,+ Fuchsia,+ Gainsboro,+ GhostWhite,+ Gold,+ Goldenrod,+ Gray,+ Green,+ GreenYellow,+ Grey,+ Honeydew,+ HotPink,+ IndianRed,+ Indigo,+ Ivory,+ Khaki,+ Lavender,+ LavenderBlush,+ LawnGreen,+ LemonChiffon,+ LightBlue,+ LightCoral,+ LightCyan,+ LightGoldenrodYellow,+ LightGray,+ LightGreen,+ LightGrey,+ LightPink,+ LightSalmon,+ LightSeaGreen,+ LightSkyBlue,+ LightSlateGray,+ LightSlateGrey,+ LightSteelBlue,+ LightYellow,+ Lime,+ LimeGreen,+ Linen,+ LtBlue,+ LtCoral,+ LtCyan,+ LtGoldenrodYellow,+ LtGray,+ LtGreen,+ LtGrey,+ LtPink,+ LtSalmon,+ LtSeaGreen,+ LtSkyBlue,+ LtSlateGray,+ LtSlateGrey,+ LtSteelBlue,+ LtYellow,+ Magenta,+ Maroon,+ MedAquamarine,+ MedBlue,+ MedOrchid,+ MedPurple,+ MedSeaGreen,+ MedSlateBlue,+ MedSpringGreen,+ MedTurquoise,+ MedVioletRed,+ MediumAquamarine,+ MediumBlue,+ MediumOrchid,+ MediumPurple,+ MediumSeaGreen,+ MediumSlateBlue,+ MediumSpringGreen,+ MediumTurquoise,+ MediumVioletRed,+ MidnightBlue,+ MintCream,+ MistyRose,+ Moccasin,+ NavajoWhite,+ Navy,+ OldLace,+ Olive,+ OliveDrab,+ Orange,+ OrangeRed,+ Orchid,+ PaleGoldenrod,+ PaleGreen,+ PaleTurquoise,+ PaleVioletRed,+ PapayaWhip,+ PeachPuff,+ Peru,+ Pink,+ Plum,+ PowderBlue,+ Purple,+ Red,+ RosyBrown,+ RoyalBlue,+ SaddleBrown,+ Salmon,+ SandyBrown,+ SeaGreen,+ SeaShell,+ Sienna,+ Silver,+ SkyBlue,+ SlateBlue,+ SlateGray,+ SlateGrey,+ Snow,+ SpringGreen,+ SteelBlue,+ Tan,+ Teal,+ Thistle,+ Tomato,+ Turquoise,+ Violet,+ Wheat,+ White,+ WhiteSmoke,+ Yellow,+ YellowGreen,+}++impl From<StPresetColorVal> for PresetColorVal {+ fn from(s: StPresetColorVal) -> Self {+ use StPresetColorVal as X;+ match s {+ X::AliceBlue => Self::AliceBlue,+ X::AntiqueWhite => Self::AntiqueWhite,+ X::Aqua => Self::Aqua,+ X::Aquamarine => Self::Aquamarine,+ X::Azure => Self::Azure,+ X::Beige => Self::Beige,+ X::Bisque => Self::Bisque,+ X::Black => Self::Black,+ X::BlanchedAlmond => Self::BlanchedAlmond,+ X::Blue => Self::Blue,+ X::BlueViolet => Self::BlueViolet,+ X::Brown => Self::Brown,+ X::BurlyWood => Self::BurlyWood,+ X::CadetBlue => Self::CadetBlue,+ X::Chartreuse => Self::Chartreuse,+ X::Chocolate => Self::Chocolate,+ X::Coral => Self::Coral,+ X::CornflowerBlue => Self::CornflowerBlue,+ X::Cornsilk => Self::Cornsilk,+ X::Crimson => Self::Crimson,+ X::Cyan => Self::Cyan,+ X::DarkBlue => Self::DarkBlue,+ X::DarkCyan => Self::DarkCyan,+ X::DarkGoldenrod => Self::DarkGoldenrod,+ X::DarkGray => Self::DarkGray,+ X::DarkGreen => Self::DarkGreen,+ X::DarkGrey => Self::DarkGrey,+ X::DarkKhaki => Self::DarkKhaki,+ X::DarkMagenta => Self::DarkMagenta,+ X::DarkOliveGreen => Self::DarkOliveGreen,+ X::DarkOrange => Self::DarkOrange,+ X::DarkOrchid => Self::DarkOrchid,+ X::DarkRed => Self::DarkRed,+ X::DarkSalmon => Self::DarkSalmon,+ X::DarkSeaGreen => Self::DarkSeaGreen,+ X::DarkSlateBlue => Self::DarkSlateBlue,+ X::DarkSlateGray => Self::DarkSlateGray,+ X::DarkSlateGrey => Self::DarkSlateGrey,+ X::DarkTurquoise => Self::DarkTurquoise,+ X::DarkViolet => Self::DarkViolet,+ X::DeepPink => Self::DeepPink,+ X::DeepSkyBlue => Self::DeepSkyBlue,+ X::DimGray => Self::DimGray,+ X::DimGrey => Self::DimGrey,+ X::DkBlue => Self::DkBlue,+ X::DkCyan => Self::DkCyan,+ X::DkGoldenrod => Self::DkGoldenrod,+ X::DkGray => Self::DkGray,+ X::DkGreen => Self::DkGreen,+ X::DkGrey => Self::DkGrey,+ X::DkKhaki => Self::DkKhaki,+ X::DkMagenta => Self::DkMagenta,+ X::DkOliveGreen => Self::DkOliveGreen,+ X::DkOrange => Self::DkOrange,+ X::DkOrchid => Self::DkOrchid,+ X::DkRed => Self::DkRed,+ X::DkSalmon => Self::DkSalmon,+ X::DkSeaGreen => Self::DkSeaGreen,+ X::DkSlateBlue => Self::DkSlateBlue,+ X::DkSlateGray => Self::DkSlateGray,+ X::DkSlateGrey => Self::DkSlateGrey,+ X::DkTurquoise => Self::DkTurquoise,+ X::DkViolet => Self::DkViolet,+ X::DodgerBlue => Self::DodgerBlue,+ X::Firebrick => Self::Firebrick,+ X::FloralWhite => Self::FloralWhite,+ X::ForestGreen => Self::ForestGreen,+ X::Fuchsia => Self::Fuchsia,+ X::Gainsboro => Self::Gainsboro,+ X::GhostWhite => Self::GhostWhite,+ X::Gold => Self::Gold,+ X::Goldenrod => Self::Goldenrod,+ X::Gray => Self::Gray,+ X::Green => Self::Green,+ X::GreenYellow => Self::GreenYellow,+ X::Grey => Self::Grey,+ X::Honeydew => Self::Honeydew,+ X::HotPink => Self::HotPink,+ X::IndianRed => Self::IndianRed,+ X::Indigo => Self::Indigo,+ X::Ivory => Self::Ivory,+ X::Khaki => Self::Khaki,+ X::Lavender => Self::Lavender,+ X::LavenderBlush => Self::LavenderBlush,+ X::LawnGreen => Self::LawnGreen,+ X::LemonChiffon => Self::LemonChiffon,+ X::LightBlue => Self::LightBlue,+ X::LightCoral => Self::LightCoral,+ X::LightCyan => Self::LightCyan,+ X::LightGoldenrodYellow => Self::LightGoldenrodYellow,+ X::LightGray => Self::LightGray,+ X::LightGreen => Self::LightGreen,+ X::LightGrey => Self::LightGrey,+ X::LightPink => Self::LightPink,+ X::LightSalmon => Self::LightSalmon,+ X::LightSeaGreen => Self::LightSeaGreen,+ X::LightSkyBlue => Self::LightSkyBlue,+ X::LightSlateGray => Self::LightSlateGray,+ X::LightSlateGrey => Self::LightSlateGrey,+ X::LightSteelBlue => Self::LightSteelBlue,+ X::LightYellow => Self::LightYellow,+ X::Lime => Self::Lime,+ X::LimeGreen => Self::LimeGreen,+ X::Linen => Self::Linen,+ X::LtBlue => Self::LtBlue,+ X::LtCoral => Self::LtCoral,+ X::LtCyan => Self::LtCyan,+ X::LtGoldenrodYellow => Self::LtGoldenrodYellow,+ X::LtGray => Self::LtGray,+ X::LtGreen => Self::LtGreen,+ X::LtGrey => Self::LtGrey,+ X::LtPink => Self::LtPink,+ X::LtSalmon => Self::LtSalmon,+ X::LtSeaGreen => Self::LtSeaGreen,+ X::LtSkyBlue => Self::LtSkyBlue,+ X::LtSlateGray => Self::LtSlateGray,+ X::LtSlateGrey => Self::LtSlateGrey,+ X::LtSteelBlue => Self::LtSteelBlue,+ X::LtYellow => Self::LtYellow,+ X::Magenta => Self::Magenta,+ X::Maroon => Self::Maroon,+ X::MedAquamarine => Self::MedAquamarine,+ X::MedBlue => Self::MedBlue,+ X::MedOrchid => Self::MedOrchid,+ X::MedPurple => Self::MedPurple,+ X::MedSeaGreen => Self::MedSeaGreen,+ X::MedSlateBlue => Self::MedSlateBlue,+ X::MedSpringGreen => Self::MedSpringGreen,+ X::MedTurquoise => Self::MedTurquoise,+ X::MedVioletRed => Self::MedVioletRed,+ X::MediumAquamarine => Self::MediumAquamarine,+ X::MediumBlue => Self::MediumBlue,+ X::MediumOrchid => Self::MediumOrchid,+ X::MediumPurple => Self::MediumPurple,+ X::MediumSeaGreen => Self::MediumSeaGreen,+ X::MediumSlateBlue => Self::MediumSlateBlue,+ X::MediumSpringGreen => Self::MediumSpringGreen,+ X::MediumTurquoise => Self::MediumTurquoise,+ X::MediumVioletRed => Self::MediumVioletRed,+ X::MidnightBlue => Self::MidnightBlue,+ X::MintCream => Self::MintCream,+ X::MistyRose => Self::MistyRose,+ X::Moccasin => Self::Moccasin,+ X::NavajoWhite => Self::NavajoWhite,+ X::Navy => Self::Navy,+ X::OldLace => Self::OldLace,+ X::Olive => Self::Olive,+ X::OliveDrab => Self::OliveDrab,+ X::Orange => Self::Orange,+ X::OrangeRed => Self::OrangeRed,+ X::Orchid => Self::Orchid,+ X::PaleGoldenrod => Self::PaleGoldenrod,+ X::PaleGreen => Self::PaleGreen,+ X::PaleTurquoise => Self::PaleTurquoise,+ X::PaleVioletRed => Self::PaleVioletRed,+ X::PapayaWhip => Self::PapayaWhip,+ X::PeachPuff => Self::PeachPuff,+ X::Peru => Self::Peru,+ X::Pink => Self::Pink,+ X::Plum => Self::Plum,+ X::PowderBlue => Self::PowderBlue,+ X::Purple => Self::Purple,+ X::Red => Self::Red,+ X::RosyBrown => Self::RosyBrown,+ X::RoyalBlue => Self::RoyalBlue,+ X::SaddleBrown => Self::SaddleBrown,+ X::Salmon => Self::Salmon,+ X::SandyBrown => Self::SandyBrown,+ X::SeaGreen => Self::SeaGreen,+ X::SeaShell => Self::SeaShell,+ X::Sienna => Self::Sienna,+ X::Silver => Self::Silver,+ X::SkyBlue => Self::SkyBlue,+ X::SlateBlue => Self::SlateBlue,+ X::SlateGray => Self::SlateGray,+ X::SlateGrey => Self::SlateGrey,+ X::Snow => Self::Snow,+ X::SpringGreen => Self::SpringGreen,+ X::SteelBlue => Self::SteelBlue,+ X::Tan => Self::Tan,+ X::Teal => Self::Teal,+ X::Thistle => Self::Thistle,+ X::Tomato => Self::Tomato,+ X::Turquoise => Self::Turquoise,+ X::Violet => Self::Violet,+ X::Wheat => Self::Wheat,+ X::White => Self::White,+ X::WhiteSmoke => Self::WhiteSmoke,+ X::Yellow => Self::Yellow,+ X::YellowGreen => Self::YellowGreen,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> DrawingColor {+ // Wrap in a parent so the enum dispatches on the child's element name.+ let wrapped = format!(r#"<wrap xmlns:a="urn:a">{}</wrap>"#, xml);+ let (_tag, c): (String, DrawingColorXml) = {+ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "$value")]+ c: DrawingColorXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ (String::new(), w.c)+ };+ to_drawing_color(c).expect("test fixture uses a modelled color element")+ }++ #[test]+ fn srgb_with_no_transforms() {+ let c = parse(r#"<srgbClr val="FF0000"/>"#);+ assert!(matches!(c, DrawingColor::Srgb { rgb: 0xFF0000, .. }));+ assert!(c.transforms().is_empty());+ }++ #[test]+ fn srgb_with_transforms_preserves_order() {+ let c = parse(+ r#"<srgbClr val="4F81BD">+ <tint val="50000"/>+ <shade val="75000"/>+ <comp/>+ </srgbClr>"#,+ );+ match c {+ DrawingColor::Srgb { rgb, transforms } => {+ assert_eq!(rgb, 0x4F81BD);+ assert!(matches!(transforms[0], ColorTransform::Tint(d) if d.raw() == 50000));+ assert!(matches!(transforms[1], ColorTransform::Shade(d) if d.raw() == 75000));+ assert!(matches!(transforms[2], ColorTransform::Comp));+ }+ other => panic!("expected Srgb, got {other:?}"),+ }+ }++ #[test]+ fn scheme_color_with_lum_mods() {+ let c = parse(+ r#"<schemeClr val="accent1">+ <lumMod val="60000"/>+ <lumOff val="40000"/>+ </schemeClr>"#,+ );+ match c {+ DrawingColor::Scheme { name, transforms } => {+ assert_eq!(name, SchemeColorVal::Accent1);+ assert_eq!(transforms.len(), 2);+ }+ other => panic!("expected Scheme, got {other:?}"),+ }+ }++ #[test]+ fn sys_color_with_last_clr() {+ let c = parse(r#"<sysClr val="windowText" lastClr="000000"/>"#);+ match c {+ DrawingColor::Sys { name, last_clr, .. } => {+ assert_eq!(name, SystemColorVal::WindowText);+ assert_eq!(last_clr, Some(0));+ }+ other => panic!("expected Sys, got {other:?}"),+ }+ }++ #[test]+ fn sys_3d_dk_shadow_spec_rename() {+ let c = parse(r#"<sysClr val="3dDkShadow"/>"#);+ match c {+ DrawingColor::Sys { name, .. } => assert_eq!(name, SystemColorVal::ThreeDDkShadow),+ other => panic!("expected Sys, got {other:?}"),+ }+ }++ #[test]+ fn scrgb_color_components() {+ let c = parse(r#"<scRgbClr r="50000" g="25000" b="10000"/>"#);+ match c {+ DrawingColor::ScRgb { r, g, b, .. } => {+ assert_eq!(r.raw(), 50000);+ assert_eq!(g.raw(), 25000);+ assert_eq!(b.raw(), 10000);+ }+ other => panic!("expected ScRgb, got {other:?}"),+ }+ }++ #[test]+ fn hsl_color_components() {+ let c = parse(r#"<hslClr hue="14400000" sat="50000" lum="50000"/>"#);+ match c {+ DrawingColor::Hsl { hue, sat, lum, .. } => {+ assert_eq!(hue.raw(), 14_400_000);+ assert_eq!(sat.raw(), 50000);+ assert_eq!(lum.raw(), 50000);+ }+ other => panic!("expected Hsl, got {other:?}"),+ }+ }++ #[test]+ fn preset_color_alice_blue() {+ let c = parse(r#"<prstClr val="aliceBlue"/>"#);+ match c {+ DrawingColor::Prst { name, .. } => assert_eq!(name, PresetColorVal::AliceBlue),+ other => panic!("expected Prst, got {other:?}"),+ }+ }++ #[test]+ fn preset_color_dk_alias() {+ let c = parse(r#"<prstClr val="dkBlue"/>"#);+ match c {+ DrawingColor::Prst { name, .. } => assert_eq!(name, PresetColorVal::DkBlue),+ other => panic!("expected Prst, got {other:?}"),+ }+ }++ #[test]+ fn hue_transform_preserves_angle() {+ let c = parse(r#"<srgbClr val="FF0000"><hue val="3600000"/></srgbClr>"#);+ match c {+ DrawingColor::Srgb { transforms, .. } => {+ assert!(matches!(&transforms[0], ColorTransform::Hue(d) if d.raw() == 3_600_000));+ }+ other => panic!("expected Srgb, got {other:?}"),+ }+ }++ #[test]+ fn parameterless_transforms() {+ let c = parse(+ r#"<srgbClr val="FF0000">+ <inv/>+ <gray/>+ <gamma/>+ <invGamma/>+ </srgbClr>"#,+ );+ let transforms = match c {+ DrawingColor::Srgb { transforms, .. } => transforms,+ _ => panic!(),+ };+ assert_eq!(transforms.len(), 4);+ assert!(matches!(transforms[0], ColorTransform::Inv));+ assert!(matches!(transforms[1], ColorTransform::Gray));+ assert!(matches!(transforms[2], ColorTransform::Gamma));+ assert!(matches!(transforms[3], ColorTransform::InvGamma));+ }++ /// Upstream asserted that an unknown preset color is a hard error. We+ /// deliberately reversed that: an unrecognized value must degrade to "no+ /// color" rather than abort the document. The color element is dropped,+ /// and the containing fill/effect drops with it.+ #[test]+ fn unknown_preset_color_drops_the_color_instead_of_failing() {+ let x: PrstClrXml = quick_xml::de::from_str(r#"<x val="unknownColor"/>"#)+ .expect("an unknown preset color must not fail the parse");+ assert!(x.val.is_none());++ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "$value")]+ c: DrawingColorXml,+ }+ let w: Wrap = quick_xml::de::from_str(r#"<wrap><prstClr val="unknownColor"/></wrap>"#)+ .expect("an unknown preset color must not fail the parse");+ assert!(to_drawing_color(w.c).is_none());+ }++ /// A known preset still resolves — the leniency must not swallow good input.+ #[test]+ fn known_preset_color_still_parses() {+ let x: PrstClrXml =+ quick_xml::de::from_str(r#"<x val="red"/>"#).expect("known preset must parse");+ assert!(x.val.is_some());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/effect.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/effect.rsnew file mode 100644index 0000000..8059c52--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/effect.rs@@ -0,0 +1,643 @@+//! DrawingML effect schema (§20.1.8.24 CT_EffectList).+//!+//! Flat `<a:effectLst>` with eight child effect types, preserving document+//! order. Consumes `DrawingColorXml` and `DrawingFillXml`.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::dimension::{Dimension, Emu, SixtieThousandthDeg, ThousandthPercent};+use crate::docx::model::{+ BlendMode, BlurEffect, DrawingColor, DrawingFill, Effect, EffectList, FillOverlayEffect,+ GlowEffect, InnerShadowEffect, OuterShadowEffect, PresetShadowEffect, PresetShadowVal,+ RectAlignment, ReflectionEffect, SoftEdgeEffect,+};++use super::color::{DrawingColorXml, to_drawing_color};+use super::fill::{AttrBool, DrawingFillXml, StRectAlignment};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++// ── Top-level effect list ─────────────────────────────────────────────────++#[derive(Debug, Deserialize, Default)]+pub struct EffectListXml {+ #[serde(rename = "$value", default)]+ pub effects: Vec<EffectXml>,+}++#[derive(Debug, Deserialize)]+pub enum EffectXml {+ #[serde(rename = "blur")]+ Blur(BlurXml),+ #[serde(rename = "reflection")]+ Reflection(ReflectionXml),+ #[serde(rename = "softEdge")]+ SoftEdge(SoftEdgeXml),+ #[serde(rename = "fillOverlay")]+ FillOverlay(FillOverlayXml),+ #[serde(rename = "glow")]+ Glow(GlowXml),+ #[serde(rename = "innerShdw")]+ InnerShdw(InnerShdwXml),+ #[serde(rename = "outerShdw")]+ OuterShdw(OuterShdwXml),+ #[serde(rename = "prstShdw")]+ PrstShdw(PrstShdwXml),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++// ── Parameter-only effects ────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct BlurXml {+ #[serde(+ rename = "@rad",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub rad: Option<Dimension<Emu>>,+ #[serde(rename = "@grow", default)]+ pub grow: Option<AttrBool>,+}++#[derive(Debug, Deserialize)]+pub struct SoftEdgeXml {+ #[serde(+ rename = "@rad",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub rad: Option<Dimension<Emu>>,+}++#[derive(Debug, Deserialize)]+pub struct ReflectionXml {+ #[serde(+ rename = "@blurRad",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub blur_rad: Option<Dimension<Emu>>,+ #[serde(+ rename = "@stA",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub start_alpha: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@stPos",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub start_pos: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@endA",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub end_alpha: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@endPos",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub end_pos: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@dist",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub distance: Option<Dimension<Emu>>,+ #[serde(+ rename = "@dir",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub direction: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@fadeDir",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub fade_direction: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@sx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub sx: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@sy",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub sy: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@kx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub kx: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@ky",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub ky: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@algn",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub algn: Option<StRectAlignment>,+ #[serde(rename = "@rotWithShape", default)]+ pub rot_with_shape: Option<AttrBool>,+}++// ── Effects with fill/color children ──────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct FillOverlayXml {+ #[serde(+ rename = "@blend",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub blend: Option<StBlendMode>,+ #[serde(rename = "$value", default)]+ pub fill: Option<DrawingFillXml>,+}++#[derive(Debug, Deserialize)]+pub struct GlowXml {+ #[serde(+ rename = "@rad",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub rad: Option<Dimension<Emu>>,+ #[serde(rename = "$value", default)]+ pub color: Option<DrawingColorXml>,+}++#[derive(Debug, Deserialize)]+pub struct InnerShdwXml {+ #[serde(+ rename = "@blurRad",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub blur_rad: Option<Dimension<Emu>>,+ #[serde(+ rename = "@dist",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub distance: Option<Dimension<Emu>>,+ #[serde(+ rename = "@dir",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub direction: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(rename = "$value", default)]+ pub color: Option<DrawingColorXml>,+}++#[derive(Debug, Deserialize)]+pub struct OuterShdwXml {+ #[serde(+ rename = "@blurRad",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub blur_rad: Option<Dimension<Emu>>,+ #[serde(+ rename = "@dist",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub distance: Option<Dimension<Emu>>,+ #[serde(+ rename = "@dir",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub direction: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@sx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub sx: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@sy",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub sy: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@kx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub kx: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@ky",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub ky: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@algn",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub algn: Option<StRectAlignment>,+ #[serde(rename = "@rotWithShape", default)]+ pub rot_with_shape: Option<AttrBool>,+ #[serde(rename = "$value", default)]+ pub color: Option<DrawingColorXml>,+}++#[derive(Debug, Deserialize)]+pub struct PrstShdwXml {+ #[serde(+ rename = "@prst",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub prst: Option<StPresetShadowVal>,+ #[serde(+ rename = "@dist",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub distance: Option<Dimension<Emu>>,+ #[serde(+ rename = "@dir",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub direction: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(rename = "$value", default)]+ pub color: Option<DrawingColorXml>,+}++// ── ST enums ──────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StBlendMode {+ Over,+ Mult,+ Screen,+ Darken,+ Lighten,+}++impl From<StBlendMode> for BlendMode {+ fn from(s: StBlendMode) -> Self {+ match s {+ StBlendMode::Over => Self::Over,+ StBlendMode::Mult => Self::Mult,+ StBlendMode::Screen => Self::Screen,+ StBlendMode::Darken => Self::Darken,+ StBlendMode::Lighten => Self::Lighten,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPresetShadowVal {+ Shdw1,+ Shdw2,+ Shdw3,+ Shdw4,+ Shdw5,+ Shdw6,+ Shdw7,+ Shdw8,+ Shdw9,+ Shdw10,+ Shdw11,+ Shdw12,+ Shdw13,+ Shdw14,+ Shdw15,+ Shdw16,+ Shdw17,+ Shdw18,+ Shdw19,+ Shdw20,+}++impl From<StPresetShadowVal> for PresetShadowVal {+ fn from(s: StPresetShadowVal) -> Self {+ use StPresetShadowVal as X;+ match s {+ X::Shdw1 => Self::Shdw1,+ X::Shdw2 => Self::Shdw2,+ X::Shdw3 => Self::Shdw3,+ X::Shdw4 => Self::Shdw4,+ X::Shdw5 => Self::Shdw5,+ X::Shdw6 => Self::Shdw6,+ X::Shdw7 => Self::Shdw7,+ X::Shdw8 => Self::Shdw8,+ X::Shdw9 => Self::Shdw9,+ X::Shdw10 => Self::Shdw10,+ X::Shdw11 => Self::Shdw11,+ X::Shdw12 => Self::Shdw12,+ X::Shdw13 => Self::Shdw13,+ X::Shdw14 => Self::Shdw14,+ X::Shdw15 => Self::Shdw15,+ X::Shdw16 => Self::Shdw16,+ X::Shdw17 => Self::Shdw17,+ X::Shdw18 => Self::Shdw18,+ X::Shdw19 => Self::Shdw19,+ X::Shdw20 => Self::Shdw20,+ }+ }+}++// ── Conversion to model ───────────────────────────────────────────────────++impl From<EffectListXml> for EffectList {+ fn from(x: EffectListXml) -> Self {+ let mut effects = Vec::new();+ for e in x.effects {+ match Effect::try_from(e) {+ Ok(eff) => effects.push(eff),+ // §20.1.8.* — the color/fill child is mandatory for these+ // effects; a malformed one is dropped rather than silently+ // vanishing without a trace (cf. the geometry short-command warn).+ Err(name) => {+ log::warn!("drawing effect <{name}> dropped: missing required color/fill child")+ }+ }+ }+ Self { effects }+ }+}++impl TryFrom<EffectXml> for Effect {+ /// The name of the effect element that could not be built (missing its+ /// required color/fill child), for diagnostics.+ type Error = &'static str;+ fn try_from(e: EffectXml) -> Result<Self, Self::Error> {+ Ok(match e {+ // Unmodelled effect element — reported like a malformed one.+ EffectXml::Other => return Err("unknown"),+ EffectXml::Blur(b) => Effect::Blur(BlurEffect {+ radius: b.rad.unwrap_or_default(),+ grow: b.grow.map(|o| o.0),+ }),+ EffectXml::SoftEdge(s) => Effect::SoftEdge(SoftEdgeEffect {+ radius: s.rad.unwrap_or_default(),+ }),+ EffectXml::Reflection(r) => Effect::Reflection(reflection(r)),+ EffectXml::FillOverlay(f) => {+ // Spec requires a fill child; if missing, skip this effect.+ let fill: DrawingFill = f.fill.ok_or("fillOverlay")?.into();+ Effect::FillOverlay(FillOverlayEffect {+ fill,+ blend: f.blend.ok_or("fillOverlay")?.into(),+ })+ }+ EffectXml::Glow(g) => Effect::Glow(GlowEffect {+ radius: g.rad.unwrap_or_default(),+ color: to_drawing_color(g.color.ok_or("glow")?).ok_or("glow")?,+ }),+ EffectXml::InnerShdw(i) => {+ let color: DrawingColor =+ to_drawing_color(i.color.ok_or("innerShdw")?).ok_or("innerShdw")?;+ Effect::InnerShdw(InnerShadowEffect {+ blur_radius: i.blur_rad.unwrap_or_default(),+ distance: i.distance.unwrap_or_default(),+ direction: i.direction.unwrap_or_default(),+ color,+ })+ }+ EffectXml::OuterShdw(o) => {+ let color: DrawingColor =+ to_drawing_color(o.color.ok_or("outerShdw")?).ok_or("outerShdw")?;+ Effect::OuterShdw(OuterShadowEffect {+ blur_radius: o.blur_rad.unwrap_or_default(),+ distance: o.distance.unwrap_or_default(),+ direction: o.direction.unwrap_or_default(),+ sx: o.sx.unwrap_or(Dimension::new(100_000)),+ sy: o.sy.unwrap_or(Dimension::new(100_000)),+ kx: o.kx.unwrap_or_default(),+ ky: o.ky.unwrap_or_default(),+ alignment: o.algn.map(Into::into).unwrap_or(RectAlignment::B),+ rot_with_shape: o.rot_with_shape.map(|b| b.0),+ color,+ })+ }+ EffectXml::PrstShdw(p) => {+ let color: DrawingColor =+ to_drawing_color(p.color.ok_or("prstShdw")?).ok_or("prstShdw")?;+ Effect::PrstShdw(PresetShadowEffect {+ preset: p.prst.ok_or("prstShdw")?.into(),+ distance: p.distance.unwrap_or_default(),+ direction: p.direction.unwrap_or_default(),+ color,+ })+ }+ })+ }+}++fn reflection(r: ReflectionXml) -> ReflectionEffect {+ ReflectionEffect {+ blur_radius: r.blur_rad.unwrap_or_default(),+ start_alpha: r.start_alpha.unwrap_or(Dimension::new(100_000)),+ start_pos: r.start_pos.unwrap_or_default(),+ end_alpha: r.end_alpha.unwrap_or_default(),+ end_pos: r.end_pos.unwrap_or(Dimension::new(100_000)),+ distance: r.distance.unwrap_or_default(),+ direction: r.direction.unwrap_or_default(),+ fade_direction: r.fade_direction.unwrap_or(Dimension::new(5_400_000)),+ sx: r.sx.unwrap_or(Dimension::new(100_000)),+ sy: r.sy.unwrap_or(Dimension::new(100_000)),+ kx: r.kx.unwrap_or_default(),+ ky: r.ky.unwrap_or_default(),+ alignment: r.algn.map(Into::into).unwrap_or(RectAlignment::B),+ rot_with_shape: r.rot_with_shape.map(|b| b.0),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> EffectList {+ let wrapped = format!(+ r#"<wrap xmlns:a="urn:a" xmlns:r="urn:r"><effectLst>{}</effectLst></wrap>"#,+ xml+ );+ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "effectLst")]+ el: EffectListXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.el.into()+ }++ #[test]+ fn empty_effect_list() {+ let el = parse("");+ assert!(el.effects.is_empty());+ }++ #[test]+ fn blur_effect() {+ let el = parse(r#"<blur rad="50000" grow="1"/>"#);+ assert_eq!(el.effects.len(), 1);+ match &el.effects[0] {+ Effect::Blur(b) => {+ assert_eq!(b.radius.raw(), 50000);+ assert_eq!(b.grow, Some(true));+ }+ other => panic!("expected Blur, got {other:?}"),+ }+ }++ #[test]+ fn soft_edge_effect() {+ let el = parse(r#"<softEdge rad="25000"/>"#);+ match &el.effects[0] {+ Effect::SoftEdge(s) => assert_eq!(s.radius.raw(), 25000),+ other => panic!("expected SoftEdge, got {other:?}"),+ }+ }++ #[test]+ fn glow_with_color() {+ let el = parse(r#"<glow rad="40000"><srgbClr val="FF0000"/></glow>"#);+ match &el.effects[0] {+ Effect::Glow(g) => {+ assert_eq!(g.radius.raw(), 40000);+ assert!(matches!(+ g.color,+ crate::docx::model::DrawingColor::Srgb { rgb: 0xFF0000, .. }+ ));+ }+ other => panic!("expected Glow, got {other:?}"),+ }+ }++ #[test]+ fn outer_shadow_full() {+ let el = parse(+ r#"<outerShdw blurRad="50800" dist="38100" dir="2700000" sx="100000" sy="100000"+ algn="tl" rotWithShape="0">+ <srgbClr val="000000"/>+ </outerShdw>"#,+ );+ match &el.effects[0] {+ Effect::OuterShdw(o) => {+ assert_eq!(o.blur_radius.raw(), 50800);+ assert_eq!(o.direction.raw(), 2_700_000);+ assert_eq!(o.alignment, RectAlignment::Tl);+ assert_eq!(o.rot_with_shape, Some(false));+ }+ other => panic!("expected OuterShdw, got {other:?}"),+ }+ }++ #[test]+ fn inner_shadow_with_scheme_color() {+ let el = parse(+ r#"<innerShdw blurRad="12700" dist="6350" dir="13500000">+ <schemeClr val="accent1"/>+ </innerShdw>"#,+ );+ match &el.effects[0] {+ Effect::InnerShdw(i) => {+ assert_eq!(i.blur_radius.raw(), 12700);+ assert_eq!(i.direction.raw(), 13_500_000);+ assert!(matches!(+ i.color,+ crate::docx::model::DrawingColor::Scheme { .. }+ ));+ }+ other => panic!("expected InnerShdw, got {other:?}"),+ }+ }++ #[test]+ fn preset_shadow_with_color() {+ let el = parse(r#"<prstShdw prst="shdw5" dist="10000"><srgbClr val="808080"/></prstShdw>"#);+ match &el.effects[0] {+ Effect::PrstShdw(p) => {+ assert_eq!(p.preset, PresetShadowVal::Shdw5);+ assert_eq!(p.distance.raw(), 10000);+ }+ other => panic!("expected PrstShdw, got {other:?}"),+ }+ }++ #[test]+ fn fill_overlay_screen_blend() {+ let el = parse(+ r#"<fillOverlay blend="screen"><solidFill><srgbClr val="FFFFFF"/></solidFill></fillOverlay>"#,+ );+ match &el.effects[0] {+ Effect::FillOverlay(f) => {+ assert_eq!(f.blend, BlendMode::Screen);+ assert!(matches!(f.fill, DrawingFill::Solid(_)));+ }+ other => panic!("expected FillOverlay, got {other:?}"),+ }+ }++ #[test]+ fn reflection_preserves_order() {+ let el = parse(+ r#"<reflection blurRad="0" stA="50000" stPos="0" endA="10000" endPos="100000"+ dist="20000" dir="5400000" fadeDir="5400000"+ sx="100000" sy="-100000" kx="0" ky="0" algn="bl" rotWithShape="0"/>"#,+ );+ match &el.effects[0] {+ Effect::Reflection(r) => {+ assert_eq!(r.start_alpha.raw(), 50000);+ assert_eq!(r.sy.raw(), -100_000);+ assert_eq!(r.alignment, RectAlignment::Bl);+ }+ other => panic!("expected Reflection, got {other:?}"),+ }+ }++ #[test]+ fn effect_missing_required_color_is_dropped() {+ // glow/shadow require a color child; a malformed one is skipped (with a+ // warn) while well-formed siblings survive — the list never crashes.+ let el = parse(+ r#"<glow rad="40000"/>+ <outerShdw blurRad="0" dist="0" dir="0"/>+ <blur rad="5000"/>"#,+ );+ assert_eq!(el.effects.len(), 1);+ assert!(matches!(&el.effects[0], Effect::Blur(_)));+ }++ #[test]+ fn multiple_effects_in_order() {+ let el = parse(+ r#"<outerShdw blurRad="0" dist="0" dir="0"><srgbClr val="000000"/></outerShdw>+ <blur rad="5000"/>+ <softEdge rad="2500"/>"#,+ );+ assert_eq!(el.effects.len(), 3);+ assert!(matches!(&el.effects[0], Effect::OuterShdw(_)));+ assert!(matches!(&el.effects[1], Effect::Blur(_)));+ assert!(matches!(&el.effects[2], Effect::SoftEdge(_)));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/fill.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/fill.rsnew file mode 100644index 0000000..a584bfe--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/fill.rs@@ -0,0 +1,805 @@+//! DrawingML fill schema (§20.1.8 EG_FillProperties).+//!+//! Six-way choice: `noFill`, `solidFill`, `gradFill`, `blipFill`, `pattFill`,+//! `grpFill`. Each variant has its own attribute/child grammar. Consumes+//! `DrawingColorXml` from the color schema.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::dimension::{Dimension, Emu, SixtieThousandthDeg, ThousandthPercent};+use crate::docx::model::{+ Blip, BlipCompression, BlipFill, BlipFillKind, DrawingFill, GradientFill,+ GradientShadeProperties, GradientStop, PathShadeType, PatternFill, PresetPatternVal,+ RectAlignment, RelativeRect, StretchFill, TileFill, TileFlipMode,+};+pub use crate::docx::parse::primitives::AttrBool;++use super::color::{DrawingColorXml, to_drawing_color};++// ── Top-level choice ──────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub enum DrawingFillXml {+ #[serde(rename = "noFill")]+ NoFill(Empty),+ #[serde(rename = "grpFill")]+ GrpFill(Empty),+ #[serde(rename = "solidFill")]+ SolidFill(SolidFillXml),+ #[serde(rename = "gradFill")]+ GradFill(GradFillXml),+ #[serde(rename = "blipFill")]+ BlipFill(BlipFillXml),+ #[serde(rename = "pattFill")]+ PattFill(PattFillXml),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++#[derive(Debug, Deserialize, Default)]+pub struct Empty {}++impl From<DrawingFillXml> for DrawingFill {+ fn from(f: DrawingFillXml) -> Self {+ match f {+ // An unmodelled fill element degrades to no fill, matching the+ // existing treatment of an ill-formed solidFill below.+ DrawingFillXml::Other => Self::None,+ DrawingFillXml::NoFill(_) => Self::None,+ DrawingFillXml::GrpFill(_) => Self::Group,+ DrawingFillXml::SolidFill(s) => match s.color {+ Some(c) => match to_drawing_color(c) {+ Some(c) => Self::Solid(c),+ None => Self::None,+ },+ // Ill-formed solidFill with no color — degrade to None per+ // legacy parser.+ None => Self::None,+ },+ DrawingFillXml::GradFill(g) => Self::Gradient(g.into()),+ DrawingFillXml::BlipFill(b) => Self::Blip(b.into()),+ DrawingFillXml::PattFill(p) => Self::Pattern(p.into()),+ }+ }+}++// ── solidFill ──────────────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct SolidFillXml {+ #[serde(rename = "$value", default)]+ pub color: Option<DrawingColorXml>,+}++// ── gradFill ───────────────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct GradFillXml {+ #[serde(+ rename = "@flip",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub flip: Option<StTileFlipMode>,+ #[serde(rename = "@rotWithShape", default)]+ pub rot_with_shape: Option<AttrBool>,+ #[serde(rename = "gsLst", default)]+ pub gs_lst: Option<GsLstXml>,+ #[serde(rename = "lin", default)]+ pub lin: Option<LinShadeXml>,+ #[serde(rename = "path", default)]+ pub path: Option<PathShadeXml>,+ #[serde(rename = "tileRect", default)]+ pub tile_rect: Option<RelativeRectXml>,+}++#[derive(Debug, Deserialize, Default)]+pub struct GsLstXml {+ #[serde(rename = "gs", default)]+ pub stops: Vec<GsXml>,+}++#[derive(Debug, Deserialize)]+pub struct GsXml {+ #[serde(+ rename = "@pos",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub pos: Dimension<ThousandthPercent>,+ #[serde(rename = "$value")]+ pub color: DrawingColorXml,+}++#[derive(Debug, Deserialize)]+pub struct LinShadeXml {+ #[serde(+ rename = "@ang",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub angle: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(rename = "@scaled", default)]+ pub scaled: Option<AttrBool>,+}++#[derive(Debug, Deserialize)]+pub struct PathShadeXml {+ // §20.1.8.46 CT_PathShadeProperties: `@path` is use="optional". Keep it+ // optional so a conformant `<a:path>` that omits it does not fail the+ // whole document (theme `fmtScheme` fills feed this parser).+ #[serde(+ rename = "@path",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub path_type: Option<StPathShadeType>,+ #[serde(rename = "fillToRect", default)]+ pub fill_to_rect: Option<RelativeRectXml>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPathShadeType {+ Shape,+ Circle,+ Rect,+}++impl From<StPathShadeType> for PathShadeType {+ fn from(s: StPathShadeType) -> Self {+ match s {+ StPathShadeType::Shape => Self::Shape,+ StPathShadeType::Circle => Self::Circle,+ StPathShadeType::Rect => Self::Rect,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StTileFlipMode {+ None,+ X,+ Y,+ Xy,+}++impl From<StTileFlipMode> for TileFlipMode {+ fn from(s: StTileFlipMode) -> Self {+ match s {+ StTileFlipMode::None => Self::None,+ StTileFlipMode::X => Self::X,+ StTileFlipMode::Y => Self::Y,+ StTileFlipMode::Xy => Self::Xy,+ }+ }+}++#[derive(Debug, Deserialize)]+pub struct RelativeRectXml {+ #[serde(+ rename = "@l",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub l: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@t",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub t: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@r",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub r: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@b",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub b: Option<Dimension<ThousandthPercent>>,+}++impl From<RelativeRectXml> for RelativeRect {+ fn from(x: RelativeRectXml) -> Self {+ Self {+ left: x.l,+ top: x.t,+ right: x.r,+ bottom: x.b,+ }+ }+}++impl From<GradFillXml> for GradientFill {+ fn from(x: GradFillXml) -> Self {+ let stops = x+ .gs_lst+ .map(|l| l.stops.into_iter().filter_map(to_gradient_stop).collect())+ .unwrap_or_default();+ let shade_properties = if let Some(lin) = x.lin {+ GradientShadeProperties::Linear {+ angle: lin.angle.unwrap_or_default(),+ scaled: lin.scaled.map(|o| o.0),+ }+ } else if let Some(path) = x.path {+ GradientShadeProperties::Path {+ // An omitted `@path` still denotes a path (radial-family)+ // gradient; default to `circle`, which is what the shade+ // currently resolves to downstream (Radial).+ path_type: path+ .path_type+ .map(Into::into)+ .unwrap_or(PathShadeType::Circle),+ fill_to_rect: path.fill_to_rect.map(Into::into),+ }+ } else {+ GradientShadeProperties::Linear {+ angle: Dimension::new(0),+ scaled: None,+ }+ };+ Self {+ stops,+ shade_properties,+ flip: x.flip.map(Into::into),+ rot_with_shape: x.rot_with_shape.map(|o| o.0),+ tile_rect: x.tile_rect.map(Into::into),+ }+ }+}++/// A gradient stop with an unmodelled color element is dropped: `GradientStop`+/// requires a color and there is no honest placeholder for one.+fn to_gradient_stop(x: GsXml) -> Option<GradientStop> {+ Some(GradientStop {+ position: x.pos,+ color: to_drawing_color(x.color)?,+ })+}++// ── blipFill ───────────────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct BlipFillXml {+ #[serde(rename = "@rotWithShape", default)]+ pub rot_with_shape: Option<AttrBool>,+ #[serde(+ rename = "@dpi",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub dpi: Option<u32>,+ #[serde(rename = "blip", default)]+ pub blip: Option<BlipXml>,+ #[serde(rename = "srcRect", default)]+ pub src_rect: Option<RelativeRectXml>,+ #[serde(rename = "stretch", default)]+ pub stretch: Option<StretchXml>,+ #[serde(rename = "tile", default)]+ pub tile: Option<TileXml>,+}++#[derive(Debug, Deserialize)]+pub struct BlipXml {+ #[serde(rename = "@r:embed", alias = "@embed", default)]+ pub embed: Option<String>,+ #[serde(rename = "@r:link", alias = "@link", default)]+ pub link: Option<String>,+ #[serde(+ rename = "@cstate",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub cstate: Option<StBlipCompression>,+}++#[derive(Debug, Deserialize, Default)]+pub struct StretchXml {+ #[serde(rename = "fillRect", default)]+ pub fill_rect: Option<RelativeRectXml>,+}++#[derive(Debug, Deserialize)]+pub struct TileXml {+ #[serde(+ rename = "@tx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub tx: Option<Dimension<Emu>>,+ #[serde(+ rename = "@ty",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub ty: Option<Dimension<Emu>>,+ #[serde(+ rename = "@sx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub sx: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@sy",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub sy: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@flip",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub flip: Option<StTileFlipMode>,+ #[serde(+ rename = "@algn",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub algn: Option<StRectAlignment>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StBlipCompression {+ Email,+ Hqprint,+ None,+ Print,+ Screen,+}++impl From<StBlipCompression> for BlipCompression {+ fn from(s: StBlipCompression) -> Self {+ match s {+ StBlipCompression::Email => Self::Email,+ StBlipCompression::Hqprint => Self::Hqprint,+ StBlipCompression::None => Self::None,+ StBlipCompression::Print => Self::Print,+ StBlipCompression::Screen => Self::Screen,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StRectAlignment {+ #[serde(rename = "tl")]+ Tl,+ #[serde(rename = "t")]+ T,+ #[serde(rename = "tr")]+ Tr,+ #[serde(rename = "l")]+ L,+ #[serde(rename = "ctr")]+ Ctr,+ #[serde(rename = "r")]+ R,+ #[serde(rename = "bl")]+ Bl,+ #[serde(rename = "b")]+ B,+ #[serde(rename = "br")]+ Br,+}++impl From<StRectAlignment> for RectAlignment {+ fn from(s: StRectAlignment) -> Self {+ match s {+ StRectAlignment::Tl => Self::Tl,+ StRectAlignment::T => Self::T,+ StRectAlignment::Tr => Self::Tr,+ StRectAlignment::L => Self::L,+ StRectAlignment::Ctr => Self::Ctr,+ StRectAlignment::R => Self::R,+ StRectAlignment::Bl => Self::Bl,+ StRectAlignment::B => Self::B,+ StRectAlignment::Br => Self::Br,+ }+ }+}++impl From<BlipFillXml> for BlipFill {+ fn from(x: BlipFillXml) -> Self {+ use crate::docx::model::RelId;+ let blip = x.blip.map(|b| Blip {+ embed: b.embed.map(RelId::new),+ link: b.link.map(RelId::new),+ compression: b.cstate.map(Into::into),+ });+ let fill_kind = match (x.stretch, x.tile) {+ (Some(s), _) => BlipFillKind::Stretch(StretchFill {+ fill_rect: s.fill_rect.map(Into::into),+ }),+ (None, Some(t)) => BlipFillKind::Tile(TileFill {+ tx: t.tx,+ ty: t.ty,+ sx: t.sx,+ sy: t.sy,+ flip: t.flip.map(Into::into),+ alignment: t.algn.map(Into::into),+ }),+ (None, None) => BlipFillKind::Unspecified,+ };+ Self {+ rotate_with_shape: x.rot_with_shape.map(|o| o.0),+ dpi: x.dpi,+ blip,+ src_rect: x.src_rect.map(Into::into),+ fill_kind,+ }+ }+}++// ── pattFill ───────────────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct PattFillXml {+ // §20.1.8.47 CT_PatternFillProperties: `@prst` is use="optional".+ #[serde(+ rename = "@prst",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub prst: Option<StPresetPatternVal>,+ #[serde(rename = "fgClr", default)]+ pub fg_clr: Option<ColorParent>,+ #[serde(rename = "bgClr", default)]+ pub bg_clr: Option<ColorParent>,+}++/// `<a:fgClr>` / `<a:bgClr>` wrap a single color-choice child.+#[derive(Debug, Deserialize)]+pub struct ColorParent {+ #[serde(rename = "$value")]+ pub color: DrawingColorXml,+}++impl From<PattFillXml> for PatternFill {+ fn from(x: PattFillXml) -> Self {+ Self {+ preset: x.prst.map(Into::into),+ fg_color: x.fg_clr.and_then(|c| to_drawing_color(c.color)),+ bg_color: x.bg_clr.and_then(|c| to_drawing_color(c.color)),+ }+ }+}++// ── ST_PresetPatternVal (§20.1.10.50) ─────────────────────────────────────++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPresetPatternVal {+ Pct5,+ Pct10,+ Pct20,+ Pct25,+ Pct30,+ Pct40,+ Pct50,+ Pct60,+ Pct70,+ Pct75,+ Pct80,+ Pct90,+ Horz,+ Vert,+ LtHorz,+ LtVert,+ DkHorz,+ DkVert,+ NarHorz,+ NarVert,+ DashHorz,+ DashVert,+ Cross,+ DnDiag,+ UpDiag,+ LtDnDiag,+ LtUpDiag,+ DkDnDiag,+ DkUpDiag,+ WdDnDiag,+ WdUpDiag,+ DashDnDiag,+ DashUpDiag,+ DiagCross,+ SmCheck,+ LgCheck,+ SmGrid,+ LgGrid,+ DotGrid,+ SmConfetti,+ LgConfetti,+ HorzBrick,+ DiagBrick,+ SolidDmnd,+ OpenDmnd,+ DotDmnd,+ Plaid,+ Sphere,+ Weave,+ DivotShingle,+ Trellis,+ ZigZag,+ Wave,+}++impl From<StPresetPatternVal> for PresetPatternVal {+ fn from(s: StPresetPatternVal) -> Self {+ use StPresetPatternVal as X;+ match s {+ X::Pct5 => Self::Pct5,+ X::Pct10 => Self::Pct10,+ X::Pct20 => Self::Pct20,+ X::Pct25 => Self::Pct25,+ X::Pct30 => Self::Pct30,+ X::Pct40 => Self::Pct40,+ X::Pct50 => Self::Pct50,+ X::Pct60 => Self::Pct60,+ X::Pct70 => Self::Pct70,+ X::Pct75 => Self::Pct75,+ X::Pct80 => Self::Pct80,+ X::Pct90 => Self::Pct90,+ X::Horz => Self::Horz,+ X::Vert => Self::Vert,+ X::LtHorz => Self::LtHorz,+ X::LtVert => Self::LtVert,+ X::DkHorz => Self::DkHorz,+ X::DkVert => Self::DkVert,+ X::NarHorz => Self::NarHorz,+ X::NarVert => Self::NarVert,+ X::DashHorz => Self::DashHorz,+ X::DashVert => Self::DashVert,+ X::Cross => Self::Cross,+ X::DnDiag => Self::DnDiag,+ X::UpDiag => Self::UpDiag,+ X::LtDnDiag => Self::LtDnDiag,+ X::LtUpDiag => Self::LtUpDiag,+ X::DkDnDiag => Self::DkDnDiag,+ X::DkUpDiag => Self::DkUpDiag,+ X::WdDnDiag => Self::WdDnDiag,+ X::WdUpDiag => Self::WdUpDiag,+ X::DashDnDiag => Self::DashDnDiag,+ X::DashUpDiag => Self::DashUpDiag,+ X::DiagCross => Self::DiagCross,+ X::SmCheck => Self::SmCheck,+ X::LgCheck => Self::LgCheck,+ X::SmGrid => Self::SmGrid,+ X::LgGrid => Self::LgGrid,+ X::DotGrid => Self::DotGrid,+ X::SmConfetti => Self::SmConfetti,+ X::LgConfetti => Self::LgConfetti,+ X::HorzBrick => Self::HorzBrick,+ X::DiagBrick => Self::DiagBrick,+ X::SolidDmnd => Self::SolidDmnd,+ X::OpenDmnd => Self::OpenDmnd,+ X::DotDmnd => Self::DotDmnd,+ X::Plaid => Self::Plaid,+ X::Sphere => Self::Sphere,+ X::Weave => Self::Weave,+ X::DivotShingle => Self::DivotShingle,+ X::Trellis => Self::Trellis,+ X::ZigZag => Self::ZigZag,+ X::Wave => Self::Wave,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> DrawingFill {+ let wrapped = format!(r#"<wrap xmlns:a="urn:a" xmlns:r="urn:r">{}</wrap>"#, xml);+ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "$value")]+ f: DrawingFillXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.f.into()+ }++ #[test]+ fn no_fill() {+ assert!(matches!(parse(r#"<noFill/>"#), DrawingFill::None));+ }++ #[test]+ fn grp_fill() {+ assert!(matches!(parse(r#"<grpFill/>"#), DrawingFill::Group));+ }++ #[test]+ fn solid_fill_srgb() {+ match parse(r#"<solidFill><srgbClr val="4F81BD"/></solidFill>"#) {+ DrawingFill::Solid(crate::docx::model::DrawingColor::Srgb { rgb, .. }) => {+ assert_eq!(rgb, 0x4F81BD);+ }+ other => panic!("expected Solid(Srgb), got {other:?}"),+ }+ }++ #[test]+ fn solid_fill_scheme_with_lum_mod() {+ match parse(+ r#"<solidFill><schemeClr val="accent1"><lumMod val="60000"/></schemeClr></solidFill>"#,+ ) {+ DrawingFill::Solid(crate::docx::model::DrawingColor::Scheme { name, transforms }) => {+ assert_eq!(name, crate::docx::model::SchemeColorVal::Accent1);+ assert_eq!(transforms.len(), 1);+ }+ other => panic!("expected Solid(Scheme), got {other:?}"),+ }+ }++ #[test]+ fn grad_fill_linear_two_stops() {+ match parse(+ r#"<gradFill rotWithShape="1">+ <gsLst>+ <gs pos="0"><srgbClr val="FFFFFF"/></gs>+ <gs pos="100000"><srgbClr val="000000"/></gs>+ </gsLst>+ <lin ang="5400000" scaled="1"/>+ </gradFill>"#,+ ) {+ DrawingFill::Gradient(g) => {+ assert_eq!(g.stops.len(), 2);+ assert_eq!(g.stops[0].position.raw(), 0);+ assert_eq!(g.stops[1].position.raw(), 100000);+ match g.shade_properties {+ GradientShadeProperties::Linear { angle, scaled } => {+ assert_eq!(angle.raw(), 5_400_000);+ assert_eq!(scaled, Some(true));+ }+ other => panic!("expected Linear, got {other:?}"),+ }+ assert_eq!(g.rot_with_shape, Some(true));+ }+ other => panic!("expected Gradient, got {other:?}"),+ }+ }++ #[test]+ fn grad_fill_path_circle() {+ match parse(+ r#"<gradFill>+ <gsLst><gs pos="0"><srgbClr val="FF0000"/></gs></gsLst>+ <path path="circle"/>+ </gradFill>"#,+ ) {+ DrawingFill::Gradient(g) => match g.shade_properties {+ GradientShadeProperties::Path { path_type, .. } => {+ assert_eq!(path_type, PathShadeType::Circle);+ }+ other => panic!("expected Path, got {other:?}"),+ },+ other => panic!("expected Gradient, got {other:?}"),+ }+ }++ #[test]+ fn blip_fill_embed_stretch() {+ match parse(+ r#"<blipFill rotWithShape="1">+ <blip r:embed="rId1"/>+ <stretch><fillRect l="0" t="0" r="0" b="0"/></stretch>+ </blipFill>"#,+ ) {+ DrawingFill::Blip(b) => {+ assert_eq!(b.rotate_with_shape, Some(true));+ assert_eq!(+ b.blip+ .as_ref()+ .and_then(|bl| bl.embed.as_ref())+ .map(|r| r.as_str()),+ Some("rId1")+ );+ assert!(matches!(b.fill_kind, BlipFillKind::Stretch(_)));+ }+ other => panic!("expected Blip, got {other:?}"),+ }+ }++ #[test]+ fn blip_fill_tile() {+ match parse(+ r#"<blipFill>+ <blip r:embed="rId2"/>+ <tile tx="0" ty="0" sx="100000" sy="100000" flip="xy" algn="ctr"/>+ </blipFill>"#,+ ) {+ DrawingFill::Blip(b) => match b.fill_kind {+ BlipFillKind::Tile(t) => {+ assert_eq!(t.sx.map(|d| d.raw()), Some(100000));+ assert_eq!(t.flip, Some(TileFlipMode::Xy));+ assert_eq!(t.alignment, Some(RectAlignment::Ctr));+ }+ other => panic!("expected Tile, got {other:?}"),+ },+ other => panic!("expected Blip, got {other:?}"),+ }+ }++ #[test]+ fn pattern_fill_with_fg_bg() {+ match parse(+ r#"<pattFill prst="cross">+ <fgClr><srgbClr val="FF0000"/></fgClr>+ <bgClr><srgbClr val="00FF00"/></bgClr>+ </pattFill>"#,+ ) {+ DrawingFill::Pattern(p) => {+ assert_eq!(p.preset, Some(PresetPatternVal::Cross));+ assert!(p.fg_color.is_some());+ assert!(p.bg_color.is_some());+ }+ other => panic!("expected Pattern, got {other:?}"),+ }+ }++ #[test]+ fn pattern_fill_dk_horz() {+ match parse(r#"<pattFill prst="dkHorz"/>"#) {+ DrawingFill::Pattern(p) => assert_eq!(p.preset, Some(PresetPatternVal::DkHorz)),+ other => panic!("expected Pattern, got {other:?}"),+ }+ }++ #[test]+ fn path_gradient_without_path_attr_defaults_to_circle() {+ // §20.1.8.46 CT_PathShadeProperties: `@path` is optional. A `<a:path>`+ // omitting it must parse (not crash the theme parse) and default to a+ // circle path so the gradient still resolves as radial downstream.+ match parse(+ r#"<gradFill>+ <gsLst><gs pos="0"><srgbClr val="FF0000"/></gs></gsLst>+ <path><fillToRect l="0" t="0" r="0" b="0"/></path>+ </gradFill>"#,+ ) {+ DrawingFill::Gradient(g) => match g.shade_properties {+ GradientShadeProperties::Path { path_type, .. } => {+ assert_eq!(path_type, PathShadeType::Circle);+ }+ other => panic!("expected Path, got {other:?}"),+ },+ other => panic!("expected Gradient, got {other:?}"),+ }+ }++ #[test]+ fn pattern_fill_without_prst_is_none() {+ // §20.1.8.47 CT_PatternFillProperties: `@prst` is optional. An omitted+ // preset must parse to `None`, not fail the whole document.+ match parse(r#"<pattFill><fgClr><srgbClr val="FF0000"/></fgClr></pattFill>"#) {+ DrawingFill::Pattern(p) => {+ assert_eq!(p.preset, None);+ assert!(p.fg_color.is_some());+ }+ other => panic!("expected Pattern, got {other:?}"),+ }+ }++ #[test]+ fn blip_compression_alias() {+ // Per spec, `cstate="hqprint"` is valid.+ let xml = r#"<blipFill><blip r:embed="rId1" cstate="hqprint"/></blipFill>"#;+ match parse(xml) {+ DrawingFill::Blip(b) => {+ assert_eq!(b.blip.unwrap().compression, Some(BlipCompression::Hqprint));+ }+ other => panic!("expected Blip, got {other:?}"),+ }+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/geometry.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/geometry.rsnew file mode 100644index 0000000..30269f7--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/geometry.rs@@ -0,0 +1,688 @@+//! DrawingML custom geometry schema (§20.1.9.8 CT_CustomGeometry2D).+//!+//! Path commands are mixed-content (moveTo / lnTo / cubicBezTo / quadBezTo /+//! arcTo / close) preserving document order via `$value` + untagged enum.+//! `AdjCoord` attributes are either decimal integers or guide-name+//! references, resolved by a custom `Deserialize` that tries integer first.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::{Deserialize, Deserializer};++use crate::docx::dimension::{Dimension, Emu};+use crate::docx::model::{+ AdjCoord, AdjPoint, AdjustHandle, ConnectionSite, CustomGeometry, GeomGuide, PathCommand,+ PathDef, PathFillMode, TextRect,+};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++// ── CustomGeometry ────────────────────────────────────────────────────────++#[derive(Debug, Deserialize, Default)]+pub struct CustomGeometryXml {+ #[serde(rename = "avLst", default)]+ pub av_lst: Option<GdListXml>,+ #[serde(rename = "gdLst", default)]+ pub gd_lst: Option<GdListXml>,+ #[serde(rename = "ahLst", default)]+ pub ah_lst: Option<AhListXml>,+ #[serde(rename = "cxnLst", default)]+ pub cxn_lst: Option<CxnListXml>,+ #[serde(rename = "rect", default)]+ pub rect: Option<TextRectXml>,+ #[serde(rename = "pathLst", default)]+ pub path_lst: Option<PathListXml>,+}++#[derive(Debug, Deserialize, Default)]+pub struct GdListXml {+ #[serde(rename = "gd", default)]+ pub guides: Vec<GeomGuideXml>,+}++#[derive(Debug, Deserialize)]+pub struct GeomGuideXml {+ #[serde(rename = "@name")]+ pub name: String,+ #[serde(rename = "@fmla")]+ pub fmla: String,+}++#[derive(Debug, Deserialize, Default)]+pub struct AhListXml {+ #[serde(rename = "$value", default)]+ pub handles: Vec<AhXml>,+}++#[derive(Debug, Deserialize)]+pub enum AhXml {+ #[serde(rename = "ahXY")]+ XY(AhXyXml),+ #[serde(rename = "ahPolar")]+ Polar(AhPolarXml),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++#[derive(Debug, Deserialize)]+pub struct AhXyXml {+ #[serde(rename = "@gdRefX", default)]+ pub gd_ref_x: Option<String>,+ #[serde(rename = "@gdRefY", default)]+ pub gd_ref_y: Option<String>,+ #[serde(rename = "@minX", default)]+ pub min_x: Option<AdjCoordXml>,+ #[serde(rename = "@maxX", default)]+ pub max_x: Option<AdjCoordXml>,+ #[serde(rename = "@minY", default)]+ pub min_y: Option<AdjCoordXml>,+ #[serde(rename = "@maxY", default)]+ pub max_y: Option<AdjCoordXml>,+ #[serde(rename = "pos")]+ pub pos: AdjPointXml,+}++#[derive(Debug, Deserialize)]+pub struct AhPolarXml {+ #[serde(rename = "@gdRefR", default)]+ pub gd_ref_r: Option<String>,+ #[serde(rename = "@gdRefAng", default)]+ pub gd_ref_ang: Option<String>,+ #[serde(rename = "@minR", default)]+ pub min_r: Option<AdjCoordXml>,+ #[serde(rename = "@maxR", default)]+ pub max_r: Option<AdjCoordXml>,+ #[serde(rename = "@minAng", default)]+ pub min_ang: Option<AdjCoordXml>,+ #[serde(rename = "@maxAng", default)]+ pub max_ang: Option<AdjCoordXml>,+ #[serde(rename = "pos")]+ pub pos: AdjPointXml,+}++#[derive(Debug, Deserialize, Default)]+pub struct CxnListXml {+ #[serde(rename = "cxn", default)]+ pub sites: Vec<CxnXml>,+}++#[derive(Debug, Deserialize)]+pub struct CxnXml {+ #[serde(rename = "@ang")]+ pub ang: AdjCoordXml,+ #[serde(rename = "pos")]+ pub pos: AdjPointXml,+}++#[derive(Debug, Deserialize)]+pub struct TextRectXml {+ #[serde(rename = "@l")]+ pub l: AdjCoordXml,+ #[serde(rename = "@t")]+ pub t: AdjCoordXml,+ #[serde(rename = "@r")]+ pub r: AdjCoordXml,+ #[serde(rename = "@b")]+ pub b: AdjCoordXml,+}++#[derive(Debug, Deserialize, Default)]+pub struct PathListXml {+ #[serde(rename = "path", default)]+ pub paths: Vec<PathXml>,+}++#[derive(Debug, Deserialize, Default)]+pub struct PathXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub w: Option<Dimension<Emu>>,+ #[serde(+ rename = "@h",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub h: Option<Dimension<Emu>>,+ #[serde(+ rename = "@fill",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub fill: Option<StPathFillMode>,+ /// Per §20.1.9.15, default is `true`.+ #[serde(rename = "@stroke", default)]+ pub stroke: Option<StrAttrBool>,+ /// Per §20.1.9.15, default is `false`.+ #[serde(rename = "@extrusionOk", default)]+ pub extrusion_ok: Option<StrAttrBool>,+ #[serde(rename = "$value", default)]+ pub commands: Vec<PathCommandXml>,+}++#[derive(Debug, Deserialize)]+pub enum PathCommandXml {+ #[serde(rename = "moveTo")]+ MoveTo(SinglePtXml),+ #[serde(rename = "lnTo")]+ LnTo(SinglePtXml),+ #[serde(rename = "cubicBezTo")]+ CubicBezTo(MultiPtXml),+ #[serde(rename = "quadBezTo")]+ QuadBezTo(MultiPtXml),+ #[serde(rename = "arcTo")]+ ArcTo(ArcToXml),+ #[serde(rename = "close")]+ Close(CloseXml),+ /// Catch-all for unmodelled OOXML elements. Vendoring divergence from+ /// dxpdf: upstream fails the whole document on an unknown element.+ #[serde(other)]+ Other,+}++#[derive(Debug, Deserialize)]+pub struct SinglePtXml {+ #[serde(rename = "pt")]+ pub pt: AdjPointXml,+}++#[derive(Debug, Deserialize)]+pub struct MultiPtXml {+ #[serde(rename = "pt", default)]+ pub pts: Vec<AdjPointXml>,+}++#[derive(Debug, Deserialize)]+pub struct ArcToXml {+ #[serde(rename = "@wR")]+ pub wr: AdjCoordXml,+ #[serde(rename = "@hR")]+ pub hr: AdjCoordXml,+ #[serde(rename = "@stAng")]+ pub st_ang: AdjCoordXml,+ #[serde(rename = "@swAng")]+ pub sw_ang: AdjCoordXml,+}++#[derive(Debug, Deserialize, Default)]+pub struct CloseXml {}++#[derive(Debug, Deserialize)]+pub struct AdjPointXml {+ #[serde(rename = "@x")]+ pub x: AdjCoordXml,+ #[serde(rename = "@y")]+ pub y: AdjCoordXml,+}++/// An `AdjCoord` attribute value: either a decimal integer literal or a+/// guide-name reference.+#[derive(Clone, Debug, PartialEq)]+pub struct AdjCoordXml(pub AdjCoord);++impl<'de> Deserialize<'de> for AdjCoordXml {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ if let Ok(n) = s.parse::<i64>() {+ return Ok(AdjCoordXml(AdjCoord::Lit(n)));+ }+ if s.is_empty() {+ return Err(serde::de::Error::custom(+ "empty AdjCoord: expected integer or guide name",+ ));+ }+ Ok(AdjCoordXml(AdjCoord::Guide(s)))+ }+}++/// Alias for the shared attribute-level boolean primitive.+pub use crate::docx::parse::primitives::AttrBool as StrAttrBool;++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPathFillMode {+ None,+ Norm,+ Lighten,+ LightenLess,+ Darken,+ DarkenLess,+}++impl From<StPathFillMode> for PathFillMode {+ fn from(s: StPathFillMode) -> Self {+ match s {+ StPathFillMode::None => Self::None,+ StPathFillMode::Norm => Self::Norm,+ StPathFillMode::Lighten => Self::Lighten,+ StPathFillMode::LightenLess => Self::LightenLess,+ StPathFillMode::Darken => Self::Darken,+ StPathFillMode::DarkenLess => Self::DarkenLess,+ }+ }+}++// ── Conversion to model ───────────────────────────────────────────────────++impl From<CustomGeometryXml> for CustomGeometry {+ fn from(x: CustomGeometryXml) -> Self {+ Self {+ av_list: x.av_lst.map(guides).unwrap_or_default(),+ gd_list: x.gd_lst.map(guides).unwrap_or_default(),+ ah_list: x+ .ah_lst+ .map(|a| a.handles.into_iter().filter_map(to_adjust_handle).collect())+ .unwrap_or_default(),+ cxn_list: x+ .cxn_lst+ .map(|c| c.sites.into_iter().map(Into::into).collect())+ .unwrap_or_default(),+ rect: x.rect.map(Into::into),+ paths: x+ .path_lst+ .map(|p| p.paths.into_iter().map(Into::into).collect())+ .unwrap_or_default(),+ }+ }+}++fn guides(l: GdListXml) -> Vec<GeomGuide> {+ l.guides+ .into_iter()+ .map(|g| GeomGuide {+ name: g.name,+ formula: g.fmla,+ })+ .collect()+}++impl From<AdjPointXml> for AdjPoint {+ fn from(x: AdjPointXml) -> Self {+ Self { x: x.x.0, y: x.y.0 }+ }+}++/// An unmodelled adjust-handle element is dropped by the caller; `AdjustHandle`+/// has no variant that could stand in for one.+fn to_adjust_handle(h: AhXml) -> Option<AdjustHandle> {+ Some(match h {+ AhXml::Other => return None,+ AhXml::XY(x) => AdjustHandle::XY {+ guide_ref_x: x.gd_ref_x,+ guide_ref_y: x.gd_ref_y,+ min_x: x.min_x.map(|c| c.0),+ max_x: x.max_x.map(|c| c.0),+ min_y: x.min_y.map(|c| c.0),+ max_y: x.max_y.map(|c| c.0),+ position: x.pos.into(),+ },+ AhXml::Polar(p) => AdjustHandle::Polar {+ guide_ref_r: p.gd_ref_r,+ guide_ref_ang: p.gd_ref_ang,+ min_r: p.min_r.map(|c| c.0),+ max_r: p.max_r.map(|c| c.0),+ min_ang: p.min_ang.map(|c| c.0),+ max_ang: p.max_ang.map(|c| c.0),+ position: p.pos.into(),+ },+ })+}++impl From<CxnXml> for ConnectionSite {+ fn from(x: CxnXml) -> Self {+ Self {+ angle: x.ang.0,+ position: x.pos.into(),+ }+ }+}++impl From<TextRectXml> for TextRect {+ fn from(x: TextRectXml) -> Self {+ Self {+ left: x.l.0,+ top: x.t.0,+ right: x.r.0,+ bottom: x.b.0,+ }+ }+}++impl From<PathXml> for PathDef {+ fn from(x: PathXml) -> Self {+ Self {+ w: x.w.unwrap_or_default(),+ h: x.h.unwrap_or_default(),+ fill: x.fill.map(Into::into).unwrap_or(PathFillMode::Norm),+ stroke: x.stroke.map(|b| b.0).unwrap_or(true),+ extrusion_ok: x.extrusion_ok.map(|b| b.0).unwrap_or(false),+ commands: x.commands.into_iter().filter_map(to_command).collect(),+ }+ }+}++fn to_command(c: PathCommandXml) -> Option<PathCommand> {+ Some(match c {+ // An unmodelled path command is dropped, as malformed ones already are.+ PathCommandXml::Other => return None,+ PathCommandXml::MoveTo(s) => PathCommand::MoveTo(s.pt.into()),+ PathCommandXml::LnTo(s) => PathCommand::LineTo(s.pt.into()),+ PathCommandXml::CubicBezTo(m) => {+ let mut it = m.pts.into_iter();+ match (it.next(), it.next(), it.next()) {+ (Some(a), Some(b), Some(c)) => {+ PathCommand::CubicBezTo(a.into(), b.into(), c.into())+ }+ _ => {+ log::warn!("cubicBezTo: expected 3 points; dropping malformed command");+ return None;+ }+ }+ }+ PathCommandXml::QuadBezTo(m) => {+ let mut it = m.pts.into_iter();+ match (it.next(), it.next()) {+ (Some(a), Some(b)) => PathCommand::QuadBezTo(a.into(), b.into()),+ _ => {+ log::warn!("quadBezTo: expected 2 points; dropping malformed command");+ return None;+ }+ }+ }+ PathCommandXml::ArcTo(a) => PathCommand::ArcTo {+ wr: a.wr.0,+ hr: a.hr.0,+ start_angle: a.st_ang.0,+ swing_angle: a.sw_ang.0,+ },+ PathCommandXml::Close(_) => PathCommand::Close,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> CustomGeometry {+ let wrapped = format!(r#"<wrap xmlns:a="urn:a">{}</wrap>"#, xml);+ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "custGeom")]+ cg: CustomGeometryXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.cg.into()+ }++ #[test]+ fn empty_custom_geometry() {+ let g = parse(r#"<custGeom/>"#);+ assert!(g.av_list.is_empty());+ assert!(g.paths.is_empty());+ }++ #[test]+ fn guides_av_and_gd() {+ let g = parse(+ r#"<custGeom>+ <avLst><gd name="adj1" fmla="val 25000"/></avLst>+ <gdLst>+ <gd name="a" fmla="*/ w 1 2"/>+ <gd name="b" fmla="+- h 0 0"/>+ </gdLst>+ </custGeom>"#,+ );+ assert_eq!(g.av_list.len(), 1);+ assert_eq!(g.av_list[0].name, "adj1");+ assert_eq!(g.gd_list.len(), 2);+ assert_eq!(g.gd_list[1].formula, "+- h 0 0");+ }++ #[test]+ fn adj_coord_literal_vs_guide() {+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100">+ <moveTo><pt x="0" y="0"/></moveTo>+ <lnTo><pt x="a" y="b"/></lnTo>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ assert_eq!(g.paths.len(), 1);+ match &g.paths[0].commands[0] {+ PathCommand::MoveTo(p) => {+ assert_eq!(p.x, AdjCoord::Lit(0));+ assert_eq!(p.y, AdjCoord::Lit(0));+ }+ other => panic!("expected MoveTo, got {other:?}"),+ }+ match &g.paths[0].commands[1] {+ PathCommand::LineTo(p) => {+ assert_eq!(p.x, AdjCoord::Guide("a".into()));+ assert_eq!(p.y, AdjCoord::Guide("b".into()));+ }+ other => panic!("expected LineTo, got {other:?}"),+ }+ }++ #[test]+ fn cubic_and_quad_beziers() {+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100">+ <cubicBezTo>+ <pt x="10" y="0"/>+ <pt x="20" y="0"/>+ <pt x="30" y="0"/>+ </cubicBezTo>+ <quadBezTo>+ <pt x="40" y="5"/>+ <pt x="50" y="0"/>+ </quadBezTo>+ <close/>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ let cmds = &g.paths[0].commands;+ assert_eq!(cmds.len(), 3);+ assert!(matches!(&cmds[0], PathCommand::CubicBezTo(_, _, _)));+ assert!(matches!(&cmds[1], PathCommand::QuadBezTo(_, _)));+ assert!(matches!(&cmds[2], PathCommand::Close));+ }++ #[test]+ fn arc_to_all_attrs() {+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100">+ <arcTo wR="50" hR="50" stAng="0" swAng="21600000"/>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ match &g.paths[0].commands[0] {+ PathCommand::ArcTo {+ wr,+ hr,+ start_angle,+ swing_angle,+ } => {+ assert_eq!(*wr, AdjCoord::Lit(50));+ assert_eq!(*hr, AdjCoord::Lit(50));+ assert_eq!(*start_angle, AdjCoord::Lit(0));+ assert_eq!(*swing_angle, AdjCoord::Lit(21_600_000));+ }+ other => panic!("expected ArcTo, got {other:?}"),+ }+ }++ #[test]+ fn adjust_handle_xy() {+ let g = parse(+ r#"<custGeom>+ <ahLst>+ <ahXY gdRefX="adj1" minX="0" maxX="100">+ <pos x="adj1" y="0"/>+ </ahXY>+ </ahLst>+ </custGeom>"#,+ );+ assert_eq!(g.ah_list.len(), 1);+ match &g.ah_list[0] {+ AdjustHandle::XY {+ guide_ref_x,+ min_x,+ max_x,+ position,+ ..+ } => {+ assert_eq!(guide_ref_x.as_deref(), Some("adj1"));+ assert_eq!(*min_x, Some(AdjCoord::Lit(0)));+ assert_eq!(*max_x, Some(AdjCoord::Lit(100)));+ assert_eq!(position.x, AdjCoord::Guide("adj1".into()));+ }+ other => panic!("expected XY, got {other:?}"),+ }+ }++ #[test]+ fn adjust_handle_polar() {+ let g = parse(+ r#"<custGeom>+ <ahLst>+ <ahPolar gdRefR="adj2" minAng="0" maxAng="21600000">+ <pos x="0" y="0"/>+ </ahPolar>+ </ahLst>+ </custGeom>"#,+ );+ match &g.ah_list[0] {+ AdjustHandle::Polar {+ guide_ref_r,+ max_ang,+ ..+ } => {+ assert_eq!(guide_ref_r.as_deref(), Some("adj2"));+ assert_eq!(*max_ang, Some(AdjCoord::Lit(21_600_000)));+ }+ other => panic!("expected Polar, got {other:?}"),+ }+ }++ #[test]+ fn connection_site() {+ let g = parse(+ r#"<custGeom>+ <cxnLst>+ <cxn ang="5400000"><pos x="50" y="0"/></cxn>+ </cxnLst>+ </custGeom>"#,+ );+ assert_eq!(g.cxn_list.len(), 1);+ assert_eq!(g.cxn_list[0].angle, AdjCoord::Lit(5_400_000));+ assert_eq!(g.cxn_list[0].position.x, AdjCoord::Lit(50));+ }++ #[test]+ fn text_rect() {+ let g = parse(+ r#"<custGeom>+ <rect l="0" t="0" r="w" b="h"/>+ </custGeom>"#,+ );+ let r = g.rect.unwrap();+ assert_eq!(r.left, AdjCoord::Lit(0));+ assert_eq!(r.right, AdjCoord::Guide("w".into()));+ assert_eq!(r.bottom, AdjCoord::Guide("h".into()));+ }++ #[test]+ fn path_attrs_with_fill_and_stroke() {+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100" fill="none" stroke="false" extrusionOk="1">+ <moveTo><pt x="0" y="0"/></moveTo>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ let p = &g.paths[0];+ assert_eq!(p.w.raw(), 100);+ assert_eq!(p.h.raw(), 100);+ assert_eq!(p.fill, PathFillMode::None);+ assert!(!p.stroke);+ assert!(p.extrusion_ok);+ }++ #[test]+ fn path_defaults_fill_norm_stroke_true_extrusion_false() {+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100">+ <close/>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ let p = &g.paths[0];+ assert_eq!(p.fill, PathFillMode::Norm);+ assert!(p.stroke);+ assert!(!p.extrusion_ok);+ }++ #[test]+ fn malformed_cubic_bezier_is_dropped() {+ // A cubicBezTo needs 3 points; a short one is dropped (with a warn)+ // rather than corrupting the path or aborting the parse.+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100">+ <moveTo><pt x="0" y="0"/></moveTo>+ <cubicBezTo><pt x="10" y="0"/><pt x="20" y="0"/></cubicBezTo>+ <lnTo><pt x="50" y="50"/></lnTo>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ let cmds = &g.paths[0].commands;+ assert_eq!(cmds.len(), 2, "malformed cubicBezTo dropped, others kept");+ assert!(matches!(cmds[0], PathCommand::MoveTo(_)));+ assert!(matches!(cmds[1], PathCommand::LineTo(_)));+ }++ #[test]+ fn complex_path_preserves_order() {+ let g = parse(+ r#"<custGeom>+ <pathLst>+ <path w="100" h="100">+ <moveTo><pt x="0" y="0"/></moveTo>+ <lnTo><pt x="50" y="0"/></lnTo>+ <arcTo wR="10" hR="10" stAng="0" swAng="5400000"/>+ <lnTo><pt x="0" y="100"/></lnTo>+ <close/>+ </path>+ </pathLst>+ </custGeom>"#,+ );+ let cmds = &g.paths[0].commands;+ assert_eq!(cmds.len(), 5);+ assert!(matches!(cmds[0], PathCommand::MoveTo(_)));+ assert!(matches!(cmds[1], PathCommand::LineTo(_)));+ assert!(matches!(cmds[2], PathCommand::ArcTo { .. }));+ assert!(matches!(cmds[3], PathCommand::LineTo(_)));+ assert!(matches!(cmds[4], PathCommand::Close));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/mod.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/mod.rsnew file mode 100644index 0000000..47f1f94--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/mod.rs@@ -0,0 +1,13 @@+//! Serde schema types for DrawingML (§20) — one submodule per primitive+//! family. Schemas are additive during Phase 5: they coexist with the+//! procedural parsers in `drawing/` and will progressively replace them+//! as higher-level container parsers are migrated in later sub-phases.++pub mod anchor;+pub mod color;+pub mod effect;+pub mod fill;+pub mod geometry;+pub mod picture;+pub mod shape;+pub mod stroke;diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/picture.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/picture.rsnew file mode 100644index 0000000..c1be680--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/picture.rs@@ -0,0 +1,320 @@+//! DrawingML picture schema (§19.3.1.37 pic:pic).+//!+//! `<pic:pic>` has three children: non-visual picture properties+//! (`<pic:nvPicPr>`), blip fill (`<pic:blipFill>`), and shape properties+//! (`<pic:spPr>`). All three are fully modeled.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::model::{CnvPicProperties, DocProperties, NvPicProperties, PicLocks, Picture};++use super::fill::{AttrBool, BlipFillXml};+use super::shape::SpPrXml;++#[derive(Deserialize)]+pub(crate) struct PictureXml {+ #[serde(rename = "nvPicPr")]+ pub(crate) nv_pic_pr: NvPicPrXml,+ #[serde(rename = "blipFill")]+ pub(crate) blip_fill: BlipFillXml,+ #[serde(rename = "spPr", default)]+ pub(crate) sp_pr: Option<SpPrXml>,+}++#[derive(Debug, Deserialize)]+pub struct NvPicPrXml {+ #[serde(rename = "cNvPr")]+ pub cnv_pr: CNvPrXml,+ #[serde(rename = "cNvPicPr", default)]+ pub cnv_pic_pr: Option<CNvPicPrXml>,+}++#[derive(Debug, Deserialize)]+pub struct CNvPrXml {+ /// Drawing ids are cosmetic metadata; zero is harmless.+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub id: u32,+ #[serde(rename = "@name")]+ pub name: String,+ #[serde(rename = "@descr", default)]+ pub descr: Option<String>,+ #[serde(rename = "@hidden", default)]+ pub hidden: Option<AttrBool>,+ #[serde(rename = "@title", default)]+ pub title: Option<String>,+ // Children like hlinkClick, hlinkHover, extLst accepted but ignored.+}++#[derive(Debug, Deserialize)]+pub struct CNvPicPrXml {+ #[serde(rename = "@preferRelativeResize", default)]+ pub prefer_relative_resize: Option<AttrBool>,+ #[serde(rename = "picLocks", default)]+ pub pic_locks: Option<PicLocksXml>,+}++#[derive(Debug, Deserialize)]+pub struct PicLocksXml {+ #[serde(rename = "@noChangeAspect", default)]+ pub no_change_aspect: Option<AttrBool>,+ #[serde(rename = "@noCrop", default)]+ pub no_crop: Option<AttrBool>,+ #[serde(rename = "@noResize", default)]+ pub no_resize: Option<AttrBool>,+ #[serde(rename = "@noMove", default)]+ pub no_move: Option<AttrBool>,+ #[serde(rename = "@noRot", default)]+ pub no_rot: Option<AttrBool>,+ #[serde(rename = "@noSelect", default)]+ pub no_select: Option<AttrBool>,+ #[serde(rename = "@noEditPoints", default)]+ pub no_edit_points: Option<AttrBool>,+ #[serde(rename = "@noAdjustHandles", default)]+ pub no_adjust_handles: Option<AttrBool>,+ #[serde(rename = "@noChangeArrowheads", default)]+ pub no_change_arrowheads: Option<AttrBool>,+ #[serde(rename = "@noChangeShapeType", default)]+ pub no_change_shape_type: Option<AttrBool>,+ #[serde(rename = "@noGrp", default)]+ pub no_grp: Option<AttrBool>,+}++// ── Conversion to model ───────────────────────────────────────────────────++impl From<PictureXml> for Picture {+ fn from(x: PictureXml) -> Self {+ Self {+ nv_pic_pr: x.nv_pic_pr.into(),+ blip_fill: x.blip_fill.into(),+ shape_properties: x.sp_pr.map(Into::into),+ }+ }+}++impl From<NvPicPrXml> for NvPicProperties {+ fn from(x: NvPicPrXml) -> Self {+ Self {+ cnv_pr: x.cnv_pr.into(),+ cnv_pic_pr: x.cnv_pic_pr.map(Into::into),+ }+ }+}++impl From<CNvPrXml> for DocProperties {+ fn from(x: CNvPrXml) -> Self {+ Self {+ id: x.id,+ name: x.name,+ description: x.descr,+ hidden: x.hidden.map(|b| b.0),+ title: x.title,+ }+ }+}++impl From<CNvPicPrXml> for CnvPicProperties {+ fn from(x: CNvPicPrXml) -> Self {+ Self {+ prefer_relative_resize: x.prefer_relative_resize.map(|b| b.0),+ pic_locks: x.pic_locks.map(Into::into),+ }+ }+}++impl From<PicLocksXml> for PicLocks {+ fn from(x: PicLocksXml) -> Self {+ Self {+ no_change_aspect: x.no_change_aspect.map(|b| b.0),+ no_crop: x.no_crop.map(|b| b.0),+ no_resize: x.no_resize.map(|b| b.0),+ no_move: x.no_move.map(|b| b.0),+ no_rot: x.no_rot.map(|b| b.0),+ no_select: x.no_select.map(|b| b.0),+ no_edit_points: x.no_edit_points.map(|b| b.0),+ no_adjust_handles: x.no_adjust_handles.map(|b| b.0),+ no_change_arrowheads: x.no_change_arrowheads.map(|b| b.0),+ no_change_shape_type: x.no_change_shape_type.map(|b| b.0),+ no_grp: x.no_grp.map(|b| b.0),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::BlipFillKind;++ fn parse(xml: &str) -> Picture {+ let wrapped = format!(+ r#"<wrap xmlns:pic="urn:pic" xmlns:a="urn:a" xmlns:r="urn:r">{}</wrap>"#,+ xml+ );+ #[derive(Deserialize)]+ struct Wrap {+ pic: PictureXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.pic.into()+ }++ #[test]+ fn minimal_picture_with_blip_embed() {+ let p = parse(+ r#"<pic>+ <nvPicPr>+ <cNvPr id="1" name="image1"/>+ </nvPicPr>+ <blipFill>+ <blip r:embed="rId1"/>+ <stretch/>+ </blipFill>+ </pic>"#,+ );+ assert_eq!(p.nv_pic_pr.cnv_pr.id, 1);+ assert_eq!(p.nv_pic_pr.cnv_pr.name, "image1");+ assert!(p.nv_pic_pr.cnv_pic_pr.is_none());+ assert_eq!(+ p.blip_fill+ .blip+ .as_ref()+ .and_then(|b| b.embed.as_ref())+ .map(|r| r.as_str()),+ Some("rId1")+ );+ assert!(matches!(p.blip_fill.fill_kind, BlipFillKind::Stretch(_)));+ }++ #[test]+ fn picture_with_description_and_title() {+ let p = parse(+ r#"<pic>+ <nvPicPr>+ <cNvPr id="2" name="logo" descr="Company logo" title="Logo"/>+ </nvPicPr>+ <blipFill><blip r:embed="rId2"/></blipFill>+ </pic>"#,+ );+ assert_eq!(+ p.nv_pic_pr.cnv_pr.description.as_deref(),+ Some("Company logo")+ );+ assert_eq!(p.nv_pic_pr.cnv_pr.title.as_deref(), Some("Logo"));+ }++ #[test]+ fn picture_with_hidden_and_relative_resize() {+ let p = parse(+ r#"<pic>+ <nvPicPr>+ <cNvPr id="3" name="hidden" hidden="1"/>+ <cNvPicPr preferRelativeResize="0"/>+ </nvPicPr>+ <blipFill><blip r:embed="rId3"/></blipFill>+ </pic>"#,+ );+ assert_eq!(p.nv_pic_pr.cnv_pr.hidden, Some(true));+ assert_eq!(+ p.nv_pic_pr+ .cnv_pic_pr+ .as_ref()+ .unwrap()+ .prefer_relative_resize,+ Some(false)+ );+ }++ #[test]+ fn picture_with_pic_locks() {+ let p = parse(+ r#"<pic>+ <nvPicPr>+ <cNvPr id="4" name="locked"/>+ <cNvPicPr>+ <picLocks noChangeAspect="1" noCrop="0" noResize="true"/>+ </cNvPicPr>+ </nvPicPr>+ <blipFill><blip r:embed="rId4"/></blipFill>+ </pic>"#,+ );+ let locks = p+ .nv_pic_pr+ .cnv_pic_pr+ .as_ref()+ .and_then(|c| c.pic_locks.as_ref())+ .expect("picLocks");+ assert_eq!(locks.no_change_aspect, Some(true));+ assert_eq!(locks.no_crop, Some(false));+ assert_eq!(locks.no_resize, Some(true));+ }++ #[test]+ fn picture_sp_pr_fully_parsed() {+ use crate::docx::model::{PresetShapeType, ShapeGeometry};+ let p = parse(+ r#"<pic>+ <nvPicPr><cNvPr id="5" name="with-sp"/></nvPicPr>+ <blipFill><blip r:embed="rId5"/></blipFill>+ <spPr>+ <xfrm rot="900000"><off x="10" y="20"/><ext cx="100" cy="200"/></xfrm>+ <prstGeom prst="roundRect"/>+ </spPr>+ </pic>"#,+ );+ let sp = p.shape_properties.expect("spPr parsed");+ let t = sp.transform.unwrap();+ assert_eq!(t.rotation.unwrap().raw(), 900_000);+ assert_eq!(t.extent.unwrap().width.raw(), 100);+ match sp.geometry {+ Some(ShapeGeometry::Preset(g)) => assert_eq!(g.preset, PresetShapeType::RoundRect),+ other => panic!("expected Preset, got {other:?}"),+ }+ }++ #[test]+ fn blip_with_crop_source_rect() {+ let p = parse(+ r#"<pic>+ <nvPicPr><cNvPr id="6" name="cropped"/></nvPicPr>+ <blipFill>+ <blip r:embed="rId6" cstate="hqprint"/>+ <srcRect l="5000" t="0" r="5000" b="0"/>+ <stretch><fillRect/></stretch>+ </blipFill>+ </pic>"#,+ );+ assert_eq!(+ p.blip_fill.src_rect.as_ref().unwrap().left.unwrap().raw(),+ 5000+ );+ assert_eq!(+ p.blip_fill.blip.as_ref().unwrap().compression,+ Some(crate::docx::model::BlipCompression::Hqprint)+ );+ }++ #[test]+ fn blip_tile_fill() {+ let p = parse(+ r#"<pic>+ <nvPicPr><cNvPr id="7" name="tiled"/></nvPicPr>+ <blipFill>+ <blip r:embed="rId7"/>+ <tile tx="0" ty="0" sx="50000" sy="50000" algn="tl"/>+ </blipFill>+ </pic>"#,+ );+ match p.blip_fill.fill_kind {+ BlipFillKind::Tile(t) => {+ assert_eq!(t.sx.unwrap().raw(), 50000);+ assert_eq!(t.alignment, Some(crate::docx::model::RectAlignment::Tl));+ }+ other => panic!("expected Tile, got {other:?}"),+ }+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/shape.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/shape.rsnew file mode 100644index 0000000..7e89330--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/shape.rs@@ -0,0 +1,1167 @@+//! DrawingML shape schema (§20.1.2.2.35 CT_ShapeProperties + §14.5 wps:wsp).+//!+//! Consumes color, fill, stroke, effect, and geometry schemas. Adds+//! `Transform2D`, `PresetGeometryDef` (with the ~150-variant+//! `PresetShapeType` enum), `BodyProperties`, and the `WordProcessingShape`+//! wrapper.+//!+//! Text box content inside `<wps:txbx>` uses `body_schema::BlockChildXml`+//! and is materialized into `Vec<Block>` via the body schema's+//! `convert_container` — same pipeline as body and notes.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::{Deserialize, Deserializer};++use crate::docx::dimension::{Dimension, Emu, SixtieThousandthDeg, ThousandthPercent};+use crate::docx::geometry::Offset;+use crate::docx::model::{+ BlackWhiteMode, Block, BodyProperties, DrawingFill, FontCollectionIndex, FontReference,+ GeomGuide, NormalAutoFit, PresetGeometryDef, PresetShapeType, ShapeGeometry, ShapeProperties,+ StyleMatrixRef, TextAnchoringType, TextAutoFit, TextVertOverflow, TextVerticalType,+ TextWrappingType, Transform2D, WordProcessingShape,+};++use super::color::{DrawingColorXml, to_drawing_color};+use super::effect::EffectListXml;+use super::fill::{AttrBool, DrawingFillXml};+use super::geometry::CustomGeometryXml;+use super::picture::CNvPrXml;+use super::stroke::OutlineXml;++// ── spPr (§20.1.2.2.35) ───────────────────────────────────────────────────++#[derive(Debug, Deserialize, Default)]+pub struct SpPrXml {+ #[serde(+ rename = "@bwMode",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub bw_mode: Option<StBlackWhiteMode>,+ #[serde(rename = "xfrm", default)]+ pub xfrm: Option<XfrmXml>,+ #[serde(rename = "prstGeom", default)]+ pub prst_geom: Option<PrstGeomXml>,+ #[serde(rename = "custGeom", default)]+ pub cust_geom: Option<CustomGeometryXml>,+ // Six fill variants — flatten by routing through DrawingFillXml.+ #[serde(rename = "noFill", default)]+ pub no_fill: Option<super::fill::Empty>,+ #[serde(rename = "solidFill", default)]+ pub solid_fill: Option<super::fill::SolidFillXml>,+ #[serde(rename = "gradFill", default)]+ pub grad_fill: Option<super::fill::GradFillXml>,+ #[serde(rename = "blipFill", default)]+ pub blip_fill: Option<super::fill::BlipFillXml>,+ #[serde(rename = "pattFill", default)]+ pub patt_fill: Option<super::fill::PattFillXml>,+ #[serde(rename = "grpFill", default)]+ pub grp_fill: Option<super::fill::Empty>,+ #[serde(rename = "ln", default)]+ pub ln: Option<OutlineXml>,+ #[serde(rename = "effectLst", default)]+ pub effect_lst: Option<EffectListXml>,+}++impl From<SpPrXml> for ShapeProperties {+ fn from(x: SpPrXml) -> Self {+ let geometry = if let Some(p) = x.prst_geom {+ Some(ShapeGeometry::Preset(p.into()))+ } else {+ x.cust_geom.map(|c| ShapeGeometry::Custom(c.into()))+ };+ let fill = pick_fill(+ x.no_fill,+ x.grp_fill,+ x.solid_fill,+ x.grad_fill,+ x.blip_fill,+ x.patt_fill,+ );+ Self {+ bw_mode: x.bw_mode.map(Into::into),+ transform: x.xfrm.map(Into::into),+ geometry,+ fill,+ outline: x.ln.map(Into::into),+ effect_list: x.effect_lst.map(Into::into),+ }+ }+}++fn pick_fill(+ no: Option<super::fill::Empty>,+ grp: Option<super::fill::Empty>,+ solid: Option<super::fill::SolidFillXml>,+ grad: Option<super::fill::GradFillXml>,+ blip: Option<super::fill::BlipFillXml>,+ patt: Option<super::fill::PattFillXml>,+) -> Option<DrawingFill> {+ let f = if let Some(e) = no {+ Some(DrawingFillXml::NoFill(e))+ } else if let Some(e) = grp {+ Some(DrawingFillXml::GrpFill(e))+ } else if let Some(s) = solid {+ Some(DrawingFillXml::SolidFill(s))+ } else if let Some(g) = grad {+ Some(DrawingFillXml::GradFill(g))+ } else if let Some(b) = blip {+ Some(DrawingFillXml::BlipFill(b))+ } else {+ patt.map(DrawingFillXml::PattFill)+ };+ f.map(Into::into)+}++// ── xfrm (§20.1.7.6) ──────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct XfrmXml {+ #[serde(+ rename = "@rot",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub rot: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(rename = "@flipH", default)]+ pub flip_h: Option<AttrBool>,+ #[serde(rename = "@flipV", default)]+ pub flip_v: Option<AttrBool>,+ #[serde(rename = "off", default)]+ pub off: Option<OffXml>,+ #[serde(rename = "ext", default)]+ pub ext: Option<ExtXml>,+}++#[derive(Debug, Deserialize)]+pub struct OffXml {+ #[serde(+ rename = "@x",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub x: Dimension<Emu>,+ #[serde(+ rename = "@y",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub y: Dimension<Emu>,+}++#[derive(Debug, Deserialize)]+pub struct ExtXml {+ #[serde(+ rename = "@cx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub cx: Dimension<Emu>,+ #[serde(+ rename = "@cy",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub cy: Dimension<Emu>,+}++impl From<XfrmXml> for Transform2D {+ fn from(x: XfrmXml) -> Self {+ use crate::docx::geometry::Size;+ Self {+ rotation: x.rot,+ flip_h: x.flip_h.map(|b| b.0),+ flip_v: x.flip_v.map(|b| b.0),+ offset: x.off.map(|o| Offset::new(o.x, o.y)),+ extent: x.ext.map(|e| Size::new(e.cx, e.cy)),+ }+ }+}++// ── prstGeom (§20.1.9.18) ─────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+pub struct PrstGeomXml {+ #[serde(rename = "@prst")]+ pub prst: PresetShapeTypeXml,+ #[serde(rename = "avLst", default)]+ pub av_lst: Option<super::geometry::GdListXml>,+}++impl From<PrstGeomXml> for PresetGeometryDef {+ fn from(x: PrstGeomXml) -> Self {+ Self {+ preset: x.prst.0,+ adjust_values: x+ .av_lst+ .map(|l| {+ l.guides+ .into_iter()+ .map(|g| GeomGuide {+ name: g.name,+ formula: g.fmla,+ })+ .collect()+ })+ .unwrap_or_default(),+ }+ }+}++/// Wrapper that tolerates unknown preset names by falling back to+/// `PresetShapeType::Other`. Known values go through `rename_all="camelCase"`.+#[derive(Debug)]+pub struct PresetShapeTypeXml(pub PresetShapeType);++impl<'de> Deserialize<'de> for PresetShapeTypeXml {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ Ok(Self(map_preset_shape(&s)))+ }+}++fn map_preset_shape(val: &str) -> PresetShapeType {+ use PresetShapeType as P;+ match val {+ "rect" => P::Rect,+ "roundRect" => P::RoundRect,+ "ellipse" => P::Ellipse,+ "triangle" => P::Triangle,+ "rtTriangle" => P::RtTriangle,+ "diamond" => P::Diamond,+ "parallelogram" => P::Parallelogram,+ "trapezoid" => P::Trapezoid,+ "pentagon" => P::Pentagon,+ "hexagon" => P::Hexagon,+ "octagon" => P::Octagon,+ "star4" => P::Star4,+ "star5" => P::Star5,+ "star6" => P::Star6,+ "star8" => P::Star8,+ "star10" => P::Star10,+ "star12" => P::Star12,+ "star16" => P::Star16,+ "star24" => P::Star24,+ "star32" => P::Star32,+ "line" => P::Line,+ "plus" => P::Plus,+ "can" => P::Can,+ "cube" => P::Cube,+ "donut" => P::Donut,+ "noSmoking" => P::NoSmoking,+ "blockArc" => P::BlockArc,+ "heart" => P::Heart,+ "sun" => P::Sun,+ "moon" => P::Moon,+ "smileyFace" => P::SmileyFace,+ "lightningBolt" => P::LightningBolt,+ "cloud" => P::Cloud,+ "arc" => P::Arc,+ "plaque" => P::Plaque,+ "frame" => P::Frame,+ "bevel" => P::Bevel,+ "foldedCorner" => P::FoldedCorner,+ "chevron" => P::Chevron,+ "homePlate" => P::HomePlate,+ "ribbon" => P::Ribbon,+ "ribbon2" => P::Ribbon2,+ "pie" => P::Pie,+ "pieWedge" => P::PieWedge,+ "chord" => P::Chord,+ "teardrop" => P::Teardrop,+ "arrow" => P::Arrow,+ "leftArrow" => P::LeftArrow,+ "rightArrow" => P::RightArrow,+ "upArrow" => P::UpArrow,+ "downArrow" => P::DownArrow,+ "leftRightArrow" => P::LeftRightArrow,+ "upDownArrow" => P::UpDownArrow,+ "quadArrow" => P::QuadArrow,+ "bentArrow" => P::BentArrow,+ "uturnArrow" => P::UturnArrow,+ "circularArrow" => P::CircularArrow,+ "curvedRightArrow" => P::CurvedRightArrow,+ "curvedLeftArrow" => P::CurvedLeftArrow,+ "curvedUpArrow" => P::CurvedUpArrow,+ "curvedDownArrow" => P::CurvedDownArrow,+ "stripedRightArrow" => P::StripedRightArrow,+ "notchedRightArrow" => P::NotchedRightArrow,+ "bentUpArrow" => P::BentUpArrow,+ "leftUpArrow" => P::LeftUpArrow,+ "leftRightUpArrow" => P::LeftRightUpArrow,+ "leftArrowCallout" => P::LeftArrowCallout,+ "rightArrowCallout" => P::RightArrowCallout,+ "upArrowCallout" => P::UpArrowCallout,+ "downArrowCallout" => P::DownArrowCallout,+ "leftRightArrowCallout" => P::LeftRightArrowCallout,+ "upDownArrowCallout" => P::UpDownArrowCallout,+ "quadArrowCallout" => P::QuadArrowCallout,+ "swooshArrow" => P::SwooshArrow,+ "leftCircularArrow" => P::LeftCircularArrow,+ "leftRightCircularArrow" => P::LeftRightCircularArrow,+ "callout1" => P::Callout1,+ "callout2" => P::Callout2,+ "callout3" => P::Callout3,+ "accentCallout1" => P::AccentCallout1,+ "accentCallout2" => P::AccentCallout2,+ "accentCallout3" => P::AccentCallout3,+ "borderCallout1" => P::BorderCallout1,+ "borderCallout2" => P::BorderCallout2,+ "borderCallout3" => P::BorderCallout3,+ "accentBorderCallout1" => P::AccentBorderCallout1,+ "accentBorderCallout2" => P::AccentBorderCallout2,+ "accentBorderCallout3" => P::AccentBorderCallout3,+ "wedgeRectCallout" => P::WedgeRectCallout,+ "wedgeRoundRectCallout" => P::WedgeRoundRectCallout,+ "wedgeEllipseCallout" => P::WedgeEllipseCallout,+ "cloudCallout" => P::CloudCallout,+ "leftBracket" => P::LeftBracket,+ "rightBracket" => P::RightBracket,+ "leftBrace" => P::LeftBrace,+ "rightBrace" => P::RightBrace,+ "bracketPair" => P::BracketPair,+ "bracePair" => P::BracePair,+ "straightConnector1" => P::StraightConnector1,+ "bentConnector2" => P::BentConnector2,+ "bentConnector3" => P::BentConnector3,+ "bentConnector4" => P::BentConnector4,+ "bentConnector5" => P::BentConnector5,+ "curvedConnector2" => P::CurvedConnector2,+ "curvedConnector3" => P::CurvedConnector3,+ "curvedConnector4" => P::CurvedConnector4,+ "curvedConnector5" => P::CurvedConnector5,+ "flowChartProcess" => P::FlowChartProcess,+ "flowChartDecision" => P::FlowChartDecision,+ "flowChartInputOutput" => P::FlowChartInputOutput,+ "flowChartPredefinedProcess" => P::FlowChartPredefinedProcess,+ "flowChartInternalStorage" => P::FlowChartInternalStorage,+ "flowChartDocument" => P::FlowChartDocument,+ "flowChartMultidocument" => P::FlowChartMultidocument,+ "flowChartTerminator" => P::FlowChartTerminator,+ "flowChartPreparation" => P::FlowChartPreparation,+ "flowChartManualInput" => P::FlowChartManualInput,+ "flowChartManualOperation" => P::FlowChartManualOperation,+ "flowChartConnector" => P::FlowChartConnector,+ "flowChartPunchedCard" => P::FlowChartPunchedCard,+ "flowChartPunchedTape" => P::FlowChartPunchedTape,+ "flowChartSummingJunction" => P::FlowChartSummingJunction,+ "flowChartOr" => P::FlowChartOr,+ "flowChartCollate" => P::FlowChartCollate,+ "flowChartSort" => P::FlowChartSort,+ "flowChartExtract" => P::FlowChartExtract,+ "flowChartMerge" => P::FlowChartMerge,+ "flowChartOfflineStorage" => P::FlowChartOfflineStorage,+ "flowChartOnlineStorage" => P::FlowChartOnlineStorage,+ "flowChartMagneticTape" => P::FlowChartMagneticTape,+ "flowChartMagneticDisk" => P::FlowChartMagneticDisk,+ "flowChartMagneticDrum" => P::FlowChartMagneticDrum,+ "flowChartDisplay" => P::FlowChartDisplay,+ "flowChartDelay" => P::FlowChartDelay,+ "flowChartAlternateProcess" => P::FlowChartAlternateProcess,+ "flowChartOffpageConnector" => P::FlowChartOffpageConnector,+ "actionButtonBlank" => P::ActionButtonBlank,+ "actionButtonHome" => P::ActionButtonHome,+ "actionButtonHelp" => P::ActionButtonHelp,+ "actionButtonInformation" => P::ActionButtonInformation,+ "actionButtonForwardNext" => P::ActionButtonForwardNext,+ "actionButtonBackPrevious" => P::ActionButtonBackPrevious,+ "actionButtonEnd" => P::ActionButtonEnd,+ "actionButtonBeginning" => P::ActionButtonBeginning,+ "actionButtonReturn" => P::ActionButtonReturn,+ "actionButtonDocument" => P::ActionButtonDocument,+ "actionButtonSound" => P::ActionButtonSound,+ "actionButtonMovie" => P::ActionButtonMovie,+ "irregularSeal1" => P::IrregularSeal1,+ "irregularSeal2" => P::IrregularSeal2,+ "wave" => P::Wave,+ "doubleWave" => P::DoubleWave,+ "ellipseRibbon" => P::EllipseRibbon,+ "ellipseRibbon2" => P::EllipseRibbon2,+ "verticalScroll" => P::VerticalScroll,+ "horizontalScroll" => P::HorizontalScroll,+ "leftRightRibbon" => P::LeftRightRibbon,+ "gear6" => P::Gear6,+ "gear9" => P::Gear9,+ "funnel" => P::Funnel,+ "mathPlus" => P::MathPlus,+ "mathMinus" => P::MathMinus,+ "mathMultiply" => P::MathMultiply,+ "mathDivide" => P::MathDivide,+ "mathEqual" => P::MathEqual,+ "mathNotEqual" => P::MathNotEqual,+ "cornerTabs" => P::CornerTabs,+ "squareTabs" => P::SquareTabs,+ "plaqueTabs" => P::PlaqueTabs,+ "chartX" => P::ChartX,+ "chartStar" => P::ChartStar,+ "chartPlus" => P::ChartPlus,+ "halfFrame" => P::HalfFrame,+ "corner" => P::Corner,+ "diagStripe" => P::DiagStripe,+ "nonIsoscelesTrapezoid" => P::NonIsoscelesTrapezoid,+ "heptagon" => P::Heptagon,+ "decagon" => P::Decagon,+ "dodecagon" => P::Dodecagon,+ "round1Rect" => P::Round1Rect,+ "round2SameRect" => P::Round2SameRect,+ "round2DiagRect" => P::Round2DiagRect,+ "snipRoundRect" => P::SnipRoundRect,+ "snip1Rect" => P::Snip1Rect,+ "snip2SameRect" => P::Snip2SameRect,+ "snip2DiagRect" => P::Snip2DiagRect,+ other => P::Other(other.to_string()),+ }+}++// ── bodyPr (§20.1.2.1.1) ─────────────────────────────────────────────────++#[derive(Debug, Deserialize, Default)]+pub struct BodyPrXml {+ #[serde(+ rename = "@rot",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub rot: Option<Dimension<SixtieThousandthDeg>>,+ #[serde(+ rename = "@vert",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub vert: Option<StTextVerticalType>,+ #[serde(+ rename = "@wrap",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub wrap: Option<StTextWrappingType>,+ // §20.1.2.1.1: text insets are `ST_Coordinate32` (signed) — negative insets+ // let text bleed past the shape's box, so they must not be clamped to zero.+ // The default `Dimension` deserializer is signed and decimal-tolerant.+ #[serde(+ rename = "@lIns",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub l_ins: Option<Dimension<Emu>>,+ #[serde(+ rename = "@tIns",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub t_ins: Option<Dimension<Emu>>,+ #[serde(+ rename = "@rIns",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub r_ins: Option<Dimension<Emu>>,+ #[serde(+ rename = "@bIns",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub b_ins: Option<Dimension<Emu>>,+ #[serde(+ rename = "@anchor",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub anchor: Option<StTextAnchoringType>,+ #[serde(+ rename = "@vertOverflow",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub vert_overflow: Option<StTextVertOverflowType>,+ // Auto-fit choice — at most one present.+ #[serde(rename = "noAutofit", default)]+ pub no_autofit: Option<super::fill::Empty>,+ #[serde(rename = "normAutofit", default)]+ pub norm_autofit: Option<NormAutofitXml>,+ #[serde(rename = "spAutoFit", default)]+ pub sp_autofit: Option<super::fill::Empty>,+}++/// §20.1.2.1.18 CT_TextNormalAutofit. Both attributes are `ST_TextFontScalePercentOrPercentString`+/// / `ST_TextSpacingPercentOrPercentString` — thousandths of a percent, so+/// `62500` is 62.5%.+#[derive(Debug, Deserialize, Default)]+pub struct NormAutofitXml {+ #[serde(+ rename = "@fontScale",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub font_scale: Option<Dimension<ThousandthPercent>>,+ #[serde(+ rename = "@lnSpcReduction",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub ln_spc_reduction: Option<Dimension<ThousandthPercent>>,+}++impl From<BodyPrXml> for BodyProperties {+ fn from(x: BodyPrXml) -> Self {+ let auto_fit = if x.no_autofit.is_some() {+ Some(TextAutoFit::NoAutoFit)+ } else if let Some(na) = x.norm_autofit {+ Some(TextAutoFit::NormalAutoFit(NormalAutoFit {+ font_scale: na.font_scale,+ line_spacing_reduction: na.ln_spc_reduction,+ }))+ } else {+ x.sp_autofit.map(|_| TextAutoFit::SpAutoFit)+ };+ Self {+ rotation: x.rot,+ vert: x.vert.map(Into::into),+ wrap: x.wrap.map(Into::into),+ left_inset: x.l_ins,+ top_inset: x.t_ins,+ right_inset: x.r_ins,+ bottom_inset: x.b_ins,+ anchor: x.anchor.map(Into::into),+ vert_overflow: x.vert_overflow.map(Into::into),+ auto_fit,+ }+ }+}++// ── wps:wsp (Word Processing Shape) ───────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct WspXml {+ #[serde(rename = "cNvPr", default)]+ pub(crate) cnv_pr: Option<CNvPrXml>,+ #[serde(rename = "cNvSpPr", default)]+ pub(crate) cnv_sp_pr: Option<super::fill::Empty>,+ #[serde(rename = "cNvCnPr", default)]+ pub(crate) cnv_cn_pr: Option<super::fill::Empty>,+ #[serde(rename = "spPr", default)]+ pub(crate) sp_pr: Option<SpPrXml>,+ #[serde(rename = "style", default)]+ pub(crate) style: Option<ShapeStyleXml>,+ #[serde(rename = "bodyPr", default)]+ pub(crate) body_pr: Option<BodyPrXml>,+ #[serde(rename = "txbx", default)]+ pub(crate) txbx: Option<TxbxXml>,+}++// ── wps:style (§20.1.4.1.4 CT_ShapeStyle) ─────────────────────────────────+//+// References into the theme's style matrices. Only `effectRef` is consumed+// today; the other siblings (`lnRef`, `fillRef`, `fontRef`) are siblings+// whose schema differs (`fontRef/@idx` is a string enum, not a number), so+// they're silently skipped via serde's default unknown-element behavior.++#[derive(Deserialize, Default)]+pub(crate) struct ShapeStyleXml {+ #[serde(rename = "lnRef", default)]+ pub(crate) ln_ref: Option<StyleMatrixRefXml>,+ #[serde(rename = "fillRef", default)]+ pub(crate) fill_ref: Option<StyleMatrixRefXml>,+ #[serde(rename = "effectRef", default)]+ pub(crate) effect_ref: Option<StyleMatrixRefXml>,+ /// §20.1.4.1.17 a:fontRef — `@idx` is `ST_FontCollectionIndex` (a string+ /// enum, unlike the numeric matrix refs above), plus an optional color.+ #[serde(rename = "fontRef", default)]+ pub(crate) font_ref: Option<FontRefXml>,+}++/// §20.1.4.1.17 CT_FontReference.+#[derive(Deserialize)]+pub(crate) struct FontRefXml {+ #[serde(+ rename = "@idx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub(crate) idx: StFontCollectionIndex,+ #[serde(rename = "$value", default)]+ pub(crate) color: Option<DrawingColorXml>,+}++/// §20.1.8.30 ST_FontCollectionIndex.+#[derive(Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub(crate) enum StFontCollectionIndex {+ Major,+ Minor,+ #[default]+ None,+}++impl From<StFontCollectionIndex> for FontCollectionIndex {+ fn from(x: StFontCollectionIndex) -> Self {+ match x {+ StFontCollectionIndex::Major => Self::Major,+ StFontCollectionIndex::Minor => Self::Minor,+ StFontCollectionIndex::None => Self::None,+ }+ }+}++impl From<FontRefXml> for FontReference {+ fn from(x: FontRefXml) -> Self {+ Self {+ collection: x.idx.into(),+ color: x.color.and_then(to_drawing_color),+ }+ }+}++/// §20.1.4.2.19 CT_StyleMatrixReference — `idx` + optional color for+/// `phClr` substitution within the referenced theme style.+#[derive(Deserialize)]+pub(crate) struct StyleMatrixRefXml {+ /// Style-matrix index is cosmetic; zero selects the default entry.+ #[serde(+ rename = "@idx",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ pub(crate) idx: u32,+ #[serde(rename = "$value", default)]+ pub(crate) color: Option<DrawingColorXml>,+}++impl From<StyleMatrixRefXml> for StyleMatrixRef {+ fn from(x: StyleMatrixRefXml) -> Self {+ Self {+ idx: x.idx,+ color: x.color.and_then(to_drawing_color),+ }+ }+}++#[derive(Deserialize, Default)]+pub(crate) struct TxbxXml {+ #[serde(rename = "txbxContent", default)]+ pub(crate) content: Option<TxbxContentXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct TxbxContentXml {+ #[serde(rename = "$value", default)]+ pub(crate) children: Vec<crate::docx::parse::body_schema::BlockChildXml>,+}++impl WspXml {+ /// Convert to the model; `ctx` drives drawing/pict embed resolution+ /// inside the text box content.+ pub(crate) fn into_model(+ self,+ ctx: &mut crate::docx::parse::body::ConvertCtx,+ ) -> WordProcessingShape {+ let txbx_content: Vec<Block> = self+ .txbx+ .and_then(|t| t.content)+ .map(|c| {+ let (blocks, _) = crate::docx::parse::body::convert_container(c.children, ctx);+ blocks+ })+ .unwrap_or_default();+ let (style_line_ref, style_fill_ref, style_effect_ref, style_font_ref) = match self.style {+ Some(s) => (+ s.ln_ref.map(Into::into),+ s.fill_ref.map(Into::into),+ s.effect_ref.map(Into::into),+ s.font_ref.map(Into::into),+ ),+ None => (None, None, None, None),+ };+ WordProcessingShape {+ cnv_pr: self.cnv_pr.map(Into::into),+ shape_properties: self.sp_pr.map(Into::into),+ style_line_ref,+ style_effect_ref,+ style_fill_ref,+ style_font_ref,+ body_pr: self.body_pr.map(Into::into),+ txbx_content,+ }+ }+}++// ── ST enums ──────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StBlackWhiteMode {+ Auto,+ Black,+ BlackGray,+ BlackWhite,+ Clr,+ Gray,+ GrayWhite,+ Hidden,+ InvGray,+ LtGray,+ White,+}++impl From<StBlackWhiteMode> for BlackWhiteMode {+ fn from(s: StBlackWhiteMode) -> Self {+ match s {+ StBlackWhiteMode::Auto => Self::Auto,+ StBlackWhiteMode::Black => Self::Black,+ StBlackWhiteMode::BlackGray => Self::BlackGray,+ StBlackWhiteMode::BlackWhite => Self::BlackWhite,+ StBlackWhiteMode::Clr => Self::Clr,+ StBlackWhiteMode::Gray => Self::Gray,+ StBlackWhiteMode::GrayWhite => Self::GrayWhite,+ StBlackWhiteMode::Hidden => Self::Hidden,+ StBlackWhiteMode::InvGray => Self::InvGray,+ StBlackWhiteMode::LtGray => Self::LtGray,+ StBlackWhiteMode::White => Self::White,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StTextVerticalType {+ Horz,+ Vert,+ Vert270,+ WordArtVert,+ EaVert,+ MongolianVert,+ WordArtVertRtl,+}++impl From<StTextVerticalType> for TextVerticalType {+ fn from(s: StTextVerticalType) -> Self {+ use StTextVerticalType as X;+ match s {+ X::Horz => Self::Horz,+ X::Vert => Self::Vert,+ X::Vert270 => Self::Vert270,+ X::WordArtVert => Self::WordArtVert,+ X::EaVert => Self::EaVert,+ X::MongolianVert => Self::MongolianVert,+ X::WordArtVertRtl => Self::WordArtVertRtl,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StTextWrappingType {+ None,+ Square,+}++impl From<StTextWrappingType> for TextWrappingType {+ fn from(s: StTextWrappingType) -> Self {+ match s {+ StTextWrappingType::None => Self::None,+ StTextWrappingType::Square => Self::Square,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StTextAnchoringType {+ #[serde(rename = "t")]+ T,+ #[serde(rename = "ctr")]+ Ctr,+ #[serde(rename = "b")]+ B,+ #[serde(rename = "just")]+ Just,+ #[serde(rename = "dist")]+ Dist,+}++/// ST_TextVertOverflowType. `overflow` is the spec default, so an absent+/// attribute and an explicit `overflow` mean the same thing.+#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StTextVertOverflowType {+ #[serde(rename = "overflow")]+ Overflow,+ #[serde(rename = "ellipsis")]+ Ellipsis,+ #[serde(rename = "clip")]+ Clip,+}++impl From<StTextVertOverflowType> for TextVertOverflow {+ fn from(s: StTextVertOverflowType) -> Self {+ match s {+ StTextVertOverflowType::Overflow => Self::Overflow,+ StTextVertOverflowType::Ellipsis => Self::Ellipsis,+ StTextVertOverflowType::Clip => Self::Clip,+ }+ }+}++impl From<StTextAnchoringType> for TextAnchoringType {+ fn from(s: StTextAnchoringType) -> Self {+ match s {+ StTextAnchoringType::T => Self::Top,+ StTextAnchoringType::Ctr => Self::Center,+ StTextAnchoringType::B => Self::Bottom,+ StTextAnchoringType::Just => Self::Justified,+ StTextAnchoringType::Dist => Self::Distributed,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::{PathFillMode, PresetShapeType, ShapeGeometry, TextWrappingType};++ fn parse_sp_pr(xml: &str) -> ShapeProperties {+ let wrapped = format!(+ r#"<wrap xmlns:a="urn:a" xmlns:r="urn:r" xmlns:w="urn:w" xmlns:wps="urn:wps">{}</wrap>"#,+ xml+ );+ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "spPr")]+ sp: SpPrXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.sp.into()+ }++ #[test]+ fn empty_sp_pr() {+ let sp = parse_sp_pr(r#"<spPr/>"#);+ assert!(sp.geometry.is_none());+ assert!(sp.fill.is_none());+ }++ #[test]+ fn transform_with_offset_and_ext() {+ let sp = parse_sp_pr(+ r#"<spPr>+ <xfrm rot="5400000" flipH="1">+ <off x="100" y="200"/>+ <ext cx="914400" cy="457200"/>+ </xfrm>+ </spPr>"#,+ );+ let t = sp.transform.unwrap();+ assert_eq!(t.rotation.unwrap().raw(), 5_400_000);+ assert_eq!(t.flip_h, Some(true));+ assert_eq!(t.offset.unwrap().x.raw(), 100);+ assert_eq!(t.extent.unwrap().width.raw(), 914_400);+ }++ #[test]+ fn preset_geometry_rect() {+ let sp = parse_sp_pr(r#"<spPr><prstGeom prst="rect"/></spPr>"#);+ match sp.geometry {+ Some(ShapeGeometry::Preset(p)) => assert_eq!(p.preset, PresetShapeType::Rect),+ other => panic!("expected Preset(Rect), got {other:?}"),+ }+ }++ #[test]+ fn preset_with_adjust_values() {+ let sp = parse_sp_pr(+ r#"<spPr>+ <prstGeom prst="roundRect">+ <avLst><gd name="adj" fmla="val 20000"/></avLst>+ </prstGeom>+ </spPr>"#,+ );+ match sp.geometry {+ Some(ShapeGeometry::Preset(p)) => {+ assert_eq!(p.preset, PresetShapeType::RoundRect);+ assert_eq!(p.adjust_values.len(), 1);+ assert_eq!(p.adjust_values[0].formula, "val 20000");+ }+ other => panic!("got {other:?}"),+ }+ }++ #[test]+ fn preset_unknown_falls_back_to_other() {+ let sp = parse_sp_pr(r#"<spPr><prstGeom prst="newShapeType2030"/></spPr>"#);+ match sp.geometry {+ Some(ShapeGeometry::Preset(p)) => match p.preset {+ PresetShapeType::Other(s) => assert_eq!(s, "newShapeType2030"),+ other => panic!("expected Other, got {other:?}"),+ },+ other => panic!("got {other:?}"),+ }+ }++ #[test]+ fn custom_geometry_routed() {+ let sp = parse_sp_pr(+ r#"<spPr>+ <custGeom>+ <pathLst>+ <path w="100" h="100">+ <moveTo><pt x="0" y="0"/></moveTo>+ <close/>+ </path>+ </pathLst>+ </custGeom>+ </spPr>"#,+ );+ match sp.geometry {+ Some(ShapeGeometry::Custom(c)) => {+ assert_eq!(c.paths.len(), 1);+ assert_eq!(c.paths[0].fill, PathFillMode::Norm);+ }+ other => panic!("got {other:?}"),+ }+ }++ #[test]+ fn solid_fill_inside_sp_pr() {+ let sp = parse_sp_pr(r#"<spPr><solidFill><srgbClr val="FF0000"/></solidFill></spPr>"#);+ assert!(matches!(sp.fill, Some(DrawingFill::Solid(_))));+ }++ #[test]+ fn no_fill_inside_sp_pr() {+ let sp = parse_sp_pr(r#"<spPr><noFill/></spPr>"#);+ assert!(matches!(sp.fill, Some(DrawingFill::None)));+ }++ #[test]+ fn outline_routes_through_stroke() {+ let sp = parse_sp_pr(r#"<spPr><ln w="9525"><prstDash val="dashDot"/></ln></spPr>"#);+ let o = sp.outline.unwrap();+ assert_eq!(o.width.unwrap().raw(), 9525);+ }++ #[test]+ fn effect_list_routes_through_effect() {+ let sp = parse_sp_pr(+ r#"<spPr><effectLst><outerShdw blurRad="0" dist="0" dir="0">+ <srgbClr val="000000"/>+ </outerShdw></effectLst></spPr>"#,+ );+ assert_eq!(sp.effect_list.unwrap().effects.len(), 1);+ }++ // ── Body properties ──++ fn parse_body_pr(xml: &str) -> BodyProperties {+ let wrapped = format!(r#"<wrap xmlns:a="urn:a">{}</wrap>"#, xml);+ #[derive(Deserialize)]+ struct Wrap {+ #[serde(rename = "bodyPr")]+ bp: BodyPrXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.bp.into()+ }++ #[test]+ fn body_pr_attrs_and_autofit() {+ let bp = parse_body_pr(+ r#"<bodyPr rot="0" vert="horz" wrap="square" anchor="ctr"+ lIns="91440" tIns="45720" rIns="91440" bIns="45720">+ <normAutofit/>+ </bodyPr>"#,+ );+ assert_eq!(bp.wrap, Some(TextWrappingType::Square));+ assert_eq!(bp.anchor, Some(TextAnchoringType::Center));+ assert_eq!(+ bp.auto_fit,+ Some(TextAutoFit::NormalAutoFit(NormalAutoFit::default()))+ );+ assert_eq!(bp.left_inset.unwrap().raw(), 91440);+ }++ #[test]+ fn body_pr_no_autofit() {+ let bp = parse_body_pr(r#"<bodyPr><noAutofit/></bodyPr>"#);+ assert_eq!(bp.auto_fit, Some(TextAutoFit::NoAutoFit));+ }++ /// §20.1.2.1.18: `normAutofit` carries the shrink Word already computed.+ /// Both attributes are thousandths of a percent — `62500` is 62.5%, not+ /// 62500%.+ #[test]+ fn norm_autofit_keeps_the_scale_word_computed() {+ let bp = parse_body_pr(+ r#"<bodyPr><normAutofit fontScale="62500" lnSpcReduction="20000"/></bodyPr>"#,+ );+ let Some(TextAutoFit::NormalAutoFit(na)) = bp.auto_fit else {+ panic!("expected normAutofit, got {:?}", bp.auto_fit);+ };+ assert_eq!(na.font_scale.unwrap().raw(), 62500);+ assert_eq!(na.line_spacing_reduction.unwrap().raw(), 20000);+ }++ /// `@vertOverflow` reaches the model for all three values, and an absent+ /// attribute stays `None` — the model's `Default` is what supplies+ /// `overflow`, so parse never has to invent it.+ #[test]+ fn vert_overflow_reaches_the_model() {+ assert_eq!(parse_body_pr(r#"<bodyPr/>"#).vert_overflow, None);+ assert_eq!(+ parse_body_pr(r#"<bodyPr vertOverflow="overflow"/>"#).vert_overflow,+ Some(TextVertOverflow::Overflow)+ );+ assert_eq!(+ parse_body_pr(r#"<bodyPr vertOverflow="clip"/>"#).vert_overflow,+ Some(TextVertOverflow::Clip)+ );+ assert_eq!(+ parse_body_pr(r#"<bodyPr vertOverflow="ellipsis"/>"#).vert_overflow,+ Some(TextVertOverflow::Ellipsis)+ );+ assert_eq!(TextVertOverflow::default(), TextVertOverflow::Overflow);+ }++ /// Each attribute is independent — Word writes `fontScale` alone whenever+ /// shrinking the glyphs was enough on its own.+ #[test]+ fn norm_autofit_attributes_are_independent() {+ let scale_only = parse_body_pr(r#"<bodyPr><normAutofit fontScale="90000"/></bodyPr>"#);+ assert_eq!(+ scale_only.auto_fit,+ Some(TextAutoFit::NormalAutoFit(NormalAutoFit {+ font_scale: Some(Dimension::new(90000)),+ line_spacing_reduction: None,+ }))+ );++ let reduction_only =+ parse_body_pr(r#"<bodyPr><normAutofit lnSpcReduction="10000"/></bodyPr>"#);+ assert_eq!(+ reduction_only.auto_fit,+ Some(TextAutoFit::NormalAutoFit(NormalAutoFit {+ font_scale: None,+ line_spacing_reduction: Some(Dimension::new(10000)),+ }))+ );+ }++ #[test]+ fn body_pr_preserves_signed_decimal_insets() {+ // §20.1.2.1.1: lIns/tIns/rIns/bIns are ST_Coordinate32 (signed); a+ // negative inset lets text overflow the shape box and must survive+ // parsing (Word also emits decimal-valued measurements).+ let bp = parse_body_pr(r#"<bodyPr lIns="-91440" tIns="-45720.0" rIns="91440" bIns="0"/>"#);+ assert_eq!(bp.left_inset.unwrap().raw(), -91440);+ assert_eq!(bp.top_inset.unwrap().raw(), -45720);+ assert_eq!(bp.right_inset.unwrap().raw(), 91440);+ assert_eq!(bp.bottom_inset.unwrap().raw(), 0);+ }++ // ── wsp ──++ #[test]+ fn wsp_with_txbx_empty() {+ let xml = r#"<wrap xmlns:wps="urn:wps" xmlns:w="urn:w" xmlns:a="urn:a" xmlns:r="urn:r">+ <wsp>+ <cNvPr id="1" name="Shape1"/>+ <spPr><prstGeom prst="rect"/></spPr>+ <bodyPr/>+ <txbx><txbxContent/></txbx>+ </wsp>+ </wrap>"#;+ #[derive(Deserialize)]+ struct Wrap {+ wsp: WspXml,+ }+ let w: Wrap = quick_xml::de::from_str(xml).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ let wsp = w.wsp.into_model(&mut ctx);+ assert_eq!(wsp.cnv_pr.unwrap().name, "Shape1");+ assert!(wsp.txbx_content.is_empty());+ }++ #[test]+ fn wsp_txbx_with_paragraph() {+ let xml = r#"<wrap xmlns:wps="urn:wps" xmlns:w="urn:w" xmlns:a="urn:a" xmlns:r="urn:r">+ <wsp>+ <cNvPr id="2" name="Shape2"/>+ <spPr><prstGeom prst="rect"/></spPr>+ <bodyPr/>+ <txbx>+ <txbxContent>+ <w:p><w:r><w:t>Hello</w:t></w:r></w:p>+ </txbxContent>+ </txbx>+ </wsp>+ </wrap>"#;+ #[derive(Deserialize)]+ struct Wrap {+ wsp: WspXml,+ }+ let w: Wrap = quick_xml::de::from_str(xml).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ let wsp = w.wsp.into_model(&mut ctx);+ assert_eq!(wsp.txbx_content.len(), 1);+ match &wsp.txbx_content[0] {+ Block::Paragraph(_) => (),+ other => panic!("expected Paragraph, got {other:?}"),+ }+ }++ #[test]+ fn wsp_style_fill_ref_parsed() {+ // §20.1.4.1.13: a `<wps:style><a:fillRef>` is captured with its idx and+ // phClr-substitute color for theme-fill resolution.+ let xml = r#"<wrap xmlns:wps="urn:wps" xmlns:w="urn:w" xmlns:a="urn:a" xmlns:r="urn:r">+ <wsp>+ <cNvPr id="1" name="S"/>+ <style>+ <lnRef idx="2"><schemeClr val="accent1"/></lnRef>+ <fillRef idx="1"><schemeClr val="accent1"/></fillRef>+ <effectRef idx="0"/>+ </style>+ <spPr><prstGeom prst="rect"/></spPr>+ <bodyPr/>+ </wsp>+ </wrap>"#;+ #[derive(Deserialize)]+ struct Wrap {+ wsp: WspXml,+ }+ let w: Wrap = quick_xml::de::from_str(xml).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ let wsp = w.wsp.into_model(&mut ctx);+ let fr = wsp.style_fill_ref.expect("fillRef parsed");+ assert_eq!(fr.idx, 1);+ assert!(fr.color.is_some(), "phClr-substitute color captured");+ }++ #[test]+ fn wsp_style_font_ref_parsed() {+ // §20.1.4.1.17: fontRef carries the shape's default text color (here a+ // light scheme color for text on a dark fill) and the theme font+ // collection (`@idx` is a string enum: major/minor/none).+ let xml = r#"<wrap xmlns:wps="urn:wps" xmlns:w="urn:w" xmlns:a="urn:a" xmlns:r="urn:r">+ <wsp>+ <cNvPr id="1" name="S"/>+ <style>+ <fillRef idx="1"><schemeClr val="accent1"/></fillRef>+ <fontRef idx="minor"><schemeClr val="lt1"/></fontRef>+ </style>+ <bodyPr/>+ </wsp>+ </wrap>"#;+ #[derive(Deserialize)]+ struct Wrap {+ wsp: WspXml,+ }+ let w: Wrap = quick_xml::de::from_str(xml).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ let wsp = w.wsp.into_model(&mut ctx);+ let fr = wsp.style_font_ref.expect("fontRef parsed");+ assert_eq!(fr.collection, FontCollectionIndex::Minor);+ assert!(fr.color.is_some(), "fontRef text color captured");+ }++ // ── Picture spPr wiring (now that shape schema exists) ──+ // (We don't re-wire picture.rs here; that's a follow-up edit.)+}diff --git a/crates/liteparse-docx/src/docx/parse/drawing/schema/stroke.rs b/crates/liteparse-docx/src/docx/parse/drawing/schema/stroke.rsnew file mode 100644index 0000000..f089ee0--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/drawing/schema/stroke.rs@@ -0,0 +1,530 @@+//! DrawingML outline schema (§20.1.2.2.24 CT_LineProperties).+//!+//! `<a:ln>` with optional attributes (width, cap, compound, alignment) and+//! optional children for fill, dash, join, and head/tail arrows. Consumes+//! `DrawingFillXml` from the fill schema.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::dimension::{Dimension, Emu, ThousandthPercent};+use crate::docx::model::{+ CompoundLine, DashStop, LineCap, LineDash, LineEnd, LineEndSize, LineEndType, LineJoin,+ Outline, PenAlignment, PresetLineDashVal,+};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++use super::fill::DrawingFillXml;++/// `<a:ln …>` — outline (§20.1.2.2.24 CT_LineProperties).+#[derive(Debug, Deserialize)]+pub struct OutlineXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub w: Option<Dimension<Emu>>,+ #[serde(+ rename = "@cap",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub cap: Option<StLineCap>,+ #[serde(+ rename = "@cmpd",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub cmpd: Option<StCompoundLine>,+ #[serde(+ rename = "@algn",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub algn: Option<StPenAlignment>,+ #[serde(rename = "$value", default)]+ pub children: Vec<LnChildXml>,+}++/// Each child of `<a:ln>` is either a fill choice, a dash choice, a join+/// choice, or a head/tail end spec.+#[derive(Debug, Deserialize)]+pub enum LnChildXml {+ // Fill choices — forward to DrawingFillXml.+ #[serde(rename = "noFill")]+ NoFill(super::fill::Empty),+ #[serde(rename = "grpFill")]+ GrpFill(super::fill::Empty),+ #[serde(rename = "solidFill")]+ SolidFill(super::fill::SolidFillXml),+ #[serde(rename = "gradFill")]+ GradFill(super::fill::GradFillXml),+ #[serde(rename = "blipFill")]+ BlipFill(super::fill::BlipFillXml),+ #[serde(rename = "pattFill")]+ PattFill(super::fill::PattFillXml),++ // Dash choices.+ #[serde(rename = "prstDash")]+ PrstDash(PrstDashXml),+ #[serde(rename = "custDash")]+ CustDash(CustDashXml),++ // Join choices (parameterless unit variants for round/bevel/miter).+ #[serde(rename = "round")]+ Round(super::fill::Empty),+ #[serde(rename = "bevel")]+ Bevel(super::fill::Empty),+ #[serde(rename = "miter")]+ Miter(MiterXml),++ // Head/tail arrows.+ #[serde(rename = "headEnd")]+ HeadEnd(LineEndXml),+ #[serde(rename = "tailEnd")]+ TailEnd(LineEndXml),++ // §20.1.2.2.24 CT_LineProperties ends with an optional `<a:extLst>`, and+ // producers may emit other extension children. Absorb anything unknown+ // rather than failing the whole document (theme `lnStyleLst` feeds this).+ #[serde(other)]+ Other,+}++#[derive(Debug, Deserialize)]+pub struct PrstDashXml {+ // Word emits empty `<a:prstDash/>` in some files; tolerate the missing val.+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub val: Option<StPresetLineDashVal>,+}++#[derive(Debug, Deserialize, Default)]+pub struct CustDashXml {+ #[serde(rename = "ds", default)]+ pub stops: Vec<DsXml>,+}++#[derive(Debug, Deserialize)]+pub struct DsXml {+ #[serde(+ rename = "@d",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub d: Dimension<ThousandthPercent>,+ #[serde(+ rename = "@sp",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::nonneg_or_default"+ )]+ pub sp: Dimension<ThousandthPercent>,+}++#[derive(Debug, Deserialize)]+pub struct MiterXml {+ #[serde(+ rename = "@lim",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ pub lim: Option<Dimension<ThousandthPercent>>,+}++#[derive(Debug, Deserialize)]+pub struct LineEndXml {+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub ty: Option<StLineEndType>,+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub w: Option<StLineEndSize>,+ #[serde(+ rename = "@len",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub len: Option<StLineEndSize>,+}++// ── ST enums ──────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StLineCap {+ #[serde(rename = "flat")]+ Flat,+ #[serde(rename = "rnd")]+ Rnd,+ #[serde(rename = "sq")]+ Sq,+}++impl From<StLineCap> for LineCap {+ fn from(s: StLineCap) -> Self {+ match s {+ StLineCap::Flat => Self::Flat,+ StLineCap::Rnd => Self::Round,+ StLineCap::Sq => Self::Square,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StCompoundLine {+ #[serde(rename = "sng")]+ Sng,+ #[serde(rename = "dbl")]+ Dbl,+ #[serde(rename = "thickThin")]+ ThickThin,+ #[serde(rename = "thinThick")]+ ThinThick,+ #[serde(rename = "tri")]+ Tri,+}++impl From<StCompoundLine> for CompoundLine {+ fn from(s: StCompoundLine) -> Self {+ match s {+ StCompoundLine::Sng => Self::Single,+ StCompoundLine::Dbl => Self::Double,+ StCompoundLine::ThickThin => Self::ThickThin,+ StCompoundLine::ThinThick => Self::ThinThick,+ StCompoundLine::Tri => Self::Triple,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StPenAlignment {+ #[serde(rename = "ctr")]+ Ctr,+ #[serde(rename = "in")]+ In,+}++impl From<StPenAlignment> for PenAlignment {+ fn from(s: StPenAlignment) -> Self {+ match s {+ StPenAlignment::Ctr => Self::Center,+ StPenAlignment::In => Self::Inset,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPresetLineDashVal {+ Solid,+ Dot,+ Dash,+ LgDash,+ DashDot,+ LgDashDot,+ LgDashDotDot,+ SysDash,+ SysDot,+ SysDashDot,+ SysDashDotDot,+}++impl From<StPresetLineDashVal> for PresetLineDashVal {+ fn from(s: StPresetLineDashVal) -> Self {+ use StPresetLineDashVal as X;+ match s {+ X::Solid => Self::Solid,+ X::Dot => Self::Dot,+ X::Dash => Self::Dash,+ X::LgDash => Self::LgDash,+ X::DashDot => Self::DashDot,+ X::LgDashDot => Self::LgDashDot,+ X::LgDashDotDot => Self::LgDashDotDot,+ X::SysDash => Self::SysDash,+ X::SysDot => Self::SysDot,+ X::SysDashDot => Self::SysDashDot,+ X::SysDashDotDot => Self::SysDashDotDot,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StLineEndType {+ None,+ Triangle,+ Stealth,+ Diamond,+ Oval,+ Arrow,+}++impl From<StLineEndType> for LineEndType {+ fn from(s: StLineEndType) -> Self {+ match s {+ StLineEndType::None => Self::None,+ StLineEndType::Triangle => Self::Triangle,+ StLineEndType::Stealth => Self::Stealth,+ StLineEndType::Diamond => Self::Diamond,+ StLineEndType::Oval => Self::Oval,+ StLineEndType::Arrow => Self::Arrow,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub enum StLineEndSize {+ #[serde(rename = "sm")]+ Sm,+ #[serde(rename = "med")]+ Med,+ #[serde(rename = "lg")]+ Lg,+}++impl From<StLineEndSize> for LineEndSize {+ fn from(s: StLineEndSize) -> Self {+ match s {+ StLineEndSize::Sm => Self::Sm,+ StLineEndSize::Med => Self::Med,+ StLineEndSize::Lg => Self::Lg,+ }+ }+}++// ── Conversion to model ───────────────────────────────────────────────────++impl From<OutlineXml> for Outline {+ fn from(x: OutlineXml) -> Self {+ let mut fill = None;+ let mut dash = None;+ let mut join = None;+ let mut head_end = None;+ let mut tail_end = None;++ for child in x.children {+ match child {+ LnChildXml::NoFill(_)+ | LnChildXml::GrpFill(_)+ | LnChildXml::SolidFill(_)+ | LnChildXml::GradFill(_)+ | LnChildXml::BlipFill(_)+ | LnChildXml::PattFill(_) => {+ // Wrap the raw variant into a DrawingFillXml for conversion.+ let f = match child {+ LnChildXml::NoFill(e) => DrawingFillXml::NoFill(e),+ LnChildXml::GrpFill(e) => DrawingFillXml::GrpFill(e),+ LnChildXml::SolidFill(s) => DrawingFillXml::SolidFill(s),+ LnChildXml::GradFill(g) => DrawingFillXml::GradFill(g),+ LnChildXml::BlipFill(b) => DrawingFillXml::BlipFill(b),+ LnChildXml::PattFill(p) => DrawingFillXml::PattFill(p),+ _ => unreachable!(),+ };+ fill = Some(f.into());+ }+ LnChildXml::PrstDash(p) => {+ if let Some(v) = p.val {+ dash = Some(LineDash::Preset(v.into()));+ }+ }+ LnChildXml::CustDash(c) => {+ dash = Some(LineDash::Custom(+ c.stops+ .into_iter()+ .map(|d| DashStop {+ dash: d.d,+ space: d.sp,+ })+ .collect(),+ ));+ }+ LnChildXml::Round(_) => join = Some(LineJoin::Round),+ LnChildXml::Bevel(_) => join = Some(LineJoin::Bevel),+ LnChildXml::Miter(m) => {+ join = Some(LineJoin::Miter { limit: m.lim });+ }+ LnChildXml::HeadEnd(le) => {+ head_end = Some(line_end(le));+ }+ LnChildXml::TailEnd(le) => {+ tail_end = Some(line_end(le));+ }+ LnChildXml::Other => {}+ }+ }++ Self {+ width: x.w,+ cap: x.cap.map(Into::into),+ compound: x.cmpd.map(Into::into),+ alignment: x.algn.map(Into::into),+ fill,+ dash,+ join,+ head_end,+ tail_end,+ }+ }+}++fn line_end(le: LineEndXml) -> LineEnd {+ LineEnd {+ kind: le.ty.map(Into::into).unwrap_or(LineEndType::None),+ width: le.w.map(Into::into).unwrap_or(LineEndSize::Med),+ length: le.len.map(Into::into).unwrap_or(LineEndSize::Med),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::DrawingFill;++ fn parse(xml: &str) -> Outline {+ let wrapped = format!(r#"<wrap xmlns:a="urn:a" xmlns:r="urn:r">{}</wrap>"#, xml);+ #[derive(Deserialize)]+ struct Wrap {+ ln: OutlineXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ w.ln.into()+ }++ #[test]+ fn empty_outline() {+ let o = parse(r#"<ln/>"#);+ assert!(o.width.is_none());+ assert!(o.fill.is_none());+ assert!(o.dash.is_none());+ }++ #[test]+ fn width_and_cap() {+ let o = parse(r#"<ln w="12700" cap="flat" algn="ctr" cmpd="dbl"/>"#);+ assert_eq!(o.width.unwrap().raw(), 12700);+ assert_eq!(o.cap, Some(LineCap::Flat));+ assert_eq!(o.compound, Some(CompoundLine::Double));+ assert_eq!(o.alignment, Some(PenAlignment::Center));+ }++ #[test]+ fn solid_fill_child() {+ let o = parse(r#"<ln><solidFill><srgbClr val="FF0000"/></solidFill></ln>"#);+ match o.fill {+ Some(DrawingFill::Solid(_)) => (),+ other => panic!("expected Solid fill, got {other:?}"),+ }+ }++ #[test]+ fn preset_dash() {+ let o = parse(r#"<ln><prstDash val="dashDot"/></ln>"#);+ match o.dash {+ Some(LineDash::Preset(PresetLineDashVal::DashDot)) => (),+ other => panic!("expected Preset(DashDot), got {other:?}"),+ }+ }++ #[test]+ fn custom_dash_stops() {+ let o = parse(+ r#"<ln><custDash>+ <ds d="100000" sp="50000"/>+ <ds d="200000" sp="50000"/>+ </custDash></ln>"#,+ );+ match o.dash {+ Some(LineDash::Custom(stops)) => {+ assert_eq!(stops.len(), 2);+ assert_eq!(stops[0].dash.raw(), 100000);+ assert_eq!(stops[0].space.raw(), 50000);+ }+ other => panic!("expected Custom dash, got {other:?}"),+ }+ }++ #[test]+ fn join_round_bevel_miter() {+ assert!(matches!(+ parse(r#"<ln><round/></ln>"#).join,+ Some(LineJoin::Round)+ ));+ assert!(matches!(+ parse(r#"<ln><bevel/></ln>"#).join,+ Some(LineJoin::Bevel)+ ));+ match parse(r#"<ln><miter lim="800000"/></ln>"#).join {+ Some(LineJoin::Miter { limit: Some(d) }) => assert_eq!(d.raw(), 800000),+ other => panic!("expected Miter, got {other:?}"),+ }+ }++ #[test]+ fn head_end_arrow() {+ let o = parse(r#"<ln><headEnd type="arrow" w="lg" len="sm"/></ln>"#);+ let h = o.head_end.unwrap();+ assert_eq!(h.kind, LineEndType::Arrow);+ assert_eq!(h.width, LineEndSize::Lg);+ assert_eq!(h.length, LineEndSize::Sm);+ }++ #[test]+ fn tail_end_defaults_when_attrs_missing() {+ let o = parse(r#"<ln><tailEnd/></ln>"#);+ let t = o.tail_end.unwrap();+ assert_eq!(t.kind, LineEndType::None);+ assert_eq!(t.width, LineEndSize::Med);+ assert_eq!(t.length, LineEndSize::Med);+ }++ #[test]+ fn outline_with_ext_lst_is_tolerated() {+ // §20.1.2.2.24 CT_LineProperties permits a trailing <a:extLst>; an+ // unknown child must be absorbed, not crash the theme parse. The+ // recognised siblings still resolve.+ let o = parse(+ r#"<ln w="9525">+ <solidFill><srgbClr val="FF0000"/></solidFill>+ <prstDash val="solid"/>+ <extLst><ext uri="{X}"><foo/></ext></extLst>+ </ln>"#,+ );+ assert_eq!(o.width.unwrap().raw(), 9525);+ assert!(matches!(o.fill, Some(DrawingFill::Solid(_))));+ assert!(matches!(+ o.dash,+ Some(LineDash::Preset(PresetLineDashVal::Solid))+ ));+ }++ #[test]+ fn full_outline_end_to_end() {+ let o = parse(+ r#"<ln w="9525" cap="rnd" cmpd="sng" algn="in">+ <solidFill><schemeClr val="accent1"/></solidFill>+ <prstDash val="solid"/>+ <round/>+ <tailEnd type="triangle" w="med" len="med"/>+ </ln>"#,+ );+ assert_eq!(o.width.unwrap().raw(), 9525);+ assert_eq!(o.cap, Some(LineCap::Round));+ assert!(matches!(o.fill, Some(DrawingFill::Solid(_))));+ assert!(matches!(+ o.dash,+ Some(LineDash::Preset(PresetLineDashVal::Solid))+ ));+ assert_eq!(o.join, Some(LineJoin::Round));+ assert_eq!(o.tail_end.unwrap().kind, LineEndType::Triangle);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/fonts.rs b/crates/liteparse-docx/src/docx/parse/fonts.rsnew file mode 100644index 0000000..3b98121--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/fonts.rs@@ -0,0 +1,259 @@+//! §17.8: Font table parsing — extract embedded font declarations and de-obfuscate font data.+//!+//! Parses `word/fontTable.xml` to discover embedded font references,+//! then de-obfuscates `.odttf` files per §17.8.3.3.++use serde::Deserialize;++use crate::docx::error::{ParseError, Result};+use crate::docx::parse::serde_xml::from_xml;+use crate::docx::relationships::Relationships;+use crate::docx::zip::PackageContents;++use crate::model::{EmbeddedFont, EmbeddedFontVariant, RelId};++/// A raw embedded font reference before de-obfuscation.+struct FontEmbedRef {+ family: String,+ variant: EmbeddedFontVariant,+ rel_id: String,+ font_key: String,+}++/// Parse `fontTable.xml` and extract all embedded fonts.+///+/// Returns de-obfuscated font data ready for registration with a font manager.+///+/// Per §17.8.3.3, embedded fonts are obfuscated by XOR-ing the first 32 bytes+/// with the fontKey GUID (16 bytes, applied twice).+pub fn parse_embedded_fonts(+ font_table_data: &[u8],+ font_table_rels: &Relationships,+ package: &mut PackageContents,+ font_table_dir: &str,+) -> Result<Vec<EmbeddedFont>> {+ let refs = parse_font_table(font_table_data)?;++ let mut fonts = Vec::new();+ for embed_ref in refs {+ // Look up the relationship to find the font file path.+ let target_id = RelId::new(&embed_ref.rel_id);+ let rel = font_table_rels+ .rels+ .iter()+ .find(|r| r.id == target_id)+ .ok_or_else(|| {+ ParseError::MissingPart(format!(+ "font relationship '{}' for '{}'",+ embed_ref.rel_id, embed_ref.family+ ))+ })?;++ let font_path = crate::docx::zip::resolve_target(font_table_dir, &rel.target);+ let font_data = package.take_part(&font_path).ok_or_else(|| {+ ParseError::MissingPart(format!(+ "font file '{font_path}' for '{}'",+ embed_ref.family+ ))+ })?;++ // Without a usable fontKey this one embedded font cannot be+ // de-obfuscated. Skip it — the document still renders with a+ // substituted face, which beats failing the whole parse.+ let key_bytes = match parse_font_key(&embed_ref.font_key) {+ Ok(k) => k,+ Err(e) => {+ log::warn!(+ "skipping embedded font '{}': unusable fontKey: {e}",+ embed_ref.family+ );+ continue;+ }+ };+ let data = deobfuscate_font(font_data, &key_bytes);++ fonts.push(EmbeddedFont {+ family: embed_ref.family,+ variant: embed_ref.variant,+ data,+ });+ }++ Ok(fonts)+}++/// Parse fontTable.xml and extract embedded font references.+fn parse_font_table(data: &[u8]) -> Result<Vec<FontEmbedRef>> {+ let ft: FontTableXml = from_xml(data)?;+ let mut refs = Vec::new();+ for font in ft.fonts {+ for (variant, embed) in [+ (EmbeddedFontVariant::Regular, font.embed_regular),+ (EmbeddedFontVariant::Bold, font.embed_bold),+ (EmbeddedFontVariant::Italic, font.embed_italic),+ (EmbeddedFontVariant::BoldItalic, font.embed_bold_italic),+ ] {+ if let Some(e) = embed {+ refs.push(FontEmbedRef {+ family: font.name.clone(),+ variant,+ rel_id: e.id,+ font_key: e.font_key,+ });+ }+ }+ }+ Ok(refs)+}++#[derive(Deserialize)]+struct FontTableXml {+ #[serde(rename = "font", default)]+ fonts: Vec<FontEntryXml>,+}++#[derive(Deserialize)]+struct FontEntryXml {+ #[serde(rename = "@name")]+ name: String,+ #[serde(rename = "embedRegular", default)]+ embed_regular: Option<EmbedXml>,+ #[serde(rename = "embedBold", default)]+ embed_bold: Option<EmbedXml>,+ #[serde(rename = "embedItalic", default)]+ embed_italic: Option<EmbedXml>,+ #[serde(rename = "embedBoldItalic", default)]+ embed_bold_italic: Option<EmbedXml>,+}++#[derive(Deserialize)]+struct EmbedXml {+ /// Attribute `r:id` / `@id` depending on namespace handling. Try both.+ #[serde(rename = "@id", alias = "@r:id")]+ id: String,+ /// Attribute `fontKey` — `w:` prefix stripped by quick-xml if present.+ #[serde(rename = "@fontKey", alias = "@w:fontKey")]+ font_key: String,+}++/// §17.8.3.3: Parse a fontKey GUID string into the 16-byte XOR key.+///+/// The GUID format is `{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}`. Strip the+/// braces and dashes to get 16 bytes in GUID display order, then reverse the+/// whole 16-byte sequence to form the de-obfuscation key (§17.8.3.3) — the+/// reversal is applied to the entire byte array, not field-wise per RFC 4122.+fn parse_font_key(key: &str) -> Result<[u8; 16]> {+ let hex: String = key.chars().filter(|c| c.is_ascii_hexdigit()).collect();+ if hex.len() != 32 {+ return Err(ParseError::InvalidAttributeValue {+ attr: "w:fontKey".into(),+ value: key.into(),+ reason: "expected 32 hex digits in GUID".into(),+ });+ }++ let raw: Vec<u8> = (0..16)+ .map(|i| u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16))+ .collect::<std::result::Result<Vec<_>, _>>()+ .map_err(|e| ParseError::InvalidAttributeValue {+ attr: "w:fontKey".into(),+ value: key.into(),+ reason: format!("hex parse: {e}"),+ })?;++ // §17.8.3.3: the key bytes are the GUID hex digits reversed as a whole.+ let mut key = [0u8; 16];+ for (i, b) in raw.iter().rev().enumerate() {+ key[i] = *b;+ }+ Ok(key)+}++/// §17.8.3.3: De-obfuscate embedded font data.+///+/// XOR the first 32 bytes with the 16-byte key (applied twice).+fn deobfuscate_font(mut data: Vec<u8>, key: &[u8; 16]) -> Vec<u8> {+ for i in 0..32.min(data.len()) {+ data[i] ^= key[i % 16];+ }+ data+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_font_key_valid() {+ let key = parse_font_key("{3EEE3167-E5B8-4798-AE48-EA6B71E31D4D}").unwrap();+ // GUID hex: 3EEE3167E5B84798AE48EA6B71E31D4D+ // Reversed: 4D1DE3716BEA48AE9847B8E56731EE3E+ assert_eq!(key[0], 0x4D);+ assert_eq!(key[1], 0x1D);+ assert_eq!(key[2], 0xE3);+ assert_eq!(key[3], 0x71);+ assert_eq!(key[15], 0x3E);+ }++ #[test]+ fn parse_font_key_invalid_length() {+ let result = parse_font_key("{SHORT}");+ assert!(result.is_err());+ }++ #[test]+ fn deobfuscate_round_trip() {+ let key = [+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,+ 0x0F, 0x10,+ ];+ let original = vec![0xAA; 64];+ let obfuscated = deobfuscate_font(original.clone(), &key);+ // First 32 bytes should be XOR'd+ assert_ne!(&obfuscated[..32], &original[..32]);+ // Bytes after 32 should be unchanged+ assert_eq!(&obfuscated[32..], &original[32..]);+ // XOR again to recover+ let recovered = deobfuscate_font(obfuscated, &key);+ assert_eq!(recovered, original);+ }++ #[test]+ fn parse_font_table_extracts_embeds() {+ let xml = br#"<?xml version="1.0" encoding="UTF-8"?>+<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"+ xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">+ <w:font w:name="Ubuntu">+ <w:panose1 w:val="020B0504030602030204"/>+ <w:charset w:val="00"/>+ <w:family w:val="swiss"/>+ <w:pitch w:val="variable"/>+ <w:embedRegular r:id="rId1" w:fontKey="{3EEE3167-E5B8-4798-AE48-EA6B71E31D4D}"/>+ <w:embedBold r:id="rId2" w:fontKey="{773052E6-96AB-44E5-B2F7-4EE7F6CC51B1}"/>+ </w:font>+ <w:font w:name="Times New Roman">+ <w:charset w:val="00"/>+ </w:font>+</w:fonts>"#;+ let refs = parse_font_table(xml).unwrap();+ assert_eq!(refs.len(), 2);+ assert_eq!(refs[0].family, "Ubuntu");+ assert_eq!(refs[0].variant, EmbeddedFontVariant::Regular);+ assert_eq!(refs[0].rel_id, "rId1");+ assert_eq!(refs[1].family, "Ubuntu");+ assert_eq!(refs[1].variant, EmbeddedFontVariant::Bold);+ assert_eq!(refs[1].rel_id, "rId2");+ }++ #[test]+ fn parse_font_table_no_embeds() {+ let xml = br#"<?xml version="1.0" encoding="UTF-8"?>+<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:font w:name="Arial">+ <w:charset w:val="00"/>+ </w:font>+</w:fonts>"#;+ let refs = parse_font_table(xml).unwrap();+ assert!(refs.is_empty());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/mod.rs b/crates/liteparse-docx/src/docx/parse/mod.rsnew file mode 100644index 0000000..af01321--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/mod.rs@@ -0,0 +1,359 @@+//! DOCX parsing — all submodules that parse specific parts of the OOXML package.++pub mod body;+pub mod body_schema;+pub mod drawing;+pub mod fonts;+pub mod notes;+pub mod numbering;+pub mod primitives;+pub mod properties;+pub mod rel_rewrite;+pub mod serde_xml;+pub mod settings;+pub mod styles;+pub mod theme;+pub mod vml;++use std::collections::HashMap;+use std::sync::Arc;++use crate::docx::error::{ParseError, Result};+use crate::docx::model::*;+use crate::docx::relationships::{RelationshipType, Relationships};+use crate::docx::zip::{self, PackageContents};++/// Parse a DOCX file from raw bytes into a `Document`.+pub fn parse(data: &[u8]) -> Result<Document> {+ // Phase 1: Unzip+ let mut package = PackageContents::from_bytes(data)?;++ // Phase 1b: Find main document part via package-level rels+ let pkg_rels_data = package.require_part("_rels/.rels")?;+ let pkg_rels = Relationships::parse(pkg_rels_data)?;+ let doc_rel = pkg_rels+ .find_by_type(&RelationshipType::OfficeDocument)+ .ok_or_else(|| ParseError::MissingPart("officeDocument relationship".into()))?;+ let doc_path = zip::resolve_target("", &doc_rel.target);+ let doc_dir = zip::part_directory(&doc_path);++ // Phase 1c: Parse document-level relationships+ let doc_rels_path = zip::rels_path_for(&doc_path);+ let doc_rels = if let Some(data) = package.get_part(&doc_rels_path) {+ Relationships::parse(data)?+ } else {+ Relationships::default()+ };++ // Phase 2: Parse auxiliary parts++ // Theme+ let theme = if let Some(theme_rel) = doc_rels.find_by_type(&RelationshipType::Theme) {+ let theme_path = zip::resolve_target(doc_dir, &theme_rel.target);+ if let Some(data) = package.get_part(&theme_path) {+ Some(theme::parse_theme(data)?)+ } else {+ None+ }+ } else {+ None+ };++ // Styles+ let style_sheet = if let Some(styles_rel) = doc_rels.find_by_type(&RelationshipType::Styles) {+ let styles_path = zip::resolve_target(doc_dir, &styles_rel.target);+ let data = package.require_part(&styles_path)?;+ styles::parse_styles(data)?+ } else {+ StyleSheet::default()+ };++ // Numbering+ let mut numbering_defs =+ if let Some(num_rel) = doc_rels.find_by_type(&RelationshipType::Numbering) {+ let num_path = zip::resolve_target(doc_dir, &num_rel.target);+ if let Some(data) = package.get_part(&num_path) {+ numbering::parse_numbering(data)?+ } else {+ NumberingDefinitions::default()+ }+ } else {+ NumberingDefinitions::default()+ };++ // Settings+ let doc_settings =+ if let Some(settings_rel) = doc_rels.find_by_type(&RelationshipType::Settings) {+ let settings_path = zip::resolve_target(doc_dir, &settings_rel.target);+ if let Some(data) = package.get_part(&settings_path) {+ settings::parse_settings(data)?+ } else {+ DocumentSettings::default()+ }+ } else {+ DocumentSettings::default()+ };++ // Phase 2b: Extract media+ //+ // Body image bytes are *cloned* out of the package (not moved): a header+ // or footer can reference the same media part through its own rels, and+ // moving the bytes here would leave the later reader with nothing. The+ // package is dropped at the end of parse, so the transient duplication is+ // bounded.+ //+ // This is the pipeline's only copy of an image. `Document.media` holds+ // `Arc<[u8]>`, so resolve, layout and paint all pass the same allocation+ // around by handle.+ let mut media = HashMap::new();+ for rel in doc_rels.filter_by_type(&RelationshipType::Image) {+ let media_path = zip::resolve_target(doc_dir, &rel.target);+ if let Some(data) = package.get_part(&media_path).map(Arc::<[u8]>::from) {+ let fmt = ImageFormat::detect(&rel.target, &data);+ media.insert(rel.id.clone(), (data, fmt));+ }+ }++ // §17.9.21: extract picture bullet images from numbering.xml relationships.+ // These rIds live in numbering.xml.rels — an independent namespace from the+ // body's document.xml.rels — so a numbering `rId1` must not overwrite a body+ // `rId1` in the shared `media` map. Synthesize unique keys (as the+ // header/footer path does) and rewrite the numbering model's VML rel_ids to+ // match, so `list_label` looks the bullet up under the collision-free key.+ if let Some(num_rel) = doc_rels.find_by_type(&RelationshipType::Numbering) {+ let num_path = zip::resolve_target(doc_dir, &num_rel.target);+ let num_dir = zip::part_directory(&num_path);+ let num_rels_path = zip::rels_path_for(&num_path);+ if let Some(rels_data) = package.get_part(&num_rels_path) {+ let num_rels = Relationships::parse(rels_data)?;+ let mut num_remap: HashMap<RelId, RelId> = HashMap::new();+ for rel in num_rels.filter_by_type(&RelationshipType::Image) {+ let img_path = zip::resolve_target(num_dir, &rel.target);+ if let Some(data) = package.get_part(&img_path).map(Arc::<[u8]>::from) {+ let fmt = ImageFormat::detect(&rel.target, &data);+ let unique_id = RelId::new(format!("{}::{}", num_path, rel.id.as_str()));+ media.insert(unique_id.clone(), (data, fmt));+ num_remap.insert(rel.id.clone(), unique_id);+ }+ }+ for bullet in numbering_defs.pic_bullets.values_mut() {+ if let Some(ref mut pict) = bullet.pict {+ rel_rewrite::rewrite_part_rels_in_pict(pict, &num_remap);+ }+ }+ }+ }++ // Phase 2c: Parse embedded fonts from fontTable+ let embedded_fonts = if let Some(ft_rel) = doc_rels.find_by_type(&RelationshipType::FontTable) {+ let ft_path = zip::resolve_target(doc_dir, &ft_rel.target);+ let ft_dir = zip::part_directory(&ft_path);+ let ft_rels_path = zip::rels_path_for(&ft_path);+ // Take data out to avoid overlapping borrows.+ let ft_data = package.take_part(&ft_path);+ let ft_rels_data = package.take_part(&ft_rels_path);+ if let Some(ft_data) = ft_data {+ let ft_rels = if let Some(rd) = ft_rels_data {+ Relationships::parse(&rd)?+ } else {+ Relationships::default()+ };+ fonts::parse_embedded_fonts(&ft_data, &ft_rels, &mut package, ft_dir)?+ } else {+ Vec::new()+ }+ } else {+ Vec::new()+ };++ // Phase 3: Parse document body+ let doc_data = package.require_part(&doc_path)?;+ let (mut body_blocks, final_section) = body::parse_body(doc_data)?;++ // Phase 4: Parse headers and footers+ let mut headers = HashMap::new();+ let mut footers = HashMap::new();++ for rel in doc_rels.filter_by_type(&RelationshipType::Header) {+ let path = zip::resolve_target(doc_dir, &rel.target);+ if let Some(data) = package.get_part(&path) {+ let mut blocks = body::parse_blocks(data)?;+ let remap = load_part_rel_remap(&path, &mut package, &mut media)?;+ rel_rewrite::rewrite_part_rels_in_blocks(&mut blocks, &remap);+ headers.insert(rel.id.clone(), blocks);+ }+ }++ for rel in doc_rels.filter_by_type(&RelationshipType::Footer) {+ let path = zip::resolve_target(doc_dir, &rel.target);+ if let Some(data) = package.get_part(&path) {+ let mut blocks = body::parse_blocks(data)?;+ let remap = load_part_rel_remap(&path, &mut package, &mut media)?;+ rel_rewrite::rewrite_part_rels_in_blocks(&mut blocks, &remap);+ footers.insert(rel.id.clone(), blocks);+ }+ }++ // Phase 4b: Parse footnotes and endnotes. All footnote bodies+ // share the same `footnotes.xml.rels` namespace (one part holds+ // all of them); same for endnotes.+ let mut footnotes = HashMap::new();+ if let Some(fn_rel) = doc_rels.find_by_type(&RelationshipType::Footnotes) {+ let path = zip::resolve_target(doc_dir, &fn_rel.target);+ if let Some(data) = package.get_part(&path) {+ footnotes = notes::parse_notes(data)?;+ let remap = load_part_rel_remap(&path, &mut package, &mut media)?;+ for blocks in footnotes.values_mut() {+ rel_rewrite::rewrite_part_rels_in_blocks(blocks, &remap);+ }+ }+ }++ let mut endnotes = HashMap::new();+ if let Some(en_rel) = doc_rels.find_by_type(&RelationshipType::Endnotes) {+ let path = zip::resolve_target(doc_dir, &en_rel.target);+ if let Some(data) = package.get_part(&path) {+ endnotes = notes::parse_notes(data)?;+ let remap = load_part_rel_remap(&path, &mut package, &mut media)?;+ for blocks in endnotes.values_mut() {+ rel_rewrite::rewrite_part_rels_in_blocks(blocks, &remap);+ }+ }+ }++ // Phase 5: Resolve body hyperlink RelIds to actual URLs.+ // Headers/footers/footnotes/endnotes already had both their image+ // and hyperlink rIds rewritten through `load_part_rel_remap` —+ // that pass is the per-part equivalent of this body-level resolve.+ resolve_hyperlinks(&mut body_blocks, &doc_rels);++ // Phase 6: Assemble+ Ok(Document {+ settings: doc_settings,+ theme,+ styles: style_sheet,+ numbering: numbering_defs,+ body: body_blocks,+ final_section,+ headers,+ footers,+ footnotes,+ endnotes,+ media,+ embedded_fonts,+ })+}++/// Process the rels of a single subordinate XML part — a header,+/// footer, footnote, or endnote. §17.16 gives every part its own+/// `_rels/<part>.xml.rels` file with its own `rId` namespace, so an+/// `rId1` in a header is unrelated to an `rId1` in the document, in+/// a footer, or in another header.+///+/// To make the parsed `Document` collision-free we synthesize **two**+/// kinds of remap entries here and return them as one combined map+/// the caller applies via `rel_rewrite::rewrite_part_rels_in_blocks`:+///+/// * **Image rels** — each loaded image is inserted into the+/// document-wide `media` map under a synthesized unique key+/// (`<part_path>::<orig_rId>`); the part's blocks are rewritten to+/// reference that key.+/// * **Hyperlink rels** — `External(rId)` targets are rewritten to+/// `External(URL)` using *this part's* relationships, not the+/// document's. Pre-fix the hyperlink resolution pass used+/// `doc_rels` for every part, which silently re-targeted any+/// header/footer/note hyperlink whose rId happened to mean+/// something different in the document's own rels.+///+/// Other relationship types (font tables, OLE objects, custom XML, …)+/// are not modeled in the block tree yet and are skipped.+fn load_part_rel_remap(+ part_path: &str,+ package: &mut PackageContents,+ media: &mut HashMap<RelId, (Arc<[u8]>, ImageFormat)>,+) -> Result<HashMap<RelId, RelId>> {+ let mut remap: HashMap<RelId, RelId> = HashMap::new();+ let rels_path = zip::rels_path_for(part_path);+ let Some(rels_data) = package.get_part(&rels_path) else {+ return Ok(remap);+ };+ let rels = Relationships::parse(rels_data)?;++ // Image rels — synthesize unique ids and load bytes into `media`.+ for img_rel in rels.filter_by_type(&RelationshipType::Image) {+ let img_path = zip::resolve_target(zip::part_directory(part_path), &img_rel.target);+ // Clone, don't take: multiple parts (e.g. a header and a+ // footer) commonly reference the *same* image part; if we+ // moved the bytes out at the first reader the second reader+ // would silently drop the image.+ if let Some(img_data) = package.get_part(&img_path).map(Arc::<[u8]>::from) {+ let fmt = ImageFormat::detect(&img_rel.target, &img_data);+ let unique_id = RelId::new(format!("{}::{}", part_path, img_rel.id.as_str()));+ media.insert(unique_id.clone(), (img_data, fmt));+ remap.insert(img_rel.id.clone(), unique_id);+ }+ }++ // Hyperlink rels — same mechanism the document-level hyperlink+ // resolver uses: rewrite `External(rId)` to `External(URL)` by+ // smuggling the URL through a `RelId` newtype. The model layer+ // already treats a URL-shaped RelId as an external link target.+ for link_rel in rels.filter_by_type(&RelationshipType::Hyperlink) {+ remap.insert(link_rel.id.clone(), RelId::new(link_rel.target.clone()));+ }++ Ok(remap)+}++/// Walk blocks and resolve `HyperlinkTarget::External(RelId)` to actual URLs.+fn resolve_hyperlinks(blocks: &mut [Block], rels: &crate::docx::relationships::Relationships) {+ for block in blocks {+ match block {+ Block::Paragraph(p) => resolve_hyperlinks_in_inlines(&mut p.content, rels),+ Block::Table(t) => {+ for row in &mut t.rows {+ for cell in &mut row.cells {+ resolve_hyperlinks(&mut cell.content, rels);+ }+ }+ }+ _ => {}+ }+ }+}++fn resolve_hyperlinks_in_inlines(+ inlines: &mut [crate::model::Inline],+ rels: &crate::docx::relationships::Relationships,+) {+ use crate::model::{HyperlinkTarget, Inline};++ for inline in inlines {+ match inline {+ Inline::Hyperlink(link) => {+ // Resolve an unresolved relationship id to its actual URL.+ if let HyperlinkTarget::ExternalRel(ref rel_id) = link.target {+ if let Some(rel) = rels.find_by_id(rel_id.as_str()) {+ link.target = HyperlinkTarget::ExternalUrl(rel.target.clone());+ }+ }+ // Recurse into hyperlink content.+ resolve_hyperlinks_in_inlines(&mut link.content, rels);+ }+ Inline::Field(field) => {+ resolve_hyperlinks_in_inlines(&mut field.content, rels);+ }+ Inline::AlternateContent(ac) => {+ // §M.2.2: choices are the preferred (usually rendered) branch,+ // so resolve their hyperlinks too — not just the fallback.+ for choice in &mut ac.choices {+ resolve_hyperlinks_in_inlines(&mut choice.content, rels);+ }+ if let Some(ref mut fallback) = ac.fallback {+ resolve_hyperlinks_in_inlines(fallback, rels);+ }+ }+ _ => {}+ }+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/notes.rs b/crates/liteparse-docx/src/docx/parse/notes.rsnew file mode 100644index 0000000..4252ef0--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/notes.rs@@ -0,0 +1,99 @@+//! Parser for footnotes.xml and endnotes.xml.++use std::collections::HashMap;++use serde::Deserialize;++use crate::docx::error::Result;+use crate::docx::model::{Block, NoteId};+use crate::docx::parse::body;+use crate::docx::parse::serde_xml::from_xml;++/// Parse footnotes.xml or endnotes.xml into a map of note ID → blocks. The+/// schema accepts either `<w:footnote>` or `<w:endnote>` children under either+/// root, so one function serves both parts.+pub fn parse_notes(data: &[u8]) -> Result<HashMap<NoteId, Vec<Block>>> {+ if data.is_empty() {+ return Ok(HashMap::new());+ }+ let file: NotesFileXml = from_xml(data)?;+ let mut ctx = body::ConvertCtx::new();+ let mut out = HashMap::new();+ for note in file.entries {+ let Some(id) = note.id else { continue };+ let (blocks, _) = body::convert_container(note.content, &mut ctx);+ out.insert(NoteId::new(id), blocks);+ }+ Ok(out)+}++/// Matches both `<w:footnotes>` and `<w:endnotes>`. Their children are+/// `<w:footnote>` or `<w:endnote>` respectively — we accept either tag.+#[derive(Deserialize)]+struct NotesFileXml {+ #[serde(alias = "footnote", alias = "endnote", default)]+ entries: Vec<NoteXml>,+}++#[derive(Deserialize)]+struct NoteXml {+ #[serde(+ rename = "@id",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ id: Option<i64>,+ #[serde(rename = "$value", default)]+ content: Vec<crate::docx::parse::body_schema::BlockChildXml>,+}++#[cfg(test)]+mod tests {+ use super::*;++ const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;++ #[test]+ fn empty_data_yields_empty_map() {+ assert!(parse_notes(b"").unwrap().is_empty());+ }++ #[test]+ fn parses_footnotes_keyed_by_id() {+ let xml = format!(+ r#"<w:footnotes {NS}>+ <w:footnote w:id="1"><w:p><w:r><w:t>first</w:t></w:r></w:p></w:footnote>+ <w:footnote w:id="2"><w:p><w:r><w:t>second</w:t></w:r></w:p></w:footnote>+ </w:footnotes>"#+ );+ let notes = parse_notes(xml.as_bytes()).expect("parse footnotes");+ assert_eq!(notes.len(), 2);+ assert!(notes.contains_key(&NoteId::new(1)));+ assert!(notes.contains_key(&NoteId::new(2)));+ }++ #[test]+ fn note_without_id_is_dropped() {+ let xml = format!(+ r#"<w:footnotes {NS}>+ <w:footnote><w:p/></w:footnote>+ <w:footnote w:id="5"><w:p/></w:footnote>+ </w:footnotes>"#+ );+ let notes = parse_notes(xml.as_bytes()).expect("parse");+ assert_eq!(notes.len(), 1, "the id-less note is dropped");+ assert!(notes.contains_key(&NoteId::new(5)));+ }++ #[test]+ fn endnote_alias_is_accepted() {+ let xml = format!(+ r#"<w:endnotes {NS}>+ <w:endnote w:id="3"><w:p><w:r><w:t>e</w:t></w:r></w:p></w:endnote>+ </w:endnotes>"#+ );+ let notes = parse_notes(xml.as_bytes()).expect("parse endnotes");+ assert_eq!(notes.len(), 1);+ assert!(notes.contains_key(&NoteId::new(3)));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/numbering.rs b/crates/liteparse-docx/src/docx/parse/numbering.rsnew file mode 100644index 0000000..94d2525--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/numbering.rs@@ -0,0 +1,429 @@+//! Parser for `word/numbering.xml` — single-pass serde over the whole file.+//! Picture bullets' `<w:pict>` contents are deserialized via the VML schema.++use serde::Deserialize;++use crate::docx::error::Result;+use crate::docx::model::{+ AbstractNumId, AbstractNumbering, Alignment, Indentation, LevelOverride, LevelSuffix, NumId,+ NumPicBullet, NumPicBulletId, NumberFormat, NumberingDefinitions, NumberingInstance,+ NumberingLevelDefinition, RunProperties,+};+use crate::docx::parse::primitives::OnOff;+use crate::docx::parse::primitives::st_enums::{StJc, StNumberFormat};+use crate::docx::parse::properties::schema::paragraph::PPrXml;+use crate::docx::parse::properties::schema::run::RPrXml;+use crate::docx::parse::serde_xml::from_xml;++pub fn parse_numbering(data: &[u8]) -> Result<NumberingDefinitions> {+ if data.is_empty() {+ return Ok(NumberingDefinitions::default());+ }+ let schema: NumberingXml = from_xml(data)?;+ Ok(schema.into())+}++// ── serde schema ──────────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+struct NumberingXml {+ #[serde(rename = "$value", default)]+ children: Vec<NumberingChildXml>,+}++#[derive(Deserialize)]+enum NumberingChildXml {+ #[serde(rename = "abstractNum")]+ AbstractNum(AbstractNumXml),+ #[serde(rename = "num")]+ Num(NumXml),+ #[serde(rename = "numPicBullet")]+ NumPicBullet(Box<NumPicBulletXml>),+ #[serde(other)]+ Unknown,+}++#[derive(Deserialize)]+struct AbstractNumXml {+ /// The definition is keyed by this id; without it there is nothing to key.+ #[serde(+ rename = "@abstractNumId",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ abstract_num_id: Option<i64>,+ #[serde(rename = "lvl", default)]+ levels: Vec<LvlXml>,+}++#[derive(Deserialize)]+struct LvlXml {+ /// An unusable level index falls back to the top level.+ #[serde(+ rename = "@ilvl",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ ilvl: u8,+ #[serde(+ rename = "numFmt",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ num_fmt: Option<StNumberFormat>,+ #[serde(rename = "lvlText", default)]+ lvl_text: Option<ValString>,+ #[serde(+ rename = "start",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ start: Option<u32>,+ #[serde(+ rename = "lvlJc",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ lvl_jc: Option<StJc>,+ #[serde(+ rename = "suff",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ suff: Option<StLevelSuffix>,+ #[serde(rename = "isLgl", default)]+ is_lgl: Option<OnOff>,+ #[serde(rename = "pPr", default)]+ p_pr: Option<PPrXml>,+ #[serde(rename = "rPr", default)]+ r_pr: Option<RPrXml>,+ #[serde(+ rename = "lvlPicBulletId",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ lvl_pic_bullet_id: Option<i64>,+}++/// §17.18.53 ST_LevelSuffix.+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+enum StLevelSuffix {+ Tab,+ Space,+ Nothing,+}++impl From<StLevelSuffix> for LevelSuffix {+ fn from(s: StLevelSuffix) -> Self {+ match s {+ StLevelSuffix::Tab => Self::Tab,+ StLevelSuffix::Space => Self::Space,+ StLevelSuffix::Nothing => Self::Nothing,+ }+ }+}++#[derive(Deserialize)]+struct NumXml {+ /// The instance is keyed by this id; without it there is nothing to key.+ #[serde(+ rename = "@numId",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ num_id: Option<i64>,+ #[serde(+ rename = "abstractNumId",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ abstract_num_id: Option<i64>,+ #[serde(rename = "lvlOverride", default)]+ overrides: Vec<LvlOverrideXml>,+}++#[derive(Deserialize)]+struct LvlOverrideXml {+ #[serde(+ rename = "@ilvl",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ ilvl: u8,+ #[serde(+ rename = "startOverride",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ start_override: Option<u32>,+ #[serde(rename = "lvl", default)]+ lvl: Option<LvlXml>,+}++#[derive(Deserialize)]+struct NumPicBulletXml {+ /// The picture bullet is keyed by this id.+ #[serde(+ rename = "@numPicBulletId",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ num_pic_bullet_id: Option<i64>,+ #[serde(rename = "pict", default)]+ pict: Option<crate::docx::parse::vml::schema::PictXml>,+}++#[derive(Deserialize)]+struct ValString {+ #[serde(rename = "@val")]+ val: String,+}++// ── schema → model ────────────────────────────────────────────────────────++impl From<NumberingXml> for NumberingDefinitions {+ fn from(x: NumberingXml) -> Self {+ let mut defs = NumberingDefinitions::default();+ // Picture bullets may contain a VML `<w:pict>` (e.g., an imagedata+ // reference). Numbering has no body content, so no embeds crossing+ // into body convert — pass an empty ctx.+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ for child in x.children {+ match child {+ // Definitions with no usable key are dropped: inserting them+ // under a fabricated id would shadow a real definition.+ NumberingChildXml::AbstractNum(a) => {+ let Some(raw_id) = a.abstract_num_id else {+ continue;+ };+ let id = AbstractNumId::new(raw_id);+ defs.abstract_nums.insert(+ id,+ AbstractNumbering {+ levels: a.levels.into_iter().map(Into::into).collect(),+ },+ );+ }+ NumberingChildXml::Num(n) => {+ let Some(raw_id) = n.num_id else { continue };+ defs.numbering_instances+ .insert(NumId::new(raw_id), convert_num(n));+ }+ NumberingChildXml::NumPicBullet(bullet) => {+ let Some(raw_id) = bullet.num_pic_bullet_id else {+ continue;+ };+ let id = NumPicBulletId::new(raw_id);+ let pict = bullet.pict.map(|p| p.into_model(&mut ctx));+ defs.pic_bullets.insert(id, NumPicBullet { id, pict });+ }+ NumberingChildXml::Unknown => {}+ }+ }+ defs+ }+}++impl From<LvlXml> for NumberingLevelDefinition {+ fn from(x: LvlXml) -> Self {+ let (indentation, run_properties) = extract_level_properties(x.p_pr, x.r_pr);+ Self {+ level: x.ilvl,+ format: x.num_fmt.map(|v| NumberFormat::from(v)),+ level_text: x.lvl_text.map(|v| v.val).unwrap_or_default(),+ start: x.start,+ justification: x.lvl_jc.map(Alignment::from),+ indentation,+ run_properties,+ lvl_pic_bullet_id: x.lvl_pic_bullet_id.map(|v| NumPicBulletId::new(v)),+ suffix: x.suff.map(LevelSuffix::from).unwrap_or_default(),+ is_legal: x.is_lgl.map(|OnOff(b)| b).unwrap_or(false),+ }+ }+}++fn extract_level_properties(+ p_pr: Option<PPrXml>,+ r_pr: Option<RPrXml>,+) -> (Option<Indentation>, Option<RunProperties>) {+ let indentation = p_pr.and_then(|p| p.split().properties.indentation);+ let run_properties = r_pr.map(|r| r.split().0);+ (indentation, run_properties)+}++fn convert_num(n: NumXml) -> NumberingInstance {+ let abstract_num_id = n+ .abstract_num_id+ .map(|v| AbstractNumId::new(v))+ .unwrap_or_else(|| {+ log::warn!(+ "numbering instance numId={:?} has no abstractNumId; defaulting to 0",+ n.num_id+ );+ AbstractNumId::new(0)+ });+ let level_overrides = n+ .overrides+ .into_iter()+ .map(|o| {+ let definition = o.lvl.map(|mut lvl| {+ lvl.ilvl = o.ilvl; // the override's @ilvl wins over the inner lvl's+ NumberingLevelDefinition::from(lvl)+ });+ LevelOverride {+ level: o.ilvl,+ start_override: o.start_override,+ definition,+ }+ })+ .collect();+ NumberingInstance {+ abstract_num_id,+ level_overrides,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ /// Upstream failed the document on a non-integer id. We drop the+ /// definition instead — but the guard it existed for still holds, and is+ /// the important part: `"1.0"` must never be silently accepted *as* id 1,+ /// which would shadow the real abstract numbering 1 and renumber lists.+ fn non_integer_numbering_ids_are_dropped_never_coerced() {+ let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="1.0"/></w:numbering>"#;+ let defs = parse_numbering(xml).expect("a bad id must not fail the document");+ assert!(+ defs.abstract_nums.is_empty(),+ "\"1.0\" must not be keyed as any id"+ );+ }++ /// A malformed definition must not take its well-formed siblings with it.+ #[test]+ fn a_bad_numbering_id_does_not_discard_valid_definitions() {+ let xml = br#"+ <w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:abstractNum w:abstractNumId="bogusValue"><w:lvl w:ilvl="0"><w:lvlText w:val="X%1"/></w:lvl></w:abstractNum>+ <w:abstractNum w:abstractNumId="2"><w:lvl w:ilvl="0"><w:lvlText w:val="B%1"/></w:lvl></w:abstractNum>+ <w:num w:numId="12"><w:abstractNumId w:val="2"/></w:num>+ </w:numbering>"#;+ let defs = parse_numbering(xml).unwrap();+ assert_eq!(defs.abstract_nums.len(), 1);+ assert!(defs.abstract_nums.contains_key(&AbstractNumId::new(2)));+ assert_eq!(defs.numbering_instances.len(), 1);+ }++ #[test]+ fn repeated_abstract_and_concrete_numbering_definitions_are_collected() {+ let xml = br#"+ <w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:lvlText w:val="A%1"/></w:lvl></w:abstractNum>+ <w:num w:numId="11"><w:abstractNumId w:val="1"/></w:num>+ <w:abstractNum w:abstractNumId="2"><w:lvl w:ilvl="0"><w:lvlText w:val="B%1"/></w:lvl></w:abstractNum>+ <w:num w:numId="12"><w:abstractNumId w:val="2"/></w:num>+ </w:numbering>"#;+ let defs = parse_numbering(xml).unwrap();+ assert_eq!(defs.abstract_nums.len(), 2);+ assert_eq!(defs.numbering_instances.len(), 2);+ assert_eq!(+ defs.numbering_instances[&NumId::new(11)].abstract_num_id,+ AbstractNumId::new(1)+ );+ assert_eq!(+ defs.numbering_instances[&NumId::new(12)].abstract_num_id,+ AbstractNumId::new(2)+ );+ }++ #[test]+ fn num_without_abstract_ref_defaults_to_zero() {+ // `<w:num>` with no `<w:abstractNumId>` binds to abstract 0 (with a warn).+ let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:num w:numId="7"/></w:numbering>"#;+ let defs = parse_numbering(xml).unwrap();+ assert_eq!(+ defs.numbering_instances[&NumId::new(7)].abstract_num_id,+ AbstractNumId::new(0)+ );+ }++ #[test]+ fn lvl_override_uses_override_ilvl_not_inner_lvl() {+ // The override's own @ilvl wins over the nested `<w:lvl w:ilvl>`.+ let xml = br#"+ <w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:num w:numId="9">+ <w:abstractNumId w:val="1"/>+ <w:lvlOverride w:ilvl="2">+ <w:lvl w:ilvl="0"><w:lvlText w:val="X%1"/></w:lvl>+ </w:lvlOverride>+ </w:num>+ </w:numbering>"#;+ let defs = parse_numbering(xml).unwrap();+ let inst = &defs.numbering_instances[&NumId::new(9)];+ assert_eq!(inst.level_overrides.len(), 1);+ assert_eq!(inst.level_overrides[0].level, 2);+ assert!(inst.level_overrides[0].definition.is_some());+ }++ #[test]+ fn lvl_suff_and_islgl_parse() {+ let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:abstractNum w:abstractNumId="1">+ <w:lvl w:ilvl="0">+ <w:numFmt w:val="decimal"/>+ <w:lvlText w:val="%1."/>+ <w:suff w:val="space"/>+ <w:isLgl/>+ </w:lvl>+ </w:abstractNum>+ </w:numbering>"#;+ let lvl = &parse_numbering(xml).unwrap().abstract_nums[&AbstractNumId::new(1)].levels[0];+ assert_eq!(lvl.suffix, LevelSuffix::Space);+ assert!(lvl.is_legal);+ }++ #[test]+ fn lvl_suff_defaults_to_tab_and_islgl_false() {+ let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>+ </w:numbering>"#;+ let lvl = &parse_numbering(xml).unwrap().abstract_nums[&AbstractNumId::new(1)].levels[0];+ assert_eq!(lvl.suffix, LevelSuffix::Tab);+ assert!(!lvl.is_legal);+ }++ #[test]+ fn start_override_without_lvl_is_captured() {+ // A `<w:lvlOverride>` may carry only `<w:startOverride>` (no `<w:lvl>`);+ // the old filter_map dropped such overrides entirely.+ let xml = br#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:num w:numId="3">+ <w:abstractNumId w:val="1"/>+ <w:lvlOverride w:ilvl="0"><w:startOverride w:val="5"/></w:lvlOverride>+ </w:num>+ </w:numbering>"#;+ let defs = parse_numbering(xml).unwrap();+ let inst = &defs.numbering_instances[&NumId::new(3)];+ assert_eq!(inst.level_overrides.len(), 1);+ assert_eq!(inst.level_overrides[0].level, 0);+ assert_eq!(inst.level_overrides[0].start_override, Some(5));+ assert!(inst.level_overrides[0].definition.is_none());+ }++ #[test]+ fn unknown_numbering_root_children_do_not_discard_known_definitions() {+ let xml = br#"+ <w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:abstractNum w:abstractNumId="3"/>+ <w:futureExtension><w:nested w:val="ignored"/></w:futureExtension>+ <w:num w:numId="13"><w:abstractNumId w:val="3"/></w:num>+ </w:numbering>"#;+ let defs = parse_numbering(xml).unwrap();+ assert!(defs.abstract_nums.contains_key(&AbstractNumId::new(3)));+ assert!(defs.numbering_instances.contains_key(&NumId::new(13)));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/primitives/colors.rs b/crates/liteparse-docx/src/docx/parse/primitives/colors.rsnew file mode 100644index 0000000..669f86c--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/colors.rs@@ -0,0 +1,158 @@+//! OOXML color-attribute primitives.+//!+//! - [`HexColor`] — ST_HexColor (§17.3.4.1): either the literal `"auto"`+//! sentinel or a 6-digit RGB hex. Used by `<w:color>` and DrawingML color+//! choices where "auto" is spec-legal.+//! - [`RgbHexU32`] — ST_HexColorRGB (§20.1.10.41): strictly a 6-digit RGB hex.+//! Used where the spec disallows "auto".+//!+//! Both fail deserialization on malformed input (strict per plan §Decisions).++use serde::{Deserialize, Deserializer};++use crate::docx::model::Color;++/// Parse exactly six ASCII hex digits into a packed `0xRRGGBB`. ST_HexColor+/// (§17.3.4.1) and ST_HexColorRGB (§20.1.10.41) are both defined as a 6-digit+/// RGB hex; anything else (3-digit shorthand, 8-digit ARGB, a leading sign)+/// is rejected rather than silently mis-decoded by `from_str_radix`.+fn parse_rgb_hex6(s: &str) -> Result<u32, &'static str> {+ if s.len() == 6 && s.bytes().all(|b| b.is_ascii_hexdigit()) {+ Ok(u32::from_str_radix(s, 16).expect("six hex digits always fit in u32"))+ } else {+ Err("expected a 6-digit RGB hex value")+ }+}++/// OOXML `ST_HexColor` (§17.3.4.1): `"auto"` or 6-digit RGB hex.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum HexColor {+ Auto,+ Rgb(u32),+}++impl HexColor {+ /// RGB value if concrete; `None` if `Auto`.+ pub fn rgb(self) -> Option<u32> {+ match self {+ HexColor::Auto => None,+ HexColor::Rgb(v) => Some(v),+ }+ }+}++impl From<HexColor> for Color {+ fn from(h: HexColor) -> Self {+ match h {+ HexColor::Auto => Self::Auto,+ HexColor::Rgb(v) => Self::Rgb(v),+ }+ }+}++impl<'de> Deserialize<'de> for HexColor {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ if s.eq_ignore_ascii_case("auto") {+ return Ok(HexColor::Auto);+ }+ parse_rgb_hex6(&s)+ .map(HexColor::Rgb)+ .map_err(serde::de::Error::custom)+ }+}++/// OOXML `ST_HexColorRGB` (§20.1.10.41): strictly a 6-digit RGB hex.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct RgbHexU32(pub u32);++impl<'de> Deserialize<'de> for RgbHexU32 {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ parse_rgb_hex6(&s)+ .map(RgbHexU32)+ .map_err(serde::de::Error::custom)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[derive(Deserialize)]+ struct HexVal {+ #[serde(rename = "@val")]+ val: HexColor,+ }++ #[derive(Deserialize)]+ struct RgbVal {+ #[serde(rename = "@val")]+ val: RgbHexU32,+ }++ #[test]+ fn hex_color_rgb() {+ let v: HexVal = quick_xml::de::from_str(r#"<x val="4F81BD"/>"#).unwrap();+ assert_eq!(v.val, HexColor::Rgb(0x4F81BD));+ assert_eq!(v.val.rgb(), Some(0x4F81BD));+ }++ #[test]+ fn hex_color_auto_is_case_insensitive() {+ for raw in ["auto", "AUTO", "Auto"] {+ let xml = format!(r#"<x val="{raw}"/>"#);+ let v: HexVal = quick_xml::de::from_str(&xml).unwrap();+ assert_eq!(v.val, HexColor::Auto);+ assert!(v.val.rgb().is_none());+ }+ }++ #[test]+ fn hex_color_rejects_garbage() {+ let r: Result<HexVal, _> = quick_xml::de::from_str(r#"<x val="notahex"/>"#);+ assert!(r.is_err());+ }++ #[test]+ fn rgb_hex_accepts_six_digit() {+ let v: RgbVal = quick_xml::de::from_str(r#"<x val="DEADBE"/>"#).unwrap();+ assert_eq!(v.val.0, 0xDEADBE);+ }++ #[test]+ fn rgb_hex_rejects_auto() {+ let r: Result<RgbVal, _> = quick_xml::de::from_str(r#"<x val="auto"/>"#);+ assert!(+ r.is_err(),+ "RgbHexU32 must reject 'auto' per ST_HexColorRGB"+ );+ }++ #[test]+ fn rgb_hex_rejects_garbage() {+ let r: Result<RgbVal, _> = quick_xml::de::from_str(r#"<x val="xyz123"/>"#);+ assert!(r.is_err());+ }++ #[test]+ fn hex_enforces_exactly_six_digits() {+ // ST_HexColor / ST_HexColorRGB are strictly 6-digit RGB. Shorthand,+ // 8-digit ARGB, and a signed value must be rejected, not silently+ // mis-decoded by from_str_radix (e.g. "FFF" -> 0x000FFF).+ for bad in ["FFF", "FFFFF", "FFFFFFF", "FFFFFFFF", "+F0F0F0", " F0F0F0"] {+ let xml = format!(r#"<x val="{bad}"/>"#);+ assert!(+ quick_xml::de::from_str::<HexVal>(&xml).is_err(),+ "HexColor must reject {bad:?}"+ );+ assert!(+ quick_xml::de::from_str::<RgbVal>(&xml).is_err(),+ "RgbHexU32 must reject {bad:?}"+ );+ }+ // The exact 6-digit form still parses.+ let v: RgbVal = quick_xml::de::from_str(r#"<x val="0A0B0C"/>"#).unwrap();+ assert_eq!(v.val.0, 0x0A0B0C);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/primitives/integer_measure.rs b/crates/liteparse-docx/src/docx/parse/primitives/integer_measure.rsnew file mode 100644index 0000000..5fdfb20--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/integer_measure.rs@@ -0,0 +1,112 @@+use serde::{Deserialize, Deserializer};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct IntegerMeasure {+ value: i64,+ negative: bool,+}++impl IntegerMeasure {+ pub(crate) fn value(self) -> i64 {+ self.value+ }++ pub(crate) fn is_negative(&self) -> bool {+ self.negative+ }+}++impl<'de> Deserialize<'de> for IntegerMeasure {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let raw = String::deserialize(deserializer)?;+ parse_integer_measure(&raw).map_err(serde::de::Error::custom)+ }+}++fn parse_integer_measure(raw: &str) -> Result<IntegerMeasure, &'static str> {+ if let Ok(value) = raw.parse::<i64>() {+ return Ok(IntegerMeasure {+ value,+ negative: raw.starts_with('-'),+ });+ }++ let (negative, unsigned) = match raw.strip_prefix('-') {+ Some(rest) => (true, rest),+ None => (false, raw.strip_prefix('+').unwrap_or(raw)),+ };+ let (whole, fraction) = unsigned+ .split_once('.')+ .ok_or("expected an integer or decimal measurement")?;+ if whole.is_empty()+ || fraction.is_empty()+ || !whole.bytes().all(|b| b.is_ascii_digit())+ || !fraction.bytes().all(|b| b.is_ascii_digit())+ {+ return Err("invalid decimal measurement");+ }++ let magnitude = whole+ .parse::<i128>()+ .map_err(|_| "measurement is outside the supported range")?;+ let rounded_magnitude = magnitude+ .checked_add(i128::from(fraction.as_bytes()[0] >= b'5'))+ .ok_or("measurement is outside the supported range")?;+ let signed = if negative {+ -rounded_magnitude+ } else {+ rounded_magnitude+ };+ let value = i64::try_from(signed).map_err(|_| "measurement is outside the supported range")?;+ Ok(IntegerMeasure { value, negative })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[derive(Deserialize)]+ struct Value {+ #[serde(rename = "@val")]+ val: IntegerMeasure,+ }++ fn parse(raw: &str) -> Result<i64, quick_xml::DeError> {+ quick_xml::de::from_str::<Value>(&format!(r#"<x val="{raw}"/>"#))+ .map(|value| value.val.value())+ }++ #[test]+ fn accepts_integer_and_decimal_measurements() {+ assert_eq!(parse("0").unwrap(), 0);+ assert_eq!(parse("-120").unwrap(), -120);+ assert_eq!(parse("100.0").unwrap(), 100);+ assert_eq!(parse("252.00000000000003").unwrap(), 252);+ assert_eq!(parse("283.46456692913375").unwrap(), 283);+ }++ #[test]+ fn rounds_half_away_from_zero() {+ assert_eq!(parse("1.5").unwrap(), 2);+ assert_eq!(parse("-1.5").unwrap(), -2);+ assert_eq!(parse("1.499").unwrap(), 1);+ assert_eq!(parse("-1.499").unwrap(), -1);+ }++ #[test]+ fn rejects_non_decimal_and_out_of_range_values() {+ for raw in [+ "",+ ".5",+ "1.",+ "1e2",+ "NaN",+ "inf",+ "abc",+ "9223372036854775808",+ "-9223372036854775809",+ ] {+ assert!(parse(raw).is_err(), "{raw:?} must be rejected");+ }+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/primitives/lenient.rs b/crates/liteparse-docx/src/docx/parse/primitives/lenient.rsnew file mode 100644index 0000000..6bd6997--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/lenient.rs@@ -0,0 +1,291 @@+//! Tolerant deserializers for OOXML simple-type (`ST_*`) attribute values.+//!+//! Vendoring divergence from dxpdf, and a standing requirement of this copy:+//! **one bad attribute value must not fail the whole document.**+//!+//! Upstream models each `ST_*` simple type as a plain serde enum, so an+//! unrecognized value (a newer spec revision, a producer quirk, or plain+//! corruption) aborts the entire parse. That is the same fail-closed pattern+//! that cost us 4% of the `docx_files` corpus via unknown *elements*; unknown+//! *values* are the other half of it.+//!+//! ECMA-376 §17.17 treats an invalid attribute value as if the attribute were+//! absent, so the correct degradation is "unspecified", not "some other value".+//! That matters: absent means *inherit from the style chain*, whereas+//! substituting a default would silently override an inherited value.+//!+//! These helpers only apply where absence is representable. Required+//! attributes with no meaningful "unspecified" state are handled at their own+//! definition instead — see `ATTRIBUTION.md`.++use serde::Deserialize;+use serde::de::value::Error as ValueError;+use serde::de::value::StrDeserializer;+use serde::de::{Deserializer, IntoDeserializer, Visitor};++/// Deserializer over one raw attribute string that *coerces* to the target+/// type instead of requiring the target to be string-shaped.+///+/// `serde`'s own `StrDeserializer` forwards every `deserialize_*` hook to+/// `visit_str`, so `u32::deserialize` on it fails. That matters a great deal+/// here, because these helpers deliberately swallow conversion failures: using+/// it would have turned every numeric attribute (`gridSpan`, `numId`, `ilvl`,+/// `outlineLvl`, …) silently into `None`, corrupting documents rather than+/// merely being strict about them. This wrapper parses the integer/float/bool+/// forms and leaves everything else to `visit_str`, which is what the+/// string-shaped types (the `ST_*` enums) want.+struct AttrValueDeserializer<'a>(&'a str);++macro_rules! coerce {+ ($method:ident, $visit:ident, $ty:ty) => {+ fn $method<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Error> {+ match self.0.trim().parse::<$ty>() {+ Ok(n) => v.$visit(n),+ Err(e) => Err(serde::de::Error::custom(e)),+ }+ }+ };+}++impl<'de> Deserializer<'de> for AttrValueDeserializer<'_> {+ type Error = ValueError;++ fn deserialize_any<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Error> {+ v.visit_str(self.0)+ }++ coerce!(deserialize_i8, visit_i8, i8);+ coerce!(deserialize_i16, visit_i16, i16);+ coerce!(deserialize_i32, visit_i32, i32);+ coerce!(deserialize_i64, visit_i64, i64);+ coerce!(deserialize_u8, visit_u8, u8);+ coerce!(deserialize_u16, visit_u16, u16);+ coerce!(deserialize_u32, visit_u32, u32);+ coerce!(deserialize_u64, visit_u64, u64);+ coerce!(deserialize_f32, visit_f32, f32);+ coerce!(deserialize_f64, visit_f64, f64);+ coerce!(deserialize_bool, visit_bool, bool);++ /// Unit-variant enums (every `ST_*` type) need `visit_enum`, not+ /// `visit_str`, so this one hook delegates to serde's string deserializer+ /// rather than falling through to `deserialize_any`.+ fn deserialize_enum<V: Visitor<'de>>(+ self,+ name: &'static str,+ variants: &'static [&'static str],+ v: V,+ ) -> Result<V::Value, Self::Error> {+ let d: StrDeserializer<'_, ValueError> = self.0.into_deserializer();+ d.deserialize_enum(name, variants, v)+ }++ fn deserialize_option<V: Visitor<'de>>(self, v: V) -> Result<V::Value, Self::Error> {+ v.visit_some(self)+ }++ serde::forward_to_deserialize_any! {+ char str string bytes byte_buf unit unit_struct newtype_struct+ seq tuple tuple_struct map struct identifier ignored_any+ }+}++/// For `Option<StX>` attribute fields: unknown value → `None`.+///+/// Pair with `#[serde(default)]` so an absent attribute and an unparseable one+/// both land on `None`.+pub fn opt_attr<'de, D, T>(d: D) -> Result<Option<T>, D::Error>+where+ D: Deserializer<'de>,+ T: Deserialize<'de>,+{+ // Attribute values always arrive as strings, so we can take the raw text+ // first and only then attempt the enum conversion — the failure is ours to+ // swallow rather than the outer deserializer's to propagate.+ let Some(raw) = Option::<String>::deserialize(d)? else {+ return Ok(None);+ };+ Ok(T::deserialize(AttrValueDeserializer(&raw)).ok())+}++/// For `<w:x w:val="…"/>` elements whose `@val` is an `StX`: an unknown value+/// makes the whole element `None`, exactly as if it had not been written.+///+/// Collapses the `ValAttr<T>` wrapper away, so the field type is `Option<T>`+/// rather than `Option<ValAttr<T>>`.+pub fn opt_val_attr<'de, D, T>(d: D) -> Result<Option<T>, D::Error>+where+ D: Deserializer<'de>,+ T: Deserialize<'de>,+{+ /// `@val` is taken as a string so an unrecognized token is a value we can+ /// inspect rather than a deserializer error we cannot intercept.+ #[derive(Deserialize)]+ struct RawVal {+ #[serde(rename = "@val")]+ val: Option<String>,+ }++ let Some(raw) = Option::<RawVal>::deserialize(d)?.and_then(|r| r.val) else {+ return Ok(None);+ };+ Ok(T::deserialize(AttrValueDeserializer(&raw)).ok())+}++/// For *required* `StX` attributes that have a spec default: unknown value →+/// `T::default()`, i.e. treated as if the attribute were absent, which is what+/// §17.17 prescribes and what the field's own `#[serde(default)]` already does.+///+/// Only correct where `T`'s `Default` *is* the spec default. Where no default+/// is meaningful, make the field `Option<T>` with [`opt_attr`] instead and let+/// the consumer drop the containing element.+pub fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>+where+ D: Deserializer<'de>,+ T: Deserialize<'de> + Default,+{+ let raw = String::deserialize(d)?;+ Ok(T::deserialize(AttrValueDeserializer(&raw)).unwrap_or_default())+}++/// Required non-negative measurement: unparseable **or negative** → zero.+///+/// The zero fallback suits DrawingML sizes and offsets, where the value is+/// appearance-only and a zero-size shape is a harmless degradation. Keeps the+/// non-negativity guard that `deserialize_nonnegative_dimension` provides —+/// dropping it would let a negative extent through as a real size.+pub fn nonneg_or_default<'de, D, U>(d: D) -> Result<crate::model::dimension::Dimension<U>, D::Error>+where+ D: Deserializer<'de>,+ U: crate::model::dimension::Unit,+{+ use crate::docx::parse::primitives::integer_measure::IntegerMeasure;+ use crate::model::dimension::Dimension;++ let raw = String::deserialize(d)?;+ Ok(IntegerMeasure::deserialize(AttrValueDeserializer(&raw))+ .ok()+ .filter(|m| !m.is_negative())+ .map_or_else(Dimension::default, |m| Dimension::new(m.value())))+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde::Deserialize;++ #[derive(Debug, PartialEq, Deserialize)]+ #[serde(rename_all = "camelCase")]+ enum StFake {+ Left,+ Right,+ }++ #[derive(Debug, Deserialize)]+ struct AttrHolder {+ #[serde(rename = "@jc", default, deserialize_with = "opt_attr")]+ jc: Option<StFake>,+ }++ #[derive(Debug, Deserialize)]+ struct ValHolder {+ #[serde(rename = "jc", default, deserialize_with = "opt_val_attr")]+ jc: Option<StFake>,+ }++ fn attr(xml: &str) -> Option<StFake> {+ quick_xml::de::from_str::<AttrHolder>(xml).unwrap().jc+ }++ fn val(xml: &str) -> Option<StFake> {+ quick_xml::de::from_str::<ValHolder>(xml).unwrap().jc+ }++ #[test]+ fn attr_known_value_parses() {+ assert_eq!(attr(r#"<p jc="left"/>"#), Some(StFake::Left));+ }++ #[test]+ fn attr_unknown_value_is_none_not_an_error() {+ assert_eq!(attr(r#"<p jc="bogusValue"/>"#), None);+ }++ #[test]+ fn attr_absent_is_none() {+ assert_eq!(attr("<p/>"), None);+ }++ #[test]+ fn val_known_value_parses() {+ assert_eq!(val(r#"<p><jc val="right"/></p>"#), Some(StFake::Right));+ }++ #[test]+ fn val_unknown_value_is_none_not_an_error() {+ assert_eq!(val(r#"<p><jc val="bogusValue"/></p>"#), None);+ }++ #[test]+ fn val_absent_element_and_absent_attr_are_both_none() {+ assert_eq!(val("<p/>"), None);+ assert_eq!(val("<p><jc/></p>"), None);+ }++ // ── numeric coercion ──────────────────────────────────────────────────+ //+ // These guard a bug that silently corrupts documents rather than failing+ // them: serde's own string deserializer refuses to produce an integer, so+ // routing a numeric attribute through these helpers would swallow every+ // *valid* value as `None`. `gridSpan`, `numId`, `ilvl` and `outlineLvl`+ // all depend on this.++ #[derive(Debug, Deserialize)]+ struct NumAttrHolder {+ #[serde(rename = "@n", default, deserialize_with = "opt_attr")]+ n: Option<u32>,+ }++ #[derive(Debug, Deserialize)]+ struct NumValHolder {+ #[serde(rename = "n", default, deserialize_with = "opt_val_attr")]+ n: Option<i64>,+ }++ #[test]+ fn valid_numeric_attribute_is_not_swallowed() {+ let h: NumAttrHolder = quick_xml::de::from_str(r#"<x n="3"/>"#).unwrap();+ assert_eq!(h.n, Some(3), "a valid number must survive the helper");+ }++ #[test]+ fn valid_numeric_val_element_is_not_swallowed() {+ let h: NumValHolder = quick_xml::de::from_str(r#"<x><n val="-7"/></x>"#).unwrap();+ assert_eq!(h.n, Some(-7));+ }++ #[test]+ fn bogus_numeric_attribute_is_none_not_an_error() {+ let h: NumAttrHolder = quick_xml::de::from_str(r#"<x n="bogusValue"/>"#).unwrap();+ assert_eq!(h.n, None);+ }++ #[test]+ fn out_of_range_numeric_attribute_is_none_not_a_wrapped_value() {+ // u32::MAX + 1 must not wrap around into a plausible-looking number.+ let h: NumAttrHolder = quick_xml::de::from_str(r#"<x n="4294967296"/>"#).unwrap();+ assert_eq!(h.n, None);+ }++ #[test]+ fn or_default_coerces_numbers_and_falls_back() {+ #[derive(Debug, Deserialize)]+ struct H {+ #[serde(rename = "@n", default, deserialize_with = "or_default")]+ n: u32,+ }+ let ok: H = quick_xml::de::from_str(r#"<x n="12"/>"#).unwrap();+ assert_eq!(ok.n, 12);+ let bad: H = quick_xml::de::from_str(r#"<x n="bogusValue"/>"#).unwrap();+ assert_eq!(bad.n, 0);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/primitives/mod.rs b/crates/liteparse-docx/src/docx/parse/primitives/mod.rsnew file mode 100644index 0000000..a34bfc4--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/mod.rs@@ -0,0 +1,16 @@+//! Reusable schema atoms shared across OOXML serde parsers.+//!+//! Each submodule owns one category of primitive and its `Deserialize` impl.+//! All types here are pure schema-layer concerns — they may wrap model types+//! (e.g., `Dimension<U>`) but never leak serde into the model layer.++pub mod colors;+pub(crate) mod integer_measure;+pub mod lenient;+pub mod st_enums;+pub mod toggles;+pub mod units;++pub use colors::{HexColor, RgbHexU32};+pub(crate) use toggles::last_toggle;+pub use toggles::{AttrBool, OnOff};diff --git a/crates/liteparse-docx/src/docx/parse/primitives/st_enums.rs b/crates/liteparse-docx/src/docx/parse/primitives/st_enums.rsnew file mode 100644index 0000000..727a0be--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/st_enums.rs@@ -0,0 +1,1424 @@+//! OOXML `ST_*` simple-type enums with strict `Deserialize` impls.+//!+//! Each schema enum mirrors an OOXML spec-defined simple type. `From<St…>`+//! implementations convert the schema enum into the matching model type.+//! Unknown string values fail deserialization (plan §Decisions: strict) — the+//! one exception is `StNumberFormat`, a large extensible value space (~60 spec+//! values) whose unsupported members must degrade rather than fail the parse+//! (see its `#[serde(other)]` variant).+//!+//! Alphabetically ordered by schema type name. Layered as:+//!+//! 1. Schema enum with `#[derive(Deserialize)]` + `#[serde(rename_all)]`+//! (or explicit per-variant rename where the value doesn't match `camelCase`).+//! 2. `impl From<StXxx> for ModelXxx` — identity mapping in most cases,+//! re-naming/re-mapping where the model is coarser or uses different names.+//!+//! Tests live at the bottom of the file and cover every variant plus a+//! known-bad value for each enum.++use serde::Deserialize;++use crate::docx::model::{+ Alignment, BorderStyle, BreakClear, CellVerticalAlign, FieldCharType, FrameWrap, HeightRule,+ HighlightColor, NumberFormat, PTabAlignment, PTabLeader, PTabRelativeTo, PageOrientation,+ SectionType, ShadingPattern, TabAlignment, TabLeader, TableAnchor, TableLayout, TableOverlap,+ TableXAlign, TableYAlign, TextAlignment, TextDirection, ThemeFontRef, UnderlineStyle,+ VerticalAlign,+};++// ── StBorderType (§17.18.2) ───────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StBorderType {+ /// §17.18.2: "no border" — distinct from `none`, and carried through as+ /// such. See `BorderStyle` for why the two must not be merged.+ Nil,+ #[default]+ None,+ Single,+ Thick,+ Double,+ Dotted,+ Dashed,+ DotDash,+ DotDotDash,+ Triple,+ ThinThickSmallGap,+ ThickThinSmallGap,+ ThinThickThinSmallGap,+ ThinThickMediumGap,+ ThickThinMediumGap,+ ThinThickThinMediumGap,+ ThinThickLargeGap,+ ThickThinLargeGap,+ ThinThickThinLargeGap,+ Wave,+ DoubleWave,+ DashSmallGap,+ DashDotStroked,+ ThreeDEmboss,+ ThreeDEngrave,+ Outset,+ Inset,+}++impl From<StBorderType> for BorderStyle {+ fn from(s: StBorderType) -> Self {+ match s {+ // §17.18.2: kept distinct. Both draw nothing, but [MS-OI29500]+ // §17.4.66 gives them opposite behaviour in table border conflict+ // resolution — `nil` suppresses the shared edge, `none` yields.+ StBorderType::Nil => Self::Nil,+ StBorderType::None => Self::None,+ StBorderType::Single => Self::Single,+ StBorderType::Thick => Self::Thick,+ StBorderType::Double => Self::Double,+ StBorderType::Dotted => Self::Dotted,+ StBorderType::Dashed => Self::Dashed,+ StBorderType::DotDash => Self::DotDash,+ StBorderType::DotDotDash => Self::DotDotDash,+ StBorderType::Triple => Self::Triple,+ StBorderType::ThinThickSmallGap => Self::ThinThickSmallGap,+ StBorderType::ThickThinSmallGap => Self::ThickThinSmallGap,+ StBorderType::ThinThickThinSmallGap => Self::ThinThickThinSmallGap,+ StBorderType::ThinThickMediumGap => Self::ThinThickMediumGap,+ StBorderType::ThickThinMediumGap => Self::ThickThinMediumGap,+ StBorderType::ThinThickThinMediumGap => Self::ThinThickThinMediumGap,+ StBorderType::ThinThickLargeGap => Self::ThinThickLargeGap,+ StBorderType::ThickThinLargeGap => Self::ThickThinLargeGap,+ StBorderType::ThinThickThinLargeGap => Self::ThinThickThinLargeGap,+ StBorderType::Wave => Self::Wave,+ StBorderType::DoubleWave => Self::DoubleWave,+ StBorderType::DashSmallGap => Self::DashSmallGap,+ StBorderType::DashDotStroked => Self::DashDotStroked,+ StBorderType::ThreeDEmboss => Self::ThreeDEmboss,+ StBorderType::ThreeDEngrave => Self::ThreeDEngrave,+ StBorderType::Outset => Self::Outset,+ StBorderType::Inset => Self::Inset,+ }+ }+}++// ── StBrClear (§17.18.4) ──────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StBrClear {+ None,+ Left,+ Right,+ All,+}++impl From<StBrClear> for BreakClear {+ fn from(s: StBrClear) -> Self {+ match s {+ StBrClear::None => Self::None,+ StBrClear::Left => Self::Left,+ StBrClear::Right => Self::Right,+ StBrClear::All => Self::All,+ }+ }+}++// ── StFldCharType (§17.18.29) ─────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StFldCharType {+ Begin,+ Separate,+ End,+}++impl From<StFldCharType> for FieldCharType {+ fn from(s: StFldCharType) -> Self {+ match s {+ StFldCharType::Begin => Self::Begin,+ StFldCharType::Separate => Self::Separate,+ StFldCharType::End => Self::End,+ }+ }+}++// ── StFrameWrap (§17.18.104 ST_Wrap) ──────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StFrameWrap {+ Auto,+ NotBeside,+ Around,+ Tight,+ Through,+ None,+}++impl From<StFrameWrap> for FrameWrap {+ fn from(s: StFrameWrap) -> Self {+ match s {+ StFrameWrap::Auto => Self::Auto,+ StFrameWrap::NotBeside => Self::NotBeside,+ StFrameWrap::Around => Self::Around,+ StFrameWrap::Tight => Self::Tight,+ StFrameWrap::Through => Self::Through,+ StFrameWrap::None => Self::None,+ }+ }+}++// ── StHeightRule (§17.18.38) ──────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StHeightRule {+ Auto,+ Exact,+ AtLeast,+}++impl From<StHeightRule> for HeightRule {+ fn from(s: StHeightRule) -> Self {+ match s {+ StHeightRule::Auto => Self::Auto,+ StHeightRule::Exact => Self::Exact,+ StHeightRule::AtLeast => Self::AtLeast,+ }+ }+}++// ── StHighlightColor (§17.18.40) ──────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StHighlightColor {+ /// §17.18.40: explicit "no highlight" — overrides any inherited+ /// highlight. Distinct from absence of the element, which inherits.+ None,+ Black,+ Blue,+ Cyan,+ DarkBlue,+ DarkCyan,+ DarkGray,+ DarkGreen,+ DarkMagenta,+ DarkRed,+ DarkYellow,+ Green,+ LightGray,+ Magenta,+ Red,+ White,+ Yellow,+}++impl From<StHighlightColor> for HighlightColor {+ fn from(s: StHighlightColor) -> Self {+ match s {+ StHighlightColor::None => Self::None,+ StHighlightColor::Black => Self::Black,+ StHighlightColor::Blue => Self::Blue,+ StHighlightColor::Cyan => Self::Cyan,+ StHighlightColor::DarkBlue => Self::DarkBlue,+ StHighlightColor::DarkCyan => Self::DarkCyan,+ StHighlightColor::DarkGray => Self::DarkGray,+ StHighlightColor::DarkGreen => Self::DarkGreen,+ StHighlightColor::DarkMagenta => Self::DarkMagenta,+ StHighlightColor::DarkRed => Self::DarkRed,+ StHighlightColor::DarkYellow => Self::DarkYellow,+ StHighlightColor::Green => Self::Green,+ StHighlightColor::LightGray => Self::LightGray,+ StHighlightColor::Magenta => Self::Magenta,+ StHighlightColor::Red => Self::Red,+ StHighlightColor::White => Self::White,+ StHighlightColor::Yellow => Self::Yellow,+ }+ }+}++// ── StJc (§17.18.44) ──────────────────────────────────────────────────────+//+// OOXML `both` and `justify` are synonyms per the spec; both produce+// `Alignment::Both`. Rust variant names follow the model's directional+// naming (Start/End) rather than OOXML's presentation naming (Left/Right),+// preserving fidelity to the schema side.++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+pub enum StJc {+ #[serde(rename = "left", alias = "start")]+ Left,+ #[serde(rename = "center")]+ Center,+ #[serde(rename = "right", alias = "end")]+ Right,+ #[serde(rename = "both", alias = "justify")]+ Both,+ #[serde(rename = "distribute")]+ Distribute,+ #[serde(rename = "thaiDistribute")]+ ThaiDistribute,+ // §17.18.44: Arabic kashida justification and the legacy numbering-tab+ // alignment are spec-legal but not modelled distinctly. They must still+ // parse (else an Arabic document fails outright); each degrades to the+ // nearest modelled alignment. Kept as named variants rather than a+ // catch-all so a genuine typo still fails deserialization.+ #[serde(rename = "mediumKashida")]+ MediumKashida,+ #[serde(rename = "highKashida")]+ HighKashida,+ #[serde(rename = "lowKashida")]+ LowKashida,+ #[serde(rename = "numTab")]+ NumTab,+}++impl From<StJc> for Alignment {+ fn from(s: StJc) -> Self {+ match s {+ StJc::Left => Self::Start,+ StJc::Center => Self::Center,+ StJc::Right => Self::End,+ StJc::Both => Self::Both,+ StJc::Distribute => Self::Distribute,+ StJc::ThaiDistribute => Self::Thai,+ // Kashida is a form of full justification; numTab aligns to the+ // start of the numbering area.+ StJc::MediumKashida | StJc::HighKashida | StJc::LowKashida => Self::Both,+ StJc::NumTab => Self::Start,+ }+ }+}++// ── StLineSpacingRule (§17.18.48) ─────────────────────────────────────────+//+// No `From` impl: the model's `LineSpacing` is a discriminated union that+// combines the rule with the value. The conversion happens at the owning+// schema (see `parse::properties::paragraph::SpacingXml`).++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StLineSpacingRule {+ Auto,+ Exact,+ AtLeast,+}++// ── StNumberFormat (§17.18.59) ────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StNumberFormat {+ Decimal,+ UpperRoman,+ LowerRoman,+ UpperLetter,+ LowerLetter,+ Bullet,+ Ordinal,+ CardinalText,+ OrdinalText,+ None,+ /// §17.18.59 ST_NumberFormat lists ~60 values (hebrew1, japaneseCounting,+ /// decimalZero, russianLower, hex, …); the renderer models only the common+ /// subset above. This is the **exception to the strict-enum rule**: a large,+ /// extensible value space where a legal-but-unsupported value must degrade,+ /// not fail — otherwise one exotic `<w:numFmt>` would fail the *whole*+ /// document parse (`parse_numbering(..)?` propagates the error). Word itself+ /// falls back to decimal for formats it can't render.+ #[serde(other)]+ Other,+}++impl From<StNumberFormat> for NumberFormat {+ fn from(s: StNumberFormat) -> Self {+ match s {+ StNumberFormat::Decimal => Self::Decimal,+ StNumberFormat::UpperRoman => Self::UpperRoman,+ StNumberFormat::LowerRoman => Self::LowerRoman,+ StNumberFormat::UpperLetter => Self::UpperLetter,+ StNumberFormat::LowerLetter => Self::LowerLetter,+ StNumberFormat::Bullet => Self::Bullet,+ StNumberFormat::Ordinal => Self::Ordinal,+ StNumberFormat::CardinalText => Self::CardinalText,+ StNumberFormat::OrdinalText => Self::OrdinalText,+ StNumberFormat::None => Self::None,+ StNumberFormat::Other => Self::Decimal,+ }+ }+}++// ── StPageOrientation (§17.18.65) ─────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StPageOrientation {+ Portrait,+ Landscape,+}++impl From<StPageOrientation> for PageOrientation {+ fn from(s: StPageOrientation) -> Self {+ match s {+ StPageOrientation::Portrait => Self::Portrait,+ StPageOrientation::Landscape => Self::Landscape,+ }+ }+}++// ── StSectionMark (§17.18.77) ─────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StSectionMark {+ #[default]+ NextPage,+ Continuous,+ EvenPage,+ OddPage,+ NextColumn,+}++impl From<StSectionMark> for SectionType {+ fn from(s: StSectionMark) -> Self {+ match s {+ StSectionMark::NextPage => Self::NextPage,+ StSectionMark::Continuous => Self::Continuous,+ StSectionMark::EvenPage => Self::EvenPage,+ StSectionMark::OddPage => Self::OddPage,+ StSectionMark::NextColumn => Self::NextColumn,+ }+ }+}++// ── StShd (§17.18.78) ─────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StShd {+ /// §17.18.78 ST_Shd: `nil` — no shading whatsoever (distinct from+ /// `clear`, which means "transparent shading with a defined color").+ Nil,+ #[default]+ Clear,+ Solid,+ HorzStripe,+ VertStripe,+ ReverseDiagStripe,+ DiagStripe,+ HorzCross,+ DiagCross,+ ThinHorzStripe,+ ThinVertStripe,+ ThinReverseDiagStripe,+ ThinDiagStripe,+ ThinHorzCross,+ ThinDiagCross,+ Pct5,+ Pct10,+ Pct12,+ Pct15,+ Pct20,+ Pct25,+ Pct30,+ Pct35,+ Pct37,+ Pct40,+ Pct45,+ Pct50,+ Pct55,+ Pct60,+ Pct62,+ Pct65,+ Pct70,+ Pct75,+ Pct80,+ Pct85,+ Pct87,+ Pct90,+ Pct95,+}++impl From<StShd> for ShadingPattern {+ fn from(s: StShd) -> Self {+ match s {+ StShd::Nil => Self::Nil,+ StShd::Clear => Self::Clear,+ StShd::Solid => Self::Solid,+ StShd::HorzStripe => Self::HorzStripe,+ StShd::VertStripe => Self::VertStripe,+ StShd::ReverseDiagStripe => Self::ReverseDiagStripe,+ StShd::DiagStripe => Self::DiagStripe,+ StShd::HorzCross => Self::HorzCross,+ StShd::DiagCross => Self::DiagCross,+ StShd::ThinHorzStripe => Self::ThinHorzStripe,+ StShd::ThinVertStripe => Self::ThinVertStripe,+ StShd::ThinReverseDiagStripe => Self::ThinReverseDiagStripe,+ StShd::ThinDiagStripe => Self::ThinDiagStripe,+ StShd::ThinHorzCross => Self::ThinHorzCross,+ StShd::ThinDiagCross => Self::ThinDiagCross,+ StShd::Pct5 => Self::Pct5,+ StShd::Pct10 => Self::Pct10,+ StShd::Pct12 => Self::Pct12,+ StShd::Pct15 => Self::Pct15,+ StShd::Pct20 => Self::Pct20,+ StShd::Pct25 => Self::Pct25,+ StShd::Pct30 => Self::Pct30,+ StShd::Pct35 => Self::Pct35,+ StShd::Pct37 => Self::Pct37,+ StShd::Pct40 => Self::Pct40,+ StShd::Pct45 => Self::Pct45,+ StShd::Pct50 => Self::Pct50,+ StShd::Pct55 => Self::Pct55,+ StShd::Pct60 => Self::Pct60,+ StShd::Pct62 => Self::Pct62,+ StShd::Pct65 => Self::Pct65,+ StShd::Pct70 => Self::Pct70,+ StShd::Pct75 => Self::Pct75,+ StShd::Pct80 => Self::Pct80,+ StShd::Pct85 => Self::Pct85,+ StShd::Pct87 => Self::Pct87,+ StShd::Pct90 => Self::Pct90,+ StShd::Pct95 => Self::Pct95,+ }+ }+}++// ── StHAnchor/StVAnchor (§17.18.35/106) ─────────────────────────────────+//+// Shared by table positioning (`<w:tblpPr>`) and frame positioning+// (`<w:framePr>`). OOXML uses the same tag set in both spots.++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StAnchor {+ Text,+ Margin,+ Page,+}++impl From<StAnchor> for TableAnchor {+ fn from(s: StAnchor) -> Self {+ match s {+ StAnchor::Text => Self::Text,+ StAnchor::Margin => Self::Margin,+ StAnchor::Page => Self::Page,+ }+ }+}++// ── StXAlign (§17.18.108) ────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StXAlign {+ Left,+ Center,+ Right,+ Inside,+ Outside,+}++impl From<StXAlign> for TableXAlign {+ fn from(s: StXAlign) -> Self {+ match s {+ StXAlign::Left => Self::Left,+ StXAlign::Center => Self::Center,+ StXAlign::Right => Self::Right,+ StXAlign::Inside => Self::Inside,+ StXAlign::Outside => Self::Outside,+ }+ }+}++// ── StYAlign (§17.18.109) ────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StYAlign {+ Top,+ Center,+ Bottom,+ Inside,+ Outside,+ Inline,+}++impl From<StYAlign> for TableYAlign {+ fn from(s: StYAlign) -> Self {+ match s {+ StYAlign::Top => Self::Top,+ StYAlign::Center => Self::Center,+ StYAlign::Bottom => Self::Bottom,+ StYAlign::Inside => Self::Inside,+ StYAlign::Outside => Self::Outside,+ StYAlign::Inline => Self::Inline,+ }+ }+}++// ── StTabJc (§17.18.85 tab alignment) ─────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StTabJc {+ #[default]+ Left,+ Center,+ Right,+ Decimal,+ Bar,+ Clear,+ /// Legacy — treated as `Left`.+ Num,+}++impl From<StTabJc> for TabAlignment {+ fn from(s: StTabJc) -> Self {+ match s {+ StTabJc::Left | StTabJc::Num => Self::Left,+ StTabJc::Center => Self::Center,+ StTabJc::Right => Self::Right,+ StTabJc::Decimal => Self::Decimal,+ StTabJc::Bar => Self::Bar,+ StTabJc::Clear => Self::Clear,+ }+ }+}++// ── StTabTlc (§17.18.86 tab leader character) ─────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StTabTlc {+ #[default]+ None,+ Dot,+ Hyphen,+ Underscore,+ Heavy,+ MiddleDot,+}++impl From<StTabTlc> for TabLeader {+ fn from(s: StTabTlc) -> Self {+ match s {+ StTabTlc::None => Self::None,+ StTabTlc::Dot => Self::Dot,+ StTabTlc::Hyphen => Self::Hyphen,+ StTabTlc::Underscore => Self::Underscore,+ StTabTlc::Heavy => Self::Heavy,+ StTabTlc::MiddleDot => Self::MiddleDot,+ }+ }+}++// ── StPTabAlignment (§17.18.59 absolute position tab alignment) ────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StPTabAlignment {+ #[default]+ Left,+ Center,+ Right,+}++impl From<StPTabAlignment> for PTabAlignment {+ fn from(s: StPTabAlignment) -> Self {+ match s {+ StPTabAlignment::Left => Self::Left,+ StPTabAlignment::Center => Self::Center,+ StPTabAlignment::Right => Self::Right,+ }+ }+}++// ── StPTabRelativeTo (§17.18.61 absolute position tab base) ────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StPTabRelativeTo {+ Margin,+ #[default]+ Indent,+}++impl From<StPTabRelativeTo> for PTabRelativeTo {+ fn from(s: StPTabRelativeTo) -> Self {+ match s {+ StPTabRelativeTo::Margin => Self::Margin,+ StPTabRelativeTo::Indent => Self::Indent,+ }+ }+}++// ── StPTabLeader (§17.18.60 absolute position tab leader) ──────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StPTabLeader {+ #[default]+ None,+ Dot,+ Hyphen,+ Underscore,+ MiddleDot,+}++impl From<StPTabLeader> for PTabLeader {+ fn from(s: StPTabLeader) -> Self {+ match s {+ StPTabLeader::None => Self::None,+ StPTabLeader::Dot => Self::Dot,+ StPTabLeader::Hyphen => Self::Hyphen,+ StPTabLeader::Underscore => Self::Underscore,+ StPTabLeader::MiddleDot => Self::MiddleDot,+ }+ }+}++// ── StTblLayoutType (§17.18.87) ───────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum StTblLayoutType {+ #[default]+ Auto,+ Fixed,+}++impl From<StTblLayoutType> for TableLayout {+ fn from(s: StTblLayoutType) -> Self {+ match s {+ StTblLayoutType::Auto => Self::Auto,+ StTblLayoutType::Fixed => Self::Fixed,+ }+ }+}++// ── StTblOverlap (§17.4.56) ───────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StTblOverlap {+ Overlap,+ Never,+}++impl From<StTblOverlap> for TableOverlap {+ fn from(s: StTblOverlap) -> Self {+ match s {+ StTblOverlap::Overlap => Self::Overlap,+ StTblOverlap::Never => Self::Never,+ }+ }+}++// ── StTextAlignment (§17.18.91) ───────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StTextAlignment {+ Auto,+ Top,+ Center,+ Baseline,+ Bottom,+}++impl From<StTextAlignment> for TextAlignment {+ fn from(s: StTextAlignment) -> Self {+ match s {+ StTextAlignment::Auto => Self::Auto,+ StTextAlignment::Top => Self::Top,+ StTextAlignment::Center => Self::Center,+ StTextAlignment::Baseline => Self::Baseline,+ StTextAlignment::Bottom => Self::Bottom,+ }+ }+}++// ── StTextDirection (§17.18.93) ───────────────────────────────────────────+//+// OOXML uses opaque two/three-letter codes; the model spells the full+// directional order. Mapping is static.++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+pub enum StTextDirection {+ #[serde(rename = "lrTb")]+ LrTb,+ #[serde(rename = "tbRl")]+ TbRl,+ #[serde(rename = "btLr")]+ BtLr,+ #[serde(rename = "lrTbV")]+ LrTbV,+ #[serde(rename = "tbRlV")]+ TbRlV,+ #[serde(rename = "tbLrV")]+ TbLrV,+}++impl From<StTextDirection> for TextDirection {+ fn from(s: StTextDirection) -> Self {+ match s {+ StTextDirection::LrTb => Self::LeftToRightTopToBottom,+ StTextDirection::TbRl => Self::TopToBottomRightToLeft,+ StTextDirection::BtLr => Self::BottomToTopLeftToRight,+ StTextDirection::LrTbV => Self::LeftToRightTopToBottomRotated,+ StTextDirection::TbRlV => Self::TopToBottomRightToLeftRotated,+ StTextDirection::TbLrV => Self::TopToBottomLeftToRightRotated,+ }+ }+}++// ── StTheme (§17.18.95) ───────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StTheme {+ MajorHAnsi,+ MajorEastAsia,+ MajorBidi,+ MinorHAnsi,+ MinorEastAsia,+ MinorBidi,+}++impl From<StTheme> for ThemeFontRef {+ fn from(s: StTheme) -> Self {+ match s {+ StTheme::MajorHAnsi => Self::MajorHAnsi,+ StTheme::MajorEastAsia => Self::MajorEastAsia,+ StTheme::MajorBidi => Self::MajorBidi,+ StTheme::MinorHAnsi => Self::MinorHAnsi,+ StTheme::MinorEastAsia => Self::MinorEastAsia,+ StTheme::MinorBidi => Self::MinorBidi,+ }+ }+}++// ── StUnderline (§17.18.99) ───────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StUnderline {+ None,+ Single,+ Words,+ Double,+ Thick,+ Dotted,+ DottedHeavy,+ Dash,+ DashedHeavy,+ DashLong,+ DashLongHeavy,+ DotDash,+ DashDotHeavy,+ DotDotDash,+ DashDotDotHeavy,+ Wave,+ WavyHeavy,+ WavyDouble,+}++impl From<StUnderline> for UnderlineStyle {+ fn from(s: StUnderline) -> Self {+ match s {+ StUnderline::None => Self::None,+ StUnderline::Single => Self::Single,+ StUnderline::Words => Self::Words,+ StUnderline::Double => Self::Double,+ StUnderline::Thick => Self::Thick,+ StUnderline::Dotted => Self::Dotted,+ StUnderline::DottedHeavy => Self::DottedHeavy,+ StUnderline::Dash => Self::Dash,+ StUnderline::DashedHeavy => Self::DashedHeavy,+ StUnderline::DashLong => Self::DashLong,+ StUnderline::DashLongHeavy => Self::DashLongHeavy,+ StUnderline::DotDash => Self::DotDash,+ StUnderline::DashDotHeavy => Self::DashDotHeavy,+ StUnderline::DotDotDash => Self::DotDotDash,+ StUnderline::DashDotDotHeavy => Self::DashDotDotHeavy,+ StUnderline::Wave => Self::Wave,+ StUnderline::WavyHeavy => Self::WavyHeavy,+ StUnderline::WavyDouble => Self::WavyDouble,+ }+ }+}++// ── StVerticalAlignRun (§17.18.100) ───────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StVerticalAlignRun {+ Baseline,+ Superscript,+ Subscript,+}++impl From<StVerticalAlignRun> for VerticalAlign {+ fn from(s: StVerticalAlignRun) -> Self {+ match s {+ StVerticalAlignRun::Baseline => Self::Baseline,+ StVerticalAlignRun::Superscript => Self::Superscript,+ StVerticalAlignRun::Subscript => Self::Subscript,+ }+ }+}++// ── StVerticalJc (§17.18.101) ─────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum StVerticalJc {+ Top,+ Center,+ Bottom,+ Both,+}++impl From<StVerticalJc> for CellVerticalAlign {+ fn from(s: StVerticalJc) -> Self {+ match s {+ StVerticalJc::Top => Self::Top,+ StVerticalJc::Center => Self::Center,+ StVerticalJc::Bottom => Self::Bottom,+ StVerticalJc::Both => Self::Both,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde::de::DeserializeOwned;++ fn de<T: DeserializeOwned>(v: &str) -> Result<T, quick_xml::DeError> {+ #[derive(Deserialize)]+ struct Wrap<X> {+ #[serde(rename = "@v")]+ v: X,+ }+ quick_xml::de::from_str::<Wrap<T>>(&format!(r#"<x v="{v}"/>"#)).map(|w| w.v)+ }++ fn assert_bad<T: DeserializeOwned + std::fmt::Debug>(v: &str) {+ let r: Result<T, _> = de(v);+ assert!(r.is_err(), "expected error for {v:?}, got {r:?}");+ }++ // ── StBorderType ──+ #[test]+ fn border_type_all_variants() {+ assert_eq!(de::<StBorderType>("none").unwrap(), StBorderType::None);+ assert_eq!(de::<StBorderType>("single").unwrap(), StBorderType::Single);+ assert_eq!(+ de::<StBorderType>("dotDash").unwrap(),+ StBorderType::DotDash+ );+ assert_eq!(+ de::<StBorderType>("threeDEmboss").unwrap(),+ StBorderType::ThreeDEmboss+ );+ assert_eq!(+ de::<StBorderType>("threeDEngrave").unwrap(),+ StBorderType::ThreeDEngrave+ );+ assert_eq!(de::<StBorderType>("inset").unwrap(), StBorderType::Inset);+ }+ #[test]+ fn border_type_strict() {+ assert_bad::<StBorderType>("bogus");+ }+ #[test]+ fn border_type_converts_to_model() {+ let m: BorderStyle = StBorderType::DashDotStroked.into();+ assert_eq!(m, BorderStyle::DashDotStroked);+ }++ // ── StBrClear ──+ #[test]+ fn br_clear_all_variants() {+ assert_eq!(de::<StBrClear>("none").unwrap(), StBrClear::None);+ assert_eq!(de::<StBrClear>("left").unwrap(), StBrClear::Left);+ assert_eq!(de::<StBrClear>("right").unwrap(), StBrClear::Right);+ assert_eq!(de::<StBrClear>("all").unwrap(), StBrClear::All);+ }+ #[test]+ fn br_clear_strict() {+ assert_bad::<StBrClear>("middle");+ }+ #[test]+ fn br_clear_converts_to_model() {+ let m: BreakClear = StBrClear::Left.into();+ assert_eq!(m, BreakClear::Left);+ }++ // ── StFldCharType ──+ #[test]+ fn fld_char_type_all_variants() {+ assert_eq!(de::<StFldCharType>("begin").unwrap(), StFldCharType::Begin);+ assert_eq!(+ de::<StFldCharType>("separate").unwrap(),+ StFldCharType::Separate+ );+ assert_eq!(de::<StFldCharType>("end").unwrap(), StFldCharType::End);+ }+ #[test]+ fn fld_char_type_strict() {+ assert_bad::<StFldCharType>("middle");+ }++ // ── StFrameWrap ──+ #[test]+ fn frame_wrap_all_variants() {+ assert_eq!(de::<StFrameWrap>("auto").unwrap(), StFrameWrap::Auto);+ assert_eq!(+ de::<StFrameWrap>("notBeside").unwrap(),+ StFrameWrap::NotBeside+ );+ assert_eq!(de::<StFrameWrap>("around").unwrap(), StFrameWrap::Around);+ assert_eq!(de::<StFrameWrap>("tight").unwrap(), StFrameWrap::Tight);+ assert_eq!(de::<StFrameWrap>("through").unwrap(), StFrameWrap::Through);+ assert_eq!(de::<StFrameWrap>("none").unwrap(), StFrameWrap::None);+ }+ #[test]+ fn frame_wrap_strict() {+ assert_bad::<StFrameWrap>("wrap");+ }++ // ── StHeightRule ──+ #[test]+ fn height_rule_all_variants() {+ assert_eq!(de::<StHeightRule>("auto").unwrap(), StHeightRule::Auto);+ assert_eq!(de::<StHeightRule>("exact").unwrap(), StHeightRule::Exact);+ assert_eq!(+ de::<StHeightRule>("atLeast").unwrap(),+ StHeightRule::AtLeast+ );+ }+ #[test]+ fn height_rule_strict() {+ assert_bad::<StHeightRule>("maximum");+ }++ // ── StHighlightColor ──+ #[test]+ fn highlight_color_sample_variants() {+ assert_eq!(+ de::<StHighlightColor>("black").unwrap(),+ StHighlightColor::Black+ );+ assert_eq!(+ de::<StHighlightColor>("darkMagenta").unwrap(),+ StHighlightColor::DarkMagenta+ );+ assert_eq!(+ de::<StHighlightColor>("lightGray").unwrap(),+ StHighlightColor::LightGray+ );+ assert_eq!(+ de::<StHighlightColor>("yellow").unwrap(),+ StHighlightColor::Yellow+ );+ }+ #[test]+ fn highlight_color_strict() {+ assert_bad::<StHighlightColor>("chartreuse");+ }++ // ── StJc — includes the both/justify alias and Start/End rename ──+ #[test]+ fn jc_all_variants_and_aliases() {+ assert_eq!(de::<StJc>("left").unwrap(), StJc::Left);+ assert_eq!(de::<StJc>("start").unwrap(), StJc::Left); // alias+ assert_eq!(de::<StJc>("center").unwrap(), StJc::Center);+ assert_eq!(de::<StJc>("right").unwrap(), StJc::Right);+ assert_eq!(de::<StJc>("end").unwrap(), StJc::Right); // alias+ assert_eq!(de::<StJc>("both").unwrap(), StJc::Both);+ assert_eq!(de::<StJc>("justify").unwrap(), StJc::Both); // alias+ assert_eq!(de::<StJc>("distribute").unwrap(), StJc::Distribute);+ assert_eq!(de::<StJc>("thaiDistribute").unwrap(), StJc::ThaiDistribute);+ }+ #[test]+ fn jc_kashida_and_numtab_are_legal_and_degrade() {+ // §17.18.44: spec-legal values that would otherwise crash an Arabic /+ // legacy-numbered document's parse. They parse and degrade to the+ // nearest modelled alignment.+ assert_eq!(de::<StJc>("mediumKashida").unwrap(), StJc::MediumKashida);+ assert_eq!(de::<StJc>("highKashida").unwrap(), StJc::HighKashida);+ assert_eq!(de::<StJc>("lowKashida").unwrap(), StJc::LowKashida);+ assert_eq!(de::<StJc>("numTab").unwrap(), StJc::NumTab);+ }+ #[test]+ fn jc_strict() {+ // A genuine typo still fails — the kashida/numTab additions are named+ // variants, not a catch-all.+ assert_bad::<StJc>("middle");+ }+ #[test]+ fn jc_converts_to_model_with_rename() {+ assert_eq!(Alignment::from(StJc::Left), Alignment::Start);+ assert_eq!(Alignment::from(StJc::Right), Alignment::End);+ assert_eq!(Alignment::from(StJc::ThaiDistribute), Alignment::Thai);+ assert_eq!(Alignment::from(StJc::MediumKashida), Alignment::Both);+ assert_eq!(Alignment::from(StJc::NumTab), Alignment::Start);+ }++ // ── StNumberFormat ──+ #[test]+ fn number_format_all_variants() {+ assert_eq!(+ de::<StNumberFormat>("decimal").unwrap(),+ StNumberFormat::Decimal+ );+ assert_eq!(+ de::<StNumberFormat>("upperRoman").unwrap(),+ StNumberFormat::UpperRoman+ );+ assert_eq!(+ de::<StNumberFormat>("cardinalText").unwrap(),+ StNumberFormat::CardinalText+ );+ assert_eq!(+ de::<StNumberFormat>("bullet").unwrap(),+ StNumberFormat::Bullet+ );+ }+ #[test]+ fn number_format_unsupported_legal_values_degrade_not_fail() {+ // §17.18.59 has ~60 legal values; unsupported ones must parse (→ Other)+ // and convert to Decimal rather than failing the whole document parse.+ for v in [+ "hex",+ "hebrew1",+ "japaneseCounting",+ "decimalZero",+ "russianLower",+ ] {+ assert_eq!(+ de::<StNumberFormat>(v).unwrap(),+ StNumberFormat::Other,+ "{v:?} is spec-legal and must degrade to Other, not error"+ );+ }+ assert_eq!(+ NumberFormat::from(StNumberFormat::Other),+ NumberFormat::Decimal+ );+ }++ // ── StPageOrientation ──+ #[test]+ fn page_orientation_both() {+ assert_eq!(+ de::<StPageOrientation>("portrait").unwrap(),+ StPageOrientation::Portrait+ );+ assert_eq!(+ de::<StPageOrientation>("landscape").unwrap(),+ StPageOrientation::Landscape+ );+ }+ #[test]+ fn page_orientation_strict() {+ assert_bad::<StPageOrientation>("sideways");+ }++ // ── StSectionMark ──+ #[test]+ fn section_mark_all_variants() {+ assert_eq!(+ de::<StSectionMark>("nextPage").unwrap(),+ StSectionMark::NextPage+ );+ assert_eq!(+ de::<StSectionMark>("continuous").unwrap(),+ StSectionMark::Continuous+ );+ assert_eq!(+ de::<StSectionMark>("evenPage").unwrap(),+ StSectionMark::EvenPage+ );+ assert_eq!(+ de::<StSectionMark>("oddPage").unwrap(),+ StSectionMark::OddPage+ );+ assert_eq!(+ de::<StSectionMark>("nextColumn").unwrap(),+ StSectionMark::NextColumn+ );+ }+ #[test]+ fn section_mark_strict() {+ assert_bad::<StSectionMark>("previous");+ }++ // ── StShd ──+ #[test]+ fn shd_sample_variants() {+ assert_eq!(de::<StShd>("clear").unwrap(), StShd::Clear);+ assert_eq!(de::<StShd>("solid").unwrap(), StShd::Solid);+ assert_eq!(de::<StShd>("horzStripe").unwrap(), StShd::HorzStripe);+ assert_eq!(de::<StShd>("thinDiagCross").unwrap(), StShd::ThinDiagCross);+ assert_eq!(de::<StShd>("pct5").unwrap(), StShd::Pct5);+ assert_eq!(de::<StShd>("pct95").unwrap(), StShd::Pct95);+ }+ #[test]+ fn shd_strict() {+ assert_bad::<StShd>("pct100");+ }++ // ── StTblLayoutType ──+ #[test]+ fn tbl_layout_type_both() {+ assert_eq!(+ de::<StTblLayoutType>("auto").unwrap(),+ StTblLayoutType::Auto+ );+ assert_eq!(+ de::<StTblLayoutType>("fixed").unwrap(),+ StTblLayoutType::Fixed+ );+ }+ #[test]+ fn tbl_layout_type_strict() {+ assert_bad::<StTblLayoutType>("flex");+ }++ // ── StTblOverlap ──+ #[test]+ fn tbl_overlap_both() {+ assert_eq!(+ de::<StTblOverlap>("overlap").unwrap(),+ StTblOverlap::Overlap+ );+ assert_eq!(de::<StTblOverlap>("never").unwrap(), StTblOverlap::Never);+ }+ #[test]+ fn tbl_overlap_strict() {+ assert_bad::<StTblOverlap>("always");+ }++ // ── StTextAlignment ──+ #[test]+ fn text_alignment_all_variants() {+ assert_eq!(+ de::<StTextAlignment>("auto").unwrap(),+ StTextAlignment::Auto+ );+ assert_eq!(de::<StTextAlignment>("top").unwrap(), StTextAlignment::Top);+ assert_eq!(+ de::<StTextAlignment>("center").unwrap(),+ StTextAlignment::Center+ );+ assert_eq!(+ de::<StTextAlignment>("baseline").unwrap(),+ StTextAlignment::Baseline+ );+ assert_eq!(+ de::<StTextAlignment>("bottom").unwrap(),+ StTextAlignment::Bottom+ );+ }+ #[test]+ fn text_alignment_strict() {+ assert_bad::<StTextAlignment>("middle");+ }++ // ── StTextDirection ──+ #[test]+ fn text_direction_all_variants() {+ assert_eq!(+ de::<StTextDirection>("lrTb").unwrap(),+ StTextDirection::LrTb+ );+ assert_eq!(+ de::<StTextDirection>("tbRl").unwrap(),+ StTextDirection::TbRl+ );+ assert_eq!(+ de::<StTextDirection>("btLr").unwrap(),+ StTextDirection::BtLr+ );+ assert_eq!(+ de::<StTextDirection>("lrTbV").unwrap(),+ StTextDirection::LrTbV+ );+ assert_eq!(+ de::<StTextDirection>("tbRlV").unwrap(),+ StTextDirection::TbRlV+ );+ assert_eq!(+ de::<StTextDirection>("tbLrV").unwrap(),+ StTextDirection::TbLrV+ );+ }+ #[test]+ fn text_direction_strict() {+ assert_bad::<StTextDirection>("ltr");+ }+ #[test]+ fn text_direction_converts_to_model() {+ assert_eq!(+ TextDirection::from(StTextDirection::LrTb),+ TextDirection::LeftToRightTopToBottom+ );+ assert_eq!(+ TextDirection::from(StTextDirection::TbLrV),+ TextDirection::TopToBottomLeftToRightRotated+ );+ }++ // ── StTheme ──+ #[test]+ fn theme_all_variants() {+ assert_eq!(de::<StTheme>("majorHAnsi").unwrap(), StTheme::MajorHAnsi);+ assert_eq!(+ de::<StTheme>("majorEastAsia").unwrap(),+ StTheme::MajorEastAsia+ );+ assert_eq!(de::<StTheme>("majorBidi").unwrap(), StTheme::MajorBidi);+ assert_eq!(de::<StTheme>("minorHAnsi").unwrap(), StTheme::MinorHAnsi);+ assert_eq!(+ de::<StTheme>("minorEastAsia").unwrap(),+ StTheme::MinorEastAsia+ );+ assert_eq!(de::<StTheme>("minorBidi").unwrap(), StTheme::MinorBidi);+ }+ #[test]+ fn theme_strict() {+ assert_bad::<StTheme>("default");+ }++ // ── StUnderline ──+ #[test]+ fn underline_sample_variants() {+ assert_eq!(de::<StUnderline>("none").unwrap(), StUnderline::None);+ assert_eq!(de::<StUnderline>("single").unwrap(), StUnderline::Single);+ assert_eq!(de::<StUnderline>("dotted").unwrap(), StUnderline::Dotted);+ assert_eq!(+ de::<StUnderline>("dashDotHeavy").unwrap(),+ StUnderline::DashDotHeavy+ );+ assert_eq!(+ de::<StUnderline>("wavyDouble").unwrap(),+ StUnderline::WavyDouble+ );+ }+ #[test]+ fn underline_strict() {+ assert_bad::<StUnderline>("italic");+ }++ // ── StVerticalAlignRun ──+ #[test]+ fn vertical_align_run_all_variants() {+ assert_eq!(+ de::<StVerticalAlignRun>("baseline").unwrap(),+ StVerticalAlignRun::Baseline+ );+ assert_eq!(+ de::<StVerticalAlignRun>("superscript").unwrap(),+ StVerticalAlignRun::Superscript+ );+ assert_eq!(+ de::<StVerticalAlignRun>("subscript").unwrap(),+ StVerticalAlignRun::Subscript+ );+ }+ #[test]+ fn vertical_align_run_strict() {+ assert_bad::<StVerticalAlignRun>("middle");+ }++ // ── StVerticalJc ──+ #[test]+ fn vertical_jc_all_variants() {+ assert_eq!(de::<StVerticalJc>("top").unwrap(), StVerticalJc::Top);+ assert_eq!(de::<StVerticalJc>("center").unwrap(), StVerticalJc::Center);+ assert_eq!(de::<StVerticalJc>("bottom").unwrap(), StVerticalJc::Bottom);+ assert_eq!(de::<StVerticalJc>("both").unwrap(), StVerticalJc::Both);+ }+ #[test]+ fn vertical_jc_strict() {+ assert_bad::<StVerticalJc>("start");+ }++ // ── StPTabAlignment ──+ #[test]+ fn ptab_alignment_all_variants() {+ assert_eq!(+ de::<StPTabAlignment>("left").unwrap(),+ StPTabAlignment::Left+ );+ assert_eq!(+ de::<StPTabAlignment>("center").unwrap(),+ StPTabAlignment::Center+ );+ assert_eq!(+ de::<StPTabAlignment>("right").unwrap(),+ StPTabAlignment::Right+ );+ }+ #[test]+ fn ptab_alignment_strict() {+ assert_bad::<StPTabAlignment>("decimal");+ }+ #[test]+ fn ptab_alignment_converts_to_model() {+ let m: PTabAlignment = StPTabAlignment::Center.into();+ assert_eq!(m, PTabAlignment::Center);+ }++ // ── StPTabRelativeTo ──+ #[test]+ fn ptab_relative_to_all_variants() {+ assert_eq!(+ de::<StPTabRelativeTo>("margin").unwrap(),+ StPTabRelativeTo::Margin+ );+ assert_eq!(+ de::<StPTabRelativeTo>("indent").unwrap(),+ StPTabRelativeTo::Indent+ );+ }+ #[test]+ fn ptab_relative_to_strict() {+ assert_bad::<StPTabRelativeTo>("page");+ }++ // ── StPTabLeader ──+ #[test]+ fn ptab_leader_all_variants() {+ assert_eq!(de::<StPTabLeader>("none").unwrap(), StPTabLeader::None);+ assert_eq!(de::<StPTabLeader>("dot").unwrap(), StPTabLeader::Dot);+ assert_eq!(de::<StPTabLeader>("hyphen").unwrap(), StPTabLeader::Hyphen);+ assert_eq!(+ de::<StPTabLeader>("underscore").unwrap(),+ StPTabLeader::Underscore+ );+ assert_eq!(+ de::<StPTabLeader>("middleDot").unwrap(),+ StPTabLeader::MiddleDot+ );+ }+ #[test]+ fn ptab_leader_strict() {+ // `heavy` is a regular tab leader (§17.18.86) but not a ptab leader.+ assert_bad::<StPTabLeader>("heavy");+ }+ #[test]+ fn ptab_leader_converts_to_model() {+ let m: PTabLeader = StPTabLeader::MiddleDot.into();+ assert_eq!(m, PTabLeader::MiddleDot);+ // …and the model leader maps onto the shared TabLeader painter enum.+ let t: TabLeader = m.into();+ assert_eq!(t, TabLeader::MiddleDot);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/primitives/toggles.rs b/crates/liteparse-docx/src/docx/parse/primitives/toggles.rsnew file mode 100644index 0000000..b88f6e0--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/toggles.rs@@ -0,0 +1,114 @@+//! OOXML `ST_OnOff` (§17.18.68) toggle element plus attribute-level booleans.+//!+//! A toggle element without `@val` is "on" by default — the element's+//! presence alone asserts the property. With `@val`, the spec lists+//! `true`/`1`/`on` and `false`/`0`/`off` as the valid values.+//!+//! Per plan §Decisions, `OnOff` is the single spec-driven exception to+//! strict enum handling: unknown `@val` values resolve to `true` rather than+//! failing deserialization, matching legacy Word's tolerant toggle behavior.+//!+//! [`AttrBool`] is the attribute-level counterpart: a plain boolean+//! attribute like `@rotWithShape="1"` that reads as a string and maps+//! `"1"`/`"true"`/`"on"` to `true`, everything else to `false`.++use serde::{Deserialize, Deserializer};++/// Toggle value wrapper. `.0` is the resolved bool.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct OnOff(pub bool);++impl<'de> Deserialize<'de> for OnOff {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ #[derive(Deserialize)]+ struct Raw {+ #[serde(rename = "@val", default)]+ val: Option<String>,+ }+ let raw = Raw::deserialize(d)?;+ let on = match raw.val.as_deref() {+ None => true,+ Some("true" | "1" | "on") => true,+ Some("false" | "0" | "off") => false,+ Some(_) => true,+ };+ Ok(OnOff(on))+ }+}++/// OOXML §17.7.2 — when the same toggle element repeats inside one container,+/// the last occurrence wins. Schema structs collect repeated toggles into a+/// `Vec<OnOff>` (rather than `Option<OnOff>`, which serde rejects as a+/// duplicate field) because third-party writers (notably LibreOffice/AOO) emit+/// redundant duplicates like `<w:b/><w:b/>`. This collapses the list to the+/// final value, or `None` when the toggle is absent so the style cascade can+/// supply an inherited value.+pub(crate) fn last_toggle(toggles: Vec<OnOff>) -> Option<bool> {+ toggles.into_iter().next_back().map(|OnOff(b)| b)+}++/// Attribute-level boolean. Accepts `"1"`, `"true"`, `"on"` as true;+/// anything else (including `"0"`, `"false"`, `"off"`) as false.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct AttrBool(pub bool);++impl<'de> Deserialize<'de> for AttrBool {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ Ok(Self(matches!(s.as_str(), "1" | "true" | "on")))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[derive(Deserialize)]+ struct Toggle {+ #[serde(rename = "flag", default)]+ flag: Option<OnOff>,+ }++ fn flag(xml: &str) -> Option<bool> {+ let t: Toggle = quick_xml::de::from_str(xml).unwrap();+ t.flag.map(|o| o.0)+ }++ #[test]+ fn present_without_val_is_on() {+ assert_eq!(flag(r#"<x><flag/></x>"#), Some(true));+ }++ #[test]+ fn val_true_family_is_on() {+ assert_eq!(flag(r#"<x><flag val="true"/></x>"#), Some(true));+ assert_eq!(flag(r#"<x><flag val="1"/></x>"#), Some(true));+ assert_eq!(flag(r#"<x><flag val="on"/></x>"#), Some(true));+ }++ #[test]+ fn val_false_family_is_off() {+ assert_eq!(flag(r#"<x><flag val="false"/></x>"#), Some(false));+ assert_eq!(flag(r#"<x><flag val="0"/></x>"#), Some(false));+ assert_eq!(flag(r#"<x><flag val="off"/></x>"#), Some(false));+ }++ #[test]+ fn unknown_val_defaults_to_on() {+ assert_eq!(flag(r#"<x><flag val="garbage"/></x>"#), Some(true));+ }++ #[test]+ fn absent_is_none() {+ assert_eq!(flag(r#"<x/>"#), None);+ }++ #[test]+ fn last_toggle_is_last_wins() {+ assert_eq!(last_toggle(vec![]), None);+ assert_eq!(last_toggle(vec![OnOff(true)]), Some(true));+ // §17.7.2: last occurrence wins when a toggle is duplicated.+ assert_eq!(last_toggle(vec![OnOff(true), OnOff(false)]), Some(false));+ assert_eq!(last_toggle(vec![OnOff(false), OnOff(true)]), Some(true));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/primitives/units.rs b/crates/liteparse-docx/src/docx/parse/primitives/units.rsnew file mode 100644index 0000000..6636769--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/primitives/units.rs@@ -0,0 +1,136 @@+//! `Deserialize` for `Dimension<U>`. Makes OOXML numeric attributes with a+//! unit marker (twips, EMU, half-points, etc.) usable directly in schema+//! structs without hand-written wrapper types.++use serde::de::IntoDeserializer;+use serde::de::value::{Error as ValueError, StringDeserializer};+use serde::{Deserialize, Deserializer};++use super::integer_measure::IntegerMeasure;+use crate::model::dimension::{Dimension, Unit};++/// Optional non-negative measurement. A value that is unparseable **or**+/// negative degrades to `None` — "unspecified", so the style cascade supplies+/// the value — rather than failing the document.+///+/// Vendoring divergence from dxpdf, which errors on both. One malformed+/// measurement anywhere in a file should not cost the whole parse; note that+/// upstream's behaviour meant a real document with `w:before="-100"` was+/// unreadable rather than merely imprecise.+pub(crate) fn deserialize_optional_nonnegative_dimension<'de, D, U>(+ deserializer: D,+) -> Result<Option<Dimension<U>>, D::Error>+where+ D: Deserializer<'de>,+ U: Unit,+{+ // Take the raw text first: a failed measurement parse is a value we want+ // to discard, not an error to propagate out of the containing struct.+ let Some(raw) = Option::<String>::deserialize(deserializer)? else {+ return Ok(None);+ };+ let de: StringDeserializer<ValueError> = raw.into_deserializer();+ Ok(IntegerMeasure::deserialize(de)+ .ok()+ .filter(|m| !m.is_negative())+ .map(|m| Dimension::new(m.value())))+}++impl<'de, U: Unit> Deserialize<'de> for Dimension<U> {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Ok(Dimension::new(IntegerMeasure::deserialize(d)?.value()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::{Emu, HalfPoints, Twips};+ use serde::Deserialize;++ #[derive(Deserialize)]+ struct TwipsVal {+ #[serde(rename = "@val")]+ val: Dimension<Twips>,+ }++ #[derive(Deserialize)]+ struct Sample {+ #[serde(rename = "@w")]+ w: Dimension<Emu>,+ #[serde(rename = "@h")]+ h: Dimension<HalfPoints>,+ }++ #[derive(Deserialize)]+ struct OptionalNonnegativeTwips {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ val: Option<Dimension<Twips>>,+ }++ #[test]+ fn twips_attribute_deserializes() {+ let v: TwipsVal = quick_xml::de::from_str(r#"<x val="720"/>"#).unwrap();+ assert_eq!(v.val.raw(), 720);+ }++ #[test]+ fn mixed_unit_attributes() {+ let s: Sample = quick_xml::de::from_str(r#"<ext w="914400" h="400"/>"#).unwrap();+ assert_eq!(s.w.raw(), 914_400);+ assert_eq!(s.h.raw(), 400);+ }++ #[test]+ fn negative_values_preserved() {+ let v: TwipsVal = quick_xml::de::from_str(r#"<x val="-120"/>"#).unwrap();+ assert_eq!(v.val.raw(), -120);+ }++ #[test]+ fn non_integer_rejected() {+ let r: Result<TwipsVal, _> = quick_xml::de::from_str(r#"<x val="abc"/>"#);+ assert!(+ r.is_err(),+ "expected error, got {:?}",+ r.map(|v| v.val.raw())+ );+ }++ /// Upstream rejected these outright, taking the whole document with them.+ /// We degrade to `None` instead — but the original guard still holds: a+ /// negative fraction must never be silently truncated to `0`, which would+ /// masquerade as an explicitly-specified zero rather than "unspecified".+ #[test]+ fn negative_fractions_are_unspecified_for_optional_nonnegative_dimensions() {+ for raw in ["-0.1", "-0.49"] {+ let value: OptionalNonnegativeTwips =+ quick_xml::de::from_str(&format!(r#"<x val="{raw}"/>"#))+ .unwrap_or_else(|e| panic!("{raw:?} must not fail the parse: {e}"));+ assert_eq!(+ value.val.map(|d| d.raw()),+ None,+ "{raw:?} must be unspecified, not coerced"+ );+ }+ }++ /// An unparseable measurement degrades the same way.+ #[test]+ fn unparseable_optional_nonnegative_dimension_is_unspecified() {+ let value: OptionalNonnegativeTwips = quick_xml::de::from_str(r#"<x val="bogusValue"/>"#)+ .expect("a bogus measurement must not fail the parse");+ assert_eq!(value.val.map(|d| d.raw()), None);+ }++ /// Good values still parse — the leniency must not swallow real input.+ #[test]+ fn valid_optional_nonnegative_dimension_still_parses() {+ let value: OptionalNonnegativeTwips = quick_xml::de::from_str(r#"<x val="240"/>"#).unwrap();+ assert_eq!(value.val.map(|d| d.raw()), Some(240));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/mod.rs b/crates/liteparse-docx/src/docx/parse/properties/mod.rsnew file mode 100644index 0000000..eca7816--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/mod.rs@@ -0,0 +1,6 @@+//! OOXML property element schemas: pPr, rPr, tblPr, trPr, tcPr, sectPr.+//!+//! All parsing is serde-based; see [`schema`] for the per-element modules+//! and shared sub-schemas (border, shading, tabs, measure, etc.).++pub mod schema;diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/border.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/border.rsnew file mode 100644index 0000000..407378a--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/border.rs@@ -0,0 +1,260 @@+//! Border sub-schemas (§17.3.4 pBdr, §17.4.39 tblBorders, §17.4.66 tcBorders).+//!+//! `BorderXml` matches a single `<w:top>`/`<w:bottom>`/etc. element. The+//! container structs (paragraph / table / table-cell borders) share the same+//! inner `BorderXml` but differ in which sides are allowed. Each container+//! accepts both modern (`start`/`end`) and legacy (`left`/`right`) side+//! names per OOXML bidi handling.++use serde::Deserialize;++use crate::docx::model::dimension::{Dimension, EighthPoints, Points};+use crate::docx::model::{Border, Color, ParagraphBorders, TableBorders, TableCellBorders};+use crate::docx::parse::primitives::HexColor;+use crate::docx::parse::primitives::st_enums::StBorderType;+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++/// A single `<w:top w:val="..." w:sz="..." w:space="..." w:color="..."/>` etc.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct BorderXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ val: StBorderType,+ #[serde(+ rename = "@sz",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ sz: Option<Dimension<EighthPoints>>,+ #[serde(+ rename = "@space",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ space: Option<Dimension<Points>>,+ #[serde(+ rename = "@color",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ color: Option<HexColor>,+}++impl From<BorderXml> for Border {+ fn from(x: BorderXml) -> Self {+ Self {+ style: x.val.into(),+ width: x.sz.unwrap_or_default(),+ space: x.space.unwrap_or_default(),+ color: x.color.map_or(Color::Auto, Into::into),+ }+ }+}++/// `<w:pBdr>` — five sides plus `between`.+#[derive(Clone, Copy, Debug, Default, Deserialize)]+pub(crate) struct ParagraphBordersXml {+ #[serde(default)]+ top: Option<BorderXml>,+ #[serde(default)]+ bottom: Option<BorderXml>,+ #[serde(default, alias = "start")]+ left: Option<BorderXml>,+ #[serde(default, alias = "end")]+ right: Option<BorderXml>,+ #[serde(default)]+ between: Option<BorderXml>,+}++impl From<ParagraphBordersXml> for ParagraphBorders {+ fn from(x: ParagraphBordersXml) -> Self {+ Self {+ top: x.top.map(Into::into),+ bottom: x.bottom.map(Into::into),+ left: x.left.map(Into::into),+ right: x.right.map(Into::into),+ between: x.between.map(Into::into),+ }+ }+}++/// `<w:tblBorders>` — six sides (adds `insideH`, `insideV`).+#[derive(Clone, Copy, Debug, Default, Deserialize)]+pub(crate) struct TableBordersXml {+ #[serde(default)]+ top: Option<BorderXml>,+ #[serde(default)]+ bottom: Option<BorderXml>,+ #[serde(default, alias = "start")]+ left: Option<BorderXml>,+ #[serde(default, alias = "end")]+ right: Option<BorderXml>,+ #[serde(rename = "insideH", default)]+ inside_h: Option<BorderXml>,+ #[serde(rename = "insideV", default)]+ inside_v: Option<BorderXml>,+}++impl From<TableBordersXml> for TableBorders {+ fn from(x: TableBordersXml) -> Self {+ Self {+ top: x.top.map(Into::into),+ bottom: x.bottom.map(Into::into),+ left: x.left.map(Into::into),+ right: x.right.map(Into::into),+ inside_h: x.inside_h.map(Into::into),+ inside_v: x.inside_v.map(Into::into),+ }+ }+}++/// `<w:tcBorders>` — eight sides (adds diagonal `tl2br`, `tr2bl`).+#[derive(Clone, Copy, Debug, Default, Deserialize)]+pub(crate) struct TableCellBordersXml {+ #[serde(default)]+ top: Option<BorderXml>,+ #[serde(default)]+ bottom: Option<BorderXml>,+ #[serde(default, alias = "start")]+ left: Option<BorderXml>,+ #[serde(default, alias = "end")]+ right: Option<BorderXml>,+ #[serde(rename = "insideH", default)]+ inside_h: Option<BorderXml>,+ #[serde(rename = "insideV", default)]+ inside_v: Option<BorderXml>,+ #[serde(rename = "tl2br", default)]+ tl2br: Option<BorderXml>,+ #[serde(rename = "tr2bl", default)]+ tr2bl: Option<BorderXml>,+}++impl From<TableCellBordersXml> for TableCellBorders {+ fn from(x: TableCellBordersXml) -> Self {+ Self {+ top: x.top.map(Into::into),+ bottom: x.bottom.map(Into::into),+ left: x.left.map(Into::into),+ right: x.right.map(Into::into),+ inside_h: x.inside_h.map(Into::into),+ inside_v: x.inside_v.map(Into::into),+ tl2br: x.tl2br.map(Into::into),+ tr2bl: x.tr2bl.map(Into::into),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn single_border_with_all_attrs() {+ let xml = r#"<top val="single" sz="4" space="0" color="FF0000"/>"#;+ let b: BorderXml = quick_xml::de::from_str(xml).unwrap();+ let m: Border = b.into();+ assert_eq!(m.style, crate::docx::model::BorderStyle::Single);+ assert_eq!(m.width.raw(), 4);+ assert_eq!(m.space.raw(), 0);+ assert_eq!(m.color, Color::Rgb(0xFF0000));+ }++ #[test]+ fn border_with_auto_color() {+ let xml = r#"<top val="single" color="auto"/>"#;+ let b: BorderXml = quick_xml::de::from_str(xml).unwrap();+ let m: Border = b.into();+ assert_eq!(m.color, Color::Auto);+ }++ /// §17.18.2 ST_Border: `nil` and `none` both mean "no border", but they+ /// are **not** merged. [MS-OI29500] §17.4.66 separates them in table border+ /// conflict resolution — `nil` suppresses the shared edge, `none` inherits+ /// and yields — so the distinction has to survive parsing. The cascade sees+ /// `Some(Border)` either way, so an explicit child can still override an+ /// inherited side.+ #[test]+ fn border_val_nil_and_none_stay_distinct() {+ let nil: Border = quick_xml::de::from_str::<BorderXml>(r#"<top val="nil"/>"#)+ .unwrap()+ .into();+ let none: Border = quick_xml::de::from_str::<BorderXml>(r#"<top val="none"/>"#)+ .unwrap()+ .into();+ assert_eq!(nil.style, crate::docx::model::BorderStyle::Nil);+ assert_eq!(none.style, crate::docx::model::BorderStyle::None);+ assert_ne!(nil.style, none.style, "merging these loses §17.4.66");+ // Both still paint nothing — only conflict resolution tells them apart.+ assert!(nil.style.draws_nothing() && none.style.draws_nothing());+ }++ #[test]+ fn paragraph_borders_all_nil_preserves_some_per_side() {+ // Word emits this in pPrDefault. Each side must round-trip as+ // `Some(Border { style: Nil })`, not as the parent `pBdr` being+ // None — the merge cascade needs the explicit override.+ let xml = r#"<pBdr>+ <top val="nil"/>+ <left val="nil"/>+ <bottom val="nil"/>+ <right val="nil"/>+ <between val="nil"/>+ <bar val="nil"/>+ </pBdr>"#;+ let px: ParagraphBordersXml = quick_xml::de::from_str(xml).unwrap();+ let p: ParagraphBorders = px.into();+ assert!(p.top.is_some());+ assert_eq!(p.top.unwrap().style, crate::docx::model::BorderStyle::Nil);+ assert!(p.bottom.is_some());+ assert!(p.left.is_some());+ assert!(p.right.is_some());+ }++ #[test]+ fn paragraph_borders_aliases_start_left() {+ let xml = r#"<pBdr>+ <top val="single"/>+ <start val="double"/>+ <end val="thick"/>+ </pBdr>"#;+ let px: ParagraphBordersXml = quick_xml::de::from_str(xml).unwrap();+ let p: ParagraphBorders = px.into();+ assert!(p.top.is_some());+ assert_eq!(+ p.left.unwrap().style,+ crate::docx::model::BorderStyle::Double+ );+ assert_eq!(+ p.right.unwrap().style,+ crate::docx::model::BorderStyle::Thick+ );+ }++ #[test]+ fn table_borders_inside_pair() {+ let xml = r#"<tblBorders>+ <insideH val="single"/>+ <insideV val="dashed"/>+ </tblBorders>"#;+ let tx: TableBordersXml = quick_xml::de::from_str(xml).unwrap();+ let t: TableBorders = tx.into();+ assert!(t.inside_h.is_some());+ assert!(t.inside_v.is_some());+ assert!(t.top.is_none());+ }++ #[test]+ fn cell_borders_diagonals() {+ let xml = r#"<tcBorders>+ <tl2br val="single"/>+ <tr2bl val="dotted"/>+ </tcBorders>"#;+ let cx: TableCellBordersXml = quick_xml::de::from_str(xml).unwrap();+ let c: TableCellBorders = cx.into();+ assert!(c.tl2br.is_some());+ assert!(c.tr2bl.is_some());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/cnf_style.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/cnf_style.rsnew file mode 100644index 0000000..3a43f22--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/cnf_style.rs@@ -0,0 +1,166 @@+//! `<w:cnfStyle>` (§17.3.1.8) — conditional formatting flags for table cells+//! and paragraphs inside tables.+//!+//! Two wire encodings are supported per spec:+//!+//! 1. **Binary string on `@val`** — a 12-character `0`/`1` string, MSB-first,+//! matching the `CnfStyle` bitflag order (first_row, last_row, …).+//! 2. **Individual boolean attributes** — `@firstRow="1"`, `@oddHBand="true"`,+//! etc. These are merged on top of the `@val` bitmask (if both are present).++use serde::Deserialize;++use crate::docx::model::CnfStyle;++#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct CnfStyleXml {+ #[serde(rename = "@val", default)]+ val: Option<String>,+ #[serde(rename = "@firstRow", default)]+ first_row: Option<OnOffAttr>,+ #[serde(rename = "@lastRow", default)]+ last_row: Option<OnOffAttr>,+ #[serde(rename = "@firstColumn", default)]+ first_column: Option<OnOffAttr>,+ #[serde(rename = "@lastColumn", default)]+ last_column: Option<OnOffAttr>,+ #[serde(rename = "@oddVBand", default)]+ odd_v_band: Option<OnOffAttr>,+ #[serde(rename = "@evenVBand", default)]+ even_v_band: Option<OnOffAttr>,+ #[serde(rename = "@oddHBand", default)]+ odd_h_band: Option<OnOffAttr>,+ #[serde(rename = "@evenHBand", default)]+ even_h_band: Option<OnOffAttr>,+ #[serde(rename = "@firstRowFirstColumn", default)]+ first_row_first_column: Option<OnOffAttr>,+ #[serde(rename = "@firstRowLastColumn", default)]+ first_row_last_column: Option<OnOffAttr>,+ #[serde(rename = "@lastRowFirstColumn", default)]+ last_row_first_column: Option<OnOffAttr>,+ #[serde(rename = "@lastRowLastColumn", default)]+ last_row_last_column: Option<OnOffAttr>,+}++use crate::docx::parse::primitives::AttrBool as OnOffAttr;++impl From<CnfStyleXml> for CnfStyle {+ fn from(x: CnfStyleXml) -> Self {+ let mut bits = match x.val.as_deref() {+ Some(s) => parse_cnf_val(s),+ None => CnfStyle::empty(),+ };+ set(&mut bits, CnfStyle::FIRST_ROW, x.first_row);+ set(&mut bits, CnfStyle::LAST_ROW, x.last_row);+ set(&mut bits, CnfStyle::FIRST_COLUMN, x.first_column);+ set(&mut bits, CnfStyle::LAST_COLUMN, x.last_column);+ set(&mut bits, CnfStyle::ODD_V_BAND, x.odd_v_band);+ set(&mut bits, CnfStyle::EVEN_V_BAND, x.even_v_band);+ set(&mut bits, CnfStyle::ODD_H_BAND, x.odd_h_band);+ set(&mut bits, CnfStyle::EVEN_H_BAND, x.even_h_band);+ set(+ &mut bits,+ CnfStyle::FIRST_ROW_FIRST_COLUMN,+ x.first_row_first_column,+ );+ set(+ &mut bits,+ CnfStyle::FIRST_ROW_LAST_COLUMN,+ x.first_row_last_column,+ );+ set(+ &mut bits,+ CnfStyle::LAST_ROW_FIRST_COLUMN,+ x.last_row_first_column,+ );+ set(+ &mut bits,+ CnfStyle::LAST_ROW_LAST_COLUMN,+ x.last_row_last_column,+ );+ bits+ }+}++fn set(bits: &mut CnfStyle, flag: CnfStyle, on: Option<OnOffAttr>) {+ if let Some(OnOffAttr(true)) = on {+ bits.insert(flag);+ } else if let Some(OnOffAttr(false)) = on {+ bits.remove(flag);+ }+}++/// Parse a 12-character 0/1 bitstring. Shorter strings pad with zeros;+/// longer strings are truncated. Non-0/1 chars clear the bit.+fn parse_cnf_val(s: &str) -> CnfStyle {+ const ORDER: [CnfStyle; 12] = [+ CnfStyle::FIRST_ROW,+ CnfStyle::LAST_ROW,+ CnfStyle::FIRST_COLUMN,+ CnfStyle::LAST_COLUMN,+ CnfStyle::ODD_V_BAND,+ CnfStyle::EVEN_V_BAND,+ CnfStyle::ODD_H_BAND,+ CnfStyle::EVEN_H_BAND,+ CnfStyle::FIRST_ROW_FIRST_COLUMN,+ CnfStyle::FIRST_ROW_LAST_COLUMN,+ CnfStyle::LAST_ROW_FIRST_COLUMN,+ CnfStyle::LAST_ROW_LAST_COLUMN,+ ];+ let mut out = CnfStyle::empty();+ for (ch, flag) in s.chars().zip(ORDER.iter()) {+ if ch == '1' {+ out.insert(*flag);+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> CnfStyle {+ let x: CnfStyleXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn empty_yields_empty_bits() {+ let c = parse(r#"<cnfStyle val="000000000000"/>"#);+ assert!(c.is_empty());+ }++ #[test]+ fn first_row_only() {+ let c = parse(r#"<cnfStyle val="100000000000"/>"#);+ assert_eq!(c, CnfStyle::FIRST_ROW);+ }++ #[test]+ fn multiple_bits_from_val() {+ let c = parse(r#"<cnfStyle val="101010000000"/>"#);+ assert_eq!(+ c,+ CnfStyle::FIRST_ROW | CnfStyle::FIRST_COLUMN | CnfStyle::ODD_V_BAND+ );+ }++ #[test]+ fn individual_attrs_override_val() {+ let c = parse(r#"<cnfStyle val="000000000000" firstRow="1" oddHBand="true"/>"#);+ assert_eq!(c, CnfStyle::FIRST_ROW | CnfStyle::ODD_H_BAND);+ }++ #[test]+ fn short_val_pads_with_zero() {+ let c = parse(r#"<cnfStyle val="11"/>"#);+ assert_eq!(c, CnfStyle::FIRST_ROW | CnfStyle::LAST_ROW);+ }++ #[test]+ fn no_val_no_attrs_is_empty() {+ let c = parse(r#"<cnfStyle/>"#);+ assert!(c.is_empty());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/fonts.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/fonts.rsnew file mode 100644index 0000000..747e4e5--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/fonts.rs@@ -0,0 +1,111 @@+//! `<w:rFonts>` (§17.3.2.26) — four font slots, each with explicit-name and+//! theme-reference attributes. Splits into a `FontSet` model.++use serde::Deserialize;++use crate::docx::model::{FontSet, FontSlot};+use crate::docx::parse::primitives::st_enums::StTheme;++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct RFontsXml {+ #[serde(rename = "@ascii", default)]+ ascii: Option<String>,+ #[serde(+ rename = "@asciiTheme",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ ascii_theme: Option<StTheme>,+ #[serde(rename = "@hAnsi", default)]+ h_ansi: Option<String>,+ #[serde(+ rename = "@hAnsiTheme",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ h_ansi_theme: Option<StTheme>,+ #[serde(rename = "@eastAsia", default)]+ east_asia: Option<String>,+ #[serde(+ rename = "@eastAsiaTheme",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ east_asia_theme: Option<StTheme>,+ #[serde(rename = "@cs", default)]+ cs: Option<String>,+ #[serde(+ rename = "@cstheme",+ alias = "@csTheme",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ cs_theme: Option<StTheme>,+}++impl From<RFontsXml> for FontSet {+ fn from(x: RFontsXml) -> Self {+ Self {+ ascii: FontSlot {+ explicit: x.ascii,+ theme: x.ascii_theme.map(Into::into),+ },+ high_ansi: FontSlot {+ explicit: x.h_ansi,+ theme: x.h_ansi_theme.map(Into::into),+ },+ east_asian: FontSlot {+ explicit: x.east_asia,+ theme: x.east_asia_theme.map(Into::into),+ },+ complex_script: FontSlot {+ explicit: x.cs,+ theme: x.cs_theme.map(Into::into),+ },+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::ThemeFontRef;++ fn parse(xml: &str) -> FontSet {+ let x: RFontsXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn explicit_names() {+ let f = parse(r#"<rFonts ascii="Calibri" hAnsi="Calibri" eastAsia="SimSun" cs="Arial"/>"#);+ assert_eq!(f.ascii.explicit.as_deref(), Some("Calibri"));+ assert_eq!(f.high_ansi.explicit.as_deref(), Some("Calibri"));+ assert_eq!(f.east_asian.explicit.as_deref(), Some("SimSun"));+ assert_eq!(f.complex_script.explicit.as_deref(), Some("Arial"));+ }++ #[test]+ fn theme_refs() {+ let f = parse(+ r#"<rFonts asciiTheme="minorHAnsi" hAnsiTheme="minorHAnsi" eastAsiaTheme="minorEastAsia"/>"#,+ );+ assert_eq!(f.ascii.theme, Some(ThemeFontRef::MinorHAnsi));+ assert_eq!(f.east_asian.theme, Some(ThemeFontRef::MinorEastAsia));+ }++ #[test]+ fn cs_theme_accepts_legacy_and_modern_case() {+ let f = parse(r#"<rFonts cstheme="minorBidi"/>"#);+ assert_eq!(f.complex_script.theme, Some(ThemeFontRef::MinorBidi));++ let f = parse(r#"<rFonts csTheme="minorBidi"/>"#);+ assert_eq!(f.complex_script.theme, Some(ThemeFontRef::MinorBidi));+ }++ #[test]+ fn missing_attrs_become_empty_slots() {+ let f = parse(r#"<rFonts/>"#);+ assert!(f.ascii.explicit.is_none() && f.ascii.theme.is_none());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/insets.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/insets.rsnew file mode 100644index 0000000..adf17c7--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/insets.rs@@ -0,0 +1,187 @@+//! Edge insets (§17.4.42 tcMar, §17.4.44 tblCellMar) — four-sided twips+//! padding shared by table-cell margins and table default cell margins.+//!+//! Each side is `<w:top w:w="N" w:type="dxa"/>` etc. Only `dxa` (twips) is+//! meaningful for cell padding; other `@type` values are ignored here.++use serde::Deserialize;++use crate::docx::model::dimension::{Dimension, Twips};+use crate::docx::model::geometry::{EdgeInsets, PartialEdgeInsets};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++#[derive(Clone, Copy, Debug, Default, Deserialize)]+pub(crate) struct EdgeInsetsTwipsXml {+ #[serde(default)]+ top: Option<SideXml>,+ #[serde(default)]+ bottom: Option<SideXml>,+ #[serde(default, alias = "start")]+ left: Option<SideXml>,+ #[serde(default, alias = "end")]+ right: Option<SideXml>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+struct SideXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ w: Option<Dimension<Twips>>,+}++/// Conversion used for the table-level default (`<w:tblCellMar>`). Per+/// OOXML §17.4.44 a table default has no further inheritance, so missing+/// sides collapse to zero.+impl From<EdgeInsetsTwipsXml> for EdgeInsets<Twips> {+ fn from(x: EdgeInsetsTwipsXml) -> Self {+ Self::new(+ x.top.and_then(|s| s.w).unwrap_or_default(),+ x.right.and_then(|s| s.w).unwrap_or_default(),+ x.bottom.and_then(|s| s.w).unwrap_or_default(),+ x.left.and_then(|s| s.w).unwrap_or_default(),+ )+ }+}++/// Conversion used for per-cell overrides (`<w:tcMar>`, §17.4.42). Each+/// child element (`<w:top>` §17.4.81, `<w:start>` §17.4.71, `<w:bottom>`+/// §17.4.7, `<w:end>` §17.4.13) is an *exception* that overrides the+/// corresponding side of the parent `<w:tblCellMar>` (§17.4.44).+///+/// Per the spec, cascade is per-side: a side whose element is structurally+/// absent inherits from the parent; a side whose element is present is an+/// explicit override, including `<w:top w:w="0" w:type="dxa"/>` which is+/// `CT_TblWidth` (§17.18.87) for "0 twips" — an explicit zero, not a+/// placeholder for "no override". The layout layer resolves the partial+/// override against the table-level default via+/// [`PartialEdgeInsets::resolve_against`].+impl From<EdgeInsetsTwipsXml> for PartialEdgeInsets<Twips> {+ fn from(x: EdgeInsetsTwipsXml) -> Self {+ Self::new(+ x.top.and_then(|s| s.w),+ x.right.and_then(|s| s.w),+ x.bottom.and_then(|s| s.w),+ x.left.and_then(|s| s.w),+ )+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> EdgeInsets<Twips> {+ let x: EdgeInsetsTwipsXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn all_four_sides_captured() {+ let e = parse(+ r#"<tcMar>+ <top w="100"/>+ <bottom w="200"/>+ <left w="50"/>+ <right w="75"/>+ </tcMar>"#,+ );+ assert_eq!(e.top.raw(), 100);+ assert_eq!(e.bottom.raw(), 200);+ assert_eq!(e.left.raw(), 50);+ assert_eq!(e.right.raw(), 75);+ }++ #[test]+ fn start_and_end_alias_left_right() {+ let e = parse(+ r#"<tcMar>+ <start w="80"/>+ <end w="120"/>+ </tcMar>"#,+ );+ assert_eq!(e.left.raw(), 80);+ assert_eq!(e.right.raw(), 120);+ }++ #[test]+ fn missing_sides_default_to_zero() {+ let e = parse(r#"<tcMar><top w="100"/></tcMar>"#);+ assert_eq!(e.top.raw(), 100);+ assert_eq!(e.right.raw(), 0);+ assert_eq!(e.bottom.raw(), 0);+ assert_eq!(e.left.raw(), 0);+ }++ /// Per OOXML §17.4.42, an absent child element in `<w:tcMar>` means+ /// "inherit from `<w:tblCellMar>` for that side". Only the sides+ /// structurally present in the XML are an override; the rest stay `None`+ /// so the layout cascade can fall back to the table-level default.+ #[test]+ fn partial_tcmar_preserves_absent_sides_as_none() {+ let xml = r#"<tcMar>+ <top w="40"/>+ </tcMar>"#;+ let parsed: EdgeInsetsTwipsXml = quick_xml::de::from_str(xml).unwrap();+ let p: PartialEdgeInsets<Twips> = parsed.into();+ assert_eq!(p.top.map(|d| d.raw()), Some(40));+ assert!(p.bottom.is_none(), "absent <w:bottom> must stay None");+ assert!(p.left.is_none(), "absent <w:start>/<w:left> must stay None");+ assert!(p.right.is_none(), "absent <w:end>/<w:right> must stay None");++ let default = EdgeInsets::<Twips>::new(+ Dimension::new(57),+ Dimension::new(108),+ Dimension::new(57),+ Dimension::new(103),+ );+ let resolved = p.resolve_against(default);+ assert_eq!(resolved.top.raw(), 40, "explicit override wins");+ assert_eq!(resolved.bottom.raw(), 57, "absent side inherits");+ assert_eq!(resolved.left.raw(), 103, "absent side inherits");+ assert_eq!(resolved.right.raw(), 108, "absent side inherits");+ }++ /// Per OOXML §17.18.87 (`CT_TblWidth`), `@type="dxa" @w="0"` is+ /// "0 twentieths of a point", i.e. an explicit zero. Combined with+ /// §17.4.42's "exception" semantics, a `<w:top w:w="0" w:type="dxa"/>`+ /// inside `<w:tcMar>` is an *explicit override* to zero, structurally+ /// distinct from an absent child element. This test pins the spec-+ /// faithful interpretation: the parser must report `Some(0)`, not `None`.+ ///+ /// (Word/LibreOffice may render such cells with the table-default+ /// padding regardless — that is a rendering quirk in those products+ /// and not something the parser may silently impose; emulating it+ /// belongs in the layout layer behind an explicit, named code path.)+ #[test]+ fn partial_tcmar_w_zero_is_explicit_zero_override() {+ let xml = r#"<tcMar>+ <top w="0"/>+ <bottom w="0"/>+ </tcMar>"#;+ let parsed: EdgeInsetsTwipsXml = quick_xml::de::from_str(xml).unwrap();+ let p: PartialEdgeInsets<Twips> = parsed.into();+ assert_eq!(+ p.top.map(|d| d.raw()),+ Some(0),+ "w=0 must be preserved as explicit Some(0), not silently dropped"+ );+ assert_eq!(p.bottom.map(|d| d.raw()), Some(0));+ assert!(p.left.is_none());+ assert!(p.right.is_none());++ let default = EdgeInsets::<Twips>::new(+ Dimension::new(57),+ Dimension::new(108),+ Dimension::new(57),+ Dimension::new(103),+ );+ let resolved = p.resolve_against(default);+ assert_eq!(resolved.top.raw(), 0, "explicit zero overrides default");+ assert_eq!(resolved.bottom.raw(), 0, "explicit zero overrides default");+ assert_eq!(resolved.left.raw(), 103, "absent side inherits default");+ assert_eq!(resolved.right.raw(), 108, "absent side inherits default");+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/lang.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/lang.rsnew file mode 100644index 0000000..1eb6ecc--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/lang.rs@@ -0,0 +1,49 @@+//! Language sub-schema (§17.3.2.20 w:lang) — tri-mode language tag.++use serde::Deserialize;++use crate::docx::model::Lang;++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct LangXml {+ #[serde(rename = "@val", default)]+ val: Option<String>,+ #[serde(rename = "@eastAsia", default)]+ east_asia: Option<String>,+ #[serde(rename = "@bidi", default)]+ bidi: Option<String>,+}++impl From<LangXml> for Lang {+ fn from(x: LangXml) -> Self {+ Self {+ val: x.val,+ east_asia: x.east_asia,+ bidi: x.bidi,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn parse(xml: &str) -> Lang {+ let x: LangXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn all_three_modes() {+ let l = parse(r#"<lang val="en-US" eastAsia="ja-JP" bidi="ar-SA"/>"#);+ assert_eq!(l.val.as_deref(), Some("en-US"));+ assert_eq!(l.east_asia.as_deref(), Some("ja-JP"));+ assert_eq!(l.bidi.as_deref(), Some("ar-SA"));+ }++ #[test]+ fn missing_attrs_become_none() {+ let l = parse(r#"<lang/>"#);+ assert!(l.val.is_none() && l.east_asia.is_none() && l.bidi.is_none());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/measure.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/measure.rsnew file mode 100644index 0000000..4d3815d--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/measure.rs@@ -0,0 +1,161 @@+//! Table measure (§17.18.87 ST_TblWidth) — a discriminated width value used+//! by `<w:tblW>`, `<w:tcW>`, `<w:tblInd>`, `<w:tblCellSpacing>`, `<w:wAfter>`.+//!+//! `@type` picks the interpretation of `@w`:+//! - `dxa` → twips+//! - `pct` → percentage (stored as thousandths-of-percent)+//! - `auto` / `nil` → no explicit value++use serde::Deserialize;++use crate::docx::model::TableMeasure;+use crate::docx::model::dimension::{Dimension, ThousandthPercent};+use crate::docx::parse::primitives::integer_measure::IntegerMeasure;++#[derive(Clone, Copy, Debug, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+enum StTblWidthType {+ #[default]+ Auto,+ Dxa,+ Nil,+ Pct,+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct TableMeasureXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ w: Option<IntegerMeasure>,+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ ty: StTblWidthType,+}++impl From<TableMeasureXml> for TableMeasure {+ fn from(x: TableMeasureXml) -> Self {+ let value = x.w.map(IntegerMeasure::value).unwrap_or(0);+ match x.ty {+ StTblWidthType::Auto => Self::Auto,+ StTblWidthType::Nil => Self::Nil,+ StTblWidthType::Dxa => Self::Twips(Dimension::new(value)),+ StTblWidthType::Pct => Self::Pct(Dimension::<ThousandthPercent>::new(value)),+ }+ }+}++pub(crate) fn deserialize_optional_nonnegative_table_measure<'de, D>(+ deserializer: D,+) -> Result<Option<TableMeasureXml>, D::Error>+where+ D: serde::Deserializer<'de>,+{+ let measure = Option::<TableMeasureXml>::deserialize(deserializer)?;+ // A negative width is dropped to "unspecified" rather than failing the+ // document; the `@type` still describes how an inherited width applies.+ Ok(measure.map(|mut value| {+ if value.w.as_ref().is_some_and(IntegerMeasure::is_negative) {+ value.w = None;+ }+ value+ }))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[derive(Deserialize)]+ struct NonnegativeTableMeasure {+ #[serde(+ rename = "tblW",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ value: Option<TableMeasureXml>,+ }++ fn parse(xml: &str) -> TableMeasure {+ let x: TableMeasureXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn dxa_twips() {+ match parse(r#"<tblW w="5000" type="dxa"/>"#) {+ TableMeasure::Twips(d) => assert_eq!(d.raw(), 5000),+ other => panic!("expected Twips, got {other:?}"),+ }+ }++ #[test]+ fn pct_thousandth_percent() {+ match parse(r#"<tblW w="2500" type="pct"/>"#) {+ TableMeasure::Pct(d) => assert_eq!(d.raw(), 2500),+ other => panic!("expected Pct, got {other:?}"),+ }+ }++ #[test]+ fn auto_and_nil() {+ assert!(matches!(+ parse(r#"<tblW w="0" type="auto"/>"#),+ TableMeasure::Auto+ ));+ assert!(matches!(+ parse(r#"<tblW w="0" type="nil"/>"#),+ TableMeasure::Nil+ ));+ }++ #[test]+ fn missing_type_defaults_to_auto() {+ assert!(matches!(parse(r#"<tblW/>"#), TableMeasure::Auto));+ }++ #[test]+ fn decimal_widths_round_to_nearest_integer() {+ match parse(r#"<tblW w="2500.4" type="dxa"/>"#) {+ TableMeasure::Twips(d) => assert_eq!(d.raw(), 2500),+ other => panic!("expected Twips, got {other:?}"),+ }+ match parse(r#"<tblW w="2500.5" type="dxa"/>"#) {+ TableMeasure::Twips(d) => assert_eq!(d.raw(), 2501),+ other => panic!("expected Twips, got {other:?}"),+ }+ }++ #[test]+ /// Upstream failed the document on a negative width. We drop the width to+ /// "unspecified" instead — but the guard still holds: it must never be+ /// truncated into a real `Twips(0)`-style width that overrides inheritance.+ fn negative_fractions_are_unspecified_for_table_measurements() {+ for raw in ["-0.1", "-0.49"] {+ let parsed: NonnegativeTableMeasure =+ quick_xml::de::from_str(&format!(r#"<x><tblW w="{raw}" type="dxa"/></x>"#))+ .unwrap_or_else(|e| panic!("{raw:?} must not fail the parse: {e}"));+ assert_eq!(+ parsed.value.map(TableMeasure::from),+ Some(TableMeasure::Twips(Dimension::new(0))),+ "{raw:?} must not carry a negative width"+ );+ }+ }++ /// A valid width still parses.+ #[test]+ fn valid_table_measure_still_parses() {+ let parsed: NonnegativeTableMeasure =+ quick_xml::de::from_str(r#"<x><tblW w="5000" type="dxa"/></x>"#).unwrap();+ assert_eq!(+ parsed.value.map(TableMeasure::from),+ Some(TableMeasure::Twips(Dimension::new(5000)))+ );+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/mod.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/mod.rsnew file mode 100644index 0000000..6f07976--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/mod.rs@@ -0,0 +1,27 @@+//! Serde schema types for OOXML property elements.+//!+//! Schema types carry the `Xml` suffix and are `pub(crate)` — never exported+//! from `docx::`. They mirror OOXML grammar; `From<_Xml> for ModelType`+//! conversions live alongside each schema.+//!+//! During Phase 2 these coexist with the legacy event-driven parsers in+//! `parse/properties/*.rs`. Phase 4 (body) completes the migration by+//! consuming these schemas directly and retiring the legacy parsers. Until+//! then, the module is dead code to cargo; the allow attribute below+//! suppresses the warning — every struct is reachable via `From` impls and+//! tested in-module.++#![allow(dead_code)]++pub mod border;+pub mod cnf_style;+pub mod fonts;+pub mod insets;+pub mod lang;+pub mod measure;+pub mod paragraph;+pub mod run;+pub mod section;+pub mod shading;+pub mod table;+pub mod tabs;diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/paragraph.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/paragraph.rsnew file mode 100644index 0000000..8cb769a--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/paragraph.rs@@ -0,0 +1,633 @@+//! `<w:pPr>` schema (§17.3.1 paragraph properties).+//!+//! Entry point: `PPrXml::split()` returns `ParsedParagraphProperties` —+//! direct formatting, style id, mark-run properties, and an optional+//! nested `<w:sectPr>` (§17.6.18 "last-paragraph-of-section" marker).++use serde::Deserialize;++use crate::docx::model::dimension::{Dimension, Twips};+use crate::docx::model::{+ Alignment, CnfStyle, DropCap, FirstLineIndent, FrameKind, FrameWrap, HeightRule, Indentation,+ LineSpacing, NumberingReference, OutlineLevel, ParagraphBorders, ParagraphProperties,+ ParagraphSpacing, RunProperties, Shading, StyleId, TabStop, TextAlignment, TextBoxPositioning,+};+use crate::docx::parse::primitives::st_enums::{+ StAnchor, StFrameWrap, StHeightRule, StJc, StLineSpacingRule, StTextAlignment, StXAlign,+ StYAlign,+};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;+use crate::docx::parse::primitives::{OnOff, last_toggle};++use super::border::ParagraphBordersXml;+use super::cnf_style::CnfStyleXml;+use super::run::RPrXml;+use super::section::SectPrXml;+use super::shading::ShdXml;+use super::tabs::TabsXml;++/// All the artifacts produced by deserializing a `<w:pPr>`. The split+/// mirrors the legacy `ParsedParagraphProperties` so it plugs into the+/// existing resolve pipeline unchanged.+pub(crate) struct ParsedPPr {+ pub properties: ParagraphProperties,+ pub style_id: Option<StyleId>,+ pub run_properties: Option<RunProperties>,+ pub section_properties: Option<crate::docx::model::SectionProperties>,+}++#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct PPrXml {+ #[serde(rename = "pStyle", default)]+ p_style: Option<ValString>,+ #[serde(default)]+ ind: Option<IndXml>,+ #[serde(default)]+ spacing: Option<SpacingXml>,+ #[serde(+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ jc: Option<StJc>,+ #[serde(default)]+ shd: Option<ShdXml>,+ #[serde(+ rename = "outlineLvl",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ outline_lvl: Option<u8>,+ #[serde(rename = "numPr", default)]+ num_pr: Option<NumPrXml>,+ #[serde(default)]+ tabs: Option<TabsXml>,+ #[serde(rename = "pBdr", default)]+ p_bdr: Option<ParagraphBordersXml>,+ #[serde(rename = "rPr", default)]+ r_pr: Option<RPrXml>,+ #[serde(rename = "sectPr", default)]+ sect_pr: Option<SectPrXml>,+ #[serde(+ rename = "textAlignment",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ text_alignment: Option<StTextAlignment>,+ #[serde(rename = "cnfStyle", default)]+ cnf_style: Option<CnfStyleXml>,+ #[serde(rename = "framePr", default)]+ frame_pr: Option<FramePrXml>,++ // OnOff toggles. Typed as `Vec<OnOff>` (not `Option<OnOff>`) so a duplicated+ // toggle — which LibreOffice/AOO emit, e.g. `<w:keepNext/><w:keepNext/>` —+ // doesn't trip serde's "duplicate field" error and fail the whole parse.+ // §17.7.2 last-wins is applied via `last_toggle` in `split`. Same rationale+ // as `RPrXml`'s run toggles.+ #[serde(rename = "keepNext", default)]+ keep_next: Vec<OnOff>,+ #[serde(rename = "keepLines", default)]+ keep_lines: Vec<OnOff>,+ #[serde(rename = "widowControl", default)]+ widow_control: Vec<OnOff>,+ #[serde(rename = "pageBreakBefore", default)]+ page_break_before: Vec<OnOff>,+ #[serde(rename = "suppressAutoHyphens", default)]+ suppress_auto_hyphens: Vec<OnOff>,+ #[serde(rename = "contextualSpacing", default)]+ contextual_spacing: Vec<OnOff>,+ #[serde(default)]+ bidi: Vec<OnOff>,+ #[serde(rename = "wordWrap", default)]+ word_wrap: Vec<OnOff>,+ #[serde(rename = "autoSpaceDE", default)]+ auto_space_de: Vec<OnOff>,+ #[serde(rename = "autoSpaceDN", default)]+ auto_space_dn: Vec<OnOff>,+}++#[derive(Clone, Debug, Deserialize)]+struct ValString {+ #[serde(rename = "@val")]+ val: String,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))]+struct ValAttr<T> {+ #[serde(rename = "@val")]+ val: T,+}++/// `<w:ind>` — indentation. Legacy `@left`/`@right` alias `@start`/`@end`.+/// `@firstLine` and `@hanging` are mutually exclusive; when both present,+/// hanging wins per renderer convention (legacy parser matched this).+#[derive(Clone, Copy, Debug, Deserialize)]+struct IndXml {+ #[serde(+ rename = "@start",+ alias = "@left",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ start: Option<Dimension<Twips>>,+ #[serde(+ rename = "@end",+ alias = "@right",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ end: Option<Dimension<Twips>>,+ #[serde(+ rename = "@firstLine",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ first_line: Option<Dimension<Twips>>,+ #[serde(+ rename = "@hanging",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ hanging: Option<Dimension<Twips>>,+ #[serde(rename = "@mirrorIndents", default)]+ mirror: Option<AttrBool>,+}++impl From<IndXml> for Indentation {+ fn from(x: IndXml) -> Self {+ let first_line = match (x.first_line, x.hanging) {+ (_, Some(h)) => Some(FirstLineIndent::Hanging(h)),+ (Some(f), None) => Some(FirstLineIndent::FirstLine(f)),+ (None, None) => None,+ };+ Self {+ start: x.start,+ end: x.end,+ first_line,+ mirror: x.mirror.map(|b| b.0),+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+struct SpacingXml {+ #[serde(+ rename = "@before",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ before: Option<Dimension<Twips>>,+ #[serde(+ rename = "@after",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ after: Option<Dimension<Twips>>,+ #[serde(+ rename = "@line",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ line: Option<Dimension<Twips>>,+ #[serde(+ rename = "@lineRule",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ line_rule: Option<StLineSpacingRule>,+ #[serde(rename = "@beforeAutospacing", default)]+ before_auto: Option<AttrBool>,+ #[serde(rename = "@afterAutospacing", default)]+ after_auto: Option<AttrBool>,+}++impl From<SpacingXml> for ParagraphSpacing {+ fn from(x: SpacingXml) -> Self {+ let line = x+ .line+ .map(|v| match x.line_rule.unwrap_or(StLineSpacingRule::Auto) {+ StLineSpacingRule::Auto => LineSpacing::Auto(v),+ StLineSpacingRule::Exact => LineSpacing::Exact(v),+ StLineSpacingRule::AtLeast => LineSpacing::AtLeast(v),+ });+ Self {+ before: x.before,+ after: x.after,+ line,+ before_auto_spacing: x.before_auto.map(|b| b.0),+ after_auto_spacing: x.after_auto.map(|b| b.0),+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+struct NumPrXml {+ #[serde(+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ ilvl: Option<u8>,+ #[serde(+ rename = "numId",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ num_id: Option<i64>,+}++/// `<w:framePr>` — legacy frame positioning. Splits by `@dropCap`:+/// `drop`/`margin` → `FrameKind::DropCap`; absent or `none` → `TextBox`.+#[derive(Clone, Copy, Debug, Deserialize)]+struct FramePrXml {+ #[serde(+ rename = "@dropCap",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ drop_cap: Option<StDropCap>,+ #[serde(+ rename = "@lines",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ lines: Option<u32>,+ #[serde(+ rename = "@hSpace",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ h_space: Option<Dimension<Twips>>,+ #[serde(+ rename = "@vSpace",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ v_space: Option<Dimension<Twips>>,+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ w: Option<Dimension<Twips>>,+ #[serde(+ rename = "@h",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ h: Option<Dimension<Twips>>,+ #[serde(+ rename = "@hRule",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ h_rule: Option<StHeightRule>,+ #[serde(+ rename = "@wrap",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ wrap: Option<StFrameWrap>,+ #[serde(+ rename = "@hAnchor",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ h_anchor: Option<StAnchor>,+ #[serde(+ rename = "@vAnchor",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ v_anchor: Option<StAnchor>,+ #[serde(+ rename = "@x",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ x: Option<Dimension<Twips>>,+ #[serde(+ rename = "@y",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ y: Option<Dimension<Twips>>,+ #[serde(+ rename = "@xAlign",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ x_align: Option<StXAlign>,+ #[serde(+ rename = "@yAlign",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ y_align: Option<StYAlign>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+enum StDropCap {+ None,+ Drop,+ Margin,+}++impl From<FramePrXml> for FrameKind {+ fn from(x: FramePrXml) -> Self {+ match x.drop_cap {+ Some(StDropCap::Drop) => Self::DropCap {+ style: DropCap::Drop,+ lines: x.lines.unwrap_or(3),+ h_space: x.h_space,+ },+ Some(StDropCap::Margin) => Self::DropCap {+ style: DropCap::Margin,+ lines: x.lines.unwrap_or(3),+ h_space: x.h_space,+ },+ Some(StDropCap::None) | None => Self::TextBox(TextBoxPositioning {+ width: x.w,+ height: x.h,+ height_rule: x.h_rule.map(HeightRule::from),+ h_space: x.h_space,+ v_space: x.v_space,+ wrap: x.wrap.map(FrameWrap::from),+ h_anchor: x.h_anchor.map(Into::into),+ v_anchor: x.v_anchor.map(Into::into),+ x: x.x,+ y: x.y,+ x_align: x.x_align.map(Into::into),+ y_align: x.y_align.map(Into::into),+ }),+ }+ }+}++use crate::docx::parse::primitives::AttrBool;++impl PPrXml {+ pub(crate) fn split(self) -> ParsedPPr {+ let style_id = self.p_style.map(|v| StyleId::new(v.val));++ let (run_properties, _run_style_id) = match self.r_pr {+ Some(r) => {+ let (rp, sid) = r.split();+ (Some(rp), sid)+ }+ None => (None, None),+ };+ // rStyle inside pPr/rPr applies to the paragraph mark only; the+ // legacy parser discards this style id too.++ let section_properties = self.sect_pr.map(Into::into);++ let properties = ParagraphProperties {+ alignment: self.jc.map(Alignment::from),+ indentation: self.ind.map(Into::into),+ spacing: self.spacing.map(Into::into),+ numbering: self.num_pr.and_then(numbering_ref),+ tabs: self.tabs.map(<Vec<TabStop>>::from).unwrap_or_default(),+ borders: self.p_bdr.map(ParagraphBorders::from),+ shading: self.shd.map(Shading::from),+ keep_next: last_toggle(self.keep_next),+ keep_lines: last_toggle(self.keep_lines),+ widow_control: last_toggle(self.widow_control),+ page_break_before: last_toggle(self.page_break_before),+ suppress_auto_hyphens: last_toggle(self.suppress_auto_hyphens),+ contextual_spacing: last_toggle(self.contextual_spacing),+ bidi: last_toggle(self.bidi),+ word_wrap: last_toggle(self.word_wrap),+ outline_level: self.outline_lvl.and_then(|v| OutlineLevel::from_ooxml(v)),+ text_alignment: self.text_alignment.map(TextAlignment::from),+ cnf_style: self.cnf_style.map(CnfStyle::from),+ frame_properties: self.frame_pr.map(FrameKind::from),+ auto_space_de: last_toggle(self.auto_space_de),+ auto_space_dn: last_toggle(self.auto_space_dn),+ };++ ParsedPPr {+ properties,+ style_id,+ run_properties,+ section_properties,+ }+ }+}++fn numbering_ref(x: NumPrXml) -> Option<NumberingReference> {+ let num_id = x.num_id?;+ Some(NumberingReference {+ num_id: num_id,+ level: x.ilvl.unwrap_or(0),+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::{Alignment, BorderStyle, DropCap, ShadingPattern, TextAlignment};++ fn parse(xml: &str) -> ParsedPPr {+ let x: PPrXml = quick_xml::de::from_str(xml).unwrap();+ x.split()+ }++ #[test]+ fn empty_pprx_produces_defaults() {+ let r = parse(r#"<pPr/>"#);+ assert_eq!(r.properties.alignment, None);+ assert!(r.style_id.is_none());+ assert!(r.run_properties.is_none());+ assert!(r.section_properties.is_none());+ }++ #[test]+ fn p_style_routed_separately() {+ let r = parse(r#"<pPr><pStyle val="Heading1"/></pPr>"#);+ assert_eq!(+ r.style_id.map(|s| s.as_str().to_string()),+ Some("Heading1".into())+ );+ assert_eq!(r.properties.alignment, None);+ }++ #[test]+ fn direct_formatting_batch() {+ let r = parse(+ r#"<pPr>+ <jc val="both"/>+ <ind start="720" firstLine="360"/>+ <spacing before="120" after="240" line="360" lineRule="auto"/>+ <keepNext/>+ <keepLines val="false"/>+ <outlineLvl val="0"/>+ <textAlignment val="center"/>+ </pPr>"#,+ );+ let p = r.properties;+ assert_eq!(p.alignment, Some(Alignment::Both));+ assert_eq!(p.indentation.unwrap().start.unwrap().raw(), 720);+ match p.indentation.unwrap().first_line {+ Some(FirstLineIndent::FirstLine(d)) => assert_eq!(d.raw(), 360),+ other => panic!("expected FirstLine, got {other:?}"),+ }+ match p.spacing.unwrap().line {+ Some(LineSpacing::Auto(d)) => assert_eq!(d.raw(), 360),+ other => panic!("expected Auto, got {other:?}"),+ }+ assert_eq!(p.keep_next, Some(true));+ assert_eq!(p.keep_lines, Some(false));+ assert_eq!(p.outline_level.map(|o| o.value()), Some(1));+ assert_eq!(p.text_alignment, Some(TextAlignment::Center));+ }++ #[test]+ fn indentation_legacy_left_right_aliases() {+ let r = parse(r#"<pPr><ind left="720" right="360"/></pPr>"#);+ let ind = r.properties.indentation.unwrap();+ assert_eq!(ind.start.unwrap().raw(), 720);+ assert_eq!(ind.end.unwrap().raw(), 360);+ }++ #[test]+ fn negative_decimal_indentation_remains_valid() {+ let r = parse(r#"<pPr><ind start="-1.5"/></pPr>"#);+ assert_eq!(r.properties.indentation.unwrap().start.unwrap().raw(), -2);+ }++ #[test]+ fn num_pr_both_ilvl_and_num_id() {+ let r = parse(r#"<pPr><numPr><ilvl val="2"/><numId val="5"/></numPr></pPr>"#);+ let n = r.properties.numbering.unwrap();+ assert_eq!(n.level, 2);+ assert_eq!(n.num_id, 5);+ }++ #[test]+ fn num_pr_without_num_id_is_none() {+ let r = parse(r#"<pPr><numPr><ilvl val="1"/></numPr></pPr>"#);+ assert!(r.properties.numbering.is_none());+ }++ #[test]+ fn borders_shading_and_tabs() {+ let r = parse(+ r#"<pPr>+ <pBdr><top val="single"/></pBdr>+ <shd val="solid" fill="FFFF00"/>+ <tabs><tab pos="1440" val="center"/></tabs>+ </pPr>"#,+ );+ let p = r.properties;+ assert_eq!(p.borders.unwrap().top.unwrap().style, BorderStyle::Single);+ assert_eq!(p.shading.unwrap().pattern, ShadingPattern::Solid);+ assert_eq!(p.tabs.len(), 1);+ assert_eq!(p.tabs[0].position.raw(), 1440);+ }++ #[test]+ fn mark_run_properties_split_out() {+ let r = parse(r#"<pPr><rPr><b/><color val="FF0000"/></rPr></pPr>"#);+ let rp = r.run_properties.unwrap();+ assert_eq!(rp.bold, Some(true));+ }++ #[test]+ fn nested_sect_pr_routed_separately() {+ let r = parse(r#"<pPr><sectPr><pgSz w="12240" h="15840"/></sectPr></pPr>"#);+ let sp = r.section_properties.unwrap();+ assert_eq!(sp.page_size.unwrap().width.unwrap().raw(), 12240);+ }++ #[test]+ fn frame_pr_drop_cap() {+ let r = parse(r#"<pPr><framePr dropCap="drop" lines="2"/></pPr>"#);+ match r.properties.frame_properties {+ Some(FrameKind::DropCap { style, lines, .. }) => {+ assert_eq!(style, DropCap::Drop);+ assert_eq!(lines, 2);+ }+ other => panic!("expected DropCap, got {other:?}"),+ }+ }++ #[test]+ fn frame_pr_text_box_default() {+ let r = parse(r#"<pPr><framePr w="5000" h="3000" hAnchor="margin"/></pPr>"#);+ match r.properties.frame_properties {+ Some(FrameKind::TextBox(tb)) => {+ assert_eq!(tb.width.unwrap().raw(), 5000);+ assert_eq!(tb.height.unwrap().raw(), 3000);+ }+ other => panic!("expected TextBox, got {other:?}"),+ }+ }++ #[test]+ fn cnf_style_binary_val() {+ let r = parse(r#"<pPr><cnfStyle val="100000000000"/></pPr>"#);+ assert_eq!(r.properties.cnf_style, Some(CnfStyle::FIRST_ROW));+ }++ #[test]+ fn all_ten_toggles() {+ let r = parse(+ r#"<pPr>+ <keepNext/><keepLines/><widowControl/><pageBreakBefore/>+ <suppressAutoHyphens/><contextualSpacing/><bidi/><wordWrap/>+ <autoSpaceDE/><autoSpaceDN/>+ </pPr>"#,+ );+ let p = r.properties;+ assert_eq!(p.keep_next, Some(true));+ assert_eq!(p.keep_lines, Some(true));+ assert_eq!(p.widow_control, Some(true));+ assert_eq!(p.page_break_before, Some(true));+ assert_eq!(p.suppress_auto_hyphens, Some(true));+ assert_eq!(p.contextual_spacing, Some(true));+ assert_eq!(p.bidi, Some(true));+ assert_eq!(p.word_wrap, Some(true));+ assert_eq!(p.auto_space_de, Some(true));+ assert_eq!(p.auto_space_dn, Some(true));+ }++ /// Upstream asserted that an unknown `@val` is a hard error, which meant a+ /// single bad attribute anywhere took down the whole document. We+ /// deliberately reversed that: the alignment is treated as unspecified, so+ /// it inherits from the style chain exactly as if `<w:jc>` were absent.+ #[test]+ fn unknown_jc_is_unspecified_not_an_error() {+ let r = parse(r#"<pPr><jc val="bogus"/></pPr>"#);+ assert_eq!(r.properties.alignment, None);+ }++ /// The leniency must not swallow good input.+ #[test]+ fn known_jc_still_parses() {+ let r = parse(r#"<pPr><jc val="center"/></pPr>"#);+ assert_eq!(r.properties.alignment, Some(Alignment::Center));+ }++ /// The whole point of the change: one bad value must not cost the+ /// surrounding properties.+ #[test]+ fn a_bad_value_does_not_discard_its_siblings() {+ let r = parse(r#"<pPr><jc val="bogus"/><keepNext/></pPr>"#);+ assert_eq!(r.properties.alignment, None);+ assert_eq!(r.properties.keep_next, Some(true));+ }++ #[test]+ fn duplicate_toggles_are_tolerated_last_wins() {+ // LibreOffice/AOO emit redundant duplicate toggles. With `Option<OnOff>`+ // serde would fail with "duplicate field" and take down the whole parse;+ // `Vec<OnOff>` + last_toggle accepts them (§17.7.2 last wins).+ let r = parse(r#"<pPr><keepNext/><keepNext/></pPr>"#);+ assert_eq!(r.properties.keep_next, Some(true));++ // When duplicates disagree, the last one wins.+ let r = parse(r#"<pPr><widowControl val="1"/><widowControl val="0"/></pPr>"#);+ assert_eq!(r.properties.widow_control, Some(false));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/run.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/run.rsnew file mode 100644index 0000000..e8c2752--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/run.rs@@ -0,0 +1,502 @@+//! `<w:rPr>` schema (§17.3.2 run properties).+//!+//! Carries every direct run-formatting element plus the shared sub-schemas+//! from sibling modules. Deserializes to `(RunProperties, Option<StyleId>)`+//! via the `split` method — the style id is routed separately because the+//! property cascade applies it before direct formatting.++use serde::Deserialize;++use crate::docx::model::dimension::{Dimension, HalfPoints, Twips, Unit};+use crate::docx::model::{RunProperties, StrikeStyle, StyleId, TextScale, UnderlineStyle};+use crate::docx::parse::primitives::st_enums::{StHighlightColor, StUnderline, StVerticalAlignRun};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;+use crate::docx::parse::primitives::{HexColor, OnOff, last_toggle};++use super::border::BorderXml;+use super::fonts::RFontsXml;+use super::lang::LangXml;+use super::shading::ShdXml;++/// Schema for the `<w:rPr>` element. All fields optional.+///+/// OnOff toggles are typed as `Vec<OnOff>` rather than `Option<OnOff>` because+/// some third-party DOCX writers (notably LibreOffice/AOO) emit redundant+/// duplicates like `<w:b/><w:b/>` within a single `<w:rPr>`. Word tolerates+/// these via the "last wins" property cascade; the derived `Option<T>`+/// deserializer would reject the second occurrence as a duplicate field and+/// fail otherwise-valid documents. quick-xml + serde natively accumulate+/// repeated XML children into `Vec<T>`, so the derive stays clean and `split`+/// takes the final element per spec semantics.+#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct RPrXml {+ #[serde(rename = "rStyle", default)]+ r_style: Option<ValString>,+ #[serde(rename = "rFonts", default)]+ r_fonts: Option<RFontsXml>,++ #[serde(rename = "sz", default)]+ sz: Option<NonNegativeDimensionVal<HalfPoints>>,+ // Complex-script counterparts are intentionally ignored — renderer uses a single size.+ #[serde(rename = "b", default)]+ b: Vec<OnOff>,+ #[serde(rename = "i", default)]+ i: Vec<OnOff>,+ #[serde(rename = "u", default)]+ u: Option<UnderlineXml>,+ #[serde(rename = "strike", default)]+ strike: Vec<OnOff>,+ #[serde(rename = "dstrike", default)]+ dstrike: Vec<OnOff>,++ #[serde(rename = "color", default)]+ color: Option<ColorXml>,+ #[serde(+ rename = "highlight",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ highlight: Option<StHighlightColor>,+ #[serde(default)]+ shd: Option<ShdXml>,++ #[serde(+ rename = "vertAlign",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ vert_align: Option<StVerticalAlignRun>,++ #[serde(+ rename = "spacing",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ spacing: Option<Dimension<Twips>>,+ #[serde(rename = "kern", default)]+ kern: Option<NonNegativeDimensionVal<HalfPoints>>,+ /// §17.3.2.45 — `<w:w w:val="80"/>`: horizontal character scale in percent.+ #[serde(+ rename = "w",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ char_scale: Option<u16>,++ #[serde(rename = "caps", default)]+ caps: Vec<OnOff>,+ #[serde(rename = "smallCaps", default)]+ small_caps: Vec<OnOff>,+ #[serde(rename = "vanish", default)]+ vanish: Vec<OnOff>,+ #[serde(rename = "noProof", default)]+ no_proof: Vec<OnOff>,+ #[serde(rename = "webHidden", default)]+ web_hidden: Vec<OnOff>,+ #[serde(rename = "rtl", default)]+ rtl: Vec<OnOff>,+ #[serde(rename = "emboss", default)]+ emboss: Vec<OnOff>,+ #[serde(rename = "imprint", default)]+ imprint: Vec<OnOff>,+ #[serde(rename = "outline", default)]+ outline: Vec<OnOff>,+ #[serde(rename = "shadow", default)]+ shadow: Vec<OnOff>,++ #[serde(+ rename = "position",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ position: Option<Dimension<HalfPoints>>,++ #[serde(rename = "lang", default)]+ lang: Option<LangXml>,+ #[serde(rename = "bdr", default)]+ bdr: Option<BorderXml>,+}++/// `<w:u w:val="..."/>` — underline. Unlike other ST-enum wrappers we can't+/// use a bare `ValAttr<StUnderline>` because the attribute is optional; an+/// underline element with no `@val` means "Single" per §17.3.2.40.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct UnderlineXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ val: Option<StUnderline>,+}++/// `<w:color w:val="RRGGBB" ... />` — run color. The spec also allows+/// theme-color fields (`@themeColor`, `@themeTint`, `@themeShade`) which we+/// don't yet resolve — they are currently ignored (only `@val` is read).+#[derive(Clone, Debug, Deserialize)]+pub(crate) struct ColorXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ val: Option<HexColor>,+}++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct ValString {+ #[serde(rename = "@val")]+ val: String,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))]+pub(crate) struct ValAttr<T> {+ #[serde(rename = "@val")]+ val: T,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(bound(deserialize = "U: Unit"))]+struct NonNegativeDimensionVal<U: Unit> {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ val: Option<Dimension<U>>,+}++impl RPrXml {+ /// Split into `(properties, style_id)`. The style id applies first in+ /// the cascade (§17.7.2), so it stays separate from the direct-formatting+ /// `RunProperties`.+ pub(crate) fn split(self) -> (RunProperties, Option<StyleId>) {+ let style_id = self.r_style.map(|v| StyleId::new(v.val));+ let props = RunProperties {+ fonts: self.r_fonts.map(Into::into).unwrap_or_default(),+ font_size: self.sz.and_then(|s| s.val),+ bold: last_toggle(self.b),+ italic: last_toggle(self.i),+ underline: self.u.and_then(resolve_underline),+ strike: resolve_strike(self.strike, self.dstrike),+ color: self.color.and_then(|c| c.val).map(Into::into),+ highlight: self.highlight.map(Into::into),+ shading: self.shd.map(Into::into),+ vertical_align: self.vert_align.map(Into::into),+ spacing: self.spacing,+ kerning: self.kern.and_then(|k| k.val),+ all_caps: last_toggle(self.caps),+ small_caps: last_toggle(self.small_caps),+ vanish: last_toggle(self.vanish),+ no_proof: last_toggle(self.no_proof),+ web_hidden: last_toggle(self.web_hidden),+ rtl: last_toggle(self.rtl),+ emboss: last_toggle(self.emboss),+ imprint: last_toggle(self.imprint),+ outline: last_toggle(self.outline),+ shadow: last_toggle(self.shadow),+ position: self.position,+ lang: self.lang.map(Into::into),+ border: self.bdr.map(Into::into),+ text_scale: self.char_scale.map(|v| TextScale::new(v)),+ };+ (props, style_id)+ }+}++/// Resolve `<w:u .../>` to an `UnderlineStyle` if — and only if — `@val` is+/// present. A `<w:u>` element without `@val` is silent in the cascade+/// (returns `None`) so it doesn't override an inherited style and doesn't+/// force an underline of its own.+///+/// §17.3.2.40 documents `@val` defaulting to `single` when omitted, but real+/// Word output emits `<w:u w:color="…"/>` (no `@val`) merely to remember a+/// chosen underline color even when the user has *not* turned underline on.+/// Treating that as "single" makes every such run render underlined — which+/// neither Word nor LibreOffice does. Matching Word's observable behaviour+/// is the right call here; the literal spec interpretation is wrong about+/// real-world documents.+fn resolve_underline(u: UnderlineXml) -> Option<UnderlineStyle> {+ u.val.map(Into::into)+}++/// `<w:strike/>` and `<w:dstrike/>` are separate OnOff toggles; dstrike+/// takes precedence when both are on. Each input is the full list of repeated+/// occurrences inside the parent `<w:rPr>` — by §17.7.2 last-wins cascade,+/// only the final element of each list is observable, so we collapse before+/// resolving precedence.+fn resolve_strike(strike: Vec<OnOff>, dstrike: Vec<OnOff>) -> Option<StrikeStyle> {+ let strike_present = !strike.is_empty();+ let dstrike_present = !dstrike.is_empty();+ let s = last_toggle(strike).unwrap_or(false);+ let d = last_toggle(dstrike).unwrap_or(false);+ match (d, s) {+ (true, _) => Some(StrikeStyle::Double),+ (false, true) => Some(StrikeStyle::Single),+ (false, false) => {+ // explicit off → Some(None), absent → None+ if strike_present || dstrike_present {+ Some(StrikeStyle::None)+ } else {+ None+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::{+ BorderStyle, Color, HighlightColor, TextScale, UnderlineStyle, VerticalAlign,+ };++ fn parse(xml: &str) -> (RunProperties, Option<StyleId>) {+ let r: RPrXml = quick_xml::de::from_str(xml).expect("deserialize rPr");+ r.split()+ }++ #[test]+ fn empty_rpr_default_run_properties() {+ let (rp, sid) = parse(r#"<rPr/>"#);+ assert!(sid.is_none());+ assert!(rp.bold.is_none());+ assert!(rp.italic.is_none());+ }++ #[test]+ fn style_ref_extracted() {+ let (rp, sid) = parse(r#"<rPr><rStyle val="Emphasis"/></rPr>"#);+ assert_eq!(sid.map(|s| s.as_str().to_string()), Some("Emphasis".into()));+ assert!(rp.bold.is_none());+ }++ #[test]+ fn basic_toggles() {+ let (rp, _) = parse(r#"<rPr><b/><i/><caps/></rPr>"#);+ assert_eq!(rp.bold, Some(true));+ assert_eq!(rp.italic, Some(true));+ assert_eq!(rp.all_caps, Some(true));+ }++ #[test]+ fn toggle_off_is_false() {+ let (rp, _) = parse(r#"<rPr><b val="false"/></rPr>"#);+ assert_eq!(rp.bold, Some(false));+ }++ #[test]+ fn font_size_is_half_points() {+ let (rp, _) = parse(r#"<rPr><sz val="22"/></rPr>"#);+ assert_eq!(rp.font_size.map(|d| d.raw()), Some(22));+ }++ #[test]+ fn underline_with_val() {+ let (rp, _) = parse(r#"<rPr><u val="double"/></rPr>"#);+ assert_eq!(rp.underline, Some(UnderlineStyle::Double));+ }++ #[test]+ fn underline_without_val_is_silent_in_cascade() {+ // Real Word emits `<w:u w:color="…"/>` — no `@val` — to remember a+ // chosen underline color even when underline is *not* on. Treating+ // that as "single" caused every such run to render underlined, which+ // doesn't match Word's actual rendering. So `<w:u>` without `@val`+ // contributes nothing to the cascade (parser returns None), letting+ // any inherited underline win.+ let (rp, _) = parse(r#"<rPr><u/></rPr>"#);+ assert_eq!(rp.underline, None);+ }++ #[test]+ fn underline_with_color_but_no_val_is_silent() {+ // Same shape Word actually emits — color attribute alone, no `@val`.+ let (rp, _) = parse(r#"<rPr><u color="000000"/></rPr>"#);+ assert_eq!(rp.underline, None);+ }++ #[test]+ fn underline_val_none_is_explicit_override() {+ // §17.3.2.40: w:val="none" is the explicit "no underline" override —+ // it must round-trip as `Some(UnderlineStyle::None)`, distinct from+ // both an absent <w:u/> element (None) and an inherited underline.+ let (rp, _) = parse(r#"<rPr><u val="none"/></rPr>"#);+ assert_eq!(rp.underline, Some(UnderlineStyle::None));+ }++ #[test]+ fn strike_single() {+ let (rp, _) = parse(r#"<rPr><strike/></rPr>"#);+ assert_eq!(rp.strike, Some(StrikeStyle::Single));+ }++ #[test]+ fn dstrike_wins_over_strike() {+ let (rp, _) = parse(r#"<rPr><strike/><dstrike/></rPr>"#);+ assert_eq!(rp.strike, Some(StrikeStyle::Double));+ }++ #[test]+ fn strike_explicit_off() {+ let (rp, _) = parse(r#"<rPr><strike val="0"/></rPr>"#);+ assert_eq!(rp.strike, Some(StrikeStyle::None));+ }++ #[test]+ fn color_rgb_and_auto() {+ let (rp, _) = parse(r#"<rPr><color val="FF0000"/></rPr>"#);+ assert_eq!(rp.color, Some(Color::Rgb(0xFF0000)));++ let (rp, _) = parse(r#"<rPr><color val="auto"/></rPr>"#);+ assert_eq!(rp.color, Some(Color::Auto));+ }++ #[test]+ fn highlight_via_st_enum() {+ let (rp, _) = parse(r#"<rPr><highlight val="yellow"/></rPr>"#);+ assert_eq!(rp.highlight, Some(HighlightColor::Yellow));+ }++ #[test]+ fn highlight_val_none_is_explicit_override() {+ // §17.3.2.15 / §17.18.40: <w:highlight w:val="none"/> is the spec's+ // explicit "no highlight" override — must round-trip to+ // `Some(HighlightColor::None)`, not a parse error.+ let (rp, _) = parse(r#"<rPr><highlight val="none"/></rPr>"#);+ assert_eq!(rp.highlight, Some(HighlightColor::None));+ }++ #[test]+ fn vertical_align_superscript() {+ let (rp, _) = parse(r#"<rPr><vertAlign val="superscript"/></rPr>"#);+ assert_eq!(rp.vertical_align, Some(VerticalAlign::Superscript));+ }++ #[test]+ fn text_scale_parsed() {+ // §17.3.2.45: <w:w w:val="80"/> compresses character width to 80%.+ let (rp, _) = parse(r#"<rPr><w val="80"/></rPr>"#);+ assert_eq!(rp.text_scale, Some(TextScale::new(80)));+ assert_eq!(rp.text_scale.unwrap().percent(), 80);+ }++ #[test]+ fn text_scale_absent_is_none() {+ // No <w:w> element → inherit from style cascade.+ let (rp, _) = parse(r#"<rPr><b/></rPr>"#);+ assert_eq!(rp.text_scale, None);+ }++ #[test]+ fn text_scale_clamps_above_600() {+ // §17.18.81: ST_TextScale max is 600.+ let (rp, _) = parse(r#"<rPr><w val="999"/></rPr>"#);+ assert_eq!(rp.text_scale, Some(TextScale::new(600)));+ }++ #[test]+ fn text_scale_zero_normalizes_to_100() {+ // Word treats <w:w w:val="0"/> as the default 100%.+ let (rp, _) = parse(r#"<rPr><w val="0"/></rPr>"#);+ assert_eq!(rp.text_scale, Some(TextScale::NORMAL));+ }++ #[test]+ /// Upstream rejected a negative font size, failing the whole document.+ /// We treat it as unspecified so the size inherits from the style chain —+ /// but it must still never be accepted as a real size.+ fn negative_decimal_font_size_is_unspecified() {+ let (rp, _) = parse(r#"<rPr><sz val="-1.5"/></rPr>"#);+ assert_eq!(rp.font_size, None);+ }++ #[test]+ fn valid_font_size_still_parses() {+ let (rp, _) = parse(r#"<rPr><sz val="24"/></rPr>"#);+ assert_eq!(rp.font_size.map(|d| d.raw()), Some(24));+ }++ #[test]+ fn spacing_and_kern_and_position() {+ let (rp, _) = parse(+ r#"<rPr>+ <spacing val="40"/>+ <kern val="20"/>+ <position val="-4"/>+ </rPr>"#,+ );+ assert_eq!(rp.spacing.map(|d| d.raw()), Some(40));+ assert_eq!(rp.kerning.map(|d| d.raw()), Some(20));+ assert_eq!(rp.position.map(|d| d.raw()), Some(-4));+ }++ #[test]+ fn lang_tri_mode() {+ let (rp, _) = parse(r#"<rPr><lang val="en-US" eastAsia="ja-JP"/></rPr>"#);+ let l = rp.lang.unwrap();+ assert_eq!(l.val.as_deref(), Some("en-US"));+ assert_eq!(l.east_asia.as_deref(), Some("ja-JP"));+ }++ #[test]+ fn border_via_bdr() {+ let (rp, _) = parse(r#"<rPr><bdr val="single" sz="4" color="000000"/></rPr>"#);+ let b = rp.border.unwrap();+ assert_eq!(b.style, BorderStyle::Single);+ assert_eq!(b.width.raw(), 4);+ }++ #[test]+ fn fonts_explicit_and_theme_mix() {+ let (rp, _) = parse(r#"<rPr><rFonts ascii="Calibri" hAnsiTheme="minorHAnsi"/></rPr>"#);+ assert_eq!(rp.fonts.ascii.explicit.as_deref(), Some("Calibri"));+ assert!(rp.fonts.high_ansi.theme.is_some());+ }++ #[test]+ fn duplicate_toggle_is_tolerated_last_wins() {+ // Real-world LibreOffice DOCX writers occasionally emit duplicate+ // self-closing toggles like `<w:b/><w:b/>`. Word renders these without+ // complaint — last-wins semantics means the second copy is a no-op.+ // The derived serde impl would error with `duplicate field`; the+ // manual Deserialize impl on RPrXml must accept it.+ let (rp, _) = parse(r#"<rPr><b/><b/></rPr>"#);+ assert_eq!(rp.bold, Some(true));+ }++ #[test]+ fn duplicate_toggle_last_wins_when_values_differ() {+ // If two duplicate toggles disagree, last wins.+ let (rp, _) = parse(r#"<rPr><b val="0"/><b/></rPr>"#);+ assert_eq!(rp.bold, Some(true));+ let (rp, _) = parse(r#"<rPr><b/><b val="0"/></rPr>"#);+ assert_eq!(rp.bold, Some(false));+ }++ #[test]+ fn full_rpr_end_to_end() {+ let xml = r#"<rPr>+ <rStyle val="Heading1Char"/>+ <rFonts ascii="Arial" hAnsi="Arial"/>+ <b/>+ <i/>+ <sz val="28"/>+ <color val="2E74B5"/>+ <u val="single"/>+ <lang val="en-US"/>+ </rPr>"#;+ let (rp, sid) = parse(xml);+ assert_eq!(+ sid.map(|s| s.as_str().to_string()),+ Some("Heading1Char".into())+ );+ assert_eq!(rp.fonts.ascii.explicit.as_deref(), Some("Arial"));+ assert_eq!(rp.bold, Some(true));+ assert_eq!(rp.italic, Some(true));+ assert_eq!(rp.font_size.map(|d| d.raw()), Some(28));+ assert_eq!(rp.color, Some(Color::Rgb(0x2E74B5)));+ assert_eq!(rp.underline, Some(UnderlineStyle::Single));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/section.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/section.rsnew file mode 100644index 0000000..c06877c--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/section.rs@@ -0,0 +1,584 @@+//! `<w:sectPr>` schema (§17.6 section properties).+//!+//! RSIDs on the `<w:sectPr>` start tag are captured via `@rsidR`, `@rsidRPr`,+//! `@rsidSect` because serde reads them as ordinary attributes on the root.++use serde::Deserialize;++use crate::docx::model::dimension::{Dimension, FractionPoints, Twips};+use crate::docx::model::{+ ChapterSeparator, ColumnDefinition, Columns, DocGrid, DocGridType, NumberFormat, PageMargins,+ PageNumberType, PageSize, RelId, RevisionSaveId, SectionHeaderFooterRefs, SectionProperties,+ SectionRevisionIds, SectionType,+};+use crate::docx::parse::primitives::OnOff;+use crate::docx::parse::primitives::st_enums::{StNumberFormat, StPageOrientation, StSectionMark};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;++/// `<w:sectPr>` root.+///+/// Children are collected into a single `$value` Vec rather than as named+/// fields because real DOCX files commonly interleave `<w:headerReference>`+/// and `<w:footerReference>` (one h+f pair per `type`), and quick-xml's+/// serde deserializer rejects non-contiguous repeats of a named field.+#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct SectPrXml {+ #[serde(rename = "@rsidR", default)]+ rsid_r: Option<String>,+ #[serde(rename = "@rsidRPr", default)]+ rsid_r_pr: Option<String>,+ #[serde(rename = "@rsidSect", default)]+ rsid_sect: Option<String>,++ #[serde(rename = "$value", default)]+ children: Vec<SectChildXml>,+}++#[derive(Clone, Debug, Deserialize)]+pub(crate) enum SectChildXml {+ #[serde(rename = "pgSz")]+ PgSz(PgSzXml),+ #[serde(rename = "pgMar")]+ PgMar(PgMarXml),+ #[serde(rename = "cols")]+ Cols(ColsXml),+ #[serde(rename = "docGrid")]+ DocGrid(DocGridXml),+ #[serde(rename = "headerReference")]+ HeaderRef(HfRefXml),+ #[serde(rename = "footerReference")]+ FooterRef(HfRefXml),+ #[serde(rename = "titlePg")]+ TitlePg(OnOff),+ #[serde(rename = "type")]+ Type(ValStSectionMark),+ #[serde(rename = "pgNumType")]+ PgNumType(PgNumTypeXml),+ #[serde(other)]+ Other,+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct PgSzXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ w: Option<Dimension<Twips>>,+ #[serde(+ rename = "@h",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ h: Option<Dimension<Twips>>,+ #[serde(+ rename = "@orient",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ orient: Option<StPageOrientation>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct PgMarXml {+ #[serde(+ rename = "@top",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ top: Option<Dimension<Twips>>,+ #[serde(+ rename = "@right",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ right: Option<Dimension<Twips>>,+ #[serde(+ rename = "@bottom",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ bottom: Option<Dimension<Twips>>,+ #[serde(+ rename = "@left",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ left: Option<Dimension<Twips>>,+ #[serde(+ rename = "@header",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ header: Option<Dimension<Twips>>,+ #[serde(+ rename = "@footer",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ footer: Option<Dimension<Twips>>,+ #[serde(+ rename = "@gutter",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ gutter: Option<Dimension<Twips>>,+}++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct ColsXml {+ #[serde(+ rename = "@num",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ num: Option<u32>,+ #[serde(+ rename = "@space",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ space: Option<Dimension<Twips>>,+ #[serde(rename = "@equalWidth", default)]+ equal_width: Option<OnOffFromAttr>,+ /// §17.6.4 `w:sep` — draw a vertical rule between columns.+ #[serde(rename = "@sep", default)]+ sep: Option<OnOffFromAttr>,+ #[serde(rename = "col", default)]+ cols: Vec<ColXml>,+}++use crate::docx::parse::primitives::AttrBool as OnOffFromAttr;++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct ColXml {+ #[serde(+ rename = "@w",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ w: Option<Dimension<Twips>>,+ #[serde(+ rename = "@space",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ space: Option<Dimension<Twips>>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct DocGridXml {+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ ty: Option<StDocGrid>,+ #[serde(+ rename = "@linePitch",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ line_pitch: Option<Dimension<Twips>>,+ #[serde(+ rename = "@charSpace",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ char_space: Option<Dimension<FractionPoints>>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+enum StDocGrid {+ Default,+ Lines,+ LinesAndChars,+ SnapToChars,+}++impl From<StDocGrid> for DocGridType {+ fn from(s: StDocGrid) -> Self {+ match s {+ StDocGrid::Default => Self::Default,+ StDocGrid::Lines => Self::Lines,+ StDocGrid::LinesAndChars => Self::LinesAndChars,+ StDocGrid::SnapToChars => Self::SnapToChars,+ }+ }+}++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct HfRefXml {+ #[serde(rename = "@id")]+ id: String,+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ ty: Option<StHdrFtr>,+}++#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+enum StHdrFtr {+ Default,+ First,+ Even,+}++#[derive(Clone, Debug, Deserialize)]+pub(crate) struct PgNumTypeXml {+ #[serde(rename = "@fmt", default)]+ fmt: Option<StNumberFormat>,+ #[serde(+ rename = "@start",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ start: Option<u32>,+ #[serde(+ rename = "@chapStyle",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ chap_style: Option<u32>,+ #[serde(+ rename = "@chapSep",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ chap_sep: Option<StChapSep>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+enum StChapSep {+ Hyphen,+ Period,+ Colon,+ EmDash,+ EnDash,+}++impl From<StChapSep> for ChapterSeparator {+ fn from(s: StChapSep) -> Self {+ match s {+ StChapSep::Hyphen => Self::Hyphen,+ StChapSep::Period => Self::Period,+ StChapSep::Colon => Self::Colon,+ StChapSep::EmDash => Self::EmDash,+ StChapSep::EnDash => Self::EnDash,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct ValStSectionMark {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ val: StSectionMark,+}++impl From<PgSzXml> for PageSize {+ fn from(x: PgSzXml) -> Self {+ Self {+ width: x.w,+ height: x.h,+ orientation: x.orient.map(Into::into),+ }+ }+}++impl From<PgMarXml> for PageMargins {+ fn from(x: PgMarXml) -> Self {+ Self {+ top: x.top,+ right: x.right,+ bottom: x.bottom,+ left: x.left,+ header: x.header,+ footer: x.footer,+ gutter: x.gutter,+ }+ }+}++impl From<ColsXml> for Columns {+ fn from(x: ColsXml) -> Self {+ Self {+ count: x.num,+ space: x.space,+ equal_width: x.equal_width.map(|v| v.0),+ separator: x.sep.map(|v| v.0),+ columns: x.cols.into_iter().map(Into::into).collect(),+ }+ }+}++impl From<ColXml> for ColumnDefinition {+ fn from(x: ColXml) -> Self {+ Self {+ width: x.w,+ space: x.space,+ }+ }+}++impl From<DocGridXml> for DocGrid {+ fn from(x: DocGridXml) -> Self {+ Self {+ grid_type: x.ty.map(Into::into),+ line_pitch: x.line_pitch,+ char_space: x.char_space,+ }+ }+}++impl From<PgNumTypeXml> for PageNumberType {+ fn from(x: PgNumTypeXml) -> Self {+ Self {+ format: x.fmt.map(NumberFormat::from),+ start: x.start,+ chap_style: x.chap_style,+ chap_sep: x.chap_sep.map(Into::into),+ }+ }+}++impl From<SectPrXml> for SectionProperties {+ fn from(x: SectPrXml) -> Self {+ let mut page_size: Option<PgSzXml> = None;+ let mut page_margins: Option<PgMarXml> = None;+ let mut cols: Option<ColsXml> = None;+ let mut doc_grid: Option<DocGridXml> = None;+ let mut header_refs = SectionHeaderFooterRefs::default();+ let mut footer_refs = SectionHeaderFooterRefs::default();+ let mut title_page: Option<bool> = None;+ let mut section_type: Option<SectionType> = None;+ let mut page_number_type: Option<PgNumTypeXml> = None;++ for child in x.children {+ match child {+ SectChildXml::PgSz(v) => page_size = Some(v),+ SectChildXml::PgMar(v) => page_margins = Some(v),+ SectChildXml::Cols(v) => cols = Some(v),+ SectChildXml::DocGrid(v) => doc_grid = Some(v),+ SectChildXml::HeaderRef(r) => assign_hf_ref(&mut header_refs, r),+ SectChildXml::FooterRef(r) => assign_hf_ref(&mut footer_refs, r),+ SectChildXml::TitlePg(OnOff(b)) => title_page = Some(b),+ SectChildXml::Type(v) => section_type = Some(SectionType::from(v.val)),+ SectChildXml::PgNumType(v) => page_number_type = Some(v),+ SectChildXml::Other => {}+ }+ }++ Self {+ page_size: page_size.map(Into::into),+ page_margins: page_margins.map(Into::into),+ columns: cols.map(Into::into),+ doc_grid: doc_grid.map(Into::into),+ header_refs,+ footer_refs,+ title_page,+ section_type,+ page_number_type: page_number_type.map(Into::into),+ rsids: SectionRevisionIds {+ r: x.rsid_r.as_deref().and_then(RevisionSaveId::from_hex),+ r_pr: x.rsid_r_pr.as_deref().and_then(RevisionSaveId::from_hex),+ sect: x.rsid_sect.as_deref().and_then(RevisionSaveId::from_hex),+ },+ }+ }+}++fn assign_hf_ref(out: &mut SectionHeaderFooterRefs, r: HfRefXml) {+ let rel = RelId::new(&r.id);+ match r.ty {+ Some(StHdrFtr::First) => out.first = Some(rel),+ Some(StHdrFtr::Even) => out.even = Some(rel),+ Some(StHdrFtr::Default) | None => out.default = Some(rel),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::PageOrientation;++ fn parse(xml: &str) -> SectionProperties {+ let x: SectPrXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn page_size_with_orientation() {+ let s = parse(r#"<sectPr><pgSz w="12240" h="15840" orient="landscape"/></sectPr>"#);+ let ps = s.page_size.unwrap();+ assert_eq!(ps.width.unwrap().raw(), 12240);+ assert_eq!(ps.height.unwrap().raw(), 15840);+ assert_eq!(ps.orientation, Some(PageOrientation::Landscape));+ }++ #[test]+ fn page_margins_all_seven() {+ let s = parse(+ r#"<sectPr><pgMar top="1440" right="1800" bottom="1440" left="1800"+ header="720" footer="720" gutter="0"/></sectPr>"#,+ );+ let pm = s.page_margins.unwrap();+ assert_eq!(pm.top.unwrap().raw(), 1440);+ assert_eq!(pm.header.unwrap().raw(), 720);+ assert_eq!(pm.gutter.unwrap().raw(), 0);+ }++ #[test]+ fn page_margins_preserve_signed_vertical_values() {+ let s = parse(+ r#"<sectPr><pgMar top="-720.0" right="1800" bottom="-360"+ left="1800" header="720" footer="720" gutter="0"/></sectPr>"#,+ );+ let pm = s.page_margins.unwrap();+ assert_eq!(pm.top.unwrap().raw(), -720);+ assert_eq!(pm.bottom.unwrap().raw(), -360);+ }++ #[test]+ fn cols_with_child_definitions() {+ let s = parse(+ r#"<sectPr><cols num="2" space="720" equalWidth="false">+ <col w="3000" space="500"/>+ <col w="4000"/>+ </cols></sectPr>"#,+ );+ let c = s.columns.unwrap();+ assert_eq!(c.count, Some(2));+ assert_eq!(c.equal_width, Some(false));+ assert_eq!(c.columns.len(), 2);+ assert_eq!(c.columns[0].width.unwrap().raw(), 3000);+ }++ #[test]+ fn doc_grid_basic() {+ let s = parse(r#"<sectPr><docGrid type="lines" linePitch="360"/></sectPr>"#);+ let g = s.doc_grid.unwrap();+ assert_eq!(g.grid_type, Some(DocGridType::Lines));+ assert_eq!(g.line_pitch.unwrap().raw(), 360);+ }++ #[test]+ fn doc_grid_preserves_signed_decimal_values() {+ let s = parse(+ r#"<sectPr><docGrid type="linesAndChars" linePitch="-360.0" charSpace="-12"/></sectPr>"#,+ );+ let g = s.doc_grid.unwrap();+ assert_eq!(g.line_pitch.unwrap().raw(), -360);+ assert_eq!(g.char_space.unwrap().raw(), -12);+ }++ #[test]+ fn header_footer_refs_split_by_type() {+ let s = parse(+ r#"<sectPr>+ <headerReference id="rId1" type="default"/>+ <headerReference id="rId2" type="first"/>+ <footerReference id="rId3"/>+ </sectPr>"#,+ );+ assert_eq!(+ s.header_refs.default.as_ref().map(|r| r.as_str()),+ Some("rId1")+ );+ assert_eq!(+ s.header_refs.first.as_ref().map(|r| r.as_str()),+ Some("rId2")+ );+ assert_eq!(+ s.footer_refs.default.as_ref().map(|r| r.as_str()),+ Some("rId3")+ );+ }++ #[test]+ fn header_footer_refs_interleaved() {+ // Real docs commonly interleave header/footer refs by type+ // (even headers+footers, then default headers+footers, then first).+ let s = parse(+ r#"<sectPr>+ <headerReference id="rId6" type="even"/>+ <headerReference id="rId7" type="default"/>+ <footerReference id="rId8" type="even"/>+ <footerReference id="rId9" type="default"/>+ <headerReference id="rId10" type="first"/>+ <footerReference id="rId11" type="first"/>+ </sectPr>"#,+ );+ assert_eq!(+ s.header_refs.even.as_ref().map(|r| r.as_str()),+ Some("rId6")+ );+ assert_eq!(+ s.header_refs.default.as_ref().map(|r| r.as_str()),+ Some("rId7")+ );+ assert_eq!(+ s.header_refs.first.as_ref().map(|r| r.as_str()),+ Some("rId10")+ );+ assert_eq!(+ s.footer_refs.even.as_ref().map(|r| r.as_str()),+ Some("rId8")+ );+ assert_eq!(+ s.footer_refs.default.as_ref().map(|r| r.as_str()),+ Some("rId9")+ );+ assert_eq!(+ s.footer_refs.first.as_ref().map(|r| r.as_str()),+ Some("rId11")+ );+ }++ #[test]+ fn section_type_roundtrip() {+ let s = parse(r#"<sectPr><type val="evenPage"/></sectPr>"#);+ assert_eq!(s.section_type, Some(SectionType::EvenPage));+ }++ #[test]+ fn title_pg_toggle() {+ let s = parse(r#"<sectPr><titlePg/></sectPr>"#);+ assert_eq!(s.title_page, Some(true));+ }++ #[test]+ fn page_num_type_with_chap_sep() {+ let s = parse(+ r#"<sectPr><pgNumType fmt="decimal" start="1" chapStyle="1" chapSep="emDash"/></sectPr>"#,+ );+ let p = s.page_number_type.unwrap();+ assert_eq!(p.format, Some(NumberFormat::Decimal));+ assert_eq!(p.start, Some(1));+ assert_eq!(p.chap_sep, Some(ChapterSeparator::EmDash));+ }++ #[test]+ fn rsids_captured_from_root_attrs() {+ let s = parse(r#"<sectPr rsidR="001A2B3C" rsidSect="00A1B2C3"/>"#);+ assert!(s.rsids.r.is_some());+ assert!(s.rsids.sect.is_some());+ assert!(s.rsids.r_pr.is_none());+ }++ #[test]+ fn empty_sect_pr_is_default() {+ let s = parse(r#"<sectPr/>"#);+ assert!(s.page_size.is_none());+ assert!(s.columns.is_none());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/shading.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/shading.rsnew file mode 100644index 0000000..16fe374--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/shading.rs@@ -0,0 +1,79 @@+//! Shading sub-schema (§17.3.5 w:shd).++use serde::Deserialize;++use crate::docx::model::{Color, Shading};+use crate::docx::parse::primitives::HexColor;+use crate::docx::parse::primitives::st_enums::StShd;++/// `<w:shd w:val="..." w:fill="..." w:color="..."/>`.+///+/// `@fill` is the background color; `@color` the pattern foreground (for+/// striped/crossed patterns). Both accept `auto`. Defaults: fill=auto,+/// color=auto, pattern=clear.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct ShdXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ val: StShd,+ #[serde(+ rename = "@fill",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ fill: Option<HexColor>,+ #[serde(+ rename = "@color",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ color: Option<HexColor>,+}++impl From<ShdXml> for Shading {+ fn from(x: ShdXml) -> Self {+ Self {+ fill: x.fill.map_or(Color::Auto, Into::into),+ pattern: x.val.into(),+ color: x.color.map_or(Color::Auto, Into::into),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::ShadingPattern;++ fn parse(xml: &str) -> Shading {+ let x: ShdXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn full_solid() {+ let s = parse(r#"<shd val="solid" fill="FF0000" color="000000"/>"#);+ assert_eq!(s.pattern, ShadingPattern::Solid);+ assert_eq!(s.fill, Color::Rgb(0xFF0000));+ assert_eq!(s.color, Color::Rgb(0));+ }++ #[test]+ fn fill_auto_preserved() {+ let s = parse(r#"<shd val="clear" fill="auto" color="auto"/>"#);+ assert_eq!(s.pattern, ShadingPattern::Clear);+ assert_eq!(s.fill, Color::Auto);+ assert_eq!(s.color, Color::Auto);+ }++ #[test]+ fn missing_colors_default_to_auto() {+ let s = parse(r#"<shd val="pct25"/>"#);+ assert_eq!(s.pattern, ShadingPattern::Pct25);+ assert_eq!(s.fill, Color::Auto);+ assert_eq!(s.color, Color::Auto);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/table.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/table.rsnew file mode 100644index 0000000..02e48d1--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/table.rs@@ -0,0 +1,875 @@+//! Table property schemas: `<w:tblPr>`, `<w:trPr>`, `<w:tcPr>`.+//!+//! `TblPrXml::split` returns `(TableProperties, Option<StyleId>)` — the style+//! id travels separately for cascade reasons, matching the legacy parser's+//! signature.++use serde::{Deserialize, Deserializer};++use crate::docx::model::dimension::Twips;+use crate::docx::model::{+ Alignment, CnfStyle, StyleId, TableCellProperties, TableLook, TablePositioning,+ TableProperties, TableRowHeight, TableRowProperties, VerticalMerge,+};+use crate::docx::parse::primitives::st_enums::{+ StAnchor, StHeightRule, StJc, StTblLayoutType, StTblOverlap, StTextDirection, StVerticalJc,+ StXAlign, StYAlign,+};+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;+use crate::docx::parse::primitives::{OnOff, last_toggle};++use super::border::{TableBordersXml, TableCellBordersXml};+use super::cnf_style::CnfStyleXml;+use super::insets::EdgeInsetsTwipsXml;+use super::measure::{TableMeasureXml, deserialize_optional_nonnegative_table_measure};+use super::shading::ShdXml;++// ── tblPr ───────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct TblPrXml {+ #[serde(rename = "tblStyle", default)]+ tbl_style: Option<ValString>,+ #[serde(rename = "tblBorders", default)]+ tbl_borders: Option<TableBordersXml>,+ #[serde(rename = "tblCellMar", default)]+ tbl_cell_mar: Option<EdgeInsetsTwipsXml>,+ #[serde(+ rename = "jc",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ jc: Option<StJc>,+ #[serde(+ rename = "tblW",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ tbl_w: Option<TableMeasureXml>,+ #[serde(rename = "tblLayout", default)]+ tbl_layout: Option<TblLayoutXml>,+ #[serde(rename = "tblInd", default)]+ tbl_ind: Option<TableMeasureXml>,+ #[serde(+ rename = "tblCellSpacing",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ tbl_cell_spacing: Option<TableMeasureXml>,+ #[serde(rename = "tblLook", default)]+ tbl_look: Option<TblLookXml>,+ #[serde(+ rename = "tblStyleRowBandSize",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ tbl_style_row_band_size: Option<u32>,+ #[serde(+ rename = "tblStyleColBandSize",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ tbl_style_col_band_size: Option<u32>,+ #[serde(rename = "tblpPr", default)]+ tblp_pr: Option<TblpPrXml>,+ #[serde(+ rename = "tblOverlap",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ tbl_overlap: Option<StTblOverlap>,+}++/// `<w:tblLayout w:type="fixed"/>` — note `@type` (not `@val`).+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct TblLayoutXml {+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ ty: StTblLayoutType,+}++/// `<w:tblLook>` — supports both the modern explicit attributes (firstRow,+/// lastRow, ...) and the legacy hex bitfield on `@val`. Per+/// [MS-OI29500] §2.1.1583, when both are present the explicit attribute+/// wins per-flag; otherwise the bitfield supplies the value.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct TblLookXml {+ /// A malformed bitfield leaves the explicit per-flag attributes to speak+ /// for themselves rather than failing the table.+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ val: Option<TblLookHex>,+ #[serde(rename = "@firstRow", default)]+ first_row: Option<AttrBool>,+ #[serde(rename = "@lastRow", default)]+ last_row: Option<AttrBool>,+ #[serde(rename = "@firstColumn", default)]+ first_column: Option<AttrBool>,+ #[serde(rename = "@lastColumn", default)]+ last_column: Option<AttrBool>,+ #[serde(rename = "@noHBand", default)]+ no_h_band: Option<AttrBool>,+ #[serde(rename = "@noVBand", default)]+ no_v_band: Option<AttrBool>,+}++/// Word's legacy `<w:tblLook val>` hex bitfield, per [MS-OI29500] §2.1.1583.+///+/// Bit positions:+/// | Mask | Flag |+/// |----------|-------------|+/// | `0x0020` | firstRow |+/// | `0x0040` | lastRow |+/// | `0x0080` | firstColumn |+/// | `0x0100` | lastColumn |+/// | `0x0200` | noHBand |+/// | `0x0400` | noVBand |+///+/// Other bits are reserved/ignored. The Word default `04A0` =+/// firstRow + firstColumn + noVBand.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct TblLookHex(u16);++impl TblLookHex {+ const FIRST_ROW: u16 = 0x0020;+ const LAST_ROW: u16 = 0x0040;+ const FIRST_COLUMN: u16 = 0x0080;+ const LAST_COLUMN: u16 = 0x0100;+ const NO_H_BAND: u16 = 0x0200;+ const NO_V_BAND: u16 = 0x0400;++ fn first_row(self) -> bool {+ self.0 & Self::FIRST_ROW != 0+ }+ fn last_row(self) -> bool {+ self.0 & Self::LAST_ROW != 0+ }+ fn first_column(self) -> bool {+ self.0 & Self::FIRST_COLUMN != 0+ }+ fn last_column(self) -> bool {+ self.0 & Self::LAST_COLUMN != 0+ }+ fn no_h_band(self) -> bool {+ self.0 & Self::NO_H_BAND != 0+ }+ fn no_v_band(self) -> bool {+ self.0 & Self::NO_V_BAND != 0+ }+}++impl<'de> Deserialize<'de> for TblLookHex {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ u16::from_str_radix(s.trim_start_matches("0x"), 16)+ .map(TblLookHex)+ .map_err(serde::de::Error::custom)+ }+}++/// `<w:tblpPr>` — floating table positioning.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct TblpPrXml {+ #[serde(+ rename = "@leftFromText",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ left_from_text: Option<crate::docx::model::dimension::Dimension<Twips>>,+ #[serde(+ rename = "@rightFromText",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ right_from_text: Option<crate::docx::model::dimension::Dimension<Twips>>,+ #[serde(+ rename = "@topFromText",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ top_from_text: Option<crate::docx::model::dimension::Dimension<Twips>>,+ #[serde(+ rename = "@bottomFromText",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ bottom_from_text: Option<crate::docx::model::dimension::Dimension<Twips>>,+ #[serde(+ rename = "@vertAnchor",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ vert_anchor: Option<StAnchor>,+ #[serde(+ rename = "@horzAnchor",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ horz_anchor: Option<StAnchor>,+ #[serde(+ rename = "@tblpXSpec",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ x_spec: Option<StXAlign>,+ #[serde(+ rename = "@tblpYSpec",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ y_spec: Option<StYAlign>,+ #[serde(rename = "@tblpX", default)]+ x: Option<crate::docx::model::dimension::Dimension<Twips>>,+ #[serde(rename = "@tblpY", default)]+ y: Option<crate::docx::model::dimension::Dimension<Twips>>,+}++/// §17.4.61 `<w:tblPrEx>` — table-level property exceptions scoped to+/// a single row. Per the spec it accepts the same vocabulary as+/// `<w:tblPr>` minus `tblStyle` and `tblpPr`. We model only the slice+/// the layout currently honors (table borders); other fields can be+/// added incrementally.+#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct TblPrExXml {+ #[serde(rename = "tblBorders", default)]+ tbl_borders: Option<TableBordersXml>,+ /// §17.4.41: per-row override of the table's `tblCellSpacing`.+ #[serde(+ rename = "tblCellSpacing",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ tbl_cell_spacing: Option<TableMeasureXml>,+}++impl From<TblPrExXml> for crate::docx::model::TableRowPropertyExceptions {+ fn from(x: TblPrExXml) -> Self {+ Self {+ borders: x.tbl_borders.map(Into::into),+ cell_spacing: x.tbl_cell_spacing.map(Into::into),+ }+ }+}++impl TblPrXml {+ pub(crate) fn split(self) -> (TableProperties, Option<StyleId>) {+ let style_id = self.tbl_style.map(|v| StyleId::new(v.val));+ let props = TableProperties {+ style_id: style_id.clone(),+ alignment: self.jc.map(Alignment::from),+ width: self.tbl_w.map(Into::into),+ layout: self+ .tbl_layout+ .map(|v| crate::docx::model::TableLayout::from(v.ty)),+ indent: self.tbl_ind.map(Into::into),+ borders: self.tbl_borders.map(Into::into),+ cell_margins: self.tbl_cell_mar.map(Into::into),+ cell_spacing: self.tbl_cell_spacing.map(Into::into),+ look: self.tbl_look.map(Into::into),+ style_row_band_size: self.tbl_style_row_band_size,+ style_col_band_size: self.tbl_style_col_band_size,+ positioning: self.tblp_pr.map(Into::into),+ overlap: self.tbl_overlap.map(crate::docx::model::TableOverlap::from),+ };+ (props, style_id)+ }+}++impl From<TblLookXml> for TableLook {+ fn from(x: TblLookXml) -> Self {+ // Per [MS-OI29500] §2.1.1583: explicit attribute wins per-flag,+ // legacy `val` supplies the fallback bit when the attribute is absent.+ let from_val = |bit: fn(TblLookHex) -> bool| x.val.map(bit);+ Self {+ first_row: x+ .first_row+ .map(|b| b.0)+ .or_else(|| from_val(TblLookHex::first_row)),+ last_row: x+ .last_row+ .map(|b| b.0)+ .or_else(|| from_val(TblLookHex::last_row)),+ first_column: x+ .first_column+ .map(|b| b.0)+ .or_else(|| from_val(TblLookHex::first_column)),+ last_column: x+ .last_column+ .map(|b| b.0)+ .or_else(|| from_val(TblLookHex::last_column)),+ no_h_band: x+ .no_h_band+ .map(|b| b.0)+ .or_else(|| from_val(TblLookHex::no_h_band)),+ no_v_band: x+ .no_v_band+ .map(|b| b.0)+ .or_else(|| from_val(TblLookHex::no_v_band)),+ }+ }+}++impl From<TblpPrXml> for TablePositioning {+ fn from(x: TblpPrXml) -> Self {+ Self {+ left_from_text: x.left_from_text,+ right_from_text: x.right_from_text,+ top_from_text: x.top_from_text,+ bottom_from_text: x.bottom_from_text,+ vert_anchor: x.vert_anchor.map(Into::into),+ horz_anchor: x.horz_anchor.map(Into::into),+ x_align: x.x_spec.map(Into::into),+ y_align: x.y_spec.map(Into::into),+ x: x.x,+ y: x.y,+ }+ }+}++// ── trPr ───────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct TrPrXml {+ #[serde(rename = "trHeight", default)]+ tr_height: Option<TrHeightXml>,+ // `Vec<OnOff>` (not `Option`) tolerates duplicated toggles per §17.7.2+ // last-wins — see `RPrXml` / `PPrXml` for the rationale.+ #[serde(rename = "tblHeader", default)]+ tbl_header: Vec<OnOff>,+ #[serde(rename = "cantSplit", default)]+ cant_split: Vec<OnOff>,+ #[serde(+ rename = "jc",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ jc: Option<StJc>,+ #[serde(rename = "cnfStyle", default)]+ cnf_style: Option<CnfStyleXml>,+ #[serde(+ rename = "gridBefore",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ grid_before: Option<u32>,+ #[serde(+ rename = "wBefore",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ w_before: Option<TableMeasureXml>,+ #[serde(+ rename = "gridAfter",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ grid_after: Option<u32>,+ #[serde(+ rename = "wAfter",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ w_after: Option<TableMeasureXml>,+ /// §17.4.42: row-level override of the table's `tblCellSpacing`.+ #[serde(+ rename = "tblCellSpacing",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ tbl_cell_spacing: Option<TableMeasureXml>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct TrHeightXml {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ val: Option<crate::docx::model::dimension::Dimension<Twips>>,+ #[serde(+ rename = "@hRule",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ rule: Option<StHeightRule>,+}++impl From<TrHeightXml> for TableRowHeight {+ fn from(x: TrHeightXml) -> Self {+ Self {+ value: x.val.unwrap_or_default(),+ // §17.4.81 says an omitted `hRule` means `auto`; [MS-OI29500]+ // §17.4.80(a) records that **Word assumes `atLeast`**, and Word is+ // what produced these files. Defaulting to `Auto` here would be+ // indistinguishable from an explicit `hRule="auto"`, where the+ // standard says the `val` is ignored — so the two must not collapse+ // to the same variant.+ rule: x+ .rule+ .map(Into::into)+ .unwrap_or(crate::docx::model::HeightRule::AtLeast),+ }+ }+}++impl From<TrPrXml> for TableRowProperties {+ fn from(x: TrPrXml) -> Self {+ Self {+ height: x.tr_height.map(Into::into),+ is_header: last_toggle(x.tbl_header),+ cant_split: last_toggle(x.cant_split),+ justification: x.jc.map(Alignment::from),+ cnf_style: x.cnf_style.map(CnfStyle::from),+ grid_before: x.grid_before.unwrap_or(0),+ w_before: x.w_before.map(Into::into),+ grid_after: x.grid_after.unwrap_or(0),+ w_after: x.w_after.map(Into::into),+ cell_spacing: x.tbl_cell_spacing.map(Into::into),+ }+ }+}++// ── tcPr ───────────────────────────────────────────────────────────────++#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct TcPrXml {+ #[serde(rename = "tcBorders", default)]+ tc_borders: Option<TableCellBordersXml>,+ #[serde(rename = "tcMar", default)]+ tc_mar: Option<EdgeInsetsTwipsXml>,+ #[serde(+ rename = "tcW",+ default,+ deserialize_with = "deserialize_optional_nonnegative_table_measure"+ )]+ tc_w: Option<TableMeasureXml>,+ #[serde(rename = "shd", default)]+ shd: Option<ShdXml>,+ #[serde(+ rename = "vAlign",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ v_align: Option<StVerticalJc>,+ #[serde(rename = "vMerge", default)]+ v_merge: Option<VMergeXml>,+ #[serde(+ rename = "gridSpan",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ grid_span: Option<u32>,+ #[serde(+ rename = "textDirection",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_val_attr"+ )]+ text_direction: Option<StTextDirection>,+ #[serde(rename = "noWrap", default)]+ no_wrap: Vec<OnOff>,+ #[serde(rename = "cnfStyle", default)]+ cnf_style: Option<CnfStyleXml>,+}++/// `<w:vMerge/>` — absent `@val` means "continue"; `@val="restart"` starts a+/// new vertical merge group; `@val="continue"` is explicit continue.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct VMergeXml {+ /// An unrecognized `@val` degrades to the same "continue" that an absent+ /// one means, so a bad value merges the cell rather than failing the doc.+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ val: Option<VMergeKind>,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+enum VMergeKind {+ Restart,+ Continue,+}++impl From<VMergeXml> for VerticalMerge {+ fn from(x: VMergeXml) -> Self {+ match x.val {+ Some(VMergeKind::Restart) => Self::Restart,+ Some(VMergeKind::Continue) | None => Self::Continue,+ }+ }+}++impl From<TcPrXml> for TableCellProperties {+ fn from(x: TcPrXml) -> Self {+ Self {+ width: x.tc_w.map(Into::into),+ borders: x.tc_borders.map(Into::into),+ shading: x.shd.map(Into::into),+ margins: x.tc_mar.map(Into::into),+ vertical_align: x.v_align.map(crate::docx::model::CellVerticalAlign::from),+ vertical_merge: x.v_merge.map(Into::into),+ grid_span: x.grid_span,+ text_direction: x+ .text_direction+ .map(crate::docx::model::TextDirection::from),+ no_wrap: last_toggle(x.no_wrap),+ cnf_style: x.cnf_style.map(CnfStyle::from),+ }+ }+}++// ── shared helpers ──────────────────────────────────────────────────────++#[derive(Clone, Debug, Deserialize)]+struct ValString {+ #[serde(rename = "@val")]+ val: String,+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(bound(deserialize = "T: serde::Deserialize<'de>"))]+pub(crate) struct ValAttr<T> {+ #[serde(rename = "@val")]+ val: T,+}++use crate::docx::parse::primitives::AttrBool;++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::{+ BorderStyle, CellVerticalAlign, HeightRule, TableLayout, TableMeasure, TableOverlap,+ TextDirection,+ };++ // ── tblPr ──++ fn parse_tbl_pr(xml: &str) -> (TableProperties, Option<StyleId>) {+ let x: TblPrXml = quick_xml::de::from_str(xml).unwrap();+ x.split()+ }++ #[test]+ fn tbl_pr_style_and_width() {+ let (tp, sid) = parse_tbl_pr(+ r#"<tblPr><tblStyle val="TableGrid"/><tblW w="5000" type="pct"/></tblPr>"#,+ );+ assert_eq!(+ sid.map(|s| s.as_str().to_string()),+ Some("TableGrid".into())+ );+ match tp.width.unwrap() {+ TableMeasure::Pct(d) => assert_eq!(d.raw(), 5000),+ other => panic!("expected Pct, got {other:?}"),+ }+ }++ #[test]+ /// Upstream failed the whole table on a negative width; we drop the width+ /// and keep the table.+ fn negative_decimal_table_width_does_not_fail_the_table() {+ let parsed: TblPrXml = quick_xml::de::from_str(+ r#"<tblPr><tblW w="-1.5" type="dxa"/><jc val="center"/></tblPr>"#,+ )+ .expect("a negative table width must not fail the parse");+ let (tp, _) = parsed.split();+ assert_eq!(+ tp.alignment,+ Some(Alignment::Center),+ "sibling properties must survive"+ );+ }++ #[test]+ fn tbl_pr_layout_and_alignment() {+ let (tp, _) = parse_tbl_pr(r#"<tblPr><jc val="center"/><tblLayout type="fixed"/></tblPr>"#);+ assert_eq!(tp.layout, Some(TableLayout::Fixed));+ assert_eq!(tp.alignment, Some(Alignment::Center));+ }++ #[test]+ fn tbl_pr_borders_and_margins() {+ let (tp, _) = parse_tbl_pr(+ r#"<tblPr>+ <tblBorders><top val="single"/><left val="double"/></tblBorders>+ <tblCellMar><top w="100"/><left w="80"/></tblCellMar>+ </tblPr>"#,+ );+ let b = tp.borders.unwrap();+ assert_eq!(b.top.unwrap().style, BorderStyle::Single);+ assert_eq!(b.left.unwrap().style, BorderStyle::Double);+ assert_eq!(tp.cell_margins.unwrap().top.raw(), 100);+ }++ #[test]+ fn tbl_pr_tbl_look_attrs() {+ let (tp, _) =+ parse_tbl_pr(r#"<tblPr><tblLook firstRow="1" lastRow="0" noHBand="true"/></tblPr>"#);+ let l = tp.look.unwrap();+ assert_eq!(l.first_row, Some(true));+ assert_eq!(l.last_row, Some(false));+ assert_eq!(l.no_h_band, Some(true));+ }++ /// [MS-OI29500] §2.1.1583: legacy `@val` hex bitfield must decode to the+ /// same flags as the modern explicit attributes. Bit positions:+ /// 0x0020 firstRow, 0x0040 lastRow, 0x0080 firstColumn, 0x0100 lastColumn,+ /// 0x0200 noHBand, 0x0400 noVBand. The Word-default `04A0` =+ /// firstRow + firstColumn + noVBand.+ #[test]+ fn tbl_pr_tbl_look_legacy_val_default() {+ let (tp, _) = parse_tbl_pr(r#"<tblPr><tblLook val="04A0"/></tblPr>"#);+ let l = tp.look.unwrap();+ assert_eq!(l.first_row, Some(true));+ assert_eq!(l.last_row, Some(false));+ assert_eq!(l.first_column, Some(true));+ assert_eq!(l.last_column, Some(false));+ assert_eq!(l.no_h_band, Some(false));+ assert_eq!(l.no_v_band, Some(true));+ }++ /// Sample1's ITEM/NEEDED table uses `val="0620"` =+ /// firstRow + noHBand + noVBand. Without legacy decoding, banding is+ /// erroneously enabled and `band1Horz` CF paints inner borders.+ #[test]+ fn tbl_pr_tbl_look_legacy_val_suppresses_banding() {+ let (tp, _) = parse_tbl_pr(r#"<tblPr><tblLook val="0620"/></tblPr>"#);+ let l = tp.look.unwrap();+ assert_eq!(l.first_row, Some(true));+ assert_eq!(l.no_h_band, Some(true));+ assert_eq!(l.no_v_band, Some(true));+ }++ #[test]+ fn tbl_pr_tbl_look_legacy_val_zero_clears_all() {+ let (tp, _) = parse_tbl_pr(r#"<tblPr><tblLook val="0000"/></tblPr>"#);+ let l = tp.look.unwrap();+ assert_eq!(l.first_row, Some(false));+ assert_eq!(l.last_row, Some(false));+ assert_eq!(l.first_column, Some(false));+ assert_eq!(l.last_column, Some(false));+ assert_eq!(l.no_h_band, Some(false));+ assert_eq!(l.no_v_band, Some(false));+ }++ /// Per [MS-OI29500]: when both legacy `val` and explicit attributes are+ /// specified, the explicit attribute wins per-flag. Sample3 has tables+ /// shaped like `<tblLook val="04A0" firstRow="1" noHBand="0" .../>`.+ #[test]+ fn tbl_pr_tbl_look_explicit_attrs_override_val() {+ let (tp, _) =+ parse_tbl_pr(r#"<tblPr><tblLook val="0000" firstRow="1" noVBand="1"/></tblPr>"#);+ let l = tp.look.unwrap();+ assert_eq!(l.first_row, Some(true), "explicit firstRow=1 wins");+ assert_eq!(l.last_row, Some(false), "from val=0000");+ assert_eq!(l.first_column, Some(false), "from val=0000");+ assert_eq!(l.no_v_band, Some(true), "explicit noVBand=1 wins");+ }++ #[test]+ fn tbl_pr_tbl_look_legacy_val_lowercase() {+ let (tp, _) = parse_tbl_pr(r#"<tblPr><tblLook val="04a0"/></tblPr>"#);+ let l = tp.look.unwrap();+ assert_eq!(l.first_row, Some(true));+ assert_eq!(l.no_v_band, Some(true));+ }++ #[test]+ fn tbl_pr_overlap_and_positioning() {+ let (tp, _) = parse_tbl_pr(+ r#"<tblPr>+ <tblOverlap val="never"/>+ <tblpPr tblpX="100" tblpY="200" vertAnchor="page"+ horzAnchor="margin" tblpXSpec="center"/>+ </tblPr>"#,+ );+ assert_eq!(tp.overlap, Some(TableOverlap::Never));+ let pos = tp.positioning.unwrap();+ assert_eq!(pos.x.unwrap().raw(), 100);+ assert_eq!(pos.y.unwrap().raw(), 200);+ assert_eq!(pos.vert_anchor, Some(crate::docx::model::TableAnchor::Page));+ assert_eq!(pos.x_align, Some(crate::docx::model::TableXAlign::Center));+ }++ // ── trPr ──++ fn parse_tr_pr(xml: &str) -> TableRowProperties {+ let x: TrPrXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn tr_pr_height_with_rule() {+ let tr = parse_tr_pr(r#"<trPr><trHeight val="440" hRule="atLeast"/></trPr>"#);+ let h = tr.height.unwrap();+ assert_eq!(h.value.raw(), 440);+ assert_eq!(h.rule, HeightRule::AtLeast);+ }++ #[test]+ fn tr_pr_is_header_and_cant_split() {+ let tr = parse_tr_pr(r#"<trPr><tblHeader/><cantSplit/></trPr>"#);+ assert_eq!(tr.is_header, Some(true));+ assert_eq!(tr.cant_split, Some(true));+ }++ #[test]+ fn tr_pr_duplicate_toggles_tolerated_last_wins() {+ // Duplicated row toggles (as some writers emit) must not fail the parse.+ let tr = parse_tr_pr(r#"<trPr><cantSplit/><cantSplit/></trPr>"#);+ assert_eq!(tr.cant_split, Some(true));+ let tr = parse_tr_pr(r#"<trPr><tblHeader val="1"/><tblHeader val="0"/></trPr>"#);+ assert_eq!(tr.is_header, Some(false));+ }++ #[test]+ fn tc_pr_duplicate_no_wrap_tolerated() {+ let tc = parse_tc_pr(r#"<tcPr><noWrap/><noWrap/></tcPr>"#);+ assert_eq!(tc.no_wrap, Some(true));+ }++ #[test]+ fn tr_pr_grid_after_and_w_after() {+ let tr = parse_tr_pr(r#"<trPr><gridAfter val="2"/><wAfter w="500" type="dxa"/></trPr>"#);+ assert_eq!(tr.grid_after, 2);+ match tr.w_after.unwrap() {+ TableMeasure::Twips(d) => assert_eq!(d.raw(), 500),+ other => panic!("expected Twips, got {other:?}"),+ }+ }++ #[test]+ fn tr_pr_grid_before_and_w_before() {+ let tr = parse_tr_pr(r#"<trPr><gridBefore val="1"/><wBefore w="38" type="dxa"/></trPr>"#);+ assert_eq!(tr.grid_before, 1);+ match tr.w_before.unwrap() {+ TableMeasure::Twips(d) => assert_eq!(d.raw(), 38),+ other => panic!("expected Twips, got {other:?}"),+ }+ }++ #[test]+ fn tr_pr_grid_before_and_grid_after_default_zero() {+ let tr = parse_tr_pr(r#"<trPr/>"#);+ assert_eq!(tr.grid_before, 0);+ assert_eq!(tr.grid_after, 0);+ assert!(tr.w_before.is_none());+ assert!(tr.w_after.is_none());+ }++ // ── tcPr ──++ fn parse_tc_pr(xml: &str) -> TableCellProperties {+ let x: TcPrXml = quick_xml::de::from_str(xml).unwrap();+ x.into()+ }++ #[test]+ fn tc_pr_width_and_borders() {+ let tc = parse_tc_pr(+ r#"<tcPr>+ <tcW w="2500" type="dxa"/>+ <tcBorders><top val="single"/><tl2br val="dotted"/></tcBorders>+ </tcPr>"#,+ );+ match tc.width.unwrap() {+ TableMeasure::Twips(d) => assert_eq!(d.raw(), 2500),+ other => panic!("expected Twips, got {other:?}"),+ }+ assert!(tc.borders.unwrap().tl2br.is_some());+ }++ #[test]+ fn tc_pr_vertical_align() {+ let tc = parse_tc_pr(r#"<tcPr><vAlign val="center"/></tcPr>"#);+ assert_eq!(tc.vertical_align, Some(CellVerticalAlign::Center));+ }++ #[test]+ fn tc_pr_v_merge_restart_and_continue() {+ let tc = parse_tc_pr(r#"<tcPr><vMerge val="restart"/></tcPr>"#);+ assert_eq!(tc.vertical_merge, Some(VerticalMerge::Restart));++ let tc = parse_tc_pr(r#"<tcPr><vMerge/></tcPr>"#);+ assert_eq!(tc.vertical_merge, Some(VerticalMerge::Continue));+ }++ #[test]+ fn tc_pr_grid_span_and_text_direction() {+ let tc = parse_tc_pr(r#"<tcPr><gridSpan val="3"/><textDirection val="tbRl"/></tcPr>"#);+ assert_eq!(tc.grid_span, Some(3));+ assert_eq!(+ tc.text_direction,+ Some(TextDirection::TopToBottomRightToLeft)+ );+ }++ #[test]+ fn tc_pr_no_wrap_and_cnf_style() {+ let tc = parse_tc_pr(r#"<tcPr><noWrap/><cnfStyle val="100000000000"/></tcPr>"#);+ assert_eq!(tc.no_wrap, Some(true));+ assert_eq!(tc.cnf_style, Some(CnfStyle::FIRST_ROW));+ }++ /// §17.4.81 vs [MS-OI29500] §17.4.80(a). The standard says an omitted+ /// `hRule` means `auto`; Word assumes `atLeast`, and Word wrote these files.+ ///+ /// The distinction is load-bearing rather than cosmetic: with `hRule="auto"`+ /// the standard says `val` is **ignored**, so collapsing "omitted" into+ /// `Auto` would make every Word row with a `trHeight` lose its minimum+ /// height — or, as before this change, force an explicit `auto` to be+ /// treated as a minimum it should not have.+ #[test]+ fn omitted_hrule_is_at_least_but_explicit_auto_is_auto() {+ use crate::docx::model::HeightRule;+ let parse = |xml: &str| -> crate::docx::model::TableRowHeight {+ quick_xml::de::from_str::<TrHeightXml>(xml).unwrap().into()+ };+ assert_eq!(parse(r#"<trHeight val="440"/>"#).rule, HeightRule::AtLeast);+ assert_eq!(+ parse(r#"<trHeight val="440" hRule="auto"/>"#).rule,+ HeightRule::Auto+ );+ assert_eq!(+ parse(r#"<trHeight val="440" hRule="atLeast"/>"#).rule,+ HeightRule::AtLeast+ );+ assert_eq!(+ parse(r#"<trHeight val="440" hRule="exact"/>"#).rule,+ HeightRule::Exact+ );+ // The value survives in every case; only the rule decides its meaning.+ assert_eq!(parse(r#"<trHeight val="440"/>"#).value.raw(), 440);+ }++ /// §17.4.41 / §17.4.42: both cell-spacing overrides now reach the model.+ /// Layout applies spacing per table and warns rather than honouring these,+ /// but dropping them at the parser would make that gap invisible.+ #[test]+ fn cell_spacing_overrides_reach_the_model() {+ let tr: crate::docx::model::TableRowProperties = quick_xml::de::from_str::<TrPrXml>(+ r#"<trPr><tblCellSpacing w="72" type="dxa"/></trPr>"#,+ )+ .unwrap()+ .into();+ assert!(tr.cell_spacing.is_some(), "row-level §17.4.42");++ let ex: crate::docx::model::TableRowPropertyExceptions =+ quick_xml::de::from_str::<TblPrExXml>(+ r#"<tblPrEx><tblCellSpacing w="72" type="dxa"/></tblPrEx>"#,+ )+ .unwrap()+ .into();+ assert!(ex.cell_spacing.is_some(), "tblPrEx §17.4.41");+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/properties/schema/tabs.rs b/crates/liteparse-docx/src/docx/parse/properties/schema/tabs.rsnew file mode 100644index 0000000..b20cf59--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/properties/schema/tabs.rs@@ -0,0 +1,120 @@+//! Tabs sub-schema (§17.3.1.38 w:tabs).++use serde::Deserialize;++use crate::docx::model::TabStop;+use crate::docx::model::dimension::{Dimension, Twips};+use crate::docx::parse::primitives::st_enums::{StTabJc, StTabTlc};++/// `<w:tabs>` — a list of `<w:tab>` stops.+#[derive(Clone, Debug, Default, Deserialize)]+pub(crate) struct TabsXml {+ #[serde(rename = "tab", default)]+ pub stops: Vec<TabXml>,+}++/// `<w:tab w:pos="..." w:val="..." w:leader="..."/>` inside a `<w:tabs>`.+#[derive(Clone, Copy, Debug, Deserialize)]+pub(crate) struct TabXml {+ #[serde(+ rename = "@pos",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pos: Option<Dimension<Twips>>,+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ val: StTabJc,+ #[serde(+ rename = "@leader",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ leader: StTabTlc,+}++/// A tab stop with no usable `@pos` cannot be placed, so it is dropped rather+/// than collapsed onto position zero.+fn to_tab_stop(x: TabXml) -> Option<TabStop> {+ Some(TabStop {+ position: x.pos?,+ alignment: x.val.into(),+ leader: x.leader.into(),+ })+}++impl From<TabsXml> for Vec<TabStop> {+ fn from(x: TabsXml) -> Self {+ // `<w:tab val="clear"/>` removes an inherited stop. We keep these in+ // the model so the style cascade (§17.7.2) can apply them when+ // merging a paragraph's tabs with its parent style's tabs. The+ // layout build step (`render::layout::build::convert`) drops them+ // before emitting layout tab stops.+ x.stops.into_iter().filter_map(to_tab_stop).collect()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::{TabAlignment, TabLeader};++ fn parse(xml: &str) -> Vec<TabStop> {+ let t: TabsXml = quick_xml::de::from_str(xml).unwrap();+ t.into()+ }++ #[test]+ fn single_tab_with_leader() {+ let ts = parse(r#"<tabs><tab pos="1440" val="center" leader="dot"/></tabs>"#);+ assert_eq!(ts.len(), 1);+ assert_eq!(ts[0].position.raw(), 1440);+ assert_eq!(ts[0].alignment, TabAlignment::Center);+ assert_eq!(ts[0].leader, TabLeader::Dot);+ }++ #[test]+ fn tab_defaults_left_and_no_leader() {+ let ts = parse(r#"<tabs><tab pos="720"/></tabs>"#);+ assert_eq!(ts.len(), 1);+ assert_eq!(ts[0].alignment, TabAlignment::Left);+ assert_eq!(ts[0].leader, TabLeader::None);+ }++ #[test]+ fn clear_tabs_preserved_for_style_cascade() {+ // Clear entries must survive parsing so the style cascade can use+ // them to remove inherited tabs at matching positions+ // (`render::resolve::properties::merge_paragraph_properties`).+ // The layout build step filters them out before rendering.+ let ts = parse(+ r#"<tabs>+ <tab pos="1440" val="left"/>+ <tab pos="2880" val="clear"/>+ <tab pos="4320" val="right"/>+ </tabs>"#,+ );+ assert_eq!(ts.len(), 3);+ assert_eq!(ts[0].position.raw(), 1440);+ assert_eq!(ts[0].alignment, TabAlignment::Left);+ assert_eq!(ts[1].position.raw(), 2880);+ assert_eq!(ts[1].alignment, TabAlignment::Clear);+ assert_eq!(ts[2].position.raw(), 4320);+ assert_eq!(ts[2].alignment, TabAlignment::Right);+ }++ #[test]+ fn legacy_num_becomes_left() {+ let ts = parse(r#"<tabs><tab pos="720" val="num"/></tabs>"#);+ assert_eq!(ts[0].alignment, TabAlignment::Left);+ }++ #[test]+ fn empty_tabs() {+ let ts = parse(r#"<tabs/>"#);+ assert!(ts.is_empty());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/rel_rewrite.rs b/crates/liteparse-docx/src/docx/parse/rel_rewrite.rsnew file mode 100644index 0000000..d520c4b--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/rel_rewrite.rs@@ -0,0 +1,805 @@+//! Rewrite relationship IDs in a parsed block tree.+//!+//! Each XML part in an OOXML package (the main document, every header,+//! every footer, the footnotes/endnotes parts, …) has its **own**+//! relationships file (`_rels/<part>.xml.rels`) with its **own** `rId`+//! namespace. Two different parts may both contain `r:embed="rId1"`+//! pointing at entirely different image targets, or+//! `<w:hyperlink r:id="rId7"/>` pointing at entirely different URLs —+//! the rId is meaningful only with respect to the part it lives in.+//!+//! `Document.media` is a single document-wide `HashMap<RelId, _>`,+//! so a header part's `rId1` can't be allowed to collide with a+//! footer part's `rId1` (the second loader would silently overwrite+//! the first). For each subordinate part the caller (`mod.rs`'s+//! `load_part_rel_remap`) synthesizes a remap that contains:+//!+//! * **image rIds** → globally-unique synthesized ids, with the+//! loaded image bytes registered in `media` under those ids;+//! * **hyperlink rIds** → the resolved external URL (carried as a+//! `RelId`-shaped string, the same way the document-level+//! hyperlink resolver represents a resolved external link).+//!+//! [`rewrite_part_rels_in_blocks`] walks the block tree once and+//! applies the remap to every relationship-bearing node it knows+//! about — pictures, blip fills on shapes, outlines, VML images,+//! VML text-box content, hyperlink targets, fields, and recursively+//! into shape `txbxContent`, table cells, and `AlternateContent`+//! fallbacks. After this pass every rId reference in the part's+//! blocks is unambiguous against `Document.media` (for images) or is+//! already a resolved URL (for hyperlinks).+//!+//! The body uses a separate code path: its image rels populate+//! `media` keyed by their original rIds (which is fine — there's+//! only one body), and `mod.rs::resolve_hyperlinks` does the+//! body-level URL resolution against `doc_rels`.++use std::collections::HashMap;++use crate::model::{+ Blip, BlipFill, Block, DrawingFill, GraphicContent, HyperlinkTarget, Image, Inline, Outline,+ Pict, RelId, ShapeProperties, VmlCommonAttrs, VmlImageData, VmlPrimitive, VmlTextBox,+ WordProcessingShape,+};++/// Apply `remap` to every relationship-bearing `RelId` inside+/// `blocks` — image embeds/links (DrawingML and VML), hyperlink+/// targets, and the same nested in shape `txbxContent`, VML+/// text-box content, table cells, fields, and `AlternateContent`+/// fallbacks. Identifiers absent from the remap are left unchanged,+/// so callers can run this pass over already-resolved content+/// safely.+pub fn rewrite_part_rels_in_blocks(blocks: &mut [Block], remap: &HashMap<RelId, RelId>) {+ if remap.is_empty() {+ return;+ }+ for block in blocks {+ match block {+ Block::Paragraph(p) => rewrite_in_inlines(&mut p.content, remap),+ Block::Table(t) => {+ for row in &mut t.rows {+ for cell in &mut row.cells {+ rewrite_part_rels_in_blocks(&mut cell.content, remap);+ }+ }+ }+ Block::SectionBreak(_) => {}+ }+ }+}++fn rewrite_in_inlines(inlines: &mut [Inline], remap: &HashMap<RelId, RelId>) {+ for inline in inlines {+ match inline {+ Inline::Image(image) => rewrite_in_image(image, remap),+ Inline::Pict(pict) => rewrite_in_pict(pict, remap),+ Inline::Hyperlink(h) => {+ rewrite_in_hyperlink_target(&mut h.target, remap);+ rewrite_in_inlines(&mut h.content, remap);+ }+ Inline::Field(f) => rewrite_in_inlines(&mut f.content, remap),+ Inline::AlternateContent(ac) => {+ // §M.2.2: the renderer prefers a supported `<mc:Choice>` over+ // `<mc:Fallback>` (see `layout::choices_render_wps_shape`), so+ // rIds inside the choices must be rewritten too — not just the+ // fallback. A header/footer logo or link often lives in a choice.+ for choice in &mut ac.choices {+ rewrite_in_inlines(&mut choice.content, remap);+ }+ if let Some(ref mut fb) = ac.fallback {+ rewrite_in_inlines(fb, remap);+ }+ }+ Inline::TextRun(_)+ | Inline::FootnoteRef(_)+ | Inline::EndnoteRef(_)+ | Inline::BookmarkStart { .. }+ | Inline::BookmarkEnd(_)+ | Inline::Symbol(_)+ | Inline::Separator+ | Inline::ContinuationSeparator+ | Inline::FieldChar(_)+ | Inline::InstrText(_)+ | Inline::FootnoteRefMark+ | Inline::EndnoteRefMark => {}+ }+ }+}++fn rewrite_in_image(image: &mut Image, remap: &HashMap<RelId, RelId>) {+ if let Some(ref mut graphic) = image.graphic {+ match graphic {+ GraphicContent::Picture(pic) => {+ if let Some(ref mut blip) = pic.blip_fill.blip {+ rewrite_blip(blip, remap);+ }+ if let Some(ref mut props) = pic.shape_properties {+ rewrite_in_shape_properties(props, remap);+ }+ }+ GraphicContent::WordProcessingShape(wsp) => {+ rewrite_in_word_processing_shape(wsp, remap);+ }+ }+ }+}++fn rewrite_in_word_processing_shape(wsp: &mut WordProcessingShape, remap: &HashMap<RelId, RelId>) {+ if let Some(ref mut props) = wsp.shape_properties {+ rewrite_in_shape_properties(props, remap);+ }+ // §17.17.1: text inside the shape can host its own paragraph tree+ // with images that share this part's rels namespace.+ rewrite_part_rels_in_blocks(&mut wsp.txbx_content, remap);+}++fn rewrite_in_shape_properties(props: &mut ShapeProperties, remap: &HashMap<RelId, RelId>) {+ if let Some(ref mut fill) = props.fill {+ rewrite_in_drawing_fill(fill, remap);+ }+ if let Some(ref mut outline) = props.outline {+ rewrite_in_outline(outline, remap);+ }+}++fn rewrite_in_outline(outline: &mut Outline, remap: &HashMap<RelId, RelId>) {+ if let Some(ref mut fill) = outline.fill {+ rewrite_in_drawing_fill(fill, remap);+ }+}++fn rewrite_in_drawing_fill(fill: &mut DrawingFill, remap: &HashMap<RelId, RelId>) {+ match fill {+ DrawingFill::Blip(blip_fill) => rewrite_in_blip_fill(blip_fill, remap),+ // None / Solid / Gradient / Pattern / Group: no rIds.+ DrawingFill::None+ | DrawingFill::Solid(_)+ | DrawingFill::Gradient(_)+ | DrawingFill::Pattern(_)+ | DrawingFill::Group => {}+ }+}++fn rewrite_in_blip_fill(blip_fill: &mut BlipFill, remap: &HashMap<RelId, RelId>) {+ if let Some(ref mut blip) = blip_fill.blip {+ rewrite_blip(blip, remap);+ }+}++fn rewrite_blip(blip: &mut Blip, remap: &HashMap<RelId, RelId>) {+ if let Some(new) = blip.embed.as_ref().and_then(|id| remap.get(id)).cloned() {+ blip.embed = Some(new);+ }+ if let Some(new) = blip.link.as_ref().and_then(|id| remap.get(id)).cloned() {+ blip.link = Some(new);+ }+}++/// Apply `remap` to every `RelId` inside a single VML `Pict`. Numbering+/// picture bullets (§17.9.21) hold their image in a `Pict` that lives outside+/// the block tree, so they need this entry point rather than+/// [`rewrite_part_rels_in_blocks`]. A no-op on an empty remap.+pub fn rewrite_part_rels_in_pict(pict: &mut Pict, remap: &HashMap<RelId, RelId>) {+ if remap.is_empty() {+ return;+ }+ rewrite_in_pict(pict, remap);+}++fn rewrite_in_pict(pict: &mut Pict, remap: &HashMap<RelId, RelId>) {+ for primitive in &mut pict.primitives {+ rewrite_in_vml_primitive(primitive, remap);+ }+}++/// Walk a single VML primitive, rewriting every `RelId` it owns+/// directly (image data) or holds nested (text-box content, group+/// children). Adding new primitive variants in+/// `crate::model::VmlPrimitive` requires adding them here too — the+/// match arms are exhaustive deliberately.+fn rewrite_in_vml_primitive(p: &mut VmlPrimitive, remap: &HashMap<RelId, RelId>) {+ rewrite_in_vml_common(p.common_mut(), remap);+ match p {+ VmlPrimitive::Group(group) => {+ for child in &mut group.children {+ rewrite_in_vml_primitive(child, remap);+ }+ }+ // Other variants have no nested rels beyond the common attrs.+ VmlPrimitive::Shape(_)+ | VmlPrimitive::Rect(_)+ | VmlPrimitive::RoundRect(_)+ | VmlPrimitive::Oval(_)+ | VmlPrimitive::Line(_)+ | VmlPrimitive::PolyLine(_)+ | VmlPrimitive::Arc(_)+ | VmlPrimitive::Curve(_)+ | VmlPrimitive::Image(_) => {}+ }+}++fn rewrite_in_vml_common(c: &mut VmlCommonAttrs, remap: &HashMap<RelId, RelId>) {+ if let Some(ref mut data) = c.image_data {+ rewrite_vml_image_data(data, remap);+ }+ // §14.1.2.22: a VML shape can host a `<v:textbox>` with block+ // content; images inside it share the part's rels namespace.+ if let Some(ref mut tb) = c.text_box {+ rewrite_in_vml_text_box(tb, remap);+ }+}++fn rewrite_in_vml_text_box(tb: &mut VmlTextBox, remap: &HashMap<RelId, RelId>) {+ rewrite_part_rels_in_blocks(&mut tb.content, remap);+}++fn rewrite_vml_image_data(data: &mut VmlImageData, remap: &HashMap<RelId, RelId>) {+ if let Some(new) = data.rel_id.as_ref().and_then(|id| remap.get(id)).cloned() {+ data.rel_id = Some(new);+ }+}++/// Apply the remap to an `External(rId)` hyperlink target. For+/// header/footer/note parts the remap contains `rId → URL`+/// (resolved through the part's own rels), so this rewrite turns the+/// `External(rId)` placeholder into the final `External(URL)` form+/// the renderer consumes — exactly the job the body-level+/// `resolve_hyperlinks` pass does for the body. When the target is+/// already a URL (e.g. the same blocks were processed twice for some+/// reason) the URL won't match any rId in `remap` and this is a+/// no-op.+fn rewrite_in_hyperlink_target(target: &mut HyperlinkTarget, remap: &HashMap<RelId, RelId>) {+ if let HyperlinkTarget::ExternalRel(id) = target {+ if let Some(new) = remap.get(id) {+ // For a subordinate part the remap resolves a hyperlink rId directly+ // to its external URL (see `load_part_rel_remap`), so the target+ // becomes a resolved URL rather than another rId.+ *target = HyperlinkTarget::ExternalUrl(new.as_str().to_string());+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::Dimension;+ use crate::model::geometry::{EdgeInsets, Size};+ use crate::model::*;++ fn remap_one(from: &str, to: &str) -> HashMap<RelId, RelId> {+ let mut m = HashMap::new();+ m.insert(RelId::new(from), RelId::new(to));+ m+ }++ fn picture_with_blip(rel_id: &str) -> Image {+ Image {+ extent: Size::new(Dimension::new(0), Dimension::new(0)),+ effect_extent: None,+ doc_properties: DocProperties {+ id: 1,+ name: "img".into(),+ description: None,+ hidden: None,+ title: None,+ },+ graphic_frame_locks: None,+ graphic: Some(GraphicContent::Picture(Picture {+ nv_pic_pr: NvPicProperties {+ cnv_pr: DocProperties {+ id: 1,+ name: "pic".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(rel_id)),+ link: None,+ compression: None,+ }),+ src_rect: None,+ fill_kind: BlipFillKind::Unspecified,+ },+ shape_properties: None,+ })),+ placement: ImagePlacement::Inline {+ distance: EdgeInsets::new(+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ ),+ },+ }+ }++ fn paragraph_with_image(image: Image) -> Block {+ Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![Inline::Image(Box::new(image))],+ rsids: ParagraphRevisionIds::default(),+ }))+ }++ #[test]+ fn rewrites_picture_blip_embed() {+ let mut blocks = vec![paragraph_with_image(picture_with_blip("rId1"))];+ let remap = remap_one("rId1", "header3.xml::rId1");++ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!();+ };+ let Inline::Image(img) = &p.content[0] else {+ panic!();+ };+ let new = crate::render::resolve::images::extract_image_rel_id(img).unwrap();+ assert_eq!(new.as_str(), "header3.xml::rId1");+ }++ #[test]+ fn leaves_unmapped_rel_ids_unchanged() {+ let mut blocks = vec![paragraph_with_image(picture_with_blip("rId99"))];+ let remap = remap_one("rId1", "synth");++ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!();+ };+ let Inline::Image(img) = &p.content[0] else {+ panic!();+ };+ let v = crate::render::resolve::images::extract_image_rel_id(img).unwrap();+ assert_eq!(v.as_str(), "rId99");+ }++ #[test]+ fn empty_remap_is_a_noop() {+ let mut blocks = vec![paragraph_with_image(picture_with_blip("rId1"))];+ let remap = HashMap::new();+ rewrite_part_rels_in_blocks(&mut blocks, &remap);+ // No panic, no change — the image still references rId1.+ let Block::Paragraph(p) = &blocks[0] else {+ panic!();+ };+ let Inline::Image(img) = &p.content[0] else {+ panic!();+ };+ let v = crate::render::resolve::images::extract_image_rel_id(img).unwrap();+ assert_eq!(v.as_str(), "rId1");+ }++ #[test]+ fn rewrites_blip_link_too() {+ let mut blip = Blip {+ embed: None,+ link: Some(RelId::new("rId7")),+ compression: None,+ };+ let remap = remap_one("rId7", "linked");+ rewrite_blip(&mut blip, &remap);+ assert_eq!(blip.link.unwrap().as_str(), "linked");+ }++ #[test]+ fn rewrites_vml_image_data_rel_id() {+ let mut data = VmlImageData {+ rel_id: Some(RelId::new("rId2")),+ title: None,+ };+ let remap = remap_one("rId2", "synth_vml");+ rewrite_vml_image_data(&mut data, &remap);+ assert_eq!(data.rel_id.unwrap().as_str(), "synth_vml");+ }++ #[test]+ fn recurses_into_table_cells() {+ let img = picture_with_blip("rId1");+ let cell = TableCell {+ properties: TableCellProperties::default(),+ content: vec![paragraph_with_image(img)],+ };+ let row = TableRow {+ properties: TableRowProperties::default(),+ cells: vec![cell],+ rsids: TableRowRevisionIds::default(),+ property_exceptions: None,+ };+ let mut blocks = vec![Block::Table(Box::new(Table {+ properties: TableProperties::default(),+ grid: vec![],+ rows: vec![row],+ }))];+ let remap = remap_one("rId1", "synth");+ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Table(t) = &blocks[0] else {+ panic!();+ };+ let Block::Paragraph(p) = &t.rows[0].cells[0].content[0] else {+ panic!();+ };+ let Inline::Image(img) = &p.content[0] else {+ panic!();+ };+ let v = crate::render::resolve::images::extract_image_rel_id(img).unwrap();+ assert_eq!(v.as_str(), "synth");+ }++ // ── §17.17.1 wsp:txbxContent — text inside DrawingML shapes ─────────++ /// Build a `WordProcessingShape` with the given `txbx_content` and+ /// the given optional `shape_properties`. All other fields default+ /// to None / empty.+ fn shape_with_text(+ txbx_content: Vec<Block>,+ shape_properties: Option<ShapeProperties>,+ ) -> 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,+ style_line_ref: None,+ style_effect_ref: None,+ style_fill_ref: None,+ style_font_ref: None,+ body_pr: None,+ txbx_content,+ })),+ placement: ImagePlacement::Inline {+ distance: EdgeInsets::new(+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ ),+ },+ }+ }++ #[test]+ fn recurses_into_word_processing_shape_txbx_content() {+ // §17.17.1: a WordProcessingShape may host its own paragraph+ // tree via `<wsp:txbxContent>`. Image rIds inside that subtree+ // belong to the same part as the outer shape and must be+ // rewritten alongside it.+ let inner_image = picture_with_blip("rId1");+ let shape = shape_with_text(vec![paragraph_with_image(inner_image)], None);+ let mut blocks = vec![paragraph_with_image(shape)];+ let remap = remap_one("rId1", "synth_inner");++ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ // Drill through: outer paragraph → outer shape → txbx_content+ // → inner paragraph → inner Picture → blip embed.+ let Block::Paragraph(outer_p) = &blocks[0] else {+ panic!();+ };+ let Inline::Image(outer_img) = &outer_p.content[0] else {+ panic!();+ };+ let Some(GraphicContent::WordProcessingShape(wsp)) = &outer_img.graphic else {+ panic!();+ };+ let Block::Paragraph(inner_p) = &wsp.txbx_content[0] else {+ panic!();+ };+ let Inline::Image(inner) = &inner_p.content[0] else {+ panic!();+ };+ let v = crate::render::resolve::images::extract_image_rel_id(inner).unwrap();+ assert_eq!(v.as_str(), "synth_inner");+ }++ // ── §20.1.8.14 blip image fill on shape body / outline ──────────────++ /// Build a `ShapeProperties` whose body fill is a Blip referencing+ /// `rel_id`. All other properties are empty.+ fn shape_props_with_blip_fill(rel_id: &str) -> ShapeProperties {+ ShapeProperties {+ bw_mode: None,+ transform: None,+ geometry: None,+ fill: Some(DrawingFill::Blip(BlipFill {+ rotate_with_shape: None,+ dpi: None,+ blip: Some(Blip {+ embed: Some(RelId::new(rel_id)),+ link: None,+ compression: None,+ }),+ src_rect: None,+ fill_kind: BlipFillKind::Unspecified,+ })),+ outline: None,+ effect_list: None,+ }+ }++ #[test]+ fn rewrites_blip_image_fill_on_shape_body() {+ // §20.1.8.14: `DrawingFill::Blip` lets a shape use an image as+ // its fill. Whether or not the renderer paints it today, the+ // rId still belongs to the part's namespace and must be+ // remapped at parse time so future renderer wiring sees a+ // valid lookup key.+ let shape = shape_with_text(vec![], Some(shape_props_with_blip_fill("rId1")));+ let mut blocks = vec![paragraph_with_image(shape)];+ let remap = remap_one("rId1", "synth_shape_fill");++ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!();+ };+ let Inline::Image(img) = &p.content[0] else {+ panic!();+ };+ let Some(GraphicContent::WordProcessingShape(wsp)) = &img.graphic else {+ panic!();+ };+ let Some(props) = &wsp.shape_properties else {+ panic!();+ };+ let Some(DrawingFill::Blip(blip_fill)) = &props.fill else {+ panic!();+ };+ let blip = blip_fill.blip.as_ref().unwrap();+ assert_eq!(blip.embed.as_ref().unwrap().as_str(), "synth_shape_fill");+ }++ #[test]+ fn rewrites_blip_image_fill_on_shape_outline() {+ // Outlines accept the same EG_FillProperties choice as bodies.+ let outline = Outline {+ width: None,+ cap: None,+ compound: None,+ alignment: None,+ fill: Some(DrawingFill::Blip(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,+ })),+ dash: None,+ join: None,+ head_end: None,+ tail_end: None,+ };+ let props = ShapeProperties {+ bw_mode: None,+ transform: None,+ geometry: None,+ fill: None,+ outline: Some(outline),+ effect_list: None,+ };+ let shape = shape_with_text(vec![], Some(props));+ let mut blocks = vec![paragraph_with_image(shape)];+ let remap = remap_one("rId7", "synth_outline");++ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!();+ };+ let Inline::Image(img) = &p.content[0] else {+ panic!();+ };+ let Some(GraphicContent::WordProcessingShape(wsp)) = &img.graphic else {+ panic!();+ };+ let outline = wsp+ .shape_properties+ .as_ref()+ .unwrap()+ .outline+ .as_ref()+ .unwrap();+ let Some(DrawingFill::Blip(blip_fill)) = &outline.fill else {+ panic!();+ };+ let blip = blip_fill.blip.as_ref().unwrap();+ assert_eq!(blip.embed.as_ref().unwrap().as_str(), "synth_outline");+ }++ // ── VML §14.1.2.22 v:textbox content recursion ──────────────────────++ #[test]+ fn recurses_into_vml_text_box_content() {+ let inner_image = picture_with_blip("rId1");+ let pict = Pict {+ shape_type: None,+ primitives: vec![VmlPrimitive::Shape(VmlShape {+ common: VmlCommonAttrs {+ text_box: Some(VmlTextBox {+ style: VmlStyle::default(),+ inset: None,+ content: vec![paragraph_with_image(inner_image)],+ }),+ ..VmlCommonAttrs::default()+ },+ shape_type_ref: None,+ vml_path: None,+ })],+ };+ let mut blocks = vec![Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![Inline::Pict(pict)],+ rsids: ParagraphRevisionIds::default(),+ }))];+ let remap = remap_one("rId1", "synth_vml_box");++ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!();+ };+ let Inline::Pict(pict) = &p.content[0] else {+ panic!();+ };+ let shape = pict.shapes().next().unwrap();+ let tb = shape.common.text_box.as_ref().unwrap();+ let Block::Paragraph(inner_p) = &tb.content[0] else {+ panic!();+ };+ let Inline::Image(img) = &inner_p.content[0] else {+ panic!();+ };+ let v = crate::render::resolve::images::extract_image_rel_id(img).unwrap();+ assert_eq!(v.as_str(), "synth_vml_box");+ }++ // ── hyperlink target rewrite ────────────────────────────────────────++ #[test]+ fn rewrites_external_hyperlink_target() {+ let mut blocks = vec![Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![Inline::Hyperlink(Hyperlink {+ target: HyperlinkTarget::ExternalRel(RelId::new("rId7")),+ content: vec![],+ })],+ rsids: ParagraphRevisionIds::default(),+ }))];+ let remap = remap_one("rId7", "https://example.com");+ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!()+ };+ let Inline::Hyperlink(h) = &p.content[0] else {+ panic!()+ };+ let HyperlinkTarget::ExternalUrl(url) = &h.target else {+ panic!()+ };+ assert_eq!(url, "https://example.com");+ }++ // ── §M.2.2 AlternateContent choice (the preferred branch) ───────────++ #[test]+ fn rewrites_image_inside_alternate_content_choice() {+ // Regression for the fix: the renderer prefers a supported <mc:Choice>+ // over <mc:Fallback>, so image rIds inside a choice must be rewritten+ // too — previously only the fallback was walked.+ let ac = AlternateContent {+ choices: vec![McChoice {+ requires: vec![McRequires::Wps],+ content: vec![Inline::Image(Box::new(picture_with_blip("rId1")))],+ }],+ fallback: None,+ };+ let mut blocks = vec![Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![Inline::AlternateContent(ac)],+ rsids: ParagraphRevisionIds::default(),+ }))];+ let remap = remap_one("rId1", "header3.xml::rId1");+ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!()+ };+ let Inline::AlternateContent(ac) = &p.content[0] else {+ panic!()+ };+ let Inline::Image(img) = &ac.choices[0].content[0] else {+ panic!()+ };+ let v = crate::render::resolve::images::extract_image_rel_id(img).unwrap();+ assert_eq!(v.as_str(), "header3.xml::rId1");+ }++ // ── VML group child recursion ───────────────────────────────────────++ #[test]+ fn recurses_into_vml_group_children() {+ let child = VmlPrimitive::Shape(VmlShape {+ common: VmlCommonAttrs {+ image_data: Some(VmlImageData {+ rel_id: Some(RelId::new("rId1")),+ title: None,+ }),+ ..VmlCommonAttrs::default()+ },+ shape_type_ref: None,+ vml_path: None,+ });+ let pict = Pict {+ shape_type: None,+ primitives: vec![VmlPrimitive::Group(Box::new(VmlGroup {+ common: VmlCommonAttrs::default(),+ coord_size: None,+ coord_origin: None,+ children: vec![child],+ }))],+ };+ let mut blocks = vec![Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![Inline::Pict(pict)],+ rsids: ParagraphRevisionIds::default(),+ }))];+ let remap = remap_one("rId1", "grouped");+ rewrite_part_rels_in_blocks(&mut blocks, &remap);++ let Block::Paragraph(p) = &blocks[0] else {+ panic!()+ };+ let Inline::Pict(pict) = &p.content[0] else {+ panic!()+ };+ let VmlPrimitive::Group(g) = &pict.primitives[0] else {+ panic!()+ };+ let VmlPrimitive::Shape(s) = &g.children[0] else {+ panic!()+ };+ assert_eq!(+ s.common+ .image_data+ .as_ref()+ .unwrap()+ .rel_id+ .as_ref()+ .unwrap()+ .as_str(),+ "grouped"+ );+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/serde_xml.rs b/crates/liteparse-docx/src/docx/parse/serde_xml.rsnew file mode 100644index 0000000..5b5bd3c--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/serde_xml.rs@@ -0,0 +1,11 @@+//! Shared helpers for serde-driven OOXML parsers.++use serde::de::DeserializeOwned;++use crate::docx::error::Result;++/// Deserialize an OOXML part into a schema type, mapping quick-xml's error+/// into the crate's `ParseError`.+pub fn from_xml<T: DeserializeOwned>(data: &[u8]) -> Result<T> {+ Ok(quick_xml::de::from_reader(data)?)+}diff --git a/crates/liteparse-docx/src/docx/parse/settings.rs b/crates/liteparse-docx/src/docx/parse/settings.rsnew file mode 100644index 0000000..fda0f8d--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/settings.rs@@ -0,0 +1,76 @@+//! Parser for `word/settings.xml`.++use serde::Deserialize;++use crate::docx::dimension::{Dimension, Twips};+use crate::docx::error::Result;+use crate::docx::model::{DocumentSettings, RevisionSaveId};+use crate::docx::parse::primitives::OnOff;+use crate::docx::parse::primitives::units::deserialize_optional_nonnegative_dimension;+use crate::docx::parse::serde_xml::from_xml;++/// Parse `word/settings.xml`. Entry point: deserializes into an intermediate+/// schema, then maps to the model type.+pub fn parse_settings(data: &[u8]) -> Result<DocumentSettings> {+ from_xml::<SettingsXml>(data).map(Into::into)+}++#[derive(Deserialize, Default)]+struct SettingsXml {+ #[serde(rename = "defaultTabStop", default)]+ default_tab_stop: Option<DimensionVal<Twips>>,+ #[serde(rename = "evenAndOddHeaders", default)]+ even_and_odd_headers: Option<OnOff>,+ #[serde(default)]+ rsids: Option<RsidsXml>,+}++#[derive(Deserialize, Default)]+struct RsidsXml {+ #[serde(rename = "rsidRoot", default)]+ rsid_root: Option<StringVal>,+ #[serde(rename = "rsid", default)]+ rsids: Vec<StringVal>,+}++#[derive(Deserialize)]+#[serde(bound(deserialize = "U: crate::docx::dimension::Unit"))]+struct DimensionVal<U: crate::docx::dimension::Unit> {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "deserialize_optional_nonnegative_dimension"+ )]+ val: Option<Dimension<U>>,+}++#[derive(Deserialize)]+struct StringVal {+ #[serde(rename = "@val")]+ val: String,+}++impl From<SettingsXml> for DocumentSettings {+ fn from(x: SettingsXml) -> Self {+ let mut s = DocumentSettings::default();+ // A malformed value leaves the built-in default in place rather than+ // failing the document.+ if let Some(t) = x.default_tab_stop.and_then(|t| t.val) {+ s.default_tab_stop = t;+ }+ if let Some(OnOff(on)) = x.even_and_odd_headers {+ s.even_and_odd_headers = on;+ }+ if let Some(r) = x.rsids {+ if let Some(root) = r.rsid_root {+ s.rsid_root = RevisionSaveId::from_hex(&root.val);+ }+ s.rsids = r+ .rsids+ .into_iter()+ .filter_map(|v| RevisionSaveId::from_hex(&v.val))+ .collect();+ }+ s+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/styles.rs b/crates/liteparse-docx/src/docx/parse/styles.rsnew file mode 100644index 0000000..444f2d0--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/styles.rs@@ -0,0 +1,476 @@+//! Parser for `word/styles.xml` — parses style definitions as-is.+//! No inheritance resolution — `basedOn` references are preserved.++use serde::Deserialize;++use crate::docx::error::Result;+use crate::docx::model::*;+use crate::docx::parse::properties::schema::paragraph::PPrXml;+use crate::docx::parse::properties::schema::run::RPrXml;+use crate::docx::parse::properties::schema::section::SectPrXml;+use crate::docx::parse::properties::schema::table::{TblPrXml, TcPrXml, TrPrXml};+use crate::docx::parse::serde_xml::from_xml;++/// Parse `word/styles.xml` into a raw `StyleSheet`.+pub fn parse_styles(data: &[u8]) -> Result<StyleSheet> {+ if data.is_empty() {+ return Ok(StyleSheet::default());+ }+ from_xml::<StylesXml>(data).map(Into::into)+}++#[derive(Deserialize, Default)]+struct StylesXml {+ #[serde(rename = "docDefaults", default)]+ doc_defaults: Option<DocDefaultsXml>,+ #[serde(rename = "latentStyles", default)]+ latent_styles: Option<LatentStylesXml>,+ #[serde(rename = "style", default)]+ styles: Vec<StyleXml>,+}++#[derive(Deserialize)]+struct DocDefaultsXml {+ #[serde(rename = "rPrDefault", default)]+ r_pr_default: Option<RPrDefaultXml>,+ #[serde(rename = "pPrDefault", default)]+ p_pr_default: Option<PPrDefaultXml>,+}++#[derive(Deserialize)]+struct RPrDefaultXml {+ #[serde(rename = "rPr", default)]+ r_pr: Option<RPrXml>,+}++#[derive(Deserialize)]+struct PPrDefaultXml {+ #[serde(rename = "pPr", default)]+ p_pr: Option<PPrXml>,+}++#[derive(Deserialize)]+struct StyleXml {+ /// `@w:type` — style kind. Absent defaults to `paragraph` per §17.7.+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::or_default"+ )]+ ty: StStyleType,+ #[serde(rename = "@styleId", default)]+ style_id: Option<String>,+ #[serde(rename = "@default", default)]+ default: Option<AttrBool>,++ #[serde(rename = "name", default)]+ name: Option<ValString>,+ #[serde(rename = "basedOn", default)]+ based_on: Option<ValString>,+ #[serde(rename = "pPr", default)]+ p_pr: Option<PPrXml>,+ #[serde(rename = "rPr", default)]+ r_pr: Option<RPrXml>,+ #[serde(rename = "tblPr", default)]+ tbl_pr: Option<TblPrXml>,+ #[serde(rename = "tblStylePr", default)]+ tbl_style_pr: Vec<TblStylePrXml>,+}++#[derive(Deserialize)]+struct TblStylePrXml {+ #[serde(+ rename = "@type",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ ty: Option<StTblStylePrType>,+ #[serde(rename = "pPr", default)]+ p_pr: Option<PPrXml>,+ #[serde(rename = "rPr", default)]+ r_pr: Option<RPrXml>,+ #[serde(rename = "tblPr", default)]+ tbl_pr: Option<TblPrXml>,+ #[serde(rename = "trPr", default)]+ tr_pr: Option<TrPrXml>,+ #[serde(rename = "tcPr", default)]+ tc_pr: Option<TcPrXml>,+}++#[derive(Deserialize)]+struct LatentStylesXml {+ #[serde(rename = "@defLockedState", default)]+ def_locked_state: Option<AttrBool>,+ #[serde(+ rename = "@defUIPriority",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ def_ui_priority: Option<u32>,+ #[serde(rename = "@defSemiHidden", default)]+ def_semi_hidden: Option<AttrBool>,+ #[serde(rename = "@defUnhideWhenUsed", default)]+ def_unhide_when_used: Option<AttrBool>,+ #[serde(rename = "@defQFormat", default)]+ def_q_format: Option<AttrBool>,+ #[serde(+ rename = "@count",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ count: Option<u32>,+ #[serde(rename = "lsdException", default)]+ exceptions: Vec<LsdExceptionXml>,+}++#[derive(Deserialize)]+struct LsdExceptionXml {+ #[serde(rename = "@name", default)]+ name: Option<String>,+ #[serde(rename = "@locked", default)]+ locked: Option<AttrBool>,+ #[serde(+ rename = "@uiPriority",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ ui_priority: Option<u32>,+ #[serde(rename = "@semiHidden", default)]+ semi_hidden: Option<AttrBool>,+ #[serde(rename = "@unhideWhenUsed", default)]+ unhide_when_used: Option<AttrBool>,+ #[serde(rename = "@qFormat", default)]+ q_format: Option<AttrBool>,+}++// ── ST enums local to styles ─────────────────────────────────────────────++#[derive(Clone, Copy, Debug, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+enum StStyleType {+ #[default]+ Paragraph,+ Character,+ Table,+ Numbering,+}++impl From<StStyleType> for StyleType {+ fn from(s: StStyleType) -> Self {+ match s {+ StStyleType::Paragraph => Self::Paragraph,+ StStyleType::Character => Self::Character,+ StStyleType::Table => Self::Table,+ StStyleType::Numbering => Self::Numbering,+ }+ }+}++#[derive(Clone, Copy, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+enum StTblStylePrType {+ FirstRow,+ LastRow,+ FirstCol,+ LastCol,+ Band1Vert,+ Band2Vert,+ Band1Horz,+ Band2Horz,+ NeCell,+ NwCell,+ SeCell,+ SwCell,+ WholeTable,+}++impl From<StTblStylePrType> for TableStyleOverrideType {+ fn from(s: StTblStylePrType) -> Self {+ match s {+ StTblStylePrType::FirstRow => Self::FirstRow,+ StTblStylePrType::LastRow => Self::LastRow,+ StTblStylePrType::FirstCol => Self::FirstCol,+ StTblStylePrType::LastCol => Self::LastCol,+ StTblStylePrType::Band1Vert => Self::Band1Vert,+ StTblStylePrType::Band2Vert => Self::Band2Vert,+ StTblStylePrType::Band1Horz => Self::Band1Horz,+ StTblStylePrType::Band2Horz => Self::Band2Horz,+ StTblStylePrType::NeCell => Self::NeCell,+ StTblStylePrType::NwCell => Self::NwCell,+ StTblStylePrType::SeCell => Self::SeCell,+ StTblStylePrType::SwCell => Self::SwCell,+ StTblStylePrType::WholeTable => Self::WholeTable,+ }+ }+}++// ── shared helpers ───────────────────────────────────────────────────────++#[derive(Deserialize)]+struct ValString {+ #[serde(rename = "@val")]+ val: String,+}++use crate::docx::parse::primitives::AttrBool;++// Suppress unused warnings on schema-private fields used only via serde.+#[allow(dead_code)]+const _: Option<SectPrXml> = None;++// ── schema → model conversion ────────────────────────────────────────────++impl From<StylesXml> for StyleSheet {+ fn from(x: StylesXml) -> Self {+ let mut sheet = StyleSheet::default();++ if let Some(dd) = x.doc_defaults {+ if let Some(r) = dd.r_pr_default.and_then(|d| d.r_pr) {+ let (rp, _) = r.split();+ sheet.doc_defaults_run = rp;+ }+ if let Some(p) = dd.p_pr_default.and_then(|d| d.p_pr) {+ sheet.doc_defaults_paragraph = p.split().properties;+ }+ }++ for s in x.styles {+ if let Some((id, style)) = convert_style(s) {+ sheet.styles.insert(id, style);+ }+ }++ sheet.latent_styles = x.latent_styles.map(Into::into);+ sheet+ }+}++fn convert_style(s: StyleXml) -> Option<(StyleId, Style)> {+ let id = StyleId::new(s.style_id?);+ let style_type = StyleType::from(s.ty);+ let is_default = s.default.map(|b| b.0).unwrap_or(false);++ let (mut paragraph_properties, mut run_properties_from_ppr): (+ Option<ParagraphProperties>,+ Option<RunProperties>,+ ) = (None, None);+ if let Some(p) = s.p_pr {+ let parsed = p.split();+ paragraph_properties = Some(parsed.properties);+ run_properties_from_ppr = parsed.run_properties;+ }++ let run_properties = s.r_pr.map(|r| r.split().0).or(run_properties_from_ppr);++ let table_properties = s.tbl_pr.map(|t| t.split().0);++ let table_style_overrides = s+ .tbl_style_pr+ .into_iter()+ .filter_map(convert_override)+ .collect();++ Some((+ id,+ Style {+ name: s.name.map(|v| v.val),+ style_type,+ based_on: s.based_on.map(|v| StyleId::new(v.val)),+ is_default,+ paragraph_properties,+ run_properties,+ table_properties,+ table_style_overrides,+ },+ ))+}++/// An unrecognized `@type` leaves no region for the override to apply to, so+/// the whole `tblStylePr` entry is dropped rather than misapplied.+fn convert_override(x: TblStylePrXml) -> Option<TableStyleOverride> {+ Some(TableStyleOverride {+ override_type: x.ty?.into(),+ paragraph_properties: x.p_pr.map(|p| p.split().properties),+ run_properties: x.r_pr.map(|r| r.split().0),+ table_properties: x.tbl_pr.map(|t| t.split().0),+ table_row_properties: x.tr_pr.map(Into::into),+ table_cell_properties: x.tc_pr.map(Into::into),+ })+}++impl From<LatentStylesXml> for LatentStyles {+ fn from(x: LatentStylesXml) -> Self {+ Self {+ default_locked_state: x.def_locked_state.map(|b| b.0),+ default_ui_priority: x.def_ui_priority,+ default_semi_hidden: x.def_semi_hidden.map(|b| b.0),+ default_unhide_when_used: x.def_unhide_when_used.map(|b| b.0),+ default_q_format: x.def_q_format.map(|b| b.0),+ count: x.count,+ exceptions: x.exceptions.into_iter().map(Into::into).collect(),+ }+ }+}++impl From<LsdExceptionXml> for LatentStyleException {+ fn from(x: LsdExceptionXml) -> Self {+ Self {+ name: x.name,+ locked: x.locked.map(|b| b.0),+ ui_priority: x.ui_priority,+ semi_hidden: x.semi_hidden.map(|b| b.0),+ unhide_when_used: x.unhide_when_used.map(|b| b.0),+ q_format: x.q_format.map(|b| b.0),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;++ fn sid(s: &str) -> StyleId {+ StyleId::new(s)+ }++ fn parse(inner: &str) -> StyleSheet {+ let xml = format!("<w:styles {NS}>{inner}</w:styles>");+ parse_styles(xml.as_bytes()).expect("styles must parse")+ }++ #[test]+ fn empty_input_returns_default_stylesheet() {+ let sheet = parse_styles(b"").unwrap();+ assert!(sheet.styles.is_empty());+ assert!(sheet.latent_styles.is_none());+ }++ #[test]+ fn style_type_defaults_to_paragraph_and_maps_all_kinds() {+ let sheet = parse(+ r#"<w:style w:styleId="NoType"><w:name w:val="No Type"/></w:style>+ <w:style w:type="character" w:styleId="Char"/>+ <w:style w:type="table" w:styleId="Tbl"/>+ <w:style w:type="numbering" w:styleId="Num"/>"#,+ );+ assert_eq!(+ sheet.styles[&sid("NoType")].style_type,+ StyleType::Paragraph+ );+ assert_eq!(sheet.styles[&sid("Char")].style_type, StyleType::Character);+ assert_eq!(sheet.styles[&sid("Tbl")].style_type, StyleType::Table);+ assert_eq!(sheet.styles[&sid("Num")].style_type, StyleType::Numbering);+ }++ #[test]+ fn name_based_on_and_default_flag_preserved() {+ let sheet = parse(+ r#"<w:style w:type="paragraph" w:styleId="Heading1" w:default="1">+ <w:name w:val="heading 1"/>+ <w:basedOn w:val="Normal"/>+ </w:style>"#,+ );+ let s = &sheet.styles[&sid("Heading1")];+ assert_eq!(s.name.as_deref(), Some("heading 1"));+ assert_eq!(s.based_on, Some(sid("Normal")));+ assert!(s.is_default);+ }++ #[test]+ fn style_without_style_id_is_dropped() {+ // styleId is required; a style missing it can't be referenced, so it's+ // dropped rather than aborting the whole styles.xml parse.+ let sheet = parse(+ r#"<w:style w:type="paragraph"><w:name w:val="Anon"/></w:style>+ <w:style w:type="paragraph" w:styleId="Kept"/>"#,+ );+ assert_eq!(sheet.styles.len(), 1);+ assert!(sheet.styles.contains_key(&sid("Kept")));+ }++ #[test]+ fn doc_defaults_run_and_paragraph_extracted() {+ let sheet = parse(+ r#"<w:docDefaults>+ <w:rPrDefault><w:rPr><w:b/></w:rPr></w:rPrDefault>+ <w:pPrDefault><w:pPr><w:jc w:val="center"/></w:pPr></w:pPrDefault>+ </w:docDefaults>"#,+ );+ assert_eq!(sheet.doc_defaults_run.bold, Some(true));+ assert_eq!(+ sheet.doc_defaults_paragraph.alignment,+ Some(Alignment::Center)+ );+ }++ #[test]+ fn all_table_style_override_types_map() {+ let names = [+ "firstRow",+ "lastRow",+ "firstCol",+ "lastCol",+ "band1Vert",+ "band2Vert",+ "band1Horz",+ "band2Horz",+ "neCell",+ "nwCell",+ "seCell",+ "swCell",+ "wholeTable",+ ];+ let inner: String = names+ .iter()+ .map(|t| format!(r#"<w:tblStylePr w:type="{t}"><w:rPr><w:b/></w:rPr></w:tblStylePr>"#))+ .collect();+ let sheet = parse(&format!(+ r#"<w:style w:type="table" w:styleId="TblStyle">{inner}</w:style>"#+ ));+ let got: Vec<TableStyleOverrideType> = sheet.styles[&sid("TblStyle")]+ .table_style_overrides+ .iter()+ .map(|o| o.override_type)+ .collect();+ assert_eq!(got.len(), 13);+ for expected in [+ TableStyleOverrideType::FirstRow,+ TableStyleOverrideType::LastRow,+ TableStyleOverrideType::FirstCol,+ TableStyleOverrideType::LastCol,+ TableStyleOverrideType::Band1Vert,+ TableStyleOverrideType::Band2Vert,+ TableStyleOverrideType::Band1Horz,+ TableStyleOverrideType::Band2Horz,+ TableStyleOverrideType::NeCell,+ TableStyleOverrideType::NwCell,+ TableStyleOverrideType::SeCell,+ TableStyleOverrideType::SwCell,+ TableStyleOverrideType::WholeTable,+ ] {+ assert!(+ got.contains(&expected),+ "missing override type {expected:?}"+ );+ }+ }++ #[test]+ fn latent_styles_and_exceptions_parsed() {+ let sheet = parse(+ r#"<w:latentStyles w:count="371" w:defUIPriority="99">+ <w:lsdException w:name="Normal" w:uiPriority="0" w:qFormat="1"/>+ <w:lsdException w:name="heading 1" w:semiHidden="1"/>+ </w:latentStyles>"#,+ );+ let ls = sheet.latent_styles.expect("latentStyles present");+ assert_eq!(ls.count, Some(371));+ assert_eq!(ls.default_ui_priority, Some(99));+ assert_eq!(ls.exceptions.len(), 2);+ assert_eq!(ls.exceptions[0].name.as_deref(), Some("Normal"));+ assert_eq!(ls.exceptions[0].q_format, Some(true));+ assert_eq!(ls.exceptions[1].semi_hidden, Some(true));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/theme/mod.rs b/crates/liteparse-docx/src/docx/parse/theme/mod.rsnew file mode 100644index 0000000..d7859ec--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/theme/mod.rs@@ -0,0 +1,409 @@+//! Parser for `word/theme/theme1.xml` (DrawingML theme).+//!+//! Hierarchical parsing per §20.1.6.9 `CT_OfficeStyleSheet`. Color transforms+//! (`satMod`, `shade`, `tint`, `alpha`, `lumMod`, `lumOff`) are accepted+//! syntactically but discarded — the resolved model stores only flat RGB.++mod script;++use serde::Deserialize;++use crate::docx::error::Result;+use crate::docx::model::{+ EffectList, Outline, Theme, ThemeColorScheme, ThemeFontScheme, ThemeScriptFont,+};+use crate::docx::parse::drawing::schema::effect::EffectListXml;+use crate::docx::parse::drawing::schema::stroke::OutlineXml;+use crate::docx::parse::primitives::HexColor;+use crate::docx::parse::serde_xml::from_xml;++use self::script::parse_script_tag;++pub fn parse_theme(data: &[u8]) -> Result<Theme> {+ if data.is_empty() {+ return Ok(Theme::default());+ }+ from_xml::<ThemeXml>(data).map(Into::into)+}++#[derive(Deserialize, Default)]+struct ThemeXml {+ #[serde(rename = "themeElements", default)]+ theme_elements: Option<ThemeElementsXml>,+}++#[derive(Deserialize, Default)]+struct ThemeElementsXml {+ #[serde(rename = "clrScheme", default)]+ clr_scheme: Option<ClrSchemeXml>,+ #[serde(rename = "fontScheme", default)]+ font_scheme: Option<FontSchemeXml>,+ #[serde(rename = "fmtScheme", default)]+ fmt_scheme: Option<FmtSchemeXml>,+}++#[derive(Deserialize, Default)]+struct FmtSchemeXml {+ #[serde(rename = "fillStyleLst", default)]+ fill_style_lst: Option<FillStyleLstXml>,+ #[serde(rename = "lnStyleLst", default)]+ ln_style_lst: Option<LnStyleLstXml>,+ #[serde(rename = "effectStyleLst", default)]+ effect_style_lst: Option<EffectStyleLstXml>,+}++/// §20.1.4.1.13 CT_FillStyleList — theme fill styles (spec requires ≥3). Each+/// child is one of the DrawingML fill choices, routed through the shared+/// `DrawingFillXml` parser.+#[derive(Deserialize, Default)]+struct FillStyleLstXml {+ #[serde(rename = "$value", default)]+ fills: Vec<crate::docx::parse::drawing::schema::fill::DrawingFillXml>,+}++/// §20.1.4.1.21 CT_LineStyleList — exactly 3 `<a:ln>` entries per spec.+#[derive(Deserialize, Default)]+struct LnStyleLstXml {+ #[serde(rename = "ln", default)]+ lines: Vec<OutlineXml>,+}++#[derive(Deserialize, Default)]+struct EffectStyleLstXml {+ #[serde(rename = "effectStyle", default)]+ effect_styles: Vec<EffectStyleXml>,+}++/// §20.1.4.1.11 CT_EffectStyleItem — an effect style entry. May include+/// `scene3d`/`sp3d` siblings (ignored — Tier-3 3D extrusion).+#[derive(Deserialize, Default)]+struct EffectStyleXml {+ #[serde(rename = "effectLst", default)]+ effect_lst: Option<EffectListXml>,+}++#[derive(Deserialize, Default)]+struct ClrSchemeXml {+ #[serde(default)]+ dk1: Option<ColorChoice>,+ #[serde(default)]+ lt1: Option<ColorChoice>,+ #[serde(default)]+ dk2: Option<ColorChoice>,+ #[serde(default)]+ lt2: Option<ColorChoice>,+ #[serde(default)]+ accent1: Option<ColorChoice>,+ #[serde(default)]+ accent2: Option<ColorChoice>,+ #[serde(default)]+ accent3: Option<ColorChoice>,+ #[serde(default)]+ accent4: Option<ColorChoice>,+ #[serde(default)]+ accent5: Option<ColorChoice>,+ #[serde(default)]+ accent6: Option<ColorChoice>,+ #[serde(default)]+ hlink: Option<ColorChoice>,+ #[serde(rename = "folHlink", default)]+ fol_hlink: Option<ColorChoice>,+}++/// A slot's single color-choice element. §20.1.2.3 defines several; we resolve+/// `srgbClr` and `sysClr` and ignore the rest (scRgbClr, hslClr, schemeClr,+/// prstClr) by leaving their fields absent.+#[derive(Deserialize, Default)]+struct ColorChoice {+ #[serde(rename = "srgbClr", default)]+ srgb: Option<SrgbClr>,+ #[serde(rename = "sysClr", default)]+ sys: Option<SysClr>,+}++#[derive(Deserialize)]+struct SrgbClr {+ #[serde(+ rename = "@val",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ val: Option<HexColor>,+}++#[derive(Deserialize)]+struct SysClr {+ #[serde(+ rename = "@lastClr",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ last_clr: Option<HexColor>,+}++impl ColorChoice {+ fn resolve(self) -> Option<u32> {+ if let Some(s) = self.srgb {+ return s.val.and_then(HexColor::rgb);+ }+ if let Some(s) = self.sys {+ return s.last_clr.and_then(HexColor::rgb);+ }+ None+ }+}++#[derive(Deserialize, Default)]+struct FontSchemeXml {+ #[serde(rename = "majorFont", default)]+ major: Option<FontCollectionXml>,+ #[serde(rename = "minorFont", default)]+ minor: Option<FontCollectionXml>,+}++#[derive(Deserialize, Default)]+struct FontCollectionXml {+ #[serde(default)]+ latin: Option<TypefaceXml>,+ #[serde(default)]+ ea: Option<TypefaceXml>,+ #[serde(default)]+ cs: Option<TypefaceXml>,+ #[serde(rename = "font", default)]+ fonts: Vec<ScriptFontXml>,+}++#[derive(Deserialize)]+struct TypefaceXml {+ #[serde(rename = "@typeface", default)]+ typeface: String,+}++#[derive(Deserialize)]+struct ScriptFontXml {+ #[serde(rename = "@script")]+ script: String,+ #[serde(rename = "@typeface", default)]+ typeface: String,+}++impl From<ThemeXml> for Theme {+ fn from(x: ThemeXml) -> Self {+ let mut theme = Theme::default();+ if let Some(elements) = x.theme_elements {+ if let Some(cs) = elements.clr_scheme {+ theme.color_scheme = cs.into();+ }+ if let Some(fs) = elements.font_scheme {+ if let Some(major) = fs.major {+ theme.major_font = major.into();+ }+ if let Some(minor) = fs.minor {+ theme.minor_font = minor.into();+ }+ }+ if let Some(fmt) = elements.fmt_scheme {+ if let Some(list) = fmt.fill_style_lst {+ theme.fill_styles = list.fills.into_iter().map(Into::into).collect();+ }+ if let Some(list) = fmt.ln_style_lst {+ theme.line_styles = list.lines.into_iter().map(Outline::from).collect();+ }+ if let Some(list) = fmt.effect_style_lst {+ theme.effect_styles = list+ .effect_styles+ .into_iter()+ .map(|es| es.effect_lst.map(EffectList::from).unwrap_or_default())+ .collect();+ }+ }+ }+ theme+ }+}++impl From<ClrSchemeXml> for ThemeColorScheme {+ fn from(x: ClrSchemeXml) -> Self {+ let mut s = ThemeColorScheme::default();+ assign(&mut s.dark1, x.dk1);+ assign(&mut s.light1, x.lt1);+ assign(&mut s.dark2, x.dk2);+ assign(&mut s.light2, x.lt2);+ assign(&mut s.accent1, x.accent1);+ assign(&mut s.accent2, x.accent2);+ assign(&mut s.accent3, x.accent3);+ assign(&mut s.accent4, x.accent4);+ assign(&mut s.accent5, x.accent5);+ assign(&mut s.accent6, x.accent6);+ assign(&mut s.hyperlink, x.hlink);+ assign(&mut s.followed_hyperlink, x.fol_hlink);+ s+ }+}++fn assign(slot: &mut u32, choice: Option<ColorChoice>) {+ if let Some(rgb) = choice.and_then(ColorChoice::resolve) {+ *slot = rgb;+ }+}++impl From<FontCollectionXml> for ThemeFontScheme {+ fn from(x: FontCollectionXml) -> Self {+ Self {+ latin: x.latin.map(|t| t.typeface).unwrap_or_default(),+ east_asian: x.ea.map(|t| t.typeface).unwrap_or_default(),+ complex_script: x.cs.map(|t| t.typeface).unwrap_or_default(),+ script_fonts: x+ .fonts+ .into_iter()+ .map(|f| ThemeScriptFont {+ script: parse_script_tag(&f.script),+ typeface: f.typeface,+ })+ .collect(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::ScriptTag;++ const MINIMAL_THEME: &str = r#"<?xml version="1.0" encoding="UTF-8"?>+<a:theme xmlns:a="urn:a" name="Office">+ <a:themeElements>+ <a:clrScheme name="Office">+ <a:dk1><a:srgbClr val="000000"/></a:dk1>+ <a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>+ <a:accent1><a:srgbClr val="4F81BD"/></a:accent1>+ <a:hlink><a:srgbClr val="0000FF"/></a:hlink>+ <a:folHlink><a:srgbClr val="800080"/></a:folHlink>+ </a:clrScheme>+ <a:fontScheme name="Office">+ <a:majorFont>+ <a:latin typeface="Calibri Light"/>+ <a:ea typeface=""/>+ <a:cs typeface=""/>+ <a:font script="Hans" typeface="Noto Sans SC"/>+ </a:majorFont>+ <a:minorFont>+ <a:latin typeface="Calibri"/>+ <a:ea typeface=""/>+ <a:cs typeface=""/>+ </a:minorFont>+ </a:fontScheme>+ <a:fmtScheme name="Office">+ <a:fillStyleLst/>+ </a:fmtScheme>+ </a:themeElements>+ <a:objectDefaults/>+ <a:extraClrSchemeLst/>+</a:theme>"#;++ #[test]+ fn end_to_end_theme_parse() {+ let theme = parse_theme(MINIMAL_THEME.as_bytes()).unwrap();++ assert_eq!(theme.color_scheme.dark1, 0x000000);+ assert_eq!(theme.color_scheme.light1, 0xFFFFFF);+ assert_eq!(theme.color_scheme.accent1, 0x4F81BD);+ assert_eq!(theme.color_scheme.hyperlink, 0x0000FF);+ assert_eq!(theme.color_scheme.followed_hyperlink, 0x800080);++ assert_eq!(theme.major_font.latin, "Calibri Light");+ assert_eq!(theme.minor_font.latin, "Calibri");+ assert_eq!(theme.major_font.script_fonts.len(), 1);+ assert_eq!(theme.major_font.script_fonts[0].script, ScriptTag::Hans);+ assert_eq!(theme.major_font.script_fonts[0].typeface, "Noto Sans SC");+ }++ #[test]+ fn empty_input_returns_default_theme() {+ let theme = parse_theme(b"").unwrap();+ assert_eq!(theme.color_scheme.dark1, 0);+ assert!(theme.major_font.latin.is_empty());+ }++ #[test]+ fn missing_theme_elements_keeps_defaults() {+ let xml = r#"<a:theme xmlns:a="urn:a"><a:objectDefaults/></a:theme>"#;+ let theme = parse_theme(xml.as_bytes()).unwrap();+ assert_eq!(theme.color_scheme.dark1, 0);+ assert!(theme.minor_font.latin.is_empty());+ }++ #[test]+ fn srgb_transforms_are_tolerated() {+ let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:clrScheme>+ <a:accent1>+ <a:srgbClr val="DEADBE">+ <a:shade val="75000"/>+ <a:satMod val="200000"/>+ </a:srgbClr>+ </a:accent1>+ </a:clrScheme></a:themeElements></a:theme>"#;+ let theme = parse_theme(xml.as_bytes()).unwrap();+ assert_eq!(theme.color_scheme.accent1, 0xDEADBE);+ }++ #[test]+ fn fill_style_lst_parsed_into_fill_styles() {+ let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:fmtScheme>+ <a:fillStyleLst>+ <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>+ <a:gradFill><a:gsLst>+ <a:gs pos="0"><a:schemeClr val="phClr"/></a:gs>+ <a:gs pos="100000"><a:schemeClr val="phClr"/></a:gs>+ </a:gsLst><a:lin ang="5400000"/></a:gradFill>+ <a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>+ </a:fillStyleLst>+ </a:fmtScheme></a:themeElements></a:theme>"#;+ let theme = parse_theme(xml.as_bytes()).unwrap();+ assert_eq!(theme.fill_styles.len(), 3);+ assert!(matches!(+ &theme.fill_styles[0],+ crate::docx::model::DrawingFill::Solid(_)+ ));+ assert!(matches!(+ &theme.fill_styles[1],+ crate::docx::model::DrawingFill::Gradient(_)+ ));+ assert!(matches!(+ &theme.fill_styles[2],+ crate::docx::model::DrawingFill::Solid(_)+ ));+ }++ #[test]+ fn sys_clr_uses_last_clr() {+ let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:clrScheme>+ <a:lt1><a:sysClr val="window" lastClr="ABCDEF"/></a:lt1>+ </a:clrScheme></a:themeElements></a:theme>"#;+ let theme = parse_theme(xml.as_bytes()).unwrap();+ assert_eq!(theme.color_scheme.light1, 0xABCDEF);+ }++ #[test]+ fn unknown_script_preserved_as_other() {+ let xml = r#"<a:theme xmlns:a="urn:a"><a:themeElements><a:fontScheme>+ <a:majorFont>+ <a:latin typeface="L"/>+ <a:ea typeface=""/>+ <a:cs typeface=""/>+ <a:font script="Xxxx" typeface="FallbackFace"/>+ </a:majorFont>+ <a:minorFont>+ <a:latin typeface=""/>+ <a:ea typeface=""/>+ <a:cs typeface=""/>+ </a:minorFont>+ </a:fontScheme></a:themeElements></a:theme>"#;+ let theme = parse_theme(xml.as_bytes()).unwrap();+ assert_eq!(theme.major_font.script_fonts.len(), 1);+ match &theme.major_font.script_fonts[0].script {+ ScriptTag::Other(s) => assert_eq!(&**s, "Xxxx"),+ other => panic!("expected Other, got {other:?}"),+ }+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/theme/script.rs b/crates/liteparse-docx/src/docx/parse/theme/script.rsnew file mode 100644index 0000000..8691503--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/theme/script.rs@@ -0,0 +1,102 @@+//! ISO 15924 script-code mapping for `<a:font script="...">` (§20.1.4.1.16).++use crate::docx::model::ScriptTag;++/// Known ISO 15924 script codes referenced by OOXML theme font schemes.+///+/// The list matches the variants enumerated on `ScriptTag`. Unknown codes+/// fall through to `ScriptTag::Other`.+const SCRIPT_TAGS: &[(&str, ScriptTag)] = &[+ ("Arab", ScriptTag::Arab),+ ("Armn", ScriptTag::Armn),+ ("Beng", ScriptTag::Beng),+ ("Bopo", ScriptTag::Bopo),+ ("Bugi", ScriptTag::Bugi),+ ("Cans", ScriptTag::Cans),+ ("Cher", ScriptTag::Cher),+ ("Deva", ScriptTag::Deva),+ ("Ethi", ScriptTag::Ethi),+ ("Geor", ScriptTag::Geor),+ ("Gujr", ScriptTag::Gujr),+ ("Guru", ScriptTag::Guru),+ ("Hang", ScriptTag::Hang),+ ("Hans", ScriptTag::Hans),+ ("Hant", ScriptTag::Hant),+ ("Hebr", ScriptTag::Hebr),+ ("Java", ScriptTag::Java),+ ("Jpan", ScriptTag::Jpan),+ ("Khmr", ScriptTag::Khmr),+ ("Knda", ScriptTag::Knda),+ ("Laoo", ScriptTag::Laoo),+ ("Lisu", ScriptTag::Lisu),+ ("Mlym", ScriptTag::Mlym),+ ("Mong", ScriptTag::Mong),+ ("Mymr", ScriptTag::Mymr),+ ("Nkoo", ScriptTag::Nkoo),+ ("Olck", ScriptTag::Olck),+ ("Orya", ScriptTag::Orya),+ ("Osma", ScriptTag::Osma),+ ("Phag", ScriptTag::Phag),+ ("Sinh", ScriptTag::Sinh),+ ("Sora", ScriptTag::Sora),+ ("Syre", ScriptTag::Syre),+ ("Syrj", ScriptTag::Syrj),+ ("Syrn", ScriptTag::Syrn),+ ("Syrc", ScriptTag::Syrc),+ ("Tale", ScriptTag::Tale),+ ("Talu", ScriptTag::Talu),+ ("Taml", ScriptTag::Taml),+ ("Telu", ScriptTag::Telu),+ ("Tfng", ScriptTag::Tfng),+ ("Thaa", ScriptTag::Thaa),+ ("Thai", ScriptTag::Thai),+ ("Tibt", ScriptTag::Tibt),+ ("Uigh", ScriptTag::Uigh),+ ("Viet", ScriptTag::Viet),+ ("Yiii", ScriptTag::Yiii),+];++/// Parse an ISO 15924 script code into a `ScriptTag`.+pub fn parse_script_tag(s: &str) -> ScriptTag {+ if let Some((_, tag)) = SCRIPT_TAGS.iter().find(|(name, _)| *name == s) {+ return tag.clone();+ }+ log::warn!("theme: unrecognized script tag {s:?}");+ ScriptTag::Other(s.to_string().into_boxed_str())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn known_tag_is_mapped() {+ assert_eq!(parse_script_tag("Hans"), ScriptTag::Hans);+ assert_eq!(parse_script_tag("Arab"), ScriptTag::Arab);+ }++ #[test]+ fn unknown_tag_preserves_full_string() {+ match parse_script_tag("Xxxx-long") {+ ScriptTag::Other(s) => assert_eq!(&*s, "Xxxx-long"),+ other => panic!("expected Other, got {other:?}"),+ }+ }++ #[test]+ fn empty_tag_is_other() {+ match parse_script_tag("") {+ ScriptTag::Other(s) => assert_eq!(&*s, ""),+ other => panic!("expected Other, got {other:?}"),+ }+ }++ #[test]+ fn all_listed_tags_are_unique() {+ let mut names: Vec<&str> = SCRIPT_TAGS.iter().map(|(n, _)| *n).collect();+ names.sort_unstable();+ let before = names.len();+ names.dedup();+ assert_eq!(names.len(), before, "duplicate script tag in table");+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/vml/color.rs b/crates/liteparse-docx/src/docx/parse/vml/color.rsnew file mode 100644index 0000000..04617d8--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/vml/color.rs@@ -0,0 +1,275 @@+//! VML color parsing.++use crate::docx::model::*;++/// Parse a VML color value (§14.1.2.1): `#RRGGBB`, `RRGGBB` hex, or named color.+///+/// Returns `None` for an unrecognized value; every call site treats a color as+/// optional (an unparseable `fillcolor` simply means "no color"), so this+/// mirrors the sibling `parse_style`/`parse_formula`/`parse_length` helpers+/// rather than raising a document-fatal error.+pub(super) fn parse_color(s: &str) -> Option<VmlColor> {+ let hex = s.strip_prefix('#').unwrap_or(s);+ if hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {+ let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);+ let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);+ let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);+ return Some(VmlColor::Rgb(r, g, b));+ }+ parse_named_color(s).map(VmlColor::Named)+}++fn parse_named_color(s: &str) -> Option<VmlNamedColor> {+ // Case-insensitive match per CSS spec.+ Some(match s.to_ascii_lowercase().as_str() {+ // CSS2.1 standard colors.+ "black" => VmlNamedColor::Black,+ "silver" => VmlNamedColor::Silver,+ "gray" | "grey" => VmlNamedColor::Gray,+ "white" => VmlNamedColor::White,+ "maroon" => VmlNamedColor::Maroon,+ "red" => VmlNamedColor::Red,+ "purple" => VmlNamedColor::Purple,+ "fuchsia" => VmlNamedColor::Fuchsia,+ "green" => VmlNamedColor::Green,+ "lime" => VmlNamedColor::Lime,+ "olive" => VmlNamedColor::Olive,+ "yellow" => VmlNamedColor::Yellow,+ "navy" => VmlNamedColor::Navy,+ "blue" => VmlNamedColor::Blue,+ "teal" => VmlNamedColor::Teal,+ "aqua" => VmlNamedColor::Aqua,+ "orange" => VmlNamedColor::Orange,+ // SVG/CSS3 extended colors.+ "aliceblue" => VmlNamedColor::AliceBlue,+ "antiquewhite" => VmlNamedColor::AntiqueWhite,+ "beige" => VmlNamedColor::Beige,+ "bisque" => VmlNamedColor::Bisque,+ "blanchedalmond" => VmlNamedColor::BlanchedAlmond,+ "blueviolet" => VmlNamedColor::BlueViolet,+ "brown" => VmlNamedColor::Brown,+ "burlywood" => VmlNamedColor::BurlyWood,+ "cadetblue" => VmlNamedColor::CadetBlue,+ "chartreuse" => VmlNamedColor::Chartreuse,+ "chocolate" => VmlNamedColor::Chocolate,+ "coral" => VmlNamedColor::Coral,+ "cornflowerblue" => VmlNamedColor::CornflowerBlue,+ "cornsilk" => VmlNamedColor::Cornsilk,+ "crimson" => VmlNamedColor::Crimson,+ "cyan" => VmlNamedColor::Cyan,+ "darkblue" => VmlNamedColor::DarkBlue,+ "darkcyan" => VmlNamedColor::DarkCyan,+ "darkgoldenrod" => VmlNamedColor::DarkGoldenrod,+ "darkgray" | "darkgrey" => VmlNamedColor::DarkGray,+ "darkgreen" => VmlNamedColor::DarkGreen,+ "darkkhaki" => VmlNamedColor::DarkKhaki,+ "darkmagenta" => VmlNamedColor::DarkMagenta,+ "darkolivegreen" => VmlNamedColor::DarkOliveGreen,+ "darkorange" => VmlNamedColor::DarkOrange,+ "darkorchid" => VmlNamedColor::DarkOrchid,+ "darkred" => VmlNamedColor::DarkRed,+ "darksalmon" => VmlNamedColor::DarkSalmon,+ "darkseagreen" => VmlNamedColor::DarkSeaGreen,+ "darkslateblue" => VmlNamedColor::DarkSlateBlue,+ "darkslategray" | "darkslategrey" => VmlNamedColor::DarkSlateGray,+ "darkturquoise" => VmlNamedColor::DarkTurquoise,+ "darkviolet" => VmlNamedColor::DarkViolet,+ "deeppink" => VmlNamedColor::DeepPink,+ "deepskyblue" => VmlNamedColor::DeepSkyBlue,+ "dimgray" | "dimgrey" => VmlNamedColor::DimGray,+ "dodgerblue" => VmlNamedColor::DodgerBlue,+ "firebrick" => VmlNamedColor::Firebrick,+ "floralwhite" => VmlNamedColor::FloralWhite,+ "forestgreen" => VmlNamedColor::ForestGreen,+ "gainsboro" => VmlNamedColor::Gainsboro,+ "ghostwhite" => VmlNamedColor::GhostWhite,+ "gold" => VmlNamedColor::Gold,+ "goldenrod" => VmlNamedColor::Goldenrod,+ "greenyellow" => VmlNamedColor::GreenYellow,+ "honeydew" => VmlNamedColor::Honeydew,+ "hotpink" => VmlNamedColor::HotPink,+ "indianred" => VmlNamedColor::IndianRed,+ "indigo" => VmlNamedColor::Indigo,+ "ivory" => VmlNamedColor::Ivory,+ "khaki" => VmlNamedColor::Khaki,+ "lavender" => VmlNamedColor::Lavender,+ "lavenderblush" => VmlNamedColor::LavenderBlush,+ "lawngreen" => VmlNamedColor::LawnGreen,+ "lemonchiffon" => VmlNamedColor::LemonChiffon,+ "lightblue" => VmlNamedColor::LightBlue,+ "lightcoral" => VmlNamedColor::LightCoral,+ "lightcyan" => VmlNamedColor::LightCyan,+ "lightgoldenrodyellow" => VmlNamedColor::LightGoldenrodYellow,+ "lightgray" | "lightgrey" => VmlNamedColor::LightGray,+ "lightgreen" => VmlNamedColor::LightGreen,+ "lightpink" => VmlNamedColor::LightPink,+ "lightsalmon" => VmlNamedColor::LightSalmon,+ "lightseagreen" => VmlNamedColor::LightSeaGreen,+ "lightskyblue" => VmlNamedColor::LightSkyBlue,+ "lightslategray" | "lightslategrey" => VmlNamedColor::LightSlateGray,+ "lightsteelblue" => VmlNamedColor::LightSteelBlue,+ "lightyellow" => VmlNamedColor::LightYellow,+ "limegreen" => VmlNamedColor::LimeGreen,+ "linen" => VmlNamedColor::Linen,+ "magenta" => VmlNamedColor::Magenta,+ "mediumaquamarine" => VmlNamedColor::MediumAquamarine,+ "mediumblue" => VmlNamedColor::MediumBlue,+ "mediumorchid" => VmlNamedColor::MediumOrchid,+ "mediumpurple" => VmlNamedColor::MediumPurple,+ "mediumseagreen" => VmlNamedColor::MediumSeaGreen,+ "mediumslateblue" => VmlNamedColor::MediumSlateBlue,+ "mediumspringgreen" => VmlNamedColor::MediumSpringGreen,+ "mediumturquoise" => VmlNamedColor::MediumTurquoise,+ "mediumvioletred" => VmlNamedColor::MediumVioletRed,+ "midnightblue" => VmlNamedColor::MidnightBlue,+ "mintcream" => VmlNamedColor::MintCream,+ "mistyrose" => VmlNamedColor::MistyRose,+ "moccasin" => VmlNamedColor::Moccasin,+ "navajowhite" => VmlNamedColor::NavajoWhite,+ "oldlace" => VmlNamedColor::OldLace,+ "olivedrab" => VmlNamedColor::OliveDrab,+ "orangered" => VmlNamedColor::OrangeRed,+ "orchid" => VmlNamedColor::Orchid,+ "palegoldenrod" => VmlNamedColor::PaleGoldenrod,+ "palegreen" => VmlNamedColor::PaleGreen,+ "paleturquoise" => VmlNamedColor::PaleTurquoise,+ "palevioletred" => VmlNamedColor::PaleVioletRed,+ "papayawhip" => VmlNamedColor::PapayaWhip,+ "peachpuff" => VmlNamedColor::PeachPuff,+ "peru" => VmlNamedColor::Peru,+ "pink" => VmlNamedColor::Pink,+ "plum" => VmlNamedColor::Plum,+ "powderblue" => VmlNamedColor::PowderBlue,+ "rosybrown" => VmlNamedColor::RosyBrown,+ "royalblue" => VmlNamedColor::RoyalBlue,+ "saddlebrown" => VmlNamedColor::SaddleBrown,+ "salmon" => VmlNamedColor::Salmon,+ "sandybrown" => VmlNamedColor::SandyBrown,+ "seagreen" => VmlNamedColor::SeaGreen,+ "seashell" => VmlNamedColor::Seashell,+ "sienna" => VmlNamedColor::Sienna,+ "skyblue" => VmlNamedColor::SkyBlue,+ "slateblue" => VmlNamedColor::SlateBlue,+ "slategray" | "slategrey" => VmlNamedColor::SlateGray,+ "snow" => VmlNamedColor::Snow,+ "springgreen" => VmlNamedColor::SpringGreen,+ "steelblue" => VmlNamedColor::SteelBlue,+ "tan" => VmlNamedColor::Tan,+ "thistle" => VmlNamedColor::Thistle,+ "tomato" => VmlNamedColor::Tomato,+ "turquoise" => VmlNamedColor::Turquoise,+ "violet" => VmlNamedColor::Violet,+ "wheat" => VmlNamedColor::Wheat,+ "whitesmoke" => VmlNamedColor::WhiteSmoke,+ "yellowgreen" => VmlNamedColor::YellowGreen,+ // VML system colors.+ "buttonface" => VmlNamedColor::ButtonFace,+ "buttonhighlight" => VmlNamedColor::ButtonHighlight,+ "buttonshadow" => VmlNamedColor::ButtonShadow,+ "buttontext" => VmlNamedColor::ButtonText,+ "captiontext" => VmlNamedColor::CaptionText,+ "graytext" => VmlNamedColor::GrayText,+ "highlight" => VmlNamedColor::Highlight,+ "highlighttext" => VmlNamedColor::HighlightText,+ "inactiveborder" => VmlNamedColor::InactiveBorder,+ "inactivecaption" => VmlNamedColor::InactiveCaption,+ "inactivecaptiontext" => VmlNamedColor::InactiveCaptionText,+ "infobackground" => VmlNamedColor::InfoBackground,+ "infotext" => VmlNamedColor::InfoText,+ "menu" => VmlNamedColor::Menu,+ "menutext" => VmlNamedColor::MenuText,+ "scrollbar" => VmlNamedColor::Scrollbar,+ "threeddarkshadow" => VmlNamedColor::ThreeDDarkShadow,+ "threedface" => VmlNamedColor::ThreeDFace,+ "threedhighlight" => VmlNamedColor::ThreeDHighlight,+ "threedlightshadow" => VmlNamedColor::ThreeDLightShadow,+ "threedshadow" => VmlNamedColor::ThreeDShadow,+ "window" => VmlNamedColor::Window,+ "windowframe" => VmlNamedColor::WindowFrame,+ "windowtext" => VmlNamedColor::WindowText,+ _ => return None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hex_with_hash() {+ assert_eq!(+ parse_color("#4F81BD"),+ Some(VmlColor::Rgb(0x4F, 0x81, 0xBD))+ );+ }++ #[test]+ fn hex_without_hash() {+ assert_eq!(parse_color("FF0000"), Some(VmlColor::Rgb(255, 0, 0)));+ }++ #[test]+ fn hex_is_case_insensitive() {+ assert_eq!(+ parse_color("#abcdef"),+ Some(VmlColor::Rgb(0xAB, 0xCD, 0xEF))+ );+ }++ #[test]+ fn named_color_basic() {+ assert_eq!(+ parse_color("red"),+ Some(VmlColor::Named(VmlNamedColor::Red))+ );+ }++ #[test]+ fn named_color_is_case_insensitive() {+ // §14.1.2.1 matches CSS color names case-insensitively.+ assert_eq!(+ parse_color("RED"),+ Some(VmlColor::Named(VmlNamedColor::Red))+ );+ assert_eq!(+ parse_color("Red"),+ Some(VmlColor::Named(VmlNamedColor::Red))+ );+ }++ #[test]+ fn gray_grey_spelling_aliases() {+ let gray = Some(VmlColor::Named(VmlNamedColor::Gray));+ assert_eq!(parse_color("gray"), gray);+ assert_eq!(parse_color("grey"), gray);+ let dark = Some(VmlColor::Named(VmlNamedColor::DarkGray));+ assert_eq!(parse_color("darkgray"), dark);+ assert_eq!(parse_color("darkgrey"), dark);+ }++ #[test]+ fn vml_system_color() {+ assert_eq!(+ parse_color("threeddarkshadow"),+ Some(VmlColor::Named(VmlNamedColor::ThreeDDarkShadow))+ );+ }++ #[test]+ fn unrecognized_name_is_none() {+ // Callers `.and_then` this, so an unknown color degrades to "no color".+ assert_eq!(parse_color("notacolor"), None);+ }++ #[test]+ fn three_digit_hex_is_not_six_digit_and_falls_through_to_none() {+ // Not 6 hex digits → not treated as RGB; "fff" is not a named color.+ assert_eq!(parse_color("#fff"), None);+ }++ #[test]+ fn six_non_hex_chars_are_not_rgb() {+ // Length 6 but not all hex digits → named lookup (which also fails).+ assert_eq!(parse_color("gggggg"), None);+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/vml/formulas.rs b/crates/liteparse-docx/src/docx/parse/vml/formulas.rsnew file mode 100644index 0000000..94c7c29--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/vml/formulas.rs@@ -0,0 +1,154 @@+//! VML formula parsing.++use crate::docx::model::*;++/// Parse a single VML formula equation string (e.g., "sum #0 0 10800").+pub(super) fn parse_formula(eqn: &str) -> Option<VmlFormula> {+ let parts: Vec<&str> = eqn.split_whitespace().collect();+ if parts.is_empty() {+ return None;+ }++ let operation = match parts[0] {+ "val" => VmlFormulaOp::Val,+ "sum" => VmlFormulaOp::Sum,+ "prod" => VmlFormulaOp::Product,+ "mid" => VmlFormulaOp::Mid,+ "abs" => VmlFormulaOp::Abs,+ "min" => VmlFormulaOp::Min,+ "max" => VmlFormulaOp::Max,+ "if" => VmlFormulaOp::If,+ "sqrt" => VmlFormulaOp::Sqrt,+ "mod" => VmlFormulaOp::Mod,+ "sin" => VmlFormulaOp::Sin,+ "cos" => VmlFormulaOp::Cos,+ "tan" => VmlFormulaOp::Tan,+ "atan2" => VmlFormulaOp::Atan2,+ "sinatan2" => VmlFormulaOp::SinAtan2,+ "cosatan2" => VmlFormulaOp::CosAtan2,+ "sumangle" => VmlFormulaOp::SumAngle,+ "ellipse" => VmlFormulaOp::Ellipse,+ other => {+ log::warn!("vml-formula: unsupported operation {:?}", other);+ return None;+ }+ };++ let arg = |i: usize| -> VmlFormulaArg {+ parts+ .get(i)+ .and_then(|s| parse_formula_arg(s))+ .unwrap_or(VmlFormulaArg::Literal(0))+ };++ Some(VmlFormula {+ operation,+ args: [arg(1), arg(2), arg(3)],+ })+}++/// Parse a single VML formula argument.+fn parse_formula_arg(s: &str) -> Option<VmlFormulaArg> {+ if let Some(rest) = s.strip_prefix('#') {+ return rest.parse::<u32>().ok().map(VmlFormulaArg::AdjRef);+ }+ if let Some(rest) = s.strip_prefix('@') {+ return rest.parse::<u32>().ok().map(VmlFormulaArg::FormulaRef);+ }+ let guide = match s {+ "width" => Some(VmlGuide::Width),+ "height" => Some(VmlGuide::Height),+ "xcenter" => Some(VmlGuide::XCenter),+ "ycenter" => Some(VmlGuide::YCenter),+ "xrange" => Some(VmlGuide::XRange),+ "yrange" => Some(VmlGuide::YRange),+ "pixelWidth" => Some(VmlGuide::PixelWidth),+ "pixelHeight" => Some(VmlGuide::PixelHeight),+ "pixelLineWidth" => Some(VmlGuide::PixelLineWidth),+ "emuWidth" => Some(VmlGuide::EmuWidth),+ "emuHeight" => Some(VmlGuide::EmuHeight),+ "emuWidth2" => Some(VmlGuide::EmuWidth2),+ "emuHeight2" => Some(VmlGuide::EmuHeight2),+ _ => None,+ };+ if let Some(g) = guide {+ return Some(VmlFormulaArg::Guide(g));+ }+ s.parse::<i64>().ok().map(VmlFormulaArg::Literal)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sum_with_adj_ref_and_literals() {+ let f = parse_formula("sum #0 0 10800").unwrap();+ assert_eq!(f.operation, VmlFormulaOp::Sum);+ assert_eq!(+ f.args,+ [+ VmlFormulaArg::AdjRef(0),+ VmlFormulaArg::Literal(0),+ VmlFormulaArg::Literal(10800),+ ]+ );+ }++ #[test]+ fn prod_maps_from_short_name() {+ let f = parse_formula("prod @2 1 2").unwrap();+ assert_eq!(f.operation, VmlFormulaOp::Product);+ assert_eq!(f.args[0], VmlFormulaArg::FormulaRef(2));+ }++ #[test]+ fn guide_arguments() {+ let f = parse_formula("mid width height").unwrap();+ assert_eq!(f.operation, VmlFormulaOp::Mid);+ assert_eq!(f.args[0], VmlFormulaArg::Guide(VmlGuide::Width));+ assert_eq!(f.args[1], VmlFormulaArg::Guide(VmlGuide::Height));+ // No third token → defaults to literal 0.+ assert_eq!(f.args[2], VmlFormulaArg::Literal(0));+ }++ #[test]+ fn missing_arguments_default_to_literal_zero() {+ let f = parse_formula("val 100").unwrap();+ assert_eq!(f.operation, VmlFormulaOp::Val);+ assert_eq!(+ f.args,+ [+ VmlFormulaArg::Literal(100),+ VmlFormulaArg::Literal(0),+ VmlFormulaArg::Literal(0),+ ]+ );+ }++ #[test]+ fn negative_literal() {+ let f = parse_formula("sum 0 0 -10800").unwrap();+ assert_eq!(f.args[2], VmlFormulaArg::Literal(-10800));+ }++ #[test]+ fn unknown_operation_is_dropped() {+ assert!(parse_formula("bogus 1 2 3").is_none());+ }++ #[test]+ fn empty_string_is_none() {+ assert!(parse_formula("").is_none());+ assert!(parse_formula(" ").is_none());+ }++ #[test]+ fn unparseable_guide_falls_back_to_literal_zero() {+ // An unrecognized non-numeric arg is not a guide and not an integer;+ // `arg()` substitutes literal 0 rather than failing the whole formula.+ let f = parse_formula("sum notaguide 5 6").unwrap();+ assert_eq!(f.args[0], VmlFormulaArg::Literal(0));+ assert_eq!(f.args[1], VmlFormulaArg::Literal(5));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/vml/mod.rs b/crates/liteparse-docx/src/docx/parse/vml/mod.rsnew file mode 100644index 0000000..26ab1a6--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/vml/mod.rs@@ -0,0 +1,11 @@+//! VML (Vector Markup Language) parsing — fully serde-based.+//!+//! Pure attribute-level sub-grammars live in sibling submodules+//! (`color`, `formulas`, `path_commands`, `style`) as `&str → value`+//! functions. XML structure lives in [`schema`].++mod color;+mod formulas;+mod path_commands;+pub mod schema;+mod style;diff --git a/crates/liteparse-docx/src/docx/parse/vml/path_commands.rs b/crates/liteparse-docx/src/docx/parse/vml/path_commands.rsnew file mode 100644index 0000000..6667b35--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/vml/path_commands.rs@@ -0,0 +1,408 @@+//! VML path command parsing.++use crate::docx::model::*;++/// Parse VML path commands from the `path` attribute string (§14.2.1.6).+pub(super) fn parse_path_commands(s: Option<String>) -> Vec<VmlPathCommand> {+ let s = match s {+ Some(s) => s,+ None => return Vec::new(),+ };++ let mut cmds = Vec::new();+ // Tokenize: split on commas and whitespace, but keep command letters as separate tokens.+ let mut tokens: Vec<&str> = Vec::new();+ let mut rest = s.as_str();+ while !rest.is_empty() {+ // Skip whitespace and commas.+ rest = rest.trim_start_matches(|c: char| c == ',' || c.is_ascii_whitespace());+ if rest.is_empty() {+ break;+ }+ // Check for the two-letter commands first (§14.2.1.6): the angle-arc+ // pair (`wa`/`wr`/`at`/`ar`), elliptical quadrants (`qx`/`qy`), and the+ // fill/stroke toggles (`nf`/`ns`).+ let cmd_len = if rest.starts_with("wa")+ || rest.starts_with("wr")+ || rest.starts_with("at")+ || rest.starts_with("ar")+ || rest.starts_with("qx")+ || rest.starts_with("qy")+ || rest.starts_with("nf")+ || rest.starts_with("ns")+ {+ 2+ } else if rest.starts_with(|c: char| c.is_ascii_alphabetic()) {+ 1+ } else {+ 0+ };++ if cmd_len > 0 {+ tokens.push(&rest[..cmd_len]);+ rest = &rest[cmd_len..];+ } else if rest.starts_with('@') {+ // §14.2.1.6: @n formula reference — consume @digits.+ let end = rest[1..]+ .find(|c: char| !c.is_ascii_digit())+ .map(|p| p + 1)+ .unwrap_or(rest.len());+ tokens.push(&rest[..end]);+ rest = &rest[end..];+ } else {+ // Numeric token: consume until delimiter.+ let end = rest+ .find(|c: char| {+ c == ',' || c == '@' || c.is_ascii_whitespace() || c.is_ascii_alphabetic()+ })+ .unwrap_or(rest.len());+ if end > 0 {+ tokens.push(&rest[..end]);+ rest = &rest[end..];+ } else {+ rest = &rest[1..]; // skip unrecognized char+ }+ }+ }++ let mut i = 0;+ while i < tokens.len() {+ let tok = tokens[i];+ i += 1;+ match tok {+ "m" => {+ if let Some((x, y)) = take_2_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::MoveTo { x, y });+ }+ }+ "l" => {+ if let Some((x, y)) = take_2_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::LineTo { x, y });+ }+ }+ "c" => {+ if let Some((x1, y1, x2, y2, x, y)) = take_6_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::CurveTo {+ x1,+ y1,+ x2,+ y2,+ x,+ y,+ });+ }+ }+ "r" => {+ if let Some((dx, dy)) = take_2_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::RLineTo { dx, dy });+ }+ }+ "v" => {+ if let Some((dx1, dy1, dx2, dy2, dx, dy)) = take_6_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::RCurveTo {+ dx1,+ dy1,+ dx2,+ dy2,+ dx,+ dy,+ });+ }+ }+ "t" => {+ if let Some((dx, dy)) = take_2_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::RMoveTo { dx, dy });+ }+ }+ "x" => cmds.push(VmlPathCommand::Close),+ "e" => cmds.push(VmlPathCommand::End),+ "qx" => {+ if let Some((x, y)) = take_2_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::QuadrantX { x, y });+ }+ }+ "qy" => {+ if let Some((x, y)) = take_2_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::QuadrantY { x, y });+ }+ }+ "nf" => cmds.push(VmlPathCommand::NoFill),+ "ns" => cmds.push(VmlPathCommand::NoStroke),+ "wa" | "wr" | "at" | "ar" => {+ let kind = match tok {+ "wa" => VmlArcKind::WA,+ "wr" => VmlArcKind::WR,+ "at" => VmlArcKind::AT,+ _ => VmlArcKind::AR,+ };+ let args = (|| {+ Some(VmlPathCommand::Arc {+ kind,+ bounding_x1: take_coord(&tokens, &mut i)?,+ bounding_y1: take_coord(&tokens, &mut i)?,+ bounding_x2: take_coord(&tokens, &mut i)?,+ bounding_y2: take_coord(&tokens, &mut i)?,+ start_x: take_coord(&tokens, &mut i)?,+ start_y: take_coord(&tokens, &mut i)?,+ end_x: take_coord(&tokens, &mut i)?,+ end_y: take_coord(&tokens, &mut i)?,+ })+ })();+ if let Some(cmd) = args {+ cmds.push(cmd);+ }+ }+ _ => {+ // §14.2.1.6: bare coordinate in command position — implicit lineto.+ let x = if let Some(rest) = tok.strip_prefix('@') {+ rest.parse::<u32>().ok().map(VmlPathCoord::FormulaRef)+ } else {+ tok.parse::<i64>().ok().map(VmlPathCoord::Literal)+ };+ if let Some(x) = x {+ if let Some(y) = take_coord(&tokens, &mut i) {+ cmds.push(VmlPathCommand::LineTo { x, y });+ }+ } else {+ log::warn!("vml-path: unsupported command {:?}", tok);+ }+ }+ }+ }++ cmds+}++fn take_coord(tokens: &[&str], i: &mut usize) -> Option<VmlPathCoord> {+ if *i >= tokens.len() {+ return None;+ }+ let tok = tokens[*i];+ let coord = if let Some(rest) = tok.strip_prefix('@') {+ VmlPathCoord::FormulaRef(rest.parse::<u32>().ok()?)+ } else {+ VmlPathCoord::Literal(tok.parse::<i64>().ok()?)+ };+ *i += 1;+ Some(coord)+}++fn take_2_coord(tokens: &[&str], i: &mut usize) -> Option<(VmlPathCoord, VmlPathCoord)> {+ let a = take_coord(tokens, i)?;+ let b = take_coord(tokens, i)?;+ Some((a, b))+}++fn take_6_coord(+ tokens: &[&str],+ i: &mut usize,+) -> Option<(+ VmlPathCoord,+ VmlPathCoord,+ VmlPathCoord,+ VmlPathCoord,+ VmlPathCoord,+ VmlPathCoord,+)> {+ let a = take_coord(tokens, i)?;+ let b = take_coord(tokens, i)?;+ let c = take_coord(tokens, i)?;+ let d = take_coord(tokens, i)?;+ let e = take_coord(tokens, i)?;+ let f = take_coord(tokens, i)?;+ Some((a, b, c, d, e, f))+}++/// Parse a VML `adj` attribute — comma-separated integer adjustment values.+pub(super) fn parse_adj(s: Option<String>) -> Vec<i64> {+ match s {+ Some(s) => s+ .split(',')+ .filter_map(|v| v.trim().parse::<i64>().ok())+ .collect(),+ None => Vec::new(),+ }+}++/// Parse a VML Vector2D string ("x,y") into `VmlVector2D`.+pub(super) fn parse_vector2d(s: Option<String>) -> Option<VmlVector2D> {+ let s = s?;+ let (x_str, y_str) = s.split_once(',')?;+ let x = x_str.trim().parse::<i64>().ok()?;+ let y = y_str.trim().parse::<i64>().ok()?;+ Some(VmlVector2D { x, y })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn lit(v: i64) -> VmlPathCoord {+ VmlPathCoord::Literal(v)+ }++ #[test]+ fn none_yields_empty() {+ assert!(parse_path_commands(None).is_empty());+ }++ #[test]+ fn move_line_close_end() {+ let cmds = parse_path_commands(Some("m 0,0 l 100,100 x e".into()));+ assert_eq!(+ cmds,+ vec![+ VmlPathCommand::MoveTo {+ x: lit(0),+ y: lit(0)+ },+ VmlPathCommand::LineTo {+ x: lit(100),+ y: lit(100)+ },+ VmlPathCommand::Close,+ VmlPathCommand::End,+ ]+ );+ }++ #[test]+ fn curveto_takes_six_coords() {+ let cmds = parse_path_commands(Some("c 1 2 3 4 5 6".into()));+ assert_eq!(+ cmds,+ vec![VmlPathCommand::CurveTo {+ x1: lit(1),+ y1: lit(2),+ x2: lit(3),+ y2: lit(4),+ x: lit(5),+ y: lit(6),+ }]+ );+ }++ #[test]+ fn relative_commands() {+ let cmds = parse_path_commands(Some("t 5,5 r 10,0".into()));+ assert_eq!(+ cmds,+ vec![+ VmlPathCommand::RMoveTo {+ dx: lit(5),+ dy: lit(5)+ },+ VmlPathCommand::RLineTo {+ dx: lit(10),+ dy: lit(0)+ },+ ]+ );+ }++ #[test]+ fn two_letter_commands_tokenize_correctly() {+ // Guards the tokenizer's two-letter set (`nf`/`ns`/`qx`/`qy`/arcs). The+ // adjacent `nfns` must split into two toggles, not one bogus token.+ let cmds = parse_path_commands(Some("qx 1,1 nfns".into()));+ assert_eq!(+ cmds,+ vec![+ VmlPathCommand::QuadrantX {+ x: lit(1),+ y: lit(1)+ },+ VmlPathCommand::NoFill,+ VmlPathCommand::NoStroke,+ ]+ );+ }++ #[test]+ fn arc_takes_eight_coords_with_kind() {+ let cmds = parse_path_commands(Some("at 0 0 100 100 0 50 50 0".into()));+ assert_eq!(cmds.len(), 1);+ match cmds[0] {+ VmlPathCommand::Arc {+ kind,+ bounding_x1,+ end_y,+ ..+ } => {+ assert_eq!(kind, VmlArcKind::AT);+ assert_eq!(bounding_x1, lit(0));+ assert_eq!(end_y, lit(0));+ }+ other => panic!("expected Arc, got {other:?}"),+ }+ }++ #[test]+ fn formula_reference_as_coordinate() {+ let cmds = parse_path_commands(Some("m @0,@1".into()));+ assert_eq!(+ cmds,+ vec![VmlPathCommand::MoveTo {+ x: VmlPathCoord::FormulaRef(0),+ y: VmlPathCoord::FormulaRef(1),+ }]+ );+ }++ #[test]+ fn bare_coordinates_are_implicit_lineto() {+ // §14.2.1.6: coordinates in command position imply a lineto.+ let cmds = parse_path_commands(Some("m 0,0 10,20".into()));+ assert_eq!(+ cmds,+ vec![+ VmlPathCommand::MoveTo {+ x: lit(0),+ y: lit(0)+ },+ VmlPathCommand::LineTo {+ x: lit(10),+ y: lit(20)+ },+ ]+ );+ }++ #[test]+ fn unsupported_letter_command_is_dropped() {+ // A stray non-command letter (e.g. 'h', which is not a VML path+ // command) is dropped; well-formed neighbours survive.+ let cmds = parse_path_commands(Some("m 0,0 h l 5,5".into()));+ assert_eq!(+ cmds,+ vec![+ VmlPathCommand::MoveTo {+ x: lit(0),+ y: lit(0)+ },+ VmlPathCommand::LineTo {+ x: lit(5),+ y: lit(5)+ },+ ]+ );+ }++ #[test]+ fn parse_adj_filters_non_integers() {+ assert_eq!(parse_adj(Some("1,2,3".into())), vec![1, 2, 3]);+ assert_eq!(parse_adj(Some("1, 2 , x".into())), vec![1, 2]);+ assert!(parse_adj(None).is_empty());+ }++ #[test]+ fn parse_vector2d_pairs() {+ assert_eq!(+ parse_vector2d(Some("10,20".into())),+ Some(VmlVector2D { x: 10, y: 20 })+ );+ assert_eq!(parse_vector2d(Some("21600,21600".into())).unwrap().x, 21600);+ assert!(parse_vector2d(None).is_none());+ assert!(parse_vector2d(Some("bad".into())).is_none());+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/vml/schema.rs b/crates/liteparse-docx/src/docx/parse/vml/schema.rsnew file mode 100644index 0000000..e58d075--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/vml/schema.rs@@ -0,0 +1,1315 @@+//! Serde schema for VML (§14.1) — `<w:pict>` picture containers with shape+//! types, shapes, text boxes, and related child elements.+//!+//! XML structure goes through serde. Attribute-level string sub-grammars+//! (CSS-like `style`, `path` commands, `adj` / `coordsize` numeric lists,+//! color names/hex) are reused from `vml::{style, color, path_commands,+//! formulas}` as pure `&str` → value parsers.++#![allow(dead_code, clippy::large_enum_variant)]++use serde::Deserialize;++use crate::docx::model::{+ Block, Pict, RelId, VmlArc, VmlCommonAttrs, VmlConnectType, VmlCurve, VmlDashStyle,+ VmlExtHandling, VmlFormula, VmlGroup, VmlImage, VmlImageData, VmlJoinStyle, VmlLine, VmlLock,+ VmlOval, VmlPath, VmlPoint, VmlPolyLine, VmlPrimitive, VmlRect, VmlRoundRect, VmlShape,+ VmlShapeId, VmlShapeType, VmlStroke, VmlTextBox, VmlTextBoxInset, VmlVector2D, VmlWrap,+ VmlWrapSide, VmlWrapType,+};+use crate::docx::parse::body_schema::BlockChildXml;++use super::color::parse_color;+use super::formulas::parse_formula;+use super::path_commands::{parse_adj, parse_path_commands, parse_vector2d};+use super::style::{parse_length, parse_style};++// ── pict ──────────────────────────────────────────────────────────────────++/// `<w:pict>` — legacy VML picture container. Per ECMA-376 Part 4+/// §14.1.1, the children form a sequence: optional `<v:shapetype>`+/// definitions followed by any of the primitive shape elements+/// (`<v:shape>`, `<v:rect>`, `<v:roundrect>`, `<v:oval>`, `<v:line>`,+/// `<v:polyline>`, `<v:arc>`, `<v:curve>`, `<v:image>`, `<v:group>`).+/// We capture every child via `$value` and dispatch through+/// [`VmlPrimitiveXml`].+#[derive(Deserialize)]+pub(crate) struct PictXml {+ #[serde(rename = "shapetype", default)]+ pub shape_type: Option<ShapeTypeXml>,+ #[serde(rename = "$value", default)]+ pub primitives: Vec<VmlPrimitiveXml>,+}++impl PictXml {+ /// Convert to the model; `ctx` resolves embedded drawings nested inside+ /// VML text box content (same iterator threading as shape).+ pub(crate) fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> Pict {+ Pict {+ shape_type: self.shape_type.map(Into::into),+ primitives: self+ .primitives+ .into_iter()+ .filter_map(|p| p.into_model(ctx))+ .collect(),+ }+ }+}++/// VML §14.1.2 shape choice — a `<w:pict>` admits any of these as+/// children. `ShapeType` here is *not* a primitive but appears in+/// the same sibling list; serde routes it into this variant so we+/// don't have to special-case `<v:shapetype>` in the deserializer+/// (the dedicated `PictXml::shape_type` field also captures it).+/// `Other` absorbs unknown VML elements (or extension namespaces) so+/// parsing never fails on a strange child.+#[derive(Deserialize)]+pub(crate) enum VmlPrimitiveXml {+ #[serde(rename = "shape")]+ Shape(Box<ShapeXml>),+ #[serde(rename = "rect")]+ Rect(RectXml),+ #[serde(rename = "roundrect")]+ RoundRect(RoundRectXml),+ #[serde(rename = "oval")]+ Oval(OvalXml),+ #[serde(rename = "line")]+ Line(LineXml),+ #[serde(rename = "polyline")]+ PolyLine(PolyLineXml),+ #[serde(rename = "arc")]+ Arc(ArcXml),+ #[serde(rename = "curve")]+ Curve(CurveXml),+ #[serde(rename = "image")]+ Image(ImageXml),+ #[serde(rename = "group")]+ Group(Box<GroupXml>),+ /// `<v:shapetype>` is captured separately on `PictXml.shape_type`,+ /// but `$value` collects *every* child — this variant lets serde+ /// absorb the duplicate match without erroring.+ #[serde(rename = "shapetype")]+ ShapeType(Box<ShapeTypeXml>),+ /// Unknown / unsupported VML element. Dropped at conversion time.+ #[serde(other)]+ Other,+}++impl VmlPrimitiveXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> Option<VmlPrimitive> {+ Some(match self {+ VmlPrimitiveXml::Shape(s) => VmlPrimitive::Shape(s.into_model(ctx)),+ VmlPrimitiveXml::Rect(r) => VmlPrimitive::Rect(r.into_model(ctx)),+ VmlPrimitiveXml::RoundRect(r) => VmlPrimitive::RoundRect(r.into_model(ctx)),+ VmlPrimitiveXml::Oval(o) => VmlPrimitive::Oval(o.into_model(ctx)),+ VmlPrimitiveXml::Line(l) => VmlPrimitive::Line(l.into_model(ctx)),+ VmlPrimitiveXml::PolyLine(p) => VmlPrimitive::PolyLine(p.into_model(ctx)),+ VmlPrimitiveXml::Arc(a) => VmlPrimitive::Arc(a.into_model(ctx)),+ VmlPrimitiveXml::Curve(c) => VmlPrimitive::Curve(c.into_model(ctx)),+ VmlPrimitiveXml::Image(i) => VmlPrimitive::Image(i.into_model(ctx)),+ VmlPrimitiveXml::Group(g) => VmlPrimitive::Group(Box::new(g.into_model(ctx))),+ // Captured separately on `PictXml.shape_type`; drop the duplicate.+ VmlPrimitiveXml::ShapeType(_) | VmlPrimitiveXml::Other => return None,+ })+ }+}++/// Common attributes + child elements shared by every VML primitive+/// (§14.1.2.18 CoreAttributes plus `<v:stroke>` / `<v:textbox>` /+/// `<v:wrap>` / `<v:imagedata>`). Each per-primitive schema struct+/// embeds this via `#[serde(flatten)]` so we don't repeat the eight+/// field declarations across nine primitive types.+#[derive(Deserialize, Default)]+pub(crate) struct CommonAttrsXml {+ #[serde(rename = "@id", default)]+ pub id: Option<String>,+ #[serde(rename = "@style", default)]+ pub style: Option<String>,+ #[serde(rename = "@fillcolor", default)]+ pub fillcolor: Option<String>,+ #[serde(rename = "@stroked", default)]+ pub stroked: Option<VmlBool>,+ #[serde(rename = "stroke", default)]+ pub stroke: Option<StrokeXml>,+ #[serde(rename = "textbox", default)]+ pub textbox: Option<TextBoxXml>,+ #[serde(rename = "wrap", default)]+ pub wrap: Option<WrapXml>,+ #[serde(rename = "imagedata", default)]+ pub imagedata: Option<ImageDataXml>,+ #[serde(rename = "fill", default)]+ pub fill: Option<FillXml>,+}++/// VML §14.1.2.5 `<v:fill>` — every primitive can carry one. Fields+/// are admitted as attributes, not children.+#[derive(Deserialize, Default)]+pub(crate) struct FillXml {+ #[serde(rename = "@type", default)]+ pub fill_type: Option<String>,+ #[serde(rename = "@color", default)]+ pub color: Option<String>,+ #[serde(rename = "@color2", default)]+ pub color2: Option<String>,+ #[serde(rename = "@opacity", default)]+ pub opacity: Option<String>,+ #[serde(rename = "@src", default)]+ pub src: Option<String>,+ #[serde(rename = "@id", default)]+ pub rel_id: Option<String>,+}++impl From<FillXml> for crate::docx::model::VmlFill {+ fn from(x: FillXml) -> Self {+ use crate::docx::model::{VmlFill, VmlFillType};+ let fill_type = match x.fill_type.as_deref() {+ Some("solid") | None => VmlFillType::Solid,+ Some("gradient") | Some("gradientCenter") | Some("gradientUnscaled") => {+ VmlFillType::Gradient+ }+ Some("gradientRadial") => VmlFillType::GradientRadial,+ Some("tile") => VmlFillType::Tile,+ Some("frame") => VmlFillType::Frame,+ Some("pattern") => VmlFillType::Pattern,+ // Unknown type → treat as solid; the renderer logs a warn+ // when it can't honor a fill, never panics.+ Some(_) => VmlFillType::Solid,+ };+ VmlFill {+ fill_type,+ color: x.color.as_deref().and_then(parse_color),+ color2: x.color2.as_deref().and_then(parse_color),+ opacity: x.opacity.as_deref().and_then(|s| {+ // VML opacity admits "0.5" or "32768f" (fixed-point fraction+ // of 65536). For phase C we accept the float form.+ s.parse::<f32>().ok()+ }),+ src: x.src,+ rel_id: x.rel_id.map(crate::docx::model::RelId::new),+ }+ }+}++impl CommonAttrsXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlCommonAttrs {+ VmlCommonAttrs {+ id: self.id.map(VmlShapeId::new),+ style: parse_style(self.style),+ fill_color: self.fillcolor.as_deref().and_then(parse_color),+ stroked: self.stroked.map(|b| b.0),+ stroke: self.stroke.map(Into::into),+ text_box: self.textbox.map(|t| t.into_model(ctx)),+ wrap: self.wrap.map(Into::into),+ image_data: self.imagedata.map(Into::into),+ fill: self.fill.map(Into::into),+ }+ }+}++// ── shapetype ─────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct ShapeTypeXml {+ #[serde(rename = "@id", default)]+ pub id: Option<String>,+ #[serde(rename = "@coordsize", default)]+ pub coordsize: Option<String>,+ #[serde(rename = "@spt", default)]+ pub spt: Option<String>,+ #[serde(rename = "@adj", default)]+ pub adj: Option<String>,+ #[serde(rename = "@path", default)]+ pub path: Option<String>,+ #[serde(rename = "@filled", default)]+ pub filled: Option<VmlBool>,+ #[serde(rename = "@stroked", default)]+ pub stroked: Option<VmlBool>,++ #[serde(rename = "stroke", default)]+ pub stroke: Option<StrokeXml>,+ #[serde(rename = "path", default)]+ pub vml_path: Option<PathXml>,+ #[serde(rename = "formulas", default)]+ pub formulas: Option<FormulasXml>,+ #[serde(rename = "lock", default)]+ pub lock: Option<LockXml>,+}++impl From<ShapeTypeXml> for VmlShapeType {+ fn from(x: ShapeTypeXml) -> Self {+ Self {+ id: x.id.map(VmlShapeId::new),+ coord_size: parse_vector2d(x.coordsize),+ spt: x.spt.and_then(|s| s.parse::<f32>().ok()),+ adj: parse_adj(x.adj),+ path: parse_path_commands(x.path),+ filled: x.filled.map(|b| b.0),+ stroked: x.stroked.map(|b| b.0),+ stroke: x.stroke.map(Into::into),+ vml_path: x.vml_path.map(Into::into),+ formulas: x+ .formulas+ .map(|f| {+ f.entries+ .into_iter()+ .filter_map(|e| parse_formula(&e.eqn))+ .collect()+ })+ .unwrap_or_default(),+ lock: x.lock.map(Into::into),+ }+ }+}++// ── shape ─────────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct ShapeXml {+ #[serde(rename = "@id", default)]+ pub id: Option<String>,+ /// Reference like `"#_x0000_t202"` — strip the leading `#`.+ #[serde(rename = "@type", default)]+ pub ty: Option<String>,+ #[serde(rename = "@style", default)]+ pub style: Option<String>,+ #[serde(rename = "@fillcolor", default)]+ pub fillcolor: Option<String>,+ #[serde(rename = "@stroked", default)]+ pub stroked: Option<VmlBool>,++ #[serde(rename = "stroke", default)]+ pub stroke: Option<StrokeXml>,+ #[serde(rename = "path", default)]+ pub vml_path: Option<PathXml>,+ #[serde(rename = "textbox", default)]+ pub textbox: Option<TextBoxXml>,+ #[serde(rename = "wrap", default)]+ pub wrap: Option<WrapXml>,+ #[serde(rename = "imagedata", default)]+ pub imagedata: Option<ImageDataXml>,+ #[serde(rename = "fill", default)]+ pub fill: Option<FillXml>,+}++impl ShapeXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlShape {+ VmlShape {+ common: crate::model::VmlCommonAttrs {+ id: self.id.map(VmlShapeId::new),+ style: parse_style(self.style),+ fill_color: self.fillcolor.as_deref().and_then(parse_color),+ stroked: self.stroked.map(|b| b.0),+ stroke: self.stroke.map(Into::into),+ text_box: self.textbox.map(|t| t.into_model(ctx)),+ wrap: self.wrap.map(Into::into),+ image_data: self.imagedata.map(Into::into),+ fill: self.fill.map(Into::into),+ },+ shape_type_ref: self+ .ty+ .map(|s| VmlShapeId::new(s.strip_prefix('#').unwrap_or(&s))),+ vml_path: self.vml_path.map(Into::into),+ }+ }+}++// ── primitive shapes (rect / roundrect / oval / line / polyline /+// arc / curve / image / group) ──────────────────────────────────────++/// VML §14.1.2.16 `<v:rect>`.+///+/// Common attrs are inlined here (rather than via+/// `#[serde(flatten)]` on a `CommonAttrsXml`) because quick-xml's+/// serde drops the deeply-nested `<v:textbox><w:txbxContent>...`+/// when the field carrying `<v:textbox>` lives behind a flatten+/// boundary — the rect's textbox content silently vanishes. Inlining+/// keeps every child element on the same struct level so it parses+/// faithfully. The other primitives keep `flatten` because they+/// don't host text-box content in practice (or do but were simpler+/// to wire that way).+#[derive(Deserialize)]+pub(crate) struct RectXml {+ #[serde(rename = "@id", default)]+ pub id: Option<String>,+ #[serde(rename = "@style", default)]+ pub style: Option<String>,+ #[serde(rename = "@fillcolor", default)]+ pub fillcolor: Option<String>,+ #[serde(rename = "@stroked", default)]+ pub stroked: Option<VmlBool>,+ #[serde(rename = "stroke", default)]+ pub stroke: Option<StrokeXml>,+ #[serde(rename = "textbox", default)]+ pub textbox: Option<TextBoxXml>,+ #[serde(rename = "wrap", default)]+ pub wrap: Option<WrapXml>,+ #[serde(rename = "imagedata", default)]+ pub imagedata: Option<ImageDataXml>,+ #[serde(rename = "fill", default)]+ pub fill: Option<FillXml>,+}++impl RectXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlRect {+ VmlRect {+ common: VmlCommonAttrs {+ id: self.id.map(VmlShapeId::new),+ style: parse_style(self.style),+ fill_color: self.fillcolor.as_deref().and_then(parse_color),+ stroked: self.stroked.map(|b| b.0),+ stroke: self.stroke.map(Into::into),+ text_box: self.textbox.map(|t| t.into_model(ctx)),+ wrap: self.wrap.map(Into::into),+ image_data: self.imagedata.map(Into::into),+ fill: self.fill.map(Into::into),+ },+ }+ }+}++/// VML §14.1.2.17 `<v:roundrect>`.+#[derive(Deserialize)]+pub(crate) struct RoundRectXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+ /// `@arcsize` — corner radius as a fraction (e.g. "10923f" = ~16.7%+ /// in the spec's fixed-point format, or a plain decimal). We accept+ /// floats; downstream layout clamps to [0, 1].+ #[serde(+ rename = "@arcsize",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub arcsize: Option<f32>,+}++impl RoundRectXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlRoundRect {+ VmlRoundRect {+ common: self.common.into_model(ctx),+ arcsize: self.arcsize,+ }+ }+}++/// VML §14.1.2.13 `<v:oval>`.+#[derive(Deserialize)]+pub(crate) struct OvalXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+}++impl OvalXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlOval {+ VmlOval {+ common: self.common.into_model(ctx),+ }+ }+}++/// VML §14.1.2.12 `<v:line>` — endpoints in `@from` / `@to` as+/// comma-separated lengths (e.g. "10pt,20pt").+#[derive(Deserialize)]+pub(crate) struct LineXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+ #[serde(rename = "@from", default)]+ pub from: Option<String>,+ #[serde(rename = "@to", default)]+ pub to: Option<String>,+}++impl LineXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlLine {+ VmlLine {+ common: self.common.into_model(ctx),+ from: self.from.as_deref().and_then(parse_vml_point),+ to: self.to.as_deref().and_then(parse_vml_point),+ }+ }+}++/// VML §14.1.2.15 `<v:polyline>`. `@points` is a space-and-comma+/// separated list of x,y pairs.+#[derive(Deserialize)]+pub(crate) struct PolyLineXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+ #[serde(rename = "@points", default)]+ pub points: Option<String>,+}++impl PolyLineXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlPolyLine {+ VmlPolyLine {+ common: self.common.into_model(ctx),+ points: self+ .points+ .as_deref()+ .map(parse_vml_points)+ .unwrap_or_default(),+ }+ }+}++/// VML §14.1.2.3 `<v:arc>`.+#[derive(Deserialize)]+pub(crate) struct ArcXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+ #[serde(+ rename = "@startangle",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub start_angle: Option<f32>,+ #[serde(+ rename = "@endangle",+ default,+ deserialize_with = "crate::docx::parse::primitives::lenient::opt_attr"+ )]+ pub end_angle: Option<f32>,+}++impl ArcXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlArc {+ VmlArc {+ common: self.common.into_model(ctx),+ start_angle: self.start_angle,+ end_angle: self.end_angle,+ }+ }+}++/// VML §14.1.2.7 `<v:curve>` — cubic Bezier with two control points.+#[derive(Deserialize)]+pub(crate) struct CurveXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+ #[serde(rename = "@from", default)]+ pub from: Option<String>,+ #[serde(rename = "@control1", default)]+ pub control1: Option<String>,+ #[serde(rename = "@control2", default)]+ pub control2: Option<String>,+ #[serde(rename = "@to", default)]+ pub to: Option<String>,+}++impl CurveXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlCurve {+ VmlCurve {+ common: self.common.into_model(ctx),+ from: self.from.as_deref().and_then(parse_vml_point),+ control1: self.control1.as_deref().and_then(parse_vml_point),+ control2: self.control2.as_deref().and_then(parse_vml_point),+ to: self.to.as_deref().and_then(parse_vml_point),+ }+ }+}++/// VML §14.1.2.10 `<v:image>` — image element. `@src` carries the+/// path; rels (`<v:imagedata r:id>`) are still picked up via the+/// shared `CommonAttrsXml.imagedata`, so either form works.+#[derive(Deserialize)]+pub(crate) struct ImageXml {+ #[serde(flatten)]+ pub common: CommonAttrsXml,+ #[serde(rename = "@src", default)]+ pub src: Option<String>,+}++impl ImageXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlImage {+ VmlImage {+ common: self.common.into_model(ctx),+ src: self.src,+ }+ }+}++/// VML §14.1.2.9 `<v:group>` — recursive shape grouping.+///+/// The common attribute fields are inlined here (rather than via+/// `#[serde(flatten)]` like the other primitives) because flatten+/// fights with `$value` for child capture: with flatten enabled,+/// quick-xml's serde resolver routes `<rect>`/`<oval>`/etc. through+/// the flattened struct first, which rejects them as unknown fields+/// and drops them. Inlining keeps the children path clean.+#[derive(Deserialize)]+pub(crate) struct GroupXml {+ #[serde(rename = "@id", default)]+ pub id: Option<String>,+ #[serde(rename = "@style", default)]+ pub style: Option<String>,+ #[serde(rename = "@fillcolor", default)]+ pub fillcolor: Option<String>,+ #[serde(rename = "@stroked", default)]+ pub stroked: Option<VmlBool>,+ #[serde(rename = "@coordsize", default)]+ pub coord_size: Option<String>,+ #[serde(rename = "@coordorigin", default)]+ pub coord_origin: Option<String>,+ /// Recursive: a group's children are themselves primitives.+ #[serde(rename = "$value", default)]+ pub children: Vec<VmlPrimitiveXml>,+}++impl GroupXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlGroup {+ VmlGroup {+ common: VmlCommonAttrs {+ id: self.id.map(VmlShapeId::new),+ style: parse_style(self.style),+ fill_color: self.fillcolor.as_deref().and_then(parse_color),+ stroked: self.stroked.map(|b| b.0),+ ..VmlCommonAttrs::default()+ },+ coord_size: parse_vector2d(self.coord_size),+ coord_origin: parse_vector2d(self.coord_origin),+ children: self+ .children+ .into_iter()+ .filter_map(|c| c.into_model(ctx))+ .collect(),+ }+ }+}++/// Parse a single VML 2D point from a comma-separated `"x,y"` string,+/// honoring CSS-like length units. Returns `None` on parse error so+/// callers can drop malformed values without aborting the whole parse.+fn parse_vml_point(s: &str) -> Option<VmlPoint> {+ let s = s.trim();+ let (xs, ys) = s.split_once(',')?;+ let x = parse_length(xs.trim())?;+ let y = parse_length(ys.trim())?;+ Some(VmlPoint {+ x: pt_value(&x),+ y: pt_value(&y),+ })+}++/// Parse a `<v:polyline>`-style points list: pairs separated by+/// whitespace and/or commas. Skips malformed pairs rather than failing.+fn parse_vml_points(s: &str) -> Vec<VmlPoint> {+ let toks: Vec<&str> = s+ .split(|c: char| c == ',' || c.is_whitespace())+ .filter(|t| !t.is_empty())+ .collect();+ toks.chunks_exact(2)+ .filter_map(|pair| {+ let x = parse_length(pair[0])?;+ let y = parse_length(pair[1])?;+ Some(VmlPoint {+ x: pt_value(&x),+ y: pt_value(&y),+ })+ })+ .collect()+}++/// Convert a parsed `VmlLength` to a plain `f32` in points, honoring+/// the unit. Used by primitive coord parsers; the layout layer keeps+/// the typed `VmlLength` for shape geometry but points/curves are+/// scalar enough that a flat `f32` suffices.+fn pt_value(len: &crate::docx::model::VmlLength) -> f32 {+ // Absolute units come from the shared table on `VmlLength`. The units it+ // leaves unresolved (`%`, `em`, and a bare number) degrade to the raw+ // value here: on a primitive's coordinate attributes a bare number is in+ // the shape's *local* coordinate system, not EMU as it would be in a+ // `style` measurement, and the relative units aren't expected at all.+ len.to_absolute_points().unwrap_or(len.value as f32)+}++// ── textbox ───────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct TextBoxXml {+ #[serde(rename = "@style", default)]+ pub style: Option<String>,+ #[serde(rename = "@inset", default)]+ pub inset: Option<String>,+ #[serde(rename = "txbxContent", default)]+ pub content: Option<TxbxContentXml>,+}++#[derive(Deserialize, Default)]+pub(crate) struct TxbxContentXml {+ #[serde(rename = "$value", default)]+ pub children: Vec<BlockChildXml>,+}++impl TextBoxXml {+ fn into_model(self, ctx: &mut crate::docx::parse::body::ConvertCtx) -> VmlTextBox {+ let content: Vec<Block> = self+ .content+ .map(|c| {+ let (blocks, _) = crate::docx::parse::body::convert_container(c.children, ctx);+ blocks+ })+ .unwrap_or_default();+ VmlTextBox {+ style: parse_style(self.style),+ inset: self.inset.and_then(parse_inset),+ content,+ }+ }+}++/// Parse comma-separated `left,top,right,bottom` CSS lengths.+fn parse_inset(s: String) -> Option<VmlTextBoxInset> {+ let parts: Vec<&str> = s.split(',').collect();+ Some(VmlTextBoxInset {+ left: parts.first().and_then(|v| parse_length(v)),+ top: parts.get(1).and_then(|v| parse_length(v)),+ right: parts.get(2).and_then(|v| parse_length(v)),+ bottom: parts.get(3).and_then(|v| parse_length(v)),+ })+}++// ── stroke ────────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct StrokeXml {+ #[serde(rename = "@dashstyle", default)]+ pub dashstyle: Option<String>,+ #[serde(rename = "@joinstyle", default)]+ pub joinstyle: Option<String>,+}++impl From<StrokeXml> for VmlStroke {+ fn from(x: StrokeXml) -> Self {+ Self {+ dash_style: x.dashstyle.as_deref().and_then(parse_dash_style),+ join_style: x.joinstyle.as_deref().and_then(parse_join_style),+ }+ }+}++fn parse_dash_style(s: &str) -> Option<VmlDashStyle> {+ match s {+ "solid" => Some(VmlDashStyle::Solid),+ "shortdash" => Some(VmlDashStyle::ShortDash),+ "shortdot" => Some(VmlDashStyle::ShortDot),+ "shortdashdot" => Some(VmlDashStyle::ShortDashDot),+ "shortdashdotdot" => Some(VmlDashStyle::ShortDashDotDot),+ "dot" => Some(VmlDashStyle::Dot),+ "dash" => Some(VmlDashStyle::Dash),+ "longdash" => Some(VmlDashStyle::LongDash),+ "dashdot" => Some(VmlDashStyle::DashDot),+ "longdashdot" => Some(VmlDashStyle::LongDashDot),+ "longdashdotdot" => Some(VmlDashStyle::LongDashDotDot),+ _ => None,+ }+}++fn parse_join_style(s: &str) -> Option<VmlJoinStyle> {+ match s {+ "round" => Some(VmlJoinStyle::Round),+ "bevel" => Some(VmlJoinStyle::Bevel),+ "miter" => Some(VmlJoinStyle::Miter),+ _ => None,+ }+}++// ── path ──────────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct PathXml {+ #[serde(rename = "@gradientshapeok", default)]+ pub gradient_shape_ok: Option<VmlBool>,+ #[serde(rename = "@connecttype", default)]+ pub connect_type: Option<String>,+ #[serde(rename = "@extrusionok", default)]+ pub extrusion_ok: Option<VmlBool>,+}++impl From<PathXml> for VmlPath {+ fn from(x: PathXml) -> Self {+ Self {+ gradient_shape_ok: x.gradient_shape_ok.map(|b| b.0),+ connect_type: x.connect_type.as_deref().and_then(|s| match s {+ "none" => Some(VmlConnectType::None),+ "rect" => Some(VmlConnectType::Rect),+ "segments" => Some(VmlConnectType::Segments),+ "custom" => Some(VmlConnectType::Custom),+ _ => None,+ }),+ extrusion_ok: x.extrusion_ok.map(|b| b.0),+ }+ }+}++// ── formulas ──────────────────────────────────────────────────────────────++#[derive(Deserialize, Default)]+pub(crate) struct FormulasXml {+ #[serde(rename = "f", default)]+ pub entries: Vec<FormulaEntryXml>,+}++#[derive(Deserialize)]+pub(crate) struct FormulaEntryXml {+ #[serde(rename = "@eqn", default)]+ pub eqn: String,+}++// Re-exported so VmlFormula is reachable without silencing `unused` warnings.+#[doc(hidden)]+pub(crate) type _KeepFormulaAlive = VmlFormula;++// ── lock ──────────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct LockXml {+ #[serde(rename = "@aspectratio", default)]+ pub aspect_ratio: Option<VmlBool>,+ #[serde(rename = "@ext", default)]+ pub ext: Option<String>,+}++impl From<LockXml> for VmlLock {+ fn from(x: LockXml) -> Self {+ let ext = x.ext.as_deref().and_then(|s| match s {+ "edit" => Some(VmlExtHandling::Edit),+ "view" => Some(VmlExtHandling::View),+ "backwardCompatible" => Some(VmlExtHandling::BackwardCompatible),+ _ => None,+ });+ Self {+ aspect_ratio: x.aspect_ratio.map(|b| b.0),+ ext,+ }+ }+}++// ── imagedata ─────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct ImageDataXml {+ #[serde(rename = "@id", default)]+ pub id: Option<String>,+ #[serde(rename = "@title", default)]+ pub title: Option<String>,+}++impl From<ImageDataXml> for VmlImageData {+ fn from(x: ImageDataXml) -> Self {+ Self {+ rel_id: x.id.map(RelId::new),+ title: x.title,+ }+ }+}++// ── wrap ──────────────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub(crate) struct WrapXml {+ #[serde(rename = "@type", default)]+ pub ty: Option<String>,+ #[serde(rename = "@side", default)]+ pub side: Option<String>,+}++impl From<WrapXml> for VmlWrap {+ fn from(x: WrapXml) -> Self {+ let wrap_type = x.ty.as_deref().and_then(|s| match s {+ "topAndBottom" => Some(VmlWrapType::TopAndBottom),+ "square" => Some(VmlWrapType::Square),+ "none" => Some(VmlWrapType::None),+ "tight" => Some(VmlWrapType::Tight),+ "through" => Some(VmlWrapType::Through),+ _ => None,+ });+ let side = x.side.as_deref().and_then(|s| match s {+ "both" => Some(VmlWrapSide::Both),+ "left" => Some(VmlWrapSide::Left),+ "right" => Some(VmlWrapSide::Right),+ "largest" => Some(VmlWrapSide::Largest),+ _ => None,+ });+ Self { wrap_type, side }+ }+}++// ── helpers ───────────────────────────────────────────────────────────────++/// VML boolean attribute — `"t"`/`"true"` → true, `"f"`/`"false"` → false,+/// anything else silently ignored.+#[derive(Clone, Copy, Debug)]+pub(crate) struct VmlBool(pub bool);++impl<'de> Deserialize<'de> for VmlBool {+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ Ok(Self(matches!(s.as_str(), "t" | "true")))+ }+}++// Keep VmlVector2D reachable so it doesn't trip dead-code lint when the+// only user is via parse_vector2d.+#[doc(hidden)]+pub(crate) fn _keep_vmlvector_alive(v: VmlVector2D) -> VmlVector2D {+ v+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::docx::model::VmlColor;++ fn parse(xml: &str) -> Pict {+ let wrapped = format!(+ r#"<wrap xmlns:v="urn:v" xmlns:o="urn:o" xmlns:w="urn:w" xmlns:r="urn:r">{}</wrap>"#,+ xml+ );+ #[derive(Deserialize)]+ struct Wrap {+ pict: PictXml,+ }+ let w: Wrap = quick_xml::de::from_str(&wrapped).unwrap();+ let mut ctx = crate::docx::parse::body::ConvertCtx::new();+ w.pict.into_model(&mut ctx)+ }++ fn shapes(p: &Pict) -> Vec<&VmlShape> {+ p.shapes().collect()+ }++ #[test]+ fn empty_pict() {+ let p = parse(r#"<pict/>"#);+ assert!(p.shape_type.is_none());+ assert!(p.primitives.is_empty());+ }++ #[test]+ fn minimal_shape_with_fill_and_type_ref() {+ let p = parse(+ r##"<pict>+ <shape id="s1" type="#_x0000_t202"+ style="position:absolute;left:0;top:0;width:100pt;height:50pt"+ fillcolor="#ff0000" stroked="f"/>+ </pict>"##,+ );+ let shapes = shapes(&p);+ assert_eq!(shapes.len(), 1);+ let s = shapes[0];+ assert_eq!(s.common.id.as_ref().map(|v| v.as_str()), Some("s1"));+ assert_eq!(+ s.shape_type_ref.as_ref().map(|v| v.as_str()),+ Some("_x0000_t202")+ );+ assert_eq!(s.common.stroked, Some(false));+ assert!(matches!(+ s.common.fill_color,+ Some(VmlColor::Rgb(0xFF, 0, 0))+ ));+ }++ #[test]+ fn shapetype_with_stroke_and_path() {+ let p = parse(+ r#"<pict>+ <shapetype id="t1" coordsize="21600,21600" adj="5400,5400"+ filled="t" stroked="t" path="m 0,0 l 10,10 x e">+ <stroke dashstyle="dash" joinstyle="miter"/>+ <path gradientshapeok="t" connecttype="rect" extrusionok="f"/>+ <lock aspectratio="t" ext="edit"/>+ </shapetype>+ </pict>"#,+ );+ let st = p.shape_type.expect("shapetype parsed");+ assert_eq!(st.filled, Some(true));+ assert_eq!(st.stroked, Some(true));+ assert_eq!(st.adj, vec![5400, 5400]);+ assert_eq!(st.coord_size, Some(VmlVector2D { x: 21600, y: 21600 }));+ assert!(!st.path.is_empty());+ let stroke = st.stroke.unwrap();+ assert_eq!(stroke.dash_style, Some(VmlDashStyle::Dash));+ assert_eq!(stroke.join_style, Some(VmlJoinStyle::Miter));+ assert_eq!(+ st.vml_path.unwrap().connect_type,+ Some(VmlConnectType::Rect)+ );+ let lock = st.lock.unwrap();+ assert_eq!(lock.aspect_ratio, Some(true));+ assert_eq!(lock.ext, Some(VmlExtHandling::Edit));+ }++ #[test]+ fn shape_with_imagedata() {+ let p = parse(+ r##"<pict>+ <shape id="img1" type="#_x0000_t75" style="width:100pt;height:50pt">+ <imagedata r:id="rId7" o:title="Logo"/>+ </shape>+ </pict>"##,+ );+ let shapes = shapes(&p);+ let id = shapes[0].common.image_data.as_ref().unwrap();+ assert_eq!(id.rel_id.as_ref().map(|r| r.as_str()), Some("rId7"));+ assert_eq!(id.title.as_deref(), Some("Logo"));+ }++ #[test]+ fn shape_with_textbox_no_content() {+ let p = parse(+ r#"<pict>+ <shape id="tb" style="width:100pt;height:50pt">+ <textbox style="mso-fit-shape-to-text:t" inset="1pt,2pt,3pt,4pt">+ <txbxContent/>+ </textbox>+ </shape>+ </pict>"#,+ );+ let shapes = shapes(&p);+ let tb = shapes[0].common.text_box.as_ref().unwrap();+ assert!(tb.content.is_empty());+ assert!(tb.inset.is_some());+ }++ #[test]+ fn shape_with_textbox_containing_paragraph() {+ let p = parse(+ r#"<pict>+ <shape id="tb" style="width:100pt">+ <textbox>+ <txbxContent>+ <w:p><w:r><w:t>Hello VML</w:t></w:r></w:p>+ </txbxContent>+ </textbox>+ </shape>+ </pict>"#,+ );+ let shapes = shapes(&p);+ let tb = shapes[0].common.text_box.as_ref().unwrap();+ assert_eq!(tb.content.len(), 1);+ match &tb.content[0] {+ Block::Paragraph(_) => (),+ other => panic!("expected Paragraph, got {other:?}"),+ }+ }++ #[test]+ fn shape_with_wrap() {+ let p = parse(+ r#"<pict>+ <shape id="wr" style="width:100pt">+ <wrap type="square" side="both"/>+ </shape>+ </pict>"#,+ );+ let shapes = shapes(&p);+ let w = shapes[0].common.wrap.unwrap();+ assert_eq!(w.wrap_type, Some(VmlWrapType::Square));+ assert_eq!(w.side, Some(VmlWrapSide::Both));+ }++ #[test]+ fn multiple_shapes_preserve_order() {+ let p = parse(+ r#"<pict>+ <shape id="a" style="width:10pt"/>+ <shape id="b" style="width:20pt"/>+ <shape id="c" style="width:30pt"/>+ </pict>"#,+ );+ let shapes = shapes(&p);+ assert_eq!(shapes.len(), 3);+ assert_eq!(shapes[0].common.id.as_ref().unwrap().as_str(), "a");+ assert_eq!(shapes[2].common.id.as_ref().unwrap().as_str(), "c");+ }++ #[test]+ fn style_is_parsed_via_existing_helper() {+ let p = parse(+ r#"<pict>+ <shape id="s" style="position:absolute;left:10pt;top:20pt;width:100pt;height:50pt;z-index:5"/>+ </pict>"#,+ );+ let shapes = shapes(&p);+ let st = &shapes[0].common.style;+ assert!(st.position.is_some());+ assert!(st.left.is_some());+ assert_eq!(st.z_index, Some(5));+ }++ // ── §14.1.2 primitive shapes ────────────────────────────────────────++ #[test]+ fn rect_parses_into_rect_primitive() {+ let p = parse(+ r##"<pict>+ <rect id="r1"+ style="position:absolute;margin-left:-.5pt;margin-top:0;width:596.5pt;height:40.5pt"+ fillcolor="#888b8d" stroked="f"/>+ </pict>"##,+ );+ assert_eq!(p.primitives.len(), 1);+ let VmlPrimitive::Rect(r) = &p.primitives[0] else {+ panic!("expected VmlPrimitive::Rect, got {:?}", p.primitives[0]);+ };+ assert_eq!(r.common.id.as_ref().map(|v| v.as_str()), Some("r1"),);+ assert!(matches!(+ r.common.fill_color,+ Some(VmlColor::Rgb(0x88, 0x8B, 0x8D))+ ));+ assert_eq!(r.common.stroked, Some(false));+ assert!(r.common.style.width.is_some());+ }++ #[test]+ fn rect_and_shape_in_same_pict_preserve_order() {+ let p = parse(+ r##"<pict>+ <rect id="r1" style="width:10pt;height:10pt"/>+ <shape id="s1" style="width:20pt;height:20pt"/>+ <rect id="r2" style="width:30pt;height:30pt"/>+ </pict>"##,+ );+ assert_eq!(p.primitives.len(), 3);+ assert!(matches!(p.primitives[0], VmlPrimitive::Rect(_)));+ assert!(matches!(p.primitives[1], VmlPrimitive::Shape(_)));+ assert!(matches!(p.primitives[2], VmlPrimitive::Rect(_)));+ }++ #[test]+ fn roundrect_carries_arcsize() {+ let p = parse(+ r##"<pict>+ <roundrect id="rr" arcsize="0.25" style="width:50pt;height:30pt" fillcolor="#ff0000"/>+ </pict>"##,+ );+ let VmlPrimitive::RoundRect(rr) = &p.primitives[0] else {+ panic!();+ };+ assert!((rr.arcsize.unwrap() - 0.25).abs() < 1e-6);+ }++ #[test]+ fn oval_parses_into_oval_primitive() {+ let p = parse(r#"<pict><oval id="o" style="width:40pt;height:20pt"/></pict>"#);+ assert!(matches!(p.primitives[0], VmlPrimitive::Oval(_)));+ }++ #[test]+ fn line_carries_from_and_to_points() {+ let p = parse(+ r#"<pict>+ <line id="l" from="10pt,20pt" to="100pt,120pt" stroked="t"/>+ </pict>"#,+ );+ let VmlPrimitive::Line(l) = &p.primitives[0] else {+ panic!();+ };+ let from = l.from.unwrap();+ let to = l.to.unwrap();+ assert!((from.x - 10.0).abs() < 1e-3);+ assert!((from.y - 20.0).abs() < 1e-3);+ assert!((to.x - 100.0).abs() < 1e-3);+ assert!((to.y - 120.0).abs() < 1e-3);+ }++ #[test]+ fn polyline_collects_points_from_attribute() {+ let p = parse(+ r#"<pict>+ <polyline id="pl" points="0pt,0pt 10pt,20pt,30pt,40pt"/>+ </pict>"#,+ );+ let VmlPrimitive::PolyLine(pl) = &p.primitives[0] else {+ panic!();+ };+ assert_eq!(pl.points.len(), 3);+ assert!((pl.points[2].x - 30.0).abs() < 1e-3);+ }++ #[test]+ fn arc_carries_start_and_end_angles() {+ let p = parse(+ r#"<pict>+ <arc id="a" startangle="0" endangle="90" style="width:50pt;height:50pt"/>+ </pict>"#,+ );+ let VmlPrimitive::Arc(a) = &p.primitives[0] else {+ panic!();+ };+ assert_eq!(a.start_angle, Some(0.0));+ assert_eq!(a.end_angle, Some(90.0));+ }++ #[test]+ fn curve_parses_all_four_points() {+ let p = parse(+ r#"<pict>+ <curve id="c"+ from="0pt,0pt"+ control1="10pt,10pt"+ control2="20pt,30pt"+ to="40pt,50pt"/>+ </pict>"#,+ );+ let VmlPrimitive::Curve(c) = &p.primitives[0] else {+ panic!();+ };+ assert!(c.from.is_some());+ assert!(c.control1.is_some());+ assert!(c.control2.is_some());+ assert!(c.to.is_some());+ }++ #[test]+ fn image_carries_src_and_image_data() {+ let p = parse(+ r#"<pict>+ <image id="i" src="photo.png" style="width:100pt;height:80pt">+ <imagedata r:id="rId9"/>+ </image>+ </pict>"#,+ );+ let VmlPrimitive::Image(img) = &p.primitives[0] else {+ panic!();+ };+ assert_eq!(img.src.as_deref(), Some("photo.png"));+ assert_eq!(+ img.common+ .image_data+ .as_ref()+ .and_then(|d| d.rel_id.as_ref().map(|r| r.as_str())),+ Some("rId9"),+ );+ }++ #[test]+ fn group_recursively_parses_children() {+ let p = parse(+ r##"<pict>+ <group id="g" coordsize="21600,21600" coordorigin="0,0">+ <rect id="r" style="width:10pt;height:10pt" fillcolor="#ff0000"/>+ <oval id="o" style="width:20pt;height:20pt"/>+ </group>+ </pict>"##,+ );+ let VmlPrimitive::Group(g) = &p.primitives[0] else {+ panic!();+ };+ assert_eq!(g.children.len(), 2);+ assert!(matches!(g.children[0], VmlPrimitive::Rect(_)));+ assert!(matches!(g.children[1], VmlPrimitive::Oval(_)));+ assert_eq!(g.coord_size.as_ref().map(|v| v.x), Some(21600));+ }++ #[test]+ fn rect_textbox_content_is_populated() {+ // Regression for the gray-bar text bug: `<v:rect>` with a+ // `<v:textbox><w:txbxContent>` should reach the model with+ // its inner paragraphs intact, just like `<v:shape>` does.+ // The `flatten` indirection on `RectXml.common` was dropping+ // the inner content when this test was first added.+ use crate::docx::model::VmlPrimitive;+ let p = parse(+ r#"<pict>+ <rect id="r" style="width:100pt;height:50pt">+ <textbox>+ <txbxContent>+ <w:p><w:r><w:t>Inside the rect</w:t></w:r></w:p>+ </txbxContent>+ </textbox>+ </rect>+ </pict>"#,+ );+ let VmlPrimitive::Rect(r) = &p.primitives[0] else {+ panic!();+ };+ let tb = r.common.text_box.as_ref().expect("textbox parsed");+ assert_eq!(tb.content.len(), 1, "textbox should contain one paragraph");+ }++ #[test]+ fn rect_with_fill_child_carries_fill_type_and_color() {+ // §14.1.2.5: `<v:fill>` overrides `@fillcolor`. The model+ // carries both — the renderer's fill resolver picks the+ // child when present.+ use crate::docx::model::{VmlFillType, VmlPrimitive};+ let p = parse(+ r##"<pict>+ <rect id="r" style="width:50pt;height:30pt" fillcolor="#ff0000">+ <fill type="solid" color="#00ff00"/>+ </rect>+ </pict>"##,+ );+ let VmlPrimitive::Rect(r) = &p.primitives[0] else {+ panic!();+ };+ assert!(matches!(+ r.common.fill_color,+ Some(VmlColor::Rgb(0xFF, 0, 0))+ ));+ let fill = r.common.fill.as_ref().expect("fill child parsed");+ assert_eq!(fill.fill_type, VmlFillType::Solid);+ assert!(matches!(fill.color, Some(VmlColor::Rgb(0, 0xFF, 0))));+ }++ #[test]+ fn fill_type_gradient_and_tile_are_modeled() {+ use crate::docx::model::{VmlFillType, VmlPrimitive};+ for (input, expected) in [+ ("gradient", VmlFillType::Gradient),+ ("gradientRadial", VmlFillType::GradientRadial),+ ("tile", VmlFillType::Tile),+ ("frame", VmlFillType::Frame),+ ("pattern", VmlFillType::Pattern),+ ] {+ let xml = format!(+ r##"<pict>+ <rect id="r" style="width:10pt;height:10pt">+ <fill type="{input}" color="#aabbcc"/>+ </rect>+ </pict>"##+ );+ let p = parse(&xml);+ let VmlPrimitive::Rect(r) = &p.primitives[0] else {+ panic!();+ };+ assert_eq!(+ r.common.fill.as_ref().unwrap().fill_type,+ expected,+ "fill type {input} should map to {expected:?}"+ );+ }+ }++ #[test]+ fn fill_with_image_source_carries_src_attribute() {+ use crate::docx::model::VmlPrimitive;+ let p = parse(+ r#"<pict>+ <rect id="r" style="width:10pt;height:10pt">+ <fill type="frame" src="watermark.png"/>+ </rect>+ </pict>"#,+ );+ let VmlPrimitive::Rect(r) = &p.primitives[0] else {+ panic!();+ };+ let fill = r.common.fill.as_ref().unwrap();+ assert_eq!(fill.src.as_deref(), Some("watermark.png"));+ }++ #[test]+ fn unknown_vml_element_falls_into_other_and_is_dropped() {+ let p = parse(+ r#"<pict>+ <rect id="r" style="width:10pt;height:10pt"/>+ <unknownVmlThing foo="bar"/>+ </pict>"#,+ );+ // Only the rect survives; the unknown element is silently+ // discarded by `VmlPrimitiveXml::Other` → `into_model = None`.+ assert_eq!(p.primitives.len(), 1);+ assert!(matches!(p.primitives[0], VmlPrimitive::Rect(_)));+ }+}diff --git a/crates/liteparse-docx/src/docx/parse/vml/style.rs b/crates/liteparse-docx/src/docx/parse/vml/style.rsnew file mode 100644index 0000000..15db538--- /dev/null+++ b/crates/liteparse-docx/src/docx/parse/vml/style.rs@@ -0,0 +1,341 @@+//! VML CSS style and length parsing.++use crate::docx::model::*;++/// Parse a VML `style` attribute — semicolon-separated CSS2 properties.+pub(super) fn parse_style(s: Option<String>) -> VmlStyle {+ let s = match s {+ Some(s) => s,+ None => return VmlStyle::default(),+ };++ let mut style = VmlStyle::default();++ for decl in s.split(';') {+ let decl = decl.trim();+ if decl.is_empty() {+ continue;+ }+ let Some((key, val)) = decl.split_once(':') else {+ continue;+ };+ let key = key.trim();+ let val = val.trim();++ match key {+ "position" => {+ style.position = match val {+ "static" => Some(CssPosition::Static),+ "relative" => Some(CssPosition::Relative),+ "absolute" => Some(CssPosition::Absolute),+ _ => {+ log::warn!("vml-style: unsupported position value {:?}", val);+ None+ }+ };+ }+ "left" => style.left = parse_length(val),+ "top" => style.top = parse_length(val),+ "width" => style.width = parse_length(val),+ "height" => style.height = parse_length(val),+ "margin-left" => style.margin_left = parse_length(val),+ "margin-top" => style.margin_top = parse_length(val),+ "margin-right" => style.margin_right = parse_length(val),+ "margin-bottom" => style.margin_bottom = parse_length(val),+ "z-index" => style.z_index = val.parse::<i64>().ok(),+ "rotation" => style.rotation = val.parse::<f64>().ok(),+ "flip" => {+ style.flip = match val {+ "x" => Some(VmlFlip::X),+ "y" => Some(VmlFlip::Y),+ "xy" | "yx" => Some(VmlFlip::XY),+ _ => {+ log::warn!("vml-style: unsupported flip value {:?}", val);+ None+ }+ };+ }+ "visibility" => {+ style.visibility = match val {+ "visible" => Some(CssVisibility::Visible),+ "hidden" => Some(CssVisibility::Hidden),+ "inherit" => Some(CssVisibility::Inherit),+ _ => {+ log::warn!("vml-style: unsupported visibility value {:?}", val);+ None+ }+ };+ }+ "mso-position-horizontal" => {+ style.mso_position_horizontal = match val {+ "absolute" => Some(MsoPositionH::Absolute),+ "left" => Some(MsoPositionH::Left),+ "center" => Some(MsoPositionH::Center),+ "right" => Some(MsoPositionH::Right),+ "inside" => Some(MsoPositionH::Inside),+ "outside" => Some(MsoPositionH::Outside),+ _ => {+ log::warn!(+ "vml-style: unsupported mso-position-horizontal value {:?}",+ val+ );+ None+ }+ };+ }+ "mso-position-horizontal-relative" => {+ style.mso_position_horizontal_relative = match val {+ "margin" => Some(MsoPositionHRelative::Margin),+ "page" => Some(MsoPositionHRelative::Page),+ "text" => Some(MsoPositionHRelative::Text),+ "char" => Some(MsoPositionHRelative::Char),+ "left-margin-area" => Some(MsoPositionHRelative::LeftMarginArea),+ "right-margin-area" => Some(MsoPositionHRelative::RightMarginArea),+ "inner-margin-area" => Some(MsoPositionHRelative::InnerMarginArea),+ "outer-margin-area" => Some(MsoPositionHRelative::OuterMarginArea),+ _ => {+ log::warn!(+ "vml-style: unsupported mso-position-horizontal-relative value {:?}",+ val+ );+ None+ }+ };+ }+ "mso-position-vertical" => {+ style.mso_position_vertical = match val {+ "absolute" => Some(MsoPositionV::Absolute),+ "top" => Some(MsoPositionV::Top),+ "center" => Some(MsoPositionV::Center),+ "bottom" => Some(MsoPositionV::Bottom),+ "inside" => Some(MsoPositionV::Inside),+ "outside" => Some(MsoPositionV::Outside),+ _ => {+ log::warn!(+ "vml-style: unsupported mso-position-vertical value {:?}",+ val+ );+ None+ }+ };+ }+ "mso-position-vertical-relative" => {+ style.mso_position_vertical_relative = match val {+ "margin" => Some(MsoPositionVRelative::Margin),+ "page" => Some(MsoPositionVRelative::Page),+ "text" => Some(MsoPositionVRelative::Text),+ "line" => Some(MsoPositionVRelative::Line),+ "top-margin-area" => Some(MsoPositionVRelative::TopMarginArea),+ "bottom-margin-area" => Some(MsoPositionVRelative::BottomMarginArea),+ "inner-margin-area" => Some(MsoPositionVRelative::InnerMarginArea),+ "outer-margin-area" => Some(MsoPositionVRelative::OuterMarginArea),+ _ => {+ log::warn!(+ "vml-style: unsupported mso-position-vertical-relative value {:?}",+ val+ );+ None+ }+ };+ }+ "mso-wrap-distance-left" => {+ style.mso_wrap_distance_left = parse_length(val);+ }+ "mso-wrap-distance-right" => {+ style.mso_wrap_distance_right = parse_length(val);+ }+ "mso-wrap-distance-top" => {+ style.mso_wrap_distance_top = parse_length(val);+ }+ "mso-wrap-distance-bottom" => {+ style.mso_wrap_distance_bottom = parse_length(val);+ }+ "mso-wrap-style" => {+ style.mso_wrap_style = match val {+ "square" => Some(MsoWrapStyle::Square),+ "none" => Some(MsoWrapStyle::None),+ "tight" => Some(MsoWrapStyle::Tight),+ "through" => Some(MsoWrapStyle::Through),+ _ => {+ log::warn!("vml-style: unsupported mso-wrap-style value {:?}", val);+ None+ }+ };+ }+ _ => log::warn!("vml-style: unsupported property {:?}: {:?}", key, val),+ }+ }++ style+}++/// Parse a CSS length value (e.g., "468pt", "0", "3.5in", "50%").+pub(super) fn parse_length(s: &str) -> Option<VmlLength> {+ let s = s.trim();+ if s.is_empty() {+ return None;+ }++ // Try known unit suffixes.+ let (num_str, unit) = if let Some(n) = s.strip_suffix("pt") {+ (n, VmlLengthUnit::Pt)+ } else if let Some(n) = s.strip_suffix("in") {+ (n, VmlLengthUnit::In)+ } else if let Some(n) = s.strip_suffix("cm") {+ (n, VmlLengthUnit::Cm)+ } else if let Some(n) = s.strip_suffix("mm") {+ (n, VmlLengthUnit::Mm)+ } else if let Some(n) = s.strip_suffix("px") {+ (n, VmlLengthUnit::Px)+ } else if let Some(n) = s.strip_suffix("em") {+ (n, VmlLengthUnit::Em)+ } else if let Some(n) = s.strip_suffix('%') {+ (n, VmlLengthUnit::Percent)+ } else {+ // Find where the numeric part ends and the suffix begins.+ let split = s+ .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-' && c != '+')+ .unwrap_or(s.len());+ if split < s.len() {+ log::warn!("vml-length: unsupported unit suffix {:?}", &s[split..]);+ return None;+ }+ (s, VmlLengthUnit::None)+ };++ let value = num_str.trim().parse::<f64>().ok()?;+ Some(VmlLength { value, unit })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn none_yields_default() {+ let s = parse_style(None);+ assert!(s.position.is_none());+ assert!(s.left.is_none());+ }++ #[test]+ fn position_and_dimensions() {+ let s = parse_style(Some(+ "position:absolute;left:10pt;top:20pt;width:100pt;height:50pt".into(),+ ));+ assert_eq!(s.position, Some(CssPosition::Absolute));+ assert_eq!(+ s.left,+ Some(VmlLength {+ value: 10.0,+ unit: VmlLengthUnit::Pt+ })+ );+ assert_eq!(+ s.width,+ Some(VmlLength {+ value: 100.0,+ unit: VmlLengthUnit::Pt+ })+ );+ assert_eq!(+ s.height,+ Some(VmlLength {+ value: 50.0,+ unit: VmlLengthUnit::Pt+ })+ );+ }++ #[test]+ fn flip_and_visibility() {+ let s = parse_style(Some("flip:xy;visibility:hidden".into()));+ assert_eq!(s.flip, Some(VmlFlip::XY));+ assert_eq!(s.visibility, Some(CssVisibility::Hidden));+ }++ #[test]+ fn mso_positioning() {+ let s = parse_style(Some(+ "mso-position-horizontal:center;mso-position-vertical-relative:line".into(),+ ));+ assert_eq!(s.mso_position_horizontal, Some(MsoPositionH::Center));+ assert_eq!(+ s.mso_position_vertical_relative,+ Some(MsoPositionVRelative::Line)+ );+ }++ #[test]+ fn z_index_and_rotation() {+ let s = parse_style(Some("z-index:5;rotation:45".into()));+ assert_eq!(s.z_index, Some(5));+ assert_eq!(s.rotation, Some(45.0));+ }++ #[test]+ fn whitespace_and_unknown_props_are_ignored() {+ // Extra whitespace, a trailing empty declaration, and an unrecognized+ // property must not derail the recognized ones.+ let s = parse_style(Some(" left : 3pt ; mso-bogus:1 ;".into()));+ assert_eq!(+ s.left,+ Some(VmlLength {+ value: 3.0,+ unit: VmlLengthUnit::Pt+ })+ );+ }++ #[test]+ fn length_units() {+ assert_eq!(+ parse_length("468pt"),+ Some(VmlLength {+ value: 468.0,+ unit: VmlLengthUnit::Pt+ })+ );+ assert_eq!(+ parse_length("3.5in"),+ Some(VmlLength {+ value: 3.5,+ unit: VmlLengthUnit::In+ })+ );+ assert_eq!(+ parse_length("50%"),+ Some(VmlLength {+ value: 50.0,+ unit: VmlLengthUnit::Percent+ })+ );+ assert_eq!(+ parse_length("-10pt"),+ Some(VmlLength {+ value: -10.0,+ unit: VmlLengthUnit::Pt+ })+ );+ }++ #[test]+ fn unitless_length() {+ assert_eq!(+ parse_length("0"),+ Some(VmlLength {+ value: 0.0,+ unit: VmlLengthUnit::None+ })+ );+ }++ #[test]+ fn empty_and_unsupported_unit_are_none() {+ assert!(parse_length("").is_none());+ assert!(parse_length(" ").is_none());+ // Unknown unit suffix → warn + None (rather than a wrong value).+ assert!(parse_length("10xyz").is_none());+ assert!(parse_length("auto").is_none());+ }+}diff --git a/crates/liteparse-docx/src/docx/relationships.rs b/crates/liteparse-docx/src/docx/relationships.rsnew file mode 100644index 0000000..7adf310--- /dev/null+++ b/crates/liteparse-docx/src/docx/relationships.rs@@ -0,0 +1,304 @@+//! OOXML package relationships (`.rels` files).++use log::warn;+use serde::{Deserialize, Deserializer};++use crate::docx::error::Result;+use crate::docx::model::RelId;+use crate::docx::parse::serde_xml::from_xml;++/// A parsed relationship from a .rels file.+#[derive(Clone, Debug)]+pub struct Relationship {+ pub id: RelId,+ pub rel_type: RelationshipType,+ pub target: String,+ pub target_mode: TargetMode,+}++/// Known OOXML relationship types (§7.1, §11.3, §15.2).+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum RelationshipType {+ /// §11.3.10: main document part.+ OfficeDocument,+ /// §11.3.11: style definitions.+ Styles,+ /// §11.3.7: numbering definitions.+ Numbering,+ /// §11.3.9: document settings.+ Settings,+ /// §11.3.5: font table.+ FontTable,+ /// §14.2.7: theme.+ Theme,+ /// §11.3.6: header part.+ Header,+ /// §11.3.4: footer part.+ Footer,+ /// §11.3.3: footnotes part.+ Footnotes,+ /// §11.3.2: endnotes part.+ Endnotes,+ /// §15.2.13: font.+ Font,+ /// §15.2.14: image.+ Image,+ /// §15.3.6: hyperlink.+ Hyperlink,+ /// §11.3.1: comments part.+ Comments,+ /// §15.2.12.1: core (Dublin Core) properties.+ CoreProperties,+ /// §15.2.12.3: extended (application) properties.+ ExtendedProperties,+ /// §15.2.12.2: custom properties.+ CustomProperties,+ /// §15.2.1.1: custom XML data.+ CustomXml,+ /// §11.3.12: web settings.+ WebSettings,+ /// MS Office extension: styles with effects (Office 2007+).+ StylesWithEffects,+ /// §11.3.8: glossary/building blocks document.+ GlossaryDocument,+ /// Any relationship type not listed above.+ Unknown(String),+}++impl RelationshipType {+ fn from_uri(uri: &str) -> Self {+ // OOXML uses long URIs; match on the final segment.+ if uri.ends_with("/officeDocument") || uri.ends_with("/document") {+ Self::OfficeDocument+ } else if uri.ends_with("/styles") {+ Self::Styles+ } else if uri.ends_with("/numbering") {+ Self::Numbering+ } else if uri.ends_with("/settings") {+ Self::Settings+ } else if uri.ends_with("/fontTable") {+ Self::FontTable+ } else if uri.ends_with("/theme") {+ Self::Theme+ } else if uri.ends_with("/header") {+ Self::Header+ } else if uri.ends_with("/footer") {+ Self::Footer+ } else if uri.ends_with("/footnotes") {+ Self::Footnotes+ } else if uri.ends_with("/endnotes") {+ Self::Endnotes+ } else if uri.ends_with("/font") {+ Self::Font+ } else if uri.ends_with("/image") {+ Self::Image+ } else if uri.ends_with("/hyperlink") {+ Self::Hyperlink+ } else if uri.ends_with("/comments") {+ Self::Comments+ } else if uri.ends_with("/core-properties") {+ Self::CoreProperties+ } else if uri.ends_with("/extended-properties") {+ Self::ExtendedProperties+ } else if uri.ends_with("/custom-properties") {+ Self::CustomProperties+ } else if uri.ends_with("/customXml") {+ Self::CustomXml+ } else if uri.ends_with("/webSettings") {+ Self::WebSettings+ } else if uri.ends_with("/stylesWithEffects") {+ Self::StylesWithEffects+ } else if uri.ends_with("/glossaryDocument") {+ Self::GlossaryDocument+ } else {+ warn!("unknown relationship type: {}", uri);+ Self::Unknown(uri.to_string())+ }+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum TargetMode {+ #[default]+ Internal,+ External,+}++impl<'de> Deserialize<'de> for TargetMode {+ fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ Ok(if s.eq_ignore_ascii_case("external") {+ TargetMode::External+ } else {+ TargetMode::Internal+ })+ }+}++/// A collection of relationships from a single .rels file.+#[derive(Clone, Debug, Default)]+pub struct Relationships {+ pub(crate) rels: Vec<Relationship>,+}++impl Relationships {+ /// Parse a .rels XML file.+ pub fn parse(data: &[u8]) -> Result<Self> {+ from_xml::<RelationshipsXml>(data).map(Into::into)+ }++ /// Find the first relationship of a given type.+ pub fn find_by_type(&self, rel_type: &RelationshipType) -> Option<&Relationship> {+ self.rels.iter().find(|r| &r.rel_type == rel_type)+ }++ /// Find all relationships of a given type.+ pub fn filter_by_type(&self, rel_type: &RelationshipType) -> Vec<&Relationship> {+ self.rels+ .iter()+ .filter(|r| &r.rel_type == rel_type)+ .collect()+ }++ /// Look up a relationship by its ID.+ pub fn find_by_id(&self, id: &str) -> Option<&Relationship> {+ self.rels.iter().find(|r| r.id.as_str() == id)+ }++ /// Get all relationships.+ pub fn all(&self) -> &[Relationship] {+ &self.rels+ }+}++#[derive(Deserialize, Default)]+struct RelationshipsXml {+ #[serde(rename = "Relationship", default)]+ rels: Vec<RelationshipXml>,+}++#[derive(Deserialize)]+struct RelationshipXml {+ #[serde(rename = "@Id")]+ id: String,+ #[serde(rename = "@Type")]+ rel_type: String,+ #[serde(rename = "@Target")]+ target: String,+ #[serde(rename = "@TargetMode", default)]+ target_mode: TargetMode,+}++impl From<RelationshipsXml> for Relationships {+ fn from(x: RelationshipsXml) -> Self {+ Self {+ rels: x.rels.into_iter().map(Relationship::from).collect(),+ }+ }+}++impl From<RelationshipXml> for Relationship {+ fn from(r: RelationshipXml) -> Self {+ Self {+ id: RelId::new(r.id),+ rel_type: RelationshipType::from_uri(&r.rel_type),+ target: r.target,+ target_mode: r.target_mode,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";++ fn classify(suffix: &str) -> RelationshipType {+ RelationshipType::from_uri(&format!("{NS}/{suffix}"))+ }++ #[test]+ fn classifies_common_types() {+ assert_eq!(classify("officeDocument"), RelationshipType::OfficeDocument);+ assert_eq!(classify("styles"), RelationshipType::Styles);+ assert_eq!(classify("numbering"), RelationshipType::Numbering);+ assert_eq!(classify("settings"), RelationshipType::Settings);+ assert_eq!(classify("theme"), RelationshipType::Theme);+ assert_eq!(classify("header"), RelationshipType::Header);+ assert_eq!(classify("footer"), RelationshipType::Footer);+ assert_eq!(classify("footnotes"), RelationshipType::Footnotes);+ assert_eq!(classify("endnotes"), RelationshipType::Endnotes);+ assert_eq!(classify("image"), RelationshipType::Image);+ assert_eq!(classify("hyperlink"), RelationshipType::Hyperlink);+ }++ // These pairs share a suffix prefix, so the order of the `ends_with`+ // chain in `from_uri` matters. A reorder that let the shorter suffix win+ // would silently misclassify — these lock the distinction in.+ #[test]+ fn font_table_is_not_font() {+ assert_eq!(classify("fontTable"), RelationshipType::FontTable);+ assert_eq!(classify("font"), RelationshipType::Font);+ }++ #[test]+ fn styles_with_effects_is_not_styles() {+ assert_eq!(+ classify("stylesWithEffects"),+ RelationshipType::StylesWithEffects+ );+ assert_eq!(classify("styles"), RelationshipType::Styles);+ }++ #[test]+ fn property_relationship_types_are_distinct() {+ // core-properties uses a different namespace in practice, but the+ // suffix match is what disambiguates it from the -properties siblings.+ assert_eq!(+ RelationshipType::from_uri(+ "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"+ ),+ RelationshipType::CoreProperties+ );+ assert_eq!(+ classify("extended-properties"),+ RelationshipType::ExtendedProperties+ );+ assert_eq!(+ classify("custom-properties"),+ RelationshipType::CustomProperties+ );+ }++ #[test]+ fn unknown_type_is_preserved_not_dropped() {+ let uri = "http://example.com/relationships/somethingNovel";+ assert_eq!(+ RelationshipType::from_uri(uri),+ RelationshipType::Unknown(uri.to_string())+ );+ }++ #[test]+ fn target_mode_defaults_to_internal_and_is_case_insensitive() {+ let xml = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId1" Type="http://x/image" Target="media/i.png"/>+ <Relationship Id="rId2" Type="http://x/hyperlink" Target="http://e.com" TargetMode="External"/>+ <Relationship Id="rId3" Type="http://x/hyperlink" Target="http://e.com" TargetMode="eXtErNaL"/>+ </Relationships>"#;+ let rels = Relationships::parse(xml).expect("parse rels");+ assert_eq!(+ rels.find_by_id("rId1").unwrap().target_mode,+ TargetMode::Internal+ );+ assert_eq!(+ rels.find_by_id("rId2").unwrap().target_mode,+ TargetMode::External+ );+ assert_eq!(+ rels.find_by_id("rId3").unwrap().target_mode,+ TargetMode::External+ );+ }+}diff --git a/crates/liteparse-docx/src/docx/whitespace_workaround.rs b/crates/liteparse-docx/src/docx/whitespace_workaround.rsnew file mode 100644index 0000000..2ebd712--- /dev/null+++ b/crates/liteparse-docx/src/docx/whitespace_workaround.rs@@ -0,0 +1,429 @@+//! Workaround for quick-xml's silent whitespace stripping.+//!+//! # The problem+//!+//! quick-xml's serde [`Deserializer`](quick_xml::de::Deserializer) wraps every+//! input reader in a private trimmer that drops `Text` events containing only+//! whitespace. Even when the source XML carries `xml:space="preserve"`, the+//! trimmer eats the content before any visitor sees it. Custom `Deserialize`+//! impls cannot intercept — the relevant constructors and trim flag are private,+//! and `XmlRead` cannot be plugged in via any public API in 0.39.+//!+//! In Word documents this typically appears as `<w:r>` runs that contain a+//! single whitespace-only `<w:t xml:space="preserve"> </w:t>` between two+//! other runs (e.g. a label followed by a value with different formatting).+//! Without this workaround, the space disappears and rendered text reads+//! `Label:Value` instead of `Label: Value`.+//!+//! # The hack+//!+//! Before handing each XML part to quick-xml we resolve WordprocessingML text+//! elements, then substitute each byte in a whitespace-only text node with a+//! Private Use Area codepoint. quick-xml then sees a non-whitespace text node+//! and preserves it. Resolving namespaces makes the workaround independent of+//! the arbitrary prefix chosen by the DOCX producer. The body parser+//! ([`crate::docx::parse::body`]) reverses the substitution when emitting+//! [`RunElement::Text`].+//!+//! Sentinel mapping (BYTE → CHAR):+//!+//! | source byte | sentinel |+//! |-------------|-------------|+//! | `0x20` SP | `U+E020` |+//! | `0x09` HT | `U+E009` |+//! | `0x0A` LF | `U+E00A` |+//! | `0x0D` CR | `U+E00D` |+//!+//! The pattern `0xE000 + <ASCII byte>` keeps the reversal trivial and ensures+//! sentinels never collide with anything OOXML legitimately emits — Word never+//! writes Private Use Area codepoints.+//!+//! TODO(quick-xml): drop this module once one of the following lands upstream+//! and we adopt it:+//! * a public `Deserializer` constructor that accepts a custom `XmlRead`,+//! * a public knob to disable `StartTrimmer`, or+//! * `xml:space="preserve"` honored for whitespace-only `Text` events.+//!+//! Tracked upstream at the quick-xml repository+//! (<https://github.com/tafia/quick-xml>); this module is the local+//! stopgap until one of the above is available.++/// Sentinel for ASCII space (`0x20`).+pub(crate) const WS_SENTINEL_SPACE: char = '\u{E020}';+/// Sentinel for ASCII tab (`0x09`).+pub(crate) const WS_SENTINEL_TAB: char = '\u{E009}';+/// Sentinel for ASCII line feed (`0x0A`).+pub(crate) const WS_SENTINEL_LF: char = '\u{E00A}';+/// Sentinel for ASCII carriage return (`0x0D`).+pub(crate) const WS_SENTINEL_CR: char = '\u{E00D}';++const TRANSITIONAL_WORDPROCESSINGML_NAMESPACE: &[u8] =+ b"http://schemas.openxmlformats.org/wordprocessingml/2006/main";+const STRICT_WORDPROCESSINGML_NAMESPACE: &[u8] =+ b"http://purl.oclc.org/ooxml/wordprocessingml/main";++#[inline]+fn is_wordprocessingml_namespace(uri: &[u8]) -> bool {+ matches!(+ uri,+ TRANSITIONAL_WORDPROCESSINGML_NAMESPACE | STRICT_WORDPROCESSINGML_NAMESPACE+ )+}++/// Pre-process an XML byte buffer so whitespace-only WordprocessingML text+/// content survives quick-xml's trimmer. Returns the original buffer unchanged+/// when no substitution is needed.+///+/// See module-level docs for why this is necessary.+pub(crate) fn substitute_whitespace_only_runs(xml: &[u8]) -> Vec<u8> {+ let spans = whitespace_only_wordprocessingml_text_spans(xml);+ if spans.is_empty() {+ return xml.to_vec();+ }++ let mut out: Vec<u8> = Vec::with_capacity(xml.len());+ let mut cursor = 0;+ for (start, end) in spans {+ out.extend_from_slice(&xml[cursor..start]);+ substitute_whitespace(&xml[start..end], &mut out);+ cursor = end;+ }+ out.extend_from_slice(&xml[cursor..]);+ out+}++/// Reverse the sentinel substitution. Returns the original string when no+/// sentinels are present (zero-allocation common path).+pub(crate) fn restore_whitespace_sentinels(s: &str) -> String {+ if !s.chars().any(is_ws_sentinel) {+ return s.to_string();+ }+ let mut out = String::with_capacity(s.len());+ for ch in s.chars() {+ out.push(match ch {+ WS_SENTINEL_SPACE => ' ',+ WS_SENTINEL_TAB => '\t',+ WS_SENTINEL_LF => '\n',+ WS_SENTINEL_CR => '\r',+ other => other,+ });+ }+ out+}++#[inline]+fn is_xml_whitespace_byte(b: &u8) -> bool {+ matches!(*b, b' ' | b'\t' | b'\n' | b'\r')+}++#[inline]+fn is_ws_sentinel(c: char) -> bool {+ matches!(+ c,+ WS_SENTINEL_SPACE | WS_SENTINEL_TAB | WS_SENTINEL_LF | WS_SENTINEL_CR+ )+}++/// Return source spans for whitespace-only text nodes directly inside+/// WordprocessingML `<*:t>` elements. Namespace prefixes are resolved by+/// quick-xml, so DrawingML and other XML vocabularies are not mutated.+/// Malformed XML is left untouched.+fn whitespace_only_wordprocessingml_text_spans(xml: &[u8]) -> Vec<(usize, usize)> {+ use quick_xml::events::Event;+ use quick_xml::name::ResolveResult;+ use quick_xml::reader::NsReader;++ let mut reader = NsReader::from_reader(xml);+ reader.config_mut().trim_text(false);+ let mut spans = Vec::new();+ let mut depth: usize = 0;+ let mut text_depth = None;++ loop {+ let (namespace, event) = match reader.read_resolved_event() {+ Ok(event) => event,+ Err(_) => return Vec::new(),+ };++ match event {+ Event::Start(start) => {+ depth += 1;+ if matches!(namespace, ResolveResult::Bound(uri) if is_wordprocessingml_namespace(uri.as_ref()))+ && start.local_name().as_ref() == b"t"+ {+ text_depth = Some(depth);+ }+ }+ Event::Text(text) if text_depth.is_some() => {+ let content = text.as_ref();+ if !content.is_empty() && content.iter().all(is_xml_whitespace_byte) {+ let end = reader.buffer_position() as usize;+ let Some(start) = end.checked_sub(content.len()) else {+ return Vec::new();+ };+ spans.push((start, end));+ }+ }+ Event::End(_) => {+ if text_depth == Some(depth) {+ text_depth = None;+ }+ depth = depth.saturating_sub(1);+ }+ Event::Eof => return if depth == 0 { spans } else { Vec::new() },+ _ => {}+ }+ }+}++fn substitute_whitespace(content: &[u8], out: &mut Vec<u8>) {+ for &b in content {+ let sentinel = match b {+ b' ' => WS_SENTINEL_SPACE,+ b'\t' => WS_SENTINEL_TAB,+ b'\n' => WS_SENTINEL_LF,+ b'\r' => WS_SENTINEL_CR,+ _ => unreachable!("caller only passes XML whitespace"),+ };+ let mut buf = [0u8; 4];+ out.extend_from_slice(sentinel.encode_utf8(&mut buf).as_bytes());+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn s(b: Vec<u8>) -> String {+ String::from_utf8(b).unwrap()+ }++ fn substitute_wml_fragment(fragment: &str) -> String {+ let open =+ r#"<w:root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">"#;+ let xml = format!("{open}{fragment}</w:root>");+ let out = s(substitute_whitespace_only_runs(xml.as_bytes()));+ out.strip_prefix(open)+ .and_then(|out| out.strip_suffix("</w:root>"))+ .unwrap()+ .to_string()+ }++ // ── substitute_whitespace_only_runs ──────────────────────────────────────++ #[test]+ fn single_space_preserve_is_substituted() {+ let xml = br#"<w:r><w:t xml:space="preserve"> </w:t></w:r>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(+ out,+ format!(+ r#"<w:r><w:t xml:space="preserve">{}</w:t></w:r>"#,+ WS_SENTINEL_SPACE+ )+ );+ }++ #[test]+ fn three_spaces_preserve_each_substituted() {+ let xml = br#"<w:t xml:space="preserve"> </w:t>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ let expected = format!(+ r#"<w:t xml:space="preserve">{0}{0}{0}</w:t>"#,+ WS_SENTINEL_SPACE+ );+ assert_eq!(out, expected);+ }++ #[test]+ fn whitespace_only_without_preserve_is_also_substituted() {+ // Many third-party DOCX writers emit whitespace-only <w:t> without the+ // xml:space attribute. quick-xml strips them all the same.+ let xml = br#"<w:t> </w:t>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(out, format!("<w:t>{}</w:t>", WS_SENTINEL_SPACE));+ }++ #[test]+ fn tab_only_is_substituted() {+ let xml = b"<w:t xml:space=\"preserve\">\t</w:t>";+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(+ out,+ format!("<w:t xml:space=\"preserve\">{}</w:t>", WS_SENTINEL_TAB)+ );+ }++ #[test]+ fn lf_and_cr_substituted() {+ let xml = b"<w:t xml:space=\"preserve\">\r\n</w:t>";+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(+ out,+ format!(+ "<w:t xml:space=\"preserve\">{}{}</w:t>",+ WS_SENTINEL_CR, WS_SENTINEL_LF+ )+ );+ }++ #[test]+ fn mixed_content_is_left_untouched() {+ // Content has a non-whitespace char → quick-xml preserves it as-is,+ // we must not modify.+ let xml = br#"<w:t xml:space="preserve">hello world </w:t>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(out, std::str::from_utf8(xml).unwrap());+ }++ #[test]+ fn empty_w_t_is_left_untouched() {+ let xml = br#"<w:t></w:t>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(out, std::str::from_utf8(xml).unwrap());+ }++ #[test]+ fn self_closing_w_t_is_left_untouched() {+ let xml = br#"<w:t xml:space="preserve"/>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(out, std::str::from_utf8(xml).unwrap());+ }++ #[test]+ fn longer_element_names_are_not_matched() {+ // `<w:tbl>`, `<w:tab/>`, `<w:tc>` all start with `<w:t` but should not+ // trigger substitution.+ let xml = br#"<w:tbl><w:tr><w:tc><w:tab/></w:tc></w:tr></w:tbl>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(out, std::str::from_utf8(xml).unwrap());+ }++ #[test]+ fn multiple_runs_in_one_buffer() {+ let xml = br#"<w:p><w:r><w:t>A</w:t></w:r><w:r><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t>B</w:t></w:r></w:p>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ let expected = format!(+ r#"<w:p><w:r><w:t>A</w:t></w:r><w:r><w:t xml:space="preserve">{}</w:t></w:r><w:r><w:t>B</w:t></w:r></w:p>"#,+ WS_SENTINEL_SPACE+ );+ assert_eq!(out, expected);+ }++ #[test]+ fn non_wordprocessingml_text_is_unchanged() {+ let xml = br#"<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:t> </a:t></a:theme>"#;+ let out = substitute_whitespace_only_runs(xml);+ assert_eq!(&out[..], &xml[..]);+ }++ #[test]+ fn malformed_xml_is_left_untouched() {+ let xml = br#"<w:root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:t> </w:t>"#;+ let out = substitute_whitespace_only_runs(xml);+ assert_eq!(&out[..], &xml[..]);+ }++ #[test]+ fn empty_buffer_is_handled() {+ let xml: &[u8] = b"";+ let out = substitute_whitespace_only_runs(xml);+ assert!(out.is_empty());+ }++ #[test]+ fn attribute_with_quoted_gt_is_handled() {+ // XML technically allows `>` in attribute values without escaping.+ // The scanner must respect quoting so the inner `>` doesn't end the+ // start tag prematurely.+ let xml = br#"<w:t weird="a>b" xml:space="preserve"> </w:t>"#;+ let out = substitute_wml_fragment(std::str::from_utf8(xml).unwrap());+ assert_eq!(+ out,+ format!(+ r#"<w:t weird="a>b" xml:space="preserve">{}</w:t>"#,+ WS_SENTINEL_SPACE+ )+ );+ }++ // ── restore_whitespace_sentinels ─────────────────────────────────────────++ #[test]+ fn restore_replaces_each_sentinel_with_original_byte() {+ let input = format!(+ "{}{}{}{}",+ WS_SENTINEL_SPACE, WS_SENTINEL_TAB, WS_SENTINEL_LF, WS_SENTINEL_CR+ );+ assert_eq!(restore_whitespace_sentinels(&input), " \t\n\r");+ }++ #[test]+ fn restore_passes_normal_text_through() {+ let input = "hello world";+ assert_eq!(restore_whitespace_sentinels(input), "hello world");+ }++ #[test]+ fn restore_handles_mixed_text_and_sentinels() {+ let input = format!("a{}b", WS_SENTINEL_SPACE);+ assert_eq!(restore_whitespace_sentinels(&input), "a b");+ }++ // ── round-trip: substitute then parse via quick-xml then restore ────────++ #[test]+ fn round_trip_through_quick_xml_recovers_original_whitespace() {+ use serde::Deserialize;++ #[derive(Deserialize)]+ struct TextXml {+ #[serde(rename = "$text", default)]+ content: String,+ }+ #[derive(Deserialize)]+ struct R {+ #[serde(rename = "t")]+ t: TextXml,+ }++ let original = br#"<r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:t xml:space="preserve"> </w:t></r>"#;+ let preprocessed = substitute_whitespace_only_runs(original);+ let parsed: R = quick_xml::de::from_str(std::str::from_utf8(&preprocessed).unwrap())+ .expect("quick-xml parse");+ let restored = restore_whitespace_sentinels(&parsed.t.content);+ assert_eq!(restored, " ", "expected single literal space to survive");+ }++ /// The "Label: Value" class this module exists to fix isn't only+ /// whitespace-*only* nodes — a mixed run with a significant *trailing*+ /// space (`<w:t xml:space="preserve">Label: </w:t>`) must also survive the+ /// full substitute → quick-xml → restore round-trip. This node is not+ /// all-whitespace, so `substitute_whitespace_only_runs` leaves it untouched;+ /// the test asserts quick-xml itself preserves the trailing space.+ #[test]+ fn round_trip_preserves_trailing_space_in_mixed_content() {+ use serde::Deserialize;++ #[derive(Deserialize)]+ struct TextXml {+ #[serde(rename = "$text", default)]+ content: String,+ }+ #[derive(Deserialize)]+ struct R {+ #[serde(rename = "t")]+ t: TextXml,+ }++ let original = br#"<r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:t xml:space="preserve">Label: </w:t></r>"#;+ let preprocessed = substitute_whitespace_only_runs(original);+ let parsed: R = quick_xml::de::from_str(std::str::from_utf8(&preprocessed).unwrap())+ .expect("quick-xml parse");+ let restored = restore_whitespace_sentinels(&parsed.t.content);+ assert_eq!(+ restored, "Label: ",+ "trailing space in mixed content must survive quick-xml"+ );+ }+}diff --git a/crates/liteparse-docx/src/docx/zip.rs b/crates/liteparse-docx/src/docx/zip.rsnew file mode 100644index 0000000..0a83524--- /dev/null+++ b/crates/liteparse-docx/src/docx/zip.rs@@ -0,0 +1,205 @@+//! ZIP extraction and OOXML package-path resolution.++use std::collections::HashMap;+use std::io::Read;++use crate::docx::error::{ParseError, Result};+use crate::docx::whitespace_workaround::substitute_whitespace_only_runs;++/// The contents of a DOCX package, extracted from the ZIP archive.+pub struct PackageContents {+ /// All files in the ZIP, keyed by normalized path (no leading slash).+ pub parts: HashMap<String, Vec<u8>>,+}++impl PackageContents {+ /// Extract all parts from a DOCX ZIP archive.+ pub fn from_bytes(data: &[u8]) -> Result<Self> {+ let cursor = std::io::Cursor::new(data);+ let mut archive = zip::ZipArchive::new(cursor)?;+ let mut parts = HashMap::with_capacity(archive.len());++ for i in 0..archive.len() {+ let mut file = archive.by_index(i)?;+ let name = normalize_path(file.name());+ let mut buf = Vec::with_capacity(file.size() as usize);+ file.read_to_end(&mut buf)?;+ // Apply the whitespace workaround only to XML parts. Binary parts+ // (images, fonts, embedded OLE) must not be touched.+ // See `whitespace_workaround` module docs for the rationale.+ if name.ends_with(".xml") || name.ends_with(".rels") {+ buf = substitute_whitespace_only_runs(&buf);+ }+ parts.insert(name, buf);+ }++ Ok(Self { parts })+ }++ /// Get the bytes for a part, case-insensitively.+ pub fn get_part(&self, path: &str) -> Option<&[u8]> {+ let normalized = normalize_path(path);+ self.parts.get(&normalized).map(|v| v.as_slice())+ }++ /// Get part bytes, or return MissingPart error.+ pub fn require_part(&self, path: &str) -> Result<&[u8]> {+ self.get_part(path)+ .ok_or_else(|| ParseError::MissingPart(path.to_string()))+ }++ /// Remove and return the owned bytes for a part. Avoids cloning.+ pub fn take_part(&mut self, path: &str) -> Option<Vec<u8>> {+ let normalized = normalize_path(path);+ self.parts.remove(&normalized)+ }+}++fn normalize_path(path: &str) -> String {+ path.trim_start_matches('/').to_lowercase()+}++/// Resolve a relationship target to an absolute path within the package.+/// base_dir is the directory containing the source part (e.g., "word" for "word/document.xml").+pub fn resolve_target(base_dir: &str, target: &str) -> String {+ if target.starts_with('/') {+ // Absolute path within the package+ normalize_path(target)+ } else {+ // Relative to base_dir+ let mut path = if base_dir.is_empty() {+ target.to_string()+ } else {+ format!("{}/{}", base_dir, target)+ };+ // Drop a leading "./" and collapse interior "/./" no-op segments so a+ // target like "./media/x.png" resolves the same as "media/x.png".+ if let Some(stripped) = path.strip_prefix("./") {+ path = stripped.to_string();+ }+ while let Some(pos) = path.find("/./") {+ path = format!("{}{}", &path[..pos], &path[pos + 2..]);+ }+ // Simplify "../" sequences+ while let Some(pos) = path.find("/../") {+ if let Some(parent_start) = path[..pos].rfind('/') {+ path = format!("{}{}", &path[..parent_start], &path[pos + 3..]);+ } else {+ path = path[pos + 4..].to_string();+ }+ }+ normalize_path(&path)+ }+}++/// Get the .rels path for a given part path.+/// e.g., "word/document.xml" → "word/_rels/document.xml.rels"+pub fn rels_path_for(part_path: &str) -> String {+ let normalized = normalize_path(part_path);+ if let Some(slash_pos) = normalized.rfind('/') {+ format!(+ "{}/_rels/{}.rels",+ &normalized[..slash_pos],+ &normalized[slash_pos + 1..]+ )+ } else {+ format!("_rels/{}.rels", normalized)+ }+}++/// Get the directory portion of a part path.+pub fn part_directory(part_path: &str) -> &str {+ match part_path.rfind('/') {+ Some(pos) => &part_path[..pos],+ None => "",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn normalize_strips_leading_slash_and_lowercases() {+ assert_eq!(normalize_path("/Word/Document.XML"), "word/document.xml");+ assert_eq!(+ normalize_path("word/media/Image1.PNG"),+ "word/media/image1.png"+ );+ }++ #[test]+ fn resolve_relative_target_joins_base_dir() {+ assert_eq!(+ resolve_target("word", "media/image1.png"),+ "word/media/image1.png"+ );+ }++ #[test]+ fn resolve_absolute_target_ignores_base_dir() {+ assert_eq!(+ resolve_target("word", "/word/media/image1.png"),+ "word/media/image1.png"+ );+ }++ #[test]+ fn resolve_empty_base_dir_uses_target_as_is() {+ assert_eq!(resolve_target("", "document.xml"), "document.xml");+ }++ #[test]+ fn resolve_collapses_parent_sequences() {+ // A theme rel from word/ pointing at word/theme/theme1.xml via "../".+ assert_eq!(+ resolve_target("word/theme", "../media/image1.png"),+ "word/media/image1.png"+ );+ // Multiple "../" segments.+ assert_eq!(resolve_target("a/b/c", "../../x.xml"), "a/x.xml");+ }++ #[test]+ fn resolve_parent_past_root_leaves_residual_dotdot() {+ // Traversing above the package root is malformed. One "../" is consumed+ // against "word"; the second has no parent left, so a residual "../"+ // remains — a path that matches no part, which is the safe outcome for+ // malformed input (the image is simply not found).+ assert_eq!(resolve_target("word", "../../x.xml"), "../x.xml");+ }++ #[test]+ fn resolve_collapses_current_dir_segments() {+ // Leading "./" and interior "/./" are no-ops and must normalize away,+ // otherwise the part lookup (an exact map key) would miss.+ assert_eq!(resolve_target("word", "./media/x.png"), "word/media/x.png");+ assert_eq!(resolve_target("", "./document.xml"), "document.xml");+ assert_eq!(resolve_target("word", "media/./x.png"), "word/media/x.png");+ }++ #[test]+ fn rels_path_for_builds_sibling_rels_file() {+ assert_eq!(+ rels_path_for("word/document.xml"),+ "word/_rels/document.xml.rels"+ );+ // A root-level part has no directory prefix.+ assert_eq!(+ rels_path_for("[Content_Types].xml"),+ "_rels/[content_types].xml.rels"+ );+ }++ #[test]+ fn part_directory_returns_dir_or_empty() {+ assert_eq!(part_directory("word/media/image1.png"), "word/media");+ assert_eq!(part_directory("document.xml"), "");+ }++ // KNOWN GAP: percent-encoded relationship targets (e.g. spaces as "%20")+ // are not decoded, so a target like "media/my%20image.png" resolves to a+ // key that won't match the ZIP part "media/my image.png". Word does not+ // percent-encode internal media names in practice, so this is left as a+ // documented limitation rather than pulling in a percent-decoder.+}diff --git a/crates/liteparse-docx/src/error.rs b/crates/liteparse-docx/src/error.rsnew file mode 100644index 0000000..a4a1f94--- /dev/null+++ b/crates/liteparse-docx/src/error.rs@@ -0,0 +1,13 @@+use thiserror::Error;++#[derive(Debug, Error)]+pub enum Error {+ #[error("IO error: {0}")]+ Io(#[from] std::io::Error),++ #[error("Parse error: {0}")]+ Parse(#[from] crate::docx::error::ParseError),++ #[error("Render error: {0}")]+ Render(#[from] crate::render::error::RenderError),+}diff --git a/crates/liteparse-docx/src/field/ast.rs b/crates/liteparse-docx/src/field/ast.rsnew file mode 100644index 0000000..fd66fe1--- /dev/null+++ b/crates/liteparse-docx/src/field/ast.rs@@ -0,0 +1,166 @@+/// A parsed OOXML field instruction (§17.16.5).+#[derive(Clone, Debug, PartialEq)]+pub enum FieldInstruction {+ /// PAGE — current page number (§17.16.5.52).+ Page { switches: CommonSwitches },+ /// NUMPAGES — total page count (§17.16.5.51).+ NumPages { switches: CommonSwitches },+ /// SECTION — current section number (§17.16.5.66).+ Section { switches: CommonSwitches },+ /// SECTIONPAGES — pages in current section (§17.16.5.67).+ SectionPages { switches: CommonSwitches },+ /// DATE — current date (§17.16.5.13).+ Date {+ format: Option<String>,+ switches: CommonSwitches,+ },+ /// TIME — current time (§17.16.5.76).+ Time {+ format: Option<String>,+ switches: CommonSwitches,+ },+ /// AUTHOR — document author (§17.16.5.4).+ Author {+ format: Option<String>,+ switches: CommonSwitches,+ },+ /// TITLE — document title (§17.16.5.77).+ Title { switches: CommonSwitches },+ /// SUBJECT — document subject (§17.16.5.72).+ Subject { switches: CommonSwitches },+ /// FILENAME — document file name (§17.16.5.18).+ FileName {+ /// `\p` — include full path.+ path: bool,+ switches: CommonSwitches,+ },+ /// REF — cross-reference to a bookmark (§17.16.5.60).+ Ref {+ bookmark: String,+ /// `\f` — footnote/endnote reference number.+ footnote_ref: bool,+ /// `\n` — paragraph number only.+ paragraph_number: bool,+ /// `\h` — create hyperlink.+ hyperlink: bool,+ switches: CommonSwitches,+ },+ /// PAGEREF — page number of a bookmark (§17.16.5.53).+ PageRef {+ bookmark: String,+ /// `\h` — create hyperlink.+ hyperlink: bool,+ switches: CommonSwitches,+ },+ /// NOTEREF — footnote/endnote reference number (§17.16.5.50).+ NoteRef {+ bookmark: String,+ /// `\f` — superscript formatting.+ superscript: bool,+ /// `\h` — create hyperlink.+ hyperlink: bool,+ switches: CommonSwitches,+ },+ /// HYPERLINK — clickable link (§17.16.5.25).+ Hyperlink {+ target: String,+ /// `\l` — bookmark/anchor within target.+ anchor: Option<String>,+ /// `\t` — target frame.+ target_frame: Option<String>,+ /// `\m` — image map coordinates.+ image_map: bool,+ switches: CommonSwitches,+ },+ /// TOC — table of contents (§17.16.5.75).+ Toc {+ /// `\o` — outline levels, e.g. "1-3".+ outline_levels: Option<String>,+ /// `\h` — make entries hyperlinks.+ hyperlinks: bool,+ /// `\n` — omit page numbers.+ no_page_numbers: bool,+ /// `\t` — custom style/level pairs.+ custom_styles: Option<String>,+ /// `\f` — TC field identifier.+ tc_identifier: Option<String>,+ switches: CommonSwitches,+ },+ /// SEQ — sequence/autonumber (§17.16.5.68).+ Seq {+ identifier: String,+ /// `\r` — reset to value.+ reset_to: Option<String>,+ /// `\c` — repeat closest preceding number.+ repeat: bool,+ /// `\n` — next sequence number (default).+ next: bool,+ switches: CommonSwitches,+ },+ /// IF — conditional (§17.16.5.26).+ If {+ left: String,+ operator: ComparisonOp,+ right: String,+ then_text: String,+ else_text: String,+ switches: CommonSwitches,+ },+ /// MERGEFIELD — mail merge field (§17.16.5.44).+ MergeField {+ name: String,+ /// `\b` — text before if non-blank.+ text_before: Option<String>,+ /// `\f` — text after if non-blank.+ text_after: Option<String>,+ switches: CommonSwitches,+ },+ /// DOCPROPERTY — document property value (§17.16.5.15).+ DocProperty {+ name: String,+ switches: CommonSwitches,+ },+ /// SYMBOL — insert a character by code (§17.16.5.73).+ Symbol {+ char_code: u32,+ /// `\f` — font name.+ font: Option<String>,+ switches: CommonSwitches,+ },+ /// INCLUDEPICTURE — embedded picture (§17.16.5.28).+ IncludePicture {+ path: String,+ /// `\d` — don't store data with document.+ no_store: bool,+ switches: CommonSwitches,+ },+ /// EQ — equation (§17.16.5.16).+ Eq {+ equation: String,+ switches: CommonSwitches,+ },+ /// An unrecognized but syntactically valid field type.+ Unknown { field_type: String, raw: String },+}++/// Common formatting switches shared by most field types (§17.16.4.1).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct CommonSwitches {+ /// `\*` — general formatting switch (e.g., `\* MERGEFORMAT`, `\* Upper`).+ pub format: Option<String>,+ /// `\#` — numeric formatting switch (e.g., `\# "0.00"`).+ pub numeric_format: Option<String>,+ /// `\@` — date/time formatting switch (e.g., `\@ "dd/MM/yyyy"`).+ pub date_format: Option<String>,+}++/// Comparison operators for IF fields.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ComparisonOp {+ Equal,+ NotEqual,+ LessThan,+ LessEqual,+ GreaterThan,+ GreaterEqual,+}diff --git a/crates/liteparse-docx/src/field/context.rs b/crates/liteparse-docx/src/field/context.rsnew file mode 100644index 0000000..a730116--- /dev/null+++ b/crates/liteparse-docx/src/field/context.rs@@ -0,0 +1,63 @@+use std::collections::HashMap;++/// Runtime context for evaluating field instructions.+///+/// Consumers provide whichever fields they have available — layout provides+/// page numbers, mail merge provides data fields, etc. Missing context+/// causes the evaluator to return `FieldValue::Unevaluable`.+#[derive(Clone, Debug, Default)]+pub struct FieldContext {+ /// Current page number (1-based).+ pub page_number: Option<u32>,+ /// Total number of pages in the document.+ pub total_pages: Option<u32>,+ /// Current section number (1-based).+ pub section_number: Option<u32>,+ /// Total pages in the current section.+ pub section_pages: Option<u32>,+ /// Current date for DATE fields.+ pub date: Option<Date>,+ /// Current time for TIME fields.+ pub time: Option<Time>,+ /// Document properties (author, title, subject, etc.).+ pub document_properties: HashMap<String, String>,+ /// Bookmark locations for REF/PAGEREF/NOTEREF.+ pub bookmarks: HashMap<String, BookmarkLocation>,+ /// Mail merge data for MERGEFIELD.+ pub merge_data: Option<HashMap<String, String>>,+ /// Sequence counters for SEQ fields.+ pub sequences: HashMap<String, u32>,+ /// File name for FILENAME field.+ pub file_name: Option<String>,+ /// Full file path for FILENAME \p.+ pub file_path: Option<String>,+}++/// A simple date representation (no external dependency required).+#[derive(Clone, Copy, Debug)]+pub struct Date {+ pub year: i32,+ pub month: u32,+ pub day: u32,+}++/// A simple time representation.+#[derive(Clone, Copy, Debug)]+pub struct Time {+ pub hour: u32,+ pub minute: u32,+ pub second: u32,+}++/// Location information for a bookmark.+#[derive(Clone, Debug)]+pub struct BookmarkLocation {+ /// The page number (1-based) where the bookmark appears.+ pub page: Option<u32>,+ /// The text content at the bookmark.+ pub text: Option<String>,+ /// Paragraph number, if applicable.+ pub paragraph_number: Option<String>,+ /// Footnote/endnote reference number, if the bookmark is in a note.+ pub note_ref: Option<String>,+}diff --git a/crates/liteparse-docx/src/field/error.rs b/crates/liteparse-docx/src/field/error.rsnew file mode 100644index 0000000..cc2ed73--- /dev/null+++ b/crates/liteparse-docx/src/field/error.rs@@ -0,0 +1,93 @@+use std::fmt;++/// Errors that can occur when parsing a field instruction string.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum FieldParseError {+ /// The instruction string is empty or contains only whitespace.+ Empty,+ /// A quoted string was not terminated.+ UnterminatedString { position: usize },+ /// A switch character (`\x`) was found but the letter is missing or invalid.+ InvalidSwitch { position: usize, found: String },+ /// A required argument is missing (e.g., REF without a bookmark name).+ MissingArgument {+ field_type: String,+ argument: String,+ },+ /// A numeric value could not be parsed (e.g., SYMBOL with non-numeric code).+ InvalidNumber { value: String, reason: String },+ /// An IF field has an invalid or missing comparison operator.+ InvalidOperator { found: String },+ /// A switch value was expected but not found.+ MissingSwitchValue { switch: String },+}++impl fmt::Display for FieldParseError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Empty => write!(f, "empty field instruction"),+ Self::UnterminatedString { position } => {+ write!(f, "unterminated string at position {position}")+ }+ Self::InvalidSwitch { position, found } => {+ write!(f, "invalid switch '{found}' at position {position}")+ }+ Self::MissingArgument {+ field_type,+ argument,+ } => {+ write!(+ f,+ "{field_type} field missing required argument: {argument}"+ )+ }+ Self::InvalidNumber { value, reason } => {+ write!(f, "invalid number '{value}': {reason}")+ }+ Self::InvalidOperator { found } => {+ write!(f, "invalid comparison operator: '{found}'")+ }+ Self::MissingSwitchValue { switch } => {+ write!(f, "switch '{switch}' requires a value")+ }+ }+ }+}++impl std::error::Error for FieldParseError {}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn display_includes_the_salient_detail() {+ assert_eq!(+ FieldParseError::Empty.to_string(),+ "empty field instruction"+ );+ assert_eq!(+ FieldParseError::MissingSwitchValue {+ switch: "\\o".into()+ }+ .to_string(),+ "switch '\\o' requires a value"+ );+ assert_eq!(+ FieldParseError::MissingArgument {+ field_type: "REF".into(),+ argument: "bookmark".into(),+ }+ .to_string(),+ "REF field missing required argument: bookmark"+ );+ assert_eq!(+ FieldParseError::UnterminatedString { position: 7 }.to_string(),+ "unterminated string at position 7"+ );+ assert_eq!(+ FieldParseError::InvalidOperator { found: "=?".into() }.to_string(),+ "invalid comparison operator: '=?'"+ );+ }+}diff --git a/crates/liteparse-docx/src/field/eval.rs b/crates/liteparse-docx/src/field/eval.rsnew file mode 100644index 0000000..4599ba3--- /dev/null+++ b/crates/liteparse-docx/src/field/eval.rs@@ -0,0 +1,581 @@+use crate::field::ast::{ComparisonOp, FieldInstruction};+use crate::field::context::FieldContext;+use crate::field::format;++/// The result of evaluating a field instruction.+#[derive(Clone, Debug, PartialEq)]+pub enum FieldValue {+ /// A text string result.+ Text(String),+ /// A numeric result.+ Number(f64),+ /// Field cannot be evaluated with the current context.+ Unevaluable,+}++/// Evaluate a parsed field instruction against a context.+pub fn evaluate(instr: &FieldInstruction, ctx: &FieldContext) -> FieldValue {+ match instr {+ FieldInstruction::Page { switches } => match ctx.page_number {+ Some(n) => format_result(n.to_string(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::NumPages { switches } => match ctx.total_pages {+ Some(n) => format_result(n.to_string(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::Section { switches } => match ctx.section_number {+ Some(n) => format_result(n.to_string(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::SectionPages { switches } => match ctx.section_pages {+ Some(n) => format_result(n.to_string(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::Date {+ format: _,+ switches,+ } => {+ match &ctx.date {+ Some(date) => {+ let formatted = if let Some(pattern) = &switches.date_format {+ format::format_date(date, pattern)+ } else {+ // Default: M/d/yyyy+ format::format_date(date, "M/d/yyyy")+ };+ format_result(formatted, switches)+ }+ None => FieldValue::Unevaluable,+ }+ }++ FieldInstruction::Time {+ format: _,+ switches,+ } => match &ctx.time {+ Some(time) => {+ let formatted = if let Some(pattern) = &switches.date_format {+ format::format_time(time, pattern)+ } else {+ format::format_time(time, "h:mm AM/PM")+ };+ format_result(formatted, switches)+ }+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::Author {+ format: _,+ switches,+ } => match ctx.document_properties.get("author") {+ Some(author) => format_result(author.clone(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::Title { switches } => match ctx.document_properties.get("title") {+ Some(title) => format_result(title.clone(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::Subject { switches } => match ctx.document_properties.get("subject") {+ Some(subject) => format_result(subject.clone(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::FileName { path, switches } => {+ let value = if *path {+ ctx.file_path.as_ref()+ } else {+ ctx.file_name.as_ref()+ };+ match value {+ Some(name) => format_result(name.clone(), switches),+ None => FieldValue::Unevaluable,+ }+ }++ FieldInstruction::Ref {+ bookmark,+ footnote_ref,+ paragraph_number,+ hyperlink: _,+ switches,+ } => match ctx.bookmarks.get(bookmark) {+ Some(loc) => {+ let text = if *footnote_ref {+ loc.note_ref.as_deref().unwrap_or("").to_string()+ } else if *paragraph_number {+ loc.paragraph_number.as_deref().unwrap_or("").to_string()+ } else {+ loc.text.as_deref().unwrap_or("").to_string()+ };+ format_result(text, switches)+ }+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::PageRef {+ bookmark,+ hyperlink: _,+ switches,+ } => match ctx.bookmarks.get(bookmark) {+ Some(loc) => match loc.page {+ Some(page) => format_result(page.to_string(), switches),+ None => FieldValue::Unevaluable,+ },+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::NoteRef {+ bookmark,+ superscript: _,+ hyperlink: _,+ switches,+ } => match ctx.bookmarks.get(bookmark) {+ Some(loc) => match &loc.note_ref {+ Some(nr) => format_result(nr.clone(), switches),+ None => FieldValue::Unevaluable,+ },+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::Hyperlink { target, .. } => {+ // Hyperlinks produce their target as text — the display text+ // is typically in the field result, not the instruction.+ FieldValue::Text(target.clone())+ }++ FieldInstruction::Toc { .. } => {+ // TOC requires full document analysis — unevaluable at field level.+ FieldValue::Unevaluable+ }++ FieldInstruction::Seq {+ identifier,+ reset_to,+ repeat,+ next: _,+ switches,+ } => {+ // SEQ evaluation is stateful. We use the snapshot from context.+ if let Some(reset) = reset_to {+ if let Ok(n) = reset.parse::<u32>() {+ return format_result(n.to_string(), switches);+ }+ }+ if *repeat {+ let n = ctx.sequences.get(identifier.as_str()).copied().unwrap_or(0);+ return format_result(n.to_string(), switches);+ }+ // Default: next value (current + 1)+ let n = ctx.sequences.get(identifier.as_str()).copied().unwrap_or(0) + 1;+ format_result(n.to_string(), switches)+ }++ FieldInstruction::If {+ left,+ operator,+ right,+ then_text,+ else_text,+ switches,+ } => {+ let result = if evaluate_comparison(left, *operator, right) {+ then_text.clone()+ } else {+ else_text.clone()+ };+ format_result(result, switches)+ }++ FieldInstruction::MergeField {+ name,+ text_before,+ text_after,+ switches,+ } => match ctx.merge_data.as_ref().and_then(|d| d.get(name.as_str())) {+ Some(value) if !value.is_empty() => {+ let mut result = String::new();+ if let Some(before) = text_before {+ result.push_str(before);+ }+ result.push_str(value);+ if let Some(after) = text_after {+ result.push_str(after);+ }+ format_result(result, switches)+ }+ _ => FieldValue::Unevaluable,+ },++ FieldInstruction::DocProperty { name, switches } => {+ // Try case-insensitive lookup+ let key = name.to_ascii_lowercase();+ let value = ctx+ .document_properties+ .iter()+ .find(|(k, _)| k.to_ascii_lowercase() == key)+ .map(|(_, v)| v.clone());+ match value {+ Some(v) => format_result(v, switches),+ None => FieldValue::Unevaluable,+ }+ }++ FieldInstruction::Symbol {+ char_code,+ font: _,+ switches,+ } => match char::from_u32(*char_code) {+ Some(ch) => format_result(ch.to_string(), switches),+ None => FieldValue::Unevaluable,+ },++ FieldInstruction::IncludePicture { .. } => {+ // Picture inclusion requires image loading — unevaluable at field level.+ FieldValue::Unevaluable+ }++ FieldInstruction::Eq { equation, switches } => format_result(equation.clone(), switches),++ FieldInstruction::Unknown { .. } => FieldValue::Unevaluable,+ }+}++/// Apply formatting switches to a text result.+fn format_result(value: String, switches: &crate::field::ast::CommonSwitches) -> FieldValue {+ let mut text = value;++ // Apply numeric format+ if let Some(ref num_fmt) = switches.numeric_format {+ if let Ok(n) = text.parse::<f64>() {+ text = format::format_number(n, num_fmt);+ }+ }++ // Apply general format+ if let Some(ref fmt) = switches.format {+ text = format::apply_general_format(&text, fmt);+ }++ FieldValue::Text(text)+}++/// Evaluate a comparison for IF fields.+fn evaluate_comparison(left: &str, op: ComparisonOp, right: &str) -> bool {+ // Try numeric comparison first+ if let (Ok(l), Ok(r)) = (left.parse::<f64>(), right.parse::<f64>()) {+ return match op {+ ComparisonOp::Equal => (l - r).abs() < f64::EPSILON,+ ComparisonOp::NotEqual => (l - r).abs() >= f64::EPSILON,+ ComparisonOp::LessThan => l < r,+ ComparisonOp::LessEqual => l <= r,+ ComparisonOp::GreaterThan => l > r,+ ComparisonOp::GreaterEqual => l >= r,+ };+ }++ // Fall back to string comparison (case-insensitive per OOXML spec)+ let l = left.to_ascii_lowercase();+ let r = right.to_ascii_lowercase();+ match op {+ ComparisonOp::Equal => l == r,+ ComparisonOp::NotEqual => l != r,+ ComparisonOp::LessThan => l < r,+ ComparisonOp::LessEqual => l <= r,+ ComparisonOp::GreaterThan => l > r,+ ComparisonOp::GreaterEqual => l >= r,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::field::ast::CommonSwitches;+ use crate::field::context::{BookmarkLocation, Date, Time};+ use std::collections::HashMap;++ fn sw() -> CommonSwitches {+ CommonSwitches::default()+ }++ fn ctx_with<F: FnOnce(&mut FieldContext)>(f: F) -> FieldContext {+ let mut ctx = FieldContext::default();+ f(&mut ctx);+ ctx+ }++ #[test]+ fn eval_page() {+ let ctx = ctx_with(|c| c.page_number = Some(7));+ let instr = FieldInstruction::Page { switches: sw() };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("7".into()));+ }++ #[test]+ fn eval_page_missing() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::Page { switches: sw() };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Unevaluable);+ }++ #[test]+ fn eval_numpages() {+ let ctx = ctx_with(|c| c.total_pages = Some(42));+ let instr = FieldInstruction::NumPages { switches: sw() };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("42".into()));+ }++ #[test]+ fn eval_date_default_format() {+ let ctx = ctx_with(|c| {+ c.date = Some(Date {+ year: 2026,+ month: 3,+ day: 24,+ })+ });+ let instr = FieldInstruction::Date {+ format: None,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("3/24/2026".into()));+ }++ #[test]+ fn eval_date_custom_format() {+ let ctx = ctx_with(|c| {+ c.date = Some(Date {+ year: 2026,+ month: 12,+ day: 5,+ })+ });+ let instr = FieldInstruction::Date {+ format: None,+ switches: CommonSwitches {+ date_format: Some("dd/MM/yyyy".into()),+ ..Default::default()+ },+ };+ assert_eq!(+ evaluate(&instr, &ctx),+ FieldValue::Text("05/12/2026".into())+ );+ }++ #[test]+ fn eval_time() {+ let ctx = ctx_with(|c| {+ c.time = Some(Time {+ hour: 14,+ minute: 30,+ second: 0,+ })+ });+ let instr = FieldInstruction::Time {+ format: None,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("2:30 PM".into()));+ }++ #[test]+ fn eval_author() {+ let ctx = ctx_with(|c| {+ c.document_properties+ .insert("author".into(), "Jane Doe".into());+ });+ let instr = FieldInstruction::Author {+ format: None,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("Jane Doe".into()));+ }++ #[test]+ fn eval_mergefield() {+ let ctx = ctx_with(|c| {+ c.merge_data = Some(HashMap::from([("FirstName".into(), "Alice".into())]));+ });+ let instr = FieldInstruction::MergeField {+ name: "FirstName".into(),+ text_before: Some("Dear ".into()),+ text_after: Some(",".into()),+ switches: sw(),+ };+ assert_eq!(+ evaluate(&instr, &ctx),+ FieldValue::Text("Dear Alice,".into())+ );+ }++ #[test]+ fn eval_mergefield_missing() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::MergeField {+ name: "FirstName".into(),+ text_before: None,+ text_after: None,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Unevaluable);+ }++ #[test]+ fn eval_if_equal() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::If {+ left: "hello".into(),+ operator: ComparisonOp::Equal,+ right: "hello".into(),+ then_text: "yes".into(),+ else_text: "no".into(),+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("yes".into()));+ }++ #[test]+ fn eval_if_numeric() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::If {+ left: "10".into(),+ operator: ComparisonOp::GreaterThan,+ right: "5".into(),+ then_text: "big".into(),+ else_text: "small".into(),+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("big".into()));+ }++ #[test]+ fn eval_pageref() {+ let ctx = ctx_with(|c| {+ c.bookmarks.insert(+ "_Ref123".into(),+ BookmarkLocation {+ page: Some(5),+ text: None,+ paragraph_number: None,+ note_ref: None,+ },+ );+ });+ let instr = FieldInstruction::PageRef {+ bookmark: "_Ref123".into(),+ hyperlink: false,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("5".into()));+ }++ #[test]+ fn eval_symbol() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::Symbol {+ char_code: 169,+ font: None,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("\u{a9}".into()));+ }++ #[test]+ fn eval_with_numeric_format() {+ let ctx = ctx_with(|c| c.page_number = Some(7));+ let instr = FieldInstruction::Page {+ switches: CommonSwitches {+ numeric_format: Some("0.00".into()),+ ..Default::default()+ },+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("7.00".into()));+ }++ #[test]+ fn eval_with_upper_format() {+ let ctx = ctx_with(|c| {+ c.document_properties+ .insert("author".into(), "jane doe".into());+ });+ let instr = FieldInstruction::Author {+ format: None,+ switches: CommonSwitches {+ format: Some("Upper".into()),+ ..Default::default()+ },+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("JANE DOE".into()));+ }++ #[test]+ fn eval_seq_next() {+ let ctx = ctx_with(|c| {+ c.sequences.insert("Figure".into(), 3);+ });+ let instr = FieldInstruction::Seq {+ identifier: "Figure".into(),+ reset_to: None,+ repeat: false,+ next: true,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("4".into()));+ }++ #[test]+ fn eval_seq_reset() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::Seq {+ identifier: "Table".into(),+ reset_to: Some("1".into()),+ repeat: false,+ next: false,+ switches: sw(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Text("1".into()));+ }++ #[test]+ fn eval_filename() {+ let ctx = ctx_with(|c| {+ c.file_name = Some("document.docx".into());+ c.file_path = Some("/home/user/document.docx".into());+ });++ let instr_name = FieldInstruction::FileName {+ path: false,+ switches: sw(),+ };+ assert_eq!(+ evaluate(&instr_name, &ctx),+ FieldValue::Text("document.docx".into())+ );++ let instr_path = FieldInstruction::FileName {+ path: true,+ switches: sw(),+ };+ assert_eq!(+ evaluate(&instr_path, &ctx),+ FieldValue::Text("/home/user/document.docx".into())+ );+ }++ #[test]+ fn eval_unknown() {+ let ctx = FieldContext::default();+ let instr = FieldInstruction::Unknown {+ field_type: "FOOBAR".into(),+ raw: " FOOBAR ".into(),+ };+ assert_eq!(evaluate(&instr, &ctx), FieldValue::Unevaluable);+ }+}diff --git a/crates/liteparse-docx/src/field/format.rs b/crates/liteparse-docx/src/field/format.rsnew file mode 100644index 0000000..893a296--- /dev/null+++ b/crates/liteparse-docx/src/field/format.rs@@ -0,0 +1,480 @@+use crate::field::context::{Date, Time};++/// Format a date using an OOXML date/time format string (§17.16.4.1).+///+/// Supports common patterns:+/// - `d`, `dd` — day of month (1 vs 01)+/// - `M`, `MM`, `MMM`, `MMMM` — month (3, 03, Mar, March)+/// - `yy`, `yyyy` — year (26, 2026)+/// - `H`, `HH` — 24-hour (7, 07)+/// - `h`, `hh` — 12-hour (7, 07)+/// - `m`, `mm` — minute (5, 05)+/// - `s`, `ss` — second (3, 03)+/// - `AM/PM`, `am/pm`+///+/// Literal text can be included in single quotes: `'at' h:mm`.+pub fn format_date(date: &Date, pattern: &str) -> String {+ let mut result = String::new();+ let chars: Vec<char> = pattern.chars().collect();+ let len = chars.len();+ let mut i = 0;++ while i < len {+ // Literal text in single quotes+ if chars[i] == '\'' {+ i += 1;+ while i < len && chars[i] != '\'' {+ result.push(chars[i]);+ i += 1;+ }+ if i < len {+ i += 1; // skip closing quote+ }+ continue;+ }++ // Year+ if chars[i] == 'y' {+ let count = count_run(&chars, i, 'y');+ if count >= 4 {+ result.push_str(&format!("{:04}", date.year));+ } else {+ result.push_str(&format!("{:02}", date.year % 100));+ }+ i += count;+ continue;+ }++ // Month (uppercase M to distinguish from minute)+ if chars[i] == 'M' {+ let count = count_run(&chars, i, 'M');+ match count {+ 1 => result.push_str(&date.month.to_string()),+ 2 => result.push_str(&format!("{:02}", date.month)),+ 3 => result.push_str(short_month_name(date.month)),+ _ => result.push_str(long_month_name(date.month)),+ }+ i += count;+ continue;+ }++ // Day+ if chars[i] == 'd' {+ let count = count_run(&chars, i, 'd');+ if count >= 2 {+ result.push_str(&format!("{:02}", date.day));+ } else {+ result.push_str(&date.day.to_string());+ }+ i += count;+ continue;+ }++ // Passthrough for other characters (separators like /, -, space)+ result.push(chars[i]);+ i += 1;+ }++ result+}++/// Format a time using an OOXML date/time format string.+pub fn format_time(time: &Time, pattern: &str) -> String {+ let has_ampm = pattern.contains("AM/PM") || pattern.contains("am/pm");++ let (display_hour, ampm) = if has_ampm {+ let (h, period) = to_12hour(time.hour);+ (h, Some(period))+ } else {+ (time.hour, None)+ };++ let mut result = String::new();+ let chars: Vec<char> = pattern.chars().collect();+ let len = chars.len();+ let mut i = 0;++ while i < len {+ if chars[i] == '\'' {+ i += 1;+ while i < len && chars[i] != '\'' {+ result.push(chars[i]);+ i += 1;+ }+ if i < len {+ i += 1;+ }+ continue;+ }++ // AM/PM — compare on the char slice, not byte offsets: `i` is a char+ // index, so `pattern[i..i+5]` would misalign (and can panic) after any+ // multi-byte character earlier in the pattern.+ if chars[i..].starts_with(&['A', 'M', '/', 'P', 'M']) {+ result.push_str(ampm.unwrap_or("AM"));+ i += 5;+ continue;+ }+ if chars[i..].starts_with(&['a', 'm', '/', 'p', 'm']) {+ result.push_str(&m.unwrap_or("am").to_ascii_lowercase());+ i += 5;+ continue;+ }++ // 24-hour (H)+ if chars[i] == 'H' {+ let count = count_run(&chars, i, 'H');+ if count >= 2 {+ result.push_str(&format!("{:02}", time.hour));+ } else {+ result.push_str(&time.hour.to_string());+ }+ i += count;+ continue;+ }++ // 12-hour (h)+ if chars[i] == 'h' {+ let count = count_run(&chars, i, 'h');+ if count >= 2 {+ result.push_str(&format!("{:02}", display_hour));+ } else {+ result.push_str(&display_hour.to_string());+ }+ i += count;+ continue;+ }++ // Minute+ if chars[i] == 'm' {+ let count = count_run(&chars, i, 'm');+ if count >= 2 {+ result.push_str(&format!("{:02}", time.minute));+ } else {+ result.push_str(&time.minute.to_string());+ }+ i += count;+ continue;+ }++ // Second+ if chars[i] == 's' {+ let count = count_run(&chars, i, 's');+ if count >= 2 {+ result.push_str(&format!("{:02}", time.second));+ } else {+ result.push_str(&time.second.to_string());+ }+ i += count;+ continue;+ }++ result.push(chars[i]);+ i += 1;+ }++ result+}++/// Format a number using an OOXML numeric format string (§17.16.4.1).+///+/// Basic support: `0` = digit (pad with zero), `#` = digit (no pad).+pub fn format_number(value: f64, pattern: &str) -> String {+ // Find decimal point in pattern+ let parts: Vec<&str> = pattern.split('.').collect();++ if parts.len() == 2 {+ let decimal_places = parts[1].len();+ format!("{:.prec$}", value, prec = decimal_places)+ } else if pattern.contains('0') || pattern.contains('#') {+ // Integer format: round (like the decimal branch's `{:.prec$}`) rather+ // than truncate toward zero. `.round()` first also avoids a "-0" result+ // from `-0.4 as i64`.+ format!("{}", value.round() as i64)+ } else {+ value.to_string()+ }+}++/// Apply a general format switch (`\* FORMAT`) to a string value.+///+/// For `ROMAN`/`ALPHABETIC` the *case of the switch keyword* selects the output+/// case (`\* roman` → `iv`, `\* ROMAN` → `IV`), per §17.16.4.1.+pub fn apply_general_format(value: &str, format: &str) -> String {+ // Lowercase output when the keyword itself is written lowercase.+ let lowercase = format+ .chars()+ .find(|c| c.is_ascii_alphabetic())+ .is_some_and(|c| c.is_ascii_lowercase());+ match format.to_ascii_uppercase().as_str() {+ "UPPER" => value.to_ascii_uppercase(),+ "LOWER" => value.to_ascii_lowercase(),+ // §17.16.4.1: FirstCap capitalizes the first letter of the *first* word;+ // Caps capitalizes the first letter of *every* word (title case).+ "FIRSTCAP" => first_cap(value),+ "CAPS" => title_case(value),+ "MERGEFORMAT" => value.to_string(), // preserve existing formatting, no-op for text+ "ALPHABETIC" => match value.parse::<u32>() {+ Ok(n) => to_alphabetic(n, lowercase),+ Err(_) => value.to_string(),+ },+ "ROMAN" => match value.parse::<u32>() {+ Ok(n) => to_roman(n, lowercase),+ Err(_) => value.to_string(),+ },+ _ => value.to_string(),+ }+}++/// Capitalize the first letter of the first word only (`\* FirstCap`).+fn first_cap(value: &str) -> String {+ let mut chars = value.chars();+ match chars.next() {+ None => String::new(),+ Some(c) => {+ let mut s = c.to_uppercase().to_string();+ s.extend(chars);+ s+ }+ }+}++/// Capitalize the first letter of every word (`\* Caps` — title case). A word is+/// a maximal run of alphabetic characters; the rest of each word is left as-is.+fn title_case(value: &str) -> String {+ let mut out = String::with_capacity(value.len());+ let mut at_word_start = true;+ for c in value.chars() {+ if c.is_alphabetic() {+ if at_word_start {+ out.extend(c.to_uppercase());+ } else {+ out.push(c);+ }+ at_word_start = false;+ } else {+ out.push(c);+ at_word_start = true;+ }+ }+ out+}++fn count_run(chars: &[char], start: usize, ch: char) -> usize {+ chars[start..].iter().take_while(|&&c| c == ch).count()+}++fn to_12hour(hour: u32) -> (u32, &'static str) {+ match hour {+ 0 => (12, "AM"),+ 1..=11 => (hour, "AM"),+ 12 => (12, "PM"),+ _ => (hour - 12, "PM"),+ }+}++fn short_month_name(month: u32) -> &'static str {+ match month {+ 1 => "Jan",+ 2 => "Feb",+ 3 => "Mar",+ 4 => "Apr",+ 5 => "May",+ 6 => "Jun",+ 7 => "Jul",+ 8 => "Aug",+ 9 => "Sep",+ 10 => "Oct",+ 11 => "Nov",+ 12 => "Dec",+ _ => "???",+ }+}++fn long_month_name(month: u32) -> &'static str {+ match month {+ 1 => "January",+ 2 => "February",+ 3 => "March",+ 4 => "April",+ 5 => "May",+ 6 => "June",+ 7 => "July",+ 8 => "August",+ 9 => "September",+ 10 => "October",+ 11 => "November",+ 12 => "December",+ _ => "???",+ }+}++fn to_roman(mut n: u32, lowercase: bool) -> String {+ const TABLE: &[(u32, &str)] = &[+ (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 result = String::new();+ for &(value, numeral) in TABLE {+ while n >= value {+ result.push_str(numeral);+ n -= value;+ }+ }+ if lowercase {+ result.to_ascii_lowercase()+ } else {+ result+ }+}++fn to_alphabetic(n: u32, lowercase: bool) -> String {+ if n == 0 {+ return String::new();+ }+ let base = if lowercase { b'a' } else { b'A' };+ let mut result = Vec::new();+ let mut val = n - 1;+ loop {+ result.push(base + (val % 26) as u8);+ if val < 26 {+ break;+ }+ val = val / 26 - 1;+ }+ result.reverse();+ String::from_utf8(result).unwrap_or_default()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn format_date_basic() {+ let date = Date {+ year: 2026,+ month: 3,+ day: 5,+ };+ assert_eq!(format_date(&date, "dd/MM/yyyy"), "05/03/2026");+ assert_eq!(format_date(&date, "d/M/yy"), "5/3/26");+ assert_eq!(format_date(&date, "MMMM d, yyyy"), "March 5, 2026");+ }++ #[test]+ fn format_time_24h() {+ let time = Time {+ hour: 14,+ minute: 5,+ second: 9,+ };+ assert_eq!(format_time(&time, "HH:mm:ss"), "14:05:09");+ assert_eq!(format_time(&time, "H:m"), "14:5");+ }++ #[test]+ fn format_time_12h() {+ let time = Time {+ hour: 14,+ minute: 30,+ second: 0,+ };+ assert_eq!(format_time(&time, "h:mm AM/PM"), "2:30 PM");+ }++ #[test]+ fn format_number_decimal() {+ assert_eq!(format_number(1.2345, "0.00"), "1.23");+ assert_eq!(format_number(42.0, "0.000"), "42.000");+ }++ #[test]+ fn general_format_upper() {+ assert_eq!(apply_general_format("hello", "Upper"), "HELLO");+ assert_eq!(apply_general_format("hello", "Lower"), "hello");+ assert_eq!(+ apply_general_format("hello world", "FirstCap"),+ "Hello world"+ );+ }++ #[test]+ fn roman_numerals() {+ assert_eq!(to_roman(1, false), "I");+ assert_eq!(to_roman(4, false), "IV");+ assert_eq!(to_roman(14, false), "XIV");+ assert_eq!(to_roman(2026, false), "MMXXVI");+ }++ #[test]+ fn alphabetic_numbering() {+ assert_eq!(to_alphabetic(1, false), "A");+ assert_eq!(to_alphabetic(26, false), "Z");+ assert_eq!(to_alphabetic(27, false), "AA");+ }++ #[test]+ fn general_format_roman_case_follows_switch() {+ // §17.16.4.1: `\* roman` → lowercase, `\* ROMAN` → uppercase.+ assert_eq!(apply_general_format("4", "roman"), "iv");+ assert_eq!(apply_general_format("4", "ROMAN"), "IV");+ assert_eq!(apply_general_format("4", "Roman"), "IV");+ // Non-numeric input is passed through unchanged.+ assert_eq!(apply_general_format("abc", "roman"), "abc");+ }++ #[test]+ fn general_format_alphabetic_case_follows_switch() {+ assert_eq!(apply_general_format("1", "alphabetic"), "a");+ assert_eq!(apply_general_format("1", "ALPHABETIC"), "A");+ assert_eq!(apply_general_format("28", "alphabetic"), "ab");+ }++ #[test]+ fn general_format_caps_is_title_case_firstcap_is_not() {+ // Caps capitalizes every word; FirstCap only the first.+ assert_eq!(apply_general_format("hello world", "Caps"), "Hello World");+ assert_eq!(+ apply_general_format("hello world", "FirstCap"),+ "Hello world"+ );+ // Existing capitals inside a word are left alone.+ assert_eq!(+ apply_general_format("the fbi report", "Caps"),+ "The Fbi Report"+ );+ }++ #[test]+ fn number_integer_format_rounds_not_truncates() {+ assert_eq!(format_number(2.7, "0"), "3");+ assert_eq!(format_number(2.4, "0"), "2");+ assert_eq!(format_number(-2.7, "0"), "-3");+ // `.round()` first avoids a "-0" result.+ assert_eq!(format_number(-0.4, "0"), "0");+ }++ #[test]+ fn time_ampm_after_multibyte_literal_does_not_panic() {+ let time = Time {+ hour: 14,+ minute: 30,+ second: 0,+ };+ // A multi-byte char in a literal shifts byte vs char offsets; the AM/PM+ // match must still align (previously this byte-sliced and could panic).+ assert_eq!(format_time(&time, "'é' h AM/PM"), "é 2 PM");+ }+}diff --git a/crates/liteparse-docx/src/field/mod.rs b/crates/liteparse-docx/src/field/mod.rsnew file mode 100644index 0000000..c26264d--- /dev/null+++ b/crates/liteparse-docx/src/field/mod.rs@@ -0,0 +1,43 @@+//! OOXML field instruction parser and evaluator.+//!+//! Parses raw field instruction strings (from `w:instrText` or `w:fldSimple/@instr`)+//! into a typed AST, and evaluates them given a document context.+//!+//! # Examples+//!+//! ```+//! use liteparse_docx::field::{parse, evaluate, FieldContext};+//!+//! // Parse a PAGE field+//! let instr = parse(" PAGE ").unwrap();+//!+//! // Evaluate with context+//! let mut ctx = FieldContext::default();+//! ctx.page_number = Some(7);+//! let result = evaluate(&instr, &ctx);+//! ```++pub mod ast;+pub mod context;+pub mod error;+pub mod eval;+pub mod format;+pub(crate) mod parse;+pub(crate) mod switches;++pub use ast::{CommonSwitches, ComparisonOp, FieldInstruction};+pub use context::FieldContext;+pub use error::FieldParseError;+pub use eval::{FieldValue, evaluate};++/// Parse a field instruction string into a typed `FieldInstruction`.+///+/// The input is the raw instruction text as found in `w:instrText` elements+/// or the `instr` attribute of `w:fldSimple`, e.g. `" PAGE "`, `" TOC \o \"1-3\" \h "`.+///+/// Returns `Err(FieldParseError)` for malformed syntax (unterminated strings,+/// missing required arguments, invalid values). Unknown but syntactically valid+/// field types parse into `FieldInstruction::Unknown`.+pub fn parse(input: &str) -> Result<FieldInstruction, FieldParseError> {+ parse::parse(input)+}diff --git a/crates/liteparse-docx/src/field/parse.rs b/crates/liteparse-docx/src/field/parse.rsnew file mode 100644index 0000000..11e615c--- /dev/null+++ b/crates/liteparse-docx/src/field/parse.rs@@ -0,0 +1,694 @@+use crate::field::ast::{CommonSwitches, ComparisonOp, FieldInstruction};+use crate::field::error::FieldParseError;+use crate::field::switches;++// ── Tokenizer ────────────────────────────────────────────────────────++/// A token produced by the field instruction tokenizer.+#[derive(Clone, Debug, PartialEq)]+pub(crate) enum Token {+ /// An unquoted word.+ Word(String, usize),+ /// A double-quoted string (contents only, quotes stripped).+ Quoted(String, usize),+ /// A switch: backslash followed by a character, e.g. `\o`, `\*`.+ Switch(char, usize),+}++/// Tokenize a field instruction string into a sequence of tokens.+pub(crate) fn tokenize(input: &str) -> Result<Vec<Token>, FieldParseError> {+ let mut tokens = Vec::new();+ let bytes = input.as_bytes();+ let len = bytes.len();+ let mut i = 0;++ while i < len {+ // Skip whitespace+ if bytes[i].is_ascii_whitespace() {+ i += 1;+ continue;+ }++ // Quoted string+ if bytes[i] == b'"' {+ let start = i;+ i += 1; // skip opening quote+ while i < len && bytes[i] != b'"' {+ i += 1;+ }+ if i >= len {+ return Err(FieldParseError::UnterminatedString { position: start });+ }+ i += 1; // skip closing quote+ // Handle Unicode: re-decode from the original slice for non-ASCII+ let content = &input[start + 1..i - 1];+ tokens.push(Token::Quoted(content.to_string(), start));+ continue;+ }++ // Switch: backslash followed by a non-whitespace character+ if bytes[i] == b'\\' {+ let start = i;+ i += 1;+ if i < len && !bytes[i].is_ascii_whitespace() {+ let ch = bytes[i] as char;+ i += 1;+ tokens.push(Token::Switch(ch, start));+ } else {+ return Err(FieldParseError::InvalidSwitch {+ position: start,+ found: "\\".to_string(),+ });+ }+ continue;+ }++ // Word: sequence of non-whitespace, non-quote, non-backslash characters+ let start = i;+ while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b'"' && bytes[i] != b'\\' {+ i += 1;+ }+ let word = &input[start..i];+ tokens.push(Token::Word(word.to_string(), start));+ }++ Ok(tokens)+}++// ── Parser ───────────────────────────────────────────────────────────++/// Parse a field instruction string into a typed `FieldInstruction`.+pub fn parse(input: &str) -> Result<FieldInstruction, FieldParseError> {+ let tokens = tokenize(input)?;+ if tokens.is_empty() {+ return Err(FieldParseError::Empty);+ }++ // First token must be a word (the field type keyword)+ let (field_type_str, rest) = match &tokens[0] {+ Token::Word(w, _) => (w.as_str(), &tokens[1..]),+ Token::Quoted(_, pos) | Token::Switch(_, pos) => {+ return Err(FieldParseError::MissingArgument {+ field_type: String::new(),+ argument: format!("field type keyword at position {pos}"),+ });+ }+ };++ // Extract common switches first+ let (common, mut remaining) = switches::extract_common_switches(rest)?;++ match field_type_str.to_ascii_uppercase().as_str() {+ "PAGE" => Ok(FieldInstruction::Page { switches: common }),+ "NUMPAGES" => Ok(FieldInstruction::NumPages { switches: common }),+ "SECTION" => Ok(FieldInstruction::Section { switches: common }),+ "SECTIONPAGES" => Ok(FieldInstruction::SectionPages { switches: common }),++ "DATE" => {+ let format = take_first_arg(&mut remaining);+ Ok(FieldInstruction::Date {+ format,+ switches: common,+ })+ }+ "TIME" => {+ let format = take_first_arg(&mut remaining);+ Ok(FieldInstruction::Time {+ format,+ switches: common,+ })+ }+ "AUTHOR" => {+ let format = take_first_arg(&mut remaining);+ Ok(FieldInstruction::Author {+ format,+ switches: common,+ })+ }+ "TITLE" => Ok(FieldInstruction::Title { switches: common }),+ "SUBJECT" => Ok(FieldInstruction::Subject { switches: common }),++ "FILENAME" => {+ let path = switches::has_flag(&remaining, 'p');+ Ok(FieldInstruction::FileName {+ path,+ switches: common,+ })+ }++ "REF" => {+ let bookmark = require_first_arg(&mut remaining, "REF", "bookmark")?;+ let footnote_ref = switches::has_flag(&remaining, 'f');+ let paragraph_number = switches::has_flag(&remaining, 'n');+ let hyperlink = switches::has_flag(&remaining, 'h');+ Ok(FieldInstruction::Ref {+ bookmark,+ footnote_ref,+ paragraph_number,+ hyperlink,+ switches: common,+ })+ }++ "PAGEREF" => {+ let bookmark = require_first_arg(&mut remaining, "PAGEREF", "bookmark")?;+ let hyperlink = switches::has_flag(&remaining, 'h');+ Ok(FieldInstruction::PageRef {+ bookmark,+ hyperlink,+ switches: common,+ })+ }++ "NOTEREF" => {+ let bookmark = require_first_arg(&mut remaining, "NOTEREF", "bookmark")?;+ let superscript = switches::has_flag(&remaining, 'f');+ let hyperlink = switches::has_flag(&remaining, 'h');+ Ok(FieldInstruction::NoteRef {+ bookmark,+ superscript,+ hyperlink,+ switches: common,+ })+ }++ "HYPERLINK" => {+ let target = require_first_arg(&mut remaining, "HYPERLINK", "target URL")?;+ let anchor = switches::take_switch_with_value(&mut remaining, 'l')?;+ let target_frame = switches::take_switch_with_value(&mut remaining, 't')?;+ let image_map = switches::has_flag(&remaining, 'm');+ Ok(FieldInstruction::Hyperlink {+ target,+ anchor,+ target_frame,+ image_map,+ switches: common,+ })+ }++ "TOC" => {+ let outline_levels = switches::take_switch_with_value(&mut remaining, 'o')?;+ let hyperlinks = switches::has_flag(&remaining, 'h');+ let no_page_numbers = switches::has_flag(&remaining, 'n');+ let custom_styles = switches::take_switch_with_value(&mut remaining, 't')?;+ let tc_identifier = switches::take_switch_with_value(&mut remaining, 'f')?;+ Ok(FieldInstruction::Toc {+ outline_levels,+ hyperlinks,+ no_page_numbers,+ custom_styles,+ tc_identifier,+ switches: common,+ })+ }++ "SEQ" => {+ let identifier = require_first_arg(&mut remaining, "SEQ", "identifier")?;+ let reset_to = switches::take_switch_with_value(&mut remaining, 'r')?;+ let repeat = switches::has_flag(&remaining, 'c');+ let next = switches::has_flag(&remaining, 'n');+ Ok(FieldInstruction::Seq {+ identifier,+ reset_to,+ repeat,+ next,+ switches: common,+ })+ }++ "IF" => parse_if_field(&mut remaining, common),++ "MERGEFIELD" => {+ let name = require_first_arg(&mut remaining, "MERGEFIELD", "field name")?;+ let text_before = switches::take_switch_with_value(&mut remaining, 'b')?;+ let text_after = switches::take_switch_with_value(&mut remaining, 'f')?;+ Ok(FieldInstruction::MergeField {+ name,+ text_before,+ text_after,+ switches: common,+ })+ }++ "DOCPROPERTY" => {+ let name = require_first_arg(&mut remaining, "DOCPROPERTY", "property name")?;+ Ok(FieldInstruction::DocProperty {+ name,+ switches: common,+ })+ }++ "SYMBOL" => {+ let code_str = require_first_arg(&mut remaining, "SYMBOL", "character code")?;+ let char_code =+ code_str+ .parse::<u32>()+ .map_err(|e| FieldParseError::InvalidNumber {+ value: code_str,+ reason: e.to_string(),+ })?;+ let font = switches::take_switch_with_value(&mut remaining, 'f')?;+ Ok(FieldInstruction::Symbol {+ char_code,+ font,+ switches: common,+ })+ }++ "INCLUDEPICTURE" => {+ let path = require_first_arg(&mut remaining, "INCLUDEPICTURE", "file path")?;+ let no_store = switches::has_flag(&remaining, 'd');+ Ok(FieldInstruction::IncludePicture {+ path,+ no_store,+ switches: common,+ })+ }++ "EQ" => {+ // Collect all remaining tokens as the equation text+ let equation = collect_remaining_as_text(&remaining);+ Ok(FieldInstruction::Eq {+ equation,+ switches: common,+ })+ }++ _ => Ok(FieldInstruction::Unknown {+ field_type: field_type_str.to_string(),+ raw: input.to_string(),+ }),+ }+}++// ── Helpers ──────────────────────────────────────────────────────────++/// Take the first word/quoted argument from the remaining tokens, if present.+fn take_first_arg(tokens: &mut Vec<Token>) -> Option<String> {+ match tokens.first() {+ Some(Token::Word(s, _) | Token::Quoted(s, _)) => {+ let val = s.clone();+ tokens.remove(0);+ Some(val)+ }+ _ => None,+ }+}++/// Require the first word/quoted argument, returning an error if missing.+fn require_first_arg(+ tokens: &mut Vec<Token>,+ field_type: &str,+ argument: &str,+) -> Result<String, FieldParseError> {+ take_first_arg(tokens).ok_or_else(|| FieldParseError::MissingArgument {+ field_type: field_type.to_string(),+ argument: argument.to_string(),+ })+}++/// Collect all remaining tokens back into a single string.+fn collect_remaining_as_text(tokens: &[Token]) -> String {+ let mut parts = Vec::new();+ for token in tokens {+ match token {+ Token::Word(s, _) => parts.push(s.clone()),+ Token::Quoted(s, _) => {+ parts.push(format!("\"{s}\""));+ }+ Token::Switch(ch, _) => parts.push(format!("\\{ch}")),+ }+ }+ parts.join(" ")+}++/// Parse an IF field: `IF expr op expr "then" "else"`+fn parse_if_field(+ tokens: &mut Vec<Token>,+ switches: CommonSwitches,+) -> Result<FieldInstruction, FieldParseError> {+ let left = require_first_arg(tokens, "IF", "left operand")?;++ let op_str = require_first_arg(tokens, "IF", "comparison operator")?;+ let operator = parse_comparison_op(&op_str)?;++ let right = require_first_arg(tokens, "IF", "right operand")?;++ let then_text = take_first_arg(tokens).unwrap_or_default();+ let else_text = take_first_arg(tokens).unwrap_or_default();++ Ok(FieldInstruction::If {+ left,+ operator,+ right,+ then_text,+ else_text,+ switches,+ })+}++fn parse_comparison_op(s: &str) -> Result<ComparisonOp, FieldParseError> {+ match s {+ "=" => Ok(ComparisonOp::Equal),+ "<>" => Ok(ComparisonOp::NotEqual),+ "<" => Ok(ComparisonOp::LessThan),+ "<=" => Ok(ComparisonOp::LessEqual),+ ">" => Ok(ComparisonOp::GreaterThan),+ ">=" => Ok(ComparisonOp::GreaterEqual),+ _ => Err(FieldParseError::InvalidOperator {+ found: s.to_string(),+ }),+ }+}++// ── Tests ────────────────────────────────────────────────────────────++#[cfg(test)]+mod tests {+ use super::*;+ use crate::field::ast::*;++ #[test]+ fn tokenize_simple() {+ let tokens = tokenize(" PAGE ").unwrap();+ assert_eq!(tokens, vec![Token::Word("PAGE".into(), 1)]);+ }++ #[test]+ fn tokenize_switches_and_quoted() {+ let tokens = tokenize(r#" TOC \o "1-3" \h "#).unwrap();+ assert_eq!(+ tokens,+ vec![+ Token::Word("TOC".into(), 1),+ Token::Switch('o', 5),+ Token::Quoted("1-3".into(), 8),+ Token::Switch('h', 14),+ ]+ );+ }++ #[test]+ fn tokenize_unterminated_string() {+ let err = tokenize(r#" REF "unterminated "#).unwrap_err();+ assert!(matches!(err, FieldParseError::UnterminatedString { .. }));+ }++ #[test]+ fn parse_page() {+ let instr = parse(" PAGE ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Page {+ switches: CommonSwitches::default()+ }+ );+ }++ #[test]+ fn parse_page_case_insensitive() {+ let instr = parse(" page ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Page {+ switches: CommonSwitches::default()+ }+ );+ }++ #[test]+ fn parse_page_with_format_switch() {+ let instr = parse(r#" PAGE \* MERGEFORMAT "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Page {+ switches: CommonSwitches {+ format: Some("MERGEFORMAT".into()),+ numeric_format: None,+ date_format: None,+ }+ }+ );+ }++ #[test]+ fn parse_numpages() {+ let instr = parse(" NUMPAGES ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::NumPages {+ switches: CommonSwitches::default()+ }+ );+ }++ #[test]+ fn parse_date_with_format() {+ let instr = parse(r#" DATE \@ "dd/MM/yyyy" "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Date {+ format: None,+ switches: CommonSwitches {+ format: None,+ numeric_format: None,+ date_format: Some("dd/MM/yyyy".into()),+ },+ }+ );+ }++ #[test]+ fn parse_ref_with_switches() {+ let instr = parse(r" REF _Toc123 \h \n ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Ref {+ bookmark: "_Toc123".into(),+ footnote_ref: false,+ paragraph_number: true,+ hyperlink: true,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_ref_missing_bookmark() {+ let err = parse(" REF ").unwrap_err();+ assert!(matches!(err, FieldParseError::MissingArgument { .. }));+ }++ #[test]+ fn parse_hyperlink() {+ let instr = parse(r#" HYPERLINK "https://example.com" \l "section1" "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Hyperlink {+ target: "https://example.com".into(),+ anchor: Some("section1".into()),+ target_frame: None,+ image_map: false,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_toc() {+ let instr = parse(r#" TOC \o "1-3" \h "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Toc {+ outline_levels: Some("1-3".into()),+ hyperlinks: true,+ no_page_numbers: false,+ custom_styles: None,+ tc_identifier: None,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_if_field() {+ let instr = parse(r#" IF x = y "yes" "no" "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::If {+ left: "x".into(),+ operator: ComparisonOp::Equal,+ right: "y".into(),+ then_text: "yes".into(),+ else_text: "no".into(),+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_mergefield() {+ let instr = parse(r#" MERGEFIELD FirstName \* Upper "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::MergeField {+ name: "FirstName".into(),+ text_before: None,+ text_after: None,+ switches: CommonSwitches {+ format: Some("Upper".into()),+ numeric_format: None,+ date_format: None,+ },+ }+ );+ }++ #[test]+ fn parse_symbol() {+ let instr = parse(r#" SYMBOL 169 \f "Symbol" "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Symbol {+ char_code: 169,+ font: Some("Symbol".into()),+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_symbol_invalid_code() {+ let err = parse(" SYMBOL abc ").unwrap_err();+ assert!(matches!(err, FieldParseError::InvalidNumber { .. }));+ }++ #[test]+ fn parse_unknown_field() {+ let input = " FOOBAR something ";+ let instr = parse(input).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Unknown {+ field_type: "FOOBAR".into(),+ raw: input.to_string(),+ }+ );+ }++ #[test]+ fn parse_empty() {+ let err = parse(" ").unwrap_err();+ assert_eq!(err, FieldParseError::Empty);+ }++ #[test]+ fn parse_filename_with_path() {+ let instr = parse(r" FILENAME \p ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::FileName {+ path: true,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_seq() {+ let instr = parse(r" SEQ Figure \r 1 ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Seq {+ identifier: "Figure".into(),+ reset_to: Some("1".into()),+ repeat: false,+ next: false,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_pageref() {+ let instr = parse(r" PAGEREF _Ref123 \h ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::PageRef {+ bookmark: "_Ref123".into(),+ hyperlink: true,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_docproperty() {+ let instr = parse(" DOCPROPERTY Author ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::DocProperty {+ name: "Author".into(),+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_includepicture() {+ let instr = parse(r#" INCLUDEPICTURE "image.png" \d "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::IncludePicture {+ path: "image.png".into(),+ no_store: true,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_noteref() {+ let instr = parse(r" NOTEREF _Ref456 \f \h ").unwrap();+ assert_eq!(+ instr,+ FieldInstruction::NoteRef {+ bookmark: "_Ref456".into(),+ superscript: true,+ hyperlink: true,+ switches: CommonSwitches::default(),+ }+ );+ }++ #[test]+ fn parse_numeric_format() {+ let instr = parse(r#" PAGE \# "0.00" "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::Page {+ switches: CommonSwitches {+ format: None,+ numeric_format: Some("0.00".into()),+ date_format: None,+ }+ }+ );+ }++ #[test]+ fn parse_if_not_equal() {+ let instr = parse(r#" IF a <> b "different" "same" "#).unwrap();+ assert_eq!(+ instr,+ FieldInstruction::If {+ left: "a".into(),+ operator: ComparisonOp::NotEqual,+ right: "b".into(),+ then_text: "different".into(),+ else_text: "same".into(),+ switches: CommonSwitches::default(),+ }+ );+ }+}diff --git a/crates/liteparse-docx/src/field/switches.rs b/crates/liteparse-docx/src/field/switches.rsnew file mode 100644index 0000000..e10f4c1--- /dev/null+++ b/crates/liteparse-docx/src/field/switches.rs@@ -0,0 +1,212 @@+use crate::field::ast::CommonSwitches;+use crate::field::error::FieldParseError;+use crate::field::parse::Token;++/// Consume common formatting switches (`\*`, `\#`, `\@`) from a token stream.+///+/// Returns the consumed switches and any tokens that were not common switches+/// (i.e., field-specific switches or arguments).+pub(crate) fn extract_common_switches(+ tokens: &[Token],+) -> Result<(CommonSwitches, Vec<Token>), FieldParseError> {+ let mut switches = CommonSwitches::default();+ let mut remaining = Vec::new();+ let mut i = 0;++ while i < tokens.len() {+ match &tokens[i] {+ Token::Switch(ch, pos) if *ch == '*' => {+ i += 1;+ let value = take_switch_value(tokens, &mut i, "\\*", *pos)?;+ switches.format = Some(value);+ }+ Token::Switch(ch, pos) if *ch == '#' => {+ i += 1;+ let value = take_switch_value(tokens, &mut i, "\\#", *pos)?;+ switches.numeric_format = Some(value);+ }+ Token::Switch(ch, pos) if *ch == '@' => {+ i += 1;+ let value = take_switch_value(tokens, &mut i, "\\@", *pos)?;+ switches.date_format = Some(value);+ }+ _ => {+ remaining.push(tokens[i].clone());+ i += 1;+ }+ }+ }++ Ok((switches, remaining))+}++/// Take a switch value — either the next quoted string or word token.+fn take_switch_value(+ tokens: &[Token],+ i: &mut usize,+ switch_name: &str,+ _pos: usize,+) -> Result<String, FieldParseError> {+ if *i < tokens.len() {+ match &tokens[*i] {+ Token::Quoted(s, _) | Token::Word(s, _) => {+ let val = s.clone();+ *i += 1;+ Ok(val)+ }+ _ => Err(FieldParseError::MissingSwitchValue {+ switch: switch_name.to_string(),+ }),+ }+ } else {+ Err(FieldParseError::MissingSwitchValue {+ switch: switch_name.to_string(),+ })+ }+}++/// Return whether a flag switch (`\<ch>`, no value) is present anywhere in the+/// token stream. A pure predicate — it does not consume or reorder tokens.+pub(crate) fn has_flag(tokens: &[Token], ch: char) -> bool {+ tokens+ .iter()+ .any(|t| matches!(t, Token::Switch(c, _) if *c == ch))+}++/// Find a switch with the given character and consume its value argument.+/// Returns `Some(value)` if found, `None` if not present.+pub(crate) fn take_switch_with_value(+ tokens: &mut Vec<Token>,+ ch: char,+) -> Result<Option<String>, FieldParseError> {+ let pos = tokens+ .iter()+ .position(|t| matches!(t, Token::Switch(c, _) if *c == ch));++ let Some(idx) = pos else {+ return Ok(None);+ };++ let switch_pos = match &tokens[idx] {+ Token::Switch(_, p) => *p,+ _ => unreachable!(),+ };++ // Remove the switch token+ tokens.remove(idx);++ // The value should now be at `idx` (shifted down)+ if idx < tokens.len() {+ match &tokens[idx] {+ Token::Quoted(s, _) | Token::Word(s, _) => {+ let val = s.clone();+ tokens.remove(idx);+ Ok(Some(val))+ }+ _ => Err(FieldParseError::MissingSwitchValue {+ switch: format!("\\{ch}"),+ }),+ }+ } else {+ Err(FieldParseError::MissingSwitchValue {+ switch: format!("\\{ch} at position {switch_pos}"),+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn extract_captures_all_three_common_switches() {+ // \* MERGEFORMAT \# "0.00" \@ "dd/MM/yyyy"+ let tokens = vec![+ Token::Switch('*', 0),+ Token::Word("MERGEFORMAT".into(), 2),+ Token::Switch('#', 14),+ Token::Quoted("0.00".into(), 16),+ Token::Switch('@', 22),+ Token::Quoted("dd/MM/yyyy".into(), 24),+ ];+ let (sw, remaining) = extract_common_switches(&tokens).unwrap();+ assert_eq!(sw.format.as_deref(), Some("MERGEFORMAT"));+ assert_eq!(sw.numeric_format.as_deref(), Some("0.00"));+ assert_eq!(sw.date_format.as_deref(), Some("dd/MM/yyyy"));+ assert!(remaining.is_empty());+ }++ #[test]+ fn extract_leaves_field_specific_tokens() {+ // \o "1-3" is field-specific and must pass through untouched.+ let tokens = vec![+ Token::Switch('o', 0),+ Token::Quoted("1-3".into(), 2),+ Token::Switch('*', 8),+ Token::Word("Upper".into(), 10),+ ];+ let (sw, remaining) = extract_common_switches(&tokens).unwrap();+ assert_eq!(sw.format.as_deref(), Some("Upper"));+ assert_eq!(remaining.len(), 2);+ assert!(matches!(&remaining[0], Token::Switch('o', _)));+ assert!(matches!(&remaining[1], Token::Quoted(s, _) if s == "1-3"));+ }++ #[test]+ fn extract_missing_value_is_error() {+ let tokens = vec![Token::Switch('*', 0)];+ assert!(matches!(+ extract_common_switches(&tokens),+ Err(FieldParseError::MissingSwitchValue { .. })+ ));+ }++ #[test]+ fn has_flag_is_a_pure_predicate() {+ let tokens = vec![Token::Switch('h', 0), Token::Word("x".into(), 2)];+ assert!(has_flag(&tokens, 'h'));+ assert!(!has_flag(&tokens, 'z'));+ // Does not consume: the stream is unchanged (it takes `&[Token]`).+ assert_eq!(tokens.len(), 2);+ }++ #[test]+ fn take_switch_with_value_found_removes_switch_and_value() {+ let mut tokens = vec![+ Token::Switch('l', 0),+ Token::Quoted("bookmark".into(), 2),+ Token::Word("keep".into(), 12),+ ];+ let v = take_switch_with_value(&mut tokens, 'l').unwrap();+ assert_eq!(v.as_deref(), Some("bookmark"));+ // Only the trailing unrelated token remains.+ assert_eq!(tokens.len(), 1);+ assert!(matches!(&tokens[0], Token::Word(s, _) if s == "keep"));+ }++ #[test]+ fn take_switch_with_value_absent_returns_none() {+ let mut tokens = vec![Token::Word("x".into(), 0)];+ assert_eq!(take_switch_with_value(&mut tokens, 'l').unwrap(), None);+ assert_eq!(tokens.len(), 1); // untouched+ }++ #[test]+ fn take_switch_with_value_at_end_is_error() {+ let mut tokens = vec![Token::Switch('l', 0)];+ assert!(matches!(+ take_switch_with_value(&mut tokens, 'l'),+ Err(FieldParseError::MissingSwitchValue { .. })+ ));+ }++ #[test]+ fn take_switch_with_value_wrong_value_type_is_error() {+ // \l immediately followed by another switch — no usable value.+ let mut tokens = vec![Token::Switch('l', 0), Token::Switch('m', 2)];+ assert!(matches!(+ take_switch_with_value(&mut tokens, 'l'),+ Err(FieldParseError::MissingSwitchValue { .. })+ ));+ }+}diff --git a/crates/liteparse-docx/src/lib.rs b/crates/liteparse-docx/src/lib.rsnew file mode 100644index 0000000..d88a529--- /dev/null+++ b/crates/liteparse-docx/src/lib.rs@@ -0,0 +1,26 @@+//! Native DOCX structure reader.+//!+//! Vendored, Skia-free subset of [dxpdf](https://github.com/nerdy-pro/dxpdf)+//! 0.4.0 (MIT — see `LICENSE` and `ATTRIBUTION.md`). Upstream is a DOCX→PDF+//! engine; this crate keeps only `parse → resolve`, which is where the+//! document's *structure* lives, and drops the Skia-bound layout/paint half.+//!+//! The whole point is that a DOCX already states, explicitly, everything the+//! LibreOffice→PDF→projection path has to reverse-engineer from coordinates:+//! heading levels (`outlineLvl`), list numbering (including `startOverride`),+//! merged cells (`gridSpan`/`vMerge`), emphasis, footnotes, reading order.+//!+//! ```no_run+//! let bytes = std::fs::read("report.docx")?;+//! let doc = liteparse_docx::docx::parse(&bytes)?;+//! let resolved = liteparse_docx::render::resolve::resolve(doc);+//! # Ok::<(), liteparse_docx::Error>(())+//! ```++pub mod docx;+pub mod error;+pub mod field;+pub mod model;+pub mod render;++pub use error::Error;diff --git a/crates/liteparse-docx/src/model/dimension.rs b/crates/liteparse-docx/src/model/dimension.rsnew file mode 100644index 0000000..da9f77c--- /dev/null+++ b/crates/liteparse-docx/src/model/dimension.rs@@ -0,0 +1,295 @@+use std::fmt;+use std::marker::PhantomData;+use std::ops::{Add, Div, Mul, Neg, Sub};++/// Marker trait for dimension unit types.+pub trait Unit: Copy + Clone + fmt::Debug + PartialEq + Eq {+ const NAME: &'static str;+}++/// A dimension value parameterized by its unit of measurement.+/// Integer storage for lossless OOXML round-tripping.+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+pub struct Dimension<U: Unit> {+ raw: i64,+ _unit: PhantomData<U>,+}++impl<U: Unit> Dimension<U> {+ pub const ZERO: Self = Self {+ raw: 0,+ _unit: PhantomData,+ };++ pub const fn new(raw: i64) -> Self {+ Self {+ raw,+ _unit: PhantomData,+ }+ }++ pub const fn raw(self) -> i64 {+ self.raw+ }+}++impl<U: Unit> fmt::Debug for Dimension<U> {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}{}", self.raw, U::NAME)+ }+}++impl<U: Unit> Default for Dimension<U> {+ fn default() -> Self {+ Self::ZERO+ }+}++// Ordering depends only on the stored value, never on the phantom unit, so+// `Dimension<U>` is `Ord` for *every* `U: Unit`. Deriving these would instead+// synthesize a spurious `U: Ord` bound — and no unit marker implements `Ord` —+// leaving the derived impl unusable and forcing callers to compare `.raw()` by+// hand. These manual impls (like the manual `Default`/arithmetic above) drop the+// bound.+impl<U: Unit> PartialOrd for Dimension<U> {+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {+ Some(self.cmp(other))+ }+}++impl<U: Unit> Ord for Dimension<U> {+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {+ self.raw.cmp(&other.raw)+ }+}++impl<U: Unit> Add for Dimension<U> {+ type Output = Self;+ fn add(self, rhs: Self) -> Self {+ Self::new(self.raw + rhs.raw)+ }+}++impl<U: Unit> Sub for Dimension<U> {+ type Output = Self;+ fn sub(self, rhs: Self) -> Self {+ Self::new(self.raw - rhs.raw)+ }+}++impl<U: Unit> Mul<i64> for Dimension<U> {+ type Output = Self;+ fn mul(self, rhs: i64) -> Self {+ Self::new(self.raw * rhs)+ }+}++impl<U: Unit> Div<i64> for Dimension<U> {+ type Output = Self;+ fn div(self, rhs: i64) -> Self {+ Self::new(self.raw / rhs)+ }+}++impl<U: Unit> Neg for Dimension<U> {+ type Output = Self;+ fn neg(self) -> Self {+ Self::new(-self.raw)+ }+}++// --- Unit markers ---++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct Twips;+impl Unit for Twips {+ const NAME: &'static str = "twip";+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct HalfPoints;+impl Unit for HalfPoints {+ const NAME: &'static str = "hp";+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct Emu;+impl Unit for Emu {+ const NAME: &'static str = "emu";+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct EighthPoints;+impl Unit for EighthPoints {+ const NAME: &'static str = "ep";+}++/// 1/4096th of a point — used for document grid character spacing (§17.6.5).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct FractionPoints;+impl Unit for FractionPoints {+ const NAME: &'static str = "fp4096";+}++/// §17.18.68 ST_PointMeasure — whole points (1/72nd of an inch).+/// Used for border spacing (§17.3.4 w:space).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct Points;+impl Unit for Points {+ const NAME: &'static str = "pt";+}++/// Percentage in 1/1000th of a percent (OOXML ST_DecimalNumberOrPercent).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct ThousandthPercent;+impl Unit for ThousandthPercent {+ const NAME: &'static str = "‰%";+}++/// DrawingML angle in 60,000ths of a degree (§20.1.10.3 ST_Angle).+/// 0 = no rotation, 5400000 = 90° clockwise.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct SixtieThousandthDeg;+impl Unit for SixtieThousandthDeg {+ const NAME: &'static str = "∠60k";+}++// --- Conversions ---++impl Dimension<Twips> {+ /// 1 twip = 1/20 of a point.+ pub fn to_half_points(self) -> Dimension<HalfPoints> {+ Dimension::new(self.raw / 10)+ }++ /// 1 twip = 635 EMU.+ pub fn to_emu(self) -> Dimension<Emu> {+ Dimension::new(self.raw * 635)+ }++ pub fn to_points_f32(self) -> f32 {+ self.raw as f32 / 20.0+ }+}++impl Dimension<HalfPoints> {+ pub fn to_twips(self) -> Dimension<Twips> {+ Dimension::new(self.raw * 10)+ }++ pub fn to_points_f32(self) -> f32 {+ self.raw as f32 / 2.0+ }+}++impl Dimension<Emu> {+ /// 1 EMU = 1/914400 inch = 1/635 twip.+ pub fn to_twips(self) -> Dimension<Twips> {+ Dimension::new(self.raw / 635)+ }++ pub fn to_points_f32(self) -> f32 {+ self.raw as f32 / 12700.0+ }+}++impl Dimension<EighthPoints> {+ pub fn to_half_points(self) -> Dimension<HalfPoints> {+ Dimension::new(self.raw / 4)+ }++ pub fn to_points_f32(self) -> f32 {+ self.raw as f32 / 8.0+ }+}++impl Dimension<ThousandthPercent> {+ /// Returns the percentage as a fraction (e.g., 50000 → 0.5).+ ///+ /// The single home for the ST_Percentage / CT_RelativeRect scale (100% =+ /// 100000); every consumer that needs a `[0, 1]` fraction routes through+ /// here rather than open-coding the divisor.+ pub fn to_fraction(self) -> f32 {+ self.raw as f32 / 100_000.0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// f32 equality with a small tolerance (clippy forbids bare `==` on floats).+ fn approx(a: f32, b: f32) {+ assert!((a - b).abs() < 1e-6, "{a} != {b}");+ }++ #[test]+ fn twips_to_half_points() {+ // 20 twips = 1 pt = 2 half-points; the conversion divides by 10.+ assert_eq!(Dimension::<Twips>::new(20).to_half_points().raw(), 2);+ assert_eq!(Dimension::<Twips>::new(1440).to_half_points().raw(), 144);+ }++ #[test]+ fn twips_emu_roundtrip() {+ // 1 twip = 635 EMU; 1 inch = 1440 twip = 914400 EMU.+ assert_eq!(Dimension::<Twips>::new(1440).to_emu().raw(), 914_400);+ assert_eq!(Dimension::<Emu>::new(914_400).to_twips().raw(), 1440);+ }++ #[test]+ fn to_points_conversions() {+ approx(Dimension::<Twips>::new(1440).to_points_f32(), 72.0);+ approx(Dimension::<Twips>::new(240).to_points_f32(), 12.0);+ approx(Dimension::<HalfPoints>::new(24).to_points_f32(), 12.0);+ approx(Dimension::<Emu>::new(12_700).to_points_f32(), 1.0);+ approx(Dimension::<EighthPoints>::new(8).to_points_f32(), 1.0);+ }++ #[test]+ fn half_points_to_twips() {+ assert_eq!(Dimension::<HalfPoints>::new(24).to_twips().raw(), 240);+ }++ #[test]+ fn eighth_points_to_half_points() {+ // 8 eighth-points = 1 pt = 2 half-points; divides by 4.+ assert_eq!(Dimension::<EighthPoints>::new(8).to_half_points().raw(), 2);+ }++ #[test]+ fn thousandth_percent_to_fraction() {+ approx(+ Dimension::<ThousandthPercent>::new(50_000).to_fraction(),+ 0.5,+ );+ approx(+ Dimension::<ThousandthPercent>::new(100_000).to_fraction(),+ 1.0,+ );+ approx(Dimension::<ThousandthPercent>::new(0).to_fraction(), 0.0);+ }++ #[test]+ fn arithmetic_ops() {+ let a = Dimension::<Twips>::new(100);+ let b = Dimension::<Twips>::new(30);+ assert_eq!((a + b).raw(), 130);+ assert_eq!((a - b).raw(), 70);+ assert_eq!((a * 3).raw(), 300);+ assert_eq!((a / 4).raw(), 25); // integer division truncates+ assert_eq!((-a).raw(), -100);+ }++ #[test]+ fn zero_and_default() {+ assert_eq!(Dimension::<Twips>::ZERO.raw(), 0);+ assert_eq!(Dimension::<Emu>::default().raw(), 0);+ }++ #[test]+ fn ordering_and_equality() {+ assert!(Dimension::<Twips>::new(10) < Dimension::<Twips>::new(20));+ assert_eq!(Dimension::<Twips>::new(5), Dimension::<Twips>::new(5));+ }+}diff --git a/crates/liteparse-docx/src/model/geometry.rs b/crates/liteparse-docx/src/model/geometry.rsnew file mode 100644index 0000000..7e48204--- /dev/null+++ b/crates/liteparse-docx/src/model/geometry.rs@@ -0,0 +1,191 @@+use crate::model::dimension::{Dimension, Unit};++/// A 2D offset (x, y) in a given unit.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Offset<U: Unit> {+ pub x: Dimension<U>,+ pub y: Dimension<U>,+}++impl<U: Unit> Offset<U> {+ pub const ZERO: Self = Self {+ x: Dimension::ZERO,+ y: Dimension::ZERO,+ };++ pub const fn new(x: Dimension<U>, y: Dimension<U>) -> Self {+ Self { x, y }+ }+}++/// A 2D size (width, height) in a given unit.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Size<U: Unit> {+ pub width: Dimension<U>,+ pub height: Dimension<U>,+}++impl<U: Unit> Size<U> {+ pub const ZERO: Self = Self {+ width: Dimension::ZERO,+ height: Dimension::ZERO,+ };++ pub const fn new(width: Dimension<U>, height: Dimension<U>) -> Self {+ Self { width, height }+ }+}++/// A rectangle defined by origin + size.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Rect<U: Unit> {+ pub origin: Offset<U>,+ pub size: Size<U>,+}++impl<U: Unit> Rect<U> {+ pub const fn new(origin: Offset<U>, size: Size<U>) -> Self {+ Self { origin, size }+ }+}++/// Insets from each edge (top, right, bottom, left) — used for margins and padding.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct EdgeInsets<U: Unit> {+ pub top: Dimension<U>,+ pub right: Dimension<U>,+ pub bottom: Dimension<U>,+ pub left: Dimension<U>,+}++impl<U: Unit> EdgeInsets<U> {+ pub const ZERO: Self = Self {+ top: Dimension::ZERO,+ right: Dimension::ZERO,+ bottom: Dimension::ZERO,+ left: Dimension::ZERO,+ };++ pub const fn new(+ top: Dimension<U>,+ right: Dimension<U>,+ bottom: Dimension<U>,+ left: Dimension<U>,+ ) -> Self {+ Self {+ top,+ right,+ bottom,+ left,+ }+ }++ pub const fn uniform(value: Dimension<U>) -> Self {+ Self {+ top: value,+ right: value,+ bottom: value,+ left: value,+ }+ }+}++/// Edge insets where each side may be unspecified — used for cell-level+/// overrides (`<w:tcMar>`) that cascade against a parent default. Per+/// OOXML §17.4.42, an explicit `<w:tcMar>` with only some sides present+/// inherits the remaining sides from the table-level `<w:tblCellMar>`;+/// `unwrap_or_default()` per side would incorrectly zero out the inherited+/// values (visible as missing left/right padding inside a cell whose+/// `tcMar` set only `top` and `bottom`). `resolve_against` performs the+/// per-side fallback.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct PartialEdgeInsets<U: Unit> {+ pub top: Option<Dimension<U>>,+ pub right: Option<Dimension<U>>,+ pub bottom: Option<Dimension<U>>,+ pub left: Option<Dimension<U>>,+}++impl<U: Unit> PartialEdgeInsets<U> {+ pub const fn new(+ top: Option<Dimension<U>>,+ right: Option<Dimension<U>>,+ bottom: Option<Dimension<U>>,+ left: Option<Dimension<U>>,+ ) -> Self {+ Self {+ top,+ right,+ bottom,+ left,+ }+ }++ /// Resolve unspecified sides against a fully-specified default.+ pub fn resolve_against(self, default: EdgeInsets<U>) -> EdgeInsets<U> {+ EdgeInsets {+ top: self.top.unwrap_or(default.top),+ right: self.right.unwrap_or(default.right),+ bottom: self.bottom.unwrap_or(default.bottom),+ left: self.left.unwrap_or(default.left),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::Twips;++ fn tw(v: i64) -> Dimension<Twips> {+ Dimension::new(v)+ }++ #[test]+ fn partial_insets_resolve_per_side() {+ // §17.4.42: a tcMar that sets only top/bottom inherits left/right from+ // the table default — it must NOT zero the absent sides.+ let default = EdgeInsets::<Twips>::uniform(tw(100));+ let partial = PartialEdgeInsets::new(Some(tw(5)), None, Some(tw(7)), None);+ let resolved = partial.resolve_against(default);+ assert_eq!(resolved.top, tw(5));+ assert_eq!(resolved.right, tw(100)); // inherited+ assert_eq!(resolved.bottom, tw(7));+ assert_eq!(resolved.left, tw(100)); // inherited+ }++ #[test]+ fn all_none_partial_inherits_everything() {+ let default = EdgeInsets::new(tw(1), tw(2), tw(3), tw(4));+ // All sides absent → every side falls back to the default.+ let resolved =+ PartialEdgeInsets::<Twips>::new(None, None, None, None).resolve_against(default);+ assert_eq!(resolved, default);+ }++ #[test]+ fn fully_specified_partial_ignores_default() {+ let default = EdgeInsets::<Twips>::uniform(tw(99));+ let partial = PartialEdgeInsets::new(Some(tw(1)), Some(tw(2)), Some(tw(3)), Some(tw(4)));+ assert_eq!(+ partial.resolve_against(default),+ EdgeInsets::new(tw(1), tw(2), tw(3), tw(4))+ );+ }++ #[test]+ fn uniform_sets_all_edges() {+ let e = EdgeInsets::<Twips>::uniform(tw(9));+ assert_eq!(+ (e.top, e.right, e.bottom, e.left),+ (tw(9), tw(9), tw(9), tw(9))+ );+ }++ #[test]+ fn zero_consts() {+ assert_eq!(Offset::<Twips>::ZERO.x, tw(0));+ assert_eq!(Size::<Twips>::ZERO.height, tw(0));+ assert_eq!(EdgeInsets::<Twips>::ZERO.top, tw(0));+ }+}diff --git a/crates/liteparse-docx/src/model/mod.rs b/crates/liteparse-docx/src/model/mod.rsnew file mode 100644index 0000000..6c9ffee--- /dev/null+++ b/crates/liteparse-docx/src/model/mod.rs@@ -0,0 +1,9 @@+//! DOCX document model — fully resolved algebraic data types.+//!+//! This crate contains the type-safe dimension system, geometry primitives,+//! and the complete DOCX document model. No parsing logic, no external dependencies.++pub mod dimension;+pub mod geometry;+pub mod types;+pub use types::*;diff --git a/crates/liteparse-docx/src/model/types/color.rs b/crates/liteparse-docx/src/model/types/color.rsnew file mode 100644index 0000000..334fd52--- /dev/null+++ b/crates/liteparse-docx/src/model/types/color.rs@@ -0,0 +1,15 @@+//! Color types.++/// A color value as specified in the XML (§17.18.5 ST_HexColor).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Color {+ /// sRGB color parsed from a 6-digit hex string (0xRRGGBB).+ Rgb(u32),+ /// The special "auto" color — meaning context-dependent.+ Auto,+}++impl Color {+ pub const BLACK: Self = Self::Rgb(0x000000);+ pub const WHITE: Self = Self::Rgb(0xFFFFFF);+}diff --git a/crates/liteparse-docx/src/model/types/content.rs b/crates/liteparse-docx/src/model/types/content.rsnew file mode 100644index 0000000..e29a69d--- /dev/null+++ b/crates/liteparse-docx/src/model/types/content.rs@@ -0,0 +1,198 @@+//! Content model — Block and Inline enums, hyperlinks, fields, alternate content.++use crate::field::FieldInstruction;++use super::drawing::Image;+use super::identifiers::{BookmarkId, NoteId, RevisionIds, StyleId};+use super::paragraph::Paragraph;+use super::run_properties::RunProperties;+use super::section::SectionProperties;+use super::table::Table;+use super::vml::Pict;++// ── Blocks ───────────────────────────────────────────────────────────────────++#[derive(Clone, Debug)]+pub enum Block {+ Paragraph(Box<Paragraph>),+ Table(Box<Table>),+ /// A section break that applies to all preceding content since the last break.+ SectionBreak(Box<SectionProperties>),+}++// ── Inline content ───────────────────────────────────────────────────────────++/// A child element within a `<w:r>` run. All elements in a run share+/// the same `RunProperties` (font, size, color, etc.).+#[derive(Clone, Debug)]+pub enum RunElement {+ Text(String),+ Tab,+ /// §17.3.1.30: absolute-position tab (`<w:ptab>`).+ PositionTab(super::formatting::PositionTab),+ LineBreak(BreakKind),+ ColumnBreak,+ PageBreak,+ /// §17.3.3.13: rendering hint, not a content break.+ LastRenderedPageBreak,+}++#[derive(Clone, Debug)]+pub enum Inline {+ TextRun(Box<TextRun>),+ Image(Box<Image>),+ FootnoteRef(NoteId),+ EndnoteRef(NoteId),+ Hyperlink(Hyperlink),+ Field(Field),+ BookmarkStart {+ id: BookmarkId,+ name: String,+ },+ BookmarkEnd(BookmarkId),+ Symbol(Symbol),+ /// §17.11.23: footnote/endnote separator line.+ Separator,+ /// §17.11.3: continuation separator for notes spanning pages.+ ContinuationSeparator,+ /// §17.16.18: complex field character (begin/separate/end marker).+ FieldChar(FieldChar),+ /// §17.16.23: field instruction text (appears between begin and separate).+ InstrText(String),+ /// §17.11.13: footnote reference mark (auto-number rendered in the footnote body).+ FootnoteRefMark,+ /// §17.11.6: endnote reference mark (auto-number rendered in the endnote body).+ EndnoteRefMark,+ /// §17.3.3.19: VML picture/shape container (legacy drawing).+ Pict(Pict),+ /// MCE §M.2.1: markup compatibility alternate content.+ AlternateContent(AlternateContent),+}++/// §17.16.18: complex field character marker.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct FieldChar {+ /// §17.18.29 ST_FldCharType: begin, separate, or end.+ pub field_char_type: FieldCharType,+ /// Field result needs recalculation.+ pub dirty: Option<bool>,+ /// Field is locked from updates.+ pub fld_lock: Option<bool>,+}++/// §17.18.29 ST_FldCharType+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FieldCharType {+ Begin,+ Separate,+ End,+}++#[derive(Clone, Debug)]+pub struct TextRun {+ /// Character style ID reference (e.g., "Hyperlink"). Resolve via `Document.styles`.+ pub style_id: Option<StyleId>,+ pub properties: RunProperties,+ /// Children of this run: text segments, breaks, and tabs.+ /// All share the run's properties.+ pub content: Vec<RunElement>,+ pub rsids: RevisionIds,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum BreakKind {+ TextWrapping,+ /// Clears left, right, or both float areas.+ Clear(BreakClear),+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum BreakClear {+ None,+ Left,+ Right,+ All,+}++/// A symbol character from a specific font (w:sym).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Symbol {+ pub font: String,+ pub char_code: u16,+}++// ── Hyperlink ────────────────────────────────────────────────────────────────++#[derive(Clone, Debug)]+pub struct Hyperlink {+ pub target: HyperlinkTarget,+ pub content: Vec<Inline>,+}++/// A hyperlink target. External links start life as an unresolved relationship+/// id (`w:hyperlink/@r:id`) and are rewritten to a concrete URL by the+/// parse-time `resolve_hyperlinks` pass; the two states are distinct variants so+/// no code has to guess whether an `External` payload is an rId or a URL.+#[derive(Clone, Debug)]+pub enum HyperlinkTarget {+ /// Unresolved external relationship id, before the rels lookup.+ ExternalRel(super::identifiers::RelId),+ /// Resolved external URL, after `resolve_hyperlinks`.+ ExternalUrl(String),+ /// Internal bookmark anchor.+ Internal { anchor: String },+}++// ── Field ────────────────────────────────────────────────────────────────────++/// A simple field (w:fldSimple). Stores the parsed field instruction.+#[derive(Clone, Debug)]+pub struct Field {+ /// Parsed field instruction (e.g., `FieldInstruction::Page`, `FieldInstruction::Toc { .. }`).+ pub instruction: FieldInstruction,+ pub content: Vec<Inline>,+}++// ── Alternate Content ────────────────────────────────────────────────────────++/// MCE §M.2.1: alternate content for markup compatibility.+#[derive(Clone, Debug)]+pub struct AlternateContent {+ /// §M.2.2: ordered list of preferred choices.+ pub choices: Vec<McChoice>,+ /// §M.2.3: fallback content when no choice is supported.+ pub fallback: Option<Vec<Inline>>,+}++/// MCE §M.2.2: a single choice in alternate content.+#[derive(Clone, Debug)]+pub struct McChoice {+ /// Required namespace/feature identifiers. `@Requires` is a space-separated+ /// list of prefixes; the choice is usable only if every one is understood.+ pub requires: Vec<McRequires>,+ /// Inline content for this choice.+ pub content: Vec<Inline>,+}++/// MCE §M.2.2: namespace prefixes used in `mc:Choice Requires`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum McRequires {+ /// Word Processing Shape (wps).+ Wps,+ /// Word Processing Group (wpg).+ Wpg,+ /// Word Processing Canvas (wpc).+ Wpc,+ /// Word Processing Ink (wpi).+ Wpi,+ /// Math (m).+ Math,+ /// DrawingML 2010 (a14).+ A14,+ /// Word 2010 extensions (w14).+ W14,+ /// Word 2012 extensions (w15).+ W15,+ /// Word 2016 extensions (w16).+ W16,+}diff --git a/crates/liteparse-docx/src/model/types/document.rs b/crates/liteparse-docx/src/model/types/document.rsnew file mode 100644index 0000000..5c6bda9--- /dev/null+++ b/crates/liteparse-docx/src/model/types/document.rs@@ -0,0 +1,72 @@+//! Top-level Document struct.++use std::collections::HashMap;+use std::sync::Arc;++use super::content::Block;+use super::drawing::ImageFormat;+use super::identifiers::{NoteId, RelId};+use super::numbering::NumberingDefinitions;+use super::section::SectionProperties;+use super::settings::DocumentSettings;+use super::styles::StyleSheet;+use super::theme::Theme;++/// The fully parsed and resolved DOCX document.+#[derive(Clone, Debug)]+pub struct Document {+ pub settings: DocumentSettings,+ pub theme: Option<Theme>,+ /// Style definitions from `word/styles.xml`, with `basedOn` references intact.+ pub styles: StyleSheet,+ /// Numbering definitions from `word/numbering.xml`.+ pub numbering: NumberingDefinitions,+ pub body: Vec<Block>,+ /// Final section properties (from the last `w:sectPr` in `w:body`).+ pub final_section: SectionProperties,+ /// Header content keyed by relationship ID.+ pub headers: HashMap<RelId, Vec<Block>>,+ /// Footer content keyed by relationship ID.+ pub footers: HashMap<RelId, Vec<Block>>,+ pub footnotes: HashMap<NoteId, Vec<Block>>,+ pub endnotes: HashMap<NoteId, Vec<Block>>,+ /// Embedded media (images) — raw bytes and detected format, keyed by+ /// relationship ID.+ ///+ /// The bytes are shared rather than owned so that the resolve layer, which+ /// consumes this document, hands the painter a *handle* instead of copying+ /// every image a second time — on an image-heavy document that copy is the+ /// single largest allocation in the pipeline. `Arc` rather than `Rc` keeps+ /// `Document` `Send`, so a caller may still parse on one thread and render+ /// on another; the refcount is touched once per image placement, which is+ /// nowhere near hot enough for the atomic to matter.+ pub media: HashMap<RelId, (Arc<[u8]>, ImageFormat)>,+ /// §17.8.3: embedded fonts — de-obfuscated font data.+ pub embedded_fonts: Vec<EmbeddedFont>,+}++/// §17.8.3: an embedded font extracted from the DOCX package.+/// The font data is de-obfuscated (XOR with fontKey per §17.8.3.3)+/// and ready to be registered with a font manager.+#[derive(Clone, Debug)]+pub struct EmbeddedFont {+ /// Font family name from `w:font/@w:name`.+ pub family: String,+ /// Which variant of the font this is.+ pub variant: EmbeddedFontVariant,+ /// De-obfuscated TrueType/OpenType font data.+ pub data: Vec<u8>,+}++/// §17.8.3.3: which style variant an embedded font represents.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum EmbeddedFontVariant {+ /// §17.8.3.3 w:embedRegular+ Regular,+ /// §17.8.3.3 w:embedBold+ Bold,+ /// §17.8.3.3 w:embedItalic+ Italic,+ /// §17.8.3.3 w:embedBoldItalic+ BoldItalic,+}diff --git a/crates/liteparse-docx/src/model/types/drawing.rs b/crates/liteparse-docx/src/model/types/drawing.rsnew file mode 100644index 0000000..108a092--- /dev/null+++ b/crates/liteparse-docx/src/model/types/drawing.rs@@ -0,0 +1,1513 @@+//! DrawingML types — images, pictures, shapes, anchoring, and preset geometry.++use crate::model::dimension::{Dimension, Emu, SixtieThousandthDeg, ThousandthPercent};+use crate::model::geometry::{EdgeInsets, Offset, Size};++use super::content::Block;+use super::drawing_color::DrawingColor;+use super::identifiers::RelId;++/// Format of an embedded image, detected from the OOXML relationship target path+/// (§M.1.1) with magic-byte fallback.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ImageFormat {+ Png,+ Jpeg,+ Gif,+ Bmp,+ Tiff,+ /// Windows Enhanced Metafile (MS-EMF).+ Emf,+ /// Windows Metafile (MS-WMF).+ Wmf,+ Svg,+ WebP,+ Unknown,+}++impl ImageFormat {+ /// Detect format from the relationship target file extension (OOXML §M.1.1)+ /// with magic-byte fallback for unrecognised or missing extensions.+ pub fn detect(target_path: &str, data: &[u8]) -> Self {+ let ext = target_path+ .rsplit('.')+ .next()+ .map(|e| e.to_ascii_lowercase());+ match ext.as_deref() {+ Some("png") => Self::Png,+ Some("jpg" | "jpeg") => Self::Jpeg,+ Some("gif") => Self::Gif,+ Some("bmp") => Self::Bmp,+ Some("tif" | "tiff") => Self::Tiff,+ Some("emf") => Self::Emf,+ Some("wmf") => Self::Wmf,+ Some("svg" | "svgz") => Self::Svg,+ Some("webp") => Self::WebP,+ _ => Self::detect_by_magic(data),+ }+ }++ /// Magic-byte detection for the most common raster formats.+ fn detect_by_magic(data: &[u8]) -> Self {+ // EMF (MS-EMF §2.3.4.2 ENHMETAHEADER): `iType` == 1 at offset 0 and the+ // `dSignature` value 0x464D4520 (" EMF", stored little-endian) at+ // offset 40 — *not* near the start, so it can't be expressed as a+ // leading slice pattern.+ if data.len() >= 44+ && data[0..4] == [0x01, 0x00, 0x00, 0x00]+ && data[40..44] == [0x20, 0x45, 0x4D, 0x46]+ {+ return Self::Emf;+ }+ match data {+ [0x89, b'P', b'N', b'G', ..] => Self::Png,+ [0xFF, 0xD8, 0xFF, ..] => Self::Jpeg,+ [b'G', b'I', b'F', b'8', ..] => Self::Gif,+ [b'B', b'M', ..] => Self::Bmp,+ // TIFF: little-endian "II*\0" or big-endian "MM\0*" (MS-TIFF).+ [0x49, 0x49, 0x2A, 0x00, ..] | [0x4D, 0x4D, 0x00, 0x2A, ..] => Self::Tiff,+ [+ b'R',+ b'I',+ b'F',+ b'F',+ _,+ _,+ _,+ _,+ b'W',+ b'E',+ b'B',+ b'P',+ ..,+ ] => Self::WebP,+ [b'<', ..] => Self::Svg,+ _ => Self::Unknown,+ }+ }+}++#[derive(Clone, Debug)]+pub struct Image {+ /// §20.4.2.7: drawing extent.+ pub extent: Size<Emu>,+ /// §20.4.2.6: additional extent for effects.+ pub effect_extent: Option<EdgeInsets<Emu>>,+ /// §20.1.2.2.8: non-visual drawing properties (wp:docPr).+ pub doc_properties: DocProperties,+ /// §20.4.2.4: graphic frame locking properties.+ pub graphic_frame_locks: Option<GraphicFrameLocks>,+ /// Graphic content from a:graphic > a:graphicData.+ pub graphic: Option<GraphicContent>,+ /// Inline or anchor placement.+ pub placement: ImagePlacement,+}++/// How the image is placed in the document flow.+#[derive(Clone, Debug)]+pub enum ImagePlacement {+ /// §20.4.2.8: inline with text — no wrapping.+ Inline {+ /// Distance from surrounding text.+ distance: EdgeInsets<Emu>,+ },+ /// §20.4.2.3: floating/anchored with text wrapping.+ Anchor(AnchorProperties),+}++/// §20.1.2.2.8 CT_NonVisualDrawingProps — shared by wp:docPr and pic:cNvPr.+#[derive(Clone, Debug)]+pub struct DocProperties {+ /// Unique identifier.+ pub id: u32,+ /// Element name.+ pub name: String,+ /// Alternative text description.+ pub description: Option<String>,+ /// Whether the element is hidden.+ pub hidden: Option<bool>,+ /// Title (Office 2010+).+ pub title: Option<String>,+}++/// §20.1.2.2.19 CT_GraphicalObjectFrameLocking.+#[derive(Clone, Copy, Debug)]+pub struct GraphicFrameLocks {+ pub no_change_aspect: Option<bool>,+ pub no_drilldown: Option<bool>,+ pub no_grp: Option<bool>,+ pub no_move: Option<bool>,+ pub no_resize: Option<bool>,+ pub no_select: Option<bool>,+}++/// Content type inside a:graphicData.+#[derive(Clone, Debug)]+pub enum GraphicContent {+ /// §19.3.1.37: picture.+ Picture(Picture),+ /// §14.5 wps:wsp: Word Processing Shape.+ WordProcessingShape(WordProcessingShape),+}++/// §14.5 wps:wsp — a Word Processing Shape.+/// Contains shape properties and optional text body.+#[derive(Clone, Debug)]+pub struct WordProcessingShape {+ /// §20.1.2.2.8: non-visual drawing properties.+ pub cnv_pr: Option<DocProperties>,+ /// §20.1.2.2.35: shape properties.+ pub shape_properties: Option<ShapeProperties>,+ /// §20.1.2.2.45 wps:style / §20.1.4.1.22 a:lnRef — reference to a theme+ /// line style. Attributes absent from the direct `<a:ln>` inherit from+ /// the referenced theme line style (e.g. width when `<a:ln>` omits `@w`).+ pub style_line_ref: Option<StyleMatrixRef>,+ /// §20.1.2.2.45 wps:style / §20.1.4.1.10 a:effectRef — reference to a+ /// theme effect style. Word treats a present-but-empty `<a:effectLst/>`+ /// on spPr as inheritance from this reference, so resolve consults it+ /// when the direct effect list is absent or empty.+ pub style_effect_ref: Option<StyleMatrixRef>,+ /// §20.1.2.2.45 wps:style / §20.1.4.1.13 a:fillRef — reference to a theme+ /// fill style. When the shape has no direct `spPr` fill, the referenced+ /// theme fill (recolored by the ref's `phClr`) supplies the fill.+ pub style_fill_ref: Option<StyleMatrixRef>,+ /// §20.1.2.2.45 wps:style / §20.1.4.1.17 a:fontRef — the shape's default+ /// text color and theme font collection for text inside `<wps:txbx>`.+ pub style_font_ref: Option<FontReference>,+ /// §20.1.2.1.1: body properties (text layout within the shape).+ pub body_pr: Option<BodyProperties>,+ /// §17.17.1: text content inside the shape.+ pub txbx_content: Vec<Block>,+}++/// §20.1.4.1.17 CT_FontReference — `wps:style/fontRef`: selects the theme font+/// collection (major/minor) and the shape's default text color.+#[derive(Clone, Debug)]+pub struct FontReference {+ pub collection: FontCollectionIndex,+ /// Default text color for the shape's text (often a scheme color such as+ /// `lt1` for light text on a dark fill). `None` leaves the normal cascade.+ pub color: Option<DrawingColor>,+}++/// §20.1.8.30 ST_FontCollectionIndex — which theme font collection a+/// `fontRef` selects.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FontCollectionIndex {+ Major,+ Minor,+ None,+}++/// §20.1.4.2.19 CT_StyleMatrixReference — a 1-based index into one of the+/// theme's style matrices (`fillStyleLst`, `lnStyleLst`, `effectStyleLst`,+/// `bgFillStyleLst`) paired with an optional color used to substitute+/// `phClr` placeholders within the referenced style.+#[derive(Clone, Debug)]+pub struct StyleMatrixRef {+ pub idx: u32,+ pub color: Option<DrawingColor>,+}++/// §20.1.2.1.1 CT_TextBodyProperties — text body properties inside a shape.+#[derive(Clone, Debug)]+pub struct BodyProperties {+ /// Rotation of the text body in 60,000ths of a degree.+ pub rotation: Option<Dimension<SixtieThousandthDeg>>,+ /// §20.1.10.82 ST_TextVerticalType: vertical text mode.+ pub vert: Option<TextVerticalType>,+ /// §20.1.10.85 ST_TextWrappingType: text wrapping within the shape.+ pub wrap: Option<TextWrappingType>,+ /// Left inset in EMU.+ pub left_inset: Option<Dimension<Emu>>,+ /// Top inset in EMU.+ pub top_inset: Option<Dimension<Emu>>,+ /// Right inset in EMU.+ pub right_inset: Option<Dimension<Emu>>,+ /// Bottom inset in EMU.+ pub bottom_inset: Option<Dimension<Emu>>,+ /// §20.1.10.59 ST_TextAnchoringType: vertical anchor.+ pub anchor: Option<TextAnchoringType>,+ /// `@vertOverflow` (ST_TextVertOverflowType): what becomes of a body taller+ /// than its box. `None` is the spec default, [`TextVertOverflow::Overflow`].+ pub vert_overflow: Option<TextVertOverflow>,+ /// Auto-fit mode.+ pub auto_fit: Option<TextAutoFit>,+}++/// `a:bodyPr/@vertOverflow` (ST_TextVertOverflowType) — what a text body does+/// with the part of itself that does not fit its box.+///+/// The default is [`Overflow`](TextVertOverflow::Overflow), and it is not a+/// degenerate case: Word really does draw shape text past the shape's bottom+/// edge, and it is what every `bodyPr` in the corpus asks for. Treating a body+/// that overflows as a bug to be clipped loses content that renders correctly.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum TextVertOverflow {+ /// Draw the whole body, past the box if need be. The spec default.+ #[default]+ Overflow,+ /// Draw only what fits inside the box.+ Clip,+ /// Clip, and mark the truncation with an ellipsis on the last visible line.+ Ellipsis,+}++/// §20.1.10.82 ST_TextVerticalType.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TextVerticalType {+ Horz,+ Vert,+ Vert270,+ WordArtVert,+ EaVert,+ MongolianVert,+ WordArtVertRtl,+}++/// §20.1.10.85 ST_TextWrappingType.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TextWrappingType {+ None,+ Square,+}++/// §20.1.10.59 ST_TextAnchoringType.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TextAnchoringType {+ Top,+ Center,+ Bottom,+ Justified,+ Distributed,+}++/// Text auto-fit mode for shape text bodies.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TextAutoFit {+ /// §20.1.2.1.16 `a:noAutofit`: no auto-fit.+ NoAutoFit,+ /// §20.1.2.1.18 `a:normAutofit`: shrink text to fit.+ NormalAutoFit(NormalAutoFit),+ /// §20.1.2.1.20 `a:spAutoFit`: resize the shape to fit its text.+ SpAutoFit,+}++/// §20.1.2.1.18 `a:normAutofit` — the shrink Word computed when it laid the+/// shape out, and wrote back into the file.+///+/// These attributes are the fit *itself*, not a hint. Word does not re-derive+/// them on open, so a consumer that keeps the element and drops its attributes+/// renders every shrunk body at full size — and then spills out of the box,+/// because `vertOverflow` defaults to `overflow`. That is why this is a struct+/// rather than a bare variant.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct NormalAutoFit {+ /// `@fontScale` — the percentage every font size in the body is multiplied+ /// by. Absent means 100%.+ pub font_scale: Option<Dimension<ThousandthPercent>>,+ /// `@lnSpcReduction` — the percentage subtracted from each paragraph's line+ /// spacing. Absent means 0%.+ pub line_spacing_reduction: Option<Dimension<ThousandthPercent>>,+}++/// §19.3.1.37 pic:pic — a picture element.+#[derive(Clone, Debug)]+pub struct Picture {+ /// §19.3.1.32: non-visual picture properties.+ pub nv_pic_pr: NvPicProperties,+ /// §20.1.8.14: blip fill (picture data + crop + fill mode).+ pub blip_fill: BlipFill,+ /// §20.1.2.2.35: shape properties (transform, geometry, outline).+ pub shape_properties: Option<ShapeProperties>,+}++/// §19.3.1.32 pic:nvPicPr — non-visual picture properties.+#[derive(Clone, Debug)]+pub struct NvPicProperties {+ /// §20.1.2.2.8 pic:cNvPr.+ pub cnv_pr: DocProperties,+ /// §19.3.1.4 pic:cNvPicPr.+ pub cnv_pic_pr: Option<CnvPicProperties>,+}++/// §19.3.1.4 pic:cNvPicPr — non-visual picture drawing properties.+#[derive(Clone, Debug)]+pub struct CnvPicProperties {+ pub prefer_relative_resize: Option<bool>,+ /// §20.1.2.2.31: picture locking.+ pub pic_locks: Option<PicLocks>,+}++/// §20.1.2.2.31 a:picLocks — picture locking constraints.+#[derive(Clone, Copy, Debug)]+pub struct PicLocks {+ pub no_change_aspect: Option<bool>,+ pub no_crop: Option<bool>,+ pub no_resize: Option<bool>,+ pub no_move: Option<bool>,+ pub no_rot: Option<bool>,+ pub no_select: Option<bool>,+ pub no_edit_points: Option<bool>,+ pub no_adjust_handles: Option<bool>,+ pub no_change_arrowheads: Option<bool>,+ pub no_change_shape_type: Option<bool>,+ pub no_grp: Option<bool>,+}++/// §20.1.8.14 CT_BlipFillProperties — image fill. Used both as a picture+/// content (via `Picture.blip_fill`) and as an `EG_FillProperties` choice+/// inside shape `spPr`/outline fills.+#[derive(Clone, Debug)]+pub struct BlipFill {+ pub rotate_with_shape: Option<bool>,+ pub dpi: Option<u32>,+ /// §20.1.8.13: blip reference.+ pub blip: Option<Blip>,+ /// §20.1.10.48: source rectangle (crop).+ pub src_rect: Option<RelativeRect>,+ /// §20.1.8.14 choice: stretch, tile, or neither.+ pub fill_kind: BlipFillKind,+}++/// §20.1.8.14 fill presentation — stretch into fillRect or tile.+///+/// Per spec the choice is optional; `Unspecified` is Word's default+/// (equivalent to `Stretch` with no `fillRect`).+#[derive(Clone, Debug)]+pub enum BlipFillKind {+ Stretch(StretchFill),+ Tile(TileFill),+ Unspecified,+}++/// §20.1.8.58 CT_TileInfoProperties — tiled blip fill parameters.+#[derive(Clone, Copy, Debug)]+pub struct TileFill {+ /// Translate X in EMU.+ pub tx: Option<Dimension<Emu>>,+ /// Translate Y in EMU.+ pub ty: Option<Dimension<Emu>>,+ /// Scale X (1000ths of a percent).+ pub sx: Option<Dimension<ThousandthPercent>>,+ /// Scale Y (1000ths of a percent).+ pub sy: Option<Dimension<ThousandthPercent>>,+ /// §20.1.10.86: tile flip mode.+ pub flip: Option<TileFlipMode>,+ /// §20.1.10.53: alignment of the tiled blip within the fill rect.+ pub alignment: Option<RectAlignment>,+}++/// §20.1.8.13 a:blip — reference to image data.+#[derive(Clone, Debug)]+pub struct Blip {+ /// r:embed — relationship ID for embedded image.+ pub embed: Option<RelId>,+ /// r:link — relationship ID for linked (external) image.+ pub link: Option<RelId>,+ /// §20.1.10.7: compression state.+ pub compression: Option<BlipCompression>,+}++/// §20.1.10.7 ST_BlipCompression.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum BlipCompression {+ Email,+ Hqprint,+ None,+ Print,+ Screen,+}++/// §20.1.10.48 CT_RelativeRect — relative rectangle (thousandths of percent).+/// Used for a:srcRect and a:fillRect.+#[derive(Clone, Copy, Debug)]+pub struct RelativeRect {+ pub left: Option<Dimension<ThousandthPercent>>,+ pub top: Option<Dimension<ThousandthPercent>>,+ pub right: Option<Dimension<ThousandthPercent>>,+ pub bottom: Option<Dimension<ThousandthPercent>>,+}++/// §20.1.8.56 a:stretch — stretch fill mode.+#[derive(Clone, Copy, Debug)]+pub struct StretchFill {+ /// §20.1.10.48: fill rectangle.+ pub fill_rect: Option<RelativeRect>,+}++/// §20.1.2.2.35 CT_ShapeProperties — shape visual properties.+#[derive(Clone, Debug)]+pub struct ShapeProperties {+ /// §20.1.10.10: black-and-white mode.+ pub bw_mode: Option<BlackWhiteMode>,+ /// §20.1.7.6: 2D transform.+ pub transform: Option<Transform2D>,+ /// §20.1.9.18 prstGeom or §20.1.9.8 custGeom — shape geometry.+ pub geometry: Option<ShapeGeometry>,+ /// Fill type (noFill, solidFill, etc.).+ pub fill: Option<DrawingFill>,+ /// §20.1.2.2.24: outline/line properties.+ pub outline: Option<Outline>,+ /// §20.1.8.24: shape effects, in document order.+ pub effect_list: Option<EffectList>,+}++/// §20.1.7.6 CT_Transform2D — 2D transform.+#[derive(Clone, Copy, Debug)]+pub struct Transform2D {+ /// Rotation in 60,000ths of a degree (§20.1.10.3).+ pub rotation: Option<Dimension<SixtieThousandthDeg>>,+ pub flip_h: Option<bool>,+ pub flip_v: Option<bool>,+ /// §20.1.7.4: offset (x, y).+ pub offset: Option<Offset<Emu>>,+ /// §20.1.7.3: extent (cx, cy).+ pub extent: Option<Size<Emu>>,+}++/// §20.1.9.18 CT_PresetGeometry2D — preset shape geometry.+#[derive(Clone, Debug)]+pub struct PresetGeometryDef {+ /// §20.1.10.56: preset shape type.+ pub preset: PresetShapeType,+ /// §20.1.9.5: adjustment values.+ pub adjust_values: Vec<GeomGuide>,+}++/// §20.1.9.11 CT_GeomGuide — geometry guide (named formula).+#[derive(Clone, Debug)]+pub struct GeomGuide {+ pub name: String,+ pub formula: String,+}++// ── §20.1.9.8 CT_CustomGeometry2D ──────────────────────────────────────────++/// §20.1.9.8 CT_CustomGeometry2D — user-defined shape geometry.+///+/// The coordinate system is defined by the `path` element's `w` and `h`+/// attributes. Guides in `av_list` are user-adjustable values (shipped with+/// the authored shape); guides in `gd_list` are computed from formulas+/// referencing other guides, `w`/`h`, and the spec's named constants.+#[derive(Clone, Debug, Default)]+pub struct CustomGeometry {+ /// §20.1.9.1 avLst — adjust-value list (user-editable guides).+ pub av_list: Vec<GeomGuide>,+ /// §20.1.9.10 gdLst — computed-guide list.+ pub gd_list: Vec<GeomGuide>,+ /// §20.1.9.1 ahLst — adjust-handle list.+ pub ah_list: Vec<AdjustHandle>,+ /// §20.1.9.7 cxnLst — connection sites.+ pub cxn_list: Vec<ConnectionSite>,+ /// §20.1.9.22 rect — text rectangle within the shape.+ pub rect: Option<TextRect>,+ /// §20.1.9.15 pathLst — the actual path(s).+ pub paths: Vec<PathDef>,+}++/// §20.1.9.15 CT_Path2D — one path in a custom geometry.+#[derive(Clone, Debug)]+pub struct PathDef {+ /// Path-local coordinate width in EMUs.+ pub w: Dimension<Emu>,+ /// Path-local coordinate height in EMUs.+ pub h: Dimension<Emu>,+ /// §20.1.10.45: path fill mode.+ pub fill: PathFillMode,+ /// §20.1.9.15 @stroke — whether the path is stroked.+ pub stroke: bool,+ /// §20.1.9.15 @extrusionOk — whether 3D extrusion is permitted.+ pub extrusion_ok: bool,+ /// Path verbs (moveTo/lnTo/cubicBezTo/quadBezTo/arcTo/close) in order.+ pub commands: Vec<PathCommand>,+}++/// §20.1.10.45 ST_PathFillMode.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub enum PathFillMode {+ /// No fill (`"none"`).+ None,+ /// Normal fill (`"norm"`). Default per spec.+ #[default]+ Norm,+ /// `"lighten"`.+ Lighten,+ /// `"lightenLess"`.+ LightenLess,+ /// `"darken"`.+ Darken,+ /// `"darkenLess"`.+ DarkenLess,+}++/// §20.1.9.14 / §20.1.9.2 / §20.1.9.19 / §20.1.9.3 / §20.1.9.4 — path verbs.+#[derive(Clone, Debug)]+pub enum PathCommand {+ /// §20.1.9.14 moveTo.+ MoveTo(AdjPoint),+ /// §20.1.9.13 lnTo.+ LineTo(AdjPoint),+ /// §20.1.9.2 cubicBezTo — three control points (two controls + endpoint).+ CubicBezTo(AdjPoint, AdjPoint, AdjPoint),+ /// §20.1.9.19 quadBezTo — two control points (control + endpoint).+ QuadBezTo(AdjPoint, AdjPoint),+ /// §20.1.9.3 arcTo — elliptical arc.+ ArcTo {+ /// Horizontal radius (any AdjCoord expression).+ wr: AdjCoord,+ /// Vertical radius.+ hr: AdjCoord,+ /// Start angle (any AdjAngle expression).+ start_angle: AdjAngle,+ /// Swing angle (arc sweep).+ swing_angle: AdjAngle,+ },+ /// §20.1.9.4 close — close the current subpath.+ Close,+}++/// §20.1.9.12 CT_AdjPoint2D — a point in path-local coordinates.+#[derive(Clone, Debug)]+pub struct AdjPoint {+ pub x: AdjCoord,+ pub y: AdjCoord,+}++/// Coordinate value: either a literal integer (EMU when positional, raw+/// integer for size attributes) or a guide-name reference that the evaluator+/// resolves via the enclosing `PathDef`/`CustomGeometry` guide scope.+#[derive(Clone, Debug, PartialEq)]+pub enum AdjCoord {+ Lit(i64),+ Guide(String),+}++/// §20.1.10.4 ST_AdjAngle — angle value (shares the `AdjCoord` shape).+pub type AdjAngle = AdjCoord;++/// §20.1.9.1 CT_AdjustHandleList — each entry may be XY or polar. For Tier 0+/// we capture the raw structure (positions + guide references); evaluators+/// can derive concrete handle positions from the enclosing geometry.+#[derive(Clone, Debug)]+pub enum AdjustHandle {+ /// §20.1.9.1.1 ahXY.+ XY {+ guide_ref_x: Option<String>,+ guide_ref_y: Option<String>,+ min_x: Option<AdjCoord>,+ max_x: Option<AdjCoord>,+ min_y: Option<AdjCoord>,+ max_y: Option<AdjCoord>,+ position: AdjPoint,+ },+ /// §20.1.9.1.2 ahPolar.+ Polar {+ guide_ref_r: Option<String>,+ guide_ref_ang: Option<String>,+ min_r: Option<AdjCoord>,+ max_r: Option<AdjCoord>,+ min_ang: Option<AdjAngle>,+ max_ang: Option<AdjAngle>,+ position: AdjPoint,+ },+}++/// §20.1.9.7 CT_ConnectionSite — attachment point on a shape boundary.+#[derive(Clone, Debug)]+pub struct ConnectionSite {+ /// §20.1.9.7 @ang — angle of the connection site (any AdjAngle expression).+ pub angle: AdjAngle,+ pub position: AdjPoint,+}++/// §20.1.9.22 CT_GeomRect — text bounds within a shape, as AdjCoord.+#[derive(Clone, Debug)]+pub struct TextRect {+ pub left: AdjCoord,+ pub top: AdjCoord,+ pub right: AdjCoord,+ pub bottom: AdjCoord,+}++/// The unified geometry reference for a shape — either a preset or fully+/// custom. Populated by `parse_shape_properties` from either `<a:prstGeom>`+/// or `<a:custGeom>`.+#[derive(Clone, Debug)]+pub enum ShapeGeometry {+ Preset(PresetGeometryDef),+ Custom(CustomGeometry),+}++/// §20.1.10.56 ST_ShapeType — preset shape types (subset).+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum PresetShapeType {+ Rect,+ RoundRect,+ Ellipse,+ Triangle,+ RtTriangle,+ Diamond,+ Parallelogram,+ Trapezoid,+ Pentagon,+ Hexagon,+ Octagon,+ Star4,+ Star5,+ Star6,+ Star8,+ Star10,+ Star12,+ Star16,+ Star24,+ Star32,+ Line,+ Plus,+ Can,+ Cube,+ Donut,+ NoSmoking,+ BlockArc,+ Heart,+ Sun,+ Moon,+ SmileyFace,+ LightningBolt,+ Cloud,+ Arc,+ Plaque,+ Frame,+ Bevel,+ FoldedCorner,+ Chevron,+ HomePlate,+ Ribbon,+ Ribbon2,+ Pie,+ PieWedge,+ Chord,+ Teardrop,+ Arrow,+ LeftArrow,+ RightArrow,+ UpArrow,+ DownArrow,+ LeftRightArrow,+ UpDownArrow,+ QuadArrow,+ BentArrow,+ UturnArrow,+ CircularArrow,+ CurvedRightArrow,+ CurvedLeftArrow,+ CurvedUpArrow,+ CurvedDownArrow,+ StripedRightArrow,+ NotchedRightArrow,+ BentUpArrow,+ LeftUpArrow,+ LeftRightUpArrow,+ LeftArrowCallout,+ RightArrowCallout,+ UpArrowCallout,+ DownArrowCallout,+ LeftRightArrowCallout,+ UpDownArrowCallout,+ QuadArrowCallout,+ SwooshArrow,+ LeftCircularArrow,+ LeftRightCircularArrow,+ Callout1,+ Callout2,+ Callout3,+ AccentCallout1,+ AccentCallout2,+ AccentCallout3,+ BorderCallout1,+ BorderCallout2,+ BorderCallout3,+ AccentBorderCallout1,+ AccentBorderCallout2,+ AccentBorderCallout3,+ WedgeRectCallout,+ WedgeRoundRectCallout,+ WedgeEllipseCallout,+ CloudCallout,+ LeftBracket,+ RightBracket,+ LeftBrace,+ RightBrace,+ BracketPair,+ BracePair,+ StraightConnector1,+ BentConnector2,+ BentConnector3,+ BentConnector4,+ BentConnector5,+ CurvedConnector2,+ CurvedConnector3,+ CurvedConnector4,+ CurvedConnector5,+ FlowChartProcess,+ FlowChartDecision,+ FlowChartInputOutput,+ FlowChartPredefinedProcess,+ FlowChartInternalStorage,+ FlowChartDocument,+ FlowChartMultidocument,+ FlowChartTerminator,+ FlowChartPreparation,+ FlowChartManualInput,+ FlowChartManualOperation,+ FlowChartConnector,+ FlowChartPunchedCard,+ FlowChartPunchedTape,+ FlowChartSummingJunction,+ FlowChartOr,+ FlowChartCollate,+ FlowChartSort,+ FlowChartExtract,+ FlowChartMerge,+ FlowChartOfflineStorage,+ FlowChartOnlineStorage,+ FlowChartMagneticTape,+ FlowChartMagneticDisk,+ FlowChartMagneticDrum,+ FlowChartDisplay,+ FlowChartDelay,+ FlowChartAlternateProcess,+ FlowChartOffpageConnector,+ ActionButtonBlank,+ ActionButtonHome,+ ActionButtonHelp,+ ActionButtonInformation,+ ActionButtonForwardNext,+ ActionButtonBackPrevious,+ ActionButtonEnd,+ ActionButtonBeginning,+ ActionButtonReturn,+ ActionButtonDocument,+ ActionButtonSound,+ ActionButtonMovie,+ IrregularSeal1,+ IrregularSeal2,+ Wave,+ DoubleWave,+ EllipseRibbon,+ EllipseRibbon2,+ VerticalScroll,+ HorizontalScroll,+ LeftRightRibbon,+ Gear6,+ Gear9,+ Funnel,+ MathPlus,+ MathMinus,+ MathMultiply,+ MathDivide,+ MathEqual,+ MathNotEqual,+ CornerTabs,+ SquareTabs,+ PlaqueTabs,+ ChartX,+ ChartStar,+ ChartPlus,+ HalfFrame,+ Corner,+ DiagStripe,+ NonIsoscelesTrapezoid,+ Heptagon,+ Decagon,+ Dodecagon,+ Round1Rect,+ Round2SameRect,+ Round2DiagRect,+ SnipRoundRect,+ Snip1Rect,+ Snip2SameRect,+ Snip2DiagRect,+ /// Unrecognized shape type — preserved as raw string.+ Other(String),+}++/// §20.1.10.10 ST_BlackWhiteMode.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum BlackWhiteMode {+ Auto,+ Black,+ BlackGray,+ BlackWhite,+ Clr,+ Gray,+ GrayWhite,+ Hidden,+ InvGray,+ LtGray,+ White,+}++/// §20.1.8 EG_FillProperties — fill choice for shapes, outlines, overlays.+///+/// Every base fill carries its own structure; pattern of use is+/// `match fill { DrawingFill::Solid(color) => …, … }`.+#[derive(Clone, Debug)]+pub enum DrawingFill {+ /// §20.1.8.44 noFill — transparent.+ None,+ /// §20.1.8.54 solidFill — single color.+ Solid(DrawingColor),+ /// §20.1.8.33 gradFill — gradient with stops and a shade shape.+ Gradient(GradientFill),+ /// §20.1.8.14 blipFill — image fill.+ Blip(BlipFill),+ /// §20.1.8.47 pattFill — preset pattern with fg/bg colors.+ Pattern(PatternFill),+ /// §20.1.8.35 grpFill — inherit fill from the enclosing group.+ Group,+}++/// §20.1.8.33 CT_GradientFillProperties.+#[derive(Clone, Debug)]+pub struct GradientFill {+ /// §20.1.8.37 gsLst — gradient stops, in document order.+ pub stops: Vec<GradientStop>,+ /// The gradient shape: linear at an angle, or a path-based (radial etc.).+ pub shade_properties: GradientShadeProperties,+ /// §20.1.10.86 @flip — tile flip mode.+ pub flip: Option<TileFlipMode>,+ /// §20.1.8.33 @rotWithShape — rotate with the containing shape.+ pub rot_with_shape: Option<bool>,+ /// §20.1.8.56 tileRect — source rect within the gradient's conceptual area.+ pub tile_rect: Option<RelativeRect>,+}++/// §20.1.8.38 CT_GradientStop.+#[derive(Clone, Debug)]+pub struct GradientStop {+ /// §20.1.10.42 @pos — stop position in 1000ths of a percent [0, 100000].+ pub position: Dimension<ThousandthPercent>,+ pub color: DrawingColor,+}++/// §20.1.8.33 EG_ShadeProperties — the gradient's geometric shape.+#[derive(Clone, Debug)]+pub enum GradientShadeProperties {+ /// §20.1.8.41 lin — linear gradient at `angle`.+ Linear {+ /// Angle in 60000ths of a degree.+ angle: Dimension<SixtieThousandthDeg>,+ /// §20.1.8.41 @scaled — scale gradient with shape.+ scaled: Option<bool>,+ },+ /// §20.1.8.46 path — radial / shape / rect gradient.+ Path {+ path_type: PathShadeType,+ fill_to_rect: Option<RelativeRect>,+ },+}++/// §20.1.10.46 ST_PathShadeType.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PathShadeType {+ Shape,+ Circle,+ Rect,+}++/// §20.1.10.86 ST_TileFlipMode.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum TileFlipMode {+ None,+ X,+ Y,+ Xy,+}++/// §20.1.8.47 CT_PatternFillProperties.+#[derive(Clone, Debug)]+pub struct PatternFill {+ /// §20.1.10.50 @prst — preset pattern. Optional per spec; `None` when the+ /// `<a:pattFill>` omits `@prst` (an unspecified pattern).+ pub preset: Option<PresetPatternVal>,+ /// §20.1.8.30 fgClr — foreground color.+ pub fg_color: Option<DrawingColor>,+ /// §20.1.8.10 bgClr — background color.+ pub bg_color: Option<DrawingColor>,+}++/// §20.1.10.50 ST_PresetPatternVal — 48 preset pattern names.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PresetPatternVal {+ Pct5,+ Pct10,+ Pct20,+ Pct25,+ Pct30,+ Pct40,+ Pct50,+ Pct60,+ Pct70,+ Pct75,+ Pct80,+ Pct90,+ Horz,+ Vert,+ LtHorz,+ LtVert,+ DkHorz,+ DkVert,+ NarHorz,+ NarVert,+ DashHorz,+ DashVert,+ Cross,+ DnDiag,+ UpDiag,+ LtDnDiag,+ LtUpDiag,+ DkDnDiag,+ DkUpDiag,+ WdDnDiag,+ WdUpDiag,+ DashDnDiag,+ DashUpDiag,+ DiagCross,+ SmCheck,+ LgCheck,+ SmGrid,+ LgGrid,+ DotGrid,+ SmConfetti,+ LgConfetti,+ HorzBrick,+ DiagBrick,+ SolidDmnd,+ OpenDmnd,+ DotDmnd,+ Plaid,+ Sphere,+ Weave,+ DivotShingle,+ Trellis,+ ZigZag,+ Wave,+}++/// §20.1.10.53 ST_RectAlignment — nine-point rect alignment grid.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum RectAlignment {+ Tl,+ T,+ Tr,+ L,+ Ctr,+ R,+ Bl,+ B,+ Br,+}++/// §20.1.2.2.24 CT_LineProperties — full shape outline specification.+#[derive(Clone, Debug)]+pub struct Outline {+ /// §20.1.2.2.24 @w — line width in EMUs.+ pub width: Option<Dimension<Emu>>,+ /// §20.1.10.31: line cap style.+ pub cap: Option<LineCap>,+ /// §20.1.10.15: compound line type.+ pub compound: Option<CompoundLine>,+ /// §20.1.10.39: pen alignment.+ pub alignment: Option<PenAlignment>,+ /// §20.1.2.2.24 EG_LineFillProperties — outlines use any fill choice.+ pub fill: Option<DrawingFill>,+ /// §20.1.8.25: preset or custom dash pattern.+ pub dash: Option<LineDash>,+ /// §20.1.2.2.22: line join style.+ pub join: Option<LineJoin>,+ /// §20.1.2.2.12 headEnd — arrow at the line's head (start).+ pub head_end: Option<LineEnd>,+ /// §20.1.2.2.46 tailEnd — arrow at the line's tail (end).+ pub tail_end: Option<LineEnd>,+}++/// §20.1.8.25 CT_LineDashProperties — preset pattern or custom stop list.+#[derive(Clone, Debug)]+pub enum LineDash {+ /// §20.1.10.48: named preset pattern.+ Preset(PresetLineDashVal),+ /// §20.1.8.26 custDash — sequence of dash/space pairs.+ Custom(Vec<DashStop>),+}++/// §20.1.10.48 ST_PresetLineDashVal.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PresetLineDashVal {+ Solid,+ Dot,+ Dash,+ LgDash,+ DashDot,+ LgDashDot,+ LgDashDotDot,+ SysDash,+ SysDot,+ SysDashDot,+ SysDashDotDot,+}++/// §20.1.8.27 CT_DashStop — one dash/space pair in a custom dash pattern.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct DashStop {+ pub dash: Dimension<ThousandthPercent>,+ pub space: Dimension<ThousandthPercent>,+}++/// §20.1.2.2.22 EG_LineJoinProperties — line join style.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum LineJoin {+ /// §20.1.8.42 round.+ Round,+ /// §20.1.8.9 bevel.+ Bevel,+ /// §20.1.8.43 miter with optional limit (1000ths of a percent).+ Miter {+ limit: Option<Dimension<ThousandthPercent>>,+ },+}++/// §20.1.2.2.12 / §20.1.2.2.46 CT_LineEndProperties — arrow head / tail.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct LineEnd {+ pub kind: LineEndType,+ pub width: LineEndSize,+ pub length: LineEndSize,+}++/// §20.1.10.33 ST_LineEndType.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum LineEndType {+ None,+ Triangle,+ Stealth,+ Diamond,+ Oval,+ Arrow,+}++/// §20.1.10.34 ST_LineEndWidth / §20.1.10.35 ST_LineEndLength (shared enum).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum LineEndSize {+ Sm,+ Med,+ Lg,+}++/// §20.1.10.31 ST_LineCap.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LineCap {+ Flat,+ Round,+ Square,+}++/// §20.1.10.15 ST_CompoundLine.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CompoundLine {+ Single,+ Double,+ ThickThin,+ ThinThick,+ Triple,+}++/// §20.1.10.39 ST_PenAlignment.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PenAlignment {+ Center,+ Inset,+}++/// §20.4.2.3 CT_Anchor — anchor/floating drawing properties.+#[derive(Clone, Debug)]+pub struct AnchorProperties {+ /// §20.4.2.3: distance from surrounding text.+ pub distance: EdgeInsets<Emu>,+ /// §20.4.2.13: simple positioning point.+ pub simple_pos: Option<Offset<Emu>>,+ /// §20.4.2.3 @simplePos: whether to use simplePos coordinates.+ pub use_simple_pos: Option<bool>,+ /// §20.4.2.10: horizontal position.+ pub horizontal_position: AnchorPosition,+ /// §20.4.2.11: vertical position.+ pub vertical_position: AnchorPosition,+ /// Text wrapping mode.+ pub wrap: TextWrap,+ /// §20.4.2.3 @behindDoc: behind document text.+ pub behind_text: bool,+ /// §20.4.2.3 @locked: anchor is locked to position.+ pub lock_anchor: bool,+ /// §20.4.2.3 @allowOverlap: can overlap other anchored objects.+ pub allow_overlap: bool,+ /// §20.4.2.3 @relativeHeight: z-ordering value.+ pub relative_height: u32,+ /// §20.4.2.3 @layoutInCell: allow layout inside table cell.+ pub layout_in_cell: Option<bool>,+ /// §20.4.2.3 @hidden: whether the anchor is hidden.+ pub hidden: Option<bool>,+}++/// §20.4.2.10 / §20.4.2.11: anchor position (offset or alignment).+#[derive(Clone, Copy, Debug)]+pub enum AnchorPosition {+ /// §20.4.2.12: position by EMU offset from relativeFrom.+ Offset {+ relative_from: AnchorRelativeFrom,+ offset: Dimension<Emu>,+ },+ /// §20.4.2.1: position by alignment within relativeFrom.+ Align {+ relative_from: AnchorRelativeFrom,+ alignment: AnchorAlignment,+ },+}++/// §20.4.3.4 ST_RelFromH / §20.4.3.5 ST_RelFromV — relative-from values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AnchorRelativeFrom {+ Page,+ Margin,+ Column,+ Character,+ Paragraph,+ Line,+ InsideMargin,+ OutsideMargin,+ TopMargin,+ BottomMargin,+ LeftMargin,+ RightMargin,+}++/// §20.4.3.1 ST_AlignH / §20.4.3.2 ST_AlignV — alignment values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AnchorAlignment {+ Left,+ Center,+ Right,+ Inside,+ Outside,+ Top,+ Bottom,+}++/// Text wrapping mode for anchored drawings.+#[derive(Clone, Debug)]+pub enum TextWrap {+ /// §20.4.2.15: no wrapping.+ None,+ /// §20.4.2.17: square wrapping.+ Square {+ distance: EdgeInsets<Emu>,+ wrap_text: WrapText,+ },+ /// §20.4.2.16: tight wrapping around the shape's polygon outline.+ /// `polygon` is optional: malformed documents may omit it and are+ /// treated as square-wrap approximations at layout time.+ Tight {+ distance: EdgeInsets<Emu>,+ wrap_text: WrapText,+ polygon: Option<WrapPolygon>,+ },+ /// §20.4.2.18: text above and below only.+ TopAndBottom {+ distance_top: Dimension<Emu>,+ distance_bottom: Dimension<Emu>,+ },+ /// §20.4.2.14: through wrapping — text flows through polygon interior.+ Through {+ distance: EdgeInsets<Emu>,+ wrap_text: WrapText,+ polygon: Option<WrapPolygon>,+ },+}++/// §20.4.2.10 CT_WrapPath — the polygon outline used by `wrapTight` and+/// `wrapThrough`. `start` is the initial moveTo; `line_to` is the sequence+/// of subsequent edge endpoints; the polygon is implicitly closed back to+/// `start` (§20.4.2.10 spec note).+#[derive(Clone, Debug)]+pub struct WrapPolygon {+ /// @edited — whether the polygon has been hand-edited. Default false.+ pub edited: Option<bool>,+ /// §20.4.2.13 wp:start — first point (shape-local EMU coords).+ pub start: Offset<Emu>,+ /// §20.4.2.11 wp:lineTo — edge sequence after `start`. The spec+ /// requires at least two lineTo entries (polygon must have ≥3 points+ /// total when closed); malformed shorter inputs are accepted but will+ /// be skipped at layout time.+ pub line_to: Vec<Offset<Emu>>,+}++/// §20.4.3.7 ST_WrapText — which sides text wraps on.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum WrapText {+ BothSides,+ Left,+ Right,+ Largest,+}++// ── §20.1.8.24 CT_EffectList — shape effects ─────────────────────────────────++/// §20.1.8.24 CT_EffectList — an ordered sequence of shape effects.+///+/// Each variant is applied in order. The spec also defines §20.1.8.25+/// CT_EffectContainer (`effectDag`) for arbitrary compositing; our parser+/// accepts only `effectLst` and logs-and-skips `effectDag` for Tier 0.+#[derive(Clone, Debug, Default)]+pub struct EffectList {+ pub effects: Vec<Effect>,+}++/// §20.1.8 — effect variants.+#[derive(Clone, Debug)]+pub enum Effect {+ /// §20.1.8.15.+ Blur(BlurEffect),+ /// §20.1.8.29.+ FillOverlay(FillOverlayEffect),+ /// §20.1.8.32.+ Glow(GlowEffect),+ /// §20.1.8.40.+ InnerShdw(InnerShadowEffect),+ /// §20.1.8.45.+ OuterShdw(OuterShadowEffect),+ /// §20.1.8.49.+ PrstShdw(PresetShadowEffect),+ /// §20.1.8.50.+ Reflection(ReflectionEffect),+ /// §20.1.8.53.+ SoftEdge(SoftEdgeEffect),+}++/// §20.1.8.15 CT_BlurEffect.+#[derive(Clone, Copy, Debug)]+pub struct BlurEffect {+ pub radius: Dimension<Emu>,+ pub grow: Option<bool>,+}++/// §20.1.8.29 CT_FillOverlayEffect.+#[derive(Clone, Debug)]+pub struct FillOverlayEffect {+ pub fill: DrawingFill,+ pub blend: BlendMode,+}++/// §20.1.8.32 CT_GlowEffect.+#[derive(Clone, Debug)]+pub struct GlowEffect {+ pub radius: Dimension<Emu>,+ pub color: DrawingColor,+}++/// §20.1.8.40 CT_InnerShadowEffect.+#[derive(Clone, Debug)]+pub struct InnerShadowEffect {+ pub blur_radius: Dimension<Emu>,+ pub distance: Dimension<Emu>,+ pub direction: Dimension<SixtieThousandthDeg>,+ pub color: DrawingColor,+}++/// §20.1.8.45 CT_OuterShadowEffect.+///+/// `sx/sy` are horizontal/vertical scale factors (1000ths of a percent);+/// `kx/ky` are skew angles (60000ths of a degree). All default to their+/// parent attribute defaults when absent.+#[derive(Clone, Debug)]+pub struct OuterShadowEffect {+ pub blur_radius: Dimension<Emu>,+ pub distance: Dimension<Emu>,+ pub direction: Dimension<SixtieThousandthDeg>,+ pub sx: Dimension<ThousandthPercent>,+ pub sy: Dimension<ThousandthPercent>,+ pub kx: Dimension<SixtieThousandthDeg>,+ pub ky: Dimension<SixtieThousandthDeg>,+ pub alignment: RectAlignment,+ pub rot_with_shape: Option<bool>,+ pub color: DrawingColor,+}++/// §20.1.8.49 CT_PresetShadowEffect.+#[derive(Clone, Debug)]+pub struct PresetShadowEffect {+ pub preset: PresetShadowVal,+ pub distance: Dimension<Emu>,+ pub direction: Dimension<SixtieThousandthDeg>,+ pub color: DrawingColor,+}++/// §20.1.10.51 ST_PresetShadowVal — 20 shadow presets.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PresetShadowVal {+ Shdw1,+ Shdw2,+ Shdw3,+ Shdw4,+ Shdw5,+ Shdw6,+ Shdw7,+ Shdw8,+ Shdw9,+ Shdw10,+ Shdw11,+ Shdw12,+ Shdw13,+ Shdw14,+ Shdw15,+ Shdw16,+ Shdw17,+ Shdw18,+ Shdw19,+ Shdw20,+}++/// §20.1.8.50 CT_ReflectionEffect.+#[derive(Clone, Copy, Debug)]+pub struct ReflectionEffect {+ pub blur_radius: Dimension<Emu>,+ pub start_alpha: Dimension<ThousandthPercent>,+ pub start_pos: Dimension<ThousandthPercent>,+ pub end_alpha: Dimension<ThousandthPercent>,+ pub end_pos: Dimension<ThousandthPercent>,+ pub distance: Dimension<Emu>,+ pub direction: Dimension<SixtieThousandthDeg>,+ pub fade_direction: Dimension<SixtieThousandthDeg>,+ pub sx: Dimension<ThousandthPercent>,+ pub sy: Dimension<ThousandthPercent>,+ pub kx: Dimension<SixtieThousandthDeg>,+ pub ky: Dimension<SixtieThousandthDeg>,+ pub alignment: RectAlignment,+ pub rot_with_shape: Option<bool>,+}++/// §20.1.8.53 CT_SoftEdgesEffect.+#[derive(Clone, Copy, Debug)]+pub struct SoftEdgeEffect {+ pub radius: Dimension<Emu>,+}++/// §20.1.10.11 ST_BlendMode.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum BlendMode {+ Over,+ Mult,+ Screen,+ Darken,+ Lighten,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn detect_by_extension_case_insensitive() {+ // §M.1.1: extension wins when recognised.+ assert_eq!(+ ImageFormat::detect("media/image1.png", &[]),+ ImageFormat::Png+ );+ assert_eq!(ImageFormat::detect("a.JPG", &[]), ImageFormat::Jpeg);+ assert_eq!(ImageFormat::detect("a.jpeg", &[]), ImageFormat::Jpeg);+ assert_eq!(ImageFormat::detect("a.GIF", &[]), ImageFormat::Gif);+ assert_eq!(ImageFormat::detect("a.tif", &[]), ImageFormat::Tiff);+ assert_eq!(ImageFormat::detect("a.tiff", &[]), ImageFormat::Tiff);+ assert_eq!(ImageFormat::detect("a.emf", &[]), ImageFormat::Emf);+ assert_eq!(ImageFormat::detect("a.wmf", &[]), ImageFormat::Wmf);+ assert_eq!(ImageFormat::detect("a.svg", &[]), ImageFormat::Svg);+ assert_eq!(ImageFormat::detect("a.svgz", &[]), ImageFormat::Svg);+ assert_eq!(ImageFormat::detect("a.webp", &[]), ImageFormat::WebP);+ }++ #[test]+ fn extension_takes_precedence_over_contradicting_bytes() {+ // A `.png` target with JPEG bytes is still reported as PNG (the OOXML+ // relationship target is authoritative).+ let jpeg = [0xFF, 0xD8, 0xFF, 0xE0];+ assert_eq!(ImageFormat::detect("a.png", &jpeg), ImageFormat::Png);+ }++ #[test]+ fn unknown_extension_falls_back_to_magic() {+ let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];+ assert_eq!(ImageFormat::detect("a.dat", &png), ImageFormat::Png);+ // No extension at all also routes through magic.+ assert_eq!(ImageFormat::detect("blob", &png), ImageFormat::Png);+ }++ #[test]+ fn magic_raster_signatures() {+ assert_eq!(+ ImageFormat::detect_by_magic(&[0x89, b'P', b'N', b'G', 0x0D]),+ ImageFormat::Png+ );+ assert_eq!(+ ImageFormat::detect_by_magic(&[0xFF, 0xD8, 0xFF, 0xE0]),+ ImageFormat::Jpeg+ );+ assert_eq!(ImageFormat::detect_by_magic(b"GIF89a"), ImageFormat::Gif);+ assert_eq!(ImageFormat::detect_by_magic(b"BM___"), ImageFormat::Bmp);+ }++ #[test]+ fn magic_tiff_both_byte_orders() {+ assert_eq!(+ ImageFormat::detect_by_magic(&[0x49, 0x49, 0x2A, 0x00]),+ ImageFormat::Tiff+ );+ assert_eq!(+ ImageFormat::detect_by_magic(&[0x4D, 0x4D, 0x00, 0x2A]),+ ImageFormat::Tiff+ );+ }++ #[test]+ fn magic_webp_riff_container() {+ assert_eq!(+ ImageFormat::detect_by_magic(b"RIFF\0\0\0\0WEBPVP8 "),+ ImageFormat::WebP+ );+ }++ #[test]+ fn magic_emf_signature_at_offset_40() {+ // ENHMETAHEADER: iType=1 at 0, " EMF" at offset 40.+ let mut emf = vec![0u8; 44];+ emf[0] = 0x01;+ emf[40..44].copy_from_slice(&[0x20, 0x45, 0x4D, 0x46]);+ assert_eq!(ImageFormat::detect_by_magic(&emf), ImageFormat::Emf);+ // The signature bytes appearing at the wrong (old) offset 8 must NOT+ // be mistaken for EMF.+ let mut not_emf = vec![0u8; 44];+ not_emf[0] = 0x01;+ not_emf[8..12].copy_from_slice(&[0x20, 0x45, 0x4D, 0x46]);+ assert_ne!(ImageFormat::detect_by_magic(¬_emf), ImageFormat::Emf);+ }++ #[test]+ fn magic_svg_and_unknown() {+ assert_eq!(+ ImageFormat::detect_by_magic(b"<svg xmlns"),+ ImageFormat::Svg+ );+ assert_eq!(+ ImageFormat::detect_by_magic(&[0x00, 0x01, 0x02]),+ ImageFormat::Unknown+ );+ assert_eq!(ImageFormat::detect_by_magic(&[]), ImageFormat::Unknown);+ }+}diff --git a/crates/liteparse-docx/src/model/types/drawing_color.rs b/crates/liteparse-docx/src/model/types/drawing_color.rsnew file mode 100644index 0000000..2628136--- /dev/null+++ b/crates/liteparse-docx/src/model/types/drawing_color.rs@@ -0,0 +1,658 @@+//! DrawingML color model (§20.1.2.3 EG_ColorChoice).+//!+//! The `DrawingColor` ADT models the six base color representations defined+//! by the spec, each followed by an ordered list of color transforms. All+//! values are stored in their spec-defined units (percent in 1000ths, angle+//! in 60000ths of a degree) — no normalization at parse time.++use crate::model::dimension::{Dimension, SixtieThousandthDeg, ThousandthPercent};++// ── EG_ColorChoice (§20.1.2.3) ──────────────────────────────────────────────++/// A DrawingML color specification.+#[derive(Clone, Debug, PartialEq)]+pub enum DrawingColor {+ /// §20.1.2.3.30 CT_ScRgbColor — linear RGB as percentages.+ ScRgb {+ r: Dimension<ThousandthPercent>,+ g: Dimension<ThousandthPercent>,+ b: Dimension<ThousandthPercent>,+ transforms: Vec<ColorTransform>,+ },+ /// §20.1.2.3.32 CT_SRgbColor — sRGB 6-hex-digit value (`val="RRGGBB"`).+ Srgb {+ rgb: u32,+ transforms: Vec<ColorTransform>,+ },+ /// §20.1.2.3.14 CT_HslColor.+ Hsl {+ hue: Dimension<SixtieThousandthDeg>,+ sat: Dimension<ThousandthPercent>,+ lum: Dimension<ThousandthPercent>,+ transforms: Vec<ColorTransform>,+ },+ /// §20.1.2.3.33 CT_SystemColor — OS color with cached RGB.+ Sys {+ name: SystemColorVal,+ last_clr: Option<u32>,+ transforms: Vec<ColorTransform>,+ },+ /// §20.1.2.3.29 CT_SchemeColor — theme color reference.+ Scheme {+ name: SchemeColorVal,+ transforms: Vec<ColorTransform>,+ },+ /// §20.1.2.3.22 CT_PresetColor — named color from the preset palette.+ Prst {+ name: PresetColorVal,+ transforms: Vec<ColorTransform>,+ },+}++impl DrawingColor {+ /// Returns the transform list for any variant.+ pub fn transforms(&self) -> &[ColorTransform] {+ match self {+ Self::ScRgb { transforms, .. }+ | Self::Srgb { transforms, .. }+ | Self::Hsl { transforms, .. }+ | Self::Sys { transforms, .. }+ | Self::Scheme { transforms, .. }+ | Self::Prst { transforms, .. } => transforms,+ }+ }+}++// ── Color transforms (§20.1.2.3.*) ──────────────────────────────────────────++/// A single color-transform child of a color-choice element.+///+/// Transforms apply in document order. Each variant carries the spec's value+/// type and range exactly; clamping/conversion is the resolver's job.+#[derive(Clone, Debug, PartialEq)]+pub enum ColorTransform {+ // Intensity / lightness+ /// §20.1.2.3.34 tint — lighten toward white by `val` ∈ [0, 100%].+ Tint(Dimension<ThousandthPercent>),+ /// §20.1.2.3.31 shade — darken toward black by `val` ∈ [0, 100%].+ Shade(Dimension<ThousandthPercent>),+ /// §20.1.2.3.7 comp — complementary (180° hue rotation).+ Comp,+ /// §20.1.2.3.17 inv — RGB channel inversion.+ Inv,+ /// §20.1.2.3.8 gray — luminance-preserving desaturation.+ Gray,+ /// §20.1.2.3.9 gamma — sRGB → linear gamma correction.+ Gamma,+ /// §20.1.2.3.18 invGamma — linear → sRGB gamma correction.+ InvGamma,++ // Alpha+ /// §20.1.2.3.1 alpha — absolute alpha, `val` ∈ [0, 100%].+ Alpha(Dimension<ThousandthPercent>),+ /// §20.1.2.3.3 alphaOff — alpha offset, `val` ∈ [-100%, 100%].+ AlphaOff(Dimension<ThousandthPercent>),+ /// §20.1.2.3.2 alphaMod — alpha multiplier, `val` ∈ [0, ∞).+ AlphaMod(Dimension<ThousandthPercent>),++ // Hue / Saturation / Luminance (HSL space)+ /// §20.1.2.3.15 hue — absolute hue, `val` ∈ [0, 360°).+ Hue(Dimension<SixtieThousandthDeg>),+ /// §20.1.2.3.16 hueOff — hue offset (any angle).+ HueOff(Dimension<SixtieThousandthDeg>),+ /// §20.1.2.3.14 hueMod — hue multiplier, `val` ∈ [0, ∞).+ HueMod(Dimension<ThousandthPercent>),+ /// §20.1.2.3.26 sat — absolute saturation.+ Sat(Dimension<ThousandthPercent>),+ /// §20.1.2.3.27 satOff — saturation offset.+ SatOff(Dimension<ThousandthPercent>),+ /// §20.1.2.3.28 satMod — saturation multiplier.+ SatMod(Dimension<ThousandthPercent>),+ /// §20.1.2.3.19 lum — absolute luminance.+ Lum(Dimension<ThousandthPercent>),+ /// §20.1.2.3.20 lumOff — luminance offset.+ LumOff(Dimension<ThousandthPercent>),+ /// §20.1.2.3.21 lumMod — luminance multiplier.+ LumMod(Dimension<ThousandthPercent>),++ // Per-channel (RGB space)+ /// §20.1.2.3.23 red — absolute red channel.+ Red(Dimension<ThousandthPercent>),+ /// §20.1.2.3.24 redOff — red offset.+ RedOff(Dimension<ThousandthPercent>),+ /// §20.1.2.3.25 redMod — red multiplier.+ RedMod(Dimension<ThousandthPercent>),+ /// §20.1.2.3.10 green — absolute green channel.+ Green(Dimension<ThousandthPercent>),+ /// §20.1.2.3.11 greenOff — green offset.+ GreenOff(Dimension<ThousandthPercent>),+ /// §20.1.2.3.12 greenMod — green multiplier.+ GreenMod(Dimension<ThousandthPercent>),+ /// §20.1.2.3.4 blue — absolute blue channel.+ Blue(Dimension<ThousandthPercent>),+ /// §20.1.2.3.5 blueOff — blue offset.+ BlueOff(Dimension<ThousandthPercent>),+ /// §20.1.2.3.6 blueMod — blue multiplier.+ BlueMod(Dimension<ThousandthPercent>),+}++// ── ST_SchemeColorVal (§20.1.10.54) ─────────────────────────────────────────++/// §20.1.10.54 ST_SchemeColorVal — named theme color slot.+///+/// `bg1`/`tx1`/`bg2`/`tx2` and `dk1`/`lt1`/`dk2`/`lt2` refer to the same+/// four core slots but with different conventions:+/// * `dk1`/`lt1`/`dk2`/`lt2` reference the theme scheme directly.+/// * `bg1`/`tx1`/`bg2`/`tx2` reference the scheme via the host's+/// foreground/background convention (§17.3.1.31). In Word, light+/// themes map `tx1 → dk1` and `bg1 → lt1`; the resolver folds this.+///+/// `phClr` is a placeholder for master/layout parts; not meaningful in body.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum SchemeColorVal {+ Bg1,+ Tx1,+ Bg2,+ Tx2,+ Accent1,+ Accent2,+ Accent3,+ Accent4,+ Accent5,+ Accent6,+ Hlink,+ FolHlink,+ PhClr,+ Dk1,+ Lt1,+ Dk2,+ Lt2,+}++// ── ST_SystemColorVal (§20.1.10.57) ─────────────────────────────────────────++/// §20.1.10.57 ST_SystemColorVal — OS-defined color name.+///+/// The cached RGB in `CT_SystemColor/@lastClr` is the runtime-resolved value+/// at last save. Renderers without OS access should prefer `lastClr` when+/// present and fall back to a fixed defaults table.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum SystemColorVal {+ ScrollBar,+ Background,+ ActiveCaption,+ InactiveCaption,+ Menu,+ Window,+ WindowFrame,+ MenuText,+ WindowText,+ CaptionText,+ ActiveBorder,+ InactiveBorder,+ AppWorkspace,+ Highlight,+ HighlightText,+ BtnFace,+ BtnShadow,+ GrayText,+ BtnText,+ InactiveCaptionText,+ BtnHighlight,+ ThreeDDkShadow,+ ThreeDLight,+ InfoText,+ InfoBk,+ HotLight,+ GradientActiveCaption,+ GradientInactiveCaption,+ MenuHighlight,+ MenuBar,+}++impl SystemColorVal {+ /// Default RGB fallback when `lastClr` is absent. Based on the Windows+ /// default theme, since OOXML system colors originate from GDI.+ pub fn default_rgb(self) -> u32 {+ match self {+ Self::ScrollBar => 0xC8C8C8,+ Self::Background => 0x000000,+ Self::ActiveCaption => 0x99B4D1,+ Self::InactiveCaption => 0xBFCDDB,+ Self::Menu => 0xF0F0F0,+ Self::Window => 0xFFFFFF,+ Self::WindowFrame => 0x646464,+ Self::MenuText => 0x000000,+ Self::WindowText => 0x000000,+ Self::CaptionText => 0x000000,+ Self::ActiveBorder => 0xB4B4B4,+ Self::InactiveBorder => 0xF4F7FC,+ Self::AppWorkspace => 0xABABAB,+ Self::Highlight => 0x3399FF,+ Self::HighlightText => 0xFFFFFF,+ Self::BtnFace => 0xF0F0F0,+ Self::BtnShadow => 0xA0A0A0,+ Self::GrayText => 0x6D6D6D,+ Self::BtnText => 0x000000,+ Self::InactiveCaptionText => 0x000000,+ Self::BtnHighlight => 0xFFFFFF,+ Self::ThreeDDkShadow => 0x696969,+ Self::ThreeDLight => 0xE3E3E3,+ Self::InfoText => 0x000000,+ Self::InfoBk => 0xFFFFE1,+ Self::HotLight => 0x0066CC,+ Self::GradientActiveCaption => 0xB9D1EA,+ Self::GradientInactiveCaption => 0xD7E4F2,+ Self::MenuHighlight => 0x3399FF,+ Self::MenuBar => 0xF0F0F0,+ }+ }+}++// ── ST_PresetColorVal (§20.1.10.47) ─────────────────────────────────────────++/// §20.1.10.47 ST_PresetColorVal — named preset color.+///+/// A fixed palette of 140 named colors derived from X11 / CSS color names.+/// The spec specifies the RGB value for each; see `rgb()`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum PresetColorVal {+ AliceBlue,+ AntiqueWhite,+ Aqua,+ Aquamarine,+ Azure,+ Beige,+ Bisque,+ Black,+ BlanchedAlmond,+ Blue,+ BlueViolet,+ Brown,+ BurlyWood,+ CadetBlue,+ Chartreuse,+ Chocolate,+ Coral,+ CornflowerBlue,+ Cornsilk,+ Crimson,+ Cyan,+ DarkBlue,+ DarkCyan,+ DarkGoldenrod,+ DarkGray,+ DarkGreen,+ DarkGrey,+ DarkKhaki,+ DarkMagenta,+ DarkOliveGreen,+ DarkOrange,+ DarkOrchid,+ DarkRed,+ DarkSalmon,+ DarkSeaGreen,+ DarkSlateBlue,+ DarkSlateGray,+ DarkSlateGrey,+ DarkTurquoise,+ DarkViolet,+ DeepPink,+ DeepSkyBlue,+ DimGray,+ DimGrey,+ DkBlue,+ DkCyan,+ DkGoldenrod,+ DkGray,+ DkGreen,+ DkGrey,+ DkKhaki,+ DkMagenta,+ DkOliveGreen,+ DkOrange,+ DkOrchid,+ DkRed,+ DkSalmon,+ DkSeaGreen,+ DkSlateBlue,+ DkSlateGray,+ DkSlateGrey,+ DkTurquoise,+ DkViolet,+ DodgerBlue,+ Firebrick,+ FloralWhite,+ ForestGreen,+ Fuchsia,+ Gainsboro,+ GhostWhite,+ Gold,+ Goldenrod,+ Gray,+ Green,+ GreenYellow,+ Grey,+ Honeydew,+ HotPink,+ IndianRed,+ Indigo,+ Ivory,+ Khaki,+ Lavender,+ LavenderBlush,+ LawnGreen,+ LemonChiffon,+ LightBlue,+ LightCoral,+ LightCyan,+ LightGoldenrodYellow,+ LightGray,+ LightGreen,+ LightGrey,+ LightPink,+ LightSalmon,+ LightSeaGreen,+ LightSkyBlue,+ LightSlateGray,+ LightSlateGrey,+ LightSteelBlue,+ LightYellow,+ Lime,+ LimeGreen,+ Linen,+ LtBlue,+ LtCoral,+ LtCyan,+ LtGoldenrodYellow,+ LtGray,+ LtGreen,+ LtGrey,+ LtPink,+ LtSalmon,+ LtSeaGreen,+ LtSkyBlue,+ LtSlateGray,+ LtSlateGrey,+ LtSteelBlue,+ LtYellow,+ Magenta,+ Maroon,+ MedAquamarine,+ MedBlue,+ MedOrchid,+ MedPurple,+ MedSeaGreen,+ MedSlateBlue,+ MedSpringGreen,+ MedTurquoise,+ MedVioletRed,+ MediumAquamarine,+ MediumBlue,+ MediumOrchid,+ MediumPurple,+ MediumSeaGreen,+ MediumSlateBlue,+ MediumSpringGreen,+ MediumTurquoise,+ MediumVioletRed,+ MidnightBlue,+ MintCream,+ MistyRose,+ Moccasin,+ NavajoWhite,+ Navy,+ OldLace,+ Olive,+ OliveDrab,+ Orange,+ OrangeRed,+ Orchid,+ PaleGoldenrod,+ PaleGreen,+ PaleTurquoise,+ PaleVioletRed,+ PapayaWhip,+ PeachPuff,+ Peru,+ Pink,+ Plum,+ PowderBlue,+ Purple,+ Red,+ RosyBrown,+ RoyalBlue,+ SaddleBrown,+ Salmon,+ SandyBrown,+ SeaGreen,+ SeaShell,+ Sienna,+ Silver,+ SkyBlue,+ SlateBlue,+ SlateGray,+ SlateGrey,+ Snow,+ SpringGreen,+ SteelBlue,+ Tan,+ Teal,+ Thistle,+ Tomato,+ Turquoise,+ Violet,+ Wheat,+ White,+ WhiteSmoke,+ Yellow,+ YellowGreen,+}++impl PresetColorVal {+ /// §20.1.10.47 spec-defined RGB for each preset color.+ ///+ /// The `dk*` / `lt*` / `med*` variants are spec aliases for their+ /// `dark*` / `light*` / `medium*` counterparts and share RGB values.+ pub fn rgb(self) -> u32 {+ match self {+ Self::AliceBlue => 0xF0F8FF,+ Self::AntiqueWhite => 0xFAEBD7,+ Self::Aqua => 0x00FFFF,+ Self::Aquamarine => 0x7FFFD4,+ Self::Azure => 0xF0FFFF,+ Self::Beige => 0xF5F5DC,+ Self::Bisque => 0xFFE4C4,+ Self::Black => 0x000000,+ Self::BlanchedAlmond => 0xFFEBCD,+ Self::Blue => 0x0000FF,+ Self::BlueViolet => 0x8A2BE2,+ Self::Brown => 0xA52A2A,+ Self::BurlyWood => 0xDEB887,+ Self::CadetBlue => 0x5F9EA0,+ Self::Chartreuse => 0x7FFF00,+ Self::Chocolate => 0xD2691E,+ Self::Coral => 0xFF7F50,+ Self::CornflowerBlue => 0x6495ED,+ Self::Cornsilk => 0xFFF8DC,+ Self::Crimson => 0xDC143C,+ Self::Cyan => 0x00FFFF,+ Self::DarkBlue | Self::DkBlue => 0x00008B,+ Self::DarkCyan | Self::DkCyan => 0x008B8B,+ Self::DarkGoldenrod | Self::DkGoldenrod => 0xB8860B,+ Self::DarkGray | Self::DkGray | Self::DarkGrey | Self::DkGrey => 0xA9A9A9,+ Self::DarkGreen | Self::DkGreen => 0x006400,+ Self::DarkKhaki | Self::DkKhaki => 0xBDB76B,+ Self::DarkMagenta | Self::DkMagenta => 0x8B008B,+ Self::DarkOliveGreen | Self::DkOliveGreen => 0x556B2F,+ Self::DarkOrange | Self::DkOrange => 0xFF8C00,+ Self::DarkOrchid | Self::DkOrchid => 0x9932CC,+ Self::DarkRed | Self::DkRed => 0x8B0000,+ Self::DarkSalmon | Self::DkSalmon => 0xE9967A,+ Self::DarkSeaGreen | Self::DkSeaGreen => 0x8FBC8F,+ Self::DarkSlateBlue | Self::DkSlateBlue => 0x483D8B,+ Self::DarkSlateGray | Self::DkSlateGray | Self::DarkSlateGrey | Self::DkSlateGrey => {+ 0x2F4F4F+ }+ Self::DarkTurquoise | Self::DkTurquoise => 0x00CED1,+ Self::DarkViolet | Self::DkViolet => 0x9400D3,+ Self::DeepPink => 0xFF1493,+ Self::DeepSkyBlue => 0x00BFFF,+ Self::DimGray | Self::DimGrey => 0x696969,+ Self::DodgerBlue => 0x1E90FF,+ Self::Firebrick => 0xB22222,+ Self::FloralWhite => 0xFFFAF0,+ Self::ForestGreen => 0x228B22,+ Self::Fuchsia => 0xFF00FF,+ Self::Gainsboro => 0xDCDCDC,+ Self::GhostWhite => 0xF8F8FF,+ Self::Gold => 0xFFD700,+ Self::Goldenrod => 0xDAA520,+ Self::Gray | Self::Grey => 0x808080,+ Self::Green => 0x008000,+ Self::GreenYellow => 0xADFF2F,+ Self::Honeydew => 0xF0FFF0,+ Self::HotPink => 0xFF69B4,+ Self::IndianRed => 0xCD5C5C,+ Self::Indigo => 0x4B0082,+ Self::Ivory => 0xFFFFF0,+ Self::Khaki => 0xF0E68C,+ Self::Lavender => 0xE6E6FA,+ Self::LavenderBlush => 0xFFF0F5,+ Self::LawnGreen => 0x7CFC00,+ Self::LemonChiffon => 0xFFFACD,+ Self::LightBlue | Self::LtBlue => 0xADD8E6,+ Self::LightCoral | Self::LtCoral => 0xF08080,+ Self::LightCyan | Self::LtCyan => 0xE0FFFF,+ Self::LightGoldenrodYellow | Self::LtGoldenrodYellow => 0xFAFAD2,+ Self::LightGray | Self::LtGray | Self::LightGrey | Self::LtGrey => 0xD3D3D3,+ Self::LightGreen | Self::LtGreen => 0x90EE90,+ Self::LightPink | Self::LtPink => 0xFFB6C1,+ Self::LightSalmon | Self::LtSalmon => 0xFFA07A,+ Self::LightSeaGreen | Self::LtSeaGreen => 0x20B2AA,+ Self::LightSkyBlue | Self::LtSkyBlue => 0x87CEFA,+ Self::LightSlateGray | Self::LtSlateGray | Self::LightSlateGrey | Self::LtSlateGrey => {+ 0x778899+ }+ Self::LightSteelBlue | Self::LtSteelBlue => 0xB0C4DE,+ Self::LightYellow | Self::LtYellow => 0xFFFFE0,+ Self::Lime => 0x00FF00,+ Self::LimeGreen => 0x32CD32,+ Self::Linen => 0xFAF0E6,+ Self::Magenta => 0xFF00FF,+ Self::Maroon => 0x800000,+ Self::MedAquamarine | Self::MediumAquamarine => 0x66CDAA,+ Self::MedBlue | Self::MediumBlue => 0x0000CD,+ Self::MedOrchid | Self::MediumOrchid => 0xBA55D3,+ Self::MedPurple | Self::MediumPurple => 0x9370DB,+ Self::MedSeaGreen | Self::MediumSeaGreen => 0x3CB371,+ Self::MedSlateBlue | Self::MediumSlateBlue => 0x7B68EE,+ Self::MedSpringGreen | Self::MediumSpringGreen => 0x00FA9A,+ Self::MedTurquoise | Self::MediumTurquoise => 0x48D1CC,+ Self::MedVioletRed | Self::MediumVioletRed => 0xC71585,+ Self::MidnightBlue => 0x191970,+ Self::MintCream => 0xF5FFFA,+ Self::MistyRose => 0xFFE4E1,+ Self::Moccasin => 0xFFE4B5,+ Self::NavajoWhite => 0xFFDEAD,+ Self::Navy => 0x000080,+ Self::OldLace => 0xFDF5E6,+ Self::Olive => 0x808000,+ Self::OliveDrab => 0x6B8E23,+ Self::Orange => 0xFFA500,+ Self::OrangeRed => 0xFF4500,+ Self::Orchid => 0xDA70D6,+ Self::PaleGoldenrod => 0xEEE8AA,+ Self::PaleGreen => 0x98FB98,+ Self::PaleTurquoise => 0xAFEEEE,+ Self::PaleVioletRed => 0xDB7093,+ Self::PapayaWhip => 0xFFEFD5,+ Self::PeachPuff => 0xFFDAB9,+ Self::Peru => 0xCD853F,+ Self::Pink => 0xFFC0CB,+ Self::Plum => 0xDDA0DD,+ Self::PowderBlue => 0xB0E0E6,+ Self::Purple => 0x800080,+ Self::Red => 0xFF0000,+ Self::RosyBrown => 0xBC8F8F,+ Self::RoyalBlue => 0x4169E1,+ Self::SaddleBrown => 0x8B4513,+ Self::Salmon => 0xFA8072,+ Self::SandyBrown => 0xF4A460,+ Self::SeaGreen => 0x2E8B57,+ Self::SeaShell => 0xFFF5EE,+ Self::Sienna => 0xA0522D,+ Self::Silver => 0xC0C0C0,+ Self::SkyBlue => 0x87CEEB,+ Self::SlateBlue => 0x6A5ACD,+ Self::SlateGray | Self::SlateGrey => 0x708090,+ Self::Snow => 0xFFFAFA,+ Self::SpringGreen => 0x00FF7F,+ Self::SteelBlue => 0x4682B4,+ Self::Tan => 0xD2B48C,+ Self::Teal => 0x008080,+ Self::Thistle => 0xD8BFD8,+ Self::Tomato => 0xFF6347,+ Self::Turquoise => 0x40E0D0,+ Self::Violet => 0xEE82EE,+ Self::Wheat => 0xF5DEB3,+ Self::White => 0xFFFFFF,+ Self::WhiteSmoke => 0xF5F5F5,+ Self::Yellow => 0xFFFF00,+ Self::YellowGreen => 0x9ACD32,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn drawing_color_transforms_accessor() {+ let c = DrawingColor::Srgb {+ rgb: 0xAABBCC,+ transforms: vec![ColorTransform::Comp, ColorTransform::Inv],+ };+ assert_eq!(c.transforms().len(), 2);++ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Accent1,+ transforms: vec![],+ };+ assert!(c.transforms().is_empty());+ }++ #[test]+ fn preset_color_aliases_share_rgb() {+ assert_eq!(PresetColorVal::DarkBlue.rgb(), PresetColorVal::DkBlue.rgb());+ assert_eq!(PresetColorVal::Gray.rgb(), PresetColorVal::Grey.rgb());+ assert_eq!(+ PresetColorVal::MediumAquamarine.rgb(),+ PresetColorVal::MedAquamarine.rgb()+ );+ assert_eq!(+ PresetColorVal::LightSlateGray.rgb(),+ PresetColorVal::LtSlateGrey.rgb()+ );+ }++ #[test]+ fn preset_color_black_and_white() {+ assert_eq!(PresetColorVal::Black.rgb(), 0x000000);+ assert_eq!(PresetColorVal::White.rgb(), 0xFFFFFF);+ }++ #[test]+ fn preset_color_spec_values() {+ assert_eq!(PresetColorVal::AliceBlue.rgb(), 0xF0F8FF);+ assert_eq!(PresetColorVal::Red.rgb(), 0xFF0000);+ assert_eq!(PresetColorVal::Chocolate.rgb(), 0xD2691E);+ }++ #[test]+ fn system_color_default_window() {+ assert_eq!(SystemColorVal::Window.default_rgb(), 0xFFFFFF);+ assert_eq!(SystemColorVal::WindowText.default_rgb(), 0x000000);+ }+}diff --git a/crates/liteparse-docx/src/model/types/formatting.rs b/crates/liteparse-docx/src/model/types/formatting.rsnew file mode 100644index 0000000..f27fccd--- /dev/null+++ b/crates/liteparse-docx/src/model/types/formatting.rs@@ -0,0 +1,422 @@+//! Shared formatting primitives — borders, shading, tabs, alignment, and enums+//! used across paragraph, table, and run properties.++use crate::model::dimension::{Dimension, EighthPoints, Points, Twips};++use super::color::Color;++// ── Alignment ────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Alignment {+ Start,+ Center,+ End,+ Both,+ Distribute,+ Thai,+}++// ── Number Format ────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum NumberFormat {+ Decimal,+ UpperRoman,+ LowerRoman,+ UpperLetter,+ LowerLetter,+ Bullet,+ Ordinal,+ CardinalText,+ OrdinalText,+ None,+}++// ── Height Rule ──────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum HeightRule {+ Auto,+ Exact,+ AtLeast,+}++// ── Borders ──────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ParagraphBorders {+ pub top: Option<Border>,+ pub bottom: Option<Border>,+ pub left: Option<Border>,+ pub right: Option<Border>,+ pub between: Option<Border>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Border {+ pub style: BorderStyle,+ /// §17.3.4: border width in eighths of a point (ST_EighthPointMeasure).+ pub width: Dimension<EighthPoints>,+ /// §17.3.4: spacing offset (ST_PointMeasure §17.18.68).+ pub space: Dimension<Points>,+ pub color: Color,+}++/// §17.18.2 `ST_Border`.+///+/// `Nil` and `None` are **not** synonyms and must not be merged. Both draw+/// nothing, but [MS-OI29500] §17.4.66 separates them in table border conflict+/// resolution: a `nil` edge *suppresses* the shared border outright, while a+/// `none` edge behaves exactly like an omitted one — it inherits from the style+/// and table-level borders, and yields to the opposing cell's border. Use+/// [`BorderStyle::draws_nothing`] wherever only "is there a line to paint"+/// matters, so the distinction can't be lost by an `== None` comparison.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum BorderStyle {+ /// `val="nil"` — no border, and it wins conflict resolution.+ Nil,+ /// `val="none"` — no border, but inherits and yields like an omitted edge.+ None,+ Single,+ Thick,+ Double,+ Dotted,+ Dashed,+ DotDash,+ DotDotDash,+ Triple,+ ThinThickSmallGap,+ ThickThinSmallGap,+ ThinThickThinSmallGap,+ ThinThickMediumGap,+ ThickThinMediumGap,+ ThinThickThinMediumGap,+ ThinThickLargeGap,+ ThickThinLargeGap,+ ThinThickThinLargeGap,+ Wave,+ DoubleWave,+ DashSmallGap,+ DashDotStroked,+ ThreeDEmboss,+ ThreeDEngrave,+ Outset,+ Inset,+}++impl BorderStyle {+ /// Whether this style paints no line at all — true for both `nil` and+ /// `none` (§17.18.2).+ ///+ /// Every consumer that only asks "is there a border to draw" should call+ /// this rather than comparing against a variant, because the two differ+ /// solely in table conflict resolution ([MS-OI29500] §17.4.66). Comparing+ /// `== BorderStyle::None` is how the distinction was lost before: it+ /// silently answered "no" for `nil` too, at every site outside the table+ /// resolver where the difference is genuinely irrelevant — and at the one+ /// site where it isn't.+ pub fn draws_nothing(self) -> bool {+ matches!(self, Self::Nil | Self::None)+ }+}++// ── Shading ──────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Shading {+ pub fill: Color,+ pub pattern: ShadingPattern,+ pub color: Color,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ShadingPattern {+ /// §17.18.78 ST_Shd: `nil` — no shading whatsoever.+ Nil,+ Clear,+ Solid,+ HorzStripe,+ VertStripe,+ ReverseDiagStripe,+ DiagStripe,+ HorzCross,+ DiagCross,+ ThinHorzStripe,+ ThinVertStripe,+ ThinReverseDiagStripe,+ ThinDiagStripe,+ ThinHorzCross,+ ThinDiagCross,+ Pct5,+ Pct10,+ Pct12,+ Pct15,+ Pct20,+ Pct25,+ Pct30,+ Pct35,+ Pct37,+ Pct40,+ Pct45,+ Pct50,+ Pct55,+ Pct60,+ Pct62,+ Pct65,+ Pct70,+ Pct75,+ Pct80,+ Pct85,+ Pct87,+ Pct90,+ Pct95,+}++// ── Tabs ─────────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct TabStop {+ pub position: Dimension<Twips>,+ pub alignment: TabAlignment,+ pub leader: TabLeader,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TabAlignment {+ Left,+ Center,+ Right,+ Decimal,+ Bar,+ Clear,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TabLeader {+ None,+ Dot,+ Hyphen,+ Underscore,+ Heavy,+ MiddleDot,+}++// ── Absolute position tabs (§17.3.1.30 w:ptab) ───────────────────────────────++/// §17.3.1.30: an absolute-position tab (`<w:ptab>`). Unlike a regular tab+/// (§17.3.3.29), it carries no `pos`; the position is derived from+/// `relative_to` and `alignment` at layout time.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct PositionTab {+ /// §17.18.59: how following content aligns to the derived position.+ pub alignment: PTabAlignment,+ /// §17.18.61: reference the position is measured against.+ pub relative_to: PTabRelativeTo,+ /// §17.18.60: leader character filling the gap.+ pub leader: PTabLeader,+}++/// §17.18.59 ST_PTabAlignment — a strict subset of tab alignments (no+/// decimal/bar/clear).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PTabAlignment {+ Left,+ Center,+ Right,+}++/// §17.18.61 ST_PTabRelativeTo — the base the position is measured from.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PTabRelativeTo {+ /// Relative to the page text margins.+ Margin,+ /// Relative to the current paragraph indents.+ Indent,+}++/// §17.18.60 ST_PTabLeader — leader characters for a position tab. A subset of+/// [`TabLeader`] (no `heavy`); [`From`] lets layout reuse the tab-leader painter.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PTabLeader {+ None,+ Dot,+ Hyphen,+ Underscore,+ MiddleDot,+}++impl From<PTabLeader> for TabLeader {+ fn from(l: PTabLeader) -> Self {+ match l {+ PTabLeader::None => Self::None,+ PTabLeader::Dot => Self::Dot,+ PTabLeader::Hyphen => Self::Hyphen,+ PTabLeader::Underscore => Self::Underscore,+ PTabLeader::MiddleDot => Self::MiddleDot,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn cnf_first_row_bit_is_leftmost() {+ assert_eq!(CnfStyle::from_val_str("100000000000"), CnfStyle::FIRST_ROW);+ }++ #[test]+ fn cnf_last_row_last_column_is_rightmost() {+ assert_eq!(+ CnfStyle::from_val_str("000000000001"),+ CnfStyle::LAST_ROW_LAST_COLUMN+ );+ }++ #[test]+ fn cnf_all_twelve_bits() {+ assert_eq!(CnfStyle::from_val_str("111111111111"), CnfStyle::all());+ }++ #[test]+ fn cnf_empty_is_empty() {+ assert_eq!(CnfStyle::from_val_str(""), CnfStyle::empty());+ }++ #[test]+ fn cnf_short_string_sets_only_leading_bits() {+ assert_eq!(+ CnfStyle::from_val_str("11"),+ CnfStyle::FIRST_ROW | CnfStyle::LAST_ROW+ );+ }++ #[test]+ fn cnf_chars_beyond_twelve_are_ignored() {+ assert_eq!(+ CnfStyle::from_val_str("100000000000ZZZ"),+ CnfStyle::FIRST_ROW+ );+ }++ #[test]+ fn cnf_non_one_chars_leave_bits_unset() {+ // Only '1' sets a bit; '0' and anything else leave it clear.+ assert_eq!(CnfStyle::from_val_str("0x0000000000"), CnfStyle::empty());+ }++ #[test]+ fn ptab_leader_maps_to_tab_leader() {+ assert_eq!(TabLeader::from(PTabLeader::None), TabLeader::None);+ assert_eq!(TabLeader::from(PTabLeader::Dot), TabLeader::Dot);+ assert_eq!(TabLeader::from(PTabLeader::Hyphen), TabLeader::Hyphen);+ assert_eq!(+ TabLeader::from(PTabLeader::Underscore),+ TabLeader::Underscore+ );+ assert_eq!(TabLeader::from(PTabLeader::MiddleDot), TabLeader::MiddleDot);+ }+}++// ── Conditional Formatting ───────────────────────────────────────────────────++bitflags::bitflags! {+ /// §17.3.1.8: conditional formatting region flags indicating which table+ /// style regions apply to an element (paragraph, row, or cell).+ ///+ /// The 12 bits correspond to the positional regions defined in ST_CnfType.+ /// The legacy `val` binary string (e.g. `"100000000000"`) maps to these+ /// bits left-to-right: bit 0 = firstRow, …, bit 11 = lastRowLastColumn.+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+ pub struct CnfStyle: u16 {+ const FIRST_ROW = 1 << 0;+ const LAST_ROW = 1 << 1;+ const FIRST_COLUMN = 1 << 2;+ const LAST_COLUMN = 1 << 3;+ const ODD_V_BAND = 1 << 4;+ const EVEN_V_BAND = 1 << 5;+ const ODD_H_BAND = 1 << 6;+ const EVEN_H_BAND = 1 << 7;+ const FIRST_ROW_FIRST_COLUMN = 1 << 8;+ const FIRST_ROW_LAST_COLUMN = 1 << 9;+ const LAST_ROW_FIRST_COLUMN = 1 << 10;+ const LAST_ROW_LAST_COLUMN = 1 << 11;+ }+}++impl CnfStyle {+ /// Parse the legacy 12-character `val` binary string (§17.3.1.8).+ ///+ /// Each character position maps to a flag left-to-right: `'1'` sets the+ /// flag, `'0'` or any other character leaves it unset. Characters beyond+ /// position 11 are ignored.+ pub fn from_val_str(s: &str) -> Self {+ let flags = [+ CnfStyle::FIRST_ROW,+ CnfStyle::LAST_ROW,+ CnfStyle::FIRST_COLUMN,+ CnfStyle::LAST_COLUMN,+ CnfStyle::ODD_V_BAND,+ CnfStyle::EVEN_V_BAND,+ CnfStyle::ODD_H_BAND,+ CnfStyle::EVEN_H_BAND,+ CnfStyle::FIRST_ROW_FIRST_COLUMN,+ CnfStyle::FIRST_ROW_LAST_COLUMN,+ CnfStyle::LAST_ROW_FIRST_COLUMN,+ CnfStyle::LAST_ROW_LAST_COLUMN,+ ];+ s.bytes()+ .zip(flags.iter())+ .fold(+ CnfStyle::empty(),+ |acc, (ch, &flag)| {+ if ch == b'1' { acc | flag } else { acc }+ },+ )+ }+}++// ── Text Alignment ───────────────────────────────────────────────────────────++/// §17.18.91 ST_TextAlignment — vertical alignment of characters on a line.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TextAlignment {+ Auto,+ Top,+ Center,+ Baseline,+ Bottom,+}++// ── Positioning enums (shared by table and frame) ────────────────────────────++/// §17.18.106 ST_VAnchor — vertical/horizontal anchor for table positioning.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableAnchor {+ Text,+ Margin,+ Page,+}++/// §17.18.108 ST_XAlign — horizontal alignment for floating table.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableXAlign {+ Left,+ Center,+ Right,+ Inside,+ Outside,+}++/// §17.18.109 ST_YAlign — vertical alignment for floating table.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableYAlign {+ Top,+ Center,+ Bottom,+ Inside,+ Outside,+ Inline,+}diff --git a/crates/liteparse-docx/src/model/types/identifiers.rs b/crates/liteparse-docx/src/model/types/identifiers.rsnew file mode 100644index 0000000..e88c86b--- /dev/null+++ b/crates/liteparse-docx/src/model/types/identifiers.rs@@ -0,0 +1,220 @@+//! Typed identifiers and revision tracking.++/// A relationship ID (e.g., "rId1") — opaque, interned from the .rels files.+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub struct RelId(String);++impl RelId {+ pub fn new(id: impl Into<String>) -> Self {+ Self(id.into())+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// Footnote or endnote numeric ID.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct NoteId(i64);++impl NoteId {+ pub fn new(id: i64) -> Self {+ Self(id)+ }++ pub fn value(self) -> i64 {+ self.0+ }+}++/// A bookmark ID.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct BookmarkId(i64);++impl BookmarkId {+ pub fn new(id: i64) -> Self {+ Self(id)+ }++ pub fn value(self) -> i64 {+ self.0+ }+}++/// A style ID (e.g., "Heading1", "Normal") — reference into `Document.styles`.+/// Per §17.7.4.17, this is the `w:styleId` attribute value.+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub struct StyleId(String);++impl StyleId {+ pub fn new(id: impl Into<String>) -> Self {+ Self(id.into())+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// §17.9.1: abstract numbering definition ID.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct AbstractNumId(i64);++impl AbstractNumId {+ pub fn new(id: i64) -> Self {+ Self(id)+ }++ pub fn value(self) -> i64 {+ self.0+ }+}++/// §17.9.19: numbering instance ID.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct NumId(i64);++impl NumId {+ pub fn new(id: i64) -> Self {+ Self(id)+ }++ pub fn value(self) -> i64 {+ self.0+ }+}++/// §17.9.21: picture bullet ID. References between `w:numPicBullet` and `w:lvlPicBulletId`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct NumPicBulletId(i64);++impl NumPicBulletId {+ pub fn new(id: i64) -> Self {+ Self(id)+ }++ pub fn value(self) -> i64 {+ self.0+ }+}++/// VML shape identifier (e.g., "_x0000_t202"). Used as a `v:shapetype` `id`+/// and referenced by `v:shape` `type` (with a leading `#` prefix).+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub struct VmlShapeId(String);++impl VmlShapeId {+ pub fn new(id: impl Into<String>) -> Self {+ Self(id.into())+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// Revision Save ID — identifies which editing session produced a change.+/// Stored as a 32-bit value parsed from an 8-digit hex string (e.g., "00A2B3C4").+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct RevisionSaveId(u32);++impl RevisionSaveId {+ pub fn value(self) -> u32 {+ self.0+ }++ /// Parse from an OOXML hex string. Returns None if invalid.+ pub fn from_hex(s: &str) -> Option<Self> {+ u32::from_str_radix(s, 16).ok().map(Self)+ }+}++/// Revision tracking IDs attached to an element.+/// Each field records which editing session performed that type of change.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct RevisionIds {+ /// Session that added this element.+ pub r: Option<RevisionSaveId>,+ /// Session that last modified this element's properties.+ pub r_pr: Option<RevisionSaveId>,+ /// Session that deleted this element (for tracked deletions).+ pub del: Option<RevisionSaveId>,+}++/// Revision tracking IDs specific to paragraphs.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct ParagraphRevisionIds {+ /// Session that added this paragraph.+ pub r: Option<RevisionSaveId>,+ /// Session that added the default run content.+ pub r_default: Option<RevisionSaveId>,+ /// Session that last modified paragraph properties.+ pub p: Option<RevisionSaveId>,+ /// Session that last modified run properties on the paragraph mark.+ pub r_pr: Option<RevisionSaveId>,+ /// Session that deleted this paragraph.+ pub del: Option<RevisionSaveId>,+}++/// Revision tracking IDs specific to table rows.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct TableRowRevisionIds {+ /// Session that added this row.+ pub r: Option<RevisionSaveId>,+ /// Session that last modified row properties.+ pub r_pr: Option<RevisionSaveId>,+ /// Session that deleted this row.+ pub del: Option<RevisionSaveId>,+ /// Session that last modified this row's table-level formatting.+ pub tr: Option<RevisionSaveId>,+}++/// Revision tracking IDs specific to section properties.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct SectionRevisionIds {+ /// Session that added this section.+ pub r: Option<RevisionSaveId>,+ /// Session that last modified section run properties.+ pub r_pr: Option<RevisionSaveId>,+ /// Session that last modified section properties.+ pub sect: Option<RevisionSaveId>,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn revision_save_id_parses_eight_digit_hex() {+ assert_eq!(+ RevisionSaveId::from_hex("00A2B3C4").unwrap().value(),+ 0x00A2_B3C4+ );+ assert_eq!(+ RevisionSaveId::from_hex("FFFFFFFF").unwrap().value(),+ 0xFFFF_FFFF+ );+ }++ #[test]+ fn revision_save_id_rejects_non_hex() {+ assert!(RevisionSaveId::from_hex("XYZ").is_none());+ assert!(RevisionSaveId::from_hex("").is_none());+ assert!(RevisionSaveId::from_hex("-1").is_none());+ }++ #[test]+ fn revision_save_id_rejects_overflow() {+ // Nine hex digits exceed u32::MAX.+ assert!(RevisionSaveId::from_hex("1FFFFFFFF").is_none());+ }++ #[test]+ fn typed_id_accessors_round_trip() {+ assert_eq!(RelId::new("rId7").as_str(), "rId7");+ assert_eq!(NumId::new(3).value(), 3);+ assert_eq!(StyleId::new("Heading1").as_str(), "Heading1");+ assert_eq!(VmlShapeId::new("_x0000_t202").as_str(), "_x0000_t202");+ }+}diff --git a/crates/liteparse-docx/src/model/types/mod.rs b/crates/liteparse-docx/src/model/types/mod.rsnew file mode 100644index 0000000..4948de5--- /dev/null+++ b/crates/liteparse-docx/src/model/types/mod.rs@@ -0,0 +1,36 @@+//! Complete DOCX document model — all types are fully resolved ADTs.+//! No unparsed strings, no style indirection, no invalid states.++mod color;+mod content;+mod document;+mod drawing;+mod drawing_color;+mod formatting;+mod identifiers;+mod numbering;+mod paragraph;+mod run_properties;+mod section;+mod settings;+mod styles;+mod table;+mod theme;+mod vml;++pub use color::*;+pub use content::*;+pub use document::*;+pub use drawing::*;+pub use drawing_color::*;+pub use formatting::*;+pub use identifiers::*;+pub use numbering::*;+pub use paragraph::*;+pub use run_properties::*;+pub use section::*;+pub use settings::*;+pub use styles::*;+pub use table::*;+pub use theme::*;+pub use vml::*;diff --git a/crates/liteparse-docx/src/model/types/numbering.rs b/crates/liteparse-docx/src/model/types/numbering.rsnew file mode 100644index 0000000..b305252--- /dev/null+++ b/crates/liteparse-docx/src/model/types/numbering.rs@@ -0,0 +1,85 @@+//! Numbering definitions — abstract numbering, instances, picture bullets.++use std::collections::HashMap;++use super::formatting::{Alignment, NumberFormat};+use super::identifiers::{AbstractNumId, NumId, NumPicBulletId};+use super::paragraph::Indentation;+use super::run_properties::RunProperties;+use super::vml::Pict;++/// Raw numbering definitions as parsed from `word/numbering.xml`.+#[derive(Clone, Debug, Default)]+pub struct NumberingDefinitions {+ /// Abstract numbering definitions keyed by abstract numbering ID.+ pub abstract_nums: HashMap<AbstractNumId, AbstractNumbering>,+ /// Numbering instances keyed by numbering ID.+ pub numbering_instances: HashMap<NumId, NumberingInstance>,+ /// §17.9.21: picture bullet definitions keyed by numPicBulletId.+ pub pic_bullets: HashMap<NumPicBulletId, NumPicBullet>,+}++/// §17.9.21: a picture bullet definition.+#[derive(Clone, Debug)]+pub struct NumPicBullet {+ /// §17.9.21 @numPicBulletId: unique identifier.+ pub id: NumPicBulletId,+ /// §17.3.3.19: VML picture content.+ pub pict: Option<Pict>,+}++/// An abstract numbering definition.+#[derive(Clone, Debug)]+pub struct AbstractNumbering {+ pub levels: Vec<NumberingLevelDefinition>,+}++/// §17.18.53 ST_LevelSuffix — the character between a list label and the+/// paragraph text.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum LevelSuffix {+ /// A tab (the spec default).+ #[default]+ Tab,+ /// A single space.+ Space,+ /// Nothing — the text follows the label directly.+ Nothing,+}++/// A single level within an abstract numbering definition.+#[derive(Clone, Debug)]+pub struct NumberingLevelDefinition {+ pub level: u8,+ pub format: Option<NumberFormat>,+ pub level_text: String,+ pub start: Option<u32>,+ /// §17.9.7: justification of the numbering symbol (uses ST_Jc).+ pub justification: Option<Alignment>,+ pub indentation: Option<Indentation>,+ pub run_properties: Option<RunProperties>,+ /// §17.9.10: reference to a picture bullet definition.+ pub lvl_pic_bullet_id: Option<NumPicBulletId>,+ /// §17.9.29: separator between the number and the paragraph text.+ pub suffix: LevelSuffix,+ /// §17.9.8: render all level numbers as decimal (legal numbering).+ pub is_legal: bool,+}++/// §17.9.9: a per-instance override of one abstract numbering level.+#[derive(Clone, Debug)]+pub struct LevelOverride {+ /// §17.9.9 @ilvl: the level this override applies to.+ pub level: u8,+ /// §17.9.28 startOverride: restart this level's counter at the given value.+ pub start_override: Option<u32>,+ /// §17.9.9: the replacement level definition, if the override supplies one.+ pub definition: Option<NumberingLevelDefinition>,+}++/// A numbering instance — maps to an abstract numbering, with optional level overrides.+#[derive(Clone, Debug)]+pub struct NumberingInstance {+ pub abstract_num_id: AbstractNumId,+ pub level_overrides: Vec<LevelOverride>,+}diff --git a/crates/liteparse-docx/src/model/types/paragraph.rs b/crates/liteparse-docx/src/model/types/paragraph.rsnew file mode 100644index 0000000..ce62496--- /dev/null+++ b/crates/liteparse-docx/src/model/types/paragraph.rs@@ -0,0 +1,235 @@+//! Paragraph types — paragraph properties, spacing, indentation, frames.++use crate::model::dimension::{Dimension, Twips};++use super::formatting::{+ Alignment, CnfStyle, HeightRule, ParagraphBorders, Shading, TabStop, TableAnchor, TableXAlign,+ TableYAlign, TextAlignment,+};+use super::identifiers::{ParagraphRevisionIds, StyleId};+use super::run_properties::RunProperties;++use super::content::Inline;++#[derive(Clone, Debug)]+pub struct Paragraph {+ /// Style ID reference (e.g., "Heading1"). Resolve via `Document.styles`.+ pub style_id: Option<StyleId>,+ pub properties: ParagraphProperties,+ /// Run properties specified on the paragraph mark (w:rPr inside w:pPr).+ pub mark_run_properties: Option<RunProperties>,+ pub content: Vec<Inline>,+ pub rsids: ParagraphRevisionIds,+}++/// Paragraph properties — only fields explicitly present in the XML are `Some`.+#[derive(Clone, Debug, Default)]+pub struct ParagraphProperties {+ pub alignment: Option<Alignment>,+ pub indentation: Option<Indentation>,+ pub spacing: Option<ParagraphSpacing>,+ pub numbering: Option<NumberingReference>,+ pub tabs: Vec<TabStop>,+ pub borders: Option<ParagraphBorders>,+ pub shading: Option<Shading>,+ pub keep_next: Option<bool>,+ pub keep_lines: Option<bool>,+ pub widow_control: Option<bool>,+ pub page_break_before: Option<bool>,+ pub suppress_auto_hyphens: Option<bool>,+ /// §17.3.1.9: suppress spacing when adjacent paragraph has same style.+ pub contextual_spacing: Option<bool>,+ pub bidi: Option<bool>,+ /// §17.3.1.45: allow line breaking between any characters for East Asian text.+ pub word_wrap: Option<bool>,+ pub outline_level: Option<OutlineLevel>,+ /// §17.3.1.39: vertical alignment of text on each line (ST_TextAlignment).+ pub text_alignment: Option<TextAlignment>,+ /// §17.3.1.8: table conditional formatting applied to this paragraph.+ pub cnf_style: Option<CnfStyle>,+ /// §17.3.1.11: text frame (legacy positioned text region).+ pub frame_properties: Option<FrameKind>,+ /// §17.3.1.2: auto-space East Asian text with Latin text.+ pub auto_space_de: Option<bool>,+ /// §17.3.1.3: auto-space East Asian text with numbers.+ pub auto_space_dn: Option<bool>,+}++/// §17.3.1.11: frame kind — a paragraph is either a drop cap or a floating text box.+///+/// OOXML `w:framePr` conflates these two uses; the presence and value of `w:dropCap`+/// determines which kind a given `framePr` represents.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FrameKind {+ /// The paragraph's first character(s) are rendered as a drop cap.+ DropCap {+ /// Whether the cap is inline (`Drop`) or in the margin (`Margin`).+ style: DropCap,+ /// Number of body-text lines the cap letter spans (default 3).+ lines: u32,+ /// Horizontal space between cap and body text, in twips.+ h_space: Option<Dimension<Twips>>,+ },+ /// Legacy floating text frame — positioned outside normal flow.+ TextBox(TextBoxPositioning),+}++/// §17.18.16 ST_DropCap — the two active drop-cap styles.+/// (`dropCap="none"` is represented by the absence of `FrameKind::DropCap`.)+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum DropCap {+ /// Cap is inline, to the left of the paragraph text.+ Drop,+ /// Cap is placed in the page margin.+ Margin,+}++/// Positioning attributes for a legacy floating text frame (`w:framePr` without drop cap).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct TextBoxPositioning {+ /// Frame width in twips.+ pub width: Option<Dimension<Twips>>,+ /// Frame height in twips.+ pub height: Option<Dimension<Twips>>,+ /// §17.18.37 ST_HeightRule: how to interpret the height value.+ pub height_rule: Option<HeightRule>,+ /// Horizontal distance from surrounding text in twips.+ pub h_space: Option<Dimension<Twips>>,+ /// Vertical distance from surrounding text in twips.+ pub v_space: Option<Dimension<Twips>>,+ /// §17.18.104 ST_Wrap: text wrapping mode.+ pub wrap: Option<FrameWrap>,+ /// §17.18.35 ST_HAnchor: horizontal anchor.+ pub h_anchor: Option<TableAnchor>,+ /// §17.18.106 ST_VAnchor: vertical anchor.+ pub v_anchor: Option<TableAnchor>,+ /// Absolute horizontal position in twips.+ pub x: Option<Dimension<Twips>>,+ /// §17.18.108 ST_XAlign: horizontal alignment.+ pub x_align: Option<TableXAlign>,+ /// Absolute vertical position in twips.+ pub y: Option<Dimension<Twips>>,+ /// §17.18.109 ST_YAlign: vertical alignment.+ pub y_align: Option<TableYAlign>,+}++/// §17.18.104 ST_Wrap — text wrapping for frames.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FrameWrap {+ Auto,+ NotBeside,+ Around,+ Tight,+ Through,+ None,+}++/// Heading outline level (0–8, where 0 = Heading 1 in OOXML).+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct OutlineLevel(u8);++impl OutlineLevel {+ /// Create an outline level. Panics if `level` is 0 or > 9.+ pub fn new(level: u8) -> Self {+ assert!((1..=9).contains(&level), "outline level must be 1..=9");+ Self(level)+ }++ /// Create from a §17.3.1.19 `w:outlineLvl/@w:val`, which is 0-based.+ ///+ /// Returns `None` for 9, and that is the spec rather than a bound: value 9+ /// is "body text" — an explicit statement that the paragraph has **no**+ /// outline level, not a ninth heading level. Word writes it when a+ /// paragraph's outline level is reset to Body Text, so a heading style's+ /// level can be overridden back off. `None` therefore means "not a+ /// heading", whether the attribute was absent or present-and-9.+ pub fn from_ooxml(val: u8) -> Option<Self> {+ if val <= 8 { Some(Self(val + 1)) } else { None }+ }++ pub fn value(self) -> u8 {+ self.0+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct Indentation {+ pub start: Option<Dimension<Twips>>,+ pub end: Option<Dimension<Twips>>,+ pub first_line: Option<FirstLineIndent>,+ pub mirror: Option<bool>,+}++/// First-line indent: either hanging (negative) or first-line (positive).+/// These are mutually exclusive in OOXML.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FirstLineIndent {+ None,+ FirstLine(Dimension<Twips>),+ Hanging(Dimension<Twips>),+}++/// Paragraph spacing — only fields explicitly present in the XML are `Some`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub struct ParagraphSpacing {+ pub before: Option<Dimension<Twips>>,+ pub after: Option<Dimension<Twips>>,+ pub line: Option<LineSpacing>,+ pub before_auto_spacing: Option<bool>,+ pub after_auto_spacing: Option<bool>,+}++/// Line spacing rule — the three OOXML modes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LineSpacing {+ /// Automatic (proportional). Value is in 240ths of a line (240 = single).+ Auto(Dimension<Twips>),+ /// Exact line height.+ Exact(Dimension<Twips>),+ /// Minimum line height (at least this much).+ AtLeast(Dimension<Twips>),+}++/// Raw numbering reference on a paragraph (w:numPr).+/// Resolve via `Document.numbering` using `num_id` + `level`.+#[derive(Clone, Copy, Debug)]+pub struct NumberingReference {+ pub num_id: i64,+ pub level: u8,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn outline_level_from_ooxml_is_one_based() {+ // OOXML `w:outlineLvl` is 0-based (0 = Heading 1); storage is 1-based.+ assert_eq!(OutlineLevel::from_ooxml(0).unwrap().value(), 1);+ assert_eq!(OutlineLevel::from_ooxml(8).unwrap().value(), 9);+ }++ #[test]+ fn outline_level_from_ooxml_rejects_out_of_range() {+ assert!(OutlineLevel::from_ooxml(9).is_none());+ assert!(OutlineLevel::from_ooxml(255).is_none());+ }++ #[test]+ fn outline_level_new_accepts_valid_range() {+ assert_eq!(OutlineLevel::new(1).value(), 1);+ assert_eq!(OutlineLevel::new(9).value(), 9);+ }++ #[test]+ #[should_panic(expected = "outline level must be 1..=9")]+ fn outline_level_new_rejects_zero() {+ OutlineLevel::new(0);+ }++ #[test]+ #[should_panic(expected = "outline level must be 1..=9")]+ fn outline_level_new_rejects_ten() {+ OutlineLevel::new(10);+ }+}diff --git a/crates/liteparse-docx/src/model/types/run_properties.rs b/crates/liteparse-docx/src/model/types/run_properties.rsnew file mode 100644index 0000000..e8fc885--- /dev/null+++ b/crates/liteparse-docx/src/model/types/run_properties.rs@@ -0,0 +1,253 @@+//! Run (character) properties.++use crate::model::dimension::{Dimension, HalfPoints, Twips};++use super::color::Color;+use super::formatting::{Border, Shading};++/// Run properties — only fields explicitly present in the XML are `Some`.+#[derive(Clone, Debug, PartialEq, Default)]+pub struct RunProperties {+ pub fonts: FontSet,+ pub font_size: Option<Dimension<HalfPoints>>,+ pub bold: Option<bool>,+ pub italic: Option<bool>,+ pub underline: Option<UnderlineStyle>,+ pub strike: Option<StrikeStyle>,+ pub color: Option<Color>,+ pub highlight: Option<HighlightColor>,+ pub shading: Option<Shading>,+ pub vertical_align: Option<VerticalAlign>,+ pub spacing: Option<Dimension<Twips>>,+ pub kerning: Option<Dimension<HalfPoints>>,+ pub all_caps: Option<bool>,+ pub small_caps: Option<bool>,+ pub vanish: Option<bool>,+ /// §17.3.2.21: suppress spell/grammar checking for this run.+ pub no_proof: Option<bool>,+ /// §17.3.2.44: hidden when displayed as a web page, visible in print view.+ pub web_hidden: Option<bool>,+ pub rtl: Option<bool>,+ pub emboss: Option<bool>,+ pub imprint: Option<bool>,+ pub outline: Option<bool>,+ pub shadow: Option<bool>,+ /// §17.3.2.19: vertical position offset of text baseline, in half-points.+ /// Positive raises, negative lowers.+ pub position: Option<Dimension<HalfPoints>>,+ /// §17.3.2.20: proofing languages per script category (BCP 47 tags).+ pub lang: Option<Lang>,+ /// §17.3.2.4: border around run content.+ pub border: Option<Border>,+ /// §17.3.2.45 (`<w:w>`): horizontal character scaling, as a percentage.+ /// Scales glyph advances horizontally without affecting font size or+ /// inter-character spacing (`w:spacing`). Default 100% (no scaling).+ pub text_scale: Option<TextScale>,+}++/// §17.18.81 ST_TextScale — integer percent in `1..=600`. Default 100.+///+/// Carried as a typed newtype so the spec's percent semantics are explicit+/// and the value can't be confused with `Pt`, `HalfPoints`, or other+/// dimensions in the model.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct TextScale(u16);++impl TextScale {+ /// 100% — Word's default character width.+ pub const NORMAL: Self = Self(100);++ /// Construct from a raw percent value. Values outside `1..=600` are+ /// clamped per §17.18.81; `0` is normalized to 100 (Word treats a zero+ /// scale as "use the default").+ pub fn new(percent: u16) -> Self {+ let clamped = match percent {+ 0 => 100,+ 1..=600 => percent,+ _ => 600,+ };+ Self(clamped)+ }++ /// Raw percent in `1..=600`.+ pub fn percent(self) -> u16 {+ self.0+ }++ /// Multiplier as a fraction (e.g. 80 → 0.8, 150 → 1.5).+ pub fn as_factor(self) -> f32 {+ self.0 as f32 / 100.0+ }+}++impl Default for TextScale {+ fn default() -> Self {+ Self::NORMAL+ }+}++/// §17.3.2.20: proofing language specification per script category.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Lang {+ /// Language for Latin text (e.g., "en-US").+ pub val: Option<String>,+ /// Language for East Asian text (e.g., "zh-CN").+ pub east_asia: Option<String>,+ /// Language for complex script text (e.g., "ar-SA").+ pub bidi: Option<String>,+}++/// §17.3.2.26: font theme reference identifiers.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ThemeFontRef {+ MajorHAnsi,+ MajorEastAsia,+ MajorBidi,+ MinorHAnsi,+ MinorEastAsia,+ MinorBidi,+}++/// One script-category font slot — an explicit family name and/or a theme reference.+///+/// §17.3.2.26: when a theme reference is present it is resolved to an actual+/// font name (written into `explicit`) during the resolve phase, overwriting+/// any explicit name — theme references take precedence.+#[derive(Clone, Debug, PartialEq, Eq, Default)]+pub struct FontSlot {+ /// Explicitly named font family (e.g. `"Calibri"`).+ pub explicit: Option<String>,+ /// Theme font reference — resolved to a concrete name during the resolve phase.+ pub theme: Option<ThemeFontRef>,+}++impl FontSlot {+ /// Construct a slot from a plain font-family name with no theme reference.+ pub fn from_name(name: impl Into<String>) -> Self {+ FontSlot {+ explicit: Some(name.into()),+ theme: None,+ }+ }++ /// Merge `base` into `self`: fill any `None` field from `base`.+ ///+ /// Only the `explicit` name is propagated through inheritance — theme+ /// references are resolved into `explicit` before the merge step, so+ /// carrying the raw `ThemeFontRef` through the cascade is unnecessary.+ pub fn merge_from(&mut self, base: &FontSlot) {+ if self.explicit.is_none() {+ self.explicit = base.explicit.clone();+ }+ }+}++/// Font family names for each script category.+///+/// Each field is a [`FontSlot`] that bundles the explicit name and an optional+/// theme reference for that category, keeping related data co-located.+#[derive(Clone, Debug, PartialEq, Eq, Default)]+pub struct FontSet {+ pub ascii: FontSlot,+ pub high_ansi: FontSlot,+ pub east_asian: FontSlot,+ pub complex_script: FontSlot,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum UnderlineStyle {+ None,+ Single,+ Words,+ Double,+ Thick,+ Dotted,+ DottedHeavy,+ Dash,+ DashedHeavy,+ DashLong,+ DashLongHeavy,+ DotDash,+ DashDotHeavy,+ DotDotDash,+ DashDotDotHeavy,+ Wave,+ WavyHeavy,+ WavyDouble,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StrikeStyle {+ None,+ Single,+ Double,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VerticalAlign {+ Baseline,+ Superscript,+ Subscript,+}++#[cfg(test)]+mod text_scale_tests {+ use super::TextScale;++ #[test]+ fn normal_is_100() {+ assert_eq!(TextScale::NORMAL.percent(), 100);+ assert_eq!(TextScale::NORMAL.as_factor(), 1.0);+ }++ #[test]+ fn factor_for_compressed() {+ assert_eq!(TextScale::new(80).as_factor(), 0.8);+ assert_eq!(TextScale::new(50).as_factor(), 0.5);+ }++ #[test]+ fn factor_for_expanded() {+ assert_eq!(TextScale::new(150).as_factor(), 1.5);+ assert_eq!(TextScale::new(200).as_factor(), 2.0);+ }++ #[test]+ fn out_of_range_clamps() {+ // §17.18.81: 1..=600. Above-range values clamp to 600.+ assert_eq!(TextScale::new(700).percent(), 600);+ assert_eq!(TextScale::new(u16::MAX).percent(), 600);+ }++ #[test]+ fn zero_normalizes_to_default() {+ // Word treats 0 as the default 100% rather than rejecting the run.+ assert_eq!(TextScale::new(0), TextScale::NORMAL);+ }+}++/// Highlight colors — fixed palette per OOXML spec (ST_HighlightColor §17.18.40).+///+/// `None` is the spec's explicit "no highlight" override (`<w:highlight w:val="none"/>`),+/// distinct from absence of the element. Mirrors the `UnderlineStyle::None`+/// tri-state convention used elsewhere in `RunProperties`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum HighlightColor {+ None,+ Black,+ Blue,+ Cyan,+ DarkBlue,+ DarkCyan,+ DarkGray,+ DarkGreen,+ DarkMagenta,+ DarkRed,+ DarkYellow,+ Green,+ LightGray,+ Magenta,+ Red,+ White,+ Yellow,+}diff --git a/crates/liteparse-docx/src/model/types/section.rs b/crates/liteparse-docx/src/model/types/section.rsnew file mode 100644index 0000000..a24b737--- /dev/null+++ b/crates/liteparse-docx/src/model/types/section.rs@@ -0,0 +1,132 @@+//! Section properties — page size, margins, columns, headers/footers.++use crate::model::dimension::{Dimension, FractionPoints, Twips};++use super::formatting::NumberFormat;+use super::identifiers::{RelId, SectionRevisionIds};++#[derive(Clone, Debug, Default)]+pub struct SectionProperties {+ pub page_size: Option<PageSize>,+ pub page_margins: Option<PageMargins>,+ pub columns: Option<Columns>,+ /// §17.6.5: document grid for East Asian typography and line pitch.+ pub doc_grid: Option<DocGrid>,+ pub header_refs: SectionHeaderFooterRefs,+ pub footer_refs: SectionHeaderFooterRefs,+ pub title_page: Option<bool>,+ pub section_type: Option<SectionType>,+ /// §17.6.12: page numbering settings for this section.+ pub page_number_type: Option<PageNumberType>,+ pub rsids: SectionRevisionIds,+}++/// §17.6.12: page numbering settings.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct PageNumberType {+ /// §17.18.59 ST_NumberFormat: page number format.+ pub format: Option<NumberFormat>,+ /// Starting page number (overrides sequential).+ pub start: Option<u32>,+ /// Heading style level for chapter numbering (1-indexed).+ pub chap_style: Option<u32>,+ /// §17.18.6 ST_ChapSep: separator between chapter and page number.+ pub chap_sep: Option<ChapterSeparator>,+}++/// §17.18.6 ST_ChapSep — separator between chapter number and page number.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ChapterSeparator {+ Hyphen,+ Period,+ Colon,+ EmDash,+ EnDash,+}++/// §17.6.5: document grid — controls character and line pitch.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct DocGrid {+ /// §17.18.14 ST_DocGrid: type of grid.+ pub grid_type: Option<DocGridType>,+ /// Distance between lines in twips.+ pub line_pitch: Option<Dimension<Twips>>,+ /// Additional character pitch in 4096ths of a point.+ pub char_space: Option<Dimension<FractionPoints>>,+}++/// §17.18.14 ST_DocGrid+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum DocGridType {+ Default,+ Lines,+ LinesAndChars,+ SnapToChars,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SectionType {+ NextPage,+ Continuous,+ EvenPage,+ OddPage,+ NextColumn,+}++#[derive(Clone, Copy, Debug)]+pub struct PageSize {+ pub width: Option<Dimension<Twips>>,+ pub height: Option<Dimension<Twips>>,+ pub orientation: Option<PageOrientation>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PageOrientation {+ Portrait,+ Landscape,+}++#[derive(Clone, Copy, Debug)]+pub struct PageMargins {+ pub top: Option<Dimension<Twips>>,+ pub right: Option<Dimension<Twips>>,+ pub bottom: Option<Dimension<Twips>>,+ pub left: Option<Dimension<Twips>>,+ pub header: Option<Dimension<Twips>>,+ pub footer: Option<Dimension<Twips>>,+ pub gutter: Option<Dimension<Twips>>,+}++#[derive(Clone, Debug)]+pub struct Columns {+ pub count: Option<u32>,+ pub space: Option<Dimension<Twips>>,+ pub equal_width: Option<bool>,+ /// §17.6.4 `w:sep`: draw a vertical rule between columns.+ ///+ /// Parsed and carried so the document is mirrored faithfully; **not drawn**+ /// — see `render::layout::page::compute_columns`, which records it as a+ /// Tier-0 gap. Column positions are unaffected; only the divider is absent.+ pub separator: Option<bool>,+ /// §17.6.3: individual column definitions. Consulted only when+ /// `equal_width` is explicitly `Some(false)` — §17.6.4 defaults the+ /// attribute to `true`, so an absent value means equal widths.+ pub columns: Vec<ColumnDefinition>,+}++/// §17.6.3: a single column definition within a multi-column section.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ColumnDefinition {+ /// Column width in twips.+ pub width: Option<Dimension<Twips>>,+ /// Spacing after this column in twips.+ pub space: Option<Dimension<Twips>>,+}++/// Header/footer references for a section, by position type.+#[derive(Clone, Debug, Default)]+pub struct SectionHeaderFooterRefs {+ pub default: Option<RelId>,+ pub first: Option<RelId>,+ pub even: Option<RelId>,+}diff --git a/crates/liteparse-docx/src/model/types/settings.rs b/crates/liteparse-docx/src/model/types/settings.rsnew file mode 100644index 0000000..ff21898--- /dev/null+++ b/crates/liteparse-docx/src/model/types/settings.rs@@ -0,0 +1,53 @@+//! Document-level settings.++use crate::model::dimension::{Dimension, Twips};++use super::identifiers::RevisionSaveId;++#[derive(Clone, Debug)]+pub struct DocumentSettings {+ /// Default tab stop interval (OOXML default: 720 twips = 0.5 inch).+ pub default_tab_stop: Dimension<Twips>,+ /// Whether even/odd headers/footers are enabled.+ pub even_and_odd_headers: bool,+ /// The rsid of the original editing session that created this document.+ pub rsid_root: Option<RevisionSaveId>,+ /// All revision save IDs recorded in this document's history.+ pub rsids: Vec<RevisionSaveId>,+}++impl Default for DocumentSettings {+ fn default() -> Self {+ Self {+ // §17.15.1.25: when `w:defaultTabStop` is omitted the default tab+ // stop interval is 720 twips (0.5"). A derived `Default` would give+ // 0 here — wrong per spec, and it would silently collapse default+ // tabs for any consumer that reads this field.+ default_tab_stop: Dimension::new(720),+ even_and_odd_headers: false,+ rsid_root: None,+ rsids: Vec::new(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn default_tab_stop_is_720_twips_per_spec() {+ // §17.15.1.25: an omitted `w:defaultTabStop` is 720 twips (0.5"), not+ // the 0 a derived `Default` would produce. Guards against a "simplify+ // to #[derive(Default)]" regression.+ assert_eq!(DocumentSettings::default().default_tab_stop.raw(), 720);+ }++ #[test]+ fn remaining_defaults() {+ let s = DocumentSettings::default();+ assert!(!s.even_and_odd_headers);+ assert!(s.rsid_root.is_none());+ assert!(s.rsids.is_empty());+ }+}diff --git a/crates/liteparse-docx/src/model/types/styles.rs b/crates/liteparse-docx/src/model/types/styles.rsnew file mode 100644index 0000000..33d4b11--- /dev/null+++ b/crates/liteparse-docx/src/model/types/styles.rs@@ -0,0 +1,100 @@+//! Style sheet — style definitions, latent styles, table style overrides.++use std::collections::HashMap;++use super::identifiers::StyleId;+use super::paragraph::ParagraphProperties;+use super::run_properties::RunProperties;+use super::table::{TableCellProperties, TableProperties, TableRowProperties};++/// Raw style definitions as parsed from `word/styles.xml`.+/// No inheritance resolution — `basedOn` references are preserved as-is.+#[derive(Clone, Debug, Default)]+pub struct StyleSheet {+ /// Document-level default paragraph properties (from `w:docDefaults/w:pPrDefault`).+ pub doc_defaults_paragraph: ParagraphProperties,+ /// Document-level default run properties (from `w:docDefaults/w:rPrDefault`).+ pub doc_defaults_run: RunProperties,+ /// All style definitions keyed by style ID.+ pub styles: HashMap<StyleId, Style>,+ /// §17.7.4.5: default properties for styles not explicitly defined.+ pub latent_styles: Option<LatentStyles>,+}++/// §17.7.4.5: default properties for latent (not explicitly defined) styles.+#[derive(Clone, Debug)]+pub struct LatentStyles {+ pub default_locked_state: Option<bool>,+ pub default_ui_priority: Option<u32>,+ pub default_semi_hidden: Option<bool>,+ pub default_unhide_when_used: Option<bool>,+ pub default_q_format: Option<bool>,+ pub count: Option<u32>,+ /// §17.7.4.8: per-style exceptions to the defaults.+ pub exceptions: Vec<LatentStyleException>,+}++/// §17.7.4.8: exception to latent style defaults for a specific style name.+#[derive(Clone, Debug)]+pub struct LatentStyleException {+ pub name: Option<String>,+ pub locked: Option<bool>,+ pub ui_priority: Option<u32>,+ pub semi_hidden: Option<bool>,+ pub unhide_when_used: Option<bool>,+ pub q_format: Option<bool>,+}++/// A single style definition.+#[derive(Clone, Debug)]+pub struct Style {+ pub name: Option<String>,+ pub style_type: StyleType,+ /// Parent style ID. Properties not specified here should be inherited from this style.+ pub based_on: Option<StyleId>,+ pub is_default: bool,+ pub paragraph_properties: Option<ParagraphProperties>,+ pub run_properties: Option<RunProperties>,+ pub table_properties: Option<TableProperties>,+ /// §17.7.6.6: conditional formatting overrides for table regions.+ pub table_style_overrides: Vec<TableStyleOverride>,+}++/// §17.7.6.6: formatting override for a specific table region.+#[derive(Clone, Debug)]+pub struct TableStyleOverride {+ /// Which region this override applies to.+ pub override_type: TableStyleOverrideType,+ pub paragraph_properties: Option<ParagraphProperties>,+ pub run_properties: Option<RunProperties>,+ pub table_properties: Option<TableProperties>,+ pub table_row_properties: Option<TableRowProperties>,+ pub table_cell_properties: Option<TableCellProperties>,+}++/// §17.18.89 ST_TblStyleOverrideType — table region for conditional formatting.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableStyleOverrideType {+ FirstRow,+ LastRow,+ FirstCol,+ LastCol,+ Band1Vert,+ Band2Vert,+ Band1Horz,+ Band2Horz,+ NeCell,+ NwCell,+ SeCell,+ SwCell,+ WholeTable,+}++/// The type of a style definition (§17.7.4.17).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StyleType {+ Paragraph,+ Character,+ Table,+ Numbering,+}diff --git a/crates/liteparse-docx/src/model/types/table.rs b/crates/liteparse-docx/src/model/types/table.rsnew file mode 100644index 0000000..643a671--- /dev/null+++ b/crates/liteparse-docx/src/model/types/table.rs@@ -0,0 +1,235 @@+//! Table types — table, row, cell properties, borders, positioning.++use crate::model::dimension::{Dimension, ThousandthPercent, Twips};+use crate::model::geometry::{EdgeInsets, PartialEdgeInsets};++use super::content::Block;+use super::formatting::{+ Alignment, Border, CnfStyle, HeightRule, Shading, TableAnchor, TableXAlign, TableYAlign,+};+use super::identifiers::TableRowRevisionIds;++#[derive(Clone, Debug)]+pub struct Table {+ pub properties: TableProperties,+ pub grid: Vec<GridColumn>,+ pub rows: Vec<TableRow>,+}++#[derive(Clone, Debug, Default)]+pub struct TableProperties {+ /// §17.4.63: table style reference.+ pub style_id: Option<super::identifiers::StyleId>,+ pub alignment: Option<Alignment>,+ pub width: Option<TableMeasure>,+ pub layout: Option<TableLayout>,+ pub indent: Option<TableMeasure>,+ pub borders: Option<TableBorders>,+ pub cell_margins: Option<EdgeInsets<Twips>>,+ pub cell_spacing: Option<TableMeasure>,+ pub look: Option<TableLook>,+ /// §17.4.68: number of rows in each row band for conditional formatting.+ pub style_row_band_size: Option<u32>,+ /// §17.4.67: number of columns in each column band for conditional formatting.+ pub style_col_band_size: Option<u32>,+ /// §17.4.58: floating table positioning properties.+ pub positioning: Option<TablePositioning>,+ /// §17.4.56: whether this floating table can overlap other floating tables.+ pub overlap: Option<TableOverlap>,+}++/// §17.4.58: floating table positioning.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct TablePositioning {+ pub left_from_text: Option<Dimension<Twips>>,+ pub right_from_text: Option<Dimension<Twips>>,+ pub top_from_text: Option<Dimension<Twips>>,+ pub bottom_from_text: Option<Dimension<Twips>>,+ /// §17.18.106: vertical anchor (text, margin, page).+ pub vert_anchor: Option<TableAnchor>,+ /// §17.18.106: horizontal anchor (text, margin, page).+ pub horz_anchor: Option<TableAnchor>,+ /// §17.18.108: horizontal alignment relative to anchor.+ pub x_align: Option<TableXAlign>,+ /// §17.18.109: vertical alignment relative to anchor.+ pub y_align: Option<TableYAlign>,+ /// Absolute horizontal offset from anchor.+ pub x: Option<Dimension<Twips>>,+ /// Absolute vertical offset from anchor.+ pub y: Option<Dimension<Twips>>,+}++/// §17.4.56 ST_TblOverlap — floating table overlap behavior.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableOverlap {+ Overlap,+ Never,+}++/// A dimension for table/cell widths — may be auto, fixed, or percentage.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableMeasure {+ Auto,+ Twips(Dimension<Twips>),+ /// Percentage in 50ths of a percent (OOXML `pct` type).+ Pct(Dimension<ThousandthPercent>),+ /// Nil — explicitly zero.+ Nil,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TableLayout {+ Auto,+ Fixed,+}++#[derive(Clone, Copy, Debug)]+pub struct GridColumn {+ pub width: Dimension<Twips>,+}++#[derive(Clone, Debug)]+pub struct TableRow {+ pub properties: TableRowProperties,+ pub cells: Vec<TableCell>,+ pub rsids: TableRowRevisionIds,+ /// §17.4.61 `<w:tblPrEx>` — table-level property *exceptions*+ /// scoped to this row. The spec admits the full vocabulary of+ /// `<w:tblPr>` minus tblStyle/tblpPr; we carry only the slice we+ /// honor today (currently borders) and grow as needed. Values+ /// here override the corresponding entries on the table's+ /// `TableProperties` for this row's cells only.+ pub property_exceptions: Option<TableRowPropertyExceptions>,+}++/// §17.4.61 — the subset of `<w:tblPrEx>` we currently honor. Each+/// field, when `Some`, replaces the matching field on the parent+/// table's `TableProperties` for the row that owns this struct;+/// `None` falls through to the table's value.+#[derive(Clone, Debug, Default)]+pub struct TableRowPropertyExceptions {+ /// Per-row replacement for `TableProperties.borders`.+ pub borders: Option<TableBorders>,+ /// §17.4.41: per-row replacement for `TableProperties.cell_spacing`.+ pub cell_spacing: Option<TableMeasure>,+}++#[derive(Clone, Debug, Default)]+pub struct TableRowProperties {+ pub height: Option<TableRowHeight>,+ pub is_header: Option<bool>,+ pub cant_split: Option<bool>,+ /// §17.4.29: alignment of the row with respect to text margins (uses ST_Jc).+ pub justification: Option<Alignment>,+ /// §17.3.1.8: table conditional formatting applied to this row.+ pub cnf_style: Option<CnfStyle>,+ /// §17.4.17: number of grid columns to skip before the first cell of the row.+ /// Default 0 when omitted from `<w:trPr>`.+ pub grid_before: u32,+ /// §17.4.42: row-level override of the table's `tblCellSpacing`.+ pub cell_spacing: Option<TableMeasure>,+ /// §17.4.86: preferred width of the leading space before the first cell.+ /// Note: when present and divergent from the corresponding `tblGrid` columns'+ /// summed widths, treated as informational only — column widths are not+ /// overridden per row in this implementation; a `warn!` is logged on mismatch.+ pub w_before: Option<TableMeasure>,+ /// §17.4.16: number of grid columns to skip after the last cell of the row.+ /// Default 0 when omitted from `<w:trPr>`.+ pub grid_after: u32,+ /// §17.4.85: preferred width of the trailing space after the last cell.+ /// Same width-override caveat as `w_before`.+ pub w_after: Option<TableMeasure>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct TableRowHeight {+ pub value: Dimension<Twips>,+ pub rule: HeightRule,+}++#[derive(Clone, Debug)]+pub struct TableCell {+ pub properties: TableCellProperties,+ pub content: Vec<Block>,+}++/// Table cell properties — only fields explicitly present in the XML are `Some`.+#[derive(Clone, Debug, Default)]+pub struct TableCellProperties {+ pub width: Option<TableMeasure>,+ pub borders: Option<TableCellBorders>,+ pub shading: Option<Shading>,+ /// §17.4.42 `<w:tcMar>` — per-cell margin override. Each side is `Some`+ /// only when explicitly present in the XML; missing sides inherit from+ /// the table-level `<w:tblCellMar>` via `PartialEdgeInsets::resolve_against`.+ pub margins: Option<PartialEdgeInsets<Twips>>,+ pub vertical_align: Option<CellVerticalAlign>,+ /// Vertical merge (w:vMerge): None = not present, Some(Restart) or Some(Continue).+ pub vertical_merge: Option<VerticalMerge>,+ /// Horizontal span (w:gridSpan): None = not present, Some(n) = spans n columns.+ pub grid_span: Option<u32>,+ pub text_direction: Option<TextDirection>,+ pub no_wrap: Option<bool>,+ /// §17.3.1.8: table conditional formatting applied to this cell.+ pub cnf_style: Option<CnfStyle>,+}++/// Vertical merge state from `w:vMerge` attribute.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VerticalMerge {+ /// `w:vMerge val="restart"` — this cell starts a new vertical merge group.+ Restart,+ /// `w:vMerge` (no val or val="continue") — this cell continues from above.+ Continue,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CellVerticalAlign {+ Top,+ Center,+ Bottom,+ Both,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TextDirection {+ LeftToRightTopToBottom,+ TopToBottomRightToLeft,+ BottomToTopLeftToRight,+ LeftToRightTopToBottomRotated,+ TopToBottomRightToLeftRotated,+ TopToBottomLeftToRightRotated,+}++#[derive(Clone, Copy, Debug)]+pub struct TableBorders {+ pub top: Option<Border>,+ pub bottom: Option<Border>,+ pub left: Option<Border>,+ pub right: Option<Border>,+ pub inside_h: Option<Border>,+ pub inside_v: Option<Border>,+}++#[derive(Clone, Copy, Debug)]+pub struct TableCellBorders {+ pub top: Option<Border>,+ pub bottom: Option<Border>,+ pub left: Option<Border>,+ pub right: Option<Border>,+ pub inside_h: Option<Border>,+ pub inside_v: Option<Border>,+ pub tl2br: Option<Border>,+ pub tr2bl: Option<Border>,+}++/// Table conditional formatting flags (ST_TblLook).+#[derive(Clone, Copy, Debug, Default)]+pub struct TableLook {+ pub first_row: Option<bool>,+ pub last_row: Option<bool>,+ pub first_column: Option<bool>,+ pub last_column: Option<bool>,+ pub no_h_band: Option<bool>,+ pub no_v_band: Option<bool>,+}diff --git a/crates/liteparse-docx/src/model/types/theme.rs b/crates/liteparse-docx/src/model/types/theme.rsnew file mode 100644index 0000000..c989626--- /dev/null+++ b/crates/liteparse-docx/src/model/types/theme.rs@@ -0,0 +1,186 @@+//! Theme types — color schemes, font schemes, and script tags.++use super::drawing::{DrawingFill, EffectList, Outline};++/// Resolved theme data from `theme1.xml`.+#[derive(Clone, Debug, Default)]+pub struct Theme {+ pub color_scheme: ThemeColorScheme,+ pub major_font: ThemeFontScheme,+ pub minor_font: ThemeFontScheme,+ /// §20.1.4.1.13 fillStyleLst — theme fill styles referenced via+ /// `<a:fillRef idx="N">`. 0-based in storage — `fillRef idx="1"` is+ /// `fill_styles[0]`. `phClr` inside the fill is substituted by the ref's+ /// color at resolve time.+ pub fill_styles: Vec<DrawingFill>,+ /// §20.1.4.1.21 lnStyleLst — theme line styles referenced via+ /// `<a:lnRef idx="N">`. 0-based in storage — `lnRef idx="1"` is+ /// `line_styles[0]`.+ pub line_styles: Vec<Outline>,+ /// §20.1.4.1.12 effectStyleLst — theme effect styles referenced via+ /// `<a:effectRef idx="N">`. Spec requires exactly 3, so the typical+ /// contents are `[subtle, moderate, intense]`. 0-based in storage —+ /// `effectRef idx="1"` is `effect_styles[0]`.+ pub effect_styles: Vec<EffectList>,+}++#[derive(Clone, Copy, Debug, Default)]+pub struct ThemeColorScheme {+ pub dark1: u32,+ pub light1: u32,+ pub dark2: u32,+ pub light2: u32,+ pub accent1: u32,+ pub accent2: u32,+ pub accent3: u32,+ pub accent4: u32,+ pub accent5: u32,+ pub accent6: u32,+ pub hyperlink: u32,+ pub followed_hyperlink: u32,+}++impl ThemeColorScheme {+ /// Resolve a theme color index to an RGB value.+ pub fn resolve(&self, idx: ThemeColorIndex) -> u32 {+ match idx {+ ThemeColorIndex::Dark1 => self.dark1,+ ThemeColorIndex::Light1 => self.light1,+ ThemeColorIndex::Dark2 => self.dark2,+ ThemeColorIndex::Light2 => self.light2,+ ThemeColorIndex::Accent1 => self.accent1,+ ThemeColorIndex::Accent2 => self.accent2,+ ThemeColorIndex::Accent3 => self.accent3,+ ThemeColorIndex::Accent4 => self.accent4,+ ThemeColorIndex::Accent5 => self.accent5,+ ThemeColorIndex::Accent6 => self.accent6,+ ThemeColorIndex::Hyperlink => self.hyperlink,+ ThemeColorIndex::FollowedHyperlink => self.followed_hyperlink,+ }+ }+}++/// Index into the theme color scheme (ST_ThemeColor).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum ThemeColorIndex {+ Dark1,+ Light1,+ Dark2,+ Light2,+ Accent1,+ Accent2,+ Accent3,+ Accent4,+ Accent5,+ Accent6,+ Hyperlink,+ FollowedHyperlink,+}++#[derive(Clone, Debug, Default)]+pub struct ThemeFontScheme {+ pub latin: String,+ pub east_asian: String,+ pub complex_script: String,+ /// §20.1.4.1.16: per-script font overrides.+ pub script_fonts: Vec<ThemeScriptFont>,+}++/// §20.1.4.1.16: a per-script font mapping in a theme font scheme.+#[derive(Clone, Debug)]+pub struct ThemeScriptFont {+ /// ISO 15924 script code.+ pub script: ScriptTag,+ /// Typeface name for this script.+ pub typeface: String,+}++/// ISO 15924 script codes used in OOXML theme font schemes (§20.1.4.1.16).+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub enum ScriptTag {+ Arab,+ Armn,+ Beng,+ Bopo,+ Bugi,+ Cans,+ Cher,+ Deva,+ Ethi,+ Geor,+ Gujr,+ Guru,+ Hang,+ Hans,+ Hant,+ Hebr,+ Java,+ Jpan,+ Khmr,+ Knda,+ Laoo,+ Lisu,+ Mlym,+ Mong,+ Mymr,+ Nkoo,+ Olck,+ Orya,+ Osma,+ Phag,+ Sinh,+ Sora,+ Syre,+ Syrj,+ Syrn,+ Syrc,+ Tale,+ Talu,+ Taml,+ Telu,+ Tfng,+ Thaa,+ Thai,+ Tibt,+ Uigh,+ Viet,+ Yiii,+ /// Unrecognized script code — preserved as-is.+ Other(Box<str>),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn resolve_maps_each_index_to_its_slot() {+ // Distinct value per slot catches an accidental field swap in `resolve`.+ let cs = ThemeColorScheme {+ dark1: 1,+ light1: 2,+ dark2: 3,+ light2: 4,+ accent1: 5,+ accent2: 6,+ accent3: 7,+ accent4: 8,+ accent5: 9,+ accent6: 10,+ hyperlink: 11,+ followed_hyperlink: 12,+ };+ assert_eq!(cs.resolve(ThemeColorIndex::Dark1), 1);+ assert_eq!(cs.resolve(ThemeColorIndex::Light1), 2);+ assert_eq!(cs.resolve(ThemeColorIndex::Dark2), 3);+ assert_eq!(cs.resolve(ThemeColorIndex::Light2), 4);+ assert_eq!(cs.resolve(ThemeColorIndex::Accent1), 5);+ assert_eq!(cs.resolve(ThemeColorIndex::Accent2), 6);+ assert_eq!(cs.resolve(ThemeColorIndex::Accent3), 7);+ assert_eq!(cs.resolve(ThemeColorIndex::Accent4), 8);+ assert_eq!(cs.resolve(ThemeColorIndex::Accent5), 9);+ assert_eq!(cs.resolve(ThemeColorIndex::Accent6), 10);+ assert_eq!(cs.resolve(ThemeColorIndex::Hyperlink), 11);+ assert_eq!(cs.resolve(ThemeColorIndex::FollowedHyperlink), 12);+ }+}diff --git a/crates/liteparse-docx/src/model/types/vml.rs b/crates/liteparse-docx/src/model/types/vml.rsnew file mode 100644index 0000000..6842ac6--- /dev/null+++ b/crates/liteparse-docx/src/model/types/vml.rs@@ -0,0 +1,1168 @@+//! VML (Vector Markup Language) types — legacy shapes, paths, formulas, styling.++use super::content::Block;+use super::identifiers::{RelId, VmlShapeId};++/// §17.3.3.19: VML picture container. Wraps legacy VML shape content.+///+/// The `<w:pict>` element admits any of the VML primitive shape+/// elements (§14.1.2): `<v:shape>`, `<v:rect>`, `<v:roundrect>`,+/// `<v:oval>`, `<v:line>`, `<v:polyline>`, `<v:arc>`, `<v:curve>`,+/// `<v:image>`, `<v:group>`. We model the choice as a tagged enum+/// (`VmlPrimitive`) so each variant carries its element-specific+/// shape, while sharing common style/fill/stroke/etc. via+/// `VmlCommonAttrs`.+#[derive(Clone, Debug)]+pub struct Pict {+ /// VML §14.1.2.20: optional reusable shape type definition.+ pub shape_type: Option<VmlShapeType>,+ /// VML §14.1.2.* — primitive shape children in document order.+ pub primitives: Vec<VmlPrimitive>,+}++impl Pict {+ /// Convenience accessor: yields every `VmlShape` (the generic+ /// `<v:shape>` variant). Other primitive variants are skipped.+ /// Use this where the caller only handles `<v:shape>` today —+ /// new code should match on `VmlPrimitive` directly.+ pub fn shapes(&self) -> impl Iterator<Item = &VmlShape> {+ self.primitives.iter().filter_map(|p| match p {+ VmlPrimitive::Shape(s) => Some(s),+ _ => None,+ })+ }++ /// Mutable counterpart to [`Pict::shapes`].+ pub fn shapes_mut(&mut self) -> impl Iterator<Item = &mut VmlShape> {+ self.primitives.iter_mut().filter_map(|p| match p {+ VmlPrimitive::Shape(s) => Some(s),+ _ => None,+ })+ }+}++/// VML §14.1.2 — every primitive shape child of `<w:pict>`. Variants+/// share a `VmlCommonAttrs` payload accessed via [`VmlPrimitive::common`].+#[derive(Clone, Debug)]+pub enum VmlPrimitive {+ /// `<v:shape>` — generic shape with shapetype reference or own path.+ Shape(VmlShape),+ /// `<v:rect>` (§14.1.2.16) — bounding-box rectangle.+ Rect(VmlRect),+ /// `<v:roundrect>` (§14.1.2.17) — `@arcsize` corner radius.+ RoundRect(VmlRoundRect),+ /// `<v:oval>` (§14.1.2.13).+ Oval(VmlOval),+ /// `<v:line>` (§14.1.2.12) — `@from`/`@to` endpoints.+ Line(VmlLine),+ /// `<v:polyline>` (§14.1.2.15) — `@points` list.+ PolyLine(VmlPolyLine),+ /// `<v:arc>` (§14.1.2.3) — `@startangle`/`@endangle`.+ Arc(VmlArc),+ /// `<v:curve>` (§14.1.2.7) — Bezier with two control points.+ Curve(VmlCurve),+ /// `<v:image>` (§14.1.2.10) — image element with `@src`.+ Image(VmlImage),+ /// `<v:group>` (§14.1.2.9) — recursive shape grouping with its+ /// own coordinate system.+ Group(Box<VmlGroup>),+}++impl VmlPrimitive {+ /// Borrow the common attribute set every variant carries.+ pub fn common(&self) -> &VmlCommonAttrs {+ match self {+ VmlPrimitive::Shape(s) => &s.common,+ VmlPrimitive::Rect(r) => &r.common,+ VmlPrimitive::RoundRect(r) => &r.common,+ VmlPrimitive::Oval(o) => &o.common,+ VmlPrimitive::Line(l) => &l.common,+ VmlPrimitive::PolyLine(p) => &p.common,+ VmlPrimitive::Arc(a) => &a.common,+ VmlPrimitive::Curve(c) => &c.common,+ VmlPrimitive::Image(i) => &i.common,+ VmlPrimitive::Group(g) => &g.common,+ }+ }++ /// Mutable counterpart to [`VmlPrimitive::common`].+ pub fn common_mut(&mut self) -> &mut VmlCommonAttrs {+ match self {+ VmlPrimitive::Shape(s) => &mut s.common,+ VmlPrimitive::Rect(r) => &mut r.common,+ VmlPrimitive::RoundRect(r) => &mut r.common,+ VmlPrimitive::Oval(o) => &mut o.common,+ VmlPrimitive::Line(l) => &mut l.common,+ VmlPrimitive::PolyLine(p) => &mut p.common,+ VmlPrimitive::Arc(a) => &mut a.common,+ VmlPrimitive::Curve(c) => &mut c.common,+ VmlPrimitive::Image(i) => &mut i.common,+ VmlPrimitive::Group(g) => &mut g.common,+ }+ }+}++/// VML §14.1.2.18 CoreAttributes plus the shared child elements every+/// primitive admits: `<v:fill>`, `<v:stroke>`, `<v:textbox>`,+/// `<v:wrap>`, `<v:imagedata>`. Extracting these out of `VmlShape`+/// lets every other primitive type share the same parse-and-render+/// machinery without copying ten fields.+#[derive(Clone, Debug, Default)]+pub struct VmlCommonAttrs {+ /// Shape identifier.+ pub id: Option<VmlShapeId>,+ /// Parsed CSS2 style properties.+ pub style: VmlStyle,+ /// `@fillcolor` attribute fill color.+ pub fill_color: Option<VmlColor>,+ /// Whether the shape has a stroke.+ pub stroked: Option<bool>,+ /// VML §14.1.2.21: stroke child element.+ pub stroke: Option<VmlStroke>,+ /// VML §14.1.2.22: text box child element.+ pub text_box: Option<VmlTextBox>,+ /// VML §14.1.2.23: text wrapping around shape.+ pub wrap: Option<VmlWrap>,+ /// VML §14.1.2.11: image data reference.+ pub image_data: Option<VmlImageData>,+ /// VML §14.1.2.5 `<v:fill>` — fill child element. When present,+ /// overrides the `@fillcolor` attribute. Carries gradient/pattern/+ /// image fill specifications that the attribute can't express.+ pub fill: Option<VmlFill>,+}++/// VML §14.1.2.5 `<v:fill>` — fill specification on any shape.+///+/// The element carries many attributes; we model the most-used+/// subset and grow on demand. Non-solid fills (gradient/tile/pattern/+/// frame) are modeled but only `Solid` is renderered today; the+/// renderer falls through with a one-time `log::warn!` for the rest.+#[derive(Clone, Debug, Default)]+pub struct VmlFill {+ /// `@type` — fill kind. Defaults to `Solid` when omitted (matches+ /// spec).+ pub fill_type: VmlFillType,+ /// `@color` — primary color (used by Solid and most gradient+ /// types as the start color).+ pub color: Option<VmlColor>,+ /// `@color2` — secondary color (gradient end / pattern bg).+ pub color2: Option<VmlColor>,+ /// `@opacity` — 0..1; missing means opaque.+ pub opacity: Option<f32>,+ /// `@src` — relative path to a fill image (Tile/Frame).+ pub src: Option<String>,+ /// `r:id` — relationship-ID alternative to `@src` for fill image.+ pub rel_id: Option<RelId>,+}++/// VML §14.1.2.5 `@type` values. The spec also defines+/// `gradientCenter` and `gradientUnscaled`, which we treat as+/// gradient kinds.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum VmlFillType {+ /// Solid color (default).+ #[default]+ Solid,+ /// Linear/axial gradient.+ Gradient,+ /// Radial gradient.+ GradientRadial,+ /// Tiled image fill.+ Tile,+ /// Frame (single-image) fill.+ Frame,+ /// Pattern fill with foreground/background colors.+ Pattern,+}++/// VML §14.1.2.16 `<v:rect>` — bounding-box rectangle.+#[derive(Clone, Debug)]+pub struct VmlRect {+ pub common: VmlCommonAttrs,+}++/// VML §14.1.2.17 `<v:roundrect>` — rectangle with rounded corners.+#[derive(Clone, Debug)]+pub struct VmlRoundRect {+ pub common: VmlCommonAttrs,+ /// `@arcsize` — corner radius as fraction of the smaller half-side.+ /// Stored as 0..=1; the spec admits values up to 0.5 in practice+ /// but Word emits up to 1.0.+ pub arcsize: Option<f32>,+}++/// VML §14.1.2.13 `<v:oval>`.+#[derive(Clone, Debug)]+pub struct VmlOval {+ pub common: VmlCommonAttrs,+}++/// VML §14.1.2.12 `<v:line>` — single segment between two points.+#[derive(Clone, Debug)]+pub struct VmlLine {+ pub common: VmlCommonAttrs,+ pub from: Option<VmlPoint>,+ pub to: Option<VmlPoint>,+}++/// VML §14.1.2.15 `<v:polyline>`.+#[derive(Clone, Debug)]+pub struct VmlPolyLine {+ pub common: VmlCommonAttrs,+ pub points: Vec<VmlPoint>,+}++/// VML §14.1.2.3 `<v:arc>`.+#[derive(Clone, Debug)]+pub struct VmlArc {+ pub common: VmlCommonAttrs,+ pub start_angle: Option<f32>,+ pub end_angle: Option<f32>,+}++/// VML §14.1.2.7 `<v:curve>` — cubic Bezier from `from` to `to` with+/// two control points.+#[derive(Clone, Debug)]+pub struct VmlCurve {+ pub common: VmlCommonAttrs,+ pub from: Option<VmlPoint>,+ pub control1: Option<VmlPoint>,+ pub control2: Option<VmlPoint>,+ pub to: Option<VmlPoint>,+}++/// VML §14.1.2.10 `<v:image>` — image element with `@src` attribute.+/// Distinct from `<v:shape>`+`<v:imagedata>` even though the rendering+/// outcome can be identical.+#[derive(Clone, Debug)]+pub struct VmlImage {+ pub common: VmlCommonAttrs,+ /// `@src` — file path or URL of the image.+ pub src: Option<String>,+}++/// VML §14.1.2.9 `<v:group>` — nested primitives with their own+/// coordinate system.+#[derive(Clone, Debug)]+pub struct VmlGroup {+ pub common: VmlCommonAttrs,+ /// Coordinate space declared by the group (`@coordsize`).+ pub coord_size: Option<VmlVector2D>,+ /// Origin of the group's coord space (`@coordorigin`).+ pub coord_origin: Option<VmlVector2D>,+ /// Child primitives in the group's coordinate system.+ pub children: Vec<VmlPrimitive>,+}++/// VML 2D point — typically `(x,y)` in the parent coord space.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct VmlPoint {+ pub x: f32,+ pub y: f32,+}++// ── Path Commands ────────────────────────────────────────────────────────────++/// VML §14.2.1.6: path coordinate — literal integer or `@n` formula reference.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlPathCoord {+ /// Literal integer coordinate value.+ Literal(i64),+ /// `@n` — reference to formula result n.+ FormulaRef(u32),+}++/// VML §14.2.1.6: a single path command in the shape path language.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlPathCommand {+ /// `m x,y` — move to absolute position.+ MoveTo { x: VmlPathCoord, y: VmlPathCoord },+ /// `l x,y` — line to absolute position.+ LineTo { x: VmlPathCoord, y: VmlPathCoord },+ /// `c x1,y1,x2,y2,x,y` — cubic bezier to absolute position.+ CurveTo {+ x1: VmlPathCoord,+ y1: VmlPathCoord,+ x2: VmlPathCoord,+ y2: VmlPathCoord,+ x: VmlPathCoord,+ y: VmlPathCoord,+ },+ /// `r dx,dy` — relative line to.+ RLineTo { dx: VmlPathCoord, dy: VmlPathCoord },+ /// `v dx1,dy1,dx2,dy2,dx,dy` — relative cubic bezier.+ RCurveTo {+ dx1: VmlPathCoord,+ dy1: VmlPathCoord,+ dx2: VmlPathCoord,+ dy2: VmlPathCoord,+ dx: VmlPathCoord,+ dy: VmlPathCoord,+ },+ /// `t dx,dy` — relative move to.+ RMoveTo { dx: VmlPathCoord, dy: VmlPathCoord },+ /// `x` — close subpath.+ Close,+ /// `e` — end of path.+ End,+ /// `qx x,y` — elliptical quadrant, x-axis first.+ QuadrantX { x: VmlPathCoord, y: VmlPathCoord },+ /// `qy x,y` — elliptical quadrant, y-axis first.+ QuadrantY { x: VmlPathCoord, y: VmlPathCoord },+ /// `nf` — no fill for following subpath.+ NoFill,+ /// `ns` — no stroke for following subpath.+ NoStroke,+ /// `wa/wr/at/ar x1,y1,x2,y2,x3,y3,x4,y4` — arc commands.+ Arc {+ /// `wa` (angle clockwise), `wr` (angle counter-clockwise),+ /// `at` (to clockwise), `ar` (to counter-clockwise).+ kind: VmlArcKind,+ bounding_x1: VmlPathCoord,+ bounding_y1: VmlPathCoord,+ bounding_x2: VmlPathCoord,+ bounding_y2: VmlPathCoord,+ start_x: VmlPathCoord,+ start_y: VmlPathCoord,+ end_x: VmlPathCoord,+ end_y: VmlPathCoord,+ },+}++/// VML §14.2.1.6: arc sub-type.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlArcKind {+ /// `wa` — clockwise arc (angle).+ WA,+ /// `wr` — counter-clockwise arc (angle).+ WR,+ /// `at` — clockwise arc (to point).+ AT,+ /// `ar` — counter-clockwise arc (to point).+ AR,+}++// ── Formulas ─────────────────────────────────────────────────────────────────++/// VML §14.1.2.6: a single formula equation (`v:f eqn="..."`).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct VmlFormula {+ pub operation: VmlFormulaOp,+ pub args: [VmlFormulaArg; 3],+}++/// VML §14.1.2.6: formula operations.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlFormulaOp {+ /// `val` — returns arg1.+ Val,+ /// `sum` — arg1 + arg2 - arg3.+ Sum,+ /// `product` — arg1 * arg2 / arg3.+ Product,+ /// `mid` — (arg1 + arg2) / 2.+ Mid,+ /// `abs` — |arg1|.+ Abs,+ /// `min` — min(arg1, arg2).+ Min,+ /// `max` — max(arg1, arg2).+ Max,+ /// `if` — if arg1 > 0 then arg2 else arg3.+ If,+ /// `sqrt` — sqrt(arg1).+ Sqrt,+ /// `mod` — sqrt(arg1² + arg2² + arg3²).+ Mod,+ /// `sin` — arg1 * sin(arg2).+ Sin,+ /// `cos` — arg1 * cos(arg2).+ Cos,+ /// `tan` — arg1 * tan(arg2).+ Tan,+ /// `atan2` — atan2(arg1, arg2) in fd units.+ Atan2,+ /// `sinatan2` — arg1 * sin(atan2(arg2, arg3)).+ SinAtan2,+ /// `cosatan2` — arg1 * cos(atan2(arg2, arg3)).+ CosAtan2,+ /// `sumangle` — arg1 + arg2 * 2^16 - arg3 * 2^16 (angle arithmetic).+ SumAngle,+ /// `ellipse` — arg3 * sqrt(1 - (arg1/arg2)²).+ Ellipse,+}++/// VML §14.1.2.6: formula argument — a reference or literal.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlFormulaArg {+ /// Integer literal.+ Literal(i64),+ /// `#n` — adjustment value reference.+ AdjRef(u32),+ /// `@n` — formula result reference.+ FormulaRef(u32),+ /// Named guide value (width, height, xcenter, ycenter, etc.).+ Guide(VmlGuide),+}++/// VML §14.1.2.6: named guide constants available in formulas.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlGuide {+ Width,+ Height,+ XCenter,+ YCenter,+ XRange,+ YRange,+ PixelWidth,+ PixelHeight,+ PixelLineWidth,+ EmuWidth,+ EmuHeight,+ EmuWidth2,+ EmuHeight2,+}++// ── Shape Types and Shapes ───────────────────────────────────────────────────++/// VML Vector2D — unitless coordinate pair (e.g., coordsize="21600,21600").+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VmlVector2D {+ pub x: i64,+ pub y: i64,+}++/// VML §14.1.2.20: shape type definition (reusable template for shapes).+#[derive(Clone, Debug)]+pub struct VmlShapeType {+ /// Shape type identifier (e.g., "_x0000_t202").+ pub id: Option<VmlShapeId>,+ /// Coordinate space for the shape (VML Vector2D, e.g., 21600,21600).+ pub coord_size: Option<VmlVector2D>,+ /// o:spt — shape type number (Office extension, xsd:float).+ pub spt: Option<f32>,+ /// Adjustment values for parameterized shapes (comma-separated integers).+ pub adj: Vec<i64>,+ /// VML §14.2.1.6: parsed shape path commands.+ pub path: Vec<VmlPathCommand>,+ /// Whether the shape is filled by default.+ pub filled: Option<bool>,+ /// Whether the shape is stroked by default.+ pub stroked: Option<bool>,+ /// VML §14.1.2.21: stroke child element.+ pub stroke: Option<VmlStroke>,+ /// VML §14.1.2.14: path child element.+ pub vml_path: Option<VmlPath>,+ /// VML §14.1.2.6: formula definitions.+ pub formulas: Vec<VmlFormula>,+ /// Office VML extension: editing locks.+ pub lock: Option<VmlLock>,+}++/// VML §14.1.2.19 `<v:shape>` — generic shape instance, optionally+/// referencing a `<v:shapetype>` and/or carrying its own path.+/// Common attribute and child elements live on+/// [`VmlCommonAttrs`]; only shape-specific fields stay here.+#[derive(Clone, Debug)]+pub struct VmlShape {+ /// Common attribute group + shared children.+ pub common: VmlCommonAttrs,+ /// `@type` — reference to a shapetype id (e.g., "#_x0000_t202").+ pub shape_type_ref: Option<VmlShapeId>,+ /// VML §14.1.2.14 `<v:path>` — explicit path child element.+ pub vml_path: Option<VmlPath>,+}++// ── Wrapping ─────────────────────────────────────────────────────────────────++/// VML §14.1.2.23: text wrapping element.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VmlWrap {+ /// Wrapping type.+ pub wrap_type: Option<VmlWrapType>,+ /// Which side(s) text wraps on.+ pub side: Option<VmlWrapSide>,+}++/// VML §14.1.2.23: wrap type values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlWrapType {+ TopAndBottom,+ Square,+ None,+ Tight,+ Through,+}++/// VML §14.1.2.23: wrap side values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlWrapSide {+ Both,+ Left,+ Right,+ Largest,+}++// ── Lock / Extension ─────────────────────────────────────────────────────────++/// Office VML extension: editing locks on a shape type or shape.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VmlLock {+ /// Lock aspect ratio.+ pub aspect_ratio: Option<bool>,+ /// v:ext — extension handling mode.+ pub ext: Option<VmlExtHandling>,+}++/// VML v:ext — extension handling mode.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlExtHandling {+ Edit,+ View,+ BackwardCompatible,+}++// ── Image Data ───────────────────────────────────────────────────────────────++/// VML §14.1.2.11: image data reference.+#[derive(Clone, Debug)]+pub struct VmlImageData {+ /// r:id — relationship ID to the image part.+ pub rel_id: Option<RelId>,+ /// o:title — image title/alt text.+ pub title: Option<String>,+}++// ── VML Style ────────────────────────────────────────────────────────────────++/// VML style — parsed CSS2 properties from the `style` attribute (§14.1.2.19).+#[derive(Clone, Debug, Default)]+pub struct VmlStyle {+ /// CSS `position`.+ pub position: Option<CssPosition>,+ /// CSS `left`.+ pub left: Option<VmlLength>,+ /// CSS `top`.+ pub top: Option<VmlLength>,+ /// CSS `width`.+ pub width: Option<VmlLength>,+ /// CSS `height`.+ pub height: Option<VmlLength>,+ /// CSS `margin-left`.+ pub margin_left: Option<VmlLength>,+ /// CSS `margin-top`.+ pub margin_top: Option<VmlLength>,+ /// CSS `margin-right`.+ pub margin_right: Option<VmlLength>,+ /// CSS `margin-bottom`.+ pub margin_bottom: Option<VmlLength>,+ /// CSS `z-index`.+ pub z_index: Option<i64>,+ /// CSS `rotation` (degrees).+ pub rotation: Option<f64>,+ /// VML `flip`.+ pub flip: Option<VmlFlip>,+ /// CSS `visibility`.+ pub visibility: Option<CssVisibility>,+ /// Office `mso-position-horizontal`.+ pub mso_position_horizontal: Option<MsoPositionH>,+ /// Office `mso-position-horizontal-relative`.+ pub mso_position_horizontal_relative: Option<MsoPositionHRelative>,+ /// Office `mso-position-vertical`.+ pub mso_position_vertical: Option<MsoPositionV>,+ /// Office `mso-position-vertical-relative`.+ pub mso_position_vertical_relative: Option<MsoPositionVRelative>,+ /// Office `mso-wrap-distance-left`.+ pub mso_wrap_distance_left: Option<VmlLength>,+ /// Office `mso-wrap-distance-right`.+ pub mso_wrap_distance_right: Option<VmlLength>,+ /// Office `mso-wrap-distance-top`.+ pub mso_wrap_distance_top: Option<VmlLength>,+ /// Office `mso-wrap-distance-bottom`.+ pub mso_wrap_distance_bottom: Option<VmlLength>,+ /// Office `mso-wrap-style`.+ pub mso_wrap_style: Option<MsoWrapStyle>,+}++// ── VML Color ────────────────────────────────────────────────────────────────++/// VML color value (§14.1.2.1 ST_ColorType).+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub enum VmlColor {+ /// Hex-specified sRGB color (r, g, b).+ Rgb(u8, u8, u8),+ /// Predefined named color.+ Named(VmlNamedColor),+}++/// VML/CSS named colors (§14.1.2.1, CSS2.1 §4.3.6, and SVG/CSS3 extended colors).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum VmlNamedColor {+ // CSS2.1 §4.3.6 — the 17 standard colors.+ Black,+ Silver,+ Gray,+ White,+ Maroon,+ Red,+ Purple,+ Fuchsia,+ Green,+ Lime,+ Olive,+ Yellow,+ Navy,+ Blue,+ Teal,+ Aqua,+ Orange,+ // SVG/CSS3 extended named colors used in Office documents.+ AliceBlue,+ AntiqueWhite,+ Beige,+ Bisque,+ BlanchedAlmond,+ BlueViolet,+ Brown,+ BurlyWood,+ CadetBlue,+ Chartreuse,+ Chocolate,+ Coral,+ CornflowerBlue,+ Cornsilk,+ Crimson,+ Cyan,+ DarkBlue,+ DarkCyan,+ DarkGoldenrod,+ DarkGray,+ DarkGreen,+ DarkKhaki,+ DarkMagenta,+ DarkOliveGreen,+ DarkOrange,+ DarkOrchid,+ DarkRed,+ DarkSalmon,+ DarkSeaGreen,+ DarkSlateBlue,+ DarkSlateGray,+ DarkTurquoise,+ DarkViolet,+ DeepPink,+ DeepSkyBlue,+ DimGray,+ DodgerBlue,+ Firebrick,+ FloralWhite,+ ForestGreen,+ Gainsboro,+ GhostWhite,+ Gold,+ Goldenrod,+ GreenYellow,+ Honeydew,+ HotPink,+ IndianRed,+ Indigo,+ Ivory,+ Khaki,+ Lavender,+ LavenderBlush,+ LawnGreen,+ LemonChiffon,+ LightBlue,+ LightCoral,+ LightCyan,+ LightGoldenrodYellow,+ LightGray,+ LightGreen,+ LightPink,+ LightSalmon,+ LightSeaGreen,+ LightSkyBlue,+ LightSlateGray,+ LightSteelBlue,+ LightYellow,+ LimeGreen,+ Linen,+ Magenta,+ MediumAquamarine,+ MediumBlue,+ MediumOrchid,+ MediumPurple,+ MediumSeaGreen,+ MediumSlateBlue,+ MediumSpringGreen,+ MediumTurquoise,+ MediumVioletRed,+ MidnightBlue,+ MintCream,+ MistyRose,+ Moccasin,+ NavajoWhite,+ OldLace,+ OliveDrab,+ OrangeRed,+ Orchid,+ PaleGoldenrod,+ PaleGreen,+ PaleTurquoise,+ PaleVioletRed,+ PapayaWhip,+ PeachPuff,+ Peru,+ Pink,+ Plum,+ PowderBlue,+ RosyBrown,+ RoyalBlue,+ SaddleBrown,+ Salmon,+ SandyBrown,+ SeaGreen,+ Seashell,+ Sienna,+ SkyBlue,+ SlateBlue,+ SlateGray,+ Snow,+ SpringGreen,+ SteelBlue,+ Tan,+ Thistle,+ Tomato,+ Turquoise,+ Violet,+ Wheat,+ WhiteSmoke,+ YellowGreen,+ // VML §14.1.2.1 system colors.+ ButtonFace,+ ButtonHighlight,+ ButtonShadow,+ ButtonText,+ CaptionText,+ GrayText,+ Highlight,+ HighlightText,+ InactiveBorder,+ InactiveCaption,+ InactiveCaptionText,+ InfoBackground,+ InfoText,+ Menu,+ MenuText,+ Scrollbar,+ ThreeDDarkShadow,+ ThreeDFace,+ ThreeDHighlight,+ ThreeDLightShadow,+ ThreeDShadow,+ Window,+ WindowFrame,+ WindowText,+}++// ── CSS Enums ────────────────────────────────────────────────────────────────++/// CSS2 `position` property values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CssPosition {+ Static,+ Relative,+ Absolute,+}++/// CSS2 `visibility` property values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CssVisibility {+ Visible,+ Hidden,+ Inherit,+}++/// VML `flip` attribute values (§14.1.2.19).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlFlip {+ /// Flip along the x-axis.+ X,+ /// Flip along the y-axis.+ Y,+ /// Flip along both axes.+ XY,+}++// ── MSO Position / Wrap ──────────────────────────────────────────────────────++/// Office `mso-position-horizontal` values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MsoPositionH {+ Absolute,+ Left,+ Center,+ Right,+ Inside,+ Outside,+}++/// Office `mso-position-horizontal-relative` values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MsoPositionHRelative {+ Margin,+ Page,+ Text,+ Char,+ LeftMarginArea,+ RightMarginArea,+ InnerMarginArea,+ OuterMarginArea,+}++/// Office `mso-position-vertical` values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MsoPositionV {+ Absolute,+ Top,+ Center,+ Bottom,+ Inside,+ Outside,+}++/// Office `mso-position-vertical-relative` values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MsoPositionVRelative {+ Margin,+ Page,+ Text,+ Line,+ TopMarginArea,+ BottomMarginArea,+ InnerMarginArea,+ OuterMarginArea,+}++/// Office `mso-wrap-style` values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MsoWrapStyle {+ Square,+ None,+ Tight,+ Through,+}++// ── VML Length ────────────────────────────────────────────────────────────────++/// A CSS length value with unit.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct VmlLength {+ pub value: f64,+ pub unit: VmlLengthUnit,+}++impl VmlLength {+ /// Convert to points when the unit is *absolute*.+ ///+ /// Returns `None` for units this type cannot resolve on its own:+ ///+ /// * [`VmlLengthUnit::Percent`] and [`VmlLengthUnit::Em`] are relative to a+ /// containing box or font size that only the caller knows.+ /// * [`VmlLengthUnit::None`] — a bare number — means different things in+ /// different attributes: EMU in a `style` measurement, but *local+ /// coordinate units* (relative to `coordsize`) on a primitive's+ /// `from`/`to`/`points`. Callers apply the rule for their own context.+ ///+ /// This carries only the arithmetic that is context-free, so every caller+ /// shares one unit table instead of restating it.+ pub fn to_absolute_points(&self) -> Option<f32> {+ let v = self.value as f32;+ Some(match self.unit {+ VmlLengthUnit::Pt => v,+ VmlLengthUnit::In => v * 72.0,+ VmlLengthUnit::Cm => v * 72.0 / 2.54,+ VmlLengthUnit::Mm => v * 72.0 / 25.4,+ // CSS reference pixel: 96dpi → 72pt/in.+ VmlLengthUnit::Px => v * 0.75,+ VmlLengthUnit::Em | VmlLengthUnit::Percent | VmlLengthUnit::None => return None,+ })+ }+}++/// CSS length unit.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlLengthUnit {+ /// Points (pt).+ Pt,+ /// Inches (in).+ In,+ /// Centimeters (cm).+ Cm,+ /// Millimeters (mm).+ Mm,+ /// Pixels (px).+ Px,+ /// Em units (em).+ Em,+ /// Percentage (%).+ Percent,+ /// No unit (bare number, treated as EMU in VML context).+ None,+}++// ── Stroke ───────────────────────────────────────────────────────────────────++/// VML §14.1.2.21: stroke styling.+#[derive(Clone, Debug)]+pub struct VmlStroke {+ /// Dash pattern.+ pub dash_style: Option<VmlDashStyle>,+ /// Line join style.+ pub join_style: Option<VmlJoinStyle>,+}++/// VML §14.1.2.21: stroke dash patterns.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlDashStyle {+ Solid,+ ShortDash,+ ShortDot,+ ShortDashDot,+ ShortDashDotDot,+ Dot,+ Dash,+ LongDash,+ DashDot,+ LongDashDot,+ LongDashDotDot,+}++/// VML §14.1.2.21: line join styles.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlJoinStyle {+ Round,+ Bevel,+ Miter,+}++// ── Path Properties ──────────────────────────────────────────────────────────++/// VML §14.1.2.14: path properties.+#[derive(Clone, Debug)]+pub struct VmlPath {+ /// o:gradientshapeok — whether the path supports gradient fill.+ pub gradient_shape_ok: Option<bool>,+ /// o:connecttype — connection point type.+ pub connect_type: Option<VmlConnectType>,+ /// o:extrusionok — whether the path supports 3D extrusion.+ pub extrusion_ok: Option<bool>,+}++/// VML o:connecttype — how connection points are defined on the shape.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VmlConnectType {+ /// No connection points.+ None,+ /// Four connection points at the rectangle midpoints.+ Rect,+ /// Connection points derived from path segments.+ Segments,+ /// Custom connection points.+ Custom,+}++// ── Text Box ─────────────────────────────────────────────────────────────────++/// VML §14.1.2.22: text box inset margins (comma-separated CSS lengths).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct VmlTextBoxInset {+ pub left: Option<VmlLength>,+ pub top: Option<VmlLength>,+ pub right: Option<VmlLength>,+ pub bottom: Option<VmlLength>,+}++/// VML §14.1.2.22: text box within a shape.+#[derive(Clone, Debug)]+pub struct VmlTextBox {+ /// Parsed CSS2 style properties.+ pub style: VmlStyle,+ /// VML §14.1.2.22: inset margins (top, left, bottom, right).+ pub inset: Option<VmlTextBoxInset>,+ /// §17.17.1: block-level content from w:txbxContent.+ pub content: Vec<Block>,+}++#[cfg(test)]+mod tests {+ use super::*;++ fn common_with_id(id: &str) -> VmlCommonAttrs {+ VmlCommonAttrs {+ id: Some(VmlShapeId::new(id)),+ ..Default::default()+ }+ }++ fn shape(id: &str) -> VmlPrimitive {+ VmlPrimitive::Shape(VmlShape {+ common: common_with_id(id),+ shape_type_ref: None,+ vml_path: None,+ })+ }++ #[test]+ fn pict_shapes_filters_to_shape_variant() {+ // Only the `<v:shape>` primitives are yielded; rect/oval are skipped.+ let pict = Pict {+ shape_type: None,+ primitives: vec![+ shape("s1"),+ VmlPrimitive::Rect(VmlRect {+ common: common_with_id("r1"),+ }),+ shape("s2"),+ VmlPrimitive::Oval(VmlOval {+ common: common_with_id("o1"),+ }),+ ],+ };+ let ids: Vec<&str> = pict+ .shapes()+ .map(|s| s.common.id.as_ref().unwrap().as_str())+ .collect();+ assert_eq!(ids, ["s1", "s2"]);+ }++ #[test]+ fn pict_shapes_mut_allows_mutation() {+ let mut pict = Pict {+ shape_type: None,+ primitives: vec![shape("s1")],+ };+ for s in pict.shapes_mut() {+ s.common.id = Some(VmlShapeId::new("changed"));+ }+ assert_eq!(+ pict.shapes()+ .next()+ .unwrap()+ .common+ .id+ .as_ref()+ .unwrap()+ .as_str(),+ "changed"+ );+ }++ /// Every `VmlPrimitive` variant must return its own `common` — guards the+ /// large match in `common()` against a mis-wired arm.+ #[test]+ fn common_returns_each_variants_attrs() {+ let variants = [+ shape("a"),+ VmlPrimitive::Rect(VmlRect {+ common: common_with_id("b"),+ }),+ VmlPrimitive::RoundRect(VmlRoundRect {+ common: common_with_id("c"),+ arcsize: None,+ }),+ VmlPrimitive::Oval(VmlOval {+ common: common_with_id("d"),+ }),+ VmlPrimitive::Line(VmlLine {+ common: common_with_id("e"),+ from: None,+ to: None,+ }),+ VmlPrimitive::PolyLine(VmlPolyLine {+ common: common_with_id("f"),+ points: vec![],+ }),+ VmlPrimitive::Arc(VmlArc {+ common: common_with_id("g"),+ start_angle: None,+ end_angle: None,+ }),+ VmlPrimitive::Curve(VmlCurve {+ common: common_with_id("h"),+ from: None,+ control1: None,+ control2: None,+ to: None,+ }),+ VmlPrimitive::Image(VmlImage {+ common: common_with_id("i"),+ src: None,+ }),+ VmlPrimitive::Group(Box::new(VmlGroup {+ common: common_with_id("j"),+ coord_size: None,+ coord_origin: None,+ children: vec![],+ })),+ ];+ let ids: Vec<&str> = variants+ .iter()+ .map(|p| p.common().id.as_ref().unwrap().as_str())+ .collect();+ assert_eq!(ids, ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);+ }++ #[test]+ fn common_mut_mutates_in_place() {+ let mut p = VmlPrimitive::Rect(VmlRect {+ common: common_with_id("before"),+ });+ p.common_mut().id = Some(VmlShapeId::new("after"));+ assert_eq!(p.common().id.as_ref().unwrap().as_str(), "after");+ }++ // ── §14.1.2 length units ─────────────────────────────────────────────++ fn len(value: f64, unit: VmlLengthUnit) -> VmlLength {+ VmlLength { value, unit }+ }++ #[test]+ fn absolute_units_convert_to_points() {+ let cases = [+ (len(9.0, VmlLengthUnit::Pt), 9.0),+ (len(1.0, VmlLengthUnit::In), 72.0),+ (len(2.54, VmlLengthUnit::Cm), 72.0),+ (len(25.4, VmlLengthUnit::Mm), 72.0),+ (len(96.0, VmlLengthUnit::Px), 72.0), // 96dpi reference pixel+ ];+ for (input, expected) in cases {+ let got = input.to_absolute_points().expect("absolute unit resolves");+ assert!(+ (got - expected).abs() < 1e-3,+ "{:?} → {got}, expected {expected}",+ input.unit+ );+ }+ }++ /// Units that need a containing box, a font size, or the attribute's own+ /// context are `None` — never a fabricated number. Three separate+ /// converters previously each invented their own answer here, and they+ /// disagreed: a bare number was EMU in one and points in the others.+ #[test]+ fn context_dependent_units_are_unresolved() {+ for unit in [+ VmlLengthUnit::Percent,+ VmlLengthUnit::Em,+ VmlLengthUnit::None,+ ] {+ assert_eq!(+ len(50.0, unit).to_absolute_points(),+ None,+ "{unit:?} cannot be resolved without context"+ );+ }+ }+}diff --git a/crates/liteparse-docx/src/render/dimension.rs b/crates/liteparse-docx/src/render/dimension.rsnew file mode 100644index 0000000..2467399--- /dev/null+++ b/crates/liteparse-docx/src/render/dimension.rs@@ -0,0 +1,251 @@+//! Point-based dimension type for layout and rendering.+//!+//! `Pt` is the f32-based unit used throughout the layout pipeline.+//! All OOXML integer units (Twips, EMU, HalfPoints, EighthPoints) are+//! converted to Pt before layout.++use std::fmt;+use std::iter::Sum;+use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};++/// A dimension in typographic points (1pt = 1/72 inch).+#[derive(Clone, Copy, Default, PartialEq, PartialOrd)]+pub struct Pt(f32);++impl Pt {+ pub const ZERO: Self = Self(0.0);+ pub const INFINITY: Self = Self(f32::INFINITY);++ pub const fn new(v: f32) -> Self {+ Self(v)+ }++ pub fn abs(self) -> Self {+ Self(self.0.abs())+ }++ pub fn max(self, other: Self) -> Self {+ Self(self.0.max(other.0))+ }++ pub fn min(self, other: Self) -> Self {+ Self(self.0.min(other.0))+ }++ pub fn raw(self) -> f32 {+ self.0+ }+}++impl fmt::Debug for Pt {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{:.2}pt", self.0)+ }+}++impl fmt::Display for Pt {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{:.2}pt", self.0)+ }+}++impl From<Pt> for f32 {+ fn from(pt: Pt) -> f32 {+ pt.0+ }+}++impl Add for Pt {+ type Output = Self;+ fn add(self, rhs: Self) -> Self {+ Self(self.0 + rhs.0)+ }+}++impl AddAssign for Pt {+ fn add_assign(&mut self, rhs: Self) {+ self.0 += rhs.0;+ }+}++impl Sub for Pt {+ type Output = Self;+ fn sub(self, rhs: Self) -> Self {+ Self(self.0 - rhs.0)+ }+}++impl SubAssign for Pt {+ fn sub_assign(&mut self, rhs: Self) {+ self.0 -= rhs.0;+ }+}++impl Neg for Pt {+ type Output = Self;+ fn neg(self) -> Self {+ Self(-self.0)+ }+}++impl Mul<f32> for Pt {+ type Output = Self;+ fn mul(self, rhs: f32) -> Self {+ Self(self.0 * rhs)+ }+}++impl Div<f32> for Pt {+ type Output = Self;+ fn div(self, rhs: f32) -> Self {+ Self(self.0 / rhs)+ }+}++impl Div<Pt> for Pt {+ type Output = f32;+ fn div(self, rhs: Pt) -> f32 {+ self.0 / rhs.0+ }+}++impl Sum for Pt {+ fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {+ Self(iter.map(|p| p.0).sum())+ }+}++// ── Conversions from OOXML units ─────────────────────────────────────────++use crate::model::dimension::{Dimension, EighthPoints, Emu, HalfPoints, Points, Twips};++impl From<Dimension<Twips>> for Pt {+ /// 1 twip = 1/20 pt.+ fn from(d: Dimension<Twips>) -> Self {+ Self(d.raw() as f32 / 20.0)+ }+}++impl From<Dimension<HalfPoints>> for Pt {+ /// 1 half-point = 0.5 pt.+ fn from(d: Dimension<HalfPoints>) -> Self {+ Self(d.raw() as f32 / 2.0)+ }+}++impl From<Dimension<Emu>> for Pt {+ /// 1 EMU = 1/12700 pt.+ fn from(d: Dimension<Emu>) -> Self {+ Self(d.raw() as f32 / 12700.0)+ }+}++impl From<Dimension<EighthPoints>> for Pt {+ /// 1 eighth-point = 1/8 pt.+ fn from(d: Dimension<EighthPoints>) -> Self {+ Self(d.raw() as f32 / 8.0)+ }+}++impl From<Dimension<Points>> for Pt {+ /// §17.18.68 ST_PointMeasure: 1 point = 1 pt.+ fn from(d: Dimension<Points>) -> Self {+ Self(d.raw() as f32)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pt_zero() {+ assert_eq!(Pt::ZERO.raw(), 0.0);+ }++ #[test]+ fn pt_arithmetic() {+ let a = Pt::new(10.0);+ let b = Pt::new(3.0);+ assert_eq!((a + b).raw(), 13.0);+ assert_eq!((a - b).raw(), 7.0);+ assert_eq!((a * 2.0).raw(), 20.0);+ assert_eq!((a / 2.0).raw(), 5.0);+ assert_eq!(a / b, 10.0 / 3.0);+ }++ #[test]+ fn pt_add_assign() {+ let mut a = Pt::new(5.0);+ a += Pt::new(3.0);+ assert_eq!(a.raw(), 8.0);+ }++ #[test]+ fn pt_sub_assign() {+ let mut a = Pt::new(5.0);+ a -= Pt::new(2.0);+ assert_eq!(a.raw(), 3.0);+ }++ #[test]+ fn pt_neg() {+ assert_eq!((-Pt::new(5.0)).raw(), -5.0);+ }++ #[test]+ fn pt_abs() {+ assert_eq!(Pt::new(-3.0).abs().raw(), 3.0);+ assert_eq!(Pt::new(3.0).abs().raw(), 3.0);+ }++ #[test]+ fn pt_max_min() {+ let a = Pt::new(5.0);+ let b = Pt::new(10.0);+ assert_eq!(a.max(b).raw(), 10.0);+ assert_eq!(a.min(b).raw(), 5.0);+ }++ #[test]+ fn pt_sum() {+ let pts = vec![Pt::new(1.0), Pt::new(2.0), Pt::new(3.0)];+ let total: Pt = pts.into_iter().sum();+ assert_eq!(total.raw(), 6.0);+ }++ #[test]+ fn twips_to_pt() {+ // 720 twips = 36 pt+ assert_eq!(Pt::from(Dimension::<Twips>::new(720)).raw(), 36.0);+ }++ #[test]+ fn half_points_to_pt() {+ // 24 half-points = 12 pt+ assert_eq!(Pt::from(Dimension::<HalfPoints>::new(24)).raw(), 12.0);+ }++ #[test]+ fn emu_to_pt() {+ // 914400 EMU = 72 pt (1 inch)+ let pt = Pt::from(Dimension::<Emu>::new(914400));+ assert!((pt.raw() - 72.0).abs() < 0.01);+ }++ #[test]+ fn eighth_points_to_pt() {+ // 8 eighth-points = 1 pt+ assert_eq!(Pt::from(Dimension::<EighthPoints>::new(8)).raw(), 1.0);+ }++ #[test]+ fn pt_display() {+ assert_eq!(format!("{}", Pt::new(12.5)), "12.50pt");+ }++ #[test]+ fn pt_infinity() {+ assert!(Pt::INFINITY.raw().is_infinite());+ }+}diff --git a/crates/liteparse-docx/src/render/emoji/cluster.rs b/crates/liteparse-docx/src/render/emoji/cluster.rsnew file mode 100644index 0000000..fcad327--- /dev/null+++ b/crates/liteparse-docx/src/render/emoji/cluster.rs@@ -0,0 +1,580 @@+//! Grapheme cluster classification for inline text.+//!+//! Splits a run's text into a typed sequence of [`InlineCluster`]s. Cluster+//! boundaries follow UAX #29 (Extended Grapheme Cluster). Emoji classification+//! follows UTS #51 (Unicode Emoji): the decision is made from codepoint+//! properties, never from the run's font name.+//!+//! Spec references for individual rules are inline in `classify_cluster`.++use unicode_properties::{EmojiStatus, UnicodeEmoji};+use unicode_segmentation::UnicodeSegmentation;++// ─── Public ADTs ─────────────────────────────────────────────────────────────++/// One indivisible rendering unit produced from a run's text.+///+/// Adjacent non-emoji clusters are merged into a single [`InlineCluster::Text`]+/// span so the existing text path can measure them in one call. Emoji clusters+/// are surfaced individually because each is rasterized independently.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum InlineCluster<'a> {+ /// Plain text — render via the existing text path. The slice is one or+ /// more contiguous grapheme clusters from the source string.+ Text(&'a str),+ /// Emoji — render via the raster-and-embed path.+ Emoji(EmojiCluster<'a>),+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct EmojiCluster<'a> {+ /// The cluster text exactly as it appeared in the source (no normalization+ /// at this stage — normalization happens at the rasterizer cache key).+ pub text: &'a str,+ pub presentation: EmojiPresentation,+ pub structure: EmojiStructure,+}++/// UTS #51 §2 presentation style. Determined from the default-presentation+/// property of the base scalar, modulated by VS-15 (U+FE0E) / VS-16 (U+FE0F).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EmojiPresentation {+ /// Default-text or VS-15 forced. The codepoint should be rendered as a+ /// monochrome glyph using the run's text font.+ Text,+ /// Default-emoji or VS-16 forced. The codepoint should be rendered via+ /// the color emoji typeface.+ Emoji,+}++/// UTS #51 §2 emoji sequence taxonomy.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EmojiStructure {+ /// Single emoji codepoint, optionally followed by a presentation selector.+ Single,+ /// Keycap: `[0-9#*]` + VS-16 + U+20E3 (COMBINING ENCLOSING KEYCAP).+ KeycapSequence { base: char },+ /// Emoji_Modifier_Base + Emoji_Modifier (skin tone).+ ModifierSequence { base: char, tone: SkinTone },+ /// Flag sequence — either RIS pair or black-flag tag sequence.+ FlagSequence(FlagKind),+ /// Two or more emoji elements joined by U+200D (ZWJ).+ ZwjSequence,+}++/// UTS #51 §1.4.5 emoji modifiers (Fitzpatrick skin tone).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SkinTone {+ Light, // U+1F3FB+ MediumLight, // U+1F3FC+ Medium, // U+1F3FD+ MediumDark, // U+1F3FE+ Dark, // U+1F3FF+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FlagKind {+ /// Pair of Regional Indicator Symbols (UTS #51 §1.4.7).+ Regional,+ /// Black flag (U+1F3F4) + tag sequence + END_TAG (U+E007F).+ Subdivision,+}++// ─── Public API ──────────────────────────────────────────────────────────────++/// Classify `text` into a sequence of clusters.+///+/// Adjacent text clusters are merged into one [`InlineCluster::Text`] span.+/// Empty input yields an empty vector.+pub fn classify(text: &str) -> Vec<InlineCluster<'_>> {+ let mut out = Vec::new();+ let mut text_start: Option<usize> = None;+ let mut text_end = 0usize;+ let mut byte_offset = 0usize;++ for cluster in text.graphemes(true) {+ let cluster_len = cluster.len();+ match classify_cluster(cluster) {+ ClusterClass::Text => {+ if text_start.is_none() {+ text_start = Some(byte_offset);+ }+ text_end = byte_offset + cluster_len;+ }+ ClusterClass::Emoji {+ presentation,+ structure,+ } => {+ if let Some(s) = text_start.take() {+ out.push(InlineCluster::Text(&text[s..text_end]));+ }+ out.push(InlineCluster::Emoji(EmojiCluster {+ text: cluster,+ presentation,+ structure,+ }));+ }+ }+ byte_offset += cluster_len;+ }+ if let Some(s) = text_start {+ out.push(InlineCluster::Text(&text[s..text_end]));+ }+ out+}++// ─── Internal classification ────────────────────────────────────────────────++/// Outcome of classifying one grapheme cluster. Internal — the public API+/// produces [`InlineCluster`]s with text slices.+enum ClusterClass {+ Text,+ Emoji {+ presentation: EmojiPresentation,+ structure: EmojiStructure,+ },+}++fn classify_cluster(cluster: &str) -> ClusterClass {+ // UAX #29 grapheme iteration never yields an empty cluster, but be+ // defensive — an empty input string at the API boundary skips the loop.+ let mut chars = cluster.chars();+ let Some(first) = chars.next() else {+ return ClusterClass::Text;+ };+ let chars: Vec<char> = std::iter::once(first).chain(chars).collect();++ // 1. Subdivision flag — UTS #51 §1.4.7. Black flag base + tag sequence.+ // Tag chars are U+E0020..U+E007E with U+E007F as terminator.+ if first == '\u{1F3F4}' && chars.iter().any(|&c| is_tag(c)) {+ return ClusterClass::Emoji {+ presentation: EmojiPresentation::Emoji,+ structure: EmojiStructure::FlagSequence(FlagKind::Subdivision),+ };+ }++ // 2. Regional indicator pair — UTS #51 §1.4.7. Exactly two RIS chars.+ let ris_count = chars.iter().filter(|&&c| is_regional_indicator(c)).count();+ if ris_count == 2 && ris_count == chars.len() {+ return ClusterClass::Emoji {+ presentation: EmojiPresentation::Emoji,+ structure: EmojiStructure::FlagSequence(FlagKind::Regional),+ };+ }++ // 3. Keycap — UTS #51 §1.4.4. Base char + VS-16 + U+20E3.+ if chars.contains(&'\u{20E3}') && is_keycap_base(first) {+ return ClusterClass::Emoji {+ presentation: EmojiPresentation::Emoji,+ structure: EmojiStructure::KeycapSequence { base: first },+ };+ }++ // After special sequences, an Emoji=YES char must appear in the cluster+ // before we treat it as emoji at all. Without this guard, "a\u{200D}b"+ // (a non-emoji ZWJ pairing — illegal but representable) would be+ // misclassified as a ZwjSequence.+ let Some(emoji_base) = chars.iter().copied().find(|&c| char_is_emoji(c)) else {+ return ClusterClass::Text;+ };++ let has_zwj = chars.contains(&'\u{200D}');+ let has_vs15 = chars.contains(&'\u{FE0E}');+ let has_vs16 = chars.contains(&'\u{FE0F}');++ // 4. ZWJ sequence — UTS #51 §1.4.6.+ if has_zwj {+ return ClusterClass::Emoji {+ presentation: EmojiPresentation::Emoji,+ structure: EmojiStructure::ZwjSequence,+ };+ }++ // 5. Modifier sequence — UTS #51 §1.4.5.+ if let Some(tone) = chars.iter().find_map(|&c| skin_tone_for(c)) {+ return ClusterClass::Emoji {+ presentation: EmojiPresentation::Emoji,+ structure: EmojiStructure::ModifierSequence {+ base: emoji_base,+ tone,+ },+ };+ }++ // 6. Single emoji codepoint, with optional presentation selector.+ //+ // UTS #51 distinguishes "default-text" emoji codepoints (digits 0-9,+ // '#', '*', ☎, ☃, ✉, ⌚, etc.) from "default-emoji" ones. A default-text+ // codepoint without VS-16 must NOT be rasterized via the color emoji+ // typeface — it's intended to render as the run's normal text glyph,+ // and routing it to the rasterizer corrupts page numbers, IBANs, dates,+ // and any other run that happens to contain digits.+ //+ // Decision rule:+ // VS-15 → Text (forced text presentation)+ // VS-16 → Emoji (forced emoji presentation)+ // default-emoji → Emoji (color glyph rendering intended)+ // default-text → Text (monochrome text-font rendering intended)+ if has_vs15 {+ return ClusterClass::Text;+ }+ if has_vs16 || has_default_emoji_presentation(emoji_base) {+ return ClusterClass::Emoji {+ presentation: EmojiPresentation::Emoji,+ structure: EmojiStructure::Single,+ };+ }+ ClusterClass::Text+}++// ─── Codepoint property helpers ──────────────────────────────────────────────++/// `Emoji=YES` per UTS #51. Pure emoji components (RIS, ZWJ, VS-16, digits as+/// keycap bases) are *not* covered here — those are handled by the sequence+/// detectors above.+fn char_is_emoji(c: char) -> bool {+ use EmojiStatus::*;+ matches!(+ c.emoji_status(),+ EmojiPresentation+ | EmojiModifierBase+ | EmojiPresentationAndModifierBase+ | EmojiOther+ | EmojiPresentationAndEmojiComponent+ | EmojiPresentationAndModifierAndEmojiComponent+ | EmojiOtherAndEmojiComponent+ )+}++/// `Emoji_Presentation=YES` per UTS #51 — the codepoint defaults to emoji+/// (color) presentation in the absence of a VS selector.+fn has_default_emoji_presentation(c: char) -> bool {+ use EmojiStatus::*;+ matches!(+ c.emoji_status(),+ EmojiPresentation+ | EmojiPresentationAndModifierBase+ | EmojiPresentationAndEmojiComponent+ | EmojiPresentationAndModifierAndEmojiComponent+ )+}++fn is_regional_indicator(c: char) -> bool {+ matches!(c, '\u{1F1E6}'..='\u{1F1FF}')+}++fn is_tag(c: char) -> bool {+ // UTS #51: tag base U+E0020..U+E007E and END_TAG U+E007F.+ matches!(c, '\u{E0020}'..='\u{E007F}')+}++fn is_keycap_base(c: char) -> bool {+ matches!(c, '0'..='9' | '#' | '*')+}++/// Return the [`SkinTone`] for emoji modifier codepoints U+1F3FB..U+1F3FF.+fn skin_tone_for(c: char) -> Option<SkinTone> {+ match c {+ '\u{1F3FB}' => Some(SkinTone::Light),+ '\u{1F3FC}' => Some(SkinTone::MediumLight),+ '\u{1F3FD}' => Some(SkinTone::Medium),+ '\u{1F3FE}' => Some(SkinTone::MediumDark),+ '\u{1F3FF}' => Some(SkinTone::Dark),+ _ => None,+ }+}++// ─── Tests ───────────────────────────────────────────────────────────────────+//+// `cN_` names are the classification cases this module was built against:+// plain text, emoji between text, default-text presentation, VS-16/VS-15+// promotion and demotion, modifier / ZWJ / regional-flag / subdivision-flag /+// keycap sequences, adjacent emoji, the empty string, and a combining mark+// adjacent to an emoji.++#[cfg(test)]+mod tests {+ use super::*;++ fn emoji(+ text: &str,+ presentation: EmojiPresentation,+ structure: EmojiStructure,+ ) -> InlineCluster<'_> {+ InlineCluster::Emoji(EmojiCluster {+ text,+ presentation,+ structure,+ })+ }++ /// C1 — pure ASCII text, no emoji.+ #[test]+ fn c1_pure_text() {+ assert_eq!(classify("hello"), vec![InlineCluster::Text("hello")]);+ }++ /// C2 — emoji embedded in surrounding text. Adjacent text clusters merge+ /// into a single span; the emoji is surfaced on its own.+ #[test]+ fn c2_emoji_between_text() {+ assert_eq!(+ classify("hi 📞 there"),+ vec![+ InlineCluster::Text("hi "),+ emoji("📞", EmojiPresentation::Emoji, EmojiStructure::Single),+ InlineCluster::Text(" there"),+ ]+ );+ }++ /// C3 — U+260E BLACK TELEPHONE has Emoji=YES with default-text presentation.+ /// Per UTS #51 it must render via the run's text font, not as a color+ /// emoji raster — so it stays in an `InlineCluster::Text` span.+ #[test]+ fn c3_default_text_presentation_stays_text() {+ assert_eq!(classify("\u{260E}"), vec![InlineCluster::Text("\u{260E}")]);+ }++ /// C4 — VS-16 promotes a default-text emoji to emoji presentation.+ #[test]+ fn c4_vs16_promotes_to_emoji() {+ assert_eq!(+ classify("\u{260E}\u{FE0F}"),+ vec![emoji(+ "\u{260E}\u{FE0F}",+ EmojiPresentation::Emoji,+ EmojiStructure::Single+ )]+ );+ }++ /// C5 — VS-15 explicitly forces text presentation. The cluster must+ /// stay as text so it renders via the run's text font.+ #[test]+ fn c5_vs15_forces_text() {+ assert_eq!(+ classify("\u{260E}\u{FE0E}"),+ vec![InlineCluster::Text("\u{260E}\u{FE0E}")]+ );+ }++ // ─── Default-text emoji codepoint regression tests ───────────────────────+ //+ // Per UTS #51 emoji-data.txt: digits 0-9, '#', '*' have Emoji=YES with+ // default-text presentation. A prior version of the classifier returned+ // them as `InlineCluster::Emoji` with `presentation: Text`, which still+ // routed them through the color emoji rasterizer downstream — corrupting+ // page numbers, IBANs, dates, and any other digit-bearing text.++ /// Standalone digit must be plain text — no rasterization.+ #[test]+ fn standalone_digit_is_text() {+ assert_eq!(classify("1"), vec![InlineCluster::Text("1")]);+ }++ /// Multi-digit string is one text span (digits are separate graphemes+ /// per UAX #29 but adjacent text clusters merge in `classify`).+ #[test]+ fn multi_digit_is_single_text_span() {+ assert_eq!(classify("12345"), vec![InlineCluster::Text("12345")]);+ }++ /// `#` and `*` alone are text — they're keycap *bases*, not emojis.+ #[test]+ fn hash_and_star_alone_are_text() {+ assert_eq!(classify("#"), vec![InlineCluster::Text("#")]);+ assert_eq!(classify("*"), vec![InlineCluster::Text("*")]);+ }++ /// Real-world regression: footer text "Seite 1 von 2" must produce a+ /// single text span. Previously the digits were rasterized, so+ /// `pdftotext` showed only "Seite von" with the numbers replaced by+ /// images.+ #[test]+ fn footer_page_number_text_is_not_rasterized() {+ let clusters = classify("Seite 1 von 2");+ assert_eq!(clusters, vec![InlineCluster::Text("Seite 1 von 2")]);+ for c in &clusters {+ assert!(+ matches!(c, InlineCluster::Text(_)),+ "no emoji clusters expected, got {c:?}"+ );+ }+ }++ /// IBAN strings (digits and letters) must stay as one text span.+ #[test]+ fn iban_is_text_only() {+ assert_eq!(+ classify("IBAN: DE50 3705 0299 0000 3812 08"),+ vec![InlineCluster::Text("IBAN: DE50 3705 0299 0000 3812 08")]+ );+ }++ /// Phone-number-style content with separators stays as text.+ #[test]+ fn phone_number_is_text_only() {+ assert_eq!(+ classify("0221 – 89 06 37 69"),+ vec![InlineCluster::Text("0221 – 89 06 37 69")]+ );+ }++ /// VS-16 on a digit DOES route through the emoji rasterizer (uncommon+ /// but spec-allowed: VS-16 forces emoji presentation regardless of the+ /// codepoint's default). This keeps C4's contract symmetric across+ /// codepoints.+ #[test]+ fn digit_with_vs16_is_emoji() {+ assert_eq!(+ classify("1\u{FE0F}"),+ vec![emoji(+ "1\u{FE0F}",+ EmojiPresentation::Emoji,+ EmojiStructure::Single+ )]+ );+ }++ /// C6 — modifier sequence: 👍 (U+1F44D) + medium-dark skin tone (U+1F3FE).+ #[test]+ fn c6_modifier_sequence() {+ assert_eq!(+ classify("\u{1F44D}\u{1F3FE}"),+ vec![emoji(+ "\u{1F44D}\u{1F3FE}",+ EmojiPresentation::Emoji,+ EmojiStructure::ModifierSequence {+ base: '\u{1F44D}',+ tone: SkinTone::MediumDark,+ },+ )]+ );+ }++ /// C7 — ZWJ sequence: family of three (man + ZWJ + woman + ZWJ + girl).+ #[test]+ fn c7_zwj_sequence() {+ let text = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}";+ assert_eq!(+ classify(text),+ vec![emoji(+ text,+ EmojiPresentation::Emoji,+ EmojiStructure::ZwjSequence+ )]+ );+ }++ /// C8 — Regional indicator pair (German flag).+ #[test]+ fn c8_regional_flag() {+ let text = "\u{1F1E9}\u{1F1EA}";+ assert_eq!(+ classify(text),+ vec![emoji(+ text,+ EmojiPresentation::Emoji,+ EmojiStructure::FlagSequence(FlagKind::Regional),+ )]+ );+ }++ /// C9 — Subdivision flag (Scotland: black flag + tag sequence).+ #[test]+ fn c9_subdivision_flag() {+ let text = "\u{1F3F4}\u{E0067}\u{E0062}\u{E0073}\u{E0063}\u{E0074}\u{E007F}";+ assert_eq!(+ classify(text),+ vec![emoji(+ text,+ EmojiPresentation::Emoji,+ EmojiStructure::FlagSequence(FlagKind::Subdivision),+ )]+ );+ }++ /// C10 — keycap: '1' + VS-16 + U+20E3.+ #[test]+ fn c10_keycap() {+ let text = "1\u{FE0F}\u{20E3}";+ assert_eq!(+ classify(text),+ vec![emoji(+ text,+ EmojiPresentation::Emoji,+ EmojiStructure::KeycapSequence { base: '1' },+ )]+ );+ }++ /// C11 — two adjacent emoji split into two clusters per UAX #29.+ #[test]+ fn c11_adjacent_emojis() {+ assert_eq!(+ classify("\u{1F4DE}\u{1F4E7}"),+ vec![+ emoji(+ "\u{1F4DE}",+ EmojiPresentation::Emoji,+ EmojiStructure::Single+ ),+ emoji(+ "\u{1F4E7}",+ EmojiPresentation::Emoji,+ EmojiStructure::Single+ ),+ ]+ );+ }++ /// C12 — empty string yields no clusters.+ #[test]+ fn c12_empty_string() {+ assert_eq!(classify(""), Vec::<InlineCluster>::new());+ }++ /// C13 — combining mark on a base letter forms one text grapheme cluster+ /// preceding an emoji cluster. Tests that the merging logic flushes the+ /// pending text span before emitting the emoji.+ #[test]+ fn c13_combining_mark_then_emoji() {+ let text = "a\u{0301}\u{1F4DE}";+ assert_eq!(+ classify(text),+ vec![+ InlineCluster::Text("a\u{0301}"),+ emoji(+ "\u{1F4DE}",+ EmojiPresentation::Emoji,+ EmojiStructure::Single+ ),+ ]+ );+ }++ // ─── Negative / robustness tests ─────────────────────────────────────────++ /// Non-emoji ZWJ pair must not be misclassified as a ZWJ emoji sequence.+ #[test]+ fn negative_zwj_between_letters_is_text() {+ let text = "a\u{200D}b";+ // UAX #29 may bind these as one cluster; either way, no emoji char+ // is present so the result must be Text only.+ let clusters = classify(text);+ for cluster in &clusters {+ assert!(+ matches!(cluster, InlineCluster::Text(_)),+ "non-emoji ZWJ pairing must classify as text, got {cluster:?}"+ );+ }+ }++ /// Single Regional Indicator (no pair) is a degenerate input. We accept+ /// either Text or Single-emoji classification but must never panic.+ #[test]+ fn negative_lone_regional_indicator_does_not_panic() {+ let _ = classify("\u{1F1E9}");+ }+}diff --git a/crates/liteparse-docx/src/render/emoji/mod.rs b/crates/liteparse-docx/src/render/emoji/mod.rsnew file mode 100644index 0000000..3607317--- /dev/null+++ b/crates/liteparse-docx/src/render/emoji/mod.rs@@ -0,0 +1,7 @@+//! Only `cluster`, 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`.++pub mod cluster;diff --git a/crates/liteparse-docx/src/render/error.rs b/crates/liteparse-docx/src/render/error.rsnew file mode 100644index 0000000..07516c1--- /dev/null+++ b/crates/liteparse-docx/src/render/error.rs@@ -0,0 +1,32 @@+//! Renderer error types.++/// Errors that can occur during rendering.+///+/// There is exactly one, and it is the only condition the pipeline cannot+/// render its way out of. Emptiness is deliberately *not* one: a document with+/// no content produces a single blank page (`render::layout_document`), which+/// is what Word does — so the `EmptyDocument` variant this type used to carry+/// was not merely unconstructed, it contradicted the behaviour the pipeline+/// had chosen.+#[derive(Debug)]+pub enum RenderError {+ /// The host font system exposes no typeface at all, so there is nothing to+ /// fall back to when a requested family cannot be resolved. Seen on+ /// container images built without any fonts installed, and with a+ /// deliberately empty `FontMgr`.+ NoFontsAvailable,+}++impl std::fmt::Display for RenderError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ RenderError::NoFontsAvailable => write!(+ f,+ "no fonts available on this system — install at least one font, \+ or check that fontconfig is configured"+ ),+ }+ }+}++impl std::error::Error for RenderError {}diff --git a/crates/liteparse-docx/src/render/fonts.rs b/crates/liteparse-docx/src/render/fonts.rsnew file mode 100644index 0000000..70b4b67--- /dev/null+++ b/crates/liteparse-docx/src/render/fonts.rs@@ -0,0 +1,15 @@+//! Font-handle placeholder for the Skia-free subset.+//!+//! 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.+//!+//! 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.+#[derive(Clone, Debug)]+pub struct TypefaceEntry {+ _private: (),+}diff --git a/crates/liteparse-docx/src/render/geometry.rs b/crates/liteparse-docx/src/render/geometry.rsnew file mode 100644index 0000000..203f7a7--- /dev/null+++ b/crates/liteparse-docx/src/render/geometry.rs@@ -0,0 +1,143 @@+//! Point-space geometry types for layout and rendering.++use crate::render::dimension::Pt;++/// A 2D offset in points.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PtOffset {+ pub x: Pt,+ pub y: Pt,+}++impl PtOffset {+ pub const ZERO: Self = Self {+ x: Pt::ZERO,+ y: Pt::ZERO,+ };++ pub const fn new(x: Pt, y: Pt) -> Self {+ Self { x, y }+ }+}++impl std::ops::Add for PtOffset {+ type Output = Self;+ fn add(self, rhs: Self) -> Self {+ Self {+ x: self.x + rhs.x,+ y: self.y + rhs.y,+ }+ }+}++/// A 2D size in points.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PtSize {+ pub width: Pt,+ pub height: Pt,+}++impl PtSize {+ pub const ZERO: Self = Self {+ width: Pt::ZERO,+ height: Pt::ZERO,+ };++ pub const fn new(width: Pt, height: Pt) -> Self {+ Self { width, height }+ }+}++/// Axis-aligned rectangle in points.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PtRect {+ pub origin: PtOffset,+ pub size: PtSize,+}++impl PtRect {+ pub fn from_xywh(x: Pt, y: Pt, w: Pt, h: Pt) -> Self {+ Self {+ origin: PtOffset::new(x, y),+ size: PtSize::new(w, h),+ }+ }+}++/// Edge insets (padding/margins) in points.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PtEdgeInsets {+ pub top: Pt,+ pub right: Pt,+ pub bottom: Pt,+ pub left: Pt,+}++impl PtEdgeInsets {+ pub const ZERO: Self = Self {+ top: Pt::ZERO,+ right: Pt::ZERO,+ bottom: Pt::ZERO,+ left: Pt::ZERO,+ };++ pub const fn new(top: Pt, right: Pt, bottom: Pt, left: Pt) -> Self {+ Self {+ top,+ right,+ bottom,+ left,+ }+ }++ pub fn horizontal(&self) -> Pt {+ self.left + self.right+ }++ pub fn vertical(&self) -> Pt {+ self.top + self.bottom+ }+}++/// A line segment in points.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PtLineSegment {+ pub start: PtOffset,+ pub end: PtOffset,+}++impl PtLineSegment {+ pub const fn new(start: PtOffset, end: PtOffset) -> Self {+ Self { start, end }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn offset_add() {+ let a = PtOffset::new(Pt::new(1.0), Pt::new(2.0));+ let b = PtOffset::new(Pt::new(3.0), Pt::new(4.0));+ let c = a + b;+ assert_eq!(c.x.raw(), 4.0);+ assert_eq!(c.y.raw(), 6.0);+ }++ #[test]+ fn edge_insets_horizontal_vertical() {+ let ei = PtEdgeInsets::new(Pt::new(10.0), Pt::new(20.0), Pt::new(30.0), Pt::new(40.0));+ assert_eq!(ei.horizontal().raw(), 60.0);+ assert_eq!(ei.vertical().raw(), 40.0);+ }++ #[test]+ fn rect_from_xywh() {+ let r = PtRect::from_xywh(Pt::new(1.0), Pt::new(2.0), Pt::new(3.0), Pt::new(4.0));+ assert_eq!(r.origin.x.raw(), 1.0);+ assert_eq!(r.origin.y.raw(), 2.0);+ assert_eq!(r.size.width.raw(), 3.0);+ assert_eq!(r.size.height.raw(), 4.0);+ }+}diff --git a/crates/liteparse-docx/src/render/layout/draw_command.rs b/crates/liteparse-docx/src/render/layout/draw_command.rsnew file mode 100644index 0000000..8919a58--- /dev/null+++ b/crates/liteparse-docx/src/render/layout/draw_command.rs@@ -0,0 +1,728 @@+//! Draw commands — the output of layout, consumed by the painter.++use std::rc::Rc;++use crate::model::dimension::{Dimension, SixtieThousandthDeg};+use crate::render::dimension::Pt;+use crate::render::emoji::cluster::{EmojiPresentation, EmojiStructure};+use crate::render::fonts::TypefaceEntry;+use crate::render::geometry::{PtLineSegment, PtOffset, PtRect, PtSize};+use crate::render::resolve::color::RgbColor;+use crate::render::resolve::drawing_color::Rgba;+use crate::render::resolve::images::MediaEntry;+use crate::render::resolve::shape_geometry::SubPath;++/// §17.3.1.19: one heading, as it will appear in the PDF outline.+///+/// `node_id` is assigned at **layout** time and carried here rather than+/// recomputed at paint. The painter and the structure-tree builder both walk+/// the same command stream, and two counters that agree only by argument is+/// exactly the shape that produced this codebase's MCE double-render and then+/// the missing render after it. One field, read twice.+#[derive(Debug, Clone)]+pub struct OutlineHeading {+ /// PDF structure node ID. Unique per document and **1-based**:+ /// `skia_safe::pdf::node_id` reserves 0 for "no node" and every negative+ /// value for artifacts.+ pub node_id: i32,+ /// §17.3.1.19 level, 1-based (`w:outlineLvl` 0 → 1).+ pub level: crate::model::OutlineLevel,+ /// The paragraph's own text, **without** its §17.9.22 list label — which+ /// is what Word and LibreOffice both put in the outline, even for a+ /// numbered heading that renders with its number on the page.+ pub title: Rc<str>,+}++/// §17.3.1.19: the boundaries of a heading's marked content.+///+/// A *pair* rather than a single marker because the PDF destination is the+/// union of the marks under the node — leaving the node ID set past the+/// heading would drag its destination down onto the body text below. This is+/// the same shape as the `BDC`/`EMC` operator pair it ultimately becomes.+///+/// The balance invariant is held by a single emitter+/// (`paragraph::line_emit::emit_line_commands`) rather than by the type: the+/// alternative — a variant owning a `Vec<DrawCommand>` — would need an arm in+/// every one of the twenty files that match on `DrawCommand`, for a nesting+/// the flat per-page command list does not otherwise have.+#[derive(Debug, Clone)]+pub enum OutlineMark {+ /// Opens the heading's marked content.+ Begin(OutlineHeading),+ /// Closes it, restoring "no node".+ End,+}++/// A positioned drawing command — absolute page coordinates.+#[derive(Debug, Clone)]+pub enum DrawCommand {+ Text {+ position: PtOffset,+ text: Rc<str>,+ font_family: Rc<str>,+ char_spacing: Pt,+ font_size: Pt,+ bold: bool,+ italic: bool,+ color: RgbColor,+ /// §17.3.2.45: horizontal scale factor (1.0 = normal, 0.8 = 80%,+ /// 1.5 = 150%). Painter applies via `Font::set_scale_x`.+ text_scale: f32,+ },+ Underline {+ line: PtLineSegment,+ color: RgbColor,+ width: Pt,+ },+ Line {+ line: PtLineSegment,+ color: RgbColor,+ width: Pt,+ },+ Image {+ rect: PtRect,+ image_data: MediaEntry,+ /// §20.1.10.48 `a:srcRect` — fractional source crop in `[0, 1]`+ /// relative to the image's natural extent, applied before the image+ /// is stretched into `rect`. `None` draws the whole image.+ src_rect: Option<PtRect>,+ },+ /// One emoji grapheme cluster placed at `rect`. The painter rasterizes+ /// the cluster against `typeface` (Skia raster backend honours the color+ /// glyph tables that the PDF backend strips) and embeds the result as+ /// an inline image. Produced from [`Fragment::Emoji`]; painted by the+ /// `EmojiCluster` arm in `painter.rs`.+ ///+ /// [`Fragment::Emoji`]: crate::render::layout::fragment::Fragment::Emoji+ EmojiCluster {+ /// Page-coordinate rectangle at which to draw the rasterized image.+ rect: PtRect,+ /// Cluster text — one grapheme cluster, possibly multi-codepoint.+ text: String,+ /// Color emoji typeface to rasterize against.+ typeface: TypefaceEntry,+ /// Font size in Pt at which to rasterize.+ size: Pt,+ /// UTS #51 cluster classification (carried for future paint-side+ /// behaviour and diagnostics; not needed by the raster pipeline).+ presentation: EmojiPresentation,+ structure: EmojiStructure,+ },+ Rect {+ rect: PtRect,+ color: RgbColor,+ },+ /// One annotation rect per word of a `w:hyperlink`, so the target is+ /// shared with the fragment it came from (see+ /// [`LinkTarget`](crate::render::layout::fragment::LinkTarget)) rather+ /// than copied per word.+ LinkAnnotation {+ rect: PtRect,+ url: Rc<str>,+ },+ /// Internal link to a named destination (bookmark). Shared for the same+ /// reason as [`DrawCommand::LinkAnnotation`]'s `url`.+ InternalLink {+ rect: PtRect,+ destination: Rc<str>,+ },+ /// Named destination marker (bookmark target).+ NamedDestination {+ position: PtOffset,+ name: String,+ },+ /// §17.3.1.19: brackets one heading paragraph's commands so the PDF+ /// outline can point at it. Draws nothing.+ Outline(OutlineMark),+ /// §20.1.8 shape draw command — a resolved geometry with fill, stroke,+ /// and optional effects. `paths` are in shape-local Pt; the painter+ /// applies the placement transform (origin/rotation/flip).+ Path {+ /// Top-left placement anchor in page coordinates.+ origin: PtOffset,+ /// Rotation in 60000ths of a degree, around the shape's center.+ rotation: Dimension<SixtieThousandthDeg>,+ /// Mirror the shape horizontally before placement.+ flip_h: bool,+ /// Mirror the shape vertically before placement.+ flip_v: bool,+ /// Shape-local size — the bounding box the geometry was built for.+ extent: PtSize,+ /// One or more subpaths; each may be stroked and/or filled.+ paths: Vec<SubPath>,+ /// Fill applied to path interiors.+ fill: ResolvedFill,+ /// Stroke applied to path outlines (if stroked at the path level).+ stroke: Option<ResolvedStroke>,+ /// Post-processing effects (shadow, glow, …). Painter applies in order.+ effects: Vec<ResolvedEffect>,+ },+}++// ── Resolved render-ready types ─────────────────────────────────────────────++/// Painter-ready fill specification. Tier 0 renders `None` and `Solid`+/// faithfully; the other variants fall through with a one-time log.+#[derive(Clone, Debug)]+pub enum ResolvedFill {+ /// No fill — path interior is transparent.+ None,+ /// §20.1.8.54 solidFill — a single RGBA color.+ Solid(Rgba),+ /// §20.1.8.33 gradFill — stops and a direction. Tier 2 renders.+ Gradient(ResolvedGradient),+ /// §20.1.8.14 blipFill — image fill. Tier 2 renders.+ Blip(ResolvedBlip),+ /// §20.1.8.47 pattFill — preset pattern with fg/bg. Tier 3 renders.+ Pattern(ResolvedPattern),+}++/// Painter-ready stroke specification. Color/width are always honoured;+/// dash pattern is applied as a Skia path effect; cap/join map to Skia's+/// stroke primitives.+#[derive(Clone, Debug)]+pub struct ResolvedStroke {+ pub width: Pt,+ pub color: Rgba,+ pub dash: ResolvedDashPattern,+ pub cap: ResolvedLineCap,+ pub join: ResolvedLineJoin,+}++/// §20.1.10.31 ST_LineCap, ready for Skia.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ResolvedLineCap {+ Butt,+ Round,+ Square,+}++/// §20.1.2.2.22 EG_LineJoinProperties, ready for Skia.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum ResolvedLineJoin {+ Round,+ Bevel,+ Miter,+}++/// Stroke dash pattern. `Solid` renders without a dash effect; `Dashes`+/// alternates on/off lengths in Pt.+#[derive(Clone, Debug, PartialEq)]+pub enum ResolvedDashPattern {+ Solid,+ Dashes(Vec<Pt>),+}++/// Post-processing effects. Tier 0 carries the data only — the painter+/// renders none of these until later tiers.+#[derive(Clone, Debug)]+pub enum ResolvedEffect {+ /// §20.1.8.45 outerShdw.+ OuterShadow {+ blur_radius: Pt,+ offset: PtOffset,+ color: Rgba,+ },+}++/// Painter-ready gradient fill — included for typing completeness; Tier 0+/// painter logs and draws no fill. Tier 2 adds rendering.+#[derive(Clone, Debug)]+pub struct ResolvedGradient {+ pub stops: Vec<GradientStopRgba>,+ pub kind: ResolvedGradientKind,+}++#[derive(Clone, Copy, Debug)]+pub struct GradientStopRgba {+ /// Position in `[0, 1]`.+ pub position: f32,+ pub color: Rgba,+}++#[derive(Clone, Copy, Debug)]+pub enum ResolvedGradientKind {+ /// Linear gradient at angle (degrees, OOXML convention: 0° = horizontal,+ /// clockwise positive).+ Linear { angle_deg: f32 },+ /// Radial/path-based gradient.+ Radial,+}++/// Painter-ready image fill — pointer to decoded bytes + source crop.+#[derive(Clone, Debug)]+pub struct ResolvedBlip {+ pub data: std::sync::Arc<[u8]>,+ pub format: crate::model::ImageFormat,+ /// Fraction of the source to crop: values in `[0, 1]` relative to the+ /// blip's natural extent. Derive this from the blip's `a:srcRect` via+ /// `resolve::images::relative_rect_to_fraction` — the same converter the+ /// picture path uses — so cropped fills and cropped pictures stay in+ /// lockstep.+ pub src_rect: Option<PtRect>,+}++/// Painter-ready pattern fill — foreground/background + preset id.+#[derive(Clone, Debug)]+pub struct ResolvedPattern {+ pub preset: crate::model::PresetPatternVal,+ pub fg: Rgba,+ pub bg: Rgba,+}++impl DrawCommand {+ /// Shift all coordinates by `(dx, dy)`.+ pub fn shift(&mut self, dx: Pt, dy: Pt) {+ match self {+ DrawCommand::Text { position, .. } => {+ position.x += dx;+ position.y += dy;+ }+ DrawCommand::Underline { line, .. } | DrawCommand::Line { line, .. } => {+ line.start.x += dx;+ line.start.y += dy;+ line.end.x += dx;+ line.end.y += dy;+ }+ DrawCommand::Image { rect, .. }+ | DrawCommand::EmojiCluster { rect, .. }+ | DrawCommand::Rect { rect, .. }+ | DrawCommand::LinkAnnotation { rect, .. }+ | DrawCommand::InternalLink { rect, .. } => {+ rect.origin.x += dx;+ rect.origin.y += dy;+ }+ DrawCommand::NamedDestination { position, .. } => {+ position.x += dx;+ position.y += dy;+ }+ DrawCommand::Path { origin, .. } => {+ origin.x += dx;+ origin.y += dy;+ }+ // A marked-content boundary has no coordinates of its own — the+ // destination is derived from the commands it brackets, which do+ // get shifted.+ DrawCommand::Outline(_) => {}+ }+ }++ /// The vertical band this command paints into, as `(top, bottom)`.+ ///+ /// `None` for commands that paint nothing — a link annotation covers+ /// content that is already accounted for by the command underneath it, and+ /// a named destination is a point.+ ///+ /// **Text is approximate.** A `Text` command carries a baseline and a font+ /// size, not the ascent/descent it was measured with, so the band is taken+ /// as `baseline ± font_size`. That is the same approximation+ /// `render::estimate_cursor_y` already makes for the descender, kept+ /// deliberately identical so the two cannot disagree about where a line+ /// ends. It is generous on both sides, which is the safe direction for the+ /// one caller that exists (`vertOverflow="clip"`): a line is dropped when+ /// it *might* paint outside its box rather than when it certainly does.+ pub fn vertical_span(&self) -> Option<(Pt, Pt)> {+ match self {+ DrawCommand::Text {+ position,+ font_size,+ ..+ } => Some((position.y - *font_size, position.y + *font_size)),+ DrawCommand::Underline { line, .. } | DrawCommand::Line { line, .. } => {+ Some((line.start.y.min(line.end.y), line.start.y.max(line.end.y)))+ }+ DrawCommand::Image { rect, .. }+ | DrawCommand::EmojiCluster { rect, .. }+ | DrawCommand::Rect { rect, .. } => {+ Some((rect.origin.y, 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, .. } => Some((origin.y, origin.y + extent.height)),+ DrawCommand::LinkAnnotation { .. }+ | DrawCommand::InternalLink { .. }+ | DrawCommand::NamedDestination { .. }+ | DrawCommand::Outline(_) => None,+ }+ }++ /// Shift all y-coordinates by `dy`.+ pub fn shift_y(&mut self, dy: Pt) {+ self.shift(Pt::ZERO, dy);+ }++ /// Shift all x-coordinates by `dx`.+ pub fn shift_x(&mut self, dx: Pt) {+ self.shift(dx, Pt::ZERO);+ }+}++/// A fully laid-out page — ready for painting.+#[derive(Debug, Clone)]+pub struct LayoutedPage {+ pub commands: Vec<DrawCommand>,+ pub page_size: PtSize,+}++impl LayoutedPage {+ pub fn new(page_size: PtSize) -> Self {+ Self {+ commands: Vec::new(),+ page_size,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn shift_y_moves_text() {+ let mut cmd = DrawCommand::Text {+ position: PtOffset::new(Pt::new(10.0), Pt::new(20.0)),+ text: "hi".into(),+ font_family: Rc::from("Arial"),+ char_spacing: Pt::ZERO,+ font_size: Pt::new(12.0),+ bold: false,+ italic: false,+ color: RgbColor::BLACK,+ text_scale: 1.0,+ };+ cmd.shift_y(Pt::new(5.0));+ if let DrawCommand::Text { position, .. } = cmd {+ assert_eq!(position.y.raw(), 25.0);+ assert_eq!(position.x.raw(), 10.0); // x unchanged+ }+ }++ #[test]+ fn shift_y_moves_line() {+ let mut cmd = DrawCommand::Line {+ line: PtLineSegment::new(+ PtOffset::new(Pt::new(0.0), Pt::new(10.0)),+ PtOffset::new(Pt::new(100.0), Pt::new(10.0)),+ ),+ color: RgbColor::BLACK,+ width: Pt::new(1.0),+ };+ cmd.shift_y(Pt::new(50.0));+ if let DrawCommand::Line { line, .. } = cmd {+ assert_eq!(line.start.y.raw(), 60.0, "Line y shifted");+ }+ }++ #[test]+ fn shift_y_moves_rect() {+ let mut cmd = DrawCommand::Rect {+ rect: PtRect::from_xywh(Pt::new(0.0), Pt::new(10.0), Pt::new(50.0), Pt::new(20.0)),+ color: RgbColor::BLACK,+ };+ cmd.shift_y(Pt::new(100.0));+ if let DrawCommand::Rect { rect, .. } = cmd {+ assert_eq!(rect.origin.y.raw(), 110.0);+ }+ }++ #[test]+ fn layouted_page_new() {+ let page = LayoutedPage::new(PtSize::new(Pt::new(612.0), Pt::new(792.0)));+ assert!(page.commands.is_empty());+ assert_eq!(page.page_size.width.raw(), 612.0);+ }++ #[test]+ fn shift_y_moves_path_origin() {+ use crate::model::dimension::Dimension;++ let mut cmd = DrawCommand::Path {+ origin: PtOffset::new(Pt::new(10.0), Pt::new(20.0)),+ rotation: Dimension::new(0),+ flip_h: false,+ flip_v: false,+ extent: PtSize::new(Pt::new(100.0), Pt::new(50.0)),+ paths: vec![],+ fill: ResolvedFill::None,+ stroke: None,+ effects: vec![],+ };+ cmd.shift_y(Pt::new(7.5));+ if let DrawCommand::Path { origin, .. } = cmd {+ assert_eq!(origin.y.raw(), 27.5);+ assert_eq!(origin.x.raw(), 10.0);+ } else {+ panic!();+ }+ }++ // ── `shift` over every variant ───────────────────────────────────────+ //+ // The match in `shift` is exhaustive, so a *new* variant is a compile+ // error — that half is free. What exhaustiveness cannot check is whether+ // each arm moves the right field, which is what these cover. Six variants+ // (`Underline`, `Image`, `EmojiCluster`, `LinkAnnotation`, `InternalLink`,+ // `NamedDestination`) previously had no test at all, and `shift_x` had+ // none on any variant.++ const DX: f32 = 3.0;+ const DY: f32 = 7.0;++ fn origin_of(cmd: &DrawCommand) -> (f32, f32) {+ match cmd {+ DrawCommand::Text { position, .. } | DrawCommand::NamedDestination { position, .. } => {+ (position.x.raw(), position.y.raw())+ }+ DrawCommand::Underline { line, .. } | DrawCommand::Line { line, .. } => {+ (line.start.x.raw(), line.start.y.raw())+ }+ DrawCommand::Image { rect, .. }+ | DrawCommand::EmojiCluster { rect, .. }+ | DrawCommand::Rect { rect, .. }+ | DrawCommand::LinkAnnotation { rect, .. }+ | DrawCommand::InternalLink { rect, .. } => (rect.origin.x.raw(), rect.origin.y.raw()),+ DrawCommand::Path { origin, .. } => (origin.x.raw(), origin.y.raw()),+ // §17.3.1.19: a marked-content boundary has no coordinates, so+ // there is nothing for `shift` to move. `shift_leaves_a_marker_be`+ // asserts that directly rather than through this helper.+ DrawCommand::Outline(_) => unreachable!("markers are tested separately"),+ }+ }++ /// The only variant `one_of_each` cannot carry, because it has no origin to+ /// compare. Shifting it must leave it alone — the destination its outline+ /// entry gets is derived from the commands it brackets, which *are* shifted.+ #[test]+ fn shift_leaves_a_marker_be() {+ let heading = OutlineHeading {+ node_id: 7,+ level: crate::model::OutlineLevel::new(1),+ title: Rc::from("Title"),+ };+ for mut cmd in [+ DrawCommand::Outline(OutlineMark::Begin(heading)),+ DrawCommand::Outline(OutlineMark::End),+ ] {+ let before = format!("{cmd:?}");+ cmd.shift(Pt::new(DX), Pt::new(DY));+ assert_eq!(format!("{cmd:?}"), before);+ assert_eq!(cmd.vertical_span(), None, "a marker occupies no band");+ }+ }++ /// A sample of each variant, all anchored at (10, 20).+ fn one_of_each() -> Vec<(&'static str, DrawCommand)> {+ let at = |x: f32, y: f32| PtOffset::new(Pt::new(x), Pt::new(y));+ let rect = PtRect::from_xywh(Pt::new(10.0), Pt::new(20.0), Pt::new(4.0), Pt::new(4.0));+ let seg = PtLineSegment {+ start: at(10.0, 20.0),+ end: at(30.0, 20.0),+ };+ vec![+ (+ "Text",+ DrawCommand::Text {+ position: at(10.0, 20.0),+ text: "hi".into(),+ font_family: Rc::from("Arial"),+ char_spacing: Pt::ZERO,+ font_size: Pt::new(12.0),+ bold: false,+ italic: false,+ color: RgbColor::BLACK,+ text_scale: 1.0,+ },+ ),+ (+ "Underline",+ DrawCommand::Underline {+ line: seg,+ color: RgbColor::BLACK,+ width: Pt::new(1.0),+ },+ ),+ (+ "Line",+ DrawCommand::Line {+ line: seg,+ color: RgbColor::BLACK,+ width: Pt::new(1.0),+ },+ ),+ (+ "Rect",+ DrawCommand::Rect {+ rect,+ color: RgbColor::BLACK,+ },+ ),+ (+ "Image",+ DrawCommand::Image {+ rect,+ image_data: crate::render::resolve::images::MediaEntry {+ data: std::sync::Arc::from(&[0u8][..]),+ format: crate::model::ImageFormat::Png,+ },+ src_rect: None,+ },+ ),+ (+ "LinkAnnotation",+ DrawCommand::LinkAnnotation {+ rect,+ url: "https://example.invalid".into(),+ },+ ),+ (+ "InternalLink",+ DrawCommand::InternalLink {+ rect,+ destination: "bm".into(),+ },+ ),+ (+ "NamedDestination",+ DrawCommand::NamedDestination {+ position: at(10.0, 20.0),+ name: "bm".into(),+ },+ ),+ (+ "Path",+ DrawCommand::Path {+ origin: at(10.0, 20.0),+ rotation: Dimension::new(0),+ flip_h: false,+ flip_v: false,+ extent: PtSize::new(Pt::new(4.0), Pt::new(4.0)),+ paths: Vec::new(),+ fill: ResolvedFill::None,+ stroke: None,+ effects: Vec::new(),+ },+ ),+ ]+ }++ // ── `vertical_span` ──────────────────────────────────────────────────++ /// Every painting variant reports a band, and it must track the command:+ /// `one_of_each` places them all at y = 20, so shifting down by `DY` moves+ /// each band by exactly `DY`. Catches an arm that reads the wrong field.+ #[test]+ fn vertical_span_follows_every_painting_variant() {+ for (name, cmd) in one_of_each() {+ let Some((top, bottom)) = cmd.vertical_span() else {+ continue;+ };+ let mut moved = cmd;+ moved.shift_y(Pt::new(DY));+ let (top2, bottom2) = moved.vertical_span().expect("still paints");+ assert_eq!(top2.raw() - top.raw(), DY, "{name} top");+ assert_eq!(bottom2.raw() - bottom.raw(), DY, "{name} bottom");+ assert!(top.raw() <= bottom.raw(), "{name} band is inverted");+ }+ }++ /// The three annotation variants paint nothing of their own, so they have+ /// no band — a clip must not drop a link whose rect happens to hang below+ /// a box while the text it annotates is kept.+ #[test]+ fn annotations_have_no_vertical_span() {+ for (name, cmd) in one_of_each() {+ let expected_none = matches!(+ cmd,+ DrawCommand::LinkAnnotation { .. }+ | DrawCommand::InternalLink { .. }+ | DrawCommand::NamedDestination { .. }+ );+ assert_eq!(+ cmd.vertical_span().is_none(),+ expected_none,+ "{name} disagrees about whether it paints",+ );+ }+ }++ /// A `Text` command carries a baseline, not a box: the band straddles it.+ #[test]+ fn a_text_span_straddles_its_baseline() {+ let cmd = DrawCommand::Text {+ position: PtOffset::new(Pt::new(10.0), Pt::new(20.0)),+ text: Rc::from("x"),+ font_family: Rc::from("Arial"),+ char_spacing: Pt::ZERO,+ font_size: Pt::new(12.0),+ bold: false,+ italic: false,+ color: RgbColor::BLACK,+ text_scale: 1.0,+ };+ let (top, bottom) = cmd.vertical_span().unwrap();+ assert_eq!((top.raw(), bottom.raw()), (8.0, 32.0));+ }++ #[test]+ fn shift_moves_every_variant_on_both_axes() {+ for (name, mut cmd) in one_of_each() {+ cmd.shift(Pt::new(DX), Pt::new(DY));+ assert_eq!(origin_of(&cmd), (10.0 + DX, 20.0 + DY), "{name}");+ }+ }++ #[test]+ fn shift_x_and_shift_y_move_one_axis_each() {+ for (name, mut cmd) in one_of_each() {+ cmd.shift_x(Pt::new(DX));+ assert_eq!(origin_of(&cmd), (10.0 + DX, 20.0), "{name} shift_x");+ }+ for (name, mut cmd) in one_of_each() {+ cmd.shift_y(Pt::new(DY));+ assert_eq!(origin_of(&cmd), (10.0, 20.0 + DY), "{name} shift_y");+ }+ }++ /// A line has two endpoints; shifting must move both, or the segment+ /// changes length instead of position.+ #[test]+ fn shift_moves_both_ends_of_a_segment() {+ let mut cmd = DrawCommand::Line {+ line: PtLineSegment {+ start: PtOffset::new(Pt::new(10.0), Pt::new(20.0)),+ end: PtOffset::new(Pt::new(30.0), Pt::new(20.0)),+ },+ color: RgbColor::BLACK,+ width: Pt::new(1.0),+ };+ cmd.shift(Pt::new(DX), Pt::new(DY));+ let DrawCommand::Line { line, .. } = cmd else {+ unreachable!()+ };+ assert_eq!((line.start.x.raw(), line.start.y.raw()), (13.0, 27.0));+ assert_eq!((line.end.x.raw(), line.end.y.raw()), (33.0, 27.0));+ }++ /// `Path` carries its geometry in shape-local coordinates, so `shift` must+ /// move only the placement origin — moving the subpaths as well would+ /// double-apply the offset.+ #[test]+ fn shift_leaves_path_extent_and_geometry_alone() {+ let mut cmd = DrawCommand::Path {+ origin: PtOffset::new(Pt::new(10.0), Pt::new(20.0)),+ rotation: Dimension::new(0),+ flip_h: false,+ flip_v: false,+ extent: PtSize::new(Pt::new(4.0), Pt::new(6.0)),+ paths: Vec::new(),+ fill: ResolvedFill::None,+ stroke: None,+ effects: Vec::new(),+ };+ cmd.shift(Pt::new(DX), Pt::new(DY));+ let DrawCommand::Path { extent, .. } = cmd else {+ unreachable!()+ };+ assert_eq!((extent.width.raw(), extent.height.raw()), (4.0, 6.0));+ }+}diff --git a/crates/liteparse-docx/src/render/layout/mod.rs b/crates/liteparse-docx/src/render/layout/mod.rsnew file mode 100644index 0000000..57e2a75--- /dev/null+++ b/crates/liteparse-docx/src/render/layout/mod.rs@@ -0,0 +1,8 @@+//! Only the Skia-free part of dxpdf's layout stage.+//!+//! `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.++pub mod draw_command;diff --git a/crates/liteparse-docx/src/render/mod.rs b/crates/liteparse-docx/src/render/mod.rsnew file mode 100644index 0000000..c345e2c--- /dev/null+++ b/crates/liteparse-docx/src/render/mod.rs@@ -0,0 +1,18 @@+//! Skia-free half of dxpdf's render pipeline.+//!+//! 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.++pub mod dimension;+pub mod emoji;+pub mod error;+pub mod fonts;+pub mod geometry;+pub mod layout;+pub mod resolve;diff --git a/crates/liteparse-docx/src/render/resolve/color.rs b/crates/liteparse-docx/src/render/resolve/color.rsnew file mode 100644index 0000000..75e77fc--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/color.rs@@ -0,0 +1,159 @@+//! Color resolution — Color::Auto to RGB, theme color index to RGB.++use crate::model::{Color, ThemeColorIndex, ThemeColorScheme};++/// Resolved RGB color (0xRRGGBB).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct RgbColor {+ pub r: u8,+ pub g: u8,+ pub b: u8,+}++impl RgbColor {+ pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };+ pub const WHITE: Self = Self {+ r: 255,+ g: 255,+ b: 255,+ };+}++/// Context for resolving Color::Auto.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ColorContext {+ /// Text color — Auto means black.+ Text,+ /// Background/fill color — Auto means white.+ Background,+}++/// Resolve a model Color to concrete RGB.+pub fn resolve_color(color: Color, context: ColorContext) -> RgbColor {+ match color {+ Color::Rgb(v) => rgb_from_u32(v),+ Color::Auto => match context {+ ColorContext::Text => RgbColor::BLACK,+ ColorContext::Background => RgbColor::WHITE,+ },+ }+}++/// Resolve a theme color index to RGB via the color scheme.+pub fn resolve_theme_color(index: ThemeColorIndex, scheme: &ThemeColorScheme) -> RgbColor {+ rgb_from_u32(scheme.resolve(index))+}++/// Convert a packed u32 (0xRRGGBB) to RgbColor.+pub fn rgb_from_u32(v: u32) -> RgbColor {+ RgbColor {+ r: ((v >> 16) & 0xFF) as u8,+ g: ((v >> 8) & 0xFF) as u8,+ b: (v & 0xFF) as u8,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rgb_from_u32_red() {+ let c = rgb_from_u32(0xFF0000);+ assert_eq!(c, RgbColor { r: 255, g: 0, b: 0 });+ }++ #[test]+ fn rgb_from_u32_white() {+ let c = rgb_from_u32(0xFFFFFF);+ assert_eq!(c, RgbColor::WHITE);+ }++ #[test]+ fn rgb_from_u32_black() {+ let c = rgb_from_u32(0x000000);+ assert_eq!(c, RgbColor::BLACK);+ }++ #[test]+ fn rgb_from_u32_mixed() {+ let c = rgb_from_u32(0x1A2B3C);+ assert_eq!(+ c,+ RgbColor {+ r: 0x1A,+ g: 0x2B,+ b: 0x3C+ }+ );+ }++ #[test]+ fn resolve_color_rgb_passes_through() {+ let c = resolve_color(Color::Rgb(0x336699), ColorContext::Text);+ assert_eq!(+ c,+ RgbColor {+ r: 0x33,+ g: 0x66,+ b: 0x99+ }+ );+ }++ #[test]+ fn resolve_color_auto_text_is_black() {+ let c = resolve_color(Color::Auto, ColorContext::Text);+ assert_eq!(c, RgbColor::BLACK);+ }++ #[test]+ fn resolve_color_auto_background_is_white() {+ let c = resolve_color(Color::Auto, ColorContext::Background);+ assert_eq!(c, RgbColor::WHITE);+ }++ #[test]+ fn resolve_theme_color_accent1() {+ let scheme = ThemeColorScheme {+ accent1: 0x4472C4,+ ..Default::default()+ };+ let c = resolve_theme_color(ThemeColorIndex::Accent1, &scheme);+ assert_eq!(+ c,+ RgbColor {+ r: 0x44,+ g: 0x72,+ b: 0xC4+ }+ );+ }++ #[test]+ fn resolve_theme_color_dark1() {+ let scheme = ThemeColorScheme {+ dark1: 0x000000,+ ..Default::default()+ };+ let c = resolve_theme_color(ThemeColorIndex::Dark1, &scheme);+ assert_eq!(c, RgbColor::BLACK);+ }++ #[test]+ fn resolve_theme_color_hyperlink() {+ let scheme = ThemeColorScheme {+ hyperlink: 0x0563C1,+ ..Default::default()+ };+ let c = resolve_theme_color(ThemeColorIndex::Hyperlink, &scheme);+ assert_eq!(+ c,+ RgbColor {+ r: 0x05,+ g: 0x63,+ b: 0xC1+ }+ );+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/conditional.rs b/crates/liteparse-docx/src/render/resolve/conditional.rsnew file mode 100644index 0000000..e259d68--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/conditional.rs@@ -0,0 +1,657 @@+//! §17.7.6: Table conditional formatting resolution.+//!+//! Determines which conditional formatting regions apply to each cell+//! based on its position, tblLook flags, and band sizes. Overlays+//! applicable tblStylePr overrides in priority order.++use crate::model::{+ ParagraphProperties, RunProperties, TableCellProperties, TableLook, TableStyleOverride,+ TableStyleOverrideType,+};++/// Resolved conditional formatting for a single cell.+#[derive(Clone, Debug, Default)]+pub struct CellConditionalFormatting {+ pub cell_properties: Option<TableCellProperties>,+ pub run_properties: Option<RunProperties>,+ pub paragraph_properties: Option<ParagraphProperties>,+}++/// Grid position and dimension context for a single cell.+pub struct CellGridPosition {+ pub row_idx: usize,+ pub col_idx: usize,+ pub num_rows: usize,+ pub num_cols: usize,+ pub row_band_size: u32,+ pub col_band_size: u32,+}++/// §17.7.6: resolve conditional formatting for a cell at (row, col).+///+/// Overlays applicable `tblStylePr` overrides in ascending priority (later+/// overlays win), per §17.7.6:+/// 0. `wholeTable` — the base layer, applying to every cell+/// 1. Band1/Band2 Vertical (banded columns)+/// 2. Band1/Band2 Horizontal (banded rows — override column banding)+/// 3. First/Last Column+/// 4. First/Last Row+/// 5. Corner cells (highest)+///+/// `wholeTable` is not positional — it applies to every cell — so it is not+/// produced by `applicable_regions`, which answers "which *positional* regions+/// is this cell in?". Seeding the chain with it here keeps that function honest+/// and reuses the existing overlay machinery unchanged, so the positional+/// precedence (including D1's banding fix) is untouched: `wholeTable` simply+/// sits underneath.+///+/// The table-level half — a `wholeTable` override's `tblPr` (borders, cell+/// margins) — is folded into `ResolvedStyle::table` during style resolution,+/// because that is where `build_table` reads them from.+pub fn resolve_cell_conditional(+ pos: &CellGridPosition,+ look: Option<&TableLook>,+ overrides: &[TableStyleOverride],+) -> CellConditionalFormatting {+ let regions = applicable_regions(+ pos.row_idx,+ pos.col_idx,+ pos.num_rows,+ pos.num_cols,+ look,+ pos.row_band_size,+ pos.col_band_size,+ );++ let mut result = CellConditionalFormatting::default();++ // §17.7.6: apply overrides in priority order (lowest first, highest last).+ // Later overlays take precedence.+ for region in std::iter::once(&TableStyleOverrideType::WholeTable).chain(regions.iter()) {+ if let Some(ovr) = overrides.iter().find(|o| o.override_type == *region) {+ if let Some(ref tcp) = ovr.table_cell_properties {+ overlay_cell_properties(&mut result, tcp);+ }+ if let Some(ref rp) = ovr.run_properties {+ overlay_run_properties(&mut result, rp);+ }+ if let Some(ref pp) = ovr.paragraph_properties {+ overlay_paragraph_properties(&mut result, pp);+ }+ }+ }++ result+}++/// §17.7.6: determine which regions apply to a cell, in priority order+/// (lowest priority first). §17.4.56 tblLook controls which regions are active.+fn applicable_regions(+ row_idx: usize,+ col_idx: usize,+ num_rows: usize,+ num_cols: usize,+ look: Option<&TableLook>,+ row_band_size: u32,+ col_band_size: u32,+) -> Vec<TableStyleOverrideType> {+ let mut regions = Vec::new();++ // §17.4.56: tblLook flags. When absent, all regions are active.+ let first_row_active = look.and_then(|l| l.first_row).unwrap_or(true);+ let last_row_active = look.and_then(|l| l.last_row).unwrap_or(true);+ let first_col_active = look.and_then(|l| l.first_column).unwrap_or(true);+ let last_col_active = look.and_then(|l| l.last_column).unwrap_or(true);+ let h_band_active = !look.and_then(|l| l.no_h_band).unwrap_or(false);+ let v_band_active = !look.and_then(|l| l.no_v_band).unwrap_or(false);++ // §17.7.6 priority 1: vertical banding (banded columns). Pushed *before*+ // horizontal banding so that — per the spec's ascending order (band1Vert,+ // band2Vert, band1Horz, band2Horz) — row banding overrides column banding.+ if v_band_active {+ let band_col = if first_col_active && col_idx > 0 {+ col_idx - 1+ } else {+ col_idx+ };+ let band_size = col_band_size.max(1) as usize;+ let in_first_band = (band_col / band_size).is_multiple_of(2);++ let is_first = first_col_active && col_idx == 0;+ let is_last = last_col_active && col_idx == num_cols - 1;+ if !is_first && !is_last {+ if in_first_band {+ regions.push(TableStyleOverrideType::Band1Vert);+ } else {+ regions.push(TableStyleOverrideType::Band2Vert);+ }+ }+ }++ // §17.7.6 priority 2: horizontal banding (banded rows) — higher priority+ // than vertical banding.+ if h_band_active {+ // When firstRow is active, banding starts from row 1.+ let band_row = if first_row_active && row_idx > 0 {+ row_idx - 1+ } else {+ row_idx+ };+ let band_size = row_band_size.max(1) as usize;+ let in_first_band = (band_row / band_size).is_multiple_of(2);++ // Don't apply banding to first/last row if those regions are active.+ let is_first = first_row_active && row_idx == 0;+ let is_last = last_row_active && row_idx == num_rows - 1;+ if !is_first && !is_last {+ if in_first_band {+ regions.push(TableStyleOverrideType::Band1Horz);+ } else {+ regions.push(TableStyleOverrideType::Band2Horz);+ }+ }+ }++ // §17.7.6 priority 4: first/last column.+ if first_col_active && col_idx == 0 {+ regions.push(TableStyleOverrideType::FirstCol);+ }+ if last_col_active && col_idx == num_cols - 1 {+ regions.push(TableStyleOverrideType::LastCol);+ }++ // §17.7.6 priority 5: first/last row.+ if first_row_active && row_idx == 0 {+ regions.push(TableStyleOverrideType::FirstRow);+ }+ if last_row_active && row_idx == num_rows - 1 {+ regions.push(TableStyleOverrideType::LastRow);+ }++ // §17.7.6 priority 6: corner cells (highest priority).+ if first_row_active && first_col_active && row_idx == 0 && col_idx == 0 {+ regions.push(TableStyleOverrideType::NwCell);+ }+ if first_row_active && last_col_active && row_idx == 0 && col_idx == num_cols - 1 {+ regions.push(TableStyleOverrideType::NeCell);+ }+ if last_row_active && first_col_active && row_idx == num_rows - 1 && col_idx == 0 {+ regions.push(TableStyleOverrideType::SwCell);+ }+ if last_row_active && last_col_active && row_idx == num_rows - 1 && col_idx == num_cols - 1 {+ regions.push(TableStyleOverrideType::SeCell);+ }++ regions+}++/// Overlay cell properties (higher priority replaces existing values).+fn overlay_cell_properties(result: &mut CellConditionalFormatting, tcp: &TableCellProperties) {+ let target = result+ .cell_properties+ .get_or_insert_with(TableCellProperties::default);++ // §17.7.6: each non-None field from the overlay replaces the target.+ if tcp.shading.is_some() {+ target.shading = tcp.shading;+ }+ if let Some(ref src) = tcp.borders {+ // §17.7.6: when a tblStylePr has tcBorders, it REPLACES all cell+ // borders for that region. Sides not mentioned are implicitly nil.+ target.borders = Some(*src);+ }+ if tcp.vertical_align.is_some() {+ target.vertical_align = tcp.vertical_align;+ }+}++/// Overlay run properties (higher priority replaces existing values).+fn overlay_run_properties(result: &mut CellConditionalFormatting, rp: &RunProperties) {+ let target = result+ .run_properties+ .get_or_insert_with(RunProperties::default);+ // Higher priority: overlay's values replace target's.+ // Use merge in reverse: merge target into a clone of overlay.+ let mut merged = rp.clone();+ crate::render::resolve::properties::merge_run_properties(&mut merged, target);+ *target = merged;+}++/// Overlay paragraph properties (higher priority replaces existing values).+fn overlay_paragraph_properties(result: &mut CellConditionalFormatting, pp: &ParagraphProperties) {+ let target = result+ .paragraph_properties+ .get_or_insert_with(ParagraphProperties::default);+ let mut merged = pp.clone();+ crate::render::resolve::properties::merge_paragraph_properties(&mut merged, target);+ *target = merged;+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::*;++ fn make_override(+ override_type: TableStyleOverrideType,+ shading: Option<Shading>,+ bold: Option<bool>,+ ) -> TableStyleOverride {+ TableStyleOverride {+ override_type,+ paragraph_properties: None,+ run_properties: bold.map(|b| RunProperties {+ bold: Some(b),+ ..Default::default()+ }),+ table_properties: None,+ table_row_properties: None,+ table_cell_properties: shading.map(|s| TableCellProperties {+ shading: Some(s),+ ..Default::default()+ }),+ }+ }++ fn green_shading() -> Shading {+ Shading {+ fill: Color::Rgb(0x9BBB59),+ pattern: ShadingPattern::Clear,+ color: Color::Auto,+ }+ }++ fn blue_shading() -> Shading {+ Shading {+ fill: Color::Rgb(0xD3DFEE),+ pattern: ShadingPattern::Clear,+ color: Color::Auto,+ }+ }++ // ── Region detection ─────────────────────────────────────────────++ #[test]+ fn first_row_detected() {+ let regions = applicable_regions(0, 2, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::FirstRow));+ assert!(!regions.contains(&TableStyleOverrideType::LastRow));+ }++ #[test]+ fn last_row_detected() {+ let regions = applicable_regions(5, 2, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::LastRow));+ assert!(!regions.contains(&TableStyleOverrideType::FirstRow));+ }++ #[test]+ fn first_col_detected() {+ let regions = applicable_regions(2, 0, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::FirstCol));+ }++ #[test]+ fn last_col_detected() {+ let regions = applicable_regions(2, 5, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::LastCol));+ }++ #[test]+ fn nw_corner_detected() {+ let regions = applicable_regions(0, 0, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::NwCell));+ assert!(regions.contains(&TableStyleOverrideType::FirstRow));+ assert!(regions.contains(&TableStyleOverrideType::FirstCol));+ }++ #[test]+ fn se_corner_detected() {+ let regions = applicable_regions(5, 5, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::SeCell));+ }++ #[test]+ fn interior_cell_gets_banding() {+ let regions = applicable_regions(1, 1, 6, 6, None, 1, 1);+ // Row 1 with firstRow active: band_row = 0 → band1+ assert!(regions.contains(&TableStyleOverrideType::Band1Horz));+ }++ #[test]+ fn banding_alternates() {+ // Row 2 with firstRow active: band_row = 1 → band2+ let regions = applicable_regions(2, 1, 6, 6, None, 1, 1);+ assert!(regions.contains(&TableStyleOverrideType::Band2Horz));+ }++ #[test]+ fn no_h_band_disables_banding() {+ let look = TableLook {+ first_row: Some(true),+ last_row: Some(true),+ first_column: Some(true),+ last_column: Some(true),+ no_h_band: Some(true),+ no_v_band: None,+ };+ let regions = applicable_regions(1, 1, 6, 6, Some(&look), 1, 1);+ assert!(!regions.contains(&TableStyleOverrideType::Band1Horz));+ assert!(!regions.contains(&TableStyleOverrideType::Band2Horz));+ }++ #[test]+ fn first_row_disabled_by_look() {+ let look = TableLook {+ first_row: Some(false),+ last_row: None,+ first_column: None,+ last_column: None,+ no_h_band: None,+ no_v_band: None,+ };+ let regions = applicable_regions(0, 2, 6, 6, Some(&look), 1, 1);+ assert!(!regions.contains(&TableStyleOverrideType::FirstRow));+ }++ #[test]+ fn band_size_2() {+ // Row 1 with firstRow: band_row=0, band_size=2 → 0/2=0 → band1+ let r1 = applicable_regions(1, 1, 10, 6, None, 2, 1);+ assert!(r1.contains(&TableStyleOverrideType::Band1Horz));++ // Row 2: band_row=1, 1/2=0 → band1+ let r2 = applicable_regions(2, 1, 10, 6, None, 2, 1);+ assert!(r2.contains(&TableStyleOverrideType::Band1Horz));++ // Row 3: band_row=2, 2/2=1 → band2+ let r3 = applicable_regions(3, 1, 10, 6, None, 2, 1);+ assert!(r3.contains(&TableStyleOverrideType::Band2Horz));+ }++ // ── Priority overlay ─────────────────────────────────────────────++ #[test]+ fn first_row_shading_applied() {+ let overrides = vec![make_override(+ TableStyleOverrideType::FirstRow,+ Some(green_shading()),+ Some(true),+ )];+ let result = resolve_cell_conditional(+ &CellGridPosition {+ row_idx: 0,+ col_idx: 2,+ num_rows: 6,+ num_cols: 6,+ row_band_size: 1,+ col_band_size: 1,+ },+ None,+ &overrides,+ );+ assert!(result.cell_properties.is_some());+ assert!(result.cell_properties.as_ref().unwrap().shading.is_some());+ assert!(result.run_properties.as_ref().unwrap().bold == Some(true));+ }++ #[test]+ fn banding_shading_for_interior() {+ let overrides = vec![make_override(+ TableStyleOverrideType::Band1Horz,+ Some(blue_shading()),+ None,+ )];+ let result = resolve_cell_conditional(+ &CellGridPosition {+ row_idx: 1,+ col_idx: 2,+ num_rows: 6,+ num_cols: 6,+ row_band_size: 1,+ col_band_size: 1,+ },+ None,+ &overrides,+ );+ let shading = result+ .cell_properties+ .as_ref()+ .unwrap()+ .shading+ .as_ref()+ .unwrap();+ assert_eq!(shading.fill, Color::Rgb(0xD3DFEE));+ }++ #[test]+ fn corner_overrides_first_row() {+ let overrides = vec![+ make_override(+ TableStyleOverrideType::FirstRow,+ Some(green_shading()),+ None,+ ),+ make_override(TableStyleOverrideType::NwCell, Some(blue_shading()), None),+ ];+ let result = resolve_cell_conditional(+ &CellGridPosition {+ row_idx: 0,+ col_idx: 0,+ num_rows: 6,+ num_cols: 6,+ row_band_size: 1,+ col_band_size: 1,+ },+ None,+ &overrides,+ );+ // NW corner has higher priority than FirstRow.+ let shading = result+ .cell_properties+ .as_ref()+ .unwrap()+ .shading+ .as_ref()+ .unwrap();+ assert_eq!(shading.fill, Color::Rgb(0xD3DFEE));+ }++ #[test]+ fn no_overrides_returns_empty() {+ let result = resolve_cell_conditional(+ &CellGridPosition {+ row_idx: 2,+ col_idx: 2,+ num_rows: 6,+ num_cols: 6,+ row_band_size: 1,+ col_band_size: 1,+ },+ None,+ &[],+ );+ assert!(result.cell_properties.is_none());+ assert!(result.run_properties.is_none());+ }++ #[test]+ fn horizontal_banding_overrides_vertical() {+ // §17.7.6: band1Horz is applied after band1Vert, so on a cell that is in+ // both an odd row-band and an odd column-band the *row* banding wins.+ let overrides = vec![+ make_override(+ TableStyleOverrideType::Band1Vert,+ Some(blue_shading()),+ None,+ ),+ make_override(+ TableStyleOverrideType::Band1Horz,+ Some(green_shading()),+ None,+ ),+ ];+ // Interior cell (1,1): band_row=0 → Band1Horz, band_col=0 → Band1Vert.+ let result = resolve_cell_conditional(+ &CellGridPosition {+ row_idx: 1,+ col_idx: 1,+ num_rows: 6,+ num_cols: 6,+ row_band_size: 1,+ col_band_size: 1,+ },+ None,+ &overrides,+ );+ let shading = result.cell_properties.unwrap().shading.unwrap();+ assert_eq!(+ shading.fill,+ Color::Rgb(0x9BBB59),+ "row banding (green) must override column banding (blue)"+ );+ }++ // ── wholeTable base layer (§17.7.6, backlog Unit 5) ──────────────++ fn pos(row_idx: usize, col_idx: usize) -> CellGridPosition {+ CellGridPosition {+ row_idx,+ col_idx,+ num_rows: 6,+ num_cols: 6,+ row_band_size: 1,+ col_band_size: 1,+ }+ }++ fn red_shading() -> Shading {+ Shading {+ fill: Color::Rgb(0xFF0000),+ pattern: ShadingPattern::Clear,+ color: Color::Auto,+ }+ }++ /// `wholeTable` applies to every cell — including plain interior cells that+ /// match no positional region at all, which used to resolve to nothing.+ #[test]+ fn whole_table_applies_to_an_interior_cell() {+ let overrides = vec![make_override(+ TableStyleOverrideType::WholeTable,+ Some(red_shading()),+ Some(true),+ )];+ // (2,2) with band sizes of 1 lands in a band, but a table whose style+ // declares no banding override still gets the base layer.+ let result = resolve_cell_conditional(&pos(2, 2), None, &overrides);+ assert_eq!(+ result.cell_properties.unwrap().shading.unwrap().fill,+ Color::Rgb(0xFF0000)+ );+ assert_eq!(result.run_properties.unwrap().bold, Some(true));+ }++ /// …and to the corners, where the highest-priority region also applies.+ #[test]+ fn whole_table_applies_to_every_position() {+ let overrides = vec![make_override(+ TableStyleOverrideType::WholeTable,+ Some(red_shading()),+ None,+ )];+ for (r, c) in [(0, 0), (0, 5), (5, 0), (5, 5), (0, 3), (3, 0), (3, 3)] {+ let result = resolve_cell_conditional(&pos(r, c), None, &overrides);+ assert_eq!(+ result+ .cell_properties+ .and_then(|p| p.shading)+ .map(|s| s.fill),+ Some(Color::Rgb(0xFF0000)),+ "cell ({r},{c}) must receive the wholeTable base layer"+ );+ }+ }++ /// It is the *base*: every positional region outranks it.+ #[test]+ fn positional_regions_override_whole_table() {+ for (region, r, c) in [+ (TableStyleOverrideType::Band1Horz, 1, 2),+ (TableStyleOverrideType::FirstRow, 0, 2),+ (TableStyleOverrideType::FirstCol, 2, 0),+ (TableStyleOverrideType::NwCell, 0, 0),+ ] {+ let overrides = vec![+ make_override(+ TableStyleOverrideType::WholeTable,+ Some(red_shading()),+ None,+ ),+ make_override(region, Some(green_shading()), None),+ ];+ let result = resolve_cell_conditional(&pos(r, c), None, &overrides);+ assert_eq!(+ result.cell_properties.unwrap().shading.unwrap().fill,+ Color::Rgb(0x9BBB59),+ "{region:?} must outrank wholeTable"+ );+ }+ }++ /// A positional override that sets only *some* properties leaves the rest+ /// of the base layer showing through — that is what makes it a layer and+ /// not a replacement.+ #[test]+ fn whole_table_shows_through_a_partial_positional_override() {+ let overrides = vec![+ make_override(+ TableStyleOverrideType::WholeTable,+ Some(red_shading()),+ Some(true),+ ),+ // firstRow sets bold=false but no shading.+ make_override(TableStyleOverrideType::FirstRow, None, Some(false)),+ ];+ let result = resolve_cell_conditional(&pos(0, 2), None, &overrides);+ assert_eq!(+ result.cell_properties.unwrap().shading.unwrap().fill,+ Color::Rgb(0xFF0000),+ "shading falls through from wholeTable"+ );+ assert_eq!(+ result.run_properties.unwrap().bold,+ Some(false),+ "but firstRow's own bold wins"+ );+ }++ /// D1 fixed horizontal-over-vertical banding precedence (§17.7.6). Adding a+ /// base layer beneath both must not disturb it.+ #[test]+ fn whole_table_does_not_disturb_banding_precedence() {+ let overrides = vec![+ make_override(+ TableStyleOverrideType::WholeTable,+ Some(red_shading()),+ None,+ ),+ make_override(+ TableStyleOverrideType::Band1Vert,+ Some(blue_shading()),+ None,+ ),+ make_override(+ TableStyleOverrideType::Band1Horz,+ Some(green_shading()),+ None,+ ),+ ];+ let result = resolve_cell_conditional(&pos(1, 1), None, &overrides);+ assert_eq!(+ result.cell_properties.unwrap().shading.unwrap().fill,+ Color::Rgb(0x9BBB59),+ "row banding must still override column banding, and both the base"+ );+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/drawing_color.rs b/crates/liteparse-docx/src/render/resolve/drawing_color.rsnew file mode 100644index 0000000..4d0b4d5--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/drawing_color.rs@@ -0,0 +1,799 @@+//! DrawingML color resolver (§20.1.2.3).+//!+//! Takes a parsed `DrawingColor` and a `ColorContext` (theme + bg/tx+//! convention) and produces a concrete `Rgba`. Color transforms are applied+//! in document order via a pure left-fold.+//!+//! ## Spec references for transforms+//!+//! Most transforms can be described in one of two spaces:+//!+//! * **RGB-direct**: `red`/`green`/`blue` and their `Off`/`Mod` siblings+//! act directly on sRGB channels. Absolute forms overwrite the channel;+//! offsets add a signed percentage; multipliers scale (clamped to `[0,1]`).+//! * **HSL-space**: `hue`/`sat`/`lum` and their siblings convert the color+//! to HSL, modify the named component, and convert back.+//!+//! Intensity transforms:+//!+//! * `tint(p)` — per-channel: `c' = c + (1 - c) * p` (§20.1.2.3.34).+//! * `shade(p)` — per-channel: `c' = c * (1 - p)` (§20.1.2.3.31).+//! * `comp` — HSL hue rotated by 180° (§20.1.2.3.7).+//! * `inv` — per-channel: `c' = 1 - c` (§20.1.2.3.17).+//! * `gray` — luminance-preserving desaturation (§20.1.2.3.8). The+//! resulting value sets all three sRGB channels to the original luminance.+//! * `gamma` — sRGB → linear (§20.1.2.3.9).+//! * `invGamma` — linear → sRGB (§20.1.2.3.18).+//!+//! Alpha transforms act on the alpha channel only (§20.1.2.3.1/2/3).++use crate::model::dimension::{Dimension, SixtieThousandthDeg, ThousandthPercent};+use crate::model::{ColorTransform, DrawingColor, SchemeColorVal, Theme};++/// RGBA with per-channel `f32` in `[0, 1]`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Rgba {+ pub r: f32,+ pub g: f32,+ pub b: f32,+ pub a: f32,+}++impl Rgba {+ pub const BLACK: Self = Self {+ r: 0.0,+ g: 0.0,+ b: 0.0,+ a: 1.0,+ };+ pub const WHITE: Self = Self {+ r: 1.0,+ g: 1.0,+ b: 1.0,+ a: 1.0,+ };++ /// Construct from a packed `0xRRGGBB` sRGB value with full alpha.+ pub fn from_rgb24(v: u32) -> Self {+ Self {+ r: ((v >> 16) & 0xFF) as f32 / 255.0,+ g: ((v >> 8) & 0xFF) as f32 / 255.0,+ b: (v & 0xFF) as f32 / 255.0,+ a: 1.0,+ }+ }++ /// Convert to a packed `0xRRGGBB` sRGB value (alpha discarded).+ pub fn to_rgb24(self) -> u32 {+ let c = |v: f32| -> u32 { ((v.clamp(0.0, 1.0) * 255.0).round() as u32) & 0xFF };+ (c(self.r) << 16) | (c(self.g) << 8) | c(self.b)+ }+}++/// §17.3.1.31: Word documents treat `tx1`/`bg1`/`tx2`/`bg2` as references+/// against an assumed background brightness. For light-backgrounded bodies+/// (Word's default) `tx1 → dk1`, `bg1 → lt1`, etc. Dark themes invert.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum BgTxConvention {+ #[default]+ LightBackground,+ DarkBackground,+}++/// Resolver context. `theme` is optional because documents can omit theme+/// parts; when missing, scheme references fall back to black.+#[derive(Clone, Copy, Debug)]+pub struct DrawingColorContext<'a> {+ pub theme: Option<&'a Theme>,+ pub bg_tx_convention: BgTxConvention,+ /// §20.1.2.3.29: the value substituted for `phClr` when resolving a theme+ /// style-matrix fill referenced via `<a:fillRef>`. `None` outside that+ /// context (body `phClr` has no concrete color and falls back to black).+ pub placeholder: Option<Rgba>,+}++impl<'a> DrawingColorContext<'a> {+ pub fn new(theme: Option<&'a Theme>) -> Self {+ Self {+ theme,+ bg_tx_convention: BgTxConvention::LightBackground,+ placeholder: None,+ }+ }++ /// Return a copy of this context with a `phClr` substitute installed.+ pub fn with_placeholder(self, color: Rgba) -> Self {+ Self {+ placeholder: Some(color),+ ..self+ }+ }+}++/// Resolve a `DrawingColor` to its final RGBA.+pub fn resolve_drawing_color(color: &DrawingColor, ctx: &DrawingColorContext<'_>) -> Rgba {+ let base = resolve_base(color, ctx);+ color.transforms().iter().fold(base, apply_transform)+}++// ── Base color resolution ───────────────────────────────────────────────────++fn resolve_base(color: &DrawingColor, ctx: &DrawingColorContext<'_>) -> Rgba {+ match color {+ DrawingColor::Srgb { rgb, .. } => Rgba::from_rgb24(*rgb),+ DrawingColor::ScRgb { r, g, b, .. } => Rgba {+ r: pct_f32(*r),+ g: pct_f32(*g),+ b: pct_f32(*b),+ a: 1.0,+ },+ DrawingColor::Hsl { hue, sat, lum, .. } => {+ hsl_to_rgba(angle_f32(*hue), pct_f32(*sat), pct_f32(*lum))+ }+ DrawingColor::Sys { name, last_clr, .. } => {+ Rgba::from_rgb24(last_clr.unwrap_or_else(|| name.default_rgb()))+ }+ DrawingColor::Scheme { name, .. } => resolve_scheme(*name, ctx),+ DrawingColor::Prst { name, .. } => Rgba::from_rgb24(name.rgb()),+ }+}++fn resolve_scheme(name: SchemeColorVal, ctx: &DrawingColorContext<'_>) -> Rgba {+ // §20.1.2.3.29: phClr is the theme style-matrix placeholder. When resolving+ // a `<a:fillRef>` theme fill, it is substituted by the ref's own color;+ // elsewhere (body content) it has no concrete value and falls back to black.+ if matches!(name, SchemeColorVal::PhClr) {+ return ctx.placeholder.unwrap_or(Rgba::BLACK);+ }+ let theme = match ctx.theme {+ Some(t) => t,+ None => return Rgba::BLACK,+ };+ let scheme = &theme.color_scheme;+ let rgb = match (name, ctx.bg_tx_convention) {+ (SchemeColorVal::Dk1, _) => scheme.dark1,+ (SchemeColorVal::Lt1, _) => scheme.light1,+ (SchemeColorVal::Dk2, _) => scheme.dark2,+ (SchemeColorVal::Lt2, _) => scheme.light2,++ // §17.3.1.31: Word light-background convention maps tx↔dk and bg↔lt.+ (SchemeColorVal::Tx1, BgTxConvention::LightBackground) => scheme.dark1,+ (SchemeColorVal::Bg1, BgTxConvention::LightBackground) => scheme.light1,+ (SchemeColorVal::Tx2, BgTxConvention::LightBackground) => scheme.dark2,+ (SchemeColorVal::Bg2, BgTxConvention::LightBackground) => scheme.light2,+ (SchemeColorVal::Tx1, BgTxConvention::DarkBackground) => scheme.light1,+ (SchemeColorVal::Bg1, BgTxConvention::DarkBackground) => scheme.dark1,+ (SchemeColorVal::Tx2, BgTxConvention::DarkBackground) => scheme.light2,+ (SchemeColorVal::Bg2, BgTxConvention::DarkBackground) => scheme.dark2,++ (SchemeColorVal::Accent1, _) => scheme.accent1,+ (SchemeColorVal::Accent2, _) => scheme.accent2,+ (SchemeColorVal::Accent3, _) => scheme.accent3,+ (SchemeColorVal::Accent4, _) => scheme.accent4,+ (SchemeColorVal::Accent5, _) => scheme.accent5,+ (SchemeColorVal::Accent6, _) => scheme.accent6,+ (SchemeColorVal::Hlink, _) => scheme.hyperlink,+ (SchemeColorVal::FolHlink, _) => scheme.followed_hyperlink,++ (SchemeColorVal::PhClr, _) => {+ // §20.1.2.3.29 phClr is a placeholder used by master/layout parts;+ // for Word body content it has no concrete RGB. Fall back to black+ // rather than producing a panic.+ 0x000000+ }+ };+ Rgba::from_rgb24(rgb)+}++// ── Transform application ───────────────────────────────────────────────────++fn apply_transform(c: Rgba, t: &ColorTransform) -> Rgba {+ match t {+ // Intensity+ ColorTransform::Tint(p) => apply_tint(c, pct_f32(*p)),+ ColorTransform::Shade(p) => apply_shade(c, pct_f32(*p)),+ ColorTransform::Comp => apply_comp(c),+ ColorTransform::Inv => Rgba {+ r: 1.0 - c.r,+ g: 1.0 - c.g,+ b: 1.0 - c.b,+ a: c.a,+ },+ ColorTransform::Gray => apply_gray(c),+ ColorTransform::Gamma => Rgba {+ r: srgb_to_linear(c.r),+ g: srgb_to_linear(c.g),+ b: srgb_to_linear(c.b),+ a: c.a,+ },+ ColorTransform::InvGamma => Rgba {+ r: linear_to_srgb(c.r),+ g: linear_to_srgb(c.g),+ b: linear_to_srgb(c.b),+ a: c.a,+ },++ // Alpha+ ColorTransform::Alpha(p) => Rgba {+ a: pct_f32(*p).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::AlphaOff(p) => Rgba {+ a: (c.a + pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::AlphaMod(p) => Rgba {+ a: (c.a * pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },++ // HSL+ ColorTransform::Hue(a) => hsl_adjust(c, |_h, s, l| (angle_f32(*a), s, l)),+ ColorTransform::HueOff(a) => {+ hsl_adjust(c, |h, s, l| ((h + angle_f32(*a)).rem_euclid(1.0), s, l))+ }+ ColorTransform::HueMod(p) => {+ hsl_adjust(c, |h, s, l| ((h * pct_f32(*p)).rem_euclid(1.0), s, l))+ }+ ColorTransform::Sat(p) => hsl_adjust(c, |h, _s, l| (h, pct_f32(*p).clamp(0.0, 1.0), l)),+ ColorTransform::SatOff(p) => {+ hsl_adjust(c, |h, s, l| (h, (s + pct_f32(*p)).clamp(0.0, 1.0), l))+ }+ ColorTransform::SatMod(p) => {+ hsl_adjust(c, |h, s, l| (h, (s * pct_f32(*p)).clamp(0.0, 1.0), l))+ }+ ColorTransform::Lum(p) => hsl_adjust(c, |h, s, _l| (h, s, pct_f32(*p).clamp(0.0, 1.0))),+ ColorTransform::LumOff(p) => {+ hsl_adjust(c, |h, s, l| (h, s, (l + pct_f32(*p)).clamp(0.0, 1.0)))+ }+ ColorTransform::LumMod(p) => {+ hsl_adjust(c, |h, s, l| (h, s, (l * pct_f32(*p)).clamp(0.0, 1.0)))+ }++ // Per-RGB-channel+ ColorTransform::Red(p) => Rgba {+ r: pct_f32(*p).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::RedOff(p) => Rgba {+ r: (c.r + pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::RedMod(p) => Rgba {+ r: (c.r * pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::Green(p) => Rgba {+ g: pct_f32(*p).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::GreenOff(p) => Rgba {+ g: (c.g + pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::GreenMod(p) => Rgba {+ g: (c.g * pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::Blue(p) => Rgba {+ b: pct_f32(*p).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::BlueOff(p) => Rgba {+ b: (c.b + pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ ColorTransform::BlueMod(p) => Rgba {+ b: (c.b * pct_f32(*p)).clamp(0.0, 1.0),+ ..c+ },+ }+}++fn apply_tint(c: Rgba, p: f32) -> Rgba {+ let p = p.clamp(0.0, 1.0);+ Rgba {+ r: c.r + (1.0 - c.r) * p,+ g: c.g + (1.0 - c.g) * p,+ b: c.b + (1.0 - c.b) * p,+ a: c.a,+ }+}++fn apply_shade(c: Rgba, p: f32) -> Rgba {+ let p = p.clamp(0.0, 1.0);+ Rgba {+ r: c.r * (1.0 - p),+ g: c.g * (1.0 - p),+ b: c.b * (1.0 - p),+ a: c.a,+ }+}++fn apply_comp(c: Rgba) -> Rgba {+ let (h, s, l) = rgba_to_hsl(c);+ let h2 = (h + 0.5).rem_euclid(1.0);+ let (r, g, b) = hsl_to_rgb(h2, s, l);+ Rgba { r, g, b, a: c.a }+}++fn apply_gray(c: Rgba) -> Rgba {+ // ITU-R BT.601 luminance.+ let y = 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;+ Rgba {+ r: y,+ g: y,+ b: y,+ a: c.a,+ }+}++fn hsl_adjust<F: FnOnce(f32, f32, f32) -> (f32, f32, f32)>(c: Rgba, f: F) -> Rgba {+ let (h, s, l) = rgba_to_hsl(c);+ let (h, s, l) = f(h, s, l);+ let (r, g, b) = hsl_to_rgb(h, s, l);+ Rgba { r, g, b, a: c.a }+}++// ── Color space conversions ────────────────────────────────────────────────++fn pct_f32(p: Dimension<ThousandthPercent>) -> f32 {+ p.to_fraction()+}++fn angle_f32(a: Dimension<SixtieThousandthDeg>) -> f32 {+ // Normalize any angle to [0, 1) expressed as a fraction of a full turn.+ let degrees = a.raw() as f32 / 60_000.0;+ (degrees / 360.0).rem_euclid(1.0)+}++fn hsl_to_rgba(h: f32, s: f32, l: f32) -> Rgba {+ let (r, g, b) = hsl_to_rgb(h, s, l);+ Rgba { r, g, b, a: 1.0 }+}++/// HSL → RGB. All inputs and outputs in [0, 1].+fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) {+ if s <= 0.0 {+ return (l, l, l);+ }+ let q = if l < 0.5 {+ l * (1.0 + s)+ } else {+ l + s - l * s+ };+ let p = 2.0 * l - q;+ let r = hue_to_channel(p, q, h + 1.0 / 3.0);+ let g = hue_to_channel(p, q, h);+ let b = hue_to_channel(p, q, h - 1.0 / 3.0);+ (r, g, b)+}++fn hue_to_channel(p: f32, q: f32, mut t: f32) -> f32 {+ if t < 0.0 {+ t += 1.0;+ }+ if t > 1.0 {+ t -= 1.0;+ }+ if t < 1.0 / 6.0 {+ return p + (q - p) * 6.0 * t;+ }+ if t < 0.5 {+ return q;+ }+ if t < 2.0 / 3.0 {+ return p + (q - p) * (2.0 / 3.0 - t) * 6.0;+ }+ p+}++/// RGB → HSL. All inputs and outputs in [0, 1].+fn rgba_to_hsl(c: Rgba) -> (f32, f32, f32) {+ let max = c.r.max(c.g).max(c.b);+ let min = c.r.min(c.g).min(c.b);+ let l = (max + min) / 2.0;+ if (max - min).abs() < f32::EPSILON {+ return (0.0, 0.0, l);+ }+ let d = max - min;+ let s = if l > 0.5 {+ d / (2.0 - max - min)+ } else {+ d / (max + min)+ };+ let h = if (max - c.r).abs() < f32::EPSILON {+ (c.g - c.b) / d + if c.g < c.b { 6.0 } else { 0.0 }+ } else if (max - c.g).abs() < f32::EPSILON {+ (c.b - c.r) / d + 2.0+ } else {+ (c.r - c.g) / d + 4.0+ } / 6.0;+ (h, s, l)+}++/// §20.1.2.3.9 gamma — sRGB EOTF (sRGB → linear).+fn srgb_to_linear(c: f32) -> f32 {+ if c <= 0.04045 {+ c / 12.92+ } else {+ ((c + 0.055) / 1.055).powf(2.4)+ }+}++/// §20.1.2.3.18 invGamma — inverse sRGB EOTF (linear → sRGB).+fn linear_to_srgb(c: f32) -> f32 {+ if c <= 0.0031308 {+ c * 12.92+ } else {+ 1.055 * c.powf(1.0 / 2.4) - 0.055+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::{PresetColorVal, SystemColorVal, ThemeColorScheme, ThemeFontScheme};++ fn approx(a: f32, b: f32) -> bool {+ (a - b).abs() < 5e-3+ }++ fn default_ctx() -> DrawingColorContext<'static> {+ DrawingColorContext {+ theme: None,+ bg_tx_convention: BgTxConvention::LightBackground,+ placeholder: None,+ }+ }++ fn theme_ctx(theme: &Theme) -> DrawingColorContext<'_> {+ DrawingColorContext {+ theme: Some(theme),+ bg_tx_convention: BgTxConvention::LightBackground,+ placeholder: None,+ }+ }++ fn sample_theme() -> Theme {+ Theme {+ color_scheme: ThemeColorScheme {+ dark1: 0x000000,+ light1: 0xFFFFFF,+ dark2: 0x44546A,+ light2: 0xE7E6E6,+ accent1: 0x4472C4,+ accent2: 0xED7D31,+ accent3: 0xA5A5A5,+ accent4: 0xFFC000,+ accent5: 0x5B9BD5,+ accent6: 0x70AD47,+ hyperlink: 0x0563C1,+ followed_hyperlink: 0x954F72,+ },+ major_font: ThemeFontScheme::default(),+ minor_font: ThemeFontScheme::default(),+ fill_styles: vec![],+ line_styles: vec![],+ effect_styles: vec![],+ }+ }++ // ── Base color resolution ──────────────────────────────────────────++ #[test]+ fn srgb_passes_through() {+ let c = DrawingColor::Srgb {+ rgb: 0xAABBCC,+ transforms: vec![],+ };+ let r = resolve_drawing_color(&c, &default_ctx());+ assert_eq!(r.to_rgb24(), 0xAABBCC);+ }++ #[test]+ fn scheme_accent1_resolves_via_theme() {+ let theme = sample_theme();+ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Accent1,+ transforms: vec![],+ };+ let r = resolve_drawing_color(&c, &theme_ctx(&theme));+ assert_eq!(r.to_rgb24(), 0x4472C4);+ }++ #[test]+ fn scheme_tx1_maps_to_dk1_on_light_bg() {+ let theme = sample_theme();+ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Tx1,+ transforms: vec![],+ };+ let r = resolve_drawing_color(&c, &theme_ctx(&theme));+ assert_eq!(r.to_rgb24(), 0x000000);+ }++ #[test]+ fn scheme_bg1_maps_to_lt1_on_light_bg() {+ let theme = sample_theme();+ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Bg1,+ transforms: vec![],+ };+ let r = resolve_drawing_color(&c, &theme_ctx(&theme));+ assert_eq!(r.to_rgb24(), 0xFFFFFF);+ }++ #[test]+ fn scheme_tx1_maps_to_lt1_on_dark_bg() {+ let theme = sample_theme();+ let ctx = DrawingColorContext {+ theme: Some(&theme),+ bg_tx_convention: BgTxConvention::DarkBackground,+ placeholder: None,+ };+ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Tx1,+ transforms: vec![],+ };+ let r = resolve_drawing_color(&c, &ctx);+ assert_eq!(r.to_rgb24(), 0xFFFFFF);+ }++ #[test]+ fn sys_clr_uses_last_clr_when_present() {+ let c = DrawingColor::Sys {+ name: SystemColorVal::Window,+ last_clr: Some(0xAABBCC),+ transforms: vec![],+ };+ assert_eq!(+ resolve_drawing_color(&c, &default_ctx()).to_rgb24(),+ 0xAABBCC+ );+ }++ #[test]+ fn sys_clr_falls_back_to_default_rgb() {+ let c = DrawingColor::Sys {+ name: SystemColorVal::Window,+ last_clr: None,+ transforms: vec![],+ };+ assert_eq!(+ resolve_drawing_color(&c, &default_ctx()).to_rgb24(),+ SystemColorVal::Window.default_rgb()+ );+ }++ #[test]+ fn prst_clr_uses_preset_rgb() {+ let c = DrawingColor::Prst {+ name: PresetColorVal::Red,+ transforms: vec![],+ };+ assert_eq!(+ resolve_drawing_color(&c, &default_ctx()).to_rgb24(),+ 0xFF0000+ );+ }++ #[test]+ fn scheme_without_theme_falls_back_to_black() {+ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Accent1,+ transforms: vec![],+ };+ assert_eq!(+ resolve_drawing_color(&c, &default_ctx()).to_rgb24(),+ 0x000000+ );+ }++ // ── Transforms ─────────────────────────────────────────────────────++ fn srgb(rgb: u32, transforms: Vec<ColorTransform>) -> DrawingColor {+ DrawingColor::Srgb { rgb, transforms }+ }++ fn pct(thousandth: i64) -> Dimension<ThousandthPercent> {+ Dimension::new(thousandth)+ }++ fn angle(sixtie: i64) -> Dimension<SixtieThousandthDeg> {+ Dimension::new(sixtie)+ }++ #[test]+ fn tint_toward_white() {+ let c = srgb(0x000000, vec![ColorTransform::Tint(pct(50_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.r, 0.5));+ assert!(approx(r.g, 0.5));+ assert!(approx(r.b, 0.5));+ }++ #[test]+ fn tint_100pct_produces_white() {+ let c = srgb(0x000000, vec![ColorTransform::Tint(pct(100_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert_eq!(r.to_rgb24(), 0xFFFFFF);+ }++ #[test]+ fn shade_toward_black() {+ let c = srgb(0xFFFFFF, vec![ColorTransform::Shade(pct(50_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.r, 0.5));+ }++ #[test]+ fn shade_100pct_produces_black() {+ let c = srgb(0xFFFFFF, vec![ColorTransform::Shade(pct(100_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert_eq!(r.to_rgb24(), 0x000000);+ }++ #[test]+ fn inv_flips_channels() {+ let c = srgb(0x112233, vec![ColorTransform::Inv]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert_eq!(r.to_rgb24(), 0xEEDDCC);+ }++ #[test]+ fn alpha_sets_absolute() {+ let c = srgb(0xFF0000, vec![ColorTransform::Alpha(pct(50_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.a, 0.5));+ }++ #[test]+ fn alpha_mod_multiplies() {+ let c = srgb(+ 0xFF0000,+ vec![+ ColorTransform::Alpha(pct(80_000)),+ ColorTransform::AlphaMod(pct(50_000)),+ ],+ );+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.a, 0.4));+ }++ #[test]+ fn alpha_off_shifts() {+ let c = srgb(0xFF0000, vec![ColorTransform::AlphaOff(pct(-25_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.a, 0.75));+ }++ #[test]+ fn lum_mod_half_darkens() {+ // Accent1 with lumMod 75000 + lumOff 25000 is the canonical Office+ // recipe for a lightened accent. Just sanity-check monotonicity.+ let theme = sample_theme();+ let c = DrawingColor::Scheme {+ name: SchemeColorVal::Accent1,+ transforms: vec![+ ColorTransform::LumMod(pct(75_000)),+ ColorTransform::LumOff(pct(25_000)),+ ],+ };+ let r = resolve_drawing_color(&c, &theme_ctx(&theme));+ // Accent1 is 0x4472C4 (bluish). LumMod+LumOff lightens it; the+ // resulting color should have L > input L.+ let input = Rgba::from_rgb24(0x4472C4);+ let (_, _, l_in) = rgba_to_hsl(input);+ let (_, _, l_out) = rgba_to_hsl(r);+ assert!(l_out > l_in);+ }++ #[test]+ fn hue_offset_rotates() {+ // Pure red → hue-offset 120° → pure green.+ let c = srgb(0xFF0000, vec![ColorTransform::HueOff(angle(120 * 60_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.r, 0.0));+ assert!(approx(r.g, 1.0));+ assert!(approx(r.b, 0.0));+ }++ #[test]+ fn gray_desaturates_to_luminance() {+ let c = srgb(0xFF0000, vec![ColorTransform::Gray]);+ let r = resolve_drawing_color(&c, &default_ctx());+ // BT.601 luminance of pure red = 0.299.+ assert!(approx(r.r, 0.299));+ assert!(approx(r.g, 0.299));+ assert!(approx(r.b, 0.299));+ }++ #[test]+ fn comp_rotates_hue_180() {+ // Pure red hue → cyan-ish (opposite hue).+ let c = srgb(0xFF0000, vec![ColorTransform::Comp]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.r, 0.0));+ assert!(approx(r.g, 1.0));+ assert!(approx(r.b, 1.0));+ }++ #[test]+ fn red_channel_absolute() {+ let c = srgb(0x000000, vec![ColorTransform::Red(pct(100_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert_eq!(r.to_rgb24(), 0xFF0000);+ }++ #[test]+ fn red_offset_adds() {+ let c = srgb(0x800000, vec![ColorTransform::RedOff(pct(-50_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.r, 0.0));+ }++ #[test]+ fn red_mod_multiplies() {+ let c = srgb(0x800000, vec![ColorTransform::RedMod(pct(50_000))]);+ let r = resolve_drawing_color(&c, &default_ctx());+ assert!(approx(r.r, 0.25));+ }++ #[test]+ fn transforms_apply_in_order() {+ // shade 50% then tint 50% is NOT the same as tint 50% then shade 50%.+ let c1 = srgb(+ 0xFF0000,+ vec![+ ColorTransform::Shade(pct(50_000)),+ ColorTransform::Tint(pct(50_000)),+ ],+ );+ let c2 = srgb(+ 0xFF0000,+ vec![+ ColorTransform::Tint(pct(50_000)),+ ColorTransform::Shade(pct(50_000)),+ ],+ );+ let r1 = resolve_drawing_color(&c1, &default_ctx());+ let r2 = resolve_drawing_color(&c2, &default_ctx());+ assert_ne!(r1.to_rgb24(), r2.to_rgb24());+ }++ #[test]+ fn gamma_then_inv_gamma_roundtrips() {+ let c = srgb(+ 0x808080,+ vec![ColorTransform::Gamma, ColorTransform::InvGamma],+ );+ let r = resolve_drawing_color(&c, &default_ctx());+ // Allow small floating-point drift.+ let orig = Rgba::from_rgb24(0x808080);+ assert!(approx(r.r, orig.r));+ assert!(approx(r.g, orig.g));+ assert!(approx(r.b, orig.b));+ }++ // ── Rgba roundtrip ─────────────────────────────────────────────────++ #[test]+ fn rgba_from_to_rgb24_roundtrip() {+ for v in [0x000000, 0xFFFFFF, 0x808080, 0x123456, 0xAABBCC] {+ assert_eq!(Rgba::from_rgb24(v).to_rgb24(), v);+ }+ }++ #[test]+ fn rgba_clamp_in_to_rgb24() {+ let out = Rgba {+ r: 2.0,+ g: -1.0,+ b: 0.5,+ a: 1.0,+ }+ .to_rgb24();+ assert_eq!(out, 0xFF0080);+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/fonts.rs b/crates/liteparse-docx/src/render/resolve/fonts.rsnew file mode 100644index 0000000..d9dce52--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/fonts.rs@@ -0,0 +1,375 @@+//! Font collection — extract all font families referenced in the document.++use std::collections::HashSet;++use crate::model::{Block, Document, FontSet, Inline};++/// Collect all unique font family names referenced in the document.+/// Sources: theme, style sheet, inline content, numbering levels, paragraph marks.+pub fn collect_font_families(doc: &Document) -> Vec<String> {+ let mut families = HashSet::new();++ // Theme fonts+ if let Some(ref theme) = doc.theme {+ add_nonempty(&mut families, &theme.major_font.latin);+ add_nonempty(&mut families, &theme.minor_font.latin);+ add_nonempty(&mut families, &theme.major_font.east_asian);+ add_nonempty(&mut families, &theme.minor_font.east_asian);+ add_nonempty(&mut families, &theme.major_font.complex_script);+ add_nonempty(&mut families, &theme.minor_font.complex_script);+ for sf in &theme.major_font.script_fonts {+ add_nonempty(&mut families, &sf.typeface);+ }+ for sf in &theme.minor_font.script_fonts {+ add_nonempty(&mut families, &sf.typeface);+ }+ }++ // Style sheet defaults+ collect_from_fontset(&mut families, &doc.styles.doc_defaults_run.fonts);++ // Style definitions+ for style in doc.styles.styles.values() {+ if let Some(ref rp) = style.run_properties {+ collect_from_fontset(&mut families, &rp.fonts);+ }+ }++ // Body content+ collect_from_blocks(&mut families, &doc.body);++ // Headers and footers+ for blocks in doc.headers.values() {+ collect_from_blocks(&mut families, blocks);+ }+ for blocks in doc.footers.values() {+ collect_from_blocks(&mut families, blocks);+ }++ // Footnotes and endnotes+ for blocks in doc.footnotes.values() {+ collect_from_blocks(&mut families, blocks);+ }+ for blocks in doc.endnotes.values() {+ collect_from_blocks(&mut families, blocks);+ }++ // Numbering levels+ for abs in doc.numbering.abstract_nums.values() {+ for level in &abs.levels {+ if let Some(ref rp) = level.run_properties {+ collect_from_fontset(&mut families, &rp.fonts);+ }+ }+ }++ families.into_iter().collect()+}++/// Extract the effective font family from a FontSet.+///+/// Returns the first `explicit` name that is set, in priority order:+/// ascii > high_ansi > east_asian > complex_script (§17.3.2.26).+/// By the time this is called, theme references will have been resolved+/// into the `explicit` field by [`resolve_font_set_themes`].+pub fn effective_font(fonts: &FontSet) -> Option<&str> {+ fonts+ .ascii+ .explicit+ .as_deref()+ .or(fonts.high_ansi.explicit.as_deref())+ .or(fonts.east_asian.explicit.as_deref())+ .or(fonts.complex_script.explicit.as_deref())+}++/// §17.3.2.26: resolve theme font references in a FontSet.+///+/// For each slot that carries a theme reference, look up the concrete font+/// family name from the theme and write it into `slot.explicit`, overwriting+/// any explicit name — theme references take precedence per §17.3.2.26.+pub fn resolve_font_set_themes(fonts: &mut FontSet, theme: &crate::model::Theme) {+ for slot in [+ &mut fonts.ascii,+ &mut fonts.high_ansi,+ &mut fonts.east_asian,+ &mut fonts.complex_script,+ ] {+ if let Some(ref tf) = slot.theme {+ if let Some(name) = resolve_theme_font_ref(tf, theme) {+ slot.explicit = Some(name);+ }+ }+ }+}++fn resolve_theme_font_ref(+ tf: &crate::model::ThemeFontRef,+ theme: &crate::model::Theme,+) -> Option<String> {+ use crate::model::ThemeFontRef;+ let name = match tf {+ ThemeFontRef::MajorHAnsi => &theme.major_font.latin,+ ThemeFontRef::MajorEastAsia => &theme.major_font.east_asian,+ ThemeFontRef::MajorBidi => &theme.major_font.complex_script,+ ThemeFontRef::MinorHAnsi => &theme.minor_font.latin,+ ThemeFontRef::MinorEastAsia => &theme.minor_font.east_asian,+ ThemeFontRef::MinorBidi => &theme.minor_font.complex_script,+ };+ if name.is_empty() {+ None+ } else {+ Some(name.clone())+ }+}++fn add_nonempty(set: &mut HashSet<String>, s: &str) {+ if !s.is_empty() {+ set.insert(s.to_string());+ }+}++fn collect_from_fontset(set: &mut HashSet<String>, fonts: &FontSet) {+ for slot in [+ &fonts.ascii,+ &fonts.high_ansi,+ &fonts.east_asian,+ &fonts.complex_script,+ ] {+ if let Some(ref f) = slot.explicit {+ add_nonempty(set, f);+ }+ }+}++fn collect_from_blocks(set: &mut HashSet<String>, blocks: &[Block]) {+ for block in blocks {+ match block {+ Block::Paragraph(p) => {+ if let Some(ref mrp) = p.mark_run_properties {+ collect_from_fontset(set, &mrp.fonts);+ }+ collect_from_inlines(set, &p.content);+ }+ Block::Table(t) => {+ for row in &t.rows {+ for cell in &row.cells {+ collect_from_blocks(set, &cell.content);+ }+ }+ }+ Block::SectionBreak(_) => {}+ }+ }+}++fn collect_from_inlines(set: &mut HashSet<String>, inlines: &[Inline]) {+ for inline in inlines {+ match inline {+ Inline::TextRun(tr) => {+ collect_from_fontset(set, &tr.properties.fonts);+ }+ Inline::Hyperlink(h) => {+ collect_from_inlines(set, &h.content);+ }+ Inline::Field(f) => {+ collect_from_inlines(set, &f.content);+ }+ Inline::AlternateContent(ac) => {+ for choice in &ac.choices {+ collect_from_inlines(set, &choice.content);+ }+ if let Some(ref fb) = ac.fallback {+ collect_from_inlines(set, fb);+ }+ }+ _ => {}+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::*;+ use std::collections::HashMap;++ fn empty_doc() -> Document {+ Document {+ settings: DocumentSettings::default(),+ theme: None,+ styles: StyleSheet::default(),+ numbering: NumberingDefinitions::default(),+ body: vec![],+ final_section: SectionProperties::default(),+ headers: HashMap::new(),+ footers: HashMap::new(),+ footnotes: HashMap::new(),+ endnotes: HashMap::new(),+ media: HashMap::new(),+ embedded_fonts: vec![],+ }+ }++ fn text_run(font: &str, text: &str) -> Inline {+ Inline::TextRun(Box::new(TextRun {+ style_id: None,+ properties: RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name(font),+ ..Default::default()+ },+ ..Default::default()+ },+ content: vec![RunElement::Text(text.into())],+ rsids: RevisionIds::default(),+ }))+ }++ fn para_with_run(font: &str) -> Block {+ Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![text_run(font, "hello")],+ rsids: ParagraphRevisionIds::default(),+ }))+ }++ // ── effective_font ───────────────────────────────────────────────────++ #[test]+ fn effective_font_prefers_ascii() {+ let fs = FontSet {+ ascii: FontSlot::from_name("Arial"),+ high_ansi: FontSlot::from_name("Times"),+ ..Default::default()+ };+ assert_eq!(effective_font(&fs), Some("Arial"));+ }++ #[test]+ fn effective_font_falls_back_to_high_ansi() {+ let fs = FontSet {+ high_ansi: FontSlot::from_name("Times"),+ ..Default::default()+ };+ assert_eq!(effective_font(&fs), Some("Times"));+ }++ #[test]+ fn effective_font_falls_back_to_east_asian() {+ let fs = FontSet {+ east_asian: FontSlot::from_name("SimSun"),+ ..Default::default()+ };+ assert_eq!(effective_font(&fs), Some("SimSun"));+ }++ #[test]+ fn effective_font_empty_returns_none() {+ let fs = FontSet::default();+ assert_eq!(effective_font(&fs), None);+ }++ // ── collect_font_families ────────────────────────────────────────────++ #[test]+ fn collects_from_body_text_runs() {+ let mut doc = empty_doc();+ doc.body = vec![para_with_run("Calibri"), para_with_run("Arial")];++ let families = collect_font_families(&doc);+ assert!(families.contains(&"Calibri".to_string()));+ assert!(families.contains(&"Arial".to_string()));+ }++ #[test]+ fn collects_from_style_sheet_defaults() {+ let mut doc = empty_doc();+ doc.styles.doc_defaults_run = RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name("Cambria"),+ ..Default::default()+ },+ ..Default::default()+ };++ let families = collect_font_families(&doc);+ assert!(families.contains(&"Cambria".to_string()));+ }++ #[test]+ fn collects_from_theme_fonts() {+ let mut doc = empty_doc();+ doc.theme = Some(Theme {+ major_font: ThemeFontScheme {+ latin: "Calibri Light".into(),+ ..Default::default()+ },+ minor_font: ThemeFontScheme {+ latin: "Calibri".into(),+ ..Default::default()+ },+ ..Default::default()+ });++ let families = collect_font_families(&doc);+ assert!(families.contains(&"Calibri Light".to_string()));+ assert!(families.contains(&"Calibri".to_string()));+ }++ #[test]+ fn collects_from_headers() {+ let mut doc = empty_doc();+ let header_id = RelId::new("rId1");+ doc.headers+ .insert(header_id, vec![para_with_run("Georgia")]);++ let families = collect_font_families(&doc);+ assert!(families.contains(&"Georgia".to_string()));+ }++ #[test]+ fn deduplicates() {+ let mut doc = empty_doc();+ doc.body = vec![para_with_run("Arial"), para_with_run("Arial")];++ let families = collect_font_families(&doc);+ let count = families.iter().filter(|f| *f == "Arial").count();+ assert_eq!(count, 1);+ }++ #[test]+ fn empty_doc_returns_empty() {+ let doc = empty_doc();+ let families = collect_font_families(&doc);+ assert!(families.is_empty());+ }++ #[test]+ fn collects_from_style_definitions() {+ let mut doc = empty_doc();+ doc.styles.styles.insert(+ StyleId::new("Heading1"),+ Style {+ name: None,+ style_type: StyleType::Paragraph,+ based_on: None,+ is_default: false,+ paragraph_properties: None,+ run_properties: Some(RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name("Verdana"),+ ..Default::default()+ },+ ..Default::default()+ }),+ table_properties: None,+ table_style_overrides: vec![],+ },+ );++ let families = collect_font_families(&doc);+ assert!(families.contains(&"Verdana".to_string()));+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/header_footer.rs b/crates/liteparse-docx/src/render/resolve/header_footer.rsnew file mode 100644index 0000000..218990e--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/header_footer.rs@@ -0,0 +1,103 @@+//! Header / footer set ADT.+//!+//! Per ECMA-376 §17.10.5 (`headerReference`/`footerReference`'s+//! `@type` attribute), each section can supply up to three header XML+//! parts and three footer XML parts, distinguished by purpose:+//!+//! - `default` — used on most pages+//! - `first` — used on page 1 of a section when `<w:titlePg/>` is set+//! (§17.10.6); falling back to a *blank* header (not `default`) when+//! `first` is missing+//! - `even` — used on even-numbered logical pages when the document+//! setting `<w:evenAndOddHeaders/>` is on (§17.10.1); falling back to+//! *blank* (not `default`) when `even` is missing+//!+//! The data structure is generic over the slot value: parse layer holds+//! relationship ids, resolve layer holds the loaded block content, and+//! tests can use any owned/borrowed value type. Selection lives in+//! `crate::render::layout::header_footer`.++/// Three slots per ECMA-376 §17.10.5. Slots are independent; an absent+/// slot is `None` and is *not* substituted with `default` at selection+/// time — that matches Word's observed behavior and the spec literal.+#[derive(Clone, Debug, Default, Eq, PartialEq)]+pub struct HeaderFooterSet<T> {+ /// `<w:headerReference w:type="default" .../>` — the everyday slot.+ pub default: Option<T>,+ /// `<w:headerReference w:type="first" .../>` — paired with+ /// `<w:titlePg/>` on the section.+ pub first: Option<T>,+ /// `<w:headerReference w:type="even" .../>` — paired with+ /// `<w:evenAndOddHeaders/>` on document settings.+ pub even: Option<T>,+}++/// The three reference kinds OOXML defines. Useful as a key when+/// iterating slots and as the result of a per-page selection.+#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]+pub enum HeaderFooterKind {+ Default,+ First,+ Even,+}++impl<T> HeaderFooterSet<T> {+ /// True when no slot is populated. Allows callers to skip+ /// header/footer rendering entirely for sections that have neither.+ pub fn is_empty(&self) -> bool {+ self.default.is_none() && self.first.is_none() && self.even.is_none()+ }++ /// Borrow a specific slot.+ pub fn get(&self, kind: HeaderFooterKind) -> Option<&T> {+ match kind {+ HeaderFooterKind::Default => self.default.as_ref(),+ HeaderFooterKind::First => self.first.as_ref(),+ HeaderFooterKind::Even => self.even.as_ref(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn empty_set_reports_empty() {+ let s: HeaderFooterSet<&str> = HeaderFooterSet::default();+ assert!(s.is_empty());+ }++ #[test]+ fn populated_set_is_not_empty() {+ let s: HeaderFooterSet<&str> = HeaderFooterSet {+ default: Some("d"),+ first: None,+ even: None,+ };+ assert!(!s.is_empty());+ }++ #[test]+ fn get_returns_each_slot() {+ let s = HeaderFooterSet {+ default: Some("D"),+ first: Some("F"),+ even: Some("E"),+ };+ assert_eq!(s.get(HeaderFooterKind::Default), Some(&"D"));+ assert_eq!(s.get(HeaderFooterKind::First), Some(&"F"));+ assert_eq!(s.get(HeaderFooterKind::Even), Some(&"E"));+ }++ #[test]+ fn get_returns_none_for_absent_slot() {+ let s: HeaderFooterSet<&str> = HeaderFooterSet {+ default: Some("D"),+ first: None,+ even: None,+ };+ assert_eq!(s.get(HeaderFooterKind::First), None);+ assert_eq!(s.get(HeaderFooterKind::Even), None);+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/images.rs b/crates/liteparse-docx/src/render/resolve/images.rsnew file mode 100644index 0000000..0d570c8--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/images.rs@@ -0,0 +1,341 @@+//! Image extraction — navigate DrawingML hierarchy to extract image RelIds.++use std::sync::Arc;++use crate::model::dimension::{Dimension, ThousandthPercent};+use crate::model::{GraphicContent, Image, ImageFormat, RelId, RelativeRect};+use crate::render::dimension::Pt;+use crate::render::geometry::PtRect;++/// Resolved image entry — shared bytes with detected format.+///+/// All references to the same image share one `Arc<[u8]>` allocation — the very+/// one the parser read out of the package, since resolve moves the handle+/// rather than copying the bytes. That identity is load-bearing: the painter's+/// bitmap cache keys on the pointer, so two placements of one image decode once.+#[derive(Clone, Debug)]+pub struct MediaEntry {+ pub data: Arc<[u8]>,+ pub format: ImageFormat,+}++/// Extract the embedded image relationship ID from a DrawingML Image.+/// Navigates: Image → graphic → Picture → blip_fill → blip → embed.+pub fn extract_image_rel_id(image: &Image) -> Option<&RelId> {+ match image.graphic.as_ref()? {+ GraphicContent::Picture(pic) => pic.blip_fill.blip.as_ref()?.embed.as_ref(),+ GraphicContent::WordProcessingShape(_) => None,+ }+}++/// §20.1.10.48 CT_RelativeRect → the visible source region as a fraction rect+/// in `[0, 1]` (origin = top-left crop offset, size = visible fraction).+///+/// The single home for the `1 - l - r` crop math: both the picture blip+/// (`extract_src_rect`) and the shape-fill blip (`ResolvedBlip::src_rect`)+/// paths call it, so cropped pictures and cropped fills can never diverge.+///+/// Returns `None` when there is no crop (all edges zero → draw the whole image)+/// or when the insets overlap so the visible region collapses (`l + r ≥ 1` or+/// `t + b ≥ 1`, malformed → fall back to the whole image rather than a blank+/// `Strict`-sampled frame). Negative insets are preserved as an out-of-`[0, 1]`+/// rect — the painter resolves those into letterbox/pillarbox padding.+pub(crate) fn relative_rect_to_fraction(rel: &RelativeRect) -> Option<PtRect> {+ // CT_RelativeRect edges are in thousandths of a percent (100% = 100000).+ let frac = |d: Option<Dimension<ThousandthPercent>>| d.map_or(0.0, |v| v.to_fraction());+ let (left, top, right, bottom) = (+ frac(rel.left),+ frac(rel.top),+ frac(rel.right),+ frac(rel.bottom),+ );+ if left == 0.0 && top == 0.0 && right == 0.0 && bottom == 0.0 {+ return None;+ }+ let (visible_w, visible_h) = (1.0 - left - right, 1.0 - top - bottom);+ if visible_w <= 0.0 || visible_h <= 0.0 {+ return None;+ }+ Some(PtRect::from_xywh(+ Pt::new(left),+ Pt::new(top),+ Pt::new(visible_w),+ Pt::new(visible_h),+ ))+}++/// §20.1.10.48 `a:srcRect` — the picture's source crop, as a fraction rect in+/// `[0, 1]` relative to the image's natural extent. Returns `None` when there+/// is no crop, so the whole image is drawn. Word crops the source *before*+/// stretching it into the display frame; ignoring this squashes cropped logos+/// (the visible aspect ratio no longer matches the frame). The conversion+/// itself lives in `relative_rect_to_fraction`, shared with the shape-fill+/// blip path (`ResolvedBlip::src_rect`).+pub fn extract_src_rect(image: &Image) -> Option<PtRect> {+ let GraphicContent::Picture(pic) = image.graphic.as_ref()? else {+ return None;+ };+ relative_rect_to_fraction(pic.blip_fill.src_rect.as_ref()?)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::Dimension;+ use crate::model::geometry::{EdgeInsets, Size};+ use crate::model::*;++ fn make_image_with_blip(rel_id: &str) -> Image {+ Image {+ extent: Size::new(Dimension::new(0), Dimension::new(0)),+ effect_extent: None,+ doc_properties: DocProperties {+ id: 1,+ name: "img".into(),+ description: None,+ hidden: None,+ title: None,+ },+ graphic_frame_locks: None,+ graphic: Some(GraphicContent::Picture(Picture {+ nv_pic_pr: NvPicProperties {+ cnv_pr: DocProperties {+ id: 1,+ name: "pic".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(rel_id)),+ link: None,+ compression: None,+ }),+ src_rect: None,+ fill_kind: BlipFillKind::Unspecified,+ },+ shape_properties: None,+ })),+ placement: ImagePlacement::Inline {+ distance: EdgeInsets::new(+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ ),+ },+ }+ }++ #[test]+ fn extracts_rel_id_from_picture_blip() {+ let img = make_image_with_blip("rId5");+ let rel_id = extract_image_rel_id(&img);+ assert_eq!(rel_id.map(|r| r.as_str()), Some("rId5"));+ }++ #[test]+ fn no_graphic_returns_none() {+ let img = Image {+ extent: Size::new(Dimension::new(0), Dimension::new(0)),+ effect_extent: None,+ doc_properties: DocProperties {+ id: 1,+ name: "img".into(),+ description: None,+ hidden: None,+ title: None,+ },+ graphic_frame_locks: None,+ graphic: None,+ placement: ImagePlacement::Inline {+ distance: EdgeInsets::new(+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ ),+ },+ };+ assert!(extract_image_rel_id(&img).is_none());+ }++ #[test]+ fn no_blip_returns_none() {+ let img = Image {+ extent: Size::new(Dimension::new(0), Dimension::new(0)),+ effect_extent: None,+ doc_properties: DocProperties {+ id: 1,+ name: "img".into(),+ description: None,+ hidden: None,+ title: None,+ },+ graphic_frame_locks: None,+ graphic: Some(GraphicContent::Picture(Picture {+ nv_pic_pr: NvPicProperties {+ cnv_pr: DocProperties {+ id: 1,+ name: "pic".into(),+ description: None,+ hidden: None,+ title: None,+ },+ cnv_pic_pr: None,+ },+ blip_fill: BlipFill {+ rotate_with_shape: None,+ dpi: None,+ blip: None,+ src_rect: None,+ fill_kind: BlipFillKind::Unspecified,+ },+ shape_properties: None,+ })),+ placement: ImagePlacement::Inline {+ distance: EdgeInsets::new(+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ ),+ },+ };+ assert!(extract_image_rel_id(&img).is_none());+ }++ #[test]+ fn word_processing_shape_returns_none() {+ let img = Image {+ extent: Size::new(Dimension::new(0), Dimension::new(0)),+ effect_extent: None,+ doc_properties: DocProperties {+ id: 1,+ name: "img".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::Inline {+ distance: EdgeInsets::new(+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ Dimension::new(0),+ ),+ },+ };+ assert!(extract_image_rel_id(&img).is_none());+ }++ #[test]+ fn src_rect_none_when_no_crop() {+ // `make_image_with_blip` leaves `blip_fill.src_rect = None`.+ assert!(extract_src_rect(&make_image_with_blip("rId1")).is_none());+ }++ #[test]+ fn src_rect_converts_thousandth_percent_crop() {+ // Real values from the IP-05 header logo: top/right/bottom crop, no+ // left. Thousandths of a percent → fractions of the natural extent.+ let mut img = make_image_with_blip("rId1");+ if let Some(GraphicContent::Picture(pic)) = img.graphic.as_mut() {+ pic.blip_fill.src_rect = Some(RelativeRect {+ left: None,+ top: Some(Dimension::new(15883)),+ right: Some(Dimension::new(14520)),+ bottom: Some(Dimension::new(17647)),+ });+ }+ let r = extract_src_rect(&img).expect("crop present");+ assert!((r.origin.x.raw() - 0.0).abs() < 1e-4, "left crop = 0");+ assert!((r.origin.y.raw() - 0.15883).abs() < 1e-4, "top crop");+ assert!((r.size.width.raw() - 0.85480).abs() < 1e-4, "visible width");+ assert!(+ (r.size.height.raw() - 0.66470).abs() < 1e-4,+ "visible height"+ );+ }++ #[test]+ fn src_rect_none_when_horizontal_crop_collapses_region() {+ // l + r ≥ 1: the insets overlap, so no visible width remains. Malformed+ // input must fall back to the whole image (None), not a blank frame.+ let mut img = make_image_with_blip("rId1");+ if let Some(GraphicContent::Picture(pic)) = img.graphic.as_mut() {+ pic.blip_fill.src_rect = Some(RelativeRect {+ left: Some(Dimension::new(60000)),+ top: None,+ right: Some(Dimension::new(60000)),+ bottom: None,+ });+ }+ assert!(extract_src_rect(&img).is_none());+ }++ #[test]+ fn src_rect_none_when_vertical_crop_collapses_region() {+ // t + b ≥ 1: no visible height remains.+ let mut img = make_image_with_blip("rId1");+ if let Some(GraphicContent::Picture(pic)) = img.graphic.as_mut() {+ pic.blip_fill.src_rect = Some(RelativeRect {+ left: None,+ top: Some(Dimension::new(100000)),+ right: None,+ bottom: Some(Dimension::new(5000)),+ });+ }+ assert!(extract_src_rect(&img).is_none());+ }++ #[test]+ fn relative_rect_to_fraction_is_the_shared_converter() {+ // Direct test of the seam both blip paths call: 25% left / 10% bottom+ // crop → origin (0.25, 0) and visible (0.65, 0.90).+ let rel = RelativeRect {+ left: Some(Dimension::new(25000)),+ top: None,+ right: Some(Dimension::new(10000)),+ bottom: Some(Dimension::new(10000)),+ };+ let r = relative_rect_to_fraction(&rel).expect("crop present");+ assert!((r.origin.x.raw() - 0.25).abs() < 1e-5);+ assert!((r.size.width.raw() - 0.65).abs() < 1e-5);+ assert!((r.size.height.raw() - 0.90).abs() < 1e-5);+ }++ #[test]+ fn relative_rect_to_fraction_preserves_negative_insets_for_padding() {+ // Negative insets (letterbox padding) stay as an out-of-[0,1] rect; the+ // painter turns that into padding rather than the converter clamping it.+ let rel = RelativeRect {+ left: Some(Dimension::new(-20000)),+ top: None,+ right: Some(Dimension::new(-20000)),+ bottom: None,+ };+ let r = relative_rect_to_fraction(&rel).expect("crop present");+ assert!(+ (r.origin.x.raw() + 0.2).abs() < 1e-5,+ "negative origin kept"+ );+ assert!((r.size.width.raw() - 1.4).abs() < 1e-5, "width > 1 kept");+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/locale.rs b/crates/liteparse-docx/src/render/resolve/locale.rsnew file mode 100644index 0000000..dc0e9a2--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/locale.rs@@ -0,0 +1,245 @@+//! §17.3.2.20 `w:lang` reduced to the distinctions layout actually makes.++use crate::model::RunProperties;++/// The language a piece of the document is written in, as far as this engine's+/// layout is concerned.+///+/// Deliberately **not** a BCP-47 parser. The tag space is open and unbounded,+/// while the engine asks a language exactly two questions:+///+/// * §17.18.85 — which character a `decimal` tab aligns its zone on;+/// * §17.9.27 — whether `ordinal` / `cardinalText` / `ordinalText` can be+/// rendered as words.+///+/// So this names the groups those two questions have distinct answers for, and+/// stops. When a third question arrives, or when a language's number words are+/// implemented, the enum gains a variant and the compiler finds every site that+/// has to answer for it — which is the whole reason this is an enum and not a+/// `&str` compared afresh at each call site.+///+/// Only `w:lang/@w:val` is read. `@w:eastAsia` and `@w:bidi` name the languages+/// of *other script runs* in the same document, and neither of the two+/// questions above is asked of them.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum Locale {+ /// English, in any region — the one language whose number words this engine+ /// spells. Also the answer for a document that declares no language at all,+ /// which is what every document was assumed to be before `w:lang` was read.+ #[default]+ English,+ /// A recognised language that writes a decimal **comma**: German, French,+ /// Spanish, Italian, Portuguese, Russian, Polish, Dutch, the Nordics, and+ /// most of Central and Eastern Europe.+ CommaDecimal,+ /// A recognised language that is not English and writes a decimal **point**:+ /// Japanese, Chinese, Korean, Hebrew, Thai, and most of South and+ /// South-East Asia.+ PointDecimal,+ /// A tag whose primary subtag is not in the table below.+ ///+ /// It answers every question exactly as [`Locale::English`] does, on+ /// purpose: before `w:lang` was read, *every* document got a decimal point+ /// and English number words, so an unfamiliar tag has to keep rendering as+ /// it does today rather than silently losing content to a degrade. It is a+ /// separate variant because it is a different *fact* — it logs, so an+ /// unhandled language is visible rather than silently assumed English.+ Unrecognised,+}++impl Locale {+ /// §17.18.85: the character a `decimal` tab stop aligns its zone on.+ pub fn decimal_separator(self) -> char {+ match self {+ Locale::CommaDecimal => ',',+ Locale::English | Locale::PointDecimal | Locale::Unrecognised => '.',+ }+ }++ /// §17.9.27: whether this engine can render a number as words in this+ /// language — which `ordinal`, `cardinalText` and `ordinalText` all need.+ ///+ /// A language that answers `false` gets digits. That is not a degrade for+ /// its own sake: writing `1st` onto a German list is not an approximation+ /// of German, it is English text in a German document, and the digits Word+ /// itself falls back to are closer than another language's words.+ pub fn spells_numbers(self) -> bool {+ match self {+ Locale::English | Locale::Unrecognised => true,+ Locale::CommaDecimal | Locale::PointDecimal => false,+ }+ }++ /// §17.7.2: classify the first `w:lang/@w:val` a cascade sets.+ ///+ /// Layers come highest-priority first, exactly as §17.7.2 resolves any+ /// other run property. A cascade that sets none anywhere is+ /// [`Locale::English`] and logs nothing — an absent tag is the common case+ /// for a minimal document, not an unhandled language.+ pub fn from_cascade<'a>(layers: impl IntoIterator<Item = &'a RunProperties>) -> Self {+ layers+ .into_iter()+ // The emptiness test belongs *inside* the search: an empty+ // `@w:val` sets nothing, so it must not stop the walk and shadow a+ // lower layer that does.+ .find_map(|rp| {+ rp.lang+ .as_ref()+ .and_then(|l| l.val.as_deref())+ .filter(|tag| !tag.is_empty())+ })+ .map_or(Locale::English, Locale::from_tag)+ }++ /// Classify one §17.3.2.20 tag by its **primary subtag**.+ ///+ /// BCP-47's primary subtag is everything before the first `-`, and it is+ /// all either question depends on for the languages below: `de-DE` and+ /// `de-AT` write the same decimal comma, `en-US` and `en-GB` the same+ /// point. Matched case-insensitively, because the attribute is a tag and+ /// tags are case-insensitive even though Word writes them `ll-CC`.+ ///+ /// **Known simplification.** CLDR has regional overrides that this ignores+ /// — `de-CH` and `it-CH` write a point where `de` and `it` write a comma,+ /// `en-ZA` a comma where `en` writes a point, and Latin-American Spanish+ /// splits both ways. Modelling those means carrying a region table, which+ /// is the BCP-47 parsing this type exists to avoid; a half-filled table+ /// would look complete and not be. Likewise Arabic and Persian are listed+ /// as point-decimal, which is right for their Latin-digit documents and+ /// wrong for the Arabic-Indic `٫` some regions use.+ pub fn from_tag(tag: &str) -> Self {+ let primary = tag.split('-').next().unwrap_or("").to_ascii_lowercase();+ match primary.as_str() {+ "en" => Locale::English,++ // Writes a decimal comma.+ "af" | "sq" | "hy" | "az" | "be" | "bs" | "bg" | "ca" | "hr" | "cs" | "da" | "nl"+ | "et" | "eu" | "fi" | "fo" | "fr" | "gl" | "ka" | "de" | "el" | "hu" | "is" | "id"+ | "it" | "kk" | "lb" | "lv" | "lt" | "mk" | "mn" | "nb" | "nn" | "no" | "pl" | "pt"+ | "ro" | "ru" | "sr" | "sk" | "sl" | "es" | "sv" | "tr" | "uk" | "vi" => {+ Locale::CommaDecimal+ }++ // Writes a decimal point, but is not English.+ "am" | "ar" | "bn" | "cy" | "fa" | "fil" | "ga" | "gu" | "he" | "hi" | "iw" | "ja"+ | "km" | "kn" | "ko" | "lo" | "ml" | "mr" | "ms" | "mt" | "my" | "ne" | "pa" | "si"+ | "sw" | "ta" | "te" | "th" | "tl" | "ur" | "zh" => Locale::PointDecimal,++ _ => {+ log::warn!(+ "w:lang: unhandled language tag {tag:?} (§17.3.2.20) — \+ assuming a decimal point and English number words, which \+ is what every document got before locale was read"+ );+ Locale::Unrecognised+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::Lang;++ fn rp(tag: Option<&str>) -> RunProperties {+ RunProperties {+ lang: tag.map(|t| Lang {+ val: Some(t.to_string()),+ east_asia: None,+ bidi: None,+ }),+ ..Default::default()+ }+ }++ #[test]+ fn english_regions_are_all_english() {+ for tag in ["en", "en-US", "en-GB", "en-AU", "EN-us"] {+ assert_eq!(Locale::from_tag(tag), Locale::English, "{tag}");+ }+ }++ #[test]+ fn the_corpus_languages_classify_as_they_should() {+ // Every tag `test-files/` and `test-cases/` actually declares.+ for tag in ["de-AT", "de-DE", "pl-PL", "it-IT", "ca-ES", "fr-FR"] {+ assert_eq!(Locale::from_tag(tag), Locale::CommaDecimal, "{tag}");+ }+ for tag in ["en-US", "en-GB"] {+ assert_eq!(Locale::from_tag(tag), Locale::English, "{tag}");+ }+ }++ #[test]+ fn point_decimal_languages_are_not_english() {+ for tag in ["ja-JP", "zh-CN", "ko-KR", "he-IL", "th-TH", "hi-IN"] {+ assert_eq!(Locale::from_tag(tag), Locale::PointDecimal, "{tag}");+ }+ }++ /// The primary subtag alone decides, so a region this table has never seen+ /// still classifies rather than falling through to `Unrecognised`.+ #[test]+ fn an_unknown_region_still_resolves_by_its_primary_subtag() {+ assert_eq!(Locale::from_tag("de-LI"), Locale::CommaDecimal);+ assert_eq!(Locale::from_tag("en-ZZ"), Locale::English);+ }++ #[test]+ fn an_unknown_primary_subtag_is_unrecognised() {+ for tag in ["zz-ZZ", "x-klingon", "qqq"] {+ assert_eq!(Locale::from_tag(tag), Locale::Unrecognised, "{tag}");+ }+ }++ /// The reason `Unrecognised` is its own variant rather than `English`: it+ /// must answer identically, so an unfamiliar document renders unchanged.+ #[test]+ fn an_unrecognised_tag_answers_exactly_as_english_does() {+ assert_eq!(+ Locale::Unrecognised.decimal_separator(),+ Locale::English.decimal_separator(),+ );+ assert_eq!(+ Locale::Unrecognised.spells_numbers(),+ Locale::English.spells_numbers(),+ );+ }++ #[test]+ fn only_comma_languages_write_a_comma() {+ assert_eq!(Locale::CommaDecimal.decimal_separator(), ',');+ assert_eq!(Locale::English.decimal_separator(), '.');+ assert_eq!(Locale::PointDecimal.decimal_separator(), '.');+ }++ #[test]+ fn only_english_spells_numbers() {+ assert!(Locale::English.spells_numbers());+ assert!(!Locale::CommaDecimal.spells_numbers());+ assert!(!Locale::PointDecimal.spells_numbers());+ }++ #[test]+ fn the_cascade_takes_the_first_layer_that_sets_a_tag() {+ let layers = [rp(None), rp(Some("de-DE")), rp(Some("en-US"))];+ assert_eq!(Locale::from_cascade(layers.iter()), Locale::CommaDecimal);+ }++ /// An empty `@w:val` sets nothing — it must not shadow a lower layer that+ /// does, and it must not be classified as an unknown language either.+ #[test]+ fn an_empty_tag_falls_through_to_the_next_layer() {+ let layers = [rp(Some("")), rp(Some("de-DE"))];+ assert_eq!(Locale::from_cascade(layers.iter()), Locale::CommaDecimal);+ }++ /// A document that declares no language anywhere is English and silent —+ /// the overwhelmingly common minimal document, not an unhandled language.+ #[test]+ fn a_cascade_with_no_tag_at_all_is_english() {+ assert_eq!(Locale::from_cascade([rp(None)].iter()), Locale::English);+ assert_eq!(Locale::from_cascade(std::iter::empty()), Locale::English);+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/mod.rs b/crates/liteparse-docx/src/render/resolve/mod.rsnew file mode 100644index 0000000..0fa6136--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/mod.rs@@ -0,0 +1,377 @@+//! Resolve layer — transforms raw `Document` into layout-ready `ResolvedDocument`.++pub mod color;+pub mod conditional;+pub mod drawing_color;+pub mod fonts;+pub mod header_footer;+pub mod images;+pub mod locale;+pub mod numbering;+pub mod properties;+pub mod sections;+pub mod shape_geometry;+pub mod shape_visuals;+pub mod styles;++use std::collections::HashMap;++use crate::model::dimension::{Dimension, Twips};+use crate::model::{+ Block, Document, EmbeddedFont, NoteId, NumId, NumPicBullet, NumPicBulletId,+ ParagraphProperties, RelId, RunProperties, StyleId, Theme,+};++use self::images::MediaEntry;+use self::numbering::ResolvedNumberingLevel;+use self::sections::ResolvedSection;+use self::styles::ResolvedStyle;++/// A fully resolved document — ready for the layout pipeline.+/// All style inheritance resolved, sections split, headers/footers attached,+/// font families collected, image RelIds extracted.+#[derive(Debug)]+pub struct ResolvedDocument {+ /// Sections with their blocks, page geometry, and header/footer content.+ pub sections: Vec<ResolvedSection>,+ /// Fully resolved styles (basedOn chains walked, doc defaults applied).+ pub styles: HashMap<StyleId, ResolvedStyle>,+ /// Flattened numbering definitions.+ pub numbering: HashMap<NumId, Vec<ResolvedNumberingLevel>>,+ /// All unique font families referenced in the document.+ pub font_families: Vec<String>,+ /// Embedded media (images) — shared bytes with detected format, keyed by relationship ID.+ pub media: HashMap<RelId, MediaEntry>,+ /// §17.8.3: embedded fonts, carried through so the font registry can be+ /// built from the resolved document alone. They belong here rather than+ /// being read back off the `Document` because [`resolve`] consumes it.+ pub embedded_fonts: Vec<EmbeddedFont>,+ /// §17.9.21: picture bullet definitions keyed by numPicBulletId.+ pub pic_bullets: HashMap<NumPicBulletId, NumPicBullet>,+ /// Theme (for color resolution during paint).+ pub theme: Option<Theme>,+ /// Document-level default paragraph properties (from docDefaults).+ pub doc_defaults_paragraph: ParagraphProperties,+ /// Document-level default run properties (from docDefaults).+ pub doc_defaults_run: RunProperties,+ /// §17.7.4.17: the default paragraph style (w:default="1", type="paragraph").+ /// Applied to paragraphs that don't specify a style explicitly.+ pub default_paragraph_style_id: Option<StyleId>,+ /// Footnote content keyed by note ID.+ pub footnotes: HashMap<NoteId, Vec<Block>>,+ /// Endnote content keyed by note ID.+ pub endnotes: HashMap<NoteId, Vec<Block>>,+ /// §17.10.1 — when true, even-numbered pages use the section's+ /// `even` header/footer slot (and the `default` slot is restricted+ /// to odd pages). Without this flag, the `even` slots are dead+ /// data even if the document supplies them.+ pub even_and_odd_headers: bool,+ /// §17.15.1.25: the document's default tab-stop interval (`w:defaultTabStop`,+ /// spec default 720 twips). Consumed by paragraph tab layout.+ pub default_tab_stop: Dimension<Twips>,+}++/// Transform a raw parsed Document into a layout-ready ResolvedDocument.+///+/// Takes the document **by value**. Resolve is the parse output's last reader —+/// nothing downstream can reach a `Document` — so every part it carries forward+/// unchanged (body blocks, note bodies, theme, picture bullets, embedded fonts,+/// media handles) is *moved*. Borrowing instead forced a deep clone of the+/// entire block tree plus a second copy of every image, which on a large or+/// image-heavy document was the largest allocation in the pipeline outside+/// paint.+///+/// The two derived maps — resolved styles and flattened numbering — still read+/// their sources by reference, because each produces a new value rather than+/// re-homing the old one.+pub fn resolve(doc: Document) -> ResolvedDocument {+ use crate::model::StyleType;++ let font_families = fonts::collect_font_families(&doc);++ // §17.7.4.17: find the default paragraph style.+ let default_paragraph_style_id = doc+ .styles+ .styles+ .iter()+ .find(|(_, s)| s.is_default && s.style_type == StyleType::Paragraph)+ .map(|(id, _)| id.clone());++ // Destructured rather than field-by-field so that adding a field to+ // `Document` breaks this build: an unhandled part is a silently dropped+ // one.+ let Document {+ settings,+ theme,+ styles,+ numbering,+ body,+ final_section,+ headers,+ footers,+ footnotes,+ endnotes,+ media,+ embedded_fonts,+ } = doc;++ let resolved_styles = styles::resolve_styles(&styles, theme.as_ref());+ let resolved_numbering = numbering::resolve_numbering(&numbering);+ let sections = sections::resolve_sections(body, final_section, &headers, &footers);++ ResolvedDocument {+ sections,+ styles: resolved_styles,+ numbering: resolved_numbering,+ font_families,+ media: media+ .into_iter()+ .map(|(id, (data, format))| (id, MediaEntry { data, format }))+ .collect(),+ pic_bullets: numbering.pic_bullets,+ doc_defaults_paragraph: styles.doc_defaults_paragraph,+ doc_defaults_run: styles.doc_defaults_run,+ default_paragraph_style_id,+ theme,+ footnotes,+ endnotes,+ embedded_fonts,+ even_and_odd_headers: settings.even_and_odd_headers,+ default_tab_stop: settings.default_tab_stop,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::{Dimension, HalfPoints};+ use crate::model::*;++ fn empty_doc() -> Document {+ Document {+ settings: DocumentSettings::default(),+ theme: None,+ styles: StyleSheet::default(),+ numbering: NumberingDefinitions::default(),+ body: vec![],+ final_section: SectionProperties::default(),+ headers: HashMap::new(),+ footers: HashMap::new(),+ footnotes: HashMap::new(),+ endnotes: HashMap::new(),+ media: HashMap::new(),+ embedded_fonts: vec![],+ }+ }++ fn para(text: &str) -> Block {+ Block::Paragraph(Box::new(Paragraph {+ style_id: None,+ properties: ParagraphProperties::default(),+ mark_run_properties: None,+ content: vec![Inline::TextRun(Box::new(TextRun {+ style_id: None,+ properties: RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name("TestFont"),+ ..Default::default()+ },+ ..Default::default()+ },+ content: vec![RunElement::Text(text.to_string())],+ rsids: RevisionIds::default(),+ }))],+ rsids: ParagraphRevisionIds::default(),+ }))+ }++ #[test]+ fn resolve_empty_doc() {+ let doc = empty_doc();+ let resolved = resolve(doc);++ assert_eq!(resolved.sections.len(), 1);+ assert!(resolved.sections[0].blocks.is_empty());+ assert!(resolved.styles.is_empty());+ assert!(resolved.numbering.is_empty());+ assert!(resolved.font_families.is_empty());+ assert!(resolved.media.is_empty());+ assert!(resolved.theme.is_none());+ }++ #[test]+ fn resolve_preserves_body_content() {+ let mut doc = empty_doc();+ doc.body = vec![para("hello"), para("world")];++ let resolved = resolve(doc);+ assert_eq!(resolved.sections.len(), 1);+ assert_eq!(resolved.sections[0].blocks.len(), 2);+ }++ #[test]+ fn resolve_splits_sections() {+ let mut doc = empty_doc();+ doc.body = vec![+ para("first"),+ Block::SectionBreak(Box::default()),+ para("second"),+ ];++ let resolved = resolve(doc);+ assert_eq!(resolved.sections.len(), 2);+ assert_eq!(resolved.sections[0].blocks.len(), 1);+ assert_eq!(resolved.sections[1].blocks.len(), 1);+ }++ #[test]+ fn resolve_resolves_styles() {+ let mut doc = empty_doc();+ doc.styles.doc_defaults_run = RunProperties {+ font_size: Some(Dimension::<HalfPoints>::new(22)),+ ..Default::default()+ };+ doc.styles.styles.insert(+ StyleId::new("Normal"),+ Style {+ name: None,+ style_type: StyleType::Paragraph,+ based_on: None,+ is_default: true,+ paragraph_properties: Some(ParagraphProperties {+ alignment: Some(Alignment::Start),+ ..Default::default()+ }),+ run_properties: None,+ table_properties: None,+ table_style_overrides: vec![],+ },+ );++ let resolved = resolve(doc);+ let normal = resolved.styles.get(&StyleId::new("Normal")).unwrap();+ assert_eq!(normal.paragraph.alignment, Some(Alignment::Start));+ assert_eq!(+ normal.run.font_size,+ Some(Dimension::<HalfPoints>::new(22)),+ "should inherit doc default"+ );+ }++ #[test]+ fn resolve_collects_fonts() {+ let mut doc = empty_doc();+ doc.body = vec![para("text")];++ let resolved = resolve(doc);+ assert!(resolved.font_families.contains(&"TestFont".to_string()));+ }++ #[test]+ fn resolve_resolves_numbering() {+ let mut doc = empty_doc();+ doc.numbering.abstract_nums.insert(+ AbstractNumId::new(0),+ AbstractNumbering {+ levels: vec![NumberingLevelDefinition {+ level: 0,+ format: Some(NumberFormat::Decimal),+ level_text: "%1.".into(),+ start: Some(1),+ justification: None,+ indentation: None,+ run_properties: None,+ lvl_pic_bullet_id: None,+ suffix: crate::model::LevelSuffix::default(),+ is_legal: false,+ }],+ },+ );+ doc.numbering.numbering_instances.insert(+ NumId::new(1),+ NumberingInstance {+ abstract_num_id: AbstractNumId::new(0),+ level_overrides: vec![],+ },+ );++ let resolved = resolve(doc);+ let levels = resolved.numbering.get(&NumId::new(1)).unwrap();+ assert_eq!(levels.len(), 1);+ assert_eq!(levels[0].format, NumberFormat::Decimal);+ }++ #[test]+ fn resolve_preserves_media() {+ let mut doc = empty_doc();+ use crate::model::ImageFormat;+ doc.media.insert(+ RelId::new("rId1"),+ (+ std::sync::Arc::from(&[0xFF_u8, 0xD8, 0xFF][..]),+ ImageFormat::Jpeg,+ ),+ );++ let resolved = resolve(doc);+ assert!(resolved.media.contains_key(&RelId::new("rId1")));+ let entry = &resolved.media[&RelId::new("rId1")];+ assert_eq!(&*entry.data, &[0xFF_u8, 0xD8, 0xFF][..]);+ assert_eq!(entry.format, ImageFormat::Jpeg);+ }++ /// Media crosses the resolve boundary as a *handle*. Copying instead is+ /// invisible in the rendered output — every assertion above still holds —+ /// but it doubles the resident cost of every image, so nothing else can+ /// catch a regression here.+ #[test]+ fn resolve_shares_media_bytes_rather_than_copying_them() {+ use crate::model::ImageFormat;+ use std::sync::Arc;++ let bytes: Arc<[u8]> = Arc::from(&[0xFF_u8, 0xD8, 0xFF][..]);+ let mut doc = empty_doc();+ doc.media+ .insert(RelId::new("rId1"), (Arc::clone(&bytes), ImageFormat::Jpeg));++ let resolved = resolve(doc);+ assert!(+ Arc::ptr_eq(&resolved.media[&RelId::new("rId1")].data, &bytes),+ "resolve must pass the parser's allocation through, not a copy of it",+ );+ }++ #[test]+ fn resolve_preserves_theme() {+ let mut doc = empty_doc();+ doc.theme = Some(Theme {+ color_scheme: ThemeColorScheme {+ accent1: 0x4472C4,+ ..Default::default()+ },+ ..Default::default()+ });++ let resolved = resolve(doc);+ assert!(resolved.theme.is_some());+ assert_eq!(resolved.theme.unwrap().color_scheme.accent1, 0x4472C4);+ }++ #[test]+ fn resolve_headers_attached_to_sections() {+ let mut doc = empty_doc();+ let hdr_id = RelId::new("rId1");+ doc.headers.insert(hdr_id.clone(), vec![para("header")]);+ doc.final_section = SectionProperties {+ header_refs: SectionHeaderFooterRefs {+ default: Some(hdr_id),+ ..Default::default()+ },+ ..Default::default()+ };+ doc.body = vec![para("body")];++ let resolved = resolve(doc);+ assert!(resolved.sections[0].headers.default.is_some());+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/numbering.rs b/crates/liteparse-docx/src/render/resolve/numbering.rsnew file mode 100644index 0000000..8adca9a--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/numbering.rs@@ -0,0 +1,758 @@+//! Numbering resolution — flatten abstract + instance + overrides into lookup table.++use std::collections::HashMap;++use crate::model::{+ Alignment, Indentation, LevelSuffix, NumId, NumPicBulletId, NumberFormat, NumberingDefinitions,+ NumberingLevelDefinition, RunProperties,+};+use crate::render::resolve::locale::Locale;++/// A resolved numbering level — ready for label generation.+#[derive(Clone, Debug)]+pub struct ResolvedNumberingLevel {+ pub format: NumberFormat,+ pub level_text: String,+ pub start: u32,+ /// §17.9.3: run properties for the numbering symbol (font, color, etc.).+ pub run_properties: Option<RunProperties>,+ /// §17.9.3: paragraph indentation from the numbering level definition.+ /// When present, overrides the paragraph style's indentation.+ pub indentation: Option<Indentation>,+ /// §17.9.7: justification of the numbering symbol (left, center, right).+ pub justification: Option<Alignment>,+ /// §17.9.10: reference to a picture bullet definition.+ pub lvl_pic_bullet_id: Option<NumPicBulletId>,+ /// §17.9.29: separator between the label and the paragraph text.+ pub suffix: LevelSuffix,+ /// §17.9.8: render all level numbers as decimal (legal numbering).+ pub is_legal: bool,+}++/// Resolve numbering definitions into a flat lookup: `NumId` →+/// `Vec<ResolvedNumberingLevel>`.+/// Each instance's abstract definition is looked up and level overrides applied.+pub fn resolve_numbering(+ defs: &NumberingDefinitions,+) -> HashMap<NumId, Vec<ResolvedNumberingLevel>> {+ let mut result = HashMap::new();++ for (num_id, instance) in &defs.numbering_instances {+ let abstract_levels = defs+ .abstract_nums+ .get(&instance.abstract_num_id)+ .map(|a| a.levels.as_slice())+ .unwrap_or(&[]);++ let mut levels: Vec<ResolvedNumberingLevel> =+ abstract_levels.iter().map(resolve_level).collect();++ // Apply level overrides (§17.9.9). A `<w:lvlOverride>` may supply a full+ // replacement `<w:lvl>` and/or a `<w:startOverride>` that restarts the+ // level's counter.+ for ovr in &instance.level_overrides {+ let idx = ovr.level as usize;+ if idx >= levels.len() {+ continue; // override references a level beyond the abstract def+ }+ if let Some(def) = &ovr.definition {+ levels[idx] = resolve_level(def);+ }+ if let Some(start) = ovr.start_override {+ levels[idx].start = start;+ }+ }++ result.insert(*num_id, levels);+ }++ result+}++fn resolve_level(def: &NumberingLevelDefinition) -> ResolvedNumberingLevel {+ ResolvedNumberingLevel {+ format: def.format.unwrap_or(NumberFormat::None),+ level_text: def.level_text.clone(),+ start: def.start.unwrap_or(1),+ run_properties: def.run_properties.clone(),+ indentation: def.indentation,+ justification: def.justification,+ lvl_pic_bullet_id: def.lvl_pic_bullet_id,+ suffix: def.suffix,+ is_legal: def.is_legal,+ }+}++/// §17.9.11: format a list label by expanding the level_text template.+/// `%1` is replaced with the formatted counter for level 0, `%2` for level 1, etc.+/// Returns `None` for `NumberFormat::None`.+pub fn format_list_label(+ levels: &[ResolvedNumberingLevel],+ level: u8,+ counters: &HashMap<(NumId, u8), u32>,+ num_id: NumId,+ locale: Locale,+) -> Option<String> {+ let lvl = levels.get(level as usize)?;+ if lvl.format == NumberFormat::None {+ return None;+ }+ if lvl.format == NumberFormat::Bullet {+ return Some(lvl.level_text.clone());+ }++ // Expand template: %1 → level 0 counter, %2 → level 1 counter, etc.+ // §17.9.8: when this level is "legal", every referenced counter is rendered+ // as decimal regardless of the individual levels' own formats.+ let mut result = lvl.level_text.clone();+ for i in (0..=level).rev() {+ let placeholder = format!("%{}", i + 1);+ if result.contains(&placeholder) {+ let count = counters.get(&(num_id, i)).copied().unwrap_or(1);+ let fmt = if lvl.is_legal {+ NumberFormat::Decimal+ } else {+ levels+ .get(i as usize)+ .map(|l| l.format)+ .unwrap_or(NumberFormat::Decimal)+ };+ let formatted = format_number(count, fmt, locale);+ result = result.replace(&placeholder, &formatted);+ }+ }+ Some(result)+}++/// §17.18.59 `ST_NumberFormat`: render one counter.+///+/// Total over `NumberFormat` — the `_ =>` arm this replaced answered+/// `n.to_string()` for every format it did not implement, which is right for+/// none of them: it printed a digit where `none` asks for nothing, and it hid+/// `cardinalText` and `ordinalText` behind an answer that looked deliberate.+///+/// `locale` decides only the three language-dependent formats; the rest are+/// the same in every language, which is why they take it without using it.+fn format_number(n: u32, fmt: NumberFormat, locale: Locale) -> String {+ match fmt {+ NumberFormat::Decimal => n.to_string(),+ NumberFormat::LowerLetter => to_letter_lower(n),+ NumberFormat::UpperLetter => to_letter_upper(n),+ NumberFormat::LowerRoman => to_roman_lower(n),+ NumberFormat::UpperRoman => to_roman_upper(n),++ // §17.9.27: the three formats that are written differently in every+ // language. This engine spells one of them; for the rest the digits+ // are the honest answer — see `Locale::spells_numbers`.+ NumberFormat::Ordinal if locale.spells_numbers() => format_ordinal(n),+ NumberFormat::CardinalText if locale.spells_numbers() => to_cardinal_text(n),+ NumberFormat::OrdinalText if locale.spells_numbers() => to_ordinal_text(n),+ NumberFormat::Ordinal | NumberFormat::CardinalText | NumberFormat::OrdinalText => {+ n.to_string()+ }++ // §17.18.59: `bullet` renders the level text, `none` renders nothing —+ // neither renders the counter. `format_list_label` returns before+ // reaching either, so these are unreachable in practice; answering with+ // the digit would be wrong if a future caller did reach them.+ NumberFormat::Bullet | NumberFormat::None => String::new(),+ }+}++/// §17.9.27 `cardinalText`: the number in English words, e.g. `1234` →+/// "One Thousand Two Hundred Thirty-Four".+///+/// US English convention, which is what Word writes: tens and units joined by a+/// hyphen, scale groups by a space, and **no** "and" before the final group.+/// Each word capitalised. Unverified against a Word render; recorded here+/// rather than guessed at each call site.+fn to_cardinal_text(n: u32) -> String {+ const UNITS: [&str; 20] = [+ "Zero",+ "One",+ "Two",+ "Three",+ "Four",+ "Five",+ "Six",+ "Seven",+ "Eight",+ "Nine",+ "Ten",+ "Eleven",+ "Twelve",+ "Thirteen",+ "Fourteen",+ "Fifteen",+ "Sixteen",+ "Seventeen",+ "Eighteen",+ "Nineteen",+ ];+ const TENS: [&str; 10] = [+ "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",+ ];+ /// Groups of a thousand, smallest first. `u32::MAX` needs three.+ const SCALES: [&str; 4] = ["", "Thousand", "Million", "Billion"];++ /// 1..=999 — never called with 0, so it never emits a stray "Zero".+ fn under_thousand(n: u32) -> String {+ match n {+ 0 => String::new(),+ 1..=19 => UNITS[n as usize].to_string(),+ 20..=99 => {+ let (tens, unit) = (TENS[(n / 10) as usize], n % 10);+ if unit == 0 {+ tens.to_string()+ } else {+ format!("{tens}-{}", UNITS[unit as usize])+ }+ }+ _ => {+ let (hundreds, rest) = (UNITS[(n / 100) as usize], n % 100);+ if rest == 0 {+ format!("{hundreds} Hundred")+ } else {+ format!("{hundreds} Hundred {}", under_thousand(rest))+ }+ }+ }+ }++ if n == 0 {+ return UNITS[0].to_string();+ }++ // Split into thousand-groups, then emit largest-first.+ let mut groups = Vec::new();+ let mut rest = n;+ while rest > 0 {+ groups.push(rest % 1000);+ rest /= 1000;+ }+ let mut words = Vec::new();+ for (i, group) in groups.iter().enumerate().rev() {+ if *group == 0 {+ continue;+ }+ let scale = SCALES[i];+ words.push(if scale.is_empty() {+ under_thousand(*group)+ } else {+ format!("{} {scale}", under_thousand(*group))+ });+ }+ words.join(" ")+}++/// §17.9.27 `ordinalText`: the number as an English ordinal in words, e.g.+/// `21` → "Twenty-First".+///+/// Only the **final word** takes the ordinal form — "One Thousand Two Hundred+/// Thirty-Four" becomes "…Thirty-Fourth", not "First Thousandth …" — so this+/// spells the cardinal and rewrites its last word. The separator before that+/// word (space or hyphen) is preserved exactly.+fn to_ordinal_text(n: u32) -> String {+ let cardinal = to_cardinal_text(n);+ // ASCII throughout, so a byte index from `rfind` is a char boundary.+ match cardinal.rfind([' ', '-']) {+ Some(i) => format!("{}{}", &cardinal[..=i], ordinal_word(&cardinal[i + 1..])),+ None => ordinal_word(&cardinal),+ }+}++/// The ordinal form of one English number word.+///+/// The irregulars are listed; everything else — "Four", "Six", "Seven", "Ten",+/// the teens, and the scale words "Hundred"/"Thousand"/"Million"/"Billion" —+/// takes a plain `th`.+fn ordinal_word(word: &str) -> String {+ match word {+ "One" => "First",+ "Two" => "Second",+ "Three" => "Third",+ "Five" => "Fifth",+ "Eight" => "Eighth",+ "Nine" => "Ninth",+ "Twelve" => "Twelfth",+ "Twenty" => "Twentieth",+ "Thirty" => "Thirtieth",+ "Forty" => "Fortieth",+ "Fifty" => "Fiftieth",+ "Sixty" => "Sixtieth",+ "Seventy" => "Seventieth",+ "Eighty" => "Eightieth",+ "Ninety" => "Ninetieth",+ other => return format!("{other}th"),+ }+ .to_string()+}++fn to_letter_lower(n: u32) -> String {+ if n == 0 {+ return String::new();+ }+ // ST_NumberFormat `lowerLetter`: Word repeats the letter on overflow —+ // a…z, then aa, bb, …, zz, aaa (a *repeating* scheme, not bijective+ // base-26). Item 27 is "aa", not "a" again.+ let idx = ((n - 1) % 26) as u8;+ let count = ((n - 1) / 26) as usize + 1;+ std::iter::repeat_n((b'a' + idx) as char, count).collect()+}++fn to_letter_upper(n: u32) -> String {+ to_letter_lower(n).to_uppercase()+}++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+}++fn to_roman_upper(n: u32) -> String {+ to_roman_lower(n).to_uppercase()+}++fn format_ordinal(n: u32) -> String {+ let suffix = match n % 100 {+ 11..=13 => "th",+ _ => match n % 10 {+ 1 => "st",+ 2 => "nd",+ 3 => "rd",+ _ => "th",+ },+ };+ format!("{n}{suffix}")+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::*;++ fn make_defs(+ abstracts: Vec<(AbstractNumId, Vec<NumberingLevelDefinition>)>,+ instances: Vec<(NumId, AbstractNumId, Vec<NumberingLevelDefinition>)>,+ ) -> NumberingDefinitions {+ NumberingDefinitions {+ abstract_nums: abstracts+ .into_iter()+ .map(|(id, levels)| (id, AbstractNumbering { levels }))+ .collect(),+ numbering_instances: instances+ .into_iter()+ .map(|(num_id, abstract_id, overrides)| {+ (+ num_id,+ NumberingInstance {+ abstract_num_id: abstract_id,+ level_overrides: overrides+ .into_iter()+ .map(|def| crate::model::LevelOverride {+ level: def.level,+ start_override: None,+ definition: Some(def),+ })+ .collect(),+ },+ )+ })+ .collect(),+ pic_bullets: HashMap::new(),+ }+ }++ fn level(lvl: u8, fmt: NumberFormat, text: &str, start: u32) -> NumberingLevelDefinition {+ NumberingLevelDefinition {+ level: lvl,+ format: Some(fmt),+ level_text: text.to_string(),+ start: Some(start),+ justification: None,+ indentation: None,+ run_properties: None,+ lvl_pic_bullet_id: None,+ suffix: LevelSuffix::default(),+ is_legal: false,+ }+ }++ #[test]+ fn single_instance_resolves_from_abstract() {+ let defs = make_defs(+ vec![(+ AbstractNumId::new(0),+ vec![level(0, NumberFormat::Decimal, "%1.", 1)],+ )],+ vec![(NumId::new(1), AbstractNumId::new(0), vec![])],+ );++ let resolved = resolve_numbering(&defs);+ let levels = resolved.get(&NumId::new(1)).unwrap();++ assert_eq!(levels.len(), 1);+ assert_eq!(levels[0].format, NumberFormat::Decimal);+ assert_eq!(levels[0].level_text, "%1.");+ assert_eq!(levels[0].start, 1);+ }++ #[test]+ fn level_override_replaces_abstract_level() {+ let defs = make_defs(+ vec![(+ AbstractNumId::new(0),+ vec![+ level(0, NumberFormat::Decimal, "%1.", 1),+ level(1, NumberFormat::LowerLetter, "%2)", 1),+ ],+ )],+ vec![(+ NumId::new(1),+ AbstractNumId::new(0),+ // Override level 0 to bullet+ vec![level(0, NumberFormat::Bullet, "•", 1)],+ )],+ );++ let resolved = resolve_numbering(&defs);+ let levels = resolved.get(&NumId::new(1)).unwrap();++ assert_eq!(levels.len(), 2);+ assert_eq!(levels[0].format, NumberFormat::Bullet, "overridden");+ assert_eq!(levels[0].level_text, "•");+ assert_eq!(levels[1].format, NumberFormat::LowerLetter, "from abstract");+ }++ #[test]+ fn missing_abstract_produces_empty_levels() {+ let defs = make_defs(+ vec![],+ vec![(NumId::new(1), AbstractNumId::new(99), vec![])],+ );++ let resolved = resolve_numbering(&defs);+ let levels = resolved.get(&NumId::new(1)).unwrap();+ assert!(levels.is_empty());+ }++ #[test]+ fn multiple_instances_same_abstract() {+ let defs = make_defs(+ vec![(+ AbstractNumId::new(0),+ vec![level(0, NumberFormat::Decimal, "%1.", 1)],+ )],+ vec![+ (NumId::new(1), AbstractNumId::new(0), vec![]),+ (+ NumId::new(2),+ AbstractNumId::new(0),+ vec![level(0, NumberFormat::Decimal, "%1)", 10)],+ ),+ ],+ );++ let resolved = resolve_numbering(&defs);++ let l1 = resolved.get(&NumId::new(1)).unwrap();+ assert_eq!(l1[0].level_text, "%1.");+ assert_eq!(l1[0].start, 1);++ let l2 = resolved.get(&NumId::new(2)).unwrap();+ assert_eq!(l2[0].level_text, "%1)");+ assert_eq!(l2[0].start, 10);+ }++ #[test]+ fn start_override_restarts_level_counter() {+ // A startOverride-only lvlOverride resets the level's start value.+ let mut abstract_nums = HashMap::new();+ abstract_nums.insert(+ AbstractNumId::new(0),+ AbstractNumbering {+ levels: vec![level(0, NumberFormat::Decimal, "%1.", 1)],+ },+ );+ let mut numbering_instances = HashMap::new();+ numbering_instances.insert(+ NumId::new(1),+ NumberingInstance {+ abstract_num_id: AbstractNumId::new(0),+ level_overrides: vec![crate::model::LevelOverride {+ level: 0,+ start_override: Some(5),+ definition: None,+ }],+ },+ );+ let defs = NumberingDefinitions {+ abstract_nums,+ numbering_instances,+ pic_bullets: HashMap::new(),+ };+ let resolved = resolve_numbering(&defs);+ assert_eq!(resolved[&NumId::new(1)][0].start, 5);+ }++ #[test]+ fn legal_numbering_renders_all_levels_decimal() {+ let levels = vec![+ ResolvedNumberingLevel {+ format: NumberFormat::UpperRoman,+ level_text: "%1".to_string(),+ start: 1,+ run_properties: None,+ indentation: None,+ justification: None,+ lvl_pic_bullet_id: None,+ suffix: LevelSuffix::default(),+ is_legal: false,+ },+ ResolvedNumberingLevel {+ format: NumberFormat::LowerLetter,+ level_text: "%1.%2".to_string(),+ start: 1,+ run_properties: None,+ indentation: None,+ justification: None,+ lvl_pic_bullet_id: None,+ suffix: LevelSuffix::default(),+ is_legal: true,+ },+ ];+ let mut counters = HashMap::new();+ counters.insert((NumId::new(1), 0u8), 3u32); // would be "III" un-legal+ counters.insert((NumId::new(1), 1u8), 2u32); // would be "b" un-legal+ let label =+ format_list_label(&levels, 1, &counters, NumId::new(1), Locale::English).unwrap();+ assert_eq!(+ label, "3.2",+ "isLgl forces decimal for every referenced level"+ );+ }++ #[test]+ fn level_with_no_format_defaults_to_none() {+ let defs = make_defs(+ vec![(+ AbstractNumId::new(0),+ vec![NumberingLevelDefinition {+ level: 0,+ format: None,+ level_text: String::new(),+ start: None,+ justification: None,+ indentation: None,+ run_properties: None,+ lvl_pic_bullet_id: None,+ suffix: LevelSuffix::default(),+ is_legal: false,+ }],+ )],+ vec![(NumId::new(1), AbstractNumId::new(0), vec![])],+ );++ let resolved = resolve_numbering(&defs);+ let levels = resolved.get(&NumId::new(1)).unwrap();+ assert_eq!(levels[0].format, NumberFormat::None);+ assert_eq!(levels[0].start, 1);+ }++ #[test]+ fn lower_letter_repeats_on_overflow() {+ // §17.9 lowerLetter: a…z then aa, bb, … (repeating, not bijective).+ assert_eq!(+ format_number(1, NumberFormat::LowerLetter, Locale::English),+ "a"+ );+ assert_eq!(+ format_number(26, NumberFormat::LowerLetter, Locale::English),+ "z"+ );+ assert_eq!(+ format_number(27, NumberFormat::LowerLetter, Locale::English),+ "aa"+ );+ assert_eq!(+ format_number(28, NumberFormat::LowerLetter, Locale::English),+ "bb"+ );+ assert_eq!(+ format_number(52, NumberFormat::LowerLetter, Locale::English),+ "zz"+ );+ assert_eq!(+ format_number(53, NumberFormat::LowerLetter, Locale::English),+ "aaa"+ );+ }++ #[test]+ fn upper_letter_matches_lower_uppercased() {+ assert_eq!(+ format_number(27, NumberFormat::UpperLetter, Locale::English),+ "AA"+ );+ }++ #[test]+ fn roman_and_ordinal_formats() {+ assert_eq!(+ format_number(4, NumberFormat::LowerRoman, Locale::English),+ "iv"+ );+ assert_eq!(+ format_number(2026, NumberFormat::UpperRoman, Locale::English),+ "MMXXVI"+ );+ assert_eq!(+ format_number(1, NumberFormat::Ordinal, Locale::English),+ "1st"+ );+ assert_eq!(+ format_number(2, NumberFormat::Ordinal, Locale::English),+ "2nd"+ );+ assert_eq!(+ format_number(11, NumberFormat::Ordinal, Locale::English),+ "11th"+ );+ assert_eq!(+ format_number(23, NumberFormat::Ordinal, Locale::English),+ "23rd"+ );+ assert_eq!(+ format_number(111, NumberFormat::Ordinal, Locale::English),+ "111th"+ );+ }++ // ── §17.9.27 number words ────────────────────────────────────────────++ #[test]+ fn cardinal_text_spells_each_decade_boundary() {+ for (n, want) in [+ (0, "Zero"),+ (1, "One"),+ (12, "Twelve"),+ (19, "Nineteen"),+ (20, "Twenty"),+ (21, "Twenty-One"),+ (99, "Ninety-Nine"),+ (100, "One Hundred"),+ (101, "One Hundred One"),+ (115, "One Hundred Fifteen"),+ (999, "Nine Hundred Ninety-Nine"),+ ] {+ assert_eq!(to_cardinal_text(n), want, "{n}");+ }+ }++ /// A zero group is skipped rather than spelled: 1,000,007 has no "Thousand"+ /// in it at all. Getting this wrong yields "One Million Zero Thousand …".+ #[test]+ fn cardinal_text_skips_empty_scale_groups() {+ assert_eq!(to_cardinal_text(1_000), "One Thousand");+ assert_eq!(to_cardinal_text(1_000_007), "One Million Seven");+ assert_eq!(+ to_cardinal_text(1_234_567),+ "One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven",+ );+ }++ /// The largest counter the type admits, so the scale table cannot run off+ /// its end.+ #[test]+ fn cardinal_text_spells_the_whole_u32_range() {+ assert_eq!(+ to_cardinal_text(u32::MAX),+ "Four Billion Two Hundred Ninety-Four Million Nine Hundred Sixty-Seven \+ Thousand Two Hundred Ninety-Five",+ );+ }++ /// §17.9.27 `ordinalText` changes the **last word only**, and the irregular+ /// forms are where a naive `+ "th"` breaks.+ #[test]+ fn ordinal_text_rewrites_only_the_final_word() {+ for (n, want) in [+ (1, "First"),+ (2, "Second"),+ (3, "Third"),+ (4, "Fourth"),+ (5, "Fifth"),+ (8, "Eighth"),+ (9, "Ninth"),+ (12, "Twelfth"),+ (13, "Thirteenth"),+ (20, "Twentieth"),+ (21, "Twenty-First"),+ (40, "Fortieth"),+ (100, "One Hundredth"),+ (101, "One Hundred First"),+ (1_000, "One Thousandth"),+ (1_021, "One Thousand Twenty-First"),+ ] {+ assert_eq!(to_ordinal_text(n), want, "{n}");+ }+ }++ /// §17.18.59: neither `bullet` nor `none` renders the counter. The `_ =>`+ /// arm this replaced printed the digit for both.+ #[test]+ fn formats_that_render_no_counter_render_nothing() {+ assert_eq!(format_number(7, NumberFormat::Bullet, Locale::English), "");+ assert_eq!(format_number(7, NumberFormat::None, Locale::English), "");+ }++ /// A language whose number words this engine cannot spell gets the digits —+ /// for all three text formats, not just the one that was implemented.+ #[test]+ fn a_non_spelling_locale_gets_digits_for_every_text_format() {+ for fmt in [+ NumberFormat::Ordinal,+ NumberFormat::CardinalText,+ NumberFormat::OrdinalText,+ ] {+ assert_eq!(format_number(3, fmt, Locale::CommaDecimal), "3", "{fmt:?}");+ assert_eq!(format_number(3, fmt, Locale::PointDecimal), "3", "{fmt:?}");+ }+ }++ /// …and the formats that are the same in every language are untouched by it.+ #[test]+ fn language_independent_formats_ignore_the_locale() {+ for locale in [+ Locale::English,+ Locale::CommaDecimal,+ Locale::PointDecimal,+ Locale::Unrecognised,+ ] {+ assert_eq!(format_number(4, NumberFormat::Decimal, locale), "4");+ assert_eq!(format_number(4, NumberFormat::LowerRoman, locale), "iv");+ assert_eq!(format_number(4, NumberFormat::UpperLetter, locale), "D");+ }+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/properties.rs b/crates/liteparse-docx/src/render/resolve/properties.rsnew file mode 100644index 0000000..9abb7ac--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/properties.rs@@ -0,0 +1,764 @@+//! Option-field merging for RunProperties and ParagraphProperties.+//!+//! "Merge" means: for each field, if `self` is `None`, take the value from `base`.+//! This implements the OOXML style inheritance cascade.++use crate::model::{ParagraphProperties, RunProperties, TabAlignment, TableProperties};++/// Fill any `None` fields in `$target` from the corresponding fields in `$base`.+///+/// Expands to a sequence of `merge_opt(&mut $target.$field, &$base.$field)` calls.+macro_rules! merge_fields {+ ($target:expr, $base:expr, $($field:ident),+ $(,)?) => {+ $(merge_opt(&mut $target.$field, &$base.$field);)++ };+}++/// Merge `base` into `target`: any `None` field in `target` gets filled from `base`.+pub fn merge_run_properties(target: &mut RunProperties, base: &RunProperties) {+ // FontSet: delegate to FontSlot::merge_from so each slot handles its own fields.+ target.fonts.ascii.merge_from(&base.fonts.ascii);+ target.fonts.high_ansi.merge_from(&base.fonts.high_ansi);+ target.fonts.east_asian.merge_from(&base.fonts.east_asian);+ target+ .fonts+ .complex_script+ .merge_from(&base.fonts.complex_script);++ merge_fields!(+ target,+ base,+ font_size,+ bold,+ italic,+ underline,+ strike,+ color,+ highlight,+ shading,+ vertical_align,+ spacing,+ kerning,+ all_caps,+ small_caps,+ vanish,+ no_proof,+ web_hidden,+ rtl,+ emboss,+ imprint,+ outline,+ shadow,+ position,+ lang,+ border,+ text_scale,+ );+}++/// Merge `base` into `target`: any `None` field in `target` gets filled from `base`.+pub fn merge_paragraph_properties(target: &mut ParagraphProperties, base: &ParagraphProperties) {+ merge_opt(&mut target.alignment, &base.alignment);+ // §17.3.1.12: merge indentation sub-fields individually so partial+ // overrides (e.g., left from child style, firstLine from parent) combine.+ match (&mut target.indentation, &base.indentation) {+ (Some(ti), Some(bi)) => {+ merge_opt(&mut ti.start, &bi.start);+ merge_opt(&mut ti.end, &bi.end);+ merge_opt(&mut ti.first_line, &bi.first_line);+ merge_opt(&mut ti.mirror, &bi.mirror);+ }+ (None, Some(_)) => target.indentation = base.indentation,+ _ => {}+ }+ // §17.3.1.33: merge spacing sub-fields individually so partial+ // overrides (e.g., line from table style, after from paragraph style)+ // combine correctly.+ match (&mut target.spacing, &base.spacing) {+ (Some(ts), Some(bs)) => {+ merge_opt(&mut ts.before, &bs.before);+ merge_opt(&mut ts.after, &bs.after);+ merge_opt(&mut ts.line, &bs.line);+ merge_opt(&mut ts.before_auto_spacing, &bs.before_auto_spacing);+ merge_opt(&mut ts.after_auto_spacing, &bs.after_auto_spacing);+ }+ (None, Some(_)) => target.spacing = base.spacing,+ _ => {}+ }+ merge_fields!(+ target,+ base,+ numbering,+ borders,+ shading,+ keep_next,+ keep_lines,+ widow_control,+ page_break_before,+ suppress_auto_hyphens,+ contextual_spacing,+ bidi,+ word_wrap,+ outline_level,+ text_alignment,+ cnf_style,+ frame_properties,+ auto_space_de,+ auto_space_dn,+ );++ // §17.3.1.38: merge tab stops at the individual-stop level.+ // Child Clear entries remove matching positions from the parent.+ // Child non-Clear entries are added. Result is sorted by position.+ if !base.tabs.is_empty() || !target.tabs.is_empty() {+ let child_tabs = std::mem::take(&mut target.tabs);+ // Start from parent tabs.+ target.tabs.clone_from(&base.tabs);+ // Remove positions that the child clears.+ for clear in child_tabs+ .iter()+ .filter(|t| t.alignment == TabAlignment::Clear)+ {+ target.tabs.retain(|t| t.position != clear.position);+ }+ // Add child's non-Clear tabs (replacing any at the same position).+ for tab in child_tabs+ .iter()+ .filter(|t| t.alignment != TabAlignment::Clear)+ {+ target.tabs.retain(|t| t.position != tab.position);+ target.tabs.push(*tab);+ }+ target.tabs.sort_by_key(|t| t.position.raw());+ }+}++/// §17.7.2: merge table properties from a parent table style.+/// Only `cell_margins` is merged — other table properties (borders, width, etc.)+/// are resolved separately through the table-level cascade in `build_table`.+pub fn merge_table_properties(+ target: &mut Option<TableProperties>,+ base: &Option<TableProperties>,+) {+ match (target.as_mut(), base.as_ref()) {+ (Some(t), Some(b)) => {+ merge_opt(&mut t.cell_margins, &b.cell_margins);+ }+ (None, Some(_)) => {+ *target = base.clone();+ }+ _ => {}+ }+}++/// §17.7.6: overlay a `wholeTable` conditional layer onto a table style's own+/// table properties. Every field the overlay specifies wins; the rest fall+/// through to `base`.+///+/// This is the opposite direction from [`merge_table_properties`], which is+/// *inheritance* (the target keeps what it has and the base fills gaps).+/// `wholeTable` is conditional formatting layered on top of the style, so it+/// overrides rather than backfills.+///+/// `style_id` is deliberately not overlaid: a `tblStylePr` carrying a+/// `tblStyle` reference would point a style at another style from inside its+/// own conditional formatting, which §17.7.6 does not define and which would+/// invite a resolution loop.+pub fn overlay_table_properties(+ base: Option<TableProperties>,+ overlay: &TableProperties,+) -> TableProperties {+ let mut out = base.unwrap_or_default();+ // Listed field by field rather than by `..overlay.clone()` so that adding a+ // field to `TableProperties` without deciding how it layers is a visible+ // omission here, not a silent one. `table_properties_overlay_covers_every_field`+ // pins it.+ take(&mut out.alignment, overlay.alignment);+ take(&mut out.width, overlay.width);+ take(&mut out.layout, overlay.layout);+ take(&mut out.indent, overlay.indent);+ take(&mut out.borders, overlay.borders);+ take(&mut out.cell_margins, overlay.cell_margins);+ take(&mut out.cell_spacing, overlay.cell_spacing);+ take(&mut out.look, overlay.look);+ take(&mut out.style_row_band_size, overlay.style_row_band_size);+ take(&mut out.style_col_band_size, overlay.style_col_band_size);+ take(&mut out.positioning, overlay.positioning);+ take(&mut out.overlap, overlay.overlap);+ out+}++/// If `overlay` specifies a value, it replaces `target`.+fn take<T>(target: &mut Option<T>, overlay: Option<T>) {+ if overlay.is_some() {+ *target = overlay;+ }+}++/// If `target` is `None`, clone `base` into it.+fn merge_opt<T: Clone>(target: &mut Option<T>, base: &Option<T>) {+ if target.is_none() {+ *target = base.clone();+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::{Dimension, HalfPoints, Twips};+ use crate::model::*;++ // ── RunProperties merging ────────────────────────────────────────────++ #[test]+ fn merge_run_empty_target_takes_all_from_base() {+ let mut target = RunProperties::default();+ let base = RunProperties {+ bold: Some(true),+ italic: Some(true),+ font_size: Some(Dimension::<HalfPoints>::new(24)),+ color: Some(Color::Rgb(0xFF0000)),+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);++ assert_eq!(target.bold, Some(true));+ assert_eq!(target.italic, Some(true));+ assert_eq!(target.font_size, Some(Dimension::<HalfPoints>::new(24)));+ assert_eq!(target.color, Some(Color::Rgb(0xFF0000)));+ }++ #[test]+ fn merge_run_target_values_not_overwritten() {+ let mut target = RunProperties {+ bold: Some(false),+ font_size: Some(Dimension::<HalfPoints>::new(20)),+ ..Default::default()+ };+ let base = RunProperties {+ bold: Some(true),+ italic: Some(true),+ font_size: Some(Dimension::<HalfPoints>::new(24)),+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);++ assert_eq!(target.bold, Some(false), "target's bold should win");+ assert_eq!(+ target.font_size,+ Some(Dimension::<HalfPoints>::new(20)),+ "target's size should win"+ );+ assert_eq!(target.italic, Some(true), "italic should come from base");+ }++ #[test]+ fn merge_run_both_empty_stays_empty() {+ let mut target = RunProperties::default();+ let base = RunProperties::default();+ merge_run_properties(&mut target, &base);++ assert_eq!(target.bold, None);+ assert_eq!(target.italic, None);+ assert_eq!(target.font_size, None);+ }++ #[test]+ fn merge_run_explicit_underline_none_overrides_parent_single() {+ // §17.7.2 + §17.3.2.40: <w:u w:val="none"/> on the child explicitly+ // turns off an underline that the parent style would otherwise+ // inherit. The merge must preserve `Some(UnderlineStyle::None)`+ // rather than overwriting it with the parent's `Single`.+ let mut target = RunProperties {+ underline: Some(UnderlineStyle::None),+ ..Default::default()+ };+ let base = RunProperties {+ underline: Some(UnderlineStyle::Single),+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);+ assert_eq!(+ target.underline,+ Some(UnderlineStyle::None),+ "explicit <w:u w:val=\"none\"/> must override the parent's Single"+ );+ }++ #[test]+ fn merge_run_absent_underline_inherits_from_parent() {+ // Mirror invariant: when the child is silent, parent's underline wins.+ let mut target = RunProperties::default();+ let base = RunProperties {+ underline: Some(UnderlineStyle::Single),+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);+ assert_eq!(target.underline, Some(UnderlineStyle::Single));+ }++ #[test]+ fn merge_run_fonts_merged_field_by_field() {+ let mut target = RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name("Arial"),+ ..Default::default()+ },+ ..Default::default()+ };+ let base = RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name("Times"),+ east_asian: FontSlot::from_name("SimSun"),+ ..Default::default()+ },+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);++ assert_eq!(+ target.fonts.ascii.explicit.as_deref(),+ Some("Arial"),+ "target's ascii should win"+ );+ assert_eq!(+ target.fonts.east_asian.explicit.as_deref(),+ Some("SimSun"),+ "east_asian should come from base"+ );+ }++ #[test]+ fn merge_run_all_fields_covered() {+ // Ensure merge touches every field by setting all in base, none in target.+ let base = RunProperties {+ fonts: FontSet {+ ascii: FontSlot::from_name("F"),+ high_ansi: FontSlot::from_name("F"),+ east_asian: FontSlot::from_name("F"),+ complex_script: FontSlot::from_name("F"),+ },+ font_size: Some(Dimension::<HalfPoints>::new(24)),+ bold: Some(true),+ italic: Some(true),+ underline: Some(UnderlineStyle::Single),+ strike: Some(StrikeStyle::Single),+ color: Some(Color::Rgb(0)),+ highlight: Some(HighlightColor::Yellow),+ shading: Some(Shading {+ fill: Color::Rgb(0),+ pattern: ShadingPattern::Clear,+ color: Color::Rgb(0),+ }),+ vertical_align: Some(VerticalAlign::Superscript),+ spacing: Some(Dimension::<Twips>::new(10)),+ kerning: Some(Dimension::<HalfPoints>::new(2)),+ all_caps: Some(true),+ small_caps: Some(true),+ vanish: Some(true),+ no_proof: Some(true),+ web_hidden: Some(true),+ rtl: Some(true),+ emboss: Some(true),+ imprint: Some(true),+ outline: Some(true),+ shadow: Some(true),+ position: Some(Dimension::<HalfPoints>::new(5)),+ lang: Some(Lang {+ val: Some("en".into()),+ east_asia: None,+ bidi: None,+ }),+ border: Some(Border {+ style: BorderStyle::Single,+ width: Dimension::new(0),+ space: Dimension::new(0),+ color: Color::BLACK,+ }),+ text_scale: Some(TextScale::new(80)),+ };+ let mut target = RunProperties::default();+ merge_run_properties(&mut target, &base);++ assert!(target.bold.is_some());+ assert!(target.italic.is_some());+ assert!(target.underline.is_some());+ assert!(target.strike.is_some());+ assert!(target.color.is_some());+ assert!(target.highlight.is_some());+ assert!(target.shading.is_some());+ assert!(target.vertical_align.is_some());+ assert!(target.spacing.is_some());+ assert!(target.kerning.is_some());+ assert!(target.all_caps.is_some());+ assert!(target.small_caps.is_some());+ assert!(target.vanish.is_some());+ assert!(target.no_proof.is_some());+ assert!(target.web_hidden.is_some());+ assert!(target.rtl.is_some());+ assert!(target.emboss.is_some());+ assert!(target.imprint.is_some());+ assert!(target.outline.is_some());+ assert!(target.shadow.is_some());+ assert!(target.position.is_some());+ assert!(target.lang.is_some());+ assert!(target.border.is_some());+ assert!(target.fonts.ascii.explicit.is_some());+ assert!(target.fonts.high_ansi.explicit.is_some());+ assert!(target.fonts.east_asian.explicit.is_some());+ assert!(target.fonts.complex_script.explicit.is_some());+ assert!(target.font_size.is_some());+ assert_eq!(target.text_scale, Some(TextScale::new(80)));+ }++ #[test]+ fn merge_run_text_scale_child_wins() {+ // §17.7.2: when both parent and child specify text_scale, the child's+ // value wins. Mirrors the standard merge semantics for run properties.+ let mut target = RunProperties {+ text_scale: Some(TextScale::new(120)),+ ..Default::default()+ };+ let base = RunProperties {+ text_scale: Some(TextScale::new(80)),+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);+ assert_eq!(target.text_scale, Some(TextScale::new(120)));+ }++ #[test]+ fn merge_run_text_scale_inherited_from_parent() {+ // No child override → parent's text_scale propagates.+ let mut target = RunProperties::default();+ let base = RunProperties {+ text_scale: Some(TextScale::new(80)),+ ..Default::default()+ };+ merge_run_properties(&mut target, &base);+ assert_eq!(target.text_scale, Some(TextScale::new(80)));+ }++ // ── ParagraphProperties merging ──────────────────────────────────────++ #[test]+ fn merge_para_empty_target_takes_from_base() {+ let mut target = ParagraphProperties::default();+ let base = ParagraphProperties {+ alignment: Some(Alignment::Center),+ keep_next: Some(true),+ ..Default::default()+ };+ merge_paragraph_properties(&mut target, &base);++ assert_eq!(target.alignment, Some(Alignment::Center));+ assert_eq!(target.keep_next, Some(true));+ }++ #[test]+ fn merge_para_target_values_not_overwritten() {+ let mut target = ParagraphProperties {+ alignment: Some(Alignment::End),+ ..Default::default()+ };+ let base = ParagraphProperties {+ alignment: Some(Alignment::Center),+ keep_next: Some(true),+ ..Default::default()+ };+ merge_paragraph_properties(&mut target, &base);++ assert_eq!(target.alignment, Some(Alignment::End), "target should win");+ assert_eq!(target.keep_next, Some(true), "keep_next from base");+ }++ #[test]+ fn merge_tabs_child_adds_to_parent() {+ // §17.3.1.38: child non-Clear tabs are added to inherited parent tabs.+ let mut target = ParagraphProperties {+ tabs: vec![TabStop {+ position: Dimension::<Twips>::new(720),+ alignment: TabAlignment::Left,+ leader: TabLeader::None,+ }],+ ..Default::default()+ };+ let base = ParagraphProperties {+ tabs: vec![TabStop {+ position: Dimension::<Twips>::new(1440),+ alignment: TabAlignment::Right,+ leader: TabLeader::Dot,+ }],+ ..Default::default()+ };+ merge_paragraph_properties(&mut target, &base);++ assert_eq!(target.tabs.len(), 2, "both tabs should be present");+ assert_eq!(+ target.tabs[0].position,+ Dimension::<Twips>::new(720),+ "sorted: left@720 first"+ );+ assert_eq!(+ target.tabs[1].position,+ Dimension::<Twips>::new(1440),+ "sorted: right@1440 second"+ );+ }++ #[test]+ fn merge_tabs_inherited_when_target_empty() {+ let mut target = ParagraphProperties::default();+ let base = ParagraphProperties {+ tabs: vec![TabStop {+ position: Dimension::<Twips>::new(1440),+ alignment: TabAlignment::Right,+ leader: TabLeader::Dot,+ }],+ ..Default::default()+ };+ merge_paragraph_properties(&mut target, &base);++ assert_eq!(target.tabs.len(), 1);+ assert_eq!(target.tabs[0].position, Dimension::<Twips>::new(1440));+ }++ #[test]+ fn merge_tabs_clear_removes_parent_stop() {+ // §17.3.1.38: val="clear" removes an inherited tab at that position.+ let mut target = ParagraphProperties {+ tabs: vec![+ TabStop {+ position: Dimension::<Twips>::new(4536),+ alignment: TabAlignment::Clear,+ leader: TabLeader::None,+ },+ TabStop {+ position: Dimension::<Twips>::new(1701),+ alignment: TabAlignment::Left,+ leader: TabLeader::None,+ },+ ],+ ..Default::default()+ };+ let base = ParagraphProperties {+ tabs: vec![+ TabStop {+ position: Dimension::<Twips>::new(4536),+ alignment: TabAlignment::Center,+ leader: TabLeader::None,+ },+ TabStop {+ position: Dimension::<Twips>::new(9072),+ alignment: TabAlignment::Right,+ leader: TabLeader::None,+ },+ ],+ ..Default::default()+ };+ merge_paragraph_properties(&mut target, &base);++ // center@4536 removed by clear, right@9072 inherited, left@1701 added.+ assert_eq!(target.tabs.len(), 2);+ assert_eq!(target.tabs[0].position, Dimension::<Twips>::new(1701));+ assert_eq!(target.tabs[0].alignment, TabAlignment::Left);+ assert_eq!(target.tabs[1].position, Dimension::<Twips>::new(9072));+ assert_eq!(target.tabs[1].alignment, TabAlignment::Right);+ }++ #[test]+ fn merge_tabs_clear_only_no_additions() {+ // Child only clears a parent tab, adds nothing.+ let mut target = ParagraphProperties {+ tabs: vec![TabStop {+ position: Dimension::<Twips>::new(4536),+ alignment: TabAlignment::Clear,+ leader: TabLeader::None,+ }],+ ..Default::default()+ };+ let base = ParagraphProperties {+ tabs: vec![TabStop {+ position: Dimension::<Twips>::new(4536),+ alignment: TabAlignment::Center,+ leader: TabLeader::None,+ }],+ ..Default::default()+ };+ merge_paragraph_properties(&mut target, &base);++ assert!(+ target.tabs.is_empty(),+ "cleared tab should be gone, nothing added"+ );+ }++ #[test]+ fn merge_para_all_fields_covered() {+ let base = ParagraphProperties {+ alignment: Some(Alignment::Start),+ indentation: Some(Indentation::default()),+ spacing: Some(ParagraphSpacing::default()),+ numbering: Some(NumberingReference {+ num_id: 1,+ level: 0,+ }),+ tabs: vec![TabStop {+ position: Dimension::new(720),+ alignment: TabAlignment::Left,+ leader: TabLeader::None,+ }],+ borders: Some(ParagraphBorders {+ top: None,+ bottom: None,+ left: None,+ right: None,+ between: None,+ }),+ shading: Some(Shading {+ fill: Color::Rgb(0),+ pattern: ShadingPattern::Clear,+ color: Color::Rgb(0),+ }),+ keep_next: Some(true),+ keep_lines: Some(true),+ widow_control: Some(true),+ page_break_before: Some(true),+ suppress_auto_hyphens: Some(true),+ contextual_spacing: Some(true),+ bidi: Some(true),+ word_wrap: Some(true),+ outline_level: Some(OutlineLevel::new(1)),+ text_alignment: Some(TextAlignment::Center),+ cnf_style: Some(CnfStyle::FIRST_ROW),+ frame_properties: None,+ auto_space_de: Some(true),+ auto_space_dn: Some(true),+ };+ let mut target = ParagraphProperties::default();+ merge_paragraph_properties(&mut target, &base);++ assert!(target.alignment.is_some());+ assert!(target.indentation.is_some());+ assert!(target.spacing.is_some());+ assert!(target.numbering.is_some());+ assert!(!target.tabs.is_empty());+ assert!(target.borders.is_some());+ assert!(target.shading.is_some());+ assert!(target.keep_next.is_some());+ assert!(target.keep_lines.is_some());+ assert!(target.widow_control.is_some());+ assert!(target.page_break_before.is_some());+ assert!(target.suppress_auto_hyphens.is_some());+ assert!(target.contextual_spacing.is_some());+ assert!(target.bidi.is_some());+ assert!(target.word_wrap.is_some());+ assert!(target.outline_level.is_some());+ assert!(target.text_alignment.is_some());+ assert!(target.cnf_style.is_some());+ assert!(target.auto_space_de.is_some());+ assert!(target.auto_space_dn.is_some());+ }++ // ── wholeTable table-property overlay (§17.7.6) ──────────────────────++ /// Every field must be listed in `overlay_table_properties`. If a field is+ /// added to `TableProperties` and not to the overlay, a `wholeTable` style+ /// setting it would be silently dropped — this fails instead.+ #[test]+ fn table_properties_overlay_covers_every_field() {+ use crate::model::geometry::EdgeInsets;+ let overlay = TableProperties {+ style_id: Some(StyleId::new("Ignored")),+ alignment: Some(Alignment::Center),+ width: Some(TableMeasure::Auto),+ layout: Some(TableLayout::Fixed),+ indent: Some(TableMeasure::Twips(Dimension::new(120))),+ borders: Some(TableBorders {+ top: None,+ bottom: None,+ left: None,+ right: None,+ inside_h: None,+ inside_v: None,+ }),+ cell_margins: Some(EdgeInsets {+ top: Dimension::new(1),+ right: Dimension::new(2),+ bottom: Dimension::new(3),+ left: Dimension::new(4),+ }),+ cell_spacing: Some(TableMeasure::Twips(Dimension::new(30))),+ look: Some(TableLook {+ first_row: Some(true),+ last_row: None,+ first_column: None,+ last_column: None,+ no_h_band: None,+ no_v_band: None,+ }),+ style_row_band_size: Some(2),+ style_col_band_size: Some(3),+ positioning: Some(TablePositioning {+ left_from_text: None,+ right_from_text: None,+ top_from_text: None,+ bottom_from_text: None,+ vert_anchor: None,+ horz_anchor: None,+ x_align: None,+ y_align: None,+ x: Some(Dimension::new(5)),+ y: None,+ }),+ overlap: Some(TableOverlap::Never),+ };+ let out = overlay_table_properties(None, &overlay);++ assert_eq!(out.alignment, overlay.alignment);+ assert_eq!(out.width, overlay.width);+ assert_eq!(out.layout, overlay.layout);+ assert_eq!(out.indent, overlay.indent);+ assert!(out.borders.is_some(), "borders overlaid"); // no PartialEq on TableBorders+ assert_eq!(out.cell_margins, overlay.cell_margins);+ assert_eq!(out.cell_spacing, overlay.cell_spacing);+ assert!(out.look.is_some(), "look overlaid"); // no PartialEq on TableLook+ assert_eq!(out.style_row_band_size, overlay.style_row_band_size);+ assert_eq!(out.style_col_band_size, overlay.style_col_band_size);+ assert_eq!(out.positioning, overlay.positioning);+ assert_eq!(out.overlap, overlay.overlap);+ // The one deliberate exclusion: a conditional layer must not re-point+ // the style at another style.+ assert_eq!(+ out.style_id, None,+ "style_id must not be overlaid — see overlay_table_properties"+ );+ }++ /// The overlay direction is the opposite of `merge_table_properties`:+ /// what the overlay specifies wins, and what it omits falls through.+ #[test]+ fn table_properties_overlay_wins_but_only_where_specified() {+ use crate::model::geometry::EdgeInsets;+ let base = TableProperties {+ alignment: Some(Alignment::Start),+ cell_margins: Some(EdgeInsets {+ top: Dimension::new(9),+ right: Dimension::new(9),+ bottom: Dimension::new(9),+ left: Dimension::new(9),+ }),+ ..Default::default()+ };+ let overlay = TableProperties {+ alignment: Some(Alignment::Center),+ ..Default::default()+ };+ let out = overlay_table_properties(Some(base.clone()), &overlay);+ assert_eq!(out.alignment, Some(Alignment::Center), "overlay wins");+ assert_eq!(+ out.cell_margins, base.cell_margins,+ "what the overlay omits falls through to the base"+ );+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/sections.rs b/crates/liteparse-docx/src/render/resolve/sections.rsnew file mode 100644index 0000000..653b210--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/sections.rs@@ -0,0 +1,423 @@+//! Section splitting — split body blocks at SectionBreak nodes,+//! resolve header/footer content via Document.headers/footers.++use std::collections::HashMap;++use crate::model::{Block, RelId, SectionHeaderFooterRefs, SectionProperties};++use super::header_footer::HeaderFooterSet;++/// A resolved section with its blocks, properties, and the three+/// `default` / `first` / `even` slots populated for both header and+/// footer per ECMA-376 §17.10.5. Slot selection per page lives in+/// `crate::render::layout::header_footer::select_slot`.+#[derive(Clone, Debug)]+pub struct ResolvedSection {+ pub blocks: Vec<Block>,+ pub properties: SectionProperties,+ pub headers: HeaderFooterSet<Vec<Block>>,+ pub footers: HeaderFooterSet<Vec<Block>>,+}++/// Split a document body into sections at `Block::SectionBreak` boundaries.+/// The trailing section takes `final_section` (the last `w:sectPr` in+/// `w:body`); header/footer content is looked up in the document's loaded+/// `headers`/`footers` parts.+///+/// `body` and `final_section` are taken **by value** — every block ends up in+/// exactly one section, so they are moved across rather than cloned. The two+/// part maps stay borrowed: one header part may be referenced by any number of+/// sections, directly or through the inheritance chain below, so its blocks+/// genuinely have to be copied per use.+///+/// §17.10.5 inheritance is applied **per slot independently**: if a+/// section omits its `first` reference, it inherits the previous+/// section's `first`, regardless of whether `default` is overridden.+/// This mirrors Word's behavior — each header type is its own+/// inheritance chain.+pub fn resolve_sections(+ body: Vec<Block>,+ final_section: SectionProperties,+ header_parts: &HashMap<RelId, Vec<Block>>,+ footer_parts: &HashMap<RelId, Vec<Block>>,+) -> Vec<ResolvedSection> {+ let mut sections = Vec::new();+ let mut current_blocks = Vec::new();+ let mut prev_headers: HeaderFooterSet<Vec<Block>> = HeaderFooterSet::default();+ let mut prev_footers: HeaderFooterSet<Vec<Block>> = HeaderFooterSet::default();++ for block in body {+ match block {+ Block::SectionBreak(props) => {+ let headers = resolve_set(&props.header_refs, header_parts, &prev_headers);+ let footers = resolve_set(&props.footer_refs, footer_parts, &prev_footers);+ prev_headers = headers.clone();+ prev_footers = footers.clone();+ sections.push(ResolvedSection {+ blocks: std::mem::take(&mut current_blocks),+ headers,+ footers,+ properties: *props,+ });+ }+ other => {+ current_blocks.push(other);+ }+ }+ }++ let headers = resolve_set(&final_section.header_refs, header_parts, &prev_headers);+ let footers = resolve_set(&final_section.footer_refs, footer_parts, &prev_footers);+ sections.push(ResolvedSection {+ blocks: current_blocks,+ headers,+ footers,+ properties: final_section,+ });++ sections+}++/// Resolve all three slots of a section's header (or footer) refs:+/// look each up in the document's loaded parts, falling back to the+/// previous section's same slot when this section omits the reference.+fn resolve_set(+ refs: &SectionHeaderFooterRefs,+ parts: &HashMap<RelId, Vec<Block>>,+ prev: &HeaderFooterSet<Vec<Block>>,+) -> HeaderFooterSet<Vec<Block>> {+ let resolve_one = |id: Option<&RelId>, fallback: &Option<Vec<Block>>| -> Option<Vec<Block>> {+ id.and_then(|i| parts.get(i))+ .cloned()+ .or_else(|| fallback.clone())+ };+ HeaderFooterSet {+ default: resolve_one(refs.default.as_ref(), &prev.default),+ first: resolve_one(refs.first.as_ref(), &prev.first),+ even: resolve_one(refs.even.as_ref(), &prev.even),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::*;+ use std::collections::HashMap;++ fn empty_doc() -> Document {+ Document {+ settings: DocumentSettings::default(),+ theme: None,+ styles: StyleSheet::default(),+ numbering: NumberingDefinitions::default(),+ body: vec![],+ final_section: SectionProperties::default(),+ headers: HashMap::new(),+ footers: HashMap::new(),+ footnotes: HashMap::new(),+ endnotes: HashMap::new(),+ media: HashMap::new(),+ embedded_fonts: vec![],+ }+ }++ fn para(text: &str) -> Block {+ Block::Paragraph(Box::new(Paragraph {+ 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(text.to_string())],+ rsids: RevisionIds::default(),+ }))],+ rsids: ParagraphRevisionIds::default(),+ }))+ }++ /// How `resolve` calls this: the body and final section move out of the+ /// document, the two part maps stay behind it.+ fn sections_of(doc: Document) -> Vec<ResolvedSection> {+ resolve_sections(doc.body, doc.final_section, &doc.headers, &doc.footers)+ }++ #[test]+ fn empty_body_produces_one_section() {+ let doc = empty_doc();+ let sections = sections_of(doc);+ assert_eq!(sections.len(), 1);+ assert!(sections[0].blocks.is_empty());+ }++ #[test]+ fn no_section_breaks_all_blocks_in_final_section() {+ let mut doc = empty_doc();+ doc.body = vec![para("a"), para("b"), para("c")];+ let sections = sections_of(doc);++ assert_eq!(sections.len(), 1);+ assert_eq!(sections[0].blocks.len(), 3);+ }++ #[test]+ fn section_break_splits_into_two_sections() {+ let mut doc = empty_doc();+ let break_props = SectionProperties {+ section_type: Some(SectionType::NextPage),+ ..Default::default()+ };+ doc.body = vec![+ para("before"),+ Block::SectionBreak(Box::new(break_props)),+ para("after"),+ ];++ let sections = sections_of(doc);+ assert_eq!(sections.len(), 2);+ assert_eq!(sections[0].blocks.len(), 1, "first section has 'before'");+ assert_eq!(sections[1].blocks.len(), 1, "second section has 'after'");+ assert_eq!(+ sections[0].properties.section_type,+ Some(SectionType::NextPage)+ );+ }++ #[test]+ fn header_resolved_from_document_headers() {+ let mut doc = empty_doc();+ let header_id = RelId::new("rId1");+ doc.headers+ .insert(header_id.clone(), vec![para("header text")]);+ doc.final_section = SectionProperties {+ header_refs: SectionHeaderFooterRefs {+ default: Some(header_id),+ ..Default::default()+ },+ ..Default::default()+ };+ doc.body = vec![para("body")];++ let sections = sections_of(doc);+ assert_eq!(sections.len(), 1);+ assert!(sections[0].headers.default.is_some());+ assert_eq!(sections[0].headers.default.as_ref().unwrap().len(), 1);+ }++ #[test]+ fn footer_resolved_from_document_footers() {+ let mut doc = empty_doc();+ let footer_id = RelId::new("rId2");+ doc.footers+ .insert(footer_id.clone(), vec![para("footer text")]);+ doc.final_section = SectionProperties {+ footer_refs: SectionHeaderFooterRefs {+ default: Some(footer_id),+ ..Default::default()+ },+ ..Default::default()+ };+ doc.body = vec![para("body")];++ let sections = sections_of(doc);+ assert!(sections[0].footers.default.is_some());+ }++ #[test]+ fn missing_header_ref_produces_none() {+ let mut doc = empty_doc();+ doc.final_section = SectionProperties {+ header_refs: SectionHeaderFooterRefs {+ default: Some(RelId::new("nonexistent")),+ ..Default::default()+ },+ ..Default::default()+ };+ doc.body = vec![para("body")];++ let sections = sections_of(doc);+ assert!(sections[0].headers.default.is_none());+ }++ /// Helper: produce a single-paragraph block list to use as+ /// distinct header/footer content per ref.+ fn block(text: &str) -> Vec<Block> {+ vec![para(text)]+ }++ #[test]+ fn all_three_slots_resolved_when_all_refs_present() {+ let mut doc = empty_doc();+ let (rd, rf, re) = (RelId::new("rD"), RelId::new("rF"), RelId::new("rE"));+ doc.headers.insert(rd.clone(), block("default"));+ doc.headers.insert(rf.clone(), block("first"));+ doc.headers.insert(re.clone(), block("even"));+ doc.final_section = SectionProperties {+ header_refs: SectionHeaderFooterRefs {+ default: Some(rd),+ first: Some(rf),+ even: Some(re),+ },+ ..Default::default()+ };++ let s = §ions_of(doc)[0];+ assert!(s.headers.default.is_some());+ assert!(s.headers.first.is_some());+ assert!(s.headers.even.is_some());+ }++ #[test]+ fn missing_first_and_even_slots_remain_none_with_no_prior_section() {+ // §17.10.5: a slot that is neither set on this section nor+ // inheritable from a previous one stays `None`.+ let mut doc = empty_doc();+ let rd = RelId::new("rD");+ doc.headers.insert(rd.clone(), block("default"));+ doc.final_section = SectionProperties {+ header_refs: SectionHeaderFooterRefs {+ default: Some(rd),+ ..Default::default()+ },+ ..Default::default()+ };++ let s = §ions_of(doc)[0];+ assert!(s.headers.default.is_some());+ assert!(s.headers.first.is_none());+ assert!(s.headers.even.is_none());+ }++ #[test]+ fn first_slot_inherits_independently_when_only_default_is_overridden() {+ // Section 1: full set. Section 2: overrides only `default` —+ // its `first` and `even` must inherit Section 1's values.+ let mut doc = empty_doc();+ let (s1d, s1f, s1e, s2d) = (+ RelId::new("s1D"),+ RelId::new("s1F"),+ RelId::new("s1E"),+ RelId::new("s2D"),+ );+ doc.headers.insert(s1d.clone(), block("S1 default"));+ doc.headers.insert(s1f.clone(), block("S1 first"));+ doc.headers.insert(s1e.clone(), block("S1 even"));+ doc.headers.insert(s2d.clone(), block("S2 default"));++ let s1_break = SectionProperties {+ section_type: Some(SectionType::NextPage),+ header_refs: SectionHeaderFooterRefs {+ default: Some(s1d),+ first: Some(s1f.clone()),+ even: Some(s1e.clone()),+ },+ ..Default::default()+ };+ doc.final_section = SectionProperties {+ header_refs: SectionHeaderFooterRefs {+ default: Some(s2d),+ first: None,+ even: None,+ },+ ..Default::default()+ };+ doc.body = vec![+ para("section 1 body"),+ Block::SectionBreak(Box::new(s1_break)),+ para("section 2 body"),+ ];++ let sections = sections_of(doc);+ let s2 = §ions[1];+ assert_eq!(+ s2.headers.default.as_ref().map(|b| b.len()),+ Some(1),+ "section 2 default is its own override",+ );+ assert!(+ s2.headers.first.is_some(),+ "section 2 must inherit `first` from section 1",+ );+ assert!(+ s2.headers.even.is_some(),+ "section 2 must inherit `even` from section 1",+ );+ }++ #[test]+ fn slots_inherit_independently_across_three_sections() {+ // Section 1 sets `even` only. Section 2 sets `first` only.+ // Section 3 sets nothing — it should inherit `first` from S2,+ // `even` from S1, and have no `default`.+ let mut doc = empty_doc();+ let (s1e, s2f) = (RelId::new("s1E"), RelId::new("s2F"));+ doc.headers.insert(s1e.clone(), block("S1 even"));+ doc.headers.insert(s2f.clone(), block("S2 first"));++ let s1_break = SectionProperties {+ section_type: Some(SectionType::NextPage),+ header_refs: SectionHeaderFooterRefs {+ default: None,+ first: None,+ even: Some(s1e),+ },+ ..Default::default()+ };+ let s2_break = SectionProperties {+ section_type: Some(SectionType::NextPage),+ header_refs: SectionHeaderFooterRefs {+ default: None,+ first: Some(s2f),+ even: None,+ },+ ..Default::default()+ };+ doc.final_section = SectionProperties::default();+ doc.body = vec![+ para("S1"),+ Block::SectionBreak(Box::new(s1_break)),+ para("S2"),+ Block::SectionBreak(Box::new(s2_break)),+ para("S3"),+ ];++ let sections = sections_of(doc);+ assert_eq!(sections.len(), 3);+ let s3 = §ions[2];+ assert!(s3.headers.default.is_none());+ assert!(s3.headers.first.is_some(), "S3 inherits `first` from S2",);+ assert!(+ s3.headers.even.is_some(),+ "S3 inherits `even` transitively from S1 (S2 didn't override it)",+ );+ }++ #[test]+ fn footer_slots_inherit_with_the_same_per_slot_rule() {+ let mut doc = empty_doc();+ let (s1d, s1f) = (RelId::new("s1D"), RelId::new("s1F"));+ doc.footers.insert(s1d.clone(), block("default"));+ doc.footers.insert(s1f.clone(), block("first"));++ let s1_break = SectionProperties {+ section_type: Some(SectionType::NextPage),+ footer_refs: SectionHeaderFooterRefs {+ default: Some(s1d),+ first: Some(s1f),+ even: None,+ },+ ..Default::default()+ };+ doc.final_section = SectionProperties::default();+ doc.body = vec![+ para("S1"),+ Block::SectionBreak(Box::new(s1_break)),+ para("S2"),+ ];++ let s2 = §ions_of(doc)[1];+ assert!(s2.footers.default.is_some(), "S2 inherits default footer");+ assert!(s2.footers.first.is_some(), "S2 inherits first footer");+ assert!(s2.footers.even.is_none());+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_geometry/custom.rs b/crates/liteparse-docx/src/render/resolve/shape_geometry/custom.rsnew file mode 100644index 0000000..7c9353c--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_geometry/custom.rs@@ -0,0 +1,331 @@+//! Evaluator for `<a:custGeom>` (§20.1.9.8).+//!+//! Each `<a:path>` declares its own coordinate space via `w`/`h`. The+//! evaluator:+//!+//! 1. Builds a `GuideContext` for the path using the path's `w`/`h` (in EMU,+//! cast to f64). Shape-level and path-level guides are both evaluated+//! against this context per §20.1.9.8.+//! 2. Evaluates `av_list` then `gd_list` in document order.+//! 3. Walks the path's `PathCommand` list, resolving each `AdjPoint` /+//! `AdjCoord` / `AdjAngle` to a concrete path-local f64 via+//! [`super::guides::resolve_adj_coord`].+//! 4. Scales the result from path-local units into the shape's `extent`+//! (Pt), producing [`PathVerb`]s.+//!+//! Angles are preserved in 60000ths of a degree (§20.1.10.3) — we do not+//! scale them by the size transform; Skia picks them up in OOXML's native+//! convention via a painter-side conversion.++use crate::model::dimension::Dimension;+use crate::model::{AdjAngle, AdjCoord, AdjPoint, CustomGeometry, PathCommand, PathDef};+use crate::render::dimension::Pt;+use crate::render::geometry::{PtOffset, PtRect, PtSize};++use super::guides::{GuideContext, evaluate_guides, resolve_adj_angle, resolve_adj_coord};+use super::{PathVerb, ShapePath, SubPath};++pub fn build_custom(geom: &CustomGeometry, extent: PtSize) -> Option<ShapePath> {+ if geom.paths.is_empty() {+ return None;+ }+ let paths: Vec<SubPath> = geom+ .paths+ .iter()+ .filter_map(|p| build_subpath(geom, p, extent))+ .collect();++ if paths.is_empty() {+ return None;+ }++ // `rect` is resolved in the first path's coordinate space. When multiple+ // paths exist, the spec (§20.1.9.22) does not name a preferred scope —+ // we use the first as a convention.+ let text_rect = geom+ .rect+ .as_ref()+ .and_then(|r| resolve_text_rect(geom, &geom.paths[0], r, extent));++ Some(ShapePath { paths, text_rect })+}++fn build_subpath(geom: &CustomGeometry, path: &PathDef, extent: PtSize) -> Option<SubPath> {+ let path_w = path.w.raw() as f64;+ let path_h = path.h.raw() as f64;+ if path_w <= 0.0 || path_h <= 0.0 {+ return None;+ }+ let ctx = GuideContext::new(path_w, path_h);++ // Evaluate shape-level guides first (av_list + gd_list), then we're+ // ready to resolve `AdjCoord::Guide` references within the commands.+ let mut values = evaluate_guides(&geom.av_list, ctx);+ let computed = evaluate_guides(&geom.gd_list, ctx);+ values.extend(computed);++ // Scale factors from path-local units → shape-local Pt.+ let sx = extent.width.raw() / path_w as f32;+ let sy = extent.height.raw() / path_h as f32;++ let mut verbs = Vec::with_capacity(path.commands.len());+ for cmd in &path.commands {+ match cmd {+ PathCommand::MoveTo(p) => {+ verbs.push(PathVerb::MoveTo(point_to_pt(p, &values, ctx, sx, sy)))+ }+ PathCommand::LineTo(p) => {+ verbs.push(PathVerb::LineTo(point_to_pt(p, &values, ctx, sx, sy)))+ }+ PathCommand::QuadBezTo(c, p) => verbs.push(PathVerb::QuadTo(+ point_to_pt(c, &values, ctx, sx, sy),+ point_to_pt(p, &values, ctx, sx, sy),+ )),+ PathCommand::CubicBezTo(c1, c2, p) => verbs.push(PathVerb::CubicTo(+ point_to_pt(c1, &values, ctx, sx, sy),+ point_to_pt(c2, &values, ctx, sx, sy),+ point_to_pt(p, &values, ctx, sx, sy),+ )),+ PathCommand::ArcTo {+ wr,+ hr,+ start_angle,+ swing_angle,+ } => {+ let wr_pt = Pt::new((coord_val(wr, &values, ctx) as f32) * sx);+ let hr_pt = Pt::new((coord_val(hr, &values, ctx) as f32) * sy);+ verbs.push(PathVerb::ArcTo {+ radii: PtSize::new(wr_pt, hr_pt),+ start_angle: angle(start_angle, &values, ctx),+ swing_angle: angle(swing_angle, &values, ctx),+ });+ }+ PathCommand::Close => verbs.push(PathVerb::Close),+ }+ }++ Some(SubPath {+ verbs,+ fill_mode: path.fill,+ stroked: path.stroke,+ })+}++fn resolve_text_rect(+ geom: &CustomGeometry,+ path: &PathDef,+ rect: &crate::model::TextRect,+ extent: PtSize,+) -> Option<PtRect> {+ let path_w = path.w.raw() as f64;+ let path_h = path.h.raw() as f64;+ if path_w <= 0.0 || path_h <= 0.0 {+ return None;+ }+ let ctx = GuideContext::new(path_w, path_h);+ let mut values = evaluate_guides(&geom.av_list, ctx);+ values.extend(evaluate_guides(&geom.gd_list, ctx));++ let sx = extent.width.raw() / path_w as f32;+ let sy = extent.height.raw() / path_h as f32;++ let l = (coord_val(&rect.left, &values, ctx) as f32) * sx;+ let t = (coord_val(&rect.top, &values, ctx) as f32) * sy;+ let r = (coord_val(&rect.right, &values, ctx) as f32) * sx;+ let b = (coord_val(&rect.bottom, &values, ctx) as f32) * sy;+ Some(PtRect::from_xywh(+ Pt::new(l),+ Pt::new(t),+ Pt::new((r - l).max(0.0)),+ Pt::new((b - t).max(0.0)),+ ))+}++fn point_to_pt(+ p: &AdjPoint,+ values: &super::guides::GuideValues,+ ctx: GuideContext,+ sx: f32,+ sy: f32,+) -> PtOffset {+ let x = (resolve_adj_coord(&p.x, values, ctx) as f32) * sx;+ let y = (resolve_adj_coord(&p.y, values, ctx) as f32) * sy;+ PtOffset::new(Pt::new(x), Pt::new(y))+}++fn coord_val(c: &AdjCoord, values: &super::guides::GuideValues, ctx: GuideContext) -> f64 {+ resolve_adj_coord(c, values, ctx)+}++fn angle(+ a: &AdjAngle,+ values: &super::guides::GuideValues,+ ctx: GuideContext,+) -> Dimension<crate::model::dimension::SixtieThousandthDeg> {+ Dimension::new(resolve_adj_angle(a, values, ctx) as i64)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::{GeomGuide, PathDef, PathFillMode};++ fn lit_point(x: i64, y: i64) -> AdjPoint {+ AdjPoint {+ x: AdjCoord::Lit(x),+ y: AdjCoord::Lit(y),+ }+ }++ fn emu(v: i64) -> Dimension<crate::model::dimension::Emu> {+ Dimension::new(v)+ }++ fn rect_path() -> PathDef {+ PathDef {+ w: emu(100),+ h: emu(50),+ fill: PathFillMode::Norm,+ stroke: true,+ extrusion_ok: true,+ commands: vec![+ PathCommand::MoveTo(lit_point(0, 0)),+ PathCommand::LineTo(lit_point(100, 0)),+ PathCommand::LineTo(lit_point(100, 50)),+ PathCommand::LineTo(lit_point(0, 50)),+ PathCommand::Close,+ ],+ }+ }++ #[test]+ fn scales_path_coords_to_shape_extent() {+ let geom = CustomGeometry {+ paths: vec![rect_path()],+ ..Default::default()+ };+ let extent = PtSize::new(Pt::new(200.0), Pt::new(100.0));+ let s = build_custom(&geom, extent).unwrap();+ let sub = &s.paths[0];+ // Second verb is LineTo(100, 0) in path-local, should scale to (200, 0).+ let PathVerb::LineTo(p) = sub.verbs[1] else {+ panic!()+ };+ assert_eq!(p.x, Pt::new(200.0));+ assert_eq!(p.y, Pt::new(0.0));+ // Fourth verb is LineTo(0, 50) in path-local, should scale to (0, 100).+ let PathVerb::LineTo(p) = sub.verbs[3] else {+ panic!()+ };+ assert_eq!(p.x, Pt::new(0.0));+ assert_eq!(p.y, Pt::new(100.0));+ }++ #[test]+ fn empty_paths_return_none() {+ let geom = CustomGeometry::default();+ assert!(build_custom(&geom, PtSize::new(Pt::new(10.0), Pt::new(10.0))).is_none());+ }++ #[test]+ fn zero_width_path_is_skipped() {+ let mut path = rect_path();+ path.w = emu(0);+ let geom = CustomGeometry {+ paths: vec![path],+ ..Default::default()+ };+ assert!(build_custom(&geom, PtSize::new(Pt::new(10.0), Pt::new(10.0))).is_none());+ }++ #[test]+ fn guide_reference_resolved_via_gd_list() {+ let geom = CustomGeometry {+ gd_list: vec![GeomGuide {+ name: "mid".into(),+ formula: "*/ w 1 2".into(),+ }],+ paths: vec![PathDef {+ w: emu(100),+ h: emu(50),+ fill: PathFillMode::Norm,+ stroke: true,+ extrusion_ok: true,+ commands: vec![+ PathCommand::MoveTo(AdjPoint {+ x: AdjCoord::Guide("mid".into()),+ y: AdjCoord::Lit(0),+ }),+ PathCommand::LineTo(AdjPoint {+ x: AdjCoord::Guide("mid".into()),+ y: AdjCoord::Guide("h".into()),+ }),+ ],+ }],+ ..Default::default()+ };+ let extent = PtSize::new(Pt::new(200.0), Pt::new(100.0));+ let s = build_custom(&geom, extent).unwrap();+ let PathVerb::MoveTo(p) = s.paths[0].verbs[0] else {+ panic!()+ };+ // mid = w/2 = 50 path-local → scale factor 2 → 100 Pt.+ assert_eq!(p.x, Pt::new(100.0));+ let PathVerb::LineTo(p) = s.paths[0].verbs[1] else {+ panic!()+ };+ // h = 50 path-local → scale factor 2 → 100 Pt.+ assert_eq!(p.y, Pt::new(100.0));+ }++ #[test]+ fn arc_to_preserves_angle_in_60k_deg() {+ let geom = CustomGeometry {+ paths: vec![PathDef {+ w: emu(100),+ h: emu(100),+ fill: PathFillMode::Norm,+ stroke: true,+ extrusion_ok: true,+ commands: vec![PathCommand::ArcTo {+ wr: AdjCoord::Lit(25),+ hr: AdjCoord::Lit(25),+ start_angle: AdjCoord::Lit(0),+ swing_angle: AdjCoord::Lit(5_400_000),+ }],+ }],+ ..Default::default()+ };+ let extent = PtSize::new(Pt::new(100.0), Pt::new(100.0));+ let s = build_custom(&geom, extent).unwrap();+ let PathVerb::ArcTo {+ start_angle,+ swing_angle,+ ..+ } = s.paths[0].verbs[0]+ else {+ panic!()+ };+ assert_eq!(start_angle.raw(), 0);+ assert_eq!(swing_angle.raw(), 5_400_000);+ }++ #[test]+ fn text_rect_resolves_and_scales() {+ let geom = CustomGeometry {+ rect: Some(crate::model::TextRect {+ left: AdjCoord::Lit(0),+ top: AdjCoord::Lit(0),+ right: AdjCoord::Lit(100),+ bottom: AdjCoord::Lit(50),+ }),+ paths: vec![rect_path()],+ ..Default::default()+ };+ let s = build_custom(&geom, PtSize::new(Pt::new(200.0), Pt::new(100.0))).unwrap();+ let tr = s.text_rect.unwrap();+ assert_eq!(tr.origin.x, Pt::ZERO);+ assert_eq!(tr.size.width, Pt::new(200.0));+ assert_eq!(tr.size.height, Pt::new(100.0));+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_geometry/guides.rs b/crates/liteparse-docx/src/render/resolve/shape_geometry/guides.rsnew file mode 100644index 0000000..0f2cea7--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_geometry/guides.rs@@ -0,0 +1,413 @@+//! Geometry guide expression evaluator (§20.1.9.11 CT_GeomGuide).+//!+//! OOXML guide formulas are postfix-like prefix expressions. Each formula is+//! a single operator followed by one to three operand tokens, where each+//! operand is either a decimal literal, a guide-name reference, or one of a+//! small set of spec-defined named constants.+//!+//! The spec enumerates 17 operators (§20.1.9.11 ST_GeomGuideFormula). All+//! are implemented here. Resolution is pure: given a `GuideContext` and a+//! slice of `GeomGuide`s in document order, `evaluate_guides` returns a+//! `GuideValues` map keyed by guide name.+//!+//! Units: formula operands and results are f64. Angles are expressed in+//! 60000ths of a degree (§20.1.10.3 ST_PositiveFixedAngle convention);+//! dimensions are in the path's local EMU coordinate space.++use std::collections::HashMap;+use std::f64::consts::PI;++use crate::model::{AdjAngle, AdjCoord, GeomGuide};++/// The coordinate context a guide expression is evaluated against.+///+/// Fields correspond to the spec's named constants:+/// * `w`, `h` — path extent.+/// * `ss` — shortest side (`min(w, h)`).+/// * `ls` — longest side (`max(w, h)`).+/// * `hc`, `vc` — horizontal/vertical center.+/// * `t`, `b`, `l`, `r` — top/bottom/left/right edges.+/// * `wd2`, `wd4`, `wd8`, `wd16`, `wd32` — width divisions.+/// * `hd2`, `hd4`, `hd8`, `hd16`, `hd32` — height divisions.+/// * `cd2`, `cd4`, `cd8` — 360° / N angle divisions (in 60000ths of a deg).+/// * `3cd4`, `3cd8`, `5cd8`, `7cd8` — compound angle constants.+#[derive(Clone, Copy, Debug)]+pub struct GuideContext {+ pub w: f64,+ pub h: f64,+}++impl GuideContext {+ pub fn new(w: f64, h: f64) -> Self {+ Self { w, h }+ }+}++/// A name → evaluated value map produced by [`evaluate_guides`].+pub type GuideValues = HashMap<String, f64>;++/// Evaluate a list of guides in document order. Later guides may reference+/// earlier guide names via [`AdjCoord::Guide`]. Returns a map of resolved+/// values; callers pass this to [`resolve_adj_coord`] / [`resolve_adj_angle`]+/// when reading path commands.+///+/// Unknown guide references resolve to 0.0 (spec says behaviour is undefined+/// for forward references; we default to 0 so we never panic on malformed+/// but structurally-valid input).+pub fn evaluate_guides(guides: &[GeomGuide], ctx: GuideContext) -> GuideValues {+ let mut values = GuideValues::new();+ for guide in guides {+ if let Some(v) = evaluate_formula(&guide.formula, &values, ctx) {+ values.insert(guide.name.clone(), v);+ }+ }+ values+}++/// Resolve an `AdjCoord` (literal or guide reference) to a concrete value.+pub fn resolve_adj_coord(c: &AdjCoord, values: &GuideValues, ctx: GuideContext) -> f64 {+ match c {+ AdjCoord::Lit(n) => *n as f64,+ AdjCoord::Guide(name) => values+ .get(name.as_str())+ .copied()+ .or_else(|| named_constant(name, ctx))+ .unwrap_or(0.0),+ }+}++/// `AdjAngle` is `AdjCoord` per §20.1.10.4 — same resolution.+pub fn resolve_adj_angle(a: &AdjAngle, values: &GuideValues, ctx: GuideContext) -> f64 {+ resolve_adj_coord(a, values, ctx)+}++/// Parse + evaluate a single formula string.+///+/// Returns `None` if the formula cannot be parsed (malformed) or if an+/// operator's arity is wrong. The caller leaves the guide unassigned, which+/// surfaces as 0.0 downstream.+fn evaluate_formula(formula: &str, values: &GuideValues, ctx: GuideContext) -> Option<f64> {+ let mut tokens = formula.split_whitespace();+ let op = tokens.next()?;+ let a = tokens.next();+ let b = tokens.next();+ let c = tokens.next();+ let v = |t: &str| -> f64 { resolve_token(t, values, ctx) };++ Some(match op {+ // §20.1.9.11 three-operand operators+ "*/" => {+ let (a, b, c) = (v(a?), v(b?), v(c?));+ if c == 0.0 { 0.0 } else { (a * b) / c }+ }+ "+-" => v(a?) + v(b?) - v(c?),+ "+/" => {+ let (a, b, c) = (v(a?), v(b?), v(c?));+ if c == 0.0 { 0.0 } else { (a + b) / c }+ }+ "?:" => {+ // If a > 0 then b else c.+ if v(a?) > 0.0 { v(b?) } else { v(c?) }+ }+ "cat2" => {+ // val1 * cos(arctan2(val3, val2))+ let (a, b, c) = (v(a?), v(b?), v(c?));+ a * (c.atan2(b)).cos()+ }+ "mod" => {+ // sqrt(val1² + val2² + val3²) — despite the name, this is+ // vector magnitude per the spec.+ let (a, b, c) = (v(a?), v(b?), v(c?));+ (a * a + b * b + c * c).sqrt()+ }+ "pin" => {+ // clamp(val2, val1, val3): lower=val1, value=val2, upper=val3.+ let (a, b, c) = (v(a?), v(b?), v(c?));+ b.max(a).min(c)+ }+ "sat2" => {+ // val1 * sin(arctan2(val3, val2))+ let (a, b, c) = (v(a?), v(b?), v(c?));+ a * (c.atan2(b)).sin()+ }++ // Two-operand operators+ "at2" => {+ // arctan2(val2, val1), result in 60000ths of a degree.+ let (a, b) = (v(a?), v(b?));+ b.atan2(a) * 180.0 / PI * 60_000.0+ }+ "cos" => {+ // val1 * cos(val2); val2 in 60000ths of a degree.+ let (a, b) = (v(a?), v(b?));+ a * (b * PI / 180.0 / 60_000.0).cos()+ }+ "max" => v(a?).max(v(b?)),+ "min" => v(a?).min(v(b?)),+ "sin" => {+ let (a, b) = (v(a?), v(b?));+ a * (b * PI / 180.0 / 60_000.0).sin()+ }+ "tan" => {+ let (a, b) = (v(a?), v(b?));+ a * (b * PI / 180.0 / 60_000.0).tan()+ }++ // One-operand operators+ "abs" => v(a?).abs(),+ "sqrt" => v(a?).sqrt(),+ "val" => v(a?),++ _ => return None,+ })+}++fn resolve_token(token: &str, values: &GuideValues, ctx: GuideContext) -> f64 {+ if let Ok(n) = token.parse::<i64>() {+ return n as f64;+ }+ if let Ok(n) = token.parse::<f64>() {+ return n;+ }+ if let Some(v) = named_constant(token, ctx) {+ return v;+ }+ values.get(token).copied().unwrap_or(0.0)+}++/// §20.1.9.11 spec-named constants available inside any formula.+fn named_constant(name: &str, ctx: GuideContext) -> Option<f64> {+ Some(match name {+ "w" => ctx.w,+ "h" => ctx.h,+ "ss" => ctx.w.min(ctx.h),+ "ls" => ctx.w.max(ctx.h),+ "hc" => ctx.w / 2.0,+ "vc" => ctx.h / 2.0,+ "t" | "l" => 0.0,+ "b" => ctx.h,+ "r" => ctx.w,+ "wd2" => ctx.w / 2.0,+ "wd4" => ctx.w / 4.0,+ "wd8" => ctx.w / 8.0,+ "wd16" => ctx.w / 16.0,+ "wd32" => ctx.w / 32.0,+ "hd2" => ctx.h / 2.0,+ "hd4" => ctx.h / 4.0,+ "hd8" => ctx.h / 8.0,+ "hd16" => ctx.h / 16.0,+ "hd32" => ctx.h / 32.0,+ // Angle constants — 360° expressed in 60000ths of a degree.+ "cd2" => 360.0 / 2.0 * 60_000.0,+ "cd4" => 360.0 / 4.0 * 60_000.0,+ "cd8" => 360.0 / 8.0 * 60_000.0,+ "3cd4" => 3.0 * 360.0 / 4.0 * 60_000.0,+ "3cd8" => 3.0 * 360.0 / 8.0 * 60_000.0,+ "5cd8" => 5.0 * 360.0 / 8.0 * 60_000.0,+ "7cd8" => 7.0 * 360.0 / 8.0 * 60_000.0,+ _ => return None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ctx() -> GuideContext {+ GuideContext::new(100.0, 50.0)+ }++ fn g(name: &str, formula: &str) -> GeomGuide {+ GeomGuide {+ name: name.into(),+ formula: formula.into(),+ }+ }++ #[test]+ fn val_literal() {+ let vs = evaluate_guides(&[g("a", "val 42")], ctx());+ assert_eq!(vs["a"], 42.0);+ }++ #[test]+ fn val_named_constant_w() {+ let vs = evaluate_guides(&[g("x", "val w")], ctx());+ assert_eq!(vs["x"], 100.0);+ }++ #[test]+ fn val_named_constant_hc_vc() {+ let vs = evaluate_guides(&[g("cx", "val hc"), g("cy", "val vc")], ctx());+ assert_eq!(vs["cx"], 50.0);+ assert_eq!(vs["cy"], 25.0);+ }++ #[test]+ fn val_ss_ls() {+ let vs = evaluate_guides(&[g("s", "val ss"), g("l", "val ls")], ctx());+ assert_eq!(vs["s"], 50.0);+ assert_eq!(vs["l"], 100.0);+ }++ #[test]+ fn muldiv() {+ // (10 * 3) / 2 = 15+ let vs = evaluate_guides(&[g("r", "*/ 10 3 2")], ctx());+ assert_eq!(vs["r"], 15.0);+ }++ #[test]+ fn muldiv_by_zero_returns_zero() {+ let vs = evaluate_guides(&[g("r", "*/ 10 3 0")], ctx());+ assert_eq!(vs["r"], 0.0);+ }++ #[test]+ fn plus_minus() {+ // 10 + 5 - 3 = 12+ let vs = evaluate_guides(&[g("r", "+- 10 5 3")], ctx());+ assert_eq!(vs["r"], 12.0);+ }++ #[test]+ fn plus_div() {+ // (10 + 6) / 4 = 4+ let vs = evaluate_guides(&[g("r", "+/ 10 6 4")], ctx());+ assert_eq!(vs["r"], 4.0);+ }++ #[test]+ fn ternary_selects_by_sign() {+ // if 1 > 0 then 42 else 99+ let vs = evaluate_guides(&[g("a", "?: 1 42 99"), g("b", "?: -1 42 99")], ctx());+ assert_eq!(vs["a"], 42.0);+ assert_eq!(vs["b"], 99.0);+ }++ #[test]+ fn pin_clamp() {+ // clamp(5, 0, 10) = 5; clamp(-1, 0, 10) = 0; clamp(20, 0, 10) = 10.+ let vs = evaluate_guides(+ &[+ g("a", "pin 0 5 10"),+ g("b", "pin 0 -1 10"),+ g("c", "pin 0 20 10"),+ ],+ ctx(),+ );+ assert_eq!(vs["a"], 5.0);+ assert_eq!(vs["b"], 0.0);+ assert_eq!(vs["c"], 10.0);+ }++ #[test]+ fn min_max() {+ let vs = evaluate_guides(&[g("mn", "min 3 7"), g("mx", "max 3 7")], ctx());+ assert_eq!(vs["mn"], 3.0);+ assert_eq!(vs["mx"], 7.0);+ }++ #[test]+ fn abs_and_sqrt() {+ let vs = evaluate_guides(&[g("a", "abs -9"), g("s", "sqrt 16")], ctx());+ assert_eq!(vs["a"], 9.0);+ assert_eq!(vs["s"], 4.0);+ }++ #[test]+ fn mod_is_vector_magnitude() {+ // sqrt(3² + 4² + 12²) = sqrt(169) = 13+ let vs = evaluate_guides(&[g("m", "mod 3 4 12")], ctx());+ assert!((vs["m"] - 13.0).abs() < 1e-9);+ }++ #[test]+ fn trig_cos_sin_zero_angle() {+ // cos(0) = 1, sin(0) = 0. val1 = 100 scales.+ let vs = evaluate_guides(&[g("c", "cos 100 0"), g("s", "sin 100 0")], ctx());+ assert!((vs["c"] - 100.0).abs() < 1e-9);+ assert!(vs["s"].abs() < 1e-9);+ }++ #[test]+ fn trig_cos_90deg() {+ // cos(90°) ≈ 0, sin(90°) ≈ 1. 90° = 5_400_000 in 60000ths of a deg.+ let vs = evaluate_guides(+ &[g("c", "cos 100 5400000"), g("s", "sin 100 5400000")],+ ctx(),+ );+ assert!(vs["c"].abs() < 1e-6);+ assert!((vs["s"] - 100.0).abs() < 1e-6);+ }++ #[test]+ fn at2_returns_angle_in_60k_deg() {+ // arctan2(100, 0) = 90° = 5_400_000.+ let vs = evaluate_guides(&[g("a", "at2 0 100")], ctx());+ assert!((vs["a"] - 5_400_000.0).abs() < 1e-3);+ }++ #[test]+ fn cat2_sat2_polar_projection() {+ // cat2(r, 0, r) = r * cos(arctan2(r, 0)) = r * cos(90°) = 0+ // sat2(r, 0, r) = r * sin(arctan2(r, 0)) = r * sin(90°) = r+ let vs = evaluate_guides(+ &[g("cx", "cat2 100 0 100"), g("cy", "sat2 100 0 100")],+ ctx(),+ );+ assert!(vs["cx"].abs() < 1e-6);+ assert!((vs["cy"] - 100.0).abs() < 1e-6);+ }++ #[test]+ fn guide_references_preceding_guide() {+ let vs = evaluate_guides(+ &[g("half_w", "*/ w 1 2"), g("quarter_w", "*/ half_w 1 2")],+ ctx(),+ );+ assert_eq!(vs["half_w"], 50.0);+ assert_eq!(vs["quarter_w"], 25.0);+ }++ #[test]+ fn forward_reference_resolves_to_zero() {+ // First guide references second (not yet computed) → 0.+ let vs = evaluate_guides(&[g("first", "val later"), g("later", "val 10")], ctx());+ assert_eq!(vs["first"], 0.0);+ assert_eq!(vs["later"], 10.0);+ }++ #[test]+ fn malformed_formula_is_skipped() {+ let vs = evaluate_guides(&[g("a", "bogus_op 1 2")], ctx());+ assert!(!vs.contains_key("a"));+ }++ #[test]+ fn resolve_adj_coord_lit_vs_guide() {+ let mut values = GuideValues::new();+ values.insert("x".into(), 42.0);+ assert_eq!(resolve_adj_coord(&AdjCoord::Lit(7), &values, ctx()), 7.0);+ assert_eq!(+ resolve_adj_coord(&AdjCoord::Guide("x".into()), &values, ctx()),+ 42.0+ );+ // Named constant fallback.+ assert_eq!(+ resolve_adj_coord(&AdjCoord::Guide("w".into()), &values, ctx()),+ 100.0+ );+ // Unknown → 0.+ assert_eq!(+ resolve_adj_coord(&AdjCoord::Guide("nope".into()), &values, ctx()),+ 0.0+ );+ }++ #[test]+ fn angle_constants_cd4_is_90deg() {+ let vs = evaluate_guides(&[g("a", "val cd4")], ctx());+ assert_eq!(vs["a"], 5_400_000.0);+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_geometry/mod.rs b/crates/liteparse-docx/src/render/resolve/shape_geometry/mod.rsnew file mode 100644index 0000000..ab69b95--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_geometry/mod.rs@@ -0,0 +1,130 @@+//! Shape geometry resolution — evaluates OOXML geometry definitions+//! (`prstGeom`, `custGeom`) into drawable paths in shape-local Pt+//! coordinates.+//!+//! # Pipeline+//!+//! 1. Parse produces a `ShapeGeometry` (Preset | Custom).+//! 2. `build_geometry(&geom, extent)` dispatches to the preset generator or+//! the custom-geometry evaluator, yielding a `ShapePath`.+//! 3. The layout phase places the `ShapePath` within the document; the+//! painter converts `PathVerb`s to Skia path operations.+//!+//! All coordinates in a `ShapePath` are in shape-local points (origin at the+//! top-left of the shape, positive x right, positive y down). Angles follow+//! the OOXML convention — 60000ths of a degree — and are kept in that unit+//! so the painter can apply them directly to Skia's clockwise-from-3-o'clock+//! arc operations without a unit conversion at the call site.++pub mod custom;+pub mod guides;+pub mod presets;++use crate::model::ShapeGeometry;+use crate::model::dimension::{Dimension, SixtieThousandthDeg};+use crate::render::dimension::Pt;+use crate::render::geometry::{PtOffset, PtRect, PtSize};++/// A fully evaluated shape geometry, ready for placement and painting.+#[derive(Clone, Debug)]+pub struct ShapePath {+ /// One or more subpaths. A preset typically produces one; `custGeom`+ /// preserves the source `<a:path>` grouping.+ pub paths: Vec<SubPath>,+ /// Optional text rectangle for `<wps:txbx>` body layout. Presets may+ /// leave this `None`; `custGeom` copies the `<a:rect>` child if present.+ pub text_rect: Option<PtRect>,+}++/// A single contiguous path in shape-local Pt.+#[derive(Clone, Debug)]+pub struct SubPath {+ pub verbs: Vec<PathVerb>,+ /// §20.1.10.45 path-level fill mode.+ pub fill_mode: crate::model::PathFillMode,+ /// Whether this path should be stroked with the shape's outline.+ pub stroked: bool,+}++/// Path verbs in shape-local Pt. Maps directly onto Skia path operations+/// with an angular-unit conversion for [`PathVerb::ArcTo`].+#[derive(Clone, Debug)]+pub enum PathVerb {+ MoveTo(PtOffset),+ LineTo(PtOffset),+ QuadTo(PtOffset, PtOffset),+ CubicTo(PtOffset, PtOffset, PtOffset),+ /// Elliptical arc. `radii` are horizontal/vertical radii; angles follow+ /// OOXML convention (60000ths of a degree; 0° points to the right,+ /// positive swing is clockwise). The start point of the arc is implicit+ /// (the prior path cursor); the arc does not implicitly line-to its+ /// start.+ ArcTo {+ radii: PtSize,+ start_angle: Dimension<SixtieThousandthDeg>,+ swing_angle: Dimension<SixtieThousandthDeg>,+ },+ Close,+}++/// Build a `ShapePath` for a parsed `ShapeGeometry` given the shape's+/// rendered extent.+///+/// Returns `None` if:+/// * a preset has no generator registered (Tier 0 supports `line` and+/// `rect`; callers should log once and fall back to a stub bounding box),+/// * the extent is zero in either dimension (nothing to draw).+pub fn build_geometry(geometry: &ShapeGeometry, extent: PtSize) -> Option<ShapePath> {+ // Reject only fully zero-extent shapes. Lines are commonly authored as+ // `cx=0, cy=N` (vertical) or `cx=N, cy=0` (horizontal); both are valid+ // and must render.+ if extent.width <= Pt::ZERO && extent.height <= Pt::ZERO {+ return None;+ }+ match geometry {+ ShapeGeometry::Preset(def) => presets::build_preset(def, extent),+ ShapeGeometry::Custom(def) => custom::build_custom(def, extent),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::{PresetGeometryDef, PresetShapeType, ShapeGeometry};++ fn preset(preset: PresetShapeType) -> ShapeGeometry {+ ShapeGeometry::Preset(PresetGeometryDef {+ preset,+ adjust_values: vec![],+ })+ }++ #[test]+ fn zero_extent_returns_none() {+ // Both dimensions zero → nothing to draw.+ let g = preset(PresetShapeType::Rect);+ assert!(build_geometry(&g, PtSize::new(Pt::ZERO, Pt::ZERO)).is_none());+ }++ #[test]+ fn single_zero_dimension_still_builds() {+ // A vertical line is authored as cx=0, cy=N — must not be rejected.+ let g = preset(PresetShapeType::Line);+ assert!(build_geometry(&g, PtSize::new(Pt::ZERO, Pt::new(40.0))).is_some());+ // …and a horizontal line as cx=N, cy=0.+ assert!(build_geometry(&g, PtSize::new(Pt::new(40.0), Pt::ZERO)).is_some());+ }++ #[test]+ fn preset_dispatch_builds_supported_shapes() {+ let extent = PtSize::new(Pt::new(30.0), Pt::new(20.0));+ assert!(build_geometry(&preset(PresetShapeType::Rect), extent).is_some());+ assert!(build_geometry(&preset(PresetShapeType::Line), extent).is_some());+ }++ #[test]+ fn unimplemented_preset_returns_none() {+ let extent = PtSize::new(Pt::new(30.0), Pt::new(20.0));+ assert!(build_geometry(&preset(PresetShapeType::Star12), extent).is_none());+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/line.rs b/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/line.rsnew file mode 100644index 0000000..09376d1--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/line.rs@@ -0,0 +1,57 @@+//! §20.1.9.18 `line` preset — a single straight line from the top-left+//! corner (0, 0) to the bottom-right corner (w, h) of the shape's bounding+//! box, unstroked-by-default-fill (the outline supplies the visible stroke).++use crate::model::PathFillMode;+use crate::render::dimension::Pt;+use crate::render::geometry::{PtOffset, PtSize};+use crate::render::resolve::shape_geometry::{PathVerb, ShapePath, SubPath};++pub fn build(extent: PtSize) -> ShapePath {+ let verbs = vec![+ PathVerb::MoveTo(PtOffset::new(Pt::ZERO, Pt::ZERO)),+ PathVerb::LineTo(PtOffset::new(extent.width, extent.height)),+ ];+ ShapePath {+ paths: vec![SubPath {+ verbs,+ fill_mode: PathFillMode::None,+ stroked: true,+ }],+ text_rect: None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn line_from_origin_to_extent() {+ let p = build(PtSize::new(Pt::new(100.0), Pt::new(50.0)));+ assert_eq!(p.paths.len(), 1);+ let sub = &p.paths[0];+ assert!(!matches!(sub.fill_mode, PathFillMode::Norm));+ assert!(sub.stroked);+ assert_eq!(sub.verbs.len(), 2);+ matches!(sub.verbs[0], PathVerb::MoveTo(_));+ matches!(sub.verbs[1], PathVerb::LineTo(_));+ }++ #[test]+ fn line_handles_vertical_shape() {+ let p = build(PtSize::new(Pt::ZERO, Pt::new(50.0)));+ let sub = &p.paths[0];+ let PathVerb::LineTo(pt) = sub.verbs[1] else {+ panic!()+ };+ assert_eq!(pt.x, Pt::ZERO);+ assert_eq!(pt.y, Pt::new(50.0));+ }++ #[test]+ fn line_text_rect_is_none() {+ let p = build(PtSize::new(Pt::new(10.0), Pt::new(10.0)));+ assert!(p.text_rect.is_none());+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/mod.rs b/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/mod.rsnew file mode 100644index 0000000..baaa76e--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/mod.rs@@ -0,0 +1,74 @@+//! Preset shape generators (§20.1.9.18 ST_ShapeType).+//!+//! Each generator is a pure function `PtSize → ShapePath`. Dispatch by+//! variant lives in [`build_preset`]. Unimplemented presets return `None`+//! and log once; callers should fall back to the shape's bounding box or+//! skip the shape.+//!+//! Tier 0 supports only `line` and `rect` — the minimum to validate the+//! pipeline end-to-end. Tier 1 adds the common ~20 shapes; Tier 2 adds the+//! remaining ~60; Tier 3 completes the spec's ~200.++mod line;+mod rect;++use crate::model::{PresetGeometryDef, PresetShapeType};+use crate::render::geometry::PtSize;++use super::ShapePath;++/// Dispatch a preset to its generator. Returns `None` for presets not yet+/// implemented; the call site is expected to log.+pub fn build_preset(def: &PresetGeometryDef, extent: PtSize) -> Option<ShapePath> {+ match def.preset {+ PresetShapeType::Line => Some(line::build(extent)),+ PresetShapeType::Rect => Some(rect::build(extent)),+ _ => {+ log::warn!(+ "shape_geometry: preset {:?} not yet implemented",+ def.preset+ );+ None+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::render::dimension::Pt;++ fn def(preset: PresetShapeType) -> PresetGeometryDef {+ PresetGeometryDef {+ preset,+ adjust_values: vec![],+ }+ }++ #[test]+ fn line_dispatches() {+ let p = build_preset(+ &def(PresetShapeType::Line),+ PtSize::new(Pt::new(10.0), Pt::new(20.0)),+ );+ assert!(p.is_some());+ }++ #[test]+ fn rect_dispatches() {+ let p = build_preset(+ &def(PresetShapeType::Rect),+ PtSize::new(Pt::new(10.0), Pt::new(20.0)),+ );+ assert!(p.is_some());+ }++ #[test]+ fn unknown_preset_returns_none() {+ let p = build_preset(+ &def(PresetShapeType::Star12),+ PtSize::new(Pt::new(10.0), Pt::new(20.0)),+ );+ assert!(p.is_none());+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/rect.rs b/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/rect.rsnew file mode 100644index 0000000..38e24dc--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_geometry/presets/rect.rs@@ -0,0 +1,59 @@+//! §20.1.9.18 `rect` preset — a closed rectangle matching the shape's+//! bounding box. Fills with the shape's fill; strokes with the outline.++use crate::model::PathFillMode;+use crate::render::dimension::Pt;+use crate::render::geometry::{PtOffset, PtSize};+use crate::render::resolve::shape_geometry::{PathVerb, ShapePath, SubPath};++pub fn build(extent: PtSize) -> ShapePath {+ let (w, h) = (extent.width, extent.height);+ let verbs = vec![+ PathVerb::MoveTo(PtOffset::new(Pt::ZERO, Pt::ZERO)),+ PathVerb::LineTo(PtOffset::new(w, Pt::ZERO)),+ PathVerb::LineTo(PtOffset::new(w, h)),+ PathVerb::LineTo(PtOffset::new(Pt::ZERO, h)),+ PathVerb::Close,+ ];+ ShapePath {+ paths: vec![SubPath {+ verbs,+ fill_mode: PathFillMode::Norm,+ stroked: true,+ }],+ // §20.1.9.22: the preset rect's text area is its full bounding box.+ text_rect: Some(crate::render::geometry::PtRect::from_xywh(+ Pt::ZERO,+ Pt::ZERO,+ w,+ h,+ )),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rect_five_verbs() {+ let p = build(PtSize::new(Pt::new(100.0), Pt::new(50.0)));+ assert_eq!(p.paths.len(), 1);+ assert_eq!(p.paths[0].verbs.len(), 5);+ assert!(matches!(p.paths[0].verbs[4], PathVerb::Close));+ }++ #[test]+ fn rect_text_rect_matches_extent() {+ let p = build(PtSize::new(Pt::new(100.0), Pt::new(50.0)));+ let tr = p.text_rect.unwrap();+ assert_eq!(tr.origin, PtOffset::new(Pt::ZERO, Pt::ZERO));+ assert_eq!(tr.size, PtSize::new(Pt::new(100.0), Pt::new(50.0)));+ }++ #[test]+ fn rect_fill_mode_is_normal() {+ let p = build(PtSize::new(Pt::new(10.0), Pt::new(10.0)));+ assert!(matches!(p.paths[0].fill_mode, PathFillMode::Norm));+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/shape_visuals.rs b/crates/liteparse-docx/src/render/resolve/shape_visuals.rsnew file mode 100644index 0000000..b66dc30--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/shape_visuals.rs@@ -0,0 +1,762 @@+//! Resolve DrawingML shape visuals (fill / stroke / effects) from the+//! parsed model ADTs into painter-ready `Resolved*` types.+//!+//! The resolver is pure: given a shape's `ShapeProperties` and the active+//! theme, it produces concrete RGBA fills, point-sized strokes, and a flat+//! list of effects ready for the painter. Unsupported variants map to+//! sensible defaults (`ResolvedFill::None`, no stroke, empty effects) with+//! a log.++use crate::model::dimension::{Dimension, Emu};+use crate::model::{+ DrawingFill, Effect, GlowEffect, InnerShadowEffect, LineCap, LineDash, LineJoin,+ OuterShadowEffect, Outline, PathFillMode, PresetShadowEffect, ReflectionEffect,+ ShapeProperties, SoftEdgeEffect, StyleMatrixRef, Theme,+};+use crate::render::dimension::Pt;+use crate::render::geometry::PtOffset;+use crate::render::layout::draw_command::{+ ResolvedDashPattern, ResolvedEffect, ResolvedFill, ResolvedLineCap, ResolvedLineJoin,+ ResolvedStroke,+};+use crate::render::resolve::drawing_color::{DrawingColorContext, Rgba, resolve_drawing_color};++/// Resolved bundle for one shape.+pub struct ResolvedVisuals {+ pub fill: ResolvedFill,+ pub stroke: Option<ResolvedStroke>,+ pub effects: Vec<ResolvedEffect>,+}++/// Resolve the visual aspect of a shape (fill, outline, effects) into the+/// painter-ready types. Missing `ShapeProperties` → empty / `None` visuals.+///+/// `style_effect_ref` is the `wps:style/effectRef` on the enclosing shape.+/// Per Word's rendering behavior — which the OOXML spec is ambiguous about —+/// a present-but-empty `<a:effectLst/>` on spPr falls through to the theme+/// effect style. Only when the direct effectLst has children do we treat it+/// as an explicit override.+pub fn resolve_shape_visuals(+ props: Option<&ShapeProperties>,+ style_line_ref: Option<&StyleMatrixRef>,+ style_effect_ref: Option<&StyleMatrixRef>,+ style_fill_ref: Option<&StyleMatrixRef>,+ theme: Option<&Theme>,+) -> ResolvedVisuals {+ let ctx = DrawingColorContext::new(theme);+ let props = match props {+ Some(p) => p,+ None => {+ // No spPr, but a bare `<wps:style>` may still carry a fillRef.+ return ResolvedVisuals {+ fill: resolve_theme_fill(style_fill_ref, theme, &ctx),+ stroke: None,+ effects: Vec::new(),+ };+ }+ };++ // §20.1.4.1.13: a direct spPr fill wins; otherwise fall back to the theme+ // fill style referenced by `<a:fillRef>` (recolored by its phClr).+ let fill = match props.fill.as_ref() {+ Some(f) => resolve_fill(f, &ctx),+ None => resolve_theme_fill(style_fill_ref, theme, &ctx),+ };++ let theme_ln = theme_line_style(style_line_ref, theme);+ let stroke = props+ .outline+ .as_ref()+ .and_then(|o| resolve_outline(o, theme_ln, &ctx));++ let direct_effects = props+ .effect_list+ .as_ref()+ .map(|el| el.effects.as_slice())+ .unwrap_or(&[]);+ let effects = if !direct_effects.is_empty() {+ resolve_effects(direct_effects, &ctx)+ } else {+ resolve_theme_effects(style_effect_ref, theme, &ctx)+ };++ ResolvedVisuals {+ fill,+ stroke,+ effects,+ }+}++/// §20.1.4.1.13: resolve the theme fill style referenced by `<a:fillRef>`,+/// substituting `phClr` with the reference's own color. Returns+/// `ResolvedFill::None` when the ref is absent, `idx` is 0, or the theme+/// doesn't define the requested style.+fn resolve_theme_fill(+ style_fill_ref: Option<&StyleMatrixRef>,+ theme: Option<&Theme>,+ ctx: &DrawingColorContext<'_>,+) -> ResolvedFill {+ let Some(r) = style_fill_ref else {+ return ResolvedFill::None;+ };+ // §20.1.4.2.19: idx is 1-based; 0 is the no-reference sentinel.+ if r.idx == 0 {+ return ResolvedFill::None;+ }+ let Some(theme) = theme else {+ return ResolvedFill::None;+ };+ let Some(fill) = theme.fill_styles.get((r.idx as usize) - 1) else {+ return ResolvedFill::None;+ };+ // Substitute phClr with the fillRef's own color before resolving the fill.+ let fill_ctx = match r.color.as_ref() {+ Some(c) => ctx.with_placeholder(resolve_drawing_color(c, ctx)),+ None => *ctx,+ };+ resolve_fill(fill, &fill_ctx)+}++/// Look up a theme line style by its 1-based `lnRef` index.+fn theme_line_style<'a>(+ style_line_ref: Option<&StyleMatrixRef>,+ theme: Option<&'a Theme>,+) -> Option<&'a Outline> {+ let idx = style_line_ref?.idx;+ if idx == 0 {+ return None;+ }+ theme?.line_styles.get((idx as usize) - 1)+}++/// Consult the theme's `effectStyleLst` via a shape's `effectRef`. Returns an+/// empty list when the ref is absent, the index is out of range, or the theme+/// doesn't define the requested style.+fn resolve_theme_effects(+ style_effect_ref: Option<&StyleMatrixRef>,+ theme: Option<&Theme>,+ ctx: &DrawingColorContext<'_>,+) -> Vec<ResolvedEffect> {+ let Some(r) = style_effect_ref else {+ return Vec::new();+ };+ let Some(theme) = theme else {+ return Vec::new();+ };+ // §20.1.4.2.19: idx is 1-based. idx=0 is the no-reference sentinel.+ if r.idx == 0 {+ return Vec::new();+ }+ let slot = (r.idx as usize).saturating_sub(1);+ let Some(list) = theme.effect_styles.get(slot) else {+ return Vec::new();+ };+ resolve_effects(&list.effects, ctx)+}++/// Most preset shapes default the fill mode from `<a:path>`; for Tier 0+/// presets without a path-level fill directive, callers can read this.+pub fn default_path_fill_for_stroked_shape() -> PathFillMode {+ PathFillMode::None+}++// ── Fills ───────────────────────────────────────────────────────────────────++pub fn resolve_fill(fill: &DrawingFill, ctx: &DrawingColorContext<'_>) -> ResolvedFill {+ match fill {+ DrawingFill::None => ResolvedFill::None,+ DrawingFill::Solid(color) => ResolvedFill::Solid(resolve_drawing_color(color, ctx)),+ DrawingFill::Gradient(g) => {+ log::warn!("shape_visuals: gradient fill not yet resolved (Tier 2)");+ use crate::render::layout::draw_command::{+ GradientStopRgba, ResolvedGradient, ResolvedGradientKind,+ };+ let stops = g+ .stops+ .iter()+ .map(|s| GradientStopRgba {+ position: s.position.to_fraction(),+ color: resolve_drawing_color(&s.color, ctx),+ })+ .collect();+ let kind = match &g.shade_properties {+ crate::model::GradientShadeProperties::Linear { angle, .. } => {+ ResolvedGradientKind::Linear {+ angle_deg: angle.raw() as f32 / 60_000.0,+ }+ }+ crate::model::GradientShadeProperties::Path { .. } => ResolvedGradientKind::Radial,+ };+ ResolvedFill::Gradient(ResolvedGradient { stops, kind })+ }+ DrawingFill::Blip(_) => {+ log::warn!("shape_visuals: blip fill not yet resolved (Tier 2)");+ ResolvedFill::None+ }+ DrawingFill::Pattern(_) => {+ log::warn!("shape_visuals: pattern fill not yet resolved (Tier 3)");+ ResolvedFill::None+ }+ DrawingFill::Group => {+ log::warn!(+ "shape_visuals: group fill (grpFill) not resolved — no enclosing group context"+ );+ ResolvedFill::None+ }+ }+}++// ── Outline → Stroke ────────────────────────────────────────────────────────++fn resolve_outline(+ outline: &Outline,+ theme_ln: Option<&Outline>,+ ctx: &DrawingColorContext<'_>,+) -> Option<ResolvedStroke> {+ // Width: direct `@w` wins; else theme `lnRef`; else spec default 0.75pt.+ // OOXML `w` is EMU (12700 per pt).+ let width = outline+ .width+ .or_else(|| theme_ln.and_then(|t| t.width))+ .map(emu_to_pt)+ .unwrap_or_else(|| Pt::new(0.75));++ // Pull the outline color from its fill. If the fill is non-solid or+ // absent, default to black; Tier 0 cannot paint gradient strokes.+ let color = match outline.fill.as_ref() {+ Some(DrawingFill::Solid(c)) => resolve_drawing_color(c, ctx),+ Some(DrawingFill::None) => return None,+ Some(DrawingFill::Gradient(_) | DrawingFill::Blip(_) | DrawingFill::Pattern(_)) => {+ log::warn!("shape_visuals: non-solid stroke fill not yet supported");+ Rgba::BLACK+ }+ Some(DrawingFill::Group) | None => Rgba::BLACK,+ };++ let cap = outline+ .cap+ .or_else(|| theme_ln.and_then(|t| t.cap))+ .map(map_line_cap)+ .unwrap_or(ResolvedLineCap::Butt);+ let join = outline+ .join+ .as_ref()+ .or_else(|| theme_ln.and_then(|t| t.join.as_ref()))+ .map(map_line_join)+ .unwrap_or(ResolvedLineJoin::Round);+ let dash = outline+ .dash+ .as_ref()+ .or_else(|| theme_ln.and_then(|t| t.dash.as_ref()))+ .map(|d| map_line_dash(d, width))+ .unwrap_or(ResolvedDashPattern::Solid);++ Some(ResolvedStroke {+ width,+ color,+ dash,+ cap,+ join,+ })+}++fn map_line_cap(cap: LineCap) -> ResolvedLineCap {+ match cap {+ LineCap::Flat => ResolvedLineCap::Butt,+ LineCap::Round => ResolvedLineCap::Round,+ LineCap::Square => ResolvedLineCap::Square,+ }+}++fn map_line_join(join: &LineJoin) -> ResolvedLineJoin {+ match join {+ LineJoin::Round => ResolvedLineJoin::Round,+ LineJoin::Bevel => ResolvedLineJoin::Bevel,+ LineJoin::Miter { .. } => ResolvedLineJoin::Miter,+ }+}++/// Map a `LineDash` into painter units. Preset dash patterns use the+/// canonical Microsoft ratios expressed as multiples of the stroke width.+/// Custom dashes carry their own dash/space pairs as thousandth-percent of+/// line width.+fn map_line_dash(dash: &LineDash, width: Pt) -> ResolvedDashPattern {+ use crate::model::PresetLineDashVal as P;+ match dash {+ LineDash::Preset(preset) => {+ let ratios: &[f32] = match preset {+ P::Solid => return ResolvedDashPattern::Solid,+ P::Dot | P::SysDot => &[1.0, 3.0],+ P::Dash => &[4.0, 3.0],+ P::LgDash => &[8.0, 3.0],+ P::DashDot => &[4.0, 3.0, 1.0, 3.0],+ P::LgDashDot => &[8.0, 3.0, 1.0, 3.0],+ P::LgDashDotDot => &[8.0, 3.0, 1.0, 3.0, 1.0, 3.0],+ P::SysDash => &[3.0, 1.0],+ P::SysDashDot => &[3.0, 1.0, 1.0, 1.0],+ P::SysDashDotDot => &[3.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ };+ let w = width.raw();+ let dashes: Vec<Pt> = ratios.iter().map(|r| Pt::new(r * w)).collect();+ ResolvedDashPattern::Dashes(dashes)+ }+ LineDash::Custom(stops) => {+ if stops.is_empty() {+ return ResolvedDashPattern::Solid;+ }+ let w = width.raw();+ let mut out = Vec::with_capacity(stops.len() * 2);+ for s in stops {+ // §20.1.8.27: dash/space in 1000ths of a percent of line width.+ out.push(Pt::new(s.dash.to_fraction() * w));+ out.push(Pt::new(s.space.to_fraction() * w));+ }+ ResolvedDashPattern::Dashes(out)+ }+ }+}++// ── Effects ─────────────────────────────────────────────────────────────────++fn resolve_effects(effects: &[Effect], ctx: &DrawingColorContext<'_>) -> Vec<ResolvedEffect> {+ effects+ .iter()+ .filter_map(|e| resolve_effect(e, ctx))+ .collect()+}++fn resolve_effect(effect: &Effect, ctx: &DrawingColorContext<'_>) -> Option<ResolvedEffect> {+ match effect {+ Effect::OuterShdw(sh) => Some(resolve_outer_shadow(sh, ctx)),+ Effect::Blur(_b) => {+ log::warn!("shape_visuals: blur effect not yet rendered (Tier 2)");+ None+ }+ Effect::Glow(g) => {+ log::warn!("shape_visuals: glow effect not yet rendered (Tier 2)");+ let _: &GlowEffect = g;+ None+ }+ Effect::InnerShdw(s) => {+ log::warn!("shape_visuals: innerShdw not yet rendered (Tier 2)");+ let _: &InnerShadowEffect = s;+ None+ }+ Effect::PrstShdw(s) => {+ log::warn!("shape_visuals: prstShdw not yet rendered (Tier 2)");+ let _: &PresetShadowEffect = s;+ None+ }+ Effect::Reflection(r) => {+ log::warn!("shape_visuals: reflection not yet rendered (Tier 2)");+ let _: &ReflectionEffect = r;+ None+ }+ Effect::SoftEdge(s) => {+ log::warn!("shape_visuals: softEdge not yet rendered (Tier 2)");+ let _: &SoftEdgeEffect = s;+ None+ }+ Effect::FillOverlay(_) => {+ log::warn!("shape_visuals: fillOverlay not yet rendered (Tier 2)");+ None+ }+ }+}++fn resolve_outer_shadow(sh: &OuterShadowEffect, ctx: &DrawingColorContext<'_>) -> ResolvedEffect {+ // §20.1.8.45: `dist` = distance from shape, `dir` = angle from the+ // shape's top-left toward which the shadow is cast (60000ths of a+ // degree, clockwise positive, 0° = east).+ let dist = emu_to_pt(sh.distance);+ let dir_rad = (sh.direction.raw() as f32 / 60_000.0).to_radians();+ let dx = dist.raw() * dir_rad.cos();+ let dy = dist.raw() * dir_rad.sin();+ ResolvedEffect::OuterShadow {+ blur_radius: emu_to_pt(sh.blur_radius),+ offset: PtOffset::new(Pt::new(dx), Pt::new(dy)),+ color: resolve_drawing_color(&sh.color, ctx),+ }+}++// ── Unit helpers ────────────────────────────────────────────────────────────++/// Convert EMU (English Metric Units — 914400 per inch) to Pt (72 per inch).+pub fn emu_to_pt(emu: Dimension<Emu>) -> Pt {+ Pt::new(emu.raw() as f32 / 12_700.0)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::{+ DrawingColor, DrawingFill, EffectList, Outline, PresetLineDashVal, SchemeColorVal,+ ShapeProperties,+ };++ fn empty_outline() -> Outline {+ Outline {+ width: None,+ cap: None,+ compound: None,+ alignment: None,+ fill: None,+ dash: None,+ join: None,+ head_end: None,+ tail_end: None,+ }+ }++ fn shape_props(+ fill: Option<DrawingFill>,+ outline: Option<Outline>,+ effects: Option<EffectList>,+ ) -> ShapeProperties {+ ShapeProperties {+ bw_mode: None,+ transform: None,+ geometry: None,+ fill,+ outline,+ effect_list: effects,+ }+ }++ #[test]+ fn empty_props_resolves_to_none_visuals() {+ let v = resolve_shape_visuals(None, None, None, None, None);+ assert!(matches!(v.fill, ResolvedFill::None));+ assert!(v.stroke.is_none());+ assert!(v.effects.is_empty());+ }++ #[test]+ fn solid_fill_srgb_resolves_to_rgba() {+ let props = shape_props(+ Some(DrawingFill::Solid(DrawingColor::Srgb {+ rgb: 0xD99F34,+ transforms: vec![],+ })),+ None,+ None,+ );+ let v = resolve_shape_visuals(Some(&props), None, None, None, None);+ let ResolvedFill::Solid(c) = v.fill else {+ panic!()+ };+ assert_eq!(c.to_rgb24(), 0xD99F34);+ }++ #[test]+ fn outline_with_solid_fill_resolves_to_stroke() {+ let outline = Outline {+ width: Some(Dimension::new(9525)), // 0.75pt+ cap: Some(LineCap::Round),+ compound: None,+ alignment: None,+ fill: Some(DrawingFill::Solid(DrawingColor::Srgb {+ rgb: 0x0000FF,+ transforms: vec![],+ })),+ dash: Some(LineDash::Preset(PresetLineDashVal::Dash)),+ join: Some(LineJoin::Miter { limit: None }),+ head_end: None,+ tail_end: None,+ };+ let props = shape_props(None, Some(outline), None);+ let v = resolve_shape_visuals(Some(&props), None, None, None, None);+ let s = v.stroke.unwrap();+ assert_eq!(s.width, Pt::new(0.75));+ assert_eq!(s.color.to_rgb24(), 0x0000FF);+ assert_eq!(s.cap, ResolvedLineCap::Round);+ assert_eq!(s.join, ResolvedLineJoin::Miter);+ match s.dash {+ ResolvedDashPattern::Dashes(_) => {}+ _ => panic!("expected dashed pattern"),+ }+ }++ #[test]+ fn outline_defaults_when_no_width_or_fill() {+ let outline = Outline {+ width: None,+ cap: None,+ compound: None,+ alignment: None,+ fill: None,+ dash: None,+ join: None,+ head_end: None,+ tail_end: None,+ };+ let props = shape_props(None, Some(outline), None);+ let v = resolve_shape_visuals(Some(&props), None, None, None, None);+ let s = v.stroke.unwrap();+ assert_eq!(s.width, Pt::new(0.75));+ assert_eq!(s.color, Rgba::BLACK);+ assert_eq!(s.cap, ResolvedLineCap::Butt);+ assert_eq!(s.join, ResolvedLineJoin::Round);+ assert!(matches!(s.dash, ResolvedDashPattern::Solid));+ }++ #[test]+ fn outline_nofill_suppresses_stroke() {+ let outline = Outline {+ width: Some(Dimension::new(9525)),+ cap: None,+ compound: None,+ alignment: None,+ fill: Some(DrawingFill::None),+ dash: None,+ join: None,+ head_end: None,+ tail_end: None,+ };+ let props = shape_props(None, Some(outline), None);+ let v = resolve_shape_visuals(Some(&props), None, None, None, None);+ assert!(v.stroke.is_none());+ }++ #[test]+ fn emu_to_pt_conversion() {+ assert_eq!(emu_to_pt(Dimension::new(12_700)), Pt::new(1.0));+ assert_eq!(emu_to_pt(Dimension::new(9525)), Pt::new(0.75));+ assert_eq!(emu_to_pt(Dimension::new(914_400)), Pt::new(72.0));+ }++ #[test]+ fn outline_width_falls_back_to_theme_ln_ref() {+ use crate::model::DrawingColor;+ // Shape's `<a:ln>` has only a solid color — width/cap/dash absent.+ let outline = Outline {+ width: None,+ cap: None,+ compound: None,+ alignment: None,+ fill: Some(DrawingFill::Solid(DrawingColor::Srgb {+ rgb: 0xD99F34,+ transforms: vec![],+ })),+ dash: None,+ join: None,+ head_end: None,+ tail_end: None,+ };+ // Theme lnStyleLst[1] = 2pt wide (25400 EMU).+ let theme_ln = Outline {+ width: Some(Dimension::new(25_400)),+ cap: Some(LineCap::Flat),+ compound: None,+ alignment: None,+ fill: None,+ dash: None,+ join: None,+ head_end: None,+ tail_end: None,+ };+ let theme = Theme {+ line_styles: vec![empty_outline(), theme_ln, empty_outline()],+ ..Theme::default()+ };+ let props = shape_props(None, Some(outline), None);+ let ln_ref = StyleMatrixRef {+ idx: 2,+ color: None,+ };+ let v = resolve_shape_visuals(Some(&props), Some(&ln_ref), None, None, Some(&theme));+ let s = v.stroke.unwrap();+ assert_eq!(s.width, Pt::new(2.0));+ assert_eq!(s.color.to_rgb24(), 0xD99F34);+ assert_eq!(s.cap, ResolvedLineCap::Butt);+ }++ #[test]+ fn empty_effect_list_falls_back_to_theme_via_effect_ref() {+ use crate::model::DrawingColor;+ // Empty direct effect list + effectRef idx=1 → theme effect style [0].+ let props = shape_props(None, None, Some(EffectList { effects: vec![] }));+ let theme = Theme {+ effect_styles: vec![EffectList {+ effects: vec![Effect::OuterShdw(OuterShadowEffect {+ blur_radius: Dimension::new(25_400), // 2pt+ distance: Dimension::new(12_700), // 1pt+ direction: Dimension::new(0), // east+ sx: Dimension::new(100_000),+ sy: Dimension::new(100_000),+ kx: Dimension::new(0),+ ky: Dimension::new(0),+ alignment: crate::model::RectAlignment::B,+ rot_with_shape: None,+ color: DrawingColor::Srgb {+ rgb: 0x000000,+ transforms: vec![],+ },+ })],+ }],+ ..Theme::default()+ };+ let er = StyleMatrixRef {+ idx: 1,+ color: None,+ };+ let v = resolve_shape_visuals(Some(&props), None, Some(&er), None, Some(&theme));+ assert_eq!(v.effects.len(), 1);+ }++ #[test]+ fn direct_effect_list_overrides_theme() {+ use crate::model::DrawingColor;+ let own = Effect::OuterShdw(OuterShadowEffect {+ blur_radius: Dimension::new(50_800), // 4pt+ distance: Dimension::new(0),+ direction: Dimension::new(0),+ sx: Dimension::new(100_000),+ sy: Dimension::new(100_000),+ kx: Dimension::new(0),+ ky: Dimension::new(0),+ alignment: crate::model::RectAlignment::B,+ rot_with_shape: None,+ color: DrawingColor::Srgb {+ rgb: 0xFF0000,+ transforms: vec![],+ },+ });+ let props = shape_props(None, None, Some(EffectList { effects: vec![own] }));+ let theme = Theme {+ effect_styles: vec![EffectList {+ effects: vec![Effect::OuterShdw(OuterShadowEffect {+ blur_radius: Dimension::new(12_700),+ distance: Dimension::new(12_700),+ direction: Dimension::new(0),+ sx: Dimension::new(100_000),+ sy: Dimension::new(100_000),+ kx: Dimension::new(0),+ ky: Dimension::new(0),+ alignment: crate::model::RectAlignment::B,+ rot_with_shape: None,+ color: DrawingColor::Srgb {+ rgb: 0x000000,+ transforms: vec![],+ },+ })],+ }],+ ..Theme::default()+ };+ let er = StyleMatrixRef {+ idx: 1,+ color: None,+ };+ let v = resolve_shape_visuals(Some(&props), None, Some(&er), None, Some(&theme));+ let ResolvedEffect::OuterShadow {+ blur_radius, color, ..+ } = &v.effects[0];+ assert_eq!(*blur_radius, Pt::new(4.0));+ assert_eq!(color.to_rgb24(), 0xFF0000);+ }++ #[test]+ fn outer_shadow_resolves_with_offset_from_angle() {+ let sh = OuterShadowEffect {+ blur_radius: Dimension::new(25_400), // 2pt+ distance: Dimension::new(38_100), // 3pt+ direction: Dimension::new(0), // 0° = east+ sx: Dimension::new(100_000),+ sy: Dimension::new(100_000),+ kx: Dimension::new(0),+ ky: Dimension::new(0),+ alignment: crate::model::RectAlignment::B,+ rot_with_shape: None,+ color: DrawingColor::Srgb {+ rgb: 0x000000,+ transforms: vec![],+ },+ };+ let props = shape_props(+ None,+ None,+ Some(EffectList {+ effects: vec![Effect::OuterShdw(sh)],+ }),+ );+ let v = resolve_shape_visuals(Some(&props), None, None, None, None);+ assert_eq!(v.effects.len(), 1);+ let ResolvedEffect::OuterShadow {+ blur_radius,+ offset,+ color,+ } = &v.effects[0];+ assert_eq!(*blur_radius, Pt::new(2.0));+ assert!((offset.x.raw() - 3.0).abs() < 1e-5);+ assert!(offset.y.raw().abs() < 1e-5);+ assert_eq!(color.to_rgb24(), 0x000000);+ }++ fn ph_theme() -> Theme {+ // A theme whose fill style 1 is solidFill(phClr) — the common shape+ // fill style, colored by whatever the fillRef supplies.+ Theme {+ fill_styles: vec![DrawingFill::Solid(DrawingColor::Scheme {+ name: SchemeColorVal::PhClr,+ transforms: vec![],+ })],+ ..Default::default()+ }+ }++ #[test]+ fn fill_ref_resolves_theme_fill_with_phclr_substitution() {+ let theme = ph_theme();+ let fill_ref = StyleMatrixRef {+ idx: 1,+ color: Some(DrawingColor::Srgb {+ rgb: 0xFF0000,+ transforms: vec![],+ }),+ };+ // No direct spPr fill → the theme fill referenced by fillRef supplies it.+ let props = shape_props(None, None, None);+ let v = resolve_shape_visuals(Some(&props), None, None, Some(&fill_ref), Some(&theme));+ let ResolvedFill::Solid(c) = v.fill else {+ panic!("expected solid theme fill, got {:?}", v.fill);+ };+ assert_eq!(c.to_rgb24(), 0xFF0000, "phClr substituted by fillRef color");+ }++ #[test]+ fn direct_fill_wins_over_fill_ref() {+ let theme = ph_theme();+ let fill_ref = StyleMatrixRef {+ idx: 1,+ color: Some(DrawingColor::Srgb {+ rgb: 0xFF0000,+ transforms: vec![],+ }),+ };+ let props = shape_props(+ Some(DrawingFill::Solid(DrawingColor::Srgb {+ rgb: 0x00FF00,+ transforms: vec![],+ })),+ None,+ None,+ );+ let v = resolve_shape_visuals(Some(&props), None, None, Some(&fill_ref), Some(&theme));+ let ResolvedFill::Solid(c) = v.fill else {+ panic!("expected solid fill");+ };+ assert_eq!(c.to_rgb24(), 0x00FF00, "direct spPr fill overrides fillRef");+ }++ #[test]+ fn fill_ref_idx_zero_is_no_fill() {+ let theme = ph_theme();+ let fill_ref = StyleMatrixRef {+ idx: 0,+ color: None,+ };+ let props = shape_props(None, None, None);+ let v = resolve_shape_visuals(Some(&props), None, None, Some(&fill_ref), Some(&theme));+ assert!(matches!(v.fill, ResolvedFill::None));+ }+}diff --git a/crates/liteparse-docx/src/render/resolve/styles.rs b/crates/liteparse-docx/src/render/resolve/styles.rsnew file mode 100644index 0000000..cba67c3--- /dev/null+++ b/crates/liteparse-docx/src/render/resolve/styles.rs@@ -0,0 +1,560 @@+//! Style inheritance resolution — walk `basedOn` chains and merge properties.++use std::collections::{HashMap, HashSet};++use crate::model::{+ ParagraphProperties, RunProperties, StyleId, StyleSheet, TableProperties, Theme,+};++use super::properties::{merge_paragraph_properties, merge_run_properties, merge_table_properties};++/// A fully resolved style — all `basedOn` inheritance has been applied.+#[derive(Clone, Debug)]+pub struct ResolvedStyle {+ pub paragraph: ParagraphProperties,+ pub run: RunProperties,+ pub table: Option<TableProperties>,+ /// §17.7.6.6: table style conditional formatting overrides.+ pub table_style_overrides: Vec<crate::model::TableStyleOverride>,+ /// §17.7.4.9: this style is a table-of-contents *entry* style (`toc 1` …+ /// `toc 9`), either directly or through its `basedOn` chain.+ ///+ /// Derived here rather than tested at the render boundary because the+ /// signal is the **primary style name**, not the `w:styleId` spelling —+ /// see the private `is_toc_entry_name` helper below.+ pub is_toc_entry: bool,+}++/// §17.7.4.9: recognize the built-in primary style names for table-of-contents+/// **entries** — `toc 1` … `toc 9`.+///+/// `<w:name>` carries the *built-in* style name, which is locale-independent:+/// Word writes `toc 1` whatever the UI language, while the `w:styleId` is an+/// arbitrary identifier a producer may spell however it likes. Matching on the+/// name is therefore both narrower and wider than matching the ID — it does not+/// catch an unrelated user style called `TOCustom`, and it does catch a+/// localized document whose ToC style IDs are not spelled `TOC1`.+///+/// Deliberately excludes `TOC Heading` (the heading *above* a ToC, not an+/// entry) and `toc` with no level, neither of which is an entry style.+fn is_toc_entry_name(name: &str) -> bool {+ // OOXML style names compare case-insensitively.+ let rest = if name.len() >= 4 && name[..4].eq_ignore_ascii_case("toc ") {+ &name[4..]+ } else {+ return false;+ };+ matches!(rest.parse::<u8>(), Ok(1..=9))+}++/// Resolve all styles in the stylesheet by walking `basedOn` chains.+/// The theme is used to resolve `asciiTheme` / `hAnsiTheme` font references+/// on style-level run properties (§17.3.2.26).+pub fn resolve_styles(+ sheet: &StyleSheet,+ theme: Option<&Theme>,+) -> HashMap<StyleId, ResolvedStyle> {+ let mut resolved: HashMap<StyleId, ResolvedStyle> = HashMap::new();++ for id in sheet.styles.keys() {+ if !resolved.contains_key(id) {+ resolve_one(id, sheet, theme, &mut resolved, &mut HashSet::new());+ }+ }++ resolved+}++/// Recursively resolve a single style, memoizing results.+/// `visiting` tracks the current chain for cycle detection.+fn resolve_one(+ id: &StyleId,+ sheet: &StyleSheet,+ theme: Option<&Theme>,+ resolved: &mut HashMap<StyleId, ResolvedStyle>,+ visiting: &mut HashSet<StyleId>,+) {+ if resolved.contains_key(id) {+ return;+ }++ let style = match sheet.styles.get(id) {+ Some(s) => s,+ None => return,+ };++ // Cycle detection: if we're already visiting this style, stop recursion.+ if !visiting.insert(id.clone()) {+ // Break the cycle — resolve with just own properties + doc defaults.+ let mut para = style.paragraph_properties.clone().unwrap_or_default();+ let mut run = style.run_properties.clone().unwrap_or_default();+ let table = fold_whole_table(style.table_properties.clone(), &style.table_style_overrides);+ merge_paragraph_properties(&mut para, &sheet.doc_defaults_paragraph);+ merge_run_properties(&mut run, &sheet.doc_defaults_run);+ let is_toc_entry = style.name.as_deref().is_some_and(is_toc_entry_name);+ resolved.insert(+ id.clone(),+ ResolvedStyle {+ paragraph: para,+ run,+ table,+ table_style_overrides: style.table_style_overrides.clone(),+ is_toc_entry,+ },+ );+ return;+ }++ // Resolve parent first (if any).+ if let Some(ref parent_id) = style.based_on {+ if !resolved.contains_key(parent_id) {+ resolve_one(parent_id, sheet, theme, resolved, visiting);+ }+ }++ // Start with own properties.+ let mut para = style.paragraph_properties.clone().unwrap_or_default();+ let mut run = style.run_properties.clone().unwrap_or_default();+ // §17.3.2.26: resolve theme font references on the style's own run properties.+ if let Some(th) = theme {+ super::fonts::resolve_font_set_themes(&mut run.fonts, th);+ }++ // §17.7.2: table property inheritance — cell margins from parent table styles.+ let mut table = style.table_properties.clone();+ // Merge from resolved parent (if it exists and was successfully resolved).+ if let Some(ref parent_id) = style.based_on {+ if let Some(parent_resolved) = resolved.get(parent_id) {+ merge_paragraph_properties(&mut para, &parent_resolved.paragraph);+ merge_run_properties(&mut run, &parent_resolved.run);+ merge_table_properties(&mut table, &parent_resolved.table);+ }+ }++ // §17.7.2: doc defaults are NOT merged here — they are merged by the+ // caller at the correct cascade level. For table cell paragraphs, the+ // table style must be able to override doc defaults, which requires+ // doc defaults to be the lowest priority in the merge chain.+ // Character styles inherit only from their basedOn chain.+ // Run defaults from docDefaults still apply for font resolution.+ if style.style_type != crate::model::StyleType::Character {+ merge_run_properties(&mut run, &sheet.doc_defaults_run);+ }++ visiting.remove(id);++ // §17.7.4.9: ToC-entry-ness follows the `basedOn` chain, so a user style+ // derived from `toc 2` is still a ToC entry.+ let is_toc_entry = style.name.as_deref().is_some_and(is_toc_entry_name)+ || style+ .based_on+ .as_ref()+ .and_then(|parent| resolved.get(parent))+ .is_some_and(|parent| parent.is_toc_entry);++ resolved.insert(+ id.clone(),+ ResolvedStyle {+ paragraph: para,+ run,+ // §17.7.6: applied after the parent merge, so `wholeTable` overrides+ // both this style's own `tblPr` and anything inherited.+ table: fold_whole_table(table, &style.table_style_overrides),+ table_style_overrides: style.table_style_overrides.clone(),+ is_toc_entry,+ },+ );+}++/// §17.7.6: fold a table style's `wholeTable` conditional layer into its own+/// table properties.+///+/// `wholeTable` sits above the style's own `tblPr` and below every positional+/// override. Folding it here — rather than at the two places `build_table` reads+/// `ResolvedStyle::table` — means the table-level cascade needs no second+/// lookup, and a style that inherits from another sees the parent's already+/// folded (the parent resolves first).+///+/// The cell-level half (`tcPr`/`rPr`/`pPr`) is seeded separately, in+/// [`resolve_cell_conditional`](super::conditional::resolve_cell_conditional).+fn fold_whole_table(+ table: Option<crate::model::TableProperties>,+ overrides: &[crate::model::TableStyleOverride],+) -> Option<crate::model::TableProperties> {+ let whole = overrides+ .iter()+ .find(|o| o.override_type == crate::model::TableStyleOverrideType::WholeTable)+ .and_then(|o| o.table_properties.as_ref());+ match whole {+ Some(overlay) => Some(super::properties::overlay_table_properties(table, overlay)),+ None => table,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::model::dimension::{Dimension, HalfPoints};+ use crate::model::*;++ fn make_sheet(styles: Vec<(StyleId, Style)>) -> StyleSheet {+ StyleSheet {+ styles: styles.into_iter().collect(),+ ..Default::default()+ }+ }++ fn style(+ based_on: Option<&str>,+ para: Option<ParagraphProperties>,+ run: Option<RunProperties>,+ ) -> Style {+ Style {+ name: None,+ style_type: StyleType::Paragraph,+ based_on: based_on.map(StyleId::new),+ is_default: false,+ paragraph_properties: para,+ run_properties: run,+ table_properties: None,+ table_style_overrides: vec![],+ }+ }++ #[test]+ fn single_style_no_inheritance() {+ let sheet = make_sheet(vec![(+ StyleId::new("Normal"),+ style(+ None,+ Some(ParagraphProperties {+ alignment: Some(Alignment::Start),+ ..Default::default()+ }),+ Some(RunProperties {+ bold: Some(false),+ font_size: Some(Dimension::<HalfPoints>::new(24)),+ ..Default::default()+ }),+ ),+ )]);++ let resolved = resolve_styles(&sheet, None);+ let normal = resolved.get(&StyleId::new("Normal")).unwrap();++ assert_eq!(normal.paragraph.alignment, Some(Alignment::Start));+ assert_eq!(normal.run.bold, Some(false));+ assert_eq!(normal.run.font_size, Some(Dimension::<HalfPoints>::new(24)));+ }++ #[test]+ fn child_inherits_from_parent() {+ let sheet = make_sheet(vec![+ (+ StyleId::new("Normal"),+ style(+ None,+ Some(ParagraphProperties {+ alignment: Some(Alignment::Start),+ ..Default::default()+ }),+ Some(RunProperties {+ font_size: Some(Dimension::<HalfPoints>::new(24)),+ bold: Some(false),+ ..Default::default()+ }),+ ),+ ),+ (+ StyleId::new("Heading1"),+ style(+ Some("Normal"),+ Some(ParagraphProperties {+ alignment: Some(Alignment::Center),+ ..Default::default()+ }),+ Some(RunProperties {+ bold: Some(true),+ ..Default::default()+ }),+ ),+ ),+ ]);++ let resolved = resolve_styles(&sheet, None);+ let h1 = resolved.get(&StyleId::new("Heading1")).unwrap();++ assert_eq!(+ h1.paragraph.alignment,+ Some(Alignment::Center),+ "child overrides parent"+ );+ assert_eq!(h1.run.bold, Some(true), "child overrides parent");+ assert_eq!(+ h1.run.font_size,+ Some(Dimension::<HalfPoints>::new(24)),+ "inherited from Normal"+ );+ }++ #[test]+ fn three_level_chain() {+ let sheet = make_sheet(vec![+ (+ StyleId::new("Base"),+ style(+ None,+ None,+ Some(RunProperties {+ font_size: Some(Dimension::<HalfPoints>::new(20)),+ bold: Some(false),+ italic: Some(false),+ ..Default::default()+ }),+ ),+ ),+ (+ StyleId::new("Mid"),+ style(+ Some("Base"),+ None,+ Some(RunProperties {+ bold: Some(true),+ ..Default::default()+ }),+ ),+ ),+ (+ StyleId::new("Leaf"),+ style(+ Some("Mid"),+ None,+ Some(RunProperties {+ italic: Some(true),+ ..Default::default()+ }),+ ),+ ),+ ]);++ let resolved = resolve_styles(&sheet, None);+ let leaf = resolved.get(&StyleId::new("Leaf")).unwrap();++ assert_eq!(leaf.run.italic, Some(true), "own value");+ assert_eq!(leaf.run.bold, Some(true), "from Mid");+ assert_eq!(+ leaf.run.font_size,+ Some(Dimension::<HalfPoints>::new(20)),+ "from Base"+ );+ }++ #[test]+ fn cycle_does_not_panic() {+ let sheet = make_sheet(vec![+ (+ StyleId::new("A"),+ style(+ Some("B"),+ None,+ Some(RunProperties {+ bold: Some(true),+ ..Default::default()+ }),+ ),+ ),+ (+ StyleId::new("B"),+ style(+ Some("A"),+ None,+ Some(RunProperties {+ italic: Some(true),+ ..Default::default()+ }),+ ),+ ),+ ]);++ // Should not infinite loop or panic+ let resolved = resolve_styles(&sheet, None);+ assert!(resolved.contains_key(&StyleId::new("A")));+ assert!(resolved.contains_key(&StyleId::new("B")));+ }++ #[test]+ fn missing_based_on_target_is_harmless() {+ let sheet = make_sheet(vec![(+ StyleId::new("Orphan"),+ style(+ Some("DoesNotExist"),+ None,+ Some(RunProperties {+ bold: Some(true),+ ..Default::default()+ }),+ ),+ )]);++ let resolved = resolve_styles(&sheet, None);+ let orphan = resolved.get(&StyleId::new("Orphan")).unwrap();+ assert_eq!(orphan.run.bold, Some(true));+ }++ #[test]+ fn doc_defaults_are_applied_as_base() {+ // §17.7.2: doc defaults paragraph properties are NOT merged during+ // style resolution — they are merged by the caller at the correct+ // cascade level. Only run defaults are merged into resolved styles.+ let sheet = StyleSheet {+ doc_defaults_paragraph: ParagraphProperties {+ alignment: Some(Alignment::Both),+ ..Default::default()+ },+ doc_defaults_run: RunProperties {+ font_size: Some(Dimension::<HalfPoints>::new(22)),+ ..Default::default()+ },+ styles: [(StyleId::new("Normal"), style(None, None, None))]+ .into_iter()+ .collect(),+ latent_styles: None,+ };++ let resolved = resolve_styles(&sheet, None);+ let normal = resolved.get(&StyleId::new("Normal")).unwrap();++ // Paragraph doc defaults are deferred to the caller.+ assert_eq!(+ normal.paragraph.alignment, None,+ "paragraph doc defaults are not merged into resolved styles"+ );+ // Run doc defaults ARE merged during resolution.+ assert_eq!(+ normal.run.font_size,+ Some(Dimension::<HalfPoints>::new(22)),+ "should inherit from doc defaults"+ );+ }++ #[test]+ fn style_overrides_doc_defaults() {+ let sheet = StyleSheet {+ doc_defaults_run: RunProperties {+ font_size: Some(Dimension::<HalfPoints>::new(22)),+ bold: Some(false),+ ..Default::default()+ },+ styles: [(+ StyleId::new("Strong"),+ style(+ None,+ None,+ Some(RunProperties {+ bold: Some(true),+ ..Default::default()+ }),+ ),+ )]+ .into_iter()+ .collect(),+ ..Default::default()+ };++ let resolved = resolve_styles(&sheet, None);+ let strong = resolved.get(&StyleId::new("Strong")).unwrap();++ assert_eq!(strong.run.bold, Some(true), "style overrides doc default");+ assert_eq!(+ strong.run.font_size,+ Some(Dimension::<HalfPoints>::new(22)),+ "inherited from doc default"+ );+ }++ // ── §17.7.4.9 ToC entry detection ────────────────────────────────────++ /// A paragraph style carrying a primary style name.+ fn named_style(name: &str, based_on: Option<&str>) -> Style {+ Style {+ name: Some(name.to_string()),+ ..style(based_on, None, None)+ }+ }++ #[test]+ fn toc_entry_names_are_levels_one_through_nine() {+ for level in 1..=9 {+ assert!(+ is_toc_entry_name(&format!("toc {level}")),+ "toc {level} is an entry style"+ );+ }+ // OOXML style names compare case-insensitively.+ assert!(is_toc_entry_name("TOC 3"));+ assert!(is_toc_entry_name("Toc 3"));+ }++ #[test]+ fn non_entry_toc_names_are_rejected() {+ for name in [+ "TOC Heading", // the heading above a ToC, not an entry+ "toc", // no level+ "toc 0", // levels are 1..=9+ "toc 10",+ "toc 1x",+ "table of contents",+ "TOCustom", // the false positive the old styleId prefix test hit+ "",+ ] {+ assert!(+ !is_toc_entry_name(name),+ "{name:?} is not a ToC entry style"+ );+ }+ }++ /// The signal is the primary style **name**, not the `w:styleId` spelling:+ /// a producer may use any ID, and Word writes the locale-independent+ /// built-in name regardless of UI language.+ #[test]+ fn toc_entry_is_detected_from_name_not_style_id() {+ let sheet = make_sheet(vec![+ // Localized/arbitrary ID, built-in ToC name → is an entry.+ (StyleId::new("Verzeichnis1"), named_style("toc 1", None)),+ // TOC-prefixed ID, unrelated name → is NOT an entry.+ (StyleId::new("TOCustom"), named_style("My Custom", None)),+ // The ToC heading is not an entry.+ (StyleId::new("TOCHeading"), named_style("TOC Heading", None)),+ ]);+ let resolved = resolve_styles(&sheet, None);++ assert!(+ resolved[&StyleId::new("Verzeichnis1")].is_toc_entry,+ "a localized style ID with the built-in toc name is an entry"+ );+ assert!(+ !resolved[&StyleId::new("TOCustom")].is_toc_entry,+ "a TOC-prefixed ID with an unrelated name is not an entry"+ );+ assert!(+ !resolved[&StyleId::new("TOCHeading")].is_toc_entry,+ "the ToC heading is not an entry"+ );+ }++ #[test]+ fn toc_entry_is_inherited_through_based_on() {+ let sheet = make_sheet(vec![+ (StyleId::new("TOC2"), named_style("toc 2", None)),+ (StyleId::new("MyToc"), named_style("My ToC", Some("TOC2"))),+ (StyleId::new("Deeper"), named_style("Deeper", Some("MyToc"))),+ (StyleId::new("Unrelated"), named_style("Body", None)),+ ]);+ let resolved = resolve_styles(&sheet, None);++ assert!(resolved[&StyleId::new("MyToc")].is_toc_entry, "one hop");+ assert!(resolved[&StyleId::new("Deeper")].is_toc_entry, "two hops");+ assert!(!resolved[&StyleId::new("Unrelated")].is_toc_entry);+ }+}diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.tomlindex 110e5ee..dd37a9a 100644--- a/crates/liteparse/Cargo.toml+++ b/crates/liteparse/Cargo.toml@@ -14,6 +14,10 @@ name = "liteparse"name = "lit"path = "src/main.rs"+[[example]]+name = "docx_blocks"+required-features = ["docx-native"]+[features]default = ["tesseract"]oar-ocr = ["dep:oar-ocr"]@@ -25,11 +29,14 @@ oar-ocr-coreml = ["oar-ocr", "oar-ocr/coreml"]oar-ocr-webgpu = ["oar-ocr", "oar-ocr/webgpu"]oar-ocr-openvino = ["oar-ocr", "oar-ocr/openvino"]tesseract = ["dep:tesseract-rs"]+# Native DOCX structure reading (no LibreOffice, no projection).+docx-native = ["dep:liteparse-docx"][dependencies]blake3 = "1"clap = { version = "4.5.55", features = ["derive"] }file-format = { version = "0.29.0", features = ["reader"] }+liteparse-docx = { version = "0.1.0", path = "../liteparse-docx", optional = true }image = { version = "0.25", default-features = false, features = ["default-formats"] }memchr = "2"ordered-float = "5.3.0"diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rsindex 551c7ee..ca5390a 100644--- a/crates/liteparse/src/lib.rs+++ b/crates/liteparse/src/lib.rs@@ -45,8 +45,11 @@ pub mod glyph_names;pub mod markdown_layout;#[doc(hidden)]pub mod ocr;+#[doc(hidden)]pub mod ocr_merge;+/// Native readers for office formats (DOCX today), bypassing LibreOffice.+pub mod office;#[doc(hidden)]pub mod output;#[doc(hidden)]diff --git a/crates/liteparse/src/markdown_layout/blocks.rs b/crates/liteparse/src/markdown_layout/blocks.rsindex be06fee..e58a5f8 100644--- a/crates/liteparse/src/markdown_layout/blocks.rs+++ b/crates/liteparse/src/markdown_layout/blocks.rs@@ -39,6 +39,20 @@ pub enum Block {header: Option<Vec<String>>,rows: Vec<Vec<String>>,},+ /// Table whose cells carry explicit spans. Emitted by producers that know+ /// the merge structure outright (the native office path reads `gridSpan` /+ /// `vMerge` from the DOCX) rather than inferring it from coordinates.+ ///+ /// `rows` is *not* rectangular: a cell absorbed by a neighbour's+ /// `colspan`/`rowspan` is omitted entirely, exactly as in HTML. `header_rows`+ /// is the count of leading rows that are header rows (`<th>`); 0 means none.+ ///+ /// Renders as a GFM pipe table when it degenerates to a plain grid, and as+ /// HTML `<table>` otherwise — pipe tables cannot express spans at all.+ MergedTable {+ rows: Vec<Vec<Cell>>,+ header_rows: usize,+ },/// Tabular-looking region we couldn't classify confidently — rendered/// verbatim inside a fenced block to preserve visual structure for the/// downstream LLM. Strictly better than emitting a mangled pipe table.@@ -56,6 +70,54 @@ pub enum Block {},}+/// One cell of a [`Block::MergedTable`]. `colspan`/`rowspan` are 1 for an+/// ordinary cell; the cells they cover are absent from `rows` rather than+/// present-and-empty, matching HTML's occupancy model.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Cell {+ pub text: String,+ pub colspan: u16,+ pub rowspan: u16,+}++impl Cell {+ /// A plain 1x1 cell.+ pub fn new(text: impl Into<String>) -> Self {+ Self {+ text: text.into(),+ colspan: 1,+ rowspan: 1,+ }+ }++ /// A cell spanning `colspan` columns and `rowspan` rows. Zero is coerced to+ /// 1 — a zero span is meaningless in HTML and `rowspan="0"` means "to the+ /// end of the section", which is not what any producer here intends.+ pub fn spanning(text: impl Into<String>, colspan: u16, rowspan: u16) -> Self {+ Self {+ text: text.into(),+ colspan: colspan.max(1),+ rowspan: rowspan.max(1),+ }+ }++ fn is_plain(&self) -> bool {+ self.colspan <= 1 && self.rowspan <= 1+ }+}++impl From<&str> for Cell {+ fn from(s: &str) -> Self {+ Cell::new(s)+ }+}++impl From<String> for Cell {+ fn from(s: String) -> Self {+ Cell::new(s)+ }+}+/// Resolve a `ParaAccum` to a `Block::Paragraph`. When the paragraph was/// uniformly styled across all lines, return the raw text with block-level/// `bold`/`italic` flags set so the renderer wraps it once. Otherwise return@@ -96,6 +158,97 @@ fn wrap_emphasis(text: &str, bold: bool, italic: bool) -> String {}}+/// Render a GFM pipe table. `head` is the header row (already chosen by the+/// caller); `body` the remaining rows. No-ops when there are no columns.+fn render_pipe_table(head: Option<&[String]>, body: &[Vec<String>], out: &mut String) {+ let column_count = head.map(|h| h.len()).unwrap_or(0);+ if column_count == 0 {+ return;+ }+ out.push_str("| ");+ for (i, cell) in head.unwrap().iter().enumerate() {+ if i > 0 {+ out.push_str(" | ");+ }+ out.push_str(&escape_table_cell(cell));+ }+ out.push_str(" |\n");+ out.push('|');+ for _ in 0..column_count {+ out.push_str("---|");+ }+ for row in body {+ out.push_str("\n| ");+ for (i, cell) in row.iter().enumerate() {+ if i > 0 {+ out.push_str(" | ");+ }+ out.push_str(&escape_table_cell(cell));+ }+ out.push_str(" |");+ }+}++/// Escape a cell for HTML `<td>` content. Markdown specials are deliberately+/// left alone — inside an HTML block they are literal text, and escaping them+/// would surface backslashes in the rendered output.+fn escape_html_cell(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for c in s.chars() {+ match c {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '\n' => out.push(' '),+ _ => out.push(c),+ }+ }+ out+}++/// True when a merged table degenerates to a plain rectangular grid, in which+/// case the pipe rendering is both valid and nicer to read.+fn is_plain_grid(rows: &[Vec<Cell>], header_rows: usize) -> bool {+ // GFM has exactly one header row, or none.+ if header_rows > 1 {+ return false;+ }+ if !rows.iter().all(|r| r.iter().all(Cell::is_plain)) {+ return false;+ }+ // Ragged rows can only have come from spans we've just ruled out, but check+ // anyway: a pipe table with uneven rows renders as a broken table.+ let width = rows.first().map(|r| r.len()).unwrap_or(0);+ rows.iter().all(|r| r.len() == width)+}++/// Render a merged table as HTML. Cells covered by a neighbour's span are+/// simply absent from `rows`, so this is a direct transcription.+fn render_html_table(rows: &[Vec<Cell>], header_rows: usize, out: &mut String) {+ out.push_str("<table>");+ for (r, row) in rows.iter().enumerate() {+ out.push_str("\n<tr>");+ let tag = if r < header_rows { "th" } else { "td" };+ for cell in row {+ out.push_str("\n<");+ out.push_str(tag);+ if cell.colspan > 1 {+ out.push_str(&format!(" colspan=\"{}\"", cell.colspan));+ }+ if cell.rowspan > 1 {+ out.push_str(&format!(" rowspan=\"{}\"", cell.rowspan));+ }+ out.push('>');+ out.push_str(&escape_html_cell(&cell.text));+ out.push_str("</");+ out.push_str(tag);+ out.push('>');+ }+ out.push_str("\n</tr>");+ }+ out.push_str("\n</table>");+}+/// Render a list of blocks to a markdown string.pub fn render_blocks(blocks: &[Block]) -> String {let mut out = String::new();@@ -181,31 +334,30 @@ pub fn render_blocks(blocks: &[Block]) -> String {None => (None, rows.as_slice()),},};- let column_count = head.map(|h| h.len()).unwrap_or(0);- if column_count == 0 {+ render_pipe_table(head, body, &mut out);+ }+ Block::MergedTable { rows, header_rows } => {+ if rows.is_empty() {continue;}- out.push_str("| ");- for (i, cell) in head.unwrap().iter().enumerate() {- if i > 0 {- out.push_str(" | ");- }- out.push_str(&escape_table_cell(cell));- }- out.push_str(" |\n");- out.push('|');- for _ in 0..column_count {- out.push_str("---|");- }- for row in body {- out.push_str("\n| ");- for (i, cell) in row.iter().enumerate() {- if i > 0 {- out.push_str(" | ");- }- out.push_str(&escape_table_cell(cell));- }- out.push_str(" |");+ if is_plain_grid(rows, *header_rows) {+ // Degenerate case — no merges, so pipes are expressive+ // enough. Reuse the exact same rendering the PDF path gets,+ // including the promote-first-row-when-headerless rule.+ let plain: Vec<Vec<String>> = rows+ .iter()+ .map(|r| r.iter().map(|c| c.text.clone()).collect())+ .collect();+ // `header_rows` is 0 or 1 here (>1 forces HTML). Either way+ // the first row leads: as the real header, or promoted into+ // one because GFM has no headerless table.+ let (head, body) = match plain.split_first() {+ Some((first, rest)) => (Some(first.as_slice()), rest),+ None => (None, plain.as_slice()),+ };+ render_pipe_table(head, body, &mut out);+ } else {+ render_html_table(rows, *header_rows, &mut out);}}Block::GridFallback { lines } => {@@ -389,6 +541,90 @@ mod tests {assert_eq!(s, "a -\n\ndash line");}+ #[test]+ fn merged_table_without_spans_renders_as_pipes() {+ // A merge-aware producer that happens to emit a plain grid must be+ // byte-identical to the PDF path's pipe table — otherwise the same+ // table looks different depending on which pipeline produced it.+ let plain = Block::Table {+ header: Some(vec!["a".into(), "b".into()]),+ rows: vec![vec!["1".into(), "2".into()]],+ };+ let merged = Block::MergedTable {+ header_rows: 1,+ rows: vec![+ vec![Cell::new("a"), Cell::new("b")],+ vec![Cell::new("1"), Cell::new("2")],+ ],+ };+ assert_eq!(render_blocks(&[plain]), render_blocks(&[merged]));+ }++ #[test]+ fn merged_table_with_spans_renders_as_html() {+ // Cells covered by a span are absent, not empty — row 1 has one cell.+ let s = render_blocks(&[Block::MergedTable {+ header_rows: 1,+ rows: vec![+ vec![Cell::spanning("wide", 2, 1)],+ vec![Cell::spanning("tall", 1, 2), Cell::new("x")],+ vec![Cell::new("y")],+ ],+ }]);+ assert_eq!(+ s,+ "<table>\n<tr>\n<th colspan=\"2\">wide</th>\n</tr>\n\+ <tr>\n<td rowspan=\"2\">tall</td>\n<td>x</td>\n</tr>\n\+ <tr>\n<td>y</td>\n</tr>\n</table>"+ );+ }++ #[test]+ fn merged_table_escapes_html_not_markdown() {+ // Inside an HTML block, markdown specials are literal; `<` is not.+ let s = render_blocks(&[Block::MergedTable {+ header_rows: 0,+ rows: vec![vec![Cell::new("a|b *c* <d> &e"), Cell::spanning("f", 2, 1)]],+ }]);+ assert!(s.contains("<td>a|b *c* <d> &e</td>"), "{s}");+ }++ #[test]+ fn merged_table_multiple_header_rows_force_html() {+ // Two header rows have no pipe-table representation even with no spans.+ let s = render_blocks(&[Block::MergedTable {+ header_rows: 2,+ rows: vec![+ vec![Cell::new("a"), Cell::new("b")],+ vec![Cell::new("c"), Cell::new("d")],+ vec![Cell::new("1"), Cell::new("2")],+ ],+ }]);+ assert!(s.starts_with("<table>"), "{s}");+ assert_eq!(s.matches("<th>").count(), 4);+ assert_eq!(s.matches("<td>").count(), 2);+ }++ #[test]+ fn merged_table_ragged_rows_force_html() {+ // Uneven row widths with no declared spans would render as a broken+ // pipe table; HTML at least preserves the cells.+ let s = render_blocks(&[Block::MergedTable {+ header_rows: 1,+ rows: vec![vec![Cell::new("a"), Cell::new("b")], vec![Cell::new("1")]],+ }]);+ assert!(s.starts_with("<table>"), "{s}");+ }++ #[test]+ fn zero_span_is_coerced_to_one() {+ // `rowspan="0"` means "to the end of the section" in HTML — never what+ // a producer means here, so it must not survive into the output.+ let c = Cell::spanning("x", 0, 0);+ assert_eq!((c.colspan, c.rowspan), (1, 1));+ assert!(c.is_plain());+ }+#[test]fn render_table_without_header_promotes_first_row() {let blocks = vec![Block::Table {diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rsindex e3751a5..63d783f 100644--- a/crates/liteparse/src/markdown_layout/inline.rs+++ b/crates/liteparse/src/markdown_layout/inline.rs@@ -30,7 +30,7 @@ impl SpanStyle {/// Escape characters that would otherwise be interpreted as markdown emphasis./// Deliberately narrow: only `*`, `_`, and backslash. Aggressive escaping/// (`#`, `[`, backticks, etc.) breaks more output than it saves in practice.-pub(super) fn escape_inline(s: &str) -> String {+pub fn escape_inline(s: &str) -> String {let mut out = String::with_capacity(s.len());for c in s.chars() {match c {diff --git a/crates/liteparse/src/markdown_layout/mod.rs b/crates/liteparse/src/markdown_layout/mod.rsindex 80fe019..8f6bccb 100644--- a/crates/liteparse/src/markdown_layout/mod.rs+++ b/crates/liteparse/src/markdown_layout/mod.rs@@ -18,9 +18,10 @@ mod paragraphs;mod repetition;mod tables;-pub use blocks::{Block, render_blocks};+pub use blocks::{Block, Cell, render_blocks};pub use classify::classify_page_with_filters;pub use headings::{build_heading_map, compute_body_size};+pub use inline::escape_inline;pub use repetition::{compute_header_footer_set, detect_single_page_chrome};pub use tables::detect_table_rects;pub(crate) use tables::{count_text_table_runs, validated_ruled_table_rects};diff --git a/crates/liteparse/src/office/docx.rs b/crates/liteparse/src/office/docx.rsnew file mode 100644index 0000000..175a85b--- /dev/null+++ b/crates/liteparse/src/office/docx.rs@@ -0,0 +1,573 @@+//! DOCX → [`Block`] using only `liteparse-docx`'s `parse` + `resolve` stages.+//!+//! Deliberately avoids the vendored crate's `render::layout` stage: structure+//! alone — headings, lists, emphasis, merged cells, notes — is recoverable+//! without a layout engine, and layout is where the font/measurement+//! dependencies live. Geometry is a separate concern (see `NATIVE_OFFICE_PLAN.md`+//! stage 2); this module produces no bounding boxes.+//!+//! What `resolve()` hands us is *not* fully cascaded: it walks `basedOn` chains+//! and flattens numbering (including `lvlOverride`/`startOverride`), but leaves+//! the per-run merge to the caller. That merge is [`Emitter::effective_fmt`].++use std::collections::HashMap;++use liteparse_docx::model::{+ Block as DocxBlock, Inline, NoteId, NumId, NumberFormat, OutlineLevel, Paragraph,+ ParagraphProperties, RunElement, RunProperties, StrikeStyle, StyleId, Table, VerticalMerge,+};+use liteparse_docx::render::resolve::ResolvedDocument;++use crate::error::LiteParseError;+use crate::markdown_layout::{Block, Cell, escape_inline};++/// Parse a DOCX and emit the shared block model.+///+/// Errors only when the archive itself is unreadable — the vendored parser is+/// fail-open on unknown elements, unknown attribute values and malformed+/// scalars, so a document with unmodeled markup still yields blocks.+pub fn docx_to_blocks(data: &[u8]) -> Result<Vec<Block>, LiteParseError> {+ let parsed = liteparse_docx::docx::parse(data)+ .map_err(|e| LiteParseError::Conversion(format!("docx parse failed: {e}")))?;+ let resolved = liteparse_docx::render::resolve::resolve(parsed);+ Ok(emit(&resolved))+}++/// Emit blocks for an already-resolved document.+pub fn emit(doc: &ResolvedDocument) -> Vec<Block> {+ let body: Vec<DocxBlock> = doc+ .sections+ .iter()+ .flat_map(|s| s.blocks.iter().cloned())+ .collect();++ let mut em = Emitter::new(doc);+ let mut out = Vec::new();+ em.blocks(&body, &mut out);++ // Note bodies are appended after the document, behind a rule. Emit *all* of+ // them, not just those whose reference we walked past: notes are frequently+ // referenced from headers, footers and textboxes, and content-completeness+ // is what matters here (spike 4 measured `present` 0.568 → 0.921 from this+ // one choice). Note ids 0 and 1 are the separator and continuationSeparator+ // — chrome, never real content.+ let mut notes = Vec::new();+ for map in [&doc.footnotes, &doc.endnotes] {+ let mut ids: Vec<NoteId> = map.keys().copied().filter(|i| i.value() > 1).collect();+ ids.sort_by_key(|i| i.value());+ for id in ids {+ em.blocks(&map[&id], &mut notes);+ }+ }+ if !notes.is_empty() {+ out.push(Block::HorizontalRule);+ out.extend(notes);+ }+ out+}++/// Effective character formatting after the style cascade is applied.+#[derive(Default, Clone, Copy, PartialEq)]+struct Fmt {+ bold: bool,+ italic: bool,+ strike: bool,+}++impl Fmt {+ fn is_plain(self) -> bool {+ !self.bold && !self.italic && !self.strike+ }+}++struct Emitter<'a> {+ doc: &'a ResolvedDocument,+ /// `(numId, level)` → next counter, so ordered lists number correctly and+ /// a list interrupted by prose continues its count.+ counters: HashMap<(i64, u8), u32>,+ /// True while emitting the content of a table cell. Cell text must stay+ /// *unescaped*: `render_blocks` escapes it per dialect on the way out (`|`+ /// for pipe tables, `&<>` for HTML), and markdown-escaping it here would+ /// either double the backslashes (`\\*`) or surface them literally inside+ /// an HTML block, where markdown escapes mean nothing.+ in_cell: bool,+}++impl<'a> Emitter<'a> {+ fn new(doc: &'a ResolvedDocument) -> Self {+ Self {+ doc,+ counters: HashMap::new(),+ in_cell: false,+ }+ }++ fn style_run(&self, id: Option<&StyleId>) -> Option<&RunProperties> {+ let id = id.or(self.doc.default_paragraph_style_id.as_ref())?;+ self.doc.styles.get(id).map(|s| &s.run)+ }++ fn style_para(&self, id: Option<&StyleId>) -> Option<&ParagraphProperties> {+ let id = id.or(self.doc.default_paragraph_style_id.as_ref())?;+ self.doc.styles.get(id).map(|s| &s.paragraph)+ }++ /// The cascade `resolve()` intentionally leaves to the caller:+ /// doc defaults → paragraph style → run's character style → direct.+ ///+ /// `Option<bool>` distinguishes "inherit" (`None`) from "explicitly off"+ /// (`Some(false)`), so a `NotBold` character style correctly overrides a+ /// bold paragraph style rather than being ignored.+ fn effective_fmt(+ &self,+ para: &Paragraph,+ run_style: Option<&StyleId>,+ direct: &RunProperties,+ ) -> Fmt {+ let mut bold = self.doc.doc_defaults_run.bold;+ let mut italic = self.doc.doc_defaults_run.italic;+ let mut strike = self.doc.doc_defaults_run.strike;++ let mut apply = |p: &RunProperties| {+ if p.bold.is_some() {+ bold = p.bold;+ }+ if p.italic.is_some() {+ italic = p.italic;+ }+ if p.strike.is_some() {+ strike = p.strike;+ }+ };++ if let Some(r) = self.style_run(para.style_id.as_ref()) {+ apply(r);+ }+ if let Some(s) = run_style.and_then(|id| self.doc.styles.get(id)) {+ apply(&s.run);+ }+ apply(direct);++ Fmt {+ bold: bold.unwrap_or(false),+ italic: italic.unwrap_or(false),+ strike: !matches!(strike.unwrap_or(StrikeStyle::None), StrikeStyle::None),+ }+ }++ /// Escape markdown specials unless we are inside a table cell.+ fn escape(&self, s: &str) -> String {+ if self.in_cell {+ s.to_string()+ } else {+ escape_inline(s)+ }+ }++ /// Cascade the two paragraph-level facts this emitter reads. Direct+ /// formatting wins; the paragraph style fills in what it leaves unset.+ fn para_props(&self, para: &Paragraph) -> ParagraphProperties {+ let mut out = para.properties.clone();+ if let Some(sp) = self.style_para(para.style_id.as_ref()) {+ if out.outline_level.is_none() {+ out.outline_level = sp.outline_level;+ }+ if out.numbering.is_none() {+ out.numbering = sp.numbering;+ }+ }+ out+ }++ /// Flatten a paragraph's inlines into formatting-tagged text chunks, in+ /// document order.+ fn chunks(&self, para: &Paragraph, content: &[Inline]) -> Vec<(Fmt, String)> {+ let mut out = Vec::new();+ self.collect(para, content, &mut out);+ out+ }++ fn collect(&self, para: &Paragraph, content: &[Inline], out: &mut Vec<(Fmt, String)>) {+ for inline in content {+ match inline {+ Inline::TextRun(run) => {+ let fmt = self.effective_fmt(para, run.style_id.as_ref(), &run.properties);+ let mut text = String::new();+ for el in &run.content {+ match el {+ RunElement::Text(t) => text.push_str(t),+ // A tab or a break inside a paragraph is a+ // *within-line* separator once the paragraph+ // becomes one markdown line; a space is the only+ // faithful rendering.+ RunElement::Tab | RunElement::LineBreak(_) => text.push(' '),+ _ => {}+ }+ }+ if !text.is_empty() {+ out.push((fmt, text));+ }+ }+ Inline::Hyperlink(h) => self.collect(para, &h.content, out),+ Inline::Field(f) => self.collect(para, &f.content, out),+ _ => {}+ }+ }+ }++ fn paragraph(&mut self, para: &Paragraph, out: &mut Vec<Block>) {+ let props = self.para_props(para);+ let chunks = self.chunks(para, ¶.content);+ if chunks.iter().all(|(_, t)| t.trim().is_empty()) {+ return;+ }++ // Headings win over list formatting: a numbered heading is a heading.+ if let Some(lvl) = props.outline_level {+ // Deliberately plain — no `**` inside the `#`. The `#` *is* the+ // emphasis, and `# **Heading**` is redundant markup.+ let text: String = chunks.iter().map(|(_, t)| t.as_str()).collect();+ out.push(Block::Heading {+ // Emitted as declared. A dense 1..N remap was measured on the+ // 48-doc corpus and lost 39 of 66 heading rules; see the+ // "heading levels" note in NATIVE_OFFICE_PLAN.md.+ level: OutlineLevel::value(lvl).clamp(1, 6) as u8,+ text: self.escape(text.trim()),+ });+ return;+ }++ let (text, bold, italic) = render_chunks(&chunks, !self.in_cell);++ if let Some(nref) = props.numbering {+ let level = self+ .doc+ .numbering+ .get(&NumId::new(nref.num_id))+ .and_then(|lv| lv.get(nref.level as usize));+ let ordered = !matches!(level.map(|l| l.format), Some(NumberFormat::Bullet) | None);+ let marker = if ordered {+ let start = level.map(|l| l.start).unwrap_or(1);+ let key = (nref.num_id, nref.level);+ let n = *self+ .counters+ .entry(key)+ .and_modify(|c| *c += 1)+ .or_insert(start);+ // Deeper levels restart once a shallower one advances.+ self.counters+ .retain(|(id, l), _| !(*id == nref.num_id && *l > nref.level));+ format!("{n}.")+ } else {+ // `render_blocks` prints `- ` for unordered items and ignores+ // this, but keep it meaningful rather than empty.+ "-".to_string()+ };+ out.push(Block::ListItem {+ ordered,+ marker,+ level: nref.level,+ text,+ bold,+ italic,+ });+ return;+ }++ out.push(Block::Paragraph { text, bold, italic });+ }++ /// Emit a table as [`Block::MergedTable`], which is the whole point of the+ /// native path: `gridSpan` and `vMerge` are explicit in the source, so the+ /// merge structure is read rather than inferred from cell coordinates.+ fn table(&mut self, table: &Table, out: &mut Vec<Block>) {+ // Grid column of each cell, so a vMerge run can be matched down a+ // column even when rows have different cell counts.+ let mut cols: Vec<Vec<u32>> = Vec::new();+ for row in &table.rows {+ let mut c = row.properties.grid_before;+ let mut rc = Vec::new();+ for cell in &row.cells {+ rc.push(c);+ c += cell.properties.grid_span.unwrap_or(1);+ }+ cols.push(rc);+ }++ // Row extent of each vMerge=Restart cell: how many following rows carry+ // a Continue cell in the same grid column.+ let mut rowspans: Vec<Vec<u16>> =+ table.rows.iter().map(|r| vec![1; r.cells.len()]).collect();+ for r in 0..table.rows.len() {+ for c in 0..table.rows[r].cells.len() {+ if table.rows[r].cells[c].properties.vertical_merge != Some(VerticalMerge::Restart)+ {+ continue;+ }+ let col = cols[r][c];+ let mut n: u16 = 1;+ for r2 in r + 1..table.rows.len() {+ let continues = table.rows[r2]+ .cells+ .iter()+ .zip(&cols[r2])+ .any(|(cell, cc)| {+ *cc == col+ && cell.properties.vertical_merge == Some(VerticalMerge::Continue)+ });+ if !continues {+ break;+ }+ n += 1;+ }+ rowspans[r][c] = n;+ }+ }++ let mut rows: Vec<Vec<Cell>> = Vec::new();+ for (r, row) in table.rows.iter().enumerate() {+ let mut cells = Vec::new();+ for (c, cell) in row.cells.iter().enumerate() {+ // Continuation cells are absorbed into the restart cell's+ // rowspan and are absent from the grid, matching HTML.+ if cell.properties.vertical_merge == Some(VerticalMerge::Continue) {+ continue;+ }+ cells.push(Cell::spanning(+ self.cell_text(&cell.content),+ cell.properties.grid_span.unwrap_or(1) as u16,+ rowspans[r][c],+ ));+ }+ rows.push(cells);+ }++ // `header_rows` is a count of *leading* header rows. A `tblHeader` flag+ // deeper in the table marks a repeat-on-page-break row, which is not a+ // header in any markup we emit, so stop at the first non-header row.+ let header_rows = table+ .rows+ .iter()+ .take_while(|r| r.properties.is_header.unwrap_or(false))+ .count();++ if rows.iter().any(|r| !r.is_empty()) {+ out.push(Block::MergedTable { rows, header_rows });+ }+ }++ /// Flatten a cell's block content to a single line of inline markdown.+ ///+ /// A cell is a `Vec<Block>` in DOCX (it can hold paragraphs, lists, even+ /// nested tables) but both of our table renderings are single-line per+ /// cell, so the content is collapsed. Text is left *unescaped*: the+ /// renderer escapes per dialect (`|` for pipes, `&<>` for HTML), and+ /// escaping here would double up.+ fn cell_text(&mut self, content: &[DocxBlock]) -> String {+ let outer = std::mem::replace(&mut self.in_cell, true);+ let mut inner = Vec::new();+ self.blocks(content, &mut inner);+ self.in_cell = outer;+ let mut parts: Vec<String> = Vec::new();+ for b in &inner {+ match b {+ Block::Heading { text, .. } | Block::Paragraph { text, .. } => {+ parts.push(text.clone())+ }+ Block::ListItem { text, .. } => parts.push(text.clone()),+ _ => {}+ }+ }+ parts+ .join(" ")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+ }++ fn blocks(&mut self, blocks: &[DocxBlock], out: &mut Vec<Block>) {+ for b in blocks {+ match b {+ DocxBlock::Paragraph(p) => self.paragraph(p, out),+ DocxBlock::Table(t) => self.table(t, out),+ DocxBlock::SectionBreak(_) => {}+ }+ }+ }+}++/// Render formatting-tagged chunks to the `(text, bold, italic)` shape+/// `Block::Paragraph` and `Block::ListItem` expect.+///+/// When every chunk shares one plain-or-emphasised style the block-level flags+/// carry it and the text stays clean; otherwise emphasis is baked inline and+/// the flags are cleared. This mirrors `paragraph_from_accum` on the PDF path,+/// so the same prose looks the same whichever pipeline produced it.+fn render_chunks(chunks: &[(Fmt, String)], escape: bool) -> (String, bool, bool) {+ // Coalesce adjacent runs that share formatting first. Word splits a run at+ // every property change, including ones that don't survive the cascade+ // (language, spell-check state, rsid), so a single bold phrase routinely+ // arrives as several identically-formatted chunks. Emitting each one+ // separately would produce `**a****b**`, which no markdown parser reads as+ // one bold span.+ let mut merged: Vec<(Fmt, String)> = Vec::new();+ for (fmt, text) in chunks {+ match merged.last_mut() {+ Some((prev, buf)) if prev == fmt => buf.push_str(text),+ _ => merged.push((*fmt, text.clone())),+ }+ }+ let chunks = &merged[..];++ let uniform = chunks.first().map(|(f, _)| *f).filter(|f| {+ // Strike has no block-level flag, so a uniformly-struck paragraph still+ // takes the inline path.+ !f.strike && chunks.iter().all(|(g, _)| g == f)+ });++ if let Some(fmt) = uniform {+ let raw: String = chunks.iter().map(|(_, t)| t.as_str()).collect();+ let raw = raw.trim();+ let text = if escape {+ escape_inline(raw)+ } else {+ raw.to_string()+ };+ return (text, fmt.bold, fmt.italic);+ }++ let mut out = String::new();+ for (fmt, text) in chunks {+ // Emphasis markers must hug non-space content to be valid markdown, so+ // surrounding whitespace is hoisted outside the markers.+ let lead: String = text.chars().take_while(|c| c.is_whitespace()).collect();+ let core = text.trim();+ let trail = if core.is_empty() {+ String::new()+ } else {+ text.chars()+ .rev()+ .take_while(|c| c.is_whitespace())+ .collect::<Vec<_>>()+ .into_iter()+ .rev()+ .collect()+ };++ out.push_str(&lead);+ if core.is_empty() {+ continue;+ }+ let escaped = if escape {+ escape_inline(core)+ } else {+ core.to_string()+ };+ if fmt.is_plain() {+ out.push_str(&escaped);+ } else {+ let (mut open, mut close) = (String::new(), String::new());+ if fmt.bold {+ open.push_str("**");+ close.insert_str(0, "**");+ }+ if fmt.italic {+ open.push('*');+ close.insert(0, '*');+ }+ if fmt.strike {+ open.push_str("~~");+ close.insert_str(0, "~~");+ }+ out.push_str(&open);+ out.push_str(&escaped);+ out.push_str(&close);+ }+ out.push_str(&trail);+ }+ (out.trim().to_string(), false, false)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fmt(bold: bool, italic: bool, strike: bool) -> Fmt {+ Fmt {+ bold,+ italic,+ strike,+ }+ }++ fn chunks(v: &[(Fmt, &str)]) -> Vec<(Fmt, String)> {+ v.iter().map(|(f, t)| (*f, t.to_string())).collect()+ }++ #[test]+ fn uniform_emphasis_becomes_block_flags() {+ let (text, bold, italic) =+ render_chunks(&chunks(&[(fmt(true, false, false), "all bold")]), true);+ assert_eq!((text.as_str(), bold, italic), ("all bold", true, false));+ }++ #[test]+ fn mixed_emphasis_is_baked_inline_and_flags_cleared() {+ let (text, bold, italic) = render_chunks(+ &chunks(&[+ (fmt(false, false, false), "plain "),+ (fmt(true, false, false), "bold"),+ ]),+ true,+ );+ assert_eq!(+ (text.as_str(), bold, italic),+ ("plain **bold**", false, false)+ );+ }++ /// `Block` has no strike flag, so a uniformly-struck paragraph must take+ /// the inline path rather than silently losing the strikethrough.+ #[test]+ fn uniform_strike_falls_back_to_inline() {+ let (text, bold, italic) =+ render_chunks(&chunks(&[(fmt(false, false, true), "gone")]), true);+ assert_eq!((text.as_str(), bold, italic), ("~~gone~~", false, false));+ }++ /// Markers must hug non-space content or markdown won't parse them, so+ /// whitespace inside a run is hoisted outside the markers.+ #[test]+ fn markers_hug_content_across_run_whitespace() {+ let (text, ..) = render_chunks(+ &chunks(&[+ (fmt(true, false, false), "bold "),+ (fmt(false, false, false), "tail"),+ ]),+ true,+ );+ assert_eq!(text, "**bold** tail");+ }++ #[test]+ fn escaping_is_skipped_for_cell_content() {+ let c = chunks(&[(fmt(false, false, false), "a_b*c")]);+ assert_eq!(render_chunks(&c, true).0, "a\\_b\\*c");+ // Inside a cell the renderer escapes per dialect; escaping here would+ // double the backslash in a pipe table and surface it in HTML.+ assert_eq!(render_chunks(&c, false).0, "a_b*c");+ }++ #[test]+ fn adjacent_runs_sharing_format_do_not_split_markers() {+ let (text, ..) = render_chunks(+ &chunks(&[+ (fmt(true, false, false), "a"),+ (fmt(true, false, false), "b"),+ (fmt(false, false, false), "!"),+ ]),+ true,+ );+ assert_eq!(text, "**ab**!");+ }+}diff --git a/crates/liteparse/src/office/mod.rs b/crates/liteparse/src/office/mod.rsnew file mode 100644index 0000000..1db846b--- /dev/null+++ b/crates/liteparse/src/office/mod.rs@@ -0,0 +1,14 @@+//! Native office-format readers.+//!+//! These bypass the LibreOffice→PDF→projection pipeline entirely. Office+//! formats carry explicit structure (heading levels, list numbering, merged+//! table cells, notes) that rendering to PDF destroys and projection then has+//! to reverse-engineer from coordinates. Reading it directly is both faster and+//! strictly more faithful.+//!+//! Each reader emits [`markdown_layout::Block`](crate::markdown_layout::Block),+//! the same model the PDF path produces, so `render_blocks` and every+//! text-level heuristic downstream are shared between the two pipelines.++#[cfg(feature = "docx-native")]+pub mod docx;