diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 7dfc49e095..bfbd782e85 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,14 @@ 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) + 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 = "&".join(kept + [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..f708cc3685 100644 --- a/apps/rustgis-python/tests/test_widget.py +++ b/apps/rustgis-python/tests/test_widget.py @@ -225,3 +225,18 @@ 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" + # 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/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..1811bcf637 --- /dev/null +++ b/apps/rustgis-web/src/picker.rs @@ -0,0 +1,29 @@ +//! Browser file-picker extension filters, shared with `ui-egui` so desktop and browser filters +//! cannot drift. + +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]> { + 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, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The browser picker re-exports `ui-egui`'s canonical project and item extension slices. + #[test] + 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(rustgis_ui_egui::GEOLIBRE_EXTS)); + assert_eq!(filter_extensions("unknown"), None); + } +} diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 5185b55eac..23d3cd8bba 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1379,30 +1379,17 @@ 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, GeoLibre)"), - &["rgis", "rgisx", "rgispkg", "geolibre", "json"], - ) + } 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" + }; + 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", - &[ - "rgismap", - "rgismpk", - "rgispkg", - "rgislyr", - "rgisstyle", - "rgisramp", - "rgistemplate", - "rgistask", - "rgisbookmarks", - "rgis", - "rgisx", - ], - ) } 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 2b659c7dda..7aa3a0434d 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -1479,6 +1479,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 8e17fd6e34..d7bb4352ac 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 260ca9d761..78655d34f2 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 2a27412a0b..27c5e290ff 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 0cf477dd2f..dd48a573a9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -64953,6 +64953,57 @@ fn a_transparency_reads_back_without_float_noise() { 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(); +} + /// Headless sessions emit the CJK font-folder scan notice once through `Session::run` when a /// fallback scan was lossy, stay silent when clean, and leave the summary untouched across every /// `Session::new` copy once a UI shell claims process-wide ownership for translation. diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index 98cb993f27..d17c4753ab 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -397,20 +397,56 @@ 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}")) +} + +/// 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 { - 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 +461,50 @@ 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<(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((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 { + let key = note.text.clone(); + grouped_plain.push((key, vec![(idx, name.to_string(), 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(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) { - outs.push(OutputLayer::Table(dataset(v, tool)?)); + let (ds, report) = dataset(v, tool)?; + push_report(output_idx, &ds.name, report); + output_idx += 1; + outs.push(OutputLayer::Table(ds)); + } + let losses = grouped_losses + .into_iter() + .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: Vec::new(), output: Output::Layers(outs), messages }) + Ok(ToolResult { losses, output: Output::Layers(outs), messages }) } #[cfg(test)] @@ -470,4 +543,128 @@ 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` + /// 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!({ + "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); + + // Single lossy output keeps its direct layer-prefixed message. + let single = json!({ + "layers": [{ + "name": "Solo", + "geojson": { + "type": "FeatureCollection", + "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": { + "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_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!( + 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!( + 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/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d5e23274e6..b3575b68b5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -71,13 +71,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, - /// The source-backed layer last counted: its name for PostGIS, numeric ID for GeoPackage. + pub source_map: Option, + /// 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, @@ -327,14 +327,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(MapOwner::of(s)); } "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(MapOwner::of(s)); + self.source_layer = layer.map(|l| l.id); + self.source_instance = layer.map(|l| l.instance_id()); + self.source_map = Some(MapOwner::of(s)); } // A table of addresses is what's usually geocoded: picked by its id (`flag` says the // choice is a table), since names can repeat. @@ -348,30 +351,49 @@ impl Dialogs { Ok(()) } - fn gpkg_owner(&self, s: &Session) -> Result<(), String> { - if !self.gpkg_map.as_ref().is_some_and(|owner| owner.holds(s)) { - return Err(tl!("The active project or map changed; reopen the GeoPackage dialog for the intended layer.").into()); + fn source_owner(&self, s: &Session, prefix: &str) -> Result<(), String> { + if !self.source_map.as_ref().is_some_and(|owner| owner.holds(s)) { + 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) } @@ -1066,6 +1088,12 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { app.dialogs.values = Default::default(); // And so is a count still on its way (dropping it stops the worker). app.dialogs.matching = Default::default(); + if which == "addDatabase" { + app.dialogs.b.clear(); + } + if which == "addCsv" { + app.dialogs.csv = None; + } if which == "addDxf" { app.dialogs.dxf = None; } @@ -2387,7 +2415,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") @@ -2400,6 +2428,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(); }); @@ -2647,9 +2676,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); @@ -2664,52 +2691,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![ @@ -2752,7 +2774,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 @@ -2763,7 +2786,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. @@ -2771,7 +2797,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 @@ -2788,7 +2814,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(|_| ()) }) } @@ -3660,14 +3686,14 @@ mod tests { fn the_gpkg_prompt_follows_its_map_when_the_map_moves() { let mut app = RustGisApp::with_sample(); let first = app.session.map().name.clone(); - let dialogs = Dialogs { gpkg_map: Some(MapOwner::of(&app.session)), ..Dialogs::default() }; - assert!(dialogs.gpkg_owner(&app.session).is_ok()); + let dialogs = Dialogs { source_map: Some(MapOwner::of(&app.session)), ..Dialogs::default() }; + assert!(dialogs.source_owner(&app.session, "gpkg").is_ok()); app.run("map.new", json!({"name": "Second"})).unwrap(); - assert!(dialogs.gpkg_owner(&app.session).is_err(), "another map is in view"); + assert!(dialogs.source_owner(&app.session, "gpkg").is_err(), "another map is in view"); app.run("map.activate", json!({"name": first})).unwrap(); app.run("map.move", json!({"name": first, "to": 1})).unwrap(); assert_eq!(app.session.project.active_map, 1, "the map in view moved to the end"); - assert!(dialogs.gpkg_owner(&app.session).is_ok(), "the same map, moved"); + assert!(dialogs.source_owner(&app.session, "gpkg").is_ok(), "the same map, moved"); } #[test] @@ -5808,4 +5834,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 c795fb356f..be3b7eff98 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,6 +242,68 @@ 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 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] = &[ + "rgismap", + "rgismpk", + "rgispkg", + "rgislyr", + "rgisstyle", + "rgisramp", + "rgistemplate", + "rgistask", + "rgisbookmarks", + "rgis", + "rgisx", + "qml", + "rgisreport", + "rgisrpttemplate", + "rgispres", + "rgisnb", + "ipynb", + "rgisdlpk", + "rgisfield", + "json", + "rgistool", + "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"), + ("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_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"), + ("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; @@ -2782,11 +2844,20 @@ 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 && (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(); @@ -2805,6 +2876,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"), @@ -3510,27 +3583,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)?; assistant::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); + } + Ok(()) + } + + /// Resets transient UI and editing state tied to the replaced project, shared by ordinary + /// project-replacement commands and peer project replacement. + fn reset_after_project_replace(&mut self) { + self.map.cancel_sketch(); + pluginpanel::cancel_pick(self); + // A project replacing this one hasn't been saved in the browser yet (opening a file + // names it again). 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, - ); - } - layoutview::follow_project(self); - for notice in report.notices() { - self.session.notify(notice, false); + let n = steps.len().to_string(); + let text = + crate::i18n::fmt("Recording stopped: another project opened, and its {n} steps were for the previous one.", &[("n", &n)]); + self.session.notify(text, true); } - Ok(()) + // A probe still under way is for an address added to the old project: dropped, so + // its layer never lands in the new one, and said, as a download landing late is. A plugin + // command waiting for it went with the old project's waits. + self.retire_cog_probes(); + self.ws.task_edit = None; } /// Reports pending header reads retired by either ordinary or peer project replacement. @@ -3780,29 +3874,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); @@ -5172,10 +5245,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") { @@ -5412,37 +5482,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(); @@ -6295,7 +6345,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()); } @@ -10800,6 +10853,108 @@ 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); + let view = h.state().map.view_rect.unwrap().0; + let at = view.center(); + // 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(); + 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"); + } + + /// 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}"); + } + } + "geolibre" => assert_eq!(exts, GEOLIBRE_EXTS, "the GeoLibre picker must offer what {kind} opens"), + _ => {} + } + } + for ext in std::iter::once(&"rgislayout").chain(modelbuilder::MODEL_EXTS.iter()) { + 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)] @@ -11264,6 +11419,22 @@ 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(); + 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"); diff --git a/crates/ui-egui/src/modelbuilder.rs b/crates/ui-egui/src/modelbuilder.rs index 0356ed15e8..08888fd414 100644 --- a/crates/ui-egui/src/modelbuilder.rs +++ b/crates/ui-egui/src/modelbuilder.rs @@ -538,12 +538,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), 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 71b9c95142..294e74d09f 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -223,6 +223,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/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); diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index acfa3044cf..6a9408d67c 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -504,7 +504,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(); @@ -521,7 +521,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"); @@ -544,7 +544,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); @@ -563,7 +563,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(); @@ -577,7 +577,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"))] @@ -615,7 +615,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()); @@ -637,7 +637,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], @@ -655,7 +655,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());