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

            
17
use base64::Engine;
18
use base64::engine::general_purpose::STANDARD as BASE64;
19
use image::{ImageBuffer, Rgba};
20
use plotters::prelude::*;
21

            
22
use crate::draw::{NEUTRAL, draw_on};
23
use crate::layout::DEFAULT_TEXT_PX;
24
use crate::spec::ChartSpec;
25

            
26
/// Dimensions, in pixels, and look of the rendered chart.
27
#[derive(Debug, Clone, Copy)]
28
pub 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

            
37
impl Default for KittyOpts {
38
8
    fn default() -> Self {
39
8
        Self {
40
8
            width_px: 640,
41
8
            height_px: 400,
42
8
            text_px: DEFAULT_TEXT_PX,
43
8
            background: None,
44
8
        }
45
8
    }
46
}
47

            
48
/// The kitty graphics protocol caps a single APC chunk's base64 payload
49
/// at this many characters.
50
const 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]
56
2664
pub fn render_png(spec: &ChartSpec, opts: KittyOpts) -> Option<Vec<u8>> {
57
2664
    let (width, height) = (opts.width_px, opts.height_px);
58
2664
    let rgba = match opts.background {
59
1332
        Some(ground) => opaque(&render_on(spec, opts, ground)?),
60
1332
        None => unblend(
61
1332
            &render_on(spec, opts, [0xff; 3])?,
62
1332
            &render_on(spec, opts, [0x00; 3])?,
63
        ),
64
    };
65
2664
    let rgba: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)?;
66
2664
    let mut png = Vec::new();
67
2664
    rgba.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
68
2664
        .ok()?;
69
2664
    Some(png)
70
2664
}
71

            
72
/// The chart drawn without a background over an RGB buffer pre-filled with
73
/// `ground`; plotters' bitmap backend has no alpha channel.
74
3996
fn render_on(spec: &ChartSpec, opts: KittyOpts, ground: [u8; 3]) -> Option<Vec<u8>> {
75
3996
    let (width, height) = (opts.width_px, opts.height_px);
76
3996
    let pixels = (width as usize).checked_mul(height as usize)?;
77
3996
    pixels.checked_mul(3)?;
78
3996
    let mut rgb: Vec<u8> = ground.repeat(pixels);
79
    let drew = {
80
3996
        let root = BitMapBackend::with_buffer(&mut rgb, (width, height)).into_drawing_area();
81
3996
        draw_on(&root, spec, opts.text_px, ink(opts.background)).is_ok() && root.present().is_ok()
82
    };
83
3996
    drew.then_some(rgb)
84
3996
}
85

            
86
/// The grey that reads on any terminal when there is no background, else black or white
87
/// whichever contrasts with it.
88
3999
fn ink(background: Option<[u8; 3]>) -> RGBColor {
89
3999
    match background {
90
2665
        None => NEUTRAL,
91
        Some([r, g, b]) => {
92
1334
            let luma = (299 * u32::from(r) + 587 * u32::from(g) + 114 * u32::from(b)) / 1000;
93
1334
            match luma > 140 {
94
3
                true => RGBColor(30, 30, 30),
95
1331
                false => RGBColor(235, 235, 235),
96
            }
97
        }
98
    }
99
3999
}
100

            
101
1332
fn opaque(rgb: &[u8]) -> Vec<u8> {
102
1332
    let (pixels, _) = rgb.as_chunks::<3>();
103
1332
    pixels
104
1332
        .iter()
105
664909792
        .flat_map(|[r, g, b]| [*r, *g, *b, u8::MAX])
106
        .collect()
107
1332
}
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.
111
1335
fn unblend(on_white: &[u8], on_black: &[u8]) -> Vec<u8> {
112
1335
    let (whites, _) = on_white.as_chunks::<3>();
113
1335
    let (blacks, _) = on_black.as_chunks::<3>();
114
1335
    whites
115
1335
        .iter()
116
1335
        .zip(blacks)
117
305342403
        .flat_map(|(white, black)| {
118
305342403
            let spread: u32 = white
119
305342403
                .iter()
120
305342403
                .zip(black)
121
916027209
                .map(|(w, b)| u32::from(*w).saturating_sub(u32::from(*b)))
122
                .sum();
123
305342403
            let alpha = 255 - (spread / 3).min(255);
124
916027209
            let channel = |b: &u8| match alpha {
125
771392976
                0 => 0,
126
144634233
                a => u8::try_from((u32::from(*b) * 255 + a / 2) / a).unwrap_or(u8::MAX),
127
916027209
            };
128
305342403
            let [r, g, b] = black.each_ref().map(channel);
129
305342403
            [r, g, b, u8::try_from(alpha).unwrap_or(u8::MAX)]
130
305342403
        })
131
        .collect()
132
1335
}
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]
138
335
pub fn encode_png_apc(png: &[u8]) -> String {
139
335
    let encoded = BASE64.encode(png);
140
335
    let mut out = String::with_capacity(encoded.len() + 64);
141
335
    let chunks: Vec<&str> = encoded
142
335
        .as_bytes()
143
335
        .chunks(KITTY_CHUNK_MAX)
144
1335
        .map(|c| std::str::from_utf8(c).unwrap_or(""))
145
        .collect();
146

            
147
335
    if chunks.is_empty() {
148
1
        return String::new();
149
334
    }
150

            
151
334
    for (i, chunk) in chunks.iter().enumerate() {
152
1335
        let first = i == 0;
153
1335
        let last = i + 1 == chunks.len();
154
1335
        let more = i32::from(!last);
155
1335
        if first {
156
334
            out.push_str(&format!("\x1b_Gf=100,a=T,m={more};"));
157
        } else {
158
1001
            out.push_str(&format!("\x1b_Gm={more};"));
159
        }
160
1335
        out.push_str(chunk);
161
1335
        out.push_str("\x1b\\");
162
    }
163
334
    out
164
335
}
165

            
166
#[cfg(test)]
167
mod tests;