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