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    pub fn toggle_hidden_files(&mut self) {
595        self.left.toggle_hidden_files();
596        self.right.toggle_hidden_files();
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603
604    #[test]
605    fn visible_offset_leaves_a_cursor_already_in_view_alone() {
606        // Rows 10..14 are showing and the cursor is among them: not scrolling
607        // is what lets the cursor travel inside the viewport.
608        assert_eq!(visible_offset(10, 10, 5), 10);
609        assert_eq!(visible_offset(12, 10, 5), 10);
610        assert_eq!(visible_offset(14, 10, 5), 10);
611    }
612
613    #[test]
614    fn visible_offset_follows_a_cursor_above_the_viewport() {
615        assert_eq!(visible_offset(7, 10, 5), 7);
616        assert_eq!(visible_offset(0, 10, 5), 0);
617    }
618
619    #[test]
620    fn visible_offset_follows_a_cursor_below_the_viewport() {
621        // One past the last visible row scrolls by exactly one row.
622        assert_eq!(visible_offset(15, 10, 5), 11);
623        assert_eq!(visible_offset(20, 10, 5), 16);
624    }
625
626    #[test]
627    fn visible_offset_stays_at_zero_when_everything_fits() {
628        assert_eq!(visible_offset(0, 0, 50), 0);
629        assert_eq!(visible_offset(20, 0, 50), 0);
630    }
631
632    #[test]
633    fn visible_offset_survives_a_zero_row_viewport() {
634        // Nothing can be shown, so the best available answer is the cursor
635        // itself; the point is that it must not underflow.
636        assert_eq!(visible_offset(0, 0, 0), 0);
637        assert_eq!(visible_offset(3, 0, 0), 3);
638    }
639
640    #[test]
641    fn ensure_cursor_visible_scrolls_to_the_cursor() {
642        let mut pane = Pane::new(PathBuf::from("/tmp"));
643        pane.cursor = 30;
644        pane.ensure_cursor_visible(5);
645        assert_eq!(pane.scroll_offset, 26);
646
647        pane.cursor = 2;
648        pane.ensure_cursor_visible(5);
649        assert_eq!(pane.scroll_offset, 2);
650    }
651
652    #[test]
653    fn cursor_does_not_go_below_zero() {
654        let mut pane = Pane::new(PathBuf::from("/tmp"));
655        pane.move_cursor_up();
656        assert_eq!(pane.cursor, 0);
657    }
658
659    #[test]
660    fn hidden_files_are_hidden_by_default() {
661        let pane = Pane::new(PathBuf::from("/tmp"));
662        assert!(!pane.show_hidden);
663    }
664
665    #[test]
666    fn toggle_hidden_files_toggles_both_panes() {
667        let mut dp = DualPane::new("/".into(), "/tmp".into());
668
669        dp.toggle_hidden_files();
670
671        assert!(dp.left.show_hidden);
672        assert!(dp.right.show_hidden);
673
674        dp.toggle_hidden_files();
675
676        assert!(!dp.left.show_hidden);
677        assert!(!dp.right.show_hidden);
678    }
679
680    /// Entry names excluding the synthetic `..`, in listing order.
681    fn listed(pane: &Pane) -> Vec<&str> {
682        pane.entries
683            .iter()
684            .filter(|e| e.name != "..")
685            .map(|e| e.name.as_str())
686            .collect()
687    }
688
689    #[test]
690    fn cursor_does_not_exceed_entries() {
691        let mut pane = Pane::new(PathBuf::from("/tmp"));
692        pane.entries = vec![Entry {
693            name: "a".into(),
694            path: "/tmp/a".into(),
695            is_dir: false,
696            size: 0,
697            modified: None,
698        }];
699        pane.move_cursor_down();
700        pane.move_cursor_down();
701        assert_eq!(pane.cursor, 0);
702    }
703
704    #[test]
705    fn switch_active_toggles_pane() {
706        let mut dp = DualPane::new("/".into(), "/tmp".into());
707        assert_eq!(dp.active, PaneId::Left);
708        dp.switch_active();
709        assert_eq!(dp.active, PaneId::Right);
710        dp.switch_active();
711        assert_eq!(dp.active, PaneId::Left);
712    }
713
714    #[test]
715    fn load_entries_sorts_directories_first() {
716        let mut pane = Pane::new(std::env::temp_dir());
717        pane.load_entries();
718
719        // Verify structure: all dirs should come before all files
720        let mut found_file = false;
721        for entry in &pane.entries {
722            if !entry.is_dir {
723                found_file = true;
724            } else if found_file {
725                panic!("Found directory after file; sort order violated");
726            }
727        }
728
729        // Also verify alphabetical within each group
730        let mut prev_dir: Option<&str> = None;
731        for entry in &pane.entries {
732            if entry.is_dir {
733                if let Some(prev) = prev_dir {
734                    assert!(
735                        prev <= entry.name.as_str(),
736                        "Directories not sorted alphabetically"
737                    );
738                }
739                prev_dir = Some(&entry.name);
740            }
741        }
742    }
743
744    #[test]
745    fn enter_directory_changes_cwd() {
746        // Use a real temp directory for this test
747        let temp_dir = std::env::temp_dir();
748        let mut pane = Pane::new(temp_dir.clone());
749
750        // Create an entry pointing to a real directory
751        pane.entries = vec![Entry {
752            name: "test_entry".into(),
753            path: temp_dir.clone(),
754            is_dir: true,
755            size: 0,
756            modified: None,
757        }];
758        pane.cursor = 0;
759
760        pane.enter_directory();
761
762        // The cwd should update to the selected entry's path
763        assert_eq!(pane.cwd, temp_dir);
764    }
765
766    #[test]
767    fn goto_parent_navigates_up() {
768        let mut pane = Pane::new(PathBuf::from("/tmp/some/nested/path"));
769        let parent = pane.cwd.parent().unwrap().to_path_buf();
770
771        pane.goto_parent();
772
773        assert_eq!(pane.cwd, parent);
774    }
775
776    #[test]
777    fn goto_parent_at_root_does_nothing() {
778        let mut pane = Pane::new(PathBuf::from("/"));
779        let _original_cwd = pane.cwd.clone();
780
781        pane.goto_parent();
782
783        assert_eq!(pane.cwd, PathBuf::from("/"));
784    }
785
786    fn pane_with_entries(names: &[&str]) -> Pane {
787        let mut pane = Pane::new(PathBuf::from("/tmp"));
788        pane.entries = names
789            .iter()
790            .map(|n| Entry {
791                name: n.to_string(),
792                path: PathBuf::from(format!("/tmp/{n}")),
793                is_dir: false,
794                size: 0,
795                modified: None,
796            })
797            .collect();
798        pane
799    }
800
801    #[test]
802    fn toggle_selection_marks_and_unmarks() {
803        let mut pane = pane_with_entries(&["a", "b", "c"]);
804        pane.toggle_selection();
805        assert!(pane.selected.contains(&0));
806        pane.toggle_selection();
807        assert!(!pane.selected.contains(&0));
808    }
809
810    #[test]
811    fn toggle_selection_skips_parent_entry() {
812        let mut pane = Pane::new(PathBuf::from("/tmp"));
813        pane.entries = vec![Entry {
814            name: "..".into(),
815            path: "/".into(),
816            is_dir: true,
817            size: 0,
818            modified: None,
819        }];
820        pane.toggle_selection();
821        assert!(pane.selected.is_empty());
822    }
823
824    #[test]
825    fn effective_selection_returns_cursor_when_nothing_tagged() {
826        let mut pane = pane_with_entries(&["a", "b", "c"]);
827        pane.cursor = 2;
828        assert_eq!(pane.effective_selection(), vec![2]);
829    }
830
831    #[test]
832    fn effective_selection_returns_sorted_tagged_indices() {
833        let mut pane = pane_with_entries(&["a", "b", "c"]);
834        pane.selected.insert(2);
835        pane.selected.insert(0);
836        assert_eq!(pane.effective_selection(), vec![0, 2]);
837    }
838
839    #[test]
840    fn extend_selection_down_tags_current_and_advances_cursor() {
841        let mut pane = pane_with_entries(&["a", "b", "c"]);
842        pane.extend_selection_down();
843        assert!(pane.selected.contains(&0));
844        assert_eq!(pane.cursor, 1);
845    }
846
847    #[test]
848    fn extend_selection_up_tags_current_and_moves_cursor_up() {
849        let mut pane = pane_with_entries(&["a", "b", "c"]);
850        pane.cursor = 2;
851        pane.extend_selection_up();
852        assert!(pane.selected.contains(&2));
853        assert_eq!(pane.cursor, 1);
854    }
855
856    #[test]
857    fn load_entries_clears_selection() {
858        let mut pane = Pane::new(std::env::temp_dir());
859        pane.selected.insert(0);
860        pane.selected.insert(1);
861        pane.load_entries();
862        assert!(pane.selected.is_empty());
863    }
864
865    #[test]
866    fn jump_to_prefix_moves_cursor_to_match() {
867        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
868        assert!(pane.jump_to_prefix("ban"));
869        assert_eq!(pane.cursor, 1);
870    }
871
872    #[test]
873    fn jump_to_prefix_is_case_insensitive() {
874        let mut pane = pane_with_entries(&["Apple", "Banana", "Cherry"]);
875        assert!(pane.jump_to_prefix("cher"));
876        assert_eq!(pane.cursor, 2);
877    }
878
879    #[test]
880    fn jump_to_prefix_no_match_leaves_cursor_and_returns_false() {
881        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
882        pane.cursor = 1;
883        assert!(!pane.jump_to_prefix("zzz"));
884        assert_eq!(pane.cursor, 1);
885    }
886
887    #[test]
888    fn jump_to_prefix_skips_parent_entry() {
889        let mut pane = Pane::new(PathBuf::from("/tmp"));
890        pane.entries = vec![
891            Entry {
892                name: "..".into(),
893                path: "/".into(),
894                is_dir: true,
895                size: 0,
896                modified: None,
897            },
898            Entry {
899                name: "docs".into(),
900                path: "/tmp/docs".into(),
901                is_dir: true,
902                size: 0,
903                modified: None,
904            },
905        ];
906        pane.cursor = 1;
907        assert!(!pane.jump_to_prefix(".."));
908        assert_eq!(pane.cursor, 1);
909    }
910
911    #[test]
912    fn set_sort_key_changes_key_and_leaves_direction() {
913        let mut pane = Pane::new(std::env::temp_dir());
914        pane.sort_reversed = true;
915        pane.set_sort_key(SortKey::Size);
916        assert_eq!(pane.sort_key, SortKey::Size);
917        assert!(pane.sort_reversed);
918    }
919
920    #[test]
921    fn set_sort_key_toggles_direction_when_key_already_active() {
922        let mut pane = Pane::new(std::env::temp_dir());
923        assert_eq!(pane.sort_key, SortKey::Name);
924        assert!(!pane.sort_reversed);
925
926        pane.set_sort_key(SortKey::Name);
927        assert_eq!(pane.sort_key, SortKey::Name);
928        assert!(pane.sort_reversed);
929
930        pane.set_sort_key(SortKey::Name);
931        assert_eq!(pane.sort_key, SortKey::Name);
932        assert!(!pane.sort_reversed);
933    }
934
935    #[test]
936    fn set_sort_key_reorders_entries() {
937        let dir = std::env::temp_dir().join("oxinav_test_set_sort_key_reorders");
938        std::fs::create_dir_all(&dir).unwrap();
939        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
940        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
941
942        let mut pane = Pane::new(dir.clone());
943        pane.load_entries();
944        pane.set_sort_key(SortKey::Size);
945
946        let names: Vec<&str> = pane
947            .entries
948            .iter()
949            .filter(|e| e.name != "..")
950            .map(|e| e.name.as_str())
951            .collect();
952        assert_eq!(names, vec!["small.txt", "big.txt"]);
953
954        std::fs::remove_dir_all(&dir).ok();
955    }
956
957    #[test]
958    fn sorts_files_by_size() {
959        let dir = std::env::temp_dir().join("oxinav_test_sort_by_size");
960        std::fs::create_dir_all(&dir).unwrap();
961        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
962        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
963
964        let mut pane = Pane::new(dir.clone());
965        pane.sort_key = SortKey::Size;
966        pane.load_entries();
967
968        let names: Vec<&str> = pane
969            .entries
970            .iter()
971            .filter(|e| e.name != "..")
972            .map(|e| e.name.as_str())
973            .collect();
974        assert_eq!(names, vec!["small.txt", "big.txt"]);
975
976        std::fs::remove_dir_all(&dir).ok();
977    }
978
979    #[test]
980    fn sorts_files_reversed() {
981        let dir = std::env::temp_dir().join("oxinav_test_sort_reversed");
982        std::fs::create_dir_all(&dir).unwrap();
983        std::fs::write(dir.join("a.txt"), b"a").unwrap();
984        std::fs::write(dir.join("b.txt"), b"b").unwrap();
985
986        let mut pane = Pane::new(dir.clone());
987        pane.sort_reversed = true;
988        pane.load_entries();
989
990        let names: Vec<&str> = pane
991            .entries
992            .iter()
993            .filter(|e| e.name != "..")
994            .map(|e| e.name.as_str())
995            .collect();
996        assert_eq!(names, vec!["b.txt", "a.txt"]);
997
998        std::fs::remove_dir_all(&dir).ok();
999    }
1000
1001    // --- filtering ---
1002
1003    #[test]
1004    fn bare_pattern_matches_as_a_substring() {
1005        assert!(matches_filter("Cargo.toml", "cargo"));
1006        assert!(matches_filter("main.rs", ".rs"));
1007        assert!(!matches_filter("main.rs", "toml"));
1008    }
1009
1010    #[test]
1011    fn wildcard_pattern_matches_as_a_glob_over_the_whole_name() {
1012        assert!(matches_filter("main.rs", "*.rs"));
1013        assert!(!matches_filter("main.rsx", "*.rs"));
1014        assert!(matches_filter("Cargo.toml", "cargo*"));
1015        assert!(!matches_filter("build.rs", "cargo*"));
1016    }
1017
1018    #[test]
1019    fn question_mark_matches_exactly_one_character() {
1020        assert!(matches_filter("a.rs", "?.rs"));
1021        assert!(!matches_filter("ab.rs", "?.rs"));
1022    }
1023
1024    #[test]
1025    fn matching_ignores_case_in_both_modes() {
1026        assert!(matches_filter("README.MD", "readme"));
1027        assert!(matches_filter("README.MD", "*.md"));
1028    }
1029
1030    #[test]
1031    fn blank_pattern_matches_everything() {
1032        assert!(matches_filter("anything", ""));
1033        assert!(matches_filter("anything", "   "));
1034    }
1035
1036    #[test]
1037    fn consecutive_stars_do_not_change_the_match() {
1038        assert!(matches_filter("main.rs", "**.rs"));
1039        assert!(matches_filter("main.rs", "*"));
1040    }
1041
1042    #[test]
1043    fn set_filter_narrows_the_listing_and_clear_restores_it() {
1044        let dir = std::env::temp_dir().join("oxinav_test_filter_narrows");
1045        std::fs::remove_dir_all(&dir).ok();
1046        std::fs::create_dir_all(&dir).unwrap();
1047        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1048        std::fs::write(dir.join("lib.rs"), b"b").unwrap();
1049        std::fs::write(dir.join("Cargo.toml"), b"c").unwrap();
1050
1051        let mut pane = Pane::new(dir.clone());
1052        pane.load_entries();
1053        pane.set_filter("*.rs");
1054
1055        let names = listed(&pane);
1056        assert_eq!(names, vec!["lib.rs", "main.rs"]);
1057
1058        pane.clear_filter();
1059        assert_eq!(listed(&pane), vec!["Cargo.toml", "lib.rs", "main.rs"]);
1060
1061        std::fs::remove_dir_all(&dir).ok();
1062    }
1063
1064    #[test]
1065    fn parent_entry_survives_a_filter_matching_nothing() {
1066        let dir = std::env::temp_dir().join("oxinav_test_filter_keeps_parent");
1067        std::fs::remove_dir_all(&dir).ok();
1068        std::fs::create_dir_all(&dir).unwrap();
1069        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1070
1071        let mut pane = Pane::new(dir.clone());
1072        pane.load_entries();
1073        pane.set_filter("*.nomatch");
1074
1075        assert!(listed(&pane).is_empty());
1076        // `..` is the only thing left, so navigating up is still possible.
1077        let all: Vec<&str> = pane.entries.iter().map(|e| e.name.as_str()).collect();
1078        assert_eq!(all, vec![".."]);
1079
1080        std::fs::remove_dir_all(&dir).ok();
1081    }
1082
1083    #[test]
1084    fn filter_composes_with_the_hidden_files_toggle() {
1085        let dir = std::env::temp_dir().join("oxinav_test_filter_hidden");
1086        std::fs::remove_dir_all(&dir).ok();
1087        std::fs::create_dir_all(&dir).unwrap();
1088        std::fs::write(dir.join("visible.rs"), b"a").unwrap();
1089        std::fs::write(dir.join(".hidden.rs"), b"b").unwrap();
1090
1091        let mut pane = Pane::new(dir.clone());
1092        pane.load_entries();
1093        pane.set_filter("*.rs");
1094        assert_eq!(listed(&pane), vec!["visible.rs"]);
1095
1096        // Revealing hidden files widens the set the filter then narrows.
1097        pane.toggle_hidden_files();
1098        assert_eq!(listed(&pane), vec![".hidden.rs", "visible.rs"]);
1099
1100        std::fs::remove_dir_all(&dir).ok();
1101    }
1102
1103    #[test]
1104    fn filter_composes_with_the_active_sort_key() {
1105        let dir = std::env::temp_dir().join("oxinav_test_filter_sort");
1106        std::fs::remove_dir_all(&dir).ok();
1107        std::fs::create_dir_all(&dir).unwrap();
1108        std::fs::write(dir.join("big.rs"), vec![0u8; 100]).unwrap();
1109        std::fs::write(dir.join("small.rs"), vec![0u8; 10]).unwrap();
1110        std::fs::write(dir.join("huge.toml"), vec![0u8; 999]).unwrap();
1111
1112        let mut pane = Pane::new(dir.clone());
1113        pane.load_entries();
1114        pane.set_filter("*.rs");
1115        pane.set_sort_key(SortKey::Size);
1116
1117        // Sorted by size, and the excluded .toml stays excluded.
1118        assert_eq!(listed(&pane), vec!["small.rs", "big.rs"]);
1119
1120        std::fs::remove_dir_all(&dir).ok();
1121    }
1122
1123    #[test]
1124    fn filter_applies_to_directories_too() {
1125        let dir = std::env::temp_dir().join("oxinav_test_filter_dirs");
1126        std::fs::remove_dir_all(&dir).ok();
1127        std::fs::create_dir_all(dir.join("src")).unwrap();
1128        std::fs::create_dir_all(dir.join("target")).unwrap();
1129        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1130
1131        let mut pane = Pane::new(dir.clone());
1132        pane.load_entries();
1133        pane.set_filter("*.rs");
1134
1135        assert_eq!(listed(&pane), vec!["main.rs"]);
1136
1137        std::fs::remove_dir_all(&dir).ok();
1138    }
1139
1140    #[test]
1141    fn refiltering_does_not_re_read_the_directory() {
1142        let dir = std::env::temp_dir().join("oxinav_test_filter_no_reread");
1143        std::fs::remove_dir_all(&dir).ok();
1144        std::fs::create_dir_all(&dir).unwrap();
1145        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1146        std::fs::write(dir.join("notes.txt"), b"b").unwrap();
1147
1148        let mut pane = Pane::new(dir.clone());
1149        pane.load_entries();
1150
1151        // Delete the directory out from under the pane. Re-filtering now can
1152        // only succeed if it works off the cached read, which is what makes
1153        // it cheap enough to run on every keystroke.
1154        std::fs::remove_dir_all(&dir).ok();
1155
1156        pane.set_filter("*.rs");
1157        assert_eq!(listed(&pane), vec!["main.rs"]);
1158
1159        pane.clear_filter();
1160        assert_eq!(listed(&pane), vec!["main.rs", "notes.txt"]);
1161    }
1162
1163    // --- directory history ---
1164
1165    #[test]
1166    fn back_returns_to_the_previous_directory() {
1167        let mut pane = Pane::new(PathBuf::from("/a"));
1168        pane.navigate_to(PathBuf::from("/b"));
1169        assert_eq!(pane.cwd, PathBuf::from("/b"));
1170
1171        assert!(pane.go_back());
1172        assert_eq!(pane.cwd, PathBuf::from("/a"));
1173    }
1174
1175    #[test]
1176    fn forward_returns_after_going_back() {
1177        let mut pane = Pane::new(PathBuf::from("/a"));
1178        pane.navigate_to(PathBuf::from("/b"));
1179        pane.go_back();
1180
1181        assert!(pane.go_forward());
1182        assert_eq!(pane.cwd, PathBuf::from("/b"));
1183    }
1184
1185    #[test]
1186    fn navigating_anew_truncates_the_forward_tail() {
1187        let mut pane = Pane::new(PathBuf::from("/a"));
1188        pane.navigate_to(PathBuf::from("/b"));
1189        pane.go_back();
1190        // Branching from A to C makes B unreachable.
1191        pane.navigate_to(PathBuf::from("/c"));
1192
1193        assert!(!pane.can_go_forward());
1194        assert!(!pane.go_forward());
1195        assert_eq!(pane.cwd, PathBuf::from("/c"));
1196
1197        // Back now leads to A, not B.
1198        assert!(pane.go_back());
1199        assert_eq!(pane.cwd, PathBuf::from("/a"));
1200    }
1201
1202    #[test]
1203    fn back_at_the_start_of_history_does_nothing() {
1204        let mut pane = Pane::new(PathBuf::from("/a"));
1205
1206        assert!(!pane.can_go_back());
1207        assert!(!pane.go_back());
1208        assert_eq!(pane.cwd, PathBuf::from("/a"));
1209    }
1210
1211    #[test]
1212    fn forward_without_going_back_does_nothing() {
1213        let mut pane = Pane::new(PathBuf::from("/a"));
1214        pane.navigate_to(PathBuf::from("/b"));
1215
1216        assert!(!pane.can_go_forward());
1217        assert!(!pane.go_forward());
1218        assert_eq!(pane.cwd, PathBuf::from("/b"));
1219    }
1220
1221    #[test]
1222    fn navigating_to_the_current_directory_is_not_recorded() {
1223        let mut pane = Pane::new(PathBuf::from("/a"));
1224        pane.navigate_to(PathBuf::from("/a"));
1225
1226        // Re-entering where we already are must not create a history step
1227        // that back would then have to walk through.
1228        assert!(!pane.can_go_back());
1229    }
1230
1231    #[test]
1232    fn history_survives_several_steps_in_both_directions() {
1233        let mut pane = Pane::new(PathBuf::from("/a"));
1234        pane.navigate_to(PathBuf::from("/b"));
1235        pane.navigate_to(PathBuf::from("/c"));
1236
1237        assert!(pane.go_back());
1238        assert!(pane.go_back());
1239        assert_eq!(pane.cwd, PathBuf::from("/a"));
1240
1241        assert!(pane.go_forward());
1242        assert!(pane.go_forward());
1243        assert_eq!(pane.cwd, PathBuf::from("/c"));
1244    }
1245
1246    #[test]
1247    fn history_is_per_pane() {
1248        let mut dp = DualPane::new("/left".into(), "/right".into());
1249        dp.left.navigate_to(PathBuf::from("/left/sub"));
1250
1251        assert!(dp.left.can_go_back());
1252        assert!(!dp.right.can_go_back());
1253    }
1254
1255    #[test]
1256    fn set_filter_with_a_blank_pattern_clears_it() {
1257        let mut pane = Pane::new(std::env::temp_dir());
1258        pane.set_filter("*.rs");
1259        assert!(pane.filter.is_some());
1260
1261        pane.set_filter("   ");
1262        assert!(pane.filter.is_none());
1263    }
1264
1265    #[test]
1266    fn directories_stay_name_sorted_regardless_of_sort_key() {
1267        let dir = std::env::temp_dir().join("oxinav_test_sort_dirs_stable");
1268        std::fs::create_dir_all(dir.join("b_dir")).unwrap();
1269        std::fs::create_dir_all(dir.join("a_dir")).unwrap();
1270
1271        let mut pane = Pane::new(dir.clone());
1272        pane.sort_key = SortKey::Size;
1273        pane.load_entries();
1274
1275        let names: Vec<&str> = pane
1276            .entries
1277            .iter()
1278            .filter(|e| e.name != "..")
1279            .map(|e| e.name.as_str())
1280            .collect();
1281        assert_eq!(names, vec!["a_dir", "b_dir"]);
1282
1283        std::fs::remove_dir_all(&dir).ok();
1284    }
1285
1286    #[test]
1287    fn sort_key_labels_round_trip() {
1288        for key in [SortKey::Name, SortKey::Size, SortKey::Modified] {
1289            assert_eq!(SortKey::from_label(key.label()), Some(key));
1290        }
1291    }
1292
1293    #[test]
1294    fn sort_key_from_label_ignores_case_and_padding() {
1295        assert_eq!(SortKey::from_label(" Modified "), Some(SortKey::Modified));
1296    }
1297
1298    #[test]
1299    fn sort_key_from_label_is_none_for_an_unknown_word() {
1300        assert_eq!(SortKey::from_label("colour"), None);
1301        assert_eq!(SortKey::from_label(""), None);
1302    }
1303    // --- refreshing after an external change ---
1304
1305    /// The refresh tests need a real directory they can mutate behind the
1306    /// pane's back, which is what an external change *is*.
1307    fn refresh_scratch(name: &str) -> PathBuf {
1308        let dir = std::env::temp_dir().join(format!("oxinav_test_refresh_{name}"));
1309        std::fs::remove_dir_all(&dir).ok();
1310        std::fs::create_dir_all(&dir).unwrap();
1311        dir
1312    }
1313
1314    fn visible_names(pane: &Pane) -> Vec<&str> {
1315        pane.entries
1316            .iter()
1317            .filter(|e| e.name != "..")
1318            .map(|e| e.name.as_str())
1319            .collect()
1320    }
1321
1322    fn tagged_names(pane: &Pane) -> Vec<&str> {
1323        let mut names: Vec<&str> = pane
1324            .selected
1325            .iter()
1326            .map(|&i| pane.entries[i].name.as_str())
1327            .collect();
1328        names.sort_unstable();
1329        names
1330    }
1331
1332    #[test]
1333    fn refresh_shows_an_externally_created_file_and_keeps_the_cursor() {
1334        let dir = refresh_scratch("create");
1335        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1336        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1337
1338        let mut pane = Pane::new(dir.clone());
1339        pane.load_entries();
1340        // ["..", "a.txt", "c.txt"] — park on c.txt.
1341        pane.cursor = 2;
1342        assert_eq!(pane.entries[pane.cursor].name, "c.txt");
1343
1344        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1345        pane.reload_preserving_view();
1346
1347        assert_eq!(visible_names(&pane), vec!["a.txt", "b.txt", "c.txt"]);
1348        // b.txt pushed c.txt down a row; the cursor followed the file.
1349        assert_eq!(pane.cursor, 3);
1350        assert_eq!(pane.entries[pane.cursor].name, "c.txt");
1351
1352        std::fs::remove_dir_all(&dir).ok();
1353    }
1354
1355    #[test]
1356    fn refresh_keeps_tags_on_their_files_when_a_row_is_inserted_above() {
1357        let dir = refresh_scratch("insert_above");
1358        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1359        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1360
1361        let mut pane = Pane::new(dir.clone());
1362        pane.load_entries();
1363        // ["..", "b.txt", "c.txt"]
1364        pane.selected.insert(1);
1365        pane.selected.insert(2);
1366
1367        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1368        pane.reload_preserving_view();
1369
1370        // Had the indices been preserved, a.txt would now be tagged and
1371        // c.txt would not.
1372        assert_eq!(tagged_names(&pane), vec!["b.txt", "c.txt"]);
1373
1374        std::fs::remove_dir_all(&dir).ok();
1375    }
1376
1377    #[test]
1378    fn refresh_drops_a_tagged_file_that_was_deleted_externally() {
1379        let dir = refresh_scratch("delete_tagged");
1380        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1381        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1382        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1383
1384        let mut pane = Pane::new(dir.clone());
1385        pane.load_entries();
1386        // ["..", "a.txt", "b.txt", "c.txt"]
1387        pane.selected.insert(1);
1388        pane.selected.insert(3);
1389
1390        std::fs::remove_file(dir.join("a.txt")).unwrap();
1391        pane.reload_preserving_view();
1392
1393        assert_eq!(visible_names(&pane), vec!["b.txt", "c.txt"]);
1394        assert_eq!(tagged_names(&pane), vec!["c.txt"]);
1395
1396        std::fs::remove_dir_all(&dir).ok();
1397    }
1398
1399    #[test]
1400    fn refresh_clamps_the_cursor_when_its_file_is_deleted() {
1401        let dir = refresh_scratch("delete_cursor");
1402        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1403        std::fs::write(dir.join("b.txt"), b"b").unwrap();
1404        std::fs::write(dir.join("c.txt"), b"c").unwrap();
1405
1406        let mut pane = Pane::new(dir.clone());
1407        pane.load_entries();
1408        pane.cursor = 2;
1409        assert_eq!(pane.entries[pane.cursor].name, "b.txt");
1410
1411        std::fs::remove_file(dir.join("b.txt")).unwrap();
1412        pane.reload_preserving_view();
1413
1414        // Row held, not reset to 0: the cursor sits on what took b.txt's place.
1415        assert_eq!(pane.cursor, 2);
1416        assert_eq!(pane.entries[pane.cursor].name, "c.txt");
1417
1418        // And clamps rather than dangling when the tail is gone too.
1419        std::fs::remove_file(dir.join("c.txt")).unwrap();
1420        pane.reload_preserving_view();
1421        assert_eq!(pane.cursor, 1);
1422        assert_eq!(pane.entries[pane.cursor].name, "a.txt");
1423
1424        std::fs::remove_dir_all(&dir).ok();
1425    }
1426
1427    #[test]
1428    fn refresh_keeps_hidden_files_hidden() {
1429        let dir = refresh_scratch("hidden");
1430        std::fs::write(dir.join("a.txt"), b"a").unwrap();
1431
1432        let mut pane = Pane::new(dir.clone());
1433        pane.load_entries();
1434
1435        std::fs::write(dir.join(".secret"), b"s").unwrap();
1436        pane.reload_preserving_view();
1437        assert_eq!(visible_names(&pane), vec!["a.txt"]);
1438
1439        pane.toggle_hidden_files();
1440        assert_eq!(visible_names(&pane), vec![".secret", "a.txt"]);
1441
1442        std::fs::remove_dir_all(&dir).ok();
1443    }
1444
1445    #[test]
1446    fn refresh_applies_the_active_filter_and_sort_key() {
1447        let dir = refresh_scratch("filter_sort");
1448        std::fs::write(dir.join("keep_big.log"), vec![0u8; 100]).unwrap();
1449        std::fs::write(dir.join("keep_small.log"), vec![0u8; 10]).unwrap();
1450        std::fs::write(dir.join("other.txt"), b"x").unwrap();
1451
1452        let mut pane = Pane::new(dir.clone());
1453        pane.sort_key = SortKey::Size;
1454        pane.load_entries();
1455        pane.set_filter(".log");
1456        assert_eq!(visible_names(&pane), vec!["keep_small.log", "keep_big.log"]);
1457
1458        std::fs::write(dir.join("keep_mid.log"), vec![0u8; 50]).unwrap();
1459        std::fs::write(dir.join("ignored.txt"), b"y").unwrap();
1460        pane.reload_preserving_view();
1461
1462        assert_eq!(
1463            visible_names(&pane),
1464            vec!["keep_small.log", "keep_mid.log", "keep_big.log"]
1465        );
1466
1467        std::fs::remove_dir_all(&dir).ok();
1468    }
1469
1470    #[test]
1471    fn refresh_of_an_unchanged_directory_changes_nothing() {
1472        let dir = refresh_scratch("unchanged");
1473        for name in ["a.txt", "b.txt", "c.txt", "d.txt"] {
1474            std::fs::write(dir.join(name), b"x").unwrap();
1475        }
1476
1477        let mut pane = Pane::new(dir.clone());
1478        pane.load_entries();
1479        pane.cursor = 3;
1480        pane.scroll_offset = 2;
1481        pane.selected.insert(1);
1482        pane.selected.insert(4);
1483        let before = pane.entries.clone();
1484
1485        pane.reload_preserving_view();
1486
1487        assert_eq!(pane.entries, before);
1488        assert_eq!(pane.cursor, 3);
1489        assert_eq!(pane.scroll_offset, 2);
1490        assert_eq!(tagged_names(&pane), vec!["a.txt", "d.txt"]);
1491
1492        std::fs::remove_dir_all(&dir).ok();
1493    }
1494
1495    #[test]
1496    fn pane_mut_reaches_either_pane_regardless_of_which_is_active() {
1497        let mut panes = DualPane::new(PathBuf::from("/left"), PathBuf::from("/right"));
1498        assert_eq!(panes.active, PaneId::Left);
1499
1500        panes.pane_mut(PaneId::Right).cursor = 7;
1501        assert_eq!(panes.right.cursor, 7);
1502        assert_eq!(panes.left.cursor, 0);
1503    }
1504}