Lines
100 %
Functions
Branches
//! A PNG drawn through ratatui's buffer: kitty unicode placeholders or halfblocks.
//!
//! The `Picker` of ratatui-image is not used: its font-size constructor is
//! deprecated and its stdio query cannot work over an ssh channel, so the
//! protocol structs are built directly from the caller's cell pixels.
mod halves;
use halves::Halves;
use image::ImageFormat;
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui::style::Color;
use ratatui::widgets::Widget;
use ratatui_image::protocol::Protocol;
use ratatui_image::protocol::kitty::Kitty;
use ratatui_image::{FontSize, Resize};
/// How the picture reaches the terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageBackend {
Kitty { id: u32 },
HalfBlocks,
}
#[derive(Debug, thiserror::Error)]
pub enum ImageError {
#[error("the image area has no room")]
NoRoom,
#[error("the image is not a PNG: {0}")]
NotPng(#[source] image::ImageError),
#[error("the image cannot be drawn: {0}")]
Protocol(#[source] ratatui_image::errors::Errors),
/// A decoded PNG ready to draw into an area of the size it was built for.
pub struct Image {
drawn: Drawn,
enum Drawn {
Kitty(Protocol),
Halves(Halves),
impl Image {
/// # Errors
/// The area has no cells, the PNG cannot be decoded, or the protocol rejects the image.
pub fn new(
png: &[u8],
backend: ImageBackend,
size: Size,
cell_pixels: (u16, u16),
) -> Result<Self, ImageError> {
if size.width == 0 || size.height == 0 {
return Err(ImageError::NoRoom);
let decoded = image::load_from_memory_with_format(png, ImageFormat::Png)
.map_err(ImageError::NotPng)?;
let font = FontSize::from(cell_pixels);
let fitted = Resize::Scale(None).resize(&decoded, font, size, None);
let drawn = match backend {
ImageBackend::Kitty { id } => Kitty::new(fitted, size, id, false, true)
.map(|kitty| Drawn::Kitty(Protocol::Kitty(kitty)))
.map_err(ImageError::Protocol)?,
ImageBackend::HalfBlocks => Drawn::Halves(Halves::new(&fitted, size)),
};
Ok(Self { drawn })
/// Transparent pixels show `background`.
pub fn render(&self, area: Rect, buffer: &mut Buffer, background: Color) {
match &self.drawn {
Drawn::Kitty(protocol) => ratatui_image::Image::new(protocol).render(area, buffer),
Drawn::Halves(halves) => halves.render(area, buffer, background),
/// The kitty command that deletes image `id` and frees its data.
#[must_use]
pub fn kitty_delete(id: u32) -> Vec<u8> {
format!("\x1b_Ga=d,d=I,i={id},q=2\x1b\\").into_bytes()
#[cfg(test)]
mod tests;