diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 00ce0d2393..428bf66793 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -539,17 +539,22 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> continue; } let s = g.attribute("srsName").or_else(|| g.descendants().find_map(|d| d.attribute("srsName"))); + // A system RustGIS doesn't know is said only for a geometry read in it. + let mut unknown = None; if let Some(s) = s { match srs(s) { Some(found) => { file_srs.get_or_insert(found); } - None => unknown_srs = Some(s.to_string()), + None => unknown = Some(s.to_string()), } } let (dims, lost) = (Cell::new(false), Cell::new(0)); match geometry(&g, &dims, &lost) { Some(gm) => { + if unknown.is_some() { + unknown_srs = unknown; + } zm = dims.get(); rings_lost += lost.get(); geom = Some(gm); @@ -730,7 +735,11 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> rep.skipped = kind.skipped; if kind.skipped > 0 { let what = if kind.skipped == 1 { "feature" } else { "features" }; - rep.messages.push(format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped)); + // Kept, without the geometry. + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped), + )); } if unplaced > 0 { let what = if unplaced == 1 { "feature has" } else { "features have" }; @@ -799,9 +808,9 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } if unread > 0 { let what = if unread == 1 { "property" } else { "properties" }; - rep.messages.push(format!( - "{}: {unread} {what} not read: nested records, other GML values or further shapes ({unread_names})", - ds.name + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{}: {unread} {what} not read: nested records, other GML values or further shapes ({unread_names})", ds.name), )); } if kind.repeated > 0 { @@ -990,7 +999,10 @@ mod tests { // Its height is dropped, and said; so is the nested `member` property, not an attribute. assert!(ds.zm_dropped && rep.messages.iter().any(|m| m.contains("Z or M values")), "{:?}", rep.messages); assert!( - rep.messages.iter().any(|m| m == "n: 1 property not read: nested records, other GML values or further shapes (member)"), + rep.messages + .iter() + .any(|m| m.as_str() == "n: 1 property not read: nested records, other GML values or further shapes (member)" + && m.loss == Some(crate::loss::LossCode::DroppedValue)), "{:?}", rep.messages ); @@ -1123,9 +1135,8 @@ mod tests { // The first shape is the one kept; the second is said as not read. assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(10.0, 48.0)))); assert!( - rep.messages - .iter() - .any(|m| m == "t parks: 3 properties not read: nested records, other GML values or further shapes (owner, built, entrance)"), + rep.messages.iter().any(|m| m.as_str() + == "t parks: 3 properties not read: nested records, other GML values or further shapes (owner, built, entrance)"), "{:?}", rep.messages ); @@ -1140,7 +1151,9 @@ mod tests { let (ds, rep) = &layers[0]; assert_eq!((ds.features.len(), rep.skipped), (1, 0), "{:?}", rep.messages); assert!( - rep.messages.iter().any(|m| m == "d: 4 properties not read: nested records, other GML values or further shapes (a, b, c, …)"), + rep.messages + .iter() + .any(|m| m.as_str() == "d: 4 properties not read: nested records, other GML values or further shapes (a, b, c, …)"), "{:?}", rep.messages ); @@ -1424,6 +1437,31 @@ mod tests { assert!(!said(&lossy[0], "couldn't be read") && said(&lossy[1], "t parks: 1 feature had geometry that couldn't be read")); let clean = read("t.gml", two("10 49").as_bytes()).unwrap(); assert!(clean.iter().all(|l| l.1.skipped == 0 && !said(l, "couldn't be read"))); + // The feature is kept, without its geometry. + assert_eq!(lossy[1].0.features.len(), 1); + let note = lossy[1].1.messages.iter().find(|m| m.contains("couldn't be read")).unwrap(); + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedGeometry)); + } + + /// A system RustGIS doesn't know is said, as assumed, only for a geometry read in it: one that + /// names it and can't be read places nothing there. + #[test] + fn an_unknown_system_is_said_only_for_a_geometry_read_in_it() { + let member = |g: &str| doc(&format!("{g}")); + let unknown = |layers: &[(Dataset, ReadReport)]| { + layers + .iter() + .flat_map(|l| l.1.messages.iter()) + .filter(|m| m.contains("unknown coordinate system")) + .map(|m| m.loss) + .collect::>() + }; + let read_in_it = + read("t.gml", member(r#"10 48"#).as_bytes()).unwrap(); + assert_eq!(unknown(&read_in_it), [Some(crate::loss::LossCode::AssumedCrs)]); + let failed = + read("t.gml", member(r#"bad"#).as_bytes()).unwrap(); + assert!(unknown(&failed).is_empty(), "{:?}", failed[0].1.messages); } /// #1620: unread property names come in document order, and a `gml:description` value is no shape. diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index 074285c670..6c832b647b 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -81,6 +81,8 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } let mut skipped = 0usize; let mut short_segments = 0usize; + // Route points without usable coordinates: vertices left out of their route, not features. + let mut route_points = 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))); @@ -110,17 +112,19 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> }; let mut routes = Dataset::new(format!("{name} routes"), GeometryType::Polyline, line_fields()); for r in children(&gpx, "rte") { - let mut pts = Vec::new(); + let (mut pts, mut unplaced) = (Vec::new(), 0usize); for p in children(&r, "rtept") { match coord(&p) { Some(c) => pts.push(c), - None => skipped += 1, + None => unplaced += 1, } } let n = pts.len(); if n >= 2 { routes.push_next(Some(Geometry::Line(vec![pts])), line_attrs(&r, n)); + route_points += unplaced; } else { + // Left out whole, said with the routes; its points aren't also a kept route's loss. skipped += 1; } } @@ -196,11 +200,29 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } 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.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{name}: {short_segments} GPX track {segment} with fewer than two usable points {action}"), + )); + } + if route_points > 0 { + let what = if route_points == 1 { + "point without usable coordinates was left out of its route" + } else { + "points without usable coordinates were left out of their routes" + }; + report + .messages + .push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!("{name}: {route_points} GPX route {what}"))); } report.skipped = skipped; if skipped > 0 { - report.messages.push(format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped")); + let what = if skipped == 1 { + "point, route or track without usable geometry was skipped" + } else { + "points, routes or tracks without usable geometry were skipped" + }; + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, format!("{name}: {skipped} {what}"))); } } if out.is_empty() { @@ -224,9 +246,10 @@ mod tests { 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, + layers[0].1.messages.texts().collect::>(), ["a: 1 GPX track segment with fewer than two usable points was left out of tracks; its point remains in track points"] ); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedGeometry)); assert!(layers[1].1.messages.is_empty()); let clean = read("a.gpx", br#""#).unwrap(); @@ -245,6 +268,26 @@ mod tests { "#; + /// A route point without usable coordinates is left out of a route that is kept: its geometry + /// lost a vertex, said apart from the points, routes and tracks left out whole. + #[test] + fn a_route_point_without_coordinates_is_a_vertex_left_out() { + let xml = br#"kept"#; + let layers = read("a.gpx", xml).unwrap(); + let (routes, _) = layers.iter().find(|(d, _)| d.name == "a routes").unwrap(); + assert_eq!(routes.features.len(), 1); + let report = &layers[0].1; + assert_eq!(report.skipped, 1, "only the waypoint off the globe is a feature left out"); + let said: Vec<_> = report.messages.iter().map(|m| (m.as_str(), m.loss)).collect(); + assert_eq!( + said, + [ + ("a: 1 GPX route point without usable coordinates was left out of its route", Some(crate::loss::LossCode::DroppedGeometry)), + ("a: 1 point, route or track without usable geometry was skipped", Some(crate::loss::LossCode::DroppedFeature)), + ] + ); + } + #[test] fn splits_into_layers() { let layers = read("run.gpx", GPX.as_bytes()).unwrap(); diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 6ff3f9fcf5..9dc269e6b9 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -355,20 +355,23 @@ impl GeometryLosses { /// 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"), + use crate::loss::LossCode::{DroppedGeometry, DroppedRing}; + // Each is a part left out of a kept placemark's geometry. + for (count, one, many, code) in [ + (self.unreadable.get(), "unreadable KML coordinate tuple", "unreadable KML coordinate tuples", DroppedGeometry), + (self.holes, "unreadable KML polygon hole", "unreadable KML polygon holes", DroppedRing), ( self.short_lines, "KML line part with fewer than two usable coordinates", "KML line parts with fewer than two usable coordinates", + DroppedGeometry, ), - (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"), + (self.excess_points, "excess KML Point coordinate tuple", "excess KML Point coordinate tuples", DroppedGeometry), + (self.polygons, "KML polygon without a usable outer ring", "KML polygons without a usable outer ring", DroppedGeometry), ] { if count > 0 { let (subject, verb) = if count == 1 { (one, "was") } else { (many, "were") }; - report.messages.push(format!("{name}: {count} {subject} {verb} left out")); + report.messages.push(crate::loss::Note::loss(code, format!("{name}: {count} {subject} {verb} left out"))); } } } @@ -583,7 +586,9 @@ impl Reader { for g in pm.children().filter(|c| c.is_element()) { geometry(&g, &mut parts, 0); } - self.geometry_losses.add(&parts.losses); + // A placemark left out whole is said as one; only a kept one's parts left out are its + // geometry's loss. + let losses = std::mem::take(&mut parts.losses); let mut data = Vec::new(); let mut seen = HashSet::new(); let mut duplicates = 0usize; @@ -646,6 +651,9 @@ impl Reader { if !parts.polygons.is_empty() { push(Geometry::Polygon(parts.polygons), &parts.zm[2], &mut self.rows); } + if any { + self.geometry_losses.add(&losses); + } if !any { self.skipped += 1; } else if duplicates > 0 { @@ -733,9 +741,12 @@ impl Reader { )); } if self.duplicate_entries > 0 { - report.messages.push(format!( - "{name}: {} repeated ExtendedData entries in {} placemarks were left out", - self.duplicate_entries, self.duplicate_placemarks + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!( + "{name}: {} repeated ExtendedData entries in {} placemarks were left out", + self.duplicate_entries, self.duplicate_placemarks + ), )); } if self.dropped_keys > 0 { @@ -800,13 +811,16 @@ mod tests { 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, + layers[0].report.messages.texts().collect::>(), [ "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" ] ); + use crate::loss::LossCode::{DroppedGeometry, DroppedRing}; + let codes: Vec<_> = layers[0].report.messages.iter().map(|m| m.loss).collect(); + assert_eq!(codes, [Some(DroppedGeometry), Some(DroppedRing), Some(DroppedGeometry)]); for clean in [ "", " ", @@ -830,7 +844,7 @@ mod tests { ); 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, + layers[0].report.messages.texts().collect::>(), [ "a: 2 unreadable KML coordinate tuples were left out", "a: 2 KML line parts with fewer than two usable coordinates were left out" @@ -852,6 +866,19 @@ mod tests { } } + /// A placemark left out whole is said once, as one: the parts of it that couldn't be read + /// aren't also a kept placemark's geometry loss. + #[test] + fn a_placemark_left_out_whole_is_said_once() { + let layers = read( + "a.kml", + br#"x,y 1,21,2"#, + ) + .unwrap(); + let said: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(|m| (m.as_str(), m.loss))).collect(); + assert_eq!(said, [("a: 1 placemarks without a geometry RustGIS draws were skipped", Some(crate::loss::LossCode::DroppedFeature))]); + } + #[test] fn xml_loss_partial_geometry_losses_are_counted() { let xml = br#"kept @@ -890,6 +917,9 @@ mod tests { "a: 2 excess KML Point coordinate tuples were left out" ] ); + use crate::loss::LossCode::{DroppedGeometry, DroppedRing}; + let codes: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(|m| m.loss)).collect(); + assert_eq!(codes, [Some(DroppedGeometry), Some(DroppedRing), Some(DroppedGeometry), Some(DroppedGeometry)]); } let clean = read("a.kml", br#"1,2 0,0 4,0 4,4 0,0 "#).unwrap(); assert!(clean[0].report.messages.is_empty()); @@ -949,7 +979,11 @@ mod tests { let layers = read("duplicates.kml", xml.as_bytes()).unwrap(); assert_eq!(layers.len(), 2); let messages: Vec<_> = layers.iter().flat_map(|l| &l.report.messages).collect(); - assert_eq!(messages, ["duplicates: 4 repeated ExtendedData entries in 2 placemarks were left out"]); + assert_eq!( + messages.iter().map(|m| m.as_str()).collect::>(), + ["duplicates: 4 repeated ExtendedData entries in 2 placemarks were left out"] + ); + assert_eq!(messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); for layer in &layers { let ds = &layer.dataset; assert_eq!(ds.value(0, ds.field_index("n").unwrap()), &Value::Int(0)); diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index d1f0c8331d..347911e41e 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -80,6 +80,10 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result) -> Result Vec { + // `unread` counts the point references (a Start or End) that can't be read. + let path = |cg: &Node, unread: &mut usize| -> Vec { let mut pts: Vec = Vec::new(); for seg in cg.children().filter(|c| c.is_element() && matches!(local(c), "Line" | "Curve" | "Spiral" | "IrregularLine")) { // A curve's PI (where its tangents meet) is off the curve: its chord runs Start to End. @@ -122,7 +127,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result pts.push(c), Some(_) => {} - None => *skipped += 1, + None => *unread += 1, } } } @@ -140,7 +145,8 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result) -> Result().ok()).map(Value::Float).unwrap_or_default(); let attr = |k: &str| p.attribute(k).map(|v| Value::Text(v.to_string())).unwrap_or_default(); parcels.push_next(Some(Geometry::Polygon(vec![vec![ring]])), vec![attr("name"), area, attr("desc")]); @@ -161,12 +168,19 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result().ok()).map(Value::Float).unwrap_or_default(); alignments.push_next( Some(Geometry::Line(vec![line])), @@ -180,24 +194,33 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result = Vec::new(); + let mut faces_left_out = 0usize; for s in elements(&root, "Surface") { let sname = s.attribute("name").unwrap_or("").to_string(); let mut pnts: HashMap<&str, (Coord, Option)> = HashMap::new(); for p in elements(&s, "P") { + // A point that can't be read isn't kept. The faces that name it are left out, and + // counted as features, so the point is said on its own without a code. match (p.attribute("id"), nez(&text_of(&p))) { (Some(id), Some(v)) => { pnts.insert(id, v); } - _ => skipped += 1, + _ => surface_points += 1, } } - for (i, f) in elements(&s, "F").enumerate() { + // Invisible faces (i="1") are holes in the surface, never read, so the cap counts the + // faces that are. + for (i, f) in elements(&s, "F").filter(|f| f.attribute("i") != Some("1")).enumerate() { + // Past the limit, a face is only counted, so the notice says how many are left out. if i >= MAX_FACES { - report.messages.push(format!("surface '{sname}' has more than {MAX_FACES} faces: the rest are left out")); - break; - } - // Invisible faces (i="1") are holes in the surface. - if f.attribute("i") == Some("1") { + if i == MAX_FACES { + over_limit.push(sname.clone()); + } + faces_left_out += 1; continue; } let tri: Option)>> = text_of(&f).split_whitespace().map(|id| pnts.get(id).copied()).collect(); @@ -215,6 +238,29 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { + let what = if surface_points == 1 { "surface point couldn't be read and was" } else { "surface points couldn't be read and were" }; + report.messages.push(format!("{surface_points} LandXML {what} left out")); + } + match over_limit.as_slice() { + [] => {} + [one] => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("surface '{one}' has more than {MAX_FACES} faces: the {faces_left_out} past the limit are left out"), + )), + many => { + let shown: Vec = many.iter().take(10).map(|n| format!("'{n}'")).collect(); + let more = if many.len() > 10 { format!(" and {} more", many.len() - 10) } else { String::new() }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!( + "{} surfaces ({}{more}) have more than {MAX_FACES} faces: the {faces_left_out} past the limit are left out", + many.len(), + shown.join(", ") + ), + )); + } + } if missing_parcels > 0 { let (parcels, verb) = if missing_parcels == 1 { ("parcel", "was") } else { ("parcels", "were") }; report.messages.push(crate::loss::Note::loss( @@ -222,9 +268,31 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { + let (alignments, verb) = if missing_alignments == 1 { ("alignment", "was") } else { ("alignments", "were") }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{missing_alignments} LandXML {alignments} without CoordGeom {verb} left out"), + )); + } + report.skipped = skipped + missing_parcels + missing_alignments; if skipped > 0 { - report.messages.push(format!("{skipped} points, faces or figures couldn't be read and were left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + if skipped == 1 { + "1 point, face or figure couldn't be read and was left out".to_string() + } else { + format!("{skipped} points, faces or figures couldn't be read and were left out") + }, + )); + } + if vertices > 0 { + let what = if vertices == 1 { + "point reference (a Start or End) couldn't be read and was left out of its shape" + } else { + "point references (a Start or End) couldn't be read and were left out of their shapes" + }; + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!("{vertices} LandXML {what}"))); } let mut out: Vec<(Dataset, ReadReport)> = Vec::new(); let transformer = match crs.filter(|c| *c != Crs::LonLat) { @@ -301,6 +369,61 @@ mod tests { 1 2 31 3 41 2 41 2 9 "#; + /// A surface point that can't be read is said, without a code: the faces that name it are + /// counted as the features left out. + #[test] + fn an_unreadable_surface_point_is_said() { + let xml = r#" +

0 0 1

0 1 1

1 0 1

x y

+
1 2 3
"#; + let layers = read("s.xml", xml.as_bytes(), None).unwrap(); + let said: Vec<_> = layers[0].1.messages.iter().filter(|m| m.contains("surface point")).map(|m| (m.as_str(), m.loss)).collect(); + assert_eq!(said, [("1 LandXML surface point couldn't be read and was left out", None)]); + } + + /// An alignment without its CoordGeom has no shape: it is left out, and said with the + /// features left out. + #[test] + fn an_alignment_without_coordgeom_is_said_left_out() { + let xml = r#"0 0"#; + let layers = read("a.xml", xml.as_bytes(), None).unwrap(); + assert_eq!(layers[0].1.skipped, 1); + let said: Vec<_> = layers[0].1.messages.iter().filter(|m| m.contains("left out")).map(|m| (m.as_str(), m.loss)).collect(); + assert_eq!(said, [("1 LandXML alignment without CoordGeom was left out", Some(crate::loss::LossCode::DroppedFeature))]); + } + + /// A point reference (a Start or End) a parcel's CoordGeom gives that can't be read is left + /// out of a parcel that is still kept: its geometry's loss, said apart from the features left + /// out. Each reference counts once, as the notice says, whether or not two of them meant the + /// same point. + #[test] + fn a_point_reference_left_out_is_said_apart_from_features() { + let xml = r#" + 0 01 0 + 1 1 + 1 10 1 +"#; + let layers = read("v.xml", xml.as_bytes(), None).unwrap(); + assert_eq!(layers[0].0.features.len(), 1, "the parcel is kept"); + assert_eq!(layers[0].1.skipped, 0, "no feature is left out"); + let said: Vec<_> = layers[0].1.messages.iter().filter(|m| m.contains("left out")).map(|m| (m.as_str(), m.loss)).collect(); + assert_eq!( + said, + [( + "1 LandXML point reference (a Start or End) couldn't be read and was left out of its shape", + Some(crate::loss::LossCode::DroppedGeometry) + )] + ); + // One line's End and the next one's Start, both unreadable: two references. + let junction = xml.replace( + "1 1", + "1 0x yx y1 1", + ); + let layers = read("j.xml", junction.as_bytes(), None).unwrap(); + let said: Vec<_> = layers[0].1.messages.texts().filter(|m| m.contains("point reference")).collect(); + assert_eq!(said, ["2 LandXML point references (a Start or End) couldn't be read and were left out of their shapes"]); + } + #[test] fn reads_landxml() { assert!(looks_like_landxml(LANDXML)); @@ -326,6 +449,9 @@ mod tests { assert_eq!(faces.features.len(), 2, "the invisible face is a hole; the face naming a missing point is skipped"); assert_eq!(faces.features[0].attrs[1], Value::Float(102.0)); assert!(layers[0].1.skipped >= 2); + // The point and the face left out are features; nothing in this file loses a vertex. + let said: Vec<_> = layers[0].1.messages.iter().filter(|m| m.contains("left out")).map(|m| (m.as_str(), m.loss)).collect(); + assert_eq!(said, [("2 points, faces or figures couldn't be read and were left out", Some(crate::loss::LossCode::DroppedFeature))]); assert!(looks_like_landxml(&format!("{}é", " ".repeat(4087))), "a head cut inside a character"); // A given system wins; none at all keeps the coordinates. let plain = LANDXML.replace("", ""); diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index c265fc0363..716cd3adae 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -241,7 +241,8 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe .unwrap_or(w.len()); match coordsys(w.get(i + 1..end).unwrap_or_default()) { Ok(c) => crs = c, - Err(e) => report.messages.push(e), + // Its coordinates are kept as they are: a system assumed. + Err(e) => report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, e)), } i = end; } @@ -378,38 +379,49 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe } } } - for (count, one, many) in [ - (arcs, "MapInfo arc object was kept as a row without geometry", "MapInfo arc objects were kept as rows without geometry"), + use crate::loss::LossCode::{DroppedGeometry, DroppedRing}; + for (count, one, many, code) in [ + ( + arcs, + "MapInfo arc object was kept as a row without geometry", + "MapInfo arc objects were kept as rows without geometry", + DroppedGeometry, + ), ( texts, "MapInfo text object was kept as a row without its position or text", "MapInfo text objects were kept as rows without their position or text", + DroppedGeometry, ), ( short_parts, "MapInfo line part with fewer than two coordinates was omitted", "MapInfo line parts with fewer than two coordinates were omitted", + DroppedGeometry, ), ( short_rings, "MapInfo polygon ring with fewer than four coordinates after closure was omitted", "MapInfo polygon rings with fewer than four coordinates after closure were omitted", + DroppedRing, ), ] { if count > 0 { let subject = if count == 1 { one } else { many }; - report.messages.push(format!("{count} {subject}")); + report.messages.push(crate::loss::Note::loss(code, format!("{count} {subject}"))); } } if empty_objects > 0 { let subject = if empty_objects == 1 { "object was kept as a row" } else { "objects were kept as rows" }; let possessive = if empty_objects == 1 { "its" } else { "their" }; - report - .messages - .push(format!("{empty_objects} MapInfo {subject} without geometry because all {possessive} parts or rings were too short")); + report.messages.push(crate::loss::Note::loss( + DroppedGeometry, + format!("{empty_objects} MapInfo {subject} without geometry because all {possessive} parts or rings were too short"), + )); } + // The objects after one that can't be read are left out. if let Some(e) = error { - report.messages.push(e); + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, e)); } if !columns.is_empty() && mid.is_none() { report.messages.push("no .mid file next to the .mif: the attributes are empty"); @@ -530,19 +542,31 @@ mod tests { assert_eq!(ds.features[1].geometry, Some(Geometry::Point(Coord::new(9.0, 9.0)))); assert_eq!(ds.features[1].attrs, vec![Value::Int(8)]); assert_eq!(report.skipped, 0); - assert_eq!(report.messages, [message]); + assert_eq!(report.messages.texts().collect::>(), [message]); + let code = + if message.contains("polygon ring") { crate::loss::LossCode::DroppedRing } else { crate::loss::LossCode::DroppedGeometry }; + assert_eq!(report.messages[0].loss, Some(code), "{message}"); let mif = format!("Columns 1\nid Integer\nData\n{object}\n{object}\n"); let (twice, report) = read(&mif, Some("7\n8\n"), "twice").unwrap(); assert_eq!(twice.features.len(), 2); assert_eq!(twice.features[0].geometry, geometry); assert_eq!(twice.features[1].geometry, geometry); - assert_eq!(report.messages, [repeated_message]); + assert_eq!(report.messages.texts().collect::>(), [repeated_message]); } let (_, clean) = read("Columns 1\nid Integer\nData\nPline 2 0 0 1 1\nRegion 1 3 0 0 4 0 4 4\nNone", Some("1\n2\n3"), "clean").unwrap(); assert!(clean.messages.is_empty(), "{clean:?}"); } + /// An object that can't be read ends the read: the objects after it are left out, said as + /// dropped features. + #[test] + fn the_objects_after_one_that_cant_be_read_are_said_left_out() { + let (_, report) = read("Columns 1\nid Integer\nData\nPoint 0 0\nRegion x\nPoint 1 1\n", Some("1\n2\n3\n"), "cut").unwrap(); + let note = report.messages.iter().find(|m| m.contains("the objects after it are left out")).unwrap(); + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedFeature), "{:?}", report.messages); + } + /// A row stays aligned even when all of its short line parts or polygon rings disappear. #[test] fn all_short_parts_keep_rows_and_report_missing_geometry() { @@ -559,9 +583,10 @@ mod tests { assert_eq!(ds.features[1].attrs, [Value::Int(8)]); assert_eq!(report.skipped, 0); assert_eq!( - report.messages, + report.messages.texts().collect::>(), [part_note, "1 MapInfo object was kept as a row without geometry because all its parts or rings were too short",] ); + assert_eq!(report.messages[1].loss, Some(crate::loss::LossCode::DroppedGeometry)); } } @@ -622,7 +647,7 @@ mod tests { assert!(matches!(&ds.features[3].geometry, Some(Geometry::Line(l)) if l.len() == 2)); assert!(ds.features[4].geometry.is_none() && ds.features[5].geometry.is_none(), "text and none"); assert!(matches!(&ds.features[6].geometry, Some(Geometry::Polygon(_)))); - assert_eq!(rep.messages, ["1 MapInfo text object was kept as a row without its position or text"]); + assert_eq!(rep.messages.texts().collect::>(), ["1 MapInfo text object was kept as a row without its position or text"]); } #[test] @@ -659,7 +684,11 @@ mod tests { assert!(read("Version 300\nColumns 1\n x Integer\n", None, "x").is_err(), "no DATA"); assert!(read("Version 300\nColumns 99999\nData\n", None, "x").is_err()); let (_, rep) = read("CoordSys NonEarth Units \"m\" Bounds (0, 0) (10, 10)\nData\nPoint 1 1\n", None, "n").unwrap(); - assert!(rep.messages.iter().any(|m| m.contains("non-earth"))); + assert!( + rep.messages.iter().any(|m| m.contains("non-earth") && m.loss == Some(crate::loss::LossCode::AssumedCrs)), + "{:?}", + rep.messages + ); for cut in (0..MIF.len()).step_by(7) { let _ = read(MIF.get(..cut).unwrap_or(""), Some(MID), "t"); } diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index f0f3a94bec..0c98e1f060 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -436,10 +436,12 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { }) .collect(); let t = tags(&strings, &k, &vv); - // Only the relations drawn are kept. - if osm.relations.len() >= MAX_RELATIONS { + // Only the relations drawn are kept, so only they meet the cap: one of + // another type is left out either way. + let drawn = matches!(tag(&t, "type"), Some("multipolygon" | "boundary")); + if drawn && osm.relations.len() >= MAX_RELATIONS { osm.capped = true; - } else if matches!(tag(&t, "type"), Some("multipolygon" | "boundary")) { + } else if drawn { if roles.len() != mems.len() || types.len() != mems.len() { return Err(DataError::Format(format!( "OSM relation {id} has mismatched member arrays (IDs: {}, roles: {}, types: {})", @@ -448,7 +450,9 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { types.len() ))); } - let omitted = mems.len().saturating_sub(MAX_MEMBERS) as u64; + // Node members are never read, so only the others past the limit are + // left out by it. + let omitted = types.iter().skip(MAX_MEMBERS).filter(|ty| **ty != 0).count() as u64; osm.omitted_members = osm.omitted_members.saturating_add(omitted); let members = mems .into_iter() @@ -768,7 +772,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let mut report = ReadReport { skipped: missing + short_ways + no_closed_outer, ..ReadReport::default() }; if osm.omitted_members > 0 { let members = if osm.omitted_members == 1 { "relation member" } else { "relation members" }; - report.messages.push(format!("{} {members} left out at the per-relation limit of {MAX_MEMBERS}", osm.omitted_members)); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{} {members} left out at the per-relation limit of {MAX_MEMBERS}", osm.omitted_members), + )); } if short_ways > 0 { let subject = if short_ways == 1 { "tagged way left out because it has" } else { "tagged ways left out because they have" }; @@ -1246,7 +1253,13 @@ pub(crate) mod tests { assert_eq!(layers[1].0.features.iter().collect::>(), clean[1].0.features.iter().collect::>()); assert_eq!(layers[0].1.skipped, 0, "a member is not a whole skipped feature"); assert_eq!(layers[0].1.messages.texts().collect::>(), ["1 relation member left out at the per-relation limit of 100000"]); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedOverLimit)); assert!(layers[1].1.messages.is_empty()); + // A node member past the limit is never read either way, so nothing is left out by it. + members.pop(); + members.push((5, 0, 8)); + let nodes = read("finite.pbf", &finite_omission_file(ways, Some(&members))).unwrap(); + assert!(nodes[0].1.messages.is_empty(), "{:?}", nodes[0].1.messages); } #[test] diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index 56ef128996..d1fc84e0f9 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -502,7 +502,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.xml", landxml(&cg_points("1 1")), landxml(&cg_points("x y")), - Said("couldn't be read and were left out"), + Expect::Classified(LossCode::DroppedFeature, "couldn't be read and was left out"), ), case( "LandXML: a parcel without geometry",