matrixr 1.1.0

Animated Matrix-style terminal screensaver
Documentation
use std::io::{self, Write};

use crossterm::cursor::MoveTo;
use crossterm::queue;
use crossterm::style::{Attribute, Color, Print, ResetColor, SetAttribute, SetForegroundColor};
use crossterm::terminal::{Clear, ClearType};
use rand::{Rng, RngExt};

use crate::color::{MatrixColor, RAINBOW_COLORS};
use crate::config::BoldMode;
use crate::engine::{MatrixState, VALUE_BAR, VALUE_DOT, VALUE_EMPTY};
use crate::help::render_popup;

#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(test, derive(Debug, Eq))]
pub(crate) enum MessagePosition {
    Center,
    TopRight,
}

pub(crate) struct RenderOptions<'a> {
    pub(crate) bold: BoldMode,
    pub(crate) color: MatrixColor,
    pub(crate) rainbow: bool,
    pub(crate) deep: bool,
    pub(crate) console_or_xwindow: bool,
    pub(crate) old_style: bool,
    pub(crate) message: Option<(&'a str, MessagePosition)>,
    pub(crate) shortcuts_scroll: Option<usize>,
}

pub(crate) fn clear_screen<W: Write>(writer: &mut W) -> io::Result<()> {
    queue!(writer, Clear(ClearType::All), MoveTo(0, 0))?;
    writer.flush()
}

pub(crate) fn render_frame<W: Write, R: Rng>(
    writer: &mut W,
    matrix: &MatrixState,
    options: &RenderOptions<'_>,
    rng: &mut R,
) -> io::Result<()> {
    let overlay_layout = options
        .message
        .filter(|(text, _)| !text.is_empty())
        .map(|message| {
            (
                message,
                message_overlay_layout(matrix, message.0, message.1),
            )
        });

    let (start_row, end_row) = if options.old_style {
        (0, matrix.height().saturating_sub(1))
    } else {
        (1, matrix.height())
    };
    for col in (0..matrix.width()).step_by(2) {
        for src_row in start_row..=end_row {
            let dst_row = src_row - start_row;
            if let Some((_, layout)) = overlay_layout.as_ref()
                && layout.contains(dst_row as i32, col as i32)
            {
                continue;
            }

            let cell = matrix.cell(src_row, col);
            let value = cell.val;
            let head_or_dot =
                value == VALUE_DOT || (cell.is_head && (!options.rainbow || options.deep));

            let (color, bold, glyph) = if head_or_dot {
                (
                    MatrixColor::White.to_terminal_color(),
                    options.bold != BoldMode::None,
                    head_glyph(value, options.console_or_xwindow),
                )
            } else {
                let matrix_color = if options.rainbow {
                    RAINBOW_COLORS[rng.random_range(0..RAINBOW_COLORS.len())]
                } else {
                    options.color
                };
                let (bold, glyph) = if value == VALUE_BAR {
                    (options.bold != BoldMode::None, '|')
                } else {
                    (
                        should_render_bold(value, options.bold),
                        trailing_glyph(value),
                    )
                };
                let color = if options.deep && glyph != ' ' {
                    deep_tail_color(
                        matrix_color,
                        matrix.tail_distance_to_head(src_row, col),
                        matrix.depth_plane(col),
                    )
                } else {
                    matrix_color.to_terminal_color()
                };

                (color, bold, glyph)
            };

            queue!(
                writer,
                MoveTo(col as u16, dst_row as u16),
                SetForegroundColor(color),
                SetAttribute(if bold {
                    Attribute::Bold
                } else {
                    Attribute::NormalIntensity
                }),
                Print(glyph)
            )?;
        }
    }

    queue!(writer, ResetColor, SetAttribute(Attribute::NormalIntensity))?;

    if let Some((message, layout)) = overlay_layout {
        draw_message_overlay(writer, matrix, message.0, &layout)?;
    }

    if let Some(scroll) = options.shortcuts_scroll {
        draw_shortcuts_popup(
            writer,
            matrix.width() as u16,
            matrix.height() as u16,
            scroll,
        )?;
    }

    writer.flush()
}

fn draw_shortcuts_popup<W: Write>(
    writer: &mut W,
    columns: u16,
    rows: u16,
    scroll: usize,
) -> io::Result<()> {
    let Some(popup) = render_popup(columns, rows, scroll) else {
        return Ok(());
    };

    const DEFAULT_COLORS: &str = "\x1b[39;49m";

    queue!(writer, Print(DEFAULT_COLORS))?;
    for (row, line) in popup.lines.iter().enumerate() {
        queue!(
            writer,
            MoveTo(popup.left, popup.top + row as u16),
            Print(line)
        )?;
    }
    Ok(())
}

fn deep_tail_color(color: MatrixColor, head_distance: usize, depth_plane: u8) -> Color {
    let tail_intensity = match head_distance {
        0 => 100,
        1 => 90,
        2 => 75,
        3 => 60,
        4 => 45,
        5 => 32,
        _ => 22,
    };
    let plane_intensity = match depth_plane {
        1 => 100,
        2 => 78,
        _ => 55,
    };
    let intensity = tail_intensity * plane_intensity;
    let (red, green, blue) = match color {
        MatrixColor::Black => (0, 0, 0),
        MatrixColor::Green => (140, 207, 127),
        MatrixColor::White => (255, 255, 255),
        MatrixColor::Red => (255, 0, 0),
        MatrixColor::Cyan => (0, 255, 255),
        MatrixColor::Magenta => (255, 0, 255),
        MatrixColor::Blue => (0, 0, 255),
        MatrixColor::Yellow => (255, 255, 0),
    };
    let scale = |component: u8| (component as usize * intensity / 10_000) as u8;

    Color::Rgb {
        r: scale(red),
        g: scale(green),
        b: scale(blue),
    }
}

fn head_glyph(value: i32, console_or_xwindow: bool) -> char {
    if value == VALUE_DOT {
        if console_or_xwindow { '\u{00B7}' } else { '&' }
    } else if value == VALUE_EMPTY {
        ' '
    } else {
        glyph_from_value(value)
    }
}

fn trailing_glyph(value: i32) -> char {
    if value == VALUE_EMPTY {
        ' '
    } else {
        glyph_from_value(value)
    }
}

fn glyph_from_value(value: i32) -> char {
    char::from_u32(value as u32).unwrap_or(' ')
}

fn should_render_bold(value: i32, bold_mode: BoldMode) -> bool {
    match bold_mode {
        BoldMode::None => false,
        BoldMode::Random => value % 2 == 0,
        BoldMode::All => true,
    }
}

pub(crate) fn erase_message_overlay<W: Write>(
    writer: &mut W,
    matrix: &MatrixState,
    message: &str,
    position: MessagePosition,
) -> io::Result<()> {
    if message.is_empty() {
        return Ok(());
    }
    let layout = message_overlay_layout(matrix, message, position);
    draw_overlay_background(writer, matrix, &layout)
}

fn draw_message_overlay<W: Write>(
    writer: &mut W,
    matrix: &MatrixState,
    message: &str,
    layout: &MessageOverlayLayout,
) -> io::Result<()> {
    draw_overlay_background(writer, matrix, layout)?;

    let screen_rows = matrix.height() as i32;
    let screen_cols = matrix.width() as i32;
    for (offset, ch) in message.chars().enumerate() {
        let col = layout.text_col + offset as i32;
        write_if_visible(writer, layout.text_row, col, ch, screen_rows, screen_cols)?;
    }

    Ok(())
}

fn draw_overlay_background<W: Write>(
    writer: &mut W,
    matrix: &MatrixState,
    layout: &MessageOverlayLayout,
) -> io::Result<()> {
    let screen_rows = matrix.height() as i32;
    let screen_cols = matrix.width() as i32;
    for row in layout.top_row..(layout.top_row + layout.height) {
        for col in layout.left_col..(layout.left_col + layout.width) {
            write_if_visible(writer, row, col, ' ', screen_rows, screen_cols)?;
        }
    }
    Ok(())
}

fn write_if_visible<W: Write>(
    writer: &mut W,
    row: i32,
    col: i32,
    ch: char,
    max_rows: i32,
    max_cols: i32,
) -> io::Result<()> {
    if row >= 0 && row < max_rows && col >= 0 && col < max_cols {
        queue!(writer, MoveTo(col as u16, row as u16), Print(ch))?;
    }
    Ok(())
}

struct MessageOverlayLayout {
    top_row: i32,
    left_col: i32,
    width: i32,
    height: i32,
    text_row: i32,
    text_col: i32,
}

impl MessageOverlayLayout {
    fn contains(&self, row: i32, col: i32) -> bool {
        (self.top_row..self.top_row + self.height).contains(&row)
            && (self.left_col..self.left_col + self.width).contains(&col)
    }
}

fn message_overlay_layout(
    matrix: &MatrixState,
    message: &str,
    position: MessagePosition,
) -> MessageOverlayLayout {
    let screen_rows = matrix.height() as i32;
    let screen_cols = matrix.width() as i32;
    let message_width = message.chars().count() as i32;
    let width = (message_width + 4).clamp(1, screen_cols.max(1));
    let text_width = message_width.min(width);

    let (top_row, left_col, height, text_row) = match position {
        MessagePosition::Center => {
            let height = 3.min(screen_rows.max(1));
            let text_row = screen_rows / 2;
            (
                (text_row - height / 2).max(0),
                (screen_cols - width) / 2,
                height,
                text_row,
            )
        }
        MessagePosition::TopRight => (0, screen_cols - width, 1, 0),
    };

    MessageOverlayLayout {
        top_row,
        left_col,
        width,
        height,
        text_row,
        text_col: left_col + (width - text_width) / 2,
    }
}

#[cfg(test)]
mod tests;