diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d899000448..6f46962c5c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -253,22 +253,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(); @@ -1552,13 +1552,16 @@ 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 { + 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 /// app reads it so, [`crate::readjob`]). pub(crate) fn add_dxf_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) + add_data_file(app, p) } /// The columns of a file picked for Add Delimited Text, split at `separator` (a code of @@ -1742,7 +1745,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)), }; @@ -2541,6 +2544,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> { @@ -2556,8 +2578,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)?; @@ -2653,21 +2674,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(|_| ()) }) @@ -2887,13 +2894,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). @@ -5838,6 +5858,83 @@ mod tests { 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()); + } + /// Helper to attach an editable PostGIS layer with a known table name and baseline versions. fn add_postgis_layer(app: &mut RustGisApp, name: &str, table: &str) -> u32 { use rustgis_engine::data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; diff --git a/crates/ui-egui/src/layerchooser.rs b/crates/ui-egui/src/layerchooser.rs index 94eac85f21..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})); @@ -156,7 +161,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 6862eed518..6d63ec2715 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -194,6 +194,12 @@ fn complete_gp_file(result: Result, id: u64, completed: &Result bool { + rustgis_engine::project::open_command(name) == "project.open" || name.to_ascii_lowercase().ends_with(".rgistemplate") +} + /// Files read asynchronously (browser uploads, drops) waiting to be opened: (file name, bytes). pub type Inbox = std::sync::Arc)>>>; @@ -1135,6 +1141,9 @@ pub struct UiState { pub pending_open: Option<&'static str>, /// The file the project was last saved or opened as (web), which Save downloads again. pub web_file: Option, + /// A project file the user opened is being opened (web): a `project.openText` that succeeds + /// now names [`Self::web_file`]. One from a script, Command Search or the Assistant doesn't. + pub opening_file: bool, /// Add Delimited Text, for the file being picked (web): `null` opens its dialog for the file, /// a script's options are read with it. pub pending_csv: Option, @@ -1377,6 +1386,7 @@ impl Default for UiState { pending_layout_picture: false, pending_open: None, web_file: None, + opening_file: false, pending_csv: None, pending_dxf: Default::default(), next_dxf: 0, @@ -2802,6 +2812,10 @@ impl RustGisApp { return Ok(Value::Null); } if let Some(name) = name.strip_prefix(SHAPEFILE_PICK) { + // An answer with no name is a cancelled picker: nothing to open, nothing to say. + if name.is_empty() { + return Ok(Value::Null); + } if !name.to_ascii_lowercase().ends_with(".zip") { let error = tl!("Choose a zipped Shapefile, or pick its .shp and .dbf together.").to_string(); self.session.notify(error.clone(), true); @@ -2924,7 +2938,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" @@ -2940,7 +2954,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; } @@ -2996,10 +3010,9 @@ 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() { - self.ui.web_file = Some(format!("{}.rgis", self.session.project.name)); - } + self.ui.opening_file = true; + let r = self.run_by_user("project.openText", json!({"text": text, "fileName": name})); + self.ui.opening_file = false; self.map.invalidate(); r } else { @@ -3578,7 +3591,18 @@ impl RustGisApp { /// commands without asking ([`Self::run`]). pub fn run_by_user(&mut self, id: &str, params: Value) -> Result { if saveprompt::asks(self, id) { - saveprompt::ask(self, saveprompt::Discard::Replace(id.to_string(), params)); + // 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; + // A downloaded project is read, once answered, as received from where it came from. + let reach = self.session.receiving(None); + self.session.receiving(reach); + saveprompt::ask(self, saveprompt::Discard::Replace(id.to_string(), params, opening_file, reach)); return Ok(Value::Null); } // A plugin command with a dialog opens it, from the ribbon, a panel button, Command Search @@ -3617,36 +3641,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)?; assistant::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); + } + Ok(()) + } + + /// 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; } - self.reset_after_project_replace(); + // Fields and layers can go while the table is closed: its column views follow them. table::prune_views(self); - layoutview::follow_project(self); - for notice in report.notices() { - self.session.notify(notice, false); - } - Ok(()) } - /// Resets transient UI and editing state tied to the replaced project, shared by ordinary - /// project-replacement commands and peer project replacement. - fn reset_after_project_replace(&mut self) { - self.map.cancel_sketch(); - pluginpanel::cancel_pick(self); - // A project replacing this one hasn't been saved in the browser yet (opening a file - // names it again). + /// 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); (self.workflow.result, self.workflow.error) = (None, None); + 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() { let n = steps.len().to_string(); @@ -3658,7 +3692,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(); - self.ws.task_edit = None; } /// Reports pending header reads retired by either ordinary or peer project replacement. @@ -3885,12 +3918,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); } @@ -3905,16 +3932,17 @@ 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, 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_after_project_replace(); + self.reset_replaced_project(); + // Only a file the user opened names the browser file, not project text a script, + // Command Search or the Assistant opened. + if id == "project.openText" && self.ui.opening_file { + 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. @@ -6298,10 +6326,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 } @@ -7659,13 +7693,39 @@ impl RustGisApp { self.session.notify(text, false); } // Files from the async picker or browser drops. - let arrived: Vec<(String, Vec)> = match &self.services.inbox { + let mut arrived: Vec<(String, Vec)> = match &self.services.inbox { 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. + // A project first, so the data that arrived with it goes into that project, not the one + // it replaces, as for desktop drops. + arrived.sort_by_key(|(name, _)| !replaces_project(name)); + let mut held = 0usize; for (name, bytes) in arrived { + // 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; + } 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() { @@ -7681,7 +7741,7 @@ impl RustGisApp { let mut dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); // A project first, so the data dropped with it goes into that project, not the one // it replaces. While the save prompt asks about replacing this one, the rest wait. - dropped.sort_by_key(|f| rustgis_engine::project::open_command(&f.path().display().to_string()) != "project.open"); + dropped.sort_by_key(|f| !replaces_project(&f.path().display().to_string())); let mut held = 0usize; for f in dropped { let p = f.path().display().to_string(); @@ -10600,6 +10660,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(); + let refused = app.run("ui.exportLayer", json!({"format": "shp"})); + assert!(refused.as_ref().is_err_and(|e| e.contains("download blocked")), "{refused:?}"); + let notices = app.session.notices_since(mark); + 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] @@ -10738,6 +10845,198 @@ 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, 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, 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()); + + 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"); + } + } + + /// 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:?}"); + // 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:?}"); + // A Shapefile picker cancelled while the prompt waits opens nothing and says nothing. + let mark = h.state().session.notice_mark(); + inbox.lock().unwrap().push((SHAPEFILE_PICK.to_string(), Vec::new())); + h.step(); + let notices = h.state().session.notices_since(mark); + assert!(notices.is_empty(), "a cancelled Shapefile picker said: {notices:?}"); + assert_eq!(h.state_mut().open_picked(SHAPEFILE_PICK, &[]), Ok(Value::Null)); + assert!(h.state_mut().open_picked(&format!("{SHAPEFILE_PICK}roads.shp"), &[]).is_err(), "a non-zip name is still refused"); + 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"); + } + + /// A project arriving in the inbox after data opens first: the data isn't added to the + /// project about to be replaced, and is said while the save prompt waits. + #[test] + fn an_inbox_project_opens_before_the_data_with_it() { + 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, + ); + let mark = h.state().session.notice_mark(); + 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()), ("other.rgis".to_string(), text.into_bytes())]); + h.step(); + assert!(saveprompt::waiting(h.state()), "the project asks about the unsaved changes"); + assert_eq!(h.state().session.map().layers.len(), layers, "the data isn't added to the project about to be replaced"); + let notices = h.state().session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("Another file wasn't opened")), "got: {notices:?}"); + // A template and a package replace the project too, and sort first the same way. + assert!(replaces_project("other.rgistemplate") && replaces_project("x.rgispkg") && !replaces_project("a.geojson")); + } + + /// A downloaded project deferred by the save prompt keeps the reach it was received with, + /// for that replacement only. + #[test] + fn a_deferred_download_keeps_its_reach() { + use rustgis_engine::render::rustgis_tiles::address::Reach; + 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(()))); + app.run("map.rename", json!({"name": "Unsaved Map"})).unwrap(); + let was = app.session.receiving(Some(Reach::Public)); + app.ui.opening_file = true; + app.run_by_user("project.openText", json!({"text": text, "fileName": "remote.rgis"})).unwrap(); + app.ui.opening_file = false; + app.session.receiving(was); + assert!( + matches!(&app.save_prompt.asking, Some(saveprompt::Discard::Replace(_, _, true, Some(Reach::Public)))), + "{:?}", + app.save_prompt.asking + ); + } + + /// 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] + fn only_an_opened_file_names_the_browser_file() { + let (text, _) = Project::default().saved_text(None).unwrap(); + let mut app = RustGisApp::with_sample(); + app.run("project.openText", json!({"text": text, "fileName": "scripted.rgis"})).unwrap(); + assert!(app.ui.web_file.is_none(), "a scripted project.openText must not name the browser file"); + app.open_bytes("opened.rgis", text.as_bytes()).unwrap(); + assert_eq!(app.ui.web_file, Some(format!("{}.rgis", app.session.project.name))); + assert!(!app.ui.opening_file); + } + /// 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/saveprompt.rs b/crates/ui-egui/src/saveprompt.rs index 6819bc6a67..d252e84cf0 100644 --- a/crates/ui-egui/src/saveprompt.rs +++ b/crates/ui-egui/src/saveprompt.rs @@ -13,6 +13,7 @@ use serde_json::Value; use crate::RustGisApp; use crate::theme::{Tokens, semibold}; +use rustgis_engine::render::rustgis_tiles::address::Reach; /// The commands that replace the open project. const REPLACES: &[&str] = &["project.new", "project.sample", "project.open", "project.openText", "project.fromTemplate"]; @@ -20,8 +21,10 @@ const REPLACES: &[&str] = &["project.new", "project.sample", "project.open", "pr /// What waits for the user's answer. #[derive(Clone, Debug, PartialEq)] pub(crate) enum Discard { - /// A command replacing the project, with its parameters. - Replace(String, Value), + /// A command replacing the project, with its parameters, whether it opens a project file + /// the user picked ([`crate::UiState::opening_file`]), and the reach of a downloaded project + /// it opens ([`rustgis_engine::Session::receiving`]), restored for that replacement only. + Replace(String, Value, bool, Option), /// Quitting: the window closes once the answer allows it. Quit, } @@ -338,8 +341,12 @@ fn save_then(app: &mut RustGisApp, what: Discard) { /// (`on_exit`); a replacement leaves no unsaved changes, so autosave removes it too. fn proceed(app: &mut RustGisApp, what: Discard) { match what { - Discard::Replace(id, params) => { + Discard::Replace(id, params, opening_file, reach) => { + app.ui.opening_file = opening_file; + let was = app.session.receiving(reach); let _ = app.run(&id, params); + app.session.receiving(was); + app.ui.opening_file = false; app.ui.backstage = false; app.map.invalidate(); } @@ -933,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] diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index c292f99cd0..3afee6024c 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -2463,6 +2463,22 @@ mod tests { } } + /// 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"); + } + /// Attribute table mutations (`edit.setValue`, `edit.delete`, `edit.addFeature`, /// `edit.deleteField`) must not run while the table pane holds an extra `Dataset` clone. #[test] diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 2d4ae1608e..e4f4e41d33 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -4621,6 +4621,7 @@ fn web_save_asks_for_the_file_name() { log.lock().unwrap().push((name.to_string(), bytes.to_vec())); Ok(()) })), + open_async: Some(Box::new(|_| {})), ..Default::default() }; let app = RustGisApp::with_sample().with_services(services);