Skip to main content

rpc/chart/
render.rs

1//! A chart spec in the format a client asks for.
2
3use base64::Engine;
4use base64::engine::general_purpose::STANDARD as BASE64;
5use plotting::DEFAULT_TEXT_PX;
6use plotting::kitty::{KittyOpts, render_png};
7use plotting::svg::render_svg;
8use plotting::text::render_text_default;
9use plotting::{ChartKind, ChartSpec, Series, SeriesPoint};
10use scripting::runtime::EvalValue;
11
12use crate::forms::outcome::key;
13
14pub const MAX_SIDE: u32 = 2048;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ChartFormat {
18    Spec,
19    Svg,
20    Png,
21    Text,
22}
23
24impl ChartFormat {
25    #[must_use]
26    pub fn name(self) -> &'static str {
27        match self {
28            Self::Spec => "spec",
29            Self::Svg => "svg",
30            Self::Png => "png",
31            Self::Text => "text",
32        }
33    }
34
35    #[must_use]
36    pub fn parse(name: &str) -> Option<Self> {
37        match name.to_ascii_lowercase().as_str() {
38            "spec" => Some(Self::Spec),
39            "svg" => Some(Self::Svg),
40            "png" => Some(Self::Png),
41            "text" => Some(Self::Text),
42            _ => None,
43        }
44    }
45}
46
47fn text(value: &str) -> EvalValue {
48    EvalValue::String(value.to_string())
49}
50
51#[must_use]
52pub fn kind_name(kind: ChartKind) -> &'static str {
53    match kind {
54        ChartKind::Bar => "bar",
55        ChartKind::HBar => "hbar",
56        ChartKind::StackedBar => "stacked",
57        ChartKind::Line => "line",
58    }
59}
60
61fn point_value(point: &SeriesPoint) -> EvalValue {
62    EvalValue::List(vec![
63        key("X"),
64        text(&point.x),
65        key("Y"),
66        EvalValue::Ratio {
67            numer: point.y_num,
68            denom: point.y_denom,
69        },
70    ])
71}
72
73fn series_value(series: &Series) -> EvalValue {
74    EvalValue::List(vec![
75        key("LABEL"),
76        text(&series.label),
77        key("COMMODITY"),
78        text(&series.commodity_symbol),
79        key("POINTS"),
80        EvalValue::List(series.points.iter().map(point_value).collect()),
81    ])
82}
83
84/// The spec as a plist: `(:title … :kind … :x-label … :y-label … :series ((:label … :commodity …
85/// :points ((:x … :y ratio) …)) …) :notes (…))`.
86pub(super) fn spec_value(spec: &ChartSpec) -> EvalValue {
87    EvalValue::List(vec![
88        key("TITLE"),
89        text(&spec.title),
90        key("KIND"),
91        text(kind_name(spec.kind)),
92        key("X-LABEL"),
93        text(&spec.x_label),
94        key("Y-LABEL"),
95        text(&spec.y_label),
96        key("SERIES"),
97        EvalValue::List(spec.series.iter().map(series_value).collect()),
98        key("NOTES"),
99        EvalValue::List(spec.notes.iter().map(|note| text(note)).collect()),
100    ])
101}
102
103/// How a chart's text is sized and what a PNG is drawn on.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct ChartLook {
106    /// The text height in pixels every label size scales from.
107    pub text_px: u32,
108    /// The PNG's opaque background; `None` leaves it transparent.
109    pub background: Option<[u8; 3]>,
110}
111
112impl Default for ChartLook {
113    fn default() -> Self {
114        Self {
115            text_px: DEFAULT_TEXT_PX,
116            background: None,
117        }
118    }
119}
120
121/// The spec drawn as an SVG document.
122#[must_use]
123pub fn render_svg_chart(spec: &ChartSpec, width: u32, height: u32) -> String {
124    render_svg(spec, width, height, DEFAULT_TEXT_PX)
125}
126
127/// The PNG as the `#"base64"` literal a bytes value prints as.
128fn png_value(
129    spec: &ChartSpec,
130    (width, height): (u32, u32),
131    look: ChartLook,
132) -> wasmtime::Result<EvalValue> {
133    let opts = KittyOpts {
134        width_px: width,
135        height_px: height,
136        text_px: look.text_px,
137        background: look.background,
138    };
139    let png = render_png(spec, opts)
140        .ok_or_else(|| wasmtime::Error::msg("the chart could not be drawn as a PNG"))?;
141    Ok(EvalValue::String(format!("#\"{}\"", BASE64.encode(png))))
142}
143
144/// `spec` in `format`; `size` is the SVG's and the PNG's width and height.
145///
146/// # Errors
147/// A PNG that cannot be drawn.
148pub fn render_chart(
149    spec: &ChartSpec,
150    format: ChartFormat,
151    size: (u32, u32),
152    look: ChartLook,
153) -> wasmtime::Result<EvalValue> {
154    match format {
155        ChartFormat::Spec => Ok(spec_value(spec)),
156        ChartFormat::Svg => Ok(EvalValue::String(render_svg(
157            spec,
158            size.0,
159            size.1,
160            look.text_px,
161        ))),
162        ChartFormat::Png => png_value(spec, size, look),
163        ChartFormat::Text => Ok(EvalValue::String(render_text_default(spec))),
164    }
165}