matrixr 1.1.0

Animated Matrix-style terminal screensaver
Documentation
use crossterm::style::Color;
use rand::SeedableRng;
use rand::rngs::SmallRng;

use super::{
    MessagePosition, RenderOptions, deep_tail_color, draw_shortcuts_popup, message_overlay_layout,
    render_frame,
};
use crate::color::MatrixColor;
use crate::config::BoldMode;
use crate::engine::MatrixState;

fn visible_output(output: Vec<u8>) -> String {
    let output = String::from_utf8(output).unwrap();
    let mut chars = output.chars();
    let mut visible = String::new();

    while let Some(ch) = chars.next() {
        if ch != '\u{1b}' {
            visible.push(ch);
            continue;
        }

        if chars.next() == Some('[') {
            for code in chars.by_ref() {
                if ('@'..='~').contains(&code) {
                    break;
                }
            }
        }
    }

    visible
}

#[test]
fn status_overlay_is_rendered_top_right_while_lock_overlay_stays_centered() {
    let mut rng = SmallRng::seed_from_u64(42);
    let matrix = MatrixState::new(80, 24, &mut rng);
    let message = "FPS: 60 (d-/f+)";

    let status = message_overlay_layout(&matrix, message, MessagePosition::TopRight);
    assert_eq!(status.top_row, 0);
    assert_eq!(status.height, 1);
    assert_eq!(status.left_col + status.width, matrix.width() as i32);

    let lock = message_overlay_layout(&matrix, "Computer locked", MessagePosition::Center);
    assert_eq!(lock.height, 3);
    assert_eq!(lock.top_row + lock.height / 2, matrix.height() as i32 / 2);

    let options = RenderOptions {
        bold: BoldMode::None,
        color: MatrixColor::Green,
        rainbow: false,
        deep: false,
        console_or_xwindow: false,
        old_style: false,
        message: Some((message, MessagePosition::TopRight)),
        shortcuts_scroll: None,
    };
    let mut output = Vec::new();
    render_frame(&mut output, &matrix, &options, &mut rng).unwrap();
    assert!(visible_output(output).contains(message));
}

#[test]
fn deep_tail_restores_the_initial_continuous_depth_curve() {
    let cases = [
        (0, 1, (140, 207, 127)),
        (1, 1, (126, 186, 114)),
        (3, 2, (65, 96, 59)),
        (6, 3, (16, 25, 15)),
    ];

    for (distance, plane, (r, g, b)) in cases {
        assert_eq!(
            deep_tail_color(MatrixColor::Green, distance, plane),
            Color::Rgb { r, g, b }
        );
    }
}

#[test]
fn shortcuts_popup_uses_terminal_default_colors() {
    let mut output = Vec::new();

    draw_shortcuts_popup(&mut output, 80, 24, 0).unwrap();

    let rendered = String::from_utf8_lossy(&output);
    assert!(rendered.starts_with("\x1b[39;49m"));
    assert!(rendered.contains("Shortcuts"));
}