From 85a502daec36c7ca9bbba04f9925e7bc98b564c8 Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 09:57:57 +0100 Subject: [PATCH 1/3] A project coordinate system: new maps and layers start in it (#2032 C3a part 1, C3) A project can have a coordinate system of its own, saved with it and required by name (project-crs) so an older release refuses rather than dropping it. New maps are drawn in it, new template layers are held in it, and with the option on the first layer added with a system gives it. Project Properties sets it; the map's Coordinate System dialog offers the project's and the first layer's system. --- crates/engine/src/cmd/field.rs | 2 + crates/engine/src/cmd/items.rs | 10 +- crates/engine/src/cmd/navigate.rs | 35 +++++ crates/engine/src/cmd/project.rs | 92 ++++++++++++ crates/engine/src/cmd/workflows.rs | 1 + crates/engine/src/policy/dispatch.rs | 7 + crates/engine/src/project.rs | 20 +++ crates/engine/src/project_capabilities.rs | 24 +++ crates/engine/src/tests.rs | 2 + crates/engine/src/tests/project_crs.rs | 169 ++++++++++++++++++++++ crates/ui-egui/src/backstage.rs | 8 + crates/ui-egui/src/chrome.rs | 1 + crates/ui-egui/src/dialogs.rs | 129 +++++++++++++++++ crates/ui-egui/src/readjob.rs | 23 +++ docs/user-guide/maps.md | 25 +++- schema/fixtures/project_crs.rgis | 16 ++ schema/project.schema.json | 21 ++- 17 files changed, 580 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/tests/project_crs.rs create mode 100644 schema/fixtures/project_crs.rgis diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 750ec1fbb4..e55d5b0345 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -328,6 +328,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< } let mut project = crate::project::Project::new(area.clone()); project.field_origin = origin; + // New layers made in the field are held in the home project's system, as at home. + (project.coordinate_system, project.crs_from_first_layer) = (s.project.coordinate_system, s.project.crs_from_first_layer); // The package has no home offline areas and carries its association in field_origin. map.offline_area_id = None; let mut copied = Vec::new(); diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 3979117a93..9da20f0f3c 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -940,7 +940,15 @@ fn layer_template(s: &mut Session, p: &Value) -> CmdResult { o => return Err(format!("unknown layer template '{o}'")), }; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(title); - let id = super::layer::add_dataset(s, Dataset::new(name, gt, fields)); + let mut ds = Dataset::new(name, gt, fields); + // Held in the project's coordinate system, when it has one (#2032 C3a). + // One that doesn't convert to longitude/latitude, which the map draws through, is said. + if let Some(crs) = s.project.coordinate_system + && let Err(e) = ds.hold_as(crs, Some(crs)) + { + s.notify(format!("Layer '{name}' is held in longitude/latitude, not the project's coordinate system: {e}"), false); + } + let id = super::layer::add_dataset(s, ds); if let Some(l) = s.map_mut().layer_mut(id) { l.labels.default.field = "name".into(); } diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 8aa650cca7..a81c4394d7 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -1247,6 +1247,19 @@ fn new_map(s: &mut Session, p: &Value) -> CmdResult { } let mut m = Map::new(name.clone()); (m.basemap, m.paper) = (s.map().basemap, s.map().paper); + // Drawn in the project's coordinate system, where the active map is looking; one a map can't + // be drawn in is said, and the map starts in Web Mercator as without one. + if let Some(crs) = s.project.coordinate_system { + match map_projection_for(crs) { + Ok(projection) => { + (m.projection, m.camera) = (s.map().projection.clone(), s.map().camera); + m.camera.bearing = 0.0; + m.camera.pitch = 0.0; + m.set_projection(projection); + } + Err(why) => s.notify(format!("New map '{name}' is drawn in Web Mercator: {why}"), false), + } + } s.project.maps.push(m); s.project.active_map = s.project.maps.len() - 1; s.active_layer = None; @@ -1254,6 +1267,28 @@ fn new_map(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"name": name})) } +/// The map projection for a coordinate system, or why a map can't be drawn in it: a map is +/// drawn in Web Mercator, a world projection or a projected system with an EPSG or ESRI code. +pub fn map_projection_for(crs: rustgis_data::raster::Crs) -> Result { + use rustgis_data::raster::Crs; + match crs { + Crs::WebMercator => Ok(Projection::WebMercator), + c if c.is_geographic() => { + Err(format!("the project's coordinate system, {}, is in degrees, and a map is drawn in a projected one", c.label())) + } + // An ESRI system is a custom one named by its code. + c => { + let code = match c { + Crs::Epsg(_) => c.code(), + _ => Some(c.label()).filter(|l| l.starts_with("ESRI:")).ok_or_else(|| { + format!("a map is drawn in a system with an EPSG or ESRI code, and the project's, {}, has none", c.label()) + })?, + }; + Projection::from_code(&code).map_err(|e| format!("a map can't be drawn in the project's coordinate system, {}: {e}", c.label())) + } + } +} + /// Uses the strict map selector for operations that accept map names or null. fn map_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index c4ae5269a4..7aa2d9ce4e 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -19,6 +19,8 @@ pub fn commands() -> Vec { C::new("project.save", "Save Project", "Project", save).inputs(save_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).key("Mod+S").view().params(r#"{"path"?: string}"#), C::new("project.saveAs", "Save Project As", "Project", save_as).inputs(save_as_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).key("Mod+Shift+S").view().params(r#"{"path": string}"#), C::new("project.rename", "Rename Project", "Project", rename).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": string}"#), + C::new("project.coordinateSystem", "Project Coordinate System", "Project", coordinate_system).roles(&[]).effects(crate::policy::Effects::NONE) + .params(r#"{"crs"?: the system new maps are drawn in and new empty layers are held in: EPSG:, ESRI:, WKT or a PROJ string ("" or null: none, as a project starts; omitted: kept), "fromFirstLayer"?: bool (while the project has none, the first layer added with a coordinate system gives it; omitted: kept)}"#), C::new("edit.undo", "Undo", "Quick Access Toolbar", |s, _| if s.undo() { Ok(Value::Null) } else { Err("nothing to undo".into()) }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::History)) .key("Mod+Z") .view() @@ -822,6 +824,95 @@ fn rename(s: &mut Session, p: &Value) -> CmdResult { Ok(Value::Null) } +/// Sets the project's coordinate system and whether the first layer added gives it one. Maps +/// and layers already in the project keep their own systems: it is what new ones start in. +fn coordinate_system(s: &mut Session, p: &Value) -> CmdResult { + let given = p.get("crs"); + let from_first = p.get("fromFirstLayer").filter(|v| !v.is_null()); + if given.is_none() && from_first.is_none() { + return Err("give crs, fromFirstLayer or both".into()); + } + let crs = match given { + None => s.project.coordinate_system, + Some(Value::Null) => None, + Some(Value::String(t)) if t.trim().is_empty() => None, + Some(Value::String(t)) => { + Some(rustgis_data::raster::Crs::parse(super::within("crs", "a coordinate system", t, 64 * 1024)?.as_str())?) + } + Some(_) => return Err("crs is a coordinate system's code, WKT or PROJ string, or null".into()), + }; + let from_first = match from_first { + None => s.project.crs_from_first_layer, + Some(v) => v.as_bool().ok_or("fromFirstLayer is true or false")?, + }; + s.project.coordinate_system = crs; + s.project.crs_from_first_layer = from_first; + Ok(project_crs_json(&s.project)) +} + +/// The project's coordinate system as commands give it: its code (which `crs` reads back), its +/// name, whether a map can be drawn in it, and whether the first layer added gives it one. +pub(crate) fn project_crs_json(project: &crate::project::Project) -> Value { + let crs = project.coordinate_system; + json!({ + "crs": crs.map(|c| c.code()), + "label": crs.map(|c| c.label()), + "mapsCanUse": crs.map(|c| super::navigate::map_projection_for(c).is_ok()), + "fromFirstLayer": project.crs_from_first_layer, + }) +} + +/// The layers in the project before a command, when the project is to take its coordinate +/// system from the first layer added ([`Project::crs_from_first_layer`]) and has none yet; else +/// `None`, and nothing is looked at. Undo and Redo bring back layers that were added before, and +/// a project opened or started brings its own setting: they give none. +/// +/// [`Project::crs_from_first_layer`]: crate::project::Project::crs_from_first_layer +pub(crate) fn first_layer_watch(s: &Session, id: &str) -> Option<(u64, std::collections::HashSet)> { + let p = &s.project; + if !p.crs_from_first_layer || p.coordinate_system.is_some() || matches!(id, "edit.undo" | "edit.redo") { + return None; + } + // A raster whose pixels haven't landed yet (read in place, or from a server) says no system + // until they do: it counts as added until then, so the next command finds it. + let decided = |l: &&rustgis_map::Layer| l.raster.as_ref().is_none_or(|r| r.data.is_some()); + Some((s.opened, p.maps.iter().flat_map(|m| m.layers.iter().filter(decided).map(rustgis_map::Layer::instance_id)).collect())) +} + +/// The coordinate system a layer says it is in: a raster's, or the one a feature layer was read +/// in. `None` for a feature layer whose source named none (taken for longitude/latitude). +pub fn layer_system(l: &rustgis_map::Layer) -> Option { + match &l.raster { + Some(r) => r.data.as_ref().map(|d| d.crs), + None => l.dataset.crs, + } +} + +/// After a command: the project takes the coordinate system of the first layer it added that +/// has one, in the maps' order, and says so ([`first_layer_watch`]). +pub(crate) fn take_first_layer_system(s: &mut Session, (opened, before): &(u64, std::collections::HashSet)) { + if s.opened != *opened || !s.project.crs_from_first_layer || s.project.coordinate_system.is_some() { + return; + } + let found = s + .project + .maps + .iter() + .flat_map(|m| m.layers.iter()) + .filter(|l| !before.contains(&l.instance_id())) + .find_map(|l| layer_system(l).map(|crs| (crs, l.name.clone()))); + if let Some((crs, name)) = found { + s.project.coordinate_system = Some(crs); + s.notify( + format!( + "The project's coordinate system is now {}, from layer '{name}': new maps are drawn in it and new layers held in it", + crs.label() + ), + false, + ); + } +} + /// Picks the map tool: a Create tool needs a layer of its kind selected, and the tools that /// change features (Edit Vertices, Cut Polygon, Reshape) need editing on. fn set_tool(s: &mut Session, p: &Value) -> CmdResult { @@ -953,6 +1044,7 @@ fn info(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({ "name": s.project.name, "path": s.path.as_ref().map(|p| p.display().to_string()), + "coordinateSystem": project_crs_json(&s.project), "unsaved": s.dirty(), "maps": s.project.maps.iter().map(|m| m.name.clone()).collect::>(), "activeMap": m.name, diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b7eb5aefd7..7cb24fc7f3 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -931,6 +931,7 @@ fn check_prepared_prefix(s: &Session, lines: &[(usize, String, Value)]) -> Resul /// A line that makes rows of its own (a layer edit, a layer from a selection) isn't one. Table edits are the /// exception: their rows are recorded and taken, so later tools retain their shared input. pub(crate) const ON_A_COPY: &[&str] = &[ + "project.coordinateSystem", "edit.enable", "edit.setValue", "edit.addFeature", diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index eb21357ca8..c1c7a816c6 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -989,11 +989,18 @@ impl Session { result }) }; + // A command run by itself, however it lands (a read ahead, a download, a URL + // read in place), may add the layer the project takes its system from. + let first_layer = + (matches!(txn, Txn::Own) && self.depth == 0).then(|| crate::cmd::project::first_layer_watch(self, spec.id)).flatten(); let result = match txn { Txn::Own => self.guarded(spec.label, spec.mutates, run), Txn::Shared if spec.id == "edit.applyShapeConversion" => self.shared_step(&spec, |s| s.savepoint(spec.label, run)), Txn::Shared => self.shared_step(&spec, run), }; + if let (Ok(_), Some(before)) = (&result, first_layer) { + crate::cmd::project::take_first_layer_system(self, &before); + } self.url_completion_landed(spec.id, ¶ms, &result); if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" { // Edits and history moves can replace selections without select::set. History diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 0e3471d3c0..91ea0caf82 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -106,10 +106,15 @@ pub const CAPABILITIES: &[&str] = &[ NATIVE_COORDINATES, "layout-legend-text", "label-guide", + PROJECT_CRS, ]; /// A layer or table saved in a coordinate system of its own, not longitude/latitude /// (`Dataset::held_in`, #2032 C2d): an older reader would read its coordinates as degrees. pub(crate) const NATIVE_COORDINATES: &str = "native-coordinates"; +/// A project with a coordinate system of its own, or taking one from its first layer +/// (`Project::coordinate_system`, `Project::crs_from_first_layer`, #2032 C3a): an older reader +/// would save it again without them. +pub(crate) const PROJECT_CRS: &str = "project-crs"; /// Independent marker sizes alongside classified point colours (`Layer::size_by`). pub(crate) const SIZE_BY_CAPABILITY: &str = "classified-point-size"; /// The most entries a document's `requires` may list: past it the document is refused without @@ -470,6 +475,17 @@ pub struct Project { #[serde(default)] #[cfg_attr(feature = "schema", schemars(with = "Vec"))] pub data_stores: Vec, + /// The project's coordinate system (#2032 C3a): new maps are drawn in it, when a map can be, + /// and new empty layers hold their coordinates in it. Maps and layers already in the project + /// keep theirs. `None`: new maps in Web Mercator and new layers in longitude/latitude, as + /// before there was one. Saved with [`PROJECT_CRS`], which an older reader refuses rather + /// than saving the project again without it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub coordinate_system: Option, + /// While the project has no coordinate system, the first layer added with one of its own + /// gives it its system ([`Project::coordinate_system`]). Off by default. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub crs_from_first_layer: bool, } /// A standalone table: a dataset without geometry, under an id that stays with it. Names can @@ -1153,6 +1169,8 @@ impl Project { dl_models: Vec::new(), shared: Vec::new(), data_stores: Vec::new(), + coordinate_system: None, + crs_from_first_layer: false, } } @@ -2435,6 +2453,8 @@ impl Durable for Project { dl_models: _, shared: _, data_stores: _, + coordinate_system: _, + crs_from_first_layer: _, } = self; for (i, v) in maps.iter().enumerate() { p.child(Owner::Map(i), v); diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index f2591c9559..28f597f24b 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -43,6 +43,9 @@ impl Project { if !required.contains(&super::NATIVE_COORDINATES) && self.tables.iter().any(|t| held_natively(&t.dataset)) { required.push(super::NATIVE_COORDINATES); } + if self.coordinate_system.is_some() || self.crs_from_first_layer { + required.push(super::PROJECT_CRS); + } // Saved symbology keeps its images too. if !required.contains(&"picture-markers") && self.styles.iter().any(|s| s.renderer.has_picture_markers()) { required.push("picture-markers"); @@ -1378,6 +1381,27 @@ mod tests { assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-zarr")); } + /// A project's coordinate system and its first-layer option (#2032 C3a) are required by name: + /// an older reader would save the project again without them. A project with neither needs + /// nothing, and one listing a capability this release lacks is still refused by name. + #[test] + fn a_project_coordinate_system_is_required_where_it_is_saved() { + let text = include_str!("../../../schema/fixtures/project_crs.rgis"); + let mut p = Project::from_json(text).unwrap(); + assert_eq!(p.coordinate_system, Some(rustgis_data::raster::Crs::Epsg(2056))); + assert!(p.crs_from_first_layer); + let saved = serde_json::to_value(&p).unwrap(); + assert_eq!(saved["requires"], json!(["project-crs"])); + assert_eq!(saved["coordinate_system"], json!({"Epsg": 2056})); + p.coordinate_system = None; + p.crs_from_first_layer = false; + let clean = serde_json::to_value(&p).unwrap(); + assert!(clean.get("requires").is_none() && clean.get("coordinate_system").is_none() && clean.get("crs_from_first_layer").is_none()); + let mut newer: Value = serde_json::from_str(text).unwrap(); + newer["requires"] = json!(["project-crs", "future-crs"]); + assert!(Project::from_json(&newer.to_string()).unwrap_err().contains("future-crs")); + } + /// A blank basemap's paper colour (#2532) is required by name in a project and a map file: an /// older reader would draw the paper white and save the colour away. White paper needs nothing. #[test] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index afe38b7d5e..306ba6e31a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33,6 +33,8 @@ mod write_notices; #[path = "tests/held_layers.rs"] mod held_layers; +#[path = "tests/project_crs.rs"] +mod project_crs; #[path = "tests/task_reentry.rs"] mod task_reentry; diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs new file mode 100644 index 0000000000..38257371fc --- /dev/null +++ b/crates/engine/src/tests/project_crs.rs @@ -0,0 +1,169 @@ +//! The project's coordinate system (#2032 C3a): saved only when set, with `project-crs`; new maps +//! drawn in it and new empty layers held in it; taken from the first layer added when asked. + +use rustgis_data::raster::Crs; +use serde_json::{Value, json}; + +use crate::{Project, Session}; + +/// Swiss LV95, a projected system a map can be drawn in. +const LV95: Crs = Crs::Epsg(2056); + +fn saved(s: &Session) -> Value { + serde_json::to_value(&s.project).unwrap() +} + +fn requires(v: &Value) -> Vec { + v.get("requires") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|c| c.as_str().map(str::to_string)).collect()) + .unwrap_or_default() +} + +#[test] +fn a_project_without_a_coordinate_system_saves_as_before() { + let s = Session::new(Project::default()); + let v = saved(&s); + assert!(v.get("coordinate_system").is_none() && v.get("crs_from_first_layer").is_none(), "{v}"); + assert!(!requires(&v).contains(&"project-crs".to_string())); + let info = Session::new(Project::default()).run("info.project", &json!({})).unwrap(); + assert_eq!(info["coordinateSystem"], json!({"crs": null, "label": null, "mapsCanUse": null, "fromFirstLayer": false})); +} + +#[test] +fn the_coordinate_system_is_set_saved_reopened_and_undone() { + let mut s = Session::new(Project::default()); + let out = s.run("project.coordinateSystem", &json!({"crs": "2056"})).unwrap(); + assert_eq!(out, json!({"crs": "EPSG:2056", "label": "EPSG:2056", "mapsCanUse": true, "fromFirstLayer": false})); + let v = saved(&s); + assert_eq!(requires(&v), ["project-crs"]); + assert!(v.get("crs_from_first_layer").is_none()); + let mut t = Session::new(Project::default()); + t.run("project.openText", &json!({"text": v.to_string()})).unwrap(); + assert_eq!(t.project.coordinate_system, Some(LV95)); + // The option alone needs the capability too: an older reader would save the project without it. + s.run("project.coordinateSystem", &json!({"crs": null, "fromFirstLayer": true})).unwrap(); + assert_eq!((s.project.coordinate_system, s.project.crs_from_first_layer), (None, true)); + assert_eq!(requires(&saved(&s)), ["project-crs"]); + // Omitted keys are kept; Undo takes each step back. + s.run("project.coordinateSystem", &json!({"crs": "EPSG:32632"})).unwrap(); + assert_eq!((s.project.coordinate_system, s.project.crs_from_first_layer), (Some(Crs::Epsg(32632)), true)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!((s.project.coordinate_system, s.project.crs_from_first_layer), (None, true)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!((s.project.coordinate_system, s.project.crs_from_first_layer), (Some(LV95), false)); +} + +#[test] +fn the_command_refuses_what_it_cant_read() { + let mut s = Session::new(Project::default()); + for p in + [json!({}), json!({"crs": 7}), json!({"crs": "EPSG:999999999"}), json!({"crs": "not a system"}), json!({"fromFirstLayer": "yes"})] + { + assert!(s.run("project.coordinateSystem", &p).is_err(), "{p}"); + } + assert_eq!((s.project.coordinate_system, s.project.crs_from_first_layer), (None, false)); + // An empty code clears it, as null does. + s.run("project.coordinateSystem", &json!({"crs": "2056"})).unwrap(); + s.run("project.coordinateSystem", &json!({"crs": " "})).unwrap(); + assert_eq!(s.project.coordinate_system, None); +} + +#[test] +fn a_new_map_is_drawn_in_the_project_system_where_the_active_map_looks() { + let mut s = Session::new(Project::default()); + s.run("map.new", &json!({"name": "Before"})).unwrap(); + assert_eq!(s.map().projection, rustgis_map::Projection::WebMercator, "without one, as before"); + s.run("map.zoomToExtent", &json!({"extent": [6.0, 45.8, 10.5, 47.8]})).unwrap(); + let centre = s.map().center_lonlat(); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + // The maps already there keep theirs. + assert_eq!(s.map().projection, rustgis_map::Projection::WebMercator); + s.run("map.new", &json!({"name": "Swiss"})).unwrap(); + assert_eq!(s.map().projection.code(), "EPSG:2056"); + let at = s.map().center_lonlat(); + assert!((at.x - centre.x).abs() < 1e-6 && (at.y - centre.y).abs() < 1e-6, "{at:?} vs {centre:?}"); +} + +#[test] +fn a_new_map_in_a_system_a_map_cant_use_says_why() { + let mut s = Session::new(Project::default()); + // ETRS89, in degrees. + s.run("project.coordinateSystem", &json!({"crs": "EPSG:4258"})).unwrap(); + assert_eq!(s.run("info.project", &json!({})).unwrap()["coordinateSystem"]["mapsCanUse"], json!(false)); + let mark = s.notice_mark(); + s.run("map.new", &json!({"name": "Degrees"})).unwrap(); + assert_eq!(s.map().projection, rustgis_map::Projection::WebMercator); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("Web Mercator") && t.contains("EPSG:4258")), "{said:?}"); +} + +#[test] +fn a_new_template_layer_is_held_in_the_project_system_and_edited_there() { + let mut s = Session::new(Project::default()); + s.run("layer.template", &json!({"template": "points", "name": "Plain"})).unwrap(); + assert_eq!(s.map().layer_by_name("Plain").unwrap().dataset.coord_crs(), Crs::LonLat, "without one, as before"); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + s.run("layer.template", &json!({"template": "points", "name": "Swiss"})).unwrap(); + let l = s.map().layer_by_name("Swiss").unwrap(); + assert_eq!((l.dataset.coord_crs(), l.dataset.crs), (LV95, Some(LV95))); + // A point drawn at Bern's place is held in LV95 metres. + s.map_mut().editing.settings.enabled = true; + s.run("edit.addFeature", &json!({"layer": "Swiss", "geometry": {"type": "Point", "coordinates": [7.43863, 46.95108]}})).unwrap(); + let l = s.map().layer_by_name("Swiss").unwrap(); + let Some(rustgis_data::Geometry::Point(c)) = l.dataset.features.first().and_then(|f| f.geometry.clone()) else { panic!("no point") }; + assert!((c.x - 2_600_000.0).abs() < 5.0 && (c.y - 1_200_000.0).abs() < 5.0, "{c:?}"); + // Saved, it needs the native coordinates as any held layer does. + let r = requires(&saved(&s)); + assert!(r.contains(&"native-coordinates".to_string()) && r.contains(&"project-crs".to_string()), "{r:?}"); +} + +/// A GeoPackage with a point at Bern in LV95, made in a project of that system. +fn lv95_file(name: &str) -> (std::path::PathBuf, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("rustgis-project-crs-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("bern.gpkg"); + let mut w = Session::new(Project::default()); + w.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + w.run("layer.template", &json!({"template": "points", "name": "Bern"})).unwrap(); + w.map_mut().editing.settings.enabled = true; + w.run("edit.addFeature", &json!({"layer": "Bern", "geometry": {"type": "Point", "coordinates": [7.43863, 46.95108]}})).unwrap(); + w.run("share.exportLayer", &json!({"layer": "Bern", "path": path})).unwrap(); + (dir, path) +} + +#[test] +fn the_first_layer_added_gives_its_system_when_asked() { + let (dir, path) = lv95_file("first"); + // Off (the default): nothing is taken. + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path, "name": "Off"})).unwrap(); + assert_eq!(s.project.coordinate_system, None); + // On: the next layer added with a system of its own gives it, said, and Undo takes both back. + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let mark = s.notice_mark(); + s.run("layer.addData", &json!({"path": path, "name": "On"})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("EPSG:2056") && n.text.contains("'On'")), "{:?}", s.notices); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.project.coordinate_system, None); + assert!(s.map().layer_by_name("On").is_none()); + // Redo brings back the layer and the system the step set. + s.run("edit.redo", &Value::Null).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + // Once set, a later layer doesn't change it. + s.run("project.coordinateSystem", &json!({"crs": "EPSG:32632"})).unwrap(); + s.run("layer.addData", &json!({"path": path, "name": "Later"})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(Crs::Epsg(32632))); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn a_layer_without_a_system_of_its_own_gives_none() { + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + // A template's layer is made in longitude/latitude with no system named. + s.run("layer.template", &json!({"template": "lines"})).unwrap(); + assert_eq!(s.project.coordinate_system, None); +} diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 9918e35fbb..79745cee4f 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -149,7 +149,15 @@ fn start(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ui.label(egui::RichText::new(tl!("Layers")).color(t.text_dim)); ui.label(app.session.project.maps.iter().map(|m| m.layers.len()).sum::().to_string()); ui.end_row(); + ui.label(egui::RichText::new(tl!("Coordinate system")).color(t.text_dim)); + ui.label(app.session.project.coordinate_system.map_or_else(|| tl!("None").to_string(), |c| c.label())); + ui.end_row(); }); + ui.add_space(6.0); + if ui.button(tl!("Project Properties…")).clicked() { + let _ = app.run("ui.dialog", json!({"name": "projectProperties"})); + app.ui.backstage = false; + } } /// A project choice whose visible title is also its accessible button name. diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 4e3add01bc..9bf5774d11 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1106,6 +1106,7 @@ fn search_action(id: &str) -> Option { "map.import" => OpenItem("map"), "map.save" => SaveItem("map"), "map.package" => SaveItem("mapPackage"), + "project.coordinateSystem" => Dialog("projectProperties"), "map.rename" => Dialog("renameMap"), "map.goToXY" => Dialog("goToXY"), "map.exportOrbit" => Dialog("exportOrbit"), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 223ae19e03..ebf2f8d67e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -147,6 +147,7 @@ impl Dialogs { "renameServiceGroup" => "renameServiceGroup", "renameGroup" => "renameGroup", "coordinateSystem" => "coordinateSystem", + "projectProperties" => "projectProperties", "defineProjection" => "defineProjection", "addShapefile" => "addShapefile", "camera" => "camera", @@ -210,6 +211,10 @@ impl Dialogs { let is_code = self.text.to_ascii_lowercase().starts_with("epsg"); self.a = if is_code { self.text.trim_start_matches(|c: char| !c.is_ascii_digit()).to_string() } else { String::new() }; } + "projectProperties" => { + self.text = s.project.coordinate_system.map(|c| c.definition_text()).unwrap_or_default(); + self.flag = s.project.crs_from_first_layer; + } "addDxf" => { // A drawing never says its coordinate system: the map's, where it is drawn. self.text = map_crs(&s.map().projection); @@ -327,6 +332,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { "addField" => "Add Field", "calculateField" => "Calculate Field", "coordinateSystem" => "Coordinate System", + "projectProperties" => "Project Properties", "defineProjection" => "Define Projection", "addShapefile" => "Import Shapefile with Projection", "camera" => "Camera", @@ -539,6 +545,56 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { Ok(()) }); } + "projectProperties" => { + ui.label(egui::RichText::new(&app.session.project.name).strong()); + ui.label(tl!("New maps are drawn in the project's coordinate system, and new empty layers hold their coordinates in it. Maps and layers already in the project keep theirs.")); + let input_label = ui.label(tl!("Coordinate system")); + let recent = app.ui.recent_crs.clone(); + let width = ui.available_width(); + let (r, _) = crate::crspicker::crs_box( + ui, + "projectProperties", + &mut app.dialogs.text, + &recent, + crate::crspicker::Offer::All, + width, + tl!("None: new maps in Web Mercator"), + &t, + ); + let r = r.labelled_by(input_label.id); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, tl!("Coordinate system"))); + // Read when the text changes, not every frame: a WKT or PROJ definition costs a + // conversion to build, and each one typed takes a place in the run's table. + let typed = app.dialogs.text.trim().to_string(); + let memo = egui::Id::unique("projectPropertiesSystem"); + let cached: Option<(String, Option<(String, bool)>)> = ui.data(|d| d.get_temp(memo)); + let said = match cached { + Some((text, said)) if text == typed => said, + _ => { + let said = match (!typed.is_empty()).then(|| rustgis_engine::data::raster::Crs::parse(&typed)) { + Some(Ok(crs)) => rustgis_engine::cmd::navigate::map_projection_for(crs) + .err() + .map(|why| (i18n::fmt("New maps stay in Web Mercator: {why}", &[("why", &why)]), false)), + Some(Err(e)) => Some((e, true)), + None => None, + }; + ui.data_mut(|d| d.insert_temp(memo, (typed.clone(), said.clone()))); + said + } + }; + if let Some((text, error)) = said { + ui.label(egui::RichText::new(text).color(if error { t.red } else { t.text_dim })); + } + ui.checkbox(&mut app.dialogs.flag, tl!("While it has none, take it from the first layer added")); + close = buttons(app, ui, "Apply", |app| { + let crs = app.dialogs.text.trim().to_string(); + app.run("project.coordinateSystem", json!({"crs": crs, "fromFirstLayer": app.dialogs.flag}))?; + if !crs.is_empty() { + app.remember_crs_if_listed(&crs); + } + Ok(()) + }); + } "basemap" | "body" | "addSample" | "layerTemplate" => { // Menu items close their nearest closable parent. Keep that local to the // gallery so picking an item doesn't persistently collapse the Window's body. @@ -2781,6 +2837,40 @@ fn coordinate_system(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) -> boo }); }); }); + // The project's system and the first layer's with one of its own, each picked as a row of the + // list is (Apply draws the map in it), and off with why when a map can't be drawn in it. + ui.horizontal_wrapped(|ui| { + use rustgis_engine::cmd::navigate::map_projection_for; + let project = app.session.project.coordinate_system; + let first = + app.session.map().layers.iter().find_map(|l| rustgis_engine::cmd::project::layer_system(l).map(|c| (c, l.name.clone()))); + let offers = [ + ( + tl!("Use the project's"), + project.ok_or_else(|| tl!("The project has no coordinate system (Project Properties)").to_string()), + "useProject", + ), + ( + tl!("Use the first layer's"), + first.map(|(c, _)| c).ok_or_else(|| tl!("No layer of the map has a coordinate system of its own").to_string()), + "useFirstLayer", + ), + ]; + for (label, crs, _) in offers { + let projection = crs.and_then(|c| map_projection_for(c).map(|p| (c, p))); + let r = ui.add_enabled(projection.is_ok(), egui::Button::new(label)); + let r = match &projection { + Ok((c, _)) => r.on_hover_text(c.label()), + Err(why) => r.on_disabled_hover_text(why.as_str()), + }; + if r.clicked() + && let Ok((_, p)) = projection + { + app.dialogs.text = p.code(); + app.dialogs.a.clear(); + } + } + }); ui.separator(); let chosen = app.dialogs.text.clone(); let check = rustgis_engine::map::Projection::from_code(&chosen); @@ -3537,6 +3627,45 @@ mod tests { assert_eq!(h.state().session.tool, rustgis_engine::Tool::ZoomIn, "nor switched the tool"); } + /// Project Properties sets the project's coordinate system and its first-layer option through + /// `project.coordinateSystem`, and opens on what the project has; the map's Coordinate System + /// dialog then offers the project's system, and the first layer's once one has a system. + #[test] + fn project_properties_set_the_system_the_map_dialog_offers() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "projectProperties"})).unwrap(); + assert_eq!((app.dialogs.text.as_str(), app.dialogs.flag), ("", false)); + app.dialogs.text = "EPSG:2056".into(); + app.dialogs.flag = true; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 1000.0)).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h.get_by_role_and_label(Role::Button, "Apply").click(); + h.run_steps(4); + let p = &h.state().session.project; + assert_eq!((p.coordinate_system, p.crs_from_first_layer), (Some(rustgis_engine::data::raster::Crs::Epsg(2056)), true)); + assert_eq!(h.state().dialogs.open, None, "applied and closed"); + h.state_mut().run("ui.dialog", json!({"name": "projectProperties"})).unwrap(); + assert_eq!((h.state().dialogs.text.as_str(), h.state().dialogs.flag), ("EPSG:2056", true), "opens on what it has"); + h.state_mut().dialogs.open = None; + h.state_mut().run("ui.dialog", json!({"name": "coordinateSystem"})).unwrap(); + h.run_steps(4); + h.get_by_role_and_label(Role::Button, "Use the project's").click(); + h.run_steps(2); + assert_eq!(h.state().dialogs.text, "EPSG:2056"); + h.get_by_role_and_label(Role::Button, "Apply").click(); + h.run_steps(4); + assert_eq!(h.state().session.map().projection.code(), "EPSG:2056"); + } + /// In the app, Escape in a coordinate system box closes its list, not the dialog, and the /// Escape shortcut (the Explore tool) doesn't take it; Enter in the blank box takes no recent /// system, while ↓ then Enter does. diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 165cb07366..5ea148717c 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -1331,6 +1331,29 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A file added on a thread gives the project its coordinate system when the project takes + /// it from the first layer added: the read lands through the same seam as a command. + #[test] + fn a_file_added_on_a_thread_gives_the_project_its_system() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("bern.shp"); + let mut w = rustgis_engine::Session::new(rustgis_engine::Project::default()); + w.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + w.run("layer.template", &json!({"template": "points", "name": "Bern"})).unwrap(); + w.map_mut().editing.settings.enabled = true; + w.run("edit.addFeature", &json!({"layer": "Bern", "geometry": {"type": "Point", "coordinates": [7.43863, 46.95108]}})).unwrap(); + w.run("share.exportLayer", &json!({"layer": "Bern", "path": path})).unwrap(); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.reads_off_frame = true; + app.run("project.coordinateSystem", json!({"fromFirstLayer": true})).unwrap(); + assert_eq!(crate::layerchooser::add_file(&mut app, &path.display().to_string()).unwrap()["started"], "Add Data"); + landed(&mut app, 60); + assert_eq!(app.session.map().layers.len(), 1); + assert_eq!(app.session.project.coordinate_system, Some(rustgis_engine::data::raster::Crs::Epsg(2056))); + app.run("edit.undo", Value::Null).unwrap(); + assert_eq!(app.session.project.coordinate_system, None, "Undo takes it back with the layer"); + } + /// Scripted Delimited Text picks join the same background queue as ordinary file picks. #[test] fn scripted_delimited_picks_run_in_background() { diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 2e0ffdeef2..c9fc217159 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -819,8 +819,8 @@ World, Sphere and Africa Sinusoidal (`ESRI:54008`, `53008`, `102011`) can be the ### Finding a coordinate system -The coordinate system boxes of the Coordinate System dialog, Define Projection, the Shapefile, DXF -and CSV imports, the measured grid, **Settings › Start-up › Projection** and the analysis +The coordinate system boxes of the Coordinate System dialog, Project Properties, Define Projection, +the Shapefile, DXF and CSV imports, the measured grid, **Settings › Start-up › Projection** and the analysis environment search as you type. A box finds a system by its code (`3035`, `EPSG:3035`, `esri:102033`), by words of its name (`lv95`, `utm 32n wgs`), by its projection method (`albers`, `oblique mercator`) or by its area of use (`switzerland`), and lists the matches under the box: the @@ -842,6 +842,27 @@ systems only. Text the list doesn't hold, such as WKT or a PROJ string, is used is remembered once it is applied or its import starts; **Clear** beside **Recently used** in the Coordinate System dialog forgets them all. +### The project's coordinate system + +A project can have a coordinate system of its own, set in **Project Properties** (the project +page's **Project Properties…** button, or `project.coordinateSystem` from the command line, Python +or the Assistant). New maps are drawn in it, starting where the active map is looking, and new +empty layers from **Layer Templates** hold their coordinates in it, so features drawn in them are +stored in its units. Maps and layers already in the project keep their own systems. A system in +degrees, or one without an EPSG or ESRI code, can't be a map's projection: new maps then stay in +Web Mercator, and RustGIS says why. A project without one works as before. + +**While it has none, take it from the first layer added** gives the project the system of the next +layer added that says what system it is in (a raster's, or a file's such as a GeoPackage's or a +Shapefile's `.prj`), and says so; Undo takes it back with the layer. A layer that names no system, +taken for longitude/latitude, gives none; one that names WGS 84 or another system in degrees gives +that, and new maps then stay in Web Mercator. The setting and the option are saved with the project; +an older RustGIS refuses a project that has them (it needs `project-crs`) rather than saving it +again without them. + +In the **Coordinate System** dialog, **Use the project's** and **Use the first layer's** pick the +project's system or that of the map's first layer with one, and Apply draws the map in it. + ## Globe
diff --git a/schema/fixtures/project_crs.rgis b/schema/fixtures/project_crs.rgis new file mode 100644 index 0000000000..580cbe0f49 --- /dev/null +++ b/schema/fixtures/project_crs.rgis @@ -0,0 +1,16 @@ +{ + "format": 2, + "name": "Project coordinate system", + "requires": ["project-crs"], + "active_map": 0, + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": {"center": {"x": 0, "y": 0}, "res": 30000} + } + ], + "coordinate_system": {"Epsg": 2056}, + "crs_from_first_layer": true +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 1254f284f1..66b98b949a 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -929,6 +929,21 @@ "minimum": 0, "type": "integer" }, + "coordinate_system": { + "anyOf": [ + { + "$ref": "#/$defs/Crs" + }, + { + "type": "null" + } + ], + "description": "The project's coordinate system (#2032 C3a): new maps are drawn in it, when a map can be,\nand new empty layers hold their coordinates in it. Maps and layers already in the project\nkeep theirs. `None`: new maps in Web Mercator and new layers in longitude/latitude, as\nbefore there was one. Saved with [`PROJECT_CRS`], which an older reader refuses rather\nthan saving the project again without it." + }, + "crs_from_first_layer": { + "description": "While the project has no coordinate system, the first layer added with one of its own\ngives it its system ([`Project::coordinate_system`]). Off by default.", + "type": "boolean" + }, "data_stores": { "default": [], "items": { @@ -1113,7 +1128,8 @@ "layout-frame-border", "native-coordinates", "layout-legend-text", - "label-guide" + "label-guide", + "project-crs" ], "type": "string" }, @@ -1212,7 +1228,8 @@ "layout-frame-border", "native-coordinates", "layout-legend-text", - "label-guide" + "label-guide", + "project-crs" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From dd5dba83b08aed574df62743db7f17f94bcdbc60 Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 10:39:37 +0100 Subject: [PATCH 2/3] Project coordinate system: review fixes - A raster whose system was assumed WGS 84 (no .prj, degree-like coordinates; ASCII, GeoTIFF, GDAL-converted, JPEG 2000, Zarr) gives the project none: Raster::crs_assumed. - project.coordinateSystem gives back text that reads as the same system: EPSG and ESRI codes, else a custom system's WKT. - The first layer's system is taken at each step that changes the project (script lines, MCP scripts, read-aheads), inside its transaction, so later steps see it and Undo or a failure takes it back; a step that changes nothing never sets it. - A raster whose pixels land later stays a candidate until they have, also across a rolled-back script. - Project Properties reads the typed system only once it is taken. --- crates/data/src/raster/ascii.rs | 1 + crates/data/src/raster/geotiff.rs | 1 + crates/data/src/raster/mod.rs | 7 ++ crates/data/src/raster/zarr.rs | 3 + crates/engine/src/cmd/project.rs | 63 +++++++---- crates/engine/src/cmd/raster.rs | 4 +- crates/engine/src/lib.rs | 5 + crates/engine/src/policy/dispatch.rs | 11 +- crates/engine/src/tests/permission_policy.rs | 25 +++++ crates/engine/src/tests/project_crs.rs | 111 +++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 19 ++-- 11 files changed, 216 insertions(+), 34 deletions(-) diff --git a/crates/data/src/raster/ascii.rs b/crates/data/src/raster/ascii.rs index 997725ff85..1e1a372a37 100644 --- a/crates/data/src/raster/ascii.rs +++ b/crates/data/src/raster/ascii.rs @@ -110,6 +110,7 @@ pub(super) fn read_with_nodata( let mut r = Raster::new(name, w, h, vec![data], gt, crs, nodata, ColorHint::Gray, "Float32")?; r.lost.extend(super::planetary::note_of(crs)); if assumed { + r.crs_assumed = true; r.lost.push(super::assumed_wgs84_note( crs_issue.unwrap_or("it doesn't say its coordinate system (a .prj file next to an ASCII grid does)"), )); diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index ba9b0e2843..916d8a0da1 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1795,6 +1795,7 @@ pub(super) fn read_limited_with_nodata( r.copyright = copyright.filter(|c| !c.is_empty()); r.lost.extend(copyright_lost); r.lost.extend(super::planetary::note_of(crs)); + r.crs_assumed = assumed.is_some(); r.lost.extend(assumed); r.lost.extend(turned); r.lost.extend(table_lost); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 2126a7f2e7..d34d67e62b 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -726,6 +726,11 @@ pub struct Raster { /// `false` for a scan (a TIFF with no GeoTIFF tags, a PNG, a JPEG): `transform` is then only /// a stand-in until the picture is placed or georeferenced, and says nothing about the ground. pub georeferenced: bool, + /// Whether `crs` is WGS 84 assumed for a file that doesn't say its system, its coordinates + /// looking like degrees (an ASCII grid without a `.prj`, a GeoTIFF without one), or says only + /// that it is in degrees (a GeoTIFF's geographic model with no EPSG code, its datum unread): + /// it names no system to give (a project taking its system from the first layer added). + pub crs_assumed: bool, /// What reading it left out or cut (a colour table, names), one line a kind with a count, /// for whoever adds it to the map to say (AGENTS.md, Never silent). Empty when nothing was /// left out. @@ -922,6 +927,7 @@ impl Raster { step: 1, posts: false, georeferenced: true, + crs_assumed: false, lost: Vec::new(), rounded: Vec::new(), rounded_some: Vec::new(), @@ -1544,6 +1550,7 @@ pub fn read_converted(path: &Path, c: &gdal::Converted) -> Result { // assumed as if it had been the file's own): said with the raster's other losses, whichever way // it is read, as a reload says them again. if c.assumed_lonlat { + r.crs_assumed = true; r.lost.push(format!("{} (give \"crs\" if not)", assumed_wgs84_note("it doesn't say its coordinate system"))); } if !c.others.is_empty() { diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index 790097545e..56dcb88a16 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -2070,8 +2070,10 @@ pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap>, n // Unread proj: values stay visible beside the system used, or in the error below. let found = crs_of(store, a); let unread = if found.is_none() { unread_proj(a) } else { None }; + let mut crs_assumed = false; let (crs, crs_notes): (Option, Vec) = if lonlat { let assumed = lonlat_assumption(found.as_ref().map(|(c, _)| *c), crs); + crs_assumed = assumed.is_some(); let (actual, note) = found.unwrap_or((Crs::LonLat, None)); (Some(if actual.is_geographic() { actual } else { Crs::LonLat }), note.into_iter().chain(assumed).collect()) } else { @@ -2117,6 +2119,7 @@ pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap>, n if rounded > 0 { r.rounded = vec![rounded]; } + r.crs_assumed = crs_assumed; r.lost.extend(crs_notes); r.lost.extend(unread); // A transform the coordinates stood in for is said, not dropped without a word. diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 7aa2d9ce4e..582c55702b 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -850,22 +850,35 @@ fn coordinate_system(s: &mut Session, p: &Value) -> CmdResult { Ok(project_crs_json(&s.project)) } -/// The project's coordinate system as commands give it: its code (which `crs` reads back), its -/// name, whether a map can be drawn in it, and whether the first layer added gives it one. +/// Text `crs` reads back as the same system: an EPSG or ESRI code, else a custom system's WKT when +/// it was given one (its PROJ definition alone can leave out what places points, such as angles in +/// grads), else its PROJ definition. +pub fn crs_text(crs: rustgis_data::raster::Crs) -> String { + let label = crs.label(); + if label.starts_with("ESRI:") { label } else { crs.definition_text() } +} + +/// The project's coordinate system as commands give it: text that `crs` reads back as the same +/// system ([`crs_text`]), its name, whether a map can be drawn in it, and whether the first layer +/// added gives it one. pub(crate) fn project_crs_json(project: &crate::project::Project) -> Value { let crs = project.coordinate_system; json!({ - "crs": crs.map(|c| c.code()), + "crs": crs.map(crs_text), "label": crs.map(|c| c.label()), "mapsCanUse": crs.map(|c| super::navigate::map_projection_for(c).is_ok()), "fromFirstLayer": project.crs_from_first_layer, }) } -/// The layers in the project before a command, when the project is to take its coordinate -/// system from the first layer added ([`Project::crs_from_first_layer`]) and has none yet; else -/// `None`, and nothing is looked at. Undo and Redo bring back layers that were added before, and -/// a project opened or started brings its own setting: they give none. +/// The layers in the project before a step (a command, or a line of a script or task), when the +/// project is to take its coordinate system from the first layer added +/// ([`Project::crs_from_first_layer`]) and has none yet; else `None`, and nothing is looked at. +/// Undo and Redo bring back layers that were added before, and a project opened or started brings +/// its own setting: they give none. A raster whose pixels haven't landed (read in place, or from +/// a server) says no system until they do: it is left out, as are those +/// [`take_first_layer_system`] kept waiting, so the first step that changes the project after +/// their pixels land finds them. /// /// [`Project::crs_from_first_layer`]: crate::project::Project::crs_from_first_layer pub(crate) fn first_layer_watch(s: &Session, id: &str) -> Option<(u64, std::collections::HashSet)> { @@ -873,34 +886,40 @@ pub(crate) fn first_layer_watch(s: &Session, id: &str) -> Option<(u64, std::coll if !p.crs_from_first_layer || p.coordinate_system.is_some() || matches!(id, "edit.undo" | "edit.redo") { return None; } - // A raster whose pixels haven't landed yet (read in place, or from a server) says no system - // until they do: it counts as added until then, so the next command finds it. - let decided = |l: &&rustgis_map::Layer| l.raster.as_ref().is_none_or(|r| r.data.is_some()); + let decided = + |l: &&rustgis_map::Layer| l.raster.as_ref().is_none_or(|r| r.data.is_some()) && !s.first_layer_pending.contains(&l.instance_id()); Some((s.opened, p.maps.iter().flat_map(|m| m.layers.iter().filter(decided).map(rustgis_map::Layer::instance_id)).collect())) } /// The coordinate system a layer says it is in: a raster's, or the one a feature layer was read -/// in. `None` for a feature layer whose source named none (taken for longitude/latitude). +/// in. `None` for a layer whose file named none: a feature layer taken for longitude/latitude, a +/// raster read as WGS 84 because its coordinates look like degrees, a scan not yet placed. pub fn layer_system(l: &rustgis_map::Layer) -> Option { match &l.raster { - Some(r) => r.data.as_ref().map(|d| d.crs), + Some(r) => r.data.as_ref().filter(|d| d.georeferenced && !d.crs_assumed).map(|d| d.crs), None => l.dataset.crs, } } -/// After a command: the project takes the coordinate system of the first layer it added that -/// has one, in the maps' order, and says so ([`first_layer_watch`]). +/// After a step: the project takes the coordinate system of the first layer it added that has +/// one, in the maps' order, and says so ([`first_layer_watch`]). Rasters it added whose pixels +/// are still to come wait for the next step. pub(crate) fn take_first_layer_system(s: &mut Session, (opened, before): &(u64, std::collections::HashSet)) { - if s.opened != *opened || !s.project.crs_from_first_layer || s.project.coordinate_system.is_some() { + if s.opened != *opened { + s.first_layer_pending.clear(); return; } - let found = s - .project - .maps - .iter() - .flat_map(|m| m.layers.iter()) - .filter(|l| !before.contains(&l.instance_id())) - .find_map(|l| layer_system(l).map(|crs| (crs, l.name.clone()))); + if !s.project.crs_from_first_layer || s.project.coordinate_system.is_some() { + return; + } + let added = || s.project.maps.iter().flat_map(|m| m.layers.iter()).filter(|l| !before.contains(&l.instance_id())); + let found = added().find_map(|l| layer_system(l).map(|crs| (crs, l.name.clone()))); + // Those waiting stay listed when one is taken: a script that took it, failing later, gives + // the project back without it, and they are still to be found then. + if found.is_none() { + s.first_layer_pending = + added().filter(|l| l.raster.as_ref().is_some_and(|r| r.data.is_none())).map(rustgis_map::Layer::instance_id).collect(); + } if let Some((crs, name)) = found { s.project.coordinate_system = Some(crs); s.notify( diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 02608d7be7..3bc009d952 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -698,7 +698,9 @@ fn add_jpeg2000_bytes(s: &mut Session, p: &Value, name: &str, bytes: Vec, zo let c = raster::gdal::convert_jpeg2000(bytes, crs, MAX_UPLOAD_BYTES as u64).map_err(|e| format!("{name}: {e}"))?; let stem = Path::new(name).file_stem().and_then(|s| s.to_str()).unwrap_or("raster"); let file_name = format!("{stem}.tif"); - let r = raster::read_bytes(&file_name, &c.tif).map_err(|e| format!("{name}: {e}"))?; + let mut r = raster::read_bytes(&file_name, &c.tif).map_err(|e| format!("{name}: {e}"))?; + // The GeoTIFF GDAL made names the WGS 84 it assumed, as if the file had. + r.crs_assumed = c.assumed_lonlat; if c.assumed_lonlat { s.notify(format!("{name} doesn't say its coordinate system; its coordinates look like longitude/latitude, so it's read as WGS 84 (give \"crs\" if not)"), false); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97914fbe0e..335fc531f9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1006,6 +1006,10 @@ pub struct Session { /// the command fails ([`PutAside`]); and how deep commands run within commands now. put_aside: Option>, pub(crate) depth: u32, + /// Rasters added while the project takes its system from the first layer added, whose pixels + /// hadn't landed when the step that added them ended: still candidates until they have + /// ([`cmd::project::first_layer_watch`]). + pub(crate) first_layer_pending: Vec, /// Only the command's registered id, never its parameters. Nested commands restore this. pub(crate) diagnostic_source: Option<&'static str>, /// How many of the commands running now restore the project if they fail: a replacement is @@ -1473,6 +1477,7 @@ impl Session { merged: None, put_aside: None, depth: 0, + first_layer_pending: Vec::new(), diagnostic_source: None, restorable: 0, published_syncs: Vec::new(), diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index c1c7a816c6..d32babce79 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -989,10 +989,13 @@ impl Session { result }) }; - // A command run by itself, however it lands (a read ahead, a download, a URL - // read in place), may add the layer the project takes its system from. - let first_layer = - (matches!(txn, Txn::Own) && self.depth == 0).then(|| crate::cmd::project::first_layer_watch(self, spec.id)).flatten(); + // Each step that changes the project, however it lands (a read ahead, a download, + // a URL read in place, a line of a script or task), may add the layer the project + // takes its system from: taken then, so the steps after it (a new map) start in + // it, and inside the transaction that made it, so Undo and a failure take it back + // and the project is unsaved. A step that changes nothing (a zoom, a read-only + // scope) never changes the project for it. + let first_layer = if spec.mutates { crate::cmd::project::first_layer_watch(self, spec.id) } else { None }; let result = match txn { Txn::Own => self.guarded(spec.label, spec.mutates, run), Txn::Shared if spec.id == "edit.applyShapeConversion" => self.shared_step(&spec, |s| s.savepoint(spec.label, run)), diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index 9b83c22eb6..c4f8b87150 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -2154,3 +2154,28 @@ fn permission_policy_rollback_keeps_retired_url_requests_consumed() { assert_eq!(addresses, ["https://rollback.invalid/untouched.csv"], "rollback cannot revive retired authority"); assert_eq!(s.notices_since(mark).iter().filter(|n| n.text.contains("revoked before it started")).count(), 1); } + +/// A script sent as a call (the MCP vehicle, not `script.run`) gives the project its coordinate +/// system at the line that adds the first layer with one, as a script run by itself does. +#[test] +fn permission_policy_a_called_script_gives_the_project_its_system() { + let dir = std::env::temp_dir().join(format!("rustgis-called-script-crs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("bern.gpkg"); + let mut w = Session::new(Project::default()); + w.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + w.run("layer.template", &json!({"template": "points", "name": "Bern"})).unwrap(); + w.map_mut().editing.settings.enabled = true; + w.run("edit.addFeature", &json!({"layer": "Bern", "geometry": {"type": "Point", "coordinates": [7.43863, 46.95108]}})).unwrap(); + w.run("share.exportLayer", &json!({"layer": "Bern", "path": path})).unwrap(); + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let (scope, _) = assistant(26670); + let call = Call::script(&format!("layer.addData {}\nmap.new {}", json!({"path": path}), json!({"name": "After"}))); + let approved = pending(&s, &scope, &call); + s.run_permitted(scope, approved.allow(), &call).unwrap(); + assert_eq!(s.project.coordinate_system, Some(rustgis_data::raster::Crs::Epsg(2056))); + assert_eq!(s.map().projection.code(), "EPSG:2056"); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs index 38257371fc..f8761339e9 100644 --- a/crates/engine/src/tests/project_crs.rs +++ b/crates/engine/src/tests/project_crs.rs @@ -167,3 +167,114 @@ fn a_layer_without_a_system_of_its_own_gives_none() { s.run("layer.template", &json!({"template": "lines"})).unwrap(); assert_eq!(s.project.coordinate_system, None); } + +/// An ASCII grid of 4 × 3 cells at (x, y), 0.5 units a side. +fn grid(dir: &std::path::Path, name: &str, x: f64, y: f64, prj: Option) -> std::path::PathBuf { + let path = dir.join(format!("{name}.asc")); + std::fs::write(&path, format!("ncols 4\nnrows 3\nxllcorner {x}\nyllcorner {y}\ncellsize 0.5\n1 2 3 4\n5 6 7 8\n9 10 11 12\n")).unwrap(); + if let Some(prj) = prj { + std::fs::write(dir.join(format!("{name}.prj")), prj).unwrap(); + } + path +} + +#[test] +fn a_raster_read_as_wgs84_by_assumption_gives_none_and_one_that_names_its_system_gives_it() { + let dir = std::env::temp_dir().join(format!("rustgis-project-crs-{}-grids", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + // No .prj, coordinates that look like degrees: WGS 84 assumed, so no system of its own. + let assumed = grid(&dir, "assumed", 8.0, 46.0, None); + s.run("layer.addData", &json!({"path": assumed})).unwrap(); + let l = s.map().layers.last().unwrap(); + assert!(l.raster.as_ref().unwrap().data.as_ref().unwrap().crs_assumed); + assert_eq!(s.project.coordinate_system, None); + // With its .prj: LV95. + let named = grid(&dir, "named", 2_600_000.0, 1_200_000.0, rustgis_data::raster::wkt::to_wkt(LV95)); + s.run("layer.addData", &json!({"path": named})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn the_system_given_back_reads_as_the_same_system() { + let mut s = Session::new(Project::default()); + // A WKT whose PROJ definition alone loses its grads, and an ESRI code. + let grads = r#"GEOGCS["NTF (Paris)",DATUM["Nouvelle_Triangulation_Francaise_Paris",SPHEROID["Clarke 1880 (IGN)",6378249.2,293.466021293627,AUTHORITY["EPSG","7011"]],AUTHORITY["EPSG","6807"]],PRIMEM["Paris",2.33722917,AUTHORITY["EPSG","8903"]],UNIT["grad",0.0157079632679489,AUTHORITY["EPSG","9105"]]]"#; + for given in [grads, "ESRI:102033", "EPSG:2056"] { + let out = s.run("project.coordinateSystem", &json!({"crs": given})).unwrap(); + let first = s.project.coordinate_system.unwrap(); + s.run("project.coordinateSystem", &json!({"crs": null})).unwrap(); + s.run("project.coordinateSystem", &json!({"crs": out["crs"]})).unwrap(); + let again = s.project.coordinate_system.unwrap(); + assert_eq!((first.definition_text(), first.label()), (again.definition_text(), again.label()), "{given}"); + } + let out = s.run("project.coordinateSystem", &json!({"crs": "ESRI:102033"})).unwrap(); + assert_eq!(out["crs"], "ESRI:102033"); +} + +#[test] +fn a_script_step_gives_the_system_to_the_steps_after_it() { + let (dir, path) = lv95_file("script"); + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let script = format!("layer.addData {}\nmap.new {}", json!({"path": path}), json!({"name": "After"})); + s.run("script.run", &json!({"script": script})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + assert_eq!(s.map().projection.code(), "EPSG:2056", "the new map, made after the layer, is in it"); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.project.coordinate_system, None, "one step with the script"); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn a_raster_whose_pixels_land_between_commands_still_gives_its_system() { + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let gt = rustgis_data::raster::GeoTransform { origin_x: 2_600_000.0, origin_y: 1_200_000.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = rustgis_data::raster::Raster::new( + "dem", + 2, + 2, + vec![vec![1.0; 4]], + gt, + LV95, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + // Added with its pixels still to come, as a raster read in place is. + let watch = crate::cmd::project::first_layer_watch(&s, "layer.addData").unwrap(); + let mut layer = rustgis_map::RasterLayer::from_path(r, "dem.tif"); + let pixels = layer.data.take(); + let id = s.map_mut().add_raster("dem", layer); + crate::cmd::project::take_first_layer_system(&mut s, &watch); + assert_eq!(s.project.coordinate_system, None); + // They land while the map draws, between commands. A command that changes nothing leaves the + // project as it is; the next that changes it finds the raster, unsaved and undone with it. + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = pixels; + s.mark_saved(); + s.run("map.zoomIn", &json!({})).unwrap(); + assert_eq!(s.project.coordinate_system, None); + assert!(!s.dirty()); + s.run("project.rename", &json!({"name": "Swiss"})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + assert!(s.dirty()); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.project.coordinate_system, None); +} + +#[test] +fn a_script_that_fails_after_taking_the_system_gives_it_back() { + let (dir, path) = lv95_file("failing"); + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let script = format!("layer.addData {}\nlayer.remove {}", json!({"path": path}), json!({"layer": "No such layer"})); + assert!(s.run("script.run", &json!({"script": script})).is_err()); + assert_eq!(s.project.coordinate_system, None); + assert!(s.map().layers.is_empty()); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ebf2f8d67e..419f6e9d18 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -13,6 +13,9 @@ use crate::{RustGisApp, i18n}; #[derive(Default)] pub struct Dialogs { + /// Project Properties: the system text last read, and what was said of it (and whether that is + /// an error); empty when the dialog opens, so each opening reads its text once. + pub project_crs_said: Option<(String, Option<(String, bool)>)>, /// The layer captured when Define Projection opens; changing selection must not retarget it. pub projection_layer: Option, /// Map-local layer IDs require the dialog to retain its original project and map as well. @@ -212,7 +215,7 @@ impl Dialogs { self.a = if is_code { self.text.trim_start_matches(|c: char| !c.is_ascii_digit()).to_string() } else { String::new() }; } "projectProperties" => { - self.text = s.project.coordinate_system.map(|c| c.definition_text()).unwrap_or_default(); + self.text = s.project.coordinate_system.map(rustgis_engine::cmd::project::crs_text).unwrap_or_default(); self.flag = s.project.crs_from_first_layer; } "addDxf" => { @@ -551,7 +554,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { let input_label = ui.label(tl!("Coordinate system")); let recent = app.ui.recent_crs.clone(); let width = ui.available_width(); - let (r, _) = crate::crspicker::crs_box( + let (r, taken) = crate::crspicker::crs_box( ui, "projectProperties", &mut app.dialogs.text, @@ -563,13 +566,15 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { ); let r = r.labelled_by(input_label.id); r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, tl!("Coordinate system"))); - // Read when the text changes, not every frame: a WKT or PROJ definition costs a - // conversion to build, and each one typed takes a place in the run's table. + // Read once the text is taken (the box left, a row picked, or the dialog opened on + // it), not as it is typed: a WKT or PROJ definition costs a conversion to build, + // and each one read takes a place in the run's table of typed systems for good. let typed = app.dialogs.text.trim().to_string(); - let memo = egui::Id::unique("projectPropertiesSystem"); - let cached: Option<(String, Option<(String, bool)>)> = ui.data(|d| d.get_temp(memo)); + let cached = app.dialogs.project_crs_said.clone(); + let committed = taken || r.lost_focus() || cached.is_none(); let said = match cached { Some((text, said)) if text == typed => said, + _ if !committed => None, _ => { let said = match (!typed.is_empty()).then(|| rustgis_engine::data::raster::Crs::parse(&typed)) { Some(Ok(crs)) => rustgis_engine::cmd::navigate::map_projection_for(crs) @@ -578,7 +583,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { Some(Err(e)) => Some((e, true)), None => None, }; - ui.data_mut(|d| d.insert_temp(memo, (typed.clone(), said.clone()))); + app.dialogs.project_crs_said = Some((typed.clone(), said.clone())); said } }; From 45c1eae7ba2822653d86081fbc964ff2f3c16711 Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 11:35:16 +0100 Subject: [PATCH 3/3] Project coordinate system: only data added gives it; waiting rasters kept with the project MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Only steps that add data (Home › Add, Import Map, Paste Layers, Open Offline Map) look at new layers: a tool's output gives no system. - What was looked at and which rasters wait for their pixels are kept on the project, unsaved, so Undo and a rolled-back command restore them; each layer is looked at once, so a script's outer step doesn't take again what a line cleared; any change looks at waiting rasters. - Choosing a system, turning the option off or taking one settles the rasters still waiting. - JPEG 2000 keeps the reader's assumed flag. --- crates/engine/src/cmd/project.rs | 97 ++++++++++++----- crates/engine/src/cmd/raster.rs | 2 +- crates/engine/src/lib.rs | 5 - crates/engine/src/policy/dispatch.rs | 14 +-- crates/engine/src/project.rs | 23 ++++ crates/engine/src/tests/project_crs.rs | 139 ++++++++++++++++++++++++- docs/user-guide/maps.md | 12 ++- 7 files changed, 243 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 582c55702b..ec543ee675 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -847,6 +847,11 @@ fn coordinate_system(s: &mut Session, p: &Value) -> CmdResult { }; s.project.coordinate_system = crs; s.project.crs_from_first_layer = from_first; + // A system chosen, or the option off: rasters waiting for their pixels were added before it, + // and give none later (cleared again, or the option on again). + if crs.is_some() || !from_first { + s.project.first_layer.settle(); + } Ok(project_crs_json(&s.project)) } @@ -871,24 +876,41 @@ pub(crate) fn project_crs_json(project: &crate::project::Project) -> Value { }) } -/// The layers in the project before a step (a command, or a line of a script or task), when the -/// project is to take its coordinate system from the first layer added -/// ([`Project::crs_from_first_layer`]) and has none yet; else `None`, and nothing is looked at. -/// Undo and Redo bring back layers that were added before, and a project opened or started brings -/// its own setting: they give none. A raster whose pixels haven't landed (read in place, or from -/// a server) says no system until they do: it is left out, as are those -/// [`take_first_layer_system`] kept waiting, so the first step that changes the project after -/// their pixels land finds them. +/// Commands that add data from outside the project without being under Home › Add. +const ADDS_DATA: &[&str] = &["map.import", "layer.paste", "offline.open"]; + +/// The layers in the project before a step that adds data (a command of Home › Add: a file, a +/// URL, a service, a database; or [`ADDS_DATA`]), when the project is to take its coordinate +/// system from the first layer added ([`Project::crs_from_first_layer`]) and has none yet; else +/// `None`, and nothing is looked at. A tool's output isn't a layer added: a raster made from one +/// whose system was assumed would name WGS 84 as if it had been given. Undo and Redo change +/// nothing (they are views of history), and a project opened or started brings its own setting. +/// A raster added with its pixels still to come (read in place, or from a server) says no system +/// until they land: [`take_first_layer_system`] keeps it waiting, and any later step that changes +/// the project, not only one adding data, looks at those waiting. /// /// [`Project::crs_from_first_layer`]: crate::project::Project::crs_from_first_layer -pub(crate) fn first_layer_watch(s: &Session, id: &str) -> Option<(u64, std::collections::HashSet)> { +pub(crate) fn first_layer_watch(s: &Session, spec: &crate::CommandSpec) -> Option { let p = &s.project; - if !p.crs_from_first_layer || p.coordinate_system.is_some() || matches!(id, "edit.undo" | "edit.redo") { + if !spec.mutates || !p.crs_from_first_layer || p.coordinate_system.is_some() { + return None; + } + let adds_data = spec.location.starts_with("Home › Add") || ADDS_DATA.contains(&spec.id); + if !adds_data && p.first_layer.pending.is_empty() { return None; } - let decided = - |l: &&rustgis_map::Layer| l.raster.as_ref().is_none_or(|r| r.data.is_some()) && !s.first_layer_pending.contains(&l.instance_id()); - Some((s.opened, p.maps.iter().flat_map(|m| m.layers.iter().filter(decided).map(rustgis_map::Layer::instance_id)).collect())) + let waiting = &p.first_layer.pending; + let before = + p.maps.iter().flat_map(|m| m.layers.iter()).map(rustgis_map::Layer::instance_id).filter(|id| !waiting.contains(id)).collect(); + Some(FirstLayerWatch { opened: s.opened, before, adds_data }) +} + +/// What [`first_layer_watch`] saw before a step, for [`take_first_layer_system`] after it. +pub(crate) struct FirstLayerWatch { + opened: u64, + before: std::collections::HashSet, + /// The step adds data: the layers it added are looked at, besides the rasters waiting. + adds_data: bool, } /// The coordinate system a layer says it is in: a raster's, or the one a feature layer was read @@ -902,26 +924,45 @@ pub fn layer_system(l: &rustgis_map::Layer) -> Option } /// After a step: the project takes the coordinate system of the first layer it added that has -/// one, in the maps' order, and says so ([`first_layer_watch`]). Rasters it added whose pixels -/// are still to come wait for the next step. -pub(crate) fn take_first_layer_system(s: &mut Session, (opened, before): &(u64, std::collections::HashSet)) { - if s.opened != *opened { - s.first_layer_pending.clear(); +/// one, in the maps' order, and says so ([`first_layer_watch`]). Each layer is looked at once, by +/// the innermost step that added it, so a step around it (a script and its lines) doesn't take it +/// again; rasters whose pixels are still to come wait. What was looked at is kept with the project +/// ([`crate::project::FirstLayerSeen`]), so Undo and a rolled-back command restore it. +pub(crate) fn take_first_layer_system(s: &mut Session, FirstLayerWatch { opened, before, adds_data }: &FirstLayerWatch) { + if s.opened != *opened || !s.project.crs_from_first_layer || s.project.coordinate_system.is_some() { return; } - if !s.project.crs_from_first_layer || s.project.coordinate_system.is_some() { - return; + let p = &mut s.project; + let (mut found, mut waiting) = (None, Vec::new()); + for l in p.maps.iter().flat_map(|m| m.layers.iter()) { + let id = l.instance_id(); + let candidate = if *adds_data { !before.contains(&id) } else { p.first_layer.pending.contains(&id) }; + if !candidate || p.first_layer.considered.contains(&id) { + continue; + } + if l.raster.as_ref().is_some_and(|r| r.data.is_none()) { + waiting.push(id); + continue; + } + p.first_layer.considered.insert(id); + if found.is_none() { + found = layer_system(l).map(|crs| (crs, l.name.clone())); + } } - let added = || s.project.maps.iter().flat_map(|m| m.layers.iter()).filter(|l| !before.contains(&l.instance_id())); - let found = added().find_map(|l| layer_system(l).map(|crs| (crs, l.name.clone()))); - // Those waiting stay listed when one is taken: a script that took it, failing later, gives - // the project back without it, and they are still to be found then. - if found.is_none() { - s.first_layer_pending = - added().filter(|l| l.raster.as_ref().is_some_and(|r| r.data.is_none())).map(rustgis_map::Layer::instance_id).collect(); + // Waiting: those still to come, and only layers still in the project (Undo restores the list + // with a layer it brings back). + let present: std::collections::HashSet = + p.maps.iter().flat_map(|m| m.layers.iter()).map(rustgis_map::Layer::instance_id).collect(); + let considered = &p.first_layer.considered; + p.first_layer.pending.retain(|id| present.contains(id) && !considered.contains(id)); + for id in waiting { + if !p.first_layer.pending.contains(&id) { + p.first_layer.pending.push(id); + } } if let Some((crs, name)) = found { - s.project.coordinate_system = Some(crs); + p.coordinate_system = Some(crs); + p.first_layer.settle(); s.notify( format!( "The project's coordinate system is now {}, from layer '{name}': new maps are drawn in it and new layers held in it", diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 3bc009d952..5c22b6e175 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -700,7 +700,7 @@ fn add_jpeg2000_bytes(s: &mut Session, p: &Value, name: &str, bytes: Vec, zo let file_name = format!("{stem}.tif"); let mut r = raster::read_bytes(&file_name, &c.tif).map_err(|e| format!("{name}: {e}"))?; // The GeoTIFF GDAL made names the WGS 84 it assumed, as if the file had. - r.crs_assumed = c.assumed_lonlat; + r.crs_assumed |= c.assumed_lonlat; if c.assumed_lonlat { s.notify(format!("{name} doesn't say its coordinate system; its coordinates look like longitude/latitude, so it's read as WGS 84 (give \"crs\" if not)"), false); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 335fc531f9..97914fbe0e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1006,10 +1006,6 @@ pub struct Session { /// the command fails ([`PutAside`]); and how deep commands run within commands now. put_aside: Option>, pub(crate) depth: u32, - /// Rasters added while the project takes its system from the first layer added, whose pixels - /// hadn't landed when the step that added them ended: still candidates until they have - /// ([`cmd::project::first_layer_watch`]). - pub(crate) first_layer_pending: Vec, /// Only the command's registered id, never its parameters. Nested commands restore this. pub(crate) diagnostic_source: Option<&'static str>, /// How many of the commands running now restore the project if they fail: a replacement is @@ -1477,7 +1473,6 @@ impl Session { merged: None, put_aside: None, depth: 0, - first_layer_pending: Vec::new(), diagnostic_source: None, restorable: 0, published_syncs: Vec::new(), diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index d32babce79..15d15f2ba2 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -989,13 +989,13 @@ impl Session { result }) }; - // Each step that changes the project, however it lands (a read ahead, a download, - // a URL read in place, a line of a script or task), may add the layer the project - // takes its system from: taken then, so the steps after it (a new map) start in - // it, and inside the transaction that made it, so Undo and a failure take it back - // and the project is unsaved. A step that changes nothing (a zoom, a read-only - // scope) never changes the project for it. - let first_layer = if spec.mutates { crate::cmd::project::first_layer_watch(self, spec.id) } else { None }; + // Each step that adds data, however it lands (a read ahead, a download, a URL + // read in place, a line of a script or task), may add the layer the project takes + // its system from, and any step that changes the project may find a raster added + // earlier whose pixels have landed: taken then, so the steps after it (a new map) + // start in it, and inside the transaction that made it, so Undo and a failure take + // it back and the project is unsaved ([`crate::cmd::project::first_layer_watch`]). + let first_layer = crate::cmd::project::first_layer_watch(self, &spec); let result = match txn { Txn::Own => self.guarded(spec.label, spec.mutates, run), Txn::Shared if spec.id == "edit.applyShapeConversion" => self.shared_step(&spec, |s| s.savepoint(spec.label, run)), diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 91ea0caf82..7bcf68c840 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -390,6 +390,11 @@ pub(crate) fn public_login_params(value: &serde_json::Value) -> Option, @@ -488,6 +493,22 @@ pub struct Project { pub crs_from_first_layer: bool, } +/// The layers a project taking its system from the first layer added has looked at, by instance +/// id: those looked at (each once, by the innermost step that added it), and rasters added whose +/// pixels were still to come. +#[derive(Clone, Debug, Default)] +pub(crate) struct FirstLayerSeen { + pub(crate) considered: std::collections::HashSet, + pub(crate) pending: Vec, +} + +impl FirstLayerSeen { + /// The project has a system, or doesn't take one: the rasters waiting count as looked at. + pub(crate) fn settle(&mut self) { + self.considered.extend(self.pending.drain(..)); + } +} + /// A standalone table: a dataset without geometry, under an id that stays with it. Names can /// repeat and positions change, so the id is what says which table is meant. #[derive(Clone, Debug, Serialize, Deserialize)] @@ -1141,6 +1162,7 @@ impl Project { pub fn new(name: impl Into) -> Self { Project { + first_layer: FirstLayerSeen::default(), read_notices: Vec::new(), format: FORMAT, name: name.into(), @@ -2425,6 +2447,7 @@ impl Durable for Project { /// Offers classified whole fields once, before any live mutation. fn prepare(&self, p: &mut Prepare<'_>) { let Self { + first_layer: _, read_notices: _, format: _, name: _, diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs index f8761339e9..5c57365031 100644 --- a/crates/engine/src/tests/project_crs.rs +++ b/crates/engine/src/tests/project_crs.rs @@ -247,14 +247,21 @@ fn a_raster_whose_pixels_land_between_commands_still_gives_its_system() { ) .unwrap(); // Added with its pixels still to come, as a raster read in place is. - let watch = crate::cmd::project::first_layer_watch(&s, "layer.addData").unwrap(); + let spec = *s.registry.get("layer.addData").unwrap(); + let watch = crate::cmd::project::first_layer_watch(&s, &spec).unwrap(); let mut layer = rustgis_map::RasterLayer::from_path(r, "dem.tif"); let pixels = layer.data.take(); - let id = s.map_mut().add_raster("dem", layer); + s.map_mut().add_raster("dem", layer); crate::cmd::project::take_first_layer_system(&mut s, &watch); assert_eq!(s.project.coordinate_system, None); - // They land while the map draws, between commands. A command that changes nothing leaves the - // project as it is; the next that changes it finds the raster, unsaved and undone with it. + // Removed and brought back by Undo while waiting, it still waits. + s.run("layer.remove", &json!({"layer": "dem"})).unwrap(); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.project.coordinate_system, None); + // Its pixels land while the map draws, between commands. A command that changes nothing + // leaves the project as it is; the next that changes it finds the raster, unsaved and undone + // with it. + let id = s.map().layer_by_name("dem").unwrap().id; s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = pixels; s.mark_saved(); s.run("map.zoomIn", &json!({})).unwrap(); @@ -278,3 +285,127 @@ fn a_script_that_fails_after_taking_the_system_gives_it_back() { assert!(s.map().layers.is_empty()); std::fs::remove_dir_all(&dir).ok(); } + +#[test] +fn a_tool_output_gives_no_system_only_data_added_does() { + let mut s = Session::new(Project::default()); + s.project.crs_from_first_layer = true; + // With no raster waiting: only a command adding data looks. + for (id, watched) in [ + ("gp.run", false), + ("model.run", false), + ("layer.template", false), + ("project.rename", false), + ("layer.addData", true), + ("layer.addUrl", true), + ("service.add", true), + ("map.import", true), + ("layer.paste", true), + ("offline.open", true), + ] { + let spec = *s.registry.get(id).unwrap_or_else(|| panic!("{id} is a command")); + assert_eq!(crate::cmd::project::first_layer_watch(&s, &spec).is_some(), watched, "{id}"); + } +} + +#[test] +fn a_script_line_that_clears_the_system_isnt_undone_by_the_script() { + let (dir, path) = lv95_file("cleared"); + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let script = format!("layer.addData {}\nproject.coordinateSystem {}", json!({"path": path}), json!({"crs": null})); + s.run("script.run", &json!({"script": script})).unwrap(); + assert_eq!(s.project.coordinate_system, None, "the layer was looked at once, by its own line"); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A Swiss raster added to the map with its pixels still to come, as one read in place is, by a +/// step adding data; its pixels, to land later. +fn waiting_raster(s: &mut Session) -> Option> { + let gt = rustgis_data::raster::GeoTransform { origin_x: 2_600_000.0, origin_y: 1_200_000.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = rustgis_data::raster::Raster::new( + "dem", + 2, + 2, + vec![vec![1.0; 4]], + gt, + LV95, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + let spec = *s.registry.get("layer.addData").unwrap(); + let watch = crate::cmd::project::first_layer_watch(s, &spec).unwrap(); + let mut layer = rustgis_map::RasterLayer::from_path(r, "dem.tif"); + let pixels = layer.data.take(); + s.map_mut().add_raster("dem", layer); + crate::cmd::project::take_first_layer_system(s, &watch); + pixels +} + +fn land(s: &mut Session, pixels: Option>) { + let id = s.map().layer_by_name("dem").unwrap().id; + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = pixels; +} + +#[test] +fn a_waiting_raster_taken_by_a_step_undone_or_rolled_back_is_still_to_be_found() { + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let pixels = waiting_raster(&mut s); + land(&mut s, pixels); + // A script whose first line takes it, failing later, gives the project back as it was. + let script = format!("project.rename {}\nlayer.remove {}", json!({"name": "A"}), json!({"layer": "No such layer"})); + assert!(s.run("script.run", &json!({"script": script})).is_err()); + assert_eq!(s.project.coordinate_system, None); + // An edit takes it; Undo gives it back, and the next edit takes it again. + s.run("project.rename", &json!({"name": "B"})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.project.coordinate_system, None); + s.run("project.rename", &json!({"name": "C"})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); +} + +#[test] +fn a_raster_already_in_the_project_isnt_added_by_the_next_data() { + let mut s = Session::new(Project::default()); + // In the project before the option: its pixels still to come. + let gt = rustgis_data::raster::GeoTransform { origin_x: 2_600_000.0, origin_y: 1_200_000.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = rustgis_data::raster::Raster::new( + "old", + 2, + 2, + vec![vec![1.0; 4]], + gt, + LV95, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + let mut layer = rustgis_map::RasterLayer::from_path(r, "old.tif"); + let pixels = layer.data.take(); + let id = s.map_mut().add_raster("old", layer); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let point = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[7.4,46.9]}}]}"#; + s.run("layer.addDataText", &json!({"fileName": "p.geojson", "text": point})).unwrap(); + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = pixels; + s.run("project.rename", &json!({"name": "Later"})).unwrap(); + assert_eq!(s.project.coordinate_system, None); +} + +#[test] +fn a_raster_waiting_when_a_system_is_chosen_or_the_option_turned_off_gives_none_later() { + for settle in [json!({"crs": "EPSG:32632"}), json!({"fromFirstLayer": false})] { + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + let pixels = waiting_raster(&mut s); + s.run("project.coordinateSystem", &settle).unwrap(); + land(&mut s, pixels); + s.run("project.coordinateSystem", &json!({"crs": null, "fromFirstLayer": true})).unwrap(); + s.run("project.rename", &json!({"name": "Later"})).unwrap(); + assert_eq!(s.project.coordinate_system, None, "{settle}"); + } +} diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index c9fc217159..ed3ac56604 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -853,10 +853,14 @@ degrees, or one without an EPSG or ESRI code, can't be a map's projection: new m Web Mercator, and RustGIS says why. A project without one works as before. **While it has none, take it from the first layer added** gives the project the system of the next -layer added that says what system it is in (a raster's, or a file's such as a GeoPackage's or a -Shapefile's `.prj`), and says so; Undo takes it back with the layer. A layer that names no system, -taken for longitude/latitude, gives none; one that names WGS 84 or another system in degrees gives -that, and new maps then stay in Web Mercator. The setting and the option are saved with the project; +layer added from data (**Home › Add**: a file, a URL, a service, a database; or a map imported, an +offline map opened, layers pasted) that says what system +it is in (a raster's, or a file's such as a GeoPackage's or a Shapefile's `.prj`), and says so; Undo +takes it back with the layer. A tool's output gives none. A layer that names no system, taken for +longitude/latitude, gives none, nor does a raster read as WGS 84 because its coordinates look like +degrees; one that names WGS 84 or another system in degrees gives that, and new maps then stay in +Web Mercator. A raster read in place gives its system once its pixels have arrived, at the next +change to the project. The setting and the option are saved with the project; an older RustGIS refuses a project that has them (it needs `project-crs`) rather than saving it again without them.