Skip to main content

nsh_core/
file_dialog.rs

1//! The system's file dialogs and file manager for local paths: the open
2//! and save dialogs ([`OpenDialog`], [`SaveDialog`]; shown with
3//! [`crate::element::pick_paths`] and [`crate::element::pick_save_path`]),
4//! opening a file or folder in its default app, showing it in the file
5//! manager and moving it to the trash ([`crate::element::open_path`],
6//! [`crate::element::reveal_path`], [`crate::element::move_to_trash`]), as
7//! GPUI's `prompt_for_paths`, `prompt_for_new_path`, `open_with_system` and
8//! `reveal_path` are.
9//!
10//! Each request is a [`Command::FileRequest`](crate::Command::FileRequest)
11//! on the root with a [`FileRequest`]; the platform carries it out
12//! (AppKit's `NSOpenPanel`, `NSSavePanel`, `NSWorkspace` and
13//! `NSFileManager`; GTK's `GtkFileDialog`, `GtkFileLauncher` and
14//! `g_file_trash`; the shell's `IFileOpenDialog`, `IFileSaveDialog`,
15//! `ShellExecuteW`, `SHOpenFolderAndSelectItems` and `IFileOperation`;
16//! GPUI's prompts and openers) and answers with the root's
17//! [`EventKind::FileRequest`](crate::EventKind::FileRequest), whose
18//! [`EventPayload::FileRequest`](crate::EventPayload::FileRequest) carries
19//! the paths and the error, if any ([`EventPayload::file_answer`],
20//! [`EventPayload::file_failed`]).
21//!
22//! Only platforms whose
23//! [`Environment::file_requests`](crate::platform::Environment::file_requests)
24//! is set get these commands. Desktops support the full set; iOS and
25//! Android support the open dialog, returning app-owned copies without
26//! reading their contents into memory. Android also supports opening paths.
27//! Unsupported requests (including all requests on the web) answer with
28//! an error.
29//!
30//! These services are Rust's only: no module of the runtime exposes them to
31//! an app's JS, so only native code (an app's own crate, `nsh-base`) asks,
32//! which reaches the filesystem anyway, and no capability gates them. The
33//! dialogs only give what the user chose.
34
35use std::path::{Path, PathBuf};
36
37use crate::EventPayload;
38
39/// What the open dialog lets the user pick ([`OpenDialog::kind`]).
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41#[non_exhaustive]
42pub enum OpenDialogKind {
43    /// Files.
44    #[default]
45    Files,
46    /// Folders.
47    Folders,
48    /// Files and folders alike, where the platform's dialog can (macOS);
49    /// files elsewhere.
50    FilesAndFolders,
51}
52
53/// A group of file types a dialog offers, shown by its name: `Markdown`
54/// for `md` and `markdown`.
55#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub struct FileFilter {
58    /// What the dialog shows for it (`"Markdown"`).
59    pub name: String,
60    /// Its file extensions, without the dot, lower case (`"md"`); never
61    /// empty.
62    pub extensions: Vec<String>,
63}
64
65impl FileFilter {
66    /// The files of `extensions` (`"md"`, `".md"` or `"*.md"`, any case),
67    /// shown as `name`.
68    pub fn new(
69        name: impl Into<String>,
70        extensions: impl IntoIterator<Item = impl Into<String>>,
71    ) -> Self {
72        let mut filter = FileFilter {
73            name: name.into(),
74            extensions: extensions.into_iter().map(Into::into).collect(),
75        };
76        normalize(&mut filter.extensions);
77        filter
78    }
79
80    /// Whether `path`'s extension is one of the filter's, for platforms
81    /// whose dialogs cannot filter (GPUI's).
82    pub fn matches(&self, path: &Path) -> bool {
83        path.extension()
84            .and_then(|e| e.to_str())
85            .is_some_and(|e| self.extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
86    }
87}
88
89/// Whether `path` passes `filters`: any file when there are none.
90pub fn passes(filters: &[FileFilter], path: &Path) -> bool {
91    filters.is_empty() || filters.iter().any(|f| f.matches(path))
92}
93
94/// The open dialog ([`crate::element::pick_paths`]):
95///
96/// ```ignore
97/// let picked = pick_paths(
98///     OpenDialog::files()
99///         .multiple(true)
100///         .filter(FileFilter::new("Markdown", ["md", "markdown"]))
101///         .button_label("Open"),
102/// )
103/// .await;
104/// ```
105#[derive(Debug, Clone, PartialEq, Eq, Default)]
106#[non_exhaustive]
107pub struct OpenDialog {
108    /// What the user picks.
109    pub kind: OpenDialogKind,
110    /// The user may pick several.
111    pub multiple: bool,
112    /// The file types offered, the first chosen; none: any file. Ignored
113    /// when picking folders.
114    pub filters: Vec<FileFilter>,
115    /// The dialog's title; `None`: the system's. macOS shows none on a
116    /// dialog attached to the window: give a [`Self::button_label`] too.
117    pub title: Option<String>,
118    /// The label of the button that confirms (`"Link"`); `None`: the
119    /// system's (`Open`). GPUI's `prompt`.
120    pub button_label: Option<String>,
121    /// The folder the dialog starts in; `None`: the system's choice.
122    pub directory: Option<PathBuf>,
123}
124
125impl OpenDialog {
126    /// A dialog picking a file.
127    pub fn files() -> Self {
128        Self::default()
129    }
130
131    /// A dialog picking a folder.
132    pub fn folders() -> Self {
133        Self::of(OpenDialogKind::Folders)
134    }
135
136    /// A dialog picking a file or a folder where the platform can (macOS),
137    /// a file elsewhere.
138    pub fn files_and_folders() -> Self {
139        Self::of(OpenDialogKind::FilesAndFolders)
140    }
141
142    fn of(kind: OpenDialogKind) -> Self {
143        OpenDialog {
144            kind,
145            ..Self::default()
146        }
147    }
148
149    /// Whether the user may pick several.
150    pub fn multiple(mut self, multiple: bool) -> Self {
151        self.multiple = multiple;
152        self
153    }
154
155    /// Offers the file types of `filter`, after those given before.
156    pub fn filter(mut self, filter: FileFilter) -> Self {
157        push_filter(&mut self.filters, filter);
158        self
159    }
160
161    /// The dialog's title.
162    pub fn title(mut self, title: impl Into<String>) -> Self {
163        self.title = Some(title.into());
164        self
165    }
166
167    /// The label of the button that confirms.
168    pub fn button_label(mut self, label: impl Into<String>) -> Self {
169        self.button_label = Some(label.into());
170        self
171    }
172
173    /// The folder the dialog starts in.
174    pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
175        self.directory = Some(directory.into());
176        self
177    }
178
179    /// Whether the user picks folders (with files or not).
180    pub fn picks_folders(&self) -> bool {
181        self.kind != OpenDialogKind::Files
182    }
183
184    /// Whether the user picks files (with folders or not).
185    pub fn picks_files(&self) -> bool {
186        self.kind != OpenDialogKind::Folders
187    }
188}
189
190/// The save dialog ([`crate::element::pick_save_path`]):
191///
192/// ```ignore
193/// let path = pick_save_path(
194///     SaveDialog::new()
195///         .file_name("Untitled.md")
196///         .filter(FileFilter::new("Markdown", ["md"])),
197/// )
198/// .await;
199/// ```
200#[derive(Debug, Clone, PartialEq, Eq, Default)]
201#[non_exhaustive]
202pub struct SaveDialog {
203    /// The file name suggested (`"Untitled.md"`); `None`: none.
204    pub file_name: Option<String>,
205    /// The file types the file may have, the first chosen; none: any.
206    pub filters: Vec<FileFilter>,
207    /// The dialog's title; `None`: the system's.
208    pub title: Option<String>,
209    /// The label of the button that confirms (`"Export"`); `None`: the
210    /// system's (`Save`).
211    pub button_label: Option<String>,
212    /// The folder the dialog starts in; `None`: the system's choice.
213    pub directory: Option<PathBuf>,
214}
215
216impl SaveDialog {
217    /// A save dialog with the system's defaults.
218    pub fn new() -> Self {
219        Self::default()
220    }
221
222    /// The file name suggested.
223    pub fn file_name(mut self, name: impl Into<String>) -> Self {
224        self.file_name = Some(name.into());
225        self
226    }
227
228    /// Offers the file types of `filter`, after those given before.
229    pub fn filter(mut self, filter: FileFilter) -> Self {
230        push_filter(&mut self.filters, filter);
231        self
232    }
233
234    /// The dialog's title.
235    pub fn title(mut self, title: impl Into<String>) -> Self {
236        self.title = Some(title.into());
237        self
238    }
239
240    /// The label of the button that confirms.
241    pub fn button_label(mut self, label: impl Into<String>) -> Self {
242        self.button_label = Some(label.into());
243        self
244    }
245
246    /// The folder the dialog starts in.
247    pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
248        self.directory = Some(directory.into());
249        self
250    }
251}
252
253/// The file extensions of all `filters`, each once, for platforms whose
254/// dialogs take one list.
255pub fn extensions(filters: &[FileFilter]) -> Vec<String> {
256    let mut all: Vec<String> = Vec::new();
257    for extension in filters.iter().flat_map(|f| &f.extensions) {
258        if !all.contains(extension) {
259            all.push(extension.clone());
260        }
261    }
262    all
263}
264
265/// What the platform is asked to do with local paths
266/// ([`crate::Command::FileRequest`]).
267#[derive(Debug, Clone, PartialEq, Eq)]
268#[non_exhaustive]
269pub enum FileRequest {
270    /// Show the open dialog: answer with the paths picked, none when
271    /// cancelled, or the error.
272    OpenDialog(OpenDialog),
273    /// Show the save dialog: answer with the path chosen, none when
274    /// cancelled, or the error.
275    SaveDialog(SaveDialog),
276    /// Open the file or folder in its default app: answer with no error
277    /// when it opened.
278    OpenPath(PathBuf),
279    /// Show the item selected in the file manager: answer with no error
280    /// when it showed.
281    RevealPath(PathBuf),
282    /// Move the item to the trash: answer with where it went when the
283    /// platform says (none otherwise), or the error.
284    MoveToTrash(PathBuf),
285}
286
287/// Adds `filter` unless it has no extensions left.
288fn push_filter(filters: &mut Vec<FileFilter>, filter: FileFilter) {
289    if !filter.extensions.is_empty() {
290        filters.push(filter);
291    }
292}
293
294/// `extensions` as the dialogs take them: without leading dots or `*.`,
295/// lower case, each once, empty ones left out.
296fn normalize(extensions: &mut Vec<String>) {
297    for extension in extensions.iter_mut() {
298        let trimmed = extension
299            .trim()
300            .trim_start_matches('*')
301            .trim_start_matches('.');
302        *extension = trimmed.to_lowercase();
303    }
304    extensions.retain(|e| !e.is_empty());
305    let mut seen = Vec::with_capacity(extensions.len());
306    extensions.retain(|e| {
307        let new = !seen.contains(e);
308        if new {
309            seen.push(e.clone());
310        }
311        new
312    });
313}
314
315impl EventPayload {
316    /// The answer to file request `id` that succeeded with `paths`: those
317    /// picked, the one chosen to save to, where a trashed item went, or
318    /// none (cancelled, or nothing to say).
319    pub fn file_answer(id: u32, paths: Vec<PathBuf>) -> EventPayload {
320        EventPayload::FileRequest {
321            id,
322            paths,
323            error: None,
324        }
325    }
326
327    /// The answer to file request `id` that failed, with why.
328    pub fn file_failed(id: u32, error: impl Into<String>) -> EventPayload {
329        EventPayload::FileRequest {
330            id,
331            paths: Vec::new(),
332            error: Some(error.into()),
333        }
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn filters_lose_dots_case_and_empty_extensions() {
343        let filter = FileFilter::new("Markdown", [".MD", "*.markdown", "", "md", " txt "]);
344        assert_eq!(filter.extensions, ["md", "markdown", "txt"]);
345        assert!(filter.matches(Path::new("/a/B.Markdown")));
346        assert!(!filter.matches(Path::new("/a/b.rs")));
347
348        let dialog = OpenDialog::files()
349            .filter(filter)
350            .filter(FileFilter::new("Nothing", [".", ""]))
351            .filter(FileFilter::new("Text", ["TXT", "log"]));
352        assert_eq!(
353            dialog.filters.len(),
354            2,
355            "a filter without extensions is left out"
356        );
357        assert_eq!(
358            extensions(&dialog.filters),
359            ["md", "markdown", "txt", "log"]
360        );
361        assert!(passes(&dialog.filters, Path::new("/a/b.log")));
362        assert!(!passes(&dialog.filters, Path::new("/a/b")));
363        assert!(passes(&[], Path::new("/a/b")));
364    }
365
366    #[test]
367    fn open_dialog_kinds() {
368        assert!(OpenDialog::files().picks_files() && !OpenDialog::files().picks_folders());
369        assert!(!OpenDialog::folders().picks_files() && OpenDialog::folders().picks_folders());
370        let both = OpenDialog::files_and_folders();
371        assert!(both.picks_files() && both.picks_folders());
372    }
373}