mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
docx: chart axis and series formatting
Add the series formatting (fill, line, markers, smooth, labels, number format) and the category/value axis formatting (title, bounds, number format, gridlines, tick labels, axis line) to the chart model, and read and write them in the DOCX chart part. GraphicItem::Text gets an angle for the rotated vertical axis title. With none of the new fields set the chart part is written as before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f0f4758c01
commit
b6a2df0c1d
15 files changed
+726
-119
No files matched your search
+334
-65
@@ -6,7 +6,7 @@
|
||||
//! [`spec_of`] turns a chart part back into the model only when writing that model again gives
|
||||
//! the same markup, so a chart with anything the model leaves out stays as it was read.
|
||||
|
||||
use craft_wordmodel::chart::{ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES};
|
||||
use craft_wordmodel::chart::{ChartAxis, ChartSeries, ChartSpec, ChartType, LegendPos, MAX_POINTS, MAX_SERIES};
|
||||
use craft_wordmodel::graphic::GraphicItem;
|
||||
use craft_wordmodel::props::Rgb;
|
||||
|
||||
@@ -102,11 +102,24 @@ fn bounded(spec: &ChartSpec) -> ChartSpec {
|
||||
.series
|
||||
.iter()
|
||||
.take(MAX_SERIES)
|
||||
.map(|s| ChartSeries { name: s.name.clone(), values: s.values.iter().take(MAX_POINTS).copied().collect() })
|
||||
.map(|s| ChartSeries {
|
||||
name: s.name.clone(),
|
||||
values: s.values.iter().take(MAX_POINTS).copied().collect(),
|
||||
fill: s.fill,
|
||||
no_fill: s.no_fill,
|
||||
line_w: s.line_w,
|
||||
no_line: s.no_line,
|
||||
markers: s.markers,
|
||||
smooth: s.smooth,
|
||||
labels: s.labels,
|
||||
fmt: s.fmt.clone(),
|
||||
})
|
||||
.collect(),
|
||||
title: spec.title.clone(),
|
||||
legend: spec.legend,
|
||||
data_labels: spec.data_labels,
|
||||
cat_axis: spec.cat_axis.clone(),
|
||||
val_axis: spec.val_axis.clone(),
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
@@ -185,17 +198,19 @@ fn plot(w: &mut W, spec: &ChartSpec) {
|
||||
match k {
|
||||
ChartType::Pie | ChartType::Doughnut => {}
|
||||
ChartType::Scatter => {
|
||||
value_axis(w, CAT_AX, VAL_AX, "b", false, "midCat");
|
||||
value_axis(w, VAL_AX, CAT_AX, "l", true, "midCat");
|
||||
value_axis(w, CAT_AX, VAL_AX, "b", "midCat", &spec.cat_axis);
|
||||
value_axis(w, VAL_AX, CAT_AX, "l", "midCat", &spec.val_axis);
|
||||
}
|
||||
_ => {
|
||||
category_axis(w, if horizontal { "l" } else { "b" });
|
||||
value_axis(w, VAL_AX, CAT_AX, if horizontal { "b" } else { "l" }, true, "between");
|
||||
category_axis(w, if horizontal { "l" } else { "b" }, &spec.cat_axis);
|
||||
value_axis(w, VAL_AX, CAT_AX, if horizontal { "b" } else { "l" }, "between", &spec.val_axis);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `c:ser` (ECMA-376 element order: idx, order, tx, spPr, marker, cat/xVal, val/yVal, smooth).
|
||||
/// One `c:ser` (ECMA-376 element order: idx, order, tx, spPr, marker, invertIfNegative, dLbls,
|
||||
/// cat/xVal, val/yVal, smooth): the series' formatting (fill, line, markers, its own labels) sits
|
||||
/// in `c:spPr`, `c:marker` and `c:dLbls`; the values carry their number format.
|
||||
fn series(w: &mut W, spec: &ChartSpec, i: usize, s: &ChartSeries) {
|
||||
let k = spec.kind;
|
||||
let i = i.to_string();
|
||||
@@ -207,25 +222,26 @@ fn series(w: &mut W, spec: &ChartSpec, i: usize, s: &ChartSeries) {
|
||||
w.leaf("c:v", &[], &s.name);
|
||||
w.close("c:tx");
|
||||
}
|
||||
match k {
|
||||
// Markers only: the series has no line.
|
||||
ChartType::Scatter => {
|
||||
w.open("c:spPr", &[]);
|
||||
w.open("a:ln", &[("w", "19050")]);
|
||||
w.empty("a:noFill", &[]);
|
||||
w.close("a:ln");
|
||||
w.close("c:spPr");
|
||||
}
|
||||
ChartType::Column | ChartType::ColumnStacked | ChartType::Bar | ChartType::BarStacked => {
|
||||
w.empty("c:invertIfNegative", &[("val", "0")]);
|
||||
}
|
||||
ChartType::Line => {
|
||||
w.open("c:marker", &[]);
|
||||
w.empty("c:symbol", &[("val", "none")]);
|
||||
w.close("c:marker");
|
||||
}
|
||||
_ => {}
|
||||
series_props(w, s);
|
||||
series_marker(w, k, s);
|
||||
if matches!(k, ChartType::Column | ChartType::ColumnStacked | ChartType::Bar | ChartType::BarStacked) {
|
||||
w.empty("c:invertIfNegative", &[("val", "0")]);
|
||||
}
|
||||
if let Some(on) = s.labels {
|
||||
w.open("c:dLbls", &[]);
|
||||
for (name, show) in [
|
||||
("c:showLegendKey", false),
|
||||
("c:showVal", on),
|
||||
("c:showCatName", false),
|
||||
("c:showSerName", false),
|
||||
("c:showPercent", false),
|
||||
("c:showBubbleSize", false),
|
||||
] {
|
||||
w.empty(name, &[("val", if show { "1" } else { "0" })]);
|
||||
}
|
||||
w.close("c:dLbls");
|
||||
}
|
||||
let code = s.fmt.as_deref().unwrap_or("General");
|
||||
if k == ChartType::Scatter {
|
||||
let xs: Option<Vec<Option<f64>>> = spec
|
||||
.categories
|
||||
@@ -234,27 +250,84 @@ fn series(w: &mut W, spec: &ChartSpec, i: usize, s: &ChartSeries) {
|
||||
.collect();
|
||||
w.open("c:xVal", &[]);
|
||||
match xs {
|
||||
Some(xs) => num_lit(w, &xs),
|
||||
Some(xs) => num_lit(w, &xs, "General"),
|
||||
None => str_lit(w, &spec.categories),
|
||||
}
|
||||
w.close("c:xVal");
|
||||
w.open("c:yVal", &[]);
|
||||
num_lit(w, &s.values);
|
||||
num_lit(w, &s.values, code);
|
||||
w.close("c:yVal");
|
||||
} else {
|
||||
w.open("c:cat", &[]);
|
||||
str_lit(w, &spec.categories);
|
||||
w.close("c:cat");
|
||||
w.open("c:val", &[]);
|
||||
num_lit(w, &s.values);
|
||||
num_lit(w, &s.values, code);
|
||||
w.close("c:val");
|
||||
}
|
||||
if matches!(k, ChartType::Line | ChartType::Scatter) {
|
||||
w.empty("c:smooth", &[("val", "0")]);
|
||||
w.empty("c:smooth", &[("val", if s.smooth { "1" } else { "0" })]);
|
||||
}
|
||||
w.close("c:ser");
|
||||
}
|
||||
|
||||
/// `c:spPr`: the series' fill (`a:solidFill` / `a:noFill`) and line (`a:ln`), written when the
|
||||
/// model sets them. `a:ln` without `w` is the default width, `w` a fixed one, and `a:noFill`
|
||||
/// inside it "no line" (a scatter series keeps its markers with no line).
|
||||
fn series_props(w: &mut W, s: &ChartSeries) {
|
||||
let fill_set = s.no_fill || s.fill.is_some();
|
||||
let ln_set = s.no_line || s.line_w.is_some();
|
||||
if !(fill_set || ln_set) {
|
||||
return;
|
||||
}
|
||||
w.open("c:spPr", &[]);
|
||||
if fill_set {
|
||||
match &s.fill {
|
||||
Some(c) => {
|
||||
w.open("a:solidFill", &[]);
|
||||
w.empty("a:srgbClr", &[("val", &c.hex())]);
|
||||
w.close("a:solidFill");
|
||||
}
|
||||
None => w.empty("a:noFill", &[]),
|
||||
}
|
||||
}
|
||||
if ln_set {
|
||||
let w_attr = s.line_w.map(emu).unwrap_or_default();
|
||||
let attrs = [("w", w_attr.as_str())];
|
||||
w.open("a:ln", if w_attr.is_empty() { &[] } else { &attrs });
|
||||
if s.no_line {
|
||||
w.empty("a:noFill", &[]);
|
||||
}
|
||||
w.close("a:ln");
|
||||
}
|
||||
w.close("c:spPr");
|
||||
}
|
||||
|
||||
/// `c:marker`: line and scatter series say which symbol each point gets; other types have none.
|
||||
fn series_marker(w: &mut W, k: ChartType, s: &ChartSeries) {
|
||||
match k {
|
||||
ChartType::Line => {
|
||||
w.open("c:marker", &[]);
|
||||
w.empty("c:symbol", &[("val", if s.markers == Some(true) { "circle" } else { "none" })]);
|
||||
w.close("c:marker");
|
||||
}
|
||||
// Unset: no `c:marker`, so Word picks its automatic symbol for each series.
|
||||
ChartType::Scatter => {
|
||||
if let Some(on) = s.markers {
|
||||
w.open("c:marker", &[]);
|
||||
w.empty("c:symbol", &[("val", if on { "circle" } else { "none" })]);
|
||||
w.close("c:marker");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A line width in points as the `w` attribute DrawingML wants (EMU).
|
||||
fn emu(pt: f32) -> String {
|
||||
((pt * 12700.0).round().max(0.0) as i64).to_string()
|
||||
}
|
||||
|
||||
fn str_lit(w: &mut W, items: &[String]) {
|
||||
w.open("c:strLit", &[]);
|
||||
w.empty("c:ptCount", &[("val", &items.len().to_string())]);
|
||||
@@ -266,9 +339,9 @@ fn str_lit(w: &mut W, items: &[String]) {
|
||||
w.close("c:strLit");
|
||||
}
|
||||
|
||||
fn num_lit(w: &mut W, values: &[Option<f64>]) {
|
||||
fn num_lit(w: &mut W, values: &[Option<f64>], code: &str) {
|
||||
w.open("c:numLit", &[]);
|
||||
w.leaf("c:formatCode", &[], "General");
|
||||
w.leaf("c:formatCode", &[], code);
|
||||
w.empty("c:ptCount", &[("val", &values.len().to_string())]);
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
if let Some(v) = v.filter(|v| v.is_finite()) {
|
||||
@@ -285,17 +358,21 @@ fn num(v: f64) -> String {
|
||||
if v == 0.0 { "0".to_string() } else { format!("{v}") }
|
||||
}
|
||||
|
||||
fn category_axis(w: &mut W, pos: &str) {
|
||||
fn category_axis(w: &mut W, pos: &str, ax: &ChartAxis) {
|
||||
w.open("c:catAx", &[]);
|
||||
w.empty("c:axId", &[("val", CAT_AX)]);
|
||||
w.open("c:scaling", &[]);
|
||||
w.empty("c:orientation", &[("val", "minMax")]);
|
||||
w.close("c:scaling");
|
||||
scaling(w, ax);
|
||||
w.empty("c:delete", &[("val", "0")]);
|
||||
w.empty("c:axPos", &[("val", pos)]);
|
||||
if ax.gridlines {
|
||||
w.empty("c:majorGridlines", &[]);
|
||||
}
|
||||
axis_title(w, ax);
|
||||
num_fmt(w, ax);
|
||||
w.empty("c:majorTickMark", &[("val", "none")]);
|
||||
w.empty("c:minorTickMark", &[("val", "none")]);
|
||||
w.empty("c:tickLblPos", &[("val", "nextTo")]);
|
||||
w.empty("c:tickLblPos", &[("val", if ax.labels { "nextTo" } else { "none" })]);
|
||||
axis_line(w, ax);
|
||||
w.empty("c:crossAx", &[("val", VAL_AX)]);
|
||||
w.empty("c:crosses", &[("val", "autoZero")]);
|
||||
w.empty("c:auto", &[("val", "1")]);
|
||||
@@ -305,34 +382,81 @@ fn category_axis(w: &mut W, pos: &str) {
|
||||
w.close("c:catAx");
|
||||
}
|
||||
|
||||
/// A value axis: with gridlines and no axis line (`grid`), else with its line and no gridlines.
|
||||
fn value_axis(w: &mut W, id: &str, cross: &str, pos: &str, grid: bool, between: &str) {
|
||||
/// A value axis (scatter x axes included): its scale, gridlines, title, labels and line, as the
|
||||
/// model sets them.
|
||||
fn value_axis(w: &mut W, id: &str, cross: &str, pos: &str, between: &str, ax: &ChartAxis) {
|
||||
w.open("c:valAx", &[]);
|
||||
w.empty("c:axId", &[("val", id)]);
|
||||
w.open("c:scaling", &[]);
|
||||
w.empty("c:orientation", &[("val", "minMax")]);
|
||||
w.close("c:scaling");
|
||||
scaling(w, ax);
|
||||
w.empty("c:delete", &[("val", "0")]);
|
||||
w.empty("c:axPos", &[("val", pos)]);
|
||||
if grid {
|
||||
if ax.gridlines {
|
||||
w.empty("c:majorGridlines", &[]);
|
||||
}
|
||||
axis_title(w, ax);
|
||||
num_fmt(w, ax);
|
||||
w.empty("c:majorTickMark", &[("val", "none")]);
|
||||
w.empty("c:minorTickMark", &[("val", "none")]);
|
||||
w.empty("c:tickLblPos", &[("val", "nextTo")]);
|
||||
if grid {
|
||||
w.open("c:spPr", &[]);
|
||||
w.open("a:ln", &[]);
|
||||
w.empty("a:noFill", &[]);
|
||||
w.close("a:ln");
|
||||
w.close("c:spPr");
|
||||
}
|
||||
w.empty("c:tickLblPos", &[("val", if ax.labels { "nextTo" } else { "none" })]);
|
||||
axis_line(w, ax);
|
||||
w.empty("c:crossAx", &[("val", cross)]);
|
||||
w.empty("c:crosses", &[("val", "autoZero")]);
|
||||
w.empty("c:crossBetween", &[("val", between)]);
|
||||
w.close("c:valAx");
|
||||
}
|
||||
|
||||
/// `c:scaling`: the orientation, then the fixed bounds when the model sets them.
|
||||
fn scaling(w: &mut W, ax: &ChartAxis) {
|
||||
w.open("c:scaling", &[]);
|
||||
w.empty("c:orientation", &[("val", "minMax")]);
|
||||
for (name, v) in [("c:max", ax.max), ("c:min", ax.min)] {
|
||||
if let Some(v) = v.filter(|v| v.is_finite()) {
|
||||
w.empty(name, &[("val", &num(v))]);
|
||||
}
|
||||
}
|
||||
w.close("c:scaling");
|
||||
}
|
||||
|
||||
/// The axis title, in the same rich-text shape the chart title uses.
|
||||
fn axis_title(w: &mut W, ax: &ChartAxis) {
|
||||
let Some(t) = &ax.title else { return };
|
||||
w.open("c:title", &[]);
|
||||
w.open("c:tx", &[]);
|
||||
w.open("c:rich", &[]);
|
||||
w.empty("a:bodyPr", &[]);
|
||||
w.empty("a:lstStyle", &[]);
|
||||
w.open("a:p", &[]);
|
||||
w.open("a:r", &[]);
|
||||
w.leaf("a:t", &[], t);
|
||||
w.close("a:r");
|
||||
w.close("a:p");
|
||||
w.close("c:rich");
|
||||
w.close("c:tx");
|
||||
w.empty("c:overlay", &[("val", "0")]);
|
||||
w.close("c:title");
|
||||
}
|
||||
|
||||
/// Tick-label number format: the model's code, unlinked from the source, else the default.
|
||||
fn num_fmt(w: &mut W, ax: &ChartAxis) {
|
||||
match &ax.fmt {
|
||||
Some(code) => w.empty("c:numFmt", &[("formatCode", code), ("sourceLinked", "0")]),
|
||||
None => w.empty("c:numFmt", &[("formatCode", "General"), ("sourceLinked", "1")]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `c:spPr`: an axis line only when the model keeps it (the default writes nothing, which reads
|
||||
/// as a line); `a:noFill` when the axis line is off.
|
||||
fn axis_line(w: &mut W, ax: &ChartAxis) {
|
||||
if ax.line {
|
||||
return;
|
||||
}
|
||||
w.open("c:spPr", &[]);
|
||||
w.open("a:ln", &[]);
|
||||
w.empty("a:noFill", &[]);
|
||||
w.close("a:ln");
|
||||
w.close("c:spPr");
|
||||
}
|
||||
|
||||
/// The chart a chart part holds, when the part is exactly what [`chart_xml`] writes for it (so
|
||||
/// editing and saving it loses nothing). `None` for any other chart.
|
||||
pub(crate) fn spec_of(space: &El) -> Option<ChartSpec> {
|
||||
@@ -365,15 +489,40 @@ pub(crate) fn spec_of(space: &El) -> Option<ChartSpec> {
|
||||
let categories = sers.first().and_then(|s| s.child(if scatter { "c:xVal" } else { "c:cat" })).map(literal).unwrap_or_default();
|
||||
let series = sers
|
||||
.iter()
|
||||
.map(|s| ChartSeries {
|
||||
name: s.child("c:tx").and_then(|t| t.child("c:v")).map(|v| v.text()).unwrap_or_default(),
|
||||
values: s
|
||||
.child(if scatter { "c:yVal" } else { "c:val" })
|
||||
.map(literal)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|v| v.parse::<f64>().ok().filter(|v| v.is_finite()))
|
||||
.collect(),
|
||||
.map(|s| {
|
||||
let ln = s.child("c:spPr").and_then(|p| p.child("a:ln"));
|
||||
let symbol = s.child("c:marker").and_then(|m| m.child("c:symbol")).and_then(|m| m.attr("val"));
|
||||
ChartSeries {
|
||||
name: s.child("c:tx").and_then(|t| t.child("c:v")).map(|v| v.text()).unwrap_or_default(),
|
||||
values: s
|
||||
.child(if scatter { "c:yVal" } else { "c:val" })
|
||||
.map(literal)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|v| v.parse::<f64>().ok().filter(|v| v.is_finite()))
|
||||
.collect(),
|
||||
fill: s
|
||||
.child("c:spPr")
|
||||
.and_then(|p| p.child("a:solidFill"))
|
||||
.and_then(|f| f.child("a:srgbClr"))
|
||||
.and_then(|c| c.attr("val"))
|
||||
.and_then(Rgb::parse),
|
||||
no_fill: s.child("c:spPr").and_then(|p| p.child("a:noFill")).is_some(),
|
||||
line_w: ln.and_then(|l| l.attr("w")).and_then(|w| w.parse::<f64>().ok()).filter(|w| w.is_finite()).map(|w| (w / 12700.0) as f32),
|
||||
no_line: ln.and_then(|l| l.child("a:noFill")).is_some(),
|
||||
// Line series show no markers by default: only a setting that differs from that
|
||||
// belongs in the model. A scatter series keeps what the file says, so a missing
|
||||
// `c:marker` (Word's automatic symbols) stays unset and is not written back.
|
||||
markers: symbol.map(|v| v != "none").filter(|m| scatter || *m),
|
||||
smooth: s.child("c:smooth").and_then(|v| v.attr("val")).is_some_and(|v| v == "1"),
|
||||
labels: s.child("c:dLbls").and_then(|d| d.child("c:showVal")).and_then(|v| v.attr("val")).map(|v| v == "1"),
|
||||
fmt: s
|
||||
.child(if scatter { "c:yVal" } else { "c:val" })
|
||||
.and_then(|v| v.els().find(|e| e.name == "c:numLit"))
|
||||
.and_then(|l| l.child("c:formatCode"))
|
||||
.map(|f| f.text())
|
||||
.filter(|f| *f != "General"),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let title = chart.child("c:title").and_then(|t| t.find("a:t")).map(|t| t.text());
|
||||
@@ -384,12 +533,48 @@ pub(crate) fn spec_of(space: &El) -> Option<ChartSpec> {
|
||||
_ => LegendPos::Right,
|
||||
});
|
||||
let data_labels = ty.child("c:dLbls").and_then(|d| d.child("c:showVal")).and_then(|v| v.attr("val")) == Some("1");
|
||||
let spec = ChartSpec { kind, categories, series, title, legend, data_labels }.sanitized();
|
||||
// Editable only when nothing would be lost: writing the model again gives the same part.
|
||||
let again = xml::parse(chart_xml(&spec).as_bytes()).ok()?;
|
||||
let (cat_a, val_a) = crate::read::chart::chart_axes(plot, scatter);
|
||||
let axis = |a: crate::read::chart::Axis| ChartAxis {
|
||||
title: a.title,
|
||||
min: a.min,
|
||||
max: a.max,
|
||||
fmt: a.fmt,
|
||||
gridlines: a.grid,
|
||||
labels: a.labels,
|
||||
line: a.line,
|
||||
};
|
||||
let spec = ChartSpec { kind, categories, series, title, legend, data_labels, cat_axis: axis(cat_a), val_axis: axis(val_a) }.sanitized();
|
||||
// Editable only when nothing would be lost: writing the model again gives the same part, as
|
||||
// this writer or the earlier one wrote it.
|
||||
let mut again = xml::parse(chart_xml(&spec).as_bytes()).ok()?;
|
||||
if same(space, &again, 0) {
|
||||
return Some(spec);
|
||||
}
|
||||
as_previous_writer(&mut again);
|
||||
same(space, &again, 0).then_some(spec)
|
||||
}
|
||||
|
||||
/// `part` (what [`chart_xml`] writes) as the earlier WordCraft writer wrote the same model: it
|
||||
/// had no axis `c:numFmt`. Only that element goes, and only with the value its absence reads as
|
||||
/// (General, linked to the source), so a part that matches still holds nothing the model leaves out.
|
||||
fn as_previous_writer(part: &mut El) {
|
||||
fn els_mut(e: &mut El) -> impl Iterator<Item = &mut El> {
|
||||
e.kids.iter_mut().filter_map(|n| match n {
|
||||
Node::El(e) => Some(e),
|
||||
Node::Text(_) => None,
|
||||
})
|
||||
}
|
||||
fn drop_els(e: &mut El, drop: impl Fn(&El) -> bool) {
|
||||
e.kids.retain(|n| !matches!(n, Node::El(c) if drop(c)));
|
||||
}
|
||||
let Some(plot) = els_mut(part).find(|e| e.name == "c:chart").and_then(|c| els_mut(c).find(|e| e.name == "c:plotArea")) else { return };
|
||||
for e in els_mut(plot) {
|
||||
if matches!(e.name.as_str(), "c:catAx" | "c:valAx") {
|
||||
drop_els(e, |c| c.name == "c:numFmt" && c.attr("sourceLinked") == Some("1"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of a `c:strLit` / `c:numLit` (or a cache) as texts by index, `ptCount` long.
|
||||
fn literal(e: &El) -> Vec<String> {
|
||||
let Some(lit) = e.els().find(|c| matches!(c.name.as_str(), "c:strLit" | "c:numLit")) else { return Vec::new() };
|
||||
@@ -461,10 +646,11 @@ mod tests {
|
||||
let spec = ChartSpec {
|
||||
kind: ChartType::Column,
|
||||
categories: (0..4500).map(|i| i.to_string()).collect(),
|
||||
series: (0..300).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 4500] }).collect(),
|
||||
series: (0..300).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 4500], ..Default::default() }).collect(),
|
||||
title: None,
|
||||
legend: None,
|
||||
data_labels: false,
|
||||
..Default::default()
|
||||
};
|
||||
let x = chart_xml(&spec);
|
||||
let series = x.matches("<c:ser>").count();
|
||||
@@ -500,6 +686,61 @@ mod tests {
|
||||
assert_eq!(spec_of(&xml::parse(x.as_bytes()).unwrap()), None);
|
||||
}
|
||||
|
||||
/// Chart parts as the previous WordCraft chart writer saved them (its output for
|
||||
/// `ChartSpec::sample`): no axis `c:numFmt`, and scatter series with no `c:marker`.
|
||||
const PREVIOUS_COLUMN: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><c:roundedCorners val="0"/><c:chart><c:autoTitleDeleted val="1"/><c:plotArea><c:layout/><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:varyColors val="0"/><c:ser><c:idx val="0"/><c:order val="0"/><c:tx><c:v>Series 1</c:v></c:tx><c:invertIfNegative val="0"/><c:cat><c:strLit><c:ptCount val="4"/><c:pt idx="0"><c:v>Q1</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt><c:pt idx="2"><c:v>Q3</c:v></c:pt><c:pt idx="3"><c:v>Q4</c:v></c:pt></c:strLit></c:cat><c:val><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>3.2</c:v></c:pt><c:pt idx="1"><c:v>4.1</c:v></c:pt><c:pt idx="2"><c:v>3.6</c:v></c:pt><c:pt idx="3"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser><c:ser><c:idx val="1"/><c:order val="1"/><c:tx><c:v>Series 2</c:v></c:tx><c:invertIfNegative val="0"/><c:cat><c:strLit><c:ptCount val="4"/><c:pt idx="0"><c:v>Q1</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt><c:pt idx="2"><c:v>Q3</c:v></c:pt><c:pt idx="3"><c:v>Q4</c:v></c:pt></c:strLit></c:cat><c:val><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>2</c:v></c:pt><c:pt idx="1"><c:v>2.7</c:v></c:pt><c:pt idx="2"><c:v>3.9</c:v></c:pt><c:pt idx="3"><c:v>3.3</c:v></c:pt></c:numLit></c:val></c:ser><c:ser><c:idx val="2"/><c:order val="2"/><c:tx><c:v>Series 3</c:v></c:tx><c:invertIfNegative val="0"/><c:cat><c:strLit><c:ptCount val="4"/><c:pt idx="0"><c:v>Q1</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt><c:pt idx="2"><c:v>Q3</c:v></c:pt><c:pt idx="3"><c:v>Q4</c:v></c:pt></c:strLit></c:cat><c:val><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>1.5</c:v></c:pt><c:pt idx="1"><c:v>2.2</c:v></c:pt><c:pt idx="2"><c:v>2.4</c:v></c:pt><c:pt idx="3"><c:v>3.8</c:v></c:pt></c:numLit></c:val></c:ser><c:gapWidth val="150"/><c:axId val="500000001"/><c:axId val="500000002"/></c:barChart><c:catAx><c:axId val="500000001"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="b"/><c:majorTickMark val="none"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:crossAx val="500000002"/><c:crosses val="autoZero"/><c:auto val="1"/><c:lblAlgn val="ctr"/><c:lblOffset val="100"/><c:noMultiLvlLbl val="0"/></c:catAx><c:valAx><c:axId val="500000002"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="l"/><c:majorGridlines/><c:majorTickMark val="none"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:spPr><a:ln><a:noFill/></a:ln></c:spPr><c:crossAx val="500000001"/><c:crosses val="autoZero"/><c:crossBetween val="between"/></c:valAx></c:plotArea><c:legend><c:legendPos val="b"/><c:overlay val="0"/></c:legend><c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart><c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill><a:ln><a:noFill/></a:ln></c:spPr></c:chartSpace>"#;
|
||||
const PREVIOUS_SCATTER: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><c:roundedCorners val="0"/><c:chart><c:autoTitleDeleted val="1"/><c:plotArea><c:layout/><c:scatterChart><c:scatterStyle val="lineMarker"/><c:varyColors val="0"/><c:ser><c:idx val="0"/><c:order val="0"/><c:tx><c:v>Series 1</c:v></c:tx><c:spPr><a:ln w="19050"><a:noFill/></a:ln></c:spPr><c:xVal><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt><c:pt idx="3"><c:v>4</c:v></c:pt></c:numLit></c:xVal><c:yVal><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>2.1</c:v></c:pt><c:pt idx="1"><c:v>3.4</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt><c:pt idx="3"><c:v>4.6</c:v></c:pt></c:numLit></c:yVal><c:smooth val="0"/></c:ser><c:ser><c:idx val="1"/><c:order val="1"/><c:tx><c:v>Series 2</c:v></c:tx><c:spPr><a:ln w="19050"><a:noFill/></a:ln></c:spPr><c:xVal><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt><c:pt idx="3"><c:v>4</c:v></c:pt></c:numLit></c:xVal><c:yVal><c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="4"/><c:pt idx="0"><c:v>1.2</c:v></c:pt><c:pt idx="1"><c:v>1.9</c:v></c:pt><c:pt idx="2"><c:v>2.8</c:v></c:pt><c:pt idx="3"><c:v>3.1</c:v></c:pt></c:numLit></c:yVal><c:smooth val="0"/></c:ser><c:axId val="500000001"/><c:axId val="500000002"/></c:scatterChart><c:valAx><c:axId val="500000001"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="b"/><c:majorTickMark val="none"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:crossAx val="500000002"/><c:crosses val="autoZero"/><c:crossBetween val="midCat"/></c:valAx><c:valAx><c:axId val="500000002"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="l"/><c:majorGridlines/><c:majorTickMark val="none"/><c:minorTickMark val="none"/><c:tickLblPos val="nextTo"/><c:spPr><a:ln><a:noFill/></a:ln></c:spPr><c:crossAx val="500000001"/><c:crosses val="autoZero"/><c:crossBetween val="midCat"/></c:valAx></c:plotArea><c:legend><c:legendPos val="b"/><c:overlay val="0"/></c:legend><c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart><c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill><a:ln><a:noFill/></a:ln></c:spPr></c:chartSpace>"#;
|
||||
|
||||
#[test]
|
||||
fn charts_saved_by_the_previous_writer_stay_editable() {
|
||||
for (x, kind) in [(PREVIOUS_COLUMN, ChartType::Column), (PREVIOUS_SCATTER, ChartType::Scatter)] {
|
||||
let spec = spec_of(&xml::parse(x.as_bytes()).unwrap()).unwrap_or_else(|| panic!("{kind:?}: the earlier part is read-only"));
|
||||
assert_eq!((spec.kind, spec.series.len()), (kind, if kind == ChartType::Scatter { 2 } else { 3 }));
|
||||
assert_eq!((spec.cat_axis.fmt.as_deref(), spec.val_axis.fmt.as_deref()), (None, None), "{kind:?}");
|
||||
assert!(spec.series.iter().all(|s| s.markers.is_none()), "{kind:?}: markers unset");
|
||||
// Saved again, it is in the current shape and still reads back as the same model.
|
||||
assert_eq!(spec_of(&parse(&spec)).as_ref(), Some(&spec), "{kind:?}");
|
||||
}
|
||||
// What neither writer writes still keeps such a part read-only: an axis format linked to
|
||||
// the source that isn't General, a scatter marker other than the default, a marker size.
|
||||
let edited = |x: &str, from: &str, to: &str| {
|
||||
assert!(x.contains(from), "{from}");
|
||||
spec_of(&xml::parse(x.replacen(from, to, 1).as_bytes()).unwrap())
|
||||
};
|
||||
let ax = r#"<c:axPos val="l"/><c:majorGridlines/>"#;
|
||||
assert_eq!(edited(PREVIOUS_COLUMN, ax, &format!(r#"{ax}<c:numFmt formatCode="0.0" sourceLinked="1"/>"#)), None);
|
||||
let ln = r#"<a:ln w="19050"><a:noFill/></a:ln></c:spPr>"#;
|
||||
assert_eq!(edited(PREVIOUS_SCATTER, ln, &format!(r#"{ln}<c:marker><c:symbol val="square"/></c:marker>"#)), None);
|
||||
assert_eq!(edited(PREVIOUS_SCATTER, ln, &format!(r#"{ln}<c:marker><c:symbol val="circle"/><c:size val="9"/></c:marker>"#)), None);
|
||||
assert_eq!(edited(PREVIOUS_COLUMN, "<c:roundedCorners val=\"0\"/>", "<c:roundedCorners val=\"0\"/><c:style val=\"2\"/>"), None);
|
||||
}
|
||||
|
||||
/// A scatter series with no `c:marker` (Word's automatic symbols) stays without one after an
|
||||
/// unrelated edit and a save; an explicit circle or "none" stays explicit.
|
||||
#[test]
|
||||
fn scatter_series_without_a_marker_stay_without_after_a_save() {
|
||||
let marker_of = |x: &El| -> Vec<Option<String>> {
|
||||
let sc = x.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:scatterChart").unwrap();
|
||||
sc.children("c:ser").map(|s| s.child("c:marker").map(|m| m.child("c:symbol").unwrap().attr("val").unwrap().to_string())).collect()
|
||||
};
|
||||
let mut spec = spec_of(&xml::parse(PREVIOUS_SCATTER.as_bytes()).unwrap()).unwrap();
|
||||
assert_eq!(marker_of(&xml::parse(PREVIOUS_SCATTER.as_bytes()).unwrap()), [None, None]);
|
||||
spec.title = Some("Edited".into());
|
||||
spec.series[0].name = "Renamed".into();
|
||||
let saved = parse(&spec);
|
||||
assert_eq!(marker_of(&saved), [None, None]);
|
||||
let again = spec_of(&saved).unwrap();
|
||||
assert_eq!(again, spec);
|
||||
assert!(again.series.iter().all(|s| s.markers.is_none()));
|
||||
// Explicit choices are kept as written.
|
||||
spec.series[0].markers = Some(true);
|
||||
spec.series[1].markers = Some(false);
|
||||
let saved = parse(&spec);
|
||||
assert_eq!(marker_of(&saved), [Some("circle".to_string()), Some("none".to_string())]);
|
||||
let again = spec_of(&saved).unwrap();
|
||||
assert_eq!((again.series[0].markers, again.series[1].markers), (Some(true), Some(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elements_come_in_schema_order() {
|
||||
let mut spec = ChartSpec::sample(ChartType::ColumnStacked);
|
||||
@@ -517,6 +758,11 @@ mod tests {
|
||||
["c:barDir", "c:grouping", "c:varyColors", "c:ser", "c:ser", "c:ser", "c:dLbls", "c:gapWidth", "c:overlap", "c:axId", "c:axId"]
|
||||
);
|
||||
assert_eq!(names(bar.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:invertIfNegative", "c:cat", "c:val"]);
|
||||
// A series with its own labels keeps `c:invertIfNegative` ahead of `c:dLbls` (CT_BarSer).
|
||||
spec.series[0].labels = Some(true);
|
||||
let labelled = parse(&spec);
|
||||
let ser = labelled.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:barChart").unwrap().child("c:ser").unwrap();
|
||||
assert_eq!(names(ser), ["c:idx", "c:order", "c:tx", "c:invertIfNegative", "c:dLbls", "c:cat", "c:val"]);
|
||||
let val_ax = plot.child("c:valAx").unwrap();
|
||||
assert_eq!(
|
||||
names(val_ax),
|
||||
@@ -526,6 +772,7 @@ mod tests {
|
||||
"c:delete",
|
||||
"c:axPos",
|
||||
"c:majorGridlines",
|
||||
"c:numFmt",
|
||||
"c:majorTickMark",
|
||||
"c:minorTickMark",
|
||||
"c:tickLblPos",
|
||||
@@ -535,13 +782,35 @@ mod tests {
|
||||
"c:crossBetween"
|
||||
]
|
||||
);
|
||||
let cat_ax = plot.child("c:catAx").unwrap();
|
||||
assert_eq!(
|
||||
names(cat_ax),
|
||||
[
|
||||
"c:axId",
|
||||
"c:scaling",
|
||||
"c:delete",
|
||||
"c:axPos",
|
||||
"c:numFmt",
|
||||
"c:majorTickMark",
|
||||
"c:minorTickMark",
|
||||
"c:tickLblPos",
|
||||
"c:crossAx",
|
||||
"c:crosses",
|
||||
"c:auto",
|
||||
"c:lblAlgn",
|
||||
"c:lblOffset",
|
||||
"c:noMultiLvlLbl"
|
||||
]
|
||||
);
|
||||
let line = parse(&ChartSpec { data_labels: true, ..ChartSpec::sample(ChartType::Line) });
|
||||
let lc = line.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:lineChart").unwrap();
|
||||
assert_eq!(names(lc), ["c:grouping", "c:varyColors", "c:ser", "c:ser", "c:ser", "c:dLbls", "c:marker", "c:axId", "c:axId"]);
|
||||
assert_eq!(names(lc.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:marker", "c:cat", "c:val", "c:smooth"]);
|
||||
let sc = parse(&ChartSpec::sample(ChartType::Scatter));
|
||||
let mut scatter = ChartSpec::sample(ChartType::Scatter);
|
||||
scatter.series.iter_mut().for_each(|s| s.markers = Some(true));
|
||||
let sc = parse(&scatter);
|
||||
let sc = sc.child("c:chart").unwrap().child("c:plotArea").unwrap().child("c:scatterChart").unwrap();
|
||||
assert_eq!(names(sc.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:spPr", "c:xVal", "c:yVal", "c:smooth"]);
|
||||
assert_eq!(names(sc.child("c:ser").unwrap()), ["c:idx", "c:order", "c:tx", "c:spPr", "c:marker", "c:xVal", "c:yVal", "c:smooth"]);
|
||||
let dn = parse(&ChartSpec::sample(ChartType::Doughnut));
|
||||
let dn = dn.child("c:chart").unwrap().child("c:plotArea").unwrap();
|
||||
assert_eq!(names(dn), ["c:layout", "c:doughnutChart"]);
|
||||
|
||||
@@ -29,7 +29,9 @@ pub(super) use canvas::text_w;
|
||||
use canvas::{Rect, clip_text, legend, text};
|
||||
#[cfg(test)]
|
||||
use format::{civil, excel_stamp, format_value};
|
||||
use model::{Axis, Grouping, Kind, Pos, Series};
|
||||
pub(crate) use model::Axis;
|
||||
use model::{Grouping, Kind, Pos, Series};
|
||||
pub(crate) use parse::chart_axes;
|
||||
#[cfg(test)]
|
||||
use parse::{axis, category_text, labels, numbers};
|
||||
use parse::{read_series, text_size, title_of};
|
||||
|
||||
@@ -41,8 +41,13 @@ pub(super) fn widest(items: &[String], size: f32) -> f32 {
|
||||
items.iter().map(|s| text_w(s, size)).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// Text in `rect`; `angle` degrees clockwise turns it about the rect's centre (axis titles).
|
||||
pub(super) fn text(out: &mut Vec<GraphicItem>, rect: Rect, s: &str, size: f32, align: TextAlign, bold: bool) {
|
||||
out.push(GraphicItem::Text { rect: rect.arr(), text: s.to_string(), size, color: TEXT, bold, align, font: None });
|
||||
text_angle(out, rect, s, size, align, bold, 0.0);
|
||||
}
|
||||
|
||||
pub(super) fn text_angle(out: &mut Vec<GraphicItem>, rect: Rect, s: &str, size: f32, align: TextAlign, bold: bool, angle: f32) {
|
||||
out.push(GraphicItem::Text { rect: rect.arr(), text: s.to_string(), size, color: TEXT, bold, align, font: None, angle });
|
||||
}
|
||||
|
||||
/// Text centred on `cx` with its top at `y`.
|
||||
|
||||
@@ -52,16 +52,21 @@ pub(super) enum Pos {
|
||||
|
||||
/// One value axis (or category axis) as the file states it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Axis {
|
||||
pub(super) deleted: bool,
|
||||
pub(super) grid: bool,
|
||||
pub(super) line: bool,
|
||||
pub(crate) struct Axis {
|
||||
pub(crate) deleted: bool,
|
||||
pub(crate) grid: bool,
|
||||
pub(crate) line: bool,
|
||||
/// `c:crossBetween val="midCat"`: categories sit on the tick marks, not between them.
|
||||
pub(super) mid: bool,
|
||||
pub(super) min: Option<f64>,
|
||||
pub(super) max: Option<f64>,
|
||||
pub(crate) min: Option<f64>,
|
||||
pub(crate) max: Option<f64>,
|
||||
/// Number format of the tick labels, when not linked to the source data.
|
||||
pub(super) fmt: Option<String>,
|
||||
pub(crate) fmt: Option<String>,
|
||||
/// The axis title, when the file gives it one.
|
||||
pub(crate) title: Option<String>,
|
||||
/// Tick labels, as `c:tickLblPos` says (`none` hides them; a file that says nothing shows
|
||||
/// them, as Word does).
|
||||
pub(crate) labels: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Series {
|
||||
@@ -70,9 +75,17 @@ pub(super) struct Series {
|
||||
/// when missing or not a valid number.
|
||||
pub(super) idx: Option<usize>,
|
||||
pub(super) color: Option<Rgb>,
|
||||
pub(super) line_w: f32,
|
||||
/// Fixed line width in points, `None`: the chart's default.
|
||||
pub(super) line_w: Option<f32>,
|
||||
/// Whether the series is drawn as a line (scatter series without one get markers).
|
||||
pub(super) line: bool,
|
||||
/// The series' own fill: `Some` colour, `None` colour with `no_fill` set, else the chart's
|
||||
/// accent for the series.
|
||||
pub(super) no_fill: bool,
|
||||
/// Markers on the series' points, when the file says.
|
||||
pub(super) markers: Option<bool>,
|
||||
/// Draw the series' line as a smooth curve (`c:smooth`).
|
||||
pub(super) smooth: bool,
|
||||
pub(super) values: Vec<Option<f64>>,
|
||||
/// Scatter x values (index + 1 when the file has none).
|
||||
pub(super) xs: Vec<Option<f64>>,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::format::{date_text, excel_stamp, format_value, is_date_code};
|
||||
use super::model::{Axis, Grouping, Kind, Pos, Series};
|
||||
use super::plot::label;
|
||||
use super::{Chart, El, FONT, LINE_W, MAX_CELLS, MAX_POINTS, MAX_RADAR_SERIES, MAX_SERIES, MAX_SPOKES, Rgb, fill_colour, int, measure, slot};
|
||||
use super::{Chart, El, FONT, MAX_CELLS, MAX_POINTS, MAX_RADAR_SERIES, MAX_SERIES, MAX_SPOKES, Rgb, fill_colour, int, measure, slot};
|
||||
|
||||
impl Chart {
|
||||
pub(super) fn parse(space: &El, theme: &[Rgb]) -> Option<Chart> {
|
||||
@@ -149,7 +149,7 @@ fn to_percent(series: &mut [Series], n: usize) {
|
||||
}
|
||||
|
||||
/// The category axis (scatter: the horizontal value axis) and the value axis of a plot area.
|
||||
fn chart_axes(plot: &El, scatter: bool) -> (Axis, Axis) {
|
||||
pub(crate) fn chart_axes(plot: &El, scatter: bool) -> (Axis, Axis) {
|
||||
let vals_ax: Vec<&El> = plot.children("c:valAx").collect();
|
||||
let horiz_pos = |a: &&El| matches!(a.child("c:axPos").and_then(|p| p.attr("val")), Some("b" | "t"));
|
||||
let (val_el, x_el) = if scatter {
|
||||
@@ -207,8 +207,14 @@ impl Series {
|
||||
let ln = sp.and_then(|p| p.child("a:ln"));
|
||||
let marker = ser.child("c:marker").and_then(|m| m.child("c:spPr")).and_then(|p| fill_colour(p, theme));
|
||||
let color = sp.and_then(|p| fill_colour(p, theme)).or_else(|| ln.and_then(|l| fill_colour(l, theme))).or(marker);
|
||||
let line_w = ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).map_or(LINE_W, |w| w.clamp(0.0, 20.0));
|
||||
let no_fill = sp.and_then(|p| p.child("a:noFill")).is_some();
|
||||
let line_w = ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).map(|w| w.clamp(0.0, 20.0));
|
||||
let line = ln.is_none_or(|l| l.child("a:noFill").is_none());
|
||||
// `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 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) };
|
||||
if scatter && xs.is_empty() {
|
||||
@@ -223,7 +229,7 @@ impl Series {
|
||||
}
|
||||
}
|
||||
let labels = show_values(ser.child("c:dLbls"));
|
||||
Series { name, idx, color, line_w, line, values, xs, points, fmt, x_fmt, labels, raw: Vec::new() }
|
||||
Series { name, idx, color, line_w, line, no_fill, markers, smooth, values, xs, points, fmt, x_fmt, labels, raw: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +296,7 @@ fn pts(cache: &El, cap: usize) -> Vec<Option<String>> {
|
||||
}
|
||||
|
||||
pub(super) fn axis(a: Option<&El>) -> Axis {
|
||||
let Some(a) = a else { return Axis { deleted: true, ..Default::default() } };
|
||||
let Some(a) = a else { return Axis { deleted: true, labels: true, line: true, ..Default::default() } };
|
||||
let scaling = a.child("c:scaling");
|
||||
let num =
|
||||
|n: &str| scaling.and_then(|s| s.child(n)).and_then(|e| e.attr("val")).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite());
|
||||
@@ -307,6 +313,8 @@ pub(super) fn axis(a: Option<&El>) -> Axis {
|
||||
.and_then(|f| f.attr("formatCode"))
|
||||
.filter(|f| f.len() <= MAX_FORMAT_CODE)
|
||||
.map(str::to_string),
|
||||
title: a.child("c:title").and_then(title_text),
|
||||
labels: a.child("c:tickLblPos").and_then(|p| p.attr("val")) != Some("none"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::canvas::{Rect, fill, rect_segs, runs, seg, stroke, text, text_at, text_w, widest, wrap};
|
||||
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::parse::category_text;
|
||||
use super::polar::{draw_data_labels, label_of};
|
||||
use super::{AXIS, Chart, El, GAP, GRID, GraphicItem, LINE, MAX_LABEL, MAX_TICKS, PathSeg, Rgb, ShapeKind, TextAlign, fill_colour, measure};
|
||||
use super::{AXIS, Chart, El, GAP, GRID, GraphicItem, LINE, LINE_W, MAX_LABEL, MAX_TICKS, PathSeg, Rgb, ShapeKind, TextAlign, fill_colour, measure};
|
||||
|
||||
pub(super) fn label(s: &str) -> String {
|
||||
s.chars().take(MAX_LABEL).collect()
|
||||
@@ -151,21 +151,23 @@ struct Margins {
|
||||
}
|
||||
|
||||
/// The margins the axis labels need around the plot in `area`. Category labels under a column
|
||||
/// chart wrap to the band; labels that still don't fit show every k-th category.
|
||||
/// chart wrap to the band; labels that still don't fit show every k-th category. Hidden tick
|
||||
/// labels take no room; an axis title adds one line on its side.
|
||||
fn axis_margins(c: &Chart, ax: &Axes, area: Rect) -> Margins {
|
||||
let fs = c.text_size;
|
||||
let lh = fs * LINE;
|
||||
let scatter = c.kind == Kind::Scatter;
|
||||
let (cat_on, val_on) = (!c.cat.deleted, !c.val.deleted);
|
||||
let (cat_labels, val_labels) = (cat_on && c.cat.labels, val_on && c.val.labels);
|
||||
let left = if c.horizontal {
|
||||
if cat_on { widest(&c.cats, fs).min(area.w * 0.4) + GAP } else { 0.0 }
|
||||
} else if val_on {
|
||||
if cat_labels { widest(&c.cats, fs).min(area.w * 0.4) + GAP } else { 0.0 }
|
||||
} else if val_labels {
|
||||
ax.vticks.iter().map(|(_, s)| text_w(s, fs)).fold(0.0, f32::max) + GAP
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
} + title_left(c, cat_on, val_on, lh);
|
||||
let band_w = (area.w - left).max(1.0) / c.n as f32;
|
||||
let wrapped: Vec<Vec<String>> = if cat_on && !scatter {
|
||||
let wrapped: Vec<Vec<String>> = if cat_labels && !scatter {
|
||||
let width = if c.horizontal { left - GAP } else { band_w };
|
||||
c.cats.iter().map(|s| wrap(s, width, fs)).collect()
|
||||
} else {
|
||||
@@ -174,17 +176,31 @@ fn axis_margins(c: &Chart, ax: &Axes, area: Rect) -> Margins {
|
||||
let widest_line = wrapped.iter().flatten().map(|s| text_w(s, fs)).fold(0.0, f32::max);
|
||||
let skip = ((widest_line / band_w).ceil() as usize).max(1);
|
||||
let label_lines = wrapped.iter().map(Vec::len).max().unwrap_or(1) as f32;
|
||||
let bottom = if cat_on && !c.horizontal {
|
||||
let bottom = (if cat_labels && !c.horizontal {
|
||||
if scatter { lh + GAP } else { label_lines * lh + GAP }
|
||||
} else if c.horizontal && val_on {
|
||||
} else if c.horizontal && val_labels {
|
||||
lh + GAP
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let top = if !c.horizontal && val_on { lh / 2.0 } else { 0.0 };
|
||||
}) + title_bottom(c, cat_on, val_on, lh);
|
||||
let top = if !c.horizontal && val_labels { lh / 2.0 } else { 0.0 };
|
||||
Margins { left, top, bottom, wrapped, skip }
|
||||
}
|
||||
|
||||
/// Room for the vertical axis title on the plot's left: one line when the axis that sits there
|
||||
/// (the value axis for columns, the category axis for bars) has a title.
|
||||
fn title_left(c: &Chart, cat_on: bool, val_on: bool, lh: f32) -> f32 {
|
||||
let side = if c.horizontal { cat_on && c.cat.title.is_some() } else { val_on && c.val.title.is_some() };
|
||||
if side { lh } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Room for the horizontal axis title under the plot: one line when the axis that sits there
|
||||
/// (the category axis for columns, the value axis for bars) has a title.
|
||||
fn title_bottom(c: &Chart, cat_on: bool, val_on: bool, lh: f32) -> f32 {
|
||||
let side = if c.horizontal { val_on && c.val.title.is_some() } else { cat_on && c.cat.title.is_some() };
|
||||
if side { lh } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A bar, column, line, area or scatter chart in `area`: gridlines, series, axes, then labels.
|
||||
pub(super) fn cartesian(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
if c.n == 0 {
|
||||
@@ -200,6 +216,9 @@ pub(super) fn cartesian(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
if c.val.grid {
|
||||
draw_grid(out, &g, &ax.vticks);
|
||||
}
|
||||
if c.cat.grid {
|
||||
draw_cat_grid(out, &g, &ax.xticks, c.kind == Kind::Scatter);
|
||||
}
|
||||
let mut labels = Vec::new();
|
||||
match c.kind {
|
||||
Kind::Bar => bars(out, c, &g, &mut labels),
|
||||
@@ -210,12 +229,36 @@ pub(super) fn cartesian(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
}
|
||||
draw_axes(out, c, &g);
|
||||
draw_data_labels(out, &labels, c.text_size, g.horiz && c.kind == Kind::Bar);
|
||||
if !c.val.deleted {
|
||||
draw_value_labels(out, c, &g, &ax.vticks, Rect { w: m.left, ..area });
|
||||
if !c.val.deleted && c.val.labels {
|
||||
let room = title_left(c, !c.cat.deleted, true, c.text_size * LINE);
|
||||
draw_value_labels(out, c, &g, &ax.vticks, Rect { x: area.x + room, w: m.left - room, ..area });
|
||||
}
|
||||
if !c.cat.deleted {
|
||||
if !c.cat.deleted && c.cat.labels {
|
||||
draw_category_labels(out, c, &g, &ax.xticks, &m, area);
|
||||
}
|
||||
draw_axis_titles(out, c, &g, area);
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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) };
|
||||
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);
|
||||
}
|
||||
if !bottom.deleted
|
||||
&& let Some(t) = &bottom.title
|
||||
{
|
||||
let t = clip_text(t, g.plot.w, c.text_size);
|
||||
text_angle(out, Rect { x: g.plot.x, y: area.bottom() - lh, w: g.plot.w, h: lh }, &t, c.text_size, TextAlign::Center, false, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Major gridlines at the value ticks.
|
||||
@@ -228,6 +271,24 @@ fn draw_grid(out: &mut Vec<GraphicItem>, g: &Frame, ticks: &[(f64, String)]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gridlines along the category axis: across the plot at each category's centre, at the x ticks
|
||||
/// of a scatter chart.
|
||||
fn draw_cat_grid(out: &mut Vec<GraphicItem>, g: &Frame, xticks: &[(f64, String)], scatter: bool) {
|
||||
let plot = g.plot;
|
||||
if scatter {
|
||||
for (t, _) in xticks {
|
||||
let p = g.scat_x(*t);
|
||||
stroke(out, seg(p, plot.y, p, plot.bottom()), GRID, 0.75);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for i in 0..g.n {
|
||||
let p = g.band_start(i) + g.band() / 2.0;
|
||||
let segs = if g.horiz { seg(plot.x, p, plot.right(), p) } else { seg(p, plot.y, p, plot.bottom()) };
|
||||
stroke(out, segs, GRID, 0.75);
|
||||
}
|
||||
}
|
||||
|
||||
/// The category axis line, the plot area's outline and the value axis line, as the file shows them.
|
||||
fn draw_axes(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame) {
|
||||
let plot = g.plot;
|
||||
@@ -361,7 +422,9 @@ fn bars(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<DataL
|
||||
let (p0, p1) = (g.val(v0), g.val(v1));
|
||||
let (p0, p1) = (p0.min(p1), p0.max(p1));
|
||||
let segs = if g.horiz { rect_segs(p0, a, p1, a + thick) } else { rect_segs(a, p0, a + thick, p1) };
|
||||
fill(out, segs, c.point_colour(j, i));
|
||||
if !s.no_fill {
|
||||
fill(out, segs, c.point_colour(j, i));
|
||||
}
|
||||
if let Some(text) = label_of(s, i) {
|
||||
let mid = a + thick / 2.0;
|
||||
let (x, y) = match (g.horiz, stacked) {
|
||||
@@ -404,10 +467,64 @@ fn lines(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<Data
|
||||
labels.push(DataLabel { x: *x, y: *y, text, inside: false });
|
||||
}
|
||||
}
|
||||
stroke(out, runs(pts.into_iter()), c.series_colour(j), s.line_w);
|
||||
if s.line {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
const MARKER: f32 = 6.0;
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// A polyline through `pts`, a smooth curve (Catmull-Rom pieces) when `smooth` and there are at
|
||||
/// least three points in a row; gaps (`None`) end a run.
|
||||
fn curve(pts: impl Iterator<Item = Option<(f32, f32)>>, smooth: bool) -> Vec<PathSeg> {
|
||||
if !smooth {
|
||||
return runs(pts);
|
||||
}
|
||||
let pts: Vec<Option<(f32, f32)>> = pts.collect();
|
||||
let mut segs = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < pts.len() {
|
||||
let Some(first) = pts[i] else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
// Collect one run of points.
|
||||
let mut run = vec![first];
|
||||
while let Some(p) = pts.get(i + 1).copied().flatten() {
|
||||
run.push(p);
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
if run.len() < 3 {
|
||||
segs.extend(runs(run.into_iter().map(Some)));
|
||||
continue;
|
||||
}
|
||||
segs.push(PathSeg::Move(run[0].0, run[0].1));
|
||||
for k in 0..run.len() - 1 {
|
||||
// Catmull-Rom: tangent at p1 from p0 to p2 (ends mirror their own tangent).
|
||||
let p0 = run[k.max(1) - 1];
|
||||
let p1 = run[k];
|
||||
let p2 = run[k + 1];
|
||||
let p3 = run.get(k + 2).copied().unwrap_or(p2);
|
||||
let c1 = (p1.0 + (p2.0 - p0.0) / 6.0, p1.1 + (p2.1 - p0.1) / 6.0);
|
||||
let c2 = (p2.0 - (p3.0 - p1.0) / 6.0, p2.1 - (p3.1 - p1.1) / 6.0);
|
||||
segs.push(PathSeg::Cubic(c1.0, c1.1, c2.0, c2.1, p2.0, p2.1));
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
fn areas(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<DataLabel>) {
|
||||
let mut base = vec![0.0f64; g.n];
|
||||
for (j, s) in c.series.iter().enumerate().filter(|(_, s)| has_values(s)) {
|
||||
@@ -434,7 +551,7 @@ fn areas(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<Data
|
||||
}
|
||||
}
|
||||
|
||||
/// Scatter series as lines, or as small markers when the series has no line.
|
||||
/// Scatter series as lines, and as small markers when the series asks for them.
|
||||
fn draw_scatter(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<DataLabel>) {
|
||||
const MARKER: f32 = 6.0;
|
||||
for (j, s) in c.series.iter().enumerate() {
|
||||
@@ -452,12 +569,13 @@ fn draw_scatter(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut V
|
||||
}
|
||||
}
|
||||
if s.line {
|
||||
stroke(out, runs(pts.iter().copied()), c.series_colour(j), s.line_w);
|
||||
continue;
|
||||
stroke(out, curve(pts.iter().copied(), s.smooth), c.series_colour(j), s.line_w.unwrap_or(LINE_W));
|
||||
}
|
||||
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 });
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use super::canvas::{Rect, clip_text, fill, stroke, text, text_w, widest};
|
||||
use super::format::format_value;
|
||||
use super::model::{DataLabel, Kind, Series};
|
||||
use super::plot::{Axes, has_values};
|
||||
use super::{Chart, FRAC_PI_2, GAP, GRID, GraphicItem, LINE, PathSeg, Rgb, ShapeKind, TAU, TEXT, TextAlign};
|
||||
use super::{Chart, FRAC_PI_2, GAP, GRID, GraphicItem, LINE, LINE_W, PathSeg, Rgb, ShapeKind, TAU, TEXT, TextAlign};
|
||||
|
||||
pub(super) fn pie(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
let Some(s) = c.series.first() else { return };
|
||||
@@ -92,7 +92,7 @@ pub(super) fn radar(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
if c.radar_fill {
|
||||
fill(out, segs.clone(), col);
|
||||
}
|
||||
stroke(out, segs, col, s.line_w);
|
||||
stroke(out, segs, col, s.line_w.unwrap_or(LINE_W));
|
||||
for (i, p) in ring.iter().enumerate() {
|
||||
if c.radar_marks && s.values.get(i).copied().flatten().is_some() {
|
||||
let rect = [p.0 as f32 - MARKER / 2.0, p.1 as f32 - MARKER / 2.0, MARKER, MARKER];
|
||||
@@ -171,7 +171,7 @@ pub(super) fn draw_data_labels(out: &mut Vec<GraphicItem>, labels: &[DataLabel],
|
||||
(Rect { x: l.x - w / 2.0, y: l.y - lh, w, h: lh }, TextAlign::Center)
|
||||
};
|
||||
let color = if l.inside { Rgb::WHITE } else { TEXT };
|
||||
out.push(GraphicItem::Text { rect: rect.arr(), text: l.text.clone(), size: fs, color, bold: false, align, font: None });
|
||||
out.push(GraphicItem::Text { rect: rect.arr(), text: l.text.clone(), size: fs, color, bold: false, align, font: None, angle: 0.0 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -463,7 +463,16 @@ fn text(sp: &El, xf: Xf, b: [f64; 4], theme: &[Rgb], filled: bool, fit: f32, out
|
||||
let mut y = y0 + (th - total) / 2.0;
|
||||
for l in lines {
|
||||
let lh = l.size * LINE;
|
||||
out.push(GraphicItem::Text { rect: [x0, y, tw, lh], text: l.text, size: l.size, color: l.color, bold: l.bold, align: l.align, font: l.font });
|
||||
out.push(GraphicItem::Text {
|
||||
rect: [x0, y, tw, lh],
|
||||
text: l.text,
|
||||
size: l.size,
|
||||
color: l.color,
|
||||
bold: l.bold,
|
||||
align: l.align,
|
||||
font: l.font,
|
||||
angle: 0.0,
|
||||
});
|
||||
y += lh;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -884,10 +884,11 @@ mod tests {
|
||||
let spec = ChartSpec {
|
||||
kind: ChartType::Column,
|
||||
categories: vec!["a".into(), "b".into()],
|
||||
series: (0..series).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 2] }).collect(),
|
||||
series: (0..series).map(|i| ChartSeries { name: format!("S{i}"), values: vec![Some(1.0); 2], ..Default::default() }).collect(),
|
||||
title: None,
|
||||
legend: None,
|
||||
data_labels: false,
|
||||
..Default::default()
|
||||
};
|
||||
let graphic = Graphic { kind: GraphicKind::Chart, w: 100.0, h: 100.0, chart: Some(Arc::new(spec)), ..Default::default() };
|
||||
InlineObject::Graphic { w: 100.0, h: 100.0, alt: String::new(), float: Default::default(), graphic: Arc::new(graphic) }
|
||||
|
||||
@@ -749,7 +749,7 @@ fn graphic_group(
|
||||
let inline = Inline::Shape { kind: *kind, w: rect[2] * sx, h: rect[3] * sy, float: None, blocks: Vec::new(), look, path: None };
|
||||
Some(Member { x: rect[0] * sx, y: rect[1] * sy, inline })
|
||||
}
|
||||
GraphicItem::Text { rect, text, size, color, bold, align, font } if finite(rect) && !text.trim().is_empty() => {
|
||||
GraphicItem::Text { rect, text, size, color, bold, align, font, .. } if finite(rect) && !text.trim().is_empty() => {
|
||||
let size = if size.is_finite() { size.clamp(1.0, 400.0) } else { 11.0 };
|
||||
// One line, centred vertically in its place as the graphic draws it.
|
||||
let line = size * 1.2;
|
||||
|
||||
@@ -229,7 +229,7 @@ impl Reader {
|
||||
};
|
||||
let name = s.label.as_deref().and_then(|a| cells_of(a).first().copied()).map(|at| label(self.cell(at))).unwrap_or_default();
|
||||
let name = if name.is_empty() { format!("Series {}", i + 1) } else { name };
|
||||
ChartSeries { name, values }
|
||||
ChartSeries { name, values, ..Default::default() }
|
||||
})
|
||||
.collect();
|
||||
// A scatter chart's x values: its first series' domain.
|
||||
@@ -248,7 +248,10 @@ impl Reader {
|
||||
_ => LegendPos::Right,
|
||||
});
|
||||
let title = self.title.as_deref().map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
|
||||
Some(ChartSpec { kind, categories, series, title, legend, data_labels }.sanitized())
|
||||
// ODF axis formatting is not read; the value axis keeps the look every chart had before
|
||||
// axes were formattable (gridlines, no axis line), a round chart has none.
|
||||
let val_axis = if kind.is_round() { Default::default() } else { craft_wordmodel::chart::value_axis() };
|
||||
Some(ChartSpec { kind, categories, series, title, legend, data_labels, val_axis, ..Default::default() }.sanitized())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,8 @@ fn spec(chart: &str) -> Option<ChartSpec> {
|
||||
|
||||
fn north_south() -> Vec<ChartSeries> {
|
||||
vec![
|
||||
ChartSeries { name: "North".into(), values: vec![Some(10.0), Some(14.0), Some(8.0), Some(16.0)] },
|
||||
ChartSeries { name: "South".into(), values: vec![Some(12.0), None, Some(11.0), Some(13.0)] },
|
||||
ChartSeries { name: "North".into(), values: vec![Some(10.0), Some(14.0), Some(8.0), Some(16.0)], ..Default::default() },
|
||||
ChartSeries { name: "South".into(), values: vec![Some(12.0), None, Some(11.0), Some(13.0)], ..Default::default() },
|
||||
]
|
||||
}
|
||||
|
||||
@@ -78,6 +78,8 @@ fn a_column_chart_reads_its_data_title_and_legend() {
|
||||
title: Some("Sales by quarter".into()),
|
||||
legend: Some(LegendPos::Right),
|
||||
data_labels: false,
|
||||
val_axis: craft_wordmodel::chart::value_axis(),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
// The frame's size, in points.
|
||||
@@ -135,7 +137,7 @@ fn line_area_pie_doughnut_and_scatter_classes() {
|
||||
let s = spec(&chart_xml("chart:scatter", "", "", "", scatter)).unwrap();
|
||||
assert_eq!(s.kind, ChartType::Scatter);
|
||||
assert_eq!(s.categories, vec!["10", "14", "8", "16"]);
|
||||
assert_eq!(s.series, vec![ChartSeries { name: "South".into(), values: vec![Some(12.0), None, Some(11.0), Some(13.0)] }]);
|
||||
assert_eq!(s.series, vec![ChartSeries { name: "South".into(), values: vec![Some(12.0), None, Some(11.0), Some(13.0)], ..Default::default() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -249,7 +251,15 @@ fn every_chart_type_is_saved_as_a_chart_object_and_reads_back() {
|
||||
let bytes = crate::text::export(&doc_with(spec.clone(), false)).unwrap();
|
||||
let back = reread(&bytes);
|
||||
assert_eq!(back.len(), 1, "{kind:?}");
|
||||
assert_eq!(*back[0].spec, spec.clone().sanitized(), "{kind:?}");
|
||||
// ODF keeps no series or axis formatting here: only the data, the title and the legend
|
||||
// come back; the value axis has the gridlines every chart had before axes were formattable.
|
||||
let mut expected = spec.clone().sanitized();
|
||||
for s in &mut expected.series {
|
||||
*s = ChartSeries { name: std::mem::take(&mut s.name), values: std::mem::take(&mut s.values), ..Default::default() };
|
||||
}
|
||||
expected.cat_axis = Default::default();
|
||||
expected.val_axis = if kind.is_round() { Default::default() } else { craft_wordmodel::chart::value_axis() };
|
||||
assert_eq!(*back[0].spec, expected, "{kind:?}");
|
||||
assert_eq!((back[0].w, back[0].h, back[0].alt.as_str()), (300.0, 180.0, "Sales chart"), "{kind:?}");
|
||||
// The package lists the chart object.
|
||||
let z = crate::Package::open(&bytes, &crate::Limits::DEFAULT).unwrap();
|
||||
|
||||
@@ -130,6 +130,7 @@ fn a_diagram_is_saved_as_a_group_of_its_drawing() {
|
||||
bold: false,
|
||||
align: TextAlign::Center,
|
||||
font: None,
|
||||
angle: 0.0,
|
||||
},
|
||||
GraphicItem::Shape { rect: [90.0, 9.0, 18.0, 18.0], kind: ShapeKind::Arrow, fill: Some(blue), stroke: None, stroke_width: 0.0 },
|
||||
],
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::props::Rgb;
|
||||
|
||||
/// Most series in a chart.
|
||||
pub const MAX_SERIES: usize = 255;
|
||||
/// Most categories (points per series) in a chart.
|
||||
@@ -123,13 +125,107 @@ impl LegendPos {
|
||||
}
|
||||
}
|
||||
|
||||
/// One series: its name and a value per category (`None` = no value, a gap).
|
||||
/// One series: its name, a value per category (`None` = no value, a gap) and how it is drawn
|
||||
/// (Chart Design ▸ Format Series): fill, line, markers, smooth lines, its own data labels and
|
||||
/// number format. Unset fields follow the chart's defaults.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartSeries {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub values: Vec<Option<f64>>,
|
||||
/// Fill colour; `None`: the chart's accent colour for the series.
|
||||
#[serde(default)]
|
||||
pub fill: Option<Rgb>,
|
||||
/// "None" fill: the series draws no fill.
|
||||
#[serde(default)]
|
||||
pub no_fill: bool,
|
||||
/// Line width in points; `None`: the chart's default.
|
||||
#[serde(default)]
|
||||
pub line_w: Option<f32>,
|
||||
/// "None" line: the series draws no line.
|
||||
#[serde(default)]
|
||||
pub no_line: bool,
|
||||
/// Markers on points; `None`: unset (scatter charts draw them; a saved scatter series then has no `c:marker`, so Word picks its own symbols).
|
||||
#[serde(default)]
|
||||
pub markers: Option<bool>,
|
||||
/// Draw the line as a smooth curve.
|
||||
#[serde(default)]
|
||||
pub smooth: bool,
|
||||
/// Data labels for this series; `None`: follow the chart's setting.
|
||||
#[serde(default)]
|
||||
pub labels: Option<bool>,
|
||||
/// Number format of this series's labels and values; `None`: linked to the source.
|
||||
#[serde(default)]
|
||||
pub fmt: Option<String>,
|
||||
}
|
||||
|
||||
/// One chart axis as Word formats it (Format Axis): title, scale bounds, tick-label number
|
||||
/// format, gridlines, tick labels and the axis line.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartAxis {
|
||||
/// `None`: no axis title; text cut to [`MAX_TEXT`] characters.
|
||||
#[serde(default)]
|
||||
pub title: Option<String>,
|
||||
/// Fixed lower bound; `None`: automatic.
|
||||
#[serde(default)]
|
||||
pub min: Option<f64>,
|
||||
/// Fixed upper bound; `None`: automatic.
|
||||
#[serde(default)]
|
||||
pub max: Option<f64>,
|
||||
/// Tick-label number format (`#,##0`, `0.00`, `0%`…); `None`: linked to the source data.
|
||||
#[serde(default)]
|
||||
pub fmt: Option<String>,
|
||||
/// Major gridlines drawn along this axis.
|
||||
#[serde(default)]
|
||||
pub gridlines: bool,
|
||||
/// Tick labels; `false` hides the axis the way Word's Axis Labels ▸ None does.
|
||||
#[serde(default = "the_true")]
|
||||
pub labels: bool,
|
||||
/// The axis line.
|
||||
#[serde(default = "the_true")]
|
||||
pub line: bool,
|
||||
}
|
||||
|
||||
fn the_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for ChartAxis {
|
||||
fn default() -> Self {
|
||||
ChartAxis { title: None, min: None, max: None, fmt: None, gridlines: false, labels: true, line: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The value axis as a new chart has it: gridlines, labels, no axis line.
|
||||
pub fn value_axis() -> ChartAxis {
|
||||
ChartAxis { gridlines: true, line: false, ..ChartAxis::default() }
|
||||
}
|
||||
|
||||
impl ChartAxis {
|
||||
/// Make the axis safe to store: texts cleaned, bounds finite, `min` under `max` (an
|
||||
/// impossible pair drops both), the format code cut to [`MAX_FMT`] characters.
|
||||
pub fn sanitize(&mut self) {
|
||||
self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty());
|
||||
self.min = self.min.filter(|v| v.is_finite());
|
||||
self.max = self.max.filter(|v| v.is_finite());
|
||||
if matches!((self.min, self.max), (Some(lo), Some(hi)) if lo >= hi) {
|
||||
self.min = None;
|
||||
self.max = None;
|
||||
}
|
||||
self.fmt = self.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest axis number format kept, characters.
|
||||
pub const MAX_FMT: usize = 128;
|
||||
|
||||
/// A number format code: control characters as spaces, ends trimmed, at most [`MAX_FMT`]
|
||||
/// characters.
|
||||
pub fn clean_fmt(s: &str) -> String {
|
||||
let s: String = s.chars().take(MAX_FMT * 4).map(|c| if c.is_control() { ' ' } else { c }).collect();
|
||||
s.trim().chars().take(MAX_FMT).collect::<String>().trim_end().to_string()
|
||||
}
|
||||
|
||||
/// A chart the app can edit.
|
||||
@@ -151,6 +247,12 @@ pub struct ChartSpec {
|
||||
/// Show each point's value next to it.
|
||||
#[serde(default)]
|
||||
pub data_labels: bool,
|
||||
/// The category axis (scatter charts: the x axis).
|
||||
#[serde(default)]
|
||||
pub cat_axis: ChartAxis,
|
||||
/// The value axis (scatter charts: the y axis); gridlines on, no axis line, as a new chart has them.
|
||||
#[serde(default = "value_axis")]
|
||||
pub val_axis: ChartAxis,
|
||||
}
|
||||
|
||||
impl ChartSpec {
|
||||
@@ -168,10 +270,23 @@ impl ChartSpec {
|
||||
ChartSpec {
|
||||
kind,
|
||||
categories: categories.into_iter().map(str::to_string).collect(),
|
||||
series: series.into_iter().map(|(n, v)| ChartSeries { name: n.to_string(), values: v.into_iter().map(Some).collect() }).collect(),
|
||||
series: series
|
||||
.into_iter()
|
||||
.map(|(n, v)| ChartSeries {
|
||||
name: n.to_string(),
|
||||
values: v.into_iter().map(Some).collect(),
|
||||
// Scatter series are drawn as markers without a line.
|
||||
no_line: kind == ChartType::Scatter,
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
title: None,
|
||||
legend: Some(LegendPos::Bottom),
|
||||
data_labels: false,
|
||||
cat_axis: ChartAxis::default(),
|
||||
// Pie and doughnut charts have no axes: their axes stay plain, so the chart reads back
|
||||
// as the same model.
|
||||
val_axis: if kind.is_round() { ChartAxis::default() } else { value_axis() },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,8 +318,12 @@ impl ChartSpec {
|
||||
*v = v.filter(|x| x.is_finite());
|
||||
}
|
||||
s.values.resize(n, None);
|
||||
s.fmt = s.fmt.as_deref().map(clean_fmt).filter(|f| !f.is_empty());
|
||||
s.line_w = s.line_w.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 20.0));
|
||||
}
|
||||
self.title = self.title.as_deref().map(clean_text).filter(|t| !t.is_empty());
|
||||
self.cat_axis.sanitize();
|
||||
self.val_axis.sanitize();
|
||||
}
|
||||
|
||||
/// The chart after `sanitize`.
|
||||
@@ -229,7 +348,11 @@ mod tests {
|
||||
let mut c = ChartSpec {
|
||||
categories: vec!["a".into(); MAX_POINTS + 10],
|
||||
series: (0..MAX_SERIES + 5)
|
||||
.map(|i| ChartSeries { name: format!("{}\n{}", "x".repeat(400), i), values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)] })
|
||||
.map(|i| ChartSeries {
|
||||
name: format!("{}\n{}", "x".repeat(400), i),
|
||||
values: vec![Some(f64::NAN), Some(f64::INFINITY), Some(1.0)],
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
title: Some(" ".into()),
|
||||
..Default::default()
|
||||
@@ -250,7 +373,7 @@ mod tests {
|
||||
fn short_categories_are_padded_to_the_longest_series() {
|
||||
let c = ChartSpec {
|
||||
categories: vec!["a".into()],
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)] }],
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0), Some(2.0)], ..Default::default() }],
|
||||
..Default::default()
|
||||
}
|
||||
.sanitized();
|
||||
@@ -258,4 +381,45 @@ mod tests {
|
||||
assert_eq!(ChartType::from_id("BARSTACKED"), Some(ChartType::BarStacked));
|
||||
assert_eq!(LegendPos::from_id("top"), Some(LegendPos::Top));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_bounds_and_formats_are_cleaned() {
|
||||
let mut a = ChartAxis {
|
||||
title: Some(" Sales\n".into()),
|
||||
min: Some(f64::NAN),
|
||||
max: Some(50.0),
|
||||
fmt: Some("x".repeat(MAX_FMT + 40)),
|
||||
gridlines: true,
|
||||
labels: false,
|
||||
line: true,
|
||||
};
|
||||
a.sanitize();
|
||||
assert_eq!(a.title.as_deref(), Some("Sales"));
|
||||
assert_eq!(a.min, None);
|
||||
assert_eq!(a.max, Some(50.0));
|
||||
assert_eq!(a.fmt.as_deref().map(|f| f.chars().count()), Some(MAX_FMT));
|
||||
|
||||
// min not under max drops the pair; a format of only spaces is no format.
|
||||
let mut b = ChartAxis { min: Some(50.0), max: Some(50.0), fmt: Some(" ".into()), ..Default::default() };
|
||||
b.sanitize();
|
||||
assert_eq!((b.min, b.max), (None, None));
|
||||
assert_eq!(b.fmt, None);
|
||||
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![Some(1.0)], ..Default::default() }],
|
||||
categories: vec!["a".into()],
|
||||
..Default::default()
|
||||
};
|
||||
spec.series[0].line_w = Some(f32::NAN);
|
||||
spec.series[0].fmt = Some("0.00".into());
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, None);
|
||||
assert_eq!(spec.series[0].fmt.as_deref(), Some("0.00"));
|
||||
let mut spec = ChartSpec {
|
||||
series: vec![ChartSeries { name: "s".into(), values: vec![], line_w: Some(100.0), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.series[0].line_w, Some(20.0), "a wild width clamps to 20 pt");
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,9 @@ pub enum GraphicItem {
|
||||
#[serde(default)]
|
||||
stroke_width: f32,
|
||||
},
|
||||
/// One line of text in `rect`, aligned horizontally by `align`, centred vertically.
|
||||
/// 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).
|
||||
Text {
|
||||
rect: [f32; 4],
|
||||
text: String,
|
||||
@@ -127,6 +129,8 @@ pub enum GraphicItem {
|
||||
align: TextAlign,
|
||||
#[serde(default)]
|
||||
font: Option<String>,
|
||||
#[serde(default)]
|
||||
angle: f32,
|
||||
},
|
||||
/// A picture (`Document::media` key) stretched into `rect`.
|
||||
Image { rect: [f32; 4], media: String },
|
||||
|
||||
Reference in new issue
Block a user