Lines
94.48 %
Functions
83.33 %
Branches
100 %
//! The Reports tab's chart pane: the picture of the shown report, fetched as a PNG.
use cli_core::render::{WireValue, parse_wire};
use cli_core::report_form::{ChartRequest, chart_call, png_from_literal};
use forms::{Form, FormValues};
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui::widgets::{Paragraph, Widget, Wrap};
use rpc::chart::{ChartBackend, ChartFormat, ChartLook, MAX_SIDE};
use scripting::nomiscript::Value;
use tvui::{Image, ImageBackend, ImageError, Role, Theme, inner};
use crate::tabs::seq::Seq;
use crate::view::DrawCtx;
use crate::window::WindowId;
/// The kitty image id of window 0; each window adds its own id, so charts never replace each other.
const KITTY_IMAGE_BASE: u32 = 0x4E_4F_4D;
/// The kitty image id of the chart of `window`.
#[must_use]
pub fn kitty_image_id(window: WindowId) -> u32 {
KITTY_IMAGE_BASE.saturating_add(window.0)
}
/// What the chart is drawn on: the screen, its cell size in pixels and the graphics protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TerminalEnv {
pub screen: Size,
pub cell_pixels: (u16, u16),
pub backend: ChartBackend,
/// The pane's size in cells: the area inside the frame of the window drawn at `window`.
pub fn pane_cells(window: Rect) -> Size {
inner(window).as_size()
/// The pixel height of a terminal glyph: about 70% of its cell, at least 8.
fn glyph_px(cell_h: u16) -> u32 {
((u32::from(cell_h) * 7 + 5) / 10).max(8)
impl TerminalEnv {
/// A pane of `cells` in pixels and the text height of a terminal glyph. Both shrink
/// together past the renderer's limit, so the picture keeps the pane's shape.
fn fit(self, cells: Size) -> ((u32, u32), u32) {
let (cell_w, cell_h) = self.cell_pixels;
let pane = |cells: u16, cell: u16| (u32::from(cells) * u32::from(cell)).max(1);
let (width, height, text) = (
pane(cells.width, cell_w),
pane(cells.height, cell_h),
glyph_px(cell_h),
);
let longest = u64::from(width.max(height));
let shrink = |side: u32| match longest > u64::from(MAX_SIDE) {
true => u32::try_from(u64::from(side) * u64::from(MAX_SIDE) / longest)
.unwrap_or(MAX_SIDE)
.max(1),
false => side,
};
((shrink(width), shrink(height)), shrink(text))
/// Text `text_px` high, on the colour of the pane.
fn look(text_px: u32, theme: &Theme) -> ChartLook {
ChartLook {
text_px,
background: Some(theme.bg_rgb(Role::Panel)),
/// The user config key that forces the chart's graphics protocol: `kitty` or `halfblocks`.
pub const BACKEND_KEY: &str = "tui-chart-backend";
enum ChartState {
Loading,
Ready(Picture),
Failed(String),
/// A drawn chart with the PNG it came from, so a new protocol redraws it without a fetch.
struct Picture {
png: Vec<u8>,
cells: Size,
backend: ChartBackend,
image_id: u32,
image: Image,
impl Picture {
fn new(png: Vec<u8>, cells: Size, env: TerminalEnv, image_id: u32) -> Result<Self, String> {
let backend = image_backend(env.backend, image_id);
let image =
Image::new(&png, backend, cells, env.cell_pixels).map_err(|err| chart_error(&err))?;
Ok(Self {
png,
cells,
backend: env.backend,
image_id,
image,
})
fn chart_error(err: &ImageError) -> String {
match err {
ImageError::NoRoom => "the chart pane has no room".to_string(),
ImageError::NotPng(err) => format!("the chart is not a PNG: {err}"),
ImageError::Protocol(err) => format!("the chart cannot be drawn: {err}"),
fn image_backend(backend: ChartBackend, image_id: u32) -> ImageBackend {
match backend {
ChartBackend::Kitty => ImageBackend::Kitty { id: image_id },
ChartBackend::Halfblocks => ImageBackend::HalfBlocks,
/// What the app knows of the terminal, shared by every Reports window.
#[derive(Default)]
pub struct TerminalState {
env: Option<TerminalEnv>,
backend_override: Option<String>,
impl TerminalState {
pub fn env(&self) -> Option<TerminalEnv> {
self.env
pub fn backend_override(&self) -> Option<&str> {
self.backend_override.as_deref()
/// Adopts the terminal's geometry and returns the one it replaces.
pub fn replace(&mut self, env: TerminalEnv) -> Option<TerminalEnv> {
self.env.replace(env)
/// Keeps the override a current reply holds.
pub fn set_override(&mut self, value: Option<String>) {
self.backend_override = value;
pub struct ChartPane {
shown: bool,
/// Counts chart requests; a reply of an older one is dropped.
seq: Seq,
/// Counts reads of [`BACKEND_KEY`]; a reply of an older one is dropped.
override_seq: Seq,
state: ChartState,
impl ChartPane {
pub fn new() -> Self {
Self {
shown: false,
seq: Seq::default(),
override_seq: Seq::default(),
state: ChartState::Loading,
pub fn shown(&self) -> bool {
self.shown
pub fn toggle(&mut self) {
self.shown = !self.shown;
/// Start a read of the backend override and return its number.
pub fn begin_override(&mut self) -> u64 {
self.override_seq.advance()
/// Whether a reply of read `seq` is the pane's current one.
pub fn awaits_override(&self, seq: u64) -> bool {
self.override_seq.awaits(seq)
/// Adopts a new terminal geometry; returns whether the chart must be fetched again.
/// A new protocol alone redraws the picture already held.
pub fn on_env(&mut self, previous: Option<TerminalEnv>, env: TerminalEnv) -> bool {
let Some(previous) = previous else {
return true;
if previous.screen != env.screen || previous.cell_pixels != env.cell_pixels {
if previous.backend != env.backend {
self.redraw_kept(env);
false
fn redraw_kept(&mut self, env: TerminalEnv) {
if let ChartState::Ready(picture) = std::mem::replace(&mut self.state, ChartState::Loading)
{
self.state = match Picture::new(picture.png, picture.cells, env, picture.image_id) {
Ok(picture) => ChartState::Ready(picture),
Err(reason) => ChartState::Failed(reason),
/// The `report-chart` call for a pane of `cells` on `env`.
pub fn call(
form: &Form,
values: &FormValues,
env: TerminalEnv,
theme: &Theme,
) -> String {
let (size, text_px) = env.fit(cells);
let request = ChartRequest {
kind: "bar",
format: ChartFormat::Png,
size,
look: look(text_px, theme),
chart_call(form, values, &request)
/// Start a request and return its number.
pub fn begin(&mut self) -> u64 {
self.state = ChartState::Loading;
self.seq.advance()
pub fn fail(&mut self, reason: &str) {
self.state = ChartState::Failed(reason.to_string());
/// Show the reply of request `seq`, drawn for a pane of `cells`.
pub fn accept(
&mut self,
seq: u64,
window: WindowId,
wire: &str,
) {
if !self.seq.awaits(seq) {
return;
self.state = match Self::decode(cells, env, kitty_image_id(window), wire) {
fn decode(
) -> Result<Picture, String> {
let Some(env) = env else {
return Err("the terminal size is not known".to_string());
let png = match parse_wire(wire).map_err(|err| err.to_string())? {
WireValue::Value(Value::String(literal)) => {
png_from_literal(&literal).map_err(|err| err.to_string())?
WireValue::Value(_) => return Err("the chart reply is not a PNG".to_string()),
Picture::new(png, cells, env, image_id)
/// Gives up the transmitted kitty image: the picture is rebuilt from its PNG so the next draw
/// transmits again. Returns the id the terminal must delete.
pub fn forget_kitty(&mut self, env: Option<TerminalEnv>) -> Option<u32> {
let id = self.kitty_id()?;
if let Some(env) = env {
Some(id)
/// The kitty image the pane has transmitted, if it shows one.
pub fn kitty_id(&self) -> Option<u32> {
match &self.state {
ChartState::Ready(picture) if picture.backend == ChartBackend::Kitty => {
Some(picture.image_id)
_ => None,
/// Draw the pane; a kitty image outside the active window stays undrawn so its one-cell kitty transmit is not lost.
pub fn draw(&self, buf: &mut Buffer, inner: Rect, ctx: &DrawCtx) {
ChartState::Loading => Paragraph::new("Loading chart...").render(inner, buf),
ChartState::Failed(reason) => {
let message =
Paragraph::new(format!("[error] {reason}")).wrap(Wrap { trim: false });
message.render(inner, buf);
ChartState::Ready(picture)
if ctx.frame.mode == tvui::FrameMode::Active
|| picture.backend != ChartBackend::Kitty =>
picture.image.render(inner, buf, ctx.theme.bg(Role::Panel));
ChartState::Ready(_) => {}
impl Default for ChartPane {
fn default() -> Self {
Self::new()
#[cfg(test)]
mod tests;