From 1bff6bc5a882ec12830d9ea46290cc84b9464435 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:15:08 -0500 Subject: [PATCH 1/5] Fix UI dialog validation, browser export notices, and project reset state Fix five bugs in `rustgis-ui-egui`: 1. Use `io::export_losses_notes_in(..., crs)` in browser layer export, move `io::left_out_note` and missing-`.prj` notices inside `if self.download(...)` so failed downloads emit no export notices, and format the missing-`.prj` notice with `i18n::fmt`. 2. Route desktop `CsvSource::Path` imports in `add_csv` through `readjob::run` (matching `add_dxf_file`) so disk CSV reads run off the UI thread. 3. Share the grouped whole-number parser between `gpkg_add_layer` and `add_for_editing` so decimal strings like `"1.5"` are rejected, and validate `maxZoom` in `add_tiles` as a finite number instead of silently ignoring invalid input. 4. Wrap the five raw English error literals in `Dialogs::open` in `tl!`. 5. Route project-replacing files in `open_bytes_with` through `run_by_user` (gating `ui.web_file` on `!saveprompt::waiting`) so unsaved edits prompt before replacement, and share `reset_replaced_project` between `run_with_prepared` and `open_peer_text` so both reset `ws.task_edit`, `ws.task_step`, sketches, plugin picks, edit drags, and stale table views. --- crates/ui-egui/src/dialogs.rs | 152 +++++++++++++++++++++++----- crates/ui-egui/src/lib.rs | 184 +++++++++++++++++++++++++--------- crates/ui-egui/src/table.rs | 16 +++ crates/ui-egui/tests/smoke.rs | 1 + 4 files changed, 282 insertions(+), 71 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ef0d3dc4c5..0bedb21a79 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -195,22 +195,22 @@ impl Dialogs { other => return Err(format!("unknown dialog '{other}'")), }; if matches!(name, "addField" | "calculateField" | "renameLayer" | "exportLayer" | "defineProjection") && active.is_none() { - return Err("select a layer in the Layers pane first".into()); + return Err(tl!("select a layer in the Layers pane first").into()); } if name == "exportLayer" && active.is_some_and(|l| l.is_raster()) { - return Err("Export Features needs a vector layer (Data › Export Raster writes a raster)".into()); + return Err(tl!("Export Features needs a vector layer (Data › Export Raster writes a raster)").into()); } if matches!(name, "pgSave" | "pgDiscard") && !s.map().layers.iter().any(|l| l.postgis.is_some()) { - return Err("the map has no PostGIS layer loaded for editing (Home › Add Data › Database…, Load for editing)".into()); + return Err(tl!("the map has no PostGIS layer loaded for editing (Home › Add Data › Database…, Load for editing)").into()); } if matches!(name, "gpkgSave" | "gpkgDiscard") && !s.map().layers.iter().any(|l| l.gpkg.is_some()) { return Err(tl!("the map has no GeoPackage layer loaded for editing (Home › Add Data › Edit GeoPackage Table…)").into()); } if name == "exportOrbit" && cfg!(target_arch = "wasm32") { - return Err("exporting an orbit needs the desktop app".into()); + return Err(tl!("exporting an orbit needs the desktop app").into()); } if name == "selectByAttributes" && s.map().layers.is_empty() { - return Err("the map has no layers".into()); + return Err(tl!("the map has no layers").into()); } *self = Dialogs { open: Some(name), mode: "new", edit: which == "pgAddLayer", reset_collapse: true, ..Dialogs::default() }; self.layer = active.or_else(|| s.map().layers.first()).map(|l| l.name.clone()).unwrap_or_default(); @@ -1398,15 +1398,21 @@ fn add_dxf(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { }) } -/// Adds a drawing on disk, read as Add Data reads a file (on a thread of its own when the desktop +/// Adds a file on disk, read as Add Data reads a file (on a thread of its own when the desktop /// app reads it so, [`crate::readjob`]). -pub(crate) fn add_dxf_file(app: &mut RustGisApp, p: Value) -> Result { +fn add_data_file(app: &mut RustGisApp, p: Value) -> Result { #[cfg(not(target_arch = "wasm32"))] return crate::readjob::run(app, "layer.addData", p); #[cfg(target_arch = "wasm32")] app.run("layer.addData", p) } +/// Adds a drawing on disk, read as Add Data reads a file (on a thread of its own when the desktop +/// app reads it so, [`crate::readjob`]). +pub(crate) fn add_dxf_file(app: &mut RustGisApp, p: Value) -> Result { + add_data_file(app, p) +} + /// The columns of a file picked for Add Delimited Text, split at `separator` (a code of /// [`SEPARATORS`]), respecting the coordinate system entered in the dialog. fn csv_columns(file: &CsvFile, separator: &str, crs: &str) -> Result { @@ -1588,7 +1594,7 @@ fn add_csv(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { let r = match &file.source { CsvSource::Path(path) => { p["path"] = json!(path); - app.run("layer.addData", p) + add_data_file(app, p) } CsvSource::Bytes(bytes) => app.open_bytes_with(&file.name, bytes, Some(p)), }; @@ -2386,6 +2392,25 @@ fn add_database(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { }) } +/// Parses a non-negative whole number, allowing optional 3-digit comma grouping (`1,000`). +fn parse_whole_number(text: &str) -> Result { + let input = text.trim(); + let mut groups = input.split(','); + let first = groups.next().unwrap_or_default(); + let grouped = first.len() != input.len(); + if grouped + && (first.is_empty() + || first.len() > 3 + || !first.bytes().all(|b| b.is_ascii_digit()) + || !groups.all(|group| group.len() == 3 && group.bytes().all(|b| b.is_ascii_digit()))) + { + return Err(tl!("Most rows: a whole number").to_string()); + } + let n: u64 = + if grouped { input.replace(',', "").parse() } else { input.parse() }.map_err(|_| tl!("Most rows: a whole number").to_string())?; + Ok(n) +} + /// Add From Database with Load for editing: connects to the PostgreSQL database for editing /// (`pg.connect`) and loads the chosen table whole (`pg.addLayer`). fn add_for_editing(app: &mut RustGisApp, address: String) -> Result<(), String> { @@ -2401,8 +2426,7 @@ fn add_for_editing(app: &mut RustGisApp, address: String) -> Result<(), String> } } if !d.e.trim().is_empty() { - let n: u64 = d.e.trim().replace([',', '.'], "").parse().map_err(|_| tl!("Most rows: a whole number").to_string())?; - p["limit"] = json!(n); + p["limit"] = json!(parse_whole_number(&d.e)?); } let connect = json!({"connection": address, "password": d.b}); app.run("pg.connect", connect)?; @@ -2498,21 +2522,7 @@ fn gpkg_add_layer(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { p["table"] = json!(app.dialogs.c.trim()); } if !app.dialogs.e.trim().is_empty() { - let input = app.dialogs.e.trim(); - let mut groups = input.split(','); - let first = groups.next().unwrap_or_default(); - let grouped = first.len() != input.len(); - if grouped - && (first.is_empty() - || first.len() > 3 - || !first.bytes().all(|b| b.is_ascii_digit()) - || !groups.all(|group| group.len() == 3 && group.bytes().all(|b| b.is_ascii_digit()))) - { - return Err(tl!("Most rows: a whole number").to_string()); - } - let n: u64 = if grouped { input.replace(',', "").parse() } else { input.parse() } - .map_err(|_| tl!("Most rows: a whole number").to_string())?; - p["limit"] = json!(n); + p["limit"] = json!(parse_whole_number(&app.dialogs.e)?); } app.run("gpkg.addLayer", p).map(|_| ()) }) @@ -2735,13 +2745,26 @@ fn add_tiles(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { p[key] = json!(v.trim()); } } - if let Ok(z) = app.dialogs.c.trim().parse::() { + if let Some(z) = parse_max_zoom(&app.dialogs.c)? { p["maxZoom"] = json!(z); } app.run("map.addTiles", p).map(|_| ()) }) } +/// Parses an optional finite number for Add Tile Layer's Maximum zoom field. +fn parse_max_zoom(text: &str) -> Result, String> { + let s = text.trim(); + if s.is_empty() { + return Ok(None); + } + s.parse::() + .ok() + .filter(|z| z.is_finite()) + .map(Some) + .ok_or_else(|| crate::i18n::fmt("{what} must be a number", &[("what", tl_raw!("Maximum zoom"))])) +} + /// A dialog's multi-line text box. [`buttons`] takes Enter to confirm the dialog, so only /// Shift+Enter breaks a line here: a plain Enter would also add one where the cursor is, in the /// same frame (egui's default, which also takes Shift+Enter). @@ -5153,4 +5176,81 @@ mod tests { h.run_steps(4); assert_eq!(h.state().dialogs.open, None); } + + #[test] + fn whole_number_and_max_zoom_parsers() { + assert_eq!(parse_whole_number("1,000"), Ok(1000)); + assert_eq!(parse_whole_number("1000"), Ok(1000)); + assert!(parse_whole_number("1.5").is_err()); + assert!(parse_whole_number("1,2").is_err()); + + assert_eq!(parse_max_zoom(""), Ok(None)); + assert_eq!(parse_max_zoom(" "), Ok(None)); + assert_eq!(parse_max_zoom("18"), Ok(Some(18.0))); + assert!(parse_max_zoom("abc").is_err()); + assert!(parse_max_zoom("NaN").is_err()); + assert!(parse_max_zoom("inf").is_err()); + } + + /// `add_for_editing` rejects decimal row limits like `"1.5"`, and Add Tile Layer rejects + /// non-numeric / non-finite Maximum zoom inputs instead of silently ignoring them. + #[test] + fn add_for_editing_and_add_tiles_reject_invalid_numbers() { + use egui_kittest::kittest::Queryable; + + let mut app = RustGisApp::with_sample(); + app.dialogs.c = "roads".into(); + app.dialogs.e = "1.5".into(); + let err = add_for_editing(&mut app, "postgres://localhost/db".into()).unwrap_err(); + assert!(err.contains("whole number"), "expected whole-number error for 1.5, got: {err}"); + + for bad_zoom in ["abc", "NaN"] { + let mut app = RustGisApp::with_sample(); + app.run("project.new", json!({})).unwrap(); + app.run("ui.dialog", json!({"name": "addTiles"})).unwrap(); + app.dialogs.text = "https://example.com/{z}/{x}/{y}.png".into(); + app.dialogs.c = bad_zoom.into(); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_label("Add").click(); + h.run_steps(3); + assert!( + h.state().dialogs.error.as_deref().is_some_and(|e| e.contains("Maximum zoom must be a number")), + "{bad_zoom}: expected validation error, got {:?}", + h.state().dialogs.error + ); + assert!(h.state().session.map().tiles.is_empty(), "{bad_zoom}: invalid maxZoom must not add tiles"); + } + } + + /// On the desktop with off-frame reads enabled, Add Delimited Text queues disk CSV reads + /// through `readjob` instead of running `layer.addData` synchronously on the UI thread. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn add_csv_path_uses_background_read_queue() { + use egui_kittest::kittest::Queryable; + + let dir = tempfile::tempdir().unwrap(); + let csv_path = dir.path().join("points.csv"); + std::fs::write(&csv_path, "lon,lat,name\n10,20,Alpha\n").unwrap(); + let path_str = csv_path.display().to_string(); + + let mut app = RustGisApp::with_sample(); + app.reads_off_frame = true; + open_csv(&mut app, &path_str, CsvSource::Path(path_str.clone())).unwrap(); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_label("Add").click(); + h.run_steps(2); + assert!( + h.state().background_busy(), + "desktop CSV path import should queue through readjob rather than running synchronously on the UI thread" + ); + let end = std::time::Instant::now() + std::time::Duration::from_secs(10); + while crate::readjob::land(h.state_mut()) { + assert!(std::time::Instant::now() < end, "background CSV read never landed"); + std::thread::yield_now(); + } + assert!(h.state().session.map().layer_by_name("points").is_some()); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dd31c685bb..776fa4bbad 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2617,7 +2617,7 @@ impl RustGisApp { if cmd == "ramp.add" { p["file"] = json!(name); } - let r = self.run(cmd, p); + let r = self.run_by_user(cmd, p); self.map.invalidate(); // A model file opens in ModelBuilder. if cmd == "model.import" @@ -2633,7 +2633,7 @@ impl RustGisApp { } if lower.ends_with(".rgispkg") { let text = rustgis_engine::cmd::items::package_text(bytes)?; - let r = self.run("project.openText", json!({"text": text, "package": true})); + let r = self.run_by_user("project.openText", json!({"text": text, "package": true})); self.map.invalidate(); return r; } @@ -2689,8 +2689,8 @@ impl RustGisApp { return Err(e); }; if rustgis_engine::project::is_project_file(name) { - let r = self.run("project.openText", json!({"text": text, "fileName": name})); - if r.is_ok() { + let r = self.run_by_user("project.openText", json!({"text": text, "fileName": name})); + if r.is_ok() && !saveprompt::waiting(self) { self.ui.web_file = Some(format!("{}.rgis", self.session.project.name)); } self.map.invalidate(); @@ -3265,27 +3265,46 @@ impl RustGisApp { pub fn open_peer_text(&mut self, text: &str) -> Result<(), String> { let report = self.session.open_peer_text(rustgis_engine::Peer::Embedder, text)?; assistantpane::peer_replaced(self); + self.reset_replaced_project(); + layoutview::follow_project(self); + for notice in report.notices() { + self.session.notify(notice, false); + } + Ok(()) + } + + /// Clears UI state bound to the previous project after either ordinary or peer replacement. + fn reset_replaced_project(&mut self) { self.ui.web_file = None; + // A deletion asked for in the old project never reaches a namesake in the new one. self.map.deleting = None; - // A spectral profile's points were read on the old project's rasters. + self.map.cancel_sketch(); + pluginpanel::cancel_pick(self); + crate::vertexedit::cancel_stale_drag(self); + annotation::sync(self); + crate::boxedit::cancel_stale(self); + crate::circleedit::cancel_stale(self); + if self.ui.symbology_pending.as_ref().is_some_and(|pending| !pending.is_current(&self.session)) { + self.ui.symbology_pending = None; + } + // Nor are a spectral profile's points read on a namesake raster of the new one. self.workflow.spectral.clear(); crate::analysispane::forget_similar(&mut self.workflow); (self.workflow.result, self.workflow.error) = (None, None); - self.retire_cog_probes(); + self.ws.task_edit = None; + self.ws.task_step = 0; + // A recording's steps name the old project's layers: it ends here, and says so. if let Some(steps) = self.ws.recording.take() { - self.session.notify( - crate::i18n::fmt( - "Recording stopped: another project opened, and its {n} steps were for the previous one.", - &[("n", &steps.len().to_string())], - ), - true, - ); - } - layoutview::follow_project(self); - for notice in report.notices() { - self.session.notify(notice, false); + let n = steps.len().to_string(); + let text = + crate::i18n::fmt("Recording stopped: another project opened, and its {n} steps were for the previous one.", &[("n", &n)]); + self.session.notify(text, true); } - Ok(()) + // A probe still under way is for an address added to the old project: dropped, so + // its layer never lands in the new one, and said, as a download landing late is. A plugin + // command waiting for it went with the old project's waits. + self.retire_cog_probes(); + table::prune_views(self); } /// Reports pending header reads retired by either ordinary or peer project replacement. @@ -3533,26 +3552,7 @@ impl RustGisApp { // A project replacing this one hasn't been saved in the browser yet (opening a file // names it again). if r.is_ok() && matches!(id, "project.new" | "project.sample" | "project.open" | "project.openText" | "project.fromTemplate") { - self.ui.web_file = None; - // A deletion asked for in the old project never reaches a namesake in the new one. - self.map.deleting = None; - // Nor are a spectral profile's points read on a namesake raster of the new one. - self.workflow.spectral.clear(); - crate::analysispane::forget_similar(&mut self.workflow); - (self.workflow.result, self.workflow.error) = (None, None); - // A recording's steps name the old project's layers: it ends here, and says so. - if let Some(steps) = self.ws.recording.take() { - let n = steps.len().to_string(); - let text = crate::i18n::fmt( - "Recording stopped: another project opened, and its {n} steps were for the previous one.", - &[("n", &n)], - ); - self.session.notify(text, true); - } - // A probe still under way is for an address added to the old project: dropped, so - // its layer never lands in the new one, and said, as a download landing late is. A plugin - // command waiting for it went with the old project's waits. - self.retire_cog_probes(); + self.reset_replaced_project(); } // Fields and layers can go while the table is closed: its column views follow them. table::prune_views(self); @@ -5630,15 +5630,21 @@ impl RustGisApp { } dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.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())?); + dbf_notes.extend(io::export_losses_notes_in(&ds, &ext, io::name_field(&ds), &name, crs).map_err(|e| e.to_string())?); drop(ds); - if let Some(note) = io::left_out_note(&name, &ext, left_out) { - self.session.notify(note, false); - } - if ext == "zip" && rustgis_engine::data::raster::wkt::to_wkt(crs).is_none() { - self.session.notify(format!("{name}: no .prj written, as {} has no WKT form", crs.label()), false); - } if self.download(&name, bytes) { + if let Some(note) = io::left_out_note(&name, &ext, left_out) { + self.session.notify(note, false); + } + if ext == "zip" && rustgis_engine::data::raster::wkt::to_wkt(crs).is_none() { + self.session.notify( + crate::i18n::fmt( + "{name}: no .prj written, as {crs} has no WKT form", + &[("name", &name), ("crs", &crs.label())], + ), + false, + ); + } rustgis_engine::cmd::share::notify_export_query(&mut self.session, &name, &layer_name, &query_report); for note in notes .into_iter() @@ -9872,6 +9878,53 @@ mod download_service_tests { assert!(!app.session.notices.iter().any(|n| n.text.contains("254 bytes") || n.text.contains("left empty"))); } + /// Browser layer export computes format-loss notes in the layer's export CRS and emits no + /// export notices (including left-out features and missing `.prj`) when the download fails. + #[test] + fn browser_export_uses_layer_crs_and_suppresses_notes_on_failed_download() { + use rustgis_engine::data::raster::Crs; + use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + use rustgis_engine::geom::Coord; + + let gnomonic = Crs::parse("+proj=gnom +lat_0=51 +lon_0=9 +datum=WGS84 +units=m +no_defs").unwrap(); + assert!(rustgis_engine::data::raster::wkt::to_wkt(gnomonic).is_none()); + let make_app = |accept: bool| { + let download: Box) -> Result<(), String>> = + if accept { Box::new(|_, _| Ok(())) } else { Box::new(|_, _| Err("download blocked".into())) }; + let mut app = RustGisApp::with_sample().with_services(Services { download: Some(download), ..Default::default() }); + let mut ds = Dataset::new("Partial", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("ok".into())]); + ds.push(None, vec![Value::Text("no geom".into())]); + ds.crs = Some(gnomonic); + ds.held_in = gnomonic; + let id = app.session.map_mut().add_dataset(ds); + app.session.active_layer = Some(id); + app + }; + + // Accepted download emits both left-out and missing-.prj notices for the projected layer. + let mut app = make_app(true); + let mark = app.session.notice_mark(); + app.run("ui.exportLayer", json!({"format": "shp"})).unwrap(); + let notices = app.session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("left out")), "expected left-out notice, got: {notices:?}"); + assert!( + notices.iter().any(|n| n.text.contains("no .prj written") && n.text.contains(&gnomonic.label())), + "expected missing-.prj notice, got: {notices:?}" + ); + + // Failed download must not emit left-out feature notices or missing-.prj notices. + let mut app = make_app(false); + let mark = app.session.notice_mark(); + app.run("ui.exportLayer", json!({"format": "shp"})).unwrap(); + let notices = app.session.notices_since(mark); + assert!(notices.iter().any(|n| n.error && n.text.contains("download blocked")), "got: {notices:?}"); + assert!( + !notices.iter().any(|n| n.text.contains("left out") || n.text.contains("no .prj written")), + "failed download emitted export notices: {notices:?}" + ); + } + /// Export Features into an existing GeoPackage: the file is picked to open, not to save over, /// and the layer goes in as the table named in the dialog, beside the file's others. #[test] @@ -10010,6 +10063,47 @@ mod peer_output_tests { } } + /// Replacing the project (via command or peer text) clears any active task-step edit and step index. + #[test] + fn project_replacement_clears_task_edit_and_step() { + for peer in [false, true] { + let mut app = RustGisApp::with_sample(); + app.ws.task_edit = Some((1, "Old title".into(), "Old instructions".into())); + app.ws.task_step = 3; + if peer { + let (text, _) = Project::default().saved_text(None).unwrap(); + app.open_peer_text(&text).unwrap(); + } else { + app.run("project.new", json!({})).unwrap(); + } + assert!(app.ws.task_edit.is_none(), "peer={peer}: task_edit must be cleared on project replace"); + assert_eq!(app.ws.task_step, 0, "peer={peer}: task_step must reset to 0 on project replace"); + } + } + + /// Opening a project, package, or template via `open_bytes` when unsaved edits exist and + /// `save_project` is present asks the save prompt instead of silently discarding edits. + #[test] + fn open_bytes_with_asks_to_save_unsaved_edits_before_replacing() { + let (other_text, _) = Project::default().saved_text(None).unwrap(); + let pkg_bytes = rustgis_engine::data::zip::write(&[("other.rgis".into(), other_text.as_bytes().to_vec())]).unwrap(); + + for (file, bytes) in + [("other.rgis", other_text.as_bytes()), ("other.rgispkg", pkg_bytes.as_slice()), ("other.rgistemplate", other_text.as_bytes())] + { + let mut app = RustGisApp::with_sample(); + app.services.open_async = Some(Box::new(|_| {})); + app.services.save_project = Some(Box::new(|_, _, _| Ok(()))); + app.run("map.rename", json!({"name": "Unsaved Map"})).unwrap(); + assert!(app.session.dirty()); + + app.open_bytes(file, bytes).unwrap(); + assert!(saveprompt::waiting(&app), "{file}: expected save prompt to wait for user answer"); + assert_eq!(app.session.map().name, "Unsaved Map", "{file}: unsaved edits must not be discarded yet"); + assert!(app.ui.web_file.is_none(), "{file}: web_file must not be set while waiting on save prompt"); + } + } + /// Drives the actual receiving wrapper, including the UI state a direct Session call misses. #[test] fn peer_project_uses_import_authority_and_resets_old_ui_work() { diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index d413721370..eaf24fe434 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -1708,4 +1708,20 @@ mod tests { assert_eq!(app.table.stats.is_some(), !selected, "only the selected-row window closes"); } } + + /// Replacing the project via `open_peer_text` prunes stale column views from the previous project. + #[test] + fn peer_project_replacement_prunes_stale_table_views() { + let mut app = RustGisApp::with_sample(); + prune_views(&mut app); + let layer = app.session.map().layers.iter().find(|l| l.name == "Countries").unwrap(); + let mut v = ColumnView::default(); + v.hide(&layer.dataset.fields, 0); + app.table.views.insert(ViewKey::Layer(layer.instance_id()), v); + assert_eq!(app.table.views.len(), 1); + + let (text, _) = rustgis_engine::Project::default().saved_text(None).unwrap(); + app.open_peer_text(&text).unwrap(); + assert!(app.table.views.is_empty(), "open_peer_text must prune stale table views"); + } } diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 0325a9162f..89c7be8615 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -3989,6 +3989,7 @@ fn web_save_asks_for_the_file_name() { log.lock().unwrap().push((name.to_string(), bytes)); Ok(()) })), + open_async: Some(Box::new(|_| {})), ..Default::default() }; let app = RustGisApp::with_sample().with_services(services); From 54fb5fbd7fe6b3dee440109b0d7e9a4c901143c9 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:33:51 -0500 Subject: [PATCH 2/5] Restore web_file on deferred project.openText and deduplicate UI sync Address review feedback on PR #2930: 1. Set `self.ui.web_file` in `run_with_prepared` after `reset_replaced_project` when `project.openText` succeeds with a non-empty `fileName` (and not a package), so both immediate and save-prompt-deferred opens populate `web_file` in one place. Extend `open_bytes_with_asks_to_save_unsaved_edits_before_replacing` to click Don't Save and assert the resulting `web_file`. 2. Split per-command UI reconciliation into `sync_after_session_change` and keep `reset_replaced_project` focused on replacement-only teardown so neither `run_with_prepared` nor `open_peer_text` duplicates cleanup calls. --- crates/ui-egui/src/lib.rs | 93 +++++++++++++++++++++++++-------------- 1 file changed, 60 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 776fa4bbad..533468a14b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2690,9 +2690,6 @@ impl RustGisApp { }; if rustgis_engine::project::is_project_file(name) { let r = self.run_by_user("project.openText", json!({"text": text, "fileName": name})); - if r.is_ok() && !saveprompt::waiting(self) { - self.ui.web_file = Some(format!("{}.rgis", self.session.project.name)); - } self.map.invalidate(); r } else { @@ -3266,6 +3263,7 @@ impl RustGisApp { let report = self.session.open_peer_text(rustgis_engine::Peer::Embedder, text)?; assistantpane::peer_replaced(self); self.reset_replaced_project(); + self.sync_after_session_change(); layoutview::follow_project(self); for notice in report.notices() { self.session.notify(notice, false); @@ -3273,20 +3271,31 @@ impl RustGisApp { Ok(()) } - /// Clears UI state bound to the previous project after either ordinary or peer replacement. - fn reset_replaced_project(&mut self) { - self.ui.web_file = None; - // A deletion asked for in the old project never reaches a namesake in the new one. - self.map.deleting = None; - self.map.cancel_sketch(); - pluginpanel::cancel_pick(self); + /// Reconciles UI handles (active edit drags, annotations, pending symbology pick, table views) + /// with the current session after a command or peer project replacement. + fn sync_after_session_change(&mut self) { + // Nested commands (including scripts) can replace rows too; never retarget a chosen + // vertex or held gesture to the replacement feature at the same row. crate::vertexedit::cancel_stale_drag(self); annotation::sync(self); crate::boxedit::cancel_stale(self); crate::circleedit::cancel_stale(self); + // Commands can replace the project, switch maps or change the renderer while the pane + // is closed. A field picked for the old context must not overwrite the new renderer. if self.ui.symbology_pending.as_ref().is_some_and(|pending| !pending.is_current(&self.session)) { self.ui.symbology_pending = None; } + // Fields and layers can go while the table is closed: its column views follow them. + table::prune_views(self); + } + + /// Clears UI state bound to the previous project after either ordinary or peer replacement. + fn reset_replaced_project(&mut self) { + self.ui.web_file = None; + // A deletion asked for in the old project never reaches a namesake in the new one. + self.map.deleting = None; + self.map.cancel_sketch(); + pluginpanel::cancel_pick(self); // Nor are a spectral profile's points read on a namesake raster of the new one. self.workflow.spectral.clear(); crate::analysispane::forget_similar(&mut self.workflow); @@ -3304,7 +3313,6 @@ impl RustGisApp { // its layer never lands in the new one, and said, as a download landing late is. A plugin // command waiting for it went with the old project's waits. self.retire_cog_probes(); - table::prune_views(self); } /// Reports pending header reads retired by either ordinary or peer project replacement. @@ -3524,12 +3532,6 @@ impl RustGisApp { // Esc chooses Explore: a plugin's pick stops waiting for the map, as for any tool. pluginpanel::cancel_pick(self); } - // Nested commands (including scripts) can replace rows too; never retarget a chosen - // vertex or held gesture to the replacement feature at the same row. - crate::vertexedit::cancel_stale_drag(self); - annotation::sync(self); - crate::boxedit::cancel_stale(self); - crate::circleedit::cancel_stale(self); if let Err(e) = &r { self.command_failed(id, e, notice_mark); } @@ -3544,18 +3546,18 @@ impl RustGisApp { { self.keep_refused(&e); } - // Commands can replace the project, switch maps or change the renderer while the pane - // is closed. A field picked for the old context must not overwrite the new renderer. - if self.ui.symbology_pending.as_ref().is_some_and(|pending| !pending.is_current(&self.session)) { - self.ui.symbology_pending = None; - } // A project replacing this one hasn't been saved in the browser yet (opening a file - // names it again). + // names it again, including when deferred through the save prompt). if r.is_ok() && matches!(id, "project.new" | "project.sample" | "project.open" | "project.openText" | "project.fromTemplate") { self.reset_replaced_project(); + if id == "project.openText" + && params.get("fileName").and_then(Value::as_str).is_some_and(|name| !name.is_empty()) + && params.get("package").and_then(Value::as_bool) != Some(true) + { + self.ui.web_file = Some(format!("{}.rgis", self.session.project.name)); + } } - // Fields and layers can go while the table is closed: its column views follow them. - table::prune_views(self); + self.sync_after_session_change(); // Undo and redo can move vertices: an index chosen before may now name another vertex. // A step moved or deleted, from the pane, Command Search, the assistant or a script: the // step being edited (and the current one) follow it, so Save writes where it was typed. @@ -10082,25 +10084,50 @@ mod peer_output_tests { } /// Opening a project, package, or template via `open_bytes` when unsaved edits exist and - /// `save_project` is present asks the save prompt instead of silently discarding edits. + /// `save_project` is present asks the save prompt instead of silently discarding edits, and + /// sets `ui.web_file` once a deferred `.rgis` replacement completes. #[test] fn open_bytes_with_asks_to_save_unsaved_edits_before_replacing() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let (other_text, _) = Project::default().saved_text(None).unwrap(); let pkg_bytes = rustgis_engine::data::zip::write(&[("other.rgis".into(), other_text.as_bytes().to_vec())]).unwrap(); - for (file, bytes) in - [("other.rgis", other_text.as_bytes()), ("other.rgispkg", pkg_bytes.as_slice()), ("other.rgistemplate", other_text.as_bytes())] - { + for (file, bytes, expected_web_file) in [ + ("other.rgis", other_text.as_bytes(), Some("other.rgis")), + ("other.rgispkg", pkg_bytes.as_slice(), None), + ("other.rgistemplate", other_text.as_bytes(), None), + ] { let mut app = RustGisApp::with_sample(); app.services.open_async = Some(Box::new(|_| {})); app.services.save_project = Some(Box::new(|_, _, _| Ok(()))); app.run("map.rename", json!({"name": "Unsaved Map"})).unwrap(); assert!(app.session.dirty()); - app.open_bytes(file, bytes).unwrap(); - assert!(saveprompt::waiting(&app), "{file}: expected save prompt to wait for user answer"); - assert_eq!(app.session.map().name, "Unsaved Map", "{file}: unsaved edits must not be discarded yet"); - assert!(app.ui.web_file.is_none(), "{file}: web_file must not be set while waiting on save prompt"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 860.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.state_mut().open_bytes(file, bytes).unwrap(); + assert!(saveprompt::waiting(h.state()), "{file}: expected save prompt to wait for user answer"); + assert_eq!(h.state().session.map().name, "Unsaved Map", "{file}: unsaved edits must not be discarded yet"); + assert!(h.state().ui.web_file.is_none(), "{file}: web_file must not be set while waiting on save prompt"); + + for _ in 0..3 { + h.step(); + } + h.get_by_role_and_label(Role::Button, "Don't Save").click(); + for _ in 0..3 { + h.step(); + } + assert!(!saveprompt::waiting(h.state()), "{file}: replacement should complete after Don't Save"); + assert_ne!(h.state().session.map().name, "Unsaved Map", "{file}: project should be replaced after Don't Save"); + assert_eq!(h.state().ui.web_file.as_deref(), expected_web_file, "{file}: web_file after deferred replacement"); } } From 12074733cde11f82960b03068b144237818d5e88 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 19:57:41 -0500 Subject: [PATCH 3/5] fix(ui): say files opened while the save prompt waits; ask before a downloaded project replaces unsaved edits A second project replacement asked for while the save prompt waits is refused with a notice, and files arriving in the inbox then are counted in a notice instead of being opened into the project about to be replaced. A project downloaded by ui.openUrl goes through the save prompt, and names the browser file through ui.opening_file. add_data_file reuses layerchooser::add. --- crates/ui-egui/src/dialogs.rs | 5 +- crates/ui-egui/src/layerchooser.rs | 2 +- crates/ui-egui/src/lib.rs | 73 ++++++++++++++++++++++++++++-- 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 112b2f0bed..4cbe4dacac 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1527,10 +1527,7 @@ fn add_dxf(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { /// Adds a file on disk, read as Add Data reads a file (on a thread of its own when the desktop /// app reads it so, [`crate::readjob`]). fn add_data_file(app: &mut RustGisApp, p: Value) -> Result { - #[cfg(not(target_arch = "wasm32"))] - return crate::readjob::run(app, "layer.addData", p); - #[cfg(target_arch = "wasm32")] - app.run("layer.addData", p) + crate::layerchooser::add(app, p) } /// Adds a drawing on disk, read as Add Data reads a file (on a thread of its own when the desktop diff --git a/crates/ui-egui/src/layerchooser.rs b/crates/ui-egui/src/layerchooser.rs index 94eac85f21..a355486b50 100644 --- a/crates/ui-egui/src/layerchooser.rs +++ b/crates/ui-egui/src/layerchooser.rs @@ -156,7 +156,7 @@ fn list_layers(path: &str, stop: std::sync::Arc) } /// Adds a file, read on a thread of its own when the desktop app reads it so ([`crate::readjob`]). -fn add(app: &mut RustGisApp, p: Value) -> Result { +pub(crate) fn add(app: &mut RustGisApp, p: Value) -> Result { #[cfg(not(target_arch = "wasm32"))] return crate::readjob::run(app, "layer.addData", p); #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9c3366aafb..f724d444d4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3476,6 +3476,13 @@ impl RustGisApp { /// commands without asking ([`Self::run`]). pub fn run_by_user(&mut self, id: &str, params: Value) -> Result { if saveprompt::asks(self, id) { + // The dialog already asks about another replacement: this one isn't queued behind + // it, and says so rather than going nowhere. + if saveprompt::waiting(self) { + let e = tl!("Not opened: answer about the unsaved changes first, then open it again.").to_string(); + self.session.notify(e.clone(), true); + return Err(e); + } let opening_file = self.ui.opening_file; saveprompt::ask(self, saveprompt::Discard::Replace(id.to_string(), params, opening_file)); return Ok(Value::Null); @@ -6331,10 +6338,16 @@ impl RustGisApp { if let Some(f) = file.filter(|_| !package) { p["fileName"] = json!(f); } - let r = self.run("project.openText", p); - if r.is_ok() && !package { - self.ui.web_file = Some(format!("{}.rgis", self.session.project.name)); + // While the dialog asks about another replacement, it isn't opened (the caller says so, + // with its address). + if saveprompt::waiting(self) && saveprompt::asks(self, "project.openText") { + return Err(tl!("Not opened: answer about the unsaved changes first, then open it again.").to_string()); } + // Unsaved changes are asked about first, as for a file opened; a downloaded project file + // names the browser file once it has replaced this one (a package doesn't). + self.ui.opening_file = !package; + let r = self.run_by_user("project.openText", p); + self.ui.opening_file = false; self.map.invalidate(); r } @@ -7693,9 +7706,25 @@ impl RustGisApp { Some(inbox) => std::mem::take(&mut *inbox.lock().unwrap_or_else(|e| e.into_inner())), None => Vec::new(), }; + // While the save prompt asks about replacing this project, the rest aren't opened into + // the project about to be replaced: they're said, as held desktop drops are. + let mut held = 0usize; for (name, bytes) in arrived { + if saveprompt::waiting(self) { + held += 1; + continue; + } let _ = self.open_picked(&name, &bytes); } + if held == 1 { + self.session.notify(tl!("Another file wasn't opened: open it again once you've answered about the unsaved changes."), false); + } else if held > 1 { + let text = crate::i18n::fmt( + "{n} other files weren't opened: open them again once you've answered about the unsaved changes.", + &[("n", &held.to_string())], + ); + self.session.notify(text, false); + } // A script file for the Script pane's Load…, opened with the context its undo needs; said, // not dropped, if something in the inbox started a run meanwhile. if let Some(script) = self.workflow.script_picked.take() { @@ -10797,6 +10826,44 @@ mod peer_output_tests { } } + /// While the save prompt asks about replacing the project, a second project file opened is + /// refused with a notice, and files arriving in the inbox aren't opened into the project + /// about to be replaced: they're counted in a notice. + #[test] + fn files_opened_while_the_save_prompt_waits_are_said() { + let (text, _) = Project::default().saved_text(None).unwrap(); + let mut app = RustGisApp::with_sample(); + app.services.open_async = Some(Box::new(|_| {})); + app.services.save_project = Some(Box::new(|_, _, _| Ok(()))); + let inbox = Inbox::default(); + app.services.inbox = Some(inbox.clone()); + app.run("map.rename", json!({"name": "Unsaved Map"})).unwrap(); + let layers = app.session.map().layers.len(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 860.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.state_mut().open_bytes("first.rgis", text.as_bytes()).unwrap(); + assert!(saveprompt::waiting(h.state())); + let mark = h.state().session.notice_mark(); + assert!(h.state_mut().open_bytes("second.rgis", text.as_bytes()).is_err()); + let points = r#"{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[1,2]},"properties":{}}]}"#; + inbox + .lock() + .unwrap() + .extend([("a.geojson".to_string(), points.as_bytes().to_vec()), ("b.geojson".to_string(), points.as_bytes().to_vec())]); + h.step(); + let notices = h.state().session.notices_since(mark); + assert!(notices.iter().any(|n| n.error && n.text.contains("answer about the unsaved changes")), "got: {notices:?}"); + assert!(notices.iter().any(|n| n.text.contains("2 other files weren't opened")), "got: {notices:?}"); + assert_eq!(h.state().session.map().layers.len(), layers, "nothing is added to the project about to be replaced"); + assert_eq!(h.state().session.map().name, "Unsaved Map"); + } + /// Only a project file the user opened names the browser file: the same `project.openText` /// from a script, Command Search or the Assistant leaves Save asking where to save. #[test] From a3c01c1ed9659f2cd36d1a2a0603a68907007e4a Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:16:01 -0500 Subject: [PATCH 4/5] fix(ui): a picker cancelled while the save prompt waits ends its request A cancelled picker's empty answer still reaches open_picked while the save prompt waits, and isn't counted as a held file. A held DXF answer retires its pending_dxf request, so it doesn't count toward the limit. --- crates/ui-egui/src/lib.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 254b4850cb..ad0313c8cf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7775,7 +7775,14 @@ impl RustGisApp { arrived.sort_by_key(|(name, _)| !replaces_project(name)); let mut held = 0usize; for (name, bytes) in arrived { - if saveprompt::waiting(self) { + // A picker closed without a choice opens nothing, and still ends its request. + let cancelled = name.starts_with('\u{1}') && name.ends_with(':'); + if saveprompt::waiting(self) && !cancelled { + // A held drawing's request ends too, so it doesn't count toward the requests + // still waiting for a file. + if let Some(id) = name.strip_prefix(DXF_PICK).and_then(|p| p.split_once(':')).and_then(|(id, _)| id.parse::().ok()) { + self.ui.pending_dxf.remove(&id); + } held += 1; continue; } @@ -10925,6 +10932,16 @@ mod peer_output_tests { let notices = h.state().session.notices_since(mark); assert!(notices.iter().any(|n| n.error && n.text.contains("answer about the unsaved changes")), "got: {notices:?}"); assert!(notices.iter().any(|n| n.text.contains("2 other files weren't opened")), "got: {notices:?}"); + // A DXF picker cancelled, and one answered, while the prompt waits: both end their + // requests, and only the answered one is said as held. + h.state_mut().ui.pending_dxf.insert(7, Value::Null); + h.state_mut().ui.pending_dxf.insert(8, Value::Null); + let mark = h.state().session.notice_mark(); + inbox.lock().unwrap().extend([(format!("{DXF_PICK}7:"), Vec::new()), (format!("{DXF_PICK}8:plan.dxf"), b"0\nEOF\n".to_vec())]); + h.step(); + assert!(h.state().ui.pending_dxf.is_empty(), "{:?}", h.state().ui.pending_dxf); + let notices = h.state().session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("Another file wasn't opened")), "got: {notices:?}"); assert_eq!(h.state().session.map().layers.len(), layers, "nothing is added to the project about to be replaced"); assert_eq!(h.state().session.map().name, "Unsaved Map"); } From 0839cb276c4bc185ec6aa5c2dfeb9e18c4457dbd Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:40:19 -0500 Subject: [PATCH 5/5] fix(ui): a dropped project template opens as a template layerchooser::add_file sent a .rgistemplate to layer.addData, as project::open_command doesn't count templates, so a template dropped on the desktop window never replaced the project the drop sort and the save prompt were guarding. It now goes to project.fromTemplate, named after the file, through run_by_user so unsaved changes are asked about. --- crates/ui-egui/src/layerchooser.rs | 5 +++++ crates/ui-egui/src/saveprompt.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/crates/ui-egui/src/layerchooser.rs b/crates/ui-egui/src/layerchooser.rs index a355486b50..5b486e793b 100644 --- a/crates/ui-egui/src/layerchooser.rs +++ b/crates/ui-egui/src/layerchooser.rs @@ -92,6 +92,11 @@ pub fn lists_layers(path: &str) -> bool { pub fn add_file(app: &mut RustGisApp, path: &str) -> Result { // Opening a project replaces this one: asked about first when it has unsaved changes. Only // the interface comes here (drops, Add Data, the Browser pane, `ui.addFile`). + // A project template starts a new project from it, named after the file. + if path.trim().to_ascii_lowercase().ends_with(".rgistemplate") { + let name = std::path::Path::new(path.trim()).file_stem().map(|s| s.to_string_lossy().into_owned()); + return app.run_by_user("project.fromTemplate", json!({"path": path, "name": name})); + } let command = rustgis_engine::project::open_command(path); if command != "layer.addData" { return app.run_by_user(command, json!({"path": path})); diff --git a/crates/ui-egui/src/saveprompt.rs b/crates/ui-egui/src/saveprompt.rs index d767c375cf..d252e84cf0 100644 --- a/crates/ui-egui/src/saveprompt.rs +++ b/crates/ui-egui/src/saveprompt.rs @@ -940,6 +940,33 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A project template dropped with data starts a new project from it: asked about first, the + /// data isn't added to the project it replaces, and Don't Save opens the template, not as data. + #[test] + fn a_dropped_template_asks_before_replacing_unsaved_work() { + let dir = folder("template"); + let template = dir.join("atlas.rgistemplate"); + let mut h = launch(); + frames(&mut h, 2); + h.state_mut().run("project.saveTemplate", json!({"path": template.display().to_string()})).unwrap(); + edit(&mut h, "Edited"); + let data = dir.join("sites.geojson"); + std::fs::write(&data, r#"{"type":"FeatureCollection","features":[]}"#).unwrap(); + let said = h.state().session.notices.len(); + for f in [data.clone(), template.clone()] { + h.input_mut().dropped_files.push(std::sync::Arc::new(Dropped(f))); + } + frames(&mut h, 2); + assert!(asking(&h) && h.state().session.map().layer_by_name("sites").is_none()); + assert!(h.state().session.map().layer_by_name("atlas").is_none(), "the template isn't added as data"); + assert!(h.state().session.notices[said..].iter().any(|n| n.text.starts_with("Another dropped file wasn't opened"))); + click(&mut h, "Don't Save"); + assert!(!asking(&h) && !h.state().session.dirty()); + assert_eq!(h.state().session.project.name, "atlas"); + assert!(h.state().session.path.is_none(), "a template opens as a new, unsaved project"); + let _ = std::fs::remove_dir_all(&dir); + } + /// The project changed while the dialog showed (an agent's edit): Don't Save doesn't discard /// what the user wasn't asked about. The dialog says so and asks again; the next answer goes. #[test]