diff --git a/ROADMAP.md b/ROADMAP.md index bc90a6afc2..eb71641ee1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index cee173fd23..307ac35be9 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -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 diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0494af599a..5cb3dd9cb6 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -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; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d5ceafc03a..4ee04553d9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -28,7 +28,8 @@ pub fn commands() -> Vec { 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)}"#), @@ -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)> = Vec::new(); for l in &mut s.map_mut().layers { @@ -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")), + } + } + 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); + 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 { if ty.is_numeric() && v.is_null() && !input.asks_null() { @@ -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 diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index efb4f02d46..e74d0ea899 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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 { + 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. diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 518cb6d83a..44ddc15887 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -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 { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 6226a7378a..107758b92a 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1137,9 +1137,12 @@ fn text_takes(chord: Option, 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 @@ -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; } @@ -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) + { + let params = json!({"table": table, "rows": rows}); + let why = if rows.is_empty() { Some("nothing is selected") } else { app.session.why_blocked("edit.delete", ¶ms) }; + 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" @@ -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) @@ -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). @@ -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)); diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index b71832370f..fbcd5a07e0 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -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(); @@ -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(); @@ -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] { diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index 093b9c15c1..e2b8996a41 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -15,7 +15,7 @@ use rustgis_engine::data::{Dataset, Feature, Field, Value as V}; use serde_json::{Value, json}; use crate::theme::{Tokens, semibold}; -use crate::widgets::{small, small_for}; +use crate::widgets::{small, small_for, small_local}; use crate::{RustGisApp, icons}; pub(crate) use cursor::take_keys; @@ -48,6 +48,81 @@ pub struct TableState { keys: Vec, /// Whether the next frame scrolls the current cell into view. reveal: bool, + /// Each standalone table's selected rows, by table id: the attribute table's own (a layer's + /// selection is the layer's), kept for the session and not an Undo step. + table_selection: HashMap, +} + +/// The rows selected in a standalone table: dataset rows, sorted and once each, for the table +/// (`instance`) and the very rows (`source`) they were picked in. Any change to the rows forgets +/// them (rows deleted or added by the view, a script, the Assistant or Undo; a value edited; the +/// table replaced): a row number never points at another record, even when a delete and an add +/// leave as many rows as before. +struct TableSelection { + instance: u64, + /// The rows the numbers are for: a weak key, as [`RowOrder`]'s, that stops matching after any + /// change to them without keeping the old rows alive. + source: Weak>, + rows: Vec, +} + +impl TableSelection { + /// Whether these rows are still `table`'s, unchanged. + fn fits(&self, table: &rustgis_engine::project::Table) -> bool { + self.instance == table.instance_id() && self.source.ptr_eq(&table.dataset.features.allocation_key()) + } +} + +/// The standalone table the attribute table shows (none while it shows a layer), with its +/// selected rows: what Delete deletes there. +pub(crate) fn shown_table_selection(app: &RustGisApp) -> Option<(u32, Vec)> { + if app.session.table_layer.is_some() { + return None; + } + let table = app.session.project.table(app.session.table_standalone?)?; + Some((table.id, table_rows(&app.table.table_selection, table).to_vec())) +} + +/// Select All in the standalone table the attribute table shows: every row. False when it shows +/// none (a layer's view selects with `select.all`). +pub(crate) fn select_all_shown_table(app: &mut RustGisApp) -> bool { + if app.session.table_layer.is_some() { + return false; + } + let Some(table) = app.session.table_standalone.and_then(|id| app.session.project.table(id)) else { return false }; + let rows: Vec = (0..table.dataset.features.len()).collect(); + app.table.select_table_rows(table, &rows, "new"); + true +} + +/// Standalone table `table`'s selected rows in `selections`, while they still fit it. A function +/// of the selections alone, so the grid can hold them while it changes the rest of the state. +fn table_rows<'a>(selections: &'a HashMap, table: &rustgis_engine::project::Table) -> &'a [usize] { + match selections.get(&table.id) { + Some(sel) if sel.fits(table) => &sel.rows, + _ => &[], + } +} + +impl TableState { + /// Selects `rows` of standalone table `table` as `mode` says ("new", "add" or "remove"), as + /// `select.rows` selects a layer's. + fn select_table_rows(&mut self, table: &rustgis_engine::project::Table, rows: &[usize], mode: &str) { + let len = table.dataset.features.len(); + let mut now = if mode == "new" { Vec::new() } else { table_rows(&self.table_selection, table).to_vec() }; + let rows = rows.iter().copied().filter(|&r| r < len); + match mode { + "remove" => { + let gone: Vec = rows.collect(); + now.retain(|r| !gone.contains(r)); + } + _ => now.extend(rows), + } + now.sort_unstable(); + now.dedup(); + let source = table.dataset.features.allocation_key(); + self.table_selection.insert(table.id, TableSelection { instance: table.instance_id(), source, rows: now }); + } } struct RowOrder { @@ -199,9 +274,11 @@ pub(crate) fn prune_views(app: &mut RustGisApp) { app.table.row_order = None; app.table.menu = None; app.table.current = None; + app.table.table_selection.clear(); app.table.opened = app.session.opened; } let project = &app.session.project; + app.table.table_selection.retain(|id, sel| project.table(*id).is_some_and(|t| sel.fits(t))); let fields_for = |key: ViewKey| match key { ViewKey::Layer(instance) => { project.maps.iter().flat_map(|m| &m.layers).find(|l| l.instance_id() == instance).map(|l| &l.dataset.fields) @@ -418,7 +495,13 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let (ds, selected_n, title, key, table_instance) = match layer_id.and_then(|id| app.session.map().layer(id)) { Some(l) => (&l.dataset, l.selection.len(), l.name.clone(), ViewKey::Layer(l.instance_id()), None), None => match app.session.table_standalone.and_then(|id| app.session.project.table(id)) { - Some(tb) => (&tb.dataset, 0, tb.name.clone(), ViewKey::Table(tb.id), Some(tb.instance_id())), + Some(tb) => ( + &tb.dataset, + table_rows(&app.table.table_selection, tb).len(), + tb.name.clone(), + ViewKey::Table(tb.id), + Some(tb.instance_id()), + ), None => { app.session.table_standalone = None; return; @@ -516,6 +599,20 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let add_row = json!({"table": id}); let why = app.session.why_blocked("edit.addFeature", &add_row); small_for(ui, app, "new", "", "Add row", "edit.addFeature", add_row, why); + // Its selection is the table view's own: cleared here, deleted by number. + let rows: Vec = app + .session + .project + .table(id) + .map(|tb| table_rows(&app.table.table_selection, tb).to_vec()) + .unwrap_or_default(); + let none = rows.is_empty().then_some("nothing is selected"); + if small_local(ui, app, "clear_sel", "Clear selection", none.is_none(), none) { + app.table.table_selection.remove(&id); + } + let delete = json!({"table": id, "rows": rows}); + let why = none.or_else(|| app.session.why_blocked("edit.delete", &delete)); + small_for(ui, app, "delete", "", "Delete selected rows", "edit.delete", delete, why); small(ui, app, "field", "", "Add field", "ui.dialog", json!({"name": "addField", "table": id}), false); small( ui, @@ -528,6 +625,8 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { false, ); ui.add_space(6.0); + ui.checkbox(&mut app.table.selected_only, egui::RichText::new(tl!("Selected only")).size(11.5)); + ui.add_space(6.0); } ui.add(egui::TextEdit::singleline(&mut app.table.filter).hint_text(tl!("Filter rows…")).desired_width(160.0)); }); @@ -538,7 +637,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { // the frame's commands are resolved to what they need, below. let source = match key { ViewKey::Layer(_) => layer_id.and_then(|id| app.session.map().layer(id)).map(|l| (&l.dataset, l.selection.as_slice())), - ViewKey::Table(id) => app.session.project.table(id).map(|tb| (&tb.dataset, &[] as &[usize])), + ViewKey::Table(id) => app.session.project.table(id).map(|tb| (&tb.dataset, table_rows(&app.table.table_selection, tb))), }; let Some((ds, selection)) = source else { return }; let rows = RowOrder::displayed( @@ -546,7 +645,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { ds, app.table.sort, &app.table.filter, - (app.table.selected_only && is_layer).then_some(selection), + app.table.selected_only.then_some(selection), ); let row_count = rows.map_or(ds.features.len(), <[usize]>::len); let table = cursor::Shown { view: key, table_instance, ds, rows, columns: &shown }; @@ -859,7 +958,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { // Only the dialog's background scan takes a copy, and only when it opens. let convert = convert.and_then(|(i, ty)| field_name(i).map(|name| (i, ty, name, (!streamed).then(|| ds.clone())))); let delete_field = delete_field.and_then(field_name); - let clicked = clicked.filter(|_| is_layer).map(|(r, add)| { + let clicked = clicked.map(|(r, add)| { let mode = if add { if selection.contains(&r) { "remove" } else { "add" } } else { "new" }; (r, mode) }); @@ -902,7 +1001,17 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } } if let Some((r, mode)) = clicked { - let _ = app.run("select.rows", json!({"layer": layer_id, "rows": [r], "mode": mode})); + match key { + ViewKey::Layer(_) => { + let _ = app.run("select.rows", json!({"layer": layer_id, "rows": [r], "mode": mode})); + } + // A standalone table's selection is the view's own: no command, no Undo step. + ViewKey::Table(id) => { + if let Some(tb) = app.session.project.table(id) { + app.table.select_table_rows(tb, &[r], mode); + } + } + } } let ends = |editing: &Option, fid: u64, c: usize| editing.as_ref().is_some_and(|e| e.fid == fid && e.col == c); if let Some((fid, c)) = cancel @@ -1500,14 +1609,130 @@ mod tests { h.run_steps(2); h.get_by_label("Delta").click_secondary(); h.run_steps(3); - for row in ["Zoom To", "Remove from Selection", "Copy", "Delete"] { + for row in ["Zoom To", "Copy"] { assert!(h.get_by_label(row).accesskit_node().is_disabled(), "{row} can't act on a table's row"); } + // The right-click selected the row: it can leave the selection, and is deleted while + // editing is on. + assert!(!h.get_by_label("Remove from Selection").accesskit_node().is_disabled()); + assert!(h.get_by_label("Delete Delete").accesskit_node().is_disabled(), "editing is off"); h.get_by_label("Copy Value").click(); h.step(); assert_eq!(h.state().ui.copy_out.as_deref(), Some("Delta")); } + /// A standalone table's rows are selected as a layer's are (a click picks one, Ctrl-click adds + /// or takes one away, Ctrl+A picks them all) and deleted by the toolbar, the row menu or the + /// Delete key, each an Undo step. The selection is the table view's own: the map's selected + /// feature is never deleted from there, and a change to the rows forgets it. + #[test] + fn a_standalone_tables_rows_are_selected_and_deleted() { + use egui::Modifiers; + use egui_kittest::kittest::NodeT; + let (mut app, id) = places(); + app.run("select.rows", json!({"layer": id, "rows": [0]})).unwrap(); + let added = app.run("layer.addDataText", json!({"fileName": "sites.csv", "text": "Name\nEcho\nFoxtrot\nGolf\nHotel\n"})).unwrap(); + let table = added["id"].as_u64().and_then(|t| u32::try_from(t).ok()).unwrap(); + app.session.table_layer = None; + app.session.table_standalone = Some(table); + let mut h = window(app); + let names = |h: &Window| -> Vec { + let t = &h.state().session.project.table(table).unwrap().dataset; + (0..t.features.len()).map(|r| t.value(r, 0).to_string()).collect() + }; + let selected = |h: &Window| crate::table::shown_table_selection(h.state()).map(|(_, rows)| rows).unwrap_or_default(); + let places = |h: &Window| h.state().session.map().layer(id).unwrap().dataset.features.len(); + let undo = |h: &mut Window| { + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + }; + + h.get_by_label("Foxtrot").click(); + h.run_steps(3); + assert_eq!(selected(&h), [1]); + h.get_by_label("Hotel").click_modifiers(Modifiers::COMMAND); + h.run_steps(3); + assert_eq!(selected(&h), [1, 3]); + assert_eq!(h.state().session.map().layer(id).unwrap().selection, [0], "the map's selection is its own"); + let depth = h.state().session.undo_depth(); + h.get_by_label("Foxtrot").click_modifiers(Modifiers::COMMAND); + h.run_steps(3); + assert_eq!(selected(&h), [3]); + assert_eq!(h.state().session.undo_depth(), depth, "selecting a table's rows is no Undo step"); + + // A row deleted and another added elsewhere (a script, the command line) leave as many + // rows as before, but row 3 now holds another record: the selection is forgotten. + h.state_mut().run("edit.delete", json!({"table": table, "rows": [0]})).unwrap(); + h.state_mut().run("edit.addFeature", json!({"table": table, "attributes": {"Name": "India"}})).unwrap(); + h.run_steps(2); + assert_eq!(names(&h), ["Foxtrot", "Golf", "Hotel", "India"]); + assert!(selected(&h).is_empty(), "row 3 is India now, not the Hotel selected"); + undo(&mut h); + undo(&mut h); + assert_eq!(names(&h), ["Echo", "Foxtrot", "Golf", "Hotel"]); + assert!(selected(&h).is_empty(), "nor after Undo"); + // (The table's last rows sit under the status bar and the notices in this window: the + // clicks are on its first.) + h.get_by_label("Foxtrot").click(); + h.run_steps(3); + assert_eq!(selected(&h), [1]); + + // Selected only shows the selected rows. + h.get_by_label("Selected only").click(); + h.run_steps(3); + assert!(h.query_by_label("Echo").is_none() && h.query_by_label("Foxtrot").is_some()); + h.get_by_label("Selected only").click(); + h.run_steps(3); + + // The toolbar's Delete: one Undo step, and the selection is forgotten with the rows. + h.get_by_label("Delete selected rows").click(); + h.run_steps(3); + assert_eq!(names(&h), ["Echo", "Golf", "Hotel"]); + assert!(selected(&h).is_empty()); + assert!(h.get_by_label("Delete selected rows").accesskit_node().is_disabled(), "nothing is selected"); + undo(&mut h); + assert_eq!(names(&h), ["Echo", "Foxtrot", "Golf", "Hotel"]); + + // The Delete key deletes the table's selected rows, never the map's selected feature. + h.get_by_label("Echo").click(); + h.run_steps(3); + key(&mut h, egui::Key::Delete); + assert_eq!(names(&h), ["Foxtrot", "Golf", "Hotel"]); + assert_eq!(places(&h), 4, "the map's selected feature stays"); + undo(&mut h); + // With nothing selected in the table, Delete still leaves the map's feature alone. + key(&mut h, egui::Key::Delete); + assert_eq!((names(&h).len(), places(&h)), (4, 4)); + assert!(h.state().session.notices.iter().any(|n| n.text == "Delete: nothing is selected"), "said why"); + + // A key bound to delete given rows deletes those, not the rows selected in the view. + let f9 = crate::keymap::Chord::parse("F9").unwrap(); + h.state_mut().ui.keymap.assign(f9, "edit.delete", json!({"table": table, "rows": [3]})); + h.get_by_label("Echo").click(); + h.run_steps(3); + assert_eq!(selected(&h), [0]); + key(&mut h, egui::Key::F9); + assert_eq!(names(&h), ["Echo", "Foxtrot", "Golf"], "row 3 went, not the selected Echo"); + assert_eq!(places(&h), 4); + undo(&mut h); + h.state_mut().ui.keymap.remove(f9); + + // Ctrl+A selects every row, and the row menu deletes them all. (The table's last rows sit + // under the status bar in this window: the clicks are on its first.) + h.get_by_label("Echo").click(); + h.run_steps(3); + assert_eq!(selected(&h), [0]); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.run_steps(2); + assert_eq!(selected(&h), [0, 1, 2, 3]); + h.get_by_label("Echo").click_secondary(); + h.run_steps(3); + h.get_by_label("Delete 4 Rows Delete").click(); + h.run_steps(3); + assert!(names(&h).is_empty()); + assert_eq!(places(&h), 4); + } + type Window = egui_kittest::Harness<'static, RustGisApp>; /// The whole window, as its frames run, so the keys are read where a frame reads them and the diff --git a/crates/ui-egui/src/table/rowmenu.rs b/crates/ui-egui/src/table/rowmenu.rs index 580598558b..494fea29d2 100644 --- a/crates/ui-egui/src/table/rowmenu.rs +++ b/crates/ui-egui/src/table/rowmenu.rs @@ -45,6 +45,13 @@ pub(super) fn show(app: &mut RustGisApp, view: ViewKey, at: RowAt) { { let _ = app.run("select.rows", json!({"layer": layer, "rows": [at.row], "mode": "new"})); } + // A standalone table's selection is the view's own. + if let ViewKey::Table(id) = view + && let Some(table) = app.session.project.table(id) + && !super::table_rows(&app.table.table_selection, table).contains(&at.row) + { + app.table.select_table_rows(table, &[at.row], "new"); + } } at.resp.context_menu(|ui| match view { ViewKey::Layer(_) => layer_rows(app, ui, view, at.row), @@ -108,25 +115,46 @@ fn copy_value(app: &mut RustGisApp, ui: &mut Ui, text: String) { } } -/// The menu of a standalone table's row: only Copy Value can act, as no command selects, copies or -/// deletes such a row, and it has no shape on the map. +/// The menu of a standalone table's row: Remove from Selection, Copy Value and Delete (the +/// table's selection when the row is in it, else the row alone, as a layer's menu acts). Zoom To +/// and Copy are greyed: the row has no shape on the map and isn't a feature to paste. fn table_row(app: &mut RustGisApp, ui: &mut Ui, view: ViewKey, table: u32, row: usize) { let cell = app.session.project.table(table).and_then(|t| { let feature = t.dataset.features.row(row)?; let col = opened_cell(app, view, Some(feature.id()))?; - Some(col.map_or_else(|| feature.id().to_string(), |c| cell_text(feature.value(c)))) + let text = col.map_or_else(|| feature.id().to_string(), |c| cell_text(feature.value(c))); + let selected = super::table_rows(&app.table.table_selection, t); + let acted = if selected.contains(&row) { selected.to_vec() } else { vec![row] }; + Some((text, selected.contains(&row), acted)) }); - let Some(text) = cell else { + let Some((text, selected, acted)) = cell else { ui.close(); return; }; greyed(ui, tl!("Zoom To"), tl!("A standalone table has no features on the map.")); - greyed(ui, tl!("Remove from Selection"), tl!("A standalone table has no selection.")); + let several = acted.len() > 1; + let remove = if several { tl!("Remove This Row from Selection") } else { tl!("Remove from Selection") }; + if menu_row(ui, "", remove, "", selected).on_disabled_hover_text(tl!("This row isn't selected.")).clicked() { + if let Some(t) = app.session.project.table(table) { + app.table.select_table_rows(t, &[row], "remove"); + } + ui.close(); + } ui.separator(); greyed(ui, tl!("Copy"), tl!("A standalone table's rows can't be copied as features.")); copy_value(app, ui, text); ui.separator(); - greyed(ui, tl!("Delete"), tl!("A standalone table's rows can't be deleted.")); + let n = acted.len().to_string(); + let delete = if several { crate::i18n::fmt("Delete {n} Rows", &[("n", n.as_str())]) } else { tl!("Delete").to_string() }; + // The Delete key deletes the table's selection: shown where that is what this row does. + let shortcut = if selected { shortcut_text(ui.ctx(), app, "edit.delete") } else { String::new() }; + let params = json!({"table": table, "rows": acted}); + let why = app.session.why_blocked("edit.delete", ¶ms).map(|why| tl!(why)); + if menu_row(ui, "", &delete, &shortcut, why.is_none()).on_disabled_hover_text(why.unwrap_or_default()).clicked() { + // A refusal is said by `run`. + let _ = app.run("edit.delete", params); + ui.close(); + } } /// What the menu of a layer's row shows, read from the layer as it is now. diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ac1baf8f47..d246553094 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -613,6 +613,12 @@ pub fn small_for( small_button(ui, app, icon, label, desc, id, params, false, why.is_none(), why) } +/// A small icon button for what the interface keeps itself (a standalone table's selection), with +/// no command behind it: whether it was clicked while `on`. +pub fn small_local(ui: &mut Ui, app: &mut RustGisApp, icon: &str, desc: &str, on: bool, why: Option<&'static str>) -> bool { + small_drawn(ui, app, icon, "", desc, "", &Value::Null, false, on, why).clicked() && on +} + /// The small button [`small`] and [`small_for`] draw: `on` says whether it runs `id` when /// clicked, `why` why it doesn't, in its tooltip. fn small_button( @@ -626,6 +632,26 @@ fn small_button( checked: bool, on: bool, why: Option<&str>, +) -> Response { + let resp = small_drawn(ui, app, icon, label, desc, id, ¶ms, checked, on, why); + if resp.clicked() && on { + let _ = app.run_by_user(id, params); + } + resp +} + +/// Draws [`small_button`] without running anything. +fn small_drawn( + ui: &mut Ui, + app: &mut RustGisApp, + icon: &str, + label: &str, + desc: &str, + id: &str, + params: &Value, + checked: bool, + on: bool, + why: Option<&str>, ) -> Response { let (label, desc) = (tl!(label), tl!(desc)); let t = Tokens::get(ui.ctx()); @@ -646,11 +672,8 @@ fn small_button( ); } let title = if label.is_empty() { desc } else { label }; - let resp = tooltip_for(app, resp, title, if label.is_empty() { "" } else { desc }, id, ¶ms, why); - crate::showme::ring(ui, app, r, id, ¶ms); - if resp.clicked() && on { - let _ = app.run_by_user(id, params); - } + let resp = tooltip_for(app, resp, title, if label.is_empty() { "" } else { desc }, id, params, why); + crate::showme::ring(ui, app, r, id, params); resp } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 3a360b3082..968de15be8 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -55,8 +55,9 @@ editing is off and on a layer read in place from its file). A right-click on a r on it does. One on a selected row keeps the selection, and Zoom To, Copy and Delete then act on the layer's whole selection, as their labels count it and as the table's toolbar does (selected rows a filter hides are among them); choosing one of them clears any selection in other layers. -**Remove from Selection** takes out only the row clicked. In a standalone table only Copy Value -can be chosen; the other rows are greyed. +**Remove from Selection** takes out only the row clicked. In a standalone table, Zoom To and Copy +are greyed (its rows have no shape and aren't features to paste); Remove from Selection, Copy +Value and Delete act on its own selection. Right-click a column header for **Hide Column**, **Move Left**, **Move Right** and **Show All Columns**. A hidden column is only left out of the table: export, selection, expressions and the @@ -158,7 +159,8 @@ by case cannot be changed there. The `edit.*` commands take the table as `"table"` (its name or id) instead of `"layer"`: `edit.setValue`, `edit.addField`, `edit.deleteField`, `edit.convertField`, `edit.calculateField`, -and `edit.addFeature` with `"attributes"` and no geometry, which adds a row. As for a layer, a +`edit.addFeature` with `"attributes"` and no geometry, which adds a row, and `edit.delete` with +`"rows"`, which deletes them. As for a layer, a notice says when a field can't hold a value whole (a fraction in a whole-number field), and when an attribute names no field. A new row's attributes match exact field names first, then a unique match ignoring case; an ambiguous name is refused. When two keys reach the same field, a notice @@ -167,12 +169,24 @@ names the key left out. A table's rows live in the project, as they were copied in when it was added: edits change the project, not the CSV or other file the table came from. **Export Table** writes the edited table to a file: right-click the table in the Layers pane, or search for it in Command Search (scripts -use `share.exportTable`). Tables have no selection yet, so rows can't be deleted. +use `share.exportTable`). + +Select a standalone table's rows as a layer's: click a row, Ctrl-click (⌘-click) to add or take +one away, or press Ctrl+A (⌘A) for them all; **Selected only** then shows just those. While +editing is on, **Delete selected rows** in the toolbar, **Delete** in a row's menu or the Delete +key deletes them, and Undo brings them back. A table's selection belongs to its view: it isn't +saved with the project, selecting isn't an Undo step, and it is forgotten whenever the table's +rows change (a row added or deleted, a value edited, an Undo, by the view, a script or the +command line), so it never points at another row. With a table shown, Delete deletes its rows and +never the features selected on the map. Scripts and the command line delete rows by number with +`edit.delete`, giving `"table"` and `"rows"` (numbered from 0, the first row being 0). As with the +other table writes above, the AI Assistant can't delete a table's rows on the desktop. ```text edit.setValue={"table":"sites","row":0,"field":"street","value":"Rue Cler"} edit.addFeature={"table":"sites","attributes":{"id":3,"street":"Quai Branly"}} edit.calculateField={"table":"sites","field":"visits","expression":"visits + 1"} +edit.delete={"table":"sites","rows":[0,2]} ```