Skip to main content

plotting/
kitty.rs

1//! Kitty terminal graphics renderer.
2//!
3//! Renders a [`ChartSpec`] to an RGB bitmap via plotters, encodes it as
4//! PNG via the `image` crate, then wraps the PNG in kitty's graphics
5//! Application Programming Command (APC) escape sequence so the result
6//! can be written directly to stdout inside a kitty-compatible terminal.
7//!
8//! Protocol reference: <https://sw.kovidgoyal.net/kitty/graphics-protocol/>.
9//! Key choices:
10//!
11//! - `f=100` — the payload is PNG, not raw RGB. Lets the terminal
12//!   decode via libpng without us having to specify pixel dimensions.
13//! - `a=T` — transmit and display immediately at the cursor.
14//! - `m=1`/`m=0` — chunking. The protocol caps each APC chunk at 4096
15//!   base64 characters; any more gets silently dropped.
16
17use base64::Engine;
18use base64::engine::general_purpose::STANDARD as BASE64;
19use image::{ImageBuffer, Rgba};
20use plotters::prelude::*;
21
22use crate::draw::{NEUTRAL, draw_on};
23use crate::layout::DEFAULT_TEXT_PX;
24use crate::spec::ChartSpec;
25
26/// Dimensions, in pixels, and look of the rendered chart.
27#[derive(Debug, Clone, Copy)]
28pub struct KittyOpts {
29    pub width_px: u32,
30    pub height_px: u32,
31    /// The text height every label size scales from.
32    pub text_px: u32,
33    /// The colour to draw on; `None` leaves the PNG transparent.
34    pub background: Option<[u8; 3]>,
35}
36
37impl Default for KittyOpts {
38    fn default() -> Self {
39        Self {
40            width_px: 640,
41            height_px: 400,
42            text_px: DEFAULT_TEXT_PX,
43            background: None,
44        }
45    }
46}
47
48/// The kitty graphics protocol caps a single APC chunk's base64 payload
49/// at this many characters.
50const KITTY_CHUNK_MAX: usize = 4096;
51
52/// Render `spec` to an RGBA PNG byte vector: opaque over `opts.background`, or
53/// transparent when there is none. Returns `None` on any drawing or encoding
54/// failure; callers decide whether to substitute a text fallback.
55#[must_use]
56pub fn render_png(spec: &ChartSpec, opts: KittyOpts) -> Option<Vec<u8>> {
57    let (width, height) = (opts.width_px, opts.height_px);
58    let rgba = match opts.background {
59        Some(ground) => opaque(&render_on(spec, opts, ground)?),
60        None => unblend(
61            &render_on(spec, opts, [0xff; 3])?,
62            &render_on(spec, opts, [0x00; 3])?,
63        ),
64    };
65    let rgba: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)?;
66    let mut png = Vec::new();
67    rgba.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
68        .ok()?;
69    Some(png)
70}
71
72/// The chart drawn without a background over an RGB buffer pre-filled with
73/// `ground`; plotters' bitmap backend has no alpha channel.
74fn render_on(spec: &ChartSpec, opts: KittyOpts, ground: [u8; 3]) -> Option<Vec<u8>> {
75    let (width, height) = (opts.width_px, opts.height_px);
76    let pixels = (width as usize).checked_mul(height as usize)?;
77    pixels.checked_mul(3)?;
78    let mut rgb: Vec<u8> = ground.repeat(pixels);
79    let drew = {
80        let root = BitMapBackend::with_buffer(&mut rgb, (width, height)).into_drawing_area();
81        draw_on(&root, spec, opts.text_px, ink(opts.background)).is_ok() && root.present().is_ok()
82    };
83    drew.then_some(rgb)
84}
85
86/// The grey that reads on any terminal when there is no background, else black or white
87/// whichever contrasts with it.
88fn ink(background: Option<[u8; 3]>) -> RGBColor {
89    match background {
90        None => NEUTRAL,
91        Some([r, g, b]) => {
92            let luma = (299 * u32::from(r) + 587 * u32::from(g) + 114 * u32::from(b)) / 1000;
93            match luma > 140 {
94                true => RGBColor(30, 30, 30),
95                false => RGBColor(235, 235, 235),
96            }
97        }
98    }
99}
100
101fn opaque(rgb: &[u8]) -> Vec<u8> {
102    let (pixels, _) = rgb.as_chunks::<3>();
103    pixels
104        .iter()
105        .flat_map(|[r, g, b]| [*r, *g, *b, u8::MAX])
106        .collect()
107}
108
109/// Recovers straight RGBA from the same drawing over white and over black:
110/// a pixel of alpha `a` and colour `c` reads `a*c + (1-a)*ground` on each.
111fn unblend(on_white: &[u8], on_black: &[u8]) -> Vec<u8> {
112    let (whites, _) = on_white.as_chunks::<3>();
113    let (blacks, _) = on_black.as_chunks::<3>();
114    whites
115        .iter()
116        .zip(blacks)
117        .flat_map(|(white, black)| {
118            let spread: u32 = white
119                .iter()
120                .zip(black)
121                .map(|(w, b)| u32::from(*w).saturating_sub(u32::from(*b)))
122                .sum();
123            let alpha = 255 - (spread / 3).min(255);
124            let channel = |b: &u8| match alpha {
125                0 => 0,
126                a => u8::try_from((u32::from(*b) * 255 + a / 2) / a).unwrap_or(u8::MAX),
127            };
128            let [r, g, b] = black.each_ref().map(channel);
129            [r, g, b, u8::try_from(alpha).unwrap_or(u8::MAX)]
130        })
131        .collect()
132}
133
134/// Encode PNG bytes as one or more kitty APC graphics commands. The
135/// chunks share an implicit image ID; the final chunk sets `m=0` to
136/// tell the terminal to display.
137#[must_use]
138pub fn encode_png_apc(png: &[u8]) -> String {
139    let encoded = BASE64.encode(png);
140    let mut out = String::with_capacity(encoded.len() + 64);
141    let chunks: Vec<&str> = encoded
142        .as_bytes()
143        .chunks(KITTY_CHUNK_MAX)
144        .map(|c| std::str::from_utf8(c).unwrap_or(""))
145        .collect();
146
147    if chunks.is_empty() {
148        return String::new();
149    }
150
151    for (i, chunk) in chunks.iter().enumerate() {
152        let first = i == 0;
153        let last = i + 1 == chunks.len();
154        let more = i32::from(!last);
155        if first {
156            out.push_str(&format!("\x1b_Gf=100,a=T,m={more};"));
157        } else {
158            out.push_str(&format!("\x1b_Gm={more};"));
159        }
160        out.push_str(chunk);
161        out.push_str("\x1b\\");
162    }
163    out
164}
165
166#[cfg(test)]
167mod tests;