Merge pull request #2867 from AnhNgoo/fix/chart-explicit-style-rendering

fix(chart): render explicit Excel chart styles 1 and 9
This commit is contained in:
FredApps
2026-11-27 05:55:30 +01:00
committed by GitHub
7 changed files with 555 additions and 14 deletions
+29 -9
View File
@@ -58,6 +58,15 @@ fn has_markers(k: ChartKind) -> bool {
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
}
/// Stroke widths for explicitly selected Excel chart styles.
fn line_style_width(style: u32) -> f32 {
match style {
1 => 3.0,
9 => 5.0,
_ => 2.25,
}
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
/// bars' start positions) and along the value axis (`lo..hi`).
struct BarRun {
@@ -71,6 +80,7 @@ struct BarRun {
}
impl BarRun {
/// Starts a single-bar run at `pos` spanning `lo..hi`.
fn new(pos: f32, lo: f32, hi: f32) -> Self {
BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false }
}
@@ -78,6 +88,7 @@ impl BarRun {
fn touches(&self, lo: f32, hi: f32) -> bool {
lo <= self.hi && hi >= self.lo
}
/// Extends the merged run to cover `pos` and `lo..hi`.
fn add(&mut self, pos: f32, lo: f32, hi: f32) {
self.merged = true;
self.a0 = self.a0.min(pos);
@@ -112,13 +123,15 @@ struct BarSink {
bw: f32,
horizontal: bool,
color: Rgba,
stroke: Option<(Rgba, f32)>,
nslots: f32,
k: f32,
}
impl BarSink {
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, nslots, k }
/// Creates a bar emitter for series slot `k` of `nslots`.
fn new(bw: f32, horizontal: bool, color: Rgba, stroke: Option<(Rgba, f32)>, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, stroke, nslots, k }
}
/// Start of this series' slot along the category axis, for the category centered at `c`.
fn pos(&self, c: f32) -> f32 {
@@ -138,11 +151,10 @@ impl BarSink {
let pos = self.pos(c);
let band = self.band();
if !merge {
if self.horizontal {
ctx.rect(lo, pos, len, self.bw, self.color, None);
} else {
ctx.rect(pos, lo, self.bw, len, self.color, None);
}
let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) };
// Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears.
let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw);
ctx.rect(x, y, w, h, self.color, stroke);
return;
}
match &mut self.run {
@@ -154,6 +166,7 @@ impl BarSink {
}
}
}
/// Flushes any pending hairline bar run at the end of the series.
fn finish(self, ctx: &mut Ctx) {
let band = self.band();
if let Some(m) = self.run {
@@ -294,6 +307,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec<usize>, f32) {
(slot_of, slot_keys.len().max(1) as f32)
}
/// Renders Cartesian column, bar, line, area, and combination charts.
///
/// Resolves series families and their axes, calculates stacking and
/// category positions, and draws the corresponding primitives.
/// Explicit chart style 9 adds white outlines to column and bar
/// rectangles, including stacked and 100%-stacked variants.
pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) {
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
if ncat == 0 {
@@ -392,7 +411,8 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
let k = slot_of.get(i).copied().unwrap_or(0) as f32;
// Hairline bars are merged per pixel column (their envelope is what shows).
let cull = merge_hairlines(bw, labels_on);
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
let stroke = (chart.style == 9).then_some((WHITE, 1.0));
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
for (j, sp) in row.iter().enumerate() {
let Some((b, t)) = sp else { continue };
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
@@ -429,7 +449,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
}
_ => {
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if has_markers(k) && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
+70 -3
View File
@@ -39,6 +39,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba {
[r, g, b, 0xFF]
}
/// Excel reference colours for explicit styles 1 and 9.
///
/// These palettes cover measured default-theme examples.
/// Other counts still use the existing theme-based fallback.
fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba {
if !matches!(style, 1 | 9) {
return series_color(theme, index);
}
const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50];
const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8];
const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA];
let shades: &[u8] = match count {
1..=4 => &SMALL,
5..=8 => &MEDIUM,
9..=16 => &LARGE,
_ => return series_color(theme, index),
};
shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF])
}
/// The first `n` series colours for `theme`.
pub fn default_palette(theme: &Theme, n: usize) -> Vec<Rgba> {
(0..n.min(4096)).map(|i| series_color(theme, i)).collect()
@@ -470,8 +492,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() {
let values = nums(wb, sheet, &s.values, limit);
let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1));
let color =
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
let color = s
.color
.as_ref()
.and_then(|c| c.resolve(&wb.theme))
.map(|[r, g, b]| [r, g, b, 0xFF])
.unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
let kind = chart.series_kind(i);
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
// X values with text in them (labels) are ignored: the points are numbered 1..n.
@@ -519,10 +545,51 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
}
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
let palette = if matches!(chart.style, 1 | 9) {
(0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect()
} else {
default_palette(&wb.theme, n.min(PALETTE_CYCLE))
};
ChartData { categories, category_levels, series, palette }
}
#[cfg(test)]
mod explicit_style_palette_tests {
use super::*;
/// Verifies grayscale palette selection and fallback boundaries for explicit styles 1 and 9.
#[test]
fn explicit_style_palette_boundaries() {
let theme = Workbook::default().theme;
for style in [1, 9] {
for count in [0, 17, 255] {
for index in [0, 1, 4, 8, 16] {
assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index));
}
}
for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] {
assert_eq!(
chart_style_series_color(&theme, style, 0, count),
[expected_first, expected_first, expected_first, 255],
"style {style}, count {count}",
);
assert_eq!(
chart_style_series_color(&theme, style, 16, count),
series_color(&theme, 16),
"out-of-range index for style {style}, count {count}",
);
}
}
for style in [0, 2, 10, 48] {
assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0));
}
}
}
#[cfg(test)]
mod label_budget_tests {
use gridcraft_model::Workbook;
+205
View File
@@ -1743,6 +1743,7 @@ fn box_whisker_draws_each_series_quartile_method() {
assert!((heights[0] / heights[1] - 1.4).abs() < 0.001);
}
/// Defined-name series titles on sheets with apostrophes resolve properly.
#[test]
fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
// #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series
@@ -1780,6 +1781,7 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
}
/// Defined-name series titles on sheets whose names contain `!` resolve properly.
#[test]
fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
// `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at
@@ -1817,6 +1819,7 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
}
/// Volatile functions in series values or names mark the chart as volatile.
#[test]
fn volatile_series_formulas_are_detected() {
let wb = Workbook::new();
@@ -1849,6 +1852,7 @@ fn volatile_series_formulas_are_detected() {
assert!(!has_volatile_series(&wb, 0, &chart(ChartKind::Line)));
}
/// Defined names referenced by series formulas are followed for volatility checks.
#[test]
fn volatile_defined_names_are_followed() {
let with = |values: &str| {
@@ -1913,3 +1917,204 @@ fn volatile_defined_names_are_followed() {
assert!(!has_volatile_series(&wb, 1, &with("=Dice")));
assert!(has_volatile_series(&wb, 1, &with("=FreshClock")));
}
/// Explicit Excel chart styles should affect default series colours,
/// without changing the workbook theme.
#[test]
fn explicit_chart_styles_use_distinct_default_colors() {
let wb = Workbook::default();
let mut c = chart(ChartKind::ColumnClustered);
c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() });
c.style = 2;
let style2 = resolve(&wb, 0, &c).series[0].color;
assert_eq!(style2, series_color(&wb.theme, 0));
c.style = 1;
let style1 = resolve(&wb, 0, &c).series[0].color;
c.style = 9;
let style9 = resolve(&wb, 0, &c).series[0].color;
assert_ne!(style1, style2, "style 1 should differ from style 2");
assert_ne!(style9, style2, "style 9 should differ from style 2");
}
/// Excel chart styles must not override explicitly assigned series colours.
#[test]
fn explicit_chart_styles_preserve_custom_series_colors() {
let wb = Workbook::default();
let mut c = chart(ChartKind::ColumnClustered);
c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() });
for style in [1, 2, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}");
}
}
/// Check the first four point colours measured in Excel for styles 1 and 9.
#[test]
fn excel_chart_styles_use_measured_point_palette() {
let wb = Workbook::default();
let mut c = chart(ChartKind::Pie);
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]];
for style in [1, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
assert_eq!(&data.palette[..4], &expected);
assert_eq!(data.series[0].color, expected[0]);
}
}
/// Excel's default-theme chart colours depend on the total series count.
#[test]
fn excel_chart_styles_depend_on_series_count() {
let wb = Workbook::default();
let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() };
let cases: &[(usize, [[u8; 4]; 3])] = &[
(6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]),
(12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]),
];
for (count, expected) in cases {
for style in [1, 9] {
let mut c = chart(ChartKind::ColumnClustered);
c.style = style;
c.series = vec![base_series.clone(); *count];
let data = resolve(&wb, 0, &c);
assert_eq!(data.series.len(), *count);
for (i, color) in expected.iter().enumerate() {
assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}");
}
}
}
}
/// Style 9 uses white outlines on column and bar data rectangles.
#[test]
fn explicit_style_nine_draws_white_column_outlines() {
let wb = Workbook::default();
for kind in [
ChartKind::ColumnClustered,
ChartKind::BarClustered,
ChartKind::ColumnStacked,
ChartKind::BarStacked,
ChartKind::ColumnStacked100,
ChartKind::BarStacked100,
] {
let mut c = chart(kind);
c.legend = LegendPos::None;
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
for style in [1, 2, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
let color = data.series[0].color;
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
let outlines: Vec<_> = prims
.iter()
.filter_map(|p| match p {
Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke),
_ => None,
})
.collect();
assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}");
let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None };
assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}");
}
}
}
/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9.
/// Other styles retain GridCraft's existing stroke width.
#[test]
fn explicit_excel_styles_set_line_stroke_width() {
let color: Rgba = [17, 73, 131, 255];
for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] {
let data = ChartData {
categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(),
category_levels: vec![],
palette: vec![],
series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)],
};
let mut c = chart(kind);
c.legend = LegendPos::None;
c.data_labels = false;
for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] {
c.style = style;
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
let widths: Vec<f32> = prims
.iter()
.filter_map(|primitive| match primitive {
Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width),
_ => None,
})
.collect();
assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}");
}
}
}
/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible.
#[test]
fn narrow_style_9_bars_retain_visible_fill() {
let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF];
// Stay within MAX_LABELS (200) so data labels remain active on the direct unmerged path,
// while keeping each single-series slot <= 0.88 px inside the 220 px chart.
let count = 100usize;
let categories: Vec<String> = (0..count).map(|i| format!("C{i}")).collect();
let values = vec![50.0; count];
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] {
let data = ChartData {
categories: categories.clone(),
category_levels: vec![],
palette: vec![],
series: vec![series("S1", &values, fill_color, kind)],
};
let mut c = chart(kind);
c.legend = LegendPos::None;
// Data labels keep bars on the unmerged direct path even when narrower than 1 px.
c.data_labels = true;
c.gridlines = false;
c.style = 9;
let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure);
let narrow_bars: Vec<_> = prims
.iter()
.filter_map(|p| match p {
Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke),
_ => None,
})
.collect();
assert_eq!(narrow_bars.len(), count, "Direct unmerged path must emit all {count} bars individually for {kind:?}");
assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}");
}
}
+19 -2
View File
@@ -432,6 +432,11 @@ const DASHES: [(LineDash, &str); 11] = [
const EMU_PER_PT: f64 = 12_700.0;
/// Parses a legacy OOXML `<c:style val="..."/>` index (`1..=48`), trimming surrounding spaces.
fn parse_chart_style(val: &str) -> Option<u32> {
val.trim().parse::<u32>().ok().filter(|s| (1..=48).contains(s))
}
fn group_kind(g: &El) -> Option<ChartKind> {
let grouping = g.child_val("grouping").unwrap_or("standard");
let stacked = grouping == "stacked";
@@ -463,7 +468,8 @@ fn group_kind(g: &El) -> Option<ChartKind> {
}
}
}
"pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie,
"pieChart" | "pie3DChart" => ChartKind::Pie,
"ofPieChart" => ChartKind::Pie,
"doughnutChart" => ChartKind::Doughnut,
"areaChart" | "area3DChart" => {
if pct {
@@ -713,7 +719,18 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>, budget: &mut Chart
outline: t.outline,
}),
gridlines: dc.gridlines,
style: dc.style,
// Excel can wrap the legacy chart style in mc:AlternateContent.
// The c14 Choice uses different IDs, so read the c:style Fallback.
style: root
.and_then(|r| {
r.child_val("style").and_then(parse_chart_style).or_else(|| {
r.kids("AlternateContent")
.filter_map(|wrapper| wrapper.child("Fallback"))
.find_map(|fallback| fallback.child_val("style").and_then(parse_chart_style))
})
})
.or_else(|| (1..=48).contains(&dc.style).then_some(dc.style))
.unwrap_or(2),
hole_size,
first_slice_angle: dc.first_slice_angle,
x_title: axis_titles.0,
+1
View File
@@ -9,6 +9,7 @@ mod chart_data_table;
mod chart_line_percent_stacked;
mod chart_read_tests;
mod chart_ref_offsets;
mod chart_style_roundtrip;
mod controls_tests;
mod csv_tests;
mod encrypted_tests;
@@ -45,6 +45,44 @@ fn line_first_group_stays_a_line() {
assert_eq!(k[1], Some(ChartKind::ColumnClustered));
}
/// Verifies explicit `<c:style>` values round-trip unchanged through chart XML serialization.
#[test]
fn explicit_chart_style_survives_xml_roundtrip() {
use gridcraft_model::Workbook;
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] {
for style in [1, 9, 48] {
let mut chart = crate::chart::read_chart(
&parse(
format!(
"<c:chartSpace xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\">\
<c:style val=\"{style}\"/>\
<c:chart><c:plotArea>\
<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>\
<c:ser><c:idx val=\"0\"/><c:order val=\"0\"/></c:ser>\
</c:barChart>\
</c:plotArea></c:chart></c:chartSpace>"
)
.as_bytes(),
)
.unwrap(),
)
.unwrap()
.0;
chart.kind = kind;
assert_eq!(chart.style, style);
let wb = Workbook::default();
let xml = crate::chart::write_chart(&wb, 0, &chart, "Book.xlsx");
let root = parse(xml.as_bytes()).unwrap();
let restored = crate::chart::read_chart(&root).unwrap().0;
assert_eq!(restored.style, style, "chart style changed for {kind:?}");
}
}
}
/// Outside a combo, a series keeps its own markers or lines where they differ from its chart's,
/// read and written. The chart's kind is its first series'.
#[test]
@@ -0,0 +1,193 @@
//! Explicit chart styles survive complete XLSX serialization.
use std::sync::Arc;
use gridcraft_core::CellRef;
use gridcraft_model::{Anchor, Chart, ChartKind, LegendPos, Series, Sheet, Workbook};
use crate::{read_xlsx, write_xlsx};
/// Verifies explicit chart styles survive full XLSX save and reload cycles.
#[test]
fn explicit_styles_survive_xlsx_save_and_reload() {
// Start from the XLSX reader so this fixture follows new optional Chart fields.
let template: Chart = crate::chart::read_chart(
&crate::xml::parse(
concat!(
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart">"#,
"<c:chart><c:plotArea><c:barChart>",
r#"<c:barDir val="col"/><c:grouping val="clustered"/>"#,
r#"<c:ser><c:idx val="0"/><c:order val="0"/></c:ser>"#,
"</c:barChart></c:plotArea></c:chart></c:chartSpace>",
)
.as_bytes(),
)
.unwrap(),
)
.unwrap()
.0;
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered, ChartKind::Line] {
for style in [1, 9, 48] {
let mut wb = Workbook::default();
let mut sheet = Sheet::new("Data");
let mut chart = template.clone();
chart.id = 1;
chart.kind = kind;
chart.anchor = Anchor { cell: CellRef::new(0, 3), width: 480.0, height: 300.0, ..Anchor::default() };
chart.title = Some("Style roundtrip".into());
chart.series = vec![Series {
name: Some("Series 1".into()),
categories: Some(r#"{"A","B","C"}"#.into()),
values: "{10,20,30}".into(),
..Series::default()
}];
chart.legend = LegendPos::Bottom;
chart.data_labels = false;
chart.gridlines = true;
chart.style = style;
chart.x_title = None;
chart.y_title = None;
chart.source = None;
chart.by_rows = false;
chart.pivot = None;
sheet.charts.push(chart);
wb.sheets = vec![Arc::new(sheet)];
let bytes = write_xlsx(&wb).unwrap();
let (reloaded, _) = read_xlsx(&bytes).unwrap();
assert_eq!(reloaded.sheets[0].charts.len(), 1);
assert_eq!(reloaded.sheets[0].charts[0].kind, kind);
assert_eq!(reloaded.sheets[0].charts[0].style, style);
let bytes2 = write_xlsx(&reloaded).unwrap();
let (reloaded2, _) = read_xlsx(&bytes2).unwrap();
assert_eq!(reloaded2.sheets[0].charts.len(), 1);
assert_eq!(reloaded2.sheets[0].charts[0].kind, kind);
assert_eq!(reloaded2.sheets[0].charts[0].style, style, "XLSX round-trip changed style {style} for {kind:?}");
}
}
}
/// Excel stores legacy styles 1 and 9 in mc:Fallback,
/// alongside c14 Choice values 101 and 109.
#[test]
fn excel_alternate_content_chart_styles_roundtrip() {
use crate::chart::{read_chart, write_chart};
use crate::xml::parse;
for (kind, group) in [
(
ChartKind::ColumnClustered,
r#"<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>"#,
),
(
ChartKind::BarClustered,
r#"<c:barChart><c:barDir val="bar"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>"#,
),
(
ChartKind::Line,
r#"<c:lineChart><c:grouping val="standard"/><c:marker val="0"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:lineChart>"#,
),
] {
for (legacy_style, modern_style) in [(1, 101), (9, 109)] {
let xml = format!(
r#"<c:chartSpace
xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<mc:AlternateContent>
<mc:Choice Requires="c14">
<c14:style val="{modern_style}"/>
</mc:Choice>
<mc:Fallback>
<c:style val="{legacy_style}"/>
</mc:Fallback>
</mc:AlternateContent>
<c:chart>
<c:plotArea>{group}</c:plotArea>
</c:chart>
</c:chartSpace>"#
);
let root = parse(xml.as_bytes()).unwrap();
let chart = read_chart(&root).unwrap().0;
assert_eq!(chart.kind, kind);
assert_eq!(chart.style, legacy_style, "Excel AlternateContent style for {kind:?}");
let saved = write_chart(&Workbook::default(), 0, &chart, "Book.xlsx");
let reopened = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap().0;
assert_eq!(reopened.style, legacy_style, "Style changed when re-exporting {kind:?}");
}
}
}
/// Surrounding whitespace on `<c:style val="..."/>` trims cleanly, while out-of-range fallback values default to style 2.
#[test]
fn alternate_content_fallback_style_trims_and_validates_range() {
use crate::chart::read_chart;
use crate::xml::parse;
for (raw_val, expected) in [(" 9 ", 9), ("\t1\n", 1), ("0", 2), ("49", 2), ("200", 2)] {
let xml = format!(
r#"<c:chartSpace
xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:style val="109"/></mc:Choice>
<mc:Fallback><c:style val="{raw_val}"/></mc:Fallback>
</mc:AlternateContent>
<c:chart>
<c:plotArea>
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>
</c:plotArea>
</c:chart>
</c:chartSpace>"#
);
let chart = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap().0;
assert_eq!(chart.style, expected, "raw fallback style {raw_val:?}");
}
}
/// Reads `<c:style>` from a later `mc:AlternateContent` wrapper when an earlier wrapper has no style fallback.
#[test]
fn later_alternate_content_wrapper_provides_fallback_style() {
use crate::chart::read_chart;
use crate::xml::parse;
let xml = r#"<c:chartSpace
xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart">
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:sketchOptions/></mc:Choice>
</mc:AlternateContent>
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:dropZoneFilter val="0"/></mc:Choice>
<mc:Fallback><c:roundedCorners val="0"/></mc:Fallback>
</mc:AlternateContent>
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:style val="100"/></mc:Choice>
<mc:Fallback><c:style val="0"/></mc:Fallback>
</mc:AlternateContent>
<mc:AlternateContent>
<mc:Choice Requires="c14"><c14:style val="109"/></mc:Choice>
<mc:Fallback><c:style val="9"/></mc:Fallback>
</mc:AlternateContent>
<c:chart>
<c:plotArea>
<c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/></c:ser></c:barChart>
</c:plotArea>
</c:chart>
</c:chartSpace>"#;
let chart = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap().0;
assert_eq!(chart.style, 9);
}