tui-file-explorer 0.1.5

A self-contained, keyboard-driven file-browser widget 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
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
//! Application state for the `tfe` binary.
//!
//! This module owns all runtime state that is not part of the file-explorer
//! widget itself:
//!
//! * [`Pane`]          — which of the two panes is active.
//! * [`ClipOp`]        — whether a yanked entry is being copied or cut.
//! * [`ClipboardItem`] — what is currently in the clipboard.
//! * [`Modal`]         — an optional blocking confirmation dialog.
//! * [`App`]           — the top-level state struct that drives the event loop.

use std::{
    fs,
    io::{self},
    path::{Path, PathBuf},
};

use crate::fs::copy_dir_all;

use crossterm::event::{self, Event, KeyCode, KeyModifiers};
use tui_file_explorer::{ExplorerOutcome, FileExplorer, SortMode, Theme};

// ── Pane ─────────────────────────────────────────────────────────────────────

/// Which of the two explorer panes is currently focused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    Left,
    Right,
}

impl Pane {
    /// Return the opposite pane.
    pub fn other(self) -> Self {
        match self {
            Pane::Left => Pane::Right,
            Pane::Right => Pane::Left,
        }
    }
}

// ── ClipOp ───────────────────────────────────────────────────────────────────

/// Whether the clipboard item should be copied or moved on paste.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClipOp {
    Copy,
    Cut,
}

// ── ClipboardItem ─────────────────────────────────────────────────────────────

/// An entry that has been yanked (copied or cut) and is waiting to be pasted.
#[derive(Debug, Clone)]
pub struct ClipboardItem {
    /// Absolute path of the source file or directory.
    pub path: PathBuf,
    /// Whether this is a copy or a cut operation.
    pub op: ClipOp,
}

impl ClipboardItem {
    /// A small emoji that visually distinguishes copy from cut in the action bar.
    pub fn icon(&self) -> &'static str {
        match self.op {
            ClipOp::Copy => "\u{1F4CB}", // 📋
            ClipOp::Cut => "\u{2702} ",  //        }
    }

    /// A short human-readable label for the current operation.
    pub fn label(&self) -> &'static str {
        match self.op {
            ClipOp::Copy => "Copy",
            ClipOp::Cut => "Cut ",
        }
    }
}

// ── Modal ─────────────────────────────────────────────────────────────────────

/// A blocking confirmation dialog that intercepts all keyboard input until
/// the user either confirms or cancels.
#[derive(Debug)]
pub enum Modal {
    /// Asks the user to confirm deletion of a file or directory.
    DeleteConfirm {
        /// Absolute path of the entry to delete.
        path: PathBuf,
    },
    /// Asks the user whether to overwrite an existing destination during paste.
    OverwriteConfirm {
        /// Absolute path of the source being pasted.
        src: PathBuf,
        /// Absolute path of the destination that already exists.
        dst: PathBuf,
        /// `true` if the original operation was a cut (move).
        is_cut: bool,
    },
}

// ── App ───────────────────────────────────────────────────────────────────────

/// Top-level application state for the `tfe` binary.
///
/// Owns both [`FileExplorer`] panes, the clipboard, the active modal, theme
/// state, and the final selected path (set when the user confirms a file).
pub struct App {
    /// The left-hand explorer pane.
    pub left: FileExplorer,
    /// The right-hand explorer pane.
    pub right: FileExplorer,
    /// Which pane currently has keyboard focus.
    pub active: Pane,
    /// The most recently yanked entry, if any.
    pub clipboard: Option<ClipboardItem>,
    /// All available themes as `(name, description, Theme)` triples.
    pub themes: Vec<(&'static str, &'static str, Theme)>,
    /// Index into `themes` for the currently active theme.
    pub theme_idx: usize,
    /// Whether the theme-picker side-panel is visible.
    pub show_theme_panel: bool,
    /// Whether only the active pane is shown (single-pane mode).
    pub single_pane: bool,
    /// The currently displayed confirmation modal, if any.
    pub modal: Option<Modal>,
    /// The path chosen by the user (set on `Enter` / `→` confirm).
    pub selected: Option<PathBuf>,
    /// One-line status text shown in the action bar.
    pub status_msg: String,
}

impl App {
    /// Construct a new `App` with two panes both starting at `start_dir`.
    pub fn new(
        start_dir: PathBuf,
        extensions: Vec<String>,
        show_hidden: bool,
        theme_idx: usize,
        show_theme_panel: bool,
        single_pane: bool,
        sort_mode: SortMode,
    ) -> Self {
        let left = FileExplorer::builder(start_dir.clone())
            .extension_filter(extensions.clone())
            .show_hidden(show_hidden)
            .sort_mode(sort_mode)
            .build();
        let right = FileExplorer::builder(start_dir)
            .extension_filter(extensions)
            .show_hidden(show_hidden)
            .sort_mode(sort_mode)
            .build();
        Self {
            left,
            right,
            active: Pane::Left,
            clipboard: None,
            themes: Theme::all_presets(),
            theme_idx,
            show_theme_panel,
            single_pane,
            modal: None,
            selected: None,
            status_msg: String::new(),
        }
    }

    // ── Pane accessors ────────────────────────────────────────────────────────

    /// Return a shared reference to the currently active pane.
    pub fn active_pane(&self) -> &FileExplorer {
        match self.active {
            Pane::Left => &self.left,
            Pane::Right => &self.right,
        }
    }

    /// Return a mutable reference to the currently active pane.
    pub fn active_pane_mut(&mut self) -> &mut FileExplorer {
        match self.active {
            Pane::Left => &mut self.left,
            Pane::Right => &mut self.right,
        }
    }

    // ── Theme helpers ─────────────────────────────────────────────────────────

    /// Return a reference to the currently selected [`Theme`].
    pub fn theme(&self) -> &Theme {
        &self.themes[self.theme_idx].2
    }

    /// Return the name of the currently selected theme.
    pub fn theme_name(&self) -> &str {
        self.themes[self.theme_idx].0
    }

    /// Return the description of the currently selected theme.
    pub fn theme_desc(&self) -> &str {
        self.themes[self.theme_idx].1
    }

    /// Advance to the next theme, wrapping around at the end of the list.
    pub fn next_theme(&mut self) {
        self.theme_idx = (self.theme_idx + 1) % self.themes.len();
    }

    /// Retreat to the previous theme, wrapping around at the beginning.
    pub fn prev_theme(&mut self) {
        self.theme_idx = self
            .theme_idx
            .checked_sub(1)
            .unwrap_or(self.themes.len() - 1);
    }

    // ── File operations ───────────────────────────────────────────────────────

    /// Yank (copy or cut) the currently highlighted entry into the clipboard.
    pub fn yank(&mut self, op: ClipOp) {
        if let Some(entry) = self.active_pane().current_entry() {
            let label = entry.name.clone();
            self.clipboard = Some(ClipboardItem {
                path: entry.path.clone(),
                op,
            });
            let (verb, hint) = if op == ClipOp::Copy {
                ("Copied", "paste a copy")
            } else {
                ("Cut", "move it")
            };
            self.status_msg = format!("{verb} '{label}' — press p in other pane to {hint}");
        }
    }

    /// Paste the clipboard item into the active pane's current directory.
    ///
    /// If the destination already exists, a [`Modal::OverwriteConfirm`] is
    /// raised instead of overwriting silently.
    pub fn paste(&mut self) {
        let Some(clip) = self.clipboard.clone() else {
            self.status_msg = "Nothing in clipboard.".into();
            return;
        };

        let dst_dir = self.active_pane().current_dir.clone();
        let file_name = match clip.path.file_name() {
            Some(n) => n.to_owned(),
            None => {
                self.status_msg = "Cannot paste: clipboard path has no filename.".into();
                return;
            }
        };
        let dst = dst_dir.join(&file_name);

        // Don't paste into the same location for Cut.
        if clip.op == ClipOp::Cut && clip.path.parent() == Some(&dst_dir) {
            self.status_msg = "Source and destination are the same — skipped.".into();
            return;
        }

        if dst.exists() {
            self.modal = Some(Modal::OverwriteConfirm {
                src: clip.path,
                dst,
                is_cut: clip.op == ClipOp::Cut,
            });
        } else {
            self.do_paste(&clip.path, &dst, clip.op == ClipOp::Cut);
        }
    }

    /// Perform the actual copy/move on disk and refresh both panes.
    ///
    /// For a cut operation the source is removed after a successful copy and
    /// the clipboard is cleared.
    pub fn do_paste(&mut self, src: &Path, dst: &Path, is_cut: bool) {
        let result = if src.is_dir() {
            copy_dir_all(src, dst)
        } else {
            fs::copy(src, dst).map(|_| ())
        };

        match result {
            Ok(()) => {
                if is_cut {
                    let _ = if src.is_dir() {
                        fs::remove_dir_all(src)
                    } else {
                        fs::remove_file(src)
                    };
                    self.clipboard = None;
                }
                self.left.reload();
                self.right.reload();
                self.status_msg = format!(
                    "{} '{}'",
                    if is_cut { "Moved" } else { "Pasted" },
                    dst.file_name().unwrap_or_default().to_string_lossy()
                );
            }
            Err(e) => {
                self.status_msg = format!("Error: {e}");
            }
        }
    }

    /// Raise a [`Modal::DeleteConfirm`] for the currently highlighted entry.
    pub fn prompt_delete(&mut self) {
        if let Some(entry) = self.active_pane().current_entry() {
            self.modal = Some(Modal::DeleteConfirm {
                path: entry.path.clone(),
            });
        }
    }

    /// Execute a confirmed deletion and reload both panes.
    pub fn confirm_delete(&mut self, path: &Path) {
        let name = path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();
        let result = if path.is_dir() {
            fs::remove_dir_all(path)
        } else {
            fs::remove_file(path)
        };
        match result {
            Ok(()) => {
                self.left.reload();
                self.right.reload();
                self.status_msg = format!("Deleted '{name}'");
            }
            Err(e) => {
                self.status_msg = format!("Delete failed: {e}");
            }
        }
    }

    // ── Event handling ────────────────────────────────────────────────────────

    /// Read one terminal event and update application state.
    ///
    /// Returns `true` when the event loop should exit (user confirmed a
    /// selection or dismissed the explorer).
    pub fn handle_event(&mut self) -> io::Result<bool> {
        let Event::Key(key) = event::read()? else {
            return Ok(false);
        };

        // Always handle Ctrl-C.
        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return Ok(true);
        }

        // ── Modal intercepts all input ────────────────────────────────────────
        if let Some(modal) = self.modal.take() {
            match &modal {
                Modal::DeleteConfirm { path } => match key.code {
                    KeyCode::Char('y') | KeyCode::Char('Y') => {
                        let p = path.clone();
                        self.confirm_delete(&p);
                    }
                    _ => self.status_msg = "Delete cancelled.".into(),
                },
                Modal::OverwriteConfirm { src, dst, is_cut } => match key.code {
                    KeyCode::Char('y') | KeyCode::Char('Y') => {
                        let (s, d, cut) = (src.clone(), dst.clone(), *is_cut);
                        self.do_paste(&s, &d, cut);
                    }
                    _ => self.status_msg = "Paste cancelled.".into(),
                },
            }
            return Ok(false);
        }

        // ── Global keys (always active) ───────────────────────────────────────
        match key.code {
            // Cycle theme forward
            KeyCode::Char('t') if key.modifiers.is_empty() => {
                self.next_theme();
                return Ok(false);
            }
            // Cycle theme backward
            KeyCode::Char('[') => {
                self.prev_theme();
                return Ok(false);
            }
            // Toggle theme panel
            KeyCode::Char('T') => {
                self.show_theme_panel = !self.show_theme_panel;
                return Ok(false);
            }
            // Switch pane
            KeyCode::Tab => {
                self.active = self.active.other();
                return Ok(false);
            }
            // Toggle single/two-pane
            KeyCode::Char('w') if key.modifiers.is_empty() => {
                self.single_pane = !self.single_pane;
                return Ok(false);
            }
            // Copy
            KeyCode::Char('y') if key.modifiers.is_empty() => {
                self.yank(ClipOp::Copy);
                return Ok(false);
            }
            // Cut
            KeyCode::Char('x') if key.modifiers.is_empty() => {
                self.yank(ClipOp::Cut);
                return Ok(false);
            }
            // Paste
            KeyCode::Char('p') if key.modifiers.is_empty() => {
                self.paste();
                return Ok(false);
            }
            // Delete
            KeyCode::Char('d') if key.modifiers.is_empty() => {
                self.prompt_delete();
                return Ok(false);
            }
            _ => {}
        }

        // ── Delegate to active pane explorer ─────────────────────────────────
        // Clear any previous non-error status when navigating.
        let outcome = self.active_pane_mut().handle_key(key);
        match outcome {
            ExplorerOutcome::Selected(path) => {
                self.selected = Some(path);
                return Ok(true);
            }
            ExplorerOutcome::Dismissed => return Ok(true),
            ExplorerOutcome::Pending => {
                if self.status_msg.starts_with("Error") || self.status_msg.starts_with("Delete") {
                    // keep error messages visible
                } else {
                    self.status_msg.clear();
                }
            }
            ExplorerOutcome::Unhandled => {}
        }

        Ok(false)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── Helpers ───────────────────────────────────────────────────────────────

    /// Build a minimal `App` rooted at `dir` with sensible defaults.
    fn make_app(dir: PathBuf) -> App {
        App::new(dir, vec![], false, 0, false, false, SortMode::default())
    }

    // ── Pane ─────────────────────────────────────────────────────────────────

    #[test]
    fn pane_other_left_returns_right() {
        assert_eq!(Pane::Left.other(), Pane::Right);
    }

    #[test]
    fn pane_other_right_returns_left() {
        assert_eq!(Pane::Right.other(), Pane::Left);
    }

    // ── ClipboardItem ─────────────────────────────────────────────────────────

    #[test]
    fn clipboard_item_copy_icon_and_label() {
        let item = ClipboardItem {
            path: PathBuf::from("/tmp/foo"),
            op: ClipOp::Copy,
        };
        assert_eq!(item.icon(), "\u{1F4CB}");
        assert_eq!(item.label(), "Copy");
    }

    #[test]
    fn clipboard_item_cut_icon_and_label() {
        let item = ClipboardItem {
            path: PathBuf::from("/tmp/foo"),
            op: ClipOp::Cut,
        };
        assert_eq!(item.icon(), "\u{2702} ");
        assert_eq!(item.label(), "Cut ");
    }

    // ── App::new ──────────────────────────────────────────────────────────────

    #[test]
    fn new_sets_default_active_pane_to_left() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert_eq!(app.active, Pane::Left);
    }

    #[test]
    fn new_clipboard_is_empty() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(app.clipboard.is_none());
    }

    #[test]
    fn new_modal_is_none() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(app.modal.is_none());
    }

    #[test]
    fn new_selected_is_none() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(app.selected.is_none());
    }

    #[test]
    fn new_status_msg_is_empty() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(app.status_msg.is_empty());
    }

    // ── Theme helpers ─────────────────────────────────────────────────────────

    #[test]
    fn theme_name_returns_str_for_idx_zero() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        // Index 0 is always the "default" preset.
        assert!(!app.theme_name().is_empty());
    }

    #[test]
    fn theme_name_matches_preset_catalogue() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        let expected = app.themes[app.theme_idx].0;
        assert_eq!(app.theme_name(), expected);
    }

    #[test]
    fn theme_desc_returns_non_empty_string() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(!app.theme_desc().is_empty());
    }

    #[test]
    fn theme_desc_matches_preset_catalogue() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        let expected = app.themes[app.theme_idx].1;
        assert_eq!(app.theme_desc(), expected);
    }

    #[test]
    fn theme_returns_correct_preset_object() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        // Advance to a known non-default index so we're not just testing the default.
        app.theme_idx = 2;
        let expected = &app.themes[2].2;
        assert_eq!(app.theme(), expected);
    }

    #[test]
    fn theme_name_and_desc_change_together_with_idx() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.theme_idx = 1;
        assert_eq!(app.theme_name(), app.themes[1].0);
        assert_eq!(app.theme_desc(), app.themes[1].1);
    }

    #[test]
    fn next_theme_increments_idx() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        let initial = app.theme_idx;
        app.next_theme();
        assert_eq!(app.theme_idx, initial + 1);
    }

    #[test]
    fn next_theme_wraps_around() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        let total = app.themes.len();
        app.theme_idx = total - 1;
        app.next_theme();
        assert_eq!(app.theme_idx, 0);
    }

    #[test]
    fn prev_theme_decrements_idx() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.theme_idx = 3;
        app.prev_theme();
        assert_eq!(app.theme_idx, 2);
    }

    #[test]
    fn prev_theme_wraps_around() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.theme_idx = 0;
        app.prev_theme();
        assert_eq!(app.theme_idx, app.themes.len() - 1);
    }

    // ── single_pane / show_theme_panel toggles ────────────────────────────────

    #[test]
    fn new_single_pane_false_by_default() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(!app.single_pane);
    }

    #[test]
    fn new_show_theme_panel_false_by_default() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        assert!(!app.show_theme_panel);
    }

    #[test]
    fn new_single_pane_true_when_requested() {
        let dir = tempdir().expect("tempdir");
        let app = App::new(
            dir.path().to_path_buf(),
            vec![],
            false,
            0,
            false,
            true, // single_pane = true
            SortMode::default(),
        );
        assert!(app.single_pane);
    }

    #[test]
    fn new_show_theme_panel_true_when_requested() {
        let dir = tempdir().expect("tempdir");
        let app = App::new(
            dir.path().to_path_buf(),
            vec![],
            false,
            0,
            true, // show_theme_panel = true
            false,
            SortMode::default(),
        );
        assert!(app.show_theme_panel);
    }

    // ── Pane switching ────────────────────────────────────────────────────────

    #[test]
    fn active_pane_returns_left_by_default() {
        let dir = tempdir().expect("tempdir");
        let app = make_app(dir.path().to_path_buf());
        // Both panes start at the same dir; active_pane should refer to left.
        assert_eq!(app.active_pane().current_dir, app.left.current_dir);
    }

    #[test]
    fn active_pane_returns_right_when_switched() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.active = Pane::Right;
        assert_eq!(app.active_pane().current_dir, app.right.current_dir);
    }

    // ── yank ─────────────────────────────────────────────────────────────────

    #[test]
    fn yank_copy_populates_clipboard_with_copy_op() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("file.txt"), b"hi").expect("write");
        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Copy);
        let clip = app.clipboard.expect("clipboard should be set");
        assert_eq!(clip.op, ClipOp::Copy);
    }

    #[test]
    fn yank_cut_populates_clipboard_with_cut_op() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("file.txt"), b"hi").expect("write");
        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Cut);
        let clip = app.clipboard.expect("clipboard should be set");
        assert_eq!(clip.op, ClipOp::Cut);
    }

    #[test]
    fn yank_sets_status_message() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("file.txt"), b"hi").expect("write");
        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Copy);
        assert!(!app.status_msg.is_empty());
    }

    #[test]
    fn yank_copy_status_mentions_copied_and_filename() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("report.txt"), b"data").expect("write");
        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Copy);
        assert!(
            app.status_msg.contains("Copied"),
            "status should mention 'Copied', got: {}",
            app.status_msg
        );
        assert!(
            app.status_msg.contains("report.txt"),
            "status should mention the filename, got: {}",
            app.status_msg
        );
    }

    #[test]
    fn yank_cut_status_mentions_cut_and_filename() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("move_me.txt"), b"data").expect("write");
        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Cut);
        assert!(
            app.status_msg.contains("Cut"),
            "status should mention 'Cut', got: {}",
            app.status_msg
        );
        assert!(
            app.status_msg.contains("move_me.txt"),
            "status should mention the filename, got: {}",
            app.status_msg
        );
    }

    #[test]
    fn yank_on_empty_dir_does_not_set_clipboard() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Copy);
        assert!(app.clipboard.is_none());
    }

    // ── paste ─────────────────────────────────────────────────────────────────

    #[test]
    fn paste_with_empty_clipboard_sets_status() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.paste();
        assert_eq!(app.status_msg, "Nothing in clipboard.");
    }

    #[test]
    fn paste_copy_creates_file_in_destination() {
        let src_dir = tempdir().expect("src tempdir");
        let dst_dir = tempdir().expect("dst tempdir");
        fs::write(src_dir.path().join("hello.txt"), b"world").expect("write");

        let mut app = App::new(
            src_dir.path().to_path_buf(),
            vec![],
            false,
            0,
            false,
            false,
            SortMode::default(),
        );
        app.yank(ClipOp::Copy);

        // Switch active pane to right and point it at dst_dir.
        app.active = Pane::Right;
        app.right.navigate_to(dst_dir.path().to_path_buf());

        app.paste();

        assert!(dst_dir.path().join("hello.txt").exists());
        // Source file must still exist after a copy.
        assert!(src_dir.path().join("hello.txt").exists());
    }

    #[test]
    fn paste_cut_moves_file_and_clears_clipboard() {
        let src_dir = tempdir().expect("src tempdir");
        let dst_dir = tempdir().expect("dst tempdir");
        fs::write(src_dir.path().join("move_me.txt"), b"data").expect("write");

        let mut app = App::new(
            src_dir.path().to_path_buf(),
            vec![],
            false,
            0,
            false,
            false,
            SortMode::default(),
        );
        app.yank(ClipOp::Cut);

        app.active = Pane::Right;
        app.right.navigate_to(dst_dir.path().to_path_buf());

        app.paste();

        assert!(dst_dir.path().join("move_me.txt").exists());
        assert!(!src_dir.path().join("move_me.txt").exists());
        assert!(
            app.clipboard.is_none(),
            "clipboard should be cleared after cut-paste"
        );
    }

    #[test]
    fn paste_same_dir_cut_is_skipped() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("same.txt"), b"x").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        app.yank(ClipOp::Cut);
        // Active pane is still the same dir.
        app.paste();

        assert_eq!(
            app.status_msg,
            "Source and destination are the same — skipped."
        );
    }

    #[test]
    fn paste_existing_dst_raises_overwrite_modal() {
        let src_dir = tempdir().expect("src tempdir");
        let dst_dir = tempdir().expect("dst tempdir");
        fs::write(src_dir.path().join("clash.txt"), b"src").expect("write src");
        fs::write(dst_dir.path().join("clash.txt"), b"dst").expect("write dst");

        let mut app = App::new(
            src_dir.path().to_path_buf(),
            vec![],
            false,
            0,
            false,
            false,
            SortMode::default(),
        );
        app.yank(ClipOp::Copy);
        app.active = Pane::Right;
        app.right.navigate_to(dst_dir.path().to_path_buf());
        app.paste();

        assert!(
            matches!(app.modal, Some(Modal::OverwriteConfirm { .. })),
            "expected OverwriteConfirm modal"
        );
    }

    // ── do_paste ──────────────────────────────────────────────────────────────

    #[test]
    fn do_paste_copy_file_succeeds() {
        let dir = tempdir().expect("tempdir");
        let src = dir.path().join("orig.txt");
        let dst = dir.path().join("copy.txt");
        fs::write(&src, b"content").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        app.do_paste(&src, &dst, false);

        assert!(dst.exists());
        assert!(src.exists());
        assert!(app.status_msg.contains("Pasted"));
    }

    #[test]
    fn do_paste_cut_file_removes_source() {
        let dir = tempdir().expect("tempdir");
        let src = dir.path().join("src.txt");
        let dst = dir.path().join("dst.txt");
        fs::write(&src, b"content").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        // Put something in clipboard so it can be cleared.
        app.clipboard = Some(ClipboardItem {
            path: src.clone(),
            op: ClipOp::Cut,
        });
        app.do_paste(&src, &dst, true);

        assert!(dst.exists());
        assert!(!src.exists());
        assert!(app.clipboard.is_none());
        assert!(app.status_msg.contains("Moved"));
    }

    #[test]
    fn do_paste_copy_dir_recursively() {
        let dir = tempdir().expect("tempdir");
        let src = dir.path().join("src_dir");
        fs::create_dir(&src).expect("mkdir src");
        fs::write(src.join("nested.txt"), b"hello").expect("write nested");

        let dst = dir.path().join("dst_dir");
        let mut app = make_app(dir.path().to_path_buf());
        app.do_paste(&src, &dst, false);

        assert!(dst.join("nested.txt").exists());
        assert!(src.exists(), "source dir should survive a copy");
    }

    #[test]
    fn do_paste_error_sets_error_status() {
        let dir = tempdir().expect("tempdir");
        // src does not exist — copy will fail.
        let src = dir.path().join("ghost.txt");
        let dst = dir.path().join("out.txt");

        let mut app = make_app(dir.path().to_path_buf());
        app.do_paste(&src, &dst, false);

        assert!(app.status_msg.starts_with("Error"));
    }

    // ── prompt_delete / confirm_delete ────────────────────────────────────────

    #[test]
    fn prompt_delete_raises_modal_when_entry_exists() {
        let dir = tempdir().expect("tempdir");
        fs::write(dir.path().join("del.txt"), b"bye").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        app.prompt_delete();

        assert!(
            matches!(app.modal, Some(Modal::DeleteConfirm { .. })),
            "expected DeleteConfirm modal"
        );
    }

    #[test]
    fn prompt_delete_on_empty_dir_does_not_set_modal() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        app.prompt_delete();
        assert!(app.modal.is_none());
    }

    #[test]
    fn confirm_delete_removes_file_and_updates_status() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("gone.txt");
        fs::write(&path, b"delete me").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        app.confirm_delete(&path);

        assert!(!path.exists());
        assert!(app.status_msg.contains("Deleted"));
    }

    #[test]
    fn confirm_delete_removes_directory_recursively() {
        let dir = tempdir().expect("tempdir");
        let sub = dir.path().join("subdir");
        fs::create_dir(&sub).expect("mkdir");
        fs::write(sub.join("inner.txt"), b"x").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        app.confirm_delete(&sub);

        assert!(!sub.exists());
    }

    #[test]
    fn confirm_delete_nonexistent_path_sets_error_status() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("not_here.txt");

        let mut app = make_app(dir.path().to_path_buf());
        app.confirm_delete(&path);

        assert!(app.status_msg.starts_with("Delete failed"));
    }

    // ── status_msg clearing behaviour ────────────────────────────────────────

    #[test]
    fn status_msg_is_cleared_by_do_paste_on_success() {
        let src_dir = tempdir().expect("src tempdir");
        let dst_dir = tempdir().expect("dst tempdir");
        fs::write(src_dir.path().join("a.txt"), b"x").expect("write");

        let mut app = App::new(
            src_dir.path().to_path_buf(),
            vec![],
            false,
            0,
            false,
            false,
            SortMode::default(),
        );
        // Seed an old status message to prove it gets replaced.
        app.status_msg = "old message".into();

        let src = src_dir.path().join("a.txt");
        let dst = dst_dir.path().join("a.txt");
        app.do_paste(&src, &dst, false);

        assert_ne!(app.status_msg, "old message");
        assert!(app.status_msg.contains("Pasted"));
    }

    #[test]
    fn status_msg_starts_with_error_on_failed_paste() {
        let dir = tempdir().expect("tempdir");
        let src = dir.path().join("ghost.txt"); // does not exist
        let dst = dir.path().join("out.txt");

        let mut app = make_app(dir.path().to_path_buf());
        app.do_paste(&src, &dst, false);

        assert!(
            app.status_msg.starts_with("Error"),
            "expected error prefix, got: {}",
            app.status_msg
        );
    }

    // ── paste edge cases ──────────────────────────────────────────────────────

    #[test]
    fn paste_clipboard_path_with_no_filename_sets_status() {
        let dir = tempdir().expect("tempdir");
        let mut app = make_app(dir.path().to_path_buf());
        // A path with no filename component (e.g. "/" on Unix).
        app.clipboard = Some(ClipboardItem {
            path: PathBuf::from("/"),
            op: ClipOp::Copy,
        });
        app.paste();
        assert_eq!(
            app.status_msg,
            "Cannot paste: clipboard path has no filename."
        );
    }

    // ── both panes reload after operations ────────────────────────────────────

    #[test]
    fn confirm_delete_reloads_both_panes() {
        let dir = tempdir().expect("tempdir");
        let file = dir.path().join("vanish.txt");
        fs::write(&file, b"bye").expect("write");

        let mut app = make_app(dir.path().to_path_buf());
        // Both panes start in the same directory. After delete the file must
        // not appear in either entry list.
        app.confirm_delete(&file);

        let in_left = app.left.entries.iter().any(|e| e.name == "vanish.txt");
        let in_right = app.right.entries.iter().any(|e| e.name == "vanish.txt");
        assert!(!in_left, "file still appears in left pane after delete");
        assert!(!in_right, "file still appears in right pane after delete");
    }

    #[test]
    fn do_paste_reloads_both_panes() {
        let src_dir = tempdir().expect("src tempdir");
        let dst_dir = tempdir().expect("dst tempdir");
        fs::write(src_dir.path().join("appear.txt"), b"hi").expect("write");

        let mut app = App::new(
            dst_dir.path().to_path_buf(),
            vec![],
            false,
            0,
            false,
            false,
            SortMode::default(),
        );
        let src = src_dir.path().join("appear.txt");
        let dst = dst_dir.path().join("appear.txt");
        app.do_paste(&src, &dst, false);

        let in_left = app.left.entries.iter().any(|e| e.name == "appear.txt");
        let in_right = app.right.entries.iter().any(|e| e.name == "appear.txt");
        assert!(in_left, "pasted file should appear in left pane");
        assert!(in_right, "pasted file should appear in right pane");
    }
}