use f_office_drawingml::color::{DrawColor, on_white};
use f_office_drawingml::custom::circle_arc;
use f_office_effects::{Angle, Picture, Pie, Scene, Share, Slice};
use f_office_paint::Rgb;
use f_office_paint::{
Image, ImageColor, ImageFormat, ImageItem, InkConversion, Item, Opacity, PathCommand, Point,
};
use f_office_units::scale::{DEGREE, FULL_TURN, PERCENT, QUARTER_TURN};
use f_office_units::{Edges, Length};
use super::labels::data_label_props;
use super::{DrawnText, layout_edges, path, ten_power};
use crate::chart::{
Columns, Decimal, LegendPlace, PieExplosion, PieLabelPlace, PieView, PlotPlace, SeriesFill,
SeriesLabels, Title,
};
use crate::layout::Layout;
use crate::params::{
CHART_LINES_UNTITLED_TOP, CHART_PIE_3D_MARGIN, CHART_PIE_3D_PIXELS_PER_INCH,
CHART_PIE_3D_THICKNESS, CHART_PIE_INNER_END_GAP, CHART_PIE_OUTER_END_ACROSS,
CHART_PIE_OUTER_END_DOWN, CHART_PIE_OUTER_END_SLIDE, CHART_PIE_OUTER_END_WIDTH,
CHART_PIE_OUTSIDE_LABEL_SHARE, CHART_PLOT_RIGHT, CHART_TITLE_TOP,
};
use crate::props::RunProps;
impl Layout<'_> {
pub(super) fn pie(
&mut self,
chart: &Columns,
(first_angle, view, fills, place): (i64, Option<PieView>, &[DrawColor], PieLabelPlace),
explosion: &PieExplosion,
frame: Edges<Length>,
) -> Option<(Vec<Item>, DrawnText)> {
let (plot, legend_plot) = self.pie_plot(chart, frame, view.is_some())?;
let series = chart.series.first()?;
let angles = slice_angles(&series.values, first_angle)?;
let colors = self.slice_colors(fills)?;
let mut items = Vec::with_capacity(angles.len() * 2 + 2);
let labels = if let Some(view) = view {
let shrinks = place.outside() && chart.plot_place == PlotPlace::Automatic;
let picture = PiePicture::of(
picture_plot(plot, shrinks)?,
view,
&angles,
&colors,
&explosion.slices,
)?;
items.push(picture.item());
self.pie_labels(
&series.labels,
&series.values,
&angles,
&explosion.slices,
|bisector, pull, _| {
(place == PieLabelPlace::Center)
.then(|| picture.label_center(bisector, pull))
.flatten()
},
)
} else {
let (center, base_radius) = circle_of(plot, place.outside())?;
let radius = exploded_radius(base_radius, explosion.series)?;
items.extend(pie_slices(
(center, radius),
&angles,
&colors,
&explosion.slices,
)?);
self.pie_labels(
&series.labels,
&series.values,
&angles,
&explosion.slices,
|bisector, pull, size| {
let apex = slice_center(center, radius, bisector, pull)?;
box_center(place, (apex, radius), bisector, size)
},
)
};
let data_labels = labels.map(|labels| items.extend(labels)).is_some();
let (axes_and_legend, extra) = self.radial_chrome(chart, legend_plot, frame);
items.extend(extra);
Some((
items,
DrawnText {
axes_and_legend,
data_labels,
},
))
}
pub(super) fn doughnut(
&mut self,
chart: &Columns,
(first_angle, hole_size): (i64, u32),
frame: Edges<Length>,
) -> Option<(Vec<Item>, DrawnText)> {
let (plot, legend_plot) = self.pie_plot(chart, frame, true)?;
let shrinks = chart.plot_place == PlotPlace::Automatic
&& chart
.series
.iter()
.any(|series| !matches!(series.labels, SeriesLabels::Hidden));
let (center, outer) = circle_of(plot, shrinks)?;
let hole = outer.checked_mul(i64::from(hole_size))?.div_round(PERCENT);
let band = outer - hole;
let rings = i64::try_from(chart.series.len()).ok().filter(|&n| n > 0)?;
let mut items = Vec::with_capacity(chart.categories * chart.series.len() * 2 + 2);
let mut data_labels = true;
for (index, series) in chart.series.iter().enumerate() {
let idx = i64::try_from(index).ok()?;
let r_in = hole + band.checked_mul(idx)?.div_round(rings);
let r_out = hole + band.checked_mul(idx + 1)?.div_round(rings);
let angles = slice_angles(&series.values, first_angle)?;
let SeriesFill::Points(fills) = &series.fill else {
return None;
};
let colors = self.slice_colors(fills)?;
items.extend(doughnut_slices((center, r_in, r_out), &angles, &colors)?);
let zeros = vec![0_u32; angles.len()];
let r_mid = Length::from_units(r_in.units().midpoint(r_out.units()));
let drawn = self.pie_labels(
&series.labels,
&series.values,
&angles,
&zeros,
|bisector, _, _| Some(circle_arc(center, r_mid, [bisector, 0])?.0),
);
if let Some(drawn) = drawn {
items.extend(drawn);
} else {
data_labels = false;
}
}
let (axes_and_legend, extra) = self.radial_chrome(chart, legend_plot, frame);
items.extend(extra);
Some((
items,
DrawnText {
axes_and_legend,
data_labels,
},
))
}
fn radial_chrome(
&mut self,
chart: &Columns,
legend_plot: Edges<Length>,
frame: Edges<Length>,
) -> (bool, Vec<Item>) {
let mut items = Vec::new();
let title = chart.title.as_ref().map_or(Some(()), |title| {
self.chart_title(title, frame)
.map(|lines| items.extend(lines))
});
let legend = chart.legend.map_or(Some(()), |_| {
self.chart_legend(chart, legend_plot, frame)
.map(|legend| items.extend(legend))
});
(title.is_some() && legend.is_some(), items)
}
fn slice_colors(&self, fills: &[DrawColor]) -> Option<Vec<Rgb>> {
let theme = &self.shaper.theme().shapes;
fills
.iter()
.map(|fill| {
let (rgb, alpha) = fill.resolve(&theme.colors)?;
Some(on_white(rgb, alpha))
})
.collect()
}
fn pie_labels(
&mut self,
labels: &SeriesLabels,
values: &[Option<Decimal>],
angles: &[(i64, i64)],
explosions: &[u32],
box_center: impl Fn(i64, u32, (Length, Length)) -> Option<Point>,
) -> Option<Vec<Item>> {
let labels = match labels {
SeriesLabels::Hidden => return Some(Vec::new()),
SeriesLabels::Values(labels) => labels,
SeriesLabels::Other => return None,
};
let props = data_label_props(labels);
let lines = self.lines_of(&props)?;
let color = self.label_color(labels.fill.as_ref());
let insets = labels.insets;
let height = insets.top + lines.single_line + insets.bottom;
let mut items = Vec::with_capacity(values.len());
for ((value, &(start, swing)), &pull) in values.iter().zip(angles).zip(explosions) {
let Some(value) = *value else {
continue;
};
if swing == 0 {
return None;
}
let (text, own) = self.written_text(&props, (&labels.format, value))?;
let room = insets.left + text.width() + insets.right;
let middle = box_center(start + swing / 2, pull, (room, height))?;
let x = middle.x - room.div_toward_zero(2) + insets.left;
let baseline = middle.y - height.div_toward_zero(2) + insets.top + lines.single_top;
items.push(text.item(x, baseline, own.unwrap_or(color))?);
}
Some(items)
}
}
pub(super) fn exploded_radius(base: Length, series: u32) -> Option<Length> {
if series == 0 {
return Some(base);
}
Some(
base.checked_mul(PERCENT)?
.div_round(PERCENT.checked_add(i64::from(series))?),
)
}
pub(super) fn slice_center(
center: Point,
radius: Length,
bisector: i64,
explosion: u32,
) -> Option<Point> {
if explosion == 0 {
return Some(center);
}
let shift = radius.checked_mul(i64::from(explosion))?.div_round(PERCENT);
Some(circle_arc(center, shift, [bisector, 0])?.0)
}
fn pie_slices(
(center, radius): (Point, Length),
angles: &[(i64, i64)],
colors: &[Rgb],
explosions: &[u32],
) -> Option<Vec<Item>> {
let mut items = Vec::with_capacity(angles.len());
for ((&(start, swing), &color), &explosion) in angles.iter().zip(colors).zip(explosions) {
if swing == 0 {
continue;
}
let apex = slice_center(center, radius, start + swing / 2, explosion)?;
let (from, curves) = circle_arc(apex, radius, [start, swing])?;
let mut commands = vec![PathCommand::MoveTo(apex), PathCommand::LineTo(from)];
commands.extend(curves);
commands.push(PathCommand::Close);
items.push(path(commands, color));
}
Some(items)
}
fn doughnut_slices(
(center, inner, outer): (Point, Length, Length),
angles: &[(i64, i64)],
colors: &[Rgb],
) -> Option<Vec<Item>> {
let mut items = Vec::with_capacity(angles.len());
for (&(start, swing), &color) in angles.iter().zip(colors) {
if swing == 0 {
continue;
}
items.push(annular_wedge(
(center, inner, outer),
(start, swing),
color,
)?);
}
Some(items)
}
fn annular_wedge(
(center, inner, outer): (Point, Length, Length),
(start, swing): (i64, i64),
color: Rgb,
) -> Option<Item> {
let (outer_from, outer_curves) = circle_arc(center, outer, [start, swing])?;
if inner <= Length::ZERO {
let mut commands = vec![PathCommand::MoveTo(center), PathCommand::LineTo(outer_from)];
commands.extend(outer_curves);
commands.push(PathCommand::Close);
return Some(path(commands, color));
}
let (inner_end, inner_curves) = circle_arc(center, inner, [start + swing, -swing])?;
let mut commands = vec![PathCommand::MoveTo(outer_from)];
commands.extend(outer_curves);
if swing == FULL_TURN {
commands.push(PathCommand::Close);
commands.push(PathCommand::MoveTo(inner_end));
commands.extend(inner_curves);
commands.push(PathCommand::Close);
} else {
commands.push(PathCommand::LineTo(inner_end));
commands.extend(inner_curves);
commands.push(PathCommand::Close);
}
Some(path(commands, color))
}
pub(super) struct PiePicture {
plot: Edges<Length>,
picture: Picture,
}
impl PiePicture {
pub(super) fn of(
plot: Edges<Length>,
view: PieView,
angles: &[(i64, i64)],
colors: &[Rgb],
explosions: &[u32],
) -> Option<Self> {
let pixels = |side: Length| {
let whole = side
.checked_mul(CHART_PIE_3D_PIXELS_PER_INCH)?
.div_round(Length::UNITS_PER_INCH);
u32::try_from(whole.units())
.ok()
.filter(|&n| n > 0)?
.checked_add(1)
};
let slices = angles
.iter()
.zip(colors)
.zip(explosions)
.filter(|(((_, swing), _), _)| *swing != 0)
.map(|((&(start, swing), color), &explosion)| Slice {
start: Angle::from_sixty_thousandths(start),
swing: Angle::from_sixty_thousandths(swing),
color: [color.r, color.g, color.b],
explosion,
})
.collect();
let scene = Scene::Pie(Pie {
tilt: Angle::from_sixty_thousandths(view.tilt.checked_mul(DEGREE)?),
angle_of_view: Angle::from_sixty_thousandths(view.field_of_view.checked_mul(DEGREE)?),
thickness: Share::ratio(CHART_PIE_3D_THICKNESS.0, CHART_PIE_3D_THICKNESS.1)?,
margin: Share::ratio(CHART_PIE_3D_MARGIN.0, CHART_PIE_3D_MARGIN.1)?,
slices,
});
Some(Self {
plot,
picture: Picture {
width: pixels(plot.right - plot.left)?,
height: pixels(plot.bottom - plot.top)?,
scene,
},
})
}
pub(super) fn item(&self) -> Item {
Item::Image(ImageItem {
x: self.plot.left,
y: self.plot.top,
width: self.plot.right - self.plot.left,
height: self.plot.bottom - self.plot.top,
clip: None,
turn: None,
image: Image {
format: ImageFormat::EffectPicture,
data: self.picture.encode().into(),
opacity: Opacity::FULL,
color: ImageColor::Original,
inks: InkConversion::EmbeddedProfile,
},
})
}
pub(super) fn label_center(&self, bisector: i64, explosion: u32) -> Option<Point> {
let point = self.picture.slice_top_point(
Angle::from_sixty_thousandths(bisector),
Share::ratio(1, 2)?,
explosion,
)?;
let whole = i64::from(Share::ratio(1, 1)?.hundred_thousandths());
let at = |start: Length, side: Length, share: Share| {
Some(
start
+ side
.checked_mul(i64::from(share.hundred_thousandths()))?
.div_round(whole),
)
};
let plot = self.plot;
Some(Point {
x: at(plot.left, plot.right - plot.left, point.across)?,
y: at(plot.top, plot.bottom - plot.top, point.down)?,
})
}
}
pub(super) fn picture_plot(plot: Edges<Length>, shrinks: bool) -> Option<Edges<Length>> {
if !shrinks {
return Some(plot);
}
let shrunk = |low: Length, high: Length| {
let half = (high - low).div_toward_zero(2);
let middle = low + half;
let kept = inside_labels_radius(half).filter(|&kept| kept > Length::ZERO)?;
Some((middle - kept, middle + kept))
};
let (left, right) = shrunk(plot.left, plot.right)?;
let (top, bottom) = shrunk(plot.top, plot.bottom)?;
Some(Edges {
left,
top,
right,
bottom,
})
}
pub(super) fn box_center(
place: PieLabelPlace,
(center, radius): (Point, Length),
bisector: i64,
size: (Length, Length),
) -> Option<Point> {
match place {
PieLabelPlace::Center => {
Some(circle_arc(center, radius.div_toward_zero(2), [bisector, 0])?.0)
}
PieLabelPlace::InnerEnd => inner_end((center, radius), bisector, size),
PieLabelPlace::OuterEnd => outer_end((center, radius), bisector, size),
PieLabelPlace::BestFit => None,
}
}
fn bisector_end(center: Point, radius: Length, bisector: i64) -> Option<(Point, Length, Length)> {
let (end, _) = circle_arc(center, radius, [bisector, 0])?;
Some((end, end.x - center.x, end.y - center.y))
}
fn inner_end(
(center, radius): (Point, Length),
bisector: i64,
(width, height): (Length, Length),
) -> Option<Point> {
let (_, across, down) = bisector_end(center, radius, bisector)?;
let reach = [(width, across), (height, down)]
.into_iter()
.filter(|(_, part)| *part != Length::ZERO)
.map(|(side, part)| {
i128::from(side.units()) * i128::from(radius.units())
/ (i128::from(part.units().abs()) * 2)
})
.min()?;
let (gap, whole) = CHART_PIE_INNER_END_GAP;
let gap = radius.checked_mul(gap)?.div_round(whole);
let reach = Length::from_units(i64::try_from(reach).ok()?);
Some(circle_arc(center, radius - gap - reach, [bisector, 0])?.0)
}
fn outer_end(
(center, radius): (Point, Length),
bisector: i64,
(width, height): (Length, Length),
) -> Option<Point> {
let (end, across, down) = bisector_end(center, radius, bisector)?;
let ((out, whole), (below, of)) = (CHART_PIE_OUTER_END_ACROSS, CHART_PIE_OUTER_END_DOWN);
let (wide, by) = CHART_PIE_OUTER_END_WIDTH;
let half_width = width.checked_mul(wide)?.div_round(by * 2);
let half_height = height.div_toward_zero(2);
let (ax, ay) = (across.units().abs(), down.units().abs());
let (shift_x, shift_y) = if ax >= ay {
(half_width, half_height.checked_mul(ay)?.div_round(ax))
} else {
(outer_end_slide(half_width, ax, ay)?, half_height)
};
Some(Point {
x: end.x
+ across.checked_mul(out)?.div_round(whole)
+ shift_x.checked_mul(across.units().signum())?,
y: end.y
+ down.checked_mul(below)?.div_round(of)
+ shift_y.checked_mul(down.units().signum())?,
})
}
fn outer_end_slide(half_width: Length, ax: i64, ay: i64) -> Option<Length> {
let lean = ax.checked_mul(CHART_PIE_OUTER_END_SLIDE)?;
if lean >= ay {
return Some(half_width);
}
Some(half_width.checked_mul(lean)?.div_round(ay))
}
fn circle_of(plot: Edges<Length>, outside_labels: bool) -> Option<(Point, Length)> {
let (width, height) = (plot.right - plot.left, plot.bottom - plot.top);
if width <= Length::ZERO || height <= Length::ZERO {
return None;
}
let center = Point {
x: plot.left + width.div_toward_zero(2),
y: plot.top + height.div_toward_zero(2),
};
let largest = width.min(height).div_toward_zero(2);
let radius = if outside_labels {
inside_labels_radius(largest).filter(|&radius| radius > Length::ZERO)?
} else {
largest
};
Some((center, radius))
}
pub(super) fn inside_labels_radius(largest: Length) -> Option<Length> {
let (kept, whole) = CHART_PIE_OUTSIDE_LABEL_SHARE;
let with_edge = (largest + CHART_PLOT_RIGHT)
.checked_mul(kept)?
.div_toward_zero(whole);
Some(with_edge - CHART_PLOT_RIGHT)
}
impl Layout<'_> {
pub(super) fn pie_plot(
&mut self,
chart: &Columns,
frame: Edges<Length>,
manual_layout: bool,
) -> Option<(Edges<Length>, Edges<Length>)> {
let automatic = self.automatic_pie_plot(chart, frame)?;
let plot = match chart.plot_place {
PlotPlace::Automatic => automatic,
PlotPlace::Manual(layout) if manual_layout => layout_edges(frame, layout.edges)?,
PlotPlace::Manual(_) | PlotPlace::Other => return None,
};
Some((plot, automatic))
}
fn automatic_pie_plot(
&mut self,
chart: &Columns,
frame: Edges<Length>,
) -> Option<Edges<Length>> {
let top = match &chart.title {
Some(title) => self.pie_title_room(title, frame)?,
None => CHART_LINES_UNTITLED_TOP,
};
let mut plot = Edges {
left: frame.left + CHART_PLOT_RIGHT,
top: frame.top + top,
right: frame.right - CHART_PLOT_RIGHT,
bottom: frame.bottom - CHART_LINES_UNTITLED_TOP,
};
let Some(place) = chart.legend else {
return Some(plot);
};
let lines = self.legend_lines(chart)?;
match place {
LegendPlace::Bottom => plot.bottom -= lines.legend_room()?,
LegendPlace::Top => plot.top += lines.legend_room()?,
LegendPlace::Left => plot.left += self.side_legend(chart, lines)?,
LegendPlace::Right => plot.right -= self.side_legend(chart, lines)?,
}
Some(plot)
}
fn pie_title_room(&mut self, title: &Title, frame: Edges<Length>) -> Option<Length> {
let props = RunProps {
font_ascii: Some(title.font.clone()),
font_hansi: Some(title.font.clone()),
size: Some(title.size),
..RunProps::default()
};
let line = self.line_of(&props)?;
Some(line.checked_mul(self.title_line_count(title, frame)?)? + CHART_TITLE_TOP)
}
}
pub(super) fn slice_angles(
values: &[Option<Decimal>],
first_angle: i64,
) -> Option<Vec<(i64, i64)>> {
let low = values.iter().flatten().map(|value| value.exponent).min()?;
let scaled = values
.iter()
.map(|value| match value {
None => Some(0_i128),
Some(value) => i128::from(value.digits)
.checked_mul(ten_power(value.exponent, low)?)
.filter(|digits| *digits >= 0),
})
.collect::<Option<Vec<_>>>()?;
let total = scaled
.iter()
.try_fold(0_i128, |sum, &value| sum.checked_add(value))?;
if total == 0 {
return None;
}
let first = first_angle.checked_mul(DEGREE)? - QUARTER_TURN;
let (mut sum, mut start) = (0_i128, first);
let mut angles = Vec::with_capacity(scaled.len());
for value in scaled {
sum = sum.checked_add(value)?;
let end = first + i64::try_from(rounded_share(sum, total)?).ok()?;
angles.push((start, end - start));
start = end;
}
Some(angles)
}
fn rounded_share(part: i128, whole: i128) -> Option<i128> {
let turns = part.checked_mul(i128::from(FULL_TURN))?.checked_mul(2)?;
Some((turns / whole + 1) / 2)
}