tauri_plugin_android_fs/api/
android_fs.rs

1use sync_async::sync_async;
2use crate::*;
3use super::*;
4
5
6/// ***Root API***  
7/// 
8/// # Examples
9/// ```no_run
10/// fn example(app: &tauri::AppHandle) {
11///     use tauri_plugin_android_fs::AndroidFsExt as _;
12/// 
13///     let api = app.android_fs();
14/// }
15/// ```
16
17#[sync_async]
18pub struct AndroidFs<R: tauri::Runtime> {
19    #[cfg(target_os = "android")]
20    pub(crate) handle: tauri::plugin::PluginHandle<R>,
21
22    #[cfg(not(target_os = "android"))]
23    #[allow(unused)]
24    pub(crate) handle: std::marker::PhantomData<fn() -> R>
25}
26
27#[cfg(target_os = "android")]
28#[sync_async(
29    use(if_sync) impls::SyncImpls as Impls;
30    use(if_async) impls::AsyncImpls as Impls;
31)]
32impl<R: tauri::Runtime> AndroidFs<R> {
33    
34    #[always_sync]
35    pub(crate) fn impls(&self) -> Impls<'_, R> {
36        Impls { handle: &self.handle }
37    }
38}
39
40#[sync_async(
41    use(if_async) api_async::{FileOpener, FilePicker, PrivateStorage, PublicStorage, WritableStream};
42    use(if_sync) api_sync::{FileOpener, FilePicker, PrivateStorage, PublicStorage, WritableStream};
43)]
44impl<R: tauri::Runtime> AndroidFs<R> {
45
46    /// API of file storage intended for the app's use only.
47    #[always_sync]
48    pub fn private_storage(&self) -> PrivateStorage<'_, R> {
49        PrivateStorage { handle: &self.handle }
50    }
51
52    /// API of file storage that is available to other applications and users.
53    #[always_sync]
54    pub fn public_storage(&self) -> PublicStorage<'_, R> {
55        PublicStorage { handle: &self.handle }
56    }
57
58    /// API of file/dir picker.
59    #[always_sync]
60    pub fn file_picker(&self) -> FilePicker<'_, R> {
61        FilePicker { handle: &self.handle }
62    }
63
64    /// API of opening file/dir with other apps.
65    #[always_sync]
66    pub fn file_opener(&self) -> FileOpener<'_, R> {
67        FileOpener { handle: &self.handle }
68    }
69
70    /// Get the file or directory name.  
71    /// 
72    /// # Args
73    /// - ***uri*** :  
74    /// Target URI.  
75    /// Must be **readable**.
76    /// 
77    /// # Support
78    /// All Android version.
79    #[maybe_async]
80    pub fn get_name(&self, uri: &FileUri) -> Result<String> {
81        #[cfg(not(target_os = "android"))] {
82            Err(Error::NOT_ANDROID)
83        }
84        #[cfg(target_os = "android")] {
85            self.impls().get_entry_name(uri).await
86        }
87    }
88
89    /// Queries the provider to get the MIME type.
90    ///
91    /// For file URIs via [`FileUri::from_path`], the MIME type is determined from the file extension.  
92    /// In most other cases, it uses the MIME type that was associated with the file when it was created.  
93    /// If the MIME type is unknown or unset, it falls back to `"application/octet-stream"`.  
94    /// 
95    /// If the target is a directory, an error will occur.  
96    /// To check whether the target is a file or a directory, use [`AndroidFs::get_type`].  
97    /// 
98    /// # Args
99    /// - ***uri*** :  
100    /// Target file URI.  
101    /// Must be **readable**.
102    /// 
103    /// # Support
104    /// All Android version.
105    #[maybe_async]
106    pub fn get_mime_type(&self, uri: &FileUri) -> Result<String> {
107        #[cfg(not(target_os = "android"))] {
108            Err(Error::NOT_ANDROID)
109        }
110        #[cfg(target_os = "android")] {
111            self.impls().get_file_mime_type(uri).await
112        }
113    }
114
115    /// Gets the entry type.
116    ///
117    /// If the target is a directory, returns [`EntryType::Dir`].
118    ///
119    /// If the target is a file, returns [`EntryType::File { mime_type }`](EntryType::File).  
120    /// For file URIs via [`FileUri::from_path`], the MIME type is determined from the file extension.  
121    /// In most other cases, it uses the MIME type that was associated with the file when it was created.  
122    /// If the MIME type is unknown or unset, it falls back to `"application/octet-stream"`.  
123    /// 
124    /// # Args
125    /// - ***uri*** :  
126    /// Target URI.  
127    /// Must be **readable**.
128    /// 
129    /// # Support
130    /// All Android version.
131    #[maybe_async]
132    pub fn get_type(&self, uri: &FileUri) -> Result<EntryType> {
133        #[cfg(not(target_os = "android"))] {
134            Err(Error::NOT_ANDROID)
135        }
136        #[cfg(target_os = "android")] {
137            self.impls().get_entry_type(uri).await
138        }
139    }
140
141    /// Queries the file system to get information about a file, directory.
142    /// 
143    /// # Args
144    /// - ***uri*** :  
145    /// Target URI.  
146    /// Must be **readable**.
147    /// 
148    /// # Note
149    /// This uses [`AndroidFs::open_file`] internally.
150    /// 
151    /// # Support
152    /// All Android version.
153    #[maybe_async]
154    pub fn get_metadata(&self, uri: &FileUri) -> Result<std::fs::Metadata> {
155        #[cfg(not(target_os = "android"))] {
156            Err(Error::NOT_ANDROID)
157        }
158        #[cfg(target_os = "android")] {
159            self.impls().get_entry_metadata(uri).await
160        }
161    }
162
163    /// Open the file in **readable** mode. 
164    /// 
165    /// # Note
166    /// If the target is a file on cloud storage or otherwise not physically present on the device,
167    /// the file provider may downloads the entire contents, and then opens it. 
168    /// As a result, this processing may take longer than with regular local files.
169    /// And files might be a pair of pipe or socket for streaming data.
170    /// 
171    /// # Args
172    /// - ***uri*** :  
173    /// Target file URI.  
174    /// This need to be **readable**.
175    /// 
176    /// # Support
177    /// All Android version.
178    #[maybe_async]
179    pub fn open_file_readable(&self, uri: &FileUri) -> Result<std::fs::File> {
180        #[cfg(not(target_os = "android"))] {
181            Err(Error::NOT_ANDROID)
182        }
183        #[cfg(target_os = "android")] {
184            self.impls().open_file_readable(uri).await
185        }
186    }
187
188    /// Open the file in **writable** mode.  
189    /// This truncates the existing contents.  
190    /// 
191    /// # Note
192    /// For file provider of some cloud storage, 
193    /// writing by file descriptor like std::fs may not correctoly notify and reflect changes. 
194    /// If you need to write to such files, use [`AndroidFs::open_writable_stream`].
195    /// It will fall back to Kotlin API as needed.
196    /// And you can check by [`AndroidFs::need_write_via_kotlin`].
197    /// 
198    /// # Args
199    /// - ***uri*** :  
200    /// Target file URI.  
201    /// This need to be **writable**.
202    /// 
203    /// # Support
204    /// All Android version.
205    #[maybe_async]
206    pub fn open_file_writable(
207        &self, 
208        uri: &FileUri, 
209    ) -> Result<std::fs::File> {
210
211        #[cfg(not(target_os = "android"))] {
212            Err(Error::NOT_ANDROID)
213        }
214        #[cfg(target_os = "android")] {
215            self.impls().open_file_writable(uri).await
216        }
217    }
218
219    /// Open the file in the specified mode.  
220    /// 
221    /// # Note
222    /// If the target is a file on cloud storage or otherwise not physically present on the device,
223    /// the file provider may downloads the entire contents, and then opens it. 
224    /// As a result, this processing may take longer than with regular local files.
225    /// And files might be a pair of pipe or socket for streaming data.
226    /// 
227    /// When writing to a file with this function,
228    /// pay attention to the following points:
229    /// 
230    /// 1. **File reflection**:  
231    /// For file provider of some cloud storage, 
232    /// writing by file descriptor like std::fs may not correctoly notify and reflect changes. 
233    /// If you need to write to such files, use [`AndroidFs::open_writable_stream`].
234    /// It will fall back to Kotlin API as needed.
235    /// And you can check by [`AndroidFs::need_write_via_kotlin`].
236    /// 
237    /// 2. **File mode restrictions**:  
238    /// Files provided by third-party apps may not support writable modes other than
239    /// [`FileAccessMode::Write`]. However, [`FileAccessMode::Write`] does not guarantee
240    /// that existing contents will always be truncated.  
241    /// As a result, if the new contents are shorter than the original, the file may
242    /// become corrupted. To avoid this, consider using
243    /// [`AndroidFs::open_file_writable`] or [`AndroidFs::open_writable_stream`], which
244    /// ensure that existing contents are truncated and also automatically apply the
245    /// maximum possible fallbacks.  
246    /// <https://issuetracker.google.com/issues/180526528>
247    /// 
248    /// # Args
249    /// - ***uri*** :  
250    /// Target file URI.  
251    /// This must have corresponding permissions (read, write, or both) for the specified ***mode***.
252    /// 
253    /// - ***mode*** :  
254    /// Indicates how the file is opened and the permissions granted. 
255    /// The only ones that can be expected to work in all cases are [`FileAccessMode::Write`] and [`FileAccessMode::Read`].
256    /// Because files hosted by third-party apps may not support others.
257    /// 
258    /// # Support
259    /// All Android version.
260    #[maybe_async]
261    pub fn open_file(&self, uri: &FileUri, mode: FileAccessMode) -> crate::Result<std::fs::File> {
262        #[cfg(not(target_os = "android"))] {
263            Err(Error::NOT_ANDROID)
264        }
265        #[cfg(target_os = "android")] {
266            self.impls().open_file(uri, mode).await
267        }
268    }
269 
270    /// For detailed documentation and notes, see [`AndroidFs::open_file`].  
271    ///
272    /// The modes specified in ***candidate_modes*** are tried in order.  
273    /// If the file can be opened, this returns the file along with the mode used.  
274    /// If all attempts fail, an error is returned.  
275    #[maybe_async]
276    pub fn open_file_with_fallback(
277        &self, 
278        uri: &FileUri, 
279        candidate_modes: impl IntoIterator<Item = FileAccessMode>
280    ) -> Result<(std::fs::File, FileAccessMode)> {
281
282        #[cfg(not(target_os = "android"))] {
283            Err(Error::NOT_ANDROID)
284        }
285        #[cfg(target_os = "android")] {
286            self.impls().open_file_with_fallback(uri, candidate_modes).await
287        }
288    }
289
290    /// Opens a stream for writing to the specified file.  
291    /// This truncates the existing contents.  
292    /// 
293    /// # Usage
294    /// [`WritableStream`] implements [`std::io::Write`], so it can be used for writing.  
295    /// As with [`std::fs::File`], wrap it with [`std::io::BufWriter`] if buffering is needed.  
296    ///
297    /// After writing, call [`WritableStream::reflect`].  
298    /// 
299    /// # Note
300    /// The behavior depends on [`AndroidFs::need_write_via_kotlin`].  
301    /// If it is `false`, this behaves like [`AndroidFs::open_file_writable`].  
302    /// If it is `true`, this behaves like [`AndroidFs::open_writable_stream_via_kotlin`].  
303    /// 
304    /// # Args
305    /// - ***uri*** :  
306    /// Target file URI.  
307    /// This need to be **writable**.
308    /// 
309    /// # Support
310    /// All Android version.
311    #[maybe_async]
312    pub fn open_writable_stream(
313        &self,
314        uri: &FileUri
315    ) -> Result<WritableStream<R>> {
316
317        #[cfg(not(target_os = "android"))] {
318            Err(Error::NOT_ANDROID)
319        }
320        #[cfg(target_os = "android")] {
321            let impls = self.impls().create_writable_stream_auto(uri).await?;
322            Ok(WritableStream { impls })
323        }
324    }
325
326    /// Opens a writable stream to the specified file.  
327    /// This truncates the existing contents.  
328    /// 
329    /// This function always writes content via the Kotlin API.
330    /// But this takes several times longer compared.  
331    /// [`AndroidFs::open_writable_stream`] automatically falls back to this function depending on [`AndroidFs::need_write_via_kotlin`].  
332    /// 
333    /// # Usage
334    /// [`WritableStream`] implements [`std::io::Write`], so it can be used for writing.  
335    /// As with [`std::fs::File`], wrap it with [`std::io::BufWriter`] if buffering is needed.  
336    ///
337    /// After writing, call [`WritableStream::reflect`].
338    /// 
339    /// # Args
340    /// - ***uri*** :  
341    /// Target file URI.  
342    /// This need to be **writable**.
343    /// 
344    /// # Support
345    /// All Android version.
346    #[maybe_async]
347    pub fn open_writable_stream_via_kotlin(
348        &self,
349        uri: &FileUri
350    ) -> Result<WritableStream<R>> {
351
352        #[cfg(not(target_os = "android"))] {
353            Err(Error::NOT_ANDROID)
354        }
355        #[cfg(target_os = "android")] {
356            let impls = self.impls().create_writable_stream_via_kotlin(uri).await?;
357            Ok(WritableStream { impls })
358        }
359    }
360
361    /// Reads the entire contents of a file into a bytes vector.  
362    /// 
363    /// # Args
364    /// - ***uri*** :  
365    /// Target file URI.    
366    /// Must be **readable**.
367    /// 
368    /// # Support
369    /// All Android version.
370    #[maybe_async]
371    pub fn read(&self, uri: &FileUri) -> Result<Vec<u8>> {
372        #[cfg(not(target_os = "android"))] {
373            Err(Error::NOT_ANDROID)
374        }
375        #[cfg(target_os = "android")] {
376            self.impls().read_file(uri).await
377        }
378    }
379
380    /// Reads the entire contents of a file into a string.  
381    /// 
382    /// # Args
383    /// - ***uri*** :  
384    /// Target file URI.  
385    /// Must be **readable**.
386    /// 
387    /// # Support
388    /// All Android version.
389    #[maybe_async]
390    pub fn read_to_string(&self, uri: &FileUri) -> Result<String> {
391        #[cfg(not(target_os = "android"))] {
392            Err(Error::NOT_ANDROID)
393        }
394        #[cfg(target_os = "android")] {
395            self.impls().read_file_to_string(uri).await
396        }
397    }
398
399    /// Writes a slice as the entire contents of a file.  
400    /// This function will entirely replace its contents if it does exist.    
401    /// 
402    /// # Note
403    /// The behavior depends on [`AndroidFs::need_write_via_kotlin`].  
404    /// If it is `false`, this uses [`std::fs::File`].  
405    /// If it is `true`, this uses [`AndroidFs::write_via_kotlin`].  
406    /// 
407    /// # Args
408    /// - ***uri*** :  
409    /// Target file URI.  
410    /// Must be **writable**.
411    /// 
412    /// # Support
413    /// All Android version.
414    #[maybe_async]
415    pub fn write(&self, uri: &FileUri, contents: impl AsRef<[u8]>) -> Result<()> {
416        #[cfg(not(target_os = "android"))] {
417            Err(Error::NOT_ANDROID)
418        }
419        #[cfg(target_os = "android")] {
420            self.impls().write_file_auto(uri, contents).await
421        }
422    }
423
424    /// Writes a slice as the entire contents of a file.  
425    /// This function will entirely replace its contents if it does exist.    
426    /// 
427    /// This function always writes content via the Kotlin API.
428    /// But this takes several times longer compared.   
429    /// [`AndroidFs::write`] automatically falls back to this function depending on [`AndroidFs::need_write_via_kotlin`].  
430    /// 
431    /// # Support
432    /// All Android version.
433    #[maybe_async]
434    pub fn write_via_kotlin(
435        &self, 
436        uri: &FileUri,
437        contents: impl AsRef<[u8]>
438    ) -> Result<()> {
439
440        #[cfg(not(target_os = "android"))] {
441            Err(Error::NOT_ANDROID)
442        }
443        #[cfg(target_os = "android")] {
444            self.impls().write_file_via_kotlin(uri, contents).await
445        }
446    }
447
448    /// Copies the contents of the source file to the destination.  
449    /// If the destination already has contents, they are truncated before writing the source contents.  
450    /// 
451    /// # Note
452    /// The behavior depends on [`AndroidFs::need_write_via_kotlin`].  
453    /// If it is `false`, this uses [`std::io::copy`] with [`std::fs::File`].  
454    /// If it is `true`, this uses [`AndroidFs::copy_via_kotlin`].  
455    /// 
456    /// # Args
457    /// - ***src*** :  
458    /// The URI of source file.   
459    /// Must be **readable**.
460    /// 
461    /// - ***dest*** :  
462    /// The URI of destination file.  
463    /// Must be **writable**.
464    /// 
465    /// # Support
466    /// All Android version.
467    #[maybe_async]
468    pub fn copy(&self, src: &FileUri, dest: &FileUri) -> Result<()> {
469        #[cfg(not(target_os = "android"))] {
470            Err(Error::NOT_ANDROID)
471        }
472        #[cfg(target_os = "android")] {
473            self.impls().copy_file(src, dest).await
474        }
475    }
476
477    /// Copies the contents of src file to dest.  
478    /// If dest already has contents, it is truncated before write src contents.  
479    /// 
480    /// This function always writes content via the Kotlin API.  
481    /// [`AndroidFs::copy`] automatically falls back to this function depending on [`AndroidFs::need_write_via_kotlin`].   
482    /// 
483    /// # Args
484    /// - ***src*** :  
485    /// The URI of source file.   
486    /// Must be **readable**.
487    /// 
488    /// - ***dest*** :  
489    /// The URI of destination file.  
490    /// Must be **writable**.
491    /// 
492    /// - ***buffer_size***:  
493    /// The size of the buffer, in bytes, to use during the copy process on Kotlin.  
494    /// If `None`, [`DEFAULT_BUFFER_SIZE`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.io/-d-e-f-a-u-l-t_-b-u-f-f-e-r_-s-i-z-e.html) is used. 
495    /// At least, when I checked, it was 8 KB.  
496    /// If zero, this causes error.
497    /// 
498    /// # Support
499    /// All Android version.
500    #[maybe_async]
501    pub fn copy_via_kotlin(
502        &self, 
503        src: &FileUri, 
504        dest: &FileUri,
505        buffer_size: Option<u32>,
506    ) -> Result<()> {
507
508        #[cfg(not(target_os = "android"))] {
509            Err(Error::NOT_ANDROID)
510        }
511        #[cfg(target_os = "android")] {
512            self.impls().copy_file_via_kotlin(src, dest, buffer_size).await
513        }
514    }
515
516    /// Determines whether the file must be written via the Kotlin API rather than through a file descriptor.
517    /// 
518    /// In the case of a file that physically exists on the device, this will always return false.
519    /// This is intended for special cases, such as some cloud storage.
520    /// 
521    /// # Support
522    /// All Android version.
523    #[maybe_async]
524    pub fn need_write_via_kotlin(&self, uri: &FileUri) -> Result<bool> {
525        #[cfg(not(target_os = "android"))] {
526            Err(Error::NOT_ANDROID)
527        }
528        #[cfg(target_os = "android")] {
529            self.impls().need_write_file_via_kotlin(uri).await
530        }
531    }
532
533    /// Renames a file or directory to a new name, and return new URI.  
534    /// Even if the names conflict, the existing file will not be overwritten.  
535    /// 
536    /// Note that when files or folders (and their descendants) are renamed, their URIs will change, and any previously granted permissions will be lost.
537    /// In other words, this function returns a new URI without any permissions.
538    /// However, for files created in PublicStorage, the URI remains unchanged even after such operations, and all permissions are retained.
539    /// In this, this function returns the same URI as original URI.
540    ///
541    /// # Args
542    /// - ***uri*** :  
543    /// URI of target entry.  
544    /// 
545    /// - ***new_name*** :  
546    /// New name of target entry. 
547    /// This include extension if use.  
548    /// The behaviour in the same name already exists depends on the file provider.  
549    /// In the case of e.g. [`PublicStorage`], the suffix (e.g. `(1)`) is added to this name.  
550    /// In the case of files hosted by other applications, errors may occur.  
551    /// But at least, the existing file will not be overwritten.  
552    /// The system may sanitize these strings as needed, so those strings may not be used as it is.
553    /// 
554    /// # Support
555    /// All Android version.
556    #[maybe_async]
557    pub fn rename(&self, uri: &FileUri, new_name: impl AsRef<str>) -> Result<FileUri> {
558        #[cfg(not(target_os = "android"))] {
559            Err(Error::NOT_ANDROID)
560        }
561        #[cfg(target_os = "android")] {
562            self.impls().rename_entry(uri, new_name).await
563        }
564    }
565
566    /// Remove the file.
567    /// 
568    /// # Args
569    /// - ***uri*** :  
570    /// Target file URI.  
571    /// Must be **writable**, at least. But even if it is, 
572    /// removing may not be possible in some cases. 
573    /// For details, refer to the documentation of the function that provided the URI.  
574    /// If not file, an error will occur.
575    /// 
576    /// # Support
577    /// All Android version.
578    #[maybe_async]
579    pub fn remove_file(&self, uri: &FileUri) -> crate::Result<()> {
580        #[cfg(not(target_os = "android"))] {
581            Err(Error::NOT_ANDROID)
582        }
583        #[cfg(target_os = "android")] {
584            self.impls().remove_file(uri).await
585        }
586    }
587
588    /// Remove the **empty** directory.
589    /// 
590    /// # Args
591    /// - ***uri*** :  
592    /// Target directory URI.  
593    /// Must be **writable**.  
594    /// If not empty directory, an error will occur.
595    /// 
596    /// # Support
597    /// All Android version.
598    #[maybe_async]
599    pub fn remove_dir(&self, uri: &FileUri) -> crate::Result<()> {
600        #[cfg(not(target_os = "android"))] {
601            Err(Error::NOT_ANDROID)
602        }
603        #[cfg(target_os = "android")] {
604            self.impls().remove_dir_if_empty(uri).await
605        }
606    }
607
608    /// Removes a directory and all its contents. Use carefully!
609    /// 
610    /// # Args
611    /// - ***uri*** :  
612    /// Target directory URI.  
613    /// Must be **writable**.  
614    /// If not directory, an error will occur.
615    /// 
616    /// # Support
617    /// All Android version.
618    #[maybe_async]
619    pub fn remove_dir_all(&self, uri: &FileUri) -> crate::Result<()> {
620        #[cfg(not(target_os = "android"))] {
621            Err(Error::NOT_ANDROID)
622        }
623        #[cfg(target_os = "android")] {
624            self.impls().remove_dir_all(uri).await
625        }
626    }
627
628    /// Build a URI of an **existing** file located at the relative path from the specified directory.   
629    /// Error occurs, if the file does not exist.  
630    /// 
631    /// The permissions and validity period of the returned URI depend on the origin directory 
632    /// (e.g., the top directory selected by [`FilePicker::pick_dir`]) 
633    /// 
634    /// # Note
635    /// For [`AndroidFs::create_new_file`] and etc, the system may sanitize path strings as needed, so those strings may not be used as it is.
636    /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
637    /// 
638    /// # Args
639    /// - ***uri*** :  
640    /// Base directory URI.  
641    /// Must be **readable**.  
642    /// 
643    /// - ***relative_path*** :
644    /// Relative path from base directory.
645    /// 
646    /// # Support
647    /// All Android version.
648    #[maybe_async]
649    pub fn try_resolve_file_uri(
650        &self, 
651        dir: &FileUri, 
652        relative_path: impl AsRef<std::path::Path>
653    ) -> Result<FileUri> {
654
655        #[cfg(not(target_os = "android"))] {
656            Err(Error::NOT_ANDROID)
657        }
658        #[cfg(target_os = "android")] {
659            self.impls().try_resolve_file_uri(dir, relative_path).await
660        }
661    }
662
663    /// Build a URI of an **existing** directory located at the relative path from the specified directory.   
664    /// Error occurs, if the directory does not exist.  
665    /// 
666    /// The permissions and validity period of the returned URI depend on the origin directory 
667    /// (e.g., the top directory selected by [`FilePicker::pick_dir`]) 
668    /// 
669    /// # Note
670    /// For [`AndroidFs::create_new_file`] and etc, the system may sanitize path strings as needed, so those strings may not be used as it is.
671    /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
672    /// 
673    /// # Args
674    /// - ***uri*** :  
675    /// Base directory URI.  
676    /// Must be **readable**.  
677    /// 
678    /// - ***relative_path*** :
679    /// Relative path from base directory.
680    /// 
681    /// # Support
682    /// All Android version.
683    #[maybe_async]
684    pub fn try_resolve_dir_uri(
685        &self,
686        dir: &FileUri, 
687        relative_path: impl AsRef<std::path::Path>
688    ) -> Result<FileUri> {
689
690        #[cfg(not(target_os = "android"))] {
691            Err(Error::NOT_ANDROID)
692        }
693        #[cfg(target_os = "android")] {
694            self.impls().try_resolve_dir_uri(dir, relative_path).await
695        }
696    }
697
698    /// Build a URI of an entry located at the relative path from the specified directory.   
699    /// 
700    /// This function does **not** create any entries; it only constructs the URI.
701    /// 
702    /// This function does not perform checks on the arguments or the returned URI.  
703    /// Even if the dir argument refers to a file, no error occurs (and no panic either).
704    /// Instead, it simply returns an invalid URI that will cause errors if used with other functions.  
705    /// 
706    /// If you need check, consider using [`AndroidFs::try_resolve_file_uri`] or [`AndroidFs::try_resolve_dir_uri`] instead. 
707    /// Or use this with [`AndroidFs::get_type`].
708    /// 
709    /// The permissions and validity period of the returned URI depend on the origin directory 
710    /// (e.g., the top directory selected by [`FilePicker::pick_dir`]) 
711    /// 
712    /// # Note
713    /// For [`PublicStorage::create_new_file`] and etc, the system may sanitize path strings as needed, so those strings may not be used as it is.
714    /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
715    /// 
716    /// # Args
717    /// - ***uri*** :  
718    /// Base directory URI.  
719    /// Must be **readable**.  
720    /// 
721    /// - ***relative_path*** :
722    /// Relative path from base directory.
723    /// 
724    /// # Support
725    /// All Android version.
726    #[maybe_async]
727    pub fn resolve_uri_unvalidated(
728        &self, 
729        dir: &FileUri, 
730        relative_path: impl AsRef<std::path::Path>
731    ) -> Result<FileUri> {
732
733        #[cfg(not(target_os = "android"))] {
734            Err(Error::NOT_ANDROID)
735        }
736        #[cfg(target_os = "android")] {
737            self.impls().resolve_entry_uri_unvalidated(dir, relative_path).await
738        }
739    }
740
741    /// See [`AndroidFs::get_thumbnail_to`] for descriptions.  
742    /// 
743    /// If thumbnail does not wrote to dest, return false.
744    #[maybe_async]
745    pub fn get_thumbnail_to(
746        &self, 
747        src: &FileUri,
748        dest: &FileUri,
749        preferred_size: Size,
750        format: ImageFormat,
751    ) -> Result<bool> {
752
753        #[cfg(not(target_os = "android"))] {
754            Err(Error::NOT_ANDROID)
755        }
756        #[cfg(target_os = "android")] {
757            self.impls().get_file_thumbnail_to_file(src, dest, preferred_size, format).await
758        }
759    }
760
761    /// Get a file thumbnail.  
762    /// If thumbnail does not exist it, return None.
763    /// 
764    /// Note this does not cache. Please do it in your part if need.  
765    /// 
766    /// # Args
767    /// - ***uri*** :  
768    /// Targe file uri.  
769    /// Thumbnail availablty depends on the file provider.  
770    /// In general, images and videos are available.  
771    /// For file URIs via [`FileUri::from_path`], 
772    /// the file type must match the filename extension. 
773    /// In this case, the type is determined by the extension and generate thumbnails.  
774    /// Otherwise, thumbnails are provided through MediaStore, file provider, and etc.
775    /// 
776    /// - ***preferred_size*** :  
777    /// Optimal thumbnail size desired.  
778    /// This may return a thumbnail of a different size, 
779    /// but never more than double the requested size. 
780    /// In any case, the aspect ratio is maintained.
781    /// 
782    /// - ***format*** :  
783    /// Thumbnail image format.  
784    /// [`ImageFormat::Jpeg`] is recommended. 
785    /// If you need transparency, use others.
786    /// 
787    /// # Support
788    /// All Android version.
789    #[maybe_async]
790    pub fn get_thumbnail(
791        &self,
792        uri: &FileUri,
793        preferred_size: Size,
794        format: ImageFormat,
795    ) -> Result<Option<Vec<u8>>> {
796
797        #[cfg(not(target_os = "android"))] {
798            Err(Error::NOT_ANDROID)
799        }
800        #[cfg(target_os = "android")] {
801            self.impls().get_file_thumbnail_in_memory(uri, preferred_size, format).await
802        }
803    }
804
805    /// Creates a new empty file in the specified location and returns a URI.   
806    /// 
807    /// The permissions and validity period of the returned URIs depend on the origin directory 
808    /// (e.g., the top directory selected by [`FilePicker::pick_dir`]) 
809    /// 
810    /// # Args  
811    /// - ***dir*** :  
812    /// The URI of the base directory.  
813    /// Must be **read-write**.
814    ///  
815    /// - ***relative_path*** :  
816    /// The file path relative to the base directory.  
817    /// Any missing subdirectories in the specified path will be created automatically.  
818    /// If a file with the same name already exists, 
819    /// the system append a sequential number to ensure uniqueness.  
820    /// If no extension is present, 
821    /// the system may infer one from ***mime_type*** and may append it to the file name. 
822    /// But this append-extension operation depends on the model and version.  
823    /// The system may sanitize these strings as needed, so those strings may not be used as it is.
824    ///  
825    /// - ***mime_type*** :  
826    /// The MIME type of the file to be created.  
827    /// If this is None, MIME type is inferred from the extension of ***relative_path***
828    /// and if that fails, `application/octet-stream` is used.  
829    ///  
830    /// # Support
831    /// All Android version.
832    #[maybe_async]
833    pub fn create_new_file(
834        &self,
835        dir: &FileUri, 
836        relative_path: impl AsRef<std::path::Path>, 
837        mime_type: Option<&str>
838    ) -> Result<FileUri> {
839
840        #[cfg(not(target_os = "android"))] {
841            Err(Error::NOT_ANDROID)
842        }
843        #[cfg(target_os = "android")] {
844            self.impls().create_new_file(dir, relative_path, mime_type).await
845        }
846    }
847
848    /// Recursively create a directory and all of its parent components if they are missing,
849    /// then return the URI.  
850    /// If it already exists, do nothing and just return the direcotry uri.
851    /// 
852    /// [`AndroidFs::create_new_file`] does this automatically, so there is no need to use it together.
853    /// 
854    /// # Args  
855    /// - ***dir*** :  
856    /// The URI of the base directory.  
857    /// Must be **read-write**.
858    ///  
859    /// - ***relative_path*** :  
860    /// The directory path relative to the base directory.    
861    /// The system may sanitize these strings as needed, so those strings may not be used as it is.
862    ///  
863    /// # Support
864    /// All Android version.
865    #[maybe_async]
866    pub fn create_dir_all(
867        &self,
868        dir: &FileUri, 
869        relative_path: impl AsRef<std::path::Path>, 
870    ) -> Result<FileUri> {
871
872        #[cfg(not(target_os = "android"))] {
873            Err(Error::NOT_ANDROID)
874        }
875        #[cfg(target_os = "android")] {
876            self.impls().create_dir_all(dir, relative_path).await
877        }
878    }
879
880    /// Returns the child files and directories of the specified directory.  
881    /// The order of the entries is not guaranteed.  
882    /// 
883    /// The permissions and validity period of the returned URIs depend on the origin directory 
884    /// (e.g., the top directory selected by [`FilePicker::pick_dir`])  
885    /// 
886    /// This retrieves all metadata including `uri`, `name`, `last_modified`, `len`, and `mime_type`. 
887    /// If only specific information is needed, 
888    /// using [`AndroidFs::read_dir_with_options`] will improve performance.
889    /// 
890    /// # Note
891    /// The returned type is an iterator, but the file system call is not executed lazily.  
892    /// Instead, all data is retrieved at once.  
893    /// For directories containing thousands or even tens of thousands of entries,  
894    /// this function may take several seconds to complete.  
895    /// The returned iterator itself is low-cost, as it only performs lightweight data formatting.
896    /// 
897    /// # Args
898    /// - ***uri*** :  
899    /// Target directory URI.  
900    /// Must be **readable**.
901    /// 
902    /// # Support
903    /// All Android version.
904    #[maybe_async]
905    pub fn read_dir(&self, uri: &FileUri) -> Result<impl Iterator<Item = Entry>> {
906        let entries = self.read_dir_with_options(uri, EntryOptions::ALL).await?
907            .map(Entry::try_from)
908            .filter_map(Result::ok);
909        
910        Ok(entries)
911    }
912
913    /// Returns the child files and directories of the specified directory.  
914    /// The order of the entries is not guaranteed.  
915    /// 
916    /// The permissions and validity period of the returned URIs depend on the origin directory 
917    /// (e.g., the top directory selected by [`FilePicker::pick_dir`])  
918    /// 
919    /// # Note
920    /// The returned type is an iterator, but the file system call is not executed lazily.  
921    /// Instead, all data is retrieved at once.  
922    /// For directories containing thousands or even tens of thousands of entries,  
923    /// this function may take several seconds to complete.  
924    /// The returned iterator itself is low-cost, as it only performs lightweight data formatting.
925    /// 
926    /// # Args
927    /// - ***uri*** :  
928    /// Target directory URI.  
929    /// Must be **readable**.
930    /// 
931    /// # Support
932    /// All Android version.
933    #[maybe_async]
934    pub fn read_dir_with_options(
935        &self, 
936        uri: &FileUri, 
937        options: EntryOptions
938    ) -> Result<impl Iterator<Item = OptionalEntry>> {
939        
940        #[cfg(not(target_os = "android"))] {
941            Err::<std::iter::Empty<_>, _>(Error::NOT_ANDROID)
942        }
943        #[cfg(target_os = "android")] {
944            self.impls().read_dir_with_options(uri, options).await
945        }
946    }
947
948    /// Take persistent permission to access the file, directory and its descendants.  
949    /// This is a prolongation of an already acquired permission, not the acquisition of a new one.  
950    /// 
951    /// This works by just calling, without displaying any confirmation to the user.
952    /// 
953    /// Note that [there is a limit to the total number of URI that can be made persistent by this function.](https://stackoverflow.com/questions/71099575/should-i-release-persistableuripermission-when-a-new-storage-location-is-chosen/71100621#71100621)  
954    /// Therefore, it is recommended to relinquish the unnecessary persisted URI by [`AndroidFs::release_persisted_uri_permission`] or [`AndroidFs::release_all_persisted_uri_permissions`].  
955    /// Persisted permissions may be relinquished by other apps, user, or by moving/removing entries.
956    /// So check by [`AndroidFs::check_persisted_uri_permission`].  
957    /// And you can retrieve the list of persisted uris using [`AndroidFs::get_all_persisted_uri_permissions`].
958    /// 
959    /// # Args
960    /// - **uri** :  
961    /// URI of the target file or directory.   
962    /// This must be a URI taken from following :  
963    ///     - [`FilePicker::pick_files`]  
964    ///     - [`FilePicker::pick_file`]  
965    ///     - [`FilePicker::pick_visual_medias`]  
966    ///     - [`FilePicker::pick_visual_media`]  
967    ///     - [`FilePicker::pick_dir`]  
968    ///     - [`FilePicker::save_file`]  
969    ///     - [`AndroidFs::try_resolve_file_uri`], [`AndroidFs::try_resolve_dir_uri`], [`AndroidFs::resolve_uri`], [`AndroidFs::read_dir`], [`AndroidFs::create_new_file`], [`AndroidFs::create_dir_all`] :  
970    ///     If use URI from thoese fucntions, the permissions of the origin directory URI is persisted, not a entry iteself by this function. 
971    ///     Because the permissions and validity period of the descendant entry URIs depend on the origin directory.   
972    /// 
973    /// # Support
974    /// All Android version. 
975    #[maybe_async]
976    pub fn take_persistable_uri_permission(&self, uri: &FileUri) -> Result<()> {
977        #[cfg(not(target_os = "android"))] {
978            Err(Error::NOT_ANDROID)
979        }
980        #[cfg(target_os = "android")] {
981            self.impls().take_persistable_uri_permission(uri).await
982        }
983    }
984
985    /// Check a persisted URI permission grant by [`AndroidFs::take_persistable_uri_permission`].  
986    /// Returns false if there are only non-persistent permissions or no permissions.
987    /// 
988    /// # Args
989    /// - **uri** :  
990    /// URI of the target file or directory.  
991    /// This must be a URI taken from following :  
992    ///     - [`FilePicker::pick_files`]  
993    ///     - [`FilePicker::pick_file`]  
994    ///     - [`FilePicker::pick_visual_medias`]  
995    ///     - [`FilePicker::pick_visual_media`]  
996    ///     - [`FilePicker::pick_dir`]  
997    ///     - [`FilePicker::save_file`]  
998    ///     - [`AndroidFs::try_resolve_file_uri`], [`AndroidFs::try_resolve_dir_uri`], [`AndroidFs::resolve_uri`], [`AndroidFs::read_dir`], [`AndroidFs::create_new_file`], [`AndroidFs::create_dir_all`] :  
999    ///     If use URI from thoese fucntions, the permissions of the origin directory URI is checked, not a entry iteself by this function. 
1000    ///     Because the permissions and validity period of the descendant entry URIs depend on the origin directory.   
1001    /// 
1002    /// - **mode** :  
1003    /// The mode of permission you want to check.  
1004    /// 
1005    /// # Support
1006    /// All Android version.
1007    #[maybe_async]
1008    pub fn check_persisted_uri_permission(
1009        &self, 
1010        uri: &FileUri, 
1011        mode: PersistableAccessMode
1012    ) -> Result<bool> {
1013
1014        #[cfg(not(target_os = "android"))] {
1015            Err(Error::NOT_ANDROID)
1016        }
1017        #[cfg(target_os = "android")] {
1018            self.impls().check_persisted_uri_permission(uri, mode).await
1019        }
1020    }
1021
1022    /// Return list of all persisted URIs that have been persisted by [`AndroidFs::take_persistable_uri_permission`] and currently valid.   
1023    /// 
1024    /// # Support
1025    /// All Android version.
1026    #[maybe_async]
1027    pub fn get_all_persisted_uri_permissions(&self) -> Result<impl Iterator<Item = PersistedUriPermission>> {
1028        #[cfg(not(target_os = "android"))] {
1029            Err::<std::iter::Empty<_>, _>(Error::NOT_ANDROID)
1030        }
1031        #[cfg(target_os = "android")] {
1032            self.impls().get_all_persisted_uri_permissions().await
1033        }
1034    }
1035
1036    /// Relinquish a persisted URI permission grant by [`AndroidFs::take_persistable_uri_permission`].   
1037    /// 
1038    /// # Args
1039    /// - ***uri*** :  
1040    /// URI of the target file or directory.  
1041    ///
1042    /// # Support
1043    /// All Android version.
1044    #[maybe_async]
1045    pub fn release_persisted_uri_permission(&self, uri: &FileUri) -> Result<()> {
1046        #[cfg(not(target_os = "android"))] {
1047            Err(Error::NOT_ANDROID)
1048        }
1049        #[cfg(target_os = "android")] {
1050            self.impls().release_persisted_uri_permission(uri).await
1051        }
1052    }
1053
1054    /// Relinquish a all persisted uri permission grants by [`AndroidFs::take_persistable_uri_permission`].  
1055    /// 
1056    /// # Support
1057    /// All Android version.
1058    #[maybe_async]
1059    pub fn release_all_persisted_uri_permissions(&self) -> crate::Result<()> {
1060        #[cfg(not(target_os = "android"))] {
1061            Err(Error::NOT_ANDROID)
1062        }
1063        #[cfg(target_os = "android")] {
1064            self.impls().release_all_persisted_uri_permissions().await
1065        }
1066    }
1067
1068    /// See [`PublicStorage::get_volumes`] or [`PrivateStorage::get_volumes`] for details.
1069    /// 
1070    /// The difference is that this does not perform any filtering.
1071    /// You can it by [`StorageVolume { is_available_for_public_storage, is_available_for_private_storage, .. } `](StorageVolume).
1072    #[maybe_async]
1073    pub fn get_volumes(&self) -> Result<Vec<StorageVolume>> {
1074        #[cfg(not(target_os = "android"))] {
1075            Err(Error::NOT_ANDROID)
1076        }
1077        #[cfg(target_os = "android")] {
1078            self.impls().get_available_storage_volumes().await
1079        }
1080    }
1081
1082    /// See [`PublicStorage::get_primary_volume`] or [`PrivateStorage::get_primary_volume`] for details.
1083    /// 
1084    /// The difference is that this does not perform any filtering.
1085    /// You can it by [`StorageVolume { is_available_for_public_storage, is_available_for_private_storage, .. } `](StorageVolume).
1086    #[maybe_async]
1087    pub fn get_primary_volume(&self) -> Result<Option<StorageVolume>> {
1088        #[cfg(not(target_os = "android"))] {
1089            Err(Error::NOT_ANDROID)
1090        }
1091        #[cfg(target_os = "android")] {
1092            self.impls().get_primary_storage_volume_if_available().await
1093        }
1094    }
1095
1096    /// Verify whether this plugin is available.  
1097    /// 
1098    /// On Android, this returns true.  
1099    /// On other platforms, this returns false.  
1100    #[always_sync]
1101    pub fn is_available(&self) -> bool {
1102        cfg!(target_os = "android")
1103    }
1104
1105    /// Get the api level of this Android device.
1106    /// 
1107    /// The correspondence table between API levels and Android versions can be found following.  
1108    /// <https://developer.android.com/guide/topics/manifest/uses-sdk-element#api-level-table>
1109    /// 
1110    /// If you want the constant value of the API level from an Android version, there is the [`api_level`] module.
1111    /// 
1112    /// # Table
1113    /// | Android version  | API Level |
1114    /// |------------------|-----------|
1115    /// | 16.0             | 36        |
1116    /// | 15.0             | 35        |
1117    /// | 14.0             | 34        |
1118    /// | 13.0             | 33        |
1119    /// | 12L              | 32        |
1120    /// | 12.0             | 31        |
1121    /// | 11.0             | 30        |
1122    /// | 10.0             | 29        |
1123    /// | 9.0              | 28        |
1124    /// | 8.1              | 27        |
1125    /// | 8.0              | 26        |
1126    /// | 7.1 - 7.1.2      | 25        |
1127    /// | 7.0              | 24        |
1128    /// 
1129    /// Tauri does not support Android versions below 7.
1130    #[always_sync]
1131    pub fn api_level(&self) -> Result<i32> {
1132        #[cfg(not(target_os = "android"))] {
1133            Err(Error::NOT_ANDROID)
1134        }
1135        #[cfg(target_os = "android")] {
1136            self.impls().api_level()
1137        }
1138    }
1139
1140
1141    #[deprecated = "use `AndroidFs::resolve_uri_unvalidated`"]
1142    #[maybe_async]
1143    pub fn resolve_uri(
1144        &self, 
1145        dir: &FileUri, 
1146        relative_path: impl AsRef<std::path::Path>
1147    ) -> Result<FileUri> {
1148
1149        self.resolve_uri_unvalidated(dir, relative_path).await
1150    }
1151}