Merge pull request #4243 from bd78/lrc-map

LRC-MAP-VIEW: [GAP 16] Map view with geotagging, location filter, saved locations, track logs and the Info panel map
This commit is contained in:
FredApps authored and GitHub committed 2026-12-03 15:39:52 +01:00
commit 41bba7b486
89 files changed
+15562 -146

No files matched your search

+11 -4
View File
@@ -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<LibraryProblem>) {
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<std::path::PathBuf>, remembered: bool, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
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<std::path::PathBuf>, 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);
+226 -3
View File
@@ -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<GpsArea, Issue> {
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<GpsCircle, Issue> {
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<GpsCircle, Issue> {
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<bool> {
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())
}
+234 -1
View File
@@ -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::<Vec<_>>()
};
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::<Vec<_>>()
};
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}");
}
+48 -10
View File
@@ -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<u64> {
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<u64> {
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<u64> {
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<Item = PathBuf>, 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");
+1
View File
@@ -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)
+2
View File
@@ -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());
+10 -6
View File
@@ -404,11 +404,8 @@ pub fn specs() -> Vec<CommandSpec> {
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<CommandSpec> {
.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<CommandSpec> {
}
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<String> = 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<CommandSpec> {
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<CommandSpec> {
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::<Vec<_>>()});
if let Kind::Choice(c) = kind {
+30 -38
View File
@@ -64,41 +64,30 @@ fn set_names_ops(s: &crate::Session, names: &[String; 5]) -> Vec<Op> {
.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<Value> {
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<i64> = 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<Value> {
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<Value> {
}
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<CommandSpec> {
"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
),
+585
View File
@@ -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<Value> {
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<Vec<lightcraft_catalog::PhotoId>> {
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<usize> {
let ops: Vec<Op> = 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<Value> {
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<Value> {
const C: &str = "map.setEsriKey";
let key = match p.get("key") {
None => return Err(bad(C, "give {key: \"<your ArcGIS API 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<Option<&'a str>> {
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<Option<TileSource>> {
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<TileSource, crate::map::MapError>| 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::<Vec<_>>().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<Value> {
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<Value> {
let current = s.map.effective_source();
let list: Vec<Value> = 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<Value> {
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<Value> {
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<Option<f64>> {
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<Option<bool>> {
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<u64> {
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<Value> {
let t0 = web_time::Instant::now();
let (library, view) = (library_index(s), view_index(s));
let list: Vec<Value> = 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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<u64> = 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<CommandSpec> {
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
)
},
]
}
+1 -5
View File
@@ -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<Value> {
+71 -1
View File
@@ -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
/// `<exe dir>/LightCraftData/Cache`, so tiles stay on the portable medium too.
pub fn cache_dir() -> Option<PathBuf> {
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<OsString>, portable: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
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 `<cache>/maptiles`
/// (one folder per tile source inside; see docs/map.md).
pub fn default_map_cache_dir() -> Option<PathBuf> {
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<PathBuf> {
@@ -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] {
+9
View File
@@ -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);
+68 -3
View File
@@ -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<lightcraft_catalog::RuleSet>,
/// 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<String>)>,
pub undo: Vec<UndoEntry>,
@@ -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<print::template::PrintTemplate>,
/// 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<serde_json::Value>,
/// [`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<String>,
@@ -410,6 +432,16 @@ pub struct Session {
pub lut_profiles: Vec<cmd::lut_profiles::LutProfile>,
/// The target album B adds to (`None` = the Quick Collection).
pub target_album: Option<lightcraft_catalog::AlbumId>,
/// 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<PhotoId>,
/// 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<PhotoId>,
/// 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<String, u64>,
@@ -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::<Vec<_>>().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`].
+350 -9
View File
@@ -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<String>,
/// 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<String>,
/// 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<String>,
/// 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<O
Ok(serde_json::from_value(value).ok())
}
/// [`PrefsFile`]'s `mapSource`, or `None` (OpenStreetMap) when it isn't a tile source, with a log line.
fn lenient_tile_source<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Option<crate::map::TileSource>, D::Error> {
use serde::Deserialize;
let value = Option::<serde_json::Value>::deserialize(d)?;
Ok(value.and_then(|value| match serde_json::from_value::<crate::map::TileSource>(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<serde_json::Value>,
/// 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<crate::map::TileSource>,
/// 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<serde_json::Value>,
}
fn presets_json(s: &Session) -> String {
@@ -438,6 +473,34 @@ fn kept_note(kept: &[String], damaged: Option<&String>) -> Option<String> {
}
impl SettingsLoad {
/// Keep a copy of `name` as `<name>.corrupt-<unix time>` 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<T: serde::de::DeserializeOwned>(&mut self, store: &mut dyn Store, name: &'static str) -> Option<T> {
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-<time>` with a warning).
/// A library of an older build keeps them in `prefs.json` (`legacy`): when `locations.json`
/// doesn't exist they are written there first, read back to confirm, and only then left out of
/// `prefs.json` (by its next save). Until confirmed they stay in `prefs.json`.
fn load_locations(&mut self, files: &mut dyn Store, settings: &mut SettingsLoad, legacy: Vec<serde_json::Value>) {
use crate::locations::{FILE, LocationsFile, SavedLocations};
let revision = self.map.locations.revision();
let exists = matches!(files.read(FILE), Ok(Some(_)) | Err(_));
self.legacy_locations = Vec::new();
self.legacy_in_locations = false;
if exists {
let read = settings.read::<LocationsFile>(files, FILE);
// damaged (it was set aside, so not blocked) while prefs.json still holds an older copy:
// that copy is all there is, taken over below as when there is no file. A file written
// later with only new locations must not be taken for one that holds them.
let damaged_with_legacy = read.is_none() && !legacy.is_empty() && !settings.blocked.contains(&FILE);
if !damaged_with_legacy {
self.load_locations_file(files, settings, read, legacy, revision);
return;
}
}
if legacy.is_empty() {
self.map.locations.replace(SavedLocations::default());
return;
}
// an older build's: take them over (`isPrivate` → `private`, new numeric ids)
let entries: Vec<serde_json::Value> = legacy
.iter()
.enumerate()
.map(|(i, v)| {
let mut e = v.clone();
if let Some(o) = e.as_object_mut() {
o.insert("id".into(), serde_json::json!(i as u64 + 1));
if let Some(p) = o.remove("isPrivate") {
o.insert("private".into(), p);
}
}
e
})
.collect();
let (locations, dropped) = SavedLocations::load(LocationsFile { version: 1, locations: entries, last_id: 0 }, revision);
if dropped > 0 {
settings.warnings.push(format!("{dropped} saved location(s) in prefs.json aren't valid and were left out of {FILE}"));
}
let bytes = locations.to_file();
let confirmed = files.write_atomic(FILE, &bytes).is_ok()
&& matches!(files.read(FILE), Ok(Some(back)) if serde_json::from_slice::<LocationsFile>(&back).is_ok_and(|f| f.locations.len() == locations.len()));
if !confirmed {
log::error!("library: the saved locations couldn't be moved to {FILE}; they stay in prefs.json");
self.legacy_locations = legacy;
// they are in the active list: its next write confirms them
self.legacy_in_locations = true;
}
self.map.locations.replace(locations);
}
/// Whether the saved locations can be saved: not when `locations.json` couldn't be read at open
/// (it is never overwritten then). Location commands check it before changing anything, so no
/// edit lives only in memory.
pub(crate) fn locations_writable(&self) -> Result<()> {
if self.library.as_ref().is_some_and(|l| l.blocked.contains(&crate::locations::FILE)) {
return Err(EngineError::Other(format!(
"{0} couldn't be read when the library opened, so it isn't overwritten; reopen the library to change saved locations",
crate::locations::FILE
)));
}
Ok(())
}
/// `locations.json` as read (`None`: damaged or unreadable, so the older `prefs.json` copy stays).
fn load_locations_file(
&mut self,
files: &mut dyn Store,
settings: &mut SettingsLoad,
read: Option<crate::locations::LocationsFile>,
legacy: Vec<serde_json::Value>,
revision: u64,
) {
use crate::locations::{FILE, SavedLocations};
// a damaged (or unreadable) locations.json confirms nothing: an older prefs.json copy stays
if read.is_none() {
self.legacy_locations = legacy;
}
let file = read.unwrap_or_default();
let (locations, dropped) = SavedLocations::load(file, revision);
if dropped > 0 {
settings.set_aside(files, FILE, &format!("{dropped} saved location(s) in it aren't valid and were left out"));
// the copy is safe: write the good ones back, so the next open doesn't set it aside again
if !settings.blocked.contains(&FILE)
&& let Err(e) = files.write_atomic(FILE, &locations.to_file())
{
log::error!("library: {FILE}: {e}");
}
}
self.map.locations.replace(locations);
}
/// Save the saved locations (`locations.json`, atomically; no-op for in-memory sessions).
/// Once it is written with the older `prefs.json` copy's entries in it, that copy is no longer
/// kept; when they aren't in it (`locations.json` was damaged), the copy stays.
pub fn save_locations(&mut self) -> Result<()> {
let v = self.map.locations.to_file();
self.locations_writable()?;
let Some(lib) = self.library.as_mut() else { return Ok(()) };
// a failed write stays pending (retried by persist, counted as unsaved) until one lands
let written = lib.files.write_atomic(crate::locations::FILE, &v).map_err(|e| format!("saved locations: {e}"));
lib.locations_error = written.as_ref().err().cloned();
written.map_err(EngineError::Other)?;
if self.legacy_in_locations && !self.legacy_locations.is_empty() {
self.legacy_locations.clear();
self.legacy_in_locations = false;
if let Err(e) = self.save_prefs() {
log::warn!("prefs.json: {e}");
}
}
Ok(())
}
/// Take over what the thumbnail cache wrote under its name of before (`.jpg` files, which
/// photo galleries took for the person's photos: issues #610, #1066), once for a cache
/// folder that was not made or tidied by this build yet. On a thread of its own, with a row
@@ -620,6 +802,7 @@ impl Session {
log::error!("library: {e} (every change is in its snapshot)");
}
}
self.save_settings_before_switch()?;
let (mut journal, mut catalog, report) = Journal::open_with_legacy_denoise(catalog, || {
crate::denoise::capture_legacy_pin(self.denoise.models_dir.as_deref()).map_err(lightcraft_catalog::CatalogError::Io)
})?;
@@ -650,6 +833,9 @@ impl Session {
}
self.undo.clear();
self.redo.clear();
// photo ids are per library: positions set in the last one say nothing about this one's
self.gps_edited.clear();
self.gps_unconfirmed.clear();
self.interaction = None;
self.pending_log.clear();
self.selection = Selection::default();
@@ -694,6 +880,18 @@ 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.load_locations(files.as_mut(), &mut settings, prefs.saved_locations);
// (only ids of this library's photos: the file may be older than the catalog)
self.gps_edited = prefs
.gps_owned
.iter()
.filter_map(serde_json::Value::as_u64)
.map(lightcraft_catalog::PhotoId)
.filter(|id| self.catalog.photo(*id).is_some())
.collect();
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 {
@@ -765,6 +963,8 @@ impl Session {
last_error: None,
unsaved_error: None,
presets_error: None,
prefs_error: None,
locations_error: None,
log_held: None,
retry_at: None,
forgot_local: None,
@@ -903,6 +1103,26 @@ impl Session {
log::error!("library: compaction: {e}");
lib.last_error = Some(format!("compaction: {e}"));
}
// a locations.json write that failed: retried until it lands
if self.library.as_ref().is_some_and(|l| l.locations_error.is_some())
&& let Err(e) = self.save_locations()
{
log::error!("library: {e}");
if let Some(lib) = self.library.as_mut() {
lib.retry_at = Some(web_time::Instant::now() + RETRY_BACKOFF);
}
}
// GPS ownership of changes now appended: confirmed once the log is on disk, then written
let confirmed = self.confirm_gps_ownership();
// a prefs.json write that failed (GPS ownership, a preference): retried until it lands
if (confirmed || self.library.as_ref().is_some_and(|l| l.prefs_error.is_some()))
&& let Err(e) = self.save_prefs()
{
log::error!("library: {e}");
if let Some(lib) = self.library.as_mut() {
lib.retry_at = Some(web_time::Instant::now() + RETRY_BACKOFF);
}
}
let due = self.library.as_ref().is_some_and(|l| l.presets_saved.differs(self) && !l.blocked.contains(&"presets.json"));
if !due {
return Ok(());
@@ -933,7 +1153,9 @@ impl Session {
/// changed outside [`Session::execute`]).
pub fn persist_if_dirty(&mut self) {
let backing_off = self.library.as_ref().and_then(|l| l.retry_at).is_some_and(|t| web_time::Instant::now() < t);
let presets_unsaved = self.library.as_ref().is_some_and(|l| l.presets_error.is_some());
let presets_unsaved =
self.library.as_ref().is_some_and(|l| l.presets_error.is_some() || l.prefs_error.is_some() || l.locations_error.is_some())
|| !self.gps_unconfirmed.is_empty();
// records the log's thread can't write: a snapshot (a fresh file holding everything) is due
let log_held = self.library.as_ref().is_some_and(|l| l.log_held.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved || log_held) && !backing_off {
@@ -969,22 +1191,29 @@ impl Session {
}
/// Changes applied in memory but not yet written to disk because saving failed: the number of
/// queued ops (plus one for presets.json) and why (`None` when everything is saved, or no library
/// queued ops (plus one each for presets.json and prefs.json) and why (`None` when everything is saved, or no library
/// is open). Retried by every command and by [`Session::persist_if_dirty`].
pub fn unsaved(&self) -> Option<(usize, &str)> {
let lib = self.library.as_ref()?;
let ops = lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty());
let presets = lib.presets_error.as_deref();
let prefs = lib.prefs_error.as_deref();
let locations = lib.locations_error.as_deref();
let held = lib.log_held.as_ref().map(|(n, why)| (*n, why.as_str()));
let n = ops.map_or(0, |_| self.pending_log.len()) + held.map_or(0, |(n, _)| n) + usize::from(presets.is_some());
ops.or(held.map(|(_, why)| why)).or(presets).map(|why| (n, why))
let n = ops.map_or(0, |_| self.pending_log.len())
+ held.map_or(0, |(n, _)| n)
+ usize::from(presets.is_some())
+ usize::from(prefs.is_some())
+ usize::from(locations.is_some());
ops.or(held.map(|(_, why)| why)).or(presets).or(prefs).or(locations).map(|why| (n, why))
}
/// Flush everything and write a snapshot (on quit). Ends an open interaction first.
///
/// The snapshot is written even when appending the queued ops fails: it is a fresh file
/// holding everything in memory, so it saves those ops too (the log handle may be the only
/// thing that's broken). Fails only if nothing could be saved; the ops then stay queued.
/// thing that's broken). Fails if nothing could be saved (the ops then stay queued), or if
/// prefs.json still can't be written.
pub fn close_library(&mut self) -> Result<()> {
if self.library.is_none() {
return Ok(());
@@ -993,6 +1222,14 @@ impl Session {
let persisted = self.persist();
self.save_view();
let unlogged = if persisted.is_err() { self.pending_log.len() as u64 } else { 0 };
// a prefs.json write still failing is tried once more (persist stops before it when the
// log can't be appended)
if self.library.as_ref().is_some_and(|l| l.prefs_error.is_some()) {
let _ = self.save_prefs();
}
if self.library.as_ref().is_some_and(|l| l.locations_error.is_some()) {
let _ = self.save_locations();
}
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let before = lib.journal.seq();
let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged);
@@ -1012,6 +1249,22 @@ impl Session {
(Err(EngineError::NotSaved(e)), Err(s)) if lib.journal.seq() == before => Err(EngineError::NotSaved(format!("{e}; snapshot: {s}"))),
(_, Err(s)) => Err(s.into()),
};
// ownership not confirmed yet: the closing snapshot holds its changes now, so it is written
// (or the close fails below with what's left unsaved)
if result.is_ok() && !self.gps_unconfirmed.is_empty() {
self.gps_unconfirmed.clear();
if let Err(e) = self.save_prefs() {
log::error!("library: {e}");
}
}
let Some(lib) = self.library.as_mut() else { return result };
// what prefs.json holds and couldn't write (such as which photos' GPS is LightCraft's) is
// lost once another library opens: an error, so a switch keeps this library open and a
// quit asks first
// (a prefs.json that couldn't be read at open is never written: retrying can't help, so it
// doesn't keep the library open; the quit check still reports it through `unsaved`)
let prefs_pending = lib.prefs_error.clone().filter(|_| !lib.blocked.contains(&"prefs.json"));
let result = result.and_then(|()| prefs_pending.or(lib.locations_error.clone()).map_or(Ok(()), |e| Err(EngineError::NotSaved(e))));
if result.is_ok() {
self.library_identity = std::sync::Arc::new(());
}
@@ -1057,6 +1310,76 @@ impl Session {
}
}
/// After a command set or cleared the position of `ids` (once its commit landed): they become
/// LightCraft's for their sidecar GPS ([`Session::gps_edited`]). Saved with the preferences by
/// [`Session::persist`] once the change is on disk.
pub(crate) fn own_gps(&mut self, ids: impl IntoIterator<Item = lightcraft_catalog::PhotoId>) {
let open = self.library.is_some();
for id in ids {
// unconfirmed until the change is on disk ([`Session::persist`], or the closing snapshot):
// ownership saved for a change that was then lost (a crash between the two writes) would
// let a later sidecar save remove another app's GPS, so prefs.json never holds it before
if self.gps_edited.insert(id) && open {
self.gps_unconfirmed.insert(id);
}
}
}
/// Ownership of GPS changes now in the log: confirmed when nothing is queued and the log is on
/// disk. Returns whether some was (prefs.json is due).
fn confirm_gps_ownership(&mut self) -> bool {
if self.gps_unconfirmed.is_empty() || !self.pending_log.is_empty() {
return false;
}
if let Err(e) = self.flush_log() {
log::error!("library: GPS ownership waits for the catalog log: {e}");
if let Some(lib) = self.library.as_mut() {
lib.retry_at = Some(web_time::Instant::now() + RETRY_BACKOFF);
}
return false;
}
self.gps_unconfirmed.clear();
true
}
/// Before another library replaces this one: its pending prefs.json / locations.json writes
/// (which photos' GPS is LightCraft's, a saved location) are lost once it is replaced, so they
/// are tried once more and the open fails if one still can't be written. A prefs.json
/// unreadable at open is never written: it doesn't hold the switch back.
fn save_settings_before_switch(&mut self) -> Result<()> {
// (its log was flushed just before: ownership of what is in it is confirmed)
let confirmed = self.confirm_gps_ownership();
let writable = self.library.as_ref().is_some_and(|l| !l.blocked.contains(&"prefs.json"));
let pending = self.library.as_ref().is_some_and(|l| l.prefs_error.is_some());
if (confirmed || pending)
&& writable
&& let Err(e) = self.save_prefs()
{
return Err(EngineError::NotSaved(format!("the open library's preferences aren't on disk yet, so it stays open: {e}")));
}
if self.library.as_ref().is_some_and(|l| l.locations_error.is_some())
&& let Err(e) = self.save_locations()
{
return Err(EngineError::NotSaved(format!("the open library's saved locations aren't on disk yet, so it stays open: {e}")));
}
Ok(())
}
/// Save the library preferences after a change that `undo` takes back if the write fails. The
/// change then never happened, so the failed write isn't left pending as unsaved
/// ([`Session::unsaved`]) unless an earlier one already was.
pub(crate) fn save_prefs_or_undo(&mut self, undo: impl FnOnce(&mut Self)) -> Result<()> {
let pending = self.library.as_ref().and_then(|l| l.prefs_error.clone());
let saved = self.save_prefs();
if saved.is_err() {
undo(self);
if let Some(lib) = self.library.as_mut() {
lib.prefs_error = pending;
}
}
saved
}
/// Save the library preferences (no-op for in-memory sessions).
pub fn save_prefs(&mut self) -> Result<()> {
let v = serde_json::to_vec_pretty(&PrefsFile {
@@ -1087,15 +1410,33 @@ impl Session {
slide_overlays: self.slide_overlays.clone(),
slide_titles: self.slide_titles.clone(),
hold_view: self.hold_view,
saved_locations: self.legacy_locations.clone(),
map_source: Some(self.map.source().clone()),
gps_owned: {
// only confirmed ownership: never one whose change isn't on disk yet
let mut ids: Vec<u64> = self
.gps_edited
.iter()
.filter(|id| self.catalog.photo(**id).is_some() && !self.gps_unconfirmed.contains(id))
.map(|id| id.0)
.collect();
ids.sort_unstable();
ids.into_iter().map(serde_json::Value::from).collect()
},
})
.unwrap_or_default();
let Some(lib) = self.library.as_mut() else { return Ok(()) };
if lib.blocked.contains(&"prefs.json") {
return Err(EngineError::Other(
"prefs: prefs.json couldn't be read when the library opened, so it isn't overwritten; reopen the library to save preferences".into(),
));
// never overwritten, but recorded: what was changed is reported as unsaved rather than lost
// silently (save_prefs_or_undo puts the earlier state back when it rolls a change back)
let why = "prefs: prefs.json couldn't be read when the library opened, so it isn't overwritten; reopen the library to save preferences";
lib.prefs_error = Some(why.into());
return Err(EngineError::Other(why.into()));
}
lib.files.write_atomic("prefs.json", &v).map_err(|e| EngineError::Other(format!("prefs: {e}")))
// a failed write stays pending (retried by persist) until one lands
let written = lib.files.write_atomic("prefs.json", &v).map_err(|e| format!("prefs: {e}"));
lib.prefs_error = written.as_ref().err().cloned();
written.map_err(EngineError::Other)
}
/// Warnings about the open library not handed out yet: its settings files, and a lock that
+431
View File
@@ -0,0 +1,431 @@
//! Saved locations (LRC-MAP-LOCATIONS, as Lightroom Classic's Saved Locations): named circles on
//! the map, a centre and a radius, each optionally *private* (photos inside it are exported
//! without their location, as if "Remove location info" were on for them; see
//! [`crate::export::prepare_export`]).
//!
//! They are a library setting, not catalog records: kept in `locations.json` next to the catalog
//! (written atomically on every change, like `prefs.json`), so the catalog's journal format is
//! untouched. Edits take effect at once and are not undo steps (Lightroom Classic's saved
//! location edits aren't part of a photo's history either). The file is hostile input: one that
//! doesn't parse is set aside as `locations.json.corrupt-<time>` and the library opens without
//! saved locations; entries that aren't valid (a NaN, a latitude of 300, an empty name, a radius
//! of 0, a duplicate id, past [`MAX_LOCATIONS`]) are left out and the file is set aside the same
//! way before it is next written, with a warning naming how many were dropped.
//!
//! Commands: `map.locations`, `map.location.add`, `.update`, `.remove`, `.photos` (`cmd/map.rs`).
//! Counting photos inside each location uses a latitude-sorted index ([`PositionIndex`]): a
//! binary search for the circle's latitude band, then the exact distance for those, so thousands
//! of locations over tens of thousands of photos stay cheap.
use lightcraft_catalog::rules::{GpsCircle, MAX_RADIUS_M, MIN_RADIUS_M, valid_gps};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
/// The file next to the catalog that holds them.
pub const FILE: &str = "locations.json";
/// At most this many saved locations per library (a file with more keeps the first ones).
pub const MAX_LOCATIONS: usize = 10_000;
/// A name is 1…this many characters (after trimming).
pub const MAX_NAME_CHARS: usize = 200;
/// The file format written (a newer one is read the same way: unknown fields are ignored).
const VERSION: u32 = 1;
/// One saved location: a circle of `radius` metres around `lat, lon` (degrees).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SavedLocation {
pub id: u64,
pub name: String,
pub lat: f64,
pub lon: f64,
/// Metres, 1 m…1000 km.
pub radius: f64,
/// Photos inside are exported without location metadata, and the Info panel's map hides.
#[serde(default)]
pub private: bool,
}
impl SavedLocation {
/// Its circle (always valid: every location is checked when made, changed or loaded).
pub fn circle(&self) -> GpsCircle {
GpsCircle { lat: self.lat, lon: self.lon, radius: self.radius }
}
/// Whether the GPS position `gps` (as `Meta.gps` stores it) is inside; never for a position
/// that isn't one.
pub fn contains(&self, gps: Option<(f64, f64)>) -> bool {
valid_gps(gps).is_some_and(|(lat, lon)| self.circle().contains(lat, lon))
}
/// `{id, name, lat, lon, radius, private}`.
pub fn to_json(&self) -> Value {
json!({"id": self.id, "name": self.name, "lat": self.lat, "lon": self.lon, "radius": self.radius, "private": self.private})
}
}
/// A name as a location keeps it: trimmed, control characters out, 1…[`MAX_NAME_CHARS`].
pub fn check_name(name: &str) -> Result<String, String> {
let clean: String = name.chars().filter(|c| !c.is_control()).collect();
let clean = clean.trim();
if clean.is_empty() {
return Err("the name is empty".into());
}
if clean.chars().count() > MAX_NAME_CHARS {
return Err(format!("the name is longer than {MAX_NAME_CHARS} characters"));
}
Ok(clean.to_string())
}
/// The centre and radius checked: finite, latitude −90…90, longitude −180…180, radius 1 m…1000 km.
pub fn check_circle(lat: f64, lon: f64, radius: f64) -> Result<(), String> {
if !(lat.is_finite() && (-90.0..=90.0).contains(&lat)) {
return Err(format!("lat {lat} isn't a latitude (−90…90)"));
}
if !(lon.is_finite() && (-180.0..=180.0).contains(&lon)) {
return Err(format!("lon {lon} isn't a longitude (−180…180)"));
}
if !(radius.is_finite() && (MIN_RADIUS_M..=MAX_RADIUS_M).contains(&radius)) {
return Err(format!("radius {radius} isn't 1 m to 1000 km (in metres)"));
}
Ok(())
}
/// What `map.location.update` changes (what is `None` stays).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LocationChange {
pub name: Option<String>,
pub lat: Option<f64>,
pub lon: Option<f64>,
pub radius: Option<f64>,
pub private: Option<bool>,
}
/// The library's saved locations, in the order they were made.
#[derive(Clone, Debug, Default)]
pub struct SavedLocations {
list: Vec<SavedLocation>,
/// Changes so far this session (what the UI caches its counts under).
revision: u64,
/// The highest id ever given out (saved): a deleted location's id is never reused, so a caller
/// holding it gets "no such location", not another one.
last_id: u64,
}
/// The file's layout. Entries are read one by one ([`SavedLocations::load`]), so a bad one costs
/// only itself.
#[derive(Default, Serialize, Deserialize)]
#[serde(default)]
pub(crate) struct LocationsFile {
pub version: u32,
pub locations: Vec<Value>,
/// The highest id given out so far (0 in files of older builds).
#[serde(rename = "lastId")]
pub last_id: u64,
}
impl SavedLocations {
pub fn list(&self) -> &[SavedLocation] {
&self.list
}
pub fn len(&self) -> usize {
self.list.len()
}
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
/// Bumped by every change (and by loading a library's).
pub fn revision(&self) -> u64 {
self.revision
}
pub fn get(&self, id: u64) -> Option<&SavedLocation> {
self.list.iter().find(|l| l.id == id)
}
/// The first private location the position `gps` is inside.
pub fn private_at(&self, gps: Option<(f64, f64)>) -> Option<&SavedLocation> {
valid_gps(gps)?;
self.list.iter().find(|l| l.private && l.contains(gps))
}
fn next_id(&self) -> u64 {
self.list.iter().map(|l| l.id).max().unwrap_or(0).max(self.last_id).saturating_add(1)
}
/// Add a location (checked); returns it with its new id.
pub fn add(&mut self, name: &str, lat: f64, lon: f64, radius: f64, private: bool) -> Result<SavedLocation, String> {
if self.list.len() >= MAX_LOCATIONS {
return Err(format!("a library holds at most {MAX_LOCATIONS} saved locations"));
}
let name = check_name(name)?;
check_circle(lat, lon, radius)?;
let id = self.next_id();
if id == u64::MAX {
return Err("no location id left".into());
}
let l = SavedLocation { id, name, lat, lon, radius, private };
self.last_id = id;
self.list.push(l.clone());
self.revision = self.revision.wrapping_add(1);
Ok(l)
}
/// Change location `id` (checked as a whole: nothing changes when any part is refused).
pub fn update(&mut self, id: u64, c: &LocationChange) -> Result<SavedLocation, String> {
let Some(cur) = self.get(id) else { return Err(format!("no saved location {id}")) };
let mut next = cur.clone();
if let Some(n) = &c.name {
next.name = check_name(n)?;
}
next.lat = c.lat.unwrap_or(next.lat);
next.lon = c.lon.unwrap_or(next.lon);
next.radius = c.radius.unwrap_or(next.radius);
next.private = c.private.unwrap_or(next.private);
check_circle(next.lat, next.lon, next.radius)?;
if let Some(slot) = self.list.iter_mut().find(|l| l.id == id) {
*slot = next.clone();
self.revision = self.revision.wrapping_add(1);
}
Ok(next)
}
/// Remove location `id`; `None` when there is none.
pub fn remove(&mut self, id: u64) -> Option<SavedLocation> {
let i = self.list.iter().position(|l| l.id == id)?;
self.revision = self.revision.wrapping_add(1);
Some(self.list.remove(i))
}
/// The locations of a file's entries, and how many entries were left out (not a valid
/// location, a duplicate id, past [`MAX_LOCATIONS`]).
pub(crate) fn load(file: LocationsFile, revision: u64) -> (SavedLocations, usize) {
let last_id = file.last_id;
let mut list: Vec<SavedLocation> = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut dropped = 0usize;
for v in file.locations {
let ok = serde_json::from_value::<SavedLocation>(v).ok().and_then(|mut l| {
l.name = check_name(&l.name).ok()?;
check_circle(l.lat, l.lon, l.radius).ok()?;
(l.id > 0 && l.id < u64::MAX && list.len() < MAX_LOCATIONS && seen.insert(l.id)).then_some(l)
});
match ok {
Some(l) => list.push(l),
None => dropped += 1,
}
}
let last_id = list.iter().map(|l| l.id).max().unwrap_or(0).max(last_id);
(SavedLocations { list, revision: revision.wrapping_add(1), last_id }, dropped)
}
/// The file's bytes for these locations.
pub(crate) fn to_file(&self) -> Vec<u8> {
#[derive(Serialize)]
struct Out<'a> {
version: u32,
locations: &'a [SavedLocation],
#[serde(rename = "lastId")]
last_id: u64,
}
serde_json::to_vec_pretty(&Out { version: VERSION, locations: &self.list, last_id: self.last_id }).unwrap_or_default()
}
/// Replace them all (a library opened, or one with none).
pub(crate) fn replace(&mut self, other: SavedLocations) {
let revision = self.revision.max(other.revision).wrapping_add(1);
*self = SavedLocations { list: other.list, revision, last_id: other.last_id };
}
}
/// Photo positions sorted by latitude, to find those inside a circle quickly: a binary search for
/// the circle's latitude band ([`GpsCircle::lat_range`]), then the exact distance for each
/// position in it.
#[derive(Clone, Debug, Default)]
pub struct PositionIndex {
/// `(lat, lon, id)`, by latitude.
by_lat: Vec<(f64, f64, u64)>,
}
impl PositionIndex {
/// From `(id, gps)` pairs; positions that aren't ones are left out.
pub fn new<I: IntoIterator<Item = (u64, Option<(f64, f64)>)>>(items: I) -> PositionIndex {
let mut by_lat: Vec<(f64, f64, u64)> = items.into_iter().filter_map(|(id, gps)| valid_gps(gps).map(|(lat, lon)| (lat, lon, id))).collect();
by_lat.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.2.cmp(&b.2)));
PositionIndex { by_lat }
}
/// Positions held.
pub fn len(&self) -> usize {
self.by_lat.len()
}
pub fn is_empty(&self) -> bool {
self.by_lat.is_empty()
}
fn band(&self, c: &GpsCircle) -> &[(f64, f64, u64)] {
let (south, north) = c.lat_range();
let from = self.by_lat.partition_point(|p| p.0 < south);
let to = self.by_lat.partition_point(|p| p.0 <= north);
self.by_lat.get(from..to.max(from)).unwrap_or(&[])
}
/// How many positions are inside `c`.
pub fn count(&self, c: &GpsCircle) -> usize {
self.band(c).iter().filter(|p| c.contains(p.0, p.1)).count()
}
/// The ids of the positions inside `c` (by latitude, south first).
pub fn inside(&self, c: &GpsCircle) -> Vec<u64> {
self.band(c).iter().filter(|p| c.contains(p.0, p.1)).map(|p| p.2).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_update_remove_check_every_value() {
let mut s = SavedLocations::default();
let home = s.add(" Home ", 48.85, 2.29, 300.0, true).unwrap();
assert_eq!((home.id, home.name.as_str(), home.private), (1, "Home", true));
let r0 = s.revision();
for (name, lat, lon, radius) in [
("", 0.0, 0.0, 100.0),
(" ", 0.0, 0.0, 100.0),
("x", 90.5, 0.0, 100.0),
("x", f64::NAN, 0.0, 100.0),
("x", 0.0, 180.01, 100.0),
("x", 0.0, 0.0, 0.5),
("x", 0.0, 0.0, 1_000_000.5),
("x", 0.0, 0.0, f64::INFINITY),
] {
assert!(s.add(name, lat, lon, radius, false).is_err(), "{name:?} {lat} {lon} {radius}");
}
assert!(s.add(&"n".repeat(MAX_NAME_CHARS + 1), 0.0, 0.0, 10.0, false).is_err());
assert_eq!(s.add(&"é".repeat(MAX_NAME_CHARS), 0.0, 0.0, 10.0, false).unwrap().name.chars().count(), MAX_NAME_CHARS);
assert_eq!(s.add("tab\there\n", 0.0, 0.0, 10.0, false).unwrap().name, "tabhere");
assert!(s.revision() > r0);
// an update is checked as a whole: a bad radius leaves the name alone too
let c = LocationChange { name: Some("Flat".into()), radius: Some(-1.0), ..Default::default() };
assert!(s.update(home.id, &c).is_err());
assert_eq!(s.get(home.id).unwrap().name, "Home");
let c = LocationChange { name: Some("Flat".into()), lon: Some(-179.5), private: Some(false), ..Default::default() };
let u = s.update(home.id, &c).unwrap();
assert_eq!((u.name.as_str(), u.lon, u.private, u.radius), ("Flat", -179.5, false, 300.0));
assert!(s.update(999, &LocationChange::default()).is_err());
assert_eq!(s.remove(home.id).map(|l| l.name), Some("Flat".into()));
assert!(s.remove(home.id).is_none());
// ids are never reused while a higher one exists
let next = s.add("Next", 1.0, 1.0, 10.0, false).unwrap();
assert!(s.list().iter().filter(|l| l.id == next.id).count() == 1);
}
#[test]
fn loading_keeps_good_entries_and_counts_the_rest() {
let file: LocationsFile = serde_json::from_value(json!({
"version": 1,
"locations": [
{"id": 1, "name": "Home", "lat": 48.8, "lon": 2.3, "radius": 200.0, "private": true},
{"id": 1, "name": "Duplicate", "lat": 1.0, "lon": 1.0, "radius": 10.0},
{"id": 2, "name": "", "lat": 1.0, "lon": 1.0, "radius": 10.0},
{"id": 3, "name": "Too far north", "lat": 300.0, "lon": 1.0, "radius": 10.0},
{"id": 4, "name": "Zero", "lat": 1.0, "lon": 1.0, "radius": 0.0},
{"id": 0, "name": "No id", "lat": 1.0, "lon": 1.0, "radius": 10.0},
{"id": "5", "name": "Text id", "lat": 1.0, "lon": 1.0, "radius": 10.0},
"not an object",
null,
{"id": 6, "name": "Fiji", "lat": -17.0, "lon": 179.99, "radius": 50000.0, "extra": [1, 2]},
]
}))
.unwrap();
let (s, dropped) = SavedLocations::load(file, 0);
assert_eq!(s.list().iter().map(|l| l.id).collect::<Vec<_>>(), vec![1, 6]);
assert_eq!(dropped, 8);
assert!(s.get(1).unwrap().private && !s.get(6).unwrap().private);
// written back and read again: the same
let again: LocationsFile = serde_json::from_slice(&s.to_file()).unwrap();
assert_eq!(again.version, VERSION);
let (t, d) = SavedLocations::load(again, 0);
assert_eq!((t.list(), d), (s.list(), 0));
}
#[test]
fn a_file_with_too_many_keeps_the_first_ones() {
let locations: Vec<Value> = (1..=MAX_LOCATIONS as u64 + 5)
.map(|i| json!({"id": i, "name": format!("L{i}"), "lat": (i % 170) as f64 - 85.0, "lon": (i % 360) as f64 - 180.0, "radius": 1000.0}))
.collect();
let (mut s, dropped) = SavedLocations::load(LocationsFile { version: 1, locations, last_id: 0 }, 0);
assert_eq!((s.len(), dropped), (MAX_LOCATIONS, 5));
assert!(s.add("One more", 0.0, 0.0, 10.0, false).is_err());
}
#[test]
fn the_index_counts_like_checking_every_photo() {
// a spread of positions, the poles and both sides of the antimeridian included
let mut items = Vec::new();
let mut id = 0;
for lat in (-90..=90).step_by(3) {
for lon in (-180..=180).step_by(7) {
id += 1;
items.push((id, Some((f64::from(lat), f64::from(lon)))));
}
}
items.push((id + 1, Some((f64::NAN, 0.0))));
items.push((id + 2, None));
let idx = PositionIndex::new(items.clone());
assert_eq!(idx.len(), items.len() - 2);
let circles = [
GpsCircle::new(48.0, 2.0, 400_000.0).unwrap(),
GpsCircle::new(0.0, 179.5, 1_000_000.0).unwrap(),
GpsCircle::new(0.0, -180.0, 900_000.0).unwrap(),
GpsCircle::new(88.0, 45.0, 600_000.0).unwrap(),
GpsCircle::new(-90.0, 0.0, 1_000_000.0).unwrap(),
GpsCircle::new(10.0, 10.0, 1.0).unwrap(),
];
for c in circles {
let brute: Vec<u64> = items.iter().filter(|(_, g)| valid_gps(*g).is_some_and(|(a, b)| c.contains(a, b))).map(|(i, _)| *i).collect();
let mut got = idx.inside(&c);
got.sort();
assert_eq!(got, brute, "{c:?}");
assert_eq!(idx.count(&c), brute.len());
}
// the circle around the south pole holds every position at −90 whatever its longitude
let south = GpsCircle::new(-90.0, 0.0, 1_000_000.0).unwrap();
assert!(idx.count(&south) >= (-180..=180).step_by(7).count() * 3);
// across the antimeridian: positions on both sides
let fiji = GpsCircle::new(0.0, 179.5, 1_000_000.0).unwrap();
let lons: Vec<f64> = idx.band(&fiji).iter().filter(|p| fiji.contains(p.0, p.1)).map(|p| p.1).collect();
assert!(lons.iter().any(|l| *l > 170.0) && lons.iter().any(|l| *l < -170.0), "{lons:?}");
}
/// A deleted location's id is never given out again, also after the file is written and read back.
#[test]
fn ids_of_deleted_locations_are_not_reused() {
let mut s = SavedLocations::default();
let home = s.add("Home", 48.86, 2.33, 500.0, false).unwrap();
s.remove(home.id);
let park = s.add("Park", 48.85, 2.29, 500.0, false).unwrap();
assert_ne!(park.id, home.id, "not reused");
s.remove(park.id);
let file: LocationsFile = serde_json::from_slice(&s.to_file()).unwrap();
let (mut back, _) = SavedLocations::load(file, 0);
let next = back.add("Office", 48.87, 2.35, 500.0, false).unwrap();
assert!(next.id > park.id, "not reused after a reopen either: {} vs {}", next.id, park.id);
}
#[test]
fn private_at_finds_the_private_location_holding_a_position() {
let mut s = SavedLocations::default();
s.add("Park", 48.85, 2.29, 2000.0, false).unwrap();
let home = s.add("Home", 48.86, 2.33, 500.0, true).unwrap();
assert_eq!(s.private_at(Some((48.8601, 2.3302))).map(|l| l.id), Some(home.id));
assert!(s.private_at(Some((48.85, 2.29))).is_none(), "inside a public location only");
assert!(s.private_at(None).is_none());
assert!(s.private_at(Some((f64::NAN, 2.33))).is_none());
}
}
+435
View File
@@ -0,0 +1,435 @@
//! 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`]), with the saved locations ([`crate::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`, `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.
pub mod cache;
pub mod cluster;
mod http_date;
pub mod mercator;
pub mod service;
pub mod source;
pub mod track;
#[cfg(test)]
mod tests_cluster;
#[cfg(test)]
mod tests_mercator;
#[cfg(test)]
mod tests_service;
#[cfg(test)]
mod tests_track;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::Session;
pub use cache::{CacheInfo, DEFAULT_CACHE_BYTES, TileCache, TileMeta};
pub use cluster::{CLUSTER_CELL, Cluster, MapPoint};
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, TransportError};
pub use source::{Crop, OSM_ATTRIBUTION, OSM_TILE_URL, TileSource, USER_AGENT};
pub use track::TrackShape;
/// 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),
}
/// 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)
}
/// 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<ApiKey, String> {
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<String>,
}
/// 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 without a key is
/// kept here (never overwritten) but not used: see [`MapState::effective_source`].
source: TileSource,
/// The user's ArcGIS API key: the Esri layers are offered and fetched only with one.
esri_key: Option<ApiKey>,
/// Where the key is kept (`<config>/map-keys.json`); `None`: memory only (tests, the web).
pub key_file: Option<PathBuf>,
/// The tile cache folder (`<cache>/maptiles`, one folder per source inside); `None` = tiles
/// are kept in memory only (tests, the web).
pub cache_root: Option<PathBuf>,
/// 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<TileService>,
/// The library's saved locations (`locations.json`, see [`crate::locations`]).
pub locations: crate::locations::SavedLocations,
/// The track log loaded into the Map view (session only, see [`crate::tracklog`]).
pub track: Option<crate::tracklog::LoadedTrack>,
/// Bumped by every change of [`MapState::track`] (load, active track, offset, clear).
pub track_generation: u64,
}
impl Default for MapState {
fn default() -> Self {
MapState {
source: TileSource::Osm,
esri_key: None,
key_file: None,
cache_root: None,
cache_bytes: DEFAULT_CACHE_BYTES,
online: false,
service: None,
locations: Default::default(),
track: None,
track_generation: 0,
}
}
}
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 a key that isn't set.
pub fn effective_source(&self) -> TileSource {
if self.usable(&self.source) { self.source.clone() } else { TileSource::Osm }
}
/// 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 a key).
pub fn usable(&self, source: &TileSource) -> bool {
!source.requires_key() || self.esri_key.is_some()
}
/// The built-in sources a picker offers: those usable now.
pub fn offered(&self) -> Vec<TileSource> {
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<String> {
(!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 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_KEY_HELP}", 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();
}
}
/// 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 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<TileSource>) -> Option<String> {
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) = &notice {
log::warn!("map: {n}");
}
notice
}
/// 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<ApiKey>) -> 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<PathBuf>) {
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::<KeyFile>(&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).
pub fn reset_service(&mut self) {
self.service = None;
}
/// 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);
}
/// The service if one is running (no side effects).
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)?;
// owner-only from its creation, not after the key is on disk
lightcraft_catalog::safe_file::write_atomic_private(path, &data)
}
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;
}
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)),
)
}
}
/// 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<Self> {
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,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key() -> ApiKey {
ApiKey::parse("AAPK0123456789abcdef_TEST-key.x").unwrap()
}
#[test]
fn esri_is_neither_offered_nor_used_without_a_key() {
let mut m = MapState::default();
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("API key"), "{notice}");
assert_eq!(*m.source(), TileSource::EsriTopo);
assert_eq!(m.effective_source(), TileSource::Osm);
// 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::EsriStreet));
m.choose(TileSource::EsriStreet).unwrap();
assert_eq!(m.fallback_notice(), None);
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);
}
}
+654
View File
@@ -0,0 +1,654 @@
//! The on-disk tile cache.
//!
//! Layout: `<root>/<source>/<z>/<x>/<y>.tile` (`<source>`: [`super::TileSource::cache_id`]), 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. `<root>` 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<String>,
pub last_modified: Option<String>,
}
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`, and whether it may still be
/// stored (`no-store` says no). The 304's headers update the stored ones (RFC 9111 §4.3.4): its
/// freshness when it gives one (`Cache-Control` max-age / no-cache, or `Expires`), else the
/// stored response's lifetime again, from now; the validators it sent, else the old ones.
pub fn revalidated<'a>(&self, now: i64, header: impl Fn(&str) -> Option<&'a str>) -> (TileMeta, bool) {
let (fresh, store) = TileMeta::from_response(now, &header);
let gives_freshness = header("expires").is_some()
|| directives(header("cache-control").unwrap_or_default()).any(|(name, _)| name == "max-age" || name == "no-cache");
let expires =
if gives_freshness { fresh.expires } else { now.saturating_add(self.expires.saturating_sub(self.fetched).clamp(0, MAX_FRESH_SECS)) };
let meta = TileMeta {
fetched: now,
expires,
etag: fresh.etag.or_else(|| self.etag.clone()),
last_modified: fresh.last_modified.or_else(|| self.last_modified.clone()),
};
(meta, store)
}
/// 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<i64> = None;
let mut no_cache = false;
for (name, value) in directives(cache_control.unwrap_or_default()) {
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::<u64>().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)
}
/// The directives of a `Cache-Control` value: each name (lower-cased) and its value, if any.
fn directives(cache_control: &str) -> impl Iterator<Item = (String, Option<String>)> + '_ {
cache_control.split(',').map(|d| {
let d = d.trim().to_ascii_lowercase();
match d.split_once('=') {
Some((n, v)) => (n.trim().to_string(), Some(v.trim().trim_matches('"').to_string())),
None => (d, None),
}
})
}
/// 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<u8>,
}
/// 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<Option<u64>>,
}
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<PathBuf>, source_id: &str, cap: u64) -> Result<TileCache, MapError> {
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<CachedTile> {
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), only while it still holds
/// `validated`, the bytes the 304 was about. `false` when the tile is no longer cached, or another
/// writer replaced it meanwhile (a 304 says nothing about that one).
pub fn refresh(&self, key: TileKey, meta: &TileMeta, validated: &[u8]) -> Result<bool, MapError> {
let Some(tile) = self.read(key) else { return Ok(false) };
if tile.bytes != validated {
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<CachedTile> {
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<u64, MapError> {
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,
}
/// A name LightCraft gives a tile: `<y>.tile` (digits only before it).
fn owned_tile(name: &str) -> bool {
name.strip_suffix(".tile").is_some_and(digits)
}
/// A name LightCraft gives a tile being written ([`write_entry`]): `<y>.tile.<pid>-<seq>.part`.
fn owned_part(name: &str) -> bool {
name.strip_suffix(".part")
.and_then(|n| n.split_once(".tile."))
.is_some_and(|(y, rest)| digits(y) && rest.split_once('-').is_some_and(|(pid, seq)| digits(pid) && digits(seq)))
}
fn digits(s: &str) -> bool {
!s.is_empty() && s.len() <= 20 && s.bytes().all(|b| b.is_ascii_digit())
}
/// Every tile under `root` at `<source>/<z>/<x>/<y>.tile` (sources with valid ids only; no
/// symlinks followed; names LightCraft doesn't give left alone, so a cache folder pointed at a
/// folder that holds other files loses none of them). Stale `.part` files of LightCraft's met on
/// the way are deleted when `sweep`.
fn walk(root: &Path, sweep: bool) -> Vec<Entry> {
let now = crate::map::now_secs();
let mut out = Vec::new();
let mut seen = 0usize;
let dirs = |p: &Path| -> Vec<PathBuf> {
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 owned_part(&name) {
if sweep && now.saturating_sub(used) > STALE_PART_SECS {
let _ = fs::remove_file(e.path());
}
} else if owned_tile(&name) {
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<CacheInfo, MapError> {
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<()> {
// the same folders as `walk`: <source>/<z>/<x> with numeric z and x
let numeric_dir = |e: &fs::DirEntry| e.file_type().is_ok_and(|t| t.is_dir()) && e.file_name().to_str().is_some_and(digits);
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(numeric_dir) {
for x in fs::read_dir(z.path())?.filter_map(Result::ok).filter(numeric_dir) {
for f in fs::read_dir(x.path())?.filter_map(Result::ok) {
if owned_part(&f.file_name().to_string_lossy()) && 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 freshness headers: the stored policy again (max-age=60), same validators
let (r, store) = m.revalidated(500, headers(&[]));
assert_eq!((r.fetched, r.expires, r.etag.as_deref(), store), (500, 560, Some("\"abc\""), true));
let (r, _) = m.revalidated(500, headers(&[("Cache-Control", "public")]));
assert_eq!(r.expires, 560, "a Cache-Control without a lifetime keeps the stored one");
let (r, _) = m.revalidated(500, headers(&[("Cache-Control", "x-max-age=10, x-no-cache")]));
assert_eq!(r.expires, 560, "only the directives themselves give a lifetime, not names containing them");
let (r, _) = m.revalidated(500, headers(&[("ETag", "\"new\""), ("Cache-Control", "max-age=10")]));
assert_eq!((r.expires, r.etag.as_deref()), (510, Some("\"new\"")));
let (r, _) = m.revalidated(500, headers(&[("Cache-Control", "no-cache")]));
assert_eq!(r.expires, 500, "no-cache: revalidated every time");
// no-store in the 304: it may not be stored any more
assert!(!m.revalidated(500, headers(&[("Cache-Control", "no-store")])).1);
// 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.clone() };
assert!(c.refresh(k, &newer, b"png bytes").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, b"png bytes").unwrap(), "nothing to refresh");
// another writer replaced it while the 304 was on its way: that one is left as it is
c.write(k, &meta, b"other bytes").unwrap();
assert!(!c.refresh(k, &newer, b"png bytes").unwrap(), "not the validated tile");
assert_eq!(c.read(k).unwrap(), CachedTile { meta: meta.clone(), bytes: b"other bytes".to_vec() });
// 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();
// inside a source's folders, but names LightCraft never gives
fs::write(root.join("osm/2/1/notes.tile"), b"not ours").unwrap();
fs::write(root.join("osm/2/1/backup.part"), b"not ours").unwrap();
fs::create_dir_all(root.join("osm/downloads/pending")).unwrap();
fs::write(root.join("osm/downloads/pending/download.part"), b"not ours").unwrap();
let gone = clear(&root).unwrap();
assert_eq!(gone.tiles, 2);
assert_eq!(info(&root), CacheInfo::default());
assert!(!root.join("custom-1").exists() && !root.join("osm/2/1/1.tile.1-1.part").exists(), "ours are gone");
assert!(root.join("notes.txt").exists() && root.join("Not An Id/1/1/1.tile").exists());
for theirs in ["osm/2/1/notes.tile", "osm/2/1/backup.part", "osm/downloads/pending/download.part"] {
assert!(root.join(theirs).exists(), "{theirs} kept");
}
assert_eq!(clear(&root.join("missing")).unwrap(), CacheInfo::default());
let _ = fs::remove_dir_all(&root);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Photo pins and their clusters.
//!
//! A map view projects each photo with a GPS position once ([`MapPoint::new`], when the set of
//! photos changes) and then, every frame, groups the points on screen into [`Cluster`]s with
//! [`cluster`]: the world (at the view's zoom) is cut into square cells of `cell` screen pixels and
//! the points in one cell become one cluster, drawn at their mean position. The cells are anchored
//! to the world, not the screen, so panning never regroups the pins; zooming in splits clusters as
//! the cells shrink on the ground. The cost is one hash lookup per point on screen (about a
//! millisecond for 50 000 points), so it runs on the UI thread.
use std::collections::HashMap;
use lightcraft_geom::Point;
use super::mercator::{LatLon, Viewport, from_world, to_world, world_size};
/// Default cell edge in screen pixels: pins closer than this merge.
pub const CLUSTER_CELL: f64 = 60.0;
/// A photo's position, projected once.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MapPoint {
/// The photo (a catalog photo id).
pub id: u64,
pub pos: LatLon,
/// Position in the world square as fractions of its edge: x in [0, 1) from −180° eastward,
/// y in [0, 1] from the north edge.
fx: f64,
fy: f64,
}
impl MapPoint {
pub fn new(id: u64, pos: LatLon) -> MapPoint {
let w = to_world(pos, 0.0);
let s = world_size(0.0);
MapPoint { id, pos, fx: (w.x / s).clamp(0.0, 1.0), fy: (w.y / s).clamp(0.0, 1.0) }
}
}
/// Photos drawn as one pin (one photo) or one counted badge (several).
#[derive(Clone, Debug, PartialEq)]
pub struct Cluster {
/// The photos, in the order the points were given.
pub ids: Vec<u64>,
/// Where to draw it, in screen pixels from the viewport's top-left corner.
pub center: Point,
/// The mean position of its photos.
pub pos: LatLon,
}
impl Cluster {
pub fn len(&self) -> usize {
self.ids.len()
}
pub fn is_empty(&self) -> bool {
self.ids.is_empty()
}
}
#[derive(Default)]
struct Cell {
ids: Vec<u64>,
sx: f64,
sy: f64,
}
/// The clusters of `points` in `view`: points in the same world-anchored `cell` (screen pixels,
/// clamped to 1–4096; NaN → [`CLUSTER_CELL`]) merge. Only points within one cell of the view are
/// considered. When the world is narrower than the view (low zoom) a cluster appears once per copy
/// of the world on screen. Sorted top to bottom, then left to right. Empty for an empty view.
pub fn cluster(points: &[MapPoint], view: &Viewport, cell: f64) -> Vec<Cluster> {
let v = Viewport::new(view.center, view.zoom, view.width, view.height);
if v.width <= 0.0 || v.height <= 0.0 {
return Vec::new();
}
let cell = if cell.is_nan() { CLUSTER_CELL } else { cell.clamp(1.0, 4096.0) };
let s = world_size(v.zoom);
let c = to_world(v.center, v.zoom);
let (half_w, half_h) = (v.width / 2.0, v.height / 2.0);
// the world repeats east–west: when it is wider than the view (plus a cell each side), only
// the copy nearest the centre can be on screen
let one_copy = s >= v.width + 2.0 * cell;
let mut cells: HashMap<(i64, i64), Cell> = HashMap::new();
for p in points {
let (wx, wy) = (p.fx * s, p.fy * s);
let sy = half_h + (wy - c.y);
if sy < -cell || sy > v.height + cell {
continue;
}
if one_copy {
let dx = (wx - c.x + s / 2.0).rem_euclid(s) - s / 2.0;
let sx = half_w + dx;
if sx < -cell || sx > v.width + cell {
continue;
}
}
let key = ((wx / cell).floor() as i64, (wy / cell).floor() as i64);
let e = cells.entry(key).or_default();
e.ids.push(p.id);
e.sx += wx;
e.sy += wy;
}
let mut out = Vec::with_capacity(cells.len());
for (_, e) in cells {
let n = e.ids.len().max(1) as f64;
let (mx, my) = (e.sx / n, e.sy / n);
let pos = from_world(Point::new(mx, my), v.zoom);
let y = half_h + (my - c.y);
let dx = (mx - c.x + s / 2.0).rem_euclid(s) - s / 2.0;
let nearest = half_w + dx;
if one_copy {
out.push(Cluster { ids: e.ids, center: Point::new(nearest, y), pos });
continue;
}
// every copy of the world that puts it on screen (at most a few hundred at zoom 0 on a
// 16k-pixel view; usually one to three)
let first = ((-cell - nearest) / s).ceil() as i64;
let last = ((v.width + cell - nearest) / s).floor() as i64;
for k in first..=last {
out.push(Cluster { ids: e.ids.clone(), center: Point::new(nearest + k as f64 * s, y), pos });
}
}
out.sort_by(|a, b| a.center.y.total_cmp(&b.center.y).then(a.center.x.total_cmp(&b.center.x)));
out
}
/// The cluster drawn under screen point `at` within `radius` pixels, nearest first (later
/// clusters are drawn on top, so ties go to them).
pub fn hit(clusters: &[Cluster], at: Point, radius: impl Fn(&Cluster) -> f64) -> Option<usize> {
let mut best: Option<(f64, usize)> = None;
for (i, c) in clusters.iter().enumerate() {
let (dx, dy) = (c.center.x - at.x, c.center.y - at.y);
let d = (dx * dx + dy * dy).sqrt();
if d <= radius(c) && best.is_none_or(|(bd, _)| d <= bd) {
best = Some((d, i));
}
}
best.map(|(_, i)| i)
}
+68
View File
@@ -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<i64> {
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}");
}
}
}
+383
View File
@@ -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<LatLon> {
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<TileKey> {
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<i64>, std::ops::RangeInclusive<i64>, 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<VisibleTile> {
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<TileKey> {
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<I: IntoIterator<Item = (f64, f64)>>(points: I) -> Option<Bounds> {
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)
}
File diff suppressed because it is too large. Load diff
+528
View File
@@ -0,0 +1,528 @@
//! Tile sources: where map tiles come from.
//!
//! The default is OpenStreetMap's standard tile layer, used under the OSMF tile usage policy
//! (<https://operations.osmfoundation.org/policies/tiles/>): 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 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).
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; <https://opentopomap.org/about>).
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)";
/// The ArcGIS Location Platform static basemap tiles service (keyed; read 2026-11-15:
/// <https://developers.arcgis.com/rest/static-basemap-tiles/>). 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)");
/// 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's ArcGIS Streets style (needs the user's ArcGIS API key).
EsriStreet,
/// Esri's ArcGIS Outdoor style, a topographic map (needs the user's ArcGIS API key).
EsriTopo,
/// 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; 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.
pub fn built_in(id: &str) -> Option<TileSource> {
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" | "esri-outdoor" | "esrioutdoor" => TileSource::EsriTopo,
"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::Offline => "offline",
TileSource::Custom { id, .. } => id,
}
}
/// The name of the folder its tiles are cached in: the id, and for a custom source named by
/// the user, that name with a fingerprint of its URL template (`my-tiles-1a2b3c4d`), so the
/// same name pointed at another server never shows the first server's tiles. A derived id
/// (`custom-<hash>`) already is that fingerprint and is kept as it is.
pub fn cache_id(&self) -> String {
match self {
TileSource::Custom { id, url_template, .. } => {
let hash = fnv1a(url_template.as_bytes()) as u32;
if *id == format!("custom-{hash:08x}") {
id.clone()
} else {
// at most MAX_ID characters with the fingerprint
let head: String = id.chars().take(MAX_ID - 9).collect();
format!("{head}-{hash:08x}")
}
}
other => other.id().to_string(),
}
}
/// 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 Streets",
TileSource::EsriTopo => "Esri Outdoor (topographic)",
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_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). 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 | 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<String> {
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 => 20,
TileSource::Custom { max_zoom, .. } => *max_zoom,
}
}
/// 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.
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 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<String> {
let template = self.url_template()?;
if key.z > self.max_zoom() {
return None;
}
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.
pub fn host(&self) -> Option<String> {
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-<hash>`). 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<u8>) -> Result<TileSource, MapError> {
let url_template = url_template.trim();
validate_template(url_template)?;
// OpenStreetMap's tile servers, whatever the id or path: its source, with its credit, zoom and
// usage policy (a custom id must not drop the licence credit or ask past its zoom)
if is_osm_tile_host(url_template) {
if max_zoom.is_some_and(|z| z != OSM_MAX_ZOOM) {
return Err(bad(format!("OpenStreetMap has tiles up to zoom {OSM_MAX_ZOOM}")));
}
if attribution.map(str::trim).is_some_and(|a| !a.is_empty() && !a.contains("OpenStreetMap")) {
return Err(bad("OpenStreetMap's tiles are credited to OpenStreetMap contributors; leave the attribution empty"));
}
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<TileSource, MapError> {
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()),
}
}
}
/// Whether `template` asks OpenStreetMap's own tile servers (`tile.openstreetmap.org`, also its
/// older `a.`/`b.`/`c.` names).
fn is_osm_tile_host(template: &str) -> bool {
let host = template.split_once("://").map_or("", |(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or(""));
let host = host.rsplit_once(':').map_or(host, |(h, port)| if port.bytes().all(|b| b.is_ascii_digit()) { h } else { host });
// (a trailing dot names the same host)
let host = host.trim_end_matches('.').to_ascii_lowercase();
host == "tile.openstreetmap.org" || host.ends_with(".tile.openstreetmap.org")
}
/// 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<String>) -> 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_key());
assert_eq!(s.crop(TileKey::new(3, 1, 1).unwrap()), Crop::Whole);
}
#[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_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);
}
#[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 servers are OpenStreetMap, whatever the id: its credit and zoom stay
assert_eq!(TileSource::custom(None, OSM_TILE_URL, None, None).unwrap(), TileSource::Osm);
for (id, template, attribution) in [
(Some("my-osm"), OSM_TILE_URL, None),
(Some("my-osm"), "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png", Some("© OpenStreetMap contributors")),
(None, "https://TILE.openstreetmap.org/{z}/{x}/{y}.png?x=1", None),
(Some("my-osm"), "https://tile.openstreetmap.org./{z}/{x}/{y}.png", None),
] {
assert_eq!(TileSource::custom(id, template, attribution, None).unwrap(), TileSource::Osm, "{template}");
}
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://[email protected]/{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-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),
(OSM_TILE_URL, Some("Other provider"), None, Some("my-osm")),
(OSM_TILE_URL, None, Some(20), Some("my-osm")),
] {
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 a_named_custom_source_caches_per_server() {
// the same name pointed at another server: another cache folder
let a = TileSource::custom(Some("my-tiles"), "https://a.example/{z}/{x}/{y}.png", Some("© A"), None).unwrap();
let b = TileSource::custom(Some("my-tiles"), "https://b.example/{z}/{x}/{y}.png", Some("© B"), None).unwrap();
assert_eq!(a.id(), b.id());
assert_ne!(a.cache_id(), b.cache_id());
assert!(a.cache_id().starts_with("my-tiles-"), "{}", a.cache_id());
// unchanged: the same folder as ever (also its attribution or zoom changed)
let a2 = TileSource::custom(Some("my-tiles"), "https://a.example/{z}/{x}/{y}.png", Some("© A, again"), Some(12)).unwrap();
assert_eq!(a.cache_id(), a2.cache_id());
// a derived id already is the template's fingerprint; built-in sources keep their id
let derived = TileSource::custom(None, "https://a.example/{z}/{x}/{y}.png", Some("© A"), None).unwrap();
assert_eq!(derived.cache_id(), derived.id());
assert_eq!(TileSource::Osm.cache_id(), "osm");
// a long name still makes a valid folder name
let long = TileSource::custom(Some(&"x".repeat(MAX_ID)), "https://a.example/{z}/{x}/{y}.png", Some("© A"), None).unwrap();
assert!(validate_id(&long.cache_id()).is_ok() && long.cache_id().len() <= MAX_ID, "{}", long.cache_id());
for s in [a, b, derived] {
assert!(validate_id(&s.cache_id()).is_ok(), "{}", s.cache_id());
}
}
#[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::<TileSource>(r#"{"kind": "bing"}"#).is_err());
}
}
+162
View File
@@ -0,0 +1,162 @@
//! Pin clustering: counts per zoom, splitting as the zoom grows, stability under panning, the
//! antimeridian and the poles, and the cost for many photos.
use lightcraft_geom::Point;
use super::cluster::*;
use super::mercator::*;
fn ll(lat: f64, lon: f64) -> LatLon {
LatLon::new(lat, lon).unwrap()
}
fn view(lat: f64, lon: f64, zoom: f64) -> Viewport {
Viewport::new(ll(lat, lon), zoom, 1600.0, 1000.0)
}
/// Three photos in Paris (a few hundred metres apart), two in London, one in New York.
fn places() -> Vec<MapPoint> {
[(48.8584, 2.2945), (48.8606, 2.3376), (48.8530, 2.3499), (51.5007, -0.1246), (51.5081, -0.0759), (40.7484, -73.9857)]
.iter()
.enumerate()
.map(|(i, &(lat, lon))| MapPoint::new(i as u64 + 1, ll(lat, lon)))
.collect()
}
/// The groups, each once (a narrow world shows a cluster once per copy).
fn groups(c: &[Cluster]) -> Vec<Vec<u64>> {
let mut v: Vec<Vec<u64>> = c.iter().map(|c| c.ids.clone()).collect();
v.sort();
v.dedup();
v
}
fn counts(c: &[Cluster]) -> Vec<usize> {
let mut n: Vec<usize> = c.iter().map(Cluster::len).collect();
n.sort();
n
}
#[test]
fn clusters_split_as_the_zoom_grows() {
let pts = places();
// the North Atlantic at zoom 2: Paris and London one cluster or two, New York apart
let c = cluster(&pts, &view(48.0, -35.0, 2.0), CLUSTER_CELL);
assert_eq!(c.iter().map(Cluster::len).sum::<usize>(), 6, "every photo is in exactly one cluster");
assert!(c.len() <= 3, "{:?}", counts(&c));
// zoom 1: the world is narrower than the view, so groups repeat, but each photo is in one group
let g = groups(&cluster(&pts, &view(48.0, -35.0, 1.0), CLUSTER_CELL));
assert_eq!(g.iter().map(Vec::len).sum::<usize>(), 6);
// zoom 6 over Europe: Paris (3) and London (2) apart; New York off screen
let c = cluster(&pts, &view(50.0, 1.0, 6.0), CLUSTER_CELL);
assert_eq!(counts(&c), vec![2, 3]);
let paris = c.iter().find(|c| c.len() == 3).unwrap();
assert_eq!(paris.ids, vec![1, 2, 3], "in the order given");
assert!((paris.pos.lat - 48.857).abs() < 0.01 && (paris.pos.lon - 2.327).abs() < 0.01, "{:?}", paris.pos);
let at = view(50.0, 1.0, 6.0).to_screen(paris.pos);
assert!((at.x - paris.center.x).abs() < 1e-6 && (at.y - paris.center.y).abs() < 1e-6);
// zoom 14 over Paris: three single pins
let c = cluster(&pts, &view(48.857, 2.32, 14.0), CLUSTER_CELL);
assert_eq!(counts(&c), vec![1, 1, 1]);
// whole zooms nest their cells, so the Paris photos never regroup into fewer clusters
let mut last = 0;
for z in 0..=14 {
let n = groups(&cluster(&pts, &view(48.857, 2.32, f64::from(z)), CLUSTER_CELL)).iter().filter(|g| g.iter().any(|i| *i <= 3)).count();
assert!(n >= last && n >= 1, "zoom {z}: {n} < {last}");
last = n;
}
assert_eq!(last, 3);
}
#[test]
fn panning_keeps_the_groups() {
let pts = places();
let a = view(50.0, 1.0, 7.3);
let b = a.panned(37.0, -21.0);
let (ca, cb) = (cluster(&pts, &a, CLUSTER_CELL), cluster(&pts, &b, CLUSTER_CELL));
let ids = |c: &[Cluster]| {
let mut v: Vec<Vec<u64>> = c.iter().map(|c| c.ids.clone()).collect();
v.sort();
v
};
assert_eq!(ids(&ca), ids(&cb));
for x in &ca {
let y = cb.iter().find(|y| y.ids == x.ids).unwrap();
assert!((y.center.x - x.center.x - 37.0).abs() < 1e-6 && (y.center.y - x.center.y + 21.0).abs() < 1e-6);
}
}
#[test]
fn off_screen_points_are_left_out() {
let pts = places();
let c = cluster(&pts, &Viewport::new(ll(0.0, 100.0), 8.0, 800.0, 600.0), CLUSTER_CELL);
assert!(c.is_empty());
assert!(cluster(&pts, &Viewport::new(ll(48.0, 2.0), 5.0, 0.0, 600.0), CLUSTER_CELL).is_empty(), "empty view");
assert!(cluster(&[], &view(0.0, 0.0, 3.0), CLUSTER_CELL).is_empty());
// a hostile cell size doesn't break anything
for cell in [f64::NAN, -5.0, 0.0] {
let c = cluster(&pts, &view(50.0, 1.0, 6.0), cell);
assert_eq!(c.iter().map(Cluster::len).sum::<usize>(), 5, "{cell}");
}
for cell in [f64::INFINITY, 1e12] {
let c = cluster(&pts, &view(50.0, 1.0, 6.0), cell);
assert!(groups(&c).iter().map(Vec::len).sum::<usize>() <= 6 && c.iter().all(|c| c.center.x.is_finite()), "{cell}");
}
}
#[test]
fn antimeridian_and_poles() {
// 179.9° and −179.9° sit side by side across the date line
let pts = vec![
MapPoint::new(1, ll(-17.0, 179.9)),
MapPoint::new(2, ll(-17.0, -179.9)),
MapPoint::new(3, ll(90.0, 0.0)),
MapPoint::new(4, ll(-90.0, 180.0)),
];
let c = cluster(&pts, &view(-17.0, 180.0, 10.0), CLUSTER_CELL);
assert_eq!(counts(&c), vec![1, 1]);
let xs: Vec<f64> = c.iter().map(|c| c.center.x).collect();
assert!(xs.iter().all(|x| (x - 800.0).abs() < 200.0), "both near the centre, not a world apart: {xs:?}");
// poles are drawn at the edge of the map, as finite positions
let c = cluster(&pts, &Viewport::new(ll(0.0, 0.0), 2.0, 1600.0, 1100.0), CLUSTER_CELL);
assert!(c.iter().all(|c| c.center.x.is_finite() && c.center.y.is_finite()));
assert_eq!(groups(&c).iter().map(Vec::len).sum::<usize>(), 4);
}
#[test]
fn a_narrow_world_repeats_its_pins() {
// zoom 0: the world is 256 px wide, the view 1600: each cluster shows once per copy
let pts = vec![MapPoint::new(1, ll(0.0, 0.0))];
let c = cluster(&pts, &Viewport::new(ll(0.0, 0.0), 0.0, 1600.0, 400.0), CLUSTER_CELL);
assert!(c.len() >= 6, "{}", c.len());
assert!(c.iter().all(|c| c.ids == vec![1]));
assert!(c.windows(2).all(|w| (w[1].center.x - w[0].center.x - 256.0).abs() < 1e-6));
}
#[test]
fn hit_finds_the_nearest_cluster_under_the_pointer() {
let pts = places();
let c = cluster(&pts, &view(50.0, 1.0, 6.0), CLUSTER_CELL);
let paris = c.iter().position(|c| c.len() == 3).unwrap();
let p = c[paris].center;
assert_eq!(hit(&c, Point::new(p.x + 3.0, p.y - 2.0), |_| 12.0), Some(paris));
assert_eq!(hit(&c, Point::new(p.x + 30.0, p.y), |_| 12.0), None);
}
#[test]
fn many_photos_cluster_quickly() {
// 50 000 photos spread over Europe, deterministic
let mut seed = 12345u64;
let mut rnd = || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 11) as f64 / (1u64 << 53) as f64
};
let pts: Vec<MapPoint> = (0..50_000).map(|i| MapPoint::new(i, ll(36.0 + rnd() * 24.0, -10.0 + rnd() * 40.0))).collect();
let v = view(48.0, 10.0, 5.0);
let t = std::time::Instant::now();
let c = cluster(&pts, &v, CLUSTER_CELL);
let ms = t.elapsed().as_secs_f64() * 1e3;
eprintln!("cluster: 50 000 points → {} clusters in {ms:.2} ms", c.len());
assert_eq!(c.iter().map(Cluster::len).sum::<usize>(), 50_000);
assert!(c.len() < 600, "{}", c.len());
}
+229
View File
@@ -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<u32> = 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());
}
+864
View File
@@ -0,0 +1,864 @@
//! 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<dyn Fn(&str, &[(&'static str, String)]) -> Result<HttpResponse, TransportError> + Send + Sync>;
struct Fake {
log: Mutex<Vec<(String, Vec<(&'static str, String)>)>>,
active: AtomicUsize,
max_active: AtomicUsize,
handler: Handler,
}
impl Fake {
fn new(handler: impl Fn(&str, &[(&'static str, String)]) -> Result<HttpResponse, TransportError> + Send + Sync + 'static) -> Arc<Fake> {
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<String> {
self.log.lock().unwrap().iter().map(|(u, _)| u.clone()).collect()
}
fn keys(&self) -> Vec<TileKey> {
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<HttpResponse, TransportError> {
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<u32> = 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<u8> {
use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png};
let data: Vec<u8> = (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<TileKey> = view.tile_keys(19, 1).into_iter().collect();
wait_until("all tiles", 20, || svc.is_idle() && fake.urls().len() >= want.len());
let got: Vec<TileKey> = 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<TileKey> = 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<TileKey> =
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<TileKey> = (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::<HashSet<_>>(), [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<TileKey> = 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<TileKey> = 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::<HashSet<_>>().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<TileKey> = (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());
}
/// A `Retry-After` still running is not shortened by another request failing without one.
#[test]
fn a_later_failure_does_not_shorten_a_retry_after() {
let n = AtomicUsize::new(0);
let fake = Fake::new(move |_, _| {
if n.fetch_add(1, Ordering::SeqCst) == 0 {
// answer only once the second request is on the wire, else the backoff stops it being sent
let end = Instant::now() + Duration::from_secs(5);
while n.load(Ordering::SeqCst) < 2 && Instant::now() < end {
std::thread::sleep(Duration::from_millis(5));
}
Ok(HttpResponse { status: 503, headers: vec![("Retry-After".into(), "120".into())], body: vec![] })
} else {
std::thread::sleep(Duration::from_millis(300));
Ok(HttpResponse { status: 503, headers: vec![], body: vec![] })
}
});
let svc = TileService::with_transport(source(), None, Some(fake.clone()));
svc.want(&[TileKey::new(1, 0, 0).unwrap(), TileKey::new(1, 1, 0).unwrap()]);
wait_until("both answers", 10, || svc.stats().errors == 2);
assert!(svc.stats().backoff_ms > 100_000, "{:?}", svc.stats());
}
#[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_200_that_forbids_storing_takes_the_older_copy_off_the_disk() {
let root = tmp("fetch-no-store");
let key = TileKey::new(6, 12, 20).unwrap();
let now = crate::map::now_secs();
let old = TileMeta { fetched: now - 900_000, expires: now - 10, etag: Some("\"v0\"".into()), last_modified: None };
TileCache::new(&root, "test", 100 << 20).unwrap().write(key, &old, &png(256, 256)).unwrap();
let fake = Fake::new(|_, _| Ok(ok_png("no-store")));
let svc = TileService::with_transport(source(), Some(TileCache::new(&root, "test", 100 << 20).unwrap()), Some(fake.clone()));
svc.want(&[key]);
wait_until("the fetch", 10, || svc.is_idle() && fake.urls().len() == 1);
assert!(TileCache::new(&root, "test", 100 << 20).unwrap().read(key).is_none(), "no-store: the older copy is gone");
assert!(svc.get(key).is_some(), "the new tile is shown");
drop(svc);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_304_that_forbids_storing_takes_the_tile_off_the_disk() {
let root = tmp("revalidate-no-store");
let key = TileKey::new(6, 11, 20).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(key, &old, &png(256, 256)).unwrap();
let fake = Fake::new(|_, _| Ok(HttpResponse { status: 304, headers: vec![("Cache-Control".into(), "no-store".into())], body: vec![] }));
let svc = TileService::with_transport(source(), Some(TileCache::new(&root, "test", 100 << 20).unwrap()), Some(fake.clone()));
svc.want(&[key]);
wait_until("the refresh", 10, || svc.is_idle() && svc.stats().not_modified == 1);
assert!(TileCache::new(&root, "test", 100 << 20).unwrap().read(key).is_none(), "no-store: not kept on disk");
assert!(svc.get(key).is_some(), "the copy in memory is still shown");
assert!(!svc.poll().iter().any(|e| matches!(e, TileEvent::Failed { .. })));
drop(svc);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn repeated_cache_control_lines_are_read_together() {
let lines = [("cache-control", "max-age=3600"), ("cache-control", "no-store"), ("etag", "\"a\""), ("etag", "\"b\"")];
let kept = super::service::kept_headers(|h| lines.iter().filter(|(k, _)| *k == h).map(|(_, v)| *v).collect());
assert!(kept.contains(&("cache-control".into(), "max-age=3600, no-store".into())), "{kept:?}");
assert!(kept.contains(&("etag".into(), "\"a\"".into())), "the others: their first value");
assert!(!kept.iter().any(|(k, _)| k == "expires"));
}
#[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"<html>captive portal</html>".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<TileKey> = (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<TileKey> =
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!(!inert.can_load() && !svc.can_load());
assert!(inert.is_idle(), "a service that can't load leaves nothing pending");
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..5 {
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(),
// throttled, with an error page far past the tile cap
3 => s.write_all(b"HTTP/1.1 429 Too Many Requests\r\nRetry-After: 120\r\nContent-Length: 30000000\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!(
matches!(t.get(&format!("{base}/1/0/1.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap_err(), TransportError::TooLarge(m) if m.contains("larger"))
);
// the throttling reaches the service, though the error page is over the cap
let r = t.get(&format!("{base}/1/1/0.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap();
assert_eq!((r.status, r.header("retry-after"), r.body.len()), (429, Some("120"), 0));
assert!(
matches!(t.get(&format!("{base}/1/1/1.png"), &ua, MAX_TILE_BYTES, &cancel).unwrap_err(), TransportError::TooLarge(m) if m.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<TileKey> = (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<TileKey> = (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!(matches!(&err, TransportError::TooLarge(m) if m.contains("larger")), "{err}");
server.join().unwrap();
}
/// A server that sends a byte now and then never trips the stall timeout, but the whole body has
/// a deadline: the network slot is freed.
#[test]
fn a_trickling_tile_body_gives_up_at_its_deadline() {
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: 100000\r\n\r\n");
for _ in 0..200 {
if s.write_all(b"x").and_then(|()| s.flush()).is_err() {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
});
let t = HttpTransport { body_timeout: Duration::from_millis(600), ..HttpTransport::default() };
let ua = vec![("User-Agent", USER_AGENT.to_string())];
let start = std::time::Instant::now();
let err = t.get(&url, &ua, MAX_TILE_BYTES, &AtomicBool::new(false)).unwrap_err();
assert!(matches!(&err, TransportError::Failed(m) if m.contains("not received within")), "{err}");
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
server.join().unwrap();
}
const KEY: &str = "AAPK0123456789abcdef_TEST-key.x";
fn esri_service(fake: Arc<Fake>, cache: Option<TileCache>) -> 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}").into());
}
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<TileKey> = [(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<String> = 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"<html><body>Service unavailable</body></html>",
br#"{"copyrightText": "<script>alert(1)</script>"}"#,
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"<html>nope</html>".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");
}
/// When no worker thread starts, nothing is queued: the service is idle, says it can't load, and
/// leaves no "Loading map tiles" row behind (no one would ever finish it).
#[test]
fn a_service_whose_threads_never_start_queues_nothing() {
let fake = Fake::new(|_, _| Ok(ok_png("max-age=60")));
let activity = crate::activity::Activity::default();
let refuse: &Spawn = &|_, _| Err(std::io::Error::other("no threads"));
let svc = TileService::with_spawner(source(), Some(TileCache::new(tmp("nothreads"), "test", 1 << 20).unwrap()), Some(fake.clone()), refuse)
.with_activity(Some(activity.clone()));
svc.show(&paris());
assert!(!svc.can_load());
assert!(svc.is_idle(), "nothing left waiting for a worker");
assert!(activity.list().is_empty(), "no loading row that never ends");
assert!(fake.urls().is_empty());
}
/// A tile the transport refuses as too large is refused like a garbage one (not asked for again
/// for a while); the host isn't backed off, so the other tiles still load.
#[test]
fn an_oversized_tile_is_refused_without_backing_off_the_host() {
let fake = Fake::new(|url, _| {
if url.ends_with("/4/0/4.png") {
return Err(TransportError::TooLarge(format!("tile larger than {MAX_TILE_BYTES} bytes")));
}
Ok(ok_png("max-age=60"))
});
let svc = TileService::with_transport(source(), None, Some(fake.clone()));
let keys: Vec<TileKey> = (0..4).map(|x| TileKey::new(4, x, 4).unwrap()).collect();
svc.want(&keys);
wait_until("every tile answered", 10, || svc.is_idle() && fake.urls().len() >= 4);
let s = svc.stats();
assert_eq!(s.backoff_ms, 0, "{s:?}");
assert!(keys[1..].iter().all(|k| svc.get(*k).is_some()));
assert!(svc.poll().iter().any(|e| matches!(e, TileEvent::Failed { key, error } if *key == keys[0] && error.contains("larger"))));
svc.want(&keys);
std::thread::sleep(Duration::from_millis(200));
assert_eq!(fake.keys().iter().filter(|k| **k == keys[0]).count(), 1, "not asked for again: {:?}", fake.urls());
}
/// A request already on the wire when the host starts failing doesn't end the backoff when it
/// succeeds: only a request let through after the failure (the probe) does.
#[test]
fn an_earlier_request_does_not_end_a_newer_backoff() {
let slow = TileKey::new(4, 0, 4).unwrap();
let started = Arc::new(AtomicBool::new(false));
let seen = Arc::clone(&started);
let fake = Fake::new(move |url, _| {
if url.ends_with("/4/0/4.png") {
seen.store(true, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(300));
return Ok(ok_png("max-age=60"));
}
// fail only once the slow request is on the wire
let end = Instant::now() + Duration::from_secs(5);
while !seen.load(Ordering::SeqCst) && Instant::now() < end {
std::thread::sleep(Duration::from_millis(2));
}
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(&[slow, TileKey::new(4, 1, 4).unwrap()]);
wait_until("the slow tile", 10, || svc.get(slow).is_some());
assert!(started.load(Ordering::SeqCst));
std::thread::sleep(Duration::from_millis(300));
// the failed tile waits out its Retry-After: not asked for again
assert_eq!(fake.urls().len(), 2, "{:?}", fake.urls());
assert!(svc.stats().backoff_ms > 100_000, "{:?}", svc.stats());
}
/// Decoded tiles are bounded by bytes, not only by count: a server sending 1024 px tiles (kept
/// whole) gets [`MEMORY_BYTES`] of them, not 256 × 4 MB.
#[test]
fn large_tiles_are_kept_within_the_memory_budget() {
let big = png(1024, 1024);
let fake =
Fake::new(move |_, _| Ok(HttpResponse { status: 200, headers: vec![("Cache-Control".into(), "max-age=60".into())], body: big.clone() }));
let svc = TileService::with_transport(source(), None, Some(fake.clone()));
let keys: Vec<TileKey> = (0..24).map(|x| TileKey::new(5, x, 4).unwrap()).collect();
svc.want(&keys);
wait_until("every tile", 30, || svc.is_idle() && fake.urls().len() >= keys.len());
let in_memory = svc.stats().in_memory;
assert!(in_memory <= MEMORY_BYTES / (1024 * 1024 * 4), "{in_memory} tiles of 4 MB");
assert!(in_memory > 0);
// the arrivals waiting for the UI's first poll are bounded too, not every image decoded
let waiting: usize = svc.poll().iter().filter_map(|e| if let TileEvent::Ready { image, .. } = e { Some(image.rgba.len()) } else { None }).sum();
assert!(waiting <= MEMORY_BYTES + 1024 * 1024 * 4, "{waiting} bytes waiting");
}
/// A view wanting more than the memory holds: the tiles evicted are looked for again when the same
/// view is asked for, but at most once a second, so the service doesn't reload them every frame.
#[test]
fn evicted_tiles_of_the_view_are_loaded_again_but_not_every_frame() {
let big = png(1024, 1024);
let fake =
Fake::new(move |_, _| Ok(HttpResponse { status: 200, headers: vec![("Cache-Control".into(), "max-age=60".into())], body: big.clone() }));
let svc = TileService::with_transport(source(), None, Some(fake.clone()));
let keys: Vec<TileKey> = (0..24).map(|x| TileKey::new(5, x, 4).unwrap()).collect();
svc.want(&keys);
wait_until("every tile", 30, || svc.is_idle() && fake.urls().len() >= keys.len());
assert!(svc.stats().in_memory < keys.len(), "some were evicted");
let first = fake.urls().len();
// the same view asked for frame after frame: what is missing is asked for anew
wait_until("an evicted tile again", 30, || {
svc.want(&keys);
fake.urls().len() > first
});
// but not every frame: 50 frames ask for one batch per second they took, at most
wait_until("idle", 30, || svc.is_idle());
let second = fake.urls().len();
let started = Instant::now();
for _ in 0..50 {
svc.want(&keys);
std::thread::sleep(std::time::Duration::from_millis(10));
}
let batches = started.elapsed().as_secs() as usize + 1;
wait_until("idle", 30, || svc.is_idle());
let asked = fake.urls().len() - second;
assert!(asked <= keys.len() * batches, "{asked} requests in {batches} s of frames");
}
/// Offline (cache only), a tile that isn't on disk is looked up once, not again every second.
#[test]
fn an_offline_miss_is_not_looked_up_again_and_again() {
let dir = tmp("offline-miss");
let cache = TileCache::new(dir.clone(), &source().cache_id(), 1 << 20).unwrap();
let svc = TileService::with_transport(source(), Some(cache), None);
let keys = [TileKey::new(3, 1, 1).unwrap()];
svc.want(&keys);
wait_until("the lookup", 10, || svc.is_idle() && svc.stats().disk_reads == 1);
for _ in 0..15 {
svc.want(&keys);
std::thread::sleep(Duration::from_millis(100));
}
wait_until("idle", 10, || svc.is_idle());
assert_eq!(svc.stats().disk_reads, 1, "no second lookup");
let _ = std::fs::remove_dir_all(dir);
}
+220
View File
@@ -0,0 +1,220 @@
//! Tests of track drawing: simplification error and end points, antimeridian cuts, poles, hostile
//! points, clipping, and the cost of a big track.
use lightcraft_geom::Point;
use super::mercator::{LatLon, Viewport};
use super::track::{TOLERANCE_PX, TrackShape};
/// A wiggly walk of `n` points around (46°, 7°) (a deterministic pseudo-random walk).
fn walk(n: usize) -> Vec<(f64, f64)> {
let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 10_000) as f64 / 10_000.0 - 0.5
};
let (mut lat, mut lon) = (46.0, 7.0);
let mut heading: f64 = 0.0;
(0..n)
.map(|_| {
heading += rnd() * 0.8;
lat += heading.cos() * 0.0002;
lon += heading.sin() * 0.0003;
(lat, lon)
})
.collect()
}
fn dist_to_polyline(p: Point, lines: &[Vec<Point>]) -> f64 {
let mut best = f64::INFINITY;
for l in lines {
if let [only] = l.as_slice() {
best = best.min(((p.x - only.x).powi(2) + (p.y - only.y).powi(2)).sqrt());
}
for w in l.windows(2) {
let (a, b) = (w[0], w[1]);
let (dx, dy) = (b.x - a.x, b.y - a.y);
let len2 = dx * dx + dy * dy;
let t = if len2 > 0.0 { (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };
best = best.min(((a.x + t * dx - p.x).powi(2) + (a.y + t * dy - p.y).powi(2)).sqrt());
}
}
best
}
#[test]
fn simplification_keeps_the_ends_and_stays_within_the_tolerance() {
let pts = walk(5000);
let shape = TrackShape::new([pts.clone()]);
assert_eq!(shape.points(), 5000);
assert_eq!(shape.pieces(), 1);
let b = shape.bounds().unwrap();
let mut previous = 0;
let mut checked = 0;
for z in [6u8, 10, 12, 13, 16] {
let level = shape.level(z);
// more points the further in, never more than the track has
assert!(level.points <= 5000 && level.points >= previous, "zoom {z}: {}", level.points);
previous = level.points;
// a view at exactly that zoom holding the whole track (16 384 px at most)
let vp = Viewport::new(b.center(), f64::from(z), 16_000.0, 16_000.0);
let lines = level.screen_lines(&vp, 10.0);
assert!(!lines.is_empty());
let first = vp.to_screen(LatLon::new(pts[0].0, pts[0].1).unwrap());
let last = vp.to_screen(LatLon::new(pts[4999].0, pts[4999].1).unwrap());
if (0.0..16_000.0).contains(&first.x) && (0.0..16_000.0).contains(&first.y) && (0.0..16_000.0).contains(&last.x) {
let start = lines[0][0];
let end = *lines.last().unwrap().last().unwrap();
assert!((start.x - first.x).abs() < 1e-6 && (start.y - first.y).abs() < 1e-6, "zoom {z}: the first point is kept");
assert!((end.x - last.x).abs() < 1e-6 && (end.y - last.y).abs() < 1e-6, "zoom {z}: the last point is kept");
assert_eq!(lines.len(), 1, "zoom {z}: one unbroken line");
// no point of the track is further than the tolerance from what is drawn
let worst = pts.iter().map(|(la, lo)| dist_to_polyline(vp.to_screen(LatLon::new(*la, *lo).unwrap()), &lines)).fold(0.0, f64::max);
assert!(worst <= TOLERANCE_PX + 1e-6, "zoom {z}: {worst} px");
checked += 1;
}
}
assert!(checked >= 3, "{checked}");
assert!(shape.level(6).points < 200, "zoomed out the walk is a few points: {}", shape.level(6).points);
assert!(shape.level(18).points > 2000, "zoomed in most points stay: {}", shape.level(18).points);
}
#[test]
fn segments_are_not_joined() {
let a = vec![(46.0, 7.0), (46.01, 7.01)];
let b = vec![(46.02, 7.02), (46.03, 7.03)];
let shape = TrackShape::new([a, b]);
assert_eq!(shape.pieces(), 2);
let vp = Viewport::new(shape.bounds().unwrap().center(), 13.0, 2000.0, 2000.0);
let lines = shape.level(13).screen_lines(&vp, 0.0);
assert_eq!(lines.len(), 2, "{lines:?}");
}
#[test]
fn a_line_across_the_antimeridian_is_cut_and_drawn_the_short_way() {
let shape = TrackShape::new([vec![(-17.0, 179.0), (-17.2, -179.0), (-17.4, -178.0)]]);
assert_eq!(shape.pieces(), 2, "cut at ±180°");
let b = shape.bounds().unwrap();
assert!(b.crosses_antimeridian() && b.lon_span() < 3.5, "{b:?}");
// seen from the antimeridian: one unbroken line through the middle (the cut ends meet:
// ±180° is the same meridian), nothing drawn across the world
let vp = Viewport::new(LatLon { lat: -17.2, lon: 180.0 }, 7.0, 1200.0, 800.0);
let lines = shape.level(7).screen_lines(&vp, 0.0);
assert_eq!(lines.len(), 1, "{lines:?}");
let l = &lines[0];
assert!(l.iter().any(|p| (p.x - 600.0).abs() < 1e-6), "through the centre column: {l:?}");
assert!(l.windows(2).all(|w| w[1].x > w[0].x && w[1].x - w[0].x < 200.0), "eastward in short steps: {l:?}");
for p in l {
assert!(p.x > 0.0 && p.x < 1200.0 && p.y > 0.0 && p.y < 800.0, "{p:?} on screen");
}
// and seen from far away (the other side of the world) it is still two short lines
let far = Viewport::new(LatLon { lat: 0.0, lon: 0.0 }, 1.0, 1200.0, 800.0);
for l in shape.level(1).screen_lines(&far, 0.0) {
let span = l.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max) - l.iter().map(|p| p.x).fold(f64::INFINITY, f64::min);
assert!(span < 20.0, "{l:?}");
}
}
/// A view showing two copies of the world draws the track on both: at zoom 1 (a 512-pixel world) a
/// 400-pixel view centred at 100° E shows 0° on the left (the copy west of the centre) and −170°
/// (190° E) on the right.
#[test]
fn a_track_is_drawn_on_every_copy_of_the_world_in_view() {
let shape = TrackShape::new([vec![(0.0, -170.0), (0.0, 0.0)]]);
let vp = Viewport::new(LatLon { lat: 0.0, lon: 100.0 }, 1.0, 400.0, 300.0);
let lines = shape.level(1).screen_lines(&vp, 0.0);
let at = |lon: f64| ((lon + 180.0) / 360.0 - (100.0 + 180.0) / 360.0) * 512.0 + 200.0;
// the copy west of the centre: the part ending at 0° (x ≈ 57.8)
let zero = at(0.0);
assert!(lines.iter().flatten().any(|p| (p.x - zero).abs() < 1e-6 && (p.y - 150.0).abs() < 1e-6), "0° at x {zero}: {lines:?}");
// the copy east of it: from 190° E (x ≈ 328) to the view's edge
let east = at(190.0);
assert!(lines.iter().flatten().any(|p| (p.x - east).abs() < 1e-6), "190° E at x {east}: {lines:?}");
assert_eq!(lines.len(), 2, "two lines, never joined across the world: {lines:?}");
for p in lines.iter().flatten() {
assert!((0.0..=400.0).contains(&p.x), "{p:?} clipped to the view");
}
}
#[test]
fn poles_nan_and_degenerate_tracks_never_crash() {
// points at and beyond the Mercator edge are drawn on it
let shape = TrackShape::new([vec![(90.0, 0.0), (89.99, 10.0), (-90.0, 20.0)]]);
let vp = Viewport::new(LatLon { lat: 0.0, lon: 10.0 }, 1.0, 600.0, 600.0);
for l in shape.level(1).screen_lines(&vp, 50.0) {
assert!(l.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{l:?}");
}
// invalid points are skipped, the line goes on
let shape = TrackShape::new([vec![(f64::NAN, 1.0), (1.0, f64::INFINITY), (1.0, 1.0), (95.0, 1.0), (1.1, 1.1), (1.0, 200.0)]]);
assert_eq!(shape.points(), 2);
assert_eq!(shape.pieces(), 1);
// nothing at all
let empty = TrackShape::new(Vec::<Vec<(f64, f64)>>::new());
assert!(empty.bounds().is_none());
assert!(empty.level(10).screen_lines(&vp, 0.0).is_empty());
let none_valid = TrackShape::new([vec![(f64::NAN, f64::NAN)]]);
assert_eq!((none_valid.points(), none_valid.pieces()), (0, 0));
// one point: a dot where it is
let one = TrackShape::new([vec![(10.0, 20.0)]]);
let vp = Viewport::new(LatLon { lat: 10.0, lon: 20.0 }, 12.0, 400.0, 300.0);
let lines = one.level(12).screen_lines(&vp, 0.0);
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].len(), 1);
assert!((lines[0][0].x - 200.0).abs() < 1e-6 && (lines[0][0].y - 150.0).abs() < 1e-6);
// a zero-size view, NaN in the view, an absurd zoom and margin
let bad = Viewport { center: LatLon { lat: f64::NAN, lon: f64::NAN }, zoom: f64::NAN, width: 0.0, height: 0.0 };
assert!(one.level(255).screen_lines(&bad, f64::NAN).is_empty());
let bad = Viewport { center: LatLon { lat: f64::NAN, lon: 1e300 }, zoom: 1e9, width: 1e9, height: f64::INFINITY };
let _ = one.level(30).screen_lines(&bad, f64::INFINITY);
}
#[test]
fn a_logger_lying_still_costs_nothing_and_draws_little() {
let mut pts = vec![(46.0, 7.0); 200_000];
pts.push((46.001, 7.001));
let t0 = std::time::Instant::now();
let shape = TrackShape::new([pts]);
let level = shape.level(18);
assert!(level.points <= 3, "{}", level.points);
assert!(t0.elapsed().as_secs_f64() < 5.0, "{:?}", t0.elapsed());
}
#[test]
fn deep_zoom_lines_are_clipped_to_the_view() {
let pts: Vec<(f64, f64)> = (0..2000).map(|i| (46.0 + f64::from(i) * 0.001, 7.0 + f64::from(i) * 0.0013)).collect();
let shape = TrackShape::new([pts]);
let vp = Viewport::new(LatLon { lat: 46.5, lon: 7.65 }, 19.0, 800.0, 600.0);
let lines = shape.level(19).screen_lines(&vp, 8.0);
assert!(!lines.is_empty(), "the track passes through the view");
let n: usize = lines.iter().map(Vec::len).sum();
assert!(n < 50, "only what is on screen: {n}");
for p in lines.iter().flatten() {
assert!(p.x >= -8.0 - 1e-6 && p.x <= 808.0 + 1e-6 && p.y >= -8.0 - 1e-6 && p.y <= 608.0 + 1e-6, "{p:?}");
}
}
/// The cost of a big track (2 million points): `cargo test -p lightcraft-engine --lib --release big_track
/// -- --ignored --nocapture`.
#[test]
#[ignore]
fn big_track_cost() {
let pts = walk(2_000_000);
let t0 = std::time::Instant::now();
let shape = TrackShape::new([pts]);
let build = t0.elapsed();
let b = shape.bounds().unwrap();
for z in [4u8, 8, 12, 16, 19] {
let t1 = std::time::Instant::now();
let level = shape.level(z);
let lv = t1.elapsed();
let vp = Viewport::new(b.center(), f64::from(z), 1600.0, 1000.0);
let t2 = std::time::Instant::now();
let lines = level.screen_lines(&vp, 8.0);
let draw = t2.elapsed();
let n: usize = lines.iter().map(Vec::len).sum();
println!("zoom {z}: level {lv:?} ({} points kept), frame {draw:?} ({n} points on screen)", level.points);
}
println!("build (project, cut, rank, bounds): {build:?}");
}
+324
View File
@@ -0,0 +1,324 @@
//! GPS track logs drawn on the map: polylines projected once, simplified per zoom, clipped to the
//! view.
//!
//! - [`TrackShape::new`] takes a track's lines (one per continuous logging span; a line is never
//! joined to the next) as `(latitude, longitude)` points. Invalid points (NaN, infinities, out of
//! range) are skipped. Each line is projected once into the Web Mercator square (fractions of its
//! edge; latitudes clamped to ±85.05°, so points at the poles sit on the map's edge) and cut where
//! it crosses the antimeridian: a step of more than 180° of longitude between two points is taken
//! the short way round, the line ends at ±180° and goes on from the other edge.
//! - Simplification is Douglas–Peucker, computed once for every tolerance: each point gets the
//! *rank* at which it stops being needed (its distance from the chord of its range, capped by the
//! rank of the point that split the range before it). Keeping the points ranked above a
//! tolerance is then exactly the Douglas–Peucker result at that tolerance, so [`TrackShape::level`]
//! is one pass over the points per zoom, the ends of every line are always kept, and no dropped
//! point lies further than [`TOLERANCE_PX`] screen pixels from the line drawn. A long run of
//! points that don't move (a logger lying still) is dropped in one step, and the work is capped
//! (past the cap the rest of a line is kept whole), so no input makes it quadratic.
//! - A [`Level`] holds the kept points in chunks of [`CHUNK`] points with their bounding boxes, so
//! [`Level::screen_lines`] skips what is off screen and clips the rest to the view (no point is
//! handed to the painter thousands of pixels away).
use lightcraft_geom::Point;
use super::mercator::{Bounds, LatLon, MAX_ZOOM, TILE_SIZE, Viewport, clamp_lat, to_world, world_size};
/// Largest distance, in screen pixels, between a dropped point and the line drawn.
pub const TOLERANCE_PX: f64 = 0.6;
/// Points per chunk of a [`Level`] (the unit of culling).
pub const CHUNK: usize = 256;
/// Below this distance (world fractions; about a millimetre on the ground) a point is on the
/// chord: the rest of its range is dropped without searching it further.
const FLAT: f64 = 1e-12;
/// Distance computations allowed per point when ranking (Douglas–Peucker is n log n on real
/// tracks; this only stops pathological input).
const WORK_PER_POINT: usize = 64;
/// Most copies of the world one chunk is drawn on (a 16k-pixel view at zoom 0 shows 64).
const MAX_COPIES: u32 = 64;
/// One line cut at the antimeridian: points in the Mercator square (fractions: x from −180°
/// eastward in [0, 1], y from the north edge in [0, 1]) and their simplification ranks.
#[derive(Clone, Debug, Default)]
struct Piece {
xy: Vec<Point>,
rank: Vec<f64>,
}
/// A track ready to draw: see the module docs.
#[derive(Clone, Debug, Default)]
pub struct TrackShape {
pieces: Vec<Piece>,
bounds: Option<Bounds>,
points: usize,
}
/// Position of a valid point in the Mercator square (longitude not wrapped: 180° is x = 1).
fn frac(p: LatLon) -> Point {
let y = to_world(LatLon { lat: clamp_lat(p.lat), lon: 0.0 }, 0.0).y / f64::from(TILE_SIZE);
Point::new((p.lon + 180.0) / 360.0, y)
}
/// Distance from `p` to the segment `a`–`b`.
fn seg_dist(p: Point, a: Point, b: Point) -> f64 {
let (dx, dy) = (b.x - a.x, b.y - a.y);
let len2 = dx * dx + dy * dy;
let t = if len2 > 0.0 { (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };
let (ex, ey) = (a.x + t * dx - p.x, a.y + t * dy - p.y);
(ex * ex + ey * ey).sqrt()
}
/// The Douglas–Peucker rank of every point of `xy` (ends: infinite).
fn ranks(xy: &[Point]) -> Vec<f64> {
let n = xy.len();
let mut rank = vec![0.0; n];
if let Some(r) = rank.first_mut() {
*r = f64::INFINITY;
}
if let Some(r) = rank.last_mut() {
*r = f64::INFINITY;
}
if n < 3 {
return rank;
}
let mut budget = n.saturating_mul(WORK_PER_POINT);
let mut stack = vec![(0usize, n - 1, f64::INFINITY)];
while let Some((a, b, parent)) = stack.pop() {
if b <= a + 1 {
continue;
}
let (Some(&pa), Some(&pb)) = (xy.get(a), xy.get(b)) else { continue };
let inner = b - a - 1;
if inner > budget {
// out of work: keep the rest of this range whole (more points, never more error)
for r in rank.get_mut(a + 1..b).unwrap_or(&mut []) {
*r = parent;
}
continue;
}
budget -= inner;
let (mut best, mut at) = (-1.0, a + 1);
for (i, p) in xy.iter().enumerate().take(b).skip(a + 1) {
let d = seg_dist(*p, pa, pb);
if d > best {
best = d;
at = i;
}
}
if best <= FLAT {
// every point of the range is on the chord: all dropped (rank 0 is never kept)
continue;
}
let r = best.min(parent);
if let Some(slot) = rank.get_mut(at) {
*slot = r;
}
stack.push((a, at, r));
stack.push((at, b, r));
}
rank
}
impl TrackShape {
/// The shape of a track made of `lines` (`(latitude, longitude)` points each).
pub fn new<L, P>(lines: L) -> TrackShape
where
L: IntoIterator<Item = P>,
P: IntoIterator<Item = (f64, f64)>,
{
let mut pieces = Vec::new();
let mut all: Vec<(f64, f64)> = Vec::new();
for line in lines {
let mut cur: Vec<Point> = Vec::new();
let mut prev: Option<LatLon> = None;
for (lat, lon) in line {
let Some(p) = LatLon::new(lat, lon) else { continue };
all.push((p.lat, p.lon));
if let Some(q) = prev {
let d = p.lon - q.lon;
if d.abs() > 180.0 {
// the short way round: leave by one edge, come back by the other
let (edge, other, unwrapped) = if d < 0.0 { (180.0, -180.0, p.lon + 360.0) } else { (-180.0, 180.0, p.lon - 360.0) };
let span = unwrapped - q.lon;
let t = if span != 0.0 { ((edge - q.lon) / span).clamp(0.0, 1.0) } else { 0.0 };
let lat_x = q.lat + (p.lat - q.lat) * t;
cur.push(frac(LatLon { lat: lat_x, lon: edge }));
let done = std::mem::take(&mut cur);
if done.len() >= 2 {
pieces.push(done);
}
cur.push(frac(LatLon { lat: lat_x, lon: other }));
}
}
cur.push(frac(p));
prev = Some(p);
}
if !cur.is_empty() {
pieces.push(cur);
}
}
let points = all.len();
let bounds = Bounds::of(all);
let pieces = pieces
.into_iter()
.map(|xy| {
let rank = ranks(&xy);
Piece { xy, rank }
})
.collect();
TrackShape { pieces, bounds, points }
}
/// The box holding every valid point (antimeridian aware), `None` for a track without one.
pub fn bounds(&self) -> Option<Bounds> {
self.bounds
}
/// Valid points of the track.
pub fn points(&self) -> usize {
self.points
}
/// Lines drawn (after the antimeridian cuts).
pub fn pieces(&self) -> usize {
self.pieces.len()
}
/// The points kept at tile zoom `zoom` ([`TOLERANCE_PX`] at that zoom), chunked for culling.
pub fn level(&self, zoom: u8) -> Level {
let zoom = zoom.min(MAX_ZOOM);
let tol = TOLERANCE_PX / world_size(f64::from(zoom));
let mut chunks = Vec::new();
let mut kept = 0;
for piece in &self.pieces {
let pts: Vec<Point> = piece.xy.iter().zip(&piece.rank).filter(|(_, r)| **r > tol).map(|(p, _)| *p).collect();
kept += pts.len();
if pts.len() == 1 {
// a single point (a one-point track): a dot
chunks.push(Chunk::new(pts));
continue;
}
// chunks share their end points, so the line stays whole
let mut start = 0;
while start + 1 < pts.len() {
let end = (start + CHUNK).min(pts.len() - 1);
chunks.push(Chunk::new(pts.get(start..=end).unwrap_or(&[]).to_vec()));
start = end;
}
}
Level { zoom, chunks, points: kept }
}
}
#[derive(Clone, Debug)]
struct Chunk {
pts: Vec<Point>,
min: Point,
max: Point,
}
impl Chunk {
fn new(pts: Vec<Point>) -> Chunk {
let mut min = Point::new(f64::INFINITY, f64::INFINITY);
let mut max = Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
for p in &pts {
min = Point::new(min.x.min(p.x), min.y.min(p.y));
max = Point::new(max.x.max(p.x), max.y.max(p.y));
}
Chunk { pts, min, max }
}
}
/// A track simplified for one zoom ([`TrackShape::level`]).
#[derive(Clone, Debug, Default)]
pub struct Level {
pub zoom: u8,
chunks: Vec<Chunk>,
/// Points kept.
pub points: usize,
}
/// Clip the segment `a`–`b` to the box `[x0, x1] × [y0, y1]` (Liang–Barsky): the part inside,
/// and whether each end was moved.
fn clip(a: Point, b: Point, x0: f64, y0: f64, x1: f64, y1: f64) -> Option<(Point, Point, bool, bool)> {
let (dx, dy) = (b.x - a.x, b.y - a.y);
let (mut t0, mut t1) = (0.0f64, 1.0f64);
for (p, q) in [(-dx, a.x - x0), (dx, x1 - a.x), (-dy, a.y - y0), (dy, y1 - a.y)] {
if p == 0.0 {
if q < 0.0 {
return None;
}
} else {
let r = q / p;
if p < 0.0 {
t0 = t0.max(r);
} else {
t1 = t1.min(r);
}
}
}
if t0 > t1 || !t0.is_finite() || !t1.is_finite() {
return None;
}
let at = |t: f64| Point::new(a.x + t * dx, a.y + t * dy);
Some((at(t0), at(t1), t0 > 0.0, t1 < 1.0))
}
impl Level {
/// The lines to paint for view `vp`, in screen pixels from its top-left corner, clipped to the
/// view grown by `margin` pixels. Each chunk is drawn on every copy of the world the view shows
/// it on (a view wider than the world, or across the antimeridian, may show two). A one-point
/// track gives a one-point line (a dot).
pub fn screen_lines(&self, vp: &Viewport, margin: f64) -> Vec<Vec<Point>> {
let v = Viewport::new(vp.center, vp.zoom, vp.width, vp.height);
let mut out: Vec<Vec<Point>> = Vec::new();
if v.width <= 0.0 || v.height <= 0.0 {
return out;
}
let ws = world_size(v.zoom);
let c = to_world(v.center, v.zoom);
let (cx, cy) = (c.x / ws, c.y / ws);
let m = if margin.is_finite() { margin.clamp(0.0, 1000.0) } else { 0.0 };
let (x0, y0, x1, y1) = (-m, -m, v.width + m, v.height + m);
let sy = |y: f64| (y - cy) * ws + v.height / 2.0;
if !ws.is_finite() || ws <= 0.0 {
return out;
}
for ch in &self.chunks {
if sy(ch.max.y) < y0 || sy(ch.min.y) > y1 {
continue;
}
// the whole-world shifts k that put the chunk's x range [min + k, max + k] in view
let first = ((x0 - v.width / 2.0) / ws + cx - ch.max.x).ceil();
let last = ((x1 - v.width / 2.0) / ws + cx - ch.min.x).floor();
if !first.is_finite() || !last.is_finite() || last < first {
continue;
}
// (a view is never more than a few worlds wide; bounded whatever the input)
for i in 0..=((last - first) as u32).min(MAX_COPIES) {
let shift = first + f64::from(i);
let sx = |x: f64| (x + shift - cx) * ws + v.width / 2.0;
let screen = |p: &Point| Point::new(sx(p.x), sy(p.y));
if let [only] = ch.pts.as_slice() {
out.push(vec![screen(only)]);
continue;
}
// each copy starts its own line
let mut joined = i == 0;
for pair in ch.pts.windows(2) {
let [a, b] = pair else { continue };
if let Some((ca, cb, moved_a, _)) = clip(screen(a), screen(b), x0, y0, x1, y1) {
// a line goes on where the last one ended (the next segment, the next chunk)
if !joined || moved_a || out.last().and_then(|l| l.last()) != Some(&ca) {
out.push(vec![ca]);
}
joined = true;
if let Some(line) = out.last_mut() {
line.push(cb);
}
}
}
}
}
out
}
}
+2 -10
View File
@@ -456,11 +456,7 @@ impl Session {
} else {
let previous = self.prep.app;
self.prep.app = settings;
let saved = self.save_prefs();
if saved.is_err() {
self.prep.app = previous;
}
saved
self.save_prefs_or_undo(|s| s.prep.app = previous)
}
}
@@ -474,11 +470,7 @@ impl Session {
/// Save this library's preparation settings; when that fails, `previous` is put back, so the
/// session doesn't go on with settings the command reported as not changed (CodeRabbit on #3544).
fn save_library_prep(&mut self, previous: Option<PrepSettings>) -> crate::Result<()> {
let saved = self.save_prefs();
if saved.is_err() {
self.prep.library = previous;
}
saved
self.save_prefs_or_undo(|s| s.prep.library = previous)
}
pub(crate) fn prep_json(&self) -> Value {
+13 -6
View File
@@ -802,6 +802,11 @@ pub const OWNED: &[&str] = &[
/// writes (`xmp:CreatorTool`) goes only into new sidecars.
pub const OWNED_IF_STATED: &[&str] = &["exif:DateTimeOriginal", "photoshop:DateCreated", "exif:GPSLatitude", "exif:GPSLongitude"];
/// GPS properties added to [`OWNED`] for a photo whose position was set or cleared in LightCraft
/// ([`Session::gps_edited`]): its position is LightCraft's, so one cleared (or a geotag undone) is
/// removed from the sidecar instead of the old value staying (ported from PR #810).
pub const GPS_OWNED: &[&str] = &["exif:GPSLatitude", "exif:GPSLongitude", "exif:GPSAltitude", "exif:GPSAltitudeRef"];
/// Write `data` to `path` atomically: a temp file next to it, synced, then renamed over it.
fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
lightcraft_catalog::safe_file::write_atomic(path, data)
@@ -845,7 +850,7 @@ pub struct SidecarSaved {
/// The new contents for the sidecar at `path`: `fresh` merged into the existing file, if any.
/// Returns (contents, merged, backup).
fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result<(String, bool, Option<PathBuf>)> {
fn sidecar_contents(path: &Path, fresh: String, stamp: &str, gps_owned: bool) -> std::io::Result<(String, bool, Option<PathBuf>)> {
let bytes = match crate::read_file::read_regular(path, SIDECAR_READ_MAX) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((fresh, false, None)),
@@ -855,7 +860,8 @@ fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result<
if bytes.iter().all(u8::is_ascii_whitespace) {
return Ok((fresh, false, None));
}
let rules = lightcraft_meta::MergeRules { owned: OWNED, owned_if_present: OWNED_IF_STATED };
let owned: Vec<&str> = OWNED.iter().chain(if gps_owned { GPS_OWNED } else { &[] }).copied().collect();
let rules = lightcraft_meta::MergeRules { owned: &owned, owned_if_present: OWNED_IF_STATED };
let why = match std::str::from_utf8(&bytes) {
Ok(old) => match lightcraft_meta::merge_xmp(old, &fresh, rules) {
Ok(merged) => return Ok((merged, true, None)),
@@ -1240,7 +1246,8 @@ impl Session {
self.validate_sidecar_packets_for_paths(std::slice::from_ref(&path), &crate::rename::RealFs)?;
let p = self.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?;
let err = |e: std::io::Error| EngineError::Other(format!("{}: {e}", path.display()));
let (data, merged, backup) = sidecar_contents(&path, sidecar_packet(p, &self.catalog), &(self.clock)()).map_err(err)?;
let (data, merged, backup) =
sidecar_contents(&path, sidecar_packet(p, &self.catalog), &(self.clock)(), self.gps_edited.contains(&id)).map_err(err)?;
write_atomic(&path, data.as_bytes()).map_err(err)?;
self.note_sidecar_write(&path, data.as_bytes());
Ok(SidecarSaved { path, merged, backup })
@@ -1697,7 +1704,7 @@ mod tests {
let path = dir.join("a.xmp");
std::fs::write(&path, &old).unwrap();
let fresh = lightcraft_meta::write_xmp_lc(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() }, &[("settings", "{}")]);
assert!(super::sidecar_contents(&path, fresh, "t").is_err());
assert!(super::sidecar_contents(&path, fresh, "t", false).is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), old);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "no backup was made");
std::fs::remove_dir_all(dir).unwrap();
@@ -1712,7 +1719,7 @@ mod tests {
let path = dir.join("a.xmp");
std::fs::write(&path, "not xml at all").unwrap();
let fresh = lightcraft_meta::write_xmp_lc(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() }, &[("settings", "{}")]);
let (data, merged, backup) = super::sidecar_contents(&path, fresh.clone(), "t").unwrap();
let (data, merged, backup) = super::sidecar_contents(&path, fresh.clone(), "t", false).unwrap();
assert!(!merged && data == fresh);
assert!(backup.is_some_and(|b| std::fs::read_to_string(b).unwrap() == "not xml at all"));
std::fs::remove_dir_all(dir).unwrap();
@@ -1732,7 +1739,7 @@ mod tests {
let path = dir.join("a.xmp");
std::fs::write(&path, &old).unwrap();
let fresh = lightcraft_meta::write_xmp_lc(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() }, &[("settings", "{}")]);
assert!(super::sidecar_contents(&path, fresh, "t").is_err());
assert!(super::sidecar_contents(&path, fresh, "t", false).is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), old);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "no backup was made");
std::fs::remove_dir_all(dir).unwrap();
+4
View File
@@ -41,6 +41,8 @@ mod libops;
mod library;
mod lightroom_folder;
mod lightroom_history;
mod location;
mod map;
mod mask_effects;
mod mask_geometry;
mod merge;
@@ -56,6 +58,7 @@ mod print;
mod process;
mod recheck;
mod relocate;
mod saved_locations;
mod segment;
mod settings_files;
mod shelved_folder;
@@ -66,6 +69,7 @@ mod slow_drive;
mod spots;
mod sync;
mod task_queue;
mod tracklog;
mod view_follow;
pub(super) mod xmp;
+4
View File
@@ -437,10 +437,14 @@ fn tracklog_auto_tag() {
assert_eq!(r["skipped"], json!({"noTime": 0, "outside": 1, "hasGps": 1}));
assert_eq!((r["points"].as_u64(), r["start"].as_str()), (Some(3), Some("2026-05-01T10:00:00Z")));
assert_eq!(ids.iter().map(|i| gps(&s, *i)).collect::<Vec<_>>(), before);
assert!(!s.gps_edited.contains(&PhotoId(ids[0])), "a dry run marks nothing as LightCraft's");
// tag: one undo step
let undo_depth = s.undo.len();
s.execute("photo.autoTagTracklog", &json!({"path": path, "ids": ids, "offset": 2})).unwrap();
assert_eq!(s.undo.len(), undo_depth + 1);
// the tagged photos' positions are LightCraft's (sidecar GPS follows them, as photo.setGps's)
assert!(s.gps_edited.contains(&PhotoId(ids[0])) && s.gps_edited.contains(&PhotoId(ids[1])));
assert!(!s.gps_edited.contains(&PhotoId(ids[2])), "not tagged: not marked");
assert_eq!(gps(&s, ids[0]), Some((46.0005, 7.001)), "interpolated half-way between the first two points");
assert_eq!(gps(&s, ids[1]), Some((46.001, 7.002)));
assert_eq!(gps(&s, ids[2]), None);
+159
View File
@@ -0,0 +1,159 @@
//! Location rules through the commands (LRC-MAP-FILTER): `library.filter` and smart albums with
//! Has GPS and GPS Area, and a view's own narrowing ([`crate::Session::narrow`]) over the filter.
use lightcraft_catalog::{PhotoId, RuleSet};
use serde_json::{Value, json};
use crate::Session;
/// The demo library with Paris, Fiji and Samoa on its first three photos; the rest have no GPS.
fn tagged() -> (Session, Vec<PhotoId>) {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(3).collect();
for (id, gps) in ids.iter().zip([[48.8584, 2.2945], [-17.7, 178.0], [-13.8, -172.0]]) {
s.execute("photo.setGps", &json!({"ids": [id.0], "lat": gps[0], "lon": gps[1]})).unwrap();
}
(s, ids)
}
fn sorted(mut v: Vec<PhotoId>) -> Vec<PhotoId> {
v.sort();
v
}
fn area(south: f64, west: f64, north: f64, east: f64) -> Value {
json!({"south": south, "west": west, "north": north, "east": east})
}
/// Clearing the position of a selection marks only the photos that had one as LightCraft's: a
/// photo skipped keeps whatever position its sidecar holds.
#[test]
fn removing_gps_owns_only_the_photos_it_changed() {
let mut s = Session::with_demo();
let v = s.visible_cloned();
let (placed, bare) = (v[0], v[1]);
s.execute("photo.setGps", &json!({"ids": [placed.0], "lat": 48.85, "lon": 2.29})).unwrap();
s.gps_edited.clear();
s.execute("photo.removeGps", &json!({"ids": [placed.0, bare.0]})).unwrap();
assert_eq!(s.gps_edited.iter().copied().collect::<Vec<_>>(), [placed]);
}
#[test]
fn library_filter_takes_gps_rules() {
let (mut s, ids) = tagged();
let total = s.visible_cloned().len();
// the Pacific, across the antimeridian
let pacific = json!({"ruleSet": {"rules": [{"field": "gpsArea", "op": "inside", "value": area(-30.0, 170.0, 30.0, -170.0)}]}});
s.execute("library.filter", &pacific).unwrap();
assert_eq!(sorted(s.visible_cloned()), sorted(vec![ids[1], ids[2]]));
s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "hasGps", "op": "is", "value": false}]}})).unwrap();
assert_eq!(s.visible_cloned().len(), total - 3);
assert!(ids.iter().all(|id| !s.visible_cloned().contains(id)));
// a box that means nothing is refused, and the filter stays as it was
let before = s.filter.clone();
for bad in [area(10.0, 0.0, -10.0, 5.0), area(0.0, 0.0, 95.0, 5.0), json!({"south": 0}), json!("Paris")] {
let r = s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "gpsArea", "op": "inside", "value": bad}]}}));
assert!(r.is_err(), "{bad}");
assert_eq!(s.filter, before);
}
// the field is listed for agents, in the Location group
let fields = s.execute("album.ruleFields", &json!({})).unwrap();
let f = fields.as_array().unwrap().iter().find(|f| f["field"] == "gpsArea").cloned().unwrap();
assert_eq!((f["kind"].as_str(), f["group"].as_str()), (Some("area"), Some("Location")), "{f}");
}
#[test]
fn a_smart_album_keeps_the_photos_in_an_area() {
let (mut s, ids) = tagged();
let r = s
.execute(
"album.createSmart",
&json!({"name": "Europe", "rules": {"ruleSet": {"rules": [{"field": "gpsArea", "op": "inside", "value": area(35.0, -10.0, 60.0, 30.0)}]}}}),
)
.unwrap();
assert_eq!(r["count"], 1, "{r}");
// moving Fiji to Rome puts it in
s.execute("photo.setGps", &json!({"ids": [ids[1].0], "lat": 41.9, "lon": 12.5})).unwrap();
let album = lightcraft_catalog::AlbumId(r["id"].as_u64().unwrap());
assert_eq!(s.catalog.album_count(album), 2);
assert!(
s.execute(
"album.createSmart",
&json!({"name": "Bad", "rules": {"ruleSet": {"rules": [{"field": "gpsArea", "op": "inside", "value": null}]}}})
)
.is_err()
);
}
#[test]
fn a_views_narrowing_sits_on_the_filter_and_goes_away_cleanly() {
let (mut s, ids) = tagged();
s.execute("library.filter", &json!({"text": ""})).unwrap();
let (base_gen, all) = s.visible_shared();
let filter = s.filter.clone();
let rules: RuleSet = serde_json::from_value(json!({"rules": [{"field": "hasGps", "op": "is", "value": true}]})).unwrap();
s.narrow = Some(rules);
let (narrowed_gen, tagged) = s.visible_shared();
assert_ne!(narrowed_gen, base_gen, "a new list");
assert_eq!(sorted(tagged.to_vec()), sorted(ids.clone()));
// the library's own filter is untouched, and the list before narrowing is still there
assert_eq!(s.filter, filter);
assert_eq!(s.visible_base_shared().1.len(), all.len());
// the same narrowing again: the same list (no recomputation)
assert_eq!(s.visible_shared().0, narrowed_gen);
// it follows the catalog: an untagged photo tagged now joins
let other = *all.iter().find(|id| !ids.contains(id)).unwrap();
s.execute("photo.setGps", &json!({"ids": [other.0], "lat": 1.0, "lon": 2.0})).unwrap();
assert_eq!(s.visible_cloned().len(), 4);
// and the filter still applies under it
s.execute("library.filter", &json!({"ruleSet": {"rules": [{"field": "gpsArea", "op": "inside", "value": area(-30.0, 170.0, 30.0, -170.0)}]}}))
.unwrap();
assert_eq!(sorted(s.visible_cloned()), sorted(vec![ids[1], ids[2]]));
s.execute("library.filter", &json!({"ruleSet": null})).unwrap();
s.narrow = None;
assert_eq!(s.visible_cloned().len(), all.len());
}
#[test]
fn narrowing_an_empty_library_is_empty() {
let mut s = Session::new();
s.narrow =
Some(serde_json::from_value(json!({"rules": [{"field": "gpsArea", "op": "inside", "value": area(-90.0, -180.0, 90.0, 180.0)}]})).unwrap());
assert!(s.visible().is_empty());
assert!(s.visible_base_shared().1.is_empty());
}
/// The plan's numbers: narrowing 50,000 photos to an area, and counting 20,000 positions in one.
#[test]
fn narrowing_and_counting_many_photos() {
use lightcraft_catalog::{Op, Photo, Source};
let mut s = Session::new();
let mut seed = 7u64;
let mut rnd = || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 11) as f64 / (1u64 << 53) as f64
};
let mut ops = Vec::new();
for i in 0..50_000u64 {
let id = s.catalog.alloc_photo_id();
let mut p = Photo::new(id, Source::Demo { scene: 0 }, &format!("p{i}.jpg"), "JPEG", 600, 400, "2026-09-20T10:00:00");
p.meta.gps = (i % 5 != 0).then(|| (36.0 + rnd() * 24.0, -10.0 + rnd() * 40.0));
ops.push(Op::AddPhoto { photo: Box::new(p) });
}
for op in ops {
s.catalog.apply(op).unwrap();
}
assert_eq!(s.visible().len(), 50_000);
s.narrow = Some(serde_json::from_value(json!({"rules": [{"field": "gpsArea", "op": "inside", "value": area(45.0, 0.0, 50.0, 10.0)}]})).unwrap());
let t = std::time::Instant::now();
let n = s.visible().len();
let narrow_ms = t.elapsed().as_secs_f64() * 1e3;
assert!(n > 1000 && n < 10_000, "{n}");
let box_ = lightcraft_catalog::rules::GpsArea { south: 45.0, west: 0.0, north: 50.0, east: 10.0 };
let positions: Vec<(f64, f64)> = s.catalog.photos().filter_map(|p| p.meta.gps).take(20_000).collect();
let t = std::time::Instant::now();
let inside = positions.iter().filter(|(la, lo)| box_.contains(*la, *lo)).count();
let count_ms = t.elapsed().as_secs_f64() * 1e3;
eprintln!("location filter: narrowed 50 000 photos to {n} in {narrow_ms:.1} ms; counted {inside} of 20 000 in {count_ms:.2} ms");
assert!(narrow_ms < 5_000.0 && count_ms < 1_000.0);
}
+404
View File
@@ -0,0 +1,404 @@
use crate::Session;
use serde_json::{Value, 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 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["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)));
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);
}
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_need_a_key_and_the_key_is_never_reported() {
let mut s = Session::new();
for id in ["esri-streets", "esri-topo"] {
let e = s.execute("map.tileSource", &json!({"id": id})).unwrap_err().to_string();
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);
// 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-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]
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]
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)));
}
/// The older command names of the saved locations still work (map.savedLocations.*).
#[test]
fn the_older_saved_location_commands_still_work() {
let mut s = Session::with_demo();
let id0 = s.visible()[0];
s.execute("photo.setGps", &json!({"ids": [id0.0], "lat": 45.57, "lon": -73.2})).unwrap();
let created = s
.execute("map.savedLocations.create", &json!({"name": "Beloeil Studio", "lat": 45.57, "lon": -73.2, "radius": 2000.0, "isPrivate": true}))
.unwrap();
let id = created["id"].as_u64().unwrap();
let list = s.execute("map.savedLocations.list", &json!({})).unwrap();
let l = &list["locations"][0];
assert_eq!((l["name"].as_str(), l["photos"].as_u64(), l["private"].as_bool()), (Some("Beloeil Studio"), Some(1), Some(true)), "{list}");
s.execute("map.savedLocations.delete", &json!({"id": id})).unwrap();
assert_eq!(s.execute("map.locations", &json!({})).unwrap()["count"], 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)));
}
/// A view across the 180° meridian (west edge east of the east edge) holds what is on screen
/// there, as the Map view's Visible On Map filter reads it; bad bounds or modes are refused, not
/// read as "everything".
#[test]
fn map_filter_photos_reads_a_view_across_the_antimeridian() {
let mut s = Session::with_demo();
let ids = s.visible().to_vec();
let (fiji, montreal) = (ids[0].0, ids[1].0);
s.execute("photo.setGps", &json!({"ids": [fiji], "lat": -17.7, "lon": 178.0})).unwrap();
s.execute("photo.setGps", &json!({"ids": [montreal], "lat": 45.5, "lon": -73.6})).unwrap();
let shown = |s: &mut Session, bounds: Value| -> Vec<u64> {
let r = s.execute("map.filterPhotos", &json!({"mode": "visible", "bounds": bounds})).unwrap();
r["photos"].as_array().unwrap().iter().filter_map(|p| p["id"].as_u64()).collect()
};
let across = shown(&mut s, json!({"minLat": -30.0, "maxLat": 0.0, "minLon": 170.0, "maxLon": -170.0}));
assert!(across.contains(&fiji), "{across:?}");
assert!(!across.contains(&montreal), "{across:?}");
let americas = shown(&mut s, json!({"minLat": 0.0, "maxLat": 60.0, "minLon": -130.0, "maxLon": -60.0}));
assert!(americas.contains(&montreal) && !americas.contains(&fiji), "{americas:?}");
for bad in [
json!({"mode": "visible", "bounds": {"minLat": 0.0}}),
json!({"mode": "visible", "bounds": {"minLat": 10.0, "maxLat": 0.0, "minLon": 0.0, "maxLon": 10.0}}),
json!({"mode": "visibel"}),
json!({"mode": 3}),
] {
assert!(s.execute("map.filterPhotos", &bad).is_err(), "{bad}");
}
}
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 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": "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": "esriTopo"}));
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);
}
/// 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<u64> = 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)));
}
/// `photo.removeGps` (Photo ▸ Remove GPS Coordinates, a pin's menu) clears the selection's position
/// in one undo step; ids the library doesn't have are refused; `photo.clearGps` is the same command.
#[test]
fn remove_gps_clears_in_one_undo_step_and_refuses_unknown_ids() {
let mut s = Session::with_demo();
let ids: Vec<u64> = s.catalog.photos().take(3).map(|p| p.id.0).collect();
s.execute("photo.setGps", &json!({"ids": ids, "lat": 51.5, "lon": -0.12})).unwrap();
let gps = |s: &Session, id: u64| s.catalog.photo(lightcraft_catalog::PhotoId(id)).and_then(|p| p.meta.gps);
s.execute("library.select", &json!({"ids": [ids[0], ids[1]]})).unwrap();
let steps = s.undo.len();
let r = s.execute("photo.removeGps", &json!({})).unwrap();
assert_eq!(r["changed"], 2, "{r}");
assert_eq!((gps(&s, ids[0]), gps(&s, ids[1]), gps(&s, ids[2])), (None, None, Some((51.5, -0.12))));
assert_eq!(s.undo.len(), steps + 1);
assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Remove GPS Coordinates"));
// nothing to clear: no empty undo step
assert_eq!(s.execute("photo.removeGps", &json!({})).unwrap()["changed"], 0);
assert_eq!(s.undo.len(), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((gps(&s, ids[0]), gps(&s, ids[1])), (Some((51.5, -0.12)), Some((51.5, -0.12))));
for bad in [json!({"ids": [987_654_321]}), json!({"ids": "1"})] {
assert!(matches!(s.execute("photo.removeGps", &bad), Err(crate::EngineError::BadParams { .. })), "{bad}");
}
assert_eq!(gps(&s, ids[0]), Some((51.5, -0.12)), "a refusal changes nothing");
let r = s.execute("photo.clearGps", &json!({"ids": [ids[2]]})).unwrap();
assert_eq!((r["changed"].as_u64(), gps(&s, ids[2])), (Some(1), None));
assert!(s.gps_edited.contains(&lightcraft_catalog::PhotoId(ids[2])), "its sidecar GPS is LightCraft's now");
}
+160
View File
@@ -217,6 +217,74 @@ fn a_preset_that_cannot_be_written_counts_as_unsaved_until_it_is() {
assert!(String::from_utf8_lossy(&stored(&files)).contains("Mine"));
}
/// A prefs.json write that failed (here: which photos' GPS is LightCraft's) is retried by the next
/// save, though nothing was added to it since.
#[test]
fn a_failed_prefs_write_is_retried_until_it_lands() {
let files = Flaky::default();
let mut s = Session::new();
let stores = LibraryStores { dir: "flaky".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false };
s.open_library_in(stores, true).unwrap();
let id = s.selection.active.unwrap();
let owned = |f: &Flaky| -> Vec<serde_json::Value> {
let prefs = f.files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
serde_json::from_slice::<serde_json::Value>(&prefs).ok().and_then(|v| v["gpsOwned"].as_array().cloned()).unwrap_or_default()
};
files.set_failing(true);
s.execute("photo.setGps", &json!({"lat": 1.0, "lon": 2.0})).unwrap();
assert!(owned(&files).is_empty(), "the write failed");
// meanwhile it counts as unsaved (the quit prompt asks, a backup refuses)
let (n, why) = s.unsaved().expect("prefs.json unsaved");
assert!(n >= 1 && why.starts_with("prefs:"), "{n} {why}");
files.set_failing(false);
// any later save writes it (the set didn't change)
s.execute("library.info", &json!({})).unwrap();
assert_eq!(owned(&files), vec![json!(id.0)]);
assert!(s.unsaved().is_none(), "written");
}
/// Closing the library while prefs.json can't be written is an error even though the catalog
/// snapshot landed: what it holds (which photos' GPS is LightCraft's) would be lost when another
/// library opens, so a switch stops and keeps this one open.
#[test]
fn closing_with_prefs_unwritten_is_an_error_until_they_land() {
let files = Flaky::default();
let mut s = Session::new();
let stores = LibraryStores { dir: "flaky".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false };
s.open_library_in(stores, true).unwrap();
let id = s.selection.active.unwrap();
files.set_failing(true);
s.execute("photo.setGps", &json!({"lat": 1.0, "lon": 2.0})).unwrap();
let e = s.close_library().expect_err("prefs.json unwritten");
assert!(e.to_string().contains("prefs"), "{e}");
assert!(s.gps_edited.contains(&id), "the ownership is still held in memory");
files.set_failing(false);
s.close_library().unwrap();
let prefs = files.files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
let v: serde_json::Value = serde_json::from_slice(&prefs).unwrap();
assert_eq!(v["gpsOwned"], json!([id.0]), "written on the close that could");
}
/// A preference change whose prefs.json write failed is taken back, so nothing is left unsaved:
/// the failure isn't reported as pending (a quit would ask about a change that never happened).
#[test]
fn a_preference_taken_back_after_a_failed_write_leaves_nothing_unsaved() {
let files = Flaky::default();
let mut s = Session::new();
let stores = LibraryStores { dir: "flaky".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false };
s.open_library_in(stores, true).unwrap();
let was = s.hold_view;
files.set_failing(true);
assert!(s.execute("library.holdView", &json!({"on": !was})).is_err());
assert_eq!(s.hold_view, was, "not kept");
assert_eq!(s.unsaved(), None, "nothing changed, so nothing is unsaved");
// a failure already pending stays pending
s.execute("photo.setGps", &json!({"lat": 1.0, "lon": 2.0})).unwrap();
assert!(s.unsaved().is_some_and(|(_, why)| why.starts_with("prefs:")));
assert!(s.execute("library.holdView", &json!({"on": !was})).is_err());
assert!(s.unsaved().is_some_and(|(_, why)| why.starts_with("prefs:")), "the GPS ownership is still unsaved");
}
/// Given a library saved by an earlier version, when it is opened, then the person is told once
/// that it was upgraded and where the library as it was is kept (the files are theirs to
/// delete), and `library.info` lists it; a library that was not upgraded says nothing.
@@ -527,3 +595,95 @@ fn a_partly_applied_undo_step_keeps_its_retry_inverses() {
let Some(Op::Batch { ops }) = s.redo.last().map(|r| r.op.clone()) else { panic!("the step that takes it back is a batch") };
assert_eq!(ops.last(), Some(&fix));
}
fn open_files(files: &Flaky) -> Session {
let mut s = Session::new();
let stores = LibraryStores { dir: "flaky".into(), catalog: Box::new(MemStore::new()), files: Box::new(files.clone()), on_disk: false };
s.open_library_in(stores, true).unwrap();
s
}
/// A saved location whose `locations.json` write failed stays pending: it counts as unsaved, is
/// retried by the next save, and closing the library refuses until it lands.
#[test]
fn a_failed_locations_write_is_pending_until_it_lands() {
let files = Flaky::default();
let mut s = open_files(&files);
files.set_failing(true);
let l = s.execute("map.location.add", &json!({"name": "Home", "lat": 1.0, "lon": 2.0, "private": true})).unwrap();
assert!(l["notSaved"].is_string(), "{l}");
let (_, why) = s.unsaved().expect("locations.json unsaved");
assert!(why.contains("saved locations"), "{why}");
assert!(s.close_library().is_err(), "closing would lose it");
files.set_failing(false);
s.execute("library.info", &json!({})).unwrap();
assert!(s.unsaved().is_none(), "written by the next save");
let saved = files.files.files.lock().unwrap().get("locations.json").cloned().unwrap_or_default();
assert!(String::from_utf8_lossy(&saved).contains("Home"));
s.close_library().unwrap();
}
/// Opening another library while this one's prefs.json or locations.json can't be written fails,
/// and this library stays open with what it holds.
#[test]
fn opening_another_library_over_unsaved_settings_fails_and_keeps_this_one() {
let files = Flaky::default();
let mut s = open_files(&files);
let id = s.selection.active.unwrap();
files.set_failing(true);
s.execute("photo.setGps", &json!({"lat": 1.0, "lon": 2.0})).unwrap();
let other = LibraryStores { dir: "other".into(), catalog: Box::new(MemStore::new()), files: Box::new(MemStore::new()), on_disk: false };
let e = s.open_library_in(other, false).unwrap_err();
assert!(matches!(e, EngineError::NotSaved(_)), "{e:?}");
assert!(s.gps_edited.contains(&id), "this library's ownership is still held");
files.set_failing(false);
let other = LibraryStores { dir: "other".into(), catalog: Box::new(MemStore::new()), files: Box::new(MemStore::new()), on_disk: false };
s.open_library_in(other, false).unwrap();
let prefs = files.files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
assert!(String::from_utf8_lossy(&prefs).contains(&id.0.to_string()), "written before the switch");
}
/// GPS ownership is written only once the GPS change itself is on disk: with the catalog log
/// failing, a crash leaves no ownership for a position the catalog doesn't have.
#[test]
fn gps_ownership_waits_for_the_catalog_change() {
let store = Flaky { appends_only: true, ..Default::default() };
let files = MemStore::new();
let mut s = Session::new();
let stores = LibraryStores { dir: "flaky".into(), catalog: Box::new(store.clone()), files: Box::new(files.clone()), on_disk: false };
s.open_library_in(stores, true).unwrap();
store.set_failing(true);
assert!(s.execute("photo.setGps", &json!({"lat": 1.0, "lon": 2.0})).is_err(), "the change isn't on disk");
let prefs = files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
let owned = serde_json::from_slice::<serde_json::Value>(&prefs).ok().and_then(|v| v["gpsOwned"].as_array().cloned()).unwrap_or_default();
assert!(owned.is_empty(), "no ownership on disk before the change: {owned:?}");
// another preference saved meanwhile doesn't write it either
s.save_prefs().unwrap();
let prefs = files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
let owned = serde_json::from_slice::<serde_json::Value>(&prefs).ok().and_then(|v| v["gpsOwned"].as_array().cloned()).unwrap_or_default();
assert!(owned.is_empty(), "not by another preferences save: {owned:?}");
// the log comes back: both land, the change first
store.set_failing(false);
s.execute("library.info", &json!({})).unwrap();
let prefs = files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
let owned = serde_json::from_slice::<serde_json::Value>(&prefs).ok().and_then(|v| v["gpsOwned"].as_array().cloned()).unwrap_or_default();
assert_eq!(owned.len(), 1, "written once the change is");
}
/// GPS ownership still due when the library closes (the log couldn't be appended) is written once
/// the closing snapshot holds the change, not dropped.
#[test]
fn ownership_due_at_close_is_written_after_the_closing_snapshot() {
let store = Flaky { appends_only: true, ..Default::default() };
let files = MemStore::new();
let mut s = Session::new();
let stores = LibraryStores { dir: "flaky".into(), catalog: Box::new(store.clone()), files: Box::new(files.clone()), on_disk: false };
s.open_library_in(stores, true).unwrap();
let id = s.selection.active.unwrap();
store.set_failing(true);
assert!(s.execute("photo.setGps", &json!({"lat": 1.0, "lon": 2.0})).is_err());
s.close_library().unwrap();
let prefs = files.files.lock().unwrap().get("prefs.json").cloned().unwrap_or_default();
let v: serde_json::Value = serde_json::from_slice(&prefs).unwrap();
assert_eq!(v["gpsOwned"], json!([id.0]), "written after the snapshot");
}
+474
View File
@@ -0,0 +1,474 @@
//! Saved locations (LRC-MAP-LOCATIONS): the commands, their checks and counts (across the
//! antimeridian and around a pole), `locations.json` (saved, reloaded, a damaged or hostile file
//! set aside, never a panic), and private locations stripping the location from exports of the
//! photos inside them, and only those.
use lightcraft_catalog::PhotoId;
use serde_json::{Value, json};
use crate::export::{ExportOptions, export_photo};
use crate::tests::xmp::temp_dir;
use crate::{EngineError, Session};
fn ids(s: &Session, n: usize) -> Vec<PhotoId> {
s.catalog.photos().take(n).map(|p| p.id).collect()
}
fn place(s: &mut Session, id: PhotoId, lat: f64, lon: f64) {
s.execute("photo.setGps", &json!({"ids": [id.0], "lat": lat, "lon": lon})).unwrap();
}
fn add(s: &mut Session, p: Value) -> Value {
s.execute("map.location.add", &p).unwrap()
}
fn listed(s: &mut Session) -> Vec<Value> {
s.execute("map.locations", &json!({})).unwrap()["locations"].as_array().cloned().unwrap_or_default()
}
fn ids_in(s: &mut Session, id: &Value) -> Vec<u64> {
s.execute("map.location.photos", &json!({"id": id})).unwrap()["ids"].as_array().unwrap().iter().filter_map(Value::as_u64).collect()
}
#[test]
fn locations_count_the_photos_inside_them_across_the_antimeridian_and_a_pole() {
let mut s = Session::with_demo();
let p = ids(&s, 7);
// two near the Eiffel Tower, one in London; two either side of ±180° in Fiji; two near the north pole on opposite meridians
for (id, (lat, lon)) in
p.iter().zip([(48.8584, 2.2945), (48.8606, 2.2900), (51.5007, -0.1246), (-17.0, 179.95), (-17.0, -179.95), (89.5, 0.0), (89.5, 180.0)])
{
place(&mut s, *id, lat, lon);
}
let paris = add(&mut s, json!({"name": "Paris", "lat": 48.8584, "lon": 2.2945, "radius": 1000}));
assert_eq!((paris["id"].as_u64(), paris["photos"].as_u64(), paris["private"].as_bool()), (Some(1), Some(2), Some(false)), "{paris}");
let fiji = add(&mut s, json!({"name": "Fiji", "lat": -17.0, "lon": 180.0, "radius": 20000}));
assert_eq!(fiji["photos"], 2, "both sides of the antimeridian: {fiji}");
let pole = add(&mut s, json!({"name": "Pole", "lat": 90.0, "lon": 0.0, "radius": 100000, "private": true}));
assert_eq!(pole["photos"], 2, "around the pole: {pole}");
let all = listed(&mut s);
assert_eq!(all.iter().map(|l| l["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Paris", "Fiji", "Pole"]);
assert_eq!(all.iter().map(|l| l["photos"].as_u64().unwrap()).collect::<Vec<_>>(), [2, 2, 2]);
// the demo shows every photo, so in view = in the library
assert_eq!(all.iter().map(|l| l["inView"].as_u64().unwrap()).collect::<Vec<_>>(), [2, 2, 2]);
let mut want = vec![p[3].0, p[4].0];
want.sort();
assert_eq!(ids_in(&mut s, &fiji["id"]), want);
// the photos in view, in their order
let r = s.execute("map.location.photos", &json!({"id": paris["id"], "inView": true})).unwrap();
assert_eq!(r["count"], 2);
// moving the circle changes what is inside
let r = s.execute("map.location.update", &json!({"id": paris["id"], "lat": 51.5007, "lon": -0.1246, "name": "London"})).unwrap();
assert_eq!((r["name"].as_str(), r["photos"].as_u64()), (Some("London"), Some(1)));
let r = s.execute("map.location.update", &json!({"id": paris["id"], "radius": 400000})).unwrap();
assert_eq!(r["photos"], 3, "London and Paris within 400 km: {r}");
// deleting it leaves the photos alone
let r = s.execute("map.location.remove", &json!({"id": paris["id"]})).unwrap();
assert_eq!(r["name"], "London");
assert_eq!(listed(&mut s).len(), 2);
assert!(s.catalog.photo(p[0]).unwrap().meta.gps.is_some());
// not undo steps: Edit ▸ Undo is still about the photos
assert_eq!(s.undo.last().map(|u| u.label.as_str()), Some("Set GPS Coordinates"));
}
#[test]
fn location_commands_refuse_hostile_values_and_change_nothing() {
let mut s = Session::with_demo();
let home = add(&mut s, json!({"name": "Home", "lat": 10.0, "lon": 10.0, "radius": 50}));
for bad in [
json!({}),
json!({"name": "", "lat": 0, "lon": 0}),
json!({"name": " ", "lat": 0, "lon": 0}),
json!({"name": 5, "lat": 0, "lon": 0}),
json!({"name": "x".repeat(201), "lat": 0, "lon": 0}),
json!({"name": "x", "lat": 90.01, "lon": 0}),
json!({"name": "x", "lat": 0, "lon": -180.5}),
json!({"name": "x", "lat": "north", "lon": 0}),
json!({"name": "x", "lat": 0}),
json!({"name": "x", "lat": 0, "lon": 0, "radius": 0.5}),
json!({"name": "x", "lat": 0, "lon": 0, "radius": 1000001}),
json!({"name": "x", "lat": 0, "lon": 0, "radius": -10}),
json!({"name": "x", "lat": 0, "lon": 0, "private": "yes"}),
json!({"name": "x", "fromSelection": true, "ids": []}),
] {
assert!(matches!(s.execute("map.location.add", &bad), Err(EngineError::BadParams { .. })), "{bad}");
}
// a number too large for f64 isn't a coordinate either
if let Ok(huge) = serde_json::from_str::<Value>(r#"{"name": "x", "lat": 1e400, "lon": 0}"#) {
assert!(s.execute("map.location.add", &huge).is_err());
}
for bad in [
json!({"id": 999}),
json!({"id": "1"}),
json!({"id": home["id"], "radius": 0}),
json!({"id": home["id"], "lat": 100}),
json!({"id": home["id"], "name": ""}),
json!({"id": home["id"], "name": "Ok", "radius": 2000000}),
] {
assert!(matches!(s.execute("map.location.update", &bad), Err(EngineError::BadParams { .. })), "{bad}");
}
assert!(s.execute("map.location.remove", &json!({"id": 999})).is_err());
assert!(s.execute("map.location.photos", &json!({})).is_err());
let all = listed(&mut s);
assert_eq!(all.len(), 1);
assert_eq!((all[0]["name"].as_str(), all[0]["radius"].as_f64()), (Some("Home"), Some(50.0)), "nothing changed");
}
#[test]
fn a_location_made_from_the_selection_holds_its_photos() {
let mut s = Session::with_demo();
let p = ids(&s, 4);
place(&mut s, p[0], 48.8584, 2.2945);
place(&mut s, p[1], 48.8530, 2.3499);
place(&mut s, p[2], 48.8606, 2.3376);
s.execute("library.select", &json!({"ids": [p[0].0, p[1].0, p[2].0, p[3].0]})).unwrap();
let l = add(&mut s, json!({"name": "Paris", "fromSelection": true}));
assert_eq!(l["photos"], 3, "{l}");
let r = l["radius"].as_f64().unwrap();
assert!((2000.0..4000.0).contains(&r), "{l}");
// a selection without positions has nothing to centre on
s.execute("library.select", &json!({"ids": [p[3].0]})).unwrap();
assert!(s.execute("map.location.add", &json!({"name": "Nowhere", "fromSelection": true})).is_err());
// photos further apart than the largest radius are refused, not left outside the circle
place(&mut s, p[3], 40.7484, -73.9857);
s.execute("library.select", &json!({"ids": [p[0].0, p[3].0]})).unwrap();
let before = listed(&mut s).len();
let e = s.execute("map.location.add", &json!({"name": "Paris and New York", "fromSelection": true})).unwrap_err();
assert!(e.to_string().contains("largest radius"), "{e}");
assert_eq!(listed(&mut s).len(), before, "nothing was saved");
}
#[test]
fn locations_are_saved_with_the_library_and_reloaded() {
let dir = temp_dir("locations-persist");
{
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
add(&mut s, json!({"name": "Home", "lat": 48.86, "lon": 2.33, "radius": 300, "private": true}));
let park = add(&mut s, json!({"name": "Park", "lat": 48.85, "lon": 2.29, "radius": 2000}));
add(&mut s, json!({"name": "Gone", "lat": 1.0, "lon": 1.0, "radius": 10}));
s.execute("map.location.update", &json!({"id": park["id"], "name": "Big Park"})).unwrap();
s.execute("map.location.remove", &json!({"id": 3})).unwrap();
s.close_library().unwrap();
}
let text = std::fs::read_to_string(dir.join("locations.json")).unwrap();
assert!(text.contains("\"Big Park\"") && !text.contains("Gone"), "{text}");
assert!(!dir.join("locations.json.part").exists());
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
assert!(s.take_library_warnings().is_empty());
let all = listed(&mut s);
assert_eq!(all.iter().map(|l| l["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Home", "Big Park"]);
assert_eq!(all[0]["private"], true);
// a new one gets a fresh id: not the deleted "Gone"'s 3, even after the reopen
let l = add(&mut s, json!({"name": "New", "lat": 0.0, "lon": 0.0}));
assert!(l["id"].as_u64().is_some_and(|id| id > 3), "{l}");
assert_eq!(l["radius"].as_f64(), Some(1000.0));
drop(s);
// another library has its own (none)
let other = temp_dir("locations-other");
let mut s = Session::new().with_fs();
s.open_library(&other, false).unwrap();
assert!(listed(&mut s).is_empty());
drop(s);
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&other);
}
fn corrupt_copies(dir: &std::path::Path) -> Vec<String> {
std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.filter(|n| n.starts_with("locations.json.corrupt-"))
.collect()
}
#[test]
fn a_damaged_locations_file_is_set_aside_and_the_library_opens() {
let dir = temp_dir("locations-damaged");
let bad = br#"{"version": 1, "locations": [{"id": 1, "name": "Ho"#;
std::fs::write(dir.join("locations.json"), bad).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, true).unwrap();
assert!(listed(&mut s).is_empty());
let kept = corrupt_copies(&dir);
assert_eq!(kept.len(), 1, "{kept:?}");
assert_eq!(std::fs::read(dir.join(&kept[0])).unwrap(), bad);
let w = s.take_library_warnings();
assert!(w.iter().any(|w| w.contains("locations.json is damaged")), "{w:?}");
assert!(s.catalog.photos().next().is_some(), "the library itself is fine");
// saving goes on
add(&mut s, json!({"name": "Home", "lat": 1.0, "lon": 1.0}));
assert!(std::fs::read_to_string(dir.join("locations.json")).unwrap().contains("Home"));
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hostile_entries_are_left_out_and_the_file_kept_aside() {
let dir = temp_dir("locations-hostile");
let mut entries = vec![
json!({"id": 1, "name": "Good", "lat": 48.0, "lon": 2.0, "radius": 100.0, "private": true}),
json!({"id": 2, "name": "NaN-ish", "lat": "NaN", "lon": 2.0, "radius": 100.0}),
json!({"id": 3, "name": "Huge", "lat": 1e308, "lon": 2.0, "radius": 100.0}),
json!({"id": 4, "name": "", "lat": 1.0, "lon": 2.0, "radius": 100.0}),
json!({"id": 5, "name": "Zero", "lat": 1.0, "lon": 2.0, "radius": 0}),
json!({"id": 1, "name": "Same id", "lat": 1.0, "lon": 2.0, "radius": 100.0}),
json!({"id": 18446744073709551615u64, "name": "Max id", "lat": 1.0, "lon": 2.0, "radius": 100.0}),
json!([1, 2, 3]),
];
// and thousands of good ones
for i in 0..3000u64 {
entries
.push(json!({"id": 100 + i, "name": format!("L{i}"), "lat": (i % 170) as f64 - 85.0, "lon": (i % 359) as f64 - 179.0, "radius": 5000.0}));
}
let text = serde_json::to_string(&json!({"version": 99, "locations": entries})).unwrap();
std::fs::write(dir.join("locations.json"), &text).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, true).unwrap();
let all = listed(&mut s);
assert_eq!(all.len(), 3001);
assert_eq!((all[0]["name"].as_str(), all[0]["private"].as_bool()), (Some("Good"), Some(true)));
let w = s.take_library_warnings();
assert!(w.iter().any(|w| w.contains("7 saved location(s)")), "{w:?}");
let kept = corrupt_copies(&dir);
assert_eq!(kept.len(), 1);
assert_eq!(std::fs::read_to_string(dir.join(&kept[0])).unwrap(), text);
// counting thousands of locations over the library stays quick
let r = s.execute("map.locations", &json!({})).unwrap();
eprintln!("3001 locations counted in {} ms", r["countMs"]);
assert!(r["countMs"].as_f64().unwrap() < 2000.0, "{}", r["countMs"]);
drop(s);
// the good ones were written back: opening again finds nothing to set aside or warn about
let mut s = Session::new().with_fs();
s.open_library(&dir, true).unwrap();
assert_eq!(listed(&mut s).len(), 3001);
assert!(s.take_library_warnings().iter().all(|w| !w.contains("locations.json")));
assert_eq!(corrupt_copies(&dir).len(), 1, "no second copy");
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_locations_file_that_cant_be_read_is_never_overwritten() {
let dir = temp_dir("locations-unreadable");
// a folder where the file should be: reading fails
std::fs::create_dir_all(dir.join("locations.json")).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
assert!(listed(&mut s).is_empty());
// a change is refused before anything changes (it could never be saved), and says why
let e = s.execute("map.location.add", &json!({"name": "Home", "lat": 1.0, "lon": 1.0})).unwrap_err();
assert!(e.to_string().contains("reopen the library"), "{e}");
assert!(listed(&mut s).is_empty(), "nothing lives only in memory");
assert!(dir.join("locations.json").is_dir(), "never overwritten");
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
fn exported_gps(s: &mut Session, id: PhotoId, o: &ExportOptions) -> (Option<lightcraft_meta::Gps>, Option<String>) {
let e = export_photo(s, id, o, 1).unwrap();
let m = lightcraft_meta::extract(&e.bytes);
(m.gps, m.city)
}
#[test]
fn photos_in_a_private_location_are_exported_without_their_location() {
let mut s = Session::with_demo();
let p = ids(&s, 3);
// home (private), the park (public, overlapping home's edge… not quite), elsewhere
place(&mut s, p[0], 48.8600, 2.3300);
place(&mut s, p[1], 48.8584, 2.2945);
place(&mut s, p[2], 40.7484, -73.9857);
for id in &p {
s.execute("photo.setMeta", &json!({"ids": [id.0], "city": "Somewhere"})).unwrap();
}
let o = ExportOptions::from_json(&json!({"format": "jpeg", "width": 64, "height": 64}));
// before: every photo keeps its location
assert!(exported_gps(&mut s, p[0], &o).0.is_some());
add(&mut s, json!({"name": "Home", "lat": 48.8601, "lon": 2.3302, "radius": 200, "private": true}));
add(&mut s, json!({"name": "Park", "lat": 48.8584, "lon": 2.2945, "radius": 500}));
let (gps, city) = exported_gps(&mut s, p[0], &o);
assert!(gps.is_none() && city.is_none(), "inside the private location: no location at all ({gps:?}, {city:?})");
let (gps, city) = exported_gps(&mut s, p[1], &o);
let g = gps.expect("a public location changes nothing");
assert!((g.latitude - 48.8584).abs() < 1e-4 && city.as_deref() == Some("Somewhere"));
assert!(exported_gps(&mut s, p[2], &o).0.is_some(), "outside every location");
// the photo keeps its position in the library
assert!(s.catalog.photo(p[0]).unwrap().meta.gps.is_some());
// made public again, the location is exported again
s.execute("map.location.update", &json!({"id": 1, "private": false})).unwrap();
assert!(exported_gps(&mut s, p[0], &o).0.is_some());
s.execute("map.location.update", &json!({"id": 1, "private": true})).unwrap();
assert!(exported_gps(&mut s, p[0], &o).0.is_none());
s.execute("map.location.remove", &json!({"id": 1})).unwrap();
assert!(exported_gps(&mut s, p[0], &o).0.is_some());
}
/// The library's prefs.json of an older build, with `savedLocations` (string ids, `isPrivate`).
fn old_prefs(dir: &std::path::Path) {
let prefs = json!({"savedLocations": [
{"id": "loc-1", "name": "Home", "lat": 48.86, "lon": 2.33, "radius": 200.0, "isPrivate": true},
{"id": "loc-2", "name": "Bad", "lat": 95.0, "lon": 2.33, "radius": 200.0, "isPrivate": false},
{"id": "loc-3", "name": "Office", "lat": 48.87, "lon": 2.35, "radius": 500.0, "isPrivate": false}
]});
std::fs::write(dir.join("prefs.json"), serde_json::to_vec(&prefs).unwrap()).unwrap();
}
/// A library of an older build: its prefs.json saved locations move to locations.json once, are
/// read back to confirm, and only then left out of prefs.json; a bad entry is reported.
#[test]
fn old_prefs_locations_move_to_locations_json_once() {
let dir = temp_dir("locations-migrate");
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
drop(s);
old_prefs(&dir);
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
let names: Vec<String> = listed(&mut s).iter().map(|l| l["name"].as_str().unwrap().to_string()).collect();
assert_eq!(names, vec!["Home", "Office"], "the valid ones, in order");
assert_eq!(listed(&mut s)[0]["private"], true, "isPrivate becomes private");
assert!(s.take_library_warnings().iter().any(|w| w.contains("prefs.json") && w.contains("1 saved location")), "the bad one is reported");
let file: Value = serde_json::from_slice(&std::fs::read(dir.join("locations.json")).unwrap()).unwrap();
assert_eq!(file["locations"].as_array().unwrap().len(), 2, "written to locations.json at once");
// confirmed: the next save of prefs.json leaves the old field out
s.execute("library.preferences", &json!({})).ok();
s.save_prefs().unwrap();
let prefs: Value = serde_json::from_slice(&std::fs::read(dir.join("prefs.json")).unwrap()).unwrap();
assert!(prefs.get("savedLocations").is_none(), "{prefs}");
drop(s);
// reopened: from locations.json, same list
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
assert_eq!(listed(&mut s).len(), 2);
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
/// Both files present: locations.json wins and the old field is not taken over again.
#[test]
fn locations_json_wins_over_old_prefs() {
let dir = temp_dir("locations-both");
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
add(&mut s, json!({"name": "New", "lat": 10.0, "lon": 10.0}));
drop(s);
old_prefs(&dir);
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
let names: Vec<String> = listed(&mut s).iter().map(|l| l["name"].as_str().unwrap().to_string()).collect();
assert_eq!(names, vec!["New"]);
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
/// locations.json damaged while the old field is there too: the damaged file is set aside and the
/// old copy is taken over as when there is no file (confirmed in a new locations.json), so a
/// location saved later can't leave the old ones behind in a prefs.json that drops them.
#[test]
fn a_corrupt_locations_json_with_old_prefs_takes_the_old_copy_over() {
let dir = temp_dir("locations-corrupt-migrate");
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
drop(s);
old_prefs(&dir);
std::fs::write(dir.join("locations.json"), b"{ not json").unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
let names = |s: &mut Session| listed(s).iter().map(|l| l["name"].as_str().unwrap_or("").to_string()).collect::<Vec<_>>();
assert_eq!(names(&mut s), ["Home", "Office"], "the old copy, taken over");
assert!(!corrupt_copies(&dir).is_empty(), "the damaged file is kept aside");
let file: Value = serde_json::from_slice(&std::fs::read(dir.join("locations.json")).unwrap()).unwrap();
assert_eq!(file["locations"].as_array().map(Vec::len), Some(2), "confirmed in a new locations.json");
// a location saved now keeps them, and reopening finds all three
s.execute("map.location.add", &serde_json::json!({"name": "New", "lat": 1.0, "lon": 2.0})).unwrap();
s.save_prefs().unwrap();
drop(s);
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
assert_eq!(names(&mut s), ["Home", "Office", "New"]);
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
/// `locations.json` reads well twice (the open's check and parse), then fails: the copy kept aside
/// before writing back the valid entries can't be made.
#[derive(Clone, Default)]
struct ReadsTwice {
files: lightcraft_catalog::MemStore,
reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl lightcraft_catalog::Store for ReadsTwice {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
if name == "locations.json" && self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2 {
return Err(std::io::Error::other("locked by another process"));
}
self.files.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.files.write_atomic(name, data)
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.files.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.files.truncate(name, len)
}
fn describe(&self) -> String {
"reads-twice".into()
}
}
#[test]
fn hostile_entries_are_never_dropped_without_a_copy() {
let files = ReadsTwice::default();
let text = serde_json::to_vec(&json!({"version": 1, "locations": [
{"id": 1, "name": "Good", "lat": 48.0, "lon": 2.0, "radius": 100.0},
{"id": 2, "name": "Bad", "lat": 1e308, "lon": 2.0, "radius": 100.0},
]}))
.unwrap();
files.files.set("locations.json", text.clone());
let mut s = Session::new();
let stores = crate::library::LibraryStores {
dir: "reads-twice".into(),
catalog: Box::new(lightcraft_catalog::MemStore::new()),
files: Box::new(files.clone()),
on_disk: false,
};
s.open_library_in(stores, true).unwrap();
assert_eq!(listed(&mut s).len(), 1);
let w = s.take_library_warnings();
assert!(w.iter().any(|w| w.contains("couldn't be set aside") && w.contains("won't overwrite")), "{w:?}");
assert_eq!(files.files.get("locations.json"), Some(text), "the file with the rejected entry is left as it was");
// and a later change is refused, saying why (the file is never overwritten)
let e = s.execute("map.location.add", &json!({"name": "Home", "lat": 1.0, "lon": 1.0})).unwrap_err();
assert!(e.to_string().contains("isn't overwritten"), "{e}");
assert_eq!(listed(&mut s).len(), 1, "nothing lives only in memory");
}
/// prefs.json unreadable at open is never written; a change that needs it (which photos' GPS is
/// LightCraft's) is reported as unsaved rather than dropped silently, and closing still works
/// (retrying can't help, so it doesn't hold the library open).
#[test]
fn a_change_for_an_unreadable_prefs_json_is_reported_not_silently_dropped() {
let dir = temp_dir("prefs-unreadable");
{
let mut s = Session::new().with_fs();
s.open_library(&dir, true).unwrap();
s.close_library().unwrap();
}
let _ = std::fs::remove_file(dir.join("prefs.json"));
std::fs::create_dir_all(dir.join("prefs.json")).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&dir, false).unwrap();
let id = s.visible_cloned()[0];
s.execute("photo.setGps", &json!({"ids": [id.0], "lat": 1.0, "lon": 2.0})).unwrap();
let (_, why) = s.unsaved().expect("reported as unsaved");
assert!(why.contains("prefs.json"), "{why}");
s.close_library().unwrap();
assert!(dir.join("prefs.json").is_dir(), "never overwritten");
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
+201
View File
@@ -0,0 +1,201 @@
//! The Map view's track log (`map.trackLog`): loading, tracks and the active one, the time zone
//! offset, clearing, refused files (the loaded log stays), and tagging from it
//! (`photo.autoTagTracklog {loaded: true}`) in one undo step.
use lightcraft_catalog::{Op, PhotoId};
use serde_json::json;
use crate::{EngineError, Session};
/// Two tracks: "Walk" (two segments, 10:00–10:02 and 12:00–12:01 UTC) and "Ride" (14:00–14:10).
pub(crate) const TWO_TRACKS: &str = r#"<?xml version="1.0"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
<trk><name>Walk</name>
<trkseg>
<trkpt lat="46.0000" lon="7.0000"><time>2026-05-01T10:00:00Z</time></trkpt>
<trkpt lat="46.0010" lon="7.0020"><time>2026-05-01T10:01:00Z</time></trkpt>
<trkpt lat="46.0020" lon="7.0040"><time>2026-05-01T10:02:00Z</time></trkpt>
</trkseg>
<trkseg>
<trkpt lat="46.1000" lon="7.1000"><time>2026-05-01T12:00:00Z</time></trkpt>
<trkpt lat="46.1010" lon="7.1010"><time>2026-05-01T12:01:00Z</time></trkpt>
</trkseg>
</trk>
<trk><name>Ride</name><trkseg>
<trkpt lat="47.0000" lon="8.0000"><time>2026-05-01T14:00:00Z</time></trkpt>
<trkpt lat="47.1000" lon="8.1000"><time>2026-05-01T14:10:00Z</time></trkpt>
</trkseg></trk>
</gpx>"#;
fn temp_dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-tracklog-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn refused(r: crate::Result<serde_json::Value>) -> String {
match r {
Err(EngineError::BadParams { msg, .. }) => msg,
other => panic!("refused, not {other:?}"),
}
}
#[test]
fn load_report_pick_a_track_set_the_offset_and_clear() {
let dir = temp_dir("load");
let path = dir.join("trip.gpx");
std::fs::write(&path, TWO_TRACKS).unwrap();
let mut s = Session::new();
assert_eq!(s.execute("map.trackLog", &json!({})).unwrap()["loaded"], false);
let r = s.execute("map.trackLog", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!((r["loaded"].as_bool(), r["name"].as_str(), r["points"].as_u64()), (Some(true), Some("trip.gpx"), Some(7)), "{r}");
let tracks = r["tracks"].as_array().unwrap();
assert_eq!(tracks.len(), 2);
assert_eq!((tracks[0]["name"].as_str(), tracks[0]["points"].as_u64(), tracks[0]["segments"].as_u64()), (Some("Walk"), Some(5), Some(2)));
assert_eq!((tracks[1]["start"].as_str(), tracks[1]["end"].as_str()), (Some("2026-05-01T14:00:00Z"), Some("2026-05-01T14:10:00Z")));
assert_eq!(tracks[1]["duration"], 600.0);
// all tracks are active at first: the whole file's time range, in UTC (no offset yet)
assert!(r["active"].is_null());
assert_eq!((r["start"].as_str(), r["end"].as_str()), (Some("2026-05-01T10:00:00Z"), Some("2026-05-01T14:10:00Z")));
assert_eq!(r["startLocal"], "2026-05-01T10:00:00");
assert_eq!(s.map.track.as_ref().unwrap().shapes.len(), 2, "each track ready to draw");
let g0 = r["generation"].as_u64().unwrap();
// pick the second track, and the camera's zone: the local times follow
let r = s.execute("map.trackLog", &json!({"active": 1, "offset": "+02:00"})).unwrap();
assert_eq!((r["active"].as_u64(), r["activePoints"].as_u64(), r["offset"].as_str()), (Some(1), Some(2), Some("+02:00")), "{r}");
assert_eq!((r["startLocal"].as_str(), r["endLocal"].as_str()), (Some("2026-05-01T16:00:00"), Some("2026-05-01T16:10:00")));
assert!(r["generation"].as_u64().unwrap() > g0);
let r = s.execute("map.trackLog", &json!({"active": "all", "offset": -5.5})).unwrap();
assert_eq!((r["active"].is_null(), r["offset"].as_str()), (true, Some("-05:30")));
let r = s.execute("map.trackLog", &json!({"offset": null})).unwrap();
assert!(r["offset"].is_null());
// a report changes nothing
let g = r["generation"].clone();
assert_eq!(s.execute("map.trackLog", &json!({})).unwrap()["generation"], g);
// clear
let r = s.execute("map.trackLog", &json!({"clear": true})).unwrap();
assert_eq!(r["loaded"], false);
assert!(s.map.track.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
/// A track name in Latin-1 (a byte that isn't UTF-8) doesn't refuse the file: it loads, the
/// name read with �, as photo.autoTagTracklog always read a GPX.
#[test]
fn a_gpx_with_a_byte_that_isnt_utf8_still_loads() {
let dir = temp_dir("latin1");
let mut s = Session::with_demo();
let path = dir.join("latin1.gpx");
let mut bytes = TWO_TRACKS.as_bytes().to_vec();
let at = TWO_TRACKS.find("<name>").expect("a track name") + "<name>".len();
bytes.insert(at, 0xE9); // é in Latin-1
std::fs::write(&path, &bytes).unwrap();
let r = s.execute("map.trackLog", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(r["loaded"], true, "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn bad_files_are_refused_and_the_loaded_log_stays() {
let dir = temp_dir("bad");
let mut s = Session::with_demo();
let one = s.catalog.photos().next().unwrap().id.0;
s.execute("map.trackLog", &json!({"gpx": TWO_TRACKS})).unwrap();
let g = s.map.track_generation;
let huge = dir.join("huge.gpx");
let f = std::fs::File::create(&huge).unwrap();
f.set_len(crate::tracklog::MAX_GPX_BYTES + 1).unwrap();
drop(f);
let binary = dir.join("bin.gpx");
std::fs::write(&binary, [0xffu8, 0xfe, 0x00, 0x81]).unwrap();
let cases = [
(json!({"path": huge.to_string_lossy()}), "larger than 50 MB"),
(json!({"path": dir.join("missing.gpx").to_string_lossy()}), "can't read"),
(json!({"path": dir.to_string_lossy()}), "not a file"),
// (read as text, its bytes that aren't UTF-8 as �: it holds no GPX)
(json!({"path": binary.to_string_lossy()}), "not a GPX file"),
(json!({"gpx": "<kml><Document/></kml>"}), "not a GPX file"),
(json!({"gpx": "<gpx version=\"1.1\"/>"}), "no tracks"),
(json!({"gpx": "<gpx><trk><trkseg/></trk></gpx>"}), "no track points"),
(json!({"gpx": "<gpx><trk><trkseg><trkpt lat=\"1\" lon=\"2\"/></trkseg></trk></gpx>"}), "no timed track points (1 without a time)"),
(
json!({"gpx": "<gpx><trk><trkseg><trkpt lat=\"NaN\" lon=\"2\"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk></gpx>"}),
"no track points",
),
// an unclosed document is refused as malformed before its points are counted
(json!({"gpx": "<gpx><trk>"}), "malformed"),
(
json!({"gpx": "<gpx><trk><trkseg><trkpt lat=\"1\" lon=\"2\"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk><!-- never closed"}),
"malformed",
),
(json!({"gpx": 5}), "`path` is a file path"),
(json!({"active": 2}), "no track 2"),
(json!({"active": -1}), "track's index"),
(json!({"offset": "noon"}), "can't read offset"),
(json!({"offset": 19}), "±18"),
(json!({"offset": "+19:00"}), "offset"),
(json!({"clear": true, "active": 0}), "alone"),
(json!({"clear": "yes"}), "true or false"),
(json!({"gpx": TWO_TRACKS, "active": 5}), "no track 5"),
];
for (p, why) in cases {
let msg = refused(s.execute("map.trackLog", &p));
assert!(msg.contains(why), "{p}: {msg}");
assert_eq!(s.map.track_generation, g, "{p} changed nothing");
assert_eq!(s.map.track.as_ref().map(|t| t.tracks.len()), Some(2));
}
// nothing loaded: picking a track or an offset has nothing to act on
s.execute("map.trackLog", &json!({"clear": true})).unwrap();
assert!(refused(s.execute("map.trackLog", &json!({"active": 0}))).contains("no track log"));
assert!(refused(s.execute("map.trackLog", &json!({"offset": 2}))).contains("no track log"));
assert!(refused(s.execute("photo.autoTagTracklog", &json!({"loaded": true, "ids": [one]}))).contains("no track log"));
// the existing command keeps the larger bound it always had: a file past the Map view's 50 MB is read
// (here it holds no GPX), one past 256 MB is refused
let msg = refused(s.execute("photo.autoTagTracklog", &json!({"path": huge.to_string_lossy(), "ids": [one]})));
assert!(!msg.contains("larger than"), "{msg}");
let enormous = dir.join("enormous.gpx");
let f = std::fs::File::create(&enormous).unwrap();
f.set_len((256 << 20) + 1).unwrap();
drop(f);
assert!(refused(s.execute("photo.autoTagTracklog", &json!({"path": enormous.to_string_lossy(), "ids": [one]}))).contains("256 MB"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn auto_tag_from_the_loaded_track_uses_its_active_track_and_offset_in_one_undo_step() {
let mut s = Session::with_demo();
let ids: Vec<u64> = s.visible_cloned().iter().take(3).map(|p| p.0).collect();
let set = |s: &mut Session, id: u64, t: &str| {
s.commit("t", Op::SetCaptured { id: PhotoId(id), captured: Some(t.into()) }).unwrap();
s.execute("photo.removeGps", &json!({"ids": [id]})).unwrap();
};
set(&mut s, ids[0], "2026-05-01T12:00:30"); // +02:00 camera: 10:00:30 UTC, the walk
set(&mut s, ids[1], "2026-05-01T16:05:00"); // 14:05 UTC, half-way along the ride
set(&mut s, ids[2], "2026-05-01T14:00:30"); // 12:00:30 UTC, the walk's second segment
s.execute("map.trackLog", &json!({"gpx": TWO_TRACKS, "offset": "+02:00", "active": 1})).unwrap();
let gps = |s: &Session, id: u64| s.catalog.photo(PhotoId(id)).unwrap().meta.gps;
// a dry run: only the ride's photo falls on the active track
let r = s.execute("photo.autoTagTracklog", &json!({"loaded": true, "ids": ids, "dryRun": true})).unwrap();
assert_eq!((r["tagged"].as_u64(), r["skipped"]["outside"].as_u64(), r["points"].as_u64()), (Some(1), Some(2), Some(2)), "{r}");
// all tracks: the three, each where the log says it was (interpolated within its segment)
s.execute("map.trackLog", &json!({"active": "all"})).unwrap();
s.execute("library.select", &json!({"ids": ids})).unwrap();
let depth = s.undo.len();
let r = s.execute("photo.autoTagTracklog", &json!({"loaded": true})).unwrap();
assert_eq!((r["tagged"].as_u64(), r["assumedUtc"].as_u64()), (Some(3), Some(0)), "the track's offset counts: {r}");
assert_eq!(s.undo.len(), depth + 1, "one undo step");
let log = s.map.track.as_ref().unwrap().log.clone();
let t = |iso: &str| lightcraft_meta::DateTime::parse_iso(iso).unwrap().unix_seconds() as f64;
for (id, utc) in ids.iter().zip(["2026-05-01T10:00:30Z", "2026-05-01T14:05:00Z", "2026-05-01T12:00:30Z"]) {
let (want, _) = log.locate(t(utc), 600.0).unwrap();
let (la, lo) = gps(&s, *id).unwrap();
assert!((la - want.latitude).abs() < 1e-6 && (lo - want.longitude).abs() < 1e-6, "{id}: {la},{lo} vs {want:?}");
}
assert_eq!(gps(&s, ids[1]), Some((47.05, 8.05)));
// an offset given to the command wins over the track's
let r = s.execute("photo.autoTagTracklog", &json!({"loaded": true, "offset": 0, "replace": true, "dryRun": true})).unwrap();
assert_eq!(r["tagged"], 2, "two hours later on the log's clock: {r}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(ids.iter().all(|i| gps(&s, *i).is_none()), "one step undoes them all");
}
+110
View File
@@ -1793,6 +1793,116 @@ fn gps_typed_in_is_saved_to_xmp() {
assert!(s.catalog.photo(id).unwrap().meta.gps.is_none());
}
/// Geotagging from the map (`photo.setGps`, `photo.removeGps`) writes the position to the sidecar
/// as EXIF GPS in XMP; removing it, or undoing the geotag, removes it from the sidecar (before,
/// the old position stayed there: GPS was replaced only by a new value). Ported from PR #810.
#[test]
fn map_geotag_writes_gps_to_the_sidecar_and_removing_or_undoing_takes_it_out() {
let src = temp_dir("geotag");
let lib = temp_dir("geotag-lib");
write_png(&src.join("g.png"), 7);
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap();
let id = only(&s);
let sidecar = src.join("g.xmp");
let gps_in = |p: &Path| std::fs::read_to_string(p).ok().and_then(|x| lightcraft_meta::parse_xmp(&x).ok()).and_then(|m| m.metadata.gps);
s.execute("photo.setGps", &json!({"ids": [id.0], "lat": -33.8568, "lon": 151.2153})).unwrap();
let g = gps_in(&sidecar).expect("GPS written to the sidecar");
assert!((g.latitude + 33.8568).abs() < 1e-5 && (g.longitude - 151.2153).abs() < 1e-5, "{g:?}");
s.execute("photo.removeGps", &json!({"ids": [id.0]})).unwrap();
assert!(sidecar.is_file());
assert!(gps_in(&sidecar).is_none(), "removed from the sidecar");
s.execute("edit.undo", &json!({})).unwrap();
assert!(gps_in(&sidecar).is_some_and(|g| (g.latitude + 33.8568).abs() < 1e-5), "undo writes it back");
// undoing the geotag itself takes the position out of the sidecar again
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.catalog.photo(id).unwrap().meta.gps.is_none());
assert!(gps_in(&sidecar).is_none(), "an undone geotag leaves no GPS in the sidecar");
let _ = std::fs::remove_dir_all(&src);
let _ = std::fs::remove_dir_all(&lib);
}
/// A position cleared with automatic writing off still leaves the sidecar when it is saved after
/// the library was closed and opened again: which photos' GPS is LightCraft's is kept with the
/// library (`prefs.json` `gpsOwned`), not only for the session.
#[test]
fn a_cleared_position_leaves_the_sidecar_after_a_reopen() {
let src = temp_dir("geotag-reopen");
let lib = temp_dir("geotag-reopen-lib");
write_png(&src.join("g.png"), 9);
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
let id = only(&s);
let sidecar = src.join("g.xmp");
let gps_in = |p: &Path| std::fs::read_to_string(p).ok().and_then(|x| lightcraft_meta::parse_xmp(&x).ok()).and_then(|m| m.metadata.gps);
s.execute("photo.setGps", &json!({"ids": [id.0], "lat": 45.0, "lon": 6.0})).unwrap();
s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap();
assert!(gps_in(&sidecar).is_some());
// cleared, not written (automatic writing is off), and the library closed
s.execute("photo.removeGps", &json!({"ids": [id.0]})).unwrap();
assert!(gps_in(&sidecar).is_some(), "not written yet");
drop(s);
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
assert!(s.gps_edited.contains(&id), "kept with the library");
s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap();
assert!(gps_in(&sidecar).is_none(), "the cleared position leaves the sidecar");
drop(s);
// a damaged entry costs only itself
let prefs = lib.join("prefs.json");
let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&prefs).unwrap()).unwrap();
v["gpsOwned"] = json!(["x", -1, 1e300, id.0, 987_654_321]);
std::fs::write(&prefs, serde_json::to_vec(&v).unwrap()).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
assert_eq!(s.gps_edited.iter().copied().collect::<Vec<_>>(), vec![id], "only this library's photos");
assert!(s.take_library_warnings().is_empty());
drop(s);
let _ = std::fs::remove_dir_all(&src);
let _ = std::fs::remove_dir_all(&lib);
}
/// A photo whose position LightCraft never touched keeps another app's sidecar GPS when its
/// sidecar is rewritten; and photo ids are per library, so a geotag in one library doesn't make
/// the same id's photo in the next one claim its sidecar's GPS. Ported from PR #810.
#[test]
fn foreign_sidecar_gps_stays_for_photos_never_geotagged_here() {
let src_a = temp_dir("geotag-a");
let src_b = temp_dir("geotag-b");
let (lib_a, lib_b) = (temp_dir("geotag-lib-a"), temp_dir("geotag-lib-b"));
write_png(&src_a.join("a.png"), 3);
write_png(&src_b.join("b.png"), 4);
let mut s = Session::new().with_fs();
s.open_library(&lib_a, false).unwrap();
s.execute("library.import", &json!({"paths": [src_a.to_string_lossy()]})).unwrap();
let id_a = only(&s);
s.execute("photo.setGps", &json!({"ids": [id_a.0], "lat": 10.0, "lon": 20.0})).unwrap();
s.open_library(&lib_b, false).unwrap();
s.execute("library.import", &json!({"paths": [src_b.to_string_lossy()]})).unwrap();
let id_b = only(&s);
assert_eq!(id_a, id_b, "the test needs the same id in both libraries");
assert!(s.catalog.photo(id_b).unwrap().meta.gps.is_none());
// another app put a position in the new photo's sidecar
let foreign = lightcraft_meta::Metadata {
gps: Some(lightcraft_meta::Gps { latitude: -33.8568, longitude: 151.2153, altitude: None }),
..Default::default()
};
let sidecar = src_b.join("b.xmp");
std::fs::write(&sidecar, lightcraft_meta::write_xmp(&foreign, None)).unwrap();
s.execute("library.xmpPreferences", &json!({"autoWrite": true})).unwrap();
s.execute("photo.rate", &json!({"ids": [id_b.0], "rating": 3})).unwrap();
let back = lightcraft_meta::parse_xmp(&std::fs::read_to_string(&sidecar).unwrap()).unwrap();
assert_eq!(back.metadata.rating, Some(3), "the sidecar was written");
let g = back.metadata.gps.expect("the other app's GPS stays");
assert!((g.latitude + 33.8568).abs() < 1e-5, "{g:?}");
for d in [src_a, src_b, lib_a, lib_b] {
let _ = std::fs::remove_dir_all(d);
}
}
/// DNG export compression: lossless, zip and none all decode; none is the biggest.
#[test]
fn dng_export_compression_choices() {
+352
View File
@@ -0,0 +1,352 @@
//! The GPS track log loaded into the Map view (Lightroom Classic's Map ▸ Tracklog): session state,
//! never saved in the catalog. `map.trackLog` loads a GPX file (or text), picks the active track
//! of a file that has several, sets the camera's time zone offset and clears it;
//! `photo.autoTagTracklog {loaded: true}` tags photos from the active track with that offset.
//!
//! A file is read whole, so it is bounded: [`MAX_GPX_BYTES`] on disk (or as text) and
//! [`MAX_TRACK_POINTS`] timed points; past either the load is refused with an error saying so, and
//! the track already loaded stays. Each track is projected and ranked for drawing once, here
//! ([`TrackShape`]), so the map only filters and clips per frame.
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::map::TrackShape;
use lightcraft_meta::{DateTime, Tracklog, parse_gpx};
use serde_json::{Value, json};
use crate::cmd::bad;
use crate::{Result, Session};
/// Largest GPX file loaded (bytes).
pub const MAX_GPX_BYTES: u64 = 50 * 1024 * 1024;
/// Most timed track points loaded.
pub const MAX_TRACK_POINTS: usize = 2_000_000;
/// Default `maxGap` of tagging (seconds): how far from a logged point a photo may be.
pub const DEFAULT_MAX_GAP: f64 = 600.0;
/// One `<trk>` of the loaded file.
#[derive(Clone, Debug)]
pub struct TrackSummary {
/// Its `<name>` (empty when it has none).
pub name: String,
/// Timed points, and continuous logging spans with points.
pub points: usize,
pub segments: usize,
/// First and last point times (seconds since the epoch, UTC); `None` for an empty track.
pub span: Option<(f64, f64)>,
}
/// The loaded track log (see the module docs).
#[derive(Debug)]
pub struct LoadedTrack {
/// The file it came from (`None`: loaded from text).
pub path: Option<String>,
/// Its file name (or "GPX").
pub name: String,
pub log: Arc<Tracklog>,
pub tracks: Vec<TrackSummary>,
/// Each track's lines, ready to draw (one per `<trk>`, in file order).
pub shapes: Vec<Arc<TrackShape>>,
/// The track tagging uses and the map highlights; `None`: all of them.
pub active: Option<usize>,
/// The points tagging uses (the active track's, or all).
pub active_log: Arc<Tracklog>,
/// The camera clock's offset from UTC in minutes (east positive) for photos whose capture time
/// has no zone; `None`: read them as UTC.
pub offset_minutes: Option<i64>,
/// Time to parse, project and rank (ms).
pub load_ms: f64,
}
impl LoadedTrack {
/// The active track's (or all tracks') first and last point times, UTC.
pub fn span(&self) -> Option<(f64, f64)> {
self.active_log.span()
}
fn set_active(&mut self, active: Option<usize>) {
self.active = active;
self.active_log = match active.and_then(|i| self.log.only_track(i)) {
Some(one) => Arc::new(one),
None => self.log.clone(),
};
}
}
/// A capture time in UTC seconds: its recorded zone wins, else `offset` minutes east of UTC
/// (none: read as UTC).
pub(crate) fn capture_utc(dt: &DateTime, offset: Option<i64>) -> f64 {
let secs = match dt.offset_minutes {
Some(_) => dt.unix_seconds(),
None => dt.unix_seconds().saturating_sub(offset.unwrap_or(0).saturating_mul(60)),
};
secs as f64 + f64::from(dt.millis) / 1000.0
}
/// A position as tagging stores it (7 decimals, about a centimetre).
pub(crate) fn rounded(g: &lightcraft_meta::Gps) -> (f64, f64) {
((g.latitude * 1e7).round() / 1e7, (g.longitude * 1e7).round() / 1e7)
}
/// Where `photo.autoTagTracklog {loaded: true, replace: true}` would put each of `ids` (those
/// with a capture time within the active track's reach): the same reading of capture times, the
/// track's offset and the default 10-minute gap. Nothing is written or journaled (the map's marks).
pub fn positions(s: &Session, ids: &[lightcraft_catalog::PhotoId]) -> Vec<(u64, f64, f64)> {
let Some(t) = s.map.track.as_ref() else { return Vec::new() };
ids.iter()
.filter_map(|id| {
let dt = s.catalog.photo(*id)?.captured.as_deref().and_then(DateTime::parse_iso)?;
let (g, _) = t.active_log.locate(capture_utc(&dt, t.offset_minutes), DEFAULT_MAX_GAP)?;
let (lat, lon) = rounded(&g);
Some((id.0, lat, lon))
})
.collect()
}
/// Seconds as an ISO date-time (no zone) at `offset` minutes from UTC.
pub fn iso(t: f64, offset: i64) -> String {
lightcraft_catalog::dates::civil((t.floor() as i64).saturating_add(offset.saturating_mul(60)))
}
/// `+02:00` for 120 minutes.
pub fn fmt_offset(minutes: i64) -> String {
let sign = if minutes < 0 { '-' } else { '+' };
let m = minutes.unsigned_abs();
format!("{sign}{:02}:{:02}", m / 60, m % 60)
}
/// A camera time zone offset parameter: `+HH:MM` text or a number of hours (at most ±18).
/// `Ok(None)`: empty or null (zone-less capture times are read as UTC).
pub(crate) fn parse_offset(cmd: &str, v: &Value) -> Result<Option<i64>> {
match v {
Value::Null => Ok(None),
Value::String(o) if o.trim().is_empty() => Ok(None),
Value::Number(h) => {
let h = h.as_f64().filter(|h| h.is_finite()).ok_or_else(|| bad(cmd, "offset is a number of hours"))?;
if h.abs() > 18.0 {
return Err(bad(cmd, "offset is at most ±18 hours"));
}
Ok(Some((h * 60.0).round() as i64))
}
Value::String(o) => {
let m = DateTime::parse_offset(o).ok_or_else(|| bad(cmd, format!("can't read offset `{o}` (e.g. +02:00 or -5)")))?;
if m.unsigned_abs() > 18 * 60 {
return Err(bad(cmd, "offset is at most ±18 hours"));
}
Ok(Some(i64::from(m)))
}
_ => Err(bad(cmd, "offset is `+HH:MM` or a number of hours")),
}
}
/// The GPX text a command was given: `gpx` (the text) or `path` (a file), at most `max` bytes
/// ([`MAX_GPX_BYTES`] for the Map view's track log, which keeps the parsed file in memory; the older
/// `photo.autoTagTracklog` keeps its larger cap), and the path.
pub(crate) fn read_gpx(cmd: &str, p: &Value, max: u64) -> Result<Option<(String, Option<String>)>> {
match (p.get("gpx"), p.get("path")) {
(Some(Value::String(t)), _) => {
if t.len() as u64 > max {
return Err(bad(cmd, format!("the track log is larger than {} MB", max >> 20)));
}
Ok(Some((t.clone(), None)))
}
(None | Some(Value::Null), Some(Value::String(path))) => {
// (a folder: Windows refuses to open it at all, so say what it is)
if std::path::Path::new(path).is_dir() {
return Err(bad(cmd, format!("{path} is not a file")));
}
// read through the opened regular file under the byte cap (as every user-named file, #3703)
let bytes = crate::read_file::read_regular(path, max).map_err(|e| match e.kind() {
// (read_regular's "more than the cap" and "not a regular file")
std::io::ErrorKind::InvalidData => bad(cmd, format!("{path} is larger than {} MB: too big for a track log", max >> 20)),
std::io::ErrorKind::InvalidInput => bad(cmd, format!("{path} is not a file")),
_ => bad(cmd, format!("can't read {path}: {e}")),
})?;
// a stray byte that isn't UTF-8 (a Latin-1 track name) doesn't refuse the file: it reads as �,
// as photo.autoTagTracklog always read it
let text = String::from_utf8_lossy(&bytes).into_owned();
Ok(Some((text, Some(path.clone()))))
}
(None | Some(Value::Null), None | Some(Value::Null)) => Ok(None),
_ => Err(bad(cmd, "`path` is a file path and `gpx` the file's text")),
}
}
/// Parse and prepare a track log.
pub(crate) fn load(cmd: &str, text: &str, path: Option<String>) -> Result<LoadedTrack> {
let t0 = web_time::Instant::now();
let log = parse_gpx(text).map_err(|e| bad(cmd, e.to_string()))?;
if log.points.len() > MAX_TRACK_POINTS {
return Err(bad(cmd, format!("the track log has {} timed points; at most {MAX_TRACK_POINTS} are loaded", log.points.len())));
}
if log.points.is_empty() {
let why = if log.tracks == 0 {
"the file has no tracks (<trk>)".to_string()
} else if log.untimed > 0 {
format!("the track log has no timed track points ({} without a time)", log.untimed)
} else {
"the track log has no track points".to_string()
};
return Err(bad(cmd, why));
}
// each track's lines: its segments, points in time order
let mut lines: Vec<BTreeMap<u32, Vec<(f64, f64)>>> = vec![BTreeMap::new(); log.tracks];
let mut tracks: Vec<TrackSummary> = log.names.iter().map(|n| TrackSummary { name: n.clone(), points: 0, segments: 0, span: None }).collect();
for p in &log.points {
let i = usize::try_from(p.track).unwrap_or(usize::MAX);
if let Some(l) = lines.get_mut(i) {
l.entry(p.segment).or_default().push((p.latitude, p.longitude));
}
if let Some(t) = tracks.get_mut(i) {
t.points += 1;
t.span = Some(match t.span {
None => (p.time, p.time),
Some((a, b)) => (a.min(p.time), b.max(p.time)),
});
}
}
for (t, l) in tracks.iter_mut().zip(&lines) {
t.segments = l.len();
}
let shapes = lines.into_iter().map(|l| Arc::new(TrackShape::new(l.into_values()))).collect();
let name = path
.as_deref()
.and_then(|p| std::path::Path::new(p).file_name())
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "GPX".to_string());
let log = Arc::new(log);
Ok(LoadedTrack {
path,
name,
active_log: log.clone(),
log,
tracks,
shapes,
active: None,
offset_minutes: None,
load_ms: t0.elapsed().as_secs_f64() * 1000.0,
})
}
/// `map.trackLog`'s answer: what is loaded.
pub fn report(t: Option<&LoadedTrack>, generation: u64) -> Value {
let Some(t) = t else { return json!({"loaded": false, "generation": generation}) };
let off = t.offset_minutes.unwrap_or(0);
let tracks: Vec<Value> = t
.tracks
.iter()
.enumerate()
.map(|(i, s)| {
json!({
"index": i,
"name": s.name,
"points": s.points,
"segments": s.segments,
"start": s.span.map(|(a, _)| iso(a, 0) + "Z"),
"end": s.span.map(|(_, b)| iso(b, 0) + "Z"),
"duration": s.span.map(|(a, b)| b - a),
})
})
.collect();
let span = t.span();
json!({
"loaded": true,
"path": t.path,
"name": t.name,
"points": t.log.points.len(),
"untimed": t.log.untimed,
"tracks": tracks,
"active": t.active,
"activePoints": t.active_log.points.len(),
"start": span.map(|(a, _)| iso(a, 0) + "Z"),
"end": span.map(|(_, b)| iso(b, 0) + "Z"),
"duration": span.map(|(a, b)| b - a),
"offset": t.offset_minutes.map(fmt_offset),
"startLocal": span.map(|(a, _)| iso(a, off)),
"endLocal": span.map(|(_, b)| iso(b, off)),
"loadMs": t.load_ms,
"generation": generation,
})
}
/// `map.trackLog`: see its command spec.
/// Read and prepare the track log at `path` without the session (the Map view does it on a worker
/// thread, then [`install`]s it): the checks and caps of `map.trackLog {path}`.
pub fn prepare_file(path: &str) -> std::result::Result<LoadedTrack, String> {
const C: &str = "map.trackLog";
let (text, path) = read_gpx(C, &json!({"path": path}), MAX_GPX_BYTES).map_err(|e| e.to_string())?.ok_or_else(|| format!("{C}: no file"))?;
load(C, &text, path).map_err(|e| e.to_string())
}
/// Make `t` the loaded track log, as `map.trackLog {path}` does (it keeps the last log's offset),
/// and report it.
pub fn install(s: &mut Session, mut t: LoadedTrack) -> Value {
t.offset_minutes = s.map.track.as_ref().and_then(|o| o.offset_minutes);
s.map.track = Some(t);
s.map.track_generation += 1;
report(s.map.track.as_ref(), s.map.track_generation)
}
pub(crate) fn track_log(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "map.trackLog";
if !p.is_object() && !p.is_null() {
return Err(bad(C, "params are an object"));
}
let clear = match p.get("clear") {
None | Some(Value::Null) => false,
Some(v) => v.as_bool().ok_or_else(|| bad(C, "`clear` is true or false"))?,
};
// everything is checked before anything changes
let loaded = match read_gpx(C, p, MAX_GPX_BYTES)? {
Some((text, path)) => Some(load(C, &text, path)?),
None => None,
};
let offset = match p.get("offset") {
None => None,
Some(v) => Some(parse_offset(C, v)?),
};
let active = match p.get("active") {
None => None,
Some(Value::Null) => Some(None),
Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => Some(None),
Some(v) => Some(Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "`active` is a track's index or \"all\""))?)),
};
if clear && (loaded.is_some() || offset.is_some() || active.is_some()) {
return Err(bad(C, "`clear` goes alone"));
}
let tracks_after = loaded.as_ref().or(s.map.track.as_ref()).map(|t| t.tracks.len());
if let Some(Some(i)) = active {
match tracks_after {
None => return Err(bad(C, "no track log is loaded")),
Some(n) if i >= n => return Err(bad(C, format!("no track {i}: the log has {n} (0…{})", n.saturating_sub(1)))),
_ => {}
}
}
if (offset.is_some() || active.is_some()) && tracks_after.is_none() {
return Err(bad(C, "no track log is loaded (give `path`)"));
}
let before = s.map.track_generation;
if clear && s.map.track.take().is_some() {
s.map.track_generation += 1;
}
if let Some(mut t) = loaded {
// a new file keeps the offset chosen for the last one (the same camera, most likely)
t.offset_minutes = s.map.track.as_ref().and_then(|o| o.offset_minutes);
s.map.track = Some(t);
}
if let Some(t) = s.map.track.as_mut() {
if let Some(a) = active {
t.set_active(a);
}
if let Some(o) = offset {
t.offset_minutes = o;
}
}
if s.map.track_generation == before
&& (p.get("path").is_some_and(|v| !v.is_null()) || p.get("gpx").is_some_and(|v| !v.is_null()) || offset.is_some() || active.is_some())
{
s.map.track_generation += 1;
}
Ok(report(s.map.track.as_ref(), s.map.track_generation))
}
+83 -12
View File
@@ -24,6 +24,8 @@ pub enum HttpError {
Connect(String),
/// No data arrived for the stall timeout.
Stalled,
/// The request went past its overall deadline ([`Limits::deadline`]), data arriving or not.
TooSlow,
/// The cancel flag was raised.
Cancelled,
/// TLS failed (certificate, handshake).
@@ -40,6 +42,7 @@ impl std::fmt::Display for HttpError {
HttpError::BadUrl(e) => write!(f, "unusable URL: {e}"),
HttpError::Connect(e) => write!(f, "could not connect: {e}"),
HttpError::Stalled => write!(f, "the server stopped sending data"),
HttpError::TooSlow => write!(f, "the server took too long to answer"),
HttpError::Cancelled => write!(f, "cancelled"),
HttpError::Tls(e) => write!(f, "secure connection failed: {e}"),
HttpError::Protocol(e) => write!(f, "unexpected response: {e}"),
@@ -91,6 +94,16 @@ pub struct Limits<'a> {
pub connect: Duration,
pub stall: Duration,
pub cancel: &'a AtomicBool,
/// When the whole request must be done by (`None`: no limit). The stall timeout restarts with
/// every byte, so without this a server sending a byte now and then (in headers, chunk sizes,
/// trailers or the body) could hold one request for as long as it likes.
pub deadline: Option<Instant>,
}
impl Limits<'_> {
fn past_deadline(&self) -> bool {
self.deadline.is_some_and(|d| Instant::now() >= d)
}
}
/// How often a blocked read wakes up to check the cancel flag.
@@ -175,10 +188,12 @@ fn connect_any(host: &str, addrs: &[SocketAddr], deadline: Instant, limits: &Lim
impl Stream {
fn connect(url: &Url, limits: &Limits) -> Result<Stream, HttpError> {
// the lookup and the connection attempts share one connect timeout
let deadline = Instant::now() + limits.connect;
// the connect timeout, or the request's overall deadline when that comes first
let deadline = limits.deadline.map_or(Instant::now() + limits.connect, |d| d.min(Instant::now() + limits.connect));
let too_slow = |e: HttpError| if limits.past_deadline() { HttpError::TooSlow } else { e };
let (host, port) = (url.host.clone(), url.port);
let addrs = lookup(&url.host, move || (host.as_str(), port).to_socket_addrs().map(Iterator::collect), deadline, limits)?;
let sock = connect_any(&url.host, &addrs, deadline, limits)?;
let addrs = lookup(&url.host, move || (host.as_str(), port).to_socket_addrs().map(Iterator::collect), deadline, limits).map_err(too_slow)?;
let sock = connect_any(&url.host, &addrs, deadline, limits).map_err(too_slow)?;
sock.set_read_timeout(Some(TICK)).map_err(|e| HttpError::Io(e.to_string()))?;
sock.set_write_timeout(Some(TICK)).map_err(|e| HttpError::Io(e.to_string()))?;
let _ = sock.set_nodelay(true);
@@ -199,6 +214,9 @@ impl Stream {
if limits.cancel.load(Ordering::Relaxed) {
return Err(HttpError::Cancelled);
}
if limits.past_deadline() {
return Err(HttpError::TooSlow);
}
match f() {
Ok(v) => return Ok(v),
Err(e) if is_timeout(&e) => {
@@ -214,8 +232,21 @@ impl Stream {
fn handshake(&mut self, limits: &Limits) -> Result<(), HttpError> {
let Stream::Tls(conn, sock) = self else { return Ok(()) };
// one socket read or write at a time (not complete_io, which loops inside), so the
// deadline and cancel flag are checked between every step
while conn.is_handshaking() {
Self::retry(limits, || conn.complete_io(sock))?;
while conn.wants_write() {
Self::retry(limits, || conn.write_tls(sock))?;
}
if conn.is_handshaking() && conn.wants_read() {
if Self::retry(limits, || conn.read_tls(sock))? == 0 {
return Err(HttpError::Tls("connection closed during the handshake".into()));
}
conn.process_new_packets().map_err(|e| HttpError::Tls(e.to_string()))?;
}
}
while conn.wants_write() {
Self::retry(limits, || conn.write_tls(sock))?;
}
Ok(())
}
@@ -254,6 +285,9 @@ impl Stream {
if limits.cancel.load(Ordering::Relaxed) {
return Err(HttpError::Cancelled);
}
if limits.past_deadline() {
return Err(HttpError::TooSlow);
}
match conn.reader().read(buf) {
Ok(n) => return Ok(n),
// closed without close_notify: the caller checks the length it got
@@ -366,6 +400,12 @@ impl Response {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
/// Every header named `name` (case-insensitive), in the order received: a list header such as
/// `Cache-Control` may come in several lines.
pub fn header_all(&self, name: &str) -> Vec<&str> {
self.headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()).collect()
}
/// The body's length when the server announced it.
pub fn content_length(&self) -> Option<u64> {
match self.body {
@@ -436,14 +476,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/<version>` (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<Response, HttpError> {
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()));
@@ -497,7 +538,37 @@ mod tests_connect {
use super::*;
fn limits(cancel: &AtomicBool) -> Limits<'_> {
Limits { connect: Duration::from_millis(300), stall: Duration::from_secs(1), cancel }
Limits { connect: Duration::from_millis(300), stall: Duration::from_secs(1), cancel, deadline: None }
}
/// A server that trickles bytes (one per 100 ms, never stalling a full second) is stopped at the
/// request's deadline instead of holding it for as long as it likes.
#[test]
fn a_trickling_server_is_stopped_at_the_deadline() {
use std::io::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 (mut s, _) = listener.accept().unwrap();
let _ = s.write_all(
b"HTTP/1.1 200 OK
",
);
for _ in 0..100 {
if s.write_all(b"X").is_err() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
});
let cancel = AtomicBool::new(false);
let limits = Limits { deadline: Some(Instant::now() + Duration::from_millis(500)), ..limits(&cancel) };
let url = Url::parse(&format!("http://127.0.0.1:{port}/t")).unwrap();
let t = Instant::now();
let r = get(&url, &[], &limits);
assert!(matches!(r, Err(HttpError::TooSlow)), "{:?}", r.err());
assert!(t.elapsed() < Duration::from_secs(3), "stopped near the deadline: {:?}", t.elapsed());
drop(server);
}
/// A name lookup that hangs is given up on at the connect timeout, and Cancel stops it at once (issue #1532).
+2 -2
View File
@@ -359,7 +359,7 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: &
if let Some(src) = local {
copy_local(&src, &part, limit, f.size, cancel, report)?;
} else if fetched {
let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel };
let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel, deadline: None };
let mut url = Url::parse(url).map_err(|e| Fail::NextMirror(e.to_string()))?;
let origin = url.host.clone();
let mut redirects = 0;
@@ -567,7 +567,7 @@ fn copy_local(src: &Path, part: &Path, limit: u64, size: Option<u64>, cancel: &A
fn http_fail(e: HttpError) -> Fail {
match e {
HttpError::Cancelled => Fail::Cancelled,
HttpError::Stalled | HttpError::Io(_) | HttpError::Protocol(_) => Fail::Retry(e.to_string()),
HttpError::Stalled | HttpError::TooSlow | HttpError::Io(_) | HttpError::Protocol(_) => Fail::Retry(e.to_string()),
HttpError::BadUrl(_) | HttpError::Connect(_) | HttpError::Tls(_) => Fail::NextMirror(e.to_string()),
}
}
+33
View File
@@ -557,3 +557,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<String> {
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, deadline: None };
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)"]);
}
+68
View File
@@ -0,0 +1,68 @@
//! Geographic coordinates in degrees (WGS84): latitude in `[-90.0, 90.0]`, longitude in
//! `[-180.0, 180.0]`. The Web Mercator projection lives in `lightcraft_engine::map::mercator`.
use serde::{Deserialize, Serialize};
/// 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 {
/// 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<Self> {
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<Self> {
if !lon.is_finite() {
return None;
}
Self::new(lat, Self::normalize_lon(lon))
}
/// 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
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
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);
}
}
+2
View File
@@ -7,11 +7,13 @@
mod crop;
mod crop_drag;
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::LatLon;
pub use homography::Homography;
pub use real::{Interval, Real};
+9 -3
View File
@@ -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())
}
+4
View File
@@ -128,6 +128,10 @@ impl LightcraftApp {
image_rect: None,
grid_scroll: None,
film_scroll: None,
map_drawn: Default::default(),
map_points: Default::default(),
mini_map: None,
map_tracks: Default::default(),
widgets: vec![],
widget_hits: vec![],
next_widgets: vec![],
+7 -1
View File
@@ -20,6 +20,12 @@ pub fn id(key: &str) -> Id {
Id::unique("lc-canvas-handle").with(key)
}
/// Mark `id`, which has the focus this frame, as a stand-in on a canvas: [`has_focus`] then holds,
/// so the app's shortcuts leave it the arrows, Return and Space.
pub fn mark_focused(ctx: &egui::Context, id: Id) {
ctx.data_mut(|d| d.insert_temp(focused_key(), id));
}
/// Whether a canvas handle holds the keyboard focus: it keeps the arrow keys and Return from the
/// app's shortcuts (next photo, and so on).
pub fn has_focus(ctx: &egui::Context) -> bool {
@@ -58,7 +64,7 @@ pub fn handle(ui: &mut Ui, key: &str, name: &str, value: String, at: Pos2) -> Ha
if !resp.has_focus() {
return out;
}
ui.data_mut(|d| d.insert_temp(focused_key(), id));
mark_focused(ui.ctx(), id);
// a ring shows where the focus is
ui.painter().circle_stroke(at, 9.0, egui::Stroke::new(2.0, ui.visuals().selection.stroke.color));
ui.painter().circle_stroke(at, 11.0, egui::Stroke::new(1.0, egui::Color32::BLACK));
@@ -44,6 +44,10 @@ pub fn default_value(field: &str, op: &str) -> Value {
(Some(Kind::Number), _) => json!(if field == "rating" { 3 } else { 0 }),
(Some(Kind::Choice(c)), _) => json!(c.first().map_or("", |c| c.0)),
(Some(Kind::Bool), _) => json!(true),
// the whole world: a rule that means something, to narrow from
(Some(Kind::Area), _) => lightcraft_catalog::rules::GpsArea::WORLD.to_value(),
// a kilometre around 0, 0: a valid circle to move from
(Some(Kind::Circle), _) => json!({"lat": 0.0, "lon": 0.0, "radius": 1000.0}),
// picked from the list
(Some(Kind::Album), _) => Value::Null,
_ => json!(""),
@@ -148,11 +152,51 @@ fn album_value(ui: &mut egui::Ui, v: &mut Value, salt: &str, env: &Env) {
}
}
/// A GPS Area rule's value: south, west, north, east in degrees. A stored edge out of range is
/// shown as it is, not clamped (and saved) on sight, so the rule check can still mark it; a value
/// that isn't an area shows the whole world and is written only when an edge is changed. Ported
/// from PR #819.
fn area_value(ui: &mut egui::Ui, v: &mut Value) {
let edge = |k: &str, d: f64| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(d);
let w = lightcraft_catalog::rules::GpsArea::WORLD;
let mut e = [edge("south", w.south), edge("west", w.west), edge("north", w.north), edge("east", w.east)];
let mut changed = false;
for (i, (name, max)) in [("South", 90.0), ("West", 180.0), ("North", 90.0), ("East", 180.0)].into_iter().enumerate() {
ui.label(crate::i18n::tr(name));
if let Some(x) = e.get_mut(i) {
changed |= ui.add(egui::DragValue::new(x).range(-max..=max).clamp_existing_to_range(false).speed(0.1).max_decimals(6)).changed();
}
}
if changed {
let [south, west, north, east] = e;
*v = json!({"south": south, "west": west, "north": north, "east": east});
}
}
/// A GPS Radius rule's centre (degrees) and radius (metres). (From PR #906.)
fn circle_value(ui: &mut egui::Ui, v: &mut Value) {
let n = |k: &str, d: f64| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(d);
let (mut lat, mut lon, mut radius) = (n("lat", 0.0), n("lon", 0.0), n("radius", 1000.0));
let mut changed = false;
ui.label(crate::i18n::tr("Latitude"));
changed |= ui.add(egui::DragValue::new(&mut lat).range(-90.0..=90.0).clamp_existing_to_range(false).speed(0.01).max_decimals(6)).changed();
ui.label(crate::i18n::tr("Longitude"));
changed |= ui.add(egui::DragValue::new(&mut lon).range(-180.0..=180.0).clamp_existing_to_range(false).speed(0.01).max_decimals(6)).changed();
ui.label(crate::i18n::tr("Radius (m)"));
let (lo, hi) = (lightcraft_catalog::rules::MIN_RADIUS_M, lightcraft_catalog::rules::MAX_RADIUS_M);
changed |= ui.add(egui::DragValue::new(&mut radius).range(lo..=hi).clamp_existing_to_range(false).speed(10.0).max_decimals(0)).changed();
if changed {
*v = json!({"lat": lat, "lon": lon, "radius": radius});
}
}
/// The value editor for one rule.
fn value_editor(ui: &mut egui::Ui, field: &str, op: &str, v: &mut Value, salt: &str, env: &Env) {
match (field_kind(field), op) {
(_, "isEmpty" | "isNotEmpty") => {}
(Some(Kind::Album), _) => album_value(ui, v, salt, env),
(Some(Kind::Area), _) => area_value(ui, v),
(Some(Kind::Circle), _) => circle_value(ui, v),
(Some(Kind::Date), "inLast" | "notInLast") => {
// shown as stored ({n, unit}, or a plain number of days) and only written when changed:
// drawing never turns "0 days" into 1 or 20,000 into the spinner's 10,000
@@ -445,6 +489,8 @@ mod tests {
Kind::Number if *field == "shutterSpeed" => v.as_str().and_then(lightcraft_catalog::parse_shutter_seconds).is_some(),
Kind::Number => v.is_number(),
Kind::Bool => v.is_boolean(),
Kind::Area => lightcraft_catalog::rules::GpsArea::parse(v).is_ok(),
Kind::Circle => lightcraft_catalog::rules::GpsCircle::parse(v).is_ok(),
Kind::Album => v.is_null(),
Kind::Text | Kind::Keywords | Kind::Date => v.is_string(),
};
@@ -464,4 +510,21 @@ mod tests {
assert_eq!(default_value("shutterSpeed", "gte"), json!("1/250"));
assert_eq!(default_value("shutterSpeed", "between"), json!(["1/1000", "1/125"]));
}
/// An area whose stored edge is out of range stays as stored when the editor draws it, so
/// the rule check can still mark it (the editor doesn't fix it up unasked).
#[test]
fn an_out_of_range_area_is_not_rewritten_by_drawing_it() {
let ctx = egui::Context::default();
let stored = json!({"south": 95.0, "west": -200.0, "north": 10.0, "east": 10.0});
let mut v = stored.clone();
for _ in 0..3 {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
egui::CentralPanel::default().show(ui, |ui| area_value(ui, &mut v));
});
out.textures_delta.clear();
}
assert_eq!(v, stored);
assert_eq!(default_value("gpsArea", "inside"), lightcraft_catalog::rules::GpsArea::WORLD.to_value());
}
}
+5 -1
View File
@@ -1,5 +1,5 @@
//! The Settings dialog (⌘,): General, Import, Performance (incl. where AI masks run), Display,
//! Interface, Slideshow, Faces, AI Denoise.
//! 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,
@@ -26,6 +26,7 @@ mod display;
mod general;
mod import;
mod libraries;
mod map;
mod performance;
mod slideshow;
mod widgets;
@@ -37,6 +38,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};
@@ -54,6 +56,7 @@ pub const TABS: &[(&str, &str)] = &[
("display", "Display"),
("interface", "Interface"),
("slideshow", "Slideshow"),
("map", "Map"),
("faces", "Faces"),
("denoise", "AI Denoise"),
("aidefringe", "AI Defringe"),
@@ -73,6 +76,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),
"aidefringe" => crate::panels::aidefringe::settings_tab(app, ui, &t),
@@ -106,6 +106,9 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result<Value, String>
app.ui.mask_hover_prev = None;
// a keyword picked in the Keyword List belongs to the library being left
app.ui.keyword_list_selected = None;
// the Map view's saved-location and pin state, and Show Map approvals, are for the library being
// left (ids are per library)
app.ui.map.library_changed();
if app.ui.view == crate::state::ViewMode::Reference {
app.ui.view = crate::state::ViewMode::PhotoGrid;
}
+347
View File
@@ -0,0 +1,347 @@
use super::widgets::{field, heading, hint, row};
use super::{LightcraftApp, RichText, Tokens, json, register};
use lightcraft_engine::activity::{Activity, Cancel};
// ----------------------------------------------------------------------------------------- Map
/// Where users get an ArcGIS Location Platform API key (free tier).
const ARCGIS_SIGN_UP: &str = "https://location.arcgis.com";
/// The project's map documentation (sources, the OSM policy, Esri, privacy).
const MAP_DOCS: &str = "https://github.com/storytold/lightcraft/blob/main/docs/map.md";
/// A measurement of the tile cache (bytes, tiles) running on a worker thread: it lands here.
type CacheJob = std::sync::Arc<std::sync::Mutex<Option<(u64, u64)>>>;
/// What measures the cache under a folder: bytes, tiles (a test puts a slow one in its place).
type Measure = std::sync::Arc<dyn Fn(&std::path::Path) -> (u64, u64) + Send + Sync>;
/// A measurement still running after this long shows in the activity stack, as the free-space read
/// does: most caches answer at once, and the tab measures every 5 s, so a row for each would flash.
const SHOW_ROW_AFTER: std::time::Duration = std::time::Duration::from_millis(200);
/// The activity stack's label for a slow measurement (English; the stack translates it).
const MEASURING_LABEL: &str = "Measuring the map tile cache";
/// What Settings ▸ Map remembers between frames (egui temporary memory: never saved): the custom
/// server's fields as typed, the last refusal, and the cache size with when it was measured.
#[derive(Clone, Default)]
struct MapDraft {
template: String,
attribution: String,
max_zoom: String,
/// The fields were filled from the current custom source (once, when the tab opened).
seeded: bool,
error: Option<String>,
/// The last measurement that finished: bytes, tiles, when.
cache: Option<(u64, u64, f64)>,
/// A measurement under way (the last one stays shown meanwhile).
measuring: Option<CacheJob>,
}
/// Measure the tile cache under `root` on a worker thread (it walks the cache folder, up to a
/// million files): the result lands in the job. Where no thread can be started (the web) it is
/// measured at once.
fn measure_cache(root: Option<std::path::PathBuf>, activity: &Activity) -> CacheJob {
measure_cache_with(
root,
activity,
std::sync::Arc::new(|root: &std::path::Path| {
let info = std::panic::catch_unwind(|| lightcraft_engine::map::cache::info(root)).unwrap_or_default();
(info.bytes, info.tiles)
}),
)
}
fn store(job: &CacheJob, r: (u64, u64)) {
*job.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(r);
}
/// [`measure_cache`] with `measure` doing the walk. The walk runs on its own thread; once it has
/// taken more than [`SHOW_ROW_AFTER`] the worker shows it in the activity stack (it can't stop:
/// `Cancel::No`) until its result has landed in the job.
fn measure_cache_with(root: Option<std::path::PathBuf>, activity: &Activity, measure: Measure) -> CacheJob {
let job = CacheJob::default();
let Some(root) = root else {
store(&job, (0, 0));
return job;
};
let (out, worker_root, activity, inline) = (job.clone(), root.clone(), activity.clone(), measure.clone());
let started = std::thread::Builder::new().name("map-cache-size".into()).spawn(move || {
let row = |a: &Activity| a.start("cache", MEASURING_LABEL, Cancel::No);
let (tx, rx) = std::sync::mpsc::channel();
let (walk, walk_root) = (measure.clone(), worker_root.clone());
let walking = std::thread::Builder::new().name("map-cache-walk".into()).spawn(move || {
let _ = tx.send(walk(&walk_root));
});
// `_row` is dropped only after the result is stored
let (r, _row) = match walking {
Ok(_) => match rx.recv_timeout(SHOW_ROW_AFTER) {
Ok(r) => (r, None),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
let g = row(&activity);
(rx.recv().unwrap_or_default(), Some(g))
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => ((0, 0), None),
},
// no second thread: the walk runs here, shown from the start
Err(_) => {
let g = row(&activity);
(measure(&worker_root), Some(g))
}
};
store(&out, r);
});
if started.is_err() {
store(&job, inline(&root));
}
job
}
/// Settings ▸ Map: where tiles come from (the built-in sources, Offline, or a custom server applied
/// with Apply or Return, never while typing; a refused one shows why and changes nothing), the tile
/// cache's size with Delete Cached Tiles, what the tile server sees, then the Esri key. (After PR #921's
/// map settings, Jason Baldwin.)
pub(super) fn map_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
let id = egui::Id::unique("settings:mapDraft");
let mut d: MapDraft = ui.data_mut(|m| m.get_temp::<MapDraft>(id)).unwrap_or_default();
if !d.seeded {
if let lightcraft_engine::map::TileSource::Custom { url_template, attribution, max_zoom, .. } = app.session.map.source() {
d.template = url_template.clone();
d.attribution = attribution.clone();
d.max_zoom = max_zoom.to_string();
}
d.seeded = true;
}
heading(ui, t, crate::i18n::tr("Map tiles"));
let current = app.session.map.effective_source();
let custom_now = matches!(current, lightcraft_engine::map::TileSource::Custom { .. });
let mut chosen: Option<String> = None;
row(ui, t, crate::i18n::tr("Tile source"), |ui| {
ui.horizontal_wrapped(|ui| {
for s in app.session.map.offered() {
let r = ui.radio(s == current, crate::i18n::tr(s.label()));
register(ui, format!("settings:mapSource:{}", s.id()), r.rect);
if r.clicked() && s != current {
chosen = Some(s.id().to_string());
}
}
let r = ui.radio(custom_now, crate::i18n::tr("Custom tile server"));
register(ui, "settings:mapSource:custom", r.rect);
});
});
if let Some(s) = chosen {
match app.run("map.tileSource", json!({"id": s})) {
Ok(_) => d.error = None,
Err(e) => d.error = Some(e),
}
}
// the custom server: applied on Apply or Return only
let mut apply = false;
row(ui, t, crate::i18n::tr("URL template"), |ui| {
let r =
field(ui, crate::text_field::TextField::singleline("field:mapTemplate", &mut d.template).hint("https://…/{z}/{x}/{y}.png").width(320.0));
apply |= matches!(r.ending, Some(crate::text_field::Ending::Return));
});
row(ui, t, crate::i18n::tr("Attribution"), |ui| {
let r = field(
ui,
crate::text_field::TextField::singleline("field:mapAttribution", &mut d.attribution).hint(crate::i18n::tr("© the provider")).width(320.0),
);
apply |= matches!(r.ending, Some(crate::text_field::Ending::Return));
});
row(ui, t, crate::i18n::tr("Max zoom"), |ui| {
let r = field(ui, crate::text_field::TextField::singleline("field:mapMaxZoom", &mut d.max_zoom).hint("18").width(60.0));
apply |= matches!(r.ending, Some(crate::text_field::Ending::Return));
let b = ui.add_enabled(!d.template.trim().is_empty(), egui::Button::new(crate::i18n::tr("Apply")));
register(ui, "button:mapCustomApply", b.rect);
apply |= b.clicked();
});
if apply && !d.template.trim().is_empty() {
let zoom = d.max_zoom.trim();
let mut p = json!({"urlTemplate": d.template.trim(), "attribution": d.attribution.trim()});
let bad_zoom = !zoom.is_empty() && zoom.parse::<u8>().is_err();
if let Ok(z) = zoom.parse::<u8>() {
p["maxZoom"] = json!(z);
}
d.error =
if bad_zoom { Some(crate::i18n::tr("Max zoom is a whole number from 0 to 24").to_string()) } else { app.run("map.tileSource", p).err() };
}
if let Some(e) = &d.error {
let r = ui.label(RichText::new(e).size(11.5).color(t.caution));
register(ui, "settings:mapError", r.rect);
}
hint(
ui,
t,
crate::i18n::tr(
"A tile server sees which tiles you look at (so roughly which places), your IP address and LightCraft's name and version; nothing else leaves the machine. Offline fetches nothing. A custom server's address may carry your own key, on your own responsibility.",
),
);
// the cache, measured at most every 5 seconds on a worker thread (it walks the cache folder);
// the last measurement stays shown until the next one lands
let now = app.tick_now();
if let Some(job) = &d.measuring {
let landed = job.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
match landed {
Some((bytes, tiles)) => {
d.cache = Some((bytes, tiles, now));
d.measuring = None;
}
None => ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)),
}
}
if d.measuring.is_none() && d.cache.is_none_or(|(_, _, at)| now - at > 5.0) {
d.measuring = Some(measure_cache(app.session.map.cache_root.clone(), &app.session.activity));
ui.ctx().request_repaint();
}
let (bytes, tiles, _) = d.cache.unwrap_or_default();
row(ui, t, crate::i18n::tr("Tile cache"), |ui| {
let text = if d.cache.is_some() {
crate::i18n::tr_format!("{size} MB, {n} tiles", size = format!("{:.1}", bytes as f64 / 1_048_576.0), n = tiles)
} else {
crate::i18n::tr("Measuring…").to_string()
};
let r = ui.label(text);
register(ui, "settings:mapCacheSize", r.rect);
let b = ui.add_enabled(tiles > 0, egui::Button::new(crate::i18n::tr("Delete Cached Tiles")));
register(ui, "button:mapClearCache", b.rect);
if b.clicked() {
if let Err(e) = app.run("map.clearCache", json!({})) {
app.toast(ui.ctx(), e);
}
// measured again (a measurement from before the clear is dropped)
d.cache = None;
d.measuring = None;
}
});
row(ui, t, "", |ui| {
let r = ui.link(crate::i18n::tr("About map tiles and privacy (docs/map.md)"));
register(ui, "link:mapDocs", r.rect);
if r.clicked()
&& let Err(e) = crate::links::open(app, MAP_DOCS)
{
app.toast(ui.ctx(), e);
}
});
ui.data_mut(|m| m.insert_temp(id, d));
ui.add_space(8.0);
esri_key(app, ui, t);
}
/// 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`).
fn esri_key(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::<String>(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.",
),
);
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
fn wait_for(what: &str, mut done: impl FnMut() -> bool) {
let until = Instant::now() + Duration::from_secs(10);
while !done() {
assert!(Instant::now() < until, "{what}");
std::thread::sleep(Duration::from_millis(5));
}
}
/// A cache that takes its time to measure (a big one on a slow drive) shows in the activity
/// stack until its size has landed (CodeRabbit on #4243).
#[test]
fn a_slow_measurement_shows_in_the_activity_stack_until_it_lands() {
let activity = Activity::default();
let (release, wait) = mpsc::channel::<()>();
let wait = Mutex::new(wait);
let job = measure_cache_with(
Some(std::env::temp_dir()),
&activity,
Arc::new(move |_: &std::path::Path| {
// answers once the test lets it (or after 10 s, so a broken test can't hang)
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(10));
(7, 3)
}),
);
let shown = |a: &Activity| a.list().iter().any(|t| t.kind == "cache" && t.label == MEASURING_LABEL && !t.cancellable);
wait_for("the slow measurement never showed in the activity stack", || shown(&activity));
assert_eq!(*job.lock().unwrap(), None, "still measuring");
release.send(()).unwrap();
wait_for("the size never landed", || job.lock().unwrap().is_some());
assert_eq!(*job.lock().unwrap(), Some((7, 3)));
wait_for("the row stayed after the size landed", || !shown(&activity));
}
/// Without a cache folder there is nothing to walk: no thread, no row.
#[test]
fn no_cache_folder_measures_nothing() {
let activity = Activity::default();
let job = measure_cache_with(None, &activity, Arc::new(|_: &std::path::Path| (1, 1)));
assert_eq!(*job.lock().unwrap(), Some((0, 0)));
assert!(activity.list().is_empty());
}
}
+11
View File
@@ -766,11 +766,19 @@ pub fn show(app: &mut crate::LightcraftApp, ui: &mut egui::Ui) {
// proportion to what it has above its minimum, as the side panels did; the saved widths stay.
let shown = shown_workspace(&fitted(&workspace, ui.available_width()));
let specs = specs();
// the Info panel's map is this frame's only (`map.state` reports none once it is gone)
app.mini_map = None;
// the Map view's location filter narrows the photos only while it is shown
crate::panels::map::sync_location_filter(app);
// a track log read on a worker thread lands here
crate::panels::map::tracks::poll(app, ui.ctx());
let (output, canvas) = {
let mut content = Content { app: &mut *app, canvas: None };
let output = DockArea::new(AREA, Bind::given(Arc::clone(&shown)), &*specs, &mut content, dock_config()).show(ui);
(output, content.canvas.take())
};
// 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(invalid) = &output.error {
log::warn!("the panel layout was not drawn: {}", invalid.error);
}
@@ -796,8 +804,11 @@ 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),
});
}
// 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 = current(app);
+1 -1
View File
@@ -88,7 +88,7 @@ pub struct HeadlessView {
/// The pretend host's clipboard: what the UI last copied, and what a paste request pastes.
pub clipboard: String,
/// Events the host owes the next frame (a paste request's paste, as a desktop host sends it).
owed: Vec<egui::Event>,
pub(crate) owed: Vec<egui::Event>,
/// The last frame's AccessKit tree, once a test has turned AccessKit on (`ctx.enable_accesskit()`).
#[cfg(test)]
pub(crate) accesskit: Option<egui::accesskit::TreeUpdate>,
+12
View File
@@ -662,6 +662,18 @@ pub fn rules_label(rules: &lightcraft_catalog::RuleSet, catalog: &lightcraft_cat
Kind::Album => lightcraft_catalog::rules::album_name(value, Some(catalog)),
Kind::Choice(_) => value.as_str().map_or_else(|| value.to_string(), |id| choice_text(field, id).to_string()),
Kind::Bool => lightcraft_catalog::rules::bool_value(value).map_or_else(|| value.to_string(), |b| bool_text(b).to_string()),
Kind::Area => lightcraft_catalog::rules::GpsArea::parse(value).map_or_else(|_| value.to_string(), |a| a.describe()),
Kind::Circle => lightcraft_catalog::rules::GpsCircle::parse(value).map_or_else(
|_| value.to_string(),
|c| {
tr_format!(
"within {d} of {lat}, {lon}",
d = lightcraft_catalog::rules::format_distance(c.radius),
lat = c.lat,
lon = c.lon
)
},
),
_ if matches!(op.as_str(), "inLast" | "notInLast") => format!(
"{} {}",
value.get("n").unwrap_or(&serde_json::Value::Null),
+7
View File
@@ -108,6 +108,8 @@ pub enum Icon {
Sun,
/// Appearance Mode ▸ Dark: a crescent moon.
Moon,
/// Map pin / Location marker.
MapPin,
/// A render failed: a triangle with an exclamation mark.
Warning,
/// A virtual copy: a page with a folded corner.
@@ -233,6 +235,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)]);
+8
View File
@@ -288,6 +288,14 @@ pub struct LightcraftApp {
/// drawn last (`ui.inspect` → `scroll`).
pub grid_scroll: Option<f32>,
pub film_scroll: Option<f32>,
/// What the Map view drew last frame (pins, the drop under the pointer), for `map.state`.
pub map_drawn: panels::map::MapDrawn,
/// The Map view's pins: the current list's positions, projected once per change of the list.
pub map_points: panels::map::Points,
/// What the Info panel's map drew this frame (`map.state` → `miniMap`); reset every frame.
pub mini_map: Option<panels::map::MiniShown>,
/// What the Map view draws of the track log (simplified levels, clipped lines, marks).
pub map_tracks: panels::map::tracks::TrackState,
/// 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
+2
View File
@@ -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()
+71
View File
@@ -274,7 +274,9 @@ const LAYOUT: &[(&str, &[&str])] = &[
"---",
"app.showInFinder",
"app.showInFolders",
"photo.showInMap",
"dialog.rename",
"photo.removeGps",
"photo.reload",
"tool.enablePainting",
"---",
@@ -304,6 +306,7 @@ const LAYOUT: &[(&str, &[&str])] = &[
"---",
"@Edit Sections",
"@Tools",
"@Map",
"---",
"view.leftPanel",
"view.rightPanel",
@@ -415,6 +418,13 @@ const HIDDEN: &[&str] = &[
// View ▸ Mask Overlay (each mode and colour, then the cycle item)
"view.maskOverlayMode",
"view.maskOverlayColor",
// Window ▸ Map: `map_menu` builds Lock Markers and the filter bar; `view.map` is Map View
// there (⌘⌥3), and `map.lock` is Lock Markers' older name (View has no room: 40 rows)
"map.lockMarkers",
"map.lock",
"map.filterBar",
"view.toggleMapFilter",
"view.map",
];
/// The selection includes a photo in Recently Deleted.
@@ -449,6 +459,56 @@ pub(crate) fn in_normal_album(app: &LightcraftApp) -> bool {
}
}
/// The Map view's commands, under Window ▸ Map's panel toggles (Lightroom Classic has a Map module
/// with its own menus; LightCraft has one menu bar for every view, so they gather there, greyed
/// outside the Map view; View has no room left under the 40-row limit). Each item runs its
/// command, as its key does (the keys shown are the Map view's: ⌘K, H, O, `\`, `=` / `-`).
/// (After PR #921's map menu, Jason Baldwin.)
fn map_menu(app: &LightcraftApp) -> Vec<MenuNode> {
use crate::panels::map::LocationFilterChoice;
let u = &app.ui;
let in_map = u.view == ViewMode::Map;
let entry = |id: &str, label: &str, key: Option<&str>, enabled: bool| {
let checked = checked(app, id);
item(id, Value::Null, label, key, enabled, checked)
};
let filter = LocationFilterChoice::ALL
.into_iter()
.map(|(mode, label)| item("map.locationFilter", json!({"mode": mode.id()}), label, None, in_map, Some(u.map.filter == mode)))
.collect();
let track = app.session.map.track.is_some();
vec![
entry("map.fit", "Fit to Photos", Some("Cmd+0"), in_map),
entry("map.zoomIn", "Zoom In on Map", Some("="), in_map),
entry("map.zoomOut", "Zoom Out on Map", Some("-"), in_map),
MenuNode::Separator,
entry("map.showPins", "Map Pins", Some("H"), in_map),
entry("map.lockMarkers", "Lock Markers", Some("Cmd+K"), in_map),
item("map.filterBar", Value::Null, "Location Filter Bar", Some("\\"), in_map, Some(u.map.show_filter_bar)),
MenuNode::Submenu { label: "Location Filter".into(), children: filter },
MenuNode::Separator,
MenuNode::Submenu {
label: "Saved Locations".into(),
children: vec![
entry("map.location.new", "New Location…", None, in_map),
entry("map.showLocations", "Saved Locations List", Some("O"), in_map),
],
},
MenuNode::Submenu {
label: "Tracklog".into(),
children: vec![
entry("map.loadTrackLog", "Load Tracklog…", None, true),
entry("map.trackLog.autoTag", "Auto-Tag Photos from Map Tracklog", None, in_map && track),
entry("map.trackLog.setOffset", "Set Time Zone Offset…", None, track),
entry("map.trackLog.fit", "Fit Map to Tracklog", None, in_map && track),
item("map.trackLog", json!({"clear": true}), "Clear Tracklog", None, track, None),
],
},
MenuNode::Separator,
entry("map.settings", "Map Tiles…", None, true),
]
}
fn item(id: &str, params: Value, label: impl Into<String>, shortcut: Option<&str>, enabled: bool, checked: Option<bool>) -> MenuNode {
MenuNode::Item { id: id.into(), params, label: label.into(), shortcut: shortcut.map(str::to_string), enabled, checked }
}
@@ -467,6 +527,13 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option<bool> {
"view.compare" => Some(u.view == ViewMode::Compare),
"view.survey" => Some(u.view == ViewMode::Survey),
"view.people" => Some(u.view == ViewMode::People),
"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" | "map.lockMarkers" => Some(u.map.locked),
"map.showPins" => Some(u.map.show_pins),
"map.showLocations" => Some(u.map.navigator_open),
"view.reference" => Some(u.view == ViewMode::Reference),
"view.leftPanel" => Some(u.left_panel),
"view.rightPanel" => Some(u.right != RightPanel::None),
@@ -1023,6 +1090,10 @@ fn submenu_items(app: &LightcraftApp, entries: &[MenuEntry], used: &mut [bool],
children.push(MenuNode::Separator);
children.extend(dialogs);
}
if title == "Window" && name == "Map" {
children.push(MenuNode::Separator);
children.extend(map_menu(app));
}
children
}
+45
View File
@@ -1016,6 +1016,51 @@ fn edit_menu_places_the_select_and_paste_rows_with_their_kin() {
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.lockMarkers").is_some(), "Lock Markers must be in Window>Map");
assert!(find(window_nodes, "map.fit").is_some(), "the Map view's commands 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);
}
/// The interface language is chosen in Settings ▸ General (one choice per language), so Edit has no
/// Language submenu of 18 rows. The commands stay: agents and tests still switch language by id.
#[test]
+63
View File
@@ -475,6 +475,69 @@ 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" | "panel.map" => {
app.ui.view = ViewMode::Map;
Ok(json!({"view": "map"}))
}
"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}))
}
// Lock Markers (map.toggleLock / map.lock: older names); {on?}, without it toggles
"map.lockMarkers"
| "map.toggleLock"
| "map.lock"
| "map.locationFilter"
| "map.showPins"
| "map.showLocations"
| "map.settings"
| "map.location.show"
| "map.location.select"
| "map.location.new"
| "map.loadTrackLog"
// the session's command, then the map's part (fit a new track, drop a load it replaced)
| "map.trackLog"
| "map.trackLog.autoTag"
| "map.trackLog.setOffset"
| "map.trackLog.fit"
| "map.fit"
| "map.setView"
| "map.zoomIn"
| "map.zoomOut" => crate::panels::map::command(app, id, p).unwrap_or_else(|| Err(format!("unknown map command {id}"))),
"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}))
}
// 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 {
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(pos) = lightcraft_engine::map::from_gps(ph.meta.gps) {
app.ui.map.center_lat = pos.lat.clamp(-lightcraft_engine::map::MAX_LATITUDE, lightcraft_engine::map::MAX_LATITUDE);
app.ui.map.center_lon = pos.lon;
app.ui.map.zoom = 15.0;
app.ui.map.active_pin_photo = Some(id);
// the view is set: the first showing doesn't fit every photo over it
app.ui.map.fitted = true;
} else {
// no pin to show: don't leave the previous photo's pin active
app.ui.map.active_pin_photo = None;
app.toast(ctx, crate::i18n::tr("Photo has no GPS coordinates"));
}
}
} 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 {
+25
View File
@@ -71,6 +71,31 @@ 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+Alt+3"), "View"),
("view.toggleMapFilter", "Toggle Map Filter Bar", None, "View"),
("map.lockMarkers", "Lock Markers", None, "View"),
("photo.showInMap", "Show in Map", None, "Photo"),
("panel.map", "Map View", None, "Window>Map"),
("map.navigator", "Map Navigator", None, "Window>Map"),
("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, ""),
("map.fit", "Fit Map to Photos", None, ""),
("map.locationFilter", "Location Filter", None, ""),
("map.showPins", "Map Pins", None, ""),
("map.showLocations", "Saved Locations List", None, ""),
("map.settings", "Map Tiles…", None, ""),
("map.location.show", "Go to Saved Location", None, ""),
("map.location.select", "Select Photos in Saved Location", None, ""),
("map.location.new", "New Location…", None, ""),
("map.loadTrackLog", "Load Tracklog…", None, ""),
("map.trackLog.autoTag", "Auto-Tag Photos from Map Tracklog", None, ""),
("map.trackLog.setOffset", "Set Time Zone Offset…", None, ""),
("map.trackLog.fit", "Fit Map to Tracklog", None, ""),
("map.setView", "Set Map View", None, ""),
("map.zoomIn", "Zoom In on Map", None, ""),
("map.zoomOut", "Zoom Out on Map", None, ""),
("view.person", "Show Person", None, ""),
("view.faceBoxes", "Face Boxes", None, "View>Loupe Overlay"),
("view.focusPoint", "Focus Point", Some("Alt+F"), "View>Loupe Overlay"),
+1
View File
@@ -19,6 +19,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;
+7
View File
@@ -23,6 +23,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) {
@@ -279,6 +280,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()
@@ -684,10 +684,21 @@ fn pick_actual_frozen_native_focus_order_with_only_pick_insertion() {
"icon:compare",
"icon:survey",
"icon:people",
"icon:map",
"icon:sort",
]
} else {
vec!["slider:thumbSize", "icon:photoGrid", "icon:squareGrid", "icon:detail", "icon:compare", "icon:survey", "icon:people", "icon:sort"]
vec![
"slider:thumbSize",
"icon:photoGrid",
"icon:squareGrid",
"icon:detail",
"icon:compare",
"icon:survey",
"icon:people",
"icon:map",
"icon:sort",
]
};
// The rating pill's stars are one framework stop (the focused star) between Sort and the flags.
let mut expected = native.clone();
+3
View File
@@ -1624,6 +1624,9 @@ fn context_menu_locate_and_export(app: &mut LightcraftApp, ui: &mut egui::Ui, id
if Row::new(crate::i18n::tr("Show in Folders")).enabled(in_folders).show(ui) {
let _ = app.run("app.showInFolders", json!({"id": id.0}));
}
if Row::new(crate::i18n::tr("Show in Map")).show(ui) {
let _ = app.run("photo.showInMap", json!({"id": id.0}));
}
if Row::new(crate::i18n::tr("Export…")).show(ui) {
let _ = app.run("dialog.export", json!({}));
}
File diff suppressed because it is too large. Load diff
+364
View File
@@ -0,0 +1,364 @@
//! Saved locations on the Map view (LRC-MAP-LOCATIONS): every location in view is a circle with its
//! name; the active one (picked in the list) has a centre and a radius handle that move it (unless
//! Lock Markers is on), saved when let go (`map.location.update`). The list in the navigator panel
//! shows each location with the photos in view inside it, a checkbox selecting them, a private
//! mark, and a right-click menu (Go To, Select Photos, Rename…, Private, Delete… with a
//! confirmation). `+` makes one at the map's centre, or around the selected photos with a position.
//! Distances are along the Earth's surface (`lightcraft_catalog::rules::GpsCircle`), so circles
//! across the antimeridian and around a pole work. Ported in spirit from PR #906 (Jason Baldwin).
use egui::{Align2, FontId, Painter, Pos2, Rect, Stroke, pos2, vec2};
use lightcraft_catalog::rules::{EARTH_RADIUS_M, distance_m};
use lightcraft_engine::locations::SavedLocation;
use lightcraft_engine::map::Viewport;
use lightcraft_geom::{LatLon, Point};
use serde_json::{Value, json};
use crate::LightcraftApp;
use crate::state::MapUi;
use crate::theme::Tokens;
/// How far from a handle a press still takes it (points).
const HANDLE_HIT: f32 = 9.0;
/// A handle of the active location being dragged.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Handle {
Centre,
Radius,
}
/// The active location's handle being dragged: which location and handle, and where it is now.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LocationDrag {
pub id: u64,
pub handle: Handle,
pub at: Pos2,
}
/// A location as drawn this frame (`map.state` → `locations`).
#[derive(Clone, Debug)]
pub struct DrawnLocation {
pub id: u64,
pub at: Pos2,
pub radius_px: f32,
pub active: bool,
}
/// Screen points per metre at latitude `lat` for view `vp` (0 when it can't be told).
fn px_per_metre(vp: &Viewport, lat: f64) -> f64 {
let world = lightcraft_engine::map::mercator::world_size(vp.zoom);
let metres_round = 2.0 * std::f64::consts::PI * EARTH_RADIUS_M * lat.to_radians().cos().abs();
if metres_round > 1.0 { world / metres_round } else { 0.0 }
}
/// Where `l` is drawn on a canvas at `origin`: centre and radius in points (the radius capped so a
/// huge circle stays drawable).
fn placed(l: &SavedLocation, vp: &Viewport, origin: Pos2) -> Option<(Pos2, f32)> {
let c = LatLon::new(l.lat, l.lon)?;
let p = vp.to_screen(c);
let r = (l.radius * px_per_metre(vp, l.lat)).min(1e6) as f32;
let at = pos2(origin.x + p.x as f32, origin.y + p.y as f32);
(at.x.is_finite() && at.y.is_finite() && r.is_finite()).then_some((at, r))
}
/// The location `id` with a handle drag applied (what is drawn while dragging, and saved on release).
fn dragged(l: &SavedLocation, d: &LocationDrag, vp: &Viewport, origin: Pos2) -> SavedLocation {
let mut l = l.clone();
let p = vp.to_lat_lon(Point::new(f64::from(d.at.x - origin.x), f64::from(d.at.y - origin.y)));
match d.handle {
Handle::Centre => {
l.lat = p.lat;
l.lon = p.lon;
}
Handle::Radius => {
let r = distance_m(l.lat, l.lon, p.lat, p.lon);
if r.is_finite() {
l.radius = r.clamp(lightcraft_catalog::rules::MIN_RADIUS_M, lightcraft_catalog::rules::MAX_RADIUS_M);
}
}
}
l
}
/// A press at `at` on the active location's handle (unless markers are locked): the drag it starts.
pub fn grab(app: &LightcraftApp, m: &MapUi, vp: &Viewport, origin: Pos2, at: Pos2) -> Option<LocationDrag> {
if m.locked {
return None;
}
let id = m.active_location?;
let l = app.session.map.locations.get(id)?;
let (c, r) = placed(l, vp, origin)?;
let radius_handle = pos2(c.x + r, c.y);
if at.distance(radius_handle) <= HANDLE_HIT {
Some(LocationDrag { id, handle: Handle::Radius, at: radius_handle })
} else if at.distance(c) <= HANDLE_HIT {
Some(LocationDrag { id, handle: Handle::Centre, at: c })
} else {
None
}
}
/// Save a handle drag that ended over the map (`map.location.update`).
pub fn drop_drag(app: &mut LightcraftApp, ctx: &egui::Context, d: &LocationDrag, vp: &Viewport, origin: Pos2) {
let Some(l) = app.session.map.locations.get(d.id).cloned() else { return };
let moved = dragged(&l, d, vp, origin);
let p = match d.handle {
Handle::Centre => json!({"id": d.id, "lat": moved.lat, "lon": moved.lon}),
Handle::Radius => json!({"id": d.id, "radius": moved.radius}),
};
if let Err(e) = app.run("map.location.update", p) {
app.toast(ctx, e);
}
}
/// Draw every saved location in view (the active one with its handles), and record them.
pub fn draw(app: &mut LightcraftApp, painter: &Painter, canvas: Rect, vp: &Viewport, m: &MapUi) {
let origin = canvas.min;
let t = Tokens::get(painter.ctx());
let list: Vec<SavedLocation> = app.session.map.locations.list().to_vec();
for l in &list {
let shown = match m.location_drag {
Some(d) if d.id == l.id => dragged(l, &d, vp, origin),
_ => l.clone(),
};
let Some((c, r)) = placed(&shown, vp, origin) else { continue };
if !canvas.expand(r).contains(c) && !canvas.intersects(Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r))) {
continue;
}
let active = m.active_location == Some(l.id);
let colour = if l.private { t.map_location_private } else { t.map_location };
painter.circle_filled(c, r.max(3.0), colour.gamma_multiply(if active { 0.16 } else { 0.08 }));
painter.circle_stroke(c, r.max(3.0), Stroke::new(if active { 2.0 } else { 1.5 }, colour.gamma_multiply(0.85)));
painter.text(pos2(c.x, c.y - r.max(3.0) - 4.0), Align2::CENTER_BOTTOM, &l.name, FontId::proportional(11.5), t.map_location_label);
if active && !m.locked {
for h in [c, pos2(c.x + r, c.y)] {
painter.circle(h, 5.0, t.map_edge_hover, Stroke::new(1.5, colour));
}
}
app.map_drawn.locations.push(DrawnLocation { id: l.id, at: c, radius_px: r, active });
}
}
/// Zoom that shows a circle of `radius` metres in a map of ~800 points.
pub fn zoom_for(radius: f64) -> f64 {
let r = if radius.is_finite() { radius.max(1.0) } else { 1000.0 };
(40_075_016.0 / (r * 2.0 * 3.0)).log2().clamp(2.0, 17.0)
}
/// The navigator panel's list: each location with the photos in view inside it, a checkbox
/// selecting them, a private mark, a right-click menu; `+` makes a new one.
pub fn list(app: &mut LightcraftApp, ui: &mut egui::Ui, m: &mut MapUi, center: &mut LatLon, zoom: &mut f64) {
let t = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.add_space(8.0);
ui.label(egui::RichText::new(crate::i18n::tr("Saved Locations")).strong().color(t.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.add_space(8.0);
let b = ui.button("+").on_hover_text(crate::i18n::tr("New saved location: around the selected photos, or at the map's centre"));
crate::widgets::register(ui, "map:location:new", b.rect);
if b.clicked() {
new_location(app, ui.ctx(), m, *center);
}
});
});
ui.add_space(6.0);
let selected: std::collections::HashSet<u64> = app.session.selection.ids.iter().map(|p| p.0).collect();
// which photos each location holds: found again only when the points or the locations change
let revision = app.session.map.locations.revision();
if app.map_points.inside.as_ref().is_none_or(|(r, _)| *r != revision) {
// one index of the points by latitude: each circle looks only at those in its band
let index = lightcraft_engine::locations::PositionIndex::new(app.map_points.points.iter().map(|p| (p.id, Some((p.pos.lat, p.pos.lon)))));
let inside = app.session.map.locations.list().iter().map(|l| (l.id, index.inside(&l.circle()))).collect();
app.map_points.inside = Some((revision, inside));
}
let held = app.map_points.inside.as_ref().map(|(_, m)| m);
let rows: Vec<(SavedLocation, Vec<u64>)> =
app.session.map.locations.list().iter().map(|l| (l.clone(), held.and_then(|m| m.get(&l.id)).cloned().unwrap_or_default())).collect();
let mut action: Option<(u64, &'static str, Value)> = None;
egui::ScrollArea::vertical().id_salt("map-locations").show(ui, |ui| {
if rows.is_empty() {
ui.horizontal(|ui| {
ui.add_space(12.0);
ui.label(egui::RichText::new(crate::i18n::tr("No saved locations. Click + to save.")).small().italics().color(t.text_dim));
});
}
for (l, inside) in &rows {
ui.horizontal(|ui| {
ui.add_space(6.0);
// the checkbox: all its photos in view selected
let mut all = !inside.is_empty() && inside.iter().all(|id| selected.contains(id));
let cb = ui.add_enabled(!inside.is_empty(), egui::Checkbox::without_text(&mut all));
crate::widgets::register(ui, format!("map:location:check:{}", l.id), cb.rect);
if cb.changed() {
action = Some((l.id, if all { "select" } else { "deselect" }, Value::Null));
}
if m.renaming.as_ref().is_some_and(|(id, _)| *id == l.id) {
if let Some((_, text)) = m.renaming.as_mut() {
let r = crate::text_field::TextField::singleline("field:locationName", text).width(120.0).show(ui);
if r.committed() {
action = Some((l.id, "rename", json!(text.clone())));
} else if r.cancelled() || !r.editing && !r.response.has_focus() && r.ending.is_some() {
m.renaming = None;
}
if !r.editing {
crate::text_field::focus(ui.ctx(), "field:locationName");
}
}
} else {
let label = if l.private { format!("🔒 {}", l.name) } else { l.name.clone() };
let resp = ui.selectable_label(m.active_location == Some(l.id), label);
crate::widgets::register(ui, format!("map:location:{}", l.id), resp.rect);
if resp.clicked() {
action = Some((l.id, "goto", Value::Null));
}
resp.context_menu(|ui| {
for (key, label) in
[("goto", "Go To"), ("select", "Select Photos"), ("rename", "Rename…"), ("private", "Private"), ("delete", "Delete…")]
{
let b = if key == "private" {
let mut on = l.private;
let r = ui.checkbox(&mut on, crate::i18n::tr(label));
if r.clicked() {
action = Some((l.id, "private", json!(on)));
ui.close();
}
r
} else {
let r = ui.button(crate::i18n::tr(label));
if r.clicked() {
action = Some((l.id, key, Value::Null));
ui.close();
}
r
};
crate::widgets::register(ui, format!("map:location:menu:{key}"), b.rect);
}
});
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.add_space(8.0);
ui.label(egui::RichText::new(inside.len().to_string()).small().color(t.text_dim));
});
});
// Delete… asks first
if m.confirm_delete == Some(l.id) {
ui.horizontal(|ui| {
ui.add_space(24.0);
ui.label(egui::RichText::new(crate::i18n::tr_format!("Delete “{name}”?", name = l.name)).small().color(t.text));
let d = ui.small_button(crate::i18n::tr("Delete"));
crate::widgets::register(ui, "map:location:confirmDelete", d.rect);
if d.clicked() {
action = Some((l.id, "remove", Value::Null));
}
if ui.small_button(crate::i18n::tr("Cancel")).clicked() {
m.confirm_delete = None;
}
});
}
}
});
if let Some((id, what, v)) = action {
act(app, ui.ctx(), m, (center, zoom), id, what, v);
}
}
/// `+`: a location around the selected photos that have a position, else at the map's centre.
fn new_location(app: &mut LightcraftApp, ctx: &egui::Context, m: &mut MapUi, center: LatLon) {
let n = app.session.map.locations.len() + 1;
let name = crate::i18n::tr_format!("Location {n}", n = n);
let any_placed = app
.session
.selection
.ids
.iter()
.any(|id| app.session.catalog.photo(*id).is_some_and(|p| lightcraft_engine::map::from_gps(p.meta.gps).is_some()));
let p = if any_placed {
json!({"name": name, "fromSelection": true})
} else {
json!({"name": name, "lat": center.lat, "lon": center.lon, "radius": 1000.0})
};
match app.run("map.location.add", p) {
Ok(v) => {
m.active_location = v["id"].as_u64();
m.renaming = m.active_location.map(|id| (id, name));
}
Err(e) => app.toast(ctx, e),
}
}
/// What a list row, its menu or the confirmation asked for.
/// (`view`: the map's centre and zoom, which Go To moves)
fn act(app: &mut LightcraftApp, ctx: &egui::Context, m: &mut MapUi, view: (&mut LatLon, &mut f64), id: u64, what: &str, v: Value) {
let (center, zoom) = view;
let r = match what {
"goto" => {
if let Some(l) = app.session.map.locations.get(id)
&& let Some(c) = LatLon::new(l.lat, l.lon)
{
*center = c;
*zoom = zoom_for(l.radius);
m.fitted = true;
}
m.active_location = Some(id);
Ok(Value::Null)
}
"select" | "deselect" => {
let inside: Vec<u64> = match app.session.execute("map.location.photos", &json!({"id": id, "inView": true})) {
Ok(r) => r["ids"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(),
Err(e) => {
app.toast(ctx, e.to_string());
return;
}
};
if what == "select" {
app.run("library.select", json!({"ids": inside, "mode": "add"}))
} else {
// the selection without the location's photos (the active one kept when it stays);
// a set, so unticking a large location over a large selection stays linear
let inside: std::collections::HashSet<u64> = inside.into_iter().collect();
let rest: Vec<u64> = app.session.selection.ids.iter().map(|p| p.0).filter(|p| !inside.contains(p)).collect();
let active = app.session.selection.active.map(|a| a.0).filter(|a| rest.contains(a));
let mut q = json!({"ids": rest});
if let Some(a) = active {
q["active"] = json!(a);
}
app.run("library.select", q)
}
}
"rename" if v.is_null() => {
m.renaming = app.session.map.locations.get(id).map(|l| (id, l.name.clone()));
Ok(Value::Null)
}
"rename" => {
m.renaming = None;
app.run("map.location.update", json!({"id": id, "name": v}))
}
"private" => app.run("map.location.update", json!({"id": id, "private": v})),
"delete" => {
m.confirm_delete = Some(id);
Ok(Value::Null)
}
"remove" => {
m.confirm_delete = None;
if m.active_location == Some(id) {
m.active_location = None;
}
app.run("map.location.remove", json!({"id": id}))
}
_ => Ok(Value::Null),
};
if let Err(e) = r {
app.toast(ctx, e);
}
}
/// `map.state` → `locations`: each location drawn last frame `{id, x, y, radiusPx, active}`.
pub fn state(app: &LightcraftApp) -> Value {
json!(
app.map_drawn
.locations
.iter()
.map(|l| json!({"id": l.id, "x": l.at.x, "y": l.at.y, "radiusPx": l.radius_px, "active": l.active}))
.collect::<Vec<_>>()
)
}
+270
View File
@@ -0,0 +1,270 @@
//! 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. It lives
//! in the egui context's memory, so each window (and each headless test) has its own.
//! - 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::{Arc, 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, TileImage, 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)]
pub(crate) struct Store {
textures: HashMap<TexKey, (TextureHandle, u64)>,
/// Tiles wanted by the maps drawn in the pass `frame`, and in the pass before.
this_frame: Vec<TileKey>,
last_frame: Vec<TileKey>,
frame: u64,
/// The tiles that arrived this pass, as the service reported them: drawn from here when the
/// service already let go of them (more tiles arrived at once than it keeps in memory), so a
/// tile in view isn't left blank until the view changes.
arrived: HashMap<TexKey, Arc<TileImage>>,
}
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;
self.arrived.clear();
}
}
/// The tiles to ask the service for: this frame's, then the last frame's not yet listed.
fn wanted(&self) -> Vec<TileKey> {
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 (or the one that arrived this
/// pass) if there is one.
fn texture(&mut self, ctx: &egui::Context, svc: &TileService, source: &str, key: TileKey, pass: u64) -> Option<egui::TextureId> {
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).or_else(|| self.arrived.get(&k).cloned())?;
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);
}
}
}
/// The context's store (created on first use).
fn store(ctx: &egui::Context) -> Arc<Mutex<Store>> {
let id = egui::Id::unique("lightcraft-map-tiles");
ctx.data_mut(|d| d.get_temp_mut_or_default::<Arc<Mutex<Store>>>(id).clone())
}
/// 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() {
let at = if rect.height() < 240.0 { egui::pos2(rect.center().x, rect.top() + 14.0) } else { rect.center() };
painter.text(
at,
Align2::CENTER_CENTER,
crate::i18n::tr("Map tiles are off (Settings › Map)"),
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() } };
if cfg!(target_arch = "wasm32") && !svc.can_load() {
// wasm32 has no tile transport yet: say so instead of leaving a silent grey map (a native
// session not put online also can't load, but stays a plain grey map: see
// `a_session_not_put_online_never_fetches`)
let at = if rect.height() < 240.0 { egui::pos2(rect.center().x, rect.top() + 14.0) } else { rect.center() };
painter.text(
at,
Align2::CENTER_CENTER,
crate::i18n::tr("Map tiles can't load in this build"),
FontId::proportional(12.0),
Color32::from_rgb(90, 96, 104),
);
return Drawn { offline: true, ..Drawn::default() };
}
let view = viewport(rect, center, zoom);
let max_zoom = source.max_zoom();
// the URL-aware id: a custom source re-pointed at another server must not show the old one's tiles
let source_id = source.cache_id();
let shared = store(&ctx);
let mut guard = shared.lock().unwrap_or_else(PoisonError::into_inner);
let store = &mut *guard;
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, image, .. } = e {
store.textures.remove(&(source_id.clone(), *key));
store.arrived.insert((source_id.clone(), *key), Arc::clone(image));
}
}
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 shared = store(ctx);
let mut guard = shared.lock().unwrap_or_else(PoisonError::into_inner);
let store = &mut *guard;
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(ctx: &egui::Context) -> usize {
store(ctx).lock().unwrap_or_else(PoisonError::into_inner).textures.len()
}
#[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());
}
}
+538
View File
@@ -0,0 +1,538 @@
//! Track logs on the Map view (Lightroom Classic's Map ▸ Tracklog): the loaded GPX file's tracks
//! drawn as lines, the Tracklog button and its menu (load, pick the track, its time range, the
//! camera's time zone offset, Auto-Tag the selected photos, fit, clear), and small marks where
//! the selected photos' capture times fall on the track.
//!
//! The track log lives in the session (`map.trackLog`, [`lightcraft_engine::tracklog`]): parsed,
//! projected and ranked for simplification once when loaded. Here each frame only takes the
//! points kept at the view's zoom ([`lightcraft_map::Level`], rebuilt when the whole zoom changes)
//! and clips them to the view ([`lightcraft_map::Level::screen_lines`], recomputed when the view
//! moves). Segments (logging gaps) are separate lines; a line crossing the antimeridian is cut
//! there and drawn the short way. With a track picked in the menu the others are drawn dimmed.
//!
//! The marks of the selected photos come from the same reading of capture times and the same
//! track the menu's Auto-Tag uses ([`lightcraft_engine::tracklog::positions`]), so a mark is
//! exactly where Auto-Tag would put that photo; they are recomputed when the selection, the catalog or the track changes, for
//! at most [`MAX_TICKS`] selected photos.
use egui::{Pos2, Rect, Stroke, pos2};
use lightcraft_engine::map::track::Level;
use lightcraft_engine::map::{Bounds, Viewport, fit_bounds};
use lightcraft_geom::LatLon;
use lightcraft_geom::Point;
use serde_json::{Value, json};
use crate::LightcraftApp;
use crate::theme::Tokens;
use crate::widgets::register;
/// Selected photos marked on the track, at most.
pub const MAX_TICKS: usize = 5000;
/// Tracks listed in the menu (the rest are picked with `map.trackLog {active}`).
const MAX_LISTED: usize = 40;
/// Room drawn around the view so a line's width never shows its clipped end.
const CLIP_MARGIN: f64 = 8.0;
/// What the map draws of the track log.
#[derive(Default)]
pub struct TrackState {
/// Each track simplified for one zoom, and what for (track generation, zoom).
levels: Vec<Level>,
levels_for: Option<(u64, u8)>,
/// Each track's lines on screen (canvas coordinates), and what for (generation, zoom, view).
lines: Vec<Vec<Vec<Point>>>,
lines_for: Option<(u64, u8, [u64; 5])>,
/// Fit the track on the next frame (it was loaded before the map had a size).
pub fit_pending: bool,
/// The selected photos' positions on the track, and what for (generation, catalog revision,
/// selection).
ticks: Vec<(u64, LatLon)>,
ticks_for: Option<(u64, u64, u64)>,
/// Marks drawn last frame (screen points).
shown_ticks: Vec<(u64, Pos2)>,
/// Points handed to the painter last frame, the time to simplify (last rebuild) and to clip
/// (last view change), ms.
pub drawn_points: usize,
pub level_ms: f64,
pub clip_ms: f64,
/// A track log being read on a worker thread (Load Tracklog…), and its file.
pending: Option<(std::sync::mpsc::Receiver<Result<lightcraft_engine::tracklog::LoadedTrack, String>>, String)>,
}
/// Read and prepare the track log at `path` off the UI thread, with a row on the activity stack
/// ("Loading tracklog") for as long as it takes; [`poll`] installs it (and fits the map to it) or
/// shows why it was refused, and the loaded log stays until then. On the web, where there are no
/// threads, it is read at once.
pub fn load(app: &mut LightcraftApp, path: String) -> Result<Value, String> {
#[cfg(not(target_arch = "wasm32"))]
{
let (tx, rx) = std::sync::mpsc::channel();
let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned());
let guard = app.session.activity.start(
"import",
&crate::i18n::tr_format!("Loading tracklog {name}", name = name),
lightcraft_engine::activity::Cancel::No,
);
let file = path.clone();
std::thread::Builder::new()
.name("tracklog-load".into())
.spawn(move || {
let _row = guard;
let r = std::panic::catch_unwind(|| lightcraft_engine::tracklog::prepare_file(&file))
.unwrap_or_else(|_| Err("map.trackLog: internal error reading the track log".into()));
let _ = tx.send(r);
})
.map_err(|e| format!("map.loadTrackLog: can't start a thread: {e}"))?;
app.map_tracks.pending = Some((rx, path.clone()));
Ok(json!({"loading": path}))
}
#[cfg(target_arch = "wasm32")]
{
let t = lightcraft_engine::tracklog::prepare_file(&path)?;
let r = lightcraft_engine::tracklog::install(&mut app.session, t);
fit(app);
Ok(r)
}
}
/// Take a track log a worker finished reading: install it and fit the map to it, or say why it
/// was refused. Called every frame.
pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) {
let Some((rx, _)) = app.map_tracks.pending.as_ref() else { return };
match rx.try_recv() {
Ok(Ok(t)) => {
app.map_tracks.pending = None;
lightcraft_engine::tracklog::install(&mut app.session, t);
fit(app);
ctx.request_repaint();
}
Ok(Err(e)) => {
app.map_tracks.pending = None;
app.toast_error(ctx, e);
}
Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(50)),
Err(std::sync::mpsc::TryRecvError::Disconnected) => app.map_tracks.pending = None,
}
}
/// The zoom whose simplification the view uses: the next whole zoom (finer than needed between).
fn level_zoom(vp: &Viewport) -> u8 {
let z = vp.zoom.ceil();
if z.is_finite() { z.clamp(0.0, f64::from(lightcraft_engine::map::MAX_ZOOM)) as u8 } else { 0 }
}
/// Draw the track log on the map (after the tiles and saved locations, under the pins).
pub fn draw(app: &mut LightcraftApp, painter: &egui::Painter, t: &Tokens, canvas: Rect, vp: &Viewport) {
let generation = app.session.map.track_generation;
let Some(track) = app.session.map.track.as_ref() else {
let s = &mut app.map_tracks;
if s.levels_for.is_some() {
// the drawing caches only: a log still loading keeps its receiver
*s = TrackState { fit_pending: s.fit_pending, pending: s.pending.take(), ..Default::default() };
}
return;
};
let shapes = track.shapes.clone();
let active = track.active;
let z = level_zoom(vp);
let s = &mut app.map_tracks;
if s.levels_for != Some((generation, z)) {
let t0 = crate::now_ms();
s.levels = shapes.iter().map(|sh| sh.level(z)).collect();
s.levels_for = Some((generation, z));
s.level_ms = crate::now_ms() - t0;
s.lines_for = None;
}
let key = (generation, z, [vp.center.lat.to_bits(), vp.center.lon.to_bits(), vp.zoom.to_bits(), vp.width.to_bits(), vp.height.to_bits()]);
if s.lines_for != Some(key) {
let t0 = crate::now_ms();
s.lines = s.levels.iter().map(|l| l.screen_lines(vp, CLIP_MARGIN)).collect();
s.lines_for = Some(key);
s.clip_ms = crate::now_ms() - t0;
}
let at = |p: &Point| pos2(canvas.min.x + p.x as f32, canvas.min.y + p.y as f32);
let mut drawn = 0;
// the other tracks first (dimmed when one is picked), the active one on top
let mut order: Vec<usize> = (0..s.lines.len()).filter(|i| Some(*i) != active).collect();
order.extend(active.filter(|a| *a < s.lines.len()));
for i in order {
let on = active.is_none_or(|a| a == i);
let (w, color) = if on { (3.0, t.map_track) } else { (2.0, t.map_track.gamma_multiply(0.45)) };
for line in s.lines.get(i).map(Vec::as_slice).unwrap_or(&[]) {
let pts: Vec<Pos2> = line.iter().map(at).filter(|p| p.x.is_finite() && p.y.is_finite()).collect();
drawn += pts.len();
match pts.as_slice() {
[] => {}
[one] => {
painter.circle(*one, w + 1.0, color, Stroke::new(1.5, t.map_track_casing));
}
_ => {
if on {
painter.add(egui::Shape::line(pts.clone(), Stroke::new(w + 2.5, t.map_track_casing)));
}
painter.add(egui::Shape::line(pts, Stroke::new(w, color)));
}
}
}
}
s.drawn_points = drawn;
// the selected photos' places on the track
refresh_ticks(app);
let mut shown = Vec::new();
for (id, pos) in &app.map_tracks.ticks {
let p = vp.to_screen(*pos);
let q = pos2(canvas.min.x + p.x as f32, canvas.min.y + p.y as f32);
if !canvas.expand(4.0).contains(q) {
continue;
}
painter.circle(q, 4.0, t.map_edge_hover, Stroke::new(2.0, t.accent));
shown.push((*id, q));
}
app.map_tracks.shown_ticks = shown;
}
/// Recompute the selected photos' positions on the track when the selection, the catalog or the
/// track changed.
fn refresh_ticks(app: &mut LightcraftApp) {
let sel = &app.session.selection.ids;
let hash = sel.iter().fold(sel.len() as u64, |h, id| h.rotate_left(7) ^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15));
let key = (app.session.map.track_generation, app.session.catalog.revision, hash);
if app.map_tracks.ticks_for == Some(key) {
return;
}
app.map_tracks.ticks_for = Some(key);
app.map_tracks.ticks.clear();
if sel.is_empty() || sel.len() > MAX_TICKS || app.session.map.track.is_none() {
return;
}
let ids = sel.clone();
app.map_tracks.ticks = lightcraft_engine::tracklog::positions(&app.session, &ids)
.into_iter()
.filter_map(|(id, lat, lon)| Some((id, LatLon::new(lat, lon)?)))
.collect();
}
/// The box of the active track (all tracks when none is picked).
fn track_bounds(app: &LightcraftApp) -> Option<Bounds> {
let t = app.session.map.track.as_ref()?;
match t.active.and_then(|i| t.shapes.get(i)) {
Some(sh) => sh.bounds(),
None => {
let corners: Vec<(f64, f64)> =
t.shapes.iter().filter_map(|sh| sh.bounds()).flat_map(|b| [(b.south, b.west), (b.north, b.east)]).collect();
Bounds::of(corners)
}
}
}
/// Fit the map to the track (the canvas last drawn, or a typical one before the map was shown).
pub fn fit(app: &mut LightcraftApp) -> bool {
let Some(b) = track_bounds(app) else { return false };
let (w, h) = app.ui.map.last_canvas.map_or((1000.0, 700.0), |r| (f64::from(r.width()), f64::from(r.height())));
let max_zoom = f64::from(app.session.map.effective_source().max_zoom()).min(super::FIT_MAX_ZOOM);
let v = fit_bounds(&b, w, h, 48.0, max_zoom);
let m = &mut app.ui.map;
m.center_lat = v.center.lat;
m.center_lon = v.center.lon;
m.zoom = v.zoom.floor().max(1.0);
m.fitted = true;
app.map_tracks.fit_pending = false;
super::apply_view_area(app);
true
}
/// "2026-05-01T12:00:00" → "2026-05-01 12:00:00".
fn local(v: &Value) -> String {
v.as_str().unwrap_or("").replacen('T', " ", 1)
}
/// "2 h 05 min", "4 min 10 s".
fn duration(secs: f64) -> String {
let s = if secs.is_finite() { secs.max(0.0).round() as u64 } else { 0 };
let (h, m, sec) = (s / 3600, s % 3600 / 60, s % 60);
if h > 0 {
format!("{h} h {m:02} min")
} else if m > 0 {
format!("{m} min {sec:02} s")
} else {
format!("{sec} s")
}
}
/// The Tracklog button (in the map's bottom toolbar) and its menu.
pub fn button(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let loaded = app.session.map.track.is_some();
let b = ui.selectable_label(loaded, crate::i18n::tr("Tracklog"));
register(ui, "map:tracklog", b.rect);
let hover = match app.session.map.track.as_ref() {
Some(tr) => {
let off = tr.offset_minutes.unwrap_or(0);
let range = tr.span().map(|(a, b)| {
let (a, b) = (lightcraft_engine::tracklog::iso(a, off), lightcraft_engine::tracklog::iso(b, off));
format!(" · {} – {}", a.replacen('T', " ", 1), b.replacen('T', " ", 1))
});
format!("{}{}", tr.name, range.unwrap_or_default())
}
None => crate::i18n::tr("Load a GPS track log (GPX) to show it on the map and tag photos from it").to_string(),
};
let b = b.on_hover_text(hover);
// the menu's contents only while it is open
egui::Popup::menu(&b).show(|ui| {
let r = report(app);
menu(app, ui, &r);
});
}
fn report(app: &LightcraftApp) -> Value {
lightcraft_engine::tracklog::report(app.session.map.track.as_ref(), app.session.map.track_generation)
}
fn item(ui: &mut egui::Ui, id: &str, enabled: bool, text: impl Into<egui::WidgetText>) -> egui::Response {
let b = ui.add_enabled(enabled, egui::Button::new(text));
register(ui, format!("map:tracklog:{id}"), b.rect);
b
}
fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Value) {
let t = Tokens::get(ui.ctx());
ui.set_min_width(300.0);
let run = |app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, p: Value| {
if let Err(e) = app.run(id, p) {
app.toast(ui.ctx(), e);
}
ui.close();
};
let can_load = app.services.pick_tracklog.is_some() || app.services.picker.is_some();
if r["loaded"] != true {
if item(ui, "load", can_load, crate::i18n::tr("Load Tracklog…")).clicked() {
run(app, ui, "map.loadTrackLog", json!({}));
}
return;
}
let dim = |s: String| egui::RichText::new(s).font(t.font(11.5)).color(t.text_label);
let head = ui.label(egui::RichText::new(r["name"].as_str().unwrap_or("")).font(t.semibold(12.5)).color(t.text));
register(ui, "map:tracklog:name", head.rect);
// the tracks: all, or one (what Auto-Tag uses and the map highlights)
let tracks = r["tracks"].as_array().cloned().unwrap_or_default();
let active = r["active"].as_u64();
if tracks.len() > 1 {
let all = ui.add(egui::Button::selectable(active.is_none(), crate::i18n::tr_format!("All Tracks ({n})", n = tracks.len())));
register(ui, "map:tracklog:track:all", all.rect);
if all.clicked() && active.is_some() {
run(app, ui, "map.trackLog", json!({"active": "all"}));
}
}
let off = r["offset"].as_str().map(str::to_string);
for tr in tracks.iter().take(MAX_LISTED) {
let i = tr["index"].as_u64().unwrap_or(0);
let name =
tr["name"].as_str().filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| crate::i18n::tr_format!("Track {n}", n = i + 1));
let text = format!("{name} · {} {}", tr["points"], crate::i18n::tr("points"));
let on = active == Some(i) || (tracks.len() == 1 && active.is_none());
let b = ui.add(egui::Button::selectable(on, text));
register(ui, format!("map:tracklog:track:{i}"), b.rect);
if b.clicked() && active != Some(i) {
run(app, ui, "map.trackLog", json!({"active": i}));
}
}
if tracks.len() > MAX_LISTED {
ui.label(dim(crate::i18n::tr_format!("{n} more tracks", n = tracks.len() - MAX_LISTED)));
}
ui.separator();
// the time range, on the camera's clock (the offset tagging uses)
let zone = match &off {
Some(o) => crate::i18n::tr_format!("camera time, UTC{o}", o = o),
None => crate::i18n::tr("UTC: no time zone offset set").to_string(),
};
let info = ui.label(dim(format!(
"{} {}\n{} {}\n{} {} ({zone})",
crate::i18n::tr("Start:"),
local(&r["startLocal"]),
crate::i18n::tr("End:"),
local(&r["endLocal"]),
crate::i18n::tr("Duration:"),
duration(r["duration"].as_f64().unwrap_or(0.0)),
)));
register(ui, "map:tracklog:info", info.rect);
let offset_label = match &off {
Some(o) => crate::i18n::tr_format!("Set Time Zone Offset… (UTC{o})", o = o),
None => crate::i18n::tr("Set Time Zone Offset…").to_string(),
};
if item(ui, "offset", true, offset_label).clicked() {
run(app, ui, "map.trackLog.setOffset", json!({}));
}
ui.separator();
let n = app.session.targets(&json!({})).unwrap_or_default().len();
let on_track = app.map_tracks.ticks.len();
let label =
if n == 1 { crate::i18n::tr("Auto-Tag Selected Photo").to_string() } else { crate::i18n::tr_format!("Auto-Tag {n} Selected Photos", n = n) };
let b = item(ui, "autoTag", n > 0, label);
let b = if n > 0 && n <= MAX_TICKS {
b.on_hover_text(crate::i18n::tr_format!("{m} of them fall within the track's time range", m = on_track))
} else {
b
};
if b.clicked() {
run(app, ui, "map.trackLog.autoTag", json!({}));
}
if item(ui, "fit", true, crate::i18n::tr("Fit Map to Tracklog")).clicked() {
run(app, ui, "map.trackLog.fit", json!({}));
}
ui.separator();
if item(ui, "load", can_load, crate::i18n::tr("Load Another Tracklog…")).clicked() {
run(app, ui, "map.loadTrackLog", json!({}));
}
if item(ui, "clear", true, crate::i18n::tr("Clear Tracklog")).clicked() {
run(app, ui, "map.trackLog", json!({"clear": true}));
}
}
/// The message after tagging (`photo.autoTagTracklog`'s answer).
pub fn tagged_message(v: &Value) -> String {
let n = v["tagged"].as_u64().unwrap_or(0);
let sk = &v["skipped"];
let mut msg = if n == 1 {
crate::i18n::tr("Tagged 1 photo from the tracklog").to_string()
} else {
crate::i18n::tr_format!("Tagged {n} photos from the tracklog", n = n)
};
let outside = sk["outside"].as_u64().unwrap_or(0);
if outside > 0 {
msg += &crate::i18n::tr_format!("; {outside} outside its time range", outside = outside);
}
let kept = sk["hasGps"].as_u64().unwrap_or(0);
if kept > 0 {
msg += &crate::i18n::tr_format!("; {kept} already had a location", kept = kept);
}
msg
}
/// The map's track log UI commands (`None`: not one of them).
pub fn command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
let ctx = app.tasks.repaint.clone().unwrap_or_default();
let r = match id {
"map.trackLog" => {
// the session's command, then the map fits a newly loaded (or picked) track
let r = app.session.execute(id, p).map_err(|e| e.to_string());
// a track log loaded or cleared here replaces any still being read: that one, when it
// arrives, must not overwrite this (a query or an offset leaves it to come; a null
// `path` / `gpx` is not given, as the engine reads it)
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
let replaced = given("path") || given("gpx") || p.get("clear") == Some(&Value::Bool(true));
if r.is_ok() && replaced {
app.map_tracks.pending = None;
}
// (a null `active` means all tracks: a pick, so it fits too)
let moved = given("path") || given("gpx") || p.get("active").is_some();
if r.is_ok() && moved && p.get("fit") != Some(&Value::Bool(false)) {
fit(app);
}
r
}
"map.loadTrackLog" => {
let path = match p.get("path").and_then(Value::as_str) {
Some(x) => Some(x.to_string()),
None => {
let req = crate::pick::PickRequest::file(crate::i18n::tr("Load Tracklog"), crate::i18n::tr("GPS Track Log"), &["gpx"]);
match crate::pick::ask(app, id, p, "path", req, |s| s.pick_tracklog.as_mut().map(|f| f())) {
crate::pick::Picked::Now(v) => v.into_iter().next(),
crate::pick::Picked::Later | crate::pick::Picked::Unavailable => None,
}
}
};
let Some(path) = path else { return Some(Ok(Value::Null)) };
load(app, path)
}
"map.trackLog.fit" => {
if fit(app) {
Ok(super::state(app))
} else {
Err("map.trackLog.fit: no track log is loaded".into())
}
}
"map.trackLog.setOffset" => {
if app.session.map.track.is_none() {
return Some(Err("map.trackLog.setOffset: no track log is loaded".into()));
}
match p.get("offset") {
Some(o) => app.session.execute("map.trackLog", &json!({"offset": o})).map_err(|e| e.to_string()),
None => {
let cur = app
.session
.map
.track
.as_ref()
.and_then(|t| t.offset_minutes)
.map(lightcraft_engine::tracklog::fmt_offset)
.unwrap_or_default();
crate::panels::dialogs::prompt(
app,
"Set Time Zone Offset",
"Camera time zone, e.g. -07:00 (empty: UTC)",
&cur,
"map.trackLog.setOffset",
json!({}),
"offset",
);
Ok(Value::Null)
}
}
}
"map.trackLog.autoTag" => {
let Some(track) = app.session.map.track.as_ref() else {
return Some(Err("map.trackLog.autoTag: no track log is loaded (Tracklog ▸ Load Tracklog…)".into()));
};
let has_offset = track.offset_minutes.is_some();
let mut params = p.as_object().cloned().unwrap_or_default();
match params.remove("offset") {
// the camera's zone, asked once for the track (kept with it, so the marks follow)
Some(o) => {
if let Err(e) = app.session.execute("map.trackLog", &json!({"offset": o})) {
return Some(Err(e.to_string()));
}
}
None if !has_offset => {
crate::panels::dialogs::prompt(
app,
"Auto-Tag from Tracklog",
"Camera time zone, e.g. -07:00 (empty: UTC)",
"",
"map.trackLog.autoTag",
Value::Object(params),
"offset",
);
return Some(Ok(Value::Null));
}
None => {}
}
params.insert("loaded".into(), json!(true));
let r = app.run("photo.autoTagTracklog", Value::Object(params));
if let Ok(v) = &r {
app.toast(&ctx, tagged_message(v));
}
r
}
_ => return None,
};
Some(r)
}
/// `map.state` → `trackLog`: what is loaded and drawn.
pub fn state(app: &LightcraftApp, s: &mut Value) {
let mut r = report(app);
r["loading"] = json!(app.map_tracks.pending.as_ref().map(|(_, p)| p.clone()));
if r["loaded"] == true {
let tr = &app.map_tracks;
r["drawn"] = json!({
"lines": tr.lines.iter().map(|l| l.len()).collect::<Vec<_>>(),
"points": tr.drawn_points,
"levelPoints": tr.levels.iter().map(|l| l.points).collect::<Vec<_>>(),
"zoom": tr.levels_for.map(|(_, z)| z),
"levelMs": tr.level_ms,
"clipMs": tr.clip_ms,
});
r["ticks"] = json!(tr.shown_ticks.iter().map(|(id, p)| json!({"id": id, "x": p.x, "y": p.y})).collect::<Vec<_>>());
r["onTrack"] = json!(tr.ticks.len());
}
s["trackLog"] = r;
}
+43 -14
View File
@@ -160,12 +160,40 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
{
app.toast(ui.ctx(), e);
}
// the fields' width (the map below keeps to it)
let width = r.response.rect.width();
// the map of the shown (active) photo's place, also while the selected photos' places
// differ; a click on it opens the Map view there
let gps = app.session.catalog.photo(id).and_then(|ph| ph.meta.gps);
if let Some(pos) = lightcraft_engine::map::from_gps(gps) {
// inside a private saved location: no map (and so no tiles of the place fetched) until asked
// (the approval is for this photo in this location: in another one it asks again, also in a
// different place that reuses a deleted location's id)
let private = app.session.map.locations.private_at(gps).map(|l| ((l.id, l.lat.to_bits(), l.lon.to_bits()), l.name.clone()));
ui.add_space(6.0);
match private {
Some(((location, lat, lon), name)) if !app.ui.map.private_shown.contains(&(id.0, location, lat, lon)) => {
ui.horizontal_wrapped(|ui| {
ui.label(
egui::RichText::new(crate::i18n::tr_format!("In private location “{name}”", name = name)).size(11.0).color(t.text_dim),
);
if text_button(ui, "showPrivateMap", crate::i18n::tr("Show Map"), false).clicked() {
app.ui.map.private_shown.push((id.0, location, lat, lon));
}
});
}
_ => crate::panels::map::mini_map(app, ui, id, pos, width),
}
ui.add_space(4.0);
}
// (one photo's place: not shown while the selected photos' places differ)
if let Some((la, lo)) = m.gps.filter(|_| !gps_mixed) {
let pretty = format!("{:.5}° {}, {:.5}° {}", la.abs(), if la >= 0.0 { "N" } else { "S" }, lo.abs(), if lo >= 0.0 { "E" } else { "W" });
ui.horizontal(|ui| {
ui.label(egui::RichText::new(pretty).size(11.0).color(t.text_dim));
if text_button(ui, "showOnMap", crate::i18n::tr("Show on Map"), false)
ui.add(egui::Label::new(egui::RichText::new(pretty).size(11.0).color(t.text_dim)).truncate());
// the place's buttons, wrapping in a narrow panel
ui.horizontal_wrapped(|ui| {
// the button keeps its old widget id (`showOnMap`)
if text_button(ui, "showOnMap", crate::i18n::tr("Open in Browser"), false)
.on_hover_text(crate::i18n::tr("Open the place in OpenStreetMap"))
.clicked()
{
@@ -174,18 +202,19 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
app.toast(ui.ctx(), e);
}
}
if text_button(ui, "fillLocation", crate::i18n::tr("Fill Location"), false)
.on_hover_text(format!(
"{}
{}",
crate::i18n::tr("Fill empty City, State and Country from GPS (offline GeoNames place names)"),
crate::i18n::tr("The place names list towns of 15,000 people or more: in a smaller one, City gets the nearest larger town.")
))
.clicked()
&& let Err(e) = app.run("metadata.reverseGeocode", json!({}))
{
app.toast_error(ui.ctx(), e);
}
});
if text_button(ui, "fillLocation", crate::i18n::tr("Fill Location"), false)
.on_hover_text(format!(
"{}\n{}",
crate::i18n::tr("Fill empty City, State and Country from GPS (offline GeoNames place names)"),
crate::i18n::tr("The place names list towns of 15,000 people or more: in a smaller one, City gets the nearest larger town.")
))
.clicked()
&& let Err(e) = app.run("metadata.reverseGeocode", json!({}))
{
app.toast_error(ui.ctx(), e);
}
}
if let Some(a) = p.analysis {
let mut line = crate::i18n::tr_format!("Focus {:.0}", a.sharpness);
+20 -2
View File
@@ -454,10 +454,24 @@ fn matches_with(i: &egui::InputState, extra: &[egui::Event], m: Modifiers, k: Ke
/// 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). In
/// the Map view also: H hides / shows the pins (Remove elsewhere), O shows / hides the saved
/// locations list (the mask overlay elsewhere), `=` / `-` zoom the map (the grid's thumbnail size
/// elsewhere), and Cmd+= / Cmd+- / Cmd+0 zoom it in, out and fit it to the photos.
/// 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.lockMarkers",
(_, "panel.remove", (m, Key::H)) if map && m == Modifiers::NONE && !fullscreen => "map.showPins",
(_, "view.maskOverlay", (m, Key::O)) if map && m == Modifiers::NONE && !fullscreen => "map.showLocations",
(_, "view.thumbSizeUp", (m, Key::Equals)) if map && m == Modifiers::NONE && !fullscreen => "map.zoomIn",
(_, "view.thumbSizeDown", (m, Key::Minus)) if map && m == Modifiers::NONE && !fullscreen => "map.zoomOut",
(_, "view.zoomIn", (m, Key::Equals)) if map && m == Modifiers::COMMAND && !fullscreen => "map.zoomIn",
(_, "view.zoomOut", (m, Key::Minus)) if map && m == Modifiers::COMMAND && !fullscreen => "map.zoomOut",
(_, "view.zoomFit", (m, Key::Num0)) if map && m == Modifiers::COMMAND && !fullscreen => "map.fit",
(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",
@@ -580,7 +594,10 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) {
return;
}
let (mut fire, aliased, h_press) = pressed_commands(app, ctx, clips);
let in_map = app.ui.view == crate::state::ViewMode::Map && !app.ui.fullscreen;
for (id, params) in aliased {
// `+` sizes the grid's thumbnails; in the Map view it zooms the map, as `=` does there
let id = if in_map && id == "view.thumbSizeUp" { "map.zoomIn" } else { id };
fire_alias(app, ctx, id, params);
}
// while the Masking panel is open, an unmodified H that no assignment has claimed toggles the
@@ -588,6 +605,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) {
// preview shows no panels and a minimized window hides the panel, so there H keeps its own
// binding
if h_press
&& !in_map
&& app.ui.right == crate::state::RightPanel::Masking
&& !app.ui.fullscreen
&& crate::docking::exposed(app, crate::docking::Panel::Tools)
@@ -671,7 +689,7 @@ fn pressed_commands(
&& !native(sc)
&& !(k == Key::Escape && popup_open)
&& (matches_with(i, &window_edits, m, k) || (window_escape && k == Key::Escape && m == Modifiers::NONE))
&& 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
@@ -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();
+6
View File
@@ -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,
@@ -434,6 +436,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,
}
/// How many panel toggles [`UiState::toggle_return`] remembers (pressing I and K in turn would grow it without end).
@@ -703,6 +708,7 @@ impl Default for UiState {
status: String::new(),
dialog: None,
print: Default::default(),
map: MapUi::default(),
}
}
}
+115
View File
@@ -0,0 +1,115 @@
use serde::{Deserialize, Serialize};
/// 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 {
pub center_lat: f64,
pub center_lon: f64,
pub zoom: f64,
pub navigator_zoom: f64,
pub filter: lightcraft_engine::map::LocationFilter,
pub show_filter_bar: bool,
pub locked: bool,
pub active_pin_photo: Option<lightcraft_catalog::PhotoId>,
pub tracklog_path: Option<String>,
pub tracklog_visible: bool,
pub legend_open: bool,
pub navigator_open: bool,
/// The photo pins are shown (H in the Map view, `map.showPins`); hidden pins can't be clicked,
/// hovered or dragged, and saved locations and track logs stay.
pub show_pins: bool,
/// The view was set (fitted, moved, zoomed) this session: the first showing fits the photos
/// only while this is false. Not saved.
#[serde(skip)]
pub fitted: bool,
/// The map canvas last drawn (Fit to Photos sizes the view to it). Not saved.
#[serde(skip)]
pub last_canvas: Option<egui::Rect>,
/// A single photo's pin being dragged to a new place. Not saved.
#[serde(skip)]
pub pin_drag: Option<crate::panels::map::PinDrag>,
/// The photos of the pin whose right-click menu is open. Not saved.
#[serde(skip)]
pub menu_for: Vec<u64>,
/// The area Visible on Map narrows the photos to (the view's, once it rested). Not saved.
#[serde(skip)]
pub applied_area: Option<lightcraft_catalog::rules::GpsArea>,
/// The view's area last seen, and when it was first seen (to wait for the view to rest).
#[serde(skip)]
pub seen_area: Option<(lightcraft_catalog::rules::GpsArea, f64)>,
/// The saved location picked in the list (its handles are shown). Not saved.
#[serde(skip)]
pub active_location: Option<u64>,
/// The active location's handle being dragged. Not saved.
#[serde(skip)]
pub location_drag: Option<crate::panels::map::locations::LocationDrag>,
/// The location being renamed in the list, and the name typed so far. Not saved.
#[serde(skip)]
pub renaming: Option<(u64, String)>,
/// The location whose Delete… asks for confirmation. Not saved.
#[serde(skip)]
pub confirm_delete: Option<u64>,
/// Photos in a private location whose Info panel map was asked for (Show Map): the photo, the
/// location's id and its centre (bits), so another location, or another place under a reused id,
/// asks again. Cleared when another library is opened. Not saved.
#[serde(skip)]
pub private_shown: Vec<(u64, u64, u64, u64)>,
/// Private saved locations whose surroundings the Map view was asked to show (Show Map): the
/// location's id and its centre (bits), as for [`MapUi::private_shown`]. While the view's centre is
/// inside a private location not listed here, the Map view fetches no tiles. Cleared when another
/// library is opened. Not saved.
#[serde(skip)]
pub private_view_shown: Vec<(u64, u64, u64)>,
}
impl MapUi {
/// Another library was opened: forget what names its photos or saved locations (ids are per
/// library, so library B's location 3 must not inherit library A's Delete… confirmation), and
/// fit the map to the new photos. The view itself (centre, zoom, style, panels) stays.
pub fn library_changed(&mut self) {
self.active_pin_photo = None;
self.fitted = false;
self.pin_drag = None;
self.menu_for.clear();
self.active_location = None;
self.location_drag = None;
self.renaming = None;
self.confirm_delete = None;
self.private_shown.clear();
self.private_view_shown.clear();
}
}
impl Default for MapUi {
fn default() -> Self {
Self {
center_lat: 45.57,
center_lon: -73.2,
zoom: 12.0,
navigator_zoom: 3.0,
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,
show_pins: true,
fitted: false,
last_canvas: None,
pin_drag: None,
menu_for: Vec::new(),
applied_area: None,
seen_area: None,
active_location: None,
location_drag: None,
renaming: None,
confirm_delete: None,
private_shown: Vec::new(),
private_view_shown: Vec::new(),
}
}
}
+2
View File
@@ -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.
+8
View File
@@ -87,6 +87,14 @@ mod lifecycle_037;
mod lightroom_destination;
mod lights_out;
mod looping_albums;
mod map_esri;
mod map_filmstrip;
mod map_filter;
mod map_geotag;
mod map_info;
mod map_keys;
mod map_locations;
mod map_tracks;
mod mask_effects;
mod masking;
mod masking_layout;
+70
View File
@@ -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<egui::Rect> {
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<String> = 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<String> = 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());
}
+275
View File
@@ -0,0 +1,275 @@
//! 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<Rect> {
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<u64> {
let mut v: Vec<u64> = 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]);
}
/// A window too narrow for the navigator panel beside a usable map: the map takes the width and the
/// panel isn't drawn (the setting stays, so a wider window shows it again).
#[test]
fn a_narrow_map_view_leaves_the_navigator_out() {
for (size, shown) in [([640.0, 800.0], false), ([1300.0, 1000.0], true)] {
let mut h = map_sized(48.86, 2.33, 10.0, size);
assert!(h.app.ui.map.navigator_open, "the setting is on");
let c = canvas(&state(&mut h));
assert!(c.width() > 100.0, "{size:?}: the map keeps a usable width: {c:?}");
assert_eq!(widget(&h, "map:location:new").is_some(), shown, "{size:?}: navigator drawn");
}
}
+167
View File
@@ -0,0 +1,167 @@
//! The Map view's location filter (LRC-MAP-FILTER): Visible on Map, Tagged, Untagged, None, with
//! their counts; it narrows the filmstrip (through `Session::narrow`) over the library's own filter,
//! Visible on Map follows the view once it rests, pins come from the photos before it, and leaving
//! the Map view gives back exactly the grid's list. The map is never online in tests.
use serde_json::{Value, json};
use crate::headless::Headless;
use crate::{LightcraftApp, Services};
/// Paris ×3, London ×2, New York ×1 on the demo library's first six photos.
const PLACES: [(f64, f64); 6] =
[(48.8584, 2.2945), (48.8606, 2.3376), (48.8530, 2.3499), (51.5007, -0.1246), (51.5081, -0.0759), (40.7484, -73.9857)];
fn demo() -> (Headless, Vec<u64>) {
let mut h = Headless::new(
LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }),
[1300.0, 1000.0],
1.0,
);
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(6).map(|p| p.0).collect();
for (id, (lat, lon)) in ids.iter().zip(PLACES) {
h.app.run("photo.setGps", json!({"ids": [id], "lat": lat, "lon": lon})).unwrap();
}
h.app.run("view.map", json!({})).unwrap();
frames(&mut h, 4);
(h, ids)
}
fn frames(h: &mut Headless, n: usize) {
for _ in 0..n {
h.step();
}
}
fn filter(h: &mut Headless, mode: &str) -> Value {
let r = h.app.run("map.locationFilter", json!({"mode": mode})).unwrap();
frames(h, 3);
r
}
fn shown(h: &mut Headless) -> Vec<u64> {
let mut v: Vec<u64> = h.app.session.visible_cloned().iter().map(|p| p.0).collect();
v.sort_unstable();
v
}
fn sorted(mut v: Vec<u64>) -> Vec<u64> {
v.sort_unstable();
v
}
fn widget(h: &Headless, id: &str) -> Option<egui::Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
#[test]
fn tagged_untagged_and_none_narrow_the_filmstrip_and_count() {
let (mut h, ids) = demo();
let all = shown(&mut h);
let r = filter(&mut h, "tagged");
assert_eq!(
(r["tagged"].as_u64(), r["untagged"].as_u64(), r["all"].as_u64()),
(Some(6), Some(all.len() as u64 - 6), Some(all.len() as u64)),
"{r}"
);
assert_eq!(r["shown"], 6);
assert_eq!(shown(&mut h), sorted(ids.clone()), "the filmstrip holds the tagged photos");
// Untagged: the others, no pins, and a note saying they can be dragged on
filter(&mut h, "untagged");
let s = h.app.run("map.state", json!({})).unwrap();
assert!(s["pins"].as_array().unwrap().is_empty(), "{s}");
assert_eq!(shown(&mut h).len(), all.len() - 6);
assert!(ids.iter().all(|id| !shown(&mut h).contains(id)));
assert!(widget(&h, "map:untaggedNote").is_some());
// the bar shows each choice with its count
let bar = widget(&h, "map:filterBar").expect("the location filter bar");
for m in ["visible", "tagged", "untagged", "none"] {
assert!(widget(&h, &format!("map:filter:{m}")).is_some_and(|r| bar.contains(r.center())), "{m}");
}
// a click on Tagged in the bar
let at = widget(&h, "map:filter:tagged").unwrap().center();
for pressed in [true, false] {
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();
}
frames(&mut h, 3);
assert_eq!(h.app.run("map.state", json!({})).unwrap()["locationFilter"]["mode"], "tagged");
assert_eq!(shown(&mut h), sorted(ids.clone()));
filter(&mut h, "none");
assert_eq!(shown(&mut h), all);
assert!(h.app.run("map.locationFilter", json!({"mode": "somewhere"})).is_err());
}
/// The narrowing sits on the library's filter, is never saved as it, and leaving the Map view gives
/// back exactly the grid's list; coming back brings the choice back.
#[test]
fn it_sits_on_the_librarys_filter_and_leaving_the_map_restores_the_grid() {
let (mut h, ids) = demo();
// the library's own filter: rated three stars or more
let everything = shown(&mut h);
h.app.run("library.filter", json!({"rating": 3, "ratingOp": "atLeast"})).unwrap();
frames(&mut h, 2);
let grid = shown(&mut h);
assert!(grid.len() < everything.len() && !grid.is_empty(), "the library's filter narrows: {} of {}", grid.len(), everything.len());
let filter_before = h.app.session.filter.clone();
filter(&mut h, "tagged");
let narrowed = shown(&mut h);
assert!(narrowed.iter().all(|id| grid.contains(id) && ids.contains(id)), "{narrowed:?}");
assert_eq!(h.app.session.filter, filter_before, "the library's filter is untouched");
h.app.run("view.photoGrid", json!({})).unwrap();
frames(&mut h, 2);
assert!(h.app.session.narrow.is_none());
assert_eq!(shown(&mut h), grid, "the grid's list, exactly");
h.app.run("view.map", json!({})).unwrap();
frames(&mut h, 2);
assert_eq!(shown(&mut h), narrowed, "the choice is kept for the session");
}
/// Visible on Map: the photos inside the view; a command's view applies at once, a pan once the
/// view rests; the count follows the view at once.
#[test]
fn visible_on_map_follows_the_view() {
let (mut h, ids) = demo();
h.app.run("map.setView", json!({"lat": 48.857, "lon": 2.32, "zoom": 11})).unwrap();
frames(&mut h, 2);
let r = filter(&mut h, "visible");
assert_eq!(r["visible"], 3, "{r}");
assert_eq!(shown(&mut h), sorted(ids[..3].to_vec()), "Paris's three");
assert!(r["area"]["south"].as_f64().unwrap() < 48.85 && r["area"]["north"].as_f64().unwrap() > 48.86, "{r}");
// a command's view applies at once
h.app.run("map.setView", json!({"lat": 51.5, "lon": -0.1, "zoom": 10})).unwrap();
frames(&mut h, 2);
assert_eq!(shown(&mut h), sorted(ids[3..5].to_vec()), "London's two");
// a pan: the count at once, the filmstrip only once the view rests
h.app.ui.map.center_lat = 40.75;
h.app.ui.map.center_lon = -73.98;
h.step();
let s = h.app.run("map.state", json!({})).unwrap();
assert_eq!(s["locationFilter"]["visible"], 1, "{s}");
assert_eq!(shown(&mut h), sorted(ids[3..5].to_vec()), "not yet: the view hasn't rested");
// (headless time is the simulated clock: frames, not sleeps)
let rest = h.time() + 0.3;
while h.time() < rest {
h.step();
}
frames(&mut h, 2);
assert_eq!(shown(&mut h), vec![ids[5]], "New York's one once the view rested");
// the whole world at low zoom, and across the antimeridian
h.app.run("map.setView", json!({"lat": 0, "lon": 180, "zoom": 1})).unwrap();
frames(&mut h, 2);
assert_eq!(shown(&mut h).len(), 6, "every tagged photo");
}
/// An empty library: every count is 0, nothing breaks.
#[test]
fn an_empty_library_counts_nothing() {
let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()), [900.0, 700.0], 1.0);
h.app.run("view.map", json!({})).unwrap();
frames(&mut h, 2);
for m in ["visible", "tagged", "untagged", "none"] {
let r = filter(&mut h, m);
assert_eq!((r["visible"].as_u64(), r["all"].as_u64(), r["shown"].as_u64()), (Some(0), Some(0), Some(0)), "{m}: {r}");
}
}
+466
View File
@@ -0,0 +1,466 @@
//! The Map view's pins (LRC-MAP-GEOTAG and the map's Phase 2): moving a single photo's pin, a
//! cluster's drag panning, Lock Markers (toolbar, `map.lockMarkers`, saved with the window state),
//! Remove GPS Coordinates from a pin's menu and the Photo menu, world-anchored clusters that keep
//! their groups while panning and split when zooming in, the view commands (`map.fit`,
//! `map.setView`, `map.zoomIn`, `map.zoomOut`), "N photos without GPS" and the hover thumbnail.
//! The map is never online in tests.
use egui::{Pos2, Rect};
use lightcraft_catalog::PhotoId;
use lightcraft_engine::map::Viewport;
use lightcraft_geom::{LatLon, Point};
use serde_json::{Value, json};
use crate::headless::Headless;
use crate::{LightcraftApp, Services};
/// Paris ×3 (a few hundred metres apart), London ×2, New York ×1.
const PLACES: [(f64, f64); 6] =
[(48.8584, 2.2945), (48.8606, 2.3376), (48.8530, 2.3499), (51.5007, -0.1246), (51.5081, -0.0759), (40.7484, -73.9857)];
/// The demo library in the Map view at 1300 × 1000, the first six photos at [`PLACES`].
fn demo() -> (Headless, Vec<u64>) {
let mut h = Headless::new(
LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }),
[1300.0, 1000.0],
1.0,
);
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(6).map(|p| p.0).collect();
for (id, (lat, lon)) in ids.iter().zip(PLACES) {
h.app.run("photo.setGps", json!({"ids": [id], "lat": lat, "lon": lon})).unwrap();
}
h.app.run("view.map", json!({})).unwrap();
frames(&mut h, 4);
(h, ids)
}
/// The photos of the list, in order.
fn ids_all(h: &mut Headless) -> Vec<u64> {
h.app.session.visible_cloned().iter().map(|p| p.0).collect()
}
fn frames(h: &mut Headless, n: usize) {
for _ in 0..n {
h.step();
}
}
fn view(h: &mut Headless, lat: f64, lon: f64, zoom: f64) {
h.app.run("map.setView", json!({"lat": lat, "lon": lon, "zoom": zoom})).unwrap();
frames(h, 3);
}
fn state(h: &mut Headless) -> Value {
h.app.run("map.state", json!({})).unwrap()
}
fn widget(h: &Headless, id: &str) -> Option<Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
fn gps(h: &Headless, id: u64) -> Option<(f64, f64)> {
h.app.session.catalog.photo(PhotoId(id)).and_then(|p| p.meta.gps)
}
fn button(h: &mut Headless, at: Pos2, b: egui::PointerButton, pressed: bool) {
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: b, pressed, modifiers: egui::Modifiers::NONE });
h.step();
}
fn press(h: &mut Headless, at: Pos2, pressed: bool) {
button(h, at, egui::PointerButton::Primary, pressed);
}
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();
}
}
/// A full drag from `a` to `b`, released there.
fn drag(h: &mut Headless, a: Pos2, b: Pos2) {
press(h, a, true);
glide(h, a, b);
press(h, b, false);
frames(h, 3);
}
fn pins(s: &Value) -> Vec<Value> {
s["pins"].as_array().cloned().unwrap_or_default()
}
fn ids_of(p: &Value) -> Vec<u64> {
let mut v: Vec<u64> = p["ids"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
v.sort_unstable();
v
}
fn pin_of(s: &Value, id: u64) -> Value {
pins(s).into_iter().find(|p| ids_of(p).contains(&id)).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)
}
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")))
}
/// The position the map shows at screen point `at`.
fn place_at(s: &Value, at: Pos2) -> LatLon {
let c = canvas(s);
let f = |k: &str| s[k].as_f64().unwrap();
let vp = Viewport::new(LatLon { lat: f("lat"), lon: f("lon") }, f("zoom"), f64::from(c.width()), f64::from(c.height()));
vp.to_lat_lon(Point::new(f64::from(at.x - c.min.x), f64::from(at.y - c.min.y)))
}
fn close(a: (f64, f64), b: LatLon) -> bool {
(a.0 - b.lat).abs() < 1e-4 && (a.1 - b.lon).abs() < 1e-4
}
#[test]
fn a_single_pin_moves_in_one_undo_step_a_cluster_pans_and_locked_markers_stay() {
let (mut h, ids) = demo();
// Paris at street zoom: one pin per photo
view(&mut h, 48.857, 2.32, 14.0);
let s = state(&mut h);
let pin = pin_of(&s, ids[0]);
assert_eq!(pin["count"], 1, "{s}");
let from = xy(&pin);
let to = from + egui::vec2(90.0, 50.0);
let want = place_at(&s, to);
let (others, before_view) = ((gps(&h, ids[1]), gps(&h, ids[2])), (s["lat"].clone(), s["lon"].clone()));
let steps = h.app.session.undo.len();
press(&mut h, from, true);
glide(&mut h, from, to);
let s = state(&mut h);
assert_eq!(s["movingPin"]["id"], ids[0], "{s}");
assert_eq!((s["lat"].clone(), s["lon"].clone()), before_view, "moving a pin doesn't pan");
assert_eq!(gps(&h, ids[0]), Some(PLACES[0]), "nothing changes before the release");
press(&mut h, to, false);
frames(&mut h, 2);
let got = gps(&h, ids[0]).expect("still placed");
assert!(close(got, want), "{got:?} vs {want:?}");
assert_eq!((gps(&h, ids[1]), gps(&h, ids[2])), others, "only that photo moved");
assert_eq!(h.app.session.undo.len(), steps + 1, "one undo step");
assert_eq!(h.app.session.undo.last().map(|u| u.label.clone()).as_deref(), Some("Set GPS Coordinates"));
let s = state(&mut h);
assert!(s["movingPin"].is_null());
assert!(xy(&pin_of(&s, ids[0])).distance(to) < 2.0, "the pin is where it was let go");
h.app.run("edit.undo", json!({})).unwrap();
assert_eq!(gps(&h, ids[0]), Some(PLACES[0]));
// a pin let go outside the map (over the filmstrip) stays where it was
let s = state(&mut h);
let from = xy(&pin_of(&s, ids[1]));
drag(&mut h, from, egui::pos2(from.x, canvas(&s).bottom() + 40.0));
assert_eq!(gps(&h, ids[1]), Some(PLACES[1]));
// a cluster (Paris's three photos at zoom 6) pans the map instead
view(&mut h, 50.0, 1.0, 6.0);
let s = state(&mut h);
let paris = pins(&s).into_iter().find(|p| p["count"] == 3).unwrap_or_else(|| panic!("{s}"));
let before: Vec<_> = ids[0..3].iter().map(|i| gps(&h, *i)).collect();
drag(&mut h, xy(&paris), xy(&paris) + egui::vec2(150.0, 0.0));
assert_eq!(ids[0..3].iter().map(|i| gps(&h, *i)).collect::<Vec<_>>(), before, "a cluster's photos stay");
assert!(state(&mut h)["lon"].as_f64().unwrap() < 0.0, "the map panned west");
// Lock Markers: a single pin's drag pans too
let r = h.app.run("map.lockMarkers", json!({"on": true})).unwrap();
assert_eq!(r["on"], true);
assert_eq!(crate::menubar::checked(&h.app, "map.lockMarkers"), Some(true));
view(&mut h, 48.857, 2.32, 14.0);
let s = state(&mut h);
assert_eq!(s["lockMarkers"], true);
let from = xy(&pin_of(&s, ids[0]));
drag(&mut h, from, from + egui::vec2(90.0, 50.0));
assert_eq!(gps(&h, ids[0]), Some(PLACES[0]), "a locked pin stays");
assert!(state(&mut h)["lon"].as_f64().unwrap() < 2.32, "the drag panned");
// saved with the window state (ui.json)
assert_eq!(serde_json::to_value(&h.app.ui).unwrap()["map"]["locked"], true);
// the toolbar's Lock Markers toggles it back
let b = widget(&h, "map:lockMarkers").expect("the toolbar has Lock Markers").center();
// nothing covers it (the tile credit sits above the toolbar, not in it)
assert!(!widget(&h, "map:attribution").unwrap().intersects(widget(&h, "map:lockMarkers").unwrap()));
press(&mut h, b, true);
press(&mut h, b, false);
frames(&mut h, 2);
assert!(!h.app.ui.map.locked, "the button toggles it");
for bad in [json!({"on": "yes"}), json!({"on": 1})] {
assert!(h.app.run("map.lockMarkers", bad.clone()).is_err(), "{bad}");
}
assert!(!h.app.ui.map.locked);
}
#[test]
fn remove_gps_from_a_pins_menu_and_the_photo_menu_in_one_undo_step() {
let (mut h, ids) = demo();
view(&mut h, 40.7484, -73.9857, 10.0);
let ny = xy(&pin_of(&state(&mut h), ids[5]));
button(&mut h, ny, egui::PointerButton::Secondary, true);
button(&mut h, ny, egui::PointerButton::Secondary, false);
frames(&mut h, 3);
let item = widget(&h, "map:pinMenu:removeGps").expect("the pin's menu offers Remove GPS Coordinates").center();
press(&mut h, item, true);
press(&mut h, item, false);
frames(&mut h, 3);
assert_eq!(gps(&h, ids[5]), None);
assert_eq!(h.app.session.undo.last().map(|u| u.label.clone()).as_deref(), Some("Remove GPS Coordinates"));
h.app.run("edit.undo", json!({})).unwrap();
assert_eq!(gps(&h, ids[5]), Some(PLACES[5]));
// Photo ▸ Remove GPS Coordinates acts on the selection
let bar = crate::menubar::menu_bar(&h.app);
let photo = bar.iter().find(|(title, _)| title == "Photo").map(|(_, items)| format!("{items:?}")).unwrap_or_default();
assert!(photo.contains("photo.removeGps"), "in the Photo menu");
h.app.run("library.select", json!({"ids": [ids[3], ids[4]]})).unwrap();
h.app.run("photo.removeGps", json!({})).unwrap();
assert_eq!((gps(&h, ids[3]), gps(&h, ids[4])), (None, None));
// a right-click on the empty map opens no menu
frames(&mut h, 30);
let empty = canvas(&state(&mut h)).center() + egui::vec2(-300.0, 200.0);
button(&mut h, empty, egui::PointerButton::Secondary, true);
button(&mut h, empty, egui::PointerButton::Secondary, false);
frames(&mut h, 3);
assert!(widget(&h, "map:pinMenu:removeGps").is_none());
}
/// Clusters are world-anchored: panning moves them without regrouping; zooming in splits them.
#[test]
fn panning_keeps_the_groups_and_zooming_in_splits_them() {
let (mut h, _) = demo();
view(&mut h, 50.0, 1.0, 6.3);
let a = state(&mut h);
let groups = |s: &Value| {
let mut g: Vec<Vec<u64>> = pins(s).iter().map(ids_of).collect();
g.sort();
g
};
let c = canvas(&a).center();
drag(&mut h, c, c + egui::vec2(37.0, -21.0));
let b = state(&mut h);
assert_eq!(groups(&a), groups(&b), "panning never regroups the pins");
// every pin moved by the same amount, the way the drag went
let shifts: Vec<egui::Vec2> = pins(&a).iter().map(|p| xy(&pins(&b).into_iter().find(|q| ids_of(q) == ids_of(p)).unwrap()) - xy(p)).collect();
let first = shifts[0];
assert!(first.x > 10.0 && first.y < -5.0, "{first:?}");
assert!(shifts.iter().all(|d| (*d - first).length() < 1.0), "{shifts:?}");
// zooming in only splits: no fewer groups for the Paris photos at each whole zoom
let mut last = 0;
for z in [3.0, 6.0, 9.0, 12.0, 14.0] {
view(&mut h, 48.857, 2.32, z);
let n =
pins(&state(&mut h)).iter().filter(|p| ids_of(p).iter().any(|i| h.app.session.visible_cloned()[..3].iter().any(|v| v.0 == *i))).count();
assert!(n >= last, "zoom {z}: {n} < {last}");
last = n;
}
assert_eq!(last, 3, "street level: one pin per Paris photo");
let s = state(&mut h);
assert!(s["clusterMs"].as_f64().is_some_and(|ms| ms >= 0.0), "{s}");
}
#[test]
fn view_commands_fit_set_and_zoom_and_refuse_hostile_values() {
let (mut h, _) = demo();
view(&mut h, 0.0, 100.0, 9.0);
assert!(pins(&state(&mut h)).is_empty(), "nothing in the Indian Ocean");
h.app.run("map.fit", json!({})).unwrap();
frames(&mut h, 3);
let s = state(&mut h);
let c = canvas(&s);
let all: Vec<u64> = pins(&s).iter().flat_map(ids_of).collect();
assert_eq!(all.len(), 6, "Fit to Photos shows every photo with a position: {s}");
// inside the map, clear of the filter bar at the top and the toolbar at the bottom
let free = Rect::from_min_max(egui::pos2(c.left(), c.top() + 50.0), egui::pos2(c.right(), c.bottom() - 36.0));
assert!(pins(&s).iter().all(|p| free.contains(xy(p))), "{s}");
let z = s["zoom"].as_f64().unwrap();
h.app.run("map.zoomIn", json!({})).unwrap();
assert_eq!(state(&mut h)["zoom"].as_f64(), Some(z.round() + 1.0));
h.app.run("map.zoomOut", json!({})).unwrap();
h.app.run("map.zoomOut", json!({})).unwrap();
assert_eq!(state(&mut h)["zoom"].as_f64(), Some(z.round() - 1.0));
for _ in 0..30 {
h.app.run("map.zoomOut", json!({})).unwrap();
}
assert_eq!(state(&mut h)["zoom"].as_f64(), Some(1.0), "never below zoom 1");
// the longitude wraps, the latitude stays on the map
h.app.run("map.setView", json!({"lat": 89.0, "lon": 190.0, "zoom": 4})).unwrap();
let s = state(&mut h);
assert!((s["lon"].as_f64().unwrap() + 170.0).abs() < 1e-9 && s["lat"].as_f64().unwrap() <= 85.06, "{s}");
for bad in [json!({"lat": 91}), json!({"lat": "north"}), json!({"zoom": 99}), json!({"zoom": -1}), json!({"lon": [1]})] {
assert!(h.app.run("map.setView", bad.clone()).is_err(), "{bad}");
}
assert_eq!(state(&mut h)["zoom"].as_f64(), Some(4.0), "a refusal changes nothing");
// photos spread north to south: Fit keeps them clear of the filter bar and the toolbar
let all = ids_all(&mut h);
let (north, south) = (all[0], all[1]);
h.app.run("photo.removeGps", json!({"ids": all[2..6].to_vec()})).unwrap();
h.app.run("photo.setGps", json!({"ids": [north], "lat": 60.0, "lon": 10.0})).unwrap();
h.app.run("photo.setGps", json!({"ids": [south], "lat": 40.0, "lon": 10.0})).unwrap();
h.app.run("map.fit", json!({})).unwrap();
frames(&mut h, 3);
let s = state(&mut h);
let c = canvas(&s);
let free = Rect::from_min_max(egui::pos2(c.left(), c.top() + 50.0), egui::pos2(c.right(), c.bottom() - 36.0));
assert_eq!(pins(&s).len(), 2, "{s}");
for p in pins(&s) {
// the pin's head is drawn up to 20 points above its point
assert!(free.contains(xy(&p)) && free.contains(xy(&p) - egui::vec2(0.0, 20.0)), "{p} not in {free:?}");
}
for (id, (lat, lon)) in all[..6].iter().zip(PLACES) {
h.app.run("photo.setGps", json!({"ids": [id], "lat": lat, "lon": lon})).unwrap();
}
// the toolbar's Fit to Photos does the same as map.fit
let fit = widget(&h, "map:fit").expect("Fit to Photos").center();
press(&mut h, fit, true);
press(&mut h, fit, false);
frames(&mut h, 3);
assert_eq!(pins(&state(&mut h)).iter().flat_map(ids_of).count(), 6);
}
#[test]
fn the_first_showing_fits_the_photos_and_counts_those_without_gps() {
let (mut h, ids) = demo();
let s = state(&mut h);
let all: Vec<u64> = pins(&s).iter().flat_map(ids_of).collect();
assert_eq!(all.len(), ids.len(), "the first showing fits every photo with a position: {s}");
let total = h.app.session.visible_cloned().len();
assert_eq!((s["withGps"].as_u64(), s["withoutGps"].as_u64()), (Some(6), Some(total as u64 - 6)), "{s}");
assert!(widget(&h, "map:withoutGps").is_some(), "the note is on the map");
// hovering a pin shows its photo's thumbnail
let p = xy(&pins(&s)[0]);
h.app.synthetic.push(egui::Event::PointerMoved(p));
frames(&mut h, 3);
assert!(widget(&h, "map:hoverThumb").is_some(), "a thumbnail over the hovered pin");
assert!(state(&mut h)["hovered"].is_array());
// an empty library: no pins, no note, nothing breaks
let mut e = Headless::new(LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()), [900.0, 700.0], 1.0);
e.app.run("view.map", json!({})).unwrap();
frames(&mut e, 3);
let s = state(&mut e);
assert_eq!((s["withGps"].as_u64(), s["withoutGps"].as_u64(), pins(&s).len()), (Some(0), Some(0), 0));
assert!(widget(&e, "map:withoutGps").is_none());
e.app.run("map.fit", json!({})).unwrap();
}
/// With the Untagged filter no pin is drawn, so none can be dragged: a drag where a pin was pans
/// the map and moves no photo (hit testing used to ignore the filter).
#[test]
fn a_pin_hidden_by_the_untagged_filter_cant_be_dragged() {
let (mut h, ids) = demo();
view(&mut h, 48.857, 2.32, 14.0);
let s = state(&mut h);
let from = xy(&pin_of(&s, ids[0]));
h.app.run("map.locationFilter", json!({"mode": "untagged"})).unwrap();
frames(&mut h, 2);
let s = state(&mut h);
assert!(pins(&s).is_empty(), "{s}");
let before_view = (s["lat"].clone(), s["lon"].clone());
drag(&mut h, from, from + egui::vec2(90.0, 50.0));
let s = state(&mut h);
assert_eq!(gps(&h, ids[0]), Some(PLACES[0]), "the photo didn't move");
assert_ne!((s["lat"].clone(), s["lon"].clone()), before_view, "the drag panned");
}
/// Show in Map on a photo without GPS must not leave the previous photo's pin active.
#[test]
fn show_in_map_on_a_photo_without_gps_clears_the_active_pin() {
let (mut h, ids) = demo();
h.app.run("photo.showInMap", json!({"id": ids[0]})).unwrap();
assert_eq!(h.app.ui.map.active_pin_photo, Some(PhotoId(ids[0])));
h.app.run("photo.removeGps", json!({"ids": [ids[1]]})).unwrap();
h.app.run("photo.showInMap", json!({"id": ids[1]})).unwrap();
assert_eq!(h.app.ui.map.active_pin_photo, None, "no pin to show for a photo without GPS");
}
/// A click on a toolbar button over a pin is the button's: the pin beneath isn't selected.
#[test]
fn a_click_on_a_button_over_a_pin_does_not_select_the_pin() {
let (mut h, ids) = demo();
view(&mut h, 40.7484, -73.9857, 10.0);
let lock = widget(&h, "map:lockMarkers").expect("the toolbar's Lock Markers button").center();
// pan so New York's pin sits under the button: the view's centre moves by the pin's offset
let s = state(&mut h);
let ny = xy(&pin_of(&s, ids[5]));
let centre = canvas(&s).center() + (ny - lock);
let to = place_at(&s, centre);
view(&mut h, to.lat, to.lon, 10.0);
let s = state(&mut h);
assert!((xy(&pin_of(&s, ids[5])) - lock).length() < 2.0, "the pin is under the button: {s}");
h.app.run("library.select", json!({"ids": [ids[0]]})).unwrap();
let locked = s["lockMarkers"].as_bool();
press(&mut h, lock, true);
press(&mut h, lock, false);
frames(&mut h, 2);
assert_ne!(state(&mut h)["lockMarkers"].as_bool(), locked, "the button took the click");
assert_eq!(h.app.session.selection.ids, vec![PhotoId(ids[0])], "the pin beneath wasn't selected");
}
/// Pins work by keyboard: a focused pin shows its preview, Return selects its photos (as a click
/// does), and an arrow key moves the focus to another pin.
#[test]
fn pins_work_by_keyboard() {
let (mut h, ids) = demo();
view(&mut h, 45.0, -36.0, 3.0);
let s = state(&mut h);
// (a pin's focus id is its first photo in its own order; only pins on the canvas take focus)
let c = &s["canvas"];
let (x0, y0) = (c["x"].as_f64().unwrap(), c["y"].as_f64().unwrap());
let (x1, y1) = (x0 + c["width"].as_f64().unwrap(), y0 + c["height"].as_f64().unwrap());
let first: Vec<u64> = pins(&s)
.iter()
.filter(|p| (x0..x1).contains(&p["x"].as_f64().unwrap()) && (y0..y1).contains(&p["y"].as_f64().unwrap()))
.filter_map(|p| p["ids"][0].as_u64())
.collect();
assert!(first.len() >= 2, "{s}");
h.app.run("library.select", json!({"ids": []})).unwrap();
h.view.ctx.memory_mut(|m| m.request_focus(crate::panels::map::pin_focus_id(first[0])));
frames(&mut h, 3);
assert!(widget(&h, "map:hoverThumb").is_some(), "the focused pin shows its preview");
let key = |h: &mut Headless, k: &str| {
let r = h.request("ui.key", json!({"key": k}), std::time::Duration::from_secs(20));
assert_eq!(r["ok"], true, "{k}: {r}");
frames(h, 3);
};
key(&mut h, "Enter");
let pin = pin_of(&state(&mut h), first[0]);
let mut selected: Vec<u64> = h.app.session.selection.ids.iter().map(|p| p.0).collect();
selected.sort_unstable();
assert_eq!(selected, ids_of(&pin), "Return selects the pin's photos");
// a map shortcut still works with a pin focused
let zoom = state(&mut h)["zoom"].as_f64().unwrap();
key(&mut h, "Minus");
assert!(state(&mut h)["zoom"].as_f64().unwrap() < zoom, "- zooms out with a pin focused");
view(&mut h, 45.0, -36.0, 3.0);
// a screen reader's Click on a pin selects it
h.app.run("library.select", json!({"ids": []})).unwrap();
h.view.owed.push(egui::Event::AccessKitActionRequest(egui::accesskit::ActionRequest {
action: egui::accesskit::Action::Click,
target_tree: egui::accesskit::TreeId::ROOT,
target_node: crate::panels::map::pin_focus_id(first[1]).accesskit_id(),
data: None,
}));
frames(&mut h, 3);
let pin = pin_of(&state(&mut h), first[1]);
let mut selected: Vec<u64> = h.app.session.selection.ids.iter().map(|p| p.0).collect();
selected.sort_unstable();
assert_eq!(selected, ids_of(&pin), "AccessKit Click selects the pin's photos");
h.view.ctx.memory_mut(|m| m.request_focus(crate::panels::map::pin_focus_id(first[0])));
frames(&mut h, 3);
// an arrow key: the focus goes to another pin
for k in ["ArrowRight", "ArrowLeft", "ArrowDown", "ArrowUp"] {
key(&mut h, k);
let now = h.view.ctx.memory(|m| m.focused());
if now != Some(crate::panels::map::pin_focus_id(first[0])) {
assert!(first.iter().any(|f| Some(crate::panels::map::pin_focus_id(*f)) == now), "{k}: focus on another pin, not elsewhere");
let _ = ids;
return;
}
}
panic!("no arrow key moved the focus off the first pin");
}
+187
View File
@@ -0,0 +1,187 @@
//! The Info panel's map of the active photo's place (LR-MAP-INFO): its pin and credit, the active
//! photo only with several selected, none without a position, a click opening the Map view there
//! from the same tiles (nothing fetched twice), no fetching once it is off screen, offline, a place
//! near the pole, and the photo changing. Tiles come from an in-process fake server, never the
//! network.
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use crate::headless::Headless;
use crate::{LightcraftApp, Services};
/// Serves one flat 256 px PNG for every tile and records the URLs asked for.
struct FakeTiles {
urls: Mutex<Vec<String>>,
png: Vec<u8>,
}
impl lightcraft_engine::map::Transport for FakeTiles {
fn get(
&self,
url: &str,
_headers: &[(&'static str, String)],
_max: usize,
_cancel: &std::sync::atomic::AtomicBool,
) -> Result<lightcraft_engine::map::HttpResponse, lightcraft_engine::map::TransportError> {
self.urls.lock().unwrap().push(url.to_string());
Ok(lightcraft_engine::map::HttpResponse { status: 200, headers: vec![], body: self.png.clone() })
}
}
fn fake() -> Arc<FakeTiles> {
use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png};
let data: Vec<u8> = (0..256 * 256).flat_map(|_| [40u8, 160, 90, 255]).collect();
let png = encode_png(&EncodeImage::new(256, 256, 4, Samples::U8(&data)), &EncodeMeta::default()).unwrap();
Arc::new(FakeTiles { urls: Mutex::new(Vec::new()), png })
}
/// The demo library (in a window tall enough to show the Info panel down to its map) with its first photos in Paris, London and near the North Pole, the third
/// without a position, the Info panel open on the first, tiles from `tiles` (a source of its own,
/// so tests don't share textures).
fn demo(id: &str, tiles: Arc<FakeTiles>) -> (Headless, Vec<u64>) {
use lightcraft_engine::map::{TileService, TileSource};
let mut session = lightcraft_engine::Session::with_demo();
let template = format!("https://{id}.tiles.test/{{z}}/{{x}}/{{y}}.png");
session.execute("map.tileSource", &json!({"id": id, "urlTemplate": template, "attribution": "© Test tiles", "maxZoom": 19})).unwrap();
let source = TileSource::custom(Some(id), &template, Some("© Test tiles"), Some(19)).unwrap();
session.map.set_service(TileService::with_transport(source, None, Some(tiles)).with_activity(Some(session.activity.clone())));
let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1400.0, 1800.0], 1.0);
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(4).map(|p| p.0).collect();
for (id, (lat, lon)) in [(ids[0], (48.8584, 2.2945)), (ids[1], (51.5007, -0.1246)), (ids[3], (89.5, 10.0))] {
h.app.run("photo.setGps", json!({"ids": [id], "lat": lat, "lon": lon})).unwrap();
}
h.app.run("library.select", json!({"ids": [ids[0]]})).unwrap();
h.app.run("panel.info", json!({})).unwrap();
frames(&mut h, 4);
(h, ids)
}
fn frames(h: &mut Headless, n: usize) {
for _ in 0..n {
h.step();
}
}
fn mini(h: &mut Headless) -> Value {
h.app.run("map.state", json!({})).unwrap()["miniMap"].clone()
}
fn widget(h: &Headless, id: &str) -> Option<egui::Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
/// Draw frames until the tile service has nothing left to do.
fn settle_tiles(h: &mut Headless) {
let end = std::time::Instant::now() + std::time::Duration::from_secs(20);
loop {
frames(h, 2);
if h.app.session.map.service().is_some_and(|s| s.is_idle()) && mini(h)["tiles"]["missing"] == 0 {
return;
}
assert!(std::time::Instant::now() < end, "the tiles never arrived: {}", mini(h));
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test]
fn the_info_panel_shows_the_active_photos_place_with_its_pin_and_credit() {
let (mut h, ids) = demo("info-pin", fake());
let m = mini(&mut h);
assert_eq!(m["photo"], ids[0], "{m}");
assert!((m["lat"].as_f64().unwrap() - 48.8584).abs() < 1e-6 && (m["lon"].as_f64().unwrap() - 2.2945).abs() < 1e-6, "{m}");
assert_eq!(m["zoom"], 14.0);
let rect = widget(&h, "info:miniMap").expect("the map is in the Info panel");
let pin = egui::pos2(m["pin"]["x"].as_f64().unwrap() as f32, m["pin"]["y"].as_f64().unwrap() as f32);
assert!(pin.distance(rect.center()) < 1.0, "the photo's place is the map's centre: {pin:?} {rect:?}");
assert!(widget(&h, "info:miniMapAttribution").is_some_and(|c| rect.contains(c.center())), "the credit is on the map");
assert!(widget(&h, "button:showOnMap").is_some(), "Open in Browser keeps its widget id");
settle_tiles(&mut h);
assert!(mini(&mut h)["tiles"]["drawn"].as_u64().unwrap() > 0);
// several selected: the active photo's place
h.app.run("library.select", json!({"ids": [ids[0], ids[1]], "active": ids[1]})).unwrap();
frames(&mut h, 3);
assert_eq!(mini(&mut h)["photo"], ids[1]);
// a photo without a position has no map
h.app.run("library.select", json!({"ids": [ids[2]]})).unwrap();
frames(&mut h, 3);
assert!(mini(&mut h).is_null() && widget(&h, "info:miniMap").is_none());
// near the pole the map stops short of the place: the pin stays on the map
h.app.run("library.select", json!({"ids": [ids[3]]})).unwrap();
frames(&mut h, 3);
let m = mini(&mut h);
let rect = widget(&h, "info:miniMap").expect("a map for the polar photo");
let pin = egui::pos2(m["pin"]["x"].as_f64().unwrap() as f32, m["pin"]["y"].as_f64().unwrap() as f32);
assert!(rect.shrink(7.0).contains(pin), "{pin:?} in {rect:?}");
}
/// A click opens the Map view on the place, from the tiles the small map already loaded: no tile
/// is asked for twice.
#[test]
fn a_click_opens_the_map_view_there_from_the_same_tiles() {
let tiles = fake();
let (mut h, ids) = demo("info-click", tiles.clone());
settle_tiles(&mut h);
let at = widget(&h, "info:miniMap").unwrap().center();
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
for pressed in [true, false] {
h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
h.step();
}
frames(&mut h, 3);
assert_eq!(h.app.ui.view, crate::state::ViewMode::Map);
let s = h.app.run("map.state", json!({})).unwrap();
assert!((s["lat"].as_f64().unwrap() - 48.8584).abs() < 1e-6 && (s["lon"].as_f64().unwrap() - 2.2945).abs() < 1e-6, "{s}");
assert_eq!(s["zoom"], 14.0);
assert!(s["pins"].as_array().unwrap().iter().any(|p| p["ids"].as_array().unwrap().contains(&json!(ids[0]))), "{s}");
let end = std::time::Instant::now() + std::time::Duration::from_secs(20);
while !h.app.session.map.service().is_some_and(|s| s.is_idle()) {
assert!(std::time::Instant::now() < end);
frames(&mut h, 2);
}
let urls = tiles.urls.lock().unwrap().clone();
let mut unique = urls.clone();
unique.sort();
unique.dedup();
assert_eq!(unique.len(), urls.len(), "a tile the small map loaded isn't fetched again: {urls:?}");
}
/// Off screen (the Info panel closed, or the map below its fold) the small map asks for nothing, so
/// nothing is fetched for it.
#[test]
fn nothing_is_fetched_for_it_once_it_is_off_screen_and_offline_it_stays_grey() {
let tiles = fake();
let (mut h, _) = demo("info-off", tiles.clone());
settle_tiles(&mut h);
assert!(h.app.session.map.service().unwrap().stats().wanted > 0);
h.app.run("panel.edit", json!({})).unwrap();
frames(&mut h, 4);
assert!(mini(&mut h).is_null());
assert_eq!(h.app.session.map.service().unwrap().stats().wanted, 0, "no map on screen: nothing wanted");
// in a shorter window the map is below the panel's fold: not drawn, nothing wanted
h.app.run("panel.info", json!({})).unwrap();
h.request("ui.resize", json!({"width": 1400, "height": 900}), std::time::Duration::from_secs(20));
frames(&mut h, 4);
assert!(mini(&mut h).is_null(), "scrolled out of view");
assert_eq!(h.app.session.map.service().unwrap().stats().wanted, 0);
h.request("ui.resize", json!({"width": 1400, "height": 1800}), std::time::Duration::from_secs(20));
// offline: the grey map, the pin, and no service at all
h.app.run("map.tileSource", json!({"offline": true})).unwrap();
frames(&mut h, 3);
let m = mini(&mut h);
assert_eq!(m["tiles"]["offline"], true, "{m}");
assert!(m["pin"]["x"].is_number());
assert!(h.app.session.map.service().is_none());
}
#[test]
fn the_pin_stays_inside_maps_of_any_size() {
let r = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(4.0, 3.0));
for p in [egui::pos2(-1e9, 1e9), egui::pos2(f32::NAN, 0.0), egui::pos2(f32::INFINITY, 5.0), egui::pos2(12.0, 11.0)] {
let q = crate::panels::map::keep_on_map(p, r);
assert!(r.contains(q), "{p:?} → {q:?}");
}
}
+222
View File
@@ -0,0 +1,222 @@
//! The Map view's keys, menus and settings (map phase 8): H hides the pins, O the saved locations
//! list, `=` / `-` and Cmd+= / Cmd+- / Cmd+0 zoom and fit the map, `\` and Cmd+K as before — in the
//! Map view only (outside it the keys keep Remove, the mask overlay, the grid's thumbnail size and
//! Add Keywords); hidden pins can't be clicked; Window ▸ Map gathers the map's commands (greyed
//! elsewhere); Settings ▸ Map picks the tile source (a custom server only on Apply or Return; a
//! refused one changes nothing) and clears the cache. The map is never online in tests.
use std::time::Duration;
use serde_json::{Value, json};
use crate::headless::Headless;
use crate::{LightcraftApp, Services};
const T: Duration = Duration::from_secs(20);
fn demo() -> (Headless, Vec<u64>) {
let mut h = Headless::new(
LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }),
[1300.0, 1000.0],
1.0,
);
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect();
for (id, (lat, lon)) in ids.iter().zip([(48.8584, 2.2945), (51.5007, -0.1246), (40.7484, -73.9857)]) {
h.app.run("photo.setGps", json!({"ids": [id], "lat": lat, "lon": lon})).unwrap();
}
h.app.run("view.map", json!({})).unwrap();
h.app.run("map.setView", json!({"lat": 48.8584, "lon": 2.2945, "zoom": 10})).unwrap();
frames(&mut h, 3);
(h, ids)
}
fn frames(h: &mut Headless, n: usize) {
for _ in 0..n {
h.step();
}
}
fn key(h: &mut Headless, k: &str, cmd: bool) {
let r = h.request("ui.key", json!({"key": k, "cmd": cmd}), T);
assert_eq!(r["ok"], true, "{k}: {r}");
frames(h, 2);
}
fn state(h: &mut Headless) -> Value {
h.app.run("map.state", json!({})).unwrap()
}
fn widget(h: &Headless, id: &str) -> Option<egui::Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
fn click_at(h: &mut Headless, at: egui::Pos2) {
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
for pressed in [true, false] {
h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
h.step();
}
frames(h, 2);
}
fn zoom(h: &mut Headless) -> f64 {
state(h)["zoom"].as_f64().unwrap()
}
#[test]
fn the_map_keys_work_in_the_map_view_only() {
let (mut h, ids) = demo();
// H hides the pins, and hidden pins can't be clicked
let pin = state(&mut h)["pins"].as_array().unwrap().iter().find(|p| p["ids"].as_array().unwrap().contains(&json!(ids[0]))).cloned().unwrap();
let at = egui::pos2(pin["x"].as_f64().unwrap() as f32, pin["y"].as_f64().unwrap() as f32);
key(&mut h, "H", false);
let s = state(&mut h);
assert_eq!((s["showPins"].as_bool(), s["pins"].as_array().map(Vec::len)), (Some(false), Some(0)), "{s}");
h.app.run("library.select", json!({"ids": [ids[2]]})).unwrap();
click_at(&mut h, at);
assert_eq!(h.app.session.selection.ids.iter().map(|p| p.0).collect::<Vec<_>>(), vec![ids[2]], "a hidden pin isn't clicked");
assert_eq!(serde_json::to_value(&h.app.ui).unwrap()["map"]["showPins"], false, "saved with the window state");
key(&mut h, "H", false);
assert_eq!(state(&mut h)["showPins"], true);
assert_ne!(h.app.ui.right, crate::state::RightPanel::Remove, "H doesn't open Remove in the Map view");
// O shows / hides the saved locations list (the navigator panel)
let (open, overlay) = (h.app.ui.map.navigator_open, h.app.ui.mask_overlay);
key(&mut h, "O", false);
assert_eq!(h.app.ui.map.navigator_open, !open);
assert_eq!(h.app.ui.mask_overlay, overlay, "O doesn't touch the mask overlay in the Map view");
key(&mut h, "O", false);
// = / - and Cmd+= / Cmd+- zoom; Cmd+0 fits
let thumbs = h.app.ui.thumb_size;
let z = zoom(&mut h);
key(&mut h, "=", false);
assert_eq!(zoom(&mut h), z + 1.0);
key(&mut h, "-", false);
key(&mut h, "-", false);
assert_eq!(zoom(&mut h), z - 1.0);
key(&mut h, "=", true);
assert_eq!(zoom(&mut h), z);
assert_eq!(h.app.ui.thumb_size, thumbs, "the grid's thumbnail size didn't change");
key(&mut h, "0", true);
assert!(zoom(&mut h) < z, "Cmd+0 fits every photo with a position (Paris, London, New York)");
// \ and Cmd+K as before
let bar = h.app.ui.map.show_filter_bar;
key(&mut h, "\\", false);
assert_eq!(h.app.ui.map.show_filter_bar, !bar);
key(&mut h, "K", true);
assert!(h.app.ui.map.locked);
// outside the Map view the keys keep their meaning
h.app.run("view.photoGrid", json!({})).unwrap();
frames(&mut h, 2);
let pins = h.app.ui.map.show_pins;
let thumbs = h.app.ui.thumb_size;
key(&mut h, "=", false);
assert!(h.app.ui.thumb_size > thumbs, "= sizes the grid's thumbnails");
key(&mut h, "H", false);
assert_eq!(h.app.ui.map.show_pins, pins, "H leaves the pins alone");
assert_eq!(h.app.ui.right, crate::state::RightPanel::Remove, "H opens Remove (in Detail, as ever)");
}
#[test]
fn window_map_gathers_the_map_commands_greyed_outside_the_map_view() {
let (mut h, _) = demo();
let find = |h: &Headless| -> Vec<(String, bool, Option<bool>)> {
let bar = crate::menubar::menu_bar(&h.app);
let view = bar.iter().find(|(t, _)| t == "Window").map(|(_, i)| i.clone()).unwrap();
let map = view
.iter()
.find_map(|n| match n {
crate::menubar::MenuNode::Submenu { label, children } if label == "Map" => Some(children.clone()),
_ => None,
})
.expect("Window ▸ Map");
map.iter()
.filter_map(|n| match n {
crate::menubar::MenuNode::Item { id, enabled, checked, .. } => Some((id.clone(), *enabled, *checked)),
_ => None,
})
.collect()
};
let items = find(&h);
for id in ["map.fit", "map.zoomIn", "map.zoomOut", "map.showPins", "map.lockMarkers", "map.filterBar", "map.settings"] {
assert!(items.iter().any(|(i, e, _)| i == id && *e), "{id} enabled in the Map view: {items:?}");
}
assert_eq!(items.iter().find(|(i, ..)| i == "map.showPins").map(|(_, _, c)| *c), Some(Some(true)));
// run from the menu, as the keys do
h.app.run("map.showPins", json!({})).unwrap();
assert_eq!(find(&h).iter().find(|(i, ..)| i == "map.showPins").map(|(_, _, c)| *c), Some(Some(false)));
h.app.run("map.settings", json!({})).unwrap();
assert!(matches!(&h.app.ui.dialog, Some(crate::state::Dialog::Settings { tab }) if tab == "map"));
h.app.ui.dialog = None;
// greyed outside the Map view (but Map Tiles… and Load Tracklog… stay)
h.app.run("view.photoGrid", json!({})).unwrap();
let items = find(&h);
assert!(items.iter().any(|(i, e, _)| i == "map.fit" && !*e));
assert!(items.iter().any(|(i, e, _)| i == "map.settings" && *e));
assert!(h.app.run("map.showPins", json!({"on": "yes"})).is_err());
}
#[test]
fn settings_map_picks_the_source_applies_a_custom_server_only_on_confirm_and_clears_the_cache() {
let (mut h, _) = demo();
h.app.run("app.settings", json!({"tab": "map"})).unwrap();
frames(&mut h, 3);
// a built-in source by its radio
let r = h.request("ui.clickWidget", json!({"id": "settings:mapSource:opentopomap"}), T);
assert_eq!(r["ok"], true, "{r}");
frames(&mut h, 2);
assert_eq!(h.app.session.map.source().id(), "opentopomap");
assert!(widget(&h, "settings:mapSource:esri-streets").is_none(), "no Esri styles without a key");
// a custom server: typing changes nothing; Return with a bad template shows why and changes nothing
h.request("ui.clickWidget", json!({"id": "field:mapTemplate"}), T);
frames(&mut h, 1);
h.request("ui.text", json!({"text": "http://tiles.example.org/{z}/{x}/{y}.png"}), T);
frames(&mut h, 2);
assert_eq!(h.app.session.map.source().id(), "opentopomap", "not while typing");
h.request("ui.key", json!({"key": "Enter"}), T);
frames(&mut h, 2);
assert!(widget(&h, "settings:mapError").is_some(), "the refusal is shown");
assert_eq!(h.app.session.map.source().id(), "opentopomap", "a refused server changes nothing");
// a good one, with its credit, on Apply
h.request("ui.clickWidget", json!({"id": "field:mapTemplate"}), T);
frames(&mut h, 1);
h.request("ui.key", json!({"key": "A", "cmd": true}), T);
h.request("ui.text", json!({"text": "https://tiles.example.org/{z}/{x}/{y}.png"}), T);
frames(&mut h, 1);
h.request("ui.clickWidget", json!({"id": "field:mapAttribution"}), T);
frames(&mut h, 1);
h.request("ui.text", json!({"text": "© Example"}), T);
frames(&mut h, 1);
h.request("ui.clickWidget", json!({"id": "button:mapCustomApply"}), T);
frames(&mut h, 2);
let s = h.app.session.execute("map.tileSource", &json!({})).unwrap();
assert_eq!((s["custom"].as_bool(), s["attribution"].as_str()), (Some(true), Some("© Example")), "{s}");
assert!(widget(&h, "settings:mapError").is_none());
// the cache: its size, and Delete Cached Tiles when it holds tiles
assert!(widget(&h, "settings:mapCacheSize").is_some());
// the Esri styles appear once a key is set
h.app.session.execute("map.setEsriKey", &json!({"key": "AAPK0123456789abcdef_TEST-key.x"})).unwrap();
frames(&mut h, 2);
assert!(widget(&h, "settings:mapSource:esri-streets").is_some());
}
/// Show in Map on the map's first showing centres on the photo: the fit to every photo that a
/// first showing does doesn't replace it.
#[test]
fn show_in_map_on_the_first_visit_keeps_the_photos_place() {
let mut h = Headless::new(
LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }),
[1300.0, 1000.0],
1.0,
);
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(2).map(|p| p.0).collect();
h.app.run("photo.setGps", json!({"ids": [ids[0]], "lat": 48.8584, "lon": 2.2945})).unwrap();
h.app.run("photo.setGps", json!({"ids": [ids[1]], "lat": 40.7484, "lon": -73.9857})).unwrap();
assert!(!h.app.ui.map.fitted, "the map wasn't shown yet");
h.app.run("photo.showInMap", json!({"id": ids[0]})).unwrap();
frames(&mut h, 3);
let s = state(&mut h);
assert_eq!(s["zoom"].as_f64(), Some(15.0), "{s}");
assert!((s["lat"].as_f64().unwrap() - 48.8584).abs() < 1e-9 && (s["lon"].as_f64().unwrap() - 2.2945).abs() < 1e-9, "{s}");
}
+279
View File
@@ -0,0 +1,279 @@
//! Saved locations on the Map view (LRC-MAP-LOCATIONS): the list with counts of the photos in
//! view, `+` at the map's centre or around the selected photos, Go To, the checkbox selecting a
//! location's photos, circles drawn on the map, the active one's centre and radius handles (and Lock
//! Markers keeping them), Delete… asking first, and the Info panel hiding the map of a photo inside a
//! private location until Show Map. The map is never online in tests.
use egui::Pos2;
use serde_json::{Value, json};
use crate::headless::Headless;
use crate::{LightcraftApp, Services};
/// Paris ×3, London ×2, New York ×1 on the demo library's first six photos.
const PLACES: [(f64, f64); 6] =
[(48.8584, 2.2945), (48.8606, 2.3376), (48.8530, 2.3499), (51.5007, -0.1246), (51.5081, -0.0759), (40.7484, -73.9857)];
fn demo(size: [f32; 2]) -> (Headless, Vec<u64>) {
let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }), size, 1.0);
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(6).map(|p| p.0).collect();
for (id, (lat, lon)) in ids.iter().zip(PLACES) {
h.app.run("photo.setGps", json!({"ids": [id], "lat": lat, "lon": lon})).unwrap();
}
h.app.run("view.map", json!({})).unwrap();
h.app.run("map.setView", json!({"lat": 48.857, "lon": 2.32, "zoom": 12})).unwrap();
frames(&mut h, 4);
(h, ids)
}
fn frames(h: &mut Headless, n: usize) {
for _ in 0..n {
h.step();
}
}
fn state(h: &mut Headless) -> Value {
h.app.run("map.state", json!({})).unwrap()
}
fn widget(h: &Headless, id: &str) -> Option<egui::Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
fn click(h: &mut Headless, at: Pos2, button: egui::PointerButton) {
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
for pressed in [true, false] {
h.app.synthetic.push(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE });
h.step();
}
frames(h, 2);
}
fn drag(h: &mut Headless, a: Pos2, b: Pos2) {
h.app.synthetic.push(egui::Event::PointerMoved(a));
h.step();
h.app.synthetic.push(egui::Event::PointerButton {
pos: a,
button: egui::PointerButton::Primary,
pressed: true,
modifiers: egui::Modifiers::NONE,
});
h.step();
for i in 1..=10 {
h.app.synthetic.push(egui::Event::PointerMoved(a + (b - a) * (i as f32 / 10.0)));
h.step();
}
h.app.synthetic.push(egui::Event::PointerButton {
pos: b,
button: egui::PointerButton::Primary,
pressed: false,
modifiers: egui::Modifiers::NONE,
});
h.step();
frames(h, 2);
}
fn location(h: &mut Headless, id: u64) -> Value {
h.app.session.execute("map.locations", &json!({})).unwrap()["locations"]
.as_array()
.unwrap()
.iter()
.find(|l| l["id"] == id)
.cloned()
.unwrap_or(Value::Null)
}
fn drawn(s: &Value, id: u64) -> Value {
s["locations"].as_array().unwrap().iter().find(|l| l["id"] == id).cloned().unwrap_or_else(|| panic!("location {id} drawn: {s}"))
}
#[test]
fn the_list_makes_shows_and_selects_locations() {
let (mut h, ids) = demo([1300.0, 1000.0]);
// + with nothing placed selected: at the map's centre, then renamed in place
h.app.run("library.select", json!({"ids": []})).unwrap();
let plus = widget(&h, "map:location:new").expect("+ in the list").center();
click(&mut h, plus, egui::PointerButton::Primary);
let first = h.app.session.map.locations.list().first().cloned().expect("a location");
assert!((first.lat - 48.857).abs() < 0.01 && (first.lon - 2.32).abs() < 0.01, "{first:?}");
assert!(h.app.ui.map.renaming.is_some(), "its name is offered for editing");
h.request("ui.text", json!({"text": "Eiffel"}), std::time::Duration::from_secs(20));
h.request("ui.key", json!({"key": "Enter"}), std::time::Duration::from_secs(20));
frames(&mut h, 3);
// (the text replaces the selected default name, or follows it)
let name = location(&mut h, first.id)["name"].as_str().unwrap().to_string();
assert!(name.ends_with("Eiffel"), "{name}");
// a location around the selected photos (Paris's three)
h.app.run("library.select", json!({"ids": &ids[..3]})).unwrap();
let r = h.app.run("map.location.new", json!({"name": "Paris"})).unwrap();
let paris = r["id"].as_u64().unwrap();
assert_eq!(r["photos"], 3, "{r}");
frames(&mut h, 3);
// the list shows it with the photos in view inside it; circles are drawn
assert!(widget(&h, &format!("map:location:{paris}")).is_some());
let s = state(&mut h);
assert_eq!(drawn(&s, paris)["active"], true, "the new one is the active one");
// Go To from another view of the world
h.app.run("map.setView", json!({"lat": 0, "lon": 100, "zoom": 6})).unwrap();
frames(&mut h, 2);
let at = widget(&h, &format!("map:location:{paris}")).unwrap().center();
click(&mut h, at, egui::PointerButton::Primary);
let s = state(&mut h);
assert!((s["lat"].as_f64().unwrap() - 48.857).abs() < 0.05 && (s["lon"].as_f64().unwrap() - 2.33).abs() < 0.05, "{s}");
// the checkbox selects the location's photos in view, and clears them
h.app.run("library.select", json!({"ids": [ids[5]]})).unwrap();
frames(&mut h, 2);
let cb = widget(&h, &format!("map:location:check:{paris}")).unwrap().center();
click(&mut h, cb, egui::PointerButton::Primary);
let mut sel: Vec<u64> = h.app.session.selection.ids.iter().map(|p| p.0).collect();
sel.sort_unstable();
let mut want = vec![ids[0], ids[1], ids[2], ids[5]];
want.sort_unstable();
assert_eq!(sel, want, "added to the selection");
click(&mut h, cb, egui::PointerButton::Primary);
assert_eq!(h.app.session.selection.ids.iter().map(|p| p.0).collect::<Vec<_>>(), vec![ids[5]]);
// the commands
h.app.run("map.location.select", json!({"id": paris})).unwrap();
assert_eq!(h.app.session.selection.ids.len(), 3);
assert!(h.app.run("map.location.show", json!({"id": 999})).is_err());
}
#[test]
fn the_active_locations_handles_move_it_unless_markers_are_locked() {
let (mut h, _) = demo([1300.0, 1000.0]);
let r = h.app.run("map.location.new", json!({"name": "Here"})).unwrap();
let id = r["id"].as_u64().unwrap();
h.app.run("library.select", json!({"ids": []})).unwrap();
h.app.run("map.location.show", json!({"id": id})).unwrap();
frames(&mut h, 3);
let before = location(&mut h, id);
let d = drawn(&state(&mut h), id);
let (c, r_px) = (egui::pos2(d["x"].as_f64().unwrap() as f32, d["y"].as_f64().unwrap() as f32), d["radiusPx"].as_f64().unwrap() as f32);
// the radius handle: twice as far
drag(&mut h, egui::pos2(c.x + r_px, c.y), egui::pos2(c.x + 2.0 * r_px, c.y));
let after = location(&mut h, id);
let ratio = after["radius"].as_f64().unwrap() / before["radius"].as_f64().unwrap();
assert!((ratio - 2.0).abs() < 0.1, "{before} → {after}");
// the centre handle: moves it
drag(&mut h, c, c + egui::vec2(80.0, 40.0));
let moved = location(&mut h, id);
assert!(
moved["lat"].as_f64().unwrap() < before["lat"].as_f64().unwrap() && moved["lon"].as_f64().unwrap() > before["lon"].as_f64().unwrap(),
"{moved}"
);
// Lock Markers keeps it: the drag pans instead
h.app.run("map.lockMarkers", json!({"on": true})).unwrap();
frames(&mut h, 2);
let d = drawn(&state(&mut h), id);
let c = egui::pos2(d["x"].as_f64().unwrap() as f32, d["y"].as_f64().unwrap() as f32);
drag(&mut h, c, c + egui::vec2(60.0, 0.0));
assert_eq!(location(&mut h, id)["lat"], moved["lat"]);
assert_eq!(location(&mut h, id)["lon"], moved["lon"]);
}
#[test]
fn delete_asks_first_and_private_hides_the_info_panel_map() {
let (mut h, ids) = demo([1400.0, 1800.0]);
// nothing selected: at the map's centre (48.857, 2.32), a kilometre round
h.app.run("library.select", json!({"ids": []})).unwrap();
let r = h.app.run("map.location.new", json!({"name": "Home"})).unwrap();
let id = r["id"].as_u64().unwrap();
frames(&mut h, 3);
// Private from the row's menu
let row = widget(&h, &format!("map:location:{id}")).unwrap().center();
click(&mut h, row, egui::PointerButton::Secondary);
let private = widget(&h, "map:location:menu:private").expect("the row's menu").center();
click(&mut h, private, egui::PointerButton::Primary);
assert_eq!(location(&mut h, id)["private"], true);
// a photo inside it: the Info panel shows no map until Show Map
h.app.run("photo.setGps", json!({"ids": [ids[0]], "lat": 48.857, "lon": 2.32})).unwrap();
h.app.run("library.select", json!({"ids": [ids[0]]})).unwrap();
h.app.run("panel.info", json!({})).unwrap();
frames(&mut h, 4);
assert!(widget(&h, "info:miniMap").is_none(), "hidden inside a private location");
let show = widget(&h, "button:showPrivateMap").expect("Show Map").center();
click(&mut h, show, egui::PointerButton::Primary);
frames(&mut h, 2);
assert!(widget(&h, "info:miniMap").is_some(), "shown when asked");
// moved into another private location, it asks again; back in the first, it doesn't
h.app.run("map.location.add", json!({"name": "Cabin", "lat": 45.0, "lon": 6.0, "radius": 1000.0, "private": true})).unwrap();
h.app.run("photo.setGps", json!({"ids": [ids[0]], "lat": 45.0, "lon": 6.0})).unwrap();
frames(&mut h, 3);
assert!(widget(&h, "info:miniMap").is_none(), "another private location: hidden again");
h.app.run("photo.setGps", json!({"ids": [ids[0]], "lat": 48.857, "lon": 2.32})).unwrap();
frames(&mut h, 3);
assert!(widget(&h, "info:miniMap").is_some(), "the location already shown");
// Delete… asks first; Delete removes it
let row = widget(&h, &format!("map:location:{id}")).unwrap().center();
click(&mut h, row, egui::PointerButton::Secondary);
let del = widget(&h, "map:location:menu:delete").expect("Delete… in the menu").center();
click(&mut h, del, egui::PointerButton::Primary);
assert!(!location(&mut h, id).is_null(), "nothing deleted before the confirmation");
let yes = widget(&h, "map:location:confirmDelete").expect("the confirmation").center();
click(&mut h, yes, egui::PointerButton::Primary);
assert!(location(&mut h, id).is_null());
// a new private place where the deleted one was asks again: the approval was for that location
let cabin = h.app.run("map.locations", json!({})).unwrap()["locations"][0]["id"].as_u64().unwrap();
h.app.run("map.location.remove", json!({"id": cabin})).unwrap();
let flat = h.app.run("map.location.add", json!({"name": "Flat", "lat": 48.8572, "lon": 2.3203, "radius": 1000.0, "private": true})).unwrap();
assert_ne!(flat["id"].as_u64(), Some(id), "a deleted location's id isn't given out again");
frames(&mut h, 3);
assert!(widget(&h, "info:miniMap").is_none(), "hidden: Show Map was for another place");
}
/// The Map view is gated like the Info panel's map: centred inside a private location (Show Map not
/// yet asked) it fetches no tiles and says so; panning out of it, or Show Map, ends that, and the approval is
/// for that location only.
#[test]
fn a_map_view_centred_in_a_private_location_asks_before_it_shows_tiles() {
let (mut h, _) = demo([1400.0, 1000.0]);
h.app.run("library.select", json!({"ids": []})).unwrap();
// a kilometre round the map's centre
let id = h.app.run("map.location.new", json!({"name": "Home"})).unwrap()["id"].as_u64().unwrap();
frames(&mut h, 3);
assert!(widget(&h, "map:privateNote").is_none(), "a public location asks nothing");
h.app.run("map.location.update", json!({"id": id, "private": true})).unwrap();
frames(&mut h, 3);
assert!(widget(&h, "map:privateNote").is_some(), "a view inside a private location says so");
assert!(widget(&h, "button:showPrivateMapView").is_some(), "and offers Show Map");
// out of it: nothing to ask
h.app.run("map.setView", json!({"lat": 51.5, "lon": -0.12, "zoom": 12})).unwrap();
frames(&mut h, 3);
assert!(widget(&h, "map:privateNote").is_none(), "centred elsewhere");
// back in it: asks again; Show Map ends it
h.app.run("map.setView", json!({"lat": 48.857, "lon": 2.32, "zoom": 12})).unwrap();
frames(&mut h, 3);
let show = widget(&h, "button:showPrivateMapView").expect("Show Map").center();
click(&mut h, show, egui::PointerButton::Primary);
frames(&mut h, 2);
assert!(widget(&h, "map:privateNote").is_none(), "shown when asked");
// another private location asks again
h.app.run("map.location.add", json!({"name": "Cabin", "lat": 45.0, "lon": 6.0, "radius": 1000.0, "private": true})).unwrap();
h.app.run("map.setView", json!({"lat": 45.0, "lon": 6.0, "zoom": 12})).unwrap();
frames(&mut h, 3);
assert!(widget(&h, "map:privateNote").is_some(), "the approval was for Home, not Cabin");
}
/// Location ids start at 1 in every library: opening another one forgets the Map view's
/// saved-location state, so library B's location 3 doesn't inherit A's Delete… confirmation.
#[test]
fn opening_another_library_forgets_the_saved_location_state() {
let dir = std::env::temp_dir().join(format!("lc-ui-map-switch-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut h, _) = demo([1200.0, 1000.0]);
let id = h.app.run("map.location.add", json!({"name": "Home", "lat": 48.86, "lon": 2.33})).unwrap()["id"].as_u64().unwrap();
let m = &mut h.app.ui.map;
m.active_location = Some(id);
m.confirm_delete = Some(id);
m.renaming = Some((id, "Home".into()));
m.active_pin_photo = Some(lightcraft_catalog::PhotoId(1));
m.private_view_shown.push((id, 1, 2));
let r = h.app.run("app.openLibrary", json!({"path": dir.join("second").to_string_lossy()}));
assert!(r.is_ok(), "{r:?}");
let m = &h.app.ui.map;
assert!(m.active_location.is_none() && m.confirm_delete.is_none() && m.renaming.is_none() && m.active_pin_photo.is_none());
assert!(m.private_view_shown.is_empty(), "the Map view's Show Map approvals are for the library they were given in");
drop(h);
let _ = std::fs::remove_dir_all(&dir);
}
+238
View File
@@ -0,0 +1,238 @@
//! Track logs on the Map view (LRC-MAP-TRACKLOG): loading one draws it and fits the map, the
//! Tracklog menu picks the active track and shows its time range, the selected photos are marked
//! where Auto-Tag would put them, Auto-Tag tags them in one undo step, and bad files, hostile tracks
//! and tiny windows never crash. The map is never online in tests.
use lightcraft_catalog::{Op, PhotoId};
use serde_json::{Value, json};
use crate::headless::Headless;
use crate::{LightcraftApp, Services};
/// Two tracks: "Walk" (10:00–10:02 and 12:00–12:01 UTC, two segments) and "Ride" (14:00–14:10).
const TWO_TRACKS: &str = r#"<?xml version="1.0"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
<trk><name>Walk</name>
<trkseg>
<trkpt lat="46.0000" lon="7.0000"><time>2026-05-01T10:00:00Z</time></trkpt>
<trkpt lat="46.0010" lon="7.0020"><time>2026-05-01T10:01:00Z</time></trkpt>
<trkpt lat="46.0020" lon="7.0040"><time>2026-05-01T10:02:00Z</time></trkpt>
</trkseg>
<trkseg>
<trkpt lat="46.1000" lon="7.1000"><time>2026-05-01T12:00:00Z</time></trkpt>
<trkpt lat="46.1010" lon="7.1010"><time>2026-05-01T12:01:00Z</time></trkpt>
</trkseg>
</trk>
<trk><name>Ride</name><trkseg>
<trkpt lat="47.0000" lon="8.0000"><time>2026-05-01T14:00:00Z</time></trkpt>
<trkpt lat="47.1000" lon="8.1000"><time>2026-05-01T14:10:00Z</time></trkpt>
</trkseg></trk>
</gpx>"#;
fn temp_gpx(tag: &str, text: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-ui-tracks-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let p = d.join("walk.gpx");
std::fs::write(&p, text).unwrap();
p
}
fn demo() -> Headless {
let mut h = Headless::new(
LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }),
[1300.0, 1000.0],
1.0,
);
h.app.run("view.map", json!({})).unwrap();
frames(&mut h, 3);
h
}
fn frames(h: &mut Headless, n: usize) {
for _ in 0..n {
h.step();
}
}
fn state(h: &mut Headless) -> Value {
h.app.run("map.state", json!({})).unwrap()
}
fn widget(h: &Headless, id: &str) -> Option<egui::Rect> {
h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r)
}
/// Frames until the track log being read on a worker thread has landed (or was refused).
fn wait_loaded(h: &mut Headless) {
let end = std::time::Instant::now() + std::time::Duration::from_secs(30);
while state(h)["trackLog"]["loading"].is_string() {
assert!(std::time::Instant::now() < end, "the track log never landed");
std::thread::sleep(std::time::Duration::from_millis(5));
h.step();
}
frames(h, 2);
}
fn click(h: &mut Headless, id: &str) {
let at = widget(h, id).unwrap_or_else(|| panic!("{id} on screen")).center();
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
for pressed in [true, false] {
h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
h.step();
}
frames(h, 2);
}
#[test]
fn a_loaded_track_is_drawn_and_the_map_fits_it_and_the_menu_picks_a_track() {
let mut h = demo();
let path = temp_gpx("load", TWO_TRACKS);
h.app.run("map.loadTrackLog", json!({"path": path.to_string_lossy()})).unwrap();
wait_loaded(&mut h);
let s = state(&mut h);
let t = &s["trackLog"];
assert_eq!(t["loaded"], true, "{s}");
assert_eq!(t["tracks"].as_array().unwrap().len(), 2);
// the map shows the whole log (Switzerland), and the track is drawn
let (lat, lon) = (s["lat"].as_f64().unwrap(), s["lon"].as_f64().unwrap());
assert!((45.5..47.6).contains(&lat) && (6.5..8.6).contains(&lon), "{lat} {lon}");
assert!(t["drawn"]["points"].as_u64().unwrap() >= 2, "{t}");
// the Tracklog menu: the two tracks, the time range; picking Ride makes it the active one
click(&mut h, "map:tracklog");
assert!(widget(&h, "map:tracklog:info").is_some(), "the menu shows the time range");
assert!(widget(&h, "map:tracklog:track:1").is_some());
click(&mut h, "map:tracklog:track:1");
let t = state(&mut h)["trackLog"].clone();
assert_eq!(t["active"], 1, "{t}");
// Clear from the menu
click(&mut h, "map:tracklog");
click(&mut h, "map:tracklog:clear");
assert_eq!(state(&mut h)["trackLog"]["loaded"], false);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
#[test]
fn the_selected_photos_are_marked_on_the_track_and_auto_tag_tags_them_in_one_step() {
let mut h = demo();
let ids: Vec<u64> = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect();
// two photos in the Walk's time (camera clock UTC), one between the tracks
for (id, t) in ids.iter().zip(["2026-05-01T10:00:30", "2026-05-01T12:00:30", "2026-05-01T13:00:00"]) {
h.app.session.commit("t", Op::SetCaptured { id: PhotoId(*id), captured: Some(t.into()) }).unwrap();
}
h.app.run("photo.removeGps", json!({"ids": ids})).unwrap();
h.app.run("map.trackLog", json!({"gpx": TWO_TRACKS, "offset": "+00:00"})).unwrap();
h.app.run("map.trackLog.fit", json!({})).unwrap();
h.app.run("library.select", json!({"ids": ids})).unwrap();
frames(&mut h, 4);
let t = state(&mut h)["trackLog"].clone();
assert_eq!(t["onTrack"], 2, "two of the three fall on the track: {t}");
let steps = h.app.session.undo.len();
let r = h.app.run("map.trackLog.autoTag", json!({})).unwrap();
assert_eq!(r["tagged"], 2, "{r}");
assert_eq!(h.app.session.undo.len(), steps + 1, "one undo step");
let gps = |h: &Headless, id: u64| h.app.session.catalog.photo(PhotoId(id)).and_then(|p| p.meta.gps);
let a = gps(&h, ids[0]).expect("tagged");
assert!((a.0 - 46.0).abs() < 0.01 && (a.1 - 7.0).abs() < 0.01, "{a:?}");
assert!(gps(&h, ids[2]).is_none(), "outside the track's time");
h.app.run("edit.undo", json!({})).unwrap();
assert!(gps(&h, ids[0]).is_none() && gps(&h, ids[1]).is_none());
}
#[test]
fn bad_files_hostile_tracks_and_tiny_windows_never_crash() {
let mut h = demo();
h.app.run("map.trackLog", json!({"gpx": TWO_TRACKS})).unwrap();
let before = h.app.session.map.track_generation;
// a file that isn't GPX, a missing one: refused with a message, and the loaded log stays
let junk = temp_gpx("junk", "<html>not a track</html>");
for p in [junk.to_string_lossy().to_string(), "Z:/no/such/file.gpx".to_string()] {
h.app.ui.toast = None;
h.app.run("map.loadTrackLog", json!({"path": p})).unwrap();
wait_loaded(&mut h);
assert!(h.app.ui.toast.is_some(), "{p}: the refusal is shown");
}
assert_eq!(h.app.session.map.track_generation, before);
// a track across the antimeridian and one at the pole draw without a crash
let hostile = r#"<gpx><trk><trkseg>
<trkpt lat="10" lon="179.9"><time>2026-05-01T10:00:00Z</time></trkpt>
<trkpt lat="10.1" lon="-179.9"><time>2026-05-01T10:01:00Z</time></trkpt>
<trkpt lat="89.99" lon="0"><time>2026-05-01T10:02:00Z</time></trkpt>
<trkpt lat="-89.99" lon="180"><time>2026-05-01T10:03:00Z</time></trkpt>
</trkseg></trk></gpx>"#;
h.app.run("map.trackLog", json!({"gpx": hostile})).unwrap();
for z in [0.0, 1.0, 5.0, 12.0] {
h.app.run("map.setView", json!({"lat": 10, "lon": 180, "zoom": z})).unwrap();
frames(&mut h, 2);
}
// a tiny window
h.request("ui.resize", json!({"width": 60, "height": 40}), std::time::Duration::from_secs(20));
frames(&mut h, 3);
h.request("ui.resize", json!({"width": 1300, "height": 1000}), std::time::Duration::from_secs(20));
frames(&mut h, 2);
assert_eq!(state(&mut h)["trackLog"]["loaded"], true);
let _ = std::fs::remove_dir_all(junk.parent().unwrap());
}
/// Load Tracklog… reads the file on a worker thread with a row on the activity stack, and the UI
/// keeps drawing meanwhile.
#[test]
fn loading_runs_off_the_ui_thread_with_an_activity_row() {
let mut h = demo();
// 60 000 points: long enough to see the row
let mut gpx = String::from("<gpx><trk><trkseg>");
for i in 0..60_000u32 {
let (lat, lon) = (45.0 + f64::from(i) * 1e-5, 6.0 + f64::from(i) * 1e-5);
gpx.push_str(&format!("<trkpt lat=\"{lat:.6}\" lon=\"{lon:.6}\"><time>2026-05-01T10:{:02}:{:02}Z</time></trkpt>", (i / 60) % 60, i % 60));
}
gpx.push_str("</trkseg></trk></gpx>");
let path = temp_gpx("big", &gpx);
h.app.run("map.loadTrackLog", json!({"path": path.to_string_lossy()})).unwrap();
let rows: Vec<String> = h.app.session.activity.list().iter().map(|t| t.label.clone()).collect();
assert!(rows.iter().any(|l| l.contains("walk.gpx")), "the activity stack shows the load: {rows:?}");
h.step();
wait_loaded(&mut h);
assert_eq!(state(&mut h)["trackLog"]["points"], 60_000);
assert!(h.app.session.activity.list().iter().all(|t| !t.label.contains("walk.gpx")), "the row goes with the load");
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A track log loaded (or cleared) while another is still being read wins: the one being read
/// doesn't overwrite it when it arrives.
#[test]
fn a_track_loaded_while_another_is_read_is_not_overwritten() {
let mut h = demo();
let mut gpx = String::from("<gpx><trk><trkseg>");
for i in 0..60_000u32 {
let (lat, lon) = (45.0 + f64::from(i) * 1e-5, 6.0 + f64::from(i) * 1e-5);
gpx.push_str(&format!("<trkpt lat=\"{lat:.6}\" lon=\"{lon:.6}\"><time>2026-05-01T10:{:02}:{:02}Z</time></trkpt>", (i / 60) % 60, i % 60));
}
gpx.push_str("</trkseg></trk></gpx>");
let path = temp_gpx("race", &gpx);
h.app.run("map.loadTrackLog", json!({"path": path.to_string_lossy()})).unwrap();
assert!(state(&mut h)["trackLog"]["loading"].is_string());
// a null path is no path (the engine reads it as a query): the load goes on
h.app.run("map.trackLog", json!({"path": null, "gpx": null})).unwrap();
assert!(state(&mut h)["trackLog"]["loading"].is_string(), "a query leaves the load to come");
h.app.run("map.trackLog", json!({"gpx": TWO_TRACKS})).unwrap();
assert!(state(&mut h)["trackLog"]["loading"].is_null(), "the earlier load is given up");
// the worker finishes (its row goes); what it read is dropped
let end = std::time::Instant::now() + std::time::Duration::from_secs(30);
while h.app.session.activity.list().iter().any(|t| t.label.contains("walk.gpx")) {
assert!(std::time::Instant::now() < end, "the read never finished");
std::thread::sleep(std::time::Duration::from_millis(5));
h.step();
}
frames(&mut h, 3);
let t = state(&mut h)["trackLog"].clone();
assert_eq!(t["tracks"].as_array().map(Vec::len), Some(2), "the log loaded last stays: {t}");
// a query with a null path or gpx doesn't fit the map to the track: the view panned away stays
h.app.ui.map.center_lat = -33.0;
h.app.ui.map.center_lon = 151.0;
h.app.ui.map.zoom = 4.0;
h.app.run("map.trackLog", json!({"path": null, "gpx": null})).unwrap();
let m = &h.app.ui.map;
assert_eq!((m.center_lat, m.center_lon, m.zoom), (-33.0, 151.0, 4.0), "the view is left alone");
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
+42
View File
@@ -81,6 +81,33 @@ pub struct Tokens {
/// Cautionary notices (e.g. a raw shown from its embedded preview): a muted amber.
pub caution: Color32,
pub mask_overlay: Color32,
// The Map view's marks. They are drawn on map tiles, which are pictures no theme changes, so every
// theme starts from the same colours, picked to stand out on light streets, green parks and blue
// water; a theme that needs others sets them here.
/// A photo's pin, and the pins' legend dot.
pub map_pin: Color32,
/// A selected photo's pin, and a cluster badge with a selected photo in it.
pub map_pin_selected: Color32,
/// A cluster's badge.
pub map_badge: Color32,
/// The outline of a mark, and of a hovered one.
pub map_edge: Color32,
pub map_edge_hover: Color32,
/// Text and dots on a mark, and dark text on the light selected badge.
pub map_mark_text: Color32,
pub map_mark_text_on_light: Color32,
/// The selected-count bubble on a badge.
pub map_selected_bubble: Color32,
/// The tile credit: dark text on a light plate, as on the tiles it sits on.
pub map_credit_text: Color32,
pub map_credit_plate: Color32,
/// A saved location's circle, a private one's, and the name written over the map.
pub map_location: Color32,
pub map_location_private: Color32,
pub map_location_label: Color32,
/// A track log, and the casing that lifts it off the tiles.
pub map_track: Color32,
pub map_track_casing: Color32,
// metrics (points)
pub top_bar_h: f32,
pub bottom_bar_h: f32,
@@ -164,6 +191,21 @@ impl Default for Tokens {
reject: Color32::from_rgb(0xe0, 0x4a, 0x4a),
caution: Color32::from_rgb(0xe3, 0xa8, 0x3c),
mask_overlay: Color32::from_rgba_unmultiplied(0xe0, 0x20, 0x30, 110),
map_pin: Color32::from_rgb(255, 115, 0),
map_pin_selected: Color32::from_rgb(255, 204, 0),
map_badge: Color32::from_rgb(240, 100, 20),
map_edge: Color32::from_black_alpha(170),
map_edge_hover: Color32::WHITE,
map_mark_text: Color32::WHITE,
map_mark_text_on_light: Color32::BLACK,
map_selected_bubble: Color32::from_rgb(30, 110, 230),
map_credit_text: Color32::from_gray(38),
map_credit_plate: Color32::from_rgba_premultiplied(205, 205, 205, 205),
map_location: Color32::from_rgb(255, 204, 0),
map_location_private: Color32::from_rgb(230, 80, 80),
map_location_label: Color32::from_gray(20),
map_track: Color32::from_rgb(0xff, 0x3d, 0x8b),
map_track_casing: Color32::from_rgba_premultiplied(0x10, 0x10, 0x18, 0xb0),
top_bar_h: 42.0,
bottom_bar_h: 48.0,
panel_w: 270.0,
+14
View File
@@ -108,6 +108,20 @@ 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:<pane>`, `compare:renderFailed:<pane>`) |
| `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, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it); `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"\|"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 |
| `engine.execute {command: "map.state"}` | — | The Map view as drawn last frame (app only) → `{lat, lon, zoom, maxZoom, source, offline, attribution, shown, canvas: {x, y, width, height}, filmstrip, pins: [{ids, count, selected, x, y, lat, lon}], clusterCount, clusterMs, withGps, withoutGps, lockMarkers, movingPin: {id, x, y}, hovered, drop: {count, x, y, lat, lon}, miniMap: {photo, lat, lon, zoom, rect, pin, tiles}}` (`miniMap`: the Info panel's map, null when not drawn); `selected` is how many of a pin's photos are selected, `x`/`y` are screen points, at most 500 pins listed. See `docs/map.md` |
| `engine.execute {command: "map.fit"}`, `map.setView`, `map.zoomIn`, `map.zoomOut` | `map.setView {lat?, lon?, zoom?}` | The Map view (UI commands): fit the photos with a position; set the centre (lat −90…90, lon wrapped) and zoom (0…24, shown within the source's own range), anything else refused; one zoom level in / out → the map state |
| `engine.execute {command: "map.lockMarkers"}` | `{on?}` | Lock Markers on / off, toggles without `on` (UI command; ⌘K / Ctrl+K in the Map view; `map.toggleLock` and `map.lock` are older names) → `{on}` |
| `engine.execute {command: "map.showPins"}` | `{on?}`; `map.showLocations {on?}`; `map.settings` | Hide Pins (H in the Map view) and the saved locations list (O) on / off, toggling without `on` → `{on}`; `map.settings` opens Settings ▸ Map (UI commands) |
| `engine.execute {command: "map.locationFilter"}` | `{mode?: visible\|tagged\|untagged\|none}` | The Map view's location filter (UI command): narrows the photos in view over the library's filter while the Map view is shown → `{mode, visible, tagged, untagged, all, area, countMs, shown}`. See `docs/map.md` → Location filter |
| `engine.execute {command: "map.locations"}` | `map.location.add {name, lat, lon, radius?, private?}` or `{name, fromSelection: true}`, `map.location.update {id, …}`, `map.location.remove {id}`, `map.location.photos {id, inView?}`; app: `map.location.show {id}`, `map.location.select {id}`, `map.location.new {name?}` | The library's saved locations (`locations.json`) → `{locations: [{id, name, lat, lon, radius, private, photos, inView}], count, countMs}`. Not undo steps. See `docs/map.md` → Saved locations |
| `engine.execute {command: "map.trackLog"}` | `{path?, gpx?, active?, offset?, clear?}`; app: `map.loadTrackLog {path?}` (a worker thread), `map.trackLog.autoTag {offset?}`, `map.trackLog.setOffset {offset?}`, `map.trackLog.fit` | The Map view's track log (session only) → `{loaded, path, name, points, tracks, active, start, end, duration, offset, startLocal, endLocal, generation, …}`; `photo.autoTagTracklog {loaded: true}` tags from it. See `docs/map.md` → Track logs |
| `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: "photo.removeGps"}` | `{ids?}` | Clears the photos' position (default: the selection), one undo step "Remove GPS Coordinates"; unknown ids are refused; `photo.clearGps` is its older name → `{changed, cleared}` |
| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{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 |
+2 -1
View File
@@ -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 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 ✅ (drop filmstrip photos on the map, move pins, Lock Markers, Remove GPS Coordinates); Info panel map, track logs on the map, the Map view's keys, Window ▸ Map and Settings ▸ Map ✅; Map module 🟡 (no keyless imagery, no place search); 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) |
@@ -97,6 +97,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| Date | Change | Summary |
|---|---|---|
| 2026-11-26 | minor | Gap 31 added: sidebar multi-selection — the batch album, keyword and library-folder commands (#2757) have no sidebar caller yet |
| 2026-11-16 | patch | Gap 16: the Map module's remaining parts landed (Info panel map, location filter with counts, saved locations, track logs, keys, menus and Settings ▸ Map); LR-MAP-MODULE 🟡; ranks and hours unchanged (Book, Slideshow and publish services remain) |
| 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open |
| 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-23 | minor | Gap 3: process V13 eases global Shadows off at large amounts, and negative Texture and the Global grading wheel act less, fitted to 56 Lightroom exports of real Canon edits (mean ΔE 9.5 → 9.0, #523); the gap stays open and hours are unchanged |
+16
View File
@@ -55,6 +55,22 @@ 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) |
| `H` | In the Map view: hide / show the photo pins (elsewhere it stays Remove) |
| `O` | In the Map view: show / hide the saved locations list (elsewhere it stays the mask overlay) |
| `=` / `-` | In the Map view: zoom the map in / out (elsewhere the grid's thumbnail size) |
| ⌘= / ⌘- / ⌘0 (Ctrl) | In the Map view: zoom the map in / out, fit it to the photos (elsewhere the photo's zoom) |
In the Map view these keys follow the same rule as `\` in the grids: they act on the map only while their default
commands (Show Original, Add Keywords, Remove, Mask Overlay, the thumbnail size and zoom) keep those keys, and a key
given to another command runs that command. Window ▸ Map lists them.
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` + `←` /
+417
View File
@@ -0,0 +1,417 @@
# Map
The Map view (Window ▸ Map ▸ Map View, ⌘⌥3 / Ctrl+Alt+3) shows the photos that have a GPS position on a slippy map.
This page describes the view, geotagging, where the map's tiles come from, what is sent over the network,
and the commands behind it.
## Map view
The map shows the photos of the current list (the same source, filter and sort as the grid) that have a
valid GPS position as pins. A position that is out of range or not a number counts as no position.
- **Pins and clusters.** Pins closer than about 60 points merge into a cluster with their count. The
groups are cells anchored to the world, not the screen, and each zoom's cells nest in the one above, so
panning never regroups the pins and zooming in only splits clusters. Positions are projected once per
change of the photo list; clustering then costs one hash lookup per photo in view (see Performance).
- **Selection.** 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.
- **Opening.** A double-click on a pin opens its photo in Detail; on a cluster it zooms in two levels.
Hovering a pin shows its (first) photo's thumbnail, with the cluster's count.
- **Moving around.** Drag the map to pan, scroll to zoom around the pointer, double-click the empty map to
zoom in. The bottom toolbar has the Map Style list, Fit to Photos, − / the zoom slider / +, and Lock
Markers. The first time the map is shown in a session it fits the photos with a position; after that it
stays where you left it.
- **Photos without a position.** "N photos without GPS" at the bottom left counts the photos of the list
that have none. Drag them onto the map from the filmstrip (below), type a position in the Info panel, or use
Photo ▸ Auto-Tag from Tracklog….
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.
**Performance.** Clustering 50,000 photos in view (spread over Europe, zoom 5, 240 clusters) took 1.7 ms in a
release build on the machine this was measured on (the `many_photos_cluster_quickly` test prints it).
## Geotagging
As in Lightroom Classic's Map module:
- **Drop photos on the map.** Drag photos from the filmstrip onto the map and let go 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; the drop gives 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.
- **Move a pin.** Drag a single photo's pin to its new place: one undo step. A cluster isn't moved:
dragging it pans the map, as a drag on the empty map does, so zoom in until the photo has its own pin. A
pin let go outside the map (over the filmstrip, say) stays where it was.
- **Lock Markers** (the bottom toolbar, ⌘K / Ctrl+K in the Map view, `map.lockMarkers {on?}`) stops pins
from being moved; dragging one then pans the map. It is saved with the window state (`ui.json`).
- **Remove GPS Coordinates.** Photo ▸ Remove GPS Coordinates clears the position of the selected photos; a
right-click on a pin offers the same for that pin's photos. One undo step, "Remove GPS Coordinates"
(`photo.removeGps`; `photo.clearGps` is its older name).
- **The poles.** The map can't show them (Web Mercator stops at ±85.05° latitude), so a drop or a pin move
reaches 85.05° north or south at most. The longitude of a drop on the world's repeat at low zoom is
wrapped into −180…180. Type a position closer to a pole in the Info panel's GPS field.
- **Sidecars.** Positions are written to XMP sidecars as EXIF GPS (`exif:GPSLatitude`, `exif:GPSLongitude`)
when sidecars are written (Photo ▸ Save Metadata to File, or at once with automatic XMP writing on). For a
photo whose position you set or cleared in LightCraft (a drop, a pin move, Remove GPS Coordinates, the Info
panel's GPS field), the sidecar takes LightCraft's position as it is: clearing it, or undoing a geotag,
removes the GPS from the sidecar. The library remembers these photos (`prefs.json` `gpsOwned`), so a
position cleared before you close it still leaves the sidecar when it is written later. A photo whose position you never touched here keeps
whatever GPS another app put in its sidecar, since LightCraft doesn't read GPS from sidecars.
`map.state` reports the view (`lat`, `lon`, `zoom`, `maxZoom`, `source`, `offline`, `attribution`), the map
canvas, whether the filmstrip is drawn, every pin or cluster drawn in the last frame (`pins`: `ids`, `count`,
`selected`, screen `x` / `y`, `lat` / `lon`; at most 500 listed, `clusterCount` counts them all),
`clusterMs`, `withGps` / `withoutGps`, `lockMarkers`, `movingPin` (`{id, x, y}` while a pin is dragged),
`hovered` (the hovered pin's photos) and `drop` (`{count, x, y, lat, lon}` while photos are carried over the
map). Widgets: `map:canvas`, `map:pin:<first photo id>`, `map:fit`, `map:lockMarkers`, `map:withoutGps`,
`map:hoverThumb`, `map:pinMenu:removeGps`, `map:attribution`.
## Info panel map
Under the location fields, the Info panel shows a small map of the active photo's place (with several photos
selected, the active one's): the fields' width, 160 points tall, zoom 14 (or the tile source's deepest zoom),
the photo's pin and the tile credit. Near a pole, where the map stops at ±85.05°, the pin stays on the map's edge.
A photo without a valid position has no map. The map doesn't pan; a click opens the Map view centred there at
zoom 14. **Open in Browser** (formerly Show on Map) still opens the place on openstreetmap.org.
It draws from the same tile service and texture cache as the Map view, so tiles it loaded are not fetched again
when you open the Map view. It asks only for the tiles it shows (no ring around them), and only while it is on
screen: with the Info panel closed or the map scrolled out of view, nothing is fetched for it. Offline it stays
grey with the pin and "Map tiles are off".
`map.state` reports it as `miniMap`: `{photo, lat, lon, zoom, rect, pin, tiles: {drawn, fromParent, missing,
offline}}` (null when it wasn't drawn in the last frame). Widgets: `info:miniMap`, `info:miniMapAttribution`.
## Location filter
The bar over the map (show or hide it with `\` in the Map view, or Window ▸ Map ▸ Location Filter Bar) narrows
the photos in view, as Lightroom Classic's Location Filter does. Each choice shows its count:
- **Visible on Map**: the photos whose position is inside the part of the world the map shows. The count
follows the view at once; the filmstrip follows once the view has rested for a quarter of a second, so
panning doesn't refilter it every frame. A view set by a command (`map.setView`, `map.fit`, zoom) applies at
once. When the map is wider than the world, every longitude counts; a view across ±180° wraps.
- **Tagged**: the photos with a valid position. **Untagged**: those without; the map then shows no pins and
says the photos can be dragged onto it from the filmstrip.
- **None**: no narrowing.
It sits on top of the library's own filter (source, Filter Bar, search), which it never changes: the
filmstrip, the selection and the keys follow it while the Map view is shown, and leaving the Map view brings
back exactly the grid's list. The choice is kept for the session. Pins always come from the photos before the
location filter, so a pin's photos are the ones it would narrow to.
It is made of two smart-rule fields that `library.filter`, smart albums and the rule editor also take
(Location group):
- **Has GPS** (`hasGps`, yes / no) counts only a valid position: finite, latitude −90…90, longitude
−180…180.
- **GPS Area** (`gpsArea`, is inside / is outside) takes `{south, west, north, east}` in degrees. East < west
means the box crosses the antimeridian and wraps. Edges count as inside, and a photo without a position is
neither inside nor outside. Missing edges, text, out-of-range values or south north of north are refused by
`library.filter`, `album.createSmart` and `album.setRules`; the rule editor shows four numbers.
`album.ruleFields` reports its kind as `area`.
`map.locationFilter {mode?: visible | tagged | untagged | none}` sets it (without `mode`, reports) and returns
`{mode, visible, tagged, untagged, all, area, countMs, shown}` (`area`: the box Visible on Map narrows to;
`shown`: the photos in the filmstrip now). `map.state` reports the same as `locationFilter`. Widgets:
`map:filterBar`, `map:filter:<mode>`, `map:untaggedNote`.
**Performance.** Narrowing 50,000 photos to an area took 9 ms, and counting 20,000 positions in one 0.1 ms, in a
release build (`narrowing_and_counting_many_photos`).
## Saved locations
Saved locations are named circles on the map: a centre and a radius (1 m to 1000 km), measured along the
Earth's surface, so a circle across ±180° or around a pole holds what it should.
- **The list** is in the navigator panel at the left of the map (Window ▸ Map ▸ Map Navigator). Each location
shows how many photos in view are inside it. A click goes to it (the map centres and zooms to show it) and
makes it the active one. Its checkbox selects its photos in view, or takes them out of the selection. Its
right-click menu has Go To, Select Photos, Rename…, Private, and Delete…, which asks first.
- **`+`** makes a new location around the selected photos that have a position (a radius that holds them, 10 % to
spare, at least 100 m), or at the map's centre with a 1 km radius when none has. Its name is offered for
editing at once.
- **On the map** every location in view is drawn as a circle with its name; private ones are red. The active
one has a centre handle and a radius handle: drag them to move it or change its size (saved when let go over
the map). Lock Markers keeps them in place; a drag then pans the map.
- **Private locations.** A photo inside one is exported without its location, as if "Remove location info" were
on for it: no GPS and no place fields (sublocation, city, state, country) in rendered exports. An Original or
DNG export of such a photo is refused when the file itself carries GPS or place names, as with Remove location
info. The photo keeps its position in the library. The Info panel shows no map for it (so no tiles of the
place are fetched) until you click Show Map. The Map view asks the same: while its centre is inside a private
location (after Show in Map, Fit to Photos, or panning there) it draws no tiles and fetches none, in the
navigator's overview map either, and says "In private location" with Show Map; panning the centre out of the
location, or Show Map, ends that (asked once per location until another library is opened). Pins and
circles are your own data and are still drawn. A wide view whose centre is outside the location can still
include it; use the offline map style (Settings › Map) to keep the Map view off the network.
- **Where they are kept.** In `locations.json` in the library folder, written atomically on every change, outside
the catalog's journal: they are not undo steps. The file is hostile input: one that doesn't parse is kept aside
as `locations.json.corrupt-<time>` with a warning and the library opens without locations; entries that aren't
valid (NaN, out of range, an empty name, a duplicate id, past 10,000) are left out one by one after the file is
kept aside. A file that can't be read is never overwritten in that session.
- **Older libraries.** Builds of this branch before kept saved locations in `prefs.json` (`savedLocations`). On
first open they are written to `locations.json`, read back to confirm, and only then left out of `prefs.json`
(from its next save). Until confirmed, and when `locations.json` is damaged, `prefs.json` keeps them. Their ids
become numbers.
The rule editor and smart albums also have **GPS Radius** (`gpsRadius`, Location group): is inside / is outside
`{lat, lon, radius}` (degrees, metres).
| Command | Params | Result |
|---|---|---|
| `map.locations` | — | `{locations: [{id, name, lat, lon, radius, private, photos, inView}], count, countMs}` (`photos`: library photos inside; `inView`: of the photos in view) |
| `map.location.add` | `{name, lat, lon, radius?, private?}` or `{name, fromSelection: true, ids?, radius?, private?}` | The new location with its counts |
| `map.location.update` | `{id, name?, lat?, lon?, radius?, private?}` | Checked as a whole: nothing changes when any part is refused |
| `map.location.remove` | `{id}` | `{removed, name, deleted}`; the photos keep their positions |
| `map.location.photos` | `{id, inView?}` | `{id, ids, count}` |
| `map.location.show` / `map.location.select` / `map.location.new` | `{id}` / `{id}` / `{name?}` | Go to a location / select its photos in view / a new one at the map's centre or around the selection (app only) |
`map.savedLocations.list`, `.create` and `.delete` are the older names of `map.locations`, `map.location.add` and
`map.location.remove` (ids are numbers now). `map.state` reports `locations` (each drawn: `{id, x, y, radiusPx,
active}`), `activeLocation` and `locationDrag`. Widgets: `map:location:new`, `map:location:<id>`,
`map:location:check:<id>`, `map:location:menu:<goto|select|rename|private|delete>`, `map:location:confirmDelete`,
`button:showPrivateMap`, and the Map view's `map:privateNote` and `button:showPrivateMapView`.
The list stays in the navigator panel of this branch's Map view rather than over the map's top-left corner.
## Track logs
A GPS track log (GPX) can be shown on the map and used to place the selected photos by their capture time, as
Lightroom Classic's Map ▸ Tracklog does.
- **Load.** The Tracklog button in the map's bottom toolbar ▸ Load Tracklog… picks a `.gpx` file. It is read on a
worker thread, with a "Loading tracklog <file>" row on the activity stack, so a large file never freezes the
window; the map fits the log when it lands. A file that isn't GPX, has no tracks or no timed points, is larger
than 50 MB or has more than 2 million timed points (or 10,000 tracks) is refused with a message, and the log
loaded before stays. The log is for the session only: it isn't saved with the library.
- **Drawing.** Each track's segments are projected once when it loads. Every point gets a Douglas–Peucker rank, so
the line for a zoom keeps the points above that zoom's tolerance (about 0.6 points of error; the ends are always
kept), built once per zoom in chunks that are clipped to the view. Lines are cut where they cross ±180° and
never drawn across a gap between segments. Measured on a synthetic 2-million-point track in a release build:
370 ms to build, 1–29 ms per zoom level, under 1 ms per frame of clipped lines.
- **The menu** lists the tracks (up to 40; `map.trackLog {active}` picks any), each with its point count: picking
one makes it the active one (drawn on top, the others dimmed) and the one Auto-Tag uses; All Tracks uses every
one. It shows the active track's start, end and duration on the camera's clock, Set Time Zone Offset… (the
camera's offset from UTC, as `+02:00`; asked for when Auto-Tag runs without one), Auto-Tag N Selected Photos
(hovering it says how many fall within the track's time), Fit Map to Tracklog, Load Another Tracklog… and Clear
Tracklog.
- **Before tagging**, the selected photos (up to 5,000) are marked as white dots where their capture times fall on
the track, so a wrong offset shows before anything is written.
- **Auto-Tag** sets the selected photos' positions from the active track by capture time (interpolated between
points of a segment, else the nearest point within 10 minutes; never across a segment break), in one undo step,
leaving photos that already have a position alone. It is `photo.autoTagTracklog {loaded: true}`.
| Command | Params | Result |
|---|---|---|
| `map.trackLog` | `{path?, gpx?, active?: index or "all", offset?: "+02:00" or hours or null, clear?: true (alone)}`; `{}` reports | Load (synchronously), pick the track, set the offset or clear → `{loaded, path, name, points, untimed, tracks: [{index, name, points, segments, start, end, duration}], active, activePoints, start, end, duration, offset, startLocal, endLocal, loadMs, generation}` |
| `photo.autoTagTracklog` | `{loaded: true, ids?, offset?, maxGap?, replace?, dryRun?}` (or `{path}` / `{gpx}` as before) | Tag from the Map view's log |
| `map.loadTrackLog` | `{path?}` (without it, a file dialog) | Read a log on a worker thread (app only) → `{loading: path}` |
| `map.trackLog.autoTag` / `.setOffset` / `.fit` | `{offset?}` / `{offset?}` / — | The menu's Auto-Tag, Set Time Zone Offset… and Fit Map to Tracklog (app only) |
`map.state` → `trackLog` adds `loading` (the file being read), `drawn` (lines, points handed to the painter, the
level's points, zoom, `levelMs`, `clipMs`), `ticks` (the marks on screen) and `onTrack`. Widgets: `map:tracklog`,
`map:tracklog:<load|info|offset|autoTag|fit|clear|name>`, `map:tracklog:track:<index|all>`.
The track maths, the loader and the menu are ported from PR #916 (Jason Baldwin); the GPX parser's track indexes,
names and caps are in the shared craft-metadata library this repository already uses.
## Keys and menus
In the Map view (and only there; elsewhere the keys keep their meaning, see `docs/library-shortcuts.md`):
| Key | Action |
|---|---|
| ⌘K / Ctrl+K | Lock Markers on / off |
| `\` | Location filter bar shown / hidden |
| `H` | Photo pins hidden / shown (Hide Pins) |
| `O` | Saved locations list (the navigator panel) shown / hidden |
| `=` / `-`, ⌘= / ⌘- | Zoom the map in / out |
| ⌘0 | Fit to Photos |
**By keyboard.** Tab reaches the pins; with a pin (or group) focused, the arrow keys move to the nearest pin in
that direction, Return or Space selects its photos (⌘/Ctrl+Return adds them to the selection) and its preview
shows, as on hover; the other Map keys keep working. Screen readers hear each pin as a button ("Photo pin" or
"Group of 3 photos, 1 selected") that their Click action selects.
**Hide Pins** (`H`, the bottom toolbar, `map.showPins {on?}`) hides the photo pins: hidden, they can't be clicked,
hovered or dragged. Saved locations and the track log stay. The choice is saved with the window state (`ui.json`).
**Window ▸ Map** gathers the map's commands, greyed outside the Map view: Fit to Photos, Zoom In / Out on Map, Map
Pins, Lock Markers, Location Filter Bar, Location Filter ▸ (Visible On Map, Tagged, Untagged, None), Saved
Locations ▸ (New Location…, Saved Locations List), Tracklog ▸ (Load Tracklog…, Auto-Tag Photos from Map Tracklog,
Set Time Zone Offset…, Fit Map to Tracklog, Clear Tracklog) and Map Tiles…. Window ▸ Map keeps the panel toggles
(Map View, Map Navigator, Location Filter Bar, Map Legend, Lock Map Markers).
**Settings ▸ Map** (Map Tiles…, `map.settings`): the tile source (each built-in one usable now, the Esri styles only
with a key; Offline), or a custom tile server (URL template, attribution, max zoom) applied with Apply or Return,
never while typing. A server that is refused (not `https://`, a missing placeholder, no credit, a bad max zoom) shows
why, and nothing changes. Then the tile cache's size with Delete Cached Tiles, what a tile server sees, a link to this page,
and the ArcGIS API key. The map's offline note ("Map tiles are off (Settings › Map)") points there.
| Command | Params | Result |
|---|---|---|
| `map.showPins` | `{on?}` | Hide Pins off / on (toggles without `on`) → `{on}` (app only) |
| `map.showLocations` | `{on?}` | The saved locations list (navigator panel) → `{on}` (app only) |
| `map.settings` | — | Opens Settings ▸ Map (app only) |
`map.state` also reports `showPins` and `showLocations`. Widgets: `map:hidePins`, `settings:mapSource:<id>`,
`settings:mapSource:custom`, `field:mapTemplate`, `field:mapAttribution`, `field:mapMaxZoom`, `button:mapCustomApply`,
`settings:mapError`, `settings:mapCacheSize`, `button:mapClearCache`, `link:mapDocs`.
## 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. A custom source that points at OpenStreetMap's own
tile servers (`tile.openstreetmap.org`, whatever its id) is the OpenStreetMap source, with its credit and
zoom 19: another credit, or a higher zoom, is refused.
**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, `<exe dir>/LightCraftData/Cache/maptiles` in portable mode, or
`$LIGHTCRAFT_MAP_CACHE` when set. Each source has its own subfolder. Clearing and trimming the cache only
delete files named as LightCraft names its tiles (`<source>/<z>/<x>/<y>.tile`, with numeric `z`, `x` and
`y`, and their temporary files); point `$LIGHTCRAFT_MAP_CACHE` at a folder of its own. 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
(<https://operations.osmfoundation.org/policies/tiles/>, 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/<version> (+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 (your own ArcGIS key)
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.
**Setting it up.** Create a free ArcGIS Location Platform account at <https://location.arcgis.com>, 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.
**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/<z>/<x>/<y>.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/<style>/static/tile/{z}/{y}/{x}?token=<key>`
(read 2026-11-15: <https://developers.arcgis.com/rest/static-basemap-tiles/>,
<https://developers.arcgis.com/rest/static-basemap-tiles/arcgis-streets-tile-get/>). Its tiles are 512 px PNGs on
the same grid as a 256 px pyramid one level down ("zoom levels are 1 less"), so LightCraft fetches the 512 px
tile once and cuts the four 256 px tiles it holds out of it; at zoom 0 it scales the world tile down. The same
fetch queue as for OpenStreetMap applies (two requests at a time, backoff, cache with the server's
`Cache-Control`). The keyless `services.arcgisonline.com` / `server.arcgisonline.com` endpoints are not used:
Esri's terms summary (<https://www.esri.com/content/dam/arcgisonline/docs/tou_summary.pdf>, April 21, 2025)
allows them only with Esri software or an ArcGIS subscription.
**No imagery.** The static tiles service has no satellite imagery style (only `arcgis/imagery/labels`, a
labels overlay), and Esri's `arcgis/topographic` and `arcgis/imagery` styles exist only as vector styles, which
this renderer can't draw. Earlier builds of this branch offered World Imagery and World Topographic Map from the
keyless endpoints; a library saved with World Imagery opens on OpenStreetMap (its saved value can't be read
any more). Outdoor is Esri's raster topographic style.
**Credit.** While an Esri style is shown the map's credit is "Powered by Esri" followed by the style's data
credits, taken from the style's metadata (`…/arcgis/<style>/static?f=json`, its `copyrightText`), fetched once
per style with the key. The answer is checked: at most 64 KiB, JSON, one line of plain text of at most 400
characters, no markup. Until it arrives, or when it fails, the credit is the providers the service's
documentation lists: "Powered by Esri | Esri, TomTom, Garmin, FAO, NOAA, USGS, © OpenStreetMap contributors,
and the GIS User Community". The service's page says: "Applications that use this service must display both
basemap and data attribution."
**Terms: what was checked and what wasn't.** Read on 2026-11-15: the static tiles pages above (tile URL, 512
px PNG, zoom 0–22, `token` parameter, the privilege, "2 million free then $0.15 per 1,000 tiles", metadata
calls free) and <https://developers.arcgis.com/documentation/security-and-authentication/api-key-authentication/>
(API keys "are typically embedded directly into client applications", usage "is billed to the ArcGIS
subscription … associated with the developer's account who created the key"). Not verified, because the pages
were not readable: Esri's attribution guide (<https://developers.arcgis.com/documentation/esri-and-data-attribution/>
returned an empty page) and the ArcGIS Location Platform Agreement
(<https://www.esri.com/content/dam/esrisites/en-us/media/legal/platform/platform-legal.pdf>), so whether its
terms limit keeping tiles in a local cache is not confirmed. Your key, your account: read those terms before
use.
**Custom templates.** A custom tile source (`map.tileSource {urlTemplate, attribution}`) may carry your own
key in its URL, for any provider, on your own responsibility. It is stored as you typed it in `prefs.json`
(it is the source's URL), and it stays checked: `https://` only, `{z}`, `{x}` and `{y}` each once, at most
512 characters.
**Other keyless providers (checked, none added).** CARTO's free basemaps are for non-commercial use only;
OpenFreeMap serves vector tiles only, which this renderer can't draw. OpenStreetMap stays the default and
OpenTopoMap the other keyless choice.
## 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" \| "esri-streets" \| "esri-topo" \| "offline"}`, `{offline: true \| false}`, or `{urlTemplate, attribution, maxZoom?, id?}` sets it (saved in `prefs.json`); the Esri styles need a key → `{…, esriKeySet}` |
| `map.setEsriKey` | `{key}`: sets your ArcGIS API key (`""` or null removes it); shape-checked only, never journaled or reported → `{esriKeySet, notice}` |
| `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), counts, a pin move or a drop in progress (app only; see Map view) |
| `map.fit` | Fit the view to the photos with a position (app only) |
| `map.setView` | `{lat?, lon?, zoom?}`: centre and zoom; lat −90…90 (shown within ±85.05°), lon wrapped, zoom 0…24 shown within the source's own range (`zoom: 22` on OpenStreetMap shows 19); anything else is refused (app only) |
| `map.zoomIn` / `map.zoomOut` | One zoom level in / out (app only) |
| `map.lockMarkers` | `{on?}`: Lock Markers on / off, toggles without `on` (app only) |
| `map.locationFilter` | `{mode?}`: the location filter (visible, tagged, untagged, none) and its counts (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.removeGps` | `{ids?}`: removes the position of the photos (default: the selection), one undo step; unknown ids are refused; `photo.clearGps` is its older name |
The tile core (Web Mercator maths, source checks, cache, fetch queue) and the pin clustering are ported
from PR #797, and the pin moves, Lock Markers, Remove GPS Coordinates and the sidecar GPS rule from PR #810,
both by Jason Baldwin.
+24 -12
View File
@@ -51,16 +51,16 @@ every PR would edit and conflict on. A row marked ✅ that is wrong or incomplet
| R. Video (VID) | 0 | 0 | 5 | 1 | — | 0/2 (0%) |
| S. Export (EXP) | 14 | 5 | 0 | 0 | 7/7 (100%) | 6/7 (86%) |
| T. Share (SHARE) | 0 | 0 | 0 | 4 | — | — |
| U. Map & location (MAP) | 0 | 1 | 1 | 0 | — | 0/1 (0%) |
| U. Map & location (MAP) | 1 | 1 | 0 | 0 | — | 1/1 (100%) |
| V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) |
| W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — |
| X. Cross-cutting behaviours (BEHAV) | 22 | 8 | 1 | 1 | 7/8 (88%) | 7/10 (70%) |
| Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) |
| Y. Menus | 86 | 1 | 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** | 417 | 74 | 56 | 35 | 192/203 (95%) | 146/163 (90%) |
| Lightroom Classic extras | 45 | 26 | 17 | 8 | — | 24/27 (89%) |
| **Total** | 423 | 75 | 51 | 35 | 192/203 (95%) | 147/163 (90%) |
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.0%** of 547 in-scope rows — P0 97.3% of 203 · P1 93.9% of 163 · P2 56.9% of 180.
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.9%** of 549 in-scope rows — P0 97.3% of 203 · P1 94.2% of 163 · P2 59.6% of 182.
<!-- /parity:summary -->
## Top gaps and shortcut notes
@@ -429,8 +429,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| Id | Feature | Tier | Status | Evidence | Missing / notes |
|---|---|---|---|---|---|
| LR-MAP-INFO | Location in the info panel | P1 | 🟡 | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `crates/ui-egui/src/panels/right.rs` | location, city, state/province, country and GPS editable; Show on Map (OpenStreetMap in the browser); no map in the panel |
| LR-MAP-MODULE | Map module [Classic] | P2 | ⬜ | | |
| LR-MAP-INFO | Location in the info panel | P1 | ✅ | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `cmd:map.state`, `crates/ui-egui/src/panels/right/info.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/tests/map_info.rs` | location, city, state/province, country and GPS editable; under them a map of the active photo's place (zoom 14, its pin, the tile credit; shares the Map view's tiles and textures; fetches only while on screen; grey with a note offline); a click opens the Map view centred there; Open in Browser shows the place on openstreetmap.org. Inside a private saved location (LRC-MAP-LOCATIONS) the map stays hidden, and none of its tiles are fetched, until Show Map (asked again in another private location; `crates/ui-egui/src/tests/map_locations.rs`) |
| LR-MAP-MODULE | Map module [Classic] | P2 | 🟡 | `cmd:view.map`, `cmd:map.state`, `cmd:map.settings`, `cmd:map.showPins`, `crates/engine/src/map.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/tests/map_keys.rs`, `docs/map.md` | A Map view (LRC-MAP-VIEW) with geotagging (LRC-MAP-GEOTAG), the location filter (LRC-MAP-FILTER), saved locations (LRC-MAP-LOCATIONS), track logs (LRC-MAP-TRACKLOG), the Info panel map (LR-MAP-INFO), the Map module's keys in the Map view (⌘K, `\`, H, O, = / −), Window ▸ Map and Settings ▸ Map (tile source, custom server, cache). Not yet: satellite / hybrid imagery without the user's own key (Esri needs one, and its keyed service has no imagery style), a place search, an offline basemap, the Map module's own panel layout |
## V. Preferences (PREF)
@@ -544,6 +544,7 @@ visible menu bar yet: the menu model is only exposed through the control channel
| MENU-VIEW-ENTERFULLSCREEN | Enter Full Screen | P1 | ✅ | `cmd:view.enterFullScreen` | |
| MENU-VIEW-PHOTOSPANEL | Show/Hide photos panel | P0 | ✅ | `cmd:view.leftPanel` | |
| MENU-VIEW-FILMSTRIP | Show/Hide filmstrip | P0 | ✅ | `cmd:view.filmstrip` | |
| MENU-VIEW-MAP | View ▸ Map submenu [Classic] | P2 | 🟡 | `cmd:map.fit`, `cmd:map.zoomIn`, `cmd:map.zoomOut`, `cmd:map.showPins`, `cmd:map.lockMarkers`, `cmd:map.locationFilter`, `cmd:map.location.new`, `cmd:map.showLocations`, `cmd:map.loadTrackLog`, `cmd:map.settings` | the Map view's commands gathered under Window ▸ Map (Lightroom Classic's Map module menus), greyed outside the Map view; not in View: that menu is at its 40-row limit |
| MENU-VIEW-INFO | Show/Hide info | P0 | ✅ | `cmd:panel.info` | |
| MENU-VIEW-KEYWORDS | Show/Hide keywords | P0 | ✅ | `cmd:panel.keywords` | |
| MENU-VIEW-ACTIVITY | Show/Hide activity (comments) | OOS | 🚫 | | our History panel is `panel.activity` |
@@ -578,6 +579,7 @@ visible menu bar yet: the menu model is only exposed through the control channel
| MENU-PHOTO-UPDATEAI | Update AI settings | P2 | ⬜ | | |
| MENU-PHOTO-RENAME | Rename N photos… | P1 | ✅ | `cmd:dialog.rename` | live “Rename N Photos…” label |
| MENU-PHOTO-CAPTURETIME | Edit capture time… | P1 | ✅ | `cmd:dialog.captureTime` | |
| MENU-PHOTO-REMOVEGPS | Remove GPS Coordinates [Classic] | P2 | ✅ | `cmd:photo.removeGps` | clears the selected photos' GPS position, one undo step; also on a map pin's right-click menu (LRC-MAP-GEOTAG) |
| MENU-PHOTO-COVER | Set as album cover | P2 | ✅ | `cmd:album.setCover` | |
| MENU-PHOTO-DELETE | Delete N photos… | P0 | ✅ | `cmd:photo.delete` | asks first (Settings ▸ General, on by default, #1239); static label |
| MENU-PHOTO-MOVETOCLOUD | Move/copy to cloud | OOS | 🚫 | | |
@@ -743,11 +745,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/lib.rs` | Photo ▸ Metadata ▸ 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.tileSource`, `cmd:map.cacheInfo`, `cmd:map.clearCache`, `cmd:map.setEsriKey`, `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:map.fit`, `cmd:map.setView`, `cmd:map.zoomIn`, `cmd:map.zoomOut`, `cmd:view.filmstrip`, `crates/geom/src/geo.rs`, `crates/engine/src/map.rs`, `crates/engine/src/map/service.rs`, `crates/engine/src/map/cluster.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); Esri Streets and Esri Outdoor with the user's own ArcGIS API key (Settings ▸ Map, `map.setEsriKey`; keyed static tiles service, credit from the style's metadata; no key: not offered, `docs/map.md`); credit always shown; missing tiles drawn from a parent tile; photos of the current list as pins, merged into counted clusters in world-anchored cells (about 60 pt; panning never regroups, zooming in splits; positions projected once per change of the list); hover shows the photo's thumbnail; double-click opens Detail or zooms into a cluster; Fit to Photos (also the first showing), `map.fit`, `map.setView`, `map.zoomIn`, `map.zoomOut`; "N photos without GPS"; 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; the location filter bar over the map (LRC-MAP-FILTER); bottom toolbar with Map Style list, Tracklog, Fit to Photos, zoom slider, Hide Pins and Lock Markers, the tile credit just above it; left navigator mini-map and saved locations list (LRC-MAP-LOCATIONS); the Map view's keys and Window ▸ Map (LR-MAP-MODULE); keyboard shortcut Ctrl+Alt+3 |
| LRC-MAP-GEOTAG | Drag photos onto the map | P2 | ✅ | `cmd:photo.setGps`, `cmd:photo.removeGps`, `cmd:photo.clearGps`, `cmd:map.lockMarkers`, `crates/engine/src/cmd/map.rs`, `crates/engine/src/sidecar.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/tests/map_filmstrip.rs`, `crates/ui-egui/src/tests/map_geotag.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. A drag that starts on a single photo's pin moves it (one undo step; let go outside the map, nothing changes); a cluster's drag pans, as in Lightroom Classic. Lock Markers (bottom toolbar, ⌘K / Ctrl+K in the Map view, `map.lockMarkers`, saved in `ui.json`) stops pins from moving. Photo ▸ Remove GPS Coordinates and a pin's right-click menu clear the position (`photo.removeGps`, one undo step). XMP sidecars: a position set or cleared in LightCraft replaces the sidecar's EXIF GPS, so a cleared one or an undone geotag is removed; other apps' sidecar GPS stays for photos never geotagged here. Drops reach ±85.05° latitude at most. No auto-pan near the map's edge, no Escape to cancel a drag, no OS file drops onto the map |
| LRC-MAP-LOCATIONS | Saved locations | P2 | ✅ | `cmd:map.locations`, `cmd:map.location.add`, `cmd:map.location.update`, `cmd:map.location.remove`, `cmd:map.location.photos`, `cmd:map.location.show`, `cmd:map.location.select`, `cmd:map.location.new`, `crates/engine/src/locations.rs`, `crates/ui-egui/src/panels/map/locations.rs`, `crates/engine/src/tests/saved_locations.rs`, `crates/ui-egui/src/tests/map_locations.rs` | Named circles (1 m–1000 km, great-circle, across ±180° and the poles) in the navigator panel's list with the photos in view inside each, a checkbox selecting them, Go To, Rename…, Private, Delete… with a confirmation; `+` around the selected photos or at the map's centre; circles with names on the map, the active one with centre and radius handles (Lock Markers keeps them). Kept per library in `locations.json` (atomic; damaged files and bad entries set aside; older `prefs.json` entries migrated once, confirmed before they leave `prefs.json`). Private locations: rendered exports of the photos inside drop GPS and place fields, Original/DNG refuse embedded GPS, the Info panel hides their map until Show Map. GPS Radius smart-rule field. The list is in the navigator panel, not over the map's corner |
| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `cmd:map.trackLog`, `cmd:map.loadTrackLog`, `cmd:map.trackLog.autoTag`, `cmd:map.trackLog.setOffset`, `cmd:map.trackLog.fit`, `crates/engine/src/tracklog.rs`, `crates/engine/src/map/track.rs`, `crates/ui-egui/src/panels/map/tracks.rs`, `crates/ui-egui/src/tests/map_tracks.rs` | Photo ▸ Auto-Tag from Tracklog…, and in the Map view the Tracklog menu: load a GPX (read on a worker thread with an activity row; fits the map), tracks drawn simplified per zoom (Douglas–Peucker ranks, chunks clipped to the view, cut at ±180°), pick the active track (others dimmed), start / end / duration on the camera clock, Set Time Zone Offset…, Auto-Tag N Selected Photos from the active track in one undo step, the selected photos marked on the track before tagging, Fit, Clear. Caps: 50 MB, 2 million timed points, 10,000 tracks; a refused file keeps the loaded one. Interpolated between the points of a segment, else the nearest point within `maxGap` (10 min); never across segment breaks. The log isn't saved with the library |
| LRC-MAP-FILTER | Location filter bar | P2 | ✅ | `cmd:map.locationFilter`, `cmd:library.filter`, `cmd:album.ruleFields`, `cmd:view.toggleMapFilter`, `crates/catalog/src/rules.rs`, `crates/engine/src/lib.rs`, `crates/ui-egui/src/panels/map.rs`, `crates/ui-egui/src/tests/map_filter.rs`, `crates/engine/src/tests/location.rs` | The bar over the map: Visible on Map, Tagged, Untagged, None, each with its count; it narrows the filmstrip (`Session::narrow`) over the library's filter, which it never changes; leaving the Map view restores the grid's list; Visible on Map follows the view once it rests (250 ms; commands at once), wrapping across ±180°; Untagged hides the pins and says photos can be dragged on. Smart-rule fields Has GPS (valid positions only) and GPS Area (`{south, west, north, east}`, inside / outside) in `library.filter`, smart albums and the rule editor. 50,000 photos narrow in 9 ms (release) |
| 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 | ⬜ | | |
@@ -808,6 +810,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| Date | Change | Summary |
|---|---|---|
| 2026-12-01 | patch | MENU-VIEW-MAP ✅ → 🟡: the Map view's commands moved from View ▸ Map to Window ▸ Map, beside the Map panel toggles, because View is at the 40-row menu limit; Map View (⌘⌥3) is there too |
| 2026-11-27 | minor | LR-IMP-ADD-DIALOG / LR-IMP-MOVE: an optional backup folder (Backup to, `library.import` `backup`) gets a verified copy of each copied or moved file under the same folders and names as the destination; a move keeps the original of a photo whose backup failed; counts unchanged |
| 2026-12-02 | minor | LR-MASK-BRUSH: a stroke's edge is feathered as one dab's is (process V16); status unchanged |
| 2026-11-24 | minor | LR-MASK-BRUSH: process V15 makes Flow coverage per brush radius travelled, as Lightroom Classic's strokes measure on a grey card, live and committed, CPU and GPU (`masks::travel_flow`; `flow_is_coverage_per_radius_travelled_as_in_lightroom`); a stroke no longer builds up more when painted slowly; status unchanged (🟡: no A/B brushes) |
@@ -816,6 +819,15 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-29 | minor | MENU-EDIT-SELECTBY: Edit → Select by lists each rating on its own (★ only … ★★★★★ only, `library.selectBy` with `ratingOp: eq`) after the "and higher" rows, beside Unrated (#3311); status unchanged (✅) |
| 2026-11-15 | patch | LR-PRE-AMOUNT: Amount blends tone curves, fades in the strength of a profile/LUT or switched-on group a preset changes, and takes white balance on another scale whole (#2669); the step at half amount for switches and choices stays (#2207); status unchanged (✅) |
| 2026-11-09 | minor | LR-PREF-LOCALSTORAGE: the low-disk notice warns under 20 GB free, no longer under 10 % of the drive (76 GB free of a 926 GB drive warned, #4013); status unchanged |
| 2026-11-16 | minor | LR-MAP-MODULE ⬜ → 🟡: the Map view's keys (⌘K, `\`, H, O, = / −, ⌘= / ⌘− / ⌘0 in the Map view only), Hide Pins (`map.showPins`), View ▸ Map (MENU-VIEW-MAP added), Settings ▸ Map tile source / custom server / cache (`map.settings`) |
| 2026-11-16 | patch | LRC-MAP-TRACKLOG: track logs drawn on the Map view (simplified per zoom, clipped, cut at ±180°) with the Tracklog menu (tracks, time range, offset, Auto-Tag from the active track, the selected photos marked on the track, fit, clear); loading off the UI thread with an activity row; `map.trackLog`; status unchanged (the row said ✅ already) |
| 2026-11-16 | patch | LRC-MAP-LOCATIONS: saved locations move to a per-library `locations.json` (migrated once from `prefs.json`), get counts, Go To, select, rename, private (exports drop the location; the Info map hides), confirmed delete, circles with draggable handles, `map.location.*` commands and a GPS Radius rule field; status unchanged (the row said ✅ already) |
| 2026-11-15 | patch | LRC-MAP-FILTER: the location filter bar now counts each choice and narrows the filmstrip (it only switched pins before); GPS Area and valid-only Has GPS smart-rule fields; status unchanged (the row said ✅ already) |
| 2026-11-15 | minor | LR-MAP-INFO 🟡 → ✅: the Info panel shows a map of the active photo's place under the location fields (shared tiles, fetched only while on screen, offline grey); a click opens the Map view there; Show on Map is now Open in Browser |
| 2026-11-15 | minor | LRC-MAP-GEOTAG 🟡 → ✅: a single photo's pin can be dragged to move it (a cluster's drag pans), Lock Markers (⌘K / Ctrl+K, `map.lockMarkers`, saved in `ui.json`) stops that, Photo ▸ Remove GPS Coordinates and a pin's menu clear the position (`photo.removeGps`), and a cleared or undone position leaves the XMP sidecar; MENU-PHOTO-REMOVEGPS added. LRC-MAP-VIEW: world-anchored clusters (no regrouping on pan), hover thumbnail, Fit to Photos (also the first showing), `map.fit` / `map.setView` / `map.zoomIn` / `map.zoomOut`, "N photos without GPS"; status unchanged |
| 2026-11-15 | patch | LRC-MAP-VIEW: the Esri styles (Streets, Outdoor) come back with the user's own ArcGIS Location Platform API key (Settings ▸ Map, `map.setEsriKey`; keyed static tiles service; credit from each style's metadata; the key never reported, logged, journaled or cached by); no keyless Esri endpoint; World Imagery dropped (no raster imagery style in the keyed service). Status unchanged |
| 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-23 | minor | LR-BEHAV-RENDER-FIDELITY, LR-EDIT-LIGHT-SHADOWS, LR-EDIT-EFFECTS-TEXTURE, LR-EDIT-COLOR-GRADING, LRC-DEV-PROCESS: process V13 eases global Shadows off at large amounts, negative Texture and the Global grading wheel act less, fitted to Lightroom exports of real edits (#523); statuses and counts unchanged |
| 2026-11-24 | minor | LR-REM-HEAL, LR-REM-CLONE, LRC-DEV-PROCESS: process V14 pins Heal and Remove spots to the photo on the spot's edge (membrane fill of the log ratio), matches the source's grain to its surroundings and reads every spot's source at whole pixels; statuses and counts unchanged |