1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! Application module for `weavetui`.
//!
//! This module defines the core `App` structure, which manages the application's lifecycle,
//! event handling, and component interactions within the TUI environment.
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent};
use tokio::sync::mpsc::{self, error::TryRecvError};
use crate::{
event::{Action, ActionKind, Event},
keyboard::KeyBindings,
theme::{Theme, ThemeManager},
tui::Tui,
Component, ComponentHandler,
};
/// `App` is the main application structure that orchestrates the TUI.
///
/// It manages the event loop, handles user input, dispatches actions to components,
/// and renders the UI.
#[derive(Debug)]
pub struct App {
tick_rate: f64,
frame_rate: f64,
should_quit: bool,
keybindings: KeyBindings,
last_tick_key_events: Vec<KeyEvent>,
mouse: bool,
paste: bool,
component_handlers: Vec<ComponentHandler>,
theme_manager: ThemeManager,
action_tx: mpsc::UnboundedSender<Action>,
action_rx: mpsc::UnboundedReceiver<Action>,
}
impl Default for App {
/// Creates a new `App` instance with default settings. This includes an unbounded MPSC channel for actions, default tick and frame rates, and no initial components or keybindings.
fn default() -> Self {
let (action_tx, action_rx) = mpsc::unbounded_channel::<Action>();
Self {
last_tick_key_events: Vec::default(),
keybindings: KeyBindings::default(),
component_handlers: Vec::new(),
theme_manager: ThemeManager::default(),
frame_rate: 24.into(),
tick_rate: 1.into(),
should_quit: false,
mouse: false,
paste: false,
action_tx,
action_rx,
}
}
}
impl App {
/// Creates a new `App` instance with specified keybindings and initial components.
///
/// # Arguments
///
/// * `kb` - An array of keybinding tuples, mapping key combinations to action kinds.
/// * `components` - A vector of boxed `Component` traits to be managed by the app.
pub fn new<const N: usize>(kb: [(&str, &str); N], components: Vec<Box<dyn Component>>) -> Self {
let keybindings = KeyBindings::new(kb);
let component_handlers = components
.into_iter()
.map(ComponentHandler::for_)
.collect::<Vec<_>>();
Self {
component_handlers,
keybindings,
..Self::default()
}
}
/// Adds a collection of components to the application.
///
/// # Arguments
///
/// * `components` - A vector of boxed `Component` traits to be added.
///
/// # Returns
///
/// The modified `App` instance.
pub fn with_components(mut self, components: Vec<Box<dyn Component>>) -> Self {
self.component_handlers
.extend(components.into_iter().map(ComponentHandler::for_));
self
}
/// Sets the keybindings for the application.
///
/// # Arguments
///
/// * `kb` - An array of keybinding tuples, mapping key combinations to action kinds.
///
/// # Returns
///
/// The modified `App` instance.
pub fn with_keybindings<const N: usize>(
mut self,
kb: [(&str, impl Into<ActionKind>); N],
) -> Self {
self.keybindings = KeyBindings::new(kb);
self
}
/// Sets the tick rate for the application's event loop.
///
/// The tick rate determines how often the application processes events and updates its state.
///
/// # Arguments
///
/// * `tick_rate` - The desired tick rate in Hertz (Hz).
///
/// # Returns
///
/// The modified `App` instance.
pub fn with_tick_rate(mut self, tick_rate: impl Into<f64>) -> Self {
self.tick_rate = tick_rate.into();
self
}
/// Sets the frame rate for rendering the application's UI.
///
/// The frame rate determines how often the application redraws the terminal screen.
///
/// # Arguments
///
/// * `frame_rate` - The desired frame rate in frames per second (fps).
///
/// # Returns
///
/// The modified `App` instance.
pub fn with_frame_rate(mut self, frame_rate: impl Into<f64>) -> Self {
self.frame_rate = frame_rate.into();
self
}
/// Enables or disables mouse event handling for the application.
///
/// # Arguments
///
/// * `mouse` - `true` to enable mouse support, `false` to disable.
///
/// # Returns
///
/// The modified `App` instance.
pub fn with_mouse(mut self, mouse: bool) -> Self {
self.mouse = mouse;
self
}
/// Enables or disables paste event handling for the application.
///
/// # Arguments
///
/// * `paste` - `true` to enable paste support, `false` to disable.
///
/// # Returns
///
/// The modified `App` instance.
pub fn with_paste(mut self, paste: bool) -> Self {
self.paste = paste;
self
}
/// Adds a theme to the application.
///
/// If no active theme is set, this theme will be set as the active theme.
///
/// # Arguments
///
/// * `theme` - The `Theme` to add.
///
/// # Returns
///
/// The modified `App` instance.
pub fn add_theme(mut self, theme: Theme) -> Self {
if !self.theme_manager.has_active_theme() {
self.theme_manager.set_active_theme(&theme.name);
}
self.theme_manager.add_theme(theme);
self
}
/// Sends an `Action` to the application's action channel.
///
/// This method is used internally to dispatch actions that need to be processed by the `App`
/// or its components.
///
/// # Arguments
///
/// * `action` - The `Action` to send.
///
/// # Returns
///
/// A `Result` indicating success or failure.
fn send(&self, action: Action) -> Result<()> {
self.action_tx.send(action)?;
Ok(())
}
/// Attempts to receive an `Action` from the application's action channel without blocking.
///
/// # Returns
///
/// A `Result` containing the received `Action` or a `TryRecvError` if no action is available.
fn try_recv(&mut self) -> Result<Action, TryRecvError> {
self.action_rx.try_recv()
}
/// Runs the main application loop.
///
/// This asynchronous function initializes the TUI, sets up event handling, and continuously
/// processes events (keyboard, mouse, tick, render) and dispatches actions to registered
/// components. The loop continues until a `Quit` action is received.
///
/// # Returns
///
/// A `Result` indicating the success or failure of the application execution.
pub async fn run(&mut self) -> Result<()> {
let mut tui = Tui::new()?
.tick_rate(self.tick_rate)
.frame_rate(self.frame_rate)
.mouse(self.mouse)
.paste(self.paste);
tui.enter()?;
for handler in self.component_handlers.iter_mut() {
handler.receive_action_handler(self.action_tx.clone());
handler.handle_theme(self.theme_manager.clone());
handler.handle_custom_keybindings(&mut self.keybindings);
}
// Check for Action::Quit
if !self
.keybindings
.0
.iter()
.any(|(_, action)| *action == Action::Quit)
{
anyhow::bail!("Action::Quit is not bound to any key. Consider binding it for graceful exit (e.g., <ctrl-c>).");
}
let mut initialize = false;
loop {
if let Some(e) = tui.next().await {
match e {
Event::Resize(x, y) => self.send(Action::Resize(x, y))?,
Event::Render => self.send(Action::Render)?,
Event::Tick => self.send(Action::Tick)?,
Event::Quit => self.send(Action::Quit)?,
Event::Key(key) => {
if let Some(action) = self.keybindings.get(&[key]) {
self.send(action.clone())?;
} else {
// If the key was not handled as a single key action,
// then consider it for multi-key combinations.
self.last_tick_key_events.push(key);
// Check for multi-key combinations
if let Some(action) = self.keybindings.get(&self.last_tick_key_events) {
self.send(action.clone())?;
}
}
// send the key event as simple key event too (not as action) if it's a
// single alphanumeric char key
if let KeyCode::Char(c) = key.code {
if c.is_alphanumeric() {
self.send(Action::Key(c.to_string()))?;
}
}
}
_ => {}
}
let mut actions = Vec::new();
for handler in self.component_handlers.iter_mut() {
let component_actions = handler.handle_events(&Some(e.clone()));
actions.extend(component_actions);
}
for action in actions {
self.send(action)?;
}
}
while let Ok(action) = self.try_recv() {
match action {
Action::Quit => self.should_quit = true,
Action::Render => {
tui.draw(|f| {
for handler in self.component_handlers.iter_mut() {
let area = f.area();
if !initialize {
handler.handle_init(area);
initialize = true;
}
handler.c.set_area(area);
handler.handle_draw(f);
}
})?;
}
Action::Tick => {
self.last_tick_key_events.drain(..);
}
Action::AppAction(ref m) => {
for handler in self.component_handlers.iter_mut() {
if handler.c.is_active() {
handler.handle_message(m.as_str());
}
}
}
_ => {}
}
for handler in self.component_handlers.iter_mut() {
handler.handle_update(&action);
}
}
if self.should_quit {
tui.stop()?;
break;
}
}
tui.exit()?;
Ok(())
}
}