1use 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
36pub trait FileDialogs {
44 fn open_file(
46 &self,
47 parent: Option<ViewId>,
48 options: OpenOptions,
49 ) -> FileDialogFuture<Option<PickedFile>>;
50
51 fn open_files(
53 &self,
54 parent: Option<ViewId>,
55 options: OpenOptions,
56 ) -> FileDialogFuture<Vec<PickedFile>>;
57
58 fn open_folder(
60 &self,
61 parent: Option<ViewId>,
62 options: FolderOptions,
63 ) -> FileDialogFuture<Option<PickedFolder>>;
64
65 fn save_file(
67 &self,
68 parent: Option<ViewId>,
69 options: SaveOptions,
70 ) -> FileDialogFuture<Option<PickedFile>>;
71}
72
73pub type FileDialogFuture<T> = Pin<Box<dyn Future<Output = Result<T, FileDialogError>>>>;
75
76#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum FileDialogError {
79 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
96pub struct FileType {
97 pub label: String,
98 pub extensions: Vec<String>,
100 pub mime_types: Vec<String>,
101}
102
103#[derive(Clone, Debug, Default, PartialEq, Eq)]
105pub struct OpenOptions {
106 pub types: Vec<FileType>,
108 pub initial_folder: Option<PathBuf>,
110 pub confirm_label: Option<String>,
112 pub writable: bool,
115}
116
117#[derive(Clone, Debug, Default, PartialEq, Eq)]
119pub struct FolderOptions {
120 pub initial_folder: Option<PathBuf>,
121 pub confirm_label: Option<String>,
122 pub writable: bool,
124}
125
126#[derive(Clone, Debug, Default, PartialEq, Eq)]
128pub struct SaveOptions {
129 pub types: Vec<FileType>,
130 pub initial_folder: Option<PathBuf>,
131 pub suggested_name: Option<String>,
133 pub confirm_label: Option<String>,
134}
135
136pub enum PickedFile {
138 Path(PathBuf),
140 Handle(Box<dyn FileHandle>),
142 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
156pub enum PickedFolder {
158 Path(PathBuf),
160 Handle(Box<dyn FolderHandle>),
162}
163
164impl PickedFolder {
165 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
186pub trait FolderHandle {
189 fn name(&self) -> &str;
191
192 fn url(&self) -> Option<String>;
194
195 fn entries(&self) -> FolderEntriesFuture;
197
198 fn open_file(&self, name: &str) -> FileOpenFuture<PickedFile>;
200
201 fn open_folder(&self, name: &str) -> FileOpenFuture<PickedFolder>;
203
204 fn create_file(&self, name: &str) -> Option<FileOpenFuture<PickedFile>>;
206
207 fn create_folder(&self, name: &str) -> Option<FileOpenFuture<PickedFolder>>;
209}
210
211#[derive(Clone, Debug, PartialEq, Eq)]
213pub struct FolderEntry {
214 pub name: String,
215 pub kind: EntryKind,
216}
217
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub enum EntryKind {
221 File,
222 Folder,
223}
224
225pub type FolderEntriesFuture = Pin<Box<dyn Future<Output = io::Result<Vec<FolderEntry>>>>>;
227
228pub trait FileHandle {
230 fn name(&self) -> &str;
232
233 fn url(&self) -> String;
235
236 fn size(&self) -> FileSizeFuture;
237
238 fn read_at<'a>(&'a self, offset: u64, buf: &'a mut [u8]) -> FileReadFuture<'a>;
240
241 fn open_write(&self) -> Option<FileOpenFuture<Box<dyn FileWriter>>>;
243}
244
245pub 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 fn finish(self: Box<Self>) -> FileFinishFuture;
254}
255
256pub trait FileStream {
258 fn name(&self) -> &str;
259
260 fn url(&self) -> String;
262
263 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
273const READ_CHUNK: usize = 64 * 1024;
275
276impl PickedFile {
277 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 pub fn read_all(self: Box<Self>) -> ReadFileFuture {
296 Box::pin(async move { read_handle(&*self).await })
297 }
298}
299
300impl dyn FileStream {
301 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 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 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}