rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The panel's list of everything that can be done right now, with the key for each. It
//! works like the command palette: type to narrow it, arrows to choose, enter to run.

use super::{Click, Opened, Tab, Thing};
use crate::review::forge::Method;
use crate::review::guide::Kind as StageKind;
use crate::review::session::{self, Seen, Verdict};

#[derive(Default)]
pub struct Menu {
    pub query: String,
    /// Among the entries the query leaves.
    pub selected: usize,
    /// How far the list is scrolled; the drawing code keeps the selection in it.
    pub scroll: f32,
}

pub struct Action {
    pub group: &'static str,
    pub label: String,
    /// The key that does the same without the list, if there is one.
    pub key: String,
    pub click: Click,
}

fn action(group: &'static str, label: impl Into<String>, key: &str, click: Click) -> Action {
    Action { group, label: label.into(), key: key.to_string(), click }
}

impl Opened {
    /// The command quoted by the chosen step, or else the first thing it quotes: (text, is
    /// it a command).
    pub(super) fn quoted_here(&self) -> Option<(String, bool)> {
        if self.tab != Tab::Guide {
            return None;
        }
        let quoted = session::quoted(&self.current()?.text);
        let command = quoted.iter().find(|q| session::is_command(q));
        command.map(|c| (c.clone(), true)).or_else(|| quoted.first().map(|q| (q.clone(), false)))
    }

    /// The command that switches the working copy to the change, while that is wanted.
    pub(super) fn checkout_here(&self) -> Option<String> {
        let setup = self.stages.get(self.stage).is_some_and(|s| s.kind == StageKind::Setup);
        let asked = self.tab == Tab::Findings || (self.tab == Tab::Guide && setup);
        self.change.checkout.clone().filter(|_| asked && !self.change.checked_out)
    }

    /// The keys that act on the checkout command, as (type, copy). A step with a command
    /// of its own keeps them.
    pub(super) fn checkout_keys(&self) -> (&'static str, &'static str) {
        if self.checkout_here().is_none() {
            return ("", "");
        }
        match self.quoted_here() {
            None => ("t", "c"),
            Some((_, false)) => ("t", ""),
            Some((_, true)) => ("", ""),
        }
    }

    /// The finding behind what is chosen on the guide.
    pub(super) fn finding_here(&self) -> Option<usize> {
        match (self.tab, self.thing()?) {
            (Tab::Guide, Thing::Item(i)) => self.items.get(i)?.findings.first().copied(),
            (Tab::Guide, Thing::File(f)) => self.findings_in(&self.change.files.get(f)?.path).first().copied(),
            _ => None,
        }
    }

    /// The step on the guide that deals with a finding.
    pub(super) fn step_for(&self, finding: usize) -> Option<usize> {
        self.items.iter().position(|i| i.findings.contains(&finding))
    }

    /// Everything that can be done right now, what is chosen first.
    pub fn actions(&self) -> Vec<Action> {
        let mut all = Vec::new();
        match (self.tab, self.thing()) {
            (Tab::Guide, Some(Thing::File(f))) => {
                const HERE: &str = "This file";
                let read = self.change.files.get(f).is_some_and(|file| self.session.seen(file) == Seen::Yes);
                all.push(action(HERE, if read { "Mark as unread" } else { "Mark as read" }, "v", Click::Seen(f)));
                all.push(action(
                    HERE,
                    if self.file_open { "Hide the diff" } else { "Show the diff" },
                    "x",
                    Click::ChangedFile(f),
                ));
            }
            (Tab::Guide, Some(Thing::Item(_))) => {
                const HERE: &str = "This step";
                let check = self.current().is_some_and(|i| i.check);
                let (pass, fail) = if check { ("Looks fine", "Problem") } else { ("Pass", "Fail") };
                all.push(action(HERE, pass, "p", Click::Verdict(Verdict::Passed)));
                all.push(action(HERE, fail, "f", Click::Verdict(Verdict::Failed)));
                all.push(action(HERE, "Skip", "s", Click::Verdict(Verdict::Skipped)));
                if self.current().is_some_and(|i| self.session.record(&i.id).is_some()) {
                    all.push(action(HERE, "Write a note", "e", Click::EditNote));
                    all.push(action(HERE, "Clear the result", "u", Click::Clear));
                }
                if let Some((text, command)) = self.quoted_here() {
                    all.push(action(HERE, format!("Copy: {text}"), "c", Click::Copy(text.clone())));
                    if command {
                        all.push(action(HERE, format!("Type in the terminal: {text}"), "t", Click::Type(text)));
                    }
                }
            }
            (Tab::Findings, _) if !self.change.report.findings.is_empty() => {
                const HERE: &str = "This finding";
                let label = if self.unfolded { "Fold" } else { "Unfold" };
                all.push(action(HERE, label, "enter", Click::Finding(self.finding)));
                if let Some(step) = self.step_for(self.finding) {
                    all.push(action(HERE, "Go to its step in the guide", "space", Click::Step(step)));
                }
            }
            _ => {}
        }
        if let Some((file, line)) = self.current_place().filter(|_| self.tab != Tab::Description) {
            let name = file.rsplit('/').next().unwrap_or(&file).to_string();
            all.push(action("Open", format!("Open {name} at line {line}"), "o", Click::File(file, line)));
        }
        if let Some(k) = self.finding_here() {
            all.push(action("Open", "Show the finding behind this", "d", Click::Finding(k)));
        }
        if let Some(url) = &self.change.url {
            let key = if self.tab == Tab::Description { "o" } else { "" };
            all.push(action("Open", "Open in the browser", key, Click::Url(url.clone())));
        }
        if let Some(command) = self.change.checkout.clone().filter(|_| !self.change.checked_out) {
            let key = self.checkout_keys();
            all.push(action("Switch to this change", format!("Type: {command}"), key.0, Click::Type(command.clone())));
            all.push(action("Switch to this change", "Copy the checkout command", key.1, Click::Copy(command)));
        }

        const REVIEW: &str = "Review";
        if self.change.pull.is_some() {
            if !self.session.approved() {
                let label = if self.confirm_approve { "Really approve?" } else { "Approve" };
                all.push(action(REVIEW, label, "a", Click::Approve));
            }
            if !self.merged {
                for (how, key, label, again) in [
                    (Method::Squash, "q", "Squash and merge", "Really squash and merge?"),
                    (Method::Commit, "g", "Merge", "Really merge?"),
                ] {
                    let label = if self.confirm_merge == Some(how) { again } else { label };
                    all.push(action(REVIEW, label, key, Click::Merge(how)));
                }
            }
        }
        if self.change.branch.is_some() {
            all.push(action(REVIEW, "Open a pull request for this branch", "m", Click::Propose));
        }
        if !self.items.is_empty() {
            all.push(action(REVIEW, "Copy the results as Markdown", "y", Click::CopyResults));
            let label = if self.confirm_reset { "Really forget every result?" } else { "Forget every result" };
            all.push(action(REVIEW, label, "", Click::Reset));
        }

        const GO: &str = "Go to";
        all.push(action(GO, "Next thing still to do", "n", Click::Continue));
        for (i, stage) in self.stages.iter().enumerate() {
            let (done, total) = self.stage_counts(i);
            let count = if total > 0 { format!("  {done}/{total}") } else { String::new() };
            let key = if i < 9 { (i + 1).to_string() } else { String::new() };
            all.push(action(GO, format!("Stage: {}{count}", stage.title), &key, Click::Stage(i)));
        }
        for (tab, label) in
            [(Tab::Guide, "Guide tab"), (Tab::Findings, "Findings tab"), (Tab::Description, "Description tab")]
        {
            if tab != self.tab {
                all.push(action(GO, label, "tab", Click::Tab(tab)));
            }
        }

        const PANEL: &str = "Panel";
        all.push(action(PANEL, "All changes", "b", Click::Back));
        all.push(action(PANEL, "Reload", "r", Click::Reload));
        all.push(action(PANEL, "Switch to the terminal", "", Click::Hide));
        all.push(action(PANEL, "Close the review", "", Click::Close));
        all
    }

    /// The actions the typed words leave: every word has to be in the group or the label.
    pub fn menu_actions(&self) -> Vec<Action> {
        let query = self.menu.as_ref().map_or("", |m| m.query.as_str());
        let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
        let mut all = self.actions();
        all.retain(|a| {
            let text = format!("{} {}", a.group, a.label).to_lowercase();
            words.iter().all(|w| text.contains(w))
        });
        all
    }
}