1
//! The Reports tab's chart: `g` toggles it, the PNG is fetched at the pane's size.
2

            
3
use crate::tabs::nms_eval::double::Sent;
4
use crate::test_support::{ctrl, key, press};
5
use cli_core::report_form::{ChartRequest, chart_call};
6
use forms::FormValues;
7
use image::{ImageBuffer, ImageFormat, Rgba};
8
use ratatui::Terminal;
9
use ratatui::backend::TestBackend;
10
use ratatui::layout::Size;
11
use ratatui::style::Color;
12
use rpc::chart::{ChartBackend, ChartFormat, ChartLook};
13
use scripting::nomiscript::{Value, format_value};
14
use tvui::Role;
15

            
16
use crate::app::App;
17
use crate::draw::draw;
18
use crate::event::{Intent, apply};
19
use crate::route::RouteCtx;
20
use crate::tabs::reports::ReportKind;
21
use crate::tabs::reports::chart::TerminalEnv;
22
use crate::view::Tab;
23
use ratatui::crossterm::event::KeyCode;
24

            
25
pub(super) const EMPTY: &str = r#"(:id 1 :value "()")"#;
26
const CELL: (u16, u16) = (10, 20);
27

            
28
105
pub(super) fn env(width: u16, height: u16, backend: ChartBackend) -> TerminalEnv {
29
105
    TerminalEnv {
30
105
        screen: Size::new(width, height),
31
105
        cell_pixels: CELL,
32
105
        backend,
33
105
    }
34
105
}
35

            
36
63
fn filter() -> FormValues {
37
63
    let mut values = FormValues::default();
38
63
    values.set("filter", "x");
39
63
    values
40
63
}
41

            
42
/// An app showing a loaded balance table on a screen of the given size.
43
53
pub(super) fn with_table(width: u16, height: u16, backend: ChartBackend) -> (App, Sent) {
44
53
    let mut app = crate::test_support::app();
45
53
    let sent = app.attach_echo();
46
53
    app.switch_tab(Tab::Reports);
47
53
    app.sync_terminal(env(width, height, backend));
48
53
    app.submit_report(
49
53
        app.window_of(crate::view::ViewId::Reports),
50
53
        ReportKind::Balance,
51
53
        &filter(),
52
53
    );
53
53
    let run = pending(&app, |ctx| matches!(ctx, RouteCtx::Reports { .. }))[0];
54
53
    app.route_reply(run, EMPTY);
55
53
    (app, sent)
56
53
}
57

            
58
309
pub(super) fn pending(app: &App, wanted: impl Fn(&RouteCtx) -> bool) -> Vec<i64> {
59
309
    let mut ids: Vec<i64> = app
60
309
        .pending_routes
61
309
        .iter()
62
355
        .filter(|(_, route)| wanted(&route.ctx))
63
319
        .map(|(id, _)| *id)
64
        .collect();
65
309
    ids.sort_unstable();
66
309
    ids
67
309
}
68

            
69
74
pub(super) fn chart_requests(app: &App) -> Vec<i64> {
70
119
    pending(app, |ctx| matches!(ctx, RouteCtx::ReportChart { .. }))
71
74
}
72

            
73
31
pub(super) fn stripes(width: u32, height: u32) -> Vec<u8> {
74
3926400
    let image = ImageBuffer::from_fn(width, height, |_, y| {
75
3926400
        if y / 10 % 2 == 0 {
76
1963200
            Rgba([255u8, 0, 0, 255])
77
        } else {
78
1963200
            Rgba([0u8, 0, 255, 255])
79
        }
80
3926400
    });
81
31
    let mut bytes = Vec::new();
82
31
    image
83
31
        .write_to(&mut std::io::Cursor::new(&mut bytes), ImageFormat::Png)
84
31
        .expect("png encodes");
85
31
    bytes
86
31
}
87

            
88
33
fn quoted(literal: &str) -> String {
89
33
    literal.replace('\\', "\\\\").replace('"', "\\\"")
90
33
}
91

            
92
33
pub(super) fn png_wire(id: i64, png: Vec<u8>) -> String {
93
33
    let literal = format_value(&Value::Bytes(png));
94
33
    format!("(:id {id} :value \"{}\")", quoted(&literal))
95
33
}
96

            
97
46
pub(super) fn rendered(app: &App, width: u16, height: u16) -> Terminal<TestBackend> {
98
46
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
99
46
    terminal
100
46
        .draw(|frame| draw(frame, app, &mut crate::hits::Hits::default()))
101
46
        .expect("draws");
102
46
    terminal
103
46
}
104

            
105
38
pub(super) fn text(terminal: &Terminal<TestBackend>) -> String {
106
38
    terminal
107
38
        .backend()
108
38
        .buffer()
109
38
        .content()
110
38
        .iter()
111
36840
        .map(|cell| cell.symbol())
112
        .collect()
113
38
}
114

            
115
26
pub(super) async fn echoed(app: &mut App, sent: &Sent) -> String {
116
26
    tokio::task::yield_now().await;
117
26
    app.drain_eval();
118
26
    sent.frames().join("\n")
119
26
}
120

            
121
pub(super) const NO_OVERRIDE: &str = r#"(:id 1 :value "(:config-value nil)")"#;
122

            
123
52
pub(super) fn overrides(app: &App) -> Vec<i64> {
124
54
    pending(app, |ctx| matches!(ctx, RouteCtx::ChartOverride { .. }))
125
52
}
126

            
127
/// Presses `g` and answers the backend override read with no override.
128
44
pub(super) fn show(app: &mut App) {
129
44
    press(app, key(KeyCode::Char('g')));
130
44
    let [id] = overrides(app)[..] else {
131
        panic!("one override read");
132
    };
133
44
    app.route_reply(id, NO_OVERRIDE);
134
44
}
135

            
136
8
pub(super) fn call_for(width: u32, height: u32) -> String {
137
8
    call_with_text(width, height, 14)
138
8
}
139

            
140
10
pub(super) fn call_with_text(width: u32, height: u32, text_px: u32) -> String {
141
10
    let theme = crate::test_support::app().theme;
142
10
    let request = ChartRequest {
143
10
        kind: "bar",
144
10
        format: ChartFormat::Png,
145
10
        size: (width, height),
146
10
        look: ChartLook {
147
10
            text_px,
148
10
            background: Some(theme.bg_rgb(Role::Panel)),
149
10
        },
150
10
    };
151
10
    chart_call(ReportKind::Balance.descriptor(), &filter(), &request)
152
10
}
153

            
154
#[tokio::test]
155
1
async fn g_without_a_report_says_so() {
156
1
    let mut app = crate::test_support::app();
157
1
    app.switch_tab(Tab::Reports);
158
1
    press(&mut app, key(KeyCode::Char('g')));
159
1
    assert_eq!(app.status, "no report to chart");
160
1
    assert!(!app.reports().chart.shown());
161
1
}
162

            
163
#[tokio::test]
164
1
async fn g_fetches_the_chart_at_the_panes_pixel_size() {
165
1
    let (mut app, sent) = with_table(40, 20, ChartBackend::Halfblocks);
166
1
    show(&mut app);
167
1
    assert_eq!(chart_requests(&app).len(), 1);
168
    // 40x20 screen: an 18-row body, 38x16 cells inside the border.
169
1
    assert!(echoed(&mut app, &sent).await.contains(&call_for(380, 320)));
170
1
}
171

            
172
#[tokio::test]
173
1
async fn the_pixel_size_is_clamped_to_the_renderer_limit() {
174
1
    let (mut app, sent) = with_table(400, 200, ChartBackend::Halfblocks);
175
1
    show(&mut app);
176
1
    let echoed = echoed(&mut app, &sent).await;
177
1
    assert!(echoed.contains(&call_with_text(2048, 2017, 7)), "{echoed}");
178
1
}
179

            
180
#[tokio::test]
181
1
async fn g_twice_restores_the_exact_table() {
182
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Halfblocks);
183
1
    let table = rendered(&app, 40, 20);
184
1
    show(&mut app);
185
1
    let [id] = chart_requests(&app)[..] else {
186
        panic!("one chart request");
187
    };
188
1
    app.route_reply(id, &png_wire(id, stripes(380, 320)));
189
1
    assert_ne!(
190
1
        rendered(&app, 40, 20).backend().buffer(),
191
1
        table.backend().buffer()
192
    );
193
1
    press(&mut app, key(KeyCode::Char('g')));
194
1
    assert_eq!(
195
1
        rendered(&app, 40, 20).backend().buffer(),
196
1
        table.backend().buffer()
197
1
    );
198
1
}
199

            
200
#[tokio::test]
201
1
async fn halfblocks_fill_every_cell_of_the_pane() {
202
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Halfblocks);
203
1
    show(&mut app);
204
1
    let [id] = chart_requests(&app)[..] else {
205
        panic!("one chart request");
206
    };
207
1
    app.route_reply(id, &png_wire(id, stripes(380, 320)));
208
1
    let terminal = rendered(&app, 40, 20);
209
1
    let buffer = terminal.backend().buffer();
210
1
    for y in 2..18 {
211
16
        for x in 1..39 {
212
608
            let cell = &buffer[(x, y)];
213
608
            assert_eq!(cell.symbol(), "â–€", "({x}, {y})");
214
608
            assert!(matches!(cell.fg, Color::Rgb(..)), "({x}, {y})");
215
1
        }
216
1
    }
217
1
}
218

            
219
const MARK: Rgba<u8> = Rgba([255, 0, 0, 255]);
220

            
221
1
fn clear_png(width: u32, height: u32) -> Vec<u8> {
222
1
    let mut image = ImageBuffer::from_pixel(width, height, Rgba([9u8, 9, 9, 0]));
223
400
    for (x, y) in (0..20).flat_map(|x| (0..20).map(move |y| (x, y))) {
224
400
        image.put_pixel(x, y, MARK);
225
    }
226
1
    let mut bytes = Vec::new();
227
1
    image
228
1
        .write_to(&mut std::io::Cursor::new(&mut bytes), ImageFormat::Png)
229
1
        .expect("png encodes");
230
1
    bytes
231
1
}
232

            
233
#[tokio::test]
234
1
async fn transparent_chart_cells_show_the_panel_background() {
235
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Halfblocks);
236
1
    show(&mut app);
237
1
    let [id] = chart_requests(&app)[..] else {
238
        panic!("one chart request");
239
    };
240
1
    app.route_reply(id, &png_wire(id, clear_png(380, 320)));
241
1
    let terminal = rendered(&app, 40, 20);
242
1
    let buffer = terminal.backend().buffer();
243
1
    let panel = app.theme.bg(Role::Panel);
244
    // The opaque top-left block proves the chart was drawn over the panel fill.
245
1
    assert_eq!(buffer[(1, 2)].fg, Color::Rgb(255, 0, 0));
246
1
    for y in 2..18 {
247
16
        for x in 1..39 {
248
608
            if !(y == 2 && (1..3).contains(&x)) {
249
606
                assert_eq!(buffer[(x, y)].bg, panel, "({x}, {y})");
250
2
            }
251
1
        }
252
1
    }
253
1
}
254

            
255
#[tokio::test]
256
1
async fn kitty_writes_its_sequence_and_placeholders_into_the_buffer() {
257
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Kitty);
258
1
    show(&mut app);
259
1
    let [id] = chart_requests(&app)[..] else {
260
        panic!("one chart request");
261
    };
262
1
    app.route_reply(id, &png_wire(id, stripes(380, 320)));
263
1
    let terminal = rendered(&app, 40, 20);
264
1
    let buffer = terminal.backend().buffer();
265
1
    assert!(buffer[(1, 2)].symbol().contains("\x1b_G"));
266
1
    for (x, y) in [(1, 2), (38, 2), (1, 17), (38, 17)] {
267
4
        assert!(buffer[(x, y)].symbol().contains('\u{10EEEE}'), "({x}, {y})");
268
    }
269
1
    let again = rendered(&app, 40, 20);
270
1
    assert!(
271
1
        again.backend().buffer()[(38, 17)]
272
1
            .symbol()
273
1
            .contains('\u{10EEEE}')
274
1
    );
275
1
}
276

            
277
#[tokio::test]
278
1
async fn a_stale_reply_is_dropped() {
279
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Halfblocks);
280
1
    show(&mut app);
281
1
    let [old] = chart_requests(&app)[..] else {
282
        panic!("one chart request");
283
    };
284
1
    press(&mut app, key(KeyCode::Char('g')));
285
1
    show(&mut app);
286
1
    let [_, new] = chart_requests(&app)[..] else {
287
        panic!("two chart requests");
288
    };
289
1
    app.route_reply(old, &png_wire(old, stripes(380, 320)));
290
1
    assert!(text(&rendered(&app, 40, 20)).contains("Loading chart..."));
291
1
    app.route_reply(new, &png_wire(new, stripes(380, 320)));
292
1
    assert!(!text(&rendered(&app, 40, 20)).contains("Loading chart..."));
293
1
}
294

            
295
#[tokio::test]
296
1
async fn a_chart_shown_again_starts_from_loading_not_the_old_picture() {
297
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Halfblocks);
298
1
    show(&mut app);
299
1
    let [id] = chart_requests(&app)[..] else {
300
        panic!("one chart request");
301
    };
302
1
    app.route_reply(id, &png_wire(id, stripes(380, 320)));
303
1
    press(&mut app, key(KeyCode::Char('g')));
304
1
    press(&mut app, ctrl(KeyCode::Char('r')));
305
1
    let run = pending(&app, |ctx| matches!(ctx, RouteCtx::Reports { .. }))[0];
306
1
    app.route_reply(run, EMPTY);
307
1
    show(&mut app);
308
1
    assert!(text(&rendered(&app, 40, 20)).contains("Loading chart..."));
309
1
}
310

            
311
#[tokio::test]
312
1
async fn a_modal_over_the_pane_keeps_the_kitty_transmit_for_later() {
313
1
    let (mut app, _) = with_table(40, 20, ChartBackend::Kitty);
314
1
    show(&mut app);
315
1
    let [id] = chart_requests(&app)[..] else {
316
        panic!("one chart request");
317
    };
318
1
    app.route_reply(id, &png_wire(id, stripes(380, 320)));
319
1
    crate::test_support::open_overlay(&mut app);
320
1
    let covered = text(&rendered(&app, 40, 20));
321
1
    assert!(!covered.contains("\x1b_G"));
322
1
    apply(&mut app, Intent::CloseTopmost);
323
1
    let uncovered = text(&rendered(&app, 40, 20));
324
1
    assert!(uncovered.contains("\x1b_Gq=2,i="));
325
1
    assert!(uncovered.contains("o=z"));
326
1
}
327

            
328
#[tokio::test]
329
1
async fn a_rejected_chart_shows_its_error_as_text() {
330
1
    let (mut app, _) = with_table(60, 20, ChartBackend::Halfblocks);
331
1
    show(&mut app);
332
1
    let [id] = chart_requests(&app)[..] else {
333
        panic!("one chart request");
334
    };
335
1
    let error = r#"(:id 1 :error (:code args :message "bad kind"))"#;
336
1
    app.route_reply(id, error);
337
1
    let shown = text(&rendered(&app, 60, 20));
338
1
    assert!(shown.contains("[error] "), "{shown}");
339
1
    assert!(shown.contains("bad kind"), "{shown}");
340
1
}
341

            
342
#[tokio::test]
343
1
async fn a_reply_that_is_not_a_png_shows_as_text() {
344
1
    let (mut app, _) = with_table(60, 20, ChartBackend::Halfblocks);
345
1
    show(&mut app);
346
1
    let [id] = chart_requests(&app)[..] else {
347
        panic!("one chart request");
348
    };
349
1
    app.route_reply(id, &png_wire(id, b"not a png".to_vec()));
350
1
    assert!(text(&rendered(&app, 60, 20)).contains("the chart is not a PNG"));
351
1
}
352

            
353
#[tokio::test]
354
1
async fn a_reply_of_the_wrong_type_shows_as_text() {
355
1
    let (mut app, _) = with_table(60, 20, ChartBackend::Halfblocks);
356
1
    show(&mut app);
357
1
    let [id] = chart_requests(&app)[..] else {
358
        panic!("one chart request");
359
    };
360
1
    app.route_reply(id, r#"(:id 1 :value "(1 2)")"#);
361
1
    assert!(text(&rendered(&app, 60, 20)).contains("the chart reply is not a PNG"));
362
1
}