Skip to main content

oxinav_core/
pane.rs

1use std::collections::HashSet;
2use std::path::PathBuf;
3use std::time::SystemTime;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Entry {
7    pub name: String,
8    pub path: PathBuf,
9    pub is_dir: bool,
10    pub size: u64,
11    pub modified: Option<SystemTime>,
12}
13
14/// Key used to sort files within a pane. Directories are always sorted by
15/// name regardless of this setting, since size/modified-time comparisons
16/// aren't meaningful for a directory without a recursive scan.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum SortKey {
19    Name,
20    Size,
21    Modified,
22}
23
24impl SortKey {
25    pub fn label(self) -> &'static str {
26        match self {
27            SortKey::Name => "name",
28            SortKey::Size => "size",
29            SortKey::Modified => "modified",
30        }
31    }
32
33    /// The inverse of `label`, for reading a sort key back out of stored
34    /// text. Case-insensitive so a hand-edited config still works, and
35    /// `None` rather than a default for an unknown word, so the caller
36    /// decides what an unreadable value should fall back to.
37    pub fn from_label(label: &str) -> Option<Self> {
38        match label.trim() {
39            l if l.eq_ignore_ascii_case("name") => Some(SortKey::Name),
40            l if l.eq_ignore_ascii_case("size") => Some(SortKey::Size),
41            l if l.eq_ignore_ascii_case("modified") => Some(SortKey::Modified),
42            _ => None,
43        }
44    }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum PaneId {
49    Left,
50    Right,
51}
52
53impl PaneId {
54    pub fn other(self) -> Self {
55        match self {
56            PaneId::Left => PaneId::Right,
57            PaneId::Right => PaneId::Left,
58        }
59    }
60}
61
62/// Whether `name` satisfies the listing filter `pattern`.
63///
64/// A pattern holding `*` or `?` is matched as a glob against the whole name;
65/// one holding neither is matched as a substring, since a bare word like
66/// `cargo` is nearly always meant as "names containing this" rather than as
67/// an exact name. Both modes ignore case.
68pub fn matches_filter(name: &str, pattern: &str) -> bool {
69    let pattern = pattern.trim();
70    if pattern.is_empty() {
71        return true;
72    }
73
74    let name = name.to_lowercase();
75    let pattern = pattern.to_lowercase();
76
77    if pattern.contains(['*', '?']) {
78        glob_match(&name, &pattern)
79    } else {
80        name.contains(&pattern)
81    }
82}
83
84/// Two-pointer wildcard match: `*` spans any run of characters, `?` exactly
85/// one. On a mismatch it backtracks to the last `*` and gives it one more
86/// character, so no recursion is involved and a pathological pattern cannot
87/// blow the stack. Both inputs are expected to be lowercased already.
88fn glob_match(name: &str, pattern: &str) -> bool {
89    let name: Vec<char> = name.chars().collect();
90    let pattern: Vec<char> = pattern.chars().collect();
91
92    let (mut n, mut p) = (0, 0);
93    let mut star: Option<usize> = None;
94    let mut resume = 0;
95
96    while n < name.len() {
97        match pattern.get(p) {
98            Some('*') => {
99                star = Some(p);
100                resume = n;
101                p += 1;
102            }
103            Some('?') => {
104                p += 1;
105                n += 1;
106            }
107            Some(c) if *c == name[n] => {
108                p += 1;
109                n += 1;
110            }
111            _ => match star {
112                Some(s) => {
113                    p = s + 1;
114                    resume += 1;
115                    n = resume;
116                }
117                None => return false,
118            },
119        }
120    }
121
122    // Whatever is left of the pattern can only still match the empty
123    // remainder if it is nothing but `*`.
124    pattern[p..].iter().all(|c| *c == '*')
125}
126
127/// First visible row that keeps `cursor` inside a `visible`-row viewport whose
128/// top is currently `offset`.
129///
130/// Scrolls by the least amount that works: an offset that already shows the
131/// cursor is returned untouched, so the cursor travels within the viewport and
132/// only drags it along at the edges. A `visible` of 0 is meaningless and would
133/// underflow the subtraction, so it pins the viewport to the cursor.
134pub fn visible_offset(cursor: usize, offset: usize, visible: usize) -> usize {
135    if cursor < offset {
136        cursor
137    } else if visible == 0 || cursor >= offset + visible {
138        cursor.saturating_sub(visible.saturating_sub(1))
139    } else {
140        offset
141    }
142}
143
144#[derive(Debug, Clone)]
145pub struct Pane {
146    pub cwd: PathBuf,
147    pub entries: Vec<Entry>,
148    pub cursor: usize,
149    pub scroll_offset: usize,
150    pub show_hidden: bool,
151    pub selected: HashSet<usize>,
152    pub sort_key: SortKey,
153    pub sort_reversed: bool,
154    /// Name filter narrowing the listing; `None` lists everything.
155    pub filter: Option<String>,
156    /// Every entry read from `cwd`, before the hidden-file rule and the
157    /// filter narrow it. Kept so that re-deriving the listing — which an
158    /// inline filter does on every keystroke — never touches the disk again.
159    all_entries: Vec<Entry>,
160    /// Directories this pane has visited, oldest first. Always non-empty:
161    /// `history[history_index]` is the current `cwd`.
162    history: Vec<PathBuf>,
163    /// Position within `history`; everything after it is forward history.
164    history_index: usize,
165}
166
167impl Pane {
168    pub fn new(cwd: PathBuf) -> Self {
169        Self {
170            history: vec![cwd.clone()],
171            history_index: 0,
172            cwd,
173            entries: Vec::new(),
174            cursor: 0,
175            scroll_offset: 0,
176            show_hidden: false,
177            selected: HashSet::new(),
178            sort_key: SortKey::Name,
179            sort_reversed: false,
180            filter: None,
181            all_entries: Vec::new(),
182        }
183    }
184
185    /// Move to `path`, recording it in history.
186    ///
187    /// Navigating somewhere new after going back discards the forward tail:
188    /// the branch not taken is no longer reachable, which is how every
189    /// back/forward stack behaves.
190    pub fn navigate_to(&mut self, path: PathBuf) {
191        if path == self.cwd {
192            return;
193        }
194        self.history.truncate(self.history_index + 1);
195        self.history.push(path.clone());
196        self.history_index = self.history.len() - 1;
197        self.cwd = path;
198        self.load_entries();
199    }
200
201    /// Step back to the previously visited directory. Returns whether there
202    /// was anywhere to go.
203    pub fn go_back(&mut self) -> bool {
204        if self.history_index == 0 {
205            return false;
206        }
207        self.history_index -= 1;
208        self.cwd = self.history[self.history_index].clone();
209        self.load_entries();
210        true
211    }
212
213    /// Step forward again after going back.
214    pub fn go_forward(&mut self) -> bool {
215        if self.history_index + 1 >= self.history.len() {
216            return false;
217        }
218        self.history_index += 1;
219        self.cwd = self.history[self.history_index].clone();
220        self.load_entries();
221        true
222    }
223
224    pub fn can_go_back(&self) -> bool {
225        self.history_index > 0
226    }
227
228    pub fn can_go_forward(&self) -> bool {
229        self.history_index + 1 < self.history.len()
230    }
231
232    /// Sets the sort key directly. If the requested key is already active,
233    /// toggles the sort direction instead (the "press again to reverse"
234    /// convention used by clickable column headers).
235    pub fn set_sort_key(&mut self, key: SortKey) {
236        if self.sort_key == key {
237            self.sort_reversed = !self.sort_reversed;
238        } else {
239            self.sort_key = key;
240        }
241        self.apply_view();
242    }
243
244    pub fn toggle_hidden_files(&mut self) {
245        self.show_hidden = !self.show_hidden;
246        self.apply_view();
247    }
248
249    /// Sets the name filter, or clears it when `pattern` is blank — so
250    /// submitting an empty prompt is the same as clearing.
251    pub fn set_filter(&mut self, pattern: &str) {
252        let pattern = pattern.trim();
253        self.filter = if pattern.is_empty() {
254            None
255        } else {
256            Some(pattern.to_string())
257        };
258        self.apply_view();
259    }
260
261    pub fn clear_filter(&mut self) {
262        self.filter = None;
263        self.apply_view();
264    }
265
266    pub fn move_cursor_up(&mut self) {
267        if self.cursor > 0 {
268            self.cursor -= 1;
269            if self.cursor < self.scroll_offset {
270                self.scroll_offset = self.cursor;
271            }
272        }
273    }
274
275    pub fn move_cursor_down(&mut self) {
276        if !self.entries.is_empty() && self.cursor < self.entries.len() - 1 {
277            self.cursor += 1;
278            // Ensure cursor is within visible range; keep it centered by keeping 5 items below
279            const VISIBLE_ITEMS: usize = 20;
280            const KEEP_BELOW: usize = 5;
281            if self.cursor >= self.scroll_offset + VISIBLE_ITEMS - KEEP_BELOW {
282                self.scroll_offset = self.cursor.saturating_sub(VISIBLE_ITEMS - KEEP_BELOW - 1);
283            }
284        }
285    }
286
287    /// Keep the cursor in the visible viewport (for when viewport size changes or entries are reloaded)
288    pub fn ensure_cursor_visible(&mut self, visible_items: usize) {
289        self.scroll_offset = visible_offset(self.cursor, self.scroll_offset, visible_items);
290    }
291
292    pub fn selected(&self) -> Option<&Entry> {
293        self.entries.get(self.cursor)
294    }
295
296    pub fn toggle_selection(&mut self) {
297        if self
298            .entries
299            .get(self.cursor)
300            .map_or(true, |e| e.name == "..")
301        {
302            return;
303        }
304        if !self.selected.remove(&self.cursor) {
305            self.selected.insert(self.cursor);
306        }
307    }
308
309    pub fn extend_selection_down(&mut self) {
310        if self
311            .entries
312            .get(self.cursor)
313            .map_or(false, |e| e.name != "..")
314        {
315            self.selected.insert(self.cursor);
316        }
317        self.move_cursor_down();
318    }
319
320    pub fn extend_selection_up(&mut self) {
321        if self
322            .entries
323            .get(self.cursor)
324            .map_or(false, |e| e.name != "..")
325        {
326            self.selected.insert(self.cursor);
327        }
328        self.move_cursor_up();
329    }
330
331    pub fn clear_selection(&mut self) {
332        self.selected.clear();
333    }
334
335    /// Move the cursor to the first entry (other than "..") whose name starts with
336    /// `query`, case-insensitively. Leaves the cursor untouched if nothing matches.
337    /// Returns whether a match was found.
338    pub fn jump_to_prefix(&mut self, query: &str) -> bool {
339        if query.is_empty() {
340            return false;
341        }
342        let query = query.to_lowercase();
343        match self
344            .entries
345            .iter()
346            .position(|e| e.name != ".." && e.name.to_lowercase().starts_with(&query))
347        {
348            Some(index) => {
349                self.cursor = index;
350                true
351            }
352            None => false,
353        }
354    }
355
356    /// Returns the tagged indices (sorted), or `[cursor]` if nothing is tagged.
357    pub fn effective_selection(&self) -> Vec<usize> {
358        if self.selected.is_empty() {
359            vec![self.cursor]
360        } else {
361            let mut indices: Vec<usize> = self.selected.iter().copied().collect();
362            indices.sort_unstable();
363            indices
364        }
365    }
366
367    /// Load entries from the current working directory.
368    /// Read `cwd` from disk into the entry cache, then derive the listing.
369    /// The read is the expensive half, so anything that only changes *how*
370    /// entries are presented — sort, hidden files, the filter — goes through
371    /// `apply_view` instead of coming back here.
372    pub fn load_entries(&mut self) {
373        self.all_entries.clear();
374
375        // An unreadable directory yields an empty listing rather than an error.
376        if let Ok(entries_iter) = std::fs::read_dir(&self.cwd) {
377            for entry_result in entries_iter {
378                let Ok(entry) = entry_result else {
379                    continue;
380                };
381                let file_name = entry.file_name();
382                let name = file_name.to_string_lossy().to_string();
383
384                // Skip "." but don't skip ".."
385                if name == "." {
386                    continue;
387                }
388
389                let path = entry.path();
390                let metadata = entry.metadata().ok();
391                let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
392                let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
393                let modified = metadata.as_ref().and_then(|m| m.modified().ok());
394
395                self.all_entries.push(Entry {
396                    name,
397                    path,
398                    is_dir,
399                    size,
400                    modified,
401                });
402            }
403        }
404
405        self.apply_view();
406    }
407
408    /// Re-read `cwd` and rebuild the listing while keeping the user's place.
409    ///
410    /// This is the entry point for a reload nobody asked for — one driven by
411    /// another process writing to the directory. `load_entries` resets the
412    /// view through `apply_view`, which is right when the *user* changed what
413    /// they are looking at (navigation, sort, filter) and wrong here: the
414    /// cursor would snap to `..` whenever some background process touched the
415    /// directory.
416    ///
417    /// The reconciliation is by entry **name**, never by row index. `selected`
418    /// holds indices into the derived `entries` vec, whose length and order
419    /// shift as files appear and vanish, so keeping the indices would silently
420    /// re-tag whichever files landed on those rows — and the delete
421    /// confirmation acts on that set. Anchoring on names means the tagged set
422    /// can only ever shrink across a refresh, which is what makes refreshing
423    /// under an open modal safe.
424    pub fn reload_preserving_view(&mut self) {
425        let cursor_name = self.entries.get(self.cursor).map(|e| e.name.clone());
426        let cursor_index = self.cursor;
427        let scroll_offset = self.scroll_offset;
428        let tagged: HashSet<String> = self
429            .selected
430            .iter()
431            .filter_map(|&i| self.entries.get(i))
432            .map(|e| e.name.clone())
433            .collect();
434
435        self.load_entries();
436
437        if self.entries.is_empty() {
438            return;
439        }
440
441        // The cursor's own file may be gone. Falling back to `..` would be as
442        // disorienting as a full reset, so hold the row position instead: the
443        // cursor lands on whatever took the deleted file's place.
444        self.cursor = cursor_name
445            .and_then(|name| self.entries.iter().position(|e| e.name == name))
446            .unwrap_or_else(|| cursor_index.min(self.entries.len() - 1));
447
448        if !tagged.is_empty() {
449            self.selected = self
450                .entries
451                .iter()
452                .enumerate()
453                .filter(|(_, e)| tagged.contains(&e.name))
454                .map(|(i, _)| i)
455                .collect();
456        }
457
458        self.scroll_offset = scroll_offset.min(self.entries.len() - 1);
459    }
460
461    /// Rebuild the visible listing from the cached read: drop hidden files,
462    /// apply the filter, sort directories-then-files, and prepend the
463    /// synthetic `..`. Touches no I/O, so it is cheap enough to run on every
464    /// keystroke of an inline filter.
465    ///
466    /// Sorts directories first (alphabetical), then files by the active sort
467    /// key. Excludes "." but includes ".." (parent directory) if not at root.
468    fn apply_view(&mut self) {
469        self.entries.clear();
470        self.cursor = 0;
471        self.scroll_offset = 0;
472        self.selected.clear();
473
474        let mut dirs: Vec<Entry> = Vec::new();
475        let mut files: Vec<Entry> = Vec::new();
476
477        for entry in &self.all_entries {
478            if !self.show_hidden && entry.name.starts_with('.') {
479                continue;
480            }
481
482            // Narrows what is listed, on top of the hidden-file rule above and
483            // the sort below. `..` is prepended further down, so it is never
484            // subject to this.
485            if let Some(pattern) = &self.filter {
486                if !matches_filter(&entry.name, pattern) {
487                    continue;
488                }
489            }
490
491            if entry.is_dir {
492                dirs.push(entry.clone());
493            } else {
494                files.push(entry.clone());
495            }
496        }
497
498        // Directories are always sorted by name; size/modified aren't
499        // meaningful for a directory without a recursive scan.
500        dirs.sort_by(|a, b| a.name.cmp(&b.name));
501
502        match self.sort_key {
503            SortKey::Name => files.sort_by(|a, b| a.name.cmp(&b.name)),
504            SortKey::Size => files.sort_by_key(|f| f.size),
505            SortKey::Modified => files.sort_by_key(|f| f.modified),
506        }
507        if self.sort_reversed {
508            files.reverse();
509        }
510
511        // Add ".." first if not at root
512        if let Some(parent) = self.cwd.parent() {
513            self.entries.push(Entry {
514                name: "..".to_string(),
515                path: parent.to_path_buf(),
516                is_dir: true,
517                size: 0,
518                modified: None,
519            });
520        }
521
522        // Combine: directories, then files
523        self.entries.extend(dirs);
524        self.entries.extend(files);
525    }
526
527    /// Enter the selected directory. If selection is not a directory, does nothing.
528    pub fn enter_directory(&mut self) {
529        if let Some(entry) = self.selected() {
530            if entry.is_dir {
531                let target = entry.path.clone();
532                self.navigate_to(target);
533            }
534        }
535    }
536
537    /// Navigate to the parent directory. Does nothing if already at root.
538    pub fn goto_parent(&mut self) {
539        if let Some(parent) = self.cwd.parent() {
540            let target = parent.to_path_buf();
541            self.navigate_to(target);
542        }
543    }
544}
545
546#[derive(Debug, Clone)]
547pub struct DualPane {
548    pub left: Pane,
549    pub right: Pane,
550    pub active: PaneId,
551}
552
553impl DualPane {
554    pub fn new(left_cwd: PathBuf, right_cwd: PathBuf) -> Self {
555        Self {
556            left: Pane::new(left_cwd),
557            right: Pane::new(right_cwd),
558            active: PaneId::Left,
559        }
560    }
561
562    pub fn active_pane(&self) -> &Pane {
563        match self.active {
564            PaneId::Left => &self.left,
565            PaneId::Right => &self.right,
566        }
567    }
568
569    pub fn active_pane_mut(&mut self) -> &mut Pane {
570        match self.active {
571            PaneId::Left => &mut self.left,
572            PaneId::Right => &mut self.right,
573        }
574    }
575
576    pub fn pane(&self, id: PaneId) -> &Pane {
577        match id {
578            PaneId::Left => &self.left,
579            PaneId::Right => &self.right,
580        }
581    }
582
583    pub fn pane_mut(&mut self, id: PaneId) -> &mut Pane {
584        match id {
585            PaneId::Left => &mut self.left,
586            PaneId::Right => &mut self.right,
587        }
588    }
589
590    pub fn switch_active(&mut self) {
591        self.active = self.active.other();
592    }
593
594    /// Point the inactive pane at the active pane's directory, as a normal
595    /// navigation: it is recorded in that pane's history, and the pane keeps
596    /// its own sort, hidden-files and filter settings.
597    pub fn sync_inactive_to_active(&mut self) {
598        let cwd = self.active_pane().cwd.clone();
599        self.pane_mut(self.active.other()).navigate_to(cwd);
600    }
601
602    pub fn toggle_hidden_files(&mut self) {
603        self.left.toggle_hidden_files();
604        self.right.toggle_hidden_files();
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611
612    #[test]
613    fn visible_offset_leaves_a_cursor_already_in_view_alone() {
614        // Rows 10..14 are showing and the cursor is among them: not scrolling
615        // is what lets the cursor travel inside the viewport.
616        assert_eq!(visible_offset(10, 10, 5), 10);
617        assert_eq!(visible_offset(12, 10, 5), 10);
618        assert_eq!(visible_offset(14, 10, 5), 10);
619    }
620
621    #[test]
622    fn visible_offset_follows_a_cursor_above_the_viewport() {
623        assert_eq!(visible_offset(7, 10, 5), 7);
624        assert_eq!(visible_offset(0, 10, 5), 0);
625    }
626
627    #[test]
628    fn visible_offset_follows_a_cursor_below_the_viewport() {
629        // One past the last visible row scrolls by exactly one row.
630        assert_eq!(visible_offset(15, 10, 5), 11);
631        assert_eq!(visible_offset(20, 10, 5), 16);
632    }
633
634    #[test]
635    fn visible_offset_stays_at_zero_when_everything_fits() {
636        assert_eq!(visible_offset(0, 0, 50), 0);
637        assert_eq!(visible_offset(20, 0, 50), 0);
638    }
639
640    #[test]
641    fn visible_offset_survives_a_zero_row_viewport() {
642        // Nothing can be shown, so the best available answer is the cursor
643        // itself; the point is that it must not underflow.
644        assert_eq!(visible_offset(0, 0, 0), 0);
645        assert_eq!(visible_offset(3, 0, 0), 3);
646    }
647
648    #[test]
649    fn ensure_cursor_visible_scrolls_to_the_cursor() {
650        let mut pane = Pane::new(PathBuf::from("/tmp"));
651        pane.cursor = 30;
652        pane.ensure_cursor_visible(5);
653        assert_eq!(pane.scroll_offset, 26);
654
655        pane.cursor = 2;
656        pane.ensure_cursor_visible(5);
657        assert_eq!(pane.scroll_offset, 2);
658    }
659
660    #[test]
661    fn cursor_does_not_go_below_zero() {
662        let mut pane = Pane::new(PathBuf::from("/tmp"));
663        pane.move_cursor_up();
664        assert_eq!(pane.cursor, 0);
665    }
666
667    #[test]
668    fn hidden_files_are_hidden_by_default() {
669        let pane = Pane::new(PathBuf::from("/tmp"));
670        assert!(!pane.show_hidden);
671    }
672
673    #[test]
674    fn toggle_hidden_files_toggles_both_panes() {
675        let mut dp = DualPane::new("/".into(), "/tmp".into());
676
677        dp.toggle_hidden_files();
678
679        assert!(dp.left.show_hidden);
680        assert!(dp.right.show_hidden);
681
682        dp.toggle_hidden_files();
683
684        assert!(!dp.left.show_hidden);
685        assert!(!dp.right.show_hidden);
686    }
687
688    /// Entry names excluding the synthetic `..`, in listing order.
689    fn listed(pane: &Pane) -> Vec<&str> {
690        pane.entries
691            .iter()
692            .filter(|e| e.name != "..")
693            .map(|e| e.name.as_str())
694            .collect()
695    }
696
697    #[test]
698    fn cursor_does_not_exceed_entries() {
699        let mut pane = Pane::new(PathBuf::from("/tmp"));
700        pane.entries = vec![Entry {
701            name: "a".into(),
702            path: "/tmp/a".into(),
703            is_dir: false,
704            size: 0,
705            modified: None,
706        }];
707        pane.move_cursor_down();
708        pane.move_cursor_down();
709        assert_eq!(pane.cursor, 0);
710    }
711
712    #[test]
713    fn switch_active_toggles_pane() {
714        let mut dp = DualPane::new("/".into(), "/tmp".into());
715        assert_eq!(dp.active, PaneId::Left);
716        dp.switch_active();
717        assert_eq!(dp.active, PaneId::Right);
718        dp.switch_active();
719        assert_eq!(dp.active, PaneId::Left);
720    }
721
722    #[test]
723    fn load_entries_sorts_directories_first() {
724        let mut pane = Pane::new(std::env::temp_dir());
725        pane.load_entries();
726
727        // Verify structure: all dirs should come before all files
728        let mut found_file = false;
729        for entry in &pane.entries {
730            if !entry.is_dir {
731                found_file = true;
732            } else if found_file {
733                panic!("Found directory after file; sort order violated");
734            }
735        }
736
737        // Also verify alphabetical within each group
738        let mut prev_dir: Option<&str> = None;
739        for entry in &pane.entries {
740            if entry.is_dir {
741                if let Some(prev) = prev_dir {
742                    assert!(
743                        prev <= entry.name.as_str(),
744                        "Directories not sorted alphabetically"
745                    );
746                }
747                prev_dir = Some(&entry.name);
748            }
749        }
750    }
751
752    #[test]
753    fn enter_directory_changes_cwd() {
754        // Use a real temp directory for this test
755        let temp_dir = std::env::temp_dir();
756        let mut pane = Pane::new(temp_dir.clone());
757
758        // Create an entry pointing to a real directory
759        pane.entries = vec![Entry {
760            name: "test_entry".into(),
761            path: temp_dir.clone(),
762            is_dir: true,
763            size: 0,
764            modified: None,
765        }];
766        pane.cursor = 0;
767
768        pane.enter_directory();
769
770        // The cwd should update to the selected entry's path
771        assert_eq!(pane.cwd, temp_dir);
772    }
773
774    #[test]
775    fn goto_parent_navigates_up() {
776        let mut pane = Pane::new(PathBuf::from("/tmp/some/nested/path"));
777        let parent = pane.cwd.parent().unwrap().to_path_buf();
778
779        pane.goto_parent();
780
781        assert_eq!(pane.cwd, parent);
782    }
783
784    #[test]
785    fn goto_parent_at_root_does_nothing() {
786        let mut pane = Pane::new(PathBuf::from("/"));
787        let _original_cwd = pane.cwd.clone();
788
789        pane.goto_parent();
790
791        assert_eq!(pane.cwd, PathBuf::from("/"));
792    }
793
794    fn pane_with_entries(names: &[&str]) -> Pane {
795        let mut pane = Pane::new(PathBuf::from("/tmp"));
796        pane.entries = names
797            .iter()
798            .map(|n| Entry {
799                name: n.to_string(),
800                path: PathBuf::from(format!("/tmp/{n}")),
801                is_dir: false,
802                size: 0,
803                modified: None,
804            })
805            .collect();
806        pane
807    }
808
809    #[test]
810    fn toggle_selection_marks_and_unmarks() {
811        let mut pane = pane_with_entries(&["a", "b", "c"]);
812        pane.toggle_selection();
813        assert!(pane.selected.contains(&0));
814        pane.toggle_selection();
815        assert!(!pane.selected.contains(&0));
816    }
817
818    #[test]
819    fn toggle_selection_skips_parent_entry() {
820        let mut pane = Pane::new(PathBuf::from("/tmp"));
821        pane.entries = vec![Entry {
822            name: "..".into(),
823            path: "/".into(),
824            is_dir: true,
825            size: 0,
826            modified: None,
827        }];
828        pane.toggle_selection();
829        assert!(pane.selected.is_empty());
830    }
831
832    #[test]
833    fn effective_selection_returns_cursor_when_nothing_tagged() {
834        let mut pane = pane_with_entries(&["a", "b", "c"]);
835        pane.cursor = 2;
836        assert_eq!(pane.effective_selection(), vec![2]);
837    }
838
839    #[test]
840    fn effective_selection_returns_sorted_tagged_indices() {
841        let mut pane = pane_with_entries(&["a", "b", "c"]);
842        pane.selected.insert(2);
843        pane.selected.insert(0);
844        assert_eq!(pane.effective_selection(), vec![0, 2]);
845    }
846
847    #[test]
848    fn extend_selection_down_tags_current_and_advances_cursor() {
849        let mut pane = pane_with_entries(&["a", "b", "c"]);
850        pane.extend_selection_down();
851        assert!(pane.selected.contains(&0));
852        assert_eq!(pane.cursor, 1);
853    }
854
855    #[test]
856    fn extend_selection_up_tags_current_and_moves_cursor_up() {
857        let mut pane = pane_with_entries(&["a", "b", "c"]);
858        pane.cursor = 2;
859        pane.extend_selection_up();
860        assert!(pane.selected.contains(&2));
861        assert_eq!(pane.cursor, 1);
862    }
863
864    #[test]
865    fn load_entries_clears_selection() {
866        let mut pane = Pane::new(std::env::temp_dir());
867        pane.selected.insert(0);
868        pane.selected.insert(1);
869        pane.load_entries();
870        assert!(pane.selected.is_empty());
871    }
872
873    #[test]
874    fn jump_to_prefix_moves_cursor_to_match() {
875        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
876        assert!(pane.jump_to_prefix("ban"));
877        assert_eq!(pane.cursor, 1);
878    }
879
880    #[test]
881    fn jump_to_prefix_is_case_insensitive() {
882        let mut pane = pane_with_entries(&["Apple", "Banana", "Cherry"]);
883        assert!(pane.jump_to_prefix("cher"));
884        assert_eq!(pane.cursor, 2);
885    }
886
887    #[test]
888    fn jump_to_prefix_no_match_leaves_cursor_and_returns_false() {
889        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
890        pane.cursor = 1;
891        assert!(!pane.jump_to_prefix("zzz"));
892        assert_eq!(pane.cursor, 1);
893    }
894
895    #[test]
896    fn jump_to_prefix_skips_parent_entry() {
897        let mut pane = Pane::new(PathBuf::from("/tmp"));
898        pane.entries = vec![
899            Entry {
900                name: "..".into(),
901                path: "/".into(),
902                is_dir: true,
903                size: 0,
904                modified: None,
905            },
906            Entry {
907                name: "docs".into(),
908                path: "/tmp/docs".into(),
909                is_dir: true,
910                size: 0,
911                modified: None,
912            },
913        ];
914        pane.cursor = 1;
915        assert!(!pane.jump_to_prefix(".."));
916        assert_eq!(pane.cursor, 1);
917    }
918
919    #[test]
920    fn set_sort_key_changes_key_and_leaves_direction() {
921        let mut pane = Pane::new(std::env::temp_dir());
922        pane.sort_reversed = true;
923        pane.set_sort_key(SortKey::Size);
924        assert_eq!(pane.sort_key, SortKey::Size);
925        assert!(pane.sort_reversed);
926    }
927
928    #[test]
929    fn set_sort_key_toggles_direction_when_key_already_active() {
930        let mut pane = Pane::new(std::env::temp_dir());
931        assert_eq!(pane.sort_key, SortKey::Name);
932        assert!(!pane.sort_reversed);
933
934        pane.set_sort_key(SortKey::Name);
935        assert_eq!(pane.sort_key, SortKey::Name);
936        assert!(pane.sort_reversed);
937
938        pane.set_sort_key(SortKey::Name);
939        assert_eq!(pane.sort_key, SortKey::Name);
940        assert!(!pane.sort_reversed);
941    }
942
943    #[test]
944    fn set_sort_key_reorders_entries() {
945        let dir = std::env::temp_dir().join("oxinav_test_set_sort_key_reorders");
946        std::fs::create_dir_all(&dir).unwrap();
947        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
948        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
949
950        let mut pane = Pane::new(dir.clone());
951        pane.load_entries();
952        pane.set_sort_key(SortKey::Size);
953
954        let names: Vec<&str> = pane
955            .entries
956            .iter()
957            .filter(|e| e.name != "..")
958            .map(|e| e.name.as_str())
959            .collect();
960        assert_eq!(names, vec!["small.txt", "big.txt"]);
961
962        std::fs::remove_dir_all(&dir).ok();
963    }
964
965    #[test]
966    fn sorts_files_by_size() {
967        let dir = std::env::temp_dir().join("oxinav_test_sort_by_size");
968        std::fs::create_dir_all(&dir).unwrap();
969        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
970        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
971
972        let mut pane = Pane::new(dir.clone());
973        pane.sort_key = SortKey::Size;
974        pane.load_entries();
975
976        let names: Vec<&str> = pane
977            .entries
978            .iter()
979            .filter(|e| e.name != "..")
980            .map(|e| e.name.as_str())
981            .collect();
982        assert_eq!(names, vec!["small.txt", "big.txt"]);
983
984        std::fs::remove_dir_all(&dir).ok();
985    }
986
987    #[test]
988    fn sorts_files_reversed() {
989        let dir = std::env::temp_dir().join("oxinav_test_sort_reversed");
990        std::fs::create_dir_all(&dir).unwrap();
991        std::fs::write(dir.join("a.txt"), b"a").unwrap();
992        std::fs::write(dir.join("b.txt"), b"b").unwrap();
993
994        let mut pane = Pane::new(dir.clone());
995        pane.sort_reversed = true;
996        pane.load_entries();
997
998        let names: Vec<&str> = pane
999            .entries
1000            .iter()
1001            .filter(|e| e.name != "..")
1002            .map(|e| e.name.as_str())
1003            .collect();
1004        assert_eq!(names, vec!["b.txt", "a.txt"]);
1005
1006        std::fs::remove_dir_all(&dir).ok();
1007    }
1008
1009    // --- filtering ---
1010
1011    #[test]
1012    fn bare_pattern_matches_as_a_substring() {
1013        assert!(matches_filter("Cargo.toml", "cargo"));
1014        assert!(matches_filter("main.rs", ".rs"));
1015        assert!(!matches_filter("main.rs", "toml"));
1016    }
1017
1018    #[test]
1019    fn wildcard_pattern_matches_as_a_glob_over_the_whole_name() {
1020        assert!(matches_filter("main.rs", "*.rs"));
1021        assert!(!matches_filter("main.rsx", "*.rs"));
1022        assert!(matches_filter("Cargo.toml", "cargo*"));
1023        assert!(!matches_filter("build.rs", "cargo*"));
1024    }
1025
1026    #[test]
1027    fn question_mark_matches_exactly_one_character() {
1028        assert!(matches_filter("a.rs", "?.rs"));
1029        assert!(!matches_filter("ab.rs", "?.rs"));
1030    }
1031
1032    #[test]
1033    fn matching_ignores_case_in_both_modes() {
1034        assert!(matches_filter("README.MD", "readme"));
1035        assert!(matches_filter("README.MD", "*.md"));
1036    }
1037
1038    #[test]
1039    fn blank_pattern_matches_everything() {
1040        assert!(matches_filter("anything", ""));
1041        assert!(matches_filter("anything", "   "));
1042    }
1043
1044    #[test]
1045    fn consecutive_stars_do_not_change_the_match() {
1046        assert!(matches_filter("main.rs", "**.rs"));
1047        assert!(matches_filter("main.rs", "*"));
1048    }
1049
1050    #[test]
1051    fn set_filter_narrows_the_listing_and_clear_restores_it() {
1052        let dir = std::env::temp_dir().join("oxinav_test_filter_narrows");
1053        std::fs::remove_dir_all(&dir).ok();
1054        std::fs::create_dir_all(&dir).unwrap();
1055        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1056        std::fs::write(dir.join("lib.rs"), b"b").unwrap();
1057        std::fs::write(dir.join("Cargo.toml"), b"c").unwrap();
1058
1059        let mut pane = Pane::new(dir.clone());
1060        pane.load_entries();
1061        pane.set_filter("*.rs");
1062
1063        let names = listed(&pane);
1064        assert_eq!(names, vec!["lib.rs", "main.rs"]);
1065
1066        pane.clear_filter();
1067        assert_eq!(listed(&pane), vec!["Cargo.toml", "lib.rs", "main.rs"]);
1068
1069        std::fs::remove_dir_all(&dir).ok();
1070    }
1071
1072    #[test]
1073    fn parent_entry_survives_a_filter_matching_nothing() {
1074        let dir = std::env::temp_dir().join("oxinav_test_filter_keeps_parent");
1075        std::fs::remove_dir_all(&dir).ok();
1076        std::fs::create_dir_all(&dir).unwrap();
1077        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1078
1079        let mut pane = Pane::new(dir.clone());
1080        pane.load_entries();
1081        pane.set_filter("*.nomatch");
1082
1083        assert!(listed(&pane).is_empty());
1084        // `..` is the only thing left, so navigating up is still possible.
1085        let all: Vec<&str> = pane.entries.iter().map(|e| e.name.as_str()).collect();
1086        assert_eq!(all, vec![".."]);
1087
1088        std::fs::remove_dir_all(&dir).ok();
1089    }
1090
1091    #[test]
1092    fn filter_composes_with_the_hidden_files_toggle() {
1093        let dir = std::env::temp_dir().join("oxinav_test_filter_hidden");
1094        std::fs::remove_dir_all(&dir).ok();
1095        std::fs::create_dir_all(&dir).unwrap();
1096        std::fs::write(dir.join("visible.rs"), b"a").unwrap();
1097        std::fs::write(dir.join(".hidden.rs"), b"b").unwrap();
1098
1099        let mut pane = Pane::new(dir.clone());
1100        pane.load_entries();
1101        pane.set_filter("*.rs");
1102        assert_eq!(listed(&pane), vec!["visible.rs"]);
1103
1104        // Revealing hidden files widens the set the filter then narrows.
1105        pane.toggle_hidden_files();
1106        assert_eq!(listed(&pane), vec![".hidden.rs", "visible.rs"]);
1107
1108        std::fs::remove_dir_all(&dir).ok();
1109    }
1110
1111    #[test]
1112    fn filter_composes_with_the_active_sort_key() {
1113        let dir = std::env::temp_dir().join("oxinav_test_filter_sort");
1114        std::fs::remove_dir_all(&dir).ok();
1115        std::fs::create_dir_all(&dir).unwrap();
1116        std::fs::write(dir.join("big.rs"), vec![0u8; 100]).unwrap();
1117        std::fs::write(dir.join("small.rs"), vec![0u8; 10]).unwrap();
1118        std::fs::write(dir.join("huge.toml"), vec![0u8; 999]).unwrap();
1119
1120        let mut pane = Pane::new(dir.clone());
1121        pane.load_entries();
1122        pane.set_filter("*.rs");
1123        pane.set_sort_key(SortKey::Size);
1124
1125        // Sorted by size, and the excluded .toml stays excluded.
1126        assert_eq!(listed(&pane), vec!["small.rs", "big.rs"]);
1127
1128        std::fs::remove_dir_all(&dir).ok();
1129    }
1130
1131    #[test]
1132    fn filter_applies_to_directories_too() {
1133        let dir = std::env::temp_dir().join("oxinav_test_filter_dirs");
1134        std::fs::remove_dir_all(&dir).ok();
1135        std::fs::create_dir_all(dir.join("src")).unwrap();
1136        std::fs::create_dir_all(dir.join("target")).unwrap();
1137        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1138
1139        let mut pane = Pane::new(dir.clone());
1140        pane.load_entries();
1141        pane.set_filter("*.rs");
1142
1143        assert_eq!(listed(&pane), vec!["main.rs"]);
1144
1145        std::fs::remove_dir_all(&dir).ok();
1146    }
1147
1148    #[test]
1149    fn refiltering_does_not_re_read_the_directory() {
1150        let dir = std::env::temp_dir().join("oxinav_test_filter_no_reread");
1151        std::fs::remove_dir_all(&dir).ok();
1152        std::fs::create_dir_all(&dir).unwrap();
1153        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1154        std::fs::write(dir.join("notes.txt"), b"b").unwrap();
1155
1156        let mut pane = Pane::new(dir.clone());
1157        pane.load_entries();
1158
1159        // Delete the directory out from under the pane. Re-filtering now can
1160        // only succeed if it works off the cached read, which is what makes
1161        // it cheap enough to run on every keystroke.
1162        std::fs::remove_dir_all(&dir).ok();
1163
1164        pane.set_filter("*.rs");
1165        assert_eq!(listed(&pane), vec!["main.rs"]);
1166
1167        pane.clear_filter();
1168        assert_eq!(listed(&pane), vec!["main.rs", "notes.txt"]);
1169    }
1170
1171    // --- directory history ---
1172
1173    #[test]
1174    fn back_returns_to_the_previous_directory() {
1175        let mut pane = Pane::new(PathBuf::from("/a"));
1176        pane.navigate_to(PathBuf::from("/b"));
1177        assert_eq!(pane.cwd, PathBuf::from("/b"));
1178
1179        assert!(pane.go_back());
1180        assert_eq!(pane.cwd, PathBuf::from("/a"));
1181    }
1182
1183    #[test]
1184    fn forward_returns_after_going_back() {
1185        let mut pane = Pane::new(PathBuf::from("/a"));
1186        pane.navigate_to(PathBuf::from("/b"));
1187        pane.go_back();
1188
1189        assert!(pane.go_forward());
1190        assert_eq!(pane.cwd, PathBuf::from("/b"));
1191    }
1192
1193    #[test]
1194    fn navigating_anew_truncates_the_forward_tail() {
1195        let mut pane = Pane::new(PathBuf::from("/a"));
1196        pane.navigate_to(PathBuf::from("/b"));
1197        pane.go_back();
1198        // Branching from A to C makes B unreachable.
1199        pane.navigate_to(PathBuf::from("/c"));
1200
1201        assert!(!pane.can_go_forward());
1202        assert!(!pane.go_forward());
1203        assert_eq!(pane.cwd, PathBuf::from("/c"));
1204
1205        // Back now leads to A, not B.
1206        assert!(pane.go_back());
1207        assert_eq!(pane.cwd, PathBuf::from("/a"));
1208    }
1209
1210    #[test]
1211    fn back_at_the_start_of_history_does_nothing() {
1212        let mut pane = Pane::new(PathBuf::from("/a"));
1213
1214        assert!(!pane.can_go_back());
1215        assert!(!pane.go_back());
1216        assert_eq!(pane.cwd, PathBuf::from("/a"));
1217    }
1218
1219    #[test]
1220    fn forward_without_going_back_does_nothing() {
1221        let mut pane = Pane::new(PathBuf::from("/a"));
1222        pane.navigate_to(PathBuf::from("/b"));
1223
1224        assert!(!pane.can_go_forward());
1225        assert!(!pane.go_forward());
1226        assert_eq!(pane.cwd, PathBuf::from("/b"));
1227    }
1228
1229    #[test]
1230    fn navigating_to_the_current_directory_is_not_recorded() {
1231        let mut pane = Pane::new(PathBuf::from("/a"));
1232        pane.navigate_to(PathBuf::from("/a"));
1233
1234        // Re-entering where we already are must not create a history step
1235        // that back would then have to walk through.
1236        assert!(!pane.can_go_back());
1237    }
1238
1239    #[test]
1240    fn history_survives_several_steps_in_both_directions() {
1241        let mut pane = Pane::new(PathBuf::from("/a"));
1242        pane.navigate_to(PathBuf::from("/b"));
1243        pane.navigate_to(PathBuf::from("/c"));
1244
1245        assert!(pane.go_back());
1246        assert!(pane.go_back());
1247        assert_eq!(pane.cwd, PathBuf::from("/a"));
1248
1249        assert!(pane.go_forward());
1250        assert!(pane.go_forward());
1251        assert_eq!(pane.cwd, PathBuf::from("/c"));
1252    }
1253
1254    #[test]
1255    fn history_is_per_pane() {
1256        let mut dp = DualPane::new("/left".into(), "/right".into());
1257        dp.left.navigate_to(PathBuf::from("/left/sub"));
1258
1259        assert!(dp.left.can_go_back());
1260        assert!(!dp.right.can_go_back());
1261    }
1262
1263    #[test]
1264    fn sync_moves_only_the_inactive_pane() {
1265        let mut dp = DualPane::new("/left".into(), "/right".into());
1266        dp.left.cursor = 3;
1267
1268        dp.sync_inactive_to_active();
1269
1270        assert_eq!(dp.right.cwd, PathBuf::from("/left"));
1271        assert_eq!(dp.left.cwd, PathBuf::from("/left"));
1272        assert_eq!(dp.left.cursor, 3);
1273        assert_eq!(dp.active, PaneId::Left);
1274    }
1275
1276    #[test]
1277    fn sync_follows_whichever_pane_is_active() {
1278        let mut dp = DualPane::new("/left".into(), "/right".into());
1279        dp.switch_active();
1280
1281        dp.sync_inactive_to_active();
1282
1283        assert_eq!(dp.left.cwd, PathBuf::from("/right"));
1284        assert_eq!(dp.active, PaneId::Right);
1285    }
1286
1287    #[test]
1288    fn sync_keeps_the_inactive_panes_view_settings() {
1289        let dir = std::env::temp_dir().join("oxinav_test_sync_view_settings");
1290        std::fs::create_dir_all(&dir).unwrap();
1291        std::fs::write(dir.join("small.rs"), "x").unwrap();
1292        std::fs::write(dir.join("large.rs"), "x".repeat(100)).unwrap();
1293        std::fs::write(dir.join("notes.txt"), "x").unwrap();
1294
1295        let mut dp = DualPane::new(dir.clone(), std::env::temp_dir());
1296        dp.right.sort_key = SortKey::Size;
1297        dp.right.set_filter("*.rs");
1298
1299        dp.sync_inactive_to_active();
1300
1301        assert_eq!(dp.right.sort_key, SortKey::Size);
1302        assert_eq!(dp.right.filter.as_deref(), Some("*.rs"));
1303        let names: Vec<&str> = dp
1304            .right
1305            .entries
1306            .iter()
1307            .map(|e| e.name.as_str())
1308            .filter(|n| *n != "..")
1309            .collect();
1310        assert_eq!(names, vec!["small.rs", "large.rs"]);
1311
1312        std::fs::remove_dir_all(&dir).unwrap();
1313    }
1314
1315    #[test]
1316    fn sync_to_the_same_directory_adds_no_history() {
1317        let mut dp = DualPane::new("/same".into(), "/same".into());
1318
1319        dp.sync_inactive_to_active();
1320
1321        assert!(!dp.left.can_go_back());
1322        assert!(!dp.right.can_go_back());
1323    }
1324
1325    #[test]
1326    fn back_on_the_inactive_pane_undoes_a_sync() {
1327        let mut dp = DualPane::new("/left".into(), "/right".into());
1328        dp.sync_inactive_to_active();
1329        dp.switch_active();
1330
1331        assert!(dp.active_pane_mut().go_back());
1332        assert_eq!(dp.right.cwd, PathBuf::from("/right"));
1333    }
1334
1335    #[test]
1336    fn set_filter_with_a_blank_pattern_clears_it() {
1337        let mut pane = Pane::new(std::env::temp_dir());
1338        pane.set_filter("*.rs");
1339        assert!(pane.filter.is_some());
1340
1341        pane.set_filter("   ");
1342        assert!(pane.filter.is_none());
1343    }
1344
1345    #[test]
1346    fn directories_stay_name_sorted_regardless_of_sort_key() {
1347        let dir = std::env::temp_dir().join("oxinav_test_sort_dirs_stable");
1348        std::fs::create_dir_all(dir.join("b_dir")).unwrap();
1349        std::fs::create_dir_all(dir.join("a_dir")).unwrap();
1350
1351        let mut pane = Pane::new(dir.clone());
1352        pane.sort_key = SortKey::Size;
1353        pane.load_entries();
1354
1355        let names: Vec<&str> = pane
1356            .entries
1357            .iter()
1358            .filter(|e| e.name != "..")
1359            .map(|e| e.name.as_str())
1360            .collect();
1361        assert_eq!(names, vec!["a_dir", "b_dir"]);
1362
1363        std::fs::remove_dir_all(&dir).ok();
1364    }
1365
1366    #[test]
1367    fn sort_key_labels_round_trip() {
1368        for key in [SortKey::Name, SortKey::Size, SortKey::Modified] {
1369            assert_eq!(SortKey::from_label(key.label()), Some(key));
1370        }
1371    }
1372
1373    #[test]
1374    fn sort_key_from_label_ignores_case_and_padding() {
1375        assert_eq!(SortKey::from_label(" Modified "), Some(SortKey::Modified));
1376    }
1377
1378    #[test]
1379    fn sort_key_from_label_is_none_for_an_unknown_word() {
1380        assert_eq!(SortKey::from_label("colour"), None);
1381        assert_eq!(SortKey::from_label(""), None);
1382    }
1383    // --- refreshing after an external change ---
1384
1385    /// The refresh tests need a real directory they can mutate behind the
1386    /// pane's back, which is what an external change *is*.
1387    fn refresh_scratch(name: &str) -> PathBuf {
1388        let dir = std::env::temp_dir().join(format!("oxinav_test_refresh_{name}"));
1389        std::fs::remove_dir_all(&dir).ok();
1390        std::fs::create_dir_all(&dir).unwrap();
1391        dir
1392    }
1393
1394    fn visible_names(pane: &Pane) -> Vec<&str> {
1395        pane.entries
1396            .iter()
1397            .filter(|e| e.name != "..")
1398            .map(|e| e.name.as_str())
1399            .collect()
1400    }
1401
1402    fn tagged_names(pane: &Pane) -> Vec<&str> {
1403        let mut names: Vec<&str> = pane
1404            .selected
1405            .iter()
1406            .map(|&i| pane.entries[i].name.as_str())
1407            .collect();
1408        names.sort_unstable();
1409        names
1410    }
1411
1412    #[test]
1413    fn refresh_shows_an_externally_created_file_and_keeps_the_cursor() {
1414        let dir = refresh_scratch("create");
1415        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1416        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1417
1418        let mut pane = Pane::new(dir.clone());
1419        pane.load_entries();
1420        // ["..", "a.txt", "c.txt"] — park on c.txt.
1421        pane.cursor = 2;
1422        assert_eq!(pane.entries[pane.cursor].name, "c.txt");
1423
1424        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1425        pane.reload_preserving_view();
1426
1427        assert_eq!(visible_names(&pane), vec!["a.txt", "b.txt", "c.txt"]);
1428        // b.txt pushed c.txt down a row; the cursor followed the file.
1429        assert_eq!(pane.cursor, 3);
1430        assert_eq!(pane.entries[pane.cursor].name, "c.txt");
1431
1432        std::fs::remove_dir_all(&dir).ok();
1433    }
1434
1435    #[test]
1436    fn refresh_keeps_tags_on_their_files_when_a_row_is_inserted_above() {
1437        let dir = refresh_scratch("insert_above");
1438        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1439        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1440
1441        let mut pane = Pane::new(dir.clone());
1442        pane.load_entries();
1443        // ["..", "b.txt", "c.txt"]
1444        pane.selected.insert(1);
1445        pane.selected.insert(2);
1446
1447        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1448        pane.reload_preserving_view();
1449
1450        // Had the indices been preserved, a.txt would now be tagged and
1451        // c.txt would not.
1452        assert_eq!(tagged_names(&pane), vec!["b.txt", "c.txt"]);
1453
1454        std::fs::remove_dir_all(&dir).ok();
1455    }
1456
1457    #[test]
1458    fn refresh_drops_a_tagged_file_that_was_deleted_externally() {
1459        let dir = refresh_scratch("delete_tagged");
1460        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1461        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1462        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1463
1464        let mut pane = Pane::new(dir.clone());
1465        pane.load_entries();
1466        // ["..", "a.txt", "b.txt", "c.txt"]
1467        pane.selected.insert(1);
1468        pane.selected.insert(3);
1469
1470        std::fs::remove_file(dir.join("a.txt")).unwrap();
1471        pane.reload_preserving_view();
1472
1473        assert_eq!(visible_names(&pane), vec!["b.txt", "c.txt"]);
1474        assert_eq!(tagged_names(&pane), vec!["c.txt"]);
1475
1476        std::fs::remove_dir_all(&dir).ok();
1477    }
1478
1479    #[test]
1480    fn refresh_clamps_the_cursor_when_its_file_is_deleted() {
1481        let dir = refresh_scratch("delete_cursor");
1482        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1483        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1484        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1485
1486        let mut pane = Pane::new(dir.clone());
1487        pane.load_entries();
1488        pane.cursor = 2;
1489        assert_eq!(pane.entries[pane.cursor].name, "b.txt");
1490
1491        std::fs::remove_file(dir.join("b.txt")).unwrap();
1492        pane.reload_preserving_view();
1493
1494        // Row held, not reset to 0: the cursor sits on what took b.txt's place.
1495        assert_eq!(pane.cursor, 2);
1496        assert_eq!(pane.entries[pane.cursor].name, "c.txt");
1497
1498        // And clamps rather than dangling when the tail is gone too.
1499        std::fs::remove_file(dir.join("c.txt")).unwrap();
1500        pane.reload_preserving_view();
1501        assert_eq!(pane.cursor, 1);
1502        assert_eq!(pane.entries[pane.cursor].name, "a.txt");
1503
1504        std::fs::remove_dir_all(&dir).ok();
1505    }
1506
1507    #[test]
1508    fn refresh_keeps_hidden_files_hidden() {
1509        let dir = refresh_scratch("hidden");
1510        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1511
1512        let mut pane = Pane::new(dir.clone());
1513        pane.load_entries();
1514
1515        std::fs::write(dir.join(".secret"), b"s").unwrap();
1516        pane.reload_preserving_view();
1517        assert_eq!(visible_names(&pane), vec!["a.txt"]);
1518
1519        pane.toggle_hidden_files();
1520        assert_eq!(visible_names(&pane), vec![".secret", "a.txt"]);
1521
1522        std::fs::remove_dir_all(&dir).ok();
1523    }
1524
1525    #[test]
1526    fn refresh_applies_the_active_filter_and_sort_key() {
1527        let dir = refresh_scratch("filter_sort");
1528        std::fs::write(dir.join("keep_big.log"), vec![0u8; 100]).unwrap();
1529        std::fs::write(dir.join("keep_small.log"), vec![0u8; 10]).unwrap();
1530        std::fs::write(dir.join("other.txt"), b"x").unwrap();
1531
1532        let mut pane = Pane::new(dir.clone());
1533        pane.sort_key = SortKey::Size;
1534        pane.load_entries();
1535        pane.set_filter(".log");
1536        assert_eq!(visible_names(&pane), vec!["keep_small.log", "keep_big.log"]);
1537
1538        std::fs::write(dir.join("keep_mid.log"), vec![0u8; 50]).unwrap();
1539        std::fs::write(dir.join("ignored.txt"), b"y").unwrap();
1540        pane.reload_preserving_view();
1541
1542        assert_eq!(
1543            visible_names(&pane),
1544            vec!["keep_small.log", "keep_mid.log", "keep_big.log"]
1545        );
1546
1547        std::fs::remove_dir_all(&dir).ok();
1548    }
1549
1550    #[test]
1551    fn refresh_of_an_unchanged_directory_changes_nothing() {
1552        let dir = refresh_scratch("unchanged");
1553        for name in ["a.txt", "b.txt", "c.txt", "d.txt"] {
1554            std::fs::write(dir.join(name), b"x").unwrap();
1555        }
1556
1557        let mut pane = Pane::new(dir.clone());
1558        pane.load_entries();
1559        pane.cursor = 3;
1560        pane.scroll_offset = 2;
1561        pane.selected.insert(1);
1562        pane.selected.insert(4);
1563        let before = pane.entries.clone();
1564
1565        pane.reload_preserving_view();
1566
1567        assert_eq!(pane.entries, before);
1568        assert_eq!(pane.cursor, 3);
1569        assert_eq!(pane.scroll_offset, 2);
1570        assert_eq!(tagged_names(&pane), vec!["a.txt", "d.txt"]);
1571
1572        std::fs::remove_dir_all(&dir).ok();
1573    }
1574
1575    #[test]
1576    fn pane_mut_reaches_either_pane_regardless_of_which_is_active() {
1577        let mut panes = DualPane::new(PathBuf::from("/left"), PathBuf::from("/right"));
1578        assert_eq!(panes.active, PaneId::Left);
1579
1580        panes.pane_mut(PaneId::Right).cursor = 7;
1581        assert_eq!(panes.right.cursor, 7);
1582        assert_eq!(panes.left.cursor, 0);
1583    }
1584}