diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index ad42b357ed..81285b37fa 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -261,7 +261,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) @@ -284,9 +284,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."))); @@ -297,7 +304,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/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 787a37a302..57ab3b3e14 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -53,6 +53,12 @@ pub enum Kind { /// One of a fixed set: (id, label). Rules store the id; people see the label. Choice(&'static [(&'static str, &'static str)]), Bool, + /// A place on Earth, `{south, west, north, east}` in degrees ([`GpsArea`]): the photo's GPS + /// position is inside it or outside it. + Area, + /// A circle on Earth, `{lat, lon, radius}` (degrees, metres; [`GpsCircle`]): the photo's GPS + /// position is within `radius` of the centre (along the Earth's surface) or not. + Circle, } /// The fields rules can test: (id, label, kind), in field-menu order ([`TOP_LEVEL_FIELDS`], then @@ -115,6 +121,8 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("state", "State / Province", Kind::Text), ("country", "Country", Kind::Text), ("hasGps", "Has GPS", Kind::Bool), + ("gpsArea", "GPS Area", Kind::Area), + ("gpsRadius", "GPS Radius", Kind::Circle), // Size ("longEdge", "Long Edge", Kind::Number), ("shortEdge", "Short Edge", Kind::Number), @@ -141,7 +149,7 @@ pub const FIELD_GROUPS: &[(&str, &[&str])] = &[ ("Keywords & People", &["keywords", "keywordCount", "person", "personCount"]), ("Description", &["title", "caption", "altText", "creator", "copyright", "copyrightStatus"]), ("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso", "flash", "exposureBias", "cameraSerial"]), - ("Location", &["location", "city", "state", "country", "hasGps"]), + ("Location", &["location", "city", "state", "country", "hasGps", "gpsArea", "gpsRadius"]), ("Size", &["longEdge", "shortEdge", "aspect", "megapixels"]), ("Develop", &["edited", "cropped", "treatment"]), ("Assisted Culling", &["sharpness", "bestOfGroup"]), @@ -200,10 +208,16 @@ pub enum Issue { AlbumLoop, FolderAlbum, EmptyGroup, + /// GPS Area: not four numbers in range. + NeedsArea, + /// GPS Area: its south edge is north of its north edge. + AreaReversed, + /// GPS Radius: not a centre in range and a radius of 1 m to 1000 km. + NeedsCircle, } impl Issue { - pub const ALL: [Issue; 22] = [ + pub const ALL: [Issue; 25] = [ Issue::UnknownField, Issue::NoSuchOperator, Issue::NotYesNo, @@ -226,6 +240,9 @@ impl Issue { Issue::AlbumLoop, Issue::FolderAlbum, Issue::EmptyGroup, + Issue::NeedsArea, + Issue::AreaReversed, + Issue::NeedsCircle, ]; /// The issue in a few words, to follow the field's name; a message for translation catalogs. @@ -253,6 +270,9 @@ impl Issue { Issue::AlbumLoop => "would make this album include itself through other smart albums", Issue::FolderAlbum => "can't test a folder; choose an album in it", Issue::EmptyGroup => "This group is empty: add a rule or remove it.", + Issue::NeedsArea => "needs south, west, north and east in degrees (latitude −90…90, longitude −180…180)", + Issue::AreaReversed => "has its south edge north of its north edge", + Issue::NeedsCircle => "needs a centre (latitude −90…90, longitude −180…180) and a radius of 1 m to 1000 km", } } } @@ -272,6 +292,16 @@ fn field_problem(field: &str, op: &str, value: &Value, cat: &Catalog, owner: Opt match kind { Kind::Bool => bool_value(value).is_none().then(|| (Issue::NotYesNo, format!("`{field}` is yes or no, not {value}"))), Kind::Album => album_problem(value, cat, owner), + Kind::Area => GpsArea::parse(value).err().map(|issue| { + let message = match issue { + Issue::AreaReversed => format!("`{field}`: the south edge is north of the north edge in {value}"), + _ => format!("`{field}` needs {{south, west, north, east}} in degrees (latitude −90…90, longitude −180…180), not {value}"), + }; + (issue, message) + }), + Kind::Circle => GpsCircle::parse(value).err().map(|issue| { + (issue, format!("`{field}` needs {{lat, lon, radius}}: a centre in degrees (latitude −90…90, longitude −180…180) and a radius of 1 m to 1000 km, not {value}")) + }), Kind::Number => { let each = match value { Value::Array(a) if op == "between" && a.len() == 2 => a.iter().find_map(|v| number_problem(field, v)), @@ -598,6 +628,176 @@ pub fn bool_label(b: bool) -> &'static str { if b { "Yes" } else { "No" } } +/// A photo's GPS position (`(latitude, longitude)`, as `Meta.gps` stores it) when it is one: both +/// finite, latitude −90…90, longitude −180…180. Rules (Has GPS, GPS Area) and the map read +/// positions this way, so a corrupt one is never "on the map". +pub fn valid_gps(gps: Option<(f64, f64)>) -> Option<(f64, f64)> { + gps.filter(|(lat, lon)| lat.is_finite() && lon.is_finite() && (-90.0..=90.0).contains(lat) && (-180.0..=180.0).contains(lon)) +} + +/// The value of a GPS Area rule: a latitude / longitude box in degrees, `{south, west, north, +/// east}`. `east < west` means the box crosses the antimeridian (±180°) and wraps: `{west: 170, +/// east: -170}` is the 20° around it. `west: -180, east: 180` is every longitude. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpsArea { + pub south: f64, + pub west: f64, + pub north: f64, + pub east: f64, +} + +impl GpsArea { + /// The whole world. + pub const WORLD: GpsArea = GpsArea { south: -90.0, west: -180.0, north: 90.0, east: 180.0 }; + + /// A rule's value as an area: an object with the four edges as finite numbers, latitudes + /// −90…90 (south not north of north), longitudes −180…180. Anything else (NaN, a missing + /// edge, text, out of range) is [`Issue::NeedsArea`] or [`Issue::AreaReversed`], and matches + /// nothing. + pub fn parse(value: &Value) -> Result { + let edge = |k: &str| value.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or(Issue::NeedsArea); + let a = GpsArea { south: edge("south")?, west: edge("west")?, north: edge("north")?, east: edge("east")? }; + let lat = |v: f64| (-90.0..=90.0).contains(&v); + let lon = |v: f64| (-180.0..=180.0).contains(&v); + if !(lat(a.south) && lat(a.north) && lon(a.west) && lon(a.east)) { + return Err(Issue::NeedsArea); + } + if a.south > a.north { + return Err(Issue::AreaReversed); + } + Ok(a) + } + + /// The rule value: `{south, west, north, east}`. + pub fn to_value(self) -> Value { + serde_json::json!({"south": self.south, "west": self.west, "north": self.north, "east": self.east}) + } + + /// Whether the position `lat`, `lon` (degrees) is inside, edges included. Longitude ±180 is + /// one meridian: a box reaching either side of it holds both. + pub fn contains(&self, lat: f64, lon: f64) -> bool { + if !(lat >= self.south && lat <= self.north) || !lon.is_finite() { + return false; + } + let within = |lon: f64| if self.west <= self.east { lon >= self.west && lon <= self.east } else { lon >= self.west || lon <= self.east }; + within(lon) || (lon.abs() == 180.0 && within(-lon)) + } + + /// `12.5, -4 – 13, 2.25` (south, west – north, east), as rule summaries show it. + pub fn describe(&self) -> String { + format!("{}, {} – {}, {}", self.south, self.west, self.north, self.east) + } +} + +/// Mean radius of the Earth in metres (IUGG), for distances along its surface. +pub const EARTH_RADIUS_M: f64 = 6_371_008.8; +/// The smallest and largest radius of a [`GpsCircle`] (metres): 1 m to 1000 km. +pub const MIN_RADIUS_M: f64 = 1.0; +pub const MAX_RADIUS_M: f64 = 1_000_000.0; + +/// The distance in metres between two positions (degrees) along the Earth's surface (haversine, +/// on a sphere of [`EARTH_RADIUS_M`]). Exact across the antimeridian and at the poles; NaN in, +/// NaN out (and NaN compares as "not within" anything). +pub fn distance_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 { + let (p1, p2) = (lat1.to_radians(), lat2.to_radians()); + let dp = p2 - p1; + let dl = (lon2 - lon1).to_radians(); + let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2); + 2.0 * EARTH_RADIUS_M * a.clamp(0.0, 1.0).sqrt().asin() +} + +/// The position `dist_m` metres from `lat, lon` (degrees) heading `bearing_deg` (0 = north, +/// clockwise), along a great circle. The longitude is returned *unwrapped* (`lon` plus the +/// change, possibly beyond ±180) so that a ring of points around a centre stays continuous. +pub fn destination(lat: f64, lon: f64, bearing_deg: f64, dist_m: f64) -> (f64, f64) { + let d = dist_m / EARTH_RADIUS_M; + let (p1, b) = (lat.to_radians(), bearing_deg.to_radians()); + let p2 = (p1.sin() * d.cos() + p1.cos() * d.sin() * b.cos()).clamp(-1.0, 1.0).asin(); + let dl = (b.sin() * d.sin() * p1.cos()).atan2(d.cos() - p1.sin() * p2.sin()); + (p2.to_degrees(), lon + dl.to_degrees()) +} + +/// The value of a GPS Radius rule and the shape of a saved location: the positions within +/// `radius` metres of `lat, lon` (degrees) along the Earth's surface, edge included. Measured on +/// the sphere, so a circle across the antimeridian or around a pole needs nothing special. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpsCircle { + pub lat: f64, + pub lon: f64, + /// Metres, [`MIN_RADIUS_M`]…[`MAX_RADIUS_M`]. + pub radius: f64, +} + +impl GpsCircle { + /// A circle when the numbers make one: all finite, latitude −90…90, longitude −180…180, + /// radius 1 m…1000 km. Anything else is [`Issue::NeedsCircle`]. + pub fn new(lat: f64, lon: f64, radius: f64) -> Result { + let ok = lat.is_finite() + && lon.is_finite() + && radius.is_finite() + && (-90.0..=90.0).contains(&lat) + && (-180.0..=180.0).contains(&lon) + && (MIN_RADIUS_M..=MAX_RADIUS_M).contains(&radius); + if ok { Ok(GpsCircle { lat, lon, radius }) } else { Err(Issue::NeedsCircle) } + } + + /// A rule's value `{lat, lon, radius}` as a circle ([`GpsCircle::new`]'s checks). + pub fn parse(value: &Value) -> Result { + let n = |k: &str| value.get(k).and_then(Value::as_f64).ok_or(Issue::NeedsCircle); + GpsCircle::new(n("lat")?, n("lon")?, n("radius")?) + } + + /// The rule value: `{lat, lon, radius}`. + pub fn to_value(self) -> Value { + serde_json::json!({"lat": self.lat, "lon": self.lon, "radius": self.radius}) + } + + /// Whether `lat, lon` (degrees) is within the radius, edge included (a millimetre of slack + /// for rounding). A position that isn't one (NaN) is not. + pub fn contains(&self, lat: f64, lon: f64) -> bool { + distance_m(self.lat, self.lon, lat, lon) <= self.radius + 1e-3 + } + + /// The latitudes the circle reaches, `(south, north)` in degrees, clamped to the poles: every + /// position inside has a latitude in this range (a cheap first test before + /// [`GpsCircle::contains`]). + pub fn lat_range(&self) -> (f64, f64) { + let d = (self.radius / EARTH_RADIUS_M).to_degrees(); + ((self.lat - d).max(-90.0), (self.lat + d).min(90.0)) + } + + /// The pole inside the circle, if any: `Some(true)` the north pole, `Some(false)` the south. + pub fn pole(&self) -> Option { + if self.contains(90.0, 0.0) { + Some(true) + } else if self.contains(-90.0, 0.0) { + Some(false) + } else { + None + } + } + + /// `within 500 m of 48.8584, 2.2945`, as rule summaries show it. + pub fn describe(&self) -> String { + format!("within {} of {}, {}", format_distance(self.radius), self.lat, self.lon) + } +} + +/// `850 m`, `1.5 km`, `120 km`: a radius as people read it. +pub fn format_distance(m: f64) -> String { + if !m.is_finite() { + return "? m".into(); + } + if m < 1000.0 { + format!("{} m", m.round()) + } else if m < 10_000.0 { + let km = (m / 100.0).round() / 10.0; + format!("{km} km") + } else { + format!("{} km", (m / 1000.0).round()) + } +} + /// The display label of choice `id` of `field` ("Public Domain" for `publicDomain`); `None` when /// `field` isn't a choice field or has no such choice. pub fn choice_label(field: &str, id: &str) -> Option<&'static str> { @@ -645,6 +845,7 @@ pub fn ops_for(kind: Kind) -> &'static [(&'static str, &'static str)] { ], Kind::Choice(_) | Kind::Album => &[("is", "is"), ("isNot", "isn't")], Kind::Bool => &[("is", "is")], + Kind::Area | Kind::Circle => &[("inside", "is inside"), ("outside", "is outside")], } } @@ -1058,6 +1259,27 @@ impl Rule { return file_path_matches(op, &p.source, value); } let m = &p.meta; + // the GPS fields first: they don't need the value as text (a GPS Area's would be its JSON, + // written out for every photo of a Visible on Map filter) + match field { + // a position the map can place (NaN or out of range counts as none, as on the map) + "hasGps" => return bool_value(value).is_some_and(|b| valid_gps(m.gps).is_some() == b), + // a photo without a position is in no area, and outside none + "gpsArea" => { + return match (valid_gps(m.gps), GpsArea::parse(value)) { + (Some((lat, lon)), Ok(area)) => area.contains(lat, lon) == (op == "inside"), + _ => false, + }; + } + // within a distance of a point (a saved location's circle) + "gpsRadius" => { + return match (valid_gps(m.gps), GpsCircle::parse(value)) { + (Some((lat, lon)), Ok(c)) => c.contains(lat, lon) == (op == "inside"), + _ => false, + }; + } + _ => {} + } let want = lower(value); let text = |have: &str| text_op(op, have, &want); let yes = |have: bool| bool_value(value).is_some_and(|b| have == b); @@ -1075,7 +1297,6 @@ impl Rule { } "kind" => (kind_name(p.kind) == want) == (op == "is"), "edited" => yes(p.is_edited()), - "hasGps" => yes(m.gps.is_some()), "virtualCopy" => yes(p.copy_of.is_some()), "copyName" => text(p.copy_name.as_deref().unwrap_or("")), "stacked" => yes(cat.stack_of(p.id).is_some()), @@ -1319,6 +1540,8 @@ impl RuleSet { let op = field_kind(field).and_then(|k| ops_for(k).iter().find(|o| o.0 == op)).map_or(op.as_str(), |o| o.1); let v = match value { _ if field == "album" && cat.is_some() => album_name(value, cat), + _ if field_kind(field) == Some(Kind::Area) => GpsArea::parse(value).map_or_else(|_| value.to_string(), |a| a.describe()), + _ if field_kind(field) == Some(Kind::Circle) => GpsCircle::parse(value).map_or_else(|_| value.to_string(), |c| c.describe()), _ if field_kind(field) == Some(Kind::Bool) => { bool_value(value).map_or_else(|| value.to_string(), |b| bool_label(b).to_lowercase()) } diff --git a/crates/catalog/src/rules/tests.rs b/crates/catalog/src/rules/tests.rs index 35b5e9e155..e68b2263be 100644 --- a/crates/catalog/src/rules/tests.rs +++ b/crates/catalog/src/rules/tests.rs @@ -747,7 +747,7 @@ fn related_fields_share_a_group() { same(&["captureDate", "importDate", "editDate"], "Date"); same(&["keywords", "keywordCount", "person", "personCount"], "Keywords & People"); same(&["title", "caption", "altText", "creator", "copyright", "copyrightStatus"], "Description"); - same(&["location", "city", "state", "country", "hasGps"], "Location"); + same(&["location", "city", "state", "country", "hasGps", "gpsArea", "gpsRadius"], "Location"); for f in ["rating", "flag", "label", "text"] { assert_eq!(field_group(f), None, "{f} stays at the top level"); } @@ -887,3 +887,236 @@ fn shutter_speed_rules_match_the_shown_value() { assert!(m(&p, "is", json!("1/3")) && !m(&p, "isNot", json!("1/3")), "3333/10000 s is the 1/3 it shows"); assert!(m(&p, "gte", json!("1/3")) && m(&p, "lte", json!("1/3")) && !m(&p, "lt", json!("1/3"))); } +fn at(gps: Option<(f64, f64)>) -> Photo { + let mut p = photo(7); + p.meta.gps = gps; + p +} + +fn area(south: f64, west: f64, north: f64, east: f64) -> serde_json::Value { + json!({"south": south, "west": west, "north": north, "east": east}) +} + +fn in_area(p: &Photo, op: &str, value: serde_json::Value) -> bool { + rs(json!({"rules": [{"field": "gpsArea", "op": op, "value": value}]})).matches(p, &Catalog::new()) +} + +/// GPS Area: inside / outside a box, edges included; a photo without a position (or with one +/// that isn't a position) is in neither. +#[test] +fn gps_area_matches_positions_in_the_box() { + let paris = at(Some((48.8584, 2.2945))); + let europe = area(35.0, -10.0, 60.0, 30.0); + assert!(in_area(&paris, "inside", europe.clone())); + assert!(!in_area(&paris, "outside", europe.clone())); + let usa = area(25.0, -125.0, 49.0, -67.0); + assert!(!in_area(&paris, "inside", usa.clone())); + assert!(in_area(&paris, "outside", usa)); + // the edges are inside + assert!(in_area(&at(Some((35.0, -10.0))), "inside", europe.clone())); + assert!(in_area(&at(Some((60.0, 30.0))), "inside", europe.clone())); + // no position, or a corrupt one: in no area and outside none + for gps in [None, Some((f64::NAN, 2.0)), Some((48.0, f64::INFINITY)), Some((91.0, 2.0)), Some((48.0, -181.0))] { + let p = at(gps); + assert!(!in_area(&p, "inside", area(-90.0, -180.0, 90.0, 180.0)), "{gps:?}"); + assert!(!in_area(&p, "outside", europe.clone()), "{gps:?}"); + } + // the whole world holds every position, poles and antimeridian included + for gps in [(90.0, 0.0), (-90.0, 0.0), (0.0, 180.0), (0.0, -180.0), (-33.9, 151.2)] { + assert!(in_area(&at(Some(gps)), "inside", GpsArea::WORLD.to_value()), "{gps:?}"); + } + // a value that isn't an area matches nothing, either way + for bad in [json!(null), json!("europe"), area(f64::NAN, 0.0, 1.0, 1.0), area(60.0, -10.0, 35.0, 30.0)] { + assert!(!in_area(&paris, "inside", bad.clone()) && !in_area(&paris, "outside", bad.clone()), "{bad}"); + } +} + +/// East < west: the box crosses the antimeridian and wraps around it (a map view over the +/// Pacific). +#[test] +fn gps_area_wraps_across_the_antimeridian() { + let pacific = area(-30.0, 170.0, 30.0, -170.0); + let fiji = at(Some((-17.7, 178.0))); + let samoa = at(Some((-13.8, -172.0))); + let dateline = at(Some((0.0, 180.0))); + let dateline_west = at(Some((0.0, -180.0))); + let hawaii = at(Some((21.3, -157.8))); + let new_zealand = at(Some((-41.3, 174.8))); + for p in [&fiji, &samoa, &dateline, &dateline_west] { + assert!(in_area(p, "inside", pacific.clone()), "{:?}", p.meta.gps); + } + for p in [&hawaii, &new_zealand, &at(Some((0.0, 0.0)))] { + assert!(!in_area(p, "inside", pacific.clone()) && in_area(p, "outside", pacific.clone()), "{:?}", p.meta.gps); + } + // a box ending at +180 holds −180 (the same meridian), and one starting at −180 holds +180 + assert!(in_area(&dateline_west, "inside", area(-10.0, 170.0, 10.0, 180.0))); + assert!(in_area(&dateline, "inside", area(-10.0, -180.0, 10.0, -170.0))); + // not wrapping: −170…170 is most of the world, without the Pacific strip + assert!(!in_area(&fiji, "inside", area(-30.0, -170.0, 30.0, 170.0))); +} + +#[test] +fn gps_area_values_are_checked() { + let cat = Catalog::new(); + let check = |value: serde_json::Value, op: &str| { + rs(json!({"rules": [{"field": "gpsArea", "op": op, "value": value}]})).check(&cat).into_iter().map(|p| p.issue).collect::>() + }; + assert!(check(area(35.0, -10.0, 60.0, 30.0), "inside").is_empty()); + assert!(check(area(-30.0, 170.0, 30.0, -170.0), "outside").is_empty(), "east < west wraps: fine"); + assert!(check(GpsArea::WORLD.to_value(), "inside").is_empty()); + for bad in [ + json!(null), + json!("everywhere"), + json!([35.0, -10.0, 60.0, 30.0]), + json!({"south": 35.0, "west": -10.0, "north": 60.0}), + json!({"south": "35", "west": -10.0, "north": 60.0, "east": 30.0}), + area(-91.0, 0.0, 10.0, 10.0), + area(0.0, 0.0, 90.5, 10.0), + area(0.0, -180.5, 10.0, 10.0), + area(0.0, 0.0, 10.0, 181.0), + ] { + assert_eq!(check(bad.clone(), "inside"), vec![Issue::NeedsArea], "{bad}"); + } + // NaN and infinities never reach a rule as JSON numbers, but a value built in code can hold them + let nan = Rule::Field { field: "gpsArea".into(), op: "inside".into(), value: area(f64::NAN, 0.0, 10.0, 10.0) }; + assert_eq!(RuleSet { mode: Match::All, rules: vec![nan] }.check(&cat).len(), 1); + assert_eq!(GpsArea::parse(&area(f64::NAN, 0.0, 1.0, 1.0)), Err(Issue::NeedsArea)); + assert_eq!(check(area(60.0, -10.0, 35.0, 30.0), "inside"), vec![Issue::AreaReversed]); + assert_eq!(check(area(35.0, -10.0, 60.0, 30.0), "is"), vec![Issue::NoSuchOperator]); + // summaries read the box + let r = rs(json!({"rules": [{"field": "gpsArea", "op": "inside", "value": area(35.0, -10.0, 60.0, 30.5)}]})); + assert_eq!(r.describe(), "gps area is inside 35, -10 – 60, 30.5"); +} + +/// Has GPS reads positions as the map does: a corrupt one (NaN, out of range) is no position. +#[test] +fn has_gps_ignores_positions_that_are_not_ones() { + let has = |p: &Photo, b: bool| rs(json!({"rules": [{"field": "hasGps", "op": "is", "value": b}]})).matches(p, &Catalog::new()); + assert!(has(&at(Some((48.8, 2.3))), true)); + for gps in [None, Some((f64::NAN, 2.0)), Some((95.0, 2.0)), Some((0.0, 200.0))] { + assert!(!has(&at(gps), true) && has(&at(gps), false), "{gps:?}"); + } +} + +/// A smart album of the photos in an area (and one of those without GPS) follows the +/// photos as they are tagged and untagged. +#[test] +fn a_smart_album_can_hold_an_area() { + use crate::{Album, AlbumId, Filter, Op}; + let mut cat = Catalog::new(); + let mut add = |gps: Option<(f64, f64)>| { + let id = cat.alloc_photo_id(); + let mut p = Photo::new(id, Source::Demo { scene: 0 }, "a.jpg", "JPEG", 600, 400, "2026-09-20T10:00:00"); + p.meta.gps = gps; + cat.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + id + }; + let paris = add(Some((48.8584, 2.2945))); + let fiji = add(Some((-17.7, 178.0))); + let nowhere = add(None); + let rules = |v: serde_json::Value| Filter { rule_set: Some(rs(v)), ..Default::default() }; + let pacific = rules(json!({"rules": [{"field": "gpsArea", "op": "inside", "value": area(-30.0, 170.0, 30.0, -170.0)}]})); + let untagged = rules(json!({"rules": [{"field": "hasGps", "op": "is", "value": false}]})); + assert!(pacific.rule_set.as_ref().unwrap().check(&cat).is_empty()); + cat.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(pacific)), ..Album::new(AlbumId(1), "Pacific") } }).unwrap(); + cat.apply(Op::AddAlbum { album: Album { smart: Some(Box::new(untagged)), ..Album::new(AlbumId(2), "No GPS") } }).unwrap(); + assert_eq!(cat.album_photos(AlbumId(1)), vec![fiji]); + assert_eq!(cat.album_photos(AlbumId(2)), vec![nowhere]); + // tag the untagged photo in Samoa: it moves from one album to the other + let mut meta = cat.photo(nowhere).unwrap().meta.clone(); + meta.gps = Some((-13.8, -172.0)); + cat.apply(Op::SetMeta { id: nowhere, meta: Box::new(meta) }).unwrap(); + let mut pac = cat.album_photos(AlbumId(1)); + pac.sort(); + assert_eq!(pac, vec![fiji, nowhere]); + assert!(cat.album_photos(AlbumId(2)).is_empty()); + assert_eq!(cat.album_count(AlbumId(1)), 2); + let _ = paris; +} + +fn in_circle(p: &Photo, op: &str, value: serde_json::Value) -> bool { + rs(json!({"rules": [{"field": "gpsRadius", "op": op, "value": value}]})).matches(p, &Catalog::new()) +} + +/// GPS Radius: within a distance of a point, measured on the sphere: across the antimeridian +/// and around a pole as anywhere else; a photo without a position is in no circle and outside +/// none; a circle that isn't one matches nothing and is reported. +#[test] +fn gps_radius_matches_positions_within_the_distance() { + let eiffel = (48.8584, 2.2945); + let notre_dame = (48.8530, 2.3499); + // ~4.1 km apart + let d = distance_m(eiffel.0, eiffel.1, notre_dame.0, notre_dame.1); + assert!((4000.0..4200.0).contains(&d), "{d}"); + let c = |lat: f64, lon: f64, r: f64| json!({"lat": lat, "lon": lon, "radius": r}); + assert!(in_circle(&at(Some(notre_dame)), "inside", c(eiffel.0, eiffel.1, 5000.0))); + assert!(!in_circle(&at(Some(notre_dame)), "inside", c(eiffel.0, eiffel.1, 3000.0))); + assert!(in_circle(&at(Some(notre_dame)), "outside", c(eiffel.0, eiffel.1, 3000.0))); + // the centre itself, and a radius of exactly the distance (edge included) + assert!(in_circle(&at(Some(eiffel)), "inside", c(eiffel.0, eiffel.1, 1.0))); + assert!(in_circle(&at(Some(notre_dame)), "inside", c(eiffel.0, eiffel.1, d))); + // across the antimeridian: Fiji's 179.9° E and 179.9° W are 22 km apart, not 40 000 + let east = at(Some((-17.0, 179.9))); + let west = at(Some((-17.0, -179.9))); + assert!(in_circle(&west, "inside", c(-17.0, 179.9, 25_000.0))); + assert!(in_circle(&east, "inside", c(-17.0, -179.9, 25_000.0))); + assert!(in_circle(&at(Some((-17.0, 180.0))), "inside", c(-17.0, -180.0, 1.0))); + // around a pole: a 500 km circle at 87° N holds the pole and the far side of it + let polar = c(87.0, 0.0, 500_000.0); + assert!(in_circle(&at(Some((90.0, 0.0))), "inside", polar.clone())); + // over the pole: 3° + 1° ≈ 445 km away; 3° + 2° ≈ 556 km is outside + assert!(in_circle(&at(Some((89.0, 180.0))), "inside", polar.clone())); + assert!(in_circle(&at(Some((88.0, 180.0))), "outside", polar.clone())); + assert_eq!(GpsCircle::parse(&polar).unwrap().pole(), Some(true)); + assert_eq!(GpsCircle::parse(&c(-89.0, 10.0, 200_000.0)).unwrap().pole(), Some(false)); + assert_eq!(GpsCircle::parse(&c(48.0, 2.0, 1_000_000.0)).unwrap().pole(), None); + // no position, or not one: neither inside nor outside + for gps in [None, Some((f64::NAN, 2.0)), Some((91.0, 2.0)), Some((48.0, -181.0))] { + assert!(!in_circle(&at(gps), "inside", c(0.0, 0.0, MAX_RADIUS_M)), "{gps:?}"); + assert!(!in_circle(&at(gps), "outside", c(0.0, 0.0, 1.0)), "{gps:?}"); + } + // hostile values match nothing and are reported + let check = |v: serde_json::Value| { + rs(json!({"rules": [{"field": "gpsRadius", "op": "inside", "value": v}]})) + .check(&Catalog::new()) + .into_iter() + .map(|p| p.issue) + .collect::>() + }; + assert!(check(c(48.0, 2.0, 500.0)).is_empty()); + for bad in [ + c(91.0, 0.0, 500.0), + c(0.0, 181.0, 500.0), + c(0.0, 0.0, 0.5), + c(0.0, 0.0, 1_000_001.0), + c(0.0, 0.0, -5.0), + json!({"lat": 0.0, "lon": 0.0}), + json!({"lat": "0", "lon": 0.0, "radius": 10.0}), + json!(null), + json!([1, 2, 3]), + ] { + assert_eq!(check(bad.clone()), vec![Issue::NeedsCircle], "{bad}"); + assert!(!in_circle(&at(Some(eiffel)), "inside", bad.clone()) && !in_circle(&at(Some(eiffel)), "outside", bad), "matches nothing"); + } + assert_eq!(GpsCircle::new(f64::NAN, 0.0, 10.0), Err(Issue::NeedsCircle)); + assert_eq!(GpsCircle::new(0.0, 0.0, f64::INFINITY), Err(Issue::NeedsCircle)); + // the latitude band holds every position inside, clamped at the poles + let (s, n) = GpsCircle::parse(&polar).unwrap().lat_range(); + assert!(n == 90.0 && (82.0..83.0).contains(&s), "{s} {n}"); + // a summary people can read + assert_eq!(GpsCircle::new(48.5, 2.25, 1500.0).unwrap().describe(), "within 1.5 km of 48.5, 2.25"); + assert_eq!(format_distance(850.0), "850 m"); + assert_eq!(format_distance(120_400.0), "120 km"); +} + +/// The point `destination` gives is at the distance asked, and its longitude stays continuous +/// (unwrapped) past ±180. +#[test] +fn destination_is_at_the_distance_and_unwrapped() { + for (lat, lon, b, d) in [(48.0, 2.0, 0.0, 1000.0), (0.0, 179.9, 90.0, 50_000.0), (-60.0, -10.0, 225.0, 900_000.0), (89.0, 0.0, 180.0, 10.0)] { + let (la, lo) = destination(lat, lon, b, d); + assert!((distance_m(lat, lon, la, lo) - d).abs() < 0.01 * d.max(1.0), "{lat} {lon} {b} {d} → {la} {lo}"); + } + let (_, lo) = destination(0.0, 179.9, 90.0, 50_000.0); + assert!(lo > 180.0, "unwrapped: {lo}"); +} diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index 2ed0acb5e1..1ab0ab5c86 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -108,8 +108,9 @@ pub fn sync_dir(dir: &Path) { } } -/// A new, empty temp file next to `path` (hidden, unique in this process and folder). -fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> { +/// A new, empty temp file next to `path` (hidden, unique in this process and folder). When +/// `private`, it is created readable by its owner only (`0600` on Unix) before any byte is written. +fn create_temp(path: &Path, private: bool) -> io::Result<(PathBuf, File)> { static N: AtomicU64 = AtomicU64::new(0); if path.file_name().is_none() { return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} is not a file path", path.display()))); @@ -117,7 +118,16 @@ fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> { let dir = parent_of(path); for _ in 0..1000 { let tmp = dir.join(format!(".lightcraft-{}-{}.tmp", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - match OpenOptions::new().write(true).create_new(true).open(&tmp) { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if private { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(not(unix))] + let _ = private; + match options.open(&tmp) { Ok(f) => return Ok((tmp, f)), Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e), @@ -128,8 +138,8 @@ fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> { /// Write a temp file next to `path` with what `fill` writes, synced to disk when `sync`. On /// failure the temp file is removed. Returns its path and length. -fn write_temp(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<(PathBuf, u64)> { - let (tmp, file) = create_temp(path)?; +fn write_temp(path: &Path, sync: bool, private: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<(PathBuf, u64)> { + let (tmp, file) = create_temp(path, private)?; let r = (|| { let limit = FAIL_AFTER.with(Cell::get); let mut w = Limited { inner: io::BufWriter::with_capacity(1 << 20, file), n: 0, limit }; @@ -160,19 +170,26 @@ pub fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> { /// [`write_atomic`] with streamed content: `fill` writes it (an error aborts and leaves the old /// file). Returns the length written. pub fn write_atomic_with(path: &Path, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result { - replace_with(path, true, fill) + replace_with(path, true, false, fill) +} + +/// [`write_atomic`] for a secret (an API key): the temp file is created readable by its owner only +/// (`0600` on Unix) before any byte is written, so the content is never readable by other users, +/// not even while it is written. Elsewhere the folder's permissions apply. +pub fn write_atomic_private(path: &Path, data: &[u8]) -> io::Result<()> { + replace_with(path, true, true, &mut |w| w.write_all(data)).map(|_| ()) } /// Replace (or create) `path` with `data` atomically but **without syncing** it to disk — only for /// outputs that can always be recreated (exports, renders, screenshots); see the module docs. /// Anything that can't be made again goes through [`write_atomic`]. pub fn write_atomic_nosync(path: &Path, data: &[u8]) -> io::Result<()> { - replace_with(path, false, &mut |w| w.write_all(data)).map(|_| ()) + replace_with(path, false, false, &mut |w| w.write_all(data)).map(|_| ()) } /// Temp file (synced when `sync`) renamed over `path`, then the folder synced when `sync`. -fn replace_with(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result { - let (tmp, n) = write_temp(path, sync, fill)?; +fn replace_with(path: &Path, sync: bool, private: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result { + let (tmp, n) = write_temp(path, sync, private, fill)?; if let Err(e) = fs::rename(&tmp, path) { let _ = fs::remove_file(&tmp); return Err(e); @@ -197,7 +214,7 @@ pub fn write_new_unique(candidates: &mut dyn Iterator, data: &[u let Some(first) = candidates.peek().cloned() else { return Err(io::Error::new(io::ErrorKind::InvalidInput, "no file name to write")); }; - let (tmp, _) = write_temp(&first, true, &mut |w| w.write_all(data))?; + let (tmp, _) = write_temp(&first, true, false, &mut |w| w.write_all(data))?; let r = (|| { // Kept (issue #134 point 4): these files replace raws (Convert / Copy as DNG) or become // library photos (merges). On a local disk the read usually comes from the cache, but on a @@ -354,6 +371,27 @@ mod tests { v } + #[test] + fn a_private_file_is_owner_only_from_its_creation() { + let d = temp("private"); + let p = d.join("keys.json"); + fs::write(&p, b"old").unwrap(); + write_atomic_private(&p, b"secret").unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"secret"); + assert_eq!(names(&d), vec!["keys.json".to_string()], "no temp file left"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + // the temp file was created 0600 and renamed: the mode is the one it was created with + assert_eq!(fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600); + let (tmp, f) = create_temp(&p, true).unwrap(); + assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600, "owner-only before a byte is written"); + drop(f); + fs::remove_file(tmp).unwrap(); + } + let _ = fs::remove_dir_all(&d); + } + #[test] fn fallback_publish_never_replaces_a_file_that_appears_at_the_same_time() { let d = temp("nolink-race"); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d9da971191..7424b6f950 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -48,6 +48,7 @@ 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) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a627e9dcd3..9fb367e186 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -29,6 +29,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; @@ -176,6 +177,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/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index b366069fe2..6db4fd0fcb 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -404,11 +404,8 @@ pub fn specs() -> Vec { if on != s.hold_view { let was = s.hold_view; s.hold_view = on; - if let Err(e) = s.save_prefs() { - // not kept: not changed either, so asking again does what was asked - s.hold_view = was; - return Err(e); - } + // not kept: not changed either, so asking again does what was asked + s.save_prefs_or_undo(|s| s.hold_view = was)?; s.refresh_view(); } Ok(json!({"hold": s.hold_view})) @@ -859,11 +856,14 @@ pub fn specs() -> Vec { .filter_map(|k| s.catalog.check_keyword_name(&k).err().map(|e| (k, e.to_string()))) .collect(); let mut ops = Vec::new(); + let mut owned = Vec::new(); for id in targets { let Some(ph) = s.catalog.photo(id) else { continue }; let mut m = ph.meta.clone(); if let Some(g) = gps { m.gps = g; + // the position typed in is LightCraft's: its sidecar follows it, cleared too + owned.push(id); } if let Some(st) = status { m.copyright_status = st; @@ -919,6 +919,8 @@ pub fn specs() -> Vec { } let n = ops.len(); s.commit("Edit Info", Op::Batch { ops })?; + // marked once the commit landed (a refused one marks nothing) + s.own_gps(owned); // keywords just added become the Recent Keywords set let added: Vec = strs("addKeywords").unwrap_or_default().into_iter().chain(strs("keywords").unwrap_or_default()).collect(); if n > 0 && !added.is_empty() { @@ -975,7 +977,7 @@ pub fn specs() -> Vec { Ok(json!({"id": id.0, "count": s.catalog.album_count(id)})) } ), - cmd!(query "album.ruleFields", "Smart Album Rule Fields", [], None, "{} → [{field, label, kind (text|keywords|number|date|choice|bool|album: an album id), group (field-menu submenu, null at the top level), ops: [{op, label}], choices? (ids), choiceLabels? ({id: label})}] for ruleSet rules, in menu order", always, |_, _| { + cmd!(query "album.ruleFields", "Smart Album Rule Fields", [], None, "{} → [{field, label, kind (text|keywords|number|date|choice|bool|album: an album id|area: {south, west, north, east} in degrees, east < west wraps across ±180°|circle: {lat, lon, radius} in degrees and metres, 1 m–1000 km), group (field-menu submenu, null at the top level), ops: [{op, label}], choices? (ids), choiceLabels? ({id: label})}] for ruleSet rules, in menu order", always, |_, _| { use lightcraft_catalog::rules::{FIELDS, Kind, field_group, ops_for}; Ok(json!(FIELDS .iter() @@ -988,6 +990,8 @@ pub fn specs() -> Vec { Kind::Date => "date", Kind::Choice(_) => "choice", Kind::Bool => "bool", + Kind::Area => "area", + Kind::Circle => "circle", }; let mut v = json!({"field": id, "label": label, "kind": k, "group": field_group(id), "ops": ops_for(*kind).iter().map(|(o, l)| json!({"op": o, "label": l})).collect::>()}); if let Kind::Choice(c) = kind { diff --git a/crates/engine/src/cmd/manage.rs b/crates/engine/src/cmd/manage.rs index 6e4cdfb105..90c012cb58 100644 --- a/crates/engine/src/cmd/manage.rs +++ b/crates/engine/src/cmd/manage.rs @@ -64,41 +64,30 @@ fn set_names_ops(s: &crate::Session, names: &[String; 5]) -> Vec { .collect() } -/// Most bytes of a track log file. -const MAX_GPX_BYTES: u64 = 256 << 20; - /// Geotag photos from a GPX track log by capture time (Lightroom Classic's Map ▸ Tracklog ▸ /// Auto-Tag Photos). GPX times are UTC; capture times are the camera's local clock, so a photo's /// recorded zone (Exif `OffsetTimeOriginal`) or the `offset` parameter converts them. fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result { use lightcraft_meta::{DateTime, Match, parse_gpx}; const C: &str = "photo.autoTagTracklog"; - let text = match (str_param(p, "gpx"), str_param(p, "path")) { - (Some(t), _) => t.to_string(), - (None, Some(path)) => crate::read_file::read_regular(path, MAX_GPX_BYTES) - .map(|b| String::from_utf8_lossy(&b).into_owned()) - .map_err(|e| bad(C, format!("can't read {path}: {e}")))?, - (None, None) => return Err(bad(C, "missing `path` (a .gpx file) or `gpx` (its text)")), + // the bound this command always had; the Map view's track log (which keeps the parsed file) has less + const MAX_GPX_BYTES: u64 = 256 << 20; + let from_map = bool_or(p, "loaded", false); + // the Map view's track log (its active track and offset), or a file / text given here + let (log, map_offset) = if from_map { + let t = s.map.track.as_ref().ok_or_else(|| bad(C, "no track log is loaded in the Map view (map.trackLog {path})"))?; + (t.active_log.clone(), t.offset_minutes) + } else { + let (text, _) = crate::tracklog::read_gpx(C, p, MAX_GPX_BYTES)?.ok_or_else(|| bad(C, "missing `path` (a .gpx file) or `gpx` (its text)"))?; + (std::sync::Arc::new(parse_gpx(&text).map_err(|e| bad(C, e.to_string()))?), None) }; - let log = parse_gpx(&text).map_err(|e| bad(C, e.to_string()))?; let (start, end) = log.span().ok_or_else(|| bad(C, "the track log has no timed track points"))?; // minutes east of UTC; `None` = not given (zone-less capture times are then read as UTC) let offset: Option = match p.get("offset") { - None | Some(Value::Null) => None, - Some(Value::String(o)) if o.trim().is_empty() => None, - Some(Value::Number(h)) => { - let h = h.as_f64().unwrap_or(0.0); - if h.abs() > 18.0 { - return Err(bad(C, "offset is at most ±18 hours")); - } - Some((h * 60.0).round() as i64) - } - Some(Value::String(o)) => { - Some(DateTime::parse_offset(o).ok_or_else(|| bad(C, format!("can't read offset `{o}` (e.g. +02:00 or -5)")))? as i64) - } - Some(_) => return Err(bad(C, "offset is `+HH:MM` or a number of hours")), + None => map_offset, + Some(v) => crate::tracklog::parse_offset(C, v)?, }; - let max_gap = f64_or(p, "maxGap", 600.0); + let max_gap = f64_or(p, "maxGap", crate::tracklog::DEFAULT_MAX_GAP); if max_gap.is_nan() || max_gap < 0.0 { return Err(bad(C, "maxGap must be ≥ 0 seconds")); } @@ -116,25 +105,17 @@ fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result { no_time += 1; continue; }; - // UTC seconds: the recorded zone wins, else the caller's offset - let utc = match dt.offset_minutes { - Some(_) => dt.unix_seconds(), - None => { - if offset.is_none() { - assumed_utc += 1; - } - dt.unix_seconds() - offset.unwrap_or(0) * 60 - } - } as f64 - + dt.millis as f64 / 1000.0; - let Some((g, m)) = log.locate(utc, max_gap) else { + if dt.offset_minutes.is_none() && offset.is_none() { + assumed_utc += 1; + } + let Some((g, m)) = log.locate(crate::tracklog::capture_utc(&dt, offset), max_gap) else { outside += 1; continue; }; if m == Match::Interpolated { interpolated += 1; } - let pos = ((g.latitude * 1e7).round() / 1e7, (g.longitude * 1e7).round() / 1e7); + let pos = crate::tracklog::rounded(&g); photos.push(json!({"id": id.0, "gps": [pos.0, pos.1], "match": if m == Match::Interpolated { "interpolated" } else { "nearest" }})); if ph.meta.gps != Some(pos) { let mut meta = ph.meta.clone(); @@ -144,7 +125,18 @@ fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result { } let tagged = photos.len(); if !bool_or(p, "dryRun", false) && !ops.is_empty() { + // the positions are LightCraft's (as photo.setGps's): marked once the commit landed (a + // refused one marks nothing), before the sidecars are written after the command, so they + // and an undo follow them + let ids: Vec<_> = ops + .iter() + .filter_map(|op| match op { + Op::SetMeta { id, .. } => Some(*id), + _ => None, + }) + .collect(); s.commit("Auto-Tag from Tracklog", Op::Batch { ops })?; + s.own_gps(ids); } let iso = |t: f64| format!("{}Z", lightcraft_catalog::dates::civil(t.floor() as i64)); Ok(json!({ @@ -272,7 +264,7 @@ pub fn specs() -> Vec { "Auto-Tag Photos from Tracklog", [], None, - "{path?: GPX file | gpx?: GPX text, ids?, offset?: camera clock's UTC offset for photos whose capture time has no zone (`+02:00`, or hours; default UTC), maxGap?: seconds (600), replace?: bool (also photos that already have GPS), dryRun?: bool} → {tagged, interpolated, nearest, skipped: {noTime, outside, hasGps}, assumedUtc, points, start, end, photos: [{id, gps, match}]} — positions from the track log by capture time; one undo step", + "{path?: GPX file (at most 50 MB) | gpx?: GPX text | loaded?: true (the Map view's track log: its active track, and its offset unless `offset` is given; map.trackLog), ids?, offset?: camera clock's UTC offset for photos whose capture time has no zone (`+02:00`, or hours; default UTC), maxGap?: seconds (600), replace?: bool (also photos that already have GPS), dryRun?: bool} → {tagged, interpolated, nearest, skipped: {noTime, outside, hasGps}, assumedUtc, points, start, end, photos: [{id, gps, match}]} — positions from the track log by capture time; one undo step", has_selection, auto_tag_tracklog ), diff --git a/crates/engine/src/cmd/map.rs b/crates/engine/src/cmd/map.rs new file mode 100644 index 0000000000..e1ac1a0e2e --- /dev/null +++ b/crates/engine/src/cmd/map.rs @@ -0,0 +1,585 @@ +//! Map module commands: tile sources and the tile cache, saved locations, location filtering, and +//! GPS tagging (`photo.setGps`, `photo.removeGps`: what dropping photos on the Map view, moving a +//! pin and Photo ▸ Remove GPS Coordinates run). The tile-source commands are ported from PR #797, +//! the geotag commands from PR #810 (Jason Baldwin). + +use lightcraft_catalog::Op; +use lightcraft_catalog::rules::GpsArea; +use lightcraft_geom::LatLon; +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd, f64_req, has_selection}; +use crate::locations::{LocationChange, PositionIndex, SavedLocation}; +use crate::map::{LocationFilter, TileSource, cache}; +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 targets = gps_targets(s, p, C)?; + let count = commit_gps(s, &targets, Some(pos), "Set GPS Coordinates")?; + Ok(json!({ "updated": count, "lat": pos.0, "lon": pos.1 })) +} + +/// The photos a geotag command acts on: those named (`ids` / `id`), else the selection, each once. +/// A named photo the library doesn't have is an error and nothing changes (a drag of photos deleted +/// meanwhile, an agent): the caller learns of it instead of a silent no-op. +fn gps_targets(s: &mut Session, p: &Value, c: &str) -> Result> { + 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")); + } + Ok(targets) +} + +/// Set (`Some`) or clear (`None`) the GPS position of `targets` as one undo step `label`; photos +/// already so are left alone (no empty undo step). The photos become LightCraft's for their +/// sidecar GPS ([`Session::gps_edited`]), so clearing (or undoing) removes it from the sidecar. +fn commit_gps(s: &mut Session, targets: &[lightcraft_catalog::PhotoId], gps: Option<(f64, f64)>, label: &str) -> Result { + let ops: Vec = targets + .iter() + .filter_map(|id| s.catalog.photo(*id)) + .filter(|ph| ph.meta.gps != gps) + .map(|ph| { + let mut meta = ph.meta.clone(); + meta.gps = gps; + Op::SetMeta { id: ph.id, meta: Box::new(meta) } + }) + .collect(); + let count = ops.len(); + // only the photos the batch changes become LightCraft's (a clear that skips a photo with no + // catalog position must not later strip its sidecar's GPS) + let changed: Vec<_> = ops.iter().filter_map(|op| if let Op::SetMeta { id, .. } = op { Some(*id) } else { None }).collect(); + if count > 0 { + s.commit(label, Op::Batch { ops })?; + // once it landed (a refused commit marks nothing): the sidecars, written after the + // command, follow LightCraft's position + s.own_gps(changed); + } + Ok(count) +} + +/// `photo.removeGps` (and its older name `photo.clearGps`): clear the photos' position, one undo +/// step "Remove GPS Coordinates". +fn remove_gps(s: &mut Session, p: &Value) -> Result { + let targets = gps_targets(s, p, "photo.removeGps")?; + let count = commit_gps(s, &targets, None, "Remove GPS Coordinates")?; + Ok(json!({ "changed": count, "cleared": count })) +} + +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": 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 without a key) + "saved": (*chosen != used).then(|| chosen.id().to_string()), + "notice": s.map.fallback_notice(), + // 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), + 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 + s.save_prefs_or_undo(|s| s.map.restore(old))?; + } + 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(), + "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()})) +} + +// ---------------------------------------------------------------- saved locations +// (ported from PR #906, Jason Baldwin) + +/// An optional number parameter (finite), `None` when absent or null. +fn opt_num(id: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_f64().filter(|v| v.is_finite()).map(Some).ok_or_else(|| bad(id, format!("`{key}` must be a number"))), + } +} + +fn opt_bool(id: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(id, format!("`{key}` is true or false"))), + } +} + +/// The saved location named by `id`. +fn location_id(cmd: &str, s: &Session, p: &Value) -> Result { + let id = p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`id` is a saved location's id (map.locations)"))?; + if s.map.locations.get(id).is_none() { + return Err(bad(cmd, format!("no saved location {id}"))); + } + Ok(id) +} + +/// Every library photo's position (not the deleted ones), for counting. +fn library_index(s: &Session) -> PositionIndex { + PositionIndex::new(s.catalog.photos().filter(|p| !p.deleted).map(|p| (p.id.0, p.meta.gps))) +} + +/// The positions of the photos in view (source, filter and sort: the grid's; before the Map +/// view's location filter). +fn view_index(s: &mut Session) -> PositionIndex { + let (_, ids) = s.visible_base_shared(); + PositionIndex::new(ids.iter().map(|id| (id.0, s.catalog.photo(*id).and_then(|p| p.meta.gps)))) +} + +fn with_counts(l: &SavedLocation, library: &PositionIndex, view: &PositionIndex) -> Value { + let mut v = l.to_json(); + v["photos"] = json!(library.count(&l.circle())); + v["inView"] = json!(view.count(&l.circle())); + v +} + +fn locations(s: &mut Session, _: &Value) -> Result { + let t0 = web_time::Instant::now(); + let (library, view) = (library_index(s), view_index(s)); + let list: Vec = s.map.locations.list().iter().map(|l| with_counts(l, &library, &view)).collect(); + Ok(json!({"locations": list, "count": list.len(), "countMs": t0.elapsed().as_secs_f64() * 1000.0})) +} + +/// Where a new location goes when made from photos: the middle of their positions, and a radius +/// that holds them all (10 % to spare, at least 100 m, at most 1000 km). Photos too far apart for +/// the largest radius are refused rather than left outside it. +fn around_photos(c: &str, s: &Session, ids: &[lightcraft_catalog::PhotoId]) -> Result<(f64, f64, f64)> { + use lightcraft_catalog::rules::MAX_RADIUS_M; + let pos: Vec<(f64, f64)> = + ids.iter().filter_map(|id| s.catalog.photo(*id)).filter_map(|p| lightcraft_catalog::rules::valid_gps(p.meta.gps)).collect(); + let b = crate::map::Bounds::of(pos.iter().copied()).ok_or_else(|| bad(c, "none of the selected photos has a GPS position"))?; + let mid = b.center(); + let lon = crate::map::mercator::wrap_lon(mid.lon); + let far = pos.iter().map(|(la, lo)| lightcraft_catalog::rules::distance_m(mid.lat, lon, *la, *lo)).filter(|d| d.is_finite()).fold(0.0, f64::max); + if far > MAX_RADIUS_M { + return Err(bad( + c, + format!( + "the selected photos are up to {:.0} km from their middle, more than a saved location's largest radius ({:.0} km); select photos closer together", + far / 1000.0, + MAX_RADIUS_M / 1000.0 + ), + )); + } + Ok((mid.lat, lon, (far * 1.1).clamp(100.0, MAX_RADIUS_M))) +} + +fn location_add(s: &mut Session, p: &Value) -> Result { + const C: &str = "map.location.add"; + // (a locations.json unreadable at open is never written: refused before anything changes) + s.locations_writable().map_err(|e| bad(C, e.to_string()))?; + let name = match p.get("name") { + Some(Value::String(n)) => n.clone(), + _ => return Err(bad(C, "`name` is the location's name (text)")), + }; + let private = opt_bool(C, p, "private")?.or(opt_bool(C, p, "isPrivate")?).unwrap_or(false); + let (lat, lon, radius) = (opt_num(C, p, "lat")?, opt_num(C, p, "lon")?, opt_num(C, p, "radius")?); + let from = opt_bool(C, p, "fromSelection")?.unwrap_or(false); + let (lat, lon, radius) = match (lat, lon) { + (Some(lat), Some(lon)) => (lat, lon, radius.unwrap_or(1000.0)), + (None, None) if from => { + let ids = s.targets(p).map_err(|e| match e { + EngineError::BadParams { msg, .. } => bad(C, msg), + other => other, + })?; + let (la, lo, r) = around_photos(C, s, &ids)?; + (la, lo, radius.unwrap_or(r)) + } + _ => return Err(bad(C, "give `lat` and `lon` (degrees), or `fromSelection: true`")), + }; + let l = s.map.locations.add(&name, lat, lon, radius, private).map_err(|e| bad(C, e))?; + if let Err(e) = s.save_locations() { + // it stays for this session; say why it wasn't saved + log::error!("{C}: {e}"); + let mut v = l.to_json(); + v["notSaved"] = json!(e.to_string()); + return Ok(v); + } + let (library, view) = (library_index(s), view_index(s)); + Ok(with_counts(&l, &library, &view)) +} + +fn location_update(s: &mut Session, p: &Value) -> Result { + const C: &str = "map.location.update"; + // (a locations.json unreadable at open is never written: refused before anything changes) + s.locations_writable().map_err(|e| bad(C, e.to_string()))?; + let id = location_id(C, s, p)?; + let name = match p.get("name") { + None | Some(Value::Null) => None, + Some(Value::String(n)) => Some(n.clone()), + Some(_) => return Err(bad(C, "`name` is text")), + }; + let change = LocationChange { + name, + lat: opt_num(C, p, "lat")?, + lon: opt_num(C, p, "lon")?, + radius: opt_num(C, p, "radius")?, + private: opt_bool(C, p, "private")?, + }; + let l = s.map.locations.update(id, &change).map_err(|e| bad(C, e))?; + let saved = s.save_locations(); + let (library, view) = (library_index(s), view_index(s)); + let mut v = with_counts(&l, &library, &view); + if let Err(e) = saved { + v["notSaved"] = json!(e.to_string()); + } + Ok(v) +} + +fn location_remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "map.location.remove"; + // (a locations.json unreadable at open is never written: refused before anything changes) + s.locations_writable().map_err(|e| bad(C, e.to_string()))?; + let id = location_id(C, s, p)?; + let gone = s.map.locations.remove(id).ok_or_else(|| bad(C, format!("no saved location {id}")))?; + let mut v = json!({"removed": gone.id, "name": gone.name, "deleted": true}); + if let Err(e) = s.save_locations() { + v["notSaved"] = json!(e.to_string()); + } + Ok(v) +} + +fn location_photos(s: &mut Session, p: &Value) -> Result { + const C: &str = "map.location.photos"; + let id = location_id(C, s, p)?; + let in_view = opt_bool(C, p, "inView")?.unwrap_or(false); + let circle = s.map.locations.get(id).map(SavedLocation::circle).ok_or_else(|| bad(C, format!("no saved location {id}")))?; + let ids: Vec = if in_view { + // in the order of the view + let (_, view) = s.visible_base_shared(); + view.iter() + .filter(|i| { + s.catalog.photo(**i).is_some_and(|ph| lightcraft_catalog::rules::valid_gps(ph.meta.gps).is_some_and(|(a, b)| circle.contains(a, b))) + }) + .map(|i| i.0) + .collect() + } else { + let mut v = library_index(s).inside(&circle); + v.sort_unstable(); + v + }; + Ok(json!({"id": id, "ids": ids, "count": ids.len()})) +} + +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 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\" | \"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", + "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!( + "map.trackLog", + "Map Tracklog", + [], + None, + "{path?: GPX file (at most 50 MB, 2 million timed points) | gpx?: GPX text, active?: track index | \"all\", offset?: camera clock's UTC offset (`+02:00`, hours, or null / \"\" for UTC), clear?: true (alone)} — the track log shown on the Map view (session only, never saved): load it (a bad file changes nothing), pick the track tagging uses, set the time zone offset, or clear it; {} reports → {loaded, path, name, points, untimed, tracks: [{index, name, points, segments, start, end, duration}], active (null: all), activePoints, start, end, duration (UTC, of the active track), offset, startLocal, endLocal (camera time), loadMs, generation}. photo.autoTagTracklog {loaded: true} tags from it", + always, + crate::tracklog::track_log + ), + cmd!(query "map.locations", "Saved Locations", [], None, "{} → the library's saved locations: {locations: [{id, name, lat, lon, radius (metres), private, photos (in the library inside it), inView (of the photos in view)}], count, countMs}", always, locations), + cmd!(query "map.savedLocations.list", "List Saved Locations", [], None, "{} → the older name of map.locations (same answer)", always, locations), + cmd!( + "map.location.add", + "New Saved Location", + [], + None, + "{name, lat, lon, radius?: metres 1–1000000 (default 1000), private?: bool} or {name, fromSelection: true, ids?, radius?, private?} (centred on the selected (or named) photos' positions, a radius that holds them) — save a location (saved at once in locations.json; not an undo step) → the location with its counts", + always, + location_add + ), + cmd!( + "map.savedLocations.create", + "Create Saved Location", + [], + None, + "the older name of map.location.add (same parameters; isPrivate is taken for private)", + always, + location_add + ), + cmd!( + "map.location.update", + "Edit Saved Location", + [], + None, + "{id, name?, lat?, lon?, radius?, private?} — change a saved location (checked as a whole: nothing changes when any part is refused; not an undo step) → the location with its counts", + always, + location_update + ), + cmd!( + "map.location.remove", + "Delete Saved Location", + [], + None, + "{id} — delete a saved location (not an undo step; the photos keep their positions) → {removed, name, deleted}", + always, + location_remove + ), + cmd!("map.savedLocations.delete", "Remove Saved Location", [], None, "{id} — the older name of map.location.remove", always, location_remove), + cmd!(query "map.location.photos", "Photos in Saved Location", [], None, "{id, inView?: bool} → {id, ids, count}: the library's photos inside the location (inView: only the photos in view, in their order)", always, location_photos), + 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; `bounds` is the area of mode \"visible\" (the other modes don't use it); minLon greater than maxLon is an area across the 180° meridian, as the Map view's Visible On Map filter reads it; a position out of range counts as untagged", always, |s, p| { + const C: &str = "map.filterPhotos"; + let mode = match p.get("mode") { + None | Some(Value::Null) => LocationFilter::None, + Some(m) => m.as_str().and_then(LocationFilter::parse).ok_or_else(|| bad(C, format!("`mode` is \"visible\", \"tagged\", \"untagged\" or \"none\", not {m}")))?, + }; + // the Map view's own area type, so this matches its Visible On Map filter (a view across 180° included) + let bounds = match p.get("bounds") { + None | Some(Value::Null) => None, + Some(b) => { + let edge = |k: &str| b.get(k).cloned().unwrap_or(Value::Null); + let area = json!({"south": edge("minLat"), "west": edge("minLon"), "north": edge("maxLat"), "east": edge("maxLon")}); + Some(GpsArea::parse(&area).map_err(|_| { + bad(C, format!("`bounds` needs minLat ≤ maxLat (−90…90) and minLon, maxLon (−180…180) in degrees, not {b}")) + })?) + } + }; + + 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); + + // a position that isn't one (latitude 95, say) is untagged, as the Map view and Has GPS read it + match (mode, lightcraft_catalog::rules::valid_gps(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 bounds.contains(lat, lon) { + 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 })) + }), + 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 + ) + }, + CommandSpec { + explicit_targets: true, + ..cmd!( + "photo.removeGps", + "Remove GPS Coordinates", + ["Photo"], + None, + "{ids?: [PhotoId]} → {changed, cleared} — clears the GPS position of the photos (default: the selection), one undo step \"Remove GPS Coordinates\"; Photo ▸ Remove GPS Coordinates and a map pin's right-click menu. Unknown ids are refused. Positions LightCraft set or cleared are removed from the photos' XMP sidecars too", + has_selection, + remove_gps + ) + }, + CommandSpec { + explicit_targets: true, + ..cmd!( + "photo.clearGps", + "Clear Photo GPS Coordinates", + [], + None, + "{ids?: [PhotoId]} → {changed, cleared} — the older name of photo.removeGps (same command)", + has_selection, + remove_gps + ) + }, + ] +} diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index a382cb774a..9bbf21b0c0 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -330,11 +330,7 @@ fn before(s: &Session) -> Before { /// Save the preferences after a change to the templates or folders; if that fails, both go back /// to `before`, so the list matches what is saved and a retry does the same thing. fn save_templates(s: &mut Session, before: Before) -> Result<()> { - if let Err(e) = s.save_prefs() { - (s.print_templates, s.print_template_folders) = before; - return Err(e); - } - Ok(()) + s.save_prefs_or_undo(|s| (s.print_templates, s.print_template_folders) = before) } fn template_save(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index c5ed4c6ad4..e966bf9622 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). @@ -118,6 +118,41 @@ fn fully_qualified(platform: Platform, dir: &OsStr) -> bool { } } +/// 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 { @@ -224,6 +259,17 @@ impl Session { self } + /// Fetch map tiles from the network and cache them in the shared default folder + /// ([`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 + } + /// 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()); @@ -288,6 +334,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/export/prepare.rs b/crates/engine/src/export/prepare.rs index e2bfa6c79c..811fbbc8d2 100644 --- a/crates/engine/src/export/prepare.rs +++ b/crates/engine/src/export/prepare.rs @@ -131,6 +131,15 @@ fn prepare_guarded( } else { o }; + // a photo inside a private saved location is exported without its location, as if "Remove + // location info" were on for it (LRC-MAP-LOCATIONS, from PR #906) + let private_opts; + let o = if !o.remove_location && session.map.locations.private_at(p.meta.gps).is_some() { + private_opts = ExportOptions { remove_location: true, ..o.clone() }; + &private_opts + } else { + o + }; let (full_px, long) = ((p.width as usize).saturating_mul(p.height as usize), p.width.max(p.height) as usize); let (work, weight) = if o.format.is_rendered() { let (w, h) = output_size(p, o); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 04be5d669a..760a6cd27d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -57,7 +57,9 @@ pub mod lightroom_catalog; pub mod lightroom_folder; pub mod lightroom_job; mod lightroom_sqlite; +pub mod locations; pub mod logging; +pub mod map; pub mod media; pub mod memory; pub mod merge; @@ -89,6 +91,7 @@ pub mod smart; pub mod sync; mod sync_same; pub mod text; +pub mod tracklog; mod view; pub mod walk; @@ -290,6 +293,15 @@ pub struct Session { /// Identifies the current `visible` list: a new value (unique in the process) every time it /// is recomputed, so frontends can key their per-view caches on it instead of hashing the ids. visible_gen: u64, + /// A view's own narrowing over the library's filter (the Map view's location filter: Tagged, + /// Untagged, Visible on Map): [`Session::visible`] keeps only the photos these rules match. + /// It is not part of `filter` (never saved, not shown as filter chips, not in smart albums made + /// from the view); the view that sets it clears it when it is left. Ported from PR #819. + pub narrow: Option, + /// The narrowed list, its generation, and what it was narrowed from (base generation, rules). + narrowed: Arc<[PhotoId]>, + narrowed_gen: u64, + narrow_key: Option<(u64, String)>, /// Photos in the current source with no filter on (cached like `visible`). total: Option<((u64, String), usize, Option)>, pub undo: Vec, @@ -385,6 +397,16 @@ pub struct Session { pub print: print::template::PrintSettings, /// Saved print templates (`print.template.*`), persisted in prefs.json. pub print_templates: Vec, + /// Saved locations read from an older `prefs.json` (`savedLocations`) and not yet confirmed + /// in `locations.json`: written back to `prefs.json` until they are, never dropped before + /// (see [`crate::locations`]). + pub(crate) legacy_locations: Vec, + /// [`Session::legacy_locations`] were taken into the active list, so writing `locations.json` + /// confirms them. `false` when `locations.json` was damaged: the list written then doesn't hold + /// them, and they stay in `prefs.json`. + pub(crate) legacy_in_locations: bool, + /// The map's tile source (persisted in prefs.json), tile cache folder and tile service. + pub map: map::MapState, /// The Template Browser's folders besides [`print::template::DEFAULT_FOLDER`], sorted by name /// (`print.template.folder.*`), persisted in prefs.json. pub print_template_folders: Vec, @@ -410,6 +432,16 @@ pub struct Session { pub lut_profiles: Vec, /// The target album B adds to (`None` = the Quick Collection). pub target_album: Option, + /// Photos whose GPS position was set or cleared by a command in this session (map drops, pins + /// moved, Remove GPS Coordinates, the Info panel's GPS field): their sidecars take LightCraft's + /// position as it is ([`sidecar::GPS_OWNED`]), so a cleared one (or an undone geotag) is removed + /// from the sidecar too. Other photos' sidecar GPS is never removed (LightCraft doesn't read GPS + /// from sidecars). Kept with the library's preferences (`prefs.json` `gpsOwned`), so it + /// survives a reopen; another library brings its own (photo ids are per library). + pub gps_edited: std::collections::HashSet, + /// Of [`Session::gps_edited`], the photos whose GPS change isn't on disk yet: left out of + /// `prefs.json` until it is ([`Session::own_gps`]). + pub(crate) gps_unconfirmed: std::collections::HashSet, /// Auto import: files seen in the watched folder and their size then (a file is imported once /// its size held between two scans). pub auto_import_seen: std::collections::HashMap, @@ -519,6 +551,10 @@ impl Session { #[cfg(test)] never_follow: false, visible_gen: 0, + narrow: None, + narrowed: Vec::new().into(), + narrowed_gen: 0, + narrow_key: None, total: None, undo: Vec::new(), commits: 0, @@ -566,6 +602,9 @@ impl Session { export_presets: Vec::new(), print: Default::default(), print_templates: Vec::new(), + legacy_locations: Vec::new(), + legacy_in_locations: false, + map: map::MapState::default(), print_template_folders: Vec::new(), metadata_presets: Vec::new(), filter_presets: Vec::new(), @@ -577,6 +616,8 @@ impl Session { signatures: Default::default(), lut_profiles: Vec::new(), target_album: None, + gps_edited: Default::default(), + gps_unconfirmed: Default::default(), auto_import_seen: Default::default(), keyword_sets: Vec::new(), keyword_set: None, @@ -1394,8 +1435,32 @@ impl Session { self.shelved_filter.is_some() } - /// Photos shown in the grid/filmstrip for the current source, filter and sort. + /// Photos shown in the grid/filmstrip for the current source, filter and sort, narrowed by + /// [`Session::narrow`] when a view sets it. pub fn visible(&mut self) -> &[PhotoId] { + self.visible_unnarrowed(); + let Some(rules) = &self.narrow else { return &self.visible }; + let key = (self.visible_gen, format!("{rules:?}")); + if self.narrow_key.as_ref() != Some(&key) { + lightcraft_catalog::rules::set_now(Some((self.clock)())); + let cat = &self.catalog; + self.narrowed = + self.visible.iter().copied().filter(|id| cat.photo(*id).is_some_and(|p| rules.matches(p, cat))).collect::>().into(); + self.narrowed_gen = VISIBLE_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.narrow_key = Some(key); + } + &self.narrowed + } + + /// The photos for the current source, filter and sort before [`Session::narrow`], with their + /// generation (as [`Session::visible_shared`]): what the Map view pins and counts. + pub fn visible_base_shared(&mut self) -> (u64, Arc<[PhotoId]>) { + self.visible_unnarrowed(); + (self.visible_gen, self.visible.clone()) + } + + /// The current source, filter and sort's photos, without [`Session::narrow`]. + fn visible_unnarrowed(&mut self) -> &[PhotoId] { let mut key = (self.catalog.revision, format!("{:?}|{:?}|{:?}|{:?}|{:?}", self.source, self.filter, self.sort, self.browse, self.library_folder)); // What a held view is told apart by: what is shown and how, and for a smart album its rules (rules that were @@ -1479,7 +1544,7 @@ impl Session { // an empty grid under the name of a folder that is gone from the sidebar self.source = LibrarySource::All; self.library_folder = None; - return self.visible(); + return self.visible_unnarrowed(); } if matches!(self.source, LibrarySource::Album(_)) && self.sort.key == lightcraft_catalog::SortKey::CaptureDate @@ -1647,7 +1712,7 @@ impl Session { /// whatever it derives from the list under that number. pub fn visible_shared(&mut self) -> (u64, Arc<[PhotoId]>) { self.visible(); - (self.visible_gen, self.visible.clone()) + if self.narrow.is_some() { (self.narrowed_gen, self.narrowed.clone()) } else { (self.visible_gen, self.visible.clone()) } } /// Targets of photo commands: the explicit `ids` (photo ids) or `id` (a photo id) param, else [`Self::selected`]. diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index effc5d5e42..40559bfec6 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -143,6 +143,13 @@ pub struct Library { /// Why the last write of presets.json failed; `None` once it is written. While set, the preset /// changes exist only in memory and count as unsaved ([`Session::unsaved`], issue #2266). presets_error: Option, + /// Why the last write of prefs.json failed; `None` once one lands. While set, what it holds + /// (such as which photos' GPS is LightCraft's) exists only in memory: retried by + /// [`Session::persist`], and counted as unsaved ([`Session::unsaved`]). + prefs_error: Option, + /// A `locations.json` write that failed: retried like `prefs_error`, reported by + /// [`Session::unsaved`], and closing the library refuses while it stands. + locations_error: Option, /// Records the catalog log's own thread holds because writing them failed (it retries them), /// and why; refreshed by every persist and every frame ([`Session::persist_if_dirty`]). While /// set they count as unsaved ([`Session::unsaved`]), so quitting asks first. @@ -283,6 +290,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 { @@ -342,6 +362,21 @@ struct PrefsFile { slide_titles: crate::slide_title::TitleSettings, /// A view holds the photos it shows until it is refreshed (`library.holdView`). hold_view: bool, + /// Saved map locations of older builds (`{id, name, lat, lon, radius, isPrivate}`): read once + /// into `locations.json`, and written back here only until that file is confirmed. Read + /// leniently (one bad entry costs only itself). + #[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, + /// Photos whose position was set or cleared in LightCraft ([`Session::gps_edited`]), so a + /// position cleared before the library closed still leaves the sidecar when it is written after + /// a reopen (with automatic XMP writing off, that can be much later). Read leniently: an entry + /// that isn't a photo id is skipped, never taking the other preferences with it. + #[serde(skip_serializing_if = "Vec::is_empty")] + gps_owned: Vec, } fn presets_json(s: &Session) -> String { @@ -438,6 +473,34 @@ fn kept_note(kept: &[String], damaged: Option<&String>) -> Option { } impl SettingsLoad { + /// Keep a copy of `name` as `.corrupt-` before it is written again without + /// some of its content (`why`), with a warning; when the copy can't be made the file isn't + /// overwritten this session. (From PR #906.) + fn set_aside(&mut self, store: &mut dyn Store, name: &'static str, why: &str) { + let bytes = match store.read(name) { + Ok(Some(b)) => b, + // gone since it was read: nothing left to lose + Ok(None) => return, + // no copy can be made, so the file must not be written with less in it + Err(e) => { + log::error!("library: {name}: {why}, and it couldn't be read again: {e}"); + self.blocked.push(name); + self.warnings.push(format!("{name}: {why}, and it couldn't be set aside ({e}). LightCraft won't overwrite the file.")); + return; + } + }; + let secs = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let keep = format!("{name}.corrupt-{secs}"); + log::error!("library: {name}: {why}"); + match store.write_atomic(&keep, &bytes) { + Ok(()) => self.warnings.push(format!("{name}: {why}. The file was kept as {keep}.")), + Err(w) => { + self.blocked.push(name); + self.warnings.push(format!("{name}: {why}, and it couldn't be set aside ({w}). LightCraft won't overwrite the file.")); + } + } + } + fn read(&mut self, store: &mut dyn Store, name: &'static str) -> Option { let bytes = match store.read(name) { Ok(b) => b?, @@ -471,6 +534,125 @@ impl SettingsLoad { } impl Session { + /// The library's saved locations: `locations.json` (hostile input, checked entry by entry; a + /// damaged file or bad entries are set aside as `locations.json.corrupt-