From 741192a57c016918badb5e2f63125721aa4d28d2 Mon Sep 17 00:00:00 2001 From: Andy Ching <53651198+andyching168@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:15:06 +0800 Subject: [PATCH 1/3] craft-docx: write Word 2010 shapes inside mc:AlternateContent with a VML fallback A shape was written as a bare `wps:wsp` in `w:drawing`. Word 2007, and Word 2000-2003 with the Office Compatibility Pack, don't know `wps` and refuse the whole file. Word writes such shapes in `mc:AlternateContent`. `write_shape` now guards the drawing with `mc:Choice Requires="wps"` and, for rectangles, text boxes, rounded rectangles and ellipses, adds an `mc:Fallback` with the shape as VML: size, position, z-order, wrapping, fill, outline and the text box's text (copied from the choice's output, so the story isn't written twice). Other kinds get no fallback; an old reader skips that shape and still opens the file. Refs storytold/wordcraft#6849 --- crates/docx/src/write/story/drawing.rs | 19 ++- crates/docx/src/write/story/object.rs | 159 ++++++++++++++++++++++++- crates/docx/tests/it/main.rs | 1 + crates/docx/tests/it/roundtrip.rs | 5 +- crates/docx/tests/it/text_boxes.rs | 3 +- crates/docx/tests/it/wps_fallback.rs | 96 +++++++++++++++ 6 files changed, 275 insertions(+), 8 deletions(-) create mode 100644 crates/docx/tests/it/wps_fallback.rs diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 7c03cca6e..94154f649 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -69,9 +69,18 @@ impl Writer<'_> { } /// A shape's or text box's `wps:wsp`, at `off` in its group (or 0, 0). In a group it carries - /// its own `wps:cNvPr` with drawing id `id`. - pub(super) fn wsp(&mut self, w: &mut W, o: &InlineObject, id: Option<&str>, off: (f32, f32), rels: &mut PartRels, depth: usize) { - let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return }; + /// its own `wps:cNvPr` with drawing id `id`. Returns where in `w` its `w:txbxContent` was + /// written, for a VML fallback to repeat. + pub(super) fn wsp( + &mut self, + w: &mut W, + o: &InlineObject, + id: Option<&str>, + off: (f32, f32), + rels: &mut PartRels, + depth: usize, + ) -> Option> { + let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, effects, float, freeform, extra } = o else { return None }; let geom = freeform.as_deref().filter(|_| *kind == ShapeKind::Freeform); w.open("wps:wsp", &[]); if let Some(id) = id { @@ -181,6 +190,7 @@ impl Writer<'_> { // its place in it instead. let part = (*story).and_then(|id| self.doc.parts.get(&id).filter(|p| p.kind == craft_wordmodel::PartKind::TextBox).map(|p| (id, p))); let link = part.and_then(|(id, _)| self.txbx_links.get(&id).copied()); + let mut content = None; if let Some((n, seq)) = link.filter(|(_, seq)| *seq > 0) { w.empty("wps:linkedTxbx", &[("id", &n.to_string()), ("seq", &seq.to_string())]); } else if let Some((id, part)) = part @@ -190,6 +200,7 @@ impl Writer<'_> { Some((n, _)) => w.open("wps:txbx", &[("id", &n.to_string())]), None => w.open("wps:txbx", &[]), } + let start = w.s.len(); w.open("w:txbxContent", &[]); if self.written_boxes.insert(id) { let blocks = part.blocks.clone(); @@ -198,6 +209,7 @@ impl Writer<'_> { w.empty("w:p", &[]); } w.close("w:txbxContent"); + content = Some(start..w.s.len()); w.close("wps:txbx"); self.boxes.leave(); } @@ -231,6 +243,7 @@ impl Writer<'_> { w.close("wps:bodyPr"); } w.close("wps:wsp"); + content } /// A `w:drawing` holding `graphic` (an `a:graphic`) in a frame of the object's size and place. diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 6cdd54f46..10f5ce03c 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -1,7 +1,7 @@ use super::drawing::{DrawingInfo, shape_name, spin_attrs, write_fill, xfrm_spin_only}; use super::field::{FieldData, field_run}; use super::section::comment_reference_style; -use super::{CharProps, Fill, InlineObject, NoteKind, PartRels, TextColor, W, Wrap, Writer, emu, n, rpr}; +use super::{Anchor, CharProps, Fill, Float, InlineObject, NoteKind, PartRels, ShapeKind, TextColor, W, Wrap, Writer, emu, n, rpr}; impl Writer<'_> { /// Write an inline object (`Bookmark`, `Comment`, `Equation`, `Field`, `Shape`, etc.). @@ -366,6 +366,11 @@ impl Writer<'_> { self.rev_open(w, props); w.open("w:r", &[]); self.rpr(w, props); + // A Word 2010 shape (`wps`) goes in `mc:AlternateContent`, as Word writes it: a reader + // that doesn't know `wps` (Word 2007, the Office Compatibility Pack) takes the VML + // fallback, or skips the shape when VML has no form for it, instead of refusing the file. + w.open("mc:AlternateContent", &[]); + w.open("mc:Choice", &[("Requires", "wps")]); w.open("w:drawing", &[]); let docpr = self.shape_docpr(extra.id); let link = Self::drawing_link(props, rels); @@ -387,15 +392,138 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); - self.wsp(w, o, None, (0.0, 0.0), rels, depth); + let content = self.wsp(w, o, None, (0.0, 0.0), rels, depth); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); w.close("w:drawing"); + w.close("mc:Choice"); + if freeform.is_none() && vml_tag(*kind).is_some() { + // The same text again: the fallback is a copy of the choice, not more of the story. + let content = content.and_then(|r| w.s.get(r)).map(str::to_owned); + w.open("mc:Fallback", &[]); + self.vml_shape(w, o, float, content.as_deref()); + w.close("mc:Fallback"); + } + w.close("mc:AlternateContent"); w.close("w:r"); self.rev_close(w, props); } + /// A shape as VML (`w:pict`), for readers older than Word 2010 shapes: its frame, place, + /// wrapping, fill, outline and text box. Only for a kind [`vml_tag`] names. + fn vml_shape(&self, w: &mut W, o: &InlineObject, float: &Float, content: Option<&str>) { + let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, extra, .. } = o else { return }; + let Some(tag) = vml_tag(*kind) else { return }; + let pt = |v: f32| format!("{:.2}pt", craft_wordmodel::geom::finite(v)); + let mut style = Vec::new(); + if float.wrap != Wrap::Inline { + style.push("position:absolute".to_string()); + style.push(format!("margin-left:{}", pt(float.x))); + style.push(format!("margin-top:{}", pt(float.y))); + } + style.push(format!("width:{}", pt(sw.max(0.0)))); + style.push(format!("height:{}", pt(sh.max(0.0)))); + let spin = float.spin(); + if spin.deg != 0.0 { + style.push(format!("rotation:{}", spin.deg)); + } + match (spin.flip_h, spin.flip_v) { + (true, true) => style.push("flip:x y".into()), + (true, false) => style.push("flip:x".into()), + (false, true) => style.push("flip:y".into()), + (false, false) => {} + } + if float.wrap != Wrap::Inline { + // The stacking order the choice was given; behind the text is below it. + let z = i64::from(self.z); + style.push(format!("z-index:{}", if float.wrap == Wrap::BehindText { -z } else { z })); + if let Some(a) = float.h_align { + style.push(format!("mso-position-horizontal:{}", a.ooxml(true))); + } + style.push(format!("mso-position-horizontal-relative:{}", vml_rel(float.h_rel, true))); + if let Some(a) = float.v_align { + style.push(format!("mso-position-vertical:{}", a.ooxml(false))); + } + style.push(format!("mso-position-vertical-relative:{}", vml_rel(float.v_rel, false))); + } + let body = (*story).and_then(|id| self.doc.parts.get(&id)).map(|p| p.body).unwrap_or_default(); + style.push( + match body.anchor { + craft_wordmodel::props::VAlign::Top => "v-text-anchor:top", + craft_wordmodel::props::VAlign::Center => "v-text-anchor:middle", + craft_wordmodel::props::VAlign::Bottom => "v-text-anchor:bottom", + } + .into(), + ); + let style = style.join(";"); + let mut attrs: Vec<(&str, String)> = vec![("style", style)]; + if *kind == ShapeKind::RoundedRectangle { + // The same fraction of the shorter side: VML's in 1/65536ths, DrawingML's in 1/100000ths. + let c = match extra.corner { + Some(c) => c.min(craft_wordmodel::connector::MAX_CORNER) as f32 / 100_000.0, + None => craft_wordmodel::connector::DEFAULT_CORNER, + }; + attrs.push(("arcsize", format!("{}f", (c * 65_536.0).round() as u32))); + } + if float.wrap != Wrap::Inline { + attrs.push(("o:allowincell", (if float.outside_cell { "f" } else { "t" }).into())); + } + let opacity = match fill.as_ref() { + Some(f) => { + attrs.push(("fillcolor", format!("#{}", f.main_color().hex()))); + match f { + Fill::Solid { transparency, .. } if *transparency > 0.0 => Some(format!("{:.4}", (1.0 - transparency / 100.0).clamp(0.0, 1.0))), + _ => None, + } + } + None => { + attrs.push(("filled", "f".into())); + None + } + }; + match stroke { + Some(c) => { + attrs.push(("strokecolor", format!("#{}", c.hex()))); + attrs.push(("strokeweight", pt(stroke_width.clamp(0.0, 100.0)))); + } + None => attrs.push(("stroked", "f".into())), + } + let attrs: Vec<(&str, &str)> = attrs.iter().map(|(k, v)| (*k, v.as_str())).collect(); + w.open("w:pict", &[]); + w.open(tag, &attrs); + if let Some(opacity) = &opacity { + w.empty("v:fill", &[("opacity", opacity)]); + } + if let Some(content) = content { + let inset = body.inset.map(|i| i.map(|v| pt(v.min(craft_wordmodel::MAX_TEXT_BOX_INSET) as f32 / 12_700.0)).join(",")); + let mut tb: Vec<(&str, &str)> = Vec::new(); + if let Some(inset) = &inset { + tb.push(("inset", inset)); + } + if body.auto_fit { + tb.push(("style", "mso-fit-shape-to-text:t")); + } + w.open("v:textbox", &tb); + w.raw(content); + w.close("v:textbox"); + } + let wrap = match float.wrap { + Wrap::Square => Some("square"), + Wrap::Tight => Some("tight"), + Wrap::Through => Some("through"), + Wrap::TopAndBottom => Some("topAndBottom"), + Wrap::Inline | Wrap::BehindText | Wrap::InFrontOfText => None, + }; + if let Some(wrap) = wrap { + let side = float.wrap_text.ooxml(); + let attrs: &[(&str, &str)] = if float.wrap_text.is_both() { &[("type", wrap)] } else { &[("type", wrap), ("side", side)] }; + w.empty("w10:wrap", attrs); + } + w.close(tag); + w.close("w:pict"); + } + fn write_group(&mut self, w: &mut W, o: &InlineObject, props: &CharProps, rels: &mut PartRels, depth: usize) { let InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children, canvas } = o else { return }; self.rev_open(w, props); @@ -487,6 +615,33 @@ impl Writer<'_> { } } +/// The VML element that draws a shape kind, for the kinds VML has one for. +fn vml_tag(kind: ShapeKind) -> Option<&'static str> { + match kind { + ShapeKind::Rectangle | ShapeKind::TextBox => Some("v:rect"), + ShapeKind::RoundedRectangle => Some("v:roundrect"), + ShapeKind::Ellipse => Some("v:oval"), + _ => None, + } +} + +/// A floating object's anchor as VML names it (`mso-position-horizontal-relative`, `-vertical-`). +fn vml_rel(a: Anchor, horiz: bool) -> &'static str { + match (a, horiz) { + (Anchor::Margin, _) => "margin", + (Anchor::Page, _) => "page", + (Anchor::InsideMargin, _) => "inner-margin-area", + (Anchor::OutsideMargin, _) => "outer-margin-area", + (Anchor::LeftMargin, true) => "left-margin-area", + (Anchor::RightMargin, true) => "right-margin-area", + (Anchor::Character, true) => "char", + (Anchor::TopMargin, false) => "top-margin-area", + (Anchor::BottomMargin, false) => "bottom-margin-area", + (Anchor::Line, false) => "line", + _ => "text", + } +} + pub(super) fn ink_name(tool: craft_wordmodel::freeform::InkTool) -> &'static str { match tool { craft_wordmodel::freeform::InkTool::Pen => "Pen", diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index b0bab5833..d1def3f8c 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -49,3 +49,4 @@ mod undefined_style; mod vml_shapes; mod word_xml; mod wordml2003_write; +mod wps_fallback; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 8f3bbdd0b..65a01e6b4 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -956,7 +956,8 @@ fn toc_field_skips_nested_stories() { let mut xml = String::new(); std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); let boxes: Vec<(usize, usize)> = xml.match_indices("").map(|(a, _)| (a, a + xml[a..].find("").unwrap())).collect(); - assert_eq!(boxes.len(), 2, "{xml}"); + // Each box twice: its shape and its VML fallback. + assert_eq!(boxes.len(), 4, "{xml}"); let in_box = |i: usize| boxes.iter().any(|(a, b)| (*a..*b).contains(&i)); for kind in ["begin", "separate", "end"] { let at: Vec = xml.match_indices(&format!(r#"fldCharType="{kind}""#)).map(|(i, _)| i).collect(); @@ -964,7 +965,7 @@ fn toc_field_skips_nested_stories() { assert!(!in_box(at[0]), "field {kind} written inside a text box: {xml}"); } let (begin, end) = (xml.find(r#"fldCharType="begin""#).unwrap(), xml.find(r#"fldCharType="end""#).unwrap()); - assert!(begin > boxes[0].1 && end > boxes[1].1 && end < xml.find("").unwrap(), "{xml}"); + assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("").unwrap(), "{xml}"); } #[test] diff --git a/crates/docx/tests/it/text_boxes.rs b/crates/docx/tests/it/text_boxes.rs index 608d22d33..a5824cafc 100644 --- a/crates/docx/tests/it/text_boxes.rs +++ b/crates/docx/tests/it/text_boxes.rs @@ -257,5 +257,6 @@ fn story_shared_by_many_shapes_is_written_once() { } let xml = document_xml(&craft_docx::write(&d).unwrap()); assert!(xml.len() < 2_000_000, "document.xml is {} bytes", xml.len()); - assert_eq!(xml.matches(text.as_str()).count(), 1); + // Once in the first shape and once in its VML fallback; the other shapes don't repeat it. + assert_eq!(xml.matches(text.as_str()).count(), 2); } diff --git a/crates/docx/tests/it/wps_fallback.rs b/crates/docx/tests/it/wps_fallback.rs new file mode 100644 index 000000000..ed9d36555 --- /dev/null +++ b/crates/docx/tests/it/wps_fallback.rs @@ -0,0 +1,96 @@ +//! Word 2010 shapes (`wps:wsp`) are written inside `mc:AlternateContent` with a VML fallback +//! (ECMA-376 Part 3, Markup Compatibility; Part 4 §14.1, VML), so a reader that doesn't know +//! `wps` — Word 2007, or Word 2000-2003 with the Office Compatibility Pack — takes the fallback +//! or skips the shape instead of refusing the whole file. + +use std::io::Read; + +use craft_wordmodel::para::{Anchor, FloatAlign, ShapeKind, Wrap}; +use craft_wordmodel::{Document, InlineObject, PartKind, TextBody, para_block}; + +fn document_xml(bytes: &[u8]) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); + s +} + +fn shape(kind: ShapeKind, story: Option) -> InlineObject { + let float = craft_wordmodel::para::Float { + wrap: Wrap::Square, + h_rel: Anchor::Margin, + h_align: Some(FloatAlign::End), + v_rel: Anchor::Paragraph, + y: 0.05, + ..Default::default() + }; + InlineObject::Shape { + kind, + w: 10.7, + h: 12.2, + fill: None, + stroke: None, + stroke_width: 0.75, + float, + story, + effects: Default::default(), + freeform: None, + extra: Default::default(), + } +} + +/// A page number in a floating text box, as in a footer: the shape that made the +/// Compatibility Pack refuse the file. +#[test] +fn a_text_box_gets_a_vml_fallback_with_its_text() { + let mut d = Document::from_text("a"); + let id = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("29", Default::default()))]); + d.parts.get_mut(&id).unwrap().body = TextBody { auto_fit: true, inset: Some([0; 4]), ..Default::default() }; + d.insert_object(&craft_wordmodel::Pos::body(0, 1), shape(ShapeKind::TextBox, Some(id)), &Default::default()).unwrap(); + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains(r#""#), "{xml}"); + assert!(!xml.contains(""), "no bare Word 2010 shape: {xml}"); + let fallback = &xml[xml.find("").expect("a fallback")..]; + assert!(fallback.starts_with(""#, + r#""#, + ] { + assert!(fallback.contains(want), "{want} in {fallback}"); + } + assert_eq!(xml.matches(">29").count(), 2, "the text in the choice and again in the fallback"); + + // Read back: the choice, once. + let r = craft_docx::read(&bytes).unwrap(); + let mut boxes = Vec::new(); + r.objects_in_reading_order(&mut |o| boxes.extend(o.text_boxes())); + boxes.retain(|id| r.parts.get(id).is_some_and(|p| p.kind == PartKind::TextBox)); + assert_eq!(boxes.len(), 1, "one text box, not the fallback as well"); + assert_eq!(r.plain_text(craft_wordmodel::StoryRef::Part(boxes[0])), "29"); +} + +/// A shape VML has no simple form for is still guarded, with no fallback: an old reader skips it. +#[test] +fn a_shape_without_a_vml_form_is_guarded_without_a_fallback() { + let mut d = Document::from_text("a"); + d.insert_object(&craft_wordmodel::Pos::body(0, 1), shape(ShapeKind::Star, None), &Default::default()).unwrap(); + let xml = document_xml(&craft_docx::write(&d).unwrap()); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(""), "{xml}"); + assert!(!xml.contains(""), "{xml}"); + let r = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + let mut kinds = Vec::new(); + r.objects_in_reading_order(&mut |o| { + if let InlineObject::Shape { kind, .. } = o { + kinds.push(*kind); + } + }); + assert_eq!(kinds, vec![ShapeKind::Star]); +} From 489f3cbc129170b39b388e087b5ff3fb4fc2ccc2 Mon Sep 17 00:00:00 2001 From: Andy Ching <53651198+andyching168@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:32:11 +0800 Subject: [PATCH 2/3] craft-docx: guard a shape only when it gets a VML fallback; keep more in the fallback A shape guarded by `mc:AlternateContent` with no fallback is skipped by a reader that doesn't know `wps`, and dropped on that reader's next save: worse than refusing the file. Such shapes are written bare again; only shapes with a VML form are guarded. The VML fallback also keeps the shape's own stacking order (a floating object in its text box moved `self.z` on), its wrap distances, its hidden flag and its text box's text direction. --- crates/docx/src/write/story/object.rs | 50 +++++++++++++++++++------ crates/docx/tests/it/wps_fallback.rs | 54 ++++++++++++++++++++++----- 2 files changed, 83 insertions(+), 21 deletions(-) diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 10f5ce03c..6b73aacd8 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -366,11 +366,16 @@ impl Writer<'_> { self.rev_open(w, props); w.open("w:r", &[]); self.rpr(w, props); - // A Word 2010 shape (`wps`) goes in `mc:AlternateContent`, as Word writes it: a reader - // that doesn't know `wps` (Word 2007, the Office Compatibility Pack) takes the VML - // fallback, or skips the shape when VML has no form for it, instead of refusing the file. - w.open("mc:AlternateContent", &[]); - w.open("mc:Choice", &[("Requires", "wps")]); + // A Word 2010 shape (`wps`) with a VML form goes in `mc:AlternateContent`, as Word writes + // it: a reader that doesn't know `wps` (Word 2007, the Office Compatibility Pack) takes the + // VML fallback instead of refusing the file. A shape without one stays bare: guarded with + // no fallback, that reader would open the file without the shape and drop it on its next + // save, which is worse than refusing the file. + let fallback = freeform.is_none() && vml_tag(*kind).is_some(); + if fallback { + w.open("mc:AlternateContent", &[]); + w.open("mc:Choice", &[("Requires", "wps")]); + } w.open("w:drawing", &[]); let docpr = self.shape_docpr(extra.id); let link = Self::drawing_link(props, rels); @@ -389,6 +394,8 @@ 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; w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); @@ -397,22 +404,22 @@ impl Writer<'_> { w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); w.close("w:drawing"); - w.close("mc:Choice"); - if freeform.is_none() && vml_tag(*kind).is_some() { + if fallback { + w.close("mc:Choice"); // The same text again: the fallback is a copy of the choice, not more of the story. let content = content.and_then(|r| w.s.get(r)).map(str::to_owned); w.open("mc:Fallback", &[]); - self.vml_shape(w, o, float, content.as_deref()); + self.vml_shape(w, o, float, z, content.as_deref()); w.close("mc:Fallback"); + w.close("mc:AlternateContent"); } - w.close("mc:AlternateContent"); w.close("w:r"); self.rev_close(w, props); } /// A shape as VML (`w:pict`), for readers older than Word 2010 shapes: its frame, place, /// wrapping, fill, outline and text box. Only for a kind [`vml_tag`] names. - fn vml_shape(&self, w: &mut W, o: &InlineObject, float: &Float, content: Option<&str>) { + fn vml_shape(&self, w: &mut W, o: &InlineObject, float: &Float, z: u32, content: Option<&str>) { let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, extra, .. } = o else { return }; let Some(tag) = vml_tag(*kind) else { return }; let pt = |v: f32| format!("{:.2}pt", craft_wordmodel::geom::finite(v)); @@ -436,8 +443,14 @@ impl Writer<'_> { } if float.wrap != Wrap::Inline { // The stacking order the choice was given; behind the text is below it. - let z = i64::from(self.z); + let z = i64::from(z); style.push(format!("z-index:{}", if float.wrap == Wrap::BehindText { -z } else { z })); + // The same clearances from the text as the choice's `distL`/`distR`/`distT`/`distB`. + let d = pt(float.dist.clamp(0.0, 1584.0)); + style.push(format!("mso-wrap-distance-left:{d}")); + style.push(format!("mso-wrap-distance-right:{d}")); + style.push(format!("mso-wrap-distance-top:{}", pt(float.dist_top.clamp(0.0, 1584.0)))); + style.push(format!("mso-wrap-distance-bottom:{}", pt(float.dist_bottom.clamp(0.0, 1584.0)))); if let Some(a) = float.h_align { style.push(format!("mso-position-horizontal:{}", a.ooxml(true))); } @@ -456,6 +469,9 @@ impl Writer<'_> { } .into(), ); + if float.hidden { + style.push("visibility:hidden".into()); + } let style = style.join(";"); let mut attrs: Vec<(&str, String)> = vec![("style", style)]; if *kind == ShapeKind::RoundedRectangle { @@ -501,8 +517,18 @@ impl Writer<'_> { if let Some(inset) = &inset { tb.push(("inset", inset)); } + // Text direction as the VML reader takes it (stacked letters have no VML form). + let mut tb_style = match body.vert { + craft_wordmodel::props::TextVert::Vert => vec!["layout-flow:vertical"], + craft_wordmodel::props::TextVert::Vert270 => vec!["layout-flow:vertical", "mso-layout-flow-alt:bottom-to-top"], + craft_wordmodel::props::TextVert::Horz | craft_wordmodel::props::TextVert::Stacked => Vec::new(), + }; if body.auto_fit { - tb.push(("style", "mso-fit-shape-to-text:t")); + tb_style.push("mso-fit-shape-to-text:t"); + } + let tb_style = tb_style.join(";"); + if !tb_style.is_empty() { + tb.push(("style", &tb_style)); } w.open("v:textbox", &tb); w.raw(content); diff --git a/crates/docx/tests/it/wps_fallback.rs b/crates/docx/tests/it/wps_fallback.rs index ed9d36555..c22a31b4e 100644 --- a/crates/docx/tests/it/wps_fallback.rs +++ b/crates/docx/tests/it/wps_fallback.rs @@ -1,11 +1,12 @@ //! Word 2010 shapes (`wps:wsp`) are written inside `mc:AlternateContent` with a VML fallback //! (ECMA-376 Part 3, Markup Compatibility; Part 4 §14.1, VML), so a reader that doesn't know //! `wps` — Word 2007, or Word 2000-2003 with the Office Compatibility Pack — takes the fallback -//! or skips the shape instead of refusing the whole file. +//! instead of refusing the whole file. A shape with no VML form is left bare. use std::io::Read; use craft_wordmodel::para::{Anchor, FloatAlign, ShapeKind, Wrap}; +use craft_wordmodel::props::TextVert; use craft_wordmodel::{Document, InlineObject, PartKind, TextBody, para_block}; fn document_xml(bytes: &[u8]) -> String { @@ -46,7 +47,11 @@ fn a_text_box_gets_a_vml_fallback_with_its_text() { let mut d = Document::from_text("a"); let id = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("29", Default::default()))]); d.parts.get_mut(&id).unwrap().body = TextBody { auto_fit: true, inset: Some([0; 4]), ..Default::default() }; - d.insert_object(&craft_wordmodel::Pos::body(0, 1), shape(ShapeKind::TextBox, Some(id)), &Default::default()).unwrap(); + let mut o = shape(ShapeKind::TextBox, Some(id)); + if let InlineObject::Shape { float, .. } = &mut o { + (float.dist, float.dist_top, float.dist_bottom) = (18.0, 12.0, 6.0); + } + d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap(); let bytes = craft_docx::write(&d).unwrap(); let xml = document_xml(&bytes); assert!(xml.contains(r#""#), "{xml}"); @@ -58,6 +63,7 @@ fn a_text_box_gets_a_vml_fallback_with_its_text() { "mso-position-horizontal:right", "mso-position-horizontal-relative:margin", "mso-position-vertical-relative:text", + "mso-wrap-distance-left:18.00pt;mso-wrap-distance-right:18.00pt;mso-wrap-distance-top:12.00pt;mso-wrap-distance-bottom:6.00pt", r#"filled="f""#, r#"stroked="f""#, r#""#, @@ -76,16 +82,46 @@ fn a_text_box_gets_a_vml_fallback_with_its_text() { assert_eq!(r.plain_text(craft_wordmodel::StoryRef::Part(boxes[0])), "29"); } -/// A shape VML has no simple form for is still guarded, with no fallback: an old reader skips it. +/// The fallback keeps the box's own stacking order (not that of a floating object inside it), +/// its hidden flag and its text direction. #[test] -fn a_shape_without_a_vml_form_is_guarded_without_a_fallback() { +fn the_fallback_keeps_order_visibility_and_direction() { + let mut d = Document::from_text("a"); + let inner = d.add_part(PartKind::TextBox, vec![para_block(craft_wordmodel::Paragraph::with_text("inner", Default::default()))]); + let mut nested = shape(ShapeKind::TextBox, Some(inner)); + if let InlineObject::Shape { float, .. } = &mut nested { + float.z = 100; + } + let mut p = craft_wordmodel::Paragraph::with_text("outer", Default::default()); + p.insert_object(0, nested, &Default::default()).unwrap(); + let outer = d.add_part(PartKind::TextBox, vec![para_block(p)]); + d.parts.get_mut(&outer).unwrap().body = TextBody { vert: TextVert::Vert270, ..Default::default() }; + let mut o = shape(ShapeKind::TextBox, Some(outer)); + if let InlineObject::Shape { float, .. } = &mut o { + float.z = 10; + float.hidden = true; + } + d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap(); + let xml = document_xml(&craft_docx::write(&d).unwrap()); + // The outer box's VML: the `v:rect` holding the vertical text box (the inner box's fallback + // 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(""#), "{xml}"); - assert!(xml.contains(""), "{xml}"); - assert!(!xml.contains(""), "{xml}"); - let r = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains("") && xml.contains(r#""#), "{xml}"); + assert!(!xml.contains(""), "{xml}"); + let r = craft_docx::read(&bytes).unwrap(); let mut kinds = Vec::new(); r.objects_in_reading_order(&mut |o| { if let InlineObject::Shape { kind, .. } = o { From 5033f10bf2127693d2d56fda2d86ffb6d4b46758 Mon Sep 17 00:00:00 2001 From: Andy Ching <53651198+andyching168@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:51:31 +0800 Subject: [PATCH 3/3] craft-docx: keep behind-text shapes' order in the VML fallback A behind-text shape's fallback `z-index` was the negated `z`, which reverses the order of overlapping behind-text shapes. It is now `z` shifted below zero within signed 32-bit range, so a higher `z` still stacks higher; other shapes' `z-index` is capped at `i32::MAX`. --- crates/docx/src/write/story/object.rs | 8 +++++--- crates/docx/tests/it/wps_fallback.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/docx/src/write/story/object.rs b/crates/docx/src/write/story/object.rs index 6b73aacd8..820b85ee7 100644 --- a/crates/docx/src/write/story/object.rs +++ b/crates/docx/src/write/story/object.rs @@ -442,9 +442,11 @@ impl Writer<'_> { (false, false) => {} } if float.wrap != Wrap::Inline { - // The stacking order the choice was given; behind the text is below it. - let z = i64::from(z); - style.push(format!("z-index:{}", if float.wrap == Wrap::BehindText { -z } else { z })); + // The stacking order the choice was given, as a signed 32-bit `z-index`. Behind the text + // is negative, shifted down rather than negated, so a higher `z` still stacks higher. + let z = i64::from(z.min(i32::MAX as u32)); + let z = if float.wrap == Wrap::BehindText { z - (i64::from(i32::MAX) + 1) } else { z }; + style.push(format!("z-index:{z}")); // The same clearances from the text as the choice's `distL`/`distR`/`distT`/`distB`. let d = pt(float.dist.clamp(0.0, 1584.0)); style.push(format!("mso-wrap-distance-left:{d}")); diff --git a/crates/docx/tests/it/wps_fallback.rs b/crates/docx/tests/it/wps_fallback.rs index c22a31b4e..e2d960cf9 100644 --- a/crates/docx/tests/it/wps_fallback.rs +++ b/crates/docx/tests/it/wps_fallback.rs @@ -111,6 +111,32 @@ fn the_fallback_keeps_order_visibility_and_direction() { assert!(rect.contains("visibility:hidden"), "{rect}"); } +/// Shapes behind the text keep their order in the fallback: a higher `z` stacks higher, below +/// the text (a negative `z-index` in signed 32-bit range). +#[test] +fn behind_text_shapes_keep_their_order() { + let mut d = Document::from_text("a"); + for z in [10, 20, u32::MAX] { + let mut o = shape(ShapeKind::Rectangle, None); + if let InlineObject::Shape { float, .. } = &mut o { + float.wrap = Wrap::BehindText; + float.z = z; + } + d.insert_object(&craft_wordmodel::Pos::body(0, 1), o, &Default::default()).unwrap(); + } + let xml = document_xml(&craft_docx::write(&d).unwrap()); + let mut got: Vec = xml + .match_indices("z-index:") + .map(|(i, m)| { + let v = &xml[i + m.len()..]; + v[..v.find([';', '"']).unwrap()].parse().unwrap() + }) + .collect(); + got.sort_unstable(); + let low = -(1i64 << 31); + assert_eq!(got, vec![low + 10, low + 20, -1], "{xml}"); +} + /// A shape VML has no simple form for stays a bare `wps:wsp`: guarded without a fallback, an old /// reader would open the file without it and drop it on its next save. #[test]