fix(odf): preserve boundary stacking and inline drawing metadata

This commit is contained in:
FredApps committed 2026-11-16 18:24:18 +01:00
1 parent c5f217e765
commit 37d7236d86
10 files changed
+150 -35

No files matched your search

+18 -2
View File
@@ -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<Box<craft_wordmodel::para::Float>> {
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<u32>, 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());
}
}
+3 -2
View File
@@ -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<Box<craft_wordmodel::para::Float>>,
/// The embedded object this picture shows, kept whole (ODT only; see [`OdfObject`]).
pub object: Option<Arc<OdfObject>>,
+1
View File
@@ -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(),
});
+6 -3
View File
@@ -67,6 +67,7 @@ pub(in crate::text) struct OpenGroup {
pub(in crate::text) anchor: Option<String>,
/// Its `text:anchor-page-number`.
pub(in crate::text) page: Option<String>,
pub(in crate::text) z: u32,
pub(in crate::text) style: Option<String>,
pub(in crate::text) members: Vec<model::Member>,
}
@@ -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 });
}
+48 -17
View File
@@ -443,47 +443,78 @@ pub(super) fn z_of(a: &Attrs) -> u32 {
get(a, "draw:z-index").and_then(|v| v.trim().parse::<u32>().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<u32>,
}
/// 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<Stacking, String> {
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<u32>, 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
+2 -2
View File
@@ -1038,7 +1038,7 @@ fn export_as(doc: &Document, mime: &str) -> Result<Vec<u8>, 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<Vec<u8>, 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<PageParts> = pages.iter().map(|(_, sec)| page_parts(doc, sec, &mut hw)).collect();
+63
View File
@@ -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#"<draw:rect svg:width="1in" svg:height="1in"/>"#.repeat(5);
let objects = if grouped {
format!(r#"<draw:g text:anchor-type="paragraph">{shapes}</draw:g>"#)
} else {
shapes.replace("<draw:rect ", r#"<draw:rect text:anchor-type="paragraph" "#)
};
let objects = if location == 3 { objects.replacen(r#"text:anchor-type="paragraph""#, r#"text:anchor-type="as-char""#, 1) } else { objects };
let content = format!(
r#"<office:document-content {NS_T} {NS_D}><office:body><office:text><text:p>{objects}</text:p></office:text></office:body></office:document-content>"#
);
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();
}
}
}
+2 -2
View File
@@ -176,8 +176,8 @@ pub(super) struct Writer {
pub(super) named_text: std::collections::BTreeSet<String>,
/// 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,
+1 -1
View File
@@ -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!(
"<draw:frame draw:name=\"{}Chart{n}\"{style}{anchor} svg:width=\"{}\" svg:height=\"{}\" draw:z-index=\"{z}\">{inner}",
self.prefix,
+6 -6
View File
@@ -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!(
"<draw:frame draw:name=\"{}Image{n}\"{style}{anchor} svg:width=\"{}\" svg:height=\"{}\" draw:z-index=\"{z}\">{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!("<draw:g draw:name=\"{}Group{}\" draw:style-name=\"{style}\"{anchor} draw:z-index=\"{z}\">", 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!(
"<draw:frame draw:name=\"{}\" draw:style-name=\"{style}\"{anchor} svg:width=\"{}\"{height}{xy} draw:z-index=\"{z}\"><draw:text-box{min}{next}>{body}</draw:text-box></draw:frame>",
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}</{element}>",
self.prefix, self.boxes,