omatrix 0.1.1

A Matrix-style terminal rain animation for Omarchy users
Documentation
use std::{
    env, fs,
    io::ErrorKind,
    path::{Path, PathBuf},
    time::SystemTime,
};

use anyhow::{Context, Result, anyhow};
use crossterm::style::Color;
use toml::Value;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Rgb {
    pub const fn new(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b }
    }

    pub const fn black() -> Self {
        Self::new(0, 0, 0)
    }

    pub const fn white() -> Self {
        Self::new(255, 255, 255)
    }

    pub fn from_hex(raw: &str) -> Result<Self> {
        let hex = raw
            .trim()
            .strip_prefix('#')
            .or_else(|| raw.trim().strip_prefix("0x"))
            .unwrap_or(raw.trim());

        if hex.len() != 6 {
            return Err(anyhow!("expected a 6-digit RGB value, got {raw}"));
        }

        let r = u8::from_str_radix(&hex[0..2], 16)?;
        let g = u8::from_str_radix(&hex[2..4], 16)?;
        let b = u8::from_str_radix(&hex[4..6], 16)?;
        Ok(Self::new(r, g, b))
    }

    pub fn mix(self, other: Self, amount: f32) -> Self {
        let amount = amount.clamp(0.0, 1.0);
        let blend = |left: u8, right: u8| -> u8 {
            (left as f32 + (right as f32 - left as f32) * amount).round() as u8
        };

        Self::new(
            blend(self.r, other.r),
            blend(self.g, other.g),
            blend(self.b, other.b),
        )
    }

    pub fn vivid(self, saturation_floor: f32, saturation_ceiling: f32, value_floor: f32) -> Self {
        let (hue, saturation, value) = self.to_hsv();
        let saturation = saturation.max(saturation_floor).min(saturation_ceiling);
        let value = value.max(value_floor).clamp(0.0, 1.0);
        Self::from_hsv(hue, saturation, value)
    }

    pub fn contrast_ratio(self, other: Self) -> f32 {
        let left = self.relative_luminance();
        let right = other.relative_luminance();
        let (lighter, darker) = if left >= right {
            (left, right)
        } else {
            (right, left)
        };
        (lighter + 0.05) / (darker + 0.05)
    }

    pub fn distance(self, other: Self) -> u32 {
        u32::from(self.r.abs_diff(other.r))
            + u32::from(self.g.abs_diff(other.g))
            + u32::from(self.b.abs_diff(other.b))
    }

    fn relative_luminance(self) -> f32 {
        let channel = |value: u8| -> f32 {
            let srgb = value as f32 / 255.0;
            if srgb <= 0.04045 {
                srgb / 12.92
            } else {
                ((srgb + 0.055) / 1.055).powf(2.4)
            }
        };

        0.2126 * channel(self.r) + 0.7152 * channel(self.g) + 0.0722 * channel(self.b)
    }

    fn to_hsv(self) -> (f32, f32, f32) {
        let r = self.r as f32 / 255.0;
        let g = self.g as f32 / 255.0;
        let b = self.b as f32 / 255.0;
        let max = r.max(g).max(b);
        let min = r.min(g).min(b);
        let delta = max - min;

        let hue = if delta == 0.0 {
            0.0
        } else if max == r {
            60.0 * ((g - b) / delta).rem_euclid(6.0)
        } else if max == g {
            60.0 * (((b - r) / delta) + 2.0)
        } else {
            60.0 * (((r - g) / delta) + 4.0)
        };

        let saturation = if max == 0.0 { 0.0 } else { delta / max };
        (hue, saturation, max)
    }

    fn from_hsv(hue: f32, saturation: f32, value: f32) -> Self {
        let chroma = value * saturation;
        let hue_section = (hue / 60.0).rem_euclid(6.0);
        let secondary = chroma * (1.0 - (hue_section.rem_euclid(2.0) - 1.0).abs());
        let (r1, g1, b1) = match hue_section {
            h if h < 1.0 => (chroma, secondary, 0.0),
            h if h < 2.0 => (secondary, chroma, 0.0),
            h if h < 3.0 => (0.0, chroma, secondary),
            h if h < 4.0 => (0.0, secondary, chroma),
            h if h < 5.0 => (secondary, 0.0, chroma),
            _ => (chroma, 0.0, secondary),
        };
        let match_value = value - chroma;

        Self::new(
            ((r1 + match_value) * 255.0).round() as u8,
            ((g1 + match_value) * 255.0).round() as u8,
            ((b1 + match_value) * 255.0).round() as u8,
        )
    }
}

impl From<Rgb> for Color {
    fn from(value: Rgb) -> Self {
        Color::Rgb {
            r: value.r,
            g: value.g,
            b: value.b,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Theme {
    pub accent: Rgb,
    pub active_border: Rgb,
    pub cursor: Rgb,
    pub foreground: Rgb,
    pub background: Rgb,
    pub selection_foreground: Rgb,
    pub selection_background: Rgb,
    pub ansi: [Rgb; 16],
    pub is_light: bool,
}

impl Theme {
    pub fn matrix_fallback() -> Self {
        Self {
            accent: Rgb::new(0x00, 0xff, 0x41),
            active_border: Rgb::new(0x00, 0xff, 0x41),
            cursor: Rgb::new(0xb6, 0xff, 0xc8),
            foreground: Rgb::new(0x8f, 0xff, 0xa8),
            background: Rgb::new(0x00, 0x08, 0x08),
            selection_foreground: Rgb::new(0x00, 0x08, 0x08),
            selection_background: Rgb::new(0x00, 0xff, 0x41),
            ansi: [
                Rgb::new(0x00, 0x08, 0x08),
                Rgb::new(0x00, 0x8f, 0x11),
                Rgb::new(0x00, 0xff, 0x41),
                Rgb::new(0x5f, 0xff, 0x87),
                Rgb::new(0x00, 0x66, 0x20),
                Rgb::new(0x00, 0xbf, 0x32),
                Rgb::new(0x2a, 0xff, 0x6a),
                Rgb::new(0xb6, 0xff, 0xc8),
                Rgb::new(0x00, 0x1a, 0x0a),
                Rgb::new(0x00, 0xa8, 0x22),
                Rgb::new(0x00, 0xff, 0x41),
                Rgb::new(0x78, 0xff, 0x9a),
                Rgb::new(0x00, 0x80, 0x28),
                Rgb::new(0x00, 0xd9, 0x38),
                Rgb::new(0x66, 0xff, 0x88),
                Rgb::new(0xd8, 0xff, 0xe0),
            ],
            is_light: false,
        }
    }

    pub fn default_path() -> PathBuf {
        env::var_os("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".local/state/omarchy/current/theme/colors.toml")
    }

    pub fn load_from_path(path: &Path) -> Result<Self> {
        let raw = fs::read_to_string(path)
            .with_context(|| format!("failed to read theme file {}", path.display()))?;
        let border = load_active_border(path).unwrap_or_else(|_| None);
        Self::from_toml_str_with_border(&raw, border)
    }

    pub fn from_toml_str(raw: &str) -> Result<Self> {
        Self::from_toml_str_with_border(raw, None)
    }

    pub fn from_toml_str_with_border(raw: &str, active_border: Option<Rgb>) -> Result<Self> {
        let value: Value = toml::from_str(raw)?;
        let accent = read_color(&value, "accent")?;
        let cursor = read_color(&value, "cursor")?;
        let foreground = read_color(&value, "foreground")?;
        let background = read_color(&value, "background")?;
        let selection_foreground = read_color(&value, "selection_foreground")?;
        let selection_background = read_color(&value, "selection_background")?;

        let mut ansi = [Rgb::black(); 16];
        for (index, slot) in ansi.iter_mut().enumerate() {
            *slot = read_color(&value, &format!("color{index}"))?;
        }

        let is_light =
            background.contrast_ratio(Rgb::black()) >= background.contrast_ratio(Rgb::white());

        Ok(Self {
            accent,
            active_border: active_border.unwrap_or(accent),
            cursor,
            foreground,
            background,
            selection_foreground,
            selection_background,
            ansi,
            is_light,
        })
    }
}

#[derive(Debug)]
pub struct ThemeWatcher {
    path: PathBuf,
    border_path: PathBuf,
    last_modified: ThemeStamp,
}

impl ThemeWatcher {
    pub fn new(path: PathBuf) -> Self {
        Self {
            border_path: active_border_path(&path),
            path,
            last_modified: ThemeStamp::default(),
        }
    }

    pub fn load(&mut self) -> Result<Theme> {
        let theme = Theme::load_from_path(&self.path)?;
        self.last_modified = ThemeStamp::read(&self.path, &self.border_path)?;
        Ok(theme)
    }

    pub fn poll(&mut self) -> Result<Option<Theme>> {
        let modified = ThemeStamp::read(&self.path, &self.border_path)?;
        if self.last_modified == modified {
            return Ok(None);
        }

        let theme = Theme::load_from_path(&self.path)?;
        self.last_modified = modified;
        Ok(Some(theme))
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct ThemeStamp {
    colors_modified: Option<SystemTime>,
    border_modified: Option<SystemTime>,
}

impl ThemeStamp {
    fn read(colors_path: &Path, border_path: &Path) -> Result<Self> {
        let colors_modified = match fs::metadata(colors_path) {
            Ok(metadata) => metadata.modified().ok(),
            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::default()),
            Err(error) => {
                return Err(error).with_context(|| {
                    format!("failed to stat theme file {}", colors_path.display())
                });
            }
        };

        let border_modified = match fs::metadata(border_path) {
            Ok(metadata) => metadata.modified().ok(),
            Err(error) if error.kind() == ErrorKind::NotFound => None,
            Err(error) => {
                return Err(error).with_context(|| {
                    format!("failed to stat border file {}", border_path.display())
                });
            }
        };

        Ok(Self {
            colors_modified,
            border_modified,
        })
    }
}

fn read_color(value: &Value, key: &str) -> Result<Rgb> {
    let raw = value
        .get(key)
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("missing string key {key}"))?;

    Rgb::from_hex(raw).with_context(|| format!("failed to parse {key} color"))
}

fn active_border_path(colors_path: &Path) -> PathBuf {
    colors_path.with_file_name("hyprland.conf")
}

fn load_active_border(colors_path: &Path) -> Result<Option<Rgb>> {
    let path = active_border_path(colors_path);
    let raw = match fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
        Err(error) => {
            return Err(error)
                .with_context(|| format!("failed to read border file {}", path.display()));
        }
    };

    Ok(parse_active_border(&raw))
}

fn parse_active_border(raw: &str) -> Option<Rgb> {
    raw.lines().find_map(parse_hyprland_color)
}

fn parse_hyprland_color(line: &str) -> Option<Rgb> {
    let candidate = line.trim();
    if !candidate.contains("activeBorderColor") && !candidate.contains("active_border") {
        return None;
    }

    parse_color_function(candidate, "rgb(", 6)
        .or_else(|| parse_color_function(candidate, "rgba(", 8))
}

fn parse_color_function(line: &str, function: &str, hex_len: usize) -> Option<Rgb> {
    let start = line.find(function)? + function.len();
    let end = line[start..].find(')')? + start;
    let hex = line[start..end].trim();
    if hex.len() < hex_len {
        return None;
    }

    let rgb = if function == "rgba(" {
        &hex[..6]
    } else {
        &hex[..hex_len]
    };
    Rgb::from_hex(rgb).ok()
}

#[cfg(test)]
mod tests {
    use super::{Rgb, parse_active_border};

    #[test]
    fn parses_active_border_from_hyprland_theme() {
        let raw = "$activeBorderColor = rgb(7aa2f7)\ncol.active_border = $activeBorderColor\n";
        assert_eq!(parse_active_border(raw), Some(Rgb::new(0x7a, 0xa2, 0xf7)));
    }

    #[test]
    fn parses_rgba_active_border() {
        let raw = "col.active_border = rgba(7aa2f7ff)\n";
        assert_eq!(parse_active_border(raw), Some(Rgb::new(0x7a, 0xa2, 0xf7)));
    }
}