Skip to main content

tui/
app.rs

1//! Application state for the TUI.
2//!
3//! The TUI is organised as a small state machine:
4//!
5//! - A top-level menu bar: View raises or opens a view, Window arranges the windows.
6//! - The windows live in a list; each owns a view, a multi-pane area managed by the view itself.
7//! - An overlay stack sits on top of the whole lot and intercepts input
8//!   when non-empty.
9//! - A bottom command line is always visible.
10//!
11//! All of this is pure state: no rendering happens in this file. The
12//! draw layer reads from `App` and renders; the event layer mutates
13//! `App` via named methods so tests can drive state transitions
14//! without a real terminal.
15
16mod account_balances;
17mod arrange;
18mod balance;
19mod bulk_delete;
20mod button_press;
21mod close;
22mod convert;
23mod deliver;
24mod detail;
25mod drag;
26mod edit;
27mod eval;
28mod filter;
29mod form_options;
30mod hold;
31mod lookup;
32mod menu;
33mod merge;
34mod mutation;
35mod open;
36mod paging;
37mod pending;
38mod refresh;
39mod report_args;
40mod report_chart;
41mod report_csv;
42mod report_rerun;
43mod scripts;
44mod ssh_keys;
45mod tag_hints;
46mod tags;
47mod template_pick;
48mod template_test;
49mod templates;
50mod ui_config;
51mod viewer;
52mod window_list;
53mod windows;
54
55#[cfg(test)]
56pub(crate) use button_press::KEY_PRESS;
57pub(crate) use button_press::button_of_key;
58pub(crate) use hold::{Face, Owner};
59pub use ui_config::{CliConfig, parse_colors};
60
61use std::collections::HashMap;
62
63pub use lookup::Lookup;
64pub use menu::{MenuEntry, MenuId};
65pub use pending::PendingForm;
66
67use crate::hits::Hits;
68use crate::keymap::{Keys, VimState};
69use crate::modal::{ConfirmAction, Modal};
70use crate::mouse::Click;
71use crate::overlay::OverlayStack;
72use crate::route::Route;
73use crate::tabs::nms_eval::ConsoleEval;
74use crate::tabs::reports::chart::TerminalState;
75use crate::tabs::seq::Seq;
76use crate::view::Tab;
77use crate::widgets::Editor;
78use crate::window::{Win, WindowId};
79use sqlx::types::Uuid;
80use tvui::{ColorDepth, Desktop, RowWindow, Theme};
81use ui_config::UiConfig;
82
83/// Command-line palette editor state.
84pub struct CmdLine {
85    pub editor: Editor,
86    pub active: bool,
87    /// Completion candidates for the current buffer, refreshed on each Tab press.
88    pub completions: Vec<String>,
89}
90
91impl CmdLine {
92    fn new() -> Self {
93        Self {
94            editor: Editor::default(),
95            active: false,
96            completions: Vec::new(),
97        }
98    }
99}
100
101pub struct App {
102    pub user_id: Uuid,
103    pub theme: Theme,
104    ui_config: UiConfig,
105    pub overlays: OverlayStack,
106    /// The submitted form awaiting its reply; owns input focus while set.
107    pub pending_form: Option<PendingForm>,
108    pub cmdline: CmdLine,
109    /// The open menu and its selected entry; `None` while it is closed.
110    pub menu: Option<(MenuId, usize)>,
111    /// Which entries of the open menu are in view.
112    pub menu_window: RowWindow,
113    /// What the mouse, a key or the size/move mode holds: a drag, or a press awaiting its release or its time.
114    pub(crate) hold: Option<hold::Hold>,
115    /// The clickable areas of the last frame drawn.
116    pub hits: Hits,
117    /// The last left click on a list row, for the double click.
118    pub(crate) last_click: Option<Click>,
119    pub keys: Keys,
120    pub status: String,
121    /// The window whose failed reply wrote `status`; only its next success clears it.
122    status_owner: Option<WindowId>,
123    pub should_quit: bool,
124    /// The async eval bridge. `None` until attached via [`App::attach_console`].
125    console_eval: Option<ConsoleEval>,
126    /// Routes pending eval reply ids to their destination view.
127    pending_routes: HashMap<i64, Route>,
128    /// Monotonic counter for form-options fetches; shared across all forms
129    /// that populate Selects. A stale reply (wrong seq) is silently dropped.
130    form_options_seq: Seq,
131    /// Counts tag-list suggestion lookups; the form drops an answer of an older one.
132    suggest_seq: Seq,
133    /// Counts palette account-merge lookups; a reply of an older one is dropped.
134    merge_seq: Seq,
135    /// Counts palette account-balance lookups; a reply of an older one is dropped.
136    balance_seq: Seq,
137    /// Counts template tests; a reply of an older one is dropped.
138    template_test_seq: Seq,
139    /// Counts template picker requests; a reply of an older one is dropped.
140    template_pick_seq: Seq,
141    /// Whether the transport runs on the user's machine, so saving a file is allowed.
142    pub local_files: bool,
143    /// Raw terminal output queued for the transport's passthrough.
144    outbound: Vec<Vec<u8>>,
145    bulk: bulk_delete::BulkDelete,
146    windows: Vec<Win>,
147    /// The id the next window gets; ids are never reused.
148    next_window: u32,
149    /// Order, rect and zoom of the windows; the front one is the active view.
150    desktop: Desktop<WindowId>,
151    /// What the terminal is and the chart backend the user forced, for every Reports window.
152    pub(crate) terminal: TerminalState,
153}
154
155impl App {
156    /// The app with the theme and keymap the command line chose; `auto_depth` is what `auto` colours mean.
157    ///
158    /// # Errors
159    /// The message of a command-line theme or a keymap preset that does not build.
160    pub fn new(user_id: Uuid, cli: CliConfig, auto_depth: ColorDepth) -> Result<Self, String> {
161        let ui_config = UiConfig::new(cli, auto_depth);
162        let (theme, _) = ui_config.build([None, None, None])?;
163        let (keys, _) = ui_config.keys(None, None)?;
164        Ok(Self {
165            user_id,
166            ui_config,
167            theme,
168            overlays: OverlayStack::new(),
169            pending_form: None,
170            cmdline: CmdLine::new(),
171            menu: None,
172            menu_window: RowWindow::default(),
173            hold: None,
174            hits: Hits::default(),
175            last_click: None,
176            keys,
177            status: String::new(),
178            status_owner: None,
179            should_quit: false,
180            console_eval: None,
181            pending_routes: HashMap::new(),
182            form_options_seq: Seq::default(),
183            suggest_seq: Seq::default(),
184            merge_seq: Seq::default(),
185            balance_seq: Seq::default(),
186            template_test_seq: Seq::default(),
187            template_pick_seq: Seq::default(),
188            local_files: false,
189            outbound: Vec::new(),
190            bulk: bulk_delete::BulkDelete::default(),
191            windows: Vec::new(),
192            next_window: 0,
193            desktop: Desktop::default(),
194            terminal: TerminalState::default(),
195        })
196    }
197
198    pub fn switch_tab(&mut self, tab: Tab) {
199        let window = self.window_or_open(tab).window;
200        self.activate_window(window);
201    }
202
203    pub fn open_command_line(&mut self) {
204        self.cmdline.editor = Editor::default();
205        self.keys.set_vim(VimState::Insert);
206        self.cmdline.active = true;
207        self.cmdline.completions.clear();
208    }
209
210    pub fn close_command_line(&mut self) {
211        self.cmdline.active = false;
212        self.cmdline.completions.clear();
213    }
214
215    pub fn set_status(&mut self, msg: impl Into<String>) {
216        self.status = msg.into();
217        self.status_owner = None;
218    }
219
220    pub fn clear_status(&mut self) {
221        self.set_status("");
222    }
223
224    pub fn confirm_quit(&mut self) {
225        self.overlays
226            .push(Modal::confirm("Quit?", ConfirmAction::Quit));
227    }
228
229    pub fn request_quit(&mut self) {
230        self.should_quit = true;
231    }
232
233    /// Attaches the console and reads the UI config.
234    pub fn attach_console(&mut self, eval: ConsoleEval) {
235        self.console_eval = Some(eval);
236        self.read_ui_config();
237    }
238}
239
240#[cfg(test)]
241pub(crate) mod tests;