1use crate::{Property, StandardButtonKind, VecModel};
2use std::{
3 cell::Cell,
4 collections::VecDeque,
5 fmt,
6 rc::Rc,
7 sync::atomic::{AtomicU64, Ordering},
8};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum FileDialogMode {
12 #[default]
13 OpenFile,
14 OpenFiles,
15 SaveFile,
16 SelectFolder,
17 SelectFolders,
18}
19
20#[derive(Debug, Default)]
21pub struct FileDialogOptions {
22 pub mode: FileDialogMode,
23 pub title: String,
24 pub directory: String,
25 pub file_name: String,
26 pub name_filters: Vec<String>,
27}
28
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum MessageLevel {
31 #[default]
32 Info,
33 Warning,
34 Error,
35}
36
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub enum MessageButtons {
39 #[default]
40 Ok,
41 OkCancel,
42 YesNo,
43 YesNoCancel,
44}
45
46#[derive(Debug, Default)]
47pub struct MessageDialogOptions {
48 pub level: MessageLevel,
49 pub buttons: MessageButtons,
50 pub title: String,
51 pub text: String,
52 pub informative_text: String,
53}
54
55#[doc(hidden)]
56#[derive(Debug)]
57pub enum NativeDialogOptions {
58 File(FileDialogOptions),
59 Message(MessageDialogOptions),
60}
61
62#[doc(hidden)]
63#[derive(Debug, PartialEq, Eq)]
64pub enum NativeDialogResult {
65 Files(Vec<String>),
66 Button(StandardButtonKind),
67 Canceled,
68 Failed(String),
69 Abandoned,
70}
71
72#[derive(Clone, Debug)]
73struct Request {
74 id: u64,
75 options: Rc<NativeDialogOptions>,
76}
77
78#[doc(hidden)]
80#[derive(Default)]
81pub struct NativeDialogSlot(Property<Option<Request>>);
82
83impl NativeDialogSlot {
84 pub fn pending(&self) -> bool {
85 self.0.get(|| None).is_some()
86 }
87
88 pub fn open(&self, options: impl FnOnce() -> NativeDialogOptions) {
89 if self.pending() {
90 return;
91 }
92 static NEXT: AtomicU64 = AtomicU64::new(1);
93 let id = NEXT
94 .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
95 .expect("native dialog request identities exhausted");
96 self.0.set(Some(Request {
97 id,
98 options: Rc::new(options()),
99 }));
100 }
101
102 pub fn register(
103 &self,
104 deliver: impl Fn(u64, NativeDialogResult) -> bool + 'static,
105 ) -> Option<NativeDialogRegistration> {
106 Some(NativeDialogRegistration {
107 request: self.0.get(|| None)?,
108 deliver: Rc::new(deliver),
109 })
110 }
111
112 pub fn finish(&self, id: u64) -> bool {
113 if self.0.get(|| None).is_none_or(|request| request.id != id) {
114 return false;
115 }
116 self.0.set(None);
117 true
118 }
119}
120
121#[doc(hidden)]
123#[derive(Default)]
124pub struct FileDialogSelection(Property<Rc<[String]>>);
125
126impl FileDialogSelection {
127 pub fn commit(&self, paths: &[String]) {
128 self.0.set_if_changed(Rc::from(paths));
129 }
130
131 pub fn selected_file(&self) -> String {
132 self.0.get(Rc::default).first().cloned().unwrap_or_default()
133 }
134
135 pub fn selected_files(&self) -> VecModel<String> {
136 VecModel::from(self.0.get(Rc::default).to_vec())
137 }
138}
139
140#[doc(hidden)]
141#[derive(Clone)]
142pub struct NativeDialogRegistration {
143 request: Request,
144 deliver: Rc<dyn Fn(u64, NativeDialogResult) -> bool>,
145}
146
147impl NativeDialogRegistration {
148 pub fn id(&self) -> u64 {
149 self.request.id
150 }
151
152 pub fn options(&self) -> Rc<NativeDialogOptions> {
153 self.request.options.clone()
154 }
155
156 pub fn deliver(self, result: NativeDialogResult) -> bool {
157 (self.deliver)(self.request.id, result)
158 }
159}
160
161impl fmt::Debug for NativeDialogRegistration {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 f.debug_struct("NativeDialogRegistration")
164 .field("id", &self.id())
165 .finish()
166 }
167}
168
169impl PartialEq for NativeDialogRegistration {
170 fn eq(&self, other: &Self) -> bool {
171 self.id() == other.id()
172 }
173}
174
175struct ActiveDialog {
176 registration: NativeDialogRegistration,
177 abandoned: Rc<Cell<bool>>,
178}
179
180#[doc(hidden)]
181pub struct NativeDialogPresentation {
182 pub id: u64,
183 pub options: Rc<NativeDialogOptions>,
184 abandoned: Rc<Cell<bool>>,
185}
186
187impl NativeDialogPresentation {
188 pub fn is_abandoned(&self) -> bool {
189 self.abandoned.get()
190 }
191}
192
193#[doc(hidden)]
195#[derive(Default)]
196pub struct NativeDialogQueue {
197 waiting: VecDeque<NativeDialogRegistration>,
198 active: Option<ActiveDialog>,
199}
200
201impl NativeDialogQueue {
202 pub fn close(&mut self) {
203 self.sync(&[]);
204 if let Some(active) = self.active.take() {
205 active.registration.deliver(NativeDialogResult::Abandoned);
206 }
207 }
208
209 pub fn sync(&mut self, live: &[&NativeDialogRegistration]) {
210 let is_live = |id| live.iter().any(|entry| entry.id() == id);
211 if let Some(active) = &self.active
212 && !is_live(active.registration.id())
213 {
214 active.abandoned.set(true);
215 }
216 self.waiting.retain(|entry| {
217 if !is_live(entry.id()) {
218 entry.clone().deliver(NativeDialogResult::Abandoned);
219 return false;
220 }
221 true
222 });
223 let queued = self.waiting.len();
224 for entry in live {
225 if self
226 .active
227 .as_ref()
228 .is_some_and(|active| active.registration.id() == entry.id())
229 || self.waiting.iter().any(|queued| queued.id() == entry.id())
230 {
231 continue;
232 }
233 self.waiting.push_back((*entry).clone());
234 }
235 if self.waiting.len() > queued {
236 self.waiting
238 .make_contiguous()
239 .sort_by_key(NativeDialogRegistration::id);
240 }
241 }
242
243 pub fn begin_next(&mut self) -> Option<NativeDialogPresentation> {
244 if self.active.is_some() {
245 return None;
246 }
247 let registration = self.waiting.pop_front()?;
248 let abandoned = Rc::new(Cell::new(false));
249 let request = NativeDialogPresentation {
250 id: registration.id(),
251 options: registration.options(),
252 abandoned: abandoned.clone(),
253 };
254 self.active = Some(ActiveDialog {
255 registration,
256 abandoned,
257 });
258 Some(request)
259 }
260
261 pub fn complete(&mut self, id: u64, result: NativeDialogResult) -> bool {
262 if self
263 .active
264 .as_ref()
265 .is_none_or(|active| active.registration.id() != id)
266 {
267 return false;
268 }
269 let active = self.active.take().expect("matching active native dialog");
270 active.registration.deliver(if active.abandoned.get() {
271 NativeDialogResult::Abandoned
272 } else {
273 result
274 });
275 true
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use super::FileDialogSelection;
282
283 #[test]
284 fn accepted_paths_are_independent_of_the_returned_model() {
285 let selection = FileDialogSelection::default();
286 assert!(selection.selected_file().is_empty());
287 assert!(selection.selected_files().is_empty());
288 selection.commit(&["/workspace/src".into(), "/workspace/tests".into()]);
289 let model = selection.selected_files();
290 assert!(model.set_row(0, "/modified".into()));
291 assert_eq!(selection.selected_file(), "/workspace/src");
292 assert_eq!(
293 selection.selected_files().snapshot(),
294 ["/workspace/src", "/workspace/tests"]
295 );
296 }
297}