anitty 0.1.0

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

use base64::{Engine as _, engine::general_purpose::STANDARD};
use image::{ExtendedColorType, ImageEncoder, codecs::png::PngEncoder};

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

/// PNG output using the iTerm2 inline-image protocol, also supported by Konsole.
///
/// Preserves the full RGBA alpha channel, including partial transparency, at
/// native pixel dimensions. Konsole replaces images at the same position and
/// size after receiving the complete new image, so animations should not clear
/// between frames. Other terminals may have different replacement behavior.
/// This backend does not erase terminal content or probe capabilities.
#[derive(Debug, Default)]
pub struct Iterm2;

impl Backend for Iterm2 {
    fn draw(&mut self, frame: &RgbaFrame, output: &mut dyn Write) -> Result<(), Error> {
        let mut png = Vec::new();
        PngEncoder::new(&mut png).write_image(
            frame.pixels(),
            frame.width(),
            frame.height(),
            ExtendedColorType::Rgba8,
        )?;
        // Konsole understands doNotMoveCursor; DECSC/DECRC also preserve the
        // cursor on terminals that ignore this extension.
        write!(
            output,
            "\x1b7\x1b]1337;File=inline=1;size={};width={}px;height={}px;doNotMoveCursor=1:",
            png.len(),
            frame.width(),
            frame.height(),
        )?;
        output.write_all(STANDARD.encode(&png).as_bytes())?;
        output.write_all(b"\x07\x1b8")?;
        output.flush()?;
        Ok(())
    }
}