1
//! The Reports tab's chart pane: the picture of the shown report, fetched as a PNG.
2

            
3
use cli_core::render::{WireValue, parse_wire};
4
use cli_core::report_form::{ChartRequest, chart_call, png_from_literal};
5
use forms::{Form, FormValues};
6
use ratatui::buffer::Buffer;
7
use ratatui::layout::{Rect, Size};
8
use ratatui::widgets::{Paragraph, Widget, Wrap};
9
use rpc::chart::{ChartBackend, ChartFormat, ChartLook, MAX_SIDE};
10
use scripting::nomiscript::Value;
11
use tvui::{Image, ImageBackend, ImageError, Role, Theme, inner};
12

            
13
use crate::tabs::seq::Seq;
14
use crate::view::DrawCtx;
15
use crate::window::WindowId;
16

            
17
/// The kitty image id of window 0; each window adds its own id, so charts never replace each other.
18
const KITTY_IMAGE_BASE: u32 = 0x4E_4F_4D;
19

            
20
/// The kitty image id of the chart of `window`.
21
#[must_use]
22
57
pub fn kitty_image_id(window: WindowId) -> u32 {
23
57
    KITTY_IMAGE_BASE.saturating_add(window.0)
24
57
}
25

            
26
/// What the chart is drawn on: the screen, its cell size in pixels and the graphics protocol.
27
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28
pub struct TerminalEnv {
29
    pub screen: Size,
30
    pub cell_pixels: (u16, u16),
31
    pub backend: ChartBackend,
32
}
33

            
34
/// The pane's size in cells: the area inside the frame of the window drawn at `window`.
35
#[must_use]
36
91
pub fn pane_cells(window: Rect) -> Size {
37
91
    inner(window).as_size()
38
91
}
39

            
40
/// The pixel height of a terminal glyph: about 70% of its cell, at least 8.
41
98
fn glyph_px(cell_h: u16) -> u32 {
42
98
    ((u32::from(cell_h) * 7 + 5) / 10).max(8)
43
98
}
44

            
45
impl TerminalEnv {
46
    /// A pane of `cells` in pixels and the text height of a terminal glyph. Both shrink
47
    /// together past the renderer's limit, so the picture keeps the pane's shape.
48
93
    fn fit(self, cells: Size) -> ((u32, u32), u32) {
49
93
        let (cell_w, cell_h) = self.cell_pixels;
50
186
        let pane = |cells: u16, cell: u16| (u32::from(cells) * u32::from(cell)).max(1);
51
93
        let (width, height, text) = (
52
93
            pane(cells.width, cell_w),
53
93
            pane(cells.height, cell_h),
54
93
            glyph_px(cell_h),
55
93
        );
56
93
        let longest = u64::from(width.max(height));
57
279
        let shrink = |side: u32| match longest > u64::from(MAX_SIDE) {
58
6
            true => u32::try_from(u64::from(side) * u64::from(MAX_SIDE) / longest)
59
6
                .unwrap_or(MAX_SIDE)
60
6
                .max(1),
61
273
            false => side,
62
279
        };
63
93
        ((shrink(width), shrink(height)), shrink(text))
64
93
    }
65
}
66

            
67
/// Text `text_px` high, on the colour of the pane.
68
97
fn look(text_px: u32, theme: &Theme) -> ChartLook {
69
97
    ChartLook {
70
97
        text_px,
71
97
        background: Some(theme.bg_rgb(Role::Panel)),
72
97
    }
73
97
}
74

            
75
/// The user config key that forces the chart's graphics protocol: `kitty` or `halfblocks`.
76
pub const BACKEND_KEY: &str = "tui-chart-backend";
77

            
78
enum ChartState {
79
    Loading,
80
    Ready(Picture),
81
    Failed(String),
82
}
83

            
84
/// A drawn chart with the PNG it came from, so a new protocol redraws it without a fetch.
85
struct Picture {
86
    png: Vec<u8>,
87
    cells: Size,
88
    backend: ChartBackend,
89
    image_id: u32,
90
    image: Image,
91
}
92

            
93
impl Picture {
94
58
    fn new(png: Vec<u8>, cells: Size, env: TerminalEnv, image_id: u32) -> Result<Self, String> {
95
58
        let backend = image_backend(env.backend, image_id);
96
        let image =
97
58
            Image::new(&png, backend, cells, env.cell_pixels).map_err(|err| chart_error(&err))?;
98
55
        Ok(Self {
99
55
            png,
100
55
            cells,
101
55
            backend: env.backend,
102
55
            image_id,
103
55
            image,
104
55
        })
105
58
    }
106
}
107

            
108
3
fn chart_error(err: &ImageError) -> String {
109
3
    match err {
110
1
        ImageError::NoRoom => "the chart pane has no room".to_string(),
111
2
        ImageError::NotPng(err) => format!("the chart is not a PNG: {err}"),
112
        ImageError::Protocol(err) => format!("the chart cannot be drawn: {err}"),
113
    }
114
3
}
115

            
116
60
fn image_backend(backend: ChartBackend, image_id: u32) -> ImageBackend {
117
60
    match backend {
118
48
        ChartBackend::Kitty => ImageBackend::Kitty { id: image_id },
119
12
        ChartBackend::Halfblocks => ImageBackend::HalfBlocks,
120
    }
121
60
}
122

            
123
/// What the app knows of the terminal, shared by every Reports window.
124
#[derive(Default)]
125
pub struct TerminalState {
126
    env: Option<TerminalEnv>,
127
    backend_override: Option<String>,
128
}
129

            
130
impl TerminalState {
131
    #[must_use]
132
45356
    pub fn env(&self) -> Option<TerminalEnv> {
133
45356
        self.env
134
45356
    }
135

            
136
    #[must_use]
137
630
    pub fn backend_override(&self) -> Option<&str> {
138
630
        self.backend_override.as_deref()
139
630
    }
140

            
141
    /// Adopts the terminal's geometry and returns the one it replaces.
142
767
    pub fn replace(&mut self, env: TerminalEnv) -> Option<TerminalEnv> {
143
767
        self.env.replace(env)
144
767
    }
145

            
146
    /// Keeps the override a current reply holds.
147
60
    pub fn set_override(&mut self, value: Option<String>) {
148
60
        self.backend_override = value;
149
60
    }
150
}
151

            
152
pub struct ChartPane {
153
    shown: bool,
154
    /// Counts chart requests; a reply of an older one is dropped.
155
    seq: Seq,
156
    /// Counts reads of [`BACKEND_KEY`]; a reply of an older one is dropped.
157
    override_seq: Seq,
158
    state: ChartState,
159
}
160

            
161
impl ChartPane {
162
    #[must_use]
163
2079
    pub fn new() -> Self {
164
2079
        Self {
165
2079
            shown: false,
166
2079
            seq: Seq::default(),
167
2079
            override_seq: Seq::default(),
168
2079
            state: ChartState::Loading,
169
2079
        }
170
2079
    }
171

            
172
    #[must_use]
173
545
    pub fn shown(&self) -> bool {
174
545
        self.shown
175
545
    }
176

            
177
70
    pub fn toggle(&mut self) {
178
70
        self.shown = !self.shown;
179
70
    }
180

            
181
    /// Start a read of the backend override and return its number.
182
64
    pub fn begin_override(&mut self) -> u64 {
183
64
        self.override_seq.advance()
184
64
    }
185

            
186
    /// Whether a reply of read `seq` is the pane's current one.
187
    #[must_use]
188
61
    pub fn awaits_override(&self, seq: u64) -> bool {
189
61
        self.override_seq.awaits(seq)
190
61
    }
191

            
192
    /// Adopts a new terminal geometry; returns whether the chart must be fetched again.
193
    /// A new protocol alone redraws the picture already held.
194
288
    pub fn on_env(&mut self, previous: Option<TerminalEnv>, env: TerminalEnv) -> bool {
195
288
        let Some(previous) = previous else {
196
74
            return true;
197
        };
198
214
        if previous.screen != env.screen || previous.cell_pixels != env.cell_pixels {
199
16
            return true;
200
198
        }
201
198
        if previous.backend != env.backend {
202
2
            self.redraw_kept(env);
203
196
        }
204
198
        false
205
288
    }
206

            
207
16
    fn redraw_kept(&mut self, env: TerminalEnv) {
208
16
        if let ChartState::Ready(picture) = std::mem::replace(&mut self.state, ChartState::Loading)
209
        {
210
15
            self.state = match Picture::new(picture.png, picture.cells, env, picture.image_id) {
211
15
                Ok(picture) => ChartState::Ready(picture),
212
                Err(reason) => ChartState::Failed(reason),
213
            };
214
1
        }
215
16
    }
216

            
217
    /// The `report-chart` call for a pane of `cells` on `env`.
218
    #[must_use]
219
91
    pub fn call(
220
91
        form: &Form,
221
91
        values: &FormValues,
222
91
        env: TerminalEnv,
223
91
        cells: Size,
224
91
        theme: &Theme,
225
91
    ) -> String {
226
91
        let (size, text_px) = env.fit(cells);
227
91
        let request = ChartRequest {
228
91
            kind: "bar",
229
91
            format: ChartFormat::Png,
230
91
            size,
231
91
            look: look(text_px, theme),
232
91
        };
233
91
        chart_call(form, values, &request)
234
91
    }
235

            
236
    /// Start a request and return its number.
237
348
    pub fn begin(&mut self) -> u64 {
238
348
        self.state = ChartState::Loading;
239
348
        self.seq.advance()
240
348
    }
241

            
242
    pub fn fail(&mut self, reason: &str) {
243
        self.state = ChartState::Failed(reason.to_string());
244
    }
245

            
246
    /// Show the reply of request `seq`, drawn for a pane of `cells`.
247
45
    pub fn accept(
248
45
        &mut self,
249
45
        seq: u64,
250
45
        cells: Size,
251
45
        env: Option<TerminalEnv>,
252
45
        window: WindowId,
253
45
        wire: &str,
254
45
    ) {
255
45
        if !self.seq.awaits(seq) {
256
2
            return;
257
43
        }
258
43
        self.state = match Self::decode(cells, env, kitty_image_id(window), wire) {
259
40
            Ok(picture) => ChartState::Ready(picture),
260
3
            Err(reason) => ChartState::Failed(reason),
261
        };
262
45
    }
263

            
264
43
    fn decode(
265
43
        cells: Size,
266
43
        env: Option<TerminalEnv>,
267
43
        image_id: u32,
268
43
        wire: &str,
269
43
    ) -> Result<Picture, String> {
270
43
        let Some(env) = env else {
271
            return Err("the terminal size is not known".to_string());
272
        };
273
43
        let png = match parse_wire(wire).map_err(|err| err.to_string())? {
274
            WireValue::Value(Value::String(literal)) => {
275
42
                png_from_literal(&literal).map_err(|err| err.to_string())?
276
            }
277
            WireValue::Value(_) => return Err("the chart reply is not a PNG".to_string()),
278
        };
279
41
        Picture::new(png, cells, env, image_id)
280
43
    }
281

            
282
    /// Gives up the transmitted kitty image: the picture is rebuilt from its PNG so the next draw
283
    /// transmits again. Returns the id the terminal must delete.
284
2146
    pub fn forget_kitty(&mut self, env: Option<TerminalEnv>) -> Option<u32> {
285
2146
        let id = self.kitty_id()?;
286
15
        if let Some(env) = env {
287
14
            self.redraw_kept(env);
288
1
        }
289
15
        Some(id)
290
2146
    }
291

            
292
    /// The kitty image the pane has transmitted, if it shows one.
293
    #[must_use]
294
2147
    pub fn kitty_id(&self) -> Option<u32> {
295
2147
        match &self.state {
296
17
            ChartState::Ready(picture) if picture.backend == ChartBackend::Kitty => {
297
16
                Some(picture.image_id)
298
            }
299
2131
            _ => None,
300
        }
301
2147
    }
302

            
303
    /// Draw the pane; a kitty image outside the active window stays undrawn so its one-cell kitty transmit is not lost.
304
126
    pub fn draw(&self, buf: &mut Buffer, inner: Rect, ctx: &DrawCtx) {
305
126
        match &self.state {
306
72
            ChartState::Loading => Paragraph::new("Loading chart...").render(inner, buf),
307
            ChartState::Failed(reason) => {
308
                let message =
309
3
                    Paragraph::new(format!("[error] {reason}")).wrap(Wrap { trim: false });
310
3
                message.render(inner, buf);
311
            }
312
            ChartState::Ready(picture)
313
51
                if ctx.frame.mode == tvui::FrameMode::Active
314
5
                    || picture.backend != ChartBackend::Kitty =>
315
            {
316
47
                picture.image.render(inner, buf, ctx.theme.bg(Role::Panel));
317
            }
318
4
            ChartState::Ready(_) => {}
319
        }
320
126
    }
321
}
322

            
323
impl Default for ChartPane {
324
    fn default() -> Self {
325
        Self::new()
326
    }
327
}
328

            
329
#[cfg(test)]
330
mod tests;