rustimal 0.2.4

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! A pane: one shell process, its terminal state, and its animation state.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Instant, SystemTime};

use alacritty_terminal::event::{Event as TermEvent, EventListener, WindowSize};
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::{Config as TermConfig, Term};
use alacritty_terminal::tty::{self, Options, Shell};
use winit::event_loop::EventLoopProxy;

use crate::anim::Tween;
use crate::claude::{self, Status};
use crate::layout::{PaneId, Rect};

pub enum TitleSignal {
    None,
    Pick(PathBuf),
}

pub enum UserEvent {
    Term(PaneId, TermEvent),
}

#[derive(Clone)]
pub struct Listener {
    id: PaneId,
    proxy: EventLoopProxy<UserEvent>,
}

impl EventListener for Listener {
    fn send_event(&self, event: TermEvent) {
        let _ = self.proxy.send_event(UserEvent::Term(self.id, event));
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct GridSize {
    pub cols: usize,
    pub rows: usize,
}

impl Dimensions for GridSize {
    fn total_lines(&self) -> usize {
        self.rows
    }
    fn screen_lines(&self) -> usize {
        self.rows
    }
    fn columns(&self) -> usize {
        self.cols
    }
}

pub struct Pane {
    pub id: PaneId,
    pub term: Arc<FairMutex<Term<Listener>>>,
    sender: EventLoopSender,
    pub grid: GridSize,
    pending_grid: Option<(GridSize, Instant)>,
    cell: (f32, f32),

    /// Where the layout wants the pane.
    pub target: Rect,
    /// Where the pane is drawn this frame (sampled from `rect_anim`).
    pub rect: Rect,
    /// 0..1 focus highlight.
    pub focus: f32,
    /// 0..1 overall opacity (fades in on spawn, out on close).
    pub opacity: f32,
    /// 0..1 visual bell flash.
    pub bell: f32,
    pub rect_anim: Tween<Rect>,
    pub focus_anim: Tween<f32>,
    pub opacity_anim: Tween<f32>,
    pub bell_anim: Tween<f32>,
    pub title: String,
    pub cwd: Option<PathBuf>,
    pub scroll_accum: f32,
    /// Claude Code is running in this pane (started through the shell integration).
    pub claude: bool,
    /// Topic Claude puts in the terminal title.
    pub claude_title: String,
    /// Latest Claude status line data, and bookkeeping for reading it.
    pub claude_status: Option<Status>,
    status_key: String,
    status_mtime: Option<SystemTime>,
}

impl Pane {
    #[allow(clippy::too_many_arguments)]
    pub fn spawn(
        id: PaneId,
        proxy: EventLoopProxy<UserEvent>,
        shell: (String, Vec<String>),
        extra_env: &[(String, String)],
        cwd: Option<PathBuf>,
        scrollback: usize,
        grid: GridSize,
        cell: (f32, f32),
        rect: Rect,
    ) -> std::io::Result<Self> {
        let listener = Listener { id, proxy };
        let mut env: HashMap<String, String> = [
            ("TERM", "xterm-256color"),
            ("COLORTERM", "truecolor"),
            ("TERM_PROGRAM", "rustimal"),
            // Keep Git Bash in the directory we start it in.
            ("CHERE_INVOKING", "1"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
        // Current PATH and friends from the registry, not the (possibly stale) inherited ones.
        for (k, v) in crate::winenv::fresh() {
            env.entry(k).or_insert(v);
        }
        env.extend(extra_env.iter().cloned());
        // Unique across rustimal windows, so concurrent instances don't share status files.
        let status_key = format!("{}-{id}", std::process::id());
        env.insert("RUSTIMAL_PANE".into(), status_key.clone());
        let opts = Options {
            shell: Some(Shell::new(shell.0, shell.1)),
            working_directory: cwd.clone(),
            drain_on_exit: false,
            env,
            escape_args: true,
        };
        let pty = tty::new(&opts, window_size(grid, cell), id)?;
        let config = TermConfig { scrolling_history: scrollback, ..Default::default() };
        let term = Arc::new(FairMutex::new(Term::new(config, &grid, listener.clone())));
        let event_loop = EventLoop::new(term.clone(), listener, pty, false, false)?;
        let sender = event_loop.channel();
        event_loop.spawn();

        Ok(Self {
            id,
            term,
            sender,
            grid,
            pending_grid: None,
            cell,
            target: rect,
            rect,
            focus: 0.0,
            opacity: 0.0,
            bell: 0.0,
            rect_anim: Tween::new(rect),
            focus_anim: Tween::new(0.0),
            opacity_anim: Tween::new(0.0),
            bell_anim: Tween::new(0.0),
            title: String::new(),
            cwd,
            scroll_accum: 0.0,
            claude: false,
            claude_title: String::new(),
            claude_status: None,
            status_key,
            status_mtime: None,
        })
    }

    pub fn write(&self, bytes: impl Into<Cow<'static, [u8]>>) {
        let _ = self.sender.send(Msg::Input(bytes.into()));
    }

    /// Request a new grid size. Applied after a short debounce so that
    /// animations and key-repeat don't spam the shell with resizes.
    pub fn request_grid(&mut self, grid: GridSize, cell: (f32, f32), immediate: bool) {
        let cell_changed = cell != self.cell;
        self.cell = cell;
        if grid == self.grid && !cell_changed {
            self.pending_grid = None;
            return;
        }
        if immediate {
            self.apply_grid(grid);
        } else {
            self.pending_grid = Some((grid, Instant::now()));
        }
    }

    /// Returns true if a pending resize is still waiting.
    pub fn flush_grid(&mut self, debounce: std::time::Duration) -> bool {
        if let Some((grid, at)) = self.pending_grid {
            if at.elapsed() >= debounce {
                self.apply_grid(grid);
            } else {
                return true;
            }
        }
        false
    }

    fn apply_grid(&mut self, grid: GridSize) {
        self.pending_grid = None;
        self.grid = grid;
        self.term.lock().resize(grid);
        let _ = self.sender.send(Msg::Resize(window_size(grid, self.cell)));
    }

    pub fn window_size(&self) -> WindowSize {
        window_size(self.grid, self.cell)
    }

    /// Handle a title change. The shell integration uses titles as a side channel:
    /// "rustimal:<dir>" at every prompt, "__rustimal_pick__:<dir>" to request the
    /// Claude picker, and "__rustimal_claude__" right before Claude starts.
    /// Plain Git Bash titles look like "MINGW64:/c/some/dir".
    pub fn set_title(&mut self, title: String) -> TitleSignal {
        if let Some(path) = title.strip_prefix("__rustimal_pick__:") {
            return match msys_to_windows(path) {
                Some(dir) => TitleSignal::Pick(dir),
                None => TitleSignal::Pick(self.cwd.clone().unwrap_or_else(|| PathBuf::from("."))),
            };
        }
        if title == "__rustimal_claude__" {
            self.claude = true;
            self.claude_title.clear();
            self.claude_status = None;
            self.status_mtime = None;
            if let Some(f) = self.status_file() {
                let _ = std::fs::remove_file(f);
            }
            return TitleSignal::None;
        }
        if let Some((prefix, path)) = title.split_once(':')
            && prefix.chars().all(|c| c.is_ascii_alphanumeric()) && path.starts_with('/') {
                if let Some(p) = msys_to_windows(path) {
                    self.cwd = Some(p);
                }
                // Back at a prompt: whatever was running has exited. Claude can
                // leave the view scrolled back a little on exit, so snap down.
                if self.claude {
                    self.term.lock().scroll_display(alacritty_terminal::grid::Scroll::Bottom);
                }
                self.claude = false;
                self.title = title;
                return TitleSignal::None;
            }
        if self.claude {
            self.claude_title = title.trim_start_matches(|c: char| !c.is_alphanumeric()).trim().to_string();
        }
        self.title = title;
        TitleSignal::None
    }

    fn status_file(&self) -> Option<PathBuf> {
        crate::config::state_dir().map(|d| d.join(format!("claude-{}.json", self.status_key)))
    }

    /// Re-read Claude's status file if it changed. Returns true on new data.
    pub fn poll_status(&mut self) -> bool {
        if !self.claude {
            return false;
        }
        let Some(file) = self.status_file() else { return false };
        let Ok(mtime) = std::fs::metadata(&file).and_then(|m| m.modified()) else { return false };
        if self.status_mtime == Some(mtime) {
            return false;
        }
        self.status_mtime = Some(mtime);
        let Some(status) = std::fs::read_to_string(&file).ok().and_then(|t| claude::parse_status(&t)) else {
            return false;
        };
        let changed = self.claude_status.as_ref() != Some(&status);
        self.claude_status = Some(status);
        changed
    }

    /// Short name for the header: the folder name, or "rustimal" at home.
    pub fn display_name(&self) -> String {
        let home = dirs::home_dir();
        match &self.cwd {
            Some(cwd) if Some(cwd) != home.as_ref() => cwd
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| cwd.to_string_lossy().into_owned()),
            _ => "rustimal".into(),
        }
    }

    pub fn shutdown(&self) {
        let _ = self.sender.send(Msg::Shutdown);
    }
}

fn window_size(grid: GridSize, cell: (f32, f32)) -> WindowSize {
    WindowSize {
        num_lines: grid.rows as u16,
        num_cols: grid.cols as u16,
        cell_width: cell.0 as u16,
        cell_height: cell.1 as u16,
    }
}

fn msys_to_windows(path: &str) -> Option<PathBuf> {
    let mut parts = path.trim_start_matches('/').splitn(2, '/');
    let drive = parts.next()?;
    if drive.len() != 1 || !drive.chars().all(|c| c.is_ascii_alphabetic()) {
        return None;
    }
    let rest = parts.next().unwrap_or("");
    let p = PathBuf::from(format!("{}:\\{}", drive.to_ascii_uppercase(), rest.replace('/', "\\")));
    p.is_dir().then_some(p)
}

impl Drop for Pane {
    fn drop(&mut self) {
        self.shutdown();
        if let Some(f) = self.status_file() {
            let _ = std::fs::remove_file(f);
        }
    }
}