tauri-plugin-android-fs 28.2.2

Android file system API for Tauri.
Documentation
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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
use sync_async::sync_async;
use crate::*;
use super::*;


#[sync_async(
    use(if_async) async_utils::sleep;
    use(if_sync) sync_utils::sleep;
)]
impl<'a, R: tauri::Runtime> Impls<'a, R> {

    #[maybe_async]
    pub fn get_entry_name(&self, uri: &FileUri) -> Result<String> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { name: String });

        self.invoke::<Res>("getName", Req { uri })
            .await
            .map(|v| v.name)
    }

    #[maybe_async]
    pub fn get_entry_type(&self, uri: &FileUri) -> Result<EntryType> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { value: Option<String> });

        self.invoke::<Res>("getMimeType", Req { uri })
            .await
            .map(|v| match v.value {
                Some(mime_type) => EntryType::File { mime_type },
                None => EntryType::Dir,
            })
    }

    #[maybe_async]
    pub fn get_entry_info(&self, uri: &FileUri) -> Result<Entry> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res {
            uri: FileUri,
            mime_type: Option<String>,
            name: String,
            last_modified: i64,
            len: Option<i64>, 
        });

        let v = self.invoke::<Res>("getMetadata", Req { uri }).await?;
        
        Ok(match v.mime_type {
            // ファイルの時は必ず Some(mime_type) になり、
            // フォルダの時にのみ None になる。
            Some(mime_type) => Entry::File {
                uri: v.uri,
                name: v.name,
                last_modified: std::time::UNIX_EPOCH + std::time::Duration::from_millis(i64::max(0, v.last_modified) as u64),
                len: i64::max(0, v.len.ok_or_else(|| Error::missing_value("len"))?) as u64,
                mime_type,
            },
            None => Entry::Dir {
                uri: v.uri,
                name: v.name,
                last_modified: std::time::UNIX_EPOCH + std::time::Duration::from_millis(i64::max(0, v.last_modified) as u64),
            }
        })
    }

    #[maybe_async]
    pub fn get_file_len(&self, uri: &FileUri) -> Result<u64> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { len: i64 });

        self.invoke::<Res>("getLen", Req { uri })
            .await
            .map(|v| i64::max(0, v.len) as u64)
    }

    #[maybe_async]
    pub fn get_file_resource_for_content_protocol(
        &self, 
        uri: &FileUri
    ) -> Result<(std::fs::File, Option<String>, Option<u64>)> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { fd: std::os::fd::RawFd, mime_type: Option<String>, len: Option<u64> });

        self.invoke::<Res>("getFileResourceForContentProtocol", Req { uri })
            .await
            .map(|r| {
                let file = unsafe {
                    use std::os::fd::FromRawFd;
                    std::fs::File::from_raw_fd(r.fd)
                };
                (file, r.mime_type, r.len)
            })
    }

    #[maybe_async]
    pub fn open_file(&self, uri: &FileUri, mode: FileAccessMode) -> Result<std::fs::File> {
        impl_se!(struct Req<'a> { uri: &'a FileUri, mode: &'a str });
        impl_de!(struct Res { fd: std::os::fd::RawFd });
    
        let mode = mode.to_mode();

        self.invoke::<Res>("getFileDescriptor", Req { uri, mode })
            .await
            .map(|v| {
                use std::os::fd::FromRawFd;
                unsafe { std::fs::File::from_raw_fd(v.fd) }
            })
    }

    #[maybe_async]
    pub fn open_file_with_fallback(
        &self, 
        uri: &FileUri, 
        candidate_modes: impl IntoIterator<Item = FileAccessMode>
    ) -> Result<(std::fs::File, FileAccessMode)> {

        impl_se!(struct Req<'a> { uri: &'a FileUri, modes: Vec<&'a str> });
        impl_de!(struct Res { fd: std::os::fd::RawFd, mode: String });
    
        let modes = candidate_modes.into_iter().map(|m| m.to_mode()).collect::<Vec<_>>();

        if modes.is_empty() {
            return Err(Error::with("candidate_modes must not be empty"));
        }

        self.invoke::<Res>("getFileDescriptorWithFallback", Req { uri, modes })
            .await
            .and_then(|v| FileAccessMode::from_mode(&v.mode).map(|m| (v.fd, m)))
            .map(|(fd, mode)| {
                let file = {
                    use std::os::fd::FromRawFd;
                    unsafe { std::fs::File::from_raw_fd(fd) }
                };
                (file, mode)
            })
    }

    #[maybe_async]
    pub fn rename_entry(&self, uri: &FileUri, new_name: impl AsRef<str>) -> Result<FileUri> {
        impl_se!(struct Req<'a> { uri: &'a FileUri, new_name: &'a str });

        let new_name = new_name.as_ref();

        self.invoke::<FileUri>("rename", Req { uri, new_name })
            .await
    }

    #[maybe_async]
    pub fn remove_file(&self, uri: &FileUri) -> Result<()> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res;);
    
        self.invoke::<Res>("deleteFile", Req { uri })
            .await
            .map(|_| ())
    }

    #[maybe_async]
    pub fn remove_dir_if_empty(&self, uri: &FileUri) -> Result<()> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res;);
        
        self.invoke::<Res>("deleteEmptyDir", Req { uri })
            .await
            .map(|_| ())
    }

    #[maybe_async]
    pub fn remove_dir_all(&self, uri: &FileUri) -> Result<()> {
        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res;);
        
        self.invoke::<Res>("deleteDirAll", Req { uri })
            .await
            .map(|_| ())
    }

    #[maybe_async]
    pub fn create_new_file(
        &self,
        dir: &FileUri, 
        relative_path: impl AsRef<std::path::Path>, 
        mime_type: Option<&str>
    ) -> Result<FileUri> {

        impl_se!(struct Req<'a> { dir: &'a FileUri, mime_type: Option<&'a str>, relative_path: &'a str });
        
        let relative_path = validate_relative_path(relative_path.as_ref())?;
        let relative_path = relative_path.to_string_lossy();
                
        self.invoke::<FileUri>("createFile", Req { dir, mime_type, relative_path: relative_path.as_ref() })
            .await
    }

    #[maybe_async]
    pub fn create_new_file_and_retrun_relative_path(
        &self,
        dir: &FileUri, 
        relative_path: impl AsRef<std::path::Path>, 
        mime_type: Option<&str>
    ) -> Result<(FileUri, std::path::PathBuf)> {

        impl_se!(struct Req<'a> { dir: &'a FileUri, mime_type: Option<&'a str>, relative_path: &'a str });
        impl_de!(struct Res { uri: FileUri, relative_path: std::path::PathBuf });

        let relative_path = validate_relative_path(relative_path.as_ref())?;
        let relative_path = relative_path.to_string_lossy();
                
        self.invoke::<Res>("createFileAndReturnRelativePath", Req { dir, mime_type, relative_path: relative_path.as_ref() })
            .await
            .map(|v| (v.uri, v.relative_path))
    }

    #[maybe_async]
    pub fn create_dir_all(
        &self,
        dir: &FileUri, 
        relative_path: impl AsRef<std::path::Path>, 
    ) -> Result<FileUri> {

        impl_se!(struct Req<'a> { dir: &'a FileUri,relative_path: &'a str });
        
        let relative_path = validate_relative_path(relative_path.as_ref())?;
        let relative_path = relative_path.to_string_lossy();
                
        self.invoke::<FileUri>("createDirAll", Req { dir, relative_path: relative_path.as_ref() })
            .await
    }

    #[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)> {

        impl_se!(struct Req<'a> { dir: &'a FileUri,relative_path: &'a str });
        impl_de!(struct Res { uri: FileUri, relative_path: std::path::PathBuf });
        
        let relative_path = validate_relative_path(relative_path.as_ref())?;
        let relative_path = relative_path.to_string_lossy();
                
        self.invoke::<Res>("createDirAllAndReturnRelativePath", Req { dir, relative_path: relative_path.as_ref() })
            .await
            .map(|v| (v.uri, v.relative_path))
    }

    #[maybe_async]
    pub fn create_new_dir(
        &self,
        dir: &FileUri, 
        relative_path: impl AsRef<std::path::Path>, 
    ) -> Result<FileUri> {

        impl_se!(struct Req<'a> { dir: &'a FileUri,relative_path: &'a str });
        
        let relative_path = validate_relative_path(relative_path.as_ref())?;
        let relative_path = relative_path.to_string_lossy();
                
        self.invoke::<FileUri>("createNewDir", Req { dir, relative_path: relative_path.as_ref() })
            .await
    }

    #[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)> {

        impl_se!(struct Req<'a> { dir: &'a FileUri,relative_path: &'a str });
        impl_de!(struct Res { uri: FileUri, relative_path: std::path::PathBuf });
        
        let relative_path = validate_relative_path(relative_path.as_ref())?;
        let relative_path = relative_path.to_string_lossy();
                
        self.invoke::<Res>("createNewDirAndReturnRelativePath", Req { dir, relative_path: relative_path.as_ref() })
            .await
            .map(|v| (v.uri, v.relative_path))
    }

    #[maybe_async]
    pub fn read_dir(
        &self, 
        uri: &FileUri, 
        options: EntryOptions,
        range: impl std::ops::RangeBounds<u64>
    ) -> Result<impl Iterator<Item = OptionalEntry>> {
        
        impl_se!(struct Req<'a> { uri: &'a FileUri, options: Ops, offset: &'a str, limit: Option<&'a str>, });
        // ファイルかフォルダかを知るために mime_type は常に取得する。
        impl_se!(struct Ops {
            uri: bool,
            name: bool,
            last_modified: bool,
            len: bool,
        });
        impl_de!(struct Res { entries: Vec<Obj> });
        impl_de!(struct Obj {
            uri: Option<FileUri>,
            mime_type: Option<String>,
            name: Option<String>,
            last_modified: Option<i64>,
            len: Option<i64>, 
        });

        let map_entry = move |v: Obj| -> OptionalEntry {
             let map_time = |millis: i64| -> std::time::SystemTime {
                use std::time::{UNIX_EPOCH, Duration};
                
                UNIX_EPOCH + Duration::from_millis(i64::max(0, millis) as u64)
            };

            // ファイルの時は必ず Some(mime_type) になり、
            // フォルダの時にのみ None になる。
            match v.mime_type {
                Some(mime_type) => OptionalEntry::File {
                    uri: v.uri,
                    name: v.name,
                    last_modified: v.last_modified.map(map_time),
                    len: v.len.map(|i| i64::max(0, i) as u64),
                    mime_type: if options.mime_type { Some(mime_type) } else { None },
                },
                None => OptionalEntry::Dir {
                    uri: v.uri,
                    name: v.name,
                    last_modified: v.last_modified.map(map_time),
                }
            }
        };


        let (offset, limit) = range_to_offset_and_len(range); 
        let entries;
        // range の要素は u64 で表されているため offset が u64::MAX を超えた場合は
        // 表現できない範囲として要素ゼロとして扱う。
        if limit == Some(0) || (u64::MAX as u128) < offset {
            entries = Vec::new();
        }
        else {
            let offset = saturate_u128_to_u64(offset);
            let limit = limit.map(saturate_u128_to_u64);
            let options = Ops {
                uri: options.uri,
                name: options.name,
                last_modified: options.last_modified,
                len: options.len,
            };

            entries = self.invoke::<Res>("readDir", Req {
                    uri, 
                    options, 
                    offset: &offset.to_string(), 
                    limit: limit.map(|l| l.to_string()).as_deref()
                })
                .await?
                .entries
        }

        Ok(entries.into_iter().map(map_entry))
    }

    #[maybe_async]
    pub fn get_file_thumbnail_to_file(
        &self, 
        src: &FileUri,
        dest: &FileUri,
        preferred_size: Size,
        format: ImageFormat,
    ) -> Result<bool> {

        impl_se!(struct Req<'a> {
            src: &'a FileUri, 
            dest: &'a FileUri,
            format: &'a str,
            quality: u8,
            width: u32,
            height: u32,
        });
        impl_de!(struct Res { value: bool });

        let (quality, format) = format.to_quality_and_format_str();
        let quality = (quality * 100.0).clamp(0.0, 100.0) as u8;
        let Size { width, height } = preferred_size;
        
        self.invoke::<Res>("getThumbnailToFile", Req { src, dest, format, quality, width, height })
            .await   
            .map(|v| v.value)
    }

    #[maybe_async]
    pub fn get_file_thumbnail_base64(
        &self, 
        uri: &FileUri,
        preferred_size: Size,
        format: ImageFormat,
    ) -> Result<Option<String>> {

        impl_se!(struct Req<'a> {
            uri: &'a FileUri, 
            format: &'a str,
            quality: u8,
            width: u32,
            height: u32,
        });
        impl_de!(struct Res { bytes: Option<String> });

        let (quality, format) = format.to_quality_and_format_str();
        let quality = (quality * 100.0).clamp(0.0, 100.0) as u8;
        let Size { width, height } = preferred_size;
        
        let Some(thumbnail) = self.invoke::<Res>("getThumbnail", Req { uri, format, quality, width, height })
            .await
            .map(|v| v.bytes)? else {
                    
            return Ok(None)
        };
        if thumbnail.is_empty() {
            return Ok(None)
        }

        Ok(Some(thumbnail))
    }

    #[maybe_async]
    pub fn check_media_store_volume_name_available(
        &self,
        media_store_volume_name: impl AsRef<str>,
    ) -> Result<bool> {

        impl_se!(struct Req<'a> { media_store_volume_name: &'a str });
        impl_de!(struct Res { value: bool });
            
        let media_store_volume_name = media_store_volume_name.as_ref();
            
        self.invoke::<Res>("checkMediaStoreVolumeNameAvailable", Req { media_store_volume_name })
            .await
            .map(|v| v.value)
    }

    #[maybe_async]
    pub fn check_storage_volume_available_by_path(
        &self,
        path: impl AsRef<std::path::Path>,
    ) -> Result<bool> {

        impl_se!(struct Req<'a> { path: &'a std::path::Path });
        impl_de!(struct Res { value: bool });

        let path = path.as_ref();

        self.invoke::<Res>("checkStorageVolumeAvailableByPath", Req { path })
            .await
            .map(|v| v.value)
    }

    #[maybe_async]
    pub fn get_available_storage_volumes(&self) -> Result<Vec<StorageVolume>> {
        impl_de!(struct Res { volumes: Vec<StorageVolume> });

        let mut volumes = self.invoke::<Res>("getAvailableStorageVolumes", "")
            .await
            .map(|v| v.volumes)?;

        // primary volume を先頭にする。他はそのままの順序
        volumes.sort_by(|a, b| b.is_primary.cmp(&a.is_primary));

        Ok(volumes)
    }

    #[maybe_async]
    pub fn get_primary_storage_volume_if_available(&self) -> Result<Option<StorageVolume>> {
        impl_de!(struct Res { volume: Option<StorageVolume> });

        self.invoke::<Res>("getPrimaryStorageVolumeIfAvailable", "")
            .await
            .map(|v| v.volume)
    }

    #[always_sync]
    pub fn consts(&self) -> Result<&'static Consts> {
        get_or_init_const(|| self.invoke_sync::<Consts>("getConsts", ""))
    }

    #[always_sync]
    pub fn private_dir_path(
        &self, 
        dir: PrivateDir
    ) -> Result<&'static std::path::PathBuf> {

        let paths = get_or_init_private_dir_paths(
            || self.invoke_sync::<PrivateDirPaths>("getPrivateBaseDirAbsolutePaths", "")
        )?;

        Ok(match dir {
            PrivateDir::Data => &paths.data,
            PrivateDir::Cache => &paths.cache,
            PrivateDir::NoBackupData => &paths.no_backup_data,
        })
    }

    #[maybe_async]
    pub fn set_media_store_file_pending(
        &self,
        uri: &FileUri,
        is_pending: bool
    ) -> Result<()> {

        impl_se!(struct Req<'a> { uri: &'a FileUri, pending: bool });
        impl_de!(struct Res;);

        self.invoke::<Res>("setMediaStoreFilePending", Req { uri, pending: is_pending })
            .await
            .map(|_| ())
    }

    #[maybe_async]
    pub fn create_new_media_store_file(
        &self,
        volume_id: Option<&StorageVolumeId>,
        base_dir: impl Into<PublicDir>,
        relative_path: impl AsRef<std::path::Path>, 
        mime_type: Option<&str>,
        is_pending: bool,
    ) -> Result<FileUri> {

        impl_se!(struct Req<'a> { 
            volume_name: Option<&'a str>, 
            relative_path: std::path::PathBuf, 
            mime_type: Option<&'a str>,
            pending: bool
        });
        impl_de!(struct Res { uri: FileUri });

        let consts = self.consts()?;
        let relative_path = {
            let mut p = std::path::PathBuf::new();
            p.push(consts.public_dir_name(base_dir)?);
            p.push(validate_relative_path(relative_path.as_ref())?);
            p
        };

        let volume_name = volume_id.and_then(|v| v.media_store_volume_name.as_deref());

        self.invoke::<Res>("createNewMediaStoreFile", Req {
                volume_name, 
                relative_path,
                mime_type,
                pending: is_pending
            })
            .await
            .map(|v| v.uri)
    }

    #[maybe_async]
    pub fn show_pick_file_dialog(
        &self,
        initial_location: Option<&FileUri>,
        mime_types: &[&str],
        multiple: bool,
        local_only: bool,
    ) -> Result<Vec<FileUri>> {

        impl_se!(struct Req<'a> { 
            mime_types: &'a [&'a str],
            multiple: bool,
            initial_location: Option<&'a FileUri>,
            local_only: bool
        });
        impl_de!(struct Res { uris: Vec<FileUri> });
    
        let result = self.invoke::<Res>("showOpenFileDialog", Req { mime_types, multiple, initial_location, local_only })
            .await
            .map(|v| v.uris);

        // kotlin から他のアプリを呼び出した後にすぐに frontend 側に戻ると、
        // その frontend 側の関数の呼び出しがなぜか終了しないことが偶にある。
        // よって遅延を強制的に追加してこれを回避する。
        // https://github.com/aiueo13/tauri-plugin-android-fs/issues/1
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_pick_visual_media_dialog(
        &self,
        target: VisualMediaTarget<'_>,
        multiple: bool,
        local_only: bool,
    ) -> Result<Vec<FileUri>> {

        impl_se!(struct Req<'a> { multiple: bool, target: &'a str, local_only: bool });
        impl_de!(struct Res { uris: Vec<FileUri> });

        let target = match target {
            VisualMediaTarget::ImageOnly => "image/*",
            VisualMediaTarget::VideoOnly => "video/*",
            VisualMediaTarget::ImageAndVideo => "*/*",
            VisualMediaTarget::ImageOrVideo { mime_type } => {
                let is_image_or_video = mime_type.starts_with("image/") || mime_type.starts_with("video/");
                if !is_image_or_video {
                    return Err(Error::with(format!("mime_type must be an image or a video, but {mime_type}")))
                }
                    
                mime_type
            }
        };
    
        let result = self.invoke::<Res>("showOpenVisualMediaDialog", Req { multiple, target, local_only })
            .await
            .map(|v| v.uris);

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_pick_content_dialog(
        &self,
        mime_types: &[&str],
        multiple: bool
    ) -> Result<Vec<FileUri>> {

        impl_se!(struct Req<'a> { mime_types: &'a [&'a str], multiple: bool });
        impl_de!(struct Res { uris: Vec<FileUri> });

        let result = self.invoke::<Res>("showOpenContentDialog", Req { mime_types, multiple })
            .await
            .map(|v| v.uris);

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_pick_dir_dialog(
        &self,
        initial_location: Option<&FileUri>,
        local_only: bool
    ) -> Result<Option<FileUri>> {

        impl_se!(struct Req<'a> { initial_location: Option<&'a FileUri>, local_only: bool });
        impl_de!(struct Res { uri: Option<FileUri> });

        let result = self.invoke::<Res>("showManageDirDialog", Req { initial_location, local_only })
            .await
            .map(|v| v.uri);

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_save_file_dialog(
        &self,
        initial_location: Option<&FileUri>,
        initial_file_name: impl AsRef<str>,
        mime_type: Option<&str>,
        local_only: bool,
    ) -> Result<Option<FileUri>> {
        
        impl_se!(struct Req<'a> {
            initial_file_name: &'a str, 
            mime_type: Option<&'a str>, 
            initial_location: Option<&'a FileUri>,
            local_only: bool,
        });
        impl_de!(struct Res { uri: Option<FileUri> });
    
        let initial_file_name = initial_file_name.as_ref();
        
        let result = self.invoke::<Res>("showSaveFileDialog", Req { local_only, initial_file_name, mime_type, initial_location })
            .await
            .map(|v| v.uri);

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn is_visual_media_picker_available(&self) -> Result<bool> {
        impl_de!(struct Res { value: bool });

        self.invoke::<Res>("isVisualMediaDialogAvailable", "")
            .await
            .map(|v| v.value)
    }

    #[maybe_async]
    pub fn show_share_file_app_chooser<'b>(
        &self, 
        uris: impl IntoIterator<Item = &'b FileUri>, 
    ) -> Result<()> {

        impl_se!(struct Req<'a> { uris: Vec<&'a FileUri> });
        impl_de!(struct Res;);

        let uris = uris.into_iter().collect::<Vec<_>>();

        let result = self.invoke::<Res>("shareFiles", Req { uris })
            .await
            .map(|_| ());

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_open_file_app_chooser(
        &self, 
        uri: &FileUri,
    ) -> Result<()> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res;);
    
        let result = self.invoke::<Res>("viewFile", Req { uri })
            .await
            .map(|_| ());

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_open_dir_app_chooser(
        &self, 
        uri: &FileUri,
    ) -> Result<()> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res;);

        let result = self.invoke::<Res>("viewDir", Req { uri })
            .await
            .map(|_| ());

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn show_edit_file_app_chooser(
        &self, 
        uri: &FileUri,
    ) -> Result<()> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res;);

        let result = self.invoke::<Res>("editFile", Req { uri })
            .await
            .map(|_| ());

        // show_pick_file_dialog 内のコメントを参照
        sleep(std::time::Duration::from_millis(200)).await;

        result
    }

    #[maybe_async]
    pub fn request_legacy_storage_permission(&self) -> Result<bool> {
        impl_de!(struct Res { granted: bool, prompted: bool });

        let result = self.invoke::<Res>("requestLegacyStoragePermission", ()).await?;

        if result.prompted {
            // show_pick_file_dialog 内のコメントを参照
            sleep(std::time::Duration::from_millis(200)).await;
        }
            
        Ok(result.granted)
    }

    #[maybe_async]
    pub fn check_legacy_storage_permission(&self) -> Result<bool> {
        impl_de!(struct Res { granted: bool });

        self.invoke::<Res>("checkLegacyStoragePermission", ())
            .await
            .map(|res| res.granted)
    }

    #[always_sync]
    pub fn is_legacy_storage(&self) -> Result<bool> {
        let is_legacy_storage = get_or_init_is_legacy_storage(move || {
            impl_de!(struct Res { value: bool });

            self.invoke_sync::<Res>("isLegacyStorage", ()).map(|res| res.value)
        })?;

        Ok(*is_legacy_storage)
    }

    #[maybe_async]
    pub fn find_saf_file_uri(
        &self,
        parent_uri: &FileUri,
        relative_path: impl AsRef<std::path::Path>,
    ) -> Result<FileUri> {
        
        impl_se!(struct Req<'a> { parent_uri: &'a FileUri, relative_path: &'a std::path::Path });
            
        let relative_path = validate_relative_path(relative_path.as_ref())?;

        self.invoke::<FileUri>("findSafFileUri", Req { parent_uri, relative_path }).await
    }

    #[maybe_async]
    pub fn find_saf_dir_uri(
        &self,
        parent_uri: &FileUri,
        relative_path: impl AsRef<std::path::Path>,
    ) -> Result<FileUri> {
        
        impl_se!(struct Req<'a> { parent_uri: &'a FileUri, relative_path: &'a std::path::Path });
            
        let relative_path = validate_relative_path(relative_path.as_ref())?;

        self.invoke::<FileUri>("findSafDirUri", Req { parent_uri, relative_path }).await
    }

    #[maybe_async]
    pub fn scan_media_store_file(
        &self,
        uri: &FileUri,
    ) -> Result<()> {
        
        impl_se!(struct Req<'a> { uri: &'a FileUri });
            
        self.invoke::<()>("scanMediaStoreFile", Req { uri }).await
    }

    #[maybe_async]
    pub fn scan_media_store_file_for_result(
        &self,
        uri: &FileUri,
    ) -> Result<()> {
        
        impl_se!(struct Req<'a> { uri: &'a FileUri });
            
        self.invoke::<()>("scanMediaStoreFileForResult", Req { uri }).await
    }

    #[maybe_async]
    pub fn scan_file_to_media_store_by_path(
        &self, 
        path: impl AsRef<std::path::Path>,
        mime_type: Option<&str>,
    ) -> Result<FileUri> {
       
        impl_se!(struct Req<'a> { path: &'a std::path::Path, mime_type: Option<&'a str>, });
        impl_de!(struct Res { uri: FileUri });

        let path = path.as_ref();
            
        self.invoke::<Res>("scanFileToMediaStoreByPath", Req { path, mime_type })
            .await
            .map(|res| res.uri)
    }

    #[maybe_async]
    pub fn get_media_store_file_path(
        &self,
        uri: &FileUri
    ) -> Result<std::path::PathBuf> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { path: std::path::PathBuf });
      
        self.invoke::<Res>("getMediaStoreFileAbsolutePath", Req { uri })
            .await
            .map(|v| v.path)
    }

    #[maybe_async]
    pub fn check_picker_uri_permission(
        &self,
        uri: &FileUri,
        permission: UriPermission
    ) -> Result<bool> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { can_write: bool, can_read: bool });

        let p = self.invoke::<Res>("getPickerUriPermission", Req { uri }).await?;

        Ok(match permission {
            UriPermission::Read => p.can_read,
            UriPermission::Write => p.can_write,
            UriPermission::ReadAndWrite => p.can_read && p.can_write,
            UriPermission::ReadOrWrite => p.can_read || p.can_write,
        })
    }

    #[maybe_async]
    pub fn check_persisted_picker_uri_permission(
        &self,
        uri: &FileUri,
        permission: UriPermission
    ) -> Result<bool> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { can_write: bool, can_read: bool });

        let p = self.invoke::<Res>("getPersistedPickerUriPermission", Req { uri }).await?;

        Ok(match permission {
            UriPermission::Read => p.can_read,
            UriPermission::Write => p.can_write,
            UriPermission::ReadAndWrite => p.can_read && p.can_write,
            UriPermission::ReadOrWrite => p.can_read || p.can_write,
        })
    }

    #[maybe_async]
    pub fn persist_picker_uri_permission(
        &self,
        uri: &FileUri,
    ) -> Result<()> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });

        self.invoke::<()>("persistPickerUriPermission", Req { uri }).await
    }

    #[maybe_async]
    pub fn release_persisted_picker_uri_permission(
        &self,
        uri: &FileUri,
    ) -> Result<bool> {

        impl_se!(struct Req<'a> { uri: &'a FileUri });
        impl_de!(struct Res { is_released: bool });

        self.invoke::<Res>("releasePersistedPickerUriPermission", Req { uri })
            .await
            .map(|res| res.is_released)
    }

    #[maybe_async]
    pub fn release_all_persisted_picker_uri_permissions(
        &self,
    ) -> Result<()> {

        self.invoke::<()>("releaseAllPersistedPickerUriPermissions", ()).await
    }

    #[maybe_async]
    pub fn get_all_persisted_picker_uri_permissions(
        &self,
    ) -> Result<impl Iterator<Item = PersistedUriPermissionState>> {

        impl_de!(struct Obj { uri: FileUri, r: bool, w: bool, d: bool });
        impl_de!(struct Res { items: Vec<Obj> });
    
        self.invoke::<Res>("getAllPersistedPickerUriPermissions", ())
            .await
            .map(|v| v.items.into_iter())
            .map(|v| v.map(|v| {
                let (uri, can_read, can_write) = (v.uri, v.r, v.w);
                match v.d {
                    true => PersistedUriPermissionState::Dir { uri, can_read, can_write },
                    false => PersistedUriPermissionState::File { uri, can_read, can_write }
                }
            }))
    }

    #[maybe_async]
    pub fn get_mime_type_from_extension(
        &self,
        ext: impl AsRef<str>
    ) -> Result<Option<String>> {

        let ext = ext.as_ref()
            .trim_start_matches('.')
            .to_lowercase();

        if let Some(mime_type) = MAP_OF_EXT_AND_MIME_TYPE
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&ext) {

            return Ok(mime_type.to_owned())
        }

        let mime_type = {
            impl_se!(struct Req<'a> { extension: &'a str });
            impl_de!(struct Res { mime_type: Option<String> });

            self.invoke::<Res>("getMimeTypeFromExtension", Req { extension: &ext })
                .await
                .map(|res| res.mime_type)?
        };

        MAP_OF_EXT_AND_MIME_TYPE
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(ext.to_string(), mime_type.to_owned());

        Ok(mime_type)
    }

    #[maybe_async]
    pub fn start_progress_notification(
        &self,
        icon_type: ProgressNotificationIcon,
        title: Option<&str>,
        text: Option<&str>,
        sub_text: Option<&str>,
        progress: Option<i32>,
        progress_max: Option<i32>,
    ) -> Result<i32> {

        impl_se!(struct Req<'a> { icon_type: ProgressNotificationIcon, title: Option<&'a str>, text: Option<&'a str>, sub_text: Option<&'a str>, progress: Option<i32>, progress_max: Option<i32> });
        impl_de!(struct Res { id: i32 });

        self.invoke::<Res>("startProgressNotification", Req { icon_type, title, text, sub_text, progress, progress_max })
            .await
            .map(|v| v.id)
    }

    #[maybe_async]
    pub fn update_progress_notification(
        &self,
        id: i32,
        icon_type: ProgressNotificationIcon,
        title: Option<&str>,
        text: Option<&str>,
        sub_text: Option<&str>,
        progress: Option<i32>,
        progress_max: Option<i32>,
    ) -> Result<()> {

        impl_se!(struct Req<'a> { id: i32, icon_type: ProgressNotificationIcon, title: Option<&'a str>, text: Option<&'a str>, sub_text: Option<&'a str>, progress: Option<i32>, progress_max: Option<i32> });
            
        self.invoke::<()>("updateProgressNotification", Req { id, icon_type, title, text, sub_text, progress, progress_max })
            .await
    }

    #[maybe_async]
    pub fn finish_progress_notification(
        &self,
        id: i32,
        icon_type: ProgressNotificationIcon,
        title: Option<&str>,
        text: Option<&str>,
        sub_text: Option<&str>,
        share_src: Option<&FileUri>,
        error: bool,
    ) -> Result<()> {

        impl_se!(struct Req<'a> { id: i32, icon_type: ProgressNotificationIcon, title: Option<&'a str>, text: Option<&'a str>, sub_text: Option<&'a str>, error: bool, share_src: Option<&'a FileUri> });
            
        self.invoke::<()>("finishProgressNotification", Req { id, icon_type, title, text, sub_text, error, share_src })
            .await
    }

    #[maybe_async]
    pub fn cancel_notification(&self, id: i32) -> Result<()> {
        impl_se!(struct Req { id: i32 });
            
        self.invoke::<()>("cancelNotification", Req { id })
            .await
    }

    #[maybe_async]
    pub fn cancel_all_notifications(&self) -> Result<()> {
        self.invoke::<()>("cancelAllNotifications", ())
            .await
    }

    #[maybe_async]
    pub fn request_notification_permission(&self) -> Result<bool> {
        impl_de!(struct Res { granted: bool, prompted: bool });

        let result = self.invoke::<Res>("requestNotificationPermission", ()).await?;

        if result.prompted {
            // show_pick_file_dialog 内のコメントを参照
            sleep(std::time::Duration::from_millis(200)).await;
        }
            
        Ok(result.granted)
    }

    #[maybe_async]
    pub fn check_notification_permission(&self) -> Result<bool> {
        impl_de!(struct Res { granted: bool });

        self.invoke::<Res>("hasNotificationPermission", ())
            .await
            .map(|res| res.granted)
    }
}

fn_get_or_init!(get_or_init_is_legacy_storage, bool);
fn_get_or_init!(get_or_init_const, Consts);
fn_get_or_init!(get_or_init_private_dir_paths, PrivateDirPaths);

static MAP_OF_EXT_AND_MIME_TYPE: std::sync::LazyLock<std::sync::Mutex<BoundedHashMap<String, Option<String>>>> = std::sync::LazyLock::new(
    || std::sync::Mutex::new(BoundedHashMap::with_bound(1000))
);

#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct PrivateDirPaths {
    data: std::path::PathBuf, 
    cache: std::path::PathBuf, 
    no_backup_data: std::path::PathBuf, 
}

/// アプリ起動中に変更されることのない値
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Consts {
    pub build_version_sdk_int: i32,

    /// Android 10 (API level 29) 以上で有効
    pub media_store_primary_volume_name: Option<String>,

    pub env_dir_pictures: String,
    pub env_dir_dcim: String,
    pub env_dir_movies: String,
    pub env_dir_music: String,
    pub env_dir_alarms: String,
    pub env_dir_notifications: String,
    pub env_dir_podcasts: String,
    pub env_dir_ringtones: String,
    pub env_dir_documents: String,
    pub env_dir_download: String,

    /// Android 10 (API level 29) 以上で有効
    pub env_dir_audiobooks: Option<String>,

    /// Android 12 (API level 31) 以上で有効
    pub env_dir_recordings: Option<String>,
}

impl Consts {

    pub fn public_dir_name(&self, dir: impl Into<PublicDir>) -> Result<&str> {
        Ok(match dir.into() {
            PublicDir::Image(dir) => match dir {
                PublicImageDir::Pictures => &self.env_dir_pictures,
                PublicImageDir::DCIM => &self.env_dir_dcim,
            },
            PublicDir::Video(dir) => match dir {
                PublicVideoDir::Movies => &self.env_dir_movies,
                PublicVideoDir::DCIM => &self.env_dir_dcim,
            },
            PublicDir::Audio(dir) => match dir  {
                PublicAudioDir::Music => &self.env_dir_music,
                PublicAudioDir::Alarms => &self.env_dir_alarms,
                PublicAudioDir::Notifications => &self.env_dir_notifications,
                PublicAudioDir::Podcasts => &self.env_dir_podcasts,
                PublicAudioDir::Ringtones => &self.env_dir_ringtones,
                PublicAudioDir::Recordings => self.env_dir_recordings.as_ref().ok_or_else(|| Error::with("requires Android 12 (API level 31) or higher"))?,
                PublicAudioDir::Audiobooks => self.env_dir_audiobooks.as_ref().ok_or_else(|| Error::with("requires Android 10 (API level 29) or higher"))?,
            },
            PublicDir::GeneralPurpose(dir) => match dir {
                PublicGeneralPurposeDir::Documents => &self.env_dir_documents,
                PublicGeneralPurposeDir::Download => &self.env_dir_download,
            }
        })
    }
}