docx charts: marker symbols and sizes, data label formats, upward axis titles

A chart file carried three things that were read but not drawn like Word:
- c:marker/c:symbol was ignored (every marker was a circle): squares, diamonds,
  triangles, x, plus, star, dash and dot are drawn now, in the series' c:size;
  unknown names fall back to a circle, sizes are clamped to 2..72 points.
- c:dLbls/c:numFmt (not linked to the source) now formats the data labels, on
  the series or on the chart type; over-long codes are ignored.
- The vertical axis title is turned -90 degrees (reading upwards) as Word does,
  or 90 when the file's bodyPr rot says so. It was always +90.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76
2026-11-15 01:06:12 +01:00
co-authored by Claude Sonnet 5.5
parent 0edccaf1bc
commit 396402940c
6 changed files with 232 additions and 18 deletions
+41
View File
@@ -64,11 +64,46 @@ pub(crate) struct Axis {
pub(crate) fmt: Option<String>,
/// The axis title, when the file gives it one.
pub(crate) title: Option<String>,
/// The title's `a:bodyPr/@rot` in degrees clockwise (`-5400000` is 90° counter-clockwise),
/// when the file gives one.
pub(crate) title_rot: Option<f32>,
/// Tick labels, as `c:tickLblPos` says (`none` hides them; a file that says nothing shows
/// them, as Word does).
pub(crate) labels: bool,
}
/// The shape of a series' point markers (`ST_MarkerStyle`, ECMA-376 §21.2.3.28).
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub(super) enum Symbol {
#[default]
Circle,
Square,
Diamond,
Triangle,
X,
Plus,
Star,
Dash,
Dot,
}
impl Symbol {
/// The symbol a `c:symbol` value names; anything unknown (`auto`, `picture`) is a circle.
pub(super) fn parse(name: &str) -> Symbol {
match name {
"square" => Symbol::Square,
"diamond" => Symbol::Diamond,
"triangle" => Symbol::Triangle,
"x" => Symbol::X,
"plus" => Symbol::Plus,
"star" => Symbol::Star,
"dash" => Symbol::Dash,
"dot" => Symbol::Dot,
_ => Symbol::Circle,
}
}
}
pub(super) struct Series {
pub(super) name: String,
/// The series' `c:idx` (an `xsd:unsignedInt`), which picks its automatic colour; `None`
@@ -84,6 +119,10 @@ pub(super) struct Series {
pub(super) no_fill: bool,
/// Markers on the series' points, when the file says.
pub(super) markers: Option<bool>,
/// The marker shape (`c:marker/c:symbol`; a circle when missing or unknown) and its size in
/// points (`c:marker/c:size`), when the file gives one.
pub(super) symbol: Symbol,
pub(super) marker_size: Option<f32>,
/// Draw the series' line as a smooth curve (`c:smooth`).
pub(super) smooth: bool,
pub(super) values: Vec<Option<f64>>,
@@ -96,6 +135,8 @@ pub(super) struct Series {
pub(super) x_fmt: Option<String>,
/// Data labels on or off for this series (`c:dLbls` of its own), when it says.
pub(super) labels: Option<bool>,
/// The labels' own number format (`c:dLbls/c:numFmt` not linked to the source), if any.
pub(super) label_fmt: Option<String>,
/// The values as the file has them, for data labels (`values` become shares in a 100%
/// stacked chart); empty when the series shows no labels.
pub(super) raw: Vec<Option<f64>>,
+50 -3
View File
@@ -1,5 +1,5 @@
use super::format::{date_text, excel_stamp, format_value, is_date_code};
use super::model::{Axis, Grouping, Kind, Pos, Series};
use super::model::{Axis, Grouping, Kind, Pos, Series, Symbol};
use super::plot::label;
use super::{Chart, El, FONT, MAX_CELLS, MAX_POINTS, MAX_RADAR_SERIES, MAX_SERIES, MAX_SPOKES, Rgb, fill_colour, int, measure, slot};
@@ -39,10 +39,14 @@ impl Chart {
cats.resize(n, String::new());
let radar_style = ty.child("c:radarStyle").and_then(|r| r.attr("val"));
let type_labels = show_values(ty.child("c:dLbls"));
let type_fmt = label_format(ty.child("c:dLbls"));
for s in &mut series {
s.values.resize(n, None);
s.xs.resize(n, None);
s.labels = Some(s.labels.or(type_labels).unwrap_or(false));
if s.label_fmt.is_none() {
s.label_fmt.clone_from(&type_fmt);
}
if s.labels == Some(true) {
s.raw = s.values.clone();
}
@@ -180,6 +184,15 @@ fn show_values(d: Option<&El>) -> Option<bool> {
d.child("c:showVal").map(|v| v.attr("val").is_none_or(truthy))
}
/// The number format of data labels (`c:dLbls/c:numFmt`) when it is not linked to the source.
fn label_format(d: Option<&El>) -> Option<String> {
d?.child("c:numFmt")
.filter(|f| f.attr("sourceLinked") != Some("1"))
.and_then(|f| f.attr("formatCode"))
.filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT)
.map(str::to_string)
}
fn legend_pos(chart: &El) -> Option<Pos> {
chart.child("c:legend").map(|l| match l.child("c:legendPos").and_then(|p| p.attr("val")).unwrap_or("r") {
"l" => Pos::Left,
@@ -213,7 +226,15 @@ impl Series {
// `c:marker/c:symbol`: which symbol each point gets (`none` for no markers). Scatter
// series show markers unless the file says not; line series only when it says so.
let symbol = ser.child("c:marker").and_then(|m| m.child("c:symbol")).and_then(|s| s.attr("val")).map(str::to_string);
let markers = symbol.map(|s| s != "none").or_else(|| scatter.then_some(true));
let markers = symbol.as_deref().map(|s| s != "none").or_else(|| scatter.then_some(true));
let symbol = symbol.as_deref().map_or(Symbol::Circle, Symbol::parse);
let marker_size = ser
.child("c:marker")
.and_then(|m| m.child("c:size"))
.and_then(|s| s.attr("val"))
.and_then(|v| v.trim().parse::<f32>().ok())
.filter(|v| v.is_finite())
.map(|v| v.clamp(2.0, 72.0));
let smooth = ser.child("c:smooth").and_then(|s| s.attr("val")).is_some_and(truthy);
let (values, fmt) = numbers(ser.child(if scatter { "c:yVal" } else { "c:val" }), cap);
let (mut xs, x_fmt) = if scatter { numbers(ser.child("c:xVal"), cap) } else { (Vec::new(), None) };
@@ -229,7 +250,27 @@ impl Series {
}
}
let labels = show_values(ser.child("c:dLbls"));
Series { name, idx, color, line_w, line, no_fill, markers, smooth, values, xs, points, fmt, x_fmt, labels, raw: Vec::new() }
let label_fmt = label_format(ser.child("c:dLbls"));
Series {
name,
idx,
color,
line_w,
line,
no_fill,
markers,
symbol,
marker_size,
smooth,
values,
xs,
points,
fmt,
x_fmt,
labels,
label_fmt,
raw: Vec::new(),
}
}
}
@@ -314,6 +355,12 @@ pub(super) fn axis(a: Option<&El>) -> Axis {
.filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT)
.map(str::to_string),
title: a.child("c:title").and_then(title_text),
title_rot: a
.child("c:title")
.and_then(|t| t.find("a:bodyPr"))
.and_then(|b| b.attr("rot"))
.and_then(|v| v.trim().parse::<i64>().ok())
.map(|v| (v as f64 / 60_000.0).clamp(-360.0, 360.0) as f32),
labels: a.child("c:tickLblPos").and_then(|p| p.attr("val")) != Some("none"),
}
}
+45 -12
View File
@@ -1,10 +1,13 @@
use super::canvas::{Rect, clip_text, fill, rect_segs, runs, seg, stroke, text, text_angle, text_at, text_w, widest, wrap};
use super::format::format_value;
use super::model::{DataLabel, Grouping, Kind, Series};
use super::model::{DataLabel, Grouping, Kind, Series, Symbol};
use super::parse::category_text;
use super::polar::{draw_data_labels, label_of};
use super::{AXIS, Chart, El, GAP, GRID, GraphicItem, LINE, LINE_W, MAX_LABEL, MAX_TICKS, PathSeg, Rgb, ShapeKind, TextAlign, fill_colour, measure};
/// Line width of the stroked marker symbols (x, plus, star), points.
const MARKER_STROKE: f32 = 1.5;
pub(super) fn label(s: &str) -> String {
s.chars().take(MAX_LABEL).collect()
}
@@ -243,18 +246,21 @@ pub(super) fn cartesian(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
}
/// The axis titles, one line: the title of the vertical axis (the value axis for columns, the
/// category axis for bars) is rotated 90° on the plot's left; the horizontal axis's title sits
/// category axis for bars) is turned 90° on the plot's left; the horizontal axis's title sits
/// under the plot.
fn draw_axis_titles(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, area: Rect) {
let lh = c.text_size * LINE;
// The axis drawn along the plot's left (the value axis for columns, the category axis for
// bars) gets its title rotated there; the other axis's title sits under the plot.
let (left, bottom) = if c.horizontal { (&c.cat, &c.val) } else { (&c.val, &c.cat) };
// Word turns the vertical axis's title counter-clockwise (reading upwards) unless the file
// turns it the other way; a title with any other rotation would not fit the strip.
let up = if left.title_rot.is_some_and(|r| (r.rem_euclid(360.0) - 90.0).abs() < 1.0) { 90.0 } else { -90.0 };
if !left.deleted
&& let Some(t) = &left.title
{
let t = clip_text(t, g.plot.h, c.text_size);
text_angle(out, Rect { x: area.x, y: g.plot.y, w: lh, h: g.plot.h }, &t, c.text_size, TextAlign::Center, false, 90.0);
text_angle(out, Rect { x: area.x, y: g.plot.y, w: lh, h: g.plot.h }, &t, c.text_size, TextAlign::Center, false, up);
}
if !bottom.deleted
&& let Some(t) = &bottom.title
@@ -481,18 +487,48 @@ fn lines(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<Data
stroke(out, curve(pts.iter().copied(), s.smooth), c.series_colour(j), s.line_w.unwrap_or(LINE_W));
}
if s.markers == Some(true) {
markers(out, pts.iter().flatten().copied(), c.series_colour(j));
markers(out, pts.iter().flatten().copied(), c.series_colour(j), s);
}
}
}
/// A series' points as small circles (`colour`), for lines and scatter charts.
fn markers(out: &mut Vec<GraphicItem>, pts: impl Iterator<Item = (f32, f32)>, colour: Rgb) {
/// A series' point markers in the series' symbol and size (`colour` fills or strokes them), for
/// lines and scatter charts.
fn markers(out: &mut Vec<GraphicItem>, pts: impl Iterator<Item = (f32, f32)>, colour: Rgb, s: &Series) {
const MARKER: f32 = 6.0;
let size = s.marker_size.filter(|v| v.is_finite()).unwrap_or(MARKER).clamp(2.0, 72.0);
let h = size / 2.0;
let shape = |out: &mut Vec<GraphicItem>, rect: [f32; 4], kind: ShapeKind| {
out.push(GraphicItem::Shape { rect, kind, fill: Some(colour), stroke: None, stroke_width: 0.0 });
};
let mut strokes = Vec::new();
for (x, y) in pts {
let rect = [x - MARKER / 2.0, y - MARKER / 2.0, MARKER, MARKER];
out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(colour), stroke: None, stroke_width: 0.0 });
match s.symbol {
Symbol::Circle => shape(out, [x - h, y - h, size, size], ShapeKind::Ellipse),
Symbol::Square => shape(out, [x - h, y - h, size, size], ShapeKind::Rectangle),
Symbol::Dot => shape(out, [x - h / 2.0, y - h / 2.0, h, h], ShapeKind::Ellipse),
Symbol::Dash => shape(out, [x - h, y - size / 6.0, size, size / 3.0], ShapeKind::Rectangle),
Symbol::Diamond => fill(
out,
vec![PathSeg::Move(x, y - h), PathSeg::Line(x + h, y), PathSeg::Line(x, y + h), PathSeg::Line(x - h, y), PathSeg::Close],
colour,
),
Symbol::Triangle => {
fill(out, vec![PathSeg::Move(x, y - h), PathSeg::Line(x + h, y + h), PathSeg::Line(x - h, y + h), PathSeg::Close], colour)
}
Symbol::X | Symbol::Plus | Symbol::Star => {
if s.symbol != Symbol::Plus {
strokes.extend(seg(x - h, y - h, x + h, y + h));
strokes.extend(seg(x - h, y + h, x + h, y - h));
}
if s.symbol != Symbol::X {
strokes.extend(seg(x - h, y, x + h, y));
strokes.extend(seg(x, y - h, x, y + h));
}
}
}
}
stroke(out, strokes, colour, MARKER_STROKE);
}
/// A polyline through `pts`, a smooth curve (Catmull-Rom pieces) when `smooth` and there are at
@@ -582,10 +618,7 @@ fn draw_scatter(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut V
stroke(out, curve(pts.iter().copied(), s.smooth), c.series_colour(j), s.line_w.unwrap_or(LINE_W));
}
if s.markers != Some(false) {
for (x, y) in pts.iter().flatten() {
let rect = [x - MARKER / 2.0, y - MARKER / 2.0, MARKER, MARKER];
out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(c.series_colour(j)), stroke: None, stroke_width: 0.0 });
}
markers(out, pts.iter().flatten().copied(), c.series_colour(j), s);
}
}
}
+2 -2
View File
@@ -134,13 +134,13 @@ pub(super) fn radar(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
}
/// The data label of point `i` of series `s`, when it shows one: the value as the file has it,
/// in the series' number format.
/// in the labels' own number format, else the series' one.
pub(super) fn label_of(s: &Series, i: usize) -> Option<String> {
if s.labels != Some(true) {
return None;
}
let v = s.raw.get(i).copied().flatten()?;
let fmt = s.fmt.as_deref().filter(|f| !f.eq_ignore_ascii_case("General"));
let fmt = s.label_fmt.as_deref().or(s.fmt.as_deref()).filter(|f| !f.eq_ignore_ascii_case("General"));
Some(match fmt {
Some(f) => format_value(v, f, 1.0),
None => general_value(v),
+93
View File
@@ -656,3 +656,96 @@ fn category_gridlines_follow_the_points_when_the_axis_crosses_mid() {
assert!(grid.iter().zip(&pts).all(|(g, p)| (g - p).abs() < 1e-3), "{cross}: grid {grid:?} points {pts:?}");
}
}
/// A line chart with one series; `extra` goes into the series (`c:marker`, `c:dLbls`), `axes`
/// into the value axis.
fn line_with(extra: &str, val_axis: &str) -> Vec<GraphicItem> {
let s = ser(0, "S", Some("FF0000"), &["Q1", "Q2", "Q3"], &["3.2", "4.1", "5"]).replace("<c:cat>", &format!("{extra}<c:cat>"));
let plot = format!(
r#"<c:lineChart><c:grouping val="standard"/>{s}<c:axId val="1"/><c:axId val="2"/></c:lineChart><c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/>{val_axis}</c:valAx>"#
);
chart_items(&space(&plot), &theme(), 300.0, 200.0)
}
fn marker_xml(symbol: &str, size: u32) -> String {
format!(r#"<c:marker><c:symbol val="{symbol}"/><c:size val="{size}"/></c:marker>"#)
}
#[test]
fn marker_symbols_are_drawn_as_their_shape() {
let shapes = |items: &[GraphicItem], kind: ShapeKind| {
items
.iter()
.filter(|it| matches!(it, GraphicItem::Shape { kind: k, rect, .. } if *k == kind && rect[2] > 3.0 && rect[2] < 20.0 && rect[3] > 1.0))
.count()
};
let paths = |items: &[GraphicItem], filled: bool| {
items
.iter()
.filter(|it| matches!(it, GraphicItem::Path { fill, segs, .. } if fill.is_some() == filled && segs.len() <= 12 && segs.len() >= 3))
.count()
};
// One marker per point, in the series' size.
let circle = line_with(&marker_xml("circle", 9), "");
assert_eq!(shapes(&circle, ShapeKind::Ellipse), 3);
assert!(circle.iter().any(|it| matches!(it, GraphicItem::Shape { kind: ShapeKind::Ellipse, rect, .. } if (rect[2] - 9.0).abs() < 1e-3)));
let square = line_with(&marker_xml("square", 7), "");
assert_eq!(shapes(&square, ShapeKind::Rectangle) - shapes(&circle, ShapeKind::Rectangle), 3, "a square per point");
assert_eq!(shapes(&square, ShapeKind::Ellipse), 0, "no circles");
// Diamonds and triangles are filled polygons; x, plus and star are strokes.
let base = paths(&line_with("", ""), true);
assert_eq!(paths(&line_with(&marker_xml("diamond", 7), ""), true) - base, 3);
assert_eq!(paths(&line_with(&marker_xml("triangle", 7), ""), true) - base, 3);
for symbol in ["x", "plus", "star"] {
let items = line_with(&marker_xml(symbol, 7), "");
assert!(items.iter().any(|it| matches!(it, GraphicItem::Path { fill: None, stroke: Some(_), segs, .. } if segs.len() >= 6)), "{symbol}");
assert_eq!(shapes(&items, ShapeKind::Ellipse), 0, "{symbol} is not a circle");
}
// Dash and dot are small shapes; `none` and unknown names never crash (unknown: a circle).
assert_eq!(shapes(&line_with(&marker_xml("dash", 7), ""), ShapeKind::Rectangle) - shapes(&circle, ShapeKind::Rectangle), 3);
assert_eq!(shapes(&line_with(&marker_xml("dot", 7), ""), ShapeKind::Ellipse), 3);
assert_eq!(shapes(&line_with(&marker_xml("none", 7), ""), ShapeKind::Ellipse), 0);
assert_eq!(shapes(&line_with(&marker_xml("wibble", 7), ""), ShapeKind::Ellipse), 3);
// Hostile sizes are clamped.
for size in ["0", "99999999999", "-4", "x"] {
let items = line_with(&format!(r#"<c:marker><c:symbol val="square"/><c:size val="{size}"/></c:marker>"#), "");
assert!(items.iter().all(|it| match it {
GraphicItem::Shape { rect, .. } => rect.iter().all(|v| v.is_finite()) && rect[2] <= 300.0,
_ => true,
}));
}
}
#[test]
fn data_labels_use_their_own_format_code() {
let dl = |num: &str| format!(r#"<c:dLbls>{num}<c:showVal val="1"/></c:dLbls>"#);
let shown = |items: &[GraphicItem]| -> Vec<String> {
items.iter().filter_map(|it| if let GraphicItem::Text { text, .. } = it { Some(text.clone()) } else { None }).collect()
};
let own = shown(&line_with(&dl(r#"<c:numFmt formatCode="0.00" sourceLinked="0"/>"#), ""));
assert!(own.contains(&"3.20".to_string()) && own.contains(&"5.00".to_string()), "{own:?}");
// Linked to the source: the series' format (General here).
let linked = shown(&line_with(&dl(r#"<c:numFmt formatCode="0.00" sourceLinked="1"/>"#), ""));
assert!(linked.contains(&"3.2".to_string()) && linked.contains(&"5".to_string()), "{linked:?}");
// A format code beyond the cap is ignored, not applied.
let long = "0".repeat(craft_wordmodel::chart::MAX_FMT + 1);
let capped = shown(&line_with(&dl(&format!(r#"<c:numFmt formatCode="{long}" sourceLinked="0"/>"#)), ""));
assert!(capped.contains(&"3.2".to_string()), "{capped:?}");
}
#[test]
fn value_axis_title_turns_counter_clockwise_like_word() {
let title = |body: &str| format!(r#"<c:title><c:tx><c:rich>{body}<a:p><a:r><a:t>Revenue</a:t></a:r></a:p></c:rich></c:tx></c:title>"#);
let angle = |items: &[GraphicItem]| {
items.iter().find_map(|it| if let GraphicItem::Text { text, angle, .. } = it { (text == "Revenue").then_some(*angle) } else { None })
};
// The file's rotation (`-5400000` is 90° counter-clockwise), or Word's default when it says none.
assert_eq!(angle(&line_with("", &title(r#"<a:bodyPr rot="-5400000" vert="horz"/>"#))), Some(-90.0));
assert_eq!(angle(&line_with("", &title("<a:bodyPr/>"))), Some(-90.0));
assert_eq!(angle(&line_with("", &title(r#"<a:bodyPr rot="5400000" vert="horz"/>"#))), Some(90.0));
// A horizontal title has no room beside the plot: it stays turned up.
assert_eq!(angle(&line_with("", &title(r#"<a:bodyPr rot="0" vert="horz"/>"#))), Some(-90.0));
// Hostile values stay finite.
let odd = angle(&line_with("", &title(r#"<a:bodyPr rot="99999999999999999999"/>"#)));
assert!(odd.is_some_and(f32::is_finite));
}
+1 -1
View File
@@ -117,7 +117,7 @@ pub enum GraphicItem {
},
/// One line of text in `rect`, aligned horizontally by `align`, centred vertically; `angle`
/// degrees clockwise turns the text about `rect`'s centre as it is drawn (chart axis titles
/// use 90° for the vertical axis).
/// turn the vertical axis's title -90°, reading upwards, as Word does).
Text {
rect: [f32; 4],
text: String,