diff --git a/crates/ui-egui/src/annotation.rs b/crates/ui-egui/src/annotation.rs index 98d21c2979..70499589e5 100644 --- a/crates/ui-egui/src/annotation.rs +++ b/crates/ui-egui/src/annotation.rs @@ -1,5 +1,6 @@ //! Session-only image/grid choices shared by Annotate and the ordinary Edit tools. use crate::{Landed, RightPane, RustGisApp}; +use rustgis_engine::data::GeometryType; use rustgis_engine::{Tool, box_edit::Frame, image_grid::Source}; use serde_json::{Value, json}; @@ -79,6 +80,7 @@ pub(crate) fn sync(app: &mut RustGisApp) { } } crate::annotation_classes::sync(app); + crate::mapview::cancel_stale_annotation(app); } /// Keep annotation navigation in the image plane, including when a shape tool is /// retained while another pane is open. Explicit camera commands remain available. @@ -244,14 +246,14 @@ pub(crate) fn drawing_frame(app: &RustGisApp) -> Result { .clone() .ok_or_else(|| app.annotation.error.clone().unwrap_or_else(|| tl!("Wait for the original image grid before drawing.").into())) } -fn polygon_layer(app: &RustGisApp, id: u32) -> bool { - app.session.map().layer(id).is_some_and(is_polygon_layer) +fn annotation_layer(app: &RustGisApp, id: u32) -> bool { + app.session.map().layer(id).is_some_and(is_annotation_layer) } -fn is_polygon_layer(l: &rustgis_engine::map::Layer) -> bool { +pub(crate) fn is_annotation_layer(l: &rustgis_engine::map::Layer) -> bool { !l.is_streamed() && !l.graphics && l.raster.is_none() - && matches!(l.geometry_type(), rustgis_engine::data::GeometryType::Polygon | rustgis_engine::data::GeometryType::None) + && matches!(l.geometry_type(), GeometryType::Point | GeometryType::Polygon | GeometryType::None) } pub(crate) fn filename_option(app: &mut RustGisApp, on: bool) { sync(app); @@ -279,6 +281,9 @@ pub(crate) fn export_name(app: &RustGisApp, layer: u32, ext: &str, annotation: b if annotation && ext != "geojson" { return Err(tl!("Annotation export uses GeoJSON.").into()); } + if annotation && !annotation_layer(app, layer) { + return Err(tl!("Choose a loaded editable point or polygon layer.").into()); + } if annotation && app.annotation.image_filename { return image_export_name(app) .ok_or_else(|| tl!("Select an image with an available filename, or uncheck Use image filename.").into()); @@ -287,17 +292,28 @@ pub(crate) fn export_name(app: &RustGisApp, layer: u32, ext: &str, annotation: b } pub(crate) fn select_layer(app: &mut RustGisApp, p: &Value) -> Result<(), String> { let id = app.session.layer_id(p)?; - if !polygon_layer(app, id) { - return Err(tl!("Choose a loaded editable polygon layer.").into()); + if !annotation_layer(app, id) { + return Err(tl!("Choose a loaded editable point or polygon layer.").into()); + } + app.run("layer.select", json!({"layer":id}))?; + let kind = app.session.map().layer(id).map(|l| l.geometry_type()); + let compatible = match app.session.tool { + Tool::CreatePoint => kind == Some(GeometryType::Point), + Tool::CreatePolygon => kind == Some(GeometryType::Polygon), + Tool::RotatedBox | Tool::Circle => kind != Some(GeometryType::Point), + _ => true, + }; + if !compatible { + app.run("tool.set", json!({"tool":"select"}))?; } - app.run("layer.select", json!({"layer":id})).map(|_| ()) + Ok(()) } /// Annotation selection is scoped to its target layer. It selects ordinary polygons too, /// but only constructions already known to this session activate an exact-shape editor. pub(crate) fn click(app: &mut RustGisApp, c: rustgis_engine::geom::Coord, modifiers: egui::Modifiers) -> bool { if app.ui.right != Some(RightPane::Annotation) || !matches!(app.session.tool, Tool::Explore | Tool::Select) - || !app.session.active_layer.is_some_and(|id| polygon_layer(app, id)) + || !app.session.active_layer.is_some_and(|id| annotation_layer(app, id)) { return false; } @@ -385,7 +401,7 @@ pub(crate) fn grid_controls(app: &mut RustGisApp, ui: &mut egui::Ui) { let _ = app.run("ui.annotationGrid", json!({"pixels":pixels})); } if app.annotation.pixels { - ui.small(tl!("New shapes use the original GeoTIFF pixels, including rotation and shear. Existing objects keep their own grid.")); + ui.small(tl!("New circles and rotated boxes use original GeoTIFF pixels, including rotation and shear. Existing shapes keep their construction grid.")); if let Some(f) = &app.annotation.frame { ui.small(crate::i18n::fmt( "{width} × {height} pixels · EPSG:{epsg}", @@ -405,7 +421,7 @@ pub(crate) fn grid_controls(app: &mut RustGisApp, ui: &mut egui::Ui) { } } else { ui.small(grid_units(&layer_frame(app)).unwrap_or_default()); - ui.small(tl!("Image pixels are the default when an image is selected.")); + ui.small(tl!("Selecting an image defaults circles and rotated boxes to its pixel grid.")); } if image.is_some() && !available { ui.colored_label(egui::Color32::RED, tl!("This image is unavailable. Choose another image or No image.")); @@ -417,12 +433,13 @@ pub(crate) fn panel(app: &mut RustGisApp, ui: &mut egui::Ui) { ui.heading(tl!("Image annotation")); grid_controls(app, ui); ui.separator(); - let active = app.session.active_layer.filter(|id| polygon_layer(app, *id)); + let active = app.session.active_layer.filter(|id| annotation_layer(app, *id)); let mut layer = active; - let name = - layer.and_then(|id| app.session.map().layer(id)).map_or_else(|| tl!("Choose a polygon layer").to_string(), |l| l.name.clone()); + let name = layer + .and_then(|id| app.session.map().layer(id)) + .map_or_else(|| tl!("Choose a point or polygon layer").to_string(), |l| l.name.clone()); egui::ComboBox::from_label(tl!("Target layer")).selected_text(name).show_ui(ui, |ui| { - for l in app.session.map().layers.iter().filter(|l| is_polygon_layer(l)) { + for l in app.session.map().layers.iter().filter(|l| is_annotation_layer(l)) { ui.selectable_value(&mut layer, Some(l.id), &l.name); } }); @@ -432,7 +449,7 @@ pub(crate) fn panel(app: &mut RustGisApp, ui: &mut egui::Ui) { let _ = app.run("ui.annotationLayer", json!({"layer":id})); } if layer.is_none() { - ui.label(tl!("Add or create a polygon feature layer using Data, then choose it here.")); + ui.label(tl!("Add or create a point or polygon feature layer using Data, then choose it here.")); } let mut enabled = app.session.map().editing.settings.enabled; if ui.checkbox(&mut enabled, tl!("Enable editing")).changed() { @@ -454,17 +471,28 @@ pub(crate) fn panel(app: &mut RustGisApp, ui: &mut egui::Ui) { "This is an ordinary polygon. To edit it as an exact shape, right-click it and choose Convert to Shape…; otherwise use Edit Vertices." )); } + let target = layer.and_then(|id| app.session.map().layer(id)); + let geometry = target.map(|l| l.geometry_type()); + let editable = target.is_some_and(|l| app.session.map().draws_at(l, app.session.scale())) && enabled; + let constrained = geometry != Some(GeometryType::Point); let ready = crate::boxedit::ready(app) && drawing_frame(app).is_ok(); - ui.add_enabled_ui(ready, |ui| { - ui.horizontal(|ui| { - for (tool, name) in [(Tool::RotatedBox, tl!("Rotated Box")), (Tool::Circle, tl!("Circle"))] { - if ui.selectable_label(app.session.tool == tool, name).clicked() { - let _ = app.run("tool.set", json!({"tool":tool.code()})); - } + ui.horizontal_wrapped(|ui| { + let tools = [ + (Tool::CreatePoint, tl!("Point"), geometry == Some(GeometryType::Point), editable), + (Tool::CreatePolygon, tl!("Polygon"), geometry == Some(GeometryType::Polygon), editable), + (Tool::RotatedBox, tl!("Rotated Box"), constrained, ready), + (Tool::Circle, tl!("Circle"), constrained, ready), + ]; + for (tool, name, show, usable) in tools { + if show && ui.add_enabled(usable, egui::Button::selectable(app.session.tool == tool, name)).clicked() { + let _ = app.run("tool.set", json!({"tool":tool.code()})); } - }); + } }); - if !crate::boxedit::ready(app) { + if app.session.tool == Tool::CreatePolygon { + ui.small(tl!("Click to add vertices. Double-click to finish, or press Escape to cancel.")); + } + if constrained && !crate::boxedit::ready(app) { let hidden = app.session.active_layer.and_then(|id| app.session.map().layer(id)).is_some_and(|l| { rustgis_engine::box_edit::check_tool(&app.session, l.id).is_ok() && !app.session.map().draws_at(l, app.session.scale()) }); @@ -476,7 +504,9 @@ pub(crate) fn panel(app: &mut RustGisApp, ui: &mut egui::Ui) { } else if hidden { ui.small(tl!("The polygon layer doesn't draw at this scale. Zoom in or out until it draws, then draw.")); } else { - ui.small(tl!("Drawing requires editing enabled, a loaded polygon layer and a flat Earth map with zero pitch.")); + ui.small(tl!( + "Circle and rotated box drawing requires editing enabled, a loaded polygon layer and a flat Earth map with zero pitch." + )); } } ui.small(tl!("Space, middle-drag or right-drag pans; releasing Space returns to the active drawing tool. Map rotation and tilt gestures are disabled while annotating. Undo/Redo use the existing commands.")); @@ -515,7 +545,7 @@ pub(crate) fn panel(app: &mut RustGisApp, ui: &mut egui::Ui) { } }); ui.small(tl!( - "Exports contain ordinary polygons and feature properties. Image/grid choices and exact constructions remain session-only." + "GeoJSON keeps points, polygons and their properties. Circles and rotated boxes reopen as polygons. Right-click a polygon and choose Convert to Shape… to restore constrained editing." )); } diff --git a/crates/ui-egui/src/annotation_classes.rs b/crates/ui-egui/src/annotation_classes.rs index c871e56760..38016923b6 100644 --- a/crates/ui-egui/src/annotation_classes.rs +++ b/crates/ui-egui/src/annotation_classes.rs @@ -1,6 +1,8 @@ //! Class defaults are session-only. Values and colours use ordinary attributes and symbology. use crate::{RightPane, RustGisApp}; -use rustgis_engine::data::{FieldType, GeometryType}; +use rustgis_engine::data::FieldType; +#[cfg(test)] +use rustgis_engine::data::GeometryType; use rustgis_engine::map::{Layer, Renderer}; use serde_json::{Value, json}; @@ -29,9 +31,7 @@ pub(crate) struct State { refusal: Option, } fn target(app: &RustGisApp) -> Option<&Layer> { - app.session.active_layer.and_then(|id| app.session.map().layer(id)).filter(|l| { - !l.is_streamed() && !l.graphics && l.raster.is_none() && matches!(l.geometry_type(), GeometryType::Polygon | GeometryType::None) - }) + app.session.active_layer.and_then(|id| app.session.map().layer(id)).filter(|l| crate::annotation::is_annotation_layer(l)) } fn binding(app: &RustGisApp) -> Option { let l = target(app)?; @@ -81,17 +81,21 @@ fn field(app: &RustGisApp) -> Result<&str, String> { return Err(tl!("The target layer changed. Choose its class field again.").into()); } let name = state.field.as_deref().ok_or_else(|| tl!("Choose a class field first.").to_string())?; + validate_field(app, name)?; + Ok(name) +} +fn validate_field(app: &RustGisApp, name: &str) -> Result<(), String> { if target(app).is_some_and(|l| l.dataset.fields.iter().filter(|f| f.name.eq_ignore_ascii_case(name)).count() > 1) { return Err(tl!("Class field names must be unique ignoring case. Rename the duplicate fields first.").into()); } if !target(app).is_some_and(|l| l.dataset.fields.iter().any(|f| f.name == name && f.ty == FieldType::Text)) { return Err(tl!("The class field is missing or is no longer text. Choose another class field.").into()); } - Ok(name) + Ok(()) } pub(crate) fn select_field(app: &mut RustGisApp, p: &Value) -> Result<(), String> { sync(app); - let layer = target(app).ok_or_else(|| tl!("Choose a loaded editable polygon layer.").to_string())?; + let layer = target(app).ok_or_else(|| tl!("Choose a loaded editable point or polygon layer.").to_string())?; let name = match p.get("field") { Some(Value::Null) => None, Some(Value::String(name)) => { @@ -135,7 +139,7 @@ pub(crate) fn select_class(app: &mut RustGisApp, p: &Value) -> Result<(), String } pub(crate) fn create_field(app: &mut RustGisApp) -> Result<(), String> { sync(app); - let layer = target(app).ok_or_else(|| tl!("Choose a loaded editable polygon layer.").to_string())?; + let layer = target(app).ok_or_else(|| tl!("Choose a loaded editable point or polygon layer.").to_string())?; if layer.dataset.field_index("class").is_some() { return Err(tl!("A field named class already exists. Choose a text field, or rename the existing field in Data.").into()); } @@ -164,6 +168,41 @@ pub(crate) fn drawing_attributes(app: &RustGisApp) -> Result { attrs.insert(name.to_string(), json!(value)); Ok(Value::Object(attrs)) } +/// A multi-click sketch keeps only its target identity and the class at its first vertex. +pub(crate) struct SketchClass { + target: Binding, + attributes: Value, +} +impl SketchClass { + pub(crate) fn capture(app: &RustGisApp) -> Result { + if !app.session.map().editing.settings.enabled { + return Err(tl!("Enable editing before drawing an annotation.").into()); + } + if !target(app).is_some_and(|l| app.session.map().draws_at(l, app.session.scale())) { + return Err(tl!("Choose a point or polygon layer that is visible at this scale.").into()); + } + let target = binding(app).ok_or_else(|| tl!("Choose a loaded editable point or polygon layer.").to_string())?; + Ok(Self { target, attributes: drawing_attributes(app)? }) + } + pub(crate) fn check_target(&self, app: &RustGisApp) -> Result<(), String> { + if !app.session.map().editing.settings.enabled { + return Err(tl!("Editing was turned off, so the annotation sketch was cancelled.").into()); + } + if Some(self.target) != binding(app) { + return Err(tl!("The annotation target changed. Start drawing again.").into()); + } + Ok(()) + } + pub(crate) fn attributes(self, app: &RustGisApp) -> Result { + self.check_target(app)?; + if let Some(fields) = self.attributes.as_object() { + for name in fields.keys() { + validate_field(app, name)?; + } + } + Ok(self.attributes) + } +} pub(crate) fn assign(app: &mut RustGisApp, p: &Value) -> Result<(), String> { sync(app); let name = field(app)?.to_string(); @@ -172,7 +211,7 @@ pub(crate) fn assign(app: &mut RustGisApp, p: &Value) -> Result<(), String> { Some(Value::String(value)) => class_name(value)?, _ => return Err(tl!("Choose a non-empty class name.").into()), }; - let l = target(app).ok_or_else(|| tl!("Choose a loaded editable polygon layer.").to_string())?; + let l = target(app).ok_or_else(|| tl!("Choose a loaded editable point or polygon layer.").to_string())?; let [row] = l.selection.as_slice() else { return Err(tl!("Select exactly one annotation to change its class.").into()) }; let fi = l.dataset.fields.iter().position(|f| f.name == name).ok_or_else(|| tl!("Choose a class field first.").to_string())?; let feature = l.dataset.features.row(*row).ok_or_else(|| tl!("The selected annotation is no longer available.").to_string())?; @@ -184,7 +223,7 @@ pub(crate) fn assign(app: &mut RustGisApp, p: &Value) -> Result<(), String> { pub(crate) fn colours(app: &mut RustGisApp) -> Result<(), String> { sync(app); let name = field(app)?.to_string(); - let l = target(app).ok_or_else(|| tl!("Choose a loaded editable polygon layer.").to_string())?; + let l = target(app).ok_or_else(|| tl!("Choose a loaded editable point or polygon layer.").to_string())?; let styled = matches!(&l.renderer, Renderer::Unique { field, expression: None, .. } if *field == name); app.ui.symbology_pending = if styled { None } else { Some(crate::PendingUniqueSymbology::new(&app.session, l, name)) }; app.ui.open_right(RightPane::Symbology); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 7a74954011..dd6acff8b0 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -306,6 +306,7 @@ pub struct MapView { /// The label being moved with the Move Label tool. moving_label: Option, sketch: Vec, + sketch_class: Option, selection_gesture: Option, radius_preview: Option<(Coord, f64, Vec>)>, radius_text: String, @@ -465,6 +466,7 @@ impl Default for MapView { drag: None, moving_label: None, sketch: Vec::new(), + sketch_class: None, selection_gesture: None, radius_preview: None, radius_text: String::new(), @@ -689,6 +691,7 @@ impl MapView { /// Drops unfinished map sketches, selection shapes and node previews without committing them. pub fn cancel_sketch(&mut self) { self.sketch.clear(); + self.sketch_class = None; self.sketch_done = false; self.sketch_full_said = false; if self.drag.is_some_and(|(_, kind)| matches!(kind, DragKind::SelectLasso | DragKind::SelectRadius)) { @@ -3204,10 +3207,10 @@ fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, rect: Rect } let shift = ui.input(|i| i.modifiers.shift); - let annotation_selection = app.ui.right == Some(crate::RightPane::Annotation) && matches!(tool, Tool::Explore | Tool::Select); + let annotation_click = app.ui.right == Some(crate::RightPane::Annotation) + && matches!(tool, Tool::Explore | Tool::Select | Tool::CreatePoint | Tool::CreatePolygon); let middle = ui.input(|i| { - i.pointer.middle_down() - || ((matches!(tool, Tool::RotatedBox | Tool::Circle) || annotation_selection) && i.key_down(egui::Key::Space)) + i.pointer.middle_down() || ((matches!(tool, Tool::RotatedBox | Tool::Circle) || annotation_click) && i.key_down(egui::Key::Space)) }); let ctrl = ui.input(|i| i.modifiers.ctrl || i.modifiers.command); // Dragging with the right button turns the map or the globe (to the right turns it @@ -3496,8 +3499,8 @@ fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, rect: Rect app.map.last_interaction = time - 1.0; } - // Space-click in annotation selection is navigation, including over text graphics. - if annotation_selection && middle && (resp.clicked() || resp.double_clicked()) { + // Space-click navigates without placing a point, adding a vertex or opening a popup. + if annotation_click && middle && (resp.clicked() || resp.double_clicked()) { return; } // Clicks. @@ -3648,7 +3651,7 @@ fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, rect: Rect } } Tool::CreatePoint => { - let _ = app.run("edit.addFeature", with_template(app, json!({"geometry": {"type": "Point", "coordinates": [c.x, c.y]}}))); + create_point(app, c); } Tool::Graphic("point") => finish_graphic(app, "point", vec![c]), // Placed, selected and open in the Format pane, as a layout's text (#516). @@ -3715,7 +3718,8 @@ fn finish_sketch(app: &mut RustGisApp) { if let Some(f) = coords.first().copied() { coords.push(f); } - let _ = app.run("edit.addFeature", with_template(app, json!({"geometry": {"type": "Polygon", "coordinates": [coords]}}))); + let sketch = app.map.sketch_class.take(); + insert_annotation(app, json!({"type":"Polygon","coordinates":[coords]}), sketch); app.map.cancel_sketch(); } Tool::CutPolygon | Tool::Reshape if pts.len() >= 2 => { @@ -3737,6 +3741,15 @@ fn finish_sketch(app: &mut RustGisApp) { /// Adds a clicked vertex to the sketch: along the edge from the last vertex when Trace finds one, /// and never past the drawn-line limit of Cut Polygon and Reshape (a notice says so). fn add_vertex(app: &mut RustGisApp, tool: Tool, c: Coord) { + if tool == Tool::CreatePolygon && app.map.sketch.is_empty() && app.ui.right == Some(crate::RightPane::Annotation) { + match crate::annotation_classes::SketchClass::capture(app) { + Ok(captured) => app.map.sketch_class = Some(captured), + Err(error) => { + app.session.notify(error, true); + return; + } + } + } let limit = rustgis_engine::cmd::design::MAX_LINE; let capped = matches!(tool, Tool::CutPolygon | Tool::Reshape); if capped && app.map.sketch.len() >= limit { @@ -3788,6 +3801,47 @@ fn snapped(app: &mut RustGisApp, c: Coord) -> Coord { } } +pub(crate) fn cancel_stale_annotation(app: &mut RustGisApp) { + if let Some(reason) = app.map.sketch_class.as_ref().and_then(|sketch| sketch.check_target(app).err()) { + app.map.cancel_sketch(); + app.session.notify(reason, false); + } +} + +fn create_point(app: &mut RustGisApp, c: Coord) { + let sketch = if app.ui.right == Some(crate::RightPane::Annotation) { + match crate::annotation_classes::SketchClass::capture(app) { + Ok(captured) => Some(captured), + Err(error) => { + app.session.notify(error, true); + return; + } + } + } else { + None + }; + insert_annotation(app, json!({"type":"Point","coordinates":[c.x,c.y]}), sketch); +} + +fn insert_annotation(app: &mut RustGisApp, geometry: Value, sketch: Option) { + let started_in_edit = sketch.is_none() && app.ui.right == Some(crate::RightPane::Annotation) && app.session.tool == Tool::CreatePolygon; + let params = if let Some(sketch) = sketch { + match sketch.attributes(app) { + Ok(attributes) => json!({"geometry":geometry,"attributes":attributes}), + Err(error) => { + app.session.notify(error, true); + return; + } + } + } else { + json!({"geometry":geometry}) + }; + if app.run("edit.addFeature", with_template(app, params)).is_ok() && started_in_edit { + app.session + .notify(tl!("This polygon was started in Edit. To apply the active class, choose Assign to selected annotation."), false); + } +} + /// Feature creation parameters with the Editing pane's chosen template, if it belongs to the layer. fn with_template(app: &RustGisApp, mut p: Value) -> Value { let t = &app.forms.template; @@ -6408,6 +6462,137 @@ mod tests { h.state().session.map().layer_by_name("Points").unwrap().selection.clone() } + #[test] + fn annotation_points_draw_select_reclassify_and_round_trip() { + use egui_kittest::kittest::Queryable; + let mut h = selection_harness(); + h.state_mut().run("ui.pane.annotation", Value::Null).unwrap(); + h.state_mut().run("ui.annotationLayer", json!({"layer":"Points"})).unwrap(); + h.state_mut().run("ui.annotationCreateClassField", Value::Null).unwrap(); + h.state_mut().run("ui.annotationClass", json!({"value":"shrub"})).unwrap(); + h.state_mut().run("ui.annotationClass", json!({"value":"tree"})).unwrap(); + h.state_mut().run("map.zoomToExtent", json!({"extent":[-1,-1,5,5]})).unwrap(); + for _ in 0..6 { + h.step(); + } + assert!(h.query_by_label("Rotated Box").is_none()); + h.get_by_label("Point").click(); + h.step(); + assert_eq!(h.state().session.tool, Tool::CreatePoint); + let depth = h.state().session.undo_depth(); + selection_click(&mut h, [1., 1.]); + selection_click(&mut h, [3., 3.]); + assert_eq!(h.state().session.undo_depth(), depth + 2); + h.state_mut().run("tool.set", json!({"tool":"select"})).unwrap(); + selection_click(&mut h, [1., 1.]); + assert_eq!(selection_rows(&h), [4]); + let geojson = |app: &RustGisApp| rustgis_engine::data::io::to_geojson(&app.session.map().layer_by_name("Points").unwrap().dataset); + let before = geojson(h.state()); + let at = selection_screen(&h, [1., 1.]); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Secondary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + h.step(); + } + h.run(); + assert!(h.query_by_label("Convert to Shape…").is_none()); + h.get_by_label("Change class").click(); + h.run(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "shrub").click(); + h.run(); + assert_eq!(crate::annotation_classes::drawing_attributes(h.state()).unwrap(), json!({"class":"tree"})); + let after = geojson(h.state()); + assert_eq!(after["features"][4]["geometry"], before["features"][4]["geometry"]); + assert_eq!(after["features"][4]["properties"]["class"], "shrub"); + assert_eq!(after["features"][5]["properties"]["class"], "tree"); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + assert_eq!(geojson(h.state()), before); + h.state_mut().run("edit.redo", Value::Null).unwrap(); + assert_eq!(geojson(h.state()), after); + let (loaded, _) = rustgis_engine::data::io::read_geojson(&after.to_string(), "Reopened").unwrap(); + assert_eq!(rustgis_engine::data::io::to_geojson(&loaded)["features"], after["features"]); + h.state_mut().run("layer.template", json!({"template":"polygons","name":"Areas"})).unwrap(); + h.state_mut().run("tool.set", json!({"tool":"createPolygon"})).unwrap(); + h.state_mut().run("ui.annotationLayer", json!({"layer":"Points"})).unwrap(); + assert_eq!(h.state().session.tool, Tool::Select); + } + + #[test] + fn annotation_polygon_freezes_class_and_cancels_on_target_change() { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + for name in ["First", "Second"] { + app.run("layer.template", json!({"template":"polygons","name":name})).unwrap(); + } + app.run("ui.pane.annotation", Value::Null).unwrap(); + app.run("ui.annotationLayer", json!({"layer":"First"})).unwrap(); + app.run("ui.annotationCreateClassField", Value::Null).unwrap(); + app.run("ui.annotationClass", json!({"value":"forest"})).unwrap(); + app.run("tool.set", json!({"tool":"createPolygon"})).unwrap(); + let triangle = |app: &mut RustGisApp| { + for (x, y) in [(0., 0.), (2., 0.), (1., 2.)] { + add_vertex(app, Tool::CreatePolygon, Coord::new(x, y)); + } + }; + triangle(&mut app); + app.run("ui.annotationClass", json!({"value":"lake"})).unwrap(); + let depth = app.session.undo_depth(); + finish_sketch(&mut app); + assert_eq!(app.session.undo_depth(), depth + 1); + let features = |app: &RustGisApp, name: &str| { + rustgis_engine::data::io::to_geojson(&app.session.map().layer_by_name(name).unwrap().dataset)["features"].clone() + }; + let saved = features(&app, "First"); + assert_eq!(saved[0]["properties"]["class"], "forest"); + assert_eq!(saved[0]["geometry"]["type"], "Polygon"); + triangle(&mut app); + app.map.cancel_sketch(); + finish_sketch(&mut app); + assert_eq!(app.session.undo_depth(), depth + 1); + triangle(&mut app); + app.run("ui.annotationLayer", json!({"layer":"Second"})).unwrap(); + assert!(app.map.sketch.is_empty()); + app.run("ui.annotationLayer", json!({"layer":"First"})).unwrap(); + finish_sketch(&mut app); + assert_eq!(features(&app, "First"), saved); + assert_eq!(features(&app, "Second"), json!([])); + + app.run("ui.annotationClass", json!({"value":"forest"})).unwrap(); + triangle(&mut app); + app.run("edit.deleteField", json!({"field":"class"})).unwrap(); + let depth = app.session.undo_depth(); + finish_sketch(&mut app); + assert_eq!(app.session.undo_depth(), depth); + assert_eq!(features(&app, "First").as_array().unwrap().len(), 1); + } + + #[test] + fn annotation_reports_edit_sketch_handoff_and_editing_disabled() { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.run("layer.template", json!({"template":"polygons","name":"Areas"})).unwrap(); + app.run("tool.set", json!({"tool":"createPolygon"})).unwrap(); + add_vertex(&mut app, Tool::CreatePolygon, Coord::new(0., 0.)); + app.run("ui.pane.annotation", Value::Null).unwrap(); + app.run("ui.annotationCreateClassField", Value::Null).unwrap(); + app.run("ui.annotationClass", json!({"value":"lake"})).unwrap(); + add_vertex(&mut app, Tool::CreatePolygon, Coord::new(1., 0.)); + add_vertex(&mut app, Tool::CreatePolygon, Coord::new(0., 1.)); + let mark = app.session.notice_mark(); + finish_sketch(&mut app); + assert!(app.session.notices_since(mark).iter().any(|n| n.text.contains("started in Edit"))); + let data = &app.session.map().layer_by_name("Areas").unwrap().dataset; + assert_eq!(data.features.len(), 1); + assert!(data.value(0, data.field_index("class").unwrap()).is_null()); + add_vertex(&mut app, Tool::CreatePolygon, Coord::new(0., 0.)); + let mark = app.session.notice_mark(); + app.run("edit.enable", json!({"on":false})).unwrap(); + assert!(app.map.sketch.is_empty()); + assert!(app.session.notices_since(mark).iter().any(|n| n.text.contains("Editing was turned off"))); + } + #[test] fn annotation_navigation_pans_and_zooms_without_changing_viewing_angle() { let mut h = selection_harness(); diff --git a/crates/ui-egui/src/shapeconvert.rs b/crates/ui-egui/src/shapeconvert.rs index fe5b5e5928..c2b74d0b7d 100644 --- a/crates/ui-egui/src/shapeconvert.rs +++ b/crates/ui-egui/src/shapeconvert.rs @@ -79,8 +79,13 @@ pub(crate) fn pick(app: &mut RustGisApp, c: Coord, alt: bool) { | rustgis_engine::Tool::Circle | rustgis_engine::Tool::RotatedBox ) || !app.session.active_layer.is_some_and(|id| { - rustgis_engine::box_edit::check_layer(&app.session, id).is_ok() - && app.session.map().layer(id).is_some_and(|l| app.session.map().draws_at(l, app.session.scale())) + app.session.map().layer(id).is_some_and(|l| { + let point = app.ui.right == Some(RightPane::Annotation) + && l.geometry_type() == rustgis_engine::data::GeometryType::Point + && crate::annotation::is_annotation_layer(l) + && app.session.map().editing.settings.enabled; + (point || rustgis_engine::box_edit::check_layer(&app.session, id).is_ok()) && app.session.map().draws_at(l, app.session.scale()) + }) }) { return; } @@ -154,6 +159,10 @@ pub(crate) fn open(app: &mut RustGisApp, p: &Value) -> Result<(), String> { pub(crate) fn menu(app: &mut RustGisApp, ui: &mut egui::Ui) { let Some(target) = app.conversion.menu.filter(|t| t.current(app)) else { return }; let layer = target.layer; + if app.session.map().layer(layer).is_some_and(|l| l.geometry_type() == rustgis_engine::data::GeometryType::Point) { + crate::annotation_classes::menu(app, ui, layer, target.row); + return; + } // Imported GeoJSON has ordinary polygons until the user explicitly fits a shape. // Known annotation shapes already have handles and should not invite another fit. let annotating = app.ui.right == Some(RightPane::Annotation) diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index fa3911576a..77a2deaccb 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -243,8 +243,10 @@ you edit the value or choose units; click **Apply elevation** to apply the new i ### Annotating an image **Analyze → Annotate** opens the annotation pane. It is also available from **View → Windows** -and Command Search. Add a GeoTIFF and a polygon feature layer first, then choose the **Image** -and **Target layer** in the pane, enable editing, and choose Circle or Rotated Box. +and Command Search. Choose an optional GeoTIFF as the **Image**, choose an editable **Target layer**, and enable editing. +For a point layer, choose **Point** and click to place each feature. For a polygon layer, choose +**Polygon** and click vertices, then double-click to finish or press Escape to cancel. +Polygon layers also offer **Circle** and **Rotated Box**. Only these constrained tools use the construction grid. The ordinary tools remain available under Edit and share these settings. Selecting an image defaults the **New shape grid** to **Original image pixels**. RustGIS reads @@ -296,7 +298,7 @@ Cancel; wait for it before choosing a class. If cancelled, use **Retry class fie On GeoPackage/PostGIS editing layers, a new local field does not create a database column. Save Edits reports fields with no matching column and keeps their local values. Save the project or export GeoJSON to preserve them, or create the database column before annotating. -Each new circle or rotated box captures that class when the drag starts; +A point captures its class on click, a polygon at its first vertex, and a circle or rotated box when the drag starts; changing the default afterwards affects subsequent shapes. Other template defaults are kept. **No class default** leaves the class to the normal template/default rules.