use f_office_drawingml::color::{DrawColor, on_white};
use f_office_drawingml::gradient::LinearGradient;
use f_office_drawingml::theme::ShapeTheme;
use f_office_paint::{
FillRule, Group, GroupClip, Item, PathCommand, PathItem, Point, Rect, Rgb, stroke,
};
use f_office_units::scale::{PERCENT, TENTHS, THOUSANDTHS};
use f_office_units::{Edges, Length};
use super::{Layout, decisions};
use crate::chart::{
AxisForms, BarStacking, CategoryCrossing, ChartGroup, Columns, Decimal, LabelPiece, LayoutBox,
LayoutCorner, LegendPlace, LineDash, LineLook, Marker, MarkerSymbol, PlotLayout, PlotPlace,
PlotRule, SeriesFill, SeriesLabels, SetScale, StyleWidth, WrittenLabel,
};
use crate::grid::{Device, Rounding};
use crate::params::{
CHART_AXIS_HEADROOM, CHART_AXIS_LABEL_ROOM, CHART_AXIS_STEP_LIMIT, CHART_AXIS_STEPS,
CHART_AXIS_UNITS, CHART_BOTTOM, CHART_BOTTOM_PER_SIZE, CHART_LINES_BAND_ASCENT_PARTS,
CHART_LINES_BOTTOM, CHART_LINES_CATEGORY_TOP_PARTS, CHART_LINES_LABEL_GAP_LINE,
CHART_LINES_LABEL_START, CHART_LINES_LEGEND_PAD, CHART_LINES_LEGEND_ROOM,
CHART_LINES_OUTER_GAP, CHART_LINES_TITLE_LABEL_TOP, CHART_LINES_UNTITLED_LABEL_TOP,
CHART_LINES_UNTITLED_TOP, CHART_LINES_VALUE_BASELINE_DESCENTS,
CHART_LINES_VALUE_BASELINE_PARTS, CHART_PLOT_RIGHT, CHART_STYLE_LINE_STYLES,
CHART_STYLE_MARKER_BASE, CHART_STYLE_MARKER_LINES, CHART_TITLE_LABEL_TOP, CHART_TITLE_TOP,
CHART_TURNED_LABEL_LEFT, CHART_VALUE_LABEL_GAP, CHART_VALUE_LABEL_LEFT, MAX_CHART_LINE_DASHES,
};
use crate::props::RunProps;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Scale {
pub(super) unit: Decimal,
pub(super) steps: i64,
}
impl Scale {
pub(super) fn of(max: Decimal) -> Option<Self> {
if !max.is_positive() {
return None;
}
let need = i128::from(max.digits) * i128::from(CHART_AXIS_HEADROOM);
let exponent = max.exponent;
let magnitude = i32::try_from(need.unsigned_abs().checked_ilog10()?).ok()?;
let first = exponent
.checked_add(magnitude)?
.checked_sub(i32::try_from(THOUSANDTHS.ilog10()).ok()?)?
.checked_sub(TEN_POWERS)?;
(first..first.checked_add(TEN_POWERS * 2)?).find_map(|power| {
CHART_AXIS_UNITS.into_iter().find_map(|multiple| {
let unit = Decimal {
digits: multiple,
exponent: power,
};
let steps = steps_for(need, exponent, unit)?;
(steps <= CHART_AXIS_STEPS).then_some(Self {
unit: unit.normalized(),
steps,
})
})
})
}
pub(super) fn top(self) -> Decimal {
Decimal {
digits: self.unit.digits * self.steps,
exponent: self.unit.exponent,
}
.normalized()
}
}
const TEN_POWERS: i32 = 2;
fn steps_for(need: i128, exponent: i32, unit: Decimal) -> Option<i64> {
let low = exponent.min(unit.exponent);
let numerator = need.checked_mul(ten_power(exponent, low)?)?;
let denominator = i128::from(unit.digits)
.checked_mul(i128::from(THOUSANDTHS))?
.checked_mul(ten_power(unit.exponent, low)?)?;
i64::try_from(numerator.checked_add(denominator - 1)? / denominator).ok()
}
fn ten_power(exponent: i32, low: i32) -> Option<i128> {
i128::from(TENTHS).checked_pow(u32::try_from(exponent - low).ok()?)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ValueAxis {
pub(super) low: Decimal,
pub(super) high: Decimal,
pub(super) unit: Decimal,
pub(super) steps: i64,
pub(super) crossing: Decimal,
}
const HEADROOM_PLACES: u32 = THOUSANDTHS.ilog10();
impl ValueAxis {
pub(super) fn from_zero(chart: &Columns) -> Option<Self> {
let scale = Scale::of(values(chart).max()?)?;
Some(Self {
low: ZERO,
high: scale.top(),
unit: scale.unit,
steps: scale.steps,
crossing: ZERO,
})
}
pub(super) fn of(chart: &Columns) -> Option<Self> {
Self::with_most(chart, CHART_AXIS_STEPS)
}
fn with_most(chart: &Columns, most: i64) -> Option<Self> {
Self::for_chart(chart, most)
}
pub(super) fn for_chart(chart: &Columns, most: i64) -> Option<Self> {
let mut axis = Self::unadjusted_for_chart(chart, most)?;
match chart.category_crossing {
Some(CategoryCrossing::AutoZero) | None => {}
Some(CategoryCrossing::Min) => axis.crossing = axis.low,
Some(CategoryCrossing::At(value)) => axis.crossing = value.clamp(axis.low, axis.high),
}
Some(axis)
}
fn unadjusted_for_chart(chart: &Columns, most: i64) -> Option<Self> {
let is_stacked = |s: Option<BarStacking>| {
matches!(s, Some(BarStacking::Stacked | BarStacking::PercentStacked))
};
let stacked_bars = is_stacked(chart.group.stacking());
let stacked_lines = is_stacked(chart.group.line_stacking());
if !stacked_bars && !stacked_lines {
return Self::over(values(chart), chart.scale, most);
}
let clamp_unit = [chart.group.stacking(), chart.group.line_stacking()]
.contains(&Some(BarStacking::PercentStacked));
let mut combined = axis_bar_values(chart, stacked_bars)?;
combined.extend(axis_line_values(chart, stacked_lines)?);
Self::over_with(combined.into_iter(), chart.scale, most, clamp_unit)
}
pub(super) fn over(
values: impl Iterator<Item = Decimal> + Clone,
set: SetScale,
most: i64,
) -> Option<Self> {
Self::over_with(values, set, most, false)
}
fn over_with(
values: impl Iterator<Item = Decimal> + Clone,
set: SetScale,
most: i64,
clamp_unit: bool,
) -> Option<Self> {
let needs = AxisNeeds::of(values, set, clamp_unit)?;
let (unit, (low, high, units)) = needs.unit_and_ends(most)?;
if units > i128::from(CHART_AXIS_STEP_LIMIT) {
return None;
}
Some(Self {
low: needs.decimal(low)?,
high: needs.decimal(high)?,
unit: needs.decimal(unit)?,
steps: i64::try_from(high.checked_sub(low)?.div_euclid(unit)).ok()?,
crossing: needs.decimal(0_i128.clamp(low, high))?,
})
}
pub(super) fn label(&self, step: i64) -> Option<Decimal> {
let rise = Decimal {
digits: self.unit.digits.checked_mul(step)?,
exponent: self.unit.exponent,
};
sum(self.low, rise)
}
pub(super) fn labels(&self) -> impl Iterator<Item = Decimal> + '_ {
(0..=self.steps).map_while(|step| self.label(step))
}
pub(super) fn along(&self, (from, to): (Length, Length), value: Decimal) -> Option<Length> {
self.along_unclamped((from, to), value.clamp(self.low, self.high))
}
pub(super) fn along_unclamped(
&self,
(from, to): (Length, Length),
value: Decimal,
) -> Option<Length> {
let span = sum(self.high, negated(self.low)?)?;
Some(from + share(to - from, sum(value, negated(self.low)?)?, span)?)
}
}
#[derive(Clone, Copy)]
pub(super) enum Across<'a> {
Bands,
Values(ValueAxis, &'a [Vec<Decimal>]),
}
#[derive(Clone, Copy)]
enum BarDirection {
Up,
Right,
}
impl BarDirection {
fn values(self, plot: Edges<Length>) -> (Length, Length) {
match self {
Self::Up => (plot.bottom, plot.top),
Self::Right => (plot.left, plot.right),
}
}
fn value_ends(self, plot: Edges<Length>) -> (Length, Length) {
match self {
Self::Up => (plot.top, plot.bottom),
Self::Right => (plot.left, plot.right),
}
}
fn run(self, plot: Edges<Length>) -> Length {
match self {
Self::Up => plot.right - plot.left,
Self::Right => plot.bottom - plot.top,
}
}
fn run_ends(self, plot: Edges<Length>) -> (Length, Length) {
match self {
Self::Up => (plot.left, plot.right),
Self::Right => (plot.top, plot.bottom),
}
}
fn at(self, plot: Edges<Length>, offset: Length) -> Length {
match self {
Self::Up => plot.left + offset,
Self::Right => plot.bottom - offset,
}
}
fn part(self, plot: Edges<Length>, offset: Length, length: Length) -> (Length, Length) {
match self {
Self::Up => {
let start = plot.left + offset;
(start, start + length)
}
Self::Right => {
let start = plot.bottom - offset;
(start - length, start)
}
}
}
fn before_run(self, plot: Edges<Length>, length: Length) -> (Length, Length) {
match self {
Self::Up => (plot.left - length, plot.left),
Self::Right => (plot.bottom, plot.bottom + length),
}
}
fn below(self, at: Length, length: Length) -> (Length, Length) {
match self {
Self::Up => (at, at + length),
Self::Right => (at - length, at),
}
}
fn rect(self, run: (Length, Length), values: (Length, Length), color: Rgb) -> Rect {
let (top_left, bottom_right) = self.corners(run, values);
Rect {
x: top_left.x,
y: top_left.y,
width: bottom_right.x - top_left.x,
height: bottom_right.y - top_left.y,
color,
}
}
fn corners(self, run: (Length, Length), values: (Length, Length)) -> (Point, Point) {
let ((x0, x1), (y0, y1)) = match self {
Self::Up => (run, values),
Self::Right => (values, run),
};
(Point { x: x0, y: y0 }, Point { x: x1, y: y1 })
}
}
#[derive(Clone, Copy)]
enum BarPaint<'a> {
Color(Rgb),
Gradient(&'a LinearGradient),
}
fn bar_paint<'a>(fill: &'a SeriesFill, category: i64, theme: &ShapeTheme) -> Option<BarPaint<'a>> {
let color = match fill {
SeriesFill::Color(color) => color,
SeriesFill::Gradient(gradient) => return Some(BarPaint::Gradient(gradient)),
SeriesFill::Points(colors) => colors.get(usize::try_from(category).ok()?)?,
};
let (rgb, alpha) = color.resolve(&theme.colors)?;
Some(BarPaint::Color(on_white(rgb, alpha)))
}
fn bar_paint_item(
direction: BarDirection,
run: (Length, Length),
values: (Length, Length),
(paint, theme): (BarPaint<'_>, &ShapeTheme),
) -> Option<Item> {
match paint {
BarPaint::Color(color) => Some(Item::Rect(direction.rect(run, values, color))),
BarPaint::Gradient(gradient) => gradient
.item(direction.corners(run, values), &theme.colors)
.map(Item::Gradient),
}
}
struct AxisNeeds {
exponent: i32,
low: i128,
high: i128,
set: [Option<i128>; 3],
}
impl AxisNeeds {
fn of(
values: impl Iterator<Item = Decimal> + Clone,
set: SetScale,
clamp_unit: bool,
) -> Option<Self> {
let min_exp = values
.clone()
.chain(set.min)
.chain(set.max)
.chain(set.major_unit)
.map(|d| d.exponent)
.min()?;
let base_exp = if clamp_unit { min_exp.min(0) } else { min_exp };
let exponent = base_exp.checked_sub_unsigned(HEADROOM_PLACES)?;
let count = |d: Decimal| i128::from(d.digits).checked_mul(ten_power(d.exponent, exponent)?);
let counts = values.map(count).collect::<Option<Vec<_>>>()?;
let (low, high) = need_bounds(
*counts.iter().min()?,
*counts.iter().max()?,
(exponent, clamp_unit),
)?;
let set_count = |d: Option<Decimal>| d.map_or(Some(None), |d| count(d).map(Some));
Some(Self {
exponent,
low,
high,
set: [
set_count(set.min)?,
set_count(set.max)?,
set_count(set.major_unit)?,
],
})
}
fn unit_and_ends(&self, most: i64) -> Option<(i128, (i128, i128, i128))> {
if let [_, _, Some(unit)] = self.set {
return Some((unit, self.ends(unit)?));
}
(0_u32..)
.map_while(|power| i128::from(TENTHS).checked_pow(power))
.flat_map(|power| {
CHART_AXIS_UNITS.map(|multiple| power.checked_mul(i128::from(multiple)))
})
.map_while(std::convert::identity)
.find_map(|unit| {
let ends = self.ends(unit)?;
(ends.2 <= i128::from(most)).then_some((unit, ends))
})
}
fn ends(&self, unit: i128) -> Option<(i128, i128, i128)> {
let [set_low, set_high, _] = self.set;
let low = set_low.map_or_else(|| self.low.div_euclid(unit).checked_mul(unit), Some)?;
let high = set_high.map_or_else(
|| low.checked_add(units_up(self.high.checked_sub(low)?, unit)?.checked_mul(unit)?),
Some,
)?;
let units = units_up(high.checked_sub(low)?, unit)?;
(high > low).then_some((low, high, units))
}
fn decimal(&self, digits: i128) -> Option<Decimal> {
let ten = i128::from(TENTHS);
let (mut digits, mut exponent) = (digits, self.exponent);
while digits != 0 && digits % ten == 0 {
digits /= ten;
exponent = exponent.checked_add(1)?;
}
Some(
Decimal {
digits: i64::try_from(digits).ok()?,
exponent,
}
.normalized(),
)
}
}
fn room_units(height: Length, line: Length) -> i64 {
if line <= Length::ZERO {
return CHART_AXIS_STEPS;
}
(height - CHART_AXIS_LABEL_ROOM)
.units()
.div_euclid(line.units())
.clamp(1, CHART_AXIS_STEPS)
}
fn units_up(span: i128, unit: i128) -> Option<i128> {
Some(span.checked_add(unit.checked_sub(1)?)?.div_euclid(unit))
}
fn headroom(span: i128) -> Option<i128> {
Some(span.checked_mul(i128::from(CHART_AXIS_HEADROOM - THOUSANDTHS))? / i128::from(THOUSANDTHS))
}
fn need_bounds(
least: i128,
most: i128,
(exponent, clamp_unit): (i32, bool),
) -> Option<(i128, i128)> {
let (low, high) = (low_need(least, most)?, high_need(most, least)?);
if !clamp_unit {
return Some((low, high));
}
let one = ten_power(0, exponent)?;
Some((low.max(-one), high.min(one)))
}
fn high_need(most: i128, least: i128) -> Option<i128> {
if most > 0 {
most.checked_add(headroom(most.checked_sub(least.min(0))?)?)
} else {
Some(0)
}
}
fn low_need(least: i128, most: i128) -> Option<i128> {
if least < 0 {
least.checked_sub(headroom(most.max(0).checked_sub(least)?)?)
} else {
Some(0)
}
}
const ZERO: Decimal = Decimal {
digits: 0,
exponent: 0,
};
fn values(chart: &Columns) -> impl Iterator<Item = Decimal> + Clone + '_ {
chart
.series
.iter()
.flat_map(|s| s.values.iter().copied().flatten())
}
fn axis_bar_values(chart: &Columns, stacked: bool) -> Option<Vec<Decimal>> {
if stacked {
return Some(bars::stacked_segments(chart)?.outer_ends().collect());
}
Some(
chart
.bar_series()
.iter()
.flat_map(|s| s.values.iter().copied().flatten())
.collect(),
)
}
fn axis_line_values(chart: &Columns, stacked: bool) -> Option<Vec<Decimal>> {
if stacked {
return Some(
bars::stacked_line_values(chart)?
.into_iter()
.flatten()
.flatten()
.collect(),
);
}
Some(
chart
.line_series()
.iter()
.flat_map(|s| s.values.iter().copied().flatten())
.collect(),
)
}
pub(super) fn sum(a: Decimal, b: Decimal) -> Option<Decimal> {
let low = a.exponent.min(b.exponent);
let wide = |d: Decimal| i128::from(d.digits).checked_mul(ten_power(d.exponent, low)?);
let total = wide(a)?.checked_add(wide(b)?)?;
let (digits, exponent) = within_digits(total, low)?;
Some(Decimal { digits, exponent }.normalized())
}
fn within_digits(digits: i128, exponent: i32) -> Option<(i64, i32)> {
let fits = |drop: u32| {
i128::from(TENTHS)
.checked_pow(drop)
.and_then(|power| digits.checked_div(power))
.is_some_and(|kept| i64::try_from(kept).is_ok())
};
let drop = (0..=u32::MAX).find(|&drop| fits(drop))?;
let power = i128::from(TENTHS).checked_pow(drop)?;
let rest = digits.checked_rem(power)?.checked_abs()?;
let away = if rest.checked_mul(2)? >= power {
digits.signum()
} else {
0
};
let kept = digits.checked_div(power)?.checked_add(away)?;
Some((
i64::try_from(kept).ok()?,
exponent.checked_add(i32::try_from(drop).ok()?)?,
))
}
fn negated(value: Decimal) -> Option<Decimal> {
Some(Decimal {
digits: value.digits.checked_neg()?,
exponent: value.exponent,
})
}
fn share(length: Length, value: Decimal, whole: Decimal) -> Option<Length> {
let low = value.exponent.min(whole.exponent);
let numerator = i128::from(length.units())
.checked_mul(i128::from(value.digits))?
.checked_mul(ten_power(value.exponent, low)?)?;
let denominator = i128::from(whole.digits).checked_mul(ten_power(whole.exponent, low)?)?;
i64::try_from(numerator.checked_div(denominator)?)
.ok()
.map(Length::from_units)
}
fn path(commands: Vec<PathCommand>, color: Rgb) -> Item {
Item::Path(PathItem {
commands,
color,
fill_rule: FillRule::NonZero,
})
}
fn line_width(width: StyleWidth, theme: &ShapeTheme, styles: i64) -> Option<Length> {
match width {
StyleWidth::Set(width) => Some(width),
StyleWidth::Automatic => theme.line_width(1)?.checked_mul(styles),
}
}
fn line_runs_items(
look: &LineLook,
points: &[Option<(Point, Point)>],
width: Option<Length>,
(color, clip): (Rgb, Option<&GroupClip>),
) -> Option<Vec<Item>> {
let mut items = Vec::new();
for run in points.split(Option::is_none) {
let drawn: Vec<Point> = run
.iter()
.filter_map(|point| point.map(|(drawn, _)| drawn))
.collect();
if drawn.len() >= 2 {
items.extend(line_item(look, drawn, width, (color, clip))?);
}
}
Some(items)
}
fn line_item(
look: &LineLook,
points: Vec<Point>,
width: Option<Length>,
(color, clip): (Rgb, Option<&GroupClip>),
) -> Option<Vec<Item>> {
let Some(width) = width else {
return Some(Vec::new());
};
let points = smooth::form_points(look.form, points);
let line = path(line_commands(&points, width, look.dash)?, color);
Some(vec![match clip {
Some(clip) => Item::Group(Group::of_page(vec![line], clip.clone())),
None => line,
}])
}
fn line_commands(
points: &[Point],
width: Length,
dash: Option<LineDash>,
) -> Option<Vec<PathCommand>> {
let half = width.div_toward_zero(2);
match dash {
None => Some(stroke::round_line(points, half)),
Some(dash) => stroke::round_dashes(
points,
half,
&dash_lengths(dash, width)?,
MAX_CHART_LINE_DASHES,
),
}
}
fn dash_lengths(dash: LineDash, width: Length) -> Option<Vec<Length>> {
(0..)
.zip(dash.pattern())
.map(|(index, &widths)| {
let length = width.checked_mul(widths)?;
if index % 2 == 0 {
length.checked_sub(width)
} else {
length.checked_add(width)
}
})
.collect()
}
fn marker_size(marker: &Marker, theme: &ShapeTheme) -> Option<Length> {
if let Some(size) = marker.size {
return Some(size);
}
let size = Length::from_points(CHART_STYLE_MARKER_BASE)?
+ theme.line_width(1)?.checked_mul(CHART_STYLE_MARKER_LINES)?;
Length::from_points(size.units() / Length::UNITS_PER_POINT)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MarkerPart {
Whole,
Even,
Lines,
}
fn marker_span(
device: &Device,
part: MarkerPart,
size: Length,
odd_outline: bool,
(point, after): (Length, bool),
) -> (Length, Length) {
let whole = device.count(size, Rounding::HalfUp);
let half_dot = device.dots(1).div_toward_zero(2);
let middle = match (odd_outline, after) {
(false, _) => device.snap(point),
(true, true) => device.dots(device.count(point, Rounding::Down)) + half_dot,
(true, false) => device.dots(device.count(point, Rounding::Up)) - half_dot,
};
let odd = i64::from(odd_outline);
let even = whole.div_euclid(2);
let (reach, length) = match part {
MarkerPart::Whole => (
device.dots(device.count(size.div_toward_zero(2), Rounding::HalfUp)),
device.dots(whole - odd),
),
MarkerPart::Even => (device.dots(even), device.dots(even * 2)),
MarkerPart::Lines => (
device.dots(even) + if odd_outline { half_dot } else { Length::ZERO },
device.dots(even * 2 + odd),
),
};
(middle - reach, length)
}
fn marker_items(
marker: &Marker,
point: Point,
series: (&DrawColor, Rgb),
theme: &ShapeTheme,
device: &Device,
) -> Vec<Item> {
let resolved = |color: &Option<DrawColor>| match color {
Some(color) => color
.resolve(&theme.colors)
.map(|(rgb, alpha)| on_white(rgb, alpha)),
None => Some(series.1),
};
let outline = match &marker.outline {
Some(outline) => match (
resolved(&outline.color),
line_width(outline.width, theme, 1),
) {
(Some(color), Some(width)) => Some((color, width)),
_ => return Vec::new(),
},
None => None,
};
let (Some(size), Some(fill)) = (marker_size(marker, theme), resolved(&marker.fill)) else {
return Vec::new();
};
let width = outline.map_or(Length::ZERO, |(_, width)| width);
let w = width.div_toward_zero(2);
let edge = outline.map(|(color, _)| (color, w));
let odd_outline = device.count(width, Rounding::HalfUp).rem_euclid(2) == 1;
let span = |part: MarkerPart| {
let (left, across) = marker_span(device, part, size, odd_outline, (point.x, true));
let (top, down) = marker_span(device, part, size, odd_outline, (point.y, false));
(
Point { x: left, y: top },
Point {
x: left + across,
y: top + down,
},
)
};
let middle = |(a, b): (Point, Point)| Point {
x: a.x + (b.x - a.x).div_toward_zero(2),
y: a.y + (b.y - a.y).div_toward_zero(2),
};
let square =
|(a, b): (Point, Point)| vec![a, Point { x: b.x, y: a.y }, b, Point { x: a.x, y: b.y }];
let corners = match marker.symbol {
MarkerSymbol::Circle => {
let (a, b) = span(MarkerPart::Whole);
let (center, r) = (middle((a, b)), (b.x - a.x).div_toward_zero(2));
return circle_items(center, r, fill, edge);
}
MarkerSymbol::X | MarkerSymbol::Star => {
let mut items = if marker.fill.is_some() {
outlined(&square(span(MarkerPart::Even)), fill, edge)
} else {
Vec::new()
};
let Some((color, _)) = outline else {
return items;
};
let (a, b) = span(MarkerPart::Lines);
let mut strokes = vec![(a, b), (Point { x: a.x, y: b.y }, Point { x: b.x, y: a.y })];
if marker.symbol == MarkerSymbol::Star {
let x = middle((a, b)).x;
strokes.push((Point { x, y: a.y }, Point { x, y: b.y }));
}
let commands = strokes
.into_iter()
.filter_map(|(from, to)| stroke::band(from, to, w))
.flatten()
.collect();
items.push(path(commands, color));
return items;
}
MarkerSymbol::Square => square(span(MarkerPart::Whole)),
MarkerSymbol::Diamond => {
let (a, b) = span(MarkerPart::Even);
let m = middle((a, b));
vec![
Point { x: m.x, y: a.y },
Point { x: b.x, y: m.y },
Point { x: m.x, y: b.y },
Point { x: a.x, y: m.y },
]
}
MarkerSymbol::Triangle => {
let (a, b) = span(MarkerPart::Even);
vec![
Point {
x: middle((a, b)).x,
y: a.y,
},
b,
Point { x: a.x, y: b.y },
]
}
};
outlined(&corners, fill, edge)
}
fn circle_items(center: Point, r: Length, fill: Rgb, edge: Option<(Rgb, Length)>) -> Vec<Item> {
let Some((color, w)) = edge else {
return vec![path(stroke::disc(center, r).to_vec(), fill)];
};
if fill == color {
return vec![path(stroke::disc(center, r + w).to_vec(), fill)];
}
let mut ring = stroke::disc(center, r + w).to_vec();
ring.extend(stroke::disc(center, r - w));
vec![
path(stroke::disc(center, r).to_vec(), fill),
Item::Path(PathItem {
commands: ring,
color,
fill_rule: FillRule::EvenOdd,
}),
]
}
fn outlined(corners: &[Point], fill: Rgb, edge: Option<(Rgb, Length)>) -> Vec<Item> {
let mut shape: Vec<PathCommand> = corners
.iter()
.enumerate()
.map(|(index, &corner)| {
if index == 0 {
PathCommand::MoveTo(corner)
} else {
PathCommand::LineTo(corner)
}
})
.collect();
shape.push(PathCommand::Close);
let mut items = vec![path(shape, fill)];
if let Some((color, half)) = edge {
items.push(path(stroke::round_outline(corners, half), color));
}
items
}
struct Clusters {
gap: i64,
overlap: i64,
categories: i64,
span: Length,
parts: i64,
thickness: Length,
}
impl Clusters {
fn of(chart: &Columns, (gap, overlap): (i64, i64), span: Length) -> Option<Self> {
let series = i64::try_from(chart.bar_series().len()).ok()?;
let categories = i64::try_from(chart.categories).ok()?;
let overlaps = (series - 1).checked_mul(overlap)?;
let band = (PERCENT * series).checked_sub(overlaps)?.checked_add(gap)?;
let parts = categories.checked_mul(band).filter(|&parts| parts > 0)?;
let thickness = span.checked_mul(PERCENT)?.div_toward_zero(parts);
Some(Self {
gap,
overlap,
categories,
span,
parts,
thickness,
})
}
fn start(&self, (category, index): (i64, i64)) -> Option<Length> {
let band = self
.span
.checked_mul(category)?
.div_toward_zero(self.categories);
let gap = self
.span
.checked_mul(self.gap)?
.div_toward_zero(self.parts.checked_mul(2)?);
let beside = self
.span
.checked_mul(index)?
.checked_mul(PERCENT.checked_sub(self.overlap)?)?
.div_toward_zero(self.parts);
Some(band + gap + beside)
}
}
fn holds_all_data_labels(chart: &Columns, drawn: bool) -> bool {
let shows_values = chart
.series
.iter()
.any(|series| matches!(series.labels, SeriesLabels::Values(_)));
!chart.other_labels && (drawn || !shows_values)
}
#[derive(Clone, Copy)]
struct LabelLines {
size: Length,
line: Length,
top: Length,
single_top: Length,
single_line: Length,
}
impl LabelLines {
fn top_part(self) -> Length {
self.top.div_toward_zero(CHART_LINES_BAND_ASCENT_PARTS)
}
fn band(self) -> Length {
self.line + self.top_part()
}
fn of_line(self, per_thousand: i64) -> Option<Length> {
Some(
self.line
.checked_mul(per_thousand)?
.div_toward_zero(THOUSANDTHS),
)
}
fn legend_room(self) -> Option<Length> {
Some(CHART_LINES_LEGEND_PAD + self.of_line(CHART_LINES_LEGEND_ROOM)?)
}
fn untitled_edge(self) -> Length {
CHART_LINES_UNTITLED_TOP.max(CHART_LINES_UNTITLED_LABEL_TOP + self.line.div_toward_zero(2))
}
fn label_gap(self) -> Option<Length> {
Some(self.of_line(CHART_LINES_LABEL_GAP_LINE)? + self.top_part())
}
fn value_baseline(self) -> Option<Length> {
let descents = (self.line - self.top).checked_mul(CHART_LINES_VALUE_BASELINE_DESCENTS)?;
Some((self.size + self.top - descents).div_toward_zero(CHART_LINES_VALUE_BASELINE_PARTS))
}
fn category_baseline(self) -> Option<Length> {
Some(
self.top
+ self
.top_part()
.checked_mul(CHART_LINES_CATEGORY_TOP_PARTS)?,
)
}
}
#[derive(Clone, Copy)]
struct SideLines {
left: LabelLines,
below: LabelLines,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct DrawnText {
pub(super) axes_and_legend: bool,
pub(super) data_labels: bool,
}
enum SpecialLayout {
Handled(Option<(Vec<Item>, DrawnText)>),
Standard,
}
impl Layout<'_> {
pub(super) fn columns(
&mut self,
chart: &Columns,
frame: Edges<Length>,
) -> Option<(Vec<Item>, DrawnText)> {
let rule = decisions::chart_plot_rule(&self.context.quirks, chart)?;
if let SpecialLayout::Handled(result) = self.special_chart_group(chart, rule, frame) {
return result;
}
let (axis, mut plot) = match rule {
PlotRule::DefaultChart => {
let axis = ValueAxis::from_zero(chart)?;
(axis, self.default_plot(chart, &axis, frame)?)
}
PlotRule::FontLines => {
let axis = ValueAxis::of(chart)?;
let plot = self.font_line_plot(chart, &axis, frame)?;
self.roomed_axis(chart, (axis, plot), frame)?
}
};
let twin = plot;
let across = self.axis_across(chart, frame, &mut plot)?;
if plot.right <= plot.left
|| plot.bottom <= plot.top
|| Self::flips_top_labels(chart, &axis)
{
return None;
}
let up = BarDirection::Up;
let mut items = self.gridlines(chart, (&axis, up), plot);
let crossing = self.place(&axis, up.values(plot), axis.crossing)?;
let (group, data_labels) = self.group_and_axes(chart, (&axis, across), plot, crossing)?;
items.extend(group);
items.extend(self.ticks_across(chart, across, plot, crossing));
let all_data_labels = holds_all_data_labels(chart, data_labels.is_some());
items.extend(data_labels.into_iter().flatten());
let axes_and_legend = rule == PlotRule::FontLines
&& self.chart_texts(
chart,
(&axis, across, plot, crossing),
(twin, frame),
&mut items,
);
Some((
items,
DrawnText {
axes_and_legend,
data_labels: all_data_labels,
},
))
}
fn flips_top_labels(chart: &Columns, axis: &ValueAxis) -> bool {
axis.crossing == axis.high
&& !chart.axis_forms.low_labels
&& !matches!(chart.group, ChartGroup::Scatter { .. })
}
fn special_chart_group(
&mut self,
chart: &Columns,
rule: PlotRule,
frame: Edges<Length>,
) -> SpecialLayout {
let allowed = rule == PlotRule::FontLines;
match &chart.group {
ChartGroup::Pie {
first_angle,
view,
fills,
labels,
explosion,
} => SpecialLayout::Handled(
allowed
.then(|| {
self.pie(
chart,
(*first_angle, *view, fills, *labels),
explosion,
frame,
)
})
.flatten(),
),
ChartGroup::Doughnut {
first_angle,
hole_size,
} => SpecialLayout::Handled(
allowed
.then(|| self.doughnut(chart, (*first_angle, *hole_size), frame))
.flatten(),
),
ChartGroup::Bars { gap, overlap, .. } => SpecialLayout::Handled(
allowed
.then(|| self.horizontal_bars(chart, (*gap, *overlap), frame))
.flatten(),
),
ChartGroup::Columns { .. }
| ChartGroup::Lines { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Combo { .. } => SpecialLayout::Standard,
}
}
fn group_and_axes(
&mut self,
chart: &Columns,
(axis, across): (&ValueAxis, Across<'_>),
plot: Edges<Length>,
crossing: Length,
) -> Option<(Vec<Item>, Option<Vec<Item>>)> {
let axis_line = self.chart_rule(&chart.axis, (plot.left, plot.right), crossing);
let mut items = Vec::new();
match &chart.group {
ChartGroup::Columns { gap, overlap, .. } => {
let up = (axis, BarDirection::Up);
items.extend(self.bars(chart, (*gap, *overlap), up, (plot, crossing)));
let context = self.context;
let data_labels = decisions::chart_data_labels(&context.quirks, || {
self.data_labels(chart, (*gap, *overlap), up, plot)
});
items.extend(self.value_axis(chart, (axis, BarDirection::Up), plot));
items.extend(axis_line);
Some((items, data_labels))
}
ChartGroup::Bars { .. } | ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => {
Some((Vec::new(), None))
}
ChartGroup::Lines { looks, .. } => {
let lines = self.series_lines(chart, looks, (axis, across), plot)?;
self.append_lines_and_axes(chart, axis, plot, (lines, axis_line), &mut items);
let context = self.context;
let data_labels = decisions::chart_data_labels(&context.quirks, || {
self.line_data_labels(chart, looks, axis, plot)
});
Some((items, data_labels))
}
ChartGroup::Scatter { looks, .. } => {
let lines = self.series_lines(chart, looks, (axis, across), plot)?;
self.append_lines_and_axes(chart, axis, plot, (lines, axis_line), &mut items);
Some((items, None))
}
ChartGroup::Combo {
gap,
overlap,
looks,
..
} => {
let up = (axis, BarDirection::Up);
items.extend(self.bars(chart, (*gap, *overlap), up, (plot, crossing)));
let context = self.context;
let data_labels = decisions::chart_data_labels(&context.quirks, || {
let mut all = self.data_labels(chart, (*gap, *overlap), up, plot)?;
all.extend(self.line_data_labels(chart, looks, axis, plot)?);
Some(all)
});
let lines = self.series_lines(chart, looks, (axis, across), plot)?;
self.append_lines_and_axes(chart, axis, plot, (lines, axis_line), &mut items);
Some((items, data_labels))
}
}
}
fn append_lines_and_axes(
&mut self,
chart: &Columns,
axis: &ValueAxis,
plot: Edges<Length>,
(lines, axis_line): (Vec<Item>, Vec<Item>),
items: &mut Vec<Item>,
) {
if decisions::chart_axis_before_lines(&self.context.quirks) {
items.extend(axis_line);
items.extend(lines);
items.extend(self.value_axis(chart, (axis, BarDirection::Up), plot));
} else {
items.extend(lines);
items.extend(self.value_axis(chart, (axis, BarDirection::Up), plot));
items.extend(axis_line);
}
}
fn axis_across<'a>(
&mut self,
chart: &'a Columns,
frame: Edges<Length>,
plot: &mut Edges<Length>,
) -> Option<Across<'a>> {
match &chart.group {
ChartGroup::Scatter {
x_values, x_scale, ..
} => {
let (x_axis, right) = self.x_axis(chart, (x_values, *x_scale), (frame, *plot))?;
plot.right = right;
Some(Across::Values(x_axis, x_values))
}
ChartGroup::Columns { .. } | ChartGroup::Lines { .. } | ChartGroup::Combo { .. } => {
Some(Across::Bands)
}
ChartGroup::Bars { .. } | ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => None,
}
}
fn default_plot(
&mut self,
chart: &Columns,
axis: &ValueAxis,
frame: Edges<Length>,
) -> Option<Edges<Length>> {
if chart.axis_forms != AxisForms::default() {
return None;
}
let title = chart.title.as_ref()?;
let size = Length::from_half_points(chart.label_size)?;
let value_size = Length::from_half_points(chart.value_label_size)?;
let widest = self.widest_label(chart, axis)?;
let left = frame.left
+ CHART_VALUE_LABEL_LEFT
+ widest
+ value_size
.checked_mul(CHART_VALUE_LABEL_GAP)?
.div_toward_zero(THOUSANDTHS);
let right = frame.right - CHART_PLOT_RIGHT;
let title_lines = self.title_line_count(title, frame)?;
let below_title = CHART_TITLE_TOP
+ self
.chart_line(chart, title.size)?
.checked_mul(title_lines)?;
let below_label = CHART_TITLE_LABEL_TOP
+ self
.chart_line(chart, chart.value_label_size)?
.div_toward_zero(2);
let top = frame.top + below_title.max(below_label);
let bottom = frame.bottom
- (CHART_BOTTOM
+ size
.checked_mul(CHART_BOTTOM_PER_SIZE)?
.div_toward_zero(THOUSANDTHS));
Some(Edges {
left,
top,
right,
bottom,
})
}
fn roomed_axis(
&mut self,
chart: &Columns,
fitted: (ValueAxis, Edges<Length>),
frame: Edges<Length>,
) -> Option<(ValueAxis, Edges<Length>)> {
let context = self.context;
decisions::chart_axis_room(&context.quirks, fitted, |fitted| {
let (axis, plot) = fitted;
let line = self.chart_line(chart, chart.value_label_size)?;
let most = room_units(plot.bottom - plot.top, line);
if axis.steps <= most {
return Some(fitted);
}
let axis = ValueAxis::with_most(chart, most)?;
let plot = self.font_line_plot(chart, &axis, frame)?;
Some((axis, plot))
})
}
fn font_line_plot(
&mut self,
chart: &Columns,
axis: &ValueAxis,
frame: Edges<Length>,
) -> Option<Edges<Length>> {
let widest = if chart.axis_forms.value_deleted {
None
} else {
Some(self.widest_label(chart, axis)?)
};
let labels_below = !chart.axis_forms.category_hidden
&& (axis.crossing == axis.low || chart.axis_forms.low_labels);
self.label_plot(chart, widest, labels_below, frame)
}
fn label_plot(
&mut self,
chart: &Columns,
widest: Option<Length>,
labels_below: bool,
frame: Edges<Length>,
) -> Option<Edges<Length>> {
let lines = self.label_lines(chart)?;
let sides = self.plot_side_lines(chart, lines)?;
let labels = match widest {
Some(widest) => Some(widest + sides.left.label_gap()?),
None => None,
};
if let PlotPlace::Manual(layout) = chart.plot_place {
let labels = labels.or_else(|| layout.inner.then_some(Length::ZERO))?;
return manual_plot(layout, frame, labels, sides);
}
let title_room = self.title_room(chart, sides.left, frame)?;
let (value_title, category_title) = self.axis_title_rooms(chart)?;
let left = labels.map_or(frame.left + CHART_PLOT_RIGHT, |labels| {
frame.left + CHART_LINES_LABEL_START + labels
}) + value_title;
let right = frame.right - CHART_PLOT_RIGHT;
let (left, bottom_room) = if labels_below {
self.below_room(chart, (left, right), frame, sides.below)?
} else {
(left, lines.legend_room()? + sides.left.untitled_edge())
};
let plot = Edges {
left,
top: frame.top + title_room,
right,
bottom: frame.bottom - bottom_room - category_title,
};
self.with_legend(chart, lines, plot)
}
fn below_room(
&mut self,
chart: &Columns,
(left, right): (Length, Length),
frame: Edges<Length>,
below: LabelLines,
) -> Option<(Length, Length)> {
let form = self.below_form(chart, right - left, frame);
let room = form
.as_ref()
.map_or(Some(Length::ZERO), |form| form.room(below))?;
let reach = form.and_then(|form| form.left_reach(right - frame.left));
let left = reach.map_or(left, |reach| {
left.max(frame.left + CHART_TURNED_LABEL_LEFT + reach)
});
Some((left, self.below_base(chart)? + room))
}
fn below_base(&mut self, chart: &Columns) -> Option<Length> {
let lines = self.label_lines(chart)?;
let sides = self.plot_side_lines(chart, lines)?;
Some(CHART_LINES_BOTTOM + sides.below.band() + sides.below.top_part() + lines.line)
}
fn title_room(
&mut self,
chart: &Columns,
left: LabelLines,
frame: Edges<Length>,
) -> Option<Length> {
let Some(title) = &chart.title else {
return Some(left.untitled_edge());
};
let half_line = left.line.div_toward_zero(2);
Some(
self.chart_line(chart, title.size)?
.checked_mul(self.title_line_count(title, frame)?)?
+ CHART_TITLE_TOP.max(CHART_LINES_TITLE_LABEL_TOP + half_line),
)
}
fn with_legend(
&mut self,
chart: &Columns,
lines: LabelLines,
mut plot: Edges<Length>,
) -> Option<Edges<Length>> {
plot.bottom -= self.legend_bottom(chart, lines)?;
let legend = match chart.legend {
Some(_) => self.legend_lines(chart)?,
None => lines,
};
match chart.legend {
Some(LegendPlace::Top) => plot.top += legend.legend_room()?,
Some(LegendPlace::Left) => plot.left += self.side_legend(chart, legend)?,
Some(LegendPlace::Right) => plot.right -= self.side_legend(chart, legend)?,
Some(LegendPlace::Bottom) | None => {}
}
Some(plot)
}
fn legend_bottom(&mut self, chart: &Columns, lines: LabelLines) -> Option<Length> {
let room = lines.legend_room()?;
if chart.legend == Some(LegendPlace::Bottom) {
Some(self.legend_lines(chart)?.legend_room()? - room)
} else {
Some(Length::ZERO - room)
}
}
fn side_legend(&mut self, chart: &Columns, lines: LabelLines) -> Option<Length> {
let names: Vec<&str> = legend::legend_entries(chart)
.into_iter()
.map(|(name, _)| name)
.collect::<Option<_>>()?;
let props = legend_props(chart);
let widest = names
.into_iter()
.map(|name| self.text_width(&props, name))
.max()?;
Some(widest + CHART_LINES_LEGEND_PAD + legend::Keys::of(chart).side_room(lines)?)
}
pub(super) fn left_labels_room(&mut self, chart: &Columns, axis: &ValueAxis) -> Option<Length> {
let lines = self.label_lines(chart)?;
let sides = self.plot_side_lines(chart, lines)?;
let widest = match chart.group {
ChartGroup::Bars { .. } if chart.axis_forms.category_hidden => None,
ChartGroup::Bars { .. } => self.widest_category(chart),
_ if chart.axis_forms.value_deleted => None,
_ => self.widest_label(chart, axis),
};
match widest {
Some(widest) => Some(widest + sides.left.label_gap()?),
None => Some(Length::ZERO),
}
}
pub(super) fn below_labels_room(
&mut self,
chart: &Columns,
axis: &ValueAxis,
plot: Edges<Length>,
frame: Edges<Length>,
) -> Option<Length> {
let lines = self.label_lines(chart)?;
let sides = self.plot_side_lines(chart, lines)?;
let labels_below = match chart.group {
ChartGroup::Bars { .. } => !chart.axis_forms.value_deleted,
_ => {
!chart.axis_forms.category_hidden
&& (axis.crossing == axis.low || chart.axis_forms.low_labels)
}
};
if labels_below {
let (_, room) = self.below_room(chart, (plot.left, plot.right), frame, sides.below)?;
Some(room - lines.legend_room()?)
} else {
Some(sides.left.untitled_edge())
}
}
fn widest_label(&mut self, chart: &Columns, axis: &ValueAxis) -> Option<Length> {
let props = chart_props(chart, chart.value_label_size);
let format = chart.value_format.as_ref()?;
let widths = axis
.labels()
.map(|value| Some(self.written_width(&props, &format.write(value)?)))
.collect::<Option<Vec<_>>>()?;
widths.into_iter().max()
}
fn written_width(&mut self, props: &RunProps, written: &WrittenLabel) -> Length {
let mut text = String::new();
let mut blanks = Length::ZERO;
for piece in &written.pieces {
match piece {
LabelPiece::Text(own) => text.push_str(own),
LabelPiece::Blank(_) => blanks += self.text_width(props, " "),
}
}
self.text_width(props, &text) + blanks
}
fn place(
&self,
axis: &ValueAxis,
(from, to): (Length, Length),
value: Decimal,
) -> Option<Length> {
let exact = axis.along((from, to), value)?;
Some(if value == axis.low || value == axis.high {
exact
} else {
self.device.snap(exact)
})
}
fn place_unclamped(
&self,
axis: &ValueAxis,
(from, to): (Length, Length),
value: Decimal,
) -> Option<Length> {
let exact = axis.along_unclamped((from, to), value)?;
Some(if value == axis.low || value == axis.high {
exact
} else {
self.device.snap(exact)
})
}
fn bars(
&self,
chart: &Columns,
(gap, overlap): (i64, i64),
(axis, direction): (&ValueAxis, BarDirection),
(plot, crossing): (Edges<Length>, Length),
) -> Vec<Item> {
let theme = &self.shaper.theme().shapes;
let (Some(clusters), Some(spans)) = (
Clusters::of(chart, (gap, overlap), direction.run(plot)),
bars::BarSpans::of(chart),
) else {
return Vec::new();
};
let mut items = Vec::new();
for (index, one) in (0_i64..).zip(chart.bar_series()) {
for (category, value) in (0_i64..).zip(&one.values) {
let (Some(value), Some(paint)) = (*value, bar_paint(&one.fill, category, theme))
else {
continue;
};
if let Some(item) = self.bar_item(
(&clusters, &spans),
(axis, direction, plot, crossing),
(index, category, value),
(paint, theme),
) {
items.push(item);
}
}
}
items
}
fn bar_item(
&self,
(clusters, spans): (&Clusters, &bars::BarSpans),
(axis, direction, plot, crossing): (&ValueAxis, BarDirection, Edges<Length>, Length),
(index, category, value): (i64, i64, Decimal),
(paint, theme): (BarPaint<'_>, &ShapeTheme),
) -> Option<Item> {
let start = clusters.start((category, index))?;
let (from_val, to_val) = spans.endpoints((index, category), (axis.crossing, value))?;
let span = direction.values(plot);
let snap = |at: Length| match paint {
BarPaint::Color(_) => self.device.snap(at),
BarPaint::Gradient(_) => at,
};
let from_px = if from_val == axis.crossing {
crossing
} else {
snap(axis.along(span, from_val)?)
};
let to_px = snap(axis.along(span, to_val)?);
let (first, last) = direction.part(plot, start, clusters.thickness);
let (run, values) = (
(snap(first), snap(last)),
(from_px.min(to_px), from_px.max(to_px)),
);
(run.1 > run.0 && values.1 > values.0)
.then(|| bar_paint_item(direction, run, values, (paint, theme)))
.flatten()
}
fn series_lines(
&self,
chart: &Columns,
looks: &[LineLook],
(axis, across): (&ValueAxis, Across<'_>),
plot: Edges<Length>,
) -> Option<Vec<Item>> {
let theme = &self.shaper.theme().shapes;
let clip = match across {
Across::Bands => {
decisions::chart_line_clip(&self.context.quirks).then(|| self.lines_clip(plot))
}
Across::Values(..) => Some(self.lines_clip(plot)),
};
let stacked = bars::stacked_line_values(chart)?;
let offset = chart.bar_series().len();
let mut items = Vec::new();
for (index, (one, look)) in chart.line_series().iter().zip(looks).enumerate() {
let Some(fill) = one.fill.color() else {
continue;
};
let Some((rgb, alpha)) = fill.resolve(&theme.colors) else {
continue;
};
let width = look
.width
.map(|width| line_width(width, theme, CHART_STYLE_LINE_STYLES));
if width == Some(None) {
continue;
}
let values = stacked
.get(index)
.map_or(one.values.as_slice(), Vec::as_slice);
let Some(points) = self.series_points(
chart,
(axis, across),
plot,
(offset + index, values, clip.is_some()),
) else {
continue;
};
let color = on_white(rgb, alpha);
items.extend(line_runs_items(
look,
&points,
width.flatten(),
(color, clip.as_ref()),
)?);
if let Some(marker) = &look.marker {
for (_, place) in points.into_iter().flatten() {
if clip.is_some()
&& (place.x < plot.left
|| place.x > plot.right
|| place.y < plot.top
|| place.y > plot.bottom)
{
continue;
}
items.extend(marker_items(
marker,
place,
(fill, color),
theme,
&self.device,
));
}
}
}
Some(items)
}
fn series_points(
&self,
chart: &Columns,
(axis, across): (&ValueAxis, Across<'_>),
plot: Edges<Length>,
(index, values, unclamped): (usize, &[Option<Decimal>], bool),
) -> Option<Vec<Option<(Point, Point)>>> {
(0_i64..)
.zip(values)
.map(|(point, value)| {
let Some(value) = *value else {
return Some(None);
};
let (x, exact_x) = self.point_across(chart, across, plot, (index, point))?;
let (y, exact_y) = if unclamped {
(
self.place_unclamped(axis, (plot.bottom, plot.top), value)?,
axis.along_unclamped((plot.bottom, plot.top), value)?,
)
} else {
(
self.place(axis, (plot.bottom, plot.top), value)?,
axis.along((plot.bottom, plot.top), value)?,
)
};
Some(Some((
Point { x, y },
Point {
x: exact_x,
y: exact_y,
},
)))
})
.collect()
}
fn point_across(
&self,
chart: &Columns,
across: Across<'_>,
plot: Edges<Length>,
(index, point): (usize, i64),
) -> Option<(Length, Length)> {
match across {
Across::Bands => {
let bands = i64::try_from(chart.categories)
.ok()?
.checked_mul(2)
.filter(|&bands| bands > 0)?;
let middle = (plot.right - plot.left)
.checked_mul(point.checked_mul(2)?.checked_add(1)?)?
.div_toward_zero(bands);
Some((self.device.snap(plot.left + middle), plot.left + middle))
}
Across::Values(x_axis, x_values) => {
let x = *x_values.get(index)?.get(usize::try_from(point).ok()?)?;
let span = (plot.left, plot.right);
Some((
self.place_unclamped(&x_axis, span, x)?,
x_axis.along_unclamped(span, x)?,
))
}
}
}
fn gridlines(
&self,
chart: &Columns,
(axis, direction): (&ValueAxis, BarDirection),
plot: Edges<Length>,
) -> Vec<Item> {
let Some(look) = &chart.gridlines else {
return Vec::new();
};
let axis_drawn = chart.axis.line(&self.shaper.theme().shapes).is_some();
axis.labels()
.filter(|&value| !axis_drawn || value != axis.crossing)
.filter_map(|value| self.place(axis, direction.values(plot), value))
.flat_map(|at| self.value_line(look, direction, direction.run_ends(plot), at))
.collect()
}
fn value_axis(
&mut self,
chart: &Columns,
(axis, direction): (&ValueAxis, BarDirection),
plot: Edges<Length>,
) -> Vec<Item> {
let mut items = self.run_line(
&chart.value_axis,
direction,
direction.value_ends(plot),
direction.at(plot, Length::ZERO),
);
if !chart.ticks.value {
return items;
}
let Some(length) = self.value_lines(chart).map(LabelLines::top_part) else {
return items;
};
for value in axis.labels() {
if let Some(at) = self.place(axis, direction.values(plot), value) {
let outside = direction.before_run(plot, length);
items.extend(self.value_line(&chart.value_axis, direction, outside, at));
}
}
items
}
fn ticks_across(
&mut self,
chart: &Columns,
across: Across<'_>,
plot: Edges<Length>,
crossing: Length,
) -> Vec<Item> {
match across {
Across::Bands => self.category_ticks(chart, (plot, BarDirection::Up), crossing),
Across::Values(x_axis, _) => self.x_ticks(chart, &x_axis, plot, crossing),
}
}
fn category_ticks(
&mut self,
chart: &Columns,
(plot, direction): (Edges<Length>, BarDirection),
crossing: Length,
) -> Vec<Item> {
if !chart.ticks.category {
return Vec::new();
}
let Some(length) = self.label_lines(chart).map(LabelLines::top_part) else {
return Vec::new();
};
let Ok(count) = i64::try_from(chart.categories) else {
return Vec::new();
};
if count == 0 {
return Vec::new();
}
let run = direction.run(plot);
let ticks = direction.below(crossing, length);
(0..=count)
.filter_map(|edge| {
Some(direction.at(plot, run.checked_mul(edge)?.div_toward_zero(count)))
})
.flat_map(|at| self.run_line(&chart.axis, direction, ticks, at))
.collect()
}
fn value_line(
&self,
look: &f_office_drawingml::shape::ShapeLook,
direction: BarDirection,
(from, to): (Length, Length),
at: Length,
) -> Vec<Item> {
match direction {
BarDirection::Up => self.chart_rule(look, (from, to), at),
BarDirection::Right => self.chart_upright(look, (from, to), at),
}
}
fn run_line(
&self,
look: &f_office_drawingml::shape::ShapeLook,
direction: BarDirection,
(from, to): (Length, Length),
at: Length,
) -> Vec<Item> {
match direction {
BarDirection::Up => self.chart_upright(look, (from, to), at),
BarDirection::Right => self.chart_rule(look, (from, to), at),
}
}
fn chart_upright(
&self,
look: &f_office_drawingml::shape::ShapeLook,
(top, bottom): (Length, Length),
x: Length,
) -> Vec<Item> {
let theme = &self.shaper.theme().shapes;
let Some((rgb, alpha, width)) = look.line(theme) else {
return Vec::new();
};
vec![Item::Rect(Rect {
x: x - width.div_toward_zero(2),
y: top,
width,
height: bottom - top,
color: on_white(rgb, alpha),
})]
}
fn chart_rule(
&self,
look: &f_office_drawingml::shape::ShapeLook,
(left, right): (Length, Length),
y: Length,
) -> Vec<Item> {
let theme = &self.shaper.theme().shapes;
let Some((rgb, alpha, width)) = look.line(theme) else {
return Vec::new();
};
vec![Item::Rect(Rect {
x: left,
y: y - width.div_toward_zero(2),
width: right - left,
height: width,
color: on_white(rgb, alpha),
})]
}
fn text_width(&mut self, props: &RunProps, text: &str) -> Length {
let mut glyphs = Vec::new();
self.shaper.measure(props, text, &mut glyphs);
glyphs.iter().map(|g| g.advance).sum()
}
fn chart_line(&mut self, chart: &Columns, size: i64) -> Option<Length> {
self.line_of(&chart_props(chart, size))
}
fn line_of(&mut self, props: &RunProps) -> Option<Length> {
let face = self.shaper.face(props, true)?;
Some(self.shaper.faces().get(face)?.line_height())
}
fn label_lines(&mut self, chart: &Columns) -> Option<LabelLines> {
self.lines_of(&chart_props(chart, chart.label_size))
}
fn value_lines(&mut self, chart: &Columns) -> Option<LabelLines> {
self.lines_of(&chart_props(chart, chart.value_label_size))
}
fn plot_side_lines(&mut self, chart: &Columns, category: LabelLines) -> Option<SideLines> {
let value = self.value_lines(chart)?;
Some(match chart.group {
ChartGroup::Bars { .. } => SideLines {
left: category,
below: value,
},
_ => SideLines {
left: value,
below: category,
},
})
}
fn legend_lines(&mut self, chart: &Columns) -> Option<LabelLines> {
self.lines_of(&legend_props(chart))
}
fn lines_of(&mut self, props: &RunProps) -> Option<LabelLines> {
let face = self.shaper.face(props, true)?;
let face = self.shaper.faces().get(face)?;
Some(LabelLines {
size: face.size,
line: face.win_line(),
top: face.win_top(),
single_top: face.ascent(),
single_line: face.line_height(),
})
}
}
fn manual_plot(
layout: PlotLayout,
frame: Edges<Length>,
labels: Length,
sides: SideLines,
) -> Option<Edges<Length>> {
let layout_box = layout_edges(frame, layout.edges)?;
if layout.inner {
return Some(layout_box);
}
let below = sides.below;
Some(Edges {
left: layout_box.left + CHART_LINES_OUTER_GAP + labels,
top: layout_box.top + sides.left.line.div_toward_zero(2),
right: layout_box.right,
bottom: layout_box.bottom - (CHART_LINES_OUTER_GAP + below.band() + below.top_part()),
})
}
const ONE: Decimal = Decimal {
digits: 1,
exponent: 0,
};
fn layout_edges(frame: Edges<Length>, layout: LayoutBox) -> Option<Edges<Length>> {
let LayoutBox { x, y, w, h } = layout;
let (left, top) = layout_corner(frame, LayoutCorner { x, y })?;
Some(Edges {
left,
top,
right: left + share(frame.right - frame.left, w, ONE)?,
bottom: top + share(frame.bottom - frame.top, h, ONE)?,
})
}
fn layout_corner(frame: Edges<Length>, corner: LayoutCorner) -> Option<(Length, Length)> {
Some((
frame.left + share(frame.right - frame.left, corner.x, ONE)?,
frame.top + share(frame.bottom - frame.top, corner.y, ONE)?,
))
}
fn legend_props(chart: &Columns) -> RunProps {
RunProps {
bold: chart.legend_text.bold.then_some(true),
italic: chart.legend_text.italic.then_some(true),
..chart_props(chart, chart.legend_size)
}
}
fn chart_props(chart: &Columns, size: i64) -> RunProps {
RunProps {
font_ascii: Some(chart.font.clone()),
font_hansi: Some(chart.font.clone()),
size: Some(size),
..RunProps::default()
}
}
mod bars;
mod categories;
mod labels;
mod legend;
mod pie;
mod scatter;
mod smooth;
#[cfg(test)]
mod tests;
mod title;