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
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum FileDialogMode {
26    OpenFile,
27    OpenFiles,
28    SaveFile,
29    OpenFolder,
30    OpenFolders,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct FileDialogFilter {
35    pub name: String,
36    pub extensions: Vec<String>,
37}
38
39impl FileDialogFilter {
40    pub fn new(
41        name: impl Into<String>,
42        extensions: impl IntoIterator<Item = impl Into<String>>,
43    ) -> Self {
44        Self {
45            name: name.into(),
46            extensions: extensions.into_iter().map(Into::into).collect(),
47        }
48    }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct FileDialogRequest {
53    pub mode: FileDialogMode,
54    pub title: Option<String>,
55    pub filters: Vec<FileDialogFilter>,
56    pub initial_directory: Option<PathBuf>,
57    pub suggested_name: Option<String>,
58    pub can_create_directories: bool,
59    /// Logical SUI window that should own the native dialog.
60    ///
61    /// Native desktop hosts resolve this to a live window and retain it while
62    /// the returned dialog future is active. Web and Android builds ignore
63    /// this field.
64    pub parent_window: Option<WindowId>,
65}
66
67impl FileDialogRequest {
68    pub fn new(mode: FileDialogMode) -> Self {
69        Self {
70            mode,
71            title: None,
72            filters: Vec::new(),
73            initial_directory: None,
74            suggested_name: None,
75            can_create_directories: true,
76            parent_window: None,
77        }
78    }
79
80    pub fn title(mut self, title: impl Into<String>) -> Self {
81        self.title = Some(title.into());
82        self
83    }
84
85    pub fn filter(mut self, filter: FileDialogFilter) -> Self {
86        self.filters.push(filter);
87        self
88    }
89
90    pub fn initial_directory(mut self, directory: impl Into<PathBuf>) -> Self {
91        self.initial_directory = Some(directory.into());
92        self
93    }
94
95    pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
96        self.suggested_name = Some(name.into());
97        self
98    }
99
100    pub const fn can_create_directories(mut self, can_create: bool) -> Self {
101        self.can_create_directories = can_create;
102        self
103    }
104
105    pub const fn parent_window(mut self, window_id: WindowId) -> Self {
106        self.parent_window = Some(window_id);
107        self
108    }
109
110    pub const fn clear_parent_window(mut self) -> Self {
111        self.parent_window = None;
112        self
113    }
114}
115
116#[cfg(all(
117    not(target_arch = "wasm32"),
118    any(target_os = "windows", target_os = "macos", target_os = "linux")
119))]
120type FileInner = crate::os_files::OsFile;
121#[cfg(all(
122    not(target_arch = "wasm32"),
123    any(target_os = "windows", target_os = "macos", target_os = "linux")
124))]
125type FolderInner = crate::os_files::OsFolder;
126#[cfg(target_arch = "wasm32")]
127type FileInner = crate::web_files::WebFile;
128#[cfg(target_arch = "wasm32")]
129type FolderInner = crate::web_files::WebFolder;
130#[cfg(target_os = "android")]
131type FileInner = crate::android_file_dialog::AndroidFile;
132#[cfg(target_os = "android")]
133type FolderInner = crate::android_file_dialog::AndroidFolder;
134#[cfg(not(any(
135    target_arch = "wasm32",
136    target_os = "windows",
137    target_os = "macos",
138    target_os = "linux",
139    target_os = "android"
140)))]
141type FileInner = Unsupported;
142#[cfg(not(any(
143    target_arch = "wasm32",
144    target_os = "windows",
145    target_os = "macos",
146    target_os = "linux",
147    target_os = "android"
148)))]
149type FolderInner = Unsupported;
150
151/// A file the user chose in a file dialog, or found in a chosen folder.
152///
153/// Desktop files have a filesystem path. Web and Android files do not, so
154/// portable code reads and writes through the file itself.
155#[derive(Clone, Debug)]
156pub struct PlatformFile {
157    inner: FileInner,
158}
159
160impl PlatformFile {
161    #[cfg(any(
162        target_arch = "wasm32",
163        target_os = "windows",
164        target_os = "macos",
165        target_os = "linux",
166        target_os = "android"
167    ))]
168    pub(crate) fn from_inner(inner: FileInner) -> Self {
169        Self { inner }
170    }
171
172    pub fn file_name(&self) -> String {
173        self.inner.file_name()
174    }
175
176    /// The file's path on desktop platforms, `None` on the web and Android.
177    pub fn path(&self) -> Option<&Path> {
178        self.inner.path()
179    }
180
181    pub async fn read(&self) -> Result<Vec<u8>> {
182        self.inner.read().await
183    }
184
185    /// Replace the file's contents with `data`.
186    pub async fn write(&self, data: &[u8]) -> Result<()> {
187        self.inner.write(data).await
188    }
189}
190
191/// A folder the user chose in a folder dialog, or found inside one.
192///
193/// Desktop folders have a filesystem path. Web and Android folders do not, so
194/// portable code lists, opens, and creates entries through the folder itself.
195/// Entries are named by a single name, never a path, so a folder reaches only
196/// what is directly inside it.
197#[derive(Clone, Debug)]
198pub struct PlatformFolder {
199    inner: FolderInner,
200}
201
202impl PlatformFolder {
203    #[cfg(any(
204        target_arch = "wasm32",
205        target_os = "windows",
206        target_os = "macos",
207        target_os = "linux",
208        target_os = "android"
209    ))]
210    pub(crate) fn from_inner(inner: FolderInner) -> Self {
211        Self { inner }
212    }
213
214    pub fn name(&self) -> String {
215        self.inner.name()
216    }
217
218    /// The folder's path on desktop platforms, `None` on the web and Android.
219    pub fn path(&self) -> Option<&Path> {
220        self.inner.path()
221    }
222
223    /// The files and folders directly inside this folder, in no particular
224    /// order.
225    pub async fn entries(&self) -> Result<Vec<FolderEntry>> {
226        self.inner.entries().await
227    }
228
229    /// The file called `name` in this folder, or `None` when there is none.
230    pub async fn file(&self, name: &str) -> Result<Option<PlatformFile>> {
231        check_entry_name(name)?;
232        self.inner.file(name).await
233    }
234
235    /// The folder called `name` in this folder, or `None` when there is none.
236    pub async fn folder(&self, name: &str) -> Result<Option<PlatformFolder>> {
237        check_entry_name(name)?;
238        self.inner.folder(name).await
239    }
240
241    /// The file called `name` in this folder, created empty when there is
242    /// none. An existing file keeps its contents; a folder with that name is
243    /// an error.
244    pub async fn create_file(&self, name: &str) -> Result<PlatformFile> {
245        check_entry_name(name)?;
246        self.inner.create_file(name).await
247    }
248
249    /// The folder called `name` in this folder, created when there is none.
250    /// A file with that name is an error.
251    pub async fn create_folder(&self, name: &str) -> Result<PlatformFolder> {
252        check_entry_name(name)?;
253        self.inner.create_folder(name).await
254    }
255}
256
257/// A file or folder inside a [`PlatformFolder`].
258#[derive(Clone, Debug)]
259pub enum FolderEntry {
260    File(PlatformFile),
261    Folder(PlatformFolder),
262}
263
264impl FolderEntry {
265    pub fn name(&self) -> String {
266        match self {
267            Self::File(file) => file.file_name(),
268            Self::Folder(folder) => folder.name(),
269        }
270    }
271}
272
273fn check_entry_name(name: &str) -> Result<()> {
274    if name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\', '\0']) {
275        return Err(Error::new(format!("{name:?} is not a file or folder name")));
276    }
277    Ok(())
278}
279
280/// Stands in for files and folders where SUI shows no file dialogs, so none
281/// can exist.
282#[cfg(not(any(
283    target_arch = "wasm32",
284    target_os = "windows",
285    target_os = "macos",
286    target_os = "linux",
287    target_os = "android"
288)))]
289#[derive(Clone, Debug)]
290enum Unsupported {}
291
292#[cfg(not(any(
293    target_arch = "wasm32",
294    target_os = "windows",
295    target_os = "macos",
296    target_os = "linux",
297    target_os = "android"
298)))]
299impl Unsupported {
300    fn file_name(&self) -> String {
301        match *self {}
302    }
303
304    fn name(&self) -> String {
305        match *self {}
306    }
307
308    fn path(&self) -> Option<&Path> {
309        match *self {}
310    }
311
312    async fn read(&self) -> Result<Vec<u8>> {
313        match *self {}
314    }
315
316    async fn write(&self, _data: &[u8]) -> Result<()> {
317        match *self {}
318    }
319
320    async fn entries(&self) -> Result<Vec<FolderEntry>> {
321        match *self {}
322    }
323
324    async fn file(&self, _name: &str) -> Result<Option<PlatformFile>> {
325        match *self {}
326    }
327
328    async fn folder(&self, _name: &str) -> Result<Option<PlatformFolder>> {
329        match *self {}
330    }
331
332    async fn create_file(&self, _name: &str) -> Result<PlatformFile> {
333        match *self {}
334    }
335
336    async fn create_folder(&self, _name: &str) -> Result<PlatformFolder> {
337        match *self {}
338    }
339}
340
341#[derive(Clone, Debug, Default)]
342pub struct FileDialogSelection {
343    /// The chosen files. Desktop folder dialogs also list the chosen folders
344    /// here, as files with their paths, as they did before `folders` existed.
345    pub files: Vec<PlatformFile>,
346    /// The chosen folders, from folder dialogs.
347    pub folders: Vec<PlatformFolder>,
348}
349
350impl FileDialogSelection {
351    pub fn first(&self) -> Option<&PlatformFile> {
352        self.files.first()
353    }
354}
355
356#[cfg(not(target_arch = "wasm32"))]
357pub type FileDialogFuture =
358    Pin<Box<dyn Future<Output = Result<Option<FileDialogSelection>>> + Send + 'static>>;
359#[cfg(target_arch = "wasm32")]
360pub type FileDialogFuture =
361    Pin<Box<dyn Future<Output = Result<Option<FileDialogSelection>>> + 'static>>;
362
363pub trait FileDialogService {
364    /// Prepare and start a dialog operation.
365    ///
366    /// Call this method from the UI callback that initiated the request. The
367    /// native implementation constructs the rfd operation synchronously (as
368    /// required by macOS), then returns a `Send` future that may be polled by a
369    /// background executor. Web callers must create and begin polling the
370    /// returned local future during browser user activation.
371    fn show(&self, request: FileDialogRequest) -> FileDialogFuture;
372}
373
374#[derive(Debug, Clone, Copy, Default)]
375pub struct NativeFileDialogs;
376
377impl FileDialogService for NativeFileDialogs {
378    fn show(&self, request: FileDialogRequest) -> FileDialogFuture {
379        prepare_file_dialog(request)
380    }
381}
382
383/// Show a dialog from an async context.
384///
385/// Unlike [`FileDialogService::show`], construction is deferred until this
386/// future is first polled. UI callbacks that need macOS main-thread setup or
387/// browser user activation should call the service method instead.
388pub async fn show_file_dialog(request: FileDialogRequest) -> Result<Option<FileDialogSelection>> {
389    prepare_file_dialog(request).await
390}
391
392fn prepare_file_dialog(request: FileDialogRequest) -> FileDialogFuture {
393    #[cfg(target_os = "android")]
394    {
395        crate::android_file_dialog::show_file_dialog(request)
396    }
397
398    #[cfg(any(
399        target_arch = "wasm32",
400        target_os = "windows",
401        target_os = "macos",
402        target_os = "linux"
403    ))]
404    {
405        let FileDialogRequest {
406            mode,
407            title,
408            filters,
409            initial_directory,
410            suggested_name,
411            can_create_directories,
412            parent_window,
413        } = request;
414        let mut dialog = rfd::AsyncFileDialog::new();
415        if let Some(title) = title {
416            dialog = dialog.set_title(title);
417        }
418        if let Some(name) = suggested_name {
419            dialog = dialog.set_file_name(name);
420        }
421        #[cfg(not(target_arch = "wasm32"))]
422        if let Some(directory) = initial_directory {
423            dialog = dialog.set_directory(directory);
424        }
425        #[cfg(target_arch = "wasm32")]
426        let _ = initial_directory;
427        dialog = dialog.set_can_create_directories(can_create_directories);
428        for filter in filters {
429            dialog = dialog.add_filter(filter.name, &filter.extensions);
430        }
431
432        #[cfg(all(
433            not(target_arch = "wasm32"),
434            any(target_os = "windows", target_os = "macos", target_os = "linux")
435        ))]
436        let parent_guard = if let Some(parent_window) = parent_window {
437            let Some(parent) = resolve_native_file_dialog_parent(parent_window) else {
438                return Box::pin(async move {
439                    Err(Error::new(format!(
440                        "file dialog parent window {} is no longer available",
441                        parent_window.get()
442                    )))
443                });
444            };
445            dialog = dialog.set_parent(parent.as_ref());
446            Some(parent)
447        } else {
448            None
449        };
450        #[cfg(target_arch = "wasm32")]
451        let parent_guard = {
452            let _ = parent_window;
453        };
454
455        match mode {
456            FileDialogMode::OpenFile => {
457                let operation = dialog.pick_file();
458                Box::pin(async move {
459                    let result = await_dialog_with_parent(parent_guard, operation).await;
460                    Ok(result.map(|file| selection(vec![file])))
461                })
462            }
463            FileDialogMode::OpenFiles => {
464                let operation = dialog.pick_files();
465                Box::pin(async move {
466                    let result = await_dialog_with_parent(parent_guard, operation).await;
467                    Ok(result.map(selection))
468                })
469            }
470            FileDialogMode::SaveFile => {
471                let operation = dialog.save_file();
472                Box::pin(async move {
473                    let result = await_dialog_with_parent(parent_guard, operation).await;
474                    Ok(result.map(|file| selection(vec![file])))
475                })
476            }
477            #[cfg(not(target_arch = "wasm32"))]
478            FileDialogMode::OpenFolder => {
479                let operation = dialog.pick_folder();
480                Box::pin(async move {
481                    let result = await_dialog_with_parent(parent_guard, operation).await;
482                    Ok(result.map(|folder| folder_selection(vec![folder])))
483                })
484            }
485            #[cfg(not(target_arch = "wasm32"))]
486            FileDialogMode::OpenFolders => {
487                let operation = dialog.pick_folders();
488                Box::pin(async move {
489                    let result = await_dialog_with_parent(parent_guard, operation).await;
490                    Ok(result.map(folder_selection))
491                })
492            }
493            #[cfg(target_arch = "wasm32")]
494            FileDialogMode::OpenFolder | FileDialogMode::OpenFolders => {
495                crate::web_files::show_directory_picker()
496            }
497        }
498    }
499
500    #[cfg(not(any(
501        target_arch = "wasm32",
502        target_os = "windows",
503        target_os = "macos",
504        target_os = "linux",
505        target_os = "android"
506    )))]
507    {
508        let _ = request;
509        Box::pin(async {
510            Err(Error::new(
511                "native file dialogs are not supported on this platform",
512            ))
513        })
514    }
515}
516
517async fn await_dialog_with_parent<Parent, Operation>(
518    _parent: Parent,
519    operation: Operation,
520) -> Operation::Output
521where
522    Operation: Future,
523{
524    operation.await
525}
526
527#[cfg(any(
528    target_arch = "wasm32",
529    target_os = "windows",
530    target_os = "macos",
531    target_os = "linux"
532))]
533fn selection(files: Vec<rfd::FileHandle>) -> FileDialogSelection {
534    FileDialogSelection {
535        files: files
536            .into_iter()
537            .map(|file| PlatformFile::from_inner(file.into()))
538            .collect(),
539        folders: Vec::new(),
540    }
541}
542
543#[cfg(all(
544    not(target_arch = "wasm32"),
545    any(target_os = "windows", target_os = "macos", target_os = "linux")
546))]
547fn folder_selection(folders: Vec<rfd::FileHandle>) -> FileDialogSelection {
548    FileDialogSelection {
549        folders: folders
550            .iter()
551            .map(|folder| {
552                PlatformFolder::from_inner(crate::os_files::OsFolder::new(
553                    folder.path().to_path_buf(),
554                ))
555            })
556            .collect(),
557        ..selection(folders)
558    }
559}
560
561#[cfg(all(
562    not(target_arch = "wasm32"),
563    any(target_os = "windows", target_os = "macos", target_os = "linux")
564))]
565type NativeFileDialogParents = HashMap<WindowId, Weak<Window>>;
566
567#[cfg(all(
568    not(target_arch = "wasm32"),
569    any(target_os = "windows", target_os = "macos", target_os = "linux")
570))]
571fn native_file_dialog_parents() -> &'static Mutex<NativeFileDialogParents> {
572    static PARENTS: OnceLock<Mutex<NativeFileDialogParents>> = OnceLock::new();
573    PARENTS.get_or_init(|| Mutex::new(HashMap::new()))
574}
575
576#[cfg(all(
577    not(target_arch = "wasm32"),
578    any(target_os = "windows", target_os = "macos", target_os = "linux")
579))]
580pub(crate) fn register_native_file_dialog_parent(window_id: WindowId, window: &Arc<Window>) {
581    native_file_dialog_parents()
582        .lock()
583        .unwrap_or_else(|poisoned| poisoned.into_inner())
584        .insert(window_id, Arc::downgrade(window));
585}
586
587#[cfg(all(
588    not(target_arch = "wasm32"),
589    any(target_os = "windows", target_os = "macos", target_os = "linux")
590))]
591pub(crate) fn unregister_native_file_dialog_parent(window_id: WindowId) {
592    native_file_dialog_parents()
593        .lock()
594        .unwrap_or_else(|poisoned| poisoned.into_inner())
595        .remove(&window_id);
596}
597
598#[cfg(all(
599    not(target_arch = "wasm32"),
600    any(target_os = "windows", target_os = "macos", target_os = "linux")
601))]
602fn resolve_native_file_dialog_parent(window_id: WindowId) -> Option<Arc<Window>> {
603    let mut parents = native_file_dialog_parents()
604        .lock()
605        .unwrap_or_else(|poisoned| poisoned.into_inner());
606    let parent = parents.get(&window_id).and_then(Weak::upgrade);
607    if parent.is_none() {
608        parents.remove(&window_id);
609    }
610    parent
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616    use std::sync::Arc;
617    use std::task::{Context, Poll, Waker};
618
619    #[test]
620    fn file_dialog_request_preserves_portable_options() {
621        let parent = WindowId::new(73);
622        let request = FileDialogRequest::new(FileDialogMode::OpenFiles)
623            .title("Attach files")
624            .filter(FileDialogFilter::new("Text", ["txt", "md"]))
625            .suggested_name("notes.md")
626            .can_create_directories(false)
627            .parent_window(parent);
628        assert_eq!(request.mode, FileDialogMode::OpenFiles);
629        assert_eq!(request.filters[0].extensions, ["txt", "md"]);
630        assert_eq!(request.suggested_name.as_deref(), Some("notes.md"));
631        assert!(!request.can_create_directories);
632        assert_eq!(request.parent_window, Some(parent));
633        assert_eq!(request.clone().clear_parent_window().parent_window, None);
634    }
635
636    #[cfg(not(target_arch = "wasm32"))]
637    #[test]
638    fn native_file_dialog_future_can_move_to_a_background_executor() {
639        fn assert_send<T: Send>() {}
640        assert_send::<FileDialogFuture>();
641    }
642
643    #[test]
644    fn dialog_parent_guard_lives_until_operation_finishes() {
645        let parent = Arc::new(());
646        let weak_parent = Arc::downgrade(&parent);
647        let operation = std::future::poll_fn({
648            let weak_parent = weak_parent.clone();
649            move |_| {
650                assert!(weak_parent.upgrade().is_some());
651                Poll::Ready(())
652            }
653        });
654        let future = await_dialog_with_parent(parent, operation);
655        assert!(weak_parent.upgrade().is_some());
656
657        let mut future = Box::pin(future);
658        let mut context = Context::from_waker(Waker::noop());
659        assert_eq!(future.as_mut().poll(&mut context), Poll::Ready(()));
660        assert!(weak_parent.upgrade().is_none());
661    }
662}