Skip to main content

tvui/
picture.rs

1//! A PNG drawn through ratatui's buffer: kitty unicode placeholders or halfblocks.
2//!
3//! The `Picker` of ratatui-image is not used: its font-size constructor is
4//! deprecated and its stdio query cannot work over an ssh channel, so the
5//! protocol structs are built directly from the caller's cell pixels.
6
7mod halves;
8
9use halves::Halves;
10use image::ImageFormat;
11use ratatui::buffer::Buffer;
12use ratatui::layout::{Rect, Size};
13use ratatui::style::Color;
14use ratatui::widgets::Widget;
15use ratatui_image::protocol::Protocol;
16use ratatui_image::protocol::kitty::Kitty;
17use ratatui_image::{FontSize, Resize};
18
19/// How the picture reaches the terminal.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum ImageBackend {
22    Kitty { id: u32 },
23    HalfBlocks,
24}
25
26#[derive(Debug, thiserror::Error)]
27pub enum ImageError {
28    #[error("the image area has no room")]
29    NoRoom,
30    #[error("the image is not a PNG: {0}")]
31    NotPng(#[source] image::ImageError),
32    #[error("the image cannot be drawn: {0}")]
33    Protocol(#[source] ratatui_image::errors::Errors),
34}
35
36/// A decoded PNG ready to draw into an area of the size it was built for.
37pub struct Image {
38    drawn: Drawn,
39}
40
41enum Drawn {
42    Kitty(Protocol),
43    Halves(Halves),
44}
45
46impl Image {
47    /// # Errors
48    /// The area has no cells, the PNG cannot be decoded, or the protocol rejects the image.
49    pub fn new(
50        png: &[u8],
51        backend: ImageBackend,
52        size: Size,
53        cell_pixels: (u16, u16),
54    ) -> Result<Self, ImageError> {
55        if size.width == 0 || size.height == 0 {
56            return Err(ImageError::NoRoom);
57        }
58        let decoded = image::load_from_memory_with_format(png, ImageFormat::Png)
59            .map_err(ImageError::NotPng)?;
60        let font = FontSize::from(cell_pixels);
61        let fitted = Resize::Scale(None).resize(&decoded, font, size, None);
62        let drawn = match backend {
63            ImageBackend::Kitty { id } => Kitty::new(fitted, size, id, false, true)
64                .map(|kitty| Drawn::Kitty(Protocol::Kitty(kitty)))
65                .map_err(ImageError::Protocol)?,
66            ImageBackend::HalfBlocks => Drawn::Halves(Halves::new(&fitted, size)),
67        };
68        Ok(Self { drawn })
69    }
70
71    /// Transparent pixels show `background`.
72    pub fn render(&self, area: Rect, buffer: &mut Buffer, background: Color) {
73        match &self.drawn {
74            Drawn::Kitty(protocol) => ratatui_image::Image::new(protocol).render(area, buffer),
75            Drawn::Halves(halves) => halves.render(area, buffer, background),
76        }
77    }
78}
79
80/// The kitty command that deletes image `id` and frees its data.
81#[must_use]
82pub fn kitty_delete(id: u32) -> Vec<u8> {
83    format!("\x1b_Ga=d,d=I,i={id},q=2\x1b\\").into_bytes()
84}
85
86#[cfg(test)]
87mod tests;