Lines
100 %
Functions
Branches
//! The button a key holds drawn down for [`KEY_PRESS`] before it acts.
use std::time::{Duration, Instant};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::App;
use super::hold::{Grip, Owner};
use crate::event::{Intent, apply};
use crate::focus::{FocusTarget, current_focus};
/// How long a key leaves a button drawn down before it acts, as in Turbo Vision.
pub(crate) const KEY_PRESS: Duration = Duration::from_millis(100);
/// A button a key holds down until `due`, when `intent` acts.
#[derive(Debug, Clone, Copy)]
pub(crate) struct KeyPress {
index: usize,
due: Instant,
intent: Intent,
}
impl App {
/// The key press, if the dialog it began on is still the top one.
fn live_key_press(&self) -> Option<KeyPress> {
match self.live_hold()?.grip {
Grip::Key(press) => Some(press),
_ => None,
pub(crate) fn hold_button_by_key(&mut self, index: usize, intent: Intent, now: Instant) {
let press = KeyPress {
index,
due: now + KEY_PRESS,
intent,
};
self.begin_hold(Owner::Layer, Grip::Key(press));
/// The button a key holds drawn down.
pub(crate) fn key_pressed_button(&self) -> Option<usize> {
self.live_key_press().map(|press| press.index)
/// Lets a key's press act now, without waiting for its time; whether it did. A press whose
/// dialog is gone is dropped.
pub(crate) fn flush_key_press(&mut self) -> bool {
let live = self.live_key_press();
self.hold.take_if(|hold| matches!(hold.grip, Grip::Key(_)));
let Some(press) = live else {
return false;
apply(self, press.intent);
true
/// Lets a key's press act once its time is up.
pub(crate) fn tick(&mut self, now: Instant) {
if self.next_deadline(now) == Some(Duration::ZERO) {
self.flush_key_press();
/// The time left until the loop has something to do besides waiting for input.
pub(crate) fn next_deadline(&self, now: Instant) -> Option<Duration> {
match self.hold?.grip {
Grip::Key(press) => Some(press.due.saturating_duration_since(now)),
/// The button the key presses and what it does: the one `Press` presses, or the one whose
/// hotkey letter the key types and whose intent the key is bound to.
pub(crate) fn button_of_key(app: &App, key: KeyEvent, intent: Intent) -> Option<(usize, Intent)> {
if current_focus(app) != FocusTarget::Overlay {
return None;
let modal = app.overlays.top()?;
let specs = modal.button_specs();
let index = match intent {
Intent::Press => modal.press_button()?,
_ => hotkey_button(specs, key, intent)?,
specs.get(index).map(|&(_, spec)| (index, spec))
fn hotkey_button(specs: &[(&str, Intent)], key: KeyEvent, intent: Intent) -> Option<usize> {
let KeyCode::Char(typed) = key.code else {
if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
specs.iter().position(|&(label, spec)| {
spec == intent && tvui::hotkey(label).is_some_and(|c| c.eq_ignore_ascii_case(&typed))
})