diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 5e98f083a8..7ba4810486 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -226,11 +226,24 @@ impl Engine { 1 => session.warn(format!("{name}: 1 row couldn't be read and was left out")), n => session.warn(format!("{name}: {n} rows couldn't be read and were left out")), } + // A Z/M loss this export says from its read; one said only when the layer opened + // isn't said here again, so the export's own note says it. + let mut read_zm = false; for message in report.messages.into_iter().filter(|message| !opened_notes.contains(message)) { + read_zm |= message.loss == Some(rustgis_engine::data::loss::LossCode::DroppedZm); session.say(message); } - if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{name} as GeoJSON")) { - session.notify(note, false); + // What GeoJSON, in WGS 84, lacks of it, as an export to GeoJSON says it; a Z/M loss + // the read just said isn't said again, as the file writer leaves it + // (`share::coalesce_read_zm`). + let target = format!("{name} as GeoJSON"); + let generic = rustgis_engine::data::zm_export_note([&ds], &target).filter(|_| read_zm); + for note in + rustgis_engine::data::export_notes([(&ds, ds.lonlat_extent())], &target, rustgis_engine::data::raster::Crs::LonLat) + { + if generic.as_ref() != Some(¬e) { + session.say(note); + } } // GeoJSON is longitude/latitude, whatever system the source holds its coordinates in; // a feature with a place that can't be given there is in it without its geometry. @@ -243,9 +256,17 @@ impl Engine { if !selected { let (lonlat, unplaced) = found.dataset.in_lonlat_leaving_out()?; let text = rustgis_engine::data::io::to_geojson(&lonlat).to_string(); - let note = rustgis_engine::data::zm_export_note([&found.dataset], &format!("{} as GeoJSON", found.name)); - let unplaced = rustgis_engine::data::unplaced_note(&format!("{} as GeoJSON", found.name), &found.name, unplaced); - for note in note.into_iter().chain(unplaced) { + let target = format!("{} as GeoJSON", found.name); + let notes = rustgis_engine::data::export_notes( + [(&found.dataset, found.dataset.lonlat_extent())], + &target, + rustgis_engine::data::raster::Crs::LonLat, + ); + let unplaced = rustgis_engine::data::unplaced_note(&target, &found.name, unplaced); + for note in notes { + session.say(note); + } + if let Some(note) = unplaced { session.notify(note, false); } return Ok(text); @@ -272,8 +293,13 @@ impl Engine { ds.push(g, r.values().cloned().collect()); } let text = rustgis_engine::data::io::to_geojson(&ds).to_string(); - if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{} as GeoJSON", ds.name)) { - session.notify(note, false); + // The selected rows lack what the layer's do: said of the layer, whose system and body + // the copy in longitude/latitude no longer holds, at the selected rows' places. + let target = format!("{} as GeoJSON", ds.name); + for note in + rustgis_engine::data::export_notes([(&found.dataset, ds.extent())], &target, rustgis_engine::data::raster::Crs::LonLat) + { + session.say(note); } if let Some(note) = rustgis_engine::data::unplaced_note(&format!("{} as GeoJSON", ds.name), &ds.name, unplaced) { session.notify(note, false); diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index b5e51e6c7c..8aed10c6d9 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1751,7 +1751,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 && let Some((_, report)) = layers.first_mut() @@ -2650,8 +2653,11 @@ mod tests { assert_eq!(l[0].0.features.len(), MAX_TOTAL_VERTICES / 200_000); assert!(l[0].0.zm_dropped); assert_eq!( - l[0].1.messages.iter().filter(|m| m.contains("varying Z")).collect::>(), - [&format!("{} features lost varying Z coordinates; only the elevation attribute is kept", l[0].0.features.len())] + l[0].1.messages.iter().filter(|m| m.contains("varying Z")).map(|m| (m.as_str(), m.loss)).collect::>(), + [( + &*format!("{} features lost varying Z coordinates; only the elevation attribute is kept", l[0].0.features.len()), + Some(crate::loss::LossCode::DroppedZm) + )] ); assert!(l[0].1.messages.iter().any(|m| m.contains("coordinates")), "{:?}", l[0].1.messages); } @@ -3066,7 +3072,10 @@ mod tests { } else { vec![] }; - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); + assert!( + report.messages.iter().filter(|m| m.contains("varying Z")).all(|m| m.loss == Some(crate::loss::LossCode::DroppedZm)) + ); let Some(Geometry::Line(parts)) = &ds.features[0].geometry else { panic!("spline line") }; let (start_xy, end_xy) = if tilted { (Coord::new(0.1, 0.0), Coord::new(end.parse().unwrap(), 3.0)) @@ -3139,7 +3148,8 @@ mod tests { assert_eq!(ds.zm_dropped, tilted); assert_eq!(report.skipped, 0); let expected = if tilted { vec!["1 feature lost varying Z coordinates; only the elevation attribute is kept"] } else { vec![] }; - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); + assert!(report.messages.iter().filter(|m| m.contains("varying Z")).all(|m| m.loss == Some(crate::loss::LossCode::DroppedZm))); } } @@ -3190,7 +3200,8 @@ mod tests { assert_eq!(ds.zm_dropped, varying, "rotation={rotation}: {:?}", report.messages); let expected = if varying { vec!["1 feature lost varying Z coordinates; only the elevation attribute is kept"] } else { vec![] }; - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); + assert!(report.messages.iter().filter(|m| m.contains("varying Z")).all(|m| m.loss == Some(crate::loss::LossCode::DroppedZm))); assert_eq!(report.skipped, 0); let Some(Geometry::Line(parts)) = &ds.features[0].geometry else { panic!("rotated line") }; assert_eq!(parts[0].first(), Some(&Coord::new(0.0, 0.0))); @@ -3240,7 +3251,11 @@ mod tests { assert_eq!(ds.value(0, 8), &Value::Float(0.0)); assert!(ds.zm_dropped, "start={start}, offset={offset}"); assert_eq!(report.skipped, 0); - assert_eq!(report.messages, ["1 feature lost varying Z coordinates; only the elevation attribute is kept"]); + assert_eq!( + report.messages.texts().collect::>(), + ["1 feature lost varying Z coordinates; only the elevation attribute is kept"] + ); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedZm)); } } @@ -3289,7 +3304,8 @@ mod tests { ); assert_eq!(report.messages.len(), if end == "9" { 2 } else { 1 }); if end == "9" { - assert_eq!(report.messages[1], "1 feature lost varying Z coordinates; only the elevation attribute is kept"); + assert_eq!(report.messages[1].as_str(), "1 feature lost varying Z coordinates; only the elevation attribute is kept"); + assert_eq!(report.messages[1].loss, Some(crate::loss::LossCode::DroppedZm)); } } } diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 844b872b9d..5eb31c3f6c 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -151,10 +151,10 @@ impl Losses { } /// What they say, one message per kind (as [`read`] says them). - pub fn messages(&self) -> Vec { - let mut out = Vec::new(); + pub fn messages(&self) -> crate::loss::Notes { + let mut out = crate::loss::Notes::new(); if self.no_crs { - out.push("the answer names no coordinate system; coordinates are read as longitude/latitude".into()); + out.push("the answer names no coordinate system; coordinates are read as longitude/latitude"); } if self.unreadable > 0 { out.push(format!("{} values don't fit their field's type and are left empty", self.unreadable)); @@ -175,7 +175,7 @@ impl Losses { )); } if self.with_zm > 0 { - out.push(crate::zm_note(Some(self.with_zm as u64))); + out.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(self.with_zm as u64)))); } out } diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 5243e46fd7..045da4bb64 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -163,7 +163,7 @@ fn z_and_m_are_dropped_and_said_even_when_they_are_all_alike() { let (ds, report) = read(&bytes, "t").unwrap(); assert_eq!(ds.features[0].geometry, Some(Geometry::Point(c(4.0, 6.0)))); assert!(ds.zm_dropped); - assert_eq!(report.messages, [crate::zm_note(Some(2))]); + assert_eq!(report.messages, [crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(2)))]); } #[test] @@ -203,7 +203,7 @@ fn a_page_read_within_a_limit_counts_what_the_features_kept_lost() { ]); let page = read_page_within(&bytes, "t", 1).unwrap(); assert_eq!((page.dataset.features.len(), page.left_out, page.losses.with_zm), (1, 2, 1)); - assert_eq!(page.losses.messages(), [crate::zm_note(Some(1))]); + assert_eq!(page.losses.messages(), [crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(1)))]); assert!(page.report.messages.is_empty(), "the losses are said apart: {:?}", page.report.messages); // Within a limit it doesn't reach, the whole page. let page = read_page_within(&bytes, "t", 3).unwrap(); diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 9a3f67f2f1..d77095b25a 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -182,8 +182,11 @@ fn a_streamed_web_mercator_export_counts_what_it_writes_at_85_degrees() { } } assert_eq!( - crate::web_mercator_moved_note("polar.gpkg", "polar", 3).as_deref(), - Some("polar.gpkg: 3 vertices of polar are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends") + crate::web_mercator_moved_note("polar.gpkg", "polar", 3), + Some(crate::loss::Note::loss( + crate::loss::LossCode::ChangedPosition, + "polar.gpkg: 3 vertices of polar are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends" + )) ); assert_eq!(crate::web_mercator_moved_note("polar.gpkg", "polar", 0), None); let _ = std::fs::remove_dir_all(d); diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 972b92a18b..1cc55b05ab 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -745,7 +745,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } if zm > 0 { ds.zm_dropped = true; - rep.messages.push(format!("{}: {}", ds.name, crate::zm_note(Some(zm as u64)))); + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedZm, + format!("{}: {}", ds.name, crate::zm_note(Some(zm as u64))), + )); } if let Some(n) = crate::source::null_text_note(&ds.fields, &null_text) { rep.messages.push(format!("{}: {n}", ds.name)); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 819eaf3e44..93a0b9c5b8 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -6623,9 +6623,9 @@ mod tests { assert_eq!( rep.messages, [ - crate::zm_note(Some(1)).as_str(), - "1 rows had geometry that isn't readable WKT", - "1 rows have another kind of geometry than the layer's polyline" + crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(1))), + "1 rows had geometry that isn't readable WKT".into(), + "1 rows have another kind of geometry than the layer's polyline".into() ] ); // A named WKT column with a given system. @@ -6674,7 +6674,7 @@ mod tests { assert_eq!( report.messages, [ - crate::zm_note(Some(1)), + crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(1))), "1 WKT value in 'wkt' lost later non-empty geometry-collection members; only the first non-empty member is kept".into() ] ); @@ -6791,8 +6791,11 @@ mod tests { other.name = "wells".into(); let flat = Dataset::new("roads", GeometryType::Polyline, vec![]); assert_eq!( - crate::zm_export_note([&ds, &flat, &other], "site.zip").as_deref(), - Some("site.zip: its geometry has no Z or M values for 2 layers (pts, wells), which were dropped when they were read") + crate::zm_export_note([&ds, &flat, &other], "site.zip"), + Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedZm, + "site.zip: its geometry has no Z or M values for 2 layers (pts, wells), which were dropped when they were read" + )) ); assert_eq!(crate::zm_export_note([&flat], "roads.zip"), None); @@ -6815,6 +6818,7 @@ mod tests { assert!(rep.messages.is_empty(), "{:?}", rep.messages); assert_eq!( crate::export_notes([(&utm, ext(&utm)), (&lonlat, ext(&lonlat))], "out.geojson", Crs::LonLat), + // Told by the extent alone: said without a code. [ "out.geojson: the coordinates of utm aren't longitude/latitude, so they're out of place: define its projection and export again" ] @@ -6833,9 +6837,12 @@ mod tests { let saved: Dataset = serde_json::from_value(serde_json::to_value(&parcels).unwrap()).unwrap(); assert_eq!( crate::export_notes([(&saved, ext(&saved))], "parcels.geojson", Crs::LonLat), - [format!( - "parcels.geojson: the positions of parcels are approximate, possibly a few hundred metres off: its coordinate system ({}) has no shift to WGS 84", - nad27.label() + [crate::loss::Note::loss( + crate::loss::LossCode::ApproximatedDatum, + format!( + "parcels.geojson: the positions of parcels are approximate, possibly a few hundred metres off: its coordinate system ({}) has no shift to WGS 84", + nad27.label() + ) )] ); // Written back in NAD 27, the positions come back as they were read. @@ -6847,9 +6854,10 @@ mod tests { shifted.crs = Some(Crs::Epsg(26716)); assert_eq!( crate::export_notes([&parcels, &roads, &shifted].map(|ds| (ds, ext(ds))), "map.json", Crs::LonLat), - [ + [crate::loss::Note::loss( + crate::loss::LossCode::ApproximatedDatum, "map.json: the positions of 2 layers (parcels, roads) are approximate, possibly a few hundred metres off: their coordinate systems have no shift to WGS 84" - ] + )] ); } @@ -6886,7 +6894,10 @@ mod tests { assert_eq!(merc.features[0].geometry, Some(Geometry::Point(lonlat_to_merc(c(10.0, MAX_LAT))))); assert_eq!( crate::export_notes([(&polar, ext(&polar))], "polar.shp", Crs::WebMercator), - ["polar.shp: 3 vertices of polar are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends"] + [crate::loss::Note::loss( + crate::loss::LossCode::ChangedPosition, + "polar.shp: 3 vertices of polar are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends" + )] ); // In another system, or within 85.05°: nothing. for crs in [Crs::LonLat, Crs::Epsg(32631)] { @@ -6898,13 +6909,17 @@ mod tests { let one = layer("one", &[c(0.0, 86.0)]); assert_eq!( crate::export_notes([(&one, ext(&one))], "one.gpkg", Crs::WebMercator), - ["one.gpkg: 1 vertex of one is beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends"] + [crate::loss::Note::loss( + crate::loss::LossCode::ChangedPosition, + "one.gpkg: 1 vertex of one is beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends" + )] ); assert_eq!( crate::export_notes([(&polar, ext(&polar)), (&within, ext(&within)), (&one, ext(&one))], "map.gpkg", Crs::WebMercator), - [ + [crate::loss::Note::loss( + crate::loss::LossCode::ChangedPosition, "map.gpkg: 4 vertices of 2 layers (polar, one) are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends" - ] + )] ); // A streamed layer's features are only those in view: its source's extent tells, without // a count, and only that it reaches beyond, as a source can declare a wider one than its @@ -6921,9 +6936,10 @@ mod tests { // A layer counted and a window told by its extent: one notice, saying both. assert_eq!( crate::export_notes([(&polar, ext(&polar)), (&window, Extent::new(-180.0, -90.0, 180.0, 84.0))], "map.gpkg", Crs::WebMercator), - [ + [crate::loss::Note::loss( + crate::loss::LossCode::ChangedPosition, "map.gpkg: 3 vertices of polar are beyond 85.05° north or south, and written at 85.05°; the extent of tiles reaches beyond 85.05° north or south, and what lies beyond is written at 85.05°, where Web Mercator ends" - ] + )] ); // A layer without features that isn't a window (a raster layer's, or a streamed layer's // written a chunk at a time, whose export counts as it writes) has no extent tell. @@ -6962,8 +6978,11 @@ mod tests { { assert_eq!( crate::export_notes([(ds, ext(ds))], &target, Crs::WebMercator), - [format!( - "{target}: {n} vertices of {name} are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends" + [crate::loss::Note::loss( + crate::loss::LossCode::ChangedPosition, + format!( + "{target}: {n} vertices of {name} are beyond 85.05° north or south, and written at 85.05°, where Web Mercator ends" + ) )] ); } diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 08fe365ae0..9f61383e0d 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -758,7 +758,10 @@ impl Reader { } if zm_rows > 0 { ds.zm_dropped = true; - report.messages.push(format!("{}: {}", ds.name, crate::zm_note(Some(zm_rows as u64)))); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedZm, + format!("{}: {}", ds.name, crate::zm_note(Some(zm_rows as u64))), + )); } let styles = used.into_iter().filter_map(|id| self.styles.get(&id).map(|s| (id, *s))).collect(); out.push(Layer { dataset: ds, report, styles }); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 80aa9bdbe9..f5d4aff082 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -747,15 +747,14 @@ pub fn zm_note(features: Option) -> String { /// What an export of `layers` says when any lost Z or M values on import, or `None`: one notice, /// naming them (the first few) and counting them. `target` names what was written (a file, or the /// text returned). -pub fn zm_export_note<'a>(layers: impl IntoIterator, target: &str) -> Option { +pub fn zm_export_note<'a>(layers: impl IntoIterator, target: &str) -> Option { let names: Vec<&str> = layers.into_iter().filter(|ds| ds.zm_dropped).map(|ds| ds.name.as_str()).collect(); - match names.as_slice() { - [] => None, - [one] => Some(format!("{target}: its geometry has no Z or M values, which were dropped when {one} was read")), - _ => { - Some(format!("{target}: its geometry has no Z or M values for {}, which were dropped when they were read", layer_list(&names))) - } - } + let text = match names.as_slice() { + [] => return None, + [one] => format!("{target}: its geometry has no Z or M values, which were dropped when {one} was read"), + _ => format!("{target}: its geometry has no Z or M values for {}, which were dropped when they were read", layer_list(&names)), + }; + Some(loss::Note::loss(loss::LossCode::DroppedZm, text)) } /// `3 layers (a, b, c)`: the count, and the first five names. @@ -790,22 +789,23 @@ pub fn export_notes<'a>( layers: impl IntoIterator, target: &str, crs: raster::Crs, -) -> Vec { +) -> loss::Notes { + use loss::{LossCode, Note}; let layers: Vec<_> = layers.into_iter().collect(); - let mut notes: Vec = zm_export_note(layers.iter().map(|(ds, _)| *ds), target).into_iter().collect(); + let mut notes: loss::Notes = zm_export_note(layers.iter().map(|(ds, _)| *ds), target).into_iter().collect(); let approximate: Vec<&Dataset> = layers.iter().map(|(ds, _)| *ds).filter(|ds| ds.crs.is_some_and(|c| c != crs && c.lacks_datum_shift())).collect(); match approximate.as_slice() { [] => {} - [one] => notes.push(format!( + [one] => notes.push(Note::loss(LossCode::ApproximatedDatum, format!( "{target}: the positions of {} are approximate, possibly a few hundred metres off: its coordinate system ({}) has no shift to WGS 84", one.name, one.crs.map(raster::Crs::label).unwrap_or_default() - )), - many => notes.push(format!( + ))), + many => notes.push(Note::loss(LossCode::ApproximatedDatum, format!( "{target}: the positions of {} are approximate, possibly a few hundred metres off: their coordinate systems have no shift to WGS 84", layer_list(&many.iter().map(|ds| ds.name.as_str()).collect::>()) - )), + ))), } // Another body's layers. Written in an Earth system, their longitude/latitude become the // Earth's. Written in another body's system, its WKT gives the datum only by the ellipsoid's @@ -836,38 +836,46 @@ pub fn export_notes<'a>( let written = if crs == raster::Crs::LonLat { "WGS 84 (EPSG:4326)".to_string() } else { crs.label() }; match as_earth.as_slice() { [] => {} - [one] => notes.push(format!( - "{target}: {} is on another body than the Earth ({}), but its longitude/latitude are written as {written}", - one.name, - one.crs.map(raster::Crs::label).unwrap_or_default() + [one] => notes.push(Note::loss( + LossCode::ChangedBody, + format!( + "{target}: {} is on another body than the Earth ({}), but its longitude/latitude are written as {written}", + one.name, + one.crs.map(raster::Crs::label).unwrap_or_default() + ), )), - many => notes.push(format!( - "{target}: {} are on other bodies than the Earth, but their longitude/latitude are written as {written}", - layer_list(&many.iter().map(|ds| ds.name.as_str()).collect::>()) + many => notes.push(Note::loss( + LossCode::ChangedBody, + format!( + "{target}: {} are on other bodies than the Earth, but their longitude/latitude are written as {written}", + layer_list(&many.iter().map(|ds| ds.name.as_str()).collect::>()) + ), )), } match in_planetary_system.as_slice() { [] => {} - [one] => notes.push(format!( + [one] => notes.push(Note::loss(LossCode::DroppedCrsName, format!( "{target}: the coordinate system of {} ({}) is another body's, and the file gives its datum only by the ellipsoid's axes, without the body's or the datum's name", one.name, one.crs.map(raster::Crs::label).unwrap_or_default() - )), - many => notes.push(format!( + ))), + many => notes.push(Note::loss(LossCode::DroppedCrsName, format!( "{target}: the coordinate systems of {} are other bodies', and the file gives their datums only by the ellipsoids' axes, without the bodies' or the datums' names", layer_list(&many.iter().map(|ds| ds.name.as_str()).collect::>()) - )), + ))), } let names: Vec<&str> = layers.iter().filter(|(_, e)| e.beyond_lonlat()).map(|(ds, _)| ds.name.as_str()).collect(); match names.as_slice() { [] => {} - [one] => notes.push(format!( + // Told by the extent alone, which also takes in longitudes past ±180° on purpose (a layer + // crossing the antimeridian): said, without a code, as it may have lost nothing. + [one] => notes.push(Note::plain(format!( "{target}: the coordinates of {one} aren't longitude/latitude, so they're out of place: define its projection and export again" - )), - _ => notes.push(format!( + ))), + _ => notes.push(Note::plain(format!( "{target}: the coordinates of {} aren't longitude/latitude, so they're out of place: define their projection and export again", layer_list(&names) - )), + ))), } if crs == raster::Crs::WebMercator { notes.extend(web_mercator_note(&layers, target)); @@ -887,7 +895,7 @@ pub fn export_notes<'a>( /// time comes with no features, and its export counts them as it writes them /// ([`export::Exported::beyond_web_mercator`], said by [`web_mercator_moved_note`]). The count is /// one pass over the coordinates, without a Cancel point, as the other notices' passes are. -fn web_mercator_note(layers: &[(&Dataset, rustgis_geom::Extent)], target: &str) -> Option { +fn web_mercator_note(layers: &[(&Dataset, rustgis_geom::Extent)], target: &str) -> Option { use rustgis_geom::MAX_LAT; let shapefile = std::path::Path::new(target) .extension() @@ -930,7 +938,7 @@ fn web_mercator_note(layers: &[(&Dataset, rustgis_geom::Extent)], target: &str) /// `layer` it wrote at 85.05° north or south, where Web Mercator ends, as it counted them /// ([`export::Exported::beyond_web_mercator`]): as [`export_notes`] says it of a layer it has /// whole. `None` for none. -pub fn web_mercator_moved_note(target: &str, layer: &str, moved: usize) -> Option { +pub fn web_mercator_moved_note(target: &str, layer: &str, moved: usize) -> Option { if moved == 0 { return None; } @@ -940,7 +948,7 @@ pub fn web_mercator_moved_note(target: &str, layer: &str, moved: usize) -> Optio /// The 85.05° notice for the layers `beyond` (each with its count of vertices moved, or `None` /// when only its extent tells), or `None` for none. Layers counted and layers told by their /// extent are said in one notice, each in its own clause, so neither hides the other. -fn web_mercator_said(beyond: &[(&str, Option)], target: &str) -> Option { +fn web_mercator_said(beyond: &[(&str, Option)], target: &str) -> Option { let counted: Vec<&str> = beyond.iter().filter(|(_, n)| n.is_some()).map(|(name, _)| *name).collect(); let total: usize = beyond.iter().filter_map(|(_, n)| *n).sum(); let extents: Vec<&str> = beyond.iter().filter(|(_, n)| n.is_none()).map(|(name, _)| *name).collect(); @@ -962,7 +970,9 @@ fn web_mercator_said(beyond: &[(&str, Option)], target: &str) -> Option 0 { self.zm_dropped = true; - report.messages.push(zm_note(Some(features as u64))); + report.messages.push(loss::Note::loss(loss::LossCode::DroppedZm, zm_note(Some(features as u64)))); } } @@ -1689,9 +1699,9 @@ mod tests { } ds.hold_in(utm).unwrap(); assert_eq!(ds.coord_crs(), utm); - let note = web_mercator_note(&[(&ds, ds.extent())], "out.gpkg").unwrap_or_default(); - assert_eq!(note, web_mercator_said(&[("held", Some(1))], "out.gpkg").unwrap_or_default()); - assert!(!note.is_empty()); + let note = web_mercator_note(&[(&ds, ds.extent())], "out.gpkg"); + assert_eq!(note, web_mercator_said(&[("held", Some(1))], "out.gpkg")); + assert_eq!(note.and_then(|n| n.loss), Some(loss::LossCode::ChangedPosition)); } /// Analysis and measurement read a longitude/latitude dataset as it is: no copy, and the diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index ccf1150602..b7b7585720 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -73,7 +73,28 @@ loss_codes! { Dropped, "Correct the expression or check the input rows named in the notice." ), + DroppedZm => ( + "dropped.zm", + Dropped, + "Keep the source file where heights or measures matter: RustGIS keeps x and y only." + ), + DroppedCrsName => ( + "dropped.crs-name", + Dropped, + "Keep the source file's coordinate system definition with the export." + ), ChangedTruncated => ("changed.truncated", Changed, "Use a decimal field to keep the fractional part."), + ChangedBody => ("changed.body", Changed, "Export in the layer's own coordinate system, which keeps its body."), + ChangedPosition => ( + "changed.position", + Changed, + "Export in a coordinate system that holds the positions, such as WGS 84." + ), + ApproximatedDatum => ( + "approximated.datum", + Approximated, + "Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84." + ), } impl LossCode { diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index bd7afa4f1e..6aad11fe72 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -7032,7 +7032,7 @@ mod tests { let Step::Decoded(ds, report, Some(note)) = step else { panic!("{step:?}") }; assert_eq!(ids(&ds), [0.0, 1.0, 2.0]); assert!(note.contains("first 3 features"), "{note}"); - assert_eq!(report.messages, [crate::zm_note(Some(3))]); + assert_eq!(report.messages, [crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(3)))]); let fresh = || Pages { url: query.into(), diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index 73f2ba4267..8846c68db0 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -377,7 +377,7 @@ impl ArcgisSource { /// What a read's pages lost, said: Z values only when the layer didn't say it has them, and, /// for a view, as counted in the pages read for it, which hold features around it (and those /// crossing its cells twice). - fn notes(&self, mut losses: crate::esripbf::Losses, view: bool) -> Vec { + fn notes(&self, mut losses: crate::esripbf::Losses, view: bool) -> crate::loss::Notes { if self.info.zm_dropped { losses.with_zm = 0; } @@ -386,8 +386,8 @@ impl ArcgisSource { } // Features without usable coordinates are left out of a view, not kept. let unplaced = std::mem::take(&mut losses.unprojected); - let mut notes: Vec = - losses.messages().into_iter().map(|n| format!("{n}, counted in the pages read for the view")).collect(); + let mut notes: crate::loss::Notes = + losses.messages().into_iter().map(|n| n.map_text(|t| format!("{t}, counted in the pages read for the view"))).collect(); if unplaced > 0 { notes.push(format!( "{unplaced} features have coordinates outside their coordinate system, so are left out of the view, counted in the pages read for it" @@ -600,7 +600,7 @@ impl ArcgisSource { let matched = if complete { features.len() as u64 } else { matched }; let mut notes = self.notes(losses, view.is_some()); notes.extend(shortfall(short)); - Ok(Batch { features, matched, complete, skipped, notes: notes.into(), ..Batch::default() }) + Ok(Batch { features, matched, complete, skipped, notes, ..Batch::default() }) } /// A count's answer, or `None` when it isn't fetched yet (noted as missing). @@ -824,7 +824,7 @@ impl FeatureSource for ArcgisSource { let mut notes = self.notes(losses, view.is_some()); let short = total.saturating_sub(received); notes.extend(shortfall(short)); - Ok(Batch { matched: visited, complete: short == 0, skipped, notes: notes.into(), ..Batch::default() }) + Ok(Batch { matched: visited, complete: short == 0, skipped, notes, ..Batch::default() }) } } } diff --git a/crates/data/src/source/arcgis/tests.rs b/crates/data/src/source/arcgis/tests.rs index 88c499d8d9..6266cc9efc 100644 --- a/crates/data/src/source/arcgis/tests.rs +++ b/crates/data/src/source/arcgis/tests.rs @@ -386,7 +386,11 @@ fn what_pages_lose_is_said_by_each_read_and_none_when_nothing_is() { // Z values: said once, by the layer, as other sources say them; not again by its reads. let (query, _) = service_with("live-z.test", Opts { z: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); - assert!(src.info.zm_dropped && src.info.notes == vec![crate::zm_note(None)], "{:?}", src.info.notes); + assert!( + src.info.zm_dropped && src.info.notes == vec![crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(None))], + "{:?}", + src.info.notes + ); assert!(read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap().notes.is_empty()); // Values each page loses: said by each read, a view's counted in its pages. let (query, _) = service_with("live-utf8.test", Opts { bad_text: true, ..Opts::default() }); diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index b3d7517082..333038c47e 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -91,6 +91,12 @@ pub struct Converted { /// Its coordinate system is one RustGIS can't read, so GDAL converted it to longitude/latitude /// (as every conversion did before layers kept their own system). pub in_lonlat: bool, + /// Its features whose Z or M values the conversion dropped, as it keeps x and y only. + pub zm_dropped: u64, + /// Its features couldn't be checked for Z or M values: any it had were dropped. + pub zm_unknown: bool, + /// Its layer declares Z or M values: one whose count failed most likely lost them. + pub zm_declared: bool, } /// A GDAL program (`ogr2ogr`, `ogrinfo`): from `RUSTGIS_GDAL_BIN` (a folder), else on the `PATH`. @@ -324,6 +330,9 @@ fn convert_in(dir: &Path, src: &Path, layer: Option<&str>, crs: Option<&str>) -> }, layer: l.name.clone(), family, + zm_dropped: 0, + zm_unknown: false, + zm_declared: l.has_zm, }), // A family the layer doesn't have. Ok(None) => {} @@ -332,6 +341,27 @@ fn convert_in(dir: &Path, src: &Path, layer: Option<&str>, crs: Option<&str>) -> Err(e) => errors.push(e), } } + // The features of each part that had Z or M values, which the conversion drops (`-dim + // XY`), as a fresh conversion counts them: counted once, with the conversion, and kept + // beside it, so a cache hit doesn't scan the source again. A count that fails is said + // without a code (the layer may hold only x and y) and isn't kept: its cause may pass, and + // a query GDAL refuses fails before scanning anything. + if l.has_zm || l.family.is_none() { + for part in out.iter_mut().skip(before) { + // A count read is touched with its conversion, so pruning keeps it as long. + let count = kept_zm_count(&part.path).inspect(|_| touch(&part.path.with_extension("zm"))).or_else(|| { + let count = count_zm_features(src, &l, part.family).ok().flatten()?; + // Kept beside the conversion, so a cache hit reads it instead of scanning the + // source again; a write that fails only means it is counted again next time. + let _ = std::fs::write(part.path.with_extension("zm"), format!("{count}\n")); + Some(count) + }); + match count { + Some(n) => part.zm_dropped = n, + None => part.zm_unknown = true, + } + } + } // Count all converted families together: splitting a mixed layer isn't a loss. Read // only the headers, so checking a cache hit doesn't scan its features or date columns. // A layer with nothing converted and no error lost every feature (all empty polygons, @@ -463,27 +493,35 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option converted.notes.push(format!("{}: couldn't check how many features GDAL's conversion kept ({error})", info.name)), } let mut zm_dropped = false; + let mut zm_note = None; // A layer declaring Z or M may still hold features with only XY: those that carry them are // counted, as for a layer of several types. if (info.has_zm || info.family.is_none()) && !converted.empty { - match count_zm_features(src, info, family) { - Ok(0) => {} - Ok(count) => { + match count_zm_features(src, info, family).ok().flatten() { + Some(0) => {} + Some(count) => { zm_dropped = true; - converted.notes.push(format!( - "GDAL: '{layer}' contains Z or M coordinates on {count} source feature(s); conversion keeps only XY coordinates" + zm_note = Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedZm, + format!( + "GDAL: '{layer}' contains Z or M coordinates on {count} source feature(s); conversion keeps only XY coordinates" + ), )); } - Err(_) => { - // A layer that declares them had them dropped, though how many is unknown. + None => { + // A layer that declares them may still hold only x and y: said without a code, as + // the count isn't known. Still marked as having lost them when it declares them, so + // its exports don't pass over what was most likely dropped. zm_dropped = info.has_zm; - converted.notes.push(format!( + zm_note = Some(crate::loss::Note::plain(format!( "GDAL: '{layer}': an unknown number of source feature(s) may have had Z or M coordinates dropped; conversion keeps only XY coordinates" - )); + ))); } } } - Ok(FreshConverted { path: converted.path, notes: converted.notes.into(), empty: converted.empty, zm_dropped, workspace }) + let mut notes: crate::loss::Notes = converted.notes.into(); + notes.extend(zm_note); + Ok(FreshConverted { path: converted.path, notes, empty: converted.empty, zm_dropped, workspace }) } /// A counted loss, or an honest diagnostic when a nonempty replacement's source count is unknown. @@ -562,6 +600,10 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques touch(&keyfile); return Ok(Some(Conversion { path: out, unprojected: was_unprojected, in_lonlat: was_in_lonlat, notes: Vec::new(), empty: false })); } + // A count of Z/M features kept for an earlier conversion with this tag isn't this one's. + if !fresh { + let _ = std::fs::remove_file(dir.join(format!("{tag}.zm"))); + } // Unique to this conversion, even with others of the same layer running in this process. let tmp = dir.join(format!("{tag}.{}{n:04}.tmp.fgb", std::process::id())); // Kept in its own coordinate system, or the one given, which the FlatGeobuf says; one RustGIS @@ -783,10 +825,28 @@ fn count_geometry_filter(src: &Path, layer: &str, filter: &str) -> Result { .ok_or_else(|| DataError::Format("GDAL: could not count features of other geometry types".into())) } +/// The count of Z/M features kept beside the conversion at `path` ([`convert_in`]), when there is +/// one: written whole, with its line's end, or not taken. Read no further than a count's length, +/// so a damaged file costs nothing. +fn kept_zm_count(path: &Path) -> Option { + use std::io::Read; + let mut text = String::new(); + // The longest a count is (`u64::MAX` and its line's end), and a byte more to tell a longer file. + const LONGEST: u64 = 21; + std::fs::File::open(path.with_extension("zm")).ok()?.take(LONGEST + 1).read_to_string(&mut text).ok()?; + if text.len() as u64 > LONGEST { + return None; + } + text.strip_suffix('\n')?.parse().ok() +} + /// Generic layers don't declare the dimensions of their features. Count the selected family's /// actual Z/M geometries that conversion flattens; SQLite's spatial functions aren't present in every -/// GDAL build, so the caller reports possible loss if this diagnostic query fails. -fn count_zm_features(src: &Path, layer: &LayerInfo, family: Option) -> Result { +/// GDAL build, so the caller reports possible loss if this diagnostic query fails. One `ogrinfo` +/// scan of the source, as long as the conversion's, with no Cancel check inside it. `Ok(None)` when +/// GDAL refuses the query or its answer can't be read, as it will every time; an error when the +/// program couldn't run it (missing, timed out), which may not happen again. +fn count_zm_features(src: &Path, layer: &LayerInfo, family: Option) -> Result> { let src = std::path::absolute(src).unwrap_or_else(|_| src.to_path_buf()); let geometry = format!("\"{}\"", layer.geometry_column.replace('"', "\"\"")); let name = format!("\"{}\"", layer.name.replace('"', "\"\"")); @@ -800,11 +860,11 @@ fn count_zm_features(src: &Path, layer: &LayerInfo, family: Option) -> R c.args(["-json", "-ro", "-features", "-nomd", "-dialect", "SQLite", "-sql", &sql]).arg(&src); let out = output(c, CONVERT_TIMEOUT, &format!("GDAL dimension count for {}, layer '{}'", src.display(), layer.name))?; if !out.status.success() { - return Err(DataError::Format(format!("GDAL: {}", String::from_utf8_lossy(&out.stderr).trim()))); + return Ok(None); } - let json: serde_json::Value = - serde_json::from_slice(&out.stdout).map_err(|e| DataError::Format(format!("GDAL: unreadable dimension count ({e})")))?; - json.get("layers") + let Ok(json) = serde_json::from_slice::(&out.stdout) else { return Ok(None) }; + Ok(json + .get("layers") .and_then(|layers| layers.as_array()) .and_then(|layers| layers.first()) .and_then(|layer| layer.get("features")) @@ -812,8 +872,7 @@ fn count_zm_features(src: &Path, layer: &LayerInfo, family: Option) -> R .and_then(|features| features.first()) .and_then(|feature| feature.get("properties")) .and_then(|properties| properties.get("zm_count")) - .and_then(|count| count.as_u64()) - .ok_or_else(|| DataError::Format("GDAL: could not count features with Z or M coordinates".into())) + .and_then(|count| count.as_u64())) } /// The longest a conversion may run, and the longest a layer listing may. @@ -832,7 +891,7 @@ fn ours(name: &str) -> bool { rest.strip_suffix(".tmp.layers").is_some_and(|nonce| !nonce.is_empty() && nonce.bytes().all(|b| b.is_ascii_alphanumeric())); tag.len() == 16 && tag.bytes().all(|b| b.is_ascii_hexdigit()) - && (matches!(rest, "fgb" | "key" | "empty" | "layers") || tmp || listing_tmp) + && (matches!(rest, "fgb" | "key" | "empty" | "layers" | "zm") || tmp || listing_tmp) } #[cfg(test)] @@ -895,7 +954,24 @@ mod tests { assert_eq!(version("ogrinfo: command not found"), None); // Pruning touches only the cache's own files. assert!(ours("0123456789abcdef.fgb") && ours("0123456789abcdef.key") && ours("0123456789abcdef.empty")); - assert!(ours("0123456789abcdef.4242.tmp.fgb")); + assert!(ours("0123456789abcdef.4242.tmp.fgb") && ours("0123456789abcdef.zm")); + } + + /// A kept Z/M count is taken only whole: a count with its line's end, or `unknown`. + #[test] + fn a_kept_zm_count_is_taken_only_whole() { + let dir = tempfile::tempdir().unwrap(); + let fgb = dir.path().join("0123456789abcdef.fgb"); + let kept = |text: &str| { + std::fs::write(fgb.with_extension("zm"), text).unwrap(); + kept_zm_count(&fgb) + }; + assert_eq!(kept("7\n"), Some(7)); + assert_eq!(kept(&format!("{}\n", u64::MAX)), Some(u64::MAX)); + assert_eq!(kept("unknown\n"), None); + assert_eq!(kept("7"), None, "cut short"); + assert_eq!(kept(&format!("{}\n", "0".repeat(30))), None, "longer than any count"); + assert_eq!(kept("18446744073709551616\n"), None, "past u64"); assert!(!ours("notes.fgb") && !ours("0123456789abcdef.txt") && !ours("photo.jpg") && !ours("0123456789abcdef.x.tmp.fgb")); // The cache key's hash is stable: a cached file is found again by its name, so a changed // hash orphans every cache already on disk. FNV-1a (64-bit) of "rustgis". @@ -1268,8 +1344,32 @@ mod tests { format!(r#"{{"type":"Feature","properties":{{"rank":1}},"geometry":{{"type":"Point","coordinates":{coordinates}}}}}"#); std::fs::write(&path, input).unwrap(); let fresh = convert_one_fresh_in(&dir.join("cache"), &path, "points", None, None).unwrap(); - assert_eq!(fresh.notes.iter().any(|n| n.contains("Z or M coordinates on 1 source feature")), lossy); + assert_eq!( + fresh + .notes + .iter() + .any(|n| n.loss == Some(crate::loss::LossCode::DroppedZm) && n.contains("Z or M coordinates on 1 source feature")), + lossy + ); assert_eq!(fresh.zm_dropped, lossy); + // A first conversion, as Add Data makes it, counts them too. + let (parts, _) = convert_in(&dir.join(format!("added-{lossy}")), &path, None, None).unwrap(); + assert_eq!(parts.iter().map(|p| p.zm_dropped).sum::(), u64::from(lossy)); + // A cache hit takes the count kept beside the conversion, without scanning the source. + if lossy { + for part in &parts { + std::fs::write(part.path.with_extension("zm"), "7\n").unwrap(); + } + let (hit, _) = convert_in(&dir.join(format!("added-{lossy}")), &path, None, None).unwrap(); + assert_eq!(hit.iter().map(|p| p.zm_dropped).collect::>(), vec![7; parts.len()]); + // A kept count that can't be read is counted again, and kept. + for part in &parts { + std::fs::write(part.path.with_extension("zm"), "junk").unwrap(); + } + let (hit, _) = convert_in(&dir.join(format!("added-{lossy}")), &path, None, None).unwrap(); + assert_eq!(hit.iter().map(|p| p.zm_dropped).sum::(), 1, "{hit:?}"); + assert!(parts.iter().all(|p| std::fs::read_to_string(p.path.with_extension("zm")).is_ok_and(|t| t != "junk"))); + } let source = crate::source::open_path(&fresh.path, None).unwrap(); let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features[0].geometry.as_ref().unwrap().extent().center().x, if lossy { 2.0 } else { 8.0 }); @@ -1461,7 +1561,7 @@ mod tests { for (point, expected) in [("POINT M (2 48 100)", 1), ("POINT ZM (2 48 100 200)", 1), ("POINT (2 48)", 0)] { std::fs::write(&path, format!("WKT,name\n\"{point}\",point\n\"LINESTRING Z (2 48 100,3 48 100)\",line\n")).unwrap(); let info = list(&path).unwrap().remove(0); - assert_eq!(count_zm_features(&path, &info, Some(Family::Points)).unwrap(), expected); + assert_eq!(count_zm_features(&path, &info, Some(Family::Points)).unwrap(), Some(expected)); } } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 5ad9697f1f..a6206f6f98 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -185,7 +185,7 @@ impl SourceInfo { pub(crate) fn drop_zm(&mut self, features: Option) { if !self.zm_dropped && features != Some(0) { self.zm_dropped = true; - self.notes.push(crate::zm_note(features)); + self.notes.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(features))); } } diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 8aea2a6fa1..63c307194e 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -1407,9 +1407,17 @@ mod tests { let none = noted(Ok(Some(Some(0)))); assert!(!none.zm_dropped && none.notes.is_empty(), "{:?}", none.notes); let two = noted(Ok(Some(Some(2)))); - assert!(two.zm_dropped && two.notes == [crate::zm_note(Some(2))], "{:?}", two.notes); + assert!( + two.zm_dropped && two.notes == [crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(2)))], + "{:?}", + two.notes + ); let uncounted = noted(Ok(Some(None))); - assert!(uncounted.zm_dropped && uncounted.notes == [crate::zm_note(None)], "{:?}", uncounted.notes); + assert!( + uncounted.zm_dropped && uncounted.notes == [crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(None))], + "{:?}", + uncounted.notes + ); let slow = noted(Ok(None)); assert!(!slow.zm_dropped && slow.notes.len() == 1 && slow.notes[0].contains("within 10 s"), "{:?}", slow.notes); let failed = noted(Err(DataError::Format("permission denied".into()))); diff --git a/crates/data/tests/integration/planetary_crs.rs b/crates/data/tests/integration/planetary_crs.rs index cf7d0daab9..e0ce0a496d 100644 --- a/crates/data/tests/integration/planetary_crs.rs +++ b/crates/data/tests/integration/planetary_crs.rs @@ -1071,14 +1071,16 @@ fn exports_say_what_they_write_instead_of_another_body_s_system() { // Earth's datum note. let notes = rustgis_data::export_notes([(&layer, extent(&layer))], "out.geojson", Crs::LonLat); assert_eq!(notes.len(), 1, "{notes:?}"); + assert_eq!(notes[0].loss, Some(rustgis_data::loss::LossCode::ChangedBody)); assert!( notes[0].contains("craters") && notes[0].contains("written as WGS 84 (EPSG:4326)") && notes[0].contains(&mars.label()), "{notes:?}" ); let notes = rustgis_data::export_notes([&layer, &moon, &earth].map(|ds| (ds, extent(ds))), "map.json", Crs::LonLat); assert_eq!(notes.len(), 2, "{notes:?}"); - assert!(notes.iter().any(|n| n.contains("2 layers (craters, moon) are on other bodies")), "{notes:?}"); - assert!(notes.iter().any(|n| n.contains("parcels") && n.contains("few hundred metres")), "{notes:?}"); + let coded = |code, words: &str| notes.iter().any(|n| n.loss == Some(code) && n.contains(words)); + assert!(coded(rustgis_data::loss::LossCode::ChangedBody, "2 layers (craters, moon) are on other bodies"), "{notes:?}"); + assert!(coded(rustgis_data::loss::LossCode::ApproximatedDatum, "few hundred metres"), "{notes:?}"); // In its own system (a Shapefile by default): the .prj is the WKT it was read from, the body's // name and all, and nothing is said. assert_eq!(io::default_export_crs(&layer, "shp"), mars); @@ -1093,12 +1095,14 @@ fn exports_say_what_they_write_instead_of_another_body_s_system() { assert!(rustgis_data::export_notes([(&on_mars, extent(&on_mars))], "out.shp", mars).is_empty()); let notes = rustgis_data::export_notes([&layer, &moon].map(|ds| (ds, extent(ds))), "out.shp", mars); assert_eq!(notes.len(), 1, "{notes:?}"); + assert_eq!(notes[0].loss, Some(rustgis_data::loss::LossCode::ChangedBody)); assert!(notes[0].contains("moon is on another body") && notes[0].contains(&format!("written as {}", mars.label())), "{notes:?}"); // A Mars system known only by a PROJ definition has no name to write: said. let by_def = Crs::parse("+proj=longlat +R=3396190 +no_defs").unwrap(); assert!(by_def.is_planetary()); let notes = rustgis_data::export_notes([(&layer, extent(&layer))], "out.shp", by_def); assert_eq!(notes.len(), 1, "{notes:?}"); + assert_eq!(notes[0].loss, Some(rustgis_data::loss::LossCode::DroppedCrsName)); assert!(notes[0].contains("only by the ellipsoid's axes"), "{notes:?}"); // An Earth layer says nothing of bodies. let notes = rustgis_data::export_notes([(&earth, extent(&earth))], "out.geojson", Crs::LonLat); diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 113e1088af..8a97c710e9 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -283,19 +283,41 @@ pub(crate) fn drawn( /// to say again where the export lands; past the notices a session keeps, how many earlier ones /// there were. `path` names the file in that count. pub(crate) fn copy_notices(copy: &mut Session, path: &str) -> Vec<(rustgis_data::diagnostics::Severity, String)> { + copy_notices_coded(copy, path).into_iter().map(|(severity, note)| (severity, note.text)).collect() +} + +/// [`copy_notices`] with each notice's loss code, for an export that says them itself +/// ([`say_coded`]). +pub(crate) fn copy_notices_coded(copy: &mut Session, path: &str) -> Vec<(rustgis_data::diagnostics::Severity, rustgis_data::loss::Note)> { let kept = std::mem::take(&mut copy.notices); let earlier = copy.notices_given().saturating_sub(kept.len() as u64); let mut said = Vec::new(); if earlier > 0 { said.push(( rustgis_data::diagnostics::Severity::Warning, - format!("{path}: {earlier} earlier notices from drawing it aren't shown"), + rustgis_data::loss::Note::plain(format!("{path}: {earlier} earlier notices from drawing it aren't shown")), )); } - said.extend(kept.into_iter().map(|n| (n.severity, n.text))); + said.extend(kept.into_iter().map(|n| (n.severity, rustgis_data::loss::Note { loss: n.loss(), text: n.text }))); said } +/// [`say`] for notices with their loss codes: one with a code is said as that loss. +pub(crate) fn say_coded(s: &mut Session, notices: Vec<(rustgis_data::diagnostics::Severity, rustgis_data::loss::Note)>) { + use rustgis_data::diagnostics::Severity; + for (severity, note) in notices { + if note.loss.is_some() { + s.say(note); + continue; + } + match severity { + Severity::Error => s.notify(note.text, true), + Severity::Warning => s.warn(note.text), + Severity::Info => s.notify(note.text, false), + } + } +} + /// Says `notices` (what an export said on a copy of the session) in `s`, each as it was said. pub(crate) fn say(s: &mut Session, notices: Vec<(rustgis_data::diagnostics::Severity, String)>) { use rustgis_data::diagnostics::Severity; diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 1ea1627713..5cedc004b1 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2844,25 +2844,27 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc, Vec<&str>)> = Vec::new(); + // Each warning with its distinct inputs, and how many reads gave it: an input named twice + // is read twice. + let mut aggregated: Vec<(&str, Option, Vec<&str>, usize)> = Vec::new(); for (target, msg, code) in &reader_warnings { - if let Some((_, _, inputs)) = aggregated.iter_mut().find(|(m, c, _)| *m == msg.as_str() && c == code) { + if let Some((_, _, inputs, reads)) = aggregated.iter_mut().find(|(m, c, _, _)| *m == msg.as_str() && c == code) { + *reads += 1; if !inputs.contains(&target.as_str()) { inputs.push(target.as_str()); } } else { - aggregated.push((msg.as_str(), *code, vec![target.as_str()])); + aggregated.push((msg.as_str(), *code, vec![target.as_str()], 1)); } } - for (msg, code, inputs) in aggregated { + for (msg, code, inputs, reads) in aggregated { let count = inputs.len(); let inputs_list = inputs.join(", "); let label = if count == 1 { "input" } else { "inputs" }; - let text = format!("gp.batch: {count} {label} ({inputs_list}): {msg}"); - if let Some(code) = code { - losses.add(code, &text, count); - } else { - s.notify(text, false); + match code { + // Its inputs are named in the example, which the batch's loss notice prefixes. + Some(code) => losses.add_stated(code, &format!("{count} {label} ({inputs_list}): {msg}"), reads), + None => s.notify(format!("gp.batch: {count} {label} ({inputs_list}): {msg}"), false), } } } @@ -3260,10 +3262,16 @@ struct BatchLoss { impl BatchLosses { /// Counts every report, even when its text is beyond the sample. fn add(&mut self, code: LossCode, text: &str, count: usize) { + self.add_stated(code, &batch_message(text, count), count); + } + + /// [`BatchLosses::add`] for a message that already says how many it covers (`count`): + /// counted, without a repetition count added to it. + fn add_stated(&mut self, code: LossCode, text: &str, count: usize) { let entry = self.0.entry(code.spec().id).or_insert_with(|| BatchLoss { code, reports: 0, examples: Vec::new(), omitted: 0 }); entry.reports = entry.reports.saturating_add(count); if entry.examples.len() < 3 { - entry.examples.push(batch_message(text, count)); + entry.examples.push(text.to_string()); } else { entry.omitted += 1; } @@ -7307,8 +7315,11 @@ mod batch_tests { } // Notices aggregated into a single notice per warning kind without truncating later files + // A Z/M loss has its code, so it is said as one loss notice for the batch. let notice = s.notices_since(mark).iter().find(|n| n.text.contains("Z or M")).unwrap(); - assert!(notice.text.starts_with("gp.batch: 4 inputs (")); + assert_eq!(notice.loss(), Some(rustgis_data::loss::LossCode::DroppedZm)); + assert!(notice.text.starts_with("gp.batch: 4 loss report(s) (4 inputs ("), "{}", notice.text); + assert!(!notice.text.contains("(×"), "{}", notice.text); assert!(notice.text.contains("file_1.geojson")); assert!(notice.text.contains("file_2.geojson")); assert!(notice.text.contains("file_3.geojson")); @@ -7322,6 +7333,12 @@ mod batch_tests { assert!(record.messages.iter().any(|m| m.contains("Z or M"))); } + // An input named twice is read, and its loss counted, twice. + let mark = s.notice_mark(); + s.run("gp.batch", &json!({"tool": "buffer", "inputs": [&files[0], &files[0]], "params": {"distance": 5}})).unwrap(); + let twice = s.notices_since(mark).iter().find(|n| n.text.contains("Z or M")).unwrap().text.clone(); + assert!(twice.starts_with("gp.batch: 2 loss report(s) (1 input ("), "{twice}"); + let _ = std::fs::remove_dir_all(root); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3dc5453da9..61470292dd 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2822,10 +2822,11 @@ fn add_picked( }) .map(|(_, r)| { let mut said = r.report.clone(); - // The layer's own Z/M note leads its messages; it is said by that layer. A note - // that reports another loss is never taken for it. - if r.dataset.zm_dropped && said.messages.first().is_some_and(|n| n.loss.is_none()) { - said.messages.drain(..1); + // The layer's own Z/M note, by its code: that layer says it. + if r.dataset.zm_dropped + && let Some(at) = said.messages.iter().position(|n| n.loss == Some(rustgis_data::loss::LossCode::DroppedZm)) + { + said.messages.drain(at..=at); } (r.dataset.source.clone(), said) }) @@ -3564,11 +3565,61 @@ fn add_gdal(s: &mut Session, p: &Value, path: &str) -> CmdResult { for f in failed { s.notify(format!("{path}: {f}"), true); } + // What the conversion dropped of the parts' Z or M values, as a fresh conversion says it. + let (lost, unknown) = zm_notices(path, &converted); + if let Some(text) = lost { + s.notify_loss(rustgis_data::loss::LossCode::DroppedZm, text.into()); + } + if let Some(text) = unknown { + s.notify(text, false); + } let original = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); let parts = gdal_parts(converted, &original, crs); add_converted(s, p, path, &original, parts) } +/// What GDAL's conversion of `path` says of its parts' Z or M values, once for each kind: the +/// parts that had some, with their total (a loss), and the parts that couldn't be counted. A part +/// alone is named in a fresh conversion's words; several are counted and named, the first ten. +#[cfg(not(target_arch = "wasm32"))] +fn zm_notices(path: &str, converted: &[rustgis_data::source::gdal::Converted]) -> (Option, Option) { + let named = |parts: &[&rustgis_data::source::gdal::Converted]| { + let mut names: Vec = parts.iter().take(10).map(|c| format!("'{}'", c.name)).collect(); + if parts.len() > 10 { + names.push(format!("{} more", parts.len() - 10)); + } + names.join(", ") + }; + let lost: Vec<_> = converted.iter().filter(|c| c.zm_dropped > 0).collect(); + let unknown: Vec<_> = converted.iter().filter(|c| c.zm_dropped == 0 && c.zm_unknown).collect(); + let lost = match lost.as_slice() { + [] => None, + [one] => Some(format!( + "{path}: GDAL: '{}' contains Z or M coordinates on {} source feature(s); conversion keeps only XY coordinates", + one.name, one.zm_dropped + )), + many => Some(format!( + "{path}: GDAL: {} layers ({}) contain Z or M coordinates on {} source feature(s); conversion keeps only XY coordinates", + many.len(), + named(many), + many.iter().map(|c| c.zm_dropped).fold(0u64, u64::saturating_add) + )), + }; + let unknown = match unknown.as_slice() { + [] => None, + [one] => Some(format!( + "{path}: GDAL: '{}': an unknown number of source feature(s) may have had Z or M coordinates dropped; conversion keeps only XY coordinates", + one.name + )), + many => Some(format!( + "{path}: GDAL: {} layers ({}): an unknown number of source feature(s) may have had Z or M coordinates dropped; conversion keeps only XY coordinates", + many.len(), + named(many) + )), + }; + (lost, unknown) +} + /// GDAL's conversions of the file `original` as the layers to add: the layers in the file's order, /// each layer split by geometry type with its parts bottom first ([`bottom_first`]). A layer of /// one type (no family) is a part alone, so the sort leaves it as it is. @@ -3584,7 +3635,9 @@ pub(crate) fn gdal_parts(mut converted: Vec 0 || (c.zm_unknown && c.zm_declared), origin: ConvertedOrigin::Gdal(rustgis_map::source::GdalOrigin { path: original.to_string(), layer: c.layer, @@ -4347,7 +4400,7 @@ pub(crate) fn duckdb_parts( // Z and M values are dropped as DuckDB writes the result: one notice for all its parts. let zm = out.parts.iter().fold(0u64, |n, p| n.saturating_add(p.zm_dropped)); if zm > 0 { - s.notify(format!("{name}: {}", rustgis_data::zm_note(Some(zm))), false); + s.notify_loss(rustgis_data::loss::LossCode::DroppedZm, format!("{name}: {}", rustgis_data::zm_note(Some(zm))).into()); } let mixed = out.parts.len() > 1; out.parts.sort_by_key(|p| bottom_first(p.family)); @@ -7783,6 +7836,41 @@ mod tests { use crate::Session; use serde_json::json; + /// A GDAL conversion's parts say their Z or M values once for each kind: a part alone in a + /// fresh conversion's words, several counted together; parts without any say nothing. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_conversion_says_its_parts_z_and_m_once_for_each_kind() { + let part = |name: &str, zm_dropped: u64, zm_unknown: bool| rustgis_data::source::gdal::Converted { + path: std::path::PathBuf::new(), + name: name.into(), + layer: "roads".into(), + family: None, + unprojected: false, + in_lonlat: false, + zm_dropped, + zm_unknown, + zm_declared: false, + }; + let (lost, unknown) = super::zm_notices("f.kml", &[part("roads (Point)", 2, false), part("roads (Line)", 3, false)]); + assert_eq!( + lost.as_deref(), + Some( + "f.kml: GDAL: 2 layers ('roads (Point)', 'roads (Line)') contain Z or M coordinates on 5 source feature(s); conversion keeps only XY coordinates" + ) + ); + assert_eq!(unknown, None); + let (lost, unknown) = + super::zm_notices("f.kml", &[part("a", 1, false), part("b", 0, true), part("c", 0, true), part("d", 0, false)]); + assert!(lost.is_some_and(|t| t.starts_with("f.kml: GDAL: 'a' contains Z or M coordinates on 1 source feature(s)"))); + assert!(unknown.is_some_and(|t| t.starts_with("f.kml: GDAL: 2 layers ('b', 'c'): an unknown number"))); + assert_eq!(super::zm_notices("f.kml", &[part("d", 0, false)]), (None, None)); + // A part whose count failed is taken as having lost them when its layer declares them. + let declared = rustgis_data::source::gdal::Converted { zm_declared: true, ..part("e", 0, true) }; + let parts = super::gdal_parts(vec![declared, part("f", 0, true), part("g", 4, false)], "f.kml", None); + assert_eq!(parts.iter().map(|p| p.zm_dropped).collect::>(), [true, false, true]); + } + /// A payload can start beyond the sniff budget; only root keys decide the route. #[test] fn json_head_stops_before_payloads() { diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index bfa3f00cef..171886ea2d 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1022,7 +1022,7 @@ pub fn pages(s: &Session, i: usize) -> Result<(Doc, Vec Result<(Vec, usize), String> { let name = s.project.reports.get(i).map(|r| r.name.clone()).unwrap_or_default(); let (bytes, mut copy) = whole_bytes(detached(&s.project), s.path.clone(), i, dpi, pdf); - super::exports::say(s, super::exports::copy_notices(&mut copy, &name)); + super::exports::say_coded(s, super::exports::copy_notices_coded(&mut copy, &name)); bytes } @@ -1047,8 +1047,13 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result, Vec<_>) = + super::exports::copy_notices_coded(&mut copy, &path).into_iter().partition(|(_, note)| note.loss.is_some()); + let said = said.into_iter().map(|(severity, note)| (severity, note.text)).collect(); + let mut wrote = super::exports::drawn(©.project.maps, said, written, path)?; + wrote.notes.extend(coded.into_iter().map(|(_, note)| note)); + Ok(wrote) })) } diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 63b66ca53c..e6c3f9be17 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -660,7 +660,7 @@ pub fn coalesce_read_zm(notes: &mut rustgis_data::loss::Notes, file: &str, ds: & if lost.zm_noted && let Some(generic) = rustgis_data::zm_export_note([ds], file) { - notes.retain(|note| note.text != generic); + notes.retain(|note| *note != generic); } } @@ -782,7 +782,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: // as they're written (`e.beyond_web_mercator`), and its source's extent only serves the // out-of-place check. A raster layer's extent is its raster's, which the file doesn't hold. 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(); + let mut notes: rustgis_data::loss::Notes = rustgis_data::export_notes([(ds, extent)], path, crs); coalesce_read_zm(&mut notes, path, ds, &unreadable); notes.extend(default_note); let csv_type = if csv_points { rustgis_data::GeometryType::Point } else { ds.geometry_type }; diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index 848e7786b8..bffdef6461 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -197,7 +197,7 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result let written_path = Some(path.clone()); Ok(Wrote { answer, - notes: notes.into(), + notes, diagnostics: Vec::new(), refused_notes, written_path, diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 3d2f76cb79..d7d0370aef 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -683,10 +683,10 @@ pub(crate) fn note_export(s: &mut Session, kind: &str, p: &Value, target: &str) ) }) .unwrap_or_default(), - _ => Vec::new(), + _ => Default::default(), }; for note in notes { - s.notify(note, false); + s.say(note); } } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index d1dc10b7c2..34815cea0a 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2132,8 +2132,8 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { let target = ds.name.clone(); let query_note = super::share::query_export_note(&target, &layer.name, &report); drop(ds); - for note in notes.into_iter().chain(construction_notes) { - s.notify(note, false); + for note in notes.into_iter().chain(construction_notes.into_iter().map(rustgis_data::loss::Note::plain)) { + s.say(note); } super::share::notify_null_numbers(s, &target, null_numbers); if let Some(note) = query_note { @@ -2171,7 +2171,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result Result 0 { @@ -2257,7 +2257,7 @@ fn conversion_format(p: &Value) -> Result<&str, String> { } /// Serializes a complete dataset and collects its loss notices for delivery after success. -fn converted(ds: &Dataset, p: &Value) -> Result<(String, Vec), String> { +fn converted(ds: &Dataset, p: &Value) -> Result<(String, rustgis_data::loss::Notes), String> { let name_field = ps(p, "nameField").and_then(|n| ds.field_index(n)).or_else(|| ds.fields.iter().position(|f| f.name.eq_ignore_ascii_case("name"))); let format = conversion_format(p)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9e86eab310..9ca1f41767 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -22544,6 +22544,9 @@ fn split_sources_keep_their_points_on_top() { family: Some(f), unprojected: false, in_lonlat: false, + zm_dropped: 0, + zm_unknown: false, + zm_declared: false, }) .collect(); let original = dir.join("file.gpx").display().to_string(); diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index 28d6648fb3..37788b2c5d 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -25,8 +25,8 @@ enum Expect { Said(&'static str), /// Imports the layer and says the loss in a notice; refusing this valid fixture is a failure. Imported(&'static str), - /// Imports successfully and identifies the loss with a code. - Classified(LossCode), + /// Imports successfully and identifies the loss with a code, in a notice holding these words. + Classified(LossCode, &'static str), /// Loses it without a notice today, still adding a layer: what is lost. Silent(&'static str), } @@ -220,7 +220,13 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { let mut out = vec![ // GeoJSON. - case("GeoJSON: a height", "a.geojson", geojson(&[point]), geojson(&[r#"{"type":"Point","coordinates":[1,2,3]}"#]), Said("Z or M")), + case( + "GeoJSON: a height", + "a.geojson", + geojson(&[point]), + geojson(&[r#"{"type":"Point","coordinates":[1,2,3]}"#]), + Expect::Classified(LossCode::DroppedZm, "Z or M"), + ), case( "GeoJSON: an unreadable geometry", "a.geojson", @@ -229,7 +235,13 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { Said("unreadable geometry"), ), // TopoJSON. - case("TopoJSON: a height", "a.topojson", topo_line("[[0,0],[1,1]]"), topo_line("[[0,0,5],[1,1,6]]"), Said("Z or M")), + case( + "TopoJSON: a height", + "a.topojson", + topo_line("[[0,0],[1,1]]"), + topo_line("[[0,0,5],[1,1,6]]"), + Expect::Classified(LossCode::DroppedZm, "Z or M"), + ), case( "TopoJSON: an arc index the file doesn't hold", "a.topojson", @@ -259,7 +271,13 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "wkt,id\n\"POINT(1 2)\",1\n\"POINT(3\",2\n", Said("isn't readable WKT"), ), - case("CSV: a height in WKT", "a.csv", "wkt,id\n\"POINT(1 2)\",1\n", "wkt,id\n\"POINT Z(1 2 3)\",1\n", Said("Z or M")), + case( + "CSV: a height in WKT", + "a.csv", + "wkt,id\n\"POINT(1 2)\",1\n", + "wkt,id\n\"POINT Z(1 2 3)\",1\n", + Expect::Classified(LossCode::DroppedZm, "Z or M"), + ), case( "CSV: an unreadable coordinate", "a.csv", @@ -294,7 +312,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.kml", kml(&["1,2"]), kml(&["1,2,30"]), - Said("Z or M"), + Expect::Classified(LossCode::DroppedZm, "Z or M"), ), case( "KML: a placemark without geometry", @@ -432,7 +450,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { gml( r#"48 10 5 49 11 6"#, ), - Said("Z or M"), + Expect::Classified(LossCode::DroppedZm, "Z or M"), ), // GeoRSS. case( @@ -447,7 +465,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.rss", georss(&[&georss_polygon("1 1 1 2 2 2 1 1")]), georss(&[&georss_polygon("1 x")]), - Expect::Classified(LossCode::DroppedRing), + Expect::Classified(LossCode::DroppedRing, "hole"), ), case( "GeoRSS: a point with more than one pair", @@ -629,9 +647,15 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { .collect::>(); out.extend(kmz); out.extend([ - case("CityJSON: varying line heights", "a.city.json", cityjson(0), cityjson(5), Said("Z or M")), - case("CityGML: varying line heights", "a.gml", citygml(0), citygml(5), Said("Z or M")), - case("GeoPackage: a height", "a.gpkg", gpkg(fixture_dir, false), gpkg(fixture_dir, true), Said("Z or M")), + case("CityJSON: varying line heights", "a.city.json", cityjson(0), cityjson(5), Expect::Classified(LossCode::DroppedZm, "Z or M")), + case("CityGML: varying line heights", "a.gml", citygml(0), citygml(5), Expect::Classified(LossCode::DroppedZm, "Z or M")), + case( + "GeoPackage: a height", + "a.gpkg", + gpkg(fixture_dir, false), + gpkg(fixture_dir, true), + Expect::Classified(LossCode::DroppedZm, "Z or M"), + ), case( "FlatGeobuf: a height", "a.fgb", @@ -990,7 +1014,10 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< if feature_pbf { let (native, report) = rustgis_engine::data::esripbf::read(content, "a").map_err(std::io::Error::other)?; check_feature_pbf(&native, pbf_lossy)?; - if report.skipped != 0 || report.messages != pbf_messages { + // Coded `dropped.zm`, as the notice the command gives. + let coded: Vec = + pbf_messages.iter().map(|text| rustgis_engine::data::loss::Note::loss(LossCode::DroppedZm, text.clone())).collect(); + if report.skipped != 0 || report.messages != coded { return Err(std::io::Error::other(format!("feature-service PBF has the wrong native report: {report:?}"))); } } @@ -1016,7 +1043,13 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< } if dxf_height { let native = rustgis_engine::data::dxf::read(file, content, &Default::default()).map_err(std::io::Error::other)?; - if native.len() != 1 || native[0].1.skipped != 0 || native[0].1.messages != dxf_messages { + // The varying heights lost are coded `dropped.zm`; nothing else is. + let expected: Vec> = dxf_messages.iter().map(|m| m.contains("varying Z").then_some(LossCode::DroppedZm)).collect(); + if native.len() != 1 + || native[0].1.skipped != 0 + || native[0].1.messages.texts().collect::>() != dxf_messages + || native[0].1.messages.iter().map(|m| m.loss).collect::>() != expected + { return Err(std::io::Error::other(format!("DXF height native report: {native:?}"))); } check_dxf_height(&native[0].0)?; @@ -1093,7 +1126,9 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< check_feature_pbf(&s.map().layers[0].dataset, pbf_lossy)?; let notices = s.notices_since(mark); // Require the exact loss count and subject, and no additional notice. - if notices.iter().map(|n| n.text.clone()).collect::>() != pbf_messages { + if notices.iter().map(|n| n.text.clone()).collect::>() != pbf_messages + || notices.iter().any(|n| n.loss() != Some(LossCode::DroppedZm)) + { return Err(std::io::Error::other(format!("feature-service PBF has the wrong command notices: {notices:?}"))); } } @@ -1113,7 +1148,9 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< } check_dxf_height(&s.map().layers[0].dataset)?; let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - if said != dxf_messages { + let codes: Vec> = s.notices_since(mark).iter().map(|n| n.loss()).collect(); + let expected: Vec> = dxf_messages.iter().map(|m| m.contains("varying Z").then_some(LossCode::DroppedZm)).collect(); + if said != dxf_messages || codes != expected { return Err(std::io::Error::other(format!("DXF height command notices: {said:?}"))); } } @@ -1157,8 +1194,9 @@ fn a_reading_that_loses_something_says_so() { Ok(Err(e)) => (vec![(e, None)], false), Ok(Ok((said, added))) => (said.into_iter().filter(|n| !clean.contains(n)).collect(), added), }; - if let Expect::Classified(code) = c.expect { + if let Expect::Classified(code, words) = c.expect { if !added + || new.iter().filter(|(text, loss)| *loss == Some(code) && text.contains(words)).count() != 1 || new.iter().filter(|(_, loss)| *loss == Some(code)).count() != 1 || clean.iter().any(|(_, loss)| *loss == Some(code)) { diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index b357c03dc6..261c6e0b7a 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -161,32 +161,11 @@ pub struct Unreadable { /// Other reader diagnostics, already qualified by their source. Date diagnostics stay in /// their typed fields above so consumers can describe what an export did to them once. pub messages: rustgis_data::loss::Notes, - /// `messages` contains the source's Z/M loss diagnostic. An export can keep that more + /// `messages` contains the source's Z/M loss diagnostic (a note with `dropped.zm`). An export can keep that more /// specific report instead of also emitting its generic already-dropped-Z/M warning. pub zm_noted: bool, } -/// Recognizes only diagnostics produced by the common Z/M formatter and the two positive -/// GDAL conversion templates. Unknown/custom wording cannot suppress an export warning. -fn reader_noted_zm(note: &str) -> bool { - if note == rustgis_data::zm_note(None) { - return true; - } - if let Some(count) = note.split_once(' ').and_then(|(n, _)| n.parse::().ok()) - && count > 0 - && note == rustgis_data::zm_note(Some(count)) - { - return true; - } - let Some((_, detail)) = note.strip_prefix("GDAL: '").and_then(|n| n.rsplit_once("' ")) else { return false }; - ["declares", "contains"].into_iter().any(|verb| { - detail - .strip_prefix(&format!("{verb} Z or M coordinates on ")) - .and_then(|n| n.strip_suffix(" source feature(s); conversion keeps only XY coordinates")) - .is_some_and(|n| n == "an unknown number of" || n.parse::().is_ok_and(|count| count > 0 && n == count.to_string())) - }) -} - /// A layer: a dataset drawn with a renderer and labels. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Layer { @@ -891,30 +870,31 @@ impl Layer { /// [`Layer::load_all`], with what of the source couldn't be read. pub fn load_all_counted(&self) -> Result<(Dataset, Unreadable), String> { - let (ds, report, zm_noted) = self.load_all_with_notices()?; + let (ds, report) = self.load_all_with_notices()?; // materialize also puts the typed date diagnostics in messages. Existing consumers // give them their own export wording, so preserve only the other messages here. let date_notes: Vec<_> = report.unread_dates.iter().chain(&report.rounded_dates).map(|n| format!(": {n}")).collect(); let mut seen = std::collections::HashSet::new(); - let messages = report + let messages: rustgis_data::loss::Notes = report .messages .into_iter() .filter(|m| !date_notes.iter().any(|date| m.ends_with(date))) .filter(|m| seen.insert(m.clone())) .collect(); + // A Z/M note found by this read too, not only one the source said when it opened. + let zm_noted = messages.iter().any(|m| m.loss == Some(rustgis_data::loss::LossCode::DroppedZm)); Ok((ds, Unreadable { rows: report.skipped, dates: report.unread_dates, rounded: report.rounded_dates, messages, zm_noted })) } /// A whole read with its complete reader report, including messages beyond rows and dates. /// Callers decide which opening notices were already shown and which the new read discovered. pub fn load_all_reported(&self) -> Result<(Dataset, rustgis_data::ReadReport), String> { - self.load_all_with_notices().map(|(ds, report, _)| (ds, report)) + self.load_all_with_notices() } - fn load_all_with_notices(&self) -> Result<(Dataset, rustgis_data::ReadReport, bool), String> { - let Some(copy) = self.open_source()? else { return Ok((self.dataset.clone(), rustgis_data::ReadReport::default(), false)) }; + fn load_all_with_notices(&self) -> Result<(Dataset, rustgis_data::ReadReport), String> { + let Some(copy) = self.open_source()? else { return Ok((self.dataset.clone(), rustgis_data::ReadReport::default())) }; let (mut ds, mut report) = copy.read_all()?; - let mut zm_noted = false; if let Some(info) = copy.info() { ds.zm_dropped |= info.zm_dropped; for note in &info.notes { @@ -922,7 +902,6 @@ impl Layer { if !report.messages.contains(&message) { report.messages.push(message); } - zm_noted |= info.zm_dropped && reader_noted_zm(¬e.text); } } ds.name = self.dataset.name.clone(); @@ -942,7 +921,7 @@ impl Layer { } } ds.source = self.dataset.source.clone(); - Ok((ds, report, zm_noted)) + Ok((ds, report)) } /// A streamed layer's source, to export whole a chunk at a time, with a dataset of no @@ -3829,27 +3808,6 @@ mod tests { use rustgis_data::{Field, FieldType, Value}; use rustgis_geom::lonlat_to_merc; - #[test] - fn only_canonical_reader_dimension_notices_can_replace_export_warnings() { - for count in [Some(1), Some(25), None] { - assert!(reader_noted_zm(&rustgis_data::zm_note(count))); - } - for detail in - ["declares Z or M coordinates on 2", "contains Z or M coordinates on 1", "declares Z or M coordinates on an unknown number of"] - { - assert!(reader_noted_zm(&format!("GDAL: 'a layer' {detail} source feature(s); conversion keeps only XY coordinates"))); - } - for unknown in [ - "a custom provider has a Z/M flag", - "the source couldn't be checked for Z or M values", - "GDAL: 'x' contains Z or M coordinates on perhaps source feature(s); conversion keeps only XY coordinates", - "GDAL: 'x' contains Z or M coordinates on 0 source feature(s); conversion keeps only XY coordinates", - ] { - assert!(!reader_noted_zm(unknown)); - } - assert!(!reader_noted_zm(&rustgis_data::zm_note(Some(0)))); - } - /// A text field an old project lists for a source's date column becomes a date field, unless /// a filter reads it as text and wouldn't as dates: then it stays text and the filter works. #[test] diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index e040eb70cf..2d36f7fbc2 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1119,7 +1119,10 @@ impl SourceLayer { } let part = out.parts.first().ok_or_else(|| format!("{path}: the table returns no {}", d.family.label()))?; if part.zm_dropped > 0 { - conversion_notes.push(rustgis_data::zm_note(Some(part.zm_dropped))); + conversion_notes.push(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedZm, + rustgis_data::zm_note(Some(part.zm_dropped)), + )); } declared_empty = part.count == 0; new.path = Some(part.path.display().to_string()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index effb353022..f03d719dbe 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5506,7 +5506,7 @@ impl RustGisApp { // The features written, read whole, give their own extent, in longitude/latitude // (not a raster's, or the one a streamed layer's source declares). let mut notes: rustgis_engine::data::loss::Notes = - rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs).into(); + rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs); rustgis_engine::cmd::share::coalesce_read_zm(&mut notes, &name, &ds, &lost); notes.extend(unplaced); // Which system it is written in, where that isn't the layer's own, as share.exportLayer says. diff --git a/docs/cli.md b/docs/cli.md index c72b40e588..bcb8e0e773 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -162,7 +162,12 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `dropped.time` | Write to a date-time field to keep the time of day. | | `dropped.value` | Correct the value or use a destination field that can hold it. | | `dropped.calculation-result` | Correct the expression or check the input rows named in the notice. | +| `dropped.zm` | Keep the source file where heights or measures matter: RustGIS keeps x and y only. | +| `dropped.crs-name` | Keep the source file's coordinate system definition with the export. | | `changed.truncated` | Use a decimal field to keep the fractional part. | +| `changed.body` | Export in the layer's own coordinate system, which keeps its body. | +| `changed.position` | Export in a coordinate system that holds the positions, such as WGS 84. | +| `approximated.datum` | Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84. | Not every loss has a code yet: losses still reported without one don't stop a strict run.