DOCX: an Office 2016 chart with a text-only fallback keeps its size as a placeholder

read_chartex_alternate built the chart object only from a picture fallback. With a fallback
that holds only text (for example "Chart not available."), it returned None and the reader
used the fallback words, so the chart's 432 x 252 pt frame was never reserved and the pages
collapsed.

Now such a chart becomes a Chart graphic of the choice's wp:extent, drawn as the same kind of
placeholder unsupported classic charts get (frame, title, chart type), with the choice and
fallback kept so saving writes them back unchanged. A fallback that holds runs or paragraphs
is still read as before, because the writer puts the fallback inside the object's own run.

The frame reading at the top of read_drawing moves into drawing_frame so both paths share it.

Part of storytold/wordcraft#6820

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Sonnet 5.5 committed 2026-11-16 02:04:08 +01:00
1 parent 58964adec1
commit e76bf4bad4
4 files changed
+192 -20

No files matched your search

+49 -1
View File
@@ -37,7 +37,7 @@ use parse::{axis, category_text, labels, numbers};
use parse::{read_series, text_size, title_of};
#[cfg(test)]
use plot::{Scale, narrow, nice_scale};
use plot::{backdrop, cartesian};
use plot::{backdrop, cartesian, label};
use polar::{pie, radar};
/// Most series read from one chart.
@@ -141,6 +141,54 @@ fn placeholder(out: &mut Vec<GraphicItem>, space: &El, theme: &[Rgb], w: f32, h:
text(out, line, &clip_text(&msg, area.w, size), size, TextAlign::Center, false);
}
/// Items for an Office 2016 chart (`cx:chartSpace`: waterfall, funnel, treemap…), sized `w` x `h`
/// points: none of these types is drawn yet, so this is the same placeholder an unsupported
/// classic chart gets (frame, title, the type it is), at the size the chart takes in Word.
/// `space` is `None` when the part can't be read: the frame and "Chart" are still drawn.
pub(crate) fn chartex_items(space: Option<&El>, w: f32, h: f32) -> Vec<GraphicItem> {
let mut out = Vec::new();
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
return out;
}
out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill: Some(Rgb::WHITE), stroke: Some(AXIS), stroke_width: 0.75 });
let mut area = Rect { x: PAD, y: PAD, w: (w - 2.0 * PAD).max(1.0), h: (h - 2.0 * PAD).max(1.0) };
let chart = space.and_then(|s| s.child("cx:chart"));
let title = chart.and_then(|c| c.child("cx:title")).and_then(|t| {
let mut s = String::new();
t.find_all("a:t").for_each(|r| s.push_str(&r.text()));
if s.is_empty() {
s = t.find("cx:v").map(|v| v.text().into_owned()).unwrap_or_default();
}
let s = label(s.trim());
(!s.is_empty()).then_some(s)
});
if let Some(t) = title {
area = title_block(&mut out, &t, area);
}
let kind = chart.and_then(|c| c.find("cx:series")).and_then(|s| s.attr("layoutId")).unwrap_or("");
let size = FONT;
let lh = size * LINE;
let msg = format!("{} (not supported yet)", chartex_name(kind));
let line = Rect { x: area.x, y: area.y + ((area.h - lh) / 2.0).max(0.0), w: area.w, h: lh };
text(&mut out, line, &clip_text(&msg, area.w, size), size, TextAlign::Center, false);
out
}
/// What a placeholder calls an Office 2016 chart type (`cx:series` `layoutId`).
fn chartex_name(layout: &str) -> &'static str {
match layout {
"waterfall" => "Waterfall chart",
"funnel" => "Funnel chart",
"treemap" => "Treemap chart",
"sunburst" => "Sunburst chart",
"boxWhisker" => "Box and whisker chart",
"clusteredColumn" => "Histogram chart",
"paretoLine" => "Pareto chart",
"regionMap" => "Map chart",
_ => "Chart",
}
}
/// What a placeholder calls a chart type element WordCraft doesn't draw.
fn unsupported_name(name: &str) -> &'static str {
match name {
+24
View File
@@ -899,3 +899,27 @@ fn source_linked_series_labels_do_not_inherit_the_chart_format() {
let inherited = run(r#"<c:dLbls><c:showVal val="1"/></c:dLbls>"#);
assert!(inherited.contains(&"320%".to_string()), "{inherited:?}");
}
#[test]
fn office_2016_chart_draws_a_placeholder_of_its_size() {
let cx = |series: &str, title: &str| {
let x = format!(
r#"<cx:chartSpace xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><cx:chart>{title}<cx:plotArea><cx:plotAreaRegion>{series}</cx:plotAreaRegion></cx:plotArea></cx:chart></cx:chartSpace>"#
);
crate::xml::parse(x.as_bytes()).unwrap()
};
let title = r#"<cx:title pos="t"><cx:tx><cx:txData><cx:v>Quarterly steps</cx:v></cx:txData></cx:tx></cx:title>"#;
let rich = r#"<cx:title><cx:tx><cx:rich><a:p><a:r><a:t>Sales </a:t></a:r><a:r><a:t>funnel</a:t></a:r></a:p></cx:rich></cx:tx></cx:title>"#;
let waterfall = chartex_items(Some(&cx(r#"<cx:series layoutId="waterfall"/>"#, title)), 432.0, 252.0);
assert_eq!(texts(&waterfall), ["Quarterly steps", "Waterfall chart (not supported yet)"]);
let framed = waterfall.iter().any(|it| matches!(it, GraphicItem::Shape { rect, stroke: Some(_), .. } if *rect == [0.0, 0.0, 432.0, 252.0]));
assert!(framed, "the frame has the chart's size: {waterfall:?}");
let funnel = chartex_items(Some(&cx(r#"<cx:series layoutId="funnel"/>"#, rich)), 300.0, 200.0);
assert_eq!(texts(&funnel), ["Sales funnel", "Funnel chart (not supported yet)"]);
let other = chartex_items(Some(&cx(r#"<cx:series layoutId="newKind"/>"#, "")), 300.0, 200.0);
assert_eq!(texts(&other), ["Chart (not supported yet)"]);
// An unreadable part still reserves and frames the chart's place.
let missing = chartex_items(None, 300.0, 200.0);
assert_eq!(texts(&missing), ["Chart (not supported yet)"]);
assert!(chartex_items(None, 0.0, 200.0).is_empty() && chartex_items(None, f32::NAN, 200.0).is_empty());
}
+60 -19
View File
@@ -12,23 +12,7 @@ impl Reader<'_> {
/// text and drawing ids are carried into the object. Returns `None` when the frame or payload
/// cannot be read. Ink written by WordCraft keeps its tool's caps rather than an outline cap.
pub(super) fn read_drawing(&mut self, sc: &mut StoryCtx, d: &El, rels: &Rels) -> Option<InlineObject> {
let (c, anchored) = match d.child("wp:inline") {
Some(c) => (c, false),
None => (d.child("wp:anchor")?, true),
};
let ext = c.child("wp:extent");
let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
let (w, h) = (dim("cx"), dim("cy"));
let (alt, meta) = nv_alt(c.child("wp:docPr"));
let mut float = if anchored { anchor_float(c) } else { Float::default() };
float.alt = meta;
float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden"));
if let Some(e) = c.child("wp:effectExtent") {
for (slot, n) in float.effect.iter_mut().zip(["l", "t", "r", "b"]) {
// Negative for a rotated object narrower than its frame; settled below.
*slot = e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(-1584.0, 1584.0);
}
}
let Frame { c, anchored, w, h, alt, mut float } = drawing_frame(d)?;
let gd = c.child("a:graphic").and_then(|g| g.child("a:graphicData"))?;
// Checked by URI before the blip search: a diagram's data can hold a blip further down.
let uri = gd.attr("uri").unwrap_or("");
@@ -188,14 +172,39 @@ impl Reader<'_> {
let fallback = ac.child("mc:Fallback")?;
let kept = El { name: "mc:AlternateContent".into(), attrs: Vec::new(), kids: vec![Node::El(choice.clone()), Node::El(fallback.clone())] };
let source = self.keep_embedded(&kept, rels, &[])?;
let Some(InlineObject::Image { media, w, h, alt, float, .. }) = self.read_drawing(sc, fallback.child("w:drawing")?, rels) else {
return None;
let picture = fallback.child("w:drawing").and_then(|d| self.read_drawing(sc, d, rels));
let Some(InlineObject::Image { media, w, h, alt, float, .. }) = picture else {
return self.chartex_placeholder(choice, fallback, rels, source);
};
let items = vec![GraphicItem::Image { rect: [0.0, 0.0, w, h], media }];
let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() });
Some(InlineObject::Graphic { w, h, alt, float, graphic })
}
/// An Office 2016 chart whose fallback holds no picture (only text, say "Chart not
/// available"): a placeholder of the chart's own size (the `wp:extent` of its `mc:Choice`),
/// so the page breaks where they do with the chart drawn. The fallback is written back as it
/// was. `None` when the fallback has a picture or another drawing (read as before), or
/// holds runs or paragraphs, which a writer can't put inside the run that holds the object.
fn chartex_placeholder(&mut self, choice: &El, fallback: &El, rels: &Rels, source: Arc<Embedded>) -> Option<InlineObject> {
const RUN_CONTENT: [&str; 6] = ["w:t", "w:tab", "w:br", "w:cr", "w:noBreakHyphen", "w:softHyphen"];
if fallback.find("a:graphic").is_some() || !fallback.els().all(|e| RUN_CONTENT.contains(&e.name.as_str())) {
return None;
}
let Frame { c, w, h, alt, mut float, .. } = drawing_frame(choice.child("w:drawing")?)?;
let part = c
.child("a:graphic")
.and_then(|g| g.child("a:graphicData"))
.and_then(|gd| gd.child("cx:chart"))
.and_then(|cx| cx.attr("r:id"))
.and_then(|id| crate::read::part_of(rels, id, "chartEx"));
let space = part.and_then(|p| self.graphic_part(&p));
let items = crate::read::chart::chartex_items(space.as_deref(), w, h);
float.effect = float.effect.map(|e| e.max(0.0));
let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() });
Some(InlineObject::Graphic { w, h, alt, float, graphic })
}
/// A group or canvas member that is native ink (`content`, a `w14:contentPart`, inside
/// `alternate` when it has a picture fallback): what to write back (the whole alternate when
/// it can be kept, else the ink alone) and its fallback picture (a `Document::media` key).
@@ -598,6 +607,38 @@ impl Reader<'_> {
}
}
/// The frame of a `w:drawing`: its `wp:inline` or `wp:anchor` element, the size in points,
/// the alternative text, and the placement with its effect extent (rotation not yet settled).
struct Frame<'a> {
c: &'a El,
anchored: bool,
w: f32,
h: f32,
alt: String,
float: Float,
}
fn drawing_frame(d: &El) -> Option<Frame<'_>> {
let (c, anchored) = match d.child("wp:inline") {
Some(c) => (c, false),
None => (d.child("wp:anchor")?, true),
};
let ext = c.child("wp:extent");
let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT);
let (w, h) = (dim("cx"), dim("cy"));
let (alt, meta) = nv_alt(c.child("wp:docPr"));
let mut float = if anchored { anchor_float(c) } else { Float::default() };
float.alt = meta;
float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden"));
if let Some(e) = c.child("wp:effectExtent") {
for (slot, n) in float.effect.iter_mut().zip(["l", "t", "r", "b"]) {
// Negative for a rotated object narrower than its frame; settled below.
*slot = e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(-1584.0, 1584.0);
}
}
Some(Frame { c, anchored, w, h, alt, float })
}
/// The `mc:Choice` holding an Office 2016 chart (`cx:chart`) in an `mc:AlternateContent`.
fn chartex_choice(ac: &El) -> Option<&El> {
ac.children("mc:Choice").find(|c| c.child("w:drawing").and_then(|d| d.find("a:graphicData")).and_then(|g| g.attr("uri")) == Some(CHARTEX_URI))
+59
View File
@@ -1861,6 +1861,65 @@ fn a_link_on_an_office_2016_charts_drawing_is_kept() {
}
}
/// A package with one invented waterfall chart (432 x 252 pt) whose `mc:Fallback` is `fallback`.
fn chartex_text_fallback_docx(fallback: &str) -> Vec<u8> {
let chart = r#"<cx:chartSpace xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex"><cx:chart><cx:title pos="t"><cx:tx><cx:txData><cx:v>Steps</cx:v></cx:txData></cx:tx></cx:title><cx:plotArea><cx:plotAreaRegion><cx:series layoutId="waterfall"/></cx:plotAreaRegion></cx:plotArea></cx:chart></cx:chartSpace>"#;
let frame = r#"<wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="5486400" cy="3200400"/><wp:docPr id="1" name="Chart 1"/><wp:cNvGraphicFramePr/>"#;
let body = format!(
r#"<w:p><w:r><w:t>Before</w:t></w:r></w:p><w:p><w:r><mc:AlternateContent><mc:Choice xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" Requires="cx1"><w:drawing>{frame}<a:graphic><a:graphicData uri="{CHARTEX_NS}"><cx:chart xmlns:cx="{CHARTEX_NS}" r:id="rIdCx"/></a:graphicData></a:graphic></wp:inline></w:drawing></mc:Choice><mc:Fallback>{fallback}</mc:Fallback></mc:AlternateContent></w:r></w:p>"#
);
let doc = format!(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document {W_NS}><w:body>{body}</w:body></w:document>"#);
let doc_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdCx" Type="http://schemas.microsoft.com/office/2014/relationships/chartEx" Target="charts/chartEx1.xml"/></Relationships>"#;
let types = format!(
r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/charts/chartEx1.xml" ContentType="{CT_CHARTEX}"/></Types>"#
);
zip(&[
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", ROOT_RELS.as_bytes()),
("word/document.xml", doc.as_bytes()),
("word/_rels/document.xml.rels", doc_rels.as_bytes()),
("word/charts/chartEx1.xml", chart.as_bytes()),
])
}
/// #6820: an Office 2016 chart whose fallback is only text keeps its 432 x 252 pt place (as a
/// placeholder) instead of becoming the fallback words, and is written back unchanged.
#[test]
fn office_2016_chart_with_a_text_fallback_keeps_its_size_through_saves() {
let mut d = craft_docx::read(&chartex_text_fallback_docx("<w:t>Chart not available.</w:t>")).unwrap();
for _ in 0..2 {
let g = graphics(&d);
let [InlineObject::Graphic { w, h, graphic, .. }] = g.as_slice() else { panic!("the chart is an object: {g:?}") };
assert_eq!((*w, *h), (432.0, 252.0));
assert_eq!((graphic.w, graphic.h), (432.0, 252.0));
assert!(
graphic.items.iter().any(|i| matches!(i, craft_wordmodel::graphic::GraphicItem::Text { text, .. } if text.starts_with("Waterfall chart"))),
"{:?}",
graphic.items
);
assert!(!paras(&d).iter().any(|p| p.text.contains("not available")), "the fallback words are not body text");
let files = unzip(&craft_docx::write(&d).unwrap());
let body = text(&files, "word/document.xml");
assert_eq!(attr_values(&body, "wp:extent", "cx"), ["5486400"], "the chart's frame; the text fallback has none: {body}");
assert!(body.contains("<w:t>Chart not available.</w:t>"), "the fallback is written back as it was: {body}");
let [cx_id] = attr_values(&body, "cx:chart", "r:id").try_into().unwrap_or_else(|_| panic!("chart lost: {body}"));
let (kind, target) = rel(&text(&files, "word/_rels/document.xml.rels"), &cx_id);
assert!(kind.ends_with("/chartEx"), "{kind}");
assert!(text(&files, &part_at("word", &target)).contains(r#"layoutId="waterfall""#));
let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect();
d = craft_docx::read(&zip(&entries)).unwrap();
}
}
/// A fallback that holds a run (not run content) can't be written back inside the object's own
/// run, so it is read as before: its text, no chart object.
#[test]
fn office_2016_chart_with_a_run_fallback_is_read_as_before() {
let d = craft_docx::read(&chartex_text_fallback_docx("<w:r><w:t>Chart not available.</w:t></w:r>")).unwrap();
assert!(graphics(&d).is_empty());
assert!(paras(&d).iter().any(|p| p.text.contains("Chart not available.")));
}
#[test]
fn resized_office_2016_chart_resizes_its_fallback_too() {
let mut d = craft_docx::read(&chartex_docx("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex")).unwrap();