diff --git a/package-lock.json b/package-lock.json index 78ac3ef35a..fa2e2bf6b6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "dependencies": { "@clerk/react": "^6.14.5", "@dnd-kit/core": "^6.3.1", + "@react-leaflet/core": "^3.0.0", "@tauri-apps/api": "^2.12.1", "@tauri-apps/plugin-dialog": "^2.7.2", "@tauri-apps/plugin-http": "^2.8.0", @@ -20,6 +21,8 @@ "framer-motion": "^13.1.1", "i18next": "^26.4.0", "konva": "^10.3.1", + "leaflet": "^1.9.4", + "leaflet.markercluster": "^1.5.3", "lodash.debounce": "^4.0.8", "lodash.throttle": "^4.1.1", "lucide-react": "^1.33.0", @@ -28,6 +31,7 @@ "react-i18next": "^17.0.12", "react-image-crop": "^11.1.2", "react-konva": "^19.2.5", + "react-leaflet": "^5.0.0", "react-toastify": "^11.1.0", "react-window": "^2.3.0", "simple-icons": "^16.28.0", @@ -39,6 +43,8 @@ "@eslint/js": "^10.0.1", "@tailwindcss/vite": "^4.3.3", "@tauri-apps/cli": "^2.12.1", + "@types/leaflet": "^1.9.16", + "@types/leaflet.markercluster": "^1.5.5", "@types/lodash.debounce": "^4.0.9", "@types/lodash.throttle": "^4.1.9", "@types/react": "^19.2.18", @@ -1360,6 +1366,17 @@ "url": "https://github.com/sponsors/Boshen" } }, + "node_modules/@react-leaflet/core": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-3.0.0.tgz", + "integrity": "sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==", + "license": "Hippocratic-2.1", + "peerDependencies": { + "leaflet": "^1.9.0", + "react": "^19.0.0", + "react-dom": "^19.0.0" + } + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.5.tgz", @@ -2550,6 +2567,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -2557,6 +2581,26 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/leaflet": { + "version": "1.9.22", + "resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.22.tgz", + "integrity": "sha512-h3lhECYEKDasG7LFHu+GiHqAvsgLuQvlJvVZzJDGONo3sEL+wUOqSFLnwkZlK0qVxnxbuGFW8iBlJNYs5wgndA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/geojson": "*" + } + }, + "node_modules/@types/leaflet.markercluster": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/leaflet.markercluster/-/leaflet.markercluster-1.5.6.tgz", + "integrity": "sha512-I7hZjO2+isVXGYWzKxBp8PsCzAYCJBc29qBdFpquOCkS7zFDqUsUvkEOyQHedsk/Cy5tocQzf+Ndorm5W9YKTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/leaflet": "^1.9" + } + }, "node_modules/@types/lodash": { "version": "4.17.25", "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz", @@ -4218,6 +4262,21 @@ } } }, + "node_modules/leaflet": { + "version": "1.9.4", + "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", + "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==", + "license": "BSD-2-Clause" + }, + "node_modules/leaflet.markercluster": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz", + "integrity": "sha512-vPTw/Bndq7eQHjLBVlWpnGeLa3t+3zGiuM7fJwCkiMFq+nmRuG3RI3f7f4N4TDX7T4NpbAXpR2+NTRSEGfCSeA==", + "license": "MIT", + "peerDependencies": { + "leaflet": "^1.3.1" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", @@ -5088,6 +5147,20 @@ "react-dom": "^19.2.0" } }, + "node_modules/react-leaflet": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz", + "integrity": "sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==", + "license": "Hippocratic-2.1", + "dependencies": { + "@react-leaflet/core": "^3.0.0" + }, + "peerDependencies": { + "leaflet": "^1.9.0", + "react": "^19.0.0", + "react-dom": "^19.0.0" + } + }, "node_modules/react-reconciler": { "version": "0.33.0", "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz", diff --git a/package.json b/package.json index f9397aed8e..cf8e1c3553 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "dependencies": { "@clerk/react": "^6.14.5", "@dnd-kit/core": "^6.3.1", + "@react-leaflet/core": "^3.0.0", "@tauri-apps/api": "^2.12.1", "@tauri-apps/plugin-dialog": "^2.7.2", "@tauri-apps/plugin-http": "^2.8.0", @@ -33,6 +34,8 @@ "framer-motion": "^13.1.1", "i18next": "^26.4.0", "konva": "^10.3.1", + "leaflet": "^1.9.4", + "leaflet.markercluster": "^1.5.3", "lodash.debounce": "^4.0.8", "lodash.throttle": "^4.1.1", "lucide-react": "^1.33.0", @@ -41,6 +44,7 @@ "react-i18next": "^17.0.12", "react-image-crop": "^11.1.2", "react-konva": "^19.2.5", + "react-leaflet": "^5.0.0", "react-toastify": "^11.1.0", "react-window": "^2.3.0", "simple-icons": "^16.28.0", @@ -52,6 +56,8 @@ "@eslint/js": "^10.0.1", "@tailwindcss/vite": "^4.3.3", "@tauri-apps/cli": "^2.12.1", + "@types/leaflet": "^1.9.16", + "@types/leaflet.markercluster": "^1.5.5", "@types/lodash.debounce": "^4.0.9", "@types/lodash.throttle": "^4.1.9", "@types/react": "^19.2.18", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 04e16aec86..d923fc9f64 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -747,6 +747,8 @@ pub fn run() { library::sidecars::set_color_label_for_paths, library::sidecars::set_rating_for_paths, library::sidecars::set_flag_for_paths, + library::sidecars::set_gps_for_paths, + library::sidecars::revert_gps_for_paths, library::file_ops::import_files, library::sidecars::create_virtual_copy, library::albums::get_albums, diff --git a/src-tauri/src/library/listing.rs b/src-tauri/src/library/listing.rs index 32793b735d..246b797ea2 100644 --- a/src-tauri/src/library/listing.rs +++ b/src-tauri/src/library/listing.rs @@ -17,13 +17,13 @@ use sysinfo::Disks; use tauri::{AppHandle, Emitter, Manager}; use walkdir::WalkDir; -struct ImageFileMetadata { - is_edited: bool, - tags: Option>, - rating: u8, - flag: Option, - is_raw: bool, - needs_ai: bool, +pub(crate) struct ImageFileMetadata { + pub(crate) is_edited: bool, + pub(crate) tags: Option>, + pub(crate) rating: u8, + pub(crate) flag: Option, + pub(crate) is_raw: bool, + pub(crate) needs_ai: bool, } pub fn rating_and_edited(path_str: &str, settings: &AppSettings) -> (u8, bool) { @@ -59,7 +59,13 @@ fn resolve_image_metadata( let is_raw = crate::decode::formats::is_raw_file(image_path); let tm_override = resolve_tonemapper_override(settings, is_raw); - let is_edited = is_image_edited(&metadata.adjustments, image_path, is_raw, tm_override); + let is_adj_edited = is_image_edited(&metadata.adjustments, image_path, is_raw, tm_override); + let is_gps_edited = metadata + .exif + .as_ref() + .and_then(|e| e.get("IsGpsModified")) + .is_some_and(|v| v == "true"); + let is_edited = is_adj_edited || is_gps_edited; let needs_ai = crate::ai::jobs::needs_generation(&metadata.adjustments, image_path); ImageFileMetadata { is_edited, @@ -71,7 +77,11 @@ fn resolve_image_metadata( } } -fn emit_image_metadata_loaded(app_handle: &AppHandle, path: &str, metadata: &ImageFileMetadata) { +pub(crate) fn emit_image_metadata_loaded( + app_handle: &AppHandle, + path: &str, + metadata: &ImageFileMetadata, +) { let _ = app_handle.emit( "image-metadata-loaded", serde_json::json!({ diff --git a/src-tauri/src/library/sidecars.rs b/src-tauri/src/library/sidecars.rs index b7b0d9919a..73facbb41e 100644 --- a/src-tauri/src/library/sidecars.rs +++ b/src-tauri/src/library/sidecars.rs @@ -8,20 +8,23 @@ use crate::decode::baseline_exposure::BaselineOptions; use crate::decode::image_loader; use crate::library::albums::add_to_album; use crate::library::file_ops::{read_file_mapped, write_file_atomic}; +use crate::library::listing::{ImageFileMetadata, emit_image_metadata_loaded}; use crate::library::tagging::COLOR_TAG_PREFIX; use crate::library::thumbnails::{ add_to_thumbnail_queue, emit_thumbnail_cache_setup_error, emit_thumbnail_generated, generate_single_thumbnail_and_cache, increment_thumbnail_progress, regenerate_thumbnails, resolve_thumbnail_cache_dir, }; -use crate::metadata::sidecar::{ImageFlag, ImageMetadata}; -use crate::metadata::xmp::{sync_metadata_from_xmp, sync_metadata_to_xmp}; +use crate::metadata::sidecar::{ImageFlag, ImageMetadata, is_image_edited}; +use crate::metadata::xmp::{parse_gps_components, sync_metadata_from_xmp, sync_metadata_to_xmp}; use crate::render::adjustment_utils::{default_adjustments, effective_baseline_exposure}; use crate::render::gpu::context::get_or_init_gpu_context; +use crate::render::options::resolve_tonemapper_override; use anyhow::Result; use image::DynamicImage; use rayon::prelude::*; use serde_json::Value; +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::{fs, thread}; use tauri::{AppHandle, Manager}; @@ -238,24 +241,117 @@ pub async fn apply_adjustments_to_paths( .map_err(|e| e.to_string()) } +fn revert_gps_in_metadata_and_cache( + source_path: &Path, + metadata: &mut ImageMetadata, +) -> Option<(f64, f64)> { + let mut exif_map = metadata.exif.clone().unwrap_or_default(); + + let orig_from_sidecar = if let (Some(orig_lat_str), Some(orig_lon_str)) = ( + exif_map.get("OriginalGPSLatitude"), + exif_map.get("OriginalGPSLongitude"), + ) { + let lat_ref = exif_map + .get("OriginalGPSLatitudeRef") + .cloned() + .unwrap_or_else(|| "N".to_string()); + let lon_ref = exif_map + .get("OriginalGPSLongitudeRef") + .cloned() + .unwrap_or_else(|| "E".to_string()); + if let (Some((ld, lm, ls)), Some((od, om, os))) = ( + parse_gps_components(orig_lat_str), + parse_gps_components(orig_lon_str), + ) { + let mut lat_val = ld as f64 + lm / 60.0 + ls / 3600.0; + if lat_ref.to_uppercase() == "S" { + lat_val = -lat_val; + } + let mut lon_val = od as f64 + om / 60.0 + os / 3600.0; + if lon_ref.to_uppercase() == "W" { + lon_val = -lon_val; + } + Some(( + lat_val, + lon_val, + orig_lat_str.clone(), + lat_ref, + orig_lon_str.clone(), + lon_ref, + )) + } else { + None + } + } else { + None + }; + + let native_opt = orig_from_sidecar.or_else(|| extract_native_gps(source_path)); + + if let Some((lat_val, lon_val, lat_str, lat_ref, lon_str, lon_ref)) = native_opt { + exif_map.insert("GPSLatitude".to_string(), lat_str.clone()); + exif_map.insert("GPSLatitudeRef".to_string(), lat_ref.clone()); + exif_map.insert("GPSLongitude".to_string(), lon_str.clone()); + exif_map.insert("GPSLongitudeRef".to_string(), lon_ref.clone()); + exif_map.insert("OriginalGPSLatitude".to_string(), lat_str); + exif_map.insert("OriginalGPSLatitudeRef".to_string(), lat_ref); + exif_map.insert("OriginalGPSLongitude".to_string(), lon_str); + exif_map.insert("OriginalGPSLongitudeRef".to_string(), lon_ref); + exif_map.insert("HasNativeGPS".to_string(), "true".to_string()); + exif_map.remove("IsGpsModified"); + + crate::metadata::exif_cache::save_exif_to_rrcache(source_path, exif_map.clone()); + metadata.exif = Some(exif_map); + Some((lat_val, lon_val)) + } else { + exif_map.remove("GPSLatitude"); + exif_map.remove("GPSLatitudeRef"); + exif_map.remove("GPSLongitude"); + exif_map.remove("GPSLongitudeRef"); + exif_map.remove("OriginalGPSLatitude"); + exif_map.remove("OriginalGPSLatitudeRef"); + exif_map.remove("OriginalGPSLongitude"); + exif_map.remove("OriginalGPSLongitudeRef"); + exif_map.remove("IsGpsModified"); + exif_map.insert("HasNativeGPS".to_string(), "false".to_string()); + crate::metadata::exif_cache::save_exif_to_rrcache(source_path, exif_map.clone()); + metadata.exif = Some(exif_map); + None + } +} + #[tauri::command] pub async fn reset_adjustments_for_paths( paths: Vec, to_neutral: Option, app_handle: AppHandle, -) -> Result<(), String> { +) -> Result>, String> { let reset_to = if to_neutral.unwrap_or(false) { crate::render::adjustment_utils::neutral_adjustments() } else { Value::Null }; - tauri::async_runtime::spawn_blocking(move || { - update_sidecars_and_thumbnails(paths, app_handle, move |_, _, metadata| { + let result = tauri::async_runtime::spawn_blocking(move || { + let gps_results = std::sync::Mutex::new(HashMap::new()); + let gps_results_ref = &gps_results; + update_sidecars_and_thumbnails(paths, app_handle, |path, source_path, metadata| { + crate::metadata::sidecar::fill_missing_exif(metadata, source_path); metadata.adjustments = reset_to.clone(); + let gps_coords = revert_gps_in_metadata_and_cache(source_path, metadata); + gps_results_ref + .lock() + .unwrap() + .insert(path.to_string(), gps_coords); }); + + gps_results.into_inner().unwrap() }) - .await - .map_err(|e| e.to_string()) + .await; + + match result { + Ok(map) => Ok(map), + Err(e) => Err(format!("Task failed: {}", e)), + } } fn update_sidecars_and_thumbnails( @@ -642,6 +738,268 @@ pub fn set_flag_for_paths( Ok(()) } +fn to_dms_string(val: f64) -> String { + let abs_val = val.abs(); + let deg = abs_val.floor() as u32; + let min_full = (abs_val - deg as f64) * 60.0; + let min = min_full.floor() as u32; + let sec = (min_full - min as f64) * 60.0; + format!("{} deg {} min {:.4} sec", deg, min, sec) +} + +pub fn extract_native_gps( + source_path: &Path, +) -> Option<(f64, f64, String, String, String, String)> { + let source_path_str = source_path.to_string_lossy(); + let map = if let Ok(mmap) = read_file_mapped(source_path) { + crate::metadata::exif_processing::read_exif_data_from_bytes(&source_path_str, &mmap) + } else if let Ok(bytes) = std::fs::read(source_path) { + crate::metadata::exif_processing::read_exif_data_from_bytes(&source_path_str, &bytes) + } else { + return None; + }; + + let lat_str = map.get("GPSLatitude")?; + let lon_str = map.get("GPSLongitude")?; + let lat_ref = map + .get("GPSLatitudeRef") + .cloned() + .unwrap_or_else(|| "N".to_string()); + let lon_ref = map + .get("GPSLongitudeRef") + .cloned() + .unwrap_or_else(|| "E".to_string()); + + let (d, m, s) = parse_gps_components(lat_str)?; + let mut lat_val = d as f64 + m / 60.0 + s / 3600.0; + if lat_ref.to_uppercase() == "S" { + lat_val = -lat_val; + } + + let (d, m, s) = parse_gps_components(lon_str)?; + let mut lon_val = d as f64 + m / 60.0 + s / 3600.0; + if lon_ref.to_uppercase() == "W" { + lon_val = -lon_val; + } + + Some(( + lat_val, + lon_val, + lat_str.clone(), + lat_ref, + lon_str.clone(), + lon_ref, + )) +} + +#[tauri::command] +pub fn set_gps_for_paths( + paths: Vec, + latitude: Option, + longitude: Option, + app_handle: AppHandle, +) -> Result<(), String> { + let settings = load_settings(app_handle.clone()).unwrap_or_default(); + let enable_xmp_sync = settings.enable_xmp_sync.unwrap_or(false); + let create_xmp_if_missing = settings.create_xmp_if_missing.unwrap_or(false); + + paths.par_iter().for_each(|path| { + let (source_path, sidecar_path) = parse_virtual_path(path); + let Ok(metadata) = + crate::metadata::sidecar::update_sidecar(&sidecar_path, &source_path, |metadata| { + crate::metadata::sidecar::fill_missing_exif(metadata, &source_path); + + let mut exif_map = metadata.exif.clone().unwrap_or_default(); + + let has_orig = exif_map.contains_key("OriginalGPSLatitude"); + let has_native = if has_orig { + true + } else if let Some(v) = exif_map.get("HasNativeGPS") { + v == "true" + } else if let Some((_, _, lat_s, lat_r, lon_s, lon_r)) = + extract_native_gps(&source_path) + { + exif_map.insert("OriginalGPSLatitude".to_string(), lat_s); + exif_map.insert("OriginalGPSLatitudeRef".to_string(), lat_r); + exif_map.insert("OriginalGPSLongitude".to_string(), lon_s); + exif_map.insert("OriginalGPSLongitudeRef".to_string(), lon_r); + exif_map.insert("HasNativeGPS".to_string(), "true".to_string()); + true + } else { + exif_map.insert("HasNativeGPS".to_string(), "false".to_string()); + false + }; + + if has_native + && !exif_map.contains_key("OriginalGPSLatitude") + && exif_map + .get("IsGpsModified") + .map(|s| s != "true") + .unwrap_or(true) + && let (Some(cur_lat), Some(cur_lon)) = ( + exif_map.get("GPSLatitude").cloned(), + exif_map.get("GPSLongitude").cloned(), + ) + { + let cur_lat_ref = exif_map + .get("GPSLatitudeRef") + .cloned() + .unwrap_or_else(|| "N".to_string()); + let cur_lon_ref = exif_map + .get("GPSLongitudeRef") + .cloned() + .unwrap_or_else(|| "E".to_string()); + exif_map.insert("OriginalGPSLatitude".to_string(), cur_lat); + exif_map.insert("OriginalGPSLatitudeRef".to_string(), cur_lat_ref); + exif_map.insert("OriginalGPSLongitude".to_string(), cur_lon); + exif_map.insert("OriginalGPSLongitudeRef".to_string(), cur_lon_ref); + } + + if let (Some(lat), Some(lon)) = (latitude, longitude) { + if (-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon) { + let lat_str = to_dms_string(lat); + let lat_ref = if lat >= 0.0 { "N" } else { "S" }.to_string(); + let lon_str = to_dms_string(lon); + let lon_ref = if lon >= 0.0 { "E" } else { "W" }.to_string(); + + exif_map.insert("GPSLatitude".to_string(), lat_str); + exif_map.insert("GPSLatitudeRef".to_string(), lat_ref); + exif_map.insert("GPSLongitude".to_string(), lon_str); + exif_map.insert("GPSLongitudeRef".to_string(), lon_ref); + exif_map.insert("IsGpsModified".to_string(), "true".to_string()); + if has_native { + exif_map.insert("HasNativeGPS".to_string(), "true".to_string()); + } else { + exif_map.insert("HasNativeGPS".to_string(), "false".to_string()); + } + + crate::metadata::exif_cache::save_exif_to_rrcache( + &source_path, + exif_map.clone(), + ); + metadata.exif = Some(exif_map); + } + } else { + exif_map.remove("GPSLatitude"); + exif_map.remove("GPSLatitudeRef"); + exif_map.remove("GPSLongitude"); + exif_map.remove("GPSLongitudeRef"); + if has_native { + exif_map.insert("IsGpsModified".to_string(), "true".to_string()); + } else { + exif_map.remove("IsGpsModified"); + exif_map.remove("HasNativeGPS"); + } + crate::metadata::exif_cache::save_exif_to_rrcache( + &source_path, + exif_map.clone(), + ); + metadata.exif = Some(exif_map); + } + }) + else { + return; + }; + + if enable_xmp_sync { + sync_metadata_to_xmp( + &source_path, + &sidecar_path, + &metadata, + create_xmp_if_missing, + ); + } + + let is_raw = crate::decode::formats::is_raw_file(&source_path); + let tm_override = resolve_tonemapper_override(&settings, is_raw); + let is_adj_edited = + is_image_edited(&metadata.adjustments, &source_path, is_raw, tm_override); + let is_gps_edited = metadata + .exif + .as_ref() + .map(|emap| { + emap.get("IsGpsModified") + .map(|v| v == "true") + .unwrap_or(false) + }) + .unwrap_or(false); + let is_edited = is_adj_edited || is_gps_edited; + let needs_ai = crate::ai::jobs::needs_generation(&metadata.adjustments, &source_path); + + emit_image_metadata_loaded( + &app_handle, + path, + &ImageFileMetadata { + is_edited, + tags: metadata.tags, + rating: metadata.rating, + flag: metadata.flag, + is_raw, + needs_ai, + }, + ); + }); + + Ok(()) +} + +#[tauri::command] +pub fn revert_gps_for_paths( + paths: Vec, + app_handle: AppHandle, +) -> Result>, String> { + let settings = load_settings(app_handle.clone()).unwrap_or_default(); + let enable_xmp_sync = settings.enable_xmp_sync.unwrap_or(false); + let create_xmp_if_missing = settings.create_xmp_if_missing.unwrap_or(false); + + let results: Vec<(String, Option<(f64, f64)>)> = paths + .par_iter() + .map(|path| { + let (source_path, sidecar_path) = parse_virtual_path(path); + let mut ret = None; + if let Ok(metadata) = + crate::metadata::sidecar::update_sidecar(&sidecar_path, &source_path, |metadata| { + crate::metadata::sidecar::fill_missing_exif(metadata, &source_path); + ret = revert_gps_in_metadata_and_cache(&source_path, metadata); + }) + { + if enable_xmp_sync { + sync_metadata_to_xmp( + &source_path, + &sidecar_path, + &metadata, + create_xmp_if_missing, + ); + } + + let is_raw = crate::decode::formats::is_raw_file(&source_path); + let tm_override = resolve_tonemapper_override(&settings, is_raw); + let is_adj_edited = + is_image_edited(&metadata.adjustments, &source_path, is_raw, tm_override); + let needs_ai = + crate::ai::jobs::needs_generation(&metadata.adjustments, &source_path); + + emit_image_metadata_loaded( + &app_handle, + path, + &ImageFileMetadata { + is_edited: is_adj_edited, + tags: metadata.tags, + rating: metadata.rating, + flag: metadata.flag, + is_raw, + needs_ai, + }, + ); + } + + (path.clone(), ret) + }) + .collect(); + + Ok(results.into_iter().collect()) +} + #[tauri::command] pub async fn load_metadata(path: String, app_handle: AppHandle) -> Result { let (source_path, _) = parse_virtual_path(&path); diff --git a/src-tauri/src/library/thumbnails.rs b/src-tauri/src/library/thumbnails.rs index e302cc3493..8c487fbc4c 100644 --- a/src-tauri/src/library/thumbnails.rs +++ b/src-tauri/src/library/thumbnails.rs @@ -635,9 +635,15 @@ pub fn generate_single_thumbnail_and_cache( if let Some(meta) = crate::metadata::sidecar::parse_sidecar(&content) { let is_raw = crate::decode::formats::is_raw_file(path_str); let tm = resolve_tonemapper_override(settings, is_raw); + let is_adj_edited = is_image_edited(&meta.adjustments, &source_path, is_raw, tm); + let is_gps_edited = meta + .exif + .as_ref() + .and_then(|e| e.get("IsGpsModified")) + .is_some_and(|v| v == "true"); let info = ( meta.rating, - is_image_edited(&meta.adjustments, &source_path, is_raw, tm), + is_adj_edited || is_gps_edited, serde_json::to_vec(&meta.adjustments).unwrap_or_default(), ); metadata = Some(meta); diff --git a/src-tauri/src/metadata/exif_processing.rs b/src-tauri/src/metadata/exif_processing.rs index 865490d82c..3fcba4e4f8 100644 --- a/src-tauri/src/metadata/exif_processing.rs +++ b/src-tauri/src/metadata/exif_processing.rs @@ -448,10 +448,50 @@ pub fn extract_metadata(file_bytes: &[u8]) -> Option> { } if !map.is_empty() { - if !map.contains_key("LensModel") - && let Some(lens) = read_raw_metadata(file_bytes).and_then(|meta| meta.lens) - { - insert_missing_lens_fields(&mut map, &lens); + if let Some(raw_meta) = read_raw_metadata(file_bytes) { + if !map.contains_key("LensModel") + && let Some(lens) = raw_meta.lens + { + insert_missing_lens_fields(&mut map, &lens); + } + if !map.contains_key("GPSLatitude") + && let Some(gps) = raw_meta.exif.gps + { + let fmt_rat = |r: &rawler::formats::tiff::Rational| -> f32 { + if r.d == 0 { + 0.0 + } else { + r.n as f32 / r.d as f32 + } + }; + let fmt_gps_coord = |coords: &[rawler::formats::tiff::Rational; 3]| -> String { + format!( + "{} deg {} min {} sec", + fmt_rat(&coords[0]), + fmt_rat(&coords[1]), + fmt_rat(&coords[2]) + ) + }; + + if let Some(lat) = gps.gps_latitude { + map.insert("GPSLatitude".to_string(), fmt_gps_coord(&lat)); + } + if let Some(lat_ref) = gps.gps_latitude_ref { + map.insert("GPSLatitudeRef".to_string(), lat_ref); + } + if let Some(lon) = gps.gps_longitude { + map.insert("GPSLongitude".to_string(), fmt_gps_coord(&lon)); + } + if let Some(lon_ref) = gps.gps_longitude_ref { + map.insert("GPSLongitudeRef".to_string(), lon_ref); + } + if let Some(alt) = gps.gps_altitude { + map.insert("GPSAltitude".to_string(), fmt_rat(&alt).to_string()); + } + if let Some(alt_ref) = gps.gps_altitude_ref { + map.insert("GPSAltitudeRef".to_string(), alt_ref.to_string()); + } + } } return Some(map); } @@ -804,8 +844,33 @@ pub fn read_rrexif_sidecar(image_path: &Path) -> Option> pub fn read_exif_data_from_bytes(path: &str, file_bytes: &[u8]) -> HashMap { if is_raw_file(path) - && let Some(map) = extract_metadata(file_bytes) + && let Some(mut map) = extract_metadata(file_bytes) { + if map.contains_key("GPSLatitude") && map.contains_key("GPSLongitude") { + map.insert("HasNativeGPS".to_string(), "true".to_string()); + if !map.contains_key("OriginalGPSLatitude") { + map.insert( + "OriginalGPSLatitude".to_string(), + map["GPSLatitude"].clone(), + ); + map.insert( + "OriginalGPSLatitudeRef".to_string(), + map.get("GPSLatitudeRef") + .cloned() + .unwrap_or_else(|| "N".to_string()), + ); + map.insert( + "OriginalGPSLongitude".to_string(), + map["GPSLongitude"].clone(), + ); + map.insert( + "OriginalGPSLongitudeRef".to_string(), + map.get("GPSLongitudeRef") + .cloned() + .unwrap_or_else(|| "E".to_string()), + ); + } + } return map; } @@ -828,6 +893,33 @@ pub fn read_exif_data_from_bytes(path: &str, file_bytes: &[u8]) -> HashMap Option { } } +pub fn parse_gps_components(coord: &str) -> Option<(u32, f64, f64)> { + let trimmed = coord.trim(); + + let re_dms = regex!( + r#"(\d+)\s*(?:deg|°)\s*(\d+(?:\.\d+)?)\s*(?:min|'|’|′)(?:\s*(\d+(?:\.\d+)?)\s*(?:sec|"|”|″)?)?"# + ); + if let Some(caps) = re_dms.captures(trimmed) { + let deg: u32 = caps.get(1)?.as_str().parse().ok()?; + let min_raw: f64 = caps.get(2)?.as_str().parse().ok()?; + if let Some(sec_match) = caps.get(3) { + let sec: f64 = sec_match.as_str().parse().unwrap_or(0.0); + return Some((deg, min_raw, sec)); + } else { + let min = min_raw.floor(); + let sec = (min_raw - min) * 60.0; + return Some((deg, min, sec)); + } + } + + let comma_parts: Vec<&str> = trimmed.split(',').map(|s| s.trim()).collect(); + let parse_frac = |s: &str| -> Option { + if let Some((n, d)) = s.split_once('/') { + let num: f64 = n.trim().parse().ok()?; + let den: f64 = d.trim().parse().ok()?; + if den != 0.0 { Some(num / den) } else { None } + } else { + s.parse().ok() + } + }; + if comma_parts.len() == 3 { + if let (Some(d), Some(m), Some(s)) = ( + parse_frac(comma_parts[0]), + parse_frac(comma_parts[1]), + parse_frac(comma_parts[2]), + ) { + return Some((d as u32, m, s)); + } + } else if comma_parts.len() == 2 + && let (Some(d), Some(m)) = (parse_frac(comma_parts[0]), parse_frac(comma_parts[1])) + { + let min = m.floor(); + let sec = (m - min) * 60.0; + return Some((d as u32, min, sec)); + } + + if let Ok(dec) = trimmed.parse::() { + let abs_val = dec.abs(); + let deg = abs_val.floor() as u32; + let min_full = (abs_val - deg as f64) * 60.0; + let min = min_full.floor(); + let sec = (min_full - min) * 60.0; + return Some((deg, min, sec)); + } + + None +} + +fn extract_xmp_tag_or_attr(content: &str, name: &str) -> Option { + let attr_pat = format!("{}=\"", name); + if let Some(idx) = content.find(&attr_pat) { + let start = idx + attr_pat.len(); + let end = content[start..].find('"').map(|i| start + i)?; + let val = content[start..end].trim(); + if !val.is_empty() { + return Some(val.to_string()); + } + } + let open_tag = format!("<{}>", name); + let close_tag = format!("", name); + if let Some(idx) = content.find(&open_tag) { + let start = idx + open_tag.len(); + let end = content[start..].find(&close_tag).map(|i| start + i)?; + let val = content[start..end].trim(); + if !val.is_empty() { + return Some(val.to_string()); + } + } + None +} + +fn parse_xmp_gps_coord( + raw: &str, + explicit_ref: Option<&str>, + is_lat: bool, +) -> Option<(String, String)> { + let mut s = raw.trim().to_string(); + let mut dir = explicit_ref + .map(|r| r.trim().to_uppercase()) + .unwrap_or_default(); + + if let Some(last_char) = s.chars().last() { + let upper = last_char.to_ascii_uppercase(); + if matches!(upper, 'N' | 'S' | 'E' | 'W') { + dir = upper.to_string(); + s.pop(); + s = s.trim().to_string(); + } + } + + if s.starts_with('-') { + dir = if is_lat { + "S".to_string() + } else { + "W".to_string() + }; + s = s.trim_start_matches('-').trim().to_string(); + } else if dir.is_empty() { + dir = if is_lat { + "N".to_string() + } else { + "E".to_string() + }; + } + + let (deg, min, sec) = parse_gps_components(&s)?; + let dms_str = format!("{} deg {} min {:.4} sec", deg, min.floor() as u32, sec); + Some((dms_str, dir)) +} + +pub fn extract_xmp_gps(content: &str) -> Option<(String, String, String, String)> { + let raw_lat = extract_xmp_tag_or_attr(content, "exif:GPSLatitude")?; + let raw_lon = extract_xmp_tag_or_attr(content, "exif:GPSLongitude")?; + let raw_lat_ref = extract_xmp_tag_or_attr(content, "exif:GPSLatitudeRef"); + let raw_lon_ref = extract_xmp_tag_or_attr(content, "exif:GPSLongitudeRef"); + + let (lat_dms, lat_ref) = parse_xmp_gps_coord(&raw_lat, raw_lat_ref.as_deref(), true)?; + let (lon_dms, lon_ref) = parse_xmp_gps_coord(&raw_lon, raw_lon_ref.as_deref(), false)?; + Some((lat_dms, lat_ref, lon_dms, lon_ref)) +} + pub fn sync_metadata_from_xmp( source_path: &Path, sidecar_path: &Path, @@ -159,6 +289,19 @@ pub fn sync_metadata_from_xmp( metadata.tags = Some(current_tags); changed = true; } + + let xmp_gps = extract_xmp_gps(&content); + if let Some((lat_s, lat_r, lon_s, lon_r)) = xmp_gps { + let mut exif_map = metadata.exif.clone().unwrap_or_default(); + if !exif_map.contains_key("GPSLatitude") { + exif_map.insert("GPSLatitude".to_string(), lat_s); + exif_map.insert("GPSLatitudeRef".to_string(), lat_r); + exif_map.insert("GPSLongitude".to_string(), lon_s); + exif_map.insert("GPSLongitudeRef".to_string(), lon_r); + metadata.exif = Some(exif_map); + changed = true; + } + } } changed } @@ -188,7 +331,8 @@ pub fn sync_metadata_to_xmp( + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:exif="http://ns.adobe.com/exif/1.0/"> "#; @@ -268,6 +412,149 @@ pub fn sync_metadata_to_xmp( } } + let gps_data = metadata.exif.as_ref().and_then(|exif| { + let lat = exif.get("GPSLatitude")?; + let lat_ref = exif + .get("GPSLatitudeRef") + .map(|s| s.as_str()) + .unwrap_or("N"); + let lon = exif.get("GPSLongitude")?; + let lon_ref = exif + .get("GPSLongitudeRef") + .map(|s| s.as_str()) + .unwrap_or("E"); + Some(( + lat.clone(), + lat_ref.to_string(), + lon.clone(), + lon_ref.to_string(), + )) + }); + + let re_lat_attr = regex!(r#"exif:GPSLatitude\s*=\s*"[^"]*""#); + let re_lat_tag = regex!(r#"[^<]*"#); + let re_lat_ref_attr = regex!(r#"exif:GPSLatitudeRef\s*=\s*"[^"]*""#); + let re_lat_ref_tag = regex!(r#"[^<]*"#); + let re_lon_attr = regex!(r#"exif:GPSLongitude\s*=\s*"[^"]*""#); + let re_lon_tag = regex!(r#"[^<]*"#); + let re_lon_ref_attr = regex!(r#"exif:GPSLongitudeRef\s*=\s*"[^"]*""#); + let re_lon_ref_tag = regex!(r#"[^<]*"#); + + if let Some((lat_val, lat_ref_val, lon_val, lon_ref_val)) = gps_data { + if !content.contains("xmlns:exif") + && let Some(desc_idx) = content.find(" String { + if let Some(deg_min_sec) = parse_gps_components(raw) { + let min_total = deg_min_sec.1 + deg_min_sec.2 / 60.0; + format!("{},{:.4}{}", deg_min_sec.0, min_total, r) + } else { + format!("{}{}", raw.trim(), r) + } + }; + + let xmp_lat = format_for_xmp(&lat_val, &lat_ref_val); + let xmp_lon = format_for_xmp(&lon_val, &lon_ref_val); + + if re_lat_attr.is_match(&content) { + content = re_lat_attr + .replace(&content, format!("exif:GPSLatitude=\"{}\"", xmp_lat)) + .to_string(); + } else if re_lat_tag.is_match(&content) { + content = re_lat_tag + .replace( + &content, + format!("{}", xmp_lat), + ) + .to_string(); + } else if let Some(last_index) = content.rfind("") { + let (start, end) = content.split_at(last_index); + content = format!( + "{} {}\n{}", + start, xmp_lat, end + ); + } + + if re_lat_ref_attr.is_match(&content) { + content = re_lat_ref_attr + .replace(&content, format!("exif:GPSLatitudeRef=\"{}\"", lat_ref_val)) + .to_string(); + } else if re_lat_ref_tag.is_match(&content) { + content = re_lat_ref_tag + .replace( + &content, + format!("{}", lat_ref_val), + ) + .to_string(); + } else if let Some(last_index) = content.rfind("") { + let (start, end) = content.split_at(last_index); + content = format!( + "{} {}\n{}", + start, lat_ref_val, end + ); + } + + if re_lon_attr.is_match(&content) { + content = re_lon_attr + .replace(&content, format!("exif:GPSLongitude=\"{}\"", xmp_lon)) + .to_string(); + } else if re_lon_tag.is_match(&content) { + content = re_lon_tag + .replace( + &content, + format!("{}", xmp_lon), + ) + .to_string(); + } else if let Some(last_index) = content.rfind("") { + let (start, end) = content.split_at(last_index); + content = format!( + "{} {}\n{}", + start, xmp_lon, end + ); + } + + if re_lon_ref_attr.is_match(&content) { + content = re_lon_ref_attr + .replace( + &content, + format!("exif:GPSLongitudeRef=\"{}\"", lon_ref_val), + ) + .to_string(); + } else if re_lon_ref_tag.is_match(&content) { + content = re_lon_ref_tag + .replace( + &content, + format!( + "{}", + lon_ref_val + ), + ) + .to_string(); + } else if let Some(last_index) = content.rfind("") { + let (start, end) = content.split_at(last_index); + content = format!( + "{} {}\n{}", + start, lon_ref_val, end + ); + } + } else { + content = re_lat_attr.replace_all(&content, "").to_string(); + content = re_lat_tag.replace_all(&content, "").to_string(); + content = re_lat_ref_attr.replace_all(&content, "").to_string(); + content = re_lat_ref_tag.replace_all(&content, "").to_string(); + content = re_lon_attr.replace_all(&content, "").to_string(); + content = re_lon_tag.replace_all(&content, "").to_string(); + content = re_lon_ref_attr.replace_all(&content, "").to_string(); + content = re_lon_ref_tag.replace_all(&content, "").to_string(); + } + let _ = write_file_atomic(&xmp_file, content.as_bytes()); } } diff --git a/src/components/panel/MainLibrary.tsx b/src/components/panel/MainLibrary.tsx index fce3e2d345..8bd79e0142 100644 --- a/src/components/panel/MainLibrary.tsx +++ b/src/components/panel/MainLibrary.tsx @@ -15,9 +15,11 @@ import { Columns, SlidersHorizontal, Rows3, + MapPin, X, } from 'lucide-react'; import CullingView from './library/CullingView'; +import MapView from './library/MapView'; import { motion, AnimatePresence } from 'framer-motion'; import { useTranslation } from 'react-i18next'; import Button from '../ui/Button'; @@ -105,6 +107,11 @@ function DisplayModeSwitch({ displayMode, setDisplayMode, t }: DisplayModeSwitch Icon: Columns, tooltip: t('library.viewMode.culling', { defaultValue: 'Culling View' }), }, + { + id: LibraryDisplayMode.Map, + Icon: MapPin, + tooltip: t('library.viewMode.map', { defaultValue: 'Map View' }), + }, ], [t], ); @@ -113,7 +120,7 @@ function DisplayModeSwitch({ displayMode, setDisplayMode, t }: DisplayModeSwitch const safeIndex = selectedIndex >= 0 ? selectedIndex : 0; return ( -
+
0 ? ( libraryDisplayMode === LibraryDisplayMode.Cull ? ( + ) : libraryDisplayMode === LibraryDisplayMode.Map ? ( + ) : ( = { + dark: { + id: 'dark', + label: 'Dark OSM', + icon: '🌙', + url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', + attribution: '© OpenStreetMap contributors', + className: 'dark-map-tiles', + maxZoom: 19, + }, + osm: { + id: 'osm', + label: 'OpenStreetMap', + icon: '☀️', + url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', + attribution: '© OpenStreetMap contributors', + className: '', + maxZoom: 19, + }, + satellite: { + id: 'satellite', + label: 'Satellite', + icon: '🛰️', + url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', + attribution: + 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and GIS User Community', + className: '', + maxZoom: 19, + }, +}; + +const MAP_STYLE_STORAGE_KEY = 'rapidraw_map_tile_style'; +const MAP_SHOW_THUMBNAILS_STORAGE_KEY = 'rapidraw_map_show_thumbnails'; +const MAP_DOCK_OPEN_STORAGE_KEY = 'rapidraw_map_dock_open'; +const MAP_DOCK_WIDTH_STORAGE_KEY = 'rapidraw_map_dock_width'; + +function getInitialMapStyle(): MapStyle { + try { + const saved = localStorage.getItem(MAP_STYLE_STORAGE_KEY); + if (saved && (saved === 'dark' || saved === 'osm' || saved === 'satellite')) { + return saved as MapStyle; + } + } catch (e) { + console.error('Failed to read map style from localStorage', e); + } + return 'dark'; +} + +function getInitialShowThumbnails(): boolean { + try { + const saved = localStorage.getItem(MAP_SHOW_THUMBNAILS_STORAGE_KEY); + if (saved !== null) { + return saved === 'true'; + } + } catch (e) { + console.error('Failed to read show thumbnails setting from localStorage', e); + } + return true; +} + +function getInitialDockOpen(): boolean { + try { + const saved = localStorage.getItem(MAP_DOCK_OPEN_STORAGE_KEY); + if (saved !== null) { + return saved === 'true'; + } + } catch (e) { + console.error('Failed to read dock open setting from localStorage', e); + } + return true; +} + +function getInitialDockWidth(): number { + try { + const saved = localStorage.getItem(MAP_DOCK_WIDTH_STORAGE_KEY); + if (saved !== null) { + const parsed = parseInt(saved, 10); + if (!isNaN(parsed) && parsed >= 160 && parsed <= 550) { + return parsed; + } + } + } catch (e) { + console.error('Failed to read dock width setting from localStorage', e); + } + return 260; +} + +function toDmsString(val: number): string { + const absVal = Math.abs(val); + const deg = Math.floor(absVal); + const minFull = (absVal - deg) * 60; + const min = Math.floor(minFull); + const sec = (minFull - min) * 60; + return `${deg} deg ${min} min ${sec.toFixed(4)} sec`; +} + +interface MapPhotoItem { + id: string; + path: string; + filename: string; + lat: number; + lon: number; + timestamp: string | null; + isRaw: boolean; + image: ImageFile; + hasNativeGps: boolean; + isGpsModified: boolean; +} + +function getFileExtension(filename: string): string { + const parts = filename.split('.'); + return parts.length > 1 ? parts.pop()!.toUpperCase() : ''; +} + +function createCustomPin(isSelected: boolean, isRaw: boolean, photoPath?: string): L.DivIcon { + const primaryColor = isSelected ? '#38bdf8' : isRaw ? '#f59e0b' : '#0284c7'; + const glow = isSelected ? 'filter: drop-shadow(0 0 10px rgba(56, 189, 248, 0.9));' : ''; + const encPath = photoPath ? encodeURIComponent(photoPath) : ''; + + const html = ` +
+ + + + + +
+ `; + + return L.divIcon({ + html, + className: 'custom-photo-pin', + iconSize: [28, 36], + iconAnchor: [14, 36], + }); +} + +function createThumbnailLoadingPin( + isSelected: boolean, + isRaw: boolean, + _filename: string, + photoPath?: string, +): L.DivIcon { + const borderColor = isSelected ? '#38bdf8' : isRaw ? '#f59e0b' : '#0284c7'; + const glow = isSelected + ? 'box-shadow: 0 0 16px rgba(56, 189, 248, 0.9), 0 4px 10px rgba(0, 0, 0, 0.6);' + : 'box-shadow: 0 4px 10px rgba(0, 0, 0, 0.6);'; + const encPath = photoPath ? encodeURIComponent(photoPath) : ''; + + const html = ` +
+
+ + + + + +
+
+
+ `; + + return L.divIcon({ + html, + className: 'photo-thumbnail-pin-loading', + iconSize: [96, 106], + iconAnchor: [48, 106], + }); +} + +function createPhotoThumbnailPin( + thumbnailUrl: string, + isSelected: boolean, + isRaw: boolean, + filename: string, + photoPath?: string, +): L.DivIcon { + const borderColor = isSelected ? '#38bdf8' : isRaw ? '#f59e0b' : '#0284c7'; + const glow = isSelected + ? 'box-shadow: 0 0 16px rgba(56, 189, 248, 0.9), 0 4px 10px rgba(0, 0, 0, 0.6);' + : 'box-shadow: 0 4px 10px rgba(0, 0, 0, 0.6);'; + const encPath = photoPath ? encodeURIComponent(photoPath) : ''; + + const html = ` +
+
+ ${filename} +
+
+
+ `; + + return L.divIcon({ + html, + className: 'photo-thumbnail-pin', + iconSize: [96, 106], + iconAnchor: [48, 106], + }); +} + +function createClusterThumbnailPin( + thumbnailUrl: string, + count: number, + clusterId?: number, + activeIndex?: number, + isSelected: boolean = false, +): L.DivIcon { + const countLabel = + activeIndex !== undefined ? `${activeIndex + 1}/${count}` : count > 999 ? '999+' : count.toString(); + + const borderColor = isSelected ? '#38bdf8' : '#0284c7'; + const glow = isSelected + ? 'box-shadow: 0 0 18px rgba(56, 189, 248, 0.9), 0 8px 16px rgba(0, 0, 0, 0.7);' + : 'box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6);'; + + const html = ` +
+
+
+
+ Cluster +
+ + + + + + ${countLabel} +
+
+
+
+ `; + + return L.divIcon({ + html, + className: 'photo-cluster-thumbnail-pin', + iconSize: [96, 106], + iconAnchor: [48, 106], + }); +} + +function createClusterLoadingPin( + count: number, + clusterId?: number, + activeIndex?: number, + isSelected: boolean = false, +): L.DivIcon { + const countLabel = + activeIndex !== undefined ? `${activeIndex + 1}/${count}` : count > 999 ? '999+' : count.toString(); + + const borderColor = isSelected ? '#38bdf8' : '#0284c7'; + const glow = isSelected + ? 'box-shadow: 0 0 18px rgba(56, 189, 248, 0.9), 0 8px 16px rgba(0, 0, 0, 0.7);' + : 'box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6);'; + const scale = isSelected ? 'scale(1.1)' : 'scale(1)'; + + const html = ` +
+
+
+
+ + + + + +
+ + + + + + ${countLabel} +
+
+
+
+ `; + + return L.divIcon({ + html, + className: 'photo-cluster-thumbnail-pin-loading', + iconSize: [96, 106], + iconAnchor: [48, 106], + }); +} + +function createCompactClusterPin(count: number, clusterId?: number): L.DivIcon { + const countLabel = count > 999 ? '999+' : count.toString(); + const c = count < 10 ? 'small' : count < 100 ? 'medium' : 'large'; + return L.divIcon({ + html: `
${countLabel}
`, + className: `marker-cluster marker-cluster-${c}`, + iconSize: new L.Point(40, 40), + }); +} + +function getBestThumbnail(path: string): string | undefined { + const proc = useProcessStore.getState(); + return proc.mediumThumbnails[path] || proc.thumbnails[path] || undefined; +} + +interface PhotoClusterLayerProps { + photos: MapPhotoItem[]; + selectedPath: string | null; + multiSelectedPaths: string[]; + currentFolderPath?: string | null; + onSelectPhoto: (path: string, event: MouseEvent) => void; + onDoubleClickPhoto: (path: string) => void; + onContextMenuPhoto: (event: MouseEvent, path: string) => void; + onRevertGps?: (path: string) => void; + onMovePhoto?: (paths: string[] | string, lat: number, lon: number) => void; + onMapContextMenu?: (lat: number, lon: number, screenX: number, screenY: number) => void; + showThumbnailCards: boolean; + onRequestThumbnails?: (paths: string[]) => void; + repositioningPath?: string | null; + onStartReposition?: (path: string) => void; + onRepositionSelect?: (lat: number, lon: number) => void; +} + +const PhotoClusterLayer: React.FC = ({ + photos, + selectedPath, + multiSelectedPaths, + currentFolderPath, + onSelectPhoto, + onDoubleClickPhoto, + onContextMenuPhoto, + onRevertGps, + onMovePhoto, + onMapContextMenu, + showThumbnailCards, + onRequestThumbnails, + repositioningPath, + onStartReposition, + onRepositionSelect, +}) => { + const map = useMap(); + const [cluster, setCluster] = useState(null); + const markersMapRef = useRef>(new Map()); + const clustersMapRef = useRef>(new Map()); + const isWheelSelectingRef = useRef(false); + const hasInitialFitRef = useRef(false); + const prevSelectedPathRef = useRef(null); + const prevSelectedPathsRef = useRef>(new Set(multiSelectedPaths || [])); + const hasZoomedToInitialRef = useRef(false); + const ignoreNextClusterClickRef = useRef(false); + const prevThumbnailsMapRef = useRef>(new Map()); + const thumbnails = useProcessStore((s) => s.thumbnails); + const mediumThumbnails = useProcessStore((s) => s.mediumThumbnails); + const { t } = useTranslation(); + + const selectedPathsSet = useMemo(() => new Set(multiSelectedPaths || []), [multiSelectedPaths]); + const selectedPathsSetRef = useRef>(selectedPathsSet); + useEffect(() => { + selectedPathsSetRef.current = selectedPathsSet; + }, [selectedPathsSet]); + + const multiSelectedPathsRef = useRef(multiSelectedPaths || []); + useEffect(() => { + multiSelectedPathsRef.current = multiSelectedPaths || []; + }, [multiSelectedPaths]); + + const prevElevatedMarkerRef = useRef(null); + const elevateMarker = useCallback((targetMarker: L.Marker | null) => { + if (prevElevatedMarkerRef.current && prevElevatedMarkerRef.current !== targetMarker) { + try { + if (typeof (prevElevatedMarkerRef.current as any).setZIndexOffset === 'function') { + prevElevatedMarkerRef.current.setZIndexOffset(0); + } + const prevEl = prevElevatedMarkerRef.current.getElement + ? prevElevatedMarkerRef.current.getElement() + : (prevElevatedMarkerRef.current as any)._icon; + if (prevEl) { + prevEl.style.zIndex = ''; + prevEl.classList.remove('elevated-map-marker'); + } + } catch {} + } + prevElevatedMarkerRef.current = targetMarker; + if (targetMarker) { + try { + if (typeof (targetMarker as any).setZIndexOffset === 'function') { + targetMarker.setZIndexOffset(100000); + } + const el = targetMarker.getElement ? targetMarker.getElement() : (targetMarker as any)._icon; + if (el) { + el.style.zIndex = '100000'; + el.classList.add('elevated-map-marker'); + } + } catch {} + } + }, []); + + const photosRef = useRef(photos); + useEffect(() => { + photosRef.current = photos; + }, [photos]); + + const pendingRefreshMarkersRef = useRef([]); + const refreshRafRef = useRef(null); + + const selectedPathRef = useRef(selectedPath); + useEffect(() => { + selectedPathRef.current = selectedPath; + }, [selectedPath]); + + const onRequestThumbnailsRef = useRef(onRequestThumbnails); + useEffect(() => { + onRequestThumbnailsRef.current = onRequestThumbnails; + }, [onRequestThumbnails]); + + const onSelectPhotoRef = useRef(onSelectPhoto); + useEffect(() => { + onSelectPhotoRef.current = onSelectPhoto; + }, [onSelectPhoto]); + + const onDoubleClickPhotoRef = useRef(onDoubleClickPhoto); + useEffect(() => { + onDoubleClickPhotoRef.current = onDoubleClickPhoto; + }, [onDoubleClickPhoto]); + + const showThumbnailCardsRef = useRef(showThumbnailCards); + useEffect(() => { + showThumbnailCardsRef.current = showThumbnailCards; + }, [showThumbnailCards]); + + useEffect(() => { + hasInitialFitRef.current = false; + hasZoomedToInitialRef.current = false; + }, [currentFolderPath]); + + const onMovePhotoRef = useRef(onMovePhoto); + useEffect(() => { + onMovePhotoRef.current = onMovePhoto; + }, [onMovePhoto]); + + const onStartRepositionRef = useRef(onStartReposition); + useEffect(() => { + onStartRepositionRef.current = onStartReposition; + }, [onStartReposition]); + + const onRepositionSelectRef = useRef(onRepositionSelect); + useEffect(() => { + onRepositionSelectRef.current = onRepositionSelect; + }, [onRepositionSelect]); + + const repositioningPathRef = useRef(repositioningPath); + useEffect(() => { + repositioningPathRef.current = repositioningPath; + }, [repositioningPath]); + + const onContextMenuPhotoRef = useRef(onContextMenuPhoto); + useEffect(() => { + onContextMenuPhotoRef.current = onContextMenuPhoto; + }, [onContextMenuPhoto]); + + const onMapContextMenuRef = useRef(onMapContextMenu); + useEffect(() => { + onMapContextMenuRef.current = onMapContextMenu; + }, [onMapContextMenu]); + + useEffect(() => { + const container = map.getContainer(); + if (repositioningPath) { + container.style.cursor = 'crosshair'; + } else { + container.style.cursor = ''; + } + return () => { + container.style.cursor = ''; + }; + }, [map, repositioningPath]); + + useEffect(() => { + const container = map.getContainer(); + + const getPinTargetPhotoPath = (pinEl: HTMLElement): string | null => { + const pinType = pinEl.getAttribute('data-map-pin'); + if (pinType === 'photo') { + const raw = pinEl.getAttribute('data-photo-path'); + return raw ? decodeURIComponent(raw) : null; + } + if (pinType === 'cluster') { + const clusterIdStr = pinEl.getAttribute('data-cluster-id'); + const clusterId = clusterIdStr ? Number(clusterIdStr) : null; + const clusterMarker = clusterId !== null ? clustersMapRef.current.get(clusterId) : null; + if (clusterMarker) { + const childMarkers = clusterMarker.getAllChildMarkers(); + const childPhotos = childMarkers.map((m: any) => m.photoPath as string).filter(Boolean); + let activeIdx = (clusterMarker as any)._activePhotoIndex ?? 0; + if (activeIdx < 0 || activeIdx >= childPhotos.length) activeIdx = 0; + return childPhotos[activeIdx] || childPhotos[0] || null; + } + } + return null; + }; + + const handleWheel = (e: WheelEvent) => { + const target = e.target as HTMLElement | null; + const clusterEl = target?.closest('[data-map-pin="cluster"]') as HTMLElement | null; + if (!clusterEl) return; + + const clusterIdStr = clusterEl.getAttribute('data-cluster-id'); + if (!clusterIdStr) return; + + const clusterId = Number(clusterIdStr); + const clusterMarker = clustersMapRef.current.get(clusterId); + if (!clusterMarker) return; + + const childMarkers = clusterMarker.getAllChildMarkers(); + if (!childMarkers || childMarkers.length <= 1) return; + + const childPhotos: string[] = childMarkers.map((m: any) => m.photoPath as string).filter(Boolean); + + if (childPhotos.length <= 1) return; + + e.preventDefault(); + e.stopPropagation(); + + elevateMarker(clusterMarker); + + let currentIdx = (clusterMarker as any)._activePhotoIndex ?? -1; + if (currentIdx === -1 && selectedPathRef.current) { + currentIdx = childPhotos.indexOf(selectedPathRef.current); + } + if (currentIdx === -1) { + currentIdx = 0; + } + + const direction = e.deltaY < 0 ? 1 : -1; + const nextIdx = (currentIdx + direction + childPhotos.length) % childPhotos.length; + (clusterMarker as any)._activePhotoIndex = nextIdx; + const nextPath = childPhotos[nextIdx]; + + if (onRequestThumbnailsRef.current) { + onRequestThumbnailsRef.current([nextPath]); + } + + const imgEl = clusterEl.querySelector('img'); + const thumb = getBestThumbnail(nextPath); + if (imgEl) { + imgEl.src = thumb || ''; + } + const badgeEl = clusterEl.querySelector('[data-cluster-badge]'); + if (badgeEl) { + badgeEl.textContent = `${nextIdx + 1}/${childPhotos.length}`; + } + + isWheelSelectingRef.current = true; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [nextPath], + libraryActivePath: nextPath, + selectionAnchorPath: nextPath, + }); + const photoObj = useLibraryStore.getState().imageList.find((p) => p.path === nextPath); + if (photoObj) { + useEditorStore.getState().setEditor({ selectedImage: photoObj as any }); + } + onSelectPhotoRef.current(nextPath, new MouseEvent('click')); + setTimeout(() => { + isWheelSelectingRef.current = false; + }, 150); + }; + + const handlePinMouseDown = (e: MouseEvent) => { + if (e.button !== 0 || e.altKey) return; + + const target = e.target as HTMLElement | null; + const pinEl = target?.closest('[data-map-pin]') as HTMLElement | null; + if (!pinEl) return; + + const pinType = pinEl.getAttribute('data-map-pin'); + + map.dragging.disable(); + + const stackCard = target?.closest('[data-stack-card]') as HTMLElement | null; + if (pinType === 'cluster' && stackCard) { + e.preventDefault(); + e.stopPropagation(); + ignoreNextClusterClickRef.current = true; + + const clusterIdStr = pinEl.getAttribute('data-cluster-id'); + const clusterId = clusterIdStr ? Number(clusterIdStr) : null; + const clusterMarker = clusterId !== null ? clustersMapRef.current.get(clusterId) : null; + if (clusterMarker) { + const childMarkers = clusterMarker.getAllChildMarkers(); + const childPhotos: string[] = childMarkers.map((m: any) => m.photoPath as string).filter(Boolean); + + if (childPhotos.length > 1) { + const stackNum = Number(stackCard.getAttribute('data-stack-card') || '1'); + let currentIdx = (clusterMarker as any)._activePhotoIndex ?? 0; + const nextIdx = (currentIdx + stackNum) % childPhotos.length; + (clusterMarker as any)._activePhotoIndex = nextIdx; + const nextPath = childPhotos[nextIdx]; + + if (onRequestThumbnailsRef.current) { + onRequestThumbnailsRef.current([nextPath]); + } + + const imgEl = pinEl.querySelector('img'); + const thumb = getBestThumbnail(nextPath); + if (imgEl) { + imgEl.src = thumb || ''; + } + const badgeEl = pinEl.querySelector('[data-cluster-badge]'); + if (badgeEl) { + badgeEl.textContent = `${nextIdx + 1}/${childPhotos.length}`; + } + + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [nextPath], + libraryActivePath: nextPath, + selectionAnchorPath: nextPath, + }); + const photoObj = useLibraryStore.getState().imageList.find((p) => p.path === nextPath); + if (photoObj) { + useEditorStore.getState().setEditor({ selectedImage: photoObj as any }); + } + onSelectPhotoRef.current(nextPath, new MouseEvent('click')); + } + } + + const onStackMouseUp = () => { + window.removeEventListener('mouseup', onStackMouseUp, true); + map.dragging.enable(); + }; + window.addEventListener('mouseup', onStackMouseUp, true); + return; + } + + const targetPhotoPath = getPinTargetPhotoPath(pinEl); + if (!targetPhotoPath) { + map.dragging.enable(); + return; + } + + const photoToDrag = targetPhotoPath; + const isPhotoSelected = selectedPathsSetRef.current.has(photoToDrag); + const currentMulti = multiSelectedPathsRef.current; + const pathsToMove = isPhotoSelected && currentMulti.length > 1 ? currentMulti : [photoToDrag]; + + const cardEl = (pinEl.querySelector('[data-front-card="true"]') || pinEl.firstElementChild) as HTMLElement | null; + const cardRect = cardEl ? cardEl.getBoundingClientRect() : pinEl.getBoundingClientRect(); + const grabOffsetX = e.clientX - cardRect.left; + const grabOffsetY = e.clientY - cardRect.top; + + const isThumbnailMode = showThumbnailCardsRef.current; + const pinWidth = isThumbnailMode ? 96 : 28; + const pinHeight = isThumbnailMode ? 106 : 36; + const anchorX = isThumbnailMode ? 48 : 14; + const anchorY = isThumbnailMode ? 106 : 36; + + const startX = e.clientX; + const startY = e.clientY; + let isDragging = false; + let avatarEl: HTMLDivElement | null = null; + + const onMouseMove = (moveEv: MouseEvent) => { + const dx = moveEv.clientX - startX; + const dy = moveEv.clientY - startY; + if (!isDragging && Math.hypot(dx, dy) > 4) { + isDragging = true; + pinEl.style.opacity = '0.4'; + + avatarEl = document.createElement('div'); + avatarEl.className = 'photo-drag-avatar'; + avatarEl.style.cssText = ` + position: fixed; + left: ${moveEv.clientX - grabOffsetX}px; + top: ${moveEv.clientY - grabOffsetY}px; + width: ${pinWidth}px; + height: ${pinHeight}px; + pointer-events: none; + z-index: 9999999; + filter: drop-shadow(0 12px 24px rgba(0, 0, 0, 0.7)); + `; + + const activeThumb = getBestThumbnail(photoToDrag); + const countBadge = + pathsToMove.length > 1 + ? ` +
+ + + + + + ${pathsToMove.length} +
+ ` + : ''; + + if (isThumbnailMode) { + avatarEl.innerHTML = ` +
+ ${ + activeThumb + ? `` + : `
${ + pathsToMove.length > 1 ? `Moving ${pathsToMove.length}...` : 'Moving...' + }
` + } + ${countBadge} +
+
+ `; + } else { + avatarEl.innerHTML = ` +
+ + + + + +
+ `; + } + document.body.appendChild(avatarEl); + } + + if (isDragging && avatarEl) { + avatarEl.style.left = `${moveEv.clientX - grabOffsetX}px`; + avatarEl.style.top = `${moveEv.clientY - grabOffsetY}px`; + } + }; + + const onMouseUp = (upEv: MouseEvent) => { + window.removeEventListener('mousemove', onMouseMove, true); + window.removeEventListener('mouseup', onMouseUp, true); + + map.dragging.enable(); + pinEl.style.opacity = '1'; + + if (avatarEl && avatarEl.parentNode) { + avatarEl.parentNode.removeChild(avatarEl); + avatarEl = null; + } + + if (isDragging) { + upEv.preventDefault(); + upEv.stopPropagation(); + ignoreNextClusterClickRef.current = true; + + const avatarLeft = upEv.clientX - grabOffsetX; + const avatarTop = upEv.clientY - grabOffsetY; + const triangleTipX = avatarLeft + anchorX; + const triangleTipY = avatarTop + anchorY; + + const mapContainer = map.getContainer(); + const rect = mapContainer.getBoundingClientRect(); + const pt = L.point(triangleTipX - rect.left, triangleTipY - rect.top); + const dropLatLng = map.containerPointToLatLng(pt); + const lat = dropLatLng.lat; + const lon = ((((dropLatLng.lng + 180) % 360) + 360) % 360) - 180; + + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: pathsToMove, + libraryActivePath: photoToDrag, + selectionAnchorPath: photoToDrag, + }); + const photoObj = useLibraryStore.getState().imageList.find((p) => p.path === photoToDrag); + if (photoObj) { + useEditorStore.getState().setEditor({ selectedImage: photoObj as any }); + } + + if (onMovePhotoRef.current) { + onMovePhotoRef.current(pathsToMove, lat, lon); + } + } else { + onSelectPhotoRef.current(photoToDrag, upEv); + } + }; + + window.addEventListener('mousemove', onMouseMove, true); + window.addEventListener('mouseup', onMouseUp, true); + }; + + const handlePinDblClick = (e: MouseEvent) => { + const target = e.target as HTMLElement | null; + const pinEl = target?.closest('[data-map-pin]') as HTMLElement | null; + if (!pinEl) return; + + e.preventDefault(); + e.stopPropagation(); + + const targetPhotoPath = getPinTargetPhotoPath(pinEl); + if (targetPhotoPath && onDoubleClickPhotoRef.current) { + onDoubleClickPhotoRef.current(targetPhotoPath); + } + }; + + const handlePinContextMenu = (e: MouseEvent) => { + const target = e.target as HTMLElement | null; + const pinEl = target?.closest('[data-map-pin]') as HTMLElement | null; + if (!pinEl) return; + + e.preventDefault(); + e.stopPropagation(); + + const targetPhotoPath = getPinTargetPhotoPath(pinEl); + if (targetPhotoPath && onContextMenuPhotoRef.current) { + onContextMenuPhotoRef.current(e, targetPhotoPath); + } + }; + + container.addEventListener('wheel', handleWheel, { passive: false, capture: true }); + container.addEventListener('mousedown', handlePinMouseDown, { capture: true }); + container.addEventListener('dblclick', handlePinDblClick, { capture: true }); + container.addEventListener('contextmenu', handlePinContextMenu, { capture: true }); + return () => { + container.removeEventListener('wheel', handleWheel, { capture: true } as any); + container.removeEventListener('mousedown', handlePinMouseDown, { capture: true } as any); + container.removeEventListener('dblclick', handlePinDblClick, { capture: true } as any); + container.removeEventListener('contextmenu', handlePinContextMenu, { capture: true } as any); + }; + }, [map, elevateMarker]); + + useEffect(() => { + const handleContextMenu = (e: L.LeafletMouseEvent) => { + if (onMapContextMenuRef.current) { + onMapContextMenuRef.current( + e.latlng.lat, + ((((e.latlng.lng + 180) % 360) + 360) % 360) - 180, + e.originalEvent.clientX, + e.originalEvent.clientY, + ); + } + }; + + const handleMapClick = (e: L.LeafletMouseEvent) => { + if (repositioningPathRef.current && onRepositionSelectRef.current) { + onRepositionSelectRef.current(e.latlng.lat, ((((e.latlng.lng + 180) % 360) + 360) % 360) - 180); + } + }; + + map.on('contextmenu', handleContextMenu); + map.on('click', handleMapClick); + return () => { + map.off('contextmenu', handleContextMenu); + map.off('click', handleMapClick); + }; + }, [map]); + + useEffect(() => { + const clusterGroup = L.markerClusterGroup({ + chunkedLoading: false, + maxClusterRadius: 50, + spiderfyOnMaxZoom: false, + showCoverageOnHover: false, + zoomToBoundsOnClick: false, + animate: false, + animateAddingMarkers: false, + disableClusteringAtZoom: 18, + iconCreateFunction: (c: L.MarkerCluster) => { + const count = c.getChildCount(); + const clusterId = (c as any)._leaflet_id; + clustersMapRef.current.set(clusterId, c); + + const childMarkers = c.getAllChildMarkers(); + const childPaths = childMarkers.map((m: any) => m.photoPath as string).filter(Boolean); + + let activeIdx = (c as any)._activePhotoIndex; + if (activeIdx === undefined || activeIdx >= childPaths.length || activeIdx < 0) { + let foundIdx = -1; + if (selectedPathRef.current) { + foundIdx = childPaths.indexOf(selectedPathRef.current); + } + if (foundIdx === -1) { + foundIdx = childPaths.findIndex((p) => selectedPathsSetRef.current.has(p)); + } + activeIdx = foundIdx !== -1 ? foundIdx : 0; + (c as any)._activePhotoIndex = activeIdx; + } + + const activePath = childPaths[activeIdx] || childPaths[0]; + + if (!showThumbnailCardsRef.current) { + return createCompactClusterPin(count, clusterId); + } + + let cachedThumbUrl: string | null = (activePath && getBestThumbnail(activePath)) || null; + if (!cachedThumbUrl) { + for (let i = 0; i < childPaths.length; i++) { + const p = childPaths[i]; + const found = p && getBestThumbnail(p); + if (found) { + cachedThumbUrl = found; + break; + } + } + } + + const isSelected = childPaths.some((p) => selectedPathsSetRef.current.has(p)); + + if (cachedThumbUrl) { + return createClusterThumbnailPin(cachedThumbUrl, count, clusterId, activeIdx, isSelected); + } + + return createClusterLoadingPin(count, clusterId, activeIdx, isSelected); + }, + }); + + const handleClusterClick = (e: L.LeafletEvent) => { + if (ignoreNextClusterClickRef.current) { + ignoreNextClusterClickRef.current = false; + return; + } + const clusterMarker = (e as any).layer as L.MarkerCluster; + if (!clusterMarker) return; + + elevateMarker(clusterMarker); + + const childMarkers = clusterMarker.getAllChildMarkers(); + const childPaths = childMarkers.map((m: any) => m.photoPath as string).filter(Boolean); + if (childPaths.length === 0) return; + + let activeIdx = (clusterMarker as any)._activePhotoIndex ?? 0; + if (activeIdx < 0 || activeIdx >= childPaths.length) activeIdx = 0; + const activePath = childPaths[activeIdx] || childPaths[0]; + + const photoObj = useLibraryStore.getState().imageList.find((p) => p.path === activePath); + if (photoObj) { + useEditorStore.getState().setEditor({ selectedImage: photoObj as any }); + } + + onSelectPhotoRef.current(activePath, (e as any).originalEvent || new MouseEvent('click')); + }; + + clusterGroup.on('clusterclick', handleClusterClick); + + map.addLayer(clusterGroup); + setCluster(clusterGroup); + + return () => { + if (refreshRafRef.current !== null) { + cancelAnimationFrame(refreshRafRef.current); + refreshRafRef.current = null; + } + clusterGroup.off('clusterclick', handleClusterClick); + clusterGroup.clearLayers(); + map.removeLayer(clusterGroup); + clustersMapRef.current.clear(); + markersMapRef.current.clear(); + setCluster(null); + }; + }, [map, elevateMarker]); + + const requestVisibleThumbnails = useCallback(() => { + if (!showThumbnailCards || !onRequestThumbnails || !map || !cluster) return; + + try { + const bounds = map.getBounds(); + const hasThumb = (p: string) => Boolean(getBestThumbnail(p)); + const missing: string[] = []; + const seenClusters = new Set(); + + for (const photo of photosRef.current) { + if (missing.length >= 30) break; + + const marker = markersMapRef.current.get(photo.path); + if (!marker) continue; + + if (!bounds.contains([photo.lat, photo.lon])) continue; + + const visibleParent = cluster.getVisibleParent(marker); + if (!visibleParent) continue; + + if (visibleParent === marker) { + if (!hasThumb(photo.path) && !missing.includes(photo.path)) { + missing.push(photo.path); + } + } else { + if (seenClusters.has(visibleParent)) continue; + seenClusters.add(visibleParent); + + const childMarkers = (visibleParent as L.MarkerCluster).getAllChildMarkers(); + const hasAnyCachedThumb = childMarkers.some((m) => { + const p = (m as any).photoPath; + return p && hasThumb(p); + }); + + if (!hasAnyCachedThumb && childMarkers.length > 0) { + const repPath = (childMarkers[0] as any)?.photoPath; + if (repPath && !hasThumb(repPath) && !missing.includes(repPath)) { + missing.push(repPath); + } + } + } + } + + if (missing.length > 0) { + onRequestThumbnails(missing); + } + } catch {} + }, [showThumbnailCards, onRequestThumbnails, map, cluster]); + + useEffect(() => { + if (!cluster) return; + + const currentPaths = new Set(photos.map((p) => p.path)); + const existingMarkers = markersMapRef.current; + + const markersToRemove: L.Marker[] = []; + existingMarkers.forEach((marker, path) => { + if (!currentPaths.has(path)) { + markersToRemove.push(marker); + existingMarkers.delete(path); + } + }); + if (markersToRemove.length > 0) { + cluster.removeLayers(markersToRemove); + } + + const markersToAdd: L.Marker[] = []; + const markersToReposition: L.Marker[] = []; + + photos.forEach((photo) => { + let marker = existingMarkers.get(photo.path); + + if (!marker) { + const isSelected = selectedPathsSet.has(photo.path); + const cachedThumb = getBestThumbnail(photo.path); + + const icon = !showThumbnailCards + ? createCustomPin(isSelected, photo.isRaw, photo.path) + : cachedThumb + ? createPhotoThumbnailPin(cachedThumb, isSelected, photo.isRaw, photo.filename, photo.path) + : createThumbnailLoadingPin(isSelected, photo.isRaw, photo.filename, photo.path); + + marker = L.marker([photo.lat, photo.lon], { + icon, + title: photo.filename, + draggable: false, + autoPan: false, + }); + (marker as any).photoPath = photo.path; + + existingMarkers.set(photo.path, marker); + markersToAdd.push(marker); + } else { + (marker as any).photoPath = photo.path; + const curLatLng = marker.getLatLng(); + if (Math.abs(curLatLng.lat - photo.lat) > 1e-6 || Math.abs(curLatLng.lng - photo.lon) > 1e-6) { + markersToReposition.push(marker); + } + } + }); + + if (markersToReposition.length > 0) { + cluster.removeLayers(markersToReposition); + for (const m of markersToReposition) { + const p = photos.find((ph) => ph.path === (m as any).photoPath); + if (p) { + m.setLatLng([p.lat, p.lon]); + } + } + cluster.addLayers(markersToReposition); + } + + if (markersToAdd.length > 0) { + cluster.addLayers(markersToAdd); + } + + const selectedPhoto = selectedPath ? photos.find((p) => p.path === selectedPath) : null; + + if (!hasInitialFitRef.current && photos.length > 0) { + hasInitialFitRef.current = true; + if (selectedPhoto) { + hasZoomedToInitialRef.current = true; + const targetZoom = 16; + map.setView([selectedPhoto.lat, selectedPhoto.lon], targetZoom); + } else { + hasZoomedToInitialRef.current = true; + try { + const latLngs = photos.map((p) => [p.lat, p.lon] as [number, number]); + const bounds = L.latLngBounds(latLngs); + if (bounds.isValid()) { + map.fitBounds(bounds, { padding: [50, 50], maxZoom: 16 }); + } + } catch (e) { + console.error('Failed to fit bounds', e); + } + } + } + }, [ + cluster, + photos, + selectedPath, + onSelectPhoto, + onDoubleClickPhoto, + onContextMenuPhoto, + onRequestThumbnails, + map, + showThumbnailCards, + elevateMarker, + ]); + + useEffect(() => { + if (!showThumbnailCards || !cluster) return; + + const debouncedReq = debounce(requestVisibleThumbnails, 250); + map.on('moveend', debouncedReq); + map.on('zoomend', debouncedReq); + + const timer = setTimeout(requestVisibleThumbnails, 400); + + return () => { + map.off('moveend', debouncedReq); + map.off('zoomend', debouncedReq); + clearTimeout(timer); + debouncedReq.cancel(); + }; + }, [map, cluster, showThumbnailCards, requestVisibleThumbnails]); + + useEffect(() => { + const newlyAdded: string[] = []; + const checkDict = (dict: Record) => { + for (const path in dict) { + const url = dict[path]; + if (url && prevThumbnailsMapRef.current.get(path) !== url) { + prevThumbnailsMapRef.current.set(path, url); + newlyAdded.push(path); + } + } + }; + checkDict(thumbnails); + checkDict(mediumThumbnails); + + if (newlyAdded.length === 0) return; + + if (!showThumbnailCards) return; + + const markersToRefresh: L.Marker[] = []; + for (const path of newlyAdded) { + const marker = markersMapRef.current.get(path); + const photo = photos.find((p) => p.path === path); + if (marker && photo) { + const thumbUrl = mediumThumbnails[path] || thumbnails[path]; + const isSelected = selectedPathsSetRef.current.has(path); + marker.setIcon(createPhotoThumbnailPin(thumbUrl, isSelected, photo.isRaw, photo.filename, photo.path)); + markersToRefresh.push(marker); + } + } + + if (cluster && markersToRefresh.length > 0) { + pendingRefreshMarkersRef.current.push(...markersToRefresh); + if (refreshRafRef.current === null) { + refreshRafRef.current = requestAnimationFrame(() => { + refreshRafRef.current = null; + const toRefresh = pendingRefreshMarkersRef.current; + pendingRefreshMarkersRef.current = []; + if (cluster && toRefresh.length > 0) { + try { + cluster.refreshClusters(toRefresh); + } catch {} + } + }); + } + } + }, [thumbnails, mediumThumbnails, showThumbnailCards, photos, selectedPath, cluster]); + + useEffect(() => { + markersMapRef.current.forEach((marker, path) => { + const photo = photosRef.current.find((p) => p.path === path); + if (!photo) return; + + const isSelected = selectedPathsSetRef.current.has(path); + if (!showThumbnailCards) { + marker.setIcon(createCustomPin(isSelected, photo.isRaw, photo.path)); + } else { + const thumb = getBestThumbnail(path); + marker.setIcon( + thumb + ? createPhotoThumbnailPin(thumb, isSelected, photo.isRaw, photo.filename, photo.path) + : createThumbnailLoadingPin(isSelected, photo.isRaw, photo.filename, photo.path), + ); + } + }); + + if (cluster) { + cluster.refreshClusters(); + } + }, [showThumbnailCards, cluster]); + + useEffect(() => { + const currentSet = new Set(multiSelectedPaths || []); + const prevSet = prevSelectedPathsRef.current; + + const deselected: string[] = []; + prevSet.forEach((p) => { + if (!currentSet.has(p)) { + deselected.push(p); + } + }); + + const newlySelected: string[] = []; + currentSet.forEach((p) => { + if (!prevSet.has(p)) { + newlySelected.push(p); + } + }); + + prevSelectedPathsRef.current = currentSet; + + for (const p of deselected) { + const marker = markersMapRef.current.get(p); + const photo = photos.find((ph) => ph.path === p); + if (marker && photo) { + const thumb = getBestThumbnail(p); + marker.setIcon( + !showThumbnailCards + ? createCustomPin(false, photo.isRaw, photo.path) + : thumb + ? createPhotoThumbnailPin(thumb, false, photo.isRaw, photo.filename, photo.path) + : createThumbnailLoadingPin(false, photo.isRaw, photo.filename, photo.path), + ); + } + } + + for (const p of newlySelected) { + const marker = markersMapRef.current.get(p); + const photo = photos.find((ph) => ph.path === p); + if (marker && photo) { + const thumb = getBestThumbnail(p); + marker.setIcon( + !showThumbnailCards + ? createCustomPin(true, photo.isRaw, photo.path) + : thumb + ? createPhotoThumbnailPin(thumb, true, photo.isRaw, photo.filename, photo.path) + : createThumbnailLoadingPin(true, photo.isRaw, photo.filename, photo.path), + ); + } + } + + if (cluster && (deselected.length > 0 || newlySelected.length > 0)) { + try { + cluster.refreshClusters(); + } catch {} + } + + if (!selectedPath) { + elevateMarker(null); + return; + } + + if (isWheelSelectingRef.current) return; + + const marker = markersMapRef.current.get(selectedPath); + const photo = photos.find((p) => p.path === selectedPath); + + if (marker && photo) { + const visibleParent = cluster ? cluster.getVisibleParent(marker) : marker; + const targetToElevate = visibleParent || marker; + + const thumb = getBestThumbnail(selectedPath); + marker.setIcon( + showThumbnailCards && thumb + ? createPhotoThumbnailPin(thumb, true, photo.isRaw, photo.filename, photo.path) + : showThumbnailCards + ? createThumbnailLoadingPin(true, photo.isRaw, photo.filename, photo.path) + : createCustomPin(true, photo.isRaw, photo.path), + ); + elevateMarker(targetToElevate); + + if (visibleParent && visibleParent !== marker) { + const clusterObj = visibleParent as L.MarkerCluster; + const childMarkers = clusterObj.getAllChildMarkers(); + const childPaths = childMarkers.map((m: any) => m.photoPath as string).filter(Boolean); + const idx = childPaths.indexOf(photo.path); + if (idx !== -1) { + (clusterObj as any)._activePhotoIndex = idx; + const el = clusterObj.getElement(); + if (el) { + const imgEl = el.querySelector('img'); + if (imgEl && thumb) { + imgEl.src = thumb; + } + const badgeEl = el.querySelector('[data-cluster-badge]'); + if (badgeEl) { + badgeEl.textContent = `${idx + 1}/${childPaths.length}`; + } + } + } + } + } + }, [multiSelectedPaths, selectedPath, photos, map, showThumbnailCards, cluster, elevateMarker]); + + return null; +}; + +interface UnlocatedPhotoCardProps { + photo: ImageFile; + filename: string; + timestamp: string | null; + exif?: Record; + isSelected: boolean; + cardHeight: number; + onSelect: (e: React.MouseEvent) => void; + onDoubleClick?: () => void; + onContextMenu?: (e: React.MouseEvent) => void; + onDragStart: (e: React.DragEvent) => void; + onDragEnd?: (e: React.DragEvent) => void; + onRequestThumb: (path: string) => void; +} + +const UnlocatedPhotoCard: React.FC = React.memo( + ({ + photo, + filename, + timestamp, + exif, + isSelected, + cardHeight, + onSelect, + onDoubleClick, + onContextMenu, + onDragStart, + onDragEnd, + onRequestThumb, + }) => { + const thumbUrl = useProcessStore((s) => s.mediumThumbnails[photo.path] || s.thumbnails[photo.path]); + + useEffect(() => { + if (!thumbUrl) { + onRequestThumb(photo.path); + } + }, [photo.path, thumbUrl, onRequestThumb]); + + const { shutter, fNumber, iso, focal } = useMemo(() => { + const e = exif || photo.exif || {}; + let fNum = e.FNumber ? String(e.FNumber) : ''; + if (fNum && !fNum.toLowerCase().startsWith('f')) fNum = `f/${fNum}`; + const focalVal = e.FocalLengthIn35mmFilm || e.FocalLength || ''; + const focalStr = focalVal ? (String(focalVal).endsWith('mm') ? String(focalVal) : `${focalVal}mm`) : ''; + return { + shutter: e.ExposureTime || '', + fNumber: fNum, + iso: e.PhotographicSensitivity || e.ISOSpeedRatings || '', + focal: focalStr, + }; + }, [exif, photo.exif]); + + return ( +
+
+ {thumbUrl ? ( + {filename} + ) : ( +
+ +
+ )} +
+ +
+ +
+
+ + {filename} + +
+ +
+
+
+ {shutter && ( +
+ + {shutter} +
+ )} + {fNumber && ( +
+ + {fNumber} +
+ )} + {iso && ( +
+ + {iso} +
+ )} + {focal && ( +
+ + {focal} +
+ )} + {!shutter && !fNumber && !iso && !focal && timestamp && ( + {timestamp} + )} +
+
+
+
+ +
+
+ ); + }, +); + +function UnlocatedDockRow(props: any) { + const { + index, + style, + unlocatedPhotos, + selectedDockPaths, + effectiveSelectedPath, + localExifMap, + dockWidth, + handlePhotoSelect, + onImageDoubleClick, + onContextMenu, + handlePhotoDragStart, + handlePhotoDragEnd, + queueThumbnailRequest, + } = props; + + const photo = unlocatedPhotos[index]; + if (!photo) return null; + + const isSelected = selectedDockPaths.has(photo.path); + const filename = photo.path.split(/[\\/]/).pop() || ''; + const timestamp = getImageTimestamp(photo, localExifMap[photo.path]); + const exif = localExifMap[photo.path] || photo.exif; + const cardHeight = Math.max(120, dockWidth - 16); + + return ( +
+ handlePhotoSelect(photo.path, e)} + onDoubleClick={() => onImageDoubleClick?.(photo.path)} + onContextMenu={(e) => onContextMenu?.(e, photo.path)} + onDragStart={(e) => handlePhotoDragStart(photo, e)} + onDragEnd={handlePhotoDragEnd} + onRequestThumb={queueThumbnailRequest} + /> +
+ ); +} + +interface MapControlsProps { + onFitBounds: () => void; + tileStyle: MapStyle; + onTileStyleChange: (style: MapStyle) => void; + showThumbnailCards: boolean; + onToggleThumbnailCards: () => void; + isDockOpen: boolean; + onToggleDock: () => void; + unlocatedCount: number; + canUndo?: boolean; + onUndo?: () => void; +} + +const MapControls: React.FC = ({ + onFitBounds, + tileStyle, + onTileStyleChange, + showThumbnailCards, + onToggleThumbnailCards, + isDockOpen, + onToggleDock, + unlocatedCount, + canUndo, + onUndo, +}) => { + const [showMenu, setShowMenu] = useState(false); + const { t } = useTranslation(); + + return ( +
+ + + + + + + + +
+ + + {showMenu && ( +
+ + {t('library.map.mapStyle', { defaultValue: 'Map Style' })} + + {(Object.values(MAP_LAYERS) as MapLayerConfig[]).map((layer) => ( + + ))} +
+ )} +
+
+ ); +}; + +export interface MapViewProps { + imageList: Array; + activePath: string | null; + multiSelectedPaths: Array; + currentFolderPath?: string | null; + onImageClick(path: string, event: React.MouseEvent | MouseEvent): void; + onImageDoubleClick(path: string): void; + onContextMenu(event: React.MouseEvent | MouseEvent, path: string): void; + onEmptyAreaContextMenu?(event: React.MouseEvent | MouseEvent): void; + onRequestThumbnails?(paths: string[]): void; +} + +interface GpsUndoItem { + path: string; + previousLat: number | null; + previousLon: number | null; + hadNativeGps?: boolean; +} + +interface GpsUndoAction { + items: GpsUndoItem[]; +} + +export default function MapView(props: MapViewProps) { + const [tileStyle, setTileStyle] = useState(getInitialMapStyle); + const [showThumbnailCards, setShowThumbnailCards] = useState(getInitialShowThumbnails); + const [isDockOpen, setIsDockOpen] = useState(getInitialDockOpen); + const [dockWidth, setDockWidth] = useState(getInitialDockWidth); + const [selectedDockPaths, setSelectedDockPaths] = useState>(new Set()); + const [repositioningPhotoPath, setRepositioningPhotoPath] = useState(null); + const [isDraggingOverMap, setIsDraggingOverMap] = useState(false); + const [mapContextMenu, setMapContextMenu] = useState<{ + x: number; + y: number; + lat: number; + lon: number; + targetPaths: string[]; + } | null>(null); + + const exifByPath = useLibraryStore((s) => s.exifByPath); + const [localExifMap, setLocalExifMap] = useState>>(() => { + const initial: Record> = { ...useLibraryStore.getState().exifByPath }; + for (const img of props.imageList || []) { + if (img.exif) { + initial[img.path] = img.exif; + } + } + return initial; + }); + const requestedExifRef = useRef>(new Set()); + const mapRef = useRef(null); + const isResizing = useRef(false); + const [isResizingState, setIsResizingState] = useState(false); + const dockWidthRef = useRef(dockWidth); + + const undoStackRef = useRef([]); + const [canUndo, setCanUndo] = useState(false); + + useEffect(() => { + dockWidthRef.current = dockWidth; + }, [dockWidth]); + + const dockListContainerRef = useRef(null); + const [dockListHeight, setDockListHeight] = useState(0); + + useEffect(() => { + const updateHeight = () => { + if (dockListContainerRef.current) { + setDockListHeight(dockListContainerRef.current.clientHeight); + } + }; + updateHeight(); + const observer = new ResizeObserver(updateHeight); + if (dockListContainerRef.current) { + observer.observe(dockListContainerRef.current); + } + window.addEventListener('resize', updateHeight); + return () => { + observer.disconnect(); + window.removeEventListener('resize', updateHeight); + }; + }, [isDockOpen]); + + const { t } = useTranslation(); + + const handleTileStyleChange = useCallback((style: MapStyle) => { + setTileStyle(style); + try { + localStorage.setItem(MAP_STYLE_STORAGE_KEY, style); + } catch (e) { + console.error('Failed to save map style to localStorage', e); + } + }, []); + + const handleToggleThumbnailCards = useCallback(() => { + setShowThumbnailCards((prev) => { + const next = !prev; + try { + localStorage.setItem(MAP_SHOW_THUMBNAILS_STORAGE_KEY, String(next)); + } catch (e) { + console.error('Failed to save show thumbnails setting to localStorage', e); + } + return next; + }); + }, []); + + const handleToggleDock = useCallback(() => { + setIsDockOpen((prev) => { + const next = !prev; + try { + localStorage.setItem(MAP_DOCK_OPEN_STORAGE_KEY, String(next)); + } catch (e) { + console.error('Failed to save dock open setting to localStorage', e); + } + return next; + }); + }, []); + + useEffect(() => { + const timer = setTimeout(() => { + mapRef.current?.invalidateSize(); + }, 220); + return () => clearTimeout(timer); + }, [isDockOpen, dockWidth]); + + const resize = useCallback((mouseMoveEvent: MouseEvent) => { + if (!isResizing.current) return; + const newWidth = window.innerWidth - mouseMoveEvent.clientX; + if (newWidth >= 160 && newWidth <= 550) { + dockWidthRef.current = newWidth; + setDockWidth(newWidth); + } + }, []); + + const stopResizing = useCallback(() => { + if (!isResizing.current) return; + isResizing.current = false; + setIsResizingState(false); + document.body.style.cursor = ''; + document.body.style.userSelect = ''; + document.removeEventListener('mousemove', resize); + document.removeEventListener('mouseup', stopResizing); + try { + localStorage.setItem(MAP_DOCK_WIDTH_STORAGE_KEY, String(dockWidthRef.current)); + } catch (e) { + console.error('Failed to save dock width to localStorage', e); + } + mapRef.current?.invalidateSize(); + }, [resize]); + + const startResizing = useCallback( + (mouseDownEvent: React.MouseEvent) => { + mouseDownEvent.preventDefault(); + isResizing.current = true; + setIsResizingState(true); + document.body.style.cursor = 'col-resize'; + document.body.style.userSelect = 'none'; + document.addEventListener('mousemove', resize); + document.addEventListener('mouseup', stopResizing); + }, + [resize, stopResizing], + ); + + useEffect(() => { + return () => { + document.body.style.cursor = ''; + document.body.style.userSelect = ''; + document.removeEventListener('mousemove', resize); + document.removeEventListener('mouseup', stopResizing); + }; + }, [resize, stopResizing]); + + useEffect(() => { + const handleWindowClick = () => setMapContextMenu(null); + window.addEventListener('click', handleWindowClick); + return () => window.removeEventListener('click', handleWindowClick); + }, []); + + const { + imageList, + activePath, + multiSelectedPaths, + currentFolderPath, + onImageClick, + onImageDoubleClick, + onContextMenu, + onRequestThumbnails, + } = props; + + const editorSelectedPath = useEditorStore((s) => s.selectedImage?.path); + const libraryActivePath = useLibraryStore((s) => s.libraryActivePath); + + const effectiveSelectedPath = useMemo(() => { + return ( + activePath || + libraryActivePath || + editorSelectedPath || + (multiSelectedPaths && multiSelectedPaths.length > 0 ? multiSelectedPaths[0] : null) || + null + ); + }, [activePath, libraryActivePath, editorSelectedPath, multiSelectedPaths]); + + const requestQueueRef = useRef>(new Set()); + const requestTimeoutRef = useRef(null); + + const queueThumbnailRequest = useCallback( + (path: string) => { + if (!onRequestThumbnails) return; + if (useProcessStore.getState().thumbnails[path]) return; + requestQueueRef.current.add(path); + if (!requestTimeoutRef.current) { + requestTimeoutRef.current = setTimeout(() => { + const paths = Array.from(requestQueueRef.current); + if (paths.length > 0) { + onRequestThumbnails(paths); + requestQueueRef.current.clear(); + } + requestTimeoutRef.current = null; + }, 50); + } + }, + [onRequestThumbnails], + ); + + useEffect(() => { + requestedExifRef.current.clear(); + setLocalExifMap({ ...useLibraryStore.getState().exifByPath }); + setSelectedDockPaths(new Set()); + setRepositioningPhotoPath(null); + setMapContextMenu(null); + undoStackRef.current = []; + setCanUndo(false); + }, [currentFolderPath]); + + useEffect(() => { + if (!imageList || imageList.length === 0) return; + setLocalExifMap((prev) => { + let changed = false; + const next = { ...prev }; + for (const img of imageList) { + const storeExif = exifByPath?.[img.path] || img.exif; + if (storeExif && next[img.path] !== storeExif) { + next[img.path] = storeExif; + changed = true; + } + } + return changed ? next : prev; + }); + }, [imageList, exifByPath]); + + useEffect(() => { + const unrequested = imageList.filter( + (img) => + !img.exif && !exifByPath?.[img.path] && !localExifMap[img.path] && !requestedExifRef.current.has(img.path), + ); + if (unrequested.length === 0) return; + + unrequested.forEach((img) => requestedExifRef.current.add(img.path)); + + let isCancelled = false; + const loadExif = async () => { + const chunkSize = 100; + + for (let i = 0; i < unrequested.length; i += chunkSize) { + if (isCancelled) break; + const chunk = unrequested.slice(i, i + chunkSize).map((img) => img.path); + try { + const chunkExif = await invoke>>(Invokes.ReadExifForPaths, { + paths: chunk, + }); + if (isCancelled) break; + + setLocalExifMap((prev) => ({ ...prev, ...chunkExif })); + useLibraryStore.getState().setLibrary((state) => ({ + exifByPath: { ...state.exifByPath, ...chunkExif }, + })); + } catch (err) { + console.error('Failed to read EXIF for MapView:', err); + } + } + }; + + loadExif(); + return () => { + isCancelled = true; + }; + }, [imageList.length, currentFolderPath, exifByPath]); + + const { geotaggedPhotos, unlocatedPhotos, totalPhotos, geotaggedCount } = useMemo(() => { + const items: MapPhotoItem[] = []; + const unlocated: ImageFile[] = []; + + for (const img of imageList) { + const exifOverride = localExifMap[img.path] || exifByPath?.[img.path]; + const gps: GeoLocation | null = getImageGps(img, exifOverride); + if (gps) { + const filename = img.path.split(/[\\/]/).pop() || ''; + const timestamp = getImageTimestamp(img, exifOverride); + const hasNative = exifOverride?.HasNativeGPS === 'true' || img.exif?.HasNativeGPS === 'true'; + const isModified = exifOverride?.IsGpsModified === 'true' || img.exif?.IsGpsModified === 'true'; + + items.push({ + id: img.path, + path: img.path, + filename, + lat: gps.lat, + lon: gps.lon, + timestamp, + isRaw: img.is_raw, + image: img, + hasNativeGps: hasNative, + isGpsModified: isModified, + }); + } else { + unlocated.push(img); + } + } + return { + geotaggedPhotos: items, + unlocatedPhotos: unlocated, + totalPhotos: imageList.length, + geotaggedCount: items.length, + }; + }, [imageList, localExifMap, exifByPath]); + + const applyGpsToPhotosInternal = useCallback( + async ( + paths: string[], + lat: number | null, + lon: number | null, + recordUndo: boolean = true, + customSuccessMsg?: string, + ) => { + if (paths.length === 0) return; + + if (recordUndo) { + const undoItems: GpsUndoItem[] = []; + for (const p of paths) { + const img = imageList.find((i) => i.path === p); + const currentExif = localExifMap[p] || exifByPath?.[p]; + const currentGps = getImageGps(img, currentExif); + const hadNative = currentExif?.HasNativeGPS === 'true' || img?.exif?.HasNativeGPS === 'true'; + undoItems.push({ + path: p, + previousLat: currentGps ? currentGps.lat : null, + previousLon: currentGps ? currentGps.lon : null, + hadNativeGps: hadNative, + }); + } + undoStackRef.current.push({ items: undoItems }); + setCanUndo(true); + } + + try { + await invoke(Invokes.SetGpsForPaths, { + paths, + latitude: lat, + longitude: lon, + }); + + const updates: Record = {}; + if (lat !== null && lon !== null) { + updates.GPSLatitude = toDmsString(lat); + updates.GPSLatitudeRef = lat >= 0 ? 'N' : 'S'; + updates.GPSLongitude = toDmsString(lon); + updates.GPSLongitudeRef = lon >= 0 ? 'E' : 'W'; + } + + setLocalExifMap((prev) => { + const next = { ...prev }; + for (const p of paths) { + if (lat !== null && lon !== null) { + const currentExif = next[p] || exifByPath?.[p] || {}; + const hasNative = + currentExif.HasNativeGPS === 'true' || + imageList.find((i) => i.path === p)?.exif?.HasNativeGPS === 'true'; + const modUpdate: Record = hasNative ? { IsGpsModified: 'true' } : {}; + next[p] = { ...currentExif, ...updates, ...modUpdate }; + } else if (next[p] || exifByPath?.[p]) { + const cleaned = { ...(next[p] || exifByPath?.[p] || {}) }; + delete cleaned.GPSLatitude; + delete cleaned.GPSLatitudeRef; + delete cleaned.GPSLongitude; + delete cleaned.GPSLongitudeRef; + delete cleaned.IsGpsModified; + next[p] = cleaned; + } + } + return next; + }); + + setSelectedDockPaths((prev) => { + const next = new Set(prev); + paths.forEach((p) => next.delete(p)); + return next; + }); + + const normalizePath = (p: string) => p.replace(/\\/g, '/').split('?vc=')[0]; + const pathsNormSet = new Set(paths.map(normalizePath)); + useLibraryStore.getState().setLibrary((state) => { + const nextExifByPath = { ...state.exifByPath }; + const nextImageList = state.imageList.map((img) => { + if (pathsNormSet.has(normalizePath(img.path))) { + const baseExif = nextExifByPath[img.path] || img.exif || localExifMap[img.path]; + if (lat !== null && lon !== null) { + const hasNative = baseExif?.HasNativeGPS === 'true'; + const modUpdate: Record = hasNative ? { IsGpsModified: 'true' } : {}; + const updatedExif: Record = { ...(baseExif || {}), ...updates, ...modUpdate }; + nextExifByPath[img.path] = updatedExif; + return { ...img, is_edited: true, exif: updatedExif }; + } else if (baseExif) { + const cleaned: Record = { ...baseExif }; + delete cleaned.GPSLatitude; + delete cleaned.GPSLatitudeRef; + delete cleaned.GPSLongitude; + delete cleaned.GPSLongitudeRef; + delete cleaned.IsGpsModified; + const hadNative = baseExif.HasNativeGPS === 'true'; + nextExifByPath[img.path] = cleaned; + return { ...img, is_edited: hadNative ? true : img.is_edited, exif: cleaned }; + } + } + return img; + }); + return { imageList: nextImageList, exifByPath: nextExifByPath }; + }); + + useEditorStore.getState().setEditor((state) => { + if (!state.selectedImage || !pathsNormSet.has(normalizePath(state.selectedImage.path))) { + return state; + } + if (lat !== null && lon !== null) { + const hasNative = + state.selectedImage.exif?.HasNativeGPS === 'true' || + localExifMap[state.selectedImage.path]?.HasNativeGPS === 'true' || + exifByPath?.[state.selectedImage.path]?.HasNativeGPS === 'true'; + const modUpdate: Record = hasNative ? { IsGpsModified: 'true' } : {}; + return { + selectedImage: { + ...state.selectedImage, + exif: { ...(state.selectedImage.exif || {}), ...updates, ...modUpdate }, + }, + }; + } else if (state.selectedImage.exif) { + const cleaned = { ...state.selectedImage.exif }; + delete cleaned.GPSLatitude; + delete cleaned.GPSLatitudeRef; + delete cleaned.GPSLongitude; + delete cleaned.GPSLongitudeRef; + delete cleaned.IsGpsModified; + return { + selectedImage: { + ...state.selectedImage, + exif: cleaned, + }, + }; + } + return state; + }); + + if (customSuccessMsg) { + toast.success(customSuccessMsg); + } else if (lat !== null) { + const hadPreviousGps = paths.some((p) => { + const img = imageList.find((i) => i.path === p); + return Boolean(getImageGps(img, localExifMap[p] || exifByPath?.[p])); + }); + + if (hadPreviousGps) { + toast.success( + t('library.map.repositionedSuccess', { + count: paths.length, + defaultValue: + paths.length === 1 + ? 'Photo repositioned successfully' + : `${paths.length} photos repositioned successfully`, + }), + ); + } else { + toast.success( + t('library.map.geotagSuccess', { + count: paths.length, + defaultValue: + paths.length === 1 ? 'Photo geotagged successfully' : `Successfully geotagged ${paths.length} photos`, + }), + ); + } + } else { + toast.info( + t('library.map.geotagRemoved', { + count: paths.length, + defaultValue: + paths.length === 1 ? 'GPS coordinates removed' : `GPS coordinates removed for ${paths.length} photos`, + }), + ); + } + } catch (err) { + console.error('Failed to set GPS coordinates', err); + toast.error( + t('library.map.errorSavingGps', { + defaultValue: `Error saving GPS coordinates: ${err}`, + err: String(err), + }), + ); + } + }, + [t, imageList, localExifMap, exifByPath], + ); + + const applyGpsToPhotos = useCallback( + (paths: string[], lat: number | null, lon: number | null) => { + return applyGpsToPhotosInternal(paths, lat, lon, true); + }, + [applyGpsToPhotosInternal], + ); + + const handleUndoGps = useCallback(async () => { + const action = undoStackRef.current.pop(); + setCanUndo(undoStackRef.current.length > 0); + if (!action || action.items.length === 0) return; + + const groups = new Map(); + for (const item of action.items) { + const key = `${item.previousLat}_${item.previousLon}`; + if (!groups.has(key)) { + groups.set(key, { lat: item.previousLat, lon: item.previousLon, paths: [] }); + } + groups.get(key)!.paths.push(item.path); + } + + for (const group of groups.values()) { + await applyGpsToPhotosInternal(group.paths, group.lat, group.lon, false); + } + + toast.info(t('library.map.undoSuccess', { defaultValue: 'GPS change undone' })); + }, [applyGpsToPhotosInternal, t]); + + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if ((e.ctrlKey || e.metaKey) && (e.key === 'z' || e.key === 'Z') && !e.shiftKey) { + if (undoStackRef.current.length > 0) { + e.preventDefault(); + e.stopPropagation(); + handleUndoGps(); + } + } + }; + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, [handleUndoGps]); + + const handleRevertGps = useCallback( + async (path: string) => { + const normalizePath = (p: string) => p.replace(/\\/g, '/').split('?vc=')[0]; + const targetNorm = normalizePath(path); + + const img = imageList.find((i) => normalizePath(i.path) === targetNorm); + const currentExif = localExifMap[path] || exifByPath?.[path]; + const currentGps = getImageGps(img || ({ path, is_raw: false } as ImageFile), currentExif); + if (currentGps) { + undoStackRef.current.push({ + items: [ + { + path, + previousLat: currentGps.lat, + previousLon: currentGps.lon, + hadNativeGps: currentExif?.HasNativeGPS === 'true' || img?.exif?.HasNativeGPS === 'true', + }, + ], + }); + setCanUndo(true); + } + + try { + const result = await invoke>(Invokes.RevertGpsForPaths, { + paths: [path], + }); + const coords = result[path] !== undefined ? result[path] : result[targetNorm]; + + if (coords) { + const [lat, lon] = coords; + const updates: Record = { + GPSLatitude: toDmsString(lat), + GPSLatitudeRef: lat >= 0 ? 'N' : 'S', + GPSLongitude: toDmsString(lon), + GPSLongitudeRef: lon >= 0 ? 'E' : 'W', + HasNativeGPS: 'true', + }; + + setLocalExifMap((prev) => { + const next = { ...prev }; + const current = next[path] + ? { ...next[path] } + : exifByPath?.[path] + ? { ...exifByPath[path] } + : img?.exif + ? { ...img.exif } + : {}; + delete current.IsGpsModified; + next[path] = { ...current, ...updates }; + if (targetNorm !== path) { + next[targetNorm] = { ...next[path] }; + } + return next; + }); + + useLibraryStore.getState().setLibrary((state) => { + const nextExifByPath = { ...state.exifByPath }; + const nextImageList = state.imageList.map((i) => { + if (normalizePath(i.path) === targetNorm) { + const currentExifMap = nextExifByPath[i.path] + ? { ...nextExifByPath[i.path] } + : i.exif + ? { ...i.exif } + : {}; + delete currentExifMap.IsGpsModified; + const updatedExif = { ...currentExifMap, ...updates }; + nextExifByPath[i.path] = updatedExif; + return { ...i, is_edited: false, exif: updatedExif }; + } + return i; + }); + return { imageList: nextImageList, exifByPath: nextExifByPath }; + }); + + useEditorStore.getState().setEditor((state) => { + if (!state.selectedImage || normalizePath(state.selectedImage.path) !== targetNorm) { + return state; + } + const currentExif = state.selectedImage.exif ? { ...state.selectedImage.exif } : {}; + delete currentExif.IsGpsModified; + return { + selectedImage: { + ...state.selectedImage, + is_edited: false, + exif: { ...currentExif, ...updates }, + }, + }; + }); + + toast.success( + t('library.map.revertSuccess', { + count: 1, + defaultValue: 'Restored original camera GPS coordinates for 1 photo', + }), + ); + } else { + setLocalExifMap((prev) => { + const next = { ...prev }; + const current = next[path] + ? { ...next[path] } + : exifByPath?.[path] + ? { ...exifByPath[path] } + : img?.exif + ? { ...img.exif } + : {}; + delete current.GPSLatitude; + delete current.GPSLatitudeRef; + delete current.GPSLongitude; + delete current.GPSLongitudeRef; + delete current.IsGpsModified; + current.HasNativeGPS = 'false'; + next[path] = current; + if (targetNorm !== path) { + next[targetNorm] = { ...current }; + } + return next; + }); + + useLibraryStore.getState().setLibrary((state) => { + const nextExifByPath = { ...state.exifByPath }; + const nextImageList = state.imageList.map((i) => { + if (normalizePath(i.path) === targetNorm) { + const cleaned = nextExifByPath[i.path] ? { ...nextExifByPath[i.path] } : i.exif ? { ...i.exif } : {}; + delete cleaned.GPSLatitude; + delete cleaned.GPSLatitudeRef; + delete cleaned.GPSLongitude; + delete cleaned.GPSLongitudeRef; + delete cleaned.IsGpsModified; + cleaned.HasNativeGPS = 'false'; + nextExifByPath[i.path] = cleaned; + return { ...i, is_edited: false, exif: cleaned }; + } + return i; + }); + return { imageList: nextImageList, exifByPath: nextExifByPath }; + }); + + useEditorStore.getState().setEditor((state) => { + if (!state.selectedImage || normalizePath(state.selectedImage.path) !== targetNorm) { + return state; + } + const cleaned = state.selectedImage.exif ? { ...state.selectedImage.exif } : {}; + delete cleaned.GPSLatitude; + delete cleaned.GPSLatitudeRef; + delete cleaned.GPSLongitude; + delete cleaned.GPSLongitudeRef; + delete cleaned.IsGpsModified; + cleaned.HasNativeGPS = 'false'; + return { selectedImage: { ...state.selectedImage, is_edited: false, exif: cleaned } }; + }); + + toast.info( + t('library.map.revertCleared', { + defaultValue: 'Cleared GPS coordinates (no original camera GPS)', + }), + ); + } + } catch (err) { + console.error('Failed to revert GPS coordinates', err); + toast.error( + t('library.map.errorSavingGps', { + defaultValue: `Error saving GPS coordinates: ${err}`, + err: String(err), + }), + ); + } + }, + [t, imageList, localExifMap], + ); + + const handleMovePhoto = useCallback( + async (draggedPaths: string[] | string, lat: number, lon: number) => { + const paths = Array.isArray(draggedPaths) ? draggedPaths : [draggedPaths]; + if (paths.length === 0) return; + await applyGpsToPhotos(paths, lat, lon); + }, + [applyGpsToPhotos], + ); + + const handleMapDrop = useCallback( + async (e: React.DragEvent) => { + e.preventDefault(); + setIsDraggingOverMap(false); + if (!mapRef.current) return; + + try { + const rawData = e.dataTransfer.getData('application/json') || e.dataTransfer.getData('text/plain'); + if (!rawData) return; + const parsed = JSON.parse(rawData); + const pathsToGeotag: string[] = Array.isArray(parsed?.paths) ? parsed.paths : []; + if (pathsToGeotag.length === 0) return; + + const container = mapRef.current.getContainer(); + const rect = container.getBoundingClientRect(); + const point = L.point(e.clientX - rect.left, e.clientY - rect.top); + const latLng = mapRef.current.containerPointToLatLng(point); + + const lat = latLng.lat; + let lon = ((((latLng.lng + 180) % 360) + 360) % 360) - 180; + + await applyGpsToPhotos(pathsToGeotag, lat, lon); + + mapRef.current.panTo([lat, lon], { animate: true, duration: 0.4 }); + + if (pathsToGeotag.length > 0) { + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: pathsToGeotag, + libraryActivePath: pathsToGeotag[0], + selectionAnchorPath: pathsToGeotag[0], + }); + const photoObj = imageList.find((p) => p.path === pathsToGeotag[0]); + if (photoObj) { + useEditorStore.getState().setEditor({ selectedImage: photoObj as any }); + } + } + } catch (err) { + console.error('Failed to handle drop on map', err); + } + }, + [applyGpsToPhotos, imageList], + ); + + const handleStartReposition = useCallback((path: string) => { + setSelectedDockPaths(new Set()); + setRepositioningPhotoPath(path); + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [path], + libraryActivePath: path, + selectionAnchorPath: path, + }); + }, []); + + const handleRepositionSelect = useCallback( + async (lat: number, lon: number) => { + if (!repositioningPhotoPath) return; + const targetPath = repositioningPhotoPath; + setRepositioningPhotoPath(null); + await applyGpsToPhotos([targetPath], lat, lon); + toast.success( + t('library.map.repositionedSuccess', { + defaultValue: 'Photo repositioned successfully', + }), + ); + }, + [repositioningPhotoPath, applyGpsToPhotos, t], + ); + + const isInternalDockSelectionRef = useRef(false); + const dockSelectionAnchorRef = useRef(null); + + const handleMapPhotoSelect = useCallback( + (path: string, e?: MouseEvent | React.MouseEvent) => { + setSelectedDockPaths(new Set()); + dockSelectionAnchorRef.current = null; + setRepositioningPhotoPath(null); + + const photoObj = imageList.find((p) => p.path === path); + if (photoObj) { + useEditorStore.getState().setEditor({ selectedImage: photoObj as any }); + } + + if (e && onImageClick) { + onImageClick(path, e as any); + } else { + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [path], + libraryActivePath: path, + selectionAnchorPath: path, + }); + } + }, + [imageList, onImageClick], + ); + + const handleMapRightClick = useCallback( + (lat: number, lon: number, screenX: number, screenY: number) => { + const targetPaths = + selectedDockPaths.size > 0 + ? Array.from(selectedDockPaths) + : effectiveSelectedPath + ? [effectiveSelectedPath] + : multiSelectedPaths.length > 0 + ? multiSelectedPaths + : []; + + if (targetPaths.length > 0) { + setMapContextMenu({ + x: screenX, + y: screenY, + lat, + lon, + targetPaths, + }); + } + }, + [selectedDockPaths, effectiveSelectedPath, multiSelectedPaths], + ); + + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + setIsDraggingOverMap(false); + setMapContextMenu(null); + setRepositioningPhotoPath(null); + if (selectedDockPaths.size > 0) { + isInternalDockSelectionRef.current = true; + setSelectedDockPaths(new Set()); + dockSelectionAnchorRef.current = null; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [], + libraryActivePath: null, + selectionAnchorPath: null, + }); + useEditorStore.getState().setEditor({ selectedImage: null }); + } + return; + } + + const isCtrlOrCmd = e.ctrlKey || e.metaKey; + if (isCtrlOrCmd && (e.key === 'a' || e.key === 'A')) { + const target = e.target as HTMLElement | null; + const isInputField = + target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable); + + if (!isInputField && isDockOpen && unlocatedPhotos.length > 0) { + e.preventDefault(); + e.stopPropagation(); + isInternalDockSelectionRef.current = true; + const allPaths = unlocatedPhotos.map((p) => p.path); + const allSelected = allPaths.every((path) => selectedDockPaths.has(path)); + if (allSelected) { + setSelectedDockPaths(new Set()); + dockSelectionAnchorRef.current = null; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [], + libraryActivePath: null, + selectionAnchorPath: null, + }); + useEditorStore.getState().setEditor({ selectedImage: null }); + } else { + setSelectedDockPaths(new Set(allPaths)); + dockSelectionAnchorRef.current = allPaths[0] || null; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: allPaths, + libraryActivePath: allPaths[0] || null, + selectionAnchorPath: allPaths[0] || null, + }); + const photo = imageList.find((p) => p.path === allPaths[0]); + if (photo) { + useEditorStore.getState().setEditor({ selectedImage: photo as any }); + } + } + } + } + }; + window.addEventListener('keydown', handleKeyDown, true); + return () => window.removeEventListener('keydown', handleKeyDown, true); + }, [isDockOpen, unlocatedPhotos, imageList, selectedDockPaths]); + + const handlePhotoSelect = useCallback( + (path: string, e: React.MouseEvent) => { + const isCtrl = e.ctrlKey || e.metaKey; + const isShift = e.shiftKey; + + isInternalDockSelectionRef.current = true; + + if (isShift) { + const anchor = + dockSelectionAnchorRef.current || + (effectiveSelectedPath && unlocatedPhotos.some((p) => p.path === effectiveSelectedPath) + ? effectiveSelectedPath + : null) || + path; + const anchorIdx = unlocatedPhotos.findIndex((p) => p.path === anchor); + const currentIdx = unlocatedPhotos.findIndex((p) => p.path === path); + + if (anchorIdx !== -1 && currentIdx !== -1) { + const start = Math.min(anchorIdx, currentIdx); + const end = Math.max(anchorIdx, currentIdx); + const rangePaths = unlocatedPhotos.slice(start, end + 1).map((p) => p.path); + const base = isCtrl ? Array.from(selectedDockPaths) : []; + const newSelection = Array.from(new Set([...base, ...rangePaths])); + + setSelectedDockPaths(new Set(newSelection)); + dockSelectionAnchorRef.current = anchor; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: newSelection, + libraryActivePath: path, + selectionAnchorPath: anchor, + }); + const photo = imageList.find((p) => p.path === path); + if (photo) { + useEditorStore.getState().setEditor({ selectedImage: photo as any }); + } + } + } else if (isCtrl) { + dockSelectionAnchorRef.current = path; + setSelectedDockPaths((prev) => { + const base = new Set(prev); + if ( + base.size === 0 && + effectiveSelectedPath && + unlocatedPhotos.some((p) => p.path === effectiveSelectedPath) + ) { + base.add(effectiveSelectedPath); + } + if (base.has(path)) { + base.delete(path); + } else { + base.add(path); + } + const nextArr = Array.from(base); + const newActive = base.has(path) ? path : nextArr[nextArr.length - 1] || null; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: nextArr, + libraryActivePath: newActive, + selectionAnchorPath: path, + }); + const photo = newActive ? imageList.find((p) => p.path === newActive) : null; + useEditorStore.getState().setEditor({ selectedImage: (photo as any) || null }); + return base; + }); + } else { + dockSelectionAnchorRef.current = path; + setSelectedDockPaths(new Set([path])); + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: [path], + libraryActivePath: path, + selectionAnchorPath: path, + }); + const photo = imageList.find((p) => p.path === path); + if (photo) { + useEditorStore.getState().setEditor({ selectedImage: photo as any }); + } + } + }, + [effectiveSelectedPath, imageList, unlocatedPhotos, selectedDockPaths], + ); + + const handlePhotoDragStart = useCallback( + (photo: ImageFile, e: React.DragEvent) => { + isInternalDockSelectionRef.current = true; + const pathsToDrag = + selectedDockPaths.has(photo.path) && selectedDockPaths.size > 1 ? Array.from(selectedDockPaths) : [photo.path]; + + if (!selectedDockPaths.has(photo.path)) { + setSelectedDockPaths(new Set(pathsToDrag)); + dockSelectionAnchorRef.current = photo.path; + } + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: pathsToDrag, + libraryActivePath: photo.path, + selectionAnchorPath: photo.path, + }); + useEditorStore.getState().setEditor({ selectedImage: photo as any }); + + e.dataTransfer.setData('application/json', JSON.stringify({ paths: pathsToDrag })); + e.dataTransfer.setData('text/plain', JSON.stringify({ paths: pathsToDrag })); + e.dataTransfer.effectAllowed = 'copyMove'; + + const ghost = document.createElement('div'); + ghost.style.position = 'fixed'; + ghost.style.left = '0'; + ghost.style.top = '0'; + ghost.style.zIndex = '-9999'; + ghost.style.opacity = '0.01'; + ghost.style.pointerEvents = 'none'; + ghost.style.display = 'flex'; + ghost.style.alignItems = 'center'; + ghost.style.gap = '8px'; + ghost.style.padding = '6px 12px 6px 6px'; + ghost.style.background = '#0f172a'; + ghost.style.color = '#ffffff'; + ghost.style.borderRadius = '10px'; + ghost.style.border = '1.5px solid #0284c7'; + ghost.style.boxShadow = '0 10px 25px rgba(0,0,0,0.5)'; + + const procStore = useProcessStore.getState(); + const thumb = procStore.mediumThumbnails[photo.path] || procStore.thumbnails[photo.path]; + if (thumb) { + const img = document.createElement('img'); + img.src = thumb; + img.style.width = '48px'; + img.style.height = '48px'; + img.style.objectFit = 'cover'; + img.style.borderRadius = '6px'; + img.style.border = '1px solid rgba(255,255,255,0.2)'; + ghost.appendChild(img); + } + + const textDiv = document.createElement('div'); + textDiv.style.display = 'flex'; + textDiv.style.flexDirection = 'column'; + textDiv.style.maxWidth = '180px'; + + const titleSpan = document.createElement('span'); + titleSpan.style.fontSize = '12px'; + titleSpan.style.fontWeight = '600'; + titleSpan.style.overflow = 'hidden'; + titleSpan.style.textOverflow = 'ellipsis'; + titleSpan.style.whiteSpace = 'nowrap'; + titleSpan.innerText = + pathsToDrag.length > 1 + ? `📍 ${pathsToDrag.length} ${t('library.map.photosCount', { defaultValue: 'photos' })}` + : `📍 ${photo.path.split(/[\\/]/).pop()}`; + textDiv.appendChild(titleSpan); + + ghost.appendChild(textDiv); + document.body.appendChild(ghost); + + ghost.getBoundingClientRect(); + + e.dataTransfer.setDragImage(ghost, 28, 28); + setTimeout(() => { + if (document.body.contains(ghost)) { + document.body.removeChild(ghost); + } + }, 0); + }, + [selectedDockPaths, t, imageList], + ); + + const handlePhotoDragEnd = useCallback(() => { + setIsDraggingOverMap(false); + }, []); + + const activeLayer = MAP_LAYERS[tileStyle] || MAP_LAYERS.dark; + + const handleFitBounds = useCallback(() => { + if (!mapRef.current || geotaggedPhotos.length === 0) return; + try { + const latLngs = geotaggedPhotos.map((p) => [p.lat, p.lon] as [number, number]); + const bounds = L.latLngBounds(latLngs); + if (bounds.isValid()) { + mapRef.current.fitBounds(bounds, { padding: [50, 50], maxZoom: 16 }); + } + } catch (e) { + console.error('Failed to fit bounds', e); + } + }, [geotaggedPhotos]); + + const initialSelectedPhoto = useMemo(() => { + if (!effectiveSelectedPath) return null; + return geotaggedPhotos.find((p) => p.path === effectiveSelectedPath) || null; + }, [effectiveSelectedPath, geotaggedPhotos]); + + const initialCenter: [number, number] = useMemo(() => { + if (initialSelectedPhoto) { + return [initialSelectedPhoto.lat, initialSelectedPhoto.lon]; + } + if (geotaggedPhotos.length > 0) { + return [geotaggedPhotos[0].lat, geotaggedPhotos[0].lon]; + } + return [20, 0]; + }, [initialSelectedPhoto, geotaggedPhotos]); + + const initialZoom: number = initialSelectedPhoto ? 16 : geotaggedPhotos.length > 0 ? 5 : 2; + + const prevEffectiveSelectedPathRef = useRef(null); + useEffect(() => { + if (isInternalDockSelectionRef.current) { + isInternalDockSelectionRef.current = false; + prevEffectiveSelectedPathRef.current = effectiveSelectedPath; + return; + } + if (!effectiveSelectedPath) return; + if (prevEffectiveSelectedPathRef.current === effectiveSelectedPath) return; + prevEffectiveSelectedPathRef.current = effectiveSelectedPath; + + const isUnlocated = unlocatedPhotos.some((p) => p.path === effectiveSelectedPath); + if (isUnlocated) { + setIsDockOpen(true); + setSelectedDockPaths((prev) => { + if (prev.has(effectiveSelectedPath)) { + return prev; + } + return new Set([effectiveSelectedPath]); + }); + if (!dockSelectionAnchorRef.current) { + dockSelectionAnchorRef.current = effectiveSelectedPath; + } + } + }, [effectiveSelectedPath, unlocatedPhotos]); + + const dockRowProps = useMemo( + () => ({ + unlocatedPhotos, + selectedDockPaths, + effectiveSelectedPath, + localExifMap, + dockWidth, + handlePhotoSelect, + onImageDoubleClick, + onContextMenu, + handlePhotoDragStart, + handlePhotoDragEnd, + queueThumbnailRequest, + }), + [ + unlocatedPhotos, + selectedDockPaths, + effectiveSelectedPath, + localExifMap, + dockWidth, + handlePhotoSelect, + onImageDoubleClick, + onContextMenu, + handlePhotoDragStart, + handlePhotoDragEnd, + queueThumbnailRequest, + ], + ); + + return ( +
+ {isResizingState &&
} +
{ + e.preventDefault(); + e.dataTransfer.dropEffect = 'copy'; + if (!isDraggingOverMap) setIsDraggingOverMap(true); + }} + onDragLeave={(e) => { + const related = e.relatedTarget as Node | null; + if (!related || !e.currentTarget.contains(related)) { + setIsDraggingOverMap(false); + } + }} + onDrop={handleMapDrop} + > +
+ + + {t('library.map.badge', { + count: geotaggedCount, + total: totalPhotos, + defaultValue: `${geotaggedCount} / ${totalPhotos} with GPS coordinates`, + })} + +
+ + {isDraggingOverMap && ( +
+
+ + + {t('library.map.dropToGeotag', { defaultValue: 'Drop onto map to geotag' })} + +
+
+ )} + + {repositioningPhotoPath && ( +
+ +
+ + {t('library.map.repositioningModeTitle', { + defaultValue: 'Click on the map to place photo', + })} + + + {repositioningPhotoPath.split(/[\\/]/).pop()} •{' '} + {t('library.map.pressEscToCancel', { defaultValue: 'Press ESC to cancel' })} + +
+ +
+ )} + + {geotaggedCount === 0 && totalPhotos > 0 && !isDockOpen && ( +
+
+ +

+ {t('library.map.noGpsTitle', { defaultValue: 'No GPS coordinates' })} +

+

+ {t('library.map.noGpsDesc', { + defaultValue: 'None of the photos in this folder contain geographic information in EXIF metadata.', + })} +

+ +
+
+ )} + + + + + + + + +
+ +
{ + e.preventDefault(); + e.dataTransfer.dropEffect = 'none'; + if (isDraggingOverMap) setIsDraggingOverMap(false); + }} + onDragEnter={(e) => { + e.preventDefault(); + if (isDraggingOverMap) setIsDraggingOverMap(false); + }} + onDrop={(e) => { + e.preventDefault(); + e.stopPropagation(); + setIsDraggingOverMap(false); + const rawData = e.dataTransfer.getData('application/json') || e.dataTransfer.getData('text/plain'); + if (rawData) { + try { + const parsed = JSON.parse(rawData); + const paths: string[] = Array.isArray(parsed?.paths) ? parsed.paths : []; + if (paths.length > 0) { + isInternalDockSelectionRef.current = true; + setSelectedDockPaths(new Set(paths)); + dockSelectionAnchorRef.current = paths[0]; + useLibraryStore.getState().setLibrary({ + multiSelectedPaths: paths, + libraryActivePath: paths[0], + selectionAnchorPath: paths[0], + }); + const photo = imageList.find((p) => p.path === paths[0]); + if (photo) { + useEditorStore.getState().setEditor({ selectedImage: photo as any }); + } + } + } catch (err) { + console.error('Failed to parse dropped data on dock', err); + } + } + }} + className={`relative shrink-0 border-l border-surface/50 bg-bg-secondary/70 backdrop-blur-md flex flex-col ${ + isResizingState ? '' : 'transition-[width] duration-200 ease-out' + } z-[1000] ${isDockOpen ? '' : 'overflow-hidden border-none'}`} + > + {isDockOpen && ( + <> +
+ +
+
+
+ + + {t('library.map.unlocatedDockTitle', { defaultValue: 'Unlocated' })} + + + {unlocatedPhotos.length} + +
+ +
+ +
+ + {t('library.map.unlocatedDockSubtitle', { + defaultValue: 'Drag onto map to geotag', + })} + + {unlocatedPhotos.length > 1 && ( + + )} +
+
+ +
+ {unlocatedPhotos.length === 0 ? ( +
+ +

+ {t('library.map.allGeotagged', { + defaultValue: 'All photos have GPS coordinates', + })} +

+
+ ) : dockListHeight > 0 ? ( + + ) : null} +
+ + )} +
+ + {mapContextMenu && ( +
e.stopPropagation()} + > +
+ + + {mapContextMenu.lat.toFixed(5)}°, {mapContextMenu.lon.toFixed(5)}° + +
+ {(() => { + const areTargetsGeotagged = mapContextMenu.targetPaths.some((p) => { + const img = imageList.find((i) => i.path === p); + return Boolean(getImageGps(img, localExifMap[p])); + }); + + return ( + + ); + })()} +
+ )} +
+ ); +} diff --git a/src/components/panel/right/ControlsPanel.tsx b/src/components/panel/right/ControlsPanel.tsx index 76ddb101ef..e31f9edc7c 100644 --- a/src/components/panel/right/ControlsPanel.tsx +++ b/src/components/panel/right/ControlsPanel.tsx @@ -46,7 +46,13 @@ export default function Controls() { const { showContextMenu } = useContextMenu(); const { isResizingWaveform, onToggleWaveform, setActiveWaveformChannel, handleWaveformResize } = useWaveformControls(); - const { setAdjustments, handleAutoAdjustments, handleLutSelect, setLutPreviewOverride } = useEditorActions(); + const { + setAdjustments, + handleAutoAdjustments, + handleLutSelect, + setLutPreviewOverride, + handleResetAdjustments: handleResetAdjustmentsAction, + } = useEditorActions(); const { appSettings, theme } = useSettingsStore( useShallow((state) => ({ @@ -125,20 +131,24 @@ export default function Controls() { ); const handleResetAdjustments = async () => { - const defaults = await getOpenImageDefaults(); - setAdjustments( - (prev: Adjustments) => ({ - ...prev, - ...Object.keys(ADJUSTMENT_SECTIONS) - .flatMap((s) => ADJUSTMENT_SECTIONS[s]) - .reduce((acc: any, key: string) => { - acc[key] = defaults[key as keyof Adjustments]; - return acc; - }, {}), - activeTools: { ...defaults.activeTools }, - }), - t('contextMenus.editor.resetAdjustments'), - ); + if (selectedImage?.path) { + handleResetAdjustmentsAction([selectedImage.path]); + } else { + const defaults = await getOpenImageDefaults(); + setAdjustments( + (prev: Adjustments) => ({ + ...prev, + ...Object.keys(ADJUSTMENT_SECTIONS) + .flatMap((s) => ADJUSTMENT_SECTIONS[s]) + .reduce((acc: any, key: string) => { + acc[key] = defaults[key as keyof Adjustments]; + return acc; + }, {}), + activeTools: { ...defaults.activeTools }, + }), + t('contextMenus.editor.resetAdjustments'), + ); + } }; const handleAutoAdjustContextMenu = (event: React.MouseEvent) => { diff --git a/src/hooks/useEditorActions.ts b/src/hooks/useEditorActions.ts index 7876177f40..8e7328f3df 100644 --- a/src/hooks/useEditorActions.ts +++ b/src/hooks/useEditorActions.ts @@ -30,6 +30,7 @@ import { Invokes } from '../types/invokes'; import { Option, Panel } from '../types/ui'; import { SelectedImage } from '../types/editor'; import { globalImageCache } from '../utils/ImageLRUCache'; +import { toDmsString } from '../utils/gpsUtils'; import { getDevicePixelRatio } from '../utils/displayScale'; export { debouncedSetHistory }; @@ -313,8 +314,8 @@ export function useEditorActions() { const resetTarget = (path: string) => toNeutral ? Promise.resolve(structuredClone(INITIAL_ADJUSTMENTS)) : getDefaultAdjustmentsFor(path); - invoke(Invokes.ResetAdjustmentsForPaths, { paths: pathsToReset, toNeutral }) - .then(async () => { + invoke>(Invokes.ResetAdjustmentsForPaths, { paths: pathsToReset, toNeutral }) + .then(async (revertedGpsMap) => { const { libraryActivePath, setLibrary } = useLibraryStore.getState(); const { selectedImage, resetHistory } = useEditorStore.getState(); if (libraryActivePath && pathsToReset.includes(libraryActivePath)) @@ -327,6 +328,105 @@ export function useEditorActions() { resetHistory(resetData); setEditor({ adjustments: resetData }); } + + if (revertedGpsMap && typeof revertedGpsMap === 'object') { + const normalizePath = (p: string) => p.replace(/\\/g, '/').split('?vc=')[0]; + const targetsSet = new Set(pathsToReset.map(normalizePath)); + + setLibrary((state) => { + const nextExifByPath = { ...state.exifByPath }; + const nextImageList = state.imageList.map((img) => { + const norm = normalizePath(img.path); + if (!targetsSet.has(norm)) return img; + + const coords = + revertedGpsMap[img.path] !== undefined ? revertedGpsMap[img.path] : revertedGpsMap[norm]; + const currentExif = { ...(state.exifByPath[img.path] || img.exif || {}) }; + delete currentExif.IsGpsModified; + + if (coords) { + const [lat, lon] = coords; + const updatedExif: Record = { + ...currentExif, + GPSLatitude: toDmsString(lat), + GPSLatitudeRef: lat >= 0 ? 'N' : 'S', + GPSLongitude: toDmsString(lon), + GPSLongitudeRef: lon >= 0 ? 'E' : 'W', + HasNativeGPS: 'true', + }; + nextExifByPath[img.path] = updatedExif; + return { + ...img, + is_edited: false, + exif: updatedExif, + }; + } else { + delete currentExif.GPSLatitude; + delete currentExif.GPSLatitudeRef; + delete currentExif.GPSLongitude; + delete currentExif.GPSLongitudeRef; + delete currentExif.OriginalGPSLatitude; + delete currentExif.OriginalGPSLatitudeRef; + delete currentExif.OriginalGPSLongitude; + delete currentExif.OriginalGPSLongitudeRef; + currentExif.HasNativeGPS = 'false'; + nextExifByPath[img.path] = currentExif; + return { + ...img, + is_edited: false, + exif: currentExif, + }; + } + }); + return { imageList: nextImageList, exifByPath: nextExifByPath }; + }); + + useEditorStore.getState().setEditor((state) => { + if (!state.selectedImage) return state; + const norm = normalizePath(state.selectedImage.path); + if (!targetsSet.has(norm)) return state; + + const coords = + revertedGpsMap[state.selectedImage.path] !== undefined + ? revertedGpsMap[state.selectedImage.path] + : revertedGpsMap[norm]; + const currentExif = state.selectedImage.exif ? { ...state.selectedImage.exif } : {}; + delete currentExif.IsGpsModified; + + if (coords) { + const [lat, lon] = coords; + return { + selectedImage: { + ...state.selectedImage, + exif: { + ...currentExif, + GPSLatitude: toDmsString(lat), + GPSLatitudeRef: lat >= 0 ? 'N' : 'S', + GPSLongitude: toDmsString(lon), + GPSLongitudeRef: lon >= 0 ? 'E' : 'W', + HasNativeGPS: 'true', + }, + }, + }; + } else { + delete currentExif.GPSLatitude; + delete currentExif.GPSLatitudeRef; + delete currentExif.GPSLongitude; + delete currentExif.GPSLongitudeRef; + delete currentExif.OriginalGPSLatitude; + delete currentExif.OriginalGPSLatitudeRef; + delete currentExif.OriginalGPSLongitude; + delete currentExif.OriginalGPSLongitudeRef; + currentExif.HasNativeGPS = 'false'; + return { + selectedImage: { + ...state.selectedImage, + exif: currentExif, + }, + }; + } + }); + } }) .catch((err) => toast.error(`Failed to reset adjustments: ${err}`)); }, diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index d122399dde..b6fe46a355 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1491,7 +1491,50 @@ "viewMode": { "culling": "Culling View", "grid": "Grid View", - "list": "List View" + "list": "List View", + "map": "Map View" + }, + "map": { + "badge": "{{count}} / {{total}} with GPS coordinates", + "noGpsTitle": "No GPS coordinates", + "noGpsDesc": "None of the photos in this folder contain geographic information in EXIF metadata.", + "openDockToGeotag": "Open panel to place them", + "fitBounds": "Fit all photos in view", + "cardsActive": "Photo thumbnail cards active (click for compact pins)", + "pinsActive": "Compact pins active (click for photo cards)", + "styleSelector": "Select map style", + "mapStyle": "Map Style", + "doubleClickHint": "Double click to open in Adjustments mode", + "unlocatedDockTitle": "Unlocated", + "unlocatedDockSubtitle": "Drag onto map to geotag", + "allGeotagged": "All photos have GPS coordinates", + "toggleDock": "Toggle unlocated photos panel", + "dropToGeotag": "Drop onto map to geotag", + "geotagSelectedHere": "Place {{count}} photo(s) here", + "repositionSelectedHere": "Reposition {{count}} photo(s) here", + "removeGps": "Remove GPS", + "revertGps": "Revert to camera GPS", + "revertGpsData": "Revert GPS data", + "revertCleared": "Cleared GPS coordinates (no original camera GPS)", + "undoSuccess": "GPS change undone", + "undoTooltip": "Undo GPS change (Ctrl+Z)", + "undoDisabled": "No GPS changes to undo", + "revertSuccess": "Restored original camera GPS coordinates for {{count}} photo(s)", + "dragToReposition": "Drag image to reposition", + "dragToMap": "Drag onto map", + "resizeDock": "Drag to resize", + "closeDock": "Close panel", + "selectAll": "Select all", + "deselectAll": "Deselect all", + "photosCount": "photos", + "errorSavingGps": "Error saving GPS coordinates: {{err}}", + "geotagSuccess": "Successfully geotagged {{count}} photo(s)", + "repositionedSuccess": "Successfully repositioned {{count}} photo(s)", + "geotagRemoved": "Removed GPS coordinates for {{count}} photo(s)", + "repositionPhotoBtn": "Reposition", + "clickToPlacePhoto": "Click on the map to place this photo (ESC to cancel)", + "repositioningModeTitle": "Click on the map to place photo", + "pressEscToCancel": "Press ESC to cancel" } }, "masks": { diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index a14d5f8bfb..d15f71ab12 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1524,7 +1524,50 @@ "viewMode": { "culling": "Vista selezione", "grid": "Vista griglia", - "list": "Vista elenco" + "list": "Vista elenco", + "map": "Vista mappa" + }, + "map": { + "badge": "{{count}} / {{total}} con coordinate GPS", + "noGpsTitle": "Nessuna coordinata GPS", + "noGpsDesc": "Nessuna delle foto in questa cartella contiene informazioni geografiche nei metadati EXIF.", + "openDockToGeotag": "Apri pannello per posizionarle", + "fitBounds": "Inquadra tutte le foto", + "cardsActive": "Miniature fotografiche attive (clicca per segnaposto compatti)", + "pinsActive": "Segnaposto compatti (clicca per miniature)", + "styleSelector": "Seleziona stile mappa", + "mapStyle": "Stile Mappa", + "doubleClickHint": "Doppio click per aprire in modalità Adjustments", + "unlocatedDockTitle": "Senza coordinate", + "unlocatedDockSubtitle": "Trascina sulla mappa per posizionare", + "allGeotagged": "Tutte le foto sono geolocalizzate", + "toggleDock": "Pannello foto non geolocalizzate", + "dropToGeotag": "Rilascia sulla mappa per posizionare", + "geotagSelectedHere": "Posiziona {{count}} foto qui", + "repositionSelectedHere": "Riposiziona {{count}} foto qui", + "removeGps": "Rimuovi GPS", + "revertGps": "Ripristina GPS fotocamera", + "revertGpsData": "Ripristina dati GPS", + "revertCleared": "Coordinate GPS rimosse (nessun GPS originale)", + "undoSuccess": "Modifica GPS annullata", + "undoTooltip": "Annulla modifica GPS (Ctrl+Z)", + "undoDisabled": "Nessuna modifica GPS da annullare", + "revertSuccess": "Ripristinate coordinate originali della fotocamera per {{count}} foto", + "dragToReposition": "Trascina immagine per riposizionare", + "dragToMap": "Trascina sulla mappa", + "resizeDock": "Trascina per ridimensionare", + "closeDock": "Chiudi pannello", + "selectAll": "Seleziona tutte", + "deselectAll": "Deseleziona", + "photosCount": "foto", + "errorSavingGps": "Errore nel salvataggio coordinate: {{err}}", + "geotagSuccess": "Posizionate {{count}} foto con successo", + "repositionedSuccess": "Riposizionate {{count}} foto con successo", + "geotagRemoved": "Coordinate GPS rimosse per {{count}} foto", + "repositionPhotoBtn": "Riposiziona", + "clickToPlacePhoto": "Fai click sulla mappa per riposizionare questa foto (ESC per annullare)", + "repositioningModeTitle": "Fai clic sulla mappa per posizionare la foto", + "pressEscToCancel": "Premi ESC per annullare" } }, "masks": { diff --git a/src/styles.css b/src/styles.css index 0c03d04cd9..f413c7b599 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1,5 +1,8 @@ @import 'tailwindcss' source('.'); @source '../index.html'; +@import 'leaflet/dist/leaflet.css'; +@import 'leaflet.markercluster/dist/MarkerCluster.css'; +@import 'leaflet.markercluster/dist/MarkerCluster.Default.css'; @theme { --color-bg-primary: var(--app-bg-primary); @@ -483,3 +486,183 @@ height: 24px; } } + +/* ======================================================== + RapidMAP / Leaflet Map Photographic Dark Theme Styling + ======================================================== */ + +.leaflet-container { + width: 100%; + height: 100%; + background: var(--color-bg-primary, #090d16) !important; + font-family: inherit; +} + +/* Dark mode filter for standard OSM tiles - zero watermark, high contrast */ +.dark-map-tiles .leaflet-tile { + filter: invert(100%) hue-rotate(180deg) brightness(85%) contrast(100%); +} + +/* Custom Photo Pin and Thumbnail Markers */ +.custom-photo-pin, +.photo-thumbnail-pin, +.photo-thumbnail-pin-loading, +.photo-cluster-thumbnail-pin, +.photo-cluster-thumbnail-pin-loading, +.leaflet-marker-draggable { + background: transparent !important; + border: none !important; + cursor: grab !important; +} + +.custom-photo-pin:active, +.photo-thumbnail-pin:active, +.photo-thumbnail-pin-loading:active, +.photo-cluster-thumbnail-pin:active, +.photo-cluster-thumbnail-pin-loading:active, +.leaflet-marker-dragging, +.leaflet-marker-dragging * { + cursor: grabbing !important; +} + +.custom-photo-pin img, +.photo-thumbnail-pin img, +.photo-thumbnail-pin-loading img, +.photo-cluster-thumbnail-pin img, +.photo-cluster-thumbnail-pin-loading img { + pointer-events: none !important; + user-select: none !important; + -webkit-user-drag: none !important; +} + +.custom-photo-pin svg, +.photo-thumbnail-pin svg, +.photo-thumbnail-pin-loading svg, +.photo-cluster-thumbnail-pin svg, +.photo-cluster-thumbnail-pin-loading svg { + pointer-events: none !important; + user-select: none !important; +} + +.photo-drag-avatar { + pointer-events: none !important; + user-select: none !important; + z-index: 999999 !important; +} + +.photo-drag-avatar img { + pointer-events: none !important; + user-select: none !important; + -webkit-user-drag: none !important; +} + +.photo-thumbnail-pin:hover, +.photo-thumbnail-pin-loading:hover, +.photo-cluster-thumbnail-pin:hover, +.photo-cluster-thumbnail-pin-loading:hover { + transform: scale(1.06); +} + +.elevated-map-marker { + z-index: 100000 !important; +} + +@keyframes spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +/* Map canvas default pointer/arrow cursor instead of grab hand */ +.leaflet-container, +.leaflet-grab, +.leaflet-container.leaflet-grab { + cursor: default !important; +} + +.leaflet-drag-target, +.leaflet-container.leaflet-dragging, +.leaflet-container.leaflet-dragging * { + cursor: grabbing !important; +} + +/* Custom dark popup styling matched with RapidRAW theme */ +.leaflet-popup-content-wrapper { + background: var(--color-surface, #111827) !important; + color: var(--color-text-primary, #f3f4f6) !important; + border: 1px solid var(--color-border-color, #374151) !important; + border-radius: 10px !important; + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.6), 0 8px 10px -6px rgba(0, 0, 0, 0.6) !important; + padding: 4px !important; +} + +.leaflet-popup-tip { + background: var(--color-surface, #111827) !important; + border: 1px solid var(--color-border-color, #374151) !important; +} + +.leaflet-popup-content { + margin: 8px 12px !important; + line-height: 1.4 !important; +} + +.leaflet-popup-close-button { + color: var(--color-text-secondary, #9ca3af) !important; + padding: 6px 8px !important; +} + +.leaflet-popup-close-button:hover { + color: var(--color-text-primary, #f3f4f6) !important; +} + +/* Custom Dark Marker Cluster Styling */ +.marker-cluster-small, +.marker-cluster-medium, +.marker-cluster-large { + background-color: rgba(14, 165, 233, 0.25) !important; + border: 1px solid rgba(56, 189, 248, 0.5) !important; + box-shadow: 0 0 15px rgba(14, 165, 233, 0.4) !important; + border-radius: 9999px; + transition: transform 0.15s ease-in-out; +} + +.marker-cluster-small div, +.marker-cluster-medium div, +.marker-cluster-large div { + background-color: var(--color-accent, #0284c7) !important; + color: #ffffff !important; + font-weight: 700 !important; + font-size: 12px !important; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; + border-radius: 9999px; +} + +.marker-cluster:hover { + transform: scale(1.08); +} + +/* Leaflet Zoom and attribution controls dark theme */ +.leaflet-bar a { + background-color: var(--color-surface, #111827) !important; + color: var(--color-text-primary, #e5e7eb) !important; + border-bottom: 1px solid var(--color-border-color, #374151) !important; +} + +.leaflet-bar a:hover { + background-color: var(--color-hover-color, #1f2937) !important; + color: var(--color-accent, #38bdf8) !important; +} + +.leaflet-control-attribution { + background: rgba(11, 15, 25, 0.75) !important; + color: var(--color-text-secondary, #6b7280) !important; + font-size: 10px !important; + backdrop-filter: blur(4px); +} + +.leaflet-control-attribution a { + color: var(--color-text-secondary, #9ca3af) !important; +} diff --git a/src/types/invokes.ts b/src/types/invokes.ts index e90601917e..4ba0fdaf5b 100644 --- a/src/types/invokes.ts +++ b/src/types/invokes.ts @@ -85,6 +85,8 @@ export enum Invokes { SetColorLabelForPaths = 'set_color_label_for_paths', SetRatingForPaths = 'set_rating_for_paths', SetFlagForPaths = 'set_flag_for_paths', + SetGpsForPaths = 'set_gps_for_paths', + RevertGpsForPaths = 'revert_gps_for_paths', ShowInFinder = 'show_in_finder', StartBackgroundIndexing = 'start_background_indexing', StitchPanorama = 'stitch_panorama', diff --git a/src/types/settings.ts b/src/types/settings.ts index 4891c935c3..c954240cb4 100644 --- a/src/types/settings.ts +++ b/src/types/settings.ts @@ -188,6 +188,7 @@ export enum LibraryDisplayMode { Grid = 'grid', Cull = 'cull', List = 'list', + Map = 'map', } export enum ThumbnailSize { diff --git a/src/utils/gpsUtils.ts b/src/utils/gpsUtils.ts new file mode 100644 index 0000000000..c7f1d596dc --- /dev/null +++ b/src/utils/gpsUtils.ts @@ -0,0 +1,105 @@ +import { ImageFile } from '../types/library'; + +export interface GeoLocation { + lat: number; + lon: number; +} + +export function parseGpsCoordinate(coordStr: string): number | null { + if (!coordStr) return null; + const trimmed = coordStr.trim(); + + const dmsMatch = trimmed.match( + /(\d+\.?\d*)\s*(?:deg|°)\s*(\d+\.?\d*)\s*(?:min|'|’|′)\s*(\d+\.?\d*)\s*(?:sec|"|”|″)?/i, + ); + if (dmsMatch) { + const deg = parseFloat(dmsMatch[1]); + const min = parseFloat(dmsMatch[2]); + const sec = parseFloat(dmsMatch[3]); + if (!isNaN(deg) && !isNaN(min) && !isNaN(sec)) { + return deg + min / 60 + sec / 3600; + } + } + + const commaParts = trimmed.split(/,\s*/); + if (commaParts.length === 3) { + const deg = parseFloat(commaParts[0]); + const min = parseFloat(commaParts[1]); + const sec = parseFloat(commaParts[2]); + if (!isNaN(deg) && !isNaN(min) && !isNaN(sec)) { + return deg + min / 60 + sec / 3600; + } + } + + const directVal = parseFloat(trimmed); + if (!isNaN(directVal) && isFinite(directVal)) { + return directVal; + } + + return null; +} + +export function getImageGps( + image?: ImageFile | null, + overrideExif?: Record, +): GeoLocation | null { + const exif = overrideExif !== undefined ? overrideExif : image?.exif; + if (!exif) return null; + + const latStr = exif.GPSLatitude; + const latRef = exif.GPSLatitudeRef; + const lonStr = exif.GPSLongitude; + const lonRef = exif.GPSLongitudeRef; + + if (!latStr || !lonStr) return null; + + let lat = parseGpsCoordinate(latStr); + let lon = parseGpsCoordinate(lonStr); + + if (lat === null || lon === null) return null; + + if (latRef && latRef.toUpperCase().startsWith('S')) { + lat = -Math.abs(lat); + } + if (lonRef && lonRef.toUpperCase().startsWith('W')) { + lon = -Math.abs(lon); + } + + if (lat < -90 || lat > 90 || lon < -180 || lon > 180) { + return null; + } + + if (Math.abs(lat) < 0.0001 && Math.abs(lon) < 0.0001) { + return null; + } + + return { lat, lon }; +} + +export function getImageTimestamp( + image?: ImageFile | null, + overrideExif?: Record, +): string | null { + const exif = overrideExif !== undefined ? overrideExif : image?.exif; + if (exif) { + const dt = exif.DateTimeOriginal || exif.CreateDate || exif.ModifyDate || exif.DateTime; + if (dt) return dt; + } + if (image?.modified) { + try { + return new Date(image.modified * 1000).toLocaleString(); + } catch { + return null; + } + } + return null; +} + +export function toDmsString(val: number): string { + const absVal = Math.abs(val); + const deg = Math.floor(absVal); + const minFull = (absVal - deg) * 60; + const min = Math.floor(minFull); + const sec = (minFull - min) * 60; + return `${deg} deg ${min} min ${sec.toFixed(2)} sec`; +} diff --git a/src/utils/leaflet-setup.ts b/src/utils/leaflet-setup.ts new file mode 100644 index 0000000000..9fad63a584 --- /dev/null +++ b/src/utils/leaflet-setup.ts @@ -0,0 +1,15 @@ +import L from 'leaflet'; +import iconUrl from 'leaflet/dist/images/marker-icon.png'; +import iconRetinaUrl from 'leaflet/dist/images/marker-icon-2x.png'; +import shadowUrl from 'leaflet/dist/images/marker-shadow.png'; + +// Fix default Leaflet icon paths in Vite / bundler environments +delete (L.Icon.Default.prototype as unknown as { _getIconUrl?: unknown })._getIconUrl; + +L.Icon.Default.mergeOptions({ + iconRetinaUrl, + iconUrl, + shadowUrl, +}); + +export default L;