rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The popups over the window: settings, the command palette, the link menu and the
//! session picker.

use super::*;

impl App {
    pub(super) fn open_settings(&mut self) {
        let settings = Settings::new(&self.config);
        if let Some(st) = self.state.as_mut() {
            st.overlay = Some(Overlay::Settings(Box::new(settings)));
            st.window.request_redraw();
        }
    }

    /// A change in the settings screen: save it and apply it at once.
    pub(super) fn apply_settings(&mut self, table: toml::Table) {
        match Config::from_table(table.clone()) {
            Ok(new) => {
                if let Err(e) = crate::config::save_table(&table) {
                    self.toast(e);
                }
                self.apply_config(new);
            }
            Err(e) => self.toast(e),
        }
    }

    /// Open the command palette: every action, plus the app-level commands.
    pub(super) fn open_palette(&mut self) {
        let mut entries: Vec<Entry> = Action::all()
            .filter(|a| !matches!(a, Action::Palette))
            .map(|a| Entry { label: a.label().to_string(), hint: self.keymap.describe(a), command: Command::Action(a) })
            .collect();
        for (label, command) in [
            ("Review a pull request, branch or commit", Command::Review),
            ("Review: try the demo pull request", Command::ReviewDemo),
            ("Reload the config file", Command::ReloadConfig),
            ("Open the config file", Command::OpenConfigFile),
            ("Restore the last session's layout", Command::RestoreSession),
            ("Open the folder of saved layouts", Command::OpenLayoutsFolder),
            ("Update rustimal (installs the newest version with cargo)", Command::Update),
        ] {
            entries.push(Entry { label: label.to_string(), hint: String::new(), command });
        }
        for name in crate::terminal::layouts::saved_names() {
            entries.push(Entry {
                label: format!("Layout: {name}"),
                hint: String::new(),
                command: Command::LoadLayout(name),
            });
        }
        if let Some(st) = self.state.as_mut() {
            st.overlay = Some(Overlay::Palette(CommandPalette::new(entries)));
            st.window.request_redraw();
        }
    }

    /// The right-click menu for a link.
    pub(super) fn open_link_menu(&mut self, pane: PaneId, link: &Link) {
        let path = links::path_of(&link.target).map(|p| p.to_path_buf());
        let item = MenuItem::new;
        let mut items = Vec::new();
        match &link.target {
            Target::Url(url) => {
                items.push(item("Open link", MenuAction::Open(link.target.clone())));
                items.push(item("Copy link", MenuAction::CopyText(url.clone())));
            }
            Target::Location { path, pos } => {
                items.push(item("Open in the editor", MenuAction::Open(link.target.clone())));
                items.push(item("Open with the default app", MenuAction::Open(Target::Path(path.clone()))));
                items.push(item("Show in Explorer", MenuAction::Reveal(path.clone())));
                let place = match pos.col {
                    Some(c) => format!("{}:{}:{c}", path.display(), pos.line),
                    None => format!("{}:{}", path.display(), pos.line),
                };
                items.push(item("Copy the path and line", MenuAction::CopyText(place)));
            }
            Target::Entry { path, .. } | Target::Path(path) => {
                let is_entry = matches!(link.target, Target::Entry { .. });
                let command = match &link.target {
                    Target::Entry { path, name } => links::entry_command(path, name),
                    _ => None,
                };
                if let (true, Some(cmd)) = (is_entry, command) {
                    let label =
                        if cmd.starts_with("cd") { "Go into the folder (cd and ls)" } else { "Print the file (cat)" };
                    items.push(item(label, MenuAction::Type(link.target.clone())));
                }
                let open = if path.is_dir() { "Open in Explorer" } else { "Open" };
                items.push(item(open, MenuAction::Open(Target::Path(path.clone()))));
                items.push(item("Show in Explorer", MenuAction::Reveal(path.clone())));
                items.push(item("Copy the path", MenuAction::CopyText(path.display().to_string())));
            }
        }
        drop(path);
        if let Some(st) = self.state.as_mut() {
            let at = st.mouse;
            st.overlay = Some(Overlay::Menu(Menu::new(pane, at, items)));
            st.window.request_redraw();
        }
    }

    pub(super) fn close_overlay(&mut self) {
        if let Some(st) = self.state.as_mut() {
            st.overlay = None;
            st.window.request_redraw();
        }
    }

    pub(super) fn run_menu_action(&mut self, pane: PaneId, action: MenuAction) {
        match action {
            MenuAction::Open(target) => self.open_target(pane, &target),
            MenuAction::Type(target) => self.activate_link(pane, &target),
            MenuAction::Reveal(path) => links::reveal(&path),
            MenuAction::CopyText(text) => {
                let ok =
                    self.state.as_mut().and_then(|st| st.clipboard.as_mut()).is_some_and(|c| c.set_text(text).is_ok());
                self.toast(if ok { "Copied" } else { "Could not copy to the clipboard" });
            }
        }
    }

    /// Keys while a popup is open: it takes all of them.
    pub(super) fn overlay_key(&mut self, event_loop: &ActiveEventLoop, event: &KeyEvent) {
        let Some(st) = self.state.as_mut() else { return };
        let mods = st.mods;
        let Some(overlay) = st.overlay.as_mut() else { return };
        match overlay {
            Overlay::Menu(menu) => {
                let pane = menu.pane;
                match menu.key(event) {
                    Outcome::Stay => st.window.request_redraw(),
                    Outcome::Close => self.close_overlay(),
                    Outcome::Pick(i) => {
                        let action = menu.items[i].action.clone();
                        self.close_overlay();
                        self.run_menu_action(pane, action);
                    }
                }
            }
            Overlay::Palette(palette) => match palette.key(event, mods) {
                Outcome::Stay => st.window.request_redraw(),
                Outcome::Close => self.close_overlay(),
                Outcome::Pick(command) => {
                    self.close_overlay();
                    self.run_command(event_loop, command);
                }
            },
            Overlay::Settings(settings) => {
                let outcome = settings.key(event, mods);
                let changed = settings.take_changed();
                st.window.request_redraw();
                if outcome == Outcome::Close {
                    self.close_overlay();
                }
                if let Some(table) = changed {
                    self.apply_settings(table);
                }
            }
        }
    }

    /// The pointer moved while a popup is open. Returns true if one is open.
    pub(super) fn overlay_hover(&mut self) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let (x, y) = st.mouse;
        let Some(overlay) = st.overlay.as_mut() else { return false };
        let moved = match overlay {
            Overlay::Menu(menu) => menu.hover(x, y),
            Overlay::Palette(palette) => palette.hover(x, y),
            Overlay::Settings(_) => false,
        };
        if moved {
            st.window.request_redraw();
        }
        true
    }

    /// A mouse button while a popup is open. Returns true if one is open (the click is theirs).
    pub(super) fn overlay_click(
        &mut self,
        event_loop: &ActiveEventLoop,
        button: MouseButton,
        state: ElementState,
    ) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let (x, y) = st.mouse;
        let Some(overlay) = st.overlay.as_mut() else { return false };
        if state != ElementState::Pressed {
            return true;
        }
        match overlay {
            Overlay::Menu(menu) => {
                let pane = menu.pane;
                let outcome = if button == MouseButton::Left { menu.click(x, y) } else { Outcome::Close };
                match outcome {
                    Outcome::Stay => {}
                    Outcome::Close => self.close_overlay(),
                    Outcome::Pick(i) => {
                        let action = menu.items[i].action.clone();
                        self.close_overlay();
                        self.run_menu_action(pane, action);
                    }
                }
            }
            Overlay::Palette(palette) => {
                let outcome = if button == MouseButton::Left { palette.click(x, y) } else { Outcome::Close };
                match outcome {
                    Outcome::Stay => {}
                    Outcome::Close => self.close_overlay(),
                    Outcome::Pick(command) => {
                        self.close_overlay();
                        self.run_command(event_loop, command);
                    }
                }
            }
            Overlay::Settings(settings) => {
                if button != MouseButton::Left {
                    return true;
                }
                let outcome = settings.click(x, y);
                let changed = settings.take_changed();
                st.window.request_redraw();
                if outcome == Outcome::Close {
                    self.close_overlay();
                }
                if let Some(table) = changed {
                    self.apply_settings(table);
                }
            }
        }
        true
    }

    /// Scroll a popup's list. Returns true if one is open.
    pub(super) fn overlay_wheel(&mut self, lines: f32) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let Some(overlay) = st.overlay.as_mut() else { return false };
        match overlay {
            Overlay::Palette(palette) => palette.wheel(lines),
            Overlay::Settings(settings) => settings.wheel(lines),
            Overlay::Menu(_) => {}
        }
        st.window.request_redraw();
        true
    }

    /// Send the picker result to the waiting `claude` shell function.
    pub(super) fn finish_picker(&mut self, choice: Choice) {
        let Some(st) = self.state.as_mut() else { return };
        let Some(picker) = st.picker.as_mut() else { return };
        picker.closing = true;
        let reply = match choice {
            Choice::New => "new\r".to_string(),
            Choice::Resume(id) => format!("{id}\r"),
            Choice::Cancel => "\r".to_string(),
        };
        if let Some(p) = st.panes.iter().find(|p| p.id == picker.pane) {
            p.write(reply.into_bytes());
        }
        st.window.request_redraw();
    }

    /// Mouse handling while the picker is open. Returns true if consumed.
    pub(super) fn picker_mouse(&mut self, pressed: Option<MouseButton>, wheel: f32) -> bool {
        let Some(st) = self.state.as_mut() else { return false };
        let (x, y) = st.mouse;
        let Some(picker) = st.picker.as_mut().filter(|p| !p.closing) else { return false };
        let row = picker.row_at(x, y);
        if wheel != 0.0 {
            let rows = picker.rows();
            picker.selected =
                if wheel > 0.0 { picker.selected.saturating_sub(1) } else { (picker.selected + 1).min(rows - 1) };
            st.window.request_redraw();
            return true;
        }
        match pressed {
            None => {
                if let Some(r) = row
                    && r != picker.selected
                {
                    picker.selected = r;
                    st.window.request_redraw();
                }
                false
            }
            Some(MouseButton::Left) => {
                if let Some(r) = row {
                    picker.selected = r;
                    let choice = picker.choice();
                    self.finish_picker(choice);
                } else if !picker.card.contains(x, y) {
                    self.finish_picker(Choice::Cancel);
                }
                true
            }
            Some(_) => true,
        }
    }
}