Skip to main content

robius_file_picker/
lib.rs

1//! Multi-platform abstractions for native file picker dialogs,
2//! including dedicated image and video pickers on mobile.
3//!
4//! ## Platform behavior
5//! All types & functions in this crate are completely platform-independent,
6//! so your app code doesn't need to deal with any of this, but here are some
7//! details about how things are implemented on a per-platform basis, in case you're curious.
8//! * **macOS**, **Linux**, **Windows**: desktop platforms are mostly a wrapper around [`rfd`].
9//! * **Android**: file pickers use the system document picker
10//!   (via//!   `ACTION_OPEN_DOCUMENT`/`ACTION_CREATE_DOCUMENT`).
11//!   * Media picking uses the system Photo Picker when available,
12//!     otherwise it falls back to the document picker above.
13//!   * On Android 10 and up, it saves directly to Downloads via `MediaStore.Downloads`.
14//!   * On Android 8 and 9, it writes directly to storage if the legacy external storage
15//!     write permission is granted. Otherwise it falls back to `ACTION_CREATE_DOCUMENT`.
16//!   * **Minimum API level: 26 (Android 8.0).** The bundled Java helper is loaded via
17//!     `InMemoryDexClassLoader`, which requires API 26. Newer features (the system
18//!     Photo Picker, `MediaStore.Downloads`) are used only when the device supports
19//!     them, so set `minSdk` to at least 26 in your app.
20//! * **iOS**: file picking use [`UIDocumentPickerViewController`], while
21//!   media picking uses `PHPickerViewController`.
22//!
23//! On Android, picked files are returned as `content://` URIs (there's no other real option),
24//! and as regular filesystem paths on all other platforms (desktop and iOS).
25//! The [`PickedFile::into_local_file`] function abstracts over that by returning either the
26//! existing real filesystem path or streaming the URI's content into a temp file
27//! in the app's cache dir and then returning that.
28//! Thus, you can always get the file as a regular path.
29//!
30//! ## Callbacks and thread contexts
31//!
32//! All completion callbacks run on a background thread (a true native OS thread,
33//! not an async task). The picker dialog popup never runs on the main UI thread,
34//! so callbacks can easily do blocking work like reading the picked file or copying
35//! its bytes around without freezing the UI.
36//!
37//! To communicate between the callback that runs in a background thread and your app's
38//! main UI thread, use a communication primitive like a channel, or something similar
39//! from your UI toolkit, e.g., `Cx::post_action` in Makepad.
40//!
41//! [`rfd`]: https://crates.io/crates/rfd
42//! [`UIDocumentPickerViewController`]: https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller
43
44mod error;
45mod sys;
46
47use std::{path::{Path, PathBuf}, sync::Arc};
48
49pub use error::{Error, Result};
50use robius_common::FileLocation;
51pub(crate) type DialogCallback = Box<dyn FnOnce(Result<Option<PickedFile>>) + Send + 'static>;
52pub(crate) type DialogData = Box<dyn AsRef<[u8]> + Send + 'static>;
53
54
55/// The image file extensions that [`pick_image`](FileDialog::pick_image) (and
56/// the image half of [`pick_image_or_video`](FileDialog::pick_image_or_video))
57/// filter by, unless you override them with [`FileDialog::add_filter`].
58///
59/// This default set only narrows the selection on platforms whose native picker
60/// filters by extension (i.e. the desktop file dialogs). The mobile media
61/// pickers filter by the broad "images" category instead, so they accept any
62/// image type regardless of this list.
63pub const DEFAULT_IMAGE_EXTENSIONS: &[&str] = &[
64    // Common display/web formats.
65    "jpg", "jpeg", "jfif", "png", "apng", "gif", "bmp", "dib", "webp", "avif", "heic", "heif",
66    "tif", "tiff", "svg", "svgz", "ico", "jp2", "jxl", "pbm", "pgm", "ppm", "tga", "psd",
67    // Common camera RAW formats.
68    "raw", "dng", "cr2", "cr3", "nef", "nrw", "arw", "srf", "sr2", "orf", "rw2", "raf", "pef",
69    "srw", "dcr", "x3f",
70];
71
72/// The video file extensions that [`pick_video`](FileDialog::pick_video) (and
73/// the video half of [`pick_image_or_video`](FileDialog::pick_image_or_video))
74/// filter by, unless you override them with [`FileDialog::add_filter`].
75///
76/// This default set only narrows the selection on platforms whose native picker
77/// filters by extension (i.e. the desktop file dialogs). The mobile media
78/// pickers filter by the broad "videos" category instead, so they accept any
79/// video type regardless of this list.
80pub const DEFAULT_VIDEO_EXTENSIONS: &[&str] = &[
81    "mp4", "m4v", "mov", "qt", "avi", "mkv", "webm", "wmv", "asf", "flv", "f4v", "ogv", "ogm",
82    "mpg", "mpeg", "mpe", "m2v", "mp2", "mts", "m2ts", "ts", "3gp", "3g2", "mxf", "vob", "rm",
83    "rmvb", "divx", "m4p",
84];
85
86/// A native file dialog builder.
87#[derive(Clone, Debug, Default)]
88pub struct FileDialog {
89    options: DialogOptions,
90}
91
92impl FileDialog {
93    /// Creates a new file dialog builder.
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    /// Appends a single named file extension filter, leaving existing filters intact.
99    /// 
100    /// Upon creation, a `FileDialog` has no filters. Adding any filter manually
101    /// will result in the default image or video extension filters *not* being used.
102    ///
103    /// Extensions may be supplied with or without a leading dot '.'.
104    /// To replace the whole filter set, use [`set_filters`](Self::set_filters) instead.
105    ///
106    /// See the README or top-level docs for more info.
107    #[must_use]
108    pub fn add_filter(mut self, name: impl Into<String>, extensions: &[impl ToString]) -> Self {
109        self.options.filters.push(FileFilter {
110            name: name.into(),
111            extensions: extensions.iter().map(|ext| ext.to_string()).collect(),
112        });
113        self
114    }
115
116    /// Replaces every previously added filter with the given set of `filters`.
117    ///
118    /// Passing an empty set clears all filters, including those previously added via `add_filter()`.
119    ///
120    /// ```no_run
121    /// # use robius_file_picker::FileDialog;
122    /// let dialog = FileDialog::new().set_filters([
123    ///     ("Images", &["png", "jpg"]),
124    ///     ("Documents", &["pdf", "txt"]),
125    /// ]);
126    /// ```
127    #[must_use]
128    pub fn set_filters<N, X, E>(mut self, filters: impl IntoIterator<Item = (N, X)>) -> Self
129    where
130        N: Into<String>,
131        X: IntoIterator<Item = E>,
132        E: ToString,
133    {
134        self.options.filters = filters
135            .into_iter()
136            .map(|(name, extensions)| FileFilter {
137                name: name.into(),
138                extensions: extensions.into_iter().map(|ext| ext.to_string()).collect(),
139            })
140            .collect();
141        self
142    }
143
144    /// Sets a platform MIME type hint.
145    ///
146    /// This is primarily used on Android and iOS. Desktop backends might ignore it.
147    #[must_use]
148    pub fn set_mime_type(mut self, mime_type: impl Into<String>) -> Self {
149        self.options.mime_type = Some(mime_type.into());
150        self
151    }
152
153    /// Sets the initial directory, where supported.
154    #[must_use]
155    pub fn set_directory<P: AsRef<Path>>(mut self, path: P) -> Self {
156        let path = path.as_ref();
157        if path.to_str().map(|p| p.is_empty()).unwrap_or(false) {
158            self.options.directory = None;
159        } else {
160            self.options.directory = Some(path.to_owned());
161        }
162        self
163    }
164
165    /// Hints which well-known folder the dialog should open in.
166    ///
167    /// This is merely a hint; the OS might very well open the last-used location instead.
168    #[must_use]
169    pub fn set_start_location(mut self, location: StartLocation) -> Self {
170        self.options.start_location = Some(location);
171        self
172    }
173
174    /// Sets the suggested file name, where supported.
175    #[must_use]
176    pub fn set_file_name(mut self, file_name: impl Into<String>) -> Self {
177        self.options.file_name = Some(file_name.into());
178        self
179    }
180
181    /// Sets the dialog title, where supported.
182    #[must_use]
183    pub fn set_title(mut self, title: impl Into<String>) -> Self {
184        self.options.title = Some(title.into());
185        self
186    }
187
188    /// Sets which representation of a picked media item the platform should hand back.
189    ///
190    /// Only the media pickers ([`pick_image`](Self::pick_image),
191    /// [`pick_video`](Self::pick_video), [`pick_image_or_video`](Self::pick_image_or_video),
192    /// [`pick_media`](Self::pick_media)) use this, and only on iOS so far.
193    /// Defaults to [`MediaRepresentation::Original`].
194    #[must_use]
195    pub fn set_media_representation(mut self, representation: MediaRepresentation) -> Self {
196        self.options.media_representation = representation;
197        self
198    }
199
200    /// Shows a native open-file dialog.
201    ///
202    /// The callback is called with `Ok(None)` if the user cancels the dialog.
203    /// Returns [`Error::AlreadyOpen`] if a dialow is already being shown.
204    pub fn pick_file<F>(self, on_completion: F) -> Result<()>
205    where
206        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
207    {
208        sys::pick_file(self.options, Box::new(on_completion))
209    }
210
211    /// Shows the platform's native image picker.
212    ///
213    /// The callback is called with `Ok(None)` if the user cancels the picker.
214    pub fn pick_image<F>(self, on_completion: F) -> Result<()>
215    where
216        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
217    {
218        self.pick_media(MediaKind::Image, on_completion)
219    }
220
221    /// Shows the platform's native video picker.
222    ///
223    /// The callback is called with `Ok(None)` if the user cancels the picker.
224    pub fn pick_video<F>(self, on_completion: F) -> Result<()>
225    where
226        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
227    {
228        self.pick_media(MediaKind::Video, on_completion)
229    }
230
231    /// Shows the platform's native image and video picker.
232    ///
233    /// The callback is called with `Ok(None)` if the user cancels the picker.
234    pub fn pick_image_or_video<F>(self, on_completion: F) -> Result<()>
235    where
236        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
237    {
238        self.pick_media(MediaKind::ImageOrVideo, on_completion)
239    }
240
241    /// Shows the platform's native media picker.
242    ///
243    /// * Android: shows the Android Photo Picker, falling back to the document picker
244    ///   with a filter for images/videos.
245    /// * iOS: shows the `PHPickerViewController`.
246    /// * Desktop: shows a filtered file dialog.
247    ///
248    /// With no explicit location set, defaults the start location to Pictures or
249    /// Videos, which only the desktop dialog and document-picker fallbacks use.
250    ///
251    /// Returns [`Error::AlreadyOpen`] if a dialow is already being shown.
252    pub fn pick_media<F>(mut self, media_kind: MediaKind, on_completion: F) -> Result<()>
253    where
254        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
255    {
256        if self.options.directory.is_none() && self.options.start_location.is_none() {
257            self.options.start_location = Some(match media_kind {
258                MediaKind::Image | MediaKind::ImageOrVideo => StartLocation::Pictures,
259                MediaKind::Video => StartLocation::Videos,
260            });
261        }
262        sys::pick_media(self.options, media_kind, Box::new(on_completion))
263    }
264
265    /// Saves the given `data` bytes to a user-specific location via platform-native operations.
266    ///
267    /// You should first set a file name via [`FileDialog::set_file_name`],
268    /// otherwise this will return [`Error::InvalidFileName`].
269    /// Returns [`Error::AlreadyOpen`] if a dialow is already being shown.
270    pub fn save_data<D, F>(self, data: D, on_completion: F) -> Result<()>
271    where
272        D: AsRef<[u8]> + Send + 'static,
273        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
274    {
275        sys::save_data(self.options, Box::new(data), Box::new(on_completion))
276    }
277
278    /// Saves a file to the user's Downloads location.
279    pub fn save_to_downloads<P, F>(self, source_path: P, on_completion: F) -> Result<()>
280    where
281        P: AsRef<Path>,
282        F: FnOnce(Result<Option<PickedFile>>) + Send + 'static,
283    {
284        sys::save_to_downloads(
285            self.options,
286            source_path.as_ref().to_owned(),
287            Box::new(on_completion),
288        )
289    }
290}
291
292/// The type of media to show in a native media picker.
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
294pub enum MediaKind {
295    #[doc(alias("photo", "picture"))]
296    Image,
297    #[doc(alias = "movie")]
298    Video,
299    #[doc(alias("photos", "pictures", "movies"))]
300    ImageOrVideo,
301}
302impl MediaKind {
303    pub fn is_image(&self) -> bool {
304        matches!(self, Self::Image | Self::ImageOrVideo)
305    }
306    pub fn is_video(&self) -> bool {
307        matches!(self, Self::Video | Self::ImageOrVideo)
308    }
309}
310
311/// Which representation of a picked media item the platform should hand back.
312///
313/// Used with [`FileDialog::set_media_representation`].
314#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
315pub enum MediaRepresentation {
316    /// Hand back the item as it is stored, without re-encoding it.
317    #[default]
318    Original,
319    /// Prefer a widely-supported format, letting the platform transcode if it must.
320    ///
321    /// iOS converts HEIC photos to JPEG and HEVC videos to H.264, so pick this when
322    /// the file is headed somewhere that can't read Apple's formats. Transcoding a
323    /// video this way can be slow, so prefer [`Original`](Self::Original) otherwise.
324    Compatible,
325}
326
327/// A well-known directory that a file dialog should start in.
328///
329/// Used with [`FileDialog::set_start_location`].
330#[derive(Clone, Copy, Debug, PartialEq, Eq)]
331pub enum StartLocation {
332    Desktop,
333    Documents,
334    Downloads,
335    #[doc(alias("photo", "image"))]
336    Pictures,
337    #[doc(alias = "audio")]
338    Music,
339    #[doc(alias = "movie")]
340    Videos,
341}
342
343#[derive(Clone, Debug, PartialEq, Eq)]
344pub(crate) struct FileFilter {
345    pub(crate) name: String,
346    pub(crate) extensions: Vec<String>,
347}
348
349/// Options collected by [`FileDialog`].
350#[derive(Clone, Debug, Default)]
351pub(crate) struct DialogOptions {
352    pub(crate) filters: Vec<FileFilter>,
353    pub(crate) directory: Option<PathBuf>,
354    pub(crate) start_location: Option<StartLocation>,
355    pub(crate) file_name: Option<String>,
356    pub(crate) title: Option<String>,
357    pub(crate) mime_type: Option<String>,
358    pub(crate) media_representation: MediaRepresentation,
359}
360
361impl DialogOptions {
362    pub(crate) fn output_file_name(&self, source_path: &Path) -> Result<String> {
363        self.file_name
364            .as_deref()
365            .and_then(file_name_component)
366            .or_else(|| {
367                source_path
368                    .file_name()
369                    .and_then(|file_name| file_name.to_str())
370            })
371            .filter(|file_name| !file_name.is_empty())
372            .map(ToOwned::to_owned)
373            .ok_or(Error::InvalidFileName)
374    }
375
376    pub(crate) fn output_file_name_only(&self) -> Result<String> {
377        self.file_name
378            .as_deref()
379            .and_then(file_name_component)
380            .filter(|file_name| !file_name.is_empty())
381            .map(ToOwned::to_owned)
382            .ok_or(Error::InvalidFileName)
383    }
384}
385
386fn file_name_component(file_name: &str) -> Option<&str> {
387    Path::new(file_name)
388        .file_name()
389        .and_then(|file_name| file_name.to_str())
390        .filter(|file_name| !file_name.is_empty())
391}
392
393/// A file chosen by the user in a native file/media picker dialog.
394///
395/// Under the hood, this is either a filesystem path or a `content://` URI,
396/// plus any metadata that the platform provided (name, MIME type, size).
397#[derive(Clone, Debug, PartialEq, Eq)]
398pub struct PickedFile {
399    location: FileLocation,
400    owned_temp: bool,
401    display_name: Option<String>,
402    mime_type: Option<String>,
403    size: Option<u64>,
404}
405
406impl PickedFile {
407    #[allow(dead_code)]
408    pub(crate) fn from_path(path: PathBuf) -> Self {
409        Self {
410            location: FileLocation::from_path(path),
411            owned_temp: false,
412            display_name: None,
413            mime_type: None,
414            size: None,
415        }
416    }
417
418    /// Like [`PickedFile::from_path`], but for a temporary file created by this library.
419    #[allow(dead_code)]
420    pub(crate) fn from_owned_temp_path(path: PathBuf) -> Self {
421        Self {
422            location: FileLocation::from_path(path),
423            owned_temp: true,
424            display_name: None,
425            mime_type: None,
426            size: None,
427        }
428    }
429
430    #[allow(dead_code)]
431    pub(crate) fn from_uri(uri: String) -> Self {
432        Self {
433            location: FileLocation::from_uri(uri),
434            owned_temp: false,
435            display_name: None,
436            mime_type: None,
437            size: None,
438        }
439    }
440
441    /// Builds a URI-backed file with metadata (mostly for Android).
442    #[allow(dead_code)]
443    pub(crate) fn from_uri_with_metadata(
444        uri: String,
445        display_name: Option<String>,
446        mime_type: Option<String>,
447        size: Option<u64>,
448    ) -> Self {
449        Self {
450            location: FileLocation::from_uri(uri),
451            owned_temp: false,
452            display_name: display_name.filter(|s| !s.is_empty()),
453            mime_type: mime_type.filter(|s| !s.is_empty()),
454            size,
455        }
456    }
457
458    /// Returns this file as a filesystem path, if the platform returned one.
459    pub fn path(&self) -> Option<&Path> {
460        self.location.path()
461    }
462
463    /// Returns this file as a platform URI, if the platform returned one.
464    pub fn uri(&self) -> Option<&str> {
465        self.location.uri()
466    }
467
468    /// Consumes this file and returns its filesystem path, if any.
469    pub fn into_path(self) -> Option<PathBuf> {
470        self.location.into_path()
471    }
472
473    /// Consumes this file and returns its platform URI, if any.
474    pub fn into_uri(self) -> Option<String> {
475        self.location.into_uri()
476    }
477
478    /// The platform-provided display name, if known (Android).
479    pub fn display_name(&self) -> Option<&str> {
480        self.display_name.as_deref()
481    }
482
483    /// The platform-provided MIME type, if known (Android).
484    pub fn mime_type(&self) -> Option<&str> {
485        self.mime_type.as_deref()
486    }
487
488    /// The platform-provided size in bytes, if known (Android).
489    pub fn size(&self) -> Option<u64> {
490        self.size
491    }
492
493    /// Returns a best-effort file name: the platform-provided display name,
494    /// otherwise the final path component or URI segment.
495    pub fn file_name(&self) -> Option<&str> {
496        if let Some(name) = self.display_name.as_deref().filter(|s| !s.is_empty()) {
497            return Some(name);
498        }
499        match &self.location {
500            FileLocation::Path(path) => path.file_name().and_then(|name| name.to_str()),
501            FileLocation::Uri(uri) => uri
502                .split('?')
503                .next()
504                .unwrap_or(uri)
505                .trim_end_matches('/')
506                .rsplit('/')
507                .next()
508                .filter(|name| !name.is_empty()),
509        }
510    }
511
512    /// Reads the file's contents into memory.
513    ///
514    /// This buffers the whole file; generally you should use [`PickedFile::into_local_file`]
515    /// if you need to write it to storage instead.
516    pub fn read_bytes(&self) -> Result<Vec<u8>> {
517        match &self.location {
518            FileLocation::Path(path) => Ok(std::fs::read(path)?),
519            FileLocation::Uri(uri) => sys::read_uri_bytes(uri),
520        }
521    }
522
523    /// Allows accessing this file via a real filesystem path.
524    ///
525    /// A path-backed file (desktop, iOS) is returned as-is.
526    /// A URI-backed file (Android) is streamed to a temp file in the app's cache dir,
527    /// which avoids buffering it in memory (nice!).
528    ///
529    /// Returns a [`LocalFile`], which owns any temp file instance and deletes it
530    /// once the last reference is dropped.
531    ///
532    /// This performs blocking I/O, so don't call it on the main UI thread.
533    /// Calling it in a callback is totally fine, those already run on background threads.
534    pub fn into_local_file(self) -> Result<LocalFile> {
535
536        fn uri_file_name(uri: &str) -> Option<&str> {
537            uri.split('?')
538                .next()
539                .unwrap_or(uri)
540                .trim_end_matches('/')
541                .rsplit('/')
542                .next()
543                .filter(|name| !name.is_empty())
544        }
545
546        let PickedFile {
547            location,
548            owned_temp,
549            display_name,
550            mime_type,
551            size,
552        } = self;
553        match location {
554            FileLocation::Path(path) => Ok(LocalFile {
555                cleanup: owned_temp.then(|| Arc::new(TempPathCleanup { path: path.clone() })),
556                path,
557                display_name,
558                mime_type,
559                size,
560            }),
561            FileLocation::Uri(uri) => {
562                let file_name = display_name
563                    .as_deref()
564                    .filter(|name| !name.is_empty())
565                    .or_else(|| uri_file_name(&uri))
566                    .unwrap_or("attachment")
567                    .to_owned();
568                let now = std::time::SystemTime::now()
569                    .duration_since(std::time::UNIX_EPOCH)
570                    .unwrap_or_default()
571                    .as_nanos();
572                let dir = sys::app_temp_dir()?
573                    .join(format!("robius-file-picker-{}-{now}", std::process::id()));
574                std::fs::create_dir_all(&dir)?;
575                let path = dir.join(file_name);
576                // Stream the URI's contents straight to disk on the backend.
577                sys::copy_uri_to_path(&uri, &path)?;
578                Ok(LocalFile {
579                    cleanup: Some(Arc::new(TempPathCleanup { path: path.clone() })),
580                    path,
581                    display_name,
582                    mime_type,
583                    size,
584                })
585            }
586        }
587    }
588}
589
590
591/// A file guaranteed to be reachable through a filesystem path.
592///
593/// Produced by [`PickedFile::into_local_file`], and as stated there,
594/// this auto-handles cleaning up any temp file instances it has created.
595///
596/// This instance should live for as long as you need to access/use the file,
597/// for example, throughout the duration of an upload/save operation.
598#[derive(Clone, Debug)]
599pub struct LocalFile {
600    path: PathBuf,
601    display_name: Option<String>,
602    mime_type: Option<String>,
603    size: Option<u64>,
604    // If `Some`, there is a temp file to clean up.
605    // If `None, the `path` points to the original real file and shouldn't be touched.
606    cleanup: Option<Arc<TempPathCleanup>>,
607}
608
609impl LocalFile {
610    /// The local filesystem path to the file.
611    pub fn path(&self) -> &Path {
612        &self.path
613    }
614
615    /// The platform-provided display name, if known (Android).
616    pub fn display_name(&self) -> Option<&str> {
617        self.display_name.as_deref()
618    }
619
620    /// The platform-provided MIME type, if known (Android).
621    pub fn mime_type(&self) -> Option<&str> {
622        self.mime_type.as_deref()
623    }
624
625    /// The platform-provided size in bytes, if known (Android).
626    pub fn size(&self) -> Option<u64> {
627        self.size
628    }
629
630    /// Whether this path is a temporary copy that will be cleaned up on drop.
631    pub fn is_temporary(&self) -> bool {
632        self.cleanup.is_some()
633    }
634}
635
636#[derive(Debug)]
637struct TempPathCleanup {
638    path: PathBuf,
639}
640
641impl Drop for TempPathCleanup {
642    fn drop(&mut self) {
643        let _ = std::fs::remove_file(&self.path);
644        // Remove the enclosing directory too, if it's empty.
645        if let Some(parent) = self.path.parent() {
646            let _ = std::fs::remove_dir(parent);
647        }
648    }
649}