From cb8a35bb60c68877404ef94f2834a58e12e9c52f Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 00:01:27 -0500 Subject: [PATCH 01/51] 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 | ⬜ | | | From 31e3cdf63cf83431d670bdb82e3ab33eeece8fd0 Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 00:19:35 -0500 Subject: [PATCH 02/51] LRC-MAP-VIEW: asynchronous map tile downloading, decoding and texture rendering --- crates/engine/src/map.rs | 59 +++++++++++++++- crates/engine/src/tests/map.rs | 11 +++ crates/ui-egui/src/panels/map.rs | 115 ++++++++++++++++++++++++++++--- 3 files changed, 173 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/map.rs b/crates/engine/src/map.rs index 533186c2e2..a50a71c7b5 100644 --- a/crates/engine/src/map.rs +++ b/crates/engine/src/map.rs @@ -5,7 +5,7 @@ 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)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum MapProvider { /// OpenStreetMap standard cartographic style. @@ -161,15 +161,70 @@ impl LocationFilter { } } +/// Base directory for caching downloaded map tiles locally. +pub fn tile_cache_dir() -> PathBuf { + crate::config::config_dir().map(|d| d.join("map-tiles")).unwrap_or_else(|| std::env::temp_dir().join("lightcraft-tiles")) +} + /// 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 { + let ext = match provider { + MapProvider::EsriImagery => "jpg", + MapProvider::EsriHybrid if layer_index == 0 => "jpg", + _ => "png", + }; 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)) + .join(format!("{}.{ext}", coord.y)) +} + +/// Pure-Rust network fetch for a map tile. +#[cfg(not(target_arch = "wasm32"))] +pub fn fetch_tile_bytes(url_str: &str) -> std::result::Result, String> { + use lightcraft_fetch::http::{Limits, Url}; + use std::sync::atomic::AtomicBool; + use std::time::Duration; + + let url = Url::parse(url_str).map_err(|e| format!("invalid tile url: {e}"))?; + let headers = [ + ("User-Agent", "LightCraft/0.9 (https://github.com/storytold/lightcraft; photo-editor)".to_string()), + ("Accept", "image/png,image/jpeg,image/*,*/*".to_string()), + ]; + let cancel = AtomicBool::new(false); + let limits = Limits { connect: Duration::from_secs(6), stall: Duration::from_secs(12), cancel: &cancel }; + let mut resp = lightcraft_fetch::http::get(&url, &headers, &limits).map_err(|e| format!("fetch tile failed: {e}"))?; + if resp.status != 200 { + return Err(format!("fetch tile HTTP {}", resp.status)); + } + let mut bytes = Vec::with_capacity(resp.content_length().unwrap_or(32 * 1024) as usize); + let mut buf = [0u8; 8192]; + loop { + let n = resp.read(&mut buf, &limits).map_err(|e| format!("read tile stream: {e}"))?; + if n == 0 { + break; + } + bytes.extend_from_slice(buf.get(..n).unwrap_or_default()); + if bytes.len() > 2 * 1024 * 1024 { + return Err("tile size exceeds 2 MiB".into()); + } + } + Ok(bytes) +} + +#[cfg(target_arch = "wasm32")] +pub fn fetch_tile_bytes(_url_str: &str) -> std::result::Result, String> { + Err("tile fetching on web is not implemented via sync engine".into()) +} + +/// Decodes tile PNG or JPEG bytes into 8-bit RGBA raster pixels. +pub fn decode_tile(bytes: &[u8]) -> std::result::Result { + let opts = lightcraft_codecs::DecodeOptions::default(); + let decoded = lightcraft_codecs::decode(bytes, opts).map_err(|e| format!("decode tile: {e}"))?; + Ok(decoded.to_srgb8()) } #[cfg(test)] diff --git a/crates/engine/src/tests/map.rs b/crates/engine/src/tests/map.rs index a7d7ded55d..c32b58b092 100644 --- a/crates/engine/src/tests/map.rs +++ b/crates/engine/src/tests/map.rs @@ -113,3 +113,14 @@ fn test_map_filter_photos() { 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))); } + +#[test] +fn test_tile_fetch_and_decode() { + let esri_url = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/6/25/31"; + if let Ok(b) = crate::map::fetch_tile_bytes(esri_url) { + assert!(!b.is_empty()); + let decoded = crate::map::decode_tile(&b).unwrap(); + assert_eq!(decoded.width, 256); + assert_eq!(decoded.height, 256); + } +} diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 7feb1f0b99..32bd3cdda0 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -1,10 +1,14 @@ //! 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 std::collections::{HashMap, HashSet}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Mutex, PoisonError}; + +use egui::{Align2, Color32, ColorImage, FontId, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, TextureHandle, TextureOptions, pos2, vec2}; use lightcraft_catalog::PhotoId; use lightcraft_engine::map::{LocationFilter, MapProvider}; -use lightcraft_geom::{GeoBounds, LatLon}; +use lightcraft_geom::{GeoBounds, LatLon, TileCoord}; use serde_json::json; use crate::LightcraftApp; @@ -17,6 +21,31 @@ 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; +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct TileKey { + provider: MapProvider, + z: u8, + x: u32, + y: u32, + layer: u8, +} + +struct TileStore { + textures: HashMap, + pending: HashSet, + tx: Sender<(TileKey, ColorImage)>, + rx: Receiver<(TileKey, ColorImage)>, +} + +impl TileStore { + fn new() -> Self { + let (tx, rx) = channel(); + Self { textures: HashMap::new(), pending: HashSet::new(), tx, rx } + } +} + +static TILES: Mutex> = Mutex::new(None); + /// Represents a clustered group of photos on the map screen. struct MapCluster { center: Pos2, @@ -179,6 +208,35 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.map = map_ui; } +fn fetch_and_cache_tile(key: TileKey, url: String, disk_path: std::path::PathBuf, tx: Sender<(TileKey, ColorImage)>, ctx: egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + let _ = std::thread::Builder::new().name("lc-tile-fetch".into()).spawn(move || { + let bytes = if disk_path.exists() { + std::fs::read(&disk_path).ok() + } else { + match lightcraft_engine::map::fetch_tile_bytes(&url) { + Ok(b) => { + if let Some(parent) = disk_path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let _ = std::fs::write(&disk_path, &b); + Some(b) + } + Err(e) => { + log::debug!("tile fetch error for {url}: {e}"); + None + } + } + }; + + if let Some(rgba) = bytes.and_then(|b| lightcraft_engine::map::decode_tile(&b).ok()) { + let img = egui::ColorImage::from_rgba_unmultiplied([rgba.width, rgba.height], &rgba.as_bytes()); + let _ = tx.send((key, img)); + ctx.request_repaint(); + } + }); +} + 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); @@ -200,20 +258,57 @@ fn render_tile_grid(p: &Painter, canvas: Rect, center_pos: Pos2, center_tx: f64, _ => Color32::from_rgba_unmultiplied(80, 90, 100, 120), }; + let mut store_guard = TILES.lock().unwrap_or_else(PoisonError::into_inner); + let store = store_guard.get_or_insert_with(TileStore::new); + + while let Ok((key, img)) = store.rx.try_recv() { + let name = format!("tile-{}-{}-{}-{}-{}", key.provider.id(), key.layer, key.z, key.x, key.y); + let tex = p.ctx().load_texture(name, img, TextureOptions::LINEAR); + store.textures.insert(key, tex); + store.pending.remove(&key); + } + + if store.textures.len() > 300 { + store.textures.retain(|k, _| k.provider == provider && (k.z as i32 - int_zoom as i32).abs() <= 1); + } + + let cache_root = lightcraft_engine::map::tile_cache_dir(); + 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, - ); + let coord = TileCoord::new(int_zoom, x as u32, y as u32); + let urls = provider.tile_urls(coord); + let mut all_loaded = true; + + for (layer_idx, url) in urls.into_iter().enumerate() { + let key = TileKey { provider, z: int_zoom, x: x as u32, y: y as u32, layer: layer_idx as u8 }; + + if let Some(tex) = store.textures.get(&key) { + p.image(tex.id(), tile_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } else { + all_loaded = false; + if !store.pending.contains(&key) { + store.pending.insert(key); + let disk_path = lightcraft_engine::map::tile_cache_path(&cache_root, provider, coord, layer_idx); + fetch_and_cache_tile(key, url, disk_path, store.tx.clone(), p.ctx().clone()); + } + } + } + + if !all_loaded { + 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, + ); + } } } } From 192a9f19805d87b18edd3f86d824c6a8eae695fe Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 00:37:07 -0500 Subject: [PATCH 03/51] LRC-MAP-VIEW: fix continuous zoom coordinate math and cursor-anchored zooming --- crates/geom/src/geo.rs | 12 ++-- crates/ui-egui/src/panels/map.rs | 120 +++++++++++++++++++++---------- 2 files changed, 89 insertions(+), 43 deletions(-) diff --git a/crates/geom/src/geo.rs b/crates/geom/src/geo.rs index b23c30646f..11fdfa6017 100644 --- a/crates/geom/src/geo.rs +++ b/crates/geom/src/geo.rs @@ -55,10 +55,9 @@ impl LatLon { (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); + /// Convert continuous tile coordinates back to `LatLon` at zoom `zoom`. + pub fn from_tile_coords(x: f64, y: f64, zoom: f64) -> Self { + let n = 2.0_f64.powf(zoom.clamp(0.0, 24.0)); 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); @@ -184,8 +183,9 @@ mod tests { ]; for p in points { - for zoom in 0..=18 { - let (x, y) = p.to_tile_coords(zoom as f64); + for zoom_step in 0..=36 { + let zoom = zoom_step as f64 * 0.5; + let (x, y) = p.to_tile_coords(zoom); 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); diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 32bd3cdda0..d6632c4268 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -79,51 +79,67 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { }; painter.rect_filled(canvas_rect, 0.0, bg_color); + let screen_center = canvas_rect.center(); + + let lat_lon_to_screen = |coord: LatLon, cur_zoom: f64, cur_center: LatLon| -> Pos2 { + let (c_tx, c_ty) = cur_center.to_tile_coords(cur_zoom); + let (tx, ty) = coord.to_tile_coords(cur_zoom); + pos2(screen_center.x + ((tx - c_tx) * TILE_SIZE as f64) as f32, screen_center.y + ((ty - c_ty) * TILE_SIZE as f64) as f32) + }; + + let screen_to_lat_lon = |screen_pos: Pos2, cur_zoom: f64, cur_center: LatLon| -> LatLon { + let (c_tx, c_ty) = cur_center.to_tile_coords(cur_zoom); + let tx = c_tx + (screen_pos.x - screen_center.x) as f64 / TILE_SIZE as f64; + let ty = c_ty + (screen_pos.y - screen_center.y) as f64 / TILE_SIZE as f64; + LatLon::from_tile_coords(tx, ty, cur_zoom) + }; + // 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 n = 2.0_f64.powf(zoom.clamp(0.0, 24.0)); 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); + center = LatLon::from_tile_coords(cur_tx, cur_ty, zoom); } - // Scroll wheel zoom + // Scroll wheel zoom anchored to cursor 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); + let double_click = canvas_response.double_clicked(); + let delta_zoom = if double_click { + 1.0 + } else if scroll.abs() > 0.5 { + scroll as f64 * 0.005 + } else { + 0.0 + }; + + if delta_zoom != 0.0 { + let max_z = map_ui.provider.max_zoom() as f64; + let new_zoom = (zoom + delta_zoom).clamp(1.0, max_z); + if let Some(pointer_pos) = ui.input(|i| i.pointer.hover_pos()).filter(|&pos| canvas_rect.contains(pos)) { + let mouse_geo = screen_to_lat_lon(pointer_pos, zoom, center); + let (m_tx, m_ty) = mouse_geo.to_tile_coords(new_zoom); + let n = 2.0_f64.powf(new_zoom.clamp(0.0, 24.0)); + let new_center_tx = (m_tx - (pointer_pos.x - screen_center.x) as f64 / TILE_SIZE as f64).rem_euclid(n); + let new_center_ty = (m_ty - (pointer_pos.y - screen_center.y) as f64 / TILE_SIZE as f64).clamp(0.0, n); + center = LatLon::from_tile_coords(new_center_tx, new_center_ty, new_zoom); + } + zoom = new_zoom; } } - // 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); + render_tile_grid(&painter, canvas_rect, screen_center, center, 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); + let candidate_photos = collect_photos(app, map_ui.filter, |p| screen_to_lat_lon(p, zoom, center), canvas_rect); + let clusters = cluster_photos(&candidate_photos, |coord| lat_lon_to_screen(coord, zoom, center), canvas_rect); // 3. Render Clusters and Markers let mut clicked_photo = None; @@ -176,7 +192,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { 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); + let pin_pos = lat_lon_to_screen(coord, zoom, center); if canvas_rect.contains(pin_pos) { render_loupe_popover(app, ui, pin_pos, active_id, &mut map_ui); } @@ -237,16 +253,17 @@ fn fetch_and_cache_tile(key: TileKey, url: String, disk_path: std::path::PathBuf }); } -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; +fn render_tile_grid(p: &Painter, canvas: Rect, center_pos: Pos2, center: LatLon, zoom: f64, provider: MapProvider) { + let int_zoom = (zoom.floor() as u8).min(provider.max_zoom()); + let scale = 2.0_f64.powf(zoom - int_zoom as f64); + let tile_screen_size = (TILE_SIZE as f64 * scale) as f32; + let (center_int_tx, center_int_ty) = center.to_tile_coords(int_zoom as f64); 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 min_x = ((center_int_tx - (center_pos.x - canvas.left()) as f64 / tile_screen_size as f64).floor() as i64).max(0); + let max_x = ((center_int_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_int_ty - (center_pos.y - canvas.top()) as f64 / tile_screen_size as f64).floor() as i64).max(0); + let max_y = ((center_int_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)), @@ -276,8 +293,8 @@ fn render_tile_grid(p: &Painter, canvas: Rect, center_pos: Pos2, center_tx: f64, 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 left = center_pos.x + ((x as f64 - center_int_tx) * tile_screen_size as f64) as f32; + let top = center_pos.y + ((y as f64 - center_int_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)); let coord = TileCoord::new(int_zoom, x as u32, y as u32); @@ -672,4 +689,33 @@ mod tests { assert_eq!(app.ui.view, ViewMode::Map); assert_eq!(app.ui.map.provider, MapProvider::OpenStreetMap); } + + #[test] + fn continuous_zoom_and_pan_preserves_coordinates() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + app.ui.view = ViewMode::Map; + app.ui.map.center_lat = 45.57; + app.ui.map.center_lon = -73.2; + app.ui.map.zoom = 10.35; + + let mut view = HeadlessView::new(); + let mut raw = HeadlessView::raw_input(vec2(1000.0, 700.0), 1.0, 0.0, vec![]); + raw.events.push(egui::Event::PointerMoved(pos2(500.0, 350.0))); + raw.events.push(egui::Event::PointerButton { + pos: pos2(500.0, 350.0), + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::default(), + }); + raw.events.push(egui::Event::PointerMoved(pos2(550.0, 370.0))); + + view.run(raw, |ui| { + show(&mut app, ui); + }); + + assert!(app.ui.map.center_lat.is_finite()); + assert!(app.ui.map.center_lon.is_finite()); + assert!((app.ui.map.center_lat - 45.57).abs() < 1.0); + assert!((app.ui.map.center_lon - (-73.2)).abs() < 1.0); + } } From 565419284ef1f0d6e20ffc807041f29dee2c90fb Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 00:54:11 -0500 Subject: [PATCH 04/51] LRC-MAP-VIEW: fix saved locations navigation and implement interactive navigator mini-map --- crates/ui-egui/src/panels/map.rs | 179 ++++++++++++++++++++++++++++--- 1 file changed, 163 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index d6632c4268..8e147010f3 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -199,6 +199,22 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } + // 4.5. Render active / matching saved location boundary circle + for loc in &app.session.saved_locations { + if (loc.lat - center.lat).abs() < 0.0001 && (loc.lon - center.lon).abs() < 0.0001 { + let loc_coord = LatLon { lat: loc.lat, lon: loc.lon }; + let screen_pos = lat_lon_to_screen(loc_coord, zoom, center); + let meters_per_px = (40075016.686 * (loc.lat.to_radians().cos().abs())) / (256.0 * 2.0_f64.powf(zoom)); + if meters_per_px > 0.0 { + let radius_px = (loc.radius / meters_per_px) as f32; + if radius_px > 4.0 && radius_px < 8000.0 { + painter.circle_filled(screen_pos, radius_px, Color32::from_rgba_unmultiplied(255, 204, 0, 20)); + painter.circle_stroke(screen_pos, radius_px, Stroke::new(1.5, Color32::from_rgba_unmultiplied(255, 204, 0, 160))); + } + } + } + } + // 5. Top Location Filter Bar & Breadcrumb if map_ui.show_filter_bar { render_top_filter_bar(app, ui, canvas_rect, &mut map_ui, center); @@ -214,7 +230,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::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); + render_left_navigator(app, ui, (rect, canvas_rect), (left_w, navigator_h), &mut center, &mut zoom, &mut map_ui); } // Update persistent state @@ -574,15 +590,34 @@ fn render_loupe_popover(app: &mut LightcraftApp, ui: &mut egui::Ui, pin_pos: Pos }); } +fn zoom_from_radius(radius_meters: f64) -> f64 { + if radius_meters <= 300.0 { + 16.5 + } else if radius_meters <= 800.0 { + 15.5 + } else if radius_meters <= 2000.0 { + 14.0 + } else if radius_meters <= 5000.0 { + 12.5 + } else if radius_meters <= 15000.0 { + 11.0 + } else if radius_meters <= 50000.0 { + 9.5 + } else { + 8.0 + } +} + fn render_left_navigator( app: &mut LightcraftApp, ui: &mut egui::Ui, - rect: Rect, + rects: (Rect, Rect), nav_dims: (f32, f32), - center: LatLon, + center: &mut LatLon, zoom: &mut f64, map_ui: &mut crate::state::MapUi, ) { + let (rect, canvas_rect) = rects; 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())); @@ -600,21 +635,76 @@ fn render_left_navigator( 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.add_space(4.0); + let mini_w = left_w - 16.0; + let mini_rect = Rect::from_min_size(pos2(left_rect.left() + 8.0, ui.cursor().top()), vec2(mini_w, nav_h)); + let nav_resp = ui.allocate_rect(mini_rect, Sense::click_and_drag()); + + let nav_zoom = (*zoom - 3.5).clamp(1.0, (map_ui.provider.max_zoom() - 2) as f64); + + if nav_resp.dragged() { + let delta = nav_resp.drag_delta(); + let delta_tx = delta.x as f64 / TILE_SIZE as f64; + let delta_ty = delta.y as f64 / TILE_SIZE as f64; + let n = 2.0_f64.powf(nav_zoom.clamp(0.0, 24.0)); + let (cur_tx, cur_ty) = center.to_tile_coords(nav_zoom); + let new_tx = (cur_tx + delta_tx).rem_euclid(n); + let new_ty = (cur_ty + delta_ty).clamp(0.0, n); + *center = LatLon::from_tile_coords(new_tx, new_ty, nav_zoom); + ui.ctx().request_repaint(); + } else if nav_resp.clicked() + && let Some(pos) = nav_resp.interact_pointer_pos() + { + let offset_x = pos.x - mini_rect.center().x; + let offset_y = pos.y - mini_rect.center().y; + let delta_tx = offset_x as f64 / TILE_SIZE as f64; + let delta_ty = offset_y as f64 / TILE_SIZE as f64; + let n = 2.0_f64.powf(nav_zoom.clamp(0.0, 24.0)); + let (cur_tx, cur_ty) = center.to_tile_coords(nav_zoom); + let new_tx = (cur_tx + delta_tx).rem_euclid(n); + let new_ty = (cur_ty + delta_ty).clamp(0.0, n); + *center = LatLon::from_tile_coords(new_tx, new_ty, nav_zoom); + ui.ctx().request_repaint(); + } + + if nav_resp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll.abs() > 0.5 { + let max_z = map_ui.provider.max_zoom() as f64; + *zoom = (*zoom + (scroll as f64 * 0.005)).clamp(1.0, max_z); + ui.ctx().request_repaint(); + } + } + + let nav_painter = ui.painter().with_clip_rect(mini_rect); + nav_painter.rect_filled(mini_rect, 4.0, Color32::from_rgb(18, 22, 26)); + + // Render overview map tiles + render_tile_grid(&nav_painter, mini_rect, mini_rect.center(), *center, nav_zoom, map_ui.provider); + + // Viewport rectangle showing the visible area on the main map + let scale_diff = 2.0_f64.powf(nav_zoom - *zoom); + let box_w = (canvas_rect.width() as f64 * scale_diff) as f32; + let box_h = (canvas_rect.height() as f64 * scale_diff) as f32; + let box_w_clamped = box_w.clamp(6.0, mini_rect.width() * 1.5); + let box_h_clamped = box_h.clamp(6.0, mini_rect.height() * 1.5); + let view_rect = Rect::from_center_size(mini_rect.center(), vec2(box_w_clamped, box_h_clamped)); + + nav_painter.rect_filled(view_rect, 1.0, Color32::from_white_alpha(35)); + nav_painter.rect_stroke(view_rect, 1.0, Stroke::new(1.5, Color32::WHITE), StrokeKind::Middle); + nav_painter.circle_filled(mini_rect.center(), 2.0, Color32::from_rgb(255, 204, 0)); + + // Frame 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.add_space(14.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() { + if ui.button("+").on_hover_text("Save current map location").clicked() { let _ = app.run( "map.savedLocations.create", json!({ @@ -629,18 +719,40 @@ fn render_left_navigator( }); ui.add_space(8.0); + let mut delete_id = None; egui::ScrollArea::vertical().show(ui, |ui| { - for loc in &app.session.saved_locations { + if app.session.saved_locations.is_empty() { 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; - } + ui.label(egui::RichText::new("No saved locations. Click + to save.").small().italics().color(Color32::GRAY)); }); + } else { + for loc in &app.session.saved_locations { + let is_active = (loc.lat - center.lat).abs() < 0.0001 && (loc.lon - center.lon).abs() < 0.0001; + ui.horizontal(|ui| { + ui.add_space(8.0); + let resp = ui.selectable_label(is_active, &loc.name); + if resp.clicked() + && let Some(target) = LatLon::new(loc.lat, loc.lon) + { + *center = target; + *zoom = zoom_from_radius(loc.radius); + ui.ctx().request_repaint(); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(8.0); + if ui.small_button("✕").on_hover_text("Delete location").clicked() { + delete_id = Some(loc.id.clone()); + } + }); + }); + } } }); + if let Some(id) = delete_id { + let _ = app.run("map.savedLocations.delete", json!({"id": id})); + ui.ctx().request_repaint(); + } }); } @@ -718,4 +830,39 @@ mod tests { assert!((app.ui.map.center_lat - 45.57).abs() < 1.0); assert!((app.ui.map.center_lon - (-73.2)).abs() < 1.0); } + + #[test] + fn saved_location_selection_updates_map_center() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + app.ui.view = ViewMode::Map; + app.ui.map.center_lat = 0.0; + app.ui.map.center_lon = 0.0; + app.ui.map.zoom = 5.0; + + let _ = app.run( + "map.savedLocations.create", + json!({ + "name": "Beloeil", + "lat": 45.57, + "lon": -73.2, + "radius": 1500.0, + }), + ); + + 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.session.saved_locations.len(), 1); + let loc = &app.session.saved_locations[0]; + app.ui.map.center_lat = loc.lat; + app.ui.map.center_lon = loc.lon; + app.ui.map.zoom = zoom_from_radius(loc.radius); + + assert_eq!(app.ui.map.center_lat, 45.57); + assert_eq!(app.ui.map.center_lon, -73.2); + assert_eq!(app.ui.map.zoom, 14.0); + } } From 27c9ced5f6a0eb45a65614b4de3382e97c9efb12 Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 01:14:12 -0500 Subject: [PATCH 05/51] LRC-MAP-VIEW: persist saved locations in prefs, add show in map to Photo and context menus, add Map submenu to Window --- crates/engine/src/cmd/map.rs | 2 ++ crates/engine/src/library.rs | 5 +++ crates/ui-egui/src/menus.rs | 2 ++ crates/ui-egui/src/menus/menubar.rs | 8 ++++- crates/ui-egui/src/menus/menubar/tests.rs | 44 +++++++++++++++++++++++ crates/ui-egui/src/menus/run.rs | 34 ++++++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 6 ++++ crates/ui-egui/src/panels/grid.rs | 3 ++ 8 files changed, 100 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/map.rs b/crates/engine/src/cmd/map.rs index c8e6d41406..5c59ff9c23 100644 --- a/crates/engine/src/cmd/map.rs +++ b/crates/engine/src/cmd/map.rs @@ -65,6 +65,7 @@ pub fn specs() -> Vec { 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()); + let _ = s.save_prefs(); Ok(json!(loc)) } ), @@ -83,6 +84,7 @@ pub fn specs() -> Vec { if s.saved_locations.len() == before_len { return Err(bad(C, format!("saved location `{id}` not found"))); } + let _ = s.save_prefs(); Ok(json!({ "deleted": true })) } ), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 261ef52eec..2aed6e7ccd 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -335,6 +335,9 @@ struct PrefsFile { slide_titles: crate::slide_title::TitleSettings, /// A view holds the photos it shows until it is refreshed (`library.holdView`). hold_view: bool, + /// User-saved map locations. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + saved_locations: Vec, } fn presets_json(s: &Session) -> String { @@ -652,6 +655,7 @@ impl Session { self.slide_titles = prefs.slide_titles.sanitized(); self.forget_local_days = prefs.forget_local_days.unwrap_or(lightcraft_catalog::DEFAULT_FORGET_DAYS); self.hold_view = prefs.hold_view; + self.saved_locations = prefs.saved_locations; self.refresh_view(); self.smart_previews_dir = prefs.smart_previews_dir.filter(|_| on_disk).map(PathBuf::from); if let Some(d) = &self.smart_previews_dir { @@ -973,6 +977,7 @@ impl Session { slide_overlays: self.slide_overlays.clone(), slide_titles: self.slide_titles.clone(), hold_view: self.hold_view, + saved_locations: self.saved_locations.clone(), }) .unwrap_or_default(); let Some(lib) = self.library.as_mut() else { return Ok(()) }; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b6b6c66c52..5d39f427a2 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -37,6 +37,8 @@ pub fn ui_enabled(app: &LightcraftApp, id: &str) -> bool { "dialog.slideshowExport" | "app.slideshowExport" => { !cfg!(target_arch = "wasm32") && !app.session.slideshow_export.as_ref().is_some_and(|r| r.running()) } + "photo.showInMap" => app.session.active().is_some(), + "panel.map" | "map.navigator" | "map.filterBar" | "map.legend" | "map.lock" => true, s if s.starts_with("panel.") || s.starts_with("tool.") || s.starts_with("section.") => app.session.active().is_some() || s == "panel.close", "app.export" | "dialog.export" | "dialog.createPreset" | "dialog.rename" | "dialog.captureTime" | "dialog.copySettings" => { app.session.active().is_some() diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 29723abbb6..2c77f257e6 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -281,6 +281,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "photo.readFocusPoints", "app.showInFinder", "app.showInFolders", + "photo.showInMap", "dialog.rename", "dialog.captureTime", "photo.tagFromTracklog", @@ -309,6 +310,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "---", "@Edit Sections", "@Tools", + "@Map", ], ), ( @@ -404,7 +406,11 @@ 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.map" | "panel.map" => Some(u.view == ViewMode::Map), + "map.navigator" => Some(u.map.navigator_open), + "map.filterBar" | "view.toggleMapFilter" => Some(u.map.show_filter_bar), + "map.legend" => Some(u.map.legend_open), + "map.lock" | "map.toggleLock" => Some(u.map.locked), "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/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index cc3c5c4b0f..6c48d25668 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -852,3 +852,47 @@ fn edit_menu_places_the_select_and_paste_rows_with_their_kin() { let after = &nodes[pos("app.settings") + 1..]; assert!(!after.iter().any(|n| matches!(n, MenuNode::Item { .. })), "no row follows Settings… but a submenu: {after:?}"); } + +/// Show in Map is present in Photo menu and Window contains a Map submenu with map controls. +#[test] +fn show_in_map_and_window_map_menu() { + let mut a = app(); + let bar = menu_bar(&a); + + // Verify photo.showInMap is in Photo menu + let photo_nodes = &bar.iter().find(|(title, _)| title == "Photo").unwrap().1; + assert!(find(photo_nodes, "photo.showInMap").is_some(), "photo.showInMap must be in Photo menu"); + + // Verify @Map is in Window menu and has items + let window_nodes = &bar.iter().find(|(title, _)| title == "Window").unwrap().1; + assert!(find(window_nodes, "panel.map").is_some(), "panel.map must be in Window>Map"); + assert!(find(window_nodes, "map.navigator").is_some(), "map.navigator must be in Window>Map"); + assert!(find(window_nodes, "map.filterBar").is_some(), "map.filterBar must be in Window>Map"); + assert!(find(window_nodes, "map.legend").is_some(), "map.legend must be in Window>Map"); + assert!(find(window_nodes, "map.lock").is_some(), "map.lock must be in Window>Map"); + + // Test running map.navigator toggles navigator_open + let nav_before = a.ui.map.navigator_open; + run_item(&mut a, "map.navigator", Value::Null).unwrap(); + assert_eq!(a.ui.map.navigator_open, !nav_before); + + // Test running map.filterBar toggles show_filter_bar + let bar_before = a.ui.map.show_filter_bar; + run_item(&mut a, "map.filterBar", Value::Null).unwrap(); + assert_eq!(a.ui.map.show_filter_bar, !bar_before); + + // Test running map.legend toggles legend_open + let legend_before = a.ui.map.legend_open; + run_item(&mut a, "map.legend", Value::Null).unwrap(); + assert_eq!(a.ui.map.legend_open, !legend_before); + + // Test running map.lock toggles locked + let lock_before = a.ui.map.locked; + run_item(&mut a, "map.lock", Value::Null).unwrap(); + assert_eq!(a.ui.map.locked, !lock_before); + + // Test running panel.map switches to ViewMode::Map + a.ui.view = ViewMode::PhotoGrid; + run_item(&mut a, "panel.map", Value::Null).unwrap(); + assert_eq!(a.ui.view, ViewMode::Map); +} diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 30e8b976ff..5580896aa2 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -368,18 +368,46 @@ 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" => { + "view.map" | "panel.map" => { app.ui.view = ViewMode::Map; Ok(json!({"view": "map"})) } - "view.toggleMapFilter" => { + "view.toggleMapFilter" | "map.filterBar" => { app.ui.map.show_filter_bar = !app.ui.map.show_filter_bar; Ok(json!({"show": app.ui.map.show_filter_bar})) } - "map.toggleLock" => { + "map.toggleLock" | "map.lock" => { app.ui.map.locked = !app.ui.map.locked; Ok(json!({"locked": app.ui.map.locked})) } + "map.navigator" => { + app.ui.map.navigator_open = !app.ui.map.navigator_open; + Ok(json!({"open": app.ui.map.navigator_open})) + } + "map.legend" => { + app.ui.map.legend_open = !app.ui.map.legend_open; + Ok(json!({"open": app.ui.map.legend_open})) + } + "photo.showInMap" => { + let target_id = p.get("id").and_then(Value::as_u64).map(lightcraft_catalog::PhotoId).or(app.session.selection.active); + if let Some(id) = target_id { + let _ = app.run("library.select", json!({"ids": [id.0]})); + app.ui.view = ViewMode::Map; + if let Some(ph) = app.session.catalog.photo(id) { + if let Some((lat, lon)) = ph.meta.gps { + app.ui.map.center_lat = lat; + app.ui.map.center_lon = lon; + app.ui.map.zoom = 15.0; + app.ui.map.active_pin_photo = Some(id); + } else { + app.toast(ctx, crate::i18n::tr("Photo has no GPS coordinates (drag onto map to place)")); + } + } + } else { + app.ui.view = ViewMode::Map; + } + Ok(json!({"view": "map"})) + } "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 fb5ec3c427..79735c0acf 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -73,6 +73,12 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("view.map", "Map", Some("Cmd+Option+3"), "View"), ("view.toggleMapFilter", "Toggle Map Filter Bar", Some("\\"), "View"), ("map.toggleLock", "Lock Markers", Some("Cmd+K"), "View"), + ("photo.showInMap", "Show in Map", None, "Photo"), + ("panel.map", "Map View", Some("Cmd+Option+3"), "Window>Map"), + ("map.navigator", "Map Navigator", None, "Window>Map"), + ("map.filterBar", "Location Filter Bar", Some("\\"), "Window>Map"), + ("map.legend", "Map Legend", None, "Window>Map"), + ("map.lock", "Lock Map Markers", Some("Cmd+K"), "Window>Map"), ("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/grid.rs b/crates/ui-egui/src/panels/grid.rs index 556f809d27..b6f177f6ce 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -1533,6 +1533,9 @@ fn context_menu_locate_and_export(app: &mut LightcraftApp, ui: &mut egui::Ui, id if ui.add_enabled(crate::menus::show_in_folders_enabled(app, Some(id)), egui::Button::new(crate::i18n::tr("Show in Folders"))).clicked() { let _ = app.run("app.showInFolders", json!({"id": id.0})); } + if ui.button(crate::i18n::tr("Show in Map")).clicked() { + let _ = app.run("photo.showInMap", json!({"id": id.0})); + } if ui.button(crate::i18n::tr("Export…")).clicked() { let _ = app.run("dialog.export", json!({})); } From 8de0726929c31f7cf083d2d24fbec198174f3ed6 Mon Sep 17 00:00:00 2001 From: bd78 Date: Sat, 14 Nov 2026 01:38:41 -0500 Subject: [PATCH 06/51] LRC-MAP-VIEW: decouple navigator overview zoom from main canvas zoom --- crates/ui-egui/src/panels/map.rs | 23 ++++++++++++++++++++--- crates/ui-egui/src/state/map.rs | 2 ++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 8e147010f3..986605cc41 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -640,7 +640,7 @@ fn render_left_navigator( let mini_rect = Rect::from_min_size(pos2(left_rect.left() + 8.0, ui.cursor().top()), vec2(mini_w, nav_h)); let nav_resp = ui.allocate_rect(mini_rect, Sense::click_and_drag()); - let nav_zoom = (*zoom - 3.5).clamp(1.0, (map_ui.provider.max_zoom() - 2) as f64); + let nav_zoom = map_ui.navigator_zoom.clamp(1.0, (map_ui.provider.max_zoom() - 2) as f64); if nav_resp.dragged() { let delta = nav_resp.drag_delta(); @@ -670,8 +670,8 @@ fn render_left_navigator( if nav_resp.hovered() { let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll.abs() > 0.5 { - let max_z = map_ui.provider.max_zoom() as f64; - *zoom = (*zoom + (scroll as f64 * 0.005)).clamp(1.0, max_z); + let max_z = (map_ui.provider.max_zoom() - 2) as f64; + map_ui.navigator_zoom = (map_ui.navigator_zoom + (scroll as f64 * 0.005)).clamp(1.0, max_z); ui.ctx().request_repaint(); } } @@ -865,4 +865,21 @@ mod tests { assert_eq!(app.ui.map.center_lon, -73.2); assert_eq!(app.ui.map.zoom, 14.0); } + + #[test] + fn navigator_zoom_is_independent_from_map_zoom() { + let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + app.ui.view = ViewMode::Map; + app.ui.map.zoom = 14.0; + app.ui.map.navigator_zoom = 3.0; + + 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.map.zoom, 14.0); + assert_eq!(app.ui.map.navigator_zoom, 3.0); + } } diff --git a/crates/ui-egui/src/state/map.rs b/crates/ui-egui/src/state/map.rs index b4a4698067..d208b205b0 100644 --- a/crates/ui-egui/src/state/map.rs +++ b/crates/ui-egui/src/state/map.rs @@ -7,6 +7,7 @@ pub struct MapUi { pub center_lat: f64, pub center_lon: f64, pub zoom: f64, + pub navigator_zoom: f64, pub provider: lightcraft_engine::map::MapProvider, pub filter: lightcraft_engine::map::LocationFilter, pub show_filter_bar: bool, @@ -24,6 +25,7 @@ impl Default for MapUi { center_lat: 45.57, center_lon: -73.2, zoom: 12.0, + navigator_zoom: 3.0, provider: lightcraft_engine::map::MapProvider::OpenStreetMap, filter: lightcraft_engine::map::LocationFilter::None, show_filter_bar: true, From 980fb625524e374cf654fa0155e8b6caa47a6d96 Mon Sep 17 00:00:00 2001 From: "Bruno D." Date: Sat, 14 Nov 2026 16:36:26 -0500 Subject: [PATCH 07/51] LRC-MAP-VIEW: fix map shortcut conflicts and cap tile download size The map commands declared shortcuts that failed the shortcut tests on CI: "Cmd+Option+3" does not parse (the keymap names the modifier Alt), each View entry shared its key with its Window>Map copy, "\" was already Show Original and Cmd+K was already Add Keywords. View > Map is now Cmd+Alt+3. The Window>Map copies no longer declare keys. As the grids do for their Filter Bar, the Map view routes the default "\" to the map filter bar and Cmd+K to locking the markers, instead of declaring second bindings for those keys. fetch_tile_bytes reserved the buffer from the server's Content-Length without a bound, so a huge announced length panicked with a capacity overflow. A length past the 2 MiB tile cap is now an error, and the reservation is capped. Tests: backslash and Cmd+K in the Map view, a huge announced tile length is an error (it panicked before the fix), and an honest length is read whole. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/map.rs | 50 ++++++++++++++++++- crates/ui-egui/src/menus/ui_commands.rs | 12 ++--- crates/ui-egui/src/shortcuts.rs | 8 ++- .../src/shortcuts/tests_filter_bar_key.rs | 29 +++++++++++ 4 files changed, 89 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/map.rs b/crates/engine/src/map.rs index a50a71c7b5..aed34f032a 100644 --- a/crates/engine/src/map.rs +++ b/crates/engine/src/map.rs @@ -183,6 +183,10 @@ pub fn tile_cache_path(cache_root: &Path, provider: MapProvider, coord: TileCoor } /// Pure-Rust network fetch for a map tile. +/// Largest map tile accepted from a server; real 256 px tiles are tens of KiB. +#[cfg(not(target_arch = "wasm32"))] +const MAX_TILE_BYTES: usize = 2 * 1024 * 1024; + #[cfg(not(target_arch = "wasm32"))] pub fn fetch_tile_bytes(url_str: &str) -> std::result::Result, String> { use lightcraft_fetch::http::{Limits, Url}; @@ -200,7 +204,13 @@ pub fn fetch_tile_bytes(url_str: &str) -> std::result::Result, String> { if resp.status != 200 { return Err(format!("fetch tile HTTP {}", resp.status)); } - let mut bytes = Vec::with_capacity(resp.content_length().unwrap_or(32 * 1024) as usize); + // The announced length comes from the server: refuse one past the cap instead of reserving it. + let announced = resp.content_length(); + if announced.is_some_and(|n| n > MAX_TILE_BYTES as u64) { + return Err("tile size exceeds 2 MiB".into()); + } + let capacity = announced.and_then(|n| usize::try_from(n).ok()).unwrap_or(32 * 1024).min(MAX_TILE_BYTES); + let mut bytes = Vec::with_capacity(capacity); let mut buf = [0u8; 8192]; loop { let n = resp.read(&mut buf, &limits).map_err(|e| format!("read tile stream: {e}"))?; @@ -208,7 +218,7 @@ pub fn fetch_tile_bytes(url_str: &str) -> std::result::Result, String> { break; } bytes.extend_from_slice(buf.get(..n).unwrap_or_default()); - if bytes.len() > 2 * 1024 * 1024 { + if bytes.len() > MAX_TILE_BYTES { return Err("tile size exceeds 2 MiB".into()); } } @@ -256,4 +266,40 @@ mod tests { // Point 10 km away assert!(!loc.contains(LatLon { lat: 51.6000, lon: -0.1278 })); } + + /// Serves one response with `head` (status line and headers) and `body` from a local server + /// (never the internet) and returns the tile URL that reaches it. + #[cfg(not(target_arch = "wasm32"))] + fn serve_once(head: &'static str, body: &'static [u8]) -> (String, std::thread::JoinHandle<()>) { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = std::thread::spawn(move || { + let Ok((mut stream, _)) = listener.accept() else { return }; + let mut request = [0u8; 1024]; + let _ = stream.read(&mut request); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(body); + }); + (format!("http://127.0.0.1:{port}/6/25/31.png"), server) + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_huge_announced_tile_length_is_an_error_not_an_allocation() { + // A server announcing u64::MAX bytes used to size the buffer from that number and panic + // with a capacity overflow before reading a byte. + let (url, server) = serve_once("HTTP/1.1 200 OK\r\nContent-Length: 18446744073709551615\r\n\r\n", b"tile"); + let err = fetch_tile_bytes(&url).unwrap_err(); + assert!(err.contains("2 MiB"), "{err}"); + server.join().unwrap(); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_tile_with_an_honest_length_is_read_whole() { + let (url, server) = serve_once("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n", b"tile"); + assert_eq!(fetch_tile_bytes(&url).unwrap(), b"tile"); + server.join().unwrap(); + } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 79735c0acf..8b1eca861b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -70,15 +70,15 @@ 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.map", "Map", Some("Cmd+Alt+3"), "View"), + ("view.toggleMapFilter", "Toggle Map Filter Bar", None, "View"), + ("map.toggleLock", "Lock Markers", None, "View"), ("photo.showInMap", "Show in Map", None, "Photo"), - ("panel.map", "Map View", Some("Cmd+Option+3"), "Window>Map"), + ("panel.map", "Map View", None, "Window>Map"), ("map.navigator", "Map Navigator", None, "Window>Map"), - ("map.filterBar", "Location Filter Bar", Some("\\"), "Window>Map"), + ("map.filterBar", "Location Filter Bar", None, "Window>Map"), ("map.legend", "Map Legend", None, "Window>Map"), - ("map.lock", "Lock Map Markers", Some("Cmd+K"), "Window>Map"), + ("map.lock", "Lock Map Markers", None, "Window>Map"), ("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/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 9ab12fe079..9c33df121b 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -319,10 +319,14 @@ fn matches(i: &egui::InputState, m: Modifiers, k: Key) -> bool { /// Default brackets rate in grids, and the default backslash shows / hides the Filter Bar there /// (Lightroom Classic's Library keys; Detail keeps brush size and Show Original). The full-screen /// preview keeps the grid's view but shows the photo alone, so backslash stays Show Original there. +/// The Map view has no original to show, so its backslash shows / hides the map's filter bar, and +/// its Cmd+K locks the markers instead of adding keywords (Lightroom Classic's Map module keys). /// Remapped brush and Show Original keys retain their action, and a saved assignment of the key to /// another command takes precedence over this default. -fn grid_key_command(keymap: &Keymap, grid: bool, fullscreen: bool, id: &'static str, shortcut: (Modifiers, Key)) -> Option<&'static str> { +fn grid_key_command(keymap: &Keymap, grid: bool, map: bool, fullscreen: bool, id: &'static str, shortcut: (Modifiers, Key)) -> Option<&'static str> { let command = match (grid, id, shortcut) { + (_, "view.showOriginal", (m, Key::Backslash)) if map && m == Modifiers::NONE && !fullscreen => "view.toggleMapFilter", + (_, "panel.addKeywords", (m, Key::K)) if map && m == Modifiers::COMMAND && !fullscreen => "map.toggleLock", (true, "brush.smaller", (m, Key::OpenBracket)) if m == Modifiers::NONE => "photo.decreaseRating", (true, "brush.larger", (m, Key::CloseBracket)) if m == Modifiers::NONE => "photo.increaseRating", (true, "view.showOriginal", (m, Key::Backslash)) if m == Modifiers::NONE && !fullscreen => "view.filterBar", @@ -450,7 +454,7 @@ fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context) -> (Vec, V && !native(sc) && !(k == Key::Escape && popup_open) && matches(i, m, k) - && let Some(id) = grid_key_command(keymap, grid, app.ui.fullscreen, b.id, (m, k)) + && let Some(id) = grid_key_command(keymap, grid, app.ui.view == crate::state::ViewMode::Map, app.ui.fullscreen, b.id, (m, k)) { if id == "view.zoomToggle" && k == Key::Space { // Toggle Zoom given Space in the keymap is the Space alias: the same hand and diff --git a/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs b/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs index 80a904c0e7..3b1c6f5a4e 100644 --- a/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs +++ b/crates/ui-egui/src/shortcuts/tests_filter_bar_key.rs @@ -109,6 +109,35 @@ fn saved_keymap_wins_over_the_grid_backslash() { assert!(!app.ui.filter_bar); } +#[test] +fn backslash_toggles_the_map_filter_bar_in_the_map_view() { + let mut app = app().unwrap(); + app.ui.view = ViewMode::Map; + let ctx = egui::Context::default(); + let shown = app.ui.map.show_filter_bar; + frame(&mut app, &ctx, Some(Key::Backslash), None); + assert_eq!(app.ui.map.show_filter_bar, !shown, "\\ toggles the map's filter bar"); + assert!(!app.ui.filter_bar, "the library Filter Bar stays as it was"); + assert_ne!(app.ui.before_after, BeforeAfter::Original, "the map has no original to show"); + frame(&mut app, &ctx, Some(Key::Backslash), None); + assert_eq!(app.ui.map.show_filter_bar, shown); +} + +#[test] +fn cmd_k_locks_the_map_markers_in_the_map_view() { + let mut app = app().unwrap(); + app.ui.view = ViewMode::Map; + let ctx = egui::Context::default(); + let locked = app.ui.map.locked; + let events = vec![egui::Event::Key { key: Key::K, physical_key: Some(Key::K), pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]; + let mut out = ctx.run_ui( + egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }, + |ui| super::handle(&mut app, ui.ctx()), + ); + out.textures_delta.clear(); + assert_eq!(app.ui.map.locked, !locked, "Cmd+K locks the markers in the Map view"); +} + #[test] fn backslash_yields_to_a_focused_text_field() { let mut app = app().unwrap(); From 1902b7bb0b3c49fa57352b21788499a12eb65d37 Mon Sep 17 00:00:00 2001 From: "Bruno D." Date: Sat, 14 Nov 2026 18:11:01 -0500 Subject: [PATCH 08/51] LRC-MAP-VIEW: translate the map view, show tile loading, honest tracker rows The map panel's labels, legend, filter names and tooltips now go through tr(), and the map's 23 new strings (panel text, menu items, the bottom-bar button and the activity row) are in all 17 catalogs. The marker lock button reads "Lock Markers" instead of a hard-coded "Locked (Ctrl+K)". Tile loads now hold one activity-stack row, "Loading map tiles" (download, no cancel), with a count. Every tile worker holds the row until it ends, so the row goes with the last load, also when the Map view is no longer drawn. LRC-MAP-GEOTAG goes back to partial: locations are set with photo.setGps, but photos can't yet be dragged onto the map. Gap 16 says so, and the tracker summary is refreshed. The Map view keys are listed in docs/library-shortcuts.md. GeoBounds::from_center_and_radius had no caller and is removed. Co-Authored-By: Claude Opus 5.5 --- crates/geom/src/geo.rs | 10 --- crates/ui-egui/locales/cs.json | 25 +++++- crates/ui-egui/locales/de.json | 25 +++++- crates/ui-egui/locales/es.json | 25 +++++- crates/ui-egui/locales/fi.json | 25 +++++- crates/ui-egui/locales/fr.json | 25 +++++- crates/ui-egui/locales/id.json | 25 +++++- crates/ui-egui/locales/it.json | 25 +++++- crates/ui-egui/locales/ja.json | 25 +++++- crates/ui-egui/locales/ka.json | 25 +++++- crates/ui-egui/locales/pl.json | 25 +++++- crates/ui-egui/locales/pt-br.json | 25 +++++- crates/ui-egui/locales/ru.json | 25 +++++- crates/ui-egui/locales/sv.json | 25 +++++- crates/ui-egui/locales/uk.json | 25 +++++- crates/ui-egui/locales/vi.json | 25 +++++- crates/ui-egui/locales/zh-hans.json | 25 +++++- crates/ui-egui/locales/zh-hant.json | 25 +++++- crates/ui-egui/src/panels/map.rs | 127 ++++++++++++++++++++++++---- docs/gaps.md | 2 +- docs/library-shortcuts.md | 11 +++ docs/parity-checklist.md | 8 +- 22 files changed, 533 insertions(+), 50 deletions(-) diff --git a/crates/geom/src/geo.rs b/crates/geom/src/geo.rs index 11fdfa6017..5d3ee5d1f9 100644 --- a/crates/geom/src/geo.rs +++ b/crates/geom/src/geo.rs @@ -119,16 +119,6 @@ impl GeoBounds { 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`. diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index d55dcd0312..69c06c5b32 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2500,5 +2500,28 @@ "Welcome": "Vítejte", "Next": "Další", "Get Started": "Začít", - "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie" + "Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie", + "Location Filter:": "Filtr polohy:", + "Visible On Map": "Viditelné na mapě", + "Tagged": "S polohou", + "Untagged": "Bez polohy", + "Map Style:": "Styl mapy:", + "Unselected photo": "Nevybraná fotografie", + "Selected photo": "Vybraná fotografie", + "Group / cluster": "Skupina", + "Saved Locations": "Uložená místa", + "Save current map location": "Uložit místo zobrazené na mapě", + "No saved locations. Click + to save.": "Žádná uložená místa. Uložte je kliknutím na +.", + "Delete location": "Odstranit místo", + "Loading map tiles": "Načítání dlaždic mapy", + "Map": "Mapa", + "Toggle Map Filter Bar": "Zobrazit/skrýt lištu filtrů mapy", + "Lock Markers": "Uzamknout značky", + "Show in Map": "Zobrazit na mapě", + "Map View": "Zobrazení mapy", + "Map Navigator": "Navigátor mapy", + "Location Filter Bar": "Lišta filtru polohy", + "Map Legend": "Legenda mapy", + "Lock Map Markers": "Uzamknout značky na mapě", + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index ce7e116dbe..6637f4d82d 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3535,5 +3535,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.", "Welcome": "Willkommen", "Next": "Weiter", - "Get Started": "Loslegen" + "Get Started": "Loslegen", + "Location Filter:": "Ortsfilter:", + "Visible On Map": "Auf der Karte sichtbar", + "Tagged": "Mit Standort", + "Untagged": "Ohne Standort", + "Map Style:": "Kartenstil:", + "Unselected photo": "Nicht ausgewähltes Foto", + "Selected photo": "Ausgewähltes Foto", + "Group / cluster": "Gruppe", + "Saved Locations": "Gespeicherte Orte", + "Save current map location": "Angezeigten Kartenort speichern", + "No saved locations. Click + to save.": "Keine gespeicherten Orte. Zum Speichern auf + klicken.", + "Delete location": "Ort löschen", + "Loading map tiles": "Kartenkacheln werden geladen", + "Map": "Karte", + "Toggle Map Filter Bar": "Kartenfilterleiste ein-/ausblenden", + "Lock Markers": "Markierungen sperren", + "Show in Map": "Auf Karte anzeigen", + "Map View": "Kartenansicht", + "Map Navigator": "Kartennavigator", + "Location Filter Bar": "Ortsfilterleiste", + "Map Legend": "Kartenlegende", + "Lock Map Markers": "Kartenmarkierungen sperren", + "Map (Ctrl+Alt+3)": "Karte (Strg+Alt+3)" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index ff9e7355ff..f51275b4ad 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2454,5 +2454,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.", "Welcome": "Bienvenido", "Next": "Siguiente", - "Get Started": "Empezar" + "Get Started": "Empezar", + "Location Filter:": "Filtro de ubicación:", + "Visible On Map": "Visibles en el mapa", + "Tagged": "Con ubicación", + "Untagged": "Sin ubicación", + "Map Style:": "Estilo de mapa:", + "Unselected photo": "Foto no seleccionada", + "Selected photo": "Foto seleccionada", + "Group / cluster": "Grupo", + "Saved Locations": "Ubicaciones guardadas", + "Save current map location": "Guardar la ubicación mostrada en el mapa", + "No saved locations. Click + to save.": "No hay ubicaciones guardadas. Haz clic en + para guardar una.", + "Delete location": "Eliminar ubicación", + "Loading map tiles": "Cargando teselas del mapa", + "Map": "Mapa", + "Toggle Map Filter Bar": "Mostrar u ocultar la barra de filtros del mapa", + "Lock Markers": "Bloquear marcadores", + "Show in Map": "Mostrar en el mapa", + "Map View": "Vista de mapa", + "Map Navigator": "Navegador del mapa", + "Location Filter Bar": "Barra de filtro de ubicación", + "Map Legend": "Leyenda del mapa", + "Lock Map Markers": "Bloquear marcadores del mapa", + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e971f91c99..a162965ad6 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2411,5 +2411,28 @@ "Top bar": "Yläpalkki", "Tool strip": "Työkalupalkki", "Bottom bar": "Alapalkki", - "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää" + "Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää", + "Location Filter:": "Sijaintisuodatin:", + "Visible On Map": "Näkyvät kartalla", + "Tagged": "Sijainnilliset", + "Untagged": "Sijainnittomat", + "Map Style:": "Kartan tyyli:", + "Unselected photo": "Valitsematon kuva", + "Selected photo": "Valittu kuva", + "Group / cluster": "Ryhmä", + "Saved Locations": "Tallennetut sijainnit", + "Save current map location": "Tallenna kartalla näkyvä sijainti", + "No saved locations. Click + to save.": "Ei tallennettuja sijainteja. Tallenna napsauttamalla +.", + "Delete location": "Poista sijainti", + "Loading map tiles": "Ladataan karttaruutuja", + "Map": "Kartta", + "Toggle Map Filter Bar": "Näytä tai piilota kartan suodatinpalkki", + "Lock Markers": "Lukitse merkit", + "Show in Map": "Näytä kartalla", + "Map View": "Karttanäkymä", + "Map Navigator": "Kartan navigaattori", + "Location Filter Bar": "Sijaintisuodatinpalkki", + "Map Legend": "Kartan selite", + "Lock Map Markers": "Lukitse karttamerkit", + "Map (Ctrl+Alt+3)": "Kartta (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 17dd17bd3f..fd34721fa9 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3637,5 +3637,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Démarrez l'application avec --control 7980 (ou LIGHTCRAFT_CONTROL_PORT), puis lightcraft-cli mcp --connect y connecte un agent.", "Welcome": "Bienvenue", "Next": "Suivant", - "Get Started": "Commencer" + "Get Started": "Commencer", + "Location Filter:": "Filtre de lieu :", + "Visible On Map": "Visibles sur la carte", + "Tagged": "Géolocalisées", + "Untagged": "Non géolocalisées", + "Map Style:": "Style de carte :", + "Unselected photo": "Photo non sélectionnée", + "Selected photo": "Photo sélectionnée", + "Group / cluster": "Groupe", + "Saved Locations": "Lieux enregistrés", + "Save current map location": "Enregistrer le lieu affiché sur la carte", + "No saved locations. Click + to save.": "Aucun lieu enregistré. Cliquez sur + pour en ajouter un.", + "Delete location": "Supprimer le lieu", + "Loading map tiles": "Chargement des tuiles de carte", + "Map": "Carte", + "Toggle Map Filter Bar": "Afficher / masquer la barre de filtres de la carte", + "Lock Markers": "Verrouiller les repères", + "Show in Map": "Afficher sur la carte", + "Map View": "Vue Carte", + "Map Navigator": "Navigateur de carte", + "Location Filter Bar": "Barre de filtre de lieu", + "Map Legend": "Légende de la carte", + "Lock Map Markers": "Verrouiller les repères de la carte", + "Map (Ctrl+Alt+3)": "Carte (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index a72b718fd5..1b77209a32 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2425,5 +2425,28 @@ "Top bar": "Bilah atas", "Tool strip": "Bilah alat", "Bottom bar": "Bilah bawah", - "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto" + "Stopped at the scan limit: there may be more photos": "Berhenti pada batas pemindaian: mungkin masih ada foto", + "Location Filter:": "Filter lokasi:", + "Visible On Map": "Terlihat di peta", + "Tagged": "Berlokasi", + "Untagged": "Tanpa lokasi", + "Map Style:": "Gaya peta:", + "Unselected photo": "Foto tidak dipilih", + "Selected photo": "Foto dipilih", + "Group / cluster": "Grup", + "Saved Locations": "Lokasi tersimpan", + "Save current map location": "Simpan lokasi yang tampil di peta", + "No saved locations. Click + to save.": "Belum ada lokasi tersimpan. Klik + untuk menyimpan.", + "Delete location": "Hapus lokasi", + "Loading map tiles": "Memuat ubin peta", + "Map": "Peta", + "Toggle Map Filter Bar": "Tampilkan/sembunyikan bilah filter peta", + "Lock Markers": "Kunci penanda", + "Show in Map": "Tampilkan di peta", + "Map View": "Tampilan peta", + "Map Navigator": "Navigator peta", + "Location Filter Bar": "Bilah filter lokasi", + "Map Legend": "Legenda peta", + "Lock Map Markers": "Kunci penanda peta", + "Map (Ctrl+Alt+3)": "Peta (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 2ddcf037fd..7e24addbd3 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2618,5 +2618,28 @@ "Welcome": "Benvenuto", "Next": "Avanti", "Get Started": "Inizia", - "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto" + "Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto", + "Location Filter:": "Filtro posizione:", + "Visible On Map": "Visibili sulla mappa", + "Tagged": "Con posizione", + "Untagged": "Senza posizione", + "Map Style:": "Stile mappa:", + "Unselected photo": "Foto non selezionata", + "Selected photo": "Foto selezionata", + "Group / cluster": "Gruppo", + "Saved Locations": "Posizioni salvate", + "Save current map location": "Salva la posizione mostrata sulla mappa", + "No saved locations. Click + to save.": "Nessuna posizione salvata. Fai clic su + per salvarne una.", + "Delete location": "Elimina posizione", + "Loading map tiles": "Caricamento dei riquadri della mappa", + "Map": "Mappa", + "Toggle Map Filter Bar": "Mostra/nascondi la barra dei filtri della mappa", + "Lock Markers": "Blocca indicatori", + "Show in Map": "Mostra sulla mappa", + "Map View": "Vista mappa", + "Map Navigator": "Navigatore mappa", + "Location Filter Bar": "Barra filtro posizione", + "Map Legend": "Legenda della mappa", + "Lock Map Markers": "Blocca indicatori della mappa", + "Map (Ctrl+Alt+3)": "Mappa (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 04db1f164a..95415fd686 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2452,5 +2452,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "アプリを --control 7980 (または LIGHTCRAFT_CONTROL_PORT) で起動してから、lightcraft-cli mcp --connect でエージェントを接続できます。", "Welcome": "ようこそ", "Next": "次へ", - "Get Started": "始める" + "Get Started": "始める", + "Location Filter:": "場所フィルター:", + "Visible On Map": "地図に表示中", + "Tagged": "位置情報あり", + "Untagged": "位置情報なし", + "Map Style:": "地図スタイル:", + "Unselected photo": "未選択の写真", + "Selected photo": "選択中の写真", + "Group / cluster": "グループ", + "Saved Locations": "保存した場所", + "Save current map location": "地図に表示中の場所を保存", + "No saved locations. Click + to save.": "保存した場所はありません。+ をクリックして保存します。", + "Delete location": "場所を削除", + "Loading map tiles": "地図タイルを読み込み中", + "Map": "地図", + "Toggle Map Filter Bar": "地図フィルターバーの表示を切り替え", + "Lock Markers": "マーカーをロック", + "Show in Map": "地図で表示", + "Map View": "地図表示", + "Map Navigator": "地図ナビゲーター", + "Location Filter Bar": "場所フィルターバー", + "Map Legend": "地図の凡例", + "Lock Map Markers": "地図マーカーをロック", + "Map (Ctrl+Alt+3)": "地図(Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 9791131d88..e6cab61533 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3720,5 +3720,28 @@ "Tool strip": "ხელსაწყოების ზოლი", "Bottom bar": "ქვედა ზოლი", "Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSync-ის ციმციმის თავიდან აცილება (ამოქმედდება შემდეგი გაშვებისას)", - "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის" + "Stopped at the scan limit: there may be more photos": "სკანირების ლიმიტზე გაჩერდა: შესაძლოა სხვა ფოტოებიც არის", + "Location Filter:": "მდებარეობის ფილტრი:", + "Visible On Map": "რუკაზე ხილული", + "Tagged": "მდებარეობით", + "Untagged": "მდებარეობის გარეშე", + "Map Style:": "რუკის სტილი:", + "Unselected photo": "მოუნიშნავი ფოტო", + "Selected photo": "მონიშნული ფოტო", + "Group / cluster": "ჯგუფი", + "Saved Locations": "შენახული მდებარეობები", + "Save current map location": "რუკაზე ნაჩვენები მდებარეობის შენახვა", + "No saved locations. Click + to save.": "შენახული მდებარეობები არ არის. შესანახად დააწკაპუნეთ +-ზე.", + "Delete location": "მდებარეობის წაშლა", + "Loading map tiles": "რუკის ფილების ჩატვირთვა", + "Map": "რუკა", + "Toggle Map Filter Bar": "რუკის ფილტრების ზოლის ჩვენება/დამალვა", + "Lock Markers": "მარკერების ჩაკეტვა", + "Show in Map": "რუკაზე ჩვენება", + "Map View": "რუკის ხედი", + "Map Navigator": "რუკის ნავიგატორი", + "Location Filter Bar": "მდებარეობის ფილტრის ზოლი", + "Map Legend": "რუკის ლეგენდა", + "Lock Map Markers": "რუკის მარკერების ჩაკეტვა", + "Map (Ctrl+Alt+3)": "რუკა (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 9fb5e33695..0f13f43c00 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2377,5 +2377,28 @@ "Welcome": "Witamy", "Next": "Dalej", "Get Started": "Zaczynamy", - "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć" + "Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć", + "Location Filter:": "Filtr lokalizacji:", + "Visible On Map": "Widoczne na mapie", + "Tagged": "Z lokalizacją", + "Untagged": "Bez lokalizacji", + "Map Style:": "Styl mapy:", + "Unselected photo": "Niezaznaczone zdjęcie", + "Selected photo": "Zaznaczone zdjęcie", + "Group / cluster": "Grupa", + "Saved Locations": "Zapisane lokalizacje", + "Save current map location": "Zapisz lokalizację widoczną na mapie", + "No saved locations. Click + to save.": "Brak zapisanych lokalizacji. Kliknij +, aby zapisać.", + "Delete location": "Usuń lokalizację", + "Loading map tiles": "Wczytywanie kafelków mapy", + "Map": "Mapa", + "Toggle Map Filter Bar": "Pokaż/ukryj pasek filtrów mapy", + "Lock Markers": "Zablokuj znaczniki", + "Show in Map": "Pokaż na mapie", + "Map View": "Widok mapy", + "Map Navigator": "Nawigator mapy", + "Location Filter Bar": "Pasek filtru lokalizacji", + "Map Legend": "Legenda mapy", + "Lock Map Markers": "Zablokuj znaczniki mapy", + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e815f09a47..9a4950dff7 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2298,5 +2298,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicie o aplicativo com --control 7980 (ou LIGHTCRAFT_CONTROL_PORT) e o lightcraft-cli mcp --connect conecta um agente a ele.", "Welcome": "Bem-vindo", "Next": "Próximo", - "Get Started": "Começar" + "Get Started": "Começar", + "Location Filter:": "Filtro de local:", + "Visible On Map": "Visíveis no mapa", + "Tagged": "Com local", + "Untagged": "Sem local", + "Map Style:": "Estilo do mapa:", + "Unselected photo": "Foto não selecionada", + "Selected photo": "Foto selecionada", + "Group / cluster": "Grupo", + "Saved Locations": "Locais salvos", + "Save current map location": "Salvar o local mostrado no mapa", + "No saved locations. Click + to save.": "Nenhum local salvo. Clique em + para salvar.", + "Delete location": "Excluir local", + "Loading map tiles": "Carregando blocos do mapa", + "Map": "Mapa", + "Toggle Map Filter Bar": "Mostrar/ocultar a barra de filtros do mapa", + "Lock Markers": "Travar marcadores", + "Show in Map": "Mostrar no mapa", + "Map View": "Visualização de mapa", + "Map Navigator": "Navegador do mapa", + "Location Filter Bar": "Barra de filtro de local", + "Map Legend": "Legenda do mapa", + "Lock Map Markers": "Travar marcadores do mapa", + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b7bb62e7d6..d391dfeaa9 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2660,5 +2660,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустите приложение с --control 7980 (или LIGHTCRAFT_CONTROL_PORT), и команда lightcraft-cli mcp --connect подключит к нему одного агента.", "Welcome": "Добро пожаловать", "Next": "Далее", - "Get Started": "Начать" + "Get Started": "Начать", + "Location Filter:": "Фильтр по месту:", + "Visible On Map": "Видимые на карте", + "Tagged": "С геотегом", + "Untagged": "Без геотега", + "Map Style:": "Стиль карты:", + "Unselected photo": "Невыделенное фото", + "Selected photo": "Выделенное фото", + "Group / cluster": "Группа", + "Saved Locations": "Сохранённые места", + "Save current map location": "Сохранить место, показанное на карте", + "No saved locations. Click + to save.": "Нет сохранённых мест. Нажмите +, чтобы сохранить.", + "Delete location": "Удалить место", + "Loading map tiles": "Загрузка фрагментов карты", + "Map": "Карта", + "Toggle Map Filter Bar": "Показать/скрыть панель фильтров карты", + "Lock Markers": "Заблокировать метки", + "Show in Map": "Показать на карте", + "Map View": "Режим карты", + "Map Navigator": "Навигатор карты", + "Location Filter Bar": "Панель фильтра по месту", + "Map Legend": "Легенда карты", + "Lock Map Markers": "Заблокировать метки на карте", + "Map (Ctrl+Alt+3)": "Карта (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 6092355c95..b3f740bcd9 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2515,5 +2515,28 @@ "Top bar": "Övre fältet", "Tool strip": "Verktygsfält", "Bottom bar": "Nedre fältet", - "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton" + "Stopped at the scan limit: there may be more photos": "Stoppade vid skanningsgränsen: det kan finnas fler foton", + "Location Filter:": "Platsfilter:", + "Visible On Map": "Synliga på kartan", + "Tagged": "Med plats", + "Untagged": "Utan plats", + "Map Style:": "Kartstil:", + "Unselected photo": "Omarkerat foto", + "Selected photo": "Markerat foto", + "Group / cluster": "Grupp", + "Saved Locations": "Sparade platser", + "Save current map location": "Spara platsen som visas på kartan", + "No saved locations. Click + to save.": "Inga sparade platser. Klicka på + för att spara.", + "Delete location": "Radera plats", + "Loading map tiles": "Läser in kartrutor", + "Map": "Karta", + "Toggle Map Filter Bar": "Visa/dölj kartans filterfält", + "Lock Markers": "Lås markörer", + "Show in Map": "Visa på karta", + "Map View": "Kartvy", + "Map Navigator": "Kartnavigator", + "Location Filter Bar": "Platsfilterfält", + "Map Legend": "Kartförklaring", + "Lock Map Markers": "Lås kartmarkörer", + "Map (Ctrl+Alt+3)": "Karta (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09e5b0e1e8..cf05530599 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2450,5 +2450,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Запустіть програму з --control 7980 (або LIGHTCRAFT_CONTROL_PORT), і lightcraft-cli mcp --connect під'єднає до неї одного агента.", "Welcome": "Ласкаво просимо", "Next": "Далі", - "Get Started": "Почати" + "Get Started": "Почати", + "Location Filter:": "Фільтр за місцем:", + "Visible On Map": "Видимі на мапі", + "Tagged": "З геотегом", + "Untagged": "Без геотегу", + "Map Style:": "Стиль мапи:", + "Unselected photo": "Невибране фото", + "Selected photo": "Вибране фото", + "Group / cluster": "Група", + "Saved Locations": "Збережені місця", + "Save current map location": "Зберегти місце, показане на мапі", + "No saved locations. Click + to save.": "Немає збережених місць. Натисніть +, щоб зберегти.", + "Delete location": "Видалити місце", + "Loading map tiles": "Завантаження фрагментів мапи", + "Map": "Мапа", + "Toggle Map Filter Bar": "Показати/сховати панель фільтрів мапи", + "Lock Markers": "Заблокувати мітки", + "Show in Map": "Показати на мапі", + "Map View": "Режим мапи", + "Map Navigator": "Навігатор мапи", + "Location Filter Bar": "Панель фільтра за місцем", + "Map Legend": "Легенда мапи", + "Lock Map Markers": "Заблокувати мітки на мапі", + "Map (Ctrl+Alt+3)": "Мапа (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index d31e48dff2..5bfa060898 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2739,5 +2739,28 @@ "Top bar": "Thanh trên cùng", "Tool strip": "Thanh công cụ", "Bottom bar": "Thanh dưới cùng", - "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác" + "Stopped at the scan limit: there may be more photos": "Đã dừng ở giới hạn quét: có thể còn ảnh khác", + "Location Filter:": "Bộ lọc vị trí:", + "Visible On Map": "Hiển thị trên bản đồ", + "Tagged": "Có vị trí", + "Untagged": "Không có vị trí", + "Map Style:": "Kiểu bản đồ:", + "Unselected photo": "Ảnh chưa chọn", + "Selected photo": "Ảnh đã chọn", + "Group / cluster": "Nhóm", + "Saved Locations": "Vị trí đã lưu", + "Save current map location": "Lưu vị trí đang hiển thị trên bản đồ", + "No saved locations. Click + to save.": "Chưa có vị trí đã lưu. Nhấn + để lưu.", + "Delete location": "Xóa vị trí", + "Loading map tiles": "Đang tải ô bản đồ", + "Map": "Bản đồ", + "Toggle Map Filter Bar": "Hiện/ẩn thanh bộ lọc bản đồ", + "Lock Markers": "Khóa điểm đánh dấu", + "Show in Map": "Xem trên bản đồ", + "Map View": "Chế độ xem bản đồ", + "Map Navigator": "Điều hướng bản đồ", + "Location Filter Bar": "Thanh lọc vị trí", + "Map Legend": "Chú giải bản đồ", + "Lock Map Markers": "Khóa điểm đánh dấu trên bản đồ", + "Map (Ctrl+Alt+3)": "Bản đồ (Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 766d982552..90e2bd6353 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2453,5 +2453,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 启动应用,lightcraft-cli mcp --connect 即可将一个智能体接入其中。", "Welcome": "欢迎", "Next": "下一步", - "Get Started": "开始使用" + "Get Started": "开始使用", + "Location Filter:": "位置过滤器:", + "Visible On Map": "地图上可见", + "Tagged": "有位置", + "Untagged": "无位置", + "Map Style:": "地图样式:", + "Unselected photo": "未选择的照片", + "Selected photo": "已选择的照片", + "Group / cluster": "组", + "Saved Locations": "已存储的位置", + "Save current map location": "存储地图上显示的位置", + "No saved locations. Click + to save.": "没有已存储的位置。单击 + 存储。", + "Delete location": "删除位置", + "Loading map tiles": "正在载入地图图块", + "Map": "地图", + "Toggle Map Filter Bar": "显示/隐藏地图过滤器栏", + "Lock Markers": "锁定标记", + "Show in Map": "在地图中显示", + "Map View": "地图视图", + "Map Navigator": "地图导航器", + "Location Filter Bar": "位置过滤器栏", + "Map Legend": "地图图例", + "Lock Map Markers": "锁定地图标记", + "Map (Ctrl+Alt+3)": "地图(Ctrl+Alt+3)" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 26ec3e8f61..756dca12d3 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2454,5 +2454,28 @@ "Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "先以 --control 7980 (或 LIGHTCRAFT_CONTROL_PORT) 啟動應用程式,lightcraft-cli mcp --connect 即可將一個代理程式連接到其中。", "Welcome": "歡迎", "Next": "下一步", - "Get Started": "開始使用" + "Get Started": "開始使用", + "Location Filter:": "位置篩選:", + "Visible On Map": "地圖上可見", + "Tagged": "有位置", + "Untagged": "無位置", + "Map Style:": "地圖樣式:", + "Unselected photo": "未選取的相片", + "Selected photo": "已選取的相片", + "Group / cluster": "群組", + "Saved Locations": "已儲存的位置", + "Save current map location": "儲存地圖上顯示的位置", + "No saved locations. Click + to save.": "沒有已儲存的位置。按一下 + 以儲存。", + "Delete location": "刪除位置", + "Loading map tiles": "正在載入地圖圖磚", + "Map": "地圖", + "Toggle Map Filter Bar": "顯示/隱藏地圖篩選列", + "Lock Markers": "鎖定標記", + "Show in Map": "在地圖中顯示", + "Map View": "地圖檢視", + "Map Navigator": "地圖導覽器", + "Location Filter Bar": "位置篩選列", + "Map Legend": "地圖圖例", + "Lock Map Markers": "鎖定地圖標記", + "Map (Ctrl+Alt+3)": "地圖(Ctrl+Alt+3)" } diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 986605cc41..82e88d46d8 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -2,8 +2,9 @@ //! photo marker clustering, loupe popover, GPX tracklog overlay, and saved locations. use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; -use std::sync::{Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError, Weak}; use egui::{Align2, Color32, ColorImage, FontId, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, TextureHandle, TextureOptions, pos2, vec2}; use lightcraft_catalog::PhotoId; @@ -35,15 +36,62 @@ struct TileStore { pending: HashSet, tx: Sender<(TileKey, ColorImage)>, rx: Receiver<(TileKey, ColorImage)>, + /// The tile loads in flight, while there are any. Only the workers hold it strongly. + batch: Weak, } impl TileStore { fn new() -> Self { let (tx, rx) = channel(); - Self { textures: HashMap::new(), pending: HashSet::new(), tx, rx } + Self { textures: HashMap::new(), pending: HashSet::new(), tx, rx, batch: Weak::new() } } } +/// The tile loads in flight share one activity row. Each worker holds an `Arc` until it ends, so +/// the last one to finish (fetched, failed or not started) drops the row, whether or not the Map +/// view is still drawn. +struct TileBatch { + guard: lightcraft_engine::activity::TaskGuard, + done: AtomicU64, + total: AtomicU64, +} + +impl TileBatch { + fn progress(&self) { + self.guard.progress(self.done.load(Ordering::Relaxed), self.total.load(Ordering::Relaxed)); + } + + fn finish(&self) { + self.done.fetch_add(1, Ordering::Relaxed); + self.progress(); + } +} + +/// Held by a tile worker: counts its load as done when the worker ends, then lets go of the batch. +struct TileLoadEnd(Arc); + +impl Drop for TileLoadEnd { + fn drop(&mut self) { + self.0.finish(); + } +} + +/// Counts one more tile load into the batch in flight, starting a batch (and its row) if none is. +fn join_tile_batch(slot: &mut Weak, activity: &lightcraft_engine::activity::Activity) -> Arc { + let batch = slot.upgrade().unwrap_or_else(|| { + let batch = Arc::new(TileBatch { + guard: activity.start("download", "Loading map tiles", lightcraft_engine::activity::Cancel::No), + done: AtomicU64::new(0), + total: AtomicU64::new(0), + }); + *slot = Arc::downgrade(&batch); + batch + }); + batch.total.fetch_add(1, Ordering::Relaxed); + batch.progress(); + batch +} + static TILES: Mutex> = Mutex::new(None); /// Represents a clustered group of photos on the map screen. @@ -135,7 +183,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } // Draw Map Grid / Tile outlines - render_tile_grid(&painter, canvas_rect, screen_center, center, zoom, map_ui.provider); + render_tile_grid(&painter, &app.session.activity, canvas_rect, screen_center, center, 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, center), canvas_rect); @@ -240,9 +288,18 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.map = map_ui; } -fn fetch_and_cache_tile(key: TileKey, url: String, disk_path: std::path::PathBuf, tx: Sender<(TileKey, ColorImage)>, ctx: egui::Context) { +fn fetch_and_cache_tile( + key: TileKey, + url: String, + disk_path: std::path::PathBuf, + tx: Sender<(TileKey, ColorImage)>, + ctx: egui::Context, + batch: Arc, +) { #[cfg(not(target_arch = "wasm32"))] let _ = std::thread::Builder::new().name("lc-tile-fetch".into()).spawn(move || { + // ends this load in the batch's row however the worker returns + let _counted = TileLoadEnd(batch); let bytes = if disk_path.exists() { std::fs::read(&disk_path).ok() } else { @@ -269,7 +326,15 @@ fn fetch_and_cache_tile(key: TileKey, url: String, disk_path: std::path::PathBuf }); } -fn render_tile_grid(p: &Painter, canvas: Rect, center_pos: Pos2, center: LatLon, zoom: f64, provider: MapProvider) { +fn render_tile_grid( + p: &Painter, + activity: &lightcraft_engine::activity::Activity, + canvas: Rect, + center_pos: Pos2, + center: LatLon, + zoom: f64, + provider: MapProvider, +) { let int_zoom = (zoom.floor() as u8).min(provider.max_zoom()); let scale = 2.0_f64.powf(zoom - int_zoom as f64); let tile_screen_size = (TILE_SIZE as f64 * scale) as f32; @@ -327,7 +392,8 @@ fn render_tile_grid(p: &Painter, canvas: Rect, center_pos: Pos2, center: LatLon, if !store.pending.contains(&key) { store.pending.insert(key); let disk_path = lightcraft_engine::map::tile_cache_path(&cache_root, provider, coord, layer_idx); - fetch_and_cache_tile(key, url, disk_path, store.tx.clone(), p.ctx().clone()); + let batch = join_tile_batch(&mut store.batch, activity); + fetch_and_cache_tile(key, url, disk_path, store.tx.clone(), p.ctx().clone(), batch); } } } @@ -459,7 +525,7 @@ fn render_top_filter_bar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re 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.label(egui::RichText::new(crate::i18n::tr("Location Filter:")).strong().color(Color32::WHITE)); ui.add_space(8.0); let filters = [ @@ -471,7 +537,7 @@ fn render_top_filter_bar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re for (f, name) in filters { let active = map_ui.filter == f; - let btn = ui.selectable_label(active, name); + let btn = ui.selectable_label(active, crate::i18n::tr(name)); if btn.clicked() { map_ui.filter = f; } @@ -495,7 +561,7 @@ fn render_bottom_toolbar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re 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)); + ui.label(egui::RichText::new(crate::i18n::tr("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 { @@ -515,7 +581,7 @@ fn render_bottom_toolbar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re } ui.add_space(12.0); - let lock_btn = ui.selectable_label(map_ui.locked, if map_ui.locked { "Locked (Ctrl+K)" } else { "Unlocked" }); + let lock_btn = ui.selectable_label(map_ui.locked, crate::i18n::tr("Lock Markers")); if lock_btn.clicked() { map_ui.locked = !map_ui.locked; } @@ -543,7 +609,7 @@ fn render_legend_overlay(ui: &mut egui::Ui, canvas: Rect, _map_ui: &mut crate::s 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); + p.text(pos2(legend_rect.left() + 34.0, y), Align2::LEFT_CENTER, crate::i18n::tr(text), FontId::proportional(11.0), Color32::WHITE); } } @@ -583,7 +649,7 @@ fn render_loupe_popover(app: &mut LightcraftApp, ui: &mut egui::Ui, pin_pos: Pos ui.add_space(6.0); ui.horizontal(|ui| { ui.add_space(8.0); - if ui.button("Open in Detail").clicked() { + if ui.button(crate::i18n::tr("Open in Detail")).clicked() { app.ui.view = ViewMode::Detail; } }); @@ -632,7 +698,7 @@ fn render_left_navigator( ui.add_space(8.0); ui.horizontal(|ui| { ui.add_space(8.0); - ui.label(egui::RichText::new("Navigator").strong().color(Color32::WHITE)); + ui.label(egui::RichText::new(crate::i18n::tr("Navigator")).strong().color(Color32::WHITE)); }); ui.add_space(4.0); @@ -680,7 +746,7 @@ fn render_left_navigator( nav_painter.rect_filled(mini_rect, 4.0, Color32::from_rgb(18, 22, 26)); // Render overview map tiles - render_tile_grid(&nav_painter, mini_rect, mini_rect.center(), *center, nav_zoom, map_ui.provider); + render_tile_grid(&nav_painter, &app.session.activity, mini_rect, mini_rect.center(), *center, nav_zoom, map_ui.provider); // Viewport rectangle showing the visible area on the main map let scale_diff = 2.0_f64.powf(nav_zoom - *zoom); @@ -701,10 +767,10 @@ fn render_left_navigator( ui.add_space(14.0); ui.horizontal(|ui| { ui.add_space(8.0); - ui.label(egui::RichText::new("Saved Locations").strong().color(Color32::WHITE)); + ui.label(egui::RichText::new(crate::i18n::tr("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("+").on_hover_text("Save current map location").clicked() { + if ui.button("+").on_hover_text(crate::i18n::tr("Save current map location")).clicked() { let _ = app.run( "map.savedLocations.create", json!({ @@ -724,7 +790,7 @@ fn render_left_navigator( if app.session.saved_locations.is_empty() { ui.horizontal(|ui| { ui.add_space(12.0); - ui.label(egui::RichText::new("No saved locations. Click + to save.").small().italics().color(Color32::GRAY)); + ui.label(egui::RichText::new(crate::i18n::tr("No saved locations. Click + to save.")).small().italics().color(Color32::GRAY)); }); } else { for loc in &app.session.saved_locations { @@ -741,7 +807,7 @@ fn render_left_navigator( } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_space(8.0); - if ui.small_button("✕").on_hover_text("Delete location").clicked() { + if ui.small_button("✕").on_hover_text(crate::i18n::tr("Delete location")).clicked() { delete_id = Some(loc.id.clone()); } }); @@ -882,4 +948,29 @@ mod tests { assert_eq!(app.ui.map.zoom, 14.0); assert_eq!(app.ui.map.navigator_zoom, 3.0); } + + #[test] + fn tile_loads_share_one_activity_row_that_goes_with_the_last_load() { + let activity = lightcraft_engine::activity::Activity::default(); + let mut slot = Weak::new(); + let first = TileLoadEnd(join_tile_batch(&mut slot, &activity)); + let second = TileLoadEnd(join_tile_batch(&mut slot, &activity)); + + let rows = activity.list(); + assert_eq!(rows.len(), 1, "every tile load in flight shares one row"); + assert_eq!((rows[0].kind, rows[0].label.as_str()), ("download", "Loading map tiles")); + assert_eq!((rows[0].done, rows[0].total), (0, 2)); + assert!(!rows[0].cancellable); + + drop(first); + assert_eq!((activity.list()[0].done, activity.list()[0].total), (1, 2), "a finished load counts"); + drop(second); + assert!(activity.list().is_empty(), "the row goes with the last load, drawn or not"); + + // a load after that starts a new row + let third = TileLoadEnd(join_tile_batch(&mut slot, &activity)); + assert_eq!(activity.list().len(), 1); + drop(third); + assert!(activity.list().is_empty()); + } } diff --git a/docs/gaps.md b/docs/gaps.md index e18dc325ef..f1a9a7e5ac 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 ✅ (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) | +| 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP view, saved locations and filter ✅ (OSM & Esri tiles); geotag 🟡 (no drag onto the map); 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/library-shortcuts.md b/docs/library-shortcuts.md index dec917d089..44fc694195 100644 --- a/docs/library-shortcuts.md +++ b/docs/library-shortcuts.md @@ -55,6 +55,17 @@ Detail and in the full-screen preview (`F`) it keeps showing the original (Devel View → Filter Bar (`Shift+F`) works in every view. A Show Original moved to another key keeps its meaning in the grids, and `\` given to another command runs that command. +## Map view + +| Key | Action | +|---|---| +| ⌘⌥3 / Ctrl+Alt+3 | Open the Map view (View → Map) | +| `\` (backslash) | In the Map view: show / hide the map's location filter bar | +| ⌘K / Ctrl+K | In the Map view: lock / unlock the markers (elsewhere it stays Add Keywords) | + +In the Map view `\` and ⌘K follow the same rule as `\` in the grids: they act on the map only while their default +commands (Show Original, Add Keywords) keep those keys, and a key given to another command runs that command. + Flag cycling and raise/lower use each photo's own flag, so a mixed selection steps together without being made uniform. Adobe's shortcut list names the backtick "Cycle flag settings" but does not state the order; unflagged → pick → reject is LightCraft's choice. The key is the logical grave key, so it follows the keyboard layout (on layouts where it is a dead accent key, assign another key in Help → Keyboard Shortcuts to `photo.cycleFlag`). `Home` and `End` make the first or last photo of the view the active, selected one. `Shift` + `←` / diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 87f4d00f7a..60f5c4c925 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 | 45 | 26 | 17 | 8 | — | 24/27 (89%) | -| **Total** | 423 | 71 | 52 | 35 | 193/203 (95%) | 147/163 (90%) | +| Lightroom Classic extras | 44 | 27 | 17 | 8 | — | 24/27 (89%) | +| **Total** | 422 | 72 | 52 | 35 | 193/203 (95%) | 147/163 (90%) | -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. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.9%** of 546 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 58.9% of 179. ## Top gaps and shortcut notes @@ -738,7 +738,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | 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 | ✅ | `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-GEOTAG | Drag photos onto the map | P2 | 🟡 | `cmd:photo.setGps`, `cmd:photo.clearGps`, `crates/engine/src/cmd/map.rs` | `photo.setGps` sets latitude / longitude and `photo.clearGps` removes them, one undo step each. Missing: dragging photos from the grid or filmstrip onto the map, and moving a pin | | 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 | From 6b39041c7d7ecd370e8910553d915abb557e80c3 Mon Sep 17 00:00:00 2001 From: "Bruno D." Date: Sat, 14 Nov 2026 20:47:30 -0500 Subject: [PATCH 09/51] LRC-MAP-VIEW: load map tiles through a bounded pool and retry failures Most visible map tiles never loaded. Each tile got its own thread and connection, and with 60 or more tiles on screen most of them hit the 6 s connect timeout. A failed tile also stayed marked as pending forever, so it stayed blank until the app restarted. - Load at most 6 tiles at once on a shared worker pool. Newest requests go first, so tiles on screen load before tiles already panned past. - A tile that failed is retried after 5 s, and the map keeps the retry wake-up alive while it waits. First attempts always run before retries. - A cached tile that no longer decodes is deleted and downloaded again. Downloaded bytes are decoded before they are cached. Tests: map panel unit tests (10 pass) cover the pool cap, failure reporting, retry timing, retry order and replacing an undecodable cache file. The cache test fails without the fix. The full `cargo xtask ci` fails only on tests outside this change: 13 raw-decoding tests and 2 engine tests that compare against local test photos, and 1 GPU test that exhausts device memory. Co-Authored-By: Claude Haiku 5.5 --- crates/ui-egui/src/panels/map.rs | 348 +++++++++++++++++++++++++++---- 1 file changed, 304 insertions(+), 44 deletions(-) diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 82e88d46d8..fddacb44ed 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -4,7 +4,9 @@ use std::collections::{HashMap, HashSet}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; -use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, Weak}; +use std::time::Duration; +use web_time::Instant; use egui::{Align2, Color32, ColorImage, FontId, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, TextureHandle, TextureOptions, pos2, vec2}; use lightcraft_catalog::PhotoId; @@ -31,22 +33,149 @@ struct TileKey { layer: u8, } +/// At most this many tiles download at once. One connection per visible tile (60 and more on a +/// large screen) left most of them stuck past the 6 s connect timeout; a small pool loads them all. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // the web has no tile fetcher (see `fetch_and_cache_tile`) +const MAX_TILE_WORKERS: usize = 6; + +/// A tile whose load failed is asked for again after this long, not on every frame. +const TILE_RETRY_AFTER: Duration = Duration::from_secs(5); + +/// A finished tile load: the image, or `None` when it could not be fetched or decoded. +type TileResult = (TileKey, Option); + struct TileStore { textures: HashMap, pending: HashSet, - tx: Sender<(TileKey, ColorImage)>, - rx: Receiver<(TileKey, ColorImage)>, - /// The tile loads in flight, while there are any. Only the workers hold it strongly. + /// Tiles whose last load failed, and when; they are retried after [`TILE_RETRY_AFTER`]. + failed: HashMap, + tx: Sender, + rx: Receiver, + /// The tile loads in flight, while there are any. Only the queued jobs hold it strongly. batch: Weak, } impl TileStore { fn new() -> Self { let (tx, rx) = channel(); - Self { textures: HashMap::new(), pending: HashSet::new(), tx, rx, batch: Weak::new() } + Self { textures: HashMap::new(), pending: HashSet::new(), failed: HashMap::new(), tx, rx, batch: Weak::new() } + } + + /// Whether `key` should be requested now: not loaded, not in flight, and not failed recently. + fn wants(&self, key: &TileKey, now: Instant) -> bool { + !self.textures.contains_key(key) + && !self.pending.contains(key) + && self.failed.get(key).is_none_or(|at| now.saturating_duration_since(*at) >= TILE_RETRY_AFTER) + } + + /// Takes in a finished load: a failed one leaves `pending` so it can be retried later. + fn finish(&mut self, key: TileKey, ok: bool, now: Instant) { + self.pending.remove(&key); + if ok { + self.failed.remove(&key); + } else { + if self.failed.len() > 1000 { + self.failed.retain(|_, at| now.saturating_duration_since(*at) < TILE_RETRY_AFTER); + } + self.failed.insert(key, now); + } } } +/// One tile to load. Dropping it (done or never run) counts it as done in the batch's row. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +struct TileJob { + key: TileKey, + url: String, + disk_path: std::path::PathBuf, + tx: Sender, + ctx: egui::Context, + /// The tile failed before: it waits behind every tile not yet tried (see [`TileQueue::push`]). + retry: bool, + _counted: TileLoadEnd, +} + +/// A bounded set of worker threads that load tiles, newest first-attempt request first, so the +/// tiles on screen now come before ones the view has already panned past; retries come last. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +struct TilePool { + queue: Mutex, + wake: Condvar, + load: fn(&TileJob) -> Option, + max_workers: usize, +} + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +struct TileQueue { + /// Popped from the end: first attempts are pushed there (newest first), retries go to the + /// front, so a tile that keeps failing cannot starve tiles that have never been tried. + jobs: Vec, + workers: usize, +} + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +impl TileQueue { + /// Queues `job`: a first attempt is taken before every queued job, a retry after all of them. + fn push(&mut self, job: TileJob) { + if job.retry { + self.jobs.insert(0, job); + } else { + self.jobs.push(job); + } + } +} + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +impl TilePool { + fn new(load: fn(&TileJob) -> Option, max_workers: usize) -> Arc { + Arc::new(Self { queue: Mutex::new(TileQueue { jobs: Vec::new(), workers: 0 }), wake: Condvar::new(), load, max_workers }) + } + + fn submit(self: &Arc, job: TileJob) { + let mut q = self.queue.lock().unwrap_or_else(PoisonError::into_inner); + q.push(job); + if q.workers < self.max_workers { + let pool = Arc::clone(self); + let spawned = std::thread::Builder::new().name("lc-tile-fetch".into()).spawn(move || pool.work()).is_ok(); + if spawned { + q.workers += 1; + } else if q.workers == 0 { + // no worker to run it: report the jobs as failed so they are retried, not stuck + for job in q.jobs.drain(..) { + let _ = job.tx.send((job.key, None)); + } + } + } + drop(q); + self.wake.notify_one(); + } + + /// Runs jobs until none has come for a while, then ends the thread. + fn work(&self) { + loop { + let mut q = self.queue.lock().unwrap_or_else(PoisonError::into_inner); + let job = loop { + if let Some(job) = q.jobs.pop() { + break job; + } + let (guard, timeout) = self.wake.wait_timeout(q, Duration::from_secs(20)).unwrap_or_else(PoisonError::into_inner); + q = guard; + if timeout.timed_out() && q.jobs.is_empty() { + q.workers = q.workers.saturating_sub(1); + return; + } + }; + drop(q); + let img = (self.load)(&job); + let _ = job.tx.send((job.key, img)); + job.ctx.request_repaint(); + } + } +} + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +static TILE_POOL: OnceLock> = OnceLock::new(); + /// The tile loads in flight share one activity row. Each worker holds an `Arc` until it ends, so /// the last one to finish (fetched, failed or not started) drops the row, whether or not the Map /// view is still drawn. @@ -288,42 +417,44 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.map = map_ui; } -fn fetch_and_cache_tile( - key: TileKey, - url: String, - disk_path: std::path::PathBuf, - tx: Sender<(TileKey, ColorImage)>, - ctx: egui::Context, - batch: Arc, -) { +/// Queues a tile load on the shared pool. On the web there is no fetcher, so the job is dropped. +fn fetch_and_cache_tile(job: TileJob) { #[cfg(not(target_arch = "wasm32"))] - let _ = std::thread::Builder::new().name("lc-tile-fetch".into()).spawn(move || { - // ends this load in the batch's row however the worker returns - let _counted = TileLoadEnd(batch); - let bytes = if disk_path.exists() { - std::fs::read(&disk_path).ok() - } else { - match lightcraft_engine::map::fetch_tile_bytes(&url) { - Ok(b) => { - if let Some(parent) = disk_path.parent() { - let _ = std::fs::create_dir_all(parent); - } - let _ = std::fs::write(&disk_path, &b); - Some(b) - } - Err(e) => { - log::debug!("tile fetch error for {url}: {e}"); - None - } - } - }; + TILE_POOL.get_or_init(|| TilePool::new(load_tile, MAX_TILE_WORKERS)).submit(job); + #[cfg(target_arch = "wasm32")] + drop(job); +} - if let Some(rgba) = bytes.and_then(|b| lightcraft_engine::map::decode_tile(&b).ok()) { - let img = egui::ColorImage::from_rgba_unmultiplied([rgba.width, rgba.height], &rgba.as_bytes()); - let _ = tx.send((key, img)); - ctx.request_repaint(); +/// Reads a tile from the disk cache, or downloads it and caches it, then decodes it. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn load_tile(job: &TileJob) -> Option { + if let Ok(cached) = std::fs::read(&job.disk_path) { + if let Some(img) = decode_image(&cached) { + return Some(img); } - }); + // a cached file that does not decode (truncated, or from a bad response) is replaced, not retried forever + let _ = std::fs::remove_file(&job.disk_path); + } + let bytes = match lightcraft_engine::map::fetch_tile_bytes(&job.url) { + Ok(b) => b, + Err(e) => { + log::debug!("tile fetch error for {}: {e}", job.url); + return None; + } + }; + // decode before caching, so a bad response is never written to the cache + let img = decode_image(&bytes)?; + if let Some(parent) = job.disk_path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let _ = std::fs::write(&job.disk_path, &bytes); + Some(img) +} + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn decode_image(bytes: &[u8]) -> Option { + let rgba = lightcraft_engine::map::decode_tile(bytes).ok()?; + Some(ColorImage::from_rgba_unmultiplied([rgba.width, rgba.height], &rgba.as_bytes())) } fn render_tile_grid( @@ -359,11 +490,18 @@ fn render_tile_grid( let mut store_guard = TILES.lock().unwrap_or_else(PoisonError::into_inner); let store = store_guard.get_or_insert_with(TileStore::new); + let now = Instant::now(); while let Ok((key, img)) = store.rx.try_recv() { - let name = format!("tile-{}-{}-{}-{}-{}", key.provider.id(), key.layer, key.z, key.x, key.y); - let tex = p.ctx().load_texture(name, img, TextureOptions::LINEAR); - store.textures.insert(key, tex); - store.pending.remove(&key); + let ok = img.is_some(); + if let Some(img) = img { + let name = format!("tile-{}-{}-{}-{}-{}", key.provider.id(), key.layer, key.z, key.x, key.y); + let tex = p.ctx().load_texture(name, img, TextureOptions::LINEAR); + store.textures.insert(key, tex); + } else { + // draw again once the failed tile may be retried, even if nothing else moves + p.ctx().request_repaint_after(TILE_RETRY_AFTER); + } + store.finish(key, ok, now); } if store.textures.len() > 300 { @@ -389,11 +527,22 @@ fn render_tile_grid( p.image(tex.id(), tile_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } else { all_loaded = false; - if !store.pending.contains(&key) { + if store.wants(&key, now) { store.pending.insert(key); let disk_path = lightcraft_engine::map::tile_cache_path(&cache_root, provider, coord, layer_idx); let batch = join_tile_batch(&mut store.batch, activity); - fetch_and_cache_tile(key, url, disk_path, store.tx.clone(), p.ctx().clone(), batch); + fetch_and_cache_tile(TileJob { + key, + url, + disk_path, + tx: store.tx.clone(), + ctx: p.ctx().clone(), + retry: store.failed.contains_key(&key), + _counted: TileLoadEnd(batch), + }); + } else if let Some(failed_at) = store.failed.get(&key).filter(|_| !store.pending.contains(&key)) { + // keep the retry wake-up alive while cooling down; a retry already in flight needs no wake-up + p.ctx().request_repaint_after(TILE_RETRY_AFTER.saturating_sub(now.saturating_duration_since(*failed_at))); } } } @@ -973,4 +1122,115 @@ mod tests { drop(third); assert!(activity.list().is_empty()); } + + fn key(x: u32) -> TileKey { + TileKey { provider: MapProvider::OpenStreetMap, z: 10, x, y: 0, layer: 0 } + } + + /// Loads a 1x1 tile, or fails for odd `x`, while counting how many loads run at once. + fn counting_load(job: &TileJob) -> Option { + let now = RUNNING.fetch_add(1, Ordering::SeqCst) + 1; + PEAK.fetch_max(now, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(20)); + RUNNING.fetch_sub(1, Ordering::SeqCst); + job.key.x.is_multiple_of(2).then(|| ColorImage::new([1, 1], vec![Color32::WHITE])) + } + static RUNNING: AtomicU64 = AtomicU64::new(0); + static PEAK: AtomicU64 = AtomicU64::new(0); + + /// One connection per visible tile made most of them time out; the pool caps them, and + /// reports every job, failed ones included, so none stays pending. + #[test] + fn tile_pool_caps_concurrent_loads_and_reports_every_job() { + let activity = lightcraft_engine::activity::Activity::default(); + let mut slot = Weak::new(); + let pool = TilePool::new(counting_load, 3); + let (tx, rx) = channel(); + for x in 0..30 { + let job = TileJob { + key: key(x), + url: String::new(), + disk_path: std::path::PathBuf::new(), + tx: tx.clone(), + ctx: egui::Context::default(), + retry: false, + _counted: TileLoadEnd(join_tile_batch(&mut slot, &activity)), + }; + pool.submit(job); + } + let mut results: Vec = (0..30).map(|_| rx.recv_timeout(Duration::from_secs(10)).unwrap()).collect(); + results.sort_by_key(|(k, _)| k.x); + assert!(PEAK.load(Ordering::SeqCst) <= 3, "peak {}", PEAK.load(Ordering::SeqCst)); + assert!(results.iter().all(|(k, img)| img.is_some() == k.x.is_multiple_of(2)), "failures come back as None"); + // every job dropped: the row is gone + let deadline = Instant::now() + Duration::from_secs(5); + while !activity.list().is_empty() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(activity.list().is_empty()); + } + + /// Retries used to be queued newest-first like any request, so tiles that kept failing could + /// be taken again and again while visible tiles never got a first attempt. + #[test] + fn retries_wait_behind_tiles_never_tried() { + let activity = lightcraft_engine::activity::Activity::default(); + let mut slot = Weak::new(); + let (tx, _rx) = channel(); + let mut job = |x: u32, retry: bool| TileJob { + key: key(x), + url: String::new(), + disk_path: std::path::PathBuf::new(), + tx: tx.clone(), + ctx: egui::Context::default(), + retry, + _counted: TileLoadEnd(join_tile_batch(&mut slot, &activity)), + }; + let mut q = TileQueue { jobs: Vec::new(), workers: 0 }; + q.push(job(1, false)); + q.push(job(2, true)); + q.push(job(3, false)); + q.push(job(4, true)); + let order: Vec = std::iter::from_fn(|| q.jobs.pop()).map(|j| j.key.x).collect(); + assert_eq!(order, vec![3, 1, 2, 4], "first attempts newest first, then retries oldest first"); + } + + /// A cached file that no longer decodes is deleted, so the next try downloads it again instead of + /// failing on the same bytes forever. No network: the URL is unusable on purpose. + #[test] + fn an_undecodable_cached_tile_is_replaced_not_retried_forever() { + let dir = std::env::temp_dir().join(format!("lc-tile-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let disk_path = dir.join("bad.png"); + std::fs::write(&disk_path, b"not a png").unwrap(); + let job = TileJob { + key: key(1), + url: String::new(), + disk_path: disk_path.clone(), + tx: channel().0, + ctx: egui::Context::default(), + retry: true, + _counted: TileLoadEnd(join_tile_batch(&mut Weak::new(), &lightcraft_engine::activity::Activity::default())), + }; + assert!(load_tile(&job).is_none()); + assert!(!disk_path.exists(), "the undecodable cache file is removed"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A failed tile used to stay pending for good; now it is asked for again after a pause. + #[test] + fn a_failed_tile_is_retried_after_a_pause() { + let mut store = TileStore::new(); + let t0 = Instant::now(); + let k = key(1); + assert!(store.wants(&k, t0)); + store.pending.insert(k); + assert!(!store.wants(&k, t0), "in flight"); + store.finish(k, false, t0); + assert!(!store.pending.contains(&k)); + assert!(!store.wants(&k, t0 + Duration::from_secs(1)), "not on every frame"); + assert!(store.wants(&k, t0 + TILE_RETRY_AFTER), "retried after the pause"); + store.finish(k, true, t0 + TILE_RETRY_AFTER); + assert!(store.failed.is_empty()); + } } From 7cbfd8c5babf94b04f0e5be6c2784221d8966588 Mon Sep 17 00:00:00 2001 From: "Bruno D." Date: Sat, 14 Nov 2026 22:18:05 -0500 Subject: [PATCH 10/51] LRC-MAP-VIEW: map tiles under the OSM tile policy from an engine tile service; Esri layers off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Map view fetched tiles from its own pool of six threads with no cache policy, no backoff and two User-Agent headers, and offered Esri's ArcGIS tiles by default. The tile core of PR #797 is ported into the engine (crates/engine/src/map/: mercator, source, cache, service; no new crate) and the view now draws from it: - Tile sources are a library preference (prefs.json mapSource, `map.tileSource`): OpenStreetMap (default), OpenTopoMap, a checked https custom template, or Offline (no service, no threads). `map.providers` lists the sources offered; `map.cacheInfo` and `map.clearCache` report and empty the disk cache. - Fetching follows the OSM tile usage policy: only the tiles in view plus one ring, newest view first with stale requests dropped, at most two requests in flight, exponential backoff on errors/429/5xx honouring Retry-After, one distinct `LightCraft/ (+https://github.com/storytold/lightcraft)` User-Agent (fetch's `get` no longer adds a second one), no no-cache, size/content/decode checks. One "Loading map tiles" activity row while tiles are queued. - Disk cache in the per-user cache folder (`/maptiles`, new `config::cache_dir`), one folder per source: Cache-Control/Expires/ETag with conditional refresh (7 days by default), 500 MB LRU cap, atomic writes, damaged entries refetched. HTTP dates go through chrono. - Sessions fetch only when the host asks (`with_default_map_cache`: desktop app, CLI snapshot, MCP), so tests never go online; the test that hit Esri's server is gone. - UI: one texture cache (256, LRU) for the map and the navigator; a missing tile is drawn from a loaded ancestor up to four zooms up; the service gets the union of the tiles drawn this frame and the last, and nothing once no map is drawn. The credit is always painted bottom right. - `LatLon::new` rejects out-of-range positions instead of clamping them (95° was accepted as the pole); `LatLon::wrapped` wraps longitude. - Esri: their terms (docs/map.md, with URLs) allow the layers only with Esri software or an ArcGIS subscription, so they are not offered, `map.tileSource` refuses them, and a library saved with one opens on OpenStreetMap with a one-line notice while prefs.json keeps the choice. No command turns them on; that needs a maintainer decision. docs/map.md is new; control-protocol, the LRC-MAP-VIEW row and gap 16 are updated. Tests: `cargo xtask ci --quick` (fmt, clippy, tests of every package): all map, fetch, geom, config and UI tests pass; the only failures are the pre-existing ones on this machine (13 lightcraft-raw corpus tests, 2 engine corpus tests, 1 GPU out-of-memory test). `cargo xtask layers`, `assets`, `roots`, `parity` and `wasm` pass. The app was run with `--demo --control 18421` and screenshotted: OSM tiles load in the map and the navigator with the credit, Esri is refused, Offline shows the grey map. Co-Authored-By: Jason Baldwin <33934381+bitshiftza@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft-cli/src/main.rs | 3 + apps/lightcraft/src/session.rs | 15 +- crates/engine/Cargo.toml | 4 +- crates/engine/src/cmd/map.rs | 166 +++++- crates/engine/src/config.rs | 70 ++- crates/engine/src/lib.rs | 3 + crates/engine/src/library.rs | 21 + crates/engine/src/map.rs | 404 +++++++------- crates/engine/src/map/cache.rs | 597 ++++++++++++++++++++ crates/engine/src/map/http_date.rs | 68 +++ crates/engine/src/map/mercator.rs | 383 +++++++++++++ crates/engine/src/map/service.rs | 693 ++++++++++++++++++++++++ crates/engine/src/map/source.rs | 397 ++++++++++++++ crates/engine/src/map/tests_mercator.rs | 229 ++++++++ crates/engine/src/map/tests_service.rs | 504 +++++++++++++++++ crates/engine/src/tests/map.rs | 198 ++++++- crates/fetch/src/http.rs | 15 +- crates/fetch/src/tests.rs | 33 ++ crates/geom/src/geo.rs | 39 +- crates/mcp/src/headless.rs | 12 +- crates/ui-egui/locales/cs.json | 5 +- crates/ui-egui/locales/de.json | 5 +- crates/ui-egui/locales/es.json | 5 +- crates/ui-egui/locales/fi.json | 5 +- crates/ui-egui/locales/fr.json | 5 +- crates/ui-egui/locales/id.json | 5 +- crates/ui-egui/locales/it.json | 5 +- crates/ui-egui/locales/ja.json | 5 +- crates/ui-egui/locales/ka.json | 5 +- crates/ui-egui/locales/pl.json | 5 +- crates/ui-egui/locales/pt-br.json | 5 +- crates/ui-egui/locales/ru.json | 5 +- crates/ui-egui/locales/sv.json | 5 +- crates/ui-egui/locales/uk.json | 5 +- crates/ui-egui/locales/vi.json | 5 +- crates/ui-egui/locales/zh-hans.json | 5 +- crates/ui-egui/locales/zh-hant.json | 5 +- crates/ui-egui/src/docking.rs | 2 + crates/ui-egui/src/panels/map.rs | 636 +++++----------------- crates/ui-egui/src/panels/map/tiles.rs | 246 +++++++++ crates/ui-egui/src/state/map.rs | 5 +- docs/control-protocol.md | 4 + docs/gaps.md | 2 +- docs/map.md | 100 ++++ docs/parity-checklist.md | 3 +- 45 files changed, 4159 insertions(+), 778 deletions(-) create mode 100644 crates/engine/src/map/cache.rs create mode 100644 crates/engine/src/map/http_date.rs create mode 100644 crates/engine/src/map/mercator.rs create mode 100644 crates/engine/src/map/service.rs create mode 100644 crates/engine/src/map/source.rs create mode 100644 crates/engine/src/map/tests_mercator.rs create mode 100644 crates/engine/src/map/tests_service.rs create mode 100644 crates/ui-egui/src/panels/map/tiles.rs create mode 100644 docs/map.md diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index d384229558..330e647177 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -863,6 +863,7 @@ fn snapshot(args: &[String]) -> Result<(), String> { let mut s = Session::new() .with_fs() .with_default_denoise_models() + .with_default_map_cache() .with_system_clock() .with_default_face_models() .with_default_lens_database() @@ -873,6 +874,7 @@ fn snapshot(args: &[String]) -> Result<(), String> { None if files.is_empty() => Session::with_demo() .with_fs() .with_default_denoise_models() + .with_default_map_cache() .with_system_clock() .with_default_face_models() .with_default_lens_database() @@ -880,6 +882,7 @@ fn snapshot(args: &[String]) -> Result<(), String> { None => Session::new() .with_fs() .with_default_denoise_models() + .with_default_map_cache() .with_system_clock() .with_default_face_models() .with_default_lens_database() diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index 52a5a5ba03..7187797e7d 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -256,7 +256,7 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std:: /// the window lists the recent ones. pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> (Session, Option) { let (mut s, problem) = match launch { - Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None), + Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_default_map_cache().with_system_clock(), None), Launch::Open { dir, remembered, .. } => open_library_session(in_memory, dir.clone(), *remembered, seed_demo), }; // lens profiles from the app's own lensfun copy, offered on the first launch (not for a throwaway session) @@ -279,9 +279,16 @@ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> /// make a new, empty one in its place, e.g. on an unmounted drive's path (issue #3239). fn open_library_session(in_memory: bool, dir: Option, remembered: bool, seed_demo: bool) -> (Session, Option) { if in_memory { - return (if seed_demo { Session::with_demo() } else { Session::new() }.with_fs().with_default_denoise_models().with_system_clock(), None); + return ( + if seed_demo { Session::with_demo() } else { Session::new() } + .with_fs() + .with_default_denoise_models() + .with_default_map_cache() + .with_system_clock(), + None, + ); } - let unopened = || Session::new().with_fs().with_default_denoise_models().with_system_clock(); + let unopened = || Session::new().with_fs().with_default_denoise_models().with_default_map_cache().with_system_clock(); let Some(dir) = dir else { log::warn!("no library location (set --library or LIGHTCRAFT_LIBRARY)"); return (unopened(), Some(LibraryProblem::new("", "There is no home folder to keep the library in. Choose a folder for it."))); @@ -292,7 +299,7 @@ fn open_library_session(in_memory: bool, dir: Option, rememb return (unopened(), Some(LibraryProblem { existing_only: true, ..LibraryProblem::new(dir.to_string_lossy(), why) })); } let t0 = std::time::Instant::now(); - let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock(); + let mut s = Session::new().with_fs().with_default_denoise_models().with_default_map_cache().with_system_clock(); match s.open_library(&dir, seed_demo && !remembered) { Ok(r) => { let (replayed, torn) = (r.replayed, r.torn_bytes); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 1486642429..36d94b039c 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -45,12 +45,12 @@ harfrust = { version = "0.13", default-features = false, features = ["std"] } unicode-normalization = "0.1" unicode-segmentation = "1.13" lightcraft-segment = { workspace = true, optional = true } +# capture-time parsing for face recognition; HTTP dates of map tiles (map/http_date.rs) +chrono = { workspace = true } # model downloads run natively only (the web build fetches no models) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] lightcraft-fetch = { workspace = true } -# capture-time parsing for face recognition (native only) -chrono = { workspace = true } # free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys) fs4 = { workspace = true } diff --git a/crates/engine/src/cmd/map.rs b/crates/engine/src/cmd/map.rs index 5c59ff9c23..63a920e1ee 100644 --- a/crates/engine/src/cmd/map.rs +++ b/crates/engine/src/cmd/map.rs @@ -1,23 +1,171 @@ -//! Map module commands: tile provider registry, saved locations, location filtering, and GPS tagging. +//! Map module commands: tile sources and the tile cache, saved locations, location filtering, and +//! GPS tagging. The tile-source commands are ported from PR #797 (Jason Baldwin). 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}; +use crate::map::{LocationFilter, SavedLocation, TileSource, cache}; +use crate::{EngineError, Result, Session}; -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!({ +const SOURCE: &str = "map.tileSource"; + +fn source_json(s: &Session) -> Value { + let chosen = s.map.source(); + let used = s.map.effective_source(); + json!({ + "id": used.id(), + "label": used.label(), + "urlTemplate": used.url_template(), + "attribution": used.attribution(), + "maxZoom": used.max_zoom(), + "userAgent": used.user_agent(), + "offline": used.is_offline(), + "custom": matches!(used, TileSource::Custom { .. }), + // what prefs.json keeps, when the map can't use it (an Esri layer while Esri is off) + "saved": (*chosen != used).then(|| chosen.id().to_string()), + "notice": s.map.fallback_notice(), + "esriEnabled": s.map.esri_enabled(), + }) +} + +fn opt_str<'a>(p: &'a Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) => Ok(Some(v.as_str())), + Some(other) => Err(bad(SOURCE, format!("`{key}` must be text, not {other}"))), + } +} + +/// The source `{id?, urlTemplate?, attribution?, maxZoom?, offline?}` asks for, from `cur` +/// (`None`: nothing asked, report only). +fn requested(cur: &TileSource, p: &Value) -> Result> { + let id = opt_str(p, "id")?.map(str::trim).filter(|v| !v.is_empty()); + let template = opt_str(p, "urlTemplate")?.map(str::trim).filter(|v| !v.is_empty()); + let attribution = opt_str(p, "attribution")?; + let max_zoom = match p.get("maxZoom") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|z| u8::try_from(z).ok()).ok_or_else(|| bad(SOURCE, "maxZoom must be a whole number 0–24"))?), + }; + let offline = match p.get("offline") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad(SOURCE, "offline must be true or false"))?), + }; + if id.is_none() && template.is_none() && attribution.is_none() && max_zoom.is_none() && offline.is_none() { + return Ok(None); + } + if offline == Some(true) { + return Ok(Some(TileSource::Offline)); + } + if offline == Some(false) && id.is_none() && template.is_none() && cur.is_offline() { + return Ok(Some(TileSource::Osm)); + } + let check = |r: std::result::Result| r.map_err(|e| bad(SOURCE, e.to_string())); + // a built-in source by name + if template.is_none() + && attribution.is_none() + && let Some(built_in) = id.and_then(TileSource::built_in) + { + if max_zoom.is_some_and(|z| z != built_in.max_zoom()) { + return Err(bad(SOURCE, format!("{} has a fixed max zoom of {}", built_in.label(), built_in.max_zoom()))); + } + return Ok(Some(built_in)); + } + // a change to the current custom source, or a new one + let base = match cur { + TileSource::Custom { url_template, .. } if template.is_none_or(|t| t == url_template) => Some(cur), + _ => None, + }; + let Some(template) = template.or(base.and_then(TileSource::url_template)) else { + let known = TileSource::BUILT_IN.iter().map(TileSource::id).collect::>().join(", "); + return Err(bad( + SOURCE, + format!("give id (one of {known}), urlTemplate (https://…/{{z}}/{{x}}/{{y}}.png) for a tile server, or {{offline: true}}"), + )); + }; + let attribution = attribution.or(base.map(TileSource::attribution)); + let max_zoom = max_zoom.or(base.map(TileSource::max_zoom)); + let id = id.or(base.map(TileSource::id)); + check(TileSource::custom(id, template, attribution, max_zoom)).map(Some) +} + +fn tile_source(s: &mut Session, p: &Value) -> Result { + if let Some(next) = requested(s.map.source(), p)? { + let old = s.map.source().clone(); + s.map.choose(next).map_err(|e| bad(SOURCE, e))?; + // a source that can't be saved isn't kept: an error means nothing changed + if let Err(e) = s.save_prefs() { + s.map.restore(old); + return Err(e); + } + } + Ok(source_json(s)) +} + +fn providers(s: &mut Session, _: &Value) -> Result { + let current = s.map.effective_source(); + let list: Vec = s + .map + .offered() + .iter() + .map(|p| { + json!({ "id": p.id(), "label": p.label(), "maxZoom": p.max_zoom(), "attribution": p.attribution(), - })).collect(); - Ok(json!(providers)) - }), + "offline": p.is_offline(), + "current": *p == current, + }) + }) + .collect(); + Ok(json!(list)) +} + +fn cache_info(s: &mut Session, _: &Value) -> Result { + let root = s.map.cache_root.clone(); + let info = root.as_deref().map(cache::info).unwrap_or_default(); + Ok(json!({ + "bytes": info.bytes, + "tiles": info.tiles, + "capBytes": s.map.cache_bytes, + "dir": root.map(|d| d.to_string_lossy().to_string()), + })) +} + +fn clear_cache(s: &mut Session, _: &Value) -> Result { + let Some(root) = s.map.cache_root.clone() else { + return Ok(json!({"bytes": 0, "tiles": 0, "dir": Value::Null})); + }; + // the service's counters and in-memory tiles go too + s.map.reset_service(); + let gone = cache::clear(&root).map_err(|e| EngineError::Other(e.to_string()))?; + Ok(json!({"bytes": gone.bytes, "tiles": gone.tiles, "dir": root.to_string_lossy()})) +} + +pub fn specs() -> Vec { + vec![ + cmd!(query "map.providers", "Map Providers", [], None, "{} → [{id, label, maxZoom, attribution, offline, current}] — the tile sources the map offers now (the Esri layers are not offered: see docs/map.md); set one with map.tileSource", always, providers), + cmd!( + "map.tileSource", + "Map Tile Source", + [], + None, + "{} → the map's tile source; set with {id: \"osm\" | \"opentopomap\" | \"offline\"}, {offline: true|false}, or {urlTemplate: \"https://…/{z}/{x}/{y}.png\", attribution: text, maxZoom?: 0–24, id?: cache-folder name [a-z0-9._-]}; fields alone change the current custom source. The Esri layers are refused (their terms, docs/map.md). Saved with the library preferences → {id, label, urlTemplate, attribution, maxZoom, userAgent, offline, custom, saved, notice, esriEnabled}", + always, + tile_source + ), + cmd!(query "map.cacheInfo", "Map Cache Info", [], None, "{} → the map tile cache: {bytes, tiles, capBytes, dir (null = no disk cache)}", always, cache_info), + cmd!( + "map.clearCache", + "Clear Map Cache", + [], + None, + "{} — delete every cached map tile (all tile sources); tiles in view are fetched again → {bytes, tiles (deleted), dir}", + always, + clear_cache + ), 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(); diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index f7b762a6b3..23f5c4ee1c 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -1,5 +1,5 @@ //! Where LightCraft keeps per-user data on this machine: the config folder (app settings, camera -//! profiles, face and denoise models). +//! profiles, face and denoise models) and the cache folder (map tiles, [`cache_dir`]). //! //! [`config_dir`] picks it, in order: //! 1. `$LIGHTCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups). @@ -64,6 +64,41 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option, p } } +/// LightCraft's per-user cache folder, for data that can be fetched or rebuilt again (map tiles): +/// `~/Library/Caches/LightCraft` on macOS, `%LOCALAPPDATA%\LightCraft\Cache` on Windows, +/// `$XDG_CACHE_HOME/lightcraft` (else `~/.cache/lightcraft`) elsewhere. In portable mode it is +/// `/LightCraftData/Cache`, so tiles stay on the portable medium too. +pub fn cache_dir() -> Option { + let platform = if cfg!(target_os = "macos") { + Platform::Mac + } else if cfg!(windows) { + Platform::Windows + } else { + Platform::Other + }; + cache_dir_with(platform, |name| std::env::var_os(name), portable_dir) +} + +fn cache_dir_with(platform: Platform, env: impl Fn(&str) -> Option, portable: impl FnOnce() -> Option) -> Option { + if let Some(dir) = portable() { + return Some(dir.join("Cache")); + } + let set = |name: &str| env(name).filter(|v| !v.is_empty()); + match platform { + Platform::Mac => set("HOME").map(|h| PathBuf::from(h).join("Library/Caches/LightCraft")), + Platform::Windows => set("LOCALAPPDATA").map(|a| PathBuf::from(a).join("LightCraft").join("Cache")), + Platform::Other => { + set("XDG_CACHE_HOME").map(PathBuf::from).or_else(|| set("HOME").map(|h| PathBuf::from(h).join(".cache"))).map(|c| c.join("lightcraft")) + } + } +} + +/// Where map tiles are cached: a nonempty `$LIGHTCRAFT_MAP_CACHE` if set, else `/maptiles` +/// (one folder per tile source inside; see docs/map.md). +pub fn default_map_cache_dir() -> Option { + std::env::var_os("LIGHTCRAFT_MAP_CACHE").filter(|v| !v.is_empty()).map(PathBuf::from).or_else(|| cache_dir().map(|d| d.join("maptiles"))) +} + /// This process's portable data folder, if a marker sits beside its executable and the folder can be /// written. Resolved once: the check creates the folder and writes a probe file. fn portable_dir() -> Option { @@ -166,6 +201,15 @@ impl Session { self } + /// Fetch map tiles from the network and cache them in the shared default folder + /// ([`default_map_cache_dir`]). Without this a session never fetches tiles (tests). + pub fn with_default_map_cache(mut self) -> Self { + self.map.cache_root = default_map_cache_dir(); + self.map.online = true; + self.map.reset_service(); + self + } + /// Keep denoise models in the shared default folder ([`default_denoise_models_dir`]). pub fn with_default_denoise_models(mut self) -> Self { self.set_denoise_models_dir(default_denoise_models_dir()); @@ -229,6 +273,30 @@ mod config_tests { let _ = std::fs::remove_dir_all(&exe); } + /// Map tiles go to the platform's cache folder, never the settings folder, and to the portable + /// folder in portable mode. + #[test] + fn the_cache_folder_follows_the_platform_and_portable_mode() { + let env = |name: &str| match name { + "HOME" => Some(OsString::from("/home/u")), + "LOCALAPPDATA" => Some(OsString::from("/local")), + "XDG_CACHE_HOME" => Some(OsString::from("")), + _ => None, + }; + assert_eq!(cache_dir_with(Platform::Mac, env, || None), Some(PathBuf::from("/home/u/Library/Caches/LightCraft"))); + assert_eq!(cache_dir_with(Platform::Windows, env, || None), Some(PathBuf::from("/local").join("LightCraft").join("Cache"))); + assert_eq!( + cache_dir_with(Platform::Other, env, || None), + Some(PathBuf::from("/home/u/.cache").join("lightcraft")), + "an empty XDG_CACHE_HOME is unset" + ); + assert_eq!( + cache_dir_with(Platform::Other, env, || Some(PathBuf::from("/usb/LightCraftData"))), + Some(PathBuf::from("/usb/LightCraftData/Cache")) + ); + assert_eq!(cache_dir_with(Platform::Windows, |_| None, || None), None); + } + #[test] fn config_override_wins_without_reading_user_profile() { for platform in [Platform::Mac, Platform::Windows, Platform::Other] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 566abd9182..b33753ef30 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -361,6 +361,8 @@ pub struct Session { pub print_templates: Vec, /// Saved geographical bookmarks for the Map module (`map.savedLocations.*`). pub saved_locations: Vec, + /// The map's tile source (persisted in prefs.json), tile cache folder and tile service. + pub map: map::MapState, /// Metadata presets (`metadata.*`), persisted in prefs.json. pub metadata_presets: Vec, /// Saved filter-bar settings (`filter.*`), persisted in prefs.json. @@ -535,6 +537,7 @@ impl Session { print: Default::default(), print_templates: Vec::new(), saved_locations: Vec::new(), + map: map::MapState::default(), metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 2aed6e7ccd..7f88458547 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -278,6 +278,19 @@ fn lenient_prep<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + use serde::Deserialize; + let value = Option::::deserialize(d)?; + Ok(value.and_then(|value| match serde_json::from_value::(value) { + Ok(source) => Some(source), + Err(e) => { + log::warn!("prefs.json mapSource: {e}; using OpenStreetMap"); + None + } + })) +} + #[derive(Default, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] struct PrefsFile { @@ -338,6 +351,10 @@ struct PrefsFile { /// User-saved map locations. #[serde(default, skip_serializing_if = "Vec::is_empty")] saved_locations: Vec, + /// The map's tile source (missing = OpenStreetMap; re-checked when read). A damaged one is + /// dropped on its own, never taking the other preferences with it. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "lenient_tile_source")] + map_source: Option, } fn presets_json(s: &Session) -> String { @@ -656,6 +673,9 @@ impl Session { self.forget_local_days = prefs.forget_local_days.unwrap_or(lightcraft_catalog::DEFAULT_FORGET_DAYS); self.hold_view = prefs.hold_view; self.saved_locations = prefs.saved_locations; + if let Some(notice) = self.map.load_source(prefs.map_source) { + settings.warnings.push(notice); + } self.refresh_view(); self.smart_previews_dir = prefs.smart_previews_dir.filter(|_| on_disk).map(PathBuf::from); if let Some(d) = &self.smart_previews_dir { @@ -978,6 +998,7 @@ impl Session { slide_titles: self.slide_titles.clone(), hold_view: self.hold_view, saved_locations: self.saved_locations.clone(), + map_source: Some(self.map.source().clone()), }) .unwrap_or_default(); let Some(lib) = self.library.as_mut() else { return Ok(()) }; diff --git a/crates/engine/src/map.rs b/crates/engine/src/map.rs index aed34f032a..764db50e95 100644 --- a/crates/engine/src/map.rs +++ b/crates/engine/src/map.rs @@ -1,101 +1,205 @@ -//! Map providers, tile URLs, saved locations, and geographic filtering for the Map module. +//! The Map module below the UI: Web Mercator maths ([`mercator`]), tile sources ([`source`]), the +//! on-disk tile cache ([`cache`]) and the tile fetch queue ([`service`]), plus the map's state in +//! the session ([`MapState`]), saved locations and the location filter. +//! +//! Nothing touches the network until a map view asks for tiles: the service is created on first +//! use ([`Session::map_tiles`]) and only fetches the tiles of the views it is shown, following the +//! OpenStreetMap tile usage policy (`docs/map.md`). A session has no cache folder and never goes +//! online until the host asks ([`Session::with_default_map_cache`]), so tests stay hermetic. The offline source +//! starts no service at all. Commands: `map.tileSource`, `map.providers`, `map.cacheInfo`, +//! `map.clearCache` (`cmd/map.rs`). +//! +//! The tile core (mercator, source validation, cache, service) is ported from PR #797 +//! (Jason Baldwin), moved from its own crate into the engine. -use lightcraft_geom::{LatLon, TileCoord}; +pub mod cache; +mod http_date; +pub mod mercator; +pub mod service; +pub mod source; + +#[cfg(test)] +mod tests_mercator; +#[cfg(test)] +mod tests_service; + +use std::path::PathBuf; + +use lightcraft_geom::LatLon; use serde::{Deserialize, Serialize}; -use std::path::{Path, PathBuf}; -/// Available slippy map tile providers for LightCraft. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, 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, +use crate::Session; +pub use cache::{CacheInfo, DEFAULT_CACHE_BYTES, TileCache, TileMeta}; +pub use mercator::{Bounds, MAX_LATITUDE, MAX_ZOOM, TILE_SIZE, TileKey, Viewport, VisibleTile, fit_bounds, from_gps}; +pub use service::{HttpResponse, ServiceStats, TileEvent, TileImage, TileService, Transport}; +pub use source::{OSM_ATTRIBUTION, OSM_TILE_URL, TileSource, USER_AGENT}; + +/// What went wrong in the map core. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum MapError { + /// A tile source setting that can't be used (template, id, attribution, zoom). + #[error("tile source: {0}")] + InvalidSource(String), + /// A cache file or folder problem (disk full, permissions…). + #[error("map tile cache: {0}")] + Io(String), + /// A tile that isn't a usable image. + #[error("map tile: {0}")] + BadTile(String), } -impl MapProvider { - pub const ALL: [MapProvider; 5] = - [MapProvider::OpenStreetMap, MapProvider::EsriImagery, MapProvider::EsriStreets, MapProvider::EsriTopo, MapProvider::EsriHybrid]; +/// Seconds since the Unix epoch, now (0 if the clock is before 1970). +pub(crate) fn now_secs() -> i64 { + web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)).unwrap_or(0) +} - /// 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", +/// Why the Esri layers can't be turned on: their terms (read 2026-11-14, `docs/map.md`) allow +/// them only with Esri software or an ArcGIS subscription, which LightCraft isn't and doesn't have. +pub const ESRI_UNAVAILABLE: &str = + "the Esri map layers are off: Esri's terms allow them only with Esri software or an ArcGIS subscription (see docs/map.md)"; + +/// The map's state in the session (see the module docs). +#[derive(Debug)] +pub struct MapState { + /// The tile source the user chose, saved in prefs.json as it is. An Esri source while Esri is + /// off is kept here (never overwritten) but not used: see [`MapState::effective_source`]. + source: TileSource, + /// The Esri layers may be offered and fetched. Off, and no command turns it on: Esri's terms + /// don't allow LightCraft to use them (`docs/map.md`); only tests set it, to check the gate. + esri_enabled: bool, + /// The tile cache folder (`/maptiles`, one folder per source inside); `None` = tiles + /// are kept in memory only (tests, the web). + pub cache_root: Option, + /// Size cap of the tile cache, all sources together. + pub cache_bytes: u64, + /// Tiles may be fetched from the network. Off until the host asks + /// ([`Session::with_default_map_cache`]), so tests and sessions without one never go online. + pub online: bool, + service: Option, +} + +impl Default for MapState { + fn default() -> Self { + MapState { source: TileSource::Osm, esri_enabled: false, cache_root: None, cache_bytes: DEFAULT_CACHE_BYTES, online: false, service: None } + } +} + +impl MapState { + /// The tile source the user chose (what prefs.json stores). + pub fn source(&self) -> &TileSource { + &self.source + } + + /// The source the map draws and fetches: the chosen one, or OpenStreetMap while the chosen + /// one needs an opt-in that isn't given. + pub fn effective_source(&self) -> TileSource { + if self.usable(&self.source) { self.source.clone() } else { TileSource::Osm } + } + + /// Whether the Esri layers may be offered and fetched. + pub fn esri_enabled(&self) -> bool { + self.esri_enabled + } + + /// `source` may be used now (an Esri layer only with the opt-in). + pub fn usable(&self, source: &TileSource) -> bool { + !source.requires_opt_in() || self.esri_enabled + } + + /// The built-in sources a picker offers: those usable now. + pub fn offered(&self) -> Vec { + TileSource::BUILT_IN.into_iter().filter(|s| self.usable(s)).collect() + } + + /// A one-line notice while the chosen source can't be used (the map shows OpenStreetMap). + pub fn fallback_notice(&self) -> Option { + (!self.usable(&self.source)).then(|| format!("The map shows OpenStreetMap instead of {}: {ESRI_UNAVAILABLE}.", self.source.label())) + } + + /// Use `source` from now on (the next [`Session::map_tiles`] starts a service for it). An Esri + /// source while Esri is off is refused and nothing changes. + pub fn choose(&mut self, source: TileSource) -> Result<(), String> { + if !self.usable(&source) { + return Err(format!("{}: {ESRI_UNAVAILABLE}", source.label())); + } + if source != self.source { + self.source = source; + self.reset_service(); + } + Ok(()) + } + + /// Put back a choice that couldn't be saved (no checks: it was the choice before). + pub(crate) fn restore(&mut self, source: TileSource) { + if source != self.source { + self.source = source; + self.reset_service(); } } - /// 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", + /// Take the source a settings file stored, re-checked (it is hostile input): an unusable one + /// falls back to OpenStreetMap, with a log line. An Esri source while Esri is off is kept as + /// the choice (prefs.json keeps it) but the map shows OpenStreetMap; the returned notice says so. + pub(crate) fn load_source(&mut self, stored: Option) -> Option { + let source = match stored.map(|s| s.checked()) { + None => TileSource::Osm, + Some(Ok(s)) => s, + Some(Err(e)) => { + log::warn!("map: the saved tile source can't be used ({e}); using OpenStreetMap"); + TileSource::Osm + } + }; + self.restore(source); + let notice = self.fallback_notice(); + if let Some(n) = ¬ice { + log::warn!("map: {n}"); + } + notice + } + + /// Let tests turn the Esri gate on (there is no command for it; see [`ESRI_UNAVAILABLE`]). + #[cfg(test)] + pub(crate) fn set_esri_enabled(&mut self, on: bool) { + if on != self.esri_enabled { + self.esri_enabled = on; + self.reset_service(); } } - /// 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)) + /// Stop the tile service (its threads end; the next use starts a fresh one). + pub fn reset_service(&mut self) { + self.service = None; } - /// 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, - } + /// Load tiles with `service` from now on (tests with a fake transport, hosts with their own). + /// It is used while its source is [`MapState::effective_source`]; a change of source replaces it. + pub fn set_service(&mut self, service: TileService) { + self.service = Some(service); } - /// 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" - } - } + /// The service if one is running (no side effects). + pub fn service(&self) -> Option<&TileService> { + self.service.as_ref() } +} - /// 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}"), - ] - } +impl Session { + /// The tile service for the effective source, started on first use; `None` for the offline + /// source (no tiles, no network, no threads). The map view hands it the tiles it draws + /// ([`TileService::want`]), draws [`TileService::get`] and polls [`TileService::poll`] for + /// arrivals; nothing here blocks on disk or network. + pub fn map_tiles(&mut self) -> Option<&TileService> { + let source = self.map.effective_source(); + if source.is_offline() { + self.map.service = None; + return None; } + let activity = self.activity.clone(); + let m = &mut self.map; + if m.service.as_ref().is_some_and(|s| *s.source() != source) { + m.service = None; + } + Some(m.service.get_or_insert_with(|| TileService::new(source, m.cache_root.clone(), m.cache_bytes, Some(activity), m.online))) } } @@ -161,100 +265,10 @@ impl LocationFilter { } } -/// Base directory for caching downloaded map tiles locally. -pub fn tile_cache_dir() -> PathBuf { - crate::config::config_dir().map(|d| d.join("map-tiles")).unwrap_or_else(|| std::env::temp_dir().join("lightcraft-tiles")) -} - -/// 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 { - let ext = match provider { - MapProvider::EsriImagery => "jpg", - MapProvider::EsriHybrid if layer_index == 0 => "jpg", - _ => "png", - }; - cache_root - .join("tiles") - .join(provider.id()) - .join(layer_index.to_string()) - .join(coord.z.to_string()) - .join(coord.x.to_string()) - .join(format!("{}.{ext}", coord.y)) -} - -/// Pure-Rust network fetch for a map tile. -/// Largest map tile accepted from a server; real 256 px tiles are tens of KiB. -#[cfg(not(target_arch = "wasm32"))] -const MAX_TILE_BYTES: usize = 2 * 1024 * 1024; - -#[cfg(not(target_arch = "wasm32"))] -pub fn fetch_tile_bytes(url_str: &str) -> std::result::Result, String> { - use lightcraft_fetch::http::{Limits, Url}; - use std::sync::atomic::AtomicBool; - use std::time::Duration; - - let url = Url::parse(url_str).map_err(|e| format!("invalid tile url: {e}"))?; - let headers = [ - ("User-Agent", "LightCraft/0.9 (https://github.com/storytold/lightcraft; photo-editor)".to_string()), - ("Accept", "image/png,image/jpeg,image/*,*/*".to_string()), - ]; - let cancel = AtomicBool::new(false); - let limits = Limits { connect: Duration::from_secs(6), stall: Duration::from_secs(12), cancel: &cancel }; - let mut resp = lightcraft_fetch::http::get(&url, &headers, &limits).map_err(|e| format!("fetch tile failed: {e}"))?; - if resp.status != 200 { - return Err(format!("fetch tile HTTP {}", resp.status)); - } - // The announced length comes from the server: refuse one past the cap instead of reserving it. - let announced = resp.content_length(); - if announced.is_some_and(|n| n > MAX_TILE_BYTES as u64) { - return Err("tile size exceeds 2 MiB".into()); - } - let capacity = announced.and_then(|n| usize::try_from(n).ok()).unwrap_or(32 * 1024).min(MAX_TILE_BYTES); - let mut bytes = Vec::with_capacity(capacity); - let mut buf = [0u8; 8192]; - loop { - let n = resp.read(&mut buf, &limits).map_err(|e| format!("read tile stream: {e}"))?; - if n == 0 { - break; - } - bytes.extend_from_slice(buf.get(..n).unwrap_or_default()); - if bytes.len() > MAX_TILE_BYTES { - return Err("tile size exceeds 2 MiB".into()); - } - } - Ok(bytes) -} - -#[cfg(target_arch = "wasm32")] -pub fn fetch_tile_bytes(_url_str: &str) -> std::result::Result, String> { - Err("tile fetching on web is not implemented via sync engine".into()) -} - -/// Decodes tile PNG or JPEG bytes into 8-bit RGBA raster pixels. -pub fn decode_tile(bytes: &[u8]) -> std::result::Result { - let opts = lightcraft_codecs::DecodeOptions::default(); - let decoded = lightcraft_codecs::decode(bytes, opts).map_err(|e| format!("decode tile: {e}"))?; - Ok(decoded.to_srgb8()) -} - #[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); @@ -267,39 +281,25 @@ mod tests { assert!(!loc.contains(LatLon { lat: 51.6000, lon: -0.1278 })); } - /// Serves one response with `head` (status line and headers) and `body` from a local server - /// (never the internet) and returns the tile URL that reaches it. - #[cfg(not(target_arch = "wasm32"))] - fn serve_once(head: &'static str, body: &'static [u8]) -> (String, std::thread::JoinHandle<()>) { - use std::io::{Read, Write}; - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - let server = std::thread::spawn(move || { - let Ok((mut stream, _)) = listener.accept() else { return }; - let mut request = [0u8; 1024]; - let _ = stream.read(&mut request); - let _ = stream.write_all(head.as_bytes()); - let _ = stream.write_all(body); - }); - (format!("http://127.0.0.1:{port}/6/25/31.png"), server) - } - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn a_huge_announced_tile_length_is_an_error_not_an_allocation() { - // A server announcing u64::MAX bytes used to size the buffer from that number and panic - // with a capacity overflow before reading a byte. - let (url, server) = serve_once("HTTP/1.1 200 OK\r\nContent-Length: 18446744073709551615\r\n\r\n", b"tile"); - let err = fetch_tile_bytes(&url).unwrap_err(); - assert!(err.contains("2 MiB"), "{err}"); - server.join().unwrap(); - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn a_tile_with_an_honest_length_is_read_whole() { - let (url, server) = serve_once("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n", b"tile"); - assert_eq!(fetch_tile_bytes(&url).unwrap(), b"tile"); - server.join().unwrap(); + fn esri_is_neither_offered_nor_used_until_enabled() { + let mut m = MapState::default(); + assert!(!m.esri_enabled()); + assert!(m.offered().iter().all(|s| !s.requires_opt_in()), "{:?}", m.offered()); + assert!(m.choose(TileSource::EsriImagery).unwrap_err().contains("Esri")); + assert_eq!(*m.source(), TileSource::Osm, "a refusal changes nothing"); + // a saved Esri choice is kept but not used, with a notice + let notice = m.load_source(Some(TileSource::EsriTopo)).unwrap(); + assert!(notice.contains("OpenStreetMap") && notice.contains("Esri"), "{notice}"); + assert_eq!(*m.source(), TileSource::EsriTopo); + assert_eq!(m.effective_source(), TileSource::Osm); + // the gate itself: with the opt-in the same choices are accepted and used + m.set_esri_enabled(true); + assert_eq!(m.effective_source(), TileSource::EsriTopo); + assert!(m.offered().contains(&TileSource::EsriImagery)); + m.choose(TileSource::EsriImagery).unwrap(); + assert_eq!(m.fallback_notice(), None); + m.set_esri_enabled(false); + assert_eq!(m.effective_source(), TileSource::Osm); } } diff --git a/crates/engine/src/map/cache.rs b/crates/engine/src/map/cache.rs new file mode 100644 index 0000000000..8ef47e93b6 --- /dev/null +++ b/crates/engine/src/map/cache.rs @@ -0,0 +1,597 @@ +//! The on-disk tile cache. +//! +//! Layout: `////.tile`, one file per tile holding a small header (magic, +//! JSON [`TileMeta`]: when it was fetched, when it expires, its ETag and Last-Modified) and the +//! image bytes as the server sent them. `` is LightCraft's cache folder's `map-tiles` (the +//! engine picks it); every source has its own folder, so switching sources never mixes tiles. +//! +//! - **Freshness** follows the server: `Cache-Control: max-age`, else `Expires`, else 7 days +//! ([`DEFAULT_FRESH_SECS`]); `no-cache` means "revalidate every time" and `no-store` means "don't +//! write it". An expired tile is still shown while a conditional request (If-None-Match / +//! If-Modified-Since) refreshes it; a 304 answer only updates its metadata. Tiles are never +//! deleted for being old, only to stay under the size cap. +//! - **Size cap** ([`DEFAULT_CACHE_BYTES`], for all sources together): when a write takes the +//! cache past it, the least recently used tiles (file modification time, bumped when a tile is +//! read) are deleted until it is back under 90 % of the cap. +//! - **Atomic writes**: a tile is written to a unique `.part` file and renamed into place, so a +//! crash never leaves a half-written tile under its real name (stale `.part` files are swept by +//! eviction and [`clear`]). +//! - **Damage**: an entry that can't be parsed (truncated, wrong magic, bad metadata, oversized) is +//! deleted when read and fetched again; nothing here panics on a hostile file. + +use std::fs::{self, File}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::PoisonError; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +use super::mercator::TileKey; +use super::source::validate_id; +use crate::map::MapError; + +/// Default size cap of the tile cache (all sources together). +pub const DEFAULT_CACHE_BYTES: u64 = 500 << 20; +/// How long a tile is fresh when the server gives no Cache-Control max-age or Expires (the OSMF +/// policy asks for at least 7 days). +pub const DEFAULT_FRESH_SECS: i64 = 7 * 86_400; +/// Longest freshness believed (a server saying "100 years" gets this). +const MAX_FRESH_SECS: i64 = 365 * 86_400; +/// Largest cache file read (a tile is tens of kB; anything this big is damage). +pub const MAX_ENTRY_BYTES: u64 = 4 << 20; +/// Largest metadata header. +const MAX_META: usize = 8 * 1024; +/// A read bumps the access time when it is older than this (keeps reads from writing every time). +const TOUCH_AFTER_SECS: i64 = 600; +/// `.part` files older than this belong to a crashed writer and are swept. +const STALE_PART_SECS: i64 = 3600; +/// Most files looked at by one walk of the cache (bounds a hostile or huge folder). +const MAX_WALK: usize = 1_000_000; +const MAGIC: &[u8; 8] = b"LCTILE1\n"; + +/// What the cache knows about a tile besides its bytes. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct TileMeta { + /// When it was fetched or last revalidated (Unix seconds). + pub fetched: i64, + /// Fresh until (Unix seconds); after that it is shown but revalidated. + pub expires: i64, + pub etag: Option, + pub last_modified: Option, +} + +impl TileMeta { + /// Metadata for a fresh `200` response with headers `header` (case-insensitive lookup), and + /// whether it may be stored (`no-store` says no). + pub fn from_response<'a>(now: i64, header: impl Fn(&str) -> Option<&'a str>) -> (TileMeta, bool) { + let (expires, store) = freshness(now, header("cache-control"), header("expires"), header("date")); + let keep = + |v: Option<&str>| v.map(str::trim).filter(|v| !v.is_empty() && v.len() <= 256 && !v.chars().any(char::is_control)).map(str::to_string); + (TileMeta { fetched: now, expires, etag: keep(header("etag")), last_modified: keep(header("last-modified")) }, store) + } + + /// The metadata after a `304 Not Modified` with headers `header`: new freshness, and the + /// validators the server sent (else the old ones). + pub fn revalidated<'a>(&self, now: i64, header: impl Fn(&str) -> Option<&'a str>) -> TileMeta { + let (fresh, _) = TileMeta::from_response(now, header); + TileMeta { + fetched: now, + expires: fresh.expires, + etag: fresh.etag.or_else(|| self.etag.clone()), + last_modified: fresh.last_modified.or_else(|| self.last_modified.clone()), + } + } + + /// Fresh at `now` (else shown, but revalidated). + pub fn is_fresh(&self, now: i64) -> bool { + now < self.expires + } + + /// The headers of a conditional request for this tile (If-None-Match, If-Modified-Since). + pub fn conditional_headers(&self) -> Vec<(&'static str, String)> { + let mut h = Vec::new(); + if let Some(e) = &self.etag { + h.push(("If-None-Match", e.clone())); + } + if let Some(m) = &self.last_modified { + h.push(("If-Modified-Since", m.clone())); + } + h + } +} + +/// When a response fetched at `now` stops being fresh, from its `Cache-Control`, `Expires` and +/// `Date` headers, and whether it may be stored. `max-age` wins over `Expires` (RFC 9111); an +/// `Expires` is taken relative to the server's `Date` when there is one (clock skew); an +/// unparsable `Expires` means already expired. Neither: [`DEFAULT_FRESH_SECS`]. +pub fn freshness(now: i64, cache_control: Option<&str>, expires: Option<&str>, date: Option<&str>) -> (i64, bool) { + let mut store = true; + let mut max_age: Option = None; + let mut no_cache = false; + for d in cache_control.unwrap_or_default().split(',') { + let d = d.trim().to_ascii_lowercase(); + let (name, value) = match d.split_once('=') { + Some((n, v)) => (n.trim().to_string(), Some(v.trim().trim_matches('"').to_string())), + None => (d.clone(), None), + }; + match name.as_str() { + "no-store" => store = false, + "no-cache" => no_cache = true, + // a bad max-age counts as 0 (RFC 9111 §4.2.1) + "max-age" => max_age = Some(value.and_then(|v| v.parse::().ok()).map_or(0, |v| i64::try_from(v).unwrap_or(i64::MAX))), + _ => {} + } + } + let lifetime = if no_cache { + 0 + } else if let Some(age) = max_age { + age + } else if let Some(exp) = expires { + match crate::map::http_date::parse(exp) { + Some(e) => match date.and_then(crate::map::http_date::parse) { + Some(d) => e.saturating_sub(d), + None => e.saturating_sub(now), + }, + None => 0, + } + } else { + DEFAULT_FRESH_SECS + }; + (now.saturating_add(lifetime.clamp(0, MAX_FRESH_SECS)), store) +} + +/// A tile read from the cache. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CachedTile { + pub meta: TileMeta, + /// The image file as the server sent it. + pub bytes: Vec, +} + +/// How much the cache holds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct CacheInfo { + pub bytes: u64, + pub tiles: u64, +} + +/// One source's tiles in the cache folder `root`. +#[derive(Debug)] +pub struct TileCache { + root: PathBuf, + dir: PathBuf, + cap: u64, + /// Bytes in the whole cache as last counted plus what was written since (counted on the first + /// write; `None` until then). + tally: Mutex>, +} + +static PART_SEQ: AtomicU64 = AtomicU64::new(0); + +impl TileCache { + /// The cache of source `source_id` under `root`, capped at `cap` bytes for all sources. + /// Nothing is touched on disk until a tile is written. + pub fn new(root: impl Into, source_id: &str, cap: u64) -> Result { + validate_id(source_id)?; + let root = root.into(); + let dir = root.join(source_id); + Ok(TileCache { root, dir, cap: cap.max(1 << 20), tally: Mutex::new(None) }) + } + + /// The cache folder (all sources). + pub fn root(&self) -> &Path { + &self.root + } + + /// This source's folder. + pub fn dir(&self) -> &Path { + &self.dir + } + + fn path(&self, key: TileKey) -> PathBuf { + self.dir.join(key.z.to_string()).join(key.x.to_string()).join(format!("{}.tile", key.y)) + } + + /// The cached tile, if there is a readable one. A damaged entry is deleted (and `None` + /// returned, so the tile is fetched again). Marks the tile as recently used. + pub fn read(&self, key: TileKey) -> Option { + let path = self.path(key); + let md = fs::symlink_metadata(&path).ok()?; + if !md.is_file() { + return None; + } + let parsed = if md.len() > MAX_ENTRY_BYTES { None } else { fs::read(&path).ok().and_then(|b| parse_entry(&b)) }; + let Some(tile) = parsed else { + log::warn!("map cache: deleting damaged tile {}", path.display()); + let _ = fs::remove_file(&path); + return None; + }; + let now = crate::map::now_secs(); + if md.modified().ok().map(secs_of).is_none_or(|m| now.saturating_sub(m) > TOUCH_AFTER_SECS) { + touch(&path, now); + } + Some(tile) + } + + /// Store `bytes` with `meta` (atomically), then evict least recently used tiles if the cache + /// went past its cap. + pub fn write(&self, key: TileKey, meta: &TileMeta, bytes: &[u8]) -> Result<(), MapError> { + let path = self.path(key); + let old = fs::symlink_metadata(&path).ok().filter(|m| m.is_file()).map_or(0, |m| m.len()); + let size = write_entry(&path, meta, bytes)?; + let mut tally = self.tally.lock().unwrap_or_else(PoisonError::into_inner); + let total = match *tally { + Some(t) => t.saturating_sub(old).saturating_add(size), + None => info(&self.root).bytes, + }; + *tally = Some(if total > self.cap { evict(&self.root, self.cap / 10 * 9).bytes } else { total }); + Ok(()) + } + + /// Replace a cached tile's metadata, keeping its bytes (after a 304). `false` when the tile is + /// no longer cached. + pub fn refresh(&self, key: TileKey, meta: &TileMeta) -> Result { + let Some(tile) = self.read(key) else { return Ok(false) }; + write_entry(&self.path(key), meta, &tile.bytes)?; + Ok(true) + } + + /// Forget a tile (e.g. its bytes turned out not to decode). + pub fn remove(&self, key: TileKey) { + let _ = fs::remove_file(self.path(key)); + } +} + +fn secs_of(t: std::time::SystemTime) -> i64 { + t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) +} + +fn touch(path: &Path, now: i64) { + let t = std::time::UNIX_EPOCH + Duration::from_secs(u64::try_from(now).unwrap_or(0)); + if let Ok(f) = File::options().write(true).open(path) { + let _ = f.set_modified(t); + } +} + +fn parse_entry(b: &[u8]) -> Option { + let rest = b.strip_prefix(MAGIC.as_slice())?; + let len = u32::from_le_bytes(rest.get(..4)?.try_into().ok()?) as usize; + if len > MAX_META { + return None; + } + let meta: TileMeta = serde_json::from_slice(rest.get(4..4usize.checked_add(len)?)?).ok()?; + let bytes = rest.get(4 + len..)?; + (!bytes.is_empty()).then(|| CachedTile { meta, bytes: bytes.to_vec() }) +} + +fn write_entry(path: &Path, meta: &TileMeta, bytes: &[u8]) -> Result { + let io = |what: &str, e: std::io::Error| MapError::Io(format!("{what} {}: {e}", path.display())); + let meta = serde_json::to_vec(meta).map_err(|e| MapError::Io(e.to_string()))?; + if meta.len() > MAX_META || bytes.is_empty() { + return Err(MapError::BadTile("nothing to cache".into())); + } + let mut data = Vec::with_capacity(MAGIC.len() + 4 + meta.len() + bytes.len()); + data.extend_from_slice(MAGIC); + data.extend_from_slice(&(meta.len() as u32).to_le_bytes()); + data.extend_from_slice(&meta); + data.extend_from_slice(bytes); + if data.len() as u64 > MAX_ENTRY_BYTES { + return Err(MapError::BadTile("tile too large to cache".into())); + } + let parent = path.parent().ok_or_else(|| MapError::Io("tile path has no folder".into()))?; + fs::create_dir_all(parent).map_err(|e| io("creating", e))?; + let seq = PART_SEQ.fetch_add(1, Ordering::Relaxed); + let part = path.with_extension(format!("tile.{}-{seq}.part", std::process::id())); + let written = File::create(&part).and_then(|mut f| f.write_all(&data)).and_then(|()| fs::rename(&part, path)); + if let Err(e) = written { + let _ = fs::remove_file(&part); + return Err(io("writing", e)); + } + Ok(data.len() as u64) +} + +/// A file of the cache: path, size, last use. +struct Entry { + path: PathBuf, + len: u64, + used: i64, +} + +/// Every `.tile` under `root` at `///` (sources with valid ids only; no +/// symlinks followed). Stale `.part` files met on the way are deleted when `sweep`. +fn walk(root: &Path, sweep: bool) -> Vec { + let now = crate::map::now_secs(); + let mut out = Vec::new(); + let mut seen = 0usize; + let dirs = |p: &Path| -> Vec { + fs::read_dir(p) + .map(|rd| rd.filter_map(Result::ok).filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()).collect()) + .unwrap_or_default() + }; + let numeric = + |p: &Path| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| !n.is_empty() && n.len() <= 10 && n.bytes().all(|b| b.is_ascii_digit())); + for source in dirs(root) { + if source.file_name().and_then(|n| n.to_str()).is_none_or(|n| validate_id(n).is_err()) { + continue; + } + for z in dirs(&source).into_iter().filter(|p| numeric(p)) { + for x in dirs(&z).into_iter().filter(|p| numeric(p)) { + let Ok(rd) = fs::read_dir(&x) else { continue }; + for e in rd.filter_map(Result::ok) { + seen += 1; + if seen > MAX_WALK { + return out; + } + let Ok(md) = e.metadata() else { continue }; + if !md.is_file() || e.file_type().is_ok_and(|t| t.is_symlink()) { + continue; + } + let name = e.file_name(); + let name = name.to_string_lossy(); + let used = md.modified().ok().map_or(0, secs_of); + if name.ends_with(".part") { + if sweep && now.saturating_sub(used) > STALE_PART_SECS { + let _ = fs::remove_file(e.path()); + } + } else if name.ends_with(".tile") { + out.push(Entry { path: e.path(), len: md.len(), used }); + } + } + } + } + } + out +} + +/// How much the cache under `root` holds (all sources). +pub fn info(root: &Path) -> CacheInfo { + let e = walk(root, false); + CacheInfo { bytes: e.iter().map(|e| e.len).sum(), tiles: e.len() as u64 } +} + +/// Delete the least recently used tiles under `root` until at most `target` bytes remain; returns +/// what remains. +pub fn evict(root: &Path, target: u64) -> CacheInfo { + let mut e = walk(root, true); + e.sort_by_key(|e| e.used); + let mut total: u64 = e.iter().map(|e| e.len).sum(); + let mut tiles = e.len() as u64; + for entry in &e { + if total <= target { + break; + } + if fs::remove_file(&entry.path).is_ok() { + total = total.saturating_sub(entry.len); + tiles -= 1; + } + } + CacheInfo { bytes: total, tiles } +} + +/// Delete every cached tile under `root` (and leftover `.part` files), then the emptied folders; +/// returns what was deleted. Only tile files are removed: a cache folder pointed somewhere odd +/// loses nothing else. +pub fn clear(root: &Path) -> Result { + let entries = walk(root, false); + let mut gone = CacheInfo::default(); + let mut failed = None; + for e in &entries { + match fs::remove_file(&e.path) { + Ok(()) => { + gone.bytes += e.len; + gone.tiles += 1; + } + Err(err) => failed = Some(format!("{}: {err}", e.path.display())), + } + } + // parts of any age, then the empty folders (remove_dir only removes empty ones) + let _ = evict_parts(root); + for e in &entries { + let mut dir = e.path.parent(); + for _ in 0..3 { + let Some(d) = dir else { break }; + if fs::remove_dir(d).is_err() { + break; + } + dir = d.parent(); + } + } + match failed { + Some(f) => Err(MapError::Io(format!("couldn't delete {f}"))), + None => Ok(gone), + } +} + +fn evict_parts(root: &Path) -> std::io::Result<()> { + for source in fs::read_dir(root)?.filter_map(Result::ok) { + if source.file_name().to_str().is_none_or(|n| validate_id(n).is_err()) || !source.file_type()?.is_dir() { + continue; + } + for z in fs::read_dir(source.path())?.filter_map(Result::ok).filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) { + for x in fs::read_dir(z.path())?.filter_map(Result::ok).filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) { + for f in fs::read_dir(x.path())?.filter_map(Result::ok) { + if f.file_name().to_string_lossy().ends_with(".part") && f.file_type().is_ok_and(|t| t.is_file()) { + let _ = fs::remove_file(f.path()); + } + } + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-map-cache-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + d + } + + fn key(z: u8, x: u32, y: u32) -> TileKey { + TileKey::new(z, x, y).unwrap() + } + + fn headers<'a>(h: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<&'a str> { + move |n| h.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| *v) + } + + #[test] + fn freshness_follows_the_headers() { + let now = 1_000_000; + assert_eq!(freshness(now, Some("max-age=3600"), None, None), (now + 3600, true)); + assert_eq!( + freshness(now, Some("public, max-age=86400, stale-while-revalidate=1"), Some("Thu, 01 Jan 1970 00:00:00 GMT"), None), + (now + 86_400, true), + "max-age wins over Expires" + ); + assert_eq!(freshness(now, Some("max-age=abc"), None, None), (now, true), "a bad max-age is 0"); + assert_eq!(freshness(now, Some("no-cache"), None, None), (now, true)); + assert!(!freshness(now, Some("no-store"), None, None).1); + assert_eq!(freshness(now, Some("max-age=99999999999"), None, None).0, now + MAX_FRESH_SECS); + assert_eq!(freshness(now, None, None, None), (now + 7 * 86_400, true), "7 days when the server says nothing"); + // Expires relative to the server's Date + assert_eq!(freshness(now, None, Some("Sun, 06 Nov 1994 09:49:37 GMT"), Some("Sun, 06 Nov 1994 08:49:37 GMT")), (now + 3600, true)); + // Expires without Date: absolute + let at = crate::map::http_date::parse("Sun, 06 Nov 1994 08:49:37 GMT").unwrap(); + assert_eq!(freshness(at - 60, None, Some("Sun, 06 Nov 1994 08:49:37 GMT"), None), (at, true)); + // already expired, or junk: expired now (shown, revalidated) + assert_eq!(freshness(now, None, Some("0"), None), (now, true)); + assert_eq!(freshness(now, None, Some("Thu, 01 Jan 1970 00:00:00 GMT"), None), (now, true)); + } + + #[test] + fn meta_from_headers_and_304() { + let h = [("Cache-Control", "max-age=60"), ("ETag", "\"abc\""), ("Last-Modified", "Sun, 06 Nov 1994 08:49:37 GMT")]; + let (m, store) = TileMeta::from_response(100, headers(&h)); + assert!(store); + assert_eq!( + m, + TileMeta { fetched: 100, expires: 160, etag: Some("\"abc\"".into()), last_modified: Some("Sun, 06 Nov 1994 08:49:37 GMT".into()) } + ); + assert!(m.is_fresh(159) && !m.is_fresh(160)); + assert_eq!( + m.conditional_headers(), + vec![("If-None-Match", "\"abc\"".to_string()), ("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT".to_string())] + ); + // a 304 without headers: 7 days, same validators + let r = m.revalidated(500, headers(&[])); + assert_eq!((r.fetched, r.expires, r.etag.as_deref()), (500, 500 + DEFAULT_FRESH_SECS, Some("\"abc\""))); + let r = m.revalidated(500, headers(&[("ETag", "\"new\""), ("Cache-Control", "max-age=10")])); + assert_eq!((r.expires, r.etag.as_deref()), (510, Some("\"new\""))); + // a header with a line break is not kept (it would be sent back) + let (m, _) = TileMeta::from_response(0, headers(&[("ETag", "a\r\nX: 1")])); + assert_eq!(m.etag, None); + } + + #[test] + fn writes_reads_and_refreshes() { + let root = tmp("rw"); + let c = TileCache::new(&root, "osm", DEFAULT_CACHE_BYTES).unwrap(); + let k = key(3, 2, 1); + assert_eq!(c.read(k), None); + let meta = TileMeta { fetched: 1, expires: 2, etag: Some("e".into()), last_modified: None }; + c.write(k, &meta, b"png bytes").unwrap(); + assert!(root.join("osm/3/2/1.tile").is_file()); + assert_eq!(c.read(k), Some(CachedTile { meta: meta.clone(), bytes: b"png bytes".to_vec() })); + let newer = TileMeta { fetched: 10, expires: 20, ..meta }; + assert!(c.refresh(k, &newer).unwrap()); + assert_eq!(c.read(k).unwrap(), CachedTile { meta: newer.clone(), bytes: b"png bytes".to_vec() }); + assert!(!c.refresh(key(3, 0, 0), &newer).unwrap(), "nothing to refresh"); + // no .part left behind + let leftovers: Vec<_> = fs::read_dir(root.join("osm/3/2")) + .unwrap() + .filter_map(Result::ok) + .filter(|e| e.file_name().to_string_lossy().ends_with(".part")) + .collect(); + assert!(leftovers.is_empty()); + assert_eq!(info(&root), CacheInfo { bytes: fs::metadata(root.join("osm/3/2/1.tile")).unwrap().len(), tiles: 1 }); + // an unusable source id never becomes a path + assert!(TileCache::new(&root, "../x", DEFAULT_CACHE_BYTES).is_err()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn damaged_entries_are_deleted_not_fatal() { + let root = tmp("damaged"); + let c = TileCache::new(&root, "osm", DEFAULT_CACHE_BYTES).unwrap(); + let dir = root.join("osm/1/0"); + fs::create_dir_all(&dir).unwrap(); + let mut too_long_meta = MAGIC.to_vec(); + too_long_meta.extend_from_slice(&u32::MAX.to_le_bytes()); + let mut bad_json = MAGIC.to_vec(); + bad_json.extend_from_slice(&3u32.to_le_bytes()); + bad_json.extend_from_slice(b"{{{png"); + let mut no_body = MAGIC.to_vec(); + no_body.extend_from_slice(&2u32.to_le_bytes()); + no_body.extend_from_slice(b"{}"); + for (i, bytes) in [b"".to_vec(), b"LCTILE".to_vec(), b"garbage garbage".to_vec(), too_long_meta, bad_json, no_body].into_iter().enumerate() { + let y = i as u32 % 2; + let k = key(1, 0, y); + fs::write(dir.join(format!("{y}.tile")), &bytes).unwrap(); + assert_eq!(c.read(k), None, "case {i}"); + assert!(!dir.join(format!("{y}.tile")).exists(), "case {i}: deleted"); + } + // oversized + fs::write(dir.join("0.tile"), vec![0u8; MAX_ENTRY_BYTES as usize + 1]).unwrap(); + assert_eq!(c.read(key(1, 0, 0)), None); + assert!(!dir.join("0.tile").exists()); + // a folder where a tile should be is left alone + fs::create_dir_all(dir.join("1.tile")).unwrap(); + assert_eq!(c.read(key(1, 0, 1)), None); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn evicts_least_recently_used_past_the_cap() { + let root = tmp("lru"); + let cap = 1 << 20; // the smallest cap; tiles of ~100 kB + let c = TileCache::new(&root, "osm", cap).unwrap(); + let body = vec![7u8; 100_000]; + let meta = TileMeta::default(); + let now = crate::map::now_secs(); + for x in 0..9u32 { + c.write(key(5, x, 0), &meta, &body).unwrap(); + // make the order of use unambiguous: tile x was used x hours ago… reversed + touch(&c.path(key(5, x, 0)), now - 100_000 + i64::from(x) * 1000); + } + // tile 0 is the oldest; reading it makes it the newest + assert!(c.read(key(5, 0, 0)).is_some()); + assert!(info(&root).bytes < cap); + // two more tiles push past 1 MiB: eviction brings it under 90 %, oldest first + c.write(key(5, 9, 0), &meta, &body).unwrap(); + c.write(key(5, 10, 0), &meta, &body).unwrap(); + let i = info(&root); + assert!(i.bytes <= cap / 10 * 9, "{i:?}"); + assert!(c.read(key(5, 0, 0)).is_some(), "recently read: kept"); + assert!(c.read(key(5, 10, 0)).is_some(), "just written: kept"); + assert!(c.read(key(5, 1, 0)).is_none(), "least recently used: evicted"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn clear_deletes_only_tiles_and_sweeps_parts() { + let root = tmp("clear"); + let c = TileCache::new(&root, "osm", DEFAULT_CACHE_BYTES).unwrap(); + let other = TileCache::new(&root, "custom-1", DEFAULT_CACHE_BYTES).unwrap(); + c.write(key(2, 1, 1), &TileMeta::default(), b"a").unwrap(); + other.write(key(2, 1, 1), &TileMeta::default(), b"b").unwrap(); + fs::write(root.join("osm/2/1/1.tile.1-1.part"), b"half").unwrap(); + fs::write(root.join("notes.txt"), b"not ours").unwrap(); + fs::create_dir_all(root.join("Not An Id/1/1")).unwrap(); + fs::write(root.join("Not An Id/1/1/1.tile"), b"not ours either").unwrap(); + let gone = clear(&root).unwrap(); + assert_eq!(gone.tiles, 2); + assert_eq!(info(&root), CacheInfo::default()); + assert!(!root.join("osm").exists() && !root.join("custom-1").exists()); + assert!(root.join("notes.txt").exists() && root.join("Not An Id/1/1/1.tile").exists()); + assert_eq!(clear(&root.join("missing")).unwrap(), CacheInfo::default()); + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/engine/src/map/http_date.rs b/crates/engine/src/map/http_date.rs new file mode 100644 index 0000000000..b9c00f8499 --- /dev/null +++ b/crates/engine/src/map/http_date.rs @@ -0,0 +1,68 @@ +//! HTTP dates (RFC 9110 §5.6.7) for tile freshness and `Retry-After`: `Sun, 06 Nov 1994 08:49:37 GMT` +//! (IMF-fixdate, what servers send), and the obsolete RFC 850 (`Sunday, 06-Nov-94 08:49:37 GMT`) +//! and asctime (`Sun Nov 6 08:49:37 1994`) forms recipients must accept. Times are Unix seconds +//! (UTC). Calendar maths goes through `chrono` (AGENTS.md: time goes through chrono). + +use chrono::NaiveDateTime; + +/// Parse an HTTP date to Unix seconds; `None` when it isn't one. +pub fn parse(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() || s.len() > 64 { + return None; + } + if let Some(rest) = s.strip_suffix(" GMT") { + // IMF-fixdate: Sun, 06 Nov 1994 08:49:37 GMT + if let Ok(t) = NaiveDateTime::parse_from_str(rest, "%a, %d %b %Y %H:%M:%S") { + return Some(t.and_utc().timestamp()); + } + // RFC 850: Sunday, 06-Nov-94 08:49:37 GMT (two-digit years: 70–99 are 19xx, the rest 20xx) + if let Ok(t) = NaiveDateTime::parse_from_str(rest, "%A, %d-%b-%y %H:%M:%S") { + return Some(t.and_utc().timestamp()); + } + return None; + } + // asctime: Sun Nov 6 08:49:37 1994 (the day may be space-padded) + let parts: Vec<&str> = s.split_whitespace().collect(); + if let [wd, mon, d, t, y] = parts.as_slice() { + let normal = format!("{wd} {mon} {d:0>2} {t} {y}"); + if let Ok(t) = NaiveDateTime::parse_from_str(&normal, "%a %b %d %H:%M:%S %Y") { + return Some(t.and_utc().timestamp()); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_the_three_forms() { + let want = 784_111_777; // 1994-11-06T08:49:37Z + assert_eq!(parse("Sun, 06 Nov 1994 08:49:37 GMT"), Some(want)); + assert_eq!(parse("Sunday, 06-Nov-94 08:49:37 GMT"), Some(want)); + assert_eq!(parse("Sun Nov 6 08:49:37 1994"), Some(want)); + assert_eq!(parse("Thu, 01 Jan 1970 00:00:00 GMT"), Some(0)); + assert_eq!(parse("Wed, 21 Oct 2026 07:28:00 GMT"), Some(1_792_567_680)); + } + + #[test] + fn rejects_junk_without_panicking() { + for bad in [ + "", + "0", + "-1", + "tomorrow", + "Sun, 31 Feb 2026 00:00:00 GMT", + "Sun, 06 Nov 1994 25:00:00 GMT", + "Sun, 06 Foo 1994 08:49:37 GMT", + "Sun, 06 Nov 1994 08:49:37 PST", + "Sun, 06 Nov 99999999999999999999 08:49:37 GMT", + "a b c d e", + &"x".repeat(1000), + ] { + assert_eq!(parse(bad), None, "{bad}"); + } + } +} diff --git a/crates/engine/src/map/mercator.rs b/crates/engine/src/map/mercator.rs new file mode 100644 index 0000000000..bc8392ad3e --- /dev/null +++ b/crates/engine/src/map/mercator.rs @@ -0,0 +1,383 @@ +//! Web Mercator (EPSG:3857) with 256 px tiles, as used by OpenStreetMap and most slippy maps. +//! +//! At zoom `z` the world is a square of `256 · 2^z` *world pixels*: x grows east from longitude +//! −180°, y grows south from latitude +85.05112878° ([`MAX_LATITUDE`], where the square ends). +//! Tile `(x, y)` at zoom `z` covers world pixels `[256x, 256x + 256) × [256y, 256y + 256)`. +//! Zoom may be fractional: a view at zoom 10.4 draws zoom-10 tiles scaled by 2^0.4. +//! +//! Latitudes are clamped to ±[`MAX_LATITUDE`] when projected and longitudes wrap around (the world +//! repeats east and west). Points from photos are checked with [`LatLon::new`]: NaN, infinities and +//! out-of-range values are rejected, so they never turn into NaN screen positions. +//! +//! Ported from the map core of PR #797 (Jason Baldwin) into the engine. + +use std::collections::HashSet; +use std::f64::consts::PI; + +use lightcraft_geom::{Point, Rect}; +use serde::{Deserialize, Serialize}; + +/// Tile edge in pixels. +pub const TILE_SIZE: u32 = 256; +const TILE: f64 = TILE_SIZE as f64; +/// The latitude where the Web Mercator square ends (north and south). +pub const MAX_LATITUDE: f64 = 85.051_128_78; +/// The deepest zoom any source may have (tile indices stay well inside `u32`). +pub const MAX_ZOOM: u8 = 24; +/// Largest viewport edge considered, in screen pixels (bounds the number of tiles). +pub const MAX_VIEW_PX: f64 = 16_384.0; + +pub use lightcraft_geom::LatLon; + +/// A photo's GPS position (`(latitude, longitude)`, as `Photo.gps` stores it), if valid +/// ([`LatLon::new`] rejects NaN, infinities and out-of-range values). +pub fn from_gps(gps: Option<(f64, f64)>) -> Option { + gps.and_then(|(lat, lon)| LatLon::new(lat, lon)) +} + +/// `lon` wrapped into [−180, 180) (0 for NaN or infinities). +pub fn wrap_lon(lon: f64) -> f64 { + if !lon.is_finite() { + return 0.0; + } + if (-180.0..180.0).contains(&lon) { + return lon; + } + let w = (lon + 180.0).rem_euclid(360.0) - 180.0; + // rem_euclid can round up to exactly 360 for tiny negative inputs + if w >= 180.0 { w - 360.0 } else { w } +} + +/// `lat` clamped to the Web Mercator square (0 for NaN). +pub fn clamp_lat(lat: f64) -> f64 { + if lat.is_nan() { 0.0 } else { lat.clamp(-MAX_LATITUDE, MAX_LATITUDE) } +} + +/// `zoom` clamped to [0, [`MAX_ZOOM`]] (0 for NaN). +pub fn clamp_zoom(zoom: f64) -> f64 { + if zoom.is_nan() { 0.0 } else { zoom.clamp(0.0, f64::from(MAX_ZOOM)) } +} + +/// Edge of the world square at `zoom`, in world pixels. +pub fn world_size(zoom: f64) -> f64 { + TILE * clamp_zoom(zoom).exp2() +} + +/// World x of longitude `lon` at zoom 0 as a fraction of the world (0..1, not wrapped). +fn x_frac(lon: f64) -> f64 { + (lon + 180.0) / 360.0 +} + +/// World y of latitude `lat` as a fraction of the world (0 at the north edge, 1 at the south). +fn y_frac(lat: f64) -> f64 { + let phi = clamp_lat(lat).to_radians(); + (1.0 - (PI / 4.0 + phi / 2.0).tan().ln() / PI) / 2.0 +} + +fn lat_of_y_frac(y: f64) -> f64 { + let y = if y.is_nan() { 0.5 } else { y.clamp(0.0, 1.0) }; + (PI * (1.0 - 2.0 * y)).sinh().atan().to_degrees() +} + +/// The world pixel of `p` at `zoom` (x in [0, world), longitude wrapped; y in [0, world]). +pub fn to_world(p: LatLon, zoom: f64) -> Point { + let s = world_size(zoom); + Point::new(x_frac(wrap_lon(p.lon)) * s, y_frac(p.lat) * s) +} + +/// The position of world pixel `w` at `zoom` (x wraps around the world, y is clamped to it). +pub fn from_world(w: Point, zoom: f64) -> LatLon { + let s = world_size(zoom); + let x = if w.x.is_finite() { w.x / s } else { 0.5 }; + LatLon { lat: lat_of_y_frac(w.y / s), lon: wrap_lon(x * 360.0 - 180.0) } +} + +/// One tile of the pyramid. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct TileKey { + pub z: u8, + pub x: u32, + pub y: u32, +} + +impl TileKey { + /// The tile, or `None` when `z` exceeds [`MAX_ZOOM`] or `x`/`y` fall outside the zoom's grid. + pub fn new(z: u8, x: u32, y: u32) -> Option { + let n = 1u64 << z.min(MAX_ZOOM); + (z <= MAX_ZOOM && u64::from(x) < n && u64::from(y) < n).then_some(TileKey { z, x, y }) + } + + /// The tile containing `p` at zoom `z` (clamped to [`MAX_ZOOM`]). + pub fn containing(p: LatLon, z: u8) -> TileKey { + let z = z.min(MAX_ZOOM); + let n = 1u64 << z; + let w = to_world(p, f64::from(z)); + let idx = |v: f64| ((v / TILE).floor().max(0.0) as u64).min(n - 1) as u32; + TileKey { z, x: idx(w.x), y: idx(w.y) } + } + + /// North-west and south-east corners of the tile. The east edge of the last column is +180° + /// (not wrapped to −180°). + pub fn corners(&self) -> (LatLon, LatLon) { + let n = f64::from(self.z.min(MAX_ZOOM)).exp2(); + let lon = |x: u32| f64::from(x) / n * 360.0 - 180.0; + let lat = |y: u32| lat_of_y_frac(f64::from(y) / n); + (LatLon { lat: lat(self.y), lon: lon(self.x) }, LatLon { lat: lat(self.y.saturating_add(1)), lon: lon(self.x.saturating_add(1)) }) + } +} + +/// A tile placed on screen by [`Viewport::tiles`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VisibleTile { + pub key: TileKey, + /// Where to draw it, in screen pixels from the viewport's top-left corner (it may reach past + /// the viewport's edges). At low zoom the world repeats east–west, so the same key can appear + /// at several places. + pub rect: Rect, +} + +/// What a map view shows: a centre, a (fractional) zoom and a size in screen pixels. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Viewport { + pub center: LatLon, + pub zoom: f64, + pub width: f64, + pub height: f64, +} + +impl Viewport { + /// A viewport with its values made safe: latitude clamped to the Mercator square, longitude + /// wrapped, zoom in [0, [`MAX_ZOOM`]], size in [0, [`MAX_VIEW_PX`]] (NaN → 0). + pub fn new(center: LatLon, zoom: f64, width: f64, height: f64) -> Viewport { + let size = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_VIEW_PX) }; + Viewport { + center: LatLon { lat: clamp_lat(center.lat), lon: wrap_lon(center.lon) }, + zoom: clamp_zoom(zoom), + width: size(width), + height: size(height), + } + } + + /// The same view, sanitized (fields are public, so a caller may have put anything there). + fn safe(&self) -> Viewport { + Viewport::new(self.center, self.zoom, self.width, self.height) + } + + /// The tile zoom drawn for this view: the view's zoom rounded, within `[0, max_zoom]`. + pub fn tile_zoom(&self, max_zoom: u8) -> u8 { + let z = clamp_zoom(self.zoom).round() as u8; + z.min(max_zoom.min(MAX_ZOOM)) + } + + /// Screen pixels per world pixel of zoom `z` (2^(zoom − z)). + pub fn scale_for(&self, z: u8) -> f64 { + (clamp_zoom(self.zoom) - f64::from(z)).exp2() + } + + /// Screen position of `p` (pixels from the top-left corner), on the copy of the world nearest + /// the centre. Positions outside the viewport are returned as they are (off screen). + pub fn to_screen(&self, p: LatLon) -> Point { + let v = self.safe(); + let s = world_size(v.zoom); + let c = to_world(v.center, v.zoom); + let w = to_world(p, v.zoom); + // the shortest way around the world + let dx = (w.x - c.x + s / 2.0).rem_euclid(s) - s / 2.0; + Point::new(v.width / 2.0 + dx, v.height / 2.0 + (w.y - c.y)) + } + + /// The position under screen point `sp` (longitude wrapped, latitude clamped to the map). + pub fn to_lat_lon(&self, sp: Point) -> LatLon { + let v = self.safe(); + let c = to_world(v.center, v.zoom); + let (dx, dy) = (if sp.x.is_finite() { sp.x - v.width / 2.0 } else { 0.0 }, if sp.y.is_finite() { sp.y - v.height / 2.0 } else { 0.0 }); + from_world(Point::new(c.x + dx, c.y + dy), v.zoom) + } + + /// The view moved by `(dx, dy)` screen pixels (content follows a drag of that amount). + pub fn panned(&self, dx: f64, dy: f64) -> Viewport { + let v = self.safe(); + let c = Point::new(v.width / 2.0 - if dx.is_finite() { dx } else { 0.0 }, v.height / 2.0 - if dy.is_finite() { dy } else { 0.0 }); + Viewport::new(v.to_lat_lon(c), v.zoom, v.width, v.height) + } + + /// The view at `zoom`, keeping the position under screen point `anchor` where it is (wheel + /// zoom around the pointer). + pub fn zoomed_around(&self, anchor: Point, zoom: f64) -> Viewport { + let v = self.safe(); + let anchor = if anchor.x.is_finite() && anchor.y.is_finite() { anchor } else { Point::new(v.width / 2.0, v.height / 2.0) }; + let under = v.to_lat_lon(anchor); + let z = clamp_zoom(zoom); + let w = to_world(under, z); + let c = Point::new(w.x - (anchor.x - v.width / 2.0), w.y - (anchor.y - v.height / 2.0)); + Viewport::new(from_world(c, z), z, v.width, v.height) + } + + /// Top-left of the view in world pixels of tile zoom `z`, and the screen scale. + fn origin(&self, z: u8) -> (Point, f64) { + let scale = self.scale_for(z); + let c = to_world(self.center, f64::from(z)); + (Point::new(c.x - self.width / 2.0 / scale, c.y - self.height / 2.0 / scale), scale) + } + + /// Tile columns and rows (unwrapped column indices) covering the view at tile zoom `z`, + /// grown by `margin` tiles on each side; rows are clamped to the grid. + fn grid(&self, z: u8, margin: i64) -> (std::ops::RangeInclusive, std::ops::RangeInclusive, Point, f64) { + let (o, scale) = self.origin(z); + let n = 1i64 << z; + let (w, h) = (self.width / scale, self.height / scale); + let first = |v: f64| (v / TILE).floor() as i64 - margin; + // a view edge exactly on a tile boundary doesn't pull in the next tile + let last = |v: f64, len: f64| ((v + len) / TILE).ceil() as i64 - 1 + margin; + let cols = first(o.x)..=last(o.x, w).max(first(o.x)); + let rows = first(o.y).max(0)..=last(o.y, h).min(n - 1); + (cols, rows, o, scale) + } + + /// The tiles to draw for this view at zoom `min(round(zoom), max_zoom)`, with their screen + /// rectangles, nearest the centre first. Empty for an empty viewport. + pub fn tiles(&self, max_zoom: u8) -> Vec { + let v = self.safe(); + if v.width <= 0.0 || v.height <= 0.0 { + return Vec::new(); + } + let z = v.tile_zoom(max_zoom); + let n = 1i64 << z; + let (cols, rows, o, scale) = v.grid(z, 0); + let mut out = Vec::new(); + for ty in rows { + for tx in cols.clone() { + let Some(key) = TileKey::new(z, tx.rem_euclid(n) as u32, ty as u32) else { continue }; + let x0 = (tx as f64 * TILE - o.x) * scale; + let y0 = (ty as f64 * TILE - o.y) * scale; + out.push(VisibleTile { key, rect: Rect::new(x0, y0, x0 + TILE * scale, y0 + TILE * scale) }); + } + } + let (cx, cy) = (v.width / 2.0, v.height / 2.0); + let d = |t: &VisibleTile| { + let (x, y) = ((t.rect.x0 + t.rect.x1) / 2.0 - cx, (t.rect.y0 + t.rect.y1) / 2.0 - cy); + x * x + y * y + }; + out.sort_by(|a, b| d(a).total_cmp(&d(b))); + out + } + + /// The distinct tiles to load for this view: those [`Viewport::tiles`] draws plus a ring of + /// `margin` tiles around them (at most 1: the OpenStreetMap tile policy forbids fetching + /// beyond what is shown), nearest the centre first. Only the drawn zoom, never others. + pub fn tile_keys(&self, max_zoom: u8, margin: u32) -> Vec { + let v = self.safe(); + if v.width <= 0.0 || v.height <= 0.0 { + return Vec::new(); + } + let z = v.tile_zoom(max_zoom); + let n = 1i64 << z; + let (cols, rows, o, scale) = v.grid(z, i64::from(margin.min(1))); + let c = Point::new(o.x + v.width / 2.0 / scale, o.y + v.height / 2.0 / scale); + let mut seen = HashSet::new(); + let mut keyed = Vec::new(); + for ty in rows { + for tx in cols.clone() { + let Some(key) = TileKey::new(z, tx.rem_euclid(n) as u32, ty as u32) else { continue }; + let (dx, dy) = ((tx as f64 + 0.5) * TILE - c.x, (ty as f64 + 0.5) * TILE - c.y); + keyed.push((dx * dx + dy * dy, key)); + } + } + keyed.sort_by(|a, b| a.0.total_cmp(&b.0)); + keyed.into_iter().filter(|(_, k)| seen.insert(*k)).map(|(_, k)| k).collect() + } +} + +/// A latitude/longitude box. `west > east` means it crosses the antimeridian (±180°): it spans +/// from `west` eastward through 180° to `east`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Bounds { + pub south: f64, + pub west: f64, + pub north: f64, + pub east: f64, +} + +impl Bounds { + /// The smallest box holding every valid point (`(latitude, longitude)` pairs, as `Photo.gps` + /// stores them); invalid points (NaN, out of range) are skipped. `None` when no point is valid. + /// + /// Longitudes are treated as a circle: the box is the complement of the widest gap between the + /// points, so photos at 179° and −179° give a 2°-wide box crossing the antimeridian (west 179, + /// east −179), not one spanning the whole world. + pub fn of>(points: I) -> Option { + let mut lons = Vec::new(); + let (mut south, mut north) = (f64::INFINITY, f64::NEG_INFINITY); + for p in points.into_iter().filter_map(|(lat, lon)| LatLon::new(lat, lon)) { + south = south.min(p.lat); + north = north.max(p.lat); + lons.push(wrap_lon(p.lon)); + } + if lons.is_empty() { + return None; + } + lons.sort_by(f64::total_cmp); + lons.dedup(); + let (first, last) = (*lons.first()?, *lons.last()?); + // the gap from the easternmost point round to the westernmost + let mut best = (first + 360.0 - last, first, last); + for pair in lons.windows(2) { + if let [a, b] = pair + && b - a > best.0 + { + best = (b - a, *b, *a); + } + } + let (_, west, mut east) = best; + if east == -180.0 && west > east { + east = 180.0; + } + Some(Bounds { south, west, north, east }) + } + + /// The box crosses the antimeridian. + pub fn crosses_antimeridian(&self) -> bool { + self.west > self.east + } + + /// Width in degrees of longitude (0..=360). + pub fn lon_span(&self) -> f64 { + if self.crosses_antimeridian() { self.east + 360.0 - self.west } else { self.east - self.west } + } + + /// `p` lies inside (edges included). + pub fn contains(&self, p: LatLon) -> bool { + let lon = wrap_lon(p.lon); + let lat_ok = (self.south..=self.north).contains(&p.lat); + let lon_ok = if self.crosses_antimeridian() { + lon >= self.west || lon <= self.east + } else { + (self.west..=self.east).contains(&lon) || (self.east == 180.0 && lon == -180.0) + }; + lat_ok && lon_ok + } + + /// The centre in Web Mercator terms (the middle of the projected box, longitude wrapped). + pub fn center(&self) -> LatLon { + let y = (y_frac(self.north) + y_frac(self.south)) / 2.0; + LatLon { lat: lat_of_y_frac(y), lon: wrap_lon(self.west + self.lon_span() / 2.0) } + } +} + +/// The view of a `width × height` px map that shows all of `bounds` with `margin` px to spare on +/// every side, at the deepest zoom up to `max_zoom` (a single point, or a box too small to need +/// more, gets `max_zoom`). Zoom is fractional; callers wanting whole zooms floor it. +pub fn fit_bounds(bounds: &Bounds, width: f64, height: f64, margin: f64, max_zoom: f64) -> Viewport { + let margin = if margin.is_finite() { margin.max(0.0) } else { 0.0 }; + let size = |v: f64| if v.is_finite() { v.clamp(0.0, MAX_VIEW_PX) } else { 0.0 }; + let (width, height) = (size(width), size(height)); + let max_zoom = clamp_zoom(max_zoom); + let avail_w = (width - 2.0 * margin).max(1.0); + let avail_h = (height - 2.0 * margin).max(1.0); + let dx = bounds.lon_span().clamp(0.0, 360.0) / 360.0 * TILE; + let dy = ((y_frac(bounds.south) - y_frac(bounds.north)) * TILE).abs(); + let fit = |avail: f64, d: f64| if d > 0.0 && d.is_finite() { (avail / d).log2() } else { f64::INFINITY }; + let zoom = fit(avail_w, dx).min(fit(avail_h, dy)); + let zoom = if zoom.is_finite() { zoom.clamp(0.0, max_zoom) } else { max_zoom }; + Viewport::new(bounds.center(), zoom, width, height) +} diff --git a/crates/engine/src/map/service.rs b/crates/engine/src/map/service.rs new file mode 100644 index 0000000000..da8d65f8f0 --- /dev/null +++ b/crates/engine/src/map/service.rs @@ -0,0 +1,693 @@ +//! The tile fetch queue: background threads that load the current view's tiles from the cache or +//! the tile server, without ever blocking the caller. +//! +//! The map view calls [`TileService::show`] with its [`Viewport`] every frame (cheap when nothing +//! changed), draws the tiles [`TileService::get`] returns, and calls [`TileService::poll`] to learn +//! which tiles arrived (to repaint). Behind that, following the OpenStreetMap tile usage policy: +//! +//! - **Only the view**: the tiles wanted are those drawn plus at most one ring around them, at the +//! drawn zoom only; no other zooms or areas are ever prefetched and there is no "download area". +//! - **Newest view first**: each `show` replaces the wanted set; queued tiles that left the view +//! are dropped before they start, the rest are fetched nearest the centre first. (A request +//! already on the wire finishes and is cached.) +//! - **Gentle**: at most [`MAX_IN_FLIGHT`] requests at a time; after an error, a 429 or a 5xx the +//! host gets exponential backoff (1 s doubling to 5 min, at least its Retry-After) and then one +//! probe at a time until a request succeeds, so a failing server sees no retry storm; a tile the server refuses (404, garbage) isn't asked for again +//! for [`FAILED_RETRY`]. +//! - **Cache first**: a fresh cached tile costs no request; an expired one is shown at once and +//! revalidated with If-None-Match / If-Modified-Since (304 just renews it). Requests carry the +//! source's User-Agent and never `Cache-Control: no-cache` or `Pragma`. +//! - **Hostile responses**: bodies over [`MAX_TILE_BYTES`], images that aren't PNG/JPEG/WebP of at +//! most 1024 px, or that fail to decode are errors, never panics. +//! +//! - **Visible**: while tiles are queued or loading, one "Loading map tiles" row is on the activity +//! stack (`docs/background-tasks.md`); it goes when the queue is empty. +//! +//! Threads start with the service only when it has something to do (a transport or a cache); on +//! wasm32 there is neither, so the service is inert and tiles never arrive. +//! +//! Ported from the map core of PR #797 (Jason Baldwin) into the engine. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use web_time::Instant; + +use super::cache::{TileCache, TileMeta}; +use super::mercator::{TileKey, Viewport}; +use super::source::TileSource; +use crate::activity::{Activity, Cancel, TaskGuard}; + +/// Most tile requests on the wire at once. +pub const MAX_IN_FLIGHT: usize = 2; +/// Largest tile body accepted. +pub const MAX_TILE_BYTES: usize = 2 << 20; +/// Largest tile edge accepted (256 px tiles; 512 for high-DPI sources). +pub const MAX_TILE_EDGE: u32 = 1024; +/// A tile the server refused is not asked for again before this. +pub const FAILED_RETRY: Duration = Duration::from_secs(10 * 60); +/// Most tiles wanted at once (a 16k-pixel view with its margin stays under this). +pub const MAX_WANTED: usize = 4096; +/// Decoded tiles kept in memory (256 × 256 × 4 bytes each: 64 MB). +pub const MEMORY_TILES: usize = 256; +/// First backoff after an error, and the longest. +const BACKOFF_START: Duration = Duration::from_secs(1); +const BACKOFF_MAX: Duration = Duration::from_secs(300); +/// Longest Retry-After honoured. +const RETRY_AFTER_MAX: Duration = Duration::from_secs(3600); +/// Worker threads: [`MAX_IN_FLIGHT`] for the network plus one so cache reads never wait behind it. +const WORKERS: usize = MAX_IN_FLIGHT + 1; + +/// A tile server's answer, as a [`Transport`] returns it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HttpResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl HttpResponse { + /// The first header named `name` (case-insensitive). + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } +} + +/// Does one GET. The real one is [`HttpTransport`] (native only); tests use an in-process fake. +pub trait Transport: Send + Sync { + /// GET `url` with `headers`; a body longer than `max_body` is an error. Must give up within a + /// bounded time (timeouts), and soon after `cancel` is raised. + fn get(&self, url: &str, headers: &[(&'static str, String)], max_body: usize, cancel: &AtomicBool) -> Result; +} + +/// HTTPS through `lightcraft-fetch` (pure Rust, rustls), with connect and stall timeouts. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug)] +pub struct HttpTransport { + pub connect_timeout: Duration, + pub stall_timeout: Duration, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for HttpTransport { + fn default() -> Self { + HttpTransport { connect_timeout: Duration::from_secs(10), stall_timeout: Duration::from_secs(15) } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Transport for HttpTransport { + fn get(&self, url: &str, headers: &[(&'static str, String)], max_body: usize, cancel: &AtomicBool) -> Result { + use lightcraft_fetch::http; + let url = http::Url::parse(url).map_err(|e| e.to_string())?; + let limits = http::Limits { connect: self.connect_timeout, stall: self.stall_timeout, cancel }; + let hs: Vec<(&str, String)> = headers.iter().map(|(k, v)| (*k, v.clone())).collect(); + let mut r = http::get(&url, &hs, &limits).map_err(|e| e.to_string())?; + if r.content_length().is_some_and(|n| n > max_body as u64) { + return Err(format!("tile larger than {max_body} bytes")); + } + let mut body = Vec::new(); + let mut buf = [0u8; 16 * 1024]; + loop { + let n = r.read(&mut buf, &limits).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + if body.len().saturating_add(n) > max_body { + return Err(format!("tile larger than {max_body} bytes")); + } + body.extend_from_slice(buf.get(..n).unwrap_or_default()); + } + let headers = ["cache-control", "expires", "date", "etag", "last-modified", "retry-after", "content-type"] + .iter() + .filter_map(|h| r.header(h).map(|v| (h.to_string(), v.to_string()))) + .collect(); + Ok(HttpResponse { status: r.status, headers, body }) + } +} + +/// A decoded tile: 8-bit sRGB RGBA, row-major, `width × height × 4` bytes (unpremultiplied). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TileImage { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +/// Decode a tile image (PNG, JPEG or WebP, at most [`MAX_TILE_EDGE`] px a side). +pub fn decode_tile(bytes: &[u8]) -> Result { + use lightcraft_codecs::{DecodeOptions, Format}; + let bad = |m: String| crate::map::MapError::BadTile(m); + if bytes.len() > MAX_TILE_BYTES { + return Err(bad("too large".into())); + } + let h = lightcraft_codecs::read_header(bytes).map_err(|e| bad(e.to_string()))?; + if !matches!(h.format, Format::Png | Format::Jpeg | Format::WebP) { + return Err(bad(format!("{:?} is not a tile format", h.format))); + } + if h.width == 0 || h.height == 0 || h.width > MAX_TILE_EDGE || h.height > MAX_TILE_EDGE { + return Err(bad(format!("{}×{} is not a tile size", h.width, h.height))); + } + let max_pixels = u64::from(MAX_TILE_EDGE) * u64::from(MAX_TILE_EDGE); + let d = lightcraft_codecs::decode(bytes, DecodeOptions { max_size: None, max_pixels }).map_err(|e| bad(e.to_string()))?; + let img = d.to_srgb8(); + let (width, height) = (u32::try_from(img.width).unwrap_or(0), u32::try_from(img.height).unwrap_or(0)); + Ok(TileImage { width, height, rgba: img.data.as_flattened().to_vec() }) +} + +/// What [`TileService::poll`] reports. +#[derive(Clone, Debug)] +pub enum TileEvent { + /// A tile is available (also from [`TileService::get`]). `stale`: from the cache past its + /// freshness, being revalidated (a fresh copy may follow). + Ready { key: TileKey, image: Arc, stale: bool }, + /// A tile couldn't be loaded (the view draws its placeholder). Not retried for a while. + Failed { key: TileKey, error: String }, +} + +/// Counters for tests and diagnostics. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ServiceStats { + /// Requests sent to the tile server. + pub requests: u64, + /// Requests on the wire now, and the most there ever were at once. + pub in_flight: usize, + pub max_in_flight: usize, + /// Answers: 304 Not Modified, errors (transport, 429/5xx, refused or garbage tiles). + pub not_modified: u64, + pub errors: u64, + /// Tiles queued, wanted, and decoded in memory. + pub queued: usize, + pub wanted: usize, + pub in_memory: usize, + /// Milliseconds until the host may be asked again (0 = not backing off). + pub backoff_ms: u64, +} + +struct MemTile { + image: Arc, + /// Fresh until (Unix seconds). + expires: i64, + used: u64, +} + +#[derive(Default)] +struct State { + /// The tiles of the newest view, nearest the centre first, and their rank in it. + wanted: Vec, + rank: HashMap, + /// Tiles to look up in the cache, then (if missing or stale) to fetch. + disk_q: VecDeque, + net_q: Vec, + /// Tiles a worker is handling now. + busy: HashSet, + net_in_flight: usize, + /// Tiles not to ask for before the given time (refused or undecodable). + failed: HashMap, + /// Stale tiles already revalidated this session (or being): not again until they expire anew. + revalidated: HashSet, + /// The host's backoff: consecutive errors and the time it may be asked again. + errors_in_row: u32, + backoff_until: Option, + memory: HashMap, + use_counter: u64, + events: Vec, + stats: ServiceStats, + shutdown: bool, + /// The activity row while there is work, and the jobs finished since it appeared. + row: Option, + row_done: u64, + activity: Option, +} + +impl State { + fn wanted(&self, k: &TileKey) -> bool { + self.rank.contains_key(k) + } + + fn remember(&mut self, key: TileKey, image: Arc, expires: i64) { + self.use_counter += 1; + self.memory.insert(key, MemTile { image, expires, used: self.use_counter }); + while self.memory.len() > MEMORY_TILES { + // never drop a tile of the current view for an older one + let victim = self.memory.iter().filter(|(k, _)| !self.rank.contains_key(k)).min_by_key(|(_, t)| t.used).map(|(k, _)| *k); + let victim = victim.or_else(|| self.memory.iter().min_by_key(|(_, t)| t.used).map(|(k, _)| *k)); + match victim { + Some(k) => self.memory.remove(&k), + None => break, + }; + } + } + + /// The host had an error: back off (doubling, at least `retry_after`). + fn back_off(&mut self, retry_after: Option) { + self.errors_in_row = self.errors_in_row.saturating_add(1); + let exp = BACKOFF_START.saturating_mul(1u32 << self.errors_in_row.saturating_sub(1).min(16)); + let wait = exp.min(BACKOFF_MAX).max(retry_after.unwrap_or_default().min(RETRY_AFTER_MAX)); + self.backoff_until = Some(Instant::now() + wait); + } + + /// Show the activity row while tiles are queued or loading, with how many are done; drop it + /// when nothing is left. + fn update_row(&mut self) { + let left = (self.disk_q.len() + self.net_q.len() + self.busy.len()) as u64; + if left == 0 { + self.row = None; + self.row_done = 0; + return; + } + if self.row.is_none() + && let Some(a) = &self.activity + { + self.row = Some(a.start("download", "Loading map tiles", Cancel::No)); + } + if let Some(row) = &self.row { + row.progress(self.row_done, self.row_done.saturating_add(left)); + } + } +} + +struct Shared { + source: TileSource, + cache: Option, + transport: Option>, + state: Mutex, + wake: Condvar, + cancel: AtomicBool, +} + +impl Shared { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// The fetch queue of one tile source (see the module docs). Dropping it stops its threads (a +/// request on the wire is cancelled). +pub struct TileService { + shared: Arc, +} + +impl std::fmt::Debug for TileService { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TileService").field("source", &self.shared.source.id()).finish() + } +} + +enum Job { + Disk(TileKey), + Net(TileKey), +} + +impl TileService { + /// The service for `source`, caching under `cache_root` (none: memory only) capped at + /// `cache_cap` bytes, fetching with the real HTTPS client (natively, unless the source is + /// offline). An unusable cache folder is logged and the service runs without it. + pub fn new(source: TileSource, cache_root: Option, cache_cap: u64, activity: Option, online: bool) -> TileService { + let cache = if source.is_offline() { + None + } else { + cache_root.and_then(|root| TileCache::new(root, source.id(), cache_cap).map_err(|e| log::warn!("map: no tile cache: {e}")).ok()) + }; + #[cfg(not(target_arch = "wasm32"))] + let transport: Option> = + (online && !source.is_offline()).then(|| Arc::new(HttpTransport::default()) as Arc); + #[cfg(target_arch = "wasm32")] + let transport: Option> = { + let _ = online; + None + }; + TileService::with_transport(source, cache, transport).with_activity(activity) + } + + /// Report loading on `activity` (one row while tiles are queued or loading). + pub fn with_activity(self, activity: Option) -> TileService { + self.shared.lock().activity = activity; + self + } + + /// The service with an explicit cache and transport (tests use a fake transport). No + /// transport, or an offline source: nothing is ever fetched. + pub fn with_transport(source: TileSource, cache: Option, transport: Option>) -> TileService { + let transport = transport.filter(|_| !source.is_offline()); + let active = transport.is_some() || cache.is_some(); + let shared = + Arc::new(Shared { source, cache, transport, state: Mutex::new(State::default()), wake: Condvar::new(), cancel: AtomicBool::new(false) }); + if active { + for i in 0..WORKERS { + let s = Arc::clone(&shared); + if let Err(e) = std::thread::Builder::new().name(format!("map-tiles-{i}")).spawn(move || worker(&s)) { + log::warn!("map: can't start a tile thread: {e}"); + break; + } + } + } + TileService { shared } + } + + pub fn source(&self) -> &TileSource { + &self.shared.source + } + + /// Load the tiles of `view` (drawn ones plus a one-tile margin), dropping queued tiles it no + /// longer shows. Call it whenever the view may have changed: it is cheap when it didn't. + pub fn show(&self, view: &Viewport) { + self.want(&view.tile_keys(self.shared.source.max_zoom(), 1)); + } + + /// Load exactly `keys` (most important first; at most [`MAX_WANTED`]), replacing what was + /// wanted before. Keys past the source's max zoom are ignored. + pub fn want(&self, keys: &[TileKey]) { + let max_zoom = self.shared.source.max_zoom(); + let mut st = self.shared.lock(); + let mut list: Vec = Vec::with_capacity(keys.len().min(MAX_WANTED)); + let mut rank = HashMap::new(); + for k in keys.iter().filter(|k| k.z <= max_zoom) { + if list.len() >= MAX_WANTED { + break; + } + if !rank.contains_key(k) { + rank.insert(*k, list.len()); + list.push(*k); + } + } + let now_unix = crate::map::now_secs(); + let now = Instant::now(); + let stale_in_memory = |st: &State, k: &TileKey| st.memory.get(k).is_some_and(|t| t.expires <= now_unix) && !st.revalidated.contains(k); + let unchanged = list == st.wanted && !list.iter().any(|k| stale_in_memory(&st, k)); + if unchanged { + return; + } + st.wanted = list; + st.rank = rank; + // newest view first: what left the view is dropped before it starts + let State { disk_q, net_q, rank, revalidated, .. } = &mut *st; + disk_q.retain(|k| rank.contains_key(k)); + net_q.retain(|k| { + let keep = rank.contains_key(k); + if !keep { + // its refresh never started: allow it again when the tile is back in view + revalidated.remove(k); + } + keep + }); + st.failed.retain(|_, until| *until > now); + let has_cache = self.shared.cache.is_some(); + let can_fetch = self.shared.transport.is_some(); + for k in st.wanted.clone() { + if st.busy.contains(&k) || st.disk_q.contains(&k) || st.net_q.contains(&k) || st.failed.contains_key(&k) { + continue; + } + if st.memory.contains_key(&k) { + if stale_in_memory(&st, &k) && can_fetch { + st.revalidated.insert(k); + st.net_q.push(k); + } + continue; + } + if has_cache { + st.disk_q.push_back(k); + } else if can_fetch { + st.net_q.push(k); + } + } + // the disk queue in the view's order too + let State { disk_q, rank, .. } = &mut *st; + disk_q.make_contiguous().sort_by_key(|k| rank.get(k).copied().unwrap_or(usize::MAX)); + st.update_row(); + drop(st); + self.shared.wake.notify_all(); + } + + /// The decoded tile if it is in memory (never touches disk or network). + pub fn get(&self, key: TileKey) -> Option> { + let mut st = self.shared.lock(); + st.use_counter += 1; + let n = st.use_counter; + st.memory.get_mut(&key).map(|t| { + t.used = n; + Arc::clone(&t.image) + }) + } + + /// Tiles that arrived (or failed) since the last call. + pub fn poll(&self) -> Vec { + std::mem::take(&mut self.shared.lock().events) + } + + pub fn stats(&self) -> ServiceStats { + let st = self.shared.lock(); + let mut s = st.stats; + s.queued = st.disk_q.len() + st.net_q.len(); + s.wanted = st.wanted.len(); + s.in_memory = st.memory.len(); + s.in_flight = st.net_in_flight; + s.backoff_ms = st.backoff_until.map_or(0, |u| u.saturating_duration_since(Instant::now()).as_millis() as u64); + s + } + + /// Nothing queued or running (tests wait for this). + pub fn is_idle(&self) -> bool { + let st = self.shared.lock(); + st.disk_q.is_empty() && st.net_q.is_empty() && st.busy.is_empty() + } +} + +impl Drop for TileService { + fn drop(&mut self) { + let mut st = self.shared.lock(); + st.shutdown = true; + st.row = None; + drop(st); + self.shared.cancel.store(true, Ordering::Relaxed); + self.shared.wake.notify_all(); + } +} + +/// The next job, waiting for one (`None`: shut down). +fn next_job(sh: &Shared) -> Option { + let mut st = sh.lock(); + loop { + if st.shutdown { + return None; + } + while let Some(k) = st.disk_q.pop_front() { + if st.wanted(&k) && !st.busy.contains(&k) { + st.busy.insert(k); + return Some(Job::Disk(k)); + } + } + let now = Instant::now(); + let backing_off = st.backoff_until.is_some_and(|u| u > now); + // while the host is failing, one probe at a time + let limit = if st.errors_in_row > 0 { 1 } else { MAX_IN_FLIGHT }; + if sh.transport.is_some() && !st.net_q.is_empty() && st.net_in_flight < limit && !backing_off { + // the most central tile of the newest view + let best = st + .net_q + .iter() + .enumerate() + .filter(|(_, k)| !st.busy.contains(k)) + .min_by_key(|(_, k)| st.rank.get(k).copied().unwrap_or(usize::MAX)) + .map(|(i, _)| i); + if let Some(i) = best { + let k = st.net_q.swap_remove(i); + if st.wanted(&k) { + st.busy.insert(k); + st.net_in_flight += 1; + st.stats.max_in_flight = st.stats.max_in_flight.max(st.net_in_flight); + return Some(Job::Net(k)); + } + continue; + } + } + st = match st.backoff_until.filter(|u| *u > now && !st.net_q.is_empty()) { + Some(until) => sh.wake.wait_timeout(st, until.saturating_duration_since(now)).unwrap_or_else(PoisonError::into_inner).0, + None => sh.wake.wait(st).unwrap_or_else(PoisonError::into_inner), + }; + } +} + +fn worker(sh: &Shared) { + while let Some(job) = next_job(sh) { + // a panic in a decoder or the transport is that tile's error, not a dead thread + let key = match job { + Job::Disk(k) | Job::Net(k) => k, + }; + let net = matches!(job, Job::Net(_)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match job { + Job::Disk(k) => disk_job(sh, k), + Job::Net(k) => net_job(sh, k), + })); + let mut st = sh.lock(); + st.busy.remove(&key); + if net { + st.net_in_flight = st.net_in_flight.saturating_sub(1); + } + if r.is_err() { + st.failed.insert(key, Instant::now() + FAILED_RETRY); + st.events.push(TileEvent::Failed { key, error: "internal error loading the tile".into() }); + } + // a tile counts as done once nothing more is queued for it (a cache miss goes on to the network) + if !st.net_q.contains(&key) && !st.disk_q.contains(&key) { + st.row_done = st.row_done.saturating_add(1); + } + st.update_row(); + drop(st); + sh.wake.notify_all(); + } +} + +/// Look `k` up in the cache: show it if there (and revalidate it if stale), else fetch it. +fn disk_job(sh: &Shared, k: TileKey) { + let now = crate::map::now_secs(); + let cached = sh.cache.as_ref().and_then(|c| c.read(k)); + let decoded = cached.and_then(|c| match decode_tile(&c.bytes) { + Ok(img) => Some((img, c.meta)), + Err(e) => { + log::warn!("map: cached tile {k:?} doesn't decode ({e}); fetching it again"); + if let Some(cache) = &sh.cache { + cache.remove(k); + } + None + } + }); + let mut st = sh.lock(); + match decoded { + Some((img, meta)) => { + let fresh = meta.is_fresh(now); + let image = Arc::new(img); + st.remember(k, Arc::clone(&image), meta.expires); + st.events.push(TileEvent::Ready { key: k, image, stale: !fresh }); + if !fresh && sh.transport.is_some() && st.wanted(&k) { + st.revalidated.insert(k); + st.net_q.push(k); + } + } + None => { + if sh.transport.is_some() && st.wanted(&k) { + st.net_q.push(k); + } + } + } +} + +/// Parse Retry-After: seconds or an HTTP date. +fn retry_after(r: &HttpResponse) -> Option { + let v = r.header("retry-after")?.trim(); + if let Ok(s) = v.parse::() { + return Some(Duration::from_secs(s)); + } + let at = crate::map::http_date::parse(v)?; + Some(Duration::from_secs(u64::try_from(at.saturating_sub(crate::map::now_secs())).unwrap_or(0))) +} + +/// Fetch `k` from the server (conditionally when a copy is cached). +fn net_job(sh: &Shared, k: TileKey) { + let (Some(transport), Some(url)) = (sh.transport.as_ref(), sh.source.url(k)) else { return }; + let cached = sh.cache.as_ref().and_then(|c| c.read(k)).map(|c| c.meta); + let mut headers: Vec<(&'static str, String)> = vec![("User-Agent", sh.source.user_agent().to_string())]; + if let Some(m) = &cached { + headers.extend(m.conditional_headers()); + } + sh.lock().stats.requests += 1; + let result = transport.get(&url, &headers, MAX_TILE_BYTES, &sh.cancel); + let now = crate::map::now_secs(); + let fail = |st: &mut State, error: String, retry: bool| { + st.stats.errors += 1; + if retry { + // the host is in trouble: wait, then try again if still in view + if st.wanted(&k) && !st.net_q.contains(&k) { + st.net_q.push(k); + } + } else { + st.failed.insert(k, Instant::now() + FAILED_RETRY); + } + st.events.push(TileEvent::Failed { key: k, error }); + }; + let resp = match result { + Ok(r) => r, + Err(e) => { + let mut st = sh.lock(); + if sh.cancel.load(Ordering::Relaxed) { + return; + } + st.back_off(None); + fail(&mut st, e, true); + return; + } + }; + let header = |n: &str| resp.header(n); + match resp.status { + 200 => { + let decoded = decode_tile(&resp.body); + let (meta, store) = TileMeta::from_response(now, header); + let mut st = sh.lock(); + st.errors_in_row = 0; + st.backoff_until = None; + match decoded { + Ok(img) => { + drop(st); + if store + && let Some(c) = &sh.cache + && let Err(e) = c.write(k, &meta, &resp.body) + { + log::warn!("map: {e}"); + } + let mut st = sh.lock(); + // an answer that is already stale (no-cache, max-age=0) isn't asked for again this session + if meta.expires > now { + st.revalidated.remove(&k); + } else { + st.revalidated.insert(k); + } + let image = Arc::new(img); + st.remember(k, Arc::clone(&image), meta.expires); + st.events.push(TileEvent::Ready { key: k, image, stale: false }); + } + Err(e) => fail(&mut st, format!("{url}: {e}"), false), + } + } + 304 => { + let refreshed = match (&cached, &sh.cache) { + (Some(old), Some(c)) => { + let meta = old.revalidated(now, header); + c.refresh(k, &meta).map(|ok| ok.then_some(meta)).unwrap_or_else(|e| { + log::warn!("map: {e}"); + None + }) + } + _ => None, + }; + let mut st = sh.lock(); + st.stats.not_modified += 1; + st.errors_in_row = 0; + st.backoff_until = None; + match refreshed { + Some(meta) => { + if let Some(t) = st.memory.get_mut(&k) { + t.expires = meta.expires; + } + if meta.expires > now { + st.revalidated.remove(&k); + } + } + None => fail(&mut st, format!("{url}: 304 for a tile that isn't cached"), false), + } + } + // overloaded or blocked: back off the whole host + 429 | 403 | 500..=599 => { + let mut st = sh.lock(); + st.back_off(retry_after(&resp)); + let retry = resp.status != 403; + fail(&mut st, format!("{url}: HTTP {}", resp.status), retry); + } + s => { + let mut st = sh.lock(); + fail(&mut st, format!("{url}: HTTP {s}"), false); + } + } +} diff --git a/crates/engine/src/map/source.rs b/crates/engine/src/map/source.rs new file mode 100644 index 0000000000..8645feab67 --- /dev/null +++ b/crates/engine/src/map/source.rs @@ -0,0 +1,397 @@ +//! Tile sources: where map tiles come from. +//! +//! The default is OpenStreetMap's standard tile layer, used under the OSMF tile usage policy +//! (): the exact URL [`OSM_TILE_URL`], the +//! attribution [`OSM_ATTRIBUTION`] always shown on the map, and a User-Agent naming LightCraft +//! ([`USER_AGENT`]). OpenTopoMap is a second built-in choice; users may also point the map at +//! another raster tile server (an `https://` URL template with `{z}`, `{x}` and `{y}`) or turn +//! tiles off ([`TileSource::Offline`]). +//! +//! The Esri layers need an explicit opt-in ([`TileSource::requires_opt_in`]): until the user has +//! turned them on they are not offered and never fetched. See `docs/map.md` (Esri's terms). +//! +//! Validation of custom sources is ported from the map core of PR #797 (Jason Baldwin). + +use serde::{Deserialize, Serialize}; + +use super::MapError; +use super::mercator::{MAX_ZOOM, TileKey}; + +/// OpenStreetMap's standard raster tiles. +pub const OSM_TILE_URL: &str = "https://tile.openstreetmap.org/{z}/{x}/{y}.png"; +/// The attribution OpenStreetMap's tiles require, shown on the map. +pub const OSM_ATTRIBUTION: &str = "© OpenStreetMap contributors"; +/// OpenStreetMap's deepest zoom. +pub const OSM_MAX_ZOOM: u8 = 19; +/// OpenTopoMap's raster tiles (CC-BY-SA; ). +pub const OPENTOPOMAP_TILE_URL: &str = "https://tile.opentopomap.org/{z}/{x}/{y}.png"; +/// The credit OpenTopoMap asks for. +pub const OPENTOPOMAP_ATTRIBUTION: &str = "Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)"; +const ESRI_STREET_URL: &str = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}"; +const ESRI_TOPO_URL: &str = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"; +const ESRI_IMAGERY_URL: &str = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"; +/// The credits of each Esri layer, as its ArcGIS Online item gives them (`accessInformation`). +const ESRI_STREET_ATTRIBUTION: &str = "Powered by Esri | Sources: Esri, HERE, Garmin, USGS, Intermap, INCREMENT P, NRCAN, Esri Japan, METI, Esri China (Hong Kong), NOSTRA, © OpenStreetMap contributors, and the GIS User Community"; +const ESRI_TOPO_ATTRIBUTION: &str = "Powered by Esri | Sources: Esri, HERE, Garmin, Intermap, INCREMENT P, GEBCO, USGS, FAO, NPS, NRCAN, GeoBase, IGN, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), © OpenStreetMap contributors, GIS User Community"; +const ESRI_IMAGERY_ATTRIBUTION: &str = "Powered by Esri | Esri, Vantor, Earthstar Geographics, and the GIS User Community"; +/// The User-Agent sent with every tile request: distinct and stable, naming the app and where to +/// find it, as the OSMF policy asks. No personal details. +pub const USER_AGENT: &str = concat!("LightCraft/", env!("CARGO_PKG_VERSION"), " (+https://github.com/storytold/lightcraft)"); + +/// Longest URL template accepted. +const MAX_TEMPLATE: usize = 512; +/// Longest attribution accepted. +const MAX_ATTRIBUTION: usize = 200; +/// Longest source id accepted. +const MAX_ID: usize = 40; + +/// Where tiles come from. The built-in sources carry their URL, attribution and max zoom; a +/// [`TileSource::Custom`] one is built with [`TileSource::custom`], which checks everything. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TileSource { + /// OpenStreetMap's standard tiles (the default). + #[default] + Osm, + /// OpenTopoMap (topographic, from OpenStreetMap data and SRTM). + OpenTopoMap, + /// Esri World Street Map (opt-in). + EsriStreet, + /// Esri World Topographic Map (opt-in). + EsriTopo, + /// Esri World Imagery (opt-in). + EsriImagery, + /// No tiles and no network: the map shows only what is drawn on top of it (pins, tracks). + Offline, + /// A user-configured raster tile server. + Custom { + /// Short id, also the name of the source's cache folder (`[a-z0-9._-]`). + id: String, + /// `https://…/{z}/{x}/{y}.png`. + url_template: String, + /// The credit shown on the map (always visible, never behind a toggle). + attribution: String, + /// Deepest zoom the server has tiles for (views zoomed further scale these up). + max_zoom: u8, + }, +} + +impl TileSource { + /// The built-in sources, in the order a picker lists them. + pub const BUILT_IN: [TileSource; 6] = + [TileSource::Osm, TileSource::OpenTopoMap, TileSource::EsriStreet, TileSource::EsriTopo, TileSource::EsriImagery, TileSource::Offline]; + + /// The built-in source with id `id` (also accepts a few spellings: `openstreetmap`, + /// `esri-street`, `esriImagery`…), case-insensitive. + pub fn built_in(id: &str) -> Option { + let id = id.trim().to_ascii_lowercase().replace(['_', ' '], "-"); + Some(match id.as_str() { + "osm" | "openstreetmap" => TileSource::Osm, + "opentopomap" | "otm" => TileSource::OpenTopoMap, + "esri-streets" | "esri-street" | "esristreet" | "esristreets" => TileSource::EsriStreet, + "esri-topo" | "esritopo" => TileSource::EsriTopo, + "esri-imagery" | "esriimagery" => TileSource::EsriImagery, + "offline" | "none" => TileSource::Offline, + _ => return None, + }) + } + + /// Short id: the built-in name, or the custom source's own id. Also the cache folder name. + pub fn id(&self) -> &str { + match self { + TileSource::Osm => "osm", + TileSource::OpenTopoMap => "opentopomap", + TileSource::EsriStreet => "esri-streets", + TileSource::EsriTopo => "esri-topo", + TileSource::EsriImagery => "esri-imagery", + TileSource::Offline => "offline", + TileSource::Custom { id, .. } => id, + } + } + + /// English name for a picker (the UI translates it). + pub fn label(&self) -> &str { + match self { + TileSource::Osm => "OpenStreetMap", + TileSource::OpenTopoMap => "OpenTopoMap", + TileSource::EsriStreet => "Esri World Street Map", + TileSource::EsriTopo => "Esri World Topographic Map", + TileSource::EsriImagery => "Esri World Imagery", + TileSource::Offline => "Offline (no tiles)", + TileSource::Custom { .. } => "Custom tile server", + } + } + + /// `https://…/{z}/{x}/{y}…`; `None` for the offline source. + pub fn url_template(&self) -> Option<&str> { + Some(match self { + TileSource::Osm => OSM_TILE_URL, + TileSource::OpenTopoMap => OPENTOPOMAP_TILE_URL, + TileSource::EsriStreet => ESRI_STREET_URL, + TileSource::EsriTopo => ESRI_TOPO_URL, + TileSource::EsriImagery => ESRI_IMAGERY_URL, + TileSource::Offline => return None, + TileSource::Custom { url_template, .. } => url_template, + }) + } + + /// The credit painted on the map whenever its tiles are (empty for the offline source). + pub fn attribution(&self) -> &str { + match self { + TileSource::Osm => OSM_ATTRIBUTION, + TileSource::OpenTopoMap => OPENTOPOMAP_ATTRIBUTION, + TileSource::EsriStreet => ESRI_STREET_ATTRIBUTION, + TileSource::EsriTopo => ESRI_TOPO_ATTRIBUTION, + TileSource::EsriImagery => ESRI_IMAGERY_ATTRIBUTION, + TileSource::Offline => "", + TileSource::Custom { attribution, .. } => attribution, + } + } + + /// Deepest zoom the server has tiles for. + pub fn max_zoom(&self) -> u8 { + match self { + TileSource::Osm | TileSource::Offline => OSM_MAX_ZOOM, + TileSource::OpenTopoMap => 17, + TileSource::EsriStreet | TileSource::EsriTopo => 18, + TileSource::EsriImagery => 19, + TileSource::Custom { max_zoom, .. } => *max_zoom, + } + } + + /// Esri's layers: offered and fetched only after the user turns them on (`docs/map.md`). + pub fn requires_opt_in(&self) -> bool { + matches!(self, TileSource::EsriStreet | TileSource::EsriTopo | TileSource::EsriImagery) + } + + /// No network: tiles are never fetched. + pub fn is_offline(&self) -> bool { + matches!(self, TileSource::Offline) + } + + /// The User-Agent sent with every request ([`USER_AGENT`]). + pub fn user_agent(&self) -> &'static str { + USER_AGENT + } + + /// The URL of `key`, or `None` for the offline source (or a key past the source's max zoom). + pub fn url(&self, key: TileKey) -> Option { + let template = self.url_template()?; + if key.z > self.max_zoom() { + return None; + } + Some(template.replace("{z}", &key.z.to_string()).replace("{x}", &key.x.to_string()).replace("{y}", &key.y.to_string())) + } + + /// The server's host name (lower-case), for messages. + pub fn host(&self) -> Option { + let rest = self.url_template()?.split_once("://")?.1; + let host = rest.split(['/', '?', '#']).next()?; + (!host.is_empty()).then(|| host.to_ascii_lowercase()) + } + + /// A user-configured raster source, checked: the template must be an `https://` URL with + /// `{z}`, `{x}` and `{y}` (and no other placeholder), the attribution non-empty (tile licences + /// require credit; OpenStreetMap's template gives [`TileSource::Osm`]), the max zoom at most + /// [`MAX_ZOOM`]. `id` names the cache folder; when absent it is derived from the template + /// (`custom-`). It may not be a built-in source's id. + pub fn custom(id: Option<&str>, url_template: &str, attribution: Option<&str>, max_zoom: Option) -> Result { + let url_template = url_template.trim(); + validate_template(url_template)?; + if url_template == OSM_TILE_URL && id.is_none_or(|i| i.trim().is_empty() || i.trim() == "osm") { + if max_zoom.is_some_and(|z| z != OSM_MAX_ZOOM) { + return Err(bad(format!("OpenStreetMap has tiles up to zoom {OSM_MAX_ZOOM}"))); + } + return Ok(TileSource::Osm); + } + let attribution = match attribution.map(str::trim).filter(|a| !a.is_empty()) { + Some(a) => a.to_string(), + None => return Err(bad("an attribution is required (the tile provider's credit, shown on the map)")), + }; + if attribution.chars().count() > MAX_ATTRIBUTION || attribution.chars().any(char::is_control) { + return Err(bad(format!("the attribution must be one line of at most {MAX_ATTRIBUTION} characters"))); + } + let max_zoom = max_zoom.unwrap_or(18); + if max_zoom > MAX_ZOOM { + return Err(bad(format!("maxZoom must be 0..={MAX_ZOOM}"))); + } + let id = match id.map(str::trim).filter(|i| !i.is_empty()) { + Some(id) => { + validate_id(id)?; + if TileSource::built_in(id).is_some() { + return Err(bad(format!("the id `{id}` is a built-in source's; give this source another id"))); + } + id.to_string() + } + None => format!("custom-{:08x}", fnv1a(url_template.as_bytes()) as u32), + }; + Ok(TileSource::Custom { id, url_template: url_template.to_string(), attribution, max_zoom }) + } + + /// Re-check a stored source (a settings file is hostile input): built-in sources as they are, + /// a custom one through [`TileSource::custom`]. + pub fn checked(&self) -> Result { + match self { + TileSource::Custom { id, url_template, attribution, max_zoom } => { + TileSource::custom(Some(id), url_template, Some(attribution), Some(*max_zoom)) + } + other => Ok(other.clone()), + } + } +} + +fn bad(msg: impl Into) -> MapError { + MapError::InvalidSource(msg.into()) +} + +/// FNV-1a, 64 bit: a stable hash for derived cache-folder names. +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) +} + +/// A source id: 1–40 characters of `[a-z0-9._-]`, not starting with `.`. +pub fn validate_id(id: &str) -> Result<(), MapError> { + let ok_chars = id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-')); + if id.is_empty() || id.len() > MAX_ID || !ok_chars || id.starts_with('.') { + return Err(bad(format!("the id must be 1–{MAX_ID} characters of a–z, 0–9, '.', '_' or '-' (not starting with '.')"))); + } + Ok(()) +} + +/// A tile URL template: `https://host/…` with `{z}`, `{x}` and `{y}` each once, no other `{…}`, no +/// spaces or control characters, at most 512 characters. +pub fn validate_template(t: &str) -> Result<(), MapError> { + if t.len() > MAX_TEMPLATE { + return Err(bad(format!("the URL template is longer than {MAX_TEMPLATE} characters"))); + } + if t.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err(bad("the URL template has spaces or control characters")); + } + let Some(rest) = t.strip_prefix("https://") else { + return Err(bad("the URL template must start with https:// (tiles are only fetched over a secure connection)")); + }; + let host = rest.split(['/', '?', '#']).next().unwrap_or_default(); + let host_ok = !host.is_empty() + && !host.contains('@') + && !host.contains('{') + && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')); + if !host_ok { + return Err(bad("the URL template needs a plain host name after https:// (no placeholders or user names there)")); + } + for p in ["{z}", "{x}", "{y}"] { + if t.matches(p).count() != 1 { + return Err(bad(format!("the URL template must contain {p} exactly once"))); + } + } + let stripped = t.replace("{z}", "").replace("{x}", "").replace("{y}", ""); + if stripped.contains(['{', '}']) { + return Err(bad("the URL template may only use the {z}, {x} and {y} placeholders")); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_is_openstreetmap_under_its_policy() { + let s = TileSource::default(); + assert_eq!(s, TileSource::Osm); + assert_eq!(s.url_template(), Some("https://tile.openstreetmap.org/{z}/{x}/{y}.png")); + assert_eq!(s.attribution(), "© OpenStreetMap contributors"); + assert_eq!((s.id(), s.max_zoom()), ("osm", 19)); + assert_eq!(s.user_agent(), format!("LightCraft/{} (+https://github.com/storytold/lightcraft)", env!("CARGO_PKG_VERSION"))); + assert_eq!(s.url(TileKey::new(10, 511, 340).unwrap()).as_deref(), Some("https://tile.openstreetmap.org/10/511/340.png")); + assert_eq!(s.url(TileKey::new(20, 0, 0).unwrap()), None, "past the max zoom"); + assert_eq!(s.host().as_deref(), Some("tile.openstreetmap.org")); + assert_eq!(s.checked().unwrap(), s); + assert!(!s.requires_opt_in()); + } + + #[test] + fn built_in_sources_have_urls_credits_and_opt_in() { + for s in TileSource::BUILT_IN { + assert_eq!(TileSource::built_in(s.id()), Some(s.clone()), "{s:?}"); + if !s.is_offline() { + assert!(!s.attribution().is_empty(), "{s:?} always has a credit"); + assert!(s.url_template().is_some_and(|t| validate_template(t).is_ok()), "{s:?}"); + } + } + let esri: Vec<_> = TileSource::BUILT_IN.into_iter().filter(TileSource::requires_opt_in).collect(); + assert_eq!(esri, vec![TileSource::EsriStreet, TileSource::EsriTopo, TileSource::EsriImagery]); + // Esri's tile URLs are row before column + assert!(TileSource::EsriImagery.url(TileKey::new(3, 1, 2).unwrap()).unwrap().ends_with("/tile/3/2/1")); + assert_eq!(TileSource::built_in("OpenStreetMap"), Some(TileSource::Osm)); + assert_eq!(TileSource::built_in("esri-street"), Some(TileSource::EsriStreet)); + assert_eq!(TileSource::built_in("bing"), None); + } + + #[test] + fn offline_never_has_urls() { + let s = TileSource::Offline; + assert!(s.is_offline()); + assert_eq!(s.url(TileKey::new(0, 0, 0).unwrap()), None); + assert_eq!(s.checked().unwrap(), s); + } + + #[test] + fn custom_sources_are_checked() { + let s = TileSource::custom(None, "https://tiles.example.org/base/{z}/{x}/{y}.png?key=1", Some("© Example"), Some(17)).unwrap(); + assert!(s.id().starts_with("custom-") && s.id().len() == 15, "{}", s.id()); + assert_eq!(s.url(TileKey::new(3, 1, 2).unwrap()).as_deref(), Some("https://tiles.example.org/base/3/1/2.png?key=1")); + assert_eq!( + TileSource::custom(None, "https://tiles.example.org/base/{z}/{x}/{y}.png?key=1", Some("© Example"), None).unwrap().id(), + s.id(), + "stable id" + ); + let named = TileSource::custom(Some("my-tiles"), "https://a.example/{z}/{y}/{x}", Some("© A"), None).unwrap(); + assert_eq!((named.id(), named.max_zoom()), ("my-tiles", 18)); + // OpenStreetMap's own template is OpenStreetMap + assert_eq!(TileSource::custom(None, OSM_TILE_URL, None, None).unwrap(), TileSource::Osm); + for (template, attribution, zoom, id) in [ + ("http://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, None), + ("ftp://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, None), + ("file:///tmp/{z}/{x}/{y}.png", Some("x"), None, None), + ("https://tiles.example.org/{z}/{x}.png", Some("x"), None, None), + ("https://tiles.example.org/{z}/{x}/{y}/{y}.png", Some("x"), None, None), + ("https://tiles.example.org/{s}/{z}/{x}/{y}.png", Some("x"), None, None), + ("https://{z}.example.org/{x}/{y}.png", Some("x"), None, None), + ("https://user@tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, None), + ("https:///{z}/{x}/{y}.png", Some("x"), None, None), + ("https://tiles.example.org/{z}/{x}/{y}.png\r\nX: 1", Some("x"), None, None), + ("https://tiles.example.org/{z}/{x}/{y}.png", None, None, None), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some(" "), None, None), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("a\nb"), None, None), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), Some(25), None), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("osm")), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("offline")), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("esri-imagery")), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("../etc")), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("Upper")), + (OSM_TILE_URL, None, Some(20), None), + ] { + assert!(TileSource::custom(id, template, attribution, zoom).is_err(), "{template} {attribution:?} {zoom:?} {id:?}"); + } + assert!(TileSource::custom(None, &format!("https://a.example/{}{{z}}/{{x}}/{{y}}", "p".repeat(600)), Some("x"), None).is_err()); + } + + #[test] + fn stored_sources_are_rechecked_and_round_trip() { + let evil = + TileSource::Custom { id: "evil".into(), url_template: "http://evil.example/{z}/{x}/{y}".into(), attribution: "x".into(), max_zoom: 19 }; + assert!(evil.checked().is_err()); + for s in + TileSource::BUILT_IN + .into_iter() + .chain([TileSource::custom(Some("mine"), "https://t.example/{z}/{x}/{y}.png", Some("© T"), Some(12)).unwrap()]) + { + let json = serde_json::to_string(&s).unwrap(); + assert!(!json.contains("userAgent"), "the User-Agent is not a setting: {json}"); + let back: TileSource = serde_json::from_str(&json).unwrap(); + assert_eq!(back, s); + } + assert_eq!(serde_json::to_value(TileSource::Osm).unwrap(), serde_json::json!({"kind": "osm"})); + assert!(serde_json::from_str::(r#"{"kind": "bing"}"#).is_err()); + } +} diff --git a/crates/engine/src/map/tests_mercator.rs b/crates/engine/src/map/tests_mercator.rs new file mode 100644 index 0000000000..1c06b71a0b --- /dev/null +++ b/crates/engine/src/map/tests_mercator.rs @@ -0,0 +1,229 @@ +//! Web Mercator maths: known values, round trips, viewport tile sets, bounds and fitting. + +use lightcraft_geom::Point; + +use super::mercator::*; + +fn ll(lat: f64, lon: f64) -> LatLon { + LatLon::new(lat, lon).unwrap() +} + +fn close(a: f64, b: f64, eps: f64) -> bool { + (a - b).abs() <= eps +} + +#[test] +fn checked_points_reject_nan_and_out_of_range() { + assert!(LatLon::new(51.5, -0.12).is_some()); + assert!(LatLon::new(90.0, 180.0).is_some() && LatLon::new(-90.0, -180.0).is_some()); + for (lat, lon) in + [(f64::NAN, 0.0), (0.0, f64::NAN), (f64::INFINITY, 0.0), (0.0, f64::NEG_INFINITY), (90.0001, 0.0), (-91.0, 0.0), (0.0, 180.5), (0.0, -720.0)] + { + assert_eq!(LatLon::new(lat, lon), None, "{lat} {lon}"); + } + assert_eq!(from_gps(Some((1.0, 2.0))), Some(ll(1.0, 2.0))); + assert_eq!(from_gps(Some((f64::NAN, 2.0))), None); + assert_eq!(from_gps(None), None); +} + +#[test] +fn tile_corners_at_known_zooms() { + // zoom 0: the whole square + let (nw, se) = TileKey::new(0, 0, 0).unwrap().corners(); + assert!(close(nw.lat, MAX_LATITUDE, 1e-8) && close(nw.lon, -180.0, 1e-12)); + assert!(close(se.lat, -MAX_LATITUDE, 1e-8) && close(se.lon, 180.0, 1e-12)); + // zoom 1: four quadrants meeting at (0, 0) + let (nw, se) = TileKey::new(1, 1, 0).unwrap().corners(); + assert!(close(nw.lat, MAX_LATITUDE, 1e-8) && close(nw.lon, 0.0, 1e-12)); + assert!(close(se.lat, 0.0, 1e-12) && close(se.lon, 180.0, 1e-12)); + let (nw, se) = TileKey::new(1, 0, 1).unwrap().corners(); + assert!(close(nw.lat, 0.0, 1e-12) && close(nw.lon, -180.0, 1e-12) && close(se.lat, -MAX_LATITUDE, 1e-8) && close(se.lon, 0.0, 1e-12)); + // zoom 10: central London is tile 511/340 (the tile OpenStreetMap serves for it) + let london = ll(51.5074, -0.1278); + assert_eq!(TileKey::containing(london, 10), TileKey::new(10, 511, 340).unwrap()); + let (nw, se) = TileKey::new(10, 511, 340).unwrap().corners(); + assert!(nw.lat > london.lat && se.lat < london.lat && nw.lon < london.lon && se.lon > london.lon); + assert!(close(nw.lon, -0.3515625, 1e-12) && close(se.lon, 0.0, 1e-12)); + assert!(close(nw.lat, 51.618_017, 1e-5) && close(se.lat, 51.399_206, 1e-5), "{nw:?} {se:?}"); + // the poles and the antimeridian clamp/wrap onto the grid + assert_eq!(TileKey::containing(ll(90.0, 180.0), 3), TileKey::new(3, 0, 0).unwrap()); + assert_eq!(TileKey::containing(ll(-90.0, 179.999), 3), TileKey::new(3, 7, 7).unwrap()); + assert_eq!(TileKey::new(3, 8, 0), None); + assert_eq!(TileKey::new(25, 0, 0), None); +} + +#[test] +fn projection_round_trips() { + for z in [0.0, 1.0, 5.5, 10.0, 19.0, 24.0] { + for p in [ll(0.0, 0.0), ll(51.5074, -0.1278), ll(-33.8688, 151.2093), ll(85.0, 179.9), ll(-85.0, -179.9), ll(35.0, 139.0)] { + let back = from_world(to_world(p, z), z); + assert!(close(back.lat, p.lat, 1e-9) && close(back.lon, p.lon, 1e-9), "z{z} {p:?} → {back:?}"); + } + } + // latitude beyond the square clamps, longitude wraps + let w = to_world(ll(89.0, 0.0), 2.0); + assert!(close(w.y, 0.0, 1e-6)); + assert_eq!(wrap_lon(180.0), -180.0); + assert_eq!(wrap_lon(190.0), -170.0); + assert_eq!(wrap_lon(-540.0), -180.0); + assert_eq!(wrap_lon(f64::NAN), 0.0); + assert!(from_world(Point::new(f64::NAN, f64::NAN), 3.0).lat.is_finite()); + assert!(close(to_world(ll(0.0, 0.0), 0.0).x, 128.0, 1e-12) && close(to_world(ll(0.0, 0.0), 0.0).y, 128.0, 1e-9)); +} + +#[test] +fn viewport_tiles_cover_the_view_exactly() { + // zoom 2 (a 1024 px world) in a 512 × 512 view centred on (0, 0): the four middle tiles + let v = Viewport::new(ll(0.0, 0.0), 2.0, 512.0, 512.0); + let tiles = v.tiles(19); + let mut keys: Vec<_> = tiles.iter().map(|t| (t.key.x, t.key.y)).collect(); + keys.sort(); + assert_eq!(keys, vec![(1, 1), (1, 2), (2, 1), (2, 2)]); + for t in &tiles { + assert!(close(t.rect.x1 - t.rect.x0, 256.0, 1e-9)); + assert!(t.rect.x0 >= -1e-9 && t.rect.x1 <= 512.0 + 1e-9, "{t:?}"); + } + // the one-tile margin adds a ring, at the same zoom only + let keys = v.tile_keys(19, 1); + assert_eq!(keys.len(), 16); + assert!(keys.iter().all(|k| k.z == 2)); + // asking for more margin still gives one ring (the tile policy) + assert_eq!(v.tile_keys(19, 5), keys); + // no margin = what is drawn + assert_eq!(v.tile_keys(19, 0).len(), 4); + // centre first + let first = keys.first().unwrap(); + assert!(matches!((first.x, first.y), (1..=2, 1..=2))); +} + +#[test] +fn fractional_zoom_scales_tiles() { + // zoom 2.4 draws zoom-2 tiles at 2^0.4 scale; 2.6 draws zoom-3 tiles at 2^-0.4 + let v = Viewport::new(ll(10.0, 20.0), 2.4, 800.0, 600.0); + assert_eq!(v.tile_zoom(19), 2); + let t = v.tiles(19); + assert!(t.iter().all(|t| t.key.z == 2 && close(t.rect.x1 - t.rect.x0, 256.0 * 0.4f64.exp2(), 1e-9))); + let v = Viewport::new(ll(10.0, 20.0), 2.6, 800.0, 600.0); + assert_eq!(v.tile_zoom(19), 3); + assert!(v.tiles(19).iter().all(|t| t.key.z == 3 && close(t.rect.x1 - t.rect.x0, 256.0 * (-0.4f64).exp2(), 1e-9))); + // the drawn tiles cover the whole view + for v in [Viewport::new(ll(10.0, 20.0), 2.6, 800.0, 600.0), Viewport::new(ll(48.85, 2.35), 13.3, 1280.0, 720.0)] { + let t = v.tiles(19); + for (x, y) in [(0.5, 0.5), (v.width - 0.5, 0.5), (0.5, v.height - 0.5), (v.width - 0.5, v.height - 0.5), (v.width / 2.0, v.height / 2.0)] { + assert!(t.iter().any(|t| t.rect.x0 <= x && x < t.rect.x1 && t.rect.y0 <= y && y < t.rect.y1), "({x}, {y}) uncovered at {v:?}"); + } + } + // past the source's max zoom: its deepest tiles, scaled up + let v = Viewport::new(ll(48.85, 2.35), 21.0, 400.0, 400.0); + assert_eq!(v.tile_zoom(19), 19); + assert!(v.tiles(19).iter().all(|t| close(t.rect.x1 - t.rect.x0, 1024.0, 1e-6))); +} + +#[test] +fn edges_wrap_east_west_and_stop_at_the_poles() { + // at the antimeridian the tiles of both sides are loaded + let v = Viewport::new(ll(0.0, 180.0), 3.0, 512.0, 256.0); + let keys = v.tile_keys(19, 0); + let xs: std::collections::BTreeSet = keys.iter().map(|k| k.x).collect(); + assert_eq!(xs, [0, 7].into_iter().collect()); + // at the top of the map no row above 0 is asked for + let v = Viewport::new(ll(85.0, 0.0), 4.0, 512.0, 512.0); + assert!(v.tile_keys(19, 1).iter().all(|k| k.y < 16)); + assert!(v.tiles(19).iter().all(|t| t.key.y == 0 || t.key.y == 1)); + // at zoom 0 a wide view repeats the one tile; it is loaded once + let v = Viewport::new(ll(0.0, 0.0), 0.0, 1500.0, 256.0); + assert!(v.tiles(19).len() > 1); + assert_eq!(v.tile_keys(19, 1), vec![TileKey::new(0, 0, 0).unwrap()]); + // empty or absurd views are safe + assert!(Viewport::new(ll(0.0, 0.0), 3.0, 0.0, 100.0).tiles(19).is_empty()); + let huge = Viewport { center: LatLon { lat: f64::NAN, lon: 1e300 }, zoom: f64::INFINITY, width: 1e12, height: f64::NAN }; + assert!(huge.tile_keys(19, 1).len() <= 4096); + let tiny = Viewport { center: LatLon { lat: 0.0, lon: 0.0 }, zoom: -5.0, width: 300.0, height: 300.0 }; + assert_eq!(tiny.tile_keys(19, 1), vec![TileKey::new(0, 0, 0).unwrap()]); +} + +#[test] +fn screen_positions_pan_and_zoom() { + let v = Viewport::new(ll(48.85, 2.35), 12.0, 800.0, 600.0); + let c = v.to_screen(ll(48.85, 2.35)); + assert!(close(c.x, 400.0, 1e-6) && close(c.y, 300.0, 1e-6)); + for p in [Point::new(0.0, 0.0), Point::new(800.0, 600.0), Point::new(123.0, 456.0)] { + let q = v.to_screen(v.to_lat_lon(p)); + assert!(close(q.x, p.x, 1e-6) && close(q.y, p.y, 1e-6), "{p:?} → {q:?}"); + } + // pins near the antimeridian show on the nearest copy of the world + let v = Viewport::new(ll(0.0, 179.0), 5.0, 800.0, 600.0); + let east = v.to_screen(ll(0.0, -179.0)); + assert!(east.x > 400.0 && east.x < 800.0, "{east:?}"); + // panning moves content with the drag + let v = Viewport::new(ll(48.85, 2.35), 12.0, 800.0, 600.0); + let p = ll(48.86, 2.36); + let before = v.to_screen(p); + let after = v.panned(30.0, -20.0).to_screen(p); + assert!(close(after.x - before.x, 30.0, 1e-6) && close(after.y - before.y, -20.0, 1e-6)); + // zooming around a point keeps it under the pointer + let anchor = Point::new(100.0, 500.0); + let under = v.to_lat_lon(anchor); + let z = v.zoomed_around(anchor, 14.5); + assert!(close(z.zoom, 14.5, 1e-12)); + let q = z.to_screen(under); + assert!(close(q.x, anchor.x, 1e-6) && close(q.y, anchor.y, 1e-6), "{q:?}"); + assert!(v.to_screen(LatLon { lat: f64::NAN, lon: f64::NAN }).x.is_finite()); +} + +#[test] +fn bounds_skip_bad_points_and_handle_the_antimeridian() { + assert_eq!(Bounds::of(Vec::<(f64, f64)>::new()), None); + assert_eq!(Bounds::of([(f64::NAN, 1.0), (100.0, 0.0), (0.0, 200.0)]), None); + let b = Bounds::of([(48.85, 2.35), (51.5, -0.12), (f64::NAN, 50.0), (95.0, 0.0), (40.4, -3.7)]).unwrap(); + assert_eq!(b, Bounds { south: 40.4, west: -3.7, north: 51.5, east: 2.35 }); + assert!(!b.crosses_antimeridian() && b.contains(ll(45.0, 0.0)) && !b.contains(ll(45.0, 10.0))); + // Fiji-ish: both sides of 180°, a small box crossing it (not the whole world) + let b = Bounds::of([(-17.0, 178.0), (-16.5, -179.5), (-18.0, 179.5)]).unwrap(); + assert!(b.crosses_antimeridian()); + assert_eq!((b.west, b.east), (178.0, -179.5)); + assert!(close(b.lon_span(), 2.5, 1e-12)); + assert!(close(b.center().lon, 179.25, 1e-9)); + assert!(b.contains(ll(-17.0, 180.0)) && b.contains(ll(-17.0, -180.0)) && !b.contains(ll(-17.0, 0.0))); + // ±180 is one meridian + let b = Bounds::of([(0.0, 170.0), (0.0, 180.0)]).unwrap(); + assert_eq!((b.west, b.east), (170.0, 180.0)); + let b = Bounds::of([(0.0, -180.0), (0.0, 180.0)]).unwrap(); + assert_eq!(b.lon_span(), 0.0); + // one point + let b = Bounds::of([(10.0, 20.0)]).unwrap(); + assert_eq!(b, Bounds { south: 10.0, west: 20.0, north: 10.0, east: 20.0 }); +} + +#[test] +fn fit_bounds_shows_every_point_with_the_margin() { + let pts = [(48.85, 2.35), (51.5, -0.12), (40.4, -3.7), (52.52, 13.4)]; + let b = Bounds::of(pts).unwrap(); + let v = fit_bounds(&b, 1000.0, 700.0, 40.0, 18.0); + assert!(v.zoom > 3.0 && v.zoom < 6.0, "{v:?}"); + for (lat, lon) in pts { + let s = v.to_screen(ll(lat, lon)); + assert!(s.x >= 40.0 - 1e-6 && s.x <= 960.0 + 1e-6 && s.y >= 40.0 - 1e-6 && s.y <= 660.0 + 1e-6, "{lat},{lon} at {s:?}"); + } + // tight on one side + let lo = pts.iter().map(|p| v.to_screen(ll(p.0, p.1)).x).fold(f64::INFINITY, f64::min); + let hi = pts.iter().map(|p| v.to_screen(ll(p.0, p.1)).x).fold(f64::NEG_INFINITY, f64::max); + let top = pts.iter().map(|p| v.to_screen(ll(p.0, p.1)).y).fold(f64::INFINITY, f64::min); + let bottom = pts.iter().map(|p| v.to_screen(ll(p.0, p.1)).y).fold(f64::NEG_INFINITY, f64::max); + assert!(close(hi - lo, 920.0, 1e-3) || close(bottom - top, 620.0, 1e-3), "{lo} {hi} {top} {bottom}"); + // a single point gets the max zoom; across the antimeridian stays small + let one = fit_bounds(&Bounds::of([(10.0, 20.0)]).unwrap(), 800.0, 600.0, 20.0, 16.0); + assert_eq!(one.zoom, 16.0); + assert!(close(one.center.lat, 10.0, 1e-9) && close(one.center.lon, 20.0, 1e-9)); + let fiji = fit_bounds(&Bounds::of([(-17.0, 178.0), (-16.5, -179.5)]).unwrap(), 800.0, 600.0, 20.0, 18.0); + assert!(fiji.zoom > 6.0, "{fiji:?}"); + for (lat, lon) in [(-17.0, 178.0), (-16.5, -179.5)] { + let s = fiji.to_screen(ll(lat, lon)); + assert!((0.0..=800.0).contains(&s.x), "{s:?}"); + } + // the whole world fits at zoom 0 at most; silly sizes don't produce NaN + let world = fit_bounds(&Bounds { south: -85.0, west: -180.0, north: 85.0, east: 180.0 }, 200.0, 200.0, 10.0, 18.0); + assert_eq!(world.zoom, 0.0); + let silly = fit_bounds(&Bounds::of(pts).unwrap(), f64::NAN, -5.0, f64::INFINITY, f64::NAN); + assert!(silly.zoom.is_finite() && silly.center.lat.is_finite()); +} diff --git a/crates/engine/src/map/tests_service.rs b/crates/engine/src/map/tests_service.rs new file mode 100644 index 0000000000..8b85cba55a --- /dev/null +++ b/crates/engine/src/map/tests_service.rs @@ -0,0 +1,504 @@ +//! The fetch queue against an in-process fake tile server (a fake transport) and a localhost +//! server (never the internet): viewport-only requests, newest view first, at most two in flight, +//! backoff, the User-Agent, conditional refreshes, hostile responses and the activity row. +//! Ported from PR #797 (Jason Baldwin). +#![cfg(not(target_arch = "wasm32"))] + +use std::collections::HashSet; +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use super::cache::{TileCache, TileMeta}; +use super::mercator::{LatLon, TileKey, Viewport}; +use super::service::*; +use super::source::{TileSource, USER_AGENT}; + +type Handler = Box Result + Send + Sync>; + +struct Fake { + log: Mutex)>>, + active: AtomicUsize, + max_active: AtomicUsize, + handler: Handler, +} + +impl Fake { + fn new(handler: impl Fn(&str, &[(&'static str, String)]) -> Result + Send + Sync + 'static) -> Arc { + Arc::new(Fake { log: Mutex::new(Vec::new()), active: AtomicUsize::new(0), max_active: AtomicUsize::new(0), handler: Box::new(handler) }) + } + fn urls(&self) -> Vec { + self.log.lock().unwrap().iter().map(|(u, _)| u.clone()).collect() + } + fn keys(&self) -> Vec { + self.urls().iter().map(|u| key_of(u)).collect() + } +} + +impl Transport for Fake { + fn get(&self, url: &str, headers: &[(&'static str, String)], _max: usize, _cancel: &AtomicBool) -> Result { + self.log.lock().unwrap().push((url.to_string(), headers.to_vec())); + let n = self.active.fetch_add(1, Ordering::SeqCst) + 1; + self.max_active.fetch_max(n, Ordering::SeqCst); + let r = (self.handler)(url, headers); + self.active.fetch_sub(1, Ordering::SeqCst); + r + } +} + +fn source() -> TileSource { + TileSource::custom(Some("test"), "https://tiles.test/{z}/{x}/{y}.png", Some("© test"), Some(19)).unwrap() +} + +fn key_of(url: &str) -> TileKey { + let p: Vec = url.trim_start_matches("https://tiles.test/").trim_end_matches(".png").split('/').map(|s| s.parse().unwrap()).collect(); + TileKey::new(p[0] as u8, p[1], p[2]).unwrap() +} + +fn png(w: u32, h: u32) -> Vec { + use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png}; + let data: Vec = (0..w * h).flat_map(|i| [(i % 256) as u8, 100, 200, 255]).collect(); + encode_png(&EncodeImage::new(w, h, 4, Samples::U8(&data)), &EncodeMeta::default()).unwrap() +} + +fn ok_png(cache_control: &str) -> HttpResponse { + HttpResponse { status: 200, headers: vec![("Cache-Control".into(), cache_control.into()), ("ETag".into(), "\"v1\"".into())], body: png(256, 256) } +} + +fn wait_until(what: &str, secs: u64, f: impl Fn() -> bool) { + let end = Instant::now() + Duration::from_secs(secs); + while !f() { + assert!(Instant::now() < end, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn tmp(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-map-svc-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn paris() -> Viewport { + Viewport::new(LatLon::new(48.8566, 2.3522).unwrap(), 12.0, 800.0, 600.0) +} + +#[test] +fn only_the_views_tiles_are_requested_with_our_user_agent() { + let fake = Fake::new(|_, _| Ok(ok_png("max-age=3600"))); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + let view = paris(); + svc.show(&view); + let want: HashSet = view.tile_keys(19, 1).into_iter().collect(); + wait_until("all tiles", 20, || svc.is_idle() && fake.urls().len() >= want.len()); + let got: Vec = fake.keys(); + assert_eq!(got.len(), want.len(), "each tile once"); + assert!(got.iter().all(|k| want.contains(k) && k.z == 12), "only the view's tiles at its zoom"); + // the drawn tiles plus at most one ring: never more than (cols + 2) × (rows + 2) + let drawn: HashSet = view.tiles(19).iter().map(|t| t.key).collect(); + assert!(want.is_superset(&drawn)); + for (_, headers) in fake.log.lock().unwrap().iter() { + let ua: Vec<_> = headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case("user-agent")).collect(); + assert_eq!(ua.len(), 1); + assert_eq!(ua[0].1, USER_AGENT); + assert!( + !headers.iter().any(|(k, v)| k.eq_ignore_ascii_case("pragma") || (k.eq_ignore_ascii_case("cache-control") && v.contains("no-cache"))) + ); + } + let events = svc.poll(); + let ready: HashSet = + events.iter().filter_map(|e| if let TileEvent::Ready { key, stale: false, .. } = e { Some(*key) } else { None }).collect(); + assert_eq!(ready, want); + let img = svc.get(*drawn.iter().next().unwrap()).unwrap(); + assert_eq!((img.width, img.height, img.rgba.len()), (256, 256, 256 * 256 * 4)); + assert_eq!(&img.rgba[..4], &[0, 100, 200, 255]); + // the same view again: nothing new + svc.show(&view); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(fake.urls().len(), want.len()); +} + +#[test] +fn at_most_two_requests_at_a_time() { + let fake = Fake::new(|_, _| { + std::thread::sleep(Duration::from_millis(15)); + Ok(ok_png("max-age=60")) + }); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + let keys: Vec = (0..12).map(|x| TileKey::new(5, x, 3).unwrap()).collect(); + svc.want(&keys); + wait_until("12 tiles", 20, || svc.is_idle() && fake.urls().len() == 12); + assert_eq!(fake.max_active.load(Ordering::SeqCst), 2); + assert_eq!(svc.stats().max_in_flight, 2); + // nearest the centre (first in the list) first + assert_eq!(fake.keys()[..2].iter().map(|k| k.x).collect::>(), [0, 1].into_iter().collect()); +} + +#[test] +fn tiles_that_left_the_view_are_dropped_before_they_start() { + let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let g = gate.clone(); + let fake = Fake::new(move |_, _| { + let (open, cv) = &*g; + let mut o = open.lock().unwrap(); + while !*o { + o = cv.wait(o).unwrap(); + } + Ok(ok_png("max-age=60")) + }); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + let a = paris(); + let b = Viewport::new(LatLon::new(-33.86, 151.21).unwrap(), 12.0, 800.0, 600.0); + svc.show(&a); + wait_until("two requests on the wire", 10, || fake.active.load(Ordering::SeqCst) == 2); + svc.show(&b); + { + let (open, cv) = &*gate; + *open.lock().unwrap() = true; + cv.notify_all(); + } + let in_b: HashSet = b.tile_keys(19, 1).into_iter().collect(); + wait_until("view B", 20, || svc.is_idle() && fake.urls().len() == 2 + in_b.len()); + let keys = fake.keys(); + let in_a: HashSet = a.tile_keys(19, 1).into_iter().collect(); + assert!(keys[..2].iter().all(|k| in_a.contains(k)), "the two on the wire were A's"); + assert!(keys[2..].iter().all(|k| in_b.contains(k)), "then only B's: {:?}", &keys[2..]); + assert_eq!(keys[2..].iter().collect::>().len(), in_b.len()); +} + +#[test] +fn a_429_backs_off_the_host_instead_of_retrying() { + let fake = Fake::new(|_, _| Ok(HttpResponse { status: 429, headers: vec![], body: b"slow down".to_vec() })); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + let keys: Vec = (0..6).map(|x| TileKey::new(4, x, 4).unwrap()).collect(); + svc.want(&keys); + wait_until("the first answers", 10, || svc.stats().errors >= 1); + std::thread::sleep(Duration::from_millis(400)); + // at most the two that were already on the wire; then silence while backing off + assert!(fake.urls().len() <= 2, "{:?}", fake.urls()); + let s = svc.stats(); + assert!(s.backoff_ms > 0, "{s:?}"); + assert!(svc.poll().iter().any(|e| matches!(e, TileEvent::Failed { .. }))); + // after the backoff the host is asked again (one request at a time while it keeps failing) + wait_until("a retry", 10, || fake.urls().len() > 2); + std::thread::sleep(Duration::from_millis(300)); + assert!(fake.urls().len() <= 4, "no retry storm: {}", fake.urls().len()); +} + +#[test] +fn retry_after_is_honoured() { + let fake = Fake::new(|_, _| Ok(HttpResponse { status: 503, headers: vec![("Retry-After".into(), "120".into())], body: vec![] })); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + svc.want(&[TileKey::new(1, 0, 0).unwrap()]); + wait_until("the answer", 10, || svc.stats().errors == 1); + assert!(svc.stats().backoff_ms > 100_000, "{:?}", svc.stats()); +} + +#[test] +fn cached_tiles_need_no_request_and_stale_ones_are_revalidated() { + let root = tmp("revalidate"); + let fresh_key = TileKey::new(6, 10, 20).unwrap(); + let stale_key = TileKey::new(6, 11, 20).unwrap(); + let cache = TileCache::new(&root, "test", 100 << 20).unwrap(); + let now = crate::map::now_secs(); + cache.write(fresh_key, &TileMeta { fetched: now, expires: now + 3600, etag: Some("\"f\"".into()), last_modified: None }, &png(256, 256)).unwrap(); + let old = TileMeta { + fetched: now - 900_000, + expires: now - 10, + etag: Some("\"v1\"".into()), + last_modified: Some("Sun, 06 Nov 1994 08:49:37 GMT".into()), + }; + cache.write(stale_key, &old, &png(256, 256)).unwrap(); + let fake = Fake::new(|_, _| Ok(HttpResponse { status: 304, headers: vec![("Cache-Control".into(), "max-age=3600".into())], body: vec![] })); + let svc = TileService::with_transport(source(), Some(TileCache::new(&root, "test", 100 << 20).unwrap()), Some(fake.clone())); + svc.want(&[fresh_key, stale_key]); + wait_until("both", 10, || svc.is_idle() && svc.stats().not_modified == 1); + let events = svc.poll(); + assert!(events.iter().any(|e| matches!(e, TileEvent::Ready { key, stale: false, .. } if *key == fresh_key))); + assert!(events.iter().any(|e| matches!(e, TileEvent::Ready { key, stale: true, .. } if *key == stale_key)), "shown at once while refreshing"); + // only the stale one was asked for, conditionally + let log = fake.log.lock().unwrap().clone(); + assert_eq!(log.len(), 1); + assert_eq!(key_of(&log[0].0), stale_key); + assert!(log[0].1.contains(&("If-None-Match", "\"v1\"".to_string()))); + assert!(log[0].1.contains(&("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT".to_string()))); + // the 304 renewed it on disk, keeping its validators and bytes + let c = TileCache::new(&root, "test", 100 << 20).unwrap().read(stale_key).unwrap(); + assert!(c.meta.expires >= now + 3500 && c.meta.fetched >= now); + assert_eq!(c.meta.etag.as_deref(), Some("\"v1\"")); + assert_eq!(c.bytes, png(256, 256)); + // showing the same tiles again asks for nothing + svc.want(&[stale_key, fresh_key]); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(fake.urls().len(), 1); + drop(svc); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_stale_tile_whose_refresh_was_dropped_is_refreshed_when_back_in_view() { + let root = tmp("revalidate-dropped"); + let stale_key = TileKey::new(6, 11, 20).unwrap(); + let busy = [TileKey::new(6, 1, 1).unwrap(), TileKey::new(6, 2, 2).unwrap()]; + let now = crate::map::now_secs(); + let old = TileMeta { fetched: now - 900_000, expires: now - 10, etag: Some("\"v1\"".into()), last_modified: None }; + TileCache::new(&root, "test", 100 << 20).unwrap().write(stale_key, &old, &png(256, 256)).unwrap(); + let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let g = gate.clone(); + let fake = Fake::new(move |_, _| { + let (open, cv) = &*g; + let mut o = open.lock().unwrap(); + while !*o { + o = cv.wait(o).unwrap(); + } + Ok(ok_png("max-age=60")) + }); + let svc = TileService::with_transport(source(), Some(TileCache::new(&root, "test", 100 << 20).unwrap()), Some(fake.clone())); + // both request slots held, so the stale tile's refresh can only wait in the queue + svc.want(&busy); + wait_until("two requests on the wire", 10, || fake.active.load(Ordering::SeqCst) == 2); + svc.want(&[busy[0], busy[1], stale_key]); + wait_until("the stale tile from disk", 10, || svc.stats().in_memory >= 1); + // it leaves the view before its refresh starts, then comes back + svc.want(&busy); + svc.want(&[busy[0], busy[1], stale_key]); + { + let (open, cv) = &*gate; + *open.lock().unwrap() = true; + cv.notify_all(); + } + wait_until("the refresh", 10, || svc.is_idle() && fake.keys().contains(&stale_key)); + drop(svc); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn tiles_that_arrive_already_stale_are_not_refetched_every_frame() { + for cache_control in ["no-cache", "max-age=0"] { + let fake = Fake::new(move |_, _| Ok(ok_png(cache_control))); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + let keys = [TileKey::new(5, 1, 1).unwrap(), TileKey::new(5, 2, 1).unwrap()]; + svc.want(&keys); + wait_until("both tiles", 10, || svc.is_idle() && svc.stats().in_memory == 2); + // the UI shows the same view every frame + for _ in 0..20 { + svc.want(&keys); + std::thread::sleep(Duration::from_millis(5)); + } + wait_until("idle", 10, || svc.is_idle()); + assert_eq!(fake.urls().len(), 2, "{cache_control}: one request per tile, not one per frame"); + } +} + +#[test] +fn fetched_tiles_are_cached_and_damaged_entries_refetched() { + let root = tmp("store"); + let fake = Fake::new(|_, _| Ok(ok_png("max-age=600"))); + let k = TileKey::new(3, 4, 5).unwrap(); + let file = root.join("test/3/4/5.tile"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, b"LCTILE1\ncorrupt").unwrap(); + let svc = TileService::with_transport(source(), Some(TileCache::new(&root, "test", 100 << 20).unwrap()), Some(fake.clone())); + svc.want(&[k]); + wait_until("the tile", 10, || svc.get(k).is_some() && svc.is_idle()); + assert_eq!(fake.urls().len(), 1, "the damaged entry was fetched again"); + let c = TileCache::new(&root, "test", 100 << 20).unwrap().read(k).unwrap(); + assert_eq!(c.meta.etag.as_deref(), Some("\"v1\"")); + assert!(c.meta.expires > crate::map::now_secs() + 500); + // a cached file that isn't an image is deleted and fetched again too + drop(svc); + TileCache::new(&root, "test", 100 << 20).unwrap().write(k, &TileMeta { expires: i64::MAX, ..Default::default() }, b"not a png").unwrap(); + let svc = TileService::with_transport(source(), Some(TileCache::new(&root, "test", 100 << 20).unwrap()), Some(fake.clone())); + svc.want(&[k]); + wait_until("the tile again", 10, || svc.get(k).is_some() && svc.is_idle()); + assert_eq!(fake.urls().len(), 2); + drop(svc); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn hostile_responses_fail_cleanly_and_are_not_retried() { + let fake = Fake::new(|url, _| { + let k = key_of(url); + Ok(match k.x { + 0 => HttpResponse { status: 200, headers: vec![], body: b"captive portal".to_vec() }, + 1 => HttpResponse { status: 200, headers: vec![], body: png(2048, 4) }, + 2 => HttpResponse { status: 404, headers: vec![], body: vec![] }, + 3 => HttpResponse { status: 200, headers: vec![], body: png(256, 256)[..300].to_vec() }, + 4 => HttpResponse { status: 304, headers: vec![], body: vec![] }, + _ => panic!("a transport bug"), + }) + }); + let svc = TileService::with_transport(source(), None, Some(fake.clone())); + let keys: Vec = (0..6).map(|x| TileKey::new(3, x, 0).unwrap()).collect(); + svc.want(&keys); + wait_until("all answers", 10, || svc.is_idle() && fake.urls().len() == 6); + let failed: HashSet = + svc.poll().into_iter().filter_map(|e| if let TileEvent::Failed { key, .. } = e { Some(key) } else { None }).collect(); + assert_eq!(failed, keys.iter().copied().collect()); + assert!(keys.iter().all(|k| svc.get(*k).is_none())); + assert_eq!(svc.stats().backoff_ms, 0, "a refused tile is not the host's trouble"); + // asked again (a new view with the same tiles): not retried for a while + svc.want(&keys[..3]); + svc.want(&keys); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(fake.urls().len(), 6); +} + +#[test] +fn offline_and_transportless_services_never_fetch() { + let fake = Fake::new(|_, _| Ok(ok_png("max-age=60"))); + let svc = TileService::with_transport(TileSource::Offline, None, Some(fake.clone())); + svc.show(&paris()); + let inert = TileService::with_transport(source(), None, None); + inert.show(&paris()); + std::thread::sleep(Duration::from_millis(50)); + assert!(fake.urls().is_empty()); + assert!(svc.poll().is_empty() && inert.poll().is_empty()); + // the offline source has no cache either + let svc = TileService::new(TileSource::Offline, Some(tmp("offline")), 1 << 20, None, true); + svc.show(&paris()); + assert!(svc.is_idle()); +} + +/// The real HTTP client against a localhost server: our User-Agent (once), conditional headers, +/// no `no-cache`, 304s, and bodies over the cap refused. +#[test] +fn the_http_transport_sends_the_right_headers_and_caps_bodies() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let tile = png(256, 256); + let body = tile.clone(); + let server = std::thread::spawn(move || { + let mut requests = Vec::new(); + for i in 0..4 { + let (mut s, _) = listener.accept().unwrap(); + let mut r = BufReader::new(s.try_clone().unwrap()); + let mut head = Vec::new(); + loop { + let mut line = String::new(); + if r.read_line(&mut line).unwrap() == 0 || line.trim().is_empty() { + break; + } + head.push(line.trim().to_string()); + } + requests.push(head); + match i { + 0 => { + s.write_all( + format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nCache-Control: max-age=60\r\nETag: \"t\"\r\n\r\n", body.len()).as_bytes(), + ) + .unwrap(); + s.write_all(&body).unwrap(); + } + 1 => s.write_all(b"HTTP/1.1 304 Not Modified\r\nCache-Control: max-age=60\r\n\r\n").unwrap(), + 2 => s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 3000000\r\n\r\n").unwrap(), + _ => { + // chunked, past the cap without announcing it + s.write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n").unwrap(); + let chunk = vec![b'x'; 64 * 1024]; + for _ in 0..40 { + if s.write_all(format!("{:x}\r\n", chunk.len()).as_bytes()).is_err() + || s.write_all(&chunk).is_err() + || s.write_all(b"\r\n").is_err() + { + break; + } + } + } + } + } + requests + }); + let t = HttpTransport::default(); + let cancel = AtomicBool::new(false); + let ua = vec![("User-Agent", USER_AGENT.to_string())]; + let r = t.get(&format!("{base}/1/0/0.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap(); + assert_eq!((r.status, r.body.len(), r.header("etag")), (200, tile.len(), Some("\"t\""))); + assert!(decode_tile(&r.body).is_ok()); + let mut cond = ua.clone(); + cond.extend(TileMeta { etag: Some("\"t\"".into()), ..Default::default() }.conditional_headers()); + let r = t.get(&format!("{base}/1/0/0.png"), &cond, MAX_TILE_BYTES, &cancel).unwrap(); + assert_eq!((r.status, r.body.len()), (304, 0)); + assert!(t.get(&format!("{base}/1/0/1.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap_err().contains("larger")); + assert!(t.get(&format!("{base}/1/1/1.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap_err().contains("larger")); + let requests = server.join().unwrap(); + for head in &requests { + let agents: Vec<_> = head.iter().filter(|l| l.to_ascii_lowercase().starts_with("user-agent:")).collect(); + assert_eq!(agents, vec![&format!("User-Agent: {USER_AGENT}")], "{head:?}"); + assert!( + !head.iter().any(|l| l.to_ascii_lowercase().starts_with("pragma") || l.to_ascii_lowercase().starts_with("cache-control")), + "{head:?}" + ); + } + assert!(requests[1].contains(&"If-None-Match: \"t\"".to_string())); +} + +/// While tiles are queued or loading, one "Loading map tiles" row is on the activity stack; it +/// goes when they are all in. +#[test] +fn a_fetch_shows_one_activity_row_until_it_is_done() { + let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let g = gate.clone(); + let fake = Fake::new(move |_, _| { + let (open, cv) = &*g; + let mut o = open.lock().unwrap(); + while !*o { + o = cv.wait(o).unwrap(); + } + Ok(ok_png("max-age=60")) + }); + let activity = crate::activity::Activity::default(); + let svc = TileService::with_transport(source(), None, Some(fake.clone())).with_activity(Some(activity.clone())); + assert!(activity.list().is_empty(), "nothing before a view asks"); + let keys: Vec = (0..5).map(|x| TileKey::new(4, x, 4).unwrap()).collect(); + svc.want(&keys); + wait_until("two requests on the wire", 10, || fake.active.load(Ordering::SeqCst) == 2); + let rows = activity.list(); + assert_eq!(rows.len(), 1, "{rows:?}"); + assert_eq!((rows[0].kind, rows[0].label.as_str(), rows[0].cancellable), ("download", "Loading map tiles", false)); + assert_eq!((rows[0].done, rows[0].total), (0, 5)); + { + let (open, cv) = &*gate; + *open.lock().unwrap() = true; + cv.notify_all(); + } + wait_until("all tiles", 10, || svc.is_idle() && fake.urls().len() == 5); + wait_until("the row to go", 10, || activity.list().is_empty()); + // a view that leaves the map drops the queue, and the row with it + let more: Vec = (0..5).map(|x| TileKey::new(5, x, 4).unwrap()).collect(); + let (open, _) = &*gate; + *open.lock().unwrap() = false; + svc.want(&more); + wait_until("a row again", 10, || activity.list().len() == 1); + svc.want(&[]); + *open.lock().unwrap() = true; + gate.1.notify_all(); + wait_until("idle", 10, || svc.is_idle()); + wait_until("no row", 10, || activity.list().is_empty()); + drop(svc); +} + +/// A server announcing a huge body is an error, not an allocation of that size (the old fetcher +/// sized its buffer from the announced length and panicked with a capacity overflow). +#[test] +fn a_huge_announced_tile_length_is_an_error_not_an_allocation() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/6/25/31.png", listener.local_addr().unwrap()); + let server = std::thread::spawn(move || { + let (mut s, _) = listener.accept().unwrap(); + let mut r = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + while r.read_line(&mut line).unwrap_or(0) > 0 && !line.trim().is_empty() { + line.clear(); + } + let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 18446744073709551615\r\n\r\ntile"); + }); + let ua = vec![("User-Agent", USER_AGENT.to_string())]; + let err = HttpTransport::default().get(&url, &ua, MAX_TILE_BYTES, &AtomicBool::new(false)).unwrap_err(); + assert!(err.contains("larger"), "{err}"); + server.join().unwrap(); +} diff --git a/crates/engine/src/tests/map.rs b/crates/engine/src/tests/map.rs index c32b58b092..a24fb85a1a 100644 --- a/crates/engine/src/tests/map.rs +++ b/crates/engine/src/tests/map.rs @@ -1,18 +1,123 @@ use crate::Session; use serde_json::json; +/// The Esri layers used to be offered (and fetched) by default; their terms don't allow it, so +/// they are neither listed nor accepted. #[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")); + let ids: Vec<&str> = res.as_array().unwrap().iter().filter_map(|v| v.get("id")?.as_str()).collect(); + assert_eq!(ids, vec!["osm", "opentopomap", "offline"]); + assert_eq!(res[0]["current"], true); + assert_eq!(res[0]["attribution"], "© OpenStreetMap contributors"); +} + +#[test] +fn tile_source_get_and_set() { + let mut s = Session::new(); + let r = s.execute("map.tileSource", &json!({})).unwrap(); + assert_eq!(r["id"], "osm"); + assert_eq!(r["urlTemplate"], "https://tile.openstreetmap.org/{z}/{x}/{y}.png"); + assert_eq!(r["attribution"], "© OpenStreetMap contributors"); + assert_eq!(r["maxZoom"], 19); + assert!(r["userAgent"].as_str().unwrap().starts_with("LightCraft/")); + assert_eq!((r["offline"].as_bool(), r["esriEnabled"].as_bool()), (Some(false), Some(false))); + + let r = s.execute("map.tileSource", &json!({"offline": true})).unwrap(); + assert_eq!((r["id"].as_str(), r["offline"].as_bool()), (Some("offline"), Some(true))); + assert!(s.map_tiles().is_none(), "offline starts no tile service"); + // a field alone needs a server when offline + assert!(s.execute("map.tileSource", &json!({"maxZoom": 10})).is_err()); + let r = s.execute("map.tileSource", &json!({"offline": false})).unwrap(); + assert_eq!(r["id"], "osm"); + let r = s.execute("map.tileSource", &json!({"id": "opentopomap"})).unwrap(); + assert_eq!((r["id"].as_str(), r["maxZoom"].as_u64()), (Some("opentopomap"), Some(17))); + + let r = s + .execute("map.tileSource", &json!({"urlTemplate": "https://tiles.example.org/{z}/{x}/{y}.png", "attribution": "© Example", "maxZoom": 17})) + .unwrap(); + assert!(r["id"].as_str().unwrap().starts_with("custom-")); + assert_eq!((r["maxZoom"].as_u64(), r["custom"].as_bool()), (Some(17), Some(true))); + // change one field of the current source + let r = s.execute("map.tileSource", &json!({"maxZoom": 15})).unwrap(); + assert_eq!((r["maxZoom"].as_u64(), r["attribution"].as_str()), (Some(15), Some("© Example"))); + // bad settings are refused and change nothing + for bad in [ + json!({"urlTemplate": "http://tiles.example.org/{z}/{x}/{y}.png", "attribution": "x"}), + json!({"urlTemplate": "https://tiles.example.org/{z}/{x}.png", "attribution": "x"}), + json!({"urlTemplate": "https://other.example.org/{z}/{x}/{y}.png"}), + json!({"maxZoom": 99}), + json!({"maxZoom": -1}), + json!({"urlTemplate": 5}), + json!({"offline": "yes"}), + json!({"id": "../../etc"}), + json!({"id": "osm", "maxZoom": 12}), + ] { + assert!(matches!(s.execute("map.tileSource", &bad), Err(crate::EngineError::BadParams { .. })), "{bad}"); + } + assert_eq!(s.map.source().max_zoom(), 15); + let r = s.execute("map.tileSource", &json!({"id": "osm"})).unwrap(); + assert_eq!(r["urlTemplate"], crate::map::OSM_TILE_URL); +} + +/// Esri is refused while its opt-in is off (it is, and no command turns it on: docs/map.md), and +/// the refusal names why; the gate lets it through once enabled. +#[test] +fn esri_sources_are_refused_while_off_and_accepted_after_enabling() { + let mut s = Session::new(); + for id in ["esri-imagery", "esri-streets", "esri-topo"] { + let e = s.execute("map.tileSource", &json!({"id": id})).unwrap_err().to_string(); + assert!(e.contains("Esri") && e.contains("docs/map.md"), "{e}"); + } + assert_eq!(*s.map.source(), crate::map::TileSource::Osm); + assert!(s.execute("map.enableEsri", &json!({"on": true})).is_err(), "no command turns Esri on"); + s.map.set_esri_enabled(true); + let r = s.execute("map.tileSource", &json!({"id": "esri-imagery"})).unwrap(); + assert_eq!(r["id"], "esri-imagery"); + assert!(r["attribution"].as_str().unwrap().contains("Esri")); + let ids: Vec = + s.execute("map.providers", &json!({})).unwrap().as_array().unwrap().iter().map(|p| p["id"].as_str().unwrap().to_string()).collect(); + assert!(ids.contains(&"esri-imagery".to_string())); + // turned off again: the map falls back to OpenStreetMap, the choice is kept + s.map.set_esri_enabled(false); + let r = s.execute("map.tileSource", &json!({})).unwrap(); + assert_eq!((r["id"].as_str(), r["saved"].as_str()), (Some("osm"), Some("esri-imagery"))); + assert!(r["notice"].as_str().unwrap().contains("OpenStreetMap")); + assert_eq!(s.map_tiles().unwrap().source(), &crate::map::TileSource::Osm, "Esri tiles are never fetched"); +} + +#[test] +fn changing_the_source_restarts_the_service() { + let mut s = Session::new(); + assert!(s.map.service().is_none(), "nothing starts until a map asks"); + assert_eq!(s.map_tiles().unwrap().source().id(), "osm"); + s.execute("map.tileSource", &json!({"id": "opentopomap"})).unwrap(); + assert!(s.map.service().is_none()); + assert_eq!(s.map_tiles().unwrap().source().id(), "opentopomap"); +} + +#[test] +fn cache_info_and_clear() { + let mut s = Session::new(); + let r = s.execute("map.cacheInfo", &json!({})).unwrap(); + assert_eq!((r["bytes"].as_u64(), r["tiles"].as_u64(), r["dir"].is_null()), (Some(0), Some(0), true)); + assert_eq!(s.execute("map.clearCache", &json!({})).unwrap()["tiles"], 0); + let root = std::env::temp_dir().join(format!("lightcraft-engine-map-cache-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + s.map.cache_root = Some(root.clone()); + let c = crate::map::TileCache::new(&root, "osm", 1 << 30).unwrap(); + for x in 0..3 { + c.write(crate::map::TileKey::new(4, x, 1).unwrap(), &Default::default(), b"tile bytes").unwrap(); + } + let r = s.execute("map.cacheInfo", &json!({})).unwrap(); + assert_eq!(r["tiles"], 3); + assert!(r["bytes"].as_u64().unwrap() > 30); + assert_eq!(r["dir"], root.to_string_lossy().as_ref()); + let r = s.execute("map.clearCache", &json!({})).unwrap(); + assert_eq!(r["tiles"], 3); + assert_eq!(s.execute("map.cacheInfo", &json!({})).unwrap()["tiles"], 0); + let _ = std::fs::remove_dir_all(&root); } #[test] @@ -114,13 +219,76 @@ fn test_map_filter_photos() { assert!(untagged_photos.iter().any(|p| p.get("id").and_then(|v| v.as_u64()) == Some(ids[1].0))); } +fn temp_lib(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("lightcraft-map-prefs-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// The tile source is a library preference; a stored one is checked again when read. #[test] -fn test_tile_fetch_and_decode() { - let esri_url = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/6/25/31"; - if let Ok(b) = crate::map::fetch_tile_bytes(esri_url) { - assert!(!b.is_empty()); - let decoded = crate::map::decode_tile(&b).unwrap(); - assert_eq!(decoded.width, 256); - assert_eq!(decoded.height, 256); +fn the_map_tile_source_persists_and_is_rechecked() { + let lib = temp_lib("persist"); + { + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.map.source().id(), "osm"); + s.execute( + "map.tileSource", + &json!({"urlTemplate": "https://tiles.example.org/{z}/{x}/{y}.png", "attribution": "© Example", "maxZoom": 16, "id": "example"}), + ) + .unwrap(); } + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let src = s.map.source().clone(); + assert_eq!((src.id(), src.max_zoom(), src.attribution()), ("example", 16, "© Example")); + s.execute("map.tileSource", &json!({"offline": true})).unwrap(); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert!(s.map.source().is_offline()); + drop(s); + // a hand-edited prefs.json pointing at plain http falls back to OpenStreetMap + let mut prefs: serde_json::Value = serde_json::from_slice(&std::fs::read(lib.join("prefs.json")).unwrap()).unwrap(); + prefs["mapSource"] = json!({"kind": "custom", "id": "evil", "urlTemplate": "http://evil.example/{z}/{x}/{y}", "attribution": "x", "maxZoom": 19}); + std::fs::write(lib.join("prefs.json"), serde_json::to_vec(&prefs).unwrap()).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(*s.map.source(), crate::map::TileSource::Osm); + drop(s); + let _ = std::fs::remove_dir_all(&lib); +} + +/// A library saved with an Esri layer (by an older build) opens on OpenStreetMap with a one-line +/// notice, and prefs.json keeps the Esri choice. +#[test] +fn a_saved_esri_source_falls_back_with_a_notice_and_is_kept() { + let lib = temp_lib("esri"); + std::fs::write(lib.join("prefs.json"), br#"{"cacheMb": 321, "mapSource": {"kind": "esriImagery"}}"#).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.cache_mb, 321); + assert_eq!(s.map.effective_source(), crate::map::TileSource::Osm); + let warnings = s.take_library_warnings(); + assert_eq!(warnings.iter().filter(|w| w.contains("OpenStreetMap") && w.contains("Esri")).count(), 1, "{warnings:?}"); + // saving other preferences keeps the Esri choice in the file + s.save_prefs().unwrap(); + let prefs: serde_json::Value = serde_json::from_slice(&std::fs::read(lib.join("prefs.json")).unwrap()).unwrap(); + assert_eq!(prefs["mapSource"], json!({"kind": "esriImagery"})); + drop(s); + let _ = std::fs::remove_dir_all(&lib); +} + +#[test] +fn a_damaged_saved_tile_source_keeps_the_other_preferences() { + let lib = temp_lib("damaged"); + std::fs::write(lib.join("prefs.json"), br#"{"cacheMb": 777, "mapSource": {"kind": "custom", "urlTemplate": 5, "maxZoom": "high"}}"#).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.cache_mb, 777, "the rest of prefs.json is read"); + assert_eq!(s.map.source().id(), "osm", "the damaged source falls back to OpenStreetMap"); + drop(s); + let _ = std::fs::remove_dir_all(&lib); } diff --git a/crates/fetch/src/http.rs b/crates/fetch/src/http.rs index f5ae5e410a..9c69cb5234 100644 --- a/crates/fetch/src/http.rs +++ b/crates/fetch/src/http.rs @@ -551,14 +551,15 @@ impl Response { } } -/// Send `GET url` with extra `headers` and read the status line and headers. +/// Send `GET url` with extra `headers` and read the status line and headers. A `User-Agent` among +/// `headers` replaces the default `LightCraft/` (it is sent once either way: the OSM tile +/// policy asks for one distinct User-Agent). pub fn get(url: &Url, headers: &[(&str, String)], limits: &Limits) -> Result { - let mut req = format!( - "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: LightCraft/{}\r\nAccept: */*\r\nAccept-Encoding: identity\r\nConnection: close\r\n", - url.path, - url.host_header(), - env!("CARGO_PKG_VERSION") - ); + let mut req = format!("GET {} HTTP/1.1\r\nHost: {}\r\n", url.path, url.host_header()); + if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("user-agent")) { + req.push_str(&format!("User-Agent: LightCraft/{}\r\n", env!("CARGO_PKG_VERSION"))); + } + req.push_str("Accept: */*\r\nAccept-Encoding: identity\r\nConnection: close\r\n"); for (k, v) in headers { if v.chars().any(|c| c == '\r' || c == '\n') || k.chars().any(|c| c == '\r' || c == '\n' || c == ':') { return Err(HttpError::BadUrl("header with a line break".into())); diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index d144e08d29..91c3808695 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -432,3 +432,36 @@ fn names_differing_only_in_case_are_one_file() { assert!(super::validate_files(&[spec("Model.bin")]).is_ok()); assert!(super::validate_files(&[spec("Model.bin"), spec("model.BIN")]).is_err()); } + +/// A caller's `User-Agent` replaces the default one instead of adding a second header. +#[test] +fn a_callers_user_agent_replaces_the_default() { + fn user_agents(headers: &[(&str, String)]) -> Vec { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = crate::http::Url::parse(&format!("http://{}/t", listener.local_addr().unwrap())).unwrap(); + let worker = std::thread::spawn(move || { + let (mut socket, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(socket.try_clone().unwrap()); + let mut agents = Vec::new(); + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap() == 0 || line.trim().is_empty() { + break; + } + if let Some((k, v)) = line.split_once(':') + && k.eq_ignore_ascii_case("user-agent") + { + agents.push(v.trim().to_string()); + } + } + socket.write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n").unwrap(); + agents + }); + let cancel = AtomicBool::new(false); + let limits = crate::http::Limits { connect: Duration::from_secs(5), stall: Duration::from_secs(5), cancel: &cancel }; + assert_eq!(crate::http::get(&url, headers, &limits).unwrap().status, 204); + worker.join().unwrap() + } + assert_eq!(user_agents(&[]), vec![format!("LightCraft/{}", env!("CARGO_PKG_VERSION"))]); + assert_eq!(user_agents(&[("User-Agent", "LightCraft/1 (+https://example.org)".into())]), vec!["LightCraft/1 (+https://example.org)"]); +} diff --git a/crates/geom/src/geo.rs b/crates/geom/src/geo.rs index 5d3ee5d1f9..37ce695e71 100644 --- a/crates/geom/src/geo.rs +++ b/crates/geom/src/geo.rs @@ -20,10 +20,21 @@ pub struct LatLon { } impl LatLon { - /// Create a new `LatLon` if coordinates are finite numbers. - /// Values outside valid ranges `[-90, 90]` or `[-180, 180]` are clamped. + /// The point, or `None` for NaN, infinities or values out of range: latitude in `[-90, 90]`, + /// longitude in `[-180, 180]`. Never clamped: a latitude of 95° is a broken record, not the + /// North Pole. A longitude of exactly 180 is kept as given (it is the same meridian as -180). 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 } + let ok = lat.is_finite() && lon.is_finite() && (-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon); + ok.then_some(Self { lat, lon }) + } + + /// The point with its longitude wrapped into `[-180, 180)`: `None` for NaN, infinities or a + /// latitude out of `[-90, 90]` (commands that accept any longitude, such as `photo.setGps`). + pub fn wrapped(lat: f64, lon: f64) -> Option { + if !lon.is_finite() { + return None; + } + Self::new(lat, Self::normalize_lon(lon)) } /// Normalizes longitude to `[-180.0, 180.0)`. @@ -151,16 +162,22 @@ 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); - } - + fn out_of_range_positions_are_rejected_not_clamped() { + // a latitude of 100° used to become the North Pole, so commands that validate with + // `LatLon::new` accepted it + assert_eq!(LatLon::new(100.0, 10.0), None); + assert_eq!(LatLon::new(-90.5, 10.0), None); + assert_eq!(LatLon::new(10.0, 190.0), None); + assert_eq!(LatLon::new(10.0, -180.1), None); assert!(LatLon::new(f64::NAN, 0.0).is_none()); assert!(LatLon::new(0.0, f64::INFINITY).is_none()); + assert_eq!(LatLon::new(90.0, 180.0), Some(LatLon { lat: 90.0, lon: 180.0 })); + assert_eq!(LatLon::new(-90.0, -180.0), Some(LatLon { lat: -90.0, lon: -180.0 })); + // wrapped: any finite longitude, latitude still checked + assert_eq!(LatLon::wrapped(10.0, 190.0), Some(LatLon { lat: 10.0, lon: -170.0 })); + assert_eq!(LatLon::wrapped(10.0, -540.0), Some(LatLon { lat: 10.0, lon: -180.0 })); + assert_eq!(LatLon::wrapped(91.0, 0.0), None); + assert_eq!(LatLon::wrapped(0.0, f64::NAN), None); } #[test] diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 11de914173..b7aacc1174 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -30,8 +30,13 @@ impl Drop for Headless { impl Default for Headless { fn default() -> Self { // the lens database the desktop app downloaded, when it is there (a headless session never fetches it) - let session = - Session::new().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models().with_default_lens_database(); + let session = Session::new() + .with_fs() + .with_default_denoise_models() + .with_default_map_cache() + .with_system_clock() + .with_default_face_models() + .with_default_lens_database(); Self::new(session.with_default_sam3_model().with_default_slide_templates()) } } @@ -43,7 +48,8 @@ impl Headless { /// A headless session with the procedurally generated demo library. pub fn demo() -> Self { - let session = Session::with_demo().with_fs().with_default_denoise_models().with_system_clock().with_default_face_models(); + let session = + Session::with_demo().with_fs().with_default_denoise_models().with_default_map_cache().with_system_clock().with_default_face_models(); Self::new(session.with_default_sam3_model().with_default_slide_templates()) } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 69c06c5b32..cd54246dfa 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2523,5 +2523,8 @@ "Location Filter Bar": "Lišta filtru polohy", "Map Legend": "Legenda mapy", "Lock Map Markers": "Uzamknout značky na mapě", - "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", + "Map tiles are off": "Mapové dlaždice jsou vypnuté", + "Offline (no tiles)": "Offline (bez dlaždic)", + "Custom tile server": "Vlastní server dlaždic" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 6637f4d82d..53af38378a 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3558,5 +3558,8 @@ "Location Filter Bar": "Ortsfilterleiste", "Map Legend": "Kartenlegende", "Lock Map Markers": "Kartenmarkierungen sperren", - "Map (Ctrl+Alt+3)": "Karte (Strg+Alt+3)" + "Map (Ctrl+Alt+3)": "Karte (Strg+Alt+3)", + "Map tiles are off": "Kartenkacheln sind aus", + "Offline (no tiles)": "Offline (keine Kacheln)", + "Custom tile server": "Eigener Kachelserver" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index f51275b4ad..5eb77a2645 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2477,5 +2477,8 @@ "Location Filter Bar": "Barra de filtro de ubicación", "Map Legend": "Leyenda del mapa", "Lock Map Markers": "Bloquear marcadores del mapa", - "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", + "Map tiles are off": "Las teselas del mapa están desactivadas", + "Offline (no tiles)": "Sin conexión (sin teselas)", + "Custom tile server": "Servidor de teselas personalizado" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index a162965ad6..7c58d5b1ca 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2434,5 +2434,8 @@ "Location Filter Bar": "Sijaintisuodatinpalkki", "Map Legend": "Kartan selite", "Lock Map Markers": "Lukitse karttamerkit", - "Map (Ctrl+Alt+3)": "Kartta (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Kartta (Ctrl+Alt+3)", + "Map tiles are off": "Karttaruudut ovat pois päältä", + "Offline (no tiles)": "Offline (ei ruutuja)", + "Custom tile server": "Oma ruutupalvelin" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index fd34721fa9..c9cdb5b6b9 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3660,5 +3660,8 @@ "Location Filter Bar": "Barre de filtre de lieu", "Map Legend": "Légende de la carte", "Lock Map Markers": "Verrouiller les repères de la carte", - "Map (Ctrl+Alt+3)": "Carte (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Carte (Ctrl+Alt+3)", + "Map tiles are off": "Les tuiles de la carte sont désactivées", + "Offline (no tiles)": "Hors ligne (sans tuiles)", + "Custom tile server": "Serveur de tuiles personnalisé" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 1b77209a32..0227d022ae 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2448,5 +2448,8 @@ "Location Filter Bar": "Bilah filter lokasi", "Map Legend": "Legenda peta", "Lock Map Markers": "Kunci penanda peta", - "Map (Ctrl+Alt+3)": "Peta (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Peta (Ctrl+Alt+3)", + "Map tiles are off": "Petak peta nonaktif", + "Offline (no tiles)": "Luring (tanpa petak)", + "Custom tile server": "Server petak khusus" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 7e24addbd3..7f8c35d975 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2641,5 +2641,8 @@ "Location Filter Bar": "Barra filtro posizione", "Map Legend": "Legenda della mappa", "Lock Map Markers": "Blocca indicatori della mappa", - "Map (Ctrl+Alt+3)": "Mappa (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Mappa (Ctrl+Alt+3)", + "Map tiles are off": "Le tessere della mappa sono disattivate", + "Offline (no tiles)": "Offline (nessuna tessera)", + "Custom tile server": "Server di tessere personalizzato" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 95415fd686..d159e819cd 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2475,5 +2475,8 @@ "Location Filter Bar": "場所フィルターバー", "Map Legend": "地図の凡例", "Lock Map Markers": "地図マーカーをロック", - "Map (Ctrl+Alt+3)": "地図(Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "地図(Ctrl+Alt+3)", + "Map tiles are off": "地図タイルはオフです", + "Offline (no tiles)": "オフライン(タイルなし)", + "Custom tile server": "カスタムタイルサーバー" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index e6cab61533..3d71f6148a 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3743,5 +3743,8 @@ "Location Filter Bar": "მდებარეობის ფილტრის ზოლი", "Map Legend": "რუკის ლეგენდა", "Lock Map Markers": "რუკის მარკერების ჩაკეტვა", - "Map (Ctrl+Alt+3)": "რუკა (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "რუკა (Ctrl+Alt+3)", + "Map tiles are off": "რუკის ფილები გამორთულია", + "Offline (no tiles)": "ოფლაინ (ფილების გარეშე)", + "Custom tile server": "საკუთარი ფილების სერვერი" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 0f13f43c00..3231878209 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2400,5 +2400,8 @@ "Location Filter Bar": "Pasek filtru lokalizacji", "Map Legend": "Legenda mapy", "Lock Map Markers": "Zablokuj znaczniki mapy", - "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", + "Map tiles are off": "Kafelki mapy są wyłączone", + "Offline (no tiles)": "Offline (bez kafelków)", + "Custom tile server": "Własny serwer kafelków" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 9a4950dff7..00c3f49350 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2321,5 +2321,8 @@ "Location Filter Bar": "Barra de filtro de local", "Map Legend": "Legenda do mapa", "Lock Map Markers": "Travar marcadores do mapa", - "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", + "Map tiles are off": "Os blocos do mapa estão desativados", + "Offline (no tiles)": "Offline (sem blocos)", + "Custom tile server": "Servidor de blocos personalizado" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index d391dfeaa9..a842adb6ac 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2683,5 +2683,8 @@ "Location Filter Bar": "Панель фильтра по месту", "Map Legend": "Легенда карты", "Lock Map Markers": "Заблокировать метки на карте", - "Map (Ctrl+Alt+3)": "Карта (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Карта (Ctrl+Alt+3)", + "Map tiles are off": "Тайлы карты отключены", + "Offline (no tiles)": "Офлайн (без тайлов)", + "Custom tile server": "Свой сервер тайлов" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index b3f740bcd9..c3592d356e 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2538,5 +2538,8 @@ "Location Filter Bar": "Platsfilterfält", "Map Legend": "Kartförklaring", "Lock Map Markers": "Lås kartmarkörer", - "Map (Ctrl+Alt+3)": "Karta (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Karta (Ctrl+Alt+3)", + "Map tiles are off": "Kartrutor är avstängda", + "Offline (no tiles)": "Offline (inga rutor)", + "Custom tile server": "Egen rutserver" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index cf05530599..20cfbcce6d 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2473,5 +2473,8 @@ "Location Filter Bar": "Панель фільтра за місцем", "Map Legend": "Легенда мапи", "Lock Map Markers": "Заблокувати мітки на мапі", - "Map (Ctrl+Alt+3)": "Мапа (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Мапа (Ctrl+Alt+3)", + "Map tiles are off": "Тайли мапи вимкнено", + "Offline (no tiles)": "Офлайн (без тайлів)", + "Custom tile server": "Власний сервер тайлів" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 5bfa060898..0e9051fd31 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2762,5 +2762,8 @@ "Location Filter Bar": "Thanh lọc vị trí", "Map Legend": "Chú giải bản đồ", "Lock Map Markers": "Khóa điểm đánh dấu trên bản đồ", - "Map (Ctrl+Alt+3)": "Bản đồ (Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "Bản đồ (Ctrl+Alt+3)", + "Map tiles are off": "Ô bản đồ đang tắt", + "Offline (no tiles)": "Ngoại tuyến (không có ô)", + "Custom tile server": "Máy chủ ô tùy chỉnh" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 90e2bd6353..779e9254af 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2476,5 +2476,8 @@ "Location Filter Bar": "位置过滤器栏", "Map Legend": "地图图例", "Lock Map Markers": "锁定地图标记", - "Map (Ctrl+Alt+3)": "地图(Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "地图(Ctrl+Alt+3)", + "Map tiles are off": "地图图块已关闭", + "Offline (no tiles)": "离线(无图块)", + "Custom tile server": "自定义图块服务器" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 756dca12d3..82513682cb 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2477,5 +2477,8 @@ "Location Filter Bar": "位置篩選列", "Map Legend": "地圖圖例", "Lock Map Markers": "鎖定地圖標記", - "Map (Ctrl+Alt+3)": "地圖(Ctrl+Alt+3)" + "Map (Ctrl+Alt+3)": "地圖(Ctrl+Alt+3)", + "Map tiles are off": "地圖圖磚已關閉", + "Offline (no tiles)": "離線(無圖磚)", + "Custom tile server": "自訂圖磚伺服器" } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index c18baff9bc..f0735fcd88 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -444,6 +444,8 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { crate::state::ViewMode::Map => crate::panels::map::show(app, ui), }); } + // no map drawn for two frames: the tile service stops fetching (only what is in view) + crate::panels::map::tiles::end_frame(&app.session, ui.ctx()); let rendered = workspace; let mut workspace = app.ui.docking.clone().unwrap_or_else(|| from_ui(app)); diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index fddacb44ed..316daa5a15 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -1,17 +1,13 @@ -//! Map module view: interactive slippy map canvas, dual-provider tile engine (OSM & Esri), -//! photo marker clustering, loupe popover, GPX tracklog overlay, and saved locations. +//! Map module view: interactive slippy map canvas, photo marker clustering, loupe popover and +//! saved locations. Tiles come from the engine's tile service (OpenStreetMap by default, under its +//! tile usage policy) and are drawn by [`tiles`]. -use std::collections::{HashMap, HashSet}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::mpsc::{Receiver, Sender, channel}; -use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, Weak}; -use std::time::Duration; -use web_time::Instant; +pub mod tiles; -use egui::{Align2, Color32, ColorImage, FontId, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, TextureHandle, TextureOptions, pos2, vec2}; +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, TileCoord}; +use lightcraft_engine::map::LocationFilter; +use lightcraft_geom::{GeoBounds, LatLon}; use serde_json::json; use crate::LightcraftApp; @@ -24,205 +20,6 @@ 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; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -struct TileKey { - provider: MapProvider, - z: u8, - x: u32, - y: u32, - layer: u8, -} - -/// At most this many tiles download at once. One connection per visible tile (60 and more on a -/// large screen) left most of them stuck past the 6 s connect timeout; a small pool loads them all. -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] // the web has no tile fetcher (see `fetch_and_cache_tile`) -const MAX_TILE_WORKERS: usize = 6; - -/// A tile whose load failed is asked for again after this long, not on every frame. -const TILE_RETRY_AFTER: Duration = Duration::from_secs(5); - -/// A finished tile load: the image, or `None` when it could not be fetched or decoded. -type TileResult = (TileKey, Option); - -struct TileStore { - textures: HashMap, - pending: HashSet, - /// Tiles whose last load failed, and when; they are retried after [`TILE_RETRY_AFTER`]. - failed: HashMap, - tx: Sender, - rx: Receiver, - /// The tile loads in flight, while there are any. Only the queued jobs hold it strongly. - batch: Weak, -} - -impl TileStore { - fn new() -> Self { - let (tx, rx) = channel(); - Self { textures: HashMap::new(), pending: HashSet::new(), failed: HashMap::new(), tx, rx, batch: Weak::new() } - } - - /// Whether `key` should be requested now: not loaded, not in flight, and not failed recently. - fn wants(&self, key: &TileKey, now: Instant) -> bool { - !self.textures.contains_key(key) - && !self.pending.contains(key) - && self.failed.get(key).is_none_or(|at| now.saturating_duration_since(*at) >= TILE_RETRY_AFTER) - } - - /// Takes in a finished load: a failed one leaves `pending` so it can be retried later. - fn finish(&mut self, key: TileKey, ok: bool, now: Instant) { - self.pending.remove(&key); - if ok { - self.failed.remove(&key); - } else { - if self.failed.len() > 1000 { - self.failed.retain(|_, at| now.saturating_duration_since(*at) < TILE_RETRY_AFTER); - } - self.failed.insert(key, now); - } - } -} - -/// One tile to load. Dropping it (done or never run) counts it as done in the batch's row. -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -struct TileJob { - key: TileKey, - url: String, - disk_path: std::path::PathBuf, - tx: Sender, - ctx: egui::Context, - /// The tile failed before: it waits behind every tile not yet tried (see [`TileQueue::push`]). - retry: bool, - _counted: TileLoadEnd, -} - -/// A bounded set of worker threads that load tiles, newest first-attempt request first, so the -/// tiles on screen now come before ones the view has already panned past; retries come last. -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -struct TilePool { - queue: Mutex, - wake: Condvar, - load: fn(&TileJob) -> Option, - max_workers: usize, -} - -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -struct TileQueue { - /// Popped from the end: first attempts are pushed there (newest first), retries go to the - /// front, so a tile that keeps failing cannot starve tiles that have never been tried. - jobs: Vec, - workers: usize, -} - -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -impl TileQueue { - /// Queues `job`: a first attempt is taken before every queued job, a retry after all of them. - fn push(&mut self, job: TileJob) { - if job.retry { - self.jobs.insert(0, job); - } else { - self.jobs.push(job); - } - } -} - -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -impl TilePool { - fn new(load: fn(&TileJob) -> Option, max_workers: usize) -> Arc { - Arc::new(Self { queue: Mutex::new(TileQueue { jobs: Vec::new(), workers: 0 }), wake: Condvar::new(), load, max_workers }) - } - - fn submit(self: &Arc, job: TileJob) { - let mut q = self.queue.lock().unwrap_or_else(PoisonError::into_inner); - q.push(job); - if q.workers < self.max_workers { - let pool = Arc::clone(self); - let spawned = std::thread::Builder::new().name("lc-tile-fetch".into()).spawn(move || pool.work()).is_ok(); - if spawned { - q.workers += 1; - } else if q.workers == 0 { - // no worker to run it: report the jobs as failed so they are retried, not stuck - for job in q.jobs.drain(..) { - let _ = job.tx.send((job.key, None)); - } - } - } - drop(q); - self.wake.notify_one(); - } - - /// Runs jobs until none has come for a while, then ends the thread. - fn work(&self) { - loop { - let mut q = self.queue.lock().unwrap_or_else(PoisonError::into_inner); - let job = loop { - if let Some(job) = q.jobs.pop() { - break job; - } - let (guard, timeout) = self.wake.wait_timeout(q, Duration::from_secs(20)).unwrap_or_else(PoisonError::into_inner); - q = guard; - if timeout.timed_out() && q.jobs.is_empty() { - q.workers = q.workers.saturating_sub(1); - return; - } - }; - drop(q); - let img = (self.load)(&job); - let _ = job.tx.send((job.key, img)); - job.ctx.request_repaint(); - } - } -} - -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -static TILE_POOL: OnceLock> = OnceLock::new(); - -/// The tile loads in flight share one activity row. Each worker holds an `Arc` until it ends, so -/// the last one to finish (fetched, failed or not started) drops the row, whether or not the Map -/// view is still drawn. -struct TileBatch { - guard: lightcraft_engine::activity::TaskGuard, - done: AtomicU64, - total: AtomicU64, -} - -impl TileBatch { - fn progress(&self) { - self.guard.progress(self.done.load(Ordering::Relaxed), self.total.load(Ordering::Relaxed)); - } - - fn finish(&self) { - self.done.fetch_add(1, Ordering::Relaxed); - self.progress(); - } -} - -/// Held by a tile worker: counts its load as done when the worker ends, then lets go of the batch. -struct TileLoadEnd(Arc); - -impl Drop for TileLoadEnd { - fn drop(&mut self) { - self.0.finish(); - } -} - -/// Counts one more tile load into the batch in flight, starting a batch (and its row) if none is. -fn join_tile_batch(slot: &mut Weak, activity: &lightcraft_engine::activity::Activity) -> Arc { - let batch = slot.upgrade().unwrap_or_else(|| { - let batch = Arc::new(TileBatch { - guard: activity.start("download", "Loading map tiles", lightcraft_engine::activity::Cancel::No), - done: AtomicU64::new(0), - total: AtomicU64::new(0), - }); - *slot = Arc::downgrade(&batch); - batch - }); - batch.total.fetch_add(1, Ordering::Relaxed); - batch.progress(); - batch -} - -static TILES: Mutex> = Mutex::new(None); - /// Represents a clustered group of photos on the map screen. struct MapCluster { center: Pos2, @@ -240,7 +37,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { 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 source = app.session.map.effective_source(); + let max_zoom = f64::from(source.max_zoom()); + let mut zoom = map_ui.zoom.clamp(1.0, max_zoom); 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); @@ -249,13 +48,6 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { 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); - let screen_center = canvas_rect.center(); let lat_lon_to_screen = |coord: LatLon, cur_zoom: f64, cur_center: LatLon| -> Pos2 { @@ -297,8 +89,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { }; if delta_zoom != 0.0 { - let max_z = map_ui.provider.max_zoom() as f64; - let new_zoom = (zoom + delta_zoom).clamp(1.0, max_z); + let new_zoom = (zoom + delta_zoom).clamp(1.0, max_zoom); if let Some(pointer_pos) = ui.input(|i| i.pointer.hover_pos()).filter(|&pos| canvas_rect.contains(pos)) { let mouse_geo = screen_to_lat_lon(pointer_pos, zoom, center); let (m_tx, m_ty) = mouse_geo.to_tile_coords(new_zoom); @@ -311,8 +102,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } - // Draw Map Grid / Tile outlines - render_tile_grid(&painter, &app.session.activity, canvas_rect, screen_center, center, zoom, map_ui.provider); + // Tiles (the service is asked for the view plus one ring) + tiles::draw(&mut app.session, &painter, canvas_rect, center, zoom, 1); // 2. Fetch and Cluster Candidate Photos let candidate_photos = collect_photos(app, map_ui.filter, |p| screen_to_lat_lon(p, zoom, center), canvas_rect); @@ -345,7 +136,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { 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); + let next_z = (zoom + 2.0).min(max_zoom); zoom_target = Some((cluster.lat_lon, next_z)); } } @@ -417,150 +208,6 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.map = map_ui; } -/// Queues a tile load on the shared pool. On the web there is no fetcher, so the job is dropped. -fn fetch_and_cache_tile(job: TileJob) { - #[cfg(not(target_arch = "wasm32"))] - TILE_POOL.get_or_init(|| TilePool::new(load_tile, MAX_TILE_WORKERS)).submit(job); - #[cfg(target_arch = "wasm32")] - drop(job); -} - -/// Reads a tile from the disk cache, or downloads it and caches it, then decodes it. -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -fn load_tile(job: &TileJob) -> Option { - if let Ok(cached) = std::fs::read(&job.disk_path) { - if let Some(img) = decode_image(&cached) { - return Some(img); - } - // a cached file that does not decode (truncated, or from a bad response) is replaced, not retried forever - let _ = std::fs::remove_file(&job.disk_path); - } - let bytes = match lightcraft_engine::map::fetch_tile_bytes(&job.url) { - Ok(b) => b, - Err(e) => { - log::debug!("tile fetch error for {}: {e}", job.url); - return None; - } - }; - // decode before caching, so a bad response is never written to the cache - let img = decode_image(&bytes)?; - if let Some(parent) = job.disk_path.parent() { - let _ = std::fs::create_dir_all(parent); - } - let _ = std::fs::write(&job.disk_path, &bytes); - Some(img) -} - -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -fn decode_image(bytes: &[u8]) -> Option { - let rgba = lightcraft_engine::map::decode_tile(bytes).ok()?; - Some(ColorImage::from_rgba_unmultiplied([rgba.width, rgba.height], &rgba.as_bytes())) -} - -fn render_tile_grid( - p: &Painter, - activity: &lightcraft_engine::activity::Activity, - canvas: Rect, - center_pos: Pos2, - center: LatLon, - zoom: f64, - provider: MapProvider, -) { - let int_zoom = (zoom.floor() as u8).min(provider.max_zoom()); - let scale = 2.0_f64.powf(zoom - int_zoom as f64); - let tile_screen_size = (TILE_SIZE as f64 * scale) as f32; - let (center_int_tx, center_int_ty) = center.to_tile_coords(int_zoom as f64); - let n = 2.0_f64.powi(int_zoom as i32); - - let min_x = ((center_int_tx - (center_pos.x - canvas.left()) as f64 / tile_screen_size as f64).floor() as i64).max(0); - let max_x = ((center_int_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_int_ty - (center_pos.y - canvas.top()) as f64 / tile_screen_size as f64).floor() as i64).max(0); - let max_y = ((center_int_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), - }; - - let mut store_guard = TILES.lock().unwrap_or_else(PoisonError::into_inner); - let store = store_guard.get_or_insert_with(TileStore::new); - - let now = Instant::now(); - while let Ok((key, img)) = store.rx.try_recv() { - let ok = img.is_some(); - if let Some(img) = img { - let name = format!("tile-{}-{}-{}-{}-{}", key.provider.id(), key.layer, key.z, key.x, key.y); - let tex = p.ctx().load_texture(name, img, TextureOptions::LINEAR); - store.textures.insert(key, tex); - } else { - // draw again once the failed tile may be retried, even if nothing else moves - p.ctx().request_repaint_after(TILE_RETRY_AFTER); - } - store.finish(key, ok, now); - } - - if store.textures.len() > 300 { - store.textures.retain(|k, _| k.provider == provider && (k.z as i32 - int_zoom as i32).abs() <= 1); - } - - let cache_root = lightcraft_engine::map::tile_cache_dir(); - - for x in min_x..=max_x { - for y in min_y..=max_y { - let left = center_pos.x + ((x as f64 - center_int_tx) * tile_screen_size as f64) as f32; - let top = center_pos.y + ((y as f64 - center_int_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)); - - let coord = TileCoord::new(int_zoom, x as u32, y as u32); - let urls = provider.tile_urls(coord); - let mut all_loaded = true; - - for (layer_idx, url) in urls.into_iter().enumerate() { - let key = TileKey { provider, z: int_zoom, x: x as u32, y: y as u32, layer: layer_idx as u8 }; - - if let Some(tex) = store.textures.get(&key) { - p.image(tex.id(), tile_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } else { - all_loaded = false; - if store.wants(&key, now) { - store.pending.insert(key); - let disk_path = lightcraft_engine::map::tile_cache_path(&cache_root, provider, coord, layer_idx); - let batch = join_tile_batch(&mut store.batch, activity); - fetch_and_cache_tile(TileJob { - key, - url, - disk_path, - tx: store.tx.clone(), - ctx: p.ctx().clone(), - retry: store.failed.contains_key(&key), - _counted: TileLoadEnd(batch), - }); - } else if let Some(failed_at) = store.failed.get(&key).filter(|_| !store.pending.contains(&key)) { - // keep the retry wake-up alive while cooling down; a retry already in flight needs no wake-up - p.ctx().request_repaint_after(TILE_RETRY_AFTER.saturating_sub(now.saturating_duration_since(*failed_at))); - } - } - } - - if !all_loaded { - 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, @@ -699,7 +346,7 @@ fn render_top_filter_bar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re }); } -fn render_bottom_toolbar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, map_ui: &mut crate::state::MapUi, zoom: &mut f64) { +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); @@ -712,21 +359,30 @@ fn render_bottom_toolbar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re ui.add_space(12.0); ui.label(egui::RichText::new(crate::i18n::tr("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; + let current = app.session.map.effective_source(); + let max_zoom = f64::from(current.max_zoom()); + let mut chosen = None; + crate::widgets::combo_box("map_style_combo").selected_text(crate::i18n::tr(current.label())).show_ui(ui, |ui| { + // only the sources usable now: the Esri layers are not offered (docs/map.md) + for p in app.session.map.offered() { + if ui.selectable_label(p == current, crate::i18n::tr(p.label())).clicked() { + chosen = Some(p.id().to_string()); } } }); + if let Some(id) = chosen + && let Err(e) = app.run("map.tileSource", json!({"id": id})) + { + app.ui.toast = Some((e, app.tick_now() + 6.0, None)); + } 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)); + ui.add(egui::Slider::new(zoom, 1.0..=max_zoom).show_value(false)); if ui.button("+").clicked() { - *zoom = (*zoom + 1.0).min(map_ui.provider.max_zoom() as f64); + *zoom = (*zoom + 1.0).min(max_zoom); } ui.add_space(12.0); @@ -735,9 +391,11 @@ fn render_bottom_toolbar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Re map_ui.locked = !map_ui.locked; } + // the tile provider's credit, always visible at the bottom right (tile licences require it) 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))); + let credit = ui.label(egui::RichText::new(current.attribution()).small().color(Color32::from_white_alpha(170))); + crate::widgets::register(ui, "map:attribution", credit.rect); }); }); } @@ -855,7 +513,8 @@ fn render_left_navigator( let mini_rect = Rect::from_min_size(pos2(left_rect.left() + 8.0, ui.cursor().top()), vec2(mini_w, nav_h)); let nav_resp = ui.allocate_rect(mini_rect, Sense::click_and_drag()); - let nav_zoom = map_ui.navigator_zoom.clamp(1.0, (map_ui.provider.max_zoom() - 2) as f64); + let nav_max = f64::from(app.session.map.effective_source().max_zoom().saturating_sub(2).max(1)); + let nav_zoom = map_ui.navigator_zoom.clamp(1.0, nav_max); if nav_resp.dragged() { let delta = nav_resp.drag_delta(); @@ -885,8 +544,7 @@ fn render_left_navigator( if nav_resp.hovered() { let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll.abs() > 0.5 { - let max_z = (map_ui.provider.max_zoom() - 2) as f64; - map_ui.navigator_zoom = (map_ui.navigator_zoom + (scroll as f64 * 0.005)).clamp(1.0, max_z); + map_ui.navigator_zoom = (map_ui.navigator_zoom + (scroll as f64 * 0.005)).clamp(1.0, nav_max); ui.ctx().request_repaint(); } } @@ -894,8 +552,8 @@ fn render_left_navigator( let nav_painter = ui.painter().with_clip_rect(mini_rect); nav_painter.rect_filled(mini_rect, 4.0, Color32::from_rgb(18, 22, 26)); - // Render overview map tiles - render_tile_grid(&nav_painter, &app.session.activity, mini_rect, mini_rect.center(), *center, nav_zoom, map_ui.provider); + // Render overview map tiles (only what it shows: no ring) + tiles::draw(&mut app.session, &nav_painter, mini_rect, *center, nav_zoom, 0); // Viewport rectangle showing the visible area on the main map let scale_diff = 2.0_f64.powf(nav_zoom - *zoom); @@ -1014,7 +672,7 @@ mod tests { }); assert_eq!(app.ui.view, ViewMode::Map); - assert_eq!(app.ui.map.provider, MapProvider::OpenStreetMap); + assert_eq!(app.session.map.effective_source(), lightcraft_engine::map::TileSource::Osm); } #[test] @@ -1098,139 +756,113 @@ mod tests { assert_eq!(app.ui.map.navigator_zoom, 3.0); } - #[test] - fn tile_loads_share_one_activity_row_that_goes_with_the_last_load() { - let activity = lightcraft_engine::activity::Activity::default(); - let mut slot = Weak::new(); - let first = TileLoadEnd(join_tile_batch(&mut slot, &activity)); - let second = TileLoadEnd(join_tile_batch(&mut slot, &activity)); - - let rows = activity.list(); - assert_eq!(rows.len(), 1, "every tile load in flight shares one row"); - assert_eq!((rows[0].kind, rows[0].label.as_str()), ("download", "Loading map tiles")); - assert_eq!((rows[0].done, rows[0].total), (0, 2)); - assert!(!rows[0].cancellable); - - drop(first); - assert_eq!((activity.list()[0].done, activity.list()[0].total), (1, 2), "a finished load counts"); - drop(second); - assert!(activity.list().is_empty(), "the row goes with the last load, drawn or not"); - - // a load after that starts a new row - let third = TileLoadEnd(join_tile_batch(&mut slot, &activity)); - assert_eq!(activity.list().len(), 1); - drop(third); - assert!(activity.list().is_empty()); + /// A transport that serves a flat 256 × 256 PNG for every tile and records the URLs (never + /// the internet). + struct FakeTiles { + urls: std::sync::Mutex>, + png: Vec, } - fn key(x: u32) -> TileKey { - TileKey { provider: MapProvider::OpenStreetMap, z: 10, x, y: 0, layer: 0 } - } - - /// Loads a 1x1 tile, or fails for odd `x`, while counting how many loads run at once. - fn counting_load(job: &TileJob) -> Option { - let now = RUNNING.fetch_add(1, Ordering::SeqCst) + 1; - PEAK.fetch_max(now, Ordering::SeqCst); - std::thread::sleep(Duration::from_millis(20)); - RUNNING.fetch_sub(1, Ordering::SeqCst); - job.key.x.is_multiple_of(2).then(|| ColorImage::new([1, 1], vec![Color32::WHITE])) - } - static RUNNING: AtomicU64 = AtomicU64::new(0); - static PEAK: AtomicU64 = AtomicU64::new(0); - - /// One connection per visible tile made most of them time out; the pool caps them, and - /// reports every job, failed ones included, so none stays pending. - #[test] - fn tile_pool_caps_concurrent_loads_and_reports_every_job() { - let activity = lightcraft_engine::activity::Activity::default(); - let mut slot = Weak::new(); - let pool = TilePool::new(counting_load, 3); - let (tx, rx) = channel(); - for x in 0..30 { - let job = TileJob { - key: key(x), - url: String::new(), - disk_path: std::path::PathBuf::new(), - tx: tx.clone(), - ctx: egui::Context::default(), - retry: false, - _counted: TileLoadEnd(join_tile_batch(&mut slot, &activity)), - }; - pool.submit(job); + impl lightcraft_engine::map::Transport for FakeTiles { + fn get( + &self, + url: &str, + _headers: &[(&'static str, String)], + _max: usize, + _cancel: &std::sync::atomic::AtomicBool, + ) -> Result { + self.urls.lock().unwrap().push(url.to_string()); + Ok(lightcraft_engine::map::HttpResponse { status: 200, headers: vec![], body: self.png.clone() }) } - let mut results: Vec = (0..30).map(|_| rx.recv_timeout(Duration::from_secs(10)).unwrap()).collect(); - results.sort_by_key(|(k, _)| k.x); - assert!(PEAK.load(Ordering::SeqCst) <= 3, "peak {}", PEAK.load(Ordering::SeqCst)); - assert!(results.iter().all(|(k, img)| img.is_some() == k.x.is_multiple_of(2)), "failures come back as None"); - // every job dropped: the row is gone - let deadline = Instant::now() + Duration::from_secs(5); - while !activity.list().is_empty() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); + } + + fn fake_tiles() -> std::sync::Arc { + use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png}; + let data: Vec = (0..256 * 256).flat_map(|_| [10u8, 120, 200, 255]).collect(); + let png = encode_png(&EncodeImage::new(256, 256, 4, Samples::U8(&data)), &EncodeMeta::default()).unwrap(); + std::sync::Arc::new(FakeTiles { urls: std::sync::Mutex::new(Vec::new()), png }) + } + + /// A session whose map uses `id` (a custom source, so tests don't share textures) served by + /// the fake transport. + fn session_with_fake_tiles(id: &str, fake: std::sync::Arc) -> lightcraft_engine::Session { + use lightcraft_engine::map::{TileService, TileSource}; + let mut session = lightcraft_engine::Session::new(); + let source = TileSource::custom(Some(id), "https://tiles.test/{z}/{x}/{y}.png", Some("© Test tiles"), Some(19)).unwrap(); + session + .execute( + "map.tileSource", + &json!({"id": id, "urlTemplate": "https://tiles.test/{z}/{x}/{y}.png", "attribution": "© Test tiles", "maxZoom": 19}), + ) + .unwrap(); + session.map.set_service(TileService::with_transport(source, None, Some(fake)).with_activity(Some(session.activity.clone()))); + session + } + + /// Draws `center` at `zoom` in a 512 × 512 map once and returns what was drawn. + fn draw_once(session: &mut lightcraft_engine::Session, center: LatLon, zoom: f64) -> tiles::Drawn { + let mut view = HeadlessView::new(); + let raw = HeadlessView::raw_input(vec2(600.0, 600.0), 1.0, 0.0, vec![]); + let mut drawn = tiles::Drawn::default(); + view.run(raw, |ui| { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(512.0, 512.0)); + drawn = tiles::draw(session, &ui.painter_at(rect), rect, center, zoom, 1); + }); + drawn + } + + fn wait_idle(session: &lightcraft_engine::Session) { + let end = std::time::Instant::now() + std::time::Duration::from_secs(20); + while !session.map.service().is_some_and(|s| s.is_idle()) { + assert!(std::time::Instant::now() < end, "the tile service never finished"); + std::thread::sleep(std::time::Duration::from_millis(5)); } - assert!(activity.list().is_empty()); } - /// Retries used to be queued newest-first like any request, so tiles that kept failing could - /// be taken again and again while visible tiles never got a first attempt. + /// Tiles come from the engine's tile service; one not loaded yet is drawn from a loaded + /// ancestor (scaled) instead of a blank square. #[test] - fn retries_wait_behind_tiles_never_tried() { - let activity = lightcraft_engine::activity::Activity::default(); - let mut slot = Weak::new(); - let (tx, _rx) = channel(); - let mut job = |x: u32, retry: bool| TileJob { - key: key(x), - url: String::new(), - disk_path: std::path::PathBuf::new(), - tx: tx.clone(), - ctx: egui::Context::default(), - retry, - _counted: TileLoadEnd(join_tile_batch(&mut slot, &activity)), - }; - let mut q = TileQueue { jobs: Vec::new(), workers: 0 }; - q.push(job(1, false)); - q.push(job(2, true)); - q.push(job(3, false)); - q.push(job(4, true)); - let order: Vec = std::iter::from_fn(|| q.jobs.pop()).map(|j| j.key.x).collect(); - assert_eq!(order, vec![3, 1, 2, 4], "first attempts newest first, then retries oldest first"); + fn tiles_are_drawn_from_the_service_and_missing_ones_from_an_ancestor() { + let fake = fake_tiles(); + let mut session = session_with_fake_tiles("ui-parent", fake.clone()); + let center = LatLon::new(48.8566, 2.3522).unwrap(); + let first = draw_once(&mut session, center, 10.0); + assert!(first.missing > 0 && first.tiles == 0, "{first:?}"); + wait_idle(&session); + let loaded = draw_once(&mut session, center, 10.0); + assert!(loaded.tiles > 0 && loaded.missing == 0, "{loaded:?}"); + // two zooms in: none of those tiles is loaded yet, but their zoom-10 ancestors are + let deeper = draw_once(&mut session, center, 12.0); + assert!(deeper.from_parent > 0 && deeper.tiles == 0, "{deeper:?}"); + assert!(fake.urls.lock().unwrap().iter().all(|u| u.starts_with("https://tiles.test/"))); } - /// A cached file that no longer decodes is deleted, so the next try downloads it again instead of - /// failing on the same bytes forever. No network: the URL is unusable on purpose. + /// The offline source draws a grey map and starts no tile service (no threads, no network). #[test] - fn an_undecodable_cached_tile_is_replaced_not_retried_forever() { - let dir = std::env::temp_dir().join(format!("lc-tile-test-{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let disk_path = dir.join("bad.png"); - std::fs::write(&disk_path, b"not a png").unwrap(); - let job = TileJob { - key: key(1), - url: String::new(), - disk_path: disk_path.clone(), - tx: channel().0, - ctx: egui::Context::default(), - retry: true, - _counted: TileLoadEnd(join_tile_batch(&mut Weak::new(), &lightcraft_engine::activity::Activity::default())), - }; - assert!(load_tile(&job).is_none()); - assert!(!disk_path.exists(), "the undecodable cache file is removed"); - let _ = std::fs::remove_dir_all(&dir); + fn the_offline_source_starts_no_tile_service() { + let mut session = lightcraft_engine::Session::new(); + session.execute("map.tileSource", &json!({"offline": true})).unwrap(); + let drawn = draw_once(&mut session, LatLon::new(0.0, 0.0).unwrap(), 3.0); + assert!(drawn.offline); + assert!(session.map.service().is_none()); + assert!(session.activity.list().is_empty()); } - /// A failed tile used to stay pending for good; now it is asked for again after a pause. + /// A session the host didn't put online never fetches: the Map view in tests (and any + /// session without `with_default_map_cache`) stays off the network. #[test] - fn a_failed_tile_is_retried_after_a_pause() { - let mut store = TileStore::new(); - let t0 = Instant::now(); - let k = key(1); - assert!(store.wants(&k, t0)); - store.pending.insert(k); - assert!(!store.wants(&k, t0), "in flight"); - store.finish(k, false, t0); - assert!(!store.pending.contains(&k)); - assert!(!store.wants(&k, t0 + Duration::from_secs(1)), "not on every frame"); - assert!(store.wants(&k, t0 + TILE_RETRY_AFTER), "retried after the pause"); - store.finish(k, true, t0 + TILE_RETRY_AFTER); - assert!(store.failed.is_empty()); + fn a_session_not_put_online_never_fetches() { + let mut session = lightcraft_engine::Session::new(); + let drawn = draw_once(&mut session, LatLon::new(51.5, -0.12).unwrap(), 6.0); + assert!(!drawn.offline && drawn.tiles == 0); + assert!(session.map.service().is_some_and(|s| s.is_idle() && s.stats().requests == 0)); + } + + /// The Esri layers are not in the Map Style list (their terms, docs/map.md). + #[test] + fn the_map_style_list_has_no_esri_layer() { + let session = lightcraft_engine::Session::new(); + let offered: Vec = session.map.offered().iter().map(|s| s.label().to_string()).collect(); + assert_eq!(offered, vec!["OpenStreetMap", "OpenTopoMap", "Offline (no tiles)"]); } } diff --git a/crates/ui-egui/src/panels/map/tiles.rs b/crates/ui-egui/src/panels/map/tiles.rs new file mode 100644 index 0000000000..2f0cbf1693 --- /dev/null +++ b/crates/ui-egui/src/panels/map/tiles.rs @@ -0,0 +1,246 @@ +//! Map tiles on screen: the textures of the tiles the engine's tile service has loaded +//! (`lightcraft_engine::map::TileService`), drawn for a map view of any size. +//! +//! - One texture cache for every map on screen, keyed by (tile source, z, x, y), least recently +//! used evicted past [`TEXTURE_CAP`]; a tile drawn in the current frame is never evicted. +//! - A tile not loaded yet is drawn from a loaded ancestor (up to [`PARENT_LEVELS`] zooms up), +//! scaled; with none, the map's grey shows through with a faint outline. +//! - The service is told the union of the tiles the maps wanted this frame and the last; when no +//! map is drawn for two frames ([`end_frame`]) it is told nothing, so it stops fetching. +//! - The offline source draws the grey map with a note and starts no tile service. +//! +//! The attribution of the source is painted by the views (always visible, bottom right). + +use std::collections::HashMap; +use std::sync::{Mutex, PoisonError}; +use std::time::Duration; + +use egui::{Align2, Color32, ColorImage, FontId, Painter, Rect, Stroke, StrokeKind, TextureHandle, TextureOptions, pos2, vec2}; +use lightcraft_engine::Session; +use lightcraft_engine::map::{TileEvent, TileKey, TileService, Viewport}; +use lightcraft_geom::LatLon; + +/// Tile textures kept on the GPU (256 × 256 × 4 bytes each: 64 MB at most). +pub const TEXTURE_CAP: usize = 256; +/// How many zooms up a missing tile looks for a loaded ancestor to draw instead. +pub const PARENT_LEVELS: u8 = 4; +/// The map's colour where no tile is drawn. +pub const MAP_GREY: Color32 = Color32::from_rgb(214, 218, 222); + +type TexKey = (String, TileKey); + +#[derive(Default)] +struct Store { + textures: HashMap, + /// Tiles wanted by the maps drawn in the pass `frame`, and in the pass before. + this_frame: Vec, + last_frame: Vec, + frame: u64, +} + +impl Store { + /// Start pass `pass` if it hasn't been started: this frame's wanted tiles become the last's. + fn roll(&mut self, pass: u64) { + if self.frame != pass { + self.last_frame = std::mem::take(&mut self.this_frame); + self.frame = pass; + } + } + + /// The tiles to ask the service for: this frame's, then the last frame's not yet listed. + fn wanted(&self) -> Vec { + let mut out = self.this_frame.clone(); + for k in &self.last_frame { + if !out.contains(k) { + out.push(*k); + } + } + out + } + + /// The texture of `key`, uploading the service's decoded tile if it has one. + fn texture(&mut self, ctx: &egui::Context, svc: &TileService, source: &str, key: TileKey, pass: u64) -> Option { + let k = (source.to_string(), key); + if let Some((tex, used)) = self.textures.get_mut(&k) { + *used = pass; + return Some(tex.id()); + } + let img = svc.get(key)?; + let size = [usize::try_from(img.width).ok()?, usize::try_from(img.height).ok()?]; + if size[0].checked_mul(size[1]).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) { + return None; + } + let image = ColorImage::from_rgba_unmultiplied(size, &img.rgba); + let tex = ctx.load_texture(format!("map-tile-{source}-{}-{}-{}", key.z, key.x, key.y), image, TextureOptions::LINEAR); + let id = tex.id(); + self.textures.insert(k, (tex, pass)); + Some(id) + } + + /// Drop least recently used textures past the cap (never one drawn in pass `pass`). + fn evict(&mut self, pass: u64) { + if self.textures.len() <= TEXTURE_CAP { + return; + } + let mut old: Vec<(u64, TexKey)> = + self.textures.iter().filter(|(_, (_, used))| *used != pass).map(|(k, (_, used))| (*used, k.clone())).collect(); + old.sort_by_key(|(used, _)| *used); + let excess = self.textures.len() - TEXTURE_CAP; + for (_, k) in old.into_iter().take(excess) { + self.textures.remove(&k); + } + } +} + +static STORE: Mutex> = Mutex::new(None); + +/// What [`draw`] did (for tests and `ui.inspect`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Drawn { + /// Tiles drawn from their own texture. + pub tiles: usize, + /// Tiles drawn from an ancestor's texture, scaled. + pub from_parent: usize, + /// Tiles with nothing to draw yet (grey). + pub missing: usize, + /// The source is offline: no tiles, no service. + pub offline: bool, +} + +/// The tile zoom shown for a view at `zoom` is a whole zoom; tiles are 256 points a side at it. +fn viewport(rect: Rect, center: LatLon, zoom: f64) -> Viewport { + Viewport::new(center, zoom, f64::from(rect.width()), f64::from(rect.height())) +} + +/// Draw the tiles of the map centred on `center` at `zoom` into `rect` (clipped by `painter`), +/// and ask the tile service for them (`ring`: also the ring of tiles around the view, at most one, +/// for a map that pans; 0 for a small fixed map). +pub fn draw(session: &mut Session, painter: &Painter, rect: Rect, center: LatLon, zoom: f64, ring: u32) -> Drawn { + let ctx = painter.ctx().clone(); + let pass = ctx.cumulative_pass_nr(); + painter.rect_filled(rect, 0.0, MAP_GREY); + let source = session.map.effective_source(); + if source.is_offline() { + painter.text( + rect.center(), + Align2::CENTER_CENTER, + crate::i18n::tr("Map tiles are off"), + FontId::proportional(12.0), + Color32::from_rgb(90, 96, 104), + ); + return Drawn { offline: true, ..Drawn::default() }; + } + let Some(svc) = session.map_tiles() else { return Drawn { offline: true, ..Drawn::default() } }; + let view = viewport(rect, center, zoom); + let max_zoom = source.max_zoom(); + let source_id = source.id().to_string(); + + let mut guard = STORE.lock().unwrap_or_else(PoisonError::into_inner); + let store = guard.get_or_insert_with(Store::default); + store.roll(pass); + // a refreshed tile replaces its texture (uploaded again from the service on the next draw) + let events = svc.poll(); + for e in &events { + if let TileEvent::Ready { key, .. } = e { + store.textures.remove(&(source_id.clone(), *key)); + } + } + for k in view.tile_keys(max_zoom, ring.min(1)) { + if !store.this_frame.contains(&k) { + store.this_frame.push(k); + } + } + svc.want(&store.wanted()); + + let mut drawn = Drawn::default(); + let full = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + for vt in view.tiles(max_zoom) { + let r = Rect::from_min_max( + pos2(rect.left() + vt.rect.x0 as f32, rect.top() + vt.rect.y0 as f32), + pos2(rect.left() + vt.rect.x1 as f32, rect.top() + vt.rect.y1 as f32), + ); + if !r.intersects(rect) { + continue; + } + if let Some(id) = store.texture(&ctx, svc, &source_id, vt.key, pass) { + painter.image(id, r, full, Color32::WHITE); + drawn.tiles += 1; + continue; + } + let parent = (1..=PARENT_LEVELS.min(vt.key.z)).find_map(|d| { + let pk = TileKey::new(vt.key.z - d, vt.key.x >> d, vt.key.y >> d)?; + let id = store.texture(&ctx, svc, &source_id, pk, pass)?; + // the part of the ancestor this tile covers + let n = f32::from(1u16 << d); + let (ox, oy) = ((vt.key.x - (pk.x << d)) as f32, (vt.key.y - (pk.y << d)) as f32); + Some((id, Rect::from_min_size(pos2(ox / n, oy / n), vec2(1.0 / n, 1.0 / n)))) + }); + match parent { + Some((id, uv)) => { + painter.image(id, r, uv, Color32::WHITE); + drawn.from_parent += 1; + } + None => { + painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_black_alpha(18)), StrokeKind::Inside); + drawn.missing += 1; + } + } + } + store.evict(pass); + drop(guard); + if !events.is_empty() { + ctx.request_repaint(); + } else if drawn.missing + drawn.from_parent > 0 || !session.map.service().is_none_or(TileService::is_idle) { + // tiles arrive on the service's threads: look again shortly + ctx.request_repaint_after(Duration::from_millis(100)); + } + drawn +} + +/// Call once per frame after every map was drawn: when no map drew this frame nor the last, the +/// tile service is told nothing is wanted, so it stops fetching (the OSM policy: only what is in +/// view). Never starts a service. +pub fn end_frame(session: &Session, ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + let mut guard = STORE.lock().unwrap_or_else(PoisonError::into_inner); + let Some(store) = guard.as_mut() else { return }; + if store.frame == pass { + return; + } + store.roll(pass); + if let Some(svc) = session.map.service() { + svc.want(&store.wanted()); + } +} + +/// Texture count, for tests and diagnostics. +pub fn texture_count() -> usize { + STORE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map_or(0, |s| s.textures.len()) +} + +/// Forget every texture (tests). +#[cfg(test)] +pub fn reset() { + *STORE.lock().unwrap_or_else(PoisonError::into_inner) = None; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_wanted_tiles_are_this_frame_and_the_last() { + let k = |x| TileKey::new(5, x, 1).unwrap(); + let mut s = Store::default(); + s.roll(1); + s.this_frame = vec![k(1), k(2)]; + s.roll(2); + s.this_frame.push(k(3)); + assert_eq!(s.wanted(), vec![k(3), k(1), k(2)]); + // a frame with no map, then another: nothing left + s.roll(3); + assert_eq!(s.wanted(), vec![k(3)]); + s.roll(4); + assert!(s.wanted().is_empty()); + } +} diff --git a/crates/ui-egui/src/state/map.rs b/crates/ui-egui/src/state/map.rs index d208b205b0..1aeb87bc93 100644 --- a/crates/ui-egui/src/state/map.rs +++ b/crates/ui-egui/src/state/map.rs @@ -1,6 +1,7 @@ use serde::{Deserialize, Serialize}; -/// State for the Map module (viewport center, zoom, provider, locked, filters). +/// State for the Map module (viewport center, zoom, locked, filters). The tile source is a +/// library preference in the engine (`map.tileSource`). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct MapUi { @@ -8,7 +9,6 @@ pub struct MapUi { pub center_lon: f64, pub zoom: f64, pub navigator_zoom: f64, - pub provider: lightcraft_engine::map::MapProvider, pub filter: lightcraft_engine::map::LocationFilter, pub show_filter_bar: bool, pub locked: bool, @@ -26,7 +26,6 @@ impl Default for MapUi { center_lon: -73.2, zoom: 12.0, navigator_zoom: 3.0, - provider: lightcraft_engine::map::MapProvider::OpenStreetMap, filter: lightcraft_engine::map::LocationFilter::None, show_filter_bar: true, locked: false, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4f25582349..5abaed6ba9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -107,6 +107,10 @@ filmstrip is visible. | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "map.tileSource"}` | `{}`, `{id: "osm"\|"opentopomap"\|"offline"}`, `{offline: true\|false}` or `{urlTemplate, attribution, maxZoom?, id?}` | The map's tile source (OpenStreetMap by default; custom `https://` templates with `{z}/{x}/{y}` only; the Esri layers are refused, see `docs/map.md`), saved with the library preferences → `{id, label, urlTemplate, attribution, maxZoom, userAgent, offline, custom, saved, notice, esriEnabled}`; `saved`/`notice` name a stored source the map can't use (it shows OpenStreetMap) | +| `engine.execute {command: "map.providers"}` | — | The tile sources the map offers now → `[{id, label, maxZoom, attribution, offline, current}]` | +| `engine.execute {command: "map.cacheInfo"}` | — | The on-disk tile cache → `{bytes, tiles, capBytes, dir}` (`dir` null: no disk cache) | +| `engine.execute {command: "map.clearCache"}` | — | Deletes every cached tile (all sources) → `{bytes, tiles, dir}` deleted | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | diff --git a/docs/gaps.md b/docs/gaps.md index f1a9a7e5ac..76c3adfaac 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 view, saved locations and filter ✅ (OSM & Esri tiles); geotag 🟡 (no drag onto the 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 view, saved locations and filter ✅ (OpenStreetMap / OpenTopoMap / custom tiles under the OSM tile policy; Esri off, see docs/map.md); geotag 🟡 (no drag onto the map); 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/map.md b/docs/map.md new file mode 100644 index 0000000000..967374c746 --- /dev/null +++ b/docs/map.md @@ -0,0 +1,100 @@ +# Map + +The Map view (View ▸ Map, ⌘⌥3 / Ctrl+Alt+3) shows the photos that have a GPS position on a slippy map. +This page describes where the map's tiles come from, what is sent over the network, and the commands +behind it. Later sections (pins and clusters, the Info panel map, geotagging, the location filter, saved +locations, track logs, keys and menus) are filled in as those parts land. + +## Tile sources and cache + +The tiles are raster images in the Web Mercator projection (256 px, zoom 0–19). Where they come from is a +library preference (`prefs.json` → `mapSource`), set with the Map Style list at the bottom of the map or +the `map.tileSource` command: + +| Source | Id | Tiles | Max zoom | Credit shown on the map | +|--------|----|-------|----------|-------------------------| +| OpenStreetMap (default) | `osm` | `https://tile.openstreetmap.org/{z}/{x}/{y}.png` | 19 | © OpenStreetMap contributors | +| OpenTopoMap | `opentopomap` | `https://tile.opentopomap.org/{z}/{x}/{y}.png` | 17 | Map data: © OpenStreetMap contributors, SRTM \| Map style: © OpenTopoMap (CC-BY-SA) | +| Offline | `offline` | none: a grey map, nothing is fetched and no tile service runs | 19 | — | +| Custom | your id | an `https://…/{z}/{x}/{y}…` template you give, with its credit | 0–24 | the credit you give (required) | + +The credit of the source in use is always painted at the bottom right of the map, never behind a toggle. +A stored source is checked again when the library opens: one that is damaged or not `https://` falls back +to OpenStreetMap and the rest of `prefs.json` is kept. + +**Cache.** Tiles are cached on disk in the per-user cache folder: `~/Library/Caches/LightCraft/maptiles` on +macOS, `%LOCALAPPDATA%\LightCraft\Cache\maptiles` on Windows, `$XDG_CACHE_HOME/lightcraft/maptiles` (else +`~/.cache/lightcraft/maptiles`) elsewhere, `/LightCraftData/Cache/maptiles` in portable mode, or +`$LIGHTCRAFT_MAP_CACHE` when set. Each source has its own subfolder. The cache follows the server's +`Cache-Control` / `Expires` headers (7 days when there are none), refreshes an expired tile with a +conditional request (`If-None-Match` / `If-Modified-Since`; a `304` only renews it) while still showing it, +writes atomically (a temporary file renamed into place), deletes and fetches again an entry that is +damaged, and stays under 500 MB by deleting the least recently used tiles. `map.cacheInfo` reports its size; +`map.clearCache` empties it. + +On screen, up to 256 tile textures are kept (least recently used dropped first); a tile that is not +loaded yet is drawn from a loaded tile up to four zoom levels above it, else the map's grey shows. + +## OpenStreetMap tile usage policy + +LightCraft uses OpenStreetMap's tile server under its tile usage policy +(, read 2026-11-14): + +- **Only what is in view.** The tiles requested are those drawn plus at most one ring around them, at the + zoom drawn. There is no prefetching, no "download area" and no offline download. When the view moves, + queued requests that left it are dropped before they start, and the newest view's tiles nearest the + centre go first. When no map is on screen for two frames, the queue is emptied. +- **Gently.** At most two requests at a time. After an error, a `429` or a `5xx` the host is left alone with + exponential backoff (1 s doubling up to 5 min, at least its `Retry-After`), then asked one request at a + time until it answers. A tile the server refuses (404, not an image) is not asked for again for 10 min. +- **Identified.** Every request carries `User-Agent: LightCraft/ (+https://github.com/storytold/lightcraft)`, + and nothing about you. Requests never send `Cache-Control: no-cache` or `Pragma`. +- **Cached** as described above, honouring the server's headers. +- **Checked.** A response over 2 MiB, one that is not a PNG, JPEG or WebP image of at most 1024 px a side, + or one that does not decode is an error for that tile, never a crash, and is not cached. +- **Visible.** While tiles are queued or loading, one "Loading map tiles" row is on the activity stack. + +Sessions that a host has not put online (tests, the web build) never fetch tiles. + +## Esri layers (off) + +Earlier builds of this branch offered Esri's World Imagery, World Street Map, World Topographic Map and a +Hybrid layer, fetched from `server.arcgisonline.com` without an account. They are **off and cannot be +turned on** in this build: the Map Style list does not offer them, `map.tileSource` refuses them with an +error naming this page, and nothing is ever fetched from Esri. A library saved with an Esri layer opens on +OpenStreetMap with a one-line notice; `prefs.json` keeps the Esri choice. + +Why: Esri's terms for these layers do not allow this use. Each layer's ArcGIS Online item +(e.g. for World Imagery) says it is +"licensed under the Esri Master License Agreement" and links its terms. The terms summary +(, "Last Updated: April 21, 2025", read +2026-11-14) lists as conditions "Use with Esri software and comply with its terms of use. If you do not have +Esri software, you must purchase an ArcGIS Online subscription", and among what you may not do, +"Systematically harvest basemap tiles through any method other than using Esri Content Packages" and "Use +content from ArcGIS Living Atlas for commercial use in your application or product". LightCraft is not Esri +software and has no ArcGIS subscription. The full terms are the Esri Master Agreement +(). The layers' required credits, kept in the code +for when this changes, come from each item's `accessInformation` +(). + +Turning them on would need a maintainer decision, for example a user-supplied ArcGIS key through Esri's +token-based basemap service, with the privacy note that Esri's server then sees which places you look at. + +## Privacy + +The tile server sees which tiles you look at (so roughly which places), your IP address and the +User-Agent above. Nothing else leaves the machine: no photo, place name or coordinate is sent except as the +tile `z/x/y` in the URL. Reverse geocoding (place names from GPS) is offline (`metadata.reverseGeocode`, +GeoNames). Choose Offline to fetch nothing. + +## Commands + +| Command | What it does | +|---------|--------------| +| `map.tileSource` | `{}` reports the source; `{id: "osm" \| "opentopomap" \| "offline"}`, `{offline: true \| false}`, or `{urlTemplate, attribution, maxZoom?, id?}` sets it (saved in `prefs.json`) | +| `map.providers` | The sources offered now, with credit and max zoom | +| `map.cacheInfo` | `{bytes, tiles, capBytes, dir}` of the tile cache | +| `map.clearCache` | Deletes every cached tile | + +The tile core (Web Mercator maths, source checks, cache, fetch queue) is ported from PR #797 by Jason +Baldwin. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 60f5c4c925..79aa6d1f08 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -737,7 +737,7 @@ 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 | ✅ | `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-VIEW | Map view | P2 | ✅ | `cmd:view.map`, `cmd:map.providers`, `cmd:map.tileSource`, `cmd:map.cacheInfo`, `cmd:map.clearCache`, `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/engine/src/map/service.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/panels/map/tiles.rs`, `docs/map.md` | Interactive slippy map; tiles from OpenStreetMap (default), OpenTopoMap, a custom `https://` template, or Offline (`map.tileSource`, saved per library), fetched under the OSM tile usage policy (view plus one ring, 2 requests at a time, backoff and `Retry-After`, LightCraft User-Agent, on-disk cache honouring Cache-Control/Expires/ETag, 500 MB LRU, activity row); the Esri layers are off (their terms, `docs/map.md`); credit always shown; missing tiles drawn from a parent tile; photo marker clustering with cluster badges and count (screen-space, regroups on pan); single-pin selection & loupe popover; top location filter bar (Visible On Map, Tagged, Untagged, None); bottom toolbar with Map Style list, zoom slider and lock toggle; 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` | `photo.setGps` sets latitude / longitude and `photo.clearGps` removes them, one undo step each. Missing: dragging photos from the grid or filmstrip onto the map, and moving a pin | | 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 | @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-14 | patch | LRC-MAP-VIEW: map tiles follow the OSM tile usage policy (view plus one ring, 2 requests at a time, backoff, `Retry-After`, LightCraft User-Agent, on-disk cache with ETag revalidation and a 500 MB cap, activity row); OpenTopoMap, custom and Offline sources (`map.tileSource`); the Esri layers are off (their terms require Esri software or an ArcGIS subscription; `docs/map.md`); status unchanged | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-05 | patch | LRC-LIB-CATALOG-LOCK: a library is written only to the folder it was opened from (on Unix, where the system gives a folder an identity, it is checked before every write of the catalog, settings, lock note and thumbnails; a share mounted over it, or a replaced folder, is refused and nothing is written; a folder that holds this session's lock note counts as the opened one, so a drive mounted again keeps saving; on Windows only that the path is still a folder is checked, so a replaced folder or a share mounted at the same path is not caught), a Move import removes its originals only once the catalog log is on disk, and dropping the lock removes only the owner note it wrote itself (#3240); status unchanged | | 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur | From f6524ed1c64b92bc5bf0f7491b566280dfdec65b Mon Sep 17 00:00:00 2001 From: "Bruno D." Date: Sun, 15 Nov 2026 00:05:17 -0500 Subject: [PATCH 11/51] LRC-MAP-GEOTAG: drag filmstrip photos onto the Map view to geotag them; filmstrip and selection on the map The Map view had no filmstrip: only Detail and Compare draw it, and in the Map view the bottom bar fell into the grid branch, showing a thumbnail-size slider that did nothing and no filmstrip toggle. So photos could not be dragged onto the map, and the map did not show which photos were selected beyond a pin colour. - The Map view draws the shared filmstrip under the map when it is on (View > Filmstrip, `/`, F6), as Detail does, and shrinks the map above it (not in full screen, not when the window is too short). In the Map view the bottom bar shows the Filmstrip toggle instead of the thumbnail size. - Photos carried from the filmstrip (the drag the filmstrip and grid already start: the selection, or the photo alone when it is not selected) draw a pin with their count at the pointer over the map, and the drag label says "Set the location of N photos". A release over the map gives all of them that point's position, overwriting one they had, as one undo step (`photo.setGps`). A release over the map's toolbar or filter bar, or outside the map, changes nothing. The longitude wraps around the world and the latitude stays inside Web Mercator's 85.05 degrees. - Selection both ways: a cluster holding selected photos is yellow and carries a bubble with how many are selected; a click on a pin selects its photo and a click on a cluster selects all its photos (the first active; Cmd/Ctrl adds), so the filmstrip shows them and scrolls to the active one. Pins are not hovered or clicked while photos are carried. - `map.state` (UI command) reports the view, the canvas, whether the filmstrip is drawn, each pin drawn last frame with its ids, count and selected count, and a drop in progress; it is cleared each frame so it reports nothing once the map is gone. - `photo.setGps` is extended rather than duplicated: it names its photos explicitly, wraps the longitude into -180..180 (it refused 190), refuses ids the library doesn't have (it skipped them silently, so a drop of photos deleted meanwhile reported success), and its undo step and label are "Set GPS Coordinates"; it now also returns lat/lon. This validation follows PR #810 (geotag); the drop itself is written for this branch's map view, since #810 builds on #797's cluster and viewport code. New strings are in every locale catalog. docs/map.md gains "Map view" and "Geotagging" sections; control-protocol, the LRC-MAP-VIEW and LRC-MAP-GEOTAG rows (geotag stays partial: no pin move, Lock Markers, Remove GPS menu or sidecar fix yet) and gap 16 are updated. Tests: new `ui-egui tests::map_filmstrip` (filmstrip drawn and toggled in the Map view, bottom bar toggle and no slider; filmstrip drag sets GPS for two photos in one undo step; a drop on the toolbar or of missing photos changes nothing; selected counts per pin and a cluster click selecting in the filmstrip) and two engine tests (one undo step and restore for several photos; longitude wrap and hostile values). Each failed with its change reverted (filmstrip not drawn; bottom bar branch, drop handler and cluster selection disabled; old `photo.setGps`). `cargo xtask ci --quick` (fmt, clippy, tests of every package): all pass except the known failures on this machine (13 lightcraft-raw corpus tests, 2 engine corpus tests; the GPU out-of-memory test failed in one run and passed in the other, and ui-egui find_similar::stopping_leaves_the_view_alone... failed once and passed three times alone). `cargo xtask layers`, `assets`, `roots`, `parity` and `wasm` pass. The app was run with `--demo --control 18421` and a headless snapshot: filmstrip under the map, a drag from it dropped two photos at the pointer, selected counts on the clusters, a cluster click selecting its photos in the filmstrip. Co-Authored-By: Jason Baldwin <33934381+bitshiftza@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/map.rs | 89 ++++--- crates/engine/src/tests/map.rs | 52 ++++ crates/ui-egui/locales/cs-formats.json | 3 +- crates/ui-egui/locales/cs.json | 3 +- crates/ui-egui/locales/de-formats.json | 3 +- crates/ui-egui/locales/de.json | 3 +- crates/ui-egui/locales/es-formats.json | 3 +- crates/ui-egui/locales/es.json | 3 +- crates/ui-egui/locales/fi-formats.json | 3 +- crates/ui-egui/locales/fi.json | 3 +- crates/ui-egui/locales/fr-formats.json | 3 +- crates/ui-egui/locales/fr.json | 3 +- crates/ui-egui/locales/id-formats.json | 3 +- crates/ui-egui/locales/id.json | 3 +- crates/ui-egui/locales/it-formats.json | 3 +- crates/ui-egui/locales/it.json | 3 +- crates/ui-egui/locales/ja-formats.json | 3 +- crates/ui-egui/locales/ja.json | 3 +- crates/ui-egui/locales/ka-formats.json | 3 +- crates/ui-egui/locales/ka.json | 3 +- crates/ui-egui/locales/pl-formats.json | 3 +- crates/ui-egui/locales/pl.json | 3 +- crates/ui-egui/locales/pt-br-formats.json | 3 +- crates/ui-egui/locales/pt-br.json | 3 +- crates/ui-egui/locales/ru-formats.json | 3 +- crates/ui-egui/locales/ru.json | 3 +- crates/ui-egui/locales/sv-formats.json | 3 +- crates/ui-egui/locales/sv.json | 3 +- crates/ui-egui/locales/uk-formats.json | 3 +- crates/ui-egui/locales/uk.json | 3 +- crates/ui-egui/locales/vi-formats.json | 3 +- crates/ui-egui/locales/vi.json | 3 +- crates/ui-egui/locales/zh-hans-formats.json | 3 +- crates/ui-egui/locales/zh-hans.json | 3 +- crates/ui-egui/locales/zh-hant-formats.json | 3 +- crates/ui-egui/locales/zh-hant.json | 3 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/docking.rs | 2 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/run.rs | 2 + crates/ui-egui/src/menus/ui_commands.rs | 1 + crates/ui-egui/src/panels/bottombar.rs | 6 + crates/ui-egui/src/panels/map.rs | 248 ++++++++++++++---- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/map_filmstrip.rs | 262 ++++++++++++++++++++ docs/control-protocol.md | 2 + docs/gaps.md | 2 +- docs/map.md | 31 +++ docs/parity-checklist.md | 5 +- 49 files changed, 693 insertions(+), 115 deletions(-) create mode 100644 crates/ui-egui/src/tests/map_filmstrip.rs diff --git a/crates/engine/src/cmd/map.rs b/crates/engine/src/cmd/map.rs index 63a920e1ee..528eb19874 100644 --- a/crates/engine/src/cmd/map.rs +++ b/crates/engine/src/cmd/map.rs @@ -11,6 +11,52 @@ use crate::{EngineError, Result, Session}; const SOURCE: &str = "map.tileSource"; +/// `photo.setGps`: every target photo gets the position (lat −90…90; the longitude wrapped into +/// −180…180, so a drop past the antimeridian lands on the same meridian), as one undo step. +/// Photos already there are left alone (no empty undo step). A named photo the library doesn't +/// have is an error and nothing changes: the caller (a drag of photos deleted meanwhile, an agent) +/// learns of it instead of a silent no-op. +fn set_gps(s: &mut Session, p: &Value) -> Result { + const C: &str = "photo.setGps"; + let lat = f64_req(p, "lat", C)?; + let lon = f64_req(p, "lon", C)?; + let Some(at) = LatLon::wrapped(lat, lon) else { + return Err(bad(C, format!("lat must be −90…90 and lon a finite number (got {lat}, {lon})"))); + }; + let pos = ((at.lat * 1e7).round() / 1e7, (at.lon * 1e7).round() / 1e7); + let mut seen = std::collections::HashSet::new(); + let targets: Vec<_> = s + .targets(p) + .map_err(|e| match e { + EngineError::BadParams { msg, .. } => bad(C, msg), + other => other, + })? + .into_iter() + .filter(|id| seen.insert(*id)) + .collect(); + if let Some(gone) = targets.iter().find(|id| s.catalog.photo(**id).is_none()) { + return Err(bad(C, format!("no such photo {}", gone.0))); + } + if targets.is_empty() { + return Err(bad(C, "no photos selected")); + } + let ops: Vec = targets + .iter() + .filter_map(|id| s.catalog.photo(*id)) + .filter(|ph| ph.meta.gps != Some(pos)) + .map(|ph| { + let mut meta = ph.meta.clone(); + meta.gps = Some(pos); + Op::SetMeta { id: ph.id, meta: Box::new(meta) } + }) + .collect(); + let count = ops.len(); + if count > 0 { + s.commit("Set GPS Coordinates", Op::Batch { ops })?; + } + Ok(json!({ "updated": count, "lat": pos.0, "lon": pos.1 })) +} + fn source_json(s: &Session) -> Value { let chosen = s.map.source(); let used = s.map.effective_source(); @@ -279,37 +325,18 @@ pub fn specs() -> Vec { } 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 })) - } - ), + CommandSpec { + explicit_targets: true, + ..cmd!( + "photo.setGps", + "Set GPS Coordinates", + [], + None, + "{ids?: [PhotoId], lat: −90…90, lon: degrees (wrapped into −180…180)} → {updated, lat, lon} — sets the GPS position of the photos (default: the selection), one undo step \"Set GPS Coordinates\"; what dropping photos on the Map view does. Unknown ids are refused", + has_selection, + set_gps + ) + }, cmd!( "photo.clearGps", "Clear Photo GPS Coordinates", diff --git a/crates/engine/src/tests/map.rs b/crates/engine/src/tests/map.rs index a24fb85a1a..a71648d08e 100644 --- a/crates/engine/src/tests/map.rs +++ b/crates/engine/src/tests/map.rs @@ -292,3 +292,55 @@ fn a_damaged_saved_tile_source_keeps_the_other_preferences() { drop(s); let _ = std::fs::remove_dir_all(&lib); } + +/// What a drop of several photos on the Map view runs: all of them (one already placed +/// elsewhere) get the drop point in one undo step, and undo restores each one's old position. +#[test] +fn set_gps_moves_every_named_photo_in_one_undo_step() { + let mut s = Session::with_demo(); + let ids: Vec = s.visible().iter().take(3).map(|p| p.0).collect(); + s.execute("photo.setGps", &json!({"ids": [ids[0]], "lat": 10.0, "lon": 20.0})).unwrap(); + let steps = s.undo.len(); + let r = s.execute("photo.setGps", &json!({"ids": ids, "lat": 48.85, "lon": 2.29})).unwrap(); + assert_eq!(r["updated"], 3, "{r}"); + assert_eq!(s.undo.len(), steps + 1, "one undo step"); + assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Set GPS Coordinates")); + let gps = |s: &Session, id: u64| s.catalog.photo(lightcraft_catalog::PhotoId(id)).and_then(|p| p.meta.gps); + assert!(ids.iter().all(|i| gps(&s, *i) == Some((48.85, 2.29)))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(gps(&s, ids[0]), Some((10.0, 20.0)), "the old position comes back"); + assert_eq!((gps(&s, ids[1]), gps(&s, ids[2])), (None, None)); + // the same position again is no new undo step + s.execute("edit.redo", &json!({})).unwrap(); + let steps = s.undo.len(); + assert_eq!(s.execute("photo.setGps", &json!({"ids": [ids[1]], "lat": 48.85, "lon": 2.29})).unwrap()["updated"], 0); + assert_eq!(s.undo.len(), steps); +} + +/// A longitude past the antimeridian (a drop on the world's repeat at low zoom) is the same +/// meridian, wrapped; a latitude out of range, a non-number or an id the library doesn't have is +/// refused and nothing changes. +#[test] +fn set_gps_wraps_longitude_and_refuses_hostile_values() { + let mut s = Session::with_demo(); + let id = s.visible()[0].0; + let r = s.execute("photo.setGps", &json!({"ids": [id], "lat": -33.9, "lon": 190.0})).unwrap(); + assert_eq!(r["lon"].as_f64(), Some(-170.0), "{r}"); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).and_then(|p| p.meta.gps), Some((-33.9, -170.0))); + let steps = s.undo.len(); + for bad in [ + json!({"ids": [id], "lat": 91.0, "lon": 0.0}), + json!({"ids": [id], "lat": -90.5, "lon": 0.0}), + json!({"ids": [id], "lat": "north", "lon": 0.0}), + json!({"ids": [id], "lon": 0.0}), + json!({"ids": [id], "lat": 0.0}), + json!({"ids": [id], "lat": 0.0, "lon": [1]}), + json!({"ids": [id, 987_654_321u64], "lat": 1.0, "lon": 1.0}), + json!({"ids": "1", "lat": 1.0, "lon": 1.0}), + json!({"ids": [], "lat": 1.0, "lon": 1.0}), + ] { + assert!(s.execute("photo.setGps", &bad).is_err(), "{bad}"); + } + assert_eq!(s.undo.len(), steps, "nothing changed"); + assert_eq!(s.catalog.photo(lightcraft_catalog::PhotoId(id)).and_then(|p| p.meta.gps), Some((-33.9, -170.0))); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 77c37c84fc..7ce176697c 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -325,5 +325,6 @@ "View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).", "File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).", "{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}", + "Set the location of {n} photos": "Nastavit polohu {n} fotek" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index cd54246dfa..0699e68341 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2526,5 +2526,6 @@ "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", "Map tiles are off": "Mapové dlaždice jsou vypnuté", "Offline (no tiles)": "Offline (bez dlaždic)", - "Custom tile server": "Vlastní server dlaždic" + "Custom tile server": "Vlastní server dlaždic", + "Set the location of this photo": "Nastavit polohu této fotky" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 7e78396a1c..6162733000 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet", "Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.", "View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).", - "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys})." + "File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).", + "Set the location of {n} photos": "Ort von {n} Fotos festlegen" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 53af38378a..9b469cb1fb 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3561,5 +3561,6 @@ "Map (Ctrl+Alt+3)": "Karte (Strg+Alt+3)", "Map tiles are off": "Kartenkacheln sind aus", "Offline (no tiles)": "Offline (keine Kacheln)", - "Custom tile server": "Eigener Kachelserver" + "Custom tile server": "Eigener Kachelserver", + "Set the location of this photo": "Ort dieses Fotos festlegen" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index eb5edf4866..6b4e245402 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado", "Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).", - "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys})." + "File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).", + "Set the location of {n} photos": "Establecer la ubicación de {n} fotos" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 5eb77a2645..b8c3d5d64d 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2480,5 +2480,6 @@ "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", "Map tiles are off": "Las teselas del mapa están desactivadas", "Offline (no tiles)": "Sin conexión (sin teselas)", - "Custom tile server": "Servidor de teselas personalizado" + "Custom tile server": "Servidor de teselas personalizado", + "Set the location of this photo": "Establecer la ubicación de esta foto" } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 31f6c32b5d..4be639b5e2 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -322,5 +322,6 @@ "View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).", "File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).", "{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}", + "Set the location of {n} photos": "Aseta {n} kuvan sijainti" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 7c58d5b1ca..1d3512179d 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2437,5 +2437,6 @@ "Map (Ctrl+Alt+3)": "Kartta (Ctrl+Alt+3)", "Map tiles are off": "Karttaruudut ovat pois päältä", "Offline (no tiles)": "Offline (ei ruutuja)", - "Custom tile server": "Oma ruutupalvelin" + "Custom tile server": "Oma ruutupalvelin", + "Set the location of this photo": "Aseta tämän kuvan sijainti" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index ba6bcc7b0f..8cccd3b0fe 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée", "Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).", "View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).", - "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys})." + "File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).", + "Set the location of {n} photos": "Définir le lieu de {n} photos" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index c9cdb5b6b9..05368ad2d6 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3663,5 +3663,6 @@ "Map (Ctrl+Alt+3)": "Carte (Ctrl+Alt+3)", "Map tiles are off": "Les tuiles de la carte sont désactivées", "Offline (no tiles)": "Hors ligne (sans tuiles)", - "Custom tile server": "Serveur de tuiles personnalisé" + "Custom tile server": "Serveur de tuiles personnalisé", + "Set the location of this photo": "Définir le lieu de cette photo" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7bd027cc35..d2df947cb4 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -325,5 +325,6 @@ "View › Detail View ({keys}).": "Tampilan › Tampilan Detail ({keys}).", "File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).", "{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}", + "Set the location of {n} photos": "Tetapkan lokasi {n} foto" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0227d022ae..56eecf9571 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2451,5 +2451,6 @@ "Map (Ctrl+Alt+3)": "Peta (Ctrl+Alt+3)", "Map tiles are off": "Petak peta nonaktif", "Offline (no tiles)": "Luring (tanpa petak)", - "Custom tile server": "Server petak khusus" + "Custom tile server": "Server petak khusus", + "Set the location of this photo": "Tetapkan lokasi foto ini" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 922bac810d..86a4feaa8d 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -325,5 +325,6 @@ "View › Detail View ({keys}).": "Visualizza › Vista dettaglio ({keys}).", "File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).", "{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}", + "Set the location of {n} photos": "Imposta la posizione di {n} foto" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 7f8c35d975..727713c84c 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2644,5 +2644,6 @@ "Map (Ctrl+Alt+3)": "Mappa (Ctrl+Alt+3)", "Map tiles are off": "Le tessere della mappa sono disattivate", "Offline (no tiles)": "Offline (nessuna tessera)", - "Custom tile server": "Server di tessere personalizzato" + "Custom tile server": "Server di tessere personalizzato", + "Set the location of this photo": "Imposta la posizione di questa foto" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 9f7dd3fe7c..a17221e5ee 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです", "Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。", "View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。", - "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。" + "File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。", + "Set the location of {n} photos": "{n} 枚の写真の位置を設定" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index d159e819cd..657fde2a10 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2478,5 +2478,6 @@ "Map (Ctrl+Alt+3)": "地図(Ctrl+Alt+3)", "Map tiles are off": "地図タイルはオフです", "Offline (no tiles)": "オフライン(タイルなし)", - "Custom tile server": "カスタムタイルサーバー" + "Custom tile server": "カスタムタイルサーバー", + "Set the location of this photo": "この写真の位置を設定" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index b13dc07d30..4dce9bf008 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -328,5 +328,6 @@ "View › Detail View ({keys}).": "ხედი › დეტალური ხედი ({keys}).", "File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).", "{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}", + "Set the location of {n} photos": "{n} ფოტოს მდებარეობის დაყენება" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 3d71f6148a..dfd0ad9b69 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3746,5 +3746,6 @@ "Map (Ctrl+Alt+3)": "რუკა (Ctrl+Alt+3)", "Map tiles are off": "რუკის ფილები გამორთულია", "Offline (no tiles)": "ოფლაინ (ფილების გარეშე)", - "Custom tile server": "საკუთარი ფილების სერვერი" + "Custom tile server": "საკუთარი ფილების სერვერი", + "Set the location of this photo": "ამ ფოტოს მდებარეობის დაყენება" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index f03219ae1e..e84dfdc2f0 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -325,5 +325,6 @@ "View › Detail View ({keys}).": "Widok › Widok szczegółów ({keys}).", "File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).", "{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}", + "Set the location of {n} photos": "Ustaw lokalizację {n} zdjęć" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 3231878209..3261e950b3 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2403,5 +2403,6 @@ "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", "Map tiles are off": "Kafelki mapy są wyłączone", "Offline (no tiles)": "Offline (bez kafelków)", - "Custom tile server": "Własny serwer kafelków" + "Custom tile server": "Własny serwer kafelków", + "Set the location of this photo": "Ustaw lokalizację tego zdjęcia" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 762eed671a..797eda5e0c 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado", "Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).", "View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).", - "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys})." + "File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).", + "Set the location of {n} photos": "Definir a localização de {n} fotos" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 00c3f49350..1d2660c220 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2324,5 +2324,6 @@ "Map (Ctrl+Alt+3)": "Mapa (Ctrl+Alt+3)", "Map tiles are off": "Os blocos do mapa estão desativados", "Offline (no tiles)": "Offline (sem blocos)", - "Custom tile server": "Servidor de blocos personalizado" + "Custom tile server": "Servidor de blocos personalizado", + "Set the location of this photo": "Definir a localização desta foto" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 24134de944..f0d0770c66 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено", "Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).", "View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).", - "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys})." + "File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).", + "Set the location of {n} photos": "Задать местоположение {n} фото" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index a842adb6ac..701451b87e 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2686,5 +2686,6 @@ "Map (Ctrl+Alt+3)": "Карта (Ctrl+Alt+3)", "Map tiles are off": "Тайлы карты отключены", "Offline (no tiles)": "Офлайн (без тайлов)", - "Custom tile server": "Свой сервер тайлов" + "Custom tile server": "Свой сервер тайлов", + "Set the location of this photo": "Задать местоположение этого фото" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index e205ea56a9..d94f49b1f3 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -325,5 +325,6 @@ "View › Detail View ({keys}).": "Visa › Detaljvy ({keys}).", "File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).", "{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}", + "Set the location of {n} photos": "Ange platsen för {n} foton" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index c3592d356e..259281bc3e 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2541,5 +2541,6 @@ "Map (Ctrl+Alt+3)": "Karta (Ctrl+Alt+3)", "Map tiles are off": "Kartrutor är avstängda", "Offline (no tiles)": "Offline (inga rutor)", - "Custom tile server": "Egen rutserver" + "Custom tile server": "Egen rutserver", + "Set the location of this photo": "Ange platsen för det här fotot" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index d30091f2d2..e69bd0a5c7 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено", "Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).", "View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).", - "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys})." + "File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).", + "Set the location of {n} photos": "Задати місце {n} фото" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 20cfbcce6d..5c52bfce52 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2476,5 +2476,6 @@ "Map (Ctrl+Alt+3)": "Мапа (Ctrl+Alt+3)", "Map tiles are off": "Тайли мапи вимкнено", "Offline (no tiles)": "Офлайн (без тайлів)", - "Custom tile server": "Власний сервер тайлів" + "Custom tile server": "Власний сервер тайлів", + "Set the location of this photo": "Задати місце цього фото" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d6c686c3b5..fb6eedd053 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -322,5 +322,6 @@ "View › Detail View ({keys}).": "Xem › Chế độ xem chi tiết ({keys}).", "File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).", "{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}", - "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}" + "{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}", + "Set the location of {n} photos": "Đặt vị trí cho {n} ảnh" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 0e9051fd31..c10339e0ac 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2765,5 +2765,6 @@ "Map (Ctrl+Alt+3)": "Bản đồ (Ctrl+Alt+3)", "Map tiles are off": "Ô bản đồ đang tắt", "Offline (no tiles)": "Ngoại tuyến (không có ô)", - "Custom tile server": "Máy chủ ô tùy chỉnh" + "Custom tile server": "Máy chủ ô tùy chỉnh", + "Set the location of this photo": "Đặt vị trí cho ảnh này" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 1d5f27c576..65d7391606 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启", "Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。", "View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。", - "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。" + "File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。", + "Set the location of {n} photos": "设置 {n} 张照片的位置" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 779e9254af..8af52409f3 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2479,5 +2479,6 @@ "Map (Ctrl+Alt+3)": "地图(Ctrl+Alt+3)", "Map tiles are off": "地图图块已关闭", "Offline (no tiles)": "离线(无图块)", - "Custom tile server": "自定义图块服务器" + "Custom tile server": "自定义图块服务器", + "Set the location of this photo": "设置这张照片的位置" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 51fb1109ae..7e317fbd4e 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -326,5 +326,6 @@ "{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟", "Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。", "View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。", - "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。" + "File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。", + "Set the location of {n} photos": "設定 {n} 張照片的位置" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 82513682cb..2bde2e68ef 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2480,5 +2480,6 @@ "Map (Ctrl+Alt+3)": "地圖(Ctrl+Alt+3)", "Map tiles are off": "地圖圖磚已關閉", "Offline (no tiles)": "離線(無圖磚)", - "Custom tile server": "自訂圖磚伺服器" + "Custom tile server": "自訂圖磚伺服器", + "Set the location of this photo": "設定這張照片的位置" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6d9faaafc9..f47c79bcaa 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -88,6 +88,7 @@ impl LightcraftApp { image_rect: None, grid_scroll: None, film_scroll: None, + map_drawn: Default::default(), widgets: vec![], widget_hits: vec![], next_widgets: vec![], diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f0735fcd88..f4152288e2 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -422,6 +422,8 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) { } }, ); + // what the Map view drew is this frame's only (`map.state` reports no pins once it is gone) + app.map_drawn = Default::default(); if let Some(mut canvas) = canvas { let ui = &mut canvas; crate::panels::bottombar::show(app, ui); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c40d16b8e9..652f1f0478 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -276,6 +276,8 @@ pub struct LightcraftApp { /// drawn last (`ui.inspect` → `scroll`). pub grid_scroll: Option, pub film_scroll: Option, + /// What the Map view drew last frame (pins, the drop under the pointer), for `map.state`. + pub map_drawn: panels::map::MapDrawn, /// Widget registry from the last completed, nondiscarded frame (automation ids → rects). pub widgets: Vec<(String, egui::Rect)>, /// Egui hit owners for [`Self::widgets`] from the same completed pass. A press is delivered diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5580896aa2..c9cf04e7ba 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -388,6 +388,8 @@ fn ui_commands_2(app: &mut LightcraftApp, ctx: &egui::Context, id: &str, p: &Val app.ui.map.legend_open = !app.ui.map.legend_open; Ok(json!({"open": app.ui.map.legend_open})) } + // the view, the pins drawn last frame (with how many of their photos are selected), a drop + "map.state" => Ok(crate::panels::map::state(app)), "photo.showInMap" => { let target_id = p.get("id").and_then(Value::as_u64).map(lightcraft_catalog::PhotoId).or(app.session.selection.active); if let Some(id) = target_id { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 93a511d4e2..d6a331720b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -79,6 +79,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("map.filterBar", "Location Filter Bar", None, "Window>Map"), ("map.legend", "Map Legend", None, "Window>Map"), ("map.lock", "Lock Map Markers", None, "Window>Map"), + ("map.state", "Map State", None, ""), ("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/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index 10a4a9a53e..23619137d7 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -194,6 +194,12 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo } if app.ui.view == ViewMode::Survey { // no zoom or thumbnail size in Survey + } else if app.ui.view == ViewMode::Map { + // the map has its own zoom; the grid's thumbnail size means nothing here, the filmstrip + // under the map (to drag photos onto it) does + if icon_button(&mut child, "filmstrip", Icon::Filmstrip, vec2(30.0, 30.0), app.ui.filmstrip, true, "Filmstrip (/)").clicked() { + let _ = app.run("view.filmstrip", json!({})); + } } else if matches!(app.ui.view, ViewMode::Detail | ViewMode::Compare) { if icon_button(&mut child, "beforeAfter", Icon::BeforeAfter, vec2(30.0, 30.0), app.ui.before_after.is_layout(), true, "Before/After (Y)") .clicked() diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 316daa5a15..9b55b8fd77 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -20,20 +20,73 @@ 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; +/// Height of the map's bottom toolbar (Map Style, zoom, Lock Markers, credit). +const TOOLBAR_H: 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, + /// How many of `photos` are selected. + selected: usize, } +/// What the Map view drew in its last frame (`map.state`; tests and agents read it). +#[derive(Clone, Debug, Default)] +pub struct MapDrawn { + /// The map canvas (screen points), `None` when the Map view wasn't drawn. + pub canvas: Option, + /// Whether the filmstrip was drawn under the map. + pub filmstrip: bool, + /// Each pin or cluster: its photos, how many of them are selected, and where it is. + pub pins: Vec, + /// Photos carried over the map: how many, the pointer, and where they would land. + pub drop: Option<(usize, Pos2, LatLon)>, +} + +/// A pin or cluster as drawn: its photos, how many of them are selected, its screen point. +#[derive(Clone, Debug)] +pub struct DrawnPin { + pub ids: Vec, + pub selected: usize, + pub at: Pos2, +} + +/// `map.state`: the view, the pins drawn last frame (each with `selected`, how many of its photos +/// are selected) and a drop in progress. +pub fn state(app: &LightcraftApp) -> serde_json::Value { + let d = &app.map_drawn; + json!({ + "lat": app.ui.map.center_lat, + "lon": app.ui.map.center_lon, + "zoom": app.ui.map.zoom, + "shown": app.ui.view == ViewMode::Map && d.canvas.is_some(), + "canvas": d.canvas.map(|r| json!({"x": r.left(), "y": r.top(), "width": r.width(), "height": r.height()})), + "filmstrip": d.filmstrip, + "pins": d.pins.iter().map(|p| json!({"ids": p.ids, "count": p.ids.len(), "selected": p.selected, "x": p.at.x, "y": p.at.y})).collect::>(), + "drop": d.drop.map(|(n, at, to)| json!({"count": n, "x": at.x, "y": at.y, "lat": to.lat, "lon": to.lon})), + }) +} + +/// Draw the Map view: the map, and the shared filmstrip under it when it is on (View ▸ +/// Filmstrip, `/`), as in Detail. Photos dragged from the filmstrip onto the map get +/// the drop point's position (`photo.setGps`, one undo step). 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 { + let t = Tokens::get(ui.ctx()); + let full = ui.available_rect_before_wrap(); + app.map_drawn = MapDrawn::default(); + if full.width() <= 10.0 || full.height() <= 10.0 { return; } + // the filmstrip takes the bottom, unless the window is too short to leave a map above it + let show_film = app.ui.filmstrip && !app.ui.fullscreen && full.height() - t.film_h >= 2.0 * TOOLBAR_H; + let film_h = if show_film { t.film_h } else { 0.0 }; + let rect = Rect::from_min_max(full.min, pos2(full.right(), full.bottom() - film_h)); + if show_film { + crate::panels::detail::filmstrip(app, ui, Rect::from_min_max(pos2(full.left(), rect.bottom()), full.max)); + } + app.map_drawn.filmstrip = show_film; 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 }); @@ -104,52 +157,24 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // Tiles (the service is asked for the view plus one ring) tiles::draw(&mut app.session, &painter, canvas_rect, center, zoom, 1); + app.map_drawn.canvas = Some(canvas_rect); + + // Photos carried from the filmstrip: a pin with their count follows the pointer over the map; + // a release there sets their position (overwriting one they had). + let drop = drop_photos(app, ui, canvas_rect, map_ui.show_filter_bar, |p| drop_point(p, screen_center, zoom, center)); // 2. Fetch and Cluster Candidate Photos let candidate_photos = collect_photos(app, map_ui.filter, |p| screen_to_lat_lon(p, zoom, center), canvas_rect); let clusters = cluster_photos(&candidate_photos, |coord| lat_lon_to_screen(coord, zoom, center), 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(max_zoom); - zoom_target = Some((cluster.lat_lon, next_z)); - } - } - } - + let PinInput { clicked, double_clicked_photo, zoom_target } = draw_pins(app, ui, &painter, &clusters, zoom, max_zoom); 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((ids, m)) = clicked { + select_pin(app, ui, &ids, m, &mut map_ui); } if let Some(id) = double_clicked_photo { let _ = app.run("library.select", json!({"ids": [id.0]})); @@ -183,6 +208,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } + if let Some((n, at, _)) = drop { + drop_indicator(&painter, &t, at, n); + } + app.map_drawn.drop = drop; + // 5. Top Location Filter Bar & Breadcrumb if map_ui.show_filter_bar { render_top_filter_bar(app, ui, canvas_rect, &mut map_ui, center); @@ -208,6 +238,60 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { app.ui.map = map_ui; } +/// What the pointer did to the pins this frame. +struct PinInput { + /// A pin's photos (a cluster: all of them) and the click's modifiers. + clicked: Option<(Vec, egui::Modifiers)>, + double_clicked_photo: Option, + /// A double-clicked cluster: zoom in on it. + zoom_target: Option<(LatLon, f64)>, +} + +/// Draw the pins and clusters (selected ones highlighted, a cluster with its selected count), +/// record them for `map.state` and read their clicks. +fn draw_pins(app: &mut LightcraftApp, ui: &egui::Ui, painter: &Painter, clusters: &[MapCluster], zoom: f64, max_zoom: f64) -> PinInput { + let mut input = PinInput { clicked: None, double_clicked_photo: None, zoom_target: None }; + // while photos are carried over the map, pins are not hovered or clicked (the drop is) + let carrying = app.ui.dragging_photos.is_some(); + for cluster in clusters { + let marker_rect = Rect::from_center_size(cluster.center, vec2(32.0, 32.0)); + let is_hovered = !carrying && ui.rect_contains_pointer(marker_rect); + app.map_drawn.pins.push(DrawnPin { ids: cluster.photos.iter().map(|p| p.0).collect(), selected: cluster.selected, at: cluster.center }); + if let Some(first) = cluster.photos.first() { + crate::widgets::register(ui, format!("map:pin:{}", first.0), marker_rect); + } + let click = is_hovered && ui.input(|i| i.pointer.primary_clicked()); + let double = is_hovered && ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)); + if let [photo_id] = cluster.photos[..] { + render_single_pin(painter, cluster.center, cluster.selected > 0, is_hovered); + if double { + input.double_clicked_photo = Some(photo_id); + } + } else { + render_cluster_badge(painter, cluster.center, cluster.photos.len(), cluster.selected, is_hovered); + if double { + input.zoom_target = Some((cluster.lat_lon, (zoom + 2.0).min(max_zoom))); + } + } + if click { + input.clicked = Some((cluster.photos.clone(), ui.input(|i| i.modifiers))); + } + } + input +} + +/// A click on a pin selects its photos (a cluster: all of them, the first active), so the +/// filmstrip shows them selected and scrolls to the active one; Cmd/Ctrl adds them instead. +fn select_pin(app: &mut LightcraftApp, ui: &egui::Ui, ids: &[PhotoId], m: egui::Modifiers, map_ui: &mut crate::state::MapUi) { + let Some(&first) = ids.first() else { return }; + map_ui.active_pin_photo = Some(first); + let mode = if m.command { "add" } else { "replace" }; + let raw: Vec = ids.iter().map(|p| p.0).collect(); + if let Err(e) = app.run("library.select", json!({"ids": raw, "active": first.0, "mode": mode})) { + app.toast(ui.ctx(), e); + } +} + fn collect_photos(app: &mut LightcraftApp, filter: LocationFilter, screen_to_lat_lon: F, canvas: Rect) -> Vec<(PhotoId, LatLon, bool)> where F: Fn(Pos2) -> LatLon, @@ -261,16 +345,14 @@ where for c in &mut clusters { if c.center.distance(pos) <= CLUSTER_RADIUS_PTS { c.photos.push(id); - if is_selected { - c.has_selected = true; - } + c.selected += usize::from(is_selected); merged = true; break; } } if !merged { - clusters.push(MapCluster { center: pos, lat_lon: coord, photos: vec![id], has_selected: is_selected }); + clusters.push(MapCluster { center: pos, lat_lon: coord, photos: vec![id], selected: usize::from(is_selected) }); } } clusters @@ -296,7 +378,10 @@ fn render_single_pin(p: &Painter, pos: Pos2, selected: bool, hovered: bool) { 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) { +/// A cluster's badge: its photo count, yellow when some of them are selected, and then a small +/// bubble at its top right with how many are selected. +fn render_cluster_badge(p: &Painter, pos: Pos2, count: usize, selected_count: usize, hovered: bool) { + let selected = selected_count > 0; 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) }); @@ -308,6 +393,75 @@ fn render_cluster_badge(p: &Painter, pos: Pos2, count: usize, selected: bool, ho 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); + if selected { + let text = selected_count.to_string(); + let w = (text.len() as f32 * 6.5 + 8.0).max(16.0); + let bubble = Rect::from_center_size(pos2(badge_rect.right() - 2.0, badge_rect.top() - 2.0), vec2(w, 16.0)); + p.rect_filled(bubble, 8.0, SELECTED_BUBBLE); + p.rect_stroke(bubble, 8.0, Stroke::new(1.0, Color32::WHITE), StrokeKind::Inside); + p.text(bubble.center(), Align2::CENTER_CENTER, text, FontId::proportional(10.0), Color32::WHITE); + } +} + +/// The selected-count bubble on a cluster (dark, so it reads on the yellow badge and the map). +const SELECTED_BUBBLE: Color32 = Color32::from_rgb(30, 110, 230); + +/// Where on the map screen point `at` is, for a drop: the longitude wraps around the world (the +/// map repeats sideways at low zoom) and the latitude stays inside Web Mercator's ±85.05°. +fn drop_point(at: Pos2, screen_center: Pos2, zoom: f64, center: LatLon) -> LatLon { + let z = if zoom.is_finite() { zoom.clamp(0.0, 24.0) } else { 0.0 }; + let n = 2.0_f64.powf(z); + let (cx, cy) = center.to_tile_coords(z); + let x = (cx + f64::from(at.x - screen_center.x) / f64::from(TILE_SIZE)).rem_euclid(n); + let y = (cy + f64::from(at.y - screen_center.y) / f64::from(TILE_SIZE)).clamp(0.0, n); + let p = LatLon::from_tile_coords(x, y, z); + let lat = p.lat.clamp(-lightcraft_engine::map::MAX_LATITUDE, lightcraft_engine::map::MAX_LATITUDE); + LatLon { lat: if lat.is_finite() { lat } else { 0.0 }, lon: if p.lon.is_finite() { p.lon } else { 0.0 } } +} + +/// Photos carried from the filmstrip over the map (not over its filter bar or +/// toolbar): returns how many, the pointer and where they would land, and on the release frame +/// sets their position there (`photo.setGps`, one undo step, overwriting a position they had). +fn drop_photos( + app: &mut LightcraftApp, + ui: &egui::Ui, + canvas: Rect, + filter_bar: bool, + place: impl Fn(Pos2) -> LatLon, +) -> Option<(usize, Pos2, LatLon)> { + let ids = app.ui.dragging_photos.clone()?; + let top = if filter_bar { canvas.top() + 50.0 } else { canvas.top() }; + let zone = Rect::from_min_max(pos2(canvas.left(), top), pos2(canvas.right(), canvas.bottom() - TOOLBAR_H)); + let at = ui.input(|i| i.pointer.latest_pos()).filter(|p| zone.contains(*p))?; + let to = place(at); + if ui.input(|i| i.pointer.primary_released()) { + app.ui.dragging_photos = None; + if let Err(e) = app.run("photo.setGps", json!({"ids": ids, "lat": to.lat, "lon": to.lon})) { + app.toast(ui.ctx(), e); + } + return None; + } + let n = ids.len(); + let hint = if n == 1 { + crate::i18n::tr("Set the location of this photo").to_string() + } else { + crate::i18n::tr_format!("Set the location of {n} photos", n = n) + }; + crate::panels::grid::drag_hint(ui.ctx(), hint); + Some((n, at, to)) +} + +/// Where carried photos would land: a pin at the point with the photo count, and a ring. +fn drop_indicator(p: &Painter, t: &Tokens, at: Pos2, n: usize) { + p.circle_stroke(at, 20.0, Stroke::new(2.0, t.accent.gamma_multiply(0.8))); + render_single_pin(p, at, true, true); + if n > 1 { + let text = if n > 9999 { format!("{}k", n / 1000) } else { n.to_string() }; + let w = (text.len() as f32 * 6.5 + 10.0).max(18.0); + let bubble = Rect::from_center_size(pos2(at.x + 12.0, at.y - 22.0), vec2(w, 16.0)); + p.rect_filled(bubble, 8.0, t.accent); + p.text(bubble.center(), Align2::CENTER_CENTER, text, FontId::proportional(10.5), Color32::WHITE); + } } fn render_top_filter_bar(_app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect, map_ui: &mut crate::state::MapUi, center: LatLon) { @@ -655,9 +809,9 @@ mod tests { 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[0].selected, 1); assert_eq!(clusters[1].photos.len(), 1); - assert!(!clusters[1].has_selected); + assert_eq!(clusters[1].selected, 0); } #[test] diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index f801ee843f..8d8da4c580 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -59,6 +59,7 @@ mod library_problem; mod lifecycle_037; mod lightroom_destination; mod lights_out; +mod map_filmstrip; mod mask_effects; mod masking; mod masking_layout; diff --git a/crates/ui-egui/src/tests/map_filmstrip.rs b/crates/ui-egui/src/tests/map_filmstrip.rs new file mode 100644 index 0000000000..96c09d322e --- /dev/null +++ b/crates/ui-egui/src/tests/map_filmstrip.rs @@ -0,0 +1,262 @@ +//! The Map view's filmstrip (LRC-MAP-VIEW, LRC-MAP-GEOTAG): it is drawn under the map and +//! toggled like Detail's, the bottom bar offers the toggle instead of the grid's thumbnail size, +//! photos dragged from it onto the map get the drop point's position in one undo step, and the +//! selection shows both ways (selected pins and clusters on the map, a pin click selecting in +//! the strip). The map is never online in tests: no tiles are fetched. + +use egui::{Pos2, Rect}; +use lightcraft_catalog::PhotoId; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +/// The demo library in the Map view at 1300 × 1000, the map centred on `lat, lon` at `zoom`. +fn map_at(lat: f64, lon: f64, zoom: f64) -> Headless { + map_sized(lat, lon, zoom, [1300.0, 1000.0]) +} + +fn map_sized(lat: f64, lon: f64, zoom: f64, size: [f32; 2]) -> Headless { + let session = lightcraft_engine::Session::with_demo(); + let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), size, 1.0); + h.app.run("view.map", json!({})).unwrap(); + h.app.ui.map.center_lat = lat; + h.app.ui.map.center_lon = lon; + h.app.ui.map.zoom = zoom; + frames(&mut h, 6); + h +} + +fn frames(h: &mut Headless, n: usize) { + for _ in 0..n { + h.step(); + } +} + +fn widget(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +fn state(h: &mut Headless) -> Value { + h.app.run("map.state", json!({})).unwrap() +} + +fn canvas(s: &Value) -> Rect { + let c = &s["canvas"]; + let f = |k: &str| c[k].as_f64().unwrap_or_else(|| panic!("canvas.{k}: {s}")) as f32; + Rect::from_min_size(egui::pos2(f("x"), f("y")), egui::vec2(f("width"), f("height"))) +} + +fn gps(h: &Headless, id: u64) -> Option<(f64, f64)> { + h.app.session.catalog.photo(PhotoId(id)).and_then(|p| p.meta.gps) +} + +fn set_gps(h: &mut Headless, ids: &[u64], lat: f64, lon: f64) { + h.app.run("photo.setGps", json!({"ids": ids, "lat": lat, "lon": lon})).unwrap(); +} + +fn press(h: &mut Headless, at: Pos2, pressed: bool) { + h.app.synthetic.push(egui::Event::PointerMoved(at)); + h.step(); + h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); +} + +fn glide(h: &mut Headless, from: Pos2, to: Pos2) { + for i in 1..=10 { + h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 10.0))); + h.step(); + } +} + +fn selected(h: &Headless) -> Vec { + let mut v: Vec = h.app.session.selection.ids.iter().map(|p| p.0).collect(); + v.sort_unstable(); + v +} + +/// The pin or cluster holding `id` in `map.state`. +fn pin_of(s: &Value, id: u64) -> Value { + s["pins"] + .as_array() + .and_then(|pins| pins.iter().find(|p| p["ids"].as_array().is_some_and(|ids| ids.iter().any(|i| i.as_u64() == Some(id))))) + .cloned() + .unwrap_or_else(|| panic!("{id} has a pin: {s}")) +} + +fn xy(p: &Value) -> Pos2 { + egui::pos2(p["x"].as_f64().unwrap_or(0.0) as f32, p["y"].as_f64().unwrap_or(0.0) as f32) +} + +#[test] +fn the_map_view_draws_the_filmstrip_and_view_filmstrip_toggles_it() { + let mut h = map_at(30.0, 0.0, 3.0); + assert!(h.app.ui.filmstrip, "the filmstrip is on by default"); + let s = state(&mut h); + assert_eq!(s["filmstrip"], true, "{s}"); + let strip = widget(&h, "filmstrip").expect("the filmstrip is drawn in the Map view"); + let map = canvas(&s); + assert!(map.bottom() <= strip.top() + 0.5, "the map ends above the strip: {map:?} {strip:?}"); + let first = h.app.session.visible_cloned()[0].0; + assert!(widget(&h, &format!("film:{first}")).is_some(), "its thumbnails are there"); + // the bottom bar: the Filmstrip toggle, not the grid's thumbnail size + assert!(widget(&h, "icon:filmstrip").is_some(), "the bottom bar has the Filmstrip toggle"); + assert!(widget(&h, "slider:thumbSize").is_none(), "no thumbnail-size slider on the map"); + + h.app.run("view.filmstrip", json!({})).unwrap(); + frames(&mut h, 3); + let s = state(&mut h); + assert_eq!(s["filmstrip"], false); + assert!(widget(&h, "filmstrip").is_none(), "hidden"); + assert!(canvas(&s).bottom() > map.bottom() + 100.0, "the map takes the room back"); + // the toggle in the bottom bar brings it back + let toggle = widget(&h, "icon:filmstrip").expect("toggle").center(); + press(&mut h, toggle, true); + press(&mut h, toggle, false); + frames(&mut h, 3); + assert!(h.app.ui.filmstrip && widget(&h, "filmstrip").is_some(), "shown again"); + + // the grid keeps its thumbnail size + h.app.run("view.photoGrid", json!({})).unwrap(); + frames(&mut h, 3); + assert!(widget(&h, "slider:thumbSize").is_some()); + // and map.state no longer reports the map's last frame + let s = state(&mut h); + assert!(s["canvas"].is_null() && s["shown"] == false && s["filmstrip"] == false, "{s}"); +} + +#[test] +fn dragging_filmstrip_photos_onto_the_map_sets_their_gps_in_one_undo_step() { + let mut h = map_at(30.0, 0.0, 3.0); + let v = h.app.session.visible_cloned(); + let (a, b) = (v[0].0, v[1].0); + // b already has a position elsewhere: a drop overwrites it, as Lightroom does + set_gps(&mut h, &[b], -33.9, 151.2); + h.app.run("library.select", json!({"ids": [a, b]})).unwrap(); + frames(&mut h, 4); + let steps = h.app.session.undo.len(); + let from = widget(&h, &format!("film:{a}")).expect("a's thumbnail").center(); + let map = canvas(&state(&mut h)); + let to = map.center() + egui::vec2(120.0, -80.0); + press(&mut h, from, true); + glide(&mut h, from, to); + // while they are over the map: a pin with their count at the pointer, nothing changed yet + let s = state(&mut h); + assert_eq!(s["drop"]["count"], 2, "{s}"); + assert!((s["drop"]["x"].as_f64().unwrap_or(0.0) - f64::from(to.x)).abs() < 0.5, "{s}"); + let (lat, lon) = (s["drop"]["lat"].as_f64().unwrap(), s["drop"]["lon"].as_f64().unwrap()); + assert!((-85.06..=85.06).contains(&lat) && (-180.0..=180.0).contains(&lon), "{lat} {lon}"); + assert_eq!((gps(&h, a), gps(&h, b)), (None, Some((-33.9, 151.2))), "nothing changes before the drop"); + press(&mut h, to, false); + frames(&mut h, 2); + for id in [a, b] { + let g = gps(&h, id).expect("placed"); + assert!((g.0 - lat).abs() < 1e-6 && (g.1 - lon).abs() < 1e-6, "{id}: {g:?} vs {lat} {lon}"); + } + assert!(h.app.ui.dragging_photos.is_none(), "the drag ended"); + assert!(state(&mut h)["drop"].is_null()); + assert_eq!(h.app.session.undo.len(), steps + 1, "one undo step for both"); + assert_eq!(h.app.session.undo.last().map(|u| u.label.clone()).as_deref(), Some("Set GPS Coordinates")); + // they are now one pin, where they were dropped + let pin = pin_of(&state(&mut h), a); + assert_eq!(pin["count"], 2, "{pin}"); + assert!(xy(&pin).distance(to) < 40.0, "{pin} vs {to:?}"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!((gps(&h, a), gps(&h, b)), (None, Some((-33.9, 151.2))), "undo puts both back"); +} + +/// Released over the map's toolbar (not the map) or carrying photos that are gone: nothing +/// changes or an error is shown, never a crash. +#[test] +fn a_drop_outside_the_map_or_of_missing_photos_changes_nothing() { + let mut h = map_at(30.0, 0.0, 3.0); + let a = h.app.session.visible_cloned()[0].0; + let from = widget(&h, &format!("film:{a}")).expect("a's thumbnail").center(); + let map = canvas(&state(&mut h)); + let toolbar = egui::pos2(map.center().x, map.bottom() - 10.0); + let steps = h.app.session.undo.len(); + press(&mut h, from, true); + glide(&mut h, from, toolbar); + assert!(state(&mut h)["drop"].is_null(), "no drop over the toolbar"); + press(&mut h, toolbar, false); + frames(&mut h, 2); + assert_eq!(gps(&h, a), None); + assert_eq!(h.app.session.undo.len(), steps); + assert!(h.app.ui.dragging_photos.is_none()); + + // photos deleted while carried: the drop reports it + let at = map.center(); + h.app.synthetic.push(egui::Event::PointerMoved(at)); + h.step(); + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }); + h.app.ui.dragging_photos = Some(vec![987_654_321]); + h.step(); + h.app.ui.dragging_photos = Some(vec![987_654_321]); + h.app.synthetic.push(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + frames(&mut h, 2); + assert!(h.app.ui.dragging_photos.is_none()); + assert_eq!(h.app.session.undo.len(), steps); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("no such photo")), "{:?}", h.app.ui.toast); +} + +#[test] +fn selected_photos_are_marked_on_the_map_and_a_pin_click_selects_them_in_the_filmstrip() { + // narrow, so the strip shows only the first few photos + let mut h = map_sized(48.0, 2.0, 5.0, [900.0, 900.0]); + let v = h.app.session.visible_cloned(); + let n = v.len(); + assert!(n >= 12, "the demo library is long enough to scroll the strip: {n}"); + // the last three photos (off screen) close together, one alone further away + let group = [v[n - 3].0, v[n - 2].0, v[n - 1].0]; + let alone = v[3].0; + set_gps(&mut h, &group[..1], 48.8584, 2.2945); + set_gps(&mut h, &group[1..2], 48.8606, 2.3376); + set_gps(&mut h, &group[2..], 48.8530, 2.3499); + set_gps(&mut h, &[alone], 45.76, 4.84); + h.app.run("library.select", json!({"ids": [group[1]]})).unwrap(); + frames(&mut h, 4); + let s = state(&mut h); + let cluster = pin_of(&s, group[0]); + assert_eq!((cluster["count"].clone(), cluster["selected"].clone()), (json!(3), json!(1)), "the cluster shows 1 of 3 selected: {s}"); + assert_eq!(pin_of(&s, alone)["selected"], 0, "{s}"); + let strip = widget(&h, "filmstrip").expect("strip"); + let off = |h: &Headless, id: u64| widget(h, &format!("film:{id}")).is_none_or(|r| !strip.contains(r.center())); + // selecting in the strip marks the pin + h.app.run("library.select", json!({"ids": [alone]})).unwrap(); + frames(&mut h, 4); + assert!(off(&h, group[0]), "the group's thumbnails start off screen"); + let s = state(&mut h); + assert_eq!(pin_of(&s, alone)["selected"], 1, "{s}"); + assert_eq!(pin_of(&s, group[0])["selected"], 0, "{s}"); + + // a click on the cluster selects its photos; the strip scrolls to the active one + let at = xy(&pin_of(&s, group[0])); + press(&mut h, at, true); + press(&mut h, at, false); + frames(&mut h, 8); + let mut want = group.to_vec(); + want.sort_unstable(); + assert_eq!(selected(&h), want, "the cluster's photos are selected"); + let active = h.app.session.selection.active.map(|p| p.0).expect("an active photo"); + assert!(group.contains(&active)); + assert!(!off(&h, active), "the filmstrip scrolled to the active photo"); + assert_eq!(pin_of(&state(&mut h), group[0])["selected"], 3); + // a single pin's click selects just that photo + let at = xy(&pin_of(&state(&mut h), alone)); + frames(&mut h, 30); + press(&mut h, at, true); + press(&mut h, at, false); + frames(&mut h, 3); + assert_eq!(selected(&h), vec![alone]); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5abaed6ba9..9cdae4021f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -111,6 +111,8 @@ filmstrip is visible. | `engine.execute {command: "map.providers"}` | — | The tile sources the map offers now → `[{id, label, maxZoom, attribution, offline, current}]` | | `engine.execute {command: "map.cacheInfo"}` | — | The on-disk tile cache → `{bytes, tiles, capBytes, dir}` (`dir` null: no disk cache) | | `engine.execute {command: "map.clearCache"}` | — | Deletes every cached tile (all sources) → `{bytes, tiles, dir}` deleted | +| `engine.execute {command: "map.state"}` | — | The Map view as drawn last frame (app only) → `{lat, lon, zoom, shown, canvas: {x, y, width, height}, filmstrip, pins: [{ids, count, selected, x, y}], drop: {count, x, y, lat, lon}}`; `selected` is how many of a pin's photos are selected, `drop` the photos carried over the map (null otherwise) | +| `engine.execute {command: "photo.setGps"}` | `{ids?, lat, lon}` | Sets the photos' position (default: the selection), one undo step "Set GPS Coordinates"; lat −90…90, lon wrapped into −180…180, unknown ids refused → `{updated, lat, lon}`; what a drop on the Map view runs | | `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | diff --git a/docs/gaps.md b/docs/gaps.md index 76c3adfaac..a93ef6b2ba 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 view, saved locations and filter ✅ (OpenStreetMap / OpenTopoMap / custom tiles under the OSM tile policy; Esri off, see docs/map.md); geotag 🟡 (no drag onto the 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 view, saved locations and filter ✅ (OpenStreetMap / OpenTopoMap / custom tiles under the OSM tile policy; Esri off, see docs/map.md); geotag 🟡 (filmstrip photos drop onto the map; no pin move or Remove GPS menu yet); 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/map.md b/docs/map.md index 967374c746..00a3008102 100644 --- a/docs/map.md +++ b/docs/map.md @@ -5,6 +5,34 @@ This page describes where the map's tiles come from, what is sent over the netwo behind it. Later sections (pins and clusters, the Info panel map, geotagging, the location filter, saved locations, track logs, keys and menus) are filled in as those parts land. +## Map view + +The filmstrip runs under the map, as in Detail: View ▸ Filmstrip, `/` (F6), or the Filmstrip button at the +right of the bottom bar, which in the Map view takes the place of the grid's thumbnail size. It shows the +same photos as the grid. The selection shows both ways: + +- Selected photos' pins are yellow. A cluster holding selected photos is yellow and carries a small blue + bubble with how many of its photos are selected. +- A click on a pin selects its photo; a click on a cluster selects all its photos, the first one active. + The filmstrip shows them selected and scrolls to the active one. ⌘-click (Ctrl-click) adds them to the + selection instead. A double-click on a pin opens Detail; on a cluster it zooms in. + +`map.state` reports the view (`lat`, `lon`, `zoom`), the map canvas, whether the filmstrip is drawn, every pin +or cluster drawn in the last frame (`ids`, `count`, `selected`, screen `x` / `y`) and a drop in progress. + +## Geotagging + +Drag photos from the filmstrip onto the map to set where they were taken. The drag carries the selection, +or only the photo dragged when it isn't selected. While they are over the map a pin with their count +follows the pointer; release to give every one of them that point's position, overwriting a position they +had. That is one undo step, "Set GPS Coordinates" (`photo.setGps`). A release over the map's toolbar or +location filter bar, or outside the map, changes nothing. Drops are limited to the map's ±85.05° latitude +(the edge of the Web Mercator projection); the longitude of a drop on the world's repeat at low zoom is +wrapped into −180…180. + +Not yet: moving a pin by dragging it, Lock Markers stopping that, and Remove GPS Coordinates in the Photo +menu and a pin's menu (`photo.clearGps` removes a position today). + ## Tile sources and cache The tiles are raster images in the Web Mercator projection (256 px, zoom 0–19). Where they come from is a @@ -95,6 +123,9 @@ GeoNames). Choose Offline to fetch nothing. | `map.providers` | The sources offered now, with credit and max zoom | | `map.cacheInfo` | `{bytes, tiles, capBytes, dir}` of the tile cache | | `map.clearCache` | Deletes every cached tile | +| `map.state` | The view, the pins drawn (with how many of their photos are selected) and a drop in progress (app only) | +| `photo.setGps` | `{ids?, lat, lon}`: sets the position of the photos (default: the selection), one undo step; lat −90…90, lon wrapped into −180…180; unknown ids are refused | +| `photo.clearGps` | `{ids?}`: removes the position of the photos, one undo step | The tile core (Web Mercator maths, source checks, cache, fetch queue) is ported from PR #797 by Jason Baldwin. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 79aa6d1f08..ccba0cdf38 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -737,8 +737,8 @@ 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 | ✅ | `cmd:view.map`, `cmd:map.providers`, `cmd:map.tileSource`, `cmd:map.cacheInfo`, `cmd:map.clearCache`, `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/engine/src/map/service.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/panels/map/tiles.rs`, `docs/map.md` | Interactive slippy map; tiles from OpenStreetMap (default), OpenTopoMap, a custom `https://` template, or Offline (`map.tileSource`, saved per library), fetched under the OSM tile usage policy (view plus one ring, 2 requests at a time, backoff and `Retry-After`, LightCraft User-Agent, on-disk cache honouring Cache-Control/Expires/ETag, 500 MB LRU, activity row); the Esri layers are off (their terms, `docs/map.md`); credit always shown; missing tiles drawn from a parent tile; photo marker clustering with cluster badges and count (screen-space, regroups on pan); single-pin selection & loupe popover; top location filter bar (Visible On Map, Tagged, Untagged, None); bottom toolbar with Map Style list, zoom slider and lock toggle; 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` | `photo.setGps` sets latitude / longitude and `photo.clearGps` removes them, one undo step each. Missing: dragging photos from the grid or filmstrip onto the map, and moving a pin | +| LRC-MAP-VIEW | Map view | P2 | ✅ | `cmd:view.map`, `cmd:map.providers`, `cmd:map.tileSource`, `cmd:map.cacheInfo`, `cmd:map.clearCache`, `cmd:map.savedLocations.list`, `cmd:map.savedLocations.create`, `cmd:map.savedLocations.delete`, `cmd:map.filterPhotos`, `cmd:photo.setGps`, `cmd:photo.clearGps`, `cmd:map.state`, `cmd:view.filmstrip`, `crates/geom/src/geo.rs`, `crates/engine/src/map.rs`, `crates/engine/src/map/service.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/panels/map/tiles.rs`, `crates/ui-egui/src/tests/map_filmstrip.rs`, `docs/map.md` | Interactive slippy map; tiles from OpenStreetMap (default), OpenTopoMap, a custom `https://` template, or Offline (`map.tileSource`, saved per library), fetched under the OSM tile usage policy (view plus one ring, 2 requests at a time, backoff and `Retry-After`, LightCraft User-Agent, on-disk cache honouring Cache-Control/Expires/ETag, 500 MB LRU, activity row); the Esri layers are off (their terms, `docs/map.md`); credit always shown; missing tiles drawn from a parent tile; photo marker clustering with cluster badges and count (screen-space, regroups on pan); the filmstrip under the map (View ▸ Filmstrip, `/`, and the bottom bar's toggle, which replaces the grid's thumbnail size there); selection shown both ways: selected pins yellow, a cluster with selected photos yellow with their count, and a click on a pin or cluster selects its photos in the filmstrip (which scrolls to the active one; ⌘/Ctrl adds them); `map.state` reports the pins drawn with their selected count; loupe popover; top location filter bar (Visible On Map, Tagged, Untagged, None); bottom toolbar with Map Style list, zoom slider and lock toggle; 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`, `crates/ui-egui/src/tests/map_filmstrip.rs` | Photos dragged from the Map view's filmstrip (the selection, or the photo alone when it isn't selected) and dropped on the map all get the drop point's position, overwriting one they had, in one undo step ("Set GPS Coordinates"); a pin with their count follows the pointer over the map; a release over the map's toolbar or filter bar changes nothing. `photo.setGps` wraps the longitude into −180…180, refuses a latitude out of range and ids the library doesn't have; `photo.clearGps` removes a position; one undo step each. Missing: moving a pin by dragging it, Lock Markers stopping that (and saved in `ui.json`), Remove GPS Coordinates in the Photo menu and a pin's menu, the XMP sidecar dropping a cleared or undone position | | 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 | @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-14 | patch | LRC-MAP-VIEW / LRC-MAP-GEOTAG: the Map view draws the filmstrip under the map (toggle in the bottom bar instead of the thumbnail size); photos dragged from it onto the map get the drop point's position in one undo step; selected photos are marked on the map and a pin click selects its photos in the filmstrip (`map.state`); `photo.setGps` wraps longitude and refuses unknown ids. Status unchanged (geotag stays 🟡: no pin move, Remove GPS menu or sidecar fix yet) | | 2026-11-14 | patch | LRC-MAP-VIEW: map tiles follow the OSM tile usage policy (view plus one ring, 2 requests at a time, backoff, `Retry-After`, LightCraft User-Agent, on-disk cache with ETag revalidation and a 500 MB cap, activity row); OpenTopoMap, custom and Offline sources (`map.tileSource`); the Esri layers are off (their terms require Esri software or an ArcGIS subscription; `docs/map.md`); status unchanged | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-05 | patch | LRC-LIB-CATALOG-LOCK: a library is written only to the folder it was opened from (on Unix, where the system gives a folder an identity, it is checked before every write of the catalog, settings, lock note and thumbnails; a share mounted over it, or a replaced folder, is refused and nothing is written; a folder that holds this session's lock note counts as the opened one, so a drive mounted again keeps saving; on Windows only that the path is still a folder is checked, so a replaced folder or a share mounted at the same path is not caught), a Move import removes its originals only once the catalog log is on disk, and dropping the lock removes only the owner note it wrote itself (#3240); status unchanged | From 1e0e814657e13777a9edc29a8640dea805b5355a Mon Sep 17 00:00:00 2001 From: "Bruno D." Date: Sun, 15 Nov 2026 18:14:32 -0500 Subject: [PATCH 12/51] LRC-MAP-VIEW: Esri map styles with the user's own ArcGIS API key - Esri Streets and Esri Outdoor (topographic) come from the ArcGIS Location Platform static basemap tiles service with the user's key (Settings > Map, map.setEsriKey); without a key they are not offered and map.tileSource refuses them, saying where to get one. The keyless arcgisonline endpoints are gone; World Imagery is dropped (no raster imagery style there). - Esri's 512 px tiles are cut into the four 256 px tiles they hold; one request serves all four. - The key is a secret: kept in the config folder (map-keys.json, 0600 on Unix), never journaled, logged, reported (esriKeySet only), used as a cache key or shown in errors ([key]); ApiKey's Debug hides it. - The map's credit is "Powered by Esri" plus the style's copyrightText from its metadata (bounded, plain text), else a fixed fallback. - docs/map.md records the endpoints, what was read and what could not be verified (attribution guide, platform agreement). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/map.rs | 37 +++- crates/engine/src/config.rs | 4 +- crates/engine/src/map.rs | 238 +++++++++++++++++---- crates/engine/src/map/service.rs | 207 +++++++++++++++++- crates/engine/src/map/source.rs | 143 +++++++++---- crates/engine/src/map/tests_service.rs | 114 ++++++++++ crates/engine/src/tests/map.rs | 63 ++++-- crates/ui-egui/locales/cs.json | 16 +- crates/ui-egui/locales/de.json | 16 +- crates/ui-egui/locales/es.json | 16 +- crates/ui-egui/locales/fi.json | 16 +- crates/ui-egui/locales/fr.json | 16 +- crates/ui-egui/locales/id.json | 16 +- crates/ui-egui/locales/it.json | 16 +- crates/ui-egui/locales/ja.json | 16 +- crates/ui-egui/locales/ka.json | 16 +- crates/ui-egui/locales/pl.json | 16 +- crates/ui-egui/locales/pt-br.json | 16 +- crates/ui-egui/locales/ru.json | 16 +- crates/ui-egui/locales/sv.json | 16 +- crates/ui-egui/locales/uk.json | 16 +- crates/ui-egui/locales/vi.json | 16 +- crates/ui-egui/locales/zh-hans.json | 16 +- crates/ui-egui/locales/zh-hant.json | 16 +- crates/ui-egui/src/dialogs/settings.rs | 8 +- crates/ui-egui/src/dialogs/settings/map.rs | 75 +++++++ crates/ui-egui/src/panels/map.rs | 7 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/map_esri.rs | 70 ++++++ docs/control-protocol.md | 3 +- docs/gaps.md | 2 +- docs/map.md | 90 ++++++-- docs/parity-checklist.md | 3 +- 33 files changed, 1180 insertions(+), 157 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/settings/map.rs create mode 100644 crates/ui-egui/src/tests/map_esri.rs diff --git a/crates/engine/src/cmd/map.rs b/crates/engine/src/cmd/map.rs index 528eb19874..4149ad5e64 100644 --- a/crates/engine/src/cmd/map.rs +++ b/crates/engine/src/cmd/map.rs @@ -64,18 +64,35 @@ fn source_json(s: &Session) -> Value { "id": used.id(), "label": used.label(), "urlTemplate": used.url_template(), - "attribution": used.attribution(), + "attribution": s.map.attribution(), "maxZoom": used.max_zoom(), "userAgent": used.user_agent(), "offline": used.is_offline(), "custom": matches!(used, TileSource::Custom { .. }), - // what prefs.json keeps, when the map can't use it (an Esri layer while Esri is off) + // what prefs.json keeps, when the map can't use it (an Esri layer without a key) "saved": (*chosen != used).then(|| chosen.id().to_string()), "notice": s.map.fallback_notice(), - "esriEnabled": s.map.esri_enabled(), + // whether an ArcGIS API key is set; the key itself is never reported + "esriKeySet": s.map.esri_key_set(), }) } +/// `map.setEsriKey {key}`: set the user's ArcGIS API key (`""` or null clears it). Checked for +/// shape only, no network call. Not journaled (a query spec), so the key never lands in the +/// journal; the reply and every error only say whether a key is set. +fn set_esri_key(s: &mut Session, p: &Value) -> Result { + const C: &str = "map.setEsriKey"; + let key = match p.get("key") { + None => return Err(bad(C, "give {key: \"\"} (\"\" clears it)")), + Some(Value::Null) => None, + Some(Value::String(k)) if k.trim().is_empty() => None, + Some(Value::String(k)) => Some(crate::map::ApiKey::parse(k).map_err(|e| bad(C, e))?), + Some(_) => return Err(bad(C, "`key` must be text")), + }; + s.map.set_esri_key(key).map_err(|e| EngineError::Other(format!("{C}: {e}")))?; + Ok(json!({"esriKeySet": s.map.esri_key_set(), "notice": s.map.fallback_notice()})) +} + fn opt_str<'a>(p: &'a Value, key: &str) -> Result> { match p.get(key) { None | Some(Value::Null) => Ok(None), @@ -192,16 +209,26 @@ fn clear_cache(s: &mut Session, _: &Value) -> Result { pub fn specs() -> Vec { vec![ - cmd!(query "map.providers", "Map Providers", [], None, "{} → [{id, label, maxZoom, attribution, offline, current}] — the tile sources the map offers now (the Esri layers are not offered: see docs/map.md); set one with map.tileSource", always, providers), + cmd!(query "map.providers", "Map Providers", [], None, "{} → [{id, label, maxZoom, attribution, offline, current}] — the tile sources the map offers now (the Esri layers only once an ArcGIS API key is set with map.setEsriKey: see docs/map.md); set one with map.tileSource", always, providers), cmd!( "map.tileSource", "Map Tile Source", [], None, - "{} → the map's tile source; set with {id: \"osm\" | \"opentopomap\" | \"offline\"}, {offline: true|false}, or {urlTemplate: \"https://…/{z}/{x}/{y}.png\", attribution: text, maxZoom?: 0–24, id?: cache-folder name [a-z0-9._-]}; fields alone change the current custom source. The Esri layers are refused (their terms, docs/map.md). Saved with the library preferences → {id, label, urlTemplate, attribution, maxZoom, userAgent, offline, custom, saved, notice, esriEnabled}", + "{} → the map's tile source; set with {id: \"osm\" | \"opentopomap\" | \"esri-streets\" | \"esri-topo\" | \"offline\"}, {offline: true|false}, or {urlTemplate: \"https://…/{z}/{x}/{y}.png\", attribution: text, maxZoom?: 0–24, id?: cache-folder name [a-z0-9._-]}; fields alone change the current custom source. The Esri layers need an ArcGIS API key (map.setEsriKey) and are refused without one. Saved with the library preferences → {id, label, urlTemplate, attribution, maxZoom, userAgent, offline, custom, saved, notice, esriKeySet}", always, tile_source ), + // a query spec on purpose: not journaled, so the key never reaches the journal + cmd!( + query "map.setEsriKey", + "Set ArcGIS API Key", + [], + None, + "{key: text | \"\" | null} → {esriKeySet, notice} — the ArcGIS Location Platform API key for the Esri map layers (free at https://location.arcgis.com); \"\" or null clears it. Shape-checked only (no network call); kept in the config folder's map-keys.json; never reported back", + always, + set_esri_key + ), cmd!(query "map.cacheInfo", "Map Cache Info", [], None, "{} → the map tile cache: {bytes, tiles, capBytes, dir (null = no disk cache)}", always, cache_info), cmd!( "map.clearCache", diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index 23f5c4ee1c..feedef0b0b 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -202,10 +202,12 @@ impl Session { } /// Fetch map tiles from the network and cache them in the shared default folder - /// ([`default_map_cache_dir`]). Without this a session never fetches tiles (tests). + /// ([`default_map_cache_dir`]), and keep the user's map API key in the config folder + /// (`map-keys.json`). Without this a session never fetches tiles and keeps no key (tests). pub fn with_default_map_cache(mut self) -> Self { self.map.cache_root = default_map_cache_dir(); self.map.online = true; + self.map.load_esri_key(config_dir().map(|d| d.join(crate::map::KEY_FILE))); self.map.reset_service(); self } diff --git a/crates/engine/src/map.rs b/crates/engine/src/map.rs index 764db50e95..f6f1976f24 100644 --- a/crates/engine/src/map.rs +++ b/crates/engine/src/map.rs @@ -7,7 +7,7 @@ //! OpenStreetMap tile usage policy (`docs/map.md`). A session has no cache folder and never goes //! online until the host asks ([`Session::with_default_map_cache`]), so tests stay hermetic. The offline source //! starts no service at all. Commands: `map.tileSource`, `map.providers`, `map.cacheInfo`, -//! `map.clearCache` (`cmd/map.rs`). +//! `map.clearCache`, `map.setEsriKey` (`cmd/map.rs`). //! //! The tile core (mercator, source validation, cache, service) is ported from PR #797 //! (Jason Baldwin), moved from its own crate into the engine. @@ -32,7 +32,7 @@ use crate::Session; pub use cache::{CacheInfo, DEFAULT_CACHE_BYTES, TileCache, TileMeta}; pub use mercator::{Bounds, MAX_LATITUDE, MAX_ZOOM, TILE_SIZE, TileKey, Viewport, VisibleTile, fit_bounds, from_gps}; pub use service::{HttpResponse, ServiceStats, TileEvent, TileImage, TileService, Transport}; -pub use source::{OSM_ATTRIBUTION, OSM_TILE_URL, TileSource, USER_AGENT}; +pub use source::{Crop, OSM_ATTRIBUTION, OSM_TILE_URL, TileSource, USER_AGENT}; /// What went wrong in the map core. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -53,20 +53,65 @@ pub(crate) fn now_secs() -> i64 { web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)).unwrap_or(0) } -/// Why the Esri layers can't be turned on: their terms (read 2026-11-14, `docs/map.md`) allow -/// them only with Esri software or an ArcGIS subscription, which LightCraft isn't and doesn't have. -pub const ESRI_UNAVAILABLE: &str = - "the Esri map layers are off: Esri's terms allow them only with Esri software or an ArcGIS subscription (see docs/map.md)"; +/// Where to get an ArcGIS API key, for messages. +pub const ESRI_KEY_HELP: &str = + "the Esri layers need your own ArcGIS Location Platform API key (Settings ▸ Map; a free one is at https://location.arcgis.com)"; + +/// Longest API key accepted (Esri's keys are a few hundred characters). +const MAX_KEY: usize = 2048; +/// Shortest API key accepted. +const MIN_KEY: usize = 20; +/// The file in the config folder that keeps the key (`docs/map.md`). +pub const KEY_FILE: &str = "map-keys.json"; + +/// The user's ArcGIS API key: a secret. Its `Debug` hides it, and nothing in the engine prints, +/// logs, caches by or reports it; only the tile service puts it in a request to Esri's host. +#[derive(Clone, PartialEq, Eq)] +pub struct ApiKey(String); + +impl std::fmt::Debug for ApiKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ApiKey(hidden)") + } +} + +impl ApiKey { + /// The key, checked for shape only (no network call): 20–2048 characters of `A–Z a–z 0–9 . _ -` + /// after trimming. The error never repeats the key. + pub fn parse(text: &str) -> Result { + let k = text.trim(); + let ok_chars = k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); + if !ok_chars || k.len() < MIN_KEY || k.len() > MAX_KEY { + return Err(format!( + "that doesn't look like an ArcGIS API key: it should be {MIN_KEY}–{MAX_KEY} characters of letters, digits, '.', '_' or '-'" + )); + } + Ok(ApiKey(k.to_string())) + } + + /// The key itself (for the request URL only). + pub(crate) fn secret(&self) -> &str { + &self.0 + } +} + +#[derive(Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct KeyFile { + #[serde(default, skip_serializing_if = "Option::is_none")] + esri_api_key: Option, +} /// The map's state in the session (see the module docs). #[derive(Debug)] pub struct MapState { - /// The tile source the user chose, saved in prefs.json as it is. An Esri source while Esri is - /// off is kept here (never overwritten) but not used: see [`MapState::effective_source`]. + /// The tile source the user chose, saved in prefs.json as it is. An Esri source without a key is + /// kept here (never overwritten) but not used: see [`MapState::effective_source`]. source: TileSource, - /// The Esri layers may be offered and fetched. Off, and no command turns it on: Esri's terms - /// don't allow LightCraft to use them (`docs/map.md`); only tests set it, to check the gate. - esri_enabled: bool, + /// The user's ArcGIS API key: the Esri layers are offered and fetched only with one. + esri_key: Option, + /// Where the key is kept (`/map-keys.json`); `None`: memory only (tests, the web). + pub key_file: Option, /// The tile cache folder (`/maptiles`, one folder per source inside); `None` = tiles /// are kept in memory only (tests, the web). pub cache_root: Option, @@ -80,7 +125,15 @@ pub struct MapState { impl Default for MapState { fn default() -> Self { - MapState { source: TileSource::Osm, esri_enabled: false, cache_root: None, cache_bytes: DEFAULT_CACHE_BYTES, online: false, service: None } + MapState { + source: TileSource::Osm, + esri_key: None, + key_file: None, + cache_root: None, + cache_bytes: DEFAULT_CACHE_BYTES, + online: false, + service: None, + } } } @@ -91,19 +144,19 @@ impl MapState { } /// The source the map draws and fetches: the chosen one, or OpenStreetMap while the chosen - /// one needs an opt-in that isn't given. + /// one needs a key that isn't set. pub fn effective_source(&self) -> TileSource { if self.usable(&self.source) { self.source.clone() } else { TileSource::Osm } } - /// Whether the Esri layers may be offered and fetched. - pub fn esri_enabled(&self) -> bool { - self.esri_enabled + /// An ArcGIS API key is set (the key itself is never reported). + pub fn esri_key_set(&self) -> bool { + self.esri_key.is_some() } - /// `source` may be used now (an Esri layer only with the opt-in). + /// `source` may be used now (an Esri layer only with a key). pub fn usable(&self, source: &TileSource) -> bool { - !source.requires_opt_in() || self.esri_enabled + !source.requires_key() || self.esri_key.is_some() } /// The built-in sources a picker offers: those usable now. @@ -113,14 +166,14 @@ impl MapState { /// A one-line notice while the chosen source can't be used (the map shows OpenStreetMap). pub fn fallback_notice(&self) -> Option { - (!self.usable(&self.source)).then(|| format!("The map shows OpenStreetMap instead of {}: {ESRI_UNAVAILABLE}.", self.source.label())) + (!self.usable(&self.source)).then(|| format!("The map shows OpenStreetMap instead of {}: {ESRI_KEY_HELP}.", self.source.label())) } /// Use `source` from now on (the next [`Session::map_tiles`] starts a service for it). An Esri - /// source while Esri is off is refused and nothing changes. + /// source without a key is refused and nothing changes. pub fn choose(&mut self, source: TileSource) -> Result<(), String> { if !self.usable(&source) { - return Err(format!("{}: {ESRI_UNAVAILABLE}", source.label())); + return Err(format!("{}: {ESRI_KEY_HELP}", source.label())); } if source != self.source { self.source = source; @@ -138,8 +191,8 @@ impl MapState { } /// Take the source a settings file stored, re-checked (it is hostile input): an unusable one - /// falls back to OpenStreetMap, with a log line. An Esri source while Esri is off is kept as - /// the choice (prefs.json keeps it) but the map shows OpenStreetMap; the returned notice says so. + /// falls back to OpenStreetMap, with a log line. An Esri source without a key is kept as the + /// choice (prefs.json keeps it) but the map shows OpenStreetMap; the returned notice says so. pub(crate) fn load_source(&mut self, stored: Option) -> Option { let source = match stored.map(|s| s.checked()) { None => TileSource::Osm, @@ -157,13 +210,44 @@ impl MapState { notice } - /// Let tests turn the Esri gate on (there is no command for it; see [`ESRI_UNAVAILABLE`]). - #[cfg(test)] - pub(crate) fn set_esri_enabled(&mut self, on: bool) { - if on != self.esri_enabled { - self.esri_enabled = on; + /// Set the ArcGIS API key (`None` clears it), keeping it in [`MapState::key_file`] when there + /// is one. Shape-checked only; nothing is sent anywhere. A key that can't be saved is not set. + pub fn set_esri_key(&mut self, key: Option) -> Result<(), String> { + if let Some(path) = &self.key_file { + let file = KeyFile { esri_api_key: key.as_ref().map(|k| k.secret().to_string()) }; + write_key_file(path, &file).map_err(|e| format!("can't save the API key in {}: {e}", path.display()))?; + } + if key != self.esri_key { + self.esri_key = key; self.reset_service(); } + Ok(()) + } + + /// Read the key kept in `path` (a missing file: no key). A damaged file or a key of the wrong + /// shape is ignored with a log line that never shows it. + pub(crate) fn load_esri_key(&mut self, path: Option) { + self.key_file = path; + let Some(path) = &self.key_file else { return }; + let bytes = match crate::read_file::read_regular(path, 64 * 1024) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return, + Err(e) => { + log::warn!("map: can't read {}: {e}", path.display()); + return; + } + }; + let key = match serde_json::from_slice::(&bytes) { + Ok(f) => { + f.esri_api_key.and_then(|k| ApiKey::parse(&k).map_err(|e| log::warn!("map: {}: the Esri key is ignored: {e}", path.display())).ok()) + } + Err(_) => { + log::warn!("map: {} isn't a key file; ignored", path.display()); + None + } + }; + self.esri_key = key; + self.reset_service(); } /// Stop the tile service (its threads end; the next use starts a fresh one). @@ -181,6 +265,31 @@ impl MapState { pub fn service(&self) -> Option<&TileService> { self.service.as_ref() } + + /// The credit to paint for the effective source: the running service's (an Esri layer's own + /// metadata once fetched), else the source's fixed one. + pub fn attribution(&self) -> String { + let source = self.effective_source(); + match self.service.as_ref().filter(|s| *s.source() == source) { + Some(s) => s.attribution(), + None => source.attribution().to_string(), + } + } +} + +/// Write the key file atomically, readable by its owner only where the system has such modes. +fn write_key_file(path: &std::path::Path, file: &KeyFile) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let data = serde_json::to_vec_pretty(file).map_err(std::io::Error::other)?; + lightcraft_catalog::safe_file::write_atomic(path, &data)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + Ok(()) } impl Session { @@ -199,7 +308,11 @@ impl Session { if m.service.as_ref().is_some_and(|s| *s.source() != source) { m.service = None; } - Some(m.service.get_or_insert_with(|| TileService::new(source, m.cache_root.clone(), m.cache_bytes, Some(activity), m.online))) + let token = if source.requires_key() { m.esri_key.clone() } else { None }; + Some( + m.service + .get_or_insert_with(|| TileService::new(source, m.cache_root.clone(), m.cache_bytes, Some(activity), m.online).with_token(token)), + ) } } @@ -281,25 +394,72 @@ mod tests { assert!(!loc.contains(LatLon { lat: 51.6000, lon: -0.1278 })); } + fn key() -> ApiKey { + ApiKey::parse("AAPK0123456789abcdef_TEST-key.x").unwrap() + } + #[test] - fn esri_is_neither_offered_nor_used_until_enabled() { + fn esri_is_neither_offered_nor_used_without_a_key() { let mut m = MapState::default(); - assert!(!m.esri_enabled()); - assert!(m.offered().iter().all(|s| !s.requires_opt_in()), "{:?}", m.offered()); - assert!(m.choose(TileSource::EsriImagery).unwrap_err().contains("Esri")); + assert!(!m.esri_key_set()); + assert!(m.offered().iter().all(|s| !s.requires_key()), "{:?}", m.offered()); + let e = m.choose(TileSource::EsriStreet).unwrap_err(); + assert!(e.contains("API key") && e.contains("location.arcgis.com"), "{e}"); assert_eq!(*m.source(), TileSource::Osm, "a refusal changes nothing"); // a saved Esri choice is kept but not used, with a notice let notice = m.load_source(Some(TileSource::EsriTopo)).unwrap(); - assert!(notice.contains("OpenStreetMap") && notice.contains("Esri"), "{notice}"); + assert!(notice.contains("OpenStreetMap") && notice.contains("API key"), "{notice}"); assert_eq!(*m.source(), TileSource::EsriTopo); assert_eq!(m.effective_source(), TileSource::Osm); - // the gate itself: with the opt-in the same choices are accepted and used - m.set_esri_enabled(true); + // with a key the same choices are offered, accepted and used + m.set_esri_key(Some(key())).unwrap(); assert_eq!(m.effective_source(), TileSource::EsriTopo); - assert!(m.offered().contains(&TileSource::EsriImagery)); - m.choose(TileSource::EsriImagery).unwrap(); + assert!(m.offered().contains(&TileSource::EsriStreet)); + m.choose(TileSource::EsriStreet).unwrap(); assert_eq!(m.fallback_notice(), None); - m.set_esri_enabled(false); + m.set_esri_key(None).unwrap(); assert_eq!(m.effective_source(), TileSource::Osm); } + + #[test] + fn keys_are_shape_checked_and_never_printed() { + let k = key(); + assert_eq!(format!("{k:?}"), "ApiKey(hidden)"); + let mut m = MapState::default(); + m.set_esri_key(Some(k.clone())).unwrap(); + assert!(!format!("{m:?}").contains(k.secret()), "Debug of the state hides the key"); + for bad in ["", "short", "has spaces in it 0123456789", "AAPK0123456789abcdef\nX", "ключ0123456789abcdefghij", &"a".repeat(3000)] { + let e = ApiKey::parse(bad).unwrap_err(); + assert!(bad.len() < 5 || !e.contains(bad), "the error doesn't repeat the key"); + } + assert_eq!(ApiKey::parse(" AAPK0123456789abcdef_TEST-key.x \n").unwrap(), k, "trimmed"); + } + + #[test] + fn the_key_file_round_trips_and_a_damaged_one_is_ignored() { + let dir = std::env::temp_dir().join(format!("lightcraft-map-key-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join(KEY_FILE); + let mut m = MapState::default(); + m.load_esri_key(Some(path.clone())); + assert!(!m.esri_key_set(), "no file: no key"); + m.set_esri_key(Some(key())).unwrap(); + let mut back = MapState::default(); + back.load_esri_key(Some(path.clone())); + assert!(back.esri_key_set()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + } + m.set_esri_key(None).unwrap(); + back.load_esri_key(Some(path.clone())); + assert!(!back.esri_key_set(), "cleared in the file too"); + for junk in [&b"not json"[..], br#"{"esriApiKey": "bad key"}"#, br#"{"esriApiKey": 5}"#] { + std::fs::write(&path, junk).unwrap(); + back.load_esri_key(Some(path.clone())); + assert!(!back.esri_key_set()); + } + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/engine/src/map/service.rs b/crates/engine/src/map/service.rs index da8d65f8f0..f25c679535 100644 --- a/crates/engine/src/map/service.rs +++ b/crates/engine/src/map/service.rs @@ -20,6 +20,11 @@ //! - **Hostile responses**: bodies over [`MAX_TILE_BYTES`], images that aren't PNG/JPEG/WebP of at //! most 1024 px, or that fail to decode are errors, never panics. //! +//! - **Keys stay secret**: a keyed source's API key ([`TileService::with_token`]) is added to the +//! request URL only; error messages, the cache (keyed by source id and tile) and the activity +//! row never carry it. +//! - **Credit**: a source with metadata (the Esri layers) has it fetched once, bounded and checked +//! ([`TileService::attribution`]); until then, or when it fails, the source's fixed credit shows. //! - **Visible**: while tiles are queued or loading, one "Loading map tiles" row is on the activity //! stack (`docs/background-tasks.md`); it goes when the queue is empty. //! @@ -37,8 +42,9 @@ use web_time::Instant; use super::cache::{TileCache, TileMeta}; use super::mercator::{TileKey, Viewport}; -use super::source::TileSource; +use super::source::{Crop, ESRI_POWERED_BY, TileSource, with_token}; use crate::activity::{Activity, Cancel, TaskGuard}; +use crate::map::ApiKey; /// Most tile requests on the wire at once. pub const MAX_IN_FLIGHT: usize = 2; @@ -57,6 +63,14 @@ const BACKOFF_START: Duration = Duration::from_secs(1); const BACKOFF_MAX: Duration = Duration::from_secs(300); /// Longest Retry-After honoured. const RETRY_AFTER_MAX: Duration = Duration::from_secs(3600); +/// Largest metadata answer accepted. +pub const MAX_METADATA_BYTES: usize = 64 * 1024; +/// Longest credit text taken from metadata. +const MAX_CREDIT: usize = 400; +/// Server tiles kept a moment after they arrive, so the four 256 px tiles cut from one 512 px tile +/// cost one request. +const RECENT_TILES: usize = 16; +const RECENT_FOR: Duration = Duration::from_secs(120); /// Worker threads: [`MAX_IN_FLIGHT`] for the network plus one so cache reads never wait behind it. const WORKERS: usize = MAX_IN_FLIGHT + 1; @@ -157,6 +171,60 @@ pub fn decode_tile(bytes: &[u8]) -> Result { Ok(TileImage { width, height, rgba: img.data.as_flattened().to_vec() }) } +/// The 256 px tile `crop` asks for, cut from (or scaled down from) the server's tile. +pub fn crop_tile(img: TileImage, crop: Crop) -> Result { + let bad = |m: String| crate::map::MapError::BadTile(m); + let (w, h) = (img.width as usize, img.height as usize); + if img.rgba.len() != w.saturating_mul(h).saturating_mul(4) { + return Err(bad("pixel data doesn't match the size".into())); + } + match crop { + Crop::Whole => Ok(img), + Crop::Quarter { right, bottom } => { + if w < 2 || h < 2 || w % 2 != 0 || h % 2 != 0 { + return Err(bad(format!("{w}×{h} can't be cut in quarters"))); + } + let (qw, qh) = (w / 2, h / 2); + let (x0, y0) = (if right { qw } else { 0 }, if bottom { qh } else { 0 }); + let mut rgba = Vec::with_capacity(qw * qh * 4); + for y in y0..y0 + qh { + let row = (y * w + x0) * 4; + rgba.extend_from_slice(img.rgba.get(row..row + qw * 4).ok_or_else(|| bad("tile row out of range".into()))?); + } + Ok(TileImage { width: qw as u32, height: qh as u32, rgba }) + } + Crop::Half => { + if w < 2 || h < 2 || w % 2 != 0 || h % 2 != 0 { + return Ok(img); + } + let (hw, hh) = (w / 2, h / 2); + let mut rgba = Vec::with_capacity(hw * hh * 4); + let px = |x: usize, y: usize, c: usize| u32::from(img.rgba.get((y * w + x) * 4 + c).copied().unwrap_or(0)); + for y in 0..hh { + for x in 0..hw { + for c in 0..4 { + let sum = px(2 * x, 2 * y, c) + px(2 * x + 1, 2 * y, c) + px(2 * x, 2 * y + 1, c) + px(2 * x + 1, 2 * y + 1, c); + rgba.push(((sum + 2) / 4) as u8); + } + } + } + Ok(TileImage { width: hw as u32, height: hh as u32, rgba }) + } + } +} + +/// The credit text in a layer's metadata answer: `copyrightText`, one line of plain text (no +/// markup) of at most 400 characters; anything else is refused. +pub fn metadata_credit(body: &[u8]) -> Option { + if body.len() > MAX_METADATA_BYTES { + return None; + } + let v: serde_json::Value = serde_json::from_slice(body).ok()?; + let t = v.get("copyrightText")?.as_str()?.trim(); + let ok = !t.is_empty() && t.chars().count() <= MAX_CREDIT && !t.chars().any(|c| c.is_control() || matches!(c, '<' | '>')); + ok.then(|| t.to_string()) +} + /// What [`TileService::poll`] reports. #[derive(Clone, Debug)] pub enum TileEvent { @@ -185,6 +253,18 @@ pub struct ServiceStats { pub in_memory: usize, /// Milliseconds until the host may be asked again (0 = not backing off). pub backoff_ms: u64, + /// Server tiles reused from a recent answer instead of a request. + pub reused: u64, +} + +/// Where the source's metadata (its credit) stands. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Meta { + #[default] + NotAsked, + Queued, + Running, + Done, } struct MemTile { @@ -221,6 +301,13 @@ struct State { row: Option, row_done: u64, activity: Option, + /// The API key added to requests (keyed sources), never anywhere else. + token: Option, + /// The credit from the source's metadata, and where fetching it stands. + credit: Option, + meta: Meta, + /// Recent server answers by URL (without key), newest last. + recent: VecDeque<(String, Instant, Arc)>, } impl State { @@ -300,6 +387,7 @@ impl std::fmt::Debug for TileService { enum Job { Disk(TileKey), Net(TileKey), + Meta, } impl TileService { @@ -323,6 +411,22 @@ impl TileService { TileService::with_transport(source, cache, transport).with_activity(activity) } + /// Add `token` (the user's API key) to this source's requests. Only to its tile and metadata + /// requests: never to messages, logs or the cache. + pub fn with_token(self, token: Option) -> TileService { + self.shared.lock().token = token; + self + } + + /// The credit to paint: for a source with metadata, "Powered by Esri" and the layer's own + /// `copyrightText` once fetched; otherwise (or until then) the source's fixed credit. + pub fn attribution(&self) -> String { + match &self.shared.lock().credit { + Some(c) => format!("{ESRI_POWERED_BY} | {c}"), + None => self.shared.source.attribution().to_string(), + } + } + /// Report loading on `activity` (one row while tiles are queued or loading). pub fn with_activity(self, activity: Option) -> TileService { self.shared.lock().activity = activity; @@ -397,6 +501,10 @@ impl TileService { st.failed.retain(|_, until| *until > now); let has_cache = self.shared.cache.is_some(); let can_fetch = self.shared.transport.is_some(); + // the credit: asked for once, with the first tiles + if can_fetch && !st.wanted.is_empty() && st.meta == Meta::NotAsked && self.shared.source.metadata_url().is_some() { + st.meta = Meta::Queued; + } for k in st.wanted.clone() { if st.busy.contains(&k) || st.disk_q.contains(&k) || st.net_q.contains(&k) || st.failed.contains_key(&k) { continue; @@ -484,6 +592,11 @@ fn next_job(sh: &Shared) -> Option { let backing_off = st.backoff_until.is_some_and(|u| u > now); // while the host is failing, one probe at a time let limit = if st.errors_in_row > 0 { 1 } else { MAX_IN_FLIGHT }; + if sh.transport.is_some() && st.meta == Meta::Queued && st.net_in_flight < limit && !backing_off { + st.meta = Meta::Running; + st.net_in_flight += 1; + return Some(Job::Meta); + } if sh.transport.is_some() && !st.net_q.is_empty() && st.net_in_flight < limit && !backing_off { // the most central tile of the newest view let best = st @@ -516,11 +629,22 @@ fn worker(sh: &Shared) { // a panic in a decoder or the transport is that tile's error, not a dead thread let key = match job { Job::Disk(k) | Job::Net(k) => k, + Job::Meta => { + let credit = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| meta_job(sh))).ok().flatten(); + let mut st = sh.lock(); + st.net_in_flight = st.net_in_flight.saturating_sub(1); + st.meta = Meta::Done; + st.credit = credit; + drop(st); + sh.wake.notify_all(); + continue; + } }; let net = matches!(job, Job::Net(_)); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match job { Job::Disk(k) => disk_job(sh, k), Job::Net(k) => net_job(sh, k), + Job::Meta => {} })); let mut st = sh.lock(); st.busy.remove(&key); @@ -541,11 +665,49 @@ fn worker(sh: &Shared) { } } +/// Fetch the source's metadata and take its credit (`None`: none usable; the fixed one shows). +fn meta_job(sh: &Shared) -> Option { + let (transport, url) = (sh.transport.as_ref()?, sh.source.metadata_url()?); + let token = sh.lock().token.clone(); + let full = match &token { + Some(t) => with_token(&url, t.secret()), + None => url.clone(), + }; + let headers = [("User-Agent", sh.source.user_agent().to_string())]; + match transport.get(&full, &headers, MAX_METADATA_BYTES, &sh.cancel) { + Ok(r) if r.status == 200 => metadata_credit(&r.body).or_else(|| { + log::warn!("map: {url}: no usable credit in the layer's metadata; showing the fixed one"); + None + }), + Ok(r) => { + log::warn!("map: {url}: HTTP {} for the layer's metadata; showing the fixed credit", r.status); + None + } + Err(e) => { + log::warn!("map: {url}: {}", hide(&e, token.as_ref())); + None + } + } +} + +/// `text` with the API key replaced, for messages (a transport error may quote the URL). +fn hide(text: &str, token: Option<&ApiKey>) -> String { + match token { + Some(t) if !t.secret().is_empty() => text.replace(t.secret(), "[key]"), + _ => text.to_string(), + } +} + +/// Decode a tile of the source and cut the 256 px tile `k` out of it. +fn decode_for(sh: &Shared, k: TileKey, bytes: &[u8]) -> Result { + crop_tile(decode_tile(bytes)?, sh.source.crop(k)) +} + /// Look `k` up in the cache: show it if there (and revalidate it if stale), else fetch it. fn disk_job(sh: &Shared, k: TileKey) { let now = crate::map::now_secs(); let cached = sh.cache.as_ref().and_then(|c| c.read(k)); - let decoded = cached.and_then(|c| match decode_tile(&c.bytes) { + let decoded = cached.and_then(|c| match decode_for(sh, k, &c.bytes) { Ok(img) => Some((img, c.meta)), Err(e) => { log::warn!("map: cached tile {k:?} doesn't decode ({e}); fetching it again"); @@ -593,8 +755,43 @@ fn net_job(sh: &Shared, k: TileKey) { if let Some(m) = &cached { headers.extend(m.conditional_headers()); } - sh.lock().stats.requests += 1; - let result = transport.get(&url, &headers, MAX_TILE_BYTES, &sh.cancel); + let token = sh.lock().token.clone(); + let cropped = sh.source.crop(k) != Crop::Whole; + // a server tile that just arrived for a neighbour (a 512 px tile holds four of ours) + let reuse = if cropped { + let mut st = sh.lock(); + let now = Instant::now(); + st.recent.retain(|(_, at, _)| now.saturating_duration_since(*at) < RECENT_FOR); + let hit = st.recent.iter().find(|(u, _, _)| *u == url).map(|(_, _, r)| HttpResponse::clone(r)); + if hit.is_some() { + st.stats.reused += 1; + } + hit + } else { + None + }; + let result = match reuse { + Some(r) => Ok(r), + None => { + sh.lock().stats.requests += 1; + let full = match &token { + Some(t) => with_token(&url, t.secret()), + None => url.clone(), + }; + let r = transport.get(&full, &headers, MAX_TILE_BYTES, &sh.cancel).map_err(|e| hide(&e, token.as_ref())); + if let Ok(resp) = &r + && resp.status == 200 + && cropped + { + let mut st = sh.lock(); + st.recent.push_back((url.clone(), Instant::now(), Arc::new(resp.clone()))); + while st.recent.len() > RECENT_TILES { + st.recent.pop_front(); + } + } + r + } + }; let now = crate::map::now_secs(); let fail = |st: &mut State, error: String, retry: bool| { st.stats.errors += 1; @@ -623,7 +820,7 @@ fn net_job(sh: &Shared, k: TileKey) { let header = |n: &str| resp.header(n); match resp.status { 200 => { - let decoded = decode_tile(&resp.body); + let decoded = decode_for(sh, k, &resp.body); let (meta, store) = TileMeta::from_response(now, header); let mut st = sh.lock(); st.errors_in_row = 0; diff --git a/crates/engine/src/map/source.rs b/crates/engine/src/map/source.rs index 8645feab67..cfd19d9ce6 100644 --- a/crates/engine/src/map/source.rs +++ b/crates/engine/src/map/source.rs @@ -7,8 +7,10 @@ //! another raster tile server (an `https://` URL template with `{z}`, `{x}` and `{y}`) or turn //! tiles off ([`TileSource::Offline`]). //! -//! The Esri layers need an explicit opt-in ([`TileSource::requires_opt_in`]): until the user has -//! turned them on they are not offered and never fetched. See `docs/map.md` (Esri's terms). +//! The Esri layers come from the ArcGIS Location Platform's static basemap tiles service and need +//! the user's own API key ([`TileSource::requires_key`]): without one they are not offered and +//! never fetched. The key is never part of a source (nor of prefs.json): the tile service adds it +//! to the request URL only ([`with_token`]). See `docs/map.md` (Esri layers). //! //! Validation of custom sources is ported from the map core of PR #797 (Jason Baldwin). @@ -27,13 +29,21 @@ pub const OSM_MAX_ZOOM: u8 = 19; pub const OPENTOPOMAP_TILE_URL: &str = "https://tile.opentopomap.org/{z}/{x}/{y}.png"; /// The credit OpenTopoMap asks for. pub const OPENTOPOMAP_ATTRIBUTION: &str = "Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)"; -const ESRI_STREET_URL: &str = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}"; -const ESRI_TOPO_URL: &str = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"; -const ESRI_IMAGERY_URL: &str = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"; -/// The credits of each Esri layer, as its ArcGIS Online item gives them (`accessInformation`). -const ESRI_STREET_ATTRIBUTION: &str = "Powered by Esri | Sources: Esri, HERE, Garmin, USGS, Intermap, INCREMENT P, NRCAN, Esri Japan, METI, Esri China (Hong Kong), NOSTRA, © OpenStreetMap contributors, and the GIS User Community"; -const ESRI_TOPO_ATTRIBUTION: &str = "Powered by Esri | Sources: Esri, HERE, Garmin, Intermap, INCREMENT P, GEBCO, USGS, FAO, NPS, NRCAN, GeoBase, IGN, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), © OpenStreetMap contributors, GIS User Community"; -const ESRI_IMAGERY_ATTRIBUTION: &str = "Powered by Esri | Esri, Vantor, Earthstar Geographics, and the GIS User Community"; +/// The ArcGIS Location Platform static basemap tiles service (keyed; read 2026-11-15: +/// ). Its tiles are 512 px PNGs whose +/// level `L` has the same 2^L × 2^L grid as a 256 px tile pyramid ("zoom levels are 1 less"), so +/// the 256 px tile `(z, x, y)` is a quarter of its tile `(z − 1, x / 2, y / 2)` ([`Crop`]). +pub const ESRI_STATIC_BASE: &str = "https://static-map-tiles-api.arcgis.com/arcgis/rest/services/static-basemap-tiles-service/v1"; +const ESRI_STREET_URL: &str = + "https://static-map-tiles-api.arcgis.com/arcgis/rest/services/static-basemap-tiles-service/v1/arcgis/streets/static/tile/{z}/{y}/{x}"; +const ESRI_OUTDOOR_URL: &str = + "https://static-map-tiles-api.arcgis.com/arcgis/rest/services/static-basemap-tiles-service/v1/arcgis/outdoor/static/tile/{z}/{y}/{x}"; +/// "Powered by Esri", painted before every Esri layer's data credits. +pub const ESRI_POWERED_BY: &str = "Powered by Esri"; +/// The Esri layers' credit when the layer's own metadata (`copyrightText`) can't be fetched: the +/// data providers the service's documentation lists for the ArcGIS styles. +pub const ESRI_FALLBACK_ATTRIBUTION: &str = + "Powered by Esri | Esri, TomTom, Garmin, FAO, NOAA, USGS, © OpenStreetMap contributors, and the GIS User Community"; /// The User-Agent sent with every tile request: distinct and stable, naming the app and where to /// find it, as the OSMF policy asks. No personal details. pub const USER_AGENT: &str = concat!("LightCraft/", env!("CARGO_PKG_VERSION"), " (+https://github.com/storytold/lightcraft)"); @@ -55,12 +65,10 @@ pub enum TileSource { Osm, /// OpenTopoMap (topographic, from OpenStreetMap data and SRTM). OpenTopoMap, - /// Esri World Street Map (opt-in). + /// Esri's ArcGIS Streets style (needs the user's ArcGIS API key). EsriStreet, - /// Esri World Topographic Map (opt-in). + /// Esri's ArcGIS Outdoor style, a topographic map (needs the user's ArcGIS API key). EsriTopo, - /// Esri World Imagery (opt-in). - EsriImagery, /// No tiles and no network: the map shows only what is drawn on top of it (pins, tracks). Offline, /// A user-configured raster tile server. @@ -78,8 +86,8 @@ pub enum TileSource { impl TileSource { /// The built-in sources, in the order a picker lists them. - pub const BUILT_IN: [TileSource; 6] = - [TileSource::Osm, TileSource::OpenTopoMap, TileSource::EsriStreet, TileSource::EsriTopo, TileSource::EsriImagery, TileSource::Offline]; + pub const BUILT_IN: [TileSource; 5] = + [TileSource::Osm, TileSource::OpenTopoMap, TileSource::EsriStreet, TileSource::EsriTopo, TileSource::Offline]; /// The built-in source with id `id` (also accepts a few spellings: `openstreetmap`, /// `esri-street`, `esriImagery`…), case-insensitive. @@ -89,8 +97,7 @@ impl TileSource { "osm" | "openstreetmap" => TileSource::Osm, "opentopomap" | "otm" => TileSource::OpenTopoMap, "esri-streets" | "esri-street" | "esristreet" | "esristreets" => TileSource::EsriStreet, - "esri-topo" | "esritopo" => TileSource::EsriTopo, - "esri-imagery" | "esriimagery" => TileSource::EsriImagery, + "esri-topo" | "esritopo" | "esri-outdoor" | "esrioutdoor" => TileSource::EsriTopo, "offline" | "none" => TileSource::Offline, _ => return None, }) @@ -103,7 +110,6 @@ impl TileSource { TileSource::OpenTopoMap => "opentopomap", TileSource::EsriStreet => "esri-streets", TileSource::EsriTopo => "esri-topo", - TileSource::EsriImagery => "esri-imagery", TileSource::Offline => "offline", TileSource::Custom { id, .. } => id, } @@ -114,9 +120,8 @@ impl TileSource { match self { TileSource::Osm => "OpenStreetMap", TileSource::OpenTopoMap => "OpenTopoMap", - TileSource::EsriStreet => "Esri World Street Map", - TileSource::EsriTopo => "Esri World Topographic Map", - TileSource::EsriImagery => "Esri World Imagery", + TileSource::EsriStreet => "Esri Streets", + TileSource::EsriTopo => "Esri Outdoor (topographic)", TileSource::Offline => "Offline (no tiles)", TileSource::Custom { .. } => "Custom tile server", } @@ -128,40 +133,66 @@ impl TileSource { TileSource::Osm => OSM_TILE_URL, TileSource::OpenTopoMap => OPENTOPOMAP_TILE_URL, TileSource::EsriStreet => ESRI_STREET_URL, - TileSource::EsriTopo => ESRI_TOPO_URL, - TileSource::EsriImagery => ESRI_IMAGERY_URL, + TileSource::EsriTopo => ESRI_OUTDOOR_URL, TileSource::Offline => return None, TileSource::Custom { url_template, .. } => url_template, }) } - /// The credit painted on the map whenever its tiles are (empty for the offline source). + /// The credit painted on the map whenever its tiles are (empty for the offline source). For an + /// Esri layer this is the fallback; the tile service paints the layer's own credits once its + /// metadata arrived ([`super::TileService::attribution`]). pub fn attribution(&self) -> &str { match self { TileSource::Osm => OSM_ATTRIBUTION, TileSource::OpenTopoMap => OPENTOPOMAP_ATTRIBUTION, - TileSource::EsriStreet => ESRI_STREET_ATTRIBUTION, - TileSource::EsriTopo => ESRI_TOPO_ATTRIBUTION, - TileSource::EsriImagery => ESRI_IMAGERY_ATTRIBUTION, + TileSource::EsriStreet | TileSource::EsriTopo => ESRI_FALLBACK_ATTRIBUTION, TileSource::Offline => "", TileSource::Custom { attribution, .. } => attribution, } } + /// The layer's metadata URL (without the key), whose `copyrightText` is its data credit; only + /// the Esri layers have one. + pub fn metadata_url(&self) -> Option { + let style = match self { + TileSource::EsriStreet => "arcgis/streets", + TileSource::EsriTopo => "arcgis/outdoor", + _ => return None, + }; + Some(format!("{ESRI_STATIC_BASE}/{style}/static?f=json")) + } + + /// How the 256 px tile `key` is cut from the server's tile ([`TileSource::remote_key`]). + pub fn crop(&self, key: TileKey) -> Crop { + if !self.requires_key() { + Crop::Whole + } else if key.z == 0 { + Crop::Half + } else { + Crop::Quarter { right: key.x & 1 == 1, bottom: key.y & 1 == 1 } + } + } + + /// The server's tile holding the 256 px tile `key`: the same key, or for the Esri layers (512 px + /// tiles, one level up) its parent. + pub fn remote_key(&self, key: TileKey) -> TileKey { + if self.requires_key() && key.z > 0 { TileKey { z: key.z - 1, x: key.x >> 1, y: key.y >> 1 } } else { key } + } + /// Deepest zoom the server has tiles for. pub fn max_zoom(&self) -> u8 { match self { TileSource::Osm | TileSource::Offline => OSM_MAX_ZOOM, TileSource::OpenTopoMap => 17, - TileSource::EsriStreet | TileSource::EsriTopo => 18, - TileSource::EsriImagery => 19, + TileSource::EsriStreet | TileSource::EsriTopo => 20, TileSource::Custom { max_zoom, .. } => *max_zoom, } } - /// Esri's layers: offered and fetched only after the user turns them on (`docs/map.md`). - pub fn requires_opt_in(&self) -> bool { - matches!(self, TileSource::EsriStreet | TileSource::EsriTopo | TileSource::EsriImagery) + /// Esri's layers: offered and fetched only with the user's own ArcGIS API key (`docs/map.md`). + pub fn requires_key(&self) -> bool { + matches!(self, TileSource::EsriStreet | TileSource::EsriTopo) } /// No network: tiles are never fetched. @@ -174,13 +205,15 @@ impl TileSource { USER_AGENT } - /// The URL of `key`, or `None` for the offline source (or a key past the source's max zoom). + /// The URL of the server's tile for `key` ([`TileSource::remote_key`]), without any API key, or + /// `None` for the offline source (or a key past the source's max zoom). pub fn url(&self, key: TileKey) -> Option { let template = self.url_template()?; if key.z > self.max_zoom() { return None; } - Some(template.replace("{z}", &key.z.to_string()).replace("{x}", &key.x.to_string()).replace("{y}", &key.y.to_string())) + let r = self.remote_key(key); + Some(template.replace("{z}", &r.z.to_string()).replace("{x}", &r.x.to_string()).replace("{y}", &r.y.to_string())) } /// The server's host name (lower-case), for messages. @@ -240,6 +273,24 @@ impl TileSource { } } +/// The part of the server's tile that makes a 256 px tile. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Crop { + /// The tile as it is. + Whole, + /// The tile halved in each direction (the 512 px world tile at zoom 0). + Half, + /// One quarter of a 512 px tile. + Quarter { right: bool, bottom: bool }, +} + +/// `url` with the API key added as its `token` query parameter: what the tile service sends. The +/// result is never logged, used as a cache key, or shown. +pub fn with_token(url: &str, token: &str) -> String { + let sep = if url.contains('?') { '&' } else { '?' }; + format!("{url}{sep}token={token}") +} + fn bad(msg: impl Into) -> MapError { MapError::InvalidSource(msg.into()) } @@ -306,7 +357,8 @@ mod tests { assert_eq!(s.url(TileKey::new(20, 0, 0).unwrap()), None, "past the max zoom"); assert_eq!(s.host().as_deref(), Some("tile.openstreetmap.org")); assert_eq!(s.checked().unwrap(), s); - assert!(!s.requires_opt_in()); + assert!(!s.requires_key()); + assert_eq!(s.crop(TileKey::new(3, 1, 1).unwrap()), Crop::Whole); } #[test] @@ -318,10 +370,21 @@ mod tests { assert!(s.url_template().is_some_and(|t| validate_template(t).is_ok()), "{s:?}"); } } - let esri: Vec<_> = TileSource::BUILT_IN.into_iter().filter(TileSource::requires_opt_in).collect(); - assert_eq!(esri, vec![TileSource::EsriStreet, TileSource::EsriTopo, TileSource::EsriImagery]); - // Esri's tile URLs are row before column - assert!(TileSource::EsriImagery.url(TileKey::new(3, 1, 2).unwrap()).unwrap().ends_with("/tile/3/2/1")); + let esri: Vec<_> = TileSource::BUILT_IN.into_iter().filter(TileSource::requires_key).collect(); + assert_eq!(esri, vec![TileSource::EsriStreet, TileSource::EsriTopo]); + // Esri's static tiles: the keyed service only (never the keyless arcgisonline hosts), row + // before column, 512 px tiles one level up: the 256 px tile (4, 3, 5) is a quarter of (3, 1, 2) + let k = TileKey::new(4, 3, 5).unwrap(); + let url = TileSource::EsriStreet.url(k).unwrap(); + assert!(url.starts_with("https://static-map-tiles-api.arcgis.com/") && url.ends_with("/arcgis/streets/static/tile/3/2/1"), "{url}"); + assert!(!url.contains("token"), "the key is not part of the source's URL"); + assert_eq!(TileSource::EsriTopo.crop(k), Crop::Quarter { right: true, bottom: true }); + assert_eq!(TileSource::EsriTopo.crop(TileKey::new(0, 0, 0).unwrap()), Crop::Half); + assert!(TileSource::BUILT_IN.iter().filter_map(TileSource::url_template).all(|t| !t.contains("arcgisonline"))); + assert!(TileSource::EsriTopo.metadata_url().unwrap().ends_with("/arcgis/outdoor/static?f=json")); + assert_eq!(TileSource::Osm.metadata_url(), None); + assert_eq!(with_token("https://a.example/x?f=json", "K"), "https://a.example/x?f=json&token=K"); + assert_eq!(with_token("https://a.example/1/2/3", "K"), "https://a.example/1/2/3?token=K"); assert_eq!(TileSource::built_in("OpenStreetMap"), Some(TileSource::Osm)); assert_eq!(TileSource::built_in("esri-street"), Some(TileSource::EsriStreet)); assert_eq!(TileSource::built_in("bing"), None); @@ -366,7 +429,7 @@ mod tests { ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), Some(25), None), ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("osm")), ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("offline")), - ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("esri-imagery")), + ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("esri-topo")), ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("../etc")), ("https://tiles.example.org/{z}/{x}/{y}.png", Some("x"), None, Some("Upper")), (OSM_TILE_URL, None, Some(20), None), diff --git a/crates/engine/src/map/tests_service.rs b/crates/engine/src/map/tests_service.rs index 8b85cba55a..aefa2ad53b 100644 --- a/crates/engine/src/map/tests_service.rs +++ b/crates/engine/src/map/tests_service.rs @@ -502,3 +502,117 @@ fn a_huge_announced_tile_length_is_an_error_not_an_allocation() { assert!(err.contains("larger"), "{err}"); server.join().unwrap(); } + +const KEY: &str = "AAPK0123456789abcdef_TEST-key.x"; + +fn esri_service(fake: Arc, cache: Option) -> TileService { + let key = crate::map::ApiKey::parse(KEY).unwrap(); + TileService::with_transport(TileSource::EsriStreet, cache, Some(fake)).with_token(Some(key)) +} + +/// The Esri layers: the key goes only into the request URL as `token`, never into errors, the +/// cache's files or the stats; 512 px tiles are cut into the four 256 px tiles they hold, and one +/// request serves all four. +#[test] +fn esri_tiles_carry_the_key_in_the_request_only_and_are_cut_in_quarters() { + let fake = Fake::new(|url, _| { + if url.contains("/static?f=json") { + return Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"copyrightText": "Sources: Test Data Co"}"#.to_vec() }); + } + if url.contains("/tile/3/") { + // a failing tile whose transport error quotes the URL (and so the key) + return Err(format!("connection reset fetching {url}")); + } + Ok(HttpResponse { status: 200, headers: vec![("Cache-Control".into(), "max-age=86400".into())], body: png(512, 512) }) + }); + let root = tmp("esri"); + let svc = esri_service(fake.clone(), Some(TileCache::new(&root, "esri-streets", 1 << 30).unwrap())); + // the four 256 px tiles of one 512 px tile at level 4 + let keys: Vec = [(10, 6), (11, 6), (10, 7), (11, 7)].iter().map(|&(x, y)| TileKey::new(5, x, y).unwrap()).collect(); + svc.want(&keys); + wait_until("the tiles", 20, || svc.is_idle() && keys.iter().all(|k| svc.get(*k).is_some())); + for k in &keys { + let t = svc.get(*k).unwrap(); + assert_eq!((t.width, t.height), (256, 256), "a quarter of the 512 px tile"); + } + let tile_urls: Vec = fake.urls().into_iter().filter(|u| u.contains("/tile/")).collect(); + assert!(!tile_urls.is_empty() && tile_urls.len() <= 2, "one server tile serves its four quarters: {tile_urls:?}"); + assert!(tile_urls.iter().all(|u| u.ends_with(&format!("/arcgis/streets/static/tile/4/3/5?token={KEY}"))), "{tile_urls:?}"); + assert!(svc.stats().reused >= 2, "{:?}", svc.stats()); + // the credit comes from the layer's metadata, fetched once with the key + wait_until("the credit", 20, || svc.attribution().contains("Test Data Co")); + assert_eq!(svc.attribution(), "Powered by Esri | Sources: Test Data Co"); + assert_eq!(fake.urls().iter().filter(|u| u.contains("/static?f=json")).count(), 1); + // a failure's message hides the key + let bad = TileKey::new(4, 0, 0).unwrap(); + svc.want(&[bad]); + let failed = Mutex::new(Vec::new()); + wait_until("the failure", 20, || { + let mut f = failed.lock().unwrap(); + f.extend(svc.poll().into_iter().filter_map(|e| if let TileEvent::Failed { error, .. } = e { Some(error) } else { None })); + !f.is_empty() + }); + let failed = failed.into_inner().unwrap(); + assert!(failed.iter().all(|e| !e.contains(KEY) && e.contains("[key]")), "{failed:?}"); + // nothing on disk names the key + let mut stack = vec![root.clone()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).unwrap().flatten() { + let p = e.path(); + assert!(!p.to_string_lossy().contains(KEY), "{}", p.display()); + if p.is_dir() { + stack.push(p); + } else { + assert!(!std::fs::read(&p).unwrap().windows(KEY.len()).any(|w| w == KEY.as_bytes()), "{}", p.display()); + } + } + } + assert!(!format!("{svc:?} {:?}", svc.stats()).contains(KEY)); + drop(svc); + let _ = std::fs::remove_dir_all(&root); +} + +/// Metadata that is huge, not JSON, markup or the wrong shape gives the fixed credit. +#[test] +fn hostile_metadata_falls_back_to_the_fixed_credit() { + assert_eq!(metadata_credit(br#"{"copyrightText": "Esri, Maxar"}"#).as_deref(), Some("Esri, Maxar")); + let huge = format!(r#"{{"copyrightText": "{}"}}"#, "x".repeat(MAX_METADATA_BYTES)); + for body in [ + huge.as_bytes(), + b"Service unavailable", + br#"{"copyrightText": ""}"#, + br#"{"copyrightText": "two\nlines"}"#, + br#"{"copyrightText": 5}"#, + br#"{"copyrightText": " "}"#, + br#"{}"#, + b"", + ] { + assert_eq!(metadata_credit(body), None, "{}", String::from_utf8_lossy(&body[..body.len().min(60)])); + } + let fake = Fake::new(|url, _| { + if url.contains("/static?f=json") { + return Ok(HttpResponse { status: 200, headers: vec![], body: b"nope".to_vec() }); + } + Ok(HttpResponse { status: 200, headers: vec![], body: png(512, 512) }) + }); + let svc = esri_service(fake.clone(), None); + svc.want(&[TileKey::new(2, 1, 1).unwrap()]); + wait_until("the metadata", 20, || fake.urls().iter().any(|u| u.contains("/static?f=json")) && svc.is_idle()); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(svc.attribution(), TileSource::EsriStreet.attribution()); + assert!(svc.attribution().starts_with("Powered by Esri | ")); +} + +/// Cutting quarters and halving refuse sizes that don't fit, never panic. +#[test] +fn cropping_checks_the_tile() { + use super::source::Crop; + let img = |w: u32, h: u32| TileImage { width: w, height: h, rgba: vec![7; (w * h * 4) as usize] }; + let q = crop_tile(img(512, 512), Crop::Quarter { right: true, bottom: false }).unwrap(); + assert_eq!((q.width, q.height, q.rgba.len()), (256, 256, 256 * 256 * 4)); + assert_eq!(crop_tile(img(512, 512), Crop::Half).unwrap().width, 256); + assert!(crop_tile(img(255, 256), Crop::Quarter { right: false, bottom: false }).is_err()); + assert!(crop_tile(img(1, 1), Crop::Quarter { right: true, bottom: true }).is_err()); + assert_eq!(crop_tile(img(3, 3), Crop::Half).unwrap().width, 3, "odd sizes are kept"); + assert!(crop_tile(TileImage { width: 4, height: 4, rgba: vec![0; 3] }, Crop::Half).is_err(), "pixel data too short"); +} diff --git a/crates/engine/src/tests/map.rs b/crates/engine/src/tests/map.rs index a71648d08e..46ef1c0faa 100644 --- a/crates/engine/src/tests/map.rs +++ b/crates/engine/src/tests/map.rs @@ -22,7 +22,7 @@ fn tile_source_get_and_set() { assert_eq!(r["attribution"], "© OpenStreetMap contributors"); assert_eq!(r["maxZoom"], 19); assert!(r["userAgent"].as_str().unwrap().starts_with("LightCraft/")); - assert_eq!((r["offline"].as_bool(), r["esriEnabled"].as_bool()), (Some(false), Some(false))); + assert_eq!((r["offline"].as_bool(), r["esriKeySet"].as_bool()), (Some(false), Some(false))); let r = s.execute("map.tileSource", &json!({"offline": true})).unwrap(); assert_eq!((r["id"].as_str(), r["offline"].as_bool()), (Some("offline"), Some(true))); @@ -61,30 +61,50 @@ fn tile_source_get_and_set() { assert_eq!(r["urlTemplate"], crate::map::OSM_TILE_URL); } -/// Esri is refused while its opt-in is off (it is, and no command turns it on: docs/map.md), and -/// the refusal names why; the gate lets it through once enabled. +const KEY: &str = "AAPK0123456789abcdef_TEST-key.x"; + +/// The Esri layers need the user's own ArcGIS API key: refused (with where to get one) and not +/// listed without it, listed and accepted with it; the key is never reported back. #[test] -fn esri_sources_are_refused_while_off_and_accepted_after_enabling() { +fn esri_sources_need_a_key_and_the_key_is_never_reported() { let mut s = Session::new(); - for id in ["esri-imagery", "esri-streets", "esri-topo"] { + for id in ["esri-streets", "esri-topo"] { let e = s.execute("map.tileSource", &json!({"id": id})).unwrap_err().to_string(); - assert!(e.contains("Esri") && e.contains("docs/map.md"), "{e}"); + assert!(e.contains("API key") && e.contains("location.arcgis.com"), "{e}"); } + assert!(s.execute("map.tileSource", &json!({"id": "esri-imagery"})).is_err(), "no keyless imagery layer"); assert_eq!(*s.map.source(), crate::map::TileSource::Osm); - assert!(s.execute("map.enableEsri", &json!({"on": true})).is_err(), "no command turns Esri on"); - s.map.set_esri_enabled(true); - let r = s.execute("map.tileSource", &json!({"id": "esri-imagery"})).unwrap(); - assert_eq!(r["id"], "esri-imagery"); - assert!(r["attribution"].as_str().unwrap().contains("Esri")); - let ids: Vec = - s.execute("map.providers", &json!({})).unwrap().as_array().unwrap().iter().map(|p| p["id"].as_str().unwrap().to_string()).collect(); - assert!(ids.contains(&"esri-imagery".to_string())); - // turned off again: the map falls back to OpenStreetMap, the choice is kept - s.map.set_esri_enabled(false); + // a key of the wrong shape is refused without being repeated + for bad in [json!({"key": "has spaces in it 0123456789"}), json!({"key": 5}), json!({})] { + let e = s.execute("map.setEsriKey", &bad).unwrap_err().to_string(); + assert!(!e.contains("0123456789"), "{e}"); + } + let r = s.execute("map.setEsriKey", &json!({"key": KEY})).unwrap(); + assert_eq!(r["esriKeySet"], true); + let r = s.execute("map.tileSource", &json!({"id": "esri-streets"})).unwrap(); + assert_eq!((r["id"].as_str(), r["esriKeySet"].as_bool()), (Some("esri-streets"), Some(true))); + assert!(r["attribution"].as_str().unwrap().starts_with("Powered by Esri")); + let providers = s.execute("map.providers", &json!({})).unwrap(); + let ids: Vec<&str> = providers.as_array().unwrap().iter().filter_map(|p| p["id"].as_str()).collect(); + assert_eq!(ids, vec!["osm", "opentopomap", "esri-streets", "esri-topo", "offline"]); + // the key appears in no reply, no journal entry and not in what prefs.json stores + let everything = format!( + "{r} {providers} {} {} {:?} {}", + s.execute("map.tileSource", &json!({})).unwrap(), + s.execute("map.setEsriKey", &json!({"key": KEY})).unwrap(), + s.journal, + serde_json::to_string(s.map.source()).unwrap() + ); + assert!(!everything.contains(KEY), "{everything}"); + assert_eq!(s.map_tiles().unwrap().source(), &crate::map::TileSource::EsriStreet); + // cleared: the map falls back to OpenStreetMap and keeps the choice, with a notice + let r = s.execute("map.setEsriKey", &json!({"key": ""})).unwrap(); + assert_eq!(r["esriKeySet"], false); + assert!(r["notice"].as_str().unwrap().contains("OpenStreetMap"), "{r}"); let r = s.execute("map.tileSource", &json!({})).unwrap(); - assert_eq!((r["id"].as_str(), r["saved"].as_str()), (Some("osm"), Some("esri-imagery"))); - assert!(r["notice"].as_str().unwrap().contains("OpenStreetMap")); - assert_eq!(s.map_tiles().unwrap().source(), &crate::map::TileSource::Osm, "Esri tiles are never fetched"); + assert_eq!((r["id"].as_str(), r["saved"].as_str()), (Some("osm"), Some("esri-streets"))); + assert_eq!(s.map_tiles().unwrap().source(), &crate::map::TileSource::Osm, "Esri tiles are never fetched without a key"); + assert!(s.execute("map.setEsriKey", &json!({"key": null})).is_ok()); } #[test] @@ -266,17 +286,18 @@ fn the_map_tile_source_persists_and_is_rechecked() { #[test] fn a_saved_esri_source_falls_back_with_a_notice_and_is_kept() { let lib = temp_lib("esri"); - std::fs::write(lib.join("prefs.json"), br#"{"cacheMb": 321, "mapSource": {"kind": "esriImagery"}}"#).unwrap(); + std::fs::write(lib.join("prefs.json"), br#"{"cacheMb": 321, "mapSource": {"kind": "esriTopo"}}"#).unwrap(); let mut s = Session::new().with_fs(); s.open_library(&lib, false).unwrap(); assert_eq!(s.cache_mb, 321); assert_eq!(s.map.effective_source(), crate::map::TileSource::Osm); let warnings = s.take_library_warnings(); assert_eq!(warnings.iter().filter(|w| w.contains("OpenStreetMap") && w.contains("Esri")).count(), 1, "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("location.arcgis.com")), "the notice says where to get a key: {warnings:?}"); // saving other preferences keeps the Esri choice in the file s.save_prefs().unwrap(); let prefs: serde_json::Value = serde_json::from_slice(&std::fs::read(lib.join("prefs.json")).unwrap()).unwrap(); - assert_eq!(prefs["mapSource"], json!({"kind": "esriImagery"})); + assert_eq!(prefs["mapSource"], json!({"kind": "esriTopo"})); drop(s); let _ = std::fs::remove_dir_all(&lib); } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 0699e68341..f775d12be3 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2527,5 +2527,19 @@ "Map tiles are off": "Mapové dlaždice jsou vypnuté", "Offline (no tiles)": "Offline (bez dlaždic)", "Custom tile server": "Vlastní server dlaždic", - "Set the location of this photo": "Nastavit polohu této fotky" + "Set the location of this photo": "Nastavit polohu této fotky", + "Esri map layers": "Mapové vrstvy Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Mapové styly Esri Streets a Esri Outdoor potřebují váš vlastní klíč API ArcGIS Location Platform. Bezplatný účet má měsíční limit dlaždic; dlaždice se počítají vašemu klíči. Server Esri pak vidí, na která místa se díváte.", + "Status": "Stav", + "A key is set": "Klíč je nastaven", + "No key: the Esri styles are not offered": "Bez klíče: styly Esri nejsou nabízeny", + "ArcGIS API key": "Klíč API ArcGIS", + "Paste a new key to replace it": "Vložte nový klíč pro nahrazení", + "Paste your key": "Vložte svůj klíč", + "Remove Key": "Odebrat klíč", + "Get a free key at location.arcgis.com": "Získejte bezplatný klíč na location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Dejte klíči jen oprávnění ke statickým dlaždicím podkladových map. Je uložen ve složce nastavení LightCraftu (map-keys.json), nikdy ve vaší knihovně, a posílá se jen na server dlaždic Esri. Styl zvolte v seznamu Styl mapy v zobrazení Mapa.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topografická)", + "Set ArcGIS API Key": "Nastavit klíč API ArcGIS" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 9b469cb1fb..d07266aaa0 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3562,5 +3562,19 @@ "Map tiles are off": "Kartenkacheln sind aus", "Offline (no tiles)": "Offline (keine Kacheln)", "Custom tile server": "Eigener Kachelserver", - "Set the location of this photo": "Ort dieses Fotos festlegen" + "Set the location of this photo": "Ort dieses Fotos festlegen", + "Esri map layers": "Esri-Kartenebenen", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Die Kartenstile Esri Streets und Esri Outdoor brauchen Ihren eigenen API-Schlüssel der ArcGIS Location Platform. Ein kostenloses Konto enthält ein monatliches Kachelkontingent; Kacheln werden Ihrem Schlüssel angerechnet. Der Esri-Server sieht dann, welche Orte Sie ansehen.", + "Status": "Status", + "A key is set": "Ein Schlüssel ist gesetzt", + "No key: the Esri styles are not offered": "Kein Schlüssel: Die Esri-Stile werden nicht angeboten", + "ArcGIS API key": "ArcGIS-API-Schlüssel", + "Paste a new key to replace it": "Neuen Schlüssel einfügen, um ihn zu ersetzen", + "Paste your key": "Schlüssel einfügen", + "Remove Key": "Schlüssel entfernen", + "Get a free key at location.arcgis.com": "Kostenlosen Schlüssel auf location.arcgis.com holen", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Geben Sie dem Schlüssel nur das Recht für statische Basemap-Kacheln. Er wird im Einstellungsordner von LightCraft gespeichert (map-keys.json), nie in Ihrer Bibliothek, und nur an den Kachelserver von Esri gesendet. Wählen Sie den Stil in der Liste Kartenstil der Kartenansicht.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topografisch)", + "Set ArcGIS API Key": "ArcGIS-API-Schlüssel festlegen" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index b8c3d5d64d..53305834a4 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2481,5 +2481,19 @@ "Map tiles are off": "Las teselas del mapa están desactivadas", "Offline (no tiles)": "Sin conexión (sin teselas)", "Custom tile server": "Servidor de teselas personalizado", - "Set the location of this photo": "Establecer la ubicación de esta foto" + "Set the location of this photo": "Establecer la ubicación de esta foto", + "Esri map layers": "Capas de mapa de Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Los estilos de mapa Esri Streets y Esri Outdoor necesitan tu propia clave de API de ArcGIS Location Platform. Una cuenta gratuita incluye una cuota mensual de teselas; las teselas cuentan para tu clave. El servidor de Esri ve entonces qué lugares miras.", + "Status": "Estado", + "A key is set": "Hay una clave", + "No key: the Esri styles are not offered": "Sin clave: los estilos de Esri no se ofrecen", + "ArcGIS API key": "Clave de API de ArcGIS", + "Paste a new key to replace it": "Pega una clave nueva para reemplazarla", + "Paste your key": "Pega tu clave", + "Remove Key": "Quitar clave", + "Get a free key at location.arcgis.com": "Consigue una clave gratuita en location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Da a la clave solo el privilegio de teselas estáticas de mapa base. Se guarda en la carpeta de ajustes de LightCraft (map-keys.json), nunca en tu biblioteca, y solo se envía al servidor de teselas de Esri. Elige el estilo en la lista Estilo de mapa de la vista Mapa.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topográfico)", + "Set ArcGIS API Key": "Establecer clave de API de ArcGIS" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 1d3512179d..1aa43cb940 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2438,5 +2438,19 @@ "Map tiles are off": "Karttaruudut ovat pois päältä", "Offline (no tiles)": "Offline (ei ruutuja)", "Custom tile server": "Oma ruutupalvelin", - "Set the location of this photo": "Aseta tämän kuvan sijainti" + "Set the location of this photo": "Aseta tämän kuvan sijainti", + "Esri map layers": "Esrin karttatasot", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Esri Streets- ja Esri Outdoor -karttatyylit tarvitsevat oman ArcGIS Location Platform -API-avaimesi. Ilmainen tili sisältää kuukausittaisen ruutukiintiön; ruudut lasketaan avaimellesi. Esrin palvelin näkee silloin, mitä paikkoja katsot.", + "Status": "Tila", + "A key is set": "Avain on asetettu", + "No key: the Esri styles are not offered": "Ei avainta: Esri-tyylejä ei tarjota", + "ArcGIS API key": "ArcGIS-API-avain", + "Paste a new key to replace it": "Liitä uusi avain korvataksesi sen", + "Paste your key": "Liitä avaimesi", + "Remove Key": "Poista avain", + "Get a free key at location.arcgis.com": "Hanki ilmainen avain osoitteesta location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Anna avaimelle vain staattisten taustakarttaruutujen oikeus. Se tallennetaan LightCraftin asetuskansioon (map-keys.json), ei koskaan kirjastoosi, ja lähetetään vain Esrin ruutupalvelimelle. Valitse tyyli Kartta-näkymän Karttatyyli-luettelosta.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topografinen)", + "Set ArcGIS API Key": "Aseta ArcGIS-API-avain" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 05368ad2d6..33c2177269 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -3664,5 +3664,19 @@ "Map tiles are off": "Les tuiles de la carte sont désactivées", "Offline (no tiles)": "Hors ligne (sans tuiles)", "Custom tile server": "Serveur de tuiles personnalisé", - "Set the location of this photo": "Définir le lieu de cette photo" + "Set the location of this photo": "Définir le lieu de cette photo", + "Esri map layers": "Couches cartographiques Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Les styles de carte Esri Streets et Esri Outdoor demandent votre propre clé d'API ArcGIS Location Platform. Un compte gratuit offre un quota mensuel de tuiles ; les tuiles sont décomptées sur votre clé. Le serveur d'Esri voit alors les lieux que vous regardez.", + "Status": "État", + "A key is set": "Une clé est définie", + "No key: the Esri styles are not offered": "Pas de clé : les styles Esri ne sont pas proposés", + "ArcGIS API key": "Clé d'API ArcGIS", + "Paste a new key to replace it": "Collez une nouvelle clé pour la remplacer", + "Paste your key": "Collez votre clé", + "Remove Key": "Supprimer la clé", + "Get a free key at location.arcgis.com": "Obtenir une clé gratuite sur location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Ne donnez à la clé que le privilège des tuiles statiques de fond de carte. Elle est conservée dans le dossier de réglages de LightCraft (map-keys.json), jamais dans votre bibliothèque, et envoyée seulement au serveur de tuiles d'Esri. Choisissez le style dans la liste Style de carte de la vue Carte.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topographique)", + "Set ArcGIS API Key": "Définir la clé d'API ArcGIS" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 56eecf9571..ddc0463e16 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2452,5 +2452,19 @@ "Map tiles are off": "Petak peta nonaktif", "Offline (no tiles)": "Luring (tanpa petak)", "Custom tile server": "Server petak khusus", - "Set the location of this photo": "Tetapkan lokasi foto ini" + "Set the location of this photo": "Tetapkan lokasi foto ini", + "Esri map layers": "Lapisan peta Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Gaya peta Esri Streets dan Esri Outdoor memerlukan kunci API ArcGIS Location Platform milik Anda. Akun gratis memberi jatah ubin bulanan; ubin dihitung pada kunci Anda. Server Esri lalu melihat tempat yang Anda lihat.", + "Status": "Status", + "A key is set": "Kunci sudah diatur", + "No key: the Esri styles are not offered": "Tanpa kunci: gaya Esri tidak ditawarkan", + "ArcGIS API key": "Kunci API ArcGIS", + "Paste a new key to replace it": "Tempel kunci baru untuk menggantinya", + "Paste your key": "Tempel kunci Anda", + "Remove Key": "Hapus Kunci", + "Get a free key at location.arcgis.com": "Dapatkan kunci gratis di location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Beri kunci hanya hak ubin peta dasar statis. Kunci disimpan di folder pengaturan LightCraft (map-keys.json), tidak pernah di pustaka Anda, dan hanya dikirim ke server ubin Esri. Pilih gaya di daftar Gaya Peta pada tampilan Peta.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topografi)", + "Set ArcGIS API Key": "Atur Kunci API ArcGIS" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 727713c84c..e24c2dbfc2 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2645,5 +2645,19 @@ "Map tiles are off": "Le tessere della mappa sono disattivate", "Offline (no tiles)": "Offline (nessuna tessera)", "Custom tile server": "Server di tessere personalizzato", - "Set the location of this photo": "Imposta la posizione di questa foto" + "Set the location of this photo": "Imposta la posizione di questa foto", + "Esri map layers": "Livelli mappa Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Gli stili di mappa Esri Streets ed Esri Outdoor richiedono la tua chiave API di ArcGIS Location Platform. Un account gratuito offre una quota mensile di tessere; le tessere sono conteggiate sulla tua chiave. Il server di Esri vede quindi quali luoghi guardi.", + "Status": "Stato", + "A key is set": "Una chiave è impostata", + "No key: the Esri styles are not offered": "Nessuna chiave: gli stili Esri non sono offerti", + "ArcGIS API key": "Chiave API ArcGIS", + "Paste a new key to replace it": "Incolla una nuova chiave per sostituirla", + "Paste your key": "Incolla la tua chiave", + "Remove Key": "Rimuovi chiave", + "Get a free key at location.arcgis.com": "Ottieni una chiave gratuita su location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Dai alla chiave solo il privilegio delle tessere statiche della mappa di base. È conservata nella cartella delle impostazioni di LightCraft (map-keys.json), mai nella tua libreria, e inviata solo al server di tessere di Esri. Scegli lo stile nell'elenco Stile mappa della vista Mappa.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topografica)", + "Set ArcGIS API Key": "Imposta chiave API ArcGIS" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 657fde2a10..6adca2837e 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2479,5 +2479,19 @@ "Map tiles are off": "地図タイルはオフです", "Offline (no tiles)": "オフライン(タイルなし)", "Custom tile server": "カスタムタイルサーバー", - "Set the location of this photo": "この写真の位置を設定" + "Set the location of this photo": "この写真の位置を設定", + "Esri map layers": "Esri マップレイヤー", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Esri Streets と Esri Outdoor のマップスタイルには、ご自身の ArcGIS Location Platform API キーが必要です。無料アカウントには毎月のタイル枠があり、タイルはキーに計上されます。Esri のサーバーには、見ている場所が伝わります。", + "Status": "状態", + "A key is set": "キーが設定されています", + "No key: the Esri styles are not offered": "キーなし:Esri スタイルは表示されません", + "ArcGIS API key": "ArcGIS API キー", + "Paste a new key to replace it": "置き換えるには新しいキーを貼り付け", + "Paste your key": "キーを貼り付け", + "Remove Key": "キーを削除", + "Get a free key at location.arcgis.com": "location.arcgis.com で無料キーを取得", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "キーには静的ベースマップタイルの権限だけを与えてください。キーは LightCraft の設定フォルダー(map-keys.json)に保存され、ライブラリには保存されず、Esri のタイルサーバーにだけ送信されます。スタイルはマップ表示の「マップスタイル」で選びます。", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor(地形図)", + "Set ArcGIS API Key": "ArcGIS API キーを設定" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index dfd0ad9b69..78b5f3c568 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -3747,5 +3747,19 @@ "Map tiles are off": "რუკის ფილები გამორთულია", "Offline (no tiles)": "ოფლაინ (ფილების გარეშე)", "Custom tile server": "საკუთარი ფილების სერვერი", - "Set the location of this photo": "ამ ფოტოს მდებარეობის დაყენება" + "Set the location of this photo": "ამ ფოტოს მდებარეობის დაყენება", + "Esri map layers": "Esri-ის რუკის ფენები", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Esri Streets-ისა და Esri Outdoor-ის რუკის სტილებს თქვენი საკუთარი ArcGIS Location Platform API გასაღები სჭირდება. უფასო ანგარიში ყოველთვიურ ფილების ლიმიტს იძლევა; ფილები თქვენს გასაღებზე ითვლება. ამ დროს Esri-ის სერვერი ხედავს, რომელ ადგილებს უყურებთ.", + "Status": "სტატუსი", + "A key is set": "გასაღები დაყენებულია", + "No key: the Esri styles are not offered": "გასაღები არ არის: Esri-ის სტილები არ არის შეთავაზებული", + "ArcGIS API key": "ArcGIS API გასაღები", + "Paste a new key to replace it": "ჩასვით ახალი გასაღები ჩასანაცვლებლად", + "Paste your key": "ჩასვით თქვენი გასაღები", + "Remove Key": "გასაღების წაშლა", + "Get a free key at location.arcgis.com": "მიიღეთ უფასო გასაღები location.arcgis.com-ზე", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "მიეცით გასაღებს მხოლოდ სტატიკური საბაზისო რუკის ფილების უფლება. ის ინახება LightCraft-ის პარამეტრების საქაღალდეში (map-keys.json), არასოდეს თქვენს ბიბლიოთეკაში, და იგზავნება მხოლოდ Esri-ის ფილების სერვერზე. სტილი აირჩიეთ რუკის ხედის „რუკის სტილის“ სიაში.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (ტოპოგრაფიული)", + "Set ArcGIS API Key": "ArcGIS API გასაღების დაყენება" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 3261e950b3..26f640ca95 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2404,5 +2404,19 @@ "Map tiles are off": "Kafelki mapy są wyłączone", "Offline (no tiles)": "Offline (bez kafelków)", "Custom tile server": "Własny serwer kafelków", - "Set the location of this photo": "Ustaw lokalizację tego zdjęcia" + "Set the location of this photo": "Ustaw lokalizację tego zdjęcia", + "Esri map layers": "Warstwy map Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Style map Esri Streets i Esri Outdoor wymagają własnego klucza API ArcGIS Location Platform. Darmowe konto ma miesięczny limit kafelków; kafelki są liczone na Twój klucz. Serwer Esri widzi wtedy, które miejsca oglądasz.", + "Status": "Stan", + "A key is set": "Klucz jest ustawiony", + "No key: the Esri styles are not offered": "Brak klucza: style Esri nie są dostępne", + "ArcGIS API key": "Klucz API ArcGIS", + "Paste a new key to replace it": "Wklej nowy klucz, aby go zastąpić", + "Paste your key": "Wklej swój klucz", + "Remove Key": "Usuń klucz", + "Get a free key at location.arcgis.com": "Uzyskaj darmowy klucz na location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Nadaj kluczowi tylko uprawnienie do statycznych kafelków map bazowych. Jest przechowywany w folderze ustawień LightCraft (map-keys.json), nigdy w bibliotece, i wysyłany tylko do serwera kafelków Esri. Styl wybierz z listy Styl mapy w widoku Mapa.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topograficzna)", + "Set ArcGIS API Key": "Ustaw klucz API ArcGIS" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 1d2660c220..d8cb6206de 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2325,5 +2325,19 @@ "Map tiles are off": "Os blocos do mapa estão desativados", "Offline (no tiles)": "Offline (sem blocos)", "Custom tile server": "Servidor de blocos personalizado", - "Set the location of this photo": "Definir a localização desta foto" + "Set the location of this photo": "Definir a localização desta foto", + "Esri map layers": "Camadas de mapa da Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Os estilos de mapa Esri Streets e Esri Outdoor precisam da sua própria chave de API da ArcGIS Location Platform. Uma conta gratuita tem uma cota mensal de blocos; os blocos contam para a sua chave. O servidor da Esri passa a ver quais lugares você olha.", + "Status": "Status", + "A key is set": "Há uma chave definida", + "No key: the Esri styles are not offered": "Sem chave: os estilos da Esri não são oferecidos", + "ArcGIS API key": "Chave de API do ArcGIS", + "Paste a new key to replace it": "Cole uma chave nova para substituí-la", + "Paste your key": "Cole sua chave", + "Remove Key": "Remover chave", + "Get a free key at location.arcgis.com": "Obtenha uma chave gratuita em location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Dê à chave apenas o privilégio de blocos estáticos de mapa base. Ela fica na pasta de configurações do LightCraft (map-keys.json), nunca na sua biblioteca, e é enviada só ao servidor de blocos da Esri. Escolha o estilo na lista Estilo do mapa da visualização Mapa.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topográfico)", + "Set ArcGIS API Key": "Definir chave de API do ArcGIS" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 701451b87e..6876684a69 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2687,5 +2687,19 @@ "Map tiles are off": "Тайлы карты отключены", "Offline (no tiles)": "Офлайн (без тайлов)", "Custom tile server": "Свой сервер тайлов", - "Set the location of this photo": "Задать местоположение этого фото" + "Set the location of this photo": "Задать местоположение этого фото", + "Esri map layers": "Слои карт Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Стилям карт Esri Streets и Esri Outdoor нужен ваш собственный API-ключ ArcGIS Location Platform. Бесплатная учётная запись даёт месячный лимит тайлов; тайлы учитываются на вашем ключе. Сервер Esri при этом видит, какие места вы смотрите.", + "Status": "Состояние", + "A key is set": "Ключ задан", + "No key: the Esri styles are not offered": "Нет ключа: стили Esri недоступны", + "ArcGIS API key": "API-ключ ArcGIS", + "Paste a new key to replace it": "Вставьте новый ключ для замены", + "Paste your key": "Вставьте ваш ключ", + "Remove Key": "Удалить ключ", + "Get a free key at location.arcgis.com": "Получите бесплатный ключ на location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Дайте ключу только право на статические тайлы базовых карт. Он хранится в папке настроек LightCraft (map-keys.json), никогда в библиотеке, и отправляется только на сервер тайлов Esri. Стиль выбирается в списке «Стиль карты» в режиме «Карта».", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (топографическая)", + "Set ArcGIS API Key": "Задать API-ключ ArcGIS" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 259281bc3e..6ffaf60b40 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2542,5 +2542,19 @@ "Map tiles are off": "Kartrutor är avstängda", "Offline (no tiles)": "Offline (inga rutor)", "Custom tile server": "Egen rutserver", - "Set the location of this photo": "Ange platsen för det här fotot" + "Set the location of this photo": "Ange platsen för det här fotot", + "Esri map layers": "Esris kartlager", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Kartstilarna Esri Streets och Esri Outdoor kräver din egen API-nyckel för ArcGIS Location Platform. Ett gratiskonto ger en månatlig kvot av rutor; rutorna räknas mot din nyckel. Esris server ser då vilka platser du tittar på.", + "Status": "Status", + "A key is set": "En nyckel är angiven", + "No key: the Esri styles are not offered": "Ingen nyckel: Esri-stilarna erbjuds inte", + "ArcGIS API key": "ArcGIS API-nyckel", + "Paste a new key to replace it": "Klistra in en ny nyckel för att ersätta den", + "Paste your key": "Klistra in din nyckel", + "Remove Key": "Ta bort nyckel", + "Get a free key at location.arcgis.com": "Skaffa en gratis nyckel på location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Ge nyckeln bara behörigheten för statiska baskartrutor. Den sparas i LightCrafts inställningsmapp (map-keys.json), aldrig i ditt bibliotek, och skickas bara till Esris ruteserver. Välj stilen i listan Kartstil i kartvyn.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (topografisk)", + "Set ArcGIS API Key": "Ange ArcGIS API-nyckel" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 5c52bfce52..c7ef8046c8 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2477,5 +2477,19 @@ "Map tiles are off": "Тайли мапи вимкнено", "Offline (no tiles)": "Офлайн (без тайлів)", "Custom tile server": "Власний сервер тайлів", - "Set the location of this photo": "Задати місце цього фото" + "Set the location of this photo": "Задати місце цього фото", + "Esri map layers": "Шари карт Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Стилям карт Esri Streets і Esri Outdoor потрібен ваш власний API-ключ ArcGIS Location Platform. Безкоштовний обліковий запис дає місячний ліміт тайлів; тайли рахуються на ваш ключ. Сервер Esri тоді бачить, які місця ви переглядаєте.", + "Status": "Стан", + "A key is set": "Ключ задано", + "No key: the Esri styles are not offered": "Немає ключа: стилі Esri недоступні", + "ArcGIS API key": "API-ключ ArcGIS", + "Paste a new key to replace it": "Вставте новий ключ для заміни", + "Paste your key": "Вставте ваш ключ", + "Remove Key": "Видалити ключ", + "Get a free key at location.arcgis.com": "Отримайте безкоштовний ключ на location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Надайте ключу лише право на статичні тайли базових карт. Він зберігається в теці налаштувань LightCraft (map-keys.json), ніколи в бібліотеці, і надсилається лише на сервер тайлів Esri. Стиль обирається у списку «Стиль карти» в режимі «Карта».", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (топографічна)", + "Set ArcGIS API Key": "Задати API-ключ ArcGIS" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index c10339e0ac..d702183b99 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2766,5 +2766,19 @@ "Map tiles are off": "Ô bản đồ đang tắt", "Offline (no tiles)": "Ngoại tuyến (không có ô)", "Custom tile server": "Máy chủ ô tùy chỉnh", - "Set the location of this photo": "Đặt vị trí cho ảnh này" + "Set the location of this photo": "Đặt vị trí cho ảnh này", + "Esri map layers": "Lớp bản đồ Esri", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Kiểu bản đồ Esri Streets và Esri Outdoor cần khóa API ArcGIS Location Platform của riêng bạn. Tài khoản miễn phí có hạn mức ô bản đồ hằng tháng; các ô được tính vào khóa của bạn. Khi đó máy chủ của Esri thấy những nơi bạn xem.", + "Status": "Trạng thái", + "A key is set": "Đã đặt khóa", + "No key: the Esri styles are not offered": "Chưa có khóa: không có các kiểu Esri", + "ArcGIS API key": "Khóa API ArcGIS", + "Paste a new key to replace it": "Dán khóa mới để thay thế", + "Paste your key": "Dán khóa của bạn", + "Remove Key": "Xóa khóa", + "Get a free key at location.arcgis.com": "Nhận khóa miễn phí tại location.arcgis.com", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "Chỉ cấp cho khóa quyền ô bản đồ nền tĩnh. Khóa được lưu trong thư mục cài đặt của LightCraft (map-keys.json), không bao giờ trong thư viện của bạn, và chỉ được gửi tới máy chủ ô bản đồ của Esri. Chọn kiểu trong danh sách Kiểu bản đồ của chế độ xem Bản đồ.", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor (địa hình)", + "Set ArcGIS API Key": "Đặt khóa API ArcGIS" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 8af52409f3..5a7eb3db0b 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2480,5 +2480,19 @@ "Map tiles are off": "地图图块已关闭", "Offline (no tiles)": "离线(无图块)", "Custom tile server": "自定义图块服务器", - "Set the location of this photo": "设置这张照片的位置" + "Set the location of this photo": "设置这张照片的位置", + "Esri map layers": "Esri 地图图层", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Esri Streets 和 Esri Outdoor 地图样式需要你自己的 ArcGIS Location Platform API 密钥。免费账户每月有图块额度,图块计入你的密钥。Esri 的服务器会看到你查看了哪些地方。", + "Status": "状态", + "A key is set": "已设置密钥", + "No key: the Esri styles are not offered": "无密钥:不提供 Esri 样式", + "ArcGIS API key": "ArcGIS API 密钥", + "Paste a new key to replace it": "粘贴新密钥以替换", + "Paste your key": "粘贴你的密钥", + "Remove Key": "移除密钥", + "Get a free key at location.arcgis.com": "在 location.arcgis.com 获取免费密钥", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "只给密钥授予静态底图图块权限。它保存在 LightCraft 的设置文件夹(map-keys.json)中,从不保存在图库里,只发送给 Esri 的图块服务器。在地图视图的“地图样式”列表中选择样式。", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor(地形)", + "Set ArcGIS API Key": "设置 ArcGIS API 密钥" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 2bde2e68ef..3ee7521c92 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2481,5 +2481,19 @@ "Map tiles are off": "地圖圖磚已關閉", "Offline (no tiles)": "離線(無圖磚)", "Custom tile server": "自訂圖磚伺服器", - "Set the location of this photo": "設定這張照片的位置" + "Set the location of this photo": "設定這張照片的位置", + "Esri map layers": "Esri 地圖圖層", + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.": "Esri Streets 和 Esri Outdoor 地圖樣式需要你自己的 ArcGIS Location Platform API 金鑰。免費帳戶每月有圖磚額度,圖磚計入你的金鑰。Esri 的伺服器會看到你查看了哪些地方。", + "Status": "狀態", + "A key is set": "已設定金鑰", + "No key: the Esri styles are not offered": "無金鑰:不提供 Esri 樣式", + "ArcGIS API key": "ArcGIS API 金鑰", + "Paste a new key to replace it": "貼上新金鑰以取代", + "Paste your key": "貼上你的金鑰", + "Remove Key": "移除金鑰", + "Get a free key at location.arcgis.com": "在 location.arcgis.com 取得免費金鑰", + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.": "只給金鑰授予靜態底圖圖磚權限。它保存在 LightCraft 的設定資料夾(map-keys.json)中,從不保存在圖庫裡,只傳送給 Esri 的圖磚伺服器。在地圖檢視的「地圖樣式」清單中選擇樣式。", + "Esri Streets": "Esri Streets", + "Esri Outdoor (topographic)": "Esri Outdoor(地形)", + "Set ArcGIS API Key": "設定 ArcGIS API 金鑰" } diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 900ee796ca..fc92606f72 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -1,5 +1,5 @@ -//! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Faces, -//! AI Denoise. +//! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Map, +//! Faces, AI Denoise. //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, @@ -25,6 +25,7 @@ mod display; mod general; mod import; mod libraries; +mod map; mod performance; mod slideshow; mod widgets; @@ -36,6 +37,7 @@ use general::general_tab; use import::import_tab; pub(crate) use libraries::{can_switch_library, free_name}; pub use libraries::{forget_library, library_name, new_library, open_library, open_library_name, recent_libraries, remember_library}; +use map::map_tab; use performance::performance_tab; use slideshow::slideshow_tab; pub(crate) use widgets::{check, choices, heading, hint, row}; @@ -53,6 +55,7 @@ pub const TABS: &[(&str, &str)] = &[ ("display", "Display"), ("interface", "Interface"), ("slideshow", "Slideshow"), + ("map", "Map"), ("faces", "Faces"), ("denoise", "AI Denoise"), ]; @@ -71,6 +74,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &str) { "display" => display_tab(app, ui, &t), "interface" => interface_tab(app, ui, &t), "slideshow" => slideshow_tab(app, ui, &t, true), + "map" => map_tab(app, ui, &t), "faces" => crate::panels::faces::settings_tab(app, ui, &t), "denoise" => crate::panels::denoise::settings_tab(app, ui, &t), _ => general_tab(app, ui, &t), diff --git a/crates/ui-egui/src/dialogs/settings/map.rs b/crates/ui-egui/src/dialogs/settings/map.rs new file mode 100644 index 0000000000..1e51c2d3bb --- /dev/null +++ b/crates/ui-egui/src/dialogs/settings/map.rs @@ -0,0 +1,75 @@ +use super::widgets::{field, heading, hint, row}; +use super::{LightcraftApp, RichText, Tokens, json, register}; + +// ----------------------------------------------------------------------------------------- Map + +/// Where users get an ArcGIS Location Platform API key (free tier). +const ARCGIS_SIGN_UP: &str = "https://location.arcgis.com"; + +/// Settings ▸ Map: the ArcGIS API key the Esri layers need. The key typed here is applied with +/// Apply or Return (never while typing), then the field empties: the key is never shown again, +/// only whether one is set. It is kept outside `ui.json` and the library (`map.setEsriKey`). +pub(super) fn map_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + heading(ui, t, crate::i18n::tr("Esri map layers")); + hint( + ui, + t, + crate::i18n::tr( + "The Esri Streets and Esri Outdoor map styles need your own ArcGIS Location Platform API key. A free account gives a monthly tile allowance; tiles count against your key. Esri's server then sees which places you look at.", + ), + ); + let set = app.session.map.esri_key_set(); + row(ui, t, crate::i18n::tr("Status"), |ui| { + let text = if set { crate::i18n::tr("A key is set") } else { crate::i18n::tr("No key: the Esri styles are not offered") }; + let r = ui.label(RichText::new(text).color(if set { t.text } else { t.text_dim })); + register(ui, "settings:esriKeyStatus", r.rect); + }); + // the draft lives in egui's temporary memory only (never saved with the window state) + let draft_id = egui::Id::unique("settings:esriKeyDraft"); + let mut draft: String = ui.data_mut(|d| d.get_temp::(draft_id)).unwrap_or_default(); + let mut apply = false; + row(ui, t, crate::i18n::tr("ArcGIS API key"), |ui| { + let shown = field( + ui, + crate::text_field::TextField::singleline("field:esriKey", &mut draft) + .hint(crate::i18n::tr(if set { "Paste a new key to replace it" } else { "Paste your key" })) + .width(260.0), + ); + apply |= matches!(shown.ending, Some(crate::text_field::Ending::Return)); + let b = ui.add_enabled(!draft.trim().is_empty(), egui::Button::new(crate::i18n::tr("Apply"))); + register(ui, "button:esriKeyApply", b.rect); + apply |= b.clicked(); + let c = ui.add_enabled(set, egui::Button::new(crate::i18n::tr("Remove Key"))); + register(ui, "button:esriKeyClear", c.rect); + if c.clicked() { + if let Err(e) = app.run("map.setEsriKey", json!({"key": ""})) { + app.toast(ui.ctx(), e); + } + draft.clear(); + } + }); + if apply && !draft.trim().is_empty() { + match app.run("map.setEsriKey", json!({"key": draft.trim()})) { + Ok(_) => draft.clear(), + // a key of the wrong shape stays in the field to be corrected; nothing changed + Err(e) => app.toast(ui.ctx(), e), + } + } + ui.data_mut(|d| d.insert_temp(draft_id, draft)); + row(ui, t, "", |ui| { + let r = ui.link(crate::i18n::tr("Get a free key at location.arcgis.com")); + register(ui, "link:arcgisSignUp", r.rect); + if r.clicked() + && let Err(e) = crate::links::open(app, ARCGIS_SIGN_UP) + { + app.toast(ui.ctx(), e); + } + }); + hint( + ui, + t, + crate::i18n::tr( + "Give the key only the static basemap tiles privilege. It is kept in LightCraft's settings folder (map-keys.json), never in your library, and sent only to Esri's tile server. Choose the style in the Map view's Map Style list.", + ), + ); +} diff --git a/crates/ui-egui/src/panels/map.rs b/crates/ui-egui/src/panels/map.rs index 9b55b8fd77..31c1aad595 100644 --- a/crates/ui-egui/src/panels/map.rs +++ b/crates/ui-egui/src/panels/map.rs @@ -548,7 +548,8 @@ fn render_bottom_toolbar(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rec // the tile provider's credit, always visible at the bottom right (tile licences require it) ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_space(12.0); - let credit = ui.label(egui::RichText::new(current.attribution()).small().color(Color32::from_white_alpha(170))); + // the source's credit; an Esri layer's comes from its metadata once fetched + let credit = ui.label(egui::RichText::new(app.session.map.attribution()).small().color(Color32::from_white_alpha(170))); crate::widgets::register(ui, "map:attribution", credit.rect); }); }); @@ -1012,9 +1013,9 @@ mod tests { assert!(session.map.service().is_some_and(|s| s.is_idle() && s.stats().requests == 0)); } - /// The Esri layers are not in the Map Style list (their terms, docs/map.md). + /// The Esri layers are not in the Map Style list without an ArcGIS API key (docs/map.md). #[test] - fn the_map_style_list_has_no_esri_layer() { + fn the_map_style_list_has_no_esri_layer_without_a_key() { let session = lightcraft_engine::Session::new(); let offered: Vec = session.map.offered().iter().map(|s| s.label().to_string()).collect(); assert_eq!(offered, vec!["OpenStreetMap", "OpenTopoMap", "Offline (no tiles)"]); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 8d8da4c580..17d2ba0fa6 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -59,6 +59,7 @@ mod library_problem; mod lifecycle_037; mod lightroom_destination; mod lights_out; +mod map_esri; mod map_filmstrip; mod mask_effects; mod masking; diff --git a/crates/ui-egui/src/tests/map_esri.rs b/crates/ui-egui/src/tests/map_esri.rs new file mode 100644 index 0000000000..9fb9821805 --- /dev/null +++ b/crates/ui-egui/src/tests/map_esri.rs @@ -0,0 +1,70 @@ +//! Settings ▸ Map (step 1.3b of the map work): the ArcGIS API key the Esri styles need is typed +//! there, applied on Return (never while typing), then never shown again; the Map Style list +//! offers the Esri styles only once a key is set; the key never reaches `ui.json`. The map is +//! never online in tests. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const KEY: &str = "AAPK0123456789abcdef_TEST-key.x"; + +fn widget(h: &Headless, id: &str) -> Option { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r) +} + +fn frames(h: &mut Headless, n: usize) { + for _ in 0..n { + h.step(); + } +} + +fn ok(h: &mut Headless, method: &str, params: serde_json::Value) { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{method}: {r}"); +} + +/// Type `text` into the key field and press Return. +fn type_key(h: &mut Headless, text: &str) { + ok(h, "ui.clickWidget", json!({"id": "field:esriKey"})); + frames(h, 2); + ok(h, "ui.text", json!({"text": text})); + frames(h, 2); +} + +#[test] +fn the_esri_key_is_applied_on_return_and_never_shown_or_saved_with_the_window() { + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()), [1300.0, 900.0], 1.0); + ok(&mut h, "engine.execute", json!({"command": "app.settings", "params": {"tab": "map"}})); + frames(&mut h, 4); + assert!(widget(&h, "settings:esriKeyStatus").is_some(), "the Map tab shows the key status"); + assert!(widget(&h, "link:arcgisSignUp").is_some(), "and where to get a key"); + // typing alone changes nothing + type_key(&mut h, KEY); + assert!(!h.app.session.map.esri_key_set(), "not applied while typing"); + ok(&mut h, "ui.key", json!({"key": "Enter"})); + frames(&mut h, 3); + assert!(h.app.session.map.esri_key_set(), "Return applies it"); + // the field is empty again, and the key is in no saved window state + let draft: Option = h.view.ctx.data(|d| d.get_temp(egui::Id::unique("settings:esriKeyDraft"))); + assert!(draft.unwrap_or_default().is_empty(), "the field forgets the key once applied"); + assert!(!serde_json::to_string(&h.app.ui).unwrap().contains(KEY), "ui.json never holds the key"); + // the Map Style list now offers the Esri styles + let offered: Vec = h.app.session.map.offered().iter().map(|s| s.id().to_string()).collect(); + assert_eq!(offered, vec!["osm", "opentopomap", "esri-streets", "esri-topo", "offline"]); + // a key of the wrong shape is refused, stays in the field, and the old one stays set + type_key(&mut h, "not a key"); + ok(&mut h, "ui.key", json!({"key": "Enter"})); + frames(&mut h, 3); + assert!(h.app.session.map.esri_key_set()); + assert!(h.app.ui.toast.as_ref().is_some_and(|t| t.0.contains("ArcGIS API key") && !t.0.contains("not a key")), "{:?}", h.app.ui.toast); + // Remove Key clears it + let remove = widget(&h, "button:esriKeyClear").expect("Remove Key").center(); + ok(&mut h, "ui.click", json!({"x": remove.x, "y": remove.y})); + frames(&mut h, 3); + assert!(!h.app.session.map.esri_key_set()); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9cdae4021f..d5417bd6a2 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -107,7 +107,8 @@ filmstrip is visible. | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | | `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | -| `engine.execute {command: "map.tileSource"}` | `{}`, `{id: "osm"\|"opentopomap"\|"offline"}`, `{offline: true\|false}` or `{urlTemplate, attribution, maxZoom?, id?}` | The map's tile source (OpenStreetMap by default; custom `https://` templates with `{z}/{x}/{y}` only; the Esri layers are refused, see `docs/map.md`), saved with the library preferences → `{id, label, urlTemplate, attribution, maxZoom, userAgent, offline, custom, saved, notice, esriEnabled}`; `saved`/`notice` name a stored source the map can't use (it shows OpenStreetMap) | +| `engine.execute {command: "map.tileSource"}` | `{}`, `{id: "osm"\|"opentopomap"\|"esri-streets"\|"esri-topo"\|"offline"}`, `{offline: true\|false}` or `{urlTemplate, attribution, maxZoom?, id?}` | The map's tile source (OpenStreetMap by default; custom `https://` templates with `{z}/{x}/{y}` only; the Esri styles need an ArcGIS API key (`map.setEsriKey`) and are refused without one, see `docs/map.md`), saved with the library preferences → `{id, label, urlTemplate, attribution, maxZoom, userAgent, offline, custom, saved, notice, esriKeySet}`; `saved`/`notice` name a stored source the map can't use (it shows OpenStreetMap) | +| `engine.execute {command: "map.setEsriKey"}` | `{key}` (`""` or null removes it) | The ArcGIS Location Platform API key for the Esri map styles, kept in the config folder (`map-keys.json`), never journaled; shape-checked only (no network call) → `{esriKeySet, notice}`. The key itself is never reported, by this or any command | | `engine.execute {command: "map.providers"}` | — | The tile sources the map offers now → `[{id, label, maxZoom, attribution, offline, current}]` | | `engine.execute {command: "map.cacheInfo"}` | — | The on-disk tile cache → `{bytes, tiles, capBytes, dir}` (`dir` null: no disk cache) | | `engine.execute {command: "map.clearCache"}` | — | Deletes every cached tile (all sources) → `{bytes, tiles, dir}` deleted | diff --git a/docs/gaps.md b/docs/gaps.md index a93ef6b2ba..bc5cc89838 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 view, saved locations and filter ✅ (OpenStreetMap / OpenTopoMap / custom tiles under the OSM tile policy; Esri off, see docs/map.md); geotag 🟡 (filmstrip photos drop onto the map; no pin move or Remove GPS menu yet); 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 view, saved locations and filter ✅ (OpenStreetMap / OpenTopoMap / custom tiles under the OSM tile policy; Esri styles with the user's own ArcGIS key, see docs/map.md); geotag 🟡 (filmstrip photos drop onto the map; no pin move or Remove GPS menu yet); 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/map.md b/docs/map.md index 00a3008102..7a269867ae 100644 --- a/docs/map.md +++ b/docs/map.md @@ -84,29 +84,76 @@ LightCraft uses OpenStreetMap's tile server under its tile usage policy Sessions that a host has not put online (tests, the web build) never fetch tiles. -## Esri layers (off) +## Esri layers (your own ArcGIS key) -Earlier builds of this branch offered Esri's World Imagery, World Street Map, World Topographic Map and a -Hybrid layer, fetched from `server.arcgisonline.com` without an account. They are **off and cannot be -turned on** in this build: the Map Style list does not offer them, `map.tileSource` refuses them with an -error naming this page, and nothing is ever fetched from Esri. A library saved with an Esri layer opens on -OpenStreetMap with a one-line notice; `prefs.json` keeps the Esri choice. +Two Esri map styles are offered once you give LightCraft your own ArcGIS Location Platform API key: +**Esri Streets** (`esri-streets`, Esri's `arcgis/streets` style) and **Esri Outdoor (topographic)** +(`esri-topo`, the `arcgis/outdoor` style). This is the "bring your own key" pattern of QGIS, darktable and +digiKam: LightCraft has no Esri account of its own, and your tile use counts against your key. -Why: Esri's terms for these layers do not allow this use. Each layer's ArcGIS Online item -(e.g. for World Imagery) says it is -"licensed under the Esri Master License Agreement" and links its terms. The terms summary -(, "Last Updated: April 21, 2025", read -2026-11-14) lists as conditions "Use with Esri software and comply with its terms of use. If you do not have -Esri software, you must purchase an ArcGIS Online subscription", and among what you may not do, -"Systematically harvest basemap tiles through any method other than using Esri Content Packages" and "Use -content from ArcGIS Living Atlas for commercial use in your application or product". LightCraft is not Esri -software and has no ArcGIS subscription. The full terms are the Esri Master Agreement -(). The layers' required credits, kept in the code -for when this changes, come from each item's `accessInformation` -(). +**Setting it up.** Create a free ArcGIS Location Platform account at , create an +API key with the static basemap tiles privilege (`premium:user:staticbasemaptiles`) and nothing else, and paste +it in Settings ▸ Map ▸ ArcGIS API key, then press Return or Apply (`map.setEsriKey {key}`; `""` removes it). +The key is checked for its shape only; nothing is sent until a map shows an Esri style. The Esri styles then +appear in the Map Style list at the bottom of the map. -Turning them on would need a maintainer decision, for example a user-supplied ArcGIS key through Esri's -token-based basemap service, with the privacy note that Esri's server then sees which places you look at. +**Without a key** the Esri styles are not in the Map Style list, `map.tileSource` refuses them with a message +saying a key is needed and where to get one, and nothing is fetched from Esri. A library saved with an Esri +style opens on OpenStreetMap with a one-line notice; `prefs.json` keeps the Esri choice, which comes back once +a key is set. + +**The key is a secret.** It is kept in LightCraft's settings folder in `map-keys.json` (readable only by you +on macOS and Linux), never in the library, `prefs.json` or `ui.json`. It is not journaled, never logged, never +shown again after you apply it (Settings shows only whether one is set), and `map.tileSource`, +`map.providers` and `map.setEsriKey` report only `esriKeySet: true | false`. It is sent only to Esri's tile +server, as the `token` query parameter of tile and metadata requests. The tile cache is keyed by style and +tile (`maptiles/esri-streets///.tile`), never by URL, so the key is in no file name or cache entry; +an error message that would quote a request URL has the key replaced by `[key]`. + +**The service.** Tiles come from Esri's static basemap tiles service, +`https://static-map-tiles-api.arcgis.com/arcgis/rest/services/static-basemap-tiles-service/v1/arcgis/