anitty 0.1.0

Anime character animation rendering for terminals
Documentation
mod probe;
pub mod render;

use anitty::{Animation, Backend, Iterm2, Kitty, RenderOptions, Sixel, TerminalCapabilities};
use crossterm::{
    cursor::{Hide, MoveTo, Show},
    event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
    execute,
    terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::{
    error::Error,
    io::{self, IsTerminal},
    time::{Duration, Instant},
};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum BackendChoice {
    Auto,
    Iterm2,
    Sixel,
    Kitty,
}

impl BackendChoice {
    fn create(self, background: [u8; 3]) -> Result<Box<dyn Backend>, Box<dyn Error>> {
        Ok(match self {
            Self::Auto | Self::Iterm2 => Box::new(Iterm2),
            Self::Sixel => Box::new(Sixel::new(background)),
            Self::Kitty => Box::new(Kitty::new([1, 2])?),
        })
    }
}

pub fn backend(name: &str) -> Result<BackendChoice, Box<dyn Error>> {
    match name {
        "auto" => Ok(BackendChoice::Auto),
        "iterm2" => Ok(BackendChoice::Iterm2),
        "sixel" => Ok(BackendChoice::Sixel),
        "kitty" => Ok(BackendChoice::Kitty),
        _ => Err(format!("unknown backend: {name}; expected auto, iterm2, sixel or kitty").into()),
    }
}

pub fn sixel_background(value: &str) -> Result<Option<[u8; 3]>, Box<dyn Error>> {
    if value == "auto" {
        return Ok(None);
    }
    let hex = value.strip_prefix('#').unwrap_or(value);
    if hex.len() != 6 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err("--sixel-background requires auto or #RRGGBB".into());
    }
    let [_, r, g, b] = u32::from_str_radix(hex, 16)?.to_be_bytes();
    Ok(Some([r, g, b]))
}

pub fn play(
    animation: &mut dyn Animation,
    [width, height]: [u32; 2],
    frame_duration: Duration,
    mut choice: BackendChoice,
    background: Option<[u8; 3]>,
    once: bool,
    render: &RenderOptions,
) -> Result<(), Box<dyn Error>> {
    // Validate all render controls before entering terminal modes or probing.
    animation.mapping(width, height, render)?;
    let mut output = io::stdout().lock();
    if once {
        // Export has no terminal handshake, including when stdout is a TTY.
        choice.create(background.unwrap_or([0; 3]))?.draw(
            animation.render_with_options(Duration::ZERO, width, height, render)?,
            &mut output,
        )?;
        return Ok(());
    }
    if !output.is_terminal() {
        return Err(
            "interactive playback needs a terminal; use --once to export image data".into(),
        );
    }
    let names: Vec<_> = animation
        .animations()
        .map(|(name, _)| name.to_owned())
        .collect();

    terminal::enable_raw_mode()?;
    let mut session = TerminalSession { alternate: false };
    // Drop the buffer before the session guard on errors, while the alternate
    // screen is still active.
    let mut output = io::BufWriter::new(output);
    let mut backend = None;
    let playback = (|| -> Result<(), Box<dyn Error>> {
        let mut capabilities = TerminalCapabilities::default();
        if choice == BackendChoice::Auto
            || (cfg!(unix) && choice == BackendChoice::Sixel && background.is_none())
        {
            let (detected, unhandled) = probe::detect(&mut output, Duration::from_millis(300))?;
            if unhandled.contains(&b'q') || unhandled.contains(&3) || unhandled == b"\x1b" {
                return Ok(()); // Exit key received during detection.
            }
            capabilities = detected;
        }
        if choice == BackendChoice::Auto {
            choice = auto_backend(&capabilities)?;
        }
        let background = background.or(capabilities.background);
        if choice == BackendChoice::Sixel {
            match background {
                Some([r, g, b]) => eprint!("SIXEL background: #{r:02x}{g:02x}{b:02x}\r\n"),
                None => eprint!(
                    "SIXEL background unknown; using #000000 (override with --sixel-background '#RRGGBB')\r\n"
                ),
            }
        }
        backend = Some(choice.create(background.unwrap_or([0; 3]))?);
        let backend = backend.as_mut().unwrap();
        session.alternate = true;
        execute!(output, EnterAlternateScreen, Hide, MoveTo(0, 0))?;
        let start = Instant::now();
        let mut clip_start = Duration::ZERO;
        let mut next_frame = Duration::ZERO;
        loop {
            let elapsed = start.elapsed();
            if elapsed >= next_frame {
                backend.draw(
                    animation.render_with_options(elapsed - clip_start, width, height, render)?,
                    &mut output,
                )?;
                next_frame = elapsed + frame_duration;
            }
            if event::poll(next_frame.saturating_sub(start.elapsed()))? {
                if let Event::Key(key) = event::read()? {
                    if key.kind != KeyEventKind::Release
                        && (matches!(key.code, KeyCode::Esc | KeyCode::Char('q'))
                            || (key.code == KeyCode::Char('c')
                                && key.modifiers.contains(KeyModifiers::CONTROL)))
                    {
                        break;
                    }
                    if key.kind == KeyEventKind::Press {
                        match key.code {
                            KeyCode::Char('[' | ']') if names.len() > 1 => {
                                let current = names
                                    .iter()
                                    .position(|name| name == animation.animation_name())
                                    .unwrap();
                                let next = if key.code == KeyCode::Char(']') {
                                    (current + 1) % names.len()
                                } else {
                                    (current + names.len() - 1) % names.len()
                                };
                                animation.set_animation(&names[next])?;
                                clip_start = start.elapsed();
                                next_frame = Duration::ZERO;
                            }
                            KeyCode::Char('r') => {
                                clip_start = start.elapsed();
                                next_frame = Duration::ZERO;
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
        Ok(())
    })();
    // Attempt resource cleanup even after a render or input error. Report the
    // original playback error first if cleanup also fails.
    let cleanup = match backend.as_mut() {
        Some(backend) => backend.finish(&mut output),
        None => Ok(()),
    };
    playback?;
    cleanup?;
    if session.alternate {
        execute!(output, Show, LeaveAlternateScreen)?;
    }
    terminal::disable_raw_mode()?;
    // Cleanup above reports errors; Drop also restores the terminal on early returns.
    std::mem::forget(session);
    Ok(())
}

fn auto_backend(capabilities: &TerminalCapabilities) -> Result<BackendChoice, Box<dyn Error>> {
    use anitty::Support;

    // Prefer the PNG path already verified for Konsole's frame replacement.
    let name = if capabilities.iterm2 == Support::Inferred {
        "iterm2"
    } else if capabilities.kitty == Support::Supported {
        "kitty"
    } else if capabilities.sixel == Support::Supported {
        "sixel"
    } else {
        return Err(format!(
            "could not determine a usable backend ({capabilities:?}); specify --backend iterm2, sixel or kitty"
        ).into());
    };
    eprint!(
        "auto backend: {name} (iterm2={:?}, kitty={:?}, sixel={:?})\r\n",
        capabilities.iterm2, capabilities.kitty, capabilities.sixel
    );
    backend(name)
}

struct TerminalSession {
    alternate: bool,
}

impl Drop for TerminalSession {
    fn drop(&mut self) {
        if self.alternate {
            let _ = execute!(io::stdout(), Show, LeaveAlternateScreen);
        }
        let _ = terminal::disable_raw_mode();
    }
}