anitty 0.1.0

Anime character animation rendering for terminals
Documentation
use std::io::Write;

use base64::{Engine as _, engine::general_purpose::STANDARD};

use crate::{Backend, Error, RgbaFrame};

/// Direct RGBA output using the Kitty graphics protocol.
///
/// Uses two explicitly supplied image IDs on one terminal screen. The caller must
/// keep these IDs exclusive to this instance and use the same output throughout
/// its lifetime. A new image is uploaded before the previous image is removed,
/// so chunked transmission does not blank the current frame.
///
/// Call [`Backend::finish`] before leaving the screen to delete both owned IDs.
/// Dropping this value cannot clean up the terminal because it does not own the
/// writer. Replies are suppressed; success reports writing, not terminal support.
#[derive(Debug)]
pub struct Kitty {
    image_ids: [u32; 2],
    next: usize,
}

impl Kitty {
    /// Use `image_ids` for alternating frames; both must be nonzero and distinct.
    /// The IDs need not be consecutive. The caller must ensure neither is used
    /// by another instance or program on the same terminal screen.
    pub fn new(image_ids: [u32; 2]) -> Result<Self, Error> {
        if image_ids.contains(&0) || image_ids[0] == image_ids[1] {
            return Err(Error::InvalidBackend(
                "Kitty needs two distinct nonzero image IDs",
            ));
        }
        Ok(Self { image_ids, next: 0 })
    }
}

impl Backend for Kitty {
    fn draw(&mut self, frame: &RgbaFrame, output: &mut dyn Write) -> Result<(), Error> {
        let id = self.image_ids[self.next];
        // 3072 source bytes encode to the protocol's maximum 4096-byte payload.
        // Every nonfinal chunk must end on a base64 quartet boundary.
        let mut encoded = [0; 4096];
        let mut chunks = frame.pixels().chunks(3072).peekable();
        let mut first = true;
        while let Some(chunk) = chunks.next() {
            let more = u8::from(chunks.peek().is_some());
            if first {
                write!(
                    output,
                    "\x1b_Ga=t,t=d,f=32,s={},v={},i={id},q=2,m={more};",
                    frame.width(),
                    frame.height(),
                )?;
                first = false;
            } else {
                write!(output, "\x1b_Gm={more},q=2;")?;
            }
            let len = STANDARD
                .encode_slice(chunk, &mut encoded)
                .expect("3072 bytes fit in a 4096-byte base64 buffer");
            output.write_all(&encoded[..len])?;
            output.write_all(b"\x1b\\")?;
        }
        // Delete the old image before placing the new one, otherwise its colors
        // show through transparent pixels. Keep both commands in one write.
        let switch = format!(
            "\x1b_Ga=d,d=I,i={},q=2;\x1b\\\x1b_Ga=p,i={id},p=1,C=1,q=2;\x1b\\",
            self.image_ids[1 - self.next],
        );
        output.write_all(switch.as_bytes())?;
        output.flush()?;
        self.next = 1 - self.next;
        Ok(())
    }

    fn finish(&mut self, output: &mut dyn Write) -> Result<(), Error> {
        for id in self.image_ids {
            write!(output, "\x1b_Ga=d,d=I,i={id},q=2;\x1b\\")?;
        }
        output.flush()?;
        Ok(())
    }
}