Lines
100 %
Functions
95.83 %
Branches
//! Kitty terminal graphics renderer.
//!
//! Renders a [`ChartSpec`] to an RGB bitmap via plotters, encodes it as
//! PNG via the `image` crate, then wraps the PNG in kitty's graphics
//! Application Programming Command (APC) escape sequence so the result
//! can be written directly to stdout inside a kitty-compatible terminal.
//! Protocol reference: <https://sw.kovidgoyal.net/kitty/graphics-protocol/>.
//! Key choices:
//! - `f=100` — the payload is PNG, not raw RGB. Lets the terminal
//! decode via libpng without us having to specify pixel dimensions.
//! - `a=T` — transmit and display immediately at the cursor.
//! - `m=1`/`m=0` — chunking. The protocol caps each APC chunk at 4096
//! base64 characters; any more gets silently dropped.
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use image::{ImageBuffer, Rgba};
use plotters::prelude::*;
use crate::draw::{NEUTRAL, draw_on};
use crate::layout::DEFAULT_TEXT_PX;
use crate::spec::ChartSpec;
/// Dimensions, in pixels, and look of the rendered chart.
#[derive(Debug, Clone, Copy)]
pub struct KittyOpts {
pub width_px: u32,
pub height_px: u32,
/// The text height every label size scales from.
pub text_px: u32,
/// The colour to draw on; `None` leaves the PNG transparent.
pub background: Option<[u8; 3]>,
}
impl Default for KittyOpts {
fn default() -> Self {
Self {
width_px: 640,
height_px: 400,
text_px: DEFAULT_TEXT_PX,
background: None,
/// The kitty graphics protocol caps a single APC chunk's base64 payload
/// at this many characters.
const KITTY_CHUNK_MAX: usize = 4096;
/// Render `spec` to an RGBA PNG byte vector: opaque over `opts.background`, or
/// transparent when there is none. Returns `None` on any drawing or encoding
/// failure; callers decide whether to substitute a text fallback.
#[must_use]
pub fn render_png(spec: &ChartSpec, opts: KittyOpts) -> Option<Vec<u8>> {
let (width, height) = (opts.width_px, opts.height_px);
let rgba = match opts.background {
Some(ground) => opaque(&render_on(spec, opts, ground)?),
None => unblend(
&render_on(spec, opts, [0xff; 3])?,
&render_on(spec, opts, [0x00; 3])?,
),
};
let rgba: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)?;
let mut png = Vec::new();
rgba.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.ok()?;
Some(png)
/// The chart drawn without a background over an RGB buffer pre-filled with
/// `ground`; plotters' bitmap backend has no alpha channel.
fn render_on(spec: &ChartSpec, opts: KittyOpts, ground: [u8; 3]) -> Option<Vec<u8>> {
let pixels = (width as usize).checked_mul(height as usize)?;
pixels.checked_mul(3)?;
let mut rgb: Vec<u8> = ground.repeat(pixels);
let drew = {
let root = BitMapBackend::with_buffer(&mut rgb, (width, height)).into_drawing_area();
draw_on(&root, spec, opts.text_px, ink(opts.background)).is_ok() && root.present().is_ok()
drew.then_some(rgb)
/// The grey that reads on any terminal when there is no background, else black or white
/// whichever contrasts with it.
fn ink(background: Option<[u8; 3]>) -> RGBColor {
match background {
None => NEUTRAL,
Some([r, g, b]) => {
let luma = (299 * u32::from(r) + 587 * u32::from(g) + 114 * u32::from(b)) / 1000;
match luma > 140 {
true => RGBColor(30, 30, 30),
false => RGBColor(235, 235, 235),
fn opaque(rgb: &[u8]) -> Vec<u8> {
let (pixels, _) = rgb.as_chunks::<3>();
pixels
.iter()
.flat_map(|[r, g, b]| [*r, *g, *b, u8::MAX])
.collect()
/// Recovers straight RGBA from the same drawing over white and over black:
/// a pixel of alpha `a` and colour `c` reads `a*c + (1-a)*ground` on each.
fn unblend(on_white: &[u8], on_black: &[u8]) -> Vec<u8> {
let (whites, _) = on_white.as_chunks::<3>();
let (blacks, _) = on_black.as_chunks::<3>();
whites
.zip(blacks)
.flat_map(|(white, black)| {
let spread: u32 = white
.zip(black)
.map(|(w, b)| u32::from(*w).saturating_sub(u32::from(*b)))
.sum();
let alpha = 255 - (spread / 3).min(255);
let channel = |b: &u8| match alpha {
0 => 0,
a => u8::try_from((u32::from(*b) * 255 + a / 2) / a).unwrap_or(u8::MAX),
let [r, g, b] = black.each_ref().map(channel);
[r, g, b, u8::try_from(alpha).unwrap_or(u8::MAX)]
})
/// Encode PNG bytes as one or more kitty APC graphics commands. The
/// chunks share an implicit image ID; the final chunk sets `m=0` to
/// tell the terminal to display.
pub fn encode_png_apc(png: &[u8]) -> String {
let encoded = BASE64.encode(png);
let mut out = String::with_capacity(encoded.len() + 64);
let chunks: Vec<&str> = encoded
.as_bytes()
.chunks(KITTY_CHUNK_MAX)
.map(|c| std::str::from_utf8(c).unwrap_or(""))
.collect();
if chunks.is_empty() {
return String::new();
for (i, chunk) in chunks.iter().enumerate() {
let first = i == 0;
let last = i + 1 == chunks.len();
let more = i32::from(!last);
if first {
out.push_str(&format!("\x1b_Gf=100,a=T,m={more};"));
} else {
out.push_str(&format!("\x1b_Gm={more};"));
out.push_str(chunk);
out.push_str("\x1b\\");
out
#[cfg(test)]
mod tests;