use crate::coordinate::{Col, Row};
use crate::model::DefinedName;
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct Chart {
pub name: String,
pub anchor: Anchor,
pub title: Option<Title>,
pub auto_title_deleted: bool,
pub plots: Vec<Plot>,
pub axes: Vec<ChartAxis>,
pub legend: Option<Legend>,
pub format: Option<ShapeFormat>,
pub plot_format: Option<ShapeFormat>,
pub markup: ChartMarkup,
pub origin: Option<ChartOrigin>,
}
impl Chart {
#[must_use]
pub fn is_unchanged(&self) -> bool {
self.origin
.as_ref()
.is_some_and(|o| self.same_placement(&o.read) && self.same_content(&o.read))
}
pub(crate) fn settle(&mut self) {
if let Some(mut origin) = self.origin.take() {
origin.read = Box::new(self.clone());
self.origin = Some(origin);
}
}
pub(crate) fn same_placement(&self, other: &Self) -> bool {
self.name == other.name && self.anchor == other.anchor
}
pub(crate) fn same_content(&self, other: &Self) -> bool {
let Self {
name: _,
anchor: _,
title,
auto_title_deleted,
plots,
axes,
legend,
format,
plot_format,
markup,
origin: _,
} = self;
*title == other.title
&& *auto_title_deleted == other.auto_title_deleted
&& *plots == other.plots
&& *axes == other.axes
&& *legend == other.legend
&& *format == other.format
&& *plot_format == other.plot_format
&& *markup == other.markup
}
pub(crate) fn formulas_mut(&mut self) -> Vec<&mut String> {
let mut out = Vec::new();
let titles = self
.title
.iter_mut()
.chain(self.axes.iter_mut().filter_map(|a| a.title.as_mut()));
out.extend(
titles
.filter_map(|t| t.text.as_mut())
.filter_map(ChartText::formula_mut),
);
for series in self.plots.iter_mut().flat_map(|p| &mut p.series) {
out.extend(series.name.as_mut().and_then(ChartText::formula_mut));
for data in [
&mut series.categories,
&mut series.values,
&mut series.bubble_sizes,
] {
out.extend(data.as_mut().and_then(DataSource::formula_mut));
}
}
out
}
pub(crate) fn markups_mut(&mut self) -> Vec<&mut String> {
let ChartMarkup {
before_chart,
before_plot_area,
plot_area_layout,
after_axes,
after_legend,
after_chart,
} = &mut self.markup;
let mut out = vec![
before_chart,
before_plot_area,
plot_area_layout,
after_axes,
after_legend,
after_chart,
];
out.extend(self.title.as_mut().map(|t| &mut t.markup));
out.extend(self.legend.as_mut().map(|l| &mut l.markup));
for axis in &mut self.axes {
let AxisMarkup {
gridlines,
ticks,
tail,
} = &mut axis.markup;
out.extend([gridlines, ticks, tail]);
out.extend(axis.title.as_mut().map(|t| &mut t.markup));
}
for plot in &mut self.plots {
out.push(&mut plot.markup);
let mut labels: Vec<&mut DataLabels> = plot.labels.iter_mut().collect();
for series in &mut plot.series {
labels.extend(series.labels.as_mut());
let SeriesMarkup {
after_format,
before_data,
after_data,
} = &mut series.markup;
out.extend([after_format, before_data, after_data]);
for data in [
&mut series.categories,
&mut series.values,
&mut series.bubble_sizes,
] {
if let Some(DataSource::Levels { formula, markup }) = data {
out.push(markup);
out.extend(formula.as_mut());
}
}
}
for labels in labels {
out.extend(labels.source.as_mut());
out.extend(labels.points.iter_mut().filter_map(|l| l.source.as_mut()));
}
}
out
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChartOrigin {
pub(crate) drawing: String,
pub(crate) part: String,
pub(crate) read: Box<Chart>,
pub(crate) root_attributes: String,
pub(crate) prefix: String,
pub(crate) grouped: bool,
}
impl ChartOrigin {
#[must_use]
pub fn part(&self) -> &str {
&self.part
}
#[must_use]
pub fn drawing(&self) -> &str {
&self.drawing
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Anchor {
TwoCell {
from: Marker,
to: Marker,
edit_as: Option<EditAs>,
},
OneCell {
from: Marker,
width: i64,
height: i64,
},
Absolute {
x: i64,
y: i64,
width: i64,
height: i64,
},
}
impl Default for Anchor {
fn default() -> Self {
Self::TwoCell {
from: Marker::default(),
to: Marker {
col: Col::new(8).unwrap_or_default(),
row: Row::new(15).unwrap_or_default(),
..Marker::default()
},
edit_as: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Marker {
pub col: Col,
pub col_offset: i64,
pub row: Row,
pub row_offset: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditAs {
TwoCell,
OneCell,
Absolute,
}
impl EditAs {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
match value {
"twoCell" => Some(Self::TwoCell),
"oneCell" => Some(Self::OneCell),
"absolute" => Some(Self::Absolute),
_ => None,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::TwoCell => "twoCell",
Self::OneCell => "oneCell",
Self::Absolute => "absolute",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChartText {
Reference {
formula: String,
cache: Option<String>,
},
Text {
text: String,
rich: Option<String>,
},
}
impl ChartText {
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self::Text {
text: text.into(),
rich: None,
}
}
#[must_use]
pub fn shown(&self) -> Option<&str> {
match self {
Self::Reference { cache, .. } => cache.as_deref(),
Self::Text { text, .. } => Some(text),
}
}
fn formula_mut(&mut self) -> Option<&mut String> {
match self {
Self::Reference { formula, .. } => Some(formula),
Self::Text { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Title {
pub text: Option<ChartText>,
pub layout: Option<ManualLayout>,
pub markup: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ManualLayout {
pub x: i32,
pub y: i32,
pub w: Option<i32>,
pub h: Option<i32>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Plot {
pub kind: PlotKind,
pub vary_colors: Option<bool>,
pub series: Vec<Series>,
pub axis_ids: Vec<u32>,
pub labels: Option<DataLabels>,
pub drop_lines: Option<ChartLines>,
pub high_low_lines: Option<ChartLines>,
pub up_down_bars: Option<UpDownBars>,
pub show_markers: Option<bool>,
pub markup: String,
}
impl Plot {
#[must_use]
pub const fn new(kind: PlotKind) -> Self {
Self {
kind,
vary_colors: None,
series: Vec::new(),
axis_ids: Vec::new(),
labels: None,
drop_lines: None,
high_low_lines: None,
up_down_bars: None,
show_markers: None,
markup: String::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ChartLines {
pub format: Option<ShapeFormat>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UpDownBars {
pub gap_width: Option<u16>,
pub up: Option<ShapeFormat>,
pub down: Option<ShapeFormat>,
pub source: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlotKind {
Bar {
direction: BarDirection,
grouping: Grouping,
three_d: bool,
},
Line {
grouping: Grouping,
three_d: bool,
},
Area {
grouping: Grouping,
three_d: bool,
},
Pie {
three_d: bool,
},
Doughnut,
OfPie {
bar: bool,
},
Scatter(ScatterStyle),
Radar(RadarStyle),
Bubble,
Stock,
Surface {
three_d: bool,
wireframe: bool,
},
}
impl PlotKind {
#[must_use]
pub const fn element(self) -> &'static str {
match self {
Self::Bar { three_d: false, .. } => "barChart",
Self::Bar { three_d: true, .. } => "bar3DChart",
Self::Line { three_d: false, .. } => "lineChart",
Self::Line { three_d: true, .. } => "line3DChart",
Self::Area { three_d: false, .. } => "areaChart",
Self::Area { three_d: true, .. } => "area3DChart",
Self::Pie { three_d: false } => "pieChart",
Self::Pie { three_d: true } => "pie3DChart",
Self::Doughnut => "doughnutChart",
Self::OfPie { .. } => "ofPieChart",
Self::Scatter(_) => "scatterChart",
Self::Radar(_) => "radarChart",
Self::Bubble => "bubbleChart",
Self::Stock => "stockChart",
Self::Surface { three_d: false, .. } => "surfaceChart",
Self::Surface { three_d: true, .. } => "surface3DChart",
}
}
#[must_use]
pub const fn has_axes(self) -> bool {
!matches!(self, Self::Pie { .. } | Self::Doughnut | Self::OfPie { .. })
}
#[must_use]
pub const fn plots_xy(self) -> bool {
matches!(self, Self::Scatter(_) | Self::Bubble)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BarDirection {
#[default]
Column,
Bar,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Grouping {
#[default]
Standard,
Clustered,
Stacked,
PercentStacked,
}
impl Grouping {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"clustered" => Self::Clustered,
"stacked" => Self::Stacked,
"percentStacked" => Self::PercentStacked,
_ => Self::Standard,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Standard => "standard",
Self::Clustered => "clustered",
Self::Stacked => "stacked",
Self::PercentStacked => "percentStacked",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScatterStyle {
None,
Line,
LineMarker,
#[default]
Marker,
Smooth,
SmoothMarker,
}
impl ScatterStyle {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"none" => Self::None,
"line" => Self::Line,
"lineMarker" => Self::LineMarker,
"smooth" => Self::Smooth,
"smoothMarker" => Self::SmoothMarker,
_ => Self::Marker,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Line => "line",
Self::LineMarker => "lineMarker",
Self::Marker => "marker",
Self::Smooth => "smooth",
Self::SmoothMarker => "smoothMarker",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RadarStyle {
#[default]
Standard,
Marker,
Filled,
}
impl RadarStyle {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"marker" => Self::Marker,
"filled" => Self::Filled,
_ => Self::Standard,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Standard => "standard",
Self::Marker => "marker",
Self::Filled => "filled",
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Series {
pub index: u32,
pub order: u32,
pub name: Option<ChartText>,
pub categories: Option<DataSource>,
pub values: Option<DataSource>,
pub bubble_sizes: Option<DataSource>,
pub format: Option<ShapeFormat>,
pub marker: Option<SeriesMarker>,
pub data_points: Vec<DataPoint>,
pub labels: Option<DataLabels>,
pub markup: SeriesMarkup,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SeriesMarkup {
pub after_format: String,
pub before_data: String,
pub after_data: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ShapeFormat {
pub fill: Option<Fill>,
pub line: Option<LineFormat>,
pub source: Option<String>,
}
impl ShapeFormat {
#[must_use]
pub fn solid(color: ChartColor) -> Self {
Self {
fill: Some(Fill::Solid(color)),
..Self::default()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LineFormat {
pub fill: Option<Fill>,
pub width: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fill {
None,
Solid(ChartColor),
Gradient {
stops: Vec<GradientStop>,
angle: Option<u32>,
path: Option<GradientPath>,
},
Pattern {
preset: Option<String>,
foreground: Option<ChartColor>,
background: Option<ChartColor>,
},
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GradientStop {
pub position: u32,
pub color: ChartColor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GradientPath {
Shape,
Circle,
Rect,
}
impl GradientPath {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Some(match value {
"shape" => Self::Shape,
"circle" => Self::Circle,
"rect" => Self::Rect,
_ => return None,
})
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Shape => "shape",
Self::Circle => "circle",
Self::Rect => "rect",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChartColor {
pub base: ColorBase,
pub transforms: Vec<ColorTransform>,
}
impl ChartColor {
#[must_use]
pub const fn rgb(rgb: u32) -> Self {
Self {
base: ColorBase::Rgb(rgb),
transforms: Vec::new(),
}
}
#[must_use]
pub fn scheme(name: impl Into<String>) -> Self {
Self {
base: ColorBase::Scheme(name.into()),
transforms: Vec::new(),
}
}
#[must_use]
pub fn resolve(&self, theme: Option<&str>) -> Option<u32> {
let mut rgb = match &self.base {
ColorBase::Rgb(rgb) => *rgb & 0x00FF_FFFF,
ColorBase::Scheme(name) => crate::shared::palette::rgb_of(
&crate::style::Color::Theme {
id: scheme_id(name)?,
tint: 0,
},
theme,
)?,
};
for t in &self.transforms {
rgb = t.apply(rgb);
}
Some(rgb)
}
pub(crate) fn to_style(&self, theme: Option<&str>) -> Option<crate::style::Color> {
use crate::style::Color;
if let ColorBase::Scheme(name) = &self.base
&& let Some(id) = scheme_id(name)
{
let tint = match self.transforms.as_slice() {
[] => Some(0),
[ColorTransform::LumMod(m)] if (0..=100_000).contains(m) => {
Some((m - 100_000) * 10)
}
[ColorTransform::LumMod(m), ColorTransform::LumOff(o)]
if (0..=100_000).contains(o) && m.checked_add(*o) == Some(100_000) =>
{
Some(o * 10)
}
_ => None,
};
if let Some(tint) = tint {
return Some(Color::Theme { id, tint });
}
}
self.resolve(theme)
.map(|rgb| Color::Argb(0xFF00_0000 | rgb))
}
#[cfg(feature = "write")]
pub(crate) fn from_style(color: &crate::style::Color) -> Option<Self> {
use crate::style::Color;
match color {
Color::Theme { id, tint } => {
let name = *SCHEME_NAMES.get(usize::try_from(*id).ok()?)?;
let mut color = Self::scheme(name);
let tint = tint.clamp(&-1_000_000, &1_000_000) / 10;
if tint < 0 {
color
.transforms
.push(ColorTransform::LumMod(100_000 + tint));
} else if tint > 0 {
color
.transforms
.push(ColorTransform::LumMod(100_000 - tint));
color.transforms.push(ColorTransform::LumOff(tint));
}
Some(color)
}
Color::Auto => None,
other => crate::shared::palette::rgb_of(other, None).map(Self::rgb),
}
}
}
#[cfg(feature = "write")]
const SCHEME_NAMES: [&str; 12] = [
"bg1", "tx1", "bg2", "tx2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6",
"hlink", "folHlink",
];
fn scheme_id(name: &str) -> Option<u32> {
Some(match name {
"lt1" | "bg1" => 0,
"dk1" | "tx1" => 1,
"lt2" | "bg2" => 2,
"dk2" | "tx2" => 3,
"accent1" => 4,
"accent2" => 5,
"accent3" => 6,
"accent4" => 7,
"accent5" => 8,
"accent6" => 9,
"hlink" => 10,
"folHlink" => 11,
_ => return None,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColorBase {
Rgb(u32),
Scheme(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorTransform {
LumMod(i32),
LumOff(i32),
Tint(i32),
Shade(i32),
Alpha(i32),
}
impl ColorTransform {
#[must_use]
pub fn parse(name: &str, value: i32) -> Option<Self> {
Some(match name {
"lumMod" => Self::LumMod(value),
"lumOff" => Self::LumOff(value),
"tint" => Self::Tint(value),
"shade" => Self::Shade(value),
"alpha" => Self::Alpha(value),
_ => return None,
})
}
#[must_use]
pub const fn parts(self) -> (&'static str, i32) {
match self {
Self::LumMod(v) => ("lumMod", v),
Self::LumOff(v) => ("lumOff", v),
Self::Tint(v) => ("tint", v),
Self::Shade(v) => ("shade", v),
Self::Alpha(v) => ("alpha", v),
}
}
fn apply(self, rgb: u32) -> u32 {
let (_, v) = self.parts();
let f = f64::from(v) / 100_000.0;
match self {
Self::LumMod(_) => crate::shared::palette::map_lightness(rgb, |l| l * f),
Self::LumOff(_) => crate::shared::palette::map_lightness(rgb, |l| l + f),
Self::Tint(_) => map_channels(rgb, |c| c * f + (1.0 - f)),
Self::Shade(_) => map_channels(rgb, |c| c * f),
Self::Alpha(_) => rgb,
}
}
}
fn map_channels(rgb: u32, f: impl Fn(f64) -> f64) -> u32 {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to 0..=255 first"
)]
let channel = |shift: u32| {
let c = f64::from((rgb >> shift) & 0xFF) / 255.0;
(f(c) * 255.0).round().clamp(0.0, 255.0) as u32
};
(channel(16) << 16) | (channel(8) << 8) | channel(0)
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SeriesMarker {
pub symbol: Option<MarkerSymbol>,
pub size: Option<u8>,
pub format: Option<ShapeFormat>,
pub source: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MarkerSymbol {
Auto,
None,
Circle,
Dash,
Diamond,
Dot,
Picture,
Plus,
Square,
Star,
Triangle,
X,
}
impl MarkerSymbol {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Some(match value {
"auto" => Self::Auto,
"none" => Self::None,
"circle" => Self::Circle,
"dash" => Self::Dash,
"diamond" => Self::Diamond,
"dot" => Self::Dot,
"picture" => Self::Picture,
"plus" => Self::Plus,
"square" => Self::Square,
"star" => Self::Star,
"triangle" => Self::Triangle,
"x" => Self::X,
_ => return None,
})
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::None => "none",
Self::Circle => "circle",
Self::Dash => "dash",
Self::Diamond => "diamond",
Self::Dot => "dot",
Self::Picture => "picture",
Self::Plus => "plus",
Self::Square => "square",
Self::Star => "star",
Self::Triangle => "triangle",
Self::X => "x",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DataPoint {
pub index: u32,
pub format: Option<ShapeFormat>,
pub marker: Option<SeriesMarker>,
pub source: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[expect(
clippy::struct_excessive_bools,
reason = "independent switches, one element each in the file"
)]
pub struct DataLabels {
pub points: Vec<DataLabel>,
pub deleted: bool,
pub position: Option<LabelPosition>,
pub show_legend_key: bool,
pub show_value: bool,
pub show_category_name: bool,
pub show_series_name: bool,
pub show_percent: bool,
pub source: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[expect(
clippy::struct_excessive_bools,
reason = "independent switches, one element each in the file"
)]
pub struct DataLabel {
pub index: u32,
pub deleted: bool,
pub position: Option<LabelPosition>,
pub show_legend_key: bool,
pub show_value: bool,
pub show_category_name: bool,
pub show_series_name: bool,
pub show_percent: bool,
pub source: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelPosition {
BestFit,
Bottom,
Center,
InsideBase,
InsideEnd,
Left,
OutsideEnd,
Right,
Top,
}
impl LabelPosition {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Some(match value {
"bestFit" => Self::BestFit,
"b" => Self::Bottom,
"ctr" => Self::Center,
"inBase" => Self::InsideBase,
"inEnd" => Self::InsideEnd,
"l" => Self::Left,
"outEnd" => Self::OutsideEnd,
"r" => Self::Right,
"t" => Self::Top,
_ => return None,
})
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::BestFit => "bestFit",
Self::Bottom => "b",
Self::Center => "ctr",
Self::InsideBase => "inBase",
Self::InsideEnd => "inEnd",
Self::Left => "l",
Self::OutsideEnd => "outEnd",
Self::Right => "r",
Self::Top => "t",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DataSource {
Numbers {
formula: Option<String>,
format_code: Option<String>,
count: Option<u32>,
points: Vec<(u32, f64)>,
},
Strings {
formula: Option<String>,
count: Option<u32>,
points: Vec<(u32, String)>,
},
Levels {
formula: Option<String>,
markup: String,
},
}
impl DataSource {
#[must_use]
pub fn numbers(formula: impl Into<String>) -> Self {
Self::Numbers {
formula: Some(formula.into()),
format_code: None,
count: None,
points: Vec::new(),
}
}
#[must_use]
pub fn strings(formula: impl Into<String>) -> Self {
Self::Strings {
formula: Some(formula.into()),
count: None,
points: Vec::new(),
}
}
#[must_use]
pub fn formula(&self) -> Option<&str> {
match self {
Self::Numbers { formula, .. }
| Self::Strings { formula, .. }
| Self::Levels { formula, .. } => formula.as_deref(),
}
}
fn formula_mut(&mut self) -> Option<&mut String> {
match self {
Self::Numbers { formula, .. } | Self::Strings { formula, .. } => formula.as_mut(),
Self::Levels { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChartAxis {
pub kind: AxisKind,
pub id: u32,
pub cross_axis: u32,
pub position: AxisPosition,
pub deleted: bool,
pub reversed: bool,
pub min: Option<f64>,
pub max: Option<f64>,
pub log_base: Option<f64>,
pub title: Option<Title>,
pub number_format: Option<(String, bool)>,
pub markup: AxisMarkup,
}
impl ChartAxis {
#[must_use]
pub fn category(id: u32, cross_axis: u32) -> Self {
Self::new(AxisKind::Category, id, cross_axis, AxisPosition::Bottom)
}
#[must_use]
pub fn value(id: u32, cross_axis: u32) -> Self {
Self::new(AxisKind::Value, id, cross_axis, AxisPosition::Left)
}
#[must_use]
pub fn new(kind: AxisKind, id: u32, cross_axis: u32, position: AxisPosition) -> Self {
Self {
kind,
id,
cross_axis,
position,
deleted: false,
reversed: false,
min: None,
max: None,
log_base: None,
title: None,
number_format: None,
markup: AxisMarkup::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AxisMarkup {
pub gridlines: String,
pub ticks: String,
pub tail: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AxisKind {
Category,
Value,
Date,
Series,
}
impl AxisKind {
#[must_use]
pub const fn element(self) -> &'static str {
match self {
Self::Category => "catAx",
Self::Value => "valAx",
Self::Date => "dateAx",
Self::Series => "serAx",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AxisPosition {
#[default]
Bottom,
Left,
Right,
Top,
}
impl AxisPosition {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"l" => Self::Left,
"r" => Self::Right,
"t" => Self::Top,
_ => Self::Bottom,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Bottom => "b",
Self::Left => "l",
Self::Right => "r",
Self::Top => "t",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Legend {
pub position: LegendPosition,
pub layout: Option<ManualLayout>,
pub markup: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LegendPosition {
Bottom,
Left,
#[default]
Right,
Top,
TopRight,
}
impl LegendPosition {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"b" => Self::Bottom,
"l" => Self::Left,
"t" => Self::Top,
"tr" => Self::TopRight,
_ => Self::Right,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Bottom => "b",
Self::Left => "l",
Self::Right => "r",
Self::Top => "t",
Self::TopRight => "tr",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ChartMarkup {
pub before_chart: String,
pub before_plot_area: String,
pub plot_area_layout: String,
pub after_axes: String,
pub after_legend: String,
pub after_chart: String,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ChartEx {
pub name: String,
pub anchor: Anchor,
pub part: String,
pub title: Option<ChartText>,
pub series: Vec<ExSeries>,
pub legend: Option<ExLegend>,
pub origin: Option<ChartExOrigin>,
}
impl ChartEx {
#[must_use]
pub fn new(layout: SeriesLayout, dimensions: Vec<Dimension>, anchor: Anchor) -> Self {
Self {
anchor,
series: vec![ExSeries::new(layout, dimensions)],
..Self::default()
}
}
#[must_use]
pub fn is_unchanged(&self) -> bool {
self.origin
.as_ref()
.is_some_and(|o| self.same_placement(&o.read) && self.same_content(&o.read))
}
pub(crate) fn same_placement(&self, other: &Self) -> bool {
self.name == other.name && self.anchor == other.anchor
}
pub(crate) fn same_content(&self, other: &Self) -> bool {
self.title == other.title && self.series == other.series && self.legend == other.legend
}
pub(crate) fn settle(&mut self) {
if let Some(mut origin) = self.origin.take() {
origin.read = Box::new(self.clone());
self.origin = Some(origin);
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChartExOrigin {
pub(crate) drawing: String,
pub(crate) id: u32,
pub(crate) grouped: bool,
pub(crate) read: Box<ChartEx>,
}
impl ChartExOrigin {
#[must_use]
pub fn drawing(&self) -> &str {
&self.drawing
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ExSeries {
pub layout: SeriesLayout,
pub name: Option<ChartText>,
pub hidden: bool,
pub dimensions: Vec<Dimension>,
pub points: Vec<ExPoint>,
pub labels: Option<ExLabels>,
pub binning: Option<Binning>,
pub subtotals: Vec<u32>,
}
impl ExSeries {
#[must_use]
pub fn new(layout: SeriesLayout, dimensions: Vec<Dimension>) -> Self {
Self {
layout,
name: None,
hidden: false,
dimensions,
points: Vec::new(),
labels: None,
binning: None,
subtotals: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExPoint {
pub index: u32,
pub format: ShapeFormat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ExLabels {
pub position: Option<LabelPosition>,
pub series_name: bool,
pub category_name: bool,
pub value: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Binning {
pub closed_left: bool,
pub underflow: Option<BinEdge>,
pub overflow: Option<BinEdge>,
pub bins: Option<Bins>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinEdge {
Auto,
Value(f64),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Bins {
Width(f64),
Count(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ExLegend {
pub position: LegendPosition,
pub overlay: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeriesLayout {
BoxWhisker,
ClusteredColumn,
Funnel,
ParetoLine,
RegionMap,
Sunburst,
Treemap,
Waterfall,
Unknown,
}
impl SeriesLayout {
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"boxWhisker" => Self::BoxWhisker,
"clusteredColumn" => Self::ClusteredColumn,
"funnel" => Self::Funnel,
"paretoLine" => Self::ParetoLine,
"regionMap" => Self::RegionMap,
"sunburst" => Self::Sunburst,
"treemap" => Self::Treemap,
"waterfall" => Self::Waterfall,
_ => Self::Unknown,
}
}
#[must_use]
pub const fn as_str(self) -> Option<&'static str> {
Some(match self {
Self::BoxWhisker => "boxWhisker",
Self::ClusteredColumn => "clusteredColumn",
Self::Funnel => "funnel",
Self::ParetoLine => "paretoLine",
Self::RegionMap => "regionMap",
Self::Sunburst => "sunburst",
Self::Treemap => "treemap",
Self::Waterfall => "waterfall",
Self::Unknown => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dimension {
pub role: DimensionRole,
pub numeric: bool,
pub formula: Option<String>,
pub levels: Vec<Vec<(u32, String)>>,
}
impl Dimension {
#[must_use]
pub fn reference<'a>(&'a self, names: &'a [DefinedName]) -> Option<&'a str> {
let formula = self.formula.as_deref()?;
Some(
names
.iter()
.find(|n| n.sheet.is_none() && n.name == formula)
.map_or(formula, |n| n.formula.as_str()),
)
}
#[cfg(feature = "formulas")]
#[must_use]
pub fn strings(
&self,
book: &crate::model::Spreadsheet,
sheet: usize,
) -> Option<Vec<(u32, String)>> {
crate::formula::chart::dimension_strings(book, sheet, self)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DimensionRole {
Categories,
Values,
Sizes,
X,
Y,
ColorValues,
ColorStrings,
EntityIds,
}
impl DimensionRole {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Some(match value {
"cat" => Self::Categories,
"val" => Self::Values,
"size" => Self::Sizes,
"x" => Self::X,
"y" => Self::Y,
"colorVal" => Self::ColorValues,
"colorStr" => Self::ColorStrings,
"entityId" => Self::EntityIds,
_ => return None,
})
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Categories => "cat",
Self::Values => "val",
Self::Sizes => "size",
Self::X => "x",
Self::Y => "y",
Self::ColorValues => "colorVal",
Self::ColorStrings => "colorStr",
Self::EntityIds => "entityId",
}
}
}