From ac46666e74df94ef2d22791cf1abb6b40420c1ed Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 08:20:08 -0600 Subject: [PATCH 1/3] fix(ui): export standalone tables from the Layers pane and Command Search A standalone table, such as a Summary Statistics result, couldn't be exported from the interface. The table's menu in the Layers pane and Command Search now open an Export Table dialog (ui.exportTable), which shares Export Features' dialog and export paths: share.exportTable on the export thread on the desktop, a download in the browser. --- crates/ui-egui/src/chrome.rs | 15 +++ crates/ui-egui/src/dialogs.rs | 136 +++++++++++++++++++++--- crates/ui-egui/src/lib.rs | 190 +++++++++++++++++++++++++++++----- crates/ui-egui/src/panes.rs | 61 +++++++++++ docs/user-guide/analysis.md | 5 +- docs/user-guide/sharing.md | 15 ++- 6 files changed, 373 insertions(+), 49 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 0286127841..aa825eb1c0 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1514,6 +1514,7 @@ fn search_action(id: &str) -> Option { "task.save" => SaveItem("task"), "share.exportMap" => Command("ui.exportMap"), "share.exportLayer" => Command("ui.exportLayer"), + "share.exportTable" => Command("ui.exportTable"), "share.exportRaster" => Command("ui.exportRaster"), "gp.run" => Command("ui.gp.open"), "gp.package" => SaveItem("gpPackage"), @@ -1588,6 +1589,9 @@ fn search_disabled(app: &RustGisApp, id: &str) -> Option<&'static str> { if let Some(reason) = search_platform_disabled(id, cfg!(target_arch = "wasm32")) { return Some(reason); } + if id == "share.exportTable" && app.session.project.tables.is_empty() { + return Some("the project has no standalone tables"); + } why_disabled(app, id).or_else(|| { (search_action(id).is_none() && app.session.registry.get(id).is_some_and(rustgis_engine::CommandSpec::needs_input)) .then_some("it needs input: open it from its pane or button, or run it from a script or the assistant") @@ -2445,6 +2449,17 @@ mod tests { assert!(app.map.toasts.iter().all(|t| t.error)); } + /// Command Search runs Export Table through its dialog, once there is a table to export. + #[test] + fn command_search_offers_export_table_for_a_standalone_table() { + use rustgis_engine::data::{Dataset, GeometryType}; + let mut app = crate::RustGisApp::with_sample(); + assert!(matches!(search_action("share.exportTable"), Some(SearchAction::Command("ui.exportTable")))); + assert_eq!(super::search_disabled(&app, "share.exportTable"), Some("the project has no standalone tables")); + app.session.project.add_table(Dataset::new("totals", GeometryType::None, vec![])); + assert_eq!(super::search_disabled(&app, "share.exportTable"), None); + } + #[test] fn desktop_only_search_actions_are_disabled_only_on_the_web() { for id in [ diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a938aa7f1d..6e07a3c2d1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4,6 +4,8 @@ use egui::{Align2, vec2}; use rustgis_engine::Session; use rustgis_engine::cmd::service_added::Removal; +use rustgis_engine::data::GeometryType; +use rustgis_engine::project::Table; use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use serde_json::{Value, json}; use std::collections::hash_map::DefaultHasher; @@ -101,6 +103,9 @@ pub struct Dialogs { /// The layer Export Features was opened on (its id and instance), exported whatever is /// selected while the dialog stays open. pub export_layer: Option<(u32, u64)>, + /// The standalone table picked in Export Table (its id and instance), refused once those + /// contents are gone: ids are reused by other projects. + pub export_table: Option<(u32, u64)>, pub flag: bool, pub error: Option, pub info: Option, @@ -151,23 +156,36 @@ pub enum DxfSource { } impl Dialogs { - /// Opens Add Field or Calculate Field (`which`) on standalone table `id`. + /// Opens Add Field, Calculate Field or Export Table (`which`) on standalone table `id`. pub fn open_on_table(&mut self, which: &str, s: &Session, id: u32) -> Result<(), String> { // The name kept is a `&'static str`, as `open` keeps it. let name: &'static str = match which { "addField" => "addField", "calculateField" => "calculateField", + "exportTable" => "exportTable", other => return Err(format!("dialog '{other}' doesn't open on a table")), }; - let dataset = &s.project.table(id).ok_or("no such table")?.dataset; + let table = s.project.table(id).ok_or("no such table")?; *self = Dialogs { open: Some(name), mode: "new", reset_collapse: true, table: Some((s.opened, id)), ..Dialogs::default() }; match name { "addField" => self.b = "Double".into(), - _ => self.a = calculation_fields(dataset).last().map(|f| f.name.clone()).unwrap_or_default(), + "exportTable" => { + // Every table can be written as CSV. + self.mode = "csv"; + self.gpkg_mode = "newFile"; + self.pick_export_table(table); + } + _ => self.a = calculation_fields(&table.dataset).last().map(|f| f.name.clone()).unwrap_or_default(), } Ok(()) } + /// Makes `table` the one Export Table writes, and names a GeoPackage's table after it. + fn pick_export_table(&mut self, table: &Table) { + self.export_table = Some((table.id, table.instance_id())); + self.text = table.dataset.name.clone(); + } + /// The standalone table the dialog acts on, as `"table"` names it in `p`; refused once another /// project is open, whose table of that id is another table. fn on_table(&self, s: &Session, mut p: Value) -> Result { @@ -418,6 +436,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { "s3Connections" => "Choose S3 connection", "zarr" => "Add Zarr Variable", "exportLayer" => "Export Features", + "exportTable" => "Export Table", "saveProject" => "Save Project As", "exportOrbit" => "Export Orbit", "renameMap" => "Rename Map", @@ -763,7 +782,8 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { "s3" => crate::s3ui::dialog(app, ui), "s3Connections" => close = crate::connectionui::s3_chooser(app, ui), "zarr" => close = crate::zarrui::dialog(app, ui), - "exportLayer" => close = export_layer(app, ui), + "exportLayer" => close = export_data(app, ui, false), + "exportTable" => close = export_data(app, ui, true), "camera" => { egui::Grid::new("cam").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { for (label, v) in @@ -1099,21 +1119,65 @@ pub(crate) fn export_formats(web: bool) -> impl Iterator bool { +/// The formats Export Table offers: [`export_formats`], less, for a table without geometry, +/// Shapefile and FlatGeobuf (which refuse it) and KML, KMZ and GPX (whose file would hold none +/// of its rows). +pub(crate) fn table_formats(web: bool, geometry: bool) -> impl Iterator { + export_formats(web).filter(move |(_, e)| geometry || !matches!(*e, "shp" | "fgb" | "kml" | "kmz" | "gpx")) +} + +/// Export Table's first row: the standalone table written, picked from the project's. One whose +/// contents are gone shows none, and is refused on export. +fn export_table_choice(app: &mut RustGisApp, ui: &mut egui::Ui) { + let label = ui.label(tl!("Table")); + let picked = app.dialogs.export_table; + let is_picked = |t: &Table| picked == Some((t.id, t.instance_id())); + let shown = app.session.project.tables.iter().find(|t| is_picked(t)).map_or("", |t| t.dataset.name.as_str()); + egui::ComboBox::from_id_salt("export_table_choice") + .selected_text(shown) + .width(220.0) + .show_ui(ui, |ui| { + for t in &app.session.project.tables { + if ui.selectable_label(is_picked(t), &t.dataset.name).clicked() { + app.dialogs.pick_export_table(t); + } + } + }) + .response + .labelled_by(label.id); +} + +/// Export Features (the active layer) and Export Table (`table`: a standalone table), in a format +/// picked here (a file's type isn't changed by the filter chosen in a save dialog, and the web +/// app has no save dialog). +fn export_data(app: &mut RustGisApp, ui: &mut egui::Ui, table: bool) -> bool { let web = app.services.download.is_some(); - egui::Grid::new("export_layer").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { - ui.label(tl!("Layer")); - ui.label(&app.dialogs.layer); + egui::Grid::new("export_data").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { + if table { + export_table_choice(app, ui); + } else { + ui.label(tl!("Layer")); + ui.label(&app.dialogs.layer); + } ui.end_row(); + let geometry = !table + || app + .dialogs + .export_table + .and_then(|(id, _)| app.session.project.table(id)) + .is_some_and(|t| t.dataset.geometry_type != GeometryType::None); + let formats = || table_formats(web, geometry); + // Another table picked may not take the format chosen for the last one. + if table && !formats().any(|(_, e)| *e == app.dialogs.mode) { + app.dialogs.mode = "csv"; + } let input_label = ui.label(tl!("Format")); let shown = EXPORT_FORMATS.iter().find(|(_, e)| *e == app.dialogs.mode).map(|(l, _)| *l).unwrap_or("GeoJSON"); egui::ComboBox::from_id_salt("export_format") .selected_text(shown) .width(220.0) .show_ui(ui, |ui| { - for (label, ext) in export_formats(web) { + for (label, ext) in formats() { ui.selectable_value(&mut app.dialogs.mode, *ext, *label); } }) @@ -1136,7 +1200,8 @@ fn export_layer(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { .labelled_by(into_label.id); ui.end_row(); if !matches!(app.dialogs.gpkg_mode, "" | "newFile") { - let table_label = ui.label(tl!("Table")); + // Export Table's first row is already labelled "Table". + let table_label = ui.label(if table { tl!("Table name") } else { tl!("Table") }); ui.add(egui::TextEdit::singleline(&mut app.dialogs.text).desired_width(220.0)).labelled_by(table_label.id); ui.end_row(); } @@ -1151,15 +1216,20 @@ fn export_layer(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { } buttons(app, ui, if web { "Download" } else { "Export…" }, |app| { let mut p = json!({"format": app.dialogs.mode}); - if let Some((layer, instance)) = app.dialogs.export_layer { - p["layer"] = json!(layer); + let (command, key, target) = if table { + ("ui.exportTable", "table", app.dialogs.export_table) + } else { + ("ui.exportLayer", "layer", app.dialogs.export_layer) + }; + if let Some((id, instance)) = target { + p[key] = json!(id); p["instance"] = json!(instance); } if into_existing { p["mode"] = json!(app.dialogs.gpkg_mode); p["tableName"] = json!(app.dialogs.text); } - app.run("ui.exportLayer", p).map(|_| ()) + app.run(command, p).map(|_| ()) }) } @@ -5034,6 +5104,42 @@ mod tests { assert_eq!(web, ["geojson", "parquet", "shp", "csv", "kml", "kmz", "gpx"]); } + /// Export Table opened with no table named takes the last added; picking another renames a + /// GeoPackage's table after it and drops a format that one can't take. + #[test] + fn export_table_follows_the_table_picked() { + use egui_kittest::kittest::Queryable; + use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + let mut app = RustGisApp::with_sample(); + assert!(app.run("ui.exportTable", json!({})).unwrap_err().contains("no standalone tables")); + let plain = app.session.project.add_table(Dataset::new("plain", GeometryType::None, vec![])); + let mut ds = Dataset::new("sites", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + ds.push(Some(Geometry::Point(rustgis_engine::geom::Coord::new(1.0, 2.0))), vec![Value::Int(1)]); + let sites = app.session.project.add_table(ds); + app.run("ui.exportTable", json!({})).unwrap(); + assert_eq!(app.dialogs.export_table.map(|(id, _)| id), Some(sites)); + assert_eq!((app.dialogs.mode, app.dialogs.text.as_str()), ("csv", "sites")); + app.dialogs.mode = "shp"; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.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); + assert_eq!(h.state().dialogs.mode, "shp", "a table with geometry takes a Shapefile"); + h.get_by_label("Table").click(); + h.run_steps(4); + // The Layers pane lists the table by this name too: the choice is the one drawn last. + h.query_all_by_label("plain").last().unwrap().click(); + h.run_steps(4); + let d = &h.state().dialogs; + assert_eq!(d.export_table.map(|(id, _)| id), Some(plain)); + assert_eq!((d.mode, d.text.as_str()), ("csv", "plain")); + } + /// The Rename… dialog shows why a name over 200 characters isn't taken and stays open with /// it, the layer keeping its name; a name of 200 renames it and closes the dialog (#1817). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8966523c7b..488895be99 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1672,6 +1672,38 @@ impl RustGisApp { } } + /// The file name Export Features and Export Table (`table`) suggest for layer or table `id`. + fn export_file_name(&self, id: u32, ext: &str, table: bool, annotation: bool) -> Result { + if !table { + return annotation::export_name(self, id, ext, annotation); + } + Ok(self.session.project.table(id).map(|t| format!("{}.{ext}", t.dataset.name)).unwrap_or_default()) + } + + /// The standalone table `ui.exportTable` acts on: the one `p` names, refused when it no longer + /// has the contents `"instance"` names (those Export Table was opened on), else the one in the + /// attribute table. + fn export_table_target(&self, p: &Value) -> Result { + let gone = || tl!("the table Export Table was opened on is gone").to_string(); + if p.get("table").is_none_or(Value::is_null) { + return self + .session + .table_standalone + .filter(|&id| self.session.project.table(id).is_some()) + .ok_or_else(|| tl!("open a standalone table first").to_string()); + } + let i = self.session.table_index(p)?; + let t = self.session.project.tables.get(i).ok_or_else(gone)?; + match p.get("instance") { + None | Some(Value::Null) => Ok(t.id), + Some(v) => match v.as_u64() { + Some(instance) if instance == t.instance_id() => Ok(t.id), + Some(_) => Err(gone()), + None => Err(crate::i18n::fmt("\"instance\" must be a table's instance number, not {value}", &[("value", &v.to_string())])), + }, + } + } + /// The Ctrl (⌘) shortcuts the keymap takes, as (Alt, Shift, key), the clipboard's left out: /// in a browser, what the web app keeps from the browser's own shortcuts (⌘D bookmarking /// the page, ⌘Y opening its history, ⌘= zooming it), as design tools in the browser do. @@ -5636,31 +5668,54 @@ impl RustGisApp { "ui.exportLayer" if p.get("format").and_then(Value::as_str).is_none() => { self.dialogs.open("exportLayer", &self.session)?; } - "ui.exportLayer" | "ui.annotationExport" if self.services.download.is_some() => { + // Without a format, the Export Table dialog asks for one, opened on the table named, + // else the one in the attribute table, else the last added. + "ui.exportTable" if p.get("format").and_then(Value::as_str).is_none() => { + let tables = &self.session.project.tables; + let id = match self.export_table_target(p) { + Err(_) if p.get("table").is_none_or(Value::is_null) => { + tables.last().map(|t| t.id).ok_or_else(|| tl!("the project has no standalone tables").to_string())? + } + target => target?, + }; + self.dialogs.open_on_table("exportTable", &self.session, id)?; + } + "ui.exportLayer" | "ui.annotationExport" | "ui.exportTable" if self.services.download.is_some() => { let annotation_export = id == "ui.annotationExport"; - let id = self.export_target(p)?; - let construction_notes = self.session.layer_construction_output_notes(id)?; - let l = self.session.map().layer(id).ok_or_else(|| tl!("select a layer in the Layers pane first").to_string())?; + let table = id == "ui.exportTable"; + let id = if table { self.export_table_target(p)? } else { self.export_target(p)? }; + let construction_notes = if table { Default::default() } else { self.session.layer_construction_output_notes(id)? }; // Any format the dialog offers here (`dialogs::export_formats`): not GeoPackage or // FlatGeobuf, which the data crate refuses in the browser. let ext = p.get("format").and_then(Value::as_str).unwrap_or("geojson").to_ascii_lowercase(); let download_ext = if ext == "shp" { "zip".to_string() } else { ext.clone() }; - let name = annotation::export_name(self, id, &download_ext, annotation_export)?; + let name = self.export_file_name(id, &download_ext, table, annotation_export)?; rustgis_engine::cmd::share::gpkg_table(p, &ext)?; - // A streamed layer exports its whole source, not the features read for the view. use std::borrow::Cow; - let (mut ds, lost) = if l.is_streamed() { - let (dataset, lost) = l.load_all_counted()?; - (Cow::Owned(dataset), lost) + let (mut ds, lost, query, source_name) = if table { + let t = + self.session.project.table(id).ok_or_else(|| tl!("the table Export Table was opened on is gone").to_string())?; + (Cow::Borrowed(&t.dataset), Default::default(), None, t.dataset.name.clone()) } else { - (Cow::Borrowed(&l.dataset), Default::default()) + let l = self.session.map().layer(id).ok_or_else(|| tl!("select a layer in the Layers pane first").to_string())?; + // A streamed layer exports its whole source, not the features read for the view. + let (ds, lost) = if l.is_streamed() { + let (dataset, lost) = l.load_all_counted()?; + (Cow::Owned(dataset), lost) + } else { + (Cow::Borrowed(&l.dataset), Default::default()) + }; + (ds, lost, l.definition_query.as_deref(), l.name.clone()) }; - let query_report = - rustgis_engine::data::export::filter_dataset(&mut ds, l.definition_query.as_deref()).map_err(|e| e.to_string())?; - let layer_name = l.name.clone(); - // In the layer's own coordinate system, as share.exportLayer writes a file. + let query_report = rustgis_engine::data::export::filter_dataset(&mut ds, query).map_err(|e| e.to_string())?; + // A layer in its own coordinate system, as share.exportLayer writes a file; a table + // in longitude/latitude, as share.exportTable does. use rustgis_engine::data::io; - let (crs, default_note) = io::default_export_in(&ds, &name, self.session.project.coordinate_system); + let (crs, default_note) = if table { + (rustgis_engine::data::raster::Crs::LonLat, None) + } else { + io::default_export_in(&ds, &name, self.session.project.coordinate_system) + }; let written = io::write_bytes_noted(&ds, &ext, crs, &name).map_err(|e| e.to_string()); let (bytes, left_out, unplaced, extent) = match written { Ok(w) => w, @@ -5692,7 +5747,7 @@ impl RustGisApp { if lost.rows > 0 { dbf_notes.push(rustgis_engine::cmd::whole::unread_note(&name, lost.rows)); } - dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.name, &lost)); + dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &source_name, &lost)); // CSV holds a point a row, GPX a name for each feature and no areas; reading text back, CSV reads blanks as null and KML and GPX trim it. dbf_notes.extend(io::export_losses_notes(&ds, &ext, io::name_field(&ds), &name).map_err(|e| e.to_string())?); // NaN and infinities, which GeoJSON can't hold, written as null. @@ -5707,7 +5762,7 @@ impl RustGisApp { )); } if self.download(&name, bytes) { - rustgis_engine::cmd::share::notify_export_query(&mut self.session, &name, &layer_name, &query_report); + rustgis_engine::cmd::share::notify_export_query(&mut self.session, &name, &source_name, &query_report); rustgis_engine::cmd::share::notify_null_numbers(&mut self.session, &name, null_numbers); for note in notes.into_iter().chain(dbf_notes).chain(construction_notes) { self.session.say(note); @@ -5797,8 +5852,10 @@ impl RustGisApp { return self.run("share.exportMap", args); } } - "ui.exportLayer" | "ui.annotationExport" => { + "ui.exportLayer" | "ui.annotationExport" | "ui.exportTable" => { let annotation_export = id == "ui.annotationExport"; + let table = id == "ui.exportTable"; + let (command, key) = if table { ("share.exportTable", "table") } else { ("share.exportLayer", "layer") }; let ext = p.get("format").and_then(Value::as_str).unwrap_or("geojson").to_ascii_lowercase(); let label = dialogs::EXPORT_FORMATS .iter() @@ -5808,9 +5865,11 @@ impl RustGisApp { // Into a GeoPackage that exists: picked to open, as it is kept, not replaced. // Checked as the command checks them, before a file is asked for; then passed on. let gpkg = rustgis_engine::cmd::share::gpkg_table(p, &ext)?; - let id = self.export_target(p)?; - let name = annotation::export_name(self, id, &ext, annotation_export)?; - let with_table = |mut args: Value| { + let id = if table { self.export_table_target(p)? } else { self.export_target(p)? }; + let name = self.export_file_name(id, &ext, table, annotation_export)?; + let arguments = |path: String| { + let mut args = json!({"path": path}); + args[key] = json!(id); for key in ["mode", "tableName"] { if let Some(v) = p.get(key) { args[key] = v.clone(); @@ -5820,11 +5879,11 @@ impl RustGisApp { }; if gpkg.mode != rustgis_engine::data::io::GpkgMode::NewFile { if let Some(path) = dialogs::pick_open(&["gpkg"], label) { - let args = with_table(json!({"layer": id, "path": path})); + let args = arguments(path); #[cfg(not(target_arch = "wasm32"))] - return exportjob::start(self, "share.exportLayer", args); + return exportjob::start(self, command, args); #[cfg(target_arch = "wasm32")] - return self.run("share.exportLayer", args); + return self.run(command, args); } return Ok(Value::Null); } @@ -5834,11 +5893,11 @@ impl RustGisApp { let typed = std::path::Path::new(&path).extension().is_some_and(|e| e.eq_ignore_ascii_case(&ext)); let path = if typed { path } else { format!("{path}.{ext}") }; // Written on a thread of its own, with progress and Cancel in the status bar. - let args = with_table(json!({"layer": id, "path": path})); + let args = arguments(path); #[cfg(not(target_arch = "wasm32"))] - return exportjob::start(self, "share.exportLayer", args); + return exportjob::start(self, command, args); #[cfg(target_arch = "wasm32")] - return self.run("share.exportLayer", args); + return self.run(command, args); } } // Add Zarr Variable, connected to a store (a link, a script). @@ -9883,6 +9942,83 @@ mod download_service_tests { } } + /// The web Export Table downloads a standalone table and says what the file lost, once the + /// browser takes it: nothing for a clean table, a refused download, or contents that are gone. + #[test] + fn table_download_writes_the_table_and_says_what_is_lost() { + use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value, loss::LossCode}; + use rustgis_engine::geom::Coord; + let taken: std::sync::Arc)>>> = Default::default(); + let with = |accept: bool| { + let taken = taken.clone(); + let mut app = RustGisApp::with_sample().with_services(Services { + download: Some(Box::new(move |name, bytes| { + if !accept { + return Err("browser rejected download".into()); + } + taken.lock().unwrap().push((name.to_string(), bytes)); + Ok(()) + })), + ..Default::default() + }); + for (name, level) in [("Totals", 2.5), ("Gaps", f64::NAN)] { + let mut ds = Dataset::new(name, GeometryType::None, vec![Field::new("level", FieldType::Double)]); + ds.push(None, vec![Value::Float(level)]); + app.session.project.add_table(ds); + } + let mut ds = Dataset::new("Sites", GeometryType::Point, vec![Field::new("population_2020", FieldType::Integer)]); + ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Int(7)]); + app.session.project.add_table(ds); + app + }; + let mut app = with(true); + // What an export says besides that the download was offered. + let export = |app: &mut RustGisApp, table: &str, format: &str| { + let mark = app.session.notice_mark(); + app.run("ui.exportTable", json!({"table": table, "format": format})).unwrap(); + app.session + .notices_since(mark) + .iter() + .filter(|n| !n.text.starts_with("Download offered")) + .map(|n| (n.loss(), n.text.clone())) + .collect::>() + }; + for format in ["csv", "geojson", "parquet"] { + assert_eq!(export(&mut app, "Totals", format), [], "{format}"); + let (name, bytes) = taken.lock().unwrap().pop().unwrap(); + assert_eq!(name, format!("Totals.{format}")); + if format == "csv" { + assert_eq!(String::from_utf8(bytes).unwrap(), "level\n2.5\n"); + } + } + let said = export(&mut app, "Gaps", "geojson"); + assert_eq!(said.len(), 1, "{said:?}"); + assert_eq!(said[0].0, Some(LossCode::DroppedValue)); + assert!(said[0].1.starts_with("Gaps.geojson: 1 attribute value(s)"), "{said:?}"); + let said = export(&mut app, "Sites", "shp"); + assert!(said.len() == 1 && said[0].1.contains("'population_2020' → 'population'"), "{said:?}"); + assert_eq!(taken.lock().unwrap().pop().unwrap().0, "Sites.zip"); + // Nothing the browser can't write, and no empty Shapefile: refused, nothing downloaded. + for (table, format) in [("Totals", "gpkg"), ("Totals", "fgb"), ("Totals", "shp")] { + taken.lock().unwrap().clear(); + assert!(app.run("ui.exportTable", json!({"table": table, "format": format})).is_err(), "{table}.{format}"); + assert!(taken.lock().unwrap().is_empty(), "{table}.{format}"); + } + // Contents other than those the dialog was opened on, and no table at all. + let e = app.run("ui.exportTable", json!({"table": "Totals", "format": "csv", "instance": 0})).unwrap_err(); + assert!(e.contains("is gone"), "{e}"); + assert!(app.run("ui.exportTable", json!({"format": "csv"})).unwrap_err().contains("open a standalone table")); + assert!(taken.lock().unwrap().is_empty()); + // The table in the attribute table, when none is named. + app.session.table_standalone = app.session.project.tables.first().map(|t| t.id); + app.run("ui.exportTable", json!({"format": "csv"})).unwrap(); + assert_eq!(taken.lock().unwrap().pop().unwrap().0, "Totals.csv"); + let mut refused = with(false); + let _ = refused.run("ui.exportTable", json!({"table": "Gaps", "format": "geojson"})); + assert!(refused.session.notices.iter().any(|n| n.error && n.text.contains("browser rejected download"))); + assert!(!refused.session.notices.iter().any(|n| n.text.contains("written as null")), "nothing was downloaded"); + } + /// The web download says the numbers GeoJSON can't hold, written as null, with their code, once /// the browser takes the file; a refused download says nothing of them. #[test] diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 1d3e9d1224..3421738961 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -930,6 +930,10 @@ fn contents(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let _ = app.run("ui.gp.open", json!({"tool": "xyTableToPoint", "table": id})); ui.close(); } + if ui.button(tl!("Export Table…")).clicked() { + let _ = app.run("ui.exportTable", json!({"table": id})); + ui.close(); + } // Names can repeat: the id says which table. A view open on it closes itself. if ui.button(tl!("Remove")).clicked() { let _ = app.run("table.remove", json!({"table": id})); @@ -8866,6 +8870,63 @@ pub(crate) mod tests { assert_eq!(h.state().ui.right, Some(RightPane::Symbology)); } + /// A standalone table's menu opens Export Table on it, which offers the formats that hold a + /// table without geometry and writes the one picked on the export thread. + #[test] + fn a_standalone_tables_menu_exports_it() { + use egui_kittest::kittest::Queryable; + use rustgis_engine::data::{Dataset, Field, FieldType, GeometryType, Value as Cell}; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("totals.csv"); + let mut app = RustGisApp::with_sample(); + let mut ds = Dataset::new("zone_totals", GeometryType::None, vec![Field::new("total", FieldType::Integer)]); + ds.push(None, vec![Cell::Int(42)]); + let table = app.session.project.add_table(ds); + // Added later: the menu's table is the one written, not the last. + app.session.project.add_table(Dataset::new("other", GeometryType::None, vec![])); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.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(6); + h.get_by_label("zone_totals").click_secondary(); + h.run_steps(2); + h.get_by_label("Export Table…").click(); + h.run_steps(4); + assert_eq!(h.state().dialogs.open, Some("exportTable")); + assert_eq!(h.state().dialogs.export_table.map(|(id, _)| id), Some(table)); + h.get_by_label("Format").click(); + h.run_steps(4); + for (label, offered) in [ + ("GeoJSON", true), + ("GeoPackage", true), + ("GeoParquet", true), + ("Shapefile", false), + ("FlatGeobuf", false), + ("KML", false), + ("KMZ", false), + ("GPX", false), + ] { + assert_eq!(h.query_all_by_label(label).count() > 0, offered, "{label}"); + } + h.key_press(egui::Key::Escape); + h.run_steps(4); + crate::dialogs::PICKED.with(|p| *p.borrow_mut() = Some(path.display().to_string())); + h.get_by_label("Export…").click(); + h.run_steps(2); + assert_eq!(h.state().dialogs.open, None); + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + while crate::exportjob::land(h.state_mut()) { + assert!(std::time::Instant::now() < end, "the export never landed"); + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: polls for the export thread's file + } + assert_eq!(std::fs::read_to_string(&path).unwrap(), "total\n42\n"); + } + /// #808: a web tile layer is listed at its place among the map's layers, moves past them /// from its menu, and is dragged to another place. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 7aa9f7e48a..fa3012f965 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -157,8 +157,9 @@ match ignoring case; an ambiguous name is refused. When two keys reach the same 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** (`share.exportTable`) -writes the edited table to a file. Tables have no selection yet, so rows can't be deleted. +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. ```text edit.setValue={"table":"sites","row":0,"field":"street","value":"Rue Cler"} diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index fcb94ecfc8..ca43d1a7de 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -74,10 +74,15 @@ A feature with a place that can't be given in the system written (one far past w layer's own system reaches, exported in WGS 84) is written without its geometry, and the export says how many; a format that holds only features with geometry leaves it out. Copy, Data Interop, the shared web map, web layer, geodata service and locator, 3D files and the mobile -map package do the same. The web app downloads every format but GeoPackage and FlatGeobuf. `share.exportTable` exports a -standalone table. **Data › Export** also writes rasters to GeoTIFF, and **Data Interop** converts layers to -KML, GPX or CSV with WKT. Layouts, reports and presentations export from their own tabs and panes -(see [Layouts and Reports](layouts.md)). +map package do the same. The web app downloads every format but GeoPackage and FlatGeobuf. **Data › Export** also writes +rasters to GeoTIFF, and **Data Interop** converts layers to KML, GPX or CSV with WKT. Layouts, reports and +presentations export from their own tabs and panes (see [Layouts and Reports](layouts.md)). + +To export a standalone table, such as a Summary Statistics result, right-click it in the Layers pane and +choose **Export Table…**, or run **Export Table** from Command Search and pick the table. The dialog offers +the formats above that can hold it: for a table without geometry, CSV, GeoJSON, GeoPackage and GeoParquet +(no GeoPackage in the web app, which downloads the file). Scripts and the command line use +`share.exportTable`. To export the largest rows of a Summary Statistics result, give `share.exportTable` an optional `sort` list and `limit`. Each sort key names a stored field; `descending` defaults to `false`. @@ -112,7 +117,7 @@ its own view is still loading: it waits for the map to move there, without progr A GeoPackage export writes a new file by default, and refuses an existing `.gpkg` to protect its tables, even if the save dialog offers to replace the file. To put the layer into an existing -GeoPackage instead, choose GeoPackage in **Export Features**, then under **Into** either +GeoPackage instead, choose GeoPackage in **Export Features** (or **Export Table**), then under **Into** either **A new table in a GeoPackage** or **A table replaced in a GeoPackage**, name the table, and pick the file (on the desktop). The GeoPackage's other tables stay as they were: one table is added, or one feature or attribute table of that name is replaced (a feature table with its From dba53353f05bf716b99cc0d13145f85b1f403fa5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 10:40:14 -0600 Subject: [PATCH 2/3] fix(ui): refuse an export while a read or table edit is still to land On the desktop a table edit, and a read such as Add Data or Load All, runs on the reads worker and changes the data only when it lands. An export started meanwhile wrote the data without it. Every export now waits: it is refused, naming what runs, until that lands. --- crates/ui-egui/src/exportjob.rs | 45 ++++++++++++++++++++++++++++++--- crates/ui-egui/src/lib.rs | 4 +-- crates/ui-egui/src/readjob.rs | 9 +++++++ 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index b2af2dce4d..506d778e0c 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -39,12 +39,21 @@ pub(crate) fn writing(app: &RustGisApp) -> Option<&str> { app.export_job.as_ref()?.writes.as_deref() } -/// Refuses another export while one runs, whichever way it would run (one at a time). +/// Refuses an export while another runs, whichever way it would run (one at a time), or while a +/// read or table edit is still to land. pub fn idle(app: &RustGisApp) -> Result<(), String> { - match &app.export_job { - Some(job) => Err(crate::i18n::fmt("{tool} is still running: wait for it, or cancel it.", &[("tool", tl_raw!(job.name))])), - None => Ok(()), + if let Some(job) = &app.export_job { + return Err(crate::i18n::fmt("{tool} is still running: wait for it, or cancel it.", &[("tool", tl_raw!(job.name))])); } + // A read or table edit on its own thread changes the data only when it lands: an export now + // would write the data without it. + if let Some(read) = crate::readjob::under_way(app) { + return Err(crate::i18n::fmt( + "{read} is still running: wait for it, or cancel it, then export, so the file holds what it changes.", + &[("read", tl_raw!(read))], + )); + } + Ok(()) } /// Starts `command` ([`exports::runs_in_background`]) with `p` on a thread of its own. One at a @@ -187,6 +196,34 @@ mod tests { assert_eq!(steps[1].params, again); } + /// A table edit still on the reads worker would be missing from the file: the export is + /// refused, naming it, until the edit lands, and then holds it. + #[test] + fn an_export_waits_for_a_table_edit_under_way() { + let mut app = RustGisApp::with_sample(); + app.run("layer.addDataText", json!({"fileName": "ranks.csv", "text": "name,score\na,1\n"})).unwrap(); + app.reads_off_frame = true; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ranks.csv"); + let export = json!({"table": "ranks", "path": path}); + app.run("edit.setValue", json!({"table": "ranks", "row": 0, "field": "score", "value": 5})).unwrap(); + assert_eq!(crate::readjob::under_way(&app), Some("Edit Attribute"), "the edit runs on the reads worker"); + let refused = app.run("share.exportTable", export.clone()).unwrap_err(); + assert!(refused.starts_with("Edit Attribute is still running"), "{refused}"); + assert!(app.export_job.is_none() && !path.exists()); + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + while crate::readjob::land(&mut app) { + assert!(std::time::Instant::now() < end, "the edit never landed"); + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: the reads worker publishes its result to the frame's polled slot + } + assert_eq!(app.run("share.exportTable", export).unwrap()["started"], "Export Table"); + while land(&mut app) { + assert!(std::time::Instant::now() < end, "the export never landed"); + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: export workers publish completion to the frame's polled slot + } + assert_eq!(std::fs::read_to_string(&path).unwrap(), "name,score\na,5\n"); + } + /// Delivers actual failed and cancelled export runs without a thread timing race. Neither /// may enter Record Task; a written file whose completion is refused is excluded too. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 488895be99..99bcd1c0c9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5855,7 +5855,7 @@ impl RustGisApp { "ui.exportLayer" | "ui.annotationExport" | "ui.exportTable" => { let annotation_export = id == "ui.annotationExport"; let table = id == "ui.exportTable"; - let (command, key) = if table { ("share.exportTable", "table") } else { ("share.exportLayer", "layer") }; + let (command, target_key) = if table { ("share.exportTable", "table") } else { ("share.exportLayer", "layer") }; let ext = p.get("format").and_then(Value::as_str).unwrap_or("geojson").to_ascii_lowercase(); let label = dialogs::EXPORT_FORMATS .iter() @@ -5869,7 +5869,7 @@ impl RustGisApp { let name = self.export_file_name(id, &ext, table, annotation_export)?; let arguments = |path: String| { let mut args = json!({"path": path}); - args[key] = json!(id); + args[target_key] = json!(id); for key in ["mode", "tableName"] { if let Some(v) = p.get(key) { args[key] = v.clone(); diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index aeaecdb4b3..20d0eefdd8 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -766,6 +766,15 @@ impl Reads { } } +/// The read or table edit under way, by its name, while one runs or waits: an export started now +/// would read the data before it lands. +pub(crate) fn under_way(app: &RustGisApp) -> Option<&'static str> { + match &app.reads.job { + Some(job) => Some(job.name), + None => (!app.reads.waiting.is_empty()).then_some("A read"), + } +} + /// Whether the status bar shows a read. pub fn showing(app: &RustGisApp) -> bool { app.reads.job.is_some() From d6ae8babfa92eda3cc24444abaa93d5d99438d5d Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 11:36:05 -0600 Subject: [PATCH 3/3] fix(ui): tell apart standalone tables that share a name in Export Table The project lets two standalone tables share a name, and the picker listed each by name alone, so a user could export the other one. A repeated name is now shown with which of them it is, in the Layers pane's order. The read named in the export refusal is translatable. --- crates/ui-egui/src/dialogs.rs | 41 +++++++++++++++++++++++++++++++---- crates/ui-egui/src/readjob.rs | 2 +- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6e07a3c2d1..8958219b52 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1132,19 +1132,37 @@ fn export_table_choice(app: &mut RustGisApp, ui: &mut egui::Ui) { let label = ui.label(tl!("Table")); let picked = app.dialogs.export_table; let is_picked = |t: &Table| picked == Some((t.id, t.instance_id())); - let shown = app.session.project.tables.iter().find(|t| is_picked(t)).map_or("", |t| t.dataset.name.as_str()); + let tables = &app.session.project.tables; + let shown = tables.iter().find(|t| is_picked(t)).map_or_else(String::new, |t| table_label(tables, t.id)); + let mut chosen = None; egui::ComboBox::from_id_salt("export_table_choice") .selected_text(shown) .width(220.0) .show_ui(ui, |ui| { - for t in &app.session.project.tables { - if ui.selectable_label(is_picked(t), &t.dataset.name).clicked() { - app.dialogs.pick_export_table(t); + for t in tables { + if ui.selectable_label(is_picked(t), table_label(tables, t.id)).clicked() { + chosen = Some(t.id); } } }) .response .labelled_by(label.id); + if let Some(t) = chosen.and_then(|id| app.session.project.table(id)) { + app.dialogs.pick_export_table(t); + } +} + +/// How Export Table names standalone table `id` among `tables`: its name, and where names repeat +/// (the project allows it), which of them it is, in the Layers pane's order. +fn table_label(tables: &[Table], id: u32) -> String { + let Some(name) = tables.iter().find(|t| t.id == id).map(|t| t.dataset.name.as_str()) else { return String::new() }; + let same: Vec = tables.iter().filter(|t| t.dataset.name == name).map(|t| t.id).collect(); + match same.iter().position(|&other| other == id) { + Some(k) if same.len() > 1 => { + crate::i18n::fmt("{name} ({k} of {n})", &[("name", name), ("k", &(k + 1).to_string()), ("n", &same.len().to_string())]) + } + _ => name.to_string(), + } } /// Export Features (the active layer) and Export Table (`table`: a standalone table), in a format @@ -3608,6 +3626,21 @@ fn calculation_preview(rows: &[rustgis_engine::cmd::edit::CalculationPreview]) - mod tests { use super::*; + /// Export Table's picker tells apart standalone tables that share a name, which the project + /// allows, so the one written is the one meant; a name used once stays as it is. + #[test] + fn export_table_labels_tell_tables_with_one_name_apart() { + use rustgis_engine::data::{Dataset, GeometryType}; + let mut app = RustGisApp::with_sample(); + let first = app.session.project.add_table(Dataset::new("totals", GeometryType::None, vec![])); + let other = app.session.project.add_table(Dataset::new("ranks", GeometryType::None, vec![])); + let second = app.session.project.add_table(Dataset::new("totals", GeometryType::None, vec![])); + let tables = &app.session.project.tables; + assert_eq!(table_label(tables, first), "totals (1 of 2)"); + assert_eq!(table_label(tables, second), "totals (2 of 2)"); + assert_eq!(table_label(tables, other), "ranks"); + } + /// The GeoPackage prompt belongs to the map it opened on, wherever that map goes among the maps; /// another map or project refuses it (#2959). #[test] diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 20d0eefdd8..250b78440a 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -771,7 +771,7 @@ impl Reads { pub(crate) fn under_way(app: &RustGisApp) -> Option<&'static str> { match &app.reads.job { Some(job) => Some(job.name), - None => (!app.reads.waiting.is_empty()).then_some("A read"), + None => (!app.reads.waiting.is_empty()).then(|| crate::tl_raw!("A read")), } }