Skip to main content

sui_platform/
file_dialog.rs

1use std::{
2    future::Future,
3    path::{Path, PathBuf},
4    pin::Pin,
5};
6
7use sui_core::{Error, Result};
8
9const RFD_SUPPORTED: bool = cfg!(any(
10    target_arch = "wasm32",
11    target_os = "windows",
12    target_os = "macos",
13    target_os = "linux"
14));
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum FileDialogMode {
18    OpenFile,
19    OpenFiles,
20    SaveFile,
21    OpenFolder,
22    OpenFolders,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct FileDialogFilter {
27    pub name: String,
28    pub extensions: Vec<String>,
29}
30
31impl FileDialogFilter {
32    pub fn new(
33        name: impl Into<String>,
34        extensions: impl IntoIterator<Item = impl Into<String>>,
35    ) -> Self {
36        Self {
37            name: name.into(),
38            extensions: extensions.into_iter().map(Into::into).collect(),
39        }
40    }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct FileDialogRequest {
45    pub mode: FileDialogMode,
46    pub title: Option<String>,
47    pub filters: Vec<FileDialogFilter>,
48    pub initial_directory: Option<PathBuf>,
49    pub suggested_name: Option<String>,
50    pub can_create_directories: bool,
51}
52
53impl FileDialogRequest {
54    pub fn new(mode: FileDialogMode) -> Self {
55        Self {
56            mode,
57            title: None,
58            filters: Vec::new(),
59            initial_directory: None,
60            suggested_name: None,
61            can_create_directories: true,
62        }
63    }
64
65    pub fn title(mut self, title: impl Into<String>) -> Self {
66        self.title = Some(title.into());
67        self
68    }
69
70    pub fn filter(mut self, filter: FileDialogFilter) -> Self {
71        self.filters.push(filter);
72        self
73    }
74
75    pub fn initial_directory(mut self, directory: impl Into<PathBuf>) -> Self {
76        self.initial_directory = Some(directory.into());
77        self
78    }
79
80    pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
81        self.suggested_name = Some(name.into());
82        self
83    }
84
85    pub const fn can_create_directories(mut self, can_create: bool) -> Self {
86        self.can_create_directories = can_create;
87        self
88    }
89}
90
91#[derive(Clone, Debug)]
92pub struct PlatformFile {
93    #[cfg(any(
94        target_arch = "wasm32",
95        target_os = "windows",
96        target_os = "macos",
97        target_os = "linux"
98    ))]
99    inner: rfd::FileHandle,
100    #[cfg(not(any(
101        target_arch = "wasm32",
102        target_os = "windows",
103        target_os = "macos",
104        target_os = "linux"
105    )))]
106    name: String,
107}
108
109impl PlatformFile {
110    pub fn file_name(&self) -> String {
111        #[cfg(any(
112            target_arch = "wasm32",
113            target_os = "windows",
114            target_os = "macos",
115            target_os = "linux"
116        ))]
117        {
118            self.inner.file_name()
119        }
120        #[cfg(not(any(
121            target_arch = "wasm32",
122            target_os = "windows",
123            target_os = "macos",
124            target_os = "linux"
125        )))]
126        {
127            self.name.clone()
128        }
129    }
130
131    pub fn path(&self) -> Option<&Path> {
132        #[cfg(all(
133            not(target_arch = "wasm32"),
134            any(target_os = "windows", target_os = "macos", target_os = "linux")
135        ))]
136        {
137            Some(self.inner.path())
138        }
139        #[cfg(not(all(
140            not(target_arch = "wasm32"),
141            any(target_os = "windows", target_os = "macos", target_os = "linux")
142        )))]
143        {
144            None
145        }
146    }
147
148    pub async fn read(&self) -> Result<Vec<u8>> {
149        #[cfg(any(
150            target_arch = "wasm32",
151            target_os = "windows",
152            target_os = "macos",
153            target_os = "linux"
154        ))]
155        {
156            Ok(self.inner.read().await)
157        }
158        #[cfg(not(any(
159            target_arch = "wasm32",
160            target_os = "windows",
161            target_os = "macos",
162            target_os = "linux"
163        )))]
164        {
165            Err(Error::new(
166                "file handles are not supported on this platform",
167            ))
168        }
169    }
170
171    pub async fn write(&self, data: &[u8]) -> Result<()> {
172        #[cfg(any(
173            target_arch = "wasm32",
174            target_os = "windows",
175            target_os = "macos",
176            target_os = "linux"
177        ))]
178        {
179            self.inner
180                .write(data)
181                .await
182                .map_err(|error| Error::new(format!("file write failed: {error}")))
183        }
184        #[cfg(not(any(
185            target_arch = "wasm32",
186            target_os = "windows",
187            target_os = "macos",
188            target_os = "linux"
189        )))]
190        {
191            let _ = data;
192            Err(Error::new(
193                "file handles are not supported on this platform",
194            ))
195        }
196    }
197}
198
199#[derive(Clone, Debug, Default)]
200pub struct FileDialogSelection {
201    pub files: Vec<PlatformFile>,
202}
203
204impl FileDialogSelection {
205    pub fn first(&self) -> Option<&PlatformFile> {
206        self.files.first()
207    }
208}
209
210pub type FileDialogFuture =
211    Pin<Box<dyn Future<Output = Result<Option<FileDialogSelection>>> + 'static>>;
212
213pub trait FileDialogService {
214    fn show(&self, request: FileDialogRequest) -> FileDialogFuture;
215}
216
217#[derive(Debug, Clone, Copy, Default)]
218pub struct NativeFileDialogs;
219
220impl FileDialogService for NativeFileDialogs {
221    fn show(&self, request: FileDialogRequest) -> FileDialogFuture {
222        Box::pin(show_file_dialog(request))
223    }
224}
225
226pub async fn show_file_dialog(request: FileDialogRequest) -> Result<Option<FileDialogSelection>> {
227    if !RFD_SUPPORTED {
228        return Err(Error::new(
229            "native file dialogs are not supported on this platform",
230        ));
231    }
232
233    #[cfg(any(
234        target_arch = "wasm32",
235        target_os = "windows",
236        target_os = "macos",
237        target_os = "linux"
238    ))]
239    {
240        let mut dialog = rfd::AsyncFileDialog::new();
241        if let Some(title) = request.title {
242            dialog = dialog.set_title(title);
243        }
244        if let Some(name) = request.suggested_name {
245            dialog = dialog.set_file_name(name);
246        }
247        #[cfg(not(target_arch = "wasm32"))]
248        if let Some(directory) = request.initial_directory {
249            dialog = dialog.set_directory(directory);
250        }
251        dialog = dialog.set_can_create_directories(request.can_create_directories);
252        for filter in request.filters {
253            dialog = dialog.add_filter(filter.name, &filter.extensions);
254        }
255
256        let handles = match request.mode {
257            FileDialogMode::OpenFile => dialog.pick_file().await.map(|file| vec![file]),
258            FileDialogMode::OpenFiles => dialog.pick_files().await,
259            FileDialogMode::SaveFile => dialog.save_file().await.map(|file| vec![file]),
260            #[cfg(not(target_arch = "wasm32"))]
261            FileDialogMode::OpenFolder => dialog.pick_folder().await.map(|file| vec![file]),
262            #[cfg(not(target_arch = "wasm32"))]
263            FileDialogMode::OpenFolders => dialog.pick_folders().await,
264            #[cfg(target_arch = "wasm32")]
265            FileDialogMode::OpenFolder | FileDialogMode::OpenFolders => {
266                return Err(Error::new("folder dialogs are not available in web builds"));
267            }
268        };
269        Ok(handles.map(|files| FileDialogSelection {
270            files: files
271                .into_iter()
272                .map(|inner| PlatformFile { inner })
273                .collect(),
274        }))
275    }
276
277    #[cfg(not(any(
278        target_arch = "wasm32",
279        target_os = "windows",
280        target_os = "macos",
281        target_os = "linux"
282    )))]
283    {
284        let _ = request;
285        Err(Error::new(
286            "native file dialogs are not supported on this platform",
287        ))
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn file_dialog_request_preserves_portable_options() {
297        let request = FileDialogRequest::new(FileDialogMode::OpenFiles)
298            .title("Attach files")
299            .filter(FileDialogFilter::new("Text", ["txt", "md"]))
300            .suggested_name("notes.md")
301            .can_create_directories(false);
302        assert_eq!(request.mode, FileDialogMode::OpenFiles);
303        assert_eq!(request.filters[0].extensions, ["txt", "md"]);
304        assert_eq!(request.suggested_name.as_deref(), Some("notes.md"));
305        assert!(!request.can_create_directories);
306    }
307}