mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 20:25:02 +00:00
Merge pull request #1290 from vangel76/feat/docx-chart-axis-series
DOCX charts keep axis and series formatting
This commit is contained in:
+362
-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,85 @@ 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 {
|
||||
// "No fill" wins over a stored colour, so the pair reads back as it was written.
|
||||
match &s.fill {
|
||||
Some(c) if !s.no_fill => {
|
||||
w.open("a:solidFill", &[]);
|
||||
w.empty("a:srgbClr", &[("val", &c.hex())]);
|
||||
w.close("a:solidFill");
|
||||
}
|
||||
_ => 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 +340,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 +359,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 +383,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 +490,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 +534,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 +647,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();
|
||||
@@ -491,6 +678,33 @@ mod tests {
|
||||
assert_eq!(spec_of(&parse(&plain)), Some(plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_fill_wins_over_a_stored_colour() {
|
||||
let mut spec = ChartSpec::sample(ChartType::Column);
|
||||
spec.series[0].fill = Some(Rgb(255, 0, 0));
|
||||
spec.series[0].no_fill = true;
|
||||
let x = chart_xml(&spec);
|
||||
assert!(!x.contains("FF0000"), "colour written next to no_fill");
|
||||
let back = spec_of(&parse(&spec)).expect("stays editable");
|
||||
assert!(back.series[0].no_fill);
|
||||
assert_eq!(back.series[0].fill, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_axis_format_is_limited_in_characters_not_bytes() {
|
||||
use craft_wordmodel::chart::MAX_FMT;
|
||||
let cjk = format!("0\"{}\"", "\u{5143}".repeat(90));
|
||||
let ascii = format!("0\"{}\"", "x".repeat(90));
|
||||
for fmt in [cjk, ascii] {
|
||||
assert!(fmt.chars().count() <= MAX_FMT);
|
||||
let mut spec = ChartSpec::sample(ChartType::Column);
|
||||
spec.val_axis.fmt = Some(fmt.clone());
|
||||
let spec = spec.sanitized();
|
||||
assert_eq!(spec.val_axis.fmt.as_deref(), Some(fmt.as_str()));
|
||||
assert_eq!(spec_of(&parse(&spec)).as_ref(), Some(&spec), "{} chars", fmt.chars().count());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chart_with_more_than_the_model_stays_read_only() {
|
||||
let spec = ChartSpec::sample(ChartType::Column);
|
||||
@@ -500,6 +714,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 +786,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 +800,7 @@ mod tests {
|
||||
"c:delete",
|
||||
"c:axPos",
|
||||
"c:majorGridlines",
|
||||
"c:numFmt",
|
||||
"c:majorTickMark",
|
||||
"c:minorTickMark",
|
||||
"c:tickLblPos",
|
||||
@@ -535,13 +810,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`.
|
||||
|
||||
@@ -7,6 +7,33 @@ pub(super) struct DataLabel {
|
||||
pub(super) y: f32,
|
||||
pub(super) text: String,
|
||||
pub(super) inside: bool,
|
||||
/// Where a label that is not `inside` sits relative to (`x`, `y`).
|
||||
pub(super) pos: LabelPos,
|
||||
/// Distance from (`x`, `y`) to the label for `pos` other than `Center`, points (half the marker).
|
||||
pub(super) off: f32,
|
||||
}
|
||||
|
||||
/// Where a data label sits beside its point (`c:dLblPos`: `t`, `b`, `l`, `r`, `ctr`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum LabelPos {
|
||||
Above,
|
||||
Below,
|
||||
Left,
|
||||
Right,
|
||||
Center,
|
||||
}
|
||||
|
||||
impl LabelPos {
|
||||
pub(super) fn parse(v: &str) -> Option<LabelPos> {
|
||||
Some(match v.trim() {
|
||||
"t" => LabelPos::Above,
|
||||
"b" => LabelPos::Below,
|
||||
"l" => LabelPos::Left,
|
||||
"r" => LabelPos::Right,
|
||||
"ctr" => LabelPos::Center,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -52,16 +79,56 @@ 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>,
|
||||
/// 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 {
|
||||
@@ -70,9 +137,21 @@ 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>,
|
||||
/// 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>>,
|
||||
/// Scatter x values (index + 1 when the file has none).
|
||||
pub(super) xs: Vec<Option<f64>>,
|
||||
@@ -83,6 +162,13 @@ 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' number format (`c:dLbls/c:numFmt`): `None` when not given (the chart type's
|
||||
/// applies), `Some(None)` when linked to the source, else `Some(Some(code))`.
|
||||
pub(super) label_fmt: Option<Option<String>>,
|
||||
/// The data labels' `c:dLblPos`, when the file gives a known one.
|
||||
pub(super) label_pos: Option<LabelPos>,
|
||||
/// The marker's own fill (`c:marker/c:spPr`); without it markers take the automatic colour.
|
||||
pub(super) marker_color: Option<Rgb>,
|
||||
/// 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>>,
|
||||
|
||||
@@ -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::model::{Axis, Grouping, Kind, LabelPos, Pos, Series, Symbol};
|
||||
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> {
|
||||
@@ -39,10 +39,15 @@ 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));
|
||||
// Absent (`None`) inherits the chart type's; explicitly source-linked (`Some(None)`) does not.
|
||||
if s.label_fmt.is_none() {
|
||||
s.label_fmt.clone_from(&type_fmt);
|
||||
}
|
||||
if s.labels == Some(true) {
|
||||
s.raw = s.values.clone();
|
||||
}
|
||||
@@ -98,6 +103,13 @@ impl Chart {
|
||||
s.and_then(|s| s.color).unwrap_or_else(|| self.accent(s.and_then(|s| s.idx).unwrap_or(j)))
|
||||
}
|
||||
|
||||
/// Colour of series `j`'s markers: the marker's own fill, else the automatic colour of the
|
||||
/// series index (not the series' explicit line colour, as Word draws them).
|
||||
pub(super) fn marker_colour(&self, j: usize) -> Rgb {
|
||||
let s = self.series.get(j);
|
||||
s.and_then(|s| s.marker_color).unwrap_or_else(|| self.accent(s.and_then(|s| s.idx).unwrap_or(j)))
|
||||
}
|
||||
|
||||
/// Colour of point `i` of series `j`: its `c:dPt` override, else the varied accent (pie) or
|
||||
/// the series colour.
|
||||
pub(super) fn point_colour(&self, j: usize, i: usize) -> Rgb {
|
||||
@@ -149,7 +161,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 {
|
||||
@@ -180,6 +192,17 @@ 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`): `None` when the labels say nothing,
|
||||
/// `Some(None)` when they are linked to the source (so a chart-level format does not apply),
|
||||
/// `Some(Some(code))` for their own format code.
|
||||
fn label_format(d: Option<&El>) -> Option<Option<String>> {
|
||||
let f = d?.child("c:numFmt")?;
|
||||
if f.attr("sourceLinked").is_some_and(truthy) {
|
||||
return Some(None);
|
||||
}
|
||||
f.attr("formatCode").filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT).map(|f| Some(f.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,
|
||||
@@ -206,9 +229,24 @@ impl Series {
|
||||
let sp = ser.child("c:spPr");
|
||||
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 marker_color = marker;
|
||||
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.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) };
|
||||
if scatter && xs.is_empty() {
|
||||
@@ -223,7 +261,30 @@ 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() }
|
||||
let label_fmt = label_format(ser.child("c:dLbls"));
|
||||
let label_pos = ser.child("c:dLbls").and_then(|d| d.child("c:dLblPos")).and_then(|p| p.attr("val")).and_then(LabelPos::parse);
|
||||
Series {
|
||||
name,
|
||||
idx,
|
||||
color,
|
||||
line_w,
|
||||
line,
|
||||
no_fill,
|
||||
markers,
|
||||
symbol,
|
||||
marker_size,
|
||||
smooth,
|
||||
values,
|
||||
xs,
|
||||
points,
|
||||
fmt,
|
||||
x_fmt,
|
||||
labels,
|
||||
label_fmt,
|
||||
label_pos,
|
||||
marker_color,
|
||||
raw: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +351,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());
|
||||
@@ -305,8 +366,16 @@ pub(super) fn axis(a: Option<&El>) -> Axis {
|
||||
.child("c:numFmt")
|
||||
.filter(|f| f.attr("sourceLinked") != Some("1"))
|
||||
.and_then(|f| f.attr("formatCode"))
|
||||
.filter(|f| f.len() <= MAX_FORMAT_CODE)
|
||||
.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"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
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::model::{DataLabel, Grouping, Kind, LabelPos, Series, Symbol};
|
||||
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};
|
||||
|
||||
/// 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()
|
||||
@@ -142,6 +145,8 @@ impl Axes {
|
||||
/// The room around the plot for axis labels, and the category labels as they'll be drawn.
|
||||
struct Margins {
|
||||
left: f32,
|
||||
/// Part of `left` taken by the rotated category-axis title (bars): the labels start after it.
|
||||
title: f32,
|
||||
top: f32,
|
||||
bottom: f32,
|
||||
/// Category labels in lines (none for scatter charts or a deleted category axis).
|
||||
@@ -151,22 +156,25 @@ 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 title = title_left(c, cat_on, val_on, area.w);
|
||||
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;
|
||||
let band_w = (area.w - left).max(1.0) / c.n as f32;
|
||||
let wrapped: Vec<Vec<String>> = if cat_on && !scatter {
|
||||
let width = if c.horizontal { left - GAP } else { band_w };
|
||||
let wrapped: Vec<Vec<String>> = if cat_labels && !scatter {
|
||||
let width = if c.horizontal { left - title - GAP } else { band_w };
|
||||
c.cats.iter().map(|s| wrap(s, width, fs)).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -174,15 +182,48 @@ 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 };
|
||||
Margins { left, top, bottom, wrapped, skip }
|
||||
}) + title_bottom(c, cat_on, val_on, lh);
|
||||
let top = if !c.horizontal && val_labels { lh / 2.0 } else { 0.0 };
|
||||
Margins { left, title, 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.
|
||||
/// A horizontal title (`rot="0"`) gets a strip as wide as its wrapped lines, at most a quarter of
|
||||
/// `area_w`, so the plot keeps its room.
|
||||
fn title_left(c: &Chart, cat_on: bool, val_on: bool, area_w: f32) -> f32 {
|
||||
let side = if c.horizontal { cat_on && c.cat.title.is_some() } else { val_on && c.val.title.is_some() };
|
||||
if !side {
|
||||
return 0.0;
|
||||
}
|
||||
match flat_title_lines(c, area_w) {
|
||||
Some(lines) => widest(&lines, c.text_size).min((area_w * 0.25).max(0.0)) + GAP,
|
||||
None => c.text_size * LINE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The wrapped lines of the left axis's title when the file keeps it horizontal (`rot="0"`).
|
||||
fn flat_title_lines(c: &Chart, area_w: f32) -> Option<Vec<String>> {
|
||||
let left = if c.horizontal { &c.cat } else { &c.val };
|
||||
let r = left.title_rot?.rem_euclid(360.0);
|
||||
if !(r < 1.0 || r > 359.0) {
|
||||
return None;
|
||||
}
|
||||
let width = if area_w.is_finite() { (area_w * 0.18).max(1.0) } else { 1.0 };
|
||||
left.title.as_ref().map(|t| wrap(t, width, c.text_size))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -200,6 +241,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);
|
||||
}
|
||||
let mut labels = Vec::new();
|
||||
match c.kind {
|
||||
Kind::Bar => bars(out, c, &g, &mut labels),
|
||||
@@ -210,12 +254,49 @@ 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, area.w);
|
||||
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 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 or keeps it horizontal (`rot="0"`, wrapped in its own strip); any
|
||||
// other rotation would not fit the strip and is read as counter-clockwise.
|
||||
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(lines) = flat_title_lines(c, area.w)
|
||||
{
|
||||
let strip = (g.plot.x - area.x - GAP).max(1.0);
|
||||
let top = g.plot.y + g.plot.h / 2.0 - lines.len() as f32 * lh / 2.0;
|
||||
for (k, l) in lines.iter().enumerate() {
|
||||
let l = clip_text(l, strip, c.text_size);
|
||||
text_angle(out, Rect { x: area.x, y: top + k as f32 * lh, w: strip, h: lh }, &l, c.text_size, TextAlign::Center, false, 0.0);
|
||||
}
|
||||
} else 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, up);
|
||||
}
|
||||
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 +309,31 @@ 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 (where line and
|
||||
/// area points sit, on the tick marks when the axis crosses "midCat"), at the x ticks of a
|
||||
/// scatter chart.
|
||||
fn draw_cat_grid(out: &mut Vec<GraphicItem>, g: &Frame, xticks: &[(f64, String)], kind: Kind) {
|
||||
let plot = g.plot;
|
||||
if kind == Kind::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 segs = if g.horiz {
|
||||
let p = g.band_start(i) + g.band() / 2.0;
|
||||
seg(plot.x, p, plot.right(), p)
|
||||
} else {
|
||||
// Bars stay in their bands; only line and area points move onto the ticks.
|
||||
let p = if matches!(kind, Kind::Line | Kind::Area) { g.cat_x(i) } else { g.band_start(i) + g.band() / 2.0 };
|
||||
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;
|
||||
@@ -271,7 +377,7 @@ fn draw_category_labels(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, xticks
|
||||
for (i, lines) in m.wrapped.iter().enumerate() {
|
||||
let top = g.band_start(i) + g.band() / 2.0 - lines.len() as f32 * lh / 2.0;
|
||||
for (k, s) in lines.iter().enumerate() {
|
||||
text(out, Rect { x: area.x, y: top + k as f32 * lh, w: m.left - GAP, h: lh }, s, fs, TextAlign::Right, false);
|
||||
text(out, Rect { x: area.x + m.title, y: top + k as f32 * lh, w: m.left - m.title - GAP, h: lh }, s, fs, TextAlign::Right, false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -361,7 +467,13 @@ 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.clone(), c.point_colour(j, i));
|
||||
}
|
||||
// An explicit outline shows without a fill too (the series' colour is the line's here).
|
||||
if let (true, true, Some(w)) = (s.line, s.no_fill, s.line_w) {
|
||||
stroke(out, segs, c.point_colour(j, i), w);
|
||||
}
|
||||
if let Some(text) = label_of(s, i) {
|
||||
let mid = a + thick / 2.0;
|
||||
let (x, y) = match (g.horiz, stacked) {
|
||||
@@ -371,7 +483,7 @@ fn bars(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<DataL
|
||||
(true, false) => (if v >= 0.0 { p1 } else { p0 }, mid),
|
||||
(false, false) => (mid, if v >= 0.0 { p0 } else { p1 }),
|
||||
};
|
||||
labels.push(DataLabel { x, y, text, inside: stacked });
|
||||
labels.push(DataLabel { x, y, text, inside: stacked, pos: LabelPos::Above, off: 0.0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,13 +513,109 @@ fn lines(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<Data
|
||||
.collect();
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
if let (Some((x, y)), Some(text)) = (p, label_of(s, i)) {
|
||||
labels.push(DataLabel { x: *x, y: *y, text, inside: false });
|
||||
labels.push(DataLabel {
|
||||
x: *x,
|
||||
y: *y,
|
||||
text,
|
||||
inside: false,
|
||||
pos: s.label_pos.unwrap_or(LabelPos::Right),
|
||||
off: marker_half(s, s.markers == Some(true)) + 2.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
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.marker_colour(j), s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A series' point markers in the series' symbol and size (`colour` fills or strokes them), for
|
||||
/// lines and scatter charts.
|
||||
/// Half a series' marker size, points; zero when it draws no markers.
|
||||
fn marker_half(s: &Series, drawn: bool) -> f32 {
|
||||
if drawn { s.marker_size.filter(|v| v.is_finite()).unwrap_or(6.0).clamp(2.0, 72.0) / 2.0 } else { 0.0 }
|
||||
}
|
||||
|
||||
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 {
|
||||
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
|
||||
/// 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)) {
|
||||
@@ -422,10 +630,12 @@ fn areas(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut Vec<Data
|
||||
segs.push(PathSeg::Line(g.cat_x(i), g.val(*b)));
|
||||
}
|
||||
segs.push(PathSeg::Close);
|
||||
fill(out, segs, c.series_colour(j));
|
||||
if !s.no_fill {
|
||||
fill(out, segs, c.series_colour(j));
|
||||
}
|
||||
for (i, (t, b)) in top.iter().zip(&base).enumerate() {
|
||||
if let Some(text) = label_of(s, i) {
|
||||
labels.push(DataLabel { x: g.cat_x(i), y: g.val((t + b) / 2.0), text, inside: true });
|
||||
labels.push(DataLabel { x: g.cat_x(i), y: g.val((t + b) / 2.0), text, inside: true, pos: LabelPos::Above, off: 0.0 });
|
||||
}
|
||||
}
|
||||
if c.stacked() {
|
||||
@@ -434,9 +644,8 @@ 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() {
|
||||
let pts: Vec<Option<(f32, f32)>> =
|
||||
s.xs.iter()
|
||||
@@ -448,16 +657,21 @@ fn draw_scatter(out: &mut Vec<GraphicItem>, c: &Chart, g: &Frame, labels: &mut V
|
||||
.collect();
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
if let (Some((x, y)), Some(text)) = (p, label_of(s, i)) {
|
||||
labels.push(DataLabel { x: *x, y: *y - MARKER / 2.0, text, inside: false });
|
||||
labels.push(DataLabel {
|
||||
x: *x,
|
||||
y: *y,
|
||||
text,
|
||||
inside: false,
|
||||
pos: s.label_pos.unwrap_or(LabelPos::Right),
|
||||
off: marker_half(s, s.markers != Some(false)) + 2.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
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) {
|
||||
markers(out, pts.iter().flatten().copied(), c.marker_colour(j), s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
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::model::{DataLabel, Kind, LabelPos, 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 };
|
||||
@@ -38,7 +38,7 @@ pub(super) fn pie(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
// Halfway across the ring (pie: two thirds out from the centre).
|
||||
let at = if inner > 0.0 { (r + inner) / 2.0 } else { r * 0.65 };
|
||||
let (x, y) = polar(cx, cy, at, (a + b) / 2.0);
|
||||
labels.push(DataLabel { x: x as f32, y: y as f32, text, inside: true });
|
||||
labels.push(DataLabel { x: x as f32, y: y as f32, text, inside: true, pos: LabelPos::Above, off: 0.0 });
|
||||
}
|
||||
a = b;
|
||||
}
|
||||
@@ -92,14 +92,14 @@ 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];
|
||||
out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(col), stroke: None, stroke_width: 0.0 });
|
||||
}
|
||||
if let Some(text) = label_of(s, i) {
|
||||
labels.push(DataLabel { x: p.0 as f32, y: p.1 as f32, text, inside: false });
|
||||
labels.push(DataLabel { x: p.0 as f32, y: p.1 as f32, text, inside: false, pos: LabelPos::Above, off: 0.0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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_ref().map_or(s.fmt.as_deref(), |f| f.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),
|
||||
@@ -165,13 +165,22 @@ pub(super) fn draw_data_labels(out: &mut Vec<GraphicItem>, labels: &[DataLabel],
|
||||
let w = text_w(&l.text, fs) + 4.0;
|
||||
let (rect, align) = if l.inside {
|
||||
(Rect { x: l.x - w / 2.0, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Center)
|
||||
} else if l.off > 0.0 || l.pos != LabelPos::Above {
|
||||
let o = l.off;
|
||||
match l.pos {
|
||||
LabelPos::Right => (Rect { x: l.x + o, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Left),
|
||||
LabelPos::Left => (Rect { x: l.x - o - w, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Right),
|
||||
LabelPos::Below => (Rect { x: l.x - w / 2.0, y: l.y + o, w, h: lh }, TextAlign::Center),
|
||||
LabelPos::Center => (Rect { x: l.x - w / 2.0, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Center),
|
||||
LabelPos::Above => (Rect { x: l.x - w / 2.0, y: l.y - o - lh, w, h: lh }, TextAlign::Center),
|
||||
}
|
||||
} else if beside_right {
|
||||
(Rect { x: l.x + GAP / 2.0, y: l.y - lh / 2.0, w, h: lh }, TextAlign::Left)
|
||||
} else {
|
||||
(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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -386,9 +386,13 @@ fn axis_format_code_length_is_capped() {
|
||||
let x = format!(r#"<c:valAx {NS}><c:numFmt formatCode="{code}" sourceLinked="0"/></c:valAx>"#);
|
||||
axis(Some(&crate::xml::parse(x.as_bytes()).unwrap())).fmt
|
||||
};
|
||||
let ok = format!("{}0", "x".repeat(254));
|
||||
use craft_wordmodel::chart::MAX_FMT;
|
||||
// The limit is the model's, counted in characters (a CJK character is one).
|
||||
let ok = format!("{}0", "x".repeat(MAX_FMT - 1));
|
||||
assert_eq!(fmt(&ok), Some(ok.clone()));
|
||||
assert_eq!(fmt(&format!("{}0", "x".repeat(300))), None);
|
||||
let cjk = format!("{}0", "\u{5143}".repeat(MAX_FMT - 1));
|
||||
assert_eq!(fmt(&cjk), Some(cjk.clone()));
|
||||
assert_eq!(fmt(&format!("{}0", "x".repeat(MAX_FMT))), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -590,3 +594,308 @@ fn series_without_a_usable_c_idx_take_their_place() {
|
||||
let big = [renumbered(&a, &format!(r#"<c:idx val="{}"/>"#, u32::MAX))];
|
||||
assert_eq!(column_colours(&big).0.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bar_category_labels_start_after_the_axis_title() {
|
||||
let long = "A category label that is much too long for its column";
|
||||
let title = r#"<c:title><c:tx><c:rich><a:p><a:r><a:t>Region</a:t></a:r></a:p></c:rich></c:tx></c:title>"#;
|
||||
let plot = format!(
|
||||
r#"<c:barChart><c:barDir val="bar"/><c:grouping val="clustered"/>{}<c:axId val="1"/><c:axId val="2"/></c:barChart><c:catAx><c:axId val="1"/>{title}</c:catAx><c:valAx><c:axId val="2"/></c:valAx>"#,
|
||||
ser(0, "S", Some("FF0000"), &[long, "Short"], &["4", "8"]),
|
||||
);
|
||||
let items = chart_items(&space(&plot), &theme(), 300.0, 200.0);
|
||||
let rect_of = |f: &dyn Fn(&str, &TextAlign) -> bool| -> Vec<[f32; 4]> {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|it| if let GraphicItem::Text { rect, text, align, .. } = it { f(text, align).then_some(*rect) } else { None })
|
||||
.collect()
|
||||
};
|
||||
let title_rect = rect_of(&|t, _| t == "Region");
|
||||
assert_eq!(title_rect.len(), 1);
|
||||
let strip_end = title_rect[0][0] + title_rect[0][2];
|
||||
let labels = rect_of(&|t, a| matches!(a, TextAlign::Right) && t != "Region" && (long.contains(t) || t == "Short"));
|
||||
assert!(!labels.is_empty());
|
||||
assert!(labels.iter().all(|r| r[0] >= strip_end - 1e-3), "labels {labels:?} overlap the title strip ending at {strip_end}");
|
||||
assert!(labels.iter().all(|r| r[2] <= 0.4 * 300.0), "{labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn category_gridlines_follow_the_points_when_the_axis_crosses_mid() {
|
||||
let line = |cross: &str| {
|
||||
let plot = format!(
|
||||
r#"<c:lineChart><c:grouping val="standard"/>{}<c:axId val="1"/><c:axId val="2"/></c:lineChart><c:catAx><c:axId val="1"/><c:majorGridlines/></c:catAx><c:valAx><c:axId val="2"/><c:crossBetween val="{cross}"/></c:valAx>"#,
|
||||
ser(0, "L", Some("FF0000"), &["Q1", "Q2", "Q3"], &["1", "5", "3"]),
|
||||
);
|
||||
let items = chart_items(&space(&plot), &theme(), 300.0, 200.0);
|
||||
let grid: Vec<f32> = items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
GraphicItem::Path { segs, stroke: Some(c), .. } if *c == GRID => match segs.first() {
|
||||
Some(PathSeg::Move(x, _)) => Some(*x),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let pts: Vec<f32> = items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
GraphicItem::Path { segs, stroke: Some(c), .. } if *c == Rgb(255, 0, 0) => Some(
|
||||
segs.iter().filter_map(|s| if let PathSeg::Move(x, _) | PathSeg::Line(x, _) = s { Some(*x) } else { None }).collect::<Vec<f32>>(),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
(grid, pts)
|
||||
};
|
||||
for cross in ["midCat", "between"] {
|
||||
let (grid, pts) = line(cross);
|
||||
assert_eq!(grid.len(), 3, "{cross}");
|
||||
assert_eq!(pts.len(), 3, "{cross}");
|
||||
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 (`rot="0"`) stays horizontal: the plot makes room for it (see below).
|
||||
assert_eq!(angle(&line_with("", &title(r#"<a:bodyPr rot="0" vert="horz"/>"#))), Some(0.0));
|
||||
// Hostile values stay finite.
|
||||
let odd = angle(&line_with("", &title(r#"<a:bodyPr rot="99999999999999999999"/>"#)));
|
||||
assert!(odd.is_some_and(f32::is_finite));
|
||||
}
|
||||
|
||||
fn first_ellipse(items: &[GraphicItem]) -> Option<([f32; 4], Rgb)> {
|
||||
items.iter().find_map(|it| match it {
|
||||
GraphicItem::Shape { kind: ShapeKind::Ellipse, rect, fill: Some(c), .. } if rect[2] > 3.0 && rect[2] < 20.0 => Some((*rect, *c)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_use_the_automatic_series_colour_not_the_line_colour() {
|
||||
// The series has an explicit red line/fill but no marker fill: Word draws the markers in the
|
||||
// palette colour of the series index (accent 1 here).
|
||||
let items = line_with(&marker_xml("circle", 9), "");
|
||||
assert_eq!(first_ellipse(&items).map(|e| e.1), Some(theme()[4]));
|
||||
// A marker's own fill wins.
|
||||
let own =
|
||||
r#"<c:marker><c:symbol val="circle"/><c:size val="9"/><c:spPr><a:solidFill><a:srgbClr val="00AA00"/></a:solidFill></c:spPr></c:marker>"#;
|
||||
assert_eq!(first_ellipse(&line_with(own, "")).map(|e| e.1), Some(Rgb(0, 0xAA, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_data_labels_default_to_the_right_and_honour_dlblpos() {
|
||||
let dl = |pos: &str| format!(r#"{}<c:dLbls>{pos}<c:showVal val="1"/></c:dLbls>"#, marker_xml("circle", 9));
|
||||
let text_rect = |items: &[GraphicItem]| {
|
||||
items.iter().find_map(|it| if let GraphicItem::Text { text, rect, .. } = it { (text == "3.2").then_some(*rect) } else { None })
|
||||
};
|
||||
let at = |pos: &str| {
|
||||
let items = line_with(&dl(pos), "");
|
||||
let (m, _) = first_ellipse(&items).unwrap();
|
||||
let t = text_rect(&items).unwrap();
|
||||
// Centre of the marker and of the label box.
|
||||
((t[0] + t[2] / 2.0) - (m[0] + m[2] / 2.0), (t[1] + t[3] / 2.0) - (m[1] + m[3] / 2.0), t, m)
|
||||
};
|
||||
let (dx, dy, t, m) = at("");
|
||||
assert!(t[0] >= m[0] + m[2] && dy.abs() < 1.0, "default is right of the marker: {dx} {dy}");
|
||||
let (dx, dy, t, m) = at(r#"<c:dLblPos val="r"/>"#);
|
||||
assert!(t[0] >= m[0] + m[2] && dy.abs() < 1.0, "{dx} {dy}");
|
||||
let (dx, dy, _, _) = at(r#"<c:dLblPos val="t"/>"#);
|
||||
assert!(dx.abs() < 1.0 && dy < -4.0, "{dx} {dy}");
|
||||
let (dx, dy, _, _) = at(r#"<c:dLblPos val="b"/>"#);
|
||||
assert!(dx.abs() < 1.0 && dy > 4.0, "{dx} {dy}");
|
||||
let (dx, dy, t, m) = at(r#"<c:dLblPos val="l"/>"#);
|
||||
assert!(t[0] + t[2] <= m[0] && dy.abs() < 1.0, "{dx} {dy}");
|
||||
let (dx, dy, _, _) = at(r#"<c:dLblPos val="ctr"/>"#);
|
||||
assert!(dx.abs() < 1.0 && dy.abs() < 1.0, "{dx} {dy}");
|
||||
// Unknown positions fall back to the default.
|
||||
let (_, _, t, m) = at(r#"<c:dLblPos val="wibble"/>"#);
|
||||
assert!(t[0] >= m[0] + m[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_value_axis_title_gets_its_own_strip() {
|
||||
let title = |rot: &str, name: &str| {
|
||||
format!(r#"<c:title><c:tx><c:rich><a:bodyPr{rot}/><a:p><a:r><a:t>{name}</a:t></a:r></a:p></c:rich></c:tx></c:title>"#)
|
||||
};
|
||||
let plot_left = |items: &[GraphicItem]| {
|
||||
// The first gridline's start is the plot's left edge.
|
||||
items.iter().find_map(|it| match it {
|
||||
GraphicItem::Path { segs, stroke: Some(_), fill: None, .. } if segs.len() == 2 => match segs.first() {
|
||||
Some(PathSeg::Move(x, _)) => Some(*x),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let rect_of = |items: &[GraphicItem], name: &str| {
|
||||
items.iter().find_map(|it| if let GraphicItem::Text { text, rect, .. } = it { text.starts_with(name).then_some(*rect) } else { None })
|
||||
};
|
||||
let turned = line_with("", &title(r#" rot="-5400000" vert="horz""#, "Revenue"));
|
||||
let flat = line_with("", &title(r#" rot="0" vert="horz""#, "Revenue"));
|
||||
let (a, b) = (plot_left(&turned).unwrap(), plot_left(&flat).unwrap());
|
||||
assert!(b > a + 10.0, "a horizontal title takes more room than a turned one: {a} {b}");
|
||||
// The title box lies left of the plot and inside the chart.
|
||||
let r = rect_of(&flat, "Revenue").unwrap();
|
||||
assert!(r[0] >= 0.0 && r[0] + r[2] <= b + 0.5, "{r:?} {b}");
|
||||
// A hostile title never takes more than a quarter of the width and stays finite.
|
||||
let long = "Wibble ".repeat(500);
|
||||
let items = line_with("", &title(r#" rot="0""#, &long));
|
||||
let p = plot_left(&items).unwrap();
|
||||
assert!(p.is_finite() && p <= 300.0 * 0.3, "{p}");
|
||||
}
|
||||
|
||||
/// A one-series chart whose series carries `sp` as its `c:spPr`.
|
||||
fn chart_with_sp(kind: &str, sp: &str) -> Vec<GraphicItem> {
|
||||
let s = ser(0, "S", None, &["Q1", "Q2"], &["4", "8"]).replace("<c:cat>", &format!("{sp}<c:cat>"));
|
||||
let plot = match kind {
|
||||
"area" => format!(
|
||||
r#"<c:areaChart><c:grouping val="standard"/>{s}<c:axId val="1"/><c:axId val="2"/></c:areaChart><c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx>"#
|
||||
),
|
||||
dir => format!(
|
||||
r#"<c:barChart><c:barDir val="{dir}"/><c:grouping val="clustered"/>{s}<c:axId val="1"/><c:axId val="2"/></c:barChart><c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx>"#
|
||||
),
|
||||
};
|
||||
chart_items(&space(&plot), &theme(), 300.0, 200.0)
|
||||
}
|
||||
|
||||
/// The series' closed shapes: (filled, stroked with the given width).
|
||||
fn series_shapes(items: &[GraphicItem], width: f32) -> (usize, usize) {
|
||||
let closed = |segs: &[PathSeg]| segs.iter().any(|s| matches!(s, PathSeg::Close));
|
||||
let fills = items.iter().filter(|it| matches!(it, GraphicItem::Path { segs, fill: Some(_), .. } if closed(segs))).count();
|
||||
let strokes = items
|
||||
.iter()
|
||||
.filter(|it| matches!(it, GraphicItem::Path { segs, fill: None, stroke: Some(_), stroke_width, .. } if closed(segs) && (*stroke_width - width).abs() < 0.01))
|
||||
.count();
|
||||
(fills, strokes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfilled_bars_keep_their_explicit_outline() {
|
||||
let outlined = r#"<c:spPr><a:noFill/><a:ln w="25400"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></a:ln></c:spPr>"#;
|
||||
let no_line = r#"<c:spPr><a:noFill/><a:ln><a:noFill/></a:ln></c:spPr>"#;
|
||||
for dir in ["col", "bar"] {
|
||||
// Two points, two outlines, no fill.
|
||||
assert_eq!(series_shapes(&chart_with_sp(dir, outlined), 2.0), (0, 2), "{dir}");
|
||||
// Control: no fill and no line draws nothing.
|
||||
assert_eq!(series_shapes(&chart_with_sp(dir, no_line), 2.0), (0, 0), "{dir}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_fill_area_series_is_not_painted() {
|
||||
let filled = r#"<c:spPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></c:spPr>"#;
|
||||
let none = r#"<c:spPr><a:noFill/><a:ln w="25400"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></a:ln></c:spPr>"#;
|
||||
assert_eq!(series_shapes(&chart_with_sp("area", filled), 2.0).0, 1);
|
||||
assert_eq!(series_shapes(&chart_with_sp("area", none), 2.0).0, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_linked_series_labels_do_not_inherit_the_chart_format() {
|
||||
let dl = |fmt: &str| format!(r#"<c:dLbls><c:numFmt formatCode="{fmt}" sourceLinked="{{}}"/><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()
|
||||
};
|
||||
// Chart-level 0%; the series' own labels are `linked` (or have no labels element at all).
|
||||
let run = |series_dl: &str| {
|
||||
let s = ser(0, "S", Some("FF0000"), &["Q1", "Q2", "Q3"], &["3.2", "4.1", "5"]).replace("<c:cat>", &format!("{series_dl}<c:cat>"));
|
||||
let chart_dl = dl("0%").replace("{}", "0");
|
||||
let plot = format!(
|
||||
r#"<c:lineChart><c:grouping val="standard"/>{s}{chart_dl}<c:axId val="1"/><c:axId val="2"/></c:lineChart><c:catAx><c:axId val="1"/></c:catAx><c:valAx><c:axId val="2"/></c:valAx>"#
|
||||
);
|
||||
shown(&chart_items(&space(&plot), &theme(), 300.0, 200.0))
|
||||
};
|
||||
for linked in ["1", "true"] {
|
||||
let own = run(&dl("General").replace("{}", linked));
|
||||
assert!(own.contains(&"3.2".to_string()) && !own.contains(&"320%".to_string()), "sourceLinked={linked}: {own:?}");
|
||||
}
|
||||
// Control: a series without a label format still takes the chart's.
|
||||
let inherited = run(r#"<c:dLbls><c:showVal val="1"/></c:dLbls>"#);
|
||||
assert!(inherited.contains(&"320%".to_string()), "{inherited:?}");
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -755,7 +755,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,17 +125,111 @@ 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.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChartSpec {
|
||||
#[serde(rename = "type")]
|
||||
@@ -151,6 +247,29 @@ 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 Default for ChartSpec {
|
||||
/// An empty chart whose value axis is the one a new chart (and a missing JSON field) has:
|
||||
/// gridlines on, no axis line.
|
||||
fn default() -> Self {
|
||||
ChartSpec {
|
||||
kind: ChartType::default(),
|
||||
categories: Vec::new(),
|
||||
series: Vec::new(),
|
||||
title: None,
|
||||
legend: None,
|
||||
data_labels: false,
|
||||
cat_axis: ChartAxis::default(),
|
||||
val_axis: value_axis(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChartSpec {
|
||||
@@ -168,10 +287,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 +335,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 +365,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 +390,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 +398,53 @@ mod tests {
|
||||
assert_eq!(ChartType::from_id("BARSTACKED"), Some(ChartType::BarStacked));
|
||||
assert_eq!(LegendPos::from_id("top"), Some(LegendPos::Top));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_and_missing_json_axis_fields_agree() {
|
||||
let from_json: ChartSpec = serde_json::from_str(r#"{"type":"column"}"#).unwrap();
|
||||
let d = ChartSpec::default();
|
||||
assert_eq!((d.cat_axis.clone(), d.val_axis.clone()), (from_json.cat_axis, from_json.val_axis));
|
||||
assert!(d.val_axis.gridlines && !d.val_axis.line);
|
||||
}
|
||||
|
||||
#[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
|
||||
/// turn the vertical axis's title -90°, reading upwards, as Word does).
|
||||
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