use super::{
ChartGroup, Decimal, LayoutBox, LegendBox, LineDash, LineForm, LineLook, Marker, MarkerSymbol,
Part, PieLabelPlace, PlotRule, SeriesFill, SeriesLabels, StyleWidth, reference, style_color,
};
use crate::ns::{A, C, R, STRICT_ALIASES};
use crate::quirks::{ChartAutomaticTitle, ChartPlotArea};
use crate::reader::PartReader;
use crate::testing::Replaced as _;
use crate::warnings::ChartReason;
use f_office_xml::{Document, Limits};
/// The part that the base target, whose quirk is `ChartPlotArea::DefaultChart`, draws of a
/// chart, or why it does not draw it.
fn read(reader: &mut PartReader, space: f_office_xml::NodeId) -> Result<Part, ChartReason> {
read_on(ChartPlotArea::DefaultChart, reader, space)
}
/// The part that a target whose quirk is `area` draws of a chart, or why it does not draw it.
fn read_on(
area: ChartPlotArea,
reader: &mut PartReader,
space: f_office_xml::NodeId,
) -> Result<Part, ChartReason> {
super::read(
reader,
space,
crate::reader::settings::PlotRules::with_area(area),
)
}
fn parse(xml: &str) -> Document {
Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), STRICT_ALIASES).unwrap()
}
fn decimal(text: &str) -> (i64, i32) {
let d = Decimal::parse(text).unwrap();
(d.digits, d.exponent)
}
#[test]
fn reads_the_numbers_of_a_cache() {
assert_eq!(decimal("4.3"), (43, -1));
assert_eq!(decimal("5"), (5, 0));
assert_eq!(decimal("40000"), (4, 4));
assert_eq!(decimal("-0.25"), (-25, -2));
assert_eq!(decimal("1.5E-3"), (15, -4));
assert_eq!(decimal("0"), (0, 0));
}
#[test]
fn reads_no_number_beyond_the_exponent_limit() {
// The largest double and the smallest one above zero, each with its 17 digits.
assert_eq!(
decimal("1.7976931348623157E308"),
(17_976_931_348_623_157, 292)
);
assert_eq!(
decimal("4.9406564584124654E-324"),
(49_406_564_584_124_654, -340)
);
assert_eq!(decimal("1E350"), (1, 350));
assert!(Decimal::parse("1E351").is_none());
assert!(Decimal::parse("1E-351").is_none());
assert!(Decimal::parse("1E2000000000").is_none());
}
#[test]
fn compares_numbers_and_leaves_out_text() {
assert!(Decimal::parse("x").is_none());
assert!(Decimal::parse(".").is_none());
assert!(Decimal::parse("4.3") > Decimal::parse("4.25"));
assert!(Decimal::parse("40000") > Decimal::parse("9999.5"));
}
#[test]
fn reads_the_chart_of_a_drawing() {
let doc = parse(&format!(
r#"<a:graphicData xmlns:a="{A}" xmlns:c="{C}" xmlns:r="{R}"><c:chart r:id="rId8"/></a:graphicData>"#
));
let chart = reference(&doc, doc.root().unwrap()).unwrap();
assert_eq!(chart.id, "rId8");
assert!(chart.columns.is_none());
}
/// A chart part in the Strict namespaces with `body` in its `c:chart`.
fn part(body: &str) -> String {
format!(
r#"<c:chartSpace xmlns:c="http://purl.oclc.org/ooxml/drawingml/chart" xmlns:a="http://purl.oclc.org/ooxml/drawingml/main"><c:chart>{body}</c:chart><c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill></c:spPr></c:chartSpace>"#
)
}
fn text(size: u32) -> String {
format!(
r#"<c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="{size}"><a:latin typeface="+mn-lt"/></a:defRPr></a:pPr></a:p></c:txPr>"#
)
}
fn series(fill: &str, values: &[&str]) -> String {
let points = values
.iter()
.enumerate()
.map(|(i, v)| format!(r#"<c:pt idx="{i}"><c:v>{v}</c:v></c:pt>"#))
.collect::<Vec<_>>()
.concat();
format!(
r#"<c:ser><c:spPr><a:solidFill><a:schemeClr val="{fill}"/></a:solidFill></c:spPr><c:val><c:numRef><c:numCache><c:ptCount val="{}"/>{points}</c:numCache></c:numRef></c:val></c:ser>"#,
values.len()
)
}
fn default_chart(legend: &str, title: &str) -> String {
let axes = format!(
r#"<c:catAx><c:delete val="0"/>{LINE}{}</c:catAx><c:valAx><c:delete val="0"/><c:majorGridlines>{LINE}</c:majorGridlines>{}</c:valAx>"#,
text(900),
text(900)
);
part(&format!(
r#"{title}<c:autoTitleDeleted val="0"/><c:plotArea><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/>{}{}<c:gapWidth val="219"/><c:overlap val="-27"/></c:barChart>{axes}</c:plotArea><c:legend><c:legendPos val="{legend}"/>{}</c:legend>"#,
series("accent1", &["4.3", "2.5"]),
series("accent2", &["2.4", "4.4"]),
text(900)
))
}
/// A line of 0.75 pt in light gray, as Word's default chart gives its gridlines and axis.
const LINE: &str = r#"<c:spPr><a:ln w="9525"><a:solidFill><a:srgbClr val="D9D9D9"/></a:solidFill></a:ln></c:spPr>"#;
/// The fill of the first series of [`default_chart`], which names that series, before its
/// values.
const FIRST_FILL: &str =
r#"<c:spPr><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></c:spPr>"#;
/// The start of the category axis of [`default_chart`], its first axis.
const CATEGORY_AXIS: &str = r#"<c:catAx><c:delete val="0"/>"#;
const TITLE: &str = r#"<c:title><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="1400"/></a:pPr></a:p></c:txPr></c:title>"#;
/// [`default_chart`] as Word's line chart without markers: a standard group whose series each
/// draw a line of 2.25 pt with round caps and round joins.
fn line_chart() -> String {
let line = |color: &str| {
format!(
r#"<c:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:schemeClr val="{color}"/></a:solidFill><a:round/></a:ln></c:spPr><c:marker><c:symbol val="none"/></c:marker>"#
)
};
let chart = default_chart("b", TITLE);
// Without its legend: F-Office draws no line chart with a legend yet.
let without_legend = match (chart.find("<c:legend>"), chart.find("</c:legend>")) {
(Some(start), Some(end)) => format!("{}{}", &chart[..start], &chart[end + 11..]),
_ => chart,
};
without_legend
.replaced_all(
r#"<c:barDir val="col"/><c:grouping val="clustered"/>"#,
r#"<c:grouping val="standard"/>"#,
)
.replaced_all(r#"<c:gapWidth val="219"/><c:overlap val="-27"/>"#, "")
.replaced_all("c:barChart>", "c:lineChart>")
.replaced_all(FIRST_FILL, &line("accent1"))
.replaced_all(
r#"<c:spPr><a:solidFill><a:schemeClr val="accent2"/></a:solidFill></c:spPr>"#,
&line("accent2"),
)
}
#[test]
fn reads_a_line_chart_with_its_lines_width_and_the_colors_of_its_lines() {
let doc = parse(&line_chart());
let found = read_on(
ChartPlotArea::FontLines,
&mut PartReader::new(&doc),
doc.root().unwrap(),
)
.unwrap();
let columns = found.columns;
let plain = LineLook {
width: Some(StyleWidth::Set(
f_office_units::Length::from_emus(28_575).unwrap(),
)),
marker: None,
form: LineForm::Straight,
dash: None,
};
assert_eq!(
columns.group,
ChartGroup::Lines {
looks: vec![plain.clone(), plain],
stacking: super::BarStacking::Clustered,
}
);
assert_eq!(columns.series.len(), 2);
assert_eq!(columns.categories, 2);
}
/// The look of each series of a line chart read with the plot area rule `FontLines`, or why it
/// is left out.
fn line_looks(xml: &str) -> Result<Vec<LineLook>, ChartReason> {
let doc = parse(xml);
let found = read_on(
ChartPlotArea::FontLines,
&mut PartReader::new(&doc),
doc.root().unwrap(),
)?;
match found.columns.group {
ChartGroup::Lines { looks, .. } => Ok(looks),
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. }
| ChartGroup::Combo { .. } => Err(ChartReason::OtherGroup),
}
}
#[test]
fn reads_the_markers_that_a_series_sets() {
let with_circles = line_chart().replaced_all(
r#"<c:symbol val="none"/>"#,
r#"<c:symbol val="circle"/><c:size val="5"/><c:spPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:ln w="9525"><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill></a:ln><a:effectLst/></c:spPr>"#,
);
let looks = line_looks(&with_circles).unwrap();
let marker = looks[0].marker.clone().unwrap();
assert_eq!(marker.symbol, MarkerSymbol::Circle);
assert_eq!(marker.size, f_office_units::Length::from_points(5));
let outline = marker.outline.unwrap();
assert!(marker.fill.is_some() && outline.color.is_some());
assert_eq!(
outline.width,
StyleWidth::Set(f_office_units::Length::from_emus(9_525).unwrap())
);
// A marker from the chart's style on a series that sets its own line is not supported.
let styled_marker =
line_chart().replaced_all(r#"<c:marker><c:symbol val="none"/></c:marker>"#, "");
let styled_marker =
styled_marker.replaced_all("</c:lineChart>", r#"<c:marker val="1"/></c:lineChart>"#);
assert_eq!(line_looks(&styled_marker), Err(ChartReason::LineMarkers));
}
#[test]
fn gives_the_series_without_properties_the_look_and_the_colors_of_the_style() {
// Both series without `c:spPr` or `c:marker`, in a group that shows markers.
let styled = line_chart()
.replaced_all(
r#"<c:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:schemeClr val="accent1"/></a:solidFill><a:round/></a:ln></c:spPr><c:marker><c:symbol val="none"/></c:marker>"#,
"",
)
.replaced_all(
r#"<c:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:schemeClr val="accent2"/></a:solidFill><a:round/></a:ln></c:spPr><c:marker><c:symbol val="none"/></c:marker>"#,
"",
)
.replaced_all("</c:lineChart>", r#"<c:marker val="1"/></c:lineChart>"#);
let looks = line_looks(&styled).unwrap();
let symbols: Vec<_> = looks
.iter()
.map(|look| look.marker.as_ref().map(|m: &Marker| m.symbol))
.collect();
assert_eq!(
symbols,
[Some(MarkerSymbol::Diamond), Some(MarkerSymbol::Square)]
);
assert!(
looks
.iter()
.all(|look| look.width == Some(StyleWidth::Automatic))
);
// Style 2, alone or as the alternate content of the Office 2010 extension names it, has
// the look of a chart that names no style; another style has a look that F-Office has not
// measured.
let styled_in = |style: &str| styled.replacen("<c:chart>", &format!("{style}<c:chart>"), 1);
let alternate = |choice: u32, fallback: u32| {
format!(
r#"<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"><mc:Choice Requires="c14" xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart"><c14:style val="{choice}"/></mc:Choice><mc:Fallback><c:style val="{fallback}"/></mc:Fallback></mc:AlternateContent>"#
)
};
for style in [alternate(102, 2), r#"<c:style val="2"/>"#.to_owned()] {
assert_eq!(line_looks(&styled_in(&style)), Ok(looks.clone()), "{style}");
}
for style in [
alternate(101, 1),
alternate(102, 18),
r#"<c:style val="18"/>"#.to_owned(),
] {
assert_eq!(
line_looks(&styled_in(&style)),
Err(ChartReason::ChartStyle),
"{style}"
);
}
}
#[test]
fn shades_the_style_colors_of_six_series_and_gives_none_past_six() {
use f_office_drawingml::color::SchemeColors;
use f_office_paint::Rgb;
let scheme = parse(
r#"<a:clrScheme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6></a:clrScheme>"#,
);
let colors = SchemeColors::read(
&scheme,
scheme.root().unwrap(),
&mut f_office_warnings::Warnings::new(),
);
let rgb = |index, count| {
style_color(index, count)
.and_then(|color| color.resolve(&colors))
.map(|(rgb, _)| rgb)
};
let hex = |v: &str| {
let channel = |at: usize| u8::from_str_radix(&v[at..at + 2], 16).unwrap();
Rgb {
r: channel(0),
g: channel(2),
b: channel(4),
}
};
assert_eq!(rgb(0, 5), Some(hex("4472C4")));
// The six darker accents that Word gives a group of six series of the chart's style, and the
// lighter second cycle at seven series.
for (index, want) in ["3B64AD", "D26E2A", "929292", "E2AA00", "5089BC", "62993E"]
.into_iter()
.enumerate()
{
assert_eq!(rgb(index, 6), Some(hex(want)), "{index}");
}
assert_eq!(rgb(6, 7), Some(hex("8FA2D4")));
}
#[test]
fn leaves_out_the_line_charts_that_it_has_not_measured() {
let reason = |xml: String| {
let doc = parse(&xml);
read_on(
ChartPlotArea::FontLines,
&mut PartReader::new(&doc),
doc.root().unwrap(),
)
.err()
};
let lines = line_chart();
assert_eq!(reason(lines.clone()), None);
for (from, to, why) in [
(
r#"<c:symbol val="none"/>"#,
r#"<c:symbol val="circle"/>"#,
ChartReason::LineMarkers,
),
(
r#"<c:symbol val="none"/>"#,
r#"<c:symbol val="dash"/>"#,
ChartReason::LineMarkers,
),
(
r#"val="standard""#,
r#"val="stacked""#,
ChartReason::StackedLines,
),
(r#" cap="rnd""#, "", ChartReason::LineLook),
(r#"w="28575""#, "", ChartReason::LineLook),
(
"</c:lineChart>",
"<c:dropLines/></c:lineChart>",
ChartReason::LineExtras,
),
(
"</c:marker>",
r#"</c:marker><c:smooth val="1"/>"#,
ChartReason::SmoothLines,
),
] {
assert_eq!(reason(lines.replaced_all(from, to)), Some(why), "{from}");
}
let legend = format!(
r#"</c:plotArea><c:legend><c:legendPos val="b"/>{}</c:legend>"#,
text(900)
);
assert_eq!(reason(lines.replaced_all("</c:plotArea>", &legend)), None);
}
#[test]
fn reads_a_clustered_column_chart() {
let doc = parse(&default_chart("b", TITLE));
let found = read(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
let columns = found.columns;
assert_eq!(columns.series.len(), 2);
assert_eq!(columns.categories, 2);
assert_eq!(
columns.group,
ChartGroup::Columns {
gap: 219,
overlap: -27,
stacking: super::BarStacking::Clustered,
}
);
assert_eq!(
columns.title.as_ref().map(|t| (t.lines, t.size)),
Some((1, 28))
);
assert_eq!(columns.label_size, 18);
assert_eq!(
columns.series[1].values[1],
Some(Decimal::parse("4.4").unwrap())
);
}
#[test]
fn reads_the_font_and_the_fill_of_a_legend() {
use crate::props::FontRef;
use f_office_drawingml::color::DrawColor;
use f_office_paint::Rgb;
let read_legend = |xml: &str| {
let doc = parse(xml);
let columns = read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns;
(columns.legend_font, columns.legend_fill)
};
// The legend of the default chart names the theme's body font and no fill.
let default = default_chart("b", TITLE);
assert_eq!(read_legend(&default), (FontRef::MinorLatin, None));
// A legend's own font and solid fill.
let own = default.replaced(
r#"<c:legendPos val="b"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="900"><a:latin typeface="+mn-lt"/>"#,
r#"<c:legendPos val="b"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="900"><a:solidFill><a:srgbClr val="595959"/></a:solidFill><a:latin typeface="Corbel"/>"#,
);
let gray = Rgb {
r: 0x59,
g: 0x59,
b: 0x59,
};
assert_eq!(
read_legend(&own),
(
FontRef::Name("Corbel".to_owned()),
Some(DrawColor::rgb(gray))
)
);
}
#[test]
fn reads_whether_a_legend_is_bold_italic_or_has_entries_of_its_own() {
use crate::chart::LegendText;
let read_text = |xml: &str| {
let doc = parse(xml);
read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns
.legend_text
};
let default = default_chart("b", TITLE);
assert_eq!(read_text(&default), LegendText::default());
let props = r#"<c:legendPos val="b"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="900">"#;
let bold = default.replaced(
props,
r#"<c:legendPos val="b"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="900" b="1" i="true">"#,
);
assert_eq!(
read_text(&bold),
LegendText {
bold: true,
italic: true,
own_entries: false
}
);
let entries = default.replaced(
r#"<c:legendPos val="b"/>"#,
r#"<c:legendPos val="b"/><c:legendEntry><c:idx val="0"/><c:delete val="1"/></c:legendEntry>"#,
);
assert!(read_text(&entries).own_entries);
}
#[test]
fn reads_the_lines_of_the_gridlines_and_the_axis() {
let doc = parse(&default_chart("b", TITLE));
let columns = read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns;
let theme = f_office_drawingml::theme::ShapeTheme::default();
let gray = f_office_paint::Rgb {
r: 0xD9,
g: 0xD9,
b: 0xD9,
};
let line = |look: &f_office_drawingml::shape::ShapeLook| {
look.line(&theme)
.map(|(rgb, _, width)| (rgb, width.units()))
};
let three_quarters = f_office_units::Length::UNITS_PER_POINT * 3 / 4;
assert_eq!(
columns.gridlines.as_ref().and_then(line),
Some((gray, three_quarters))
);
assert_eq!(line(&columns.axis), Some((gray, three_quarters)));
}
/// [`default_chart`] as a chart of style 2 writes it without properties: no fill for its
/// series, no line for its gridlines and its axes and no properties for its chart area, with
/// points of one color and tick marks outside both axes.
fn bare_chart() -> String {
default_chart("b", TITLE)
.replaced_all(LINE, "")
.replaced(FIRST_FILL, "")
.replaced(
r#"<c:spPr><a:solidFill><a:schemeClr val="accent2"/></a:solidFill></c:spPr>"#,
"",
)
.replaced(
r#"<c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill></c:spPr>"#,
"",
)
.replaced(
r#"<c:grouping val="clustered"/>"#,
r#"<c:grouping val="clustered"/><c:varyColors val="0"/>"#,
)
.replaced_all(
r#"<c:delete val="0"/>"#,
r#"<c:delete val="0"/><c:majorTickMark val="out"/>"#,
)
}
#[test]
fn fills_a_bar_series_with_its_gradient_and_leaves_out_one_that_f_office_does_not_paint() {
let stops = |count: usize| {
(0..count)
.map(|at| {
let place = at * 100_000 / count.saturating_sub(1).max(1);
format!(r#"<a:gs pos="{place}"><a:schemeClr val="accent1"/></a:gs>"#)
})
.collect::<Vec<_>>()
.concat()
};
let gradient = |count| {
format!(
r#"<c:spPr><a:gradFill rotWithShape="1"><a:gsLst>{}</a:gsLst><a:lin ang="16200000" scaled="0"/></a:gradFill></c:spPr>"#,
stops(count)
)
};
let read = |fill: &str| {
let doc = parse(&default_chart("b", TITLE).replaced(FIRST_FILL, fill));
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
};
let part = read(&gradient(3)).unwrap();
assert!(matches!(
part.columns.series[0].fill,
SeriesFill::Gradient(_)
));
assert!(matches!(part.columns.series[1].fill, SeriesFill::Color(_)));
// Two stops, which Word paints along a curve of its own, and one, which it does not.
assert!(matches!(
read(&gradient(2)).unwrap().columns.series[0].fill,
SeriesFill::Gradient(_)
));
assert_eq!(read(&gradient(1)).err(), Some(ChartReason::SeriesFill));
}
#[test]
fn draws_the_elements_without_properties_in_the_style_look_where_the_target_does() {
use crate::quirks::ChartStyleLook;
use crate::reader::settings::PlotRules;
use f_office_drawingml::color::{DrawColor, SchemeSlot};
use f_office_drawingml::theme::ShapeTheme;
let doc = parse(&bare_chart());
let rules = |look| PlotRules::with_area(ChartPlotArea::FontLines).with_style_look(look);
let read = |look| super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules(look));
assert_eq!(
read(ChartStyleLook::Unknown).err(),
Some(ChartReason::SeriesFill)
);
let part = read(ChartStyleLook::StyleTwo).unwrap();
let columns = &part.columns;
let fills: Vec<_> = columns.series.iter().map(|s| s.fill.clone()).collect();
assert_eq!(
fills,
[SchemeSlot::Accent1, SchemeSlot::Accent2]
.map(|slot| SeriesFill::Color(DrawColor::scheme(slot)))
);
assert!(columns.ticks.category && columns.ticks.value);
let theme_xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:clrScheme><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1></a:clrScheme><a:fmtScheme><a:lnStyleLst><a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln></a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>"#
);
let theme_doc = parse(&theme_xml);
let theme = ShapeTheme::read(
&theme_doc,
theme_doc.root().unwrap(),
&mut f_office_warnings::Warnings::new(),
);
let gray = f_office_paint::Rgb {
r: 0x89,
g: 0x89,
b: 0x89,
};
let line = |look: &f_office_drawingml::shape::ShapeLook| {
look.line(&theme)
.map(|(rgb, _, width)| (rgb, width.units()))
};
let one_point = f_office_units::Length::UNITS_PER_POINT;
for look in [
columns.gridlines.as_ref().unwrap(),
&columns.axis,
&columns.value_axis,
&part.area,
] {
assert_eq!(line(look), Some((gray, one_point)));
}
let white = f_office_paint::Rgb {
r: 0xFF,
g: 0xFF,
b: 0xFF,
};
let mut area = part.area.clone();
area.geometry = f_office_drawingml::shape::Geometry::Rect;
assert_eq!(area.fill(&theme).map(|(rgb, _)| rgb), Some(white));
}
#[test]
fn leaves_out_a_chart_with_a_data_table_after_its_other_reasons() {
let table = r#"<c:dTable><c:showHorzBorder val="1"/><c:showVertBorder val="1"/><c:showOutline val="1"/><c:showKeys val="1"/></c:dTable></c:plotArea>"#;
let reason = |xml: String| {
let doc = parse(&xml);
read(&mut PartReader::new(&doc), doc.root().unwrap()).err()
};
let tabled = default_chart("b", TITLE).replaced("</c:plotArea>", table);
assert_eq!(reason(default_chart("b", TITLE)), None);
assert_eq!(reason(tabled.clone()), Some(ChartReason::DataTable));
let horizontal = tabled.replaced(r#"<c:barDir val="col"/>"#, r#"<c:barDir val="bar"/>"#);
assert_eq!(reason(horizontal), Some(ChartReason::HorizontalBars));
}
/// A title of its own whose rich text has `paragraphs`, each with one run that writes `run`
/// in its run properties and `default` in its paragraph's default run properties, after
/// `before` in the title.
fn rich_title(before: &str, default: &str, run: &str, paragraphs: &[&str]) -> String {
use std::fmt::Write as _;
let paragraphs = paragraphs.iter().fold(String::new(), |mut out, text| {
let _ = write!(
out,
r#"<a:p><a:pPr><a:defRPr{default}/></a:pPr><a:r><a:rPr lang="en-US"{run}/><a:t>{text}</a:t></a:r></a:p>"#
);
out
});
format!("<c:title>{before}<c:tx><c:rich><a:bodyPr/>{paragraphs}</c:rich></c:tx></c:title>")
}
/// The title of the default chart with the title `xml`, read where the target's quirk
/// `ChartTitleText` is `drawn`.
fn read_title(
xml: &str,
drawn: crate::quirks::ChartTitleText,
) -> Result<Option<super::Title>, ChartReason> {
let doc = parse(&default_chart("b", xml));
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_title_text(drawn);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).map(|p| p.columns.title)
}
/// The text of a title with `lines` in the minor font, regular or `bold`.
fn shown(lines: &[&str], bold: bool) -> super::TitleText {
super::TitleText {
lines: lines.iter().map(|&line| line.to_owned()).collect(),
font: crate::props::FontRef::MinorLatin,
bold,
italic: false,
fill: None,
}
}
#[test]
fn reads_the_text_of_a_title_where_the_target_draws_it() {
use super::Title;
use crate::quirks::ChartTitleText;
let title = read_title;
// A size only in the paragraph's default: not known before, drawn with the rule.
let default = rich_title("", r#" sz="2000" b="0""#, "", &["A", "B c"]);
assert_eq!(
title(&default, ChartTitleText::Unknown),
Err(ChartReason::UnknownTitle)
);
assert_eq!(
title(&default, ChartTitleText::Drawn),
Ok(Some(Title {
lines: 2,
size: 40,
font: crate::props::FontRef::MinorLatin,
text: Some(shown(&["A", "B c"], false)),
corner: None,
}))
);
// A run's size and bold come before the default's; the earlier reading keeps no text.
let run = rich_title("", r#" sz="2000" b="0""#, r#" sz="1400" b="1""#, &["A"]);
assert_eq!(
title(&run, ChartTitleText::Unknown).map(|t| t.map(|t| (t.size, t.text))),
Ok(Some((28, None)))
);
assert_eq!(
title(&run, ChartTitleText::Drawn).map(|t| t.and_then(|t| t.text)),
Ok(Some(shown(&["A"], true)))
);
// No size and no bold anywhere: bold, at the chart text's size.
let plain = rich_title("", "", "", &["A"]);
assert_eq!(
title(&plain, ChartTitleText::Drawn).map(|t| t.map(|t| (t.size, t.text))),
Ok(Some((20, Some(shown(&["A"], true)))))
);
// The cached text of a reference, with the title's own text properties.
let reference = r#"<c:title><c:tx><c:strRef><c:f>Sheet1!$F$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>R</c:v></c:pt></c:strCache></c:strRef></c:tx><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="1400" b="0"/></a:pPr></a:p></c:txPr></c:title>"#;
assert_eq!(
title(reference, ChartTitleText::Drawn).map(|t| t.and_then(|t| t.text)),
Ok(Some(shown(&["R"], false)))
);
}
#[test]
fn shows_the_placeholder_in_a_title_without_text_where_the_target_knows_it() {
use crate::quirks::{ChartTitlePlaceholder, ChartTitleText};
let text = |xml: &str, placeholder| {
let doc = parse(xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_title_text(ChartTitleText::Drawn)
.with_title_placeholder(placeholder);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.map(|p| p.columns.title.and_then(|t| t.text))
};
let two = default_chart("b", TITLE);
assert_eq!(text(&two, ChartTitlePlaceholder::Unknown), Ok(None));
assert_eq!(
text(&two, ChartTitlePlaceholder::English),
Ok(Some(shown(&["Chart Title"], true)))
);
// One series: its cached name, no text when its name caches none, and the placeholder
// without a name.
let one = two.replaced(&series("accent2", &["2.4", "4.4"]), "");
let named = one.replaced(
FIRST_FILL,
&format!("<c:tx><c:v>N</c:v></c:tx>{FIRST_FILL}"),
);
assert_eq!(
text(&named, ChartTitlePlaceholder::English),
Ok(Some(shown(&["N"], true)))
);
assert_eq!(
text(&one, ChartTitlePlaceholder::English),
Ok(Some(shown(&["Chart Title"], true)))
);
let uncached = one.replaced(
FIRST_FILL,
&format!("<c:tx><c:strRef><c:f>S!$A$1</c:f><c:strCache><c:ptCount val=\"1\"/></c:strCache></c:strRef></c:tx>{FIRST_FILL}"),
);
assert_eq!(text(&uncached, ChartTitlePlaceholder::English), Ok(None));
}
#[test]
fn takes_18_pt_for_a_title_without_a_size_only_under_c14_style() {
use crate::quirks::ChartTitleText;
let plain = rich_title("", "", "", &["A"]);
let styled = |style: &str| {
let doc =
parse(&default_chart("b", &plain).replace("<c:chart>", &format!("{style}<c:chart>")));
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_title_text(ChartTitleText::Drawn);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.map(|p| p.columns.title.map(|t| t.size))
};
assert_eq!(styled(r#"<c:style val="2"/>"#), Ok(Some(20)));
assert_eq!(
styled(
r#"<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"><mc:Choice Requires="c14" xmlns:c14="http://schemas.microsoft.com/office/drawing/2007/8/2/chart"><c14:style val="130"/></mc:Choice><mc:Fallback><c:style val="30"/></mc:Fallback></mc:AlternateContent>"#
),
Ok(Some(36))
);
}
#[test]
fn reads_the_corner_of_a_titles_manual_layout_in_the_edge_mode() {
use crate::quirks::ChartTitleText;
let layout = |values: &str| {
rich_title("", r#" sz="1400""#, "", &["A"]).replaced(
"</c:title>",
&format!(
r#"<c:layout><c:manualLayout><c:xMode val="edge"/><c:yMode val="edge"/>{values}</c:manualLayout></c:layout></c:title>"#
),
)
};
let corner = super::LayoutCorner {
x: super::Decimal {
digits: 25,
exponent: -2,
},
y: super::Decimal {
digits: 5,
exponent: -2,
},
};
let read = |xml: &str| {
read_title(xml, ChartTitleText::Drawn).map(|t| t.map(|t| (t.corner, t.text.is_some())))
};
assert_eq!(
read(&layout(r#"<c:x val="0.25"/><c:y val="0.05"/>"#)),
Ok(Some((Some(corner), true)))
);
// A layout that also sets a size, or lacks a corner, keeps the room and draws no text.
for values in [
r#"<c:x val="0.25"/><c:y val="0.05"/><c:w val="0.5"/><c:h val="0.1"/>"#,
r#"<c:x val="0.25"/>"#,
] {
assert_eq!(read(&layout(values)), Ok(Some((None, false))), "{values}");
}
}
#[test]
fn keeps_no_text_of_a_title_that_it_does_not_draw() {
use crate::quirks::ChartTitleText;
use crate::reader::settings::PlotRules;
let title = read_title;
// A manual layout in the factor mode, a line break and runs of two sizes keep their room
// and draw no text.
let manual = rich_title(
"",
r#" sz="1400""#,
"",
&["A"],
)
.replaced("<c:tx>", r#"<c:layout><c:manualLayout><c:x val="0.1"/><c:y val="0"/></c:manualLayout></c:layout><c:tx>"#);
let broken = rich_title("", r#" sz="1400""#, "", &["A"]).replaced("</a:r>", "</a:r><a:br/>");
let sizes = rich_title("", "", r#" sz="1400""#, &["A"]).replaced(
"</a:r>",
r#"</a:r><a:r><a:rPr sz="1600"/><a:t>B</a:t></a:r>"#,
);
for xml in [manual, broken, sizes] {
assert_eq!(
title(&xml, ChartTitleText::Drawn).map(|t| t.map(|t| (t.size, t.text))),
Ok(Some((28, None))),
"{xml}"
);
}
// A chart whose text writes a size, and a title that writes none: not known.
let plain = rich_title("", "", "", &["A"]);
let doc = default_chart("b", &plain).replaced(
"<c:spPr><a:solidFill><a:schemeClr val=\"bg1\"/>",
&format!(
"{}<c:spPr><a:solidFill><a:schemeClr val=\"bg1\"/>",
text(1200)
),
);
let doc = parse(&doc);
let rules =
PlotRules::with_area(ChartPlotArea::FontLines).with_title_text(ChartTitleText::Drawn);
assert_eq!(
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).err(),
Some(ChartReason::UnknownTitle)
);
}
#[test]
fn warns_of_the_fills_of_a_chart_that_it_does_not_draw() {
let kinds = |area: &str, line: &str| {
let xml = default_chart("b", TITLE)
.replaced(
r#"<c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill></c:spPr>"#,
&format!("<c:spPr>{area}</c:spPr>"),
)
.replaced(
&format!("{CATEGORY_AXIS}{LINE}"),
&format!("{CATEGORY_AXIS}<c:spPr>{line}</c:spPr>"),
);
let doc = parse(&xml);
let mut reader = PartReader::new(&doc);
assert!(read(&mut reader, doc.root().unwrap()).is_ok());
let mut kinds: Vec<(&str, u32)> = reader
.drawing_warnings()
.iter()
.map(|(warning, count)| (warning.kind(), count))
.collect();
kinds.sort_unstable();
kinds
};
let solid = r#"<a:solidFill><a:srgbClr val="D9D9D9"/></a:solidFill>"#;
let gradient = r#"<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="D9D9D9"/></a:gs></a:gsLst></a:gradFill>"#;
let picture = "<a:blipFill><a:blip/></a:blipFill>";
let ln = |fill: &str| format!(r#"<a:ln w="9525">{fill}</a:ln>"#);
assert_eq!(kinds(solid, &ln(solid)), []);
// The chart area draws no picture fill.
assert_eq!(
kinds(picture, &ln(solid)),
[("drawingml-picture-fill-not-supported", 1)]
);
assert_eq!(
kinds(gradient, &ln(solid)),
[("drawingml-gradient-fill-not-supported", 1)]
);
// An axis draws only its line, so a fill of its properties is no feature that F-Office
// leaves out; a gradient of its line is.
assert_eq!(kinds(solid, &format!("{gradient}{}", ln(solid))), []);
assert_eq!(
kinds(solid, &ln(gradient)),
[("drawingml-gradient-fill-not-supported", 1)]
);
}
#[test]
fn leaves_out_the_charts_that_it_does_not_draw() {
let reason = |xml: &str| {
let doc = parse(xml);
read(&mut PartReader::new(&doc), doc.root().unwrap()).err()
};
// Without a title of its own, a chart whose automatic title is not deleted has a title
// that F-Office does not know, and one whose automatic title is deleted has none, which
// the rule of DefaultChart does not draw.
let untitled = default_chart("b", "");
assert_eq!(reason(&untitled), Some(ChartReason::UnknownTitle));
let deleted = untitled.replaced(
r#"<c:autoTitleDeleted val="0"/>"#,
r#"<c:autoTitleDeleted val="1"/>"#,
);
assert_eq!(reason(&deleted), Some(ChartReason::Untitled));
assert_eq!(
reason(&default_chart("t", TITLE)),
Some(ChartReason::LegendNotAtBottom)
);
let negative = default_chart("b", TITLE).replaced_all("<c:v>2.5</c:v>", "<c:v>-2.5</c:v>");
assert_eq!(reason(&negative), Some(ChartReason::NegativeValue));
let rows = default_chart("b", TITLE).replaced_all(r#"barDir val="col""#, r#"barDir val="bar""#);
assert_eq!(reason(&rows), Some(ChartReason::HorizontalBars));
}
#[test]
fn hides_the_automatic_title_where_the_target_shows_none() {
let reason = |xml: &str, automatic: ChartAutomaticTitle| {
let doc = parse(xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_automatic_title(automatic);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).err()
};
let mark = r#"<c:autoTitleDeleted val="0"/>"#;
// Two series without names, with and without the mark, and one series without a name.
let untitled = default_chart("b", "");
let unmarked = untitled.replaced(mark, "");
let one = untitled.replaced(&series("accent2", &["2.4", "4.4"]), "");
for xml in [&untitled, &unmarked, &one] {
assert_eq!(
reason(xml, ChartAutomaticTitle::Unknown),
Some(ChartReason::UnknownTitle)
);
assert_eq!(reason(xml, ChartAutomaticTitle::OnlySeriesName), None);
}
// One named series shows its name where the chart writes the mark, which F-Office does
// not draw, and no title without the mark.
let named = one.replaced(
&format!("<c:ser>{FIRST_FILL}"),
&format!(
r#"<c:ser><c:tx><c:strRef><c:f>Sheet1!$B$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>North</c:v></c:pt></c:strCache></c:strRef></c:tx>{FIRST_FILL}"#
),
);
assert_eq!(
reason(&named, ChartAutomaticTitle::OnlySeriesName),
Some(ChartReason::UnknownTitle)
);
assert_eq!(
reason(
&named.replaced(mark, ""),
ChartAutomaticTitle::OnlySeriesName
),
None
);
// A title of its own stays as it was.
assert_eq!(
reason(
&default_chart("b", TITLE),
ChartAutomaticTitle::OnlySeriesName
),
None
);
}
#[test]
fn reads_no_series_whose_count_is_above_its_points() {
let count = |val: &str| {
let xml = default_chart("b", TITLE).replaced(
&format!(r#"{FIRST_FILL}<c:val><c:numRef><c:numCache><c:ptCount val="2"/>"#),
&format!(r#"{FIRST_FILL}<c:val><c:numRef><c:numCache><c:ptCount val="{val}"/>"#),
);
let doc = parse(&xml);
read(&mut PartReader::new(&doc), doc.root().unwrap()).is_ok()
};
assert!(count("2"));
assert!(!count("3"));
// The largest count of 64 bits is refused before a vector of that size is made.
assert!(!count("18446744073709551615"));
}
#[test]
fn gives_a_chart_in_a_text_box_its_part() {
use std::rc::Rc;
use crate::body::{Block, Content, InlineDrawing, Paragraph, Run};
use crate::floating::Floating;
let doc = parse(&default_chart("b", TITLE));
let found = read(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
let paragraph = |content| {
Block::Paragraph(Paragraph {
runs: vec![Run {
content: vec![content],
..Run::default()
}],
..Paragraph::empty()
})
};
// An inline chart in the text box of a floating shape.
let chart = Floating {
chart: Some(super::Chart {
id: "rId8".to_owned(),
columns: None,
}),
..Floating::default()
};
let text_box = Floating {
blocks: vec![paragraph(Content::Drawing(Rc::new(
InlineDrawing::of_shape(chart),
)))],
..Floating::default()
};
let mut blocks = vec![paragraph(Content::Floating(Box::new(text_box)))];
super::attach_charts(&mut blocks, &mut |id| (id == "rId8").then(|| found.clone()));
let Block::Paragraph(outer) = &blocks[0] else {
panic!("no paragraph");
};
let Content::Floating(text_box) = &outer.runs[0].content[0] else {
panic!("no text box");
};
let Block::Paragraph(inner) = &text_box.blocks[0] else {
panic!("no paragraph in the text box");
};
let Content::Drawing(drawing) = &inner.runs[0].content[0] else {
panic!("no inline drawing");
};
let columns = drawing.shape.chart.as_ref().unwrap().columns.as_deref();
assert_eq!(columns, Some(&found.columns));
}
/// A paragraph of an inline chart whose part the relationship `id` of its story's part names.
fn chart_paragraph(id: &str) -> String {
let wp = crate::ns::WP;
format!(
r#"<w:p><w:r><w:drawing><wp:inline xmlns:wp="{wp}" xmlns:a="{A}" xmlns:c="{C}"><wp:extent cx="914400" cy="457200"/><a:graphic><a:graphicData><c:chart r:id="{id}"/></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
)
}
/// The chart of the inline drawing of the first run of `block`, a paragraph.
fn chart_of(block: &crate::body::Block) -> &super::Chart {
let crate::body::Block::Paragraph(paragraph) = block else {
panic!("no paragraph");
};
let crate::body::Content::Drawing(drawing) = ¶graph.runs[0].content[0] else {
panic!("no inline drawing");
};
drawing.shape.chart.as_ref().unwrap()
}
/// A package whose main document names the part `word/{target}` of the relationship type
/// `kind` by the ID `p1`; that part, with the root `w:{root}` around `content`, names a chart
/// part that F-Office draws by the relationship `c1`.
fn package_with_chart(
kind: &str,
target: &str,
root: &str,
content: &str,
) -> f_office_opc::Package {
use crate::testing::{self, WordParts as _};
let bytes = testing::docx("<w:sectPr/>")
.word_part("p1", kind, target, root, content)
.relationship(
&format!("word/{target}"),
"c1",
"chart",
"charts/chart1.xml",
)
.part("word/charts/chart1.xml", default_chart("b", TITLE))
.plain_styles()
.zip()
.unwrap();
f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap()
}
#[test]
fn gives_a_chart_in_a_header_its_part() {
let package = package_with_chart("header", "h1.xml", "hdr", &chart_paragraph("c1"));
let relationships = &package
.relationships(&package.main_document().unwrap())
.unwrap()
.relationships;
let (_, _, reader, _) =
crate::quirks_and_device(&crate::Options::default().profile().unwrap()).unwrap();
let (styles, theme) = (
crate::styles::Styles::default(),
crate::styles::Theme::default(),
);
let mut stories = crate::StoryParts::new(
&package,
relationships,
(reader, &styles, &theme),
&crate::body::TEST_PARAGRAPH_IDS,
);
let refs = crate::body::References {
default: Some("p1".to_owned()),
..crate::body::References::default()
};
let header = stories
.stories(&refs, &mut crate::Warnings::new())
.unwrap()
.default
.unwrap();
assert!(chart_of(&header.blocks[0]).columns.is_some());
}
#[test]
fn gives_a_chart_in_a_footnote_its_part() {
let footnote = format!(
r#"<w:footnote w:id="1">{}</w:footnote>"#,
chart_paragraph("c1")
);
let package = package_with_chart("footnotes", "footnotes.xml", "footnotes", &footnote);
let (_, _, reader, _) =
crate::quirks_and_device(&crate::Options::default().profile().unwrap()).unwrap();
let (styles, theme) = (
crate::styles::Styles::default(),
crate::styles::Theme::default(),
);
let notes = crate::read_notes(
&package,
Some("word/footnotes.xml".to_owned()),
(&styles, &theme),
&mut crate::parts::Reading {
warnings: &mut crate::Warnings::new(),
ids: &crate::body::TEST_PARAGRAPH_IDS,
settings: reader,
notes: None,
colors: f_office_drawingml::color::SchemeColors::default(),
styles: None,
},
)
.unwrap();
assert!(
chart_of(¬es.by_id[&crate::body::NoteId::of(1)][0])
.columns
.is_some()
);
}
#[test]
fn reads_the_names_of_the_chart_types() {
use crate::enumerations::assert_names;
assert_names(super::BAR_DIRECTION, "bar col");
assert_names(
super::BAR_GROUPING,
"percentStacked clustered standard stacked",
);
assert_names(super::ORIENTATION, "maxMin minMax");
assert_names(super::LABEL_POSITION, "high low nextTo none");
assert_names(super::LEGEND_POSITION, "b tr l r t");
}
#[test]
fn has_a_model_of_the_bar_line_and_pie_charts_only() {
let model = |xml: &str| {
let doc = parse(xml);
super::ChartModel::read(&mut PartReader::new(&doc), doc.root().unwrap())
.map(|_| ())
.err()
};
let columns = default_chart("b", TITLE);
assert_eq!(model(&columns), None);
// A line chart has a model, which the rule of `DefaultChart` does not draw.
let lines = columns.replaced_all("c:barChart>", "c:lineChart>");
assert_eq!(model(&lines), None);
let doc = parse(&line_chart());
assert_eq!(
read(&mut PartReader::new(&doc), doc.root().unwrap()).err(),
Some(ChartReason::Lines)
);
// A pie chart has a model, which a target that draws no pie leaves out.
let pie = columns.replaced_all("c:barChart>", "c:pieChart>");
assert_eq!(model(&pie), None);
let doc = parse(&pie);
assert_eq!(
read(&mut PartReader::new(&doc), doc.root().unwrap()).err(),
Some(ChartReason::OtherGroup)
);
// An area chart has none, and nor has a bar chart without its direction.
assert_eq!(
model(&columns.replaced_all("c:barChart>", "c:areaChart>")),
Some(ChartReason::OtherGroup)
);
assert_eq!(
model(&columns.replaced_all(r#"<c:barDir val="col"/>"#, "")),
Some(ChartReason::NoBarDirection)
);
}
#[test]
fn warns_of_the_looks_of_a_chart_only_when_it_draws_it() {
// A gradient fill of the chart area warns in a chart that F-Office draws. A chart that it
// leaves out, here for its legend at the top, has only the warning `chart-skipped`, which
// the reader of the document gives.
let gradient = r#"<c:spPr><a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="D9D9D9"/></a:gs></a:gsLst></a:gradFill></c:spPr>"#;
for (legend, drawn, warnings) in [("b", true, 1), ("t", false, 0)] {
let xml = default_chart(legend, TITLE).replaced(
r#"<c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill></c:spPr>"#,
gradient,
);
let doc = parse(&xml);
let mut reader = PartReader::new(&doc);
assert_eq!(read(&mut reader, doc.root().unwrap()).is_ok(), drawn);
assert_eq!(reader.drawing_warnings().len(), warnings);
}
}
#[test]
fn warns_of_a_value_that_does_not_read_in_every_chart_with_a_model() {
let invalid = |xml: &str| {
let doc = parse(xml);
let mut reader = PartReader::new(&doc);
assert!(read(&mut reader, doc.root().unwrap()).is_err());
reader.invalid_values().len()
};
let wide = default_chart("t", TITLE)
.replaced_all(r#"<c:gapWidth val="219"/>"#, r#"<c:gapWidth val="wide"/>"#);
assert_eq!(invalid(&wide), 1);
// A pie chart has no model, so that its values are not read.
assert_eq!(invalid(&wide.replaced_all("c:barChart>", "c:pieChart>")), 0);
}
#[test]
fn reads_an_axis_delete_without_a_value_as_on_and_false_as_off() {
// An axis' `c:delete` without a value, or with `1` or `true`, deletes the axis, so that
// F-Office does not draw the chart; with `0` or `false`, the axis shows.
let shown = default_chart("b", TITLE);
for (delete, drawn) in [
("<c:delete/>", false),
(r#"<c:delete val="1"/>"#, false),
(r#"<c:delete val="true"/>"#, false),
(r#"<c:delete val="0"/>"#, true),
(r#"<c:delete val="false"/>"#, true),
] {
let xml = shown.replaced(CATEGORY_AXIS, &format!("<c:catAx>{delete}"));
let doc = parse(&xml);
assert_eq!(
read(&mut PartReader::new(&doc), doc.root().unwrap()).is_ok(),
drawn,
"{delete}"
);
}
}
#[test]
fn reads_each_form_of_a_boolean_element() {
use super::Flag;
let read = |child: &str| {
let doc = parse(&format!(r#"<c:legend xmlns:c="{C}">{child}</c:legend>"#));
Flag::of(&doc, doc.root().unwrap(), "overlay")
};
for on in [
"<c:overlay/>",
r#"<c:overlay val="1"/>"#,
r#"<c:overlay val="true"/>"#,
] {
assert_eq!(read(on), Flag::On, "{on}");
}
for off in [r#"<c:overlay val="0"/>"#, r#"<c:overlay val="false"/>"#] {
assert_eq!(read(off), Flag::Off, "{off}");
}
assert_eq!(read(r#"<c:legendPos val="b"/>"#), Flag::Missing);
assert!(!Flag::Missing.is_on());
}
/// The rule of `DefaultChart`, of `FontLines`, and no drawing, as [`rules`] gives them.
const DEFAULT_RULE: Option<PlotRule> = Some(PlotRule::DefaultChart);
const LINE_RULE: Option<PlotRule> = Some(PlotRule::FontLines);
const NOT_DRAWN: Option<PlotRule> = None;
/// The rules that place the plot area of a chart part on the targets whose quirks are
/// `DefaultChart` and `FontLines`, `None` where the target does not draw it.
fn rules(xml: &str) -> [Option<PlotRule>; 2] {
let doc = parse(xml);
[ChartPlotArea::DefaultChart, ChartPlotArea::FontLines].map(|area| {
read_on(area, &mut PartReader::new(&doc), doc.root().unwrap())
.ok()
.and_then(|part| {
crate::reader::settings::PlotRules::with_area(area)
.rule(&part.columns)
.ok()
})
})
}
/// `xml` with `inner` after the first `start` tag.
fn with(xml: &str, start: &str, inner: &str) -> String {
xml.replaced(start, &format!("{start}{inner}"))
}
/// A manual layout of the plot area in the modes `x_mode` and `y_mode`, or the default mode
/// for an empty name.
fn manual_layout(target: &str, x_mode: &str, y_mode: &str) -> String {
let mode = |name: &str, value: &str| {
if value.is_empty() {
String::new()
} else {
format!(r#"<c:{name} val="{value}"/>"#)
}
};
format!(
r#"<c:layout><c:manualLayout><c:layoutTarget val="{target}"/>{}{}<c:x val="0.1"/><c:y val="0.15"/><c:w val="0.8"/><c:h val="0.6"/></c:manualLayout></c:layout>"#,
mode("xMode", x_mode),
mode("yMode", y_mode)
)
}
/// Checks for each case, by its name, the rules that place its chart part's plot area on the
/// targets whose quirks are `DefaultChart` and `FontLines`.
fn assert_rules(cases: Vec<(&str, String, [Option<PlotRule>; 2])>) {
for (name, xml, expected) in cases {
assert_eq!(rules(&xml), expected, "{name}");
}
}
#[test]
fn draws_each_legend_place_on_font_lines() {
let default = default_chart("b", TITLE);
let start = default.find("<c:legend>").unwrap();
let end = default.find("</c:legend>").unwrap() + "</c:legend>".len();
let named =
default_chart("l", TITLE).replaced_all("<c:ser>", "<c:ser><c:tx><c:v>S</c:v></c:tx>");
assert_rules(vec![
("bottom", default.clone(), [DEFAULT_RULE, LINE_RULE]),
("top", default_chart("t", TITLE), [NOT_DRAWN, LINE_RULE]),
// A legend at a side needs the series' names, which the default series lack.
(
"right without names",
default_chart("r", TITLE),
[NOT_DRAWN, NOT_DRAWN],
),
("left with names", named, [NOT_DRAWN, LINE_RULE]),
// A legend at the top right corner is drawn by neither.
(
"top right",
default_chart("tr", TITLE),
[NOT_DRAWN, NOT_DRAWN],
),
(
"none",
format!("{}{}", &default[..start], &default[end..]),
[NOT_DRAWN, LINE_RULE],
),
]);
}
#[test]
fn draws_the_titles_values_and_scales_on_font_lines() {
let default = default_chart("b", TITLE);
let deleted = r#"<c:autoTitleDeleted val="1"/>"#;
let scaling = r#"<c:scaling><c:orientation val="minMax"/><c:max val="8"/></c:scaling>"#;
let empty =
r#"<c:scaling><c:orientation val="minMax"/><c:max val="1"/><c:min val="1"/></c:scaling>"#;
assert_rules(vec![
// A deleted automatic title shows no title; a title of its own with a deleted
// automatic title is not known.
(
"untitled",
default_chart("b", "").replaced_all(r#"<c:autoTitleDeleted val="0"/>"#, deleted),
[NOT_DRAWN, LINE_RULE],
),
(
"title and deleted title",
default.replaced_all(r#"<c:autoTitleDeleted val="0"/>"#, deleted),
[NOT_DRAWN, NOT_DRAWN],
),
(
"negative",
default.replaced_all("<c:v>2.5</c:v>", "<c:v>-2.5</c:v>"),
[NOT_DRAWN, LINE_RULE],
),
(
"set maximum",
with(&default, "<c:valAx>", scaling),
[NOT_DRAWN, LINE_RULE],
),
(
"no range",
with(&default, "<c:valAx>", empty),
[NOT_DRAWN, NOT_DRAWN],
),
]);
}
#[test]
fn places_an_axis_title_or_value_format_with_the_default_rule_on_font_lines() {
let default = default_chart("b", TITLE);
let axis_title = "<c:title><c:tx><c:rich><a:bodyPr/><a:p/></c:rich></c:tx></c:title>";
let own = |code: &str, linked: &str| {
format!(r#"<c:numFmt formatCode="{code}" sourceLinked="{linked}"/>"#)
};
let cached = |code: &str| {
default.replaced(
&format!("{FIRST_FILL}<c:val><c:numRef><c:numCache>"),
&format!(
"{FIRST_FILL}<c:val><c:numRef><c:numCache><c:formatCode>{code}</c:formatCode>"
),
)
};
// Both draw them all; FontLines places a chart with an axis title, or with value labels in
// another format than General, whether the axis sets it or takes its source's, with the
// rule of DefaultChart.
assert_rules(vec![
(
"value axis title",
with(&default, "<c:valAx>", axis_title),
[DEFAULT_RULE, DEFAULT_RULE],
),
(
"category axis title",
with(&default, "<c:catAx>", axis_title),
[DEFAULT_RULE, DEFAULT_RULE],
),
(
"own percent",
with(&default, "<c:valAx>", &own("0%", "0")),
[DEFAULT_RULE, DEFAULT_RULE],
),
(
"own general",
with(&default, "<c:valAx>", &own("general", "0")),
[DEFAULT_RULE, LINE_RULE],
),
(
"cache general",
cached("General"),
[DEFAULT_RULE, LINE_RULE],
),
(
"cache with decimals",
cached("0.0"),
[DEFAULT_RULE, DEFAULT_RULE],
),
(
"linked to the cache",
with(&cached("#,##0"), "<c:valAx>", &own("General", "1")),
[DEFAULT_RULE, DEFAULT_RULE],
),
(
"own general over the cache",
with(&cached("#,##0"), "<c:valAx>", &own("General", "0")),
[DEFAULT_RULE, LINE_RULE],
),
]);
}
#[test]
fn gives_the_reason_of_the_targets_own_rule_when_its_fallback_does_not_draw_either() {
// FontLines places a chart outside its scope with the rule of DefaultChart; when that rule
// does not draw the chart either, the reason is the first condition of FontLines' scope
// that the chart does not meet.
let axis_title = "<c:title><c:tx><c:rich><a:bodyPr/><a:p/></c:rich></c:tx></c:title>";
let doc = parse(&with(&default_chart("t", TITLE), "<c:valAx>", axis_title));
let reasons = [ChartPlotArea::DefaultChart, ChartPlotArea::FontLines]
.map(|area| read_on(area, &mut PartReader::new(&doc), doc.root().unwrap()).err());
assert_eq!(
reasons,
[
Some(ChartReason::LegendNotAtBottom),
Some(ChartReason::AxisTitle)
]
);
}
#[test]
fn draws_the_manual_layouts_and_crossings_that_font_lines_reads() {
let default = default_chart("b", TITLE);
// A manual layout in the edge mode is drawn with each target's rule; one in another mode,
// and axes that cross elsewhere than at the automatic zero, with the rule of DefaultChart,
// which reads neither.
assert_rules(vec![
(
"edge",
with(
&default,
"<c:plotArea>",
&manual_layout("inner", "edge", "edge"),
),
[DEFAULT_RULE, LINE_RULE],
),
(
"factor",
with(
&default,
"<c:plotArea>",
&manual_layout("inner", "", "edge"),
),
[DEFAULT_RULE, DEFAULT_RULE],
),
(
"crosses at the maximum",
with(&default, "<c:catAx>", r#"<c:crosses val="max"/>"#),
[DEFAULT_RULE, DEFAULT_RULE],
),
]);
}
#[test]
fn reads_the_names_layout_and_scale_of_a_drawn_chart() {
let cached = r#"<c:tx><c:strRef><c:f>Sheet1!$B$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>North</c:v></c:pt></c:strCache></c:strRef></c:tx>"#;
let xml = default_chart("b", TITLE)
.replaced(FIRST_FILL, &format!("{cached}{FIRST_FILL}"))
.replaced(
"<c:ser><c:spPr>",
"<c:ser><c:tx><c:v>South</c:v></c:tx><c:spPr>",
);
let xml = with(
&xml,
"<c:plotArea>",
&manual_layout("outer", "edge", "edge"),
);
let scaling = r#"<c:scaling><c:orientation val="minMax"/><c:min val="-2"/></c:scaling>"#;
let xml = with(&xml, "<c:valAx>", scaling);
let xml = xml.replaced("</c:valAx>", r#"<c:majorUnit val="0.5"/></c:valAx>"#);
let doc = parse(&xml);
let found = read_on(
ChartPlotArea::FontLines,
&mut PartReader::new(&doc),
doc.root().unwrap(),
)
.unwrap();
let columns = found.columns;
let names: Vec<_> = columns.series.iter().map(|s| s.name.as_deref()).collect();
assert_eq!(names, [Some("North"), Some("South")]);
let [x, y, w, h] = ["0.1", "0.15", "0.8", "0.6"].map(|v| Decimal::parse(v).unwrap());
let layout = super::PlotLayout {
inner: false,
edges: super::LayoutBox { x, y, w, h },
};
let scale = super::SetScale {
min: Decimal::parse("-2"),
max: None,
major_unit: Decimal::parse("0.5"),
};
assert_eq!(
(columns.plot_place, columns.scale),
(super::PlotPlace::Manual(layout), scale)
);
assert_eq!(
(columns.category_crossing, columns.legend),
(
Some(super::CategoryCrossing::AutoZero),
Some(super::LegendPlace::Bottom)
)
);
}
#[test]
fn reads_the_texts_of_the_categories_and_the_fills_of_the_labels() {
let categories = r#"<c:cat><c:strRef><c:strCache><c:ptCount val="2"/><c:pt idx="1"><c:v>Two</c:v></c:pt><c:pt idx="0"><c:v>One</c:v></c:pt></c:strCache></c:strRef></c:cat>"#;
let filled = r#"<a:defRPr sz="900"><a:solidFill><a:srgbClr val="595959"/></a:solidFill>"#;
let chart = default_chart("b", TITLE);
let with = chart.replaced(FIRST_FILL, &format!("{FIRST_FILL}{categories}"));
// The text of the category axis, the only one after an axis line.
let labels = "<c:txPr><a:bodyPr/><a:p><a:pPr>";
let with = with.replaced(
&format!(r#"{LINE}{labels}<a:defRPr sz="900">"#),
&format!("{LINE}{labels}{filled}"),
);
let doc = parse(&with);
let columns = read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns;
assert_eq!(
columns.category_names,
Some(vec!["One".to_owned(), "Two".to_owned()])
);
// The first axis' labels, the category axis', name their fill; the value axis' do not.
let gray = f_office_paint::Rgb {
r: 0x59,
g: 0x59,
b: 0x59,
};
assert_eq!(
columns.category_label_fill,
Some(f_office_drawingml::color::DrawColor::rgb(gray))
);
assert_eq!(columns.value_label_fill, None);
// Categories with a point missing, or numbers, give no names.
let missing = chart.replaced(
FIRST_FILL,
&format!(
"{FIRST_FILL}{}",
categories.replaced(r#"<c:pt idx="1"><c:v>Two</c:v></c:pt>"#, "")
),
);
let numbers = chart.replaced(FIRST_FILL, &format!(r#"{FIRST_FILL}<c:cat><c:numRef><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:cat>"#));
for xml in [missing, numbers, chart] {
let doc = parse(&xml);
let columns = read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns;
assert_eq!(columns.category_names, None);
}
}
#[test]
fn reads_numeric_and_omitted_categories_under_label_codes() {
use crate::quirks::{ChartBlankPoints, ChartLabelFormats};
let separators = crate::NumberSeparators::new('.', ',').unwrap();
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_label_formats(ChartLabelFormats::Codes, Some(separators))
.with_blank_points(ChartBlankPoints::AsDisplayed);
let read_names = |xml: &str| {
let doc = parse(xml);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.unwrap()
.columns
.category_names
};
let base = default_chart("b", TITLE);
// Omitted <c:cat> falls back to 1-based category numbers.
assert_eq!(read_names(&base), Some(vec!["1".into(), "2".into()]));
// <c:cat><c:numRef><c:numCache> formats with cache formatCode (or catAx own numFmt).
let with_cat =
|cat: &str| base.replaced(FIRST_FILL, &format!("{FIRST_FILL}<c:cat>{cat}</c:cat>"));
let linked = with_cat(
r#"<c:numRef><c:numCache><c:formatCode>0.0</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2.25</c:v></c:pt></c:numCache></c:numRef>"#,
);
assert_eq!(read_names(&linked), Some(vec!["1.0".into(), "2.3".into()]));
let axis_override = linked.replaced(
"<c:catAx>",
r#"<c:catAx><c:numFmt formatCode="0.0%" sourceLinked="0"/>"#,
);
assert_eq!(
read_names(&axis_override),
Some(vec!["100.0%".into(), "225.0%".into()])
);
// <c:numLit> uses the 11-character General cap (0.333333333) and keeps blank points empty.
let num_lit = with_cat(
r#"<c:numLit><c:formatCode>General</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>0.3333333333333333</c:v></c:pt></c:numLit>"#,
);
assert_eq!(
read_names(&num_lit),
Some(vec!["0.333333333".into(), String::new()])
);
// Date format codes in <c:numCache> stay unsupported (None).
let dates = with_cat(
r#"<c:numRef><c:numCache><c:formatCode>m/d/yyyy</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>44927</c:v></c:pt><c:pt idx="1"><c:v>44958</c:v></c:pt></c:numCache></c:numRef>"#,
);
assert_eq!(read_names(&dates), None);
}
/// The size and font of a drawn chart's labels, or why F-Office does not draw it.
fn label_text(xml: &str) -> Result<(i64, crate::props::FontRef), ChartReason> {
let doc = parse(xml);
read(&mut PartReader::new(&doc), doc.root().unwrap())
.map(|found| (found.columns.label_size, found.columns.font))
}
/// The text of a chart space: `size` hundredths of a point in `face`.
fn space_text(size: u32, face: &str) -> String {
format!(
r#"<c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="{size}"><a:latin typeface="{face}"/></a:defRPr></a:pPr></a:p></c:txPr></c:chartSpace>"#
)
}
#[test]
fn takes_the_size_and_font_of_the_chart_text_where_an_element_sets_none() {
use crate::props::FontRef;
// Without a size on the axes and the legend or in the chart space, the labels are 10 pt in
// the theme's body font.
let bare = default_chart("b", TITLE).replaced_all(&text(900), "");
assert_eq!(label_text(&bare), Ok((20, FontRef::MinorLatin)));
// The chart space's text gives its size and font to each element that sets none.
let inherited = bare.replaced("</c:chartSpace>", &space_text(1100, "Georgia"));
assert_eq!(
label_text(&inherited),
Ok((22, FontRef::of_typeface("Georgia")))
);
// An element's own size and font win over the chart space's.
let own = default_chart("b", TITLE).replaced("</c:chartSpace>", &space_text(1100, "Georgia"));
assert_eq!(label_text(&own), Ok((18, FontRef::MinorLatin)));
// A legend without a size takes the chart space's, or 10 pt, beside axis labels of 9 pt.
let legend = default_chart("b", TITLE).replaced(
&format!(r#"<c:legendPos val="b"/>{}"#, text(900)),
r#"<c:legendPos val="b"/>"#,
);
assert_eq!(label_text(&legend), Ok((18, FontRef::MinorLatin)));
assert_eq!(legend_size(&legend), Ok(20));
let spaced = legend.replaced("</c:chartSpace>", &space_text(1200, "+mn-lt"));
assert_eq!(legend_size(&spaced), Ok(24));
// A legend's own size wins, whatever the axis labels write.
let own = default_chart("b", TITLE).replaced(
&format!(r#"<c:legendPos val="b"/>{}"#, text(900)),
&format!(r#"<c:legendPos val="b"/>{}"#, text(1400)),
);
assert_eq!(legend_size(&own), Ok(28));
}
/// The size of a drawn chart's legend entries, in half-points, or why F-Office does not draw it.
fn legend_size(xml: &str) -> Result<i64, ChartReason> {
let doc = parse(xml);
read(&mut PartReader::new(&doc), doc.root().unwrap()).map(|found| found.columns.legend_size)
}
/// The form of each series' data labels in the chart part `xml`, and whether any is another
/// form.
fn label_forms(xml: &str) -> (Vec<&'static str>, bool) {
let doc = parse(xml);
let columns = read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns;
let forms = columns
.series
.iter()
.map(|series| match &series.labels {
SeriesLabels::Hidden => "hidden",
SeriesLabels::Values(_) => "values",
SeriesLabels::Other => "other",
})
.collect();
(forms, columns.other_labels)
}
/// A chart part whose group's labels show the values on every series.
fn group_value_labels() -> String {
default_chart("b", TITLE).replaced(
"<c:gapWidth",
r#"<c:dLbls><c:showVal val="1"/></c:dLbls><c:gapWidth"#,
)
}
#[test]
fn reads_the_data_labels_of_each_series() {
assert_eq!(
label_forms(&default_chart("b", TITLE)),
(vec!["hidden"; 2], false)
);
let group = group_value_labels();
assert_eq!(label_forms(&group), (vec!["values"; 2], false));
// A property without a value is on, and the outer end is the values' place.
assert_eq!(
label_forms(&group.replaced(
r#"<c:showVal val="1"/>"#,
r#"<c:dLblPos val="outEnd"/><c:showVal/>"#
)),
(vec!["values"; 2], false)
);
// Deleted labels show nothing.
assert_eq!(
label_forms(&group.replaced(
r#"<c:showVal val="1"/>"#,
r#"<c:delete val="1"/><c:showVal val="1"/>"#
)),
(vec!["hidden"; 2], false)
);
// A format linked to the source takes the cache's General.
assert_eq!(
label_forms(&group.replaced(
r#"<c:showVal val="1"/>"#,
r#"<c:numFmt formatCode="0%" sourceLinked="1"/><c:showVal val="1"/>"#
)),
(vec!["values"; 2], false)
);
}
#[test]
fn reads_other_forms_of_data_labels_and_each_series_own() {
let group = group_value_labels();
// Another place, another part of the text and a number format of their own are other forms.
for other in [
r#"<c:dLblPos val="t"/><c:showVal val="1"/>"#,
r#"<c:showVal val="1"/><c:showCatName val="1"/>"#,
r#"<c:numFmt formatCode="0%" sourceLinked="0"/><c:showVal val="1"/>"#,
] {
let found = label_forms(&group.replaced(r#"<c:showVal val="1"/>"#, other));
assert_eq!(found, (vec!["other"; 2], true), "{other}");
}
// Clustered column inside positions (ctr, inEnd, inBase) are drawn as values.
for pos in ["ctr", "inEnd", "inBase"] {
let drawn = format!(r#"<c:dLblPos val="{pos}"/><c:showVal val="1"/>"#);
let found = label_forms(&group.replaced(r#"<c:showVal val="1"/>"#, &drawn));
assert_eq!(found, (vec!["values"; 2], false), "{pos}");
}
// Each series' own labels win over the group's, and a label of one point is another form.
let series_off = group.replaced_all(
"</c:spPr><c:val>",
r#"</c:spPr><c:dLbls><c:showVal val="0"/></c:dLbls><c:val>"#,
);
assert_eq!(label_forms(&series_off), (vec!["hidden"; 2], false));
let one_point = default_chart("b", TITLE).replaced(
&format!("{FIRST_FILL}<c:val>"),
&format!(
r#"{FIRST_FILL}<c:dLbls><c:dLbl><c:idx val="0"/><c:showPercent val="true"/></c:dLbl><c:showVal val="0"/></c:dLbls><c:val>"#
),
);
assert_eq!(label_forms(&one_point), (vec!["other", "hidden"], true));
}
#[test]
fn gives_data_labels_their_size_font_and_insets() {
use crate::props::FontRef;
let labels = |xml: &str| {
let doc = parse(xml);
let columns = read(&mut PartReader::new(&doc), doc.root().unwrap())
.unwrap()
.columns;
match columns.series.first().map(|series| series.labels.clone()) {
Some(SeriesLabels::Values(labels)) => Some(labels),
_ => None,
}
};
let chart = default_chart("b", TITLE);
// Without a text of their own: the chart text's size, else 10 pt, and the body font.
let plain = chart.replaced(
"<c:gapWidth",
r#"<c:dLbls><c:showVal val="1"/></c:dLbls><c:gapWidth"#,
);
let found = labels(&plain).unwrap();
assert_eq!((found.size, found.font), (20, FontRef::MinorLatin));
// Word's text box: its own size and font.
let word = chart.replaced(
"<c:gapWidth",
r#"<c:dLbls><c:txPr><a:bodyPr lIns="38100" tIns="19050" rIns="38100" bIns="19050"/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="900"><a:latin typeface="Georgia"/></a:defRPr></a:pPr></a:p></c:txPr><c:showVal val="1"/></c:dLbls><c:gapWidth"#,
);
let found = labels(&word).unwrap();
assert_eq!(found.size, 18);
assert_eq!(found.font, FontRef::of_typeface("Georgia"));
// Each inset that the text box misses is Word's own for data labels, not the text box's.
let (side, top) = crate::params::CHART_DATA_LABEL_INSETS;
assert_eq!(labels(&plain).unwrap().insets.top, top);
let left = word.replaced(
r#"<a:bodyPr lIns="38100" tIns="19050" rIns="38100" bIns="19050"/>"#,
r#"<a:bodyPr lIns="228600"/>"#,
);
let insets = labels(&left).unwrap().insets;
assert_eq!(
(insets.left, insets.top, insets.right, insets.bottom),
(
f_office_units::Length::from_emus(228_600).unwrap(),
top,
side,
top
)
);
}
/// What a target whose quirk `ChartLabelFormats` is `formats`, with the separators `.,` of an
/// en-US machine, reads of the chart `xml`: the label format of its value labels, and the label
/// format of its first series' data labels, or `None` when it does not draw them.
fn label_formats(
xml: &str,
formats: crate::quirks::ChartLabelFormats,
) -> (Option<super::LabelFormat>, Option<super::LabelFormat>) {
let doc = parse(xml);
let separators = crate::NumberSeparators::new('.', ',').unwrap();
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_label_formats(formats, Some(separators));
let columns = super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.unwrap()
.columns;
let labels = match columns.series.first().map(|series| series.labels.clone()) {
Some(SeriesLabels::Values(labels)) => Some(labels.format),
_ => None,
};
(columns.value_format, labels)
}
#[test]
fn writes_labels_in_their_number_formats_where_the_target_writes_them() {
use crate::quirks::ChartLabelFormats::{Codes, Unknown};
let chart = default_chart("b", TITLE);
let own = |code: &str| {
chart.replaced(
"<c:gapWidth",
&format!(
r#"<c:dLbls><c:numFmt formatCode="{code}" sourceLinked="0"/><c:showVal val="1"/></c:dLbls><c:gapWidth"#
),
)
};
let separators = crate::NumberSeparators::new('.', ',').unwrap();
let percent = super::LabelFormat::code("0.0%", separators);
// Data labels in a format other than General: drawn in it under Codes only.
assert_eq!(label_formats(&own("0.0%"), Unknown).1, None);
assert_eq!(label_formats(&own("0.0%"), Codes).1, percent);
// A format that F-Office does not write leaves them out on every target.
assert_eq!(label_formats(&own("m/d/yyyy"), Codes).1, None);
// Value labels linked to the cache take series 0's cache format under Codes (even when later
// series' caches differ), and keep trailing literal spaces from c:formatCode intact.
let cached = |code: &str| {
chart.replaced(
&format!("{FIRST_FILL}<c:val><c:numRef><c:numCache>"),
&format!(
"{FIRST_FILL}<c:val><c:numRef><c:numCache><c:formatCode>{code}</c:formatCode>"
),
)
};
assert_eq!(label_formats(&cached("0.0%"), Unknown).0, None);
assert_eq!(label_formats(&cached("0.0%"), Codes).0, percent);
let spaced = super::LabelFormat::code(r"0.0\ \ ", separators);
assert_eq!(label_formats(&cached(r"0.0\ \ "), Codes).0, spaced);
let both = cached("0.0%").replaced_all(
"<c:val><c:numRef><c:numCache><c:ptCount",
"<c:val><c:numRef><c:numCache><c:formatCode>0.0%</c:formatCode><c:ptCount",
);
assert_eq!(label_formats(&both, Codes).0, percent);
}
#[test]
fn writes_general_in_the_few_characters_of_the_labels_place() {
use crate::quirks::ChartLabelFormats::{Codes, Unknown};
let own = default_chart("b", TITLE).replaced(
"<c:gapWidth",
r#"<c:dLbls><c:numFmt formatCode="General" sourceLinked="0"/><c:showVal val="1"/></c:dLbls><c:gapWidth"#,
);
// Every digit under Unknown; under Codes, the data labels' few characters and the value
// axis' own.
let all = Some(super::LabelFormat::all_digits());
assert_eq!(label_formats(&own, Unknown), (all.clone(), all));
let separators = crate::NumberSeparators::new('.', ',').unwrap();
let general = |place| Some(super::LabelFormat::general(separators, place));
assert_eq!(
label_formats(&own, Codes),
(
general(super::LabelPlace::ValueAxis),
general(super::LabelPlace::Data)
)
);
}
/// [`line_chart`] as Word's scatter chart of straight lines and markers: each series' values its
/// y values, over the x values 1 and 3, with the category axis turned into a value axis below
/// the plot area and the value axis at its left.
fn scatter_chart() -> String {
let x_values = r#"<c:xVal><c:numRef><c:numCache><c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:xVal>"#;
line_chart()
.replaced_all(r#"<c:grouping val="standard"/>"#, "")
.replaced_all(
"<c:lineChart>",
r#"<c:scatterChart><c:scatterStyle val="lineMarker"/><c:varyColors val="0"/>"#,
)
.replaced_all("</c:lineChart>", "</c:scatterChart>")
.replaced_all("<c:val>", &format!("{x_values}<c:yVal>"))
.replaced_all("</c:val>", "</c:yVal>")
.replaced_all(
r#"<c:valAx><c:delete val="0"/>"#,
r#"<c:valAx><c:delete val="0"/><c:axPos val="l"/>"#,
)
.replaced_all(
CATEGORY_AXIS,
r#"<c:valAx><c:delete val="0"/><c:axPos val="b"/>"#,
)
.replaced_all("</c:catAx>", "</c:valAx>")
}
/// The part that a target whose quirks are `ChartPlotArea::FontLines` and `ChartScatter`
/// `scatter` draws of the chart `xml`, or why it does not draw it.
fn read_scatter(xml: &str, scatter: crate::quirks::ChartScatter) -> Result<Part, ChartReason> {
let doc = parse(xml);
super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_scatter(scatter),
)
}
#[test]
fn reads_a_scatter_chart_with_its_x_values_where_the_target_draws_it() {
use crate::quirks::ChartScatter;
let found = read_scatter(&scatter_chart(), ChartScatter::Drawn).unwrap();
let ChartGroup::Scatter {
looks,
x_values,
x_scale,
} = found.columns.group
else {
panic!("not a scatter group");
};
assert_eq!(x_scale, super::SetScale::default());
let one_three = vec![
Decimal {
digits: 1,
exponent: 0,
},
Decimal {
digits: 3,
exponent: 0,
},
];
assert_eq!(x_values, vec![one_three.clone(), one_three]);
let plain = LineLook {
width: Some(StyleWidth::Set(
f_office_units::Length::from_emus(28_575).unwrap(),
)),
marker: None,
form: LineForm::Straight,
dash: None,
};
assert_eq!(looks, vec![plain.clone(), plain]);
assert_eq!(found.columns.categories, 2);
assert_eq!(found.columns.category_names, None);
// A target that does not draw scatter charts leaves it out with its own reason.
assert_eq!(
read_scatter(&scatter_chart(), ChartScatter::Unknown).map(|_| ()),
Err(ChartReason::Scatter)
);
// Explicit non-negative x-axis min, max, and majorUnit are kept in `x_scale`.
let scaled_xml = scatter_chart().replacen(
r#"<c:axPos val="b"/>"#,
r#"<c:axPos val="b"/><c:scaling><c:min val="2"/><c:max val="12"/></c:scaling><c:majorUnit val="2.5"/>"#,
1,
);
let ChartGroup::Scatter { x_scale, .. } = read_scatter(&scaled_xml, ChartScatter::Drawn)
.unwrap()
.columns
.group
else {
panic!("not a scatter group");
};
assert_eq!(
x_scale,
super::SetScale {
min: Some(Decimal::parse("2").unwrap()),
max: Some(Decimal::parse("12").unwrap()),
major_unit: Some(Decimal::parse("2.5").unwrap()),
}
);
}
#[test]
fn leaves_out_a_scatter_chart_of_a_form_that_its_rules_do_not_draw() {
use crate::quirks::ChartScatter;
let x_axis = r#"<c:axPos val="b"/>"#;
let two_points =
r#"<c:ptCount val="2"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>3</c:v></c:pt>"#;
let legend = format!(
r#"</c:plotArea><c:legend><c:legendPos val="b"/>{}</c:legend>"#,
text(900)
);
// A scatter chart with a legend is drawn under `ChartScatter::Drawn`.
let with_legend = scatter_chart().replacen("</c:plotArea>", &legend, 1);
assert_eq!(
read_scatter(&with_legend, ChartScatter::Drawn)
.unwrap()
.columns
.legend,
Some(crate::chart::LegendPlace::Bottom)
);
// Each change of the scatter chart, and the reason that leaves it out.
let cases: [(&str, String, ChartReason); 8] = [
(
r#"<c:scatterStyle val="lineMarker"/>"#,
r#"<c:scatterStyle val="smoothMarker"/>"#.to_owned(),
ChartReason::ScatterStyle,
),
(
r#"<c:varyColors val="0"/>"#,
r#"<c:varyColors val="1"/>"#.to_owned(),
ChartReason::VariedColors,
),
(
"</c:yVal>",
r#"</c:yVal><c:trendline><c:trendlineType val="linear"/></c:trendline>"#.to_owned(),
ChartReason::SeriesExtras,
),
(
x_axis,
r#"<c:axPos val="l"/>"#.to_owned(),
ChartReason::ScatterAxes,
),
(
x_axis,
format!("{x_axis}<c:majorGridlines/>"),
ChartReason::XGridlines,
),
(
x_axis,
format!(r#"{x_axis}<c:scaling><c:min val="-1"/></c:scaling>"#),
ChartReason::ValueScale,
),
(
"<c:v>1</c:v>",
"<c:v>-1</c:v>".to_owned(),
ChartReason::NegativeValue,
),
(
two_points,
r#"<c:ptCount val="1"/><c:pt idx="0"><c:v>1</c:v></c:pt>"#.to_owned(),
ChartReason::SeriesLengths,
),
];
for (from, to, reason) in cases {
let chart = scatter_chart().replacen(from, &to, 1);
assert_eq!(
read_scatter(&chart, ChartScatter::Drawn).map(|_| ()),
Err(reason),
"{from}"
);
}
}
#[test]
fn draws_the_markers_alone_of_a_scatter_series_without_a_line() {
use crate::quirks::ChartScatter;
// The first series' line has no fill, and its circles a fill and an outline of their own.
let first = r#"<a:ln w="28575" cap="rnd"><a:solidFill><a:schemeClr val="accent1"/></a:solidFill><a:round/></a:ln></c:spPr><c:marker><c:symbol val="none"/></c:marker>"#;
let hidden = r#"<a:ln w="28575" cap="rnd"><a:noFill/><a:round/></a:ln></c:spPr><c:marker><c:symbol val="circle"/><c:size val="5"/><c:spPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:ln w="9525"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></a:ln></c:spPr></c:marker>"#;
let markers = scatter_chart().replacen(first, hidden, 1);
let found = read_scatter(&markers, ChartScatter::Drawn).unwrap();
let ChartGroup::Scatter { looks, .. } = &found.columns.group else {
panic!("not a scatter group");
};
assert_eq!(looks[0].width, None);
assert_eq!(
looks[0].marker.as_ref().map(|marker| marker.symbol),
Some(MarkerSymbol::Circle)
);
// The series takes its markers' fill as its color.
assert_eq!(
found.columns.series[0].fill.color(),
looks[0]
.marker
.as_ref()
.and_then(|marker| marker.fill.as_ref())
);
// A line chart's series without a line keeps no color.
let line = line_chart().replacen(first, hidden, 1);
assert_eq!(line_looks(&line), Err(ChartReason::SeriesFill));
}
/// The forms of the series' lines of the chart `xml` under the quirk `ChartSmoothLines` at
/// `smooth`, on a target that draws scatter charts, or why it is left out.
fn line_forms(
xml: &str,
smooth: crate::quirks::ChartSmoothLines,
) -> Result<Vec<LineForm>, ChartReason> {
let doc = parse(xml);
let part = super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_scatter(crate::quirks::ChartScatter::Drawn)
.with_smooth_lines(smooth),
)?;
match part.columns.group {
ChartGroup::Lines { looks, .. } | ChartGroup::Scatter { looks, .. } => {
Ok(looks.iter().map(|look| look.form).collect())
}
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. }
| ChartGroup::Combo { .. } => {
panic!("not a group of lines")
}
}
}
/// The width and the dash of a series' line.
type Stroke = (Option<StyleWidth>, Option<LineDash>);
/// The width and the dash of each series' line of the chart `xml` under the quirk
/// `ChartLineStrokes` at `strokes`, or why it is left out.
fn line_strokes(
xml: &str,
strokes: crate::quirks::ChartLineStrokes,
) -> Result<Vec<Stroke>, ChartReason> {
let doc = parse(xml);
let part = super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_line_strokes(strokes),
)?;
match part.columns.group {
ChartGroup::Lines { looks, .. } => {
Ok(looks.iter().map(|look| (look.width, look.dash)).collect())
}
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. }
| ChartGroup::Combo { .. } => {
panic!("not a line chart")
}
}
}
#[test]
fn takes_the_style_for_the_cap_join_and_width_that_a_series_line_leaves_out() {
use crate::quirks::ChartLineStrokes::{StyleRound, Unknown};
let set = Some(StyleWidth::Set(
f_office_units::Length::from_emus(28_575).unwrap(),
));
let lines = line_chart();
assert_eq!(line_strokes(&lines, StyleRound), Ok(vec![(set, None); 2]));
// Without the cap and the join: round, as the style's.
let unwritten = lines.replace(r#" cap="rnd""#, "").replace("<a:round/>", "");
assert_eq!(
line_strokes(&unwritten, StyleRound),
Ok(vec![(set, None); 2])
);
assert_eq!(
line_strokes(&unwritten, Unknown),
Err(ChartReason::LineLook)
);
// Without the width: the style's.
let automatic = lines.replace(r#" w="28575""#, "");
assert_eq!(
line_strokes(&automatic, StyleRound),
Ok(vec![(Some(StyleWidth::Automatic), None); 2])
);
assert_eq!(
line_strokes(&automatic, Unknown),
Err(ChartReason::LineLook)
);
// A cap or a join that is written and not round is not drawn yet.
for other in [
lines.replace(r#"cap="rnd""#, r#"cap="flat""#),
lines.replace(r#"cap="rnd""#, r#"cap="sq""#),
lines.replace("<a:round/>", "<a:miter/>"),
lines.replace("<a:round/>", "<a:bevel/>"),
unwritten.replace("</a:ln>", "<a:bevel/></a:ln>"),
] {
assert_eq!(line_strokes(&other, StyleRound), Err(ChartReason::LineLook));
}
}
/// A marker as the tests compare it: its symbol, whether it has a fill of its own, and its
/// outline, if any, as whether it has a color of its own and its width.
type MarkerSummary = (MarkerSymbol, bool, Option<(bool, StyleWidth)>);
/// The marker of each series of the chart `xml` under the quirk `ChartMarkerLooks` at
/// `looks`, or why the chart is left out.
fn line_markers(
xml: &str,
looks: crate::quirks::ChartMarkerLooks,
) -> Result<Vec<Option<MarkerSummary>>, ChartReason> {
let doc = parse(xml);
let part = super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_marker_looks(looks),
)?;
match part.columns.group {
ChartGroup::Lines { looks, .. } => Ok(looks
.iter()
.map(|look| {
look.marker.as_ref().map(|marker: &Marker| {
let outline = marker
.outline
.as_ref()
.map(|outline| (outline.color.is_some(), outline.width));
(marker.symbol, marker.fill.is_some(), outline)
})
})
.collect()),
ChartGroup::Columns { .. }
| ChartGroup::Bars { .. }
| ChartGroup::Scatter { .. }
| ChartGroup::Pie { .. }
| ChartGroup::Doughnut { .. }
| ChartGroup::Combo { .. } => {
panic!("not a line chart")
}
}
}
#[test]
fn takes_the_style_for_the_parts_that_a_marker_leaves_out() {
use crate::quirks::ChartMarkerLooks::{StyleParts, Unknown};
use MarkerSymbol::{Circle, Diamond, Square};
let marked = |marker: &str| line_chart().replaced_all(r#"<c:symbol val="none"/>"#, marker);
let fill = r#"<a:solidFill><a:srgbClr val="00B0F0"/></a:solidFill>"#;
let color = r#"<a:solidFill><a:srgbClr val="C00000"/></a:solidFill>"#;
let set = StyleWidth::Set(f_office_units::Length::from_emus(9_525).unwrap());
let style = Some((false, StyleWidth::Automatic));
let circles = |fill: bool, outline| Ok(vec![Some((Circle, fill, outline)); 2]);
// The whole look, drawn on every target.
let whole = marked(&format!(
r#"<c:symbol val="circle"/><c:spPr>{fill}<a:ln w="9525">{color}</a:ln></c:spPr>"#
));
for looks in [Unknown, StyleParts] {
assert_eq!(
line_markers(&whole, looks),
circles(true, Some((true, set)))
);
}
// Each part that the marker leaves out is the style's, and an outline of no fill is none.
let parts = [
(
format!(r#"<c:size val="9"/><c:spPr>{fill}<a:ln w="9525">{color}</a:ln></c:spPr>"#),
Ok(vec![
Some((Diamond, true, Some((true, set)))),
Some((Square, true, Some((true, set)))),
]),
),
(
r#"<c:size val="9"/>"#.to_owned(),
Ok(vec![
Some((Diamond, false, style)),
Some((Square, false, style)),
]),
),
(
format!(r#"<c:symbol val="circle"/><c:spPr>{fill}<a:ln>{color}</a:ln></c:spPr>"#),
circles(true, Some((true, StyleWidth::Automatic))),
),
(
format!(
r#"<c:symbol val="circle"/><c:spPr>{fill}<a:ln>{color}<a:prstDash val="solid"/></a:ln></c:spPr>"#
),
circles(true, Some((true, StyleWidth::Automatic))),
),
(
format!(r#"<c:symbol val="circle"/><c:spPr>{fill}</c:spPr>"#),
circles(true, style),
),
(
format!(
r#"<c:symbol val="circle"/><c:spPr>{fill}<a:ln w="9525"><a:noFill/></a:ln></c:spPr>"#
),
circles(true, None),
),
(
format!(r#"<c:symbol val="circle"/><c:spPr><a:ln w="9525">{color}</a:ln></c:spPr>"#),
circles(false, Some((true, set))),
),
];
for (marker, drawn) in parts {
let xml = marked(&marker);
assert_eq!(line_markers(&xml, StyleParts), drawn, "{marker}");
assert_eq!(
line_markers(&xml, Unknown),
Err(ChartReason::LineMarkers),
"{marker}"
);
}
// Other fills, effects and symbols are not drawn yet.
for marker in [
r#"<c:symbol val="circle"/><c:spPr><a:gradFill/></c:spPr>"#.to_owned(),
format!(
r#"<c:symbol val="circle"/><c:spPr>{fill}<a:ln w="9525"><a:gradFill/></a:ln></c:spPr>"#
),
format!(
r#"<c:symbol val="circle"/><c:spPr>{fill}<a:effectLst><a:outerShdw/></a:effectLst></c:spPr>"#
),
r#"<c:symbol val="auto"/>"#.to_owned(),
] {
assert_eq!(
line_markers(&marked(&marker), StyleParts),
Err(ChartReason::LineMarkers),
"{marker}"
);
}
}
#[test]
fn reads_the_preset_dash_of_a_series_line_where_the_target_draws_it() {
use crate::quirks::ChartLineStrokes::{StyleRound, Unknown};
let set = Some(StyleWidth::Set(
f_office_units::Length::from_emus(28_575).unwrap(),
));
let dashed = |val: &str| {
line_chart().replace(
"<a:round/>",
&format!(r#"<a:prstDash val="{val}"/><a:round/>"#),
)
};
for (val, dash) in [
("dot", LineDash::Dot),
("lgDashDotDot", LineDash::LongDashDotDot),
("sysDot", LineDash::SystemDot),
] {
assert_eq!(
line_strokes(&dashed(val), StyleRound),
Ok(vec![(set, Some(dash)); 2]),
"{val}"
);
assert_eq!(
line_strokes(&dashed(val), Unknown),
Err(ChartReason::LineLook)
);
}
assert_eq!(
line_strokes(&dashed("solid"), Unknown),
Ok(vec![(set, None); 2])
);
assert_eq!(
line_strokes(&dashed("other"), StyleRound),
Err(ChartReason::LineLook)
);
let own = line_chart().replace(
"<a:round/>",
r#"<a:custDash><a:ds d="100000" sp="100000"/></a:custDash><a:round/>"#,
);
assert_eq!(line_strokes(&own, StyleRound), Err(ChartReason::LineLook));
}
#[test]
fn gives_each_preset_dash_its_dashes_and_gaps_in_line_widths() {
let patterns = [
(LineDash::Dot, &[1, 3][..]),
(LineDash::Dash, &[4, 3]),
(LineDash::LongDash, &[8, 3]),
(LineDash::DashDot, &[4, 3, 1, 3]),
(LineDash::LongDashDot, &[8, 3, 1, 3]),
(LineDash::LongDashDotDot, &[8, 3, 1, 3, 1, 3]),
(LineDash::SystemDash, &[3, 1]),
(LineDash::SystemDot, &[1, 1]),
(LineDash::SystemDashDot, &[3, 1, 1, 1]),
(LineDash::SystemDashDotDot, &[3, 1, 1, 1, 1, 1]),
];
assert!(
patterns
.iter()
.all(|(dash, pattern)| dash.pattern() == *pattern)
);
}
#[test]
fn reads_smooth_lines_where_the_target_draws_them() {
use crate::quirks::ChartSmoothLines::{Curves, Unknown};
let smooth = r#"</c:marker><c:smooth val="1"/>"#;
// The first series of a line chart smoothed: its own form, the second series straight.
let lines = line_chart().replacen("</c:marker>", smooth, 1);
assert_eq!(
line_forms(&lines, Curves),
Ok(vec![LineForm::Smooth, LineForm::Straight])
);
assert_eq!(line_forms(&lines, Unknown), Err(ChartReason::SmoothLines));
// A scatter chart: the series' own flag decides, and the style of smooth lines and markers
// is drawn as straight lines and markers where the target draws smooth lines.
let scatter = scatter_chart().replacen("</c:marker>", smooth, 1);
assert_eq!(
line_forms(&scatter, Curves),
Ok(vec![LineForm::Smooth, LineForm::Straight])
);
assert_eq!(line_forms(&scatter, Unknown), Err(ChartReason::SmoothLines));
let style = scatter_chart().replaced_all(
r#"<c:scatterStyle val="lineMarker"/>"#,
r#"<c:scatterStyle val="smoothMarker"/>"#,
);
assert_eq!(
line_forms(&style, Curves),
Ok(vec![LineForm::Straight, LineForm::Straight])
);
assert_eq!(line_forms(&style, Unknown), Err(ChartReason::ScatterStyle));
}
#[test]
fn reads_horizontal_bars_as_bars_where_the_target_turns_them() {
use crate::quirks::ChartHorizontalBars::{Turned, Unknown};
let rows = default_chart("b", TITLE).replaced_all(r#"barDir val="col""#, r#"barDir val="bar""#);
let read_rows = |bars| {
let doc = parse(&rows);
super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_horizontal_bars(bars),
)
};
let found = read_rows(Turned).unwrap();
assert_eq!(
found.columns.group,
ChartGroup::Bars {
gap: 219,
overlap: -27,
stacking: super::BarStacking::Clustered,
}
);
// The rule of Word's default chart does not place them; the rule of the font's lines does.
assert_eq!(
found.columns.default_chart_rule(),
Err(ChartReason::HorizontalBars)
);
assert_eq!(found.columns.font_lines_rule(), Ok(PlotRule::FontLines));
assert_eq!(read_rows(Unknown).err(), Some(ChartReason::HorizontalBars));
}
/// What the chart `xml` reads of its axes under the quirks `ChartDeletedAxis` at `deleted` and
/// `ChartLowLabels` at `low`, in the style look: the forms of its axes, whether it has
/// gridlines, whether its value axis draws a line, and whether it draws the value axis' tick
/// marks; or why the chart is left out.
fn axes_under(
xml: &str,
rules: (
crate::quirks::ChartDeletedAxis,
crate::quirks::ChartLowLabels,
),
) -> Result<(super::AxisForms, bool, bool, bool), ChartReason> {
use f_office_drawingml::shape::{Geometry, ShapeLook};
let columns = columns_under(xml, rules)?;
let no_line = ShapeLook::plain(Geometry::Line, None, None);
Ok((
columns.axis_forms,
columns.gridlines.is_some(),
columns.value_axis != no_line,
columns.ticks.value,
))
}
/// The drawn chart of the part `xml` under the plot rules of the font's lines, with the deleted
/// axis' rule `deleted` and the low labels' rule `low`.
fn columns_under(
xml: &str,
(deleted, low): (
crate::quirks::ChartDeletedAxis,
crate::quirks::ChartLowLabels,
),
) -> Result<super::Columns, ChartReason> {
use crate::quirks::{ChartHorizontalBars, ChartStyleLook};
let doc = parse(xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_style_look(ChartStyleLook::StyleTwo)
.with_horizontal_bars(ChartHorizontalBars::Turned)
.with_deleted_axis(deleted)
.with_low_labels(low);
Ok(super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)?.columns)
}
/// The variants of `ChartDeletedAxis` and `ChartLowLabels` under which F-Office draws a
/// deleted value axis and low category labels.
const DRAWN_AXES: (
crate::quirks::ChartDeletedAxis,
crate::quirks::ChartLowLabels,
) = (
crate::quirks::ChartDeletedAxis::PlotRoom,
crate::quirks::ChartLowLabels::BelowPlot,
);
/// The start of the shown value axis of [`bare_chart`] and [`default_chart`].
const SHOWN_VALUE_AXIS: &str = r#"<c:valAx><c:delete val="0"/>"#;
/// The start of a deleted value axis.
const DELETED_VALUE_AXIS: &str = r#"<c:valAx><c:delete val="1"/>"#;
/// The start of the shown category axis of [`bare_chart`].
const SHOWN_CATEGORY_AXIS: &str = r#"<c:catAx><c:delete val="0"/>"#;
/// The forms of the axes of a chart whose value axis is deleted.
fn deleted_value_form() -> super::AxisForms {
super::AxisForms {
value_deleted: true,
..super::AxisForms::default()
}
}
/// [`bare_chart`] with its value axis deleted.
fn deleted_value_chart() -> String {
bare_chart().replaced(SHOWN_VALUE_AXIS, DELETED_VALUE_AXIS)
}
/// [`bare_chart`] with its category labels low.
fn low_labels_chart() -> String {
bare_chart().replaced(
SHOWN_CATEGORY_AXIS,
r#"<c:catAx><c:delete val="0"/><c:tickLblPos val="low"/>"#,
)
}
#[test]
fn draws_a_deleted_value_axis_without_its_line_and_tick_marks_where_the_target_does() {
use crate::quirks::ChartDeletedAxis::Unknown;
use crate::quirks::ChartLowLabels::BelowPlot;
// Both axes shown with their labels next to them: the value axis draws its line and its
// tick marks in the style look.
assert_eq!(
axes_under(&bare_chart(), DRAWN_AXES),
Ok((super::AxisForms::default(), true, true, true))
);
// A deleted value axis keeps its written gridlines, and draws no line and no tick marks.
let deleted = deleted_value_chart();
assert_eq!(
axes_under(&deleted, DRAWN_AXES),
Ok((deleted_value_form(), true, false, false))
);
assert_eq!(
axes_under(&deleted, (Unknown, BelowPlot)),
Err(ChartReason::AxisNotShown)
);
let ungridded = deleted.replaced("<c:majorGridlines></c:majorGridlines>", "");
assert_eq!(
axes_under(&ungridded, DRAWN_AXES),
Ok((deleted_value_form(), false, false, false))
);
}
#[test]
fn takes_each_axis_label_size_and_the_category_one_beside_a_deleted_value_axis() {
// The labels of a deleted value axis set no size: the category labels' size holds.
let value_end = |size| format!("{}</c:valAx>", text(size));
let shown_sizes = default_chart("b", TITLE).replaced(&value_end(900), &value_end(1200));
let other_size = shown_sizes.replaced(SHOWN_VALUE_AXIS, DELETED_VALUE_AXIS);
let sizes = |xml: &str| {
columns_under(xml, DRAWN_AXES).map(|columns| (columns.label_size, columns.value_label_size))
};
assert_eq!(sizes(&shown_sizes), Ok((18, 24)));
assert_eq!(sizes(&other_size), Ok((18, 18)));
// Horizontal bars with a deleted value axis.
let rows = deleted_value_chart().replaced_all(r#"barDir val="col""#, r#"barDir val="bar""#);
assert_eq!(
axes_under(&rows, DRAWN_AXES).map(|axes| axes.0),
Ok(deleted_value_form())
);
}
#[test]
fn draws_low_category_labels_of_columns_where_the_target_does() {
use crate::quirks::ChartDeletedAxis::PlotRoom;
use crate::quirks::ChartLowLabels::Unknown;
let low = low_labels_chart();
let low_form = super::AxisForms {
low_labels: true,
..super::AxisForms::default()
};
assert_eq!(
axes_under(&low, DRAWN_AXES).map(|axes| axes.0),
Ok(low_form)
);
assert_eq!(
axes_under(&low, (PlotRoom, Unknown)),
Err(ChartReason::AxisNotShown)
);
// Also on horizontal bars under BelowPlot, and left out under Unknown.
let low_rows = low.replaced_all(r#"barDir val="col""#, r#"barDir val="bar""#);
assert_eq!(
axes_under(&low_rows, DRAWN_AXES).map(|axes| axes.0),
Ok(low_form)
);
assert_eq!(
axes_under(&low_rows, (PlotRoom, Unknown)),
Err(ChartReason::AxisNotShown)
);
}
#[test]
fn leaves_out_high_category_labels_and_draws_hidden_axes_under_plot_room() {
use crate::quirks::ChartDeletedAxis::Unknown;
use crate::quirks::ChartLowLabels::BelowPlot;
let high = bare_chart().replaced(
SHOWN_CATEGORY_AXIS,
r#"<c:catAx><c:delete val="0"/><c:tickLblPos val="high"/>"#,
);
assert_eq!(
axes_under(&high, DRAWN_AXES),
Err(ChartReason::AxisNotShown)
);
let no_categories =
bare_chart().replaced(SHOWN_CATEGORY_AXIS, r#"<c:catAx><c:delete val="1"/>"#);
let cat_hidden = super::AxisForms {
category_hidden: true,
..super::AxisForms::default()
};
assert_eq!(
axes_under(&no_categories, DRAWN_AXES).map(|axes| axes.0),
Ok(cat_hidden)
);
assert_eq!(
axes_under(&no_categories, (Unknown, BelowPlot)),
Err(ChartReason::AxisNotShown)
);
// tickLblPos="none" hides labels while keeping the value axis line and tick marks.
let val_none = bare_chart().replaced(
SHOWN_VALUE_AXIS,
r#"<c:valAx><c:delete val="0"/><c:tickLblPos val="none"/>"#,
);
assert_eq!(
axes_under(&val_none, DRAWN_AXES),
Ok((deleted_value_form(), true, true, true))
);
let cat_none = bare_chart().replaced(
SHOWN_CATEGORY_AXIS,
r#"<c:catAx><c:delete val="0"/><c:tickLblPos val="none"/>"#,
);
assert_eq!(
axes_under(&cat_none, DRAWN_AXES).map(|axes| axes.0),
Ok(cat_hidden)
);
}
/// A pie of the points 1, 2 and 3 that starts 90 degrees clockwise from the top, with its
/// legend at the bottom: its first point in its own fill, the others in the series' fill;
/// `point` adds markup to the first point.
fn pie_chart(point: &str) -> String {
let own = format!(
r#"<c:dPt><c:idx val="0"/>{point}<c:spPr><a:solidFill><a:schemeClr val="accent2"/></a:solidFill></c:spPr></c:dPt><c:val>"#
);
part(&format!(
r#"<c:autoTitleDeleted val="1"/><c:plotArea><c:pieChart><c:varyColors val="1"/>{}<c:firstSliceAng val="90"/></c:pieChart></c:plotArea><c:legend><c:legendPos val="b"/>{}</c:legend>"#,
series("accent1", &["1", "2", "3"]).replacen("<c:val>", &own, 1),
text(900)
))
}
/// A 3-D pie of [`pie_chart`]'s points, with the chart's view `view` before its plot area.
fn pie_3d_chart(view: &str) -> String {
pie_chart("")
.replace("<c:plotArea>", &format!("{view}<c:plotArea>"))
.replace("c:pieChart>", "c:pie3DChart>")
.replace(r#"<c:firstSliceAng val="90"/>"#, "")
}
#[test]
fn reads_a_3d_pie_with_its_view() {
use crate::quirks::{ChartPies, ChartPies3D};
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_pies(ChartPies::Inscribed);
let read = |xml: &str, pies_3d| {
let doc = parse(xml);
super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
rules.with_pies_3d(pies_3d),
)
};
let xml = pie_3d_chart(
r#"<c:view3D><c:rotX val="50"/><c:rotY val="45"/><c:perspective val="40"/></c:view3D>"#,
);
let found = read(&xml, ChartPies3D::Picture).unwrap();
let ChartGroup::Pie {
first_angle, view, ..
} = found.columns.group
else {
panic!("not a pie");
};
assert_eq!(first_angle, 45);
assert_eq!(
view,
Some(super::PieView {
tilt: 50,
field_of_view: 20
})
);
// The default perspective, 30, is a field of view of 15 degrees.
let found = read(
&pie_3d_chart(r#"<c:view3D><c:rotX val="30"/></c:view3D>"#),
ChartPies3D::Picture,
);
let ChartGroup::Pie { view, .. } = found.unwrap().columns.group else {
panic!("not a pie");
};
assert_eq!(view.map(|view| view.field_of_view), Some(15));
// Not on a target that draws no 3-D pie, nor from the side.
assert_eq!(
read(&xml, ChartPies3D::Unknown).err(),
Some(ChartReason::OtherGroup)
);
assert_eq!(
read(&pie_3d_chart(""), ChartPies3D::Picture).err(),
Some(ChartReason::OtherGroup)
);
}
/// The part that a target whose quirk `ChartPies` is `pies` draws of the chart `xml`, with the
/// plot area of the font's lines.
fn pie_part(xml: &str, pies: crate::quirks::ChartPies) -> Result<Part, ChartReason> {
let doc = parse(xml);
super::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines).with_pies(pies),
)
}
#[test]
fn reads_a_pie_with_the_fill_of_each_point() {
use crate::quirks::ChartPies;
let found = pie_part(&pie_chart(""), ChartPies::Inscribed).unwrap();
let ChartGroup::Pie {
first_angle,
view,
fills,
labels,
explosion,
} = &found.columns.group
else {
panic!("not a pie");
};
assert_eq!(
(*labels, *first_angle, *view),
(PieLabelPlace::Center, 90, None)
);
assert_eq!(
(explosion.series, explosion.slices.as_slice()),
(0, [0, 0, 0].as_slice())
);
assert_eq!(fills.len(), 3);
assert_ne!(fills[0], fills[1]);
assert_eq!(fills[1], fills[2]);
assert_eq!(Some(&fills[0]), found.columns.series[0].fill.color());
}
#[test]
fn leaves_out_a_pie_that_the_target_does_not_draw_or_that_pulls_out_or_labels() {
use crate::quirks::ChartPies;
assert_eq!(
pie_part(&pie_chart(""), ChartPies::Unknown).err(),
Some(ChartReason::OtherGroup)
);
assert_eq!(
pie_part(
&pie_chart(r#"<c:explosion val="12"/>"#),
ChartPies::Inscribed
)
.err(),
Some(ChartReason::PieExplosion)
);
assert_eq!(
pie_part(
&labeled_pie(r#"<c:dLblPos val="l"/>"#, "showVal"),
ChartPies::Inscribed
)
.err(),
Some(ChartReason::PieLabels)
);
}
#[test]
fn resolves_mixed_per_point_pie_label_positions() {
use crate::quirks::ChartPies;
let place_of = |extra: &str| {
pie_part(&labeled_pie(extra, "showVal"), ChartPies::Inscribed).map(|found| {
let ChartGroup::Pie { labels, .. } = found.columns.group else {
panic!("not a pie");
};
labels
})
};
let pt_bf =
r#"<c:dLbl><c:idx val="0"/><c:dLblPos val="bestFit"/><c:showVal val="1"/></c:dLbl>"#;
let pt_ctr = r#"<c:dLbl><c:idx val="1"/><c:dLblPos val="ctr"/><c:showVal val="1"/></c:dLbl>"#;
let pt_bad = r#"<c:dLbl><c:idx val="0"/><c:dLblPos val="l"/><c:showVal val="1"/></c:dLbl>"#;
let pt_del = r#"<c:dLbl><c:idx val="0"/><c:delete val="1"/><c:dLblPos val="ctr"/></c:dLbl>"#;
assert_eq!(
[
place_of(&format!(r#"{pt_bf}<c:dLblPos val="outEnd"/>"#)),
place_of(pt_bf),
place_of(&format!(r#"{pt_bf}<c:dLblPos val="ctr"/>"#)),
place_of(&format!(r#"{pt_ctr}<c:dLblPos val="outEnd"/>"#)),
place_of(&format!(r#"{pt_del}<c:dLblPos val="outEnd"/>"#)),
place_of(&format!(r#"{pt_bad}<c:dLblPos val="outEnd"/>"#)),
],
[
Ok(PieLabelPlace::BestFit),
Ok(PieLabelPlace::BestFit),
Ok(PieLabelPlace::Center),
Ok(PieLabelPlace::Center),
Ok(PieLabelPlace::OuterEnd),
Err(ChartReason::PieLabels),
]
);
}
#[test]
fn colors_bare_bars_with_omitted_or_on_vary_colors_under_varied_rule() {
use crate::quirks::{ChartBarVaryColors, ChartStyleLook};
use crate::reader::settings::PlotRules;
use f_office_drawingml::color::{DrawColor, SchemeSlot};
let read = |xml: &str, mode| {
let doc = parse(xml);
let rules = PlotRules::with_area(ChartPlotArea::FontLines)
.with_style_look(ChartStyleLook::StyleTwo)
.with_bar_vary_colors(mode);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
};
let multi = bare_chart().replaced(r#"<c:varyColors val="0"/>"#, "");
assert_eq!(
read(&multi, ChartBarVaryColors::Unknown).err(),
Some(ChartReason::SeriesFill)
);
let multi_part = read(&multi, ChartBarVaryColors::Varied).unwrap();
let multi_fills: Vec<_> = multi_part
.columns
.series
.iter()
.map(|s| s.fill.clone())
.collect();
assert_eq!(
multi_fills,
[SchemeSlot::Accent1, SchemeSlot::Accent2]
.map(|slot| SeriesFill::Color(DrawColor::scheme(slot)))
);
let single = part(
r#"<c:autoTitleDeleted val="1"/><c:plotArea><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/><c:dPt><c:idx val="1"/><c:spPr><a:solidFill><a:schemeClr val="accent6"/></a:solidFill></c:spPr></c:dPt><c:val><c:numRef><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser></c:barChart><c:catAx><c:axId val="1"/><c:scaling/><c:delete val="0"/><c:axPos val="b"/><c:crossAx val="2"/></c:catAx><c:valAx><c:axId val="2"/><c:scaling/><c:delete val="0"/><c:axPos val="l"/><c:crossAx val="1"/></c:valAx></c:plotArea>"#,
);
let single_part = read(&single, ChartBarVaryColors::Varied).unwrap();
assert_eq!(
single_part.columns.series[0].fill,
SeriesFill::Points(vec![
DrawColor::scheme(SchemeSlot::Accent1),
DrawColor::scheme(SchemeSlot::Accent6),
DrawColor::scheme(SchemeSlot::Accent3),
])
);
}
#[test]
fn reads_pulled_out_pie_slices_when_target_draws_pie_explosion() {
use crate::quirks::{ChartPieExplosion, ChartPies};
let read = |extra: &str, mode| {
let xml = pie_chart("").replacen("<c:val>", &format!("{extra}<c:val>"), 1);
let doc = parse(&xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_pies(ChartPies::Inscribed)
.with_pie_explosion(mode);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
};
let mixed = r#"<c:explosion val="15"/><c:dPt><c:idx val="0"/><c:explosion val="40"/></c:dPt><c:dPt><c:idx val="2"/><c:explosion val="0"/></c:dPt>"#;
assert_eq!(
read(mixed, ChartPieExplosion::Unknown).err(),
Some(ChartReason::PieExplosion)
);
let found = read(mixed, ChartPieExplosion::PulledOut).unwrap();
let ChartGroup::Pie { explosion, .. } = found.columns.group else {
panic!("not a pie");
};
assert_eq!(explosion.series, 15);
assert_eq!(explosion.slices, vec![40, 15, 0]);
}
/// A pie of `count` points whose series and points name no fill, with `vary` before its
/// series, such as `<c:varyColors val="0"/>`, and `point` as a point of its series.
fn bare_pie(count: usize, vary: &str, point: &str) -> String {
let values: Vec<String> = (1..=count).map(|v| v.to_string()).collect();
let values: Vec<&str> = values.iter().map(String::as_str).collect();
let series = series("accent1", &values).replaced(
r#"<c:spPr><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></c:spPr>"#,
point,
);
part(&format!(
r#"<c:autoTitleDeleted val="1"/><c:plotArea><c:pieChart>{vary}{series}<c:firstSliceAng val="0"/></c:pieChart></c:plotArea>"#
))
}
#[test]
fn gives_the_slices_without_fills_the_style_colors_where_the_target_draws_the_style_look() {
use crate::quirks::{ChartPies, ChartStyleLook};
use crate::reader::settings::PlotRules;
use f_office_drawingml::color::{DrawColor, SchemeSlot};
let read = |xml: &str, look| {
let doc = parse(xml);
let rules = PlotRules::with_area(ChartPlotArea::FontLines)
.with_pies(ChartPies::Inscribed)
.with_style_look(look);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).map(|part| {
let ChartGroup::Pie { fills, .. } = part.columns.group else {
panic!("not a pie");
};
fills
})
};
let accents = [
SchemeSlot::Accent1,
SchemeSlot::Accent2,
SchemeSlot::Accent3,
];
let varied = read(
&bare_pie(3, r#"<c:varyColors val="1"/>"#, ""),
ChartStyleLook::StyleTwo,
);
assert_eq!(varied, Ok(accents.map(DrawColor::scheme).to_vec()));
// Varied colors when the group does not write them, the series' color when it writes off.
assert_eq!(read(&bare_pie(3, "", ""), ChartStyleLook::StyleTwo), varied);
assert_eq!(
read(
&bare_pie(3, r#"<c:varyColors val="0"/>"#, ""),
ChartStyleLook::StyleTwo
),
Ok(vec![DrawColor::scheme(SchemeSlot::Accent1); 3])
);
// Six points use the first tier of the 2-cycle ramp (shade 76%).
let six = read(&bare_pie(6, "", ""), ChartStyleLook::StyleTwo).unwrap();
assert_eq!(
six[5],
DrawColor::scheme(SchemeSlot::Accent6).shaded(76_000)
);
// Not without the style look, nor for a point that names another fill.
assert_eq!(
read(&bare_pie(3, "", ""), ChartStyleLook::Unknown).err(),
Some(ChartReason::SeriesFill)
);
let gradient = r#"<c:dPt><c:idx val="1"/><c:spPr><a:gradFill/></c:spPr></c:dPt>"#;
assert_eq!(
read(&bare_pie(3, "", gradient), ChartStyleLook::StyleTwo).err(),
Some(ChartReason::SeriesFill)
);
}
#[test]
fn draws_a_pie_chart_area_without_properties_in_the_style_look() {
use crate::quirks::{ChartPies, ChartStyleLook};
use crate::reader::settings::PlotRules;
use f_office_drawingml::color::{DrawColor, SchemeSlot};
let bare_area = bare_pie(3, "", "").replaced(
r#"<c:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill></c:spPr></c:chartSpace>"#,
"</c:chartSpace>",
);
let doc = parse(&bare_area);
let rules = PlotRules::with_area(ChartPlotArea::FontLines)
.with_pies(ChartPies::Inscribed)
.with_style_look(ChartStyleLook::StyleTwo);
let part = super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).unwrap();
let color = DrawColor::scheme(SchemeSlot::Dark1).tinted(crate::params::CHART_STYLE_LINE_TINT);
assert_eq!(
part.area,
f_office_drawingml::shape::ShapeLook::in_line_style(
f_office_drawingml::shape::Geometry::Rect,
Some(DrawColor::scheme(SchemeSlot::Light1)),
(color, 1)
)
);
}
/// [`pie_chart`] with data labels of the group that show `shown` at the position that
/// `position` writes.
fn labeled_pie(position: &str, shown: &str) -> String {
pie_chart("").replaced_all(
"<c:firstSliceAng",
&format!(r#"<c:dLbls>{position}<c:{shown} val="1"/></c:dLbls><c:firstSliceAng"#),
)
}
#[test]
fn reads_where_the_data_labels_of_a_pie_stand() {
use crate::quirks::ChartPies;
let read = |position: &str, shown: &str| {
let found = pie_part(&labeled_pie(position, shown), ChartPies::Inscribed).unwrap();
let ChartGroup::Pie { labels: place, .. } = found.columns.group else {
panic!("not a pie");
};
let labels = &found.columns.series[0].labels;
(
place,
matches!(labels, SeriesLabels::Values(_)),
matches!(labels, SeriesLabels::Other),
)
};
// Values at the center, the inner end and the outer end are drawn; only those at the
// outer end make the circle smaller.
for (position, place) in [
("ctr", PieLabelPlace::Center),
("inEnd", PieLabelPlace::InnerEnd),
("outEnd", PieLabelPlace::OuterEnd),
] {
let written = format!(r#"<c:dLblPos val="{position}"/>"#);
assert_eq!(read(&written, "showVal"), (place, true, false));
}
// At the default position and the best fit the circle is smaller and they are not drawn.
for position in ["", r#"<c:dLblPos val="bestFit"/>"#] {
assert_eq!(
read(position, "showVal"),
(PieLabelPlace::BestFit, false, true)
);
}
// Percentages at the center keep the largest circle and are not drawn.
assert_eq!(
read(r#"<c:dLblPos val="ctr"/>"#, "showPercent"),
(PieLabelPlace::Center, false, true)
);
}
#[test]
fn reads_the_box_of_a_legends_manual_layout_in_the_edge_mode() {
let read = |layout: &str| {
let chart = default_chart("b", TITLE).replaced_all(
r#"<c:legendPos val="b"/>"#,
&format!(r#"<c:legendPos val="b"/><c:layout>{layout}</c:layout>"#),
);
let doc = parse(&chart);
read_on(
ChartPlotArea::FontLines,
&mut PartReader::new(&doc),
doc.root().unwrap(),
)
.unwrap()
.columns
.legend_box
};
let part = |digits| Decimal {
digits,
exponent: -2,
};
assert_eq!(
read(
r#"<c:manualLayout><c:xMode val="edge"/><c:yMode val="edge"/><c:x val="0.7"/><c:y val="0.1"/><c:w val="0.25"/><c:h val="0.8"/></c:manualLayout>"#
),
LegendBox::Manual(LayoutBox {
x: Decimal {
digits: 7,
exponent: -1
},
y: Decimal {
digits: 1,
exponent: -1
},
w: part(25),
h: Decimal {
digits: 8,
exponent: -1
},
})
);
// A layout that moves the legend from its automatic place, and one without its size.
assert_eq!(
read(r#"<c:manualLayout><c:x val="0.1"/><c:y val="0.1"/></c:manualLayout>"#),
LegendBox::Other
);
assert_eq!(read(""), LegendBox::Automatic);
}
/// An axis title as Word writes it: the text body `body`, the run properties `run` in the
/// paragraph's default run and in its one run, the text `text`, and no overlay.
fn axis_title(body: &str, run: &str, text: &str) -> String {
format!(
r#"<c:title><c:tx><c:rich>{body}<a:lstStyle/><a:p><a:pPr><a:defRPr {run}/></a:pPr><a:r><a:rPr lang="en-US" {run}/><a:t>{text}</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="0"/></c:title>"#
)
}
/// The text body of an axis title that reads upward, as Word writes it.
const UPWARD_BODY: &str = r#"<a:bodyPr rot="-5400000" vert="horz"/>"#;
/// The text body of an upright axis title, as Word writes it.
const UPRIGHT_BODY: &str = r#"<a:bodyPr rot="0" vert="horz"/>"#;
/// An axis title's size, line and bold, as [`axis_titles_under`] gives them.
type TitleSummary = Option<(i64, String, bool)>;
/// The axis titles of the chart `xml` under the plot rules of the font's lines in the style look
/// with the quirk `ChartAxisTitles` at `titles`: the value axis' title and the category axis' title, or `None`
/// for titles that F-Office does not draw; or why the chart is left out.
fn axis_titles_under(
xml: &str,
titles: crate::quirks::ChartAxisTitles,
) -> Result<Option<[TitleSummary; 2]>, ChartReason> {
use crate::quirks::{ChartDeletedAxis, ChartHorizontalBars, ChartStyleLook};
let doc = parse(xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_style_look(ChartStyleLook::StyleTwo)
.with_horizontal_bars(ChartHorizontalBars::Turned)
.with_deleted_axis(ChartDeletedAxis::PlotRoom)
.with_axis_titles(titles);
let columns = super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)?.columns;
let summary = |title: Option<Box<super::AxisTitle>>| {
title.map(|title| (title.size, title.text.lines.concat(), title.text.bold))
};
Ok(match columns.axis_titles {
super::AxisTitles::Drawn { value, category } => Some([summary(value), summary(category)]),
super::AxisTitles::Other => None,
})
}
#[test]
fn draws_axis_titles_of_one_line_at_the_automatic_place_where_the_target_does() {
use crate::quirks::ChartAxisTitles::{BesidePlot, Unknown};
let default = default_chart("b", TITLE);
let run = r#"sz="1000" b="0""#;
let value_title = axis_title(UPWARD_BODY, run, "Amount");
let value = with(&default, "<c:valAx>", &value_title);
let both = with(
&value,
CATEGORY_AXIS,
&axis_title(UPRIGHT_BODY, r#"sz="1200" b="1""#, "Quarter"),
);
let drawn = |size, text: &str, bold| Some((size, text.to_owned(), bold));
assert_eq!(
axis_titles_under(&value, BesidePlot),
Ok(Some([drawn(20, "Amount", false), None]))
);
assert_eq!(
axis_titles_under(&both, BesidePlot),
Ok(Some([
drawn(20, "Amount", false),
drawn(24, "Quarter", true)
]))
);
assert_eq!(
axis_titles_under(&with(&line_chart(), "<c:valAx>", &value_title), BesidePlot),
Ok(Some([drawn(20, "Amount", false), None]))
);
// The earlier rule: the plot area of Word's default chart, without the title.
assert_eq!(axis_titles_under(&value, Unknown), Ok(None));
// A body that writes no turn, and a title that writes no size and no bold: the chart
// text's size, and bold.
let unturned = with(
&default,
"<c:valAx>",
&axis_title("<a:bodyPr/>", "", "Amount"),
);
assert_eq!(
axis_titles_under(&unturned, BesidePlot),
Ok(Some([drawn(20, "Amount", true), None]))
);
for (name, title) in [
("upright", axis_title(UPRIGHT_BODY, run, "Amount")),
(
"vertical",
axis_title(r#"<a:bodyPr vert="vert"/>"#, run, "Amount"),
),
("two lines", value_title.replaced("</a:p>", "</a:p><a:p/>")),
("empty", axis_title(UPWARD_BODY, run, "")),
(
"overlay",
value_title.replaced(r#"<c:overlay val="0"/>"#, r#"<c:overlay val="1"/>"#),
),
(
"no text",
r#"<c:title><c:overlay val="0"/></c:title>"#.to_owned(),
),
] {
let xml = with(&default, "<c:valAx>", &title);
assert_eq!(axis_titles_under(&xml, BesidePlot), Ok(None), "{name}");
}
}
#[test]
fn reads_manual_layout_axis_titles() {
use crate::quirks::ChartAxisTitles::BesidePlot;
let default = default_chart("b", TITLE);
let value_title = axis_title(UPWARD_BODY, r#"sz="1000" b="0""#, "Amount");
let manual = r#"</c:tx><c:layout><c:manualLayout><c:xMode val="edge"/><c:yMode val="edge"/><c:x val="0.01"/><c:y val="0.3"/></c:manualLayout></c:layout>"#;
let xml = with(
&default,
"<c:valAx>",
&value_title.replaced("</c:tx>", manual),
);
assert_eq!(
axis_titles_under(&xml, BesidePlot),
Ok(Some([Some((20, "Amount".to_owned(), false)), None]))
);
}
#[test]
fn leaves_out_the_axis_titles_of_charts_whose_form_takes_none() {
use crate::quirks::ChartAxisTitles::BesidePlot;
let value_title = axis_title(UPWARD_BODY, r#"sz="1000" b="0""#, "Amount");
// A deleted value axis, which the default chart's rule places without the title.
let deleted = with(&deleted_value_chart(), DELETED_VALUE_AXIS, &value_title);
assert_eq!(axis_titles_under(&deleted, BesidePlot), Ok(None));
// A legend at the left and horizontal bars, which no rule draws with an axis title.
let named =
default_chart("l", TITLE).replaced_all("<c:ser>", "<c:ser><c:tx><c:v>S</c:v></c:tx>");
let left = with(&named, "<c:valAx>", &value_title);
let rows = with(&default_chart("b", TITLE), "<c:valAx>", &value_title)
.replaced(r#"barDir val="col""#, r#"barDir val="bar""#);
for xml in [left, rows] {
assert_eq!(
axis_titles_under(&xml, BesidePlot),
Err(ChartReason::AxisTitle)
);
}
// Horizontal bars take an upright title on valAx (bottom) and upward on catAx (left).
let upright = axis_title(UPRIGHT_BODY, r#"sz="1000" b="0""#, "Amount");
let hbar_ok = with(&default_chart("b", TITLE), "<c:valAx>", &upright)
.replaced(r#"barDir val="col""#, r#"barDir val="bar""#);
assert!(matches!(
axis_titles_under(&hbar_ok, BesidePlot),
Ok(Some([Some(_), None]))
));
}
#[test]
fn reads_blank_points_and_categories_as_displayed() {
use crate::quirks::ChartBlankPoints::{AsDisplayed, Unknown};
use crate::reader::settings::PlotRules;
let read_blanks = |xml: &str, blank_points| {
let doc = parse(xml);
let rules = PlotRules::with_area(ChartPlotArea::FontLines).with_blank_points(blank_points);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.map(|found| found.columns)
};
let gap_series = r#"<c:ser><c:spPr><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></c:spPr><c:cat><c:strRef><c:strCache><c:ptCount val="3"/><c:pt idx="0"><c:v>A</c:v></c:pt><c:pt idx="2"><c:v>C</c:v></c:pt></c:strCache></c:strRef></c:cat><c:val><c:numRef><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>4.3</c:v></c:pt><c:pt idx="2"><c:v>2.5</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>"#;
let second = series("accent2", &["2.4", "1.8", "4.4"]);
let uncached = r#"<c:ser><c:spPr><a:solidFill><a:schemeClr val="accent2"/></a:solidFill></c:spPr><c:val><c:numRef><c:f>Sheet1!$C$2:$C$4</c:f></c:numRef></c:val></c:ser>"#;
let orig = format!(
"{}{}",
series("accent1", &["4.3", "2.5"]),
series("accent2", &["2.4", "4.4"])
);
let base = default_chart("b", TITLE).replaced(&orig, &format!("{gap_series}{second}"));
let as_gap = base.replaced("<c:plotArea>", r#"<c:dispBlanksAs val="gap"/><c:plotArea>"#);
let as_zero = base.replaced(
"<c:plotArea>",
r#"<c:dispBlanksAs val="zero"/><c:plotArea>"#,
);
let as_span = base.replaced(
"<c:plotArea>",
r#"<c:dispBlanksAs val="span"/><c:plotArea>"#,
);
let with_uncached = default_chart("b", TITLE)
.replaced(&orig, &format!("{gap_series}{uncached}"))
.replaced("<c:plotArea>", r#"<c:dispBlanksAs val="gap"/><c:plotArea>"#);
assert_eq!(
read_blanks(&as_gap, Unknown),
Err(ChartReason::SeriesValues)
);
let columns = read_blanks(&as_gap, AsDisplayed).unwrap();
assert_eq!(
columns.series[0].values,
vec![
Some(Decimal::parse("4.3").unwrap()),
None,
Some(Decimal::parse("2.5").unwrap()),
]
);
assert_eq!(
columns.category_names,
Some(vec!["A".to_owned(), String::new(), "C".to_owned()])
);
// `zero` and an omitted `c:dispBlanksAs` turn every blank point into zero.
for xml in [&as_zero, &base] {
let zeroed = read_blanks(xml, AsDisplayed).unwrap();
assert_eq!(
zeroed.series[0].values,
vec![
Some(Decimal::parse("4.3").unwrap()),
Some(Decimal::ZERO),
Some(Decimal::parse("2.5").unwrap()),
]
);
}
// `span` and a series without a cache are not drawn yet.
assert_eq!(
read_blanks(&as_span, AsDisplayed),
Err(ChartReason::SeriesValues)
);
assert_eq!(
read_blanks(&with_uncached, AsDisplayed),
Err(ChartReason::SeriesValues)
);
}
#[test]
fn reads_stacked_and_percent_stacked_bars_where_the_target_draws_them() {
use crate::quirks::ChartHorizontalBars::Turned;
use crate::quirks::ChartStackedBars::{Stacked, Unknown};
let read_bar = |xml: &str, stacked: crate::quirks::ChartStackedBars| {
let doc = parse(xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_horizontal_bars(Turned)
.with_stacked_bars(stacked);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.map(|found| found.columns)
};
let stacked_col = default_chart("b", TITLE)
.replaced(
r#"<c:grouping val="clustered"/>"#,
r#"<c:grouping val="stacked"/>"#,
)
.replaced(r#"<c:overlap val="-27"/>"#, r#"<c:overlap val="100"/>"#);
let percent_bar = stacked_col
.replaced(r#"<c:barDir val="col"/>"#, r#"<c:barDir val="bar"/>"#)
.replaced(
r#"<c:grouping val="stacked"/>"#,
r#"<c:grouping val="percentStacked"/>"#,
);
let standard_col = stacked_col.replaced(
r#"<c:grouping val="stacked"/>"#,
r#"<c:grouping val="standard"/>"#,
);
assert_eq!(
read_bar(&stacked_col, Unknown),
Err(ChartReason::NotClustered)
);
let col = read_bar(&stacked_col, Stacked).unwrap();
assert_eq!(
col.group,
ChartGroup::Columns {
gap: 219,
overlap: 100,
stacking: super::BarStacking::Stacked,
}
);
assert_eq!(col.default_chart_rule(), Err(ChartReason::NotClustered));
assert_eq!(col.font_lines_rule(), Ok(PlotRule::FontLines));
let bar = read_bar(&percent_bar, Stacked).unwrap();
assert_eq!(
bar.group,
ChartGroup::Bars {
gap: 219,
overlap: 100,
stacking: super::BarStacking::PercentStacked,
}
);
assert_eq!(
read_bar(&standard_col, Stacked),
Err(ChartReason::NotClustered)
);
}
#[test]
fn reads_centered_and_default_data_labels_of_stacked_bars() {
use crate::quirks::ChartStackedBars::Stacked;
let read_labels = |pos: &str| {
let dlbls = format!(r#"<c:dLbls>{pos}<c:showVal val="1"/></c:dLbls>"#);
let xml = default_chart("b", TITLE)
.replaced(
r#"<c:grouping val="clustered"/>"#,
r#"<c:grouping val="stacked"/>"#,
)
.replaced("<c:gapWidth", &format!("{dlbls}<c:gapWidth"));
let doc = parse(&xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_stacked_bars(Stacked);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.unwrap()
.columns
};
let ctr = read_labels(r#"<c:dLblPos val="ctr"/>"#);
assert!(matches!(ctr.series[0].labels, SeriesLabels::Values(_)));
let default = read_labels("");
assert!(matches!(default.series[0].labels, SeriesLabels::Values(_)));
// Clustered outer-end labels are not drawn on stacked bars.
let out_end = read_labels(r#"<c:dLblPos val="outEnd"/>"#);
assert!(matches!(out_end.series[0].labels, SeriesLabels::Other));
}
fn read_doughnut(
extra: &str,
ser: &str,
quirk: crate::quirks::ChartDoughnuts,
) -> Result<super::Columns, ChartReason> {
let xml = format!(
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:chart><c:autoTitleDeleted val="1"/><c:plotArea><c:doughnutChart><c:varyColors val="1"/>{ser}{extra}</c:doughnutChart></c:plotArea></c:chart></c:chartSpace>"#
);
let doc = parse(&xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_style_look(crate::quirks::ChartStyleLook::StyleTwo)
.with_doughnuts(quirk);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).map(|p| p.columns)
}
fn doughnut_series_xml(idx: usize, extra: &str) -> String {
format!(
r#"<c:ser><c:idx val="{idx}"/><c:order val="{idx}"/>{extra}<c:cat><c:strRef><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>A</c:v></c:pt><c:pt idx="1"><c:v>B</c:v></c:pt></c:strCache></c:strRef></c:cat><c:val><c:numRef><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>3</c:v></c:pt><c:pt idx="1"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>"#
)
}
#[test]
fn reads_single_series_doughnuts_under_the_doughnuts_quirk() {
use crate::quirks::ChartDoughnuts::{Annulus, Unknown};
let s0 = doughnut_series_xml(0, "");
let extra = r#"<c:firstSliceAng val="90"/><c:holeSize val="75%"/>"#;
assert_eq!(
read_doughnut(extra, &s0, Unknown),
Err(ChartReason::OtherGroup)
);
let drawn = read_doughnut(extra, &s0, Annulus).unwrap();
assert_eq!(
drawn.group,
ChartGroup::Doughnut {
first_angle: 90,
hole_size: 75,
}
);
assert!(matches!(drawn.series[0].fill, SeriesFill::Points(ref f) if f.len() == 2));
// Omitted holeSize defaults to 0 (solid circle on Word).
let omitted = read_doughnut("", &s0, Annulus).unwrap();
assert_eq!(
omitted.group,
ChartGroup::Doughnut {
first_angle: 0,
hole_size: 0,
}
);
}
#[test]
fn reads_multi_series_doughnuts_and_leaves_out_exploded_ones() {
use crate::quirks::ChartDoughnuts::Annulus;
let two = format!(
"{}{}",
doughnut_series_xml(0, r#"<c:dLbls><c:showVal val="1"/></c:dLbls>"#),
doughnut_series_xml(1, "")
);
let multi = read_doughnut(r#"<c:holeSize val="50"/>"#, &two, Annulus).unwrap();
assert_eq!(multi.series.len(), 2);
assert!(matches!(multi.series[0].labels, SeriesLabels::Values(_)));
let exploded = doughnut_series_xml(0, r#"<c:explosion val="25"/>"#);
assert_eq!(
read_doughnut(r#"<c:holeSize val="50"/>"#, &exploded, Annulus),
Err(ChartReason::PieExplosion)
);
}
#[test]
fn cycles_style_colors_across_lightness_tiers_past_six_items() {
use f_office_drawingml::color::{DrawColor, SchemeSlot};
let a1 = DrawColor::scheme(SchemeSlot::Accent1);
let cases = [
(0, 5, a1.clone()),
(0, 6, a1.clone().shaded(76_000)),
(6, 7, a1.clone().tinted(77_000)),
(0, 12, a1.clone().shaded(65_000)),
(6, 12, a1.clone()),
(12, 13, a1.clone().tinted(65_000)),
(0, 18, a1.clone().shaded(58_000)),
(6, 18, a1.clone().shaded(86_000)),
(12, 18, a1.clone().tinted(86_000)),
(0, 24, a1.clone().shaded(53_000)),
(18, 24, a1.tinted(77_000)),
];
for (index, count, expected) in cases {
assert_eq!(super::style_color(index, count), Some(expected));
}
}
/// Minimal shared-axis combination chart XML with `bar_dir`, `grouping`, `bar_idx`, and `line_idx`.
fn combo_chart_xml(bar_dir: &str, grouping: &str, bar_idx: usize, line_idx: usize) -> String {
let cats = r#"<c:cat><c:strRef><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>Q1</c:v></c:pt><c:pt idx="1"><c:v>Q2</c:v></c:pt></c:strCache></c:strRef></c:cat>"#;
let vals = r#"<c:val><c:numRef><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>4</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt></c:numCache></c:numRef></c:val>"#;
format!(
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:style val="2"/><c:chart><c:autoTitleDeleted val="1"/><c:plotArea><c:layout/><c:barChart><c:barDir val="{bar_dir}"/><c:grouping val="{grouping}"/><c:varyColors val="0"/><c:ser><c:idx val="{bar_idx}"/><c:order val="{bar_idx}"/><c:tx><c:strRef><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Bars</c:v></c:pt></c:strCache></c:strRef></c:tx>{cats}{vals}</c:ser><c:gapWidth val="150"/><c:axId val="1"/><c:axId val="2"/></c:barChart><c:lineChart><c:grouping val="standard"/><c:varyColors val="0"/><c:ser><c:idx val="{line_idx}"/><c:order val="{line_idx}"/><c:tx><c:strRef><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Line</c:v></c:pt></c:strCache></c:strRef></c:tx><c:marker><c:symbol val="none"/></c:marker>{cats}{vals}<c:smooth val="0"/></c:ser><c:marker val="1"/><c:smooth val="0"/><c:axId val="1"/><c:axId val="2"/></c:lineChart><c:catAx><c:axId val="1"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="b"/><c:tickLblPos val="nextTo"/><c:crossAx val="2"/><c:crosses val="autoZero"/></c:catAx><c:valAx><c:axId val="2"/><c:scaling><c:orientation val="minMax"/></c:scaling><c:delete val="0"/><c:axPos val="l"/><c:majorGridlines/><c:tickLblPos val="nextTo"/><c:crossAx val="1"/><c:crosses val="autoZero"/></c:valAx></c:plotArea><c:legend><c:legendPos val="b"/><c:overlay val="0"/></c:legend><c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/></c:chart></c:chartSpace>"#
)
}
/// Reads a combination chart XML under `combo`.
fn read_combo_chart(
xml: &str,
combo: crate::quirks::ChartComboCharts,
) -> Result<super::Columns, ChartReason> {
let doc = parse(xml);
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_style_look(crate::quirks::ChartStyleLook::StyleTwo)
.with_line_strokes(crate::quirks::ChartLineStrokes::StyleRound)
.with_stacked_bars(crate::quirks::ChartStackedBars::Stacked)
.with_combo_charts(combo);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules).map(|p| p.columns)
}
#[test]
fn reads_shared_axis_combo_charts_and_indexes_style_colors_by_idx() {
use crate::quirks::ChartComboCharts::{SharedAxes, Unknown};
use f_office_drawingml::color::{DrawColor, SchemeSlot};
let reversed = combo_chart_xml("col", "clustered", 1, 0);
assert_eq!(
read_combo_chart(&reversed, Unknown),
Err(ChartReason::NotOneGroup)
);
let drawn = read_combo_chart(&reversed, SharedAxes).unwrap();
let fills: Vec<_> = drawn.series.iter().map(|s| &s.fill).collect();
assert_eq!(
(drawn.bar_series().len(), drawn.line_series().len(), fills),
(
1,
1,
vec![
&SeriesFill::Color(DrawColor::scheme(SchemeSlot::Accent2)),
&SeriesFill::Color(DrawColor::scheme(SchemeSlot::Accent1)),
]
)
);
assert!(read_combo_chart(&combo_chart_xml("col", "stacked", 0, 1), SharedAxes).is_ok());
for bad in [
combo_chart_xml("bar", "clustered", 0, 1),
combo_chart_xml("col", "percentStacked", 0, 1),
] {
assert_eq!(
read_combo_chart(&bad, SharedAxes),
Err(ChartReason::NotOneGroup)
);
}
}
#[test]
fn reads_explicit_axis_crossings_under_set_rule() {
use super::CategoryCrossing::{At, AutoZero, Min};
use crate::quirks::ChartAxisCrossings::{Set, Unknown};
use crate::reader::settings::PlotRules;
let read = |cat: &str, val: &str, quirk| {
let xml = default_chart("b", TITLE)
.replaced("<c:catAx>", &format!("<c:catAx>{cat}"))
.replaced("<c:valAx>", &format!("<c:valAx>{val}"));
let doc = parse(&xml);
let rules = PlotRules::with_area(ChartPlotArea::FontLines).with_axis_crossings(quirk);
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
.unwrap()
.columns
.category_crossing
};
let cat0 = r#"<c:crossesAt val="0"/>"#;
let cat2 = r#"<c:crossesAt val="2"/>"#;
let val1 = r#"<c:crossesAt val="1"/>"#;
let val2 = r#"<c:crossesAt val="2"/>"#;
assert_eq!(read(cat0, val1, Unknown), None);
assert_eq!(
read(cat0, val1, Set),
Some(At(Decimal::parse("0").unwrap()))
);
assert_eq!(read(cat2, "", Set), Some(At(Decimal::parse("2").unwrap())));
assert_eq!(
read(
r#"<c:crosses val="min"/>"#,
r#"<c:crosses val="min"/>"#,
Set
),
Some(Min)
);
assert_eq!(read("", r#"<c:crossesAt val="-2"/>"#, Set), Some(AutoZero));
assert_eq!(read("", val2, Set), None);
assert_eq!(read(r#"<c:crosses val="max"/>"#, "", Set), None);
}
#[test]
fn reads_stacked_and_percent_stacked_lines_under_stacked_bars_quirk() {
use super::BarStacking;
use crate::quirks::ChartStackedBars::{Stacked, Unknown};
let xml = |grouping: &str| {
format!(
r#"<c:chartSpace xmlns:c="{C}" xmlns:a="{A}"><c:chart><c:autoTitleDeleted val="1"/><c:plotArea>
<c:lineChart><c:grouping val="{grouping}"/><c:varyColors val="0"/>
<c:ser><c:idx val="0"/><c:order val="0"/>
<c:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:srgbClr val="4472C4"/></a:solidFill><a:round/></a:ln></c:spPr>
<c:marker><c:symbol val="none"/></c:marker>
<c:cat><c:strRef><c:strCache><c:ptCount val="2"/><c:pt idx="0"><c:v>A</c:v></c:pt><c:pt idx="1"><c:v>B</c:v></c:pt></c:strCache></c:strRef></c:cat>
<c:val><c:numRef><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>2</c:v></c:pt><c:pt idx="1"><c:v>4</c:v></c:pt></c:numCache></c:numRef></c:val>
</c:ser>
<c:axId val="1"/><c:axId val="2"/>
</c:lineChart>
<c:catAx><c:axId val="1"/><c:scaling/><c:delete val="0"/><c:axPos val="b"/><c:crossAx val="2"/></c:catAx>
<c:valAx><c:axId val="2"/><c:scaling/><c:delete val="0"/><c:axPos val="l"/><c:numFmt formatCode="General" sourceLinked="1"/><c:crossAx val="1"/></c:valAx>
</c:plotArea></c:chart></c:chartSpace>"#
)
};
let separators = crate::NumberSeparators::new('.', ',').unwrap();
let read_line = |grouping: &str, quirk: crate::quirks::ChartStackedBars| {
let doc = parse(&xml(grouping));
let rules = crate::reader::settings::PlotRules::with_area(ChartPlotArea::FontLines)
.with_stacked_bars(quirk)
.with_label_formats(crate::quirks::ChartLabelFormats::Codes, Some(separators));
super::read(&mut PartReader::new(&doc), doc.root().unwrap(), rules)
};
assert_eq!(
read_line("stacked", Unknown).map(|_| ()),
Err(ChartReason::StackedLines)
);
assert_eq!(
read_line("percentStacked", Unknown).map(|_| ()),
Err(ChartReason::StackedLines)
);
let stacked = read_line("stacked", Stacked).unwrap();
assert_eq!(
stacked.columns.group.line_stacking(),
Some(BarStacking::Stacked)
);
// A 100%-stacked line chart with General sourceLinked axis defaults to `0%` value formatting.
let percent = read_line("percentStacked", Stacked).unwrap();
assert_eq!(
percent.columns.group.line_stacking(),
Some(BarStacking::PercentStacked)
);
let fmt = percent.columns.value_format.as_ref().unwrap();
let written = fmt.write(Decimal::parse("0.5").unwrap()).unwrap();
let text: String = written
.pieces
.iter()
.filter_map(|p| match p {
super::LabelPiece::Text(t) => Some(t.as_str()),
super::LabelPiece::Blank(_) => None,
})
.collect();
assert_eq!(text, "50%");
}