Skip to main content

native_gui_core/
file_dialog.rs

1//! Function-style native file dialogs (found while dogfooding).
2//!
3//! [`crate::ui::Ui::show_file_dialog`] opens a native open/save/folder dialog
4//! described by a [`FileDialog`] request and returns a token; the answer
5//! arrives later as [`crate::events::UiEvent::FileDialogResponse`] with the
6//! chosen paths (empty when the user cancelled). Unlike the
7//! `WidgetKind::FileChooserDialog` button widget, nothing has to be created
8//! or attached to the widget tree, and the request carries a title, filters,
9//! a suggested file name and a starting folder.
10//!
11//! ```
12//! use native_gui_core::file_dialog::FileDialog;
13//!
14//! let request = FileDialog::save()
15//!     .title("Save jobs")
16//!     .filter("JSON", &["*.json"])
17//!     .suggested_name("jobs.json");
18//! assert_eq!(request.filters[0].patterns, vec!["*.json".to_owned()]);
19//! ```
20
21use std::path::PathBuf;
22
23use crate::error::{GuiError, GuiResult};
24use crate::widgets::FileChooserMode;
25
26/// A named file-type filter, e.g. `("JSON", ["*.json"])`.
27#[derive(Debug, Clone, PartialEq, Eq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct FileFilter {
30    /// Label shown in the dialog's filter picker.
31    pub name: String,
32    /// Glob patterns such as `*.json` (matched case-insensitively where the
33    /// platform supports it).
34    pub patterns: Vec<String>,
35}
36
37/// A native file-dialog request for [`crate::ui::Ui::show_file_dialog`].
38#[derive(Debug, Clone, PartialEq, Eq, Default)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct FileDialog {
41    /// Open an existing file, pick a folder, or choose a file to save.
42    pub mode: FileChooserMode,
43    /// For [`FileChooserMode::OpenFile`]: allow selecting several files.
44    pub multiple: bool,
45    /// Dialog title; `None` uses the platform default for the mode.
46    pub title: Option<String>,
47    /// File-type filters; the first one is selected initially.
48    pub filters: Vec<FileFilter>,
49    /// Pre-filled file name for save dialogs.
50    pub suggested_name: Option<String>,
51    /// Folder the dialog starts in.
52    pub folder: Option<PathBuf>,
53}
54
55impl FileDialog {
56    /// Choose one existing file.
57    pub fn open() -> Self {
58        Self {
59            mode: FileChooserMode::OpenFile,
60            ..Self::default()
61        }
62    }
63
64    /// Choose one or more existing files.
65    pub fn open_multiple() -> Self {
66        Self {
67            mode: FileChooserMode::OpenFile,
68            multiple: true,
69            ..Self::default()
70        }
71    }
72
73    /// Choose a (possibly new) file to write.
74    pub fn save() -> Self {
75        Self {
76            mode: FileChooserMode::SaveFile,
77            ..Self::default()
78        }
79    }
80
81    /// Choose a folder.
82    pub fn pick_folder() -> Self {
83        Self {
84            mode: FileChooserMode::PickFolder,
85            ..Self::default()
86        }
87    }
88
89    /// Sets the dialog title.
90    pub fn title(mut self, title: impl Into<String>) -> Self {
91        self.title = Some(title.into());
92        self
93    }
94
95    /// Adds a file-type filter (`name`, glob `patterns`).
96    pub fn filter(mut self, name: impl Into<String>, patterns: &[&str]) -> Self {
97        self.filters.push(FileFilter {
98            name: name.into(),
99            patterns: patterns
100                .iter()
101                .map(|pattern| (*pattern).to_owned())
102                .collect(),
103        });
104        self
105    }
106
107    /// Pre-fills the file name (save dialogs).
108    pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
109        self.suggested_name = Some(name.into());
110        self
111    }
112
113    /// Sets the folder the dialog starts in.
114    pub fn folder(mut self, folder: impl Into<PathBuf>) -> Self {
115        self.folder = Some(folder.into());
116        self
117    }
118
119    /// Validates the request: no embedded NUL bytes in any string, no empty
120    /// filter, and `multiple` only for open dialogs.
121    pub fn validate(&self) -> GuiResult<()> {
122        let mut strings: Vec<&str> = Vec::new();
123        strings.extend(self.title.as_deref());
124        strings.extend(self.suggested_name.as_deref());
125        for filter in &self.filters {
126            strings.push(&filter.name);
127            if filter.patterns.is_empty() {
128                return Err(GuiError::Backend(format!(
129                    "file dialog filter `{}` has no patterns",
130                    filter.name
131                )));
132            }
133            strings.extend(filter.patterns.iter().map(String::as_str));
134        }
135        if strings.iter().any(|value| value.contains('\0')) {
136            return Err(GuiError::Backend(
137                "file dialog strings must not contain NUL bytes".to_owned(),
138            ));
139        }
140        if self.multiple && self.mode != FileChooserMode::OpenFile {
141            return Err(GuiError::Backend(
142                "multiple selection is only valid for open-file dialogs".to_owned(),
143            ));
144        }
145        Ok(())
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn builder_collects_every_option() {
155        let request = FileDialog::save()
156            .title("Save jobs")
157            .filter("JSON", &["*.json"])
158            .filter("All files", &["*"])
159            .suggested_name("jobs.json")
160            .folder("/tmp");
161        assert_eq!(request.mode, FileChooserMode::SaveFile);
162        assert_eq!(request.title.as_deref(), Some("Save jobs"));
163        assert_eq!(request.filters.len(), 2);
164        assert_eq!(request.suggested_name.as_deref(), Some("jobs.json"));
165        assert_eq!(request.folder, Some(PathBuf::from("/tmp")));
166        assert!(request.validate().is_ok());
167    }
168
169    #[test]
170    fn validation_rejects_bad_requests() {
171        assert!(FileDialog::open().title("a\0b").validate().is_err());
172        assert!(FileDialog::open().filter("none", &[]).validate().is_err());
173        let mut multi_save = FileDialog::save();
174        multi_save.multiple = true;
175        assert!(multi_save.validate().is_err());
176        assert!(FileDialog::open_multiple().validate().is_ok());
177        assert!(FileDialog::pick_folder().validate().is_ok());
178    }
179}