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
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum PaneId {
36    Left,
37    Right,
38}
39
40impl PaneId {
41    pub fn other(self) -> Self {
42        match self {
43            PaneId::Left => PaneId::Right,
44            PaneId::Right => PaneId::Left,
45        }
46    }
47}
48
49/// Whether `name` satisfies the listing filter `pattern`.
50///
51/// A pattern holding `*` or `?` is matched as a glob against the whole name;
52/// one holding neither is matched as a substring, since a bare word like
53/// `cargo` is nearly always meant as "names containing this" rather than as
54/// an exact name. Both modes ignore case.
55pub fn matches_filter(name: &str, pattern: &str) -> bool {
56    let pattern = pattern.trim();
57    if pattern.is_empty() {
58        return true;
59    }
60
61    let name = name.to_lowercase();
62    let pattern = pattern.to_lowercase();
63
64    if pattern.contains(['*', '?']) {
65        glob_match(&name, &pattern)
66    } else {
67        name.contains(&pattern)
68    }
69}
70
71/// Two-pointer wildcard match: `*` spans any run of characters, `?` exactly
72/// one. On a mismatch it backtracks to the last `*` and gives it one more
73/// character, so no recursion is involved and a pathological pattern cannot
74/// blow the stack. Both inputs are expected to be lowercased already.
75fn glob_match(name: &str, pattern: &str) -> bool {
76    let name: Vec<char> = name.chars().collect();
77    let pattern: Vec<char> = pattern.chars().collect();
78
79    let (mut n, mut p) = (0, 0);
80    let mut star: Option<usize> = None;
81    let mut resume = 0;
82
83    while n < name.len() {
84        match pattern.get(p) {
85            Some('*') => {
86                star = Some(p);
87                resume = n;
88                p += 1;
89            }
90            Some('?') => {
91                p += 1;
92                n += 1;
93            }
94            Some(c) if *c == name[n] => {
95                p += 1;
96                n += 1;
97            }
98            _ => match star {
99                Some(s) => {
100                    p = s + 1;
101                    resume += 1;
102                    n = resume;
103                }
104                None => return false,
105            },
106        }
107    }
108
109    // Whatever is left of the pattern can only still match the empty
110    // remainder if it is nothing but `*`.
111    pattern[p..].iter().all(|c| *c == '*')
112}
113
114#[derive(Debug, Clone)]
115pub struct Pane {
116    pub cwd: PathBuf,
117    pub entries: Vec<Entry>,
118    pub cursor: usize,
119    pub scroll_offset: usize,
120    pub show_hidden: bool,
121    pub selected: HashSet<usize>,
122    pub sort_key: SortKey,
123    pub sort_reversed: bool,
124    /// Name filter narrowing the listing; `None` lists everything.
125    pub filter: Option<String>,
126    /// Every entry read from `cwd`, before the hidden-file rule and the
127    /// filter narrow it. Kept so that re-deriving the listing — which an
128    /// inline filter does on every keystroke — never touches the disk again.
129    all_entries: Vec<Entry>,
130    /// Directories this pane has visited, oldest first. Always non-empty:
131    /// `history[history_index]` is the current `cwd`.
132    history: Vec<PathBuf>,
133    /// Position within `history`; everything after it is forward history.
134    history_index: usize,
135}
136
137impl Pane {
138    pub fn new(cwd: PathBuf) -> Self {
139        Self {
140            history: vec![cwd.clone()],
141            history_index: 0,
142            cwd,
143            entries: Vec::new(),
144            cursor: 0,
145            scroll_offset: 0,
146            show_hidden: false,
147            selected: HashSet::new(),
148            sort_key: SortKey::Name,
149            sort_reversed: false,
150            filter: None,
151            all_entries: Vec::new(),
152        }
153    }
154
155    /// Move to `path`, recording it in history.
156    ///
157    /// Navigating somewhere new after going back discards the forward tail:
158    /// the branch not taken is no longer reachable, which is how every
159    /// back/forward stack behaves.
160    pub fn navigate_to(&mut self, path: PathBuf) {
161        if path == self.cwd {
162            return;
163        }
164        self.history.truncate(self.history_index + 1);
165        self.history.push(path.clone());
166        self.history_index = self.history.len() - 1;
167        self.cwd = path;
168        self.load_entries();
169    }
170
171    /// Step back to the previously visited directory. Returns whether there
172    /// was anywhere to go.
173    pub fn go_back(&mut self) -> bool {
174        if self.history_index == 0 {
175            return false;
176        }
177        self.history_index -= 1;
178        self.cwd = self.history[self.history_index].clone();
179        self.load_entries();
180        true
181    }
182
183    /// Step forward again after going back.
184    pub fn go_forward(&mut self) -> bool {
185        if self.history_index + 1 >= self.history.len() {
186            return false;
187        }
188        self.history_index += 1;
189        self.cwd = self.history[self.history_index].clone();
190        self.load_entries();
191        true
192    }
193
194    pub fn can_go_back(&self) -> bool {
195        self.history_index > 0
196    }
197
198    pub fn can_go_forward(&self) -> bool {
199        self.history_index + 1 < self.history.len()
200    }
201
202    /// Sets the sort key directly. If the requested key is already active,
203    /// toggles the sort direction instead (the "press again to reverse"
204    /// convention used by clickable column headers).
205    pub fn set_sort_key(&mut self, key: SortKey) {
206        if self.sort_key == key {
207            self.sort_reversed = !self.sort_reversed;
208        } else {
209            self.sort_key = key;
210        }
211        self.apply_view();
212    }
213
214    pub fn toggle_hidden_files(&mut self) {
215        self.show_hidden = !self.show_hidden;
216        self.apply_view();
217    }
218
219    /// Sets the name filter, or clears it when `pattern` is blank — so
220    /// submitting an empty prompt is the same as clearing.
221    pub fn set_filter(&mut self, pattern: &str) {
222        let pattern = pattern.trim();
223        self.filter = if pattern.is_empty() {
224            None
225        } else {
226            Some(pattern.to_string())
227        };
228        self.apply_view();
229    }
230
231    pub fn clear_filter(&mut self) {
232        self.filter = None;
233        self.apply_view();
234    }
235
236    pub fn move_cursor_up(&mut self) {
237        if self.cursor > 0 {
238            self.cursor -= 1;
239            if self.cursor < self.scroll_offset {
240                self.scroll_offset = self.cursor;
241            }
242        }
243    }
244
245    pub fn move_cursor_down(&mut self) {
246        if !self.entries.is_empty() && self.cursor < self.entries.len() - 1 {
247            self.cursor += 1;
248            // Ensure cursor is within visible range; keep it centered by keeping 5 items below
249            const VISIBLE_ITEMS: usize = 20;
250            const KEEP_BELOW: usize = 5;
251            if self.cursor >= self.scroll_offset + VISIBLE_ITEMS - KEEP_BELOW {
252                self.scroll_offset = self.cursor.saturating_sub(VISIBLE_ITEMS - KEEP_BELOW - 1);
253            }
254        }
255    }
256
257    /// Keep the cursor in the visible viewport (for when viewport size changes or entries are reloaded)
258    pub fn ensure_cursor_visible(&mut self, visible_items: usize) {
259        if self.cursor < self.scroll_offset {
260            self.scroll_offset = self.cursor;
261        } else if self.cursor >= self.scroll_offset + visible_items {
262            self.scroll_offset = self.cursor.saturating_sub(visible_items - 1);
263        }
264    }
265
266    pub fn selected(&self) -> Option<&Entry> {
267        self.entries.get(self.cursor)
268    }
269
270    pub fn toggle_selection(&mut self) {
271        if self.entries.get(self.cursor).map_or(true, |e| e.name == "..") {
272            return;
273        }
274        if !self.selected.remove(&self.cursor) {
275            self.selected.insert(self.cursor);
276        }
277    }
278
279    pub fn extend_selection_down(&mut self) {
280        if self.entries.get(self.cursor).map_or(false, |e| e.name != "..") {
281            self.selected.insert(self.cursor);
282        }
283        self.move_cursor_down();
284    }
285
286    pub fn extend_selection_up(&mut self) {
287        if self.entries.get(self.cursor).map_or(false, |e| e.name != "..") {
288            self.selected.insert(self.cursor);
289        }
290        self.move_cursor_up();
291    }
292
293    pub fn clear_selection(&mut self) {
294        self.selected.clear();
295    }
296
297    /// Move the cursor to the first entry (other than "..") whose name starts with
298    /// `query`, case-insensitively. Leaves the cursor untouched if nothing matches.
299    /// Returns whether a match was found.
300    pub fn jump_to_prefix(&mut self, query: &str) -> bool {
301        if query.is_empty() {
302            return false;
303        }
304        let query = query.to_lowercase();
305        match self
306            .entries
307            .iter()
308            .position(|e| e.name != ".." && e.name.to_lowercase().starts_with(&query))
309        {
310            Some(index) => {
311                self.cursor = index;
312                true
313            }
314            None => false,
315        }
316    }
317
318    /// Returns the tagged indices (sorted), or `[cursor]` if nothing is tagged.
319    pub fn effective_selection(&self) -> Vec<usize> {
320        if self.selected.is_empty() {
321            vec![self.cursor]
322        } else {
323            let mut indices: Vec<usize> = self.selected.iter().copied().collect();
324            indices.sort_unstable();
325            indices
326        }
327    }
328
329    /// Load entries from the current working directory.
330    /// Read `cwd` from disk into the entry cache, then derive the listing.
331    /// The read is the expensive half, so anything that only changes *how*
332    /// entries are presented — sort, hidden files, the filter — goes through
333    /// `apply_view` instead of coming back here.
334    pub fn load_entries(&mut self) {
335        self.all_entries.clear();
336
337        // An unreadable directory yields an empty listing rather than an error.
338        if let Ok(entries_iter) = std::fs::read_dir(&self.cwd) {
339            for entry_result in entries_iter {
340                let Ok(entry) = entry_result else {
341                    continue;
342                };
343                let file_name = entry.file_name();
344                let name = file_name.to_string_lossy().to_string();
345
346                // Skip "." but don't skip ".."
347                if name == "." {
348                    continue;
349                }
350
351                let path = entry.path();
352                let metadata = entry.metadata().ok();
353                let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
354                let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
355                let modified = metadata.as_ref().and_then(|m| m.modified().ok());
356
357                self.all_entries.push(Entry {
358                    name,
359                    path,
360                    is_dir,
361                    size,
362                    modified,
363                });
364            }
365        }
366
367        self.apply_view();
368    }
369
370    /// Rebuild the visible listing from the cached read: drop hidden files,
371    /// apply the filter, sort directories-then-files, and prepend the
372    /// synthetic `..`. Touches no I/O, so it is cheap enough to run on every
373    /// keystroke of an inline filter.
374    ///
375    /// Sorts directories first (alphabetical), then files by the active sort
376    /// key. Excludes "." but includes ".." (parent directory) if not at root.
377    fn apply_view(&mut self) {
378        self.entries.clear();
379        self.cursor = 0;
380        self.scroll_offset = 0;
381        self.selected.clear();
382
383        let mut dirs: Vec<Entry> = Vec::new();
384        let mut files: Vec<Entry> = Vec::new();
385
386        for entry in &self.all_entries {
387            if !self.show_hidden && entry.name.starts_with('.') {
388                continue;
389            }
390
391            // Narrows what is listed, on top of the hidden-file rule above and
392            // the sort below. `..` is prepended further down, so it is never
393            // subject to this.
394            if let Some(pattern) = &self.filter {
395                if !matches_filter(&entry.name, pattern) {
396                    continue;
397                }
398            }
399
400            if entry.is_dir {
401                dirs.push(entry.clone());
402            } else {
403                files.push(entry.clone());
404            }
405        }
406
407        // Directories are always sorted by name; size/modified aren't
408        // meaningful for a directory without a recursive scan.
409        dirs.sort_by(|a, b| a.name.cmp(&b.name));
410
411        match self.sort_key {
412            SortKey::Name => files.sort_by(|a, b| a.name.cmp(&b.name)),
413            SortKey::Size => files.sort_by_key(|f| f.size),
414            SortKey::Modified => files.sort_by_key(|f| f.modified),
415        }
416        if self.sort_reversed {
417            files.reverse();
418        }
419
420        // Add ".." first if not at root
421        if let Some(parent) = self.cwd.parent() {
422            self.entries.push(Entry {
423                name: "..".to_string(),
424                path: parent.to_path_buf(),
425                is_dir: true,
426                size: 0,
427                modified: None,
428            });
429        }
430
431        // Combine: directories, then files
432        self.entries.extend(dirs);
433        self.entries.extend(files);
434    }
435
436    /// Enter the selected directory. If selection is not a directory, does nothing.
437    pub fn enter_directory(&mut self) {
438        if let Some(entry) = self.selected() {
439            if entry.is_dir {
440                let target = entry.path.clone();
441                self.navigate_to(target);
442            }
443        }
444    }
445
446    /// Navigate to the parent directory. Does nothing if already at root.
447    pub fn goto_parent(&mut self) {
448        if let Some(parent) = self.cwd.parent() {
449            let target = parent.to_path_buf();
450            self.navigate_to(target);
451        }
452    }
453}
454
455#[derive(Debug, Clone)]
456pub struct DualPane {
457    pub left: Pane,
458    pub right: Pane,
459    pub active: PaneId,
460}
461
462impl DualPane {
463    pub fn new(left_cwd: PathBuf, right_cwd: PathBuf) -> Self {
464        Self {
465            left: Pane::new(left_cwd),
466            right: Pane::new(right_cwd),
467            active: PaneId::Left,
468        }
469    }
470
471    pub fn active_pane(&self) -> &Pane {
472        match self.active {
473            PaneId::Left => &self.left,
474            PaneId::Right => &self.right,
475        }
476    }
477
478    pub fn active_pane_mut(&mut self) -> &mut Pane {
479        match self.active {
480            PaneId::Left => &mut self.left,
481            PaneId::Right => &mut self.right,
482        }
483    }
484
485    pub fn switch_active(&mut self) {
486        self.active = self.active.other();
487    }
488
489    pub fn toggle_hidden_files(&mut self) {
490        self.left.toggle_hidden_files();
491        self.right.toggle_hidden_files();
492    }
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    #[test]
500    fn cursor_does_not_go_below_zero() {
501        let mut pane = Pane::new(PathBuf::from("/tmp"));
502        pane.move_cursor_up();
503        assert_eq!(pane.cursor, 0);
504    }
505
506    #[test]
507    fn hidden_files_are_hidden_by_default() {
508        let pane = Pane::new(PathBuf::from("/tmp"));
509        assert!(!pane.show_hidden);
510    }
511
512    #[test]
513    fn toggle_hidden_files_toggles_both_panes() {
514        let mut dp = DualPane::new("/".into(), "/tmp".into());
515
516        dp.toggle_hidden_files();
517
518        assert!(dp.left.show_hidden);
519        assert!(dp.right.show_hidden);
520
521        dp.toggle_hidden_files();
522
523        assert!(!dp.left.show_hidden);
524        assert!(!dp.right.show_hidden);
525    }
526
527    /// Entry names excluding the synthetic `..`, in listing order.
528    fn listed(pane: &Pane) -> Vec<&str> {
529        pane.entries
530            .iter()
531            .filter(|e| e.name != "..")
532            .map(|e| e.name.as_str())
533            .collect()
534    }
535
536    #[test]
537    fn cursor_does_not_exceed_entries() {
538        let mut pane = Pane::new(PathBuf::from("/tmp"));
539        pane.entries = vec![Entry {
540            name: "a".into(),
541            path: "/tmp/a".into(),
542            is_dir: false,
543            size: 0,
544            modified: None,
545        }];
546        pane.move_cursor_down();
547        pane.move_cursor_down();
548        assert_eq!(pane.cursor, 0);
549    }
550
551    #[test]
552    fn switch_active_toggles_pane() {
553        let mut dp = DualPane::new("/".into(), "/tmp".into());
554        assert_eq!(dp.active, PaneId::Left);
555        dp.switch_active();
556        assert_eq!(dp.active, PaneId::Right);
557        dp.switch_active();
558        assert_eq!(dp.active, PaneId::Left);
559    }
560
561    #[test]
562    fn load_entries_sorts_directories_first() {
563        let mut pane = Pane::new(std::env::temp_dir());
564        pane.load_entries();
565
566        // Verify structure: all dirs should come before all files
567        let mut found_file = false;
568        for entry in &pane.entries {
569            if !entry.is_dir {
570                found_file = true;
571            } else if found_file {
572                panic!("Found directory after file; sort order violated");
573            }
574        }
575
576        // Also verify alphabetical within each group
577        let mut prev_dir: Option<&str> = None;
578        for entry in &pane.entries {
579            if entry.is_dir {
580                if let Some(prev) = prev_dir {
581                    assert!(
582                        prev <= entry.name.as_str(),
583                        "Directories not sorted alphabetically"
584                    );
585                }
586                prev_dir = Some(&entry.name);
587            }
588        }
589    }
590
591    #[test]
592    fn enter_directory_changes_cwd() {
593        // Use a real temp directory for this test
594        let temp_dir = std::env::temp_dir();
595        let mut pane = Pane::new(temp_dir.clone());
596
597        // Create an entry pointing to a real directory
598        pane.entries = vec![Entry {
599            name: "test_entry".into(),
600            path: temp_dir.clone(),
601            is_dir: true,
602            size: 0,
603            modified: None,
604        }];
605        pane.cursor = 0;
606
607        pane.enter_directory();
608
609        // The cwd should update to the selected entry's path
610        assert_eq!(pane.cwd, temp_dir);
611    }
612
613    #[test]
614    fn goto_parent_navigates_up() {
615        let mut pane = Pane::new(PathBuf::from("/tmp/some/nested/path"));
616        let parent = pane.cwd.parent().unwrap().to_path_buf();
617
618        pane.goto_parent();
619
620        assert_eq!(pane.cwd, parent);
621    }
622
623    #[test]
624    fn goto_parent_at_root_does_nothing() {
625        let mut pane = Pane::new(PathBuf::from("/"));
626        let _original_cwd = pane.cwd.clone();
627
628        pane.goto_parent();
629
630        assert_eq!(pane.cwd, PathBuf::from("/"));
631    }
632
633    fn pane_with_entries(names: &[&str]) -> Pane {
634        let mut pane = Pane::new(PathBuf::from("/tmp"));
635        pane.entries = names
636            .iter()
637            .map(|n| Entry {
638                name: n.to_string(),
639                path: PathBuf::from(format!("/tmp/{n}")),
640                is_dir: false,
641                size: 0,
642                modified: None,
643            })
644            .collect();
645        pane
646    }
647
648    #[test]
649    fn toggle_selection_marks_and_unmarks() {
650        let mut pane = pane_with_entries(&["a", "b", "c"]);
651        pane.toggle_selection();
652        assert!(pane.selected.contains(&0));
653        pane.toggle_selection();
654        assert!(!pane.selected.contains(&0));
655    }
656
657    #[test]
658    fn toggle_selection_skips_parent_entry() {
659        let mut pane = Pane::new(PathBuf::from("/tmp"));
660        pane.entries = vec![Entry {
661            name: "..".into(),
662            path: "/".into(),
663            is_dir: true,
664            size: 0,
665            modified: None,
666        }];
667        pane.toggle_selection();
668        assert!(pane.selected.is_empty());
669    }
670
671    #[test]
672    fn effective_selection_returns_cursor_when_nothing_tagged() {
673        let mut pane = pane_with_entries(&["a", "b", "c"]);
674        pane.cursor = 2;
675        assert_eq!(pane.effective_selection(), vec![2]);
676    }
677
678    #[test]
679    fn effective_selection_returns_sorted_tagged_indices() {
680        let mut pane = pane_with_entries(&["a", "b", "c"]);
681        pane.selected.insert(2);
682        pane.selected.insert(0);
683        assert_eq!(pane.effective_selection(), vec![0, 2]);
684    }
685
686    #[test]
687    fn extend_selection_down_tags_current_and_advances_cursor() {
688        let mut pane = pane_with_entries(&["a", "b", "c"]);
689        pane.extend_selection_down();
690        assert!(pane.selected.contains(&0));
691        assert_eq!(pane.cursor, 1);
692    }
693
694    #[test]
695    fn extend_selection_up_tags_current_and_moves_cursor_up() {
696        let mut pane = pane_with_entries(&["a", "b", "c"]);
697        pane.cursor = 2;
698        pane.extend_selection_up();
699        assert!(pane.selected.contains(&2));
700        assert_eq!(pane.cursor, 1);
701    }
702
703    #[test]
704    fn load_entries_clears_selection() {
705        let mut pane = Pane::new(std::env::temp_dir());
706        pane.selected.insert(0);
707        pane.selected.insert(1);
708        pane.load_entries();
709        assert!(pane.selected.is_empty());
710    }
711
712    #[test]
713    fn jump_to_prefix_moves_cursor_to_match() {
714        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
715        assert!(pane.jump_to_prefix("ban"));
716        assert_eq!(pane.cursor, 1);
717    }
718
719    #[test]
720    fn jump_to_prefix_is_case_insensitive() {
721        let mut pane = pane_with_entries(&["Apple", "Banana", "Cherry"]);
722        assert!(pane.jump_to_prefix("cher"));
723        assert_eq!(pane.cursor, 2);
724    }
725
726    #[test]
727    fn jump_to_prefix_no_match_leaves_cursor_and_returns_false() {
728        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
729        pane.cursor = 1;
730        assert!(!pane.jump_to_prefix("zzz"));
731        assert_eq!(pane.cursor, 1);
732    }
733
734    #[test]
735    fn jump_to_prefix_skips_parent_entry() {
736        let mut pane = Pane::new(PathBuf::from("/tmp"));
737        pane.entries = vec![
738            Entry {
739                name: "..".into(),
740                path: "/".into(),
741                is_dir: true,
742                size: 0,
743                modified: None,
744            },
745            Entry {
746                name: "docs".into(),
747                path: "/tmp/docs".into(),
748                is_dir: true,
749                size: 0,
750                modified: None,
751            },
752        ];
753        pane.cursor = 1;
754        assert!(!pane.jump_to_prefix(".."));
755        assert_eq!(pane.cursor, 1);
756    }
757
758    #[test]
759    fn set_sort_key_changes_key_and_leaves_direction() {
760        let mut pane = Pane::new(std::env::temp_dir());
761        pane.sort_reversed = true;
762        pane.set_sort_key(SortKey::Size);
763        assert_eq!(pane.sort_key, SortKey::Size);
764        assert!(pane.sort_reversed);
765    }
766
767    #[test]
768    fn set_sort_key_toggles_direction_when_key_already_active() {
769        let mut pane = Pane::new(std::env::temp_dir());
770        assert_eq!(pane.sort_key, SortKey::Name);
771        assert!(!pane.sort_reversed);
772
773        pane.set_sort_key(SortKey::Name);
774        assert_eq!(pane.sort_key, SortKey::Name);
775        assert!(pane.sort_reversed);
776
777        pane.set_sort_key(SortKey::Name);
778        assert_eq!(pane.sort_key, SortKey::Name);
779        assert!(!pane.sort_reversed);
780    }
781
782    #[test]
783    fn set_sort_key_reorders_entries() {
784        let dir = std::env::temp_dir().join("oxinav_test_set_sort_key_reorders");
785        std::fs::create_dir_all(&dir).unwrap();
786        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
787        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
788
789        let mut pane = Pane::new(dir.clone());
790        pane.load_entries();
791        pane.set_sort_key(SortKey::Size);
792
793        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
794        assert_eq!(names, vec!["small.txt", "big.txt"]);
795
796        std::fs::remove_dir_all(&dir).ok();
797    }
798
799    #[test]
800    fn sorts_files_by_size() {
801        let dir = std::env::temp_dir().join("oxinav_test_sort_by_size");
802        std::fs::create_dir_all(&dir).unwrap();
803        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
804        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
805
806        let mut pane = Pane::new(dir.clone());
807        pane.sort_key = SortKey::Size;
808        pane.load_entries();
809
810        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
811        assert_eq!(names, vec!["small.txt", "big.txt"]);
812
813        std::fs::remove_dir_all(&dir).ok();
814    }
815
816    #[test]
817    fn sorts_files_reversed() {
818        let dir = std::env::temp_dir().join("oxinav_test_sort_reversed");
819        std::fs::create_dir_all(&dir).unwrap();
820        std::fs::write(dir.join("a.txt"), b"a").unwrap();
821        std::fs::write(dir.join("b.txt"), b"b").unwrap();
822
823        let mut pane = Pane::new(dir.clone());
824        pane.sort_reversed = true;
825        pane.load_entries();
826
827        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
828        assert_eq!(names, vec!["b.txt", "a.txt"]);
829
830        std::fs::remove_dir_all(&dir).ok();
831    }
832
833    // --- filtering ---
834
835    #[test]
836    fn bare_pattern_matches_as_a_substring() {
837        assert!(matches_filter("Cargo.toml", "cargo"));
838        assert!(matches_filter("main.rs", ".rs"));
839        assert!(!matches_filter("main.rs", "toml"));
840    }
841
842    #[test]
843    fn wildcard_pattern_matches_as_a_glob_over_the_whole_name() {
844        assert!(matches_filter("main.rs", "*.rs"));
845        assert!(!matches_filter("main.rsx", "*.rs"));
846        assert!(matches_filter("Cargo.toml", "cargo*"));
847        assert!(!matches_filter("build.rs", "cargo*"));
848    }
849
850    #[test]
851    fn question_mark_matches_exactly_one_character() {
852        assert!(matches_filter("a.rs", "?.rs"));
853        assert!(!matches_filter("ab.rs", "?.rs"));
854    }
855
856    #[test]
857    fn matching_ignores_case_in_both_modes() {
858        assert!(matches_filter("README.MD", "readme"));
859        assert!(matches_filter("README.MD", "*.md"));
860    }
861
862    #[test]
863    fn blank_pattern_matches_everything() {
864        assert!(matches_filter("anything", ""));
865        assert!(matches_filter("anything", "   "));
866    }
867
868    #[test]
869    fn consecutive_stars_do_not_change_the_match() {
870        assert!(matches_filter("main.rs", "**.rs"));
871        assert!(matches_filter("main.rs", "*"));
872    }
873
874    #[test]
875    fn set_filter_narrows_the_listing_and_clear_restores_it() {
876        let dir = std::env::temp_dir().join("oxinav_test_filter_narrows");
877        std::fs::remove_dir_all(&dir).ok();
878        std::fs::create_dir_all(&dir).unwrap();
879        std::fs::write(dir.join("main.rs"), b"a").unwrap();
880        std::fs::write(dir.join("lib.rs"), b"b").unwrap();
881        std::fs::write(dir.join("Cargo.toml"), b"c").unwrap();
882
883        let mut pane = Pane::new(dir.clone());
884        pane.load_entries();
885        pane.set_filter("*.rs");
886
887        let names = listed(&pane);
888        assert_eq!(names, vec!["lib.rs", "main.rs"]);
889
890        pane.clear_filter();
891        assert_eq!(listed(&pane), vec!["Cargo.toml", "lib.rs", "main.rs"]);
892
893        std::fs::remove_dir_all(&dir).ok();
894    }
895
896    #[test]
897    fn parent_entry_survives_a_filter_matching_nothing() {
898        let dir = std::env::temp_dir().join("oxinav_test_filter_keeps_parent");
899        std::fs::remove_dir_all(&dir).ok();
900        std::fs::create_dir_all(&dir).unwrap();
901        std::fs::write(dir.join("main.rs"), b"a").unwrap();
902
903        let mut pane = Pane::new(dir.clone());
904        pane.load_entries();
905        pane.set_filter("*.nomatch");
906
907        assert!(listed(&pane).is_empty());
908        // `..` is the only thing left, so navigating up is still possible.
909        let all: Vec<&str> = pane.entries.iter().map(|e| e.name.as_str()).collect();
910        assert_eq!(all, vec![".."]);
911
912        std::fs::remove_dir_all(&dir).ok();
913    }
914
915    #[test]
916    fn filter_composes_with_the_hidden_files_toggle() {
917        let dir = std::env::temp_dir().join("oxinav_test_filter_hidden");
918        std::fs::remove_dir_all(&dir).ok();
919        std::fs::create_dir_all(&dir).unwrap();
920        std::fs::write(dir.join("visible.rs"), b"a").unwrap();
921        std::fs::write(dir.join(".hidden.rs"), b"b").unwrap();
922
923        let mut pane = Pane::new(dir.clone());
924        pane.load_entries();
925        pane.set_filter("*.rs");
926        assert_eq!(listed(&pane), vec!["visible.rs"]);
927
928        // Revealing hidden files widens the set the filter then narrows.
929        pane.toggle_hidden_files();
930        assert_eq!(listed(&pane), vec![".hidden.rs", "visible.rs"]);
931
932        std::fs::remove_dir_all(&dir).ok();
933    }
934
935    #[test]
936    fn filter_composes_with_the_active_sort_key() {
937        let dir = std::env::temp_dir().join("oxinav_test_filter_sort");
938        std::fs::remove_dir_all(&dir).ok();
939        std::fs::create_dir_all(&dir).unwrap();
940        std::fs::write(dir.join("big.rs"), vec![0u8; 100]).unwrap();
941        std::fs::write(dir.join("small.rs"), vec![0u8; 10]).unwrap();
942        std::fs::write(dir.join("huge.toml"), vec![0u8; 999]).unwrap();
943
944        let mut pane = Pane::new(dir.clone());
945        pane.load_entries();
946        pane.set_filter("*.rs");
947        pane.set_sort_key(SortKey::Size);
948
949        // Sorted by size, and the excluded .toml stays excluded.
950        assert_eq!(listed(&pane), vec!["small.rs", "big.rs"]);
951
952        std::fs::remove_dir_all(&dir).ok();
953    }
954
955    #[test]
956    fn filter_applies_to_directories_too() {
957        let dir = std::env::temp_dir().join("oxinav_test_filter_dirs");
958        std::fs::remove_dir_all(&dir).ok();
959        std::fs::create_dir_all(dir.join("src")).unwrap();
960        std::fs::create_dir_all(dir.join("target")).unwrap();
961        std::fs::write(dir.join("main.rs"), b"a").unwrap();
962
963        let mut pane = Pane::new(dir.clone());
964        pane.load_entries();
965        pane.set_filter("*.rs");
966
967        assert_eq!(listed(&pane), vec!["main.rs"]);
968
969        std::fs::remove_dir_all(&dir).ok();
970    }
971
972    #[test]
973    fn refiltering_does_not_re_read_the_directory() {
974        let dir = std::env::temp_dir().join("oxinav_test_filter_no_reread");
975        std::fs::remove_dir_all(&dir).ok();
976        std::fs::create_dir_all(&dir).unwrap();
977        std::fs::write(dir.join("main.rs"), b"a").unwrap();
978        std::fs::write(dir.join("notes.txt"), b"b").unwrap();
979
980        let mut pane = Pane::new(dir.clone());
981        pane.load_entries();
982
983        // Delete the directory out from under the pane. Re-filtering now can
984        // only succeed if it works off the cached read, which is what makes
985        // it cheap enough to run on every keystroke.
986        std::fs::remove_dir_all(&dir).ok();
987
988        pane.set_filter("*.rs");
989        assert_eq!(listed(&pane), vec!["main.rs"]);
990
991        pane.clear_filter();
992        assert_eq!(listed(&pane), vec!["main.rs", "notes.txt"]);
993    }
994
995    // --- directory history ---
996
997    #[test]
998    fn back_returns_to_the_previous_directory() {
999        let mut pane = Pane::new(PathBuf::from("/a"));
1000        pane.navigate_to(PathBuf::from("/b"));
1001        assert_eq!(pane.cwd, PathBuf::from("/b"));
1002
1003        assert!(pane.go_back());
1004        assert_eq!(pane.cwd, PathBuf::from("/a"));
1005    }
1006
1007    #[test]
1008    fn forward_returns_after_going_back() {
1009        let mut pane = Pane::new(PathBuf::from("/a"));
1010        pane.navigate_to(PathBuf::from("/b"));
1011        pane.go_back();
1012
1013        assert!(pane.go_forward());
1014        assert_eq!(pane.cwd, PathBuf::from("/b"));
1015    }
1016
1017    #[test]
1018    fn navigating_anew_truncates_the_forward_tail() {
1019        let mut pane = Pane::new(PathBuf::from("/a"));
1020        pane.navigate_to(PathBuf::from("/b"));
1021        pane.go_back();
1022        // Branching from A to C makes B unreachable.
1023        pane.navigate_to(PathBuf::from("/c"));
1024
1025        assert!(!pane.can_go_forward());
1026        assert!(!pane.go_forward());
1027        assert_eq!(pane.cwd, PathBuf::from("/c"));
1028
1029        // Back now leads to A, not B.
1030        assert!(pane.go_back());
1031        assert_eq!(pane.cwd, PathBuf::from("/a"));
1032    }
1033
1034    #[test]
1035    fn back_at_the_start_of_history_does_nothing() {
1036        let mut pane = Pane::new(PathBuf::from("/a"));
1037
1038        assert!(!pane.can_go_back());
1039        assert!(!pane.go_back());
1040        assert_eq!(pane.cwd, PathBuf::from("/a"));
1041    }
1042
1043    #[test]
1044    fn forward_without_going_back_does_nothing() {
1045        let mut pane = Pane::new(PathBuf::from("/a"));
1046        pane.navigate_to(PathBuf::from("/b"));
1047
1048        assert!(!pane.can_go_forward());
1049        assert!(!pane.go_forward());
1050        assert_eq!(pane.cwd, PathBuf::from("/b"));
1051    }
1052
1053    #[test]
1054    fn navigating_to_the_current_directory_is_not_recorded() {
1055        let mut pane = Pane::new(PathBuf::from("/a"));
1056        pane.navigate_to(PathBuf::from("/a"));
1057
1058        // Re-entering where we already are must not create a history step
1059        // that back would then have to walk through.
1060        assert!(!pane.can_go_back());
1061    }
1062
1063    #[test]
1064    fn history_survives_several_steps_in_both_directions() {
1065        let mut pane = Pane::new(PathBuf::from("/a"));
1066        pane.navigate_to(PathBuf::from("/b"));
1067        pane.navigate_to(PathBuf::from("/c"));
1068
1069        assert!(pane.go_back());
1070        assert!(pane.go_back());
1071        assert_eq!(pane.cwd, PathBuf::from("/a"));
1072
1073        assert!(pane.go_forward());
1074        assert!(pane.go_forward());
1075        assert_eq!(pane.cwd, PathBuf::from("/c"));
1076    }
1077
1078    #[test]
1079    fn history_is_per_pane() {
1080        let mut dp = DualPane::new("/left".into(), "/right".into());
1081        dp.left.navigate_to(PathBuf::from("/left/sub"));
1082
1083        assert!(dp.left.can_go_back());
1084        assert!(!dp.right.can_go_back());
1085    }
1086
1087    #[test]
1088    fn set_filter_with_a_blank_pattern_clears_it() {
1089        let mut pane = Pane::new(std::env::temp_dir());
1090        pane.set_filter("*.rs");
1091        assert!(pane.filter.is_some());
1092
1093        pane.set_filter("   ");
1094        assert!(pane.filter.is_none());
1095    }
1096
1097    #[test]
1098    fn directories_stay_name_sorted_regardless_of_sort_key() {
1099        let dir = std::env::temp_dir().join("oxinav_test_sort_dirs_stable");
1100        std::fs::create_dir_all(dir.join("b_dir")).unwrap();
1101        std::fs::create_dir_all(dir.join("a_dir")).unwrap();
1102
1103        let mut pane = Pane::new(dir.clone());
1104        pane.sort_key = SortKey::Size;
1105        pane.load_entries();
1106
1107        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
1108        assert_eq!(names, vec!["a_dir", "b_dir"]);
1109
1110        std::fs::remove_dir_all(&dir).ok();
1111    }
1112}