1mod 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#[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
36pub struct Image {
38 drawn: Drawn,
39}
40
41enum Drawn {
42 Kitty(Protocol),
43 Halves(Halves),
44}
45
46impl Image {
47 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 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#[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;