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)]
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.entries.get(self.cursor).map_or(true, |e| e.name == "..") {
298            return;
299        }
300        if !self.selected.remove(&self.cursor) {
301            self.selected.insert(self.cursor);
302        }
303    }
304
305    pub fn extend_selection_down(&mut self) {
306        if self.entries.get(self.cursor).map_or(false, |e| e.name != "..") {
307            self.selected.insert(self.cursor);
308        }
309        self.move_cursor_down();
310    }
311
312    pub fn extend_selection_up(&mut self) {
313        if self.entries.get(self.cursor).map_or(false, |e| e.name != "..") {
314            self.selected.insert(self.cursor);
315        }
316        self.move_cursor_up();
317    }
318
319    pub fn clear_selection(&mut self) {
320        self.selected.clear();
321    }
322
323    /// Move the cursor to the first entry (other than "..") whose name starts with
324    /// `query`, case-insensitively. Leaves the cursor untouched if nothing matches.
325    /// Returns whether a match was found.
326    pub fn jump_to_prefix(&mut self, query: &str) -> bool {
327        if query.is_empty() {
328            return false;
329        }
330        let query = query.to_lowercase();
331        match self
332            .entries
333            .iter()
334            .position(|e| e.name != ".." && e.name.to_lowercase().starts_with(&query))
335        {
336            Some(index) => {
337                self.cursor = index;
338                true
339            }
340            None => false,
341        }
342    }
343
344    /// Returns the tagged indices (sorted), or `[cursor]` if nothing is tagged.
345    pub fn effective_selection(&self) -> Vec<usize> {
346        if self.selected.is_empty() {
347            vec![self.cursor]
348        } else {
349            let mut indices: Vec<usize> = self.selected.iter().copied().collect();
350            indices.sort_unstable();
351            indices
352        }
353    }
354
355    /// Load entries from the current working directory.
356    /// Read `cwd` from disk into the entry cache, then derive the listing.
357    /// The read is the expensive half, so anything that only changes *how*
358    /// entries are presented — sort, hidden files, the filter — goes through
359    /// `apply_view` instead of coming back here.
360    pub fn load_entries(&mut self) {
361        self.all_entries.clear();
362
363        // An unreadable directory yields an empty listing rather than an error.
364        if let Ok(entries_iter) = std::fs::read_dir(&self.cwd) {
365            for entry_result in entries_iter {
366                let Ok(entry) = entry_result else {
367                    continue;
368                };
369                let file_name = entry.file_name();
370                let name = file_name.to_string_lossy().to_string();
371
372                // Skip "." but don't skip ".."
373                if name == "." {
374                    continue;
375                }
376
377                let path = entry.path();
378                let metadata = entry.metadata().ok();
379                let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
380                let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
381                let modified = metadata.as_ref().and_then(|m| m.modified().ok());
382
383                self.all_entries.push(Entry {
384                    name,
385                    path,
386                    is_dir,
387                    size,
388                    modified,
389                });
390            }
391        }
392
393        self.apply_view();
394    }
395
396    /// Rebuild the visible listing from the cached read: drop hidden files,
397    /// apply the filter, sort directories-then-files, and prepend the
398    /// synthetic `..`. Touches no I/O, so it is cheap enough to run on every
399    /// keystroke of an inline filter.
400    ///
401    /// Sorts directories first (alphabetical), then files by the active sort
402    /// key. Excludes "." but includes ".." (parent directory) if not at root.
403    fn apply_view(&mut self) {
404        self.entries.clear();
405        self.cursor = 0;
406        self.scroll_offset = 0;
407        self.selected.clear();
408
409        let mut dirs: Vec<Entry> = Vec::new();
410        let mut files: Vec<Entry> = Vec::new();
411
412        for entry in &self.all_entries {
413            if !self.show_hidden && entry.name.starts_with('.') {
414                continue;
415            }
416
417            // Narrows what is listed, on top of the hidden-file rule above and
418            // the sort below. `..` is prepended further down, so it is never
419            // subject to this.
420            if let Some(pattern) = &self.filter {
421                if !matches_filter(&entry.name, pattern) {
422                    continue;
423                }
424            }
425
426            if entry.is_dir {
427                dirs.push(entry.clone());
428            } else {
429                files.push(entry.clone());
430            }
431        }
432
433        // Directories are always sorted by name; size/modified aren't
434        // meaningful for a directory without a recursive scan.
435        dirs.sort_by(|a, b| a.name.cmp(&b.name));
436
437        match self.sort_key {
438            SortKey::Name => files.sort_by(|a, b| a.name.cmp(&b.name)),
439            SortKey::Size => files.sort_by_key(|f| f.size),
440            SortKey::Modified => files.sort_by_key(|f| f.modified),
441        }
442        if self.sort_reversed {
443            files.reverse();
444        }
445
446        // Add ".." first if not at root
447        if let Some(parent) = self.cwd.parent() {
448            self.entries.push(Entry {
449                name: "..".to_string(),
450                path: parent.to_path_buf(),
451                is_dir: true,
452                size: 0,
453                modified: None,
454            });
455        }
456
457        // Combine: directories, then files
458        self.entries.extend(dirs);
459        self.entries.extend(files);
460    }
461
462    /// Enter the selected directory. If selection is not a directory, does nothing.
463    pub fn enter_directory(&mut self) {
464        if let Some(entry) = self.selected() {
465            if entry.is_dir {
466                let target = entry.path.clone();
467                self.navigate_to(target);
468            }
469        }
470    }
471
472    /// Navigate to the parent directory. Does nothing if already at root.
473    pub fn goto_parent(&mut self) {
474        if let Some(parent) = self.cwd.parent() {
475            let target = parent.to_path_buf();
476            self.navigate_to(target);
477        }
478    }
479}
480
481#[derive(Debug, Clone)]
482pub struct DualPane {
483    pub left: Pane,
484    pub right: Pane,
485    pub active: PaneId,
486}
487
488impl DualPane {
489    pub fn new(left_cwd: PathBuf, right_cwd: PathBuf) -> Self {
490        Self {
491            left: Pane::new(left_cwd),
492            right: Pane::new(right_cwd),
493            active: PaneId::Left,
494        }
495    }
496
497    pub fn active_pane(&self) -> &Pane {
498        match self.active {
499            PaneId::Left => &self.left,
500            PaneId::Right => &self.right,
501        }
502    }
503
504    pub fn active_pane_mut(&mut self) -> &mut Pane {
505        match self.active {
506            PaneId::Left => &mut self.left,
507            PaneId::Right => &mut self.right,
508        }
509    }
510
511    pub fn switch_active(&mut self) {
512        self.active = self.active.other();
513    }
514
515    pub fn toggle_hidden_files(&mut self) {
516        self.left.toggle_hidden_files();
517        self.right.toggle_hidden_files();
518    }
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    #[test]
526    fn visible_offset_leaves_a_cursor_already_in_view_alone() {
527        // Rows 10..14 are showing and the cursor is among them: not scrolling
528        // is what lets the cursor travel inside the viewport.
529        assert_eq!(visible_offset(10, 10, 5), 10);
530        assert_eq!(visible_offset(12, 10, 5), 10);
531        assert_eq!(visible_offset(14, 10, 5), 10);
532    }
533
534    #[test]
535    fn visible_offset_follows_a_cursor_above_the_viewport() {
536        assert_eq!(visible_offset(7, 10, 5), 7);
537        assert_eq!(visible_offset(0, 10, 5), 0);
538    }
539
540    #[test]
541    fn visible_offset_follows_a_cursor_below_the_viewport() {
542        // One past the last visible row scrolls by exactly one row.
543        assert_eq!(visible_offset(15, 10, 5), 11);
544        assert_eq!(visible_offset(20, 10, 5), 16);
545    }
546
547    #[test]
548    fn visible_offset_stays_at_zero_when_everything_fits() {
549        assert_eq!(visible_offset(0, 0, 50), 0);
550        assert_eq!(visible_offset(20, 0, 50), 0);
551    }
552
553    #[test]
554    fn visible_offset_survives_a_zero_row_viewport() {
555        // Nothing can be shown, so the best available answer is the cursor
556        // itself; the point is that it must not underflow.
557        assert_eq!(visible_offset(0, 0, 0), 0);
558        assert_eq!(visible_offset(3, 0, 0), 3);
559    }
560
561    #[test]
562    fn ensure_cursor_visible_scrolls_to_the_cursor() {
563        let mut pane = Pane::new(PathBuf::from("/tmp"));
564        pane.cursor = 30;
565        pane.ensure_cursor_visible(5);
566        assert_eq!(pane.scroll_offset, 26);
567
568        pane.cursor = 2;
569        pane.ensure_cursor_visible(5);
570        assert_eq!(pane.scroll_offset, 2);
571    }
572
573    #[test]
574    fn cursor_does_not_go_below_zero() {
575        let mut pane = Pane::new(PathBuf::from("/tmp"));
576        pane.move_cursor_up();
577        assert_eq!(pane.cursor, 0);
578    }
579
580    #[test]
581    fn hidden_files_are_hidden_by_default() {
582        let pane = Pane::new(PathBuf::from("/tmp"));
583        assert!(!pane.show_hidden);
584    }
585
586    #[test]
587    fn toggle_hidden_files_toggles_both_panes() {
588        let mut dp = DualPane::new("/".into(), "/tmp".into());
589
590        dp.toggle_hidden_files();
591
592        assert!(dp.left.show_hidden);
593        assert!(dp.right.show_hidden);
594
595        dp.toggle_hidden_files();
596
597        assert!(!dp.left.show_hidden);
598        assert!(!dp.right.show_hidden);
599    }
600
601    /// Entry names excluding the synthetic `..`, in listing order.
602    fn listed(pane: &Pane) -> Vec<&str> {
603        pane.entries
604            .iter()
605            .filter(|e| e.name != "..")
606            .map(|e| e.name.as_str())
607            .collect()
608    }
609
610    #[test]
611    fn cursor_does_not_exceed_entries() {
612        let mut pane = Pane::new(PathBuf::from("/tmp"));
613        pane.entries = vec![Entry {
614            name: "a".into(),
615            path: "/tmp/a".into(),
616            is_dir: false,
617            size: 0,
618            modified: None,
619        }];
620        pane.move_cursor_down();
621        pane.move_cursor_down();
622        assert_eq!(pane.cursor, 0);
623    }
624
625    #[test]
626    fn switch_active_toggles_pane() {
627        let mut dp = DualPane::new("/".into(), "/tmp".into());
628        assert_eq!(dp.active, PaneId::Left);
629        dp.switch_active();
630        assert_eq!(dp.active, PaneId::Right);
631        dp.switch_active();
632        assert_eq!(dp.active, PaneId::Left);
633    }
634
635    #[test]
636    fn load_entries_sorts_directories_first() {
637        let mut pane = Pane::new(std::env::temp_dir());
638        pane.load_entries();
639
640        // Verify structure: all dirs should come before all files
641        let mut found_file = false;
642        for entry in &pane.entries {
643            if !entry.is_dir {
644                found_file = true;
645            } else if found_file {
646                panic!("Found directory after file; sort order violated");
647            }
648        }
649
650        // Also verify alphabetical within each group
651        let mut prev_dir: Option<&str> = None;
652        for entry in &pane.entries {
653            if entry.is_dir {
654                if let Some(prev) = prev_dir {
655                    assert!(
656                        prev <= entry.name.as_str(),
657                        "Directories not sorted alphabetically"
658                    );
659                }
660                prev_dir = Some(&entry.name);
661            }
662        }
663    }
664
665    #[test]
666    fn enter_directory_changes_cwd() {
667        // Use a real temp directory for this test
668        let temp_dir = std::env::temp_dir();
669        let mut pane = Pane::new(temp_dir.clone());
670
671        // Create an entry pointing to a real directory
672        pane.entries = vec![Entry {
673            name: "test_entry".into(),
674            path: temp_dir.clone(),
675            is_dir: true,
676            size: 0,
677            modified: None,
678        }];
679        pane.cursor = 0;
680
681        pane.enter_directory();
682
683        // The cwd should update to the selected entry's path
684        assert_eq!(pane.cwd, temp_dir);
685    }
686
687    #[test]
688    fn goto_parent_navigates_up() {
689        let mut pane = Pane::new(PathBuf::from("/tmp/some/nested/path"));
690        let parent = pane.cwd.parent().unwrap().to_path_buf();
691
692        pane.goto_parent();
693
694        assert_eq!(pane.cwd, parent);
695    }
696
697    #[test]
698    fn goto_parent_at_root_does_nothing() {
699        let mut pane = Pane::new(PathBuf::from("/"));
700        let _original_cwd = pane.cwd.clone();
701
702        pane.goto_parent();
703
704        assert_eq!(pane.cwd, PathBuf::from("/"));
705    }
706
707    fn pane_with_entries(names: &[&str]) -> Pane {
708        let mut pane = Pane::new(PathBuf::from("/tmp"));
709        pane.entries = names
710            .iter()
711            .map(|n| Entry {
712                name: n.to_string(),
713                path: PathBuf::from(format!("/tmp/{n}")),
714                is_dir: false,
715                size: 0,
716                modified: None,
717            })
718            .collect();
719        pane
720    }
721
722    #[test]
723    fn toggle_selection_marks_and_unmarks() {
724        let mut pane = pane_with_entries(&["a", "b", "c"]);
725        pane.toggle_selection();
726        assert!(pane.selected.contains(&0));
727        pane.toggle_selection();
728        assert!(!pane.selected.contains(&0));
729    }
730
731    #[test]
732    fn toggle_selection_skips_parent_entry() {
733        let mut pane = Pane::new(PathBuf::from("/tmp"));
734        pane.entries = vec![Entry {
735            name: "..".into(),
736            path: "/".into(),
737            is_dir: true,
738            size: 0,
739            modified: None,
740        }];
741        pane.toggle_selection();
742        assert!(pane.selected.is_empty());
743    }
744
745    #[test]
746    fn effective_selection_returns_cursor_when_nothing_tagged() {
747        let mut pane = pane_with_entries(&["a", "b", "c"]);
748        pane.cursor = 2;
749        assert_eq!(pane.effective_selection(), vec![2]);
750    }
751
752    #[test]
753    fn effective_selection_returns_sorted_tagged_indices() {
754        let mut pane = pane_with_entries(&["a", "b", "c"]);
755        pane.selected.insert(2);
756        pane.selected.insert(0);
757        assert_eq!(pane.effective_selection(), vec![0, 2]);
758    }
759
760    #[test]
761    fn extend_selection_down_tags_current_and_advances_cursor() {
762        let mut pane = pane_with_entries(&["a", "b", "c"]);
763        pane.extend_selection_down();
764        assert!(pane.selected.contains(&0));
765        assert_eq!(pane.cursor, 1);
766    }
767
768    #[test]
769    fn extend_selection_up_tags_current_and_moves_cursor_up() {
770        let mut pane = pane_with_entries(&["a", "b", "c"]);
771        pane.cursor = 2;
772        pane.extend_selection_up();
773        assert!(pane.selected.contains(&2));
774        assert_eq!(pane.cursor, 1);
775    }
776
777    #[test]
778    fn load_entries_clears_selection() {
779        let mut pane = Pane::new(std::env::temp_dir());
780        pane.selected.insert(0);
781        pane.selected.insert(1);
782        pane.load_entries();
783        assert!(pane.selected.is_empty());
784    }
785
786    #[test]
787    fn jump_to_prefix_moves_cursor_to_match() {
788        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
789        assert!(pane.jump_to_prefix("ban"));
790        assert_eq!(pane.cursor, 1);
791    }
792
793    #[test]
794    fn jump_to_prefix_is_case_insensitive() {
795        let mut pane = pane_with_entries(&["Apple", "Banana", "Cherry"]);
796        assert!(pane.jump_to_prefix("cher"));
797        assert_eq!(pane.cursor, 2);
798    }
799
800    #[test]
801    fn jump_to_prefix_no_match_leaves_cursor_and_returns_false() {
802        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
803        pane.cursor = 1;
804        assert!(!pane.jump_to_prefix("zzz"));
805        assert_eq!(pane.cursor, 1);
806    }
807
808    #[test]
809    fn jump_to_prefix_skips_parent_entry() {
810        let mut pane = Pane::new(PathBuf::from("/tmp"));
811        pane.entries = vec![
812            Entry {
813                name: "..".into(),
814                path: "/".into(),
815                is_dir: true,
816                size: 0,
817                modified: None,
818            },
819            Entry {
820                name: "docs".into(),
821                path: "/tmp/docs".into(),
822                is_dir: true,
823                size: 0,
824                modified: None,
825            },
826        ];
827        pane.cursor = 1;
828        assert!(!pane.jump_to_prefix(".."));
829        assert_eq!(pane.cursor, 1);
830    }
831
832    #[test]
833    fn set_sort_key_changes_key_and_leaves_direction() {
834        let mut pane = Pane::new(std::env::temp_dir());
835        pane.sort_reversed = true;
836        pane.set_sort_key(SortKey::Size);
837        assert_eq!(pane.sort_key, SortKey::Size);
838        assert!(pane.sort_reversed);
839    }
840
841    #[test]
842    fn set_sort_key_toggles_direction_when_key_already_active() {
843        let mut pane = Pane::new(std::env::temp_dir());
844        assert_eq!(pane.sort_key, SortKey::Name);
845        assert!(!pane.sort_reversed);
846
847        pane.set_sort_key(SortKey::Name);
848        assert_eq!(pane.sort_key, SortKey::Name);
849        assert!(pane.sort_reversed);
850
851        pane.set_sort_key(SortKey::Name);
852        assert_eq!(pane.sort_key, SortKey::Name);
853        assert!(!pane.sort_reversed);
854    }
855
856    #[test]
857    fn set_sort_key_reorders_entries() {
858        let dir = std::env::temp_dir().join("oxinav_test_set_sort_key_reorders");
859        std::fs::create_dir_all(&dir).unwrap();
860        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
861        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
862
863        let mut pane = Pane::new(dir.clone());
864        pane.load_entries();
865        pane.set_sort_key(SortKey::Size);
866
867        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
868        assert_eq!(names, vec!["small.txt", "big.txt"]);
869
870        std::fs::remove_dir_all(&dir).ok();
871    }
872
873    #[test]
874    fn sorts_files_by_size() {
875        let dir = std::env::temp_dir().join("oxinav_test_sort_by_size");
876        std::fs::create_dir_all(&dir).unwrap();
877        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
878        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();
879
880        let mut pane = Pane::new(dir.clone());
881        pane.sort_key = SortKey::Size;
882        pane.load_entries();
883
884        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
885        assert_eq!(names, vec!["small.txt", "big.txt"]);
886
887        std::fs::remove_dir_all(&dir).ok();
888    }
889
890    #[test]
891    fn sorts_files_reversed() {
892        let dir = std::env::temp_dir().join("oxinav_test_sort_reversed");
893        std::fs::create_dir_all(&dir).unwrap();
894        std::fs::write(dir.join("a.txt"), b"a").unwrap();
895        std::fs::write(dir.join("b.txt"), b"b").unwrap();
896
897        let mut pane = Pane::new(dir.clone());
898        pane.sort_reversed = true;
899        pane.load_entries();
900
901        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
902        assert_eq!(names, vec!["b.txt", "a.txt"]);
903
904        std::fs::remove_dir_all(&dir).ok();
905    }
906
907    // --- filtering ---
908
909    #[test]
910    fn bare_pattern_matches_as_a_substring() {
911        assert!(matches_filter("Cargo.toml", "cargo"));
912        assert!(matches_filter("main.rs", ".rs"));
913        assert!(!matches_filter("main.rs", "toml"));
914    }
915
916    #[test]
917    fn wildcard_pattern_matches_as_a_glob_over_the_whole_name() {
918        assert!(matches_filter("main.rs", "*.rs"));
919        assert!(!matches_filter("main.rsx", "*.rs"));
920        assert!(matches_filter("Cargo.toml", "cargo*"));
921        assert!(!matches_filter("build.rs", "cargo*"));
922    }
923
924    #[test]
925    fn question_mark_matches_exactly_one_character() {
926        assert!(matches_filter("a.rs", "?.rs"));
927        assert!(!matches_filter("ab.rs", "?.rs"));
928    }
929
930    #[test]
931    fn matching_ignores_case_in_both_modes() {
932        assert!(matches_filter("README.MD", "readme"));
933        assert!(matches_filter("README.MD", "*.md"));
934    }
935
936    #[test]
937    fn blank_pattern_matches_everything() {
938        assert!(matches_filter("anything", ""));
939        assert!(matches_filter("anything", "   "));
940    }
941
942    #[test]
943    fn consecutive_stars_do_not_change_the_match() {
944        assert!(matches_filter("main.rs", "**.rs"));
945        assert!(matches_filter("main.rs", "*"));
946    }
947
948    #[test]
949    fn set_filter_narrows_the_listing_and_clear_restores_it() {
950        let dir = std::env::temp_dir().join("oxinav_test_filter_narrows");
951        std::fs::remove_dir_all(&dir).ok();
952        std::fs::create_dir_all(&dir).unwrap();
953        std::fs::write(dir.join("main.rs"), b"a").unwrap();
954        std::fs::write(dir.join("lib.rs"), b"b").unwrap();
955        std::fs::write(dir.join("Cargo.toml"), b"c").unwrap();
956
957        let mut pane = Pane::new(dir.clone());
958        pane.load_entries();
959        pane.set_filter("*.rs");
960
961        let names = listed(&pane);
962        assert_eq!(names, vec!["lib.rs", "main.rs"]);
963
964        pane.clear_filter();
965        assert_eq!(listed(&pane), vec!["Cargo.toml", "lib.rs", "main.rs"]);
966
967        std::fs::remove_dir_all(&dir).ok();
968    }
969
970    #[test]
971    fn parent_entry_survives_a_filter_matching_nothing() {
972        let dir = std::env::temp_dir().join("oxinav_test_filter_keeps_parent");
973        std::fs::remove_dir_all(&dir).ok();
974        std::fs::create_dir_all(&dir).unwrap();
975        std::fs::write(dir.join("main.rs"), b"a").unwrap();
976
977        let mut pane = Pane::new(dir.clone());
978        pane.load_entries();
979        pane.set_filter("*.nomatch");
980
981        assert!(listed(&pane).is_empty());
982        // `..` is the only thing left, so navigating up is still possible.
983        let all: Vec<&str> = pane.entries.iter().map(|e| e.name.as_str()).collect();
984        assert_eq!(all, vec![".."]);
985
986        std::fs::remove_dir_all(&dir).ok();
987    }
988
989    #[test]
990    fn filter_composes_with_the_hidden_files_toggle() {
991        let dir = std::env::temp_dir().join("oxinav_test_filter_hidden");
992        std::fs::remove_dir_all(&dir).ok();
993        std::fs::create_dir_all(&dir).unwrap();
994        std::fs::write(dir.join("visible.rs"), b"a").unwrap();
995        std::fs::write(dir.join(".hidden.rs"), b"b").unwrap();
996
997        let mut pane = Pane::new(dir.clone());
998        pane.load_entries();
999        pane.set_filter("*.rs");
1000        assert_eq!(listed(&pane), vec!["visible.rs"]);
1001
1002        // Revealing hidden files widens the set the filter then narrows.
1003        pane.toggle_hidden_files();
1004        assert_eq!(listed(&pane), vec![".hidden.rs", "visible.rs"]);
1005
1006        std::fs::remove_dir_all(&dir).ok();
1007    }
1008
1009    #[test]
1010    fn filter_composes_with_the_active_sort_key() {
1011        let dir = std::env::temp_dir().join("oxinav_test_filter_sort");
1012        std::fs::remove_dir_all(&dir).ok();
1013        std::fs::create_dir_all(&dir).unwrap();
1014        std::fs::write(dir.join("big.rs"), vec![0u8; 100]).unwrap();
1015        std::fs::write(dir.join("small.rs"), vec![0u8; 10]).unwrap();
1016        std::fs::write(dir.join("huge.toml"), vec![0u8; 999]).unwrap();
1017
1018        let mut pane = Pane::new(dir.clone());
1019        pane.load_entries();
1020        pane.set_filter("*.rs");
1021        pane.set_sort_key(SortKey::Size);
1022
1023        // Sorted by size, and the excluded .toml stays excluded.
1024        assert_eq!(listed(&pane), vec!["small.rs", "big.rs"]);
1025
1026        std::fs::remove_dir_all(&dir).ok();
1027    }
1028
1029    #[test]
1030    fn filter_applies_to_directories_too() {
1031        let dir = std::env::temp_dir().join("oxinav_test_filter_dirs");
1032        std::fs::remove_dir_all(&dir).ok();
1033        std::fs::create_dir_all(dir.join("src")).unwrap();
1034        std::fs::create_dir_all(dir.join("target")).unwrap();
1035        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1036
1037        let mut pane = Pane::new(dir.clone());
1038        pane.load_entries();
1039        pane.set_filter("*.rs");
1040
1041        assert_eq!(listed(&pane), vec!["main.rs"]);
1042
1043        std::fs::remove_dir_all(&dir).ok();
1044    }
1045
1046    #[test]
1047    fn refiltering_does_not_re_read_the_directory() {
1048        let dir = std::env::temp_dir().join("oxinav_test_filter_no_reread");
1049        std::fs::remove_dir_all(&dir).ok();
1050        std::fs::create_dir_all(&dir).unwrap();
1051        std::fs::write(dir.join("main.rs"), b"a").unwrap();
1052        std::fs::write(dir.join("notes.txt"), b"b").unwrap();
1053
1054        let mut pane = Pane::new(dir.clone());
1055        pane.load_entries();
1056
1057        // Delete the directory out from under the pane. Re-filtering now can
1058        // only succeed if it works off the cached read, which is what makes
1059        // it cheap enough to run on every keystroke.
1060        std::fs::remove_dir_all(&dir).ok();
1061
1062        pane.set_filter("*.rs");
1063        assert_eq!(listed(&pane), vec!["main.rs"]);
1064
1065        pane.clear_filter();
1066        assert_eq!(listed(&pane), vec!["main.rs", "notes.txt"]);
1067    }
1068
1069    // --- directory history ---
1070
1071    #[test]
1072    fn back_returns_to_the_previous_directory() {
1073        let mut pane = Pane::new(PathBuf::from("/a"));
1074        pane.navigate_to(PathBuf::from("/b"));
1075        assert_eq!(pane.cwd, PathBuf::from("/b"));
1076
1077        assert!(pane.go_back());
1078        assert_eq!(pane.cwd, PathBuf::from("/a"));
1079    }
1080
1081    #[test]
1082    fn forward_returns_after_going_back() {
1083        let mut pane = Pane::new(PathBuf::from("/a"));
1084        pane.navigate_to(PathBuf::from("/b"));
1085        pane.go_back();
1086
1087        assert!(pane.go_forward());
1088        assert_eq!(pane.cwd, PathBuf::from("/b"));
1089    }
1090
1091    #[test]
1092    fn navigating_anew_truncates_the_forward_tail() {
1093        let mut pane = Pane::new(PathBuf::from("/a"));
1094        pane.navigate_to(PathBuf::from("/b"));
1095        pane.go_back();
1096        // Branching from A to C makes B unreachable.
1097        pane.navigate_to(PathBuf::from("/c"));
1098
1099        assert!(!pane.can_go_forward());
1100        assert!(!pane.go_forward());
1101        assert_eq!(pane.cwd, PathBuf::from("/c"));
1102
1103        // Back now leads to A, not B.
1104        assert!(pane.go_back());
1105        assert_eq!(pane.cwd, PathBuf::from("/a"));
1106    }
1107
1108    #[test]
1109    fn back_at_the_start_of_history_does_nothing() {
1110        let mut pane = Pane::new(PathBuf::from("/a"));
1111
1112        assert!(!pane.can_go_back());
1113        assert!(!pane.go_back());
1114        assert_eq!(pane.cwd, PathBuf::from("/a"));
1115    }
1116
1117    #[test]
1118    fn forward_without_going_back_does_nothing() {
1119        let mut pane = Pane::new(PathBuf::from("/a"));
1120        pane.navigate_to(PathBuf::from("/b"));
1121
1122        assert!(!pane.can_go_forward());
1123        assert!(!pane.go_forward());
1124        assert_eq!(pane.cwd, PathBuf::from("/b"));
1125    }
1126
1127    #[test]
1128    fn navigating_to_the_current_directory_is_not_recorded() {
1129        let mut pane = Pane::new(PathBuf::from("/a"));
1130        pane.navigate_to(PathBuf::from("/a"));
1131
1132        // Re-entering where we already are must not create a history step
1133        // that back would then have to walk through.
1134        assert!(!pane.can_go_back());
1135    }
1136
1137    #[test]
1138    fn history_survives_several_steps_in_both_directions() {
1139        let mut pane = Pane::new(PathBuf::from("/a"));
1140        pane.navigate_to(PathBuf::from("/b"));
1141        pane.navigate_to(PathBuf::from("/c"));
1142
1143        assert!(pane.go_back());
1144        assert!(pane.go_back());
1145        assert_eq!(pane.cwd, PathBuf::from("/a"));
1146
1147        assert!(pane.go_forward());
1148        assert!(pane.go_forward());
1149        assert_eq!(pane.cwd, PathBuf::from("/c"));
1150    }
1151
1152    #[test]
1153    fn history_is_per_pane() {
1154        let mut dp = DualPane::new("/left".into(), "/right".into());
1155        dp.left.navigate_to(PathBuf::from("/left/sub"));
1156
1157        assert!(dp.left.can_go_back());
1158        assert!(!dp.right.can_go_back());
1159    }
1160
1161    #[test]
1162    fn set_filter_with_a_blank_pattern_clears_it() {
1163        let mut pane = Pane::new(std::env::temp_dir());
1164        pane.set_filter("*.rs");
1165        assert!(pane.filter.is_some());
1166
1167        pane.set_filter("   ");
1168        assert!(pane.filter.is_none());
1169    }
1170
1171    #[test]
1172    fn directories_stay_name_sorted_regardless_of_sort_key() {
1173        let dir = std::env::temp_dir().join("oxinav_test_sort_dirs_stable");
1174        std::fs::create_dir_all(dir.join("b_dir")).unwrap();
1175        std::fs::create_dir_all(dir.join("a_dir")).unwrap();
1176
1177        let mut pane = Pane::new(dir.clone());
1178        pane.sort_key = SortKey::Size;
1179        pane.load_entries();
1180
1181        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
1182        assert_eq!(names, vec!["a_dir", "b_dir"]);
1183
1184        std::fs::remove_dir_all(&dir).ok();
1185    }
1186
1187    #[test]
1188    fn sort_key_labels_round_trip() {
1189        for key in [SortKey::Name, SortKey::Size, SortKey::Modified] {
1190            assert_eq!(SortKey::from_label(key.label()), Some(key));
1191        }
1192    }
1193
1194    #[test]
1195    fn sort_key_from_label_ignores_case_and_padding() {
1196        assert_eq!(SortKey::from_label(" Modified "), Some(SortKey::Modified));
1197    }
1198
1199    #[test]
1200    fn sort_key_from_label_is_none_for_an_unknown_word() {
1201        assert_eq!(SortKey::from_label("colour"), None);
1202        assert_eq!(SortKey::from_label(""), None);
1203    }
1204}