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