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] 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 {