1
//! A chart spec in the format a client asks for.
2

            
3
use base64::Engine;
4
use base64::engine::general_purpose::STANDARD as BASE64;
5
use plotting::DEFAULT_TEXT_PX;
6
use plotting::kitty::{KittyOpts, render_png};
7
use plotting::svg::render_svg;
8
use plotting::text::render_text_default;
9
use plotting::{ChartKind, ChartSpec, Series, SeriesPoint};
10
use scripting::runtime::EvalValue;
11

            
12
use crate::forms::outcome::key;
13

            
14
pub const MAX_SIDE: u32 = 2048;
15

            
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17
pub enum ChartFormat {
18
    Spec,
19
    Svg,
20
    Png,
21
    Text,
22
}
23

            
24
impl ChartFormat {
25
    #[must_use]
26
19520
    pub fn name(self) -> &'static str {
27
19520
        match self {
28
            Self::Spec => "spec",
29
480
            Self::Svg => "svg",
30
16800
            Self::Png => "png",
31
2240
            Self::Text => "text",
32
        }
33
19520
    }
34

            
35
    #[must_use]
36
5004
    pub fn parse(name: &str) -> Option<Self> {
37
5004
        match name.to_ascii_lowercase().as_str() {
38
26
            "spec" => Some(Self::Spec),
39
485
            "svg" => Some(Self::Svg),
40
1767
            "png" => Some(Self::Png),
41
2724
            "text" => Some(Self::Text),
42
2
            _ => None,
43
        }
44
5004
    }
45
}
46

            
47
348
fn text(value: &str) -> EvalValue {
48
348
    EvalValue::String(value.to_string())
49
348
}
50

            
51
#[must_use]
52
4982
pub fn kind_name(kind: ChartKind) -> &'static str {
53
4982
    match kind {
54
3046
        ChartKind::Bar => "bar",
55
2
        ChartKind::HBar => "hbar",
56
8
        ChartKind::StackedBar => "stacked",
57
1926
        ChartKind::Line => "line",
58
    }
59
4982
}
60

            
61
81
fn point_value(point: &SeriesPoint) -> EvalValue {
62
81
    EvalValue::List(vec![
63
81
        key("X"),
64
81
        text(&point.x),
65
81
        key("Y"),
66
81
        EvalValue::Ratio {
67
81
            numer: point.y_num,
68
81
            denom: point.y_denom,
69
81
        },
70
81
    ])
71
81
}
72

            
73
81
fn series_value(series: &Series) -> EvalValue {
74
81
    EvalValue::List(vec![
75
81
        key("LABEL"),
76
81
        text(&series.label),
77
81
        key("COMMODITY"),
78
81
        text(&series.commodity_symbol),
79
81
        key("POINTS"),
80
81
        EvalValue::List(series.points.iter().map(point_value).collect()),
81
81
    ])
82
81
}
83

            
84
/// The spec as a plist: `(:title … :kind … :x-label … :y-label … :series ((:label … :commodity …
85
/// :points ((:x … :y ratio) …)) …) :notes (…))`.
86
21
pub(super) fn spec_value(spec: &ChartSpec) -> EvalValue {
87
21
    EvalValue::List(vec![
88
21
        key("TITLE"),
89
21
        text(&spec.title),
90
21
        key("KIND"),
91
21
        text(kind_name(spec.kind)),
92
21
        key("X-LABEL"),
93
21
        text(&spec.x_label),
94
21
        key("Y-LABEL"),
95
21
        text(&spec.y_label),
96
21
        key("SERIES"),
97
21
        EvalValue::List(spec.series.iter().map(series_value).collect()),
98
21
        key("NOTES"),
99
21
        EvalValue::List(spec.notes.iter().map(|note| text(note)).collect()),
100
    ])
101
21
}
102

            
103
/// How a chart's text is sized and what a PNG is drawn on.
104
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105
pub 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

            
112
impl Default for ChartLook {
113
4516
    fn default() -> Self {
114
4516
        Self {
115
4516
            text_px: DEFAULT_TEXT_PX,
116
4516
            background: None,
117
4516
        }
118
4516
    }
119
}
120

            
121
/// The spec drawn as an SVG document.
122
#[must_use]
123
161
pub fn render_svg_chart(spec: &ChartSpec, width: u32, height: u32) -> String {
124
161
    render_svg(spec, width, height, DEFAULT_TEXT_PX)
125
161
}
126

            
127
/// The PNG as the `#"base64"` literal a bytes value prints as.
128
1606
fn png_value(
129
1606
    spec: &ChartSpec,
130
1606
    (width, height): (u32, u32),
131
1606
    look: ChartLook,
132
1606
) -> wasmtime::Result<EvalValue> {
133
1606
    let opts = KittyOpts {
134
1606
        width_px: width,
135
1606
        height_px: height,
136
1606
        text_px: look.text_px,
137
1606
        background: look.background,
138
1606
    };
139
1606
    let png = render_png(spec, opts)
140
        .ok_or_else(|| wasmtime::Error::msg("the chart could not be drawn as a PNG"))?;
141
1606
    Ok(EvalValue::String(format!("#\"{}\"", BASE64.encode(png))))
142
1606
}
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.
148
4673
pub fn render_chart(
149
4673
    spec: &ChartSpec,
150
4673
    format: ChartFormat,
151
4673
    size: (u32, u32),
152
4673
    look: ChartLook,
153
4673
) -> wasmtime::Result<EvalValue> {
154
4673
    match format {
155
20
        ChartFormat::Spec => Ok(spec_value(spec)),
156
484
        ChartFormat::Svg => Ok(EvalValue::String(render_svg(
157
484
            spec,
158
484
            size.0,
159
484
            size.1,
160
484
            look.text_px,
161
484
        ))),
162
1606
        ChartFormat::Png => png_value(spec, size, look),
163
2563
        ChartFormat::Text => Ok(EvalValue::String(render_text_default(spec))),
164
    }
165
4673
}