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) -> 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 **read-writable**.
572 /// If not file, an error will occur.
573 ///
574 /// # Support
575 /// All Android version.
576 #[maybe_async]
577 pub fn remove_file(&self, uri: &FileUri) -> Result<()> {
578 #[cfg(not(target_os = "android"))] {
579 Err(Error::NOT_ANDROID)
580 }
581 #[cfg(target_os = "android")] {
582 self.impls().remove_file(uri).await
583 }
584 }
585
586 /// Remove the **empty** directory.
587 ///
588 /// # Args
589 /// - ***uri*** :
590 /// Target directory URI.
591 /// Must be **read-writable**.
592 /// If not empty directory, an error will occur.
593 ///
594 /// # Support
595 /// All Android version.
596 #[maybe_async]
597 pub fn remove_dir(&self, uri: &FileUri) -> Result<()> {
598 #[cfg(not(target_os = "android"))] {
599 Err(Error::NOT_ANDROID)
600 }
601 #[cfg(target_os = "android")] {
602 self.impls().remove_dir_if_empty(uri).await
603 }
604 }
605
606 /// Removes a directory and all its contents. Use carefully!
607 ///
608 /// # Args
609 /// - ***uri*** :
610 /// Target directory URI.
611 /// Must be **read-writable**.
612 /// If not directory, an error will occur.
613 ///
614 /// # Support
615 /// All Android version.
616 #[maybe_async]
617 pub fn remove_dir_all(&self, uri: &FileUri) -> Result<()> {
618 #[cfg(not(target_os = "android"))] {
619 Err(Error::NOT_ANDROID)
620 }
621 #[cfg(target_os = "android")] {
622 self.impls().remove_dir_all(uri).await
623 }
624 }
625
626 /// Build a URI of an **existing** file located at the relative path from the specified directory.
627 /// Error occurs, if the file does not exist.
628 ///
629 /// The permissions and validity period of the returned URI depend on the origin directory
630 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
631 ///
632 /// # Note
633 /// 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.
634 /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
635 ///
636 /// # Args
637 /// - ***uri*** :
638 /// Base directory URI.
639 /// Must be **readable**.
640 ///
641 /// - ***relative_path*** :
642 /// Relative path from base directory.
643 ///
644 /// # Support
645 /// All Android version.
646 #[maybe_async]
647 pub fn try_resolve_file_uri(
648 &self,
649 dir: &FileUri,
650 relative_path: impl AsRef<std::path::Path>
651 ) -> Result<FileUri> {
652
653 #[cfg(not(target_os = "android"))] {
654 Err(Error::NOT_ANDROID)
655 }
656 #[cfg(target_os = "android")] {
657 self.impls().try_resolve_file_uri(dir, relative_path).await
658 }
659 }
660
661 /// Build a URI of an **existing** directory located at the relative path from the specified directory.
662 /// Error occurs, if the directory does not exist.
663 ///
664 /// The permissions and validity period of the returned URI depend on the origin directory
665 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
666 ///
667 /// # Note
668 /// 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.
669 /// However, this function does not perform any sanitization, so the same ***relative_path*** may still fail.
670 ///
671 /// # Args
672 /// - ***uri*** :
673 /// Base directory URI.
674 /// Must be **readable**.
675 ///
676 /// - ***relative_path*** :
677 /// Relative path from base directory.
678 ///
679 /// # Support
680 /// All Android version.
681 #[maybe_async]
682 pub fn try_resolve_dir_uri(
683 &self,
684 dir: &FileUri,
685 relative_path: impl AsRef<std::path::Path>
686 ) -> Result<FileUri> {
687
688 #[cfg(not(target_os = "android"))] {
689 Err(Error::NOT_ANDROID)
690 }
691 #[cfg(target_os = "android")] {
692 self.impls().try_resolve_dir_uri(dir, relative_path).await
693 }
694 }
695
696 /// See [`AndroidFs::get_thumbnail_to`] for descriptions.
697 ///
698 /// If thumbnail does not wrote to dest, return false.
699 #[maybe_async]
700 pub fn get_thumbnail_to(
701 &self,
702 src: &FileUri,
703 dest: &FileUri,
704 preferred_size: Size,
705 format: ImageFormat,
706 ) -> Result<bool> {
707
708 #[cfg(not(target_os = "android"))] {
709 Err(Error::NOT_ANDROID)
710 }
711 #[cfg(target_os = "android")] {
712 self.impls().get_file_thumbnail_to_file(src, dest, preferred_size, format).await
713 }
714 }
715
716 /// Get a file thumbnail.
717 /// If thumbnail does not exist it, return None.
718 ///
719 /// Note this does not cache. Please do it in your part if need.
720 ///
721 /// # Args
722 /// - ***uri*** :
723 /// Targe file uri.
724 /// Thumbnail availablty depends on the file provider.
725 /// In general, images and videos are available.
726 /// For file URIs via [`FileUri::from_path`],
727 /// the file type must match the filename extension.
728 /// In this case, the type is determined by the extension and generate thumbnails.
729 /// Otherwise, thumbnails are provided through MediaStore, file provider, and etc.
730 ///
731 /// - ***preferred_size*** :
732 /// Optimal thumbnail size desired.
733 /// This may return a thumbnail of a different size,
734 /// but never more than double the requested size.
735 /// In any case, the aspect ratio is maintained.
736 ///
737 /// - ***format*** :
738 /// Thumbnail image format.
739 /// [`ImageFormat::Jpeg`] is recommended.
740 /// If you need transparency, use others.
741 ///
742 /// # Support
743 /// All Android version.
744 #[maybe_async]
745 pub fn get_thumbnail(
746 &self,
747 uri: &FileUri,
748 preferred_size: Size,
749 format: ImageFormat,
750 ) -> Result<Option<Vec<u8>>> {
751
752 #[cfg(not(target_os = "android"))] {
753 Err(Error::NOT_ANDROID)
754 }
755 #[cfg(target_os = "android")] {
756 self.impls().get_file_thumbnail_in_memory(uri, preferred_size, format).await
757 }
758 }
759
760 /// Creates a new empty file in the specified location and returns a URI.
761 ///
762 /// The permissions and validity period of the returned URIs depend on the origin directory
763 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
764 ///
765 /// # Args
766 /// - ***dir*** :
767 /// The URI of the base directory.
768 /// Must be **read-write**.
769 ///
770 /// - ***relative_path*** :
771 /// The file path relative to the base directory.
772 /// Any missing parent directories will be created recursively.
773 /// If a file with the same name already exists,
774 /// the system append a sequential number to ensure uniqueness.
775 /// If no extension is present,
776 /// the system may infer one from ***mime_type*** and may append it to the file name.
777 /// But this append-extension operation depends on the model and version.
778 /// The system may sanitize these strings as needed, so those strings may not be used as it is.
779 ///
780 /// - ***mime_type*** :
781 /// The MIME type of the file to be created.
782 /// If this is None, MIME type is inferred from the extension of ***relative_path***
783 /// and if that fails, `application/octet-stream` is used.
784 ///
785 /// # Support
786 /// All Android version.
787 #[maybe_async]
788 pub fn create_new_file(
789 &self,
790 dir: &FileUri,
791 relative_path: impl AsRef<std::path::Path>,
792 mime_type: Option<&str>
793 ) -> Result<FileUri> {
794
795 #[cfg(not(target_os = "android"))] {
796 Err(Error::NOT_ANDROID)
797 }
798 #[cfg(target_os = "android")] {
799 self.impls().create_new_file(dir, relative_path, mime_type).await
800 }
801 }
802
803 /// Recursively create a directory and all of its parent components if they are missing,
804 /// then return the URI.
805 /// If it already exists, do nothing and just return the direcotry uri.
806 ///
807 /// [`AndroidFs::create_new_file`] does this automatically, so there is no need to use it together.
808 ///
809 /// # Args
810 /// - ***dir*** :
811 /// The URI of the base directory.
812 /// Must be **read-write**.
813 ///
814 /// - ***relative_path*** :
815 /// The directory path relative to the base directory.
816 /// The system may sanitize these strings as needed, so those strings may not be used as it is.
817 ///
818 /// # Support
819 /// All Android version.
820 #[maybe_async]
821 pub fn create_dir_all(
822 &self,
823 dir: &FileUri,
824 relative_path: impl AsRef<std::path::Path>,
825 ) -> Result<FileUri> {
826
827 #[cfg(not(target_os = "android"))] {
828 Err(Error::NOT_ANDROID)
829 }
830 #[cfg(target_os = "android")] {
831 self.impls().create_dir_all(dir, relative_path).await
832 }
833 }
834
835 /// Returns the child files and directories of the specified directory.
836 /// The order of the entries is not guaranteed.
837 ///
838 /// The permissions and validity period of the returned URIs depend on the origin directory
839 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
840 ///
841 /// This retrieves all metadata including `uri`, `name`, `last_modified`, `len`, and `mime_type`.
842 /// If only specific information is needed,
843 /// using [`AndroidFs::read_dir_with_options`] will improve performance.
844 ///
845 /// # Note
846 /// The returned type is an iterator, but the file system call is not executed lazily.
847 /// Instead, all data is retrieved at once.
848 /// For directories containing thousands or even tens of thousands of entries,
849 /// this function may take several seconds to complete.
850 /// The returned iterator itself is low-cost, as it only performs lightweight data formatting.
851 ///
852 /// # Args
853 /// - ***uri*** :
854 /// Target directory URI.
855 /// Must be **readable**.
856 ///
857 /// # Support
858 /// All Android version.
859 #[maybe_async]
860 pub fn read_dir(&self, uri: &FileUri) -> Result<impl Iterator<Item = Entry>> {
861 let entries = self.read_dir_with_options(uri, EntryOptions::ALL).await?
862 .map(Entry::try_from)
863 .filter_map(Result::ok);
864
865 Ok(entries)
866 }
867
868 /// Returns the child files and directories of the specified directory.
869 /// The order of the entries is not guaranteed.
870 ///
871 /// The permissions and validity period of the returned URIs depend on the origin directory
872 /// (e.g., the top directory selected by [`FilePicker::pick_dir`])
873 ///
874 /// # Note
875 /// The returned type is an iterator, but the file system call is not executed lazily.
876 /// Instead, all data is retrieved at once.
877 /// For directories containing thousands or even tens of thousands of entries,
878 /// this function may take several seconds to complete.
879 /// The returned iterator itself is low-cost, as it only performs lightweight data formatting.
880 ///
881 /// # Args
882 /// - ***uri*** :
883 /// Target directory URI.
884 /// Must be **readable**.
885 ///
886 /// # Support
887 /// All Android version.
888 #[maybe_async]
889 pub fn read_dir_with_options(
890 &self,
891 uri: &FileUri,
892 options: EntryOptions
893 ) -> Result<impl Iterator<Item = OptionalEntry>> {
894
895 #[cfg(not(target_os = "android"))] {
896 Err::<std::iter::Empty<_>, _>(Error::NOT_ANDROID)
897 }
898 #[cfg(target_os = "android")] {
899 self.impls().read_dir_with_options(uri, options).await
900 }
901 }
902
903 /// Take persistent permission to access the file, directory and its descendants.
904 /// This is a prolongation of an already acquired permission, not the acquisition of a new one.
905 ///
906 /// This works by just calling, without displaying any confirmation to the user.
907 ///
908 /// 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)
909 /// Therefore, it is recommended to relinquish the unnecessary persisted URI by [`AndroidFs::release_persisted_uri_permission`] or [`AndroidFs::release_all_persisted_uri_permissions`].
910 /// Persisted permissions may be relinquished by other apps, user, or by moving/removing entries.
911 /// So check by [`AndroidFs::check_persisted_uri_permission`].
912 /// And you can retrieve the list of persisted uris using [`AndroidFs::get_all_persisted_uri_permissions`].
913 ///
914 /// # Args
915 /// - **uri** :
916 /// URI of the target file or directory.
917 /// This must be a URI taken from following :
918 /// - [`FilePicker::pick_files`]
919 /// - [`FilePicker::pick_file`]
920 /// - [`FilePicker::pick_visual_medias`]
921 /// - [`FilePicker::pick_visual_media`]
922 /// - [`FilePicker::pick_dir`]
923 /// - [`FilePicker::save_file`]
924 /// - [`AndroidFs::try_resolve_file_uri`], [`AndroidFs::try_resolve_dir_uri`], [`AndroidFs::resolve_uri`], [`AndroidFs::read_dir`], [`AndroidFs::create_new_file`], [`AndroidFs::create_dir_all`] :
925 /// If use URI from thoese fucntions, the permissions of the origin directory URI is persisted, not a entry iteself by this function.
926 /// Because the permissions and validity period of the descendant entry URIs depend on the origin directory.
927 ///
928 /// # Support
929 /// All Android version.
930 #[maybe_async]
931 pub fn take_persistable_uri_permission(&self, uri: &FileUri) -> Result<()> {
932 #[cfg(not(target_os = "android"))] {
933 Err(Error::NOT_ANDROID)
934 }
935 #[cfg(target_os = "android")] {
936 self.impls().take_persistable_uri_permission(uri).await
937 }
938 }
939
940 /// Check a persisted URI permission grant by [`AndroidFs::take_persistable_uri_permission`].
941 /// Returns false if there are only non-persistent permissions or no permissions.
942 ///
943 /// # Args
944 /// - **uri** :
945 /// URI of the target file or directory.
946 /// This must be a URI taken from following :
947 /// - [`FilePicker::pick_files`]
948 /// - [`FilePicker::pick_file`]
949 /// - [`FilePicker::pick_visual_medias`]
950 /// - [`FilePicker::pick_visual_media`]
951 /// - [`FilePicker::pick_dir`]
952 /// - [`FilePicker::save_file`]
953 /// - [`AndroidFs::try_resolve_file_uri`], [`AndroidFs::try_resolve_dir_uri`], [`AndroidFs::resolve_uri`], [`AndroidFs::read_dir`], [`AndroidFs::create_new_file`], [`AndroidFs::create_dir_all`] :
954 /// If use URI from thoese fucntions, the permissions of the origin directory URI is checked, not a entry iteself by this function.
955 /// Because the permissions and validity period of the descendant entry URIs depend on the origin directory.
956 ///
957 /// - **mode** :
958 /// The mode of permission you want to check.
959 ///
960 /// # Support
961 /// All Android version.
962 #[maybe_async]
963 pub fn check_persisted_uri_permission(
964 &self,
965 uri: &FileUri,
966 mode: PersistableAccessMode
967 ) -> Result<bool> {
968
969 #[cfg(not(target_os = "android"))] {
970 Err(Error::NOT_ANDROID)
971 }
972 #[cfg(target_os = "android")] {
973 self.impls().check_persisted_uri_permission(uri, mode).await
974 }
975 }
976
977 /// Return list of all persisted URIs that have been persisted by [`AndroidFs::take_persistable_uri_permission`] and currently valid.
978 ///
979 /// # Support
980 /// All Android version.
981 #[maybe_async]
982 pub fn get_all_persisted_uri_permissions(&self) -> Result<impl Iterator<Item = PersistedUriPermission>> {
983 #[cfg(not(target_os = "android"))] {
984 Err::<std::iter::Empty<_>, _>(Error::NOT_ANDROID)
985 }
986 #[cfg(target_os = "android")] {
987 self.impls().get_all_persisted_uri_permissions().await
988 }
989 }
990
991 /// Relinquish a persisted URI permission grant by [`AndroidFs::take_persistable_uri_permission`].
992 ///
993 /// # Args
994 /// - ***uri*** :
995 /// URI of the target file or directory.
996 ///
997 /// # Support
998 /// All Android version.
999 #[maybe_async]
1000 pub fn release_persisted_uri_permission(&self, uri: &FileUri) -> Result<()> {
1001 #[cfg(not(target_os = "android"))] {
1002 Err(Error::NOT_ANDROID)
1003 }
1004 #[cfg(target_os = "android")] {
1005 self.impls().release_persisted_uri_permission(uri).await
1006 }
1007 }
1008
1009 /// Relinquish a all persisted uri permission grants by [`AndroidFs::take_persistable_uri_permission`].
1010 ///
1011 /// # Support
1012 /// All Android version.
1013 #[maybe_async]
1014 pub fn release_all_persisted_uri_permissions(&self) -> Result<()> {
1015 #[cfg(not(target_os = "android"))] {
1016 Err(Error::NOT_ANDROID)
1017 }
1018 #[cfg(target_os = "android")] {
1019 self.impls().release_all_persisted_uri_permissions().await
1020 }
1021 }
1022
1023 /// See [`PublicStorage::get_volumes`] or [`PrivateStorage::get_volumes`] for details.
1024 ///
1025 /// The difference is that this does not perform any filtering.
1026 /// You can it by [`StorageVolume { is_available_for_public_storage, is_available_for_private_storage, .. } `](StorageVolume).
1027 #[maybe_async]
1028 pub fn get_volumes(&self) -> Result<Vec<StorageVolume>> {
1029 #[cfg(not(target_os = "android"))] {
1030 Err(Error::NOT_ANDROID)
1031 }
1032 #[cfg(target_os = "android")] {
1033 self.impls().get_available_storage_volumes().await
1034 }
1035 }
1036
1037 /// See [`PublicStorage::get_primary_volume`] or [`PrivateStorage::get_primary_volume`] for details.
1038 ///
1039 /// The difference is that this does not perform any filtering.
1040 /// You can it by [`StorageVolume { is_available_for_public_storage, is_available_for_private_storage, .. } `](StorageVolume).
1041 #[maybe_async]
1042 pub fn get_primary_volume(&self) -> Result<Option<StorageVolume>> {
1043 #[cfg(not(target_os = "android"))] {
1044 Err(Error::NOT_ANDROID)
1045 }
1046 #[cfg(target_os = "android")] {
1047 self.impls().get_primary_storage_volume_if_available().await
1048 }
1049 }
1050
1051 /// Verify whether this plugin is available.
1052 ///
1053 /// On Android, this returns true.
1054 /// On other platforms, this returns false.
1055 #[always_sync]
1056 pub fn is_available(&self) -> bool {
1057 cfg!(target_os = "android")
1058 }
1059
1060 /// Get the api level of this Android device.
1061 ///
1062 /// The correspondence table between API levels and Android versions can be found following.
1063 /// <https://developer.android.com/guide/topics/manifest/uses-sdk-element#api-level-table>
1064 ///
1065 /// If you want the constant value of the API level from an Android version, there is the [`api_level`] module.
1066 ///
1067 /// # Table
1068 /// | Android version | API Level |
1069 /// |------------------|-----------|
1070 /// | 16.0 | 36 |
1071 /// | 15.0 | 35 |
1072 /// | 14.0 | 34 |
1073 /// | 13.0 | 33 |
1074 /// | 12L | 32 |
1075 /// | 12.0 | 31 |
1076 /// | 11.0 | 30 |
1077 /// | 10.0 | 29 |
1078 /// | 9.0 | 28 |
1079 /// | 8.1 | 27 |
1080 /// | 8.0 | 26 |
1081 /// | 7.1 - 7.1.2 | 25 |
1082 /// | 7.0 | 24 |
1083 ///
1084 /// Tauri does not support Android versions below 7.
1085 #[always_sync]
1086 pub fn api_level(&self) -> Result<i32> {
1087 #[cfg(not(target_os = "android"))] {
1088 Err(Error::NOT_ANDROID)
1089 }
1090 #[cfg(target_os = "android")] {
1091 self.impls().api_level()
1092 }
1093 }
1094
1095
1096 #[deprecated = "This may not return the correct uri. Use try_resolve_file_uri or try_resolve_dir_uri instead"]
1097 #[maybe_async]
1098 pub fn resolve_uri_unvalidated(
1099 &self,
1100 dir: &FileUri,
1101 relative_path: impl AsRef<std::path::Path>
1102 ) -> Result<FileUri> {
1103
1104 #[cfg(not(target_os = "android"))] {
1105 Err(Error::NOT_ANDROID)
1106 }
1107 #[cfg(target_os = "android")] {
1108 self.impls().build_candidate_uri(dir, relative_path).await
1109 }
1110 }
1111
1112 #[deprecated = "This may not return the correct uri. Use try_resolve_file_uri or try_resolve_dir_uri instead"]
1113 #[maybe_async]
1114 pub fn resolve_uri(
1115 &self,
1116 dir: &FileUri,
1117 relative_path: impl AsRef<std::path::Path>
1118 ) -> Result<FileUri> {
1119
1120 #[cfg(not(target_os = "android"))] {
1121 Err(Error::NOT_ANDROID)
1122 }
1123 #[cfg(target_os = "android")] {
1124 self.impls().build_candidate_uri(dir, relative_path).await
1125 }
1126 }
1127}