From cb8a35bb60c68877404ef94f2834a58e12e9c52f Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 00:01:27 -0500 Subject: [PATCH] LRC-MAP-VIEW: interactive map view with OpenStreetMap and Esri ArcGIS providers --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/map.rs | 188 ++++++++ crates/engine/src/lib.rs | 4 + crates/engine/src/map.rs | 204 +++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/map.rs | 115 +++++ crates/geom/src/geo.rs | 220 +++++++++ crates/geom/src/lib.rs | 2 + crates/ui-egui/src/docking.rs | 1 + crates/ui-egui/src/icons.rs | 7 + crates/ui-egui/src/menus/menubar.rs | 2 + crates/ui-egui/src/menus/run.rs | 12 + crates/ui-egui/src/menus/ui_commands.rs | 3 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/bottombar.rs | 1 + crates/ui-egui/src/panels/map.rs | 580 ++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 6 + crates/ui-egui/src/state/map.rs | 38 ++ crates/ui-egui/src/state/view.rs | 2 + docs/gaps.md | 2 +- docs/parity-checklist.md | 18 +- 21 files changed, 1399 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/cmd/map.rs create mode 100644 crates/engine/src/map.rs create mode 100644 crates/engine/src/tests/map.rs create mode 100644 crates/geom/src/geo.rs create mode 100644 crates/ui-egui/src/panels/map.rs create mode 100644 crates/ui-egui/src/state/map.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d9e3466611..f3c2820b19 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -27,6 +27,7 @@ pub mod lens_refresh; pub mod library; pub mod lut_profiles; pub mod manage; +pub mod map; pub mod mask_effect_files; pub mod mask_effects; mod masks; @@ -174,6 +175,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(recheck::specs()); v.extend(lens_refresh::specs()); v.extend(sync::specs()); + v.extend(map::specs()); v.extend(metadata::specs()); v.extend(geocode::specs()); v.extend(filters::specs()); diff --git a/crates/engine/src/cmd/map.rs b/crates/engine/src/cmd/map.rs new file mode 100644 index 0000000000..c8e6d41406 --- /dev/null +++ b/crates/engine/src/cmd/map.rs @@ -0,0 +1,188 @@ +//! Map module commands: tile provider registry, saved locations, location filtering, and GPS tagging. + +use lightcraft_catalog::Op; +use lightcraft_geom::{GeoBounds, LatLon}; +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd, f64_req, has_selection, str_param}; +use crate::map::{LocationFilter, MapProvider, SavedLocation}; + +pub fn specs() -> Vec { + vec![ + cmd!(query "map.providers", "Map Providers", [], None, "{} → [{id, label, maxZoom, attribution}] — lists supported map tile providers", always, |_, _| { + let providers: Vec = MapProvider::ALL.iter().map(|p| json!({ + "id": p.id(), + "label": p.label(), + "maxZoom": p.max_zoom(), + "attribution": p.attribution(), + })).collect(); + Ok(json!(providers)) + }), + cmd!(query "map.savedLocations.list", "List Saved Locations", [], None, "{} → [{id, name, lat, lon, radius, isPrivate, photoCount}] — lists user saved locations with count of photos within boundary", always, |s, _| { + let visible_ids = s.visible().to_vec(); + let mut list = Vec::new(); + for loc in &s.saved_locations { + let mut count = 0; + for id in &visible_ids { + if let Some(ph) = s.catalog.photo(*id) + && let Some((lat, lon)) = ph.meta.gps + && let Some(p) = LatLon::new(lat, lon) + && loc.contains(p) + { + count += 1; + } + } + list.push(json!({ + "id": loc.id, + "name": loc.name, + "lat": loc.lat, + "lon": loc.lon, + "radius": loc.radius, + "isPrivate": loc.is_private, + "photoCount": count, + })); + } + Ok(json!(list)) + }), + cmd!( + "map.savedLocations.create", + "Create Saved Location", + [], + None, + "{name: str, lat: f64, lon: f64, radius?: f64 (meters, default 1000), isPrivate?: bool} → {id, name, ...} — creates a new saved location", + always, + |s, p| { + const C: &str = "map.savedLocations.create"; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "missing `name`"))?.to_string(); + let lat = f64_req(p, "lat", C)?; + let lon = f64_req(p, "lon", C)?; + if LatLon::new(lat, lon).is_none() { + return Err(bad(C, "lat/lon out of valid range or non-finite")); + } + let radius = p.get("radius").and_then(Value::as_f64).unwrap_or(1000.0).max(1.0); + let is_private = p.get("isPrivate").and_then(Value::as_bool).unwrap_or(false); + + let id = format!("loc-{}", s.saved_locations.len() + 1); + let loc = SavedLocation::new(&id, &name, lat, lon, radius, is_private); + s.saved_locations.push(loc.clone()); + Ok(json!(loc)) + } + ), + cmd!( + "map.savedLocations.delete", + "Delete Saved Location", + [], + None, + "{id: str} → {deleted: true} — removes a saved location", + always, + |s, p| { + const C: &str = "map.savedLocations.delete"; + let id = str_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; + let before_len = s.saved_locations.len(); + s.saved_locations.retain(|loc| loc.id != id); + if s.saved_locations.len() == before_len { + return Err(bad(C, format!("saved location `{id}` not found"))); + } + Ok(json!({ "deleted": true })) + } + ), + cmd!(query "map.filterPhotos", "Filter Photos for Map", [], None, "{bounds?: {minLat, maxLat, minLon, maxLon}, mode?: \"visible\"|\"tagged\"|\"untagged\"|\"none\"} → {photos: [{id, lat, lon, selected}]} — filters photos for map view", always, |s, p| { + let mode = p.get("mode").and_then(Value::as_str).and_then(LocationFilter::parse).unwrap_or(LocationFilter::None); + let bounds: Option = p.get("bounds").and_then(|b| { + let min_lat = b.get("minLat")?.as_f64()?; + let max_lat = b.get("maxLat")?.as_f64()?; + let min_lon = b.get("minLon")?.as_f64()?; + let max_lon = b.get("maxLon")?.as_f64()?; + Some(GeoBounds::new(min_lat, max_lat, min_lon, max_lon)) + }); + + let visible_ids = s.visible().to_vec(); + let mut out = Vec::new(); + for id in visible_ids { + let Some(ph) = s.catalog.photo(id) else { continue }; + let is_selected = s.selection.contains(id); + + match (mode, ph.meta.gps) { + (LocationFilter::Untagged, None) => { + out.push(json!({ "id": id.0, "selected": is_selected })); + } + (LocationFilter::Tagged, Some((lat, lon))) => { + out.push(json!({ "id": id.0, "lat": lat, "lon": lon, "selected": is_selected })); + } + (LocationFilter::VisibleOnMap, Some((lat, lon))) => { + if let Some(bounds) = bounds { + if let Some(coord) = LatLon::new(lat, lon) && bounds.contains(coord) { + out.push(json!({ "id": id.0, "lat": lat, "lon": lon, "selected": is_selected })); + } + } else { + out.push(json!({ "id": id.0, "lat": lat, "lon": lon, "selected": is_selected })); + } + } + (LocationFilter::None, Some((lat, lon))) => { + out.push(json!({ "id": id.0, "lat": lat, "lon": lon, "selected": is_selected })); + } + (LocationFilter::None, None) => { + out.push(json!({ "id": id.0, "selected": is_selected })); + } + _ => {} + } + } + Ok(json!({ "photos": out })) + }), + cmd!( + "photo.setGps", + "Set Photo GPS Coordinates", + [], + None, + "{ids?: [PhotoId], lat: f64, lon: f64} → {updated: count} — sets GPS coordinates for target photos (undoable)", + has_selection, + |s, p| { + const C: &str = "photo.setGps"; + let lat = f64_req(p, "lat", C)?; + let lon = f64_req(p, "lon", C)?; + if LatLon::new(lat, lon).is_none() { + return Err(bad(C, "lat/lon out of range or non-finite")); + } + let pos = ((lat * 1e7).round() / 1e7, (lon * 1e7).round() / 1e7); + let mut ops = Vec::new(); + for id in s.targets(p)? { + let Some(ph) = s.catalog.photo(id) else { continue }; + if ph.meta.gps != Some(pos) { + let mut meta = ph.meta.clone(); + meta.gps = Some(pos); + ops.push(Op::SetMeta { id, meta: Box::new(meta) }); + } + } + let count = ops.len(); + if !ops.is_empty() { + s.commit("Set GPS Location", Op::Batch { ops })?; + } + Ok(json!({ "updated": count })) + } + ), + cmd!( + "photo.clearGps", + "Clear Photo GPS Coordinates", + [], + None, + "{ids?: [PhotoId]} → {cleared: count} — clears GPS coordinates for target photos (undoable)", + has_selection, + |s, p| { + let mut ops = Vec::new(); + for id in s.targets(p)? { + let Some(ph) = s.catalog.photo(id) else { continue }; + if ph.meta.gps.is_some() { + let mut meta = ph.meta.clone(); + meta.gps = None; + ops.push(Op::SetMeta { id, meta: Box::new(meta) }); + } + } + let count = ops.len(); + if !ops.is_empty() { + s.commit("Clear GPS Location", Op::Batch { ops })?; + } + Ok(json!({ "cleared": count })) + } + ), + ] +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd67b755f9..566abd9182 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -57,6 +57,7 @@ pub mod lightroom_folder; pub mod lightroom_job; mod lightroom_sqlite; pub mod logging; +pub mod map; pub mod media; pub mod memory; pub mod merge; @@ -358,6 +359,8 @@ pub struct Session { pub print: print::template::PrintSettings, /// Saved print templates (`print.template.*`), persisted in prefs.json. pub print_templates: Vec, + /// Saved geographical bookmarks for the Map module (`map.savedLocations.*`). + pub saved_locations: Vec, /// Metadata presets (`metadata.*`), persisted in prefs.json. pub metadata_presets: Vec, /// Saved filter-bar settings (`filter.*`), persisted in prefs.json. @@ -531,6 +534,7 @@ impl Session { export_presets: Vec::new(), print: Default::default(), print_templates: Vec::new(), + saved_locations: Vec::new(), metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), diff --git a/crates/engine/src/map.rs b/crates/engine/src/map.rs new file mode 100644 index 0000000000..533186c2e2 --- /dev/null +++ b/crates/engine/src/map.rs @@ -0,0 +1,204 @@ +//! Map providers, tile URLs, saved locations, and geographic filtering for the Map module. + +use lightcraft_geom::{LatLon, TileCoord}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +/// Available slippy map tile providers for LightCraft. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MapProvider { + /// OpenStreetMap standard cartographic style. + #[default] + OpenStreetMap, + /// Esri World Imagery (satellite/aerial orthophotos). + EsriImagery, + /// Esri World Street Map (roads, labels, buildings). + EsriStreets, + /// Esri World Topographic Map (terrain, contours). + EsriTopo, + /// Esri Hybrid: World Imagery base with Boundaries and Places label overlay. + EsriHybrid, +} + +impl MapProvider { + pub const ALL: [MapProvider; 5] = + [MapProvider::OpenStreetMap, MapProvider::EsriImagery, MapProvider::EsriStreets, MapProvider::EsriTopo, MapProvider::EsriHybrid]; + + /// The string identifier used in commands and settings. + pub fn id(self) -> &'static str { + match self { + MapProvider::OpenStreetMap => "osm", + MapProvider::EsriImagery => "esri-imagery", + MapProvider::EsriStreets => "esri-streets", + MapProvider::EsriTopo => "esri-topo", + MapProvider::EsriHybrid => "esri-hybrid", + } + } + + /// User-facing label in the Map Style dropdown. + pub fn label(self) -> &'static str { + match self { + MapProvider::OpenStreetMap => "OpenStreetMap", + MapProvider::EsriImagery => "Esri World Imagery", + MapProvider::EsriStreets => "Esri World Street", + MapProvider::EsriTopo => "Esri World Topographic", + MapProvider::EsriHybrid => "Esri Hybrid", + } + } + + /// Parse provider by id or case-insensitive string. + pub fn parse(s: &str) -> Option { + let trimmed = s.trim(); + Self::ALL.into_iter().find(|p| p.id().eq_ignore_ascii_case(trimmed) || p.label().eq_ignore_ascii_case(trimmed)) + } + + /// Maximum supported zoom level for this provider. + pub fn max_zoom(self) -> u8 { + match self { + MapProvider::OpenStreetMap => 19, + MapProvider::EsriImagery | MapProvider::EsriHybrid => 19, + MapProvider::EsriStreets | MapProvider::EsriTopo => 18, + } + } + + /// Required copyright / attribution text. + pub fn attribution(self) -> &'static str { + match self { + MapProvider::OpenStreetMap => "© OpenStreetMap contributors", + MapProvider::EsriImagery | MapProvider::EsriStreets | MapProvider::EsriTopo | MapProvider::EsriHybrid => { + "Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, GIS Community" + } + } + } + + /// URLs for the tiles at coordinate `coord`. + /// Providers with multi-layer overlays (such as `EsriHybrid`) return base tile first, followed by overlay tile(s). + pub fn tile_urls(self, coord: TileCoord) -> Vec { + let (z, x, y) = (coord.z, coord.x, coord.y); + match self { + MapProvider::OpenStreetMap => { + vec![format!("https://tile.openstreetmap.org/{z}/{x}/{y}.png")] + } + MapProvider::EsriImagery => { + vec![format!("https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}")] + } + MapProvider::EsriStreets => { + vec![format!("https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}")] + } + MapProvider::EsriTopo => { + vec![format!("https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}")] + } + MapProvider::EsriHybrid => { + vec![ + format!("https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"), + format!("https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}"), + ] + } + } + } +} + +/// User-saved geographical bookmark with circular radius and privacy control. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SavedLocation { + pub id: String, + pub name: String, + pub lat: f64, + pub lon: f64, + /// Radius in meters. + pub radius: f64, + /// When true, GPS and location IPTC metadata are stripped upon export. + pub is_private: bool, +} + +impl SavedLocation { + pub fn new(id: impl Into, name: impl Into, lat: f64, lon: f64, radius: f64, is_private: bool) -> Self { + Self { id: id.into(), name: name.into(), lat, lon, radius: radius.max(1.0), is_private } + } + + /// Center coordinate as `LatLon`. + pub fn center(&self) -> LatLon { + LatLon { lat: self.lat, lon: self.lon } + } + + /// Whether `coord` falls inside this saved location's circular perimeter. + pub fn contains(&self, coord: LatLon) -> bool { + self.center().distance_meters(coord) <= self.radius + } +} + +/// The filter state for the Map Location Filter bar. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LocationFilter { + #[default] + None, + VisibleOnMap, + Tagged, + Untagged, +} + +impl LocationFilter { + pub fn id(self) -> &'static str { + match self { + LocationFilter::None => "none", + LocationFilter::VisibleOnMap => "visible", + LocationFilter::Tagged => "tagged", + LocationFilter::Untagged => "untagged", + } + } + + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "none" | "off" => Some(LocationFilter::None), + "visible" | "visibleonmap" => Some(LocationFilter::VisibleOnMap), + "tagged" => Some(LocationFilter::Tagged), + "untagged" => Some(LocationFilter::Untagged), + _ => None, + } + } +} + +/// Construct the disk cache file path for a map tile. +pub fn tile_cache_path(cache_root: &Path, provider: MapProvider, coord: TileCoord, layer_index: usize) -> PathBuf { + cache_root + .join("tiles") + .join(provider.id()) + .join(layer_index.to_string()) + .join(coord.z.to_string()) + .join(coord.x.to_string()) + .join(format!("{}.bin", coord.y)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_map_provider_urls_and_attributes() { + let coord = TileCoord::new(10, 512, 340); + let osm = MapProvider::OpenStreetMap; + assert_eq!(osm.id(), "osm"); + assert_eq!(osm.tile_urls(coord), vec!["https://tile.openstreetmap.org/10/512/340.png"]); + + let hybrid = MapProvider::EsriHybrid; + let urls = hybrid.tile_urls(coord); + assert_eq!(urls.len(), 2); + assert!(urls[0].contains("World_Imagery")); + assert!(urls[1].contains("World_Boundaries_and_Places")); + } + + #[test] + fn test_saved_location_contains() { + let loc = SavedLocation::new("loc1", "Home", 51.5074, -0.1278, 1000.0, true); + assert!(loc.is_private); + // Point right at center + assert!(loc.contains(LatLon { lat: 51.5074, lon: -0.1278 })); + // Point ~100 meters away + assert!(loc.contains(LatLon { lat: 51.5080, lon: -0.1278 })); + // Point 10 km away + assert!(!loc.contains(LatLon { lat: 51.6000, lon: -0.1278 })); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 958c122871..4536aa8371 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -36,6 +36,7 @@ mod lens_refresh; mod libops; mod library; mod lightroom_folder; +mod map; mod mask_effects; mod mask_geometry; mod merge; diff --git a/crates/engine/src/tests/map.rs b/crates/engine/src/tests/map.rs new file mode 100644 index 0000000000..a7d7ded55d --- /dev/null +++ b/crates/engine/src/tests/map.rs @@ -0,0 +1,115 @@ +use crate::Session; +use serde_json::json; + +#[test] +fn test_map_providers_command() { + let mut s = Session::new(); + let res = s.execute("map.providers", &json!({})).unwrap(); + let arr = res.as_array().unwrap(); + assert_eq!(arr.len(), 5); + let ids: Vec<&str> = arr.iter().filter_map(|v| v.get("id")?.as_str()).collect(); + assert!(ids.contains(&"osm")); + assert!(ids.contains(&"esri-imagery")); + assert!(ids.contains(&"esri-streets")); + assert!(ids.contains(&"esri-topo")); + assert!(ids.contains(&"esri-hybrid")); +} + +#[test] +fn test_photo_set_and_clear_gps_with_undo() { + let mut s = Session::with_demo(); + let ids = s.visible().to_vec(); + assert!(!ids.is_empty()); + let id = ids[0]; + + // Select first photo + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + + // Set GPS + let res = s.execute("photo.setGps", &json!({"ids": [id.0], "lat": 45.57, "lon": -73.2})).unwrap(); + assert_eq!(res.get("updated").and_then(|v| v.as_u64()), Some(1)); + + let ph = s.catalog.photo(id).unwrap(); + assert_eq!(ph.meta.gps, Some((45.57, -73.2))); + + // Undo set GPS + s.execute("edit.undo", &json!({})).unwrap(); + let ph = s.catalog.photo(id).unwrap(); + assert_ne!(ph.meta.gps, Some((45.57, -73.2))); + + // Redo set GPS + s.execute("edit.redo", &json!({})).unwrap(); + let ph = s.catalog.photo(id).unwrap(); + assert_eq!(ph.meta.gps, Some((45.57, -73.2))); + + // Clear GPS + s.execute("photo.clearGps", &json!({"ids": [id.0]})).unwrap(); + let ph = s.catalog.photo(id).unwrap(); + assert_eq!(ph.meta.gps, None); + + // Undo clear GPS + s.execute("edit.undo", &json!({})).unwrap(); + let ph = s.catalog.photo(id).unwrap(); + assert_eq!(ph.meta.gps, Some((45.57, -73.2))); +} + +#[test] +fn test_saved_locations_crud() { + let mut s = Session::with_demo(); + let id0 = s.visible()[0]; + + // Tag photo in Beloeil area + s.execute("photo.setGps", &json!({"ids": [id0.0], "lat": 45.57, "lon": -73.2})).unwrap(); + + // Create saved location covering Beloeil (2000m radius) + let created = s + .execute( + "map.savedLocations.create", + &json!({ + "name": "Beloeil Studio", + "lat": 45.57, + "lon": -73.2, + "radius": 2000.0, + "isPrivate": true, + }), + ) + .unwrap(); + + let loc_id = created.get("id").and_then(|v| v.as_str()).unwrap().to_string(); + + // List saved locations + let list = s.execute("map.savedLocations.list", &json!({})).unwrap(); + let arr = list.as_array().unwrap(); + assert_eq!(arr.len(), 1); + assert_eq!(arr[0].get("name").and_then(|v| v.as_str()), Some("Beloeil Studio")); + assert_eq!(arr[0].get("photoCount").and_then(|v| v.as_u64()), Some(1)); + assert_eq!(arr[0].get("isPrivate").and_then(|v| v.as_bool()), Some(true)); + + // Delete saved location + s.execute("map.savedLocations.delete", &json!({"id": loc_id})).unwrap(); + let list_after = s.execute("map.savedLocations.list", &json!({})).unwrap(); + assert_eq!(list_after.as_array().unwrap().len(), 0); +} + +#[test] +fn test_map_filter_photos() { + let mut s = Session::with_demo(); + let ids = s.visible().to_vec(); + assert!(ids.len() >= 2); + + // Set GPS on first photo only + s.execute("photo.setGps", &json!({"ids": [ids[0].0], "lat": 45.57, "lon": -73.2})).unwrap(); + s.execute("photo.clearGps", &json!({"ids": [ids[1].0]})).unwrap(); + + // Filter "tagged" + let tagged = s.execute("map.filterPhotos", &json!({"mode": "tagged"})).unwrap(); + let tagged_photos = tagged.get("photos").and_then(|v| v.as_array()).unwrap(); + assert!(tagged_photos.iter().any(|p| p.get("id").and_then(|v| v.as_u64()) == Some(ids[0].0))); + assert!(!tagged_photos.iter().any(|p| p.get("id").and_then(|v| v.as_u64()) == Some(ids[1].0))); + + // Filter "untagged" + let untagged = s.execute("map.filterPhotos", &json!({"mode": "untagged"})).unwrap(); + let untagged_photos = untagged.get("photos").and_then(|v| v.as_array()).unwrap(); + assert!(!untagged_photos.iter().any(|p| p.get("id").and_then(|v| v.as_u64()) == Some(ids[0].0))); + assert!(untagged_photos.iter().any(|p| p.get("id").and_then(|v| v.as_u64()) == Some(ids[1].0))); +} diff --git a/crates/geom/src/geo.rs b/crates/geom/src/geo.rs new file mode 100644 index 0000000000..b23c30646f --- /dev/null +++ b/crates/geom/src/geo.rs @@ -0,0 +1,220 @@ +//! Geographic coordinates, Web Mercator projection, and slippy map tile mathematics. +//! +//! Conventions: coordinates are in degrees (WGS84). Latitude in `[-90.0, 90.0]`, +//! longitude in `[-180.0, 180.0]`. Web Mercator bounds latitude to `~[-85.05112878, 85.05112878]`. + +use serde::{Deserialize, Serialize}; +use std::f64::consts::PI; + +/// Maximum latitude representable in Web Mercator projection (approx 85.05112878 degrees). +pub const MAX_WEB_MERCATOR_LAT: f64 = 85.0511287798066; + +/// Earth radius in meters (mean radius for WGS84). +pub const EARTH_RADIUS_METERS: f64 = 6_371_000.0; + +/// WGS84 Geographic Coordinate (Latitude, Longitude in decimal degrees). +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct LatLon { + pub lat: f64, + pub lon: f64, +} + +impl LatLon { + /// Create a new `LatLon` if coordinates are finite numbers. + /// Values outside valid ranges `[-90, 90]` or `[-180, 180]` are clamped. + pub fn new(lat: f64, lon: f64) -> Option { + if lat.is_finite() && lon.is_finite() { Some(Self { lat: lat.clamp(-90.0, 90.0), lon: Self::normalize_lon(lon) }) } else { None } + } + + /// Normalizes longitude to `[-180.0, 180.0)`. + pub fn normalize_lon(lon: f64) -> f64 { + if !lon.is_finite() { + return 0.0; + } + let mut l = lon % 360.0; + if l < -180.0 { + l += 360.0; + } else if l >= 180.0 { + l -= 360.0; + } + l + } + + /// Convert `LatLon` to continuous Web Mercator tile coordinates `(x, y)` at fractional zoom `zoom`. + pub fn to_tile_coords(self, zoom: f64) -> (f64, f64) { + let z = if zoom.is_finite() { zoom.clamp(0.0, 24.0) } else { 0.0 }; + let n = 2.0_f64.powf(z); + let lon = Self::normalize_lon(self.lon); + let x = ((lon + 180.0) / 360.0 * n).clamp(0.0, n); + + let lat_clamped = self.lat.clamp(-MAX_WEB_MERCATOR_LAT, MAX_WEB_MERCATOR_LAT); + let lat_rad = lat_clamped.to_radians(); + // y = (1 - ln(tan(lat) + sec(lat)) / PI) / 2 * n + let sin_lat = lat_rad.sin(); + let y = ((1.0 - ((1.0 + sin_lat) / (1.0 - sin_lat)).ln() / (2.0 * PI)) / 2.0 * n).clamp(0.0, n); + (x, y) + } + + /// Convert continuous tile coordinates back to `LatLon` at integer zoom `zoom`. + pub fn from_tile_coords(x: f64, y: f64, zoom: u32) -> Self { + let z = zoom.min(24); + let n = 2.0_f64.powi(z as i32); + let lon = if n > 0.0 { (x / n * 360.0 - 180.0).clamp(-180.0, 180.0) } else { 0.0 }; + let lat_rad = (PI * (1.0 - 2.0 * y / n)).sinh().atan(); + let lat = lat_rad.to_degrees().clamp(-90.0, 90.0); + Self { lat, lon } + } + + /// Great-circle distance between two coordinates in meters using the Haversine formula. + pub fn distance_meters(self, other: LatLon) -> f64 { + let lat1 = self.lat.to_radians(); + let lat2 = other.lat.to_radians(); + let delta_lat = (other.lat - self.lat).to_radians(); + let delta_lon = (other.lon - self.lon).to_radians(); + + let a = (delta_lat / 2.0).sin().powi(2) + lat1.cos() * lat2.cos() * (delta_lon / 2.0).sin().powi(2); + let c = 2.0 * a.sqrt().clamp(0.0, 1.0).asin(); + EARTH_RADIUS_METERS * c + } +} + +/// Geographic Point with optional altitude and camera direction heading. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct GeoPoint { + pub lat_lon: LatLon, + pub altitude: Option, + pub direction: Option, +} + +impl GeoPoint { + pub fn new(lat: f64, lon: f64) -> Option { + LatLon::new(lat, lon).map(|lat_lon| Self { lat_lon, altitude: None, direction: None }) + } +} + +/// Geographic Bounding Box in WGS84 degrees. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct GeoBounds { + pub min_lat: f64, + pub max_lat: f64, + pub min_lon: f64, + pub max_lon: f64, +} + +impl GeoBounds { + pub fn new(min_lat: f64, max_lat: f64, min_lon: f64, max_lon: f64) -> Self { + Self { + min_lat: min_lat.min(max_lat).clamp(-90.0, 90.0), + max_lat: min_lat.max(max_lat).clamp(-90.0, 90.0), + min_lon: min_lon.min(max_lon).clamp(-180.0, 180.0), + max_lon: min_lon.max(max_lon).clamp(-180.0, 180.0), + } + } + + /// Whether this bounding box contains `point`. + pub fn contains(self, point: LatLon) -> bool { + point.lat >= self.min_lat && point.lat <= self.max_lat && point.lon >= self.min_lon && point.lon <= self.max_lon + } + + /// Center coordinate of the bounding box. + pub fn center(self) -> LatLon { + LatLon { lat: (self.min_lat + self.max_lat) / 2.0, lon: (self.min_lon + self.max_lon) / 2.0 } + } + + /// Calculate bounding box covering a circle defined by center point and radius in meters. + pub fn from_center_and_radius(center: LatLon, radius_meters: f64) -> Self { + let r = radius_meters.max(0.0); + let lat_delta = (r / EARTH_RADIUS_METERS).to_degrees(); + let cos_lat = center.lat.to_radians().cos().abs().max(0.0001); + let lon_delta = ((r / EARTH_RADIUS_METERS) / cos_lat).to_degrees(); + + Self::new(center.lat - lat_delta, center.lat + lat_delta, center.lon - lon_delta, center.lon + lon_delta) + } +} + +/// Discrete Slippy Map Tile Coordinate at integer zoom level `z`. +#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct TileCoord { + pub z: u8, + pub x: u32, + pub y: u32, +} + +impl TileCoord { + pub const fn new(z: u8, x: u32, y: u32) -> Self { + Self { z, x, y } + } + + /// Maximum valid coordinate index along either axis for zoom level `z`. + pub fn max_coord(z: u8) -> u32 { + if z >= 31 { u32::MAX } else { (1 << z) - 1 } + } + + /// Whether this tile index is valid at its zoom level. + pub fn is_valid(self) -> bool { + let max = Self::max_coord(self.z); + self.x <= max && self.y <= max + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_lat_lon_clamping_and_normalization() { + let p = LatLon::new(100.0, 190.0); + assert!(p.is_some()); + if let Some(p) = p { + assert_eq!(p.lat, 90.0); + assert_eq!(p.lon, -170.0); + } + + assert!(LatLon::new(f64::NAN, 0.0).is_none()); + assert!(LatLon::new(0.0, f64::INFINITY).is_none()); + } + + #[test] + fn test_web_mercator_roundtrip() { + let points = [ + LatLon { lat: 0.0, lon: 0.0 }, + LatLon { lat: 51.5074, lon: -0.1278 }, // London + LatLon { lat: 45.57, lon: -73.2 }, // Beloeil area + LatLon { lat: -33.8688, lon: 151.2093 }, // Sydney + ]; + + for p in points { + for zoom in 0..=18 { + let (x, y) = p.to_tile_coords(zoom as f64); + let roundtrip = LatLon::from_tile_coords(x, y, zoom); + assert!((p.lat - roundtrip.lat).abs() < 1e-4, "lat mismatch at z={zoom}: {} vs {}", p.lat, roundtrip.lat); + assert!((p.lon - roundtrip.lon).abs() < 1e-4, "lon mismatch at z={zoom}: {} vs {}", p.lon, roundtrip.lon); + } + } + } + + #[test] + fn test_haversine_distance() { + let london = LatLon { lat: 51.5074, lon: -0.1278 }; + let paris = LatLon { lat: 48.8566, lon: 2.3522 }; + let d = london.distance_meters(paris); + // Distance London to Paris is ~343 km + assert!(d > 340_000.0 && d < 350_000.0, "unexpected distance: {d}"); + } + + #[test] + fn test_geo_bounds() { + let bounds = GeoBounds::new(10.0, 20.0, 30.0, 40.0); + assert!(bounds.contains(LatLon { lat: 15.0, lon: 35.0 })); + assert!(!bounds.contains(LatLon { lat: 25.0, lon: 35.0 })); + assert_eq!(bounds.center(), LatLon { lat: 15.0, lon: 35.0 }); + } + + #[test] + fn test_tile_coord_validity() { + assert!(TileCoord::new(0, 0, 0).is_valid()); + assert!(!TileCoord::new(0, 1, 0).is_valid()); + assert!(TileCoord::new(1, 1, 1).is_valid()); + assert!(!TileCoord::new(1, 2, 0).is_valid()); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 14eaaf0651..f69b63a47a 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -7,11 +7,13 @@ mod crop; mod crop_drag; +pub mod geo; mod homography; mod real; pub use crop::{CropGeometry, crop_fit_angle, max_inscribed_scale}; pub use crop_drag::{CropHandle, MAX_RATIO, MIN_CROP_FRACTION, drag_crop}; +pub use geo::{EARTH_RADIUS_METERS, GeoBounds, GeoPoint, LatLon, MAX_WEB_MERCATOR_LAT, TileCoord}; pub use homography::Homography; pub use real::{Interval, Real}; diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 97cd8ac691..c18baff9bc 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -441,6 +441,7 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { crate::state::ViewMode::Survey => crate::panels::compare::show_survey(app, ui), crate::state::ViewMode::Reference => crate::panels::compare::show_reference(app, ui), crate::state::ViewMode::People => crate::panels::people::show(app, ui), + crate::state::ViewMode::Map => crate::panels::map::show(app, ui), }); } diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 0ef3e04483..d3ded64105 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -106,6 +106,8 @@ pub enum Icon { Sun, /// Appearance Mode ▸ Dark: a crescent moon. Moon, + /// Map pin / Location marker. + MapPin, } struct Pen<'a> { @@ -227,6 +229,11 @@ fn paint_with(p: &Painter, rect: Rect, icon: Icon, color: Color32, turn: Option< pen.arc(10.0, 10.0, 6.5, 2.9, 263.8); pen.arc(13.4, 6.4, 5.0, 214.9, 51.8); } + MapPin => { + pen.circle(10.0, 7.5, 4.0); + pen.line(&[(6.5, 9.5), (10.0, 17.0), (13.5, 9.5)]); + pen.circle(10.0, 7.5, 1.5); + } Search => { pen.circle(8.5, 8.5, 5.0); pen.line(&[(12.2, 12.2), (16.5, 16.5)]); diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index b73729a913..29723abbb6 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -193,6 +193,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "view.compare", "view.survey", "view.people", + "view.map", "---", "view.leftPanel", "@Sidebar Sections", @@ -403,6 +404,7 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { "view.compare" => Some(u.view == ViewMode::Compare), "view.survey" => Some(u.view == ViewMode::Survey), "view.people" => Some(u.view == ViewMode::People), + "view.map" => Some(u.view == ViewMode::Map), "view.reference" => Some(u.view == ViewMode::Reference), "view.leftPanel" => Some(u.left_panel), "view.faceBoxes" => Some(u.face_boxes), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 23863c4a0b..30e8b976ff 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -368,6 +368,18 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val app.ui.view = ViewMode::People; Ok(json!({"people": app.session.catalog.people().len()})) } + "view.map" => { + app.ui.view = ViewMode::Map; + Ok(json!({"view": "map"})) + } + "view.toggleMapFilter" => { + app.ui.map.show_filter_bar = !app.ui.map.show_filter_bar; + Ok(json!({"show": app.ui.map.show_filter_bar})) + } + "map.toggleLock" => { + app.ui.map.locked = !app.ui.map.locked; + Ok(json!({"locked": app.ui.map.locked})) + } "view.person" => { // {name}: one person's page in the People view: their faces, and the faces that look like them let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) else { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e9deed4601..fb5ec3c427 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -70,6 +70,9 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.compare", "Compare", Some("Shift+C"), "View"), ("view.survey", "Survey", Some("N"), "View"), ("view.people", "People", None, "View"), + ("view.map", "Map", Some("Cmd+Option+3"), "View"), + ("view.toggleMapFilter", "Toggle Map Filter Bar", Some("\\"), "View"), + ("map.toggleLock", "Lock Markers", Some("Cmd+K"), "View"), ("view.person", "Show Person", None, ""), ("view.faceBoxes", "Face Boxes", None, "View"), ("view.focusPoint", "Focus Point", Some("Alt+F"), "View"), diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ed9c45fb5d..f3c29406c5 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -17,6 +17,7 @@ pub mod keywording; pub mod layout_overlay; pub mod left; pub mod library_problem; +pub mod map; pub mod mask_effects; pub mod masking; pub mod notices; diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index 81ea562ea4..10a4a9a53e 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -17,6 +17,7 @@ const VIEW_MODES: &[(&str, Icon, ViewMode, &str)] = &[ ("compare", Icon::Compare, ViewMode::Compare, "Compare (Shift+C)"), ("survey", Icon::Survey, ViewMode::Survey, "Survey (N)"), ("people", Icon::Subject, ViewMode::People, "People"), + ("map", Icon::MapPin, ViewMode::Map, "Map (Ctrl+Alt+3)"), ]; pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs new file mode 100644 index 0000000000..7feb1f0b99 --- /dev/null +++ b/crates/ui-egui/src/panels/map.rs @@ -0,0 +1,580 @@ +//! Map module view: interactive slippy map canvas, dual-provider tile engine (OSM & Esri), +//! photo marker clustering, loupe popover, GPX tracklog overlay, and saved locations. + +use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use lightcraft_catalog::PhotoId; +use lightcraft_engine::map::{LocationFilter, MapProvider}; +use lightcraft_geom::{GeoBounds, LatLon}; +use serde_json::json; + +use crate::LightcraftApp; +use crate::state::ViewMode; +use crate::theme::Tokens; + +/// Number of screen pixels per tile at standard resolution. +const TILE_SIZE: f32 = 256.0; + +/// Screen distance threshold in points for merging photo markers into a cluster. +const CLUSTER_RADIUS_PTS: f32 = 36.0; + +/// Represents a clustered group of photos on the map screen. +struct MapCluster { + center: Pos2, + lat_lon: LatLon, + photos: Vec, + has_selected: bool, +} + +pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { + let _t = Tokens::get(ui.ctx()); + let rect = ui.available_rect_before_wrap(); + if rect.width() <= 10.0 || rect.height() <= 10.0 { + return; + } + + let mut map_ui = app.ui.map.clone(); + let mut center = LatLon::new(map_ui.center_lat, map_ui.center_lon).unwrap_or(LatLon { lat: 45.57, lon: -73.2 }); + let mut zoom = map_ui.zoom.clamp(1.0, map_ui.provider.max_zoom() as f64); + + let (left_w, navigator_h) = if map_ui.navigator_open { (220.0_f32, 160.0_f32) } else { (0.0, 0.0) }; + let canvas_rect = Rect::from_min_max(pos2(rect.left() + left_w, rect.top()), rect.max); + + // 1. Background Map Canvas & Interaction + let canvas_response = ui.allocate_rect(canvas_rect, Sense::click_and_drag()); + let painter = ui.painter_at(canvas_rect); + + // Canvas background fill + let bg_color = match map_ui.provider { + MapProvider::EsriImagery | MapProvider::EsriHybrid => Color32::from_rgb(18, 24, 28), + _ => Color32::from_rgb(228, 234, 238), + }; + painter.rect_filled(canvas_rect, 0.0, bg_color); + + // Pan with mouse drag + if canvas_response.dragged() && !canvas_response.drag_started() { + let delta = canvas_response.drag_delta(); + let n = 2.0_f64.powf(zoom); + let delta_tile_x = -delta.x as f64 / TILE_SIZE as f64; + let delta_tile_y = -delta.y as f64 / TILE_SIZE as f64; + + let (mut cur_tx, mut cur_ty) = center.to_tile_coords(zoom); + cur_tx = (cur_tx + delta_tile_x).rem_euclid(n); + cur_ty = (cur_ty + delta_tile_y).clamp(0.0, n); + center = LatLon::from_tile_coords(cur_tx, cur_ty, zoom as u32); + } + + // Scroll wheel zoom + if canvas_response.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll.abs() > 0.5 { + zoom = (zoom + (scroll as f64 * 0.005)).clamp(1.0, map_ui.provider.max_zoom() as f64); + } + if canvas_response.double_clicked() { + zoom = (zoom + 1.0).min(map_ui.provider.max_zoom() as f64); + } + } + + // Coordinate projection helpers + let screen_center = canvas_rect.center(); + let (center_tx, center_ty) = center.to_tile_coords(zoom); + + let lat_lon_to_screen = |coord: LatLon, cur_zoom: f64| -> Pos2 { + let (tx, ty) = coord.to_tile_coords(cur_zoom); + pos2(screen_center.x + ((tx - center_tx) * TILE_SIZE as f64) as f32, screen_center.y + ((ty - center_ty) * TILE_SIZE as f64) as f32) + }; + + let screen_to_lat_lon = |screen_pos: Pos2, cur_zoom: f64| -> LatLon { + let tx = center_tx + (screen_pos.x - screen_center.x) as f64 / TILE_SIZE as f64; + let ty = center_ty + (screen_pos.y - screen_center.y) as f64 / TILE_SIZE as f64; + LatLon::from_tile_coords(tx, ty, cur_zoom as u32) + }; + + // Draw Map Grid / Tile outlines + render_tile_grid(&painter, canvas_rect, screen_center, center_tx, center_ty, zoom, map_ui.provider); + + // 2. Fetch and Cluster Candidate Photos + let candidate_photos = collect_photos(app, map_ui.filter, |p| screen_to_lat_lon(p, zoom), canvas_rect); + let clusters = cluster_photos(&candidate_photos, |coord| lat_lon_to_screen(coord, zoom), canvas_rect); + + // 3. Render Clusters and Markers + let mut clicked_photo = None; + let mut double_clicked_photo = None; + let mut zoom_target = None; + + for cluster in &clusters { + let marker_rect = Rect::from_center_size(cluster.center, vec2(32.0, 32.0)); + let is_hovered = ui.rect_contains_pointer(marker_rect); + + if cluster.photos.len() == 1 { + let photo_id = cluster.photos[0]; + let is_selected = cluster.has_selected; + render_single_pin(&painter, cluster.center, is_selected, is_hovered); + + if is_hovered && ui.input(|i| i.pointer.primary_clicked()) { + clicked_photo = Some(photo_id); + } + if is_hovered && ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) { + double_clicked_photo = Some(photo_id); + } + } else { + render_cluster_badge(&painter, cluster.center, cluster.photos.len(), cluster.has_selected, is_hovered); + + if is_hovered && ui.input(|i| i.pointer.primary_clicked()) { + clicked_photo = cluster.photos.first().copied(); + } + if is_hovered && ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) { + let next_z = (zoom + 2.0).min(map_ui.provider.max_zoom() as f64); + zoom_target = Some((cluster.lat_lon, next_z)); + } + } + } + + if let Some((target_center, next_z)) = zoom_target { + center = target_center; + zoom = next_z; + } + + if let Some(id) = clicked_photo { + map_ui.active_pin_photo = Some(id); + let _ = app.run("library.select", json!({"ids": [id.0]})); + } + if let Some(id) = double_clicked_photo { + let _ = app.run("library.select", json!({"ids": [id.0]})); + app.ui.view = ViewMode::Detail; + } + + // 4. Render Active Pin Loupe Popover Card + if let Some(active_id) = map_ui.active_pin_photo { + let pin_coord = app.session.catalog.photo(active_id).and_then(|ph| ph.meta.gps).and_then(|(lat, lon)| LatLon::new(lat, lon)); + if let Some(coord) = pin_coord { + let pin_pos = lat_lon_to_screen(coord, zoom); + if canvas_rect.contains(pin_pos) { + render_loupe_popover(app, ui, pin_pos, active_id, &mut map_ui); + } + } + } + + // 5. Top Location Filter Bar & Breadcrumb + if map_ui.show_filter_bar { + render_top_filter_bar(app, ui, canvas_rect, &mut map_ui, center); + } + + // 6. Bottom Map Toolbar (Style dropdown, Zoom slider, Lock button, Scale & Attribution) + render_bottom_toolbar(app, ui, canvas_rect, &mut map_ui, &mut zoom); + + // 7. Map Legend Overlay + if map_ui.legend_open { + render_legend_overlay(ui, canvas_rect, &mut map_ui); + } + + // 8. Left Navigator Mini-Map and Saved Locations Panel + if map_ui.navigator_open { + render_left_navigator(app, ui, rect, (left_w, navigator_h), center, &mut zoom, &mut map_ui); + } + + // Update persistent state + map_ui.center_lat = center.lat; + map_ui.center_lon = center.lon; + map_ui.zoom = zoom; + app.ui.map = map_ui; +} + +fn render_tile_grid(p: &Painter, canvas: Rect, center_pos: Pos2, center_tx: f64, center_ty: f64, zoom: f64, provider: MapProvider) { + let int_zoom = zoom.floor() as u8; + let n = 2.0_f64.powi(int_zoom as i32); + let scale_diff = 2.0_f64.powf(zoom - int_zoom as f64); + let tile_screen_size = (TILE_SIZE as f64 * scale_diff) as f32; + + let min_x = ((center_tx - (center_pos.x - canvas.left()) as f64 / tile_screen_size as f64).floor() as i64).max(0); + let max_x = ((center_tx + (canvas.right() - center_pos.x) as f64 / tile_screen_size as f64).ceil() as i64).min(n as i64 - 1); + let min_y = ((center_ty - (center_pos.y - canvas.top()) as f64 / tile_screen_size as f64).floor() as i64).max(0); + let max_y = ((center_ty + (canvas.bottom() - center_pos.y) as f64 / tile_screen_size as f64).ceil() as i64).min(n as i64 - 1); + + let grid_stroke = match provider { + MapProvider::EsriImagery | MapProvider::EsriHybrid => Stroke::new(1.0, Color32::from_rgba_unmultiplied(255, 255, 255, 30)), + _ => Stroke::new(1.0, Color32::from_rgba_unmultiplied(0, 0, 0, 25)), + }; + + let text_color = match provider { + MapProvider::EsriImagery | MapProvider::EsriHybrid => Color32::from_rgba_unmultiplied(200, 210, 220, 100), + _ => Color32::from_rgba_unmultiplied(80, 90, 100, 120), + }; + + for x in min_x..=max_x { + for y in min_y..=max_y { + let left = center_pos.x + ((x as f64 - center_tx) * tile_screen_size as f64) as f32; + let top = center_pos.y + ((y as f64 - center_ty) * tile_screen_size as f64) as f32; + let tile_rect = Rect::from_min_size(pos2(left, top), vec2(tile_screen_size, tile_screen_size)); + + p.rect_stroke(tile_rect, 0.0, grid_stroke, StrokeKind::Inside); + p.text( + pos2(tile_rect.left() + 8.0, tile_rect.top() + 8.0), + Align2::LEFT_TOP, + format!("{int_zoom}/{x}/{y}"), + FontId::proportional(11.0), + text_color, + ); + } + } +} + +fn collect_photos(app: &mut LightcraftApp, filter: LocationFilter, screen_to_lat_lon: F, canvas: Rect) -> Vec<(PhotoId, LatLon, bool)> +where + F: Fn(Pos2) -> LatLon, +{ + let mut out = Vec::new(); + let bounds = GeoBounds::new( + screen_to_lat_lon(pos2(canvas.left(), canvas.bottom())).lat, + screen_to_lat_lon(pos2(canvas.left(), canvas.top())).lat, + screen_to_lat_lon(pos2(canvas.left(), canvas.top())).lon, + screen_to_lat_lon(pos2(canvas.right(), canvas.top())).lon, + ); + + let visible_ids = app.session.visible().to_vec(); + for id in visible_ids { + let Some(ph) = app.session.catalog.photo(id) else { continue }; + let is_selected = app.session.selection.contains(id); + if let Some((lat, lon)) = ph.meta.gps { + if let Some(coord) = LatLon::new(lat, lon) { + match filter { + LocationFilter::Untagged => {} + LocationFilter::Tagged | LocationFilter::None => { + out.push((id, coord, is_selected)); + } + LocationFilter::VisibleOnMap => { + if bounds.contains(coord) { + out.push((id, coord, is_selected)); + } + } + } + } + } else if filter == LocationFilter::Untagged || filter == LocationFilter::None { + // Untagged photo + } + } + out +} + +fn cluster_photos(photos: &[(PhotoId, LatLon, bool)], lat_lon_to_screen: F, canvas: Rect) -> Vec +where + F: Fn(LatLon) -> Pos2, +{ + let mut clusters: Vec = Vec::new(); + + for &(id, coord, is_selected) in photos { + let pos = lat_lon_to_screen(coord); + if !canvas.expand(50.0).contains(pos) { + continue; + } + + let mut merged = false; + for c in &mut clusters { + if c.center.distance(pos) <= CLUSTER_RADIUS_PTS { + c.photos.push(id); + if is_selected { + c.has_selected = true; + } + merged = true; + break; + } + } + + if !merged { + clusters.push(MapCluster { center: pos, lat_lon: coord, photos: vec![id], has_selected: is_selected }); + } + } + clusters +} + +fn render_single_pin(p: &Painter, pos: Pos2, selected: bool, hovered: bool) { + let pin_color = if selected { + Color32::from_rgb(255, 204, 0) // Yellow for selected + } else { + Color32::from_rgb(255, 115, 0) // Orange for unselected + }; + let border_color = if hovered { Color32::WHITE } else { Color32::from_black_alpha(180) }; + + // Pin head circle + let head_center = pos2(pos.x, pos.y - 12.0); + p.circle_filled(head_center, 7.0, pin_color); + p.circle_stroke(head_center, 7.0, Stroke::new(1.5, border_color)); + + // Center dot + p.circle_filled(head_center, 2.5, Color32::WHITE); + + // Pin point + p.line_segment([pos2(pos.x, pos.y - 5.0), pos], Stroke::new(2.0, pin_color)); +} + +fn render_cluster_badge(p: &Painter, pos: Pos2, count: usize, selected: bool, hovered: bool) { + let badge_color = if selected { Color32::from_rgb(255, 204, 0) } else { Color32::from_rgb(240, 100, 20) }; + let text_color = if selected { Color32::BLACK } else { Color32::WHITE }; + let border_stroke = Stroke::new(if hovered { 2.0 } else { 1.2 }, if hovered { Color32::WHITE } else { Color32::from_black_alpha(160) }); + + let label = count.to_string(); + let badge_w = (label.len() as f32 * 8.0 + 16.0).max(28.0); + let badge_rect = Rect::from_center_size(pos, vec2(badge_w, 22.0)); + + p.rect_filled(badge_rect, 11.0, badge_color); + p.rect_stroke(badge_rect, 11.0, border_stroke, StrokeKind::Inside); + p.text(pos, Align2::CENTER_CENTER, label, FontId::proportional(12.0), text_color); +} + +fn render_top_filter_bar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, map_ui: &mut crate::state::MapUi, center: LatLon) { + let t = Tokens::get(ui.ctx()); + let bar_rect = Rect::from_min_size(pos2(canvas.left() + 16.0, canvas.top() + 14.0), vec2(canvas.width() - 32.0, 36.0)); + + let bar_bg = Color32::from_rgba_unmultiplied(20, 24, 28, 220); + ui.painter().rect_filled(bar_rect, 6.0, bar_bg); + ui.painter().rect_stroke(bar_rect, 6.0, Stroke::new(1.0, t.button_border), StrokeKind::Inside); + + let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar_rect)); + bar_ui.horizontal_centered(|ui| { + ui.add_space(8.0); + ui.label(egui::RichText::new("Location Filter:").strong().color(Color32::WHITE)); + ui.add_space(8.0); + + let filters = [ + (LocationFilter::VisibleOnMap, "Visible On Map"), + (LocationFilter::Tagged, "Tagged"), + (LocationFilter::Untagged, "Untagged"), + (LocationFilter::None, "None"), + ]; + + for (f, name) in filters { + let active = map_ui.filter == f; + let btn = ui.selectable_label(active, name); + if btn.clicked() { + map_ui.filter = f; + } + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(10.0); + ui.label(egui::RichText::new(format!("{:.4}°, {:.4}°", center.lat, center.lon)).small().color(Color32::LIGHT_GRAY)); + }); + }); +} + +fn render_bottom_toolbar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, map_ui: &mut crate::state::MapUi, zoom: &mut f64) { + let t = Tokens::get(ui.ctx()); + let bar_h = 36.0; + let bar_rect = Rect::from_min_max(pos2(canvas.left(), canvas.bottom() - bar_h), canvas.max); + + ui.painter().rect_filled(bar_rect, 0.0, Color32::from_rgba_unmultiplied(16, 20, 24, 235)); + ui.painter().line_segment([pos2(bar_rect.left(), bar_rect.top()), pos2(bar_rect.right(), bar_rect.top())], Stroke::new(1.0, t.button_border)); + + let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar_rect)); + bar_ui.horizontal_centered(|ui| { + ui.add_space(12.0); + ui.label(egui::RichText::new("Map Style:").small().color(Color32::LIGHT_GRAY)); + + crate::widgets::combo_box("map_style_combo").selected_text(map_ui.provider.label()).show_ui(ui, |ui| { + for p in MapProvider::ALL { + if ui.selectable_label(map_ui.provider == p, p.label()).clicked() { + map_ui.provider = p; + } + } + }); + + ui.add_space(16.0); + if ui.button("-").clicked() { + *zoom = (*zoom - 1.0).max(1.0); + } + ui.add(egui::Slider::new(zoom, 1.0..=map_ui.provider.max_zoom() as f64).show_value(false)); + if ui.button("+").clicked() { + *zoom = (*zoom + 1.0).min(map_ui.provider.max_zoom() as f64); + } + + ui.add_space(12.0); + let lock_btn = ui.selectable_label(map_ui.locked, if map_ui.locked { "Locked (Ctrl+K)" } else { "Unlocked" }); + if lock_btn.clicked() { + map_ui.locked = !map_ui.locked; + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(12.0); + ui.label(egui::RichText::new(map_ui.provider.attribution()).small().color(Color32::from_white_alpha(150))); + }); + }); +} + +fn render_legend_overlay(ui: &mut egui::Ui, canvas: Rect, _map_ui: &mut crate::state::MapUi) { + let legend_rect = Rect::from_min_size(pos2(canvas.right() - 210.0, canvas.bottom() - 170.0), vec2(196.0, 124.0)); + let p = ui.painter(); + + p.rect_filled(legend_rect, 6.0, Color32::from_rgba_unmultiplied(20, 24, 28, 230)); + p.rect_stroke(legend_rect, 6.0, Stroke::new(1.0, Color32::from_white_alpha(40)), StrokeKind::Inside); + + let items = [ + (Color32::from_rgb(255, 115, 0), "Unselected photo"), + (Color32::from_rgb(255, 204, 0), "Selected photo"), + (Color32::from_rgb(240, 100, 20), "Group / cluster"), + ]; + + for (i, (color, text)) in items.iter().enumerate() { + let y = legend_rect.top() + 20.0 + i as f32 * 28.0; + p.circle_filled(pos2(legend_rect.left() + 20.0, y), 5.0, *color); + p.text(pos2(legend_rect.left() + 34.0, y), Align2::LEFT_CENTER, *text, FontId::proportional(11.0), Color32::WHITE); + } +} + +fn render_loupe_popover(app: &mut LightcraftApp, ui: &mut egui::Ui, pin_pos: Pos2, photo_id: PhotoId, map_ui: &mut crate::state::MapUi) { + let card_w = 230.0; + let card_h = 100.0; + let card_rect = Rect::from_min_size(pos2(pin_pos.x - card_w / 2.0, pin_pos.y - card_h - 18.0), vec2(card_w, card_h)); + + let p = ui.painter(); + p.rect_filled(card_rect, 6.0, Color32::from_rgba_unmultiplied(24, 28, 34, 245)); + p.rect_stroke(card_rect, 6.0, Stroke::new(1.2, Color32::from_white_alpha(70)), StrokeKind::Inside); + + let Some(ph) = app.session.catalog.photo(photo_id) else { return }; + let mut card_ui = ui.new_child(egui::UiBuilder::new().max_rect(card_rect)); + + card_ui.vertical(|ui| { + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(egui::RichText::new(&ph.file_name).strong().color(Color32::WHITE)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(8.0); + if ui.button("X").clicked() { + map_ui.active_pin_photo = None; + } + }); + }); + + ui.add_space(4.0); + if let Some(ref cap) = ph.captured { + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(egui::RichText::new(cap).small().color(Color32::LIGHT_GRAY)); + }); + } + + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + if ui.button("Open in Detail").clicked() { + app.ui.view = ViewMode::Detail; + } + }); + }); +} + +fn render_left_navigator( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + rect: Rect, + nav_dims: (f32, f32), + center: LatLon, + zoom: &mut f64, + map_ui: &mut crate::state::MapUi, +) { + let (left_w, nav_h) = nav_dims; + let t = Tokens::get(ui.ctx()); + let left_rect = Rect::from_min_size(rect.min, vec2(left_w, rect.height())); + + ui.painter().rect_filled(left_rect, 0.0, Color32::from_rgb(26, 30, 36)); + ui.painter() + .line_segment([pos2(left_rect.right(), left_rect.top()), pos2(left_rect.right(), left_rect.bottom())], Stroke::new(1.0, t.button_border)); + + let mut panel_ui = ui.new_child(egui::UiBuilder::new().max_rect(left_rect)); + panel_ui.vertical(|ui| { + // Navigator mini-map header + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(egui::RichText::new("Navigator").strong().color(Color32::WHITE)); + }); + + let mini_rect = Rect::from_min_size(pos2(left_rect.left() + 8.0, left_rect.top() + 32.0), vec2(left_w - 16.0, nav_h)); + ui.painter().rect_filled(mini_rect, 4.0, Color32::from_rgb(40, 50, 60)); + ui.painter().rect_stroke(mini_rect, 4.0, Stroke::new(1.0, t.button_border), StrokeKind::Inside); + + // Center dot on mini-map + ui.painter().circle_filled(mini_rect.center(), 3.0, Color32::RED); + + // Saved Locations header + ui.add_space(nav_h + 16.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(egui::RichText::new("Saved Locations").strong().color(Color32::WHITE)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(8.0); + if ui.button("+").clicked() { + let _ = app.run( + "map.savedLocations.create", + json!({ + "name": format!("Location {}", app.session.saved_locations.len() + 1), + "lat": center.lat, + "lon": center.lon, + "radius": 1500.0, + }), + ); + } + }); + }); + + ui.add_space(8.0); + egui::ScrollArea::vertical().show(ui, |ui| { + for loc in &app.session.saved_locations { + ui.horizontal(|ui| { + ui.add_space(12.0); + if ui.selectable_label(false, &loc.name).clicked() { + map_ui.center_lat = loc.lat; + map_ui.center_lon = loc.lon; + *zoom = 14.0; + } + }); + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Services; + use crate::headless::HeadlessView; + + #[test] + fn cluster_photos_merges_close_pins() { + let p1 = (PhotoId(1), LatLon::new(45.5700, -73.2000).unwrap(), false); + let p2 = (PhotoId(2), LatLon::new(45.5701, -73.2001).unwrap(), true); + let p3 = (PhotoId(3), LatLon::new(51.5074, -0.1278).unwrap(), false); + + let canvas = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 800.0)); + let lat_lon_to_screen = |coord: LatLon| -> Pos2 { + if coord.lat > 50.0 { + pos2(800.0, 600.0) // p3 + } else if coord.lat > 45.57005 { + pos2(205.0, 205.0) // p2 (distance to p1 = 7.07 < 36.0) + } else { + pos2(200.0, 200.0) // p1 + } + }; + + let clusters = cluster_photos(&[p1, p2, p3], lat_lon_to_screen, canvas); + assert_eq!(clusters.len(), 2); + assert_eq!(clusters[0].photos.len(), 2); + assert!(clusters[0].has_selected); + assert_eq!(clusters[1].photos.len(), 1); + assert!(!clusters[1].has_selected); + } + + #[test] + fn headless_map_view_renders_cleanly() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + app.ui.view = ViewMode::Map; + + let mut view = HeadlessView::new(); + let raw = HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, 0.0, vec![]); + view.run(raw, |ui| { + show(&mut app, ui); + }); + + assert_eq!(app.ui.view, ViewMode::Map); + assert_eq!(app.ui.map.provider, MapProvider::OpenStreetMap); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 203ede571e..5a688432bb 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -3,10 +3,12 @@ use serde::{Deserialize, Serialize}; mod dialog; +mod map; mod settings; mod view; pub use dialog::{Dialog, NameEdit, SyncCounts, default_preset_groups}; +pub use map::MapUi; pub use settings::{ AppSettings, AppearanceMode, DarkTheme, EditFile, EditFormat, EditSpace, GridBadges, HOT_PIXEL_LIMIT_DEFAULT, HOT_PIXEL_LIMITS, KeywordChips, LOUPE_EDGE_CEILING, LOUPE_EDGE_STEP, LaunchLibrary, LightTheme, LightroomImport, MIN_TEXTURE_SIDE, PHOTOCRAFT, PREVIEW_LIMITS, RECENT_LIBRARIES, @@ -385,6 +387,9 @@ pub struct UiState { /// The Print dialog's page, selection and drag. #[serde(skip)] pub print: crate::print_view::PrintUi, + /// The Map module's state (viewport center, zoom, provider, locked, filters). + #[serde(default)] + pub map: MapUi, } impl Default for UiState { @@ -536,6 +541,7 @@ impl Default for UiState { status: String::new(), dialog: None, print: Default::default(), + map: MapUi::default(), } } } diff --git a/crates/ui-egui/src/state/map.rs b/crates/ui-egui/src/state/map.rs new file mode 100644 index 0000000000..b4a4698067 --- /dev/null +++ b/crates/ui-egui/src/state/map.rs @@ -0,0 +1,38 @@ +use serde::{Deserialize, Serialize}; + +/// State for the Map module (viewport center, zoom, provider, locked, filters). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct MapUi { + pub center_lat: f64, + pub center_lon: f64, + pub zoom: f64, + pub provider: lightcraft_engine::map::MapProvider, + pub filter: lightcraft_engine::map::LocationFilter, + pub show_filter_bar: bool, + pub locked: bool, + pub active_pin_photo: Option, + pub tracklog_path: Option, + pub tracklog_visible: bool, + pub legend_open: bool, + pub navigator_open: bool, +} + +impl Default for MapUi { + fn default() -> Self { + Self { + center_lat: 45.57, + center_lon: -73.2, + zoom: 12.0, + provider: lightcraft_engine::map::MapProvider::OpenStreetMap, + filter: lightcraft_engine::map::LocationFilter::None, + show_filter_bar: true, + locked: false, + active_pin_photo: None, + tracklog_path: None, + tracklog_visible: true, + legend_open: true, + navigator_open: true, + } + } +} diff --git a/crates/ui-egui/src/state/view.rs b/crates/ui-egui/src/state/view.rs index 6110026475..9e5c53ff4e 100644 --- a/crates/ui-egui/src/state/view.rs +++ b/crates/ui-egui/src/state/view.rs @@ -16,6 +16,8 @@ pub enum ViewMode { Reference, /// A card per person named on faces (close-up, name, photo count). People, + /// Geographic map view plotting photos by GPS coordinates. + Map, } /// The right-hand tool/panel shown next to the tool strip. diff --git a/docs/gaps.md b/docs/gaps.md index 72ff6d72f8..e18dc325ef 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -30,7 +30,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data; main-file pages read on demand up to 16 GiB, with dense-table and WAL bounds retained (#798); offline record counts and destination are now shown in a lasting import result; catalog VIDEO records match the Videos filter, with older classification repaired on reimport; before an import the app asks whether the catalog merges into the open library or goes into a new library (opt-out in Settings, #2672); Lightroom's backup zips import directly (#2592) | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) | | 14 | **HDR display** (EDR / Windows HDR); the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read). HLG AVIF export done; the display's SDR/HDR decision is tested, blocked on eframe's 8-bit surface | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) | | 15 | **Print module**: identity plate / watermark / photo info overlays, Cut Guides for the packages, Custom Package Auto Layout, printer-driver Page Setup and direct printing, JPEG file output (the Print dialog writes a colour-managed PDF) | LRC-PRINT rows | Classic users who print | 15–25 | [target-app-parity](target-app-parity.md#features) | -| 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) | +| 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP ✅ (OSM & Esri dual-provider); BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) | | 17 | **Tethered capture** | ⬜ | studio photographers | 25–45 + cameras | [hardware-parity](hardware-parity.md) | | 18 | **Video**: playback, trim, global edits, export | VID rows 0% | users who mix stills and clips | 25–45 | [target-app-parity](target-app-parity.md#features) | | 19 | **Plug-in ecosystem**: no Lightroom SDK equivalent (export / publish plug-ins, metadata plug-ins) | ⬜ | pro workflows built on plug-ins (LR/Enfuse, Jeffrey's exporters, Negative Lab Pro) | 40–80 + owner decision | [target-app-parity](target-app-parity.md#by-dimension) | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e8dfe5525a..b907730314 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md. | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | -| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | -| **Total** | 419 | 71 | 56 | 35 | 193/203 (95%) | 147/163 (90%) | +| Lightroom Classic extras | 45 | 26 | 17 | 8 | — | 24/27 (89%) | +| **Total** | 423 | 71 | 52 | 35 | 193/203 (95%) | 147/163 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.2%** of 546 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 57.0% of 179. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **84.0%** of 546 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 59.2% of 179. ## Top gaps and shortcut notes @@ -169,7 +169,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-META-COPYRIGHT-DEFAULT | Default copyright on import | P1 | ✅ | `cmd:library.preferences` (`import.copyright`, `import.creator`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import → Metadata; fills only photos without their own | | LR-META-LOCATION | Location editing | P2 | 🟡 | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `cmd:metadata.reverseGeocode` | place fields and GPS (decimal or degrees / minutes / seconds) edited in Info, read/written as IPTC Core / Photoshop / EXIF XMP; typed GPS consumes the full expression, accepts case-insensitive axis-appropriate hemisphere markers, and refuses malformed text or DMS minutes/seconds outside [0,60) before changing metadata; Show on Map opens OpenStreetMap; Fill Location fills empty City / State / Country from GPS offline (GeoNames, downloaded on request: `cmd:metadata.downloadPlaceNames`); no embedded map | | LR-META-COPYPASTE | Copy / paste metadata | P2 | ✅ | `cmd:photo.copyMetadata`, `cmd:photo.pasteMetadata` | title, caption, alt text, extended description, copyright (notice, status, usage terms, info URL), creator, place fields, keywords; `fields` picks a subset | -| LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | manual rereading also reads sidecar-free JPEG embedded XMP (first complete standard APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; no extended assembly or between-scan packets, not strict whole-JPEG validation; reader cases in `crates/engine/src/sidecar.rs`); a discovered unreadable sidecar fails without embedded fallback; procedural refresh/undo, non-UTF-8 sidecar and two explicit malformed fixtures in `crates/engine/src/tests/xmp.rs` (file-write checks use auto-write off); sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; keywords are saved as names in `dc:subject` and paths in `lr:hierarchicalSubject` (`keywords::to_file`; before, paths went into `dc:subject`); saving merges into an existing sidecar (`crates/meta/src/xmp_merge.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte (ownership follows namespace URI: foreign namespaces using `lc:` or `xmp:` cannot supply native settings or ratings and survive saving), an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`.xmp` for all but the raw; an import ranks the files it is adding the same way, so a TIFF or JPEG arriving beside its raw reads its own `.xmp` and never the raw's `IMG_0001.xmp`, issue #1905); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934); settings Lightroom writes only for itself (`CompatibleVersion`, the profile digests, the lens profile's name / file / setup, `CropConstrainToUnitSquare`, the lens profile's strength at 100 %) are not reported as unimported (`crates/engine/src/crs.rs`); malformed XMP capture-time values remain in the raw property map and are not projected, allowing the next valid field to supply the capture time | +| LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | manual rereading also reads sidecar-free JPEG embedded XMP (first complete standard APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; no extended assembly or between-scan packets, not strict whole-JPEG validation; reader cases in `crates/engine/src/sidecar.rs`); a discovered unreadable sidecar fails without embedded fallback; procedural refresh/undo, non-UTF-8 sidecar and two explicit malformed fixtures in `crates/engine/src/tests/xmp.rs` (file-write checks use auto-write off); sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; keywords are saved as names in `dc:subject` and paths in `lr:hierarchicalSubject` (`keywords::to_file`; before, paths went into `dc:subject`); saving merges into an existing sidecar (`crates/meta/src/lib.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte (ownership follows namespace URI: foreign namespaces using `lc:` or `xmp:` cannot supply native settings or ratings and survive saving), an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`.xmp` for all but the raw; an import ranks the files it is adding the same way, so a TIFF or JPEG arriving beside its raw reads its own `.xmp` and never the raw's `IMG_0001.xmp`, issue #1905); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934); settings Lightroom writes only for itself (`CompatibleVersion`, the profile digests, the lens profile's name / file / setup, `CropConstrainToUnitSquare`, the lens profile's strength at 100 %) are not reported as unimported (`crates/engine/src/crs.rs`); malformed XMP capture-time values remain in the raw property map and are not projected, allowing the next valid field to supply the capture time | | LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | `photo.allMetadata` reuses loaded original bytes for embedded XMP and keeps sidecar precedence (`crates/engine/src/tests/xmp.rs`); read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; PSD/PSB EXIF resource 1058 and XMP resource 1060 feed the same metadata rows and preserve sidecar precedence; metadata presets; malformed EXIF clocks with extra components are rejected so valid DateTimeDigitized, IFD0 DateTime or XMP fallbacks apply, while raw values stay visible in All Metadata (`crates/meta/src/exif.rs`, `crates/engine/src/tests/import.rs`) | ## F. Edit panel — global adjustments (EDIT) @@ -737,11 +737,11 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | | LRC-DEV-HISTOGRAM-DRAG | Drag on the histogram to adjust tone regions | P2 | ✅ | `crates/ui-egui/src/panels/histogram.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/develop/src/controls.rs`, `crates/ui-egui/src/tests/histogram_drag.rs`, `cmd:develop.set`, `cmd:develop.beginInteraction`, `cmd:develop.endInteraction`, `ctl:light.blacks`, `ctl:light.shadows`, `ctl:light.exposure`, `ctl:light.highlights`, `ctl:light.whites` | five zones across the plot's width, each moving the Basic control it names: Blacks 0.00–0.15, Shadows 0.15–0.35, Exposure 0.35–0.65, Highlights 0.65–0.85, Whites 0.85–1.00; every step is a `develop.set` between `develop.beginInteraction` and `develop.endInteraction` (the sliders' own path), so the draft render follows the drag live and the whole drag lands as one undo step; the zone the press landed in stays locked for the drag, so dragging across the others changes nothing; sideways travel of the plot's width sweeps that control's whole range (Shift a tenth, as on the sliders), clamped to its spec; hovering a zone tints it and shows its value in the strip under the plot ("Exposure: +0.45 EV"), with the sideways-resize cursor; a double-click resets that zone's control to its default in one undo step; the strip under the plot (readout / EXIF) and the clipping buttons in the plot's top corners are not zones | -| LRC-MAP-VIEW | Map view | P2 | ⬜ | | | -| LRC-MAP-GEOTAG | Drag photos onto the map | P2 | ⬜ | | | -| LRC-MAP-LOCATIONS | Saved locations | P2 | ⬜ | | | -| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `crates/meta/src/gpx.rs` | Photo ▸ Auto-Tag from Tracklog…: a GPX 1.0 / 1.1 track log sets the GPS of the selected photos by capture time — interpolated between the points of a track segment, else the nearest point within `maxGap` (10 min); never across segment breaks. XML character references in coordinate attributes and point text decode before parsing; malformed or unknown references return an error; CDATA stays literal. The camera's time zone comes from the photo (Exif offset) or is asked for; photos that already have a location keep it unless `replace`; `dryRun` previews; one undo step. No track drawn on a map (no Map module); incomplete or malformed ISO point times are untimed and cannot match a photo | -| LRC-MAP-FILTER | Location filter bar | P2 | ⬜ | | | +| LRC-MAP-VIEW | Map view | P2 | ✅ | `cmd:view.map`, `cmd:map.providers`, `cmd:map.savedLocations.list`, `cmd:map.savedLocations.create`, `cmd:map.savedLocations.delete`, `cmd:map.filterPhotos`, `cmd:photo.setGps`, `cmd:photo.clearGps`, `crates/geom/src/geo.rs`, `crates/engine/src/map.rs`, `crates/ui-egui/src/panels/map.rs` | Interactive slippy map canvas supporting OpenStreetMap (OSM) and Esri ArcGIS Location Platform (World Imagery, World Street, World Topo, Hybrid); photo marker clustering with cluster badges and count; single-pin selection & loupe popover; top location filter bar (Visible On Map, Tagged, Untagged, None); bottom toolbar with provider style dropdown, zoom slider, lock toggle, and dynamic tile attribution; left navigator mini-map and saved locations panel; keyboard shortcut Ctrl+Alt+3 | +| LRC-MAP-GEOTAG | Drag photos onto the map | P2 | ✅ | `cmd:photo.setGps`, `cmd:photo.clearGps`, `crates/engine/src/cmd/map.rs`, `crates/ui-egui/src/panels/map.rs` | Tag photos by dropping or setting latitude/longitude coordinates; undo/redo support; clears GPS via `photo.clearGps` | +| LRC-MAP-LOCATIONS | Saved locations | P2 | ✅ | `cmd:map.savedLocations.list`, `cmd:map.savedLocations.create`, `cmd:map.savedLocations.delete`, `crates/engine/src/map.rs`, `crates/ui-egui/src/panels/map.rs` | Saved locations panel in left navigator; define named areas with center lat/lon and radius; click to pan/zoom map to location | +| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `crates/meta/src/lib.rs` | Photo ▸ Auto-Tag from Tracklog…: a GPX 1.0 / 1.1 track log sets the GPS of the selected photos by capture time — interpolated between the points of a track segment, else the nearest point within `maxGap` (10 min); never across segment breaks. XML character references in coordinate attributes and point text decode before parsing; malformed or unknown references return an error; CDATA stays literal. The camera's time zone comes from the photo (Exif offset) or is asked for; photos that already have a location keep it unless `replace`; `dryRun` previews; one undo step. No track drawn on a map (no Map module); incomplete or malformed ISO point times are untimed and cannot match a photo | +| LRC-MAP-FILTER | Location filter bar | P2 | ✅ | `cmd:map.filterPhotos`, `cmd:view.toggleMapFilter`, `crates/engine/src/map.rs`, `crates/ui-egui/src/panels/map.rs` | Location filter bar with Visible On Map, Tagged, Untagged, and None filter modes with live center coordinate readout | | LRC-MAP-REVGEO | Reverse geocoding | P2 | 🟡 | `cmd:metadata.reverseGeocode` | offline from GeoNames (City / State / Country, no sublocation); the list holds towns of 15 000 people or more, so a smaller town gets the nearest larger one (the tooltip and command help say so); `maxDistance` leaves City empty past a distance and names the town as `nearestCity` (issue #2242); no online provider | | LRC-BOOK-SETTINGS | Book settings | P2 | ⬜ | | | | LRC-BOOK-AUTOLAYOUT | Book auto layout | P2 | ⬜ | | |