From 9c8d52779deaab853c641982fd0ef0063cc18cca Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 08:56:09 +0100 Subject: [PATCH 1/6] feat(edit): vertex handles in the map's coordinates; on a map in the layer's own system edits are written as placed (C2f-7 part 2) Edit Vertices puts each selected feature where the map draws it (Flat::held), not through longitude/latitude: on a map in the layer's own system the handles are its stored coordinates, a dragged vertex is written there as placed (edit.vertex / edit.moveSharedVertex x, y), and a feature with no longitude/latitude place gets handles. Deleting a vertex edits the stored geometry. The globe keeps longitude/latitude; snapped vertices go by longitude/latitude so the place snapped to stays as stored. Carried over: split_own doc, edit.trace params and editing.md wrap (#2900), row_boxes docs (#2906). --- crates/engine/command-surface.txt | 4 +- crates/engine/src/cmd/design.rs | 88 +++++-- crates/engine/src/cmd/design/shared_vertex.rs | 24 +- crates/engine/src/tests/own_segments.rs | 45 ++++ crates/map/src/row_boxes.rs | 10 +- crates/ui-egui/src/mapview.rs | 5 +- crates/ui-egui/src/vertexedit.rs | 239 +++++++++++++++--- docs/user-guide/editing.md | 16 +- 8 files changed, 351 insertions(+), 80 deletions(-) diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index d8fbdf0ba1..3aec3e6b4d 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -102,7 +102,7 @@ edit.flip edit.groundToGrid on? scale? rotation? edit.merge edit.move dx dy units? -edit.moveSharedVertex layer? row part? ring? index lon lat +edit.moveSharedVertex layer? row part? ring? index lon? lat? x? y? edit.paste layer? text? edit.pasteSpecial name? text? edit.previewShapeConversion layer? row featureId? kind request? image? frame? @@ -124,7 +124,7 @@ edit.traverse layer? start units? legs edit.undo edit.updateBox layer? row featureId? box edit.updateCircle layer? row featureId? circle -edit.vertex layer? row action part? ring? index lon? lat? +edit.vertex layer? row action part? ring? index lon? lat? x? y? embeddings.add dataset url? year? bands? stretch? dimension? bbox? name? ran? embeddings.addCube dataset bbox? start? end? bands? stretch? name? found? complete? unusable? embeddings.change dataset from? to? bbox? cellSize? name? ran? diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 69afe3a336..51fdd14b37 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -666,11 +666,11 @@ pub fn commands() -> Vec { .when(need_editable) .params(r#"{"layer"?, "row": number, "geometry": GeoJSON geometry}"#), C::new("edit.vertex", "Edit Vertex", "Edit › Features › Modify", edit_vertex).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable).params( - r#"{"layer"?, "row": number, "action": "move"|"insert"|"delete", "part"?: number, "ring"?: number, "index": number (insert: the vertex the new one follows), "lon"?, "lat"?}"#, + r#"{"layer"?, "row": number, "action": "move"|"insert"|"delete", "part"?: number, "ring"?: number, "index": number (insert: the vertex the new one follows), "lon"?, "lat"?, "x"?, "y"? (in place of lon/lat: in the layer's own coordinates, written as they are)}"#, ), C::new("edit.merge", "Merge", "Edit › Features › Modify", merge).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable_selection), C::new("edit.moveSharedVertex", "Move Shared Vertex", "Edit › Features › Modify", shared_vertex::run).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable).params( - r#"{"layer"?, "row": number, "part"?: number, "ring"?: number, "index": number, "lon": degrees, "lat": degrees}"#, + r#"{"layer"?, "row": number, "part"?: number, "ring"?: number, "index": number, "lon"?: degrees, "lat"?: degrees, "x"?, "y"? (in place of lon/lat: in the layer's own coordinates)}"#, ), C::new("edit.explode", "Explode", "Edit › Features › Modify", explode).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable_selection), C::new("edit.split", "Split", "Edit › Features › Modify", split).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable_selection).params(r#"{"lon", "lat"}"#), @@ -681,7 +681,7 @@ pub fn commands() -> Vec { .when(need_editable_selection) .params(r#"{"line": GeoJSON LineString (lon/lat) drawn across the selected line or polygon's boundary}"#), C::new("edit.trace", "Trace Edge Path", "Edit › Features", sketch::trace).roles(&[]).effects(crate::policy::Effects::NONE).view().params( - r#"{"from": [lon, lat], "to": [lon, lat], "layer"?, "row"?: number (else the nearest edge within the tolerance), "tolerancePx"?: number (default: the snapping tolerance)} (fromOffM and toOffM in Web Mercator metres, or metres of the grid of a layer held in a projected system)"#, + r#"{"from": [lon, lat], "to": [lon, lat], "layer"?, "row"?: number (else the nearest edge within the tolerance), "tolerancePx"?: number (default: the snapping tolerance); returns fromOffM and toOffM: Web Mercator metres, or metres of the grid of a layer held in a projected system}"#, ), C::new("edit.traverse", "Traverse", "Edit › Features › Modify", traverse).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable).params( r#"{"layer"?, "start": [lon, lat], "units"?: "Meters" (default)|"Feet"|"Kilometers"|"Miles", "legs": [{"distance": number, "bearing": degrees from north}]} (closed in a polygon layer, open in a line layer)"#, @@ -1435,29 +1435,74 @@ fn edit_vertex(s: &mut Session, p: &Json) -> CmdResult { } }; let v = rustgis_data::VertexId::new(num("part")?.unwrap_or(0), num("ring")?.unwrap_or(0), num("index")?.ok_or("index is required")?); - let at = || -> Result { - let (lon, lat) = (f(p, "lon").ok_or("lon is required")?, f(p, "lat").ok_or("lat is required")?); - if !(lon.is_finite() && lat.is_finite()) || lon.abs() > 360.0 || lat.abs() > 90.0 { - return Err("lon and lat are degrees".into()); - } - Ok(Coord::new(lon, lat)) - }; - // In longitude/latitude, from the layer's own coordinates (`replace_geometry` writes it back). + let action = ps(p, "action").ok_or("action is required")?; + if !matches!(action, "move" | "insert" | "delete") { + return Err(format!("unknown action '{action}'")); + } + // A deleted vertex needs no place. + let own_at = own_place(p)?; let l = s.map().layer(id).ok_or("no such row")?; let feature = l.dataset.features.row(row).ok_or("no such row")?; let own = feature.geometry().ok_or("the feature has no shape")?; + // Deleting a vertex, or placing one in the layer's own coordinates, edits the feature as it + // is stored: no other vertex moves, and a feature with no place in longitude/latitude can be + // edited too (#2032 C2f-7). + if action == "delete" || own_at.is_some() { + let g = own.clone(); + let (g, v) = vertex_edit(g, action, v, || own_at.ok_or_else(|| "x and y are both required".to_string()))?; + replace_geometry_own(s, id, row, g)?; + return Ok(json!({"part": v.part, "ring": v.ring, "index": v.index})); + } + // In longitude/latitude, from the layer's own coordinates (`replace_geometry` writes it back). 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), + let (g, v) = vertex_edit(g, action, v, || lonlat_place(p))?; + replace_geometry(s, id, row, g)?; + Ok(json!({"part": v.part, "ring": v.ring, "index": v.index})) +} + +/// A vertex's place given in the layer's own coordinates (`x`, `y`: as the vertex editor gives it +/// on a map in the layer's system, #2032 C2f-7), or `None` when it is given in longitude/latitude +/// ([`lonlat_place`]) or not at all. Both kinds at once, or half of one, are refused. +pub(super) fn own_place(p: &Json) -> Result, String> { + if p.get("x").is_none() && p.get("y").is_none() { + return Ok(None); + } + if p.get("lon").is_some() || p.get("lat").is_some() { + return Err("give lon and lat or x and y, not both".into()); + } + let (x, y) = (f(p, "x").ok_or("x and y are both required")?, f(p, "y").ok_or("x and y are both required")?); + if !(x.is_finite() && y.is_finite()) { + return Err("x and y must be numbers".into()); + } + Ok(Some(Coord::new(x, y))) +} + +/// A vertex's place given in longitude/latitude (`lon`, `lat`). +pub(super) fn lonlat_place(p: &Json) -> Result { + let (lon, lat) = (f(p, "lon").ok_or("lon is required")?, f(p, "lat").ok_or("lat is required")?); + if !(lon.is_finite() && lat.is_finite()) || lon.abs() > 360.0 || lat.abs() > 90.0 { + return Err("lon and lat are degrees".into()); + } + Ok(Coord::new(lon, lat)) +} + +/// [`edit_vertex`]'s `action` on vertex `v` of `g`, placing a moved or inserted vertex `at`, with +/// the vertex edited after it (an inserted one follows `v`). +fn vertex_edit( + g: Geometry, + action: &str, + v: rustgis_data::VertexId, + at: impl FnOnce() -> Result, +) -> Result<(Geometry, rustgis_data::VertexId), String> { + match action { + "move" => Ok((g.move_vertex(v, at()?).ok_or("no such vertex")?, v)), "insert" => { let g = g.insert_vertex(v, at()?).ok_or("vertices can only be inserted in lines and polygons")?; - (g, rustgis_data::VertexId::new(v.part, v.ring, v.index + 1)) + Ok((g, rustgis_data::VertexId::new(v.part, v.ring, v.index + 1))) } - "delete" => (g.delete_vertex(v)?, v), - a => return Err(format!("unknown action '{a}'")), - }; - replace_geometry(s, id, row, g)?; - Ok(json!({"part": v.part, "ring": v.ring, "index": v.index})) + "delete" => Ok((g.delete_vertex(v)?, v)), + a => Err(format!("unknown action '{a}'")), + } } /// The places an edit of layer `id`, given in longitude/latitude (`edited`), keeps as stored when @@ -1865,8 +1910,9 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { } /// [`split`] of the selected lines of layer `id`, held in `grid`'s projected system, in its own -/// coordinates (#2032 C2f-7): at the point nearest `at` (longitude/latitude) on its segments as they run straight there, measured flat in its -/// grid. Every place of the line stays as stored; only the point it is split at is new. +/// coordinates (#2032 C2f-7): at the point nearest `at` (longitude/latitude) on its segments as +/// they run straight there, measured flat in its grid. Every place of the line stays as stored; +/// only the point it is split at is new. fn split_own(s: &mut Session, id: u32, grid: OwnGrid, at: Coord) -> CmdResult { // Converted as the layer is drawn; the split point is projected onto a segment anyway, so // stored places aren't looked up for it. diff --git a/crates/engine/src/cmd/design/shared_vertex.rs b/crates/engine/src/cmd/design/shared_vertex.rs index 9275bb9db5..8891d4cbf3 100644 --- a/crates/engine/src/cmd/design/shared_vertex.rs +++ b/crates/engine/src/cmd/design/shared_vertex.rs @@ -15,18 +15,20 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { let id = s.layer_id(p)?; let row = index(p, "row", None)?; let vertex = VertexId::new(index(p, "part", Some(0))?, index(p, "ring", Some(0))?, index(p, "index", None)?); - let lon = super::f(p, "lon").ok_or("lon is required")?; - let lat = super::f(p, "lat").ok_or("lat is required")?; - if !(lon.is_finite() && lat.is_finite()) || lon.abs() > 360.0 || lat.abs() > 90.0 { - return Err("lon and lat are degrees".into()); - } + let own = super::own_place(p)?; let layer = s.map().layer(id).ok_or("no such layer")?; - // The place in the layer's own coordinates, where its vertices are matched exactly: a stored - // place it was snapped to, as stored. - let place = Geometry::Point(Coord::new(lon, lat)); - let held = super::held_places(s, id, &[], &[&place]); - let Geometry::Point(at) = layer.dataset.edit_from_lonlat(place, &held)? else { - return Err("the place can't be given in the layer's coordinates".into()); + // The place in the layer's own coordinates, where its vertices are matched exactly: as given + // there (`x`, `y`), or from longitude/latitude, a stored place it was snapped to as stored. + let at = match own { + Some(at) => at, + None => { + let place = Geometry::Point(super::lonlat_place(p)?); + let held = super::held_places(s, id, &[], &[&place]); + let Geometry::Point(at) = layer.dataset.edit_from_lonlat(place, &held)? else { + return Err("the place can't be given in the layer's coordinates".into()); + }; + at + } }; let source = layer.dataset.features.get(row).ok_or("no such row")?.geometry.as_ref().ok_or("the feature has no shape")?; if !matches!(source, Geometry::Polygon(_)) { diff --git a/crates/engine/src/tests/own_segments.rs b/crates/engine/src/tests/own_segments.rs index c44abfd70e..b37271caf3 100644 --- a/crates/engine/src/tests/own_segments.rs +++ b/crates/engine/src/tests/own_segments.rs @@ -244,3 +244,48 @@ fn a_split_says_how_many_segments_it_couldnt_measure_and_a_clean_one_says_nothin let said = split(Geometry::Line(vec![vec![Coord::new(X, Y), Coord::new(X + SIDE, Y + SIDE)]])); assert!(said.iter().all(|t| !t.contains("could not be measured")), "{said:?}"); } + +/// `edit.vertex` with `x`/`y` (the vertex editor on a map in the layer's own system) writes the +/// place as given, in the layer's coordinates; a deleted vertex leaves every other as stored. A +/// feature with a place that can't be given in longitude/latitude is edited so too (#2032 C2f-7). +#[test] +fn a_vertex_given_in_the_layers_own_coordinates_is_written_as_it_is() { + let far = Geometry::Polygon(vec![vec![vec![ + Coord::new(500_000.1, 5_200_000.3), + Coord::new(501_000.7, 5_200_000.9), + Coord::new(1e9, 5_201_000.0), + Coord::new(500_000.1, 5_201_000.0), + Coord::new(500_000.1, 5_200_000.3), + ]]]); + let mut s = session(held("Parcels", GeometryType::Polygon, vec![square(500_000.0, 5_000_000.0, 100.0), far.clone()])); + let id = s.map().layers[0].id; + let at = Coord::new(500_012.345_678_9, 5_000_003.210_987_6); + let before = stored(&s); + let r = s.run("edit.vertex", &json!({"layer": id, "row": 0, "action": "move", "index": 1, "x": at.x, "y": at.y})).unwrap(); + assert_eq!(r, json!({"part": 0, "ring": 0, "index": 1})); + let after = stored(&s); + assert_eq!(after[1], at, "written as given"); + assert_eq!(after.iter().zip(&before).filter(|(a, b)| a != b).count(), 1, "no other place moved"); + let r = + s.run("edit.vertex", &json!({"layer": id, "row": 0, "action": "insert", "index": 1, "x": 500_050.0, "y": 5_000_001.0})).unwrap(); + assert_eq!(r, json!({"part": 0, "ring": 0, "index": 2})); + assert_eq!( + s.map().layers[0].dataset.features.geometry(0).unwrap().vertex(rustgis_data::VertexId::new(0, 0, 2)), + Some(Coord::new(500_050.0, 5_000_001.0)) + ); + // The feature with no place in longitude/latitude: moved and a vertex deleted, as stored. + assert!(s.map().layers[0].dataset.feature_to_lonlat(1, &far).is_err()); + s.run("edit.vertex", &json!({"layer": id, "row": 1, "action": "move", "index": 0, "x": 500_000.5, "y": 5_200_000.5})).unwrap(); + s.run("edit.vertex", &json!({"layer": id, "row": 1, "action": "delete", "index": 1})).unwrap(); + let g = s.map().layers[0].dataset.features.geometry(1).unwrap().clone(); + let want = far.move_vertex(rustgis_data::VertexId::new(0, 0, 0), Coord::new(500_000.5, 5_200_000.5)).unwrap(); + assert_eq!(g, want.delete_vertex(rustgis_data::VertexId::new(0, 0, 1)).unwrap()); + // Undo goes back step by step. + s.run("edit.undo", &json!(null)).unwrap(); + assert_eq!(s.map().layers[0].dataset.features.geometry(1), Some(&want)); + // Both kinds of place, or half of one, are refused. + let both = json!({"layer": id, "row": 0, "action": "move", "index": 1, "x": 1.0, "y": 2.0, "lon": 9.0, "lat": 45.0}); + assert!(s.run("edit.vertex", &both).unwrap_err().contains("not both")); + let half = json!({"layer": id, "row": 0, "action": "move", "index": 1, "x": 1.0}); + assert!(s.run("edit.vertex", &half).unwrap_err().contains("x and y")); +} diff --git a/crates/map/src/row_boxes.rs b/crates/map/src/row_boxes.rs index 15a05ce9a9..14c718ddbc 100644 --- a/crates/map/src/row_boxes.rs +++ b/crates/map/src/row_boxes.rs @@ -44,9 +44,9 @@ impl Grid { /// The grid of `rows`' boxes, made in two walks over every row's vertices: one for the box /// they are all in, one to list each row's box, so no box is kept per row (a list of them /// would take 32 bytes a row while the grid is made). Capped at 256 by 256 cells, so the - /// cells' headers (24 bytes each) take about 1.5 MB at most; each row is listed at 4 bytes a - /// cell it is in, in at most [`MAX_CELLS_PER_ROW`] cells (usually one to four), or once in - /// the wide list. + /// cells' headers (24 bytes each) take about 1.5 MB at most; each row is listed at least 4 + /// bytes (more where a cell's list keeps spare room as it grows) for each cell it is in, in + /// at most [`MAX_CELLS_PER_ROW`] cells, or once in the wide list. fn new(rows: &Features) -> Grid { // A row's box, empty for a row without a shape or a place (`Geometry::extent` leaves out a // coordinate that isn't a number, so every other box is finite). @@ -136,8 +136,8 @@ impl Grid { impl Cache { /// The rows of `rows` whose shape's box may meet `within` (a superset of those that do; one - /// without a shape only past `u32::MAX` rows, when every row is given), each once, in order. The grid is made again only once the rows - /// change. + /// without a shape only past `u32::MAX` rows, when every row is given), each once, in order. + /// The grid is made again only once the rows change. pub(super) fn touching(&self, rows: &Features, within: &Extent) -> Vec { // The grid is disposable; a poisoned lock does not invalidate the features themselves. let mut grid = self.0.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 059524bd34..bd9b8544e8 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -3861,8 +3861,9 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: let cam = app.session.map().camera; let key = [c.x, c.y, cam.center.x + cam.center.y * 1e-3, cam.res, app.session.revision as f64]; match (&app.map.vertex_drag, &app.map.snap) { - // A dragged vertex has snapped already (leaving its own feature out). - (Some(d), _) => d.snapped.then_some(d.at), + // A dragged vertex has snapped already (leaving its own feature out), in view + // coordinates. + (Some(d), _) => d.snapped.then(|| crate::vertexedit::view_to_lonlat(app, d.at)).flatten(), (None, Some((k, at))) if *k == key => *at, _ => { // Asked directly, not as a command: commands mark the map changed. diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index f215498240..95c3e2d5f3 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -12,6 +12,8 @@ use serde_json::json; use crate::RustGisApp; use crate::mapview::{lonlat_to_screen, screen_to_lonlat}; +use rustgis_engine::map::Projection; +use rustgis_engine::map::projection::Flat; /// How near (points) the pointer must be to a vertex, a midpoint or an edge to take it. const VERTEX_PX: f32 = 7.0; @@ -24,7 +26,7 @@ const MAX_HANDLES: usize = 4000; const MID_MIN_PX: f32 = 24.0; /// A vertex being dragged: the feature, the vertex (for an insertion, the vertex the new one -/// follows) and where the pointer has it now. +/// follows) and where the pointer has it now, in [view coordinates](view_to_screen). #[derive(Clone, Copy, Debug)] pub struct VertexDrag { pub layer: u32, @@ -101,13 +103,14 @@ impl DragOwner { shared: app.map.move_shared_vertices, preview: shared_origin(app, d).and_then(|original| { // Matched in the layer's own coordinates, where shared vertices are equal, and - // drawn in longitude/latitude, as the handles are. - let to = layer.dataset.shown_conversion().ok()?; - let lonlat = |c: Coord| if to.is_identity() { Some(c) } else { to.point(c) }; + // drawn in view coordinates, as the handles are. + let flat = map.flat(); + let placing = Placing::of(&flat, map.projection == Projection::Globe, layer)?; + let view = |c: Coord| placing.point(c); let edges = shared_edges(layer.dataset.features.iter(), original); Some(SharedPreview { - original: lonlat(original)?, - edges: edges.into_iter().filter_map(|(a, b)| Some((lonlat(a)?, lonlat(b)?))).collect(), + original: view(original)?, + edges: edges.into_iter().filter_map(|(a, b)| Some((view(a)?, view(b)?))).collect(), }) }), }) @@ -156,23 +159,121 @@ enum Handle { Edge(u32, usize, VertexId, Coord), } +/// How a layer's coordinates are put where its handles are drawn and dragged, in view +/// coordinates ([`view_to_screen`]): into the map's coordinates as the map draws the layer +/// ([`Flat::held`]: as they are on a map in the layer's own system, so the handles are on the +/// drawn line exactly), or into longitude/latitude on the globe. +enum Placing<'a> { + Map(rustgis_engine::map::projection::HeldDrawing<'a>), + Globe(rustgis_engine::data::raster::Reprojection), +} + +impl<'a> Placing<'a> { + /// `None` for a layer whose system can't be converted at all. + fn of(flat: &'a Flat, globe: bool, l: &rustgis_engine::map::Layer) -> Option { + if globe { + return l.dataset.shown_conversion().ok().map(Placing::Globe); + } + flat.held(l.dataset.coord_crs()).ok().map(Placing::Map) + } + + /// Whether the layer's own coordinates are the view's (a map in its own system). + fn is_identity(&self) -> bool { + match self { + Placing::Map(h) => h.is_identity(), + Placing::Globe(to) => to.is_identity(), + } + } + + /// `g` in view coordinates (borrowed as it is when they are the layer's own); `None` when a + /// place of it can't be drawn there ([`unplaced_targets`]). + fn geometry<'g>(&self, g: &'g Geometry) -> Option> { + if self.is_identity() { + return Some(Cow::Borrowed(g)); + } + match self { + Placing::Map(h) => match h.geometry(g) { + (_, true) => None, + (g, false) => Some(Cow::Owned(g)), + }, + Placing::Globe(to) => Dataset::converted_to_lonlat(to, g).map(|g| Cow::Owned(g.into_owned())), + } + } + + /// One place in view coordinates. + fn point(&self, c: Coord) -> Option { + let point = Geometry::Point(c); + let g = self.geometry(&point)?; + match g.as_ref() { + Geometry::Point(p) if p.is_finite() => Some(*p), + _ => None, + } + } +} + +/// Whether handles are in longitude/latitude (the globe) rather than map coordinates. +fn on_globe(app: &RustGisApp) -> bool { + app.session.map().projection == Projection::Globe +} + +/// The screen point of a place in view coordinates: the map's coordinates, or longitude/latitude +/// on the globe (`None` off the view or behind the globe). +pub(crate) fn view_to_screen(app: &RustGisApp, rect: Rect, c: Coord) -> Option { + if on_globe(app) { + return lonlat_to_screen(app, rect, c); + } + if !c.is_finite() { + return None; + } + let (x, y) = app.session.map().camera.try_to_screen(c, rect.width() as f64, rect.height() as f64)?; + Some(egui::pos2(rect.min.x + x as f32, rect.min.y + y as f32)) +} + +/// The place in view coordinates under a screen point ([`view_to_screen`]). +fn screen_to_view(app: &RustGisApp, rect: Rect, p: Pos2) -> Option { + if on_globe(app) { + return screen_to_lonlat(app, rect, p); + } + let (x, y) = ((p.x - rect.min.x) as f64, (p.y - rect.min.y) as f64); + app.session.map().camera.try_to_map(x, y, rect.width() as f64, rect.height() as f64) +} + +/// A longitude/latitude (a snapped place) in view coordinates. +fn lonlat_to_view(app: &RustGisApp, c: Coord) -> Option { + if on_globe(app) { Some(c) } else { app.session.map().to_map(c) } +} + +/// A place in view coordinates in longitude/latitude. +pub(crate) fn view_to_lonlat(app: &RustGisApp, c: Coord) -> Option { + if on_globe(app) { Some(c) } else { app.session.map().to_lonlat(c) } +} + +/// Whether layer `id`'s handles are in its own coordinates ([`Placing::is_identity`]): a map in +/// its own system, where an edit is written as placed. +fn own_placing(app: &RustGisApp, id: u32) -> bool { + let m = app.session.map(); + let flat = m.flat(); + !on_globe(app) && m.layer(id).and_then(|l| Placing::of(&flat, false, l)).is_some_and(|p| p.is_identity()) +} + /// The features whose vertices the tool edits: the selected features of visible feature layers -/// held in memory (a layer read in place from its file can't be edited), when editing is on. +/// held in memory (a layer read in place from its file can't be edited), when editing is on, in +/// view coordinates ([`Placing`]). fn targets(app: &RustGisApp) -> Vec<(u32, usize, Cow<'_, Geometry>)> { let m = app.session.map(); if !m.editing.settings.enabled { return Vec::new(); } + let (flat, globe) = (m.flat(), on_globe(app)); let mut out = Vec::new(); for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { + let Some(placing) = Placing::of(&flat, globe, l) else { continue }; for r in &l.selection { if out.len() >= MAX_FEATURES { return out; } - // In longitude/latitude, from the layer's own coordinates, as the handles are drawn - // and dragged (borrowed as it is while they are longitude/latitude). if let Some(g) = l.dataset.features.get(*r).and_then(|f| f.geometry.as_ref()) - && let Ok(g) = l.dataset.geometry_to_lonlat(g) + && let Some(g) = placing.geometry(g) { out.push((l.id, *r, g)); } @@ -186,8 +287,9 @@ fn targets(app: &RustGisApp) -> Vec<(u32, usize, Cow<'_, Geometry>)> { const MAX_UNPLACED: usize = 1000; /// The selected features [`targets`] leaves out, by layer and row, while Edit Vertices is on: -/// those with a place that can't be given in longitude/latitude (#2032 C2f-4b), where handles are -/// drawn and dragged. On a map in the layer's own system such a feature is drawn and selected. +/// those with a place that can't be given in longitude/latitude (#2032 C2f-4b), which the map +/// draws them through. On a map in the layer's own system such a feature is drawn as it is, so it +/// gets its handles and isn't counted (#2032 C2f-7). /// Up to [`MAX_UNPLACED`] of them. struct Unplaced { rows: Vec<(u32, usize)>, @@ -205,8 +307,9 @@ fn unplaced_targets(app: &RustGisApp) -> Unplaced { // made once. A row without geometry counts towards neither bound. let mut found = Unplaced { rows: Vec::new(), more: false, visited: Vec::new() }; let mut placed = 0usize; + let (flat, globe) = (m.flat(), on_globe(app)); for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { - let to = l.dataset.shown_conversion(); + let placing = Placing::of(&flat, globe, l); let mut visited = 0; for r in &l.selection { if placed >= MAX_FEATURES { @@ -214,7 +317,7 @@ fn unplaced_targets(app: &RustGisApp) -> Unplaced { } visited += 1; if let Some(g) = l.dataset.features.geometry(*r) { - match to.as_ref().ok().and_then(|to| Dataset::converted_to_lonlat(to, g)) { + match placing.as_ref().and_then(|p| p.geometry(g)) { Some(_) => placed += 1, None if found.rows.len() >= MAX_UNPLACED => { found.more = true; @@ -243,6 +346,7 @@ fn unplaced_signature(app: &RustGisApp) -> u64 { let m = app.session.map(); let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.project.active_map.hash(&mut h); + format!("{:?}", m.projection).hash(&mut h); for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { let rows = l.dataset.features.allocation_key().as_ptr() as usize; let revisions = (l.instance_id(), l.replacement_revision(), l.geometry_rev, rows); @@ -329,7 +433,7 @@ pub(crate) fn say_unplaced(app: &mut RustGisApp) { /// The screen points of an edge's ends, when both are in view. fn edge_on_screen(app: &RustGisApp, rect: Rect, a: Coord, b: Coord) -> Option<(Pos2, Pos2)> { - Some((lonlat_to_screen(app, rect, a)?, lonlat_to_screen(app, rect, b)?)) + Some((view_to_screen(app, rect, a)?, view_to_screen(app, rect, b)?)) } /// The nearest point to `p` on the segment `a`–`b`. @@ -342,12 +446,12 @@ fn nearest_on(a: Pos2, b: Pos2, p: Pos2) -> Pos2 { /// The handle under a screen point: a vertex first, then a midpoint, then an edge. fn handle_at(app: &RustGisApp, rect: Rect, p: Pos2) -> Option { - // Features nowhere near the pointer aren't searched: their extents (in degrees) padded by - // the reach of a handle around it. - let near = screen_to_lonlat(app, rect, p).map(|c| { + // Features nowhere near the pointer aren't searched: their extents (in view coordinates) + // padded by the reach of a handle around it. + let near = screen_to_view(app, rect, p).map(|c| { let reach = [vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(-1.0, 0.0), vec2(0.0, -1.0)] .iter() - .filter_map(|d| screen_to_lonlat(app, rect, p + *d * (VERTEX_PX + MID_PX))) + .filter_map(|d| screen_to_view(app, rect, p + *d * (VERTEX_PX + MID_PX))) .map(|q| (q.x - c.x).abs().max((q.y - c.y).abs())) .fold(0.0_f64, f64::max); (c, reach * 2.0) @@ -358,7 +462,7 @@ fn handle_at(app: &RustGisApp, rect: Rect, p: Pos2) -> Option { for (layer, row, g) in &ts { let (layer, row) = (*layer, *row); g.for_each_vertex(|v, c| { - let Some(s) = lonlat_to_screen(app, rect, c) else { return }; + let Some(s) = view_to_screen(app, rect, c) else { return }; let d = (s - p).length(); if d <= VERTEX_PX && best.is_none_or(|b| d < b.0) { best = Some((d, Handle::Vertex(layer, row, v, c))); @@ -381,7 +485,7 @@ fn handle_at(app: &RustGisApp, rect: Rect, p: Pos2) -> Option { }; if d <= EDGE_PX && best.is_none_or(|b| d < b.0) - && let Some(c) = screen_to_lonlat(app, rect, at) + && let Some(c) = screen_to_view(app, rect, at) { best = Some((d, Handle::Edge(layer, row, v, c))); } @@ -411,16 +515,20 @@ pub fn drag_start(app: &mut RustGisApp, rect: Rect, origin: Pos2) -> bool { /// even when this pointer position cannot be projected. pub fn drag_to(app: &mut RustGisApp, rect: Rect, p: Pos2) { cancel_stale_drag(app); - let Some(c) = screen_to_lonlat(app, rect, p) else { return }; + let Some(c) = screen_to_view(app, rect, p) else { return }; let Some(d) = app.map.vertex_drag else { return }; - // Asked directly, not as a command: commands mark the map changed, redrawing it every frame. - let snap = if d.insert { - rustgis_engine::cmd::design::snap_except(&mut app.session, c, Some((d.layer, d.row))) - } else { - rustgis_engine::cmd::design::snap_vertex_except(&mut app.session, c, Some((d.layer, d.row, d.vertex))) - }; + // Snapping looks in longitude/latitude. Asked directly, not as a command: commands mark the + // map changed, redrawing it every frame. + let snap = view_to_lonlat(app, c).and_then(|lonlat| { + let at = if d.insert { + rustgis_engine::cmd::design::snap_except(&mut app.session, lonlat, Some((d.layer, d.row))) + } else { + rustgis_engine::cmd::design::snap_vertex_except(&mut app.session, lonlat, Some((d.layer, d.row, d.vertex))) + }; + lonlat_to_view(app, at?.0) + }); if let Some(d) = &mut app.map.vertex_drag { - d.at = snap.map_or(c, |(at, _)| at); + d.at = snap.unwrap_or(c); d.snapped = snap.is_some(); } } @@ -447,7 +555,7 @@ fn commit(app: &mut RustGisApp, d: VertexDrag) { let action = if d.insert { "insert" } else { "move" }; let mut p = json!({ "layer": d.layer, "row": d.row, "action": action, - "part": d.vertex.part, "ring": d.vertex.ring, "index": d.vertex.index, "lon": d.at.x, "lat": d.at.y, + "part": d.vertex.part, "ring": d.vertex.ring, "index": d.vertex.index, }); let shared = app.map.move_shared_vertices && !d.insert @@ -458,6 +566,16 @@ fn commit(app: &mut RustGisApp, d: VertexDrag) { .and_then(|l| l.dataset.features.get(d.row)) .and_then(|f| f.geometry.as_ref()) .is_some_and(|g| matches!(g, Geometry::Polygon(_))); + // On a map in the layer's own system, a vertex placed by the pointer is written where it is, + // in the layer's coordinates. A snapped one goes by longitude/latitude, so the place snapped + // to is kept as stored (`held_places`). + let own = !d.snapped && own_placing(app, d.layer); + let place = if own { Some(("x", "y", d.at)) } else { view_to_lonlat(app, d.at).map(|c| ("lon", "lat", c)) }; + let Some((kx, ky, at)) = place else { return }; + if let Some(o) = p.as_object_mut() { + o.insert(kx.into(), json!(at.x)); + o.insert(ky.into(), json!(at.y)); + } let command = if shared { if let Some(p) = p.as_object_mut() { p.remove("action"); @@ -604,8 +722,8 @@ pub fn draw(app: &RustGisApp, p: &Painter, rect: Rect, accent: Color32) { } else { neighbours(&g, d.vertex) }; - if let Some(to) = lonlat_to_screen(app, rect, d.at) { - for e in ends.into_iter().filter_map(|c| lonlat_to_screen(app, rect, c)) { + if let Some(to) = view_to_screen(app, rect, d.at) { + for e in ends.into_iter().filter_map(|c| view_to_screen(app, rect, c)) { p.line_segment([e, to], Stroke::new(2.0, accent)); } p.circle_filled(to, 5.0, accent); @@ -638,7 +756,7 @@ pub fn draw(app: &RustGisApp, p: &Painter, rect: Rect, accent: Color32) { if shared.is_some_and(|(d, preview)| d.layer == layer && preview.original == c) { return; } - let Some(s) = lonlat_to_screen(app, rect, c).filter(|s| shown.contains(*s)) else { return }; + let Some(s) = view_to_screen(app, rect, c).filter(|s| shown.contains(*s)) else { return }; let chosen = app.map.vertex == Some((layer, row, v)); let size = if chosen { 9.0 } else { 7.0 }; let r = Rect::from_center_size(s, vec2(size, size)); @@ -728,6 +846,58 @@ mod tests { assert_eq!(targets(&app).len(), 1); } + /// On a map in the layer's own system, the handles are its own coordinates, as the map draws + /// them: a feature with a place that can't be given in longitude/latitude gets its handles and + /// isn't said, and a dragged vertex is written where the pointer put it, with every other + /// place as stored (#2032 C2f-7). + #[test] + fn on_a_map_in_the_layers_own_system_handles_are_its_own_coordinates() { + let mut app = app([square(0.)].into_iter()); + let id = app.session.active_layer.unwrap(); + let utm = rustgis_engine::data::raster::Crs::from_epsg(32631).unwrap(); + app.session.map_mut().editing.settings.enabled = true; + app.session.map_mut().editing.snapping.enabled = false; + let far = Geometry::Polygon(vec![vec![vec![ + Coord::new(500_000.25, 10.5), + Coord::new(500_040.75, 10.5), + Coord::new(1e9, 30.0), + Coord::new(500_000.25, 30.0), + Coord::new(500_000.25, 10.5), + ]]]); + let layer = app.session.map_mut().layer_mut(id).unwrap(); + layer.dataset.hold_in(utm).unwrap(); + layer.dataset.features[0].geometry = Some(far.clone()); + layer.touch_geometry(); + app.run("map.projection", json!({"type": "EPSG:32631"})).unwrap(); + let cam = &mut app.session.map_mut().camera; + cam.center = Coord::new(500_020.0, 20.0); + cam.res = 0.1; + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000., 800.)); + // Its handles, as it is stored; nothing said. + let ts = targets(&app); + assert_eq!(ts.len(), 1); + assert!(matches!(ts[0].2, Cow::Borrowed(_))); + assert_eq!(ts[0].2.as_ref(), &far); + drop(ts); + let mark = app.session.notice_mark(); + say_unplaced(&mut app); + assert!(app.session.notices_since(mark).is_empty()); + // A drag of the second vertex. + let from = view_to_screen(&app, rect, Coord::new(500_040.75, 10.5)).unwrap(); + assert!(drag_start(&mut app, rect, from)); + drag_to(&mut app, rect, from + egui::vec2(37.0, -21.0)); + let at = app.map.vertex_drag.unwrap().at; + assert!((at.x - 500_044.45).abs() < 0.01 && (at.y - 12.6).abs() < 0.01, "{at:?}"); + drag_stop(&mut app); + let g = app.session.map().layer(id).unwrap().dataset.features.geometry(0).unwrap().clone(); + assert_eq!(g, far.move_vertex(VertexId::new(0, 0, 1), at).unwrap()); + // Deleted, the others stay as stored. + choose(&mut app, Some((id, 0, VertexId::new(0, 0, 1)))); + assert!(delete_chosen(&mut app)); + let g = app.session.map().layer(id).unwrap().dataset.features.geometry(0).unwrap().clone(); + assert_eq!(g, far.delete_vertex(VertexId::new(0, 0, 1)).unwrap()); + } + /// The count stops where the handles do: at their cap of placed features. With 49 placed /// ones selected first, the two unplaced after them are both counted; past 50 placed, one /// isn't, as it gets no handles either way. @@ -885,7 +1055,8 @@ mod tests { assert_eq!(SCANNED_EDGES.get(), 8000, "stop before the remaining 101 rows"); let to = lonlat_to_screen(&app, rect, Coord::new(0.2, 0.3)).unwrap(); drag_to(&mut app, rect, to); - let at = app.map.vertex_drag.unwrap().at; + // The pointer's place is in the map's coordinates; the layer is in longitude/latitude. + let at = view_to_lonlat(&app, app.map.vertex_drag.unwrap().at).unwrap(); drag_stop(&mut app); assert!(app.map.vertex_drag_owner.is_none()); assert_eq!(app.session.undo_depth(), 1); diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 607b44f60b..e3b2d7e374 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -103,7 +103,8 @@ you edit the value or choose units; click **Apply elevation** to apply the new i Polygon (in a layer edited in its own grid, each of these changes it with the rest), 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, a shape conversion; Reshape, Trace or Merge with it, outside a layer - edited in its own grid) is refused, naming the layer and the feature; Set Geometry gives it a new shape, and Delete removes it. + edited in its own grid) 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, @@ -173,13 +174,18 @@ you edit the value or choose units; click **Apply elevation** to apply the new i - **Edit Vertices** (Edit › Features): reshape the selected features on the map. Their vertices show as square handles and each edge has a round midpoint handle. Drag a vertex to move it; drag a midpoint, or click an edge, to insert a vertex; click a vertex and press ++delete++ to - remove it (a line keeps at least two vertices, a polygon ring three). A selected feature with - a place that can't be given in longitude/latitude (see [Places with no longitude/latitude](data-formats.md#places-with-no-longitudelatitude)) - gets no handles, and a notice says so once, naming it or counting them. Clicking elsewhere + remove it (a line keeps at least two vertices, a polygon ring three). The handles sit where + the map draws the vertices. On a map in the layer's own coordinate system they are its stored + coordinates: a vertex you drag is written where you let go, in the layer's coordinates, and + every other vertex stays exactly as stored. On another map, a selected feature with a place + that can't be given in longitude/latitude (see [Places with no longitude/latitude](data-formats.md#places-with-no-longitudelatitude)) + gets no handles, and a notice says so once, naming it or counting them; on a map in its + layer's own system it gets its handles. Clicking elsewhere selects the feature there (++shift++ adds it). Multipart features and polygon holes work the same way, dragged vertices snap when snapping is on, and each move, insertion or deletion is one undo step. ++esc++ finishes. From scripts and the command line, `edit.vertex` does the - same to one vertex and `edit.setGeometry` (Set Geometry) replaces a feature's whole shape. + same to one vertex, given in longitude/latitude (`lon`, `lat`) or in the layer's own + coordinates (`x`, `y`), and `edit.setGeometry` (Set Geometry) replaces a feature's whole shape. - **Feature templates**: named default values for new features, made from a selected feature; the Create tool uses the chosen template. - **Snapping** (**Edit › Snapping**): new and dragged vertices snap to nearby vertices, edges and From 993e11b72aabd8ec6d852a5b832e87016ea959ca Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 09:14:44 +0100 Subject: [PATCH 2/6] fix(edit): a snapped vertex is committed at the longitude/latitude it snapped to; a release with no place is said From the pre-push review: the snapped place now goes to the command as snapping gave it, not after a round trip through the map's coordinates (inexact on Web Mercator for lon/lat layers). A release where the map's coordinates have no longitude/latitude says so. A null lon/lat beside x/y is no place. edit.moveSharedVertex x/y documented and tested; projection hashed directly. --- crates/engine/src/cmd/design.rs | 5 +- .../tests/integration/move_shared_vertex.rs | 27 ++++++++ crates/map/src/globe.rs | 2 +- crates/ui-egui/src/mapview.rs | 2 +- crates/ui-egui/src/vertexedit.rs | 66 ++++++++++++++++--- docs/user-guide/editing.md | 3 +- 6 files changed, 90 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 51fdd14b37..f31f0c9a4a 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1464,10 +1464,11 @@ fn edit_vertex(s: &mut Session, p: &Json) -> CmdResult { /// on a map in the layer's system, #2032 C2f-7), or `None` when it is given in longitude/latitude /// ([`lonlat_place`]) or not at all. Both kinds at once, or half of one, are refused. pub(super) fn own_place(p: &Json) -> Result, String> { - if p.get("x").is_none() && p.get("y").is_none() { + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + if !given("x") && !given("y") { return Ok(None); } - if p.get("lon").is_some() || p.get("lat").is_some() { + if given("lon") || given("lat") { return Err("give lon and lat or x and y, not both".into()); } let (x, y) = (f(p, "x").ok_or("x and y are both required")?, f(p, "y").ok_or("x and y are both required")?); diff --git a/crates/engine/tests/integration/move_shared_vertex.rs b/crates/engine/tests/integration/move_shared_vertex.rs index aab384fc3d..f2b04f4f8b 100644 --- a/crates/engine/tests/integration/move_shared_vertex.rs +++ b/crates/engine/tests/integration/move_shared_vertex.rs @@ -304,3 +304,30 @@ fn streamed_and_disabled_editing_use_existing_guards() { assert!(error.contains("Load All Features"), "{error}"); assert_eq!(s.undo_depth(), 0); } + +/// With `x`/`y` (the vertex editor on a map in the layer's own system), every coincident node +/// moves to the place as given, in the layer's coordinates; giving lon/lat too is refused. +#[test] +fn a_place_in_the_layers_own_coordinates_moves_every_corner_as_given() { + let (mut s, id) = fixture(); + let utm = rustgis_engine::data::raster::Crs::from_epsg(32631).unwrap(); + s.map_mut().layer_mut(id).unwrap().dataset.hold_in(utm).unwrap(); + let corner = s.map().layer(id).unwrap().dataset.features.geometry(0).unwrap().vertex(VertexId::new(0, 0, 0)).unwrap(); + let at = Coord::new(corner.x + 12.345_678_9, corner.y - 0.987_654_3); + let r = s.run("edit.moveSharedVertex", &json!({"layer": id, "row": 0, "index": 0, "x": at.x, "y": at.y})).unwrap(); + assert_eq!(r["modified"], json!(4)); + for f in features(&s, id) { + let g = f.geometry.unwrap(); + let mut hits = 0; + g.for_each_coord(|c| { + assert_ne!(c, corner, "{g:?}"); + hits += usize::from(c == at); + }); + assert!(hits >= 1, "{g:?}"); + } + let both = json!({"layer": id, "row": 0, "index": 0, "x": at.x, "y": at.y, "lon": 0.0, "lat": 0.0}); + assert!(s.run("edit.moveSharedVertex", &both).unwrap_err().contains("not both")); + // A null beside a place is no place. + let null = json!({"layer": id, "row": 0, "index": 0, "x": at.x, "y": at.y, "lon": null}); + assert!(s.run("edit.moveSharedVertex", &null).is_ok()); +} diff --git a/crates/map/src/globe.rs b/crates/map/src/globe.rs index ed0699e56a..a922fbb364 100644 --- a/crates/map/src/globe.rs +++ b/crates/map/src/globe.rs @@ -19,7 +19,7 @@ use crate::Camera; pub const GLOBE_DISTANCE: f64 = 6.0; /// How a map is drawn. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Projection { /// The flat Web Mercator map. #[default] diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index bd9b8544e8..d81f55ed21 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -3863,7 +3863,7 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: match (&app.map.vertex_drag, &app.map.snap) { // A dragged vertex has snapped already (leaving its own feature out), in view // coordinates. - (Some(d), _) => d.snapped.then(|| crate::vertexedit::view_to_lonlat(app, d.at)).flatten(), + (Some(d), _) => d.snapped_lonlat, (None, Some((k, at))) if *k == key => *at, _ => { // Asked directly, not as a command: commands mark the map changed. diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index 95c3e2d5f3..f8cb7a7efd 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -36,6 +36,9 @@ pub struct VertexDrag { pub at: Coord, /// Whether `at` snapped to a feature (the overlay marks it). pub snapped: bool, + /// The longitude/latitude it snapped to, as snapping gave it: committed as it is, so the + /// place snapped to is kept exactly, not after a round trip through the map's coordinates. + pub snapped_lonlat: Option, } /// The source chosen by a vertex click, without retaining rows or invalidating ordinary edits. @@ -346,7 +349,7 @@ fn unplaced_signature(app: &RustGisApp) -> u64 { let m = app.session.map(); let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.project.active_map.hash(&mut h); - format!("{:?}", m.projection).hash(&mut h); + m.projection.hash(&mut h); for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { let rows = l.dataset.features.allocation_key().as_ptr() as usize; let revisions = (l.instance_id(), l.replacement_revision(), l.geometry_rev, rows); @@ -498,8 +501,12 @@ fn handle_at(app: &RustGisApp, rect: Rect, p: Pos2) -> Option { /// and map context before previewing. A later source change cancels rather than retargets it. pub fn drag_start(app: &mut RustGisApp, rect: Rect, origin: Pos2) -> bool { let drag = match handle_at(app, rect, origin) { - Some(Handle::Vertex(layer, row, vertex, at)) => VertexDrag { layer, row, vertex, insert: false, at, snapped: false }, - Some(Handle::Edge(layer, row, vertex, at)) => VertexDrag { layer, row, vertex, insert: true, at, snapped: false }, + Some(Handle::Vertex(layer, row, vertex, at)) => { + VertexDrag { layer, row, vertex, insert: false, at, snapped: false, snapped_lonlat: None } + } + Some(Handle::Edge(layer, row, vertex, at)) => { + VertexDrag { layer, row, vertex, insert: true, at, snapped: false, snapped_lonlat: None } + } None => return false, }; let Some(owner) = DragOwner::capture(app, drag) else { return false }; @@ -524,12 +531,14 @@ pub fn drag_to(app: &mut RustGisApp, rect: Rect, p: Pos2) { rustgis_engine::cmd::design::snap_except(&mut app.session, lonlat, Some((d.layer, d.row))) } else { rustgis_engine::cmd::design::snap_vertex_except(&mut app.session, lonlat, Some((d.layer, d.row, d.vertex))) - }; - lonlat_to_view(app, at?.0) + }? + .0; + Some((lonlat_to_view(app, at)?, at)) }); if let Some(d) = &mut app.map.vertex_drag { - d.at = snap.unwrap_or(c); + d.at = snap.map_or(c, |(view, _)| view); d.snapped = snap.is_some(); + d.snapped_lonlat = snap.map(|(_, lonlat)| lonlat); } } @@ -569,9 +578,17 @@ fn commit(app: &mut RustGisApp, d: VertexDrag) { // On a map in the layer's own system, a vertex placed by the pointer is written where it is, // in the layer's coordinates. A snapped one goes by longitude/latitude, so the place snapped // to is kept as stored (`held_places`). - let own = !d.snapped && own_placing(app, d.layer); - let place = if own { Some(("x", "y", d.at)) } else { view_to_lonlat(app, d.at).map(|c| ("lon", "lat", c)) }; - let Some((kx, ky, at)) = place else { return }; + let own = d.snapped_lonlat.is_none() && own_placing(app, d.layer); + let place = match d.snapped_lonlat { + _ if own => Some(("x", "y", d.at)), + Some(lonlat) => Some(("lon", "lat", lonlat)), + None => view_to_lonlat(app, d.at).map(|c| ("lon", "lat", c)), + }; + let Some((kx, ky, at)) = place else { + // Let go where the map's coordinates have no longitude/latitude: said, not dropped. + app.session.notify(crate::tl!("The vertex can't be placed there: that place has no longitude/latitude"), true); + return; + }; if let Some(o) = p.as_object_mut() { o.insert(kx.into(), json!(at.x)); o.insert(ky.into(), json!(at.y)); @@ -597,7 +614,9 @@ fn commit(app: &mut RustGisApp, d: VertexDrag) { pub fn click(app: &mut RustGisApp, rect: Rect, p: Pos2, c: Coord, shift: bool) { match handle_at(app, rect, p) { Some(Handle::Vertex(layer, row, v, _)) => choose(app, Some((layer, row, v))), - Some(Handle::Edge(layer, row, vertex, at)) => commit(app, VertexDrag { layer, row, vertex, insert: true, at, snapped: false }), + Some(Handle::Edge(layer, row, vertex, at)) => { + commit(app, VertexDrag { layer, row, vertex, insert: true, at, snapped: false, snapped_lonlat: None }) + } None => { choose(app, None); let mode = if shift { "add" } else { "new" }; @@ -898,6 +917,33 @@ mod tests { assert_eq!(g, far.delete_vertex(VertexId::new(0, 0, 1)).unwrap()); } + /// A vertex snapped on a Web Mercator map is committed at the longitude/latitude it snapped + /// to, exactly, not after a round trip through the map's coordinates. + #[test] + fn a_snapped_vertex_is_placed_exactly_where_it_snapped() { + // The second feature's corner, at a place whose Mercator round trip isn't exact. + let target = Coord::new(0.123_456_789_012_3, 0.987_654_321_098_7); + let back = |app: &RustGisApp| view_to_lonlat(app, lonlat_to_view(app, target).unwrap()).unwrap(); + let other = Geometry::Polygon(vec![vec![vec![target, Coord::new(5., 5.), Coord::new(5., 6.), target]]]); + let mut app = app([square(0.), other].into_iter()); + let id = app.session.active_layer.unwrap(); + app.session.map_mut().editing.settings.enabled = true; + app.session.map_mut().editing.snapping.enabled = true; + app.map.move_shared_vertices = false; + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000., 800.)); + if back(&app) == target { + eprintln!("this place round-trips exactly; the test proves nothing here"); + } + let from = lonlat_to_screen(&app, rect, Coord::new(1., 1.)).unwrap(); + assert!(drag_start(&mut app, rect, from)); + let near = lonlat_to_screen(&app, rect, target).unwrap() + egui::vec2(1.0, 1.0); + drag_to(&mut app, rect, near); + assert_eq!(app.map.vertex_drag.unwrap().snapped_lonlat, Some(target)); + drag_stop(&mut app); + let g = app.session.map().layer(id).unwrap().dataset.features.geometry(0).unwrap().clone(); + assert_eq!(g.vertex(VertexId::new(0, 0, 2)), Some(target), "{g:?}"); + } + /// The count stops where the handles do: at their cap of placed features. With 49 placed /// ones selected first, the two unplaced after them are both counted; past 50 placed, one /// isn't, as it gets no handles either way. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index e3b2d7e374..3841f5f7d3 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -482,7 +482,8 @@ The command uses row positions and the same vertex addresses as `edit.vertex`: {"layer":"Parcels","row":0,"part":0,"ring":0,"index":3,"lon":12.5,"lat":41.9} ``` -Run these parameters with `edit.moveSharedVertex`. It returns the source `part`, `ring` and +Run these parameters with `edit.moveSharedVertex`. In place of `lon` and `lat`, `x` and `y` give +the place in the layer's own coordinates, written as given. It returns the source `part`, `ring` and `index`, plus `modified`: the number of features whose geometry or attributes actually changed. Every matched feature runs through attribute rules and archiving in one transaction; a rejection rolls back the whole edit. A successful command is one undo step. As with `edit.vertex`, a direct From f4f60c391c5d730cbf23a565586542a8f1b4f10b Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 09:39:47 +0100 Subject: [PATCH 3/6] test(edit): integration tests read a drag's place through VertexDrag::lonlat VertexDrag::at is in view coordinates now; VertexDrag::lonlat gives the longitude/latitude a release commits (where it snapped, else the pointer's place). --- crates/ui-egui/src/vertexedit.rs | 9 +++++++++ crates/ui-egui/tests/integration/move_shared_vertex.rs | 2 +- crates/ui-egui/tests/integration/snapping_point_types.rs | 8 ++++---- .../ui-egui/tests/integration/vertex_drag_ownership.rs | 2 +- crates/ui-egui/tests/integration/vertex_snapping.rs | 4 ++-- 5 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index f8cb7a7efd..7697af77b8 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -41,6 +41,15 @@ pub struct VertexDrag { pub snapped_lonlat: Option, } +impl VertexDrag { + /// Where letting go would put the vertex, in longitude/latitude: where it snapped, as snapping + /// gave it, else the pointer's place ([`VertexDrag::at`], in view coordinates) there. `None` + /// where the map's coordinates have none. + pub fn lonlat(&self, app: &RustGisApp) -> Option { + self.snapped_lonlat.or_else(|| view_to_lonlat(app, self.at)) + } +} + /// The source chosen by a vertex click, without retaining rows or invalidating ordinary edits. #[derive(Clone, Copy)] pub(crate) struct VertexOwner { diff --git a/crates/ui-egui/tests/integration/move_shared_vertex.rs b/crates/ui-egui/tests/integration/move_shared_vertex.rs index e492d1cc57..edada77ae7 100644 --- a/crates/ui-egui/tests/integration/move_shared_vertex.rs +++ b/crates/ui-egui/tests/integration/move_shared_vertex.rs @@ -101,7 +101,7 @@ fn ribbon_toggle_routes_polygon_drag_and_undoes_all_neighbours() { assert_eq!(h.state().session.undo_depth(), 0); assert!(!h.state().session.dirty()); let to = drag(&mut h, c(0., 0.), c(45., 30.)); - let at = h.state().map.vertex_drag.unwrap().at; + let at = h.state().map.vertex_drag.unwrap().lonlat(h.state()).unwrap(); assert_eq!(geometries(&h), before); release(&mut h, to); let after = geometries(&h); diff --git a/crates/ui-egui/tests/integration/snapping_point_types.rs b/crates/ui-egui/tests/integration/snapping_point_types.rs index 6abbf513e5..7e008e9ac9 100644 --- a/crates/ui-egui/tests/integration/snapping_point_types.rs +++ b/crates/ui-egui/tests/integration/snapping_point_types.rs @@ -121,7 +121,7 @@ fn rotated_drag_to_multipoint_commits_and_undoes_once() { drag(&mut h, from, to); let preview = h.state().map.vertex_drag.unwrap(); assert!(preview.snapped && !preview.insert); - near(preview.at, target); + near(preview.lonlat(h.state()).unwrap(), target); assert!(marker(&h).unwrap().distance(screen(&h, target)) < 0.1); near(first(&h), c(0., 0.)); assert_eq!(h.state().session.undo_depth(), 0); @@ -146,10 +146,10 @@ fn edge_only_drag_ignores_point_target() { let preview = h.state().map.vertex_drag.unwrap(); assert!(!preview.snapped); assert!(marker(&h).is_none()); - assert!((preview.at.x - target.x).abs() > 1e-6); + assert!((preview.lonlat(h.state()).unwrap().x - target.x).abs() > 1e-6); near(first(&h), c(0., 0.)); release(&mut h, to); - near(first(&h), preview.at); + near(first(&h), preview.lonlat(h.state()).unwrap()); assert_eq!(h.state().session.undo_depth(), 1); } @@ -188,7 +188,7 @@ fn multipoint_source_remains_excluded_as_a_whole() { let preview = h.state().map.vertex_drag.unwrap(); assert!(!preview.snapped); release(&mut h, to); - near(first(&h), preview.at); + near(first(&h), preview.lonlat(h.state()).unwrap()); let geometry = h.state().session.map().layers[0].dataset.features[0].geometry.as_ref().unwrap(); assert_eq!(geometry.vertex(VertexId::new(0, 0, 1)), Some(own)); assert_eq!(h.state().session.undo_depth(), 1); diff --git a/crates/ui-egui/tests/integration/vertex_drag_ownership.rs b/crates/ui-egui/tests/integration/vertex_drag_ownership.rs index 92777f9aa1..1fbe16180a 100644 --- a/crates/ui-egui/tests/integration/vertex_drag_ownership.rs +++ b/crates/ui-egui/tests/integration/vertex_drag_ownership.rs @@ -324,7 +324,7 @@ fn closed_line_and_polygon_keep_their_existing_closure_semantics() { let preview = h.state().map.vertex_drag.unwrap(); release(&mut h, to); let actual = h.state().session.map().layers[0].dataset.features[0].geometry.as_ref().unwrap(); - assert_eq!(actual.vertex(VertexId::new(0, 0, 0)), Some(preview.at)); + assert_eq!(actual.vertex(VertexId::new(0, 0, 0)), preview.lonlat(h.state())); match actual { Geometry::Polygon(parts) => assert_eq!(parts[0][0].first(), parts[0][0].last()), Geometry::Line(parts) => assert_eq!(parts[0].last(), Some(&c(0., 0.))), diff --git a/crates/ui-egui/tests/integration/vertex_snapping.rs b/crates/ui-egui/tests/integration/vertex_snapping.rs index a7736d03ce..f851e9bf0b 100644 --- a/crates/ui-egui/tests/integration/vertex_snapping.rs +++ b/crates/ui-egui/tests/integration/vertex_snapping.rs @@ -87,7 +87,7 @@ fn rotated_drag_snaps_to_another_part_and_undoes_once() { drag(&mut h, from, to); let preview = h.state().map.vertex_drag.expect("vertex drag"); assert!(preview.snapped && !preview.insert); - assert!((preview.at.x - c(180., 0.).x).abs() < 1e-9); + assert!((preview.lonlat(h.state()).unwrap().x - c(180., 0.).x).abs() < 1e-9); assert_eq!(first(&h), c(0., 0.)); assert_eq!(h.state().session.undo_depth(), 0); release(&mut h, to); @@ -129,7 +129,7 @@ fn midpoint_insertion_keeps_whole_feature_exclusion() { assert!(preview.insert && !preview.snapped); release(&mut h, to); let geometry = h.state().session.map().layers[0].dataset.features[0].geometry.as_ref().unwrap(); - assert_eq!(geometry.vertex(VertexId::new(0, 0, 1)), Some(preview.at)); + assert_eq!(geometry.vertex(VertexId::new(0, 0, 1)), preview.lonlat(h.state())); assert_eq!(geometry.vertex(VertexId::new(0, 0, 2)), Some(c(0., 160.))); assert_eq!(h.state().session.undo_depth(), 1); } From fbdc946e7492f5e6951c8dc0a50f824c6eeeb096 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 09:41:58 +0100 Subject: [PATCH 4/6] docs(edit): VertexDrag::lonlat says what a release writes; the snap test asserts its place doesn't round-trip --- crates/ui-egui/src/vertexedit.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index 7697af77b8..abab7b0cba 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -42,9 +42,10 @@ pub struct VertexDrag { } impl VertexDrag { - /// Where letting go would put the vertex, in longitude/latitude: where it snapped, as snapping - /// gave it, else the pointer's place ([`VertexDrag::at`], in view coordinates) there. `None` - /// where the map's coordinates have none. + /// The vertex's place in longitude/latitude: where it snapped, as snapping gave it (what + /// letting go writes), else the pointer's place ([`VertexDrag::at`], in view coordinates) in + /// longitude/latitude. On a map in the layer's own system an unsnapped release writes `at` in + /// the layer's coordinates instead. `None` where the map's coordinates have none. pub fn lonlat(&self, app: &RustGisApp) -> Option { self.snapped_lonlat.or_else(|| view_to_lonlat(app, self.at)) } @@ -940,9 +941,7 @@ mod tests { app.session.map_mut().editing.snapping.enabled = true; app.map.move_shared_vertices = false; let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000., 800.)); - if back(&app) == target { - eprintln!("this place round-trips exactly; the test proves nothing here"); - } + assert_ne!(back(&app), target, "the place must not round-trip exactly, or the test proves nothing"); let from = lonlat_to_screen(&app, rect, Coord::new(1., 1.)).unwrap(); assert!(drag_start(&mut app, rect, from)); let near = lonlat_to_screen(&app, rect, target).unwrap() + egui::vec2(1.0, 1.0); From 10ca36024605eaf56346dc90106e2dc31f283c94 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 11:26:54 +0100 Subject: [PATCH 5/6] fix(edit): drags cancel on a projection change; snapped moves on features with no lon/lat; half lon/lat pairs refused; release notice tested --- crates/engine/src/cmd/design.rs | 27 ++++++++++- crates/engine/src/tests/own_segments.rs | 31 ++++++++++++ crates/ui-egui/src/vertexedit.rs | 63 ++++++++++++++++++++++--- 3 files changed, 113 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index f31f0c9a4a..13515b5621 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1454,18 +1454,41 @@ fn edit_vertex(s: &mut Session, p: &Json) -> CmdResult { return Ok(json!({"part": v.part, "ring": v.ring, "index": v.index})); } // In longitude/latitude, from the layer's own coordinates (`replace_geometry` writes it back). - let g = l.dataset.feature_to_lonlat(feature.id(), own)?.into_owned(); - let (g, v) = vertex_edit(g, action, v, || lonlat_place(p))?; + let Ok(g) = l.dataset.feature_to_lonlat(feature.id(), own) else { + // A feature with a place that has no longitude/latitude: edited as stored, the place given + // in longitude/latitude written in the layer's coordinates (a place snapped to as stored). + let g = own.clone(); + let (g, v) = vertex_edit(g, action, v, || lonlat_in_own(s, id, lonlat_place(p)?))?; + replace_geometry_own(s, id, row, g)?; + return Ok(json!({"part": v.part, "ring": v.ring, "index": v.index})); + }; + let (g, v) = vertex_edit(g.into_owned(), action, v, || lonlat_place(p))?; replace_geometry(s, id, row, g)?; Ok(json!({"part": v.part, "ring": v.ring, "index": v.index})) } +/// A place in longitude/latitude in the coordinates of layer `id`, as [`replace_geometry`] writes +/// an edit's places: a stored place of a layer in its system that it reads as ([`held_places`]), +/// as stored; any other converted as the layer is drawn. +fn lonlat_in_own(s: &Session, id: u32, at: Coord) -> Result { + let point = Geometry::Point(at); + let held = held_places(s, id, &[], &[&point]); + match s.map().layer(id).ok_or("no such layer")?.dataset.edit_from_lonlat(point, &held)? { + Geometry::Point(c) => Ok(c), + _ => Err("the place can't be given in the layer's coordinates".into()), + } +} + /// A vertex's place given in the layer's own coordinates (`x`, `y`: as the vertex editor gives it /// on a map in the layer's system, #2032 C2f-7), or `None` when it is given in longitude/latitude /// ([`lonlat_place`]) or not at all. Both kinds at once, or half of one, are refused. pub(super) fn own_place(p: &Json) -> Result, String> { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); if !given("x") && !given("y") { + // Half a pair is refused here too, even where no place is needed (a deleted vertex). + if given("lon") != given("lat") { + return Err("lon and lat are both required".into()); + } return Ok(None); } if given("lon") || given("lat") { diff --git a/crates/engine/src/tests/own_segments.rs b/crates/engine/src/tests/own_segments.rs index b37271caf3..57066d96eb 100644 --- a/crates/engine/src/tests/own_segments.rs +++ b/crates/engine/src/tests/own_segments.rs @@ -288,4 +288,35 @@ fn a_vertex_given_in_the_layers_own_coordinates_is_written_as_it_is() { assert!(s.run("edit.vertex", &both).unwrap_err().contains("not both")); let half = json!({"layer": id, "row": 0, "action": "move", "index": 1, "x": 1.0}); assert!(s.run("edit.vertex", &half).unwrap_err().contains("x and y")); + let half = json!({"layer": id, "row": 0, "action": "delete", "index": 1, "lon": 9.0, "lat": null}); + assert!(s.run("edit.vertex", &half).unwrap_err().contains("lon and lat")); +} + +/// A vertex of a feature with a place that has no longitude/latitude, moved to a place given in +/// longitude/latitude (a vertex snapped to), is written in the layer's coordinates: the place +/// snapped to as stored, every other vertex as it was. +#[test] +fn a_lonlat_place_on_a_feature_with_no_lonlat_is_written_in_its_own_coordinates() { + let far = Geometry::Polygon(vec![vec![vec![ + Coord::new(500_000.1, 5_200_000.3), + Coord::new(501_000.7, 5_200_000.9), + Coord::new(1e9, 5_201_000.0), + Coord::new(500_000.1, 5_201_000.0), + Coord::new(500_000.1, 5_200_000.3), + ]]]); + let corner = Coord::new(500_100.123_456_7, 5_000_100.765_432_1); + let other = Geometry::Polygon(vec![vec![vec![ + Coord::new(500_000.0, 5_000_000.0), + Coord::new(500_100.0, 5_000_000.0), + corner, + Coord::new(500_000.0, 5_000_100.0), + Coord::new(500_000.0, 5_000_000.0), + ]]]); + let mut s = session(held("Parcels", GeometryType::Polygon, vec![other, far.clone()])); + let id = s.map().layers[0].id; + assert!(s.map().layers[0].dataset.feature_to_lonlat(1, &far).is_err()); + let [lon, lat] = lonlat(corner); + s.run("edit.vertex", &json!({"layer": id, "row": 1, "action": "move", "index": 1, "lon": lon, "lat": lat})).unwrap(); + let g = s.map().layers[0].dataset.features.geometry(1).unwrap().clone(); + assert_eq!(g, far.move_vertex(rustgis_data::VertexId::new(0, 0, 1), corner).unwrap()); } diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index abab7b0cba..cf94dfb562 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -96,6 +96,8 @@ pub(crate) struct DragOwner { project: u64, map: usize, map_name: String, + /// The map's projection: a drag's place is in its view coordinates ([`VertexDrag::at`]). + projection: Projection, rows: std::sync::Weak>, shared: bool, /// Bounded geographic edges captured once, discarded with this gesture's row identity. @@ -112,6 +114,7 @@ impl DragOwner { project: app.session.opened, map: app.session.project.active_map, map_name: map.name.clone(), + projection: map.projection.clone(), rows: layer.dataset.features.allocation_key(), shared: app.map.move_shared_vertices, preview: shared_origin(app, d).and_then(|original| { @@ -130,12 +133,13 @@ impl DragOwner { } /// A gesture is usable only in its original context while its source is still an editable - /// target. Row edits or a changed shared mode cancel; styles and camera changes do not. + /// target. Row edits, a changed projection or shared mode cancel; styles and camera changes do not. fn matches(&self, app: &RustGisApp, d: VertexDrag) -> bool { let map = app.session.map(); self.project == app.session.opened && self.map == app.session.project.active_map && self.map_name == map.name + && self.projection == map.projection && self.shared == app.map.move_shared_vertices && app.session.tool == rustgis_engine::Tool::EditVertices && map.layer(d.layer).is_some_and(|l| self.rows.ptr_eq(&l.dataset.features.allocation_key())) @@ -589,11 +593,7 @@ fn commit(app: &mut RustGisApp, d: VertexDrag) { // in the layer's coordinates. A snapped one goes by longitude/latitude, so the place snapped // to is kept as stored (`held_places`). let own = d.snapped_lonlat.is_none() && own_placing(app, d.layer); - let place = match d.snapped_lonlat { - _ if own => Some(("x", "y", d.at)), - Some(lonlat) => Some(("lon", "lat", lonlat)), - None => view_to_lonlat(app, d.at).map(|c| ("lon", "lat", c)), - }; + let place = if own { Some(("x", "y", d.at)) } else { d.lonlat(app).map(|c| ("lon", "lat", c)) }; let Some((kx, ky, at)) = place else { // Let go where the map's coordinates have no longitude/latitude: said, not dropped. app.session.notify(crate::tl!("The vertex can't be placed there: that place has no longitude/latitude"), true); @@ -952,6 +952,57 @@ mod tests { assert_eq!(g.vertex(VertexId::new(0, 0, 2)), Some(target), "{g:?}"); } + /// A vertex let go where the map's coordinates have no longitude/latitude is said once and + /// not edited; one let go at a place that has one is moved, with nothing said. + #[test] + fn a_vertex_let_go_at_no_longitude_latitude_is_said_not_dropped() { + let mut app = app([square(0.)].into_iter()); + let id = app.session.active_layer.unwrap(); + app.session.map_mut().editing.settings.enabled = true; + app.map.move_shared_vertices = false; + app.run("map.projection", json!({"type": "EPSG:32631"})).unwrap(); + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000., 800.)); + let nowhere = Coord::new(1e12, 1e12); + assert!(view_to_lonlat(&app, nowhere).is_none(), "the place must have no longitude/latitude, or the test proves nothing"); + let said = |app: &RustGisApp, mark| { + app.session.notices_since(mark).iter().filter(|n| n.text.contains("has no longitude/latitude")).count() + }; + let before = app.session.map().layer(id).unwrap().dataset.features.geometry(0).unwrap().clone(); + let from = lonlat_to_screen(&app, rect, Coord::new(1., 1.)).unwrap(); + assert!(drag_start(&mut app, rect, from)); + drag_to(&mut app, rect, from + egui::vec2(5.0, 5.0)); + app.map.vertex_drag.as_mut().unwrap().at = nowhere; + let mark = app.session.notice_mark(); + drag_stop(&mut app); + assert_eq!(said(&app, mark), 1); + assert_eq!(app.session.map().layer(id).unwrap().dataset.features.geometry(0), Some(&before)); + // A clean release moves the vertex and says nothing. + assert!(drag_start(&mut app, rect, from)); + drag_to(&mut app, rect, from + egui::vec2(5.0, 5.0)); + let mark = app.session.notice_mark(); + drag_stop(&mut app); + assert_eq!(said(&app, mark), 0); + assert_ne!(app.session.map().layer(id).unwrap().dataset.features.geometry(0), Some(&before)); + } + + /// A projection change during a drag cancels it: its place is in the old view's coordinates. + #[test] + fn a_projection_change_cancels_a_held_drag() { + let mut app = app([square(0.)].into_iter()); + let id = app.session.active_layer.unwrap(); + app.session.map_mut().editing.settings.enabled = true; + app.map.move_shared_vertices = false; + let rect = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000., 800.)); + let before = app.session.map().layer(id).unwrap().dataset.features.geometry(0).unwrap().clone(); + let from = lonlat_to_screen(&app, rect, Coord::new(1., 1.)).unwrap(); + assert!(drag_start(&mut app, rect, from)); + drag_to(&mut app, rect, from + egui::vec2(5.0, 5.0)); + app.run("map.projection", json!({"type": "EPSG:32631"})).unwrap(); + drag_stop(&mut app); + assert!(app.map.vertex_drag.is_none()); + assert_eq!(app.session.map().layer(id).unwrap().dataset.features.geometry(0), Some(&before)); + } + /// The count stops where the handles do: at their cap of placed features. With 49 placed /// ones selected first, the two unplaced after them are both counted; past 50 placed, one /// isn't, as it gets no handles either way. From 1bb7831c33cf706651315359566c816d2c5195b5 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 12:59:02 +0100 Subject: [PATCH 6/6] test(edit): a lon/lat vertex move on a feature with no lon/lat place is written in its own coordinates --- crates/engine/src/tests/unplaced_edits.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/unplaced_edits.rs b/crates/engine/src/tests/unplaced_edits.rs index 2b475d581f..1f21874f83 100644 --- a/crates/engine/src/tests/unplaced_edits.rs +++ b/crates/engine/src/tests/unplaced_edits.rs @@ -170,15 +170,20 @@ fn split_and_cut_leave_out_what_they_cant_place() { 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. +/// An edit of the one feature that can't be placed (a reshape, a merge with it) is refused +/// naming the layer and the feature. A vertex moved to a place in longitude/latitude is written +/// in the layer's coordinates, every other vertex as stored (#2032 C2f-7). #[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}"); + let before = s.map().layer_by_name("lines").unwrap().dataset.features.geometry(1).unwrap().clone(); + s.run("edit.vertex", &json!({"layer": "lines", "row": 1, "action": "move", "index": 0, "lon": 10.0, "lat": 45.0})).unwrap(); + let after = s.map().layer_by_name("lines").unwrap().dataset.features.geometry(1).unwrap().clone(); + let v = rustgis_data::VertexId::new(0, 0, 0); + assert_ne!(after.vertex(v), before.vertex(v)); + assert_eq!(after.move_vertex(v, before.vertex(v).unwrap()), Some(before), "only the moved vertex changes"); 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();