rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Keys and pastes in the review panel: what each one does on the screen that is showing.

use super::*;

impl ReviewView {
    pub(super) fn menu_input(&mut self, input: Input) -> Request {
        let Some(o) = self.opened() else { return Request::Nothing };
        let count = o.menu_actions().len();
        let Some(m) = o.menu.as_mut() else { return Request::Nothing };
        let last = count.saturating_sub(1);
        match input {
            // Up from the top goes round to the bottom, as in the command palette.
            Input::Up | Input::BackTab => m.selected = if m.selected == 0 { last } else { m.selected - 1 },
            Input::Down | Input::Tab => m.selected = if m.selected >= last { 0 } else { m.selected + 1 },
            Input::PageUp => m.selected = m.selected.saturating_sub(8),
            Input::PageDown => m.selected = (m.selected + 8).min(last),
            Input::Home => m.selected = 0,
            Input::End => m.selected = last,
            Input::Text(t) => {
                m.query.push_str(&t);
                m.selected = 0;
            }
            Input::Space => {
                m.query.push(' ');
                m.selected = 0;
            }
            Input::Backspace if !m.query.is_empty() => {
                m.query.pop();
                m.selected = 0;
            }
            Input::ClearAll => {
                m.query.clear();
                m.selected = 0;
            }
            Input::Escape | Input::Backspace => self.close_menu(),
            Input::Enter => {
                let selected = m.selected;
                return self.activate(Click::MenuRow(selected));
            }
            _ => {}
        }
        Request::Nothing
    }

    /// Put the list away without running anything, which also drops a first press.
    pub fn close_menu(&mut self) {
        if let Some(o) = self.opened()
            && o.menu.take().is_some()
        {
            o.confirm_approve = false;
            o.confirm_merge = None;
            o.confirm_reset = false;
        }
    }

    /// Text pasted into whichever field is being typed in.
    pub fn paste(&mut self, text: &str) {
        let line: String = text.lines().next().unwrap_or("").chars().filter(|c| !c.is_control()).collect();
        match &mut self.screen {
            // A description can have many lines.
            Screen::Create(c) => c.paste(text),
            Screen::Git(g) => g.paste(&line),
            Screen::Pick(p) => {
                p.filter.push_str(line.trim());
                p.selected = 0;
            }
            Screen::Open(o) => {
                if let Some(menu) = o.menu.as_mut() {
                    menu.query.push_str(&line);
                    menu.selected = 0;
                } else if let Some(note) = o.note.as_mut() {
                    note.push_str(&line);
                }
            }
            _ => {}
        }
    }

    /// Whether a repeat of this key, from holding it down, is to be ignored: it could
    /// confirm something that is meant to take two presses.
    pub fn ignores_repeat(&self, input: &Input) -> bool {
        match &self.screen {
            Screen::Git(_) | Screen::Create(_) => *input == Input::Enter,
            // Enter runs an action, which may be one that takes two presses.
            Screen::Open(o) if o.menu.is_some() => *input == Input::Enter,
            // While a note is typed, these are just letters.
            Screen::Open(o) if o.note.is_none() => {
                matches!(input, Input::Text(t) if ["a", "q", "g"].iter().any(|k| t.eq_ignore_ascii_case(k)))
            }
            _ => false,
        }
    }

    pub fn input(&mut self, input: Input) -> Request {
        match &mut self.screen {
            Screen::Git(_) => self.git_input(input),
            Screen::Create(_) => self.create_input(input),
            Screen::Pick(_) => self.picker_input(input),
            Screen::Open(o) if o.menu.is_some() => self.menu_input(input),
            Screen::Open(o) if o.note.is_some() => {
                // Typing a note is about the item it is for.
                let note = o.note.as_mut().expect("checked");
                match input {
                    Input::Text(t) => note.push_str(&t),
                    Input::Space => note.push(' '),
                    Input::Backspace => {
                        note.pop();
                    }
                    Input::ClearAll => note.clear(),
                    Input::Enter => {
                        self.finish_note();
                        self.advance();
                    }
                    // Leaves the note as it was.
                    Input::Escape => o.note = None,
                    _ => {}
                }
                Request::Nothing
            }
            Screen::Open(_) => self.review_input(input),
            Screen::Loading(_) | Screen::Message { .. } => match input {
                Input::Escape | Input::Backspace => self.activate(Click::Back),
                Input::Text(t) if t.eq_ignore_ascii_case("r") => self.activate(Click::Reload),
                _ => Request::Nothing,
            },
        }
    }

    pub(super) fn picker_input(&mut self, input: Input) -> Request {
        let Screen::Pick(p) = &mut self.screen else { return Request::Nothing };
        // Once the person is choosing, the choice is not moved for them.
        p.want = None;
        let count = p.entries().len();
        let step = |from: usize, by: isize| (from as isize + by).clamp(0, count.saturating_sub(1) as isize) as usize;
        match input {
            Input::Up | Input::BackTab => p.selected = step(p.selected, -1),
            Input::Down | Input::Tab => p.selected = step(p.selected, 1),
            Input::PageUp => p.selected = step(p.selected, -8),
            Input::PageDown => p.selected = step(p.selected, 8),
            Input::Home => p.selected = 0,
            Input::End => p.selected = step(count, 0),
            Input::Enter => {
                let selected = p.selected;
                return self.activate(Click::Choose(selected));
            }
            Input::Text(t) => {
                p.filter.push_str(&t);
                p.selected = 0;
            }
            Input::Space => p.filter.push(' '),
            Input::Backspace => {
                p.filter.pop();
                p.selected = 0;
            }
            Input::ClearAll => {
                p.filter.clear();
                p.selected = 0;
            }
            Input::Escape => {
                if p.filter.is_empty() {
                    return Request::Hide;
                }
                p.filter.clear();
                p.selected = 0;
            }
            _ => return Request::Nothing,
        }
        self.reveal = true;
        Request::Nothing
    }

    pub(super) fn review_input(&mut self, input: Input) -> Request {
        let page = (if self.view_h > 0.0 { self.view_h * 0.85 } else { self.rect.h * 0.7 }).max(100.0);
        let Some(o) = self.opened() else { return Request::Nothing };
        let (tab, finding, findings) = (o.tab, o.finding, o.change.report.findings.len());
        let thing = o.thing();
        let key = match &input {
            Input::Text(t) => t.to_lowercase(),
            _ => String::new(),
        };
        if matches!(key.as_str(), "?" | "/") {
            return self.activate(Click::Menu);
        }
        // A first press only stays armed until some other key.
        if !matches!(key.as_str(), "a" | "q" | "g") {
            o.confirm_approve = false;
            o.confirm_merge = None;
        }
        let guide = tab == Tab::Guide;
        // Judging is for the item chosen on the guide.
        let testing = guide && matches!(thing, Some(Thing::Item(_)));
        let click = match input {
            // Back one level: the other tabs to the guide, the guide to the terminal.
            Input::Escape if guide => return Request::Hide,
            Input::Escape => Click::Tab(Tab::Guide),
            Input::Tab | Input::BackTab => {
                let at = Tab::ALL.iter().position(|t| *t == tab).unwrap_or(0);
                let by = if input == Input::Tab { 1 } else { Tab::ALL.len() - 1 };
                Click::Tab(Tab::ALL[(at + by) % Tab::ALL.len()])
            }
            Input::PageUp | Input::PageDown => {
                let by = if input == Input::PageUp { -page } else { page };
                self.scroll_to(self.scroll + by);
                return Request::Nothing;
            }
            Input::Up | Input::Down => {
                let up = input == Input::Up;
                match tab {
                    Tab::Guide => {
                        let first = o.cursor == 0;
                        if self.read_on(up, first) {
                            return Request::Nothing;
                        }
                        if up { Click::Prev } else { Click::Next }
                    }
                    Tab::Findings => {
                        if !self.read_on(up, finding == 0) {
                            self.choose_finding(if up { finding.saturating_sub(1) } else { finding + 1 });
                        }
                        return Request::Nothing;
                    }
                    Tab::Description => {
                        self.scroll_to(self.scroll + if up { -60.0 } else { 60.0 });
                        return Request::Nothing;
                    }
                }
            }
            Input::Home | Input::End => {
                let end = input == Input::End;
                match tab {
                    Tab::Guide => {
                        let (stage, last) = (o.stage, o.things(o.stage).len().saturating_sub(1));
                        self.go(stage, if end { last } else { 0 });
                        if !end {
                            self.at_top = true;
                            self.scroll = 0.0;
                        }
                    }
                    Tab::Findings => self.choose_finding(if end { findings } else { 0 }),
                    Tab::Description => self.scroll_to(if end { self.max_scroll } else { 0.0 }),
                }
                return Request::Nothing;
            }
            Input::Left | Input::Right if guide => {
                let stage = if input == Input::Left {
                    o.stage.saturating_sub(1)
                } else {
                    (o.stage + 1).min(o.stages.len() - 1)
                };
                Click::Stage(stage)
            }
            Input::Enter if tab == Tab::Findings => Click::Finding(finding),
            Input::Enter if guide => {
                if o.stage_done(o.stage) {
                    Click::Continue
                } else {
                    match thing {
                        Some(Thing::File(f)) if !o.done(Thing::File(f)) => Click::Seen(f),
                        Some(Thing::Item(_)) => Click::Verdict(Verdict::Passed),
                        _ => Click::Continue,
                    }
                }
            }
            // Space: this one is done. A file is read, a finding looked at, a step passed.
            Input::Space if guide => match thing {
                Some(Thing::File(f)) => Click::Seen(f),
                Some(Thing::Item(_)) => Click::Verdict(Verdict::Passed),
                None => return Request::Nothing,
            },
            // From a finding to where the guide deals with it.
            Input::Space if tab == Tab::Findings => match o.step_for(finding) {
                Some(step) => Click::Step(step),
                None => return Request::Nothing,
            },
            Input::Space => {
                self.scroll_to(self.scroll + page);
                return Request::Nothing;
            }
            Input::Backspace if testing => Click::Verdict(Verdict::Failed),
            Input::Delete if testing => Click::Clear,
            Input::Text(_) => match key.as_str() {
                "p" if testing => Click::Verdict(Verdict::Passed),
                "f" if testing => Click::Verdict(Verdict::Failed),
                "s" if testing => Click::Verdict(Verdict::Skipped),
                "u" if testing => Click::Clear,
                "e" if testing => Click::EditNote,
                // Straight to the neighbour, however much of this one is left to read.
                "k" if guide => Click::Prev,
                "j" if guide => Click::Next,
                "k" | "j" if tab == Tab::Findings => {
                    self.choose_finding(if key == "k" { finding.saturating_sub(1) } else { finding + 1 });
                    return Request::Nothing;
                }
                "k" | "j" => {
                    self.scroll_to(self.scroll + if key == "k" { -60.0 } else { 60.0 });
                    return Request::Nothing;
                }
                "n" => Click::Continue,
                "x" => match thing {
                    Some(Thing::File(f)) if guide => Click::ChangedFile(f),
                    _ => return Request::Nothing,
                },
                "d" => match o.finding_here() {
                    Some(k) => Click::Finding(k),
                    None => return Request::Nothing,
                },
                "v" => match thing {
                    Some(Thing::File(f)) if guide => Click::Seen(f),
                    _ => return Request::Nothing,
                },
                "c" | "t" => {
                    let quoted = o.quoted_here();
                    let checkout = o.checkout_here();
                    match (key.as_str(), quoted, checkout) {
                        ("t", Some((command, true)), _) => Click::Type(command),
                        ("c", Some((text, _)), _) => Click::Copy(text),
                        ("t", _, Some(command)) => Click::Type(command),
                        ("c", None, Some(command)) => Click::Copy(command),
                        _ => {
                            self.status = Some(("There is no command here".into(), false));
                            return Request::Nothing;
                        }
                    }
                }
                "o" if tab == Tab::Description => match &o.change.url {
                    Some(url) => Click::Url(url.clone()),
                    None => return Request::Nothing,
                },
                "o" => match o.current_place() {
                    Some((file, line)) => Click::File(file, line),
                    None => return Request::Nothing,
                },
                "a" => Click::Approve,
                "q" => Click::Merge(Method::Squash),
                "g" => Click::Merge(Method::Commit),
                "m" => Click::Propose,
                "y" => Click::CopyResults,
                "r" => Click::Reload,
                "b" => Click::Back,
                // A stage by its number.
                digit => match digit.parse::<usize>() {
                    Ok(n) if (1..=o.stages.len().min(9)).contains(&n) => Click::Stage(n - 1),
                    _ => return Request::Nothing,
                },
            },
            _ => return Request::Nothing,
        };
        self.activate(click)
    }

    pub(super) fn choose_finding(&mut self, finding: usize) {
        let Some(o) = self.opened() else { return };
        o.finding = finding.min(o.change.report.findings.len().saturating_sub(1));
        self.chosen = None;
        self.reveal = true;
    }
}