mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 15:55:14 +00:00
Merge pull request #1834 from andyching168/docx/wps-shape-vml-fallback
craft-docx: write Word 2010 shapes inside mc:AlternateContent with a VML fallback
This commit is contained in:
6 files changed
+365
-8
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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,16 @@ impl Writer<'_> {
|
||||
self.rev_open(w, props);
|
||||
w.open("w:r", &[]);
|
||||
self.rpr(w, props);
|
||||
// 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);
|
||||
@@ -384,18 +394,164 @@ 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")]);
|
||||
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");
|
||||
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, z, 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, 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));
|
||||
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, 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}"));
|
||||
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)));
|
||||
}
|
||||
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(),
|
||||
);
|
||||
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 {
|
||||
// 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));
|
||||
}
|
||||
// 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_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);
|
||||
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 +643,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",
|
||||
|
||||
@@ -49,3 +49,4 @@ mod undefined_style;
|
||||
mod vml_shapes;
|
||||
mod word_xml;
|
||||
mod wordml2003_write;
|
||||
mod wps_fallback;
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! 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
|
||||
//! 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 {
|
||||
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() };
|
||||
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#"<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",
|
||||
"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#"<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");
|
||||
}
|
||||
|
||||
/// 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 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#"<v:textbox style="layout-flow:vertical;mso-layout-flow-alt:bottom-to-top">"#).expect("the outer box's text, turned");
|
||||
let rect = &xml[xml[..tb].rfind("<v:rect ").expect("its v:rect")..tb];
|
||||
assert!(rect.contains("z-index:10;"), "{rect}");
|
||||
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<i64> = 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]
|
||||
fn a_shape_without_a_vml_form_is_not_guarded() {
|
||||
let mut d = Document::from_text("a");
|
||||
d.insert_object(&craft_wordmodel::Pos::body(0, 1), shape(ShapeKind::Star, None), &Default::default()).unwrap();
|
||||
let bytes = craft_docx::write(&d).unwrap();
|
||||
let xml = document_xml(&bytes);
|
||||
assert!(xml.contains("<w:r><w:drawing>") && xml.contains(r#"<a:prstGeom prst="star5">"#), "{xml}");
|
||||
assert!(!xml.contains("<mc:AlternateContent>"), "{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 {
|
||||
kinds.push(*kind);
|
||||
}
|
||||
});
|
||||
assert_eq!(kinds, vec![ShapeKind::Star]);
|
||||
}
|
||||
Reference in new issue
Block a user