diff --git a/ROADMAP.md b/ROADMAP.md index 36f1d7f202..32f1cdc675 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -72,7 +72,7 @@ A result is right, or RustGIS says what it lost or assumed - Known silent losses: DuckDB queries (`ST_Force2D`) drop Z without a notice; the OSM reader leaves out rings that don't close, rings and member ways with nodes or ways the file doesn't hold, and inner rings outside every outer one; and the text readers' losses listed as `Silent` in `crates/engine/tests/integration/never_silent_reading.rs`, among them - unreadable coordinates, holes and parts in KML, GeoRSS, MapInfo and + unreadable coordinates, holes and parts in MapInfo and DXF, and attribute fields/values in XLSB short-cell workbooks (the original SheetJS 0.18.5 clean workbook retains its point but no attributes, without a notice). A fix makes diff --git a/crates/data/src/georss.rs b/crates/data/src/georss.rs index 190fe07136..2776caa5b5 100644 --- a/crates/data/src/georss.rs +++ b/crates/data/src/georss.rs @@ -65,12 +65,16 @@ fn bbox(ll: Coord, ur: Coord) -> Option { } /// An item's place, `Ok(None)` when it has none, `Err` when it has one that can't be read. -/// Unreadable polygon holes are omitted and counted in `lost_holes`. -fn place(item: &Node, lost_holes: &mut usize) -> std::result::Result, ()> { +/// Unreadable polygon holes and coordinate pairs past the first in points are counted where omitted. +fn place(item: &Node, lost_holes: &mut usize, excess_points: &mut usize) -> std::result::Result, ()> { let g = |name: &str| item.children().find(|c| c.is_element() && local(c) == name); let parse = |n: Node| lat_lons(&text_of(&n)).ok_or(()); + let mut point = |pts: Vec| { + *excess_points += pts.len().saturating_sub(1); + pts.first().map(|c| Some(Geometry::Point(*c))).ok_or(()) + }; if let Some(n) = g("point") { - return parse(n)?.first().map(|c| Some(Geometry::Point(*c))).ok_or(()); + return point(parse(n)?); } if let Some(n) = g("line") { let pts = parse(n)?; @@ -93,7 +97,7 @@ fn place(item: &Node, lost_holes: &mut usize) -> std::result::Result parse(pos("pos")?)?.first().map(|c| Some(Geometry::Point(*c))).ok_or(()), + "Point" => point(parse(pos("pos")?)?), "LineString" => { let pts = parse(pos("posList")?)?; if pts.len() >= 2 { Ok(Some(Geometry::Line(vec![pts]))) } else { Err(()) } @@ -129,9 +133,7 @@ fn place(item: &Node, lost_holes: &mut usize) -> std::result::Result { - lat_lons(&format!("{lat} {lon}")).and_then(|v| v.first().copied()).map(|c| Some(Geometry::Point(c))).ok_or(()) - } + (Some(lat), Some(lon)) => point(lat_lons(&format!("{lat} {lon}")).ok_or(())?), (None, None) => Ok(None), _ => Err(()), } @@ -167,9 +169,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> Dataset::new(format!("{name} lines"), GeometryType::Polyline, fields()), Dataset::new(format!("{name} polygons"), GeometryType::Polygon, fields()), ]; + let mut excess_points = 0usize; let (mut skipped, mut without, mut lost_holes) = (0usize, 0usize, 0usize); for item in root.descendants().filter(|n| n.is_element() && matches!(local(n), "item" | "entry")) { - match place(&item, &mut lost_holes) { + match place(&item, &mut lost_holes, &mut excess_points) { Ok(Some(g)) => { let i = match g.kind() { GeometryType::Polyline => 1, @@ -185,6 +188,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } } let mut report = ReadReport { skipped, ..ReadReport::default() }; + if excess_points > 0 { + let (pairs, verb) = if excess_points == 1 { ("pair", "was") } else { ("pairs", "were") }; + report.messages.push(format!("{excess_points} excess GeoRSS Point coordinate {pairs} {verb} left out")); + } if skipped > 0 { report.messages.push(format!("{skipped} items had places that couldn't be read")); } @@ -216,6 +223,25 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> mod tests { use super::*; + #[test] + fn xml_loss_excess_point_pairs_are_counted() { + for place in [ + "1 2 3 4 5 6", + "1 2 3 4 5 6", + ] { + let xml = format!( + r#"kept{place}"# + ); + let layers = read("a.rss", xml.as_bytes()).unwrap(); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(2.0, 1.0)))); + assert_eq!(layers[0].0.value(0, 0), &Value::Text("kept".into())); + assert_eq!(layers[0].1.messages, ["2 excess GeoRSS Point coordinate pairs were left out"]); + let clean = xml.replace("1 2 3 4 5 6", "1 2"); + assert!(read("a.rss", clean.as_bytes()).unwrap()[0].1.messages.is_empty()); + } + } + const RSS: &str = r#" Quakes diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index 832260d674..f0691fcbe2 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -80,6 +80,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> return Err(DataError::Format(format!("{file_name}: not a GPX file"))); } let mut skipped = 0usize; + let mut short_segments = 0usize; let point_fields = |extra: &[(&str, FieldType)]| { let mut f: Vec = extra.iter().map(|(n, t)| Field::new(*n, *t)).collect(); f.extend(["name", "ele", "time", "desc", "cmt", "sym", "type"].iter().map(|n| Field::new(*n, FieldType::Text))); @@ -148,6 +149,8 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> count += part.len(); if part.len() >= 2 { parts.push(part); + } else if !part.is_empty() { + short_segments += 1; } } if parts.is_empty() { @@ -187,9 +190,17 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> out.push((ds, report)); } if let Some((_, report)) = out.first_mut() { + if short_segments > 0 { + let (segment, action) = if short_segments == 1 { + ("segment", "was left out of tracks; its point remains in track points") + } else { + ("segments", "were left out of tracks; their points remain in track points") + }; + report.messages.push(format!("{name}: {short_segments} GPX track {segment} with fewer than two usable points {action}")); + } report.skipped = skipped; if skipped > 0 { - report.messages.push(format!("{name}: {skipped} points, routes or tracks without usable coordinates were skipped")); + report.messages.push(format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped")); } } if out.is_empty() { @@ -202,6 +213,26 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> mod tests { use super::*; + #[test] + fn xml_loss_short_segments_are_counted_but_their_points_remain() { + let xml = br#"kept"#; + let layers = read("a.gpx", xml).unwrap(); + assert_eq!(layers.len(), 2); + assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Line(vec![vec![Coord::new(2.0, 1.0), Coord::new(4.0, 3.0)]]))); + assert_eq!(layers[0].0.value(0, 0), &Value::Text("kept".into())); + assert_eq!(layers[1].0.features.len(), 3); + assert_eq!(layers[1].0.features[2].geometry, Some(Geometry::Point(Coord::new(6.0, 5.0)))); + assert_eq!(layers[1].0.value(2, 1), &Value::Int(2)); + assert_eq!( + layers[0].1.messages, + ["a: 1 GPX track segment with fewer than two usable points was left out of tracks; its point remains in track points"] + ); + assert!(layers[1].1.messages.is_empty()); + let clean = + read("a.gpx", br#""#).unwrap(); + assert!(clean.iter().all(|(_, r)| r.messages.is_empty())); + } + const GPX: &str = r#" 35ParisFlag diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 44ee751fbb..00c40ee7c9 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -84,6 +84,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> { rows: Vec::new(), keys: Vec::new(), skipped: 0, + geometry_losses: GeometryLosses::default(), }; r.collect_styles(doc.root()); r.walk(doc.root(), &mut Vec::new(), 0); @@ -215,6 +216,7 @@ struct Reader { duplicate_entries: usize, duplicate_placemarks: usize, skipped: usize, + geometry_losses: GeometryLosses, } fn local<'a>(n: &Node<'a, '_>) -> &'a str { @@ -270,21 +272,26 @@ fn style_of(n: &Node) -> Style { } /// Coordinates: `lon,lat[,alt]` tuples separated by white space; malformed ones are dropped. -/// `zm` is set when a tuple kept had an altitude other than 0 (KML's default), which is dropped. -fn coords(s: &str, zm: &Cell) -> Vec { +/// `unreadable` counts rejected tuples. `zm` is set when a tuple kept had an altitude other than 0 (KML's default), which is dropped. +fn coords(s: &str, zm: &Cell, unreadable: &Cell) -> Vec { s.split_whitespace() .filter_map(|t| { - let mut it = t.split(','); - let x = it.next()?.trim().parse::().ok()?; - let y = it.next()?.trim().parse::().ok()?; - // Longitude/latitude, as KML always is. - if !crate::io::lon_lat_in_range(x, y) { - return None; - } - if it.next().and_then(|z| z.trim().parse::().ok()).is_some_and(|z| z != 0.0) { - zm.set(true); + let parsed = (|| { + let mut it = t.split(','); + let x = it.next()?.trim().parse::().ok()?; + let y = it.next()?.trim().parse::().ok()?; + if !crate::io::lon_lat_in_range(x, y) { + return None; + } + if it.next().and_then(|z| z.trim().parse::().ok()).is_some_and(|z| z != 0.0) { + zm.set(true); + } + Some(Coord::new(x, y)) + })(); + if parsed.is_none() { + unreadable.set(unreadable.get() + 1); } - Some(Coord::new(x, y)) + parsed }) .collect() } @@ -326,6 +333,47 @@ pub(crate) fn lost_vertices(g: &Geometry) -> usize { } } +/// Discards counted at their parsing seam, aggregated once per document. +#[derive(Default)] +struct GeometryLosses { + unreadable: Cell, + holes: usize, + short_lines: usize, + excess_points: usize, + polygons: usize, +} + +impl GeometryLosses { + /// Adds a placemark's losses without repeating the document's notices per layer. + fn add(&mut self, other: &Self) { + self.unreadable.set(self.unreadable.get() + other.unreadable.get()); + self.holes += other.holes; + self.short_lines += other.short_lines; + self.excess_points += other.excess_points; + self.polygons += other.polygons; + } + + /// Emits one counted notice per kind, only for nonzero totals. + fn report(&self, name: &str, report: &mut ReadReport) { + for (count, one, many) in [ + (self.unreadable.get(), "unreadable KML coordinate tuple", "unreadable KML coordinate tuples"), + (self.holes, "unreadable KML polygon hole", "unreadable KML polygon holes"), + ( + self.short_lines, + "KML line part with fewer than two usable coordinates", + "KML line parts with fewer than two usable coordinates", + ), + (self.excess_points, "excess KML Point coordinate tuple", "excess KML Point coordinate tuples"), + (self.polygons, "KML polygon without a usable outer ring", "KML polygons without a usable outer ring"), + ] { + if count > 0 { + let (subject, verb) = if count == 1 { (one, "was") } else { (many, "were") }; + report.messages.push(format!("{name}: {count} {subject} {verb} left out")); + } + } + } +} + /// The parts of a geometry element: (points, lines, polygons), MultiGeometry flattened. #[derive(Default)] struct Parts { @@ -334,10 +382,11 @@ struct Parts { polygons: Vec>>, /// An altitude other than 0 was dropped from the points, lines or polygons. zm: [Cell; 3], + losses: GeometryLosses, } /// Adds a geometry element's parts to `out` (MultiGeometry flattened, to `MAX_DEPTH`), marking -/// altitudes dropped. +/// altitudes and counting discarded coordinate tuples, holes and line parts. fn geometry(n: &Node, out: &mut Parts, depth: usize) { if depth > MAX_DEPTH { return; @@ -345,13 +394,20 @@ fn geometry(n: &Node, out: &mut Parts, depth: usize) { match local(n) { // Altitudes count only for the parts kept. "Point" => { - // The first tuple that reads is the point; only its altitude counts. - let first = child_text(n, "coordinates").and_then(|c| { - c.split_whitespace().find_map(|t| { + // Keep the first usable tuple and its altitude; count each tuple discarded. + let mut first = None; + if let Some(c) = child_text(n, "coordinates") { + for t in c.split_whitespace() { let alt = Cell::new(false); - coords(t, &alt).into_iter().next().map(|p| (p, alt.get())) - }) - }); + if let Some(p) = coords(t, &alt, &out.losses.unreadable).into_iter().next() { + if first.is_none() { + first = Some((p, alt.get())); + } else { + out.losses.excess_points += 1; + } + } + } + } if let Some((p, alt)) = first { out.zm[0].set(out.zm[0].get() || alt); out.points.push(p); @@ -359,50 +415,77 @@ fn geometry(n: &Node, out: &mut Parts, depth: usize) { } "LineString" | "LinearRing" => { let alt = Cell::new(false); - let c = child_text(n, "coordinates").map(|c| coords(&c, &alt)).unwrap_or_default(); + let text = child_text(n, "coordinates"); + let c = text.as_deref().map(|c| coords(c, &alt, &out.losses.unreadable)).unwrap_or_default(); if c.len() >= 2 { out.zm[1].set(out.zm[1].get() || alt.get()); out.lines.push(c); + } else if text.is_some() { + out.losses.short_lines += 1; } } "Polygon" => { let ring = |b: Node| { + let text = child(&b, "LinearRing").and_then(|r| child_text(&r, "coordinates"))?; let alt = Cell::new(false); - let r = child(&b, "LinearRing").and_then(|r| child_text(&r, "coordinates")).map(|c| coords(&c, &alt)); - r.filter(|c| c.len() >= 3).map(|c| (c, alt.get())) + Some((coords(&text, &alt, &out.losses.unreadable), alt.get())) }; - if let Some((outer, mut alt)) = child(n, "outerBoundaryIs").and_then(ring) { - let mut rings = vec![outer]; - for (r, a) in n.children().filter(|c| c.is_element() && local(c) == "innerBoundaryIs").filter_map(ring) { - alt |= a; - rings.push(r); + let outer = child(n, "outerBoundaryIs").and_then(ring); + let mut has_coordinates = outer.is_some(); + let mut kept = outer.filter(|(r, _)| r.len() >= 3).map(|(r, alt)| (vec![r], alt)); + // Read every hole even if the outer ring failed. Valid holes lost with their + // polygon are covered by the polygon count, not called unreadable holes. + for inner in n.children().filter(|c| c.is_element() && local(c) == "innerBoundaryIs") { + if let Some((r, a)) = ring(inner) { + has_coordinates = true; + if r.len() < 3 { + out.losses.holes += 1; + } else if let Some((rings, alt)) = &mut kept { + *alt |= a; + rings.push(r); + } } + } + if let Some((rings, alt)) = kept { out.zm[2].set(out.zm[2].get() || alt); out.polygons.push(rings); + } else if has_coordinates { + out.losses.polygons += 1; } } // A track: gx:coord elements of "lon lat alt". "Track" => { let mut alt = false; - let c: Vec = n - .children() - .filter(|c| c.is_element() && local(c) == "coord") - .filter_map(|c| { - let t = text_of(&c); + let mut has_coordinates = false; + let mut c = Vec::new(); + for node in n.children().filter(|c| c.is_element() && local(c) == "coord") { + let t = text_of(&node); + if t.is_empty() { + continue; + } + has_coordinates = true; + let parsed = (|| { let mut it = t.split_whitespace(); let x = it.next()?.parse::().ok()?; let y = it.next()?.parse::().ok()?; - // A track keeps any finite point, as it did before; only a kept point's altitude counts. + // A track keeps any finite coordinate, without the longitude/latitude range check. if !(x.is_finite() && y.is_finite()) { return None; } alt |= it.next().and_then(|z| z.parse::().ok()).is_some_and(|z| z != 0.0); Some(Coord::new(x, y)) - }) - .collect(); + })(); + if let Some(p) = parsed { + c.push(p); + } else { + out.losses.unreadable.set(out.losses.unreadable.get() + 1); + } + } if c.len() >= 2 { out.zm[1].set(out.zm[1].get() || alt); out.lines.push(c); + } else if has_coordinates { + out.losses.short_lines += 1; } } "MultiGeometry" | "MultiTrack" => { @@ -500,6 +583,7 @@ impl Reader { for g in pm.children().filter(|c| c.is_element()) { geometry(&g, &mut parts, 0); } + self.geometry_losses.add(&parts.losses); let mut data = Vec::new(); let mut seen = HashSet::new(); let mut duplicates = 0usize; @@ -640,6 +724,7 @@ impl Reader { let mut report = ReadReport::default(); // The notes go with the first layer only. if i == 0 { + self.geometry_losses.report(name, &mut report); report.skipped = self.skipped; if self.skipped > 0 { report.messages.push(format!("{name}: {} placemarks without a geometry RustGIS draws were skipped", self.skipped)); @@ -686,6 +771,121 @@ impl Reader { mod tests { use super::*; + /// A retained point makes discarded sibling geometry observable in both KML containers. + fn mixed_geometry_layers(geometry: &str, ext: &str) -> Vec { + let xml = format!( + r#"kept1,2{geometry}"# + ); + let bytes = if ext == "kmz" { crate::zip::write(&[("doc.kml".into(), xml.into_bytes())]).unwrap() } else { xml.into_bytes() }; + read(&format!("a.{ext}"), &bytes).unwrap() + } + + #[test] + fn xml_loss_polygon_without_outer_ring_counts_its_rings() { + let geometry = r#"0,0,8 bad1,1,99 2,1 2,2bad1,1 2,1 2,2"#; + for ext in ["kml", "kmz"] { + let layers = mixed_geometry_layers(geometry, ext); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].dataset.features.len(), 1); + assert_eq!(layers[0].dataset.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 2.0)))); + assert_eq!(layers[0].dataset.features[0].attrs[0], Value::Text("kept".into())); + assert!(!layers[0].dataset.zm_dropped, "discarded rings do not set a retained point's altitude flag"); + assert_eq!( + layers[0].report.messages, + [ + "a: 2 unreadable KML coordinate tuples were left out", + "a: 1 unreadable KML polygon hole was left out", + "a: 2 KML polygons without a usable outer ring were left out" + ] + ); + for clean in [ + "", + " ", + "0,0 4,0 4,4 0,01,1 2,1 2,2", + ] { + assert!(mixed_geometry_layers(clean, ext).iter().all(|l| l.report.messages.is_empty()), "{clean}"); + } + } + } + + #[test] + fn xml_loss_track_counts_nonempty_bad_coordinates() { + let geometry = "0 0bad 12 23 3 99 bad"; + for ext in ["kml", "kmz"] { + let layers = mixed_geometry_layers(geometry, ext); + assert_eq!(layers.len(), 2); + assert_eq!(layers[0].dataset.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 2.0)))); + assert_eq!( + layers[1].dataset.features[0].geometry, + Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(2.0, 2.0)]])) + ); + assert!(layers.iter().all(|l| !l.dataset.zm_dropped && l.dataset.features[0].attrs[0] == Value::Text("kept".into()))); + assert_eq!( + layers[0].report.messages, + [ + "a: 2 unreadable KML coordinate tuples were left out", + "a: 2 KML line parts with fewer than two usable coordinates were left out" + ] + ); + assert!(layers[1].report.messages.is_empty()); + let clean = mixed_geometry_layers( + " 200 100201 101", + ext, + ); + assert!( + clean.iter().all(|l| l.report.messages.is_empty()), + "empty tracks stay quiet; finite track coordinates keep their existing range policy" + ); + assert_eq!( + clean[1].dataset.features[0].geometry, + Some(Geometry::Line(vec![vec![Coord::new(200.0, 100.0), Coord::new(201.0, 101.0)]])) + ); + } + } + + #[test] + fn xml_loss_partial_geometry_losses_are_counted() { + let xml = br#"kept +1,2 3,4 5,6 +0,0 bad 2,2 +8,8 +0,0 4,0 4,4 0,0 +1,1 x,y +"#; + for ext in ["kml", "kmz"] { + let bytes = if ext == "kmz" { crate::zip::write(&[("doc.kml".into(), xml.to_vec())]).unwrap() } else { xml.to_vec() }; + let layers = read(&format!("a.{ext}"), &bytes).unwrap(); + assert_eq!(layers.len(), 3); + assert_eq!(layers[0].dataset.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 2.0)))); + assert_eq!( + layers[1].dataset.features[0].geometry, + Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(2.0, 2.0)]])) + ); + assert_eq!( + layers[2].dataset.features[0].geometry, + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(4.0, 0.0), + Coord::new(4.0, 4.0), + Coord::new(0.0, 0.0) + ]]])) + ); + assert!(layers.iter().all(|l| l.dataset.features[0].attrs[0] == Value::Text("kept".into()))); + let messages: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(String::as_str)).collect(); + assert_eq!( + messages, + [ + "a: 2 unreadable KML coordinate tuples were left out", + "a: 1 unreadable KML polygon hole was left out", + "a: 1 KML line part with fewer than two usable coordinates was left out", + "a: 2 excess KML Point coordinate tuples were left out" + ] + ); + } + let clean = read("a.kml", br#"1,2 0,0 4,0 4,4 0,0 "#).unwrap(); + assert!(clean[0].report.messages.is_empty()); + } + /// A KMZ's overlays of one picture are copied within the archive's budget; those past it are /// left out and counted apart from those that can't be drawn. #[test] diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index ebaf8786ff..4e7813a336 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -79,6 +79,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result) -> Result) -> Result 0 { + let (parcels, verb) = if missing_parcels == 1 { ("parcel", "was") } else { ("parcels", "were") }; + report.messages.push(format!("{missing_parcels} LandXML {parcels} without CoordGeom {verb} left out")); + } + report.skipped = skipped + missing_parcels; if skipped > 0 { report.messages.push(format!("{skipped} points, faces or figures couldn't be read and were left out")); } @@ -256,6 +264,18 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result1 2"#; + let layers = read("a.xml", xml, None).unwrap(); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(2.0, 1.0)))); + assert_eq!(layers[0].0.value(0, 0), &Value::Text("kept".into())); + assert_eq!(layers[0].1.messages, ["2 LandXML parcels without CoordGeom were left out"]); + let clean = br#"1 2"#; + assert!(read("a.xml", clean, None).unwrap()[0].1.messages.is_empty()); + } + const LANDXML: &str = r#" diff --git a/crates/engine/testdata/reading-losses/README.md b/crates/engine/testdata/reading-losses/README.md index 4c8b5f0f69..e42fc706d1 100644 --- a/crates/engine/testdata/reading-losses/README.md +++ b/crates/engine/testdata/reading-losses/README.md @@ -154,6 +154,18 @@ The corpus checks exact geometry, feature ID, field names/types and attributes t messages must be exactly the one-feature Z/M drop message for XYZ/XYM and absent for XY. Other geometry and attribute losses and network paging are outside these fixtures. +## XML partial-geometry notices + +The inline KML/KMZ pairs import with counted notices for unreadable coordinate tuples, +unreadable polygon holes, polygons without usable outer rings, short line parts and excess +Point coordinates. The tuple and short-part notices also cover `gx:Track`. GPX reports short +segments omitted from track lines while retaining their usable points in the track-points +layer. GeoRSS reports excess Point coordinate pairs; LandXML reports parcels without +`CoordGeom`. Clean counterparts give none of these notices. Native regressions assert retained +coordinates and attributes, and the command corpus compares retained data and exact native +notices through `layer.addData`. Ten logical cases have seventeen rows with the KMZ twins; they do +not establish completeness for these formats or cover the gaps below. + ## Standalone DBF The harness independently encodes two dBASE III tables directly from the header and diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index c2ae5fb212..42a4692d34 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -90,10 +90,20 @@ struct Case { /// Files beside the clean and lossy inputs (binary indexes can differ). beside: [Vec<(&'static str, Vec)>; 2], expect: Expect, + /// Additional exact notices for this case's lossy input, in report order before its primary notice. + extra_notices: &'static [&'static str], } fn case(name: &'static str, file: &'static str, clean: impl AsRef<[u8]>, lossy: impl AsRef<[u8]>, expect: Expect) -> Case { - Case { name, file, clean: clean.as_ref().to_vec(), lossy: lossy.as_ref().to_vec(), beside: [Vec::new(), Vec::new()], expect } + Case { + name, + file, + clean: clean.as_ref().to_vec(), + lossy: lossy.as_ref().to_vec(), + beside: [Vec::new(), Vec::new()], + expect, + extra_notices: &[], + } } /// A GeoJSON feature collection of these geometries. @@ -196,6 +206,10 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "0 0 0 4 4 4 0 0{hole}" ) }; + let track = |coords: &[&str]| { + let body: String = coords.iter().map(|c| format!("{c}")).collect(); + format!(r#"{body}"#) + }; let polyline = |middle: &str| format!("0 POLYLINE 8 0 66 1 70 0 0 VERTEX 8 0 10 0 20 0 0 VERTEX 8 0 {middle} 0 VERTEX 8 0 10 2 20 2 0 SEQEND"); let parcel = r#"0 00 100 1010 1010 100 0"#; @@ -291,15 +305,18 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.kml", kml(&["0,0 1,1 2,2"]), kml(&["0,0 x,1 2,2"]), - Silent("the coordinate is skipped and the line drawn without it"), - ), - case( - "KML: an unreadable hole", - "a.kml", - kml(&[&kml_polygon("1,1 2,1 2,2 1,1")]), - kml(&[&kml_polygon("1,1 x,y")]), - Silent("the hole is left out of the polygon"), + Imported("1 unreadable KML coordinate tuple was left out"), ), + Case { + extra_notices: &["a: 1 unreadable KML coordinate tuple was left out"], + ..case( + "KML: an unreadable hole", + "a.kml", + kml(&[&kml_polygon("1,1 2,1 2,2 1,1")]), + kml(&[&kml_polygon("1,1 x,y")]), + Imported("1 unreadable KML polygon hole was left out"), + ) + }, case( "KML: an unreadable part", "a.kml", @@ -309,14 +326,39 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { kml(&[ "1,10,0", ]), - Silent("a line of one point is left out of the placemark"), + Imported("1 KML line part with fewer than two usable coordinates was left out"), ), case( "KML: a point with more than one coordinate", "a.kml", kml(&["1,1"]), kml(&["1,1 2,2"]), - Silent("only the first coordinate is kept"), + Imported("1 excess KML Point coordinate tuple was left out"), + ), + case( + "KML: a polygon without a usable outer ring", + "a.kml", + kml(&[ + "1,20,0 4,0 4,4", + ]), + kml(&[ + "1,20,0", + ]), + Imported("1 KML polygon without a usable outer ring was left out"), + ), + case( + "KML: an unreadable gx:Track coordinate", + "a.kml", + kml(&[&track(&["0 0", "1 1", "2 2"])]), + kml(&[&track(&["0 0", "bad 1", "2 2"])]), + Imported("1 unreadable KML coordinate tuple was left out"), + ), + case( + "KML: a short gx:Track", + "a.kml", + kml(&[&format!("1,2{}", track(&["0 0", "1 1"]))]), + kml(&[&format!("1,2{}", track(&["0 0"]))]), + Imported("1 KML line part with fewer than two usable coordinates was left out"), ), // GPX. case( @@ -324,7 +366,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.gpx", gpx(r#""#), gpx(r#""#), - Said("without usable coordinates"), + Said("without usable geometry"), ), case( "GPX: a track segment of one point", @@ -333,7 +375,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { r#""#, ), gpx(r#""#), - Silent("the segment is left out of the track's line"), + Imported("1 GPX track segment with fewer than two usable points was left out of tracks; its point remains in track points"), ), // Feature-service PBF has a distinct sniffed parser from OSM PBF. case( @@ -409,7 +451,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.rss", georss(&["45 -71"]), georss(&["45 -71 46 -72"]), - Silent("only the first pair is kept"), + Imported("1 excess GeoRSS Point coordinate pair was left out"), ), // DXF. case( @@ -446,7 +488,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.xml", landxml(&format!("{}{parcel}", cg_points("1 1"))), landxml(&format!(r#"{}"#, cg_points("1 1"))), - Silent("the parcel is left out"), + Imported("1 LandXML parcel without CoordGeom was left out"), ), // Shapefile. 臺北101 as UTF-8, and in Big5, which isn't UTF-8. case( @@ -573,6 +615,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { lossy: rustgis_engine::data::zip::write(&[("doc.kml".into(), c.lossy.clone())]).unwrap(), beside: [Vec::new(), Vec::new()], expect: c.expect, + extra_notices: c.extra_notices, }) .collect::>(); out.extend(kmz); @@ -1080,3 +1123,64 @@ fn a_reading_that_loses_something_says_so() { let _ = std::fs::remove_dir_all(&root); assert!(failures.is_empty(), "{} of the cases failed:\n{}", failures.len(), failures.join("\n")); } + +/// The pinned XML losses keep their native data and deliver exactly those notices at command ingress. +#[test] +fn xml_losses_keep_data_and_reach_command() { + use rustgis_engine::data::{Dataset, ReadReport, georss, gpx, kml, landxml}; + let root = std::env::temp_dir().join(format!("rustgis-xml-loss-reading-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let mut checked = 0; + for c in cases(&root.join("fixtures")) { + let Imported(words) = c.expect else { continue }; + if !["KML:", "GPX:", "GeoRSS:", "LandXML:"].iter().any(|prefix| c.name.starts_with(prefix)) { + continue; + } + checked += 1; + for (lossy, bytes) in [(false, &c.clean), (true, &c.lossy)] { + let native: Vec<(Dataset, ReadReport)> = match c.file { + "a.kml" | "a.kmz" => kml::read(c.file, bytes).unwrap().into_iter().map(|l| (l.dataset, l.report)).collect(), + "a.gpx" => gpx::read(c.file, bytes).unwrap(), + "a.rss" => georss::read(c.file, bytes).unwrap(), + "a.xml" => landxml::read(c.file, bytes, None).unwrap(), + other => panic!("unexpected XML fixture {other}"), + }; + let messages: Vec<_> = native.iter().flat_map(|(_, r)| r.messages.iter().cloned()).collect(); + let expected = if c.file.ends_with("kml") || c.file.ends_with("kmz") || c.file.ends_with("gpx") { + format!("a: {words}") + } else { + words.to_string() + }; + let mut expected_messages = Vec::new(); + if c.file == "a.xml" { + expected_messages.push( + "the file doesn't say its coordinate system (give \"crs\", such as EPSG:2263): coordinates are kept as they are" + .to_string(), + ); + } + if lossy { + expected_messages.extend(c.extra_notices.iter().map(|m| (*m).to_string())); + expected_messages.push(expected); + } + assert_eq!(messages, expected_messages, "{} native notices", c.name); + let path = root.join(c.file); + std::fs::write(&path, bytes).unwrap(); + let mut session = Session::new(Project::default()); + let mark = session.notice_mark(); + session.run("layer.addData", &json!({"path": path})).unwrap(); + assert_eq!(session.map().layers.len(), native.len(), "{} layer count", c.name); + for (ds, _) in &native { + let mut matches = session.map().layers.iter().filter(|layer| layer.dataset.name == ds.name); + let layer = matches.next().unwrap_or_else(|| panic!("{} missing dataset {}", c.name, ds.name)); + assert!(matches.next().is_none(), "{} repeated dataset {}", c.name, ds.name); + assert_eq!(layer.dataset.fields, ds.fields, "{} fields", c.name); + assert_eq!(layer.dataset.features, ds.features, "{} retained data", c.name); + assert_eq!(layer.dataset.held_in, ds.held_in, "{} held CRS", c.name); + } + let said: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said, messages, "{} command notices", c.name); + } + } + assert_eq!(checked, 17, "ten logical cases, seventeen rows with the KMZ twins"); + let _ = std::fs::remove_dir_all(root); +}