mod chartex;
mod place;
mod read;
mod svg;
mod table;
mod theme;
use crate::excel::numfmt::NumFmt;
pub(crate) use place::{Charts, Placed, blocks};
pub(crate) use read::read;
#[cfg(test)]
pub(crate) use read::tests as test_parts;
pub(crate) use svg::{drawn_size, svg};
pub(crate) use table::data_table;
pub(crate) use theme::{Theme, color as drawing_color, color_element, with_luminance};
pub(crate) type Rgb = [u8; 3];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ChartConfig {
pub(crate) max_part_bytes: usize,
pub(crate) max_series_count: usize,
pub(crate) max_points_per_series: usize,
pub(crate) max_points_per_chart: usize,
pub(crate) max_label_chars: usize,
pub(crate) max_charts: usize,
}
impl Default for ChartConfig {
fn default() -> Self {
Self {
max_part_bytes: 16 * 1024 * 1024,
max_series_count: 255,
max_points_per_series: 32_000,
max_points_per_chart: 1_000_000,
max_label_chars: 1_000,
max_charts: 1_000,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct Chart {
pub(crate) title: Option<String>,
pub(crate) groups: Vec<PlotGroup>,
pub(crate) axes: Vec<Axis>,
pub(crate) legend: Option<LegendPosition>,
pub(crate) plot_box: Option<PlotBox>,
pub(crate) plot_visible_only: bool,
pub(crate) style: Option<u32>,
pub(crate) date1904: bool,
pub(crate) has_data: bool,
pub(crate) truncated: bool,
pub(crate) broken_refs: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct PlotBox {
pub(crate) inner: bool,
pub(crate) x: f32,
pub(crate) y: f32,
pub(crate) width: f32,
pub(crate) height: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PlotGroup {
pub(crate) kind: ChartKind,
pub(crate) three_d: bool,
pub(crate) vary_colors: bool,
pub(crate) axis_ids: Vec<u32>,
pub(crate) series: Vec<Series>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ChartKind {
Bar {
horizontal: bool,
grouping: Grouping,
gap_width_ratio: f32,
overlap_ratio: f32,
},
Line {
grouping: Grouping,
},
Area {
grouping: Grouping,
},
Pie {
first_slice_deg: f32,
},
Doughnut {
first_slice_deg: f32,
hole_ratio: f32,
},
Scatter {
smooth: bool,
},
Radar {
filled: bool,
},
NotDrawn {
name: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Grouping {
Standard,
Clustered,
Stacked,
PercentStacked,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Series {
pub(crate) index: u32,
pub(crate) name: Option<String>,
pub(crate) categories: Option<Categories>,
pub(crate) values: Option<Numbers>,
pub(crate) color: Rgb,
pub(crate) point_colors: Vec<Rgb>,
pub(crate) markers: bool,
pub(crate) line: bool,
pub(crate) dashed: bool,
pub(crate) smooth: bool,
pub(crate) labels: DataLabels,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct DataLabels {
pub(crate) value: bool,
pub(crate) percent: bool,
pub(crate) position: Option<LabelPosition>,
pub(crate) format: Option<NumFmt>,
pub(crate) points: Vec<(usize, bool, bool)>,
}
impl DataLabels {
pub(crate) fn shown(&self, index: usize) -> (bool, bool) {
match self.points.binary_search_by_key(&index, |(point, _, _)| *point) {
Ok(found) => (self.points[found].1, self.points[found].2),
Err(_) => (self.value, self.percent),
}
}
pub(crate) fn any(&self) -> bool {
self.value || self.percent || self.points.iter().any(|(_, value, percent)| *value || *percent)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LabelPosition {
OutsideEnd,
InsideEnd,
Center,
InsideBase,
Above,
Below,
Left,
Right,
BestFit,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Categories {
Text(Vec<Vec<Option<String>>>),
Numbers(Numbers),
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Numbers {
pub(crate) points: Vec<Option<f64>>,
pub(crate) format: NumFmt,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Axis {
pub(crate) id: u32,
pub(crate) kind: AxisKind,
pub(crate) position: AxisPosition,
pub(crate) deleted: bool,
pub(crate) reversed: bool,
pub(crate) min: Option<f64>,
pub(crate) max: Option<f64>,
pub(crate) format: Option<NumFmt>,
pub(crate) major_gridlines: bool,
pub(crate) title: Option<String>,
pub(crate) cross_axis: Option<u32>,
pub(crate) major_unit: Option<f64>,
pub(crate) label_skip: Option<usize>,
pub(crate) tick_labels: bool,
pub(crate) cross_between: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AxisKind {
Category,
Value,
Date,
Series,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AxisPosition {
Bottom,
Left,
Right,
Top,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LegendPosition {
Bottom,
Top,
Left,
Right,
TopRight,
}
impl Chart {
pub(crate) fn series(&self) -> impl Iterator<Item = &Series> {
self.groups.iter().flat_map(|group| &group.series)
}
}
impl Series {
pub(crate) fn label(&self) -> String {
self.name
.clone()
.unwrap_or_else(|| format!("Series {}", u64::from(self.index) + 1))
}
}
#[cfg(test)]
mod tests {
use super::{Chart, ChartConfig, ChartKind, Theme, data_table, read};
use crate::word::zip::ZipArchive;
use std::path::{Path, PathBuf};
const DRAWN_SIZE_PT: (f32, f32) = (432.0, 252.0);
fn office_files(dir: &Path) -> Vec<PathBuf> {
let mut found = Vec::new();
let mut pending = vec![dir.to_path_buf()];
while let Some(dir) = pending.pop() {
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
let path = entry.path();
let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or_default();
if path.is_dir() {
pending.push(path);
} else if matches!(extension, "xlsx" | "xlsm" | "docx") {
found.push(path);
}
}
}
found.sort();
found
}
fn describe(chart: &Chart) -> String {
let kinds: Vec<String> = chart
.groups
.iter()
.map(|group| match &group.kind {
ChartKind::NotDrawn { name } => format!("not-drawn:{name}"),
kind => format!("{kind:?}{}", if group.three_d { "(3-D)" } else { "" }),
})
.collect();
let points: Vec<usize> = chart
.series()
.map(|series| series.values.as_ref().map_or(0, |values| values.points.len()))
.collect();
let table = data_table(chart).map(|table| format!("{}x{}", table.rows.len(), table.n_cols));
let heads: Vec<String> = chart
.series()
.map(|series| {
let first: Vec<Option<f64>> = series
.values
.iter()
.flat_map(|values| values.points.iter().take(3).copied())
.collect();
let [red, green, blue] = series.color;
format!("{:?} #{red:02X}{green:02X}{blue:02X} {first:?}", series.label())
})
.collect();
format!(
"types={} series={} points={points:?} title={:?} cached={} truncated={} table={}\n {}",
kinds.join("+"),
points.len(),
chart.title,
chart.has_data,
chart.truncated,
table.unwrap_or_else(|| "none".into()),
heads.join("\n ")
)
}
fn draw(chart: &Chart, name: &str) -> bool {
let Ok(svg) = std::panic::catch_unwind(|| super::svg(chart, DRAWN_SIZE_PT)) else {
println!(" svg: PANIC");
return false;
};
let Some(svg) = svg else {
println!(" svg: not drawn");
return true;
};
println!(" svg: {} bytes", svg.len());
if let Ok(dir) = std::env::var("KAKEMONO_CHART_PNG_DIR") {
let dir = Path::new(&dir);
std::fs::write(dir.join(format!("{name}.svg")), &svg).unwrap();
let mut options = resvg::usvg::Options::default();
options.fontdb_mut().load_system_fonts();
let tree = resvg::usvg::Tree::from_str(&svg, &options).unwrap();
let size = tree.size().to_int_size();
let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width() * 2, size.height() * 2).unwrap();
resvg::render(
&tree,
resvg::tiny_skia::Transform::from_scale(2.0, 2.0),
&mut pixmap.as_mut(),
);
pixmap.save_png(dir.join(format!("{name}.png"))).unwrap();
}
true
}
#[test]
#[ignore = "reads the files under KAKEMONO_CHART_CORPUS"]
fn corpus_charts_read_without_panics() {
let dir = std::env::var("KAKEMONO_CHART_CORPUS").expect("KAKEMONO_CHART_CORPUS");
let (mut charts, mut panics) = (0, 0);
for path in office_files(Path::new(&dir)) {
let data = std::fs::read(&path).unwrap();
let Ok(zip) = ZipArchive::new(&data) else { continue };
let theme_part = ["xl/theme/theme1.xml", "word/theme/theme1.xml"]
.into_iter()
.find_map(|name| zip.read(name).ok().flatten());
let theme = Theme::read(theme_part.as_deref());
let mut parts: Vec<String> = zip
.names()
.into_iter()
.filter(|name| {
let file = name.rsplit('/').next().unwrap_or_default();
name.contains("/charts/") && file.starts_with("chart") && file.ends_with(".xml")
})
.collect();
parts.sort();
for part in parts {
let Some(xml) = zip.read(&part).ok().flatten() else {
continue;
};
charts += 1;
let result = std::panic::catch_unwind(|| read(&xml, &theme, &ChartConfig::default()));
let file = path.file_name().unwrap().to_string_lossy();
match result {
Ok(Ok(chart)) => {
println!("{file} {part}: {}", describe(&chart));
let name = format!(
"{}-{}",
file.trim_end_matches(".xlsx"),
part.rsplit('/').next().unwrap_or_default()
);
panics += usize::from(!draw(&chart, &name.replace(".xml", "")));
}
Ok(Err(error)) => println!("{file} {part}: error {error:#}"),
Err(_) => {
panics += 1;
println!("{file} {part}: PANIC");
}
}
}
}
println!("{charts} chart parts, {panics} panics");
assert_eq!(panics, 0);
}
}