rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Keys typed into a pane: editing the command line, searching, and the keys that go on to
//! the program.

use super::*;

impl App {
    /// Text-editor keys on the command line: Shift+arrows (Ctrl for words, Home/End for the ends)
    /// select, and with something selected the next key replaces, deletes or moves past it.
    /// `Ctrl+Shift+Left/Right` and `Shift+Home/End` have other jobs (split, scroll) when there is
    /// nothing typed, and keep them. Returns true if the key was used.
    pub(super) fn edit_key(&mut self, event: &KeyEvent) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let m = st.mods;
        let (ctrl, alt, shift) = (m.control_key(), m.alt_key(), m.shift_key());
        let key = &event.logical_key;
        // Pressing a modifier on its own changes nothing.
        if matches!(
            key,
            Key::Named(
                NamedKey::Shift
                    | NamedKey::Control
                    | NamedKey::Alt
                    | NamedKey::AltGraph
                    | NamedKey::Super
                    | NamedKey::CapsLock
            )
        ) {
            return false;
        }
        if alt || m.super_key() {
            return false;
        }
        let focused = st.focused;
        let Some(p) = st.panes.iter_mut().find(|p| p.id == focused) else { return false };
        if !p.edit_ready() {
            p.kb_sel = None;
            return false;
        }
        let mv = match key {
            Key::Named(NamedKey::ArrowLeft) if shift => Some(if ctrl { Move::WordLeft } else { Move::Left }),
            Key::Named(NamedKey::ArrowRight) if shift => Some(if ctrl { Move::WordRight } else { Move::Right }),
            Key::Named(NamedKey::Home) if shift => Some(Move::Home),
            Key::Named(NamedKey::End) if shift => Some(Move::End),
            _ => None,
        };
        if let Some(mv) = mv {
            let used = p.extend_selection(mv);
            if used {
                st.blink_epoch = Instant::now();
                st.window.request_redraw();
            }
            return used;
        }
        if !p.has_selection() {
            return false;
        }
        let used = match key {
            Key::Named(NamedKey::ArrowLeft) if !ctrl && !shift => p.collapse_selection(false),
            Key::Named(NamedKey::ArrowRight) if !ctrl && !shift => p.collapse_selection(true),
            Key::Named(NamedKey::Backspace | NamedKey::Delete) if !ctrl && !shift => p.delete_selection(),
            Key::Character(c) if ctrl && !shift && c.eq_ignore_ascii_case("x") => {
                // Cut: copy, then delete.
                let text = p.term.lock().selection_to_string();
                if let (Some(text), Some(clipboard)) = (text, st.clipboard.as_mut()) {
                    let _ = clipboard.set_text(text);
                }
                p.delete_selection()
            }
            _ => {
                let typed =
                    !ctrl && event.text.as_deref().is_some_and(|t| !t.is_empty() && !t.chars().any(char::is_control));
                // Typing replaces the selection; anything else just ends it.
                if typed {
                    p.delete_selection();
                } else {
                    p.clear_selection();
                }
                false
            }
        };
        st.window.request_redraw();
        used
    }

    /// Backspace twice in a row at an empty prompt goes up a folder: `cd .. && ls`. The first
    /// press would do nothing there anyway, so it is swallowed (no bell). Returns true if consumed.
    pub(super) fn double_backspace(&mut self, event: &KeyEvent) -> bool {
        const WINDOW: Duration = Duration::from_millis(500);
        let Some(st) = self.state.as_mut() else { return false };
        let m = st.mods;
        let plain = !(m.control_key() || m.alt_key() || m.shift_key() || m.super_key());
        if !plain || event.repeat || !matches!(event.logical_key, Key::Named(NamedKey::Backspace)) {
            return false;
        }
        let focused = st.focused;
        let Some(p) = st.panes.iter_mut().find(|p| p.id == focused) else { return false };
        // Only at an idle, empty prompt, and with a known folder to fall back on.
        let Some(cwd) = p.cwd.clone().filter(|_| p.can_type() && !p.is_typing() && p.at_empty_prompt()) else {
            st.last_empty_backspace = None;
            return false;
        };
        let now = Instant::now();
        match st.last_empty_backspace.take() {
            Some(t) if now.duration_since(t) < WINDOW => {
                let parent = cwd.parent().map(|d| d.to_path_buf()).unwrap_or(cwd);
                p.start_typing("cd .. && ls".to_string(), Some(Target::Path(parent)));
                st.window.request_redraw();
            }
            _ => st.last_empty_backspace = Some(now),
        }
        true
    }

    /// Keys while the focused pane's search bar is open. Returns true if consumed.
    pub(super) fn search_key(&mut self, event: &KeyEvent) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let focused = st.focused;
        if !st.panes.iter().any(|p| p.id == focused && p.search.is_some()) {
            return false;
        }
        let (ctrl, alt, shift) = (st.mods.control_key(), st.mods.alt_key(), st.mods.shift_key());
        let ch = match &event.logical_key {
            Key::Character(s) => s.chars().next().map(|c| c.to_ascii_lowercase()),
            _ => None,
        };
        let pasted =
            if ctrl && !alt && ch == Some('v') { st.clipboard.as_mut().and_then(|c| c.get_text().ok()) } else { None };
        let Some(p) = st.panes.iter_mut().find(|p| p.id == focused) else { return false };
        let Some(search) = p.search.as_mut() else { return false };
        let mut close = false;
        {
            let mut term = p.term.lock();
            match &event.logical_key {
                Key::Named(NamedKey::Escape) => close = true,
                _ if ctrl && shift && ch == Some('f') => close = true,
                Key::Named(NamedKey::Enter) => search.step(&mut term, !shift),
                Key::Named(NamedKey::Backspace) if !alt => {
                    if ctrl {
                        // Delete the last word.
                        while search.query.ends_with(char::is_whitespace) {
                            search.query.pop();
                        }
                        while search.query.ends_with(|c: char| !c.is_whitespace()) {
                            search.query.pop();
                        }
                    } else {
                        search.query.pop();
                    }
                    search.update(&mut term);
                }
                _ if ctrl && !alt && ch == Some('v') => {
                    if let Some(text) = pasted {
                        let line = text.lines().next().unwrap_or("");
                        search.query.extend(line.chars().filter(|c| !c.is_control()));
                        search.update(&mut term);
                    }
                }
                _ if !ctrl && !alt => match event.text.as_deref() {
                    Some(t) if !t.is_empty() && !t.chars().any(char::is_control) => {
                        search.query.push_str(t);
                        search.update(&mut term);
                    }
                    // Other keys (arrows, Tab, ...) go to the shell as usual.
                    _ => return false,
                },
                _ => return false,
            }
        }
        if close {
            p.search = None;
        }
        st.blink_epoch = Instant::now();
        st.window.request_redraw();
        true
    }

    /// A key went down or up.
    pub(super) fn on_key(&mut self, event_loop: &ActiveEventLoop, event: KeyEvent) {
        if event.state != ElementState::Pressed {
            return;
        }
        if self.state.as_ref().unwrap().overlay.is_some() {
            self.overlay_key(event_loop, &event);
            return;
        }
        if self.review_key(event_loop, &event) {
            return;
        }
        if self.web_key(event_loop, &event) {
            return;
        }
        if self.chat_key(event_loop, &event) {
            return;
        }
        // The picker is modal: it takes every key while open.
        let st = self.state.as_mut().unwrap();
        if let Some(picker) = st.picker.as_mut().filter(|p| !p.closing) {
            if let Some(choice) = picker.key(&event, st.mods) {
                self.finish_picker(choice);
            }
            self.state.as_ref().unwrap().window.request_redraw();
            return;
        }
        if self.search_key(&event) {
            return;
        }
        if self.double_backspace(&event) {
            return;
        }
        if self.edit_key(&event) {
            return;
        }
        if self.shortcut(event_loop, &event) {
            return;
        }
        let st = self.state.as_mut().unwrap();
        let Some(p) = st.panes.iter().find(|p| p.id == st.focused) else { return };
        let mut term = p.term.lock();
        let mode = *term.mode();
        if let Some(bytes) = input::encode_key(&event, st.mods, mode) {
            term.scroll_display(Scroll::Bottom);
            term.selection = None;
            drop(term);
            p.write(bytes);
            st.blink_epoch = Instant::now();
            st.window.request_redraw();
        }
    }
}