rustimal 0.2.4

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
use std::path::PathBuf;

use serde::Deserialize;

pub type Rgba = [f32; 4];

#[derive(Deserialize, Clone, Debug)]
#[serde(default)]
pub struct Config {
    /// Font family name (falls back to system fonts for missing glyphs).
    pub font_family: String,
    /// Font size in points (12pt == 16px at 100% scaling).
    pub font_size: f32,
    /// Line height as a multiple of the font size.
    pub line_height: f32,
    /// Shell executable. Empty means "find Git Bash".
    pub shell: String,
    pub shell_args: Vec<String>,
    /// Inner padding of each pane, in logical pixels.
    pub padding: f32,
    /// Gap between panes and around the window edge, in logical pixels.
    pub gap: f32,
    /// Corner radius of panes, in logical pixels.
    pub radius: f32,
    pub scrollback: usize,
    pub cursor_blink: bool,
    /// Multiplier for every animation. 0 disables animations.
    pub animation_speed: f32,
    pub copy_on_select: bool,
    /// Minimal prompt, folder tracking and the Claude session picker (bash only).
    pub shell_integration: bool,
    /// See-through window with a blurred desktop behind it, and glass panes.
    pub glass: bool,
    /// How solid glass panes are, 0..1. Lower shows more of the desktop.
    pub glass_opacity: f32,
    pub theme: Theme,
}

#[derive(Deserialize, Clone, Debug)]
#[serde(default)]
pub struct Theme {
    pub background: String,
    pub surface: String,
    pub border: String,
    pub foreground: String,
    pub cursor: String,
    pub accent: String,
    pub selection: String,
    pub ansi: [String; 16],
}

impl Default for Config {
    fn default() -> Self {
        Self {
            font_family: "Cascadia Mono".into(),
            font_size: 11.0,
            line_height: 1.3,
            shell: String::new(),
            shell_args: vec!["--login".into(), "-i".into()],
            padding: 12.0,
            gap: 6.0,
            radius: 10.0,
            scrollback: 20_000,
            cursor_blink: true,
            animation_speed: 1.0,
            copy_on_select: false,
            shell_integration: true,
            glass: true,
            glass_opacity: 0.66,
            theme: Theme::default(),
        }
    }
}

impl Default for Theme {
    fn default() -> Self {
        let s = |v: &str| v.to_string();
        Self {
            background: s("#08090b"),
            surface: s("#101216"),
            border: s("#1b1f26"),
            foreground: s("#d5d9e0"),
            cursor: s("#e6e9ee"),
            accent: s("#52b6cc"),
            selection: s("#2b4a5a"),
            ansi: [
                s("#1d2128"), // black
                s("#ef7a7f"), // red
                s("#a3cf8c"), // green
                s("#e6c27f"), // yellow
                s("#78a3f2"), // blue
                s("#c49ae6"), // magenta
                s("#5ccbe0"), // cyan
                s("#c4c9d1"), // white
                s("#5d6573"), // bright black
                s("#ff9196"), // bright red
                s("#b9e3a2"), // bright green
                s("#f2d49a"), // bright yellow
                s("#9bbcff"), // bright blue
                s("#d8b2f5"), // bright magenta
                s("#8be0f0"), // bright cyan
                s("#eef0f4"), // bright white
            ],
        }
    }
}

/// Theme with colors parsed into floats (sRGB, 0..1).
#[derive(Clone, Debug)]
pub struct Palette {
    pub background: Rgba,
    pub surface: Rgba,
    pub border: Rgba,
    pub foreground: Rgba,
    pub cursor: Rgba,
    pub accent: Rgba,
    pub selection: Rgba,
    pub ansi: [Rgba; 16],
}

impl Palette {
    pub fn from_theme(t: &Theme) -> Self {
        let d = Theme::default();
        let p = |v: &str, fallback: &str| parse_hex(v).or_else(|| parse_hex(fallback)).unwrap();
        let mut ansi = [[0.0; 4]; 16];
        for (i, c) in ansi.iter_mut().enumerate() {
            *c = p(&t.ansi[i], &d.ansi[i]);
        }
        Self {
            background: p(&t.background, &d.background),
            surface: p(&t.surface, &d.surface),
            border: p(&t.border, &d.border),
            foreground: p(&t.foreground, &d.foreground),
            cursor: p(&t.cursor, &d.cursor),
            accent: p(&t.accent, &d.accent),
            selection: p(&t.selection, &d.selection),
            ansi,
        }
    }

    /// xterm 256-color palette lookup.
    pub fn indexed(&self, idx: u8) -> Rgba {
        match idx {
            0..=15 => self.ansi[idx as usize],
            16..=231 => {
                let i = idx - 16;
                let step = |v: u8| if v == 0 { 0.0 } else { (55.0 + v as f32 * 40.0) / 255.0 };
                [step(i / 36), step((i / 6) % 6), step(i % 6), 1.0]
            }
            _ => {
                let v = (8.0 + (idx - 232) as f32 * 10.0) / 255.0;
                [v, v, v, 1.0]
            }
        }
    }
}

pub fn parse_hex(s: &str) -> Option<Rgba> {
    let s = s.trim().trim_start_matches('#');
    let byte = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|b| b as f32 / 255.0);
    match s.len() {
        6 => Some([byte(0)?, byte(2)?, byte(4)?, 1.0]),
        8 => Some([byte(0)?, byte(2)?, byte(4)?, byte(6)?]),
        _ => None,
    }
}

pub fn config_path() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("rustimal").join("config.toml"))
}

impl Config {
    pub fn load() -> Self {
        let Some(path) = config_path() else { return Self::default() };
        match std::fs::read_to_string(&path) {
            Ok(text) => toml::from_str(&text).unwrap_or_else(|e| {
                log::error!("invalid config {}: {e}", path.display());
                Self::default()
            }),
            Err(_) => {
                if let Some(dir) = path.parent() {
                    let _ = std::fs::create_dir_all(dir);
                    let _ = std::fs::write(&path, DEFAULT_CONFIG);
                }
                Self::default()
            }
        }
    }

    /// Resolve the shell program, preferring Git Bash.
    pub fn shell_program(&self) -> (String, Vec<String>) {
        if !self.shell.is_empty() {
            return (self.shell.clone(), self.shell_args.clone());
        }
        let mut candidates: Vec<PathBuf> =
            vec![r"C:\Program Files\Git\bin\bash.exe".into(), r"C:\Program Files (x86)\Git\bin\bash.exe".into()];
        if let Some(local) = dirs::data_local_dir() {
            candidates.push(local.join(r"Programs\Git\bin\bash.exe"));
        }
        if let Some(home) = dirs::home_dir() {
            candidates.push(home.join(r"scoop\apps\git\current\bin\bash.exe"));
        }
        for c in candidates {
            if c.exists() {
                return (c.to_string_lossy().into_owned(), self.shell_args.clone());
            }
        }
        ("powershell.exe".into(), vec!["-NoLogo".into()])
    }
}

const DEFAULT_CONFIG: &str = r##"# rustimal configuration. Delete a line to use the default.

# font_family = "Cascadia Mono"
# font_size = 11.0          # points
# line_height = 1.3
# shell = ""                # empty = Git Bash
# shell_args = ["--login", "-i"]
# padding = 12.0
# gap = 6.0
# radius = 10.0
# scrollback = 20000
# cursor_blink = true
# animation_speed = 1.0     # 0 disables animations
# copy_on_select = false
# shell_integration = true  # minimal prompt + Claude session picker
# glass = true             # see-through, blurred window and glass panes
# glass_opacity = 0.66      # 0..1, how solid the panes are

# [theme]
# background = "#08090b"
# surface = "#101216"
# border = "#1b1f26"
# foreground = "#d5d9e0"
# cursor = "#e6e9ee"
# accent = "#52b6cc"
# selection = "#2b4a5a"
# ansi = ["#1d2128", "#ef7a7f", "#a3cf8c", "#e6c27f", "#78a3f2", "#c49ae6", "#5ccbe0", "#c4c9d1",
#         "#5d6573", "#ff9196", "#b9e3a2", "#f2d49a", "#9bbcff", "#d8b2f5", "#8be0f0", "#eef0f4"]
"##;

const SHELL_INTEGRATION: &str = include_str!("shell/rustimal.bash");

impl Config {
    /// Install the bash integration script and return the env vars that load it.
    pub fn shell_env(&self) -> Vec<(String, String)> {
        let (program, _) = self.shell_program();
        if !self.shell_integration || !program.to_ascii_lowercase().contains("bash") {
            return Vec::new();
        }
        let Some(dir) = config_path().and_then(|p| p.parent().map(|d| d.to_path_buf())) else { return Vec::new() };
        let path = dir.join("rustimal.bash");
        let _ = std::fs::create_dir_all(&dir);
        if let Err(e) = std::fs::write(&path, SHELL_INTEGRATION.replace("\r\n", "\n")) {
            log::error!("could not write {}: {e}", path.display());
            return Vec::new();
        }
        let fwd = |p: &std::path::Path| p.to_string_lossy().replace('\\', "/");
        let mut env = vec![("PROMPT_COMMAND".into(), format!("[ -z \"$__RUSTIMAL\" ] && . '{}'", fwd(&path)))];

        // Claude integration: a status line script that hands session data to rustimal,
        // passed to `claude` via --settings so the user's own Claude config is untouched.
        let state = state_dir();
        let script = dir.join("statusline.sh");
        let settings = dir.join("claude-settings.json");
        let claude_settings = serde_json::json!({
            "statusLine": { "type": "command", "command": format!("bash \"{}\"", fwd(&script)), "padding": 0 },
            "spinnerTipsEnabled": false,
        });
        let ok = state.as_ref().is_some_and(|s| std::fs::create_dir_all(s).is_ok())
            && std::fs::write(&script, STATUSLINE.replace("\r\n", "\n")).is_ok()
            && std::fs::write(&settings, claude_settings.to_string()).is_ok();
        if let (true, Some(state)) = (ok, state) {
            env.push(("RUSTIMAL_STATE".into(), fwd(&state)));
            env.push(("RUSTIMAL_CLAUDE_SETTINGS".into(), fwd(&settings)));
        }
        env
    }
}

impl Config {
    /// True once, on the first run that has nothing installed yet: the first shell
    /// then prints a tip about `rustimal --install`. `cargo install` can't register
    /// the Start menu entry itself, so this is how people find out about it.
    pub fn take_install_hint(&self) -> bool {
        if self.shell_env().is_empty() {
            return false; // the tip is printed by the bash integration
        }
        let Some(state) = state_dir() else { return false };
        let marker = state.join("install-hint-shown");
        let from_source_tree = std::env::current_exe().is_ok_and(|e| e.components().any(|c| c.as_os_str() == "target"));
        let installed = dirs::config_dir()
            .is_some_and(|d| d.join(r"Microsoft\Windows\Start Menu\Programs\rustimal.lnk").exists());
        if from_source_tree || installed || marker.exists() {
            return false;
        }
        let _ = std::fs::create_dir_all(&state);
        std::fs::write(&marker, "").is_ok()
    }
}

const STATUSLINE: &str = include_str!("shell/statusline.sh");

/// Where Claude sessions drop their status for rustimal to read.
pub fn state_dir() -> Option<PathBuf> {
    config_path().and_then(|p| p.parent().map(|d| d.join("state")))
}