runa-tui 0.5.2

A fast, keyboard-focused terminal file browser (TUI). Highly configurable and lightweight. Previously known as runner-tui.
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Application State and main controller module for runa.
//!
//! This module defines the overall [AppState] struct, which holds all major application
//! information and passes it to relevant UI/Terminal functions
//! - Configuration (loaded from config files)
//! - Pane view models for navigation, preview and parent states.
//! - Action context for relevant inputs
//! - Current layout metrics
//! - Communication with worker threads via crossbeam_channel
//! - Notification and message handling
//!
//! This module coordinates user input processing, keybindings, state mutation,
//! pane switching and communication with worder tasks
//!
//! This is the primary context/state object passed to most UI/Terminal event logic.

use crate::app::actions::{ActionContext, ActionMode, InputMode};
use crate::app::keymap::{Action, Keymap, SystemAction};
use crate::app::{NavState, ParentState, PreviewState};
use crate::config::Config;
use crate::core::worker::{WorkerResponse, WorkerTask, Workers};
use crate::ui::overlays::{Overlay, OverlayStack};

use crossterm::event::KeyEvent;
use std::ffi::OsString;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Instant;

/// Enumeration for each individual keypress result processed.
///
/// Is used to process action logic correctly.
pub enum KeypressResult {
    Continue,
    Consumed,
    Quit,
    OpenedEditor,
}

/// Enumeration which holds the metrics of the layout of the TUI
#[derive(Debug, Clone, Copy)]
pub struct LayoutMetrics {
    pub parent_width: usize,
    pub main_width: usize,
    pub preview_width: usize,
    pub preview_height: usize,
}

impl Default for LayoutMetrics {
    fn default() -> Self {
        Self {
            parent_width: 20,
            main_width: 40,
            preview_width: 40,
            preview_height: 50,
        }
    }
}

/// Main struct which holds the central Application state of runa
///
/// AppState holds all the persisten state for the application while it is running
///
/// Includes:
/// - References to configuration settings and the keymaps.
/// - Models for navigation, actions, file previews, and parent directory pane
/// - Live layout information
/// - crossbeam channels for communication with background worker threads
/// - Notification timing and loading indicators
/// - UI overlay for a seamless widet rendering
///
/// Functions are provided for the core event loop, input handling, file navigationm
/// worker requests and Notification management.
pub struct AppState<'a> {
    pub(super) config: &'a Config,
    pub(super) keymap: Keymap,

    pub(super) metrics: LayoutMetrics,

    pub(super) nav: NavState,
    pub(super) actions: ActionContext,
    pub(super) preview: PreviewState,
    pub(super) parent: ParentState,

    pub(super) workers: Workers,
    pub(super) is_loading: bool,

    pub(super) notification_time: Option<Instant>,
    pub(super) overlays: OverlayStack,
}

impl<'a> AppState<'a> {
    pub fn new(config: &'a Config) -> std::io::Result<Self> {
        let workers = Workers::spawn();
        let current_dir = std::env::current_dir()?;

        let mut app = Self {
            config,
            keymap: Keymap::from_config(config),
            metrics: LayoutMetrics::default(),
            nav: NavState::new(current_dir),
            actions: ActionContext::default(),
            preview: PreviewState::default(),
            parent: ParentState::default(),
            workers,
            is_loading: false,
            notification_time: None,
            overlays: OverlayStack::new(),
        };

        app.request_dir_load(None);
        app.request_parent_content();
        Ok(app)
    }

    // Getters/ accessors

    pub fn config(&self) -> &Config {
        self.config
    }

    pub fn metrics(&self) -> &LayoutMetrics {
        &self.metrics
    }

    pub fn metrics_mut(&mut self) -> &mut LayoutMetrics {
        &mut self.metrics
    }

    pub fn nav(&self) -> &NavState {
        &self.nav
    }

    pub fn actions(&self) -> &ActionContext {
        &self.actions
    }

    pub fn preview(&self) -> &PreviewState {
        &self.preview
    }

    pub fn parent(&self) -> &ParentState {
        &self.parent
    }

    pub fn notification_time(&self) -> &Option<Instant> {
        &self.notification_time
    }

    pub fn overlays(&self) -> &OverlayStack {
        &self.overlays
    }

    pub fn overlays_mut(&mut self) -> &mut OverlayStack {
        &mut self.overlays
    }

    pub fn set_notification_time(&mut self, t: Option<Instant>) {
        self.notification_time = t;
    }

    // Entry functions

    pub fn visible_selected(&self) -> Option<usize> {
        if self.nav.entries().is_empty() {
            None
        } else {
            Some(self.nav.selected_idx())
        }
    }
    pub fn has_visible_entries(&self) -> bool {
        !self.nav.entries().is_empty()
    }

    /// The heart of the app: updates state and handles worker messages
    ///
    /// Is used by the main event loop to update the application state.
    /// Returns a bool to determine if the AppState needs reloading
    /// and sets it to true if a WorkerResponse was made or if a preview should be triggered.
    pub fn tick(&mut self) -> bool {
        let mut changed = false;

        if let Some(expiry) = self.notification_time
            && Instant::now() >= expiry
        {
            self.notification_time = None;

            self.overlays_mut()
                .retain(|o| !matches!(o, Overlay::Message { .. }));

            changed = true;
        }

        // Handle preview debounc
        if self.preview.should_trigger() {
            self.request_preview();
            changed = true;
        }

        let current_selection_path = self
            .nav
            .selected_entry()
            .map(|entry| self.nav.current_dir().join(entry.name()));

        // Find handling with debounce
        if let ActionMode::Input {
            mode: InputMode::Find,
            ..
        } = self.actions.mode()
            && let Some(query) = self.actions.take_query()
        {
            if query.is_empty() {
                self.actions.clear_find_results();
            } else {
                self.request_find(query);
            }
            changed = true;
        }

        // Process worker response
        while let Ok(response) = self.workers.response_rx().try_recv() {
            changed = true;
            match response {
                WorkerResponse::DirectoryLoaded {
                    path,
                    entries,
                    focus,
                    request_id,
                } => {
                    // only update nav if BOTH the ID and path match.
                    if request_id == self.nav.request_id() && path == self.nav.current_dir() {
                        self.nav.update_from_worker(path, entries, focus);
                        self.is_loading = false;
                        self.request_preview();
                        self.request_parent_content();
                        self.refresh_show_info_if_open();
                    }
                    // PREVIEW CHECK: Must match the current preview request
                    else if request_id == self.preview.request_id() {
                        if current_selection_path.as_ref() == Some(&path) {
                            self.preview.update_from_entries(entries, request_id);

                            let pos = current_selection_path
                                .as_ref()
                                .and_then(|p| self.nav.get_position().get(p))
                                .copied()
                                .unwrap_or(0);

                            self.preview.set_selected_idx(pos);
                        }
                    }
                    // PARENT CHECK: Must match the current parent request
                    else if request_id == self.parent.request_id() {
                        let current_name = self
                            .nav
                            .current_dir()
                            .file_name()
                            .map(|n| n.to_string_lossy().to_string())
                            .unwrap_or_default();

                        self.parent
                            .update_from_entries(entries, &current_name, request_id, &path);
                    }
                }
                WorkerResponse::PreviewLoaded { lines, request_id } => {
                    if request_id == self.preview.request_id() {
                        self.preview.update_content(lines, request_id);
                    }
                }

                WorkerResponse::OperationComplete {
                    message: _,
                    request_id: _,
                    need_reload,
                    focus,
                } => {
                    if need_reload {
                        self.request_dir_load(focus);
                        self.request_parent_content();
                    }
                }

                WorkerResponse::FindResults {
                    base_dir,
                    results,
                    request_id,
                } => {
                    if base_dir == self.nav.current_dir()
                        && request_id == self.actions.find_request_id()
                    {
                        self.actions.set_find_results(results);
                    }
                }

                WorkerResponse::Error(e) => {
                    self.preview.set_error(e);
                }
            }
        }
        changed
    }

    /// Central key handlers
    ///
    /// Coordinates the action and handler module functions.
    pub fn handle_keypress(&mut self, key: KeyEvent) -> KeypressResult {
        if self.actions.is_input_mode() {
            return self.handle_input_mode(key);
        }

        if let Some(action) = self.keymap.lookup(key) {
            match action {
                Action::System(SystemAction::Quit) => return KeypressResult::Quit,
                Action::Nav(nav_act) => return self.handle_nav_action(nav_act),
                Action::File(file_act) => return self.handle_file_action(file_act),
            }
        }

        KeypressResult::Continue
    }

    // Worker requests functions for directory loading, preview and parent pane content

    /// Requests a directory load for the current navigation directory
    ///
    /// # Arguments
    /// * `focus` - Optional OsString to focus on a specific entry after loading
    pub fn request_dir_load(&mut self, focus: Option<std::ffi::OsString>) {
        self.is_loading = true;
        let request_id = self.nav.prepare_new_request();
        let _ = self.workers.io_tx().send(WorkerTask::LoadDirectory {
            path: self.nav.current_dir().to_path_buf(),
            focus,
            dirs_first: self.config.dirs_first(),
            show_hidden: self.config.show_hidden(),
            show_system: self.config.show_system(),
            case_insensitive: self.config.case_insensitive(),
            always_show: Arc::clone(self.config.always_show()),
            request_id,
        });
    }

    /// Requests a preview load for the currently selected entry in the navigation pane
    pub fn request_preview(&mut self) {
        if let Some(entry) = self.nav.selected_shown_entry() {
            let path = self.nav.current_dir().join(entry.name());
            let req_id = self.preview.prepare_new_request(path.clone());
            // Set the directory generation for the preview to the request_id for WorkerResponse

            if entry.is_dir() || entry.is_symlink() {
                let _ = self.workers.io_tx().send(WorkerTask::LoadDirectory {
                    path,
                    focus: None,
                    dirs_first: self.config.dirs_first(),
                    show_hidden: self.config.show_hidden(),
                    show_system: self.config.show_system(),
                    case_insensitive: self.config.case_insensitive(),
                    always_show: Arc::clone(self.config.always_show()),
                    request_id: req_id,
                });
            } else {
                let preview_options = self.config.display().preview_options();
                let preview_method = preview_options.method().clone();
                let bat_args = self
                    .config
                    .bat_args_for_preview(self.metrics.preview_width)
                    .into_iter()
                    .map(OsString::from)
                    .collect();
                let _ = self.workers.preview_tx().send(WorkerTask::LoadPreview {
                    path,
                    max_lines: self.metrics.preview_height,
                    pane_width: self.metrics.preview_width,
                    preview_method,
                    args: bat_args,
                    request_id: req_id,
                });
            }
        } else {
            self.preview.clear();
        }
    }

    /// Requests loading of the parent directory content for the parent pane
    pub fn request_parent_content(&mut self) {
        if let Some(parent_path) = self.nav.current_dir().parent() {
            let parent_path_buf = parent_path.to_path_buf();

            if self.parent.should_request(&parent_path_buf) {
                let req_id = self.parent.request_id();

                let _ = self.workers.io_tx().send(WorkerTask::LoadDirectory {
                    path: parent_path_buf,
                    focus: None,
                    dirs_first: self.config.dirs_first(),
                    show_hidden: self.config.show_hidden(),
                    show_system: self.config.show_system(),
                    case_insensitive: self.config.case_insensitive(),
                    always_show: Arc::clone(self.config.always_show()),
                    request_id: req_id,
                });
            }
        } else {
            // at root.
            self.parent.clear();
        }
    }

    /// Requests a recursive find operation for the current navigation directory
    pub fn request_find(&mut self, query: String) {
        self.actions.cancel_find();

        let request_id = self.actions.prepare_new_find_request();
        let cancel_token = Arc::new(AtomicBool::new(false));

        self.actions
            .set_cancel_find_token(Arc::clone(&cancel_token));

        let _ = self.workers.find_tx().send(WorkerTask::FindRecursive {
            base_dir: self.nav.current_dir().to_path_buf(),
            query,
            max_results: self.config().max_find_results(),
            request_id,
            cancel: cancel_token,
        });
    }
}