use f_office_drawingml::color::DrawColor;
use f_office_drawingml::shape::{Geometry, ShapeLook};
use f_office_units::scale::{DEGREE, FULL_TURN, PERCENT, QUARTER_TURN};
use f_office_warnings::{Warned, Warnings};
use f_office_xml::NodeId;
use super::{
AxisTitles, ChartGroup, ChartModel, ChartReason, ChartSeries, Columns, DataLabelPosition,
DrawingMlWarning, DrawnLines, ElementLook, FILLS, Flag, Group, LabelMarkup, Look, Part,
PieLabelPlace, PlotRules, Series, SeriesFill, SetScale, categories_of, category_names,
drawn_legend, drawn_title, plot_place, read_value, style_color,
};
use crate::ns::{A, C};
use crate::params::{CHART_VIEW_DEFAULT_PERSPECTIVE, CHART_VIEW_LARGEST_PERSPECTIVE};
use crate::reader::PartReader;
pub(super) struct PieGroup {
first_angle: i64,
view: Option<PieView>,
series: Vec<ChartSeries>,
uniform_colors: bool,
point_fills: Vec<PointFill>,
series_explosion: u32,
point_explosions: Vec<(usize, u32)>,
label_position: DataLabelPosition,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PieView {
pub(crate) tilt: i64,
pub(crate) field_of_view: i64,
}
const LARGEST_TILT: i64 = QUARTER_TURN / DEGREE;
impl PieView {
fn read(reader: &mut PartReader, node: Option<NodeId>) -> (Self, i64) {
let mut value = |name: &str, largest: i64| {
node.and_then(|view| {
read_value(reader, view, name, |v| {
v.parse::<i64>().ok().filter(|a| (0..=largest).contains(a))
})
})
};
let tilt = value("rotX", LARGEST_TILT).unwrap_or(0);
let turn = value("rotY", LARGEST_ANGLE).unwrap_or(0);
let perspective = value("perspective", CHART_VIEW_LARGEST_PERSPECTIVE)
.unwrap_or(CHART_VIEW_DEFAULT_PERSPECTIVE);
let field_of_view = perspective / 2;
(
Self {
tilt,
field_of_view,
},
turn,
)
}
}
pub(super) struct PointFill {
index: usize,
fill: Look<Option<DrawColor>>,
written: bool,
}
const LARGEST_ANGLE: i64 = FULL_TURN / DEGREE;
impl PieGroup {
pub(super) fn read(
reader: &mut PartReader,
node: NodeId,
(series, group_labels): (Vec<NodeId>, Option<NodeId>),
view: Option<NodeId>,
) -> Self {
let (first_angle, view) = if reader.doc.is(node, C, "pie3DChart") {
let (view, turn) = PieView::read(reader, view);
(turn, Some(view))
} else {
let first_angle = read_value(reader, node, "firstSliceAng", |v| {
v.parse::<i64>()
.ok()
.filter(|a| (0..=LARGEST_ANGLE).contains(a))
})
.unwrap_or(0);
(first_angle, None)
};
let points = series
.first()
.map_or_else(PiePoints::default, |&ser| points_of(reader, ser));
let doc = reader.doc;
let uniform_colors = Flag::of(doc, node, "varyColors") == Flag::Off;
let label_position = series
.first()
.and_then(|&ser| doc.child(ser, C, "dLbls").or(group_labels))
.map_or(DataLabelPosition::Default, |labels| {
DataLabelPosition::for_pie(doc, labels)
});
let series = series
.into_iter()
.map(|ser| {
ChartSeries::read(reader, (ser, group_labels), |_, props| Some(props), "val")
})
.collect();
Self {
first_angle,
view,
series,
uniform_colors,
point_fills: points.fills,
series_explosion: points.series_explosion,
point_explosions: points.point_explosions,
label_position,
}
}
}
impl PieGroup {
fn drawn(&self, rules: PlotRules) -> bool {
match self.view {
None => rules.draws_pies(),
Some(view) => rules.draws_pies_3d() && view.tilt > 0 && view.field_of_view > 0,
}
}
fn slice_style(&self, style_look: bool) -> SliceStyle {
let named = self.series.first().is_some_and(|first| first.fill_written);
if !style_look || named {
SliceStyle::Unstyled
} else if self.uniform_colors {
SliceStyle::BySeries {
index: 0,
count: self.series.len(),
}
} else {
SliceStyle::ByPoint
}
}
}
pub(super) struct DoughnutGroup {
first_angle: i64,
hole_size: u32,
uniform_colors: bool,
series: Vec<DoughnutSeries>,
}
struct DoughnutSeries {
series: ChartSeries,
points: PiePoints,
label_position: DataLabelPosition,
}
impl DoughnutGroup {
pub(super) fn read(
reader: &mut PartReader,
node: NodeId,
(series, group_labels): (Vec<NodeId>, Option<NodeId>),
) -> Self {
let first_angle = read_value(reader, node, "firstSliceAng", |v| {
v.parse::<i64>()
.ok()
.filter(|a| (0..=LARGEST_ANGLE).contains(a))
})
.unwrap_or(0);
let hole_size = read_value(reader, node, "holeSize", |v| {
f_office_drawingml::chart_percent(v)
.filter(|&n| (0..PERCENT).contains(&n))
.and_then(|n| u32::try_from(n).ok())
})
.unwrap_or(0);
let uniform_colors = Flag::of(reader.doc, node, "varyColors") == Flag::Off;
let series = series
.into_iter()
.map(|ser| {
let points = points_of(reader, ser);
let label_position = reader
.doc
.child(ser, C, "dLbls")
.or(group_labels)
.map_or(DataLabelPosition::Default, |labels| {
DataLabelPosition::of(reader.doc, labels)
});
let series =
ChartSeries::read(reader, (ser, group_labels), |_, props| Some(props), "val");
DoughnutSeries {
series,
points,
label_position,
}
})
.collect();
Self {
first_angle,
hole_size,
uniform_colors,
series,
}
}
}
const PIE_LABEL_POSITIONS: [DataLabelPosition; 3] = [
DataLabelPosition::Center,
DataLabelPosition::InsideEnd,
DataLabelPosition::OutsideEnd,
];
const DOUGHNUT_LABEL_POSITIONS: [DataLabelPosition; 2] =
[DataLabelPosition::Default, DataLabelPosition::Center];
fn label_place(
labels: &LabelMarkup,
position: DataLabelPosition,
) -> Result<PieLabelPlace, ChartReason> {
if matches!(labels, LabelMarkup::Hidden) {
return Ok(PieLabelPlace::Center);
}
match position {
DataLabelPosition::Center => Ok(PieLabelPlace::Center),
DataLabelPosition::InsideEnd => Ok(PieLabelPlace::InnerEnd),
DataLabelPosition::OutsideEnd => Ok(PieLabelPlace::OuterEnd),
DataLabelPosition::Default | DataLabelPosition::BestFit => Ok(PieLabelPlace::BestFit),
DataLabelPosition::InsideBase
| DataLabelPosition::Top
| DataLabelPosition::Bottom
| DataLabelPosition::Left
| DataLabelPosition::Right
| DataLabelPosition::Other => Err(ChartReason::PieLabels),
}
}
#[derive(Default)]
struct PiePoints {
fills: Vec<PointFill>,
series_explosion: u32,
point_explosions: Vec<(usize, u32)>,
}
fn points_of(reader: &mut PartReader, ser: NodeId) -> PiePoints {
let doc = reader.doc;
let series_explosion = explosion_of(reader, ser).unwrap_or(0);
let mut fills = Vec::new();
let mut point_explosions = Vec::new();
for point in doc.child_elements(ser).filter(|&n| doc.is(n, C, "dPt")) {
let Some(index) = read_value(reader, point, "idx", |v| v.parse::<usize>().ok()) else {
continue;
};
if let Some(explosion) = explosion_of(reader, point) {
point_explosions.push((index, explosion));
}
fills.push(point_fill(doc, point, index));
}
PiePoints {
fills,
series_explosion,
point_explosions,
}
}
pub(super) fn point_fills_of(reader: &mut PartReader, ser: NodeId) -> Vec<PointFill> {
points_of(reader, ser).fills
}
fn point_fill(doc: &f_office_xml::Document, point: NodeId, index: usize) -> PointFill {
let mut warnings = Warnings::new();
let props = doc.child(point, C, "spPr");
let written =
props.is_some_and(|props| FILLS.iter().any(|name| doc.child(props, A, name).is_some()));
let fill = props
.and_then(|props| doc.child(props, A, "solidFill"))
.and_then(|solid| DrawColor::read(doc, solid, &mut warnings));
PointFill {
index,
fill: Warned::new(fill, warnings),
written,
}
}
fn explosion_of(reader: &mut PartReader, node: NodeId) -> Option<u32> {
read_value(reader, node, "explosion", |v| v.parse::<u32>().ok())
}
fn slice_explosions(count: usize, series: u32, points: &[(usize, u32)]) -> Vec<u32> {
let mut slices = vec![series; count];
for &(index, value) in points {
if let Some(slot) = slices.get_mut(index) {
*slot = value;
}
}
slices
}
pub(super) fn part(chart: ChartModel, rules: PlotRules) -> Result<Look<Part>, ChartReason> {
let ChartModel {
groups,
legend,
title,
plot_layout,
data_table,
blanks,
area,
text,
default_style,
..
} = chart;
let Some(Group::Pie(pie)) = groups.into_iter().next() else {
return Err(ChartReason::OtherGroup);
};
if !pie.drawn(rules) {
return Err(ChartReason::OtherGroup);
}
let style_look = rules.draws_style_look() && default_style;
let style = pie.slice_style(style_look);
let first = pie.series.into_iter().next().ok_or(ChartReason::NoSeries)?;
let label_place = label_place(&first.labels, pie.label_position)?;
let mut warnings = Warnings::new();
let values = first.values.drawn((true, blanks), rules)?;
let slices = slice_explosions(values.len(), pie.series_explosion, &pie.point_explosions);
let explosion = rules.pie_explosion(pie.series_explosion, slices)?;
let fills = slice_fills(
first.fill,
pie.point_fills,
(values.len(), style),
&mut warnings,
)?;
let labels = first
.labels
.drawn((&PIE_LABEL_POSITIONS, rules), &text, &mut warnings);
let series = vec![Series {
fill: SeriesFill::Color(fills.first().cloned().ok_or(ChartReason::NoSeries)?),
values,
name: first.name,
labels,
}];
let group = ChartGroup::Pie {
first_angle: pie.first_angle,
view: pie.view,
fills,
labels: label_place,
explosion,
};
radial_part(
RadialFrame {
legend,
title,
plot_layout,
data_table,
area,
text,
},
(series, Some(first.categories), group),
(style_look, rules),
warnings,
)
}
pub(super) fn doughnut_part(
chart: ChartModel,
rules: PlotRules,
) -> Result<Look<Part>, ChartReason> {
let ChartModel {
groups,
legend,
title,
plot_layout,
data_table,
blanks,
area,
text,
default_style,
..
} = chart;
let Some(Group::Doughnut(doughnut)) = groups.into_iter().next() else {
return Err(ChartReason::OtherGroup);
};
let group = rules.doughnut_group(doughnut.first_angle, doughnut.hole_size)?;
if doughnut.series.is_empty() {
return Err(ChartReason::NoSeries);
}
let style_look = rules.draws_style_look() && default_style;
let mut warnings = Warnings::new();
let (series, first_categories) =
doughnut_series(doughnut, (blanks, style_look, rules), &text, &mut warnings)?;
radial_part(
RadialFrame {
legend,
title,
plot_layout,
data_table,
area,
text,
},
(series, first_categories, group),
(style_look, rules),
warnings,
)
}
type CategoryTexts = Option<super::CategoryCache>;
fn doughnut_series(
doughnut: DoughnutGroup,
(blanks, style_look, rules): (super::BlankPoints, bool, PlotRules),
text: &super::ChartText,
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<(Vec<Series>, CategoryTexts), ChartReason> {
let count = doughnut.series.len();
let uniform = doughnut.uniform_colors;
let mut first_categories = None;
let mut drawn = Vec::with_capacity(count);
for (index, ring) in doughnut.series.into_iter().enumerate() {
if ring.points.series_explosion > 0
|| ring.points.point_explosions.iter().any(|&(_, e)| e > 0)
{
return Err(ChartReason::PieExplosion);
}
if !matches!(ring.series.labels, LabelMarkup::Hidden)
&& !DOUGHNUT_LABEL_POSITIONS.contains(&ring.label_position)
{
return Err(ChartReason::PieLabels);
}
let values = ring.series.values.drawn((true, blanks), rules)?;
let style =
doughnut_slice_style(style_look, ring.series.fill_written, uniform, index, count);
let fills = slice_fills(
ring.series.fill,
ring.points.fills,
(values.len(), style),
warnings,
)?;
let labels = ring
.series
.labels
.drawn((&DOUGHNUT_LABEL_POSITIONS, rules), text, warnings);
if index == 0 {
first_categories = Some(ring.series.categories);
}
drawn.push(Series {
fill: SeriesFill::Points(fills),
values,
name: ring.series.name,
labels,
});
}
Ok((drawn, first_categories))
}
const fn doughnut_slice_style(
style_look: bool,
fill_written: bool,
uniform: bool,
index: usize,
count: usize,
) -> SliceStyle {
if !style_look || fill_written {
SliceStyle::Unstyled
} else if uniform {
SliceStyle::BySeries { index, count }
} else {
SliceStyle::ByPoint
}
}
struct RadialFrame {
legend: Option<super::Legend>,
title: super::TitleState,
plot_layout: Option<super::ManualLayout>,
data_table: bool,
area: ElementLook,
text: super::ChartText,
}
fn radial_part(
frame: RadialFrame,
(series, first_categories, group): (Vec<Series>, CategoryTexts, ChartGroup),
(style_look, rules): (bool, PlotRules),
mut warnings: Warnings<DrawingMlWarning>,
) -> Result<Look<Part>, ChartReason> {
let categories = categories_of(&series, frame.data_table)?;
let legend = drawn_legend(frame.legend, &frame.text)?;
let label_size = legend.size;
let title = drawn_title(frame.title, rules, &frame.text, &mut warnings)?;
let plot_place = plot_place(frame.plot_layout.as_ref());
let lines = DrawnLines::of(
frame.area,
(ElementLook::none(), None),
(None, ElementLook::none(), None),
(false, style_look),
&mut warnings,
);
warnings.extend(legend.fill.warnings, std::convert::identity);
let none = || ShapeLook::plain(Geometry::Line, None, None);
let part = Part {
area: lines.area,
columns: Columns {
series,
categories,
group,
title,
legend: legend.place,
legend_box: legend.layout,
label_size,
legend_size: label_size,
value_label_size: label_size,
font: legend.font.clone(),
gridlines: None,
axis: none(),
value_axis: none(),
ticks: lines.ticks,
plot_place,
scale: SetScale::default(),
category_crossing: Some(super::CategoryCrossing::AutoZero),
axis_titles: AxisTitles::NONE,
value_format: None,
category_names: category_names(first_categories, None, categories, rules),
value_label_fill: None,
category_label_fill: None,
legend_font: legend.font,
legend_fill: legend.fill.value,
legend_text: legend.text,
other_labels: false,
axis_forms: super::AxisForms::default(),
},
};
Ok(Warned::new(part, warnings))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SliceStyle {
Unstyled,
ByPoint,
BySeries { index: usize, count: usize },
}
impl SliceStyle {
fn color(self, index: usize, count: usize) -> Result<DrawColor, ChartReason> {
let color = match self {
Self::Unstyled => return Err(ChartReason::SeriesFill),
Self::ByPoint => style_color(index, count),
Self::BySeries {
index: series,
count: total,
} => style_color(series, total),
};
color.ok_or(ChartReason::StyleColors)
}
}
pub(super) fn slice_fills(
own: Look<Option<DrawColor>>,
mut point_fills: Vec<PointFill>,
(count, style): (usize, SliceStyle),
warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Vec<DrawColor>, ChartReason> {
let mut series_warnings = Some(own.warnings);
(0..count)
.map(|index| {
let written = point_fills.iter().any(|p| p.index == index && p.written);
let point = point_fills
.iter()
.position(|p| p.index == index && p.fill.value.is_some())
.map(|at| point_fills.swap_remove(at).fill);
let look = point.unwrap_or_else(|| {
Warned::new(
own.value.clone(),
series_warnings.take().unwrap_or_default(),
)
});
warnings.extend(look.warnings, std::convert::identity);
match look.value {
Some(fill) => Ok(fill),
None if written => Err(ChartReason::SeriesFill),
None => style.color(index, count),
}
})
.collect()
}