rustimal 0.4.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Types a command into an idle shell, and checks that it arrived intact before pressing Enter.
//!
//! Text typed into Git Bash in the first moments of a pane's life, or around a resize, can lose
//! its first characters on the way in. The shell then runs a mangled line (`-- 'dir'` instead of
//! `cd -- 'dir'`). So the command is typed without Enter, read back from the screen, and only run
//! if it looks right; otherwise the line is cleared and typed again. If that keeps failing, or
//! the shell never gets to a prompt, the caller falls back to opening the item instead.

use std::time::{Duration, Instant};

use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::term::Term;

use crate::links::Target;
use crate::pane::{awaiting_more, cursor_at_prompt, typed_text};

/// The prompt has to stay up this long before typing, so output still arriving is not mistaken for it.
const SETTLE: Duration = Duration::from_millis(150);
/// How long to wait for the typed command to show up on the line.
const ECHO_WAIT: Duration = Duration::from_millis(450);
const CLEAR_WAIT: Duration = Duration::from_millis(120);
/// Give up (and open the item instead) after this long.
const GIVE_UP: Duration = Duration::from_secs(6);
const MAX_TRIES: u8 = 3;
/// How often to press `q` while a list is paused at `--More--`.
const DISMISS_EVERY: Duration = Duration::from_millis(300);
/// Ctrl+E, Ctrl+U: clear the whole line.
const CLEAR_LINE: [u8; 2] = [0x05, 0x15];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stage {
    /// Waiting for an empty prompt.
    WaitPrompt,
    /// The prompt is up; waiting for it to stay put.
    Settle(Instant),
    /// The command is typed; waiting for it to show on the line.
    Typed(Instant),
    /// The line was cleared; waiting for the empty prompt to come back.
    Clearing(Instant),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
    Pending,
    /// Enter was sent; the command is running.
    Done,
    /// Could not get the command in; open the target instead.
    GiveUp,
}

pub struct Injector {
    cmd: String,
    /// Opened instead if the command can't be typed.
    pub target: Option<Target>,
    started: Instant,
    stage: Stage,
    tries: u8,
    last_dismiss: Option<Instant>,
}

impl Injector {
    pub fn new(cmd: String, target: Option<Target>, now: Instant) -> Self {
        Self { cmd, target, started: now, stage: Stage::WaitPrompt, tries: 0, last_dismiss: None }
    }

    /// Advance with the current screen. Returns bytes to send to the shell, in order.
    pub fn tick<T>(&mut self, term: &Term<T>, now: Instant) -> (Vec<Vec<u8>>, Outcome) {
        let mut out = Vec::new();
        if now.duration_since(self.started) > GIVE_UP {
            if matches!(self.stage, Stage::Typed(_)) {
                out.push(CLEAR_LINE.to_vec());
            }
            return (out, Outcome::GiveUp);
        }
        match self.stage {
            Stage::WaitPrompt => {
                if cursor_at_prompt(term) {
                    self.stage = Stage::Settle(now);
                } else if awaiting_more(term) && self.last_dismiss.is_none_or(|t| now.duration_since(t) >= DISMISS_EVERY) {
                    // A long listing is paused at `--More--` and would swallow what we type.
                    out.push(b"q".to_vec());
                    self.last_dismiss = Some(now);
                }
            }
            Stage::Settle(since) => {
                if !cursor_at_prompt(term) {
                    self.stage = Stage::WaitPrompt;
                } else if now.duration_since(since) >= SETTLE {
                    out.push(self.cmd.clone().into_bytes());
                    self.stage = Stage::Typed(now);
                }
            }
            Stage::Typed(since) => {
                // A command that wraps onto a second line can't be read back from one line.
                let checkable = self.cmd.chars().count() + 40 <= term.columns();
                let intact = typed_text(term).is_some_and(|t| t.trim_end() == self.cmd);
                if intact || !checkable {
                    out.push(b"\r".to_vec());
                    return (out, Outcome::Done);
                }
                if now.duration_since(since) >= ECHO_WAIT {
                    self.tries += 1;
                    out.push(CLEAR_LINE.to_vec());
                    if self.tries >= MAX_TRIES {
                        return (out, Outcome::GiveUp);
                    }
                    self.stage = Stage::Clearing(now);
                }
            }
            Stage::Clearing(since) => {
                if now.duration_since(since) >= CLEAR_WAIT {
                    self.stage = Stage::WaitPrompt;
                }
            }
        }
        (out, Outcome::Pending)
    }
}