From 898fb9769c72950f7e844810b913fcddb5299c12 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:57:05 -0500 Subject: [PATCH 1/5] Fix UI dialog, web picker, Python URL, saved-file format, and plugin loss bugs - Generalize source-backed edit dialog target identity tracking (layer ID, live instance ID, owning project/map, and revision-based count refresh) to cover both PostGIS and GeoPackage Save/Discard dialogs, passing numeric layer IDs to pg.pendingEdits, pg.saveEdits, and pg.discardEdits, and clear transient password and CSV buffers when closing addDatabase and addCsv dialogs. - Factor project-replacement UI cleanup into reset_after_project_replace and call it from both run_with_prepared and open_peer_text so peer project replacement also cancels active sketches, shape/vertex drags, plugin picks, pending symbology, stale table views, and task step edits. - Bring browser file-picker accept filters for project and item purposes into parity with the extensions ui-egui handles from bytes, extracted into a unit-tested picker module. - Use urllib.parse.urlsplit/urlunsplit in Python _app_src so embed and lang query parameters are placed before any URL fragment. - Enforce crate::project::check_format before deserializing in presentation.import, report.open, notebook.open (RustGIS format), bookmark.import, and dl.import, and reject Jupyter notebooks whose nbformat is not integer 4. - Propagate GeoJSON ReadReport losses and messages from plugin tool outputs into ToolResult.losses and ToolResult.messages. --- apps/rustgis-python/python/rustgis/_embed.py | 8 +- apps/rustgis-python/tests/test_widget.py | 11 + apps/rustgis-web/src/main.rs | 2 + apps/rustgis-web/src/picker.rs | 83 ++++++ apps/rustgis-web/src/web.rs | 23 +- crates/engine/src/cmd/deeplearning.rs | 4 +- crates/engine/src/cmd/navigate.rs | 1 + crates/engine/src/cmd/notebook.rs | 25 +- crates/engine/src/cmd/presentation.rs | 1 + crates/engine/src/cmd/report.rs | 1 + crates/engine/src/tests.rs | 51 ++++ crates/plugins/src/tools.rs | 87 ++++++- crates/ui-egui/src/dialogs.rs | 261 +++++++++++++++---- crates/ui-egui/src/lib.rs | 140 +++++++--- crates/ui-egui/src/pluginpanel.rs | 11 + crates/ui-egui/src/table.rs | 12 + crates/ui-egui/tests/smoke.rs | 16 +- 17 files changed, 601 insertions(+), 136 deletions(-) create mode 100644 apps/rustgis-web/src/picker.rs diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 7dfc49e095..f90526d118 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -16,7 +16,7 @@ import pathlib import threading from typing import Any, Dict, Iterable, List, Optional, Tuple, Union -from urllib.parse import quote +from urllib.parse import quote, urlsplit, urlunsplit from . import PathLike, RustGISError, Session, _Api, _warn_losses @@ -291,8 +291,10 @@ def _app_src(url: Optional[str], lang: Optional[str]) -> str: lang: The interface language code, or None. """ base = url or os.environ.get("RUSTGIS_WEB_URL") or DEFAULT_URL - query = "embed" + (f"&lang={quote(lang)}" if lang else "") - return base + ("&" if "?" in base else "?") + query + parts = urlsplit(base) + extra = "embed" + (f"&lang={quote(lang)}" if lang else "") + query = f"{parts.query}&{extra}" if parts.query else extra + return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment)) def _data_args(path: PathLike) -> Tuple[str, Dict[str, Any]]: diff --git a/apps/rustgis-python/tests/test_widget.py b/apps/rustgis-python/tests/test_widget.py index 47dc12736a..7161bc9c08 100644 --- a/apps/rustgis-python/tests/test_widget.py +++ b/apps/rustgis-python/tests/test_widget.py @@ -225,3 +225,14 @@ def test_widget_repeated_table_id_cannot_gain_a_retained_key(): from_app(m, json.dumps(incoming)) assert s._engine._peer_text()[1] == 0 assert any("lost their keys" in notice for notice, _ in m.notices()) + + +def test_app_src_preserves_fragments_and_existing_query(): + from rustgis._embed import _app_src + + assert _app_src("https://web.rustgis.app/", None) == "https://web.rustgis.app/?embed" + assert _app_src("https://web.rustgis.app/#map=5/10/20", None) == "https://web.rustgis.app/?embed#map=5/10/20" + assert _app_src("https://web.rustgis.app/#map=5/10/20", "fr") == "https://web.rustgis.app/?embed&lang=fr#map=5/10/20" + assert _app_src("https://web.rustgis.app/?webgl#view", "de") == "https://web.rustgis.app/?webgl&embed&lang=de#view" + assert _app_src("https://web.rustgis.app/?webgl&theme=dark", None) == "https://web.rustgis.app/?webgl&theme=dark&embed" + assert _app_src("https://web.rustgis.app/?#frag", None) == "https://web.rustgis.app/?embed#frag" diff --git a/apps/rustgis-web/src/main.rs b/apps/rustgis-web/src/main.rs index 5de3416060..da61e5909f 100644 --- a/apps/rustgis-web/src/main.rs +++ b/apps/rustgis-web/src/main.rs @@ -25,6 +25,8 @@ mod geolibre; #[cfg(target_arch = "wasm32")] mod parts; #[cfg(any(target_arch = "wasm32", test))] +mod picker; +#[cfg(any(target_arch = "wasm32", test))] mod request; #[cfg(target_arch = "wasm32")] mod web; diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs new file mode 100644 index 0000000000..39611ec639 --- /dev/null +++ b/apps/rustgis-web/src/picker.rs @@ -0,0 +1,83 @@ +//! Browser file-picker extension filters, kept in parity with the extensions `ui-egui` accepts. + +/// Extensions offered when opening a project (`purpose == "project"`). +pub(crate) const PROJECT_EXTS: &[&str] = &["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"]; + +/// Extensions offered when opening a project item (`purpose == "item"`). +pub(crate) const ITEM_EXTS: &[&str] = &[ + "rgismap", + "rgismpk", + "rgispkg", + "rgislyr", + "rgisstyle", + "rgisramp", + "rgistemplate", + "rgistask", + "rgisbookmarks", + "rgis", + "rgisx", + "qml", + "rgisreport", + "rgisrpttemplate", + "rgispres", + "rgisnb", + "ipynb", + "rgisdlpk", + "rgisfield", + "json", + "rgistool", + "rgislayout", +]; + +/// Returns the static extension filter list for a named picker `purpose`, when it uses one. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str]> { + match purpose { + "project" => Some(PROJECT_EXTS), + "item" => Some(ITEM_EXTS), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every project and item extension that `ui-egui` opens via `open_async("project")` or + /// `open_async("item")` must be selectable in the browser file picker. + #[test] + fn browser_picker_extensions_cover_all_project_and_item_formats() { + let project = filter_extensions("project").unwrap(); + for ext in ["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"] { + assert!(project.contains(&ext), "project picker is missing .{ext}"); + } + + let item = filter_extensions("item").unwrap(); + for ext in [ + "rgismap", + "rgismpk", + "rgispkg", + "rgislyr", + "rgisstyle", + "rgisramp", + "rgistemplate", + "rgistask", + "rgisbookmarks", + "rgis", + "rgisx", + "qml", + "rgisreport", + "rgisrpttemplate", + "rgispres", + "rgisnb", + "ipynb", + "rgisdlpk", + "rgisfield", + "json", + "rgistool", + "rgislayout", + ] { + assert!(item.contains(&ext), "item picker is missing .{ext}"); + } + } +} diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e0c7628e58..93f747937f 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1366,29 +1366,12 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e } else if purpose == "shapefile" { rfd::AsyncFileDialog::new().add_filter("Shapefile", &["shp", "dbf", "shx", "prj", "cpg", "zip"]) } else if purpose == "project" { - rfd::AsyncFileDialog::new().add_filter( - rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, GeoLibre)"), - &["rgis", "rgisx", "rgispkg", "geolibre", "json"], - ) + rfd::AsyncFileDialog::new() + .add_filter(rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)"), crate::picker::PROJECT_EXTS) } else if purpose == "qgisProject" { rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("QGIS project"), &["qgs", "qgz"]) } else if purpose == "item" { - rfd::AsyncFileDialog::new().add_filter( - "RustGIS items", - &[ - "rgismap", - "rgismpk", - "rgispkg", - "rgislyr", - "rgisstyle", - "rgisramp", - "rgistemplate", - "rgistask", - "rgisbookmarks", - "rgis", - "rgisx", - ], - ) + rfd::AsyncFileDialog::new().add_filter("RustGIS items", crate::picker::ITEM_EXTS) } else if purpose == "ramp" { rfd::AsyncFileDialog::new().add_filter("Colour ramps", &["rgisramp", "xml", "qml", "txt", "clr", "cpt"]) } else if purpose == "layout" { diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index c73c7e4740..c374980fb5 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -89,7 +89,9 @@ pub fn commands() -> Vec { // Only the model is inflated, whatever else the package holds. let entries = rustgis_data::zip::read_matching(&bytes, |n| n == "model.json")?; let json = entries.first().map(|e| &e.1).ok_or("not a deep learning package (no model.json)")?; - let mut m: DlModel = serde_json::from_slice(json).map_err(|e| format!("not a deep learning package: {e}"))?; + let text = std::str::from_utf8(json).map_err(|e| format!("not a deep learning package: {e}"))?; + crate::project::check_format(text, "deep learning package")?; + let mut m: DlModel = serde_json::from_str(text).map_err(|e| format!("not a deep learning package: {e}"))?; m.model.validate()?; for c in &mut m.model.classes { *c = c.chars().take(200).collect(); diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 7463431b39..4836121a92 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -1490,6 +1490,7 @@ pub(crate) fn bookmarks_file(map: &Map) -> Result, String> { fn import_bookmarks(s: &mut Session, p: &Value) -> CmdResult { let text = super::items::read_text(p)?; + crate::project::check_format(&text, "bookmarks file")?; let v: Value = serde_json::from_str(&text).map_err(|e| format!("not a RustGIS bookmarks file: {e}"))?; let list = v.get("bookmarks").and_then(Value::as_array).ok_or("not a RustGIS bookmarks file: no bookmarks")?; let m = s.map_mut(); diff --git a/crates/engine/src/cmd/notebook.rs b/crates/engine/src/cmd/notebook.rs index 4a35c145ae..b681837500 100644 --- a/crates/engine/src/cmd/notebook.rs +++ b/crates/engine/src/cmd/notebook.rs @@ -485,11 +485,25 @@ fn jupyter_outputs(outputs: &[Value]) -> (String, bool) { /// A RustGIS or Jupyter notebook. fn parse(text: &str, fallback_name: &str) -> Result { let v: Value = serde_json::from_str(text).map_err(|e| format!("not a notebook: {e}"))?; - // nbformat 3 keeps its cells in worksheets: opened as 4, they'd be lost on save. - if let Some(major) = v.get("nbformat").and_then(Value::as_u64).filter(|n| *n < 4) { - return Err(format!("this is an nbformat {major} notebook; RustGIS opens nbformat 4 notebooks (Jupyter converts older ones)")); - } - if v.get("nbformat").is_some() { + // Jupyter notebooks must be nbformat 4: older ones keep cells in worksheets and newer ones + // may hold structure RustGIS would lose on save. + if let Some(nbformat) = v.get("nbformat") { + match nbformat.as_u64() { + Some(4) => {} + Some(major) if major < 4 => { + return Err(format!( + "this is an nbformat {major} notebook; RustGIS opens nbformat 4 notebooks (Jupyter converts older ones)" + )); + } + Some(major) => { + return Err(format!( + "this is an nbformat {major} notebook; RustGIS opens nbformat 4 notebooks. Update RustGIS to open newer ones." + )); + } + None => { + return Err("not a Jupyter notebook: nbformat must be integer 4".into()); + } + } let meta = v.get("metadata").filter(|m| m.is_object()); let name = meta.and_then(|m| m.get("title")).and_then(Value::as_str).unwrap_or(fallback_name).to_string(); // Kept even when empty: a Jupyter notebook that doesn't say it's RustGIS isn't commands. @@ -528,6 +542,7 @@ fn parse(text: &str, fallback_name: &str) -> Result { } return Ok(nb); } + crate::project::check_format(text, "notebook")?; let cells = v.get("cells").and_then(Value::as_array).map_or(0, Vec::len); if cells > MAX_CELLS { return Err(format!("this notebook has {cells} cells; RustGIS opens notebooks of up to {MAX_CELLS}")); diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 4f6baf9e88..1fef8f227c 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -51,6 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"name"?, "title"?: the title page's text}"#), C::new("presentation.import", "Import Presentation", "Publish › Presentation", |s, p| { let text = super::items::read_text(p)?; + crate::project::check_format(&text, "presentation")?; let mut pres: Presentation = serde_json::from_str(&text).map_err(|e| format!("not a RustGIS presentation: {e}"))?; let repairs = pres.clamp(); let (name, cut) = unique_name(s, "Import Presentation", "the name from the file", &pres.name); diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 171886ea2d..b01f79ed6e 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -653,6 +653,7 @@ pub fn report_file(s: &Session, i: usize, template: bool) -> Result, Str fn open(s: &mut Session, p: &Value) -> CmdResult { let text = super::items::read_text(p)?; + crate::project::check_format(&text, "report")?; let mut r: Report = serde_json::from_str(&text).map_err(|e| format!("not a RustGIS report: {e}"))?; let repairs = r.clamp(); import_layer(s, p, &mut r)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a0c70f2c78..2e7de15873 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -61999,3 +61999,54 @@ fn a_transparency_reads_back_without_float_noise() { assert_eq!(crate::cmd::project::percent(33.3), json!(33.3)); assert_eq!(crate::cmd::project::percent(0.0), json!(0.0)); } + +/// Every saved-item reader refuses files saved by a newer format version or requiring an unknown +/// capability before deserializing, and Jupyter notebook import refuses any `nbformat` other than +/// integer 4. +#[test] +fn saved_item_readers_refuse_future_format_requires_and_non_v4_nbformat() { + use base64::Engine; + let mut s = world(); + let cases: &[(&str, Value)] = &[ + ("presentation.import", json!({"name": "Deck", "pages": []})), + ("report.open", json!({"name": "Rep", "layer": "Cities"})), + ("notebook.open", json!({"name": "Notes", "cells": []})), + ("bookmark.import", json!({"type": "rustgisBookmarks", "bookmarks": []})), + ]; + for (cmd, base) in cases { + let mut future = base.clone(); + future["format"] = json!(999); + let err = s.run(cmd, &json!({"text": future.to_string()})).unwrap_err(); + assert!(err.contains("newer RustGIS"), "{cmd} future format: {err}"); + + let mut req = base.clone(); + req["requires"] = json!(["future-feature-x"]); + let err = s.run(cmd, &json!({"text": req.to_string()})).unwrap_err(); + assert!(err.contains("future-feature-x"), "{cmd} unknown requires: {err}"); + } + + // Deep learning package (`dl.import`) checks `model.json` inside the ZIP archive. + let make_dlpk = |model_json: &Value| -> String { + let buf = rustgis_data::zip::write(&[("model.json".into(), model_json.to_string().into_bytes())]).unwrap(); + base64::engine::general_purpose::STANDARD.encode(buf) + }; + let future_dl = make_dlpk(&json!({"format": 999, "name": "M"})); + let err = s.run("dl.import", &json!({"data": future_dl})).unwrap_err(); + assert!(err.contains("newer RustGIS"), "dl.import future format: {err}"); + let req_dl = make_dlpk(&json!({"requires": ["future-dl-op"], "name": "M"})); + let err = s.run("dl.import", &json!({"data": req_dl})).unwrap_err(); + assert!(err.contains("future-dl-op"), "dl.import unknown requires: {err}"); + + // Jupyter notebooks must declare integer `nbformat: 4`. + for (bad, needle) in [ + (json!({"nbformat": 5, "cells": []}), "nbformat 5"), + (json!({"nbformat": 3, "cells": []}), "nbformat 3"), + (json!({"nbformat": "4", "cells": []}), "nbformat"), + (json!({"nbformat": null, "cells": []}), "nbformat"), + ] { + let err = s.run("notebook.open", &json!({"text": bad.to_string()})).unwrap_err(); + assert!(err.contains(needle), "expected {needle} for {bad}, got: {err}"); + } + let ok_v4 = json!({"nbformat": 4, "cells": [{"cell_type": "markdown", "source": "ok"}]}); + s.run("notebook.open", &json!({"text": ok_v4.to_string()})).unwrap(); +} diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index 98cb993f27..f15956744a 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -397,20 +397,19 @@ pub fn file_extensions(tool: &str, param: &str) -> Vec { } /// Reads a dataset a tool returned: `{"name": "...", "geojson": {FeatureCollection}}`. -fn dataset(v: &Value, fallback: &str) -> Result { +fn dataset(v: &Value, fallback: &str) -> Result<(rustgis_data::Dataset, rustgis_data::ReadReport), String> { let name = v.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).unwrap_or(fallback); let gj = v.get("geojson").ok_or_else(|| format!("{name}: an output has no 'geojson'"))?; if gj.get("features").and_then(Value::as_array).is_some_and(|f| f.len() > MAX_FEATURES) { return Err(format!("{name}: too many features")); } - let (ds, _) = rustgis_data::io::read_geojson(&gj.to_string(), name).map_err(|e| format!("{name}: {e}"))?; - Ok(ds) + rustgis_data::io::read_geojson(&gj.to_string(), name).map_err(|e| format!("{name}: {e}")) } /// Turns a tool's reply into a result: new `layers` and `tables`, or a `selection` /// (`{"layer": name, "rows": [...]}`), with `messages`. fn output(reply: &Value, tool: &str) -> Result { - let messages: Vec = reply + let mut messages: Vec = reply .get("messages") .and_then(Value::as_array) .map(|a| a.iter().filter_map(Value::as_str).take(200).map(str::to_string).collect()) @@ -425,13 +424,26 @@ fn output(reply: &Value, tool: &str) -> Result { return Ok(ToolResult { losses: Vec::new(), output: Output::Selection { layer, rows }, messages }); } let mut outs = Vec::new(); + let mut losses = Vec::new(); + let mut push_report = |name: &str, report: rustgis_data::ReadReport| { + for note in report.messages.prefixed(name) { + match note.loss { + Some(code) => losses.push(rustgis_data::loss::LossMessage { code, text: note.text }), + None => messages.push(note.text), + } + } + }; for v in reply.get("layers").and_then(Value::as_array).into_iter().flatten().take(64) { - outs.push(OutputLayer::Vector(dataset(v, tool)?)); + let (ds, report) = dataset(v, tool)?; + push_report(&ds.name, report); + outs.push(OutputLayer::Vector(ds)); } for v in reply.get("tables").and_then(Value::as_array).into_iter().flatten().take(64) { - outs.push(OutputLayer::Table(dataset(v, tool)?)); + let (ds, report) = dataset(v, tool)?; + push_report(&ds.name, report); + outs.push(OutputLayer::Table(ds)); } - Ok(ToolResult { losses: Vec::new(), output: Output::Layers(outs), messages }) + Ok(ToolResult { losses, output: Output::Layers(outs), messages }) } #[cfg(test)] @@ -470,4 +482,65 @@ mod tests { assert_eq!(f.len(), 1); assert!(near(&f[0], 11.6, 48.8), "{picked}"); } + + /// GeoJSON loss notices from plugin tool outputs (layers and tables) reach `ToolResult.losses` + /// (and unclassified notices reach `ToolResult.messages`), while clean outputs emit none. + #[test] + fn plugin_tool_output_propagates_geojson_loss_notices_and_stays_clean_when_lossless() { + let clean = json!({ + "layers": [{ + "name": "Clean", + "geojson": { + "type": "FeatureCollection", + "features": [{"type": "Feature", "properties": {"a": 1}, "geometry": {"type": "Point", "coordinates": [10.0, 50.0]}}] + } + }], + "tables": [{ + "name": "CleanTable", + "geojson": { + "type": "FeatureCollection", + "features": [{"type": "Feature", "properties": {"b": 2}, "geometry": null}] + } + }] + }); + let res = output(&clean, "demo").unwrap(); + assert!(res.losses.is_empty(), "clean output must have no losses: {:?}", res.losses); + assert!(res.messages.is_empty(), "clean output must have no messages: {:?}", res.messages); + + let lossy = json!({ + "layers": [{ + "name": "Peaks", + "geojson": { + "type": "FeatureCollection", + "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:CUSTOM::999"}}, + "features": [{"type": "Feature", "properties": {"name": "A"}, "geometry": {"type": "Point", "coordinates": [10.0, 50.0, 1200.0]}}] + } + }], + "tables": [{ + "name": "Summary", + "geojson": { + "type": "FeatureCollection", + "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:CUSTOM::888"}}, + "features": [{"type": "Feature", "properties": {"n": 1}, "geometry": null}] + } + }] + }); + let res = output(&lossy, "demo").unwrap(); + assert!( + res.losses.iter().any(|l| l.code == rustgis_data::loss::LossCode::DroppedZm && l.text.starts_with("Peaks: ")), + "expected DroppedZm loss for Peaks: {:?}", + res.losses + ); + assert!( + res.losses.iter().any(|l| l.code == rustgis_data::loss::LossCode::AssumedCrs && l.text.starts_with("Peaks: ")), + "expected AssumedCrs loss for Peaks: {:?}", + res.losses + ); + assert!( + res.losses.iter().any(|l| l.code == rustgis_data::loss::LossCode::AssumedCrs && l.text.starts_with("Summary: ")), + "expected AssumedCrs loss for Summary: {:?}", + res.losses + ); + assert!(res.messages.is_empty(), "classified losses belong in losses only: {:?}", res.messages); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ef0d3dc4c5..516378e8de 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -34,13 +34,13 @@ pub struct Dialogs { /// project it is in ([`Session::opened`]) and its id, which another project may give again; /// None for the active layer. pub table: Option<(u64, u32)>, - /// GeoPackage save/discard targets use IDs because display names can repeat. - pub gpkg_layer: Option, + /// PostGIS and GeoPackage save/discard targets use IDs because display names can repeat. + pub source_layer: Option, /// The live instance captured with the map-local ID; Undo can make that ID reusable. - pub gpkg_instance: Option, + pub source_instance: Option, /// Layer IDs are map-local; source writes must stay in the captured project and map. - pub gpkg_map: Option<(u64, usize, String)>, - /// The source-backed layer last counted: its name for PostGIS, numeric ID for GeoPackage. + pub source_map: Option<(u64, usize, String)>, + /// The source-backed layer last counted, by numeric ID. pub counted: String, /// Revision after the last count command, which itself advances the session revision. pub counted_revision: Option, @@ -269,14 +269,17 @@ impl Dialogs { // The active layer when it is from PostGIS, else the first that is. "pgSave" | "pgDiscard" => { let pg = |l: &&rustgis_engine::map::Layer| l.postgis.is_some(); - self.layer = active.filter(pg).or_else(|| s.map().layers.iter().find(pg)).map(|l| l.name.clone()).unwrap_or_default(); + let layer = active.filter(pg).or_else(|| s.map().layers.iter().find(pg)); + self.source_layer = layer.map(|l| l.id); + self.source_instance = layer.map(|l| l.instance_id()); + self.source_map = Some((s.opened, s.project.active_map, s.map().name.clone())); } "gpkgSave" | "gpkgDiscard" => { let gpkg = |l: &&rustgis_engine::map::Layer| l.gpkg.is_some(); let layer = active.filter(gpkg).or_else(|| s.map().layers.iter().find(gpkg)); - self.gpkg_layer = layer.map(|l| l.id); - self.gpkg_instance = layer.map(|l| l.instance_id()); - self.gpkg_map = Some((s.opened, s.project.active_map, s.map().name.clone())); + self.source_layer = layer.map(|l| l.id); + self.source_instance = layer.map(|l| l.instance_id()); + self.source_map = Some((s.opened, s.project.active_map, s.map().name.clone())); } // A table of addresses is what's usually geocoded: picked by its id (`flag` says the // choice is a table), since names can repeat. @@ -290,34 +293,53 @@ impl Dialogs { Ok(()) } - fn gpkg_owner(&self, s: &Session) -> Result<(), String> { + fn source_owner(&self, s: &Session, prefix: &str) -> Result<(), String> { if !self - .gpkg_map + .source_map .as_ref() .is_some_and(|(project, index, name)| *project == s.opened && *index == s.project.active_map && *name == s.map().name) { - return Err(tl!("The active project or map changed; reopen the GeoPackage dialog for the intended layer.").into()); + let msg = if prefix == "pg" { + tl!("The active project or map changed; reopen the PostGIS dialog for the intended layer.") + } else { + tl!("The active project or map changed; reopen the GeoPackage dialog for the intended layer.") + }; + return Err(msg.into()); } Ok(()) } - fn gpkg_target(&self, s: &Session) -> Result { - self.gpkg_owner(s)?; - let id = self.gpkg_layer.ok_or_else(|| tl!("Choose a GeoPackage layer").to_string())?; - if !s.map().layer(id).is_some_and(|l| l.gpkg.is_some() && Some(l.instance_id()) == self.gpkg_instance) { - return Err(tl!("The selected GeoPackage layer is no longer available; choose a layer").to_string()); + fn source_target(&self, s: &Session, prefix: &str) -> Result { + self.source_owner(s, prefix)?; + let id = self.source_layer.ok_or_else(|| { + if prefix == "pg" { tl!("Choose a PostGIS layer").to_string() } else { tl!("Choose a GeoPackage layer").to_string() } + })?; + let matches = |l: &rustgis_engine::map::Layer| { + let backed = if prefix == "pg" { l.postgis.is_some() } else { l.gpkg.is_some() }; + backed && Some(l.instance_id()) == self.source_instance + }; + if !s.map().layer(id).is_some_and(matches) { + let msg = if prefix == "pg" { + tl!("The selected PostGIS layer is no longer available; choose a layer") + } else { + tl!("The selected GeoPackage layer is no longer available; choose a layer") + }; + return Err(msg.to_string()); } Ok(id) } } -/// Whether `error` is a target refusal from [`Dialogs::gpkg_target`], which a later valid +/// Whether `error` is a target refusal from [`Dialogs::source_target`], which a later valid /// target (Redo restoring the layer) makes stale. Save failures and other errors aren't. -fn is_gpkg_target_error(error: &str) -> bool { +fn is_source_target_error(error: &str) -> bool { [ tl!("The active project or map changed; reopen the GeoPackage dialog for the intended layer."), tl!("Choose a GeoPackage layer"), tl!("The selected GeoPackage layer is no longer available; choose a layer"), + tl!("The active project or map changed; reopen the PostGIS dialog for the intended layer."), + tl!("Choose a PostGIS layer"), + tl!("The selected PostGIS layer is no longer available; choose a layer"), ] .contains(&error) } @@ -1008,6 +1030,12 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { }); if (!open || close) && app.dialogs.open == Some(which) { app.dialogs.open = None; + if which == "addDatabase" { + app.dialogs.b.clear(); + } + if which == "addCsv" { + app.dialogs.csv = None; + } if which == "addDxf" { app.dialogs.dxf = None; } @@ -2261,7 +2289,7 @@ fn add_database(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { ) .labelled_by(input_label.id); ui.end_row(); - ui.label(tl!("Table")); + let table_label = ui.label(tl!("Table")); ui.horizontal(|ui| { let shown = if app.dialogs.c.is_empty() { tl!("All tables with geometry").to_string() } else { app.dialogs.c.clone() }; egui::ComboBox::from_id_salt("db_table") @@ -2274,6 +2302,7 @@ fn add_database(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { } }) .response + .labelled_by(table_label.id) .on_hover_text(tl!("Table")); list = ui.button(tl!("List Tables")).clicked(); }); @@ -2521,9 +2550,7 @@ fn gpkg_add_layer(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { /// A source-backed layer to save or discard the edits of, and what changed in it: its table /// and how many rows are new, changed and deleted (cached until the selection or session changes). fn source_layer_edits(app: &mut RustGisApp, ui: &mut egui::Ui, prefix: &'static str) { - if prefix == "gpkg" - && let Err(error) = app.dialogs.gpkg_owner(&app.session) - { + if let Err(error) = app.dialogs.source_owner(&app.session, prefix) { app.dialogs.list.clear(); app.dialogs.counted.clear(); app.dialogs.error = Some(error); @@ -2538,52 +2565,47 @@ fn source_layer_edits(app: &mut RustGisApp, ui: &mut egui::Ui, prefix: &'static .map(|l| (l.id, l.instance_id(), l.name.clone())) .collect(); egui::Grid::new(("source_edits", prefix)).num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { - ui.label(tl!("Layer")); - let selected = if prefix == "gpkg" { - layers - .iter() - .find(|(id, instance, _)| Some(*id) == app.dialogs.gpkg_layer && Some(*instance) == app.dialogs.gpkg_instance) - .map(|(id, _, name)| format!("{name} (#{id})")) - .unwrap_or_else(|| tl!("Choose a layer").to_string()) - } else { - app.dialogs.layer.clone() - }; - let previous = app.dialogs.gpkg_layer.zip(app.dialogs.gpkg_instance); + let layer_label = ui.label(tl!("Layer")); + let selected = layers + .iter() + .find(|(id, instance, _)| Some(*id) == app.dialogs.source_layer && Some(*instance) == app.dialogs.source_instance) + .map(|(id, _, name)| format!("{name} (#{id})")) + .unwrap_or_else(|| tl!("Choose a layer").to_string()); + let previous = app.dialogs.source_layer.zip(app.dialogs.source_instance); let mut selected_instance = previous; - egui::ComboBox::from_id_salt(("source_edit_layer", prefix)).selected_text(selected).width(260.0).show_ui(ui, |ui| { - for (id, instance, name) in &layers { - if prefix == "gpkg" { + egui::ComboBox::from_id_salt(("source_edit_layer", prefix)) + .selected_text(selected) + .width(260.0) + .show_ui(ui, |ui| { + for (id, instance, name) in &layers { ui.selectable_value(&mut selected_instance, Some((*id, *instance)), format!("{name} (#{id})")); - } else { - ui.selectable_value(&mut app.dialogs.layer, name.clone(), name); } - } - }); - if prefix == "gpkg" && selected_instance != previous { - app.dialogs.gpkg_layer = selected_instance.map(|(id, _)| id); - app.dialogs.gpkg_instance = selected_instance.map(|(_, instance)| instance); + }) + .response + .labelled_by(layer_label.id); + if selected_instance != previous { + app.dialogs.source_layer = selected_instance.map(|(id, _)| id); + app.dialogs.source_instance = selected_instance.map(|(_, instance)| instance); app.dialogs.error = None; } ui.end_row(); - let counted = - if prefix == "gpkg" { app.dialogs.gpkg_layer.map(|id| id.to_string()).unwrap_or_default() } else { app.dialogs.layer.clone() }; - let invalid = if prefix == "gpkg" { app.dialogs.gpkg_target(&app.session).err() } else { None }; + let counted = app.dialogs.source_layer.map(|id| id.to_string()).unwrap_or_default(); + let invalid = app.dialogs.source_target(&app.session, prefix).err(); if invalid.is_some() || app.dialogs.counted != counted - || (prefix == "gpkg" && app.dialogs.counted_revision != Some(app.session.revision)) - || (prefix == "gpkg" && app.dialogs.counted_instance != app.dialogs.gpkg_instance) + || app.dialogs.counted_revision != Some(app.session.revision) + || app.dialogs.counted_instance != app.dialogs.source_instance { app.dialogs.counted = counted; - app.dialogs.counted_instance = app.dialogs.gpkg_instance; + app.dialogs.counted_instance = app.dialogs.source_instance; let result = if let Some(error) = invalid { Err(error) } else { - let target = if prefix == "gpkg" { json!(app.dialogs.gpkg_layer) } else { json!(app.dialogs.layer) }; - app.run(&format!("{prefix}.pendingEdits"), json!({"layer": target})) + app.run(&format!("{prefix}.pendingEdits"), json!({"layer": app.dialogs.source_layer})) }; app.dialogs.list = match result { Ok(v) => { - if prefix == "gpkg" && app.dialogs.error.as_deref().is_some_and(is_gpkg_target_error) { + if app.dialogs.error.as_deref().is_some_and(is_source_target_error) { app.dialogs.error = None; } vec![ @@ -2626,7 +2648,8 @@ fn pg_save(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { ui.label(egui::RichText::new(tl!("Saves the layer's edits to its table in one transaction. When a row you changed or deleted was changed or deleted in the database since it was loaded, or a new row's key is taken, nothing is saved and the rows are listed.")).weak()); source_layer_edits(app, ui, "pg"); buttons(app, ui, "Save", |app| { - let r = app.run("pg.saveEdits", json!({"layer": app.dialogs.layer})).map(|_| ()); + let id = app.dialogs.source_target(&app.session, "pg")?; + let r = app.run("pg.saveEdits", json!({"layer": id})).map(|_| ()); // Counted again, whatever happened. app.dialogs.counted.clear(); r @@ -2637,7 +2660,10 @@ fn pg_save(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { fn pg_discard(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { ui.label(egui::RichText::new(tl!("Loads the layer's rows again as they are in the database now. Its edits that weren't saved are dropped (Undo brings them back).")).weak()); source_layer_edits(app, ui, "pg"); - buttons(app, ui, "Discard", |app| app.run("pg.discardEdits", json!({"layer": app.dialogs.layer})).map(|_| ())) + buttons(app, ui, "Discard", |app| { + let id = app.dialogs.source_target(&app.session, "pg")?; + app.run("pg.discardEdits", json!({"layer": id})).map(|_| ()) + }) } /// Save a GeoPackage layer's edits to its table in one transaction. @@ -2645,7 +2671,7 @@ fn gpkg_save(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { ui.label(egui::RichText::new(tl!("Saves the layer's edits to its table in the GeoPackage file in one transaction. When a row you changed or deleted was changed or deleted in the file since it was loaded, nothing is saved and the rows are listed. Saving the project keeps edits in the project only; exporting writes a new file.")).weak()); source_layer_edits(app, ui, "gpkg"); buttons(app, ui, "Save", |app| { - let id = app.dialogs.gpkg_target(&app.session)?; + let id = app.dialogs.source_target(&app.session, "gpkg")?; let r = app.run("gpkg.saveEdits", json!({"layer": id})).map(|_| ()); app.dialogs.counted.clear(); r @@ -2662,7 +2688,7 @@ fn gpkg_discard(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { ); source_layer_edits(app, ui, "gpkg"); buttons(app, ui, "Discard", |app| { - let id = app.dialogs.gpkg_target(&app.session)?; + let id = app.dialogs.source_target(&app.session, "gpkg")?; app.run("gpkg.discardEdits", json!({"layer": id})).map(|_| ()) }) } @@ -5153,4 +5179,125 @@ mod tests { h.run_steps(4); assert_eq!(h.state().dialogs.open, None); } + + /// 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}; + use rustgis_engine::map::source::{PostgisEdit, PostgisOrigin, versions_of}; + let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for (i, x) in [0.0, 1.0, 2.0].into_iter().enumerate() { + ds.push(Some(Geometry::Point(Coord::new(x, 20.0))), vec![Value::Text("original".into())]); + if let Some(f) = ds.features.get_mut(i) { + f.id = (i + 1) as u64; + } + } + let baseline = versions_of(&ds.features, &Default::default(), &[(1, 1), (2, 1), (3, 1)].into_iter().collect()); + let id = app.session.map_mut().add_dataset(ds); + app.session.map_mut().layer_mut(id).unwrap().postgis = Some(PostgisEdit { + origin: PostgisOrigin { database: "postgres:host=127.0.0.1 dbname=test".into(), table: table.into(), family: None, crs: None }, + key: "id".into(), + srid: 4326, + writable: true, + condition: None, + limit: 1000, + versions: baseline, + }); + app.session.revision += 1; + id + } + + /// PostGIS Save/Discard dialogs distinguish duplicate layer names by numeric ID, refresh + /// pending-edit counts as session revisions advance, and refuse stale targets when the map, + /// project, or layer instance changes. + #[test] + fn postgis_edit_dialogs_track_layer_identity_and_refresh_counts() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("project.new", json!({})).unwrap(); + app.run("edit.enable", json!({"on": true})).unwrap(); + let upper = add_postgis_layer(&mut app, "Roads", "public.roads_upper"); + let lower = add_postgis_layer(&mut app, "Roads", "public.roads_lower"); + app.run("edit.setValue", json!({"layer": upper, "row": 0, "field": "name", "value": "u0"})).unwrap(); + app.run("edit.setValue", json!({"layer": lower, "row": 0, "field": "name", "value": "l0"})).unwrap(); + app.run("edit.setValue", json!({"layer": lower, "row": 1, "field": "name", "value": "l1"})).unwrap(); + app.run("layer.select", json!({"layer": lower})).unwrap(); + app.run("ui.dialog", json!({"name": "pgSave"})).unwrap(); + + let mut h = app_harness(app); + h.run_steps(3); + assert_eq!(h.state().dialogs.list.first().map(String::as_str), Some("public.roads_lower"), "must target active duplicate by ID"); + assert_eq!(h.state().dialogs.list.get(2).map(String::as_str), Some("2")); + + // Further edits while the dialog stays open refresh the pending counts. + h.state_mut().run("edit.setValue", json!({"layer": lower, "row": 2, "field": "name", "value": "l2"})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().dialogs.list.get(2).map(String::as_str), Some("3"), "open pgSave must refresh counts on revision change"); + + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().dialogs.list.get(2).map(String::as_str), Some("2")); + + // Switching the active map invalidates the captured PostGIS dialog target. + h.state_mut().run("map.new", json!({"name": "Other"})).unwrap(); + h.run_steps(3); + assert!(h.state().dialogs.list.is_empty()); + assert!(h.state().dialogs.error.as_deref().is_some_and(|e| e.contains("project or map changed")), "{:?}", h.state().dialogs.error); + h.get_by_role_and_label(Role::Button, "Save").click(); + h.run_steps(3); + assert_eq!(h.state().dialogs.open, Some("pgSave")); + + // Reopen on the original map, then replace the target layer at the same map-local ID. + h.state_mut().run("map.activate", json!({"name": "Map"})).unwrap(); + h.state_mut().run("layer.select", json!({"layer": lower})).unwrap(); + h.state_mut().run("ui.dialog", json!({"name": "pgDiscard"})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().dialogs.list.first().map(String::as_str), Some("public.roads_lower")); + assert_eq!(h.state().dialogs.list.get(2).map(String::as_str), Some("2")); + // Remove the layer and add a new PostGIS layer reusing its ID (different instance). + let old_instance = h.state().session.map().layer(lower).unwrap().instance_id(); + let pos = h.state().session.map().layers.iter().position(|l| l.id == lower).unwrap(); + let mut replacement = h.state().session.map().layers[pos].clone(); + replacement.postgis.as_mut().unwrap().origin.table = "public.roads_other".into(); + let fresh = rustgis_engine::map::Layer::new(lower, replacement.dataset); + assert_ne!(fresh.instance_id(), old_instance); + let mut fresh = fresh; + fresh.postgis = replacement.postgis; + h.state_mut().session.map_mut().layers[pos] = fresh; + h.state_mut().session.revision += 1; + h.run_steps(3); + assert!(h.state().dialogs.list.is_empty()); + assert!(h.state().dialogs.error.as_deref().is_some_and(|e| e.contains("no longer available")), "{:?}", h.state().dialogs.error); + h.get_by_role_and_label(Role::Button, "Discard").click(); + h.run_steps(3); + assert_eq!(h.state().dialogs.open, Some("pgDiscard")); + } + + /// Closing Add From Database clears any typed password (`b`), and closing Add Delimited Text + /// drops the held file (`csv`). + #[test] + fn closing_database_and_csv_dialogs_clears_transient_state() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "addDatabase"})).unwrap(); + app.dialogs.b = "ephemeral-secret".into(); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + assert_eq!(h.state().dialogs.open, None); + assert!(h.state().dialogs.b.is_empty(), "closing addDatabase must clear the password buffer"); + + let mut app = RustGisApp::with_sample(); + open_csv(&mut app, "points.csv", CsvSource::Bytes(b"lon,lat\n10,50\n".to_vec())).unwrap(); + assert!(app.dialogs.csv.is_some()); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + assert_eq!(h.state().dialogs.open, None); + assert!(h.state().dialogs.csv.is_none(), "closing addCsv must release the buffered file"); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dd31c685bb..a9007803eb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3265,27 +3265,48 @@ 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_after_project_replace(); + 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); + 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; + } + // A project replacing this one hasn't been saved in the browser yet (opening a file + // names it again). 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. + // 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(); + // 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, - ); + 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.ws.task_edit = None; + table::prune_views(self); layoutview::follow_project(self); - for notice in report.notices() { - self.session.notify(notice, false); - } - Ok(()) } /// Reports pending header reads retired by either ordinary or peer project replacement. @@ -3530,29 +3551,8 @@ impl RustGisApp { 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). 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_after_project_replace(); } // Fields and layers can go while the table is closed: its column views follow them. table::prune_views(self); @@ -10134,6 +10134,76 @@ mod peer_output_tests { } } } + + /// Peer project replacement clears active map sketches, shape drags, plugin picks, pending + /// symbology, attribute-table views and in-progress task step edits just like User replacement. + #[test] + fn peer_project_replacement_clears_editing_and_transient_ui_state() { + let mut app = RustGisApp::with_sample(); + let (text, _) = Project::default().saved_text(None).unwrap(); + let shapes = app.session.map_mut().add_dataset(rustgis_engine::data::Dataset::new( + "Shapes", + rustgis_engine::data::GeometryType::Polygon, + vec![rustgis_engine::data::Field::new("kind", rustgis_engine::data::FieldType::Text)], + )); + app.session.active_layer = Some(shapes); + app.run("edit.enable", json!({"on": true})).unwrap(); + let layer_ref = app.session.map().layer(shapes).unwrap(); + let instance = layer_ref.instance_id(); + app.ui.symbology_pending = Some(PendingUniqueSymbology::new(&app.session, layer_ref, "kind".into())); + app.ui.plugin_panel.set_picking_for_tests("demo", "extent"); + app.ws.task_edit = Some((0, "Step".into(), "Instructions".into())); + app.table.seed_view_for_tests(app.session.opened, instance); + + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_max_steps(32).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + // Start a real map sketch point and a real box-edit drag. + h.state_mut().run("tool.set", json!({"tool": "measure"})).unwrap(); + h.run_steps(2); + let view = h.state().map.view_rect.unwrap().0; + let at = view.center(); + h.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + } + h.run_steps(2); + assert_eq!(h.state().map.sketch_len(), 1); + + h.state_mut().run("tool.set", json!({"tool": "rotatedBox"})).unwrap(); + // Put the sketch point back via measure? Actually test sketch and box separately via open_peer_text. + assert!(crate::boxedit::drag_start(h.state_mut(), view, at, true)); + crate::boxedit::drag_to(h.state_mut(), view, at + egui::vec2(40.0, 40.0), false); + assert!(crate::boxedit::drawing(h.state())); + // Re-set plugin pick since tool.set cleared it. + h.state_mut().ui.plugin_panel.set_picking_for_tests("demo", "extent"); + assert!(h.state().ui.plugin_panel.is_picking_for_tests()); + + h.state_mut().open_peer_text(&text).unwrap(); + assert!(!crate::boxedit::drawing(h.state()), "open_peer_text must cancel active box drag"); + assert!(!h.state().ui.plugin_panel.is_picking_for_tests(), "open_peer_text must cancel plugin panel pick"); + assert!(h.state().ui.symbology_pending.is_none(), "open_peer_text must clear stale symbology_pending"); + assert!(h.state().ws.task_edit.is_none(), "open_peer_text must clear ws.task_edit"); + assert!(!h.state().table.has_views_for_tests(), "open_peer_text must prune old table views"); + + // Also verify an active map sketch is cancelled by open_peer_text. + h.state_mut().run("tool.set", json!({"tool": "measure"})).unwrap(); + h.run_steps(2); + h.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + } + h.run_steps(2); + assert_eq!(h.state().map.sketch_len(), 1); + h.state_mut().open_peer_text(&text).unwrap(); + assert_eq!(h.state().map.sketch_len(), 0, "open_peer_text must cancel active map sketch"); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/pluginpanel.rs b/crates/ui-egui/src/pluginpanel.rs index 0d2b74a9fd..ed1176ada1 100644 --- a/crates/ui-egui/src/pluginpanel.rs +++ b/crates/ui-egui/src/pluginpanel.rs @@ -532,6 +532,17 @@ pub(crate) fn cancel_pick(app: &mut RustGisApp) { } } +#[cfg(test)] +impl State { + pub(crate) fn set_picking_for_tests(&mut self, plugin: &str, widget: &str) { + self.picking = Some((plugin.to_string(), widget.to_string())); + } + + pub(crate) fn is_picking_for_tests(&self) -> bool { + self.picking.is_some() + } +} + /// What a pick waiting for the map asks for, for the map's hint and the status bar. pub(crate) fn pick_hint(app: &mut RustGisApp) -> Option { let (pid, item) = waiting_pick(app)?; diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index d413721370..8b6f253270 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -210,6 +210,18 @@ pub(crate) fn prune_views(app: &mut RustGisApp) { } } +#[cfg(test)] +impl TableState { + pub(crate) fn seed_view_for_tests(&mut self, opened: u64, layer_instance: u64) { + self.opened = opened; + self.views.insert(ViewKey::Layer(layer_instance), ColumnView::default()); + } + + pub(crate) fn has_views_for_tests(&self) -> bool { + !self.views.is_empty() + } +} + /// Why a column can't be changed, translated: the edit commands find a field by name, ignoring /// case, and an earlier field has this one's name but for case. fn shadowed() -> &'static str { diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 0325a9162f..4d68a5c9b3 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -120,7 +120,7 @@ fn geopackage_edit_dialogs_target_numeric_ids_with_duplicate_names() { h.run_steps(2); h.get_by_label(&format!("Duplicate (#{to})")).click(); h.run_steps(2); - assert_eq!(h.state().dialogs.gpkg_layer, Some(to)); + assert_eq!(h.state().dialogs.source_layer, Some(to)); }; let shown_count = |h: &egui_kittest::Harness<'_, RustGisApp>, count: &str| { let label = h.get_by_label("Changed rows").rect(); @@ -137,7 +137,7 @@ fn geopackage_edit_dialogs_target_numeric_ids_with_duplicate_names() { h.state_mut().run("layer.select", json!({"layer": lower})).unwrap(); h.state_mut().run("ui.dialog", json!({"name": "gpkgSave"})).unwrap(); h.run_steps(3); - assert_eq!(h.state().dialogs.gpkg_layer, Some(lower), "the lower duplicate is active"); + assert_eq!(h.state().dialogs.source_layer, Some(lower), "the lower duplicate is active"); h.get_by_label(&lower_table); assert_eq!(h.state().dialogs.list[2], "2"); shown_count(&h, "2"); @@ -160,7 +160,7 @@ fn geopackage_edit_dialogs_target_numeric_ids_with_duplicate_names() { h.state_mut().run("edit.setValue", json!({"layer": lower, "row": 0, "field": "name", "value": "lower discarded"})).unwrap(); h.state_mut().run("ui.dialog", json!({"name": "gpkgDiscard"})).unwrap(); h.run_steps(3); - assert_eq!(h.state().dialogs.gpkg_layer, Some(lower)); + assert_eq!(h.state().dialogs.source_layer, Some(lower)); h.get_by_label(&lower_table); choose(&mut h, lower, upper); h.get_by_label(&upper_table); @@ -179,7 +179,7 @@ fn geopackage_edit_dialogs_target_numeric_ids_with_duplicate_names() { for (dialog, button) in [("gpkgSave", "Save"), ("gpkgDiscard", "Discard")] { for target in [None, Some(u32::MAX)] { h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap(); - h.state_mut().dialogs.gpkg_layer = target; + h.state_mut().dialogs.source_layer = target; h.run_steps(3); assert!(h.state().dialogs.list.is_empty()); h.get_by_role_and_label(egui::accesskit::Role::Button, button).click(); @@ -193,7 +193,7 @@ fn geopackage_edit_dialogs_target_numeric_ids_with_duplicate_names() { } h.state_mut().run("layer.select", json!({"layer": "Countries"})).unwrap(); h.state_mut().run("ui.dialog", json!({"name": "gpkgSave"})).unwrap(); - assert_eq!(h.state().dialogs.gpkg_layer, Some(upper), "a non-editable active layer falls back to the first editable ID"); + assert_eq!(h.state().dialogs.source_layer, Some(upper), "a non-editable active layer falls back to the first editable ID"); } #[cfg(not(target_arch = "wasm32"))] @@ -231,7 +231,7 @@ fn geopackage_edit_dialogs_refuse_reused_layer_ids() { h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap(); h.run_steps(3); assert_eq!(h.state().dialogs.list[4], a.to_string_lossy()); - assert_eq!(h.state().dialogs.gpkg_instance, Some(instance)); + assert_eq!(h.state().dialogs.source_instance, Some(instance)); h.state_mut().run("edit.undo", json!({})).unwrap(); assert!(h.state().session.map().layer(id).is_none()); @@ -253,7 +253,7 @@ fn geopackage_edit_dialogs_refuse_reused_layer_ids() { h.run_steps(3); assert_eq!(h.state().dialogs.open, Some(dialog)); assert!(h.state().dialogs.error.is_some()); - assert_eq!(h.state().dialogs.gpkg_instance, Some(instance), "rendering must never adopt the replacement"); + assert_eq!(h.state().dialogs.source_instance, Some(instance), "rendering must never adopt the replacement"); assert!(h.state().dialogs.list.is_empty()); assert_eq!( h.state().session.map().layer(id).unwrap().dataset.features[0].attrs[0], @@ -271,7 +271,7 @@ fn geopackage_edit_dialogs_refuse_reused_layer_ids() { } h.state_mut().run("ui.dialog", json!({"name": dialog})).unwrap(); h.run_steps(3); - assert_eq!(h.state().dialogs.gpkg_instance, Some(other_instance)); + assert_eq!(h.state().dialogs.source_instance, Some(other_instance)); assert_eq!(h.state().dialogs.list[4], replacement.to_string_lossy()); assert_eq!(h.state().dialogs.list[2], "1"); assert!(h.state().dialogs.error.is_none()); From eb5042d959555718facba97c1bd69ec925295786 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:40:14 -0500 Subject: [PATCH 2/5] Address review feedback --- apps/rustgis-web/src/picker.rs | 71 ++------------ crates/plugins/src/tools.rs | 100 +++++++++++++++----- crates/ui-egui/src/lib.rs | 143 +++++++++++++++++++---------- crates/ui-egui/src/modelbuilder.rs | 5 +- 4 files changed, 183 insertions(+), 136 deletions(-) diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs index 39611ec639..226253022e 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -1,33 +1,7 @@ -//! Browser file-picker extension filters, kept in parity with the extensions `ui-egui` accepts. +//! Browser file-picker extension filters, shared with `ui-egui` so desktop and browser filters +//! cannot drift. -/// Extensions offered when opening a project (`purpose == "project"`). -pub(crate) const PROJECT_EXTS: &[&str] = &["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"]; - -/// Extensions offered when opening a project item (`purpose == "item"`). -pub(crate) const ITEM_EXTS: &[&str] = &[ - "rgismap", - "rgismpk", - "rgispkg", - "rgislyr", - "rgisstyle", - "rgisramp", - "rgistemplate", - "rgistask", - "rgisbookmarks", - "rgis", - "rgisx", - "qml", - "rgisreport", - "rgisrpttemplate", - "rgispres", - "rgisnb", - "ipynb", - "rgisdlpk", - "rgisfield", - "json", - "rgistool", - "rgislayout", -]; +pub(crate) use rustgis_ui_egui::{ITEM_EXTS, PROJECT_EXTS}; /// Returns the static extension filter list for a named picker `purpose`, when it uses one. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -43,41 +17,10 @@ pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str] mod tests { use super::*; - /// Every project and item extension that `ui-egui` opens via `open_async("project")` or - /// `open_async("item")` must be selectable in the browser file picker. + /// The browser picker re-exports `ui-egui`'s canonical project and item extension slices. #[test] - fn browser_picker_extensions_cover_all_project_and_item_formats() { - let project = filter_extensions("project").unwrap(); - for ext in ["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"] { - assert!(project.contains(&ext), "project picker is missing .{ext}"); - } - - let item = filter_extensions("item").unwrap(); - for ext in [ - "rgismap", - "rgismpk", - "rgispkg", - "rgislyr", - "rgisstyle", - "rgisramp", - "rgistemplate", - "rgistask", - "rgisbookmarks", - "rgis", - "rgisx", - "qml", - "rgisreport", - "rgisrpttemplate", - "rgispres", - "rgisnb", - "ipynb", - "rgisdlpk", - "rgisfield", - "json", - "rgistool", - "rgislayout", - ] { - assert!(item.contains(&ext), "item picker is missing .{ext}"); - } + fn browser_picker_extensions_match_ui_egui_lists() { + assert_eq!(filter_extensions("project"), Some(rustgis_ui_egui::PROJECT_EXTS)); + assert_eq!(filter_extensions("item"), Some(rustgis_ui_egui::ITEM_EXTS)); } } diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index f15956744a..085bfcd7a1 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -424,12 +424,18 @@ fn output(reply: &Value, tool: &str) -> Result { return Ok(ToolResult { losses: Vec::new(), output: Output::Selection { layer, rows }, messages }); } let mut outs = Vec::new(); - let mut losses = Vec::new(); + let mut grouped_losses: Vec<(rustgis_data::loss::LossCode, Vec<(String, String)>)> = Vec::new(); let mut push_report = |name: &str, report: rustgis_data::ReadReport| { - for note in report.messages.prefixed(name) { + for note in report.messages { match note.loss { - Some(code) => losses.push(rustgis_data::loss::LossMessage { code, text: note.text }), - None => messages.push(note.text), + Some(code) => { + if let Some((_, entries)) = grouped_losses.iter_mut().find(|(c, _)| *c == code) { + entries.push((name.to_string(), note.text)); + } else { + grouped_losses.push((code, vec![(name.to_string(), note.text)])); + } + } + None => messages.push(note.prefixed(name).text), } } }; @@ -443,6 +449,34 @@ fn output(reply: &Value, tool: &str) -> Result { push_report(&ds.name, report); outs.push(OutputLayer::Table(ds)); } + let losses = grouped_losses + .into_iter() + .map(|(code, entries)| { + const SHOWN: usize = 3; + let text = if let [(name, detail)] = entries.as_slice() { + format!("{name}: {detail}") + } else { + let mut names: Vec<&str> = Vec::new(); + for (name, _) in &entries { + if !names.contains(&name.as_str()) { + names.push(name.as_str()); + } + } + let detail = entries.first().map_or("", |(_, d)| d.as_str()); + if let [only] = names.as_slice() { + format!("{only}: {} notices: {detail}", entries.len()) + } else { + let listed = if names.len() <= SHOWN { + names.join(", ") + } else { + format!("{}, and {} more", names[..SHOWN].join(", "), names.len() - SHOWN) + }; + format!("{tool}: {} outputs ({listed}): {detail}", names.len()) + } + }; + rustgis_data::loss::LossMessage { code, text } + }) + .collect(); Ok(ToolResult { losses, output: Output::Layers(outs), messages }) } @@ -484,7 +518,8 @@ mod tests { } /// GeoJSON loss notices from plugin tool outputs (layers and tables) reach `ToolResult.losses` - /// (and unclassified notices reach `ToolResult.messages`), while clean outputs emit none. + /// grouped as one notice per `LossCode` across all outputs (with count and layer names), while + /// clean outputs emit none. #[test] fn plugin_tool_output_propagates_geojson_loss_notices_and_stays_clean_when_lossless() { let clean = json!({ @@ -507,15 +542,40 @@ mod tests { assert!(res.losses.is_empty(), "clean output must have no losses: {:?}", res.losses); assert!(res.messages.is_empty(), "clean output must have no messages: {:?}", res.messages); - let lossy = json!({ + // Single lossy output keeps its direct layer-prefixed message. + let single = json!({ "layers": [{ - "name": "Peaks", + "name": "Solo", "geojson": { "type": "FeatureCollection", - "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:CUSTOM::999"}}, - "features": [{"type": "Feature", "properties": {"name": "A"}, "geometry": {"type": "Point", "coordinates": [10.0, 50.0, 1200.0]}}] + "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10.0, 50.0, 100.0]}}] } - }], + }] + }); + let res = output(&single, "demo").unwrap(); + assert_eq!(res.losses.len(), 1, "{:?}", res.losses); + assert_eq!(res.losses[0].code, rustgis_data::loss::LossCode::DroppedZm); + assert!(res.losses[0].text.starts_with("Solo: "), "{:?}", res.losses[0].text); + assert!(res.messages.is_empty(), "classified losses belong in losses only: {:?}", res.messages); + + // Multiple outputs sharing a loss kind emit one grouped notice per LossCode with count and names. + let point_3d = |name: &str, crs: Option<&str>| { + let mut fc = json!({ + "type": "FeatureCollection", + "features": [{"type": "Feature", "properties": {"name": name}, "geometry": {"type": "Point", "coordinates": [10.0, 50.0, 1200.0]}}] + }); + if let Some(crs) = crs { + fc["crs"] = json!({"type": "name", "properties": {"name": crs}}); + } + json!({"name": name, "geojson": fc}) + }; + let lossy = json!({ + "layers": [ + point_3d("Peaks", Some("urn:ogc:def:crs:CUSTOM::999")), + point_3d("Ridges", None), + point_3d("Valleys", None), + point_3d("Passes", None), + ], "tables": [{ "name": "Summary", "geojson": { @@ -526,20 +586,18 @@ mod tests { }] }); let res = output(&lossy, "demo").unwrap(); + assert_eq!(res.losses.len(), 2, "must emit exactly one LossMessage per LossCode: {:?}", res.losses); + let zm = res.losses.iter().find(|l| l.code == rustgis_data::loss::LossCode::DroppedZm).expect("DroppedZm loss"); assert!( - res.losses.iter().any(|l| l.code == rustgis_data::loss::LossCode::DroppedZm && l.text.starts_with("Peaks: ")), - "expected DroppedZm loss for Peaks: {:?}", - res.losses - ); - assert!( - res.losses.iter().any(|l| l.code == rustgis_data::loss::LossCode::AssumedCrs && l.text.starts_with("Peaks: ")), - "expected AssumedCrs loss for Peaks: {:?}", - res.losses + zm.text.contains("4 outputs (Peaks, Ridges, Valleys, and 1 more)"), + "expected grouped count and layer names for DroppedZm, got: {}", + zm.text ); + let crs = res.losses.iter().find(|l| l.code == rustgis_data::loss::LossCode::AssumedCrs).expect("AssumedCrs loss"); assert!( - res.losses.iter().any(|l| l.code == rustgis_data::loss::LossCode::AssumedCrs && l.text.starts_with("Summary: ")), - "expected AssumedCrs loss for Summary: {:?}", - res.losses + crs.text.contains("2 outputs (Peaks, Summary)"), + "expected grouped count and output names for AssumedCrs, got: {}", + crs.text ); assert!(res.messages.is_empty(), "classified losses belong in losses only: {:?}", res.messages); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a9007803eb..6cc105394d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -233,6 +233,58 @@ pub const MARKER_FILE_MAX_BYTES: usize = rustgis_engine::map::symbology::MAX_PIC /// lists every file). pub const MARKER_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "svg"]; +/// Extensions offered when opening a project, shared between desktop (`ui.open`) and browser +/// (`purpose == "project"`). +pub const PROJECT_EXTS: &[&str] = &["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"]; + +/// Extensions offered when opening a project item in the browser (`purpose == "item"`), kept in +/// sync with [`OPEN_ITEMS`], `ui.reportLayoutFile`, and ModelBuilder's import picker. +pub const ITEM_EXTS: &[&str] = &[ + "rgismap", + "rgismpk", + "rgispkg", + "rgislyr", + "rgisstyle", + "rgisramp", + "rgistemplate", + "rgistask", + "rgisbookmarks", + "rgis", + "rgisx", + "qml", + "rgisreport", + "rgisrpttemplate", + "rgispres", + "rgisnb", + "ipynb", + "rgisdlpk", + "rgisfield", + "json", + "rgistool", + "rgislayout", +]; + +/// Every `ui.openItem` kind: `(kind, command, desktop extensions, filter label, web picker purpose)`. +const OPEN_ITEMS: &[(&str, &str, &[&str], &str, &str)] = &[ + ("map", "map.import", &["rgismap", "rgismpk", "rgis", "rgisx", "rgispkg"], "RustGIS maps and projects", "item"), + ("layer", "layer.addLayerFile", &["rgislyr"], "RustGIS layer file", "item"), + ("styles", "style.add", &["rgisstyle"], "RustGIS styles", "item"), + ("ramps", "ramp.add", &["rgisramp", "xml", "qml", "txt", "clr", "cpt"], "Colour ramps (RustGIS, QGIS, GDAL, GMT)", "ramp"), + ("importStyles", "style.import", &["rgislyr", "rgismap", "rgis", "rgisx"], "RustGIS layers, maps and projects", "item"), + ("geolibreProject", "project.importGeolibre", &["geolibre", "json"], "GeoLibre project", "project"), + ("qgisProject", "project.importQgis", &["qgs", "qgz"], "QGIS project", "qgisProject"), + ("qgisStyle", "style.importQgis", &["qml"], "QGIS layer style", "item"), + ("template", "project.fromTemplate", &["rgistemplate"], "RustGIS project template", "item"), + ("task", "task.import", &["rgistask"], "RustGIS task", "item"), + ("bookmarks", "bookmark.import", &["rgisbookmarks"], "RustGIS bookmarks", "item"), + ("report", "report.open", &["rgisreport", "rgisrpttemplate"], "RustGIS report or report template", "item"), + ("presentation", "presentation.import", &["rgispres"], "RustGIS presentation", "item"), + ("notebook", "notebook.open", &["rgisnb", "ipynb"], "RustGIS or Jupyter notebook", "item"), + ("dlPackage", "dl.import", &["rgisdlpk"], "RustGIS deep learning package", "item"), + // A field package sent back from a phone: its edits, to the area it came from. + ("fieldPackage", "offline.bringBack", &["rgisfield"], "RustGIS field package", "item"), +]; + /// The largest script file the Script pane's Load… reads, as the assistant's command file; the /// browser's shell refuses a larger one before reading it. pub const SCRIPT_FILE_MAX_BYTES: usize = 1024 * 1024; @@ -3265,7 +3317,16 @@ 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); + 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; + } self.reset_after_project_replace(); + table::prune_views(self); + layoutview::follow_project(self); for notice in report.notices() { self.session.notify(notice, false); } @@ -3277,13 +3338,6 @@ impl RustGisApp { fn reset_after_project_replace(&mut self) { 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; - } // A project replacing this one hasn't been saved in the browser yet (opening a file // names it again). self.ui.web_file = None; @@ -3305,8 +3359,6 @@ impl RustGisApp { // command waiting for it went with the old project's waits. self.retire_cog_probes(); self.ws.task_edit = None; - table::prune_views(self); - layoutview::follow_project(self); } /// Reports pending header reads retired by either ordinary or peer project replacement. @@ -4905,10 +4957,7 @@ impl RustGisApp { } open("project"); self.ui.backstage = false; - } else if let Some(path) = dialogs::pick_open( - &["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"], - tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)"), - ) { + } else if let Some(path) = dialogs::pick_open(PROJECT_EXTS, tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)")) { // A QGIS project opens as a new map of this one. let lower = path.to_ascii_lowercase(); let cmd = if lower.ends_with(".qgs") || lower.ends_with(".qgz") { @@ -5145,37 +5194,17 @@ impl RustGisApp { } "ui.openItem" => { let kind = p.get("kind").and_then(Value::as_str).ok_or("kind is required")?; - let (cmd, exts, label): (&str, &[&str], &str) = match kind { - "map" => ("map.import", &["rgismap", "rgismpk", "rgis", "rgisx", "rgispkg"], "RustGIS maps and projects"), - "layer" => ("layer.addLayerFile", &["rgislyr"], "RustGIS layer file"), - "styles" => ("style.add", &["rgisstyle"], "RustGIS styles"), - "ramps" => ("ramp.add", &["rgisramp", "xml", "qml", "txt", "clr", "cpt"], "Colour ramps (RustGIS, QGIS, GDAL, GMT)"), - "importStyles" => ("style.import", &["rgislyr", "rgismap", "rgis", "rgisx"], "RustGIS layers, maps and projects"), - "geolibreProject" => ("project.importGeolibre", &["geolibre", "json"], "GeoLibre project"), - "qgisProject" => ("project.importQgis", &["qgs", "qgz"], "QGIS project"), - "qgisStyle" => ("style.importQgis", &["qml"], "QGIS layer style"), - "template" => ("project.fromTemplate", &["rgistemplate"], "RustGIS project template"), - "task" => ("task.import", &["rgistask"], "RustGIS task"), - "bookmarks" => ("bookmark.import", &["rgisbookmarks"], "RustGIS bookmarks"), - "report" => ("report.open", &["rgisreport", "rgisrpttemplate"], "RustGIS report or report template"), - "presentation" => ("presentation.import", &["rgispres"], "RustGIS presentation"), - "notebook" => ("notebook.open", &["rgisnb", "ipynb"], "RustGIS or Jupyter notebook"), - "dlPackage" => ("dl.import", &["rgisdlpk"], "RustGIS deep learning package"), - // A field package sent back from a phone: its edits, to the area it came from. - "fieldPackage" => ("offline.bringBack", &["rgisfield"], "RustGIS field package"), - k => return Err(format!("unknown item '{k}'")), - }; + let (cmd, exts, label, purpose) = OPEN_ITEMS + .iter() + .find(|(k, ..)| *k == kind) + .map(|&(_, cmd, exts, label, purpose)| (cmd, exts, label, purpose)) + .ok_or_else(|| format!("unknown item '{kind}'"))?; if let Some(open) = &self.services.open_async { self.ui.pending_open = Some(cmd); if let Some(snapshot) = &self.services.open_options { snapshot(&self.ui); } - open(match kind { - "ramps" => "ramp", - "geolibreProject" => "project", - "qgisProject" => "qgisProject", - _ => "item", - }); + open(purpose); } else if let Some(path) = dialogs::pick_open(exts, tl!(label)) { let r = self.run_by_user(cmd, json!({"path": path})); self.map.invalidate(); @@ -10164,20 +10193,10 @@ mod peer_output_tests { app, ); h.run_steps(3); - // Start a real map sketch point and a real box-edit drag. - h.state_mut().run("tool.set", json!({"tool": "measure"})).unwrap(); - h.run_steps(2); let view = h.state().map.view_rect.unwrap().0; let at = view.center(); - h.event(egui::Event::PointerMoved(at)); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - } - h.run_steps(2); - assert_eq!(h.state().map.sketch_len(), 1); - + // Start an active rotated-box drag and a pending plugin pick, then verify peer replacement clears them. h.state_mut().run("tool.set", json!({"tool": "rotatedBox"})).unwrap(); - // Put the sketch point back via measure? Actually test sketch and box separately via open_peer_text. assert!(crate::boxedit::drag_start(h.state_mut(), view, at, true)); crate::boxedit::drag_to(h.state_mut(), view, at + egui::vec2(40.0, 40.0), false); assert!(crate::boxedit::drawing(h.state())); @@ -10204,6 +10223,30 @@ mod peer_output_tests { h.state_mut().open_peer_text(&text).unwrap(); assert_eq!(h.state().map.sketch_len(), 0, "open_peer_text must cancel active map sketch"); } + + /// Every extension handled by `ui.openItem` (plus layout templates and models opened via + /// `"item"`) must stay covered by `PROJECT_EXTS` and `ITEM_EXTS`. + #[test] + fn shared_picker_extension_lists_cover_all_open_item_specs() { + for &(kind, _, exts, _, purpose) in OPEN_ITEMS { + match purpose { + "project" => { + for ext in exts { + assert!(PROJECT_EXTS.contains(ext), "PROJECT_EXTS is missing .{ext} for {kind}"); + } + } + "item" => { + for ext in exts { + assert!(ITEM_EXTS.contains(ext), "ITEM_EXTS is missing .{ext} for {kind}"); + } + } + _ => {} + } + } + for ext in std::iter::once(&"rgislayout").chain(modelbuilder::MODEL_EXTS.iter()) { + assert!(ITEM_EXTS.contains(ext), "ITEM_EXTS is missing .{ext}"); + } + } } #[cfg(test)] diff --git a/crates/ui-egui/src/modelbuilder.rs b/crates/ui-egui/src/modelbuilder.rs index a39d5a0b53..388afe7e6f 100644 --- a/crates/ui-egui/src/modelbuilder.rs +++ b/crates/ui-egui/src/modelbuilder.rs @@ -533,12 +533,15 @@ fn export(app: &mut RustGisApp) { } } +/// Extensions accepted when importing a model file on desktop and in the browser. +pub(crate) const MODEL_EXTS: &[&str] = &["json", "rgistool"]; + /// Imports a model file (`*.model.json`, or a web tool) and opens it. pub(crate) fn import(app: &mut RustGisApp) { if let Some(open) = &app.services.open_async { app.ui.pending_open = Some("model.import"); open("item"); - } else if let Some(path) = crate::dialogs::pick_open(&["json", "rgistool"], tl!("RustGIS model")) { + } else if let Some(path) = crate::dialogs::pick_open(MODEL_EXTS, tl!("RustGIS model")) { match app.run("model.import", json!({"path": path})) { Ok(v) => imported(app, &v), Err(e) => app.mb.log(e, LogKind::Error), From 6ec8e4880f339f045217eba2a95e94b2132a1bac Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 11:21:31 -0500 Subject: [PATCH 3/5] Address Claude review feedback --- apps/rustgis-web/src/picker.rs | 4 +- apps/rustgis-web/src/web.rs | 12 +-- crates/plugins/src/tools.rs | 134 ++++++++++++++++++++++++--------- crates/ui-egui/src/lib.rs | 19 +++++ 4 files changed, 128 insertions(+), 41 deletions(-) diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs index 226253022e..c901e78717 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -1,10 +1,9 @@ //! Browser file-picker extension filters, shared with `ui-egui` so desktop and browser filters //! cannot drift. -pub(crate) use rustgis_ui_egui::{ITEM_EXTS, PROJECT_EXTS}; +use rustgis_ui_egui::{ITEM_EXTS, PROJECT_EXTS}; /// Returns the static extension filter list for a named picker `purpose`, when it uses one. -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str]> { match purpose { "project" => Some(PROJECT_EXTS), @@ -22,5 +21,6 @@ mod tests { fn browser_picker_extensions_match_ui_egui_lists() { assert_eq!(filter_extensions("project"), Some(rustgis_ui_egui::PROJECT_EXTS)); assert_eq!(filter_extensions("item"), Some(rustgis_ui_egui::ITEM_EXTS)); + assert_eq!(filter_extensions("unknown"), None); } } diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 93f747937f..5857acb523 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1365,13 +1365,15 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("Script"), &["txt"]) } else if purpose == "shapefile" { rfd::AsyncFileDialog::new().add_filter("Shapefile", &["shp", "dbf", "shx", "prj", "cpg", "zip"]) - } else if purpose == "project" { - rfd::AsyncFileDialog::new() - .add_filter(rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)"), crate::picker::PROJECT_EXTS) + } else if let Some(exts) = crate::picker::filter_extensions(purpose) { + let label = if purpose == "project" { + rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)") + } else { + "RustGIS items" + }; + rfd::AsyncFileDialog::new().add_filter(label, exts) } else if purpose == "qgisProject" { rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("QGIS project"), &["qgs", "qgz"]) - } else if purpose == "item" { - rfd::AsyncFileDialog::new().add_filter("RustGIS items", crate::picker::ITEM_EXTS) } else if purpose == "ramp" { rfd::AsyncFileDialog::new().add_filter("Colour ramps", &["rgisramp", "xml", "qml", "txt", "clr", "cpt"]) } else if purpose == "layout" { diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index 085bfcd7a1..d17c4753ab 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -406,6 +406,43 @@ fn dataset(v: &Value, fallback: &str) -> Result<(rustgis_data::Dataset, rustgis_ rustgis_data::io::read_geojson(&gj.to_string(), name).map_err(|e| format!("{name}: {e}")) } +/// Formats a group of notices collected across one or more outputs (identified by output index) +/// into a single notice with output count, names, and distinct details. +fn format_grouped_notice(tool: &str, entries: &[(usize, String, String)]) -> String { + const SHOWN: usize = 3; + if let [(_, name, detail)] = entries { + return format!("{name}: {detail}"); + } + let mut outputs: Vec<(usize, &str)> = Vec::new(); + for (idx, name, _) in entries { + if !outputs.iter().any(|(seen, _)| seen == idx) { + outputs.push((*idx, name.as_str())); + } + } + let mut details: Vec<&str> = Vec::new(); + for (_, _, d) in entries { + if !details.contains(&d.as_str()) { + details.push(d.as_str()); + } + } + let detail_text = if details.len() <= SHOWN { + details.join("; ") + } else { + format!("{}; and {} more", details[..SHOWN].join("; "), details.len() - SHOWN) + }; + if let [(_, only)] = outputs.as_slice() { + format!("{only}: {} notices: {detail_text}", entries.len()) + } else { + let listed = if outputs.len() <= SHOWN { + outputs.iter().map(|(_, n)| *n).collect::>().join(", ") + } else { + let first = outputs[..SHOWN].iter().map(|(_, n)| *n).collect::>().join(", "); + format!("{first}, and {} more", outputs.len() - SHOWN) + }; + format!("{tool}: {} outputs ({listed}): {detail_text}", outputs.len()) + } +} + /// Turns a tool's reply into a result: new `layers` and `tables`, or a `selection` /// (`{"layer": name, "rows": [...]}`), with `messages`. fn output(reply: &Value, tool: &str) -> Result { @@ -424,59 +461,49 @@ fn output(reply: &Value, tool: &str) -> Result { return Ok(ToolResult { losses: Vec::new(), output: Output::Selection { layer, rows }, messages }); } let mut outs = Vec::new(); - let mut grouped_losses: Vec<(rustgis_data::loss::LossCode, Vec<(String, String)>)> = Vec::new(); - let mut push_report = |name: &str, report: rustgis_data::ReadReport| { + let mut grouped_losses: Vec<(rustgis_data::loss::LossCode, Vec<(usize, String, String)>)> = Vec::new(); + let mut grouped_plain: Vec<(String, Vec<(usize, String, String)>)> = Vec::new(); + let mut output_idx = 0usize; + let mut push_report = |idx: usize, name: &str, report: rustgis_data::ReadReport| { for note in report.messages { match note.loss { Some(code) => { if let Some((_, entries)) = grouped_losses.iter_mut().find(|(c, _)| *c == code) { - entries.push((name.to_string(), note.text)); + entries.push((idx, name.to_string(), note.text)); + } else { + grouped_losses.push((code, vec![(idx, name.to_string(), note.text)])); + } + } + None => { + if let Some((_, entries)) = grouped_plain.iter_mut().find(|(t, _)| *t == note.text) { + entries.push((idx, name.to_string(), note.text)); } else { - grouped_losses.push((code, vec![(name.to_string(), note.text)])); + let key = note.text.clone(); + grouped_plain.push((key, vec![(idx, name.to_string(), note.text)])); } } - None => messages.push(note.prefixed(name).text), } } }; for v in reply.get("layers").and_then(Value::as_array).into_iter().flatten().take(64) { let (ds, report) = dataset(v, tool)?; - push_report(&ds.name, report); + push_report(output_idx, &ds.name, report); + output_idx += 1; outs.push(OutputLayer::Vector(ds)); } for v in reply.get("tables").and_then(Value::as_array).into_iter().flatten().take(64) { let (ds, report) = dataset(v, tool)?; - push_report(&ds.name, report); + push_report(output_idx, &ds.name, report); + output_idx += 1; outs.push(OutputLayer::Table(ds)); } let losses = grouped_losses .into_iter() - .map(|(code, entries)| { - const SHOWN: usize = 3; - let text = if let [(name, detail)] = entries.as_slice() { - format!("{name}: {detail}") - } else { - let mut names: Vec<&str> = Vec::new(); - for (name, _) in &entries { - if !names.contains(&name.as_str()) { - names.push(name.as_str()); - } - } - let detail = entries.first().map_or("", |(_, d)| d.as_str()); - if let [only] = names.as_slice() { - format!("{only}: {} notices: {detail}", entries.len()) - } else { - let listed = if names.len() <= SHOWN { - names.join(", ") - } else { - format!("{}, and {} more", names[..SHOWN].join(", "), names.len() - SHOWN) - }; - format!("{tool}: {} outputs ({listed}): {detail}", names.len()) - } - }; - rustgis_data::loss::LossMessage { code, text } - }) + .map(|(code, entries)| rustgis_data::loss::LossMessage { code, text: format_grouped_notice(tool, &entries) }) .collect(); + for (_, entries) in grouped_plain { + messages.push(format_grouped_notice(tool, &entries)); + } Ok(ToolResult { losses, output: Output::Layers(outs), messages }) } @@ -595,10 +622,49 @@ mod tests { ); let crs = res.losses.iter().find(|l| l.code == rustgis_data::loss::LossCode::AssumedCrs).expect("AssumedCrs loss"); assert!( - crs.text.contains("2 outputs (Peaks, Summary)"), - "expected grouped count and output names for AssumedCrs, got: {}", + crs.text.contains("2 outputs (Peaks, Summary)") && crs.text.contains("CUSTOM::999") && crs.text.contains("CUSTOM::888"), + "expected grouped count, output names, and both distinct CRS details for AssumedCrs, got: {}", crs.text ); assert!(res.messages.is_empty(), "classified losses belong in losses only: {:?}", res.messages); + + // Unnamed outputs share the fallback tool name, but each output is still counted accurately. + let unnamed = json!({ + "layers": [ + {"geojson": {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10.0, 50.0, 1.0]}}]}}, + {"geojson": {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [11.0, 51.0, 2.0]}}]}}, + point_3d("Peaks", None), + ] + }); + let res = output(&unnamed, "demo").unwrap(); + assert_eq!(res.losses.len(), 1, "{:?}", res.losses); + assert!( + res.losses[0].text.contains("3 outputs (demo, demo, Peaks)"), + "two unnamed outputs plus Peaks must count as 3 outputs, got: {}", + res.losses[0].text + ); + + // Plain (unclassified) GeoJSON notes (e.g. IAU planetocentric CRS) are grouped across outputs too. + let mars_layer = |name: &str| { + json!({ + "name": name, + "geojson": { + "type": "FeatureCollection", + "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:IAU_2015::49900"}}, + "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10.0, 20.0]}}] + } + }) + }; + let plain = json!({ + "layers": [mars_layer("MarsA"), mars_layer("MarsB"), mars_layer("MarsC")] + }); + let res = output(&plain, "demo").unwrap(); + assert!(res.losses.is_empty(), "IAU planetocentric note is plain, not a loss: {:?}", res.losses); + assert_eq!(res.messages.len(), 1, "identical plain notes across outputs must group into 1 message: {:?}", res.messages); + assert!( + res.messages[0].contains("3 outputs (MarsA, MarsB, MarsC)") && res.messages[0].contains("IAU_2015::49900"), + "expected grouped plain note with count and output names, got: {}", + res.messages[0] + ); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6cc105394d..192ffb4ba2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2632,6 +2632,8 @@ impl RustGisApp { let item = [ (".geolibre", "project.importGeolibre"), (".geolibre.json", "project.importGeolibre"), + (".qgs", "project.importQgis"), + (".qgz", "project.importQgis"), (".rgismap", "map.import"), (".rgismpk", "map.import"), (".rgislyr", "layer.addLayerFile"), @@ -10247,6 +10249,23 @@ mod peer_output_tests { assert!(ITEM_EXTS.contains(ext), "ITEM_EXTS is missing .{ext}"); } } + + /// Opening a `.qgs` or `.qgz` file from bytes without a pending picker command (as browser + /// Open Project and drag-and-drop do) routes directly to `project.importQgis`. + #[test] + fn open_bytes_routes_qgis_projects_to_import_qgis() { + let qgs = r#"Browser QGIS"#; + let qgz = rustgis_engine::data::zip::write(&[("demo.qgs".into(), qgs.as_bytes().to_vec())]).unwrap(); + + for (file_name, bytes) in [("demo.qgs", qgs.as_bytes()), ("demo.qgz", qgz.as_slice())] { + let mut app = RustGisApp::new(Session::new(Project::default())); + let maps_before = app.session.project.maps.len(); + assert!(app.ui.pending_open.is_none()); + app.open_bytes_with(file_name, bytes, None).unwrap_or_else(|e| panic!("{file_name}: {e}")); + assert_eq!(app.session.project.maps.len(), maps_before + 1, "{file_name} must import a new map"); + assert_eq!(app.session.map().name, "Browser QGIS", "{file_name}"); + } + } } #[cfg(test)] From d8188c56100ecb69334c733d2eb48844a17780ba Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 18:09:00 -0500 Subject: [PATCH 4/5] Refuse QGIS projects in embedded sessions; fix GeoLibre picker and lang An embedded session takes only peer project JSON, so `.qgs` and `.qgz` picks, drops and downloads are refused like GeoLibre projects and packages. The browser GeoLibre import gets its own picker purpose that offers only GeoLibre files, as the desktop does. A widget's explicit `lang` now replaces one already in the app address. --- apps/rustgis-python/python/rustgis/_embed.py | 6 +++++- apps/rustgis-python/tests/test_widget.py | 4 ++++ apps/rustgis-web/src/picker.rs | 6 ++++++ apps/rustgis-web/src/web.rs | 2 ++ crates/ui-egui/src/lib.rs | 22 ++++++++++++++++++-- 5 files changed, 37 insertions(+), 3 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index f90526d118..bfbd782e85 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -292,8 +292,12 @@ def _app_src(url: Optional[str], lang: Optional[str]) -> str: """ base = url or os.environ.get("RUSTGIS_WEB_URL") or DEFAULT_URL parts = urlsplit(base) + kept = [q for q in parts.query.split("&") if q] + if lang: + # The app reads the first `lang`: an explicit one replaces any the address holds. + kept = [q for q in kept if q.split("=", 1)[0] != "lang"] extra = "embed" + (f"&lang={quote(lang)}" if lang else "") - query = f"{parts.query}&{extra}" if parts.query else extra + query = "&".join(kept + [extra]) return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment)) diff --git a/apps/rustgis-python/tests/test_widget.py b/apps/rustgis-python/tests/test_widget.py index 7161bc9c08..f708cc3685 100644 --- a/apps/rustgis-python/tests/test_widget.py +++ b/apps/rustgis-python/tests/test_widget.py @@ -236,3 +236,7 @@ def test_app_src_preserves_fragments_and_existing_query(): assert _app_src("https://web.rustgis.app/?webgl#view", "de") == "https://web.rustgis.app/?webgl&embed&lang=de#view" assert _app_src("https://web.rustgis.app/?webgl&theme=dark", None) == "https://web.rustgis.app/?webgl&theme=dark&embed" assert _app_src("https://web.rustgis.app/?#frag", None) == "https://web.rustgis.app/?embed#frag" + # An explicit language replaces one already in the address; without one, the address's stays. + assert _app_src("https://web.rustgis.app/?lang=fr#view", "de") == "https://web.rustgis.app/?embed&lang=de#view" + assert _app_src("https://web.rustgis.app/?webgl&lang=fr&lang=es", "de") == "https://web.rustgis.app/?webgl&embed&lang=de" + assert _app_src("https://web.rustgis.app/?lang=fr#view", None) == "https://web.rustgis.app/?lang=fr&embed#view" diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs index c901e78717..6af08b042e 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -3,11 +3,16 @@ use rustgis_ui_egui::{ITEM_EXTS, PROJECT_EXTS}; +/// What the GeoLibre project import offers, as the desktop's `ui.openItem` kind does. +const GEOLIBRE_EXTS: &[&str] = &["geolibre", "json"]; + /// Returns the static extension filter list for a named picker `purpose`, when it uses one. pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str]> { match purpose { "project" => Some(PROJECT_EXTS), "item" => Some(ITEM_EXTS), + // The GeoLibre import offers what the desktop does: GeoLibre projects only. + "geolibre" => Some(GEOLIBRE_EXTS), _ => None, } } @@ -21,6 +26,7 @@ mod tests { fn browser_picker_extensions_match_ui_egui_lists() { assert_eq!(filter_extensions("project"), Some(rustgis_ui_egui::PROJECT_EXTS)); assert_eq!(filter_extensions("item"), Some(rustgis_ui_egui::ITEM_EXTS)); + assert_eq!(filter_extensions("geolibre"), Some(&["geolibre", "json"][..])); assert_eq!(filter_extensions("unknown"), None); } } diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index d9fb47b091..23d3cd8bba 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1382,6 +1382,8 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e } else if let Some(exts) = crate::picker::filter_extensions(purpose) { let label = if purpose == "project" { rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)") + } else if purpose == "geolibre" { + rustgis_ui_egui::tl!("GeoLibre project") } else { "RustGIS items" }; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e8e4214f85..3efe731ceb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -273,6 +273,12 @@ pub const ITEM_EXTS: &[&str] = &[ "rgislayout", ]; +/// Whether lower-cased file name `lower` names a QGIS project (`.qgs` or `.qgz`), which an +/// embedded session refuses as it does every project that isn't peer project JSON. +fn is_qgis_project_file(lower: &str) -> bool { + lower.ends_with(".qgs") || lower.ends_with(".qgz") +} + /// Every `ui.openItem` kind: `(kind, command, desktop extensions, filter label, web picker purpose)`. const OPEN_ITEMS: &[(&str, &str, &[&str], &str, &str)] = &[ ("map", "map.import", &["rgismap", "rgismpk", "rgis", "rgisx", "rgispkg"], "RustGIS maps and projects", "item"), @@ -280,7 +286,7 @@ const OPEN_ITEMS: &[(&str, &str, &[&str], &str, &str)] = &[ ("styles", "style.add", &["rgisstyle"], "RustGIS styles", "item"), ("ramps", "ramp.add", &["rgisramp", "xml", "qml", "txt", "clr", "cpt"], "Colour ramps (RustGIS, QGIS, GDAL, GMT)", "ramp"), ("importStyles", "style.import", &["rgislyr", "rgismap", "rgis", "rgisx"], "RustGIS layers, maps and projects", "item"), - ("geolibreProject", "project.importGeolibre", &["geolibre", "json"], "GeoLibre project", "project"), + ("geolibreProject", "project.importGeolibre", &["geolibre", "json"], "GeoLibre project", "geolibre"), ("qgisProject", "project.importQgis", &["qgs", "qgz"], "QGIS project", "qgisProject"), ("qgisStyle", "style.importQgis", &["qml"], "QGIS layer style", "item"), ("template", "project.fromTemplate", &["rgistemplate"], "RustGIS project template", "item"), @@ -2839,6 +2845,7 @@ impl RustGisApp { if self.embedded && (rustgis_engine::project::is_project_file(name) || rustgis_engine::map::geolibre::is_project_file(name) + || is_qgis_project_file(&lower) || lower.ends_with(".rgispkg")) { self.ui.pending_open.take(); @@ -6326,7 +6333,10 @@ impl RustGisApp { fn open_project_bytes(&mut self, file: Option<&str>, bytes: &[u8]) -> Result { if self.embedded { if file.is_some_and(rustgis_engine::map::geolibre::is_project_file) - || file.is_some_and(|f| f.to_ascii_lowercase().ends_with(".rgispkg")) + || file.is_some_and(|f| { + let f = f.to_ascii_lowercase(); + f.ends_with(".rgispkg") || is_qgis_project_file(&f) + }) { return Err(tl!("Embedded sessions open peer project JSON only").into()); } @@ -11396,6 +11406,14 @@ mod look_tests { assert!(app.ui.pending_open.is_none()); assert_eq!(app.session.notices.len(), before + 1); assert!(app.open_picked("map.geolibre.json", b"{}").is_err()); + // QGIS projects too: an embedding page can't import one through a pick or a drop. + let qgs = br#""#; + let maps = app.session.project.maps.len(); + for name in ["map.qgs", "MAP.QGZ"] { + assert!(app.open_project_bytes(Some(name), qgs).is_err(), "{name}"); + assert!(app.open_picked(name, qgs).is_err(), "{name}"); + } + assert_eq!(app.session.project.maps.len(), maps, "no QGIS project was imported"); app.run("ui.theme", json!({"dark": true})).expect("in-memory theme toggle"); assert!(app.ui.dark); assert!(saved.lock().expect("the log").is_empty(), "embedded UI commands must not persist preferences"); From 43f7f6a3764fc4d18bd7b0384c5c88e6dc0752c6 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 18:36:23 -0500 Subject: [PATCH 5/5] Refuse picked project imports in embedded sessions by command A GeoLibre or QGIS import picked in an embedded session is refused whatever the file is called, so `map.json` can't pass the name gate. The GeoLibre picker list is one `GEOLIBRE_EXTS` shared by the desktop item and the browser filter, and the integration test expects the new `geolibre` picker purpose. --- apps/rustgis-web/src/picker.rs | 7 ++---- crates/ui-egui/src/lib.rs | 23 ++++++++++++++++++- .../tests/integration/geolibre_projects.rs | 2 +- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs index 6af08b042e..1811bcf637 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -1,10 +1,7 @@ //! Browser file-picker extension filters, shared with `ui-egui` so desktop and browser filters //! cannot drift. -use rustgis_ui_egui::{ITEM_EXTS, PROJECT_EXTS}; - -/// What the GeoLibre project import offers, as the desktop's `ui.openItem` kind does. -const GEOLIBRE_EXTS: &[&str] = &["geolibre", "json"]; +use rustgis_ui_egui::{GEOLIBRE_EXTS, ITEM_EXTS, PROJECT_EXTS}; /// Returns the static extension filter list for a named picker `purpose`, when it uses one. pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str]> { @@ -26,7 +23,7 @@ mod tests { fn browser_picker_extensions_match_ui_egui_lists() { assert_eq!(filter_extensions("project"), Some(rustgis_ui_egui::PROJECT_EXTS)); assert_eq!(filter_extensions("item"), Some(rustgis_ui_egui::ITEM_EXTS)); - assert_eq!(filter_extensions("geolibre"), Some(&["geolibre", "json"][..])); + assert_eq!(filter_extensions("geolibre"), Some(rustgis_ui_egui::GEOLIBRE_EXTS)); assert_eq!(filter_extensions("unknown"), None); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3efe731ceb..be3b7eff98 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -246,6 +246,10 @@ pub const MARKER_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "svg"]; /// (`purpose == "project"`). pub const PROJECT_EXTS: &[&str] = &["rgis", "rgisx", "rgispkg", "rgisfield", "qgs", "qgz", "geolibre", "json"]; +/// Extensions offered by the GeoLibre project import, on the desktop (`ui.openItem`) and in the +/// browser (`purpose == "geolibre"`). +pub const GEOLIBRE_EXTS: &[&str] = &["geolibre", "json"]; + /// Extensions offered when opening a project item in the browser (`purpose == "item"`), kept in /// sync with [`OPEN_ITEMS`], `ui.reportLayoutFile`, and ModelBuilder's import picker. pub const ITEM_EXTS: &[&str] = &[ @@ -286,7 +290,7 @@ const OPEN_ITEMS: &[(&str, &str, &[&str], &str, &str)] = &[ ("styles", "style.add", &["rgisstyle"], "RustGIS styles", "item"), ("ramps", "ramp.add", &["rgisramp", "xml", "qml", "txt", "clr", "cpt"], "Colour ramps (RustGIS, QGIS, GDAL, GMT)", "ramp"), ("importStyles", "style.import", &["rgislyr", "rgismap", "rgis", "rgisx"], "RustGIS layers, maps and projects", "item"), - ("geolibreProject", "project.importGeolibre", &["geolibre", "json"], "GeoLibre project", "geolibre"), + ("geolibreProject", "project.importGeolibre", GEOLIBRE_EXTS, "GeoLibre project", "geolibre"), ("qgisProject", "project.importQgis", &["qgs", "qgz"], "QGIS project", "qgisProject"), ("qgisStyle", "style.importQgis", &["qml"], "QGIS layer style", "item"), ("template", "project.fromTemplate", &["rgistemplate"], "RustGIS project template", "item"), @@ -2840,6 +2844,14 @@ impl RustGisApp { /// ZIP parsing. fn open_bytes_with(&mut self, name: &str, bytes: &[u8], opts: Option) -> Result { let lower = name.to_ascii_lowercase(); + // A project import picked in an embedded session is refused whatever the file is called: + // a GeoLibre or QGIS project named `map.json` would otherwise pass the name gate below. + if self.embedded && matches!(self.ui.pending_open, Some("project.importGeolibre" | "project.importQgis")) { + self.ui.pending_open = None; + let error = tl!("Embedded sessions open peer project JSON only").to_string(); + self.session.notify(error.clone(), true); + return Err(error); + } // An embedded session takes a project file only as peer project JSON, however it was picked // or dropped: the same gate as a downloaded project ([`Self::open_project_bytes`]). if self.embedded @@ -10918,6 +10930,7 @@ mod peer_output_tests { assert!(ITEM_EXTS.contains(ext), "ITEM_EXTS is missing .{ext} for {kind}"); } } + "geolibre" => assert_eq!(exts, GEOLIBRE_EXTS, "the GeoLibre picker must offer what {kind} opens"), _ => {} } } @@ -11406,6 +11419,14 @@ mod look_tests { assert!(app.ui.pending_open.is_none()); assert_eq!(app.session.notices.len(), before + 1); assert!(app.open_picked("map.geolibre.json", b"{}").is_err()); + // A GeoLibre or QGIS import picked under another name is refused by its command. + for cmd in ["project.importGeolibre", "project.importQgis"] { + let maps = app.session.project.maps.len(); + app.ui.pending_open = Some(cmd); + assert!(app.open_picked("map.json", b"{}").is_err(), "{cmd}"); + assert!(app.ui.pending_open.is_none(), "{cmd}"); + assert_eq!(app.session.project.maps.len(), maps, "{cmd}"); + } // QGIS projects too: an embedding page can't import one through a pick or a drop. let qgs = br#""#; let maps = app.session.project.maps.len(); diff --git a/crates/ui-egui/tests/integration/geolibre_projects.rs b/crates/ui-egui/tests/integration/geolibre_projects.rs index f84a070b24..ede9e72e48 100644 --- a/crates/ui-egui/tests/integration/geolibre_projects.rs +++ b/crates/ui-egui/tests/integration/geolibre_projects.rs @@ -32,7 +32,7 @@ fn geolibre_card_picker_completion_imports_a_map_without_replacing_work() { h.get_by_role_and_label(egui::accesskit::Role::Button, "GeoLibre Project…").click(); h.step(); h.step(); - assert_eq!(*calls.lock().unwrap(), vec!["project"]); + assert_eq!(*calls.lock().unwrap(), vec!["geolibre"]); h.state_mut().open_picked("map.geolibre", &project()).unwrap(); h.step(); assert_eq!(h.state().session.project.maps.len(), maps + 1);