From 5f453efa9ad7e803f65c3edc7e08992d43422c23 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Sun, 15 Nov 2026 20:10:47 +0100 Subject: [PATCH 01/15] craft-docx: a relativeHeight of 0 stays the lowest stacking order Float::z kept relativeHeight as read, so a file's 0, the lowest order a file can give, read as 0, "none", which stacks above every object. z is now one more than the file's (as ODF's draw:z-index is read), and Float::stack gives the stacking key. The writer writes stored orders one less, numbers objects made in the app above every stored one, and numbers the stored ones again from Word's first order when u32::MAX leaves no room above them. Document::stacking_orders counts every story saved with the document, the glossary's building blocks included. Moved from storytold/wordcraft#2655 (wordcraft#2638), whose DOCX reader and writer now live here. --- crates/docx/src/read/story/drawing.rs | 5 +- crates/docx/src/write.rs | 24 +++++++ crates/docx/src/write/parts.rs | 4 +- crates/docx/src/write/story/drawing.rs | 13 ++-- crates/docx/tests/it/fixtures.rs | 99 +++++++++++++++++++++++++- crates/docx/tests/it/roundtrip.rs | 16 ++--- crates/wordmodel/src/document.rs | 31 ++++++++ crates/wordmodel/src/para/float.rs | 13 +++- 8 files changed, 184 insertions(+), 21 deletions(-) diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index cb1152da89..ea48efcca9 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -622,8 +622,9 @@ fn nv_alt(p: Option<&El>) -> (String, AltText) { fn anchor_float(c: &El) -> Float { // `relativeHeight`: the stacking order Word draws floating objects in (higher on top), which - // need not be their order in the file. - let z = c.attr("relativeHeight").and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + // need not be their order in the file. Kept one more (see `Float::z`): 0, the lowest a file + // can give, isn't the 0 of an object without one, which stacks above them all. + let z = c.attr("relativeHeight").and_then(|v| v.trim().parse::().ok()).map_or(0, |z| z.saturating_add(1)); let mut f = Float { wrap: Wrap::Square, z, ..Float::default() }; let behind = on_off_attr(c, "behindDoc"); // Word wraps a position relative to the page's size (`wp14:pctPosVOffset`) in diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 1d9eb08184..634f5f8333 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -82,6 +82,26 @@ impl PartRels { } } +/// Where Word's stacking orders (`relativeHeight`) start for objects made in Word. +const FIRST_Z: u32 = 251_658_240; + +/// The `relativeHeight` the objects of `doc` that have none count up from, and the `relativeHeight` +/// each stored order is written as when it isn't its own (wordcraft#2638). A stored order +/// ([`craft_wordmodel::para::Float::z`]) is one more than the file's, and the new objects go above +/// every stored one. When the stored orders leave no room for them below `u32::MAX` (a file using +/// values that high; `u32::MAX` itself would read back as the order below it), the stored ones are +/// numbered again from [`FIRST_Z`] in their order, so no two objects share an order and none goes +/// out of range. +pub(crate) fn stacking(doc: &Document) -> (u32, BTreeMap) { + let (orders, unset) = doc.stacking_orders(); + let top = orders.last().map_or(0, |z| z.saturating_sub(1)).max(FIRST_Z); + if u32::try_from(unset).ok().and_then(|n| top.checked_add(n)).is_some_and(|last| last < u32::MAX) { + return (top, BTreeMap::new()); + } + let zmap: BTreeMap = orders.iter().zip(FIRST_Z..=u32::MAX).map(|(&z, to)| (z, to)).collect(); + (zmap.values().last().copied().unwrap_or(FIRST_Z), zmap) +} + pub(crate) struct Writer<'d> { doc: &'d Document, /// Numbered display equations written so far (automatic numbers are written as text). @@ -95,7 +115,11 @@ pub(crate) struct Writer<'d> { docpr: u32, /// Shapes' own drawing ids written so far (connectors refer to them). shape_ids: std::collections::HashSet, + /// The last stacking order (`relativeHeight`) given to an object that had none. z: u32, + /// Stored stacking orders written as other `relativeHeight`s (see [`stacking`]); empty: each + /// as its own. + zmap: BTreeMap, /// Note part id → file note id, in first-reference order. footnotes: Vec, endnotes: Vec, diff --git a/crates/docx/src/write/parts.rs b/crates/docx/src/write/parts.rs index 4cb847276c..00826f4b50 100644 --- a/crates/docx/src/write/parts.rs +++ b/crates/docx/src/write/parts.rs @@ -31,7 +31,8 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result Result)> = Vec::new(); diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 7c03cca6ef..2c13e1e7d8 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -252,9 +252,14 @@ impl Writer<'_> { } else { let d = emu(float.dist.clamp(0.0, 1584.0)); let (dt, db) = (emu(float.dist_top.clamp(0.0, 1584.0)), emu(float.dist_bottom.clamp(0.0, 1584.0))); - // The stacking order read from the file is kept; objects without one stack in - // document order above it. - self.z = if float.z > 0 { float.z } else { self.z.saturating_add(1) }; + // A stacking order read from a file is kept (one less: see `Float::z`); objects made + // here go above those. + let z = if float.z > 0 { + self.zmap.get(&float.z).copied().unwrap_or(float.z.saturating_sub(1)) + } else { + self.z = self.z.saturating_add(1); + self.z + }; let behind = if float.wrap == Wrap::BehindText { "1" } else { "0" }; w.open( "wp:anchor", @@ -264,7 +269,7 @@ impl Writer<'_> { ("distL", &d), ("distR", &d), ("simplePos", "0"), - ("relativeHeight", &self.z.to_string()), + ("relativeHeight", &z.to_string()), ("behindDoc", behind), ("locked", "0"), ("layoutInCell", if float.outside_cell { "0" } else { "1" }), diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 868e8cbb0e..9c5fc1e56a 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1282,10 +1282,11 @@ fn anchor_stacking_order_is_read_and_kept() { paras(d)[0].objects.iter().filter_map(|o| if let InlineObject::Shape { float, .. } = o { Some(float.z) } else { None }).collect() }; let d = read_body(&body); - assert_eq!(zs(&d), [251660288, 251657214, 0]); + // Kept one more than the file's (`Float::z`), so a file's 0 isn't "none". + assert_eq!(zs(&d), [251660289, 251657215, 0]); let again = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); let z = zs(&again); - assert_eq!(&z[..2], &[251660288, 251657214]); + assert_eq!(&z[..2], &[251660289, 251657215]); assert!(z[2] > 0, "an object without one gets an order on saving: {z:?}"); } @@ -2592,6 +2593,100 @@ fn anchored_wsp(name: &str, cx: u32, cy: u32, sppr: &str, style: &str, extra: &s ) } +/// wordcraft#2638: Word stacks floating objects by `relativeHeight`, not by their order in the text (a +/// shape sent to back, then copied with the shape over it, comes first in the text but stays +/// behind). The order is read and kept on save, and an object made here is saved above them. +#[test] +fn floating_objects_keep_their_stacking_order() { + let shape = |name: &str, z: u32| { + anchored_wsp(name, 127000, 127000, r#""#, "", "") + .replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#)) + }; + let body = format!("{}{}", shape("Canopy", 251662336), shape("Trunk", 251661312)); + let mut d = read_body(&body); + let stacking = |d: &Document| paras(d)[0].objects.iter().map(|o| o.frame().map(|(_, _, f)| f.z)).collect::>(); + assert_eq!(stacking(&d), [Some(251662337), Some(251661313)]); + let mut made = paras(&d)[0].objects[0].clone(); + if let InlineObject::Shape { float, .. } = &mut made { + float.z = 0; + } + let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut) else { panic!("a paragraph") }; + p.insert_object(0, made, &Default::default()).unwrap(); + let files = unzip(&craft_docx::write(&d).unwrap()); + let written = attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight"); + assert_eq!(written, ["251662337", "251662336", "251661312"]); + let back = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(stacking(&back), [Some(251662338), Some(251662337), Some(251661313)]); +} + +/// wordcraft#2638: a file whose stacking orders reach `u32::MAX` leaves no room above them for an object +/// made here. The stored orders are then numbered again, in their order, so the new object still +/// goes over all of them and no two objects share an order (it was written as `u32::MAX` too). +#[test] +fn stacking_orders_at_the_top_of_the_range_are_numbered_again() { + let shape = |name: &str, z: u32| { + anchored_wsp(name, 127000, 127000, r#""#, "", "") + .replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#)) + }; + let body = format!("{}{}", shape("Top", u32::MAX), shape("Low", 7)); + let mut d = read_body(&body); + let stacking = |d: &Document| paras(d)[0].objects.iter().map(|o| o.frame().map(|(_, _, f)| f.z)).collect::>(); + assert_eq!(stacking(&d), [Some(u32::MAX), Some(8)]); + let mut made = paras(&d)[0].objects[0].clone(); + if let InlineObject::Shape { float, .. } = &mut made { + float.z = 0; + } + let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut) else { panic!("a paragraph") }; + p.insert_object(0, made, &Default::default()).unwrap(); + let back = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + let z: Vec = stacking(&back).into_iter().map(|z| z.expect("every anchor has an order")).collect(); + assert!(z[0] > z[1] && z[1] > z[2], "new over Top over Low, all different: {z:?}"); + // The note separators are saved with the document: an order there counts too. + let mut d = read_body(&format!("{}", shape("Low", 7))); + let mut sep = read_body(&format!("{}", shape("Separator", u32::MAX))); + d.footnote_separators.separator = Some(std::mem::take(&mut sep.body)); + let (orders, unset) = d.stacking_orders(); + assert_eq!((orders.last().copied(), unset), (Some(u32::MAX), 0), "the separator's order is seen"); + let mut made = paras(&d)[0].objects[0].clone(); + if let InlineObject::Shape { float, .. } = &mut made { + float.z = 0; + } + let Some(Block::Para(p)) = d.body.first_mut().map(std::sync::Arc::make_mut) else { panic!("a paragraph") }; + p.insert_object(0, made, &Default::default()).unwrap(); + let files = unzip(&craft_docx::write(&d).unwrap()); + let body: Vec = attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect(); + let seps: Vec = attr_values(&text(&files, "word/footnotes.xml"), "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect(); + assert_eq!(seps.len(), 1, "the separator's shape is saved"); + assert!(body[0] > seps[0] && seps[0] > body[1], "new over the separator's over Low: {body:?} {seps:?}"); + // So does one in a building block of the glossary, saved with the same numbering (wordcraft#2638 review). + let mut d = read_body(&format!("{}", shape("Low", 7))); + let entry = read_body(&format!("{}", shape("Entry", u32::MAX))); + d.glossary.push(craft_wordmodel::BuildingBlock { name: "Entry".into(), blocks: entry.body, ..Default::default() }); + assert_eq!(d.stacking_orders().0.last().copied(), Some(u32::MAX), "the glossary's order is seen"); + // With room above, the stored orders are written as they are. + let room = read_body(&format!("{}", shape("Top", u32::MAX - 5))); + let back = craft_docx::read(&craft_docx::write(&room).unwrap()).unwrap(); + assert_eq!(stacking(&back), [Some(u32::MAX - 4)]); +} + +/// wordcraft#2638 (review): `relativeHeight="0"`, the lowest a file can give, is a stacking order like +/// any other: under a shape with 1, not taken for an object without one (made here, which goes +/// over everything), and saved back as 0. +#[test] +fn a_stacking_order_of_zero_stays_the_lowest() { + let shape = |name: &str, z: u32| { + anchored_wsp(name, 127000, 127000, r#""#, "", "") + .replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#)) + }; + let d = read_body(&format!("{}{}", shape("Bottom", 0), shape("Top", 1))); + let floats: Vec<_> = paras(&d)[0].objects.iter().filter_map(|o| o.frame().map(|(_, _, f)| f.clone())).collect(); + assert_eq!(floats.iter().map(|f| f.z).collect::>(), [1, 2]); + assert!(floats[0].stack() < floats[1].stack(), "0 stacks under 1"); + assert!(floats[1].stack() < craft_wordmodel::para::Float::default().stack(), "an object made here goes over both"); + let files = unzip(&craft_docx::write(&d).unwrap()); + assert_eq!(attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight"), ["0", "1"]); +} + /// #611: diagrams drawn with Word's shapes were mostly missing. Connectors and boxes take their /// outline and fill from the theme through their style references, or name preset and scheme /// colours; all of these are read, with line widths and arrowheads. diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 8f3bbdd0bd..16f61be6b4 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -23,18 +23,14 @@ fn paras(doc: &Document) -> Vec<&Paragraph> { doc.body.iter().filter_map(|b| b.as_para()).collect() } -/// `doc` with the stacking order of its body's floating objects cleared: saving gives objects -/// without one an order (`relativeHeight`), so tests about other properties compare without it. +/// `doc` without the stacking order a save gives objects made in the app (`relativeHeight`, +/// read back as `Float::z`), to compare them with the objects as made. fn unstacked(mut doc: Document) -> Document { - for b in &mut doc.body { - if let Block::Para(p) = std::sync::Arc::make_mut(b) { - for o in &mut p.objects { - if let Some(f) = o.float_mut() { - f.z = 0; - } - } + doc.objects_mut(&|_| true, &mut |o| { + if let Some(f) = o.float_mut() { + f.z = 0; } - } + }); doc } diff --git a/crates/wordmodel/src/document.rs b/crates/wordmodel/src/document.rs index 0a1cc43bd6..5b0d1ae1a8 100644 --- a/crates/wordmodel/src/document.rs +++ b/crates/wordmodel/src/document.rs @@ -721,6 +721,37 @@ impl Document { max.saturating_add(1).max(1) } + /// The stacking orders ([`para::Float::z`]) the floating objects of every story have, and how + /// many floating objects have none (objects made in the app). Every story saved with the document + /// counts: the body, the parts, the note separators and the glossary's building blocks (saved + /// with the same numbering, so none of their orders is left out when it is renumbered). + pub fn stacking_orders(&self) -> (std::collections::BTreeSet, usize) { + let (mut orders, mut unset) = (std::collections::BTreeSet::new(), 0usize); + let separators = [&self.footnote_separators, &self.endnote_separators] + .into_iter() + .flat_map(|s| [&s.separator, &s.continuation_separator, &s.continuation_notice]) + .flatten(); + let stories = std::iter::once(&self.body) + .chain(self.parts.values().map(|p| &p.blocks)) + .chain(separators) + .chain(self.glossary.iter().map(|g| &g.blocks)); + for blocks in stories { + for b in blocks { + crate::walk::each_para(b, 0, &mut |p| { + for (_, _, f) in p.objects.iter().filter_map(InlineObject::frame).filter(|(_, _, f)| f.wrap != para::Wrap::Inline) { + match f.z { + 0 => unset = unset.saturating_add(1), + z => { + orders.insert(z); + } + } + } + }); + } + } + (orders, unset) + } + /// Change every inline object in every story (paragraphs inside tables too), copying only /// the blocks whose paragraphs `wants` says have objects to change. pub fn objects_mut(&mut self, wants: &dyn Fn(&InlineObject) -> bool, f: &mut dyn FnMut(&mut InlineObject)) { diff --git a/crates/wordmodel/src/para/float.rs b/crates/wordmodel/src/para/float.rs index 315e0e0424..b13db3533f 100644 --- a/crates/wordmodel/src/para/float.rs +++ b/crates/wordmodel/src/para/float.rs @@ -182,8 +182,11 @@ pub struct Float { /// off, any VML shape in a header or footer): a picture watermark in a header that starts with a table. #[serde(skip_serializing_if = "is_false")] pub outside_cell: bool, - /// Stacking order among floating objects (`wp:anchor/@relativeHeight`): higher is drawn on - /// top. 0 = unknown, drawn in document order (objects inserted here, or from other formats). + /// Stacking order among the floating objects of its layer, one more than the file's + /// (`wp:anchor/@relativeHeight`, ODF's `draw:z-index`), so a file's lowest, 0, is 1: a higher + /// one is drawn over a lower one, whatever their order in the text, as Word does. 0 = none + /// (objects inserted by the app, or from other formats): stacks above every object that has + /// one, in text order. #[serde(skip_serializing_if = "is_zero_u32")] pub z: u32, /// The page a drawing anchored to a page is on, from 1 (ODF's `text:anchor-page-number`, @@ -242,6 +245,12 @@ fn is_zero_u32(v: &u32) -> bool { } impl Float { + /// Where it stacks among the floating objects of its layer: see [`Float::z`]. None (0) is + /// past every stored order, `u32::MAX` included. + pub fn stack(&self) -> u64 { + if self.z > 0 { u64::from(self.z) } else { u64::from(u32::MAX) + 1 } + } + /// The rotation and flips, the angle normalised to `0..360` (a NaN angle is no rotation). pub fn spin(&self) -> crate::geom::Spin { crate::geom::Spin::new(self.rot, self.flip_h, self.flip_v) From f8388e2293a5441a93ef19efefb54ca6891abd77 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Mon, 16 Nov 2026 08:59:48 +0100 Subject: [PATCH 02/15] craft-odf: an object without a stored stacking order is written above every stored one (wordcraft#2638) --- crates/odf/src/text/frames.rs | 17 ++++++++++--- crates/odf/src/text/package.rs | 2 ++ crates/odf/src/text/tests_more/floats.rs | 31 +++++++++++++++++++++++- crates/odf/src/text/writer.rs | 2 ++ crates/odf/src/text/writer/charts.rs | 2 +- crates/odf/src/text/writer/drawing.rs | 16 ++++++------ 6 files changed, 58 insertions(+), 12 deletions(-) diff --git a/crates/odf/src/text/frames.rs b/crates/odf/src/text/frames.rs index cb87669064..86e11b73c1 100644 --- a/crates/odf/src/text/frames.rs +++ b/crates/odf/src/text/frames.rs @@ -443,9 +443,20 @@ pub(super) fn z_of(a: &Attrs) -> u32 { get(a, "draw:z-index").and_then(|v| v.trim().parse::().ok()).map_or(0, |z| z.saturating_add(1)) } -/// `float`'s place in the stacking order as `draw:z-index` (see [`z_of`]): 0 when unknown. -pub(crate) fn z_index(float: Option<&Float>) -> u32 { - float.map_or(0, |f| f.z.saturating_sub(1)) +/// `float`'s place in the stacking order as `draw:z-index` (see [`z_of`]). One without a stored +/// order (made in WordCraft, or nothing to place) takes `unset`, which the writer puts above every +/// stored order, where [`Float::z`] stacks it. +pub(crate) fn z_index(float: Option<&Float>, unset: u32) -> u32 { + match float.map(|f| f.z) { + Some(z) if z > 0 => z - 1, + _ => unset, + } +} + +/// The `draw:z-index` the objects of `doc` without a stored order take: past the highest stored +/// one (a stored order is one more than its `draw:z-index`), 0 when none has one. +pub(crate) fn unset_z_index(doc: &craft_wordmodel::Document) -> u32 { + doc.stacking_orders().0.last().copied().unwrap_or(0) } /// How far a frame `h` points tall in line with the text is raised from standing on the diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 97520027c9..c64306eeb2 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -1038,6 +1038,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { // Paragraphs kept as read name their own automatic styles: WordCraft's take another prefix. let kept = doc.kept.of("odt"); let mut w = if kept.is_some() { Writer::with_prefix(KEPT_PREFIX) } else { Writer::default() }; + w.unset_z = super::frames::unset_z_index(doc); w.note_numbers = Some([false, true].map(|endnote| { let o = doc.note_options(&doc.last_section, endnote); (o.num_fmt, o.num_start) @@ -1166,6 +1167,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { let mut hw = Writer::with_prefix(if kept.is_some() { "wcM" } else { "M" }); // Headers' and footers' new pictures and objects skip the kept files' names too. hw.reserved = std::sync::Arc::clone(&w.reserved); + hw.unset_z = w.unset_z; hw.accents = accents; hw.variables.clone_from(&w.variables); let parts: Vec = pages.iter().map(|(_, sec)| page_parts(doc, sec, &mut hw)).collect(); diff --git a/crates/odf/src/text/tests_more/floats.rs b/crates/odf/src/text/tests_more/floats.rs index f8ac5fe99b..ab0c0bf268 100644 --- a/crates/odf/src/text/tests_more/floats.rs +++ b/crates/odf/src/text/tests_more/floats.rs @@ -362,12 +362,41 @@ fn a_frame_keeps_its_place_in_the_stacking_order() { let saved = crate::text::tests::export_model(&d).unwrap(); assert!(crate::text::tests::entry(&saved, "content.xml").contains(r#"draw:z-index="3""#)); assert_eq!(float(&import(&saved).unwrap()).z, 4); - // Unknown (inserted in WordCraft): at the bottom, in document order. + // Unknown (inserted in WordCraft), with nothing else stored: 0. let d = open(r#"style:wrap="run-through""#, r#"text:anchor-type="paragraph""#); assert_eq!(float(&d).z, 0); assert!(crate::text::tests::entry(&crate::text::tests::export_model(&d).unwrap(), "content.xml").contains(r#"draw:z-index="0""#)); } +/// An object without a stored order (made in WordCraft) stacks above every object that has one +/// (`Float::z`), so it is written above them, not at the bottom. +#[test] +fn an_object_made_here_is_written_above_the_stored_orders() { + let png = [b"\x89PNG\r\n\x1a\n".as_slice(), &[7u8; 64]].concat(); + let frame = |z: &str| { + format!( + r#""# + ) + }; + let content = format!( + r#"{}{}Text beside."#, + frame(r#" draw:z-index="3""#), + frame("") + ); + let d = import(&zip_of(&[("content.xml", content.as_bytes()), ("Pictures/a.png", &png)])).unwrap(); + let zs: Vec = d.body[0] + .as_para() + .unwrap() + .objects + .iter() + .filter_map(|o| if let InlineObject::Image { float, .. } = o { Some(float.z) } else { None }) + .collect(); + assert_eq!(zs, [4, 0], "one stored, one made here"); + let content = crate::text::tests::entry(&crate::text::tests::export_model(&d).unwrap(), "content.xml"); + let z: Vec<&str> = content.split(r#"draw:z-index=""#).skip(1).filter_map(|s| s.split('"').next()).collect(); + assert_eq!(z, ["3", "4"], "{content}"); +} + #[test] fn a_frame_anchored_to_a_page_stays_on_that_page() { // LibreOffice's page-anchored frames name their page. Written without it, a frame on page 3 diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 2ad475739c..220f5afab2 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -176,6 +176,8 @@ pub(super) struct Writer { pub(super) named_text: std::collections::BTreeSet, /// Text boxes written so far (their frames' names). boxes: usize, + /// The `draw:z-index` of objects without a stored stacking order (see `frames::unset_z_index`). + pub(super) unset_z: u32, /// Notes written so far (their ids), and footnotes and endnotes among them (their numbers). notes: usize, footnotes: u32, diff --git a/crates/odf/src/text/writer/charts.rs b/crates/odf/src/text/writer/charts.rs index 1cc3e3e25c..9c6c2a5044 100644 --- a/crates/odf/src/text/writer/charts.rs +++ b/crates/odf/src/text/writer/charts.rs @@ -200,7 +200,7 @@ impl Writer { // Always placed by a style (see `image_frame`). let (anchor, props, xy) = placement(place, c.w, c.h); let (anchor, style) = (anchor, format!(" draw:style-name=\"{}\"{xy}", self.graphic_style(props))); - let z = place.z_index(); + let z = place.z_index(self.unset_z); out.push_str(&format!( "{inner}", self.prefix, diff --git a/crates/odf/src/text/writer/drawing.rs b/crates/odf/src/text/writer/drawing.rs index d49a07ea80..6a5f08febc 100644 --- a/crates/odf/src/text/writer/drawing.rs +++ b/crates/odf/src/text/writer/drawing.rs @@ -70,9 +70,10 @@ pub(in crate::text) enum Place<'a> { } impl<'a> Place<'a> { - /// Its place in the stacking order (§19.231 `draw:z-index`, see `frames::z_of`). - pub(in crate::text) fn z_index(self) -> u32 { - crate::text::frames::z_index(self.float()) + /// Its place in the stacking order (§19.231 `draw:z-index`, see `frames::z_of`), `unset` + /// without a stored one. + pub(in crate::text) fn z_index(self, unset: u32) -> u32 { + crate::text::frames::z_index(self.float(), unset) } /// What turns or mirrors the object, and places it in the text. @@ -323,7 +324,7 @@ impl Writer { let (anchor, props, xy) = placement(place, img.w, img.h); let (anchor, style) = (anchor, format!(" draw:style-name=\"{}\"{xy}", self.graphic_style(format!("{}{props}{clip}", super::GRAPHICS_PARENT)))); - let z = place.z_index(); + let z = place.z_index(self.unset_z); out.push_str(&format!( "{inner}", self.prefix, @@ -360,7 +361,8 @@ impl Writer { let (anchor, props, _) = placement(Place::Text(float.filter(|f| f.wrap != craft_wordmodel::para::Wrap::Inline)), size.0, size.1); let style = self.graphic_style(props); self.boxes += 1; - out.push_str(&format!("", self.prefix, self.boxes)); + let z = crate::text::frames::z_index(float, self.unset_z); + out.push_str(&format!("", self.prefix, self.boxes)); let at = Place::Text(float).origin(); self.members(members, at, 0, out); out.push_str(""); @@ -419,7 +421,7 @@ impl Writer { .and_then(|c| c.next.as_deref()) .map(|n| format!(" draw:chain-next-name=\"{}{}\"", self.prefix, x(n))) .unwrap_or_default(); - let z = place.z_index(); + let z = place.z_index(self.unset_z); out.push_str(&format!( "{body}", x(&name), @@ -522,7 +524,7 @@ impl Writer { }) .unwrap_or_default(); let conn = self.conn_attrs(kind, look); - let z = place.z_index(); + let z = place.z_index(self.unset_z); out.push_str(&format!( "<{element} draw:name=\"{}Shape{}\" draw:style-name=\"{style}\"{anchor}{at}{conn} draw:z-index=\"{z}\">{body}{geometry}", self.prefix, self.boxes, From cccb00b6b44be9ee0ee7007b29fa73969da0dffb Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:01:22 +0100 Subject: [PATCH 03/15] craft-odf: a group member's stored stacking order counts for the unset draw:z-index (wordcraft#2638) unset_z_index only looked at the floating objects' orders, so a group member without a stored order could be written below a member that has one. It now also walks the groups' members. --- crates/odf/src/text/frames.rs | 31 ++++++++++++++++++++++-- crates/odf/src/text/tests_more/floats.rs | 24 ++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/crates/odf/src/text/frames.rs b/crates/odf/src/text/frames.rs index 86e11b73c1..44a31357a3 100644 --- a/crates/odf/src/text/frames.rs +++ b/crates/odf/src/text/frames.rs @@ -454,9 +454,36 @@ pub(crate) fn z_index(float: Option<&Float>, unset: u32) -> u32 { } /// The `draw:z-index` the objects of `doc` without a stored order take: past the highest stored -/// one (a stored order is one more than its `draw:z-index`), 0 when none has one. +/// one (a stored order is one more than its `draw:z-index`), 0 when none has one. A group's +/// members are written with their own orders too, so theirs count as well as the floating +/// objects' ([`craft_wordmodel::Document::stacking_orders`]). pub(crate) fn unset_z_index(doc: &craft_wordmodel::Document) -> u32 { - doc.stacking_orders().0.last().copied().unwrap_or(0) + use craft_wordmodel::para::{GroupChild, InlineObject}; + fn members(children: &[GroupChild], depth: usize, top: &mut u32) { + for c in children { + if let Some((_, _, f)) = c.obj.frame() { + *top = (*top).max(f.z); + } + if let InlineObject::Group { children, .. } = &c.obj + && depth < craft_flow::MAX_GROUP_DEPTH + { + members(children, depth + 1, top); + } + } + } + let mut top = doc.stacking_orders().0.last().copied().unwrap_or(0); + for blocks in std::iter::once(&doc.body).chain(doc.parts.values().map(|p| &p.blocks)) { + for b in blocks { + craft_wordmodel::walk::each_para(b, 0, &mut |p| { + for o in &p.objects { + if let InlineObject::Group { children, .. } = o { + members(children, 0, &mut top); + } + } + }); + } + } + top } /// How far a frame `h` points tall in line with the text is raised from standing on the diff --git a/crates/odf/src/text/tests_more/floats.rs b/crates/odf/src/text/tests_more/floats.rs index ab0c0bf268..0fff3797a4 100644 --- a/crates/odf/src/text/tests_more/floats.rs +++ b/crates/odf/src/text/tests_more/floats.rs @@ -397,6 +397,30 @@ fn an_object_made_here_is_written_above_the_stored_orders() { assert_eq!(z, ["3", "4"], "{content}"); } +/// A group's members are written with their own stacking orders, so a member without one (made +/// in WordCraft) goes above a member's stored order too, not just above the floating objects'. +#[test] +fn an_object_made_here_is_written_above_the_group_members_stored_orders() { + let content = format!( + r#"Text beside."# + ); + let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap(); + // The group stored at the bottom, its first member stored above it, its second made here. + d.objects_mut(&|o| matches!(o, InlineObject::Group { .. }), &mut |o| { + let InlineObject::Group { float, children, .. } = o else { return }; + float.z = 1; + let wrap = float.wrap; + for (c, z) in children.iter_mut().zip([4, 0]) { + if let Some(f) = c.obj.float_mut() { + (f.wrap, f.z) = (wrap, z); + } + } + }); + let content = crate::text::tests::entry(&crate::text::tests::export_model(&d).unwrap(), "content.xml"); + let z: Vec<&str> = content.split(r#"draw:z-index=""#).skip(1).filter_map(|s| s.split('"').next()).collect(); + assert_eq!(z, ["0", "3", "4"], "the group's, the stored member's, the member made here above it: {content}"); +} + #[test] fn a_frame_anchored_to_a_page_stays_on_that_page() { // LibreOffice's page-anchored frames name their page. Written without it, a frame on page 3 From c5f217e76518f15ae27ac5ec615ed5d0735d6a90 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 16:10:03 +0100 Subject: [PATCH 04/15] craft-docx: a shape's VML fallback takes its anchor's relativeHeight Main's VML fallback (#1864) read the writer's z counter after the anchor was written. That counter now only counts objects without a stored order, so a stored order's fallback got the wrong z-index. The anchor's relativeHeight is now kept in anchor_z for the fallback, and the wps_fallback tests expect the written relativeHeight (one less than Float::z). --- crates/docx/src/write.rs | 3 +++ crates/docx/src/write/parts.rs | 1 + crates/docx/src/write/story/drawing.rs | 1 + crates/docx/src/write/story/object.rs | 5 +++-- crates/docx/tests/it/wps_fallback.rs | 6 ++++-- 5 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 634f5f8333..0391ba615e 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -120,6 +120,9 @@ pub(crate) struct Writer<'d> { /// Stored stacking orders written as other `relativeHeight`s (see [`stacking`]); empty: each /// as its own. zmap: BTreeMap, + /// The `relativeHeight` the last `wp:anchor` was written with, which a shape's VML fallback + /// gives as its `z-index`. + anchor_z: u32, /// Note part id → file note id, in first-reference order. footnotes: Vec, endnotes: Vec, diff --git a/crates/docx/src/write/parts.rs b/crates/docx/src/write/parts.rs index 00826f4b50..fa6d6b6933 100644 --- a/crates/docx/src/write/parts.rs +++ b/crates/docx/src/write/parts.rs @@ -33,6 +33,7 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result { self.z = self.z.saturating_add(1); self.z }; + self.anchor_z = z; let behind = if float.wrap == Wrap::BehindText { "1" } else { "0" }; w.open( "wp:anchor", diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 4b0ae856a6..3a42a8b044 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -398,8 +398,9 @@ impl Writer<'_> { } let float = &float; self.drawing_open(w, DrawingInfo { float, size: (*sw, *sh), docpr: &docpr, name: &name, alt: o.alt_text(), link: link.as_deref() }); - // This shape's stacking order: floating objects in its text box move `self.z` on. - let z = self.z; + // This shape's stacking order, as its anchor gave it: floating objects in its text box + // write anchors of their own. + let z = self.anchor_z; w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); diff --git a/crates/docx/tests/it/wps_fallback.rs b/crates/docx/tests/it/wps_fallback.rs index 9b209082b7..6d3deddb12 100644 --- a/crates/docx/tests/it/wps_fallback.rs +++ b/crates/docx/tests/it/wps_fallback.rs @@ -107,7 +107,8 @@ fn the_fallback_keeps_order_visibility_and_direction() { // is copied into the outer one's text, so it comes after it). let tb = xml.find(r#""#).expect("the outer box's text, turned"); let rect = &xml[xml[..tb].rfind(" Date: Mon, 16 Nov 2026 18:24:18 +0100 Subject: [PATCH 05/15] fix(odf): preserve boundary stacking and inline drawing metadata --- crates/flow/src/from_doc.rs | 20 +++++++- crates/flow/src/types.rs | 5 +- crates/odf/src/text/body.rs | 1 + crates/odf/src/text/body/drawing.rs | 9 ++-- crates/odf/src/text/frames.rs | 65 +++++++++++++++++------- crates/odf/src/text/package.rs | 4 +- crates/odf/src/text/tests_more/floats.rs | 63 +++++++++++++++++++++++ crates/odf/src/text/writer.rs | 4 +- crates/odf/src/text/writer/charts.rs | 2 +- crates/odf/src/text/writer/drawing.rs | 12 ++--- 10 files changed, 150 insertions(+), 35 deletions(-) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 810e67d552..791bb60ce5 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -418,10 +418,11 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize } } -/// The placement a flow keeps for a drawing: when it floats, or turns or mirrors it in line. +/// Keep placement, transforms, and explicit stacking metadata even for inline drawings. +/// Presence alone does not imply anchoring: the retained Float keeps its original wrap. fn kept_float(f: &craft_wordmodel::para::Float) -> Option> { let turned = f.rot.is_finite() && f.rot.rem_euclid(360.0) > 0.001 && f.rot.rem_euclid(360.0) < 359.999; - (f.wrap != craft_wordmodel::para::Wrap::Inline || turned || f.flip_h || f.flip_v).then(|| Box::new(f.clone())) + (f.wrap != craft_wordmodel::para::Wrap::Inline || turned || f.flip_h || f.flip_v || f.z != 0).then(|| Box::new(f.clone())) } fn flow_comment(doc: &Document, c: &craft_wordmodel::Comment, parent: Option, opts: FlowOpts) -> FComment { @@ -1254,3 +1255,18 @@ impl ListCounter { } } } + +#[cfg(test)] +mod stacking_tests { + #[test] + fn explicit_inline_stacking_preserves_wrap_without_creating_an_anchor() { + use craft_wordmodel::para::{Float, Wrap}; + let f = Float { z: u32::MAX, ..Float::default() }; + assert_eq!(f.wrap, Wrap::Inline); + let kept = super::kept_float(&f).unwrap(); + assert_eq!(kept.wrap, Wrap::Inline); + assert_eq!(kept.z, u32::MAX); + assert_eq!(kept.rot, f.rot); + assert!(super::kept_float(&Float::default()).is_none()); + } +} diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index f1c281c62e..d5abb75375 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -170,8 +170,9 @@ pub struct Img { pub w: f32, pub h: f32, pub alt: String, - /// How a floating picture is placed and wrapped, for formats that keep it (ODT); `None`: in - /// line with the text. + /// Placement and drawing metadata for formats that keep it (ODT). `None` is inline; + /// `Some` may also be inline, retaining rotation, mirroring or explicit stacking order. + /// The Float wrap, not the Option, determines anchoring. pub float: Option>, /// The embedded object this picture shows, kept whole (ODT only; see [`OdfObject`]). pub object: Option>, diff --git a/crates/odf/src/text/body.rs b/crates/odf/src/text/body.rs index f075956769..1b27932589 100644 --- a/crates/odf/src/text/body.rs +++ b/crates/odf/src/text/body.rs @@ -1261,6 +1261,7 @@ impl Body<'_> { self.group = Some(OpenGroup { anchor: get(a, "text:anchor-type").map(String::from), page: get(a, "text:anchor-page-number").map(String::from), + z: crate::text::frames::z_of(a), style: get(a, "draw:style-name").map(String::from), members: Vec::new(), }); diff --git a/crates/odf/src/text/body/drawing.rs b/crates/odf/src/text/body/drawing.rs index 28cb8cb120..eeb466f59c 100644 --- a/crates/odf/src/text/body/drawing.rs +++ b/crates/odf/src/text/body/drawing.rs @@ -67,6 +67,7 @@ pub(in crate::text) struct OpenGroup { pub(in crate::text) anchor: Option, /// Its `text:anchor-page-number`. pub(in crate::text) page: Option, + pub(in crate::text) z: u32, pub(in crate::text) style: Option, pub(in crate::text) members: Vec, } @@ -103,8 +104,9 @@ impl Body<'_> { f.flip_v ^= v; } // Kept when it floats, or turns or mirrors the object in line. - let float = float - .filter(|f| f.wrap != craft_wordmodel::para::Wrap::Inline || crate::text::frames::turned(f) || f.flip_h || f.flip_v || f.y != 0.0); + let float = float.filter(|f| { + f.wrap != craft_wordmodel::para::Wrap::Inline || crate::text::frames::turned(f) || f.flip_h || f.flip_v || f.y != 0.0 || f.z != 0 + }); if let Some(blocks) = &boxed && self.take_watermark(blocks) { @@ -353,7 +355,8 @@ impl Body<'_> { let mut float = crate::text::frames::float_of(g.anchor.as_deref(), Some(&crate::text::writer::pt(x0)), Some(&crate::text::writer::pt(y0)), &graphic); float.page = crate::text::frames::page_of(g.anchor.as_deref(), g.page.as_deref(), &graphic); - let float = (float.wrap != craft_wordmodel::para::Wrap::Inline).then(|| Box::new(float)); + float.z = g.z; + let float = (float.wrap != craft_wordmodel::para::Wrap::Inline || float.z != 0).then(|| Box::new(float)); let fit = |v: f32| if v.is_finite() { v.clamp(1.0, MAX_LEN) } else { 1.0 }; self.push_inline(Inline::Group { w: fit(x1 - x0), h: fit(y1 - y0), float, members }); } diff --git a/crates/odf/src/text/frames.rs b/crates/odf/src/text/frames.rs index 44a31357a3..6e1e22c6ff 100644 --- a/crates/odf/src/text/frames.rs +++ b/crates/odf/src/text/frames.rs @@ -443,47 +443,78 @@ pub(super) fn z_of(a: &Attrs) -> u32 { get(a, "draw:z-index").and_then(|v| v.trim().parse::().ok()).map_or(0, |z| z.saturating_add(1)) } -/// `float`'s place in the stacking order as `draw:z-index` (see [`z_of`]). One without a stored -/// order (made in WordCraft, or nothing to place) takes `unset`, which the writer puts above every -/// stored order, where [`Float::z`] stacks it. -pub(crate) fn z_index(float: Option<&Float>, unset: u32) -> u32 { +/// Export orders leave room for the one-more representation used on import. +/// At the upper boundary, remove an unused model order rather than saturating. +#[derive(Clone, Copy, Default)] +pub(crate) struct Stacking { + unset: u32, + gap: Option, +} + +/// A stored order stays below every unset order; equal stored orders remain equal. +pub(crate) fn z_index(float: Option<&Float>, stacking: Stacking) -> u32 { match float.map(|f| f.z) { - Some(z) if z > 0 => z - 1, - _ => unset, + Some(z) if z > 0 => z - 1 - u32::from(stacking.gap.is_some_and(|gap| z > gap)), + _ => stacking.unset, } } -/// The `draw:z-index` the objects of `doc` without a stored order take: past the highest stored -/// one (a stored order is one more than its `draw:z-index`), 0 when none has one. A group's -/// members are written with their own orders too, so theirs count as well as the floating -/// objects' ([`craft_wordmodel::Document::stacking_orders`]). -pub(crate) fn unset_z_index(doc: &craft_wordmodel::Document) -> u32 { +/// Include group members and inline frames too: the ODF writer emits their orders. +pub(crate) fn stacking(doc: &craft_wordmodel::Document) -> Result { use craft_wordmodel::para::{GroupChild, InlineObject}; - fn members(children: &[GroupChild], depth: usize, top: &mut u32) { + use std::collections::BTreeSet; + fn members(children: &[GroupChild], depth: usize, orders: &mut BTreeSet, unset: &mut bool) { for c in children { + if let Some((_, _, f)) = c.obj.frame() + && f.z > 0 + { + orders.insert(f.z); + } if let Some((_, _, f)) = c.obj.frame() { - *top = (*top).max(f.z); + *unset |= f.z == 0; } if let InlineObject::Group { children, .. } = &c.obj && depth < craft_flow::MAX_GROUP_DEPTH { - members(children, depth + 1, top); + members(children, depth + 1, orders, unset); } } } - let mut top = doc.stacking_orders().0.last().copied().unwrap_or(0); + let (mut orders, unset_count) = doc.stacking_orders(); + let mut unset = unset_count > 0; for blocks in std::iter::once(&doc.body).chain(doc.parts.values().map(|p| &p.blocks)) { for b in blocks { craft_wordmodel::walk::each_para(b, 0, &mut |p| { for o in &p.objects { + if let Some((_, _, f)) = o.frame() + && f.z > 0 + { + orders.insert(f.z); + } + if let Some((_, _, f)) = o.frame() { + unset |= f.z == 0; + } if let InlineObject::Group { children, .. } = o { - members(children, 0, &mut top); + members(children, 0, &mut orders, &mut unset); } } }); } } - top + let top = orders.last().copied().unwrap_or(0); + if top < u32::MAX || !unset { + return Ok(Stacking { unset: top, gap: None }); + } + // Find a missing positive value in linear time in the number of distinct orders, + // not the numeric range. This needs no second map and preserves relative order. + let mut gap = 1u32; + for z in orders { + if z != gap { + break; + } + gap = gap.checked_add(1).ok_or("too many distinct ODF stacking orders")?; + } + Ok(Stacking { unset: top - 1, gap: Some(gap) }) } /// How far a frame `h` points tall in line with the text is raised from standing on the diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index c64306eeb2..f7a9d164d8 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -1038,7 +1038,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { // Paragraphs kept as read name their own automatic styles: WordCraft's take another prefix. let kept = doc.kept.of("odt"); let mut w = if kept.is_some() { Writer::with_prefix(KEPT_PREFIX) } else { Writer::default() }; - w.unset_z = super::frames::unset_z_index(doc); + w.stacking = super::frames::stacking(doc)?; w.note_numbers = Some([false, true].map(|endnote| { let o = doc.note_options(&doc.last_section, endnote); (o.num_fmt, o.num_start) @@ -1167,7 +1167,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { let mut hw = Writer::with_prefix(if kept.is_some() { "wcM" } else { "M" }); // Headers' and footers' new pictures and objects skip the kept files' names too. hw.reserved = std::sync::Arc::clone(&w.reserved); - hw.unset_z = w.unset_z; + hw.stacking = w.stacking; hw.accents = accents; hw.variables.clone_from(&w.variables); let parts: Vec = pages.iter().map(|(_, sec)| page_parts(doc, sec, &mut hw)).collect(); diff --git a/crates/odf/src/text/tests_more/floats.rs b/crates/odf/src/text/tests_more/floats.rs index 0fff3797a4..00f18408a5 100644 --- a/crates/odf/src/text/tests_more/floats.rs +++ b/crates/odf/src/text/tests_more/floats.rs @@ -509,3 +509,66 @@ fn a_frame_offering_several_formats_shows_the_first_it_can_read() { let d = import(&zip_of(&[("content.xml", only.as_bytes()), ("Pictures/a.svm", &svm)])).unwrap(); assert_eq!(pictures(&d), 0); } + +/// Export must leave room for import's one-more encoding, including group members. +#[test] +fn extreme_stacking_orders_remain_distinct_after_repeated_roundtrips() { + for (grouped, location) in [(false, 0), (true, 0), (false, 1), (true, 1), (false, 2), (true, 2), (false, 3)] { + let shapes = r#""#.repeat(5); + let objects = if grouped { + format!(r#"{shapes}"#) + } else { + shapes.replace("{objects}"# + ); + let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap(); + let zs = [1, u32::MAX - 1, u32::MAX, u32::MAX, 0]; + if grouped { + d.objects_mut(&|o| matches!(o, InlineObject::Group { .. }), &mut |o| { + let InlineObject::Group { float, children, .. } = o else { return }; + float.z = 1; + for (child, z) in children.iter_mut().zip(zs) { + child.obj.float_mut().unwrap().z = z; + } + }); + } else { + let mut orders = zs.into_iter(); + d.objects_mut(&|o| o.frame().is_some(), &mut |o| { + let f = o.float_mut().unwrap(); + f.z = orders.next().unwrap(); + if location == 3 && f.wrap == Wrap::Inline { + f.y = 6.0; + } + }); + } + let mut expected = + vec!["0".to_string(), (u32::MAX - 3).to_string(), (u32::MAX - 2).to_string(), (u32::MAX - 2).to_string(), (u32::MAX - 1).to_string()]; + if grouped { + expected.insert(0, "0".into()); + } + if location == 1 || location == 2 { + let blocks = std::mem::replace(&mut d.body, vec![craft_wordmodel::para_block(craft_wordmodel::Paragraph::new())]); + let kind = if location == 1 { craft_wordmodel::PartKind::Header } else { craft_wordmodel::PartKind::Footer }; + d.parts.insert(1, craft_wordmodel::Part { kind, blocks, body: Default::default() }); + if location == 1 { + d.last_section.headers.default = Some(1); + } else { + d.last_section.footers.default = Some(1); + } + } + for pass in 0..3 { + let bytes = crate::text::tests::export_model(&d).unwrap(); + let content = crate::text::tests::entry(&bytes, if location == 1 || location == 2 { "styles.xml" } else { "content.xml" }); + let actual: Vec<&str> = content.split(r#"draw:z-index=""#).skip(1).filter_map(|s| s.split('"').next()).collect(); + assert_eq!(actual, expected, "grouped={grouped}, location={location}, pass={pass}: {content}"); + if location == 3 { + assert!(content.contains(r#"text:anchor-type="as-char""#), "inline must remain inline"); + assert!(content.contains(r#"svg:y="-78pt""#), "baseline raise must survive: {content}"); + } + d = import(&bytes).unwrap(); + } + } +} diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 220f5afab2..dc42829456 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -176,8 +176,8 @@ pub(super) struct Writer { pub(super) named_text: std::collections::BTreeSet, /// Text boxes written so far (their frames' names). boxes: usize, - /// The `draw:z-index` of objects without a stored stacking order (see `frames::unset_z_index`). - pub(super) unset_z: u32, + /// Export stacking orders, also used by the header/footer writer. + pub(super) stacking: super::frames::Stacking, /// Notes written so far (their ids), and footnotes and endnotes among them (their numbers). notes: usize, footnotes: u32, diff --git a/crates/odf/src/text/writer/charts.rs b/crates/odf/src/text/writer/charts.rs index 9c6c2a5044..76d9e56e83 100644 --- a/crates/odf/src/text/writer/charts.rs +++ b/crates/odf/src/text/writer/charts.rs @@ -200,7 +200,7 @@ impl Writer { // Always placed by a style (see `image_frame`). let (anchor, props, xy) = placement(place, c.w, c.h); let (anchor, style) = (anchor, format!(" draw:style-name=\"{}\"{xy}", self.graphic_style(props))); - let z = place.z_index(self.unset_z); + let z = place.z_index(self.stacking); out.push_str(&format!( "{inner}", self.prefix, diff --git a/crates/odf/src/text/writer/drawing.rs b/crates/odf/src/text/writer/drawing.rs index 6a5f08febc..115dd9b026 100644 --- a/crates/odf/src/text/writer/drawing.rs +++ b/crates/odf/src/text/writer/drawing.rs @@ -72,8 +72,8 @@ pub(in crate::text) enum Place<'a> { impl<'a> Place<'a> { /// Its place in the stacking order (§19.231 `draw:z-index`, see `frames::z_of`), `unset` /// without a stored one. - pub(in crate::text) fn z_index(self, unset: u32) -> u32 { - crate::text::frames::z_index(self.float(), unset) + pub(in crate::text) fn z_index(self, stacking: crate::text::frames::Stacking) -> u32 { + crate::text::frames::z_index(self.float(), stacking) } /// What turns or mirrors the object, and places it in the text. @@ -324,7 +324,7 @@ impl Writer { let (anchor, props, xy) = placement(place, img.w, img.h); let (anchor, style) = (anchor, format!(" draw:style-name=\"{}\"{xy}", self.graphic_style(format!("{}{props}{clip}", super::GRAPHICS_PARENT)))); - let z = place.z_index(self.unset_z); + let z = place.z_index(self.stacking); out.push_str(&format!( "{inner}", self.prefix, @@ -361,7 +361,7 @@ impl Writer { let (anchor, props, _) = placement(Place::Text(float.filter(|f| f.wrap != craft_wordmodel::para::Wrap::Inline)), size.0, size.1); let style = self.graphic_style(props); self.boxes += 1; - let z = crate::text::frames::z_index(float, self.unset_z); + let z = crate::text::frames::z_index(float, self.stacking); out.push_str(&format!("", self.prefix, self.boxes)); let at = Place::Text(float).origin(); self.members(members, at, 0, out); @@ -421,7 +421,7 @@ impl Writer { .and_then(|c| c.next.as_deref()) .map(|n| format!(" draw:chain-next-name=\"{}{}\"", self.prefix, x(n))) .unwrap_or_default(); - let z = place.z_index(self.unset_z); + let z = place.z_index(self.stacking); out.push_str(&format!( "{body}", x(&name), @@ -524,7 +524,7 @@ impl Writer { }) .unwrap_or_default(); let conn = self.conn_attrs(kind, look); - let z = place.z_index(self.unset_z); + let z = place.z_index(self.stacking); out.push_str(&format!( "<{element} draw:name=\"{}Shape{}\" draw:style-name=\"{style}\"{anchor}{at}{conn} draw:z-index=\"{z}\">{body}{geometry}", self.prefix, self.boxes, From c2068fc90ba5443fa9e64403fb13e0de669aa1a1 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 18:54:38 +0100 Subject: [PATCH 06/15] fix(import): normalize maximum drawing stacking orders without replay --- crates/docx/src/package.rs | 94 +++++++++++++++++++++ crates/docx/src/read.rs | 3 + crates/docx/src/read/story/drawing.rs | 6 +- crates/docx/tests/it/fixtures.rs | 55 ++++++++++++ crates/odf/src/text/body.rs | 21 +++++ crates/odf/src/text/frames.rs | 34 ++++++++ crates/odf/src/text/import.rs | 8 +- crates/odf/src/text/page_parts.rs | 2 + crates/odf/src/text/tests_more/floats.rs | 26 ++++++ crates/wordmodel/src/para.rs | 2 + crates/wordmodel/src/para/file_orders.rs | 102 +++++++++++++++++++++++ 11 files changed, 348 insertions(+), 5 deletions(-) create mode 100644 crates/wordmodel/src/para/file_orders.rs diff --git a/crates/docx/src/package.rs b/crates/docx/src/package.rs index 53202850a5..ae896dcf54 100644 --- a/crates/docx/src/package.rs +++ b/crates/docx/src/package.rs @@ -12,6 +12,9 @@ pub const MAX_PART: u64 = 256 * 1024 * 1024; pub const MAX_TOTAL: u64 = 512 * 1024 * 1024; /// Most zip entries we look at. pub const MAX_ENTRIES: usize = 20_000; +// ZIP names have at most u16::MAX raw bytes. CP437/lossy UTF-8 decoding can +// expand each byte to three UTF-8 bytes. Bound from_parts lookup copies too. +const MAX_SCAN_NAME: usize = 3 * u16::MAX as usize; /// Relationship type suffixes (after `.../relationships/`). pub mod rt { @@ -265,6 +268,61 @@ impl Package { } } + /// Read only XML attributes, once per canonical package part. This never invokes + /// an altChunk importer or fetches additional data. Non-XML extensions are valid OPC + /// targets too. Errors end a lenient part exactly as the normal XML reader does; + /// the subsequent strict main-document parse remains authoritative. + pub(crate) fn file_orders(&self) -> Result { + use craft_wordmodel::para::FileOrderScan; + let mut bytes = 0u64; + for (i, name) in self.opc.names().enumerate() { + if name.len() > MAX_SCAN_NAME { + return Err(DocxError::Limit("stacking-order source part name is too long".into())); + } + if i >= MAX_ENTRIES { + return Err(DocxError::Limit("too many stacking-order source parts".into())); + } + bytes = bytes + .checked_add(self.opc.get(name).map_or(0, |b| b.len() as u64)) + .ok_or_else(|| DocxError::Limit("stacking-order source size overflow".into()))?; + if bytes > FileOrderScan::MAX_SOURCE_BYTES { + return Err(DocxError::Limit("stacking-order source exceeds 2 GiB".into())); + } + } + let mut scan = FileOrderScan::new(bytes).map_err(DocxError::Limit)?; + let limits = craft_xml::Limits { + max_input: 2 << 30, + max_depth: xml::MAX_DEPTH + 1, + max_nodes: 2 * xml::MAX_ELEMENTS, + max_elements: xml::MAX_ELEMENTS, + max_attrs: xml::MAX_ATTRS, + max_attrs_total: 2 * xml::MAX_ELEMENTS, + }; + let opts = craft_xml::Options::default().with_limits(limits); + for name in self.opc.names() { + let Some(bytes) = self.opc.get(name) else { continue }; + let text = craft_xml::to_utf8(bytes); + // Attribute names cannot contain entity references. This only skips parts + // that cannot possibly supply an order, including ordinary binary media. + if !text.windows(b"relativeHeight".len()).any(|w| w == b"relativeHeight") { + continue; + } + let mut events = opts.events(&text); + while let Ok(Some(ev)) = events.next() { + if let craft_xml::Event::Start { attrs, .. } = ev { + for (name, value) in attrs { + if name.rsplit(':').next() == Some("relativeHeight") + && let Ok(raw) = value.trim().parse::() + { + scan.observe(raw); + } + } + } + } + } + scan.finish().map_err(DocxError::Limit) + } + /// Relationships of `part` (from `dir/_rels/name.rels`). Internal targets name the part as /// stored, so a part reached under several spellings is kept, cached and written once. pub fn rels(&self, part: &str) -> Rels { @@ -386,3 +444,39 @@ mod tests { assert!(junk.parts.is_empty()); } } + +#[cfg(test)] +mod file_order_tests { + use super::*; + + #[test] + fn file_order_scan_bounds_decoded_part_names_before_lookup() { + let at_limit = "n".repeat(MAX_SCAN_NAME); + assert!(Package::from_parts(BTreeMap::from([(at_limit, Vec::new())])).file_orders().is_ok()); + let too_long = "n".repeat(MAX_SCAN_NAME + 1); + assert!(Package::from_parts(BTreeMap::from([(too_long, Vec::new())])).file_orders().is_err()); + } + + fn scan(xml: &str) -> craft_wordmodel::para::FileOrders { + Package::from_parts(BTreeMap::from([("odd.part".into(), xml.as_bytes().to_vec())])).file_orders().unwrap() + } + + #[test] + fn file_order_scan_matches_lenient_attributes_entities_and_parser_limits() { + let malformed = r#""#; + let tree = xml::parse(malformed.as_bytes()).unwrap(); + assert_eq!(tree.find("?:x").or_else(|| tree.find("x")).unwrap().attr("relativeHeight"), Some("4294967295")); + let map = scan(malformed); + assert_eq!((map.model_order(Some(u32::MAX - 1)), map.model_order(Some(u32::MAX))), (u32::MAX - 1, u32::MAX)); + let custom = r#"]>"#; + assert_ne!(xml::parse(custom.as_bytes()).unwrap().attr("relativeHeight"), Some("4294967295")); + assert_eq!(scan(custom).model_order(Some(u32::MAX - 1)), u32::MAX); + let too_many = + format!(r#""#, (0..xml::MAX_ATTRS).map(|i| format!(r#"a{i}="x""#)).collect::>().join(" ")); + assert!(xml::parse(too_many.as_bytes()).is_err()); + assert_eq!(scan(&too_many).model_order(Some(u32::MAX - 1)), u32::MAX); + let too_deep = format!(r#"{}{}"#, "".repeat(xml::MAX_DEPTH + 1), "".repeat(xml::MAX_DEPTH + 1)); + assert!(xml::parse(too_deep.as_bytes()).is_err()); + assert_eq!(scan(&too_deep).model_order(Some(u32::MAX - 1)), u32::MAX); + } +} diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 0f95b4f76f..c00b847f33 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -70,6 +70,7 @@ const MAX_TEMPLATE_PATH: usize = 32 * 1024; pub(crate) struct Reader<'p> { pkg: &'p Package, + file_orders: craft_wordmodel::para::FileOrders, pub doc: Document, pub pc: PropCtx, revs: HashMap<(u8, String, String, Option), u32>, @@ -167,7 +168,9 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, let rels = pkg.rels(&main); let mut doc = Document::new(); doc.body.clear(); + let file_orders = pkg.file_orders()?; let mut r = Reader { + file_orders, pkg, doc, pc: PropCtx::default(), diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index ea48efcca9..811225f4a1 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -20,7 +20,7 @@ impl Reader<'_> { let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); let (w, h) = (dim("cx"), dim("cy")); let (alt, meta) = nv_alt(c.child("wp:docPr")); - let mut float = if anchored { anchor_float(c) } else { Float::default() }; + let mut float = if anchored { anchor_float(c, self.file_orders) } else { Float::default() }; float.alt = meta; float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden")); if let Some(e) = c.child("wp:effectExtent") { @@ -620,11 +620,11 @@ fn nv_alt(p: Option<&El>) -> (String, AltText) { (descr, AltText { text: String::new(), title, decorative }) } -fn anchor_float(c: &El) -> Float { +fn anchor_float(c: &El, orders: craft_wordmodel::para::FileOrders) -> Float { // `relativeHeight`: the stacking order Word draws floating objects in (higher on top), which // need not be their order in the file. Kept one more (see `Float::z`): 0, the lowest a file // can give, isn't the 0 of an object without one, which stacks above them all. - let z = c.attr("relativeHeight").and_then(|v| v.trim().parse::().ok()).map_or(0, |z| z.saturating_add(1)); + let z = orders.model_order(c.attr("relativeHeight").and_then(|v| v.trim().parse::().ok())); let mut f = Float { wrap: Wrap::Square, z, ..Float::default() }; let behind = on_off_attr(c, "behindDoc"); // Word wraps a position relative to the page's size (`wp14:pctPosVOffset`) in diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index d15f592894..08dc4befd6 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -4912,3 +4912,58 @@ fn vml_horizontal_rules_are_read_and_kept() { let d = read_body(&body); assert_eq!(rules(&d).iter().map(|r| r.0).collect::>(), [None, None]); } + +#[test] +fn extreme_raw_orders_share_one_map_across_parts_without_replaying_chunks() { + let shape = |name: &str, z: &str| { + anchored_wsp(name, 127000, 127000, r#""#, "", "") + .replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#)) + }; + let doc = format!( + r#"{}{}{}"#, + shape("zero", "0"), + shape("lower", "4294967292"), + shape("high", "4294967294") + ); + let header = format!( + r#"{}{}"#, + shape("maximum", "4294967295").replace("relativeHeight", "alien:relativeHeight"), + shape("equal", "4294967295") + ) + .replace("xmlns:wp=", "xmlns:position=") + .replace("wp:", "position:"); + let header: Vec = [vec![0xff, 0xfe], header.encode_utf16().flat_map(u16::to_le_bytes).collect()].concat(); + let ignored = format!(r#"{}"#, shape("wrong-case duplicate", "4294967293")); + let rel = rels(&[("header", "header", "header.part"), ("chunk", "aFChunk", "chunk.txt")]); + let bytes = zip(&[ + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/_rels/document.xml.rels", rel.as_bytes()), + ("word/header.part", &header), + ("WORD/HEADER.PART", ignored.as_bytes()), + ("word/chunk.txt", b"external chunk"), + ]); + let calls = std::cell::Cell::new(0); + let importer = |_: &craft_docx::AltChunk| { + calls.set(calls.get() + 1); + Some(Document::from_text("Imported once")) + }; + let mut d = craft_docx::read_with(&bytes, &craft_docx::ReadOptions { chunks: Some(&importer), ..Default::default() }).unwrap(); + assert_eq!(calls.get(), 1); + let orders = |d: &Document| { + let body: Vec = paras(d).iter().flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); + let header = &d.parts[&d.last_section.headers.default.unwrap()]; + let header: Vec = + header.blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); + (body, header) + }; + let expected = (vec![1, u32::MAX - 2, u32::MAX - 1], vec![u32::MAX, u32::MAX]); + assert_eq!(orders(&d), expected); + for _ in 0..2 { + d = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + assert_eq!(orders(&d), expected); + } + assert_eq!(calls.get(), 1); + let malformed = doc.replace("", ""); + assert!(craft_docx::read(&zip(&[("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", malformed.as_bytes())])).is_err()); +} diff --git a/crates/odf/src/text/body.rs b/crates/odf/src/text/body.rs index 1b27932589..b5a2b39681 100644 --- a/crates/odf/src/text/body.rs +++ b/crates/odf/src/text/body.rs @@ -35,6 +35,7 @@ type Frame = (Option, Option, Option>, String, Option<(String, bool)>, Option, Option); pub(super) struct Body<'a> { + pub(super) file_orders: craft_wordmodel::para::FileOrders, styles: &'a Styles, zip: &'a mut dyn FnMut(&str) -> Option>, /// The package's entry names and its manifest's media types, for embedded objects. @@ -219,6 +220,7 @@ impl<'a> Body<'a> { pub(super) fn new(styles: &'a Styles, pages: &'a Pages, zip: &'a mut dyn FnMut(&str) -> Option>) -> Self { let page = pages.first.clone().unwrap_or_default(); Body { + file_orders: Default::default(), styles, zip, entries: &[], @@ -1164,6 +1166,25 @@ impl Body<'_> { } fn start(&mut self, q: &str, a: &Attrs) { + // Keep all existing attribute readers unchanged. Only the occupied upper tail + // is adjusted, before any frame/group/note reader can saturate its one-more z. + let adjusted = a + .iter() + .enumerate() + .find(|(_, (name, _))| name == "draw:z-index") + .and_then(|(i, (_, value))| value.trim().parse::().ok().map(|raw| (i, raw))) + .and_then(|(i, raw)| { + let mapped = self.file_orders.file_order(raw); + (mapped != raw).then_some((i, mapped)) + }); + let mut normalized; + let a = if let Some((i, mapped)) = adjusted { + normalized = a.clone(); + normalized[i].1 = mapped.to_string(); + &normalized + } else { + a + }; self.depth += 1; if q == "office:text" { self.in_text = true; diff --git a/crates/odf/src/text/frames.rs b/crates/odf/src/text/frames.rs index 6e1e22c6ff..457cfbdff3 100644 --- a/crates/odf/src/text/frames.rs +++ b/crates/odf/src/text/frames.rs @@ -725,3 +725,37 @@ pub(super) fn frame_of(f: &Float, w: f32, h: f32) -> (&'static str, String, Stri } (anchor, props, xy) } + +/// Scan the same already-inflated content/style streams as the body and header readers. +/// The existing event parser supplies the same entity, malformed-input and 128-attribute +/// truncation behavior; no picture fetch or embedded-object callback is invoked. +pub(super) fn read_orders(content: &[u8], styles: Option<&[u8]>) -> Result { + use craft_wordmodel::para::FileOrderScan; + let bytes = (content.len() as u64).checked_add(styles.map_or(0, |s| s.len() as u64)).ok_or("stacking-order source size overflow")?; + let mut scan = FileOrderScan::new(bytes)?; + for xml in std::iter::once(content).chain(styles) { + super::xml::events(xml, |ev| { + if let super::xml::Ev::Start(_, attrs) = ev + && let Some(raw) = get(&attrs, "draw:z-index").and_then(|s| s.trim().parse::().ok()) + { + scan.observe(raw); + } + }); + } + scan.finish() +} + +#[cfg(test)] +mod file_order_tests { + #[test] + fn file_order_scan_uses_the_existing_odf_attribute_and_entity_rules() { + let ignored = format!(r#""#, (0..128).map(|i| format!(r#"a{i}="x""#)).collect::>().join(" ")); + let map = super::read_orders(ignored.as_bytes(), None).unwrap(); + assert_eq!(map.model_order(Some(u32::MAX - 1)), u32::MAX); + let custom = br#"]>"#; + assert_eq!(super::read_orders(custom, None).unwrap().model_order(Some(u32::MAX - 1)), u32::MAX); + let numeric = br#""#; + let map = super::read_orders(numeric, None).unwrap(); + assert_eq!((map.model_order(Some(u32::MAX - 1)), map.model_order(Some(u32::MAX))), (u32::MAX - 1, u32::MAX)); + } +} diff --git a/crates/odf/src/text/import.rs b/crates/odf/src/text/import.rs index 486e67a260..930cf0b421 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -875,6 +875,7 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result { None if styles_xml.is_some() => EMPTY_CONTENT.as_bytes().to_vec(), None => return Err("ODT: content.xml is missing".into()), }; + let file_orders = super::frames::read_orders(&content, styles_xml.as_deref())?; let mut styles = Styles::default(); let mut pages = Pages::default(); if let Some(s) = &styles_xml { @@ -916,10 +917,13 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result { let objects = (entries.as_slice(), &manifest); // One `text:s` budget for the headers and footers and then the body. let mut spaces_left = MAX_EXTRA_SPACES; - let mut parts = - styles_xml.as_deref().map(|x| page_parts::read(x, &styles, &mut pages, &mut fetch, objects, &mut spaces_left)).unwrap_or_default(); + let mut parts = styles_xml + .as_deref() + .map(|x| page_parts::read(x, &styles, &mut pages, &mut fetch, objects, &mut spaces_left, file_orders)) + .unwrap_or_default(); first_pages(&mut pages); let mut body = Body::new(&styles, &pages, &mut fetch); + body.file_orders = file_orders; (body.entries, body.manifest) = (objects.0, Some(objects.1)); body.raw = &content; body.spaces_left = spaces_left; diff --git a/crates/odf/src/text/page_parts.rs b/crates/odf/src/text/page_parts.rs index 6a67da3af3..10eb7df7c4 100644 --- a/crates/odf/src/text/page_parts.rs +++ b/crates/odf/src/text/page_parts.rs @@ -78,6 +78,7 @@ pub(super) fn read( fetch: &mut dyn FnMut(&str) -> Option>, objects: (&[String], &std::collections::HashMap), spaces_left: &mut usize, + file_orders: craft_wordmodel::para::FileOrders, ) -> Parts { let mut found: Vec<(String, Slot, Vec)> = Vec::new(); let mut master: Option = None; @@ -127,6 +128,7 @@ pub(super) fn read( let mut out = Parts::default(); for (name, kind, evs) in found { let mut reader = Body::new(styles, &none, fetch); + reader.file_orders = file_orders; reader.in_text = true; (reader.entries, reader.manifest) = (objects.0, Some(objects.1)); reader.spaces_left = *spaces_left; diff --git a/crates/odf/src/text/tests_more/floats.rs b/crates/odf/src/text/tests_more/floats.rs index 00f18408a5..b5a55e9f77 100644 --- a/crates/odf/src/text/tests_more/floats.rs +++ b/crates/odf/src/text/tests_more/floats.rs @@ -572,3 +572,29 @@ fn extreme_stacking_orders_remain_distinct_after_repeated_roundtrips() { } } } + +#[test] +fn extreme_raw_orders_are_normalized_once_across_body_and_headers() { + let shape = |z: &str| format!(r#""#); + let content = format!( + r#"{}{}"#, + shape("0"), + shape("4294967294") + ); + let styles = format!( + r#"{}{}"#, + shape("4294967295"), + shape("4294967295") + ); + let mut d = import(&zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes())])).unwrap(); + for _ in 0..3 { + let body: Vec = + d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); + let header = &d.parts[&d.last_section.headers.default.unwrap()]; + let head: Vec = + header.blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); + assert_eq!(body, [1, u32::MAX - 1]); + assert_eq!(head, [u32::MAX, u32::MAX]); + d = import(&crate::text::tests::export_model(&d).unwrap()).unwrap(); + } +} diff --git a/crates/wordmodel/src/para.rs b/crates/wordmodel/src/para.rs index bbfeb9cbcf..b6e407cd13 100644 --- a/crates/wordmodel/src/para.rs +++ b/crates/wordmodel/src/para.rs @@ -13,11 +13,13 @@ use crate::props::{CharProps, ParaProps}; use crate::section::SectionProps; use crate::{DocError, Result}; +mod file_orders; mod float; mod inline_kinds; mod inline_object; mod run; +pub use file_orders::{FileOrderScan, FileOrders}; pub use float::{AltText, Anchor, Float, FloatAlign, MAX_ALT_TEXT, Wrap, WrapText, cap_alt}; pub use inline_kinds::{NoteKind, PTabAlign, PTabBase, RubyAlign, ShapeKind, ruby_offset, ruby_raise}; pub use inline_object::{CanvasStyle, GroupChild, InlineObject, MAX_GROUP_CHILDREN}; diff --git a/crates/wordmodel/src/para/file_orders.rs b/crates/wordmodel/src/para/file_orders.rs new file mode 100644 index 0000000000..9cb543d833 --- /dev/null +++ b/crates/wordmodel/src/para/file_orders.rs @@ -0,0 +1,102 @@ +//! Bounded conversion of unsigned file stacking orders to Float's zero-is-unset model. + +/// A file-order mapping. Ordinary files retain their exact one-more encoding. +#[derive(Clone, Copy, Debug, Default)] +pub struct FileOrders { + gap: Option, +} + +impl FileOrders { + /// A file order adjusted to leave room for its one-more model representation. + pub fn file_order(self, raw: u32) -> u32 { + raw - u32::from(self.gap.is_some_and(|gap| raw > gap)) + } + + /// An absent order remains unset; a present file order remains present. + pub fn model_order(self, raw: Option) -> u32 { + raw.map_or(0, |raw| self.file_order(raw).saturating_add(1)) + } +} + +/// Collect every raw order before decoding any. No document or callback is replayed. +/// +/// The upper window has more slots than the source can contain distinct ten-digit +/// orders. Only this window can be shifted. XML callers must count all source bytes, +/// decode attributes exactly as their reader does, and never expand custom entities. +pub struct FileOrderScan { + seen: Vec, + slots: usize, +} + +impl FileOrderScan { + /// Most source bytes scanned. This also caps the bitmap below 26 MiB. + pub const MAX_SOURCE_BYTES: u64 = 2 * 1024 * 1024 * 1024; + + /// Allocate fallibly; reject an unbounded source rather than truncating the scan. + pub fn new(source_bytes: u64) -> Result { + if source_bytes > Self::MAX_SOURCE_BYTES { + return Err("stacking-order source exceeds 2 GiB".into()); + } + let slots = (source_bytes / 10 + 1) as usize; + let size = slots.div_ceil(8); + let mut seen = Vec::new(); + seen.try_reserve_exact(size).map_err(|_| "stacking-order bitmap allocation failed")?; + seen.resize(size, 0); + Ok(Self { seen, slots }) + } + + /// Observe a decoded unsigned order. Repeated values cost no extra memory. + pub fn observe(&mut self, raw: u32) { + let distance = (u32::MAX - raw) as usize; + if distance < self.slots + && let Some(byte) = self.seen.get_mut(distance / 8) + { + *byte |= 1 << (distance % 8); + } + } + + /// Finish after the complete source traversal, before constructing model floats. + pub fn finish(self) -> Result { + if self.seen.first().is_none_or(|b| b & 1 == 0) { + return Ok(FileOrders::default()); + } + for (i, byte) in self.seen.into_iter().enumerate() { + if byte == u8::MAX { + continue; + } + let distance = i * 8 + (!byte).trailing_zeros() as usize; + if distance < self.slots { + return Ok(FileOrders { gap: Some(u32::MAX - distance as u32) }); + } + } + Err("stacking-order scan did not cover its source".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn upper_tail_is_injective_and_leaves_ordinary_orders_alone() { + let raw = [0, 1, 251658240, u32::MAX - 2, u32::MAX - 1, u32::MAX, u32::MAX]; + let mut scan = FileOrderScan::new(raw.len() as u64 * 10).unwrap(); + for raw in raw { + scan.observe(raw); + } + let map = scan.finish().unwrap(); + assert_eq!(raw.map(|raw| map.model_order(Some(raw))), [1, 2, 251658241, u32::MAX - 2, u32::MAX - 1, u32::MAX, u32::MAX]); + assert_eq!(map.model_order(None), 0); + } + + #[test] + fn no_max_means_no_renumbering_and_source_limits_fail_closed() { + let mut scan = FileOrderScan::new(100).unwrap(); + scan.observe(u32::MAX - 1); + assert_eq!(scan.finish().unwrap().model_order(Some(u32::MAX - 1)), u32::MAX); + assert!(FileOrderScan::new(FileOrderScan::MAX_SOURCE_BYTES + 1).is_err()); + let mut incomplete = FileOrderScan::new(0).unwrap(); + incomplete.observe(u32::MAX); + assert!(incomplete.finish().is_err()); + } +} From 98f50bc151d427504422e96ce5242ed4a5fafea0 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 20:01:11 +0100 Subject: [PATCH 07/15] Preserve retained ODF markup while normalizing stacking orders --- crates/odf/src/text/body.rs | 21 ---- crates/odf/src/text/frames.rs | 39 ++----- crates/odf/src/text/import.rs | 13 ++- crates/odf/src/text/package.rs | 10 +- crates/odf/src/text/page_parts.rs | 2 - crates/odf/src/text/tests_more/floats.rs | 51 ++++++++- crates/odf/src/text/xml.rs | 138 +++++++++++++++++++++++ 7 files changed, 214 insertions(+), 60 deletions(-) diff --git a/crates/odf/src/text/body.rs b/crates/odf/src/text/body.rs index b5a2b39681..1b27932589 100644 --- a/crates/odf/src/text/body.rs +++ b/crates/odf/src/text/body.rs @@ -35,7 +35,6 @@ type Frame = (Option, Option, Option>, String, Option<(String, bool)>, Option, Option); pub(super) struct Body<'a> { - pub(super) file_orders: craft_wordmodel::para::FileOrders, styles: &'a Styles, zip: &'a mut dyn FnMut(&str) -> Option>, /// The package's entry names and its manifest's media types, for embedded objects. @@ -220,7 +219,6 @@ impl<'a> Body<'a> { pub(super) fn new(styles: &'a Styles, pages: &'a Pages, zip: &'a mut dyn FnMut(&str) -> Option>) -> Self { let page = pages.first.clone().unwrap_or_default(); Body { - file_orders: Default::default(), styles, zip, entries: &[], @@ -1166,25 +1164,6 @@ impl Body<'_> { } fn start(&mut self, q: &str, a: &Attrs) { - // Keep all existing attribute readers unchanged. Only the occupied upper tail - // is adjusted, before any frame/group/note reader can saturate its one-more z. - let adjusted = a - .iter() - .enumerate() - .find(|(_, (name, _))| name == "draw:z-index") - .and_then(|(i, (_, value))| value.trim().parse::().ok().map(|raw| (i, raw))) - .and_then(|(i, raw)| { - let mapped = self.file_orders.file_order(raw); - (mapped != raw).then_some((i, mapped)) - }); - let mut normalized; - let a = if let Some((i, mapped)) = adjusted { - normalized = a.clone(); - normalized[i].1 = mapped.to_string(); - &normalized - } else { - a - }; self.depth += 1; if q == "office:text" { self.in_text = true; diff --git a/crates/odf/src/text/frames.rs b/crates/odf/src/text/frames.rs index 457cfbdff3..2a2beee2f0 100644 --- a/crates/odf/src/text/frames.rs +++ b/crates/odf/src/text/frames.rs @@ -443,18 +443,17 @@ pub(super) fn z_of(a: &Attrs) -> u32 { get(a, "draw:z-index").and_then(|v| v.trim().parse::().ok()).map_or(0, |z| z.saturating_add(1)) } -/// Export orders leave room for the one-more representation used on import. -/// At the upper boundary, remove an unused model order rather than saturating. +/// Raw export orders. The package writer normalizes their upper boundary once, +/// after adding all retained markup, leaving room for one-more model orders. #[derive(Clone, Copy, Default)] pub(crate) struct Stacking { unset: u32, - gap: Option, } /// A stored order stays below every unset order; equal stored orders remain equal. pub(crate) fn z_index(float: Option<&Float>, stacking: Stacking) -> u32 { match float.map(|f| f.z) { - Some(z) if z > 0 => z - 1 - u32::from(stacking.gap.is_some_and(|gap| z > gap)), + Some(z) if z > 0 => z - 1, _ => stacking.unset, } } @@ -463,25 +462,21 @@ pub(crate) fn z_index(float: Option<&Float>, stacking: Stacking) -> u32 { pub(crate) fn stacking(doc: &craft_wordmodel::Document) -> Result { use craft_wordmodel::para::{GroupChild, InlineObject}; use std::collections::BTreeSet; - fn members(children: &[GroupChild], depth: usize, orders: &mut BTreeSet, unset: &mut bool) { + fn members(children: &[GroupChild], depth: usize, orders: &mut BTreeSet) { for c in children { if let Some((_, _, f)) = c.obj.frame() && f.z > 0 { orders.insert(f.z); } - if let Some((_, _, f)) = c.obj.frame() { - *unset |= f.z == 0; - } if let InlineObject::Group { children, .. } = &c.obj && depth < craft_flow::MAX_GROUP_DEPTH { - members(children, depth + 1, orders, unset); + members(children, depth + 1, orders); } } } - let (mut orders, unset_count) = doc.stacking_orders(); - let mut unset = unset_count > 0; + let (mut orders, _) = doc.stacking_orders(); for blocks in std::iter::once(&doc.body).chain(doc.parts.values().map(|p| &p.blocks)) { for b in blocks { craft_wordmodel::walk::each_para(b, 0, &mut |p| { @@ -491,30 +486,16 @@ pub(crate) fn stacking(doc: &craft_wordmodel::Document) -> Result Result { None => return Err("ODT: content.xml is missing".into()), }; let file_orders = super::frames::read_orders(&content, styles_xml.as_deref())?; + // Normalize source values before both model parsing and retained-markup capture. + // Rewriting values only keeps unknown XML and the model on the same order scale. + let content = super::xml::remap_orders(&content, |raw| file_orders.file_order(raw))?; + let styles_normalized = styles_xml.as_deref().map(|xml| super::xml::remap_orders(xml, |raw| file_orders.file_order(raw))).transpose()?; + let styles_xml = styles_normalized; let mut styles = Styles::default(); let mut pages = Pages::default(); if let Some(s) = &styles_xml { @@ -917,13 +922,11 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result { let objects = (entries.as_slice(), &manifest); // One `text:s` budget for the headers and footers and then the body. let mut spaces_left = MAX_EXTRA_SPACES; - let mut parts = styles_xml - .as_deref() - .map(|x| page_parts::read(x, &styles, &mut pages, &mut fetch, objects, &mut spaces_left, file_orders)) - .unwrap_or_default(); + let mut parts = + styles_xml.as_deref().map(|x| page_parts::read(x, &styles, &mut pages, &mut fetch, objects, &mut spaces_left)).unwrap_or_default(); first_pages(&mut pages); let mut body = Body::new(&styles, &pages, &mut fetch); - body.file_orders = file_orders; + (body.entries, body.manifest) = (objects.0, Some(objects.1)); body.raw = &content; body.spaces_left = spaces_left; diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index f7a9d164d8..62d27940ac 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -1257,10 +1257,16 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { None => styles, }; let (content, styles) = with_kept_defs(content, styles, &w.kept_used, &w.kept_defs); + // Choose the gap from everything actually written, including unknown retained + // drawings and master pages. Remapping modeled frames alone can alias an order + // present only in retained XML. Values are spliced without reserializing XML. + let orders = super::frames::read_orders(content.as_bytes(), Some(styles.as_bytes()))?; + let content = super::xml::remap_orders(content.as_bytes(), |raw| orders.file_order(raw))?; + let styles = super::xml::remap_orders(styles.as_bytes(), |raw| orders.file_order(raw))?; // The manifest lists every file already: the writer adds the files only. for (name, data) in [ - ("content.xml", content.as_bytes()), - ("styles.xml", styles.as_bytes()), + ("content.xml", content.as_ref()), + ("styles.xml", styles.as_ref()), ("meta.xml", meta.as_bytes()), ("settings.xml", settings_xml(doc).as_bytes()), ] { diff --git a/crates/odf/src/text/page_parts.rs b/crates/odf/src/text/page_parts.rs index 10eb7df7c4..6a67da3af3 100644 --- a/crates/odf/src/text/page_parts.rs +++ b/crates/odf/src/text/page_parts.rs @@ -78,7 +78,6 @@ pub(super) fn read( fetch: &mut dyn FnMut(&str) -> Option>, objects: (&[String], &std::collections::HashMap), spaces_left: &mut usize, - file_orders: craft_wordmodel::para::FileOrders, ) -> Parts { let mut found: Vec<(String, Slot, Vec)> = Vec::new(); let mut master: Option = None; @@ -128,7 +127,6 @@ pub(super) fn read( let mut out = Parts::default(); for (name, kind, evs) in found { let mut reader = Body::new(styles, &none, fetch); - reader.file_orders = file_orders; reader.in_text = true; (reader.entries, reader.manifest) = (objects.0, Some(objects.1)); reader.spaces_left = *spaces_left; diff --git a/crates/odf/src/text/tests_more/floats.rs b/crates/odf/src/text/tests_more/floats.rs index b5a55e9f77..d78c7a4a95 100644 --- a/crates/odf/src/text/tests_more/floats.rs +++ b/crates/odf/src/text/tests_more/floats.rs @@ -595,6 +595,55 @@ fn extreme_raw_orders_are_normalized_once_across_body_and_headers() { header.blocks.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); assert_eq!(body, [1, u32::MAX - 1]); assert_eq!(head, [u32::MAX, u32::MAX]); - d = import(&crate::text::tests::export_model(&d).unwrap()).unwrap(); + d = import(&export(&d).unwrap()).unwrap(); + } +} + +#[test] +fn kept_stacking_markup_remaps_without_losing_unknown_attributes() { + for raw in ["4294967294", "4294967295"] { + let kept = format!( + r#""# + ); + let content = format!( + r#"{kept}"# + ); + let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap(); + let extra = format!( + r#""# + ); + let mut added = import(&zip_of(&[("content.xml", extra.as_bytes())])).unwrap(); + added.objects_mut(&|o| o.frame().is_some(), &mut |o| o.float_mut().unwrap().z = 0); + d.body.extend(added.body); + for pass in 0..3 { + let bytes = export(&d).unwrap(); + let xml = crate::text::tests::entry(&bytes, "content.xml"); + let expected = kept.replace(raw, "4294967293"); + assert!(xml.contains(&expected), "kept XML lost or order not remapped, {raw}, pass {pass}: {xml}"); + d = import(&bytes).unwrap(); + let orders: Vec = + d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); + assert_eq!(orders, [u32::MAX - 1, u32::MAX], "{raw}, pass {pass}"); + } + } +} + +#[test] +fn retained_unknown_orders_participate_in_the_export_gap() { + let kept = r#""#; + let content = + format!(r#"{kept}"#); + let mut d = import(&zip_of(&[("content.xml", content.as_bytes())])).unwrap(); + let mut extra = d.body[0].as_para().unwrap().clone(); + extra.objects[0].float_mut().unwrap().z = 0; + d.body.push(craft_wordmodel::para_block(extra)); + for pass in 0..3 { + let bytes = export(&d).unwrap(); + let xml = crate::text::tests::entry(&bytes, "content.xml"); + assert!(xml.contains(""), "pass {pass}: {xml}"); + d = import(&bytes).unwrap(); + let orders: Vec = + d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| &p.objects).filter_map(|o| o.frame().map(|(_, _, f)| f.z)).collect(); + assert_eq!(orders, [u32::MAX - 1, u32::MAX]); } } diff --git a/crates/odf/src/text/xml.rs b/crates/odf/src/text/xml.rs index d96ee49170..706056270c 100644 --- a/crates/odf/src/text/xml.rs +++ b/crates/odf/src/text/xml.rs @@ -70,3 +70,141 @@ pub(super) fn events_at(xml: &[u8], mut f: impl FnMut(Ev, (usize, usize))) { } } } + +/// Rewrite only the first interpreted draw:z-index value in each start tag. +/// Event spans exclude comments/CDATA and retain the reader's first-128-attribute +/// policy. All bytes outside changed values (including unknown markup) survive. +pub(super) fn remap_orders(xml: &[u8], map: impl Fn(u32) -> u32) -> Result, String> { + // Callers only remove one unused upper-order slot: unchanged MAX means identity. + if map(u32::MAX) == u32::MAX { + return Ok(std::borrow::Cow::Borrowed(xml)); + } + let mut out = Vec::new(); + let mut copied = 0; + let mut error = None; + events_at(xml, |ev, (start, end)| { + if error.is_some() { + return; + } + let Ev::Start(_, attrs) = ev else { return }; + let Some(raw) = get(&attrs, "draw:z-index").and_then(|s| s.trim().parse::().ok()) else { return }; + let mapped = map(raw); + if mapped == raw { + return; + } + let Some(tag) = xml.get(start..end) else { return }; + let Some(range) = order_value(tag) else { + error = Some("ODT: cannot locate retained stacking attribute".to_string()); + return; + }; + let from = start + range.start; + let to = start + range.end; + // Maps never increase a value; decimal replacement cannot exceed its source bytes. + if out.is_empty() && out.try_reserve_exact(xml.len()).is_err() { + error = Some("ODT: cannot allocate normalized stacking markup".to_string()); + return; + } + out.extend_from_slice(&xml[copied..from]); + out.extend_from_slice(mapped.to_string().as_bytes()); + copied = to; + }); + if let Some(error) = error { + return Err(error); + } + if copied == 0 { + return Ok(std::borrow::Cow::Borrowed(xml)); + } + out.extend_from_slice(&xml[copied..]); + Ok(std::borrow::Cow::Owned(out)) +} + +/// Locate a quoted value in an already parsed start tag, not in arbitrary XML. +/// Skip entire quoted values so attribute-looking text inside them is untouched. +fn order_value(tag: &[u8]) -> Option> { + let mut i = 1; + while i < tag.len() && !tag[i].is_ascii_whitespace() && !matches!(tag[i], b'/' | b'>') { + i += 1; + } + while i < tag.len() { + while i < tag.len() && tag[i].is_ascii_whitespace() { + i += 1; + } + let begin = i; + while i < tag.len() && !tag[i].is_ascii_whitespace() && !matches!(tag[i], b'=' | b'/' | b'>') { + i += 1; + } + let name = tag.get(begin..i)?; + if name.is_empty() { + // The lenient parser can recover after a stray delimiter before an attribute. + i += 1; + continue; + } + while i < tag.len() && tag[i].is_ascii_whitespace() { + i += 1; + } + if tag.get(i) != Some(&b'=') { + continue; + } + i += 1; + while i < tag.len() && tag[i].is_ascii_whitespace() { + i += 1; + } + let quote = *tag.get(i)?; + if !matches!(quote, b'\'' | b'"') { + while i < tag.len() && !tag[i].is_ascii_whitespace() { + i += 1; + } + continue; + } + i += 1; + let from = i; + while i < tag.len() && tag[i] != quote { + i += 1; + } + if i == tag.len() { + return None; + } + if name == b"draw:z-index" { + return Some(from..i); + } + i += 1; + } + None +} + +#[cfg(test)] +mod order_tests { + use super::*; + + #[test] + fn order_remap_preserves_every_other_byte() { + let xml = br#"

"#; + let expected = br#"

"#; + assert_eq!(remap_orders(xml, |n| n.saturating_sub(1)).unwrap().as_ref(), expected); + assert!(matches!(remap_orders(xml, |n| n).unwrap(), std::borrow::Cow::Borrowed(_))); + let late = format!("", (0..128).map(|i| format!("a{i}='x'")).collect::>().join(" ")); + assert_eq!(remap_orders(late.as_bytes(), |n| n - 1).unwrap().as_ref(), late.as_bytes()); + for broken in ["=bad", "x=bad", "x==bad", "x", "x='a' x", "x=\"bad\"", "'odd'", "/odd", "x='a>b'"] { + let input = format!(""); + let mut seen = false; + events(input.as_bytes(), |e| { + if let Ev::Start(_, a) = e { + seen |= get(&a, "draw:z-index") == Some("99"); + } + }); + if seen { + let changed = remap_orders(input.as_bytes(), |n| n - 1).unwrap_or_else(|e| panic!("{input}: {e}")); + let mut found = false; + events(&changed, |e| { + if let Ev::Start(_, a) = e { + found |= get(&a, "draw:z-index") == Some("98"); + } + }); + assert!(found, "{input}"); + } + } + // Lenient malformed attributes are skipped just as in the reader. + let malformed = b""; + assert_eq!(remap_orders(malformed, |n| n - 1).unwrap().as_ref(), b""); + } +} From c153d95e5587c26655ba543f6315dc7fadf2adcf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:22:29 -0500 Subject: [PATCH 08/15] craft-plist: explicit legacy binary minor-version compatibility (#1980) --- crates/plist/src/binary.rs | 22 ++++++++++++++++++---- crates/plist/src/lib.rs | 2 +- crates/plist/tests/plist_marker_widths.rs | 23 +++++++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs index 3fe6aed926..241c83ba3b 100644 --- a/crates/plist/src/binary.rs +++ b/crates/plist/src/binary.rs @@ -68,6 +68,15 @@ struct Bin<'a> { limits: Limits, } +/// Explicit legacy version-admission policy. Structural validation is never relaxed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BinaryOptions { + /// Accept any eighth header byte after `bplist0`, matching historical inspection readers. + /// This is not support for a new binary encoding: all objects still obey the bplist00 + /// grammar and bounds. The default accepts only the exact `bplist00` header. + pub allow_unknown_minor_version: bool, +} + /// Parse a `bplist00` binary property list. pub fn parse_binary(data: &[u8]) -> Result { parse_binary_with_limits(data, Limits::default()) @@ -75,19 +84,24 @@ pub fn parse_binary(data: &[u8]) -> Result { /// Parse a binary property list, with caller-selected input, object, expansion and nesting limits. pub fn parse_binary_with_limits(data: &[u8], limits: Limits) -> Result { - let (mut b, top) = reader(data, limits)?; + parse_binary_with_options(data, limits, BinaryOptions::default()) +} + +/// Parse with explicit version admission and the same structural/resource checks as the strict reader. +pub fn parse_binary_with_options(data: &[u8], limits: Limits, options: BinaryOptions) -> Result { + let (mut b, top) = reader(data, limits, options)?; let mut stack = reserved(limits.max_depth.min(256))?; b.object(top, &mut stack) } -fn reader(data: &[u8], limits: Limits) -> Result<(Bin<'_>, usize), FormatError> { +fn reader(data: &[u8], limits: Limits, options: BinaryOptions) -> Result<(Bin<'_>, usize), FormatError> { if data.len() > limits.max_input_bytes { return Err(FormatError::TooLarge("input bytes".into())); } if !data.starts_with(b"bplist") { return Err(FormatError::Malformed("not a binary plist".into())); } - if !data.starts_with(b"bplist00") { + if !data.starts_with(if options.allow_unknown_minor_version { b"bplist0".as_slice() } else { b"bplist00".as_slice() }) { return Err(FormatError::Unsupported("unknown binary plist version".into())); } let len = data.len(); @@ -344,7 +358,7 @@ fn reserved_string(n: usize) -> Result { /// selected objects and resource exhaustion return errors. Unselected value graphs are not /// validated. This permits preference readers to ignore unrelated future object kinds. pub fn first_string_in_array(data: &[u8], key: &str, limits: Limits) -> Result, FormatError> { - let (mut b, top) = reader(data, limits)?; + let (mut b, top) = reader(data, limits, BinaryOptions::default())?; let (kind, n, start) = b.header(top)?; if kind != 0xd { return Ok(None); diff --git a/crates/plist/src/lib.rs b/crates/plist/src/lib.rs index d84980398e..826bbe4b2f 100644 --- a/crates/plist/src/lib.rs +++ b/crates/plist/src/lib.rs @@ -5,7 +5,7 @@ mod binary; mod bytes; mod xml; -pub use binary::{DateValue, Value, first_string_in_array, parse_binary, parse_binary_with_limits}; +pub use binary::{BinaryOptions, DateValue, Value, first_string_in_array, parse_binary, parse_binary_with_limits, parse_binary_with_options}; pub use xml::{XmlOptions, parse_xml, parse_xml_with_limits, parse_xml_with_options, parse_xml_with_token_limit}; /// Caller-selected resource limits. Zero values refuse the corresponding resource. diff --git a/crates/plist/tests/plist_marker_widths.rs b/crates/plist/tests/plist_marker_widths.rs index 5873371e76..d636c07035 100644 --- a/crates/plist/tests/plist_marker_widths.rs +++ b/crates/plist/tests/plist_marker_widths.rs @@ -45,3 +45,26 @@ fn supported_maximum_widths_keep_their_values() { empty.extend_from_slice(&0u64.to_be_bytes()); assert!(matches!(parse_binary(&single_object(&empty)), Ok(Value::Data(d)) if d.is_empty())); } + +#[test] +fn minor_version_compatibility_is_explicit_and_keeps_bounds() { + use craft_plist::{BinaryOptions, FormatError, Limits, parse_binary_with_options}; + let compat = BinaryOptions { allow_unknown_minor_version: true }; + for minor in [b'0', b'1', b'9', 0xff] { + let mut data = single_object(&[0x00]); + data[7] = minor; + assert!(matches!(parse_binary_with_options(&data, Limits::default(), compat), Ok(Value::Null))); + assert_eq!(parse_binary(&data).is_ok(), minor == b'0'); + let limited = Limits { max_nodes: 0, ..Limits::default() }; + assert!(matches!(parse_binary_with_options(&data, limited, compat), Err(FormatError::TooLarge(_)))); + data[6] = b'1'; + assert!(matches!(parse_binary_with_options(&data, Limits::default(), compat), Err(FormatError::Unsupported(_)))); + } + let mut invalid = single_object(&[0x15]); + invalid[7] = b'1'; + assert!(matches!(parse_binary_with_options(&invalid, Limits::default(), compat), Err(FormatError::Malformed(_)))); + let mut cycle = single_object(&[0xa1, 0]); + cycle[7] = b'1'; + assert!(matches!(parse_binary_with_options(&cycle, Limits::default(), compat), Err(FormatError::Malformed(_)))); + assert!(parse_binary_with_options(b"bplist01", Limits::default(), compat).is_err()); +} From bee6842e8af2716e6d7c4f17e6b9f68912249777 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:22:32 -0500 Subject: [PATCH 09/15] lottie: caller-owned numeric precision for Bezier path writing (#1979) --- crates/lottie/src/path.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/lottie/src/path.rs b/crates/lottie/src/path.rs index a8301ccbae..f404b3b6b8 100644 --- a/crates/lottie/src/path.rs +++ b/crates/lottie/src/path.rs @@ -40,7 +40,29 @@ impl Bezier { /// The path as `{c, v, i, o}`, coordinates rounded to six decimals. pub fn to_json(&self) -> Json { - let pts = |v: &[[f64; 2]]| v.iter().map(|[x, y]| json!([round6(*x), round6(*y)])).collect::>(); + self.to_json_with(|v| json!(round6(v))) + } + + /// Writes the path with a caller-owned numeric representation (for example, + /// three-decimal compact exports). Geometry and tangent lengths are unchanged. + /// The callback is applied to every coordinate; callers own finite-value policy. + pub fn to_json_with(&self, number: impl Fn(f64) -> Json) -> Json { + let pts = |v: &[[f64; 2]]| v.iter().map(|[x, y]| Json::Array(vec![number(*x), number(*y)])).collect::>(); json!({"c": self.closed, "v": pts(&self.vertices), "i": pts(&self.in_tangents), "o": pts(&self.out_tangents)}) } } + +#[cfg(test)] +mod policy_tests { + use super::*; + + #[test] + fn caller_number_policy_is_applied_without_prior_rounding() { + let p = Bezier { closed: true, vertices: vec![[1.23456, 1e303]], in_tangents: vec![[0.0, -2.0]], out_tangents: vec![] }; + let raw = p.to_json_with(|v| json!(v)); + assert_eq!(raw, json!({"c": true, "v": [[1.23456, 1e303]], "i": [[0.0, -2.0]], "o": []})); + let zero = p.to_json_with(|_| json!(0)); + assert_eq!(zero, json!({"c": true, "v": [[0, 0]], "i": [[0, 0]], "o": []})); + assert_eq!(Bezier::default().to_json(), json!({"c": false, "v": [], "i": [], "o": []})); + } +} From 06496f5bf20988123d319f83f9a51523218c2173 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:22:35 -0500 Subject: [PATCH 10/15] craft-psd: decode strict PackBits rows into caller-owned slices (#1978) --- crates/psd/src/compression.rs | 71 +++++++++++++++++++++++++---- crates/psd/src/compression/tests.rs | 41 +++++++++++++++++ 2 files changed, 102 insertions(+), 10 deletions(-) diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 8383b30c0e..987b306b4d 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -225,13 +225,61 @@ pub mod packbits { decode_row(src, expected, out, true) } + /// Decodes a strict PackBits row directly into caller-owned storage, without allocating. + /// + /// The output must be filled exactly: short input, truncated packets and packets that + /// overflow the row are errors. Trailing bytes after the row is full are ignored, as by + /// [`decode`]. An error may leave a decoded prefix in `out`; its remaining bytes are unchanged. + pub fn decode_to_slice(src: &[u8], out: &mut [u8]) -> Result<()> { + let mut offset: usize = 0; + decode_packets(src, out.len(), false, |packet| { + let len = packet.len(); + // The walker caps each packet by the remaining row, before exposing it here. + let end = offset.checked_add(len).ok_or(PsdError::LimitExceeded("PackBits output offset overflow"))?; + let dst = out.get_mut(offset..end).ok_or(PsdError::LimitExceeded("PackBits output slice overflow"))?; + match packet { + RowPacket::Literal(bytes) => dst.copy_from_slice(bytes), + RowPacket::Fill(value, _) => dst.fill(value), + } + offset = end; + Ok(()) + }) + } + + enum RowPacket<'a> { + Literal(&'a [u8]), + Fill(u8, usize), + } + + impl RowPacket<'_> { + fn len(&self) -> usize { + match self { + Self::Literal(bytes) => bytes.len(), + Self::Fill(_, len) => *len, + } + } + } + fn decode_row(src: &[u8], expected: usize, out: &mut Vec, padded: bool) -> Result<()> { - let target = out.len().checked_add(expected).ok_or(PsdError::LimitExceeded("PackBits output length overflows usize"))?; + out.len().checked_add(expected).ok_or(PsdError::LimitExceeded("PackBits output length overflows usize"))?; + decode_packets(src, expected, padded, |packet| { + match packet { + RowPacket::Literal(bytes) => out.extend_from_slice(bytes), + RowPacket::Fill(value, len) => out.extend(std::iter::repeat_n(value, len)), + } + Ok(()) + }) + } + + // One packet walker serves strict Vec, strict slice and padded recovery decoding. It + // validates the complete payload before clipping or emitting, preserving recovery errors. + fn decode_packets(src: &[u8], expected: usize, padded: bool, mut emit: impl FnMut(RowPacket<'_>) -> Result<()>) -> Result<()> { + let mut remaining = expected; let mut i = 0; - while out.len() < target { + while remaining > 0 { let Some(&h) = src.get(i) else { if padded { - out.resize(target, 0); + emit(RowPacket::Fill(0, remaining))?; break; } return Err(PsdError::Decompress("PackBits row ended early".into())); @@ -240,25 +288,28 @@ pub mod packbits { let h = h as i8; if h >= 0 { let len = h as usize + 1; - let Some(lit) = src.get(i..i + len) else { + let Some(lit) = i.checked_add(len).and_then(|end| src.get(i..end)) else { return Err(PsdError::Decompress("PackBits literal truncated".into())); }; - if !padded && len > target - out.len() { + if !padded && len > remaining { return Err(PsdError::Decompress("PackBits literal overflows row".into())); } - out.extend_from_slice(&lit[..len.min(target - out.len())]); + let take = len.min(remaining); + emit(RowPacket::Literal(&lit[..take]))?; + remaining -= take; i += len; } else if h != -128 { - let len = 1 - h as isize; - let len = len as usize; + let len = (1 - h as isize) as usize; let Some(&b) = src.get(i) else { return Err(PsdError::Decompress("PackBits run truncated".into())); }; i += 1; - if !padded && len > target - out.len() { + if !padded && len > remaining { return Err(PsdError::Decompress("PackBits run overflows row".into())); } - out.extend(std::iter::repeat_n(b, len.min(target - out.len()))); + let take = len.min(remaining); + emit(RowPacket::Fill(b, take))?; + remaining -= take; } } Ok(()) diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs index df4093aa3a..5f162dea71 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -829,3 +829,44 @@ fn caller_scratch_prediction_rejects_invalid_inputs_before_mutation() { unpredict_with_scratch(&mut [], &empty, &mut []).unwrap(); } } + +#[test] +fn packbits_slice_matches_strict_rows_and_preserves_guards() { + for (src, width) in [ + (vec![1, 10, 11, 128, 254, 7], 5), + (vec![129, 9], 128), + (vec![0, 4, 255], 1), // Ignore trailing malformed packets once full. + (vec![], 0), + (vec![128], 1), + (vec![2, 1], 3), + (vec![255], 2), + (vec![255, 9], 1), + (vec![1, 1, 2], 1), + (vec![0, 8, 128], 2), + ] { + let mut guarded = vec![0xA5; width + 2]; + let result = packbits::decode_to_slice(&src, &mut guarded[1..width + 1]); + let reference = packbits::decode(&src, width); + assert_eq!(result.is_ok(), reference.is_ok(), "{src:?}, width={width}"); + if let Ok(expected) = reference { + assert_eq!(&guarded[1..width + 1], expected); + } + assert_eq!(guarded[0], 0xA5); + assert_eq!(guarded[width + 1], 0xA5); + } + let mut out = [0xA5; 3]; + assert!(packbits::decode_to_slice(&[0, 8, 255], &mut out).is_err()); + assert_eq!(out, [8, 0xA5, 0xA5], "failure retains only completed packets"); +} + +#[test] +fn packbits_slice_roundtrips_all_packet_lengths() { + for len in 0..=256 { + for bytes in [vec![42; len], (0..len).map(|i| i as u8).collect()] { + let encoded = packbits::encode_vec(&bytes); + let mut out = vec![0; len]; + packbits::decode_to_slice(&encoded, &mut out).unwrap(); + assert_eq!(out, bytes); + } + } +} From fbb3f47f7ae712192586984af11ca8f6c0f64d33 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:24:56 -0500 Subject: [PATCH 11/15] craft-markdown: share extracted-text paragraphs and pipe-table writer (#1981) --- crates/markdown/src/escaping.rs | 24 ++++ crates/markdown/src/export.rs | 13 +- crates/markdown/src/extracted.rs | 228 +++++++++++++++++++++++++++++++ crates/markdown/src/lib.rs | 2 + 4 files changed, 255 insertions(+), 12 deletions(-) create mode 100644 crates/markdown/src/escaping.rs create mode 100644 crates/markdown/src/extracted.rs diff --git a/crates/markdown/src/escaping.rs b/crates/markdown/src/escaping.rs new file mode 100644 index 0000000000..f72bb51867 --- /dev/null +++ b/crates/markdown/src/escaping.rs @@ -0,0 +1,24 @@ +// One character walker, with explicit output policies: ordinary Markdown keeps line +// structure; extracted text flattens it and strips unrepresentable/control characters. +pub(crate) fn escape(s: &str, extracted: bool) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + if extracted && !matches!(c, '\t' | '\n' | '\r') && (c.is_ascii_control() || matches!(c, '\u{FFFE}' | '\u{FFFF}')) { + continue; + } + match c { + '\n' | '\r' | '\t' if extracted => out.push(' '), + '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '|' | '&' => { + out.push('\\'); + out.push(c); + } + '#' | '!' if extracted => { + out.push('\\'); + out.push(c); + } + '\u{000C}' | '\u{000E}' => {} + _ => out.push(c), + } + } + out +} diff --git a/crates/markdown/src/export.rs b/crates/markdown/src/export.rs index 82fd952e3f..076f9dcdd3 100644 --- a/crates/markdown/src/export.rs +++ b/crates/markdown/src/export.rs @@ -7,18 +7,7 @@ use super::{Align, Arc, Cell, Document, FBlock, FTable, Fmt, Inline, Kind, model /// Escape text for Markdown (inline context). pub fn escape(s: &str) -> String { - let mut out = String::with_capacity(s.len() + 8); - for c in s.chars() { - match c { - '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '~' | '|' | '&' => { - out.push('\\'); - out.push(c); - } - '\u{000C}' | '\u{000E}' => {} - _ => out.push(c), - } - } - out + crate::escaping::escape(s, false) } /// Escape what would start a block at the beginning of a line. Leading spaces are kept, but at diff --git a/crates/markdown/src/extracted.rs b/crates/markdown/src/extracted.rs new file mode 100644 index 0000000000..4f40caf75c --- /dev/null +++ b/crates/markdown/src/extracted.rs @@ -0,0 +1,228 @@ +//! Markdown export for extracted text: one line per paragraph, conservative markup escaping, +//! styled runs, pipe tables and explicit page separators. Unlike [`crate::export`], this mode +//! does not infer a word-processing document or normalize its block structure. Callers keep +//! layout/reading-order detection and bound the amount of supplied text and table data. +// Extracted from PDFCraft's Markdown writer (Adrian), including the empty-run correction +// by jonathanwxh-cell. The source remains shared here rather than copied into app adapters. + +const MAX_HEADING: u8 = 6; +/// Largest span represented by a table cell, matching the supported pipe-table grid. +pub const MAX_SPAN: usize = 63; + +fn md_text(s: &str) -> String { + crate::escaping::escape(s, true) +} + +/// A table cell supplied by the caller's existing model, without a second table allocation. +pub trait TableCell { + fn text(&self) -> &str; + fn bold(&self) -> bool { + false + } + fn italic(&self) -> bool { + false + } + fn span(&self) -> usize { + 1 + } +} + +/// `line` with its start escaped where Markdown would read a list item there (`- `, `+ `, +/// `1. `, `1) `); the other block markers (`#`, `>`) are escaped by [`md_text`] already. +fn block_start(line: String) -> String { + let digits = line.bytes().take_while(u8::is_ascii_digit).count(); + match line.as_bytes().get(digits) { + Some(b'.' | b')') if digits > 0 => format!("{}\\{}", line.get(..digits).unwrap_or_default(), line.get(digits..).unwrap_or_default()), + Some(b'-' | b'+') if digits == 0 => format!("\\{line}"), + _ => line, + } +} + +/// `text` (already escaped) in bold and/or italic, its outer spaces kept outside. `open` and +/// `close` say whether `*` markers would be read as emphasis on that side (see [`marks`]); +/// where they would not, as in `foo` + bold `.` + `bar`, the run is wrapped in HTML tags, which +/// CommonMark takes inline. The text's own outer spaces count as a side that marks. +pub fn emphasis(text: &str, bold: bool, italic: bool, open: bool, close: bool) -> String { + let core = text.trim(); + if core.is_empty() || !(bold || italic) { + return text.to_string(); + } + let lead = text.get(..text.len().saturating_sub(text.trim_start().len())).unwrap_or_default(); + let trail = text.get(text.trim_end().len()..).unwrap_or_default(); + let markers = (open || !lead.is_empty()) && (close || !trail.is_empty()); + let (before, after) = match (markers, bold, italic) { + (true, true, true) => ("***", "***"), + (true, true, false) => ("**", "**"), + (true, false, _) => ("*", "*"), + (false, true, true) => ("", ""), + (false, true, false) => ("", ""), + (false, false, _) => ("", ""), + }; + format!("{lead}{before}{core}{after}{trail}") +} + +/// A paragraph's runs (text, bold, italic) as one line of Markdown. Neighbouring runs in the +/// same style are joined first, so two bold runs never meet as `****`. +pub fn paragraph(runs: &[(&str, bool, bool)]) -> String { + let mut merged: Vec<(String, bool, bool)> = Vec::new(); + for &(text, bold, italic) in runs { + let text = md_text(text); + if text.is_empty() { + continue; + } + match merged.last_mut() { + Some(last) if last.1 == bold && last.2 == italic => last.0.push_str(&text), + _ => merged.push((text, bold, italic)), + } + } + let mut out = String::new(); + for (k, (text, bold, italic)) in merged.iter().enumerate() { + let core = text.trim(); + let open = marks(core.chars().next(), out.chars().last()); + // Markers of a styled neighbour right next to these would join them into one run. + let close = match merged.get(k.saturating_add(1)) { + Some((next, b, i)) if (*b || *i) && !next.starts_with(char::is_whitespace) => false, + next => marks(core.chars().last(), next.and_then(|(n, ..)| n.chars().next())), + }; + out.push_str(&emphasis(text, *bold, *italic, open, close)); + } + out +} + +/// Whether a `*` marker between the text's `edge` character and the `outside` one is read as +/// emphasis (CommonMark's flanking rules for `*`): always next to a space or the line's edge, +/// never next to another `*`, and otherwise unless the text's edge is punctuation while the +/// outside is a letter or digit. +fn marks(edge: Option, outside: Option) -> bool { + match (edge, outside) { + (_, None) => true, + (_, Some(o)) if o.is_whitespace() => true, + (_, Some('*')) => false, + (Some(e), Some(o)) => e.is_alphanumeric() || o.is_ascii_punctuation(), + (None, Some(_)) => false, + } +} + +fn cell(c: &impl TableCell) -> String { + emphasis(&md_text(c.text()), c.bold(), c.italic(), true, true) +} + +/// Incremental block writer. Input text is escaped; no caller-provided markup is trusted. +#[derive(Default)] +pub struct Writer { + blocks: Vec, +} + +impl Writer { + /// Create an empty extracted-text document. + pub fn new() -> Self { + Self::default() + } + + /// Append a paragraph or heading (levels above six are clamped). Heading weight comes + /// from its heading marker; callers may still supply italic runs. + pub fn paragraph(&mut self, runs: &[(&str, bool, bool)], level: u8) { + let text = paragraph(runs); + let text = text.trim(); + if text.is_empty() { + return; + } + self.blocks.push(match level { + 0 => block_start(text.to_string()), + l => format!("{} {text}", "#".repeat(usize::from(l.min(MAX_HEADING)))), + }); + } + + /// Append a pipe table with the first row as its header. Short rows are padded to the + /// widest row, and each span is clamped to 1..=MAX_SPAN. Callers bound input rows/cells. + pub fn table(&mut self, rows: &[Vec]) { + let span = |c: &C| c.span().clamp(1, MAX_SPAN); + let width = rows.iter().map(|r| r.iter().map(span).fold(0usize, usize::saturating_add)).max().unwrap_or(0); + if width == 0 { + return; + } + let mut lines = Vec::with_capacity(rows.len().saturating_add(1)); + for (i, row) in rows.iter().enumerate() { + let mut cells: Vec = Vec::with_capacity(width); + for c in row { + cells.push(cell(c)); + cells.extend(std::iter::repeat_n(String::new(), span(c).saturating_sub(1))); + } + cells.resize(width, String::new()); + lines.push(format!("| {} |", cells.join(" | "))); + if i == 0 { + lines.push(format!("|{}", " --- |".repeat(width))); + } + } + self.blocks.push(lines.join("\n")); + } + + /// Append a thematic break, including consecutive and leading page separators. + pub fn page_break(&mut self) { + self.blocks.push("---".into()); + } + + /// Join blocks with blank lines and finish with a newline (also for an empty document). + pub fn finish(self) -> String { + let mut out = self.blocks.join("\n\n"); + out.push('\n'); + out + } +} +#[cfg(test)] +mod tests { + use super::paragraph; + + #[test] + fn empty_or_control_run_does_not_split_styled_runs() { + assert_eq!(paragraph(&[("hello", true, false), ("", false, false), ("world", true, false)]), "**helloworld**"); + assert_eq!(paragraph(&[("hello", true, false), ("\u{1}", false, false), ("world", true, false)]), "**helloworld**"); + } + + #[test] + fn empty_styled_run_does_not_affect_neighbor_emphasis() { + assert_eq!(paragraph(&[("x", true, false), ("", false, true)]), "**x**"); + assert_eq!(paragraph(&[("foo", false, false), (".", true, false), ("", true, true), ("bar", false, false)]), "foo.bar"); + // Empty/control runs between differently styled runs still look ahead to the next non-empty run. + assert_eq!(paragraph(&[("bold", true, false), ("", false, false), ("italic", false, true)]), "bold*italic*"); + assert_eq!(paragraph(&[("bold", true, false), ("\u{1}", false, false), (" italic", false, true)]), "**bold** *italic*"); + // Leading empty/control runs do not affect the opening delimiter. + assert_eq!(paragraph(&[("", false, true), ("\u{1}", true, false), ("lead", true, false)]), "**lead**"); + // All-empty/control paragraphs produce empty output. + assert_eq!(paragraph(&[("", true, false), ("\u{1}", false, true), ("\u{7f}", false, false)]), ""); + } +} + +#[cfg(test)] +mod writer_tests { + use super::*; + + struct Cell(&'static str, usize); + impl TableCell for Cell { + fn text(&self) -> &str { + self.0 + } + fn span(&self) -> usize { + self.1 + } + } + + #[test] + fn preserves_block_spacing_heading_clamp_and_table_spans() { + let mut w = Writer::new(); + w.page_break(); + w.paragraph(&[("12. item\nnext", false, false)], 0); + w.paragraph(&[("Title", false, true)], 255); + w.table(&[vec![Cell("A|B", 2)], vec![Cell("C", 0)]]); + w.page_break(); + assert_eq!(w.finish(), "---\n\n12\\. item next\n\n###### *Title*\n\n| A\\|B | |\n| --- | --- |\n| C | |\n\n---\n"); + assert_eq!(Writer::new().finish(), "\n"); + } + + #[test] + fn control_filter_and_literal_punctuation_stay_explicit() { + assert_eq!(paragraph(&[("\0\u{7f}\u{fffe}\u{ffff}\n\r\t#!&", false, false)]), " \\#\\!\\&"); + // Ordinary export retains its existing newline/control policy and #/! behavior. + assert_eq!(crate::escaping::escape("\0\n#!\u{c}\u{e}&", false), "\0\n#!\\&"); + } +} diff --git a/crates/markdown/src/lib.rs b/crates/markdown/src/lib.rs index e7fc9abfc0..0bfd33ecce 100644 --- a/crates/markdown/src/lib.rs +++ b/crates/markdown/src/lib.rs @@ -25,7 +25,9 @@ use craft_wordmodel::{Align, Document}; use craft_flow::{self as model, Cell, FBlock, FTable, Fmt, Inline, Kind, ListInfo, Para, make_img}; mod blocks; +mod escaping; mod export; +pub mod extracted; mod inlines; pub use craft_flow::MAX_TABLE_CELLS; From de97c35f2b2af01c62371647e57a6affeab456fd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:30:28 -0500 Subject: [PATCH 12/15] craft-palette: share bounded GIMP palette reading from AniCraft (#1977) --- ATTRIBUTION.md | 4 ++ Cargo.lock | 4 ++ Cargo.toml | 1 + crates/palette/Cargo.toml | 11 +++++ crates/palette/src/lib.rs | 97 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 117 insertions(+) create mode 100644 crates/palette/Cargo.toml create mode 100644 crates/palette/src/lib.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 02935bac60..9d260300c7 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -110,3 +110,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## Non-seeking WAV primitives `crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. + +## GIMP palette reader + +`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index 74732b6d6b..1ac11475f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2592,6 +2592,10 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-palette" +version = "0.1.0" + [[package]] name = "craft-pcraft-bundle" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 72ae0083a2..2c0f4dfeaf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-palette = { path = "crates/palette" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/palette/Cargo.toml b/crates/palette/Cargo.toml new file mode 100644 index 0000000000..d39a80b677 --- /dev/null +++ b/crates/palette/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-palette" +description = "Bounded, application-independent GIMP palette reading" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/palette/src/lib.rs b/crates/palette/src/lib.rs new file mode 100644 index 0000000000..c49b0666d6 --- /dev/null +++ b/crates/palette/src/lib.rs @@ -0,0 +1,97 @@ +//! GIMP palette (.gpl) reading with neutral RGB8 colours and names. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Largest accepted palette, bounding all parsing allocations. +pub const MAX_BYTES: usize = 1 << 20; +/// Maximum colours returned; later rows are ignored. +pub const MAX_COLORS: usize = 1024; +/// A named RGB colour. Display-name sanitization belongs to the caller. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Color { + /// Whitespace-normalized colour label; "Untitled" remains literal. + pub name: String, + /// Red, green and blue channels. + pub rgb: [u8; 3], +} +/// A palette's title and colours, in file order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Palette { + /// Last Name header before the colour limit; leading value whitespace is retained. + pub name: String, + /// Valid colour rows in file order. + pub colors: Vec, +} +/// Reads GPL text, accepting BOM/CRLF, comments and metadata headers. +/// Malformed colour rows are skipped. Missing magic, empty palettes and oversized +/// input are errors. Columns and Channels headers are ignored for legacy compatibility. +pub fn parse_gpl(text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err("the palette file is too large".into()); + } + let mut lines = text.lines(); + let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim(); + if first != "GIMP Palette" { + return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into()); + } + let mut name = String::new(); + let mut out = Vec::new(); + for line in lines { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + if let Some(n) = l.strip_prefix("Name:") { + name = n.to_string(); + continue; + } + if l.starts_with("Columns:") || l.starts_with("Channels:") { + continue; + } + let mut parts = l.split_whitespace(); + let channel = |s: Option<&str>| s.and_then(|v| v.parse::().ok()).filter(|v| *v <= 255).map(|v| v as u8); + let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue }; + let rest: Vec<&str> = parts.collect(); + let label = rest.join(" "); + out.push(Color { name: label, rgb: [r, g, b] }); + if out.len() >= MAX_COLORS { + break; + } + } + if out.is_empty() { + return Err("the palette has no colours in it".into()); + } + Ok(Palette { name, colors: out }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn metadata_rgb_names_and_legacy_rows() { + let p = parse_gpl("\u{feff}GIMP Palette\r\nName: First\r\nName: Last\nColumns: 4\nChannels: RGB\n# comment\n255 0 128 Pink ink\n256 0 0 invalid\n-1 2 3 invalid\n1 2 3 Untitled\n4 5 6\n").unwrap(); + assert_eq!(p.name, " Last"); + assert_eq!( + p.colors, + vec![ + Color { name: "Pink ink".into(), rgb: [255, 0, 128] }, + Color { name: "Untitled".into(), rgb: [1, 2, 3] }, + Color { name: String::new(), rgb: [4, 5, 6] } + ] + ); + } + + #[test] + fn limits_and_empty_input() { + for text in ["", "not a palette", "GIMP Palette", "GIMP Palette\n256 0 0"] { + assert!(parse_gpl(text).is_err()); + } + assert!(parse_gpl(&"x".repeat(MAX_BYTES + 1)).is_err()); + let many = format!("GIMP Palette\n{}Name: ignored", "1 2 3 é\n".repeat(MAX_COLORS + 1)); + let p = parse_gpl(&many).unwrap(); + assert_eq!(p.colors.len(), MAX_COLORS); + assert!(p.name.is_empty()); + assert_eq!(p.colors[0].name, "é"); + } +} From af9985523a079c9e25c638003dbd9aa09fa4d254 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:37:02 -0500 Subject: [PATCH 13/15] svg: share bounded prefix-preserving kurbo path parsing (#1972) --- crates/svg/src/lib.rs | 2 + crates/svg/src/prefix_path.rs | 480 ++++++++++++++++++++++++++++++++++ 2 files changed, 482 insertions(+) create mode 100644 crates/svg/src/prefix_path.rs diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 286bd36d55..0c3c362a41 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -31,5 +31,7 @@ pub mod svgz; pub mod tree; pub mod write; +/// Prefix-preserving kurbo path compatibility for legacy SVG importers. +pub mod prefix_path; /// Compatibility CSS subset for simple SVG importers. pub mod simple_css; diff --git a/crates/svg/src/prefix_path.rs b/crates/svg/src/prefix_path.rs new file mode 100644 index 0000000000..0553d606d1 --- /dev/null +++ b/crates/svg/src/prefix_path.rs @@ -0,0 +1,480 @@ +//! SVG path data (SVG 1.1 §8.3 / SVG 2 §9.3): every command, implicit repeats, relative +//! coordinates, smooth curves and elliptical arcs (converted to cubics through kurbo's `SvgArc`). +//! Parsing stops at the first error, keeping what was read (as the specification asks). +//! +//! Compatibility API for importers requiring kurbo quadratics and cubic arc expansion, +//! distinct from the strict neutral [`crate::path_data::parse_path`] API. Retains EffectCraft's +//! malformed-prefix, close-path, finite-coordinate, radius-scaled tolerance and endpoint rules. +//! Source: EffectCraft `pathdata.rs` at `05fc7f28352361f8f183da900ac5f4dfc9b69799`. +//! Brandon Thomas authored the parser and post-Z termination fix; NetterSilver the arc +//! tolerance/endpoint fixes; FredApps the finite-coordinate and element-budget safeguards. + +use kurbo::{BezPath, PathEl, Point, SvgArc, Vec2}; + +/// Maximum path elements retained from one SVG path or point list. +pub const MAX_PATH_ELEMENTS: usize = 100_000; + +/// Tokenizer over numbers and command letters. +struct Lex<'a> { + b: &'a [u8], + i: usize, +} + +impl Lex<'_> { + fn skip_sep(&mut self) { + while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == b',') { + self.i += 1; + } + } + fn command(&mut self) -> Option { + self.skip_sep(); + let c = *self.b.get(self.i)?; + if c.is_ascii_alphabetic() && c != b'e' && c != b'E' { + self.i += 1; + Some(c) + } else { + None + } + } + fn at_number(&mut self) -> bool { + self.skip_sep(); + self.b.get(self.i).is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.')) + } + fn number(&mut self) -> Option { + self.skip_sep(); + let start = self.i; + let b = self.b; + let mut i = self.i; + if i < b.len() && matches!(b[i], b'-' | b'+') { + i += 1; + } + let mut digits = false; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + digits = true; + } + if i < b.len() && b[i] == b'.' { + i += 1; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + digits = true; + } + } + if !digits { + return None; + } + if i < b.len() && matches!(b[i], b'e' | b'E') { + let mut j = i + 1; + if j < b.len() && matches!(b[j], b'-' | b'+') { + j += 1; + } + if j < b.len() && b[j].is_ascii_digit() { + while j < b.len() && b[j].is_ascii_digit() { + j += 1; + } + i = j; + } + } + self.i = i; + let number = std::str::from_utf8(&b[start..i]).ok()?.parse::().ok()?; + number.is_finite().then_some(number) + } + /// Arc flags may be written without separators ("a1 1 0 00 1 1"). + fn flag(&mut self) -> Option { + self.skip_sep(); + let c = *self.b.get(self.i)?; + self.i += 1; + match c { + b'0' => Some(false), + b'1' => Some(true), + _ => None, + } + } +} + +/// Maximum values retained from a points list (two coordinates per path element). +pub const MAX_NUMBER_VALUES: usize = MAX_PATH_ELEMENTS * 2; + +/// Parse a finite numeric prefix, retaining at most `min(max_values, MAX_NUMBER_VALUES)`. +/// The flag reports a possible next number after the cap, not a malformed suffix. +/// The caller must decide whether to refuse the document when the flag is set. +pub fn numbers_bounded(s: &str, max_values: usize) -> (Vec, bool) { + let max_values = max_values.min(MAX_NUMBER_VALUES); + let mut l = Lex { b: s.as_bytes(), i: 0 }; + let mut v = vec![]; + while l.at_number() { + if v.len() >= max_values { + return (v, true); + } + match l.number() { + Some(x) => v.push(x), + None => break, + } + } + (v, false) +} + +/// Parse path data into a kurbo path, retaining at most [`MAX_PATH_ELEMENTS`] elements. +/// Malformed or overlong input returns the prefix parsed before the problem. +pub fn parse_path_data(d: &str) -> BezPath { + parse_path_data_bounded(d, MAX_PATH_ELEMENTS).0 +} + +/// Pen position and reflection state while parsing path commands. +struct PathState { + /// Current point. + current: Point, + /// Start of the current subpath. + start: Point, + /// Last cubic control point, for smooth curves. + last_cubic: Option, + /// Last quadratic control point, for smooth curves. + last_quad: Option, + /// Whether a subpath is open. + open: bool, +} + +/// Cap on path elements and whether it has been hit. +struct PathLimit { + /// Maximum number of path elements. + max_elements: usize, + /// Set when the cap or a non-finite coordinate stopped output. + exceeded: bool, +} + +/// Parse at most `min(max_elements, MAX_PATH_ELEMENTS)` kurbo elements. +/// The flag reports a reached cap with trailing input or a non-finite output coordinate. +/// Malformed syntax alone returns the valid prefix without setting the flag. Importers +/// should refuse the document on a true flag; [`parse_path_data`] intentionally keeps only +/// the bounded prefix. Move/close commands and expanded arc cubics count toward the cap. +pub fn parse_path_data_bounded(d: &str, max_elements: usize) -> (BezPath, bool) { + let max_elements = max_elements.min(MAX_PATH_ELEMENTS); + let mut l = Lex { b: d.as_bytes(), i: 0 }; + let mut p = BezPath::new(); + let mut state = PathState { current: Point::ZERO, start: Point::ZERO, last_cubic: None, last_quad: None, open: false }; + let mut limit = PathLimit { max_elements, exceeded: false }; + let mut cmd: Option = None; + loop { + if p.elements().len() >= limit.max_elements { + l.skip_sep(); + limit.exceeded = l.i < l.b.len(); + break; + } + let c = match l.command() { + Some(c) => c, + None => match cmd { + // Implicit repeat (a moveto repeats as lineto). Z takes no numbers, so a number + // after it is an error: repeating Z would loop forever without consuming input. + Some(c) if l.at_number() && !c.eq_ignore_ascii_case(&b'z') => match c { + b'M' => b'L', + b'm' => b'l', + other => other, + }, + _ => break, + }, + }; + let rel = c.is_ascii_lowercase(); + let base = if rel { state.current.to_vec2() } else { Vec2::ZERO }; + let pt = |l: &mut Lex| -> Option { Some(Point::new(l.number()?, l.number()?) + base) }; + let ok = (|| -> Option<()> { + match c.to_ascii_uppercase() { + b'M' => { + state.current = pt(&mut l)?; + if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) { + return None; + } + state.start = state.current; + state.open = true; + state.last_cubic = None; + state.last_quad = None; + } + b'Z' => { + if state.open && !push_element(&mut p, PathEl::ClosePath, &mut limit) { + return None; + } + state.current = state.start; + state.last_cubic = None; + state.last_quad = None; + } + _ if !state.open => { + // A segment without a preceding moveto starts at the current point. + if !push_element(&mut p, PathEl::MoveTo(state.current), &mut limit) { + return None; + } + state.open = true; + return segment(&mut l, c, base, &mut p, &mut state, &mut limit); + } + _ => return segment(&mut l, c, base, &mut p, &mut state, &mut limit), + } + Some(()) + })(); + if ok.is_none() { + break; + } + if limit.exceeded { + break; + } + cmd = Some(c); + if c.eq_ignore_ascii_case(&b'z') { + // After Z a new segment starts from the subpath start (an unused move is dropped + // below). + if !push_element(&mut p, PathEl::MoveTo(state.start), &mut limit) { + break; + } + state.open = true; + } + } + (strip_trailing_moves(p), limit.exceeded) +} + +/// Push an element if finite and under the cap; otherwise mark the limit exceeded and return false. +fn push_element(p: &mut BezPath, element: PathEl, limit: &mut PathLimit) -> bool { + let finite = match element { + PathEl::MoveTo(point) | PathEl::LineTo(point) => point.x.is_finite() && point.y.is_finite(), + PathEl::QuadTo(control, point) => [control.x, control.y, point.x, point.y].iter().all(|value| value.is_finite()), + PathEl::CurveTo(first, second, point) => [first.x, first.y, second.x, second.y, point.x, point.y].iter().all(|value| value.is_finite()), + PathEl::ClosePath => true, + }; + if p.elements().len() >= limit.max_elements || !finite { + limit.exceeded = true; + return false; + } + p.push(element); + true +} + +/// Parse one path command's arguments into `p`, returning `None` on malformed or over-limit input. +fn segment(l: &mut Lex, c: u8, base: Vec2, p: &mut BezPath, state: &mut PathState, limit: &mut PathLimit) -> Option<()> { + let num = |l: &mut Lex| l.number(); + let pt = |l: &mut Lex| -> Option { Some(Point::new(l.number()?, l.number()?) + base) }; + match c.to_ascii_uppercase() { + b'L' => { + let current = pt(l)?; + if !push_element(p, PathEl::LineTo(current), limit) { + return None; + } + state.current = current; + state.last_cubic = None; + state.last_quad = None; + } + b'H' => { + let x = num(l)? + base.x; + let current = Point::new(x, state.current.y); + if !push_element(p, PathEl::LineTo(current), limit) { + return None; + } + state.current = current; + state.last_cubic = None; + state.last_quad = None; + } + b'V' => { + let y = num(l)? + base.y; + let current = Point::new(state.current.x, y); + if !push_element(p, PathEl::LineTo(current), limit) { + return None; + } + state.current = current; + state.last_cubic = None; + state.last_quad = None; + } + b'C' => { + let (c1, c2, e) = (pt(l)?, pt(l)?, pt(l)?); + if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) { + return None; + } + state.last_cubic = Some(c2); + state.last_quad = None; + state.current = e; + } + b'S' => { + let c1 = state.last_cubic.map_or(state.current, |c| state.current + (state.current - c)); + let (c2, e) = (pt(l)?, pt(l)?); + if !push_element(p, PathEl::CurveTo(c1, c2, e), limit) { + return None; + } + state.last_cubic = Some(c2); + state.last_quad = None; + state.current = e; + } + b'Q' => { + let (q, e) = (pt(l)?, pt(l)?); + if !push_element(p, PathEl::QuadTo(q, e), limit) { + return None; + } + state.last_quad = Some(q); + state.last_cubic = None; + state.current = e; + } + b'T' => { + let q = state.last_quad.map_or(state.current, |c| state.current + (state.current - c)); + let e = pt(l)?; + if !push_element(p, PathEl::QuadTo(q, e), limit) { + return None; + } + state.last_quad = Some(q); + state.last_cubic = None; + state.current = e; + } + b'A' => { + let rx = num(l)?.abs(); + let ry = num(l)?.abs(); + let rot = num(l)?; + let large = l.flag()?; + let sweep = l.flag()?; + let e = pt(l)?; + let arc = SvgArc { from: state.current, to: e, radii: Vec2::new(rx, ry), x_rotation: rot.to_radians(), large_arc: large, sweep }; + let mut last_end = None; + if let Some(a) = kurbo::Arc::from_svg_arc(&arc) { + // Scale tolerance with the radius so the segment count stays bounded. + let tol = 0.1_f64.max(a.radii.x.max(a.radii.y) * 1e-4); + a.to_cubic_beziers(tol, |c1, c2, end| { + if limit.exceeded { + return; + } + if push_element(p, PathEl::CurveTo(c1, c2, end), limit) { + last_end = Some(end); + } + }); + } + if limit.exceeded { + return None; + } + // Degenerate arcs (e.g. huge radii) may emit nothing or stop short of the end point. + if last_end.is_none_or(|q| (q - e).hypot() > 1e-3 * (1.0 + e.to_vec2().hypot())) && !push_element(p, PathEl::LineTo(e), limit) { + return None; + } + state.current = e; + state.last_cubic = None; + state.last_quad = None; + } + _ => return None, + } + Some(()) +} + +/// Drop move-tos that start no segment (from closepath bookkeeping). +fn strip_trailing_moves(p: BezPath) -> BezPath { + use kurbo::PathEl; + let els = p.elements(); + let mut out = BezPath::new(); + for (i, e) in els.iter().enumerate() { + if let PathEl::MoveTo(_) = e { + let next_is_seg = els.get(i + 1).is_some_and(|n| !matches!(n, PathEl::MoveTo(_))); + if !next_is_seg { + continue; + } + } + out.push(*e); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::PathEl; + + #[test] + /// Huge arc radii stay bounded. + fn huge_arc_radius_stays_bounded() { + let p = parse_path_data("M0 0A1e36 1e36 0 1 1 1e30 0"); + assert!(p.elements().len() < 1000, "got {} elements", p.elements().len()); + } + + #[test] + fn commands() { + let p = parse_path_data("M10,10 L20,10 h10 v10 H10 z m5 5 l1-1.5.5.5e1 C 0 0 1 1 2 2 s3 3 4 4 Q1 1 2 2 t3 3 A5 5 0 0 1 20 20 a5 5 0 1010 0"); + let els = p.elements(); + assert_eq!(els[0], PathEl::MoveTo(Point::new(10.0, 10.0))); + assert_eq!(els[2], PathEl::LineTo(Point::new(30.0, 10.0))); + assert_eq!(els[3], PathEl::LineTo(Point::new(30.0, 20.0))); + assert!(els.iter().any(|e| matches!(e, PathEl::ClosePath))); + // Relative move after Z is relative to the subpath start (10,10). + assert!(els.contains(&PathEl::MoveTo(Point::new(15.0, 15.0)))); + // "l1-1.5.5.5e1": two implicit linetos (1,-1.5) then (.5,5). + assert!(els.contains(&PathEl::LineTo(Point::new(16.0, 13.5)))); + assert!(els.contains(&PathEl::LineTo(Point::new(16.5, 18.5)))); + assert!(els.iter().filter(|e| matches!(e, PathEl::CurveTo(..))).count() >= 4); + } + + #[test] + fn errors_keep_prefix() { + let p = parse_path_data("M0 0 L10 0 L10 x10 L0 10"); + assert_eq!(p.elements().len(), 2); + assert!(parse_path_data("garbage").elements().is_empty()); + assert!(parse_path_data("").elements().is_empty()); + } + + #[test] + fn number_after_close_stops_instead_of_looping() { + // "Z9": Z was repeated implicitly without consuming the number, appending close-paths + // until memory ran out. + let p = parse_path_data("M0 0 L10 0 L10 10 Z9 C1 2 3 4 5 6"); + assert_eq!(p.elements().len(), 4); + assert!(parse_path_data("M0 0 L10 0 z 9 9").elements().len() <= 4); + } + + #[test] + /// Huge-radius arcs still reach their end point. + fn huge_radius_arc_still_reaches_end_point() { + for d in ["M0 0 A1e20 1e20 0 0 1 10 0 L10 10", "M0 0 A1e20 1e20 0 1 1 10 0 L10 10", "M0 0 a1e20 1e20 0 0 1 10 0 L10 10"] { + let p = parse_path_data(d); + let reaches = p.elements().iter().any(|e| match e { + PathEl::LineTo(q) | PathEl::CurveTo(_, _, q) => (q.x - 10.0).abs() < 1e-6 && q.y.abs() < 1e-6, + _ => false, + }); + assert!(reaches, "{d}: {:?}", p.elements()); + } + } + + #[test] + fn number_lists() { + assert_eq!(numbers_bounded("0 0,100 50", 8).0, vec![0.0, 0.0, 100.0, 50.0]); + assert_eq!(numbers_bounded("-1-2.5.5", 8).0, vec![-1.0, -2.5, 0.5]); + assert_eq!(numbers_bounded("1e2,2E-1", 8).0, vec![100.0, 0.2]); + } + + #[test] + /// The element cap stops expansion and reports truncation. + fn path_element_limit_stops_expansion_and_reports_truncation() { + let data = format!("M0 0{}", "h1".repeat(MAX_PATH_ELEMENTS + 1)); + let (path, exceeded) = parse_path_data_bounded(&data, 32); + assert!(exceeded); + assert!(path.elements().len() <= 32); + } + + #[test] + /// The number list cap stops retaining values. + fn number_list_limit_stops_retaining_values() { + let (values, exceeded) = numbers_bounded("1 2 3 4", 3); + assert_eq!(values, [1.0, 2.0, 3.0]); + assert!(exceeded); + } +} + +#[cfg(test)] +mod shared_boundary_tests { + use super::*; + + #[test] + fn huge_caller_budgets_remain_bounded() { + let (path, limited) = parse_path_data_bounded(&format!("M0 0{}", "h1".repeat(MAX_PATH_ELEMENTS)), usize::MAX); + assert!(limited); + assert!(path.elements().len() <= MAX_PATH_ELEMENTS); + let (values, limited) = numbers_bounded(&"1 ".repeat(MAX_NUMBER_VALUES + 1), usize::MAX); + assert!(limited); + assert_eq!(values.len(), MAX_NUMBER_VALUES); + } + + #[test] + fn prefix_and_non_finite_flags_stay_distinct() { + let (path, limited) = parse_path_data_bounded("M0 0 L1 1 Lx", 20); + assert!(!limited); + assert_eq!(path.elements().len(), 2); + let (path, limited) = parse_path_data_bounded("M1e308 0 l1e308 0", 20); + assert!(limited); + assert!(path.elements().is_empty()); + assert!(parse_path_data_bounded("M0 0", 0).1); + assert!(!parse_path_data_bounded("", 0).1); + } +} From 064afccce82b01cbf85da5e265bcf897553bea2a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:01:56 -0500 Subject: [PATCH 14/15] craft-penpot: incremental container writer for bounded serialization (#1985) --- crates/penpot/src/lib.rs | 41 +++++++++++++++++++++++++++++++------- crates/penpot/src/tests.rs | 20 +++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/penpot/src/lib.rs b/crates/penpot/src/lib.rs index aafc555c33..eda3bdf857 100644 --- a/crates/penpot/src/lib.rs +++ b/crates/penpot/src/lib.rs @@ -382,16 +382,43 @@ pub fn manifest(generated_by: &str, files: &[(&str, &str, Value)]) -> Value { serde_json::json!({"type": MANIFEST_TYPE, "version": 1, "generatedBy": generated_by, "refer": "penpot", "files": files, "relations": []}) } +/// Incremental in-memory Penpot container writer. Members are compressed as they are added; +/// the writer retains their names and archive output, not a second collection of payloads. +/// Paths must be safe and distinct. Entries keep insertion order and use deflate level 3. +/// If [`Writer::add`] fails, discard the writer: additions are not transactional, and a ZIP +/// failure may leave a reserved member name or partially written output. Do not finish or reuse +/// a writer after an error. +#[derive(Default)] +pub struct Writer { + zip: craft_zip::Writer, + seen: BTreeSet, +} + +impl Writer { + pub fn new() -> Self { + Self::default() + } + + /// Write one member immediately; the caller may release its serialized payload afterwards. + /// On any error, discard this writer rather than retrying or calling [`Writer::finish`]. + pub fn add(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> { + if path.is_empty() || !safe_name(path) || !self.seen.insert(path.to_owned()) { + return Err(Error::Io(format!("unsafe or repeated member path: {}", path.chars().take(200).collect::()))); + } + self.zip.add(path, bytes, craft_zip::Compression::Level(3)).map_err(|e| Error::Io(e.to_string())) + } + + pub fn finish(self) -> Result, Error> { + self.zip.finish().map_err(|e| Error::Io(e.to_string())) + } +} + /// A Penpot archive of `members` (path, bytes), deflated, in the order given. Paths must be safe /// and distinct, as [`Archive::open`] requires of what it reads. pub fn write_archive<'a>(members: impl IntoIterator) -> Result, Error> { - let mut z = craft_zip::Writer::new(); - let mut seen = BTreeSet::new(); + let mut writer = Writer::new(); for (path, bytes) in members { - if path.is_empty() || !safe_name(path) || !seen.insert(path) { - return Err(Error::Io(format!("unsafe or repeated member path: {}", path.chars().take(200).collect::()))); - } - z.add(path, bytes, craft_zip::Compression::Level(3)).map_err(|e| Error::Io(e.to_string()))?; + writer.add(path, bytes)?; } - z.finish().map_err(|e| Error::Io(e.to_string())) + writer.finish() } diff --git a/crates/penpot/src/tests.rs b/crates/penpot/src/tests.rs index c5f14ef720..2644157ff9 100644 --- a/crates/penpot/src/tests.rs +++ b/crates/penpot/src/tests.rs @@ -438,3 +438,23 @@ fn an_archive_declaring_too_many_members_is_refused_before_it_is_indexed() { let bomb = craft_zip::zip64_entry_count_sample(MAX_ENTRIES as u64 + 1); assert_eq!(Archive::open(&bomb).err(), Some(Error::Corrupt("too many ZIP members".into()))); } + +#[test] +fn incremental_writer_keeps_members_and_rejects_ambiguous_paths() { + let all = members(); + let mut writer = Writer::new(); + for (name, bytes) in &all { + writer.add(name, bytes).unwrap(); + } + let output = writer.finish().unwrap(); + assert_eq!(output, write_archive(all.iter().map(|(n, b)| (n.as_str(), b.as_slice()))).unwrap()); + let mut archive = Archive::open(&output).unwrap(); + assert_eq!(archive.names().first().map(String::as_str), Some("manifest.json")); + assert_eq!(archive.page_shapes(FILE, PAGE).unwrap().len(), 2); + for bad in ["../x", "/abs", "a/./b", "a\\b", "", "a\u{1}b"] { + assert!(Writer::new().add(bad, b"x").is_err()); + } + let mut duplicate = Writer::new(); + duplicate.add("a", b"first").unwrap(); + assert!(duplicate.add("a", b"second").is_err()); +} From 453b0da782ccef39be9a6dac8d27c80b553ef1cc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:06:56 -0500 Subject: [PATCH 15/15] Restore XLSB fixtures and Unix atomic-report test compilation (#1994) * xtask: delegate Unix group restoration in report test filesystem * craft-xlsx: xlsb tests unwrap the zip fixture's Result #1386 made the test zip writer return Result, Error>. The xlsb tests from #1263, #1323, #1330 and #1337 merged alongside it and still used the return value as bytes, so `cargo check --workspace --tests` failed on main with seven E0308 errors in crates/xlsx/tests/xlsb.rs. These call sites now unwrap the result, as #1386 did for the others. --------- Co-authored-by: dotCooCoo --- crates/xlsx/tests/xlsb.rs | 14 +++++++++----- crates/xtask/src/report.rs | 4 ++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index 3611cafbb4..ef1464dd4b 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1010,7 +1010,7 @@ const NAMES_XML: &str = r#""#; let root = r#""#; - let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", xml.as_bytes())]); + let bytes = zip(&[("[Content_Types].xml", types.as_bytes()), ("_rels/.rels", root.as_bytes()), ("xl/workbook.xml", xml.as_bytes())]).unwrap(); Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names } @@ -1146,7 +1146,8 @@ fn xml_sheet(xml: &str) -> (Vec, SheetPart) { ("xl/workbook.xml", book.as_bytes()), ("xl/_rels/workbook.xml.rels", rels.as_bytes()), ("xl/sheet.xml", xml.as_bytes()), - ]); + ]) + .unwrap(); let (rows, part, _) = sizes_of(&bytes).unwrap(); (rows, part) } @@ -1256,6 +1257,7 @@ fn styled_file(styles: &[u8], types: &str) -> Vec { ("data/two.bin", &worksheet(&[], &[])), ("look/styles.bin", styles), ]) + .unwrap() } /// The styles part of a package, and the warnings reading it gave. @@ -1440,7 +1442,8 @@ fn xml_styles(xml: &str) -> Styles { ("xl/workbook.xml", br#""#), ("xl/_rels/workbook.xml.rels", rels.as_bytes()), ("xl/styles.xml", xml.as_bytes()), - ]); + ]) + .unwrap(); styles_of(&bytes).0.unwrap() } @@ -1793,7 +1796,7 @@ fn book_with_tables(data: &[u8], tables: &[Vec]) -> Vec { ("text/strings.bin", &strings), ]; entries.extend(names.iter().map(String::as_str).zip(tables.iter().map(Vec::as_slice))); - zip(&entries) + zip(&entries).unwrap() } /// Sheet one's tables through `Package`, and its warnings. @@ -1834,7 +1837,8 @@ fn a_name_using_a_structured_reference_is_decoded_after_tables_are_indexed() { ("data/two.bin", two.as_slice()), ("text/strings.bin", strings.as_slice()), ("tables/t1.bin", table.as_slice()), - ]); + ]) + .unwrap(); let names = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names; assert_eq!(names.iter().find(|n| n.name == "Vals").map(|n| n.formula.as_str()), Some("Sales[Val]")); let wb = read(&bytes).unwrap(); diff --git a/crates/xtask/src/report.rs b/crates/xtask/src/report.rs index f876d06f99..3c021cb97a 100644 --- a/crates/xtask/src/report.rs +++ b/crates/xtask/src/report.rs @@ -90,6 +90,10 @@ mod tests { fn set_permissions(&self, file: &File, perms: Permissions) -> io::Result<()> { RealFs.set_permissions(file, perms) } + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + RealFs.set_group(file, gid) + } } fn keys(v: &Value) -> Vec<&str> {