tui-file-explorer 4.0.1

Embeddable keyboard-driven multi-pane file explorer for Ratatui
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use std::{
    io,
    path::{Path, PathBuf},
};

use super::App;
use crate::FileSystem;

/// Identifies one file operation, so late progress and results can be matched to it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OperationId(pub u64);

/// Who runs file operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OperationMode {
    /// The app runs them itself, on the UI thread.
    #[default]
    Immediate,
    /// The app hands them to the host as [`OperationRequest`]s.
    Deferred,
}

/// A copy, move or delete over one or more paths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileOperation {
    /// Copy `sources` into the `destination` directory.
    Copy {
        /// Files and directories to copy.
        sources: Vec<PathBuf>,
        /// Directory to copy into.
        destination: PathBuf,
        /// Replace existing files of the same name.
        overwrite: bool,
    },
    /// Move `sources` into the `destination` directory.
    Move {
        /// Files and directories to move.
        sources: Vec<PathBuf>,
        /// Directory to move into.
        destination: PathBuf,
        /// Replace existing files of the same name.
        overwrite: bool,
    },
    /// Delete `paths`, directories included.
    Delete {
        /// Files and directories to delete.
        paths: Vec<PathBuf>,
    },
}

/// A file operation the host should run (see [`OperationMode::Deferred`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationRequest {
    /// Pass this back with progress and the result.
    pub id: OperationId,
    /// What to do.
    pub operation: FileOperation,
}

/// Progress of a running operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationProgress {
    /// The operation this update belongs to.
    pub id: OperationId,
    /// Items processed so far.
    pub completed: usize,
    /// Total number of items.
    pub total: usize,
    /// Item being processed now; `None` once all are done.
    pub current_path: Option<PathBuf>,
}

/// One item that an operation could not process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationFailure {
    /// The item that failed.
    pub path: PathBuf,
    /// Why it failed.
    pub error: String,
}

/// Outcome of a finished operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationResult {
    /// The operation that finished.
    pub id: OperationId,
    /// Paths that were processed: new paths for copy and move, removed paths for delete.
    pub succeeded: Vec<PathBuf>,
    /// Items that failed.
    pub failures: Vec<OperationFailure>,
}

/// Progress or a result arrived for an operation that is not the pending one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationApplyError {
    /// The pending operation, if any.
    pub expected: Option<OperationId>,
    /// The operation the update was for.
    pub received: OperationId,
}

impl std::fmt::Display for OperationApplyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "operation result {:?} does not match pending operation {:?}",
            self.received, self.expected
        )
    }
}

impl std::error::Error for OperationApplyError {}

fn copy_one(
    filesystem: &dyn FileSystem,
    source: &Path,
    destination: &Path,
    overwrite: bool,
) -> io::Result<PathBuf> {
    let name = source
        .file_name()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "source has no filename"))?;
    let target = destination.join(name);
    if filesystem.exists(&target) && !overwrite {
        return Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            format!("{} already exists", target.display()),
        ));
    }
    if filesystem.is_dir(source) {
        filesystem.copy_dir(source, &target)?;
    } else {
        filesystem.copy_file(source, &target)?;
    }
    Ok(target)
}

/// Execute an operation synchronously, reporting item-level progress.
///
/// Embedders can run this helper on a worker thread, send progress back to the
/// UI thread, then call [`App::apply_operation_result`].
pub fn execute_operation_with_progress(
    request: &OperationRequest,
    on_progress: impl FnMut(OperationProgress),
) -> OperationResult {
    execute_operation_with(crate::std_filesystem().as_ref(), request, on_progress)
}

/// Execute an operation against a custom filesystem backend.
pub fn execute_operation_with(
    filesystem: &dyn FileSystem,
    request: &OperationRequest,
    mut on_progress: impl FnMut(OperationProgress),
) -> OperationResult {
    let (paths, total) = match &request.operation {
        FileOperation::Copy { sources, .. } | FileOperation::Move { sources, .. } => {
            (sources.clone(), sources.len())
        }
        FileOperation::Delete { paths } => (paths.clone(), paths.len()),
    };

    let mut succeeded = Vec::new();
    let mut failures = Vec::new();
    for (index, path) in paths.iter().enumerate() {
        on_progress(OperationProgress {
            id: request.id,
            completed: index,
            total,
            current_path: Some(path.clone()),
        });

        let result = match &request.operation {
            FileOperation::Copy {
                destination,
                overwrite,
                ..
            } => copy_one(filesystem, path, destination, *overwrite),
            FileOperation::Move {
                destination,
                overwrite,
                ..
            } => copy_one(filesystem, path, destination, *overwrite).and_then(|target| {
                if filesystem.is_dir(path) {
                    filesystem.remove_dir_all(path)?;
                } else {
                    filesystem.remove_file(path)?;
                }
                Ok(target)
            }),
            FileOperation::Delete { .. } => {
                let changed = path.clone();
                if filesystem.is_dir(path) {
                    filesystem.remove_dir_all(path).map(|()| changed)
                } else {
                    filesystem.remove_file(path).map(|()| changed)
                }
            }
        };

        match result {
            Ok(path) => succeeded.push(path),
            Err(error) => failures.push(OperationFailure {
                path: path.clone(),
                error: error.to_string(),
            }),
        }
    }

    on_progress(OperationProgress {
        id: request.id,
        completed: total,
        total,
        current_path: None,
    });

    OperationResult {
        id: request.id,
        succeeded,
        failures,
    }
}

/// Execute an operation synchronously without progress callbacks.
#[must_use]
pub fn execute_operation(request: &OperationRequest) -> OperationResult {
    execute_operation_with_progress(request, |_| {})
}

impl App {
    /// Who runs file operations.
    #[must_use]
    pub fn operation_mode(&self) -> OperationMode {
        self.operation_mode
    }

    /// Filesystem backend associated with the active operation destination.
    #[must_use]
    pub fn operation_filesystem(&self) -> crate::SharedFileSystem {
        self.active_pane().filesystem().clone()
    }

    /// Set who runs file operations.
    pub fn set_operation_mode(&mut self, mode: OperationMode) {
        self.operation_mode = mode;
    }

    pub(crate) fn queue_operation(&mut self, operation: FileOperation) -> OperationRequest {
        if let Some(request) = self.pending_operation.clone() {
            self.notify_error("A filesystem operation is already in progress");
            return request;
        }
        let request = OperationRequest {
            id: OperationId(self.next_operation_id),
            operation,
        };
        self.next_operation_id = self.next_operation_id.wrapping_add(1);
        self.pending_operation = Some(request.clone());
        self.queued_operation = Some(request.clone());
        self.status_msg = "Filesystem operation queued.".into();
        request
    }

    /// Take a deferred request when using the legacy `handle_key` API.
    pub fn take_operation_request(&mut self) -> Option<OperationRequest> {
        self.queued_operation.take()
    }

    /// The operation that is waiting for its result, if any.
    #[must_use]
    pub fn pending_operation(&self) -> Option<&OperationRequest> {
        self.pending_operation.as_ref()
    }

    /// Cancel a queued/pending operation. Worker cancellation itself remains
    /// host-owned; late results are rejected by operation ID.
    pub fn cancel_operation(&mut self, id: OperationId) -> Result<(), OperationApplyError> {
        let expected = self.pending_operation.as_ref().map(|request| request.id);
        if expected != Some(id) {
            return Err(OperationApplyError {
                expected,
                received: id,
            });
        }
        self.pending_operation = None;
        self.queued_operation = None;
        self.copy_progress = None;
        self.status_msg = "Filesystem operation cancelled.".into();
        self.event_queue
            .push_back(super::AppEvent::OperationCancelled { id });
        Ok(())
    }

    /// Show progress reported by the host for the pending operation.
    ///
    /// # Errors
    ///
    /// [`OperationApplyError`] when `progress` is not for the pending operation.
    pub fn apply_operation_progress(
        &mut self,
        progress: OperationProgress,
    ) -> Result<(), OperationApplyError> {
        let expected = self.pending_operation.as_ref().map(|request| request.id);
        if expected != Some(progress.id) {
            return Err(OperationApplyError {
                expected,
                received: progress.id,
            });
        }
        self.copy_progress = Some(super::CopyProgress {
            label: format!("Processing {} item(s)…", progress.total),
            done: progress.completed,
            total: progress.total,
            current_item: progress
                .current_path
                .as_ref()
                .and_then(|path| path.file_name())
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned(),
        });
        self.event_queue
            .push_back(super::AppEvent::OperationProgress {
                id: progress.id,
                completed: progress.completed,
                total: progress.total,
            });
        Ok(())
    }

    /// Finish the pending operation: reload the panes and report the outcome.
    /// Returns the paths that succeeded.
    ///
    /// # Errors
    ///
    /// [`OperationApplyError`] when `result` is not for the pending operation.
    pub fn apply_operation_result(
        &mut self,
        result: OperationResult,
    ) -> Result<Vec<PathBuf>, OperationApplyError> {
        let expected = self.pending_operation.as_ref().map(|request| request.id);
        if expected != Some(result.id) {
            return Err(OperationApplyError {
                expected,
                received: result.id,
            });
        }
        let succeeded_count = result.succeeded.len();
        let failure_count = result.failures.len();
        let was_move = self
            .pending_operation
            .as_ref()
            .is_some_and(|request| matches!(request.operation, FileOperation::Move { .. }));
        self.pending_operation = None;
        self.queued_operation = None;
        self.copy_progress = None;

        if was_move && result.failures.is_empty() {
            self.clipboard = None;
        }
        for pane in &mut self.panes {
            pane.clear_marks();
            pane.reload();
            pane.clear_dir_size_cache();
        }
        self.preview_state.invalidate();

        if result.failures.is_empty() {
            let message = format!("Completed {} item(s).", result.succeeded.len());
            self.status_msg = message.clone();
            self.notify(message);
        } else {
            let details = result
                .failures
                .iter()
                .map(|failure| format!("'{}': {}", failure.path.display(), failure.error))
                .collect::<Vec<_>>()
                .join("; ");
            let message = format!(
                "Completed {}, {} error(s): {details}",
                result.succeeded.len(),
                result.failures.len()
            );
            self.status_msg = format!("Error: {message}");
            self.notify_error(message);
        }
        self.event_queue
            .push_back(super::AppEvent::OperationCompleted {
                id: result.id,
                succeeded: succeeded_count,
                failed: failure_count,
            });
        Ok(result.succeeded)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    use crate::{AppOptions, AppOutcome, ClipOp, ClipboardItem};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use tempfile::tempdir;

    #[test]
    fn deferred_paste_returns_request_without_touching_destination() {
        let source_dir = tempdir().unwrap();
        let destination = tempdir().unwrap();
        let source = source_dir.path().join("file.txt");
        fs::write(&source, b"payload").unwrap();
        let mut app = App::new(AppOptions {
            pane_dirs: vec![destination.path().to_path_buf()],
            ..AppOptions::default()
        });
        app.clipboard = Some(ClipboardItem {
            paths: vec![source.clone()],
            op: ClipOp::Copy,
        });
        app.set_operation_mode(OperationMode::Deferred);

        let outcome = app
            .dispatch_key(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE))
            .unwrap();
        let AppOutcome::OperationRequested(request) = outcome else {
            panic!("expected deferred operation");
        };
        assert!(matches!(request.operation, FileOperation::Copy { .. }));
        assert!(!destination.path().join("file.txt").exists());
    }

    #[test]
    fn execute_and_apply_deferred_copy() {
        let source_dir = tempdir().unwrap();
        let destination = tempdir().unwrap();
        let source = source_dir.path().join("file.txt");
        fs::write(&source, b"payload").unwrap();
        let mut app = App::new(AppOptions {
            pane_dirs: vec![destination.path().to_path_buf()],
            ..AppOptions::default()
        });
        app.set_operation_mode(OperationMode::Deferred);
        let request = app.queue_operation(FileOperation::Copy {
            sources: vec![source],
            destination: destination.path().to_path_buf(),
            overwrite: false,
        });
        let result = execute_operation(&request);
        let changed = app.apply_operation_result(result).unwrap();
        assert_eq!(changed, vec![destination.path().join("file.txt")]);
        assert!(destination.path().join("file.txt").exists());
        assert!(app.pending_operation().is_none());
    }

    #[test]
    fn stale_result_is_rejected() {
        let mut app = App::new(AppOptions::default());
        app.set_operation_mode(OperationMode::Deferred);
        app.queue_operation(FileOperation::Delete { paths: Vec::new() });
        let error = app
            .apply_operation_result(OperationResult {
                id: OperationId(999),
                succeeded: Vec::new(),
                failures: Vec::new(),
            })
            .unwrap_err();
        assert_eq!(error.received, OperationId(999));
    }
}