Skip to main content

waft_embedder/
file_dialogs.rs

1//! The system's file dialogs: open a file, open files, open a folder, save a file, each the
2//! system's own panel. Not a dart:ui file: Flutter reaches them through its `file_selector`
3//! package, whose functions these follow, one per kind (`openFile`, `openFiles`,
4//! `getDirectoryPath`, `getSaveLocation`), each with options of its own and answering what its
5//! kind means.
6//!
7//! A pick answers a path where the system gives one (macOS, iOS, Windows, Linux) and the
8//! system's own handle where it gives none, as Flutter's `XFile` carries a path or a blob: the
9//! web's file handle, and Android's document, open as a handle where it seeks and as a stream
10//! where it is a pipe ([`PickedFile`]). A pick grants reading only, unless the app asks to write
11//! ([`OpenOptions::writable`]); a save grants writing to the one file chosen, which may not exist
12//! yet. A folder pick answers a path where the system gives one, and the system's folder handle
13//! where it gives none, the web's directory handle and Android's document tree, which lists the
14//! folder and opens and, when writable, makes what is in it ([`PickedFolder`]).
15//!
16//! The platform answers `None` where its system has no file dialogs, and a dialog the system
17//! could not show is answered as a [`FileDialogError`]. Every answer comes through a future, once
18//! the user has chosen or cancelled: a cancelled dialog answers `None`, or no files.
19//!
20//! A future is the dialog it shows. Dropping it before the dialog answers closes the dialog, so an
21//! app that stops waiting leaves no panel on screen behind it; dropping one the dialog has already
22//! answered closes nothing. Each system closes its own way: macOS cancels its panel, Windows closes
23//! its dialog, the desktop portal closes its request, iOS dismisses its picker, and Android
24//! finishes the activity it started. The web cannot close a browser dialog: it stays on screen,
25//! and its answer, when it comes, is ignored without error.
26
27use std::fmt;
28use std::future::Future;
29use std::io;
30use std::path::PathBuf;
31use std::pin::Pin;
32
33use crate::ViewId;
34use crate::files::ReadFileFuture;
35
36/// The system's file dialogs. `parent` is the view whose window a dialog belongs to, which the
37/// system shows it on, as a sheet where it has them (macOS); without one it stands alone.
38///
39/// Each future is the dialog it shows: dropping it before the dialog answers closes the dialog
40/// on the thread the system requires, and a future the dialog has answered closes nothing when it
41/// is dropped. The web cannot close a browser dialog, which stays on screen; its answer is
42/// ignored.
43pub trait FileDialogs {
44    /// Asks for one file to open; `None` if the user cancelled.
45    fn open_file(
46        &self,
47        parent: Option<ViewId>,
48        options: OpenOptions,
49    ) -> FileDialogFuture<Option<PickedFile>>;
50
51    /// Asks for files to open; none if the user cancelled.
52    fn open_files(
53        &self,
54        parent: Option<ViewId>,
55        options: OpenOptions,
56    ) -> FileDialogFuture<Vec<PickedFile>>;
57
58    /// Asks for a folder; `None` if the user cancelled.
59    fn open_folder(
60        &self,
61        parent: Option<ViewId>,
62        options: FolderOptions,
63    ) -> FileDialogFuture<Option<PickedFolder>>;
64
65    /// Asks where to save a file, which the pick may then write; `None` if the user cancelled.
66    fn save_file(
67        &self,
68        parent: Option<ViewId>,
69        options: SaveOptions,
70    ) -> FileDialogFuture<Option<PickedFile>>;
71}
72
73/// What a file dialog answers, once the user has chosen or cancelled.
74pub type FileDialogFuture<T> = Pin<Box<dyn Future<Output = Result<T, FileDialogError>>>>;
75
76/// Why a file dialog answered nothing the user chose.
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum FileDialogError {
79    /// The system did not show the dialog, or failed to answer it.
80    Failed(String),
81}
82
83impl fmt::Display for FileDialogError {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        match self {
86            FileDialogError::Failed(reason) => write!(f, "the file dialog failed: {reason}"),
87        }
88    }
89}
90
91impl std::error::Error for FileDialogError {}
92
93/// The kinds of file a dialog offers, as `file_selector`'s `XTypeGroup`: a system takes the
94/// extensions or the MIME types it filters by, and shows the label where it shows one.
95#[derive(Clone, Debug, Default, PartialEq, Eq)]
96pub struct FileType {
97    pub label: String,
98    /// Without the dot: `txt`.
99    pub extensions: Vec<String>,
100    pub mime_types: Vec<String>,
101}
102
103/// How to ask for files to open.
104#[derive(Clone, Debug, Default, PartialEq, Eq)]
105pub struct OpenOptions {
106    /// The kinds the dialog offers; any file when there are none.
107    pub types: Vec<FileType>,
108    /// Where the dialog starts, where the system takes a folder.
109    pub initial_folder: Option<PathBuf>,
110    /// The confirming button's label, where the system takes one.
111    pub confirm_label: Option<String>,
112    /// Whether the app may write the files picked. Most systems grant writing to every pick, so
113    /// this only matters where a pick grants reading alone (Android, the web).
114    pub writable: bool,
115}
116
117/// How to ask for a folder.
118#[derive(Clone, Debug, Default, PartialEq, Eq)]
119pub struct FolderOptions {
120    pub initial_folder: Option<PathBuf>,
121    pub confirm_label: Option<String>,
122    /// Whether the app may write in the folder picked, where a pick grants reading alone.
123    pub writable: bool,
124}
125
126/// How to ask where to save a file.
127#[derive(Clone, Debug, Default, PartialEq, Eq)]
128pub struct SaveOptions {
129    pub types: Vec<FileType>,
130    pub initial_folder: Option<PathBuf>,
131    /// The file name the dialog suggests.
132    pub suggested_name: Option<String>,
133    pub confirm_label: Option<String>,
134}
135
136/// A file the user picked, as the system gives it.
137pub enum PickedFile {
138    /// macOS, iOS, Windows and Linux: a path the app opens as any file.
139    Path(PathBuf),
140    /// The web, and Android where the document seeks, as it always does when writable.
141    Handle(Box<dyn FileHandle>),
142    /// Android where the document is a pipe: read once, start to end. Read-only picks only.
143    Stream(Box<dyn FileStream>),
144}
145
146impl fmt::Debug for PickedFile {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        match self {
149            PickedFile::Path(path) => f.debug_tuple("Path").field(path).finish(),
150            PickedFile::Handle(handle) => f.debug_tuple("Handle").field(&handle.name()).finish(),
151            PickedFile::Stream(stream) => f.debug_tuple("Stream").field(&stream.name()).finish(),
152        }
153    }
154}
155
156/// A folder the user picked, as the system gives it.
157pub enum PickedFolder {
158    /// macOS, iOS, Windows and Linux: a path the app reads and writes in as any folder.
159    Path(PathBuf),
160    /// The web's directory handle, and Android's document tree.
161    Handle(Box<dyn FolderHandle>),
162}
163
164impl PickedFolder {
165    /// The URL the system names the folder by, where it has one: a `file:` URL for a path,
166    /// absolute and percent-encoded; Android's `content:` URI of the folder in the tree the user
167    /// picked, from which an embedder may tell where on the device it is. The web's directory
168    /// handle has none.
169    pub fn url(&self) -> Option<String> {
170        match self {
171            PickedFolder::Path(path) => Some(crate::opener::file_uri(path)),
172            PickedFolder::Handle(handle) => handle.url(),
173        }
174    }
175}
176
177impl fmt::Debug for PickedFolder {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        match self {
180            PickedFolder::Path(path) => f.debug_tuple("Path").field(path).finish(),
181            PickedFolder::Handle(handle) => f.debug_tuple("Handle").field(&handle.name()).finish(),
182        }
183    }
184}
185
186/// A picked folder the system gives no path for: what is in it, opened by name, and, when the
187/// pick is writable, files and folders made in it. What it opens is writable when it is.
188pub trait FolderHandle {
189    /// The folder's name, which the user sees.
190    fn name(&self) -> &str;
191
192    /// The URL the system names the folder by, where it has one (`PickedFolder::url`).
193    fn url(&self) -> Option<String>;
194
195    /// What is in the folder, in no particular order.
196    fn entries(&self) -> FolderEntriesFuture;
197
198    /// The file `name` in the folder.
199    fn open_file(&self, name: &str) -> FileOpenFuture<PickedFile>;
200
201    /// The folder `name` in the folder.
202    fn open_folder(&self, name: &str) -> FileOpenFuture<PickedFolder>;
203
204    /// Makes an empty file `name` in the folder; `None` unless the pick is writable.
205    fn create_file(&self, name: &str) -> Option<FileOpenFuture<PickedFile>>;
206
207    /// Makes a folder `name` in the folder; `None` unless the pick is writable.
208    fn create_folder(&self, name: &str) -> Option<FileOpenFuture<PickedFolder>>;
209}
210
211/// One thing in a picked folder.
212#[derive(Clone, Debug, PartialEq, Eq)]
213pub struct FolderEntry {
214    pub name: String,
215    pub kind: EntryKind,
216}
217
218/// Whether a folder's entry is a file or a folder.
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub enum EntryKind {
221    File,
222    Folder,
223}
224
225/// What a folder's listing answers.
226pub type FolderEntriesFuture = Pin<Box<dyn Future<Output = io::Result<Vec<FolderEntry>>>>>;
227
228/// A picked file the system gives no path for, read and written at any offset.
229pub trait FileHandle {
230    /// The file's name, which the user sees.
231    fn name(&self) -> &str;
232
233    /// The URL the system reads the file by (`PickedFile::url`).
234    fn url(&self) -> String;
235
236    fn size(&self) -> FileSizeFuture;
237
238    /// Reads into `buf` from `offset`; answers how many bytes it read, `0` at the end.
239    fn read_at<'a>(&'a self, offset: u64, buf: &'a mut [u8]) -> FileReadFuture<'a>;
240
241    /// Opens the file to write; `None` unless the pick is writable.
242    fn open_write(&self) -> Option<FileOpenFuture<Box<dyn FileWriter>>>;
243}
244
245/// Writing to a picked file.
246pub trait FileWriter {
247    fn write_at<'a>(&'a mut self, offset: u64, bytes: &'a [u8]) -> FileWriteFuture<'a>;
248
249    fn set_len(&mut self, len: u64) -> FileWriteFuture<'_>;
250
251    /// Ends the writing: on the web the file is replaced only now, and a writer dropped before
252    /// abandons it; on Android the writes landed in place as they were made.
253    fn finish(self: Box<Self>) -> FileFinishFuture;
254}
255
256/// A picked file that can only be read through, once, start to end.
257pub trait FileStream {
258    fn name(&self) -> &str;
259
260    /// The URL the system reads the file by (`PickedFile::url`).
261    fn url(&self) -> String;
262
263    /// Reads the next bytes into `buf`; answers how many, `0` at the end.
264    fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> FileReadFuture<'a>;
265}
266
267pub type FileSizeFuture = Pin<Box<dyn Future<Output = io::Result<u64>>>>;
268pub type FileReadFuture<'a> = Pin<Box<dyn Future<Output = io::Result<usize>> + 'a>>;
269pub type FileOpenFuture<T> = Pin<Box<dyn Future<Output = io::Result<T>>>>;
270pub type FileWriteFuture<'a> = Pin<Box<dyn Future<Output = io::Result<()>> + 'a>>;
271pub type FileFinishFuture = Pin<Box<dyn Future<Output = io::Result<()>>>>;
272
273/// How much a whole read asks for at a time.
274const READ_CHUNK: usize = 64 * 1024;
275
276impl PickedFile {
277    /// The URL a player, or any API that takes a URL, reads the file by, as every system's
278    /// player does: a `file:` URL for a path, absolute and percent-encoded; Android's
279    /// `content:` URI; the web's `blob:` URL, of the file as it was when picked. A `blob:` URL is
280    /// made once a pick and never revoked: a player may read it after the pick is let go, so the
281    /// page keeps the file until it unloads.
282    pub fn url(&self) -> String {
283        match self {
284            PickedFile::Path(path) => crate::opener::file_uri(path),
285            PickedFile::Handle(handle) => handle.url(),
286            PickedFile::Stream(stream) => stream.url(),
287        }
288    }
289}
290
291impl dyn FileHandle {
292    /// The whole file, from its start to its end, as Flutter's `XFile.readAsBytes` reads a web
293    /// pick. A picked path is read by the platform's file service (`Platform::files`), not here:
294    /// a handle reads itself, a path is only a name.
295    pub fn read_all(self: Box<Self>) -> ReadFileFuture {
296        Box::pin(async move { read_handle(&*self).await })
297    }
298}
299
300impl dyn FileStream {
301    /// The whole stream, read through, which uses it up.
302    pub fn read_all(mut self: Box<Self>) -> ReadFileFuture {
303        Box::pin(async move { read_stream(&mut *self).await })
304    }
305}
306
307async fn read_handle(handle: &dyn FileHandle) -> io::Result<Vec<u8>> {
308    let mut bytes = Vec::with_capacity(usize::try_from(handle.size().await?).unwrap_or(0));
309    let mut chunk = vec![0; READ_CHUNK];
310    loop {
311        let read = handle.read_at(bytes.len() as u64, &mut chunk).await?;
312        if read == 0 {
313            return Ok(bytes);
314        }
315        bytes.extend_from_slice(&chunk[..read]);
316    }
317}
318
319async fn read_stream(stream: &mut dyn FileStream) -> io::Result<Vec<u8>> {
320    let mut bytes = Vec::new();
321    let mut chunk = vec![0; READ_CHUNK];
322    loop {
323        let read = stream.read(&mut chunk).await?;
324        if read == 0 {
325            return Ok(bytes);
326        }
327        bytes.extend_from_slice(&chunk[..read]);
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use std::cell::RefCell;
334    use std::task::{Context, Poll, Waker};
335
336    use super::*;
337
338    /// A handle over bytes in memory, read a few at a time.
339    struct Bytes(RefCell<Vec<u8>>);
340
341    impl FileHandle for Bytes {
342        fn name(&self) -> &str {
343            "bytes"
344        }
345
346        fn url(&self) -> String {
347            "memory:bytes".to_owned()
348        }
349
350        fn size(&self) -> FileSizeFuture {
351            let size = self.0.borrow().len() as u64;
352            Box::pin(async move { Ok(size) })
353        }
354
355        fn read_at<'a>(&'a self, offset: u64, buf: &'a mut [u8]) -> FileReadFuture<'a> {
356            let bytes = self.0.borrow();
357            let start = (offset as usize).min(bytes.len());
358            let read = (bytes.len() - start).min(buf.len()).min(3);
359            buf[..read].copy_from_slice(&bytes[start..start + read]);
360            Box::pin(async move { Ok(read) })
361        }
362
363        fn open_write(&self) -> Option<FileOpenFuture<Box<dyn FileWriter>>> {
364            None
365        }
366    }
367
368    fn now<T>(future: impl Future<Output = T>) -> T {
369        let mut future = std::pin::pin!(future);
370        let mut context = Context::from_waker(Waker::noop());
371        loop {
372            if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
373                return output;
374            }
375            std::thread::yield_now();
376        }
377    }
378
379    #[test]
380    fn a_handle_answers_the_url_it_holds() {
381        let picked = PickedFile::Handle(Box::new(Bytes(RefCell::new(Vec::new()))));
382        assert_eq!(picked.url(), "memory:bytes");
383    }
384
385    #[test]
386    fn a_picked_folder_answers_its_url_where_it_has_one() {
387        let path = std::env::temp_dir().join("a folder");
388        assert_eq!(
389            PickedFolder::Path(path.clone()).url(),
390            Some(crate::opener::file_uri(&path))
391        );
392        assert_eq!(
393            PickedFolder::Handle(Box::new(Unnamed)).url(),
394            None,
395            "a handle with no URL, as the web's"
396        );
397    }
398
399    /// A folder handle with no URL, as the web's directory handles are.
400    struct Unnamed;
401
402    impl FolderHandle for Unnamed {
403        fn name(&self) -> &str {
404            "unnamed"
405        }
406
407        fn url(&self) -> Option<String> {
408            None
409        }
410
411        fn entries(&self) -> FolderEntriesFuture {
412            Box::pin(async { Ok(Vec::new()) })
413        }
414
415        fn open_file(&self, _name: &str) -> FileOpenFuture<PickedFile> {
416            Box::pin(async { Err(io::Error::from(io::ErrorKind::NotFound)) })
417        }
418
419        fn open_folder(&self, _name: &str) -> FileOpenFuture<PickedFolder> {
420            Box::pin(async { Err(io::Error::from(io::ErrorKind::NotFound)) })
421        }
422
423        fn create_file(&self, _name: &str) -> Option<FileOpenFuture<PickedFile>> {
424            None
425        }
426
427        fn create_folder(&self, _name: &str) -> Option<FileOpenFuture<PickedFolder>> {
428            None
429        }
430    }
431
432    #[test]
433    fn a_handle_is_read_whole_in_pieces() {
434        let handle: Box<dyn FileHandle> = Box::new(Bytes(RefCell::new(b"hello, file".to_vec())));
435        assert_eq!(now(handle.read_all()).unwrap(), b"hello, file");
436    }
437}