From 59c77f373773015a80a4b8060fb7dc764a17a397 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 12:32:02 +0100 Subject: [PATCH 1/4] Review: a fallback names its covering layer once --- crates/engine/src/cmd/design.rs | 8 +++++++- crates/engine/src/tests/held_layers.rs | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 21fb357bf1..d4f3a66e5e 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2460,7 +2460,13 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result { return Err(cancelled()); } - Err(e) => fell_back.push(format!("{} on '{}' ('{}' in {}: {e})", i.rule.label(), i.layer, i.by_layer, crs.label())), + Err(e) => { + // Its error starts with the covering data's own name, which the map's for the + // layer may not be: named once, as the map has it. + let source = i.by.as_ref().map_or("", |b| b.name.as_str()); + let rest = e.strip_prefix(&format!("{source}: ")).unwrap_or(&e); + fell_back.push(format!("{} on '{}' ('{}' in {}: {rest})", i.rule.label(), i.layer, i.by_layer, crs.label())); + } } } if let (Some((crs, Some(std::borrow::Cow::Owned(converted)))), Some(original)) = (&own, &i.by) { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index a9aeb70555..477361bc80 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2754,4 +2754,9 @@ fn a_covering_layers_conversion_is_said() { // Reaching the South Pole, which the NSIDC north polar stereographic system can't hold. let fell_back = said(box_of(0.0, -90.0, 10.0, -89.0), Crs::LonLat, Crs::Epsg(3413)); assert!(fell_back.len() == 1 && fell_back[0].starts_with("1 topology rule(s) checked in longitude/latitude"), "{fell_back:?}"); + assert_eq!( + fell_back[0].matches("Cover'").count() + fell_back[0].matches("Cover:").count(), + 1, + "the covering layer named once: {fell_back:?}" + ); } From e8e6f651f94cd5dae468d0c398451ea2e6b02689 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 13:01:27 +0100 Subject: [PATCH 2/4] Tool outputs, grids and exports default to the project's coordinate system (C3a part 2) --- crates/analysis/src/lib.rs | 6 + crates/analysis/src/tools.rs | 37 ++++-- crates/data/src/io.rs | 60 +++++++--- crates/engine/src/cmd/gp.rs | 54 +++++++-- crates/engine/src/cmd/share.rs | 15 +-- crates/engine/src/cmd/workflows.rs | 2 +- crates/engine/src/tests/project_crs.rs | 153 +++++++++++++++++++++++++ crates/ui-egui/src/analysispane.rs | 27 +++-- crates/ui-egui/src/lib.rs | 4 +- docs/user-guide/analysis.md | 8 +- docs/user-guide/maps.md | 10 ++ docs/user-guide/sharing.md | 4 +- 12 files changed, 325 insertions(+), 55 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index b0bb707bb0..c39bca6e5f 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -199,6 +199,12 @@ pub trait Inputs { fn work_crs(&self) -> rustgis_data::raster::Crs { rustgis_data::raster::Crs::LonLat } + /// The project's coordinate system (#2032 C3a), when it has one: the system a grid made from a + /// layer in degrees, or with no system, is made in when the run names none + /// ([`tools::raster_crs_in`]). + fn project_crs(&self) -> Option { + None + } /// A standalone table by its id: an input given as a number, which no name is taken for. fn table(&self, _id: u32) -> Option<&Dataset> { None diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b6d72d8e72..a8fbe74c19 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -4846,7 +4846,7 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { } }); } - let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), p, "IDW Interpolation")?; + let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), inp.project_crs(), p, "IDW Interpolation")?; let (pts, beyond_note) = points_from(inp.work_crs(), crs, pts)?; let extent = match s(p, "extent").trim() { "" => { @@ -4939,7 +4939,7 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result Result<(Crs, Option Result<(Crs, Option), String> { - if work == Crs::LonLat { - raster_crs_of(ds.crs, "was read in", &ds.name, p, tool) - } else { - raster_crs_of(Some(work), "is held in", &ds.name, p, tool) +/// system makes its grid there unless `p` names another; one in degrees, or with no system, makes +/// it in `project`, the project's system ([`Inputs::project_crs`]), when that is projected. +pub fn raster_crs_in(ds: &Dataset, work: Crs, project: Option, p: &Json, tool: &str) -> Result<(Crs, Option), String> { + if work != Crs::LonLat { + return raster_crs_of(Some(work), "is held in", &ds.name, p, tool); + } + if let Some(c) = project_raster_crs(ds.crs, project, p) { + let note = format!( + "{tool}: made in {}, the project's coordinate system, with its units for the extent and sizes, as {} {}; set crs to EPSG:4326 to make it in degrees", + c.label(), + ds.name, + if ds.crs.is_some() { "is in degrees" } else { "has no coordinate system" }, + ); + return Ok((c, Some(note))); } + raster_crs_of(ds.crs, "was read in", &ds.name, p, tool) +} + +/// The project's system (`project`) for a grid made from a layer read in `layer_crs` when the run +/// names none (`p`'s `crs`): only for a layer in degrees or with no system, and only a projected +/// system this version can project to. +fn project_raster_crs(layer_crs: Option, project: Option, p: &Json) -> Option { + let unnamed = p.get("crs").is_none_or(|v| v.is_null() || v.as_str().is_some_and(|t| t.trim().is_empty())); + (unnamed && layer_raster_crs(layer_crs).is_none()).then_some(())?; + layer_raster_crs(project)?.ok() } /// [`raster_crs`] for a layer named `name` that `how` ("was read in", "is held in") `layer_crs`. @@ -5445,6 +5463,9 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result let layer_crs = if inp.work_crs() == Crs::LonLat { ds.crs } else { Some(inp.work_crs()) }; let (crs, crs_note) = if !crs_text.is_empty() { crs_with_compatibility_note(crs_text)? + } else if let Some(c) = project_raster_crs(layer_crs, inp.project_crs(), p) { + let how = if layer_crs.is_some() { "is in degrees" } else { "has no coordinate system" }; + (c, Some(format!("made in {}, the project's coordinate system, as '{}' {how}", c.label(), ds.name))) } else if let Some(c) = layer_crs { (c, None) } else { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 1c96405fe4..ec7b30816d 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -619,30 +619,58 @@ pub fn csv_system_note(path: &str, geometry_type: GeometryType, crs: Crs) -> Opt /// `.prj`; one WKT can't describe goes into a Shapefile (without a `.prj`, said) and not into the /// others ([`default_export_note`] says which system is written instead). pub fn default_export_crs(ds: &Dataset, ext: &str) -> Crs { + default_export_crs_in(ds, ext, None) +} + +/// [`default_export_crs`] in a project with a coordinate system of its own (`project`, #2032 C3a): +/// a dataset with no system of its own is written in the project's, where the format can say it. +pub fn default_export_crs_in(ds: &Dataset, ext: &str, project: Option) -> Crs { let ext = ext.to_ascii_lowercase(); - ds.crs.filter(|&c| PROJECTED_FORMATS.contains(&ext.as_str()) && check_projected(&ext, c).is_ok()).unwrap_or(Crs::LonLat) + let fits = |c: &Crs| PROJECTED_FORMATS.contains(&ext.as_str()) && check_projected(&ext, *c).is_ok(); + match ds.crs { + Some(own) => Some(own).filter(fits), + None => project.filter(fits), + } + .unwrap_or(Crs::LonLat) } /// What is said when an export to `path` is written in WGS 84 where the layer has a system of /// its own that the format can't hold ([`default_export_crs`]); `None` when it keeps its system /// or has none to keep. pub fn default_export_note(ds: &Dataset, path: &str) -> Option { + default_export_note_in(ds, path, None) +} + +/// [`default_export_note`] in a project with a coordinate system of its own +/// ([`default_export_crs_in`]): also said when a dataset with none of its own is written in the +/// project's, or in WGS 84 as the format can't hold the project's. +pub fn default_export_note_in(ds: &Dataset, path: &str, project: Option) -> Option { let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); - let own = ds.crs.filter(|&c| c != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()))?; - (default_export_crs(ds, &ext) == Crs::LonLat).then(|| { - let why = if !matches!(ext.as_str(), "parquet" | "geoparquet") { - "has no EPSG code and no WKT definition RustGIS can write" - } else if own.epsg() == 0 { - "has no EPSG code" - } else { - "has no PROJJSON definition RustGIS can write" - }; - format!( - "{path}: the coordinate system of {} ({}) {why}, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another", - ds.name, - own.label() - ) - }) + let (own, whose) = match (ds.crs, project) { + (Some(own), _) => (own, format!("of {}", ds.name)), + (None, Some(p)) => (p, format!("of the project, which {} takes as it has none of its own,", ds.name)), + (None, None) => return None, + }; + if own == Crs::LonLat || !PROJECTED_FORMATS.contains(&ext.as_str()) { + return None; + } + if default_export_crs_in(ds, &ext, project) != Crs::LonLat { + return ds + .crs + .is_none() + .then(|| format!("{path}: written in {}, the project's coordinate system, as {} has none of its own", own.label(), ds.name)); + } + let why = if !matches!(ext.as_str(), "parquet" | "geoparquet") { + "has no EPSG code and no WKT definition RustGIS can write" + } else if own.epsg() == 0 { + "has no EPSG code" + } else { + "has no PROJJSON definition RustGIS can write" + }; + Some(format!( + "{path}: the coordinate system {whose} ({}) {why}, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another", + own.label() + )) } /// The dataset in `crs`'s coordinates, from the system it holds them in ([`Dataset::coord_crs`]), diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index db40af40fe..3da2741ada 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1267,13 +1267,22 @@ struct Snapshot<'a> { env: std::borrow::Cow<'a, crate::project::GpEnvironment>, /// The map view's size, for its extent. view_size: (f64, f64), + /// The project's coordinate system ([`crate::project::Project::coordinate_system`]): the one + /// outputs made in longitude/latitude are held in ([`MapInputs::hold_results`]). + project: Option, } impl<'a> Snapshot<'a> { /// The session itself, for a run on its thread. fn of(s: &'a Session) -> Snapshot<'a> { use std::borrow::Cow::Borrowed; - Snapshot { map: Borrowed(s.map()), tables: Borrowed(&s.project.tables), env: Borrowed(&s.project.gp_env), view_size: s.view_size } + Snapshot { + map: Borrowed(s.map()), + tables: Borrowed(&s.project.tables), + env: Borrowed(&s.project.gp_env), + view_size: s.view_size, + project: s.project.coordinate_system, + } } /// A copy of the session for a run on another thread: cheap, as the features and pixels are @@ -1286,6 +1295,7 @@ impl<'a> Snapshot<'a> { tables: Owned(s.project.tables.clone()), env: Owned(s.project.gp_env.clone()), view_size: s.view_size, + project: s.project.coordinate_system, } } } @@ -1321,19 +1331,41 @@ struct MapInputs<'a> { impl MapInputs<'_> { /// Marks the layers a tool made as held in the system it worked in ([`MapInputs::work`]), /// where their coordinates are, so they aren't taken for longitude/latitude: a layer it made - /// from scratch starts in longitude/latitude ([`Dataset::held_in`]). Nothing for a tool that - /// worked in longitude/latitude, or for a table. + /// from scratch starts in longitude/latitude ([`Dataset::held_in`]). A tool that worked in + /// longitude/latitude leaves them there, unless the project has a coordinate system of its own + /// (#2032 C3a): they are converted into it and hold it as theirs (`crs`), as a layer drawn in + /// the project is; one with a place it can't hold stays in longitude/latitude, said. Tables + /// have no coordinates to hold. fn hold_results(&self, result: &mut rustgis_analysis::ToolResult) { - if self.work == Crs::LonLat { + let project = self.snap.project.filter(|c| *c != Crs::LonLat); + if self.work == Crs::LonLat && project.is_none() { return; } - let hold = |ds: &mut Dataset| { - if ds.geometry_type != rustgis_data::GeometryType::None { - ds.held_in = self.work; + let mut kept = Vec::new(); + let mut hold = |ds: &mut Dataset| { + if ds.geometry_type == rustgis_data::GeometryType::None { + return; + } + match (self.work, project) { + // A tool that holds what it made in a system of its own (XY Table To Point, in the + // one its coordinates are given in) keeps it there. + (Crs::LonLat, _) if ds.held_in != Crs::LonLat => {} + (Crs::LonLat, Some(p)) => { + if let Err(e) = ds.hold_as(p, Some(p)) { + // Its refusal starts with the layer's name, named once here. + let why = e.strip_prefix(&format!("{}: ", ds.name)).unwrap_or(&e); + kept.push(format!("{} is kept in longitude/latitude, not the project's {}: {why}", ds.name, p.label())); + } + } + (work, _) => ds.held_in = work, } }; match &mut result.output { - Output::Layer(ds) | Output::Update { dataset: ds, .. } => hold(ds), + Output::Layer(ds) => hold(ds), + // An update writes into a layer the map has, which keeps its own system. + Output::Update { dataset: ds, .. } if self.work != Crs::LonLat && ds.geometry_type != rustgis_data::GeometryType::None => { + ds.held_in = self.work + } Output::Layers(outputs) => { for o in outputs { if let rustgis_analysis::OutputLayer::Vector(ds) = o { @@ -1341,8 +1373,9 @@ impl MapInputs<'_> { } } } - Output::Selection { .. } | Output::Table(_) | Output::File { .. } => {} + Output::Update { .. } | Output::Selection { .. } | Output::Table(_) | Output::File { .. } => {} } + result.messages.extend(kept); } /// The flat map's projection, built on first use. @@ -1973,6 +2006,9 @@ impl Inputs for MapInputs<'_> { fn work_crs(&self) -> Crs { self.work } + fn project_crs(&self) -> Option { + self.snap.project + } fn selection(&self, layer: &str) -> &[usize] { let Some(l) = self.snap.map.layer_by_name(layer) else { return &[] }; // Loaded selections and environment extents are already rows of the dataset returned diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 26f72b0f8f..769d3acb1a 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -625,9 +625,10 @@ pub(crate) fn layer_work(s: &Session, p: &Value) -> Result { let gpkg = gpkg_table(p, &ext)?; let compatibility = ps(p, "crs").and_then(|text| asked.and_then(|crs| rustgis_data::raster::wkt::typed_crs_note(text, crs))); let (boxes, map) = (s.constructions.clone(), s.map().instance_id()); + let project = s.project.coordinate_system; Ok(Box::new(move || { let note = boxes.export_notes(map, &l)?; - let mut wrote = write_layer(&l, &path, asked, gpkg)?; + let mut wrote = write_layer(&l, &path, asked, project, gpkg)?; wrote.notes.extend(note); if let Some(note) = compatibility { wrote.notes.insert(0, format!("crs: {note}")); @@ -681,9 +682,9 @@ pub fn gpkg_dates_note(ds: &rustgis_data::Dataset, ext: &str, path: &str) -> Vec utc.into_iter().chain(fine).chain(text_in_dates_note(&ds.fields, &text_in_dates(ds.features.iter(), &ds.fields), path)).collect() } -/// Writes layer `l` to `path`, in `asked` or the system the format defaults to; a GeoPackage's -/// table goes where `gpkg` says. -fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: GpkgTable) -> Result { +/// Writes layer `l` to `path`, in `asked` or the system the format defaults to (the project's, +/// `project`, for a layer with none of its own); a GeoPackage's table goes where `gpkg` says. +fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: Option, gpkg: GpkgTable) -> Result { let ext = Path::new(&path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); // A layer read in place from the GeoPackage it goes into is read whole first: SQLite can't // write a file while the same export is reading it. @@ -708,8 +709,8 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk let unread = unreadable.rows; let ds = chunks.as_ref().map_or(whole.as_ref(), |(_, layer)| layer); // GeoJSON, KML, GPX and CSV are longitude/latitude (CSV takes another when asked); the others - // keep the layer's own system unless told another. - let crs = asked.unwrap_or_else(|| rustgis_data::io::default_export_crs(ds, &ext)); + // keep the layer's own system unless told another, or take the project's when it has none. + let crs = asked.unwrap_or_else(|| rustgis_data::io::default_export_crs_in(ds, &ext, project)); // Another body's layer projected onto another ellipsoid would be wrong data, not a wrong name. if let Some(e) = rustgis_data::export_error(ds, crs) { return Err(format!("{path}: {e}")); @@ -780,7 +781,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk let mut notes: rustgis_data::loss::Notes = rustgis_data::export_notes([(ds, extent)], path, crs).into(); coalesce_read_zm(&mut notes, path, ds, &unreadable); if asked.is_none() { - notes.extend(rustgis_data::io::default_export_note(ds, path)); + notes.extend(rustgis_data::io::default_export_note_in(ds, path, project)); } let csv_type = if csv_points { rustgis_data::GeometryType::Point } else { ds.geometry_type }; notes.extend(rustgis_data::io::csv_system_note(path, csv_type, crs)); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 3d4ae6a705..a015339022 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1703,7 +1703,7 @@ fn interpolate_work(s: &Session, p: &Value) -> Result { let given = p.get("crs").is_some_and(|v| !v.is_null() && v.as_str().is_none_or(|t| !t.trim().is_empty())); let (crs, crs_note) = match env.projected { Some(g) if !given => (g.crs, None), - _ => rustgis_analysis::raster_crs_in(ds, work, p, "Geostatistical Wizard")?, + _ => rustgis_analysis::raster_crs_in(ds, work, s.project.coordinate_system, p, "Geostatistical Wizard")?, }; let crs_note = rustgis_analysis::in_its_units(p, crs, crs_note, &Extent::EMPTY, &[], &["cellSize"]); let env_extent = env.extent; diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs index 5c57365031..19b34eefe5 100644 --- a/crates/engine/src/tests/project_crs.rs +++ b/crates/engine/src/tests/project_crs.rs @@ -409,3 +409,156 @@ fn a_raster_waiting_when_a_system_is_chosen_or_the_option_turned_off_gives_none_ assert_eq!(s.project.coordinate_system, None, "{settle}"); } } + +/// Points around Bern in longitude/latitude, with no system of their own (as a layer drawn in a +/// project without one is), and a number for interpolating. +fn bern_points(name: &str) -> rustgis_data::Dataset { + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell}; + let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + for i in 0..3 { + for j in 0..3 { + let at = Coord::new(7.43 + 0.01 * f64::from(i), 46.94 + 0.01 * f64::from(j)); + ds.push(Some(Geometry::Point(at)), vec![Cell::Float(f64::from(i * 3 + j))]); + } + } + assert_eq!((ds.coord_crs(), ds.crs), (Crs::LonLat, None)); + ds +} + +/// Runs `cmd` and gives back what it said. +fn said(s: &mut Session, cmd: &str, p: &Value) -> Vec { + let mark = s.notice_mark(); + s.run(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +#[test] +fn a_tool_output_made_in_longitude_latitude_is_held_in_the_project_system() { + let mut s = Session::new(Project::default()); + s.map_mut().add_dataset(bern_points("Wells")); + let buffer = |s: &mut Session, out: &str| { + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Wells", "distance": 50, "units": "Meters", "output": out}})).unwrap() + }; + buffer(&mut s, "Plain"); + let plain = s.map().layer_by_name("Plain").unwrap().dataset.clone(); + assert_eq!((plain.coord_crs(), plain.crs), (Crs::LonLat, None), "without one, as before"); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + buffer(&mut s, "Swiss"); + let swiss = &s.map().layer_by_name("Swiss").unwrap().dataset; + assert_eq!((swiss.coord_crs(), swiss.crs), (LV95, Some(LV95))); + // The same rings, converted: each vertex reads back where the lon/lat run put it (within a + // centimetre, the inverse's). + let back = swiss.in_lonlat().unwrap(); + for (a, b) in plain.features.iter().zip(&back.features) { + let (Some(rustgis_data::Geometry::Polygon(a)), Some(rustgis_data::Geometry::Polygon(b))) = (&a.geometry, &b.geometry) else { + panic!("not polygons") + }; + for (p, q) in a.iter().flatten().flatten().zip(b.iter().flatten().flatten()) { + assert!((p.x - q.x).abs() < 1e-7 && (p.y - q.y).abs() < 1e-7, "{p:?} {q:?}"); + } + } + let first = swiss.features[0].geometry.as_ref().unwrap().extent(); + assert!((first.min_x - 2_599_250.0).abs() < 1_000.0 && (first.min_y - 1_198_900.0).abs() < 1_000.0, "{first:?}"); +} + +#[test] +fn a_tool_working_in_a_layers_own_system_keeps_it_in_a_project_of_another() { + let mut s = Session::new(Project::default()); + let utm = Crs::Epsg(32632); + let mut wells = bern_points("Wells"); + wells.hold_as(utm, Some(utm)).unwrap(); + s.map_mut().add_dataset(wells); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Wells", "distance": 50, "units": "Meters", "output": "Out"}})).unwrap(); + let out = &s.map().layer_by_name("Out").unwrap().dataset; + assert_eq!(out.coord_crs(), utm, "made in UTM and kept there, as its input"); +} + +#[test] +fn a_tool_output_the_project_system_cant_hold_stays_in_longitude_latitude_said() { + use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; + let mut s = Session::new(Project::default()); + let mut ds = Dataset::new("Arctic", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(Coord::new(10.0, 88.0))), vec![]); + s.map_mut().add_dataset(ds); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:3857"})).unwrap(); + let out = said(&mut s, "gp.run", &json!({"tool": "featureToPoint", "params": {"input": "Arctic", "output": "Out"}})); + let l = &s.map().layer_by_name("Out").unwrap().dataset; + assert_eq!((l.coord_crs(), l.crs), (Crs::LonLat, None)); + assert!( + out.iter().any(|m| m + == "Out is kept in longitude/latitude, not the project's EPSG:3857: feature 1 has a place that can't be held in EPSG:3857"), + "{out:?}" + ); +} + +#[test] +fn a_grid_from_points_in_degrees_is_made_in_the_project_system() { + let mut s = Session::new(Project::default()); + s.map_mut().add_dataset(bern_points("Samples")); + let kde = json!({"tool": "kernelDensity", "params": {"input": "Samples", "radius": 500, "pixelSize": 50, "output": "Kde"}}); + // Without a system, Kernel Density asks for one; IDW makes its grid in degrees. + assert!(s.run("gp.run", &kde).unwrap_err().contains("has no coordinate system")); + s.run("gp.run", &json!({"tool": "idwInterpolation", "params": {"input": "Samples", "field": "v", "output": "Deg"}})).unwrap(); + assert_eq!(s.map().layer_by_name("Deg").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().crs, Crs::LonLat); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + let grid = |s: &Session, name: &str| s.map().layer_by_name(name).unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + let out = said(&mut s, "gp.run", &kde); + assert_eq!(grid(&s, "Kde").crs, LV95); + assert!( + out.iter().any(|m| m.contains("the project's coordinate system") && m.contains("'Samples' has no coordinate system")), + "{out:?}" + ); + for (tool, name) in [("idwInterpolation", "Idw"), ("kriging", "Krig")] { + let out = + said(&mut s, "gp.run", &json!({"tool": tool, "params": {"input": "Samples", "field": "v", "pixelSize": 100, "output": name}})); + let g = grid(&s, name); + assert_eq!(g.crs, LV95, "{tool}"); + assert!((g.transform.origin_x - 2_599_000.0).abs() < 2_000.0, "{tool}: {:?}", g.transform); + assert!(out.iter().any(|m| m.contains("the project's coordinate system")), "{tool}: {out:?}"); + // Asked for degrees by name, it is made in degrees. + let deg = format!("{name}Deg"); + s.run("gp.run", &json!({"tool": tool, "params": {"input": "Samples", "field": "v", "crs": "EPSG:4326", "output": deg}})).unwrap(); + assert_eq!(grid(&s, °).crs, Crs::LonLat, "{tool}"); + } + // The Geostatistical Wizard too, when Environments sets no system. + let out = said(&mut s, "analysis.interpolate", &json!({"layer": "Samples", "field": "v", "cellSize": 100, "name": "Surface"})); + assert_eq!(grid(&s, "Surface").crs, LV95); + assert!(out.iter().any(|m| m.contains("the project's coordinate system")), "{out:?}"); +} + +#[test] +fn an_export_of_a_layer_with_no_system_takes_the_projects() { + let dir = std::env::temp_dir().join(format!("rustgis-project-crs-{}-export", 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.map_mut().add_dataset(bern_points("Wells")); + let export = |s: &mut Session, file: &str| { + let path = dir.join(file); + let out = said(s, "share.exportLayer", &json!({"layer": "Wells", "path": path})).join("\n"); + (path, out) + }; + let read = |path: &std::path::Path| rustgis_data::io::read_path(path).unwrap().0; + let (plain, out) = export(&mut s, "plain.gpkg"); + assert_ne!(read(&plain).crs, Some(LV95), "without one, in WGS 84 as before"); + assert!(!out.contains("project's"), "{out}"); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:2056"})).unwrap(); + let (swiss, out) = export(&mut s, "swiss.gpkg"); + let back = read(&swiss); + assert_eq!(back.crs, Some(LV95)); + let Some(rustgis_data::Geometry::Point(c)) = back.in_lonlat().unwrap().features[0].geometry.clone() else { panic!("no point") }; + assert!((c.x - 7.43).abs() < 1e-7 && (c.y - 46.94).abs() < 1e-7, "{c:?}"); + assert!(out.contains("written in EPSG:2056, the project's coordinate system, as Wells has none of its own"), "{out}"); + // GeoJSON is longitude/latitude whatever the project's system, and says nothing of it. + let (json_path, out) = export(&mut s, "wells.geojson"); + assert!(!out.contains("project's"), "{out}"); + assert_eq!(read(&json_path).coord_crs(), Crs::LonLat); + // A layer with a system of its own keeps it. + let id = s.map().layer_by_name("Wells").unwrap().id; + s.map_mut().layer_mut(id).unwrap().dataset.crs = Some(Crs::LonLat); + let (own, out) = export(&mut s, "own.gpkg"); + assert_ne!(read(&own).crs, Some(LV95)); + assert!(!out.contains("project's"), "{out}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 21dbef2895..3f064d4514 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -16,7 +16,9 @@ pub struct Pick { } /// A layer's systems: the one it holds its coordinates in, and the one it was read in. -type LayerSystems = (rustgis_engine::data::raster::Crs, Option); +/// The systems a layer holds its coordinates in and was read in, and the project's. +type LayerSystems = + (rustgis_engine::data::raster::Crs, Option, Option); /// The Workflows pane's inputs and results. #[derive(Default)] @@ -73,10 +75,11 @@ pub struct Workflow { /// The system the Wizard's surface was last to be made in (its own, else the environment's): /// when it changes, the cell size typed for it is cleared. pub wizard_system: String, - /// The systems the Wizard's layer holds its coordinates in and was read in, and the one its - /// surface is made in from them (the held one when projected, + /// The systems the Wizard's layer holds its coordinates in and was read in, and the project's, + /// and the one its surface is made in from them (the held one when projected, /// [`rustgis_engine::analysis::works_in`], else the read-in one, - /// [`rustgis_engine::analysis::layer_raster_crs`]), kept so it is worked out once. + /// [`rustgis_engine::analysis::layer_raster_crs`], else the project's for a layer in degrees), + /// kept so it is worked out once. pub layer_system: Option<(LayerSystems, Option)>, /// The coordinate system typed for a new ortho or reality workspace; empty: the images' /// projected system, else degrees. @@ -952,16 +955,22 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { combo(ui, "wf_i", "Layer", &mut app.workflow.layer, &points); combo(ui, "wf_if", "Field", &mut app.workflow.field, &numeric); // Empty: the environment's system, else the projected one the layer holds its - // coordinates in, else the one it was read in, else degrees; the hint shows which. - let systems = app.session.map().layer_by_name(&app.workflow.layer).map(|l| (l.dataset.coord_crs(), l.dataset.crs)); + // coordinates in, else the one it was read in, else the project's, else degrees; the + // hint shows which. + let project = app.session.project.coordinate_system; + let systems = app.session.map().layer_by_name(&app.workflow.layer).map(|l| (l.dataset.coord_crs(), l.dataset.crs, project)); // The run's choice; kept for the layer's systems, so a projection isn't built every // frame. let layer_crs = match (systems, app.workflow.layer_system) { (Some(c), Some((seen, chosen))) if seen == c => chosen, - (Some((held, read_in)), _) => { + (Some((held, read_in, project)), _) => { + use rustgis_engine::analysis::layer_raster_crs; let from = if rustgis_engine::analysis::works_in(held) { Some(held) } else { read_in }; - let chosen = rustgis_engine::analysis::layer_raster_crs(from).and_then(Result::ok); - app.workflow.layer_system = Some(((held, read_in), chosen)); + let chosen = match layer_raster_crs(from) { + Some(c) => c.ok(), + None => layer_raster_crs(project).and_then(Result::ok), + }; + app.workflow.layer_system = Some(((held, read_in, project), chosen)); chosen } (None, _) => None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ade5aebcfe..cb9e199feb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5291,7 +5291,7 @@ impl RustGisApp { let layer_name = l.name.clone(); // In the layer's own coordinate system, as share.exportLayer writes a file. use rustgis_engine::data::io; - let crs = io::default_export_crs(&ds, &ext); + let crs = io::default_export_crs_in(&ds, &ext, self.session.project.coordinate_system); let written = io::write_bytes_in(&ds, &ext, crs).map_err(|e| e.to_string()); let (bytes, left_out) = match written { Ok(w) => w, @@ -5306,6 +5306,8 @@ impl RustGisApp { let mut notes: rustgis_engine::data::loss::Notes = rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs).into(); rustgis_engine::cmd::share::coalesce_read_zm(&mut notes, &name, &ds, &lost); + // Which system it is written in, where that isn't the layer's own, as share.exportLayer says. + notes.extend(io::default_export_note_in(&ds, &name, self.session.project.coordinate_system)); let mut dbf_notes = rustgis_engine::data::loss::Notes::new(); if ext == "zip" { dbf_notes.extend(io::shapefile_names_note(&ds.fields, &name)); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 40db13de1e..1b0b5dcd3a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -528,7 +528,7 @@ are excluded and reported in the tool messages; for multipoint features, each co receives the feature's weight, a part with a coordinate missing or infinite is left out and counted, and a feature with no finite part is skipped). Calculations are performed in the linear units of a projected coordinate system (defaults to the projected system the layer is held in, or else was read in; if the input layer lacks a -coordinate system or is in degrees, or to project into a specific system, supply a projected system via `crs`, +coordinate system or is in degrees, the project's projected system, said; without one, or to project into a specific system, supply a projected system via `crs`, e.g. `EPSG:32618`). Geocentric systems such as `EPSG:4978` (X, Y and Z from the Earth's centre) are refused, whether supplied via `crs` or inherited from the layer: their three axes do not define the two-dimensional projected plane Kernel Density needs. @@ -740,8 +740,10 @@ IDW Interpolation and Ordinary Kriging make their raster in the projected coordi as `crs` (such as `EPSG:32616` for UTM zone 16N, or a State Plane code), and then take the extent, pixel size and Kriging's `range` in its units, usually metres or feet. Without `crs` they use the projected system the layer is held in (or else was read in), as Kernel Density -does without a note, and say so, naming it; a layer read in longitude and latitude gives a -raster in degrees, with all three in degrees. +does without a note, and say so, naming it; a layer read in longitude and latitude, or with no +system, gives a raster in the project's coordinate system when it has a projected one (said, as +the Geostatistical Wizard does when Environments sets none), else in degrees, with all three in +degrees. `crs: "EPSG:4326"` makes it in degrees whatever the layer was read in, as these tools always did before `crs` was there; so does a layer read in a system that can't hold a raster's cells (a geocentric one) or that this version can't project to, with a notice saying which. A script diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 36e46a8ea8..ddbd12dbaa 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -858,6 +858,16 @@ stored in its units. Maps and layers already in the project keep their own syste 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. +Tools follow it too. A tool that works in longitude/latitude (on a layer in degrees, or one that +always does) gives its new layers in the project's system, converted, and with it as their own, so +they export in it; one with a place the system can't hold (beyond 85.05° in Web Mercator, say) +stays in longitude/latitude, and the tool says so. A tool that works in its first layer's own +projected system keeps its output there. IDW, Kriging, Kernel Density and the Geostatistical Wizard +make a raster from a layer in degrees, or with no system, in the project's when it is projected, +and say so (`crs: "EPSG:4326"` still makes it in degrees). An export of a layer with no system of +its own (one drawn in longitude/latitude, say) is written in the project's system where the format +can hold one (GeoPackage, Shapefile, FlatGeobuf, GeoParquet), and says so. + **While it has none, take it from the first layer added** gives the project the system of the next 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 diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index b088ef38d8..58ce91d952 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -65,7 +65,9 @@ goes below 0). Neither has a CRS; STL stores them as unitless 32-bit floats, so **Data › Export** (or `share.exportLayer`, **Export Features**) writes a layer to GeoJSON, CSV, GeoPackage, GeoParquet, Shapefile (including a zip), FlatGeobuf, KML, KMZ or GPX (see [Writing](data-formats.md#writing)). GeoPackage, Shapefile and FlatGeobuf use the layer's source -coordinate system by default; the `crs` parameter chooses another. Export Features writes the +coordinate system by default, and the project's (see +[the project's coordinate system](maps.md#the-projects-coordinate-system)) for a layer with none of +its own, which the export says; the `crs` parameter chooses another. Export Features writes the features the layer's definition query keeps and reports how many it leaves out. For a streamed layer, it applies the query to the whole source, including features outside the current view. The web app downloads every format but GeoPackage and FlatGeobuf. `share.exportTable` exports a From eece7d24ae1b781937d7e122988cba52b863c4f3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 13:14:09 +0100 Subject: [PATCH 3/4] Review: Cancel during an output's conversion stops the run; one note for layers kept in longitude/latitude; geocentric project systems left out; export default and its note worked out once; help texts --- crates/analysis/src/tools.rs | 12 ++-- crates/data/src/io.rs | 85 ++++++++++++++------------ crates/engine/src/cmd/gp.rs | 52 +++++++++++----- crates/engine/src/cmd/share.rs | 9 +-- crates/engine/src/tests/project_crs.rs | 17 ++++++ crates/ui-egui/src/analysispane.rs | 1 - crates/ui-egui/src/lib.rs | 4 +- docs/user-guide/analysis.md | 2 +- docs/user-guide/maps.md | 3 +- docs/user-guide/sharing.md | 2 +- 10 files changed, 118 insertions(+), 69 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index a8fbe74c19..a7d73e7ec7 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -901,7 +901,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Text, required: false, default: "", - help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.", + help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the projected one the layer is held in, or else was read in, else the project's projected one, else degrees; EPSG:4326 for degrees.", }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, ], @@ -1067,7 +1067,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Text, required: false, default: "", - help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.", + help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the projected one the layer is held in, or else was read in, else the project's projected one, else degrees; EPSG:4326 for degrees.", }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, ], @@ -1317,7 +1317,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Text, required: false, default: "", - help: "Projected coordinate system (e.g. EPSG:32618); defaults to the projected system the layer is held in, or else was read in; required when the layer has none or is in degrees.", + help: "Projected coordinate system (e.g. EPSG:32618); defaults to the projected system the layer is held in, or else was read in, else the project's projected system; required when none of these is set.", }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output raster layer name." }, ], @@ -5149,7 +5149,7 @@ pub fn raster_crs_in(ds: &Dataset, work: Crs, project: Option, p: &Json, to } if let Some(c) = project_raster_crs(ds.crs, project, p) { let note = format!( - "{tool}: made in {}, the project's coordinate system, with its units for the extent and sizes, as {} {}; set crs to EPSG:4326 to make it in degrees", + "{tool}: made in {}, the project's coordinate system, with its units for the extent and sizes, as '{}' {}; set crs to EPSG:4326 to make it in degrees", c.label(), ds.name, if ds.crs.is_some() { "is in degrees" } else { "has no coordinate system" }, @@ -5164,7 +5164,9 @@ pub fn raster_crs_in(ds: &Dataset, work: Crs, project: Option, p: &Json, to /// system this version can project to. fn project_raster_crs(layer_crs: Option, project: Option, p: &Json) -> Option { let unnamed = p.get("crs").is_none_or(|v| v.is_null() || v.as_str().is_some_and(|t| t.trim().is_empty())); - (unnamed && layer_raster_crs(layer_crs).is_none()).then_some(())?; + if !unnamed || layer_raster_crs(layer_crs).is_some() { + return None; + } layer_raster_crs(project)?.ok() } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index ec7b30816d..291084107d 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -619,58 +619,67 @@ pub fn csv_system_note(path: &str, geometry_type: GeometryType, crs: Crs) -> Opt /// `.prj`; one WKT can't describe goes into a Shapefile (without a `.prj`, said) and not into the /// others ([`default_export_note`] says which system is written instead). pub fn default_export_crs(ds: &Dataset, ext: &str) -> Crs { - default_export_crs_in(ds, ext, None) -} - -/// [`default_export_crs`] in a project with a coordinate system of its own (`project`, #2032 C3a): -/// a dataset with no system of its own is written in the project's, where the format can say it. -pub fn default_export_crs_in(ds: &Dataset, ext: &str, project: Option) -> Crs { let ext = ext.to_ascii_lowercase(); - let fits = |c: &Crs| PROJECTED_FORMATS.contains(&ext.as_str()) && check_projected(&ext, *c).is_ok(); - match ds.crs { - Some(own) => Some(own).filter(fits), - None => project.filter(fits), - } - .unwrap_or(Crs::LonLat) + ds.crs.filter(|&c| PROJECTED_FORMATS.contains(&ext.as_str()) && check_projected(&ext, c).is_ok()).unwrap_or(Crs::LonLat) } /// What is said when an export to `path` is written in WGS 84 where the layer has a system of /// its own that the format can't hold ([`default_export_crs`]); `None` when it keeps its system /// or has none to keep. pub fn default_export_note(ds: &Dataset, path: &str) -> Option { - default_export_note_in(ds, path, None) + let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let own = ds.crs.filter(|&c| c != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()))?; + (default_export_crs(ds, &ext) == Crs::LonLat).then(|| { + format!( + "{path}: the coordinate system of {} ({}) {}, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another", + ds.name, + own.label(), + unwritable(&ext, own) + ) + }) } -/// [`default_export_note`] in a project with a coordinate system of its own -/// ([`default_export_crs_in`]): also said when a dataset with none of its own is written in the -/// project's, or in WGS 84 as the format can't hold the project's. -pub fn default_export_note_in(ds: &Dataset, path: &str, project: Option) -> Option { - let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); - let (own, whose) = match (ds.crs, project) { - (Some(own), _) => (own, format!("of {}", ds.name)), - (None, Some(p)) => (p, format!("of the project, which {} takes as it has none of its own,", ds.name)), - (None, None) => return None, - }; - if own == Crs::LonLat || !PROJECTED_FORMATS.contains(&ext.as_str()) { - return None; - } - if default_export_crs_in(ds, &ext, project) != Crs::LonLat { - return ds - .crs - .is_none() - .then(|| format!("{path}: written in {}, the project's coordinate system, as {} has none of its own", own.label(), ds.name)); - } - let why = if !matches!(ext.as_str(), "parquet" | "geoparquet") { +/// Why a system can't be written to a file with extension `ext` ([`check_projected`]). +fn unwritable(ext: &str, crs: Crs) -> &'static str { + if !matches!(ext, "parquet" | "geoparquet") { "has no EPSG code and no WKT definition RustGIS can write" - } else if own.epsg() == 0 { + } else if crs.epsg() == 0 { "has no EPSG code" } else { "has no PROJJSON definition RustGIS can write" + } +} + +/// The system an export to `path` is written in when none is asked for, and what is said of it, +/// in a project whose coordinate system is `project` (#2032 C3a): as [`default_export_crs`] and +/// [`default_export_note`] for a dataset with a system of its own, or in a project without one. A +/// dataset with none of its own, in longitude/latitude, is written in the project's where the +/// format can say it, and that is said; in WGS 84, said, when the format can't hold that system. +/// Places that system can't hold are written as any export into it writes them (at 85.05° in Web +/// Mercator, said). +pub fn default_export_in(ds: &Dataset, path: &str, project: Option) -> (Crs, Option) { + let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let project = project.filter(|p| { + ds.crs.is_none() + && ds.coord_crs() == Crs::LonLat + && *p != Crs::LonLat + && !p.is_geocentric() + && PROJECTED_FORMATS.contains(&ext.as_str()) + }); + let Some(p) = project else { return (default_export_crs(ds, &ext), default_export_note(ds, path)) }; + let in_wgs84 = |why: String| { + ( + Crs::LonLat, + Some(format!( + "{path}: written in WGS 84 (EPSG:4326), not the project's coordinate system ({}), as {why}; give a \"crs\" to write another", + p.label() + )), + ) }; - Some(format!( - "{path}: the coordinate system {whose} ({}) {why}, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another", - own.label() - )) + if check_projected(&ext, p).is_err() { + return in_wgs84(format!("that {}", unwritable(&ext, p))); + } + (p, Some(format!("{path}: written in {}, the project's coordinate system, as {} has none of its own", p.label(), ds.name))) } /// The dataset in `crs`'s coordinates, from the system it holds them in ([`Dataset::coord_crs`]), diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 3da2741ada..d780b22ded 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -721,10 +721,12 @@ impl ToolRun { }; let mut result = pin.run(&inputs, ¶ms, control, &|| continuation.check()); if let Ok(r) = &mut result { - inputs.hold_results(r); r.messages.extend(inputs.messages.iter().cloned()); r.losses.extend(inputs.losses.iter().cloned()); } + if let Err(e) = result.as_mut().map_or(Ok(()), |r| inputs.hold_results(r)) { + result = Err(e); + } ToolDone { inputs: Vec::new(), result, full_ids: full_ids(&inputs.loaded) } }) })) @@ -1336,32 +1338,41 @@ impl MapInputs<'_> { /// (#2032 C3a): they are converted into it and hold it as theirs (`crs`), as a layer drawn in /// the project is; one with a place it can't hold stays in longitude/latitude, said. Tables /// have no coordinates to hold. - fn hold_results(&self, result: &mut rustgis_analysis::ToolResult) { - let project = self.snap.project.filter(|c| *c != Crs::LonLat); + fn hold_results(&self, result: &mut rustgis_analysis::ToolResult) -> Result<(), String> { + // A geocentric system holds no map coordinates: outputs stay in longitude/latitude then. + let project = self.snap.project.filter(|c| *c != Crs::LonLat && !c.is_geocentric()); if self.work == Crs::LonLat && project.is_none() { - return; + return Ok(()); } - let mut kept = Vec::new(); - let mut hold = |ds: &mut Dataset| { + // The layers kept in longitude/latitude, and why the first was. + let (mut kept, mut why) = (0usize, None); + let mut hold = |ds: &mut Dataset| -> Result<(), String> { if ds.geometry_type == rustgis_data::GeometryType::None { - return; + return Ok(()); } match (self.work, project) { // A tool that holds what it made in a system of its own (XY Table To Point, in the // one its coordinates are given in) keeps it there. (Crs::LonLat, _) if ds.held_in != Crs::LonLat => {} - (Crs::LonLat, Some(p)) => { - if let Err(e) = ds.hold_as(p, Some(p)) { + (Crs::LonLat, Some(p)) => match ds.hold_as(p, Some(p)) { + // A Cancel stops the run, which adds nothing. + Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => { + return Err(e); + } + Err(e) => { + kept += 1; // Its refusal starts with the layer's name, named once here. - let why = e.strip_prefix(&format!("{}: ", ds.name)).unwrap_or(&e); - kept.push(format!("{} is kept in longitude/latitude, not the project's {}: {why}", ds.name, p.label())); + let reason = e.strip_prefix(&format!("{}: ", ds.name)).unwrap_or(&e).to_string(); + why.get_or_insert((ds.name.clone(), reason)); } - } + Ok(()) => {} + }, (work, _) => ds.held_in = work, } + Ok(()) }; match &mut result.output { - Output::Layer(ds) => hold(ds), + Output::Layer(ds) => hold(ds)?, // An update writes into a layer the map has, which keeps its own system. Output::Update { dataset: ds, .. } if self.work != Crs::LonLat && ds.geometry_type != rustgis_data::GeometryType::None => { ds.held_in = self.work @@ -1369,13 +1380,20 @@ impl MapInputs<'_> { Output::Layers(outputs) => { for o in outputs { if let rustgis_analysis::OutputLayer::Vector(ds) = o { - hold(ds); + hold(ds)?; } } } Output::Update { .. } | Output::Selection { .. } | Output::Table(_) | Output::File { .. } => {} } - result.messages.extend(kept); + if let (Some((name, reason)), Some(p)) = (why, project) { + let others = match kept { + 1 => String::new(), + n => format!(" (and {} more layer{})", n - 1, if n == 2 { "" } else { "s" }), + }; + result.messages.push(format!("{name}{others} is kept in longitude/latitude, not the project's {}: {reason}", p.label())); + } + Ok(()) } /// The flat map's projection, built on first use. @@ -3152,10 +3170,12 @@ pub(crate) fn execute( pin.run(&inputs, params, control, &|| continuation.check()) }; if let Ok(result) = &mut res { - inputs.hold_results(result); result.messages.extend(inputs.messages.iter().cloned()); result.losses.extend(inputs.losses.iter().cloned()); } + if let Err(e) = res.as_mut().map_or(Ok(()), |r| inputs.hold_results(r)) { + res = Err(e); + } let ids = full_ids(&inputs.loaded); #[cfg(not(target_arch = "wasm32"))] let view = inputs.view.get().copied(); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 769d3acb1a..2fd6565853 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -710,7 +710,10 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: let ds = chunks.as_ref().map_or(whole.as_ref(), |(_, layer)| layer); // GeoJSON, KML, GPX and CSV are longitude/latitude (CSV takes another when asked); the others // keep the layer's own system unless told another, or take the project's when it has none. - let crs = asked.unwrap_or_else(|| rustgis_data::io::default_export_crs_in(ds, &ext, project)); + let (crs, default_note) = match asked { + Some(c) => (c, None), + None => rustgis_data::io::default_export_in(ds, path, project), + }; // Another body's layer projected onto another ellipsoid would be wrong data, not a wrong name. if let Some(e) = rustgis_data::export_error(ds, crs) { return Err(format!("{path}: {e}")); @@ -780,9 +783,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: let extent = if chunks.is_some() { l.extent() } else { ds.lonlat_extent() }; let mut notes: rustgis_data::loss::Notes = rustgis_data::export_notes([(ds, extent)], path, crs).into(); coalesce_read_zm(&mut notes, path, ds, &unreadable); - if asked.is_none() { - notes.extend(rustgis_data::io::default_export_note_in(ds, path, project)); - } + notes.extend(default_note); let csv_type = if csv_points { rustgis_data::GeometryType::Point } else { ds.geometry_type }; notes.extend(rustgis_data::io::csv_system_note(path, csv_type, crs)); notes.extend(moved); diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs index 19b34eefe5..18d826e384 100644 --- a/crates/engine/src/tests/project_crs.rs +++ b/crates/engine/src/tests/project_crs.rs @@ -485,6 +485,13 @@ fn a_tool_output_the_project_system_cant_hold_stays_in_longitude_latitude_said() let out = said(&mut s, "gp.run", &json!({"tool": "featureToPoint", "params": {"input": "Arctic", "output": "Out"}})); let l = &s.map().layer_by_name("Out").unwrap().dataset; assert_eq!((l.coord_crs(), l.crs), (Crs::LonLat, None)); + // Exported, it is written in the project's system as an export into it is: at 85.05°, said. + let path = std::env::temp_dir().join(format!("rustgis-project-crs-{}-arctic.gpkg", std::process::id())); + let note = said(&mut s, "share.exportLayer", &json!({"layer": "Arctic", "path": path})); + assert_eq!(rustgis_data::io::read_path(&path).unwrap().0.crs, Some(Crs::WebMercator)); + assert!(note.iter().any(|m| m.contains("written at 85.05°, where Web Mercator ends")), "{note:?}"); + assert!(note.iter().any(|m| m.contains("written in EPSG:3857, the project's coordinate system")), "{note:?}"); + let _ = std::fs::remove_file(&path); assert!( out.iter().any(|m| m == "Out is kept in longitude/latitude, not the project's EPSG:3857: feature 1 has a place that can't be held in EPSG:3857"), @@ -492,6 +499,16 @@ fn a_tool_output_the_project_system_cant_hold_stays_in_longitude_latitude_said() ); } +#[test] +fn a_geocentric_project_system_leaves_outputs_in_longitude_latitude() { + let mut s = Session::new(Project::default()); + s.map_mut().add_dataset(bern_points("Wells")); + s.run("project.coordinateSystem", &json!({"crs": "EPSG:4978"})).unwrap(); + let out = said(&mut s, "gp.run", &json!({"tool": "featureToPoint", "params": {"input": "Wells", "output": "Out"}})); + assert_eq!(s.map().layer_by_name("Out").unwrap().dataset.coord_crs(), Crs::LonLat); + assert!(!out.iter().any(|m| m.contains("project's")), "{out:?}"); +} + #[test] fn a_grid_from_points_in_degrees_is_made_in_the_project_system() { let mut s = Session::new(Project::default()); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 3f064d4514..4d21922cc7 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -15,7 +15,6 @@ pub struct Pick { pub points: Vec, } -/// A layer's systems: the one it holds its coordinates in, and the one it was read in. /// The systems a layer holds its coordinates in and was read in, and the project's. type LayerSystems = (rustgis_engine::data::raster::Crs, Option, Option); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cb9e199feb..9788bd8890 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5291,7 +5291,7 @@ impl RustGisApp { let layer_name = l.name.clone(); // In the layer's own coordinate system, as share.exportLayer writes a file. use rustgis_engine::data::io; - let crs = io::default_export_crs_in(&ds, &ext, self.session.project.coordinate_system); + let (crs, default_note) = io::default_export_in(&ds, &name, self.session.project.coordinate_system); let written = io::write_bytes_in(&ds, &ext, crs).map_err(|e| e.to_string()); let (bytes, left_out) = match written { Ok(w) => w, @@ -5307,7 +5307,7 @@ impl RustGisApp { rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs).into(); rustgis_engine::cmd::share::coalesce_read_zm(&mut notes, &name, &ds, &lost); // Which system it is written in, where that isn't the layer's own, as share.exportLayer says. - notes.extend(io::default_export_note_in(&ds, &name, self.session.project.coordinate_system)); + notes.extend(default_note); let mut dbf_notes = rustgis_engine::data::loss::Notes::new(); if ext == "zip" { dbf_notes.extend(io::shapefile_names_note(&ds.fields, &name)); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1b0b5dcd3a..ac2b054e44 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -528,7 +528,7 @@ are excluded and reported in the tool messages; for multipoint features, each co receives the feature's weight, a part with a coordinate missing or infinite is left out and counted, and a feature with no finite part is skipped). Calculations are performed in the linear units of a projected coordinate system (defaults to the projected system the layer is held in, or else was read in; if the input layer lacks a -coordinate system or is in degrees, the project's projected system, said; without one, or to project into a specific system, supply a projected system via `crs`, +coordinate system or is in degrees, the project's projected system, which the tool says it used; when the project has none, or to project into a specific system, supply a projected system via `crs`, e.g. `EPSG:32618`). Geocentric systems such as `EPSG:4978` (X, Y and Z from the Earth's centre) are refused, whether supplied via `crs` or inherited from the layer: their three axes do not define the two-dimensional projected plane Kernel Density needs. diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index ddbd12dbaa..f1b4b38808 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -866,7 +866,8 @@ projected system keeps its output there. IDW, Kriging, Kernel Density and the Ge make a raster from a layer in degrees, or with no system, in the project's when it is projected, and say so (`crs: "EPSG:4326"` still makes it in degrees). An export of a layer with no system of its own (one drawn in longitude/latitude, say) is written in the project's system where the format -can hold one (GeoPackage, Shapefile, FlatGeobuf, GeoParquet), and says so. +can hold one (GeoPackage, Shapefile, FlatGeobuf, GeoParquet), and says so. A geocentric project system holds no map +coordinates, so outputs and exports stay in longitude/latitude in it. **While it has none, take it from the first layer added** gives the project the system of the next layer added from data (**Home › Add**: a file, a URL, a service, a database; or a map imported, an diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 58ce91d952..c1cf830685 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -67,7 +67,7 @@ GeoPackage, GeoParquet, Shapefile (including a zip), FlatGeobuf, KML, KMZ or GPX [Writing](data-formats.md#writing)). GeoPackage, Shapefile and FlatGeobuf use the layer's source coordinate system by default, and the project's (see [the project's coordinate system](maps.md#the-projects-coordinate-system)) for a layer with none of -its own, which the export says; the `crs` parameter chooses another. Export Features writes the +its own, which the export says (GeoParquet too); the `crs` parameter chooses another. Export Features writes the features the layer's definition query keeps and reports how many it leaves out. For a streamed layer, it applies the query to the whole source, including features outside the current view. The web app downloads every format but GeoPackage and FlatGeobuf. `share.exportTable` exports a From 66fc2192feaf4cc5569b27f71b701e2ece58e6d9 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 13:58:29 +0100 Subject: [PATCH 4/4] Review: holding keeps only the converted geometry beside the rows, not a copy of them; the conversion looks at the run's Cancel on the session path too; tests for both; doc sentence; name counted as a word --- crates/data/src/lib.rs | 76 +++++++++++++++++++++----- crates/engine/src/cmd/gp.rs | 8 ++- crates/engine/src/tests/held_layers.rs | 3 +- crates/engine/src/tests/project_crs.rs | 31 +++++++++++ docs/user-guide/analysis.md | 7 ++- 5 files changed, 105 insertions(+), 20 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index ad59d7b853..acb63a07ce 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -502,23 +502,33 @@ impl Dataset { let to = self.held_in.to(crs)?; if !to.is_identity() { let lonlat = self.lonlat_conversion()?; - // Before the rows are copied (by the first change), which a cancelled command needn't. - stop_when_asked(0)?; - let mut features = self.features.clone(); - for (i, f) in features.iter_mut().enumerate() { - stop_when_asked(i)?; - if let Some(g) = &f.geometry { - let mut past = false; - if crs == raster::Crs::WebMercator { - g.for_each_coord(|c| past |= c.is_finite() && lonlat.point(c).is_some_and(|l| l.y.abs() > rustgis_geom::MAX_LAT)); - } - let held = (!past).then(|| convert_keeping_missing(&to, g, &HeldPlaces::default())).flatten(); - f.geometry = Some( - held.ok_or_else(|| format!("{}: feature {} has a place that can't be held in {}", self.name, f.id, crs.label()))?, - ); + let past = |g: &Geometry| { + let mut past = false; + if crs == raster::Crs::WebMercator { + g.for_each_coord(|c| past |= c.is_finite() && lonlat.point(c).is_some_and(|l| l.y.abs() > rustgis_geom::MAX_LAT)); } + past + }; + let held = |g: &Geometry| (!past(g)).then(|| convert_keeping_missing(&to, g, &HeldPlaces::default())).flatten(); + // Each place is converted once, and what goes in is what was checked (a second pass + // could convert otherwise, as grids arriving meanwhile change the operations): the + // converted geometries are kept beside the rows, then put in their place, so a refusal + // or a Cancel changes nothing. Only geometry is kept twice meanwhile, never the + // attributes, and rows no one else holds aren't copied. + let mut converted = Vec::with_capacity(self.features.len()); + for (i, f) in self.features.iter().enumerate() { + stop_when_asked(i)?; + converted.push(match &f.geometry { + Some(g) => Some( + held(g) + .ok_or_else(|| format!("{}: feature {} has a place that can't be held in {}", self.name, f.id, crs.label()))?, + ), + None => None, + }); + } + for (f, g) in self.features.iter_mut().zip(converted) { + f.geometry = g; } - self.features = features; } self.held_in = crs; Ok(()) @@ -1468,6 +1478,42 @@ mod tests { assert_eq!((polar.coord_crs(), polar.crs), (raster::Crs::LonLat, None)); } + /// Holding converts the rows where they are, with no copy of rows no one else holds; a Cancel, + /// or a place the system can't hold, found among the last rows changes none of them. + #[test] + fn holding_converts_in_place_and_a_cancel_or_refusal_changes_nothing() { + use crate::progress::tests::Counted; + let utm = raster::Crs::Epsg(32632); + let made = |last_lat: f64| { + let mut ds = Dataset::new("made", GeometryType::Point, vec![]); + for i in 0..600 { + let lat = if i == 599 { last_lat } else { 48.0 }; + ds.push(Some(Geometry::Point(Coord::new(11.5, lat))), vec![]); + } + ds + }; + let mut ds = made(48.0); + let (held, copied) = rows_copy::with(Box::new(|| {}), || ds.hold_in(utm)); + held.unwrap(); + assert!(!copied && ds.coord_crs() == utm, "converted where the rows are"); + let Some(Geometry::Point(c)) = ds.features[0].geometry else { panic!("no point") }; + let expected = raster::Crs::LonLat.to(utm).unwrap().point(Coord::new(11.5, 48.0)).unwrap(); + assert_eq!((c.x.to_bits(), c.y.to_bits()), (expected.x.to_bits(), expected.y.to_bits())); + // Cancelled at the third check (row 512), after the first rows were looked at. + let mut ds = made(48.0); + let before = ds.features.clone(); + let probe = std::sync::Arc::new(Counted { after_checks: Some(2), ..Default::default() }); + { + let _g = crate::progress::install(Some(probe)); + assert_eq!(ds.hold_in(utm), Err(DataError::Cancelled.to_string())); + } + assert!(ds.features.shares(&before) && ds.coord_crs() == raster::Crs::LonLat); + let mut polar = made(89.0); + let before = polar.features.clone(); + assert!(polar.hold_in(raster::Crs::WebMercator).unwrap_err().contains("feature 600")); + assert!(polar.features.shares(&before) && polar.coord_crs() == raster::Crs::LonLat); + } + /// A dataset held in another system converts into it, and back, at the same places; one /// reaching past where Web Mercator ends, or a window onto a source read in place, is refused /// and left as it was. diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index d780b22ded..15c680566d 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3173,7 +3173,13 @@ pub(crate) fn execute( result.messages.extend(inputs.messages.iter().cloned()); result.losses.extend(inputs.losses.iter().cloned()); } - if let Err(e) = res.as_mut().map_or(Ok(()), |r| inputs.hold_results(r)) { + // The conversion stays under this run's Cancel, as in `ToolRun::run`: the tool's own + // probe ended with it. + let held = { + let _probe = rustgis_analysis::control::install_progress(Some(control.clone())); + res.as_mut().map_or(Ok(()), |r| inputs.hold_results(r)) + }; + if let Err(e) = held { res = Err(e); } let ids = full_ids(&inputs.loaded); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 477361bc80..7d14918f81 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2755,7 +2755,8 @@ fn a_covering_layers_conversion_is_said() { let fell_back = said(box_of(0.0, -90.0, 10.0, -89.0), Crs::LonLat, Crs::Epsg(3413)); assert!(fell_back.len() == 1 && fell_back[0].starts_with("1 topology rule(s) checked in longitude/latitude"), "{fell_back:?}"); assert_eq!( - fell_back[0].matches("Cover'").count() + fell_back[0].matches("Cover:").count(), + // The layer's name as a word ("Covered By" names the rule). + fell_back[0].split(|c: char| !c.is_alphanumeric()).filter(|w| *w == "Cover").count(), 1, "the covering layer named once: {fell_back:?}" ); diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs index 18d826e384..0b50b38d5b 100644 --- a/crates/engine/src/tests/project_crs.rs +++ b/crates/engine/src/tests/project_crs.rs @@ -579,3 +579,34 @@ fn an_export_of_a_layer_with_no_system_takes_the_projects() { assert!(!out.contains("project's"), "{out}"); let _ = std::fs::remove_dir_all(&dir); } + +/// A Cancel while a tool's output is converted into the project's system stops the run, which +/// adds nothing: stopped at each of its looks in turn, the last of which is the conversion's. +#[test] +fn a_cancel_while_an_output_is_converted_adds_nothing() { + use rustgis_analysis::control::Control; + let in_system = |crs: &str| { + let mut s = Session::new(Project::default()); + s.map_mut().add_dataset(bern_points("Wells")); + s.run("project.coordinateSystem", &json!({"crs": crs})).unwrap(); + s + }; + let session = || in_system("EPSG:2056"); + let p = json!({"input": "Wells", "output": "Out"}); + let looked = |mut s: Session| { + let counted = Control::cancelled_at_look(u64::MAX); + crate::cmd::gp::run_tool_with(&mut s, "featureToPoint", &p, &counted).unwrap(); + (counted.looked(), s.map().layer_by_name("Out").unwrap().dataset.coord_crs()) + }; + let (looks, held) = looked(session()); + assert_eq!(held, LV95); + // The conversion looks at Cancel too, on the run's own control. + let (plain, _) = looked(in_system("")); + assert!(looks > plain, "{looks} looks with the project's system, {plain} without"); + for n in 1..=looks { + let mut t = session(); + let out = crate::cmd::gp::run_tool_with(&mut t, "featureToPoint", &p, &Control::cancelled_at_look(n)); + assert!(out.as_ref().is_err_and(|e| e.contains("cancelled")), "cancelled at look {n} of {looks}: {out:?}"); + assert!(t.map().layer_by_name("Out").is_none(), "look {n} of {looks}"); + } +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index ac2b054e44..12ae97f87e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -527,9 +527,10 @@ Points can optionally be weighted by a numeric population field (invalid or non- are excluded and reported in the tool messages; for multipoint features, each constituent point part receives the feature's weight, a part with a coordinate missing or infinite is left out and counted, and a feature with no finite part is skipped). Calculations are performed in the linear units -of a projected coordinate system (defaults to the projected system the layer is held in, or else was read in; if the input layer lacks a -coordinate system or is in degrees, the project's projected system, which the tool says it used; when the project has none, or to project into a specific system, supply a projected system via `crs`, -e.g. `EPSG:32618`). Geocentric systems such as `EPSG:4978` (X, Y and Z from the Earth's centre) +of a projected coordinate system. By default this is the projected system the layer is held in, +or else was read in. If the layer has no coordinate system or is in degrees, it uses the project's +projected system and says so. When the project has none either, or to work in a specific system, +supply a projected system via `crs`, e.g. `EPSG:32618`. Geocentric systems such as `EPSG:4978` (X, Y and Z from the Earth's centre) are refused, whether supplied via `crs` or inherited from the layer: their three axes do not define the two-dimensional projected plane Kernel Density needs. Because bandwidth and cell size are measured in coordinate-space linear units, global cylindrical