Skip to content
Open
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: 0 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,6 @@ And alongside it:
[#596](https://github.com/opengeos/RustGIS/issues/596)).

### Edit
- Selecting and deleting rows of a standalone table (its cells, rows and fields are editable).
- Shared edges, so that moving one polygon boundary moves its neighbour's too
([#872](https://github.com/opengeos/RustGIS/issues/872)). Coincident vertices already move
together (`edit.moveSharedVertex`, with Shared Vertices on); boundaries with different vertex
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ edit.convertField layer? table? field type format? pivotYear?
edit.copy
edit.cut
edit.cutPolygon line
edit.delete
edit.delete table? rows?
edit.deleteBox layer? row featureId?
edit.deleteCircle layer? row featureId?
edit.deleteField layer? table? field
Expand Down
9 changes: 9 additions & 0 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ pub(crate) fn need_editable_selection(s: &Session) -> Option<&'static str> {
super::need_selection(s)
}

/// Editing is on and features are selected, or a standalone table is named (`edit.delete` with
/// `"table"` deletes the `"rows"` it is given: a table's selection is the attribute table's own).
pub(crate) fn need_editable_selection_or_table(s: &Session) -> Option<&'static str> {
if s.condition_table.is_some() && s.map().editing.settings.enabled {
return None;
}
need_editable_selection(s)
}

/// Most edits an archive keeps.
const MAX_ARCHIVE: usize = 100_000;

Expand Down
51 changes: 49 additions & 2 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ pub fn commands() -> Vec<C> {
C::new("edit.addFeature", "Create Feature", "Edit › Features", add_feature).inputs(super::design::new_feature_inputs).roles(&[]).effects(crate::policy::Effects::NONE)
.when(super::design::need_editable_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table: adds a row, without geometry or template), "geometry": GeoJSON geometry (lon/lat; left out for a table), "attributes"?: {field: value}, "template"?: feature template}"#),
C::new("edit.delete", "Delete", "Edit › Features", delete).roles(&[]).effects(crate::policy::Effects::NONE).key("Delete").when(super::design::need_editable_selection),
C::new("edit.delete", "Delete", "Edit › Features", delete).roles(&[]).effects(crate::policy::Effects::NONE).key("Delete").when(super::design::need_editable_selection_or_table)
.params(r#"{"table"?: name|id (a standalone table: deletes its "rows"; left out, every layer's selected features are deleted), "rows"?: [number] (with "table": the row numbers to delete, numbered from 0 as the read-rows tool's _row)}"#),
C::new("edit.setValue", "Edit Attribute", "Attribute Table", set_value).roles(&[]).effects(crate::policy::Effects::NONE).atomic()
.when(super::design::need_editable_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "row": number, "field": string (the exact name first; a name matching several fields only ignoring case is refused), "value": any, "classStyle"?: bool (a layer text field: ensure the applied class has a Unique Values colour rule, in the same undoable transaction)}"#),
Expand Down Expand Up @@ -927,7 +928,16 @@ fn decimal_text(t: &str) -> Option<(Value, Cut)> {
})
}

fn delete(s: &mut Session, _: &Json) -> CmdResult {
fn delete(s: &mut Session, p: &Json) -> CmdResult {
if let Some(result) = land_table_edit(s, p, "edit.delete") {
return result;
}
if p.get("table").is_some_and(|t| !t.is_null()) {
return delete_rows(s, p);
}
if p.get("rows").is_some_and(|r| !r.is_null()) {
return Err("rows are deleted from a standalone table (\"table\"); a layer's selected features are deleted without rows".into());
}
let mut n = 0;
let mut removed: Vec<(u32, Vec<super::design::Change>)> = Vec::new();
for l in &mut s.map_mut().layers {
Expand All @@ -954,6 +964,42 @@ fn delete(s: &mut Session, _: &Json) -> CmdResult {
Ok(json!({"deleted": n}))
}

/// `edit.delete` with `"table"`: deletes the `"rows"` of a standalone table, while editing is on.
/// A table's selection is the attribute table's own, so the rows to delete come with the call.
/// A row named twice is deleted once; a row the table doesn't have refuses the whole call, and
/// nothing is deleted. Runs on the desktop table worker ([`table_ahead`]): the rows to keep are
/// marked with progress and Cancel, then removed in one pass that can't be interrupted.
fn delete_rows(s: &mut Session, p: &Json) -> CmdResult {
let t = write_target(s, p)?;
let Target::Table(_) = t else { return Err("rows are deleted from a standalone table (\"table\")".into()) };
editing_on(s)?;
let rows = p.get("rows").and_then(Json::as_array).ok_or("rows is required: the row numbers to delete, such as [0, 3]")?;
let ds = data_mut(s, t)?;
let len = ds.features.len();
let mut doomed = Vec::with_capacity(rows.len());
for row in rows {
match row.as_u64().and_then(|r| usize::try_from(r).ok()) {
Some(r) if r < len => doomed.push(r),
_ => return Err(format!("the table has no row {row} (it has {len}, numbered from 0); nothing was deleted")),

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 row number that isn't a whole number is refused with the wrong reason here. For 2.0 or 1.5, as_u64() is None, so this arm says "the table has no row 2.0 (it has 4, numbered from 0)", which suggests the row is out of range when the value is the wrong type. Splitting the two cases gives the caller the right fix. Confidence: high that the message is misleading; the refusal itself is correct and nothing is deleted.

Suggested change
_ => return Err(format!("the table has no row {row} (it has {len}, numbered from 0); nothing was deleted")),
Some(_) => return Err(format!("the table has no row {row} (it has {len}, numbered from 0); nothing was deleted")),
None => return Err(format!("{row} isn't a row number: give whole numbers from 0; nothing was deleted")),

Category: quality

}
}
doomed.sort_unstable();
doomed.dedup();
let n = doomed.len();
if n > 0 {
rustgis_data::progress::begin(len);
let mut keep = vec![true; len];
for (i, k) in keep.iter_mut().enumerate() {
rustgis_data::progress::step(1).map_err(|e| e.to_string())?;
*k = doomed.binary_search(&i).is_err();
}
let mut kept = keep.into_iter();
ds.features.retain_rows(|_| kept.next().unwrap_or(true));
}
s.notify(format!("Deleted {n} rows"), false);

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.

Nit: a single deleted row is reported as "Deleted 1 rows". Use the singular here. (The rows is required error at line 976 also fires when rows is given but isn't a list, such as "rows": 3. Its message could say that it must be a list of row numbers.)

Suggested change
s.notify(format!("Deleted {n} rows"), false);
s.notify(if n == 1 { "Deleted 1 row".to_string() } else { format!("Deleted {n} rows") }, false);

Category: quality

Ok(json!({"deleted": n}))
}

/// A numeric conversion's loss, shared by edits and feature creation. Null entered explicitly is quiet.
fn numeric_loss(input: &Value, v: &Value, ty: FieldType) -> Option<CellLoss> {
if ty.is_numeric() && v.is_null() && !input.asks_null() {
Expand Down Expand Up @@ -1831,6 +1877,7 @@ pub(crate) const TABLE_EDITS: &[(&str, &str, fn(&mut Session, &Json) -> CmdResul
("edit.deleteField", "Delete Field", delete_field),
("edit.convertField", "Convert Field", convert_field),
("edit.calculateField", "Calculate Field", calculate_field),
("edit.delete", "Delete Rows", delete),
];

/// The registered command and progress label for a table write. Layer invocations keep their
Expand Down
64 changes: 64 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,70 @@ fn a_standalone_table_is_edited_with_the_edit_commands() {
assert_eq!((serde_json::to_value(&s.project.tables).unwrap(), s.undo_depth()), before);
}

/// `edit.delete` with a table deletes the rows it names, once each, in one Undo step, leaving the
/// map's selected features alone; without a table it still deletes the layers' selection. Rows
/// the table doesn't have, rows without a table, editing turned off, and a table that isn't there
/// are refused, deleting nothing.
#[test]
fn a_standalone_tables_rows_are_deleted_by_number() {
let mut s = world();
s.run(
"layer.addDataText",
&json!({"fileName": "sites.csv", "text": "id,street\n1,Champ de Mars\n2,Rue Cler\n3,Quai Branly\n4,Avenue Rapp\n"}),
)
.unwrap();
s.run("edit.enable", &json!({"on": true})).unwrap();
s.active_layer = None;
let cities = s.map().layers.iter().find(|l| l.name == "Cities").unwrap().id;
s.run("select.rows", &json!({"layer": cities, "rows": [0, 1]})).unwrap();
let layers = serde_json::to_value(&s.map().layers).unwrap();
let ids = |s: &Session| -> Vec<String> {
let t = &s.project.tables[0].dataset;
(0..t.features.len()).map(|r| t.value(r, 0).to_string()).collect()
};
let depth = s.undo_depth();
let mark = s.notice_mark();
let answer = s.run("edit.delete", &json!({"table": "sites", "rows": [2, 0, 2]})).unwrap();
assert_eq!(answer, json!({"deleted": 2}));
assert_eq!(ids(&s), ["2", "4"]);
assert!(s.notices_since(mark).iter().any(|n| n.text == "Deleted 2 rows"));
assert_eq!(s.undo_depth(), depth + 1);
assert_eq!(serde_json::to_value(&s.map().layers).unwrap(), layers, "the map's selection is left alone");
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(ids(&s), ["1", "2", "3", "4"]);
// No rows named deletes nothing.
assert_eq!(s.run("edit.delete", &json!({"table": "sites", "rows": []})).unwrap(), json!({"deleted": 0}));

// Refused, and nothing changes.
let before = (serde_json::to_value(&s.project.tables).unwrap(), serde_json::to_value(&s.map().layers).unwrap());
for p in [
json!({"table": "sites", "rows": [1, 4]}),
json!({"table": "sites", "rows": [-1]}),
json!({"table": "sites", "rows": ["1"]}),
json!({"table": "sites", "rows": [4_294_967_296u64]}),
json!({"table": "sites"}),
json!({"table": "nope", "rows": [0]}),
json!({"table": "sites", "layer": "Cities", "rows": [0]}),
json!({"rows": [0]}),
] {
assert!(s.run("edit.delete", &p).is_err(), "{p}");
assert_eq!((serde_json::to_value(&s.project.tables).unwrap(), serde_json::to_value(&s.map().layers).unwrap()), before, "{p}");
}
let err = s.run("edit.delete", &json!({"table": "sites", "rows": [7]})).unwrap_err();
assert!(err.contains("no row 7") && err.contains("nothing was deleted"), "{err}");
s.run("edit.enable", &json!({"on": false})).unwrap();
let err = s.run("edit.delete", &json!({"table": "sites", "rows": [0]})).unwrap_err();
assert!(err.contains("editing is turned off"), "{err}");
assert_eq!(ids(&s), ["1", "2", "3", "4"]);
s.run("edit.enable", &json!({"on": true})).unwrap();

// Without a table, the layers' selected features go, as before; the table stays.
let n = s.map().layer(cities).unwrap().dataset.features.len();
assert_eq!(s.run("edit.delete", &Value::Null).unwrap(), json!({"deleted": 2}));
assert_eq!(s.map().layer(cities).unwrap().dataset.features.len(), n - 2);
assert_eq!(ids(&s), ["1", "2", "3", "4"]);
}

#[test]
fn a_saved_selection_is_read_in_range_in_order_and_once() {
// A selection edited by hand: a row repeated, out of order, and one past the layer's end.
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/tests/cancellation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ pub(super) fn long_commands(boundaries: bool) {
("edit.deleteField", json!({"table": "calc", "field": "day"})),
("edit.convertField", json!({"table": "calc", "field": "day", "type": "date", "format": "%m/%d/%Y"})),
("edit.calculateField", json!({"table": "calc", "field": "n", "expression": "n * 2"})),
("edit.delete", json!({"table": "calc", "rows": [0]})),
];
assert_eq!(listed(&edits), crate::cmd::edit::TABLE_EDITS.iter().map(|(id, ..)| *id).collect(), "add a new table worker here");
for (command, p) in edits {
Expand Down
38 changes: 34 additions & 4 deletions crates/ui-egui/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1137,9 +1137,12 @@ fn text_takes(chord: Option<crate::keymap::Chord>, typing: bool, text_field: boo

/// Whether Select All's key is left alone, with `pane` in use: while text is typed or a text field
/// has the focus (`in_text`: the key selects its text), and where there are no features to select
/// (a layout, Model Designer, a standalone table's view).
/// (a layout, Model Designer, an attribute table showing neither a layer nor a standalone table).
fn select_all_left_alone(app: &RustGisApp, pane: Pane, in_text: bool) -> bool {
in_text || app.session.active_layout.is_some() || app.mb.shown() || (pane == Pane::Table && app.session.table_layer.is_none())
in_text
|| app.session.active_layout.is_some()
|| app.mb.shown()
|| (pane == Pane::Table && app.session.table_layer.is_none() && app.session.table_standalone.is_none())
}

/// Whether command `id` acts on what a click picks (the layer, the tab, the features). A frame
Expand Down Expand Up @@ -1223,9 +1226,12 @@ fn run_keys(app: &mut RustGisApp, ctx: &egui::Context, run: &[(String, Value, Pa
crate::circleedit::cancel(app);
continue;
}
// A Delete bound with its own target (a standalone table's "table" and "rows") deletes
// that wherever it is pressed: the contextual deletes below are the plain key's.
let targeted_delete = id == "edit.delete" && ["table", "rows"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
// In the layer list, Delete removes the layers picked there, never the features selected
// on the map, a layout's element or a vertex (#2945).
if id == "edit.delete" && pane == Pane::Layers {
if id == "edit.delete" && !targeted_delete && pane == Pane::Layers {
remove_picked_layers(app);
continue;
}
Expand All @@ -1244,6 +1250,26 @@ fn run_keys(app: &mut RustGisApp, ctx: &egui::Context, run: &[(String, Value, Pa
let _ = app.run("select.all", json!({"layer": layer}));
continue;
}
// In a standalone table's view, Select All selects its rows and Delete deletes them, never
// the features selected on the map. Its selection is the view's own.
if pane == Pane::Table && id == "select.all" && p.get("layer").is_none() && crate::table::select_all_shown_table(app) {
continue;
}
if pane == Pane::Table
&& id == "edit.delete"
&& !targeted_delete
&& let Some((table, rows)) = crate::table::shown_table_selection(app)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
let params = json!({"table": table, "rows": rows});
let why = if rows.is_empty() { Some("nothing is selected") } else { app.session.why_blocked("edit.delete", &params) };
match why {
Some(why) => cannot_run(app, tl_raw!("Delete"), tl_raw!(why)),
None => {
let _ = app.run_by_user("edit.delete", params);
}
}
continue;
}
// On the tabs, and in a layout, Rename (F2) is for the map or layout in view, as a
// double-click on its tab is; elsewhere it renames the active layer (below).
if id == "layer.rename"
Expand All @@ -1256,6 +1282,7 @@ fn run_keys(app: &mut RustGisApp, ctx: &egui::Context, run: &[(String, Value, Pa
}
// With Edit Vertices, Delete removes the chosen vertex rather than the feature.
if id == "edit.delete"
&& !targeted_delete
&& app.session.active_layout.is_none()
&& app.session.tool == rustgis_engine::Tool::EditVertices
&& crate::vertexedit::delete_chosen(app)
Expand All @@ -1264,6 +1291,7 @@ fn run_keys(app: &mut RustGisApp, ctx: &egui::Context, run: &[(String, Value, Pa
}
// In a layout, Delete removes the selected element (and never the map's hidden features).
if id == "edit.delete"
&& !targeted_delete
&& let Some(li) = app.session.active_layout
{
// A locked element (or a frame with a locked surround) stays, and says why (#536).
Expand Down Expand Up @@ -1295,8 +1323,10 @@ fn run_keys(app: &mut RustGisApp, ctx: &egui::Context, run: &[(String, Value, Pa
}
// A command that can't run now says why, as its greyed ribbon button does (#456).
// Running out of undo or redo needs no word.
// A targeted Delete is judged with the rows it names, not by the map's selection.
let why = if targeted_delete { app.session.why_blocked(id, &p) } else { why_disabled(app, id) };
if !matches!(id, "edit.undo" | "edit.redo")
&& let Some(why) = why_disabled(app, id)
&& let Some(why) = why
{
let label = app.session.registry.get(id).map_or(id, |s| s.label);
cannot_run(app, tl_raw!(label), tl_raw!(why));
Expand Down
3 changes: 3 additions & 0 deletions crates/ui-egui/src/readjob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2173,6 +2173,7 @@ mod tests {
("edit.deleteField", json!({"table": "records", "field": "day"})),
("edit.convertField", json!({"table": "records", "field": "day", "type": "date"})),
("edit.calculateField", json!({"table": "records", "field": "n", "expression": "n + 1"})),
("edit.delete", json!({"table": "records", "rows": [0]})),
] {
let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default()));
app.run("layer.addDataText", json!({"fileName": "records.csv", "text": "n,day\n1,2026-01-01\n2,2026-01-02\n"})).unwrap();
Expand Down Expand Up @@ -2256,6 +2257,7 @@ mod tests {
("edit.setValue", json!({"table": "records", "row": 0, "field": "n", "value": 9})),
("edit.addFeature", json!({"table": "records", "attributes": {"n": 3}})),
("edit.calculateField", json!({"table": "records", "field": "n", "expression": "n + 1"})),
("edit.delete", json!({"table": "records", "rows": [1]})),
] {
let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default()));
app.run("layer.addDataText", json!({"fileName": "records.csv", "text": "n\n1\n2\n"})).unwrap();
Expand Down Expand Up @@ -2294,6 +2296,7 @@ mod tests {
("edit.deleteField", json!({"table": "records", "field": "day"}), false),
("edit.convertField", json!({"table": "records", "field": "day", "type": "date"}), false),
("edit.calculateField", json!({"table": "records", "field": "n", "expression": "n / 2"}), true),
("edit.delete", json!({"table": "records", "rows": [1, 0]}), true),
] {
let (mut app, mut expected) = (fixture(), fixture());
for app in [&mut app, &mut expected] {
Expand Down
Loading
Loading