Skip to main content

oxinav_core/
pane.rs

1use std::path::PathBuf;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct Entry {
5    pub name: String,
6    pub path: PathBuf,
7    pub is_dir: bool,
8}
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum PaneId {
12    Left,
13    Right,
14}
15
16impl PaneId {
17    pub fn other(self) -> Self {
18        match self {
19            PaneId::Left => PaneId::Right,
20            PaneId::Right => PaneId::Left,
21        }
22    }
23}
24
25#[derive(Debug, Clone)]
26pub struct Pane {
27    pub cwd: PathBuf,
28    pub entries: Vec<Entry>,
29    pub cursor: usize,
30    pub last_error: Option<String>,
31    pub scroll_offset: usize,
32}
33
34impl Pane {
35    pub fn new(cwd: PathBuf) -> Self {
36        Self {
37            cwd,
38            entries: Vec::new(),
39            cursor: 0,
40            last_error: None,
41            scroll_offset: 0,
42        }
43    }
44
45    pub fn move_cursor_up(&mut self) {
46        if self.cursor > 0 {
47            self.cursor -= 1;
48            if self.cursor < self.scroll_offset {
49                self.scroll_offset = self.cursor;
50            }
51        }
52    }
53
54    pub fn move_cursor_down(&mut self) {
55        if !self.entries.is_empty() && self.cursor < self.entries.len() - 1 {
56            self.cursor += 1;
57            // Ensure cursor is within visible range; keep it centered by keeping 5 items below
58            const VISIBLE_ITEMS: usize = 20;
59            const KEEP_BELOW: usize = 5;
60            if self.cursor >= self.scroll_offset + VISIBLE_ITEMS - KEEP_BELOW {
61                self.scroll_offset = self.cursor.saturating_sub(VISIBLE_ITEMS - KEEP_BELOW - 1);
62            }
63        }
64    }
65
66    /// Keep the cursor in the visible viewport (for when viewport size changes or entries are reloaded)
67    pub fn ensure_cursor_visible(&mut self, visible_items: usize) {
68        if self.cursor < self.scroll_offset {
69            self.scroll_offset = self.cursor;
70        } else if self.cursor >= self.scroll_offset + visible_items {
71            self.scroll_offset = self.cursor.saturating_sub(visible_items - 1);
72        }
73    }
74
75    pub fn selected(&self) -> Option<&Entry> {
76        self.entries.get(self.cursor)
77    }
78
79    /// Load entries from the current working directory.
80    /// Sorts directories first (alphabetical), then files (alphabetical).
81    /// Excludes "." but includes ".." (parent directory) if not at root.
82    pub fn load_entries(&mut self) {
83        self.last_error = None;
84        self.entries.clear();
85        self.cursor = 0;
86        self.scroll_offset = 0;
87
88        // Try to read directory entries
89        match std::fs::read_dir(&self.cwd) {
90            Ok(entries_iter) => {
91                let mut dirs = Vec::new();
92                let mut files = Vec::new();
93
94                // Collect entries, skipping "." and errors
95                for entry_result in entries_iter {
96                    match entry_result {
97                        Ok(entry) => {
98                            let file_name = entry.file_name();
99                            let name = file_name.to_string_lossy().to_string();
100
101                            // Skip "." but don't skip ".."
102                            if name == "." {
103                                continue;
104                            }
105
106                            let path = entry.path();
107                            let is_dir = entry.metadata().map(|m| m.is_dir()).unwrap_or(false);
108
109                            let entry_item = Entry { name, path, is_dir };
110                            if is_dir {
111                                dirs.push(entry_item);
112                            } else {
113                                files.push(entry_item);
114                            }
115                        }
116                        Err(e) => {
117                            self.last_error = Some(format!("Error reading entry: {}", e));
118                        }
119                    }
120                }
121
122                // Sort both collections alphabetically
123                dirs.sort_by(|a, b| a.name.cmp(&b.name));
124                files.sort_by(|a, b| a.name.cmp(&b.name));
125
126                // Add ".." first if not at root
127                if self.cwd.parent().is_some() {
128                    self.entries.push(Entry {
129                        name: "..".to_string(),
130                        path: self.cwd.parent().unwrap().to_path_buf(),
131                        is_dir: true,
132                    });
133                }
134
135                // Combine: directories, then files
136                self.entries.extend(dirs);
137                self.entries.extend(files);
138            }
139            Err(e) => {
140                self.last_error = Some(format!("Cannot read directory: {}", e));
141            }
142        }
143    }
144
145    /// Enter the selected directory. If selection is not a directory, does nothing.
146    pub fn enter_directory(&mut self) {
147        if let Some(entry) = self.selected() {
148            if entry.is_dir {
149                self.cwd = entry.path.clone();
150                self.load_entries();
151            }
152        }
153    }
154
155    /// Navigate to the parent directory. Does nothing if already at root.
156    pub fn goto_parent(&mut self) {
157        if let Some(parent) = self.cwd.parent() {
158            self.cwd = parent.to_path_buf();
159            self.load_entries();
160        }
161    }
162}
163
164#[derive(Debug, Clone)]
165pub struct DualPane {
166    pub left: Pane,
167    pub right: Pane,
168    pub active: PaneId,
169}
170
171impl DualPane {
172    pub fn new(left_cwd: PathBuf, right_cwd: PathBuf) -> Self {
173        Self {
174            left: Pane::new(left_cwd),
175            right: Pane::new(right_cwd),
176            active: PaneId::Left,
177        }
178    }
179
180    pub fn active_pane(&self) -> &Pane {
181        match self.active {
182            PaneId::Left => &self.left,
183            PaneId::Right => &self.right,
184        }
185    }
186
187    pub fn active_pane_mut(&mut self) -> &mut Pane {
188        match self.active {
189            PaneId::Left => &mut self.left,
190            PaneId::Right => &mut self.right,
191        }
192    }
193
194    pub fn switch_active(&mut self) {
195        self.active = self.active.other();
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn cursor_does_not_go_below_zero() {
205        let mut pane = Pane::new(PathBuf::from("/tmp"));
206        pane.move_cursor_up();
207        assert_eq!(pane.cursor, 0);
208    }
209
210    #[test]
211    fn cursor_does_not_exceed_entries() {
212        let mut pane = Pane::new(PathBuf::from("/tmp"));
213        pane.entries = vec![Entry {
214            name: "a".into(),
215            path: "/tmp/a".into(),
216            is_dir: false,
217        }];
218        pane.move_cursor_down();
219        pane.move_cursor_down();
220        assert_eq!(pane.cursor, 0);
221    }
222
223    #[test]
224    fn switch_active_toggles_pane() {
225        let mut dp = DualPane::new("/".into(), "/tmp".into());
226        assert_eq!(dp.active, PaneId::Left);
227        dp.switch_active();
228        assert_eq!(dp.active, PaneId::Right);
229        dp.switch_active();
230        assert_eq!(dp.active, PaneId::Left);
231    }
232
233    #[test]
234    fn load_entries_sorts_directories_first() {
235        let mut pane = Pane::new(std::env::temp_dir());
236        pane.load_entries();
237
238        // Verify structure: all dirs should come before all files
239        let mut found_file = false;
240        for entry in &pane.entries {
241            if !entry.is_dir {
242                found_file = true;
243            } else if found_file {
244                panic!("Found directory after file; sort order violated");
245            }
246        }
247
248        // Also verify alphabetical within each group
249        let mut prev_dir: Option<&str> = None;
250        for entry in &pane.entries {
251            if entry.is_dir {
252                if let Some(prev) = prev_dir {
253                    assert!(
254                        prev <= entry.name.as_str(),
255                        "Directories not sorted alphabetically"
256                    );
257                }
258                prev_dir = Some(&entry.name);
259            }
260        }
261    }
262
263    #[test]
264    fn enter_directory_changes_cwd() {
265        // Use a real temp directory for this test
266        let temp_dir = std::env::temp_dir();
267        let mut pane = Pane::new(temp_dir.clone());
268
269        // Create an entry pointing to a real directory
270        pane.entries = vec![Entry {
271            name: "test_entry".into(),
272            path: temp_dir.clone(),
273            is_dir: true,
274        }];
275        pane.cursor = 0;
276
277        pane.enter_directory();
278
279        // The cwd should update to the selected entry's path
280        assert_eq!(pane.cwd, temp_dir);
281    }
282
283    #[test]
284    fn goto_parent_navigates_up() {
285        let mut pane = Pane::new(PathBuf::from("/tmp/some/nested/path"));
286        let parent = pane.cwd.parent().unwrap().to_path_buf();
287
288        pane.goto_parent();
289
290        assert_eq!(pane.cwd, parent);
291    }
292
293    #[test]
294    fn goto_parent_at_root_does_nothing() {
295        let mut pane = Pane::new(PathBuf::from("/"));
296        let _original_cwd = pane.cwd.clone();
297
298        pane.goto_parent();
299
300        assert_eq!(pane.cwd, PathBuf::from("/"));
301    }
302}