diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 1169d9dbb3..907f4b7150 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -260,13 +260,12 @@ pub fn shortest_route( shortest_route_with(&NETWORK, ds, rows, from, to, cost_field, snap_m) } -/// [`shortest_route`] over `held`, a layer held in another system than longitude/latitude: the -/// graph is built from `lonlat`, the layer in longitude/latitude, only when the one kept isn't -/// for `held`'s rows as they are, and is kept under them. Later routes over the same layer then -/// reuse it without converting the layer again; the converted copy isn't kept. -pub fn shortest_route_held<'a>( +/// [`shortest_route`] over `held`, a layer held in another system than longitude/latitude. The +/// graph is built from `held`'s lines, each converted to longitude/latitude as it is read (no +/// converted copy of the layer is made), only when the one kept isn't for `held`'s rows as they +/// are, and is kept under them. Later routes over the same layer then reuse it. +pub fn shortest_route_held( held: &Dataset, - lonlat: impl FnOnce() -> Result, String>, rows: &[usize], from: Coord, to: Coord, @@ -274,7 +273,7 @@ pub fn shortest_route_held<'a>( snap_m: f64, ) -> Result { check_route_ends(from, to, snap_m)?; - let graph = network_keyed(&NETWORK, held, rows, cost_field, || Network::build(&*lonlat()?, rows, cost_field))?; + let graph = network_keyed(&NETWORK, held, rows, cost_field, || Network::build(held, rows, cost_field))?; route_on(&graph, held, from, to, snap_m) } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index a461f7dea8..c8aa777afb 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -548,6 +548,20 @@ impl Dataset { Self::geometry_to_lonlat_by(&self.shown_conversion()?, g) } + /// [`Dataset::geometry_to_lonlat`] of `g`, feature `id`'s geometry, for an edit of that one + /// feature: refused naming the layer and the feature when one of its places can't be given in + /// longitude/latitude, so it can't be edited there. + pub fn feature_to_lonlat<'a>(&self, id: u64, g: &'a Geometry) -> std::result::Result, String> { + let to = self.shown_conversion()?; + Self::converted_to_lonlat(&to, g).ok_or_else(|| { + format!( + "{}: feature {id} has a place in {} that can't be given in longitude/latitude, so it can't be edited there", + self.name, + to.source().label() + ) + }) + } + /// [`Dataset::geometry_to_lonlat`] by `to`, its [`Dataset::lonlat_conversion`] made once for /// many geometries: refused, naming its system, when one of the geometry's places can't be /// converted. diff --git a/crates/data/src/raster/planetary.rs b/crates/data/src/raster/planetary.rs index 7923c89ca6..e2ba984b23 100644 --- a/crates/data/src/raster/planetary.rs +++ b/crates/data/src/raster/planetary.rs @@ -38,7 +38,7 @@ pub fn off_earth(semi_major: f64) -> bool { /// `+ellps` or `+datum`, since PROJ's named ellipsoids are all the Earth's. pub fn proj4_axes(proj4: &str) -> Option<(f64, f64)> { let value = |key: &str| { - proj4.split_whitespace().take(64).find_map(|t| t.strip_prefix(key)).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()) + proj4.split_whitespace().find_map(|t| t.strip_prefix(key)).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()) }; let a = value("+a=").or_else(|| value("+R=")).filter(|a| *a > 0.0)?; let b = match (value("+b="), value("+rf=")) { @@ -379,6 +379,9 @@ mod tests { assert_eq!(proj4_axes("+proj=longlat +ellps=WGS84 +no_defs"), None); assert_eq!(proj4_axes("+proj=longlat +a=x +no_defs"), None); assert_eq!(proj4_axes("+proj=longlat +a=-5 +no_defs"), None); + // A radius written after many other parameters still counts: the whole definition is read. + let padding = (0..80).map(|i| format!("+x{i}=0")).collect::>().join(" "); + assert_eq!(proj4_axes(&format!("+proj=longlat {padding} +a=3396190 +no_defs")), Some((3_396_190.0, 3_396_190.0))); assert_eq!(proj4_axes(""), None); } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 2405eeefd0..3034ab4563 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -141,13 +141,53 @@ fn coerce(v: &Attr, ty: FieldType) -> (Attr, Cut) { } fn paste(s: &mut Session, p: &Value) -> CmdResult { - let (src, said) = clip(s, p)?; + let (mut src, said) = clip(s, p)?; let id = s.layer_id(p)?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; if l.is_raster() { return Err("features can't be pasted into a raster layer".into()); } let want = l.geometry_type(); + // The shapes the layer takes, written in its own coordinates from the system the clipboard + // holds them in: as they are in a layer of that system (pasted where they were copied from, + // nothing moves), else converted by the operation between the two, which doesn't depend on + // the map. All converted before anything changes; one with a place the layer's system can't + // hold is left out, counted and said, rather than the paste refused. + let (from, own) = (src.coord_crs(), l.dataset.coord_crs()); + // Into Web Mercator by way of longitude/latitude, where the latitudes it can't hold are found. + let steps = if from == own { + vec![] + } else if own == Crs::WebMercator && from != Crs::LonLat { + vec![from.to(Crs::LonLat)?, Crs::LonLat.to(own)?] + } else { + vec![from.to(own)?] + }; + let mut placed = Vec::with_capacity(src.features.len()); + if !steps.is_empty() { + let none = rustgis_data::HeldPlaces::default(); + for r in 0..src.features.len() { + let fits = src.features.row(r).and_then(|x| x.geometry()).is_some_and(|g| want == GeometryType::None || g.kind() == want); + let Some(Some(g)) = fits.then(|| src.features.set_geometry(r, None)).flatten() else { + placed.push(true); + continue; + }; + match steps.iter().try_fold(g, |g, to| Dataset::edit_from_lonlat_by(to, g, &none)) { + Ok(g) => { + src.features.set_geometry(r, Some(g)); + placed.push(true); + } + Err(_) => placed.push(false), + } + } + } + let unplaced = placed.iter().filter(|p| !**p).count(); + if unplaced > 0 { + let mut keep = placed.into_iter(); + src.features.retain_rows(|_| keep.next().unwrap_or(true)); + if src.features.is_empty() { + return Err(format!("Paste: the copied feature(s) have a place {} ({}) can't hold", l.name, own.label())); + } + } // Ids for every feature the layer takes (one of another shape is left out below), above every id // it has or keeps new rows above, refused before anything changes when they would run past the // largest id. @@ -184,30 +224,11 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { // Per field, what converting the pasted values cut, and the values that aren't null but that // the field can't hold. let mut unfit = vec![(Cuts::default(), 0usize); l.dataset.fields.len()]; - // The features the layer takes, their shapes written in its own coordinates from the system - // the clipboard holds them in: as they are in a layer of that system (pasted where they were - // copied from, nothing moves), else converted by the operation between the two, which - // doesn't depend on the map. All converted before any is added. - let (from, own) = (src.coord_crs(), l.dataset.coord_crs()); - let mut taken: Vec = src + let taken: Vec = src .features .into_iter() .filter(|ft| !ft.geometry.as_ref().is_some_and(|g| want != GeometryType::None && g.kind() != want)) .collect(); - // Into Web Mercator by way of longitude/latitude, where the latitudes it can't hold are found. - let steps = if from == own { - vec![] - } else if own == Crs::WebMercator && from != Crs::LonLat { - vec![from.to(Crs::LonLat)?, Crs::LonLat.to(own)?] - } else { - vec![from.to(own)?] - }; - let none = rustgis_data::HeldPlaces::default(); - for ft in &mut taken { - for to in &steps { - ft.geometry = ft.geometry.take().map(|g| Dataset::edit_from_lonlat_by(to, g, &none)).transpose()?; - } - } for ft in taken { next = next.saturating_add(1); let attrs = l @@ -234,6 +255,14 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { let name = l.name.clone(); let features = |n: usize| if n == 1 { "1 feature".to_string() } else { format!("{n} features") }; let mut notices = Vec::new(); + if unplaced > 0 { + let (have, they) = if unplaced == 1 { ("has", "it wasn't") } else { ("have", "they weren't") }; + notices.push(format!( + "Paste: {} {have} a place that layer {name} ({}) can't hold, so {they} pasted", + features(unplaced), + own.label() + )); + } for (f, (cuts, n)) in l.dataset.fields.iter().zip(unfit) { notices.extend(cuts.notices("Paste", &f.name)); if n > 0 { diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 50a62dddc2..68b5c3a3ce 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -502,12 +502,14 @@ pub fn commands() -> Vec { // vertex with it, move on the ground (#1033), or for a move of no distance stay as // they are. let mut shifted: HashMap<(u32, usize), Geometry> = HashMap::new(); - for l in s.map().layers.iter().filter(|l| !l.is_raster()) { + for l in s.map().layers.iter().filter(|l| !l.is_raster() && !l.selection.is_empty()) { + let to = l.dataset.shown_conversion()?; for r in &l.selection { // Moved in longitude/latitude, from the layer's own coordinates (`modify` writes - // it back in them). + // it back in them). A feature with a place that can't be given there stays + // as it is (`modify` counts it). let Some(own) = l.dataset.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; - let g = l.dataset.geometry_to_lonlat(own)?; + let Some(g) = rustgis_data::Dataset::converted_to_lonlat(&to, own) else { continue }; if !within_square(&g) { continue; } @@ -591,7 +593,8 @@ pub fn commands() -> Vec { .when(need_editable_selection) .params(r#"{"factor": number}"#), C::new("edit.flip", "Flip Line", "Edit › Features › Modify", |s, _| { - modify(s, |_, g| match g { + // Only the vertices' order changes, so in the layer's own coordinates, as stored. + modify_in(s, Space::Own, |_, g| match g { Geometry::Line(parts) => Ok(Some(Geometry::Line(parts.iter().rev().map(|p| p.iter().rev().copied().collect()).collect()))), _ => Ok(None), }) @@ -890,10 +893,14 @@ fn move_planes( ) -> Result<(HashMap<(u32, usize), Coord>, usize, usize), String> { // In longitude/latitude, from each layer's own coordinates. let mut selected: Vec<((u32, usize), std::borrow::Cow<'_, Geometry>)> = Vec::new(); - for l in s.map().layers.iter().filter(|l| !l.is_raster()) { + // A feature with a place that can't be given there isn't moved ([`modify`] counts it). + for l in s.map().layers.iter().filter(|l| !l.is_raster() && !l.selection.is_empty()) { + let to = l.dataset.shown_conversion()?; for r in &l.selection { let Some(g) = l.dataset.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; - selected.push(((l.id, *r), l.dataset.geometry_to_lonlat(g)?)); + if let Some(g) = rustgis_data::Dataset::converted_to_lonlat(&to, g) { + selected.push(((l.id, *r), g)); + } } } // Most moves stay within the square: then no feature needs grouping. @@ -1129,29 +1136,69 @@ fn move_features(s: &mut Session, mut change: impl FnMut((u32, usize), &Geometry Ok(done) } -/// Applies a geometry change to every selected feature of every layer (in the selection's layers). -fn modify(s: &mut Session, mut change: impl FnMut((u32, usize), &Geometry) -> Result, String>) -> CmdResult { +/// Applies a geometry change to every selected feature of every layer (in the selection's layers), +/// in longitude/latitude ([`Space::LonLat`]). A feature with a place that can't be given there is +/// left as it is, and said with a count per layer; when every changeable feature is such a +/// feature, the edit is refused saying why. +fn modify(s: &mut Session, change: impl FnMut((u32, usize), &Geometry) -> Result, String>) -> CmdResult { + modify_in(s, Space::LonLat, change) +} + +/// Where [`modify_in`] gives each geometry to a change. +#[derive(Clone, Copy, PartialEq)] +enum Space { + /// In longitude/latitude, written back in the layer's own coordinates, keeping what the + /// change left as stored. + LonLat, + /// In the layer's own coordinates, as stored: for a change that only reorders vertices (a + /// flip), so a feature with a place that can't be given in longitude/latitude changes too. + Own, +} + +fn modify_in( + s: &mut Session, + space: Space, + mut change: impl FnMut((u32, usize), &Geometry) -> Result, String>, +) -> CmdResult { let mut n = 0; + let mut unplaced: Vec<(String, usize)> = Vec::new(); let ids: Vec = s.map().layers.iter().filter(|l| !l.selection.is_empty() && !l.is_raster()).map(|l| l.id).collect(); for id in ids { let mut changes = Vec::new(); - let selection = s.map().layer(id).ok_or("no such layer")?.selection.clone(); + let l = s.map().layer(id).ok_or("no such layer")?; + let selection = l.selection.clone(); + let to = match space { + Space::LonLat => Some(l.dataset.shown_conversion()?), + Space::Own => None, + }; + let mut left = 0usize; for r in selection { // Read first, writing only a row that changes: the first write copies the layer's rows // when Undo shares them, and frees history set aside for that copy (#2431). - // Changed in longitude/latitude, and written back in the layer's own coordinates, - // keeping what the change left as stored. let l = s.map().layer(id).ok_or("no such layer")?; let Some(f) = l.dataset.features.get(r) else { continue }; let Some(own) = f.geometry.as_ref() else { continue }; - let lonlat = l.dataset.geometry_to_lonlat(own)?; - let Some(g) = change((id, r), &lonlat)? else { continue }; - super::edit::validate(&g)?; - // A change of the whole shape (a move, a rotation) has no place of its own to snap: - // only the feature's own places are held, with no search of other features. - let mut held = rustgis_data::HeldPlaces::default(); - l.dataset.hold_places(own, None, &mut held); - let g = l.dataset.edit_from_lonlat(g, &held)?; + let g = match &to { + Some(to) => { + let Some(lonlat) = rustgis_data::Dataset::converted_to_lonlat(to, own) else { + left += 1; + continue; + }; + let Some(g) = change((id, r), &lonlat)? else { continue }; + super::edit::validate(&g)?; + // A change of the whole shape (a move, a rotation) has no place of its own to + // snap: only the feature's own places are held, with no search of other + // features. + let mut held = rustgis_data::HeldPlaces::default(); + l.dataset.hold_places(own, None, &mut held); + l.dataset.edit_from_lonlat(g, &held)? + } + None => { + let Some(g) = change((id, r), own)? else { continue }; + super::edit::validate(&g)?; + g + } + }; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; let Some(f) = l.dataset.features.get_mut(r) else { continue }; let before = f.clone(); @@ -1159,15 +1206,32 @@ fn modify(s: &mut Session, mut change: impl FnMut((u32, usize), &Geometry) -> Re changes.push(Change { before: Some(before), row: Some(r) }); n += 1; } + if left > 0 { + unplaced.push((s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(), left)); + } s.map_mut().layer_mut(id).ok_or("no such layer")?.touch_geometry(); apply(s, id, changes)?; } + if n == 0 && !unplaced.is_empty() { + return Err(format!("{}, so nothing selected can be changed this way", unplaced_said(&unplaced))); + } if n == 0 { return Err("nothing selected can be changed this way".into()); } + if !unplaced.is_empty() { + s.warn(format!("{}, so they were left as they were", unplaced_said(&unplaced))); + } Ok(json!({"modified": n})) } +/// "n feature(s) of 'a' (k), 'b' (m) have a place that can't be given in longitude/latitude": +/// the features an edit in longitude/latitude leaves out, by layer. +pub(crate) fn unplaced_said(by_layer: &[(String, usize)]) -> String { + let n: usize = by_layer.iter().map(|(_, k)| k).sum(); + let layers = by_layer.iter().map(|(name, k)| format!("'{name}' ({k})")).collect::>().join(", "); + format!("{n} feature(s) of {layers} have a place that can't be given in longitude/latitude") +} + fn set_geometry(s: &mut Session, p: &Json) -> CmdResult { let id = s.layer_id(p)?; let row = p.get("row").and_then(Json::as_u64).ok_or("row is required")? as usize; @@ -1198,8 +1262,9 @@ fn edit_vertex(s: &mut Session, p: &Json) -> CmdResult { }; // In longitude/latitude, from the layer's own coordinates (`replace_geometry` writes it back). let l = s.map().layer(id).ok_or("no such row")?; - let own = l.dataset.features.get(row).ok_or("no such row")?.geometry.as_ref().ok_or("the feature has no shape")?; - let g = l.dataset.geometry_to_lonlat(own)?.into_owned(); + let feature = l.dataset.features.row(row).ok_or("no such row")?; + let own = feature.geometry().ok_or("the feature has no shape")?; + let g = l.dataset.feature_to_lonlat(feature.id(), own)?.into_owned(); let (g, v) = match ps(p, "action").ok_or("action is required")? { "move" => (g.move_vertex(v, at()?).ok_or("no such vertex")?, v), "insert" => { @@ -1313,9 +1378,13 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult { } // Merged in longitude/latitude, from the layer's own coordinates, and written back in them, the // places it keeps as stored. - let originals: Vec<&Geometry> = sel.iter().filter_map(|r| l.dataset.features.get(*r)?.geometry.as_ref()).collect(); + // A feature with a place that can't be given there refuses the merge, naming it: the merged + // shape would lose that place. + let with_ids: Vec<(u64, &Geometry)> = + sel.iter().filter_map(|r| l.dataset.features.row(*r)).filter_map(|f| Some((f.id(), f.geometry()?))).collect(); + let originals: Vec<&Geometry> = with_ids.iter().map(|(_, g)| *g).collect(); let geoms: Vec = - originals.iter().map(|g| l.dataset.geometry_to_lonlat(g).map(std::borrow::Cow::into_owned)).collect::>()?; + with_ids.iter().map(|(fid, g)| l.dataset.feature_to_lonlat(*fid, g).map(std::borrow::Cow::into_owned)).collect::>()?; let kind = |g: &Geometry| match g { Geometry::Point(_) | Geometry::MultiPoint(_) => 0, Geometry::Line(_) => 1, @@ -1397,10 +1466,13 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { // written back in them. // Only lines are split, so only they are converted: another feature selected with them // doesn't refuse the split. + // A line with a place that can't be given there isn't split; it is counted and said. + let to = l.dataset.shown_conversion()?; let mut beyond_pole = false; for feat in l.selection.iter().filter_map(|r| l.dataset.features.get(*r)) { if let Some(g @ Geometry::Line(_)) = &feat.geometry - && let Geometry::Line(parts) = &*l.dataset.geometry_to_lonlat(g)? + && let Some(lonlat) = rustgis_data::Dataset::converted_to_lonlat(&to, g) + && let Geometry::Line(parts) = &*lonlat { beyond_pole |= parts.iter().flatten().any(|c| c.is_finite() && c.y.abs() > 90.0); } @@ -1414,10 +1486,14 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { // split at the nearest point it found, or left whole when that was an end. let (mut rough, mut whole) = (0, 0); let mut unmeasured = 0usize; + let mut unplaced = 0usize; for r in l.selection.clone() { let Some(f) = l.dataset.features.get(r).cloned() else { continue }; let Some(own @ Geometry::Line(_)) = &f.geometry else { continue }; - let lonlat = l.dataset.geometry_to_lonlat(own)?; + let Some(lonlat) = rustgis_data::Dataset::converted_to_lonlat(&to, own) else { + unplaced += 1; + continue; + }; let Geometry::Line(parts) = &*lonlat else { continue }; steps.floor = f64::INFINITY; // The nearest segment of the nearest part, in the analysis plane (Web Mercator within @@ -1532,7 +1608,11 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { } let unsearched = |n: usize| format!("{n} line(s) near a pole couldn't be searched in full within one split's limit of a million distances"); + let unplaced_lines = (unplaced > 0).then(|| unplaced_said(&[(l.name.clone(), unplaced)])); if changes.is_empty() { + if let Some(said) = unplaced_lines { + return Err(format!("{said}, so they can't be split; no other selected line was split away from its ends")); + } if unmeasured > 0 { return Err(format!( "no line could be split away from its ends; {unmeasured} segment(s) could not be measured because of invalid coordinates" @@ -1545,6 +1625,9 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { } l.touch_geometry(); apply(s, id, changes)?; + if let Some(said) = unplaced_lines { + s.warn(format!("{said}, so they weren't split")); + } if unmeasured > 0 { s.warn(format!("{unmeasured} segment(s) of the selected lines could not be measured because of invalid coordinates; the split search skipped them, so the point found may not be the nearest")); } @@ -2418,6 +2501,12 @@ struct TopologyChecked { /// and covering layers whose edges bend by their conversion into it (how many, how far). fell_back: Vec, bent: Vec<(String, usize, f64)>, + /// Rules checked in longitude/latitude that left out features with a place that can't be + /// given there: "{rule} on '{layer}': n feature(s) of '{layer}'", said once. + unplaced: Vec, + /// Issues found in a layer's own system at a place that can't be given in longitude/latitude: + /// kept, with no place to zoom to (NaN). + unlocated: usize, } /// Checks each rule and its query on the worker, with Cancel between rows/rules and counted @@ -2437,6 +2526,7 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result Result (crs, std::borrow::Cow::Borrowed(&i.data), by), - None => ( - rustgis_data::raster::Crs::LonLat, - i.data.in_lonlat().map_err(|e| named(&i.data.name, &i.layer, e))?, - i.by.as_ref().map(|b| b.in_lonlat().map_err(|e| named(&b.name, &i.by_layer, e))).transpose()?, - ), + None => { + let (data, _) = i.data.in_lonlat_leaving_out().map_err(|e| named(&i.data.name, &i.layer, e))?; + let left = rows + .iter() + .filter(|&&r| { + i.data.features.row(r).is_some_and(|f| f.geometry().is_some()) + && data.features.row(r).is_some_and(|f| f.geometry().is_none()) + }) + .count(); + if left > 0 { + unplaced.push(format!("{} on '{}': {left} feature(s) of '{}'", i.rule.label(), i.layer, i.layer)); + left_out = true; + } + let by = match &i.by { + Some(b) => { + let (by, left) = b.in_lonlat_leaving_out().map_err(|e| named(&b.name, &i.by_layer, e))?; + if left > 0 { + unplaced.push(format!("{} on '{}': {left} feature(s) of '{}'", i.rule.label(), i.layer, i.by_layer)); + left_out = true; + } + Some(by) + } + None => None, + }; + (rustgis_data::raster::Crs::LonLat, data, by) + } }; let _plane = rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(work)); let lonlat = work == rustgis_data::raster::Crs::LonLat; @@ -2524,7 +2638,9 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result t::Checked { errors: Vec::new(), complete: true, skipped: 0 }, }; rustgis_data::progress::check().map_err(|_| cancelled())?; - if !checked.complete || checked.skipped > 0 { + // A feature left out for want of a place can make its neighbours' issues (a gap where it + // lay, a dangle where it joined, a point it covered): the rule is said to be incomplete. + if !checked.complete || checked.skipped > 0 || left_out { incomplete.push(i.rule.label().to_string()); } if checked.skipped > 0 { @@ -2539,19 +2655,14 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result issue.at, - Some(to) => to.point(issue.at).filter(|c| c.is_finite()).ok_or_else(|| { - let feature = issue.rows.first().and_then(|&r| i.data.features.row(r)).map(|r| format!("feature {}", r.id())); - format!( - "{}: {} has a place in {} that can't be given in longitude/latitude", - i.layer, - feature.as_deref().unwrap_or("a gap"), - work.label() - ) - })?, + Some(to) => to.point(issue.at).filter(|c| c.is_finite()).unwrap_or_else(|| { + unlocated += 1; + rustgis_geom::Coord::new(f64::NAN, f64::NAN) + }), }; errors.push(crate::TopologyIssue { rule: i.rule.label().to_string(), @@ -2563,7 +2674,7 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result Option Json { + json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat, "located": e.lon.is_finite() && e.lat.is_finite()}) +} + fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { let tol = topology_tolerance(p); let inputs = topology_checks(s); @@ -2659,12 +2776,7 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { let answer = found .as_ref() .map(|checked| { - let first: Vec = checked - .errors - .iter() - .take(1000) - .map(|e| json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat})) - .collect(); + let first: Vec = checked.errors.iter().take(1000).map(issue_json).collect(); json!({"errors": checked.errors.len(), "first": first, "incomplete": checked.incomplete}) }) .map_err(Clone::clone); @@ -2673,7 +2785,7 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { super::gp::record_read(s, TOPOLOGY_AHEAD, p, recorded); return answer; } - let TopologyChecked { errors, incomplete, skipped, query_errors, fell_back, bent } = found?; + let TopologyChecked { errors, incomplete, skipped, query_errors, fell_back, bent, unplaced, unlocated } = found?; if !fell_back.is_empty() { s.warn(format!( "{} topology rule(s) checked in longitude/latitude, as their layer's own system can't hold their covering layer: {}", @@ -2718,9 +2830,19 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { skipped.join("; ") )); } + if !unplaced.is_empty() { + s.warn(format!( + "Features with a place that can't be given in longitude/latitude, where a rule is checked, were left out of the check: {}", + unplaced.join("; ") + )); + } + if unlocated > 0 { + s.warn(format!( + "{unlocated} topology issue(s) are at a place that can't be given in longitude/latitude, so the Error Inspector can't zoom to them" + )); + } let n = errors.len(); - let out: Vec = - errors.iter().take(1000).map(|e| json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat})).collect(); + let out: Vec = errors.iter().take(1000).map(issue_json).collect(); s.topology_errors = errors; // Count layers once even when several rules read the same unreadable query. Bound // NoticeText::list nesting independently of the number of rules or layers. @@ -2889,11 +3011,12 @@ mod tests { } /// A held layer with an error at a place that can't be given in longitude/latitude (checked in - /// its own system, #2032 C2e-5) is refused, naming the layer once; a covering layer the - /// checked one's system can't hold is checked in longitude/latitude, where its place that - /// can't be given there is refused, named as that layer, not the one checked. + /// its own system, #2032 C2e-5) keeps it with no place, counted, under the layer's map name; + /// a covering layer the checked one's system can't hold is checked in longitude/latitude, + /// where its feature with no place there is left out, named as that layer as the map has it, + /// and the rule is said to be incomplete (#2032 C2f-4b-1c). #[test] - fn a_topology_refusal_names_its_layer_once() { + fn a_topology_check_names_what_it_cant_place_by_the_maps_names() { let held = |name: &str, kind: GeometryType, far: bool| { let mut ds = rustgis_data::Dataset::new(name, kind, vec![]); ds.hold_in(rustgis_data::raster::Crs::Epsg(32632)).unwrap(); @@ -2911,17 +3034,13 @@ mod tests { }; let mut s = Session::new(crate::Project::default()); s.map_mut().add_dataset(held("Parcels", GeometryType::Polyline, true)); - s.run("topology.rules", &json!({"add": {"rule": "mustNotHaveDangles", "layer": "Parcels"}})).unwrap(); - let Err(e) = check_topology(&topology_checks(&s), 1.0) else { panic!("the check is refused") }; - assert!(e.starts_with("Parcels: feature"), "{e}"); - assert_eq!(e.matches("Parcels").count(), 1, "{e}"); - // A checked layer whose map name isn't its data's (a name taken on a clash) is named as - // the map has it, once. + // A checked layer whose map name isn't its data's (a name taken on a clash). s.map_mut().layers.iter_mut().find(|l| l.name == "Parcels").unwrap().name = "Parcels (2)".into(); s.map_mut().editing.topology = vec![TopologyRule::MustNotHaveDangles { layer: "Parcels (2)".into() }]; - let Err(e) = check_topology(&topology_checks(&s), 1.0) else { panic!("the check is refused") }; - assert!(e.starts_with("Parcels (2): feature"), "{e}"); - assert_eq!(e.matches("Parcels").count(), 1, "{e}"); + let checked = check_topology(&topology_checks(&s), 1.0).unwrap(); + assert_eq!(checked.errors.len(), 2, "both ends dangle"); + assert!(checked.errors.iter().all(|e| e.layer == "Parcels (2)" && !e.lon.is_finite()), "{:?}", checked.errors); + assert_eq!(checked.unlocated, 2); let mut s = Session::new(crate::Project::default()); s.map_mut().add_dataset(held("Cities", GeometryType::Point, false)); @@ -2929,18 +3048,13 @@ mod tests { let mut countries = held("Countries", GeometryType::Polygon, true); countries.held_in = rustgis_data::raster::Crs::Epsg(32633); s.map_mut().add_dataset(countries); - s.run("topology.rules", &json!({"add": {"rule": "mustBeCoveredBy", "layer": "Cities", "by": "Countries"}})).unwrap(); - let Err(e) = check_topology(&topology_checks(&s), 1.0) else { panic!("the check is refused") }; - assert!(e.starts_with("Countries: feature"), "{e}"); - assert!(!e.contains("Cities"), "{e}"); - // A covering layer whose map name isn't its data's (a name taken on a clash) is named as - // the map has it. + // A covering layer whose map name isn't its data's. s.map_mut().layers.iter_mut().find(|l| l.name == "Countries").unwrap().name = "Borders".into(); s.map_mut().editing.topology = vec![TopologyRule::MustBeCoveredBy { layer: "Cities".into(), by: "Borders".into() }]; - let Err(e) = check_topology(&topology_checks(&s), 1.0) else { panic!("the check is refused") }; - assert!(e.starts_with("Borders: feature"), "{e}"); - assert_eq!(e.matches("Countries").count() + e.matches("Borders").count(), 1, "{e}"); - assert!(!e.contains("Cities"), "{e}"); + let checked = check_topology(&topology_checks(&s), 1.0).unwrap(); + assert_eq!(checked.unplaced, vec!["Must Be Covered By on 'Cities': 1 feature(s) of 'Borders'".to_string()]); + assert_eq!(checked.incomplete.len(), 1); + assert_eq!(checked.errors.len(), 1, "the city, its covering polygon left out"); } #[test] diff --git a/crates/engine/src/cmd/design/sketch.rs b/crates/engine/src/cmd/design/sketch.rs index b78fdba774..98fcfd52ae 100644 --- a/crates/engine/src/cmd/design/sketch.rs +++ b/crates/engine/src/cmd/design/sketch.rs @@ -50,11 +50,22 @@ pub(super) fn cut_polygon(s: &mut Session, p: &Value) -> CmdResult { let id = selection_layer(s)?; let l = s.map().layer(id).ok_or("no such layer")?; let mut cut_up = Vec::new(); - let (mut missed, mut work) = (0, 0); + let (mut missed, mut work, mut unplaced) = (0, 0, 0); + let to = l.dataset.shown_conversion()?; for &r in &l.selection { let Some(f) = l.dataset.features.get(r) else { continue }; // Cut in longitude/latitude, from the layer's own coordinates; the pieces go back in them. - let lonlat = f.geometry.as_ref().map(|g| l.dataset.geometry_to_lonlat(g)).transpose()?; + // A polygon with a place that can't be given there isn't cut; it is counted and said. + let lonlat = match f.geometry.as_ref() { + Some(g) => match rustgis_data::Dataset::converted_to_lonlat(&to, g) { + Some(g) => Some(g), + None => { + unplaced += 1; + continue; + } + }, + None => None, + }; match lonlat.map(|g| sketch_edit::cut_polygon(&g, &line, &mut work)).transpose()?.flatten() { Some(pieces) => { for g in &pieces { @@ -74,7 +85,11 @@ pub(super) fn cut_polygon(s: &mut Session, p: &Value) -> CmdResult { let pieces = pieces.into_iter().map(|g| l.dataset.edit_from_lonlat(g, &held)).collect::, _>>()?; cuts.push((r, f.clone(), pieces)); } + let unplaced_said = (unplaced > 0).then(|| super::unplaced_said(&[(l.name.clone(), unplaced)])); if cuts.is_empty() { + if let Some(said) = unplaced_said { + return Err(format!("{said}, so they can't be cut; the line doesn't cut another selected polygon")); + } return Err("the line doesn't cut a selected polygon: draw it across the polygon, from outside to outside".into()); } let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; @@ -102,6 +117,9 @@ pub(super) fn cut_polygon(s: &mut Session, p: &Value) -> CmdResult { if missed > 0 { s.notify(format!("Cut Polygon left {missed} selected feature(s) the line didn't cut"), false); } + if let Some(said) = unplaced_said { + s.warn(format!("Cut Polygon: {said}, so they weren't cut")); + } Ok(json!({"cut": cut, "pieces": pieces, "missed": missed})) } @@ -116,7 +134,7 @@ pub(super) fn reshape(s: &mut Session, p: &Value) -> CmdResult { // Reshaped in longitude/latitude, from the layer's own coordinates, and written back in them, // what the line left (or snapped to) as stored. let own = f.geometry.as_ref().ok_or("the feature has no shape")?; - let lonlat = l.dataset.geometry_to_lonlat(own)?; + let lonlat = l.dataset.feature_to_lonlat(f.id, own)?; let done = sketch_edit::reshape(&lonlat, &line)?; super::super::edit::validate(&done.geometry)?; let held = super::held_places(s, id, &[own], &[&done.geometry]); @@ -167,8 +185,9 @@ pub(super) fn trace(s: &mut Session, p: &Value) -> CmdResult { }; // Traced in longitude/latitude, from the layer's own coordinates. let l = s.map().layer(id).ok_or("no such row")?; - let own = l.dataset.features.get(row).ok_or("no such row")?.geometry.as_ref().ok_or("the feature has no shape")?; - let g = l.dataset.geometry_to_lonlat(own)?; + let feature = l.dataset.features.row(row).ok_or("no such row")?; + let own = feature.geometry().ok_or("the feature has no shape")?; + let g = l.dataset.feature_to_lonlat(feature.id(), own)?; let t = sketch_edit::trace(&g, from, to, part)?; let path: Vec<[f64; 2]> = t.path.iter().map(|c| [c.x, c.y]).collect(); // How far each point was moved onto the edge, so a far-off point isn't taken silently. diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 0938e3af89..1234b0cef8 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -680,8 +680,6 @@ pub(crate) fn read_system_position(map: &Map, text: &str) -> Option CmdResult { let system = (l.dataset.coord_crs(), l.dataset.crs); let r = network::shortest_route_held( &l.dataset, - || Ok(std::borrow::Cow::Borrowed(&l.dataset)), &rows, point(p, "from")?, point(p, "to")?, diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index a1ea49fe9e..55222935d1 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -1079,13 +1079,37 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map, p // The source's fields the area hasn't (added there since): a deletion offline loses their // values too. let source_only: Vec = (0..sl.dataset.fields.len()).filter(|j| !to_source.contains(&Some(*j))).collect(); - let held = (sl.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat).then(|| sl.dataset.clone()); - if held.is_some() { - sl.dataset = sl.dataset.in_lonlat().map_err(|e| sync_error(&ol.name, e))?.into_owned(); - } // The ids the area held when it was last synced. let had: std::collections::HashSet = base.keys().copied().collect(); let now_ids: std::collections::HashSet = ol_ds.features.rows().map(|r| r.id()).collect(); + let held = (sl.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat).then(|| sl.dataset.clone()); + if let Some(own) = &held { + // A source feature with a place that can't be given in longitude/latitude is read + // without its geometry: one outside the area is left as stored (`merged_from_lonlat` + // takes it as the source holds it); one the area holds can't be compared, and + // refuses the sync, naming it. + let (lonlat, unplaced) = own.in_lonlat_leaving_out().map_err(|e| sync_error(&ol.name, e))?; + if unplaced > 0 + && let Some(fid) = own + .features + .rows() + .zip(lonlat.features.rows()) + .find(|(o, l)| { + o.geometry().is_some() && l.geometry().is_none() && (had.contains(&o.id()) || now_ids.contains(&o.id())) + }) + .map(|(o, _)| o.id()) + { + return Err(sync_error( + &ol.name, + format!( + "{}: feature {fid} has a place in {} that can't be given in longitude/latitude, so it can't be compared with the area's", + own.name, + own.coord_crs().label() + ), + )); + } + sl.dataset = lonlat.into_owned(); + } // The features this sync writes, by their ids in the source: only these are converted // back to a held source's system. let mut written = std::collections::HashSet::new(); diff --git a/crates/engine/src/shape_conversion.rs b/crates/engine/src/shape_conversion.rs index 6f92f4d943..78eeafb996 100644 --- a/crates/engine/src/shape_conversion.rs +++ b/crates/engine/src/shape_conversion.rs @@ -232,8 +232,9 @@ fn gather(dataset: &Dataset, mut t: Proposal, raster: Option<&rustgis_map::raste let f = frame(raster, p)?; // Fitted in longitude/latitude, from the layer's own coordinates, as its shape's geometry is // given (`replace_geometry` writes it back in them). - let polygon = dataset.features.get(t.row).and_then(|f| f.geometry.as_ref()).ok_or("missing polygon")?; - let polygon = dataset.geometry_to_lonlat(polygon)?; + let feature = dataset.features.row(t.row).ok_or("missing polygon")?; + let polygon = feature.geometry().ok_or("missing polygon")?; + let polygon = dataset.feature_to_lonlat(feature.id(), polygon)?; t.shape = fit(&polygon, f, p.get("kind").and_then(Value::as_str).ok_or("kind is required")?)?; Ok(t) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 921504a44c..e848ff3d51 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -17,6 +17,8 @@ mod services_own; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/sources_own.rs"] mod sources_own; +#[path = "tests/unplaced_edits.rs"] +mod unplaced_edits; #[path = "tests/unplaced_gp.rs"] mod unplaced_gp; #[path = "tests/unplaced_out.rs"] diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 1ffac1bc9a..aef8d1b31e 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -909,6 +909,36 @@ fn a_held_offline_map_keeps_the_sources_later_edits() { assert_eq!(wells.coord_crs(), UTM); } +/// A source feature with a place that can't be given in longitude/latitude, outside the offline +/// area, doesn't stop the area's sync and stays as stored; one the area holds refuses the sync, +/// naming it (#2032 C2f-4b-1c). +#[test] +fn a_sync_leaves_a_source_feature_it_cant_place_as_stored() { + let mut s = session(UTM); + s.run("offline.download", &json!({"name": "Field", "extent": [11.4, 48.6, 11.6, 48.8]})).unwrap(); + s.run("offline.open", &json!({"name": "Field"})).unwrap(); + s.run("edit.setValue", &json!({"layer": "Wells", "row": 1, "field": "n", "value": 99})).unwrap(); + s.run("map.activate", &json!({"name": "Map"})).unwrap(); + let far = Geometry::Point(Coord::new(1e12, 1e12)); + let wells = &mut s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset; + wells.push(Some(far.clone()), vec![]); + let far_row = wells.features.len() - 1; + let returned = s.project.maps.iter().find(|m| m.name == "Field (offline)").unwrap().clone(); + let ai = s.project.offline_areas.iter().position(|a| a.name == "Field").unwrap(); + crate::cmd::workspace::sync_area(&mut s, ai, &returned, "").unwrap(); + let wells = &s.map().layer_by_name("Wells").unwrap().dataset; + assert_eq!(wells.value(1, wells.field_index("n").unwrap()), &Cell::Int(99)); + assert_eq!(wells.features.row(far_row).and_then(|r| r.geometry().cloned()), Some(far.clone()), "kept as stored"); + assert_eq!(wells.coord_crs(), UTM); + // A feature of the area moved in the source to such a place can't be compared: refused, + // naming it. + let id = wells.features.row(0).unwrap().id(); + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset.features.set_geometry(0, Some(far)); + let returned = s.project.maps.iter().find(|m| m.name == "Field (offline)").unwrap().clone(); + let e = crate::cmd::workspace::sync_area(&mut s, ai, &returned, "").unwrap_err(); + assert!(e.contains(&format!("feature {id} has a place in")) && e.contains("can't be compared"), "{e}"); +} + /// A web scene leaves out, and says, a feature of a held layer with a place that can't be given /// in longitude/latitude, rather than failing the whole scene. #[test] diff --git a/crates/engine/src/tests/unplaced_edits.rs b/crates/engine/src/tests/unplaced_edits.rs new file mode 100644 index 0000000000..2b475d581f --- /dev/null +++ b/crates/engine/src/tests/unplaced_edits.rs @@ -0,0 +1,259 @@ +//! Edits of a layer held in its own system with a place that can't be given in +//! longitude/latitude (#2032 C2f-4b-1c): an edit of the selection leaves such a feature as it is +//! and says how many, rather than failing for all; an edit of that one feature is refused naming +//! it; a paste leaves out what the layer can't hold; a topology check leaves it out and says so. +//! The layers are held in Robinson, a world projection, so every edit converts them to +//! longitude/latitude. + +use crate::Session; +use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value, raster::Crs}; +use rustgis_geom::Coord; +use serde_json::json; + +fn robinson() -> Crs { + Crs::parse("+proj=robin +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs").unwrap() +} + +/// A place in Robinson with none in longitude/latitude: far past the projection's edge. +const FAR: Coord = Coord { x: 1e12, y: 1e12 }; + +/// A dataset held in Robinson, made from `lonlat` geometries in longitude/latitude, then with +/// `far`, one more feature reaching past the projection's edge (its last row). +fn held(name: &str, kind: GeometryType, lonlat: Vec, far: Option) -> Dataset { + let mut ds = Dataset::new(name, kind, vec![Field::new("name", FieldType::Text)]); + for (i, g) in lonlat.into_iter().enumerate() { + ds.push(Some(g), vec![Value::Text(format!("{name} {i}"))]); + } + ds.hold_in(robinson()).unwrap(); + if let Some(g) = far { + ds.push(Some(g), vec![Value::Text("far".into())]); + } + ds +} + +fn square() -> Geometry { + Geometry::Polygon(vec![vec![vec![ + Coord::new(10.0, 45.0), + Coord::new(10.03, 45.0), + Coord::new(10.03, 45.03), + Coord::new(10.0, 45.03), + Coord::new(10.0, 45.0), + ]]]) +} + +/// A session with the line layer "lines" (one line) and the polygon layer "areas" (one square), +/// both held in Robinson; with `far`, each has one more feature with a place that can't be given +/// in longitude/latitude. Every feature of both is selected. +fn session(far: bool) -> Session { + let mut s = Session::new(crate::Project::default()); + let line = Geometry::Line(vec![vec![Coord::new(10.002, 45.002), Coord::new(10.038, 45.038)]]); + let far_line = Geometry::Line(vec![vec![Coord::new(1_000_000.0, 5_000_000.0), FAR]]); + let far_square = Geometry::Polygon(vec![vec![vec![ + Coord::new(1_000_000.0, 5_000_000.0), + Coord::new(1_000_100.0, 5_000_000.0), + FAR, + Coord::new(1_000_000.0, 5_000_000.0), + ]]]); + let lines = held("lines", GeometryType::Polyline, vec![line], far.then_some(far_line)); + let areas = held("areas", GeometryType::Polygon, vec![square()], far.then_some(far_square)); + assert_eq!(lines.lonlat_conversion().unwrap().point(FAR), None, "the far place truly has none in longitude/latitude"); + crate::cmd::layer::add_dataset(&mut s, lines); + crate::cmd::layer::add_dataset(&mut s, areas); + for l in &mut s.map_mut().layers { + l.selection = (0..l.dataset.features.len()).collect(); + } + s +} + +fn select(s: &mut Session, layer: &str, rows: &[usize]) { + for l in &mut s.map_mut().layers { + l.selection = if l.name == layer { rows.to_vec() } else { Vec::new() }; + } +} + +fn geometry_of(s: &Session, layer: &str, row: usize) -> Option { + s.map().layer_by_name(layer).unwrap().dataset.features.row(row).and_then(|r| r.geometry().cloned()) +} + +/// What `cmd` with `p` answers, and its notices that speak of a place that can't be given in +/// longitude/latitude (or held). +fn run(s: &mut Session, cmd: &str, p: serde_json::Value) -> (serde_json::Value, Vec) { + let mark = s.notice_mark(); + let out = s.run(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + let said = s + .notices_since(mark) + .iter() + .map(|n| n.text.clone()) + .filter(|t| t.contains("can't be given in") || t.contains("can't hold")) + .collect(); + (out, said) +} + +/// Move, rotate and scale leave a feature they can't place as it is, and say how many per layer; +/// the rest change. Flip, which only reorders vertices, flips it in its own coordinates. A +/// selection of such features alone is refused, saying why. A layer whose places all convert +/// says nothing new. +#[test] +fn a_selection_edit_leaves_a_feature_it_cant_place_as_it_is() { + for far in [false, true] { + for (cmd, p) in [ + ("edit.move", json!({"dx": 100.0, "dy": 50.0})), + ("edit.rotate", json!({"angle": 30.0})), + ("edit.scale", json!({"factor": 1.5})), + ] { + let mut s = session(far); + let (near, far_before) = (geometry_of(&s, "lines", 0), geometry_of(&s, "lines", 1)); + let (out, said) = run(&mut s, cmd, p); + assert_ne!(geometry_of(&s, "lines", 0), near, "{cmd} changed the line it can place"); + if far { + assert_eq!(geometry_of(&s, "lines", 1), far_before, "{cmd} left the far line as stored, to the bit"); + assert_eq!(said.len(), 1, "{cmd}: {said:?}"); + assert!( + said[0].contains("2 feature(s) of 'areas' (1), 'lines' (1)") && said[0].contains("left as they were"), + "{}", + said[0] + ); + assert_eq!(out["modified"], 2, "{cmd}"); + } else { + assert!(said.is_empty(), "{cmd}: {said:?}"); + } + } + } + // Only the far line selected: refused, saying why. + let mut s = session(true); + select(&mut s, "lines", &[1]); + let e = s.run("edit.move", &json!({"dx": 100.0, "dy": 0.0})).unwrap_err(); + assert!( + e.contains("1 feature(s) of 'lines' (1) have a place that can't be given in longitude/latitude") && e.contains("nothing selected"), + "{e}" + ); + // Flip reverses it in its own coordinates. + let (_, said) = run(&mut s, "edit.flip", json!({})); + assert!(said.is_empty(), "{said:?}"); + let Some(Geometry::Line(parts)) = geometry_of(&s, "lines", 1) else { panic!("a line") }; + assert_eq!(parts[0], vec![FAR, Coord::new(1_000_000.0, 5_000_000.0)]); +} + +/// Split and Cut Polygon leave a line or polygon they can't place whole, say so, and split or cut +/// the rest; with only such features selected they are refused, saying why. +#[test] +fn split_and_cut_leave_out_what_they_cant_place() { + for far in [false, true] { + let mut s = session(far); + select(&mut s, "lines", if far { &[0, 1] } else { &[0] }); + let (_, said) = run(&mut s, "edit.split", json!({"lon": 10.02, "lat": 45.02})); + assert_eq!(s.map().layer_by_name("lines").unwrap().dataset.features.len(), 2 + usize::from(far), "the line was split"); + if far { + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("1 feature(s) of 'lines' (1)") && said[0].contains("weren't split"), "{}", said[0]); + } else { + assert!(said.is_empty(), "{said:?}"); + } + select(&mut s, "areas", if far { &[0, 1] } else { &[0] }); + let across = json!({"type": "LineString", "coordinates": [[10.015, 44.99], [10.015, 45.04]]}); + let (out, said) = run(&mut s, "edit.cutPolygon", json!({"line": across})); + assert_eq!(out["cut"], 1); + if far { + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("Cut Polygon: 1 feature(s) of 'areas' (1)") && said[0].contains("weren't cut"), "{}", said[0]); + } else { + assert!(said.is_empty(), "{said:?}"); + } + } + let mut s = session(true); + select(&mut s, "lines", &[1]); + let e = s.run("edit.split", &json!({"lon": 10.02, "lat": 45.02})).unwrap_err(); + assert!(e.contains("can't be given in longitude/latitude, so they can't be split"), "{e}"); + select(&mut s, "areas", &[1]); + let across = json!({"type": "LineString", "coordinates": [[10.015, 44.99], [10.015, 45.04]]}); + let e = s.run("edit.cutPolygon", &json!({"line": across})).unwrap_err(); + assert!(e.contains("can't be given in longitude/latitude, so they can't be cut"), "{e}"); +} + +/// An edit of the one feature that can't be placed (a vertex, a reshape, a merge with it) is +/// refused naming the layer and the feature. +#[test] +fn an_edit_of_a_feature_it_cant_place_names_it() { + let mut s = session(true); + let id = s.map().layer_by_name("lines").unwrap().dataset.features.row(1).unwrap().id(); + let named = format!("lines: feature {id} has a place in"); + let e = s.run("edit.vertex", &json!({"layer": "lines", "row": 1, "action": "move", "index": 0, "lon": 10.0, "lat": 45.0})).unwrap_err(); + assert!(e.contains(&named) && e.contains("so it can't be edited there"), "{e}"); + select(&mut s, "lines", &[1]); + let across = json!({"type": "LineString", "coordinates": [[10.0, 45.0], [10.01, 45.01]]}); + let e = s.run("edit.reshape", &json!({"line": across})).unwrap_err(); + assert!(e.contains(&named), "{e}"); + select(&mut s, "lines", &[0, 1]); + let e = s.run("edit.merge", &json!({})).unwrap_err(); + assert!(e.contains(&named), "{e}"); +} + +/// Paste into a layer of another system leaves out a feature with a place that layer can't +/// hold, and says so; the rest are pasted. +#[test] +fn a_paste_leaves_out_what_the_layer_cant_hold() { + let mut s = session(true); + let mut target = Dataset::new("plain", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + target.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]])), vec![Value::Null]); + crate::cmd::layer::add_dataset(&mut s, target); + select(&mut s, "lines", &[0, 1]); + s.run("edit.copy", &json!(null)).unwrap(); + let (out, said) = run(&mut s, "edit.paste", json!({"layer": "plain"})); + assert_eq!(out["pasted"], 1, "the line it can place"); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("Paste: 1 feature has a place that layer plain") && said[0].contains("so it wasn't pasted"), "{}", said[0]); + assert_eq!(s.map().layer_by_name("plain").unwrap().dataset.features.len(), 2); +} + +/// A topology check in longitude/latitude (a layer in a world projection) leaves out a feature +/// with a place that can't be given there and says so, rather than failing every rule. +#[test] +fn a_topology_check_leaves_out_what_it_cant_place() { + for far in [false, true] { + let mut s = session(far); + s.run("topology.rules", &json!({"add": {"rule": "mustNotSelfIntersect", "layer": "areas"}})).unwrap(); + s.run("topology.rules", &json!({"add": {"rule": "mustNotHaveDangles", "layer": "lines"}})).unwrap(); + let mark = s.notice_mark(); + let (out, said) = run(&mut s, "topology.validate", json!({"toleranceM": 1.0})); + // The near line's two ends dangle. + assert_eq!(s.topology_errors.len(), 2, "{:?}", s.topology_errors); + assert!(out["first"].as_array().unwrap().iter().all(|e| e["located"] == true), "{out}"); + // A feature left out may make its neighbours' issues: its rules are said to be incomplete. + let incomplete = s.notices_since(mark).iter().any(|n| n.text.contains("weren't checked completely")); + assert_eq!(incomplete, far); + if far { + assert_eq!(said.len(), 1, "{said:?}"); + assert!( + said[0].contains("left out of the check") + && said[0].contains("1 feature(s) of 'areas'") + && said[0].contains("1 feature(s) of 'lines'"), + "{}", + said[0] + ); + } else { + assert!(said.is_empty(), "{said:?}"); + } + } +} + +/// A check in a layer's own projected system (UTM) that finds an issue at a place that can't be +/// given in longitude/latitude keeps it, with no place to zoom to, and says so, rather than +/// failing the check. +#[test] +fn a_topology_issue_it_cant_place_is_kept_without_a_place() { + let mut s = Session::new(crate::Project::default()); + let mut lines = Dataset::new("paths", GeometryType::Polyline, vec![]); + lines.push(Some(Geometry::Line(vec![vec![Coord::new(10.0, 45.0), Coord::new(10.01, 45.01)]])), vec![]); + lines.hold_in(Crs::Epsg(32632)).unwrap(); + lines.push(Some(Geometry::Line(vec![vec![Coord::new(600_000.0, 5_000_000.0), FAR]])), vec![]); + crate::cmd::layer::add_dataset(&mut s, lines); + s.run("topology.rules", &json!({"add": {"rule": "mustNotHaveDangles", "layer": "paths"}})).unwrap(); + let (out, said) = run(&mut s, "topology.validate", json!({"toleranceM": 1.0})); + assert_eq!(s.topology_errors.len(), 4, "every end dangles: {:?}", s.topology_errors); + let errors = out["first"].as_array().unwrap(); + assert_eq!(errors.iter().filter(|e| e["located"] == false && e["lon"].is_null()).count(), 1, "{out}"); + let unlocated = s.topology_errors.iter().filter(|e| !e.lon.is_finite()).count(); + assert_eq!(unlocated, 1, "{:?}", s.topology_errors); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("1 topology issue(s) are at a place") && said[0].contains("can't zoom"), "{}", said[0]); +} diff --git a/crates/ui-egui/src/editpanes.rs b/crates/ui-egui/src/editpanes.rs index b2e00c90ae..dd768eb551 100644 --- a/crates/ui-egui/src/editpanes.rs +++ b/crates/ui-egui/src/editpanes.rs @@ -376,7 +376,11 @@ pub fn editing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if rows.is_empty() { String::new() } else { format!("#{}", rows.join(", #")) } ); if ui.link(text).on_hover_text(tl!("Zoom to the error")).clicked() { - let _ = app.run("map.goToXY", json!({"lon": e.lon, "lat": e.lat})); + // An issue at a place that can't be given in longitude/latitude has none + // (NaN): its features are selected, with no zoom. + if e.lon.is_finite() && e.lat.is_finite() { + let _ = app.run("map.goToXY", json!({"lon": e.lon, "lat": e.lat})); + } if let Some(l) = app.session.map().layer_by_name(&e.layer).map(|l| l.id) && !e.rows.is_empty() { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index b9647a15c8..5b21c575a2 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -200,8 +200,10 @@ A layer keeps its file's own coordinates and coordinate system; Shapefiles use t formats such as GeoPackage, GeoParquet and FlatGeobuf carry their coordinate system in the file. Rasters keep theirs too. The map uses Web Mercator by default, but **View › Projection** can change it; see [Maps](maps.md). On a map in a coordinate system, a layer or raster in that system -is drawn as it is, and one in another system by the transformation PROJ picks between the two -(between two datums, the one for that pair, not one through WGS 84). There, Zoom To Layer, Zoom To +is drawn as it is. On a map in a system made for one area (a UTM zone or a Gauss-Krüger strip, +say), one in another system is drawn by the transformation PROJ picks between the two (between +two datums, the one for that pair, not one through WGS 84); on a world projection, such a layer +goes through WGS 84 longitude/latitude. On a map in a coordinate system, Zoom To Layer, Zoom To Selection and Full Extent frame a layer in the map's system by its own coordinates, and its simplified drawing at small scales is made from them, with nothing converted. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index a3a6964443..96d4001981 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -68,6 +68,11 @@ you edit the value or choose units; click **Apply elevation** to apply the new i and flip line direction. A single point turns and scales on itself, so Rotate and Scale leave points (text graphics included) as they are: with only points selected they change nothing, say so, and add no undo step. Edit › Tools lists every editing tool. + A selected feature with a place that can't be given in longitude/latitude (one far past where + its layer's own system reaches) is left as it is by Move, Rotate, Scale, Split and Cut Polygon, + and a notice counts them by layer; Flip Line flips it in the layer's own coordinates. An edit + of that one feature (a vertex, Reshape, Trace, Merge with it, a shape conversion) is refused, + naming the layer and the feature; Set Geometry gives it a new shape, and Delete removes it. Beyond 85.05°, where Web Mercator stops, Move, Rotate and Scale work on the ground: a feature that reaches beyond it, or that the edit would take beyond it, moves rigidly, together with the selected features sharing a vertex with it (their center goes the distance and direction asked, @@ -165,8 +170,13 @@ you edit the value or choose units; click **Apply elevation** to apply the new i where a check in longitude/latitude takes them. A rule whose covering layer that system can't hold is checked in longitude/latitude instead, and says so. A layer in Web Mercator, another world projection or a geographic system is checked in longitude/latitude, its dangle tolerance - on the ground. An error at a place that can't be given in longitude/latitude, where the Error - Inspector would zoom, refuses the check, naming the layer and feature. + on the ground; there, a feature with a place that can't be given in longitude/latitude (one + far past where its layer's own system reaches) is left out of the check, and a notice names + the rules and counts them. An error at a place that can't be given in longitude/latitude is + listed with its features but has no place for the Error Inspector to zoom to (in + `topology.validate`'s answer, `located` is false and `lon` and `lat` are null), and a notice + counts them. A rule that left a feature out is said to be checked incompletely, since its + neighbours' issues there (a gap where it lay, a dangle where it joined) may not be real. On the desktop the check runs in the background, so the map stays in use: the status bar shows **Error Inspector** with its progress and **Cancel**, and a check that can be cancelled takes any amount of work (a gaps rule first joins all its polygons in one step, which @@ -456,8 +466,9 @@ attribute edits, Calculate Field): Copy (++ctrl+c++) and Cut (++ctrl+x++) take selected features from one layer: the active layer if it has a selection, otherwise the first layer with selected features. Paste (++ctrl+v++) adds them to the layer selected in Layers, matching fields by name and converting values to the -destination field types; unmatched fields stay empty. Geometry types must match. **Paste Special** -adds them as a new layer instead. Copied features also go on the system clipboard as GeoJSON, so +destination field types; unmatched fields stay empty. Geometry types must match. A feature with a +place the destination layer's coordinate system can't hold is left out, and a notice counts them. +**Paste Special** adds them as a new layer instead. Copied features also go on the system clipboard as GeoJSON, so they can be pasted into another RustGIS window or a text editor, and GeoJSON copied elsewhere pastes into RustGIS. **Copy Path** copies the selected layer's data source path. diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index e9082c1d77..9792957b9b 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -208,6 +208,11 @@ Where a change meets one made on the computer since the package was made: the whole return and changes nothing: add the field back, then Bring Back again. So does a field removed on the phone that the computer's layer still has, as its values in the field aren't known. +- A feature of a computer's layer held in its own coordinate system with a place that can't be + given in longitude/latitude (one far past where that system reaches) stays as stored when it + lies outside the area when the area is synced (**Sync**, or a package that goes back as a whole + map); one the area holds can't be compared with the phone's, and the sync is refused, naming it. + A return by the list of changes is refused for any such feature of the layer, naming it. Each of these keeps the version that lost on the offline area: the computer's values and shape the phone's replaced, the phone's edits to a feature deleted on the computer, the computer's feature