Lines
95.51 %
Functions
100 %
Branches
//! The Reports tab's chart: `g` toggles it, the PNG is fetched at the pane's size.
use crate::tabs::nms_eval::double::Sent;
use crate::test_support::{ctrl, key, press};
use cli_core::report_form::{ChartRequest, chart_call};
use forms::FormValues;
use image::{ImageBuffer, ImageFormat, Rgba};
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::layout::Size;
use ratatui::style::Color;
use rpc::chart::{ChartBackend, ChartFormat, ChartLook};
use scripting::nomiscript::{Value, format_value};
use tvui::Role;
use crate::app::App;
use crate::draw::draw;
use crate::event::{Intent, apply};
use crate::route::RouteCtx;
use crate::tabs::reports::ReportKind;
use crate::tabs::reports::chart::TerminalEnv;
use crate::view::Tab;
use ratatui::crossterm::event::KeyCode;
pub(super) const EMPTY: &str = r#"(:id 1 :value "()")"#;
const CELL: (u16, u16) = (10, 20);
pub(super) fn env(width: u16, height: u16, backend: ChartBackend) -> TerminalEnv {
TerminalEnv {
screen: Size::new(width, height),
cell_pixels: CELL,
backend,
}
fn filter() -> FormValues {
let mut values = FormValues::default();
values.set("filter", "x");
values
/// An app showing a loaded balance table on a screen of the given size.
pub(super) fn with_table(width: u16, height: u16, backend: ChartBackend) -> (App, Sent) {
let mut app = crate::test_support::app();
let sent = app.attach_echo();
app.switch_tab(Tab::Reports);
app.sync_terminal(env(width, height, backend));
app.submit_report(
app.window_of(crate::view::ViewId::Reports),
ReportKind::Balance,
&filter(),
);
let run = pending(&app, |ctx| matches!(ctx, RouteCtx::Reports { .. }))[0];
app.route_reply(run, EMPTY);
(app, sent)
pub(super) fn pending(app: &App, wanted: impl Fn(&RouteCtx) -> bool) -> Vec<i64> {
let mut ids: Vec<i64> = app
.pending_routes
.iter()
.filter(|(_, route)| wanted(&route.ctx))
.map(|(id, _)| *id)
.collect();
ids.sort_unstable();
ids
pub(super) fn chart_requests(app: &App) -> Vec<i64> {
pending(app, |ctx| matches!(ctx, RouteCtx::ReportChart { .. }))
pub(super) fn stripes(width: u32, height: u32) -> Vec<u8> {
let image = ImageBuffer::from_fn(width, height, |_, y| {
if y / 10 % 2 == 0 {
Rgba([255u8, 0, 0, 255])
} else {
Rgba([0u8, 0, 255, 255])
});
let mut bytes = Vec::new();
image
.write_to(&mut std::io::Cursor::new(&mut bytes), ImageFormat::Png)
.expect("png encodes");
bytes
fn quoted(literal: &str) -> String {
literal.replace('\\', "\\\\").replace('"', "\\\"")
pub(super) fn png_wire(id: i64, png: Vec<u8>) -> String {
let literal = format_value(&Value::Bytes(png));
format!("(:id {id} :value \"{}\")", quoted(&literal))
pub(super) fn rendered(app: &App, width: u16, height: u16) -> Terminal<TestBackend> {
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
terminal
.draw(|frame| draw(frame, app, &mut crate::hits::Hits::default()))
.expect("draws");
pub(super) fn text(terminal: &Terminal<TestBackend>) -> String {
.backend()
.buffer()
.content()
.map(|cell| cell.symbol())
.collect()
pub(super) async fn echoed(app: &mut App, sent: &Sent) -> String {
tokio::task::yield_now().await;
app.drain_eval();
sent.frames().join("\n")
pub(super) const NO_OVERRIDE: &str = r#"(:id 1 :value "(:config-value nil)")"#;
pub(super) fn overrides(app: &App) -> Vec<i64> {
pending(app, |ctx| matches!(ctx, RouteCtx::ChartOverride { .. }))
/// Presses `g` and answers the backend override read with no override.
pub(super) fn show(app: &mut App) {
press(app, key(KeyCode::Char('g')));
let [id] = overrides(app)[..] else {
panic!("one override read");
};
app.route_reply(id, NO_OVERRIDE);
pub(super) fn call_for(width: u32, height: u32) -> String {
call_with_text(width, height, 14)
pub(super) fn call_with_text(width: u32, height: u32, text_px: u32) -> String {
let theme = crate::test_support::app().theme;
let request = ChartRequest {
kind: "bar",
format: ChartFormat::Png,
size: (width, height),
look: ChartLook {
text_px,
background: Some(theme.bg_rgb(Role::Panel)),
},
chart_call(ReportKind::Balance.descriptor(), &filter(), &request)
#[tokio::test]
async fn g_without_a_report_says_so() {
press(&mut app, key(KeyCode::Char('g')));
assert_eq!(app.status, "no report to chart");
assert!(!app.reports().chart.shown());
async fn g_fetches_the_chart_at_the_panes_pixel_size() {
let (mut app, sent) = with_table(40, 20, ChartBackend::Halfblocks);
show(&mut app);
assert_eq!(chart_requests(&app).len(), 1);
// 40x20 screen: an 18-row body, 38x16 cells inside the border.
assert!(echoed(&mut app, &sent).await.contains(&call_for(380, 320)));
async fn the_pixel_size_is_clamped_to_the_renderer_limit() {
let (mut app, sent) = with_table(400, 200, ChartBackend::Halfblocks);
let echoed = echoed(&mut app, &sent).await;
assert!(echoed.contains(&call_with_text(2048, 2017, 7)), "{echoed}");
async fn g_twice_restores_the_exact_table() {
let (mut app, _) = with_table(40, 20, ChartBackend::Halfblocks);
let table = rendered(&app, 40, 20);
let [id] = chart_requests(&app)[..] else {
panic!("one chart request");
app.route_reply(id, &png_wire(id, stripes(380, 320)));
assert_ne!(
rendered(&app, 40, 20).backend().buffer(),
table.backend().buffer()
assert_eq!(
async fn halfblocks_fill_every_cell_of_the_pane() {
let terminal = rendered(&app, 40, 20);
let buffer = terminal.backend().buffer();
for y in 2..18 {
for x in 1..39 {
let cell = &buffer[(x, y)];
assert_eq!(cell.symbol(), "â–€", "({x}, {y})");
assert!(matches!(cell.fg, Color::Rgb(..)), "({x}, {y})");
const MARK: Rgba<u8> = Rgba([255, 0, 0, 255]);
fn clear_png(width: u32, height: u32) -> Vec<u8> {
let mut image = ImageBuffer::from_pixel(width, height, Rgba([9u8, 9, 9, 0]));
for (x, y) in (0..20).flat_map(|x| (0..20).map(move |y| (x, y))) {
image.put_pixel(x, y, MARK);
async fn transparent_chart_cells_show_the_panel_background() {
app.route_reply(id, &png_wire(id, clear_png(380, 320)));
let panel = app.theme.bg(Role::Panel);
// The opaque top-left block proves the chart was drawn over the panel fill.
assert_eq!(buffer[(1, 2)].fg, Color::Rgb(255, 0, 0));
if !(y == 2 && (1..3).contains(&x)) {
assert_eq!(buffer[(x, y)].bg, panel, "({x}, {y})");
async fn kitty_writes_its_sequence_and_placeholders_into_the_buffer() {
let (mut app, _) = with_table(40, 20, ChartBackend::Kitty);
assert!(buffer[(1, 2)].symbol().contains("\x1b_G"));
for (x, y) in [(1, 2), (38, 2), (1, 17), (38, 17)] {
assert!(buffer[(x, y)].symbol().contains('\u{10EEEE}'), "({x}, {y})");
let again = rendered(&app, 40, 20);
assert!(
again.backend().buffer()[(38, 17)]
.symbol()
.contains('\u{10EEEE}')
async fn a_stale_reply_is_dropped() {
let [old] = chart_requests(&app)[..] else {
let [_, new] = chart_requests(&app)[..] else {
panic!("two chart requests");
app.route_reply(old, &png_wire(old, stripes(380, 320)));
assert!(text(&rendered(&app, 40, 20)).contains("Loading chart..."));
app.route_reply(new, &png_wire(new, stripes(380, 320)));
assert!(!text(&rendered(&app, 40, 20)).contains("Loading chart..."));
async fn a_chart_shown_again_starts_from_loading_not_the_old_picture() {
press(&mut app, ctrl(KeyCode::Char('r')));
async fn a_modal_over_the_pane_keeps_the_kitty_transmit_for_later() {
crate::test_support::open_overlay(&mut app);
let covered = text(&rendered(&app, 40, 20));
assert!(!covered.contains("\x1b_G"));
apply(&mut app, Intent::CloseTopmost);
let uncovered = text(&rendered(&app, 40, 20));
assert!(uncovered.contains("\x1b_Gq=2,i="));
assert!(uncovered.contains("o=z"));
async fn a_rejected_chart_shows_its_error_as_text() {
let (mut app, _) = with_table(60, 20, ChartBackend::Halfblocks);
let error = r#"(:id 1 :error (:code args :message "bad kind"))"#;
app.route_reply(id, error);
let shown = text(&rendered(&app, 60, 20));
assert!(shown.contains("[error] "), "{shown}");
assert!(shown.contains("bad kind"), "{shown}");
async fn a_reply_that_is_not_a_png_shows_as_text() {
app.route_reply(id, &png_wire(id, b"not a png".to_vec()));
assert!(text(&rendered(&app, 60, 20)).contains("the chart is not a PNG"));
async fn a_reply_of_the_wrong_type_shows_as_text() {
app.route_reply(id, r#"(:id 1 :value "(1 2)")"#);
assert!(text(&rendered(&app, 60, 20)).contains("the chart reply is not a PNG"));