1
//! Report forms submitted through `submit-form`, drawn by `report-chart`.
2

            
3
use forms::{Form, FormValues, escape_str, write_payload};
4
use nomiscript::Value;
5
use plotting::kitty::encode_png_apc;
6
use rpc::Session;
7
use rpc::chart::{ChartFormat, ChartLook};
8

            
9
use crate::CommandError;
10
use crate::eval::Rendered;
11
use crate::forms::map_references;
12
use crate::render::reparse_list;
13
use crate::transaction::eval_text;
14

            
15
/// The width and height, in pixels, of a raster or vector chart.
16
pub 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)]
20
pub 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.
28
1244
fn background_arg(background: Option<[u8; 3]>) -> i32 {
29
1244
    background.map_or(-1, |[r, g, b]| {
30
1154
        i32::from(r) << 16 | i32::from(g) << 8 | i32::from(b)
31
1154
    })
32
1244
}
33

            
34
/// The `report-chart` call for `form`'s `values`.
35
#[must_use]
36
1244
pub fn chart_call(form: &Form, values: &FormValues, request: &ChartRequest) -> String {
37
1244
    let (width, height) = request.size;
38
1244
    format!(
39
1244
        "(report-chart {} {} :kind {} :format {} :width {width} :height {height} \
40
         :text-px {} :background {})",
41
1244
        escape_str(form.name),
42
1244
        escape_str(&write_payload(form, values)),
43
1244
        escape_str(request.kind),
44
1244
        escape_str(request.format.name()),
45
1244
        request.look.text_px,
46
1244
        background_arg(request.look.background),
47
    )
48
1244
}
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.
56
90
pub async fn chart(
57
90
    session: &mut Session,
58
90
    form: &Form,
59
90
    values: &FormValues,
60
90
    request: &ChartRequest<'_>,
61
90
) -> Result<String, CommandError> {
62
90
    eval_mapped(session, form, values, |mapped| {
63
89
        chart_call(form, mapped, request)
64
89
    })
65
90
    .await
66
90
}
67

            
68
94
async fn eval_mapped(
69
94
    session: &mut Session,
70
94
    form: &Form,
71
94
    values: &FormValues,
72
94
    call: impl FnOnce(&FormValues) -> String,
73
94
) -> Result<String, CommandError> {
74
94
    let mapped = map_references(session, form, values).await?;
75
93
    eval_text(session, &call(&mapped)).await
76
94
}
77

            
78
/// The `report-csv` call for the category report form's `values`.
79
#[must_use]
80
149
pub fn csv_call(form: &Form, values: &FormValues) -> String {
81
149
    format!("(report-csv {})", escape_str(&write_payload(form, values)))
82
149
}
83

            
84
/// The category report as the CSV text `report-csv` replies with.
85
///
86
/// # Errors
87
/// As [`chart`].
88
4
pub async fn csv(
89
4
    session: &mut Session,
90
4
    form: &Form,
91
4
    values: &FormValues,
92
4
) -> Result<String, CommandError> {
93
4
    eval_mapped(session, form, values, |mapped| csv_call(form, mapped)).await
94
4
}
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.
100
28
pub async fn chart_png(
101
28
    session: &mut Session,
102
28
    form: &Form,
103
28
    values: &FormValues,
104
28
    kind: &str,
105
28
    size: ChartSize,
106
28
) -> Result<Vec<u8>, CommandError> {
107
28
    let request = ChartRequest {
108
28
        kind,
109
28
        format: ChartFormat::Png,
110
28
        size,
111
28
        look: ChartLook::default(),
112
28
    };
113
28
    let literal = chart(session, form, values, &request).await?;
114
27
    png_from_literal(&literal)
115
28
}
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.
121
474
pub fn png_from_literal(literal: &str) -> Result<Vec<u8>, CommandError> {
122
474
    match reparse_list(literal) {
123
460
        Ok(Value::Bytes(png)) => Ok(png),
124
13
        Ok(other) => Err(CommandError::Command(format!(
125
13
            "the chart reply is not a PNG: {}",
126
13
            nomiscript::format_value(&other)
127
13
        ))),
128
1
        Err(e) => Err(CommandError::Command(format!(
129
1
            "the chart reply is not a PNG: {e}"
130
1
        ))),
131
    }
132
474
}
133

            
134
/// The chart for a terminal: the kitty-graphics PNG when `kitty`, else text.
135
///
136
/// # Errors
137
/// As [`chart_png`] and [`chart`].
138
26
pub async fn terminal_chart(
139
26
    session: &mut Session,
140
26
    form: &Form,
141
26
    values: &FormValues,
142
26
    kind: &str,
143
26
    kitty: bool,
144
26
    size: ChartSize,
145
26
) -> Result<Rendered, CommandError> {
146
26
    if kitty {
147
1
        let png = chart_png(session, form, values, kind, size).await?;
148
1
        return Ok(Rendered::Bytes(encode_png_apc(&png).into_bytes()));
149
25
    }
150
25
    let request = ChartRequest {
151
25
        kind,
152
25
        format: ChartFormat::Text,
153
25
        size,
154
25
        look: ChartLook::default(),
155
25
    };
156
25
    let text = chart(session, form, values, &request).await?;
157
23
    Ok(Rendered::Lines(text.lines().map(str::to_string).collect()))
158
26
}
159

            
160
#[cfg(test)]
161
mod literal_tests;
162
#[cfg(test)]
163
mod tests;