From 5f453efa9ad7e803f65c3edc7e08992d43422c23 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Sun, 15 Nov 2026 20:10:47 +0100 Subject: [PATCH 01/33] 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 cb1152da8..ea48efcca 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 1d9eb0818..634f5f833 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 4cb847276..00826f4b5 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 7c03cca6e..2c13e1e7d 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 868e8cbb0..9c5fc1e56 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 8f3bbdd0b..16f61be6b 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 0a1cc43bd..5b0d1ae1a 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 315e0e042..b13db3533 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/33] 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 cb8766906..86e11b73c 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 97520027c..c64306eeb 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 f8ac5fe99..ab0c0bf26 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 2ad475739..220f5afab 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 1cc3e3e25..9c6c2a504 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 d49a07ea8..6a5f08feb 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/33] 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 86e11b73c..44a31357a 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 ab0c0bf26..0fff3797a 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/33] 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 634f5f833..0391ba615 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 00826f4b5..fa6d6b693 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 4b0ae856a..3a42a8b04 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 9b209082b..6d3deddb1 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/33] 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 810e67d55..791bb60ce 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 f1c281c62..d5abb7537 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 f07595676..1b2793258 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 28cb8cb12..eeb466f59 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 44a31357a..6e1e22c6f 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 c64306eeb..f7a9d164d 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 0fff3797a..00f18408a 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 220f5afab..dc4282945 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 9c6c2a504..76d9e56e8 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 6a5f08feb..115dd9b02 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/33] 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 53202850a..ae896dcf5 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 0f95b4f76..c00b847f3 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 ea48efcca..811225f4a 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 d15f59289..08dc4befd 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 1b2793258..b5a2b3968 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 6e1e22c6f..457cfbdff 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 486e67a26..930cf0b42 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 6a67da3af..10eb7df7c 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 00f18408a..b5a55e9f7 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 bbfeb9cbc..b6e407cd1 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 000000000..9cb543d83 --- /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/33] 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 b5a2b3968..1b2793258 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 457cfbdff..2a2beee2f 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 f7a9d164d..62d27940a 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 10eb7df7c..6a67da3af 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 b5a55e9f7..d78c7a4a9 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 d96ee4917..706056270 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 12db39ca963d2a333bd1891b0dbba65218800fd8 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 08/33] Extract score writer changes from SoundCraft 0751dd31 --- crates/score/src/lib.rs | 344 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 344 insertions(+) create mode 100644 crates/score/src/lib.rs diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs new file mode 100644 index 000000000..30375b652 --- /dev/null +++ b/crates/score/src/lib.rs @@ -0,0 +1,344 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! MusicXML and SVG score writing over application-independent notation data. + +use std::fmt::Write as _; + +#[derive(Debug, Clone, PartialEq)] +pub struct ScoreSetup { + pub title: String, + pub composer: String, + pub bars_per_system: u32, + pub show_track_names: bool, +} + +/// One measure: its meter and its items (notes, chords or rests), in sixteenths. +#[derive(Debug, Clone, PartialEq)] +pub struct Measure { + pub numerator: u32, + pub denominator: u32, + pub items: Vec, +} + +/// A notehead group (chord) or a rest (no pitches). +#[derive(Debug, Clone, PartialEq)] +pub struct Item { + pub pitches: Vec, + /// Duration in sixteenths; always one of the supported duration values. + pub units: u32, + pub tie_start: bool, + pub tie_stop: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Part { + pub name: String, + /// True when the part reads best in bass clef. + pub bass: bool, + pub measures: Vec, +} + +fn spell(pitch: u8) -> (char, i32, i32) { + const STEPS: [(char, i32); 12] = + [('C', 0), ('C', 1), ('D', 0), ('D', 1), ('E', 0), ('F', 0), ('F', 1), ('G', 0), ('G', 1), ('A', 0), ('A', 1), ('B', 0)]; + let (step, alter) = STEPS[usize::from(pitch % 12)]; + (step, alter, i32::from(pitch / 12) - 1) +} + +fn xml_escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +fn note_type(units: u32) -> (&'static str, bool) { + match units { + 16 => ("whole", false), + 12 => ("half", true), + 8 => ("half", false), + 6 => ("quarter", true), + 4 => ("quarter", false), + 3 => ("eighth", true), + 2 => ("eighth", false), + _ => ("16th", false), + } +} + +/// MusicXML 4.0 (partwise) for `parts`. +pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> String { + let mut x = String::new(); + x.push_str("\n"); + x.push_str("\n"); + x.push_str("\n"); + let _ = writeln!(x, " {}", xml_escape(&setup.title)); + x.push_str(" \n"); + if !setup.composer.is_empty() { + let _ = writeln!(x, " {}", xml_escape(&setup.composer)); + } + x.push_str(" SoundCraft\n \n \n"); + for (i, p) in parts.iter().enumerate() { + let _ = writeln!(x, " {}", i + 1, xml_escape(&p.name)); + } + x.push_str(" \n"); + for (i, p) in parts.iter().enumerate() { + let _ = writeln!(x, " ", i + 1); + let mut meter = (0, 0); + for (mi, m) in p.measures.iter().enumerate() { + let _ = writeln!(x, " ", mi + 1); + if mi == 0 || meter != (m.numerator, m.denominator) { + x.push_str(" "); + if mi == 0 { + x.push_str("40"); + } + let _ = write!(x, "", m.numerator, m.denominator); + if mi == 0 { + x.push_str(if p.bass { "F4" } else { "G2" }); + } + x.push_str("\n"); + meter = (m.numerator, m.denominator); + } + for it in &m.items { + let (ty, dot) = note_type(it.units); + if it.pitches.is_empty() { + let _ = writeln!( + x, + " {}1{ty}{}", + it.units, + if dot { "" } else { "" } + ); + continue; + } + for (k, pitch) in it.pitches.iter().enumerate() { + let (step, alter, octave) = spell(*pitch); + x.push_str(" "); + if k > 0 { + x.push_str(""); + } + let _ = write!(x, "{step}"); + if alter != 0 { + let _ = write!(x, "{alter}"); + } + let _ = write!(x, "{octave}{}", it.units); + if it.tie_stop { + x.push_str(""); + } + if it.tie_start { + x.push_str(""); + } + let _ = write!(x, "1{ty}"); + if dot { + x.push_str(""); + } + if alter != 0 { + x.push_str("sharp"); + } + if it.tie_stop || it.tie_start { + x.push_str(""); + if it.tie_stop { + x.push_str(""); + } + if it.tie_start { + x.push_str(""); + } + x.push_str(""); + } + x.push_str("\n"); + } + } + x.push_str(" \n"); + } + x.push_str(" \n"); + } + x.push_str("\n"); + x +} + +/// Staff position of `pitch` in half-spaces above the bottom line (treble E4 / bass G2). +fn staff_step(pitch: u8, bass: bool) -> i32 { + let (step, _, octave) = spell(pitch); + let idx = "CDEFGAB".find(step).map_or(0, |i| i as i32); + let diatonic = octave * 7 + idx; + diatonic - if bass { 2 * 7 + 4 } else { 4 * 7 + 2 } +} + +/// An engraved score as a printable SVG page (A4 portrait width, as tall as needed). +pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { + const W: f64 = 794.0; + const MARGIN: f64 = 48.0; + const SP: f64 = 7.0; // staff space + const STAFF_GAP: f64 = 70.0; + const SYSTEM_GAP: f64 = 40.0; + let n_measures = parts.iter().map(|p| p.measures.len()).max().unwrap_or(0); + let per = setup.bars_per_system.max(1) as usize; + let systems = n_measures.div_ceil(per).max(1); + let label_w = if setup.show_track_names { 70.0 } else { 0.0 }; + let staff_x0 = MARGIN + label_w + 34.0; + let staff_x1 = W - MARGIN; + let sys_h = parts.len().max(1) as f64 * STAFF_GAP + SYSTEM_GAP; + let top = 110.0; + let h = top + systems as f64 * sys_h + MARGIN; + let mut o = String::new(); + let _ = + writeln!(o, ""); + let _ = writeln!(o, ""); + let _ = writeln!(o, "{}", W / 2.0, xml_escape(&setup.title)); + if !setup.composer.is_empty() { + let _ = writeln!(o, "{}", W - MARGIN, xml_escape(&setup.composer)); + } + let bar_w = (staff_x1 - staff_x0) / per as f64; + for sys in 0..systems { + let y_sys = top + sys as f64 * sys_h; + for (pi, p) in parts.iter().enumerate() { + let y0 = y_sys + pi as f64 * STAFF_GAP; // top line + let bottom = y0 + 4.0 * SP; + if setup.show_track_names && sys == 0 { + let _ = writeln!(o, "{}", y0 + 2.0 * SP + 4.0, xml_escape(&p.name)); + } + for l in 0..5 { + let y = y0 + f64::from(l) * SP; + let _ = writeln!( + o, + "", + staff_x0 - 30.0 + ); + } + let clef = if p.bass { "𝄢" } else { "𝄞" }; + let _ = writeln!( + o, + "{clef}", + staff_x0 - 29.0, + bottom + if p.bass { -SP } else { SP * 0.6 }, + if p.bass { 26 } else { 36 } + ); + for k in 0..per { + let mi = sys * per + k; + let x0 = staff_x0 + k as f64 * bar_w; + let _ = writeln!( + o, + "", + x0 + bar_w, + x0 + bar_w + ); + let Some(m) = p.measures.get(mi) else { continue }; + if pi == 0 { + let _ = writeln!(o, "{}", x0 + 2.0, y0 - 8.0, mi + 1); + } + let total: u32 = m.items.iter().map(|i| i.units).sum::().max(1); + let mut acc = 0u32; + for it in &m.items { + let x = x0 + 10.0 + (bar_w - 16.0) * f64::from(acc) / f64::from(total); + acc += it.units; + let (_, dot) = note_type(it.units); + if it.pitches.is_empty() { + rest(&mut o, x, y0, SP, it.units); + if dot { + let _ = writeln!(o, "", x + 7.0, y0 + 1.5 * SP); + } + continue; + } + let steps: Vec = it.pitches.iter().map(|p2| staff_step(*p2, p.bass)).collect(); + let filled = it.units < 8; + for (pitch, st) in it.pitches.iter().zip(&steps) { + let y = bottom - f64::from(*st) * SP / 2.0; + // Ledger lines. + let mut l = if *st < 0 { -2 } else { 10 }; + while (*st < 0 && l >= *st) || (*st > 8 && l <= *st) { + let ly = bottom - f64::from(l) * SP / 2.0; + let _ = writeln!( + o, + "", + x - 7.0, + x + 7.0 + ); + l += if *st < 0 { -2 } else { 2 }; + } + let fill = if filled { "black" } else { "white" }; + let _ = writeln!( + o, + "" + ); + if spell(*pitch).1 != 0 { + let _ = writeln!(o, "♯", x - 14.0, y + 4.0); + } + if dot { + let _ = writeln!(o, "", x + 8.0, y - 1.5); + } + } + if it.units < 16 { + let (lo, hi) = (steps.iter().copied().min().unwrap_or(4), steps.iter().copied().max().unwrap_or(4)); + let up = (lo + hi) < 8; + let (sx, y_from, y_to) = if up { + (x + 4.3, bottom - f64::from(lo) * SP / 2.0, bottom - f64::from(hi) * SP / 2.0 - 3.5 * SP) + } else { + (x - 4.3, bottom - f64::from(hi) * SP / 2.0, bottom - f64::from(lo) * SP / 2.0 + 3.5 * SP) + }; + let _ = writeln!( + o, + "" + ); + let flags = match it.units { + 1 => 2, + 2 | 3 => 1, + _ => 0, + }; + for f in 0..flags { + let fy = y_to + f64::from(f) * if up { 5.0 } else { -5.0 }; + let dy = if up { 9.0 } else { -9.0 }; + let _ = writeln!( + o, + "", + dy * 0.5 + ); + } + } + if it.tie_start { + let y = bottom - f64::from(steps[0]) * SP / 2.0 + 6.0; + let _ = writeln!(o, "", x + 3.0); + } + } + } + } + // System bracket. + let y_last = y_sys + (parts.len().max(1) - 1) as f64 * STAFF_GAP + 4.0 * SP; + let _ = writeln!( + o, + "", + staff_x0 - 30.0, + staff_x0 - 30.0 + ); + } + o.push_str("\n"); + o +} + +fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) { + let mid = y0 + 2.0 * sp; + match units { + 16 => { + let _ = writeln!(o, "", x - 4.5, y0 + sp, sp / 2.0); + } + 8 | 12 => { + let _ = writeln!(o, "", x - 4.5, mid - sp / 2.0, sp / 2.0); + } + 4 | 6 => { + let _ = writeln!( + o, + "", + x - 2.0, + mid - 9.0 + ); + } + _ => { + let _ = writeln!(o, "", x - 2.0, mid - 3.0); + let _ = writeln!( + o, + "", + x + 2.5, + mid - 4.0, + x - 1.0, + mid + 7.0 + ); + if units == 1 { + let _ = writeln!(o, "", x - 3.5, mid + 2.0); + } + } + } +} + From 68abf77e2ddaea226a742efcb363630fa07faa3c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 09/33] Extract score writer changes from SoundCraft 7509b64c --- crates/score/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 30375b652..3aee96472 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -45,7 +45,13 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) + s.chars() + .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) + .collect::() + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { From 9dfaaf27af936868710d44042ede6705cb9e616f Mon Sep 17 00:00:00 2001 From: Samuel Bacaro Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 10/33] Extract score writer changes from SoundCraft ccd3fe7c --- crates/score/src/lib.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 3aee96472..d51ab8333 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -3,6 +3,14 @@ use std::fmt::Write as _; +const MAX_OUTPUT_BYTES: usize = 256 * 1024 * 1024; // 256 MiB +fn over_budget(buf: &str) -> Result<(), String> { + if buf.len() > MAX_OUTPUT_BYTES { + return Err(format!("score too large: over {} MiB", MAX_OUTPUT_BYTES / (1024 * 1024))); + } + Ok(()) +} + #[derive(Debug, Clone, PartialEq)] pub struct ScoreSetup { pub title: String, @@ -45,13 +53,7 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.chars() - .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) - .collect::() - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { @@ -68,7 +70,7 @@ fn note_type(units: u32) -> (&'static str, bool) { } /// MusicXML 4.0 (partwise) for `parts`. -pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> String { +pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { let mut x = String::new(); x.push_str("\n"); x.push_str("\n"); @@ -149,11 +151,12 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> String { } } x.push_str(" \n"); + over_budget(&x)?; } x.push_str(" \n"); } x.push_str("\n"); - x + Ok(x) } /// Staff position of `pitch` in half-spaces above the bottom line (treble E4 / bass G2). @@ -165,7 +168,7 @@ fn staff_step(pitch: u8, bass: bool) -> i32 { } /// An engraved score as a printable SVG page (A4 portrait width, as tall as needed). -pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { +pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { const W: f64 = 794.0; const MARGIN: f64 = 48.0; const SP: f64 = 7.0; // staff space @@ -299,6 +302,7 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { let _ = writeln!(o, "", x + 3.0); } } + over_budget(&o)?; } } // System bracket. @@ -311,7 +315,7 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { ); } o.push_str("\n"); - o + Ok(o) } fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) { From 8c6e050f324f8e50bddf556d12fcd48e3476d505 Mon Sep 17 00:00:00 2001 From: Samuel Bacaro Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 11/33] Extract score writer changes from SoundCraft fa77e03e --- crates/score/src/lib.rs | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index d51ab8333..59a28de68 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -4,9 +4,9 @@ use std::fmt::Write as _; const MAX_OUTPUT_BYTES: usize = 256 * 1024 * 1024; // 256 MiB -fn over_budget(buf: &str) -> Result<(), String> { - if buf.len() > MAX_OUTPUT_BYTES { - return Err(format!("score too large: over {} MiB", MAX_OUTPUT_BYTES / (1024 * 1024))); +fn over_budget(buf: &str, budget: usize) -> Result<(), String> { + if buf.len() > budget { + return Err(format!("score too large: over {} bytes", budget)); } Ok(()) } @@ -71,10 +71,19 @@ fn note_type(units: u32) -> (&'static str, bool) { /// MusicXML 4.0 (partwise) for `parts`. pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { + musicxml_budgeted(parts, setup, MAX_OUTPUT_BYTES) +} + +/// [`musicxml`] with an explicit byte budget (kept separate so tests can pass a tiny budget +/// instead of building a 256 MiB score). +fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { let mut x = String::new(); x.push_str("\n"); x.push_str("\n"); x.push_str("\n"); + // The header (and an oversized title/composer, escaped) can itself exceed the budget even with + // no measures, so check before the per-measure loop too. + over_budget(&x, budget)?; let _ = writeln!(x, " {}", xml_escape(&setup.title)); x.push_str(" \n"); if !setup.composer.is_empty() { @@ -85,6 +94,7 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { let _ = writeln!(x, " {}", i + 1, xml_escape(&p.name)); } x.push_str(" \n"); + over_budget(&x, budget)?; for (i, p) in parts.iter().enumerate() { let _ = writeln!(x, " ", i + 1); let mut meter = (0, 0); @@ -151,11 +161,12 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { } } x.push_str(" \n"); - over_budget(&x)?; + over_budget(&x, budget)?; } x.push_str(" \n"); } x.push_str("\n"); + over_budget(&x, budget)?; Ok(x) } @@ -169,6 +180,12 @@ fn staff_step(pitch: u8, bass: bool) -> i32 { /// An engraved score as a printable SVG page (A4 portrait width, as tall as needed). pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { + svg_budgeted(parts, setup, MAX_OUTPUT_BYTES) +} + +/// [`svg`] with an explicit byte budget (kept separate so tests can pass a tiny budget instead of +/// building a 256 MiB score). +fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { const W: f64 = 794.0; const MARGIN: f64 = 48.0; const SP: f64 = 7.0; // staff space @@ -190,7 +207,9 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { let _ = writeln!(o, "{}", W / 2.0, xml_escape(&setup.title)); if !setup.composer.is_empty() { let _ = writeln!(o, "{}", W - MARGIN, xml_escape(&setup.composer)); + over_budget(&o, budget)?; } + over_budget(&o, budget)?; let bar_w = (staff_x1 - staff_x0) / per as f64; for sys in 0..systems { let y_sys = top + sys as f64 * sys_h; @@ -302,8 +321,13 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { let _ = writeln!(o, "", x + 3.0); } } - over_budget(&o)?; + // Check each measure, so a run of rest-only or missing measures that only draws + // bar lines cannot grow the output past the budget untouched. + over_budget(&o, budget)?; } + // The staff markup (lines, clef, track names) itself grows with the part count even + // without any items, so check once per staff too. + over_budget(&o, budget)?; } // System bracket. let y_last = y_sys + (parts.len().max(1) - 1) as f64 * STAFF_GAP + 4.0 * SP; @@ -313,8 +337,10 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { staff_x0 - 30.0, staff_x0 - 30.0 ); + over_budget(&o, budget)?; } o.push_str("\n"); + over_budget(&o, budget)?; Ok(o) } From 1002aca27092b6fe41e3af5b3212080a354555cb Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 12/33] Extract score writer changes from SoundCraft 5075da2f --- crates/score/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 59a28de68..023f35554 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -53,7 +53,13 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) + s.chars() + .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) + .collect::() + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { From bfef2e5ce28dbc1e57e897058851024d161bd09b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 13/33] Extract score writer changes from SoundCraft fa34e0c1 --- crates/score/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 023f35554..c64ac0054 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -198,7 +198,9 @@ fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 14/33] Extract score writer changes from SoundCraft 4bdda5ff --- crates/score/src/lib.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index c64ac0054..d8e757b21 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -53,13 +53,10 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.chars() - .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) - .collect::() - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) + // Keep the score export's existing literal whitespace and quote spelling. The + // shared attribute writer owns XML legality/escaping; only its generated + // whitespace references are restored (input ampersands were escaped first). + craft_xml::esc_attr(s).replace(" ", "\t").replace(" ", "\n").replace(" ", "\r") } fn note_type(units: u32) -> (&'static str, bool) { From 3d160af4d90797f39196c22e81288d9c403030d2 Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 15/33] Extract score writer changes from SoundCraft 21cb618d --- crates/score/src/lib.rs | 40 ++++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index d8e757b21..cab0ad9bd 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -33,8 +33,10 @@ pub struct Item { pub pitches: Vec, /// Duration in sixteenths; always one of the supported duration values. pub units: u32, - pub tie_start: bool, - pub tie_stop: bool, + /// Pitches continuing into the next item. + pub tie_start: Vec, + /// Pitches continuing from the previous item. + pub tie_stop: Vec, } #[derive(Debug, Clone, PartialEq)] @@ -53,10 +55,13 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - // Keep the score export's existing literal whitespace and quote spelling. The - // shared attribute writer owns XML legality/escaping; only its generated - // whitespace references are restored (input ampersands were escaped first). - craft_xml::esc_attr(s).replace(" ", "\t").replace(" ", "\n").replace(" ", "\r") + s.chars() + .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) + .collect::() + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { @@ -137,10 +142,10 @@ fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Resul let _ = write!(x, "{alter}"); } let _ = write!(x, "{octave}{}", it.units); - if it.tie_stop { + if it.tie_stop.contains(pitch) { x.push_str(""); } - if it.tie_start { + if it.tie_start.contains(pitch) { x.push_str(""); } let _ = write!(x, "1{ty}"); @@ -150,12 +155,12 @@ fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Resul if alter != 0 { x.push_str("sharp"); } - if it.tie_stop || it.tie_start { + if it.tie_stop.contains(pitch) || it.tie_start.contains(pitch) { x.push_str(""); - if it.tie_stop { + if it.tie_stop.contains(pitch) { x.push_str(""); } - if it.tie_start { + if it.tie_start.contains(pitch) { x.push_str(""); } x.push_str(""); @@ -321,9 +326,16 @@ fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result", x + 3.0); + for pitch in &it.tie_start { + let above = it.pitches.first().is_some_and(|low| pitch > low); + let direction = if above { -1.0 } else { 1.0 }; + let y = bottom - f64::from(staff_step(*pitch, p.bass)) * SP / 2.0 + direction * 6.0; + let _ = writeln!( + o, + "", + x + 3.0, + direction * 5.0 + ); } } // Check each measure, so a run of rest-only or missing measures that only draws From 9b570237ef8682c3848bacf374ff1db06dc95241 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:23:04 -0500 Subject: [PATCH 16/33] feat(score): register reusable writers with bounded public notation input --- ATTRIBUTION.md | 4 +++ Cargo.lock | 7 +++++ Cargo.toml | 1 + crates/score/Cargo.toml | 14 +++++++++ crates/score/src/lib.rs | 65 ++++++++++++++++++++++++++++++++--------- 5 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 crates/score/Cargo.toml diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ab167207c..70a929de8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -103,3 +103,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso `crates/tga/src/metadata_tests.rs` and metadata-boundary helpers in `crates/tga/src/lib.rs` are adapted from nuclearspike's FilmCraft #1932 at `e7842f76f887005c460c64a8ab51d59d086e6f27` (MIT OR Apache-2.0). Synthetic fixtures are original contributor test data; primary Git author retained. The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper are ported from Craft Anything `8f3b775157d331dd31cfa4da911e26d8856b8c77` (same MIT OR Apache-2.0 source licenses). Brandon Thomas is the primary import author; retained hardening credits include Afloat, BFlat, Rahul, RRFZ and NetterSilver. The finite-real fix preserves gmrmad1 as author from Craft Anything #1905 (`d85e104f`); quoted-attribute/line-ending regressions preserve RRFZ. Bounds/adaptation and bounded entity scanning are subsequent Dylan M. Taylor changes. App-specific JSON projections and keyed-archive interpretation remain outside this crate. + +## Score serializers + +`crates/score` extracts SoundCraft MusicXML and SVG score writing from `crates/engine/src/score.rs` at main `648ed9db9a0e98cc55643babffac381521a556c8`, with per-pitch ties adapted from [SoundCraft #182](https://github.com/storytold/soundcraft/pull/182) at `21cb618d93ec0e8d4771ac534994de8d5996ff10`. Source is MIT OR Apache-2.0. Import commits preserve Brandon Thomas, NetterSilver, Samuel Bacaro and Vikram Bhaskaran as primary authors of their respective changes. The consumer retains session mapping and layout. Shared API wiring, validation and focused tests are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index ef82f1afa..41290ac89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2791,6 +2791,13 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-score" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + [[package]] name = "craft-scraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8ae36287..8c3c97517 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-score = { path = "crates/score" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/score/Cargo.toml b/crates/score/Cargo.toml new file mode 100644 index 000000000..f283282c4 --- /dev/null +++ b/crates/score/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-score" +description = "Application-independent MusicXML and printable SVG score writers" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[dependencies] +craft-xml.workspace = true + +[lints] +workspace = true diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index cab0ad9bd..130f9e857 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -13,6 +13,8 @@ fn over_budget(buf: &str, budget: usize) -> Result<(), String> { #[derive(Debug, Clone, PartialEq)] pub struct ScoreSetup { + /// Software name recorded in the MusicXML encoding metadata. + pub software: String, pub title: String, pub composer: String, pub bars_per_system: u32, @@ -55,13 +57,10 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.chars() - .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) - .collect::() - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) + // Keep the score export's existing literal whitespace and quote spelling. The + // shared attribute writer owns XML legality/escaping; only its generated + // whitespace references are restored (input ampersands were escaped first). + craft_xml::esc_attr(s).replace(" ", "\t").replace(" ", "\n").replace(" ", "\r") } fn note_type(units: u32) -> (&'static str, bool) { @@ -82,9 +81,10 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { musicxml_budgeted(parts, setup, MAX_OUTPUT_BYTES) } -/// [`musicxml`] with an explicit byte budget (kept separate so tests can pass a tiny budget -/// instead of building a 256 MiB score). -fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { +/// MusicXML with an explicit byte budget, capped at 256 MiB. +pub fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { + validate(parts, setup)?; + let budget = budget.min(MAX_OUTPUT_BYTES); let mut x = String::new(); x.push_str("\n"); x.push_str("\n"); @@ -97,7 +97,8 @@ fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Resul if !setup.composer.is_empty() { let _ = writeln!(x, " {}", xml_escape(&setup.composer)); } - x.push_str(" SoundCraft\n \n \n"); + let _ = writeln!(x, " {}", xml_escape(&setup.software)); + x.push_str(" \n \n"); for (i, p) in parts.iter().enumerate() { let _ = writeln!(x, " {}", i + 1, xml_escape(&p.name)); } @@ -191,9 +192,10 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { svg_budgeted(parts, setup, MAX_OUTPUT_BYTES) } -/// [`svg`] with an explicit byte budget (kept separate so tests can pass a tiny budget instead of -/// building a 256 MiB score). -fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { +/// SVG with an explicit byte budget, capped at 256 MiB. +pub fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { + validate(parts, setup)?; + let budget = budget.min(MAX_OUTPUT_BYTES); const W: f64 = 794.0; const MARGIN: f64 = 48.0; const SP: f64 = 7.0; // staff space @@ -395,3 +397,38 @@ fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) { } } +// Public notation data can come from callers other than SoundCraft's bounded layout. +// Validate before writing/escaping so malicious dimensions cannot overflow sums or create +// an unbounded temporary string before the output-budget checks run. +fn validate(parts: &[Part], setup: &ScoreSetup) -> Result<(), String> { + let invalid = || "score exceeds supported notation limits".to_string(); + if parts.len() > 4096 { + return Err(invalid()); + } + let mut text = setup.title.len().checked_add(setup.composer.len()).and_then(|n| n.checked_add(setup.software.len())).ok_or_else(invalid)?; + for part in parts { + text = text.checked_add(part.name.len()).ok_or_else(invalid)?; + if text > 16 * 1024 * 1024 || part.measures.len() > 2000 { + return Err(invalid()); + } + for measure in &part.measures { + if measure.items.len() > 128 { + return Err(invalid()); + } + for item in &measure.items { + if ![1, 2, 3, 4, 6, 8, 12, 16].contains(&item.units) + || item.pitches.len() > 16 + || item.tie_start.len() > 16 + || item.tie_stop.len() > 16 + || item.pitches.iter().chain(&item.tie_start).chain(&item.tie_stop).any(|p| *p > 127) + { + return Err(invalid()); + } + } + } + } + if text > 16 * 1024 * 1024 { + return Err(invalid()); + } + Ok(()) +} From 0006665d60e6a4ee6aeb231de33cd41d38931ece Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Mon, 16 Nov 2026 19:23:23 -0500 Subject: [PATCH 17/33] test(score): retain per-pitch MusicXML and SVG tie regression from SoundCraft 182 --- crates/score/src/lib.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 130f9e857..fccb5c32f 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -432,3 +432,37 @@ fn validate(parts: &[Part], setup: &ScoreSetup) -> Result<(), String> { } Ok(()) } +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + fn setup() -> ScoreSetup { + ScoreSetup { software: "SoundCraft".into(), title: "A<&\u{1}".into(), composer: "B".into(), bars_per_system: 4, show_track_names: true } + } + fn parts() -> Vec { + vec![Part { + name: "Keys".into(), + bass: false, + measures: vec![Measure { + numerator: 4, + denominator: 4, + items: vec![ + Item { pitches: vec![60, 64], units: 4, tie_start: vec![64], tie_stop: vec![] }, + Item { pitches: vec![64], units: 12, tie_start: vec![], tie_stop: vec![64] }, + ], + }], + }] + } + #[test] + fn per_pitch_ties_and_escaping_survive_serialization() { + let parts = parts(); + let xml = musicxml(&parts, &setup()).unwrap(); + assert!(xml.contains("A<&")); + let notes: Vec<_> = xml.split("").skip(1).map(|n| n.split("").next().unwrap()).collect(); + assert!(notes[0].contains("4")); + assert!(!notes[0].contains("") && notes[1].contains("")); + assert!(notes[2].contains("12") && notes[2].contains("")); + assert_eq!(svg(&parts, &setup()).unwrap().matches("stroke-width=\"0.9\"").count(), 1); + } +} From d5d65b128dfc74f77ffd23ea08fd3ea428a7d0cd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:23:23 -0500 Subject: [PATCH 18/33] test(score): exercise byte budgets and hostile notation input --- crates/score/src/lib.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index fccb5c32f..7ec2141c5 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -465,4 +465,13 @@ mod tests { assert!(notes[2].contains("12") && notes[2].contains("")); assert_eq!(svg(&parts, &setup()).unwrap().matches("stroke-width=\"0.9\"").count(), 1); } + #[test] + fn byte_budgets_and_hostile_durations_fail() { + assert!(musicxml_budgeted(&parts(), &setup(), 32).is_err()); + assert!(svg_budgeted(&parts(), &setup(), 32).is_err()); + let mut parts = parts(); + parts[0].measures[0].items[0].units = u32::MAX; + assert!(musicxml(&parts, &setup()).is_err()); + assert!(svg(&parts, &setup()).is_err()); + } } From 9595e0ca9bff15b04c0096458c63d96d8b090b63 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:25:08 -0500 Subject: [PATCH 19/33] test(score): retain original pitch spelling and staff placement regression --- crates/score/src/lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 7ec2141c5..7ca06261e 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -474,4 +474,12 @@ mod tests { assert!(musicxml(&parts, &setup()).is_err()); assert!(svg(&parts, &setup()).is_err()); } + #[test] + fn spelling_and_staff_steps() { + assert_eq!(spell(60), ('C', 0, 4)); + assert_eq!(spell(61), ('C', 1, 4)); + assert_eq!(staff_step(64, false), 0); // E4: bottom treble line + assert_eq!(staff_step(77, false), 8); // F5: top treble line + assert_eq!(staff_step(43, true), 0); // G2: bottom bass line + } } From c153d95e5587c26655ba543f6315dc7fadf2adcf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:22:29 -0500 Subject: [PATCH 20/33] 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 3fe6aed92..241c83ba3 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 d84980398..826bbe4b2 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 5873371e7..d636c0703 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 21/33] 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 a8301ccba..f404b3b6b 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 22/33] 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 8383b30c0..987b306b4 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 df4093aa3..5f162dea7 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 23/33] 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 000000000..f72bb5186 --- /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 82fd952e3..076f9dcdd 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 000000000..4f40caf75 --- /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 e7fc9abfc..0bfd33ecc 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 24/33] 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 02935bac6..9d260300c 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 74732b6d6..1ac11475f 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 72ae0083a..2c0f4dfea 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 000000000..d39a80b67 --- /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 000000000..c49b0666d --- /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 5ed5fb9de7a73647a754866ad386a1d362607144 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 16 Nov 2026 22:32:40 -0500 Subject: [PATCH 25/33] video: extract bounded Screen Video key-frame decoding from AniCraft Preserves codec algorithm from AniCraft1f3e603b7ff53a3da364e41ec4da8d43dc83aab0 and2b7571363b4b647266df758f95b6e397021cfd4d; neutral frame type and explicit caller limits adapt the shared API. --- crates/video/Cargo.toml | 3 ++ crates/video/src/lib.rs | 4 +++ crates/video/src/screen_video.rs | 62 ++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 crates/video/src/screen_video.rs diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index acc40ef23..004dcc6fe 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -14,6 +14,8 @@ all-features = true workspace = true [features] +# FLV codec 3 / SWF Screen Video key frames. +screen-video = ["dep:miniz_oxide"] # Every codec feature turns on one codec module; none is on by default. # DNxHD / DNxHR (SMPTE ST 2019-1): decoder and encoder. dnx = [] @@ -64,6 +66,7 @@ av1-large-encode = ["av1-encode", "dep:rav1e"] threads = ["dep:rayon", "rav1e?/threading"] [dependencies] +miniz_oxide = { workspace = true, optional = true } craft-media = { workspace = true } craft-jpeg = { workspace = true, optional = true } thiserror = { workspace = true } diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 17b22f320..1f262f2dd 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -74,3 +74,7 @@ pub mod av1; /// Uncompressed AVI and QuickTime pixel layouts. pub mod raw_video; + +/// Bounded Screen Video key-frame decoding (FLV codec 3). +#[cfg(feature = "screen-video")] +pub mod screen_video; diff --git a/crates/video/src/screen_video.rs b/crates/video/src/screen_video.rs new file mode 100644 index 000000000..7d0c7adbd --- /dev/null +++ b/crates/video/src/screen_video.rs @@ -0,0 +1,62 @@ +//! Screen Video (FLV codec 3 / SWF SCREENVIDEOPACKET) key-frame decoding. +//! The packet excludes the FLV video-tag codec byte. Blocks and rows are bottom-up; +//! output is straight RGBA8 in top-down row order. No inter-frame state or container I/O. + +/// One decoded top-down RGBA8 picture. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Four bytes per pixel, alpha always 255. + pub rgba: Vec, +} + +/// Decodes a complete key frame within caller axis and RGBA allocation limits. +/// Returns `None` for malformed/truncated data, unchanged blocks or exceeded limits. +/// Format dimensions are at most 4095 per axis; each block inflation is capped to +/// exactly its expected BGR byte count. Legacy trailing packet bytes are tolerated. +pub fn decode_keyframe(p: &[u8], max_edge: u32, max_rgba_bytes: usize) -> Option { + let h0 = u16::from_be_bytes([*p.first()?, *p.get(1)?]); + let h1 = u16::from_be_bytes([*p.get(2)?, *p.get(3)?]); + let (bw, w) = ((usize::from(h0 >> 12) + 1) * 16, usize::from(h0 & 0x0fff)); + let (bh, h) = ((usize::from(h1 >> 12) + 1) * 16, usize::from(h1 & 0x0fff)); + if w == 0 || h == 0 || w > max_edge as usize || h > max_edge as usize { + return None; + } + let bytes = w.checked_mul(h)?.checked_mul(4)?; + if bytes > max_rgba_bytes { + return None; + } + let mut rgba = vec![0u8; bytes]; + let mut at = 4usize; + // Block rows from the bottom of the picture. + for by in 0..h.div_ceil(bh) { + for bx in 0..w.div_ceil(bw) { + let (x0, y0) = (bx * bw, by * bh); + let (cw, ch) = (bw.min(w - x0), bh.min(h - y0)); + let size = usize::from(u16::from_be_bytes([*p.get(at)?, *p.get(at + 1)?])); + let packed = p.get(at + 2..at + 2 + size)?; + at += 2 + size; + if size == 0 { + // An unchanged block can't be in a key frame. + return None; + } + let want = cw * ch * 3; + let bgr = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(packed, want).ok()?; + if bgr.len() != want { + return None; + } + for (row, line) in bgr.chunks_exact(cw * 3).enumerate() { + // Rows count up from the bottom; the bitmap's rows count down from the top. + let y = h - 1 - (y0 + row); + for (col, px) in line.as_chunks::<3>().0.iter().enumerate() { + let i = (y * w + x0 + col) * 4; + rgba.get_mut(i..i + 4)?.copy_from_slice(&[px[2], px[1], px[0], 255]); + } + } + } + } + Some(Frame { width: w as u32, height: h as u32, rgba }) +} From 8ad90cc70db18fd576e74e2036cfaeeffa9774b9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 16 Nov 2026 22:33:12 -0500 Subject: [PATCH 26/33] test(video): retain synthetic partial-block Screen Video fixture --- crates/video/src/screen_video.rs | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/video/src/screen_video.rs b/crates/video/src/screen_video.rs index 7d0c7adbd..bb2ced9da 100644 --- a/crates/video/src/screen_video.rs +++ b/crates/video/src/screen_video.rs @@ -60,3 +60,43 @@ pub fn decode_keyframe(p: &[u8], max_edge: u32, max_rgba_bytes: usize) -> Option } Some(Frame { width: w as u32, height: h as u32, rgba }) } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + fn packet(w: usize, h: usize, block: usize, px: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + let mut packet = Vec::new(); + let n = (block / 16 - 1) as u16; + packet.extend_from_slice(&((n << 12) | w as u16).to_be_bytes()); + packet.extend_from_slice(&((n << 12) | h as u16).to_be_bytes()); + for by in 0..h.div_ceil(block) { + for bx in 0..w.div_ceil(block) { + let (x0, y0) = (bx * block, by * block); + let mut bgr = Vec::new(); + for row in 0..block.min(h - y0) { + for col in 0..block.min(w - x0) { + let [r, g, b] = px(x0 + col, h - 1 - (y0 + row)); + bgr.extend_from_slice(&[b, g, r]); + } + } + let z = miniz_oxide::deflate::compress_to_vec_zlib(&bgr, 6); + packet.extend_from_slice(&(z.len() as u16).to_be_bytes()); + packet.extend_from_slice(&z); + } + } + packet + } + #[test] + fn a_screen_video_key_frame_decodes_with_its_blocks_in_place() { + // 40 × 20 in 16-pixel blocks: partial blocks on the right and at the top. + let px = |x: usize, y: usize| [(x * 6) as u8, (y * 12) as u8, if x < 20 { 255 } else { 0 }]; + let Frame { width, height, rgba } = decode_keyframe(&packet(40, 20, 16, px), 8192, 64 << 20).unwrap(); + assert_eq!((width, height), (40, 20)); + for (x, y) in [(0, 0), (39, 0), (0, 19), (39, 19), (17, 3), (21, 18)] { + let i = (y * 40 + x) * 4; + let [r, g, b] = px(x, y); + assert_eq!(&rgba[i..i + 4], &[r, g, b, 255], "({x}, {y})"); + } + } +} From 3e0bb788a7ef48edc05285f05ee7b628c7b23bdd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:33:39 -0500 Subject: [PATCH 27/33] test(video): bound Screen Video output and hostile packet handling --- ATTRIBUTION.md | 4 ++++ Cargo.lock | 1 + crates/video/src/screen_video.rs | 17 +++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9d260300c..7f9ba73c6 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -114,3 +114,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## 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. + +## Screen Video key frames + +`crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index 1ac11475f..0ebe83376 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3286,6 +3286,7 @@ dependencies = [ "craft-jpeg", "craft-media", "craft-media-testkit", + "miniz_oxide 0.8.9", "rav1e", "rayon", "thiserror 2.0.21", diff --git a/crates/video/src/screen_video.rs b/crates/video/src/screen_video.rs index bb2ced9da..aab4718fb 100644 --- a/crates/video/src/screen_video.rs +++ b/crates/video/src/screen_video.rs @@ -99,4 +99,21 @@ mod tests { assert_eq!(&rgba[i..i + 4], &[r, g, b, 255], "({x}, {y})"); } } + #[test] + fn limits_truncation_and_unchanged_blocks_are_refused() { + let p = packet(40, 20, 16, |x, y| [x as u8, y as u8, 7]); + assert!(decode_keyframe(&p, 40, 40 * 20 * 4).is_some()); + assert!(decode_keyframe(&p, 39, usize::MAX).is_none()); + assert!(decode_keyframe(&p, 40, 40 * 20 * 4 - 1).is_none()); + for cut in 0..p.len() { + let _ = decode_keyframe(&p[..cut], 40, 40 * 20 * 4); + } + let mut unchanged = p.clone(); + unchanged[4..6].fill(0); + assert!(decode_keyframe(&unchanged, 40, 40 * 20 * 4).is_none()); + assert!(decode_keyframe(&[0, 0, 0, 0], 40, usize::MAX).is_none()); + let mut trailing = p.clone(); + trailing.extend_from_slice(&[1, 2, 3]); + assert_eq!(decode_keyframe(&trailing, 40, 3200), decode_keyframe(&p, 40, 3200)); + } } From 18277c006cf27e7a6dbf3130e2b6908b9e907bc5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:35:35 -0500 Subject: [PATCH 28/33] test(video): reject short and overlong inflated Screen Video blocks --- crates/video/src/screen_video.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/video/src/screen_video.rs b/crates/video/src/screen_video.rs index aab4718fb..87025f0fd 100644 --- a/crates/video/src/screen_video.rs +++ b/crates/video/src/screen_video.rs @@ -116,4 +116,15 @@ mod tests { trailing.extend_from_slice(&[1, 2, 3]); assert_eq!(decode_keyframe(&trailing, 40, 3200), decode_keyframe(&p, 40, 3200)); } + #[test] + fn inflated_block_must_have_exactly_its_expected_pixel_bytes() { + for length in [16 * 16 * 3 - 1, 16 * 16 * 3, 16 * 16 * 3 + 1] { + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&vec![7; length], 6); + let mut p = vec![0, 16, 0, 16]; + p.extend_from_slice(&(packed.len() as u16).to_be_bytes()); + p.extend_from_slice(&packed); + assert_eq!(decode_keyframe(&p, 16, 1024).is_some(), length == 16 * 16 * 3); + assert!(decode_keyframe(&p[..6], 16, 1024).is_none()); + } + } } From af9985523a079c9e25c638003dbd9aa09fa4d254 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:37:02 -0500 Subject: [PATCH 29/33] 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 286bd36d5..0c3c362a4 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 000000000..0553d606d --- /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 30/33] 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 aafc555c3..eda3bdf85 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 c5f14ef72..2644157ff 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 31/33] 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 3611cafbb..ef1464dd4 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 f876d06f9..3c021cb97 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> { From 399ecc74de1852634bf94e680d0a373bbbd37d56 Mon Sep 17 00:00:00 2001 From: Altynzhan Karybai Date: Mon, 16 Nov 2026 23:21:07 -0500 Subject: [PATCH 32/33] svg: share bounded compatibility transform parsing Preserve EffectCraft source from 4035d181329e847d7a57bf3d059502ea2c91b560, based on Brandon Thomas original 94e1c86d89a866771f80ad1610afda9aa12e85d8. Algorithm unchanged; module imports only adapted. Co-authored-by: Brandon Thomas --- crates/svg/src/lib.rs | 3 +++ crates/svg/src/transform_compat.rs | 37 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 crates/svg/src/transform_compat.rs diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 0c3c362a4..ccb2b6837 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -35,3 +35,6 @@ pub mod write; pub mod prefix_path; /// Compatibility CSS subset for simple SVG importers. pub mod simple_css; + +/// Prefix-preserving SVG transform-list compatibility. +pub mod transform_compat; diff --git a/crates/svg/src/transform_compat.rs b/crates/svg/src/transform_compat.rs new file mode 100644 index 000000000..b6ed506bf --- /dev/null +++ b/crates/svg/src/transform_compat.rs @@ -0,0 +1,37 @@ +//! Prefix-preserving transform-list compatibility for existing SVG importers. +//! At most six numbers are retained per operation; input scanning is not byte-capped. +//! Unknown/invalid-arity operations are ignored, unterminated suffixes stop parsing. +//! Matrix overflow behavior is unchanged; callers retain their geometry validation. + +use crate::prefix_path as pathdata; +use kurbo::Affine; + +/// Parse transforms using the established EffectCraft recovery and composition order. +pub fn parse_transform(s: &str) -> Affine { + let mut m = Affine::IDENTITY; + let mut rest = s; + while let Some(open) = rest.find('(') { + let name = rest[..open].trim().trim_start_matches(',').trim(); + let Some(close) = rest[open..].find(')') else { break }; + let (a, too_many) = pathdata::numbers_bounded(&rest[open + 1..open + close], 6); + rest = &rest[open + close + 1..]; + let t = if too_many { + Affine::IDENTITY + } else { + match (name, a.as_slice()) { + ("matrix", [a0, a1, a2, a3, a4, a5]) => Affine::new([*a0, *a1, *a2, *a3, *a4, *a5]), + ("translate", [x]) => Affine::translate((*x, 0.0)), + ("translate", [x, y]) => Affine::translate((*x, *y)), + ("scale", [scale]) => Affine::scale(*scale), + ("scale", [x, y]) => Affine::scale_non_uniform(*x, *y), + ("rotate", [angle]) => Affine::rotate(angle.to_radians()), + ("rotate", [angle, x, y]) => Affine::translate((*x, *y)) * Affine::rotate(angle.to_radians()) * Affine::translate((-*x, -*y)), + ("skewX", [angle]) => Affine::new([1.0, 0.0, angle.to_radians().tan(), 1.0, 0.0, 0.0]), + ("skewY", [angle]) => Affine::new([1.0, angle.to_radians().tan(), 0.0, 1.0, 0.0, 0.0]), + _ => Affine::IDENTITY, + } + }; + m *= t; + } + m +} From a6d5f86ee486eae446cb834559085f8ae1463021 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:22:03 -0500 Subject: [PATCH 33/33] svg: pin transform composition and malformed-list parity --- crates/svg/README.md | 3 +++ crates/svg/src/transform_compat.rs | 38 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/crates/svg/README.md b/crates/svg/README.md index a387e58c2..508081367 100644 --- a/crates/svg/README.md +++ b/crates/svg/README.md @@ -13,3 +13,6 @@ and its regression test preserve NetterSilver's `10e173c0e49696ad335e3da8a069889c089b09a6`; both contributors retain primary Git authorship for their respective port commits. Source and destination use MIT OR Apache-2.0. The shared adapter adds an aggregate 64 MiB stylesheet-text limit and idempotent indexing. + +### Transform compatibility +`transform_compat::parse_transform` preserves EffectCraft transform-list recovery and exact composition. It retains six numeric arguments per operation; scanning is not time/byte capped and matrix overflow behavior is unchanged. The strict geometry reader is unchanged. Source: Brandon Thomas, EffectCraft94e1c86d89a866771f80ad1610afda9aa12e85d8; bounded safe argument matching by Altynzhan Karybai,4035d181329e847d7a57bf3d059502ea2c91b560. diff --git a/crates/svg/src/transform_compat.rs b/crates/svg/src/transform_compat.rs index b6ed506bf..446cc8c0c 100644 --- a/crates/svg/src/transform_compat.rs +++ b/crates/svg/src/transform_compat.rs @@ -35,3 +35,41 @@ pub fn parse_transform(s: &str) -> Affine { } m } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn operations_keep_composition_order() { + let cases = [ + ("matrix(1 2 3 4 5 6)", Affine::new([1., 2., 3., 4., 5., 6.])), + ("translate(2)", Affine::translate((2., 0.))), + ("translate(2,3)", Affine::translate((2., 3.))), + ("scale(2)", Affine::scale(2.)), + ("scale(2 3)", Affine::scale_non_uniform(2., 3.)), + ("rotate(30)", Affine::rotate(30f64.to_radians())), + ("rotate(30 2 3)", Affine::translate((2., 3.)) * Affine::rotate(30f64.to_radians()) * Affine::translate((-2., -3.))), + ("skewX(30)", Affine::new([1., 0., 30f64.to_radians().tan(), 1., 0., 0.])), + ("skewY(30)", Affine::new([1., 30f64.to_radians().tan(), 0., 1., 0., 0.])), + ]; + for (text, expected) in cases { + assert_eq!(parse_transform(text).as_coeffs(), expected.as_coeffs()); + assert_eq!(parse_transform(&format!("translate(7,9), {text}")).as_coeffs(), (Affine::translate((7., 9.)) * expected).as_coeffs()); + } + } + + #[test] + fn malformed_and_oversized_operations_keep_accepted_prefix() { + for text in ["", "unknown(1)", "translate()", "scale(1 2 3)", "matrix(1 2 3 4 5 6 7)", "rotate(2 3)"] { + assert_eq!(parse_transform(text), Affine::IDENTITY); + } + for suffix in ["translate(", "unknown(1)", "matrix(1 2 3 4 5 6 7)"] { + assert_eq!(parse_transform(&format!("translate(3,4){suffix}")), Affine::translate((3., 4.))); + } + assert_eq!(parse_transform("unknown(1) scale(2)"), Affine::scale(2.)); + assert_eq!(parse_transform("translate(3 4oops)"), Affine::translate((3., 4.))); + let huge = format!("scale({}) translate(2)", "1 ".repeat(10_000)); + assert_eq!(parse_transform(&huge), Affine::translate((2., 0.))); + } +}