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