rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! `do <task>` in the window: starting the agent for a pane, carrying its messages to the
//! pane's conversation, and the keys while that conversation shows.

use std::path::PathBuf;
use std::time::{Duration, Instant};

use winit::event::{ElementState, KeyEvent, MouseButton};
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::ModifiersState;

use super::{App, notify_done};
use crate::chat::{Agent, Chat, Request, Run, Update};
use crate::keys::{Action, Chord};
use crate::layout::PaneId;
use crate::pane::{Done, UserEvent};
use crate::settings::Input;

/// How often a running conversation is redrawn, for its spinner and timer.
pub(super) const CHAT_TICK: Duration = Duration::from_millis(100);

impl App {
    /// `do ...` in a shell. With a task, a new conversation; without, the pane's own comes
    /// back (or an empty one opens).
    pub(super) fn shell_do(&mut self, pane: PaneId, cwd: PathBuf, agent: &str, task: String) {
        let Some(agent) = Agent::parse(agent) else {
            let message = format!("`do` knows claude and codex, not {agent}");
            return self.toast(message);
        };
        let Some(st) = self.state.as_mut() else { return };
        st.t3.hide(pane);
        let Some(p) = st.panes.iter_mut().find(|p| p.id == pane) else { return };
        let task = task.trim().to_string();
        match p.chat.as_mut() {
            Some(chat) if task.is_empty() => chat.hidden = false,
            // A task still running is not thrown away for a new one.
            Some(chat) if chat.running() => {
                chat.hidden = false;
                chat.insert(&task);
                self.toast("This conversation is still working; your task is in the message box");
            }
            _ => {
                p.chat = Some(Box::new(Chat::new(agent, cwd)));
                if !task.is_empty() {
                    self.chat_send(pane, task);
                }
            }
        }
        self.chat_changed();
    }

    /// The shortcut: switch the focused pane between its conversation and its terminal.
    pub(super) fn toggle_chat(&mut self) {
        let Some(st) = self.state.as_mut() else { return };
        let focused = st.focused;
        let Some(p) = st.panes.iter_mut().find(|p| p.id == focused) else { return };
        match p.chat.as_mut() {
            Some(chat) => {
                chat.hidden = !chat.hidden;
                if !chat.hidden {
                    st.t3.hide(focused);
                }
            }
            None => {
                let cwd = p.cwd.clone().or_else(|| self.start_dir.clone()).or_else(dirs::home_dir);
                let Some(cwd) = cwd else { return };
                st.t3.hide(focused);
                p.chat = Some(Box::new(Chat::new(Agent::Claude, cwd)));
            }
        }
        self.chat_changed();
    }

    fn chat_changed(&mut self) {
        if let Some(st) = self.state.as_mut() {
            st.blink_epoch = Instant::now();
            st.hover_link = None;
            st.window.request_redraw();
        }
    }

    /// Does this pane show a conversation instead of its terminal?
    pub(super) fn chat_shows(&self, pane: PaneId) -> bool {
        self.state
            .as_ref()
            .and_then(|st| st.panes.iter().find(|p| p.id == pane))
            .is_some_and(|p| p.chat.as_ref().is_some_and(|c| !c.hidden))
    }

    fn chat_mut(&mut self, pane: PaneId) -> Option<&mut Chat> {
        self.state.as_mut()?.panes.iter_mut().find(|p| p.id == pane)?.chat.as_deref_mut()
    }

    fn chat_send(&mut self, pane: PaneId, message: String) {
        let proxy = self.proxy.clone();
        let Some(chat) = self.chat_mut(pane) else { return };
        chat.begin(message.clone());
        let started =
            Run::start(chat.agent, &chat.dir, chat.session.as_deref(), &chat.allowed, message, move |run, update| {
                let _ = proxy.send_event(UserEvent::Chat { pane, run, update });
            });
        match started {
            Ok(run) => chat.run = Some(run),
            Err(e) => {
                chat.apply(crate::chat::Event::Finished { error: Some(e) });
            }
        }
    }

    /// News from a pane's agent.
    pub(super) fn chat_update(&mut self, pane: PaneId, run: u64, update: Update) {
        self.t3_window_focus();
        let threshold = self.config.notify_after_secs;
        let Some(chat) = self.chat_mut(pane) else { return };
        // A run that was stopped may still have messages on the way.
        if chat.run.as_ref().is_none_or(|r| r.id != run) {
            return;
        }
        let secs = chat.elapsed();
        let mut ended = false;
        match update {
            Update::Events(events) => {
                for event in events {
                    ended |= chat.apply(event);
                }
            }
            Update::Exited(problem) => ended = chat.exited(&problem),
        }
        let (hidden, name) = (chat.hidden, chat.agent.name());
        if ended {
            if let Some(st) = self.state.as_mut() {
                notify_done(st, Done { what: format!("do ({name})"), secs }, threshold);
            }
            if hidden {
                let keys = self.keymap.describe(Action::Chat);
                self.toast(format!("{name} has finished \u{00b7} {keys} shows it"));
            }
        }
        if let Some(st) = self.state.as_ref() {
            st.window.request_redraw();
        }
    }

    fn chat_request(&mut self, pane: PaneId, request: Request) {
        match request {
            Request::Nothing => {}
            Request::Send(message) => self.chat_send(pane, message),
            Request::Hide => {
                if let Some(chat) = self.chat_mut(pane) {
                    chat.hidden = true;
                }
            }
            Request::Stop => {
                if let Some(chat) = self.chat_mut(pane) {
                    chat.stop();
                }
            }
            Request::Copy(text) => {
                let copied =
                    self.state.as_mut().and_then(|st| st.clipboard.as_mut()).is_some_and(|c| c.set_text(text).is_ok());
                self.toast(if copied { "Copied the answer" } else { "Could not copy to the clipboard" });
            }
        }
    }

    fn clipboard_text(&mut self) -> Option<String> {
        self.state.as_mut()?.clipboard.as_mut()?.get_text().ok()
    }

    /// A key while the focused pane shows a conversation. Window shortcuts keep working;
    /// nothing reaches the hidden shell.
    pub(super) fn chat_key(&mut self, event_loop: &ActiveEventLoop, event: &KeyEvent) -> bool {
        let Some(st) = self.state.as_ref() else { return false };
        let (pane, mods) = (st.focused, st.mods);
        if !self.chat_shows(pane) {
            return false;
        }
        let action = Chord::from_event(event, mods).and_then(|c| self.keymap.get(&c));
        let request = match action {
            Some(Action::Paste) => {
                if let Some(text) = self.clipboard_text()
                    && let Some(chat) = self.chat_mut(pane)
                {
                    chat.insert(&text);
                }
                Request::Nothing
            }
            Some(Action::Copy) => self.chat_mut(pane).map_or(Request::Nothing, |c| c.copy_answer()),
            // Ctrl+C and Ctrl+A belong to the conversation.
            Some(Action::SmartCopy | Action::SelectAll) | None => self.chat_input(pane, event, mods),
            // These are about the terminal underneath.
            Some(Action::Find | Action::CopyOutput) => Request::Nothing,
            Some(Action::ScrollPageUp | Action::ScrollTop) => self.chat_scroll(pane, true),
            Some(Action::ScrollPageDown | Action::ScrollBottom) => self.chat_scroll(pane, false),
            Some(_) if mods.intersects(ModifiersState::CONTROL | ModifiersState::ALT) => {
                self.shortcut(event_loop, event);
                Request::Nothing
            }
            Some(_) => self.chat_input(pane, event, mods),
        };
        self.chat_request(pane, request);
        self.chat_changed();
        true
    }

    fn chat_input(&mut self, pane: PaneId, event: &KeyEvent, mods: ModifiersState) -> Request {
        let Some(input) = Input::from_event(event, mods) else { return Request::Nothing };
        // A held Enter must not send again and again.
        if event.repeat && input == Input::Enter {
            return Request::Nothing;
        }
        self.chat_mut(pane).map_or(Request::Nothing, |c| c.key(input, mods.shift_key()))
    }

    fn chat_scroll(&mut self, pane: PaneId, up: bool) -> Request {
        if let Some(chat) = self.chat_mut(pane) {
            chat.key(if up { Input::PageUp } else { Input::PageDown }, false);
        }
        Request::Nothing
    }

    /// A mouse button over a conversation: it focuses the pane, and right or middle click
    /// pastes. Returns true if there is a conversation under the pointer.
    pub(super) fn chat_click(&mut self, button: MouseButton, state: ElementState) -> bool {
        let Some(st) = self.state.as_ref() else { return false };
        // A drag that began in a terminal goes on being that pane's.
        if st.selecting.is_some() || st.cmd_drag.is_some() || st.mouse_reporting.is_some() {
            return false;
        }
        let (x, y) = st.mouse;
        let Some(pane) = self.pane_at(x, y).filter(|&id| self.chat_shows(id)) else { return false };
        if state != ElementState::Pressed {
            return true;
        }
        if let Some(st) = self.state.as_mut()
            && st.focused != pane
        {
            let prev = st.focused;
            st.focused = pane;
            super::notify_focus(st, prev);
        }
        if matches!(button, MouseButton::Right | MouseButton::Middle)
            && let Some(text) = self.clipboard_text()
            && let Some(chat) = self.chat_mut(pane)
        {
            chat.insert(&text);
        }
        self.chat_changed();
        true
    }

    /// The wheel, in lines. Returns true if there is a conversation under the pointer.
    pub(super) fn chat_wheel(&mut self, lines: f32) -> bool {
        let Some(st) = self.state.as_ref() else { return false };
        let (x, y) = st.mouse;
        let Some(pane) = self.pane_at(x, y).filter(|&id| self.chat_shows(id)) else { return false };
        let step = (lines.abs() * 3.0).ceil() as usize;
        if let Some(chat) = self.chat_mut(pane) {
            chat.scroll = if lines > 0.0 { chat.scroll + step } else { chat.scroll.saturating_sub(step) };
        }
        self.chat_changed();
        true
    }
}