Skip to main content

kitchen_shell/
picker.rs

1//! The file picker's model: one folder at a time, what is in it, and what the app can open there.
2//! No window: [`crate::picker_view::FilePickerView`] draws it, and the tests drive it directly.
3//!
4//! File → Open… (and only that item) brings the picker up. The app says what it opens
5//! ([`FileKind`]: a name and the extensions; some "files" are folders, a Zarr store or an image
6//! sequence, and open as one). In a folder the picker lists the subfolders first, then what the app
7//! opens, and hides the rest unless "Show all files" is on (shown greyed, not openable). Hidden
8//! entries (a leading dot) are left out.
9
10use std::cmp::Ordering;
11use std::path::{Path, PathBuf};
12use std::time::SystemTime;
13
14use gpui_kit::assets::IconName;
15use kitchen_ui::icons::standard;
16
17/// What an app opens: a name for people and the extensions that are one.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct FileKind {
20    /// Shown in the picker's list and its footer ("Recording", "Zarr store").
21    pub name: String,
22    /// Extensions without the dot, lowercase (`nwb`, `zarr`, `ome.tiff`).
23    pub extensions: Vec<String>,
24    /// Whether these are folders that open as one (a Zarr store, an image sequence).
25    pub folder: bool,
26    /// Its icon in the list.
27    pub icon: IconName,
28}
29
30impl FileKind {
31    /// Files named `*.<ext>` for each of `extensions`.
32    pub fn new(name: impl Into<String>, extensions: &[&str]) -> Self {
33        Self { name: name.into(), extensions: extensions.iter().map(|e| e.trim_start_matches('.').to_lowercase()).collect(), folder: false, icon: IconName::File }
34    }
35
36    /// Folders named `*.<ext>` that open as one (a Zarr store).
37    pub fn folder(name: impl Into<String>, extensions: &[&str]) -> Self {
38        Self { folder: true, icon: IconName::Folder, ..Self::new(name, extensions) }
39    }
40
41    /// The same kind with another icon.
42    pub fn icon(mut self, icon: IconName) -> Self {
43        self.icon = icon;
44        self
45    }
46
47    /// Whether `name` (a file's or a folder's, `is_dir` saying which) is one of these. Longer
48    /// extensions count (`scan.ome.tiff` is `ome.tiff`), and case does not matter.
49    pub fn matches(&self, name: &str, is_dir: bool) -> bool {
50        if is_dir != self.folder {
51            return false;
52        }
53        let lower = name.to_lowercase();
54        self.extensions.iter().any(|e| lower.len() > e.len() + 1 && lower.ends_with(e.as_str()) && lower.as_bytes()[lower.len() - e.len() - 1] == b'.')
55    }
56}
57
58/// What an entry of the folder is.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum EntryKind {
61    /// A folder to go into.
62    Folder,
63    /// Something the app opens: the index of its [`FileKind`].
64    Opens(usize),
65    /// Anything else (listed only with "Show all files", and not openable).
66    Other,
67}
68
69/// One entry of the folder shown.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct Entry {
72    /// Its file name.
73    pub name: String,
74    /// Its full path.
75    pub path: PathBuf,
76    /// What it is.
77    pub kind: EntryKind,
78    /// Its size in bytes (files only).
79    pub size: Option<u64>,
80    /// When it last changed.
81    pub modified: Option<SystemTime>,
82}
83
84/// A place in the picker's left column: home, the desktop, downloads, a recent file's folder.
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct Place {
87    /// Its name.
88    pub name: String,
89    /// Where it is.
90    pub path: PathBuf,
91    /// Its icon.
92    pub icon: IconName,
93}
94
95/// The places on this computer that exist: home, Desktop, Documents, Downloads, then the file
96/// system's root.
97pub fn places() -> Vec<Place> {
98    let mut out = Vec::new();
99    if let Some(home) = home_dir() {
100        out.push(Place { name: "Home".into(), path: home.clone(), icon: standard::HOME });
101        for (name, icon) in [("Desktop", standard::DESKTOP), ("Documents", IconName::FileText), ("Downloads", standard::DOWNLOADS)] {
102            let path = home.join(name);
103            if path.is_dir() {
104                out.push(Place { name: name.into(), path, icon });
105            }
106        }
107    }
108    let root = if cfg!(windows) { PathBuf::from("C:\\") } else { PathBuf::from("/") };
109    out.push(Place { name: "Computer".into(), path: root, icon: IconName::HardDrive });
110    out
111}
112
113/// The user's home folder, if the environment names one.
114pub fn home_dir() -> Option<PathBuf> {
115    std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).filter(|p| p.is_dir())
116}
117
118/// `1.2 MB`, `340 kB`, `12 B` (powers of 1000, as file managers show them).
119pub fn human_size(bytes: u64) -> String {
120    const UNITS: [&str; 5] = ["kB", "MB", "GB", "TB", "PB"];
121    if bytes < 1000 {
122        return format!("{bytes} B");
123    }
124    let mut v = bytes as f64 / 1000.0;
125    let mut unit = 0;
126    while v >= 1000.0 && unit < UNITS.len() - 1 {
127        v /= 1000.0;
128        unit += 1;
129    }
130    if v < 10.0 { format!("{v:.1} {}", UNITS[unit]) } else { format!("{v:.0} {}", UNITS[unit]) }
131}
132
133/// The picker's state: the folder shown, its entries, the selection.
134#[derive(Clone, Debug)]
135pub struct Picker {
136    kinds: Vec<FileKind>,
137    dir: PathBuf,
138    entries: Vec<Entry>,
139    error: Option<String>,
140    show_all: bool,
141    selected: Option<usize>,
142    recent: Vec<PathBuf>,
143}
144
145impl Picker {
146    /// A picker for `kinds` showing `start` (or, if it cannot be read, home, then the root).
147    pub fn new(kinds: Vec<FileKind>, start: impl Into<PathBuf>) -> Self {
148        let mut picker = Picker { kinds, dir: PathBuf::new(), entries: Vec::new(), error: None, show_all: false, selected: None, recent: Vec::new() };
149        let start = start.into();
150        let fallbacks = [Some(start.clone()), home_dir(), places().last().map(|p| p.path.clone())];
151        let mut first_error = None;
152        for dir in fallbacks.into_iter().flatten() {
153            match picker.enter(&dir) {
154                Ok(()) => break,
155                Err(e) => {
156                    first_error.get_or_insert(e);
157                }
158            }
159        }
160        if picker.dir != start {
161            picker.error = first_error;
162        }
163        picker
164    }
165
166    /// The same picker listing `recent` files under Places (the app's recent files, newest first).
167    pub fn with_recent(mut self, recent: Vec<PathBuf>) -> Self {
168        self.recent = recent;
169        self
170    }
171
172    /// What the app opens.
173    pub fn kinds(&self) -> &[FileKind] {
174        &self.kinds
175    }
176
177    /// The folder shown.
178    pub fn dir(&self) -> &Path {
179        &self.dir
180    }
181
182    /// What is shown of the folder: folders first, then the rest, each by name (case ignored).
183    pub fn entries(&self) -> &[Entry] {
184        &self.entries
185    }
186
187    /// The app's recent files that still exist.
188    pub fn recent(&self) -> Vec<PathBuf> {
189        self.recent.iter().filter(|p| p.exists()).cloned().collect()
190    }
191
192    /// Why the last folder could not be shown (the picker stays where it was).
193    pub fn error(&self) -> Option<&str> {
194        self.error.as_deref()
195    }
196
197    /// Whether files the app does not open are listed (greyed).
198    pub fn show_all(&self) -> bool {
199        self.show_all
200    }
201
202    /// Lists, or hides, the files the app does not open.
203    pub fn set_show_all(&mut self, on: bool) {
204        if on != self.show_all {
205            self.show_all = on;
206            self.refresh();
207        }
208    }
209
210    /// The selected entry's index.
211    pub fn selected(&self) -> Option<usize> {
212        self.selected
213    }
214
215    /// The selected entry.
216    pub fn selected_entry(&self) -> Option<&Entry> {
217        self.selected.and_then(|i| self.entries.get(i))
218    }
219
220    /// Selects entry `i` (none if out of range).
221    pub fn select(&mut self, i: Option<usize>) {
222        self.selected = i.filter(|i| *i < self.entries.len());
223    }
224
225    /// What the Open button would open now: the selected entry, if the app opens it.
226    pub fn openable(&self) -> Option<PathBuf> {
227        self.selected_entry().filter(|e| matches!(e.kind, EntryKind::Opens(_))).map(|e| e.path.clone())
228    }
229
230    /// The breadcrumb: each folder from the root down to the one shown, with its path.
231    pub fn crumbs(&self) -> Vec<(String, PathBuf)> {
232        let mut out: Vec<(String, PathBuf)> = self
233            .dir
234            .ancestors()
235            .map(|p| {
236                let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.display().to_string());
237                (name, p.to_path_buf())
238            })
239            .collect();
240        out.reverse();
241        out
242    }
243
244    /// Shows the folder `dir`. When it cannot be read the picker stays where it was and says why.
245    pub fn enter(&mut self, dir: &Path) -> Result<(), String> {
246        match self.read(dir) {
247            Ok(entries) => {
248                self.dir = dir.to_path_buf();
249                self.entries = entries;
250                self.error = None;
251                self.selected = None;
252                Ok(())
253            }
254            Err(e) => {
255                self.error = Some(e.clone());
256                Err(e)
257            }
258        }
259    }
260
261    /// Shows the folder above; whether there is one.
262    pub fn up(&mut self) -> bool {
263        let Some(parent) = self.dir.parent().map(Path::to_path_buf) else { return false };
264        let from = self.dir.clone();
265        if self.enter(&parent).is_err() {
266            return false;
267        }
268        // Keep the folder just left selected, so going back down is one step
269        self.selected = self.entries.iter().position(|e| e.path == from);
270        true
271    }
272
273    /// Reads the folder again (after a change on disk), keeping the selection by path.
274    pub fn refresh(&mut self) {
275        let keep = self.selected_entry().map(|e| e.path.clone());
276        let dir = self.dir.clone();
277        if self.enter(&dir).is_ok() {
278            self.selected = keep.and_then(|p| self.entries.iter().position(|e| e.path == p));
279        }
280    }
281
282    /// What a double click (or Enter) on entry `i` does: a folder is entered (`None`); something
283    /// the app opens is returned, to open; anything else does nothing.
284    pub fn activate(&mut self, i: usize) -> Option<PathBuf> {
285        let entry = self.entries.get(i)?.clone();
286        match entry.kind {
287            EntryKind::Folder => {
288                let _ = self.enter(&entry.path);
289                None
290            }
291            EntryKind::Opens(_) => Some(entry.path),
292            EntryKind::Other => None,
293        }
294    }
295
296    /// The kind of `name`, given whether it is a folder.
297    pub fn kind_of(&self, name: &str, is_dir: bool) -> EntryKind {
298        if let Some(k) = self.kinds.iter().position(|k| k.matches(name, is_dir)) {
299            return EntryKind::Opens(k);
300        }
301        if is_dir { EntryKind::Folder } else { EntryKind::Other }
302    }
303
304    /// A line for the footer: what the app opens here ("Opens: Recording (.nwb), Zarr store (.zarr)").
305    pub fn opens_line(&self) -> String {
306        let kinds: Vec<String> = self.kinds.iter().map(|k| format!("{} ({})", k.name, k.extensions.iter().map(|e| format!(".{e}")).collect::<Vec<_>>().join(", "))).collect();
307        if kinds.is_empty() { "Opens any file".into() } else { format!("Opens: {}", kinds.join(", ")) }
308    }
309
310    fn read(&self, dir: &Path) -> Result<Vec<Entry>, String> {
311        let read = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
312        let mut out = Vec::new();
313        for item in read.flatten() {
314            let name = item.file_name().to_string_lossy().into_owned();
315            if name.starts_with('.') {
316                continue;
317            }
318            let path = item.path();
319            // Follow links: a linked folder is a folder
320            let meta = std::fs::metadata(&path).ok();
321            let is_dir = meta.as_ref().is_some_and(|m| m.is_dir());
322            let kind = if self.kinds.is_empty() && !is_dir { EntryKind::Opens(usize::MAX) } else { self.kind_of(&name, is_dir) };
323            if kind == EntryKind::Other && !self.show_all {
324                continue;
325            }
326            let size = meta.as_ref().filter(|m| m.is_file()).map(|m| m.len());
327            let modified = meta.as_ref().and_then(|m| m.modified().ok());
328            out.push(Entry { name, path, kind, size, modified });
329        }
330        out.sort_by(|a, b| match (a.kind == EntryKind::Folder, b.kind == EntryKind::Folder) {
331            (true, false) => Ordering::Less,
332            (false, true) => Ordering::Greater,
333            _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.name.cmp(&b.name)),
334        });
335        Ok(out)
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    fn scratch(name: &str) -> PathBuf {
344        let dir = std::env::temp_dir().join(format!("kitchen-picker-{name}-{}", std::process::id()));
345        let _ = std::fs::remove_dir_all(&dir);
346        std::fs::create_dir_all(&dir).unwrap();
347        dir
348    }
349
350    fn kinds() -> Vec<FileKind> {
351        vec![FileKind::new("Recording", &["nwb", "bin"]), FileKind::folder("Zarr store", &["zarr"]), FileKind::new("Slide", &["ome.tiff"])]
352    }
353
354    /// A project folder: two subfolders, a Zarr store, files the app opens and one it does not.
355    fn project(name: &str) -> PathBuf {
356        let dir = scratch(name);
357        std::fs::create_dir_all(dir.join("sessions/day1")).unwrap();
358        std::fs::create_dir_all(dir.join("Notes")).unwrap();
359        std::fs::create_dir_all(dir.join("probe.zarr")).unwrap();
360        std::fs::write(dir.join("b.nwb"), vec![0u8; 1500]).unwrap();
361        std::fs::write(dir.join("A.BIN"), b"12").unwrap();
362        std::fs::write(dir.join("scan.ome.tiff"), b"x").unwrap();
363        std::fs::write(dir.join("readme.txt"), b"hi").unwrap();
364        std::fs::write(dir.join(".hidden.nwb"), b"x").unwrap();
365        dir
366    }
367
368    fn names(p: &Picker) -> Vec<&str> {
369        p.entries().iter().map(|e| e.name.as_str()).collect()
370    }
371
372    #[test]
373    fn lists_folders_first_then_what_the_app_opens() {
374        let dir = project("list");
375        let p = Picker::new(kinds(), &dir);
376        assert_eq!(p.dir(), dir);
377        assert_eq!(names(&p), ["Notes", "sessions", "A.BIN", "b.nwb", "probe.zarr", "scan.ome.tiff"]);
378        let kinds: Vec<EntryKind> = p.entries().iter().map(|e| e.kind).collect();
379        assert_eq!(kinds, [EntryKind::Folder, EntryKind::Folder, EntryKind::Opens(0), EntryKind::Opens(0), EntryKind::Opens(1), EntryKind::Opens(2)]);
380        assert_eq!(p.entries()[3].size, Some(1500));
381        assert_eq!(p.entries()[0].size, None, "folders have no size");
382        assert!(p.error().is_none());
383    }
384
385    #[test]
386    fn show_all_lists_the_rest_greyed() {
387        let dir = project("all");
388        let mut p = Picker::new(kinds(), &dir);
389        p.set_show_all(true);
390        let txt = p.entries().iter().find(|e| e.name == "readme.txt").expect("listed");
391        assert_eq!(txt.kind, EntryKind::Other);
392        let i = p.entries().iter().position(|e| e.name == "readme.txt").unwrap();
393        p.select(Some(i));
394        assert_eq!(p.openable(), None, "not openable");
395        assert_eq!(p.activate(i), None);
396        assert!(!names(&p).contains(&".hidden.nwb"), "hidden entries stay hidden");
397    }
398
399    #[test]
400    fn enters_goes_up_and_keeps_the_way_back() {
401        let dir = project("walk");
402        let mut p = Picker::new(kinds(), &dir);
403        let sessions = p.entries().iter().position(|e| e.name == "sessions").unwrap();
404        assert_eq!(p.activate(sessions), None, "a folder is entered, not opened");
405        assert_eq!(p.dir(), dir.join("sessions"));
406        assert_eq!(names(&p), ["day1"]);
407        assert!(p.up());
408        assert_eq!(p.dir(), dir);
409        assert_eq!(p.selected_entry().map(|e| e.name.as_str()), Some("sessions"), "the folder just left is selected");
410        let crumbs = p.crumbs();
411        assert_eq!(crumbs.last().unwrap().1, dir);
412        assert!(crumbs.first().unwrap().1.parent().is_none(), "from the root");
413    }
414
415    #[test]
416    fn a_zarr_store_opens_as_one() {
417        let dir = project("zarr");
418        let mut p = Picker::new(kinds(), &dir);
419        let i = p.entries().iter().position(|e| e.name == "probe.zarr").unwrap();
420        p.select(Some(i));
421        assert_eq!(p.openable(), Some(dir.join("probe.zarr")));
422        assert_eq!(p.activate(i), Some(dir.join("probe.zarr")));
423        assert_eq!(p.dir(), dir, "not entered");
424    }
425
426    #[test]
427    fn an_empty_folder_and_one_that_cannot_be_read() {
428        let dir = scratch("empty");
429        let mut p = Picker::new(kinds(), &dir);
430        assert!(p.entries().is_empty());
431        assert!(p.error().is_none());
432        let missing = dir.join("gone");
433        assert!(p.enter(&missing).is_err());
434        assert_eq!(p.dir(), dir, "stays where it was");
435        assert!(p.error().unwrap().contains("gone"), "says which folder");
436        // Starting in a folder that cannot be read falls back, and says why
437        let q = Picker::new(kinds(), &missing);
438        assert_ne!(q.dir(), missing);
439        assert!(q.error().is_some());
440    }
441
442    #[test]
443    fn kinds_match_by_extension_and_shape() {
444        let k = kinds();
445        assert!(k[0].matches("rec.NWB", false));
446        assert!(!k[0].matches("rec.nwb", true), "a folder named .nwb is not a recording");
447        assert!(!k[0].matches(".nwb", false), "a name needs a stem");
448        assert!(k[1].matches("probe.zarr", true));
449        assert!(!k[1].matches("probe.zarr", false));
450        assert!(k[2].matches("scan.ome.tiff", false));
451        assert!(!k[2].matches("scan.tiff", false));
452        assert!(!k[2].matches("scanome.tiff", false));
453        let p = Picker::new(k, std::env::temp_dir());
454        assert_eq!(p.opens_line(), "Opens: Recording (.nwb, .bin), Zarr store (.zarr), Slide (.ome.tiff)");
455    }
456
457    #[test]
458    fn with_no_kinds_any_file_opens() {
459        let dir = project("any");
460        let p = Picker::new(Vec::new(), &dir);
461        assert!(names(&p).contains(&"readme.txt"));
462        assert!(p.entries().iter().filter(|e| e.kind != EntryKind::Folder).all(|e| matches!(e.kind, EntryKind::Opens(_))));
463    }
464
465    #[test]
466    fn sizes_read_like_a_file_manager() {
467        assert_eq!(human_size(12), "12 B");
468        assert_eq!(human_size(1500), "1.5 kB");
469        assert_eq!(human_size(340_000), "340 kB");
470        assert_eq!(human_size(1_200_000), "1.2 MB");
471        assert_eq!(human_size(25_000_000_000), "25 GB");
472    }
473}