1
//! Key-event routing.
2
//!
3
//! Rather than drive crossterm `KeyEvent` types through unit tests
4
//! (which would pull the terminal into test scope) we translate key
5
//! events into a small internal vocabulary and dispatch that. The
6
//! vocabulary is expressive enough to drive every interactive
7
//! operation in the TUI.
8

            
9
mod completion;
10
mod console;
11
mod filter_builder;
12
mod form_apply;
13
mod intent;
14
mod menu;
15
mod modal_open;
16
mod names;
17
mod overlay_actions;
18
mod palette_run;
19
mod script;
20
mod size_move;
21
mod submit;
22
mod template;
23
mod widget_rows;
24

            
25
use crate::app::{App, MenuId};
26
use crate::focus::{FocusTarget, current_focus};
27
use crate::keymap::{self, VimState};
28
use crate::modal::Modal;
29
use crate::pane::PaneId;
30
use crate::tabs::list::ListTab;
31
use crate::tabs::nms::ConsoleState;
32
use crate::view::{Cmd, Handled, Tab};
33
use crate::viewer::Source;
34
use crate::window::WindowId;
35
pub use filter_builder::BuilderKey;
36
use form_apply::{apply_editor_intent, apply_modal_intent};
37
pub use intent::Intent;
38
use modal_open::{
39
    confirm_delete_selected_tag, open_account_edit_for_selected, open_account_merge_for_selected,
40
    open_commodity_create_modal, open_commodity_edit_for_selected, open_config_edit_for_selected,
41
    open_config_set_modal, open_ssh_key_add_modal, open_ssh_key_remove, open_tag_create_modal,
42
    open_tag_edit_for_selected, open_transaction_create_modal,
43
    open_transaction_create_modal_for_selected, open_transaction_filter_modal,
44
};
45
use overlay_actions::{
46
    close_topmost, confirm_topmost, submit_modal, template_form_open, toggles_split_tags,
47
};
48
pub use script::ScriptKey;
49
pub use template::TemplateKey;
50

            
51
/// Apply an intent to the app. The caller (the real event loop) is
52
/// responsible for translating crossterm key events into intents.
53
///
54
/// Dispatch follows the canonical focus order: Pending > Overlay > Menu > CmdLine > ConsoleInput > ViewPane.
55
7440
pub fn apply(app: &mut App, intent: Intent) {
56
7440
    apply_at(app, current_focus(app), intent);
57
7440
}
58

            
59
/// Applies a view intent to the active view whatever holds the focus: the wheel over a list
60
/// scrolls it while the command line is open.
61
185
pub(crate) fn apply_to_view(app: &mut App, intent: Intent) {
62
185
    apply_at(app, FocusTarget::ViewPane, intent);
63
185
}
64

            
65
/// Applies a view intent to window `id`, front or not, and raises nothing: the wheel scrolls
66
/// the window under the pointer.
67
91
pub(crate) fn apply_to_window(app: &mut App, id: WindowId, intent: Intent) {
68
91
    match app.front_window() == Some(id) {
69
88
        true => apply_to_view(app, intent),
70
        false => {
71
3
            handle_view(app, id, intent);
72
        }
73
    }
74
91
}
75

            
76
/// What window `id`'s view does with `intent`, its page edges included; whether it did anything.
77
905
fn handle_view(app: &mut App, id: WindowId, intent: Intent) -> bool {
78
905
    let edge = match intent {
79
99
        Intent::ListSelectNext => Some(true),
80
23
        Intent::ListSelectPrev => Some(false),
81
783
        _ => None,
82
    };
83
905
    if let Some(forward) = edge
84
122
        && app.window_view(id) == Some(Tab::Transactions)
85
29
        && app.continue_transactions_page(id, forward)
86
    {
87
10
        return true;
88
895
    }
89
895
    let Some(Handled::Consumed(cmds)) = app.view_mut(id).map(|view| view.handle(intent)) else {
90
565
        return false;
91
    };
92
330
    execute(app, cmds);
93
330
    true
94
905
}
95

            
96
7625
fn apply_at(app: &mut App, focus: FocusTarget, intent: Intent) {
97
7625
    if apply_global(app, intent) {
98
318
        return;
99
7307
    }
100
7307
    let intent = match focus {
101
1967
        FocusTarget::Overlay => resolve_overlay(app, intent),
102
5340
        _ => intent,
103
    };
104
7307
    if focus != FocusTarget::Pending && intent.starts_action() {
105
1111
        app.clear_status();
106
6196
    }
107
7307
    match focus {
108
4
        FocusTarget::Pending => {}
109
        FocusTarget::Overlay => {
110
1967
            handle_overlay(app, intent);
111
1967
            app.fetch_tag_hints();
112
1967
            app.preview_options();
113
        }
114
86
        FocusTarget::Drag => size_move::handle(app, intent),
115
78
        FocusTarget::Menu => menu::handle(app, intent),
116
4026
        FocusTarget::CmdLine => handle_command_line(app, intent),
117
213
        FocusTarget::ConsoleInput => console::handle(app, intent),
118
933
        FocusTarget::ViewPane => handle_tab(app, intent),
119
    }
120
7625
}
121

            
122
/// Whether `intent` does anything with the focus and tab `app` is in. [`apply`], the status
123
/// bar hints and Help all answer through this, so no key is shown that does nothing.
124
#[must_use]
125
130282
pub fn acts(app: &App, intent: Intent) -> bool {
126
130282
    let focus = current_focus(app);
127
130282
    if focus == FocusTarget::Drag {
128
5864
        return matches!(
129
5864
            intent,
130
5864
            Intent::Drag(_) | Intent::DragDone | Intent::DragCancel
131
5864
        );
132
124418
    }
133
124418
    match intent {
134
        // A modal or a pending request swallows the asking quits; only `quit-now` acts there.
135
        Intent::Quit | Intent::CloseOrQuit => {
136
3342
            !matches!(focus, FocusTarget::Overlay | FocusTarget::Pending)
137
        }
138
3348
        Intent::OpenHelp => focus != FocusTarget::Pending,
139
34
        Intent::OpenOptions => windows_free(focus),
140
5676
        Intent::OpenMenu => matches!(focus, FocusTarget::ViewPane | FocusTarget::ConsoleInput),
141
        Intent::CloseWindow | Intent::SizeWindow => {
142
9599
            focus == FocusTarget::Overlay || on_front_window(app, focus)
143
        }
144
        Intent::NextWindow
145
        | Intent::PrevWindow
146
        | Intent::ToggleZoom
147
        | Intent::Tile
148
        | Intent::Cascade
149
9840
        | Intent::CloseAll => on_front_window(app, focus),
150
        Intent::Drag(_) | Intent::DragDone | Intent::DragCancel => false,
151
697
        Intent::NewWindow(_) => windows_free(focus),
152
22976
        Intent::SelectWindow(_) | Intent::RaiseWindow(_) => on_front_window(app, focus),
153
        Intent::CloseMenu
154
        | Intent::MenuNext
155
        | Intent::MenuPrev
156
        | Intent::MenuFirst
157
        | Intent::MenuLast
158
        | Intent::MenuLeft
159
        | Intent::MenuRight
160
381
        | Intent::MenuSelect => focus == FocusTarget::Menu,
161
1082
        Intent::NewRow => app.front_kind().and_then(new_row_action).is_some(),
162
1406
        Intent::EditRow => app.front_kind().and_then(edit_row_action).is_some(),
163
1696
        Intent::DeleteRow => app.front_kind().and_then(delete_row_action).is_some(),
164
1735
        Intent::OpenFilterBuilder => filter_builder::filter_text(app).is_some(),
165
1736
        Intent::ToggleSplitTags => toggles_split_tags(app),
166
60870
        _ => true,
167
    }
168
130282
}
169

            
170
/// Whether a window command can run: no dialog is open and a window is there to act on.
171
35893
fn on_front_window(app: &App, focus: FocusTarget) -> bool {
172
35893
    windows_free(focus) && app.front_window().is_some()
173
35893
}
174

            
175
36624
fn windows_free(focus: FocusTarget) -> bool {
176
36624
    matches!(
177
36624
        focus,
178
        FocusTarget::ViewPane | FocusTarget::ConsoleInput | FocusTarget::Menu
179
    )
180
36624
}
181

            
182
/// Opens `menu` the way [`Intent::OpenMenu`] does: only where that intent acts.
183
60
pub(crate) fn open_menu(app: &mut App, menu: MenuId) {
184
60
    if acts(app, Intent::OpenMenu) {
185
57
        app.open_menu_of(menu);
186
3
    }
187
60
}
188

            
189
/// Quit, help and the menu work from every focus [`acts`] allows.
190
7625
fn apply_global(app: &mut App, intent: Intent) -> bool {
191
7625
    match intent {
192
27
        Intent::Quit if acts(app, intent) => app.confirm_quit(),
193
4
        Intent::QuitNow => app.request_quit(),
194
8
        Intent::CloseOrQuit if acts(app, intent) => close_or_quit(app),
195
36
        Intent::OpenHelp if acts(app, intent) => {
196
35
            let (topic, lines) = (keymap::help_topic(app), keymap::help_lines(app));
197
35
            app.clear_status();
198
35
            app.show_viewer(Source::Help { topic }, lines);
199
        }
200
52
        Intent::OpenMenu if acts(app, intent) => open_menu(app, MenuId::View),
201
32
        Intent::OpenOptions if acts(app, intent) => app.open_options(),
202
31
        Intent::CloseWindow if acts(app, intent) => close_window_or_dialog(app),
203
        Intent::NextWindow
204
        | Intent::PrevWindow
205
        | Intent::SizeWindow
206
        | Intent::ToggleZoom
207
        | Intent::Tile
208
        | Intent::Cascade
209
        | Intent::CloseAll
210
        | Intent::NewWindow(_)
211
        | Intent::SelectWindow(_)
212
        | Intent::RaiseWindow(_)
213
22
            if acts(app, intent) =>
214
        {
215
137
            window_command(app, intent);
216
        }
217
7307
        _ => return false,
218
    }
219
318
    true
220
7625
}
221

            
222
/// Closes the front window; asks to quit on an empty desktop.
223
8
fn close_or_quit(app: &mut App) {
224
8
    match app.front_window() {
225
5
        Some(_) => close_window_or_dialog(app),
226
3
        None => app.confirm_quit(),
227
    }
228
8
}
229

            
230
/// TV's `cmClose` on a dialog is `cmCancel`.
231
34
fn close_window_or_dialog(app: &mut App) {
232
34
    match app.overlays.is_empty() {
233
        true => {
234
30
            app.close_menu();
235
30
            app.close_front_window();
236
        }
237
4
        false => close_topmost(app),
238
    }
239
34
}
240

            
241
137
fn window_command(app: &mut App, intent: Intent) {
242
137
    app.close_menu();
243
137
    match intent {
244
19
        Intent::NextWindow => app.next_window(),
245
7
        Intent::PrevWindow => app.prev_window(),
246
3
        Intent::Tile => app.tile_windows(),
247
3
        Intent::Cascade => app.cascade_windows(),
248
2
        Intent::CloseAll => app.close_all_windows(),
249
40
        Intent::SizeWindow => app.begin_size_move(),
250
27
        Intent::NewWindow(kind) => app.open_view(kind),
251
3
        Intent::SelectWindow(number) => app.select_window_number(number),
252
7
        Intent::RaiseWindow(id) => app.raise_listed(id),
253
26
        _ => app.toggle_zoom(),
254
    }
255
137
}
256

            
257
/// The overlay's context-free intents become the concrete ones before the status rule applies.
258
13502
pub(crate) fn resolve_overlay(app: &App, intent: Intent) -> Intent {
259
13502
    match intent {
260
207
        Intent::Press => app
261
207
            .overlays
262
207
            .top()
263
207
            .map_or(Intent::Submit, Modal::press_intent),
264
587
        Intent::ToggleSplitTags if template_form_open(app) => Intent::Template(TemplateKey::Test),
265
13288
        other => other,
266
    }
267
13502
}
268

            
269
1967
fn handle_overlay(app: &mut App, intent: Intent) {
270
1967
    match intent {
271
95
        Intent::CloseTopmost => close_topmost(app),
272
        // `ConfirmYes` only ever acts on a `Modal::Confirm`; for any other
273
        // overlay it is a no-op (it must never submit a form).
274
71
        Intent::ConfirmYes => confirm_topmost(app),
275
46
        Intent::OpenFilterBuilder => filter_builder::open(app),
276
106
        Intent::Builder(key) => filter_builder::apply_key(app, key),
277
4
        Intent::ApplyOptions => app.apply_options(),
278
3
        Intent::CsvCopy => app.copy_csv(),
279
2
        Intent::CsvSave => app.begin_csv_save(),
280
206
        Intent::Submit => submit_modal(app),
281
6
        Intent::Template(TemplateKey::Test) if template_form_open(app) => app.test_template_form(),
282
1429
        _ => apply_to_top(app, intent),
283
    }
284
1967
}
285

            
286
1429
fn apply_to_top(app: &mut App, intent: Intent) {
287
1429
    if let Some(top) = app.overlays.top_mut() {
288
1429
        apply_modal_intent(top, intent);
289
    }
290
1429
}
291

            
292
4026
fn handle_command_line(app: &mut App, intent: Intent) {
293
4026
    match intent {
294
2
        Intent::CloseTopmost => app.cmdline.active = false,
295
34
        Intent::EnterNormalMode => app.keys.set_vim(VimState::Normal),
296
        Intent::InsertAtCursor
297
        | Intent::InsertAfterCursor
298
        | Intent::InsertAtLineStart
299
7
        | Intent::InsertAtLineEnd => start_typing(app, intent),
300
        Intent::Submit => {
301
140
            let buffer = app.cmdline.editor.buffer().to_string();
302
140
            app.close_command_line();
303
140
            palette_run::submit_palette(app, &buffer);
304
        }
305
7
        Intent::CompleteCommandLine => completion::apply_command_completion(app),
306
        // Any other edit invalidates the displayed completion candidates.
307
        _ => {
308
3836
            app.cmdline.completions.clear();
309
3836
            apply_editor_intent(&mut app.cmdline.editor, intent);
310
        }
311
    }
312
4026
}
313

            
314
7
fn start_typing(app: &mut App, intent: Intent) {
315
7
    let editor = &mut app.cmdline.editor;
316
7
    match intent {
317
1
        Intent::InsertAfterCursor => editor.move_right(),
318
1
        Intent::InsertAtLineStart => editor.move_home(),
319
4
        Intent::InsertAtLineEnd => editor.move_end(),
320
1
        _ => {}
321
    }
322
7
    app.keys.set_vim(VimState::Insert);
323
7
}
324

            
325
330
fn execute(app: &mut App, cmds: Vec<Cmd>) {
326
330
    for cmd in cmds {
327
        match cmd {
328
            Cmd::Status(msg) => app.set_status(msg),
329
            Cmd::SwitchView(id) => app.switch_tab(id),
330
        }
331
    }
332
330
}
333

            
334
933
fn handle_tab(app: &mut App, intent: Intent) {
335
933
    let needs_window = !matches!(intent, Intent::SelectTab(_) | Intent::OpenCommandLine);
336
933
    if needs_window && app.front_window().is_none() {
337
5
        app.say_no_window(None);
338
5
        return;
339
928
    }
340
928
    if let Some(front) = app.front_window()
341
902
        && handle_view(app, front, intent)
342
    {
343
337
        return;
344
591
    }
345
591
    match intent {
346
40
        Intent::SelectTab(t) => app.switch_tab(t),
347
33
        Intent::NewRow => new_row(app),
348
54
        Intent::EditRow => edit_row(app),
349
29
        Intent::DeleteRow => delete_row(app),
350
147
        Intent::OpenCommandLine => app.open_command_line(),
351
4
        Intent::DetailEdit => app.edit_from_detail(),
352
6
        Intent::ConsoleFocus if app.front_is(Tab::Console) => {
353
5
            if let Some(console) = app.front_mut::<ConsoleState>() {
354
5
                console.panes.focus(PaneId::Prompt);
355
            }
356
5
            app.set_console_focused(true);
357
        }
358
        Intent::RefreshTab => {
359
17
            if let Some(tab) = app.front_kind() {
360
17
                app.refresh_windows(tab);
361
            }
362
        }
363
31
        Intent::ReportNew(kind) if app.front_is(Tab::Reports) => app.new_report(kind),
364
70
        Intent::ReportChart if app.front_is(Tab::Reports) => app.toggle_report_chart(),
365
13
        Intent::ReportCsv if app.front_is(Tab::Reports) => app.request_report_csv(),
366
13
        Intent::ListPageNext if app.front_is(Tab::Transactions) => {
367
13
            app.page_transactions(true);
368
        }
369
5
        Intent::ListPagePrev if app.front_is(Tab::Transactions) => {
370
5
            app.page_transactions(false);
371
        }
372
14
        Intent::ListFilter if app.front_is(Tab::Transactions) => {
373
14
            open_transaction_filter_modal(app);
374
        }
375
3
        Intent::ListFilterClear if app.front_is(Tab::Transactions) => {
376
3
            if let Some(window) = app.front_window() {
377
3
                app.clear_transaction_filter(window);
378
            }
379
        }
380
12
        Intent::Template(key) => template::apply_tab(app, key),
381
8
        Intent::Script(key) => script::apply_tab(app, key),
382
33
        Intent::ListMark if app.front_is(Tab::Transactions) => {
383
33
            if app.front_mut::<ListTab>().is_some_and(ListTab::toggle_mark) {
384
33
                let front = app.front_window();
385
33
                if !front.is_some_and(|front| app.continue_transactions_page(front, true))
386
24
                    && let Some(list) = app.front_mut::<ListTab>()
387
                {
388
24
                    list.select_next();
389
9
                }
390
            } else {
391
                app.set_status("no transaction selected");
392
            }
393
        }
394
1
        Intent::ListUnmarkAll if app.front_is(Tab::Transactions) => {
395
1
            if let Some(list) = app.front_mut::<ListTab>() {
396
1
                list.clear_marks();
397
            }
398
        }
399
13
        Intent::ListDeleteMarked if app.front_is(Tab::Transactions) => {
400
13
            app.open_delete_marked();
401
        }
402
30
        Intent::ListDetail if app.front_is(Tab::Transactions) => {
403
30
            app.open_transaction_detail_selected();
404
        }
405
5
        Intent::ListMergeAccount if app.front_is(Tab::Accounts) => {
406
5
            open_account_merge_for_selected(app);
407
        }
408
10
        Intent::ListAccountTransactions if app.front_is(Tab::Accounts) => {
409
10
            app.filter_transactions_of_selected_account();
410
        }
411
1
        _ => {}
412
    }
413
933
}
414

            
415
type RowAction = fn(&mut App);
416

            
417
1115
fn new_row_action(tab: Tab) -> Option<RowAction> {
418
1115
    match tab {
419
897
        Tab::Accounts => Some(open_transaction_create_modal_for_selected),
420
63
        Tab::Transactions => Some(open_transaction_create_modal),
421
23
        Tab::Commodities => Some(open_commodity_create_modal),
422
3
        Tab::Config => Some(|app| open_config_set_modal(app, &[])),
423
3
        Tab::SshKeys => Some(|app| open_ssh_key_add_modal(app, &[])),
424
20
        Tab::Tags => Some(open_tag_create_modal),
425
7
        Tab::Templates => Some(template::open_create),
426
20
        Tab::Scripts => Some(script::open_create),
427
        _ => None,
428
    }
429
1115
}
430

            
431
1460
fn edit_row_action(tab: Tab) -> Option<RowAction> {
432
1460
    match tab {
433
65
        Tab::Transactions => Some(open_selected_transaction_edit),
434
894
        Tab::Accounts => Some(open_account_edit_for_selected),
435
34
        Tab::Commodities => Some(open_commodity_edit_for_selected),
436
135
        Tab::Config => Some(open_config_edit_for_selected),
437
25
        Tab::Tags => Some(open_tag_edit_for_selected),
438
13
        Tab::Templates => Some(template::open_edit_for_selected),
439
31
        Tab::Scripts => Some(script::open_edit_for_selected),
440
258
        Tab::Reports => Some(App::edit_last_report),
441
5
        _ => None,
442
    }
443
1460
}
444

            
445
1725
fn delete_row_action(tab: Tab) -> Option<RowAction> {
446
1725
    match tab {
447
97
        Tab::Transactions => Some(confirm_delete_selected_transaction),
448
4
        Tab::SshKeys => Some(|app| open_ssh_key_remove(app, None)),
449
20
        Tab::Tags => Some(confirm_delete_selected_tag),
450
10
        Tab::Templates => Some(template::confirm_delete_selected),
451
30
        Tab::Scripts => Some(script::confirm_delete_selected),
452
1558
        _ => None,
453
    }
454
1725
}
455

            
456
33
fn new_row(app: &mut App) {
457
33
    if let Some(action) = app.front_kind().and_then(new_row_action) {
458
33
        action(app);
459
    }
460
33
}
461

            
462
54
fn edit_row(app: &mut App) {
463
54
    if let Some(action) = app.front_kind().and_then(edit_row_action) {
464
54
        action(app);
465
    }
466
54
}
467

            
468
29
fn delete_row(app: &mut App) {
469
29
    if let Some(action) = app.front_kind().and_then(delete_row_action) {
470
25
        action(app);
471
4
    }
472
29
}
473

            
474
5
fn open_selected_transaction_edit(app: &mut App) {
475
5
    match app.selected_id(Tab::Transactions) {
476
2
        Some(id) => app.open_transaction_edit_async(&id),
477
3
        None => app.set_status("no transaction selected"),
478
    }
479
5
}
480

            
481
4
fn confirm_delete_selected_transaction(app: &mut App) {
482
4
    let maybe_id = app.selected_id(Tab::Transactions);
483
4
    if let Some(id) = maybe_id {
484
2
        app.open_dialog_for(
485
2
            Tab::Transactions,
486
2
            Modal::confirm(
487
2
                format!("Delete transaction {id}?"),
488
2
                crate::modal::ConfirmAction::DeleteTransaction(id),
489
2
            ),
490
2
        );
491
2
    }
492
4
}
493

            
494
#[cfg(test)]
495
mod acts_tests;
496
#[cfg(test)]
497
mod tests;