Skip to main content

sui_platform/
file_dialog.rs

1use std::{
2    future::Future,
3    path::{Path, PathBuf},
4    pin::Pin,
5};
6
7#[cfg(all(
8    not(target_arch = "wasm32"),
9    any(target_os = "windows", target_os = "macos", target_os = "linux")
10))]
11use std::{
12    collections::HashMap,
13    sync::{Arc, Mutex, OnceLock, Weak},
14};
15
16use sui_core::{Error, Result, WindowId};
17
18#[cfg(all(
19    not(target_arch = "wasm32"),
20    any(target_os = "windows", target_os = "macos", target_os = "linux")
21))]
22use winit::window::Window;
23
24const RFD_SUPPORTED: bool = cfg!(any(
25    target_arch = "wasm32",
26    target_os = "windows",
27    target_os = "macos",
28    target_os = "linux"
29));
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum FileDialogMode {
33    OpenFile,
34    OpenFiles,
35    SaveFile,
36    OpenFolder,
37    OpenFolders,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct FileDialogFilter {
42    pub name: String,
43    pub extensions: Vec<String>,
44}
45
46impl FileDialogFilter {
47    pub fn new(
48        name: impl Into<String>,
49        extensions: impl IntoIterator<Item = impl Into<String>>,
50    ) -> Self {
51        Self {
52            name: name.into(),
53            extensions: extensions.into_iter().map(Into::into).collect(),
54        }
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct FileDialogRequest {
60    pub mode: FileDialogMode,
61    pub title: Option<String>,
62    pub filters: Vec<FileDialogFilter>,
63    pub initial_directory: Option<PathBuf>,
64    pub suggested_name: Option<String>,
65    pub can_create_directories: bool,
66    /// Logical SUI window that should own the native dialog.
67    ///
68    /// Native desktop hosts resolve this to a live window and retain it while
69    /// the returned dialog future is active. Web builds ignore this field.
70    pub parent_window: Option<WindowId>,
71}
72
73impl FileDialogRequest {
74    pub fn new(mode: FileDialogMode) -> Self {
75        Self {
76            mode,
77            title: None,
78            filters: Vec::new(),
79            initial_directory: None,
80            suggested_name: None,
81            can_create_directories: true,
82            parent_window: None,
83        }
84    }
85
86    pub fn title(mut self, title: impl Into<String>) -> Self {
87        self.title = Some(title.into());
88        self
89    }
90
91    pub fn filter(mut self, filter: FileDialogFilter) -> Self {
92        self.filters.push(filter);
93        self
94    }
95
96    pub fn initial_directory(mut self, directory: impl Into<PathBuf>) -> Self {
97        self.initial_directory = Some(directory.into());
98        self
99    }
100
101    pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
102        self.suggested_name = Some(name.into());
103        self
104    }
105
106    pub const fn can_create_directories(mut self, can_create: bool) -> Self {
107        self.can_create_directories = can_create;
108        self
109    }
110
111    pub const fn parent_window(mut self, window_id: WindowId) -> Self {
112        self.parent_window = Some(window_id);
113        self
114    }
115
116    pub const fn clear_parent_window(mut self) -> Self {
117        self.parent_window = None;
118        self
119    }
120}
121
122#[derive(Clone, Debug)]
123pub struct PlatformFile {
124    #[cfg(any(
125        target_arch = "wasm32",
126        target_os = "windows",
127        target_os = "macos",
128        target_os = "linux"
129    ))]
130    inner: rfd::FileHandle,
131    #[cfg(not(any(
132        target_arch = "wasm32",
133        target_os = "windows",
134        target_os = "macos",
135        target_os = "linux"
136    )))]
137    name: String,
138}
139
140impl PlatformFile {
141    pub fn file_name(&self) -> String {
142        #[cfg(any(
143            target_arch = "wasm32",
144            target_os = "windows",
145            target_os = "macos",
146            target_os = "linux"
147        ))]
148        {
149            self.inner.file_name()
150        }
151        #[cfg(not(any(
152            target_arch = "wasm32",
153            target_os = "windows",
154            target_os = "macos",
155            target_os = "linux"
156        )))]
157        {
158            self.name.clone()
159        }
160    }
161
162    pub fn path(&self) -> Option<&Path> {
163        #[cfg(all(
164            not(target_arch = "wasm32"),
165            any(target_os = "windows", target_os = "macos", target_os = "linux")
166        ))]
167        {
168            Some(self.inner.path())
169        }
170        #[cfg(not(all(
171            not(target_arch = "wasm32"),
172            any(target_os = "windows", target_os = "macos", target_os = "linux")
173        )))]
174        {
175            None
176        }
177    }
178
179    pub async fn read(&self) -> Result<Vec<u8>> {
180        #[cfg(any(
181            target_arch = "wasm32",
182            target_os = "windows",
183            target_os = "macos",
184            target_os = "linux"
185        ))]
186        {
187            Ok(self.inner.read().await)
188        }
189        #[cfg(not(any(
190            target_arch = "wasm32",
191            target_os = "windows",
192            target_os = "macos",
193            target_os = "linux"
194        )))]
195        {
196            Err(Error::new(
197                "file handles are not supported on this platform",
198            ))
199        }
200    }
201
202    pub async fn write(&self, data: &[u8]) -> Result<()> {
203        #[cfg(any(
204            target_arch = "wasm32",
205            target_os = "windows",
206            target_os = "macos",
207            target_os = "linux"
208        ))]
209        {
210            self.inner
211                .write(data)
212                .await
213                .map_err(|error| Error::new(format!("file write failed: {error}")))
214        }
215        #[cfg(not(any(
216            target_arch = "wasm32",
217            target_os = "windows",
218            target_os = "macos",
219            target_os = "linux"
220        )))]
221        {
222            let _ = data;
223            Err(Error::new(
224                "file handles are not supported on this platform",
225            ))
226        }
227    }
228}
229
230#[derive(Clone, Debug, Default)]
231pub struct FileDialogSelection {
232    pub files: Vec<PlatformFile>,
233}
234
235impl FileDialogSelection {
236    pub fn first(&self) -> Option<&PlatformFile> {
237        self.files.first()
238    }
239}
240
241#[cfg(not(target_arch = "wasm32"))]
242pub type FileDialogFuture =
243    Pin<Box<dyn Future<Output = Result<Option<FileDialogSelection>>> + Send + 'static>>;
244#[cfg(target_arch = "wasm32")]
245pub type FileDialogFuture =
246    Pin<Box<dyn Future<Output = Result<Option<FileDialogSelection>>> + 'static>>;
247
248pub trait FileDialogService {
249    /// Prepare and start a dialog operation.
250    ///
251    /// Call this method from the UI callback that initiated the request. The
252    /// native implementation constructs the rfd operation synchronously (as
253    /// required by macOS), then returns a `Send` future that may be polled by a
254    /// background executor. Web callers must create and begin polling the
255    /// returned local future during browser user activation.
256    fn show(&self, request: FileDialogRequest) -> FileDialogFuture;
257}
258
259#[derive(Debug, Clone, Copy, Default)]
260pub struct NativeFileDialogs;
261
262impl FileDialogService for NativeFileDialogs {
263    fn show(&self, request: FileDialogRequest) -> FileDialogFuture {
264        prepare_file_dialog(request)
265    }
266}
267
268/// Show a dialog from an async context.
269///
270/// Unlike [`FileDialogService::show`], construction is deferred until this
271/// future is first polled. UI callbacks that need macOS main-thread setup or
272/// browser user activation should call the service method instead.
273pub async fn show_file_dialog(request: FileDialogRequest) -> Result<Option<FileDialogSelection>> {
274    prepare_file_dialog(request).await
275}
276
277fn prepare_file_dialog(request: FileDialogRequest) -> FileDialogFuture {
278    if !RFD_SUPPORTED {
279        return Box::pin(async {
280            Err(Error::new(
281                "native file dialogs are not supported on this platform",
282            ))
283        });
284    }
285
286    #[cfg(any(
287        target_arch = "wasm32",
288        target_os = "windows",
289        target_os = "macos",
290        target_os = "linux"
291    ))]
292    {
293        let FileDialogRequest {
294            mode,
295            title,
296            filters,
297            initial_directory,
298            suggested_name,
299            can_create_directories,
300            parent_window,
301        } = request;
302        let mut dialog = rfd::AsyncFileDialog::new();
303        if let Some(title) = title {
304            dialog = dialog.set_title(title);
305        }
306        if let Some(name) = suggested_name {
307            dialog = dialog.set_file_name(name);
308        }
309        #[cfg(not(target_arch = "wasm32"))]
310        if let Some(directory) = initial_directory {
311            dialog = dialog.set_directory(directory);
312        }
313        #[cfg(target_arch = "wasm32")]
314        let _ = initial_directory;
315        dialog = dialog.set_can_create_directories(can_create_directories);
316        for filter in filters {
317            dialog = dialog.add_filter(filter.name, &filter.extensions);
318        }
319
320        #[cfg(all(
321            not(target_arch = "wasm32"),
322            any(target_os = "windows", target_os = "macos", target_os = "linux")
323        ))]
324        let parent_guard = if let Some(parent_window) = parent_window {
325            let Some(parent) = resolve_native_file_dialog_parent(parent_window) else {
326                return Box::pin(async move {
327                    Err(Error::new(format!(
328                        "file dialog parent window {} is no longer available",
329                        parent_window.get()
330                    )))
331                });
332            };
333            dialog = dialog.set_parent(parent.as_ref());
334            Some(parent)
335        } else {
336            None
337        };
338        #[cfg(target_arch = "wasm32")]
339        let parent_guard = {
340            let _ = parent_window;
341        };
342
343        match mode {
344            FileDialogMode::OpenFile => {
345                let operation = dialog.pick_file();
346                Box::pin(async move {
347                    let result = await_dialog_with_parent(parent_guard, operation).await;
348                    Ok(result.map(|file| selection(vec![file])))
349                })
350            }
351            FileDialogMode::OpenFiles => {
352                let operation = dialog.pick_files();
353                Box::pin(async move {
354                    let result = await_dialog_with_parent(parent_guard, operation).await;
355                    Ok(result.map(selection))
356                })
357            }
358            FileDialogMode::SaveFile => {
359                let operation = dialog.save_file();
360                Box::pin(async move {
361                    let result = await_dialog_with_parent(parent_guard, operation).await;
362                    Ok(result.map(|file| selection(vec![file])))
363                })
364            }
365            #[cfg(not(target_arch = "wasm32"))]
366            FileDialogMode::OpenFolder => {
367                let operation = dialog.pick_folder();
368                Box::pin(async move {
369                    let result = await_dialog_with_parent(parent_guard, operation).await;
370                    Ok(result.map(|file| selection(vec![file])))
371                })
372            }
373            #[cfg(not(target_arch = "wasm32"))]
374            FileDialogMode::OpenFolders => {
375                let operation = dialog.pick_folders();
376                Box::pin(async move {
377                    let result = await_dialog_with_parent(parent_guard, operation).await;
378                    Ok(result.map(selection))
379                })
380            }
381            #[cfg(target_arch = "wasm32")]
382            FileDialogMode::OpenFolder | FileDialogMode::OpenFolders => Box::pin(async {
383                Err(Error::new("folder dialogs are not available in web builds"))
384            }),
385        }
386    }
387
388    #[cfg(not(any(
389        target_arch = "wasm32",
390        target_os = "windows",
391        target_os = "macos",
392        target_os = "linux"
393    )))]
394    {
395        let _ = request;
396        Box::pin(async {
397            Err(Error::new(
398                "native file dialogs are not supported on this platform",
399            ))
400        })
401    }
402}
403
404async fn await_dialog_with_parent<Parent, Operation>(
405    _parent: Parent,
406    operation: Operation,
407) -> Operation::Output
408where
409    Operation: Future,
410{
411    operation.await
412}
413
414#[cfg(any(
415    target_arch = "wasm32",
416    target_os = "windows",
417    target_os = "macos",
418    target_os = "linux"
419))]
420fn selection(files: Vec<rfd::FileHandle>) -> FileDialogSelection {
421    FileDialogSelection {
422        files: files
423            .into_iter()
424            .map(|inner| PlatformFile { inner })
425            .collect(),
426    }
427}
428
429#[cfg(all(
430    not(target_arch = "wasm32"),
431    any(target_os = "windows", target_os = "macos", target_os = "linux")
432))]
433type NativeFileDialogParents = HashMap<WindowId, Weak<Window>>;
434
435#[cfg(all(
436    not(target_arch = "wasm32"),
437    any(target_os = "windows", target_os = "macos", target_os = "linux")
438))]
439fn native_file_dialog_parents() -> &'static Mutex<NativeFileDialogParents> {
440    static PARENTS: OnceLock<Mutex<NativeFileDialogParents>> = OnceLock::new();
441    PARENTS.get_or_init(|| Mutex::new(HashMap::new()))
442}
443
444#[cfg(all(
445    not(target_arch = "wasm32"),
446    any(target_os = "windows", target_os = "macos", target_os = "linux")
447))]
448pub(crate) fn register_native_file_dialog_parent(window_id: WindowId, window: &Arc<Window>) {
449    native_file_dialog_parents()
450        .lock()
451        .unwrap_or_else(|poisoned| poisoned.into_inner())
452        .insert(window_id, Arc::downgrade(window));
453}
454
455#[cfg(all(
456    not(target_arch = "wasm32"),
457    any(target_os = "windows", target_os = "macos", target_os = "linux")
458))]
459pub(crate) fn unregister_native_file_dialog_parent(window_id: WindowId) {
460    native_file_dialog_parents()
461        .lock()
462        .unwrap_or_else(|poisoned| poisoned.into_inner())
463        .remove(&window_id);
464}
465
466#[cfg(all(
467    not(target_arch = "wasm32"),
468    any(target_os = "windows", target_os = "macos", target_os = "linux")
469))]
470fn resolve_native_file_dialog_parent(window_id: WindowId) -> Option<Arc<Window>> {
471    let mut parents = native_file_dialog_parents()
472        .lock()
473        .unwrap_or_else(|poisoned| poisoned.into_inner());
474    let parent = parents.get(&window_id).and_then(Weak::upgrade);
475    if parent.is_none() {
476        parents.remove(&window_id);
477    }
478    parent
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484    use std::sync::Arc;
485    use std::task::{Context, Poll, Waker};
486
487    #[test]
488    fn file_dialog_request_preserves_portable_options() {
489        let parent = WindowId::new(73);
490        let request = FileDialogRequest::new(FileDialogMode::OpenFiles)
491            .title("Attach files")
492            .filter(FileDialogFilter::new("Text", ["txt", "md"]))
493            .suggested_name("notes.md")
494            .can_create_directories(false)
495            .parent_window(parent);
496        assert_eq!(request.mode, FileDialogMode::OpenFiles);
497        assert_eq!(request.filters[0].extensions, ["txt", "md"]);
498        assert_eq!(request.suggested_name.as_deref(), Some("notes.md"));
499        assert!(!request.can_create_directories);
500        assert_eq!(request.parent_window, Some(parent));
501        assert_eq!(request.clone().clear_parent_window().parent_window, None);
502    }
503
504    #[cfg(not(target_arch = "wasm32"))]
505    #[test]
506    fn native_file_dialog_future_can_move_to_a_background_executor() {
507        fn assert_send<T: Send>() {}
508        assert_send::<FileDialogFuture>();
509    }
510
511    #[test]
512    fn dialog_parent_guard_lives_until_operation_finishes() {
513        let parent = Arc::new(());
514        let weak_parent = Arc::downgrade(&parent);
515        let operation = std::future::poll_fn({
516            let weak_parent = weak_parent.clone();
517            move |_| {
518                assert!(weak_parent.upgrade().is_some());
519                Poll::Ready(())
520            }
521        });
522        let future = await_dialog_with_parent(parent, operation);
523        assert!(weak_parent.upgrade().is_some());
524
525        let mut future = Box::pin(future);
526        let mut context = Context::from_waker(Waker::noop());
527        assert_eq!(future.as_mut().poll(&mut context), Poll::Ready(()));
528        assert!(weak_parent.upgrade().is_none());
529    }
530}