mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-18 08:15:29 +00:00
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.
This commit is contained in:
1 parent
c376774f15
commit
5f453efa9a
8 files changed
+184
-21
No files matched your search
@@ -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::<u32>().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::<u32>().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
|
||||
|
||||
@@ -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<u32, u32>) {
|
||||
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<u32, u32> = 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<u32>,
|
||||
/// 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<u32, u32>,
|
||||
/// Note part id → file note id, in first-reference order.
|
||||
footnotes: Vec<u32>,
|
||||
endnotes: Vec<u32>,
|
||||
|
||||
@@ -31,7 +31,8 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
// Fresh drawing ids start past the shapes' own (connectors refer to those).
|
||||
docpr: doc.next_shape_id().saturating_sub(1),
|
||||
shape_ids: std::collections::HashSet::new(),
|
||||
z: 251_658_240,
|
||||
z: 0,
|
||||
zmap: BTreeMap::new(),
|
||||
footnotes: Vec::new(),
|
||||
endnotes: Vec::new(),
|
||||
hf: Vec::new(),
|
||||
@@ -57,6 +58,7 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String,
|
||||
.flat_map(|(n, c)| c.iter().enumerate().map(move |(seq, id)| (*id, (n as u32 + 1, seq as u32))))
|
||||
.collect(),
|
||||
};
|
||||
(wr.z, wr.zmap) = super::stacking(doc);
|
||||
wr.assign_media();
|
||||
wr.embeds.reserve_media(wr.media_files.values());
|
||||
let mut entries: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
|
||||
@@ -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" }),
|
||||
|
||||
@@ -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#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let body = format!("<w:p>{}{}</w:p>", 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::<Vec<_>>();
|
||||
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#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let body = format!("<w:p>{}{}</w:p>", 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::<Vec<_>>();
|
||||
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<u32> = 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!("<w:p>{}</w:p>", shape("Low", 7)));
|
||||
let mut sep = read_body(&format!("<w:p>{}</w:p>", 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<u64> = attr_values(&text(&files, "word/document.xml"), "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect();
|
||||
let seps: Vec<u64> = 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!("<w:p>{}</w:p>", shape("Low", 7)));
|
||||
let entry = read_body(&format!("<w:p>{}</w:p>", 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!("<w:p>{}</w:p>", 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#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#, "", "<wps:cNvSpPr/>")
|
||||
.replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{z}""#))
|
||||
};
|
||||
let d = read_body(&format!("<w:p>{}{}</w:p>", 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::<Vec<_>>(), [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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<u32>, 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)) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user