Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 186 additions & 1 deletion crates/ui-egui/src/mapview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,8 @@ pub struct MapView {
sketch: Vec<Coord>,
selection_gesture: Option<SelectionGesture>,
radius_preview: Option<(Coord, f64, Vec<Option<Pos2>>)>,
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).
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand All @@ -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
Expand Down Expand Up @@ -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::<f64>().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.
Expand All @@ -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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behaviour change to confirm: after one drag, radius_text stays filled, so this branch runs on every later plain click on the map. That click now replaces the selection with a circle of the remembered distance centred on the click. Before this PR, a plain click in this tool did nothing. The plain-click test clears the box to keep the old behaviour, so the change looks deliberate. But neither the guide nor the overlay hint says that a click alone selects. If click-to-reuse is intended, state it in the guide. If not, gate the typed path on the entry having been edited or focused. I did not run this in a live UI. Confidence: medium.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Click-to-reuse is intended: any nonempty Radius value is used at the clicked centre, including one filled by a drag. The guide already describes the drag's distance as reusable, and the panel says “click centre or drag.” I’m leaving the more explicit after-drag sentence and the remaining naming/coverage nits for the release quality pass.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Included the explicit wording in e4e5b82 alongside the latitude clarification: “A drag replaces the box's value; click another centre to reuse that distance or edit the box to correct it.” Fork CI passed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A double-click with a Radius value set should run this typed branch once, but it probably runs it twice. Egui usually reports clicked() on each click of a double-click, so select.byRadius is dispatched on both clicks, with two commands and two notices where the existing double-click branch below consumes the gesture. The result is the same set in every mode, so this is harmless, but it is an unintended second dispatch. Adding !resp.double_clicked() to the guard, as the drag tools already do, would fix it. I did not run this in a live UI, so confidence is medium on the egui behaviour.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving the double-click dispatch cleanup for the release quality pass. Repeating the same new/add/remove selection gives the same selected set; the current behavior has no confirmed correctness defect.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error is notified twice. app.run already reports a failure: run_with_prepared calls command_failed on Err (lib.rs:3757), which posts one error notice. This closure then returns that same error from .map(|_| ()) on line 2817, and line 2821 calls app.session.notify(error, true) again. Session::notify does not de-duplicate, so a failing select.byRadius on this path shows two identical error notices. The drag path avoids this with let _ =. The new test only covers parse errors, so it does not catch this.

Suggested fix, replacing line 2817 so the closure no longer returns the run's error:

Suggested change
app.session.notify(error, true);
// `run` already reports a failure (command_failed), so its error is not notified twice.
let _ = app.run("select.byRadius", json!({"lon":center.x,"lat":center.y,"radius":radius,"mode":selection_mode(ui)}));
Ok(())

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b91fd3c. Dispatcher errors stay on its existing notice path; parsing and projection errors still produce their own notice. The real-frame regression refuses select.byRadius through the registry and checks one error notice naming the command. The previous code produces two. Fork CI passed.

}
return;
}
// Both drag tools consume ordinary clicks and double-clicks without identifying or zooming.
if resp.double_clicked() {
app.map.cancel_sketch();
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A drag fills the box with the full f64 digits in feet (for example 984.2519685039370 ft), which is hard to read in the entry. The command still receives the unrounded radius, so rounding only the text changes the box by less than a millimetre and leaves the selection unchanged:

Suggested change
format!("{} ft", radius / rustgis_engine::geom::METRES_PER_FOOT)
format!("{:.3} ft", radius / rustgis_engine::geom::METRES_PER_FOOT)

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The next click parses radius_text again, so rounding only that text would change the reused radius, even though the first drag keeps its original value. Keeping the full precision for now; a shorter display should preserve the precise value separately. Leaving that presentation improvement for the release quality pass.

} else {
format!("{radius} m")
};
let _ =
app.run("select.byRadius", json!({"lon": center.x, "lat": center.y, "radius": radius, "mode": selection_mode(ui)}));
Comment on lines 2888 to 2889

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The drag path drops the select.byRadius error with let _ =, so a failed selection gives no notice. RustGisApp::run does not notify on its own (the typed-radius path reports its error through notify). This PR writes the dragged radius into the box just above this line, so after a failure the box shows a radius that selected nothing, with no message. AGENTS.md's "Never silent" rule asks for a notice. The let _ = predates this PR, but the PR edits the block, so I'm raising it here. Confidence: high that the error is dropped; medium that it is reachable, since the validation above catches most failures first.

Suggested change
let _ =
app.run("select.byRadius", json!({"lon": center.x, "lat": center.y, "radius": radius, "mode": selection_mode(ui)}));
if let Err(error) = app.run(
"select.byRadius",
json!({"lon": center.x, "lat": center.y, "radius": radius, "mode": selection_mode(ui)}),
) {
app.session.notify(error, true);
}

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RustGisApp::run already reports this error. On this head, run_with_prepared calls command_failed for an Err; that helper emits an error notice unless the same notice already exists. I exercised an invalid select.byRadius through the app dispatcher and verified the red error toast and Messages status in the rendered UI. Keeping the shared notice path avoids adding a duplicate notification here.

} else {
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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();
Expand All @@ -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.]);
Expand Down
33 changes: 33 additions & 0 deletions crates/ui-egui/src/measure_units.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<f64>, 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::<f64>()
.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 {
Expand Down Expand Up @@ -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] {
Expand Down
19 changes: 12 additions & 7 deletions docs/user-guide/analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading