Skip to main content

cli_core/
report_form.rs

1//! Report forms submitted through `submit-form`, drawn by `report-chart`.
2
3use forms::{Form, FormValues, escape_str, write_payload};
4use nomiscript::Value;
5use plotting::kitty::encode_png_apc;
6use rpc::Session;
7use rpc::chart::{ChartFormat, ChartLook};
8
9use crate::CommandError;
10use crate::eval::Rendered;
11use crate::forms::map_references;
12use crate::render::reparse_list;
13use crate::transaction::eval_text;
14
15/// The width and height, in pixels, of a raster or vector chart.
16pub type ChartSize = (u32, u32);
17
18/// How a chart is drawn: its `kind` (`bar`, `line` or `stacked`), format, size and look.
19#[derive(Debug, Clone, Copy)]
20pub struct ChartRequest<'a> {
21    pub kind: &'a str,
22    pub format: ChartFormat,
23    pub size: ChartSize,
24    pub look: ChartLook,
25}
26
27/// The `:background` argument of a chart: `0xRRGGBB`, or `-1` for a transparent PNG.
28fn background_arg(background: Option<[u8; 3]>) -> i32 {
29    background.map_or(-1, |[r, g, b]| {
30        i32::from(r) << 16 | i32::from(g) << 8 | i32::from(b)
31    })
32}
33
34/// The `report-chart` call for `form`'s `values`.
35#[must_use]
36pub fn chart_call(form: &Form, values: &FormValues, request: &ChartRequest) -> String {
37    let (width, height) = request.size;
38    format!(
39        "(report-chart {} {} :kind {} :format {} :width {width} :height {height} \
40         :text-px {} :background {})",
41        escape_str(form.name),
42        escape_str(&write_payload(form, values)),
43        escape_str(request.kind),
44        escape_str(request.format.name()),
45        request.look.text_px,
46        background_arg(request.look.background),
47    )
48}
49
50/// The chart of a report form, as the text, SVG or PNG literal `report-chart` replies with.
51///
52/// # Errors
53/// [`CommandError::Argument`] for an unknown commodity,
54/// [`CommandError::FormInvalid`] with one line per rejected field, or the
55/// server error.
56pub async fn chart(
57    session: &mut Session,
58    form: &Form,
59    values: &FormValues,
60    request: &ChartRequest<'_>,
61) -> Result<String, CommandError> {
62    eval_mapped(session, form, values, |mapped| {
63        chart_call(form, mapped, request)
64    })
65    .await
66}
67
68async fn eval_mapped(
69    session: &mut Session,
70    form: &Form,
71    values: &FormValues,
72    call: impl FnOnce(&FormValues) -> String,
73) -> Result<String, CommandError> {
74    let mapped = map_references(session, form, values).await?;
75    eval_text(session, &call(&mapped)).await
76}
77
78/// The `report-csv` call for the category report form's `values`.
79#[must_use]
80pub fn csv_call(form: &Form, values: &FormValues) -> String {
81    format!("(report-csv {})", escape_str(&write_payload(form, values)))
82}
83
84/// The category report as the CSV text `report-csv` replies with.
85///
86/// # Errors
87/// As [`chart`].
88pub async fn csv(
89    session: &mut Session,
90    form: &Form,
91    values: &FormValues,
92) -> Result<String, CommandError> {
93    eval_mapped(session, form, values, |mapped| csv_call(form, mapped)).await
94}
95
96/// The PNG bytes of a report form's chart.
97///
98/// # Errors
99/// As [`chart`], or a reply that is not a bytes literal.
100pub async fn chart_png(
101    session: &mut Session,
102    form: &Form,
103    values: &FormValues,
104    kind: &str,
105    size: ChartSize,
106) -> Result<Vec<u8>, CommandError> {
107    let request = ChartRequest {
108        kind,
109        format: ChartFormat::Png,
110        size,
111        look: ChartLook::default(),
112    };
113    let literal = chart(session, form, values, &request).await?;
114    png_from_literal(&literal)
115}
116
117/// The PNG bytes of the `#"…"` literal a PNG `report-chart` replies with.
118///
119/// # Errors
120/// [`CommandError::Command`] when `literal` is not a bytes literal.
121pub fn png_from_literal(literal: &str) -> Result<Vec<u8>, CommandError> {
122    match reparse_list(literal) {
123        Ok(Value::Bytes(png)) => Ok(png),
124        Ok(other) => Err(CommandError::Command(format!(
125            "the chart reply is not a PNG: {}",
126            nomiscript::format_value(&other)
127        ))),
128        Err(e) => Err(CommandError::Command(format!(
129            "the chart reply is not a PNG: {e}"
130        ))),
131    }
132}
133
134/// The chart for a terminal: the kitty-graphics PNG when `kitty`, else text.
135///
136/// # Errors
137/// As [`chart_png`] and [`chart`].
138pub async fn terminal_chart(
139    session: &mut Session,
140    form: &Form,
141    values: &FormValues,
142    kind: &str,
143    kitty: bool,
144    size: ChartSize,
145) -> Result<Rendered, CommandError> {
146    if kitty {
147        let png = chart_png(session, form, values, kind, size).await?;
148        return Ok(Rendered::Bytes(encode_png_apc(&png).into_bytes()));
149    }
150    let request = ChartRequest {
151        kind,
152        format: ChartFormat::Text,
153        size,
154        look: ChartLook::default(),
155    };
156    let text = chart(session, form, values, &request).await?;
157    Ok(Rendered::Lines(text.lines().map(str::to_string).collect()))
158}
159
160#[cfg(test)]
161mod literal_tests;
162#[cfg(test)]
163mod tests;