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
//! Action context and input mode logic for runa.
//!
//! Contains the [ActionContext] struct, tracking user input state, clipboard, and action modes.
//! Defines available modes/actions for file operations (copy, paste, rename, create, delete, filter).

use crate::app::keymap::KeyPrefix;
use crate::app::nav::NavState;
use crate::core::proc::FindResult;
use crate::core::worker::{FileOperation, WorkerTask};

use crossbeam_channel::Sender;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use std::time::Instant;

/// Describes the current mode for action handling/input.
///
/// Used to determine which UI overlays, prompts, or context actions should be active.
///
/// Used by [ActionContext] to track current user action state.
#[derive(Clone, PartialEq)]
pub(crate) enum ActionMode {
    Normal,
    Input { mode: InputMode, prompt: String },
}

/// Enumerates all the available input field modes
///
/// Used to select the prompts, behavior and the style of the input dialog.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum InputMode {
    Rename,
    NewFile,
    NewFolder,
    Filter,
    ConfirmDelete { is_trash: bool },
    Find,
    MoveFile,
    GoToPath,
}

/// Tracks current user action and input buffer state for file operations and commands.
///
/// Stores the current mode/prompt, input buffer, cursor, and clipboard (for copy/yank) status.
/// Handles mutation for input, clipboard & command responses.
///
/// Used by the main application loop to manage user interactions.
/// Includes methods for performing actions like copy, paste, delete, rename, create, and filter
///
/// Also manages fuzzy find state via the embedded [FindState] struct.
///
/// Methods to manipulate input, clipboard, and perform file actions.
/// Also find management methods.
pub(crate) struct ActionContext {
    mode: ActionMode,
    input_buffer: String,
    input_cursor_pos: usize,
    clipboard: Option<HashSet<PathBuf>>,
    autocomplete: AutocompleteState,
    prefix_recognizer: KeyPrefix,
    is_cut: bool,
    find: FindState,
}

impl ActionContext {
    // Getters / accessors

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

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

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

    pub(crate) fn prefix_recognizer_mut(&mut self) -> &mut KeyPrefix {
        &mut self.prefix_recognizer
    }

    #[inline]
    pub(crate) fn clipboard(&self) -> &Option<HashSet<PathBuf>> {
        &self.clipboard
    }

    pub(crate) fn clipboard_mut(&mut self) -> &mut Option<HashSet<PathBuf>> {
        &mut self.clipboard
    }

    pub(crate) fn autocomplete_mut(&mut self) -> &mut AutocompleteState {
        &mut self.autocomplete
    }

    // Find functions

    pub(crate) fn find_state_mut(&mut self) -> &mut FindState {
        &mut self.find
    }

    #[inline]
    pub(crate) fn find_results(&self) -> &[FindResult] {
        self.find.results()
    }

    #[inline]
    pub(crate) fn find_selected(&self) -> usize {
        self.find.selected()
    }

    pub(crate) fn set_find_results(&mut self, results: Vec<FindResult>) {
        self.find.set_results(results)
    }

    pub(crate) fn clear_find_results(&mut self) {
        self.find.clear_results()
    }

    #[inline]
    pub(crate) fn find_request_id(&self) -> u64 {
        self.find.request_id()
    }

    pub(crate) fn prepare_new_find_request(&mut self) -> u64 {
        self.find.prepare_new_request()
    }

    pub(crate) fn take_query(&mut self) -> Option<String> {
        self.find.take_query(&self.input_buffer)
    }

    pub(crate) fn find_debounce(&mut self, delay: Duration) {
        self.find.set_debounce(delay);
    }

    pub(crate) fn cancel_find(&mut self) {
        self.find.cancel_current();
    }

    pub(crate) fn set_cancel_find_token(&mut self, token: Arc<AtomicBool>) {
        self.find.set_cancel(token);
    }

    pub(crate) fn set_input_buffer(&mut self, new_buf: String) {
        self.input_cursor_pos = new_buf.len();
        self.input_buffer = new_buf;
    }

    // Mode functions

    #[inline]
    pub(crate) fn is_input_mode(&self) -> bool {
        matches!(self.mode, ActionMode::Input { .. })
    }

    pub(crate) fn enter_mode(&mut self, mode: ActionMode, initial_value: String) {
        self.mode = mode;
        self.input_buffer = initial_value;
        self.input_cursor_pos = self.input_buffer.len();
    }

    pub(crate) fn exit_mode(&mut self) {
        self.mode = ActionMode::Normal;
        self.input_buffer.clear();
        self.find.reset();
        self.autocomplete.reset();
    }

    // Actions functions

    /// Deletes the currently marked files or the selected file if no markers exist.
    ///
    /// Sends a delete task to the worker thread via the provided channel.
    pub(crate) fn action_delete(
        &mut self,
        nav: &mut NavState,
        worker_tx: &Sender<WorkerTask>,
        move_to_trash: bool,
    ) {
        let targets = nav.get_action_targets();
        if targets.is_empty() {
            return;
        }

        let _ = worker_tx.send(WorkerTask::FileOp {
            op: FileOperation::Delete(targets.into_iter().collect(), move_to_trash),
        });

        nav.clear_markers();
    }

    /// Currently, cut/move is not implemented yet. Only copy/yank is used.
    /// This allows for easy addition of a cut/move feature in the future.
    /// Sets the clipboard with the selected files.
    pub(crate) fn action_copy(&mut self, nav: &NavState, is_cut: bool) {
        let mut set = HashSet::new();
        if !nav.markers().is_empty() {
            for path in nav.markers() {
                set.insert(path.clone());
            }
        } else if let Some(entry) = nav.selected_entry() {
            set.insert(nav.current_dir().join(entry.name()));
        }
        if !set.is_empty() {
            self.clipboard = Some(set);
            self.is_cut = is_cut;
        }
    }

    /// Pastes the files from the clipboard into the current directory.
    ///
    /// Sends a copy task to the worker thread via the provided channel.
    pub(crate) fn action_paste(&mut self, nav: &mut NavState, worker_tx: &Sender<WorkerTask>) {
        if let Some(source) = &self.clipboard {
            let first_file_name = source
                .iter()
                .min()
                .and_then(|p| p.file_name())
                .map(|n| n.to_os_string());

            let _ = worker_tx.send(WorkerTask::FileOp {
                op: FileOperation::Copy {
                    src: source.iter().cloned().collect(),
                    dest: nav.current_dir().to_path_buf(),
                    cut: self.is_cut,
                    focus: first_file_name,
                },
            });
            if self.is_cut {
                self.clipboard = None;
            }
            nav.clear_markers();
        }
    }

    /// Applies the current input buffer as a filter to the navigation state.
    ///
    /// Sets the filter string in the navigation state.
    pub(crate) fn action_filter(&mut self, nav: &mut NavState) {
        nav.set_filter(self.input_buffer.clone());
    }

    /// Renames the currently selected file or folder to the name in the input buffer.
    ///
    /// Sends a rename task to the worker thread via the provided channel.
    ///
    /// Exits input mode after performing the action.
    pub(crate) fn action_rename(&mut self, nav: &mut NavState, worker_tx: &Sender<WorkerTask>) {
        if self.input_buffer.is_empty() {
            return;
        }
        if let Some(entry) = nav.selected_entry() {
            let old_path = nav.current_dir().join(entry.name());
            let new_path = old_path.with_file_name(&self.input_buffer);

            let _ = worker_tx.send(WorkerTask::FileOp {
                op: FileOperation::Rename {
                    old: old_path,
                    new: new_path,
                },
            });
        }
        self.exit_mode();
    }

    /// Creates a new file or directory with the name in the input buffer.
    ///
    /// Sends a create task to the worker thread via the provided channel.
    ///
    /// Exits input mode after performing the action.
    pub(crate) fn action_create(
        &mut self,
        nav: &mut NavState,
        is_dir: bool,
        worker_tx: &Sender<WorkerTask>,
    ) {
        if self.input_buffer.is_empty() {
            return;
        }

        let path = nav.current_dir().join(&self.input_buffer);
        let _ = worker_tx.send(WorkerTask::FileOp {
            op: FileOperation::Create { path, is_dir },
        });
        self.exit_mode();
    }

    pub(crate) fn actions_move(
        &mut self,
        nav: &mut NavState,
        destination: PathBuf,
        worker_tx: &Sender<WorkerTask>,
    ) {
        let targets = nav.get_action_targets();
        if targets.is_empty() {
            return;
        }
        let _ = worker_tx.send(WorkerTask::FileOp {
            op: FileOperation::Copy {
                src: targets.into_iter().collect(),
                dest: destination,
                cut: true,
                focus: None,
            },
        });
        nav.clear_markers();
    }

    // Cursor actions

    /// Moves the input cursor one position to the left, if possible.
    pub(crate) fn action_move_cursor_left(&mut self) {
        if self.input_cursor_pos > 0 {
            self.input_cursor_pos -= 1;
        }
    }

    /// Moves the input cursor one position to the right, if possible.
    pub(crate) fn action_move_cursor_right(&mut self) {
        if self.input_cursor_pos < self.input_buffer.len() {
            self.input_cursor_pos += 1;
        }
    }

    /// Inserts a character at the current cursor position in the input buffer.
    pub(crate) fn action_insert_at_cursor(&mut self, ch: char) {
        self.input_buffer.insert(self.input_cursor_pos, ch);
        self.input_cursor_pos += ch.len_utf8();
    }

    /// Deletes the character before the current cursor position in the input buffer.
    ///
    /// Moves the cursor back accordingly
    pub(crate) fn action_backspace_at_cursor(&mut self) {
        if self.input_cursor_pos > 0
            && let Some((previous, _)) = self.input_buffer[..self.input_cursor_pos]
                .char_indices()
                .next_back()
        {
            self.input_buffer.remove(previous);
            self.input_cursor_pos = previous;
        }
    }

    /// Moves the input cursor to the start of the input buffer.
    pub(crate) fn action_cursor_home(&mut self) {
        self.input_cursor_pos = 0;
    }

    /// Moves the input cursor to the end of the input buffer.
    pub(crate) fn action_cursor_end(&mut self) {
        self.input_cursor_pos = self.input_buffer.len();
    }
}

impl Default for ActionContext {
    fn default() -> Self {
        Self {
            mode: ActionMode::Normal,
            input_buffer: String::new(),
            input_cursor_pos: 0,
            clipboard: None,
            autocomplete: AutocompleteState::default(),
            prefix_recognizer: KeyPrefix::new(Duration::from_secs(4)),
            is_cut: false,
            find: FindState::default(),
        }
    }
}

/// Tracks the state of an ongoing fuzzy find operation.
///
/// It includes the cached results, request ID, debounce timer, last query,
/// selected result index, and cancellation token.
///
/// Used by [ActionContext] to manage fuzzy find operations.
/// Methods to manage results, requests, selection, and cancellation.
#[derive(Default)]
pub(crate) struct FindState {
    cache: Vec<FindResult>,
    request_id: u64,
    debounce: Option<Instant>,
    last_query: String,
    selected: usize,
    cancel: Option<Arc<AtomicBool>>,
}

impl FindState {
    // Getters / Accessors
    #[inline]
    fn results(&self) -> &[FindResult] {
        &self.cache
    }

    #[inline]
    fn request_id(&self) -> u64 {
        self.request_id
    }

    #[inline]
    fn selected(&self) -> usize {
        self.selected
    }

    // Find functions

    /// Cancels the current ongoing find operation, if any.
    ///
    /// Sets the cancellation token to true.
    fn cancel_current(&mut self) {
        if let Some(token) = self.cancel.take() {
            token.store(true, Ordering::Relaxed);
        }
    }

    /// Sets the cached find results and resets the selected index.
    fn set_results(&mut self, results: Vec<FindResult>) {
        self.cache = results;
        self.selected = 0;
    }

    /// Sets the cancellation token for the current find operation.
    ///
    /// Sets the internal cancel token.
    fn set_cancel(&mut self, token: Arc<AtomicBool>) {
        self.cancel = Some(token);
    }

    /// Clears the cached find results.
    fn clear_results(&mut self) {
        self.cache.clear();
    }

    /// Prepares a new unique request ID for a find operation.
    /// Increments the internal request ID counter.
    fn prepare_new_request(&mut self) -> u64 {
        self.request_id = self.request_id.wrapping_add(1);
        self.request_id
    }

    /// Sets the debounce timer for the find operation.
    fn set_debounce(&mut self, delay: Duration) {
        self.debounce = Some(Instant::now() + delay);
    }

    /// Takes the current query if the debounce period has elapsed and its different from the last query.
    fn take_query(&mut self, current_query: &str) -> Option<String> {
        let until = self.debounce?;
        if Instant::now() < until {
            return None;
        }

        self.debounce = None;
        if current_query == self.last_query {
            self.last_query.clear();
            return None;
        }

        self.last_query.clear();
        self.last_query.push_str(current_query);
        Some(current_query.to_string())
    }

    /// Resets the find state, clearing cache, debounce, and last query.
    fn reset(&mut self) {
        self.cancel_current();
        self.cache.clear();
        self.debounce = None;
        self.last_query.clear();
    }

    /// Moves the selection to the next result in the cached results.
    pub(crate) fn select_next(&mut self) {
        if self.selected + 1 < self.cache.len() {
            self.selected += 1;
        }
    }

    /// Moves the selection to the previous result in the cached results.
    pub(crate) fn select_prev(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }
}

#[derive(Default)]
pub(crate) struct AutocompleteState {
    suggestions: Vec<String>,
    index: usize,
    last_input: String,
}

impl AutocompleteState {
    #[inline]
    pub(crate) fn suggestions(&self) -> &Vec<String> {
        &self.suggestions
    }

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

    pub(crate) fn reset(&mut self) {
        self.suggestions.clear();
        self.index = 0;
        self.last_input.clear();
    }

    pub(crate) fn update(&mut self, suggestions: Vec<String>, input: &str) {
        self.suggestions = suggestions;
        self.index = 0;
        self.last_input = input.to_string();
    }

    pub(crate) fn advance(&mut self) {
        if !self.suggestions.is_empty() {
            self.index = (self.index + 1) % self.suggestions.len();
        }
    }

    pub(crate) fn current(&self) -> Option<&String> {
        self.suggestions.get(self.index)
    }
}