runa-tui 0.6.2

A fast, keyboard-focused terminal file manager (TUI). Highly configurable and lightweight.
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! 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::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};

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

/// Enumeration which holds the metrics of the layout of the TUI
#[derive(Debug, Clone, Copy)]
pub(crate) struct LayoutMetrics {
    pub(crate) parent_width: usize,
    pub(crate) main_width: usize,
    pub(crate) preview_width: usize,
    pub(crate) 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(crate) 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(crate) fn new(config: &'a Config) -> std::io::Result<Self> {
        let current_dir = std::env::current_dir()?;
        Self::from_dir(config, &current_dir)
    }

    pub(crate) fn from_dir(config: &'a Config, initial_path: &Path) -> std::io::Result<Self> {
        let workers = Workers::spawn();
        let current_dir = if initial_path.exists() && initial_path.is_dir() {
            initial_path.to_path_buf()
        } else {
            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

    #[inline]
    pub(crate) fn config(&self) -> &Config {
        self.config
    }

    #[inline]
    pub(crate) fn nav(&self) -> &NavState {
        &self.nav
    }

    #[inline]
    pub(crate) fn actions(&self) -> &ActionContext {
        &self.actions
    }

    #[inline]
    pub(crate) fn preview(&self) -> &PreviewState {
        &self.preview
    }

    #[inline]
    pub(crate) fn parent(&self) -> &ParentState {
        &self.parent
    }

    #[inline]
    pub(crate) fn is_loading(&self) -> bool {
        self.is_loading
    }

    #[inline]
    pub(crate) fn notification_time(&self) -> &Option<Instant> {
        &self.notification_time
    }

    #[inline]
    pub(crate) fn overlays(&self) -> &OverlayStack {
        &self.overlays
    }

    #[inline]
    pub(crate) fn overlays_mut(&mut self) -> &mut OverlayStack {
        &mut self.overlays
    }

    // Entry functions

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

    /// Metrics updater for LayoutMetrics to request_preview new preview after old metrics
    pub(crate) fn update_layout_metrics(&mut self, metrics: LayoutMetrics) {
        let old_width = self.metrics.preview_width;
        let old_height = self.metrics.preview_height;

        self.metrics = metrics;

        if old_width != self.metrics.preview_width || old_height != self.metrics.preview_height {
            if self.preview.data().is_empty() {
                self.request_preview();
            } else {
                self.preview.mark_pending();
            }
        }
    }

    /// 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(crate) 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;
        }

        let prefix_recognizer = self.actions.prefix_recognizer_mut();
        if prefix_recognizer.is_g_state() && prefix_recognizer.expired() {
            prefix_recognizer.cancel();
            self.hide_prefix_help();
            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 { 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, request_id) => {
                    self.is_loading = false;
                    if request_id != 0 {
                        if request_id != 0 && request_id == self.preview.request_id() {
                            self.preview.set_error(e);
                        }
                    } else {
                        self.push_overlay_message(e.to_string(), Duration::from_secs(7));
                    }
                }
            }
        }
        changed
    }

    /// Central key handlers
    ///
    /// Coordinates the action and handler module functions.
    pub(crate) 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
    pub(crate) 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.general().dirs_first(),
            show_hidden: self.config.general().show_hidden(),
            show_symlink: self.config.general().show_symlink(),
            show_system: self.config.general().show_system(),
            case_insensitive: self.config.general().case_insensitive(),
            always_show: Arc::clone(self.config.general().always_show()),
            request_id,
        });
    }

    /// Requests a preview load for the currently selected entry in the navigation pane
    pub(crate) 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);
            // Set the directory generation for the preview to the request_id for WorkerResponse

            let worker_path = self
                .preview
                .current_path()
                .map(|p| p.to_path_buf())
                .unwrap_or_default();

            if entry.is_dir() || entry.is_symlink() {
                let _ = self.workers.io_tx().send(WorkerTask::LoadDirectory {
                    path: worker_path,
                    focus: None,
                    dirs_first: self.config.general().dirs_first(),
                    show_hidden: self.config.general().show_hidden(),
                    show_symlink: self.config.general().show_symlink(),
                    show_system: self.config.general().show_system(),
                    case_insensitive: self.config.general().case_insensitive(),
                    always_show: Arc::clone(self.config.general().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: worker_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(crate) 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.prepare_new_request(&parent_path_buf);

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

    /// Requests a recursive find operation for the current navigation directory
    pub(crate) 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));

        let show_hidden = self.config.general().show_hidden();

        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().general().max_find_results(),
            request_id,
            show_hidden,
            cancel: cancel_token,
        });
    }
}

// AppState tests
#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use std::time::{Duration, Instant};

    fn dummy_config() -> Config {
        Config::default()
    }

    #[test]
    fn appstate_new_from_dir_sets_initial_state() -> Result<(), Box<dyn std::error::Error>> {
        let config = dummy_config();
        let cwd = std::env::current_dir()?;
        let app = AppState::from_dir(&config, &cwd)?;
        assert_eq!(app.nav().current_dir(), cwd);
        Ok(())
    }

    #[test]
    fn tick_clears_expired_notification_message() -> Result<(), Box<dyn std::error::Error>> {
        let config = dummy_config();
        let mut app = AppState::from_dir(&config, &std::env::current_dir()?)?;
        app.notification_time = Some(Instant::now() - Duration::from_secs(2));
        app.overlays_mut().push(Overlay::Message {
            text: "Timed MSG".to_string(),
        });
        let changed = app.tick();
        assert!(changed);
        assert!(app.notification_time.is_none());
        assert!(
            !app.overlays()
                .iter()
                .any(|o| matches!(o, Overlay::Message { .. }))
        );
        Ok(())
    }

    #[test]
    fn visible_selected_and_has_visible_entries() -> Result<(), Box<dyn std::error::Error>> {
        let config = dummy_config();
        let app = AppState::from_dir(&config, &std::env::current_dir()?)?;
        let app_nav = app.nav();
        if app_nav.entries().is_empty() {
            assert_eq!(app.visible_selected(), None);
            assert!(!app.has_visible_entries());
        } else {
            assert!(app.visible_selected().is_some());
            assert!(app.has_visible_entries());
        }
        Ok(())
    }

    #[test]
    fn handle_keypress_continue_if_no_action() -> Result<(), Box<dyn std::error::Error>> {
        let config = dummy_config();
        let mut app = AppState::from_dir(&config, &std::env::current_dir()?)?;
        let key = KeyEvent::new(KeyCode::Null, KeyModifiers::NONE);
        let result = app.handle_keypress(key);
        assert!(matches!(result, KeypressResult::Continue));
        Ok(())
    }

    #[test]
    fn request_dir_load_sets_is_loading() -> Result<(), Box<dyn std::error::Error>> {
        let config = dummy_config();
        let mut app = AppState::from_dir(&config, &std::env::current_dir()?)?;
        app.is_loading = false;
        app.request_dir_load(None);
        assert!(app.is_loading);
        Ok(())
    }

    #[test]
    fn request_parent_content_handles_root() -> Result<(), Box<dyn std::error::Error>> {
        let config = dummy_config();
        let mut app = AppState::from_dir(&config, &std::env::current_dir()?)?;
        #[cfg(unix)]
        {
            use std::path::PathBuf;
            app.nav.set_path(PathBuf::from("/"));
            app.request_parent_content();
            assert!(app.parent.entries().is_empty());
        }
        #[cfg(windows)]
        {
            use std::path::PathBuf;
            app.nav.set_path(PathBuf::from("C:\\"));
            app.request_parent_content();
            assert!(app.parent.entries().is_empty());
        }
        Ok(())
    }
}