rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Popups drawn over the window: the right-click menu on links and the command palette.
//! This is their state and input handling; `overlay_draw.rs` draws them.

use std::path::PathBuf;

use winit::event::KeyEvent;
use winit::keyboard::{Key, ModifiersState, NamedKey};

use crate::keys::Action;
use crate::layout::{PaneId, Rect};
use crate::links::Target;

/// What a popup wants done after an event.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Outcome<T> {
    /// Nothing; keep the popup open.
    Stay,
    Close,
    /// An item was chosen. The popup closes.
    Pick(T),
}

pub enum Overlay {
    Menu(Menu),
    Palette(Palette),
    Settings(Box<crate::settings::Settings>),
}

// --------------------------------------------------------------------------------------- menu

#[derive(Clone, Debug)]
pub enum MenuAction {
    Open(Target),
    /// Type the command for a listing entry (`cd` into a folder, `cat` a file).
    Type(Target),
    CopyText(String),
    Reveal(PathBuf),
}

#[derive(Clone, Debug)]
pub struct MenuItem {
    pub label: String,
    pub enabled: bool,
    pub action: MenuAction,
}

impl MenuItem {
    pub fn new(label: impl Into<String>, action: MenuAction) -> Self {
        Self { label: label.into(), enabled: true, action }
    }
}

pub struct Menu {
    pub pane: PaneId,
    /// Where the pointer was; the menu opens there.
    pub at: (f32, f32),
    pub items: Vec<MenuItem>,
    pub selected: usize,
    /// Where it was drawn, for hit-testing. Set by the drawing code.
    pub rect: Rect,
    pub row_h: f32,
}

impl Menu {
    pub fn new(pane: PaneId, at: (f32, f32), items: Vec<MenuItem>) -> Self {
        let selected = items.iter().position(|i| i.enabled).unwrap_or(0);
        Self { pane, at, items, selected, rect: Rect::default(), row_h: 1.0 }
    }

    fn step(&mut self, down: bool) {
        let n = self.items.len();
        for k in 1..=n {
            let i = if down { (self.selected + k) % n } else { (self.selected + n - k % n) % n };
            if self.items[i].enabled {
                self.selected = i;
                return;
            }
        }
    }

    pub fn key(&mut self, event: &KeyEvent) -> Outcome<usize> {
        match &event.logical_key {
            Key::Named(NamedKey::Escape) => Outcome::Close,
            Key::Named(NamedKey::ArrowDown | NamedKey::Tab) => {
                self.step(true);
                Outcome::Stay
            }
            Key::Named(NamedKey::ArrowUp) => {
                self.step(false);
                Outcome::Stay
            }
            Key::Named(NamedKey::Enter) if self.items.get(self.selected).is_some_and(|i| i.enabled) => {
                Outcome::Pick(self.selected)
            }
            _ => Outcome::Stay,
        }
    }

    /// The item under a point.
    pub fn row_at(&self, x: f32, y: f32) -> Option<usize> {
        if !self.rect.contains(x, y) || self.row_h <= 0.0 {
            return None;
        }
        let i = ((y - self.rect.y) / self.row_h).floor();
        (i >= 0.0 && (i as usize) < self.items.len()).then_some(i as usize)
    }

    /// Returns true if the highlight moved.
    pub fn hover(&mut self, x: f32, y: f32) -> bool {
        match self.row_at(x, y) {
            Some(i) if self.items[i].enabled && i != self.selected => {
                self.selected = i;
                true
            }
            _ => false,
        }
    }

    pub fn click(&mut self, x: f32, y: f32) -> Outcome<usize> {
        if !self.rect.contains(x, y) {
            return Outcome::Close;
        }
        match self.row_at(x, y) {
            Some(i) if self.items[i].enabled => Outcome::Pick(i),
            _ => Outcome::Stay,
        }
    }
}

// ------------------------------------------------------------------------------------ palette

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Command {
    Action(Action),
    Review,
    ReviewDemo,
    ReloadConfig,
    OpenConfigFile,
    SaveLayout(String),
    LoadLayout(String),
    RestoreSession,
    OpenLayoutsFolder,
    Update,
}

#[derive(Clone, Debug)]
pub struct Entry {
    pub label: String,
    /// What to show on the right: the shortcut, say.
    pub hint: String,
    pub command: Command,
}

/// Does `query` match `text` as a subsequence (case and spaces ignored)? Higher is better:
/// runs of consecutive letters and matches at the start of words score more.
pub fn fuzzy_score(query: &str, text: &str) -> Option<i32> {
    let q: Vec<char> = query.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect();
    if q.is_empty() {
        return Some(0);
    }
    let t: Vec<char> = text.chars().flat_map(char::to_lowercase).collect();
    let (mut score, mut qi, mut prev_hit) = (0, 0, false);
    for (i, &c) in t.iter().enumerate() {
        if qi < q.len() && c == q[qi] {
            score += 1;
            if prev_hit {
                score += 3;
            }
            if i == 0 || !t[i - 1].is_alphanumeric() {
                score += 4;
            }
            qi += 1;
            prev_hit = true;
        } else {
            prev_hit = false;
        }
    }
    (qi == q.len()).then_some(score - (t.len() as i32) / 8)
}

pub struct Palette {
    pub query: String,
    entries: Vec<Entry>,
    pub shown: Vec<Entry>,
    pub selected: usize,
    pub scroll: usize,
    /// Set by the drawing code, for hit-testing and scrolling.
    pub card: Rect,
    pub list: Rect,
    pub row_h: f32,
    pub visible: usize,
}

impl Palette {
    pub fn new(entries: Vec<Entry>) -> Self {
        let mut p = Self {
            query: String::new(),
            entries,
            shown: Vec::new(),
            selected: 0,
            scroll: 0,
            card: Rect::default(),
            list: Rect::default(),
            row_h: 1.0,
            visible: 8,
        };
        p.refilter();
        p
    }

    /// Recompute the list for the current query. A query that isn't empty also offers to save
    /// the layout under that name.
    pub fn refilter(&mut self) {
        let mut scored: Vec<(i32, usize)> = self
            .entries
            .iter()
            .enumerate()
            .filter_map(|(i, e)| fuzzy_score(&self.query, &e.label).map(|s| (s, i)))
            .collect();
        scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
        self.shown = scored.into_iter().map(|(_, i)| self.entries[i].clone()).collect();
        let name = self.query.trim();
        if !name.is_empty() {
            self.shown.push(Entry {
                label: format!("Save the layout as \u{201c}{name}\u{201d}"),
                hint: String::new(),
                command: Command::SaveLayout(name.to_string()),
            });
        }
        self.selected = 0;
        self.scroll = 0;
    }

    fn keep_selection_visible(&mut self) {
        if self.selected < self.scroll {
            self.scroll = self.selected;
        } else if self.selected >= self.scroll + self.visible {
            self.scroll = self.selected + 1 - self.visible;
        }
    }

    pub fn move_selection(&mut self, by: isize) {
        let n = self.shown.len() as isize;
        if n > 0 {
            self.selected = (self.selected as isize + by).clamp(0, n - 1) as usize;
            self.keep_selection_visible();
        }
    }

    pub fn key(&mut self, event: &KeyEvent, mods: ModifiersState) -> Outcome<Command> {
        match &event.logical_key {
            Key::Named(NamedKey::Escape) => return Outcome::Close,
            Key::Named(NamedKey::ArrowDown) => self.move_selection(1),
            Key::Named(NamedKey::ArrowUp) => self.move_selection(-1),
            Key::Named(NamedKey::PageDown) => self.move_selection(self.visible as isize),
            Key::Named(NamedKey::PageUp) => self.move_selection(-(self.visible as isize)),
            Key::Named(NamedKey::Home) => self.move_selection(isize::MIN / 2),
            Key::Named(NamedKey::End) => self.move_selection(isize::MAX / 2),
            Key::Named(NamedKey::Enter) => {
                if let Some(entry) = self.shown.get(self.selected) {
                    return Outcome::Pick(entry.command.clone());
                }
            }
            Key::Named(NamedKey::Backspace) => {
                if mods.control_key() {
                    self.query.clear();
                } else {
                    self.query.pop();
                }
                self.refilter();
            }
            _ => {
                if !mods.control_key()
                    && !mods.alt_key()
                    && let Some(text) = event.text.as_deref()
                    && !text.is_empty()
                    && !text.chars().any(char::is_control)
                {
                    self.query.push_str(text);
                    self.refilter();
                }
            }
        }
        Outcome::Stay
    }

    pub fn row_at(&self, x: f32, y: f32) -> Option<usize> {
        if !self.list.contains(x, y) || self.row_h <= 0.0 {
            return None;
        }
        let i = self.scroll + ((y - self.list.y) / self.row_h).floor() as usize;
        (i < self.shown.len() && i < self.scroll + self.visible).then_some(i)
    }

    pub fn hover(&mut self, x: f32, y: f32) -> bool {
        match self.row_at(x, y) {
            Some(i) if i != self.selected => {
                self.selected = i;
                true
            }
            _ => false,
        }
    }

    pub fn click(&mut self, x: f32, y: f32) -> Outcome<Command> {
        if let Some(i) = self.row_at(x, y) {
            return Outcome::Pick(self.shown[i].command.clone());
        }
        if self.card.contains(x, y) { Outcome::Stay } else { Outcome::Close }
    }

    pub fn wheel(&mut self, lines: f32) {
        let max_scroll = self.shown.len().saturating_sub(self.visible);
        let by = if lines > 0.0 { -1 } else { 1 };
        self.scroll = (self.scroll as isize + by).clamp(0, max_scroll as isize) as usize;
        self.selected = self.selected.clamp(self.scroll, (self.scroll + self.visible).saturating_sub(1));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entries() -> Vec<Entry> {
        ["Split right", "Split down", "Settings", "Copy the last command's output", "Zoom the pane"]
            .into_iter()
            .map(|l| Entry { label: l.to_string(), hint: String::new(), command: Command::LoadLayout(l.to_string()) })
            .collect()
    }

    #[test]
    fn fuzzy_matching() {
        assert!(fuzzy_score("", "anything").is_some());
        assert!(fuzzy_score("spr", "Split right").is_some());
        assert!(fuzzy_score("split r", "Split right").is_some(), "spaces are ignored");
        assert!(fuzzy_score("SET", "Settings").is_some(), "case is ignored");
        assert!(fuzzy_score("xyz", "Settings").is_none());
        // Letters in order, but they have to be there.
        assert!(fuzzy_score("tsp", "Split right").is_none());
        // Consecutive letters at the start of a word beat scattered ones.
        let tight = fuzzy_score("set", "Settings").unwrap();
        let loose = fuzzy_score("set", "Scroll a page to the end").unwrap();
        assert!(tight > loose, "{tight} vs {loose}");
    }

    #[test]
    fn palette_filters_orders_and_offers_to_save() {
        let mut p = Palette::new(entries());
        assert_eq!(p.shown.len(), 5, "everything shows with an empty query");
        p.query = "spl".to_string();
        p.refilter();
        let labels: Vec<_> = p.shown.iter().map(|e| e.label.as_str()).collect();
        assert_eq!(&labels[..2], ["Split right", "Split down"]);
        assert!(labels.last().unwrap().starts_with("Save the layout as"));
        assert_eq!(p.shown.last().unwrap().command, Command::SaveLayout("spl".to_string()));
        p.query = "zzzz".to_string();
        p.refilter();
        assert_eq!(p.shown.len(), 1, "only the save offer is left");
    }

    #[test]
    fn palette_selection_scrolls_and_stays_in_range() {
        let many: Vec<Entry> = (0..30)
            .map(|i| Entry { label: format!("item {i}"), hint: String::new(), command: Command::LoadLayout(i.to_string()) })
            .collect();
        let mut p = Palette::new(many);
        p.visible = 8;
        p.move_selection(-5);
        assert_eq!((p.selected, p.scroll), (0, 0));
        p.move_selection(9);
        assert_eq!(p.selected, 9);
        assert_eq!(p.scroll, 2, "the selection stays on screen");
        p.move_selection(1000);
        assert_eq!(p.selected, 29);
        assert_eq!(p.scroll, 22);
        p.move_selection(isize::MIN / 2);
        assert_eq!((p.selected, p.scroll), (0, 0));
    }

    #[test]
    fn menu_skips_disabled_items_and_hit_tests() {
        let item = |l: &str, on: bool| MenuItem { label: l.into(), enabled: on, action: MenuAction::CopyText(l.into()) };
        let mut m = Menu::new(1, (10.0, 10.0), vec![item("a", false), item("b", true), item("c", false), item("d", true)]);
        assert_eq!(m.selected, 1, "starts on the first enabled item");
        m.step(true);
        assert_eq!(m.selected, 3);
        m.step(true);
        assert_eq!(m.selected, 1, "wraps around");
        m.step(false);
        assert_eq!(m.selected, 3);
        m.rect = Rect::new(100.0, 100.0, 200.0, 4.0 * 20.0);
        m.row_h = 20.0;
        assert_eq!(m.row_at(150.0, 100.0 + 2.0 * 20.0 + 1.0), Some(2));
        assert_eq!(m.row_at(50.0, 150.0), None);
        assert_eq!(m.click(50.0, 50.0), Outcome::Close, "a click outside closes it");
        assert_eq!(m.click(150.0, 100.0 + 20.0 + 1.0), Outcome::Pick(1));
        assert_eq!(m.click(150.0, 100.0 + 2.0 * 20.0 + 1.0), Outcome::Stay, "disabled");
    }
}