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
1 change: 1 addition & 0 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ edit.addBox layer? box attributes? template?
edit.addCircle layer? circle attributes? template?
edit.addFeature layer? table? geometry attributes? template?
edit.addField layer? table? name type
edit.addPoint x y crs? layer? name?
edit.applyShapeConversion preview confirm
edit.boxInfo layer? row
edit.calculateField layer? table? field expression
Expand Down
42 changes: 24 additions & 18 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,21 +194,6 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
};
zs.push((*r, z));
}
// Construction belongs to an object, not a reusable numeric id. Each removed or inserted
// feature that passes here (cut/paste, split pieces, edits) forgets its construction. Some
// row changes don't (GeoPackage and offline-area syncs, archive restore): there a feature
// keeps its construction only while its geometry still equals it (see `box_spec`). Undo
// keeps its own cache snapshot.
for change in &changes {
let feature = match (change.before(), change.row) {
(Some(before), None) => Some(before.id),
(None, Some(row)) => s.map().layer(id).and_then(|l| l.dataset.features.get(row)).map(|f| f.id),
_ => None,
};
if let Some(feature) = feature {
crate::construction::forget_feature(s, id, feature);
}
}
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
// New features: subtype defaults fill empty fields; elevation goes in `z`.
if let Some(st) = l.design.subtypes.clone()
Expand Down Expand Up @@ -376,6 +361,22 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
e.added += counts.added;
e.modified += counts.modified;
e.deleted += counts.deleted;
// All refusals are past: construction metadata changes only for a kept edit.
// Construction belongs to an object, not a reusable numeric id. Each removed or inserted
// feature that passes here (cut/paste, split pieces, edits) forgets its construction. Some
// row changes don't (GeoPackage and offline-area syncs, archive restore): there a feature
// keeps its construction only while its geometry still equals it (see `box_spec`). Undo
// keeps its own cache snapshot.
for change in &changes {
let feature = match (change.before(), change.row) {
(Some(before), None) => Some(before.id),
(None, Some(row)) => s.map().layer(id).and_then(|l| l.dataset.features.get(row)).map(|f| f.id),
_ => None,
};
if let Some(feature) = feature {
crate::construction::forget_feature(s, id, feature);
}
}
// Said once the edit is kept: a rejected one changed nothing.
for (rule, field, losses, ty) in cuts {
let by = crate::notice_text::NoticeText::format("Attribute rule {rule}", [("rule", rule.into())]);
Expand Down Expand Up @@ -2966,11 +2967,16 @@ pub(crate) fn new_feature_inputs(input: &super::InputContext<'_>, p: &Json) -> R
return Ok(inputs);
}
let mut inputs = super::Inputs::primary(s, p)?;
if let Elevation::Surface(name) = &s.map().editing.settings.elevation {
inputs.layers.extend(surface_layer(input, name).map(|l| (s.map().instance_id(), l.id)));
include_new_feature_surface(input, &mut inputs);
Ok(inputs)
}

/// Every new feature may sample the configured elevation raster, even in a newly created layer.
pub(super) fn include_new_feature_surface(input: &super::InputContext<'_>, inputs: &mut super::Inputs) {
if let Elevation::Surface(name) = &input.map().editing.settings.elevation {
inputs.layers.extend(surface_layer(input, name).map(|l| (input.map().instance_id(), l.id)));
inputs.state = json!({"surface":name});
}
Ok(inputs)
}

#[cfg(test)]
Expand Down
284 changes: 282 additions & 2 deletions crates/engine/src/cmd/edit.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -976,7 +976,7 @@ fn package_gp(s: &mut Session) -> Result<Vec<u8>, String> {
Ok(archive)
}

fn layer_template(s: &mut Session, p: &Value) -> CmdResult {
pub(super) fn layer_template(s: &mut Session, p: &Value) -> CmdResult {
let t = ps(p, "template").ok_or("template is required")?;
let text = |n: &str| Field::new(n, FieldType::Text);
let (gt, title, fields) = match t {
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -855,7 +855,7 @@ fn degrees_text(v: f64) -> String {
/// number or text in degrees, minutes and seconds. With it, what the reading assumed, for a
/// notice: two bare numbers taken in an order, or an MGRS square taken at its center (`moving`
/// says whether the map goes there, which the notice's wording follows).
fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option<crate::notice_text::NoticeText>), String> {
pub(crate) fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option<crate::notice_text::NoticeText>), String> {
let position = match p.get("position") {
None | Some(Value::Null) => None,
Some(Value::String(t)) => Some(t.as_str()),
Expand Down
29 changes: 29 additions & 0 deletions crates/engine/src/tests/review_boundaries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,35 @@ fn agent(access: AgentAccess) -> Scope {
Scope::agent(access, true, "review-boundaries", None, Arc::new(Live))
}

/// Remembered script approval must bind the coordinate system even at its unchanged origin.
#[test]
fn permission_review_coordinate_points_bind_the_resolved_system() {
use rustgis_data::raster::Crs;
use rustgis_data::{Dataset, GeometryType};
for system in ["map", "Reference"] {
let mut s = Session::new(crate::Project::default());
s.run("edit.enable", &json!({"on":true})).unwrap();
s.run("layer.template", &json!({"template":"points", "name":"Pins"})).unwrap();
let pins = s.active_layer.unwrap();
let reference = s.map_mut().add_dataset(Dataset::new("Reference", GeometryType::Point, vec![]));
let call = Call::script(&format!("edit.addPoint {}\nproject.connections {{}}", json!({"layer":"Pins","x":0,"y":0,"crs":system})));
let scope = Scope::assistant(2571, Arc::new(Live));
let Outcome::NeedsApproval(approved) = s.review(&scope, &call) else { panic!("the file-reading script needs review") };
let remembered = approved.remember().unwrap();
let Outcome::NeedsApproval(unchanged) = s.review(&scope, &call) else { panic!("unchanged script needs review") };
assert!(unchanged.covered_by(&remembered));
if system == "map" {
s.map_mut().projection = rustgis_map::globe::Projection::Custom("robinson".into());
} else {
s.map_mut().layer_mut(reference).unwrap().dataset.crs = Some(Crs::WebMercator);
}
let Outcome::NeedsApproval(changed) = s.review(&scope, &call) else { panic!("changed script needs review") };
assert!(!changed.covered_by(&remembered), "coordinate-system changes invalidate approval: {system}");
assert!(s.run_remembered(scope, &remembered, &call).is_err());
assert!(s.map().layer(pins).unwrap().dataset.features.is_empty());
}
}

#[test]
fn permission_review_authentication_changes_are_reserved() {
let s = world();
Expand Down
16 changes: 16 additions & 0 deletions crates/ui-egui/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,21 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) {
if crate::saveprompt::waiting(app) || ctx.memory(|m| m.top_modal_layer()).is_some() || app.ui.shortcut_editor.capturing() {
return;
}
// The repeat-use form is not modal: another pane or an unfinished sketch keeps Escape.
let point_dialog_owns_escape = app.dialogs.open == Some("createPointXY")
&& match ctx.memory(|m| m.focused()) {
Some(id) => ctx.read_response(id).is_some_and(|r| r.layer_id.id == egui::Id::unique(("dialog", "createPointXY"))),
None => {
app.map.sketch_len() == 0
&& !app.session.map().view.first_person
&& !crate::boxedit::drawing(app)
&& !crate::circleedit::drawing(app)
}
};
if point_dialog_owns_escape && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
app.dialogs.open = None;
return;
}
if app.ui.history_jump.is_some()
&& app.dialogs.open.is_none()
&& !crate::crspicker::list_is_open(ctx)
Expand Down Expand Up @@ -1117,6 +1132,7 @@ fn search_action(id: &str) -> Option<SearchAction> {
"project.coordinateSystem" => Dialog("projectProperties"),
"map.rename" => Dialog("renameMap"),
"map.goToXY" => Dialog("goToXY"),
"edit.addPoint" => Dialog("createPointXY"),
"map.exportOrbit" => Dialog("exportOrbit"),
"map.findPlace" => Dialog("findPlace"),
"map.camera" | "map.setScale" => Dialog("camera"),
Expand Down
181 changes: 181 additions & 0 deletions crates/ui-egui/src/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ impl Dialogs {
let name: &'static str = match which {
"selectByAttributes" => "selectByAttributes",
"goToXY" => "goToXY",
"createPointXY" => "createPointXY",
"bookmark" => "bookmark",
"addField" => "addField",
"calculateField" => "calculateField",
Expand Down Expand Up @@ -344,6 +345,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) {
let title = match which {
"selectByAttributes" => "Select By Attributes",
"goToXY" => "By Coordinates",
"createPointXY" => "Create Point by Coordinates",
"bookmark" => "New Bookmark",
"addField" => "Add Field",
"calculateField" => "Calculate Field",
Expand Down Expand Up @@ -439,6 +441,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) {
ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
match which {
"selectByAttributes" => close = select_by_attributes(app, ui, &t),
"createPointXY" => create_point_xy(app, ui),
"goToXY" => {
// UTM and MGRS are the Earth's grids, so another body's map offers degrees alone.
// A grid reference, once typed, is where Go goes: the X and Y boxes gray out.
Expand Down Expand Up @@ -1151,6 +1154,79 @@ pub fn open_dxf_path(app: &mut RustGisApp, path: &str) -> Result<Value, String>
open_dxf(app, path, DxfSource::Path(path.to_string()))
}

/// A repeat-use form: errors retain the entry, successful creation clears it and keeps focus
/// on X. The current selection is named each frame because this dialog is not modal.
fn create_point_xy(app: &mut RustGisApp, ui: &mut egui::Ui) {
let target = app
.session
.active_layer
.and_then(|id| app.session.map().layer(id))
.filter(|l| rustgis_engine::cmd::edit::accepts_coordinate_point(l));
let target = target.map(|l| l.name.clone()).unwrap_or_else(|| tl!("New Points layer").into());
ui.label(i18n::fmt("Add to: {layer}", &[("layer", &target)]));
if app.session.active_layer.and_then(|id| app.session.map().layer(id)).is_some_and(|l| l.dataset.windowed) {
ui.label(tl!("The selected layer is read in place. Points will go into a new layer instead."));
}
if !app.session.map().editing.settings.enabled {
ui.label(tl!("Turn editing on to add points."));
if ui.button(tl!("Enable Editing")).clicked()
&& let Err(e) = app.run("edit.enable", json!({"on":true}))
{
app.dialogs.error = Some(e);
}
}
ui.label(tl!("Coordinates use the system below, independently of the map. A new Points layer is saved in the project."));
// Status hints disappear after fallback/Enable Editing; field identities must not shift.
let label = ui.label(tl!("X / Longitude"));
let x = ui
.add(egui::TextEdit::singleline(&mut app.dialogs.a).id(egui::Id::unique(("createPointXY", "x"))).desired_width(f32::INFINITY))
.labelled_by(label.id);
let label = ui.label(tl!("Y / Latitude"));
ui.add(egui::TextEdit::singleline(&mut app.dialogs.b).id(egui::Id::unique(("createPointXY", "y"))).desired_width(f32::INFINITY))
.labelled_by(label.id);
let label = ui.label(tl!("Coordinate system (blank: longitude/latitude)"));
ui.add(
egui::TextEdit::singleline(&mut app.dialogs.c)
.id(egui::Id::unique(("createPointXY", "crs")))
.hint_text("EPSG:3857")
.desired_width(f32::INFINITY),
)
.labelled_by(label.id);
let label = ui.label(tl!("Name (optional)"));
ui.add(egui::TextEdit::singleline(&mut app.dialogs.text).id(egui::Id::unique(("createPointXY", "name"))).desired_width(f32::INFINITY))
.labelled_by(label.id);
ui.label(egui::RichText::new(tl!("Name uses a text field named name. Leave it blank if the selected layer has no such field.")).weak());
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift) && enter_is_the_dialogs(ui);
let t = Tokens::get(ui.ctx());
let (add, close) = ui
.horizontal(|ui| {
let add = crate::widgets::dialog_button(ui, tl!("Add Point"), Some(t.accent), vec2(110.0, 28.0)).clicked();
let close = crate::widgets::dialog_button(ui, tl!("Close"), None, vec2(110.0, 28.0)).clicked();
(add, close)
})
.inner;
if add || enter {
let crs = app.dialogs.c.trim();
let mut p = json!({"x":app.dialogs.a.trim(), "y":app.dialogs.b.trim(), "name":app.dialogs.text.trim()});
if !crs.is_empty() {
p["crs"] = json!(crs);
}
match app.run("edit.addPoint", p) {
Ok(_) => {
app.dialogs.a.clear();
app.dialogs.b.clear();
app.dialogs.text.clear();
app.dialogs.error = None;
x.request_focus();
}
Err(e) => app.dialogs.error = Some(e),
}
}
if close {
app.dialogs.open = None;
}
}

/// The systems Go To XY offers, as (what `map.goToXY` takes as `crs`, its label): degrees; on a
/// flat map of the Earth, the map's own; and each layer read in a projected system, by name (at
/// most [`XY_LAYER_SYSTEMS`], the first of each system). Also how many more systems the layers
Expand Down Expand Up @@ -4886,4 +4962,109 @@ mod tests {
assert!(h.query_by_label("Add").is_none(), "grouped features have no individual Add");
assert!(h.query_by_label("Remove").is_none(), "grouped features are removed in the Layers pane");
}

/// Drive the full app, including the shortcuts that own Escape and the dialog's Enter.
#[test]
fn coordinate_point_form_repeats_and_retains_invalid_input() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut app = RustGisApp::with_sample();
app.run("project.new", json!({})).unwrap();
app.run("edit.enable", json!({"on":true})).unwrap();
app.run("layer.template", json!({"template":"points", "name":"Read in place"})).unwrap();
let streamed = app.session.active_layer.unwrap();
app.session.map_mut().layer_mut(streamed).unwrap().dataset.windowed = true;
app.run("ui.dialog", json!({"name":"createPointXY"})).unwrap();
app.dialogs.a = "14.3".into();
app.dialogs.b = "-41.2".into();
app.dialogs.text = "Survey".into();
app.ws.recording = Some(Vec::new());
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1000.0)).with_max_steps(64).build_ui_state(
|ui, app: &mut RustGisApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
h.run_steps(4);
h.get_by_role_and_label(Role::Button, "Add Point").click();
h.run_steps(4);
assert_eq!(h.state().dialogs.open, Some("createPointXY"));
assert_eq!(h.state().dialogs.a, "");
assert_eq!(h.state().dialogs.b, "");
assert_eq!(h.state().dialogs.text, "");
let point_layer = h.state().session.active_layer.unwrap();
assert_eq!(h.state().session.map().layers.len(), 2);
assert_eq!(h.state().session.map().layer(point_layer).unwrap().dataset.features.len(), 1);
assert!(
h.state().ws.recording.as_ref().unwrap().last().unwrap().params.get("layer").is_none(),
"fallback records no incompatible target"
);
h.event(egui::Event::Text("bad".into()));
h.run_steps(3);
assert_eq!(h.state().dialogs.a, "bad", "successful fallback keeps typing in X after the streamed-layer hint disappears");
h.state_mut().dialogs.b = "0".into();
h.key_press(egui::Key::Enter);
h.run_steps(4);
assert!(h.state().dialogs.error.is_some());
assert_eq!(h.state().dialogs.a, "bad");
assert_eq!(h.state().session.map().layer(point_layer).unwrap().dataset.features.len(), 1);
h.state_mut().dialogs.a = "15".into();
h.key_press(egui::Key::Enter);
h.run_steps(4);
assert!(h.state().dialogs.error.is_none());
assert_eq!(h.state().session.map().layers.len(), 2);
assert_eq!(h.state().session.map().layer(point_layer).unwrap().dataset.features.len(), 2);
assert_eq!(
h.state().ws.recording.as_ref().unwrap().last().unwrap().params["layer"],
"Points",
"later points record their actual target"
);
h.state_mut().run("tool.set", json!({"tool":"measure"})).unwrap();
h.run_steps(3);
let at = h.state().map.view_rect.unwrap().0.right_bottom() - vec2(80.0, 80.0);
h.event(egui::Event::PointerMoved(at));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
}
h.run_steps(3);
assert_eq!(h.state().map.sketch_len(), 1);
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert_eq!(h.state().map.sketch_len(), 0);
assert_eq!(h.state().dialogs.open, Some("createPointXY"));
let shapes = h.state_mut().session.map_mut().add_dataset(rustgis_engine::data::Dataset::new(
"Shapes",
rustgis_engine::data::GeometryType::Polygon,
vec![],
));
h.state_mut().session.active_layer = Some(shapes);
for circle in [true, false] {
h.state_mut().run("tool.set", json!({"tool":if circle {"circle"} else {"rotatedBox"}})).unwrap();
h.run_steps(3);
let view = h.state().map.view_rect.unwrap().0;
let start = view.right_bottom() - vec2(120.0, 120.0);
if circle {
assert!(crate::circleedit::drag_start(h.state_mut(), view, start, true));
crate::circleedit::drag_to(h.state_mut(), view, start + vec2(40.0, 40.0));
} else {
assert!(crate::boxedit::drag_start(h.state_mut(), view, start, true));
crate::boxedit::drag_to(h.state_mut(), view, start + vec2(40.0, 40.0), false);
}
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(
!crate::circleedit::drawing(h.state()) && !crate::boxedit::drawing(h.state()),
"Escape cancels the active shape gesture"
);
assert_eq!(h.state().dialogs.open, Some("createPointXY"));
crate::circleedit::drag_stop(h.state_mut());
crate::boxedit::drag_stop(h.state_mut());
assert!(h.state().session.map().layer(shapes).unwrap().dataset.features.is_empty());
}
h.key_press(egui::Key::Escape);
h.run_steps(4);
assert_eq!(h.state().dialogs.open, None);
}
}
Loading
Loading