craft-docx: read a DrawingML locked canvas as a group of its members

Word 2007 writes shapes, pictures and WordArt in a drawing as an
lc:lockedCanvas (ECMA-376 Part 1 20.3.2.1) in compatibility mode. Only
its first picture was read; its shapes and their text were dropped. The
canvas is now rewritten as the wpg group the reader already handles,
its DrawingML text as text-box paragraphs with their run formatting.

Moved from storytold/wordcraft#5067 (wordcraft#5060), whose DOCX reader
now lives here.
This commit is contained in:
Diego Guerini committed 2026-11-15 18:01:57 +01:00
1 parent c376774f15
commit 6fde933469
6 files changed
+406 -1

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ use craft_wordmodel::wordart::TextWarp;
mod blocks;
mod drawing;
mod fields;
mod locked_canvas;
mod runs;
mod vml;
+4
View File
@@ -82,6 +82,10 @@ impl Reader<'_> {
self.read_canvas(sc, c, rels, w, h, float)
} else if let Some(g) = gd.child("wpg:wgp") {
self.read_group(sc, g, rels, w, h, float)?
} else if let Some(lc) = gd.child("lc:lockedCanvas") {
// Word 2007's shapes, pictures and text in a drawing: read as the group they are.
let g = super::locked_canvas::as_group(lc, &self.doc.settings.theme_colors);
self.read_group(sc, &g, rels, w, h, float)?
} else if direct_shape.is_none() && gd.find("a:blip").is_some() {
self.read_pic(gd, rels, w, h, alt.clone(), float)?
} else {
+254
View File
@@ -0,0 +1,254 @@
//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1): the shapes,
//! pictures and text Word 2007 writes in a drawing in compatibility mode (wordcraft#5060). It is a group
//! shape in the DrawingML namespace (`a:sp`, `a:pic`, `a:grpSp`, `a:cxnSp`, text in `a:txSp`), so
//! it is read as the `wpg:wgp` group the reader already knows: each member renamed into its
//! WordprocessingML drawing form, and its DrawingML text into `w:txbxContent` paragraphs.
use super::{El, Node, Rgb};
/// Groups nested deeper than this are left out, as `group_members` does.
const MAX_NEST: usize = 8;
/// DrawingML's text size when neither the run nor the list style gives one (18 pt, in
/// hundredths of a point).
const DEFAULT_SZ: i64 = 1800;
/// The locked canvas `lc` as a `wpg:wgp` group. `theme` resolves its text colours.
pub(super) fn as_group(lc: &El, theme: &[Rgb]) -> El {
el("wpg:wgp", Vec::new(), members(lc, theme, 0))
}
/// The members of DrawingML group `g`, in their WordprocessingML drawing form.
fn members(g: &El, theme: &[Rgb], depth: usize) -> Vec<Node> {
g.els()
.filter_map(|e| match e.name.as_str() {
"a:grpSpPr" => Some(renamed(e, "wpg:grpSpPr")),
"a:grpSp" if depth < MAX_NEST => Some(el("wpg:grpSp", Vec::new(), members(e, theme, depth + 1))),
"a:sp" => Some(shape(e, theme)),
"a:cxnSp" => Some(connector(e)),
"a:pic" => Some(picture(e)),
"a:txSp" => Some(text_shape(e, theme)),
_ => None,
})
.map(Node::El)
.collect()
}
/// `a:sp` as `wps:wsp`: its name, properties and style, and its text as a text box's.
fn shape(sp: &El, theme: &[Rgb]) -> El {
let nv = sp.child("a:nvSpPr");
let mut kids: Vec<Node> = [
nv.and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")),
nv.and_then(|n| n.child("a:cNvSpPr")).map(|e| renamed(e, "wps:cNvSpPr")),
sp.child("a:spPr").map(|e| renamed(e, "wps:spPr")),
sp.child("a:style").map(|e| renamed(e, "wps:style")),
]
.into_iter()
.flatten()
.map(Node::El)
.collect();
// The text sits in the shape's own rectangle (`a:useSpRect`); a text rectangle of its own
// (`a:txSp/a:xfrm`) is not kept apart.
if let Some(body) = sp.child("a:txSp").and_then(|t| t.child("a:txBody")) {
kids.extend(text_box(body, theme));
}
el("wps:wsp", Vec::new(), kids)
}
/// A group's text shape (`a:txSp` as a member, text with no shape of its own) as a `wps:wsp` text
/// box without fill or outline at its own rectangle (`a:xfrm`).
fn text_shape(tx: &El, theme: &[Rgb]) -> El {
let none = || Node::El(el("a:noFill", Vec::new(), Vec::new()));
let geometry = el("a:prstGeom", attrs(&[("prst", "rect")]), vec![Node::El(el("a:avLst", Vec::new(), Vec::new()))]);
let mut sp_pr: Vec<Node> = tx.child("a:xfrm").map(|x| Node::El(x.clone())).into_iter().collect();
sp_pr.extend([Node::El(geometry), none(), Node::El(el("a:ln", Vec::new(), vec![none()]))]);
let mut kids = vec![Node::El(el("wps:cNvSpPr", attrs(&[("txBox", "1")]), Vec::new())), Node::El(el("wps:spPr", Vec::new(), sp_pr))];
if let Some(body) = tx.child("a:txBody") {
kids.extend(text_box(body, theme));
}
el("wps:wsp", Vec::new(), kids)
}
/// DrawingML text body `body` as a text box's content and body properties.
fn text_box(body: &El, theme: &[Rgb]) -> Vec<Node> {
let content = el("w:txbxContent", Vec::new(), paragraphs(body, theme));
let mut kids = vec![Node::El(el("wps:txbx", Vec::new(), vec![Node::El(content)]))];
if let Some(bp) = body.child("a:bodyPr") {
kids.push(Node::El(renamed(bp, "wps:bodyPr")));
}
kids
}
/// `a:cxnSp` as a `wps:wsp` line. Its glued ends name shapes by the canvas's own ids, which
/// aren't the document's, so they are left out.
fn connector(cx: &El) -> El {
let kids = [
cx.child("a:nvCxnSpPr").and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")),
cx.child("a:spPr").map(|e| renamed(e, "wps:spPr")),
cx.child("a:style").map(|e| renamed(e, "wps:style")),
];
el("wps:wsp", Vec::new(), kids.into_iter().flatten().map(Node::El).collect())
}
/// `a:pic` as `pic:pic`.
fn picture(pic: &El) -> El {
let nv = pic.child("a:nvPicPr").and_then(|n| n.child("a:cNvPr")).map(|e| el("pic:nvPicPr", Vec::new(), vec![Node::El(renamed(e, "pic:cNvPr"))]));
let kids = [nv, pic.child("a:blipFill").map(|e| renamed(e, "pic:blipFill")), pic.child("a:spPr").map(|e| renamed(e, "pic:spPr"))];
el("pic:pic", Vec::new(), kids.into_iter().flatten().map(Node::El).collect())
}
/// The paragraphs of DrawingML text body `body` as `w:p`s. DrawingML text has no space before
/// or after a paragraph and single lines, so each says so rather than taking the document's
/// defaults.
fn paragraphs(body: &El, theme: &[Rgb]) -> Vec<Node> {
body.children("a:p")
.map(|p| {
// A run's properties default to its paragraph's own (`a:pPr/a:defRPr`), then to the
// list style's for the paragraph's level (`lvl`, 0–8), property by property.
let ppr_el = p.child("a:pPr");
let level = ppr_el.and_then(|pp| pp.attr("lvl")).and_then(|v| v.trim().parse::<u8>().ok()).filter(|l| *l <= 8).unwrap_or(0);
let level_style = body.child("a:lstStyle").and_then(|l| l.child(&format!("a:lvl{}pPr", level + 1)));
let defaults: Vec<&El> =
[ppr_el.and_then(|pp| pp.child("a:defRPr")), level_style.and_then(|l| l.child("a:defRPr"))].into_iter().flatten().collect();
let defaults = defaults.as_slice();
let mut ppr =
vec![Node::El(el("w:spacing", attrs(&[("w:before", "0"), ("w:after", "0"), ("w:line", "240"), ("w:lineRule", "auto")]), Vec::new()))];
let jc = match ppr_el.and_then(|pp| pp.attr("algn")) {
Some("ctr") => Some("center"),
Some("r") => Some("right"),
Some("just") => Some("both"),
Some("dist") => Some("distribute"),
Some("l") => Some("left"),
_ => None,
};
if let Some(jc) = jc {
ppr.push(Node::El(el("w:jc", attrs(&[("w:val", jc)]), Vec::new())));
}
// The paragraph mark's own size and font (`a:endParaRPr`), which an empty one's
// height follows.
ppr.push(Node::El(run_props(p.child("a:endParaRPr"), defaults, theme)));
let mut kids = vec![Node::El(el("w:pPr", Vec::new(), ppr))];
for r in p.els() {
let text = match r.name.as_str() {
"a:r" | "a:fld" => Node::El(el(
"w:t",
attrs(&[("xml:space", "preserve")]),
vec![Node::Text(r.child("a:t").map(|t| t.text()).unwrap_or_default())],
)),
"a:br" => Node::El(el("w:br", Vec::new(), Vec::new())),
_ => continue,
};
let rpr = run_props(r.child("a:rPr"), defaults, theme);
kids.push(Node::El(el("w:r", Vec::new(), vec![Node::El(rpr), text])));
}
Node::El(el("w:p", Vec::new(), kids))
})
.collect()
}
/// A DrawingML run's properties (`a:rPr`, each falling back on the first of `defaults`, the
/// `a:defRPr`s in order, that gives it) as `w:rPr`: font, size, bold, italic, underline,
/// strikethrough, caps, baseline and colour.
fn run_props(rpr: Option<&El>, defaults: &[&El], theme: &[Rgb]) -> El {
let get = |n: &str| rpr.and_then(|r| r.attr(n)).or_else(|| defaults.iter().find_map(|d| d.attr(n)));
let child = |n: &str| rpr.and_then(|r| r.child(n)).or_else(|| defaults.iter().find_map(|d| d.child(n)));
let on = |n: &str| get(n).is_some_and(|v| v == "1" || v == "true");
let mut kids = Vec::new();
let mut push = |name: &str, a: &[(&str, &str)]| kids.push(Node::El(el(name, attrs(a), Vec::new())));
// Theme fonts (`+mn-lt`) are left to the document's.
let face = |n: &str| child(n).and_then(|f| f.attr("typeface")).filter(|t| !t.is_empty() && !t.starts_with('+'));
let mut fonts = Vec::new();
if let Some(f) = face("a:latin") {
fonts.extend([("w:ascii", f), ("w:hAnsi", f)]);
}
if let Some(f) = face("a:ea") {
fonts.push(("w:eastAsia", f));
}
if let Some(f) = face("a:cs") {
fonts.push(("w:cs", f));
}
if !fonts.is_empty() {
push("w:rFonts", &fonts);
}
if on("b") {
push("w:b", &[]);
}
if on("i") {
push("w:i", &[]);
}
match get("cap") {
Some("all") => push("w:caps", &[]),
Some("small") => push("w:smallCaps", &[]),
_ => {}
}
match get("strike") {
Some("sngStrike") => push("w:strike", &[]),
Some("dblStrike") => push("w:dstrike", &[]),
_ => {}
}
match get("u") {
None | Some("none") => {}
Some("dbl") => push("w:u", &[("w:val", "double")]),
Some(_) => push("w:u", &[("w:val", "single")]),
}
match get("baseline").and_then(|v| v.trim().parse::<i64>().ok()) {
Some(b) if b > 0 => push("w:vertAlign", &[("w:val", "superscript")]),
Some(b) if b < 0 => push("w:vertAlign", &[("w:val", "subscript")]),
_ => {}
}
if let Some(rgb) = child("a:solidFill").and_then(|f| crate::read::drawing_color::color(f, theme)) {
push("w:color", &[("w:val", &rgb.hex())]);
}
// Hundredths of a point into half-points, within Word's 1–1638 pt.
let sz = get("sz").and_then(|v| v.trim().parse::<i64>().ok()).unwrap_or(DEFAULT_SZ).clamp(100, 163_800) / 50;
let sz = sz.to_string();
push("w:sz", &[("w:val", &sz)]);
push("w:szCs", &[("w:val", &sz)]);
// WordArt's outline, shadow, glow and reflection, as Word 2010 writes them in `w:rPr`.
kids.extend(text_effects(child("a:ln"), child("a:effectLst"), theme).into_iter().map(Node::El));
el("w:rPr", Vec::new(), kids)
}
/// A DrawingML run's text outline (`a:ln`) and effects (`a:effectLst`: outer shadow, glow,
/// reflection) as the `w14:` run properties ([MS-DOCX] §2.6.1) the run reader takes for WordArt.
/// Colours are resolved here, theme and modifiers included, into a `w14:srgbClr` with its
/// transparency. Lengths (EMUs), angles and percentages carry over as they are.
fn text_effects(ln: Option<&El>, fx: Option<&El>, theme: &[Rgb]) -> Vec<El> {
let color = |e: &El| -> Option<Node> {
let (rgb, transparency) = crate::read::drawing_color::color_alpha(e, theme, None)?;
let alpha = ((transparency.clamp(0.0, 100.0) * 1000.0).round() as i64).to_string();
let kids = if transparency > 0.0 { vec![Node::El(el("w14:alpha", attrs(&[("w14:val", &alpha)]), Vec::new()))] } else { Vec::new() };
Some(Node::El(el("w14:srgbClr", attrs(&[("w14:val", &rgb.hex())]), kids)))
};
// The attributes `names` of `e`, under the `w14:` prefix.
let copied = |e: &El, names: &[&str]| -> Vec<(String, String)> {
names.iter().filter_map(|n| e.attr(n).map(|v| (format!("w14:{n}"), v.to_string()))).collect()
};
let mut out = Vec::new();
if let Some(ln) = ln
&& let Some(c) = ln.child("a:solidFill").and_then(color)
{
out.push(el("w14:textOutline", copied(ln, &["w"]), vec![Node::El(el("w14:solidFill", Vec::new(), vec![c]))]));
}
for e in fx.into_iter().flat_map(|f| f.els()) {
match e.name.as_str() {
"a:outerShdw" => out.push(el("w14:shadow", copied(e, &["blurRad", "dist", "dir"]), color(e).into_iter().collect())),
"a:glow" => out.push(el("w14:glow", copied(e, &["rad"]), color(e).into_iter().collect())),
"a:reflection" => out.push(el("w14:reflection", copied(e, &["blurRad", "stA", "endPos", "dist"]), Vec::new())),
_ => {}
}
}
out
}
fn el(name: &str, attrs: Vec<(String, String)>, kids: Vec<Node>) -> El {
El { name: name.to_string(), attrs, kids }
}
fn attrs(a: &[(&str, &str)]) -> Vec<(String, String)> {
a.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
}
/// `e` under another name, with its attributes and children.
fn renamed(e: &El, name: &str) -> El {
El { name: name.to_string(), ..e.clone() }
}
+3 -1
View File
@@ -52,8 +52,10 @@ pub const NAMESPACES: &[(&str, &str)] = &[
pub const DECORATIVE_EXT: &str = "{C183D7F6-B498-43B3-948B-1728B52AA6E4}";
pub const DECORATIVE_NS: &str = "http://schemas.microsoft.com/office/drawing/2017/decorative";
/// Namespaces that only appear in non-body parts.
/// Namespaces that only appear in non-body parts, or that the reader reads but never writes.
const OTHER_NAMESPACES: &[(&str, &str)] = &[
// A locked canvas, read into a drawing group (wordcraft#5060).
("lc", "http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"),
("b", "http://schemas.openxmlformats.org/officeDocument/2006/bibliography"),
("rel", "http://schemas.openxmlformats.org/package/2006/relationships"),
("ct", "http://schemas.openxmlformats.org/package/2006/content-types"),
+143
View File
@@ -0,0 +1,143 @@
//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1), as Word 2007 writes
//! shapes, pictures and WordArt in a drawing in compatibility mode (wordcraft#5060). Fixtures are
//! hand-written from ECMA-376 Part 1 §20.1 (DrawingML main) and §20.3 (locked canvas).
use std::io::Write;
use craft_wordmodel::para::ShapeKind;
use craft_wordmodel::props::{Rgb, TextColor};
use craft_wordmodel::{Document, InlineObject, StoryRef};
const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#;
fn docx(body: &str) -> Vec<u8> {
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document {NS}><w:body>{body}</w:body></w:document>"#);
let types =
r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="png" ContentType="image/png"/></Types>"#;
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.png"/></Relationships>"#;
let entries: [(&str, &[u8]); 5] = [
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", root.as_bytes()),
("word/document.xml", doc.as_bytes()),
("word/_rels/document.xml.rels", rels.as_bytes()),
("word/media/image1.png", "\u{89}PNG stand-in".as_bytes()),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, bytes) in entries {
zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(bytes).unwrap();
}
zw.finish().unwrap().into_inner()
}
/// A floating drawing, 200 × 100 pt, holding `canvas` (the locked canvas's members) in a canvas
/// whose members' space starts at 10 pt, 10 pt.
fn drawing(canvas: &str) -> String {
format!(
r#"<w:p><w:r><w:drawing><wp:anchor behindDoc="0" distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" locked="0" layoutInCell="1" allowOverlap="1"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="2540000" cy="1270000"/><wp:wrapNone/><wp:docPr id="1" name="Object 1"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"><lc:lockedCanvas xmlns:lc="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"><a:nvGrpSpPr><a:cNvPr id="0" name=""/><a:cNvGrpSpPr/></a:nvGrpSpPr><a:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="2540000" cy="1270000"/><a:chOff x="127000" y="127000"/><a:chExt cx="2540000" cy="1270000"/></a:xfrm></a:grpSpPr>{canvas}</lc:lockedCanvas></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>"#
)
}
const OVAL: &str = r#"<a:sp><a:nvSpPr><a:cNvPr id="2" name="Oval 2"/><a:cNvSpPr/></a:nvSpPr><a:spPr><a:xfrm><a:off x="127000" y="127000"/><a:ext cx="1270000" cy="635000"/></a:xfrm><a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="FFFF66"/></a:solidFill><a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></a:spPr></a:sp>"#;
/// WordArt in a nested group: bold, all-caps red text with a green outline and a reflection,
/// 32 pt, centred, bent by a chevron warp; a second paragraph takes the list style's size, and an
/// empty third one its mark's.
const WORD_ART: &str = r#"<a:grpSp><a:nvGrpSpPr><a:cNvPr id="3" name="Group 3"/><a:cNvGrpSpPr/></a:nvGrpSpPr><a:grpSpPr><a:xfrm><a:off x="1397000" y="762000"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="2540000" cy="1270000"/></a:xfrm></a:grpSpPr><a:sp><a:nvSpPr><a:cNvPr id="4" name="Rectangle 4"/><a:cNvSpPr/></a:nvSpPr><a:spPr><a:xfrm><a:off x="254000" y="254000"/><a:ext cx="508000" cy="254000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></a:spPr><a:txSp><a:txBody><a:bodyPr wrap="square"><a:prstTxWarp prst="textChevron"><a:avLst/></a:prstTxWarp><a:spAutoFit/></a:bodyPr><a:lstStyle><a:lvl1pPr><a:defRPr sz="1400"/></a:lvl1pPr></a:lstStyle><a:p><a:pPr algn="ctr"/><a:r><a:rPr lang="en-US" sz="3200" b="1" cap="all"><a:ln w="9525"><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill></a:ln><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:effectLst><a:reflection blurRad="12700" stA="28000" endPos="45000" dist="1000" dir="5400000"/></a:effectLst><a:latin typeface="Corsiva Stand-in"/></a:rPr><a:t>Young</a:t></a:r></a:p><a:p><a:r><a:rPr lang="en-US"/><a:t>keepers</a:t></a:r></a:p><a:p><a:endParaRPr lang="en-US" sz="1000"/></a:p></a:txBody><a:useSpRect/></a:txSp></a:sp></a:grpSp>"#;
const PICTURE: &str = r#"<a:pic><a:nvPicPr><a:cNvPr id="5" name="Picture 5" descr="A logo"/><a:cNvPicPr/></a:nvPicPr><a:blipFill><a:blip r:embed="rId8"/><a:stretch><a:fillRect/></a:stretch></a:blipFill><a:spPr><a:xfrm><a:off x="127000" y="762000"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></a:spPr></a:pic>"#;
/// A line glued to the oval by the canvas's own id, which isn't a document shape's.
const LINE: &str = r#"<a:cxnSp><a:nvCxnSpPr><a:cNvPr id="6" name="Line 6"/><a:cNvCxnSpPr><a:stCxn id="2" idx="0"/></a:cNvCxnSpPr></a:nvCxnSpPr><a:spPr><a:xfrm><a:off x="127000" y="1143000"/><a:ext cx="2540000" cy="0"/></a:xfrm><a:prstGeom prst="line"><a:avLst/></a:prstGeom><a:ln w="12700"><a:solidFill><a:srgbClr val="0000FF"/></a:solidFill></a:ln></a:spPr></a:cxnSp>"#;
fn group(d: &Document) -> (f32, f32, Vec<craft_wordmodel::para::GroupChild>) {
let p = d.body.iter().find_map(|b| b.as_para()).unwrap();
match p.objects.first() {
Some(InlineObject::Group { w, h, children, canvas: None, .. }) => (*w, *h, children.clone()),
o => panic!("{o:?}"),
}
}
/// wordcraft#5060: the locked canvas is a group of its shapes, text, picture and line, each where the
/// canvas (and the group inside it) puts it, and nothing is lost on save.
#[test]
fn a_locked_canvas_reads_as_a_group_of_its_members() {
let d = craft_docx::read(&docx(&drawing(&[OVAL, WORD_ART, PICTURE, LINE].concat()))).unwrap();
for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] {
let (w, h, children) = group(d);
assert_eq!((w, h), (200.0, 100.0));
let at: Vec<(f32, f32)> = children.iter().map(|c| (c.x, c.y)).collect();
assert_eq!(at, [(0.0, 0.0), (110.0, 60.0), (0.0, 50.0), (0.0, 80.0)]);
let [oval, art, picture, line] = &children[..] else { panic!("{children:?}") };
let InlineObject::Shape { kind: ShapeKind::Ellipse, w: 100.0, h: 50.0, fill: Some(fill), stroke: Some(stroke), .. } = &oval.obj else {
panic!("{:?}", oval.obj)
};
assert_eq!((fill.main_color(), *stroke), (Rgb(0xFF, 0xFF, 0x66), Rgb(0, 0, 0)));
let InlineObject::Shape { kind: ShapeKind::TextBox, w: 20.0, h: 10.0, story: Some(id), extra, .. } = &art.obj else {
panic!("{:?}", art.obj)
};
assert_eq!(extra.warp.as_ref().map(|w| w.preset.as_str()), Some("textChevron"));
assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Young\nkeepers");
let blocks = &d.parts.get(id).unwrap().blocks;
let first = blocks[0].as_para().unwrap();
assert_eq!(first.props.align, Some(craft_wordmodel::props::Align::Center));
assert_eq!((first.props.space_before, first.props.space_after), (Some(0.0), Some(0.0)), "DrawingML text has no paragraph spacing");
let run = &first.runs[0].props;
assert_eq!((run.size, run.bold, run.caps, run.color), (Some(32.0), Some(true), Some(true), Some(TextColor::Rgb(Rgb(0xFF, 0, 0)))));
assert_eq!(run.font.as_deref(), Some("Corsiva Stand-in"));
let fx = run.text_effects.as_deref().unwrap();
let outline = fx.outline.unwrap();
assert_eq!((outline.color, outline.width), (Some(Rgb(0, 0xFF, 0)), 0.75));
assert!(fx.reflection.is_some(), "{fx:?}");
assert_eq!(blocks[1].as_para().unwrap().runs[0].props.size, Some(14.0), "the list style's size");
assert_eq!(blocks[2].as_para().unwrap().mark.size, Some(10.0), "an empty paragraph's mark");
let InlineObject::Image { w: 50.0, h: 50.0, alt, .. } = &picture.obj else { panic!("{:?}", picture.obj) };
assert_eq!(alt, "A logo");
let InlineObject::Shape { kind: ShapeKind::Line, stroke: Some(blue), extra, .. } = &line.obj else { panic!("{:?}", line.obj) };
assert_eq!((*blue, extra.start), (Rgb(0, 0, 0xFF), None), "no glue to a canvas id");
}
}
/// A text shape as a member of the canvas (`a:txSp`, text with no shape of its own) is a text box
/// at its own rectangle. Runs take their paragraph's own defaults (`a:pPr/a:defRPr`) before the
/// list style's for the paragraph's level.
#[test]
fn a_locked_canvas_text_shape_and_paragraph_defaults() {
let text = r#"<a:txSp><a:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1400" i="1"/></a:lvl1pPr><a:lvl2pPr><a:defRPr sz="2000"/></a:lvl2pPr></a:lstStyle><a:p><a:pPr><a:defRPr sz="3200"/></a:pPr><a:r><a:rPr lang="en-US"/><a:t>Own</a:t></a:r></a:p><a:p><a:pPr lvl="1"/><a:r><a:rPr lang="en-US"/><a:t>Level</a:t></a:r></a:p><a:p><a:r><a:rPr lang="en-US"/><a:t>First</a:t></a:r></a:p></a:txBody><a:useSpRect/><a:xfrm><a:off x="635000" y="381000"/><a:ext cx="1270000" cy="508000"/></a:xfrm></a:txSp>"#;
let d = craft_docx::read(&docx(&drawing(text))).unwrap();
for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] {
let (_, _, children) = group(d);
let [shape] = &children[..] else { panic!("{children:?}") };
assert_eq!((shape.x, shape.y), (40.0, 20.0));
let InlineObject::Shape { kind: ShapeKind::TextBox, w: 100.0, h: 40.0, fill: None, stroke: None, story: Some(id), .. } = &shape.obj else {
panic!("{:?}", shape.obj)
};
assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Own\nLevel\nFirst");
let blocks = &d.parts.get(id).unwrap().blocks;
let run = |i: usize| blocks[i].as_para().unwrap().runs[0].props.clone();
assert_eq!((run(0).size, run(0).italic), (Some(32.0), Some(true)), "the paragraph's own size, the level's italic");
assert_eq!((run(1).size, run(1).italic), (Some(20.0), None), "level 2's");
assert_eq!((run(2).size, run(2).italic), (Some(14.0), Some(true)), "level 1's");
}
}
/// Before wordcraft#5060 only the canvas's first picture showed: the shapes and their text were dropped.
#[test]
fn a_locked_canvas_is_not_read_as_its_picture_alone() {
let d = craft_docx::read(&docx(&drawing(&[OVAL, PICTURE].concat()))).unwrap();
let (_, _, children) = group(&d);
assert_eq!(children.len(), 2);
}
/// Hostile canvases never panic: no members, groups nested past the limit, text with no runs,
/// huge and broken sizes.
#[test]
fn hostile_locked_canvases_never_panic() {
let deep = format!("{}{}{}", r#"<a:grpSp><a:grpSpPr/>"#.repeat(40), OVAL, "</a:grpSp>".repeat(40));
let odd = r#"<a:sp><a:spPr/><a:txSp><a:txBody><a:p/><a:p><a:r><a:rPr sz="99999999999" baseline="x"/></a:r><a:br/><a:fld><a:t>f</a:t></a:fld></a:p></a:txBody></a:txSp></a:sp><a:pic/><a:cxnSp/><a:graphicFrame/>"#;
for canvas in ["", deep.as_str(), odd] {
let d = craft_docx::read(&docx(&drawing(canvas))).unwrap();
let _ = craft_docx::write(&d).unwrap();
}
}
+1
View File
@@ -23,6 +23,7 @@ mod heading_levels;
mod legacy_forms;
mod ligatures;
mod line_numbering;
mod locked_canvas;
mod malformed;
mod missing_pictures;
mod nested_block_controls;