omatrix 0.1.1

A Matrix-style terminal rain animation for Omarchy users
Documentation
use std::{
    io::ErrorKind,
    time::{Duration, Instant},
};

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};

use crate::{
    charset::Charset,
    cli::{self, Cli},
    palette::Palette,
    render::TerminalSession,
    sim::{Simulation, Size},
    theme::{Theme, ThemeWatcher},
};

const FPS: u16 = 30;

pub fn run() -> Result<()> {
    let cli = cli::parse()?;
    run_with(cli)
}

fn run_with(cli: Cli) -> Result<()> {
    let mut watcher = ThemeWatcher::new(cli.theme_path.clone());
    let mut palette = Palette::from_theme(&load_initial_theme(&mut watcher, &cli)?);
    let mut terminal = TerminalSession::enter()?;
    let mut simulation = Simulation::new(terminal.size()?, Charset::default(), cli.seed);
    let frame_time = Duration::from_secs_f64(1.0 / f64::from(FPS));

    loop {
        if let Ok(Some(theme)) = watcher.poll() {
            palette = Palette::from_theme(&theme);
        }

        simulation.tick();
        terminal.render(&simulation, &palette)?;

        let deadline = Instant::now() + frame_time;
        while let Some(event) = poll_until(deadline)? {
            match event {
                Event::Key(key) if should_exit(key) => return Ok(()),
                Event::Resize(width, height) => simulation.resize(Size::new(width, height)),
                _ => {}
            }
        }
    }
}

fn load_initial_theme(watcher: &mut ThemeWatcher, cli: &Cli) -> Result<Theme> {
    match watcher.load() {
        Ok(theme) => Ok(theme),
        Err(error) if !cli.theme_path_was_explicit && is_not_found(&error) => {
            Ok(Theme::matrix_fallback())
        }
        Err(error) => Err(error),
    }
}

fn is_not_found(error: &anyhow::Error) -> bool {
    error.chain().any(|cause| {
        cause
            .downcast_ref::<std::io::Error>()
            .is_some_and(|io_error| io_error.kind() == ErrorKind::NotFound)
    })
}

fn poll_until(deadline: Instant) -> Result<Option<Event>> {
    let timeout = deadline.saturating_duration_since(Instant::now());
    if timeout.is_zero() || !event::poll(timeout)? {
        return Ok(None);
    }

    Ok(Some(event::read()?))
}

fn should_exit(key: KeyEvent) -> bool {
    matches!(key.code, KeyCode::Esc)
        || matches!(key.code, KeyCode::Char('q' | 'Q'))
        || (matches!(key.code, KeyCode::Char('c')) && key.modifiers.contains(KeyModifiers::CONTROL))
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::load_initial_theme;
    use crate::{
        cli::Cli,
        theme::{Theme, ThemeWatcher},
    };

    #[test]
    fn falls_back_for_missing_default_theme() {
        let cli = missing_theme_cli(false);
        let mut watcher = ThemeWatcher::new(cli.theme_path.clone());

        let theme = load_initial_theme(&mut watcher, &cli).unwrap();

        assert_eq!(theme, Theme::matrix_fallback());
    }

    #[test]
    fn errors_for_missing_explicit_theme() {
        let cli = missing_theme_cli(true);
        let mut watcher = ThemeWatcher::new(cli.theme_path.clone());

        assert!(load_initial_theme(&mut watcher, &cli).is_err());
    }

    fn missing_theme_cli(theme_path_was_explicit: bool) -> Cli {
        Cli {
            theme_path: PathBuf::from("/tmp/omatrix-definitely-missing-theme.toml"),
            theme_path_was_explicit,
            seed: None,
        }
    }
}