use crate::color::MatrixColor;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoldMode {
None,
Random,
All,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub screensaver: bool,
pub asynchronous: bool,
pub deep: bool,
pub bold: BoldMode,
pub force_linux_term: bool,
pub console: bool,
pub lock: bool,
pub old_style: bool,
pub update_delay: u64,
pub color: MatrixColor,
pub xwindow: bool,
pub rainbow: bool,
pub lambda_mode: bool,
pub dynamic_chars: bool,
pub classic: bool,
pub tty: Option<String>,
}
impl Default for Config {
fn default() -> Self {
Self {
screensaver: false,
asynchronous: false,
deep: false,
bold: BoldMode::None,
force_linux_term: false,
console: false,
lock: false,
old_style: false,
update_delay: 4,
color: MatrixColor::Green,
xwindow: false,
rainbow: false,
lambda_mode: false,
dynamic_chars: false,
classic: false,
tty: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StartupAction {
Run(Config),
PrintUsage,
PrintVersion,
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ConfigError {
#[error("unknown option '-{0}'")]
UnknownOption(char),
#[error("option '-{0}' requires an argument")]
MissingValue(char),
#[error("invalid delay value '{0}'")]
InvalidDelay(String),
#[error("delay must be between 0 and 10")]
DelayOutOfRange,
#[error("invalid color '{0}'")]
InvalidColor(String),
#[error("unexpected positional argument '{0}'")]
UnexpectedArgument(String),
}
pub fn parse_args<I, S>(args: I) -> Result<StartupAction, ConfigError>
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let args: Vec<String> = args.into_iter().map(Into::into).collect();
let mut config = Config::default();
let mut index = 1usize;
while index < args.len() {
let arg = &args[index];
if !arg.starts_with('-') || arg == "-" {
return Err(ConfigError::UnexpectedArgument(arg.clone()));
}
if arg == "--help" {
return Ok(StartupAction::PrintUsage);
}
if arg == "--" {
let unexpected = args.get(index + 1).cloned().unwrap_or_default();
return Err(ConfigError::UnexpectedArgument(unexpected));
}
let mut chars = arg[1..].chars().peekable();
while let Some(opt) = chars.next() {
match opt {
's' => config.screensaver = true,
'a' => config.asynchronous = true,
'D' => config.deep = true,
'b' => {
if config.bold != BoldMode::All {
config.bold = BoldMode::Random;
}
}
'B' => config.bold = BoldMode::All,
'C' => {
let value = take_value(&mut chars, &args, &mut index, opt)?;
let Some(color) = MatrixColor::from_name(&value) else {
return Err(ConfigError::InvalidColor(value));
};
config.color = color;
break;
}
'c' => config.classic = true,
'f' => config.force_linux_term = true,
'l' => config.console = true,
'L' => config.lock = true,
'n' => config.bold = BoldMode::None,
'h' | '?' => return Ok(StartupAction::PrintUsage),
'o' => config.old_style = true,
'u' => {
let value = take_value(&mut chars, &args, &mut index, opt)?;
let parsed = value
.parse::<u64>()
.map_err(|_| ConfigError::InvalidDelay(value))?;
if parsed > 10 {
return Err(ConfigError::DelayOutOfRange);
}
config.update_delay = parsed;
break;
}
'x' => config.xwindow = true,
'V' => return Ok(StartupAction::PrintVersion),
'r' => config.rainbow = true,
'm' => config.lambda_mode = true,
'k' => config.dynamic_chars = true,
't' => {
config.tty = Some(take_value(&mut chars, &args, &mut index, opt)?);
break;
}
_ => return Err(ConfigError::UnknownOption(opt)),
}
}
index += 1;
}
Ok(StartupAction::Run(config))
}
pub fn usage_text(binary_name: &str) -> String {
format!(
" Usage: {binary_name} -[DabBcfhlsmVxk] [-u speed] [-C color] [-t tty]
CLI + runtime-toggle (flag sets initial state, key toggles at runtime):
-D / D: Deep mode (continuous RGB depth gradient and smooth parallax)
-a / a: Asynchronous scroll
-b / b: Bold characters on
-B / B: All bold characters (overrides -b)
-c / c: Japanese (classic) charset. Requires appropriate fonts
-o / o: Old-style scrolling
-L / L: Lock mode (lock/unlock message shows for 3s)
-n / n: No bold characters (overrides -b and -B, default)
-r / r: Rainbow mode
-m / m: Lambda mode
-k / k: Characters change while scrolling. (Works without -o opt.)
-x / x: X window mode (legacy charset behavior)
-s / s: \"Screensaver\" mode (runtime key only disables, cannot re-enable
to avoid locking out the user)
-u speed (0 - 10, default 4) / 0..9: Animation speed (speed * 10 ms; 0 unlimited)
CLI-only (no runtime toggle):
-f: Force the linux $TERM type to be on
-l: Linux mode (uses matrix console font)
-h: Print usage and exit
-V: Print version information and exit
-C [color]: Use this color for matrix (default green)
-t [tty]: Set tty to use
Runtime-only hotkeys (no CLI flag):
~: Show / hide shortcuts popup
q: Quit
Ctrl+C: Quit (unless locked)
p / P: Pause / resume
d / f: Decrease / increase render FPS (1 - 120, default 60); hold for continuous adjustment
Changed runtime values appear in the top-right corner for 1 second
! @ # $ % ^ & ): Switch color (also disables rainbow)
"
)
}
pub fn version_text() -> String {
format!(
"matrixr version {}\nRepo: https://github.com/WhoSowSee/matrixr\n",
env!("CARGO_PKG_VERSION")
)
}
fn take_value(
chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
args: &[String],
index: &mut usize,
option: char,
) -> Result<String, ConfigError> {
if chars.peek().is_some() {
let value: String = chars.collect();
return Ok(value);
}
*index += 1;
args.get(*index)
.cloned()
.ok_or(ConfigError::MissingValue(option))
}