diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 2678b0a495..b45c571bc6 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -308,6 +308,8 @@ pub struct MapView { sketch: Vec, selection_gesture: Option, radius_preview: Option<(Coord, f64, Vec>)>, + radius_text: String, + radius_imperial: bool, /// A finished measurement stays on screen until the next click. sketch_done: bool, /// The next click splits the selected lines there (Editing pane › Split). @@ -461,6 +463,8 @@ impl Default for MapView { sketch: Vec::new(), selection_gesture: None, radius_preview: None, + radius_text: String::new(), + radius_imperial: false, sketch_done: false, split_mode: false, vertex: None, @@ -1022,6 +1026,7 @@ fn split_view(app: &mut RustGisApp, ui: &mut Ui, other: usize, rect: Rect, t: &T } } +/// Draws the interactive map and its active tool controls before dispatching pointer gestures. fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let t = *t; let rect = ui.available_rect_before_wrap(); @@ -1040,6 +1045,12 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let time = now(ui); app.map.record_frame(time); + if app.session.tool == Tool::SelectRadius { + sync_radius_units(app); + if !app.map.hide_overlays { + radius_panel(app, ui, rect); + } + } interact(app, ui, &resp, rect); // Render when the map changed and we're not in the middle of a pan/zoom: meanwhile the flat @@ -2733,6 +2744,47 @@ fn finish_area_selection(app: &mut RustGisApp, ui: &Ui, rect: Rect) { } } +/// Preserves the entered physical distance on unit changes, even while the editor is hidden. +fn sync_radius_units(app: &mut RustGisApp) { + let imperial = app.ui.measurement_imperial; + if imperial != app.map.radius_imperial { + if app.map.radius_text.trim().parse::().is_ok() + && let Ok(Some(m)) = crate::measure_units::parse_distance(&app.map.radius_text, app.map.radius_imperial) + { + app.map.radius_text = format!("{m} m"); + } + app.map.radius_imperial = imperial; + } +} + +/// Keeps radius entry clear of the map's navigation controls and below dialogs. +fn radius_panel(app: &mut RustGisApp, ui: &Ui, rect: Rect) { + let imperial = app.ui.measurement_imperial; + egui::Area::new(egui::Id::unique("select_radius_entry")) + .fixed_pos(pos2((rect.max.x - 260.0).max(rect.min.x + 70.0), rect.min.y + 12.0)) + .constrain_to(rect) + .order(egui::Order::Middle) + .show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.horizontal(|ui| { + let label = ui.label(tl!("Radius")); + ui.add(egui::TextEdit::singleline(&mut app.map.radius_text).desired_width(120.0).hint_text(if imperial { + tl!("ft / mi") + } else { + tl!("m / km") + })) + .labelled_by(label.id); + }); + ui.small(tl!("Approximate · click centre or drag")); + if let Err(error) = crate::measure_units::parse_distance(&app.map.radius_text, imperial) { + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).red, error); + } + }); + }); +} + +/// Handles polygon/lasso gestures and typed or dragged radius selection. +/// Clicks on the radius entry belong to its own area. fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect: Rect) { let tool = app.session.tool; // While a shortcut is being captured, Escape cancels the capture, not the sketch. @@ -2757,6 +2809,28 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect } return; } + if tool == Tool::SelectRadius && resp.clicked() && !app.map.radius_text.trim().is_empty() { + let result = (|| { + let radius = crate::measure_units::parse_distance(&app.map.radius_text, app.ui.measurement_imperial)?; + let Some(radius) = radius else { + return Ok(()); + }; + if radius > 5_000_000.0 { + return Err(tl!("Radius must be at most 5,000 km (approximate).").to_string()); + } + let point = resp.interact_pointer_pos().ok_or_else(invalid_selection)?; + let center = selection_coord(app, rect, point, &Flat::of(&app.session.map().projection))?; + radius_outline(app, rect, center, radius)?; + // The app dispatcher reports command failures; only pre-dispatch errors escape here. + let _ = app.run("select.byRadius", json!({"lon":center.x,"lat":center.y,"radius":radius,"mode":selection_mode(ui)})); + Ok(()) + })(); + app.map.cancel_sketch(); + if let Err(error) = result { + app.session.notify(error, true); + } + return; + } // Both drag tools consume ordinary clicks and double-clicks without identifying or zooming. if resp.double_clicked() { app.map.cancel_sketch(); @@ -2806,6 +2880,11 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect _ => radius_outline(app, rect, center, radius).is_ok(), }; if valid { + app.map.radius_text = if app.ui.measurement_imperial { + format!("{} ft", radius / rustgis_engine::geom::METRES_PER_FOOT) + } else { + format!("{radius} m") + }; let _ = app.run("select.byRadius", json!({"lon": center.x, "lat": center.y, "radius": radius, "mode": selection_mode(ui)})); } else { @@ -4044,7 +4123,7 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: Some("Click vertices · click the start or double-click to select · Shift adds · Ctrl/Cmd removes · Esc cancels") } Tool::SelectLasso => Some("Drag an area · release to select · Shift adds · Ctrl/Cmd removes · Esc cancels"), - Tool::SelectRadius => Some("Drag from the centre · release to select · Shift adds · Ctrl/Cmd removes · Esc cancels"), + Tool::SelectRadius => Some("Type a radius and click the centre, or drag · Shift adds · Ctrl/Cmd removes · Esc cancels"), Tool::EditVertices if app.map.vertex.is_some() => { Some("Drag a vertex to move it · click an edge to add one · Delete removes the chosen vertex") } @@ -6558,6 +6637,110 @@ mod tests { } } + /// Map-only relay captures hide the editor; ordinary and later frames retain it. + /// Set the capture flag after logic, as the relay does, without opening a listener. + #[test] + fn radius_entry_respects_map_only_capture() { + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 860.0)).build_ui_state( + |ui, (app, hide): &mut (RustGisApp, bool)| { + app.logic(ui.ctx()); + app.map.hide_overlays = *hide; + app.ui(ui); + }, + (app, false), + ); + h.run(); + assert!(h.query_by_label("Radius").is_some()); + h.state_mut().0.map.radius_text = "1000".into(); + h.state_mut().0.ui.measurement_imperial = true; + h.state_mut().1 = true; + h.run(); + assert!(h.query_by_label("Radius").is_none(), "map-only snapshots hide the radius editor"); + assert_eq!( + crate::measure_units::parse_distance(&h.state().0.map.radius_text, true).unwrap(), + Some(1000.0), + "hidden controls preserve the entered physical distance" + ); + h.state_mut().1 = false; + h.run(); + assert!(h.query_by_label("Radius").is_some(), "normal selection keeps its editor"); + } + + /// A command refused after UI validation is reported once by the app dispatcher. + #[test] + fn typed_radius_command_failure_is_reported_once() { + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.state_mut().map.radius_text = "1 km".into(); + h.state_mut().session.registry.commands.retain(|c| c.id != "select.byRadius"); + let mark = h.state().session.notice_mark(); + selection_click(&mut h, [0.5, 0.5]); + let errors: Vec<_> = h.state().session.notices_since(mark).iter().filter(|n| n.error).collect(); + assert_eq!(errors.len(), 1, "a command refusal must produce one error notice"); + assert!(errors[0].text.contains("select.byRadius"), "the notice names the refused command"); + assert!(selection_rows(&h).is_empty()); + } + + /// A circle near a local projection's boundary has valid extrema but an invalid arc. + #[test] + fn typed_radius_rejects_the_same_projection_boundary_as_drag() { + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.state_mut().run("select.rows", json!({"layer":"Points", "rows":[0]})).unwrap(); + h.state_mut().run("map.projection", json!({"type":"local:0,45"})).unwrap(); + h.state_mut().run("map.zoomToExtent", json!({"extent":[4,-61,6,-59]})).unwrap(); + h.run(); + let center = Coord::new(5.0, -60.0); + let rect = h.state().map.view_rect.unwrap().0; + assert!(validate_radius(h.state(), center, 2_250_000.0).is_ok(), "four extrema alone miss the projection boundary crossing"); + assert!(radius_outline(h.state(), rect, center, 2_250_000.0).is_err(), "dragging rejects the sampled arc"); + h.state_mut().map.radius_text = "2250 km".into(); + let mark = h.state().session.notice_mark(); + selection_click(&mut h, [5.0, -60.0]); + let errors: Vec<_> = h.state().session.notices_since(mark).iter().filter(|n| n.error).collect(); + assert_eq!(errors.len(), 1, "typed circles must reject the same unsupported arc as a drag"); + assert_eq!(errors[0].text, invalid_selection()); + assert_eq!(selection_rows(&h), vec![0], "invalid input preserves selection"); + } + + /// Typed distances reach the real map handler in metres, preserve fractional values, + /// and obey the same add/remove modifiers as dragged radii. + #[test] + fn selection_tools_typed_radius_clicks_and_validation() { + use egui_kittest::kittest::Queryable; + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.run(); + h.get_by_label("Radius").click(); + h.run(); + h.event(egui::Event::Text("120.125 km".into())); + h.step(); + selection_click(&mut h, [0.5, 0.5]); + assert_eq!(selection_rows(&h), vec![0]); + assert_eq!(crate::measure_units::parse_distance(&h.state().map.radius_text, false).unwrap(), Some(120125.0)); + let at = selection_screen(&h, [2.5, 0.5]); + let add = egui::Modifiers { shift: true, ..egui::Modifiers::NONE }; + selection_pointer(&mut h, at, Some(true), add); + selection_pointer(&mut h, at, Some(false), add); + assert_eq!(selection_rows(&h), vec![0, 2]); + let remove = egui::Modifiers { ctrl: true, command: true, ..egui::Modifiers::NONE }; + selection_pointer(&mut h, at, Some(true), remove); + selection_pointer(&mut h, at, Some(false), remove); + assert_eq!(selection_rows(&h), vec![0]); + h.state_mut().map.radius_text = "NaN".into(); + let mark = h.state().session.notice_mark(); + selection_click(&mut h, [2., 2.]); + assert_eq!(selection_rows(&h), vec![0]); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error && n.text.contains("positive distance")).count(), 1); + h.state_mut().map.radius_text = "1000".into(); + h.state_mut().ui.measurement_imperial = true; + h.step(); + assert_eq!(crate::measure_units::parse_distance(&h.state().map.radius_text, true).unwrap(), Some(1000.0)); + } + #[test] fn selection_tools_radius_release_metric_and_plain_clicks() { let mut h = selection_harness(); @@ -6578,7 +6761,9 @@ mod tests { assert_eq!(selection_rows(&h), vec![0]); assert_eq!(h.state().session.tool, Tool::SelectRadius); assert!(h.state().map.radius_preview.is_none()); + assert!(crate::measure_units::parse_distance(&h.state().map.radius_text, false).unwrap().is_some()); } + h.state_mut().map.radius_text.clear(); for tool in ["selectLasso", "selectRadius"] { h.state_mut().run("tool.set", json!({"tool": tool})).unwrap(); selection_click(&mut h, [2., 2.]); diff --git a/crates/ui-egui/src/measure_units.rs b/crates/ui-egui/src/measure_units.rs index f1f3f12d21..948e6039ca 100644 --- a/crates/ui-egui/src/measure_units.rs +++ b/crates/ui-egui/src/measure_units.rs @@ -31,6 +31,26 @@ pub fn distance(m: f64, imperial: bool) -> String { } } +/// Parse an optional positive distance. Bare numbers use metres or feet; suffixes let the +/// user enter kilometres or miles too. Command distances remain metres in both settings. +pub fn parse_distance(text: &str, imperial: bool) -> Result, String> { + let text = text.trim().to_ascii_lowercase(); + if text.is_empty() { + return Ok(None); + } + let (number, factor) = [("km", 1000.0), ("mi", geom::METRES_PER_MILE), ("ft", geom::METRES_PER_FOOT), ("m", 1.0)] + .into_iter() + .find_map(|(suffix, factor)| text.strip_suffix(suffix).map(|n| (n.trim(), factor))) + .unwrap_or((&text, if imperial { geom::METRES_PER_FOOT } else { 1.0 })); + let value = number + .parse::() + .ok() + .map(|n| n * factor) + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| tl!("Enter a positive distance in m, km, ft or mi.").to_string())?; + Ok(Some(value)) +} + /// Format an elevation supplied in metres; imperial vertical measurements always use feet. pub fn elevation(m: f64, imperial: bool) -> String { if imperial { @@ -71,6 +91,19 @@ pub fn scale_distance(max_m: f64, imperial: bool) -> f64 { mod tests { use super::*; + #[test] + fn distance_entry_accepts_units_and_rejects_invalid_values() { + assert_eq!(parse_distance("", false).unwrap(), None); + assert_eq!(parse_distance("500", false).unwrap(), Some(500.0)); + assert_eq!(parse_distance("2 km", false).unwrap(), Some(2000.0)); + assert_eq!(parse_distance(" 1.25 MI ", true).unwrap(), Some(1.25 * geom::METRES_PER_MILE)); + assert_eq!(parse_distance("3", true).unwrap(), Some(3.0 * geom::METRES_PER_FOOT)); + assert_eq!(parse_distance("500 m", true).unwrap(), Some(500.0)); + for invalid in ["0", "-1", "NaN", "inf", "1e999", "3 yards"] { + assert!(parse_distance(invalid, false).is_err(), "{invalid}"); + } + } + #[test] fn nonfinite_measurements_are_unavailable_in_both_unit_systems() { for imperial in [false, true] { diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 260edd831d..9de36862e3 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -4,13 +4,18 @@ **Home › Select** picks features by clicking or dragging a box. Open **Select options** to choose **Select by Polygon** (click vertices; click the first vertex or double-click to finish), **Select by -Lasso** (drag a freehand outline), or **Select by Radius** (drag from the centre to set a distance). Shift adds to the -selection; Ctrl/Cmd removes; Esc cancels an unfinished outline. Area tools use even-odd fill, so a -self-crossing outline selects its alternating filled regions. Radius uses the Neighborhood Explorer's -local Mercator distance and retained geographic prefilter; its outline and readout are approximate -and some features near the outline may be excluded. A feature reaching beyond 85.05°, where Web -Mercator stops, is measured on the ground instead, so it may be selected outside the outline, which -stops at 85.05°, or left out inside it. The main Select button remains click/rectangle selection. +Lasso** (drag a freehand outline), or **Select by Radius**. For a radius, enter a distance and click +its centre, or drag from the centre to an edge. A drag replaces the box's value; click another +centre to reuse that distance or edit the box to correct it. Bare numbers use metres or feet, +following the measurement setting; `m`, `km`, `ft` and `mi` suffixes select units explicitly. +Use a decimal point and no thousands separators. Shift adds to the selection; Ctrl/Cmd removes; +Esc cancels an unfinished outline. Area tools use even-odd fill, so a self-crossing outline +selects its alternating filled regions. Radius uses the Neighborhood Explorer's local Mercator +distance and retained geographic prefilter; its outline and readout are approximate and some +features near the outline may be excluded. The radius outline must stay between 85.05°S and +85.05°N; a radius crossing that limit is refused. A feature reaching beyond 85.05°, where Web +Mercator stops, is measured on the ground instead, so it may be selected outside the outline or +left out inside it. The main Select button remains click/rectangle selection. All selection tools take only features that are drawn, in selectable layers: a definition query or a display filter hiding a feature keeps it out, and a click picks the feature drawn on top among the selectable layers. **Select By Attributes** takes a SQL clause and checks it as you type and shows how many rows