use f_office_drawingml::color::{DrawColor, SchemeSlot};
use f_office_drawingml::gradient::LinearGradient;
use f_office_drawingml::shape::{Geometry, ShapeLook};
use f_office_units::scale::{HALF_POINTS_PER_POINT, PERCENT, QUARTER_TURN, TENTHS, THOUSANDTHS};
use f_office_units::{Edges, Length};
use f_office_warnings::{Warned, Warnings};
use f_office_xml::enumeration::{Values, own};
use f_office_xml::{Document, NodeId};
use crate::body::{Block, DrawingMut, visit_drawings};
use crate::floating::{Floating, body_insets};
use crate::ns::{A, C, R};
use crate::params::{
CHART_DATA_LABEL_INSETS, CHART_EXPONENT_LIMIT, CHART_GAP_WIDTH, CHART_OVERLAP,
CHART_STYLE_C14_OFFSET, CHART_STYLE_COLUMNS, CHART_STYLE_DARK_TINTS, CHART_STYLE_FLAT_ROWS,
CHART_STYLE_LINE_TINT, CHART_STYLE_MAX, CHART_STYLE_SHADE_FLOOR, CHART_STYLED_TITLE_SIZE,
CHART_TEXT_SIZE, MAX_CHART_POINTS,
};
use crate::props::FontRef;
use crate::reader::settings::PlotRules;
use crate::reader::{PartReader, picture_fill_warning};
use crate::warnings::{ChartReason, DrawingMlFeature, DrawingMlWarning};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Chart {
pub id: String,
pub columns: Option<Box<Columns>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Columns {
pub series: Vec<Series>,
pub categories: usize,
pub group: ChartGroup,
pub title: Option<Title>,
pub legend: Option<LegendPlace>,
pub legend_box: LegendBox,
pub label_size: i64,
pub legend_size: i64,
pub value_label_size: i64,
pub font: FontRef,
pub gridlines: Option<ShapeLook>,
pub axis: ShapeLook,
pub value_axis: ShapeLook,
pub ticks: OutsideTicks,
pub plot_place: PlotPlace,
pub scale: SetScale,
pub category_crossing: Option<CategoryCrossing>,
pub axis_titles: AxisTitles,
pub value_format: Option<LabelFormat>,
pub category_names: Option<Vec<String>>,
pub value_label_fill: Option<DrawColor>,
pub category_label_fill: Option<DrawColor>,
pub legend_font: FontRef,
pub legend_fill: Option<DrawColor>,
pub legend_text: LegendText,
pub other_labels: bool,
pub axis_forms: AxisForms,
pub secondary_axis: Option<Box<SecondaryValueAxis>>,
pub data_table: Option<Box<DataTable>>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DataTableBorders {
pub horz: bool,
pub vert: bool,
pub outline: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTable {
pub borders: DataTableBorders,
pub keys: bool,
pub border: ShapeLook,
pub text_size: i64,
pub text_font: FontRef,
pub text_fill: Option<DrawColor>,
pub bold: bool,
pub italic: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SecondaryValueAxis {
pub scale: SetScale,
pub format: LabelFormat,
pub label_size: i64,
pub label_fill: Option<DrawColor>,
pub line: ShapeLook,
pub ticks: bool,
pub labels_hidden: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AxisForms {
pub value_deleted: bool,
pub category_hidden: bool,
pub low_labels: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CategoryCrossing {
AutoZero,
Min,
At(Decimal),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AxisTitles {
Drawn {
value: Option<Box<AxisTitle>>,
category: Option<Box<AxisTitle>>,
},
Other,
}
impl AxisTitles {
pub const NONE: Self = Self::Drawn {
value: None,
category: None,
};
pub fn sides(&self, group: &ChartGroup) -> Option<(Option<&AxisTitle>, Option<&AxisTitle>)> {
let Self::Drawn { value, category } = self else {
return None;
};
if matches!(group, ChartGroup::Bars { .. }) {
Some((category.as_deref(), value.as_deref()))
} else {
Some((value.as_deref(), category.as_deref()))
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AxisTitle {
pub size: i64,
pub text: TitleText,
pub corner: Option<LayoutCorner>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BarStacking {
Clustered,
Stacked,
PercentStacked,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BarColorMode {
None,
BySeries,
ByCategory,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PieExplosion {
pub series: u32,
pub slices: Vec<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChartGroup {
Columns {
gap: i64,
overlap: i64,
stacking: BarStacking,
},
Bars {
gap: i64,
overlap: i64,
stacking: BarStacking,
},
Lines {
looks: Vec<LineLook>,
stacking: BarStacking,
},
Scatter {
looks: Vec<LineLook>,
x_values: Vec<Vec<Decimal>>,
x_scale: SetScale,
},
Pie {
first_angle: i64,
view: Option<pie::PieView>,
fills: Vec<DrawColor>,
labels: PieLabelPlace,
explosion: PieExplosion,
},
Columns3D {
gap: i64,
gap_depth: i64,
view: ColumnView,
},
Doughnut {
first_angle: i64,
hole_size: u32,
},
Combo {
gap: i64,
overlap: i64,
stacking: BarStacking,
bar_count: usize,
looks: Vec<LineLook>,
line_stacking: BarStacking,
},
}
impl ChartGroup {
const fn has_blank_points(&self) -> bool {
match self {
Self::Columns { .. }
| Self::Bars { .. }
| Self::Columns3D { .. }
| Self::Lines { .. }
| Self::Pie { .. }
| Self::Doughnut { .. }
| Self::Combo { .. } => true,
Self::Scatter { .. } => false,
}
}
pub(crate) const fn stacking(&self) -> Option<BarStacking> {
match *self {
Self::Columns { stacking, .. }
| Self::Bars { stacking, .. }
| Self::Combo { stacking, .. } => Some(stacking),
Self::Columns3D { .. } => Some(BarStacking::Clustered),
Self::Lines { .. }
| Self::Scatter { .. }
| Self::Pie { .. }
| Self::Doughnut { .. } => None,
}
}
pub(crate) const fn line_stacking(&self) -> Option<BarStacking> {
match *self {
Self::Lines { stacking, .. } => Some(stacking),
Self::Combo { line_stacking, .. } => Some(line_stacking),
Self::Columns { .. }
| Self::Bars { .. }
| Self::Columns3D { .. }
| Self::Scatter { .. }
| Self::Pie { .. }
| Self::Doughnut { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PieLabelPlace {
Center,
InnerEnd,
OuterEnd,
BestFit,
}
impl PieLabelPlace {
#[must_use]
pub const fn outside(self) -> bool {
matches!(self, Self::OuterEnd | Self::BestFit)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LineLook {
pub width: Option<StyleWidth>,
pub marker: Option<Marker>,
pub form: LineForm,
pub dash: Option<LineDash>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineDash {
Dot,
Dash,
LongDash,
DashDot,
LongDashDot,
LongDashDotDot,
SystemDash,
SystemDot,
SystemDashDot,
SystemDashDotDot,
}
impl LineDash {
#[must_use]
pub const fn pattern(self) -> &'static [i64] {
use crate::params::{
PRESET_DASH_WIDTHS as DASH, PRESET_DOT_WIDTHS as DOT, PRESET_GAP_WIDTHS as GAP,
PRESET_LONG_DASH_WIDTHS as LONG, PRESET_SYSTEM_DASH_WIDTHS as SYSTEM,
PRESET_SYSTEM_GAP_WIDTHS as SYSTEM_GAP,
};
match self {
Self::Dot => &[DOT, GAP],
Self::Dash => &[DASH, GAP],
Self::LongDash => &[LONG, GAP],
Self::DashDot => &[DASH, GAP, DOT, GAP],
Self::LongDashDot => &[LONG, GAP, DOT, GAP],
Self::LongDashDotDot => &[LONG, GAP, DOT, GAP, DOT, GAP],
Self::SystemDash => &[SYSTEM, SYSTEM_GAP],
Self::SystemDot => &[DOT, SYSTEM_GAP],
Self::SystemDashDot => &[SYSTEM, SYSTEM_GAP, DOT, SYSTEM_GAP],
Self::SystemDashDotDot => &[SYSTEM, SYSTEM_GAP, DOT, SYSTEM_GAP, DOT, SYSTEM_GAP],
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineForm {
Straight,
Smooth,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StyleWidth {
Set(Length),
Automatic,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Marker {
pub symbol: MarkerSymbol,
pub size: Option<Length>,
pub fill: Option<DrawColor>,
pub outline: Option<MarkerOutline>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MarkerOutline {
pub color: Option<DrawColor>,
pub width: StyleWidth,
}
impl MarkerOutline {
pub const STYLE: Self = Self {
color: None,
width: StyleWidth::Automatic,
};
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MarkerSymbol {
Circle,
Diamond,
Square,
Triangle,
X,
Star,
}
const AUTOMATIC_SYMBOLS: [MarkerSymbol; 6] = [
MarkerSymbol::Diamond,
MarkerSymbol::Square,
MarkerSymbol::Triangle,
MarkerSymbol::X,
MarkerSymbol::Star,
MarkerSymbol::Circle,
];
#[derive(Clone, Copy)]
enum SymbolCase {
Drawn(MarkerSymbol),
Hidden,
Other,
}
const MARKER_SYMBOLS: &Values<SymbolCase> = &Values::new(&[
own("circle", SymbolCase::Drawn(MarkerSymbol::Circle)),
own("diamond", SymbolCase::Drawn(MarkerSymbol::Diamond)),
own("square", SymbolCase::Drawn(MarkerSymbol::Square)),
own("triangle", SymbolCase::Drawn(MarkerSymbol::Triangle)),
own("x", SymbolCase::Drawn(MarkerSymbol::X)),
own("star", SymbolCase::Drawn(MarkerSymbol::Star)),
own("none", SymbolCase::Hidden),
own("auto", SymbolCase::Other),
own("dash", SymbolCase::Other),
own("dot", SymbolCase::Other),
own("picture", SymbolCase::Other),
own("plus", SymbolCase::Other),
]);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LegendText {
pub bold: bool,
pub italic: bool,
pub own_entries: bool,
}
impl LegendText {
fn read(doc: &Document, legend: NodeId) -> Self {
let run = default_run(doc, legend);
let on = |name| {
run.and_then(|run| doc.attribute(run, None, name))
.is_some_and(f_office_drawingml::boolean)
};
Self {
bold: on("b"),
italic: on("i"),
own_entries: doc.child(legend, C, "legendEntry").is_some(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlotRule {
DefaultChart,
FontLines,
}
impl Columns {
#[must_use]
pub(crate) fn bar_series(&self) -> &[Series] {
match self.group {
ChartGroup::Columns { .. } | ChartGroup::Bars { .. } | ChartGroup::Columns3D { .. } => {
&self.series
}
ChartGroup::Combo { bar_count, .. } => self.series.get(..bar_count).unwrap_or_default(),
ChartGroup::Lines { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. } => &[],
}
}
#[must_use]
pub(crate) fn line_series(&self) -> &[Series] {
match self.group {
ChartGroup::Lines { .. } | ChartGroup::Scatter { .. } => &self.series,
ChartGroup::Combo { bar_count, .. } => self.series.get(bar_count..).unwrap_or_default(),
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Columns3D { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. } => &[],
}
}
pub fn default_chart_rule(&self) -> Result<PlotRule, ChartReason> {
let other_group = match self.group {
ChartGroup::Scatter { .. } => ChartReason::Scatter,
ChartGroup::Bars { .. } => ChartReason::HorizontalBars,
ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } | ChartGroup::Columns3D { .. } => {
ChartReason::OtherGroup
}
ChartGroup::Combo { .. } => ChartReason::NotOneGroup,
ChartGroup::Columns {
stacking: BarStacking::Stacked | BarStacking::PercentStacked,
..
} => ChartReason::NotClustered,
ChartGroup::Columns { .. } | ChartGroup::Lines { .. } => ChartReason::Lines,
};
meets([
(
matches!(
self.group,
ChartGroup::Columns {
stacking: BarStacking::Clustered,
..
}
),
other_group,
),
(self.title.is_some(), ChartReason::Untitled),
(
self.legend == Some(LegendPlace::Bottom),
ChartReason::LegendNotAtBottom,
),
(self.scale == SetScale::default(), ChartReason::SetScale),
(
self.series
.iter()
.flat_map(|s| s.values.iter().flatten())
.all(|v| !v.digits.is_negative()),
ChartReason::NegativeValue,
),
(self.data_table.is_none(), ChartReason::DataTable),
])
.map(|()| PlotRule::DefaultChart)
}
fn draws_axis_titles(&self) -> bool {
match self.axis_titles {
AxisTitles::Drawn { .. } if self.axis_titles == AxisTitles::NONE => true,
AxisTitles::Drawn { .. } => {
self.plot_place != PlotPlace::Other && self.legend != Some(LegendPlace::Left)
}
AxisTitles::Other => false,
}
}
pub fn font_lines_rule(&self) -> Result<PlotRule, ChartReason> {
let side = matches!(self.legend, Some(LegendPlace::Left | LegendPlace::Right));
if matches!(
self.group,
ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. }
) {
return meets([
(
self.plot_place != PlotPlace::Other,
ChartReason::OtherPlotPlace,
),
(
!(side && self.category_names.is_none()),
ChartReason::UnnamedSeriesBesideLegend,
),
])
.map(|()| PlotRule::FontLines);
}
let missing_legend_name = match self.series.as_slice() {
[one] if matches!(one.fill, SeriesFill::Points(_)) => self.category_names.is_none(),
_ => self.series.iter().any(|s| s.name.is_none()),
};
meets([
(self.category_crossing.is_some(), ChartReason::SetCrossing),
(
self.plot_place != PlotPlace::Other,
ChartReason::OtherPlotPlace,
),
(
!(side && missing_legend_name),
ChartReason::UnnamedSeriesBesideLegend,
),
(self.draws_axis_titles(), ChartReason::AxisTitle),
(self.value_format.is_some(), ChartReason::OtherNumberFormat),
])
.map(|()| PlotRule::FontLines)
.or_else(|reason| self.default_chart_rule().map_err(|_| reason))
}
}
const SHOWN_LABEL_PARTS: [&str; 5] = [
"showVal",
"showPercent",
"showCatName",
"showSerName",
"showBubbleSize",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Flag {
On,
Off,
Missing,
}
impl Flag {
fn of(doc: &Document, node: NodeId, name: &str) -> Self {
match doc.child(node, C, name) {
None => Self::Missing,
Some(flag) => {
if doc
.attribute(flag, None, "val")
.is_none_or(f_office_drawingml::boolean)
{
Self::On
} else {
Self::Off
}
}
}
}
const fn is_on(self) -> bool {
matches!(self, Self::On)
}
}
fn shows_labels(doc: &Document, labels: NodeId) -> bool {
!Flag::of(doc, labels, "delete").is_on()
&& SHOWN_LABEL_PARTS
.iter()
.any(|name| Flag::of(doc, labels, name).is_on())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DataLabelPosition {
Default,
BestFit,
Center,
InsideBase,
InsideEnd,
OutsideEnd,
Top,
Bottom,
Left,
Right,
Other,
}
const DATA_LABEL_POSITIONS: [(&str, DataLabelPosition); 9] = [
("bestFit", DataLabelPosition::BestFit),
("ctr", DataLabelPosition::Center),
("inBase", DataLabelPosition::InsideBase),
("inEnd", DataLabelPosition::InsideEnd),
("outEnd", DataLabelPosition::OutsideEnd),
("t", DataLabelPosition::Top),
("b", DataLabelPosition::Bottom),
("l", DataLabelPosition::Left),
("r", DataLabelPosition::Right),
];
const COLUMN_LABEL_POSITIONS: [DataLabelPosition; 5] = [
DataLabelPosition::Default,
DataLabelPosition::OutsideEnd,
DataLabelPosition::Center,
DataLabelPosition::InsideEnd,
DataLabelPosition::InsideBase,
];
const STACKED_LABEL_POSITIONS: [DataLabelPosition; 4] = [
DataLabelPosition::Default,
DataLabelPosition::Center,
DataLabelPosition::InsideEnd,
DataLabelPosition::InsideBase,
];
const LINE_LABEL_POSITIONS: [DataLabelPosition; 6] = [
DataLabelPosition::Default,
DataLabelPosition::Center,
DataLabelPosition::Top,
DataLabelPosition::Bottom,
DataLabelPosition::Left,
DataLabelPosition::Right,
];
impl DataLabelPosition {
fn own(doc: &Document, node: NodeId) -> Self {
value(doc, node, "dLblPos").map_or(Self::Default, |written| {
DATA_LABEL_POSITIONS
.iter()
.find(|(name, _)| *name == written)
.map_or(Self::Other, |&(_, position)| position)
})
}
fn of(doc: &Document, labels: NodeId) -> Self {
let position = Self::own(doc, labels);
let agreed = doc
.child_elements(labels)
.filter(|&node| doc.is(node, C, "dLbl") && doc.child(node, C, "dLblPos").is_some())
.all(|point| Self::own(doc, point) == position);
if agreed { position } else { Self::Other }
}
fn for_pie(doc: &Document, labels: NodeId) -> Self {
let series = Self::own(doc, labels);
let has_deleted = doc
.child_elements(labels)
.any(|node| doc.is(node, C, "dLbl") && Flag::of(doc, node, "delete") == Flag::On);
let points = doc.child_elements(labels).filter(|&node| {
doc.is(node, C, "dLbl")
&& Flag::of(doc, node, "delete") != Flag::On
&& doc.child(node, C, "dLblPos").is_some()
});
let positions: Vec<Self> = std::iter::once(series)
.chain(points.map(|point| Self::own(doc, point)))
.collect();
if positions.iter().any(|pos| {
!matches!(
pos,
Self::Default | Self::BestFit | Self::Center | Self::InsideEnd | Self::OutsideEnd
)
}) {
Self::Other
} else if has_deleted || positions.iter().all(|&pos| pos == series) {
series
} else if positions
.iter()
.any(|pos| matches!(pos, Self::Center | Self::InsideEnd))
{
Self::Center
} else {
Self::BestFit
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum MarkupPercent {
Hidden,
Shown,
}
struct MarkupLabelParts {
show_ser_name: bool,
show_cat_name: bool,
show_val: bool,
percent: MarkupPercent,
separator: Option<String>,
own_format: Option<FormatCode>,
}
enum MarkupPointLabel {
Deleted,
Custom(Box<MarkupPointSpec>),
}
struct MarkupPointSpec {
position: DataLabelPosition,
size: Option<i64>,
font: Option<FontRef>,
fill: Box<Look<Option<DrawColor>>>,
insets: Edges<Length>,
format: FormatCode,
parts: MarkupLabelParts,
rich_lines: Option<Vec<String>>,
layout: PointLabelLayout,
}
enum LabelMarkup {
Hidden,
Values {
show_default: bool,
position: DataLabelPosition,
size: Option<i64>,
font: Option<FontRef>,
fill: Box<Look<Option<DrawColor>>>,
insets: Edges<Length>,
format: FormatCode,
parts: Box<MarkupLabelParts>,
point_overrides: Vec<(usize, MarkupPointLabel)>,
},
Other,
}
impl LabelMarkup {
fn drawn(
self,
(drawn_at, allow_percent, rules): (&[DataLabelPosition], bool, PlotRules),
text: &ChartText,
warnings: &mut Warnings<DrawingMlWarning>,
) -> SeriesLabels {
match self {
Self::Hidden => SeriesLabels::Hidden,
Self::Other => SeriesLabels::Other,
Self::Values {
show_default,
position,
size,
font,
fill,
insets,
format,
parts,
point_overrides,
} => {
if show_default && !drawn_at.contains(&position) {
return SeriesLabels::Other;
}
let Some((val_format, percent, parts_sep, show_ser, show_cat, show_val)) =
resolve_series_parts(show_default, *parts, &format, (allow_percent, rules))
else {
return SeriesLabels::Other;
};
let Some(resolved_points) = resolve_point_overrides(
point_overrides,
position,
(drawn_at, allow_percent, rules),
text,
warnings,
) else {
return SeriesLabels::Other;
};
let fill = *fill;
warnings.extend(fill.warnings, std::convert::identity);
SeriesLabels::Values(DataLabelText {
position,
size: text.size(size),
font: text.font(font),
fill: fill.value,
insets,
format: val_format,
parts: DataLabelParts {
show_ser_name: show_ser,
show_cat_name: show_cat,
show_val,
percent,
separator: parts_sep,
},
show_default,
point_overrides: resolved_points,
})
}
}
}
}
fn resolve_series_parts(
active: bool,
parts: MarkupLabelParts,
format: &FormatCode,
(allow_percent, rules): (bool, PlotRules),
) -> Option<(LabelFormat, PercentMode, Option<String>, bool, bool, bool)> {
if !active {
return Some((
LabelFormat::all_digits(),
PercentMode::Hidden,
parts.separator,
false,
false,
false,
));
}
if parts.percent == MarkupPercent::Shown && !allow_percent {
return None;
}
let val_format = if parts.show_val {
format.decided(rules, LabelPlace::Data)?
} else {
LabelFormat::all_digits()
};
let percent = resolved_percent_mode(parts.percent, parts.own_format.as_ref(), rules)?;
Some((
val_format,
percent,
parts.separator,
parts.show_ser_name,
parts.show_cat_name,
parts.show_val,
))
}
fn resolve_point_overrides(
overrides: Vec<(usize, MarkupPointLabel)>,
series_position: DataLabelPosition,
(drawn_at, allow_percent, rules): (&[DataLabelPosition], bool, PlotRules),
text: &ChartText,
warnings: &mut Warnings<DrawingMlWarning>,
) -> Option<Vec<(usize, PointLabelOverride)>> {
let mut out = Vec::with_capacity(overrides.len());
for (idx, item) in overrides {
match item {
MarkupPointLabel::Deleted => out.push((idx, PointLabelOverride::Deleted)),
MarkupPointLabel::Custom(spec) => {
let spec = *spec;
let effective_pos = if spec.position == DataLabelPosition::Default
&& !drawn_at.contains(&DataLabelPosition::Default)
{
series_position
} else {
spec.position
};
if !drawn_at.contains(&effective_pos) {
return None;
}
let has_rich = spec.rich_lines.is_some();
let (val_format, percent, sep, show_ser, show_cat, show_val) =
resolve_series_parts(
!has_rich,
spec.parts,
&spec.format,
(allow_percent, rules),
)?;
let fill = *spec.fill;
warnings.extend(fill.warnings, std::convert::identity);
out.push((
idx,
PointLabelOverride::Custom(Box::new(PointLabelSpec {
label: DataLabelText {
position: effective_pos,
size: text.size(spec.size),
font: text.font(spec.font),
fill: fill.value,
insets: spec.insets,
format: val_format,
parts: DataLabelParts {
show_ser_name: show_ser,
show_cat_name: show_cat,
show_val,
percent,
separator: sep,
},
show_default: true,
point_overrides: Vec::new(),
},
rich_lines: spec.rich_lines,
layout: spec.layout,
})),
));
}
}
}
Some(out)
}
fn resolved_percent_mode(
percent: MarkupPercent,
own_format: Option<&FormatCode>,
rules: PlotRules,
) -> Option<PercentMode> {
if percent == MarkupPercent::Hidden {
return Some(PercentMode::Hidden);
}
let Some(own) = own_format else {
return Some(PercentMode::Integer);
};
let trimmed = own.0.trim();
if !trimmed.contains('%') || trimmed == "0%" {
return Some(PercentMode::Integer);
}
own.decided(rules, LabelPlace::Data)
.map(PercentMode::Format)
}
fn own_num_fmt(doc: &Document, node: NodeId) -> Option<FormatCode> {
doc.child(node, C, "numFmt")
.filter(|&own| {
!doc.attribute(own, None, "sourceLinked")
.is_some_and(f_office_drawingml::boolean)
})
.map(|own| {
FormatCode(
doc.attribute(own, None, "formatCode")
.unwrap_or_default()
.to_owned(),
)
})
}
fn flag_default_on(doc: &Document, node: NodeId, name: &str) -> bool {
Flag::of(doc, node, name) != Flag::Off
}
fn read_point_layout(reader: &mut PartReader, point: NodeId) -> Option<PointLabelLayout> {
let doc = reader.doc;
let Some(layout) = doc.child(point, C, "layout") else {
return Some(PointLabelLayout::Automatic);
};
let Some(manual) = doc.child(layout, C, "manualLayout") else {
return Some(PointLabelLayout::Automatic);
};
let parsed = ManualLayout::read(reader, manual);
let [x, y, _, _] = parsed.edges;
match parsed.modes {
[LayoutMode::Edge, LayoutMode::Edge] => Some(PointLabelLayout::Edge { x: x?, y: y? }),
[LayoutMode::Factor, LayoutMode::Factor] => Some(PointLabelLayout::Offset {
dx: x.unwrap_or(Decimal::ZERO),
dy: y.unwrap_or(Decimal::ZERO),
}),
_ => None,
}
}
enum RichTextRead {
Absent,
Lines(Vec<String>),
Unsupported,
}
fn read_point_rich_lines(doc: &Document, point: NodeId) -> RichTextRead {
let Some(tx) = doc.child(point, C, "tx") else {
return RichTextRead::Absent;
};
let Some(rich) = doc.child(tx, C, "rich") else {
return RichTextRead::Unsupported;
};
let mut lines = Vec::new();
for para in doc.child_elements(rich).filter(|&n| doc.is(n, A, "p")) {
let mut line = String::new();
for child in doc.child_elements(para) {
if (doc.is(child, A, "r") || doc.is(child, A, "fld"))
&& let Some(t) = doc.child(child, A, "t")
{
line.push_str(&doc.text_content(t));
}
}
lines.push(line);
}
if lines.is_empty() {
RichTextRead::Unsupported
} else {
RichTextRead::Lines(lines)
}
}
struct SeriesLabelDefaults<'a> {
format: &'a FormatCode,
separator: Option<&'a str>,
size: Option<i64>,
font: Option<&'a FontRef>,
insets: Edges<Length>,
node: NodeId,
}
fn read_point_label(
reader: &mut PartReader,
point: NodeId,
series: &SeriesLabelDefaults<'_>,
) -> Option<(usize, MarkupPointLabel)> {
let doc = reader.doc;
let idx = read_value(reader, point, "idx", |v| v.parse::<usize>().ok())?;
if Flag::of(doc, point, "delete").is_on() {
return Some((idx, MarkupPointLabel::Deleted));
}
if flag_default_on(doc, point, "showLegendKey") || flag_default_on(doc, point, "showBubbleSize")
{
return None;
}
let position = DataLabelPosition::own(doc, point);
if position == DataLabelPosition::Other {
return None;
}
let layout = read_point_layout(reader, point)?;
let rich_lines = match read_point_rich_lines(doc, point) {
RichTextRead::Absent => None,
RichTextRead::Lines(lines) => Some(lines),
RichTextRead::Unsupported => return None,
};
let show_val = flag_default_on(doc, point, "showVal");
let show_cat_name = flag_default_on(doc, point, "showCatName");
let show_ser_name = flag_default_on(doc, point, "showSerName");
let show_percent = flag_default_on(doc, point, "showPercent");
let any_part = show_val || show_cat_name || show_ser_name || show_percent;
if rich_lines.is_none() && !any_part {
return Some((idx, MarkupPointLabel::Deleted));
}
let own_format = own_num_fmt(doc, point);
let format = own_format.clone().unwrap_or_else(|| series.format.clone());
let separator = doc
.child(point, C, "separator")
.map(|sep| doc.text_content(sep))
.or_else(|| series.separator.map(str::to_owned))
.or_else(|| Some(", ".to_owned()));
let body = doc
.child(point, C, "txPr")
.and_then(|text| doc.child(text, A, "bodyPr"));
let insets = if body.is_some() {
body_insets(reader, body, CHART_DATA_LABEL_INSETS)
} else {
series.insets
};
let own_fill = text_fill(doc, point);
let fill = if own_fill.value.is_some() {
own_fill
} else {
text_fill(doc, series.node)
};
Some((
idx,
MarkupPointLabel::Custom(Box::new(MarkupPointSpec {
position,
size: text_size(reader, point).or(series.size),
font: text_font(doc, point).or_else(|| series.font.cloned()),
fill: Box::new(fill),
insets,
format,
parts: MarkupLabelParts {
show_ser_name,
show_cat_name,
show_val,
percent: if show_percent {
MarkupPercent::Shown
} else {
MarkupPercent::Hidden
},
separator,
own_format,
},
rich_lines,
layout,
})),
))
}
fn label_markup(
reader: &mut PartReader,
labels: Option<NodeId>,
source: &FormatCode,
) -> LabelMarkup {
let doc = reader.doc;
let Some(labels) = labels else {
return LabelMarkup::Hidden;
};
let points: Vec<NodeId> = doc
.child_elements(labels)
.filter(|&node| doc.is(node, C, "dLbl"))
.collect();
let show_default = shows_labels(doc, labels);
if !show_default && !points.iter().any(|&point| shows_labels(doc, point)) {
return LabelMarkup::Hidden;
}
let own_format = own_num_fmt(doc, labels);
let format = own_format.clone().unwrap_or_else(|| source.clone());
let show_val = Flag::of(doc, labels, "showVal").is_on();
let show_cat_name = Flag::of(doc, labels, "showCatName").is_on();
let show_ser_name = Flag::of(doc, labels, "showSerName").is_on();
let show_percent = Flag::of(doc, labels, "showPercent").is_on();
let show_bubble = Flag::of(doc, labels, "showBubbleSize").is_on();
let any_part = show_val || show_cat_name || show_ser_name || show_percent;
let position = DataLabelPosition::own(doc, labels);
if show_default
&& (!any_part
|| show_bubble
|| Flag::of(doc, labels, "showLegendKey").is_on()
|| position == DataLabelPosition::Other)
{
return LabelMarkup::Other;
}
let separator = doc
.child(labels, C, "separator")
.map(|sep| doc.text_content(sep));
let body = doc
.child(labels, C, "txPr")
.and_then(|text| doc.child(text, A, "bodyPr"));
let size = text_size(reader, labels);
let font = text_font(doc, labels);
let insets = body_insets(reader, body, CHART_DATA_LABEL_INSETS);
let defaults = SeriesLabelDefaults {
format: &format,
separator: separator.as_deref(),
size,
font: font.as_ref(),
insets,
node: labels,
};
let mut point_overrides = Vec::with_capacity(points.len());
for point in points {
let Some(entry) = read_point_label(reader, point, &defaults) else {
return LabelMarkup::Other;
};
point_overrides.push(entry);
}
LabelMarkup::Values {
show_default,
position,
size,
font,
fill: Box::new(text_fill(doc, labels)),
insets,
format,
parts: Box::new(MarkupLabelParts {
show_ser_name,
show_cat_name,
show_val,
percent: if show_percent {
MarkupPercent::Shown
} else {
MarkupPercent::Hidden
},
separator,
own_format,
}),
point_overrides,
}
}
fn meets<const N: usize>(conditions: [(bool, ChartReason); N]) -> Result<(), ChartReason> {
conditions
.into_iter()
.find(|&(holds, _)| !holds)
.map_or(Ok(()), |(_, reason)| Err(reason))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlotPlace {
Automatic,
Manual(PlotLayout),
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct FormatCode(String);
impl FormatCode {
fn general() -> Self {
Self("General".to_owned())
}
fn is_general(&self) -> bool {
self.0.trim().eq_ignore_ascii_case("General")
}
fn decided(&self, rules: PlotRules, place: LabelPlace) -> Option<LabelFormat> {
rules.label_format(&self.0, place)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LegendPlace {
Bottom,
Top,
Left,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlotLayout {
pub inner: bool,
pub edges: LayoutBox,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayoutBox {
pub x: Decimal,
pub y: Decimal,
pub w: Decimal,
pub h: Decimal,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LegendBox {
Automatic,
Manual(LayoutBox),
Other,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SetScale {
pub min: Option<Decimal>,
pub max: Option<Decimal>,
pub major_unit: Option<Decimal>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Title {
pub lines: usize,
pub size: i64,
pub font: FontRef,
pub text: Option<TitleText>,
pub corner: Option<LayoutCorner>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayoutCorner {
pub x: Decimal,
pub y: Decimal,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TitleText {
pub lines: Vec<String>,
pub font: FontRef,
pub bold: bool,
pub italic: bool,
pub fill: Option<DrawColor>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Series {
pub fill: SeriesFill,
pub values: Vec<Option<Decimal>>,
pub name: Option<String>,
pub labels: SeriesLabels,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeriesFill {
Color(DrawColor),
Gradient(LinearGradient),
None,
Points(Vec<DrawColor>),
BarPoints {
base: Option<DrawColor>,
points: Vec<Option<DrawColor>>,
},
}
impl SeriesFill {
#[must_use]
pub fn color(&self) -> Option<&DrawColor> {
match self {
Self::Color(color) => Some(color),
Self::Gradient(_) | Self::None | Self::Points(_) | Self::BarPoints { .. } => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SeriesLabels {
Hidden,
Values(DataLabelText),
Other,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum PercentMode {
#[default]
Hidden,
Integer,
Format(LabelFormat),
}
impl PercentMode {
#[must_use]
pub const fn is_shown(&self) -> bool {
!matches!(self, Self::Hidden)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataLabelParts {
pub show_ser_name: bool,
pub show_cat_name: bool,
pub show_val: bool,
pub percent: PercentMode,
pub separator: Option<String>,
}
impl Default for DataLabelParts {
fn default() -> Self {
Self {
show_ser_name: false,
show_cat_name: false,
show_val: true,
percent: PercentMode::Hidden,
separator: None,
}
}
}
impl DataLabelParts {
#[must_use]
pub const fn is_value_only(&self) -> bool {
self.show_val && !self.show_ser_name && !self.show_cat_name && !self.percent.is_shown()
}
#[must_use]
pub fn effective_separator(&self) -> &str {
self.separator
.as_deref()
.unwrap_or(if self.percent.is_shown() { "\n" } else { ", " })
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PointLabelLayout {
#[default]
Automatic,
Offset {
dx: Decimal,
dy: Decimal,
},
Edge {
x: Decimal,
y: Decimal,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PointLabelOverride {
Deleted,
Custom(Box<PointLabelSpec>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PointLabelSpec {
pub label: DataLabelText,
pub rich_lines: Option<Vec<String>>,
pub layout: PointLabelLayout,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataLabelText {
pub position: DataLabelPosition,
pub size: i64,
pub font: FontRef,
pub fill: Option<DrawColor>,
pub insets: Edges<Length>,
pub format: LabelFormat,
pub parts: DataLabelParts,
pub show_default: bool,
pub point_overrides: Vec<(usize, PointLabelOverride)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Decimal {
pub digits: i64,
pub exponent: i32,
}
impl Decimal {
pub(crate) const ZERO: Self = Self {
digits: 0,
exponent: 0,
};
#[must_use]
pub fn parse(text: &str) -> Option<Self> {
let text = text.trim();
let (mantissa, exponent) = match text.split_once(['E', 'e']) {
Some((mantissa, exponent)) => (mantissa, exponent.parse::<i32>().ok()?),
None => (text, 0),
};
let negative = mantissa.starts_with('-');
let mantissa = mantissa.trim_start_matches(['-', '+']);
let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
if whole.is_empty() && fraction.is_empty() {
return None;
}
let exponent = exponent.checked_sub(i32::try_from(fraction.len()).ok()?)?;
let (digits, exponent) = digits_of(whole.chars().chain(fraction.chars()), exponent)?;
if !(-CHART_EXPONENT_LIMIT..=CHART_EXPONENT_LIMIT).contains(&i64::from(exponent)) {
return None;
}
let digits = if negative { -digits } else { digits };
Some(Self { digits, exponent }.normalized())
}
#[must_use]
pub fn normalized(self) -> Self {
let mut out = self;
while out.digits != 0 && out.digits % TENTHS == 0 {
out.digits /= TENTHS;
out.exponent += 1;
}
if out.digits == 0 {
out.exponent = 0;
}
out
}
#[must_use]
pub const fn is_positive(self) -> bool {
self.digits > 0
}
}
fn digits_of(chars: impl Iterator<Item = char>, mut exponent: i32) -> Option<(i64, i32)> {
let radix = u32::try_from(TENTHS).ok()?;
let mut digits: i64 = 0;
for ch in chars {
let digit = i64::from(ch.to_digit(radix)?);
match digits
.checked_mul(TENTHS)
.and_then(|d| d.checked_add(digit))
{
Some(next) => digits = next,
None => exponent = exponent.checked_add(1)?,
}
}
Some((digits, exponent))
}
impl PartialOrd for Decimal {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Decimal {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
let low = self.exponent.min(other.exponent);
let wide = |d: Self| {
let shift = u32::try_from(d.exponent - low).unwrap_or(u32::MAX);
i128::from(d.digits).saturating_mul(i128::from(TENTHS).saturating_pow(shift))
};
wide(*self).cmp(&wide(*other))
}
}
#[must_use]
pub fn reference(doc: &Document, graphic_data: NodeId) -> Option<Chart> {
let chart = doc.child(graphic_data, C, "chart")?;
Some(Chart {
id: doc.attribute(chart, Some(R), "id")?.to_owned(),
columns: None,
})
}
pub fn attach_charts(blocks: &mut [Block], find: &mut dyn FnMut(&str) -> Option<Part>) {
visit_drawings(blocks, &mut |drawing| {
if let DrawingMut::Floating(floating) = drawing {
attach(floating, find);
}
});
}
fn attach(floating: &mut Floating, find: &mut dyn FnMut(&str) -> Option<Part>) {
let Some(chart) = floating.chart.as_mut() else {
return;
};
let Some(columns) = find(&chart.id) else {
return;
};
floating.look = Some(columns_area(columns.area.clone()));
chart.columns = Some(Box::new(columns.columns));
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Part {
pub area: ShapeLook,
pub columns: Columns,
}
fn columns_area(mut look: ShapeLook) -> ShapeLook {
look.geometry = Geometry::Rect;
look
}
pub(crate) fn read(
reader: &mut PartReader,
space: NodeId,
rules: PlotRules,
) -> Result<Part, ChartReason> {
let mut model = ChartModel::read(reader, space)?;
model.title = model.title.decided(rules);
let drawn = match model.groups.as_slice() {
[Group::Pie(_)] => pie::part(model, rules)?,
[Group::Doughnut(_)] => pie::doughnut_part(model, rules)?,
_ => Part::of(model, rules)?,
};
rules.rule(&drawn.value.columns)?;
reader
.drawing_warnings()
.extend(drawn.warnings, std::convert::identity);
Ok(drawn.value)
}
type Look<T> = Warned<T, DrawingMlWarning>;
struct ChartModel {
groups: Vec<Group>,
axes: Vec<Axis>,
legend: Option<Legend>,
title: TitleState,
plot_layout: Option<ManualLayout>,
data_table: Option<DataTableMarkup>,
blanks: BlankPoints,
area: ElementLook,
style: Option<ChartStyleInfo>,
text: ChartText,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct ChartText {
size: Option<i64>,
font: Option<FontRef>,
bold: Option<bool>,
styled: bool,
}
impl ChartText {
fn size(&self, own: Option<i64>) -> i64 {
own.or(self.size).unwrap_or(CHART_TEXT_SIZE)
}
fn title_size(&self) -> i64 {
if self.styled {
CHART_STYLED_TITLE_SIZE
} else {
self.size(None)
}
}
fn font(&self, own: Option<FontRef>) -> FontRef {
own.or_else(|| self.font.clone())
.unwrap_or(FontRef::MinorLatin)
}
}
impl TitleState {
fn decided(self, rules: PlotRules) -> Self {
match self {
Self::Automatic(title) if rules.hides_automatic_title(title) => Self::Deleted,
Self::Automatic(_) => Self::Unknown,
other => other,
}
}
fn known(self) -> Option<Self> {
match self {
Self::Unknown | Self::Automatic(_) => None,
known => Some(known),
}
}
fn shown(self) -> Option<OwnTitle> {
match self {
Self::Shown(title) => Some(*title),
Self::Deleted | Self::Automatic(_) | Self::Unknown => None,
}
}
}
enum TitleState {
Shown(Box<OwnTitle>),
Deleted,
Automatic(AutomaticTitle),
Unknown,
}
struct OwnTitle {
lines: usize,
places: [TitleProps; 3],
text: OwnText,
corner: Option<LayoutCorner>,
turn: TitleTurn,
warnings: Warnings<DrawingMlWarning>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TitleTurn {
Default,
Upward,
Upright,
Other,
}
impl TitleTurn {
fn of(doc: &Document, node: NodeId) -> Self {
let Some(rich) = doc
.child(node, C, "tx")
.and_then(|tx| doc.child(tx, C, "rich"))
else {
return Self::Other;
};
let body = doc.child(rich, A, "bodyPr");
let attribute = |name| body.and_then(|body| doc.attribute(body, None, name));
if attribute("vert").is_some_and(|vert| vert != "horz") {
return Self::Other;
}
match attribute("rot").map(f_office_drawingml::integer) {
None => Self::Default,
Some(Some(TITLE_UPWARD_TURN)) => Self::Upward,
Some(Some(0)) => Self::Upright,
Some(_) => Self::Other,
}
}
}
const TITLE_UPWARD_TURN: i64 = -QUARTER_TURN;
enum OwnText {
Lines(Vec<String>),
Placeholder(TitleSeries),
Undrawn,
}
impl OwnText {
fn lines(self, rules: PlotRules) -> Option<Vec<String>> {
match self {
Self::Lines(lines) => Some(lines),
Self::Placeholder(series) => rules
.title_placeholder(series.automatic, series.first_name.as_deref())
.map(|text| vec![text]),
Self::Undrawn => None,
}
}
}
struct TitleSeries {
automatic: AutomaticTitle,
first_name: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct TitleProps {
size: Option<i64>,
bold: Option<bool>,
italic: Option<bool>,
font: Option<FontRef>,
fill: Option<DrawColor>,
}
impl TitleProps {
fn read(
reader: &mut PartReader,
props: NodeId,
warnings: &mut Warnings<DrawingMlWarning>,
) -> Self {
let doc = reader.doc;
let flag = |name| {
doc.attribute(props, None, name)
.map(f_office_drawingml::boolean)
};
Self {
size: reader
.or_missing_in(props, (None, "sz"), f_office_drawingml::integer)
.map(|hundredths| hundredths * HALF_POINTS_PER_POINT / PERCENT),
bold: flag("b"),
italic: flag("i"),
font: doc
.child(props, A, "latin")
.and_then(|latin| doc.attribute(latin, None, "typeface"))
.map(FontRef::of_typeface),
fill: doc
.child(props, A, "solidFill")
.and_then(|solid| DrawColor::read(doc, solid, warnings)),
}
}
}
impl OwnTitle {
fn decided(self, rules: PlotRules, text: &ChartText) -> Result<Look<Title>, ChartReason> {
let Self {
lines,
places,
text: shown,
corner,
turn: _,
warnings,
} = self;
let [run, _, own] = &places;
let font = text.font(places.iter().find_map(|place| place.font.clone()));
if !rules.draws_title_text() {
let size = run.size.or(own.size).ok_or(ChartReason::UnknownTitle)?;
let title = Title {
lines,
size,
font,
text: None,
corner,
};
return Ok(Warned::new(title, Warnings::new()));
}
let size = places.iter().find_map(|place| place.size);
if size.is_none() && text.size.is_some() {
return Err(ChartReason::UnknownTitle);
}
let bold = places
.iter()
.find_map(|place| place.bold)
.or_else(|| text.bold.is_none().then_some(true));
let italic = places.iter().find_map(|place| place.italic);
let fill = places.iter().find_map(|place| place.fill.clone());
let title = Title {
lines,
size: size.unwrap_or_else(|| text.title_size()),
font: font.clone(),
text: shown.lines(rules).zip(bold).map(|(lines, bold)| TitleText {
lines,
font,
bold,
italic: italic.unwrap_or(false),
fill,
}),
corner,
};
Ok(Warned::new(title, warnings))
}
fn axis_title(
self,
turn: TitleTurn,
text: &ChartText,
warnings: &mut Warnings<DrawingMlWarning>,
) -> Option<AxisTitle> {
let Self {
lines: _,
places,
text: shown,
corner,
turn: written,
warnings: own,
} = self;
if !(written == TitleTurn::Default || written == turn) {
return None;
}
let OwnText::Lines(lines) = shown else {
return None;
};
if !matches!(lines.as_slice(), [line] if !line.is_empty()) {
return None;
}
let bold = places
.iter()
.find_map(|place| place.bold)
.or_else(|| text.bold.is_none().then_some(true))?;
warnings.extend(own, std::convert::identity);
Some(AxisTitle {
size: text.size(places.iter().find_map(|place| place.size)),
text: TitleText {
lines,
font: text.font(places.iter().find_map(|place| place.font.clone())),
bold,
italic: places
.iter()
.find_map(|place| place.italic)
.unwrap_or(false),
fill: places.iter().find_map(|place| place.fill.clone()),
},
corner,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AutomaticTitle {
pub(crate) series: usize,
pub(crate) named: bool,
pub(crate) marked: bool,
}
struct ManualLayout {
target: LayoutTarget,
modes: [LayoutMode; 2],
size_modes: [LayoutMode; 2],
edges: [Option<Decimal>; 4],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LayoutTarget {
Inner,
Outer,
}
const LAYOUT_TARGET: &Values<LayoutTarget> = &Values::new(&[
own("inner", LayoutTarget::Inner),
own("outer", LayoutTarget::Outer),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LayoutMode {
Edge,
Factor,
}
const LAYOUT_MODE: &Values<LayoutMode> = &Values::new(&[
own("edge", LayoutMode::Edge),
own("factor", LayoutMode::Factor),
]);
enum Group {
Bars(Bars),
Lines(Lines),
Scatter(Scatter),
Pie(pie::PieGroup),
Doughnut(pie::DoughnutGroup),
}
struct Scatter {
style: Option<ScatterStyle>,
uniform_colors: bool,
extras: bool,
lines: Lines,
x_values: Vec<Option<Vec<Decimal>>>,
x_formats: Vec<FormatCode>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ScatterStyle {
Nothing,
Line,
LineMarker,
Marker,
Smooth,
SmoothMarker,
}
const SCATTER_STYLE: &Values<ScatterStyle> = &Values::new(&[
own("none", ScatterStyle::Nothing),
own("line", ScatterStyle::Line),
own("lineMarker", ScatterStyle::LineMarker),
own("marker", ScatterStyle::Marker),
own("smooth", ScatterStyle::Smooth),
own("smoothMarker", ScatterStyle::SmoothMarker),
]);
#[derive(Clone, Copy, PartialEq, Eq)]
enum HiddenLine {
NoColor,
MarkersAlone,
}
struct Lines {
grouping: Option<BarStacking>,
extras: bool,
shows_markers: bool,
series: Vec<ChartSeries>,
settings: Vec<SeriesLine>,
ax_ids: Vec<String>,
}
struct SeriesLine {
styled: bool,
width: Option<Length>,
ends: LineEnds,
dash: SeriesDash,
hidden: bool,
marker: SeriesMarker,
smooth: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LineEnds {
Round,
Unwritten,
Other,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SeriesDash {
Solid,
Preset(LineDash),
Other,
}
const PRESET_DASHES: &Values<SeriesDash> = &Values::new(&[
own("solid", SeriesDash::Solid),
own("dot", SeriesDash::Preset(LineDash::Dot)),
own("dash", SeriesDash::Preset(LineDash::Dash)),
own("lgDash", SeriesDash::Preset(LineDash::LongDash)),
own("dashDot", SeriesDash::Preset(LineDash::DashDot)),
own("lgDashDot", SeriesDash::Preset(LineDash::LongDashDot)),
own("lgDashDotDot", SeriesDash::Preset(LineDash::LongDashDotDot)),
own("sysDash", SeriesDash::Preset(LineDash::SystemDash)),
own("sysDot", SeriesDash::Preset(LineDash::SystemDot)),
own("sysDashDot", SeriesDash::Preset(LineDash::SystemDashDot)),
own(
"sysDashDotDot",
SeriesDash::Preset(LineDash::SystemDashDotDot),
),
]);
enum SeriesMarker {
Styled,
None,
Drawn {
symbol: Option<MarkerSymbol>,
size: Option<Length>,
look: Option<MarkerLook>,
},
Other,
}
struct MarkerLook {
fill: Option<DrawColor>,
outline: WrittenOutline,
}
enum WrittenOutline {
Unwritten,
Hidden,
Solid(DrawColor, Option<Length>),
}
impl MarkerLook {
fn parts(&self, fills: bool) -> Option<(Option<DrawColor>, Option<MarkerOutline>)> {
let outline = match &self.outline {
WrittenOutline::Solid(color, Some(width)) => Some(MarkerOutline {
color: Some(color.clone()),
width: StyleWidth::Set(*width),
}),
_ if !fills => return None,
WrittenOutline::Solid(color, None) => Some(MarkerOutline {
color: Some(color.clone()),
width: StyleWidth::Automatic,
}),
WrittenOutline::Unwritten => Some(MarkerOutline::STYLE),
WrittenOutline::Hidden => None,
};
(self.fill.is_some() || fills).then(|| (self.fill.clone(), outline))
}
}
struct Bars {
direction: BarDirection,
grouping: BarGrouping,
gap: i64,
overlap: i64,
uniform_colors: bool,
series: Vec<ChartSeries>,
solid: Option<columns_3d::Solid>,
}
struct ChartSeries {
index: Option<usize>,
fill: Look<Option<DrawColor>>,
gradient: Option<LinearGradient>,
fill_written: bool,
no_fill: bool,
point_fills: Vec<pie::PointFill>,
name: Option<String>,
values: CachedValues,
format: FormatCode,
categories: CategoryCache,
labels: LabelMarkup,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum CategoryCache {
Strings(Vec<Option<String>>),
Numbers {
format: FormatCode,
points: Vec<Option<Decimal>>,
},
Omitted,
Other,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BarDirection {
Horizontal,
Vertical,
}
const BAR_DIRECTION: &Values<BarDirection> = &Values::new(&[
own("bar", BarDirection::Horizontal),
own("col", BarDirection::Vertical),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BarGrouping {
Clustered,
Stacked,
PercentStacked,
Standard,
}
const BAR_GROUPING: &Values<BarGrouping> = &Values::new(&[
own("clustered", BarGrouping::Clustered),
own("stacked", BarGrouping::Stacked),
own("percentStacked", BarGrouping::PercentStacked),
own("standard", BarGrouping::Standard),
]);
struct Axis {
kind: AxisKind,
id: Option<String>,
place: Option<AxisPlace>,
minor_gridlines: bool,
deleted: bool,
scaling: Scaling,
major_unit: Option<Decimal>,
labels: LabelPosition,
label_size: Option<i64>,
label_font: Option<FontRef>,
label_fill: Look<Option<DrawColor>>,
gridlines: Option<ElementLook>,
line: ElementLook,
tick_marks: Option<TickMark>,
crosses: Crossing,
title: Option<OwnTitle>,
own_format: Option<FormatCode>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Crossing {
AutoZero,
Max,
Min,
At(Option<Decimal>),
}
const CROSSES: &Values<Crossing> = &Values::new(&[
own("autoZero", Crossing::AutoZero),
own("max", Crossing::Max),
own("min", Crossing::Min),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AxisKind {
Category,
Value,
Date,
Series,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AxisPlace {
Bottom,
Left,
Right,
Top,
}
const AXIS_PLACE: &Values<AxisPlace> = &Values::new(&[
own("b", AxisPlace::Bottom),
own("l", AxisPlace::Left),
own("r", AxisPlace::Right),
own("t", AxisPlace::Top),
]);
const AXES: [(&str, AxisKind); 4] = [
("catAx", AxisKind::Category),
("valAx", AxisKind::Value),
("dateAx", AxisKind::Date),
("serAx", AxisKind::Series),
];
struct Scaling {
min: Option<Decimal>,
max: Option<Decimal>,
log_base: Option<Decimal>,
orientation: Orientation,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Orientation {
MinMax,
MaxMin,
}
const ORIENTATION: &Values<Orientation> = &Values::new(&[
own("minMax", Orientation::MinMax),
own("maxMin", Orientation::MaxMin),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LabelPosition {
High,
Low,
NextTo,
None,
}
const LABEL_POSITION: &Values<LabelPosition> = &Values::new(&[
own("high", LabelPosition::High),
own("low", LabelPosition::Low),
own("nextTo", LabelPosition::NextTo),
own("none", LabelPosition::None),
]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TickMark {
Cross,
Inside,
None,
Outside,
}
const TICK_MARK: &Values<TickMark> = &Values::new(&[
own("cross", TickMark::Cross),
own("in", TickMark::Inside),
own("none", TickMark::None),
own("out", TickMark::Outside),
]);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct OutsideTicks {
pub category: bool,
pub value: bool,
}
struct DrawnLines {
area: ShapeLook,
gridlines: Option<ShapeLook>,
axis: ShapeLook,
value_axis: ShapeLook,
ticks: OutsideTicks,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ChartStyleInfo {
pub(super) number: u32,
pub(super) legacy_lines: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StyleLineMode {
None,
Tinted,
LegacyDarkAxes,
}
impl DrawnLines {
fn of(
area: ElementLook,
category: (ElementLook, Option<TickMark>),
value: (Option<ElementLook>, ElementLook, Option<TickMark>),
(axis_lines, style): (bool, StyleLineMode),
warnings: &mut Warnings<DrawingMlWarning>,
) -> Self {
let mut drawn = |look: ElementLook, fill: Option<DrawColor>| {
let geometry = if fill.is_some() {
Geometry::Rect
} else {
Geometry::Line
};
let look = look.drawn(style, (geometry, fill));
warnings.extend(look.warnings, std::convert::identity);
look.value
};
let area = drawn(area, Some(DrawColor::scheme(SchemeSlot::Light1)));
let gridlines = value.0.map(|look| drawn(look, None));
let axis = drawn(category.0, None);
let value_axis = if axis_lines {
drawn(value.1, None)
} else {
ShapeLook::plain(Geometry::Line, None, None)
};
let outside = |marks: Option<TickMark>| axis_lines && marks == Some(TickMark::Outside);
Self {
area,
gridlines,
axis,
value_axis,
ticks: OutsideTicks {
category: outside(category.1),
value: outside(value.2),
},
}
}
}
const FILLS: [&str; 6] = [
"noFill",
"solidFill",
"gradFill",
"blipFill",
"pattFill",
"grpFill",
];
struct ElementLook {
look: Look<ShapeLook>,
written: bool,
}
impl ElementLook {
fn none() -> Self {
Self {
look: Warned::new(
ShapeLook::plain(Geometry::Line, None, None),
Warnings::new(),
),
written: true,
}
}
fn drawn(
self,
style: StyleLineMode,
(geometry, fill): (Geometry, Option<DrawColor>),
) -> Look<ShapeLook> {
if self.written || style == StyleLineMode::None {
return self.look;
}
let color = if fill.is_none() && style == StyleLineMode::LegacyDarkAxes {
DrawColor::scheme(SchemeSlot::Dark1)
} else {
DrawColor::scheme(SchemeSlot::Dark1).tinted(CHART_STYLE_LINE_TINT)
};
let look = ShapeLook::in_line_style(geometry, fill, (color, 1));
Warned::new(look, Warnings::new())
}
}
struct DataTableMarkup {
borders: DataTableBorders,
keys: bool,
border: ElementLook,
size: Option<i64>,
font: Option<FontRef>,
fill: Look<Option<DrawColor>>,
bold: Option<bool>,
italic: Option<bool>,
}
impl DataTableMarkup {
fn read(reader: &mut PartReader, node: NodeId) -> Self {
let doc = reader.doc;
let run = default_run(doc, node);
let run_bool = |name| {
run.and_then(|r| doc.attribute(r, None, name))
.map(f_office_drawingml::boolean)
};
Self {
borders: DataTableBorders {
horz: Flag::of(doc, node, "showHorzBorder").is_on(),
vert: Flag::of(doc, node, "showVertBorder").is_on(),
outline: Flag::of(doc, node, "showOutline").is_on(),
},
keys: Flag::of(doc, node, "showKeys").is_on(),
border: line_look(doc, node),
size: text_size(reader, node),
font: text_font(doc, node),
fill: text_fill(doc, node),
bold: run_bool("b"),
italic: run_bool("i"),
}
}
fn resolve(
self,
text: &ChartText,
style: StyleLineMode,
warnings: &mut Warnings<DrawingMlWarning>,
) -> DataTable {
let border = self.border.drawn(style, (Geometry::Line, None));
extend_warnings(warnings, [border.warnings, self.fill.warnings]);
DataTable {
borders: self.borders,
keys: self.keys,
border: border.value,
text_size: text.size(self.size),
text_font: text.font(self.font),
text_fill: self.fill.value,
bold: self.bold.unwrap_or_else(|| text.bold.unwrap_or(false)),
italic: self.italic.unwrap_or(false),
}
}
}
struct Legend {
position: LegendPosition,
label_size: Option<i64>,
font: Option<FontRef>,
fill: Look<Option<DrawColor>>,
text: LegendText,
layout: Option<ManualLayout>,
}
impl Legend {
fn drawn_place(&self) -> Result<LegendPlace, ChartReason> {
match self.position {
LegendPosition::Bottom => Ok(LegendPlace::Bottom),
LegendPosition::Top => Ok(LegendPlace::Top),
LegendPosition::Left => Ok(LegendPlace::Left),
LegendPosition::Right => Ok(LegendPlace::Right),
LegendPosition::TopRight => Err(ChartReason::LegendTopRight),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LegendPosition {
Bottom,
TopRight,
Left,
Right,
Top,
}
const LEGEND_POSITION: &Values<LegendPosition> = &Values::new(&[
own("b", LegendPosition::Bottom),
own("tr", LegendPosition::TopRight),
own("l", LegendPosition::Left),
own("r", LegendPosition::Right),
own("t", LegendPosition::Top),
]);
impl ChartModel {
fn read(reader: &mut PartReader, space: NodeId) -> Result<Self, ChartReason> {
let doc = reader.doc;
let plot = doc
.child(space, C, "chart")
.and_then(|chart| doc.child(chart, C, "plotArea").map(|plot| (chart, plot)));
let (chart, plot) = plot.ok_or(ChartReason::NoPlotArea)?;
let groups: Vec<NodeId> = doc
.child_elements(plot)
.filter(|&node| {
doc.element(node)
.is_some_and(|e| e.name.local.ends_with("Chart"))
})
.collect();
let series: Vec<NodeId> = groups
.iter()
.flat_map(|&group| doc.child_elements(group).filter(|&n| doc.is(n, C, "ser")))
.collect();
let first_name = series.first().and_then(|&first| series_name(doc, first));
let automatic = AutomaticTitle {
series: series.len(),
named: series
.first()
.is_some_and(|&first| doc.child(first, C, "tx").is_some()),
marked: doc.child(chart, C, "autoTitleDeleted").is_some(),
};
let scene = (
doc.child(chart, C, "view3D"),
columns_3d::plain_walls(doc, chart),
);
let groups = groups
.into_iter()
.map(|node| Group::read(reader, node, scene))
.collect::<Result<Vec<_>, _>>()?;
let axes: Vec<(NodeId, AxisKind)> = doc
.child_elements(plot)
.filter_map(|node| {
AXES.into_iter()
.find(|(name, _)| doc.is(node, C, name))
.map(|(_, kind)| (node, kind))
})
.collect();
let axes = axes
.into_iter()
.map(|(node, kind)| Axis::read(reader, node, kind))
.collect();
let legend = doc.child(chart, C, "legend").map(|legend| Legend {
position: val_case(reader, legend, "legendPos", LEGEND_POSITION)
.unwrap_or(LegendPosition::Right),
label_size: text_size(reader, legend),
font: text_font(doc, legend),
fill: text_fill(doc, legend),
text: LegendText::read(doc, legend),
layout: doc
.child(legend, C, "layout")
.and_then(|layout| doc.child(layout, C, "manualLayout"))
.map(|manual| ManualLayout::read(reader, manual)),
});
let area_props = doc.child(space, C, "spPr");
let mut warnings = Warnings::new();
let area = ShapeLook::read(doc, (area_props, None), &mut warnings);
if area.shadow().is_some() {
warnings.push(DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Shadow,
});
}
warnings.extend(
picture_fill_warning(doc, area_props),
std::convert::identity,
);
let area = ElementLook {
look: Warned::new(area, warnings),
written: area_props.is_some(),
};
Ok(Self {
style: read_style_info(doc, space),
text: ChartText {
size: text_size(reader, space),
font: text_font(doc, space),
bold: default_run(doc, space)
.and_then(|run| doc.attribute(run, None, "b"))
.map(f_office_drawingml::boolean),
styled: style_nodes(doc, space).any(|node| !doc.is(node, C, "style")),
},
groups,
axes,
legend,
title: title(reader, chart, (automatic, first_name)),
plot_layout: doc
.child(plot, C, "layout")
.and_then(|layout| doc.child(layout, C, "manualLayout"))
.map(|manual| ManualLayout::read(reader, manual)),
data_table: doc
.child(plot, C, "dTable")
.map(|table| DataTableMarkup::read(reader, table)),
blanks: BlankPoints::read(doc, chart),
area,
})
}
}
impl Group {
fn read(
reader: &mut PartReader,
node: NodeId,
(view, plain_walls): (Option<NodeId>, bool),
) -> Result<Self, ChartReason> {
let doc = reader.doc;
let series: Vec<NodeId> = doc
.child_elements(node)
.filter(|&n| doc.is(n, C, "ser"))
.collect();
let group_labels = doc.child(node, C, "dLbls");
if doc.is(node, C, "lineChart") {
let grouping = match doc
.child(node, C, "grouping")
.and_then(|grouping| doc.attribute(grouping, None, "val"))
{
None | Some("standard") => Some(BarStacking::Clustered),
Some("stacked") => Some(BarStacking::Stacked),
Some("percentStacked") => Some(BarStacking::PercentStacked),
Some(_) => None,
};
let extras = ["dropLines", "hiLowLines", "upDownBars"]
.iter()
.any(|name| doc.child(node, C, name).is_some());
let shows_markers = Flag::of(doc, node, "marker").is_on();
let settings = series
.iter()
.map(|&ser| SeriesLine::read(reader, ser))
.collect();
let series = series
.into_iter()
.map(|ser| ChartSeries::read(reader, (ser, group_labels), line_of, "val"))
.collect();
return Ok(Self::Lines(Lines {
grouping,
extras,
shows_markers,
series,
settings,
ax_ids: axis_ids_of(doc, node),
}));
}
if doc.is(node, C, "scatterChart") {
return Ok(Self::Scatter(Scatter::read(
reader,
node,
(series, group_labels),
)));
}
if doc.is(node, C, "pieChart") || doc.is(node, C, "pie3DChart") {
return Ok(Self::Pie(pie::PieGroup::read(
reader,
node,
(series, group_labels),
view,
)));
}
if doc.is(node, C, "doughnutChart") {
return Ok(Self::Doughnut(pie::DoughnutGroup::read(
reader,
node,
(series, group_labels),
)));
}
let solid = doc
.is(node, C, "bar3DChart")
.then(|| columns_3d::Solid::read(reader, node, (view, plain_walls)));
if !doc.is(node, C, "barChart") && solid.is_none() {
return Err(ChartReason::OtherGroup);
}
let direction =
val_case(reader, node, "barDir", BAR_DIRECTION).ok_or(ChartReason::NoBarDirection)?;
let grouping =
val_case(reader, node, "grouping", BAR_GROUPING).unwrap_or(BarGrouping::Clustered);
let mut percent = |name: &str, default: i64| {
read_value(reader, node, name, f_office_drawingml::chart_percent).unwrap_or(default)
};
let (gap, overlap) = (
percent("gapWidth", CHART_GAP_WIDTH),
percent("overlap", CHART_OVERLAP),
);
let uniform_colors = Flag::of(doc, node, "varyColors") == Flag::Off;
let series = series
.into_iter()
.map(|ser| {
let mut s =
ChartSeries::read(reader, (ser, group_labels), |_, props| Some(props), "val");
s.point_fills = pie::point_fills_of(reader, ser);
s
})
.collect();
Ok(Self::Bars(Bars {
direction,
grouping,
gap,
overlap,
uniform_colors,
series,
solid,
}))
}
}
impl Scatter {
fn read(
reader: &mut PartReader,
node: NodeId,
(series, group_labels): (Vec<NodeId>, Option<NodeId>),
) -> Self {
let doc = reader.doc;
let extras = series.iter().any(|&ser| {
["trendline", "errBars"]
.iter()
.any(|name| doc.child(ser, C, name).is_some())
});
let x_formats = series
.iter()
.map(|&ser| cache_format(doc, ser, "xVal"))
.collect();
let x_values = series
.iter()
.map(|&ser| cached_values(reader, ser, "xVal").full())
.collect();
let settings = series
.iter()
.map(|&ser| SeriesLine::read(reader, ser))
.collect();
let series = series
.into_iter()
.map(|ser| ChartSeries::read(reader, (ser, group_labels), line_of, "yVal"))
.collect();
Self {
style: val_case(reader, node, "scatterStyle", SCATTER_STYLE),
uniform_colors: Flag::of(reader.doc, node, "varyColors") == Flag::Off,
extras,
lines: Lines {
grouping: Some(BarStacking::Clustered),
extras: false,
shows_markers: true,
series,
settings,
ax_ids: Vec::new(),
},
x_values,
x_formats,
}
}
fn drawn(
self,
palette: Option<StylePalette>,
rules: PlotRules,
) -> Result<(ChartGroup, Vec<ChartSeries>, FormatCode), ChartReason> {
meets([
(
match self.style {
Some(ScatterStyle::LineMarker) => true,
Some(ScatterStyle::SmoothMarker) => rules.draws_smooth_lines(),
_ => false,
},
ChartReason::ScatterStyle,
),
(self.uniform_colors, ChartReason::VariedColors),
(!self.extras, ChartReason::SeriesExtras),
])?;
let x_values: Vec<Vec<Decimal>> = self
.x_values
.into_iter()
.collect::<Option<_>>()
.ok_or(ChartReason::SeriesValues)?;
meets([
(
x_values
.iter()
.zip(&self.lines.series)
.all(|(xs, series)| match &series.values {
CachedValues::Points(ys) => ys.len() == xs.len(),
CachedValues::Uncached | CachedValues::Unread => true,
}),
ChartReason::SeriesLengths,
),
(
!x_values.iter().flatten().any(|x| x.digits.is_negative()),
ChartReason::NegativeValue,
),
])?;
let x_format = self
.x_formats
.into_iter()
.find(|format| !format.is_general())
.unwrap_or_else(FormatCode::general);
let (looks, _, series) = self.lines.drawn(palette, HiddenLine::MarkersAlone, rules)?;
Ok((
ChartGroup::Scatter {
looks,
x_values,
x_scale: SetScale::default(),
},
series,
x_format,
))
}
}
fn line_of(doc: &Document, props: NodeId) -> Option<NodeId> {
doc.child(props, A, "ln")
}
impl ChartSeries {
fn read(
reader: &mut PartReader,
(ser, group_labels): (NodeId, Option<NodeId>),
colored: fn(&Document, NodeId) -> Option<NodeId>,
values: &str,
) -> Self {
let doc = reader.doc;
let mut warnings = Warnings::new();
let colored_element = doc
.child(ser, C, "spPr")
.and_then(|props| colored(doc, props));
let fill_written = colored_element.is_some_and(|element| {
FILLS
.iter()
.any(|name| doc.child(element, A, name).is_some())
});
let no_fill =
colored_element.is_some_and(|element| doc.child(element, A, "noFill").is_some());
let fill = colored_element
.and_then(|element| doc.child(element, A, "solidFill"))
.and_then(|solid| DrawColor::read(doc, solid, &mut warnings));
let gradient = colored_element
.filter(|_| fill.is_none())
.and_then(|element| doc.child(element, A, "gradFill"))
.and_then(|gradient| LinearGradient::read(doc, gradient, &mut warnings));
let index = read_value(reader, ser, "idx", point_number);
let format = cache_format(doc, ser, values);
let labels = label_markup(reader, doc.child(ser, C, "dLbls").or(group_labels), &format);
Self {
index,
fill: Warned::new(fill, warnings),
gradient,
fill_written,
no_fill,
point_fills: Vec::new(),
name: series_name(doc, ser),
values: cached_values(reader, ser, values),
format,
categories: category_texts(reader, ser),
labels,
}
}
}
impl SeriesLine {
fn read(reader: &mut PartReader, ser: NodeId) -> Self {
let marker = SeriesMarker::read(reader, ser);
let doc = reader.doc;
let styled = doc.child(ser, C, "spPr").is_none();
let ln = doc
.child(ser, C, "spPr")
.and_then(|props| doc.child(props, A, "ln"));
let width = ln
.and_then(|ln| doc.attribute(ln, None, "w"))
.and_then(|w| w.parse::<i64>().ok())
.and_then(Length::from_emus);
let ends = ln.map_or(LineEnds::Other, |ln| LineEnds::read(doc, ln));
let dash = ln.map_or(SeriesDash::Solid, |ln| SeriesDash::read(doc, ln));
let smooth = Flag::of(doc, ser, "smooth").is_on();
Self {
styled,
width,
ends,
dash,
hidden: ln.is_some_and(|ln| doc.child(ln, A, "noFill").is_some()),
marker,
smooth,
}
}
}
impl SeriesLine {
fn stroke(&self, rules: PlotRules) -> Result<(StyleWidth, Option<LineDash>), ChartReason> {
let fills = rules.fills_line_strokes();
let width = match (self.width, fills) {
(Some(width), _) => StyleWidth::Set(width),
(None, true) => StyleWidth::Automatic,
(None, false) => return Err(ChartReason::LineLook),
};
let ends = match self.ends {
LineEnds::Round => true,
LineEnds::Unwritten => fills,
LineEnds::Other => false,
};
let dash = match self.dash {
SeriesDash::Solid => None,
SeriesDash::Preset(dash) if fills => Some(dash),
SeriesDash::Preset(_) | SeriesDash::Other => return Err(ChartReason::LineLook),
};
if ends {
Ok((width, dash))
} else {
Err(ChartReason::LineLook)
}
}
}
impl LineEnds {
fn read(doc: &Document, ln: NodeId) -> Self {
let cap = doc.attribute(ln, None, "cap");
let joins = ["round", "miter", "bevel"].map(|join| doc.child(ln, A, join).is_some());
match (cap, joins) {
(Some("rnd"), [true, false, false]) => Self::Round,
(None | Some("rnd"), [_, false, false]) => Self::Unwritten,
_ => Self::Other,
}
}
}
impl SeriesDash {
fn read(doc: &Document, ln: NodeId) -> Self {
if doc.child(ln, A, "custDash").is_some() {
return Self::Other;
}
doc.child(ln, A, "prstDash")
.and_then(|dash| doc.attribute(dash, None, "val"))
.map_or(Self::Solid, |val| {
PRESET_DASHES
.find(val)
.map_or(Self::Other, |(dash, _, _)| *dash)
})
}
}
impl SeriesMarker {
fn marker(
&self,
index: usize,
(styled, shown): (bool, bool),
fills: bool,
) -> Result<Option<Marker>, ChartReason> {
let style_symbol = || {
AUTOMATIC_SYMBOLS
.get(index)
.copied()
.ok_or(ChartReason::StyleColors)
};
match self {
Self::None => Ok(None),
Self::Styled if styled && shown => Ok(Some(Marker {
symbol: style_symbol()?,
size: None,
fill: None,
outline: Some(MarkerOutline::STYLE),
})),
Self::Drawn { symbol, size, look } => {
let symbol = match symbol {
Some(symbol) => *symbol,
None if fills => style_symbol()?,
None => return Err(ChartReason::LineMarkers),
};
let (fill, outline) = match look {
Some(look) => look.parts(fills).ok_or(ChartReason::LineMarkers)?,
None if styled || fills => (None, Some(MarkerOutline::STYLE)),
None => return Err(ChartReason::LineMarkers),
};
Ok(Some(Marker {
symbol,
size: *size,
fill,
outline,
}))
}
Self::Styled | Self::Other => Err(ChartReason::LineMarkers),
}
}
fn read(reader: &mut PartReader, ser: NodeId) -> Self {
let Some(marker) = reader.doc.child(ser, C, "marker") else {
return Self::Styled;
};
let symbol = match val_case(reader, marker, "symbol", MARKER_SYMBOLS) {
Some(SymbolCase::Drawn(symbol)) => Some(symbol),
Some(SymbolCase::Hidden) => return Self::None,
Some(SymbolCase::Other) => return Self::Other,
None => None,
};
let size = read_value(reader, marker, "size", |v| v.parse::<i64>().ok())
.and_then(Length::from_points);
let doc = reader.doc;
let Some(props) = doc.child(marker, C, "spPr") else {
return Self::Drawn {
symbol,
size,
look: None,
};
};
let mut warnings = Warnings::new();
let solid = |doc: &Document, node: NodeId, warnings: &mut Warnings<_>| {
doc.child(node, A, "solidFill")
.and_then(|solid| DrawColor::read(doc, solid, warnings))
};
let fill = solid(doc, props, &mut warnings);
let outline = match doc.child(props, A, "ln") {
None => WrittenOutline::Unwritten,
Some(ln) if doc.child(ln, A, "noFill").is_some() => WrittenOutline::Hidden,
Some(ln) => {
let Some(color) = solid(doc, ln, &mut warnings) else {
return Self::Other;
};
let width = doc
.attribute(ln, None, "w")
.and_then(|w| w.parse::<i64>().ok())
.and_then(Length::from_emus);
WrittenOutline::Solid(color, width)
}
};
let plain = doc.child_elements(props).all(|child| {
doc.is(child, A, "solidFill")
|| doc.is(child, A, "ln")
|| doc.is(child, A, "effectLst") && doc.child_elements(child).next().is_none()
});
if !plain || !warnings.is_empty() {
return Self::Other;
}
Self::Drawn {
symbol,
size,
look: Some(MarkerLook { fill, outline }),
}
}
}
impl Lines {
fn drawn(
self,
palette: Option<StylePalette>,
hidden: HiddenLine,
rules: PlotRules,
) -> Result<(Vec<LineLook>, BarStacking, Vec<ChartSeries>), ChartReason> {
self.drawn_with(palette, hidden, rules, None)
}
fn drawn_with(
mut self,
palette: Option<StylePalette>,
hidden: HiddenLine,
rules: PlotRules,
combo_colors: Option<(usize, usize)>,
) -> Result<(Vec<LineLook>, BarStacking, Vec<ChartSeries>), ChartReason> {
if self.series.is_empty() {
return Err(ChartReason::NoSeries);
}
let stacking = rules
.bar_stacking(self.grouping)
.map_err(|_| ChartReason::StackedLines)?;
meets([
(!self.extras, ChartReason::LineExtras),
(
rules.draws_smooth_lines() || !self.settings.iter().any(|line| line.smooth),
ChartReason::SmoothLines,
),
])?;
let count = self.series.len();
let mut looks = Vec::with_capacity(count);
for (index, (line, series)) in self.settings.iter().zip(&mut self.series).enumerate() {
let (style_index, style_count) = match combo_colors {
Some((offset, total)) => (series.index.unwrap_or(offset + index), total),
None => (index, count),
};
let (width, dash) = if line.styled {
let palette = palette.ok_or(ChartReason::ChartStyle)?;
let color = style_color_for(palette, style_index, style_count)
.ok_or(ChartReason::StyleColors)?;
series.fill = Warned::new(Some(color), Warnings::new());
(Some(StyleWidth::Automatic), None)
} else if line.hidden && hidden == HiddenLine::MarkersAlone {
(None, None)
} else {
let (width, dash) = line.stroke(rules)?;
(Some(width), dash)
};
let marker = line.marker.marker(
style_index,
(line.styled, self.shows_markers),
rules.fills_marker_looks(),
)?;
if width.is_none() {
let fill = marker.as_ref().and_then(|marker| {
marker
.fill
.clone()
.or_else(|| marker.outline.as_ref().and_then(|o| o.color.clone()))
});
series.fill = Warned::new(fill, Warnings::new());
series.no_fill = series.fill.value.is_none() && marker.is_none();
}
let form = if line.smooth {
LineForm::Smooth
} else {
LineForm::Straight
};
looks.push(LineLook {
width,
marker,
form,
dash,
});
}
Ok((looks, stacking, self.series))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StylePalette {
DarkMono,
Colorful,
AccentMono(SchemeSlot),
}
impl StylePalette {
pub(super) fn of(style_number: Option<u32>, draws_style_look: bool) -> Option<Self> {
let number = style_number?;
if !draws_style_look {
return (number == 2).then_some(Self::Colorful);
}
let zero_based = number.checked_sub(1)?;
if !CHART_STYLE_FLAT_ROWS.contains(&(zero_based / CHART_STYLE_COLUMNS)) {
return None;
}
match zero_based % CHART_STYLE_COLUMNS {
0 => Some(Self::DarkMono),
1 => Some(Self::Colorful),
col => ACCENTS
.get(usize::try_from(col - 2).ok()?)
.copied()
.map(Self::AccentMono),
}
}
}
fn apply_style_step(color: DrawColor, step: i64) -> DrawColor {
match step.cmp(&PERCENT) {
std::cmp::Ordering::Less => color.shaded(step * THOUSANDTHS),
std::cmp::Ordering::Equal => color,
std::cmp::Ordering::Greater => color.tinted((2 * PERCENT - step) * THOUSANDTHS),
}
}
fn style_ramp_step(index: usize, count: usize) -> Option<i64> {
let idx = i64::try_from(index).ok()?;
let total = i64::try_from(count).ok()?;
let span = 2 * (PERCENT - CHART_STYLE_SHADE_FLOOR);
Some(CHART_STYLE_SHADE_FLOOR + span.checked_mul(idx + 1)? / (total + 1))
}
pub(super) fn style_color_for(
palette: StylePalette,
index: usize,
count: usize,
) -> Option<DrawColor> {
if count == 0 {
return None;
}
let accents = ACCENTS.len();
match palette {
StylePalette::Colorful => {
let slot = *ACCENTS.get(index % accents)?;
let step = style_ramp_step(index / accents, count / accents + 1)?;
Some(apply_style_step(DrawColor::scheme(slot), step))
}
StylePalette::DarkMono => {
let tint = *CHART_STYLE_DARK_TINTS.get(index % accents)?;
let base = DrawColor::scheme(SchemeSlot::Dark1).tinted(tint * THOUSANDTHS);
let step = style_ramp_step(index / accents, count / accents + 1)?;
Some(apply_style_step(base, step))
}
StylePalette::AccentMono(slot) => {
let step = style_ramp_step(index, count)?;
Some(apply_style_step(DrawColor::scheme(slot), step))
}
}
}
#[cfg(test)]
fn style_color(index: usize, count: usize) -> Option<DrawColor> {
style_color_for(StylePalette::Colorful, index, count)
}
fn read_style_info(doc: &Document, space: NodeId) -> Option<ChartStyleInfo> {
let mut found: Option<u32> = None;
let mut has_c14 = false;
let mut has_plain = false;
for node in style_nodes(doc, space) {
let raw = doc.attribute(node, None, "val")?.parse::<u32>().ok()?;
let normalized = if doc.is(node, C, "style") {
has_plain = true;
(1..=CHART_STYLE_MAX).contains(&raw).then_some(raw)?
} else {
has_c14 = true;
raw.checked_sub(CHART_STYLE_C14_OFFSET)
.filter(|n| (1..=CHART_STYLE_MAX).contains(n))?
};
if let Some(prev) = found
&& prev != normalized
{
return None;
}
found = Some(normalized);
}
let number = found.unwrap_or(2);
Some(ChartStyleInfo {
number,
legacy_lines: has_plain && !has_c14 && number != 2,
})
}
fn style_nodes(doc: &Document, space: NodeId) -> impl Iterator<Item = NodeId> + '_ {
let alternates = doc
.child_elements(space)
.filter(|&node| {
doc.element(node)
.is_some_and(|e| e.name.local == "AlternateContent")
})
.flat_map(|alternate| doc.child_elements(alternate))
.flat_map(|branch| doc.child_elements(branch));
doc.child_elements(space)
.chain(alternates)
.filter(|&node| doc.element(node).is_some_and(|e| e.name.local == "style"))
}
const ACCENTS: [SchemeSlot; 6] = [
SchemeSlot::Accent1,
SchemeSlot::Accent2,
SchemeSlot::Accent3,
SchemeSlot::Accent4,
SchemeSlot::Accent5,
SchemeSlot::Accent6,
];
impl Axis {
fn read(reader: &mut PartReader, node: NodeId, kind: AxisKind) -> Self {
let doc = reader.doc;
let scaling = doc.child(node, C, "scaling");
let mut bound =
|name: &str| scaling.and_then(|s| read_value(reader, s, name, Decimal::parse));
let (min, max, log_base) = (bound("min"), bound("max"), bound("logBase"));
let orientation = scaling
.and_then(|s| val_case(reader, s, "orientation", ORIENTATION))
.unwrap_or(Orientation::MinMax);
Self {
kind,
id: value(doc, node, "axId").map(str::to_owned),
place: val_case(reader, node, "axPos", AXIS_PLACE),
minor_gridlines: doc.child(node, C, "minorGridlines").is_some(),
deleted: Flag::of(doc, node, "delete").is_on(),
scaling: Scaling {
min,
max,
log_base,
orientation,
},
major_unit: read_value(reader, node, "majorUnit", Decimal::parse),
labels: val_case(reader, node, "tickLblPos", LABEL_POSITION)
.unwrap_or(LabelPosition::NextTo),
label_size: text_size(reader, node),
label_font: text_font(doc, node),
label_fill: text_fill(doc, node),
gridlines: doc
.child(node, C, "majorGridlines")
.map(|lines| line_look(doc, lines)),
line: line_look(doc, node),
tick_marks: val_case(reader, node, "majorTickMark", TICK_MARK),
crosses: if doc.child(node, C, "crossesAt").is_some() {
Crossing::At(read_value(reader, node, "crossesAt", Decimal::parse))
} else {
val_case(reader, node, "crosses", CROSSES).unwrap_or(Crossing::AutoZero)
},
title: doc
.child(node, C, "title")
.map(|title| shown_title(reader, title, OwnText::Undrawn)),
own_format: own_format(doc, node),
}
}
}
impl ManualLayout {
fn read(reader: &mut PartReader, node: NodeId) -> Self {
let target =
val_case(reader, node, "layoutTarget", LAYOUT_TARGET).unwrap_or(LayoutTarget::Outer);
let mut mode =
|name: &str| val_case(reader, node, name, LAYOUT_MODE).unwrap_or(LayoutMode::Factor);
let (modes, size_modes) = (
[mode("xMode"), mode("yMode")],
[mode("wMode"), mode("hMode")],
);
let edges = ["x", "y", "w", "h"].map(|name| read_value(reader, node, name, Decimal::parse));
Self {
target,
modes,
size_modes,
edges,
}
}
fn edge_box(&self) -> Option<LayoutBox> {
if self.modes != [LayoutMode::Edge; 2] || self.size_modes != [LayoutMode::Factor; 2] {
return None;
}
let [x, y, w, h] = self.edges;
Some(LayoutBox {
x: x?,
y: y?,
w: w.filter(|w| w.is_positive())?,
h: h.filter(|h| h.is_positive())?,
})
}
fn plot_layout(&self) -> Option<PlotLayout> {
Some(PlotLayout {
inner: self.target == LayoutTarget::Inner,
edges: self.edge_box()?,
})
}
fn corner(&self) -> Option<LayoutCorner> {
let [x, y, w, h] = self.edges;
if self.modes != [LayoutMode::Edge; 2] || w.is_some() || h.is_some() {
return None;
}
Some(LayoutCorner { x: x?, y: y? })
}
fn legend_box(&self) -> LegendBox {
self.edge_box().map_or(LegendBox::Other, LegendBox::Manual)
}
}
fn plot_place(layout: Option<&ManualLayout>) -> PlotPlace {
layout.map_or(PlotPlace::Automatic, |manual| {
manual
.plot_layout()
.map_or(PlotPlace::Other, PlotPlace::Manual)
})
}
impl Part {
fn of(chart: ChartModel, rules: PlotRules) -> Result<Look<Self>, ChartReason> {
let (axis_lines, line_palette, style_palette, style) =
chart_style_modes(chart.style, rules);
let DrawnGroup {
mut group,
series: drawn_series,
vary_by_category,
x_format,
line_ax_ids,
} = drawn_group(chart.groups, (line_palette, style_palette), rules)?;
let (category_axis, value_axis, secondary_val_axis, axis_text) =
drawn_axes(chart.axes, &chart.text, (&group, &line_ax_ids, rules))?;
set_scatter_x_scale(&mut group, &category_axis);
let legend = drawn_legend(chart.legend, &chart.text)?;
group_limits(x_format.as_ref(), &category_axis)?;
let mut warnings = Warnings::new();
let secondary_axis = build_secondary_axis(
secondary_val_axis,
(&group, &drawn_series),
(&chart.text, rules, axis_lines, style),
&mut warnings,
)?;
let title = drawn_title(chart.title, rules, &chart.text, &mut warnings)?;
let plot_place = plot_place(chart.plot_layout.as_ref());
let category_crossing =
category_crossing(&group, (category_axis.crosses, value_axis.crosses), rules);
let value_format = value_format(&group, &value_axis, &drawn_series, rules);
let first_categories = first_categories(&group, &drawn_series);
let series = drawn_series_of(
drawn_series,
vary_by_category,
((&group, chart.blanks), rules, &chart.text, style_palette),
&mut warnings,
)?;
let (categories, data_table) = resolve_categories_and_data_table(
&series,
chart.data_table,
(axis_lines, plot_place, &group, &chart.text, style),
&mut warnings,
)?;
let category_names = category_names(
first_categories,
category_axis.own_format.as_ref(),
categories,
rules,
);
extend_warnings(
&mut warnings,
[legend.fill.warnings, axis_text.titles.warnings],
);
let scale = SetScale {
min: value_axis.scaling.min,
max: value_axis.scaling.max,
major_unit: value_axis.major_unit,
};
let (lines, category_label_fill, value_label_fill) = drawn_lines(
chart.area,
(category_axis, value_axis),
(axis_lines, style),
&mut warnings,
);
let part = Self {
area: lines.area,
columns: Columns {
other_labels: series.iter().any(|s| s.labels == SeriesLabels::Other),
series,
categories,
group,
title,
legend: legend.place,
legend_box: legend.layout,
label_size: axis_text.size,
legend_size: legend.size,
value_label_size: axis_text.value_size,
font: axis_text.font,
gridlines: lines.gridlines,
axis: lines.axis,
value_axis: lines.value_axis,
ticks: lines.ticks,
plot_place,
scale,
category_crossing,
axis_titles: axis_text.titles.value,
value_format,
category_names,
value_label_fill,
category_label_fill,
legend_font: legend.font,
legend_fill: legend.fill.value,
legend_text: legend.text,
axis_forms: axis_text.forms,
secondary_axis,
data_table,
},
};
Ok(Warned::new(part, warnings))
}
}
fn chart_style_modes(
style: Option<ChartStyleInfo>,
rules: PlotRules,
) -> (
bool,
Option<StylePalette>,
Option<StylePalette>,
StyleLineMode,
) {
let axis_lines = rules.draws_style_look();
let line_palette = StylePalette::of(style.map(|s| s.number), axis_lines);
let style_palette = axis_lines.then_some(line_palette).flatten();
let mode = match (style_palette, style) {
(Some(_), Some(info)) if info.legacy_lines => StyleLineMode::LegacyDarkAxes,
(Some(_), _) => StyleLineMode::Tinted,
(None, _) => StyleLineMode::None,
};
(axis_lines, line_palette, style_palette, mode)
}
fn resolve_categories_and_data_table(
series: &[Series],
data_table: Option<DataTableMarkup>,
(axis_lines, plot_place, group, text, style): (
bool,
PlotPlace,
&ChartGroup,
&ChartText,
StyleLineMode,
),
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<(usize, Option<Box<DataTable>>), ChartReason> {
let supported = axis_lines
&& matches!(
plot_place,
PlotPlace::Automatic | PlotPlace::Manual(PlotLayout { inner: true, .. })
)
&& matches!(
group,
ChartGroup::Columns { .. } | ChartGroup::Lines { .. } | ChartGroup::Combo { .. }
);
let categories = categories_of(series, data_table.is_some() && !supported)?;
let resolved = data_table.map(|table| Box::new(table.resolve(text, style, warnings)));
Ok((categories, resolved))
}
fn extend_warnings<const N: usize>(
warnings: &mut Warnings<DrawingMlWarning>,
extras: [Warnings<DrawingMlWarning>; N],
) {
for extra in extras {
warnings.extend(extra, std::convert::identity);
}
}
fn drawn_lines(
area: ElementLook,
(category_axis, value_axis): (Axis, Axis),
(axis_lines, style): (bool, StyleLineMode),
warnings: &mut Warnings<DrawingMlWarning>,
) -> (DrawnLines, Option<DrawColor>, Option<DrawColor>) {
extend_warnings(
warnings,
[
value_axis.label_fill.warnings,
category_axis.label_fill.warnings,
],
);
let (value_line, value_ticks) =
shown_axis_line(value_axis.deleted, value_axis.line, value_axis.tick_marks);
let cat_line = shown_axis_line(
category_axis.deleted,
category_axis.line,
category_axis.tick_marks,
);
let lines = DrawnLines::of(
area,
cat_line,
(value_axis.gridlines, value_line, value_ticks),
(axis_lines, style),
warnings,
);
(
lines,
category_axis.label_fill.value,
value_axis.label_fill.value,
)
}
const fn set_scatter_x_scale(group: &mut ChartGroup, axis: &Axis) {
if let ChartGroup::Scatter { x_scale, .. } = group {
*x_scale = SetScale {
min: axis.scaling.min,
max: axis.scaling.max,
major_unit: axis.major_unit,
};
}
}
fn category_crossing(
group: &ChartGroup,
(category, value): (Crossing, Crossing),
rules: PlotRules,
) -> Option<CategoryCrossing> {
if matches!(group, ChartGroup::Scatter { .. }) {
return matches!((category, value), (Crossing::AutoZero, Crossing::AutoZero))
.then_some(CategoryCrossing::AutoZero);
}
rules.category_crossing(category, value)
}
fn drawn_title(
title: TitleState,
rules: PlotRules,
text: &ChartText,
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Option<Title>, ChartReason> {
let decided = title
.known()
.ok_or(ChartReason::UnknownTitle)?
.shown()
.map(|own| own.decided(rules, text))
.transpose()?;
Ok(decided.map(|title| {
warnings.extend(title.warnings, std::convert::identity);
title.value
}))
}
fn axis_titles(
(category, value): (Option<OwnTitle>, Option<OwnTitle>),
(titled_group, swapped, value_deleted): (bool, bool, bool),
text: &ChartText,
warnings: &mut Warnings<DrawingMlWarning>,
) -> AxisTitles {
if category.is_none() && value.is_none() {
return AxisTitles::NONE;
}
if !titled_group || (value_deleted && value.is_some()) {
return AxisTitles::Other;
}
let mut drawn = |title: Option<OwnTitle>, turn| match title {
None => Some(None),
Some(title) => title
.axis_title(turn, text, warnings)
.map(|title| Some(Box::new(title))),
};
let (value_turn, category_turn) = if swapped {
(TitleTurn::Upright, TitleTurn::Upward)
} else {
(TitleTurn::Upward, TitleTurn::Upright)
};
match (drawn(value, value_turn), drawn(category, category_turn)) {
(Some(value), Some(category)) => AxisTitles::Drawn { value, category },
_ => AxisTitles::Other,
}
}
fn categories_of(series: &[Series], data_table: bool) -> Result<usize, ChartReason> {
let categories = series.first().ok_or(ChartReason::NoSeries)?.values.len();
meets([
(
series.iter().all(|s| s.values.len() == categories),
ChartReason::SeriesLengths,
),
(
series
.iter()
.flat_map(|s| s.values.iter().flatten())
.any(|v| v.digits != 0),
ChartReason::AllZero,
),
(!data_table, ChartReason::DataTable),
])?;
Ok(categories)
}
fn group_limits(x_format: Option<&FormatCode>, x_axis: &Axis) -> Result<(), ChartReason> {
let general =
x_format.is_none_or(|format| x_axis.own_format.as_ref().unwrap_or(format).is_general());
meets([(general, ChartReason::OtherNumberFormat)])
}
struct DrawnLegend {
place: Option<LegendPlace>,
size: i64,
font: FontRef,
fill: Look<Option<DrawColor>>,
text: LegendText,
layout: LegendBox,
}
struct DrawnGroup {
group: ChartGroup,
series: Vec<ChartSeries>,
vary_by_category: bool,
x_format: Option<FormatCode>,
line_ax_ids: Vec<String>,
}
fn drawn_group(
groups: Vec<Group>,
(line_palette, style_palette): (Option<StylePalette>, Option<StylePalette>),
rules: PlotRules,
) -> Result<DrawnGroup, ChartReason> {
let hidden_line = if rules.draws_style_look() {
HiddenLine::MarkersAlone
} else {
HiddenLine::NoColor
};
let bars = match <[Group; 1]>::try_from(groups) {
Ok([Group::Bars(bars)]) => bars,
Ok([Group::Lines(lines)]) => {
let (looks, stacking, series) = lines.drawn(line_palette, hidden_line, rules)?;
return Ok(DrawnGroup {
group: ChartGroup::Lines { looks, stacking },
series,
vary_by_category: false,
x_format: None,
line_ax_ids: Vec::new(),
});
}
Ok([Group::Scatter(scatter)]) => {
if !rules.draws_scatter() {
return Err(ChartReason::Scatter);
}
let (group, series, x_format) = scatter.drawn(line_palette, rules)?;
return Ok(DrawnGroup {
group,
series,
vary_by_category: false,
x_format: Some(x_format),
line_ax_ids: Vec::new(),
});
}
Ok([Group::Pie(_) | Group::Doughnut(_)]) => return Err(ChartReason::OtherGroup),
Err(groups) => return drawn_combo(groups, (line_palette, style_palette), rules),
};
let (gap, overlap) = (bars.gap, bars.overlap);
let group = if let Some(solid) = &bars.solid {
solid.drawn((bars.direction, bars.grouping), (gap, overlap), rules)?
} else {
if bars.direction != BarDirection::Vertical && !rules.draws_horizontal_bars() {
return Err(ChartReason::HorizontalBars);
}
let stacking = rules.bar_stacking(match bars.grouping {
BarGrouping::Clustered => Some(BarStacking::Clustered),
BarGrouping::Stacked => Some(BarStacking::Stacked),
BarGrouping::PercentStacked => Some(BarStacking::PercentStacked),
BarGrouping::Standard => None,
})?;
match bars.direction {
BarDirection::Vertical => ChartGroup::Columns {
gap,
overlap,
stacking,
},
BarDirection::Horizontal => ChartGroup::Bars {
gap,
overlap,
stacking,
},
}
};
let mut series = bars.series;
let vary_by_category = if let Some(palette) = style_palette {
match rules.bar_color_mode(bars.uniform_colors, series.len()) {
BarColorMode::BySeries => {
let count = series.len();
for (index, one) in series.iter_mut().enumerate() {
if !one.fill_written {
let color = style_color_for(palette, index, count)
.ok_or(ChartReason::StyleColors)?;
one.fill = Warned::new(Some(color), Warnings::new());
}
}
false
}
BarColorMode::ByCategory => true,
BarColorMode::None => false,
}
} else {
false
};
Ok(DrawnGroup {
group,
series,
vary_by_category,
x_format: None,
line_ax_ids: Vec::new(),
})
}
fn drawn_combo(
groups: Vec<Group>,
(line_palette, style_palette): (Option<StylePalette>, Option<StylePalette>),
rules: PlotRules,
) -> Result<DrawnGroup, ChartReason> {
let Ok([Group::Bars(bars), Group::Lines(lines)] | [Group::Lines(lines), Group::Bars(bars)]) =
<[Group; 2]>::try_from(groups)
else {
return Err(ChartReason::NotOneGroup);
};
if bars.direction != BarDirection::Vertical {
return Err(ChartReason::NotOneGroup);
}
let stacking = rules.bar_stacking(match bars.grouping {
BarGrouping::Clustered => Some(BarStacking::Clustered),
BarGrouping::Stacked => Some(BarStacking::Stacked),
BarGrouping::PercentStacked | BarGrouping::Standard => {
return Err(ChartReason::NotOneGroup);
}
})?;
let bar_count = bars.series.len();
let total = bar_count + lines.series.len();
if bar_count == 0 {
return Err(ChartReason::NoSeries);
}
let mut series = bars.series;
if let Some(palette) = style_palette {
for (index, one) in series.iter_mut().enumerate() {
if !one.fill_written {
let slot = one.index.unwrap_or(index);
let color =
style_color_for(palette, slot, total).ok_or(ChartReason::StyleColors)?;
one.fill = Warned::new(Some(color), Warnings::new());
}
}
}
let line_ax_ids = lines.ax_ids.clone();
let hidden_line = if rules.draws_style_look() {
HiddenLine::MarkersAlone
} else {
HiddenLine::NoColor
};
let (looks, line_stacking, line_series) =
lines.drawn_with(line_palette, hidden_line, rules, Some((bar_count, total)))?;
if line_stacking == BarStacking::PercentStacked {
return Err(ChartReason::StackedLines);
}
let group = rules.combo_group(
(bars.gap, bars.overlap, stacking),
bar_count,
(looks, line_stacking),
)?;
series.extend(line_series);
Ok(DrawnGroup {
group,
series,
vary_by_category: false,
x_format: None,
line_ax_ids,
})
}
fn resolve_series_fill(
(fill, gradient, fill_written, no_fill, point_fills): (
Look<Option<DrawColor>>,
Option<LinearGradient>,
bool,
bool,
Vec<pie::PointFill>,
),
(is_bar, vary_by_category, single_series, count): (bool, bool, bool, usize),
(rules, palette): (PlotRules, Option<StylePalette>),
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<SeriesFill, ChartReason> {
if vary_by_category
&& !fill_written
&& let Some(palette) = palette
{
return Ok(SeriesFill::Points(pie::slice_fills(
fill,
point_fills,
(count, pie::SliceStyle::ByPoint(palette)),
warnings,
)?));
}
let styled = rules.draws_style_look();
if styled && is_bar && pie::has_bar_point_override(&point_fills, count, gradient.is_some()) {
return pie::resolve_bar_point_fills(
fill,
no_fill,
point_fills,
(count, single_series),
warnings,
);
}
warnings.extend(fill.warnings, std::convert::identity);
match (fill.value, gradient) {
(Some(color), _) => Ok(SeriesFill::Color(color)),
(None, Some(gradient)) if is_bar => Ok(SeriesFill::Gradient(gradient)),
(None, None) if styled && no_fill => Ok(SeriesFill::None),
_ => Err(ChartReason::SeriesFill),
}
}
fn drawn_series_of(
series: Vec<ChartSeries>,
vary_by_category: bool,
((group, blanks), rules, text, palette): (
(&ChartGroup, BlankPoints),
PlotRules,
&ChartText,
Option<StylePalette>,
),
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Vec<Series>, ChartReason> {
let single_series = series.len() == 1;
let mut drawn = Vec::with_capacity(series.len());
for (
series_index,
ChartSeries {
fill,
gradient,
fill_written,
no_fill,
point_fills,
name,
values,
labels,
..
},
) in series.into_iter().enumerate()
{
let is_bar = match group {
ChartGroup::Columns { .. } | ChartGroup::Bars { .. } | ChartGroup::Columns3D { .. } => {
true
}
ChartGroup::Combo { bar_count, .. } => series_index < *bar_count,
ChartGroup::Lines { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. } => false,
};
let drawn_at = drawn_label_positions(group, is_bar);
let labels = labels.drawn((drawn_at, false, rules), text, warnings);
let values = values.drawn((group.has_blank_points(), blanks), rules)?;
let fill = resolve_series_fill(
(fill, gradient, fill_written, no_fill, point_fills),
(
is_bar,
vary_by_category && series_index == 0,
single_series,
values.len(),
),
(rules, palette),
warnings,
)?;
drawn.push(Series {
fill,
values,
name,
labels,
});
}
Ok(drawn)
}
const fn drawn_label_positions(group: &ChartGroup, is_bar: bool) -> &'static [DataLabelPosition] {
if is_bar {
match group.stacking() {
Some(BarStacking::Clustered) => &COLUMN_LABEL_POSITIONS,
Some(BarStacking::Stacked | BarStacking::PercentStacked) => &STACKED_LABEL_POSITIONS,
None => &[],
}
} else if matches!(group, ChartGroup::Lines { .. } | ChartGroup::Combo { .. }) {
&LINE_LABEL_POSITIONS
} else {
&[]
}
}
fn drawn_legend(legend: Option<Legend>, text: &ChartText) -> Result<DrawnLegend, ChartReason> {
let Some(legend) = legend else {
return Ok(DrawnLegend {
place: None,
size: text.size(None),
font: text.font(None),
fill: Warned::new(None, Warnings::new()),
text: LegendText::default(),
layout: LegendBox::Automatic,
});
};
Ok(DrawnLegend {
place: Some(legend.drawn_place()?),
size: text.size(legend.label_size),
font: text.font(legend.font),
fill: legend.fill,
text: legend.text,
layout: legend
.layout
.as_ref()
.map_or(LegendBox::Automatic, ManualLayout::legend_box),
})
}
struct AxisText {
size: i64,
value_size: i64,
font: FontRef,
forms: AxisForms,
titles: Look<AxisTitles>,
}
fn drawn_axes(
axes: Vec<Axis>,
text: &ChartText,
(group, line_ax_ids, rules): (&ChartGroup, &[String], PlotRules),
) -> Result<(Axis, Axis, Option<Axis>, AxisText), ChartReason> {
let (mut category_axis, mut value_axis, secondary_axis) = match group {
ChartGroup::Scatter { .. } => {
let (x, y) = x_and_y(axes)?;
(x, y, None)
}
ChartGroup::Combo { .. } if axes.len() > 2 => combo_secondary_axes(axes, line_ax_ids)?,
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Columns3D { .. }
| ChartGroup::Lines { .. }
| ChartGroup::Combo { .. } => {
let (cat, val) = category_and_value(axes).ok_or(ChartReason::Axes)?;
(cat, val, None)
}
ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => return Err(ChartReason::Axes),
};
let forms = axis_forms((&category_axis, &value_axis), group, rules)?;
check_value_scale(&value_axis)?;
if let Some(sec) = &secondary_axis {
check_value_scale(sec)?;
}
let size = text.size(category_axis.label_size);
let (value_size, font) = if forms.value_deleted {
(size, text.font(category_axis.label_font.clone()))
} else {
(
text.size(value_axis.label_size),
text.font(value_axis.label_font.clone()),
)
};
let titled_group = rules.draws_axis_titles()
&& matches!(
group,
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Lines { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Combo { .. }
);
let swapped = matches!(group, ChartGroup::Bars { .. });
let mut warnings = Warnings::new();
let titles = axis_titles(
(category_axis.title.take(), value_axis.title.take()),
(titled_group, swapped, forms.value_deleted),
text,
&mut warnings,
);
let axis_text = AxisText {
size,
value_size,
font,
forms,
titles: Warned::new(titles, warnings),
};
Ok((category_axis, value_axis, secondary_axis, axis_text))
}
fn check_value_scale(axis: &Axis) -> Result<(), ChartReason> {
let scaling = &axis.scaling;
meets([(
scaling.log_base.is_none()
&& scaling.orientation == Orientation::MinMax
&& axis.major_unit.is_none_or(Decimal::is_positive)
&& scaling
.min
.zip(scaling.max)
.is_none_or(|(min, max)| min < max),
ChartReason::ValueScale,
)])
}
fn combo_secondary_axes(
axes: Vec<Axis>,
line_ax_ids: &[String],
) -> Result<(Axis, Axis, Option<Axis>), ChartReason> {
let (mut pri_cat, mut pri_val, mut sec_cat, mut sec_val) = (None, None, None, None);
for axis in axes {
match (axis.kind, axis.place, axis.deleted) {
(AxisKind::Category, Some(AxisPlace::Bottom), false) if pri_cat.is_none() => {
pri_cat = Some(axis);
}
(AxisKind::Category, Some(AxisPlace::Bottom | AxisPlace::Top), true)
if sec_cat.is_none() =>
{
sec_cat = Some(axis);
}
(AxisKind::Value, Some(AxisPlace::Left), _) if pri_val.is_none() => {
pri_val = Some(axis);
}
(AxisKind::Value, Some(AxisPlace::Right), _) if sec_val.is_none() => {
sec_val = Some(axis);
}
_ => return Err(ChartReason::Axes),
}
}
let (Some(pri_cat), Some(pri_val), Some(_sec_cat), Some(sec_val)) =
(pri_cat, pri_val, sec_cat, sec_val)
else {
return Err(ChartReason::Axes);
};
let line_uses_sec = sec_val
.id
.as_ref()
.is_some_and(|id| line_ax_ids.iter().any(|ref_id| ref_id == id));
if !line_uses_sec || sec_val.minor_gridlines || sec_val.gridlines.is_some() {
return Err(ChartReason::Axes);
}
if sec_val.title.is_some() {
return Err(ChartReason::AxisTitle);
}
Ok((pri_cat, pri_val, Some(sec_val)))
}
fn axis_ids_of(doc: &Document, node: NodeId) -> Vec<String> {
doc.child_elements(node)
.filter(|&n| doc.is(n, C, "axId"))
.filter_map(|n| doc.attribute(n, None, "val").map(str::to_owned))
.collect()
}
fn build_secondary_axis(
sec: Option<Axis>,
(group, series): (&ChartGroup, &[ChartSeries]),
(text, rules, axis_lines, style): (&ChartText, PlotRules, bool, StyleLineMode),
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Option<Box<SecondaryValueAxis>>, ChartReason> {
let Some(sec) = sec else {
return Ok(None);
};
let labels_hidden = sec.deleted || sec.labels == LabelPosition::None;
if !labels_hidden && sec.labels != LabelPosition::NextTo {
return Err(ChartReason::AxisNotShown);
}
let bar_count = match *group {
ChartGroup::Combo { bar_count, .. } => bar_count,
_ => 0,
};
let line_series = series.get(bar_count..).unwrap_or_default();
let format =
value_format(group, &sec, line_series, rules).ok_or(ChartReason::OtherNumberFormat)?;
let (sec_line, sec_ticks) = shown_axis_line(sec.deleted, sec.line, sec.tick_marks);
let line = if axis_lines {
let drawn = sec_line.drawn(style, (Geometry::Line, None));
warnings.extend(drawn.warnings, std::convert::identity);
drawn.value
} else {
ShapeLook::plain(Geometry::Line, None, None)
};
warnings.extend(sec.label_fill.warnings, std::convert::identity);
Ok(Some(Box::new(SecondaryValueAxis {
scale: SetScale {
min: sec.scaling.min,
max: sec.scaling.max,
major_unit: sec.major_unit,
},
format,
label_size: text.size(sec.label_size),
label_fill: sec.label_fill.value,
line,
ticks: axis_lines && sec_ticks == Some(TickMark::Outside),
labels_hidden,
})))
}
fn shown_axis_line(
deleted: bool,
line: ElementLook,
ticks: Option<TickMark>,
) -> (ElementLook, Option<TickMark>) {
if deleted {
(ElementLook::none(), None)
} else {
(line, ticks)
}
}
fn axis_forms(
(category, value): (&Axis, &Axis),
group: &ChartGroup,
rules: PlotRules,
) -> Result<AxisForms, ChartReason> {
let allow_hidden = rules.draws_deleted_axis();
let forms = AxisForms {
value_deleted: (value.deleted || value.labels == LabelPosition::None)
&& !matches!(group, ChartGroup::Scatter { .. })
&& allow_hidden,
category_hidden: (category.deleted || category.labels == LabelPosition::None)
&& allow_hidden,
low_labels: !category.deleted
&& category.labels == LabelPosition::Low
&& matches!(
group,
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Lines { .. }
| ChartGroup::Combo { .. }
)
&& rules.draws_low_labels(),
};
let category_shown = forms.category_hidden
|| (!category.deleted && (category.labels == LabelPosition::NextTo || forms.low_labels));
let value_shown =
forms.value_deleted || (!value.deleted && value.labels == LabelPosition::NextTo);
meets([(category_shown && value_shown, ChartReason::AxisNotShown)])?;
Ok(forms)
}
fn x_and_y(axes: Vec<Axis>) -> Result<(Axis, Axis), ChartReason> {
let [first, second] = <[Axis; 2]>::try_from(axes).map_err(|_| ChartReason::ScatterAxes)?;
let (x, y) = match (first.place, second.place) {
(Some(AxisPlace::Bottom), Some(AxisPlace::Left)) => (first, second),
(Some(AxisPlace::Left), Some(AxisPlace::Bottom)) => (second, first),
_ => return Err(ChartReason::ScatterAxes),
};
let scaling = &x.scaling;
meets([
(
x.kind == AxisKind::Value && y.kind == AxisKind::Value,
ChartReason::ScatterAxes,
),
(
x.gridlines.is_none() && !x.minor_gridlines,
ChartReason::XGridlines,
),
(
scaling.log_base.is_none()
&& scaling.orientation == Orientation::MinMax
&& x.major_unit.is_none_or(Decimal::is_positive)
&& scaling.min.is_none_or(|min| !min.digits.is_negative())
&& scaling.max.is_none_or(Decimal::is_positive)
&& scaling
.min
.zip(scaling.max)
.is_none_or(|(min, max)| min < max),
ChartReason::ValueScale,
),
])?;
Ok((x, y))
}
fn category_and_value(axes: Vec<Axis>) -> Option<(Axis, Axis)> {
let (mut category, mut value) = (None, None);
for axis in axes {
let slot = match axis.kind {
AxisKind::Category => &mut category,
AxisKind::Value => &mut value,
AxisKind::Date | AxisKind::Series => continue,
};
if slot.replace(axis).is_some() {
return None;
}
}
Some((category?, value?))
}
fn line_look(doc: &Document, node: NodeId) -> ElementLook {
let mut warnings = Warnings::new();
let props = doc.child(node, C, "spPr");
let look = ShapeLook::read_line(doc, props, &mut warnings);
ElementLook {
look: Warned::new(look, warnings),
written: props.is_some(),
}
}
fn value<'a>(doc: &'a Document, node: NodeId, name: &str) -> Option<&'a str> {
doc.child(node, C, name)
.and_then(|child| doc.attribute(child, None, "val"))
}
fn val_case<T: Clone>(
reader: &mut PartReader,
node: NodeId,
name: &str,
table: &'static Values<T>,
) -> Option<T> {
let child = reader.doc.child(node, C, name)?;
reader.enumeration_in(child, (None, "val"), table)
}
fn read_value<T>(
reader: &mut PartReader,
node: NodeId,
name: &str,
parse: impl FnOnce(&str) -> Option<T>,
) -> Option<T> {
let child = reader.doc.child(node, C, name)?;
reader.or_missing_in(child, (None, "val"), parse)
}
fn series_name(doc: &Document, ser: NodeId) -> Option<String> {
let tx = doc.child(ser, C, "tx")?;
let value = match doc.child(tx, C, "strRef") {
Some(reference) => {
let cache = doc.child(reference, C, "strCache")?;
let point = doc
.child_elements(cache)
.find(|&n| doc.is(n, C, "pt") && doc.attribute(n, None, "idx") == Some("0"))?;
doc.child(point, C, "v")?
}
None => doc.child(tx, C, "v")?,
};
Some(doc.text_content(value))
}
fn point_number(value: &str) -> Option<usize> {
usize::try_from(f_office_drawingml::integer(value)?).ok()
}
fn value_format(
group: &ChartGroup,
axis: &Axis,
series: &[ChartSeries],
rules: PlotRules,
) -> Option<LabelFormat> {
let place = LabelPlace::ValueAxis;
if let Some(own) = &axis.own_format {
return own.decided(rules, place);
}
let percent_default = matches!(group.line_stacking(), Some(BarStacking::PercentStacked));
series.first().map_or_else(
|| {
if percent_default {
FormatCode("0%".to_owned()).decided(rules, place)
} else {
FormatCode::general().decided(rules, place)
}
},
|first| {
if percent_default && first.format.is_general() {
FormatCode("0%".to_owned()).decided(rules, place)
} else {
first.format.decided(rules, place)
}
},
)
}
fn own_format(doc: &Document, axis: NodeId) -> Option<FormatCode> {
let format = doc.child(axis, C, "numFmt")?;
let linked = doc
.attribute(format, None, "sourceLinked")
.and_then(crate::on_off::read)
.unwrap_or(false);
if linked {
return None;
}
Some(FormatCode(
doc.attribute(format, None, "formatCode")
.unwrap_or_default()
.to_owned(),
))
}
fn cache_format(doc: &Document, ser: NodeId, values: &str) -> FormatCode {
doc.child(ser, C, values)
.and_then(|val| doc.child(val, C, "numRef"))
.and_then(|num| doc.child(num, C, "numCache"))
.and_then(|cache| doc.child(cache, C, "formatCode"))
.map_or_else(FormatCode::general, |code| {
FormatCode(doc.text_content(code).trim_matches(['\r', '\n']).to_owned())
})
}
fn cached_values(reader: &mut PartReader, ser: NodeId, values: &str) -> CachedValues {
let doc = reader.doc;
let Some(reference) = doc
.child(ser, C, values)
.and_then(|val| doc.child(val, C, "numRef"))
else {
return CachedValues::Unread;
};
let Some(cache) = doc.child(reference, C, "numCache") else {
return CachedValues::Uncached;
};
cached_points(reader, cache, Decimal::parse).map_or(CachedValues::Unread, CachedValues::Points)
}
fn category_texts(reader: &mut PartReader, ser: NodeId) -> CategoryCache {
let doc = reader.doc;
let Some(categories) = doc.child(ser, C, "cat") else {
return CategoryCache::Omitted;
};
if let Some(cache) = doc
.child(categories, C, "strRef")
.and_then(|reference| doc.child(reference, C, "strCache"))
.or_else(|| doc.child(categories, C, "strLit"))
{
return cached_points(reader, cache, |text| Some(text.to_owned()))
.map_or(CategoryCache::Other, CategoryCache::Strings);
}
if let Some(cache) = doc
.child(categories, C, "numRef")
.and_then(|reference| doc.child(reference, C, "numCache"))
.or_else(|| doc.child(categories, C, "numLit"))
{
let format = doc
.child(cache, C, "formatCode")
.map_or_else(FormatCode::general, |code| {
FormatCode(doc.text_content(code).trim_matches(['\r', '\n']).to_owned())
});
return cached_points(reader, cache, Decimal::parse).map_or(
CategoryCache::Other,
|points| CategoryCache::Numbers { format, points },
);
}
CategoryCache::Other
}
fn cached_points<T: Clone>(
reader: &mut PartReader,
cache: NodeId,
parse: impl Fn(&str) -> Option<T>,
) -> Option<Vec<Option<T>>> {
let doc = reader.doc;
let points = read_value(reader, cache, "ptCount", point_number)?;
if points > MAX_CHART_POINTS {
return None;
}
let mut values = vec![None; points];
for point in doc.child_elements(cache).filter(|&n| doc.is(n, C, "pt")) {
let index = reader.or_missing_in(point, (None, "idx"), point_number)?;
let text = doc.child(point, C, "v").map(|v| doc.text_content(v))?;
*values.get_mut(index)? = Some(parse(&text)?);
}
Some(values)
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum CachedValues {
Points(Vec<Option<Decimal>>),
Uncached,
Unread,
}
impl CachedValues {
fn full(&self) -> Option<Vec<Decimal>> {
match self {
Self::Points(points) => points.iter().copied().collect(),
Self::Uncached | Self::Unread => None,
}
}
fn drawn(
self,
(blank_group, blanks): (bool, BlankPoints),
rules: PlotRules,
) -> Result<Vec<Option<Decimal>>, ChartReason> {
let points = match self {
Self::Points(points) if points.iter().all(Option::is_some) => return Ok(points),
Self::Points(points) => points,
Self::Uncached | Self::Unread => return Err(ChartReason::SeriesValues),
};
if !rules.draws_blank_points() || !blank_group {
return Err(ChartReason::SeriesValues);
}
match blanks {
BlankPoints::Gap => Ok(points),
BlankPoints::Zero => Ok(points
.into_iter()
.map(|point| Some(point.unwrap_or(Decimal::ZERO)))
.collect()),
BlankPoints::Span => Err(ChartReason::SeriesValues),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BlankPoints {
Gap,
Zero,
Span,
}
impl BlankPoints {
fn read(doc: &Document, chart: NodeId) -> Self {
match doc
.child(chart, C, "dispBlanksAs")
.and_then(|node| doc.attribute(node, None, "val"))
{
Some("gap") => Self::Gap,
Some("span") => Self::Span,
_ => Self::Zero,
}
}
}
fn first_categories(group: &ChartGroup, series: &[ChartSeries]) -> Option<CategoryCache> {
if matches!(group, ChartGroup::Scatter { .. }) {
return None;
}
series.first().map(|first| first.categories.clone())
}
fn category_names(
cache: Option<CategoryCache>,
axis_own: Option<&FormatCode>,
count: usize,
rules: PlotRules,
) -> Option<Vec<String>> {
let names = match cache? {
CategoryCache::Strings(texts) => string_category_names(texts, rules)?,
CategoryCache::Numbers { format, points } => {
let code = axis_own.unwrap_or(&format);
let label_format = code.decided(rules, LabelPlace::CategoryAxis)?;
numeric_category_names(points, &label_format, rules)?
}
CategoryCache::Omitted => {
FormatCode::general().decided(rules, LabelPlace::CategoryAxis)?;
(1..=count).map(|index| index.to_string()).collect()
}
CategoryCache::Other => return None,
};
(names.len() == count).then_some(names)
}
fn string_category_names(texts: Vec<Option<String>>, rules: PlotRules) -> Option<Vec<String>> {
if rules.draws_blank_points() {
Some(texts.into_iter().map(Option::unwrap_or_default).collect())
} else {
texts.into_iter().collect()
}
}
fn numeric_category_names(
points: Vec<Option<Decimal>>,
format: &LabelFormat,
rules: PlotRules,
) -> Option<Vec<String>> {
let blanks = rules.draws_blank_points();
points
.into_iter()
.map(|point| match point {
Some(value) => plain_written(&format.write(value)?),
None if blanks => Some(String::new()),
None => None,
})
.collect()
}
fn plain_written(written: &WrittenLabel) -> Option<String> {
if written.color.is_some() {
return None;
}
let mut out = String::new();
for piece in &written.pieces {
match piece {
LabelPiece::Text(text) => out.push_str(text),
LabelPiece::Blank(_) => out.push(' '),
}
}
Some(out)
}
fn text_size(reader: &mut PartReader, node: NodeId) -> Option<i64> {
let hundredths = default_run(reader.doc, node)
.and_then(|run| reader.or_missing_in(run, (None, "sz"), f_office_drawingml::integer))?;
Some(hundredths * HALF_POINTS_PER_POINT / PERCENT)
}
fn text_fill(doc: &Document, node: NodeId) -> Look<Option<DrawColor>> {
let mut warnings = Warnings::new();
let fill = default_run(doc, node)
.and_then(|run| doc.child(run, A, "solidFill"))
.and_then(|solid| DrawColor::read(doc, solid, &mut warnings));
Warned::new(fill, warnings)
}
fn text_font(doc: &Document, node: NodeId) -> Option<FontRef> {
let latin = default_run(doc, node).and_then(|run| doc.child(run, A, "latin"))?;
doc.attribute(latin, None, "typeface")
.map(FontRef::of_typeface)
}
fn default_run(doc: &Document, node: NodeId) -> Option<NodeId> {
let text = doc.child(node, C, "txPr")?;
let paragraph = doc.child(text, A, "p")?;
let props = doc.child(paragraph, A, "pPr")?;
doc.child(props, A, "defRPr")
}
fn title(
reader: &mut PartReader,
chart: NodeId,
series: (AutomaticTitle, Option<String>),
) -> TitleState {
let doc = reader.doc;
let deleted = Flag::of(doc, chart, "autoTitleDeleted").is_on();
let (automatic, first_name) = series;
let series = TitleSeries {
automatic,
first_name,
};
match doc.child(chart, C, "title") {
None if deleted => TitleState::Deleted,
None => TitleState::Automatic(automatic),
Some(node) if !deleted => TitleState::Shown(Box::new(shown_title(
reader,
node,
OwnText::Placeholder(series),
))),
_ => TitleState::Unknown,
}
}
fn shown_title(reader: &mut PartReader, node: NodeId, placeholder: OwnText) -> OwnTitle {
let doc = reader.doc;
let rich = doc
.child(node, C, "tx")
.and_then(|tx| doc.child(tx, C, "rich"));
let paragraphs: Vec<NodeId> = rich.map_or_default(|rich| {
doc.child_elements(rich)
.filter(|&n| doc.is(n, A, "p"))
.collect()
});
let mut warnings = Warnings::new();
let mut place = |props: Option<NodeId>| {
props.map_or_default(|props| TitleProps::read(reader, props, &mut warnings))
};
let first_run = paragraphs
.iter()
.flat_map(|&p| doc.child_elements(p).filter(|&n| doc.is(n, A, "r")))
.find_map(|r| doc.child(r, A, "rPr"));
let paragraph_default = paragraphs
.first()
.and_then(|&p| doc.child(p, A, "pPr"))
.and_then(|props| doc.child(props, A, "defRPr"));
let places = [
place(first_run),
place(paragraph_default),
place(default_run(doc, node)),
];
let layout = doc
.child(node, C, "layout")
.and_then(|layout| doc.child(layout, C, "manualLayout"))
.map(|manual| ManualLayout::read(reader, manual));
let corner = layout.as_ref().and_then(ManualLayout::corner);
let text = if (layout.is_some() && corner.is_none()) || Flag::of(doc, node, "overlay").is_on() {
OwnText::Undrawn
} else if doc.child(node, C, "tx").is_none() {
placeholder
} else {
title_lines(reader, node, ¶graphs, &places[0]).map_or(OwnText::Undrawn, OwnText::Lines)
};
OwnTitle {
lines: paragraphs.len().max(1),
places,
text,
corner,
turn: TitleTurn::of(doc, node),
warnings,
}
}
fn title_lines(
reader: &mut PartReader,
node: NodeId,
paragraphs: &[NodeId],
first: &TitleProps,
) -> Option<Vec<String>> {
let doc = reader.doc;
let tx = doc.child(node, C, "tx")?;
if let Some(reference) = doc.child(tx, C, "strRef") {
let cache = doc.child(reference, C, "strCache")?;
let point = doc
.child_elements(cache)
.find(|&n| doc.is(n, C, "pt") && doc.attribute(n, None, "idx") == Some("0"))?;
return Some(vec![doc.text_content(doc.child(point, C, "v")?)]);
}
doc.child(tx, C, "rich")?;
paragraphs
.iter()
.map(|¶graph| paragraph_line(reader, paragraph, first))
.collect()
}
fn paragraph_line(
reader: &mut PartReader,
paragraph: NodeId,
first: &TitleProps,
) -> Option<String> {
let doc = reader.doc;
let mut line = String::new();
for child in doc.child_elements(paragraph) {
if doc.is(child, A, "r") {
let mut warnings = Warnings::new();
let props = doc
.child(child, A, "rPr")
.map_or_default(|props| TitleProps::read(reader, props, &mut warnings));
if props != *first {
return None;
}
line.push_str(
&doc.child(child, A, "t")
.map_or_default(|t| doc.text_content(t)),
);
} else if !(doc.is(child, A, "pPr") || doc.is(child, A, "endParaRPr")) {
return None;
}
}
Some(line)
}
#[cfg(test)]
impl Columns {
pub(crate) fn plain(
series: Vec<Series>,
categories: usize,
group: ChartGroup,
title: Option<Title>,
) -> Self {
Self {
series,
categories,
group,
title,
legend: Some(LegendPlace::Bottom),
legend_box: LegendBox::Automatic,
label_size: 18,
legend_size: 18,
value_label_size: 18,
font: FontRef::MinorLatin,
gridlines: None,
axis: ShapeLook::plain(Geometry::Line, None, None),
value_axis: ShapeLook::plain(Geometry::Line, None, None),
ticks: OutsideTicks::default(),
plot_place: PlotPlace::Automatic,
scale: SetScale::default(),
category_crossing: Some(CategoryCrossing::AutoZero),
axis_titles: AxisTitles::NONE,
value_format: Some(LabelFormat::all_digits()),
category_names: None,
value_label_fill: None,
category_label_fill: None,
legend_font: FontRef::MinorLatin,
legend_fill: None,
legend_text: LegendText::default(),
other_labels: false,
axis_forms: AxisForms::default(),
secondary_axis: None,
data_table: None,
}
}
}
mod columns_3d;
mod label_format;
mod pie;
pub(crate) use columns_3d::ColumnView;
pub(crate) use pie::PieView;
pub(crate) use label_format::all_digits;
pub use label_format::{LabelFormat, LabelPiece, LabelPlace, WrittenLabel};
#[cfg(test)]
mod tests;