use f_office_drawingml::color::DrawColor;
use f_office_drawingml::gradient::LinearGradient;
use f_office_drawingml::shape::{Geometry, ShapeLook};
use f_office_paint::{GradientItem, Item, PathCommand, Point, Rgb};
use f_office_units::{Edges, Length};
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};
use super::{
Clusters, LabelLines, MarkerPart, Scale, SideLines, ValueAxis, layout_edges, legend_props,
manual_plot, marker_span, room_units,
};
use crate::chart::{
AxisForms, ChartGroup, Columns, DataLabelText, Decimal, LabelFormat, LayoutBox, LegendBox,
LegendPlace, LegendText, LineForm, LineLook, PlotLayout, PlotPlace, Series, SeriesFill,
SeriesLabels, SetScale, StyleWidth, Title, all_digits,
};
use crate::layout::testing::with_layout_on;
use crate::params::{CHART_LINES_OUTER_GAP, CHART_PLOT_RIGHT};
use crate::props::FontRef;
use crate::quirks::{ChartAxisOrder, ChartDataLabels, ChartPlotArea};
fn columns(gap: i64, overlap: i64) -> Columns {
let one = Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
values: vec![
Some(Decimal {
digits: 1,
exponent: 0,
});
2
],
name: None,
labels: crate::chart::SeriesLabels::Hidden,
};
Columns::plain(
vec![one.clone(), one],
2,
ChartGroup::Columns {
gap,
overlap,
stacking: crate::chart::BarStacking::Clustered,
},
Some(Title {
lines: 1,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: None,
corner: None,
}),
)
}
#[test]
fn places_the_bars_of_a_cluster_or_none_beyond_a_length() {
let chart = columns(150, 0);
let span = Length::from_units(7_000);
let clusters = Clusters::of(&chart, (150, 0), span).unwrap();
assert_eq!(clusters.parts, 700);
assert_eq!(clusters.thickness, Length::from_units(1_000));
assert_eq!(
clusters.start((1, 1)),
Some(Length::from_units(3_500 + 750 + 1_000))
);
assert!(Clusters::of(&chart, (150, i64::MAX), span).is_none());
assert!(Clusters::of(&chart, (i64::MAX, 0), span).is_none());
let too_wide = Clusters {
gap: i64::MAX,
..clusters
};
assert_eq!(too_wide.start((1, 1)), None);
}
fn scale(max: &str) -> (String, i64) {
let scale = Scale::of(Decimal::parse(max).unwrap()).unwrap();
(all_digits(scale.unit), scale.steps)
}
#[test]
fn scales_the_value_axis_by_ones_twos_and_fives() {
assert_eq!(scale("4.5"), ("0.5".to_owned(), 10));
assert_eq!(scale("5"), ("1".to_owned(), 6));
assert_eq!(scale("40000"), ("5000".to_owned(), 9));
assert_eq!(scale("0.45"), ("0.05".to_owned(), 10));
assert_eq!(scale("8"), ("1".to_owned(), 9));
assert_eq!(scale("9.6"), ("2".to_owned(), 6));
assert!(Scale::of(Decimal::parse("0").unwrap()).is_none());
}
#[test]
fn keeps_the_powers_of_the_scale_in_range() {
assert_eq!(scale("1E350").1, 6);
let largest = Decimal {
digits: 1,
exponent: i32::MAX,
};
assert!(Scale::of(largest).is_none());
}
#[test]
fn writes_axis_values_in_the_general_format() {
let text = |s: &str| all_digits(Decimal::parse(s).unwrap());
assert_eq!(text("0"), "0");
assert_eq!(text("0.5"), "0.5");
assert_eq!(text("2.5"), "2.5");
assert_eq!(text("45000"), "45000");
assert_eq!(text("0.05"), "0.05");
}
fn decimal(text: &str) -> Decimal {
Decimal::parse(text).unwrap()
}
fn plot_box() -> LayoutBox {
LayoutBox {
x: decimal("0.1"),
y: decimal("0.15"),
w: decimal("0.8"),
h: decimal("0.6"),
}
}
fn axis_of(values: &[&str], set: [Option<&str>; 3]) -> [String; 4] {
let mut chart = columns(150, 0);
chart.series.truncate(1);
chart.series[0].values = values.iter().map(|v| Some(decimal(v))).collect();
chart.categories = values.len();
let [min, max, major_unit] = set.map(|v| v.map(decimal));
chart.scale = SetScale {
min,
max,
major_unit,
};
let axis = ValueAxis::of(&chart).unwrap();
[axis.low, axis.high, axis.unit, axis.crossing].map(all_digits)
}
type AxisCase = (
&'static [&'static str],
[Option<&'static str>; 3],
[&'static str; 4],
);
#[test]
fn scales_the_value_axis_below_zero_and_as_the_axis_sets_it() {
let auto = [None; 3];
let cases: [AxisCase; 10] = [
(&["4.3", "2.5", "5"], auto, ["0", "6", "1", "0"]),
(
&["4.4000000000000004", "2", "5"],
auto,
["0", "6", "1", "0"],
),
(
&["-4.4000000000000004", "2", "5"],
auto,
["-6", "6", "2", "0"],
),
(&["4.3", "-2.5", "5"], auto, ["-3", "6", "1", "0"]),
(&["-4.3", "-2.5", "-5"], auto, ["-6", "0", "1", "0"]),
(&["4.76", "2"], auto, ["0", "5", "0.5", "0"]),
(&["4.3", "5"], [None, Some("8"), None], ["0", "8", "1", "0"]),
(
&["4.3", "5", "1.8"],
[Some("1"), None, None],
["1", "5.5", "0.5", "1"],
),
(&["4.3", "5"], [None, None, Some("2")], ["0", "6", "2", "0"]),
(
&["4.3", "-2.5", "5"],
[Some("-4"), None, Some("1")],
["-4", "6", "1", "0"],
),
];
for (values, set, expected) in cases {
assert_eq!(
axis_of(values, set),
expected.map(str::to_owned),
"{values:?} {set:?}"
);
}
let mut chart = columns(150, 0);
chart.scale.min = Some(decimal("8"));
chart.scale.max = Some(decimal("8"));
assert!(ValueAxis::of(&chart).is_none());
}
#[test]
fn scales_values_at_and_above_zero_as_the_default_chart() {
for max in ["5", "4.76", "0.43", "120", "9.99", "1E-5", "3E7"] {
let mut chart = columns(150, 0);
chart.series[0].values = vec![Some(decimal(max)), Some(decimal("0"))];
assert_eq!(ValueAxis::of(&chart), ValueAxis::from_zero(&chart), "{max}");
}
}
fn points(points: i64) -> Length {
Length::from_points(points).unwrap()
}
#[test]
fn places_the_plot_area_of_a_manual_layout_in_the_frame() {
let frame = Edges {
left: points(100),
top: points(200),
right: points(500),
bottom: points(400),
};
let layout = |inner| PlotLayout {
inner,
edges: plot_box(),
};
let edges = |[left, top, right, bottom]: [i64; 4]| Edges {
left: points(left),
top: points(top),
right: points(right),
bottom: points(bottom),
};
let lines = LabelLines {
size: points(10),
line: points(12),
top: points(9),
single_top: points(9),
single_line: points(12),
};
let sides = SideLines {
left: lines,
below: lines,
};
assert_eq!(
manual_plot(layout(true), frame, points(20), sides),
Some(edges([140, 230, 460, 350]))
);
let outer = edges([160, 236, 460, 332]);
assert_eq!(
manual_plot(layout(false), frame, points(20), sides),
Some(Edges {
left: outer.left + CHART_LINES_OUTER_GAP,
bottom: outer.bottom - CHART_LINES_OUTER_GAP,
..outer
})
);
}
fn font_line_plots(
chart: &Columns,
cases: &[(Option<LegendPlace>, Option<Title>)],
) -> Vec<Option<Edges<Length>>> {
let mut plots = Vec::new();
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
for (legend, title) in cases {
let chart = Columns {
title: title.clone(),
legend: *legend,
..chart.clone()
};
let axis = ValueAxis::of(&chart);
plots.push(axis.and_then(|axis| layout.font_line_plot(&chart, &axis, frame)));
}
},
);
plots
}
fn named_columns() -> Columns {
let mut chart = columns(219, -27);
for (series, name) in chart.series.iter_mut().zip(["A", "Longer"]) {
series.name = Some(name.to_owned());
}
chart
}
#[test]
fn moves_the_plot_area_with_a_legend_at_the_top_and_the_title_on_font_lines() {
let title = Some(Title {
lines: 1,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: None,
corner: None,
});
let cases = [
(Some(LegendPlace::Bottom), title.clone()),
(Some(LegendPlace::Top), title.clone()),
(None, title),
(Some(LegendPlace::Bottom), None),
];
let plots = font_line_plots(&named_columns(), &cases);
let [Some(bottom), Some(top), Some(none), Some(untitled)] = plots[..] else {
panic!("{plots:?}");
};
let room = none.bottom - bottom.bottom;
assert!(room > Length::ZERO);
assert_eq!(
(top.top - bottom.top, top.bottom, none.top),
(room, none.bottom, bottom.top)
);
assert!(untitled.top < bottom.top);
}
#[test]
fn keeps_no_band_below_the_plot_area_when_the_category_labels_stand_inside_on_font_lines() {
let mut below = named_columns();
below.series[0].values[0] = Some(decimal("-1"));
let cases = [(Some(LegendPlace::Bottom), None), (None, None)];
let [Some(above_zero), _] = font_line_plots(&named_columns(), &cases)[..] else {
panic!("no plot area above zero");
};
let plots = font_line_plots(&below, &cases);
let [Some(legend), Some(none)] = plots[..] else {
panic!("{plots:?}");
};
let mut lines = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| lines = layout.label_lines(&below),
);
let lines = lines.unwrap();
let edge = points(252) - lines.untitled_edge();
assert_eq!(
(legend.bottom, none.bottom),
(edge - lines.legend_room().unwrap(), edge)
);
assert!(legend.bottom > above_zero.bottom);
assert_eq!(legend.top, above_zero.top);
}
#[test]
fn takes_the_room_of_a_legend_at_a_side_on_font_lines() {
let title = Some(Title {
lines: 1,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: None,
corner: None,
});
let cases = [
(Some(LegendPlace::Bottom), title.clone()),
(None, title.clone()),
(Some(LegendPlace::Right), title.clone()),
(Some(LegendPlace::Left), title.clone()),
];
let plots = font_line_plots(&named_columns(), &cases);
let [Some(bottom), Some(none), Some(right), Some(left)] = plots[..] else {
panic!("{plots:?}");
};
let side = bottom.right - right.right;
assert!(side > Length::ZERO);
assert_eq!(
(left.left - bottom.left, left.bottom, right.bottom),
(side, none.bottom, none.bottom)
);
let mut unnamed = named_columns();
unnamed.series[1].name = None;
let plots = font_line_plots(&unnamed, &[(Some(LegendPlace::Right), title)]);
assert_eq!(plots, [None]);
}
#[test]
fn places_the_axis_labels_from_the_label_lines() {
let lines = LabelLines {
size: points(10),
line: points(12),
top: points(9),
single_top: points(9),
single_line: points(12),
};
assert_eq!(lines.label_gap(), Some(points(9)));
assert_eq!(lines.value_baseline(), Some(points(10).div_toward_zero(4)));
assert_eq!(lines.category_baseline(), Some(points(15)));
}
fn label_runs(chart: &Columns, area: ChartPlotArea) -> Vec<(String, Length, Length)> {
let mut runs = Vec::new();
with_layout_on(
|p| p.with_variant(area),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
let items = layout.columns(chart, frame).map(|(items, _)| items);
for item in items.unwrap_or_default() {
if let f_office_paint::Item::Glyphs(run) = item {
let first = run.glyphs.first().map(|g| (g.x, g.y)).unwrap();
runs.push((run.text, first.0, first.1));
}
}
},
);
runs
}
fn all_text(chart: &Columns, area: ChartPlotArea) -> Option<bool> {
let mut all = None;
with_layout_on(
|p| p.with_variant(area),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
all = layout
.columns(chart, frame)
.map(|(_, drawn)| drawn.axes_and_legend);
},
);
all
}
fn drawn_text_columns() -> Columns {
Columns {
category_names: Some(vec!["One".to_owned(), "Two".to_owned()]),
title: None,
..named_columns()
}
}
#[test]
fn says_whether_a_drawn_chart_holds_all_of_its_text() {
let mut chart = drawn_text_columns();
assert_eq!(all_text(&chart, ChartPlotArea::FontLines), Some(true));
let titled = Columns {
title: Some(Title {
lines: 1,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: None,
corner: None,
}),
..chart.clone()
};
assert_eq!(all_text(&titled, ChartPlotArea::FontLines), Some(false));
chart.legend = None;
assert_eq!(all_text(&chart, ChartPlotArea::FontLines), Some(true));
let unnamed = Columns {
category_names: None,
..chart.clone()
};
assert_eq!(all_text(&unnamed, ChartPlotArea::FontLines), Some(false));
assert_eq!(
all_text(&named_columns(), ChartPlotArea::DefaultChart),
Some(false)
);
}
#[test]
fn draws_a_legend_at_the_bottom_the_top_the_right_and_the_left_in_its_own_font() {
let place = |legend| Columns {
legend: Some(legend),
..drawn_text_columns()
};
for legend in [
LegendPlace::Bottom,
LegendPlace::Top,
LegendPlace::Right,
LegendPlace::Left,
] {
assert_eq!(
all_text(&place(legend), ChartPlotArea::FontLines),
Some(true),
"{legend:?}"
);
}
let other_font = Columns {
legend_font: FontRef::Name("Georgia".to_owned()),
..place(LegendPlace::Right)
};
assert_eq!(all_text(&other_font, ChartPlotArea::FontLines), Some(true));
}
#[test]
fn draws_the_axis_labels_on_font_lines_only() {
let mut chart = named_columns();
chart.category_names = Some(vec!["One".to_owned(), "Two".to_owned()]);
chart.legend = None;
let runs = label_runs(&chart, ChartPlotArea::FontLines);
let texts: Vec<&str> = runs.iter().map(|(text, _, _)| text.as_str()).collect();
assert_eq!(
texts,
["0", "0.2", "0.4", "0.6", "0.8", "1", "1.2", "One", "Two"]
);
let baselines: Vec<Length> = runs.iter().map(|&(_, _, y)| y).collect();
assert!(baselines[..7].windows(2).all(|pair| pair[0] > pair[1]));
assert_eq!(baselines[7], baselines[8]);
assert!(baselines[7] > baselines[0]);
assert!(runs[8].1 > runs[7].1);
chart.category_names = None;
assert_eq!(label_runs(&chart, ChartPlotArea::FontLines).len(), 7);
assert_eq!(label_runs(&chart, ChartPlotArea::DefaultChart), Vec::new());
}
fn font_line_items(chart: &Columns) -> (Vec<Item>, LabelLines) {
let mut out = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
let items = layout.columns(chart, frame).map(|(items, _)| items);
out = Some((items.unwrap(), layout.label_lines(chart).unwrap()));
},
);
out.unwrap()
}
fn runs_of(items: &[Item]) -> Vec<(&str, Length, Length)> {
items
.iter()
.filter_map(|item| match item {
Item::Glyphs(run) => {
let first = run.glyphs.first()?;
Some((run.text.as_str(), first.x, first.y))
}
_ => None,
})
.collect()
}
fn keys_of(items: &[Item], side: Length) -> Vec<(Length, Length)> {
items
.iter()
.filter_map(|item| match item {
Item::Rect(rect) if rect.width == side && rect.height == side => {
Some((rect.x, rect.y + side.div_toward_zero(2)))
}
_ => None,
})
.collect()
}
#[test]
fn draws_the_keys_and_names_of_a_legend_at_the_right_on_font_lines() {
let chart = Columns {
legend: Some(LegendPlace::Right),
..named_columns()
};
let (items, lines) = font_line_items(&chart);
let runs = runs_of(&items);
let texts: Vec<&str> = runs.iter().map(|&(text, _, _)| text).collect();
assert_eq!(texts[texts.len() - 2..], ["A", "Longer"]);
let side = lines.of_line(450).unwrap();
let keys = keys_of(&items, side);
let gap = side.div_toward_zero(2) - hundredths(32);
let down = lines.value_baseline().unwrap();
let starts: Vec<(Length, Length)> = keys
.iter()
.map(|k| (k.0 + side + gap, k.1 + down))
.collect();
let drawn: Vec<(Length, Length)> = runs[runs.len() - 2..]
.iter()
.map(|&(_, x, y)| (x, y))
.collect();
assert_eq!(drawn, starts);
let left = Columns {
legend: Some(LegendPlace::Left),
..named_columns()
};
let (left_items, _) = font_line_items(&left);
let left_keys = keys_of(&left_items, side);
assert_eq!(left_keys.len(), 2);
assert_eq!(left_keys[0].0, hundredths(825) + side.div_toward_zero(2));
assert_eq!(left_keys[0].0, left_keys[1].0);
assert_eq!(left_keys[0].1, keys[0].1);
assert_eq!(left_keys[1].1, keys[1].1);
}
fn styled_keys(
place: LegendPlace,
legend_text: LegendText,
) -> (Vec<Length>, Vec<(Length, Length)>) {
let chart = Columns {
title: None,
legend: Some(place),
legend_text,
..named_columns()
};
let (items, lines) = font_line_items(&chart);
let keys = keys_of(&items, lines.of_line(450).unwrap());
(name_widths(&chart, &["A", "Longer"]), keys)
}
fn path_boxes(items: &[Item]) -> Vec<Edges<Length>> {
items
.iter()
.filter_map(|item| match item {
Item::Path(path) => {
let points: Vec<_> = path.commands.iter().flat_map(PathCommand::points).collect();
Some(Edges {
left: points.iter().map(|p| p.x).min()?,
top: points.iter().map(|p| p.y).min()?,
right: points.iter().map(|p| p.x).max()?,
bottom: points.iter().map(|p| p.y).max()?,
})
}
_ => None,
})
.collect()
}
fn line_keys_and_names(
items: &[Item],
down: Length,
place: LegendPlace,
) -> (Vec<Edges<Length>>, Vec<(Length, Length)>) {
use crate::params::{CHART_LINE_KEY_AREA, CHART_LINE_KEY_STROKE};
let keys: Vec<Edges<Length>> = path_boxes(items)
.into_iter()
.filter(|b| b.right - b.left == CHART_LINE_KEY_STROKE + points(1))
.collect();
assert_eq!(keys.len(), 2, "{place:?}");
let runs = runs_of(items);
let names: Vec<(Length, Length)> = runs[runs.len() - 2..]
.iter()
.map(|&(_, x, y)| (x, y))
.collect();
for (key, &(x, y)) in keys.iter().zip(&names) {
assert_eq!(key.bottom - key.top, points(1));
let middle = key.top + hundredths(50);
let start = key.left + hundredths(50) + CHART_LINE_KEY_STROKE.div_toward_zero(2)
- CHART_LINE_KEY_AREA.div_toward_zero(2);
assert_eq!(x, start + CHART_LINE_KEY_AREA - hundredths(32), "{place:?}");
assert_eq!(y, middle + down, "{place:?}");
}
(keys, names)
}
#[test]
fn draws_a_line_charts_legend_with_line_keys_in_areas_of_24_points() {
for place in [LegendPlace::Right, LegendPlace::Bottom, LegendPlace::Top] {
let twin = Columns {
title: None,
legend: Some(place),
..named_columns()
};
let chart = Columns {
group: ChartGroup::Lines {
looks: vec![plain_look(); 2],
stacking: crate::chart::BarStacking::Clustered,
},
..twin.clone()
};
let (items, lines) = font_line_items(&chart);
let side = lines.of_line(450).unwrap();
let (keys, names) = line_keys_and_names(&items, lines.value_baseline().unwrap(), place);
let (twin_items, _) = font_line_items(&twin);
let squares = keys_of(&twin_items, side);
assert_eq!(squares.len(), 2);
let twin_runs = runs_of(&twin_items);
let twin_names: Vec<Length> = twin_runs[twin_runs.len() - 2..]
.iter()
.map(|r| r.1)
.collect();
let step = names[1].0 - names[0].0;
let twin_step = twin_names[1] - twin_names[0];
if place == LegendPlace::Right {
let off: Vec<i64> = names
.iter()
.zip(&twin_names)
.map(|(name, twin)| (name.0 - *twin).units().abs())
.collect();
assert!(off.iter().all(|&o| o <= 2), "{off:?}");
assert_eq!(step, twin_step);
} else {
assert!(step > twin_step, "{place:?}");
}
let heights: Vec<Length> = keys.iter().map(|k| k.top + hundredths(50)).collect();
let square_heights: Vec<Length> = squares.iter().map(|s| s.1).collect();
assert_eq!(heights, square_heights, "{place:?}");
}
}
#[test]
fn gives_dashed_line_keys_a_wider_area_and_caps_a_keys_marker_below_the_legends_size() {
use super::legend::Keys;
use crate::chart::{LineDash, Marker, MarkerSymbol};
use crate::params::{CHART_LINE_KEY_AREA, CHART_LINE_KEY_DASHED_AREA};
let lines_of = |looks: Vec<LineLook>| Columns {
title: None,
legend: Some(LegendPlace::Bottom),
group: ChartGroup::Lines {
looks,
stacking: crate::chart::BarStacking::Clustered,
},
..named_columns()
};
let dashed = LineLook {
dash: Some(LineDash::Dash),
..plain_look()
};
assert_eq!(
Keys::of(&lines_of(vec![plain_look(); 2])),
Keys::Lines(CHART_LINE_KEY_AREA)
);
assert_eq!(
Keys::of(&lines_of(vec![plain_look(), dashed])),
Keys::Lines(CHART_LINE_KEY_DASHED_AREA)
);
let marked = LineLook {
marker: Some(Marker {
symbol: MarkerSymbol::Square,
size: Some(points(17)),
fill: None,
outline: None,
}),
..plain_look()
};
for (half_points, cap) in [
(12, 3),
(15, 4),
(17, 4),
(18, 5),
(22, 6),
(27, 7),
(48, 14),
] {
let chart = Columns {
legend_size: half_points,
..lines_of(vec![marked.clone(); 2])
};
let (items, _) = font_line_items(&chart);
let small: Vec<Length> = path_boxes(&items)
.into_iter()
.filter(|b| b.right - b.left == b.bottom - b.top && b.right - b.left < points(16))
.map(|b| b.right - b.left)
.collect();
assert_eq!(small.len(), 2, "{half_points}");
for width in small {
let off = (width - points(cap)).units().abs();
assert!(off <= hundredths(12).units(), "{half_points} {width:?}");
}
}
}
#[test]
fn draws_an_italic_legend_in_its_face_and_leaves_out_one_with_entries_of_its_own() {
let italic = LegendText {
italic: true,
..LegendText::default()
};
let entries = LegendText {
own_entries: true,
..LegendText::default()
};
for place in [LegendPlace::Bottom, LegendPlace::Right] {
let (_, regular) = styled_keys(place, LegendText::default());
assert_eq!(regular.len(), 2);
assert_eq!(styled_keys(place, italic).1, regular, "{place:?}");
assert_eq!(styled_keys(place, entries).1, [], "{place:?}");
}
}
#[test]
fn draws_a_bold_legend_with_the_advances_of_its_face() {
let bold = LegendText {
bold: true,
..LegendText::default()
};
let (widths, keys) = styled_keys(LegendPlace::Bottom, bold);
let (regular_widths, regular) = styled_keys(LegendPlace::Bottom, LegendText::default());
let wider = widths[1] - regular_widths[1];
assert!(wider > Length::ZERO);
assert!(keys[1].0 - keys[0].0 > regular[1].0 - regular[0].0);
let (_, keys) = styled_keys(LegendPlace::Right, bold);
let (_, regular) = styled_keys(LegendPlace::Right, LegendText::default());
assert_eq!(keys[0].0, regular[0].0 - wider);
}
#[test]
fn caps_a_nearly_full_legend_row_and_leaves_out_a_row_past_the_cap() {
let chart = Columns {
title: None,
legend: Some(LegendPlace::Bottom),
..named_columns()
};
let (_, lines) = font_line_items(&chart);
let side = lines.of_line(450).unwrap();
let gap = side.div_toward_zero(2) - hundredths(32);
let cap = points(432).checked_mul(900).unwrap().div_toward_zero(1_000);
let named = |letters: usize| {
let mut row = chart.clone();
for series in &mut row.series {
series.name = Some("n".repeat(letters));
}
row
};
let sums = |letters: usize| {
let name = "n".repeat(letters);
let widths = name_widths(&chart, &[&name, &name]);
let mut sides = Length::ZERO;
let mut entries = Length::ZERO;
for &width in &widths {
let entry = width + side.checked_mul(2).unwrap();
sides += entry;
entries += entry.checked_mul(1_200).unwrap().div_toward_zero(1_000);
}
(widths, sides, entries)
};
let last = (1..400).find(|&n| sums(n + 1).1 > cap).unwrap();
let (widths, sides, entries) = sums(last);
assert!(sides <= cap && entries > cap);
let keys = keys_of(&font_line_items(&named(last)).0, side);
assert_eq!(keys.len(), 2);
let drawn = [widths[0] + side + gap, widths[1] + side + gap];
let space = (cap + lines.of_line(250).unwrap() - drawn[0] - drawn[1]).div_toward_zero(3);
assert_eq!(keys[1].0 - keys[0].0, drawn[0] + space);
let wrapped = keys_of(&font_line_items(&named(last + 1)).0, side);
assert_eq!(wrapped.len(), 2);
assert_eq!(wrapped[0].0, wrapped[1].0);
let step = points(6) + lines.of_line(990).unwrap();
assert_eq!(wrapped[1].1 - wrapped[0].1, step);
}
fn name_widths(chart: &Columns, names: &[&str]) -> Vec<Length> {
let mut out = Vec::new();
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let props = legend_props(chart);
out = names
.iter()
.map(|name| layout.chart_text(&props, name).unwrap().width())
.collect();
},
);
out
}
#[test]
fn spaces_and_centers_a_legend_row_at_the_bottom_and_the_top_on_font_lines() {
let chart = Columns {
title: None,
legend: Some(LegendPlace::Bottom),
..named_columns()
};
let (items, lines) = font_line_items(&chart);
let side = lines.of_line(450).unwrap();
let keys = keys_of(&items, side);
assert_eq!(keys.len(), 2);
let inset = hundredths(890) + lines.line.div_toward_zero(2);
assert_eq!([keys[0].1, keys[1].1], [points(252) - inset; 2]);
let widths = name_widths(&chart, &["A", "Longer"]);
let gap = side.div_toward_zero(2) - hundredths(32);
let drawn: Vec<Length> = widths.iter().map(|&width| side + gap + width).collect();
let counted = widths
.iter()
.fold(lines.of_line(250).unwrap(), |sum, &width| {
let entry = width + side.checked_mul(2).unwrap();
sum + entry.checked_mul(1_200).unwrap().div_toward_zero(1_000)
});
let space = (counted - drawn[0] - drawn[1]).div_toward_zero(3);
assert_eq!(keys[1].0 - keys[0].0, drawn[0] + space);
let twice = keys[0].0 - (side.div_toward_zero(2) + hundredths(115)) + keys[1].0 + drawn[1];
let units = Length::from_units(2);
assert!((points(432) - units..=points(432) + units).contains(&twice));
let top = Columns {
legend: Some(LegendPlace::Top),
..chart.clone()
};
let (items, _) = font_line_items(&top);
let top_keys = keys_of(&items, side);
assert_eq!(top_keys, [(keys[0].0, inset), (keys[1].0, inset)]);
}
#[test]
fn centers_the_rows_of_a_legend_at_the_right_in_its_area_below_the_title() {
let chart = Columns {
title: Some(Title {
lines: 1,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: None,
corner: None,
}),
legend: Some(LegendPlace::Right),
..named_columns()
};
let (items, lines) = font_line_items(&chart);
let side = lines.of_line(450).unwrap();
let keys = keys_of(&items, side);
assert_eq!(keys.len(), 2);
assert_eq!(keys[0].0, keys[1].0);
assert_eq!(
keys[1].1 - keys[0].1,
points(6) + lines.of_line(990).unwrap()
);
let mut title_line = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| title_line = layout.chart_line(&chart, 28),
);
let area_top = title_line.unwrap() + points(9);
let twice = keys[0].1 + keys[1].1 - (area_top + points(252));
let unit = Length::from_units(1);
assert!((-unit..=unit).contains(&twice));
}
fn hundredths(hundredths: i64) -> Length {
Length::from_units(hundredths * Length::UNITS_PER_POINT / 100)
}
fn thousandths(thousandths: i64) -> Length {
Length::from_units(thousandths * Length::UNITS_PER_POINT / 1_000)
}
#[test]
fn the_labels_lines_limit_the_units_of_an_automatic_axis() {
let room = |height, line| room_units(hundredths(height), hundredths(line));
assert_eq!(room(16_887, 1_099), 10);
assert_eq!(room(12_895, 2_441), 4);
assert_eq!(room(4_298, 1_709), 1);
assert_eq!(room(500, 1_709), 1);
assert_eq!(room_units(hundredths(4_298), Length::ZERO), 10);
assert_eq!(room(9_400, 1_680), 5);
assert_eq!(room(9_399, 1_680), 4);
}
#[test]
fn an_axis_of_fewer_units_takes_the_next_unit_of_the_series() {
let values = ["37", "89", "137", "64"];
let mut chart = columns(150, 0);
chart.series.truncate(1);
chart.series[0].values = values.iter().map(|v| Some(decimal(v))).collect();
chart.categories = values.len();
let shown = |most| {
let axis = ValueAxis::with_most(&chart, most).unwrap();
[axis.high, axis.unit].map(all_digits)
};
assert_eq!(shown(10), ["160", "20"]);
assert_eq!(shown(4), ["150", "50"]);
assert_eq!(shown(2), ["200", "100"]);
assert_eq!(shown(1), ["200", "200"]);
}
fn theme_with_first_line(emus: u32) -> f_office_drawingml::theme::ShapeTheme {
let xml = format!(
r#"<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:themeElements><a:fmtScheme><a:lnStyleLst><a:ln w="{emus}"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="12700"/><a:ln w="19050"/></a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>"#
);
let doc =
f_office_xml::Document::parse(xml.as_bytes(), &f_office_xml::Limits::default()).unwrap();
f_office_drawingml::theme::ShapeTheme::read(
&doc,
doc.root().unwrap(),
&mut f_office_warnings::Warnings::new(),
)
}
#[test]
fn gives_the_style_lines_and_markers_their_widths_and_sizes_from_the_theme() {
use super::{line_width, marker_size};
use crate::chart::{Marker, MarkerOutline, MarkerSymbol, StyleWidth};
let marker = Marker {
symbol: MarkerSymbol::Diamond,
size: None,
fill: None,
outline: Some(MarkerOutline::STYLE),
};
for (emus, line_emus, points) in [
(3_175, 9_525, 4),
(6_350, 19_050, 6),
(7_620, 22_860, 6),
(9_525, 28_575, 7),
(12_700, 38_100, 9),
(15_875, 47_625, 10),
(19_050, 57_150, 12),
(25_400, 76_200, 15),
] {
let theme = theme_with_first_line(emus);
assert_eq!(
line_width(StyleWidth::Automatic, &theme, 3),
Length::from_emus(line_emus),
"{emus}"
);
assert_eq!(
marker_size(&marker, &theme),
Length::from_points(points),
"{emus}"
);
}
let set = Marker {
size: Length::from_points(5),
..marker
};
assert_eq!(
marker_size(&set, &theme_with_first_line(6_350)),
Length::from_points(5)
);
}
#[test]
fn places_each_marker_part_on_whole_or_half_dots() {
let device = crate::grid::Device::per_inch(600).expect("a dot is whole units");
let dots = |tenths: i64| device.dots(tenths).div_toward_zero(10);
let point = device.dots(100);
let span = |part, points, odd, (place, after)| {
marker_span(
&device,
part,
Length::from_points(points).unwrap(),
odd,
(place, after),
)
};
assert_eq!(
span(MarkerPart::Even, 5, false, (point, true)),
(device.dots(79), device.dots(42))
);
assert_eq!(
span(MarkerPart::Whole, 3, false, (point, true)),
(device.dots(87), device.dots(25))
);
let past = point + dots(3);
assert_eq!(
span(MarkerPart::Whole, 3, true, (past, true)),
(dots(875), device.dots(24))
);
assert_eq!(
span(MarkerPart::Lines, 3, true, (past, true)),
(device.dots(88), device.dots(25))
);
assert_eq!(span(MarkerPart::Even, 3, true, (point, true)).0, dots(885));
assert_eq!(span(MarkerPart::Even, 3, true, (point, false)).0, dots(875));
}
fn data_label_runs(
chart: &Columns,
labels: ChartDataLabels,
text: &str,
) -> (Vec<(Length, Length)>, Option<bool>) {
let (mut runs, mut all) = (Vec::new(), None);
with_layout_on(
|p| {
p.with_variant(ChartPlotArea::FontLines)
.with_variant(labels)
},
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
if let Some((items, drawn)) = layout.columns(chart, frame) {
all = Some(drawn.data_labels);
for item in items {
if let Item::Glyphs(run) = item
&& run.text == text
{
let first = run.glyphs.first().map(|g| (g.x, g.y)).unwrap();
runs.push(first);
}
}
}
},
);
(runs, all)
}
fn labelled_columns(first: Decimal, (top, bottom): (Length, Length)) -> Columns {
let mut chart = drawn_text_columns();
for series in &mut chart.series {
series.values[0] = Some(first);
series.labels = SeriesLabels::Values(DataLabelText {
position: crate::chart::DataLabelPosition::Default,
size: 18,
font: FontRef::MinorLatin,
fill: None,
insets: Edges {
left: Length::ZERO,
top,
right: Length::ZERO,
bottom,
},
format: LabelFormat::all_digits(),
parts: crate::chart::DataLabelParts::default(),
show_default: true,
point_overrides: Vec::new(),
});
}
chart
}
const ABOVE: Decimal = Decimal {
digits: 225,
exponent: -2,
};
#[test]
fn draws_the_value_labels_at_the_outer_end_where_the_target_does() {
let chart = labelled_columns(ABOVE, (Length::ZERO, Length::ZERO));
assert_eq!(
data_label_runs(&chart, ChartDataLabels::LeftOut, "2.25"),
(Vec::new(), Some(false))
);
let (runs, all) = data_label_runs(&chart, ChartDataLabels::OuterEnd, "2.25");
assert_eq!((runs.len(), all), (2, Some(true)));
assert!(runs[0].0 < runs[1].0 && runs[0].1 == runs[1].1);
let mut other = chart;
other.series[1].labels = SeriesLabels::Other;
other.other_labels = true;
let (runs, all) = data_label_runs(&other, ChartDataLabels::OuterEnd, "2.25");
assert_eq!((runs.len(), all), (1, Some(false)));
}
#[test]
fn puts_the_top_inset_between_a_bar_and_its_label_on_both_sides_of_the_crossing() {
let place = |first: Decimal, text: &str, insets| {
let chart = labelled_columns(first, insets);
data_label_runs(&chart, ChartDataLabels::OuterEnd, text).0[0]
};
let plain = place(ABOVE, "2.25", (Length::ZERO, Length::ZERO));
let raised = place(ABOVE, "2.25", (points(1), Length::ZERO));
assert_eq!(raised, (plain.0, plain.1 - points(1)));
assert_eq!(place(ABOVE, "2.25", (Length::ZERO, points(1))), plain);
let negative = Decimal {
digits: -225,
exponent: -2,
};
let plain = place(negative, "-2.25", (Length::ZERO, Length::ZERO));
let lowered = place(negative, "-2.25", (points(1), Length::ZERO));
assert_eq!(lowered, (plain.0, plain.1 + points(1)));
assert_eq!(place(negative, "-2.25", (Length::ZERO, points(1))), plain);
}
#[test]
fn sums_a_value_of_seventeen_digits_and_a_value_of_other_powers_of_ten() {
let value = |text: &str| Decimal::parse(text).unwrap();
let total = super::sum(value("1500"), value("-3.4500000000000002")).unwrap();
assert_eq!(total, value("1496.55"));
let total = super::sum(value("1500"), value("-3.4500000000000042")).unwrap();
assert_eq!(total, value("1496.549999999999996"));
assert_eq!(super::sum(value("1"), value("2")).unwrap(), value("3"));
}
#[test]
fn writes_data_labels_in_their_format_with_its_blanks_and_its_color() {
let separators = crate::NumberSeparators::new('.', ',').unwrap();
let in_format = |first: Decimal, code: &str| {
let mut chart = labelled_columns(first, (Length::ZERO, Length::ZERO));
for series in &mut chart.series {
if let SeriesLabels::Values(labels) = &mut series.labels {
labels.format = LabelFormat::code(code, separators).unwrap();
}
}
chart
};
let first_run = |chart: &Columns, text: &str| {
let mut found = None;
with_layout_on(
|p| {
p.with_variant(ChartPlotArea::FontLines)
.with_variant(ChartDataLabels::OuterEnd)
},
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
let (items, _) = layout.columns(chart, frame).unwrap();
found = items.into_iter().find_map(|item| match item {
Item::Glyphs(run) if run.text == text => {
Some((run.glyphs[0].x, run.glyphs[0].y, run.color))
}
_ => None,
});
},
);
found.unwrap()
};
let accounting = r"#,##0.0_);[Red]\(#,##0.0\)";
let plain = first_run(&in_format(ABOVE, "0.0"), "2.3");
let blank = first_run(&in_format(ABOVE, "_(0.0"), "2.3");
assert!(blank.0 > plain.0 && blank.0 - plain.0 < points(3));
assert_eq!((blank.1, blank.2), (plain.1, plain.2));
assert_eq!(first_run(&in_format(ABOVE, accounting), "2.3"), plain);
let negative = Decimal {
digits: -225,
exponent: -2,
};
let red = first_run(&in_format(negative, accounting), "(2.3)");
assert_eq!(red.2, crate::params::CHART_FORMAT_RED);
let axis = |code: &str| {
let mut chart = labelled_columns(ABOVE, (Length::ZERO, Length::ZERO));
chart.value_format = LabelFormat::code(code, separators);
chart
};
let (plain, blank, spaced) = (axis("0.0"), axis("0.0_)"), axis("0.0\\ "));
assert_eq!(first_run(&blank, "2.5").0, first_run(&plain, "2.5").0);
assert_eq!(first_run(&blank, "2.25").0, first_run(&spaced, "2.25").0);
assert!(first_run(&blank, "2.25").0 > first_run(&plain, "2.25").0);
}
#[test]
fn centers_each_line_of_a_title_and_steps_its_baselines_by_the_single_line() {
use crate::chart::TitleText;
use crate::params::CHART_TITLE_LINE_TOP;
let text = |lines: &[&str]| TitleText {
lines: lines.iter().map(|&line| line.to_owned()).collect(),
font: FontRef::MinorLatin,
bold: false,
italic: false,
fill: None,
};
let title = |lines: &[&str]| Title {
lines: lines.len(),
size: 28,
font: crate::props::FontRef::MinorLatin,
text: Some(text(lines)),
corner: None,
};
let frame = Edges {
left: points(10),
top: points(20),
right: points(442),
bottom: points(272),
};
let chart = columns(219, -27);
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let face = layout
.shaper
.face(&super::chart_props(&chart, 28), true)
.and_then(|face| layout.shaper.faces().get(face).copied())
.unwrap();
let (line, descent) = (face.line_height(), face.win_line() - face.win_top());
let items = layout
.chart_title(&title(&["Ab", "", "Wide"]), frame)
.unwrap();
let runs: Vec<_> = items
.into_iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some(run),
_ => None,
})
.collect();
assert_eq!(runs.len(), 2);
let first = frame.top + CHART_TITLE_LINE_TOP + line - descent;
assert_eq!(runs[0].glyphs[0].y, first);
assert_eq!(runs[1].glyphs[0].y, first + line * 2);
for (run, shown) in runs.iter().zip(["Ab", "Wide"]) {
let width = layout
.chart_text(&super::chart_props(&chart, 28), shown)
.unwrap()
.width();
let middle = (frame.left + frame.right).div_toward_zero(2);
assert_eq!(run.glyphs[0].x, middle - width.div_toward_zero(2));
}
let narrow = Edges {
right: frame.left + points(5),
..frame
};
assert!(layout.chart_title(&title(&["Wide"]), narrow).is_none());
let kept = Title {
text: None,
..title(&["Ab"])
};
assert!(layout.chart_title(&kept, frame).is_none());
},
);
}
#[test]
fn puts_a_title_at_the_corner_of_its_manual_layout_centered_on_its_widest_line() {
use crate::chart::{Decimal, LayoutCorner, TitleText};
use crate::params::{CHART_TITLE_CORNER_LEFT, CHART_TITLE_CORNER_TOP};
let part = |digits| Decimal {
digits,
exponent: -2,
};
let title = |x| Title {
lines: 2,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: Some(TitleText {
lines: vec!["Ab".to_owned(), "Wide".to_owned()],
font: FontRef::MinorLatin,
bold: false,
italic: false,
fill: None,
}),
corner: Some(LayoutCorner {
x: part(x),
y: part(5),
}),
};
let frame = Edges {
left: points(10),
top: points(20),
right: points(442),
bottom: points(280),
};
let chart = columns(219, -27);
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let props = super::chart_props(&chart, 28);
let face = layout
.shaper
.face(&props, true)
.and_then(|face| layout.shaper.faces().get(face).copied())
.unwrap();
let (line, descent) = (face.line_height(), face.win_line() - face.win_top());
let short = layout.chart_text(&props, "Ab").unwrap().width();
let wide = layout.chart_text(&props, "Wide").unwrap().width();
let starts = |layout: &mut crate::layout::Layout<'_>, x| {
let items = layout.chart_title(&title(x), frame).unwrap();
let runs: Vec<_> = items
.into_iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some((run.glyphs[0].x, run.glyphs[0].y)),
_ => None,
})
.collect();
runs
};
let runs = starts(layout, 25);
let first = points(33) + CHART_TITLE_CORNER_TOP + line - descent;
let left = points(118) + CHART_TITLE_CORNER_LEFT;
let middle = left + wide.div_toward_zero(2);
assert_eq!(runs[0], (middle - short.div_toward_zero(2), first));
assert_eq!(runs[1], (left, first + line));
let runs = starts(layout, 99);
assert_eq!(runs[1].0, frame.right - CHART_TITLE_CORNER_LEFT - wide);
},
);
}
#[test]
fn breaks_a_title_wider_than_its_share_of_the_frame_at_its_spaces() {
use crate::chart::TitleText;
use crate::params::{CHART_TITLE_LINE_INSET, CHART_TITLE_LINE_SHARE};
let title = |line: &str| Title {
lines: 1,
size: 28,
font: crate::props::FontRef::MinorLatin,
text: Some(TitleText {
lines: vec![line.to_owned()],
font: FontRef::MinorLatin,
bold: false,
italic: false,
fill: None,
}),
corner: None,
};
let chart = columns(219, -27);
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let props = super::chart_props(&chart, 28);
let two = layout.chart_text(&props, "Ab Cd").unwrap().width();
let three = layout.chart_text(&props, "Ab Cd Ef").unwrap().width();
let width = (two + CHART_TITLE_LINE_INSET)
.checked_mul(1000)
.unwrap()
.div_toward_zero(CHART_TITLE_LINE_SHARE)
+ points(1);
let frame = Edges {
left: points(10),
top: points(20),
right: points(10) + width,
bottom: points(272),
};
let limit = width
.checked_mul(CHART_TITLE_LINE_SHARE)
.unwrap()
.div_toward_zero(1000)
- CHART_TITLE_LINE_INSET;
assert!(two <= limit && three > limit);
let items = layout.chart_title(&title("Ab Cd Ef"), frame).unwrap();
let runs: Vec<_> = items
.into_iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some(run),
_ => None,
})
.collect();
let shown: Vec<usize> = runs.iter().map(|run| run.glyphs.len()).collect();
assert_eq!(shown, [5, 2]);
let face = layout
.shaper
.face(&props, true)
.and_then(|face| layout.shaper.faces().get(face).copied())
.unwrap();
assert_eq!(
runs[1].glyphs[0].y - runs[0].glyphs[0].y,
face.line_height()
);
assert_eq!(layout.title_line_count(&title("Ab Cd Ef"), frame), Some(2));
assert!(layout.chart_title(&title("Ab Cd Ef"), frame).is_none());
assert_eq!(layout.title_line_count(&title("Ab Cd Ef"), frame), Some(1));
assert_eq!(layout.title_line_count(&title("Ab Cd"), frame), Some(1));
},
);
}
#[test]
fn takes_as_many_x_units_as_the_frame_holds_at_seven_and_a_half_zeros() {
use super::scatter::x_units;
let zero = points(5);
assert_eq!(x_units(points(172), zero), 4);
assert_eq!(x_units(points(171), zero), 3);
assert_eq!(x_units(points(10), zero), 1);
assert_eq!(x_units(points(1_000), zero), 10);
assert_eq!(x_units(points(172), Length::ZERO), 10);
}
fn five_points(group: ChartGroup) -> Columns {
let one = Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
values: ["3", "5", "1", "8", "4"].map(|v| Some(decimal(v))).to_vec(),
name: None,
labels: SeriesLabels::Hidden,
};
Columns {
legend: None,
..Columns::plain(vec![one], 5, group, None)
}
}
fn quarter_x_values() -> Vec<Vec<Decimal>> {
vec![["0", "2.25", "4.5", "6.75", "9"].map(decimal).to_vec()]
}
fn plain_look() -> LineLook {
LineLook {
width: Some(StyleWidth::Set(points(1))),
marker: None,
form: LineForm::Straight,
dash: None,
}
}
#[test]
fn ends_a_scatter_charts_plot_area_half_its_last_x_label_left_of_its_twins() {
use super::scatter::x_units;
let scatter = five_points(ChartGroup::Scatter {
looks: vec![plain_look()],
x_values: quarter_x_values(),
x_scale: SetScale::default(),
});
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(300),
bottom: points(216),
};
let plot = Edges {
left: points(21),
top: points(10),
right: points(289),
bottom: points(180),
};
let props = super::chart_props(&scatter, scatter.label_size);
let zero = layout.chart_text(&props, "0").unwrap().width();
let (axis, right) = layout
.x_axis(
&scatter,
(&quarter_x_values(), SetScale::default()),
(frame, plot),
)
.unwrap();
assert!(axis.steps <= x_units(points(300), zero));
assert_eq!(axis.low, decimal("0"));
assert!(axis.high >= decimal("9.45"));
let last = all_digits(axis.label(axis.steps).unwrap());
let width = layout.chart_text(&props, &last).unwrap().width();
assert_eq!(right, plot.right - width.div_toward_zero(2));
let span = (plot.left, right);
assert_eq!(layout.place(&axis, span, axis.low), Some(plot.left));
assert_eq!(layout.place(&axis, span, axis.high), Some(right));
},
);
}
#[test]
fn draws_a_scatter_chart_with_its_line_chart_twins_value_labels_and_its_x_labels() {
let twin = five_points(ChartGroup::Lines {
looks: vec![plain_look()],
stacking: crate::chart::BarStacking::Clustered,
});
let scatter = five_points(ChartGroup::Scatter {
looks: vec![plain_look()],
x_values: quarter_x_values(),
x_scale: SetScale::default(),
});
let twin_runs = label_runs(&twin, ChartPlotArea::FontLines);
let runs = label_runs(&scatter, ChartPlotArea::FontLines);
assert!(twin_runs.len() >= 2);
assert_eq!(runs.get(..twin_runs.len()), Some(&twin_runs[..]));
assert_x_labels(runs.get(twin_runs.len()..).unwrap_or_default(), &twin_runs);
assert_eq!(all_text(&scatter, ChartPlotArea::FontLines), Some(true));
}
fn assert_x_labels(
x_labels: &[(String, Length, Length)],
value_labels: &[(String, Length, Length)],
) {
assert!(x_labels.len() >= 2);
assert_eq!(x_labels[0].0, "0");
let baseline = x_labels[0].2;
assert!(x_labels.iter().all(|label| label.2 == baseline));
assert!(value_labels.iter().all(|label| label.2 < baseline));
assert!(x_labels.windows(2).all(|pair| pair[0].1 < pair[1].1));
}
#[test]
fn clips_a_scatter_charts_lines_on_the_dots_to_its_plot_area_and_three_quarters_of_a_point_more() {
use crate::params::CHART_SCATTER_CLIP_ROOM;
use f_office_paint::GroupClip;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let dot = layout.device.dots(1).units();
let at = Length::from_units;
let plot = Edges {
left: at(dot * 100 + dot / 2),
top: at(dot * 40 + 1),
right: at(dot * 900 + dot / 3),
bottom: at(dot * 500),
};
let down = |units: i64| units.div_euclid(dot) * dot;
let room = CHART_SCATTER_CLIP_ROOM.units();
let right = down(dot * 900 + dot / 3 + room);
let bottom = down(dot * 500 + room);
assert_eq!(
layout.lines_clip(plot),
GroupClip::rect(
at(dot * 100),
at(dot * 40),
at(right - dot * 100),
at(bottom - dot * 40)
)
);
},
);
}
fn groups_of(chart: &Columns) -> Vec<(bool, usize)> {
let (items, _) = font_line_items(chart);
items
.iter()
.filter_map(|item| match item {
Item::Group(group) => Some((group.clip.is_some(), group.items.len())),
_ => None,
})
.collect()
}
#[test]
fn draws_each_scatter_line_alone_in_a_clip_and_a_line_charts_without_one() {
let scatter = five_points(ChartGroup::Scatter {
looks: vec![plain_look()],
x_values: quarter_x_values(),
x_scale: SetScale::default(),
});
assert_eq!(groups_of(&scatter), vec![(true, 1)]);
let twin = five_points(ChartGroup::Lines {
looks: vec![plain_look()],
stacking: crate::chart::BarStacking::Clustered,
});
assert_eq!(groups_of(&twin), Vec::new());
}
fn axis_and_first_line(chart: &Columns, order: ChartAxisOrder) -> (Option<usize>, Option<usize>) {
let axis_color = Rgb { r: 1, g: 2, b: 3 };
let chart = Columns {
axis: ShapeLook::plain(Geometry::Line, None, Some((axis_color, points(1)))),
..chart.clone()
};
let mut out = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines).with_variant(order),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
out = layout.columns(&chart, frame).map(|(items, _)| items);
},
);
let items = out.unwrap();
let axis = items
.iter()
.position(|item| matches!(item, Item::Rect(rect) if rect.color == axis_color));
let line = items
.iter()
.position(|item| !matches!(item, Item::Rect(_) | Item::Glyphs(_)));
(axis, line)
}
#[test]
fn paints_the_axis_line_across_before_the_series_lines_where_the_target_does() {
let scatter = five_points(ChartGroup::Scatter {
looks: vec![plain_look()],
x_values: quarter_x_values(),
x_scale: SetScale::default(),
});
let twin = five_points(ChartGroup::Lines {
looks: vec![plain_look()],
stacking: crate::chart::BarStacking::Clustered,
});
for chart in [&scatter, &twin] {
let (axis, line) = axis_and_first_line(chart, ChartAxisOrder::BeforeLines);
assert!(axis.is_some() && line.is_some() && axis < line);
let (axis, line) = axis_and_first_line(chart, ChartAxisOrder::Unknown);
assert!(axis.is_some() && line.is_some() && axis > line);
}
}
fn tenths(x: i64, y: i64) -> f_office_paint::Point {
f_office_paint::Point {
x: Length::from_units(x * Length::UNITS_PER_POINT / 10),
y: Length::from_units(y * Length::UNITS_PER_POINT / 10),
}
}
#[test]
fn puts_a_smooth_lines_control_points_along_its_tangents() {
use super::smooth::curves;
let (first, inner, last) = (tenths(0, 0), tenths(60, 0), tenths(216, 288));
assert_eq!(
curves(&[first, inner, last]),
vec![
[first, tenths(10, 0), tenths(42, -24), inner],
[inner, tenths(96, 48), tenths(164, 192), last],
]
);
assert_eq!(
curves(&[first, inner]),
vec![[first, tenths(20, 0), tenths(40, 0), inner]]
);
assert_eq!(curves(&[first]).len(), 0);
}
#[test]
fn draws_a_smooth_series_in_curves_and_a_straight_one_in_pieces() {
let starts = |form| {
let chart = five_points(ChartGroup::Lines {
looks: vec![LineLook {
form,
..plain_look()
}],
stacking: crate::chart::BarStacking::Clustered,
});
let mut out = None;
with_layout_on(
|p| {
p.with_variant(ChartPlotArea::FontLines)
.with_variant(ChartAxisOrder::BeforeLines)
},
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
out = layout.columns(&chart, frame).map(|(items, _)| items);
},
);
let items = out.unwrap();
let line = items.iter().find_map(|item| match item {
Item::Path(path) => Some(path),
_ => None,
});
line.unwrap()
.commands
.iter()
.filter(|command| matches!(command, f_office_paint::PathCommand::MoveTo(_)))
.count()
};
assert_eq!(starts(LineForm::Straight), 4 + 5);
assert_eq!(starts(LineForm::Smooth), 4 * 16 + (4 * 16 + 1));
}
#[test]
fn shortens_each_dash_of_a_preset_by_a_width_and_lengthens_each_gap() {
use super::dash_lengths;
use crate::chart::LineDash;
let width = Length::from_emus(28_575).unwrap();
let quarters = |list: &[i64]| -> Vec<Length> {
list.iter()
.map(|&q| Length::from_units(q * Length::UNITS_PER_POINT / 4))
.collect()
};
assert_eq!(
dash_lengths(LineDash::Dash, width),
Some(quarters(&[27, 36]))
);
assert_eq!(
dash_lengths(LineDash::SystemDot, width),
Some(quarters(&[0, 18]))
);
assert_eq!(
dash_lengths(LineDash::LongDashDotDot, width),
Some(quarters(&[63, 36, 0, 36, 0, 36]))
);
}
#[test]
fn draws_a_dashed_series_line_as_its_dashes_and_leaves_out_a_chart_of_too_many() {
use crate::chart::LineDash;
let starts = |width: Length, dash: Option<LineDash>| {
let chart = five_points(ChartGroup::Lines {
looks: vec![LineLook {
width: Some(StyleWidth::Set(width)),
dash,
..plain_look()
}],
stacking: crate::chart::BarStacking::Clustered,
});
let mut out = None;
with_layout_on(
|p| {
p.with_variant(ChartPlotArea::FontLines)
.with_variant(ChartAxisOrder::BeforeLines)
},
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
out = Some(layout.columns(&chart, frame).map(|(items, _)| items));
},
);
out.unwrap().map(|items| {
let line = items.iter().find_map(|item| match item {
Item::Path(path) => Some(path),
_ => None,
});
line.unwrap()
.commands
.iter()
.filter(|command| matches!(command, f_office_paint::PathCommand::MoveTo(_)))
.count()
})
};
let solid = starts(points(1), None).unwrap();
assert_eq!(solid, 4 + 5);
let dots = starts(points(1), Some(LineDash::SystemDot)).unwrap();
assert!(dots > 2 * 150 && dots % 2 == 0, "{dots}");
assert_eq!(
starts(Length::from_units(1), Some(LineDash::SystemDot)),
None
);
}
#[test]
fn clips_a_line_charts_lines_where_the_target_does() {
use crate::quirks::ChartLineClip;
let groups = |clip: ChartLineClip| {
let chart = five_points(ChartGroup::Lines {
looks: vec![plain_look()],
stacking: crate::chart::BarStacking::Clustered,
});
let mut out = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines).with_variant(clip),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
out = layout.columns(&chart, frame).map(|(items, _)| items);
},
);
out.unwrap()
.iter()
.filter_map(|item| match item {
Item::Group(group) => Some((group.clip.is_some(), group.items.len())),
_ => None,
})
.collect::<Vec<_>>()
};
assert_eq!(groups(ChartLineClip::PlotArea), vec![(true, 1)]);
assert_eq!(groups(ChartLineClip::Unknown), Vec::new());
}
fn three_reds(group: ChartGroup) -> Columns {
let series = (1_u8..=3)
.map(|red| Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb { r: red, g: 0, b: 0 })),
values: vec![
Some(decimal(&red.to_string())),
Some(decimal(&(red + 3).to_string())),
],
name: Some(["A", "B", "C"][usize::from(red - 1)].to_owned()),
labels: SeriesLabels::Hidden,
})
.collect();
Columns {
category_names: Some(vec!["North".to_owned(), "South".to_owned()]),
..Columns::plain(series, 2, group, None)
}
}
fn reds_of(items: &[Item]) -> Vec<(u8, f_office_paint::Rect)> {
items
.iter()
.filter_map(|item| match item {
Item::Rect(rect) if rect.color.g == 0 && rect.color.b == 0 && rect.color.r > 0 => {
Some((rect.color.r, rect.clone()))
}
_ => None,
})
.collect()
}
fn upward_gradient() -> LinearGradient {
let xml = format!(
r#"<a:gradFill xmlns:a="{}" rotWithShape="1"><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs><a:gs pos="80000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:lin ang="16200000" scaled="0"/></a:gradFill>"#,
crate::ns::A
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
LinearGradient::read(&doc, doc.root().unwrap(), &mut Warnings::new()).unwrap()
}
fn gradient_box(item: &GradientItem) -> (Point, Point) {
match item.commands[..] {
[
PathCommand::MoveTo(top_left),
_,
PathCommand::LineTo(bottom_right),
..,
] => (top_left, bottom_right),
_ => panic!("not a box"),
}
}
fn gradients_of(items: &[Item]) -> Vec<&GradientItem> {
items
.iter()
.filter_map(|item| match item {
Item::Gradient(gradient) => Some(gradient),
_ => None,
})
.collect()
}
fn rect_box(rect: &f_office_paint::Rect) -> (Point, Point) {
(
Point {
x: rect.x,
y: rect.y,
},
Point {
x: rect.x + rect.width,
y: rect.y + rect.height,
},
)
}
fn assert_bar_beside_twin(gradient: &GradientItem, twin: (Point, Point)) {
let near = |a: Point, b: Point| {
(a.x - b.x).units().abs() < Length::UNITS_PER_DOT
&& (a.y - b.y).units().abs() < Length::UNITS_PER_DOT
};
let (top_left, bottom_right) = gradient_box(gradient);
assert!(near(top_left, twin.0) && near(bottom_right, twin.1));
assert_eq!(bottom_right.y, twin.1.y);
let middle = (top_left.x + bottom_right.x).div_toward_zero(2);
assert_eq!(gradient.start.x, gradient.end.x);
assert!((gradient.start.x - middle).units().abs() <= 1);
assert_eq!(
(gradient.start.y, gradient.end.y),
(bottom_right.y, top_left.y)
);
}
#[test]
fn paints_a_gradient_series_at_its_exact_places_and_its_key_over_the_key() {
let solid = three_reds(ChartGroup::Columns {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
let mut chart = solid.clone();
chart.series[1].fill = SeriesFill::Gradient(upward_gradient());
let solid_reds = reds_of(&font_line_items(&solid).0);
let (items, _) = font_line_items(&chart);
let gradients = gradients_of(&items);
assert_eq!(gradients.len(), 3);
assert_eq!(reds_of(&items).len(), 6);
let twins: Vec<_> = solid_reds
.iter()
.filter(|(red, _)| *red == 2)
.map(|(_, rect)| rect_box(rect))
.collect();
for (gradient, twin) in gradients.iter().zip(&twins) {
assert_bar_beside_twin(gradient, *twin);
}
assert!(
gradients
.iter()
.take(2)
.zip(&twins)
.any(|(gradient, twin)| gradient_box(gradient) != *twin)
);
assert_eq!(gradient_box(gradients[2]), twins[2]);
}
fn run<'a>(runs: &[(&'a str, Length, Length)], text: &str) -> (&'a str, Length, Length) {
runs.iter()
.find(|(found, _, _)| *found == text)
.copied()
.unwrap()
}
#[test]
fn turns_the_bars_of_a_horizontal_bar_chart_up_from_the_bottom() {
let chart = three_reds(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
let (items, _) = font_line_items(&chart);
let reds = reds_of(&items);
assert_eq!(reds.len(), 9);
let bars = &reds[..6];
let bar = |red: u8, category: usize| bars[usize::from(red - 1) * 2 + category].1.clone();
assert!(
bars.iter()
.zip([1, 1, 2, 2, 3, 3])
.all(|(found, red)| found.0 == red)
);
assert!(bars.iter().all(|(_, rect)| rect.x == bars[0].1.x));
let mut by_value: Vec<_> = (1..=3)
.flat_map(|red| [(red, bar(red, 0)), (red + 3, bar(red, 1))])
.collect();
by_value.sort_by_key(|&(value, _)| value);
assert!(
by_value
.windows(2)
.all(|two| two[0].1.width < two[1].1.width)
);
assert!((1..=3).all(|red| bar(red, 0).y > bar(3, 1).y + bar(3, 1).height));
assert!((1..3).all(|red| bar(red, 0).y > bar(red + 1, 0).y));
assert!((1..3).all(|red| bar(red, 1).y > bar(red + 1, 1).y));
}
#[test]
fn names_the_series_of_a_horizontal_bar_chart_in_the_reverse_order_in_its_legend() {
let chart = three_reds(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
let (items, _) = font_line_items(&chart);
let reds = reds_of(&items);
assert_eq!(reds.len(), 9);
let mut keys = reds[6..].to_vec();
keys.sort_by_key(|(_, rect)| rect.x);
assert_eq!(
keys.iter().map(|(red, _)| *red).collect::<Vec<_>>(),
[3, 2, 1]
);
let names: Vec<_> = runs_of(&items)
.into_iter()
.filter(|(text, _, _)| ["A", "B", "C"].contains(text))
.map(|(text, _, _)| text)
.collect();
assert_eq!(names, ["C", "B", "A"]);
}
#[test]
fn draws_the_value_labels_of_horizontal_bars_across_the_bottom_and_the_categories_at_the_left() {
let chart = three_reds(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
let twin = three_reds(ChartGroup::Columns {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
let (items, lines) = font_line_items(&chart);
let runs = runs_of(&items);
let (twin_items, _) = font_line_items(&twin);
let twin_runs = runs_of(&twin_items);
let values: Vec<_> = runs
.iter()
.filter(|(text, _, _)| text.parse::<i64>().is_ok())
.collect();
assert!(values.len() >= 4 && values[0].0 == "0");
assert!(
values
.windows(2)
.all(|two| two[0].1 < two[1].1 && two[0].2 == two[1].2)
);
assert_eq!(values[0].2, run(&twin_runs, "North").2);
let (north, south) = (run(&runs, "North"), run(&runs, "South"));
assert!(north.1 < values[0].1 && north.2 > south.2);
let band = north.2 - south.2;
assert!(band > lines.line);
assert_eq!(all_text(&chart, ChartPlotArea::FontLines), Some(true));
}
#[test]
fn centers_the_data_labels_of_horizontal_bars_on_their_bars_and_keeps_the_gap_beyond_them() {
let place = |insets: Edges<Length>| {
let mut chart = three_reds(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
chart.series[0].labels = SeriesLabels::Values(DataLabelText {
position: crate::chart::DataLabelPosition::Default,
size: 18,
font: FontRef::MinorLatin,
fill: None,
insets,
format: LabelFormat::all_digits(),
parts: crate::chart::DataLabelParts::default(),
show_default: true,
point_overrides: Vec::new(),
});
let (runs, all) = data_label_runs(&chart, ChartDataLabels::OuterEnd, "1");
assert_eq!(all, Some(true));
runs[0]
};
let none = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: Length::ZERO,
bottom: Length::ZERO,
};
let plain = place(none);
let left = place(Edges {
left: points(1),
..none
});
assert_eq!(left, (plain.0 + points(1), plain.1));
assert_eq!(
place(Edges {
right: points(1),
..none
}),
plain
);
let half = points(1).div_toward_zero(2);
assert_eq!(
place(Edges {
top: points(1),
..none
}),
(plain.0, plain.1 + half)
);
assert_eq!(
place(Edges {
bottom: points(1),
..none
}),
(plain.0, plain.1 - half)
);
}
#[test]
fn puts_the_legend_of_horizontal_bars_at_the_right_where_the_twins_stands() {
let at_right = |group| Columns {
legend: Some(LegendPlace::Right),
..three_reds(group)
};
let left_edges = |chart: &Columns| {
let (items, _) = font_line_items(chart);
let reds = reds_of(&items);
let keys = &reds[reds.len() - 3..];
keys.iter().map(|(_, rect)| rect.x).collect::<Vec<_>>()
};
let bars = left_edges(&at_right(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
}));
let twin = left_edges(&at_right(ChartGroup::Columns {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
}));
assert_eq!(bars, twin);
}
fn with_deleted_value_axis(shown: &Columns) -> Columns {
Columns {
axis_forms: AxisForms {
value_deleted: true,
..AxisForms::default()
},
..shown.clone()
}
}
const DELETED_AXIS_LEGENDS: [(Option<LegendPlace>, Option<Title>); 3] = [
(Some(LegendPlace::Bottom), None),
(None, None),
(Some(LegendPlace::Right), None),
];
#[test]
fn gives_the_room_of_a_deleted_value_axis_to_the_plot_area_on_font_lines() {
let shown = drawn_text_columns();
let deleted = with_deleted_value_axis(&shown);
let shown_plots = font_line_plots(&shown, &DELETED_AXIS_LEGENDS);
let deleted_plots = font_line_plots(&deleted, &DELETED_AXIS_LEGENDS);
for (shown, deleted) in shown_plots.into_iter().zip(deleted_plots) {
let (shown, deleted) = (shown.unwrap(), deleted.unwrap());
assert_eq!(
deleted,
Edges {
left: CHART_PLOT_RIGHT,
..shown
}
);
assert!(shown.left > deleted.left);
}
}
#[test]
fn draws_no_value_labels_of_a_deleted_value_axis_and_keeps_the_category_labels() {
let shown = drawn_text_columns();
let deleted = with_deleted_value_axis(&shown);
let texts = |chart| {
label_runs(chart, ChartPlotArea::FontLines)
.into_iter()
.map(|run| run.0)
.collect::<Vec<_>>()
};
let numbers = |texts: &[String]| texts.iter().filter(|t| t.parse::<f64>().is_ok()).count();
assert!(numbers(&texts(&shown)) > 0);
let deleted_texts = texts(&deleted);
assert_eq!(numbers(&deleted_texts), 0);
assert!(deleted_texts.contains(&"One".to_owned()));
assert_eq!(all_text(&deleted, ChartPlotArea::FontLines), Some(true));
}
#[test]
fn places_the_inner_box_of_a_manual_layout_beside_a_deleted_value_axis() {
let deleted = with_deleted_value_axis(&drawn_text_columns());
let manual = |inner| Columns {
plot_place: PlotPlace::Manual(PlotLayout {
inner,
edges: plot_box(),
}),
..deleted.clone()
};
let legends = &DELETED_AXIS_LEGENDS[..1];
let inner = font_line_plots(&manual(true), legends);
assert_eq!(
inner[0].map(|plot| plot.left),
Some(Length::from_emus(548_640).unwrap())
);
assert_eq!(font_line_plots(&manual(false), legends), [None]);
}
#[test]
fn ends_the_bars_of_a_deleted_value_axis_at_the_column_charts_right_edge() {
let shown = Columns {
scale: SetScale {
max: Some(decimal("6")),
..SetScale::default()
},
..three_reds(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
})
};
let deleted = Columns {
axis_forms: AxisForms {
value_deleted: true,
..AxisForms::default()
},
..shown.clone()
};
let bars = |chart: &Columns| {
let (items, _) = font_line_items(chart);
reds_of(&items)[..6].to_vec()
};
let (shown_bars, deleted_bars) = (bars(&shown), bars(&deleted));
assert!(
shown_bars
.iter()
.zip(&deleted_bars)
.all(|(a, b)| a.1.x == b.1.x && a.1.width < b.1.width && a.1.y < b.1.y)
);
let longest = deleted_bars
.iter()
.map(|(_, rect)| rect.x + rect.width)
.max()
.unwrap();
let right = points(432) - CHART_PLOT_RIGHT;
assert!(longest.max(right) - longest.min(right) <= points(1));
let runs = runs_of(&font_line_items(&deleted).0)
.into_iter()
.filter(|(text, _, _)| text.parse::<f64>().is_ok())
.count();
assert_eq!(runs, 0);
assert_eq!(all_text(&deleted, ChartPlotArea::FontLines), Some(true));
}
#[test]
fn draws_low_category_labels_below_the_plot_area_on_font_lines() {
let mut inside = drawn_text_columns();
inside.series[0].values[0] = Some(decimal("-1"));
let low = Columns {
axis_forms: AxisForms {
low_labels: true,
..AxisForms::default()
},
..inside.clone()
};
let cases = [(Some(LegendPlace::Bottom), None)];
let above_zero = font_line_plots(&drawn_text_columns(), &cases)[0].unwrap();
let inside_plot = font_line_plots(&inside, &cases)[0].unwrap();
let low_plot = font_line_plots(&low, &cases)[0].unwrap();
assert_eq!(low_plot.bottom, above_zero.bottom);
assert!(inside_plot.bottom > low_plot.bottom);
let runs = label_runs(&low, ChartPlotArea::FontLines);
let lines = font_line_items(&low).1;
let one = run(
&runs
.iter()
.map(|(text, x, y)| (text.as_str(), *x, *y))
.collect::<Vec<_>>(),
"One",
);
assert_eq!(one.2, low_plot.bottom + lines.category_baseline().unwrap());
assert_eq!(all_text(&low, ChartPlotArea::FontLines), Some(true));
assert_eq!(all_text(&inside, ChartPlotArea::FontLines), Some(true));
let inside_runs = label_runs(&inside, ChartPlotArea::FontLines);
let inside_one = run(
&inside_runs
.iter()
.map(|(text, x, y)| (text.as_str(), *x, *y))
.collect::<Vec<_>>(),
"One",
);
assert!(inside_one.2 < one.2);
}
#[test]
fn cuts_a_pie_into_the_shares_of_its_values_from_its_first_angle() {
let values = |all: &[i64]| -> Vec<Option<Decimal>> {
all.iter()
.map(|&digits| {
Some(Decimal {
digits,
exponent: 0,
})
})
.collect()
};
assert_eq!(
super::pie::slice_angles(&values(&[1, 2, 1]), 0),
Some(vec![
(-5_400_000, 5_400_000),
(0, 10_800_000),
(10_800_000, 5_400_000)
])
);
assert_eq!(
super::pie::slice_angles(&values(&[1, 1, 1]), 90),
Some(vec![
(0, 7_200_000),
(7_200_000, 7_200_000),
(14_400_000, 7_200_000)
])
);
assert_eq!(super::pie::slice_angles(&values(&[0, 0]), 0), None);
assert_eq!(super::pie::slice_angles(&values(&[2, -1]), 0), None);
}
#[test]
fn draws_a_3d_pie_as_one_picture_of_its_plot_area() {
use crate::chart::PieView;
use f_office_paint::ImageFormat;
let hundredths = |value: i64| Length::from_units(value * Length::UNITS_PER_POINT / 100);
let plot = Edges {
left: hundredths(8_300),
top: hundredths(9_644),
right: hundredths(8_300 + 40_998),
bottom: hundredths(9_644 + 22_998),
};
let view = PieView {
tilt: 30,
field_of_view: 15,
};
let colors = [
Rgb {
r: 68,
g: 114,
b: 196,
},
Rgb {
r: 237,
g: 125,
b: 49,
},
];
let angles = [(-5_400_000, 12_600_000), (7_200_000, 9_000_000)];
let Item::Image(picture) = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0, 0])
.unwrap()
.item()
else {
panic!("no picture");
};
assert_eq!((picture.x, picture.y), (plot.left, plot.top));
assert_eq!(picture.width, plot.right - plot.left);
assert_eq!(picture.height, plot.bottom - plot.top);
assert_eq!(picture.image.format, ImageFormat::EffectPicture);
let drawn = f_office_effects::draw(&picture.image.load_bytes().unwrap(), u64::MAX).unwrap();
assert_eq!((drawn.width, drawn.height), (1140, 640));
}
#[test]
fn shrinks_the_picture_of_a_3d_pie_whose_labels_may_stand_outside() {
use crate::chart::PieView;
let hundredths = |value: i64| Length::from_units(value * Length::UNITS_PER_POINT / 100);
let plot = Edges {
left: hundredths(8_300),
top: hundredths(9_644),
right: hundredths(8_300 + 40_998),
bottom: hundredths(9_644 + 22_998),
};
let view = PieView {
tilt: 30,
field_of_view: 15,
};
let angles = [(-5_400_000, 21_600_000)];
let colors = [Rgb { r: 0, g: 0, b: 0 }];
assert_eq!(super::pie::picture_plot(plot, false), Some(plot));
let shrunk = super::pie::picture_plot(plot, true).unwrap();
let middle = |low: Length, high: Length| (low + high).div_toward_zero(2);
let close = |a: Length, b: Length| (a - b).units().abs() <= 1;
assert!(close(
middle(shrunk.left, shrunk.right),
middle(plot.left, plot.right)
));
assert!(close(
middle(shrunk.top, shrunk.bottom),
middle(plot.top, plot.bottom)
));
let Item::Image(picture) = super::pie::PiePicture::of(shrunk, view, &angles, &colors, &[0])
.unwrap()
.item()
else {
panic!("no picture");
};
let drawn = f_office_effects::draw(&picture.image.load_bytes().unwrap(), u64::MAX).unwrap();
assert_eq!((drawn.width, drawn.height), (990, 552));
}
#[test]
fn puts_a_3d_pie_of_a_manual_layout_over_its_box_inner_or_outer() {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(400),
bottom: points(200),
};
let manual = |inner| Columns {
plot_place: PlotPlace::Manual(PlotLayout {
inner,
edges: plot_box(),
}),
..drawn_text_columns()
};
let mut plots = Vec::new();
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
for (inner, three_d) in [(true, true), (false, true), (true, false)] {
let plot = layout.pie_plot(&manual(inner), frame, three_d);
plots.push(plot.map(|(plot, _)| plot));
}
},
);
let expected = Edges {
left: points(40),
top: points(30),
right: points(360),
bottom: points(150),
};
assert_eq!(plots, [Some(expected), Some(expected), None]);
}
#[test]
fn centers_the_labels_of_a_3d_pie_on_its_top_face() {
use crate::chart::PieView;
let plot = Edges {
left: points(100),
top: points(100),
right: points(500),
bottom: points(300),
};
let view = PieView {
tilt: 30,
field_of_view: 15,
};
let angles = [(-5_400_000, 21_600_000)];
let colors = [Rgb { r: 0, g: 0, b: 0 }];
let picture = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0]).unwrap();
let at = |degrees: i64| picture.label_center(degrees * 60_000, 0).unwrap();
let (right, near, left, far) = (at(0), at(90), at(180), at(270));
let middle = points(300);
assert_eq!(right.y, left.y);
assert_eq!((right.x - middle) + (left.x - middle), Length::ZERO);
assert!((near.x - middle).units().abs() <= 1 && (far.x - middle).units().abs() <= 1);
assert!(near.y - right.y > right.y - far.y);
assert!(far.y > plot.top && near.y < plot.bottom);
}
#[test]
fn shifts_a_3d_pie_label_center_outward_when_its_slice_is_pulled_out() {
use crate::chart::PieView;
let plot = Edges {
left: points(100),
top: points(100),
right: points(500),
bottom: points(300),
};
let view = PieView {
tilt: 30,
field_of_view: 15,
};
let angles = [(-5_400_000, 10_800_000), (5_400_000, 10_800_000)];
let colors = [
Rgb { r: 0, g: 0, b: 0 },
Rgb {
r: 100,
g: 100,
b: 100,
},
];
let plain = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0, 0]).unwrap();
let pulled = super::pie::PiePicture::of(plot, view, &angles, &colors, &[25, 0]).unwrap();
assert!(pulled.label_center(0, 25).unwrap().x > plain.label_center(0, 0).unwrap().x);
assert!(pulled.label_center(0, 0).unwrap().x < plain.label_center(0, 0).unwrap().x);
}
#[test]
fn places_3d_pie_labels_at_inner_end_and_outer_end() {
use crate::chart::{PieLabelPlace, PieView};
let plot = Edges {
left: points(100),
top: points(100),
right: points(500),
bottom: points(300),
};
let view = PieView {
tilt: 30,
field_of_view: 15,
};
let angles = [(-5_400_000, 21_600_000)];
let colors = [Rgb { r: 0, g: 0, b: 0 }];
let picture = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0]).unwrap();
let size = (points(18), points(10));
let at = |place, degrees: i64| picture.label_box_center(place, degrees * 60_000, 0, size);
let center_right = at(PieLabelPlace::Center, 0).unwrap();
let inner_right = at(PieLabelPlace::InnerEnd, 0).unwrap();
let outer_right = at(PieLabelPlace::OuterEnd, 0).unwrap();
assert!(inner_right.x > center_right.x && outer_right.x > inner_right.x);
let inner_front = at(PieLabelPlace::InnerEnd, 90).unwrap();
let outer_front = at(PieLabelPlace::OuterEnd, 90).unwrap();
let inner_back = at(PieLabelPlace::InnerEnd, 270).unwrap();
let outer_back = at(PieLabelPlace::OuterEnd, 270).unwrap();
assert!(outer_front.y > inner_front.y && outer_back.y < inner_back.y);
assert_eq!(at(PieLabelPlace::BestFit, 0), None);
}
#[test]
fn lists_categories_in_forward_order_for_varied_single_series_bar_legend() {
use crate::chart::{ChartGroup, SeriesFill};
use f_office_drawingml::color::{DrawColor, SchemeSlot};
let fills = vec![
DrawColor::scheme(SchemeSlot::Accent1),
DrawColor::scheme(SchemeSlot::Accent2),
];
let mut chart = drawn_text_columns();
chart.group = ChartGroup::Bars {
gap: 150,
overlap: 0,
stacking: crate::chart::BarStacking::Clustered,
};
chart.category_names = Some(vec!["Cat 1".to_owned(), "Cat 2".to_owned()]);
chart.series.truncate(1);
chart.series[0].fill = SeriesFill::Points(fills);
let names: Vec<_> = super::legend::legend_entries(&chart)
.into_iter()
.map(|(name, _)| name)
.collect();
assert_eq!(names, vec![Some("Cat 1"), Some("Cat 2")]);
}
#[test]
fn shrinks_a_2d_pie_by_series_explosion_and_shifts_each_slice_apex() {
use f_office_paint::Point;
let base = points(100);
assert_eq!(super::pie::exploded_radius(base, 0), Some(points(100)));
assert_eq!(super::pie::exploded_radius(base, 25), Some(points(80)));
let center = Point {
x: points(200),
y: points(200),
};
let shifted = super::pie::slice_center(center, points(80), 0, 25).unwrap();
assert_eq!((shifted.x, shifted.y), (points(220), points(200)));
assert_eq!(
super::pie::slice_center(center, points(80), 0, 0),
Some(center)
);
}
#[test]
fn places_the_labels_of_a_pie_at_the_inner_and_the_outer_end() {
use crate::chart::PieLabelPlace;
use f_office_paint::Point;
let center = Point {
x: points(200),
y: points(200),
};
let place = |place, bisector| {
let size = (points(20), points(10));
let found = super::pie::box_center(place, (center, points(100)), bisector, size).unwrap();
(found.x - center.x, found.y - center.y)
};
assert_eq!(
place(PieLabelPlace::InnerEnd, 0),
(Length::from_units(2_192_020), Length::ZERO)
);
assert_eq!(
place(PieLabelPlace::OuterEnd, 0),
(Length::from_units(2_927_858), Length::ZERO)
);
assert_eq!(
place(PieLabelPlace::OuterEnd, 5_400_000),
(Length::ZERO, points(109))
);
let (end, _) =
f_office_drawingml::custom::circle_arc(center, points(100), [2_700_000, 0]).unwrap();
let (across, down) = (end.x - center.x, end.y - center.y);
assert_eq!(
place(PieLabelPlace::OuterEnd, 2_700_000),
(
across
+ across.checked_mul(511).unwrap().div_round(10_000)
+ Length::from_units(258_064),
down + down.div_round(25) + points(5)
)
);
}
#[test]
fn keeps_seven_eighths_of_a_pie_and_its_edge_for_labels_outside() {
assert_eq!(
super::pie::inside_labels_radius(points(117)),
Some(points(101))
);
}
fn boxed_chart(place: LegendPlace, edges: [i64; 4]) -> Columns {
let [x, y, w, h] = edges.map(|digits| Decimal {
digits,
exponent: -3,
});
Columns {
title: None,
legend: Some(place),
legend_box: LegendBox::Manual(LayoutBox { x, y, w, h }),
..named_columns()
}
}
fn boxed_keys_of(chart: &Columns, edges: [i64; 4]) -> BoxedKeys {
let (items, lines) = font_line_items(chart);
let side = lines.of_line(450).unwrap();
let gap = side.div_toward_zero(2) - hundredths(32);
let drawn = name_widths(chart, &["A", "Longer"])
.into_iter()
.map(|width| side + gap + width)
.collect();
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
let [x, y, w, h] = edges.map(|digits| Decimal {
digits,
exponent: -3,
});
BoxedKeys {
keys: keys_of(&items, side),
edges: layout_edges(frame, LayoutBox { x, y, w, h }).unwrap(),
drawn,
side,
}
}
struct BoxedKeys {
keys: Vec<(Length, Length)>,
edges: Edges<Length>,
drawn: Vec<Length>,
side: Length,
}
#[test]
fn puts_a_legend_whose_entries_fit_in_its_box_in_one_row_with_equal_spaces() {
let edges = [100, 800, 800, 150];
let BoxedKeys {
keys,
edges: area,
drawn,
side,
} = boxed_keys_of(&boxed_chart(LegendPlace::Bottom, edges), edges);
let [(first, middle), (second, other)] = keys[..] else {
panic!("{keys:?}")
};
assert_eq!(
middle,
area.top + (area.bottom - area.top).div_toward_zero(2)
);
assert_eq!(other, middle);
let into = side.div_toward_zero(2).div_toward_zero(2) + thousandths(2_763);
let counted: Vec<Length> = drawn.iter().map(|&d| d + thousandths(2_847)).collect();
let before = first - into - area.left;
let between = second - first - counted[0];
let after = area.right - (second - into + counted[1]);
assert_eq!(before, between);
let unit = Length::from_units(3);
assert!(
(-unit..=unit).contains(&(after - before)),
"{before:?} {after:?}"
);
}
#[test]
fn puts_a_legend_in_one_column_at_a_side_and_at_the_bottom_of_its_narrow_box() {
let edges = [700, 100, 100, 800];
let right = boxed_keys_of(&boxed_chart(LegendPlace::Right, edges), edges);
let bottom = boxed_keys_of(&boxed_chart(LegendPlace::Bottom, edges), edges);
let area = right.edges;
let (width, row) = (
area.right - area.left,
(area.bottom - area.top).div_toward_zero(2),
);
let widest = right.drawn[1].max(right.drawn[0]);
let half_side = right.side.div_toward_zero(2);
let left = area.left + (width - widest + half_side).div_toward_zero(2) - thousandths(170);
let middles = [
area.top + row.div_toward_zero(2),
area.top + row + row.div_toward_zero(2),
];
assert_eq!(right.keys, middles.map(|middle| (left, middle)));
let column = widest + thousandths(2_847);
let left = area.left + (width - column + half_side).div_toward_zero(2) + thousandths(2_763);
assert_eq!(bottom.keys, middles.map(|middle| (left, middle)));
}
#[test]
fn leaves_out_a_legend_in_a_box_too_low_for_its_rows_or_in_another_mode() {
let edges = [700, 100, 150, 40];
let low = boxed_keys_of(&boxed_chart(LegendPlace::Right, edges), edges);
assert_eq!(low.keys, []);
let other = Columns {
legend_box: LegendBox::Other,
..boxed_chart(LegendPlace::Right, edges)
};
assert_eq!(boxed_keys_of(&other, edges).keys, []);
}
#[test]
fn a_part_of_a_ligature_draws_no_glyph_of_a_chart_text() {
use crate::layout::testing::{LamAlef, with_layout_of};
with_layout_of(&LamAlef, crate::profile::Profile::clone, |layout| {
let props = crate::props::RunProps {
size: Some(20),
..crate::props::RunProps::default()
};
let text = layout
.chart_text(&props, "\u{0644}\u{0627}\u{064A}")
.unwrap();
assert_eq!(text.width(), points(15));
let Some(Item::Glyphs(run)) = text.item(Length::ZERO, Length::ZERO, Rgb::default()) else {
panic!("a chart text draws a glyph run");
};
let glyphs: Vec<(u32, &str, Length)> = run
.glyphs
.iter()
.map(|g| {
let range = g.text_start as usize..g.text_end as usize;
(g.id, run.text.get(range).unwrap_or(""), g.x)
})
.collect();
assert_eq!(
glyphs,
[
(900, "\u{0644}\u{0627}", Length::ZERO),
(0x064A, "\u{064A}", points(10))
]
);
});
}
#[test]
fn wraps_a_category_label_at_its_spaces_into_lines_that_fit() {
let measure = |text: &str| Some(points(i64::try_from(text.len()).unwrap_or(i64::MAX)));
let rows = |text, width| super::categories::wrapped_lines(text, points(width), measure);
let owned = |rows: &[&str]| Some(rows.iter().map(|&row| row.to_owned()).collect::<Vec<_>>());
assert_eq!(rows("Quite often able", 16), owned(&["Quite often able"]));
assert_eq!(
rows("Quite often able", 15),
owned(&["Quite often", "able"])
);
assert_eq!(
rows("Not often never able", 9),
owned(&["Not often", "never", "able"])
);
assert_eq!(rows("Commissioned services", 10), None);
}
#[test]
fn takes_a_side_of_the_square_whose_diagonal_a_length_is() {
let side = |length| super::categories::diagonal(length).map(Length::units);
let ten = points(10).units();
assert_eq!(
side(points(10)),
Some(
(i128::from(ten) * i128::from(ten) / 2)
.isqrt()
.try_into()
.unwrap_or(0)
)
);
assert_eq!(side(points(-10)), side(points(10)).map(|units| -units));
assert_eq!(side(Length::ZERO), Some(0));
}
#[test]
fn gives_turned_labels_the_height_of_their_line_box_less_a_line() {
use super::categories::{CategoryForm, diagonal};
let lines = LabelLines {
size: points(9),
line: points(12),
top: points(9),
single_top: points(9),
single_line: points(12),
};
let upright = CategoryForm::Upright(vec![vec!["a".to_owned(), "b".to_owned()]]);
assert_eq!(upright.room(lines), Some(points(12)));
assert_eq!(
CategoryForm::Diagonal(vec![points(20), points(48)]).room(lines),
diagonal(points(60)).map(|height| height - points(12))
);
assert_eq!(
CategoryForm::Vertical(points(48)).room(lines),
Some(points(36))
);
assert_eq!(
CategoryForm::Vertical(points(10)).room(lines),
Some(Length::ZERO)
);
}
#[test]
fn reaches_left_by_the_label_that_most_passes_its_middle() {
use super::categories::{CategoryForm, diagonal};
let form = CategoryForm::Diagonal(vec![points(100), points(300), Length::ZERO, points(10)]);
let reach = |width, middle| diagonal(points(width)).map(|side| side - points(middle));
assert_eq!(form.left_reach(points(400)), reach(300, 150));
let short = CategoryForm::Diagonal(vec![points(10), points(10)]);
assert_eq!(short.left_reach(points(400)), reach(10, 100));
assert_eq!(
CategoryForm::Vertical(points(300)).left_reach(points(400)),
None
);
}
fn axis_title_charts() -> [Columns; 3] {
use crate::chart::{AxisTitle, AxisTitles, TitleText};
let title = |line: &str| {
Some(Box::new(AxisTitle {
size: 20,
text: TitleText {
lines: vec![line.to_owned()],
font: FontRef::MinorLatin,
bold: false,
italic: false,
fill: None,
},
corner: None,
}))
};
let plain = Columns {
legend: None,
title: None,
..columns(219, -27)
};
let with_titles = |value, category| Columns {
axis_titles: AxisTitles::Drawn { value, category },
..plain.clone()
};
let titled = with_titles(title("Amount"), title("Quarter"));
let long = with_titles(title(&"Amount ".repeat(40)), None);
[plain, titled, long]
}
fn axis_title_frame() -> Edges<Length> {
Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
}
}
type AxisTitleLayout = ([Edges<Length>; 2], LabelLines, Vec<Item>, Option<Vec<Item>>);
fn axis_title_layout(fonts: &dyn crate::Fonts) -> AxisTitleLayout {
let [plain, titled, long] = axis_title_charts();
let frame = axis_title_frame();
let mut found = None;
crate::layout::testing::with_layout_of(
fonts,
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let mut plot = |chart: &Columns| {
let axis = ValueAxis::of(chart).unwrap();
layout.font_line_plot(chart, &axis, frame).unwrap()
};
let plots = [plot(&plain), plot(&titled)];
let axis = ValueAxis::of(&titled).unwrap();
let lines = layout.lines_of(&super::chart_props(&plain, 20)).unwrap();
let items = layout
.axis_title_items(&titled, (&axis, plots[1]), frame)
.unwrap();
let long_items = layout.axis_title_items(&long, (&axis, plots[1]), frame);
found = Some((plots, lines, items, long_items));
},
);
found.unwrap()
}
#[test]
fn takes_the_room_of_axis_titles_from_the_plot_area() {
use crate::layout::testing::{Fake, Gapped};
use crate::params::CHART_AXIS_TITLE_GAP;
for fonts in [&Fake as &dyn crate::Fonts, &Gapped] {
let ([before, after], lines, _, long_items) = axis_title_layout(fonts);
let room = lines.single_line + CHART_AXIS_TITLE_GAP;
assert_eq!(
(after.left - before.left, before.bottom - after.bottom),
(room, room)
);
assert_eq!((after.top, after.right), (before.top, before.right));
assert_eq!(long_items, None);
}
let lines = axis_title_layout(&Gapped).1;
assert_eq!(lines.single_line - lines.line, points(1));
}
fn assert_axis_title_places(fonts: &dyn crate::Fonts) {
use crate::params::{CHART_CATEGORY_TITLE_BOTTOM, CHART_VALUE_TITLE_LEFT};
let ([_, plot], lines, items, _) = axis_title_layout(fonts);
let [Item::Glyphs(value), Item::Glyphs(category)] = &items[..] else {
panic!("{items:?}");
};
assert_eq!(value.turn, Some(super::categories::UPWARD));
assert_eq!(value.glyphs[0].x, CHART_VALUE_TITLE_LEFT + lines.single_top);
assert!(value.glyphs[0].y > (plot.top + plot.bottom).div_toward_zero(2));
assert_eq!(category.turn, None);
assert_eq!(
category.glyphs[0].y,
axis_title_frame().bottom - CHART_CATEGORY_TITLE_BOTTOM - (lines.line - lines.top)
);
assert!(category.glyphs[0].x > plot.left);
}
#[test]
fn draws_axis_titles_beside_the_plot_area() {
use crate::layout::testing::{Fake, Gapped};
assert_axis_title_places(&Fake);
assert_axis_title_places(&Gapped);
let lines = axis_title_layout(&Gapped).1;
assert_eq!(lines.single_top - lines.top, points(1));
}
#[test]
fn skips_blank_points_in_bars_and_blank_categories() {
let mut full = three_reds(ChartGroup::Columns {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
full.legend = None;
let mut gapped = full.clone();
gapped.series[1].values[0] = None;
let reds = reds_of(&font_line_items(&gapped).0);
assert_eq!(reds.len(), 5);
assert_eq!(reds.iter().filter(|(r, _)| *r == 2).count(), 1);
let full_reds = reds_of(&font_line_items(&full).0);
assert_eq!(reds[0].1.x, full_reds[0].1.x);
assert_eq!(reds[3].1.x, full_reds[4].1.x);
let mut blank_bar_cat = three_reds(ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: crate::chart::BarStacking::Clustered,
});
blank_bar_cat.category_names = Some(vec!["North".to_owned(), String::new()]);
let bar_runs = label_runs(&blank_bar_cat, ChartPlotArea::FontLines);
assert!(bar_runs.iter().any(|(text, _, _)| text == "North"));
assert_eq!(
all_text(&blank_bar_cat, ChartPlotArea::FontLines),
Some(true)
);
}
#[test]
fn skips_blank_points_in_lines_and_pies() {
let mut lines_chart = five_points(ChartGroup::Lines {
looks: vec![LineLook {
marker: Some(crate::chart::Marker {
symbol: crate::chart::MarkerSymbol::Square,
size: Length::from_points(5),
fill: None,
outline: None,
}),
..plain_look()
}],
stacking: crate::chart::BarStacking::Clustered,
});
lines_chart.series[0].values[2] = None;
lines_chart.series[0].values[4] = None;
let line_items = font_line_items(&lines_chart).0;
let paths: Vec<_> = line_items
.iter()
.filter(|item| matches!(item, Item::Path(_)))
.collect();
assert_eq!(paths.len(), 4);
let angles = super::pie::slice_angles(
&[
Some(decimal("1")),
None,
Some(decimal("2")),
Some(decimal("1")),
],
0,
);
assert_eq!(
angles,
Some(vec![
(-5_400_000, 5_400_000),
(0, 0),
(0, 10_800_000),
(10_800_000, 5_400_000),
])
);
}
#[test]
fn stacks_positive_and_negative_segments_for_axis_bounds() {
let mut stacked = three_reds(ChartGroup::Columns {
gap: 219,
overlap: 100,
stacking: crate::chart::BarStacking::Stacked,
});
stacked.series[0].values = vec![Some(decimal("4")), Some(decimal("-2"))];
stacked.series[1].values = vec![Some(decimal("-3")), Some(decimal("5"))];
stacked.series[2].values = vec![Some(decimal("2")), None];
let segs = super::bars::stacked_segments(&stacked).unwrap();
assert_eq!(segs.get(0, 0), Some((decimal("0"), decimal("4"))));
assert_eq!(segs.get(1, 0), Some((decimal("0"), decimal("-3"))));
assert_eq!(segs.get(2, 0), Some((decimal("4"), decimal("6"))));
assert_eq!(segs.get(0, 1), Some((decimal("0"), decimal("-2"))));
assert_eq!(segs.get(1, 1), Some((decimal("0"), decimal("5"))));
assert_eq!(segs.get(2, 1), None);
let axis = ValueAxis::of(&stacked).unwrap();
assert_eq!((axis.low, axis.high), (decimal("-4"), decimal("8")));
}
#[test]
fn normalizes_percent_stacked_segments_and_caps_axis() {
let mut percent = three_reds(ChartGroup::Columns {
gap: 219,
overlap: 100,
stacking: crate::chart::BarStacking::PercentStacked,
});
percent.series[0].values = vec![Some(decimal("1")), Some(decimal("0"))];
percent.series[1].values = vec![Some(decimal("3")), Some(decimal("0"))];
percent.series[2].values = vec![None, Some(decimal("0"))];
let psegs = super::bars::stacked_segments(&percent).unwrap();
assert_eq!(psegs.get(0, 0), Some((decimal("0"), decimal("0.25"))));
assert_eq!(psegs.get(1, 0), Some((decimal("0.25"), decimal("1"))));
assert_eq!(psegs.get(0, 1), Some((decimal("0"), decimal("0"))));
let paxis = ValueAxis::of(&percent).unwrap();
assert_eq!(
(paxis.low, paxis.high, paxis.unit),
(decimal("0"), decimal("1"), decimal("0.1"))
);
}
#[test]
fn stacked_bars_meet_seamlessly_and_keep_forward_horizontal_legend() {
use crate::chart::BarStacking::Stacked;
let mut cols = three_reds(ChartGroup::Columns {
gap: 219,
overlap: 100,
stacking: Stacked,
});
cols.legend = None;
cols.series[0].values = vec![Some(decimal("4")), Some(decimal("2"))];
cols.series[1].values = vec![Some(decimal("3")), Some(decimal("5"))];
cols.series[2].values = vec![Some(decimal("2")), Some(decimal("1"))];
let reds = reds_of(&font_line_items(&cols).0);
assert_eq!(reds.len(), 6);
let cat0: Vec<_> = reds.iter().step_by(2).map(|(_, r)| r).collect();
assert_eq!(cat0[0].x, cat0[1].x);
assert_eq!(cat0[1].x, cat0[2].x);
assert_eq!(cat0[0].width, cat0[1].width);
assert_eq!(cat0[1].y + cat0[1].height, cat0[0].y);
assert_eq!(cat0[2].y + cat0[2].height, cat0[1].y);
let bars = three_reds(ChartGroup::Bars {
gap: 219,
overlap: 100,
stacking: Stacked,
});
let names: Vec<_> = super::bars::legend_order(&bars)
.into_iter()
.map(|s| s.name.as_deref())
.collect();
assert_eq!(names, vec![Some("A"), Some("B"), Some("C")]);
}
#[test]
fn scales_stacked_combo_across_both_groups_and_draws_wide_bar_legend_keys() {
use crate::chart::{BarStacking, LineForm, LineLook, StyleWidth};
let mut combo = three_reds(ChartGroup::Combo {
gap: 150,
overlap: 100,
stacking: BarStacking::Stacked,
bar_count: 2,
looks: vec![LineLook {
width: Some(StyleWidth::Automatic),
dash: None,
form: LineForm::Straight,
marker: None,
}],
line_stacking: BarStacking::Clustered,
});
combo.series[0].values = vec![Some(decimal("4")), Some(decimal("2"))];
combo.series[1].values = vec![Some(decimal("3")), Some(decimal("1"))];
combo.series[2].values = vec![Some(decimal("5")), Some(decimal("8"))];
let axis = super::ValueAxis::of(&combo).unwrap();
assert_eq!(axis.high, decimal("9"));
assert!(matches!(
super::legend::Keys::of(&combo),
super::legend::Keys::Lines(_)
));
let (items, _) = font_line_items(&combo);
let wide_keys = reds_of(&items)
.into_iter()
.filter(|(_, r)| r.width == crate::params::CHART_LINE_KEY_STROKE)
.count();
assert_eq!(wide_keys, 2);
}
#[test]
fn places_manual_axis_titles_and_keeps_scatter_manual_inner_right() {
use crate::chart::{AxisTitle, AxisTitles, LayoutCorner, PlotLayout, PlotPlace, TitleText};
use crate::layout::testing::Fake;
use crate::params::{CHART_TITLE_CORNER_LEFT, CHART_TITLE_CORNER_TOP};
let corner = |x, y| LayoutCorner {
x: decimal(x),
y: decimal(y),
};
let mk = |text: &str, c| {
Some(Box::new(AxisTitle {
size: 20,
text: TitleText {
lines: vec![text.to_owned()],
font: FontRef::MinorLatin,
bold: false,
italic: false,
fill: None,
},
corner: Some(c),
}))
};
let (vc, cc) = (corner("0.04", "0.35"), corner("0.40", "0.88"));
let frame = axis_title_frame();
let chart = Columns {
legend: None,
title: None,
axis_titles: AxisTitles::Drawn {
value: mk("Amount", vc),
category: mk("Quarter", cc),
},
..columns(219, -27)
};
let mut sc = five_points(ChartGroup::Scatter {
looks: vec![LineLook {
width: Some(crate::chart::StyleWidth::Automatic),
dash: None,
form: crate::chart::LineForm::Straight,
marker: None,
}],
x_values: vec![vec![decimal("1"), decimal("2"), decimal("3")]],
x_scale: SetScale::default(),
});
sc.plot_place = PlotPlace::Manual(PlotLayout {
inner: true,
edges: plot_box(),
});
crate::layout::testing::with_layout_of(
&Fake,
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let axis = ValueAxis::of(&chart).unwrap();
let plot = layout.font_line_plot(&chart, &axis, frame).unwrap();
let items = layout
.axis_title_items(&chart, (&axis, plot), frame)
.unwrap();
let lines = layout.lines_of(&super::chart_props(&chart, 20)).unwrap();
let (left_x, _) = super::layout_corner(frame, vc).unwrap();
let (cat_x, cat_y) = super::layout_corner(frame, cc).unwrap();
let [Item::Glyphs(v), Item::Glyphs(c)] = &items[..] else {
panic!("expected two axis title glyph runs");
};
assert_eq!(
(v.glyphs[0].x, c.glyphs[0].x, c.glyphs[0].y),
(
left_x + CHART_TITLE_CORNER_TOP + lines.single_top,
cat_x + CHART_TITLE_CORNER_LEFT,
cat_y + CHART_TITLE_CORNER_TOP + lines.single_top,
)
);
let sc_axis = ValueAxis::of(&sc).unwrap();
let sc_plot = layout.font_line_plot(&sc, &sc_axis, frame).unwrap();
let (_, right) = layout
.x_axis(
&sc,
(
&[vec![decimal("1"), decimal("2"), decimal("3")]],
SetScale::default(),
),
(frame, sc_plot),
)
.unwrap();
assert_eq!(right, sc_plot.right);
},
);
}
#[test]
fn places_shifted_category_crossing_and_interior_labels_for_columns_and_bars() {
let mut shifted = drawn_text_columns();
shifted.category_crossing = Some(crate::chart::CategoryCrossing::At(decimal("0.5")));
let axis = ValueAxis::for_chart(&shifted, 10).unwrap();
assert_eq!(axis.crossing, decimal("0.5"));
let mut clamped = shifted.clone();
clamped.category_crossing = Some(crate::chart::CategoryCrossing::At(decimal("99")));
assert_eq!(
ValueAxis::for_chart(&clamped, 10).unwrap().crossing,
axis.high
);
let mut at_min = drawn_text_columns();
at_min.series[0].values[0] = Some(decimal("-2"));
at_min.category_crossing = Some(crate::chart::CategoryCrossing::Min);
let min_axis = ValueAxis::for_chart(&at_min, 10).unwrap();
assert_eq!(min_axis.crossing, min_axis.low);
let mut hbar = drawn_text_columns();
hbar.group = ChartGroup::Bars {
gap: 150,
overlap: 0,
stacking: crate::chart::BarStacking::Clustered,
};
hbar.legend = None;
hbar.category_crossing = Some(crate::chart::CategoryCrossing::At(decimal("0.5")));
assert_eq!(all_text(&hbar, ChartPlotArea::FontLines), Some(true));
}
#[test]
fn applies_explicit_scatter_x_scale_and_keeps_unclamped_clipped_slope() {
let x_scale = SetScale {
min: Some(decimal("2")),
max: Some(decimal("8")),
major_unit: Some(decimal("2")),
};
let xs = vec![vec![
decimal("0"),
decimal("3"),
decimal("5"),
decimal("7"),
decimal("10"),
]];
let scatter = five_points(ChartGroup::Scatter {
looks: vec![plain_look()],
x_values: xs.clone(),
x_scale,
});
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(300),
bottom: points(216),
};
let y_axis = ValueAxis::of(&scatter).unwrap();
let plot = layout.font_line_plot(&scatter, &y_axis, frame).unwrap();
let (axis, right) = layout
.x_axis(&scatter, (&xs, x_scale), (frame, plot))
.unwrap();
assert_eq!(
(axis.low, axis.high, axis.unit),
(decimal("2"), decimal("8"), decimal("2"))
);
let span = (plot.left, right);
assert!(axis.along_unclamped(span, decimal("0")).unwrap() < plot.left);
assert!(axis.along_unclamped(span, decimal("10")).unwrap() > right);
assert_eq!(axis.along(span, decimal("0")), Some(plot.left));
},
);
}
#[test]
fn places_bar_inside_and_line_data_labels_with_marker_clearance() {
use crate::chart::{DataLabelPosition, LineForm, LineLook, Marker, MarkerSymbol};
let make_labels = |position| {
SeriesLabels::Values(DataLabelText {
position,
size: 18,
font: FontRef::MinorLatin,
fill: None,
insets: Edges {
left: Length::from_emus(38_100).unwrap(),
top: Length::from_emus(19_050).unwrap(),
right: Length::from_emus(38_100).unwrap(),
bottom: Length::from_emus(19_050).unwrap(),
},
format: LabelFormat::all_digits(),
parts: crate::chart::DataLabelParts::default(),
show_default: true,
point_overrides: Vec::new(),
})
};
let col_y = |pos| {
let mut chart = drawn_text_columns();
chart.series[0].values[0] = Some(decimal("4"));
chart.series[0].labels = make_labels(pos);
data_label_runs(&chart, ChartDataLabels::OuterEnd, "4").0[0].1
};
let (y_out, y_in_end, y_ctr, y_in_base) = (
col_y(DataLabelPosition::OutsideEnd),
col_y(DataLabelPosition::InsideEnd),
col_y(DataLabelPosition::Center),
col_y(DataLabelPosition::InsideBase),
);
assert!(y_out < y_in_end && y_in_end < y_ctr && y_ctr < y_in_base);
let line_pos = |pos, marker_pt: Option<i64>| {
let marker = marker_pt.map(|pt| Marker {
symbol: MarkerSymbol::Circle,
size: Some(points(pt)),
fill: None,
outline: None,
});
let look = LineLook {
width: None,
marker,
form: LineForm::Straight,
dash: None,
};
let mut chart = Columns::plain(
vec![Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
values: vec![Some(decimal("2")), Some(decimal("4"))],
name: Some("S1".into()),
labels: make_labels(pos),
}],
2,
ChartGroup::Lines {
looks: vec![look],
stacking: crate::chart::BarStacking::Clustered,
},
None,
);
chart.category_names = Some(vec!["A".into(), "B".into()]);
data_label_runs(&chart, ChartDataLabels::OuterEnd, "4").0[0]
};
let (def, ctr, right, left, top0, bot0, top5, top9) = (
line_pos(DataLabelPosition::Default, None),
line_pos(DataLabelPosition::Center, None),
line_pos(DataLabelPosition::Right, None),
line_pos(DataLabelPosition::Left, None),
line_pos(DataLabelPosition::Top, None),
line_pos(DataLabelPosition::Bottom, None),
line_pos(DataLabelPosition::Top, Some(5)),
line_pos(DataLabelPosition::Top, Some(9)),
);
assert_eq!(def, right);
assert!(left.0 < ctr.0 && ctr.0 < right.0);
assert!(top0.1 < ctr.1 && ctr.1 < bot0.1);
assert_eq!(top5.1, top0.1);
assert_eq!(top0.1 - top9.1, points(2));
}
#[test]
fn draws_scatter_legends_with_line_or_square_marker_keys_beside_twin_plot() {
use super::legend::Keys;
use crate::chart::{LineDash, Marker, MarkerSymbol};
use crate::params::{CHART_LINE_KEY_AREA, CHART_LINE_KEY_DASHED_AREA};
let marker_only = LineLook {
width: None,
marker: Some(Marker {
symbol: MarkerSymbol::Circle,
size: Some(points(7)),
fill: Some(DrawColor::rgb(Rgb::BLACK)),
outline: None,
}),
form: LineForm::Straight,
dash: None,
};
let mut dashed = plain_look();
dashed.dash = Some(LineDash::Dash);
let make = |looks: Vec<LineLook>, legend: LegendPlace| {
let mut chart = five_points(ChartGroup::Scatter {
looks,
x_values: quarter_x_values(),
x_scale: SetScale::default(),
});
chart.series[0].name = Some("Alpha".into());
chart.legend = Some(legend);
chart
};
let lined_right = make(vec![plain_look()], LegendPlace::Right);
let dashed_bottom = make(vec![dashed], LegendPlace::Bottom);
let markers_right = make(vec![marker_only], LegendPlace::Right);
assert_eq!(Keys::of(&lined_right), Keys::Lines(CHART_LINE_KEY_AREA));
assert_eq!(
Keys::of(&dashed_bottom),
Keys::Lines(CHART_LINE_KEY_DASHED_AREA)
);
assert_eq!(Keys::of(&markers_right), Keys::Squares);
let (lined_items, _) = font_line_items(&lined_right);
let (marker_items, _) = font_line_items(&markers_right);
let alpha_x = |items: &[Item]| {
runs_of(items)
.into_iter()
.find(|(text, _, _)| *text == "Alpha")
.map(|(_, x, _)| x)
.unwrap()
};
assert_eq!(alpha_x(&lined_items), alpha_x(&marker_items));
}
#[test]
fn stacks_lines_algebraically_treats_blanks_as_zero_and_reverses_side_legend() {
use super::bars::{legend_order, stacked_line_values};
use crate::chart::BarStacking;
let mut chart = Columns::plain(
vec![
Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
values: vec![Some(decimal("4")), Some(decimal("3"))],
name: Some("Alpha".into()),
labels: SeriesLabels::Hidden,
},
Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
values: vec![None, Some(decimal("-4.5"))],
name: Some("Beta".into()),
labels: SeriesLabels::Hidden,
},
Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
values: vec![Some(decimal("2")), Some(decimal("2"))],
name: Some("Gamma".into()),
labels: SeriesLabels::Hidden,
},
],
2,
ChartGroup::Lines {
looks: vec![plain_look(); 3],
stacking: BarStacking::Stacked,
},
None,
);
chart.legend = Some(LegendPlace::Right);
chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
let stacked = stacked_line_values(&chart).unwrap();
assert_eq!(stacked[0], vec![Some(decimal("4")), Some(decimal("3"))]);
assert_eq!(stacked[1], vec![Some(decimal("4")), Some(decimal("-1.5"))]);
assert_eq!(stacked[2], vec![Some(decimal("6")), Some(decimal("0.5"))]);
let axis = super::ValueAxis::of(&chart).unwrap();
assert_eq!(axis.low, decimal("-2"));
assert_eq!(axis.high, decimal("7"));
let right_names: Vec<_> = legend_order(&chart)
.into_iter()
.map(|s| s.name.as_deref().unwrap())
.collect();
assert_eq!(right_names, vec!["Gamma", "Beta", "Alpha"]);
chart.legend = Some(LegendPlace::Bottom);
let bottom_names: Vec<_> = legend_order(&chart)
.into_iter()
.map(|s| s.name.as_deref().unwrap())
.collect();
assert_eq!(bottom_names, vec!["Alpha", "Beta", "Gamma"]);
}
#[test]
fn lays_out_combo_secondary_right_axis_with_independent_scale_and_right_legend() {
use crate::chart::{BarStacking, LabelFormat, SecondaryValueAxis};
use f_office_drawingml::shape::{Geometry, ShapeLook};
let mut chart = Columns::plain(
vec![
Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
values: vec![Some(decimal("40")), Some(decimal("45"))],
name: Some("Bars".into()),
labels: SeriesLabels::Hidden,
},
Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
values: vec![Some(decimal("2")), Some(decimal("9"))],
name: Some("Rate".into()),
labels: SeriesLabels::Hidden,
},
],
2,
ChartGroup::Combo {
gap: 150,
overlap: 0,
stacking: BarStacking::Clustered,
bar_count: 1,
looks: vec![plain_look()],
line_stacking: BarStacking::Clustered,
},
None,
);
chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
chart.legend = Some(LegendPlace::Right);
chart.secondary_axis = Some(Box::new(SecondaryValueAxis {
scale: SetScale::default(),
format: LabelFormat::all_digits(),
label_size: chart.value_label_size,
label_fill: None,
line: ShapeLook::plain(Geometry::Line, None, None),
ticks: false,
labels_hidden: false,
}));
let primary = super::ValueAxis::of(&chart).unwrap();
assert_eq!(primary.high, decimal("50"));
let (items, _) = font_line_items(&chart);
let runs = runs_of(&items);
let right_top_x = runs
.iter()
.find(|(t, x, _)| *t == "10" && *x > points(300))
.map(|(_, x, _)| *x)
.unwrap();
let right_bottom_x = runs
.iter()
.find(|(t, x, _)| *t == "0" && *x > points(300))
.map(|(_, x, _)| *x)
.unwrap();
let legend_x = runs
.iter()
.find(|(t, _, _)| *t == "Bars")
.map(|(_, x, _)| *x)
.unwrap();
assert_eq!(right_top_x, right_bottom_x);
assert!(legend_x > right_top_x);
}
#[test]
fn formats_pie_hamilton_percents_and_two_line_default_separator() {
use crate::chart::{
DataLabelParts, DataLabelPosition, PercentMode, PieExplosion, PieLabelPlace,
};
let mut chart = drawn_text_columns();
chart.group = ChartGroup::Pie {
first_angle: 0,
view: None,
fills: vec![DrawColor::rgb(Rgb::default()); 4],
labels: PieLabelPlace::Center,
explosion: PieExplosion {
series: 0,
slices: vec![0; 4],
},
};
chart.legend = None;
chart.title = None;
chart.category_names = Some(vec!["A".into(), "B".into(), "C".into(), "D".into()]);
chart.series = vec![Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
values: [5, 1, 2, 3].map(|v| Some(decimal(&v.to_string()))).to_vec(),
name: Some("Share".into()),
labels: SeriesLabels::Values(DataLabelText {
position: DataLabelPosition::Center,
size: 18,
font: FontRef::MinorLatin,
fill: None,
insets: Edges {
left: Length::from_emus(38_100).unwrap(),
top: Length::from_emus(19_050).unwrap(),
right: Length::from_emus(38_100).unwrap(),
bottom: Length::from_emus(19_050).unwrap(),
},
format: LabelFormat::all_digits(),
parts: DataLabelParts {
show_ser_name: false,
show_cat_name: true,
show_val: false,
percent: PercentMode::Integer,
separator: None,
},
show_default: true,
point_overrides: Vec::new(),
}),
}];
let (items, _) = font_line_items(&chart);
let runs = runs_of(&items);
let texts: Vec<&str> = runs.iter().map(|(t, _, _)| *t).collect();
for expected in ["A", "46%", "B", "9%", "C", "18%", "D", "27%"] {
assert!(texts.contains(&expected), "missing {expected} in {texts:?}");
}
let y_a = runs.iter().find(|(t, _, _)| *t == "A").unwrap().2;
let y_46 = runs.iter().find(|(t, _, _)| *t == "46%").unwrap().2;
assert!(y_46 > y_a);
}
#[test]
fn applies_per_point_delete_rich_text_and_manual_layout_offsets() {
use crate::chart::{
DataLabelParts, DataLabelPosition, PercentMode, PointLabelLayout, PointLabelOverride,
PointLabelSpec,
};
let mut chart = drawn_text_columns();
chart.categories = 4;
chart.legend = None;
chart.title = None;
chart.category_names = Some(vec!["Q1".into(), "Q2".into(), "Q3".into(), "Q4".into()]);
let base_text = DataLabelText {
position: DataLabelPosition::OutsideEnd,
size: 18,
font: FontRef::MinorLatin,
fill: None,
insets: Edges {
left: Length::from_emus(38_100).unwrap(),
top: Length::from_emus(19_050).unwrap(),
right: Length::from_emus(38_100).unwrap(),
bottom: Length::from_emus(19_050).unwrap(),
},
format: LabelFormat::all_digits(),
parts: DataLabelParts {
show_ser_name: false,
show_cat_name: false,
show_val: true,
percent: PercentMode::Hidden,
separator: None,
},
show_default: true,
point_overrides: Vec::new(),
};
let mut shifted_text = base_text.clone();
shifted_text.point_overrides.clear();
let mut rich_text = base_text.clone();
rich_text.point_overrides.clear();
let mut with_overrides = base_text.clone();
with_overrides.point_overrides = vec![
(
0,
PointLabelOverride::Custom(Box::new(PointLabelSpec {
label: shifted_text,
rich_lines: None,
layout: PointLabelLayout::Offset {
dx: decimal("0.1"),
dy: decimal("0"),
},
})),
),
(1, PointLabelOverride::Deleted),
(
2,
PointLabelOverride::Custom(Box::new(PointLabelSpec {
label: rich_text,
rich_lines: Some(vec!["Peak".into()]),
layout: PointLabelLayout::Automatic,
})),
),
];
chart.series = vec![Series {
fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
values: [11, 22, 33, 44]
.map(|v| Some(decimal(&v.to_string())))
.to_vec(),
name: Some("S".into()),
labels: SeriesLabels::Values(base_text),
}];
let render = |chart: &Columns| {
let mut out = None;
with_layout_on(
|p| {
p.with_variant(ChartPlotArea::FontLines)
.with_variant(ChartDataLabels::OuterEnd)
},
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
out = layout.columns(chart, frame).map(|(items, _)| items);
},
);
out.unwrap()
};
let base_items = render(&chart);
let base_runs = runs_of(&base_items);
let base_x0 = base_runs.iter().find(|(t, _, _)| *t == "11").unwrap().1;
chart.series[0].labels = SeriesLabels::Values(with_overrides);
let items = render(&chart);
let runs = runs_of(&items);
let texts: Vec<&str> = runs.iter().map(|(t, _, _)| *t).collect();
assert!(texts.contains(&"11"));
assert!(!texts.contains(&"22"), "point 1 should be deleted");
assert!(texts.contains(&"Peak"));
assert!(!texts.contains(&"33"), "point 2 should use rich text");
assert!(texts.contains(&"44"));
let shifted_x0 = runs.iter().find(|(t, _, _)| *t == "11").unwrap().1;
let expected_dx = Length::from_units(points(432).units() / 10);
assert!((shifted_x0 - base_x0 - expected_dx).units().abs() <= 10);
}
#[test]
fn lays_out_and_paints_chart_data_table_borders_keys_and_cells() {
use crate::chart::{DataTable, DataTableBorders};
use f_office_drawingml::shape::{Geometry, ShapeLook};
let make_chart = |outline, horz, vert, keys| {
let mut chart = named_columns();
chart.legend = None;
chart.title = None;
chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
chart.series[0].name = Some("Alpha".into());
chart.series[1].name = Some("Beta".into());
chart.data_table = Some(Box::new(DataTable {
borders: DataTableBorders {
horz,
vert,
outline,
},
keys,
border: ShapeLook::plain(
Geometry::Line,
None,
Some((
Rgb {
r: 0x86,
g: 0x86,
b: 0x86,
},
points(1),
)),
),
text_size: 18,
text_font: crate::props::FontRef::MinorLatin,
text_fill: None,
bold: false,
italic: false,
}));
chart
};
let render = |chart: &Columns| {
let mut out = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
out = layout.columns(chart, frame);
},
);
out.unwrap()
};
let border_count = |items: &[Item]| {
items
.iter()
.filter(|item| {
matches!(
item,
Item::Rect(rect) if rect.color == Rgb { r: 0x86, g: 0x86, b: 0x86 }
)
})
.count()
};
let (all_items, drawn) = render(&make_chart(true, true, true, true));
let texts: Vec<&str> = runs_of(&all_items).into_iter().map(|(t, _, _)| t).collect();
let (outline_only, _) = render(&make_chart(true, false, false, true));
let (interior_only, _) = render(&make_chart(false, true, true, false));
assert_eq!(
(
drawn.axes_and_legend,
border_count(&all_items),
border_count(&outline_only),
border_count(&interior_only),
["Q1", "Q2", "Alpha", "Beta"]
.iter()
.all(|label| texts.contains(label)),
),
(true, 8, 6, 2, true)
);
}
#[test]
fn places_manual_inner_data_table_and_clamps_narrow_left_margin() {
use crate::chart::{DataTable, DataTableBorders, PlotLayout, PlotPlace};
use f_office_drawingml::shape::{Geometry, ShapeLook};
let make = |x: &str| {
let mut chart = named_columns();
chart.legend = None;
chart.title = None;
chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
chart.series[0].name = Some("Alpha".into());
chart.series[1].name = Some("Beta".into());
chart.plot_place = PlotPlace::Manual(PlotLayout {
inner: true,
edges: LayoutBox {
x: decimal(x),
y: decimal("0.05"),
w: decimal("0.70"),
h: decimal("0.65"),
},
});
chart.data_table = Some(Box::new(DataTable {
borders: DataTableBorders {
horz: true,
vert: true,
outline: true,
},
keys: true,
border: ShapeLook::plain(
Geometry::Line,
None,
Some((
Rgb {
r: 0x86,
g: 0x86,
b: 0x86,
},
points(1),
)),
),
text_size: 18,
text_font: crate::props::FontRef::MinorLatin,
text_fill: None,
bold: false,
italic: false,
}));
chart
};
let bounds = |chart: &Columns| {
let mut out = None;
with_layout_on(
|p| p.with_variant(ChartPlotArea::FontLines),
|layout| {
let frame = Edges {
left: Length::ZERO,
top: Length::ZERO,
right: points(432),
bottom: points(252),
};
let (items, _) = layout.columns(chart, frame).unwrap();
let border = Rgb {
r: 0x86,
g: 0x86,
b: 0x86,
};
let edges = items.iter().filter_map(|item| match item {
Item::Rect(r) if r.color == border => Some((r.x, r.x + r.width)),
_ => None,
});
let stub_left = edges.clone().map(|(l, _)| l).min().unwrap();
let plot_right = edges.map(|(_, r)| r).max().unwrap();
out = Some((stub_left, plot_right));
},
);
out.unwrap()
};
let (wide_stub, wide_right) = bounds(&make("0.25"));
let (clamped_stub, clamped_right) = bounds(&make("0.05"));
assert!(wide_stub > points(50));
assert!((clamped_stub - points(12)).units().abs() <= points(1).units());
assert!(clamped_right > points(324) && wide_right > clamped_right);
}