From 48ae1995ffb35af1b3297612913cd35447e964f7 Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 13:04:39 +0100 Subject: [PATCH 1/2] Exports and write-backs in a layer's own coordinate system (#2032 C2f-1) GeoParquet exports keep a system with an EPSG code (PROJJSON on the geometry column); CSV takes x and y in a system asked for; a GeoJSON with a legacy crs member is published back in that system; the sync record keeps a digest of the layer's own coordinates beside the longitude/latitude one older releases compare. --- crates/data/src/export.rs | 8 +- crates/data/src/export/tests.rs | 14 +- crates/data/src/io.rs | 111 ++++++++++-- crates/data/src/publish.rs | 21 ++- crates/data/src/publish/json.rs | 90 ++++++++-- crates/data/src/source/parquet.rs | 43 ++++- crates/data/src/source/tests.rs | 117 +++++++++++++ crates/data/src/sync.rs | 149 ++++++++++++++-- crates/engine/src/cmd/layer.rs | 4 +- crates/engine/src/cmd/publish.rs | 22 +-- crates/engine/src/cmd/share.rs | 13 +- crates/engine/src/tests.rs | 2 + crates/engine/src/tests/formats_out.rs | 97 +++++++++++ crates/ui-egui/src/syncmark.rs | 18 +- docs/user-guide/data-formats.md | 15 +- docs/user-guide/index.md | 6 +- schema/fixtures/held_synced.rgis | 226 +++++++++++++++++++++++++ 17 files changed, 857 insertions(+), 99 deletions(-) create mode 100644 crates/engine/src/tests/formats_out.rs create mode 100644 schema/fixtures/held_synced.rgis diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 26470bc055..34763ea162 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -6,7 +6,7 @@ use std::{borrow::Cow, path::Path}; -use crate::io::{CsvWriter, GeoJsonWriter, GpkgTable, GpkgWritten, PROJECTED_FORMATS, check_projected, project_each, write_atomic_with}; +use crate::io::{CsvWriter, GeoJsonWriter, GpkgTable, GpkgWritten, check_projected, project_each, write_atomic_with}; use crate::raster::Crs; use crate::rows::Query; use crate::source::FeatureSource; @@ -223,7 +223,7 @@ fn write_chunks_as( return Err(DataError::Unsupported("a source that can't be read a chunk at a time".into())); } if crs != Crs::LonLat { - if !PROJECTED_FORMATS.contains(&ext) { + if !crate::io::holds_a_system(ext) { return Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))); } check_projected(ext, crs)?; @@ -342,7 +342,7 @@ fn write_chunks_as( Ok::<_, DataError>(0) })?, "csv" => write_atomic_with(path, |out| { - let mut w = CsvWriter::new(out, &layer.fields, geometry_type)?; + let mut w = CsvWriter::new(out, &layer.fields, geometry_type, crs)?; feed(&mut |features| w.write(features))?; w.finish()?; Ok::<_, DataError>(0) @@ -351,7 +351,7 @@ fn write_chunks_as( crate::source::fgb::write_features(&layer.name, geometry_type, &layer.fields, crs, out, &mut feed) })?, _ => write_atomic_with(path, |out| { - let (_, counts, messages) = crate::source::parquet::write_features(geometry_type, &layer.fields, out, &mut feed)?; + let (_, counts, messages) = crate::source::parquet::write_features(geometry_type, &layer.fields, crs, out, &mut feed)?; unfit = counts; date_messages = messages; Ok::<_, DataError>(0) diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 043a01b0b8..7dcdcd6075 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -207,7 +207,7 @@ fn a_streamed_export_writes_what_a_whole_export_writes() { layer.crs = whole.crs; let format = src.info().format; for ext in STREAMED { - let systems: &[Crs] = if PROJECTED_FORMATS.contains(&ext) { &[Crs::LonLat, Crs::WebMercator] } else { &[Crs::LonLat] }; + let systems: &[Crs] = if crate::io::holds_a_system(ext) { &[Crs::LonLat, Crs::WebMercator] } else { &[Crs::LonLat] }; for &crs in systems { let (a, b) = (d.join(format!("{format}-streamed-{}.{ext}", crs.epsg())), d.join(format!("{format}-whole-{}.{ext}", crs.epsg()))); @@ -423,9 +423,15 @@ fn streamed_exports_refuse_what_they_cant_write() { let ds = squares(); let layer = Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone()); let src = Runs::new(&ds, 10); - for (name, crs) in - [("out.shp", Crs::LonLat), ("out.kml", Crs::LonLat), ("out.geojson", Crs::WebMercator), ("out.parquet", Crs::WebMercator)] - { + // GeoParquet says a system by its EPSG code only: one without is refused. + let gnomonic = Crs::parse("+proj=gnom +lat_0=51 +lon_0=9 +datum=WGS84 +units=m +no_defs").unwrap(); + for (name, crs) in [ + ("out.shp", Crs::LonLat), + ("out.kml", Crs::LonLat), + ("out.geojson", Crs::WebMercator), + ("out.kml", Crs::WebMercator), + ("out.parquet", gnomonic), + ] { assert!(write_source_in(&src, &layer, &d.join(name), crs).is_err(), "{name}"); } let whole_only = Runs { chunks: false, ..Runs::new(&ds, 10) }; diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 9c140bc1fc..7b87244a61 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -591,8 +591,27 @@ pub fn write_bytes(ds: &Dataset, ext: &str) -> Result<(Vec, usize)> { } /// The formats that can be written in a coordinate system other than WGS 84 longitude/latitude -/// (GeoJSON, KML and GPX are longitude/latitude by definition). -pub const PROJECTED_FORMATS: [&str; 4] = ["gpkg", "shp", "zip", "fgb"]; +/// (GeoJSON, KML and GPX are longitude/latitude by definition). GeoParquet takes only a system with +/// an EPSG code ([`check_projected`]). +pub const PROJECTED_FORMATS: [&str; 6] = ["gpkg", "shp", "zip", "fgb", "parquet", "geoparquet"]; + +/// Whether a format of extension `ext` can be written in a coordinate system other than WGS 84 +/// longitude/latitude when one is asked for: those of [`PROJECTED_FORMATS`], and CSV, whose x and +/// y columns are then in it, though the file can't say which system that is +/// ([`csv_system_note`]); CSV is never written in another by default. +pub fn holds_a_system(ext: &str) -> bool { + let ext = ext.to_ascii_lowercase(); + PROJECTED_FORMATS.contains(&ext.as_str()) || ext == "csv" +} + +/// What is said of a CSV export of a point layer written in `crs` other than longitude/latitude: +/// the file can't say its system, so adding it back needs it given. `None` otherwise. +pub fn csv_system_note(path: &str, geometry_type: GeometryType, crs: Crs) -> Option { + let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + (ext == "csv" && geometry_type == GeometryType::Point && crs != Crs::LonLat).then(|| { + format!("{path}: its coordinates are in {}, which a CSV file can't say; give that system when adding it back", crs.label()) + }) +} /// The coordinate system an export to extension `ext` is written in when none is asked for: the /// one the dataset was read in, for a format that can say it, else WGS 84. A system without an @@ -611,8 +630,15 @@ pub fn default_export_note(ds: &Dataset, path: &str) -> 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 {} ({}) has no EPSG code and no WKT definition RustGIS can write, so it is written in WGS 84 (EPSG:4326); give a \"crs\" to write another", + "{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() ) @@ -699,10 +725,15 @@ pub fn define_projection(ds: &Dataset, crs: Crs) -> Result { Ok(out) } -/// Refuses a system for a GeoPackage or FlatGeobuf that the file couldn't declare: one without an +/// Refuses a system for a GeoParquet that has no EPSG code ([`crate::source::parquet::projjson`]), +/// and for a GeoPackage or FlatGeobuf that the file couldn't declare: one without an /// EPSG code is declared by its WKT definition, and without one (a projection WKT1 has no name /// for) the file would read as longitude/latitude. pub(crate) fn check_projected(ext: &str, crs: Crs) -> Result<()> { + // GeoParquet says a system by PROJJSON with its EPSG code, which every release reads. + if matches!(ext, "parquet" | "geoparquet") && crs != Crs::LonLat && crate::source::parquet::projjson(crs).is_none() { + return Err(DataError::Unsupported(format!(".{ext} in {}: {}", crs.label(), crate::source::parquet::projjson_refusal(crs)))); + } if crs.epsg() == 0 && matches!(ext, "gpkg" | "fgb") && crate::raster::wkt::to_wkt(crs).is_none() { return Err(DataError::Unsupported(format!( ".{ext} in {}: it has no EPSG code or WKT definition; give the system as an EPSG code", @@ -717,7 +748,7 @@ pub(crate) fn check_projected(ext: &str, crs: Crs) -> Result<()> { pub fn write_bytes_in(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec, usize)> { let ext = ext.to_ascii_lowercase(); if crs != Crs::LonLat { - if !PROJECTED_FORMATS.contains(&ext.as_str()) { + if !holds_a_system(&ext) { return Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))); } check_projected(&ext, crs)?; @@ -738,9 +769,9 @@ fn projected_bytes(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec, usize) w.write(&ds.features)?; (w.finish()?, 0) } - "csv" => (to_csv(ds)?.into_bytes(), 0), + "csv" => (to_csv_in(ds, crs)?.into_bytes(), 0), "fgb" => (crate::source::fgb::write_in(ds, crs)?, without_geometry(ds)), - "parquet" | "geoparquet" => (crate::source::parquet::write(ds)?, 0), + "parquet" | "geoparquet" => (crate::source::parquet::write_in(ds, crs)?, 0), "kml" => (crate::interop::to_kml(ds, name_field(ds))?.into_bytes(), without_geometry(ds)), "kmz" => { let kml = crate::interop::to_kml(ds, name_field(ds))?.into_bytes(); @@ -813,7 +844,7 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R let projected; // From the system the dataset holds its coordinates in ([`project`]): as they are when that // is `crs`, and when `crs` is one the format can't hold, which is refused below. - let ds = if crs == ds.coord_crs() || (crs != Crs::LonLat && !PROJECTED_FORMATS.contains(&ext.as_str())) { + let ds = if crs == ds.coord_crs() || (crs != Crs::LonLat && !holds_a_system(&ext)) { ds } else { projected = project(ds, crs)?; @@ -842,7 +873,7 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R let kept = place_shapefile(path, &stage_shapefile(&parts)?)?; Ok((left_out, None, kept_backups_note(path, &kept).into_iter().collect())) } - _ if crs != Crs::LonLat && !PROJECTED_FORMATS.contains(&ext.as_str()) => { + _ if crs != Crs::LonLat && !holds_a_system(&ext) => { Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))) } _ => { @@ -3023,9 +3054,33 @@ fn csv_coordinate_names(fields: &[Field]) -> [String; 2] { [pick("longitude", LON_NAMES), pick("latitude", LAT_NAMES)] } +/// The names of a point layer's x and y columns in CSV written in a projected system: `x` and +/// `y`, which reading takes first when given a projected system, else `easting` and `northing`, +/// else `x_1` and `y_1` and so on, the first that no field has (ignoring case and spaces). +fn csv_projected_names(fields: &[Field]) -> [String; 2] { + let taken = |name: &str| fields.iter().any(|f| f.name.trim().eq_ignore_ascii_case(name)); + let pick = |base: &str, other: &str| { + let name = [base.to_string(), other.to_string()].into_iter().chain((1..).map(|i| format!("{base}_{i}"))).find(|n| !taken(n)); + name.unwrap_or_default() + }; + [pick("x", "easting"), pick("y", "northing")] +} + +/// A point layer's coordinate column names in CSV written in `crs`: longitude and latitude ones +/// for a geographic system, x and y ones for a projected one. +fn csv_names_in(fields: &[Field], crs: Crs) -> [String; 2] { + if crs.is_geographic() { csv_coordinate_names(fields) } else { csv_projected_names(fields) } +} + /// A dataset as CSV text: its fields, and a point layer's longitude and latitude ([`CsvWriter`]). pub fn to_csv(ds: &Dataset) -> Result { - let mut w = CsvWriter::new(Vec::new(), &ds.fields, ds.geometry_type)?; + to_csv_in(ds, Crs::LonLat) +} + +/// As [`to_csv`], for a dataset whose coordinates are in `crs`: a projected system's go in x and y +/// columns ([`csv_projected_names`]). +pub fn to_csv_in(ds: &Dataset, crs: Crs) -> Result { + let mut w = CsvWriter::new(Vec::new(), &ds.fields, ds.geometry_type, crs)?; w.write(&ds.features)?; String::from_utf8(w.finish()?).map_err(|e| DataError::Format(e.to_string())) } @@ -3038,14 +3093,15 @@ pub(crate) struct CsvWriter { } impl CsvWriter { - /// Writes the header for `fields`, with coordinate columns for a point layer. - pub(crate) fn new(out: W, fields: &[Field], geometry_type: GeometryType) -> Result { + /// Writes the header for `fields`, with coordinate columns for a point layer, named for + /// `crs`, the system its features' coordinates are in ([`csv_names_in`]). + pub(crate) fn new(out: W, fields: &[Field], geometry_type: GeometryType, crs: Crs) -> Result { let mut w = csv::Writer::from_writer(out); let point = geometry_type == GeometryType::Point; let mut head = Vec::new(); if point { // The coordinate columns come first, before any attributes using recognised names. - head.extend(csv_coordinate_names(fields)); + head.extend(csv_names_in(fields, crs)); } head.extend(fields.iter().map(|f| f.name.clone())); w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?; @@ -4569,9 +4625,27 @@ impl CsvLosses { /// Warns when adding the CSV back may use attributes for geometry. This can happen when the /// coordinate names are all taken or when unusable coordinate rows let a competing pair win. pub fn coordinates_note(&self, fields: &[Field], target: &str) -> Option { + self.coordinates_note_in(fields, target, Crs::LonLat) + } + + /// As [`CsvLosses::coordinates_note`], for a CSV written in `crs`. In a projected system, the + /// x and y columns come first and reading takes them first when given the system, unless the + /// fields hold every name they could have. + pub fn coordinates_note_in(&self, fields: &[Field], target: &str, crs: Crs) -> Option { if !self.points { return None; } + if !crs.is_geographic() { + let [x, y] = csv_projected_names(fields); + let target: String = target.chars().map(dbf_notice_char).collect(); + return (x != "x" && x != "easting" || y != "y" && y != "northing").then(|| { + format!( + "{target}: the fields have the names 'x', 'y', 'easting' and 'northing', so the coordinates are in columns '{}' and '{}'; pick those columns when adding the file back", + dbf_notice_name(&x), + dbf_notice_name(&y) + ) + }); + } let header: Vec = csv_coordinate_names(fields).into_iter().chain(fields.iter().map(|f| f.name.clone())).collect(); let alternative = found_non_geographic_xy(&header); let geographic = found_geographic_xy(&header); @@ -4889,13 +4963,18 @@ impl std::ops::AddAssign for TextLosses { /// other values are [`shapefile_values_notes`]). A streamed export counts CSV's changes a chunk /// at a time instead. pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Result> { + export_losses_notes_in(ds, ext, name_field, target, Crs::LonLat) +} + +/// As [`export_losses_notes`], for an export written in `crs`. +pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option, target: &str, crs: Crs) -> Result> { let mut notes = match ext { "csv" => { - // Of the longitude/latitude the file is written in. - let ds = ds.in_lonlat().map_err(DataError::of_conversion)?; + // Of the coordinates the file is written in: longitude/latitude, or another system's. + let ds = if crs == Crs::LonLat { ds.in_lonlat().map_err(DataError::of_conversion)? } else { std::borrow::Cow::Borrowed(ds) }; let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?; let mut notes = losses.notes(&ds.fields, target); - notes.extend(losses.coordinates_note(&ds.fields, target)); + notes.extend(losses.coordinates_note_in(&ds.fields, target, crs)); notes } "kml" | "kmz" => kml_empty_fields_note(ds, target)?.into_iter().collect(), diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 26265ab777..b612a14a49 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -51,6 +51,9 @@ pub struct Published { pub read: Dataset, /// Digest of `read`, computed before placement so cancellation cannot interrupt completion. pub rows: u64, + /// Its [`crate::sync::native_digest`] when it is held in a system of its own + /// ([`crate::sync::Synced::native`]). + pub native: Option, pub features: usize, pub notes: Vec, } @@ -254,12 +257,12 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result Result (Dataset, Synced) { let (read, files) = FileSync::around(path, || crate::io::read_path(path).unwrap()).unwrap(); let rows = crate::sync::rows_digest(&read.0).unwrap(); - (read.0, Synced { files: files.unwrap(), rows }) + (read.0, Synced { files: files.unwrap(), rows, native: None }) } /// An edit is written back: the file reads as the layer, keeps its columns and `.prj`, and @@ -1208,7 +1211,7 @@ mod tests { ds.features = rows.into(); let published = shapefile(&ds, &path, &sync).unwrap(); assert_eq!(published.read.features.iter().next().unwrap().attrs[0], Value::Null); - let synced = Synced { files: published.files, rows: crate::sync::rows_digest(&published.read).unwrap() }; + let synced = Synced { files: published.files, rows: crate::sync::rows_digest(&published.read).unwrap(), native: None }; let mut ds = published.read; let mut rows: Vec<_> = ds.features.iter().cloned().collect(); rows[1].attrs[0] = Value::Text("Jonas".into()); @@ -1289,7 +1292,7 @@ mod tests { ds.features = rows.clone().into(); let published = shapefile(&ds, &path, &sync).unwrap(); // The record of what was published, as the layer takes it. - let synced = Synced { files: published.files, rows: crate::sync::rows_digest(&published.read).unwrap() }; + let synced = Synced { files: published.files, rows: crate::sync::rows_digest(&published.read).unwrap(), native: None }; let dbf = std::fs::read(path.with_extension("dbf")).unwrap(); assert!(dbf.windows(5).any(|w| w == b"Mu\xf1oz"), "written in Windows-1252"); assert_eq!(std::fs::read(path.with_extension("cpg")).unwrap(), b"1252"); @@ -1435,7 +1438,7 @@ mod tests { assert_eq!(published.read.fields[1].ty, FieldType::Double); assert_eq!(published.read.features.first().unwrap().attrs[1], Value::Float(100.0)); assert!(published.notes.is_empty(), "{:?}", published.notes); - let again = shapefile(&published.read, &path, &Synced { files: published.files, rows: published.rows }).unwrap(); + let again = shapefile(&published.read, &path, &Synced { files: published.files, rows: published.rows, native: None }).unwrap(); assert!(again.notes.is_empty(), "{:?}", again.notes); } @@ -1551,7 +1554,7 @@ mod tests { rows[0].id = id; rows[0].attrs[0] = Value::Text("Smyth".into()); ds.features = rows.into(); - let sync = Synced { files: published.files, rows: published.rows }; + let sync = Synced { files: published.files, rows: published.rows, native: None }; let before = std::fs::read(&path).unwrap(); shapefile(&ds, &path, &sync).unwrap(); assert!(same_shapes(&before, &std::fs::read(&path).unwrap(), 0.0).is_none()); diff --git a/crates/data/src/publish/json.rs b/crates/data/src/publish/json.rs index 5c502f7a42..9d9ccdd42d 100644 --- a/crates/data/src/publish/json.rs +++ b/crates/data/src/publish/json.rs @@ -8,7 +8,8 @@ use std::path::Path; /// Publishes a whole-read GeoJSON layer. Checks source bytes and the original read's digest, /// then proves that both the original and the edits survive a round trip. Foreign members, -/// legacy CRS declarations, duplicate keys and noncanonical number text are refused. A file +/// duplicate keys and noncanonical number text are refused. A legacy `crs` member is kept, and +/// the layer is written back in the system it declares, which the layer must still be held in. A file /// with feature ids permits value/geometry edits, but not row changes: the reader doesn't keep /// those external ids as layer ids. Parsing, JSON equality and serialization are single steps /// that finish before Cancel is seen; @@ -24,9 +25,6 @@ pub fn geojson(ds: &Dataset, path: &Path, synced: &Synced) -> Result if changed.is_empty() { Ok(()) } else { Err(refused(path, format!("{} changed since the layer was read", changed.join(", ")))) } }; unchanged()?; - if ds.crs.is_some_and(|c| c != crate::raster::Crs::LonLat) { - return Err(refused(path, "publishing GeoJSON requires a layer read in longitude/latitude")); - } let bytes = super::read_part(path, crate::io::file_size_error)?.ok_or_else(|| refused(path, "the source file is missing"))?; let text = std::str::from_utf8(&bytes).map_err(|e| refused(path, format!("its text isn't UTF-8: {e}")))?; // Parse with serde's depth limit before the raw duplicate-key traversal below. @@ -34,9 +32,6 @@ pub fn geojson(ds: &Dataset, path: &Path, synced: &Synced) -> Result let valid = unique_keys(text).and_then(|()| canonical_numbers(text)); crate::progress::check()?; valid.map_err(|e| refused(path, e))?; - if original.get("crs").is_some() { - return Err(refused(path, "it has a legacy crs member, which a rewrite wouldn't keep")); - } let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let (mut as_read, report) = crate::io::read_geojson(text, &name)?; // What the read skipped or said can't be rewritten: refused with what it said, rather than @@ -48,8 +43,33 @@ pub fn geojson(ds: &Dataset, path: &Path, synced: &Synced) -> Result } return Err(refused(path, format!("reading it isn't lossless ({}), so a rewrite wouldn't keep the file", said.join("; ")))); } + // Written back in the system the file declares (its legacy `crs` member, else + // longitude/latitude), so what the kept member says stays true. + let declared = as_read.coord_crs(); + if ds.coord_crs() != declared { + // A layer of a project saved before RustGIS kept a file's own coordinates holds them in + // longitude/latitude. + return Err(refused( + path, + format!( + "the file's coordinates are in {}, and the layer holds them in {}; add the file again to publish to it, or export a copy", + declared.label(), + ds.coord_crs().label() + ), + )); + } + if ds.crs.unwrap_or(crate::raster::Crs::LonLat) != declared { + return Err(refused( + path, + format!( + "the file's coordinates are in {}, and the layer's coordinate system was defined as {} since; export a copy instead", + declared.label(), + ds.crs.unwrap_or(ds.coord_crs()).label() + ), + )); + } as_read.crs = ds.crs; - if crate::sync::rows_digest(&as_read)? != synced.rows { + if synced.digest_of(&as_read)? != synced.digest() { return Err(refused(path, "it reads otherwise now than when the layer was read; add the file again to compare it")); } { @@ -86,7 +106,7 @@ pub fn geojson(ds: &Dataset, path: &Path, synced: &Synced) -> Result removed.iter().take(5).map(|n| n.chars().take(80).collect::()).collect::>().join(", ") )] }; - let rows = crate::sync::rows_digest(&read)?; + let (rows, native) = crate::sync::digests(&read)?; let targets = vec![(path.to_path_buf(), written)]; let files = FileSync::of_written(path, &targets)?; let staged = crate::io::stage_shapefile(&targets)?; @@ -103,7 +123,7 @@ pub fn geojson(ds: &Dataset, path: &Path, synced: &Synced) -> Result })(); crate::io::unstage(&staged); placed?; - Ok(Published { files, read, rows, features: ds.features.len(), notes }) + Ok(Published { files, read, rows, native, features: ds.features.len(), notes }) } /// Builds only the members RustGIS understands. Comparing the original with its rebuild catches @@ -209,6 +229,12 @@ fn document(ds: &Dataset, original: &Json) -> std::result::Result } _ => return Err("a bare geometry can't hold attributes or a different number of rows; export a collection instead".into()), }; + // A legacy `crs` member says the system the coordinates are in, which they're written in. + if let (Some(crs), Some(object)) = (original.get("crs"), out.as_object_mut()) + && matches!(kind, "FeatureCollection" | "Feature") + { + object.insert("crs".into(), crs.clone()); + } keep_numbers(&mut out, original)?; Ok(out) } @@ -419,7 +445,7 @@ mod tests { let path = dir.path().join("parcels.geojson"); std::fs::write(&path, text).unwrap(); let ds = crate::io::read_path(&path).unwrap().0; - let sync = Synced { files: FileSync::read(&path).unwrap(), rows: crate::sync::rows_digest(&ds).unwrap() }; + let sync = Synced::record(FileSync::read(&path).unwrap(), &ds).unwrap(); (dir, path, ds, sync) } @@ -455,7 +481,7 @@ mod tests { assert_eq!(serde_json::from_str::(&text).unwrap(), serde_json::from_str::(&SOURCE.replace("Smith", "Jones")).unwrap()); assert!(text.contains("[1,2]")); assert!(out.files.changed(&path).unwrap().is_empty()); - let sync = Synced { files: out.files, rows: out.rows }; + let sync = Synced { files: out.files, rows: out.rows, native: None }; rename_owner(&mut ds, "Taylor"); geojson(&ds, &path, &sync).unwrap(); } @@ -509,6 +535,41 @@ mod tests { } } + /// A file with a legacy `crs` member keeps it, and is written back in its system: an edited + /// point lands where it was put, in the file's own coordinates. + #[test] + fn a_legacy_crs_member_is_kept_and_the_layer_written_back_in_it() { + let lv95 = r#"{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::2056"}},"features":[{"type":"Feature","properties":{"owner":"Smith"},"geometry":{"type":"Point","coordinates":[2600000,1200000]}}]}"#; + let (_dir, path, mut ds, sync) = loaded(lv95); + let system = crate::raster::Crs::from_epsg(2056).unwrap(); + assert_eq!(ds.coord_crs(), system); + rename_owner(&mut ds, "Jones"); + let mut rows: Vec<_> = ds.features.iter().cloned().collect(); + rows.first_mut().unwrap().geometry = Some(crate::Geometry::Point(rustgis_geom::Coord::new(2_600_010.5, 1_200_020.0))); + ds.features = rows.into(); + let out = geojson(&ds, &path, &sync).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let want = lv95.replace("Smith", "Jones").replace("[2600000,1200000]", "[2600010.5,1200020.0]"); + assert_eq!(serde_json::from_str::(&text).unwrap(), serde_json::from_str::(&want).unwrap()); + assert_eq!(out.read.coord_crs(), system); + // And again from what it wrote. + let sync = Synced { files: out.files, rows: out.rows, native: out.native }; + rename_owner(&mut ds, "Taylor"); + geojson(&ds, &path, &sync).unwrap(); + // A `crs` of null says nothing and is kept as it is. + let null = SOURCE.replace("\"features\":[", "\"crs\":null,\"features\":["); + let (_dir, path, mut ds, sync) = loaded(&null); + rename_owner(&mut ds, "Jones"); + geojson(&ds, &path, &sync).unwrap(); + assert!(std::fs::read_to_string(&path).unwrap().contains("\"crs\":null")); + // A layer whose system was defined again isn't written into a file that says the old one. + let (_dir, path, ds, sync) = loaded(lv95); + let redefined = crate::io::define_projection(&ds, crate::raster::Crs::from_epsg(21781).unwrap()).unwrap(); + let e = geojson(&redefined, &path, &sync).err().unwrap().to_string(); + assert!(e.contains("EPSG:2056") && e.contains("EPSG:21781") && e.contains("nothing was written"), "{e}"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), lv95); + } + #[test] fn a_changed_source_is_left_untouched() { let (_dir, path, mut ds, sync) = loaded(SOURCE); @@ -528,7 +589,6 @@ mod tests { SOURCE.replace("\"features\":[", "\"bbox\":[0,0,9,9],\"features\":["), SOURCE.replace("[1,2]", "[1.00,2]"), SOURCE.replace("\"owner\":\"Smith\"", "\"owner\":\"Lost\",\"owner\":\"Smith\""), - SOURCE.replace("\"features\":[", "\"crs\":null,\"features\":["), SOURCE.replace("\"owner\":\"Smith\"", "\"owner\":{\"name\":\"Smith\"}"), ] { let (_dir, path, ds, sync) = loaded(&text); @@ -622,7 +682,7 @@ mod tests { assert!(published.notes.first().unwrap().contains("1 properties left out")); assert!(published.notes.first().unwrap().contains("owner")); let written = std::fs::read_to_string(&path).unwrap(); - let sync = Synced { files: published.files, rows: published.rows }; + let sync = Synced { files: published.files, rows: published.rows, native: None }; ds.features = Vec::new().into(); assert!(geojson(&ds, &path, &sync).err().unwrap().to_string().contains("empty collection has no schema")); assert_eq!(std::fs::read_to_string(path).unwrap(), written); @@ -668,7 +728,7 @@ mod tests { let out = geojson(&ds, &path, &sync).unwrap(); let written = std::fs::read_to_string(&path).unwrap(); assert!(written.contains("parcel-17")); - let sync = Synced { files: out.files, rows: out.rows }; + let sync = Synced { files: out.files, rows: out.rows, native: None }; ds.features = Vec::new().into(); let error = geojson(&ds, &path, &sync).err().unwrap().to_string(); assert!(error.contains("feature ids"), "{error}"); diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index d9b673697b..0f23118234 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -13,6 +13,7 @@ use super::remote::{self, Remote}; use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit}; +use crate::raster::Crs; use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, wkb}; use bytes::Bytes; use parquet::basic::{ConvertedType, Encoding, LogicalType, Type as Physical}; @@ -1594,7 +1595,35 @@ fn wkb_type_name(g: &crate::Geometry) -> &'static str { /// `bbox` covering column so readers can skip rows and row groups by extent. A table without /// geometry is written as plain Parquet. pub fn write(ds: &crate::Dataset) -> Result> { - write_features(ds.geometry_type, &ds.fields, Vec::new(), &mut |add| add(&ds.features)).map(|(bytes, _, _)| bytes) + write_in(ds, Crs::LonLat) +} + +/// As [`write`], for a dataset whose coordinates are in `crs`, which the geometry column's `crs` +/// says ([`projjson`]); refused for a system it can't say. +pub fn write_in(ds: &crate::Dataset, crs: Crs) -> Result> { + write_features(ds.geometry_type, &ds.fields, crs, Vec::new(), &mut |add| add(&ds.features)).map(|(bytes, _, _)| bytes) +} + +/// The GeoParquet `crs` (PROJJSON) of a system other than longitude/latitude, which GeoParquet +/// takes when a column has none. Only a system with an EPSG code: its PROJJSON carries the code, +/// which every release of RustGIS reads ([`crs_code`]), where one without would be read as +/// longitude/latitude. `None` for one without a code, or one terrio-crs can't write. +pub(crate) fn projjson(crs: Crs) -> Option { + let code = u32::from(crs.epsg()); + if code == 0 || crs == Crs::LonLat { + return None; + } + let text = terrio_crs::SpatialRef::from_epsg(code).ok()?.to_projjson().ok()?; + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + (crs_code(Some(&value)) == Some(code)).then_some(value) +} + +/// Why a GeoParquet can't be written in `crs` ([`projjson`] has none for it). +pub(crate) fn projjson_refusal(crs: Crs) -> String { + match crs.epsg() { + 0 => "it has no EPSG code; give the system as an EPSG code".to_string(), + code => format!("RustGIS can't write a PROJJSON definition of EPSG:{code}"), + } } /// An Integer column's value, `None` for one it can't hold: a whole float fits; a fraction, a @@ -1752,6 +1781,7 @@ pub fn values_note(ds: &crate::Dataset, target: &str) -> Option { pub(crate) fn write_features( geometry_type: GeometryType, fields: &[Field], + crs: Crs, out: W, feed: &mut dyn FnMut(&mut dyn FnMut(&[Feature]) -> Result<()>) -> Result<()>, ) -> Result<(W, Vec, Vec)> { @@ -1773,6 +1803,14 @@ pub(crate) fn write_features( })?; } let has_geom = geometry_type != GeometryType::None; + // Before anything is written: a system the file couldn't say would be read as degrees. + let crs_json = match crs { + Crs::LonLat => None, + _ if !has_geom => None, + other => Some( + projjson(other).ok_or_else(|| DataError::Unsupported(format!(".parquet in {}: {}", other.label(), projjson_refusal(other))))?, + ), + }; let geom_name = free_name(fields, "geometry"); let bbox_name = free_name(fields, "bbox"); let prim = |name: &str, t: Physical, rep: Repetition, logical: Option| { @@ -1930,6 +1968,9 @@ pub(crate) fn write_features( if !e.is_empty() { col["bbox"] = serde_json::json!([e.min_x, e.min_y, e.max_x, e.max_y]); } + if let Some(c) = crs_json { + col["crs"] = c; + } let geo = serde_json::json!({"version": "1.1.0", "primary_column": geom_name, "columns": {geom_name.clone(): col}}); w.append_key_value_metadata(KeyValue::new("geo".to_string(), geo.to_string())); } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 9f910b2bed..22086d64ff 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3125,6 +3125,123 @@ fn exports_are_written_in_the_system_the_layer_was_read_in() { assert!(crate::io::write_path_in(&ds, &d.join("squares.geojson"), Crs::from_epsg(25832).unwrap()).is_err()); } +#[test] +fn a_geoparquet_export_keeps_a_system_with_an_epsg_code() { + let d = dir().join("export-parquet-crs"); + std::fs::create_dir_all(&d).unwrap(); + let ds = utm_squares(25832); + let utm = Crs::from_epsg(25832).unwrap(); + for ext in ["parquet", "geoparquet"] { + assert_eq!(crate::io::default_export_crs(&ds, ext), utm, "{ext}"); + assert_eq!(crate::io::default_export_note(&ds, &format!("a.{ext}")), None, "{ext}"); + let p = d.join(format!("utm.{ext}")); + crate::io::write_path_in(&ds, &p, utm).unwrap(); + // Read back in the same system, at the same coordinates, by its EPSG code. + let (back, _) = materialize(open_path(&p, None).unwrap().as_ref()).unwrap(); + assert_eq!(back.crs, Some(utm), "{ext}"); + assert_eq!(back.coord_crs(), utm, "{ext}"); + let coords = |ds: &Dataset| { + let mut v = Vec::new(); + for f in &ds.features { + f.geometry.as_ref().unwrap().for_each_coord(|c| v.push((c.x, c.y))); + } + v + }; + assert_eq!(coords(&back), coords(&ds), "{ext}"); + // The written bytes are the whole-file and the in-memory writer alike. + let (bytes, _) = crate::io::write_bytes_in(&ds, ext, utm).unwrap(); + let (mem, _) = crate::io::read_bytes(&format!("m.{ext}"), &bytes).unwrap(); + assert_eq!(mem.crs, Some(utm), "{ext}"); + } + // Longitude/latitude writes the file as before: no `crs` on the geometry column. + let lonlat = crate::io::project(&ds, Crs::LonLat).unwrap(); + let mut plain = lonlat.clone(); + plain.crs = None; + let (a, _) = crate::io::write_bytes_in(&plain, "parquet", Crs::LonLat).unwrap(); + assert_eq!(a, crate::source::parquet::write(&plain).unwrap()); + let geo = |bytes: &[u8]| { + use ::parquet::file::reader::FileReader; + let r = ::parquet::file::reader::SerializedFileReader::new(bytes::Bytes::copy_from_slice(bytes)).unwrap(); + let kv = r.metadata().file_metadata().key_value_metadata().unwrap().clone(); + let geo = kv.into_iter().find(|k| k.key == "geo").unwrap().value.unwrap(); + serde_json::from_str::(&geo).unwrap() + }; + assert!(geo(&a)["columns"]["geometry"].get("crs").is_none()); + let (b, _) = crate::io::write_bytes_in(&ds, "parquet", utm).unwrap(); + assert_eq!(geo(&b)["columns"]["geometry"]["crs"]["id"]["code"], 25832); + // A system without an EPSG code: written in WGS 84 by default (said), refused when asked for. + let wkt = + crate::raster::wkt::to_wkt(utm).unwrap().replace(",AUTHORITY[\"EPSG\",\"25832\"]", "").replace("ETRS89 / UTM zone 32N", "My grid"); + let custom = crate::raster::wkt::crs_from_wkt(&wkt).unwrap(); + let mut own = ds.clone(); + own.crs = Some(custom); + assert_eq!(crate::io::default_export_crs(&own, "parquet"), Crs::LonLat); + let note = crate::io::default_export_note(&own, "a.parquet").unwrap(); + assert!(note.contains("has no EPSG code,") && note.contains("WGS 84"), "{note}"); + let e = crate::io::write_path_in(&own, &d.join("custom.parquet"), custom).unwrap_err().to_string(); + assert!(e.contains("no EPSG code"), "{e}"); +} + +#[test] +fn a_csv_export_takes_x_and_y_in_a_system_asked_for() { + use crate::{Field, FieldType, Value}; + let d = dir().join("export-csv-crs"); + std::fs::create_dir_all(&d).unwrap(); + let lv95 = Crs::from_epsg(2056).unwrap(); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + ds.push(Some(Geometry::Point(Coord::new(2_600_000.5, 1_200_000.25))), vec![Value::Text("Bern".into())]); + ds.crs = Some(lv95); + ds.held_in = lv95; + // By default it stays longitude/latitude, as before. + assert_eq!(crate::io::default_export_crs(&ds, "csv"), Crs::LonLat); + assert!(crate::io::holds_a_system("CSV") && !crate::io::holds_a_system("geojson")); + let lonlat = String::from_utf8(crate::io::write_bytes(&ds, "csv").unwrap().0).unwrap(); + assert!(lonlat.starts_with("longitude,latitude,name\n7.43"), "{lonlat}"); + assert_eq!(crate::io::csv_system_note("a.csv", ds.geometry_type, Crs::LonLat), None); + // Asked for, its own coordinates go in x and y, exactly. + let p = d.join("pts.csv"); + crate::io::write_path_in(&ds, &p, lv95).unwrap(); + let text = std::fs::read_to_string(&p).unwrap(); + assert_eq!(text, "x,y,name\n2600000.5,1200000.25,Bern\n"); + let (bytes, _) = crate::io::write_bytes_in(&ds, "csv", lv95).unwrap(); + assert_eq!(String::from_utf8(bytes).unwrap(), text); + // Read back with the system given, at the same place. + let opts = crate::io::CsvOptions { crs: Some(lv95), ..Default::default() }; + let (back, _) = crate::io::read_csv_with(&text, "pts", &opts).unwrap(); + let mut at = Vec::new(); + back.features[0].geometry.as_ref().unwrap().for_each_coord(|c| at.push((c.x, c.y))); + let mut want = Vec::new(); + ds.features[0].geometry.as_ref().unwrap().for_each_coord(|c| want.push((c.x, c.y))); + let back_lonlat = crate::io::project(&back, Crs::LonLat).unwrap(); + let ds_lonlat = crate::io::project(&ds, Crs::LonLat).unwrap(); + let pt = |ds: &Dataset| match ds.features[0].geometry { + Some(Geometry::Point(c)) => c, + _ => panic!(), + }; + assert!((pt(&back_lonlat).x - pt(&ds_lonlat).x).abs() < 1e-9 && (pt(&back_lonlat).y - pt(&ds_lonlat).y).abs() < 1e-9); + // The file can't say its system, so that is said. + let note = crate::io::csv_system_note("pts.csv", ds.geometry_type, lv95).unwrap(); + assert!(note.contains("EPSG:2056") && note.contains("can't say"), "{note}"); + assert_eq!(crate::io::csv_system_note("pts.gpkg", ds.geometry_type, lv95), None); + // Fields named x and y push the columns to easting and northing; every name taken is said. + let mut xy = Dataset::new("xy", GeometryType::Point, vec![Field::new("X", FieldType::Integer), Field::new("y", FieldType::Integer)]); + xy.push(Some(Geometry::Point(Coord::new(2_600_000.0, 1_200_000.0))), vec![Value::Int(1), Value::Int(2)]); + xy.crs = Some(lv95); + xy.held_in = lv95; + let text = crate::io::to_csv_in(&xy, lv95).unwrap(); + assert!(text.starts_with("easting,northing,X,y\n"), "{text}"); + assert!(crate::io::export_losses_notes_in(&xy, "csv", None, "xy.csv", lv95).unwrap().is_empty()); + let mut every = xy.clone(); + every.fields.push(Field::new("easting", FieldType::Integer)); + every.fields.push(Field::new("northing", FieldType::Integer)); + for f in &mut every.features { + f.attrs.extend([Value::Int(3), Value::Int(4)]); + } + assert!(crate::io::to_csv_in(&every, lv95).unwrap().starts_with("x_1,y_1,")); + let notes = crate::io::export_losses_notes_in(&every, "csv", None, "xy.csv", lv95).unwrap(); + assert!(notes.iter().any(|n| n.contains("'x_1' and 'y_1'")), "{notes:?}"); +} + /// A catalog index as AlphaEarth's is (a `bbox` struct, a nested `assets.data.href`), and patch /// embeddings as Earth Index's are (a fixed-size list of floats a point), in row groups of 50. fn write_index_and_vectors() -> Vec { diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index e676e5e41f..d3ce1d08a0 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -32,6 +32,34 @@ pub struct Synced { pub files: FileSync, /// The layer's [`rows_digest`] then: the file's as it read then too. pub rows: u64, + /// For a layer held in a system of its own, its [`native_digest`] then, which is compared + /// instead of [`Synced::rows`] when there is one: it hashes the coordinates as held, so it + /// takes no conversion of the whole layer, and it still matches once the conversion to + /// longitude/latitude changes (a datum grid downloaded). `rows` is kept beside it for the + /// releases before it, which compare that. Such a release saves the project again without + /// it, which loses nothing it needs: the record is then compared by `rows`, as before. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +impl Synced { + /// The record of `ds` as read from `files`: its [`rows_digest`], and its [`native_digest`] + /// when it is held in a system other than longitude/latitude (else the two are the same). + pub fn record(files: FileSync, ds: &crate::Dataset) -> crate::Result { + let (rows, native) = digests(ds)?; + Ok(Self { files, rows, native }) + } + + /// The digest recorded, to compare with [`Synced::digest_of`] a layer. + pub fn digest(&self) -> u64 { + self.native.unwrap_or(self.rows) + } + + /// The digest of `ds` of the kind recorded: [`native_digest`] when the record has one, else + /// [`rows_digest`] (a record saved by an older release, or of a layer in longitude/latitude). + pub fn digest_of(&self, ds: &crate::Dataset) -> crate::Result { + if self.native.is_some() { native_digest(ds) } else { rows_digest(ds) } + } } /// A hash of what a dataset holds: its fields, coordinate system, and each row's geometry and @@ -43,6 +71,32 @@ pub struct Synced { /// does. Its work grows with the rows: each is counted as progress ([`crate::progress`]), and it /// stops once the run is cancelled; the desktop app runs it off the UI thread. pub fn rows_digest(ds: &crate::Dataset) -> crate::Result { + Ok(hashes(ds, true, false)?.0.unwrap_or_default()) +} + +/// The digests [`Synced::record`] keeps of `ds`: its [`rows_digest`], and its [`native_digest`] +/// when it is held in a system other than longitude/latitude. +pub fn digests(ds: &crate::Dataset) -> crate::Result<(u64, Option)> { + if ds.coord_crs() == crate::raster::Crs::LonLat { + return Ok((rows_digest(ds)?, None)); + } + let (rows, native) = hashes(ds, true, true)?; + Ok((rows.unwrap_or_default(), native)) +} + +/// [`rows_digest`] over the geometry as the dataset holds it, in its own system, without +/// converting it to longitude/latitude; the same as [`rows_digest`] for a dataset held in +/// longitude/latitude. +pub fn native_digest(ds: &crate::Dataset) -> crate::Result { + if ds.coord_crs() == crate::raster::Crs::LonLat { + return rows_digest(ds); + } + Ok(hashes(ds, false, true)?.1.unwrap_or_default()) +} + +/// The digests of `ds`: its [`rows_digest`] (its geometry in longitude/latitude) when `lonlat`, +/// and its [`native_digest`] (as held) when `native`, in one pass over the rows. +fn hashes(ds: &crate::Dataset, lonlat: bool, native: bool) -> crate::Result<(Option, Option)> { /// FNV-1a over the bytes written to it. struct Fnv(u64); impl std::io::Write for Fnv { @@ -60,35 +114,53 @@ pub fn rows_digest(ds: &crate::Dataset) -> crate::Result { let _ = serde_json::to_writer(&mut *h, value); h.0 = (h.0 ^ 0xff).wrapping_mul(0x0100_0000_01b3); } - let mut h = Fnv(0xcbf2_9ce4_8422_2325); + /// The rows' values past their geometry: a number that isn't finite by its bits. + fn non_finite(h: &mut Fnv, attrs: &[crate::Value]) { + for (index, value) in attrs.iter().enumerate() { + if let crate::Value::Float(number) = value + && !number.is_finite() + { + put(h, &("non-finite", index, number.to_bits())); + } + } + } // Whole Shapefile/GeoJSON reads record fields with no aliases. Clear display-only aliases // when comparing a layer, keeping the serialized form and existing saved digests unchanged. let mut fields = ds.fields.clone(); for field in &mut fields { field.alias = None; } - put(&mut h, &(&fields, &ds.crs)); + let start = |h: &mut Fnv| put(h, &(&fields, &ds.crs)); + let (mut a, mut b) = (Fnv(0xcbf2_9ce4_8422_2325), Fnv(0xcbf2_9ce4_8422_2325)); + start(&mut a); + start(&mut b); // Its geometry in longitude/latitude, as every release before #2032 C2 held a file's rows // (converted by the same transformer the readers converted them with), so a digest saved - // then still matches the file read now in its own coordinates. - let to = ds.lonlat_conversion().map_err(crate::DataError::Format)?; + // then still matches the file read now in its own coordinates. Or as held, with the system + // it is held in (as a project saves it, not its display label), so the same numbers held in + // another system differ. + let held = ds.coord_crs(); + if held != crate::raster::Crs::LonLat { + put(&mut b, &("held in", &held)); + } + let to = if lonlat { Some(ds.lonlat_conversion().map_err(crate::DataError::Format)?) } else { None }; + let converts = to.as_ref().filter(|t| !t.is_identity()); crate::progress::begin(ds.features.len()); for f in ds.features.iter() { - if to.is_identity() { - put(&mut h, &(&f.geometry, &f.attrs)); - } else { - put(&mut h, &(&f.geometry.as_ref().map(|g| to.geometry(g)), &f.attrs)); - } - for (index, value) in f.attrs.iter().enumerate() { - if let crate::Value::Float(number) = value - && !number.is_finite() - { - put(&mut h, &("non-finite", index, number.to_bits())); + if lonlat { + match converts { + Some(to) => put(&mut a, &(&f.geometry.as_ref().map(|g| to.geometry(g)), &f.attrs)), + None => put(&mut a, &(&f.geometry, &f.attrs)), } + non_finite(&mut a, &f.attrs); + } + if native { + put(&mut b, &(&f.geometry, &f.attrs)); + non_finite(&mut b, &f.attrs); } crate::progress::step(1)?; } - Ok(h.0) + Ok((lonlat.then_some(a.0), native.then_some(b.0))) } /// Whether `path` names a source whose files a [`FileSync`] records: a Shapefile or a @@ -416,6 +488,53 @@ mod tests { assert_eq!(rows_digest(&ds).unwrap(), 1_724_049_670_388_433_092, "an alias changes display, not file contents"); } + /// A layer held in a system of its own is recorded by its own coordinates too, compared in + /// their place, while the longitude/latitude digest older releases compare is kept beside + /// them. A layer in longitude/latitude is recorded as before, with no second digest, and a + /// record saved without one is compared as before. + #[test] + fn a_held_layer_is_recorded_by_its_own_coordinates_too() { + use crate::{Coord, Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value}; + let mut lonlat = Dataset::new("a".to_string(), GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + lonlat.features = + vec![Feature { id: 1, geometry: Some(Geometry::Point(Coord { x: 7.4, y: 46.9 })), attrs: vec![Value::Int(4)] }].into(); + let files = FileSync { files: Vec::new() }; + let plain = Synced::record(files.clone(), &lonlat).unwrap(); + assert_eq!(plain, Synced { files: files.clone(), rows: rows_digest(&lonlat).unwrap(), native: None }); + assert_eq!(serde_json::to_string(&plain).unwrap(), r#"{"files":{"files":[]},"rows":"#.to_string() + &plain.rows.to_string() + "}"); + assert_eq!(native_digest(&lonlat).unwrap(), rows_digest(&lonlat).unwrap()); + + let lv95 = crate::raster::Crs::from_epsg(2056).unwrap(); + let mut held = lonlat.clone(); + held.crs = Some(lv95); + held.held_in = lv95; + held.features = + vec![Feature { id: 1, geometry: Some(Geometry::Point(Coord { x: 2_600_000.0, y: 1_200_000.0 })), attrs: vec![Value::Int(4)] }] + .into(); + let record = Synced::record(files.clone(), &held).unwrap(); + assert_eq!(record.rows, rows_digest(&held).unwrap()); + assert_eq!(record.native, Some(native_digest(&held).unwrap())); + assert_ne!(record.native, Some(record.rows)); + assert_eq!(record.digest_of(&held).unwrap(), record.digest()); + // Read back, and as an older release saved it: compared by the longitude/latitude one. + let text = serde_json::to_string(&record).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), record); + let older = Synced { native: None, ..record.clone() }; + assert_eq!(serde_json::from_str::(&serde_json::to_string(&older).unwrap()).unwrap(), older); + assert_eq!(older.digest_of(&held).unwrap(), older.digest()); + // An edit shows by either. + let mut edited = held.clone(); + let mut rows: Vec<_> = edited.features.iter().cloned().collect(); + rows[0].attrs[0] = Value::Int(5); + edited.features = rows.into(); + assert_ne!(record.digest_of(&edited).unwrap(), record.digest()); + assert_ne!(older.digest_of(&edited).unwrap(), older.digest()); + // The same numbers held in another system are another layer. + let mut other = held.clone(); + other.held_in = crate::raster::Crs::from_epsg(21781).unwrap(); + assert_ne!(native_digest(&other).unwrap(), native_digest(&held).unwrap()); + } + #[test] fn a_record_round_trips() { let sync = FileSync { files: vec![("a.geojson".into(), Some(FileStamp { len: 2, sha256: "ab".into() })), ("a.prj".into(), None)] }; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index b637337bb6..076b00a290 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2486,9 +2486,7 @@ fn read_synced(path: &str, read: impl FnOnce() -> WholeRead) -> WholeRead { ds.source = Some(full.display().to_string()); } report.synced = match files { - Some(files) => { - Some(rustgis_data::sync::Synced { files, rows: rustgis_data::sync::rows_digest(&ds).map_err(|e| format!("{path}: {e}"))? }) - } + Some(files) => Some(rustgis_data::sync::Synced::record(files, &ds).map_err(|e| format!("{path}: {e}"))?), None => { report.messages.push(format!( "{path}: a part of it couldn't be read to record it, so RustGIS can't tell later whether the file changed since; add it again to compare it" diff --git a/crates/engine/src/cmd/publish.rs b/crates/engine/src/cmd/publish.rs index 92041cc332..0b256b4a96 100644 --- a/crates/engine/src/cmd/publish.rs +++ b/crates/engine/src/cmd/publish.rs @@ -62,9 +62,9 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result Result Option CmdResult { } #[cfg(not(target_arch = "wasm32"))] { - let (was, files, path) = (synced.rows, synced.files.clone(), path.to_string()); + let (was, synced, path) = (synced.digest(), synced.clone(), path.to_string()); let ahead = super::reads::take::(s, &ahead_key(id)); let l = s.map().layer(id).ok_or("the layer no longer exists")?; let (rows, changed) = match ahead { @@ -235,8 +237,8 @@ fn sync_state(s: &mut Session, p: &Value) -> CmdResult { // Checking again here would hold the window: the check made on its thread is dropped. Some(_) => return Err("the layer or its file's record changed while it was checked: check again".into()), None => ( - rustgis_data::sync::rows_digest(&l.dataset).map_err(|e| e.to_string())?, - files.changed(std::path::Path::new(&path)).map_err(|e| e.to_string())?, + synced.digest_of(&l.dataset).map_err(|e| e.to_string())?, + synced.files.changed(std::path::Path::new(&path)).map_err(|e| e.to_string())?, ), }; let edited = rows != was; diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 59e4b4a23f..bbe681ae0e 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -34,7 +34,7 @@ pub fn commands() -> Vec { C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) - .params(r#"{"layer"?, "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "crs"?: "EPSG:… (or WKT) for a GeoPackage, Shapefile or FlatGeobuf (default: the system the layer was read in, else EPSG:4326)", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the layer's name)"} Applies the layer's definition query and reports how many features it leaves out."#), + .params(r#"{"layer"?, "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "crs"?: "EPSG:… (or WKT) for a GeoPackage, Shapefile or FlatGeobuf, EPSG:… for a GeoParquet (default: the system the layer was read in, else EPSG:4326), or for a CSV's x and y columns (default: EPSG:4326)", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the layer's name)"} Applies the layer's definition query and reports how many features it leaves out."#), C::new("share.exportTable", "Export Table", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportTable")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params( r#"{"table": name|id (a standalone table), "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the table's name)", "sort"?: [{"field": name, "descending"?: false}], "limit"?: "nonnegative integer: keep the first N rows after sorting"}"#, @@ -705,8 +705,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 and GPX are longitude/latitude; the others keep the layer's own system unless - // told another. + // 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)); // 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) { @@ -742,15 +742,15 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk dates.extend(e.date_messages.iter().map(|n| format!("{path}: {n}"))); dates.extend(e.read_notes.iter().map(|n| format!("{path}: {}: {n} when read for the export", layer.name))); let mut format_notes = e.csv.notes(&ds.fields, path); - format_notes.extend(e.csv.coordinates_note(&ds.fields, path)); + format_notes.extend(e.csv.coordinates_note_in(&ds.fields, path, crs)); // Text that reading the file back changes: CSV reads a blank cell as null; KML and GPX trim // their values. format_notes.extend(e.text.notes(&ds.fields, path)); (e.written, e.left_out, e.skipped, table, unfit, e.null_numbers, moved, format_notes, dates) } None => { - let mut format_notes = - rustgis_data::io::export_losses_notes(ds, &ext, rustgis_data::io::name_field(ds), path).map_err(|e| e.to_string())?; + let mut format_notes = rustgis_data::io::export_losses_notes_in(ds, &ext, rustgis_data::io::name_field(ds), path, crs) + .map_err(|e| e.to_string())?; let (left_out, table, placed) = rustgis_data::io::write_path_to(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; // Old parts of a Shapefile written over that couldn't be removed. format_notes.extend(placed); @@ -771,6 +771,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk if asked.is_none() { notes.extend(rustgis_data::io::default_export_note(ds, path)); } + notes.extend(rustgis_data::io::csv_system_note(path, ds.geometry_type, crs)); notes.extend(moved); // A Shapefile (`.shp`, or zipped to `.zip`) cuts field names to dBase's. let shapefile = matches!(ext.as_str(), "shp" | "zip"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 032b314420..1ca5a5b745 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2,6 +2,8 @@ use serde_json::{Value, json}; use crate::{Project, Session, sample}; +#[path = "tests/formats_out.rs"] +mod formats_out; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/scene_losses.rs"] mod scene_losses; diff --git a/crates/engine/src/tests/formats_out.rs b/crates/engine/src/tests/formats_out.rs new file mode 100644 index 0000000000..179f58d7af --- /dev/null +++ b/crates/engine/src/tests/formats_out.rs @@ -0,0 +1,97 @@ +//! Exports and write-backs in a layer's own coordinate system (#2032 C2f-1): GeoParquet with its +//! system, CSV x and y in a system asked for, GeoJSON published back in the system its legacy +//! `crs` member names, and the sync record kept over the layer's own coordinates. + +use crate::Session; +use serde_json::{Value, json}; + +/// A folder removed however the test ends. +struct Dir(std::path::PathBuf); +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn dir(name: &str) -> Dir { + let d = std::env::temp_dir().join(format!("rustgis-formats-out-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + Dir(d) +} + +const LV95: &str = r#"{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::2056"}},"features":[{"type":"Feature","properties":{"name":"Bern"},"geometry":{"type":"Point","coordinates":[2600000,1200000]}},{"type":"Feature","properties":{"name":"Thun"},"geometry":{"type":"Point","coordinates":[2614000,1178000]}}]}"#; + +/// A GeoJSON in LV95 with a legacy `crs` member is read, edited, published back in LV95 with its +/// member, and reads in sync after; its record holds the digest of its own coordinates, which +/// a project keeps. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_legacy_crs_geojson_publishes_back_in_its_system_and_stays_in_sync() { + let d = dir("geojson"); + let path = d.0.join("towns.geojson"); + std::fs::write(&path, LV95).unwrap(); + let mut s = Session::new(crate::Project::default()); + let id = s.run("layer.addData", &json!({"path": path, "name": "towns"})).unwrap()["layer"].as_u64().unwrap() as u32; + let state = |s: &mut Session| s.run("source.syncState", &json!({"layer": id})).unwrap()["state"].clone(); + let synced = s.map().layer(id).unwrap().synced.clone().unwrap(); + assert!(synced.native.is_some(), "{synced:?}"); + assert_eq!(state(&mut s), "inSync"); + s.run("edit.setValue", &json!({"layer": id, "row": 0, "field": "name", "value": "Bärn"})).unwrap(); + assert_eq!(state(&mut s), "edited"); + let out = s.run("source.publish", &json!({"layer": id})).unwrap(); + assert_eq!(out["published"], true, "{out}"); + let text: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + let want: Value = serde_json::from_str(&LV95.replace("\"Bern\"", "\"Bärn\"")).unwrap(); + assert_eq!(text, want); + assert_eq!(state(&mut s), "inSync"); + // Saved and opened again, the record still answers for the layer. + let (saved, _) = s.project.saved_text(None).unwrap(); + let again = crate::project::Project::from_json(&saved).unwrap(); + let l = again.maps[0].layers.iter().find(|l| l.name == "towns").unwrap(); + let record = l.synced.clone().unwrap(); + assert!(record.native.is_some()); + assert_eq!(record.digest_of(&l.dataset).unwrap(), record.digest()); +} + +/// The fixture saved with a record of the layer's own coordinates opens with the layer in sync +/// with it, and the same record without them (as a release before it saved it) does too. +#[test] +fn a_saved_record_of_the_layers_own_coordinates_is_read() { + let p = crate::project::Project::from_json(include_str!("../../../../schema/fixtures/held_synced.rgis")).unwrap(); + let l = &p.maps[0].layers[0]; + let record = l.synced.clone().unwrap(); + assert!(record.native.is_some()); + assert_eq!(record.digest_of(&l.dataset).unwrap(), record.digest()); + let older = rustgis_data::sync::Synced { native: None, ..record }; + assert_eq!(older.digest_of(&l.dataset).unwrap(), older.digest()); +} + +/// `share.exportLayer` writes a held layer's GeoParquet in its own system by default, and a CSV +/// in it when asked for, saying the CSV can't hold it; without asking, CSV stays WGS 84. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn exports_take_the_layers_own_system() { + let d = dir("exports"); + let path = d.0.join("towns.geojson"); + std::fs::write(&path, LV95).unwrap(); + let mut s = Session::new(crate::Project::default()); + s.run("layer.addData", &json!({"path": path, "name": "towns"})).unwrap(); + let parquet = d.0.join("towns.parquet"); + let out = s.run("share.exportLayer", &json!({"layer": "towns", "path": parquet})).unwrap(); + assert_eq!(out["crs"], "EPSG:2056", "{out}"); + let (back, _) = rustgis_data::io::read_path(&parquet).unwrap(); + assert_eq!(back.coord_crs(), rustgis_data::raster::Crs::from_epsg(2056).unwrap()); + let csv = d.0.join("towns.csv"); + let out = s.run("share.exportLayer", &json!({"layer": "towns", "path": csv})).unwrap(); + assert_eq!(out["crs"], "EPSG:4326"); + assert!(std::fs::read_to_string(&csv).unwrap().starts_with("longitude,latitude,name\n")); + let mark = s.notice_mark(); + let out = s.run("share.exportLayer", &json!({"layer": "towns", "path": csv, "crs": "EPSG:2056"})).unwrap(); + assert_eq!(out["crs"], "EPSG:2056"); + assert_eq!(std::fs::read_to_string(&csv).unwrap(), "x,y,name\n2600000,1200000,Bern\n2614000,1178000,Thun\n"); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|n| n.contains("EPSG:2056") && n.contains("can't say")), "{said:?}"); + // GeoJSON still refuses another system. + assert!(s.run("share.exportLayer", &json!({"layer": "towns", "path": d.0.join("t.geojson"), "crs": "EPSG:2056"})).is_err()); +} diff --git a/crates/ui-egui/src/syncmark.rs b/crates/ui-egui/src/syncmark.rs index 6bfb58bb58..cfcd24cd12 100644 --- a/crates/ui-egui/src/syncmark.rs +++ b/crates/ui-egui/src/syncmark.rs @@ -1,10 +1,10 @@ //! Edits not yet published (#1385): whether a layer read whole from a Shapefile or GeoJSON file //! holds rows its file lacks, for the Layers pane. The layer's rows are hashed -//! (`rustgis_data::sync::rows_digest`) on a thread of their own and compared with the record of +//! (`rustgis_data::sync::Synced::digest_of`) on a thread of their own and compared with the record of //! the last sync; the answer is kept until the rows, fields, coordinate system or record change. //! An edit copies the rows, so a changed layer is told by their allocation without a hash. The //! rows hashed are held only while their hash runs. A hash whose layer changed or went away is -//! cancelled (`rows_digest` looks at Cancel between rows), and no more hashes run at once than +//! cancelled (the digest looks at Cancel between rows), and no more hashes run at once than //! the thread setting allows (`rustgis_data::threads::max`), so opening a project of many large //! layers doesn't start one each. Nothing is counted: the mark is a status, not a run with //! progress. App state alone: nothing here dirties the project or adds an undo step. @@ -49,7 +49,7 @@ impl Drop for Job { } /// A thread's Cancel, as the readers' progress checks look at it: the hash thread's -/// (`rows_digest`), a download's read ([`crate::read_download`]). +/// (`Synced::digest_of`), a download's read ([`crate::read_download`]). pub(crate) struct Stop(pub(crate) Arc); impl rustgis_engine::data::progress::Probe for Stop { @@ -79,7 +79,7 @@ impl Entry { /// the previous state's. fn answer(&self) -> Option { match &self.digest { - Some(Ok(digest)) => Some(*digest != self.synced.rows), + Some(Ok(digest)) => Some(*digest != self.synced.digest()), // This state's hash failed: unknown, not the previous state's answer. Some(Err(_)) => None, None => self.shown, @@ -155,13 +155,13 @@ pub(crate) fn edited(app: &mut crate::RustGisApp, l: &Layer, ctx: &egui::Context } else { let (slot, stop) = (crate::Slot::default(), Arc::new(AtomicBool::new(false))); let (out, probe) = (slot.clone(), Stop(stop.clone())); - let dataset = l.dataset.clone(); + let (dataset, synced) = (l.dataset.clone(), entry.synced.clone()); let spawned = std::thread::Builder::new().name("Edits not published".into()).spawn(move || { let _probe = rustgis_engine::data::progress::install(Some(Arc::new(probe))); // A panic lands as an answer too, so it never holds the turn. Neither this nor a - // refused thread below can be brought about in a test: `rows_digest` has no panic + // refused thread below can be brought about in a test: `digest_of` has no panic // path, and the OS refuses threads only under load. - let digest = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::data::sync::rows_digest(&dataset))) + let digest = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| synced.digest_of(&dataset))) .map_err(|_| "the hash stopped".to_string()) .and_then(|d| d.map_err(|e| e.to_string())); *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(digest); @@ -192,7 +192,7 @@ pub(crate) fn hashed(app: &mut crate::RustGisApp, l: &Layer, ctx: &egui::Context edited(app, l, ctx); let e = app.syncmark.entries.get(&(app.session.map().instance_id(), l.instance_id()))?; match e.digest.as_ref()? { - Ok(digest) => Some(*digest != e.synced.rows), + Ok(digest) => Some(*digest != e.synced.digest()), Err(_) => None, } } @@ -234,7 +234,7 @@ mod tests { rows: Weak::new(), fields: Vec::new(), crs: None, - synced: Synced { files: FileSync { files: Vec::new() }, rows: 7 }, + synced: Synced { files: FileSync { files: Vec::new() }, rows: 7, native: None }, digest: None, job: Some(Job { slot, stop: Arc::new(AtomicBool::new(false)), current }), retry: None, diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index edc77d0d8e..72d930ea76 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -688,7 +688,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | --- | --- | --- | | GeoJSON (`.geojson`, `.json`), CSV | Data › Export (`share.exportLayer`) | The Export Features dialog picks the format; the chosen extension is appended when needed. In the web app it downloads any vector format below except GeoPackage and FlatGeobuf (a Shapefile as one zip). A streamed layer exports its whole source: on the desktop, to GeoJSON, CSV, FlatGeobuf, GeoPackage or GeoParquet a chunk at a time with no limit on its size (a GeoParquet source's row groups are read whole, so on the desktop each holds at most 16,777,216 rows; a layer read in place from the GeoPackage it goes into is read whole first), otherwise loaded whole (see [Streamed layers](data.md)); remote sources on the web must be downloaded first. | | GeoPackage | Data › Export to `.gpkg` (desktop) | A new file with one feature table (an attributes table for a layer without geometry) in the layer's coordinate system (see below), with an R-tree and GeoPackage 1.4 triggers to maintain it. An existing destination is refused unless the export adds a table to it or replaces one of its feature or attribute tables (`mode`, see [Exporting](sharing.md)), leaving its other tables as they were. A layer holding more than one kind of geometry (a GeoJSON of points and polygons, say) is written whole, in a `GEOMETRY` column, which holds any kind; a layer of one kind gets that kind's column. Unique feature ids that fit signed 64-bit integers are kept; otherwise SQLite assigns new ids. Date fields are written as `DATE` and date-time fields as `DATETIME` (`2026-03-05T12:30:00.000Z`): one with a zone in UTC, as GeoPackage asks, with a notice counting those that had another offset (the moment is kept, the offset isn't); one without a zone without the `Z`. The table's `last_change` is the time of the export; with `SOURCE_DATE_EPOCH` set (whole seconds since 1970, as reproducible builds use it) it is that time instead, so the same export run twice writes the same file. | -| GeoParquet (`.parquet`, `.geoparquet`) | Data › Export | GeoParquet 1.1: WKB geometry in WGS 84, Zstd level 9 compression, row groups of up to 65,536 features and a `bbox` covering column with byte-stream-split encoding. The covering keeps spatial range reads available; compression favours smaller files over export speed. Reading the file needs Zstd support, and reading its `bbox` column needs byte-stream-split support, which current GDAL, PyArrow and DuckDB have and some older readers lack (some of those refuse the file). A standalone table without geometry writes plain Parquet. | +| GeoParquet (`.parquet`, `.geoparquet`) | Data › Export | GeoParquet 1.1: WKB geometry in the layer's coordinate system when it has an EPSG code (given as PROJJSON in the file), else WGS 84, Zstd level 9 compression, row groups of up to 65,536 features and a `bbox` covering column with byte-stream-split encoding. The covering keeps spatial range reads available; compression favours smaller files over export speed. Reading the file needs Zstd support, and reading its `bbox` column needs byte-stream-split support, which current GDAL, PyArrow and DuckDB have and some older readers lack (some of those refuse the file). A standalone table without geometry writes plain Parquet. | | Shapefile | Data › Export to `.shp` (or `.zip` for the files zipped) | Writes `.shp`, `.shx`, `.dbf`, `.prj` (the coordinate system, see below) and `.cpg` (UTF-8). Field names are cut to 10 bytes (made unique ignoring case, and reported), text to at most 254 bytes, and numbers that do not fit their dBase field are left empty. Date fields are written as dBase dates; date-time fields as ISO 8601 text, since dBase has no date-time field other programs read (said in a notice). Export notices count shortened text, non-null values left empty (including incompatible types), and numbers rounded to the field's precision, and name the affected source fields; features without geometry, and lines of a single point, are left out (and reported). An export in longitude/latitude leaves out vertices with a missing (NaN) or infinite coordinate; an export in a projected system refuses any coordinate that doesn't project to a finite one, naming its feature. In either, line parts and polygon rings too short to draw (fewer than 2 or 3 drawable vertices, whether written so or left so) and the holes of a polygon whose outer ring goes are left out. The export counts the vertices, and the parts or rings, in the features it writes; a feature with nothing drawable left is counted with the features left out. | | FlatGeobuf | Data › Export to `.fgb` | In the layer's coordinate system (see below), with a spatial index. Features are written in spatial-index order, so record order can change; keep an attribute key to match records after export. Features without geometry are left out (and reported). Desktop only: the writer needs a temporary file, which the browser doesn't have. | | KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ write non-null attributes to extended data. The export reports fields omitted because they have no non-null values in the placemarks written. Reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept, and the export names them. Features without geometry are left out. | @@ -709,14 +709,19 @@ a spreadsheet formula is prefixed with an apostrophe, including signed zero-padd integer codes such as `-007` and signed numbers that exceed those precision limits. The export reports the number of prefixed values and the affected fields. -GeoPackage, Shapefile and FlatGeobuf exports default to the layer's original coordinate system. +GeoPackage, Shapefile, FlatGeobuf and GeoParquet exports default to the layer's original coordinate system. A system with an EPSG code is written by its code; one without (a Shapefile whose `.prj` names State Plane by its parameters, say) is written by its WKT definition, which a GeoPackage and a FlatGeobuf carry too. A system WKT can't describe goes into a Shapefile in its own coordinates -without a `.prj`, and into a GeoPackage or FlatGeobuf in WGS 84; a notice says which. A layer made in RustGIS defaults to WGS 84. +without a `.prj`, and into a GeoPackage or FlatGeobuf in WGS 84; a notice says which. GeoParquet +takes a system by its EPSG code only, which every reader (and older RustGIS releases) can read; a +system without one is written in WGS 84, with a notice. A layer made in RustGIS defaults to WGS 84. `share.exportLayer` takes `"crs"` to choose -another, such as `{"layer": "Parcels", "path": "parcels.gpkg", "crs": "EPSG:4647"}`. GeoJSON, KML, -GPX, GeoParquet and CSV are always written in WGS 84. +another, such as `{"layer": "Parcels", "path": "parcels.gpkg", "crs": "EPSG:4647"}`. GeoJSON, KML +and GPX are always written in WGS 84. CSV is written in WGS 84 (`longitude` and `latitude`) unless +a `"crs"` is given: a point layer's coordinates then go in `x` and `y` columns (`easting` and +`northing` when fields have those names) in that system, and a notice says which system it is, +since a CSV file can't; give the same system when adding the file back. RustGIS keeps x and y only. When a source has Z or M values (heights or measures), adding it says they were dropped, and exporting or converting the layer (or exporting a standalone table that diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 55cdee89fa..0adad0fe23 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -490,9 +490,11 @@ For `.geojson`, publish also checks that the source is unchanged, that it still at the last sync, and that both the original and the edited layer survive a read/write. It keeps the document's kind (FeatureCollection, Feature or bare geometry), a collection's name, and feature ids. Ordinary integer coordinate text stays integer text when the value is unchanged. -Whitespace and member order may change. +Whitespace and member order may change. A legacy `crs` member is kept, and the layer is written +back in the system it names (Swiss LV95 coordinates stay LV95); a layer whose coordinate system +was defined again since is refused. -Publish refuses a rewrite that would change foreign members, a legacy `crs` member, Z values, +Publish refuses a rewrite that would change foreign members, Z values, a geometry the reader simplifies, nested properties it reads as text, duplicate object keys, number text the writer would spell differently (such as `1.00`, `1E3`, or a decimal below 0.00001 such as `0.000004`, which it writes `4e-6`), a property that mixes numbers and text diff --git a/schema/fixtures/held_synced.rgis b/schema/fixtures/held_synced.rgis new file mode 100644 index 0000000000..9876268cad --- /dev/null +++ b/schema/fixtures/held_synced.rgis @@ -0,0 +1,226 @@ +{ + "requires": [ + "native-coordinates" + ], + "format": 2, + "name": "A layer kept in its own coordinate system, with a record of its file", + "maps": [ + { + "name": "Map", + "layers": [ + { + "id": 1, + "name": "Wells", + "visible": true, + "dataset": { + "name": "Wells", + "geometry_type": "Point", + "fields": [ + { + "name": "name", + "ty": "Text", + "alias": null + }, + { + "name": "n", + "ty": "Integer", + "alias": null + } + ], + "features": [ + { + "id": 1, + "geometry": { + "Point": { + "x": 683944.5332506967, + "y": 5397122.83486662 + } + }, + "attrs": [ + { + "Text": "w0" + }, + { + "Int": 0 + } + ] + }, + { + "id": 2, + "geometry": { + "Point": { + "x": 683908.0734874264, + "y": 5398234.2945844 + } + }, + "attrs": [ + { + "Text": "w1" + }, + { + "Int": 1 + } + ] + } + ], + "source": "wells.geojson", + "crs": { + "Epsg": 32632 + }, + "held_in": { + "Epsg": 32632 + } + }, + "renderer": { + "Single": { + "fill": [ + 224, + 123, + 57, + 255 + ], + "stroke": [ + 255, + 255, + 255, + 255 + ], + "stroke_width": 1.0, + "size": 7.0, + "marker": "Circle" + } + }, + "labels": { + "enabled": false, + "field": "name", + "size": 10.0, + "color": [ + 43, + 43, + 43, + 255 + ], + "halo": true, + "bold": false, + "min_scale": null, + "max_scale": null, + "closest": null, + "farthest": null, + "placement": "Auto" + }, + "transparency": 0.0, + "min_scale": null, + "max_scale": null, + "definition_query": null, + "selection": [], + "expanded": true, + "selectable": true, + "graphics": false, + "blend": "Normal", + "mask": null, + "display_filters": [], + "aggregation": null, + "extrusion": null, + "priority": 0, + "geometry_rev": 0, + "synced": { + "files": { + "files": [ + [ + "wells.geojson", + { + "len": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + ] + ] + }, + "rows": 14795928903904870448, + "native": 12000928614795168968 + } + } + ], + "basemap": "Paper", + "camera": { + "center": { + "x": 0.0, + "y": 2000000.0 + }, + "res": 30000.0, + "bearing": 0.0, + "pitch": 0.0 + }, + "bookmarks": [], + "graticule": true, + "projection": "WebMercator", + "popup_mode": "Topmost", + "label_display": { + "paused": false, + "locked": false, + "show_unplaced": false + }, + "editing": { + "relationships": [], + "snapping": { + "enabled": false, + "tolerance_px": 10.0, + "vertex": true, + "edge": true, + "end": true + }, + "topology": [], + "settings": { + "enabled": true, + "show_vertices": true, + "elevation": "None", + "ground_to_grid": null + } + }, + "swipe": null, + "view": { + "effects": { + "stars": true, + "sun_time": null, + "weather": "None", + "vignette": false, + "edges": false, + "tilt_shift": false, + "grain": false, + "brightness": 0.0, + "contrast": 0.0, + "saturation": 0.0, + "sepia": 0.0 + }, + "wireframe": false, + "clip_distance": null, + "terrain": null + }, + "animation": [], + "next_layer_id": 2 + } + ], + "active_map": 0, + "tables": [], + "next_table_id": 1, + "gp_history": [], + "layouts": [], + "folders": [], + "styles": [], + "ramps": [], + "tasks": [], + "gp_env": { + "extent": null, + "cell_size": null + }, + "models": [], + "workspaces": [], + "link_views": false, + "jobs": [], + "offline_areas": [], + "reports": [], + "presentations": [], + "notebooks": [], + "dl_models": [], + "shared": [], + "data_stores": [] +} From a984ee2d7e14bf0f1cc13f56a3be32320dcf67bc Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 16:21:42 +0100 Subject: [PATCH 2/2] Review fixes: older records publish in the file's own system, CSV loss notes in the asked-for system (#2032 C2f-1) --- crates/data/src/io.rs | 8 +++++- crates/data/src/source/tests.rs | 11 ++++++++ crates/engine/src/cmd/publish.rs | 20 +++++++++---- crates/engine/src/cmd/share.rs | 2 +- crates/engine/src/tests/formats_out.rs | 39 ++++++++++++++++++++++++++ docs/user-guide/data-formats.md | 13 +++++---- 6 files changed, 80 insertions(+), 13 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 7b87244a61..363fe0de2c 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4971,7 +4971,13 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option let mut notes = match ext { "csv" => { // Of the coordinates the file is written in: longitude/latitude, or another system's. - let ds = if crs == Crs::LonLat { ds.in_lonlat().map_err(DataError::of_conversion)? } else { std::borrow::Cow::Borrowed(ds) }; + let ds = if crs == Crs::LonLat { + ds.in_lonlat().map_err(DataError::of_conversion)? + } else if crs == ds.coord_crs() { + std::borrow::Cow::Borrowed(ds) + } else { + std::borrow::Cow::Owned(project(ds, crs)?) + }; let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?; let mut notes = losses.notes(&ds.fields, target); notes.extend(losses.coordinates_note_in(&ds.fields, target, crs)); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 22086d64ff..1f7baf1ee1 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3240,6 +3240,17 @@ fn a_csv_export_takes_x_and_y_in_a_system_asked_for() { assert!(crate::io::to_csv_in(&every, lv95).unwrap().starts_with("x_1,y_1,")); let notes = crate::io::export_losses_notes_in(&every, "csv", None, "xy.csv", lv95).unwrap(); assert!(notes.iter().any(|n| n.contains("'x_1' and 'y_1'")), "{notes:?}"); + // Into a geographic system other than WGS 84: longitude and latitude columns, and no note + // of unusable positions, which are counted on the coordinates written. + // Fields named x and y are a pair reading could take instead, which a note names when rows + // lack a usable longitude/latitude: counted on LV95's metres, every row would. + let etrs89 = Crs::from_epsg(4258).unwrap(); + let (bytes, _) = crate::io::write_bytes_in(&ds, "csv", etrs89).unwrap(); + assert!(String::from_utf8(bytes).unwrap().starts_with("longitude,latitude,name\n7.43")); + assert!(crate::io::export_losses_notes_in(&ds, "csv", None, "pts.csv", etrs89).unwrap().is_empty()); + assert_eq!(xy.coord_crs(), lv95); + let notes = crate::io::export_losses_notes_in(&xy, "csv", None, "xy.csv", etrs89).unwrap(); + assert!(notes.is_empty(), "{notes:?}"); } /// A catalog index as AlphaEarth's is (a `bbox` struct, a nested `assets.data.href`), and patch diff --git a/crates/engine/src/cmd/publish.rs b/crates/engine/src/cmd/publish.rs index 0b256b4a96..a391ab7bf3 100644 --- a/crates/engine/src/cmd/publish.rs +++ b/crates/engine/src/cmd/publish.rs @@ -62,9 +62,14 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result Result Result Vec { C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) - .params(r#"{"layer"?, "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "crs"?: "EPSG:… (or WKT) for a GeoPackage, Shapefile or FlatGeobuf, EPSG:… for a GeoParquet (default: the system the layer was read in, else EPSG:4326), or for a CSV's x and y columns (default: EPSG:4326)", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the layer's name)"} Applies the layer's definition query and reports how many features it leaves out."#), + .params(r#"{"layer"?, "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "crs"?: "EPSG:… (or WKT) for a GeoPackage, Shapefile or FlatGeobuf, EPSG:… for a GeoParquet (default: the system the layer was read in, else EPSG:4326), or for a CSV's coordinate columns, x and y in a projected one (default: EPSG:4326)", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the layer's name)"} Applies the layer's definition query and reports how many features it leaves out."#), C::new("share.exportTable", "Export Table", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportTable")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params( r#"{"table": name|id (a standalone table), "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the table's name)", "sort"?: [{"field": name, "descending"?: false}], "limit"?: "nonnegative integer: keep the first N rows after sorting"}"#, diff --git a/crates/engine/src/tests/formats_out.rs b/crates/engine/src/tests/formats_out.rs index 179f58d7af..320f2742fe 100644 --- a/crates/engine/src/tests/formats_out.rs +++ b/crates/engine/src/tests/formats_out.rs @@ -95,3 +95,42 @@ fn exports_take_the_layers_own_system() { // GeoJSON still refuses another system. assert!(s.run("share.exportLayer", &json!({"layer": "towns", "path": d.0.join("t.geojson"), "crs": "EPSG:2056"})).is_err()); } + +/// A Shapefile layer in LV95 that a project saved before RustGIS kept a file's own coordinates +/// holds in longitude/latitude, with a record that has no digest of its own coordinates, is +/// published: it takes the file's rows in LV95 with the system they're in, and reads in sync. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_older_projects_layer_takes_the_files_own_system_when_published() { + let d = dir("older"); + let geojson = d.0.join("towns.geojson"); + std::fs::write(&geojson, LV95).unwrap(); + let mut s = Session::new(crate::Project::default()); + s.run("layer.addData", &json!({"path": geojson, "name": "source"})).unwrap(); + let shp = d.0.join("towns.shp"); + s.run("share.exportLayer", &json!({"layer": "source", "path": shp})).unwrap(); + let id = s.run("layer.addData", &json!({"path": shp, "name": "towns"})).unwrap()["layer"].as_u64().unwrap() as u32; + let lv95 = rustgis_data::raster::Crs::from_epsg(2056).unwrap(); + // As an older release held it: in longitude/latitude, its record of those rows only. + { + let l = s.map_mut().layer_mut(id).unwrap(); + assert_eq!(l.dataset.coord_crs(), lv95); + l.dataset = rustgis_data::io::project(&l.dataset, rustgis_data::raster::Crs::LonLat).unwrap(); + l.touch_geometry(); + let rows = rustgis_data::sync::rows_digest(&l.dataset).unwrap(); + let files = l.synced.clone().unwrap().files; + l.synced = Some(rustgis_data::sync::Synced { files, rows, native: None }); + } + let state = |s: &mut Session| s.run("source.syncState", &json!({"layer": id})).unwrap()["state"].clone(); + assert_eq!(state(&mut s), "inSync"); + s.run("edit.setValue", &json!({"layer": id, "row": 0, "field": "name", "value": "Bärn"})).unwrap(); + let out = s.run("source.publish", &json!({"layer": id})).unwrap(); + assert_eq!(out["published"], true, "{out}"); + let l = s.map().layer(id).unwrap(); + assert_eq!(l.dataset.coord_crs(), lv95, "the file's rows come with the system they're in"); + let first = l.dataset.features.iter().next().unwrap().geometry.clone().unwrap(); + let rustgis_data::Geometry::Point(c) = first else { panic!("{first:?}") }; + assert!((c.x - 2_600_000.0).abs() < 1e-6 && (c.y - 1_200_000.0).abs() < 1e-6, "{c:?}"); + assert!(l.synced.as_ref().unwrap().native.is_some()); + assert_eq!(state(&mut s), "inSync"); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 72d930ea76..0ed1c15485 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -714,14 +714,17 @@ A system with an EPSG code is written by its code; one without (a Shapefile whos State Plane by its parameters, say) is written by its WKT definition, which a GeoPackage and a FlatGeobuf carry too. A system WKT can't describe goes into a Shapefile in its own coordinates without a `.prj`, and into a GeoPackage or FlatGeobuf in WGS 84; a notice says which. GeoParquet -takes a system by its EPSG code only, which every reader (and older RustGIS releases) can read; a -system without one is written in WGS 84, with a notice. A layer made in RustGIS defaults to WGS 84. +takes a system by its EPSG code only, which older RustGIS releases read too; a system without one +is written in WGS 84, with a notice. A reader that ignores the file's `crs` takes projected +coordinates for degrees. A layer made in RustGIS defaults to WGS 84. `share.exportLayer` takes `"crs"` to choose another, such as `{"layer": "Parcels", "path": "parcels.gpkg", "crs": "EPSG:4647"}`. GeoJSON, KML and GPX are always written in WGS 84. CSV is written in WGS 84 (`longitude` and `latitude`) unless -a `"crs"` is given: a point layer's coordinates then go in `x` and `y` columns (`easting` and -`northing` when fields have those names) in that system, and a notice says which system it is, -since a CSV file can't; give the same system when adding the file back. +a `"crs"` is given: a point layer's coordinates are then written in that system, in `longitude` +and `latitude` columns for a geographic one, and for a projected one in `x` and `y`, or `easting` +and `northing` when fields have the names `x` or `y`, or `x_1` and `y_1` when fields have all +four. A notice says which system it is, since a CSV file can't; give the same system when adding +the file back. RustGIS keeps x and y only. When a source has Z or M values (heights or measures), adding it says they were dropped, and exporting or converting the layer (or exporting a standalone table that