omatrix 0.1.1

A Matrix-style terminal rain animation for Omarchy users
Documentation
use std::io::{Stdout, Write, stdout};

use anyhow::Result;
use crossterm::{
    cursor::{Hide, MoveTo, Show},
    execute, queue,
    style::{Color, Print, ResetColor, SetBackgroundColor, SetForegroundColor},
    terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
};

use crate::{
    palette::Palette,
    sim::{Simulation, Size},
};

pub struct TerminalSession {
    stdout: Stdout,
    previous_frame: Vec<FrameCell>,
    last_size: Option<Size>,
    last_background: Option<Color>,
}

impl TerminalSession {
    pub fn enter() -> Result<Self> {
        terminal::enable_raw_mode()?;
        let mut stdout = stdout();
        execute!(stdout, EnterAlternateScreen, Hide)?;
        Ok(Self {
            stdout,
            previous_frame: Vec::new(),
            last_size: None,
            last_background: None,
        })
    }

    pub fn size(&self) -> Result<Size> {
        let (width, height) = terminal::size()?;
        Ok(Size::new(width, height))
    }

    pub fn render(&mut self, simulation: &Simulation, palette: &Palette) -> Result<()> {
        let size = simulation.size();
        let width = size.width as usize;
        let background = palette.background();
        let frame = build_frame(simulation, palette);
        let full_redraw = self.last_size != Some(size)
            || self.last_background != Some(background)
            || self.previous_frame.len() != frame.len();

        queue!(self.stdout, SetBackgroundColor(background))?;
        if full_redraw {
            queue!(self.stdout, Clear(ClearType::All))?;
        }

        let mut current_fg = None;

        if full_redraw {
            for (index, cell) in frame.iter().enumerate() {
                if cell.is_blank() {
                    continue;
                }

                write_cell(&mut self.stdout, index, width, cell, &mut current_fg)?;
            }
        } else {
            for (index, (current, previous)) in frame.iter().zip(&self.previous_frame).enumerate() {
                if current == previous {
                    continue;
                }

                write_cell(&mut self.stdout, index, width, current, &mut current_fg)?;
            }
        }

        queue!(self.stdout, ResetColor)?;
        self.stdout.flush()?;
        self.previous_frame = frame;
        self.last_size = Some(size);
        self.last_background = Some(background);
        Ok(())
    }
}

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

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FrameCell {
    glyph: char,
    foreground: Option<Color>,
}

impl FrameCell {
    fn blank() -> Self {
        Self {
            glyph: ' ',
            foreground: None,
        }
    }

    fn visible(glyph: char, foreground: Color) -> Self {
        Self {
            glyph,
            foreground: Some(foreground),
        }
    }

    fn is_blank(self) -> bool {
        self.foreground.is_none()
    }
}

fn build_frame(simulation: &Simulation, palette: &Palette) -> Vec<FrameCell> {
    simulation
        .cells()
        .iter()
        .map(|cell| {
            if cell.ttl == 0 {
                FrameCell::blank()
            } else {
                FrameCell::visible(
                    cell.glyph,
                    palette.color_for(cell.ttl, cell.max_ttl, cell.is_head),
                )
            }
        })
        .collect()
}

fn write_cell(
    stdout: &mut Stdout,
    index: usize,
    width: usize,
    cell: &FrameCell,
    current_fg: &mut Option<Color>,
) -> Result<()> {
    let x = (index % width) as u16;
    let y = (index / width) as u16;
    queue!(stdout, MoveTo(x, y))?;

    if let Some(foreground) = cell.foreground {
        if *current_fg != Some(foreground) {
            queue!(stdout, SetForegroundColor(foreground))?;
            *current_fg = Some(foreground);
        }
    }

    queue!(stdout, Print(cell.glyph))?;
    Ok(())
}