rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The review panel in the window. It is an embed like the others: it takes a pane's
//! place, over its shell, so splitting, moving between panes, resizing, zooming and the
//! key that switches to the terminal all work on it as on anything else. This is which keys
//! and clicks are its own, and carrying out what it asks for. The panel itself is in
//! `review_ui`.

use std::path::PathBuf;

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

use super::App;
use crate::config::keys::{Action, Chord};
use crate::review_ui::{self, Job, Message, Request, ReviewView};
use crate::terminal::embeds::Embed;
use crate::terminal::events::UserEvent;
use crate::terminal::layout::PaneId;
use crate::terminal::links::{Pos, Target};
use crate::ui::settings::Input;

impl App {
    /// Does this pane show a review instead of its terminal?
    pub(super) fn review_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.review.as_ref().is_some_and(|v| !v.hidden))
    }

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

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

    /// Open the panel over a pane on a job, for the folder its shell is in.
    pub(super) fn open_review(&mut self, pane: PaneId, cwd: PathBuf, job: Job) {
        let results = crate::config::state_dir().map(|d| d.join("reviews"));
        let Some(st) = self.state.as_mut() else { return };
        let Some(p) = st.panes.iter_mut().find(|p| p.id == pane) else { return };
        match p.review.as_mut() {
            Some(view) => {
                view.cwd = cwd;
                view.start(job);
            }
            None => p.review = Some(Box::new(ReviewView::new(cwd, job, results))),
        }
        st.picker = None;
        st.overlay = None;
        self.show_review(pane);
        self.start_review_job(pane);
    }

    /// Put the pane's review in front of everything else the pane has.
    pub(super) fn show_review(&mut self, pane: PaneId) {
        let Some(st) = self.state.as_mut() else { return };
        let Some(p) = st.panes.iter_mut().find(|p| p.id == pane) else { return };
        let Some(view) = p.review.as_mut() else { return };
        view.hidden = false;
        if let Some(chat) = p.chat.as_mut() {
            chat.hidden = true;
        }
        p.embeds.shown(Embed::Review);
        st.web.hide(pane);
        self.review_changed();
    }

    /// Back to the pane's terminal, keeping the review as it is.
    fn hide_review(&mut self, pane: PaneId) {
        if let Some(view) = self.review_mut(pane) {
            view.hidden = true;
            view.blur();
        }
        self.review_changed();
    }

    /// Close the review a pane is showing, leaving the pane and its shell. Returns false if
    /// the pane shows none.
    pub(super) fn close_review(&mut self, pane: PaneId) -> bool {
        if !self.review_shows(pane) {
            return false;
        }
        // Something on its way to the host still has an answer to give.
        if self.review_mut(pane).is_some_and(|v| v.working()) {
            self.hide_review(pane);
            self.toast("Still waiting for the host, so the review is only put away");
            return true;
        }
        if let Some(p) = self.state.as_mut().and_then(|st| st.panes.iter_mut().find(|p| p.id == pane)) {
            p.review = None;
            p.embeds.closed(Embed::Review);
        }
        self.review_changed();
        true
    }

    fn start_review_job(&mut self, pane: PaneId) {
        let proxy = self.proxy.clone();
        let Some(view) = self.review_mut(pane) else { return };
        review_ui::spawn(view.job.clone(), view.cwd.clone(), view.number, move |message| {
            let _ = proxy.send_event(UserEvent::Review(pane, Box::new(message)));
        });
    }

    pub(super) fn review_message(&mut self, pane: PaneId, message: Message) {
        self.web_window_focus();
        if let Some(view) = self.review_mut(pane) {
            view.receive(message);
            if let Some(st) = self.state.as_ref() {
                st.window.request_redraw();
            }
        }
    }

    fn open_here(&mut self, job: Job) {
        let Some(st) = self.state.as_ref() else { return };
        let pane = st.focused;
        let cwd = st
            .panes
            .iter()
            .find(|p| p.id == pane)
            .and_then(|p| p.cwd.clone())
            .or_else(|| self.start_dir.clone())
            .unwrap_or_else(|| PathBuf::from("."));
        self.open_review(pane, cwd, job);
    }

    pub(super) fn open_review_list(&mut self) {
        self.open_here(Job::List);
    }

    pub(super) fn open_git_workspace(&mut self) {
        self.open_here(Job::Git(review_ui::GitJob::Read));
    }

    pub(super) fn open_review_demo(&mut self) {
        self.open_here(Job::Open(vec!["demo".to_string()]));
    }

    /// `review ...` or `pr` typed in a shell. No arguments means the list.
    pub(super) fn shell_review(&mut self, pane: PaneId, cwd: PathBuf, args: &str) {
        let args: Vec<String> = args.split_whitespace().map(str::to_string).collect();
        let job = if args.first().is_some_and(|a| a == "--new") {
            let named = args.get(1).map(|name| crate::review::propose::Of { name: name.clone(), base: None });
            Job::Propose(named)
        } else if args == ["--git"] {
            Job::Git(review_ui::GitJob::Read)
        } else if args.is_empty() {
            Job::List
        } else {
            Job::Open(args)
        };
        self.open_review(pane, cwd, job);
    }

    /// The shortcut: switch the focused pane between its review and its terminal, or start
    /// one with the list of what there is to review.
    pub(super) fn toggle_review(&mut self) {
        let Some(st) = self.state.as_ref() else { return };
        let pane = st.focused;
        if self.review_shows(pane) {
            self.hide_review(pane);
        } else if self.review_mut(pane).is_some() {
            self.show_review(pane);
        } else {
            self.open_review_list();
        }
    }

    /// A key while the focused pane shows a review. Window shortcuts keep working; nothing
    /// reaches the hidden shell.
    pub(super) fn review_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.review_shows(pane) {
            return false;
        }
        let action = Chord::from_event(event, mods).and_then(|c| self.keymap.get(&c));
        match action {
            Some(Action::Paste) => {
                let text = self.state.as_mut().and_then(|st| st.clipboard.as_mut()).and_then(|c| c.get_text().ok());
                if let Some(text) = text
                    && let Some(view) = self.review_mut(pane)
                {
                    view.paste(&text);
                    self.review_changed();
                }
                return true;
            }
            // These are about the terminal underneath.
            Some(Action::Copy | Action::SmartCopy | Action::SelectAll | Action::Find | Action::CopyOutput) => {
                return true;
            }
            Some(action)
                if mods.intersects(ModifiersState::CONTROL | ModifiersState::ALT) || action == Action::Review =>
            {
                // A first press does not stay armed while something else is done.
                if !matches!(action, Action::FontBigger | Action::FontSmaller | Action::FontReset)
                    && let Some(view) = self.review_mut(pane)
                {
                    view.blur();
                }
                self.shortcut(event_loop, event);
                return true;
            }
            _ => {}
        }
        let Some(input) = Input::from_event(event, mods) else { return true };
        let Some(view) = self.review_mut(pane) else { return true };
        view.focused = true;
        // A key held down must not both ask and confirm.
        if event.repeat && view.ignores_repeat(&input) {
            return true;
        }
        let request = view.input(input);
        self.review_changed();
        self.review_request(pane, request);
        true
    }

    /// The pane showing a review under the pointer, unless a drag that began in a terminal
    /// is going on.
    fn review_under_pointer(&self) -> Option<PaneId> {
        let st = self.state.as_ref()?;
        if st.selecting.is_some() || st.cmd_drag.is_some() || st.mouse_reporting.is_some() {
            return None;
        }
        let (x, y) = st.mouse;
        self.pane_at(x, y).filter(|&id| self.review_shows(id))
    }

    /// The pointer moved. Returns true if it is over a review.
    pub(super) fn review_hover(&mut self) -> bool {
        let over = self.review_under_pointer();
        let Some(st) = self.state.as_mut() else { return false };
        let mouse = st.mouse;
        let mut pointing = false;
        let mut changed = false;
        let was_over = st.panes.iter().any(|p| p.review.as_ref().is_some_and(|v| v.mouse.0 >= 0.0));
        for p in st.panes.iter_mut() {
            let Some(view) = p.review.as_mut() else { continue };
            let before = view.click_at(view.mouse.0, view.mouse.1);
            view.mouse = if over == Some(p.id) { mouse } else { (-1.0, -1.0) };
            let after = view.click_at(view.mouse.0, view.mouse.1);
            changed |= before != after;
            pointing |= over == Some(p.id) && after.is_some();
        }
        if changed {
            st.window.request_redraw();
        }
        // The window's edges keep their resizing pointer.
        let on_edge = st.hover != super::Hit::None;
        if over.is_some() && !on_edge {
            st.hover_link = None;
            st.window.set_cursor(if pointing { CursorIcon::Pointer } else { CursorIcon::Default });
        } else if over.is_none() && was_over && !on_edge {
            // Back over a terminal, which only changes the pointer when a link does.
            st.window.set_cursor(CursorIcon::Text);
        }
        over.is_some() && !on_edge
    }

    /// A mouse button over a review: it focuses the pane. Returns true if there is a
    /// review under the pointer.
    pub(super) fn review_click(&mut self, button: MouseButton, state: ElementState) -> bool {
        let Some(pane) = self.review_under_pointer() else { return false };
        if state != ElementState::Pressed {
            return true;
        }
        let Some(st) = self.state.as_mut() else { return true };
        let (x, y) = st.mouse;
        if st.focused != pane {
            let prev = st.focused;
            st.focused = pane;
            super::notify_focus(st, prev);
        }
        self.review_changed();
        if button == MouseButton::Left
            && let Some(view) = self.review_mut(pane)
        {
            view.focused = true;
            view.mouse = (x, y);
            let request = view.click(x, y);
            self.review_request(pane, request);
        }
        true
    }

    /// The wheel, in lines. Returns true if there is a review under the pointer.
    pub(super) fn review_wheel(&mut self, lines: f32) -> bool {
        let Some(pane) = self.review_under_pointer() else { return false };
        let Some(st) = self.state.as_ref() else { return false };
        let (mouse, step) = (st.mouse, st.glyphs.cell_h * 3.0);
        if let Some(view) = self.review_mut(pane) {
            view.mouse = mouse;
            view.scroll_by(-lines * step);
            if let Some(st) = self.state.as_ref() {
                st.window.request_redraw();
            }
        }
        true
    }

    /// A file dropped on a pane that shows a review: its path goes where one is typing.
    pub(super) fn review_drop(&mut self, pane: PaneId, path: &std::path::Path) -> bool {
        if !self.review_shows(pane) {
            return false;
        }
        if let Some(view) = self.review_mut(pane) {
            view.paste(&path.to_string_lossy());
        }
        self.review_changed();
        true
    }

    fn review_request(&mut self, pane: PaneId, request: Request) {
        match request {
            Request::Nothing => {}
            Request::Close => {
                self.close_review(pane);
            }
            Request::Hide => self.hide_review(pane),
            Request::Load => self.start_review_job(pane),
            Request::Copy(text, message) => {
                let copied = self.copy_text(text);
                self.toast(if copied { message } else { "Could not copy to the clipboard".to_string() });
            }
            Request::Type(command) => self.type_from_review(pane, command),
            // In VS Code this takes the review's place in the pane; the review's key
            // brings it back.
            Request::OpenFile(path, line) => {
                self.open_target(pane, &Target::Location { path, pos: Pos { line, col: None } });
            }
            Request::OpenUrl(url) => crate::terminal::links::open(&Target::Url(url), &self.config.editor),
            Request::Create(proposal) => {
                let proxy = self.proxy.clone();
                if let Some(view) = self.review_mut(pane) {
                    review_ui::spawn_create(*proposal, view.number, move |message| {
                        let _ = proxy.send_event(UserEvent::Review(pane, Box::new(message)));
                    });
                }
            }
            Request::Merge(root, pull, head, how) => {
                let proxy = self.proxy.clone();
                if let Some(view) = self.review_mut(pane) {
                    review_ui::spawn_merge(root, pull, head, how, view.number, move |message| {
                        let _ = proxy.send_event(UserEvent::Review(pane, Box::new(message)));
                    });
                }
            }
            Request::Approve(root, pull, head) => {
                let proxy = self.proxy.clone();
                if let Some(view) = self.review_mut(pane) {
                    review_ui::spawn_approve(root, pull, head, view.number, move |message| {
                        let _ = proxy.send_event(UserEvent::Review(pane, Box::new(message)));
                    });
                }
            }
        }
    }

    fn copy_text(&mut self, text: String) -> bool {
        self.state.as_mut().and_then(|st| st.clipboard.as_mut()).is_some_and(|c| c.set_text(text).is_ok())
    }

    /// Put a command at the prompt under the review, for the person to read and run. Only
    /// at an empty prompt: anywhere else it would land in a program or in a half-typed line.
    fn type_from_review(&mut self, pane: PaneId, command: String) {
        let ready = self
            .state
            .as_ref()
            .and_then(|st| st.panes.iter().find(|p| p.id == pane))
            .is_some_and(|p| p.can_type() && p.at_empty_prompt());
        if !ready {
            let copied = self.copy_text(command);
            self.toast(if copied {
                "The terminal is not at an empty prompt, so the command was copied instead"
            } else {
                "The terminal is not at an empty prompt"
            });
            return;
        }
        self.hide_review(pane);
        if let Some(st) = self.state.as_ref()
            && let Some(pane) = st.panes.iter().find(|p| p.id == pane)
        {
            pane.term.lock().scroll_display(alacritty_terminal::grid::Scroll::Bottom);
            pane.write(command.into_bytes());
        }
        let keys = self.keymap.describe(Action::Review);
        self.toast(format!("Typed, not run: press Enter. {keys} brings the review back"));
    }
}