Lines
95.78 %
Functions
78.79 %
Branches
100 %
//! Key-event routing.
//!
//! Rather than drive crossterm `KeyEvent` types through unit tests
//! (which would pull the terminal into test scope) we translate key
//! events into a small internal vocabulary and dispatch that. The
//! vocabulary is expressive enough to drive every interactive
//! operation in the TUI.
mod completion;
mod console;
mod filter_builder;
mod form_apply;
mod intent;
mod menu;
mod modal_open;
mod names;
mod overlay_actions;
mod palette_run;
mod script;
mod size_move;
mod submit;
mod template;
mod widget_rows;
use crate::app::{App, MenuId};
use crate::focus::{FocusTarget, current_focus};
use crate::keymap::{self, VimState};
use crate::modal::Modal;
use crate::pane::PaneId;
use crate::tabs::list::ListTab;
use crate::tabs::nms::ConsoleState;
use crate::view::{Cmd, Handled, Tab};
use crate::viewer::Source;
use crate::window::WindowId;
pub use filter_builder::BuilderKey;
use form_apply::{apply_editor_intent, apply_modal_intent};
pub use intent::Intent;
use modal_open::{
confirm_delete_selected_tag, open_account_edit_for_selected, open_account_merge_for_selected,
open_commodity_create_modal, open_commodity_edit_for_selected, open_config_edit_for_selected,
open_config_set_modal, open_ssh_key_add_modal, open_ssh_key_remove, open_tag_create_modal,
open_tag_edit_for_selected, open_transaction_create_modal,
open_transaction_create_modal_for_selected, open_transaction_filter_modal,
};
use overlay_actions::{
close_topmost, confirm_topmost, submit_modal, template_form_open, toggles_split_tags,
pub use script::ScriptKey;
pub use template::TemplateKey;
/// Apply an intent to the app. The caller (the real event loop) is
/// responsible for translating crossterm key events into intents.
///
/// Dispatch follows the canonical focus order: Pending > Overlay > Menu > CmdLine > ConsoleInput > ViewPane.
pub fn apply(app: &mut App, intent: Intent) {
apply_at(app, current_focus(app), intent);
}
/// Applies a view intent to the active view whatever holds the focus: the wheel over a list
/// scrolls it while the command line is open.
pub(crate) fn apply_to_view(app: &mut App, intent: Intent) {
apply_at(app, FocusTarget::ViewPane, intent);
/// Applies a view intent to window `id`, front or not, and raises nothing: the wheel scrolls
/// the window under the pointer.
pub(crate) fn apply_to_window(app: &mut App, id: WindowId, intent: Intent) {
match app.front_window() == Some(id) {
true => apply_to_view(app, intent),
false => {
handle_view(app, id, intent);
/// What window `id`'s view does with `intent`, its page edges included; whether it did anything.
fn handle_view(app: &mut App, id: WindowId, intent: Intent) -> bool {
let edge = match intent {
Intent::ListSelectNext => Some(true),
Intent::ListSelectPrev => Some(false),
_ => None,
if let Some(forward) = edge
&& app.window_view(id) == Some(Tab::Transactions)
&& app.continue_transactions_page(id, forward)
{
return true;
let Some(Handled::Consumed(cmds)) = app.view_mut(id).map(|view| view.handle(intent)) else {
return false;
execute(app, cmds);
true
fn apply_at(app: &mut App, focus: FocusTarget, intent: Intent) {
if apply_global(app, intent) {
return;
let intent = match focus {
FocusTarget::Overlay => resolve_overlay(app, intent),
_ => intent,
if focus != FocusTarget::Pending && intent.starts_action() {
app.clear_status();
match focus {
FocusTarget::Pending => {}
FocusTarget::Overlay => {
handle_overlay(app, intent);
app.fetch_tag_hints();
app.preview_options();
FocusTarget::Drag => size_move::handle(app, intent),
FocusTarget::Menu => menu::handle(app, intent),
FocusTarget::CmdLine => handle_command_line(app, intent),
FocusTarget::ConsoleInput => console::handle(app, intent),
FocusTarget::ViewPane => handle_tab(app, intent),
/// Whether `intent` does anything with the focus and tab `app` is in. [`apply`], the status
/// bar hints and Help all answer through this, so no key is shown that does nothing.
#[must_use]
pub fn acts(app: &App, intent: Intent) -> bool {
let focus = current_focus(app);
if focus == FocusTarget::Drag {
return matches!(
intent,
Intent::Drag(_) | Intent::DragDone | Intent::DragCancel
);
match intent {
// A modal or a pending request swallows the asking quits; only `quit-now` acts there.
Intent::Quit | Intent::CloseOrQuit => {
!matches!(focus, FocusTarget::Overlay | FocusTarget::Pending)
Intent::OpenHelp => focus != FocusTarget::Pending,
Intent::OpenOptions => windows_free(focus),
Intent::OpenMenu => matches!(focus, FocusTarget::ViewPane | FocusTarget::ConsoleInput),
Intent::CloseWindow | Intent::SizeWindow => {
focus == FocusTarget::Overlay || on_front_window(app, focus)
Intent::NextWindow
| Intent::PrevWindow
| Intent::ToggleZoom
| Intent::Tile
| Intent::Cascade
| Intent::CloseAll => on_front_window(app, focus),
Intent::Drag(_) | Intent::DragDone | Intent::DragCancel => false,
Intent::NewWindow(_) => windows_free(focus),
Intent::SelectWindow(_) | Intent::RaiseWindow(_) => on_front_window(app, focus),
Intent::CloseMenu
| Intent::MenuNext
| Intent::MenuPrev
| Intent::MenuFirst
| Intent::MenuLast
| Intent::MenuLeft
| Intent::MenuRight
| Intent::MenuSelect => focus == FocusTarget::Menu,
Intent::NewRow => app.front_kind().and_then(new_row_action).is_some(),
Intent::EditRow => app.front_kind().and_then(edit_row_action).is_some(),
Intent::DeleteRow => app.front_kind().and_then(delete_row_action).is_some(),
Intent::OpenFilterBuilder => filter_builder::filter_text(app).is_some(),
Intent::ToggleSplitTags => toggles_split_tags(app),
_ => true,
/// Whether a window command can run: no dialog is open and a window is there to act on.
fn on_front_window(app: &App, focus: FocusTarget) -> bool {
windows_free(focus) && app.front_window().is_some()
fn windows_free(focus: FocusTarget) -> bool {
matches!(
focus,
FocusTarget::ViewPane | FocusTarget::ConsoleInput | FocusTarget::Menu
)
/// Opens `menu` the way [`Intent::OpenMenu`] does: only where that intent acts.
pub(crate) fn open_menu(app: &mut App, menu: MenuId) {
if acts(app, Intent::OpenMenu) {
app.open_menu_of(menu);
/// Quit, help and the menu work from every focus [`acts`] allows.
fn apply_global(app: &mut App, intent: Intent) -> bool {
Intent::Quit if acts(app, intent) => app.confirm_quit(),
Intent::QuitNow => app.request_quit(),
Intent::CloseOrQuit if acts(app, intent) => close_or_quit(app),
Intent::OpenHelp if acts(app, intent) => {
let (topic, lines) = (keymap::help_topic(app), keymap::help_lines(app));
app.show_viewer(Source::Help { topic }, lines);
Intent::OpenMenu if acts(app, intent) => open_menu(app, MenuId::View),
Intent::OpenOptions if acts(app, intent) => app.open_options(),
Intent::CloseWindow if acts(app, intent) => close_window_or_dialog(app),
| Intent::SizeWindow
| Intent::CloseAll
| Intent::NewWindow(_)
| Intent::SelectWindow(_)
| Intent::RaiseWindow(_)
if acts(app, intent) =>
window_command(app, intent);
_ => return false,
/// Closes the front window; asks to quit on an empty desktop.
fn close_or_quit(app: &mut App) {
match app.front_window() {
Some(_) => close_window_or_dialog(app),
None => app.confirm_quit(),
/// TV's `cmClose` on a dialog is `cmCancel`.
fn close_window_or_dialog(app: &mut App) {
match app.overlays.is_empty() {
true => {
app.close_menu();
app.close_front_window();
false => close_topmost(app),
fn window_command(app: &mut App, intent: Intent) {
Intent::NextWindow => app.next_window(),
Intent::PrevWindow => app.prev_window(),
Intent::Tile => app.tile_windows(),
Intent::Cascade => app.cascade_windows(),
Intent::CloseAll => app.close_all_windows(),
Intent::SizeWindow => app.begin_size_move(),
Intent::NewWindow(kind) => app.open_view(kind),
Intent::SelectWindow(number) => app.select_window_number(number),
Intent::RaiseWindow(id) => app.raise_listed(id),
_ => app.toggle_zoom(),
/// The overlay's context-free intents become the concrete ones before the status rule applies.
pub(crate) fn resolve_overlay(app: &App, intent: Intent) -> Intent {
Intent::Press => app
.overlays
.top()
.map_or(Intent::Submit, Modal::press_intent),
Intent::ToggleSplitTags if template_form_open(app) => Intent::Template(TemplateKey::Test),
other => other,
fn handle_overlay(app: &mut App, intent: Intent) {
Intent::CloseTopmost => close_topmost(app),
// `ConfirmYes` only ever acts on a `Modal::Confirm`; for any other
// overlay it is a no-op (it must never submit a form).
Intent::ConfirmYes => confirm_topmost(app),
Intent::OpenFilterBuilder => filter_builder::open(app),
Intent::Builder(key) => filter_builder::apply_key(app, key),
Intent::ApplyOptions => app.apply_options(),
Intent::CsvCopy => app.copy_csv(),
Intent::CsvSave => app.begin_csv_save(),
Intent::Submit => submit_modal(app),
Intent::Template(TemplateKey::Test) if template_form_open(app) => app.test_template_form(),
_ => apply_to_top(app, intent),
fn apply_to_top(app: &mut App, intent: Intent) {
if let Some(top) = app.overlays.top_mut() {
apply_modal_intent(top, intent);
fn handle_command_line(app: &mut App, intent: Intent) {
Intent::CloseTopmost => app.cmdline.active = false,
Intent::EnterNormalMode => app.keys.set_vim(VimState::Normal),
Intent::InsertAtCursor
| Intent::InsertAfterCursor
| Intent::InsertAtLineStart
| Intent::InsertAtLineEnd => start_typing(app, intent),
Intent::Submit => {
let buffer = app.cmdline.editor.buffer().to_string();
app.close_command_line();
palette_run::submit_palette(app, &buffer);
Intent::CompleteCommandLine => completion::apply_command_completion(app),
// Any other edit invalidates the displayed completion candidates.
_ => {
app.cmdline.completions.clear();
apply_editor_intent(&mut app.cmdline.editor, intent);
fn start_typing(app: &mut App, intent: Intent) {
let editor = &mut app.cmdline.editor;
Intent::InsertAfterCursor => editor.move_right(),
Intent::InsertAtLineStart => editor.move_home(),
Intent::InsertAtLineEnd => editor.move_end(),
_ => {}
app.keys.set_vim(VimState::Insert);
fn execute(app: &mut App, cmds: Vec<Cmd>) {
for cmd in cmds {
match cmd {
Cmd::Status(msg) => app.set_status(msg),
Cmd::SwitchView(id) => app.switch_tab(id),
fn handle_tab(app: &mut App, intent: Intent) {
let needs_window = !matches!(intent, Intent::SelectTab(_) | Intent::OpenCommandLine);
if needs_window && app.front_window().is_none() {
app.say_no_window(None);
if let Some(front) = app.front_window()
&& handle_view(app, front, intent)
Intent::SelectTab(t) => app.switch_tab(t),
Intent::NewRow => new_row(app),
Intent::EditRow => edit_row(app),
Intent::DeleteRow => delete_row(app),
Intent::OpenCommandLine => app.open_command_line(),
Intent::DetailEdit => app.edit_from_detail(),
Intent::ConsoleFocus if app.front_is(Tab::Console) => {
if let Some(console) = app.front_mut::<ConsoleState>() {
console.panes.focus(PaneId::Prompt);
app.set_console_focused(true);
Intent::RefreshTab => {
if let Some(tab) = app.front_kind() {
app.refresh_windows(tab);
Intent::ReportNew(kind) if app.front_is(Tab::Reports) => app.new_report(kind),
Intent::ReportChart if app.front_is(Tab::Reports) => app.toggle_report_chart(),
Intent::ReportCsv if app.front_is(Tab::Reports) => app.request_report_csv(),
Intent::ListPageNext if app.front_is(Tab::Transactions) => {
app.page_transactions(true);
Intent::ListPagePrev if app.front_is(Tab::Transactions) => {
app.page_transactions(false);
Intent::ListFilter if app.front_is(Tab::Transactions) => {
open_transaction_filter_modal(app);
Intent::ListFilterClear if app.front_is(Tab::Transactions) => {
if let Some(window) = app.front_window() {
app.clear_transaction_filter(window);
Intent::Template(key) => template::apply_tab(app, key),
Intent::Script(key) => script::apply_tab(app, key),
Intent::ListMark if app.front_is(Tab::Transactions) => {
if app.front_mut::<ListTab>().is_some_and(ListTab::toggle_mark) {
let front = app.front_window();
if !front.is_some_and(|front| app.continue_transactions_page(front, true))
&& let Some(list) = app.front_mut::<ListTab>()
list.select_next();
} else {
app.set_status("no transaction selected");
Intent::ListUnmarkAll if app.front_is(Tab::Transactions) => {
if let Some(list) = app.front_mut::<ListTab>() {
list.clear_marks();
Intent::ListDeleteMarked if app.front_is(Tab::Transactions) => {
app.open_delete_marked();
Intent::ListDetail if app.front_is(Tab::Transactions) => {
app.open_transaction_detail_selected();
Intent::ListMergeAccount if app.front_is(Tab::Accounts) => {
open_account_merge_for_selected(app);
Intent::ListAccountTransactions if app.front_is(Tab::Accounts) => {
app.filter_transactions_of_selected_account();
type RowAction = fn(&mut App);
fn new_row_action(tab: Tab) -> Option<RowAction> {
match tab {
Tab::Accounts => Some(open_transaction_create_modal_for_selected),
Tab::Transactions => Some(open_transaction_create_modal),
Tab::Commodities => Some(open_commodity_create_modal),
Tab::Config => Some(|app| open_config_set_modal(app, &[])),
Tab::SshKeys => Some(|app| open_ssh_key_add_modal(app, &[])),
Tab::Tags => Some(open_tag_create_modal),
Tab::Templates => Some(template::open_create),
Tab::Scripts => Some(script::open_create),
fn edit_row_action(tab: Tab) -> Option<RowAction> {
Tab::Transactions => Some(open_selected_transaction_edit),
Tab::Accounts => Some(open_account_edit_for_selected),
Tab::Commodities => Some(open_commodity_edit_for_selected),
Tab::Config => Some(open_config_edit_for_selected),
Tab::Tags => Some(open_tag_edit_for_selected),
Tab::Templates => Some(template::open_edit_for_selected),
Tab::Scripts => Some(script::open_edit_for_selected),
Tab::Reports => Some(App::edit_last_report),
fn delete_row_action(tab: Tab) -> Option<RowAction> {
Tab::Transactions => Some(confirm_delete_selected_transaction),
Tab::SshKeys => Some(|app| open_ssh_key_remove(app, None)),
Tab::Tags => Some(confirm_delete_selected_tag),
Tab::Templates => Some(template::confirm_delete_selected),
Tab::Scripts => Some(script::confirm_delete_selected),
fn new_row(app: &mut App) {
if let Some(action) = app.front_kind().and_then(new_row_action) {
action(app);
fn edit_row(app: &mut App) {
if let Some(action) = app.front_kind().and_then(edit_row_action) {
fn delete_row(app: &mut App) {
if let Some(action) = app.front_kind().and_then(delete_row_action) {
fn open_selected_transaction_edit(app: &mut App) {
match app.selected_id(Tab::Transactions) {
Some(id) => app.open_transaction_edit_async(&id),
None => app.set_status("no transaction selected"),
fn confirm_delete_selected_transaction(app: &mut App) {
let maybe_id = app.selected_id(Tab::Transactions);
if let Some(id) = maybe_id {
app.open_dialog_for(
Tab::Transactions,
Modal::confirm(
format!("Delete transaction {id}?"),
crate::modal::ConfirmAction::DeleteTransaction(id),
),
#[cfg(test)]
mod acts_tests;
mod tests;