Skip to main content

tui/tabs/reports/
chart.rs

1//! The Reports tab's chart pane: the picture of the shown report, fetched as a PNG.
2
3use cli_core::render::{WireValue, parse_wire};
4use cli_core::report_form::{ChartRequest, chart_call, png_from_literal};
5use forms::{Form, FormValues};
6use ratatui::buffer::Buffer;
7use ratatui::layout::{Rect, Size};
8use ratatui::widgets::{Paragraph, Widget, Wrap};
9use rpc::chart::{ChartBackend, ChartFormat, ChartLook, MAX_SIDE};
10use scripting::nomiscript::Value;
11use tvui::{Image, ImageBackend, ImageError, Role, Theme, inner};
12
13use crate::tabs::seq::Seq;
14use crate::view::DrawCtx;
15use crate::window::WindowId;
16
17/// The kitty image id of window 0; each window adds its own id, so charts never replace each other.
18const KITTY_IMAGE_BASE: u32 = 0x4E_4F_4D;
19
20/// The kitty image id of the chart of `window`.
21#[must_use]
22pub fn kitty_image_id(window: WindowId) -> u32 {
23    KITTY_IMAGE_BASE.saturating_add(window.0)
24}
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)]
28pub 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]
36pub fn pane_cells(window: Rect) -> Size {
37    inner(window).as_size()
38}
39
40/// The pixel height of a terminal glyph: about 70% of its cell, at least 8.
41fn glyph_px(cell_h: u16) -> u32 {
42    ((u32::from(cell_h) * 7 + 5) / 10).max(8)
43}
44
45impl 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    fn fit(self, cells: Size) -> ((u32, u32), u32) {
49        let (cell_w, cell_h) = self.cell_pixels;
50        let pane = |cells: u16, cell: u16| (u32::from(cells) * u32::from(cell)).max(1);
51        let (width, height, text) = (
52            pane(cells.width, cell_w),
53            pane(cells.height, cell_h),
54            glyph_px(cell_h),
55        );
56        let longest = u64::from(width.max(height));
57        let shrink = |side: u32| match longest > u64::from(MAX_SIDE) {
58            true => u32::try_from(u64::from(side) * u64::from(MAX_SIDE) / longest)
59                .unwrap_or(MAX_SIDE)
60                .max(1),
61            false => side,
62        };
63        ((shrink(width), shrink(height)), shrink(text))
64    }
65}
66
67/// Text `text_px` high, on the colour of the pane.
68fn look(text_px: u32, theme: &Theme) -> ChartLook {
69    ChartLook {
70        text_px,
71        background: Some(theme.bg_rgb(Role::Panel)),
72    }
73}
74
75/// The user config key that forces the chart's graphics protocol: `kitty` or `halfblocks`.
76pub const BACKEND_KEY: &str = "tui-chart-backend";
77
78enum 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.
85struct Picture {
86    png: Vec<u8>,
87    cells: Size,
88    backend: ChartBackend,
89    image_id: u32,
90    image: Image,
91}
92
93impl Picture {
94    fn new(png: Vec<u8>, cells: Size, env: TerminalEnv, image_id: u32) -> Result<Self, String> {
95        let backend = image_backend(env.backend, image_id);
96        let image =
97            Image::new(&png, backend, cells, env.cell_pixels).map_err(|err| chart_error(&err))?;
98        Ok(Self {
99            png,
100            cells,
101            backend: env.backend,
102            image_id,
103            image,
104        })
105    }
106}
107
108fn chart_error(err: &ImageError) -> String {
109    match err {
110        ImageError::NoRoom => "the chart pane has no room".to_string(),
111        ImageError::NotPng(err) => format!("the chart is not a PNG: {err}"),
112        ImageError::Protocol(err) => format!("the chart cannot be drawn: {err}"),
113    }
114}
115
116fn image_backend(backend: ChartBackend, image_id: u32) -> ImageBackend {
117    match backend {
118        ChartBackend::Kitty => ImageBackend::Kitty { id: image_id },
119        ChartBackend::Halfblocks => ImageBackend::HalfBlocks,
120    }
121}
122
123/// What the app knows of the terminal, shared by every Reports window.
124#[derive(Default)]
125pub struct TerminalState {
126    env: Option<TerminalEnv>,
127    backend_override: Option<String>,
128}
129
130impl TerminalState {
131    #[must_use]
132    pub fn env(&self) -> Option<TerminalEnv> {
133        self.env
134    }
135
136    #[must_use]
137    pub fn backend_override(&self) -> Option<&str> {
138        self.backend_override.as_deref()
139    }
140
141    /// Adopts the terminal's geometry and returns the one it replaces.
142    pub fn replace(&mut self, env: TerminalEnv) -> Option<TerminalEnv> {
143        self.env.replace(env)
144    }
145
146    /// Keeps the override a current reply holds.
147    pub fn set_override(&mut self, value: Option<String>) {
148        self.backend_override = value;
149    }
150}
151
152pub 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
161impl ChartPane {
162    #[must_use]
163    pub fn new() -> Self {
164        Self {
165            shown: false,
166            seq: Seq::default(),
167            override_seq: Seq::default(),
168            state: ChartState::Loading,
169        }
170    }
171
172    #[must_use]
173    pub fn shown(&self) -> bool {
174        self.shown
175    }
176
177    pub fn toggle(&mut self) {
178        self.shown = !self.shown;
179    }
180
181    /// Start a read of the backend override and return its number.
182    pub fn begin_override(&mut self) -> u64 {
183        self.override_seq.advance()
184    }
185
186    /// Whether a reply of read `seq` is the pane's current one.
187    #[must_use]
188    pub fn awaits_override(&self, seq: u64) -> bool {
189        self.override_seq.awaits(seq)
190    }
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    pub fn on_env(&mut self, previous: Option<TerminalEnv>, env: TerminalEnv) -> bool {
195        let Some(previous) = previous else {
196            return true;
197        };
198        if previous.screen != env.screen || previous.cell_pixels != env.cell_pixels {
199            return true;
200        }
201        if previous.backend != env.backend {
202            self.redraw_kept(env);
203        }
204        false
205    }
206
207    fn redraw_kept(&mut self, env: TerminalEnv) {
208        if let ChartState::Ready(picture) = std::mem::replace(&mut self.state, ChartState::Loading)
209        {
210            self.state = match Picture::new(picture.png, picture.cells, env, picture.image_id) {
211                Ok(picture) => ChartState::Ready(picture),
212                Err(reason) => ChartState::Failed(reason),
213            };
214        }
215    }
216
217    /// The `report-chart` call for a pane of `cells` on `env`.
218    #[must_use]
219    pub fn call(
220        form: &Form,
221        values: &FormValues,
222        env: TerminalEnv,
223        cells: Size,
224        theme: &Theme,
225    ) -> String {
226        let (size, text_px) = env.fit(cells);
227        let request = ChartRequest {
228            kind: "bar",
229            format: ChartFormat::Png,
230            size,
231            look: look(text_px, theme),
232        };
233        chart_call(form, values, &request)
234    }
235
236    /// Start a request and return its number.
237    pub fn begin(&mut self) -> u64 {
238        self.state = ChartState::Loading;
239        self.seq.advance()
240    }
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    pub fn accept(
248        &mut self,
249        seq: u64,
250        cells: Size,
251        env: Option<TerminalEnv>,
252        window: WindowId,
253        wire: &str,
254    ) {
255        if !self.seq.awaits(seq) {
256            return;
257        }
258        self.state = match Self::decode(cells, env, kitty_image_id(window), wire) {
259            Ok(picture) => ChartState::Ready(picture),
260            Err(reason) => ChartState::Failed(reason),
261        };
262    }
263
264    fn decode(
265        cells: Size,
266        env: Option<TerminalEnv>,
267        image_id: u32,
268        wire: &str,
269    ) -> Result<Picture, String> {
270        let Some(env) = env else {
271            return Err("the terminal size is not known".to_string());
272        };
273        let png = match parse_wire(wire).map_err(|err| err.to_string())? {
274            WireValue::Value(Value::String(literal)) => {
275                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        Picture::new(png, cells, env, image_id)
280    }
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    pub fn forget_kitty(&mut self, env: Option<TerminalEnv>) -> Option<u32> {
285        let id = self.kitty_id()?;
286        if let Some(env) = env {
287            self.redraw_kept(env);
288        }
289        Some(id)
290    }
291
292    /// The kitty image the pane has transmitted, if it shows one.
293    #[must_use]
294    pub fn kitty_id(&self) -> Option<u32> {
295        match &self.state {
296            ChartState::Ready(picture) if picture.backend == ChartBackend::Kitty => {
297                Some(picture.image_id)
298            }
299            _ => None,
300        }
301    }
302
303    /// Draw the pane; a kitty image outside the active window stays undrawn so its one-cell kitty transmit is not lost.
304    pub fn draw(&self, buf: &mut Buffer, inner: Rect, ctx: &DrawCtx) {
305        match &self.state {
306            ChartState::Loading => Paragraph::new("Loading chart...").render(inner, buf),
307            ChartState::Failed(reason) => {
308                let message =
309                    Paragraph::new(format!("[error] {reason}")).wrap(Wrap { trim: false });
310                message.render(inner, buf);
311            }
312            ChartState::Ready(picture)
313                if ctx.frame.mode == tvui::FrameMode::Active
314                    || picture.backend != ChartBackend::Kitty =>
315            {
316                picture.image.render(inner, buf, ctx.theme.bg(Role::Panel));
317            }
318            ChartState::Ready(_) => {}
319        }
320    }
321}
322
323impl Default for ChartPane {
324    fn default() -> Self {
325        Self::new()
326    }
327}
328
329#[cfg(test)]
330mod tests;