ravenous-tools/graphs/src/graphs.rs

304 lines
9.1 KiB
Rust

//! The module `graphs` is responsible for exporting graphs based on CSV data
//!
//! # Usage
//!
//! - [`make_graphs`]: The main action dispatcher for graph generation and removal.
use charts_rs::{Box, Color, RadarChart, RadarIndicator, Series, get_or_try_init_fonts};
use cli_parser::Config;
use config::graph::{GraphConfig, GraphTargetType};
use glob::glob;
use serde::{Deserialize, Serialize};
use std::{
fs::File,
io::{Read, Write},
iter,
process::Command,
};
use anyhow::{Context, Result};
/// Main action dispatch for the graph make
pub fn make_graphs(args: &GraphConfig, _config: &Config) -> Result<()> {
// Choose action to do
match args.target {
GraphTargetType::Generate => gen_graph(args),
GraphTargetType::Remove => del_graphs(args),
GraphTargetType::Init => init_graph_config(args),
}
}
/// Initialize the config on the main directory
fn init_graph_config(_args: &GraphConfig) -> Result<()> {
let mut f = File::create("graph_config.ron")?;
let theme = MiniTheme::new();
f.write_all(
ron::ser::to_string_pretty(&theme, ron::ser::PrettyConfig::default())
.context("Converting to toml")?
.as_bytes(),
)
.context("Writing to file")?;
Ok(())
}
/// Load the config if given of the default config if none
fn load_graph_config(args: &GraphConfig) -> Result<MiniTheme> {
if let Some(c) = &args.config {
println!("[INFO] Reading config {}", &c);
let mut f = File::open(c).context("Opening config")?;
let mut buf = String::new();
f.read_to_string(&mut buf).context("Reading the config")?;
Ok(ron::from_str(buf.as_str()).context("Deserializing config")?)
} else {
println!("[INFO] Loading default config");
Ok(MiniTheme::new())
}
}
/// Delete the existing graphs
fn del_graphs(args: &GraphConfig) -> Result<()> {
let mut cmd = Command::new("rm");
cmd.args(
glob("Images/Radar/*.svg")?
.map(|v| v.unwrap().to_str().unwrap().to_string())
.collect::<Vec<String>>(),
);
if args.all {
cmd.args(
glob("Images/Radar/*.png")?
.map(|v| v.unwrap().to_str().unwrap().to_string())
.collect::<Vec<String>>(),
);
}
if let Err(e) = cmd.output() {
println!(
"[ERRR] An error has occured when executing the remove target \n {:#?}",
e
)
}
Ok(())
}
/// Generate the graph and save it
fn gen_graph(args: &GraphConfig) -> Result<()> {
// Import CSV
let data = include_bytes!("../../data/lmroman8-regular.ttf") as &[u8];
get_or_try_init_fonts(Some(vec![data])).unwrap();
let csv = import_csv(args)?;
let maxv = &csv.max;
let cfg = load_graph_config(args)?;
for graph in csv.values {
// println!("{:?} {:#?}", maxv, graph);
// let path = format!("{}/{}.png", args.destination, &graph.name);
let path_svg = format!("{}/{}.svg", args.destination, &graph.name);
let path_png = format!("{}/{}.png", args.destination, &graph.name);
println!("[INFO] Processing {}", path_svg);
let mut f = File::create(&path_svg)?;
let mut r = RadarChart::new([graph].to_vec(), maxv.to_vec());
cfg.apply_to(&mut r);
f.write_all(r.svg().context("Converting to SVG")?.as_bytes())?;
let mut cmd = Command::new("convert");
cmd.arg("--size")
.arg("800x600")
.arg(&path_svg)
.arg(path_png);
println!("[INFO] Using convert cli to convert to png");
if let Err(e) = cmd.output() {
println!(
"[ERRR] An error has occured when converting the file {} to png \n {:#?}",
path_svg, e
)
}
}
Ok(())
}
/// Import the default csv
fn import_csv(args: &GraphConfig) -> Result<GraphValues> {
let file = File::open(&args.origin)
.context("Opening the radar file")
.unwrap();
let rdr = csv::ReaderBuilder::new().from_reader(file);
cleanup_csv(rdr)
}
/// The data for all graphs
struct GraphValues {
/// The max values of a graph
// max: Vec<(String, f32)>,
max: Vec<RadarIndicator>,
/// The list of all character and associated values
// values: Vec<(String, Vec<f32>)>,
values: Vec<Series>,
}
/// Cleanup the given csv to output usable data
fn cleanup_csv(mut rdr: csv::Reader<File>) -> Result<GraphValues> {
let headers = rdr.headers().context("Opening headers")?;
// Making the max/base vec
// Gathering all the different category names
let headers = headers
.iter()
.filter(|v| !v.is_empty())
.skip(1)
.map(|v| v.to_string())
.collect::<Vec<String>>();
// Gather all the different categories
let mut rdr = rdr.records();
// Calculate the max values
let maxvals: Vec<f32> = rdr
.next()
.context("Gathering max values")??
.iter()
.map(|v| v.parse::<f32>().unwrap_or(0.0))
.skip(1)
.collect();
// Calculate all the values of all graphs
let mut res = Vec::new();
for line in rdr {
let line = line.context("Parsing table lines")?;
let name = line
.get(0)
.context("Fetching name for character")?
.to_string()
.replace(" ", "_")
.replace("î", "i")
.to_lowercase()
.replace("é", "e");
let vals: Vec<f32> = line
.iter()
.skip(1)
.enumerate()
.map(|(i, v)| {
v.parse::<f32>().unwrap_or(0.0) * 5.0
/ maxvals.get(i).context("Fetching max value").unwrap()
})
.collect();
res.push(Series::new(name, vals));
}
Ok(GraphValues {
max: headers
.iter()
.map(|v| v.to_owned())
.zip(iter::repeat(5.0f32))
.map(|(name, max)| RadarIndicator { name, max })
.collect::<Vec<RadarIndicator>>(),
values: res,
})
}
impl MiniTheme {
/// The default theme for out tool
pub fn new() -> Self {
Self {
font_family: "LMRoman8".to_string(),
margin: Box {
left: -10.0,
top: 20.0,
right: 70.0,
bottom: 0.0,
},
width: 720.0,
height: 440.0,
grid_stroke_color: Color {
r: 77,
g: 69,
b: 57,
a: 255,
},
grid_stroke_width: 2.5,
series_stroke_width: 5.0,
series_label_font_size: 60.0,
series_label_font_color: Color {
r: 75,
g: 61,
b: 68,
a: 255,
},
series_colors: [Color {
r: 179,
g: 165,
b: 85,
a: 255,
}]
.to_vec(),
legend_show: Some(false),
}
}
/// Apply our super custom theme to the graph
pub(super) fn apply_to(&self, r: &mut RadarChart) {
r.font_family = self.font_family.clone();
r.margin = self.margin.clone();
r.width = self.width;
r.height = self.height;
r.grid_stroke_color = self.grid_stroke_color;
r.grid_stroke_width = self.grid_stroke_width;
r.series_stroke_width = self.series_stroke_width;
r.series_label_font_size = self.series_label_font_size;
r.series_label_font_color = self.series_label_font_color;
r.series_colors = self.series_colors.clone();
r.legend_show = self.legend_show;
}
}
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
#[derive(Serialize, Deserialize)]
pub struct MiniTheme {
pub font_family: String,
pub margin: Box,
pub width: f32,
pub height: f32,
pub legend_show: Option<bool>,
// pub background_color: Color,
pub grid_stroke_color: Color,
pub grid_stroke_width: f32,
pub series_stroke_width: f32,
pub series_label_font_size: f32,
pub series_label_font_color: Color,
pub series_colors: Vec<Color>,
// pub title_font_size: f32,
// pub title_font_color: Color,
// pub title_font_weight: Option<String>,
// pub title_margin: Option<Box>,
// pub title_align: Align,
// pub title_height: f32,
// pub sub_title_font_size: f32,
// pub sub_title_font_color: Color,
// pub sub_title_margin: Option<Box>,
// pub sub_title_align: Align,
// pub sub_title_height: f32,
// pub legend_font_size: f32,
// pub legend_font_color: Color,
// pub legend_align: Align,
// pub legend_margin: Option<Box>,
// pub x_axis_font_size: f32,
// pub x_axis_stroke_color: Color,
// pub x_axis_font_color: Color,
// pub x_axis_name_gap: f32,
// pub x_axis_height: f32,
// pub y_axis_font_size: f32,
// pub y_axis_font_color: Color,
// pub y_axis_stroke_color: Color,
// pub y_axis_split_number: usize,
// pub y_axis_name_gap: f32,
// pub table_header_color: Color,
// pub table_body_colors: Vec<Color>,
// pub table_border_color: Color,
}