oxinav-core 0.2.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
use std::collections::HashSet;
use std::path::PathBuf;
use std::time::SystemTime;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    pub name: String,
    pub path: PathBuf,
    pub is_dir: bool,
    pub size: u64,
    pub modified: Option<SystemTime>,
}

/// Key used to sort files within a pane. Directories are always sorted by
/// name regardless of this setting, since size/modified-time comparisons
/// aren't meaningful for a directory without a recursive scan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    Name,
    Size,
    Modified,
}

impl SortKey {
    pub fn label(self) -> &'static str {
        match self {
            SortKey::Name => "name",
            SortKey::Size => "size",
            SortKey::Modified => "modified",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneId {
    Left,
    Right,
}

impl PaneId {
    pub fn other(self) -> Self {
        match self {
            PaneId::Left => PaneId::Right,
            PaneId::Right => PaneId::Left,
        }
    }
}

/// Whether `name` satisfies the listing filter `pattern`.
///
/// A pattern holding `*` or `?` is matched as a glob against the whole name;
/// one holding neither is matched as a substring, since a bare word like
/// `cargo` is nearly always meant as "names containing this" rather than as
/// an exact name. Both modes ignore case.
pub fn matches_filter(name: &str, pattern: &str) -> bool {
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return true;
    }

    let name = name.to_lowercase();
    let pattern = pattern.to_lowercase();

    if pattern.contains(['*', '?']) {
        glob_match(&name, &pattern)
    } else {
        name.contains(&pattern)
    }
}

/// Two-pointer wildcard match: `*` spans any run of characters, `?` exactly
/// one. On a mismatch it backtracks to the last `*` and gives it one more
/// character, so no recursion is involved and a pathological pattern cannot
/// blow the stack. Both inputs are expected to be lowercased already.
fn glob_match(name: &str, pattern: &str) -> bool {
    let name: Vec<char> = name.chars().collect();
    let pattern: Vec<char> = pattern.chars().collect();

    let (mut n, mut p) = (0, 0);
    let mut star: Option<usize> = None;
    let mut resume = 0;

    while n < name.len() {
        match pattern.get(p) {
            Some('*') => {
                star = Some(p);
                resume = n;
                p += 1;
            }
            Some('?') => {
                p += 1;
                n += 1;
            }
            Some(c) if *c == name[n] => {
                p += 1;
                n += 1;
            }
            _ => match star {
                Some(s) => {
                    p = s + 1;
                    resume += 1;
                    n = resume;
                }
                None => return false,
            },
        }
    }

    // Whatever is left of the pattern can only still match the empty
    // remainder if it is nothing but `*`.
    pattern[p..].iter().all(|c| *c == '*')
}

#[derive(Debug, Clone)]
pub struct Pane {
    pub cwd: PathBuf,
    pub entries: Vec<Entry>,
    pub cursor: usize,
    pub scroll_offset: usize,
    pub show_hidden: bool,
    pub selected: HashSet<usize>,
    pub sort_key: SortKey,
    pub sort_reversed: bool,
    /// Name filter narrowing the listing; `None` lists everything.
    pub filter: Option<String>,
    /// Every entry read from `cwd`, before the hidden-file rule and the
    /// filter narrow it. Kept so that re-deriving the listing — which an
    /// inline filter does on every keystroke — never touches the disk again.
    all_entries: Vec<Entry>,
    /// Directories this pane has visited, oldest first. Always non-empty:
    /// `history[history_index]` is the current `cwd`.
    history: Vec<PathBuf>,
    /// Position within `history`; everything after it is forward history.
    history_index: usize,
}

impl Pane {
    pub fn new(cwd: PathBuf) -> Self {
        Self {
            history: vec![cwd.clone()],
            history_index: 0,
            cwd,
            entries: Vec::new(),
            cursor: 0,
            scroll_offset: 0,
            show_hidden: false,
            selected: HashSet::new(),
            sort_key: SortKey::Name,
            sort_reversed: false,
            filter: None,
            all_entries: Vec::new(),
        }
    }

    /// Move to `path`, recording it in history.
    ///
    /// Navigating somewhere new after going back discards the forward tail:
    /// the branch not taken is no longer reachable, which is how every
    /// back/forward stack behaves.
    pub fn navigate_to(&mut self, path: PathBuf) {
        if path == self.cwd {
            return;
        }
        self.history.truncate(self.history_index + 1);
        self.history.push(path.clone());
        self.history_index = self.history.len() - 1;
        self.cwd = path;
        self.load_entries();
    }

    /// Step back to the previously visited directory. Returns whether there
    /// was anywhere to go.
    pub fn go_back(&mut self) -> bool {
        if self.history_index == 0 {
            return false;
        }
        self.history_index -= 1;
        self.cwd = self.history[self.history_index].clone();
        self.load_entries();
        true
    }

    /// Step forward again after going back.
    pub fn go_forward(&mut self) -> bool {
        if self.history_index + 1 >= self.history.len() {
            return false;
        }
        self.history_index += 1;
        self.cwd = self.history[self.history_index].clone();
        self.load_entries();
        true
    }

    pub fn can_go_back(&self) -> bool {
        self.history_index > 0
    }

    pub fn can_go_forward(&self) -> bool {
        self.history_index + 1 < self.history.len()
    }

    /// Sets the sort key directly. If the requested key is already active,
    /// toggles the sort direction instead (the "press again to reverse"
    /// convention used by clickable column headers).
    pub fn set_sort_key(&mut self, key: SortKey) {
        if self.sort_key == key {
            self.sort_reversed = !self.sort_reversed;
        } else {
            self.sort_key = key;
        }
        self.apply_view();
    }

    pub fn toggle_hidden_files(&mut self) {
        self.show_hidden = !self.show_hidden;
        self.apply_view();
    }

    /// Sets the name filter, or clears it when `pattern` is blank — so
    /// submitting an empty prompt is the same as clearing.
    pub fn set_filter(&mut self, pattern: &str) {
        let pattern = pattern.trim();
        self.filter = if pattern.is_empty() {
            None
        } else {
            Some(pattern.to_string())
        };
        self.apply_view();
    }

    pub fn clear_filter(&mut self) {
        self.filter = None;
        self.apply_view();
    }

    pub fn move_cursor_up(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
            if self.cursor < self.scroll_offset {
                self.scroll_offset = self.cursor;
            }
        }
    }

    pub fn move_cursor_down(&mut self) {
        if !self.entries.is_empty() && self.cursor < self.entries.len() - 1 {
            self.cursor += 1;
            // Ensure cursor is within visible range; keep it centered by keeping 5 items below
            const VISIBLE_ITEMS: usize = 20;
            const KEEP_BELOW: usize = 5;
            if self.cursor >= self.scroll_offset + VISIBLE_ITEMS - KEEP_BELOW {
                self.scroll_offset = self.cursor.saturating_sub(VISIBLE_ITEMS - KEEP_BELOW - 1);
            }
        }
    }

    /// Keep the cursor in the visible viewport (for when viewport size changes or entries are reloaded)
    pub fn ensure_cursor_visible(&mut self, visible_items: usize) {
        if self.cursor < self.scroll_offset {
            self.scroll_offset = self.cursor;
        } else if self.cursor >= self.scroll_offset + visible_items {
            self.scroll_offset = self.cursor.saturating_sub(visible_items - 1);
        }
    }

    pub fn selected(&self) -> Option<&Entry> {
        self.entries.get(self.cursor)
    }

    pub fn toggle_selection(&mut self) {
        if self.entries.get(self.cursor).map_or(true, |e| e.name == "..") {
            return;
        }
        if !self.selected.remove(&self.cursor) {
            self.selected.insert(self.cursor);
        }
    }

    pub fn extend_selection_down(&mut self) {
        if self.entries.get(self.cursor).map_or(false, |e| e.name != "..") {
            self.selected.insert(self.cursor);
        }
        self.move_cursor_down();
    }

    pub fn extend_selection_up(&mut self) {
        if self.entries.get(self.cursor).map_or(false, |e| e.name != "..") {
            self.selected.insert(self.cursor);
        }
        self.move_cursor_up();
    }

    pub fn clear_selection(&mut self) {
        self.selected.clear();
    }

    /// Move the cursor to the first entry (other than "..") whose name starts with
    /// `query`, case-insensitively. Leaves the cursor untouched if nothing matches.
    /// Returns whether a match was found.
    pub fn jump_to_prefix(&mut self, query: &str) -> bool {
        if query.is_empty() {
            return false;
        }
        let query = query.to_lowercase();
        match self
            .entries
            .iter()
            .position(|e| e.name != ".." && e.name.to_lowercase().starts_with(&query))
        {
            Some(index) => {
                self.cursor = index;
                true
            }
            None => false,
        }
    }

    /// Returns the tagged indices (sorted), or `[cursor]` if nothing is tagged.
    pub fn effective_selection(&self) -> Vec<usize> {
        if self.selected.is_empty() {
            vec![self.cursor]
        } else {
            let mut indices: Vec<usize> = self.selected.iter().copied().collect();
            indices.sort_unstable();
            indices
        }
    }

    /// Load entries from the current working directory.
    /// Read `cwd` from disk into the entry cache, then derive the listing.
    /// The read is the expensive half, so anything that only changes *how*
    /// entries are presented — sort, hidden files, the filter — goes through
    /// `apply_view` instead of coming back here.
    pub fn load_entries(&mut self) {
        self.all_entries.clear();

        // An unreadable directory yields an empty listing rather than an error.
        if let Ok(entries_iter) = std::fs::read_dir(&self.cwd) {
            for entry_result in entries_iter {
                let Ok(entry) = entry_result else {
                    continue;
                };
                let file_name = entry.file_name();
                let name = file_name.to_string_lossy().to_string();

                // Skip "." but don't skip ".."
                if name == "." {
                    continue;
                }

                let path = entry.path();
                let metadata = entry.metadata().ok();
                let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
                let size = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
                let modified = metadata.as_ref().and_then(|m| m.modified().ok());

                self.all_entries.push(Entry {
                    name,
                    path,
                    is_dir,
                    size,
                    modified,
                });
            }
        }

        self.apply_view();
    }

    /// Rebuild the visible listing from the cached read: drop hidden files,
    /// apply the filter, sort directories-then-files, and prepend the
    /// synthetic `..`. Touches no I/O, so it is cheap enough to run on every
    /// keystroke of an inline filter.
    ///
    /// Sorts directories first (alphabetical), then files by the active sort
    /// key. Excludes "." but includes ".." (parent directory) if not at root.
    fn apply_view(&mut self) {
        self.entries.clear();
        self.cursor = 0;
        self.scroll_offset = 0;
        self.selected.clear();

        let mut dirs: Vec<Entry> = Vec::new();
        let mut files: Vec<Entry> = Vec::new();

        for entry in &self.all_entries {
            if !self.show_hidden && entry.name.starts_with('.') {
                continue;
            }

            // Narrows what is listed, on top of the hidden-file rule above and
            // the sort below. `..` is prepended further down, so it is never
            // subject to this.
            if let Some(pattern) = &self.filter {
                if !matches_filter(&entry.name, pattern) {
                    continue;
                }
            }

            if entry.is_dir {
                dirs.push(entry.clone());
            } else {
                files.push(entry.clone());
            }
        }

        // Directories are always sorted by name; size/modified aren't
        // meaningful for a directory without a recursive scan.
        dirs.sort_by(|a, b| a.name.cmp(&b.name));

        match self.sort_key {
            SortKey::Name => files.sort_by(|a, b| a.name.cmp(&b.name)),
            SortKey::Size => files.sort_by_key(|f| f.size),
            SortKey::Modified => files.sort_by_key(|f| f.modified),
        }
        if self.sort_reversed {
            files.reverse();
        }

        // Add ".." first if not at root
        if let Some(parent) = self.cwd.parent() {
            self.entries.push(Entry {
                name: "..".to_string(),
                path: parent.to_path_buf(),
                is_dir: true,
                size: 0,
                modified: None,
            });
        }

        // Combine: directories, then files
        self.entries.extend(dirs);
        self.entries.extend(files);
    }

    /// Enter the selected directory. If selection is not a directory, does nothing.
    pub fn enter_directory(&mut self) {
        if let Some(entry) = self.selected() {
            if entry.is_dir {
                let target = entry.path.clone();
                self.navigate_to(target);
            }
        }
    }

    /// Navigate to the parent directory. Does nothing if already at root.
    pub fn goto_parent(&mut self) {
        if let Some(parent) = self.cwd.parent() {
            let target = parent.to_path_buf();
            self.navigate_to(target);
        }
    }
}

#[derive(Debug, Clone)]
pub struct DualPane {
    pub left: Pane,
    pub right: Pane,
    pub active: PaneId,
}

impl DualPane {
    pub fn new(left_cwd: PathBuf, right_cwd: PathBuf) -> Self {
        Self {
            left: Pane::new(left_cwd),
            right: Pane::new(right_cwd),
            active: PaneId::Left,
        }
    }

    pub fn active_pane(&self) -> &Pane {
        match self.active {
            PaneId::Left => &self.left,
            PaneId::Right => &self.right,
        }
    }

    pub fn active_pane_mut(&mut self) -> &mut Pane {
        match self.active {
            PaneId::Left => &mut self.left,
            PaneId::Right => &mut self.right,
        }
    }

    pub fn switch_active(&mut self) {
        self.active = self.active.other();
    }

    pub fn toggle_hidden_files(&mut self) {
        self.left.toggle_hidden_files();
        self.right.toggle_hidden_files();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cursor_does_not_go_below_zero() {
        let mut pane = Pane::new(PathBuf::from("/tmp"));
        pane.move_cursor_up();
        assert_eq!(pane.cursor, 0);
    }

    #[test]
    fn hidden_files_are_hidden_by_default() {
        let pane = Pane::new(PathBuf::from("/tmp"));
        assert!(!pane.show_hidden);
    }

    #[test]
    fn toggle_hidden_files_toggles_both_panes() {
        let mut dp = DualPane::new("/".into(), "/tmp".into());

        dp.toggle_hidden_files();

        assert!(dp.left.show_hidden);
        assert!(dp.right.show_hidden);

        dp.toggle_hidden_files();

        assert!(!dp.left.show_hidden);
        assert!(!dp.right.show_hidden);
    }

    /// Entry names excluding the synthetic `..`, in listing order.
    fn listed(pane: &Pane) -> Vec<&str> {
        pane.entries
            .iter()
            .filter(|e| e.name != "..")
            .map(|e| e.name.as_str())
            .collect()
    }

    #[test]
    fn cursor_does_not_exceed_entries() {
        let mut pane = Pane::new(PathBuf::from("/tmp"));
        pane.entries = vec![Entry {
            name: "a".into(),
            path: "/tmp/a".into(),
            is_dir: false,
            size: 0,
            modified: None,
        }];
        pane.move_cursor_down();
        pane.move_cursor_down();
        assert_eq!(pane.cursor, 0);
    }

    #[test]
    fn switch_active_toggles_pane() {
        let mut dp = DualPane::new("/".into(), "/tmp".into());
        assert_eq!(dp.active, PaneId::Left);
        dp.switch_active();
        assert_eq!(dp.active, PaneId::Right);
        dp.switch_active();
        assert_eq!(dp.active, PaneId::Left);
    }

    #[test]
    fn load_entries_sorts_directories_first() {
        let mut pane = Pane::new(std::env::temp_dir());
        pane.load_entries();

        // Verify structure: all dirs should come before all files
        let mut found_file = false;
        for entry in &pane.entries {
            if !entry.is_dir {
                found_file = true;
            } else if found_file {
                panic!("Found directory after file; sort order violated");
            }
        }

        // Also verify alphabetical within each group
        let mut prev_dir: Option<&str> = None;
        for entry in &pane.entries {
            if entry.is_dir {
                if let Some(prev) = prev_dir {
                    assert!(
                        prev <= entry.name.as_str(),
                        "Directories not sorted alphabetically"
                    );
                }
                prev_dir = Some(&entry.name);
            }
        }
    }

    #[test]
    fn enter_directory_changes_cwd() {
        // Use a real temp directory for this test
        let temp_dir = std::env::temp_dir();
        let mut pane = Pane::new(temp_dir.clone());

        // Create an entry pointing to a real directory
        pane.entries = vec![Entry {
            name: "test_entry".into(),
            path: temp_dir.clone(),
            is_dir: true,
            size: 0,
            modified: None,
        }];
        pane.cursor = 0;

        pane.enter_directory();

        // The cwd should update to the selected entry's path
        assert_eq!(pane.cwd, temp_dir);
    }

    #[test]
    fn goto_parent_navigates_up() {
        let mut pane = Pane::new(PathBuf::from("/tmp/some/nested/path"));
        let parent = pane.cwd.parent().unwrap().to_path_buf();

        pane.goto_parent();

        assert_eq!(pane.cwd, parent);
    }

    #[test]
    fn goto_parent_at_root_does_nothing() {
        let mut pane = Pane::new(PathBuf::from("/"));
        let _original_cwd = pane.cwd.clone();

        pane.goto_parent();

        assert_eq!(pane.cwd, PathBuf::from("/"));
    }

    fn pane_with_entries(names: &[&str]) -> Pane {
        let mut pane = Pane::new(PathBuf::from("/tmp"));
        pane.entries = names
            .iter()
            .map(|n| Entry {
                name: n.to_string(),
                path: PathBuf::from(format!("/tmp/{n}")),
                is_dir: false,
                size: 0,
                modified: None,
            })
            .collect();
        pane
    }

    #[test]
    fn toggle_selection_marks_and_unmarks() {
        let mut pane = pane_with_entries(&["a", "b", "c"]);
        pane.toggle_selection();
        assert!(pane.selected.contains(&0));
        pane.toggle_selection();
        assert!(!pane.selected.contains(&0));
    }

    #[test]
    fn toggle_selection_skips_parent_entry() {
        let mut pane = Pane::new(PathBuf::from("/tmp"));
        pane.entries = vec![Entry {
            name: "..".into(),
            path: "/".into(),
            is_dir: true,
            size: 0,
            modified: None,
        }];
        pane.toggle_selection();
        assert!(pane.selected.is_empty());
    }

    #[test]
    fn effective_selection_returns_cursor_when_nothing_tagged() {
        let mut pane = pane_with_entries(&["a", "b", "c"]);
        pane.cursor = 2;
        assert_eq!(pane.effective_selection(), vec![2]);
    }

    #[test]
    fn effective_selection_returns_sorted_tagged_indices() {
        let mut pane = pane_with_entries(&["a", "b", "c"]);
        pane.selected.insert(2);
        pane.selected.insert(0);
        assert_eq!(pane.effective_selection(), vec![0, 2]);
    }

    #[test]
    fn extend_selection_down_tags_current_and_advances_cursor() {
        let mut pane = pane_with_entries(&["a", "b", "c"]);
        pane.extend_selection_down();
        assert!(pane.selected.contains(&0));
        assert_eq!(pane.cursor, 1);
    }

    #[test]
    fn extend_selection_up_tags_current_and_moves_cursor_up() {
        let mut pane = pane_with_entries(&["a", "b", "c"]);
        pane.cursor = 2;
        pane.extend_selection_up();
        assert!(pane.selected.contains(&2));
        assert_eq!(pane.cursor, 1);
    }

    #[test]
    fn load_entries_clears_selection() {
        let mut pane = Pane::new(std::env::temp_dir());
        pane.selected.insert(0);
        pane.selected.insert(1);
        pane.load_entries();
        assert!(pane.selected.is_empty());
    }

    #[test]
    fn jump_to_prefix_moves_cursor_to_match() {
        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
        assert!(pane.jump_to_prefix("ban"));
        assert_eq!(pane.cursor, 1);
    }

    #[test]
    fn jump_to_prefix_is_case_insensitive() {
        let mut pane = pane_with_entries(&["Apple", "Banana", "Cherry"]);
        assert!(pane.jump_to_prefix("cher"));
        assert_eq!(pane.cursor, 2);
    }

    #[test]
    fn jump_to_prefix_no_match_leaves_cursor_and_returns_false() {
        let mut pane = pane_with_entries(&["apple", "banana", "cherry"]);
        pane.cursor = 1;
        assert!(!pane.jump_to_prefix("zzz"));
        assert_eq!(pane.cursor, 1);
    }

    #[test]
    fn jump_to_prefix_skips_parent_entry() {
        let mut pane = Pane::new(PathBuf::from("/tmp"));
        pane.entries = vec![
            Entry {
                name: "..".into(),
                path: "/".into(),
                is_dir: true,
                size: 0,
                modified: None,
            },
            Entry {
                name: "docs".into(),
                path: "/tmp/docs".into(),
                is_dir: true,
                size: 0,
                modified: None,
            },
        ];
        pane.cursor = 1;
        assert!(!pane.jump_to_prefix(".."));
        assert_eq!(pane.cursor, 1);
    }

    #[test]
    fn set_sort_key_changes_key_and_leaves_direction() {
        let mut pane = Pane::new(std::env::temp_dir());
        pane.sort_reversed = true;
        pane.set_sort_key(SortKey::Size);
        assert_eq!(pane.sort_key, SortKey::Size);
        assert!(pane.sort_reversed);
    }

    #[test]
    fn set_sort_key_toggles_direction_when_key_already_active() {
        let mut pane = Pane::new(std::env::temp_dir());
        assert_eq!(pane.sort_key, SortKey::Name);
        assert!(!pane.sort_reversed);

        pane.set_sort_key(SortKey::Name);
        assert_eq!(pane.sort_key, SortKey::Name);
        assert!(pane.sort_reversed);

        pane.set_sort_key(SortKey::Name);
        assert_eq!(pane.sort_key, SortKey::Name);
        assert!(!pane.sort_reversed);
    }

    #[test]
    fn set_sort_key_reorders_entries() {
        let dir = std::env::temp_dir().join("oxinav_test_set_sort_key_reorders");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();
        pane.set_sort_key(SortKey::Size);

        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
        assert_eq!(names, vec!["small.txt", "big.txt"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn sorts_files_by_size() {
        let dir = std::env::temp_dir().join("oxinav_test_sort_by_size");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("big.txt"), vec![0u8; 100]).unwrap();
        std::fs::write(dir.join("small.txt"), vec![0u8; 10]).unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.sort_key = SortKey::Size;
        pane.load_entries();

        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
        assert_eq!(names, vec!["small.txt", "big.txt"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn sorts_files_reversed() {
        let dir = std::env::temp_dir().join("oxinav_test_sort_reversed");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("a.txt"), b"a").unwrap();
        std::fs::write(dir.join("b.txt"), b"b").unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.sort_reversed = true;
        pane.load_entries();

        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
        assert_eq!(names, vec!["b.txt", "a.txt"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    // --- filtering ---

    #[test]
    fn bare_pattern_matches_as_a_substring() {
        assert!(matches_filter("Cargo.toml", "cargo"));
        assert!(matches_filter("main.rs", ".rs"));
        assert!(!matches_filter("main.rs", "toml"));
    }

    #[test]
    fn wildcard_pattern_matches_as_a_glob_over_the_whole_name() {
        assert!(matches_filter("main.rs", "*.rs"));
        assert!(!matches_filter("main.rsx", "*.rs"));
        assert!(matches_filter("Cargo.toml", "cargo*"));
        assert!(!matches_filter("build.rs", "cargo*"));
    }

    #[test]
    fn question_mark_matches_exactly_one_character() {
        assert!(matches_filter("a.rs", "?.rs"));
        assert!(!matches_filter("ab.rs", "?.rs"));
    }

    #[test]
    fn matching_ignores_case_in_both_modes() {
        assert!(matches_filter("README.MD", "readme"));
        assert!(matches_filter("README.MD", "*.md"));
    }

    #[test]
    fn blank_pattern_matches_everything() {
        assert!(matches_filter("anything", ""));
        assert!(matches_filter("anything", "   "));
    }

    #[test]
    fn consecutive_stars_do_not_change_the_match() {
        assert!(matches_filter("main.rs", "**.rs"));
        assert!(matches_filter("main.rs", "*"));
    }

    #[test]
    fn set_filter_narrows_the_listing_and_clear_restores_it() {
        let dir = std::env::temp_dir().join("oxinav_test_filter_narrows");
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("main.rs"), b"a").unwrap();
        std::fs::write(dir.join("lib.rs"), b"b").unwrap();
        std::fs::write(dir.join("Cargo.toml"), b"c").unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();
        pane.set_filter("*.rs");

        let names = listed(&pane);
        assert_eq!(names, vec!["lib.rs", "main.rs"]);

        pane.clear_filter();
        assert_eq!(listed(&pane), vec!["Cargo.toml", "lib.rs", "main.rs"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn parent_entry_survives_a_filter_matching_nothing() {
        let dir = std::env::temp_dir().join("oxinav_test_filter_keeps_parent");
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("main.rs"), b"a").unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();
        pane.set_filter("*.nomatch");

        assert!(listed(&pane).is_empty());
        // `..` is the only thing left, so navigating up is still possible.
        let all: Vec<&str> = pane.entries.iter().map(|e| e.name.as_str()).collect();
        assert_eq!(all, vec![".."]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn filter_composes_with_the_hidden_files_toggle() {
        let dir = std::env::temp_dir().join("oxinav_test_filter_hidden");
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("visible.rs"), b"a").unwrap();
        std::fs::write(dir.join(".hidden.rs"), b"b").unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();
        pane.set_filter("*.rs");
        assert_eq!(listed(&pane), vec!["visible.rs"]);

        // Revealing hidden files widens the set the filter then narrows.
        pane.toggle_hidden_files();
        assert_eq!(listed(&pane), vec![".hidden.rs", "visible.rs"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn filter_composes_with_the_active_sort_key() {
        let dir = std::env::temp_dir().join("oxinav_test_filter_sort");
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("big.rs"), vec![0u8; 100]).unwrap();
        std::fs::write(dir.join("small.rs"), vec![0u8; 10]).unwrap();
        std::fs::write(dir.join("huge.toml"), vec![0u8; 999]).unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();
        pane.set_filter("*.rs");
        pane.set_sort_key(SortKey::Size);

        // Sorted by size, and the excluded .toml stays excluded.
        assert_eq!(listed(&pane), vec!["small.rs", "big.rs"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn filter_applies_to_directories_too() {
        let dir = std::env::temp_dir().join("oxinav_test_filter_dirs");
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::create_dir_all(dir.join("target")).unwrap();
        std::fs::write(dir.join("main.rs"), b"a").unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();
        pane.set_filter("*.rs");

        assert_eq!(listed(&pane), vec!["main.rs"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn refiltering_does_not_re_read_the_directory() {
        let dir = std::env::temp_dir().join("oxinav_test_filter_no_reread");
        std::fs::remove_dir_all(&dir).ok();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("main.rs"), b"a").unwrap();
        std::fs::write(dir.join("notes.txt"), b"b").unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.load_entries();

        // Delete the directory out from under the pane. Re-filtering now can
        // only succeed if it works off the cached read, which is what makes
        // it cheap enough to run on every keystroke.
        std::fs::remove_dir_all(&dir).ok();

        pane.set_filter("*.rs");
        assert_eq!(listed(&pane), vec!["main.rs"]);

        pane.clear_filter();
        assert_eq!(listed(&pane), vec!["main.rs", "notes.txt"]);
    }

    // --- directory history ---

    #[test]
    fn back_returns_to_the_previous_directory() {
        let mut pane = Pane::new(PathBuf::from("/a"));
        pane.navigate_to(PathBuf::from("/b"));
        assert_eq!(pane.cwd, PathBuf::from("/b"));

        assert!(pane.go_back());
        assert_eq!(pane.cwd, PathBuf::from("/a"));
    }

    #[test]
    fn forward_returns_after_going_back() {
        let mut pane = Pane::new(PathBuf::from("/a"));
        pane.navigate_to(PathBuf::from("/b"));
        pane.go_back();

        assert!(pane.go_forward());
        assert_eq!(pane.cwd, PathBuf::from("/b"));
    }

    #[test]
    fn navigating_anew_truncates_the_forward_tail() {
        let mut pane = Pane::new(PathBuf::from("/a"));
        pane.navigate_to(PathBuf::from("/b"));
        pane.go_back();
        // Branching from A to C makes B unreachable.
        pane.navigate_to(PathBuf::from("/c"));

        assert!(!pane.can_go_forward());
        assert!(!pane.go_forward());
        assert_eq!(pane.cwd, PathBuf::from("/c"));

        // Back now leads to A, not B.
        assert!(pane.go_back());
        assert_eq!(pane.cwd, PathBuf::from("/a"));
    }

    #[test]
    fn back_at_the_start_of_history_does_nothing() {
        let mut pane = Pane::new(PathBuf::from("/a"));

        assert!(!pane.can_go_back());
        assert!(!pane.go_back());
        assert_eq!(pane.cwd, PathBuf::from("/a"));
    }

    #[test]
    fn forward_without_going_back_does_nothing() {
        let mut pane = Pane::new(PathBuf::from("/a"));
        pane.navigate_to(PathBuf::from("/b"));

        assert!(!pane.can_go_forward());
        assert!(!pane.go_forward());
        assert_eq!(pane.cwd, PathBuf::from("/b"));
    }

    #[test]
    fn navigating_to_the_current_directory_is_not_recorded() {
        let mut pane = Pane::new(PathBuf::from("/a"));
        pane.navigate_to(PathBuf::from("/a"));

        // Re-entering where we already are must not create a history step
        // that back would then have to walk through.
        assert!(!pane.can_go_back());
    }

    #[test]
    fn history_survives_several_steps_in_both_directions() {
        let mut pane = Pane::new(PathBuf::from("/a"));
        pane.navigate_to(PathBuf::from("/b"));
        pane.navigate_to(PathBuf::from("/c"));

        assert!(pane.go_back());
        assert!(pane.go_back());
        assert_eq!(pane.cwd, PathBuf::from("/a"));

        assert!(pane.go_forward());
        assert!(pane.go_forward());
        assert_eq!(pane.cwd, PathBuf::from("/c"));
    }

    #[test]
    fn history_is_per_pane() {
        let mut dp = DualPane::new("/left".into(), "/right".into());
        dp.left.navigate_to(PathBuf::from("/left/sub"));

        assert!(dp.left.can_go_back());
        assert!(!dp.right.can_go_back());
    }

    #[test]
    fn set_filter_with_a_blank_pattern_clears_it() {
        let mut pane = Pane::new(std::env::temp_dir());
        pane.set_filter("*.rs");
        assert!(pane.filter.is_some());

        pane.set_filter("   ");
        assert!(pane.filter.is_none());
    }

    #[test]
    fn directories_stay_name_sorted_regardless_of_sort_key() {
        let dir = std::env::temp_dir().join("oxinav_test_sort_dirs_stable");
        std::fs::create_dir_all(dir.join("b_dir")).unwrap();
        std::fs::create_dir_all(dir.join("a_dir")).unwrap();

        let mut pane = Pane::new(dir.clone());
        pane.sort_key = SortKey::Size;
        pane.load_entries();

        let names: Vec<&str> = pane.entries.iter().filter(|e| e.name != "..").map(|e| e.name.as_str()).collect();
        assert_eq!(names, vec!["a_dir", "b_dir"]);

        std::fs::remove_dir_all(&dir).ok();
    }
}