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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Worker thread for the runa core operations.
//!
//! Handles directory reads, previews and file operatios on a background thread.
//! All results and errors are sent back via channels.
//!
//! Small changes here can have big effects since this module is tightly integrated with every part
//! of runa.
//!
//! Requests [WorkerTask] come in from the AppState or UI via channels, and results or errors
//! [WorkerResponse] go back the same way. All filesystem I/O and previews happen on these threads
//!
//! # Caution:
//! This module is a central protocol boundary. Small changes (adding or editing variants, fields, or error handling)
//! may require corresponding changes throughout state, response-handling code and UI.

use crate::config::display::PreviewMethod;
use crate::core::{
    FileEntry, FindResult, Formatter, browse_dir, find, preview_bat, safe_read_preview,
};
use crate::utils::{copy_recursive, get_unused_path};

use crossbeam_channel::{Receiver, Sender, bounded, unbounded};

use std::collections::HashSet;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;

/// Manages worker threads channels for different task types.
pub struct Workers {
    io_tx: Sender<WorkerTask>,
    find_tx: Sender<WorkerTask>,
    preview_tx: Sender<WorkerTask>,
    fileop_tx: Sender<WorkerTask>,
    response_rx: Receiver<WorkerResponse>,
}

/// Manages worker thread channels for different task types.
///
/// Each major operation (I/O, preview, find, file-ops) has its own dedicated worker thread.
///
/// The find worker uses a bounded channel of size 1: this design ensures that only the
/// latest find request will be processed, automatically skipping obsolete queued requests
/// from rapid-fire user input. This keeps search operations efficient, responsive, and
/// guarantees only one concurrent find per application.
impl Workers {
    /// Create the worker set.
    ///
    /// Spawns dedicated threads for I/O, preview, find and file operations.
    pub fn spawn() -> Self {
        let (io_tx, io_rx) = unbounded::<WorkerTask>();
        let (preview_tx, preview_rx) = unbounded::<WorkerTask>();
        let (find_tx, find_rx) = bounded::<WorkerTask>(1);
        let (fileop_tx, fileop_rx) = unbounded::<WorkerTask>();
        let (res_tx, response_rx) = unbounded::<WorkerResponse>();

        start_io_worker(io_rx, res_tx.clone());
        start_preview_worker(preview_rx, res_tx.clone());
        start_find_worker(find_rx, res_tx.clone());
        start_fileop_worker(fileop_rx, res_tx.clone());

        Self {
            io_tx,
            preview_tx,
            find_tx,
            fileop_tx,
            response_rx,
        }
    }

    /// Accessor the I/O worker task sender.
    pub fn io_tx(&self) -> &Sender<WorkerTask> {
        &self.io_tx
    }

    /// Accessor for the preview worker task sender.
    pub fn preview_tx(&self) -> &Sender<WorkerTask> {
        &self.preview_tx
    }

    /// Accessor for the find worker task sender.
    pub fn find_tx(&self) -> &Sender<WorkerTask> {
        &self.find_tx
    }

    /// Accessor for the file operation worker task sender.
    pub fn fileop_tx(&self) -> &Sender<WorkerTask> {
        &self.fileop_tx
    }

    /// Accessor for the worker response receiver.
    pub fn response_rx(&self) -> &Receiver<WorkerResponse> {
        &self.response_rx
    }
}

/// Tasks sent to the worker thread via channel.
///
/// Each variant describes a filesystem or a preview operation to perform.
pub enum WorkerTask {
    LoadDirectory {
        path: PathBuf,
        focus: Option<OsString>,
        dirs_first: bool,
        show_hidden: bool,
        show_system: bool,
        case_insensitive: bool,
        always_show: Arc<HashSet<OsString>>,
        request_id: u64,
    },
    LoadPreview {
        path: PathBuf,
        max_lines: usize,
        pane_width: usize,
        preview_method: PreviewMethod,
        args: Vec<OsString>,
        request_id: u64,
    },
    FileOp {
        op: FileOperation,
        request_id: u64,
    },
    FindRecursive {
        base_dir: PathBuf,
        query: String,
        max_results: usize,
        cancel: Arc<AtomicBool>,
        request_id: u64,
    },
}

/// Supported file system operations the worker can perform.
pub enum FileOperation {
    Delete(Vec<PathBuf>),
    Rename {
        old: PathBuf,
        new: PathBuf,
    },
    Copy {
        src: Vec<PathBuf>,
        dest: PathBuf,
        cut: bool,
        focus: Option<OsString>,
    },
    Create {
        path: PathBuf,
        is_dir: bool,
    },
}

/// Responses sent form the worker thread back to the main thread via the channel
///
/// Each variant delivers the result or error from a request taks.
#[derive(Debug)]
pub enum WorkerResponse {
    DirectoryLoaded {
        path: PathBuf,
        entries: Vec<FileEntry>,
        focus: Option<OsString>,
        request_id: u64,
    },
    PreviewLoaded {
        lines: Vec<String>,
        request_id: u64,
    },
    OperationComplete {
        message: String,
        request_id: u64,
        need_reload: bool,
        focus: Option<OsString>,
    },
    FindResults {
        base_dir: PathBuf,
        results: Vec<FindResult>,
        request_id: u64,
    },
    Error(String),
}

/// Starts the io worker thread, wich listens to [WorkerTask] and sends back to [WorkerResponse]
///
/// # Arguments
/// * `task_rx` - Receiver channel for incoming tasks
/// * `res_tx` - Sender channel for outgoing responses
fn start_io_worker(task_rx: Receiver<WorkerTask>, res_tx: Sender<WorkerResponse>) {
    thread::spawn(move || {
        while let Ok(task) = task_rx.recv() {
            let WorkerTask::LoadDirectory {
                path,
                focus,
                dirs_first,
                show_hidden,
                show_system,
                case_insensitive,
                always_show,
                request_id,
            } = task
            else {
                continue;
            };
            match browse_dir(&path) {
                Ok(mut entries) => {
                    let formatter = Formatter::new(
                        dirs_first,
                        show_hidden,
                        show_system,
                        case_insensitive,
                        always_show,
                    );
                    formatter.filter_entries(&mut entries);
                    let _ = res_tx.send(WorkerResponse::DirectoryLoaded {
                        path,
                        entries,
                        focus,
                        request_id,
                    });
                }
                Err(e) => {
                    let _ = res_tx.send(WorkerResponse::Error(format!("I/O Error: {}", e)));
                }
            }
        }
    });
}

/// Starts the preview worker thread
///
/// # Arguments
/// * `task_rx` - Receiver channel for incoming tasks
/// * `res_tx` - Sender channel for outgoing responses
fn start_preview_worker(task_rx: Receiver<WorkerTask>, res_tx: Sender<WorkerResponse>) {
    thread::spawn(move || {
        while let Ok(task) = task_rx.recv() {
            let WorkerTask::LoadPreview {
                mut path,
                mut max_lines,
                mut pane_width,
                mut preview_method,
                mut args,
                mut request_id,
            } = task
            else {
                continue;
            };

            // Coalesce multiple LoadPreview tasks to only process the latest
            while let Ok(next) = task_rx.try_recv() {
                if let WorkerTask::LoadPreview {
                    path: p,
                    max_lines: m,
                    pane_width: w,
                    preview_method: pm,
                    args: a,
                    request_id: id,
                } = next
                {
                    path = p;
                    max_lines = m;
                    pane_width = w;
                    preview_method = pm;
                    args = a;
                    request_id = id;
                }
            }

            let lines = match preview_method {
                // Use internal preview method
                PreviewMethod::Internal => safe_read_preview(&path, max_lines, pane_width),
                PreviewMethod::Bat => match preview_bat(&path, max_lines, args.as_slice()) {
                    // Bat preview succeeded
                    // If bat fails, fallback to internal preview
                    // If bat is not installed or returns error, we fallback to internal preview
                    Ok(lines) => lines,
                    Err(_) => safe_read_preview(&path, max_lines, pane_width),
                },
            };
            let _ = res_tx.send(WorkerResponse::PreviewLoaded { lines, request_id });
        }
    });
}

/// Starts the find worker thread
///
/// # Arguments
/// * `task_rx` - Receiver channel for incoming tasks
/// * `res_tx` - Sender channel for outgoing responses
fn start_find_worker(task_rx: Receiver<WorkerTask>, res_tx: Sender<WorkerResponse>) {
    thread::spawn(move || {
        while let Ok(task) = task_rx.recv() {
            let WorkerTask::FindRecursive {
                mut base_dir,
                mut query,
                mut max_results,
                mut request_id,
                mut cancel,
            } = task
            else {
                continue;
            };

            while let Ok(next) = task_rx.try_recv() {
                if let WorkerTask::FindRecursive {
                    base_dir: base,
                    query: q,
                    max_results: max,
                    request_id: id,
                    cancel: c,
                } = next
                {
                    base_dir = base;
                    query = q;
                    max_results = max;
                    request_id = id;
                    cancel = c;
                }
            }

            let mut results = Vec::new();
            let _ = find(
                &base_dir,
                &query,
                &mut results,
                Arc::clone(&cancel),
                max_results,
            );
            if results.len() > max_results {
                results.truncate(max_results);
            }

            if cancel.load(Ordering::Acquire) {
                continue;
            }

            let _ = res_tx.send(WorkerResponse::FindResults {
                base_dir,
                results,
                request_id,
            });
        }
    });
}

/// Starts the file operation worker thread
///
/// # Arguments
/// * `task_rx` - Receiver channel for incoming tasks
/// * `res_tx` - Sender channel for outgoing responses
fn start_fileop_worker(task_rx: Receiver<WorkerTask>, res_tx: Sender<WorkerResponse>) {
    thread::spawn(move || {
        while let Ok(task) = task_rx.recv() {
            let WorkerTask::FileOp { op, request_id } = task else {
                continue;
            };
            let mut focus_target: Option<OsString> = None;
            let result: Result<String, String> = match op {
                FileOperation::Delete(paths) => {
                    for p in paths {
                        let res = if p.is_dir() {
                            std::fs::remove_dir_all(&p)
                        } else {
                            std::fs::remove_file(&p)
                        };
                        if let Err(e) = res {
                            eprintln!("Failed to delete {}: {}", p.display(), e);
                        }
                    }
                    Ok("Items deleted".to_string())
                }
                FileOperation::Rename { old, new } => {
                    let target = new;

                    if target.exists() {
                        Err(format!(
                            "Rename failed: '{}' already exists",
                            target.file_name().unwrap_or_default().to_string_lossy()
                        ))
                    } else {
                        focus_target = target.file_name().map(|n| n.to_os_string());
                        std::fs::rename(old, &target)
                            .map(|_| "Renamed".into())
                            .map_err(|e| e.to_string())
                    }
                }
                FileOperation::Create { path, is_dir } => {
                    let target = get_unused_path(&path);
                    focus_target = target.file_name().map(|n| n.to_os_string());

                    let res = if is_dir {
                        std::fs::create_dir_all(&target)
                    } else {
                        std::fs::OpenOptions::new()
                            .write(true)
                            .create_new(true)
                            .open(&target)
                            .map(|_| ())
                    };
                    res.map(|_| "Created".into()).map_err(|e| e.to_string())
                }
                FileOperation::Copy {
                    src,
                    dest,
                    cut,
                    focus,
                } => {
                    focus_target = focus;
                    for s in src {
                        if let Some(name) = s.file_name() {
                            let target = get_unused_path(&dest.join(name));

                            if let Some(ref ft) = focus_target
                                && ft == name
                            {
                                focus_target = target.file_name().map(|n| n.to_os_string());
                            }

                            let _ = if cut {
                                std::fs::rename(s, &target)
                            } else if s.is_dir() {
                                copy_recursive(&s, &target)
                            } else {
                                std::fs::copy(s, &target).map(|_| ())
                            };
                        }
                    }
                    Ok("Pasted".into())
                }
            };

            match result {
                Ok(msg) => {
                    let _ = res_tx.send(WorkerResponse::OperationComplete {
                        message: msg,
                        request_id,
                        need_reload: true,
                        focus: focus_target,
                    });
                }
                Err(e) => {
                    let _ = res_tx.send(WorkerResponse::Error(format!("Op Error: {}", e)));
                }
            }
        }
    });
}