-
-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathfile_management.rs
More file actions
4093 lines (3595 loc) · 137 KB
/
file_management.rs
File metadata and controls
4093 lines (3595 loc) · 137 KB
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
use memmap2::{Mmap, MmapOptions};
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::thread;
use anyhow::Result;
use base64::{Engine as _, engine::general_purpose};
use chrono::{DateTime, Utc};
use image::codecs::jpeg::JpegEncoder;
use image::{DynamicImage, GenericImageView, ImageBuffer, Luma};
#[cfg(target_os = "android")]
use jni::objects::{JObject, JString, JValue};
#[cfg(target_os = "android")]
use jni::{JNIEnv, JavaVM};
#[cfg(target_os = "android")]
use ndk_context::android_context;
use rayon::ThreadPoolBuilder;
use rayon::prelude::*;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tauri::{AppHandle, Emitter, Manager};
use uuid::Uuid;
use walkdir::WalkDir;
use crate::AppState;
use crate::calculate_geometry_hash;
use crate::exif_processing;
use crate::formats::{is_raw_file, is_supported_image_file};
use crate::gpu_processing;
use crate::image_loader;
use crate::image_processing::GpuContext;
use crate::image_processing::{
Crop, ImageMetadata, apply_coarse_rotation, apply_cpu_default_raw_processing, apply_crop,
apply_flip, apply_geometry_warp, apply_rotation, auto_results_to_json,
get_all_adjustments_from_json, perform_auto_analysis,
};
use crate::mask_generation::MaskDefinition;
use crate::preset_converter;
use crate::tagging::COLOR_TAG_PREFIX;
fn resolve_thumbnail_cache_dir(app_handle: &AppHandle) -> std::result::Result<PathBuf, String> {
let cache_dir = app_handle
.path()
.app_cache_dir()
.map_err(|e| e.to_string())?;
let thumb_cache_dir = cache_dir.join("thumbnails");
if !thumb_cache_dir.exists() {
fs::create_dir_all(&thumb_cache_dir).map_err(|e| e.to_string())?;
}
Ok(thumb_cache_dir)
}
fn emit_thumbnail_cache_setup_error(app_handle: &AppHandle, path: &str, reason: &str) {
let _ = app_handle.emit(
"thumbnail-generation-error",
serde_json::json!({ "path": path, "reason": reason }),
);
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Preset {
pub id: String,
pub name: String,
pub adjustments: Value,
#[serde(rename = "includeMasks", skip_serializing_if = "Option::is_none")]
pub include_masks: Option<bool>,
#[serde(
rename = "includeCropTransform",
skip_serializing_if = "Option::is_none"
)]
pub include_crop_transform: Option<bool>,
}
#[derive(Serialize)]
struct ExportPresetFile<'a> {
creator: &'a str,
presets: &'a [PresetItem],
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PresetFolder {
pub id: String,
pub name: String,
pub children: Vec<Preset>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub enum PresetItem {
Preset(Preset),
Folder(PresetFolder),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PresetFile {
pub presets: Vec<PresetItem>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SortCriteria {
pub key: String,
pub order: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FilterCriteria {
pub rating: u8,
pub raw_status: String,
#[serde(default)]
pub colors: Vec<String>,
}
impl Default for FilterCriteria {
fn default() -> Self {
Self {
rating: 0,
raw_status: "all".to_string(),
colors: Vec::new(),
}
}
}
#[derive(Debug)]
pub enum ReadFileError {
Io(std::io::Error),
Locked,
Empty,
NotFound,
Invalid,
}
impl fmt::Display for ReadFileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ReadFileError::Io(err) => write!(f, "IO error: {}", err),
ReadFileError::Locked => write!(f, "File is locked"),
ReadFileError::Empty => write!(f, "File is empty"),
ReadFileError::NotFound => write!(f, "File not found"),
ReadFileError::Invalid => write!(f, "Invalid file"),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct LastFolderState {
pub current_folder_path: String,
pub expanded_folders: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct MyLens {
pub maker: String,
pub model: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum PasteMode {
Merge,
Replace,
}
fn all_available_adjustments() -> HashSet<String> {
[
"exposure",
"brightness",
"contrast",
"curves",
"highlights",
"shadows",
"whites",
"blacks",
"toneMapper",
"temperature",
"tint",
"saturation",
"vibrance",
"hsl",
"colorGrading",
"colorCalibration",
"clarity",
"structure",
"dehaze",
"sharpness",
"centré",
"lumaNoiseReduction",
"colorNoiseReduction",
"chromaticAberrationRedCyan",
"chromaticAberrationBlueYellow",
"vignetteAmount",
"vignetteFeather",
"vignetteMidpoint",
"vignetteRoundness",
"grainAmount",
"grainRoughness",
"grainSize",
"lutIntensity",
"lutName",
"lutPath",
"lutSize",
"lutData",
"glowAmount",
"halationAmount",
"flareAmount",
"crop",
"aspectRatio",
"rotation",
"flipHorizontal",
"flipVertical",
"orientationSteps",
"transformDistortion",
"transformVertical",
"transformHorizontal",
"transformRotate",
"transformAspect",
"transformScale",
"transformXOffset",
"transformYOffset",
"masks",
]
.iter()
.map(|s| s.to_string())
.collect()
}
fn default_included_adjustments() -> HashSet<String> {
let mut defaults = all_available_adjustments();
let off_by_default = [
"crop",
"aspectRatio",
"rotation",
"flipHorizontal",
"flipVertical",
"orientationSteps",
"transformDistortion",
"transformVertical",
"transformHorizontal",
"transformRotate",
"transformAspect",
"transformScale",
"transformXOffset",
"transformYOffset",
"masks",
];
for item in off_by_default.iter() {
defaults.remove(*item);
}
defaults
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CopyPasteSettings {
pub mode: PasteMode,
#[serde(default = "default_included_adjustments")]
pub included_adjustments: HashSet<String>,
#[serde(default)]
pub known_adjustments: HashSet<String>,
}
impl Default for CopyPasteSettings {
fn default() -> Self {
Self {
mode: PasteMode::Merge,
included_adjustments: default_included_adjustments(),
known_adjustments: all_available_adjustments(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ExportPreset {
pub id: String,
pub name: String,
pub file_format: String,
pub jpeg_quality: u8,
pub enable_resize: bool,
pub resize_mode: String,
pub resize_value: u32,
pub dont_enlarge: bool,
pub keep_metadata: bool,
pub strip_gps: bool,
pub filename_template: String,
pub enable_watermark: bool,
pub watermark_path: Option<String>,
pub watermark_anchor: Option<String>,
pub watermark_scale: u32,
pub watermark_spacing: u32,
pub watermark_opacity: u32,
#[serde(default)]
pub export_masks: Option<bool>,
#[serde(default)]
pub preserve_folders: Option<bool>,
/// Last export destination path, stored on the __last_used__ preset only.
#[serde(default)]
pub last_export_path: Option<String>,
}
fn default_export_presets() -> Vec<ExportPreset> {
vec![
ExportPreset {
id: "default-hq".to_string(),
name: "High Quality".to_string(),
file_format: "jpeg".to_string(),
jpeg_quality: 95,
enable_resize: false,
resize_mode: "longEdge".to_string(),
resize_value: 2048,
dont_enlarge: true,
keep_metadata: true,
strip_gps: false,
filename_template: "{original_filename}".to_string(),
enable_watermark: false,
watermark_path: None,
watermark_anchor: Some("bottomRight".to_string()),
watermark_scale: 10,
watermark_spacing: 5,
watermark_opacity: 75,
export_masks: Some(false),
preserve_folders: Some(false),
last_export_path: None,
},
ExportPreset {
id: "default-fast".to_string(),
name: "Fast (Web)".to_string(),
file_format: "jpeg".to_string(),
jpeg_quality: 80,
enable_resize: true,
resize_mode: "width".to_string(),
resize_value: 2048,
dont_enlarge: true,
keep_metadata: false,
strip_gps: true,
filename_template: "{original_filename}_web".to_string(),
enable_watermark: false,
watermark_path: None,
watermark_anchor: Some("bottomRight".to_string()),
watermark_scale: 10,
watermark_spacing: 5,
watermark_opacity: 75,
export_masks: Some(false),
preserve_folders: Some(false),
last_export_path: None,
},
]
}
fn default_linear_raw_mode() -> String {
"auto".to_string()
}
fn default_tagging_shortcuts_option() -> Option<Vec<String>> {
Some(vec![
"portrait".to_string(),
"landscape".to_string(),
"architecture".to_string(),
"travel".to_string(),
"street".to_string(),
"family".to_string(),
"nature".to_string(),
"food".to_string(),
"event".to_string(),
])
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AppSettings {
pub last_root_path: Option<String>,
#[serde(default)]
pub pinned_folders: Vec<String>,
pub editor_preview_resolution: Option<u32>,
#[serde(default)]
pub thumbnail_resolution: Option<u32>,
#[serde(default)]
pub enable_zoom_hifi: Option<bool>,
#[serde(default)]
pub use_full_dpi_rendering: Option<bool>,
#[serde(default)]
pub high_res_zoom_multiplier: Option<f32>,
#[serde(default)]
pub enable_live_previews: Option<bool>,
#[serde(default)]
pub live_preview_quality: Option<String>,
pub sort_criteria: Option<SortCriteria>,
pub filter_criteria: Option<FilterCriteria>,
pub theme: Option<String>,
#[serde(default)]
pub font_family: Option<String>,
pub transparent: Option<bool>,
pub decorations: Option<bool>,
#[serde(alias = "comfyuiAddress")]
pub ai_connector_address: Option<String>,
pub last_folder_state: Option<LastFolderState>,
pub adaptive_editor_theme: Option<bool>,
pub ui_visibility: Option<Value>,
pub enable_ai_tagging: Option<bool>,
pub tagging_thread_count: Option<u32>,
#[serde(default = "default_tagging_shortcuts_option")]
pub tagging_shortcuts: Option<Vec<String>>,
#[serde(default)]
pub custom_ai_tags: Option<Vec<String>>,
#[serde(default)]
pub ai_tag_count: Option<u32>,
pub thumbnail_size: Option<String>,
pub thumbnail_aspect_ratio: Option<String>,
pub ai_provider: Option<String>,
#[serde(default = "default_adjustment_visibility")]
pub adjustment_visibility: HashMap<String, bool>,
pub enable_exif_reading: Option<bool>,
#[serde(default)]
pub active_tree_section: Option<String>,
#[serde(default)]
pub copy_paste_settings: CopyPasteSettings,
#[serde(default)]
pub raw_highlight_compression: Option<f32>,
#[serde(default)]
pub processing_backend: Option<String>,
#[serde(default)]
pub linux_gpu_optimization: Option<bool>,
#[serde(default)]
pub library_view_mode: Option<String>,
#[serde(default = "default_export_presets")]
pub export_presets: Vec<ExportPreset>,
#[serde(default)]
pub my_lenses: Option<Vec<MyLens>>,
#[serde(default)]
pub enable_folder_image_counts: Option<bool>,
#[serde(default = "default_linear_raw_mode")]
pub linear_raw_mode: String,
#[serde(default)]
pub enable_xmp_sync: Option<bool>,
#[serde(default)]
pub create_xmp_if_missing: Option<bool>,
#[serde(default)]
pub is_waveform_visible: Option<bool>,
#[serde(default)]
pub waveform_height: Option<u32>,
#[serde(default)]
pub active_waveform_channel: Option<String>,
#[serde(default)]
pub group_preferred_type: Option<String>,
}
fn default_adjustment_visibility() -> HashMap<String, bool> {
let mut map = HashMap::new();
map.insert("sharpening".to_string(), true);
map.insert("presence".to_string(), true);
map.insert("noiseReduction".to_string(), true);
map.insert("chromaticAberration".to_string(), false);
map.insert("vignette".to_string(), true);
map.insert("colorCalibration".to_string(), false);
map.insert("grain".to_string(), true);
map
}
impl Default for AppSettings {
fn default() -> Self {
Self {
last_root_path: None,
pinned_folders: Vec::new(),
thumbnail_resolution: Some(720),
editor_preview_resolution: Some(1920),
enable_zoom_hifi: Some(true),
use_full_dpi_rendering: Some(false),
enable_live_previews: Some(true),
live_preview_quality: Some("high".to_string()),
sort_criteria: None,
filter_criteria: None,
theme: Some("dark".to_string()),
font_family: None,
#[cfg(any(target_os = "linux", target_os = "android"))]
transparent: Some(false),
#[cfg(not(any(target_os = "linux", target_os = "android")))]
transparent: Some(true),
#[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
decorations: Some(true),
#[cfg(any(target_os = "windows", target_os = "macos"))]
decorations: Some(false),
ai_connector_address: None,
last_folder_state: None,
adaptive_editor_theme: Some(false),
ui_visibility: None,
enable_ai_tagging: Some(false),
tagging_thread_count: Some(3),
tagging_shortcuts: default_tagging_shortcuts_option(),
custom_ai_tags: Some(Vec::new()),
ai_tag_count: Some(10),
thumbnail_size: Some("medium".to_string()),
thumbnail_aspect_ratio: Some("cover".to_string()),
ai_provider: Some("cpu".to_string()),
adjustment_visibility: default_adjustment_visibility(),
enable_exif_reading: Some(false),
active_tree_section: Some("current".to_string()),
copy_paste_settings: CopyPasteSettings::default(),
raw_highlight_compression: Some(2.5),
processing_backend: Some("auto".to_string()),
#[cfg(target_os = "linux")]
linux_gpu_optimization: Some(true),
#[cfg(not(target_os = "linux"))]
linux_gpu_optimization: Some(false),
library_view_mode: Some("flat".to_string()),
export_presets: default_export_presets(),
my_lenses: Some(Vec::new()),
high_res_zoom_multiplier: Some(1.0),
enable_folder_image_counts: Some(false),
linear_raw_mode: default_linear_raw_mode(),
enable_xmp_sync: Some(true),
create_xmp_if_missing: Some(false),
is_waveform_visible: Some(false),
waveform_height: Some(220),
active_waveform_channel: Some("luma".to_string()),
group_preferred_type: Some("raw".to_string()),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ImageFile {
path: String,
modified: u64,
is_edited: bool,
rating: u8,
tags: Option<Vec<String>>,
exif: Option<HashMap<String, String>>,
is_virtual_copy: bool,
is_raw: bool,
group_id: Option<String>,
}
/// Grouping key from a source image path: the full path with the
/// extension stripped. Files sharing this key are variants of the
/// same shot. Case-sensitive.
fn make_group_key(source_path: &Path) -> String {
source_path.with_extension("").to_string_lossy().into_owned()
}
/// Tag files that share a stem with `group_id`. Virtual copies are
/// excluded from counting (one file + its virtual copy don't form a
/// group) but still get assigned the group_id of their source.
fn assign_group_ids(files: &mut Vec<ImageFile>) {
let mut stem_sources: HashMap<String, HashSet<PathBuf>> = HashMap::new();
for file in files.iter() {
if file.is_virtual_copy {
continue;
}
let (source_path, _) = parse_virtual_path(&file.path);
let key = make_group_key(&source_path);
stem_sources.entry(key).or_default().insert(source_path);
}
for file in files.iter_mut() {
let (source_path, _) = parse_virtual_path(&file.path);
let key = make_group_key(&source_path);
if stem_sources.get(&key).map_or(false, |s| s.len() >= 2) {
file.group_id = Some(key);
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ImportSettings {
pub filename_template: String,
pub organize_by_date: bool,
pub date_folder_format: String,
pub delete_after_import: bool,
}
pub fn parse_virtual_path(virtual_path: &str) -> (PathBuf, PathBuf) {
let (source_path_str, copy_id) = if let Some((base, id)) = virtual_path.rsplit_once("?vc=") {
(base.to_string(), Some(id.to_string()))
} else {
(virtual_path.to_string(), None)
};
let source_path = PathBuf::from(source_path_str);
let sidecar_filename = if let Some(id) = copy_id {
format!(
"{}.{}.rrdata",
source_path
.file_name()
.unwrap_or_default()
.to_string_lossy(),
&id
)
} else {
format!(
"{}.rrdata",
source_path
.file_name()
.unwrap_or_default()
.to_string_lossy()
)
};
let sidecar_path = source_path.with_file_name(sidecar_filename);
(source_path, sidecar_path)
}
#[cfg(target_os = "android")]
fn is_android_content_uri(path: &str) -> bool {
path.starts_with("content://")
}
#[cfg(target_os = "android")]
fn clear_pending_android_exception(env: &mut JNIEnv<'_>) {
if env.exception_check().unwrap_or(false) {
let _ = env.exception_describe();
let _ = env.exception_clear();
}
}
#[cfg(target_os = "android")]
fn map_android_jni_error(env: &mut JNIEnv<'_>, err: jni::errors::Error) -> String {
clear_pending_android_exception(env);
format!("Android JNI error: {}", err)
}
#[cfg(target_os = "android")]
fn close_android_closeable(env: &mut JNIEnv<'_>, closeable: &JObject<'_>) {
if closeable.is_null() {
return;
}
if let Err(err) = env.call_method(closeable, "close", "()V", &[]) {
clear_pending_android_exception(env);
log::warn!("Failed to close Android Closeable: {}", err);
}
}
#[cfg(target_os = "android")]
fn get_android_content_resolver<'local>(
env: &mut JNIEnv<'local>,
) -> Result<JObject<'local>, String> {
let context = env
.new_local_ref(unsafe { JObject::from_raw(android_context().context().cast()) })
.map_err(|e| map_android_jni_error(env, e))?;
let resolver = env
.call_method(
&context,
"getContentResolver",
"()Landroid/content/ContentResolver;",
&[],
)
.and_then(|value| value.l())
.map_err(|e| map_android_jni_error(env, e))?;
if resolver.is_null() {
return Err("Android ContentResolver was null.".into());
}
Ok(resolver)
}
#[cfg(target_os = "android")]
fn parse_android_uri<'local>(
env: &mut JNIEnv<'local>,
uri_str: &str,
) -> Result<JObject<'local>, String> {
let uri_string = env
.new_string(uri_str)
.map_err(|e| map_android_jni_error(env, e))?;
let uri = env
.call_static_method(
"android/net/Uri",
"parse",
"(Ljava/lang/String;)Landroid/net/Uri;",
&[(&uri_string).into()],
)
.and_then(|value| value.l())
.map_err(|e| map_android_jni_error(env, e))?;
if uri.is_null() {
return Err(format!("Failed to parse Android content URI: {}", uri_str));
}
Ok(uri)
}
#[cfg(target_os = "android")]
fn resolve_android_content_uri_name(uri_str: &str) -> Result<String, String> {
let vm = unsafe { JavaVM::from_raw(android_context().vm().cast()) }
.map_err(|e| format!("Failed to access Android JVM: {}", e))?;
let mut env = vm
.attach_current_thread()
.map_err(|e| format!("Failed to attach current thread to Android JVM: {}", e))?;
let resolver = get_android_content_resolver(&mut env)?;
let uri = parse_android_uri(&mut env, uri_str)?;
let null_obj = JObject::null();
let cursor = env
.call_method(
&resolver,
"query",
"(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;",
&[
(&uri).into(),
(&null_obj).into(),
(&null_obj).into(),
(&null_obj).into(),
(&null_obj).into(),
],
)
.and_then(|value| value.l())
.map_err(|e| map_android_jni_error(&mut env, e))?;
if cursor.is_null() {
return Err(format!(
"ContentResolver query returned no cursor for URI: {}",
uri_str
));
}
let result = (|| -> Result<String, String> {
let moved = env
.call_method(&cursor, "moveToFirst", "()Z", &[])
.and_then(|value| value.z())
.map_err(|e| map_android_jni_error(&mut env, e))?;
if !moved {
return Err(format!(
"No metadata rows found for content URI: {}",
uri_str
));
}
let display_name_column = env
.get_static_field(
"android/provider/OpenableColumns",
"DISPLAY_NAME",
"Ljava/lang/String;",
)
.and_then(|value| value.l())
.map_err(|e| map_android_jni_error(&mut env, e))?;
let column_index = env
.call_method(
&cursor,
"getColumnIndex",
"(Ljava/lang/String;)I",
&[(&display_name_column).into()],
)
.and_then(|value| value.i())
.map_err(|e| map_android_jni_error(&mut env, e))?;
if column_index < 0 {
return Err(format!(
"DISPLAY_NAME column was unavailable for content URI: {}",
uri_str
));
}
let display_name_obj = env
.call_method(
&cursor,
"getString",
"(I)Ljava/lang/String;",
&[JValue::from(column_index)],
)
.and_then(|value| value.l())
.map_err(|e| map_android_jni_error(&mut env, e))?;
if display_name_obj.is_null() {
return Err(format!(
"Display name was null for content URI: {}",
uri_str
));
}
let display_name_java = JString::from(display_name_obj);
let display_name = env
.get_string(&display_name_java)
.map_err(|e| map_android_jni_error(&mut env, e))?;
Ok(display_name.into())
})();
close_android_closeable(&mut env, &cursor);
result
}
#[cfg(target_os = "android")]
fn read_android_content_uri(uri_str: &str) -> Result<Vec<u8>, String> {
let vm = unsafe { JavaVM::from_raw(android_context().vm().cast()) }
.map_err(|e| format!("Failed to access Android JVM: {}", e))?;
let mut env = vm
.attach_current_thread()
.map_err(|e| format!("Failed to attach current thread to Android JVM: {}", e))?;
let resolver = get_android_content_resolver(&mut env)?;
let uri = parse_android_uri(&mut env, uri_str)?;
let input_stream = env
.call_method(
&resolver,
"openInputStream",
"(Landroid/net/Uri;)Ljava/io/InputStream;",
&[(&uri).into()],
)
.and_then(|value| value.l())
.map_err(|e| map_android_jni_error(&mut env, e))?;
if input_stream.is_null() {
return Err(format!(
"Failed to open InputStream for Android content URI: {}",
uri_str
));
}
let result = (|| -> Result<Vec<u8>, String> {
const BUFFER_SIZE: i32 = 8192;
let java_buffer = env
.new_byte_array(BUFFER_SIZE)
.map_err(|e| map_android_jni_error(&mut env, e))?;
let mut rust_buffer = vec![0i8; BUFFER_SIZE as usize];
let mut bytes = Vec::new();
loop {
let read_count = env
.call_method(&input_stream, "read", "([B)I", &[(&java_buffer).into()])
.and_then(|value| value.i())
.map_err(|e| map_android_jni_error(&mut env, e))?;
if read_count < 0 {
break;
}
if read_count == 0 {
continue;
}
let read_len = read_count as usize;
env.get_byte_array_region(&java_buffer, 0, &mut rust_buffer[..read_len])
.map_err(|e| map_android_jni_error(&mut env, e))?;
bytes.extend(rust_buffer[..read_len].iter().map(|byte| *byte as u8));
}
Ok(bytes)
})();
close_android_closeable(&mut env, &input_stream);
result
}
#[tauri::command]
pub async fn read_exif_for_paths(
paths: Vec<String>,
) -> Result<HashMap<String, HashMap<String, String>>, String> {
let exif_data: HashMap<String, HashMap<String, String>> = paths
.par_iter()
.filter_map(|virtual_path| {
let (source_path, _) = parse_virtual_path(virtual_path);
let source_path_str = source_path.to_string_lossy().to_string();
let map = if let Some(sidecar_exif) =
crate::exif_processing::read_rrexif_sidecar(&source_path)
{
sidecar_exif
} else if let Ok(mmap) = read_file_mapped(&source_path) {
crate::exif_processing::read_exif_data(&source_path_str, &mmap)
} else if let Ok(bytes) = fs::read(&source_path) {
crate::exif_processing::read_exif_data(&source_path_str, &bytes)
} else {
HashMap::new()
};
if map.is_empty() {
None
} else {
Some((virtual_path.clone(), map))
}
})
.collect();
Ok(exif_data)
}
#[tauri::command]
pub fn list_images_in_dir(path: String, app_handle: AppHandle) -> Result<Vec<ImageFile>, String> {
let settings = load_settings(app_handle).unwrap_or_default();
let enable_xmp_sync = settings.enable_xmp_sync.unwrap_or(false);
let entries = fs::read_dir(&path).map_err(|e| e.to_string())?;
let mut images = Vec::new();
let mut sidecars_by_filename: HashMap<String, Vec<Option<String>>> = HashMap::new();
for entry in entries.filter_map(Result::ok) {
let entry_path = entry.path();
let file_name = entry
.file_name()
.into_string()
.unwrap_or_else(|os| os.to_string_lossy().into_owned());
if file_name.ends_with(".rrdata") {
let base = &file_name[..file_name.len() - 7];
let (source_filename, copy_id) =
if base.len() >= 7 && base.as_bytes()[base.len() - 7] == b'.' {
let id = &base[base.len() - 6..];
if id.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')) {
(&base[..base.len() - 7], Some(id.to_string()))
} else {
(base, None)
}
} else {
(base, None)
};
sidecars_by_filename
.entry(source_filename.to_string())
.or_default()
.push(copy_id);
} else if is_supported_image_file(&file_name) {
images.push((file_name, entry_path));
}
}
let tasks: Vec<_> = images
.into_iter()
.map(|(file_name, path_buf)| {
let sidecars = sidecars_by_filename
.remove(&file_name)
.unwrap_or_else(|| vec![None]);
let path_str = path_buf.to_string_lossy().into_owned();
(path_str, file_name, path_buf, sidecars)
})
.collect();
let result_list: Vec<ImageFile> = tasks
.into_par_iter()
.flat_map(|(path_str, file_name, path_buf, sidecars)| {
let modified = fs::metadata(&path_buf)
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0);
let mut file_results = Vec::with_capacity(sidecars.len());
for copy_id_opt in sidecars {
let (virtual_path, is_virtual_copy, sidecar_filename) = match copy_id_opt {
Some(id) => (
format!("{}?vc={}", path_str, id),
true,
format!("{}.{}.rrdata", file_name, id),
),
None => (path_str.clone(), false, format!("{}.rrdata", file_name)),
};
let sidecar_path = path_buf.with_file_name(sidecar_filename);
let (is_edited, tags, rating) = {
let mut metadata = if sidecar_path.exists() {
if let Ok(content) = fs::read_to_string(&sidecar_path) {
serde_json::from_str::<ImageMetadata>(&content).unwrap_or_default()
} else {
ImageMetadata::default()
}
} else {
ImageMetadata::default()
};
if enable_xmp_sync
&& sync_metadata_from_xmp(&path_buf, &mut metadata)
&& let Ok(json) = serde_json::to_string_pretty(&metadata)
{
let _ = fs::write(&sidecar_path, json);
}
let edited = metadata.adjustments.as_object().is_some_and(|a| {
a.keys().len() > 1 || (a.keys().len() == 1 && !a.contains_key("rating"))
});
(edited, metadata.tags, metadata.rating)
};
file_results.push(ImageFile {
path: virtual_path,