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
This commit is contained in:
Andy Ching committed 2026-11-16 15:15:06 +08:00
1 parent 3a85d8b69a
commit 741192a57c
6 files changed
+275 -8

No files matched your search

+16 -3
View File
@@ -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<std::ops::Range<usize>> {
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.
+157 -2
View File
@@ -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",
+1
View File
@@ -49,3 +49,4 @@ mod undefined_style;
mod vml_shapes;
mod word_xml;
mod wordml2003_write;
mod wps_fallback;
+3 -2
View File
@@ -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("<w:txbxContent>").map(|(a, _)| (a, a + xml[a..].find("</w:txbxContent>").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<usize> = 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("</w:sdt>").unwrap(), "{xml}");
assert!(begin > boxes[1].1 && end > boxes[3].1 && end < xml.find("</w:sdt>").unwrap(), "{xml}");
}
#[test]
+2 -1
View File
@@ -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);
}
+96
View File
@@ -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<u32>) -> 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#"<mc:AlternateContent><mc:Choice Requires="wps"><w:drawing>"#), "{xml}");
assert!(!xml.contains("<w:r><w:drawing>"), "no bare Word 2010 shape: {xml}");
let fallback = &xml[xml.find("<mc:Fallback>").expect("a fallback")..];
assert!(fallback.starts_with("<mc:Fallback><w:pict><v:rect "), "{fallback}");
for want in [
"position:absolute",
"mso-position-horizontal:right",
"mso-position-horizontal-relative:margin",
"mso-position-vertical-relative:text",
r#"filled="f""#,
r#"stroked="f""#,
r#"<v:textbox inset="0.00pt,0.00pt,0.00pt,0.00pt" style="mso-fit-shape-to-text:t"><w:txbxContent>"#,
r#"<w10:wrap type="square"/></v:rect></w:pict></mc:Fallback></mc:AlternateContent>"#,
] {
assert!(fallback.contains(want), "{want} in {fallback}");
}
assert_eq!(xml.matches(">29</w:t>").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#"<mc:AlternateContent><mc:Choice Requires="wps"><w:drawing>"#), "{xml}");
assert!(xml.contains("</w:drawing></mc:Choice></mc:AlternateContent>"), "{xml}");
assert!(!xml.contains("<mc:Fallback>"), "{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]);
}