diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index d413721370..062774dbb6 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -2,6 +2,7 @@ //! with the map) and edit values in place, a layer's or a standalone table's. mod dates; +mod rowmenu; use std::collections::HashMap; use std::sync::Weak; @@ -36,6 +37,8 @@ pub struct TableState { opened: u64, /// The answer of Statistics… for a column, shown in a window until it is closed. stats: Option, + /// The cell a row's right-click menu was last opened on. + menu: Option, } struct RowOrder { @@ -184,6 +187,7 @@ pub(crate) fn prune_views(app: &mut RustGisApp) { app.table.sort = None; app.table.sort_schema = None; app.table.row_order = None; + app.table.menu = None; app.table.opened = app.session.opened; } let project = &app.session.project; @@ -507,6 +511,8 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let mut delete_field: Option = None; // A cell double-clicked in a column whose name finds another field. let mut by_other_name = false; + // The row right-clicked, or whose menu is open. + let mut menu_row: Option = None; egui::ScrollArea::horizontal().show(ui, |ui| { let mut tb = TableBuilder::new(ui) .striped(true) @@ -619,11 +625,31 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { let sel = selection.contains(&r); row.set_selected(sel); let oid = ds.features.get(r).map(|f| f.id).unwrap_or(0); - row.col(|ui| { - ui.label(egui::RichText::new(oid.to_string()).size(11.5).color(t.text_dim)); + // The row's cells and the text in them, one response for its menu, + // and the cell right-clicked. + let mut over: Option = None; + let mut right: Option = None; + let mut take = |cell: egui::Response, text: Option, col: Option| { + let cell = match text { + Some(text) => cell | text, + None => cell, + }; + if cell.secondary_clicked() { + right = col; + } + match over.as_mut() { + Some(o) => *o |= cell, + None => over = Some(cell), + } + }; + let mut text = None; + let (_, cell) = row.col(|ui| { + text = Some(ui.label(egui::RichText::new(oid.to_string()).size(11.5).color(t.text_dim))); }); + take(cell, text, None); for &c in &shown { - row.col(|ui| { + let mut text = None; + let (_, cell) = row.col(|ui| { let editing = app.table.editing.as_ref().is_some_and(|e| e.fid == oid && e.col == c); if editing { if let Some(e) = app.table.editing.as_mut() { @@ -674,12 +700,20 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } else if resp.clicked() { clicked = Some((r, ui.input(|i| i.modifiers.command || i.modifiers.shift))); } + text = Some(resp); } }); + take(cell, text, Some(c)); } if row.response().clicked() { clicked = Some((r, row.response().ctx.input(|i| i.modifiers.command || i.modifiers.shift))); } + // A right-click wins over another row's menu, still open this frame. + if let Some(resp) = over + && (resp.secondary_clicked() || (menu_row.is_none() && resp.context_menu_opened())) + { + menu_row = Some(rowmenu::RowAt { resp, row: r, fid: oid, col: right }); + } }); }); }); @@ -799,6 +833,10 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { app.session.notify(e, true); } } + // Last, so a cell being typed in is kept before the menu's rows act. + if let Some(at) = menu_row { + rowmenu::show(app, key, at); + } }); statistics_window(app, ui.ctx()); } @@ -1131,6 +1169,158 @@ mod tests { assert!(h.state().table.editing.is_none(), "the editor closed"); } + /// A right-click on a row selects it, or keeps a selection it is in, and opens its menu, whose + /// rows act on those features of this layer alone: Zoom To; Copy; Delete, in one step to undo + /// and greyed while editing is off; and Copy Value for the cell clicked, the only row a + /// standalone table's menu can choose. + #[test] + fn right_clicking_a_row_opens_its_menu() { + use egui_kittest::kittest::NodeT; + use rustgis_engine::data::{Geometry, GeometryType}; + use rustgis_engine::geom::Coord; + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let points = |name: &str, rows: &[(&str, f64, f64)]| { + let mut ds = Dataset::new(name, GeometryType::Point, fields(&["Name"])); + for &(name, x, y) in rows { + ds.push(Some(Geometry::Point(Coord::new(x, y))), vec![V::Text(name.into())]); + } + ds + }; + let other = app.session.map_mut().add_dataset(points("Other", &[("Elsewhere", 1.0, 1.0)])); + let places = [("Alpha", 10.0, 20.0), ("Bravo", 40.0, -30.0), ("Charlie", -70.0, 5.0)]; + let id = app.session.map_mut().add_dataset(points("Places", &places)); + app.session.table_layer = Some(id); + app.session.run("edit.enable", &json!({"on": true})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1000.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + app.logic(&ui.ctx().clone()); + show(app, ui); + }, + app, + ); + h.run_steps(2); + let names = |app: &RustGisApp, layer: u32| -> Vec { + app.session.map().layer(layer).unwrap().dataset.features.column(0).map(ToString::to_string).collect() + }; + let selected = |app: &RustGisApp, layer: u32| app.session.map().layer(layer).unwrap().selection.clone(); + + // A row that isn't selected is selected alone, as a click on it does: the selection in + // another layer goes too. + h.state_mut().run("select.rows", json!({"layer": other, "rows": [0]})).unwrap(); + h.run_steps(2); + h.get_by_label("Bravo").click_secondary(); + h.run_steps(3); + assert_eq!(selected(h.state(), id), [1], "the right-click selected the row"); + assert!(selected(h.state(), other).is_empty(), "as a click does, in every layer"); + for row in ["Zoom To", "Remove from Selection", "Copy Ctrl+C", "Copy Value", "Delete Delete"] { + assert!(h.query_by_label(row).is_some(), "{row} is in the menu"); + } + h.get_by_label("Zoom To").click(); + h.run_steps(3); + let at = h.state().session.map().camera.center_lonlat(); + assert!((at.x - 40.0).abs() < 1e-3 && (at.y + 30.0).abs() < 1e-3, "zoomed to Bravo, not {at:?}"); + assert!(h.query_by_label("Zoom To").is_none(), "choosing a row closes the menu"); + + h.get_by_label("Charlie").click_secondary(); + h.run_steps(3); + h.get_by_label("Copy Value").click(); + h.step(); + assert_eq!(h.state().ui.copy_out.as_deref(), Some("Charlie")); + // The Feature ID cell opens the menu too, and its value is the feature's id. + let at = egui::pos2(h.get_by_label("Feature ID").rect().center().x, h.get_by_label("Charlie").rect().center().y); + h.event(egui::Event::PointerMoved(at)); + h.step(); + 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_steps(2); + h.get_by_label("Copy Value").click(); + h.step(); + let charlie = h.state().session.map().layer(id).unwrap().dataset.features.row(2).unwrap().id(); + assert_eq!(h.state().ui.copy_out.clone(), Some(charlie.to_string())); + + // A row inside a selection keeps it, and the menu acts on it all; the selection in another + // layer, which Delete would take too, is left behind. + h.state_mut().run("select.rows", json!({"layer": other, "rows": [0]})).unwrap(); + h.state_mut().run("select.rows", json!({"layer": id, "rows": [0, 2], "mode": "new"})).unwrap(); + h.state_mut().run("select.rows", json!({"layer": other, "rows": [0], "mode": "add"})).unwrap(); + h.run_steps(2); + h.get_by_label("Charlie").click_secondary(); + h.run_steps(3); + assert_eq!(selected(h.state(), id), [0, 2]); + assert_eq!(selected(h.state(), other), [0], "opening the menu changed nothing"); + assert!(h.query_by_label("Zoom To 2 Rows").is_some()); + // No keys beside Copy and Delete here: the keys would take the other layer's row too. + assert!(h.query_by_label("Copy 2 Rows Ctrl+C").is_none() && h.query_by_label("Delete 2 Rows Delete").is_none()); + h.get_by_label("Copy 2 Rows").click(); + h.run_steps(3); + let text = h.state().ui.copy_out.clone().unwrap(); + assert!(text.contains("Alpha") && text.contains("Charlie"), "{text}"); + assert!(!text.contains("Bravo") && !text.contains("Elsewhere"), "{text}"); + h.state_mut().run("select.rows", json!({"layer": other, "rows": [0], "mode": "add"})).unwrap(); + h.run_steps(2); + h.get_by_label("Charlie").click_secondary(); + h.run_steps(3); + h.get_by_label("Delete 2 Rows").click(); + h.run_steps(3); + assert_eq!(names(h.state(), id), ["Bravo"]); + assert_eq!(names(h.state(), other), ["Elsewhere"], "only this table's rows went"); + + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(names(h.state(), id), ["Alpha", "Bravo", "Charlie"], "one Undo restores them"); + + // One row, deleted alone and brought back by one Undo. + h.state_mut().run("select.clear", json!({})).unwrap(); + h.run_steps(2); + h.get_by_label("Alpha").click_secondary(); + h.run_steps(3); + h.get_by_label("Delete Delete").click(); + h.run_steps(3); + assert_eq!(names(h.state(), id), ["Bravo", "Charlie"]); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(names(h.state(), id), ["Alpha", "Bravo", "Charlie"]); + + // The fields change under an open menu: the cell it was opened on may be another field's + // now, so the menu closes rather than copy that one's value. + h.get_by_label("Bravo").click_secondary(); + h.run_steps(3); + assert!(h.query_by_label("Copy Value").is_some()); + h.state_mut().run("edit.addField", json!({"layer": id, "name": "Rank", "type": "long"})).unwrap(); + h.run_steps(3); + assert!(h.query_by_label("Copy Value").is_none(), "the menu closed"); + + h.state_mut().run("edit.enable", json!({"on": false})).unwrap(); + h.run_steps(2); + h.get_by_label("Bravo").click_secondary(); + h.run_steps(3); + assert!(h.get_by_label("Delete Delete").accesskit_node().is_disabled(), "editing is off"); + assert!(!h.get_by_label("Zoom To").accesskit_node().is_disabled()); + h.get_by_label("Remove from Selection").click(); + h.run_steps(3); + assert!(selected(h.state(), id).is_empty()); + + let table = h.state_mut().run("layer.addDataText", json!({"fileName": "sites.csv", "text": "Name\nDelta\n"})).unwrap(); + h.state_mut().session.table_layer = None; + h.state_mut().session.table_standalone = table["id"].as_u64().and_then(|id| u32::try_from(id).ok()); + 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"] { + assert!(h.get_by_label(row).accesskit_node().is_disabled(), "{row} can't act on a table's row"); + } + h.get_by_label("Copy Value").click(); + h.step(); + assert_eq!(h.state().ui.copy_out.as_deref(), Some("Delta")); + } + fn fields(names: &[&str]) -> Vec { names.iter().map(|n| Field::new(*n, rustgis_engine::data::FieldType::Text)).collect() } diff --git a/crates/ui-egui/src/table/rowmenu.rs b/crates/ui-egui/src/table/rowmenu.rs new file mode 100644 index 0000000000..580598558b --- /dev/null +++ b/crates/ui-egui/src/table/rowmenu.rs @@ -0,0 +1,255 @@ +//! The menu a right-click on a row of the attribute table opens. + +use egui::{Response, Ui}; +use rustgis_engine::data::Value; +use serde_json::json; + +use super::ViewKey; +use crate::RustGisApp; +use crate::widgets::{menu_row, shortcut_text, why_disabled}; + +/// The cell the menu was opened on. +#[derive(Clone, Copy)] +pub(super) struct Opened { + view: ViewKey, + /// The row's feature: when the row holds another one (the data changed under the menu), the + /// menu closes rather than act on it. + fid: u64, + /// The cell's field, or None for the Feature ID cell. + col: Option, + /// The fields the table had, and which standalone table it was ([`schema`]): with another + /// set, `col` may be another field, and the menu closes rather than copy its value. + fields: u64, +} + +/// A row on screen that was just right-clicked, or whose menu is open. +pub(super) struct RowAt { + /// The union of the row's cells and the text in them. + pub resp: Response, + /// The row's position in the dataset, whatever the table's sort and filter show. + pub row: usize, + pub fid: u64, + /// The field of the cell right-clicked in this frame (None: the Feature ID cell). + pub col: Option, +} + +/// Opens or keeps open the menu of a row. A right-click on a row that isn't selected first selects +/// it alone, as a click on it does (so nothing stays selected in other layers either); one inside +/// the selection keeps every selection, and the menu acts on this layer's. +pub(super) fn show(app: &mut RustGisApp, view: ViewKey, at: RowAt) { + if at.resp.secondary_clicked() { + app.table.menu = schema(app, view).map(|fields| Opened { view, fid: at.fid, col: at.col, fields }); + // Once, as the menu opens, and before it is drawn: its rows are judged by the selection. + if let Some(layer) = layer_id(app, view) + && app.session.map().layer(layer).is_some_and(|l| !l.selection.contains(&at.row)) + { + let _ = app.run("select.rows", json!({"layer": layer, "rows": [at.row], "mode": "new"})); + } + } + at.resp.context_menu(|ui| match view { + ViewKey::Layer(_) => layer_rows(app, ui, view, at.row), + ViewKey::Table(id) => table_row(app, ui, view, id, at.row), + }); +} + +/// The id of the layer a table view shows, on the map shown. +fn layer_id(app: &RustGisApp, view: ViewKey) -> Option { + let ViewKey::Layer(instance) = view else { return None }; + app.session.map().layers.iter().find(|l| l.instance_id() == instance).map(|l| l.id) +} + +/// The names of the fields of the layer or table `view` shows, in order, as one number: it +/// changes when a field is added, removed, renamed or moved. A standalone table's also changes +/// when another table takes its place under the same id (a layer's view is already its own). +fn schema(app: &RustGisApp, view: ViewKey) -> Option { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + let fields = match view { + ViewKey::Layer(_) => &app.session.map().layer(layer_id(app, view)?)?.dataset.fields, + ViewKey::Table(id) => { + let table = app.session.project.table(id)?; + table.instance_id().hash(&mut hasher); + &table.dataset.fields + } + }; + for field in fields { + field.name.hash(&mut hasher); + } + Some(hasher.finish()) +} + +/// The field of the cell the open menu was opened on, if row `row` of `view` still holds the +/// feature it had then (`live`, its id now) and the fields are the ones it had. +fn opened_cell(app: &RustGisApp, view: ViewKey, live: Option) -> Option> { + let fields = schema(app, view); + app.table.menu.filter(|m| m.view == view && Some(m.fid) == live && Some(m.fields) == fields).map(|m| m.col) +} + +/// A row of the menu that can't be chosen, saying why. +fn greyed(ui: &mut Ui, label: &str, why: &str) { + menu_row(ui, "", label, "", false).on_disabled_hover_text(why); +} + +/// A cell's value as Copy Value copies it: what the table shows, but a number in full, where the +/// table rounds it to six decimals. +fn cell_text(value: &Value) -> String { + match value { + Value::Float(number) => number.to_string(), + shown => shown.to_string(), + } +} + +/// Copy Value: the text of the cell the menu was opened on, as the table shows it (a picture, +/// shown as a word, gives its stored value; a number is copied in full). +fn copy_value(app: &mut RustGisApp, ui: &mut Ui, text: String) { + if menu_row(ui, "", tl!("Copy Value"), "", true).clicked() { + app.ui.copy_out = Some(text); + ui.close(); + } +} + +/// 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. +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 Some(text) = 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.")); + 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.")); +} + +/// What the menu of a layer's row shows, read from the layer as it is now. +struct LayerRow { + layer: u32, + /// The text Copy Value copies. + text: String, + selected: bool, + /// How many rows Zoom To, Copy and Delete act on: the layer's whole selection, when the row + /// is in it, as the toolbar's buttons take it (rows a filter hides among them). + count: usize, + /// Whether any of them has a shape to zoom to. + shaped: bool, + /// Whether no other layer has a selection: the Copy and Delete keys, which take every + /// layer's, then do what the menu's rows do, and the rows show them. + alone: bool, + streamed: bool, +} + +/// Reads [`LayerRow`] for row `row`, or None when the layer or the row has gone since the menu +/// opened, or the row holds another feature. +fn read_layer_row(app: &RustGisApp, view: ViewKey, row: usize) -> Option { + let layer = layer_id(app, view)?; + let l = app.session.map().layer(layer)?; + let features = &l.dataset.features; + let feature = features.row(row)?; + let col = opened_cell(app, view, Some(feature.id()))?; + let selected = l.selection.contains(&row); + let acted: &[usize] = if selected { &l.selection } else { std::slice::from_ref(&row) }; + Some(LayerRow { + layer, + text: col.map_or_else(|| feature.id().to_string(), |c| cell_text(feature.value(c))), + selected, + count: acted.len(), + shaped: acted.iter().any(|&r| features.geometry(r).is_some()), + alone: app.session.map().layers.iter().all(|o| o.id == layer || o.selection.is_empty()), + streamed: l.is_streamed(), + }) +} + +/// Makes the rows the menu acts on the whole selection of the map, which is what Zoom To +/// Selection, Copy and Delete take: the layer's selection when `row` is in it, else `row` alone, +/// with nothing selected in other layers. False when that selection couldn't be made, so the +/// command isn't run on another. +fn select_acted(app: &mut RustGisApp, layer: u32, row: usize) -> bool { + let map = app.session.map(); + let Some(l) = map.layer(layer) else { return false }; + let selected = l.selection.contains(&row); + if selected && map.layers.iter().all(|o| o.id == layer || o.selection.is_empty()) { + return true; + } + let rows = if selected { l.selection.clone() } else { vec![row] }; + app.run("select.rows", json!({"layer": layer, "rows": rows, "mode": "new"})).is_ok() +} + +/// Runs `command` on the rows the menu acts on (see [`select_acted`]). +fn run_on_acted(app: &mut RustGisApp, layer: u32, row: usize, command: &str) { + if select_acted(app, layer, row) { + // A refusal is said by `run`. + let _ = app.run(command, serde_json::Value::Null); + } +} + +/// The menu of a layer's row: Zoom To, Remove from Selection, Copy, Copy Value and Delete. Each +/// runs the command the table's toolbar or the ribbon runs. +fn layer_rows(app: &mut RustGisApp, ui: &mut Ui, view: ViewKey, row: usize) { + let Some(at) = read_layer_row(app, view, row) else { + ui.close(); + return; + }; + let several = at.count > 1; + let n = at.count.to_string(); + let args = [("n", n.as_str())]; + + let zoom = if several { crate::i18n::fmt("Zoom To {n} Rows", &args) } else { tl!("Zoom To").to_string() }; + let why = if several { tl!("None of these rows has a shape to zoom to.") } else { tl!("This row has no shape to zoom to.") }; + if menu_row(ui, "", &zoom, "", at.shaped).on_disabled_hover_text(why).clicked() { + run_on_acted(app, at.layer, row, "select.zoomTo"); + ui.close(); + } + // This row's alone: the whole selection is the toolbar's Clear selection. + let remove = if several { tl!("Remove This Row from Selection") } else { tl!("Remove from Selection") }; + if menu_row(ui, "", remove, "", at.selected).on_disabled_hover_text(tl!("This row isn't selected.")).clicked() { + let _ = app.run("select.rows", json!({"layer": at.layer, "rows": [row], "mode": "remove"})); + ui.close(); + } + ui.separator(); + // A key is shown only where it does what its row does: with a selection in another layer, + // the key takes that one too, and the row doesn't; and with this row no longer selected (a + // command changed the selection under the open menu), the key takes other rows. + let same = at.alone && at.selected; + let key = |app: &RustGisApp, ui: &Ui, command: &str| if same { shortcut_text(ui.ctx(), app, command) } else { String::new() }; + let shortcut = key(app, ui, "edit.copy"); + let copy = if several { crate::i18n::fmt("Copy {n} Rows", &args) } else { tl!("Copy").to_string() }; + if menu_row(ui, "", ©, &shortcut, true).clicked() { + run_on_acted(app, at.layer, row, "ui.copy"); + ui.close(); + } + copy_value(app, ui, at.text); + ui.separator(); + let shortcut = key(app, ui, "edit.delete"); + let delete = if several { crate::i18n::fmt("Delete {n} Rows", &args) } else { tl!("Delete").to_string() }; + // Greyed as the ribbon's Delete is, and for a layer whose edits the command refuses. + let why = why_disabled(app, "edit.delete").map(|why| tl!(why)).or_else(|| { + at.streamed.then(|| tl!("This layer is read in place from its file. Use Load All Features in the Layers pane to edit it.")) + }); + if menu_row(ui, "", &delete, &shortcut, why.is_none()).on_disabled_hover_text(why.unwrap_or_default()).clicked() { + run_on_acted(app, at.layer, row, "edit.delete"); + ui.close(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Copy Value copies a number in full, not rounded to the six decimals the table shows. + #[test] + fn copy_value_keeps_a_numbers_decimals() { + assert_eq!(cell_text(&Value::Float(1.234_567_89)), "1.23456789"); + assert_eq!(cell_text(&Value::Float(0.000_000_1)), "0.0000001"); + assert_eq!(cell_text(&Value::Float(42.0)), "42"); + assert_eq!(cell_text(&Value::Text("Alpha".into())), "Alpha"); + assert_eq!(cell_text(&Value::Null), ""); + } +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 505ace02ec..c04e43237c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -32,6 +32,16 @@ deletes the selection, adds or calculates a field, and calculates geometry attri The first column, **Feature ID**, shows each feature's identifier, not its current row position after sorting or filtering. It is not a dataset field: do not use it as a geoprocessing field name. +Right-click a row for **Zoom To**, **Remove from Selection**, **Copy** (the feature, as +**Copy** in the ribbon does), **Copy Value** (the text of the cell clicked; a number is copied in +full and a picture gives its stored data) and **Delete** (Undo brings the rows back; greyed while +editing is off and on a layer read in place from its file). A right-click on a row that isn't selected selects it alone first, as a click +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. + 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 map are unchanged. The toolbar says how many columns are hidden, and clicking it shows them all.