From 0e7f6ec5f67683d64bfd27d9c4e4ec1de32ea484 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 03:24:07 -0600 Subject: [PATCH 01/12] feat(data): DXF, LiDAR, feature service pages, workbooks and dBASE encodings say what they leave out or assume with loss codes (#2371) DXF counts what it can't draw where it would be drawn, so a block the drawing never places loses nothing; its entities left out say dropped.feature and its vertices and hatch rings dropped.geometry or dropped.ring. A feature service page says an unusable system only when a geometry is read in it, and codes its values, rings, fields and text. Workbooks count a serial-60 WKT cell below the heading only. LiDAR's decompression limit says dropped.over-limit. New code assumed.encoding for a .cpg or code page RustGIS can't use. --- crates/data/src/dbf.rs | 24 ++- crates/data/src/dxf.rs | 149 ++++++++++++++---- crates/data/src/esripbf.rs | 45 +++++- crates/data/src/esripbf/tests.rs | 23 ++- crates/data/src/io.rs | 14 +- crates/data/src/lidar.rs | 7 +- crates/data/src/loss.rs | 5 + crates/data/src/ogc.rs | 7 +- crates/data/src/sheets.rs | 37 ++++- .../tests/integration/shapefile_encoding.rs | 10 ++ docs/cli.md | 1 + 11 files changed, 261 insertions(+), 61 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index d9059172c9..63aafaad27 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -148,7 +148,10 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No if let Some(encoding) = DbfEncoding::from_name(label) { return encoding; } - notes.push("Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedEncoding, + "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable", + )); } // No language driver: UTF-8, as it always was, without a note. if ldid == 0 { @@ -162,7 +165,10 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No Some(name) => format!(" (code page {p}, {name})"), None => format!(" (code page {p})"), }); - notes.push(format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedEncoding, + format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"), + )); DbfEncoding::Utf8 } @@ -422,7 +428,10 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) - match try_read_cpg(path) { Ok(bytes) => bytes, Err(e) => { - notes.push(format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedEncoding, + format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable"), + )); None } } @@ -585,10 +594,15 @@ mod tests { fn a_page_rustgis_cant_decode_is_named_in_the_note() { let mut notes = crate::loss::Notes::new(); assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8)); - assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"]); + assert_eq!( + notes.texts().collect::>(), + ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"] + ); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); let mut notes = crate::loss::Notes::new(); encoding(None, 0xFF, &mut notes); - assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); + assert_eq!(notes.texts().collect::>(), ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); } /// Text is read as UTF-8 unless another encoding is named, with none named, with UTF-8 named diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index eba292ec31..4c51436d7b 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -364,6 +364,10 @@ enum Shape { constant_z: bool, }, Insert(Insert), + /// An entity that can't be drawn: one RustGIS doesn't draw (by kind) or can't read. Kept in + /// its place so it is counted only where it would have been drawn: not in a block the + /// drawing never places, and once for each placement of one it does. + Lost(Option), } impl Shape { @@ -1154,10 +1158,6 @@ struct Drawing { layers: HashMap, blocks: HashMap)>, entities: Vec, - /// Entities not drawn, by kind. - unread: BTreeMap, - /// Entities that couldn't be read. - bad: usize, } /// The magnitude of an ACI color index (negative means its layer is off). The one signed @@ -1170,7 +1170,7 @@ fn color_magnitude(color: i64) -> Result { /// Reads the records of each section. fn drawing(records: &[Record]) -> Result { - let mut d = Drawing { layers: HashMap::new(), blocks: HashMap::new(), entities: Vec::new(), unread: BTreeMap::new(), bad: 0 }; + let mut d = Drawing { layers: HashMap::new(), blocks: HashMap::new(), entities: Vec::new() }; let mut section = ""; // The block being read: name, base point, entities. let mut block: Option<(String, P3, Vec)> = None; @@ -1231,8 +1231,28 @@ fn drawing(records: &[Record]) -> Result { if matches!(r.kind, "SEQEND" | "VERTEX") || (r.kind == "ATTDEF" && g.i(70).unwrap_or(0) & 2 == 0) { continue; } + // What can't be drawn stays in its place, counted where it would be drawn. + let lost = |shape: Shape| Ent { + kind: "LOST", + layer: g.s(8).map(str::trim).unwrap_or("0").to_string(), + layer_key: g.s(8).map(str::trim).unwrap_or("0").to_ascii_lowercase(), + // Not color-validated: nothing of it is drawn. + color: 256, + linetype: None, + text: None, + paper: g.i(67) == Some(1), + height: None, + rotation: None, + shape, + loss: PathLoss::default(), + }; let Some(kind) = kind_name(r.kind) else { - *d.unread.entry(r.kind.to_string()).or_insert(0) += 1; + let e = lost(Shape::Lost(Some(r.kind.to_string()))); + match &mut block { + Some((_, _, ents)) if section == "BLOCKS" => ents.push(e), + _ if section == "ENTITIES" => d.entities.push(e), + _ => {} + } continue; }; let mut loss = PathLoss::default(); @@ -1240,7 +1260,12 @@ fn drawing(records: &[Record]) -> Result { // Entity builders use Option for malformed data; cancellation must escape as an error. crate::progress::check()?; let Some(shape) = shape else { - d.bad += 1; + let e = lost(Shape::Lost(None)); + match &mut block { + Some((_, _, ents)) if section == "BLOCKS" => ents.push(e), + _ if section == "ENTITIES" => d.entities.push(e), + _ => {} + } continue; }; let text = match kind { @@ -1314,6 +1339,9 @@ struct Out { vertex_capped: bool, /// The copies the arrays above make together on the current nesting path. copies: usize, + /// Entities placed that RustGIS doesn't draw, by kind, and that couldn't be read. + unread: BTreeMap, + bad: usize, } fn fields() -> Vec { @@ -1486,13 +1514,21 @@ fn emit( { continue; } + // An entity that can't be drawn, here where it would have been: counted, by kind. + if let Shape::Lost(kind) = &e.shape { + match kind { + Some(k) => *out.unread.entry(k.clone()).or_insert(0) += 1, + None => out.bad += 1, + } + continue; + } // Every coordinate placed is charged before it is built: a large polyline in a block // inserted many times can't fill the memory. let n = match &e.shape { Shape::Point(_) => 1, Shape::Line { points: ps, .. } | Shape::Polygon(ps) => ps.len(), Shape::Rings { rings: rs, .. } => rs.iter().map(Vec::len).sum(), - Shape::Insert(_) => 0, + Shape::Insert(_) | Shape::Lost(_) => 0, }; if out.vertices.saturating_add(n) > MAX_TOTAL_VERTICES { out.vertex_capped = true; @@ -1553,7 +1589,7 @@ fn emit( let varying = has_varying_z(kept.flatten(), first, *constant_z && preserves_z); (g, first, 2, varying) } - Shape::Insert(_) => continue, + Shape::Insert(_) | Shape::Lost(_) => continue, }; let Some(geometry) = geometry else { out.cut += 1; @@ -1624,6 +1660,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = d.unread.iter().map(|(k, n)| format!("{n} {k}")).collect(); - report.messages.push(format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", "))); + if !out.unread.is_empty() { + let kinds: Vec = out.unread.iter().map(|(k, n)| format!("{n} {k}")).collect(); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", ")), + )); } - let skipped = d.bad + out.cut; + let skipped = out.bad + out.cut; report.skipped = skipped; if skipped > 0 { - report.messages.push(format!( - "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" + ), )); } let transformer = match opts.crs.filter(|c| *c != Crs::LonLat) { @@ -1741,20 +1786,35 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { let subject = if count == 1 { single } else { plural }; - report.messages.push(format!("{count} {subject} {reason}")); + report.messages.push(crate::loss::Note::loss(code, format!("{count} {subject} {reason}"))); } } } @@ -1775,7 +1835,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>() + .join("\n") + }; + let said = |text: &str| { + let layers = read("a.dxf", text.as_bytes(), &Options::default()).unwrap(); + layers + .iter() + .flat_map(|(_, r)| r.messages.iter()) + .filter(|m| m.contains("doesn't draw")) + .map(|m| (m.as_str().to_string(), m.loss)) + .collect::>() + }; + assert!(said(&drawing("")).is_empty(), "a block never placed loses nothing"); + assert_eq!( + said(&drawing("0 INSERT 2 B 10 5 20 5 0 INSERT 2 B 10 9 20 9")), + [("entities RustGIS doesn't draw were left out: 2 IMAGE".to_string(), Some(crate::loss::LossCode::DroppedFeature))] + ); + } + fn dxf(pairs: &[(i32, &str)]) -> Vec { pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() } @@ -1856,7 +1947,7 @@ mod tests { assert_eq!(parts[0][0].first(), Some(&Coord::new(0., 0.))); assert_eq!(layers[0].1.skipped, 0); assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), [format!("{} polyline path coordinates were left out at the per-entity vertex limit", (vertices - kept_segments) * 36,)] ); } @@ -1910,7 +2001,11 @@ mod tests { let Some(Geometry::Line(parts)) = &layers[0].0.features[0].geometry else { panic!("line") }; assert_eq!(parts[0].len(), if lost { 2 } else { 3 }); assert_eq!(layers[0].0.value(0, 8), &Value::Float(0.)); - assert_eq!(layers[0].1.messages, if lost { vec!["1 POLYLINE vertex with unreadable supplied Z was left out"] } else { vec![] }); + assert_eq!( + layers[0].1.messages.texts().collect::>(), + if lost { vec!["1 POLYLINE vertex with unreadable supplied Z was left out"] } else { vec![] } + ); + assert!(layers[0].1.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedGeometry))); assert_eq!(layers[0].1.skipped, 0); } } @@ -2013,7 +2108,7 @@ mod tests { let held = parts[0].len(); let total = MAX_VERTICES + tail.len() + if bulge { 35 } else { 0 }; assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), [format!( "{} polyline path {} left out at the per-entity vertex limit", total - held, diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 1287b0cd58..1fafb54987 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -139,6 +139,9 @@ pub struct Losses { pub with_zm: usize, /// Places that convert to beyond longitude/latitude (the answer's system may not fit them). pub beyond: usize, + /// The coordinate system code an answer with features with a geometry names and RustGIS + /// can't use, without a WKT (read as longitude/latitude). + pub unusable_code: Option, } impl Losses { @@ -152,6 +155,7 @@ impl Losses { self.unprojected = self.unprojected.saturating_add(other.unprojected); self.with_zm = self.with_zm.saturating_add(other.with_zm); self.beyond = self.beyond.saturating_add(other.beyond); + self.unusable_code = self.unusable_code.or(other.unusable_code); } /// What they say, one message per kind (as [`read`] says them). @@ -163,17 +167,33 @@ impl Losses { "the answer names no coordinate system; coordinates are read as longitude/latitude", )); } + // Said only when a geometry was read in it: assumed, then. + if let Some(code) = self.unusable_code { + out.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("coordinate system {code} can't be used; 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)); + out.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{} values don't fit their field's type and are left empty", self.unreadable), + )); } if self.not_utf8 > 0 { - out.push(format!( - "{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", - self.not_utf8 + out.push(crate::loss::Note::loss( + crate::loss::LossCode::ChangedEncoding, + format!( + "{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", + self.not_utf8 + ), )); } if self.flat_rings > 0 { - out.push(format!("{} polygon rings have no area and are left out", self.flat_rings)); + out.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedRing, + format!("{} polygon rings have no area and are left out", self.flat_rings), + )); } if self.unprojected > 0 { out.push(format!( @@ -319,10 +339,16 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result fields.push(Field { name, ty: read_as.field_type(), alias }); } if repeated > 0 { - report.messages.push(format!("{repeated} fields repeat an earlier field's name and are left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{repeated} fields repeat an earlier field's name and are left out"), + )); } if not_read > 0 { - report.messages.push(format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out"), + )); } if unknown > 0 { report.messages.push(format!("{unknown} fields have a type RustGIS doesn't know; their values are read as text")); @@ -354,13 +380,15 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result .messages .get(said_before..) .is_some_and(|m| m.iter().any(|m| m.ends_with("; coordinates are read as longitude/latitude"))); + // Said with the page's losses, once it is known that a geometry was read in it. + let mut unusable_code = None; if crs.is_none() && wkt.is_none() && let Some(code) = code && crate::filegdb::crs_of_code(code) != Some(crate::raster::Crs::LonLat) { unread_code = true; - report.messages.push(format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude")); + unusable_code = Some(code); } let layer_type = match shape_kind { @@ -402,6 +430,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result // Assumed, so said: an answer that names no coordinate system. no_crs: any_geometry && code.is_none() && wkt.is_none(), unread_code: any_geometry && unread_code, + unusable_code: unusable_code.filter(|_| any_geometry), unreadable: tally.unreadable, not_utf8: tally.not_utf8, flat_rings: tally.flat_rings, diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index df3daaa899..0984838962 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -147,7 +147,8 @@ fn a_ring_without_area_is_left_out_and_said() { let (ds, report) = read(&bytes, "t").unwrap(); let Some(Geometry::Polygon(polygons)) = &ds.features[0].geometry else { panic!("not a polygon") }; assert_eq!(polygons.len(), 1); - assert_eq!(report.messages, ["1 polygon rings have no area and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["1 polygon rings have no area and are left out"]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedRing)); } #[test] @@ -237,6 +238,11 @@ fn an_unknown_coordinate_system_is_said() { report.messages.texts().collect::>(), ["coordinate system 999999 can't be used; coordinates are read as longitude/latitude"] ); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::AssumedCrs)); + // An answer with no geometry places nothing in it: nothing assumed, nothing said. + let rows = answer(&[message(8, &number(1, 999_999)), transform(false, 1.0, 0.0, 0.0), feature(&[])]); + let (_, report) = read(&rows, "t").unwrap(); + assert!(!report.messages.iter().any(|m| m.contains("can't be used")), "{:?}", report.messages); } #[test] @@ -286,8 +292,9 @@ fn text_that_isnt_utf8_is_read_with_replacements_and_said() { assert_eq!(ds.fields[0].name, "N\u{FFFD}AME"); assert_eq!(ds.features[0].attrs, [Value::Text("a\u{FFFD}b".into())]); assert_eq!(ds.features[1].attrs, [Value::Text("ok".into())]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::ChangedEncoding)); assert_eq!( - report.messages, + report.messages.texts().collect::>(), ["2 values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"] ); } @@ -317,13 +324,14 @@ fn repeated_names_and_unread_field_types_are_left_out_and_said() { assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::>(), ["NAME", "COUNT"]); assert_eq!(ds.features[0].attrs, [Value::Text("a".into()), Value::Null]); assert_eq!( - report.messages, + report.messages.texts().collect::>(), [ "1 fields repeat an earlier field's name and are left out", "1 fields hold geometries, blobs or rasters, which aren't read, and are left out", "1 values don't fit their field's type and are left empty", ] ); + assert!(report.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedValue)), "{:?}", report.messages); // A table: no geometry type, no geometry. assert_eq!(ds.geometry_type, GeometryType::None); } @@ -704,7 +712,7 @@ fn a_repeated_field_of_an_unknown_type_is_only_said_left_out() { let bytes = answer(&[field("NAME", 4), field("name", 17), feature(&[text("a"), uint(5)])]); let (ds, report) = read(&bytes, "t").unwrap(); assert_eq!(ds.fields.len(), 1); - assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["1 fields repeat an earlier field's name and are left out"]); } #[test] @@ -713,10 +721,13 @@ fn a_left_out_field_whose_name_isnt_utf8_is_only_said_left_out() { let repeat = message(13, &[message(1, b"N\xffame"), number(2, 4)].concat()); let bytes = answer(&[field("N\u{FFFD}AME", 4), repeat, feature(&[text("a"), text("b")])]); let (_, report) = read(&bytes, "t").unwrap(); - assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["1 fields repeat an earlier field's name and are left out"]); let geometry = message(13, &[message(1, b"G\xff"), number(2, 7)].concat()); let (_, report) = read(&answer(&[field("NAME", 4), geometry, feature(&[text("a")])]), "t").unwrap(); - assert_eq!(report.messages, ["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"]); + assert_eq!( + report.messages.texts().collect::>(), + ["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"] + ); } #[test] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 6db7769c20..494337429e 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2922,12 +2922,18 @@ pub(crate) fn read_rows( // so its row has no geometry, said here. if let Some(w) = wkt { let column = headers.get(w).map_or("", |h| h.trim()); + // The values read as empty, below the heading: each a value lost, and with it its row's + // geometry. match workbook.and_then(|(_, empty)| empty.get(w)).copied().unwrap_or(0) { 0 => {} - 1 => report.messages.push(format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry")), - n => report - .messages - .push(format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry")), + 1 => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry"), + )), + n => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry"), + )), } } let (mut bad_wkt, mut zm_rows, mut collection_rows) = (0usize, 0usize, 0usize); diff --git a/crates/data/src/lidar.rs b/crates/data/src/lidar.rs index bdd838999c..6d5ca8a037 100644 --- a/crates/data/src/lidar.rs +++ b/crates/data/src/lidar.rs @@ -360,9 +360,10 @@ fn read_points(mut r: R, name: &str, crs: Option MAX_DECOMPRESSED { - report - .messages - .push(format!("{name}: only its first {MAX_DECOMPRESSED} of {total} points are read (use a smaller extract for the rest)")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{name}: only its first {MAX_DECOMPRESSED} of {total} points are read (use a smaller extract for the rest)"), + )); } let read = laz_points(&mut r, &h, &vlr.data, readable, stride, &mut points, &mut brightest)?; if read < readable { diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 77d99f7e44..56337b6939 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -135,6 +135,11 @@ loss_codes! { Assumed, "Give the coordinate system the coordinates are in (\"crs\" when adding the data, or Define Projection)." ), + AssumedEncoding => ( + "assumed.encoding", + Assumed, + "Give the file's encoding in a form RustGIS reads, such as a .cpg file beside a Shapefile naming UTF-8 or its Windows code page." + ), } impl LossCode { diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 724e595ddf..6121c5e634 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4595,6 +4595,11 @@ impl Pages { .messages .push(format!("the answer names no coordinate system; coordinates are read in {asked}, the system asked for")); } + if let Some(code) = losses.unusable_code.take() { + report + .messages + .push(format!("coordinate system {code} can't be used; coordinates are read in {asked}, the system asked for")); + } // One it names that RustGIS can't use (a code, a WKT): read as asked too (as a // GeoJSON answer's is), and its message says so. for mut note in std::mem::replace(&mut report.messages, crate::loss::Notes::new()) { @@ -7127,7 +7132,7 @@ mod tests { pages = match pages.join_page(page) { Step::Fetch(p) => *p, Step::Decoded(_, report, None) => { - assert_eq!(report.messages, ["5 polygon rings have no area and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["5 polygon rings have no area and are left out"]); break; } other => panic!("{other:?}"), diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 495010e739..a32d3ad553 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -205,10 +205,13 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< // Serial 60 is the 1900 system's 1900-02-29, a day that never was. A column of dates reads it // as one that isn't a date (null, and counted); in a column of other things it is read as // empty and counted here, as it would not be text of a day. + // Counted for the rows below the heading, each a value read as empty: kept, or left out as + // empty when it was all the row held. let mut phantom_dates = vec![0usize; w]; let mut error_cells = vec![0usize; w]; let mut rows = range.rows().enumerate().map(|(row, r)| { let mut had_error = false; + let mut phantom: Vec = Vec::new(); let cells = r .iter() .enumerate() @@ -221,18 +224,16 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< String::new() } (Data::DateTime(t), Some(None)) if is_phantom_day(t) => { - if let Some(n) = phantom_dates.get_mut(k) { - *n += 1; - } + phantom.push(k); String::new() } _ => cell(d), }) .collect::>(); - (row, cells, had_error) + (row, cells, had_error, phantom) }); let mut empty_error_rows = 0; - let mut keep = |(_, cells, had_error): &(usize, Vec, bool)| { + let mut keep = |(_, cells, had_error, _): &(usize, Vec, bool, Vec)| { let nonempty = cells.iter().any(|c| !c.trim().is_empty()); if !nonempty && *had_error { empty_error_rows += 1; @@ -240,7 +241,7 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< nonempty }; // The first row with anything in it names the columns. - let (header_row, headers, _) = rows.by_ref().find(&mut keep).unwrap_or_default(); + let (header_row, headers, _, _) = rows.by_ref().find(&mut keep).unwrap_or_default(); if headers.is_empty() { return Err(DataError::Format(format!("sheet '{pick}' is empty"))); } @@ -261,7 +262,17 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< if h.trim().is_empty() { column_letter(first_col + i) } else { h.trim().to_string() } }) .collect(); - let rows = rows.filter(keep).map(|(_, cells, _)| cells).collect(); + let rows = rows + .inspect(|(_, _, _, phantom)| { + for k in phantom { + if let Some(n) = phantom_dates.get_mut(*k) { + *n += 1; + } + } + }) + .filter(keep) + .map(|(_, cells, _, _)| cells) + .collect(); Ok(Grid { names, pick, headers, rows, dates, rounded_dates, error_cells, header_error_cells, empty_error_rows, phantom_dates }) } @@ -805,8 +816,20 @@ mod tests { "{:?}", report.messages ); + let said = report.messages.iter().find(|m| m.contains("isn't a date")).unwrap(); + assert_eq!(said.loss, Some(crate::loss::LossCode::DroppedValue)); let (_, report) = book("POINT (3 4)"); assert!(!report.messages.iter().any(|m| m.contains("isn't a date")), "{:?}", report.messages); + // A row whose only value is serial 60 in the WKT column is left out as empty, and its value + // read as empty is said. + let phantom = r#"60"#; + let empty = xlsx(&[("Places", &[&["name", "wkt"], &["a", "POINT (1 2)"], &["", phantom]])]); + let mut entries = crate::zip::read(&empty).unwrap(); + entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let opts = CsvOptions { wkt: Some("wkt".into()), ..CsvOptions::default() }; + let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); + assert_eq!(ds.features.len(), 1); + assert!(report.messages.iter().any(|m| m.contains("1 value in 'wkt' isn't a date")), "{:?}", report.messages); } /// Multiple errors in one column and another column count once each; blank cells don't. diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 4f4cfd2e16..bdfe144f56 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -629,6 +629,13 @@ const UNSUPPORTED_LDIDS: &[(u8, &str)] = &[ /// Three records make a limit-one read genuinely sampled; names and values use the same bytes. /// `notes` is what a read of the whole file says. A source read in place says those of opening /// when it opens, and the count of values (`places: …`) with them once it is read whole. +/// An encoding RustGIS falls back to (a `.cpg` or code page it can't use) is said as assumed. +fn encoding_assumed(notes: &rustgis_data::loss::Notes) { + for note in notes.iter().filter(|n| n.contains("; using ")) { + assert_eq!(note.loss, Some(rustgis_data::loss::LossCode::AssumedEncoding), "{note:?}"); + } +} + fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, notes: &[&str]) { let files = named_parts(text, text, ldid, cpg, 3); let check = |ds: &Dataset, rows: usize| { @@ -644,6 +651,7 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, check(&layers[0].0, 3); assert_eq!(layers[0].1.skipped, 0); assert_eq!(texts(&layers[0].1.messages), notes, "LDID {ldid:02X} ZIP notes"); + encoding_assumed(&layers[0].1.messages); #[cfg(not(target_arch = "wasm32"))] { use rustgis_data::source::{FeatureSource, Request}; @@ -656,10 +664,12 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, check(&ds, 3); assert_eq!(report.skipped, 0); assert_eq!(texts(&report.messages), notes, "LDID {ldid:02X} loose-file notes"); + encoding_assumed(&report.messages); let src = open_shp(&path, "places").unwrap(); assert_eq!(src.info().fields[0].name, expected, "LDID {ldid:02X} streamed field name"); let opening: Vec<&str> = notes.iter().copied().filter(|n| !n.starts_with("places: ")).collect(); assert_eq!(texts(&src.info().notes), opening, "LDID {ldid:02X} streamed notes"); + encoding_assumed(&src.info().notes); let whole: Vec = notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); assert_eq!(texts(&rustgis_data::source::materialize(&src).unwrap().1.messages), whole, "LDID {ldid:02X} whole read in place"); diff --git a/docs/cli.md b/docs/cli.md index 1f01b59b65..3a9fde50bf 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -176,6 +176,7 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. | | `assumed.null-marker` | Write the value another way if the text Null is meant as text, not as an empty value. | | `assumed.crs` | Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). | +| `assumed.encoding` | Give the file's encoding in a form RustGIS reads, such as a .cpg file beside a Shapefile naming UTF-8 or its Windows code page. | Not every loss has a code yet: losses still reported without one don't stop a strict run. From 1c5940d69ab4394c8c333f165145878ed856c3a1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 03:46:57 -0600 Subject: [PATCH 02/12] fix(data): what can't be drawn names no layer or meets no cap, a .cpg is assumed only without a code page, and the DXF, workbook and page siblings are coded (#2371) --- crates/data/src/dbf.rs | 28 +++++---- crates/data/src/dxf.rs | 57 ++++++++++++++----- crates/data/src/esripbf.rs | 13 +++++ crates/data/src/esripbf/tests.rs | 14 +++++ crates/data/src/io.rs | 4 +- crates/data/src/sheets.rs | 14 +++-- .../tests/integration/shapefile_encoding.rs | 21 ++++--- .../tests/integration/never_silent_reading.rs | 5 +- 8 files changed, 114 insertions(+), 42 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 63aafaad27..9e685f20b3 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -148,17 +148,25 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No if let Some(encoding) = DbfEncoding::from_name(label) { return encoding; } - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedEncoding, - "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable", - )); + } + // A `.cpg` that can't be used: the file's own language driver gives the encoding, and then + // nothing is assumed; without one it is UTF-8, assumed. One that names a code page RustGIS + // can't read is said below, as assumed, on its own. + let page = (ldid != 0).then(|| ldid_code_page(ldid)).flatten(); + let resolved = page.and_then(DbfEncoding::from_number); + if cpg.is_some() { + let text = "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"; + notes.push(if ldid == 0 { + crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, text) + } else { + crate::loss::Note::plain(text) + }); } // No language driver: UTF-8, as it always was, without a note. if ldid == 0 { return DbfEncoding::Utf8; } - let page = ldid_code_page(ldid); - if let Some(encoding) = page.and_then(DbfEncoding::from_number) { + if let Some(encoding) = resolved { return encoding; } let named = page.map_or_else(String::new, |p| match page_name(p) { @@ -428,10 +436,10 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) - match try_read_cpg(path) { Ok(bytes) => bytes, Err(e) => { - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedEncoding, - format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable"), - )); + // Whether the .dbf supplies the encoding isn't known yet: said, not as assumed. + notes.push(crate::loss::Note::plain(format!( + "could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable" + ))); None } } diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 4c51436d7b..d2eb6fc070 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -91,7 +91,7 @@ fn is_binary(bytes: &[u8]) -> bool { /// The text of a drawing and what had to be assumed to read it: UTF-8 (AutoCAD 2007 and later), /// else the ANSI code page its header names ([`code_page`], the `$DWGCODEPAGE` of older drawings), /// else Latin-1. -fn decode(bytes: &[u8]) -> (Cow<'_, str>, Option) { +fn decode(bytes: &[u8]) -> (Cow<'_, str>, Option) { if let Ok(s) = std::str::from_utf8(bytes) { return (Cow::Borrowed(s), None); } @@ -103,14 +103,21 @@ fn decode(bytes: &[u8]) -> (Cow<'_, str>, Option) { ), None => "the drawing's text isn't UTF-8 and it names no code page ($DWGCODEPAGE): it is read as Latin-1, so non-ASCII text (such as layer names) may be wrong".to_string(), }; - return (Cow::Owned(bytes.iter().map(|&b| char::from(b)).collect()), Some(said)); + // Read in an encoding it doesn't name: assumed. + return ( + Cow::Owned(bytes.iter().map(|&b| char::from(b)).collect()), + Some(crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, said)), + ); }; let (text, _) = encoding.decode_without_bom_handling(bytes); let lost = text.matches('\u{fffd}').count(); let said = (lost > 0).then(|| { - format!( - "{lost} characters of the drawing's text couldn't be read as {} (its code page): they are drawn as a replacement character", - encoding.name() + crate::loss::Note::loss( + crate::loss::LossCode::ChangedEncoding, + format!( + "{lost} characters of the drawing's text couldn't be read as {} (its code page): they are drawn as a replacement character", + encoding.name() + ), ) }); (text, said) @@ -1395,13 +1402,16 @@ fn emit( if out.vertex_capped { return Ok(()); } - if out.count >= MAX_FEATURES { + let lost = matches!(e.shape, Shape::Lost(_)); + if out.count >= MAX_FEATURES && !lost { out.capped = true; return Ok(()); } // Every placement costs a step, drawn or not: nested arrays of empty or filtered blocks - // can't make the walk run on. - out.steps += 1; + // can't make the walk run on. What can't be drawn is only counted, and costs none. + if !lost { + out.steps += 1; + } if out.steps > MAX_STEPS { out.overworked = true; return Ok(()); @@ -1670,8 +1680,9 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result Result> { for (key, (name, _, _)) in &d.layers { add(name, key); } - for e in &d.entities { + // What can't be drawn names no layer to pick. + for e in d.entities.iter().filter(|e| !matches!(e.shape, Shape::Lost(_))) { add(&e.layer, &e.layer_key); } for (_, ents) in d.blocks.values() { - for e in ents.iter().filter(|e| e.layer != "0") { + for e in ents.iter().filter(|e| e.layer != "0" && !matches!(e.shape, Shape::Lost(_))) { add(&e.layer, &e.layer_key); } } @@ -1892,7 +1905,6 @@ pub fn layers(file_name: &str, bytes: &[u8]) -> Result> { mod tests { use super::*; - /// A DXF from (code, value) pairs. /// An entity RustGIS doesn't draw, or can't read, is counted where it would have been drawn: /// not at all in a block the drawing never places, and once for each placement of one it does. #[test] @@ -1919,8 +1931,20 @@ mod tests { said(&drawing("0 INSERT 2 B 10 5 20 5 0 INSERT 2 B 10 9 20 9")), [("entities RustGIS doesn't draw were left out: 2 IMAGE".to_string(), Some(crate::loss::LossCode::DroppedFeature))] ); + // Blocks left out, or a layer not asked for: their contents aren't drawn, so nothing of + // them is lost. + let placed = drawing("0 INSERT 2 B 8 x 10 5 20 5"); + for opts in [Options { blocks: false, ..Options::default() }, Options { layer: Some("0"), ..Options::default() }] { + let layers = read("a.dxf", placed.as_bytes(), &opts).unwrap(); + assert!(!layers.iter().flat_map(|(_, r)| r.messages.iter()).any(|m| m.contains("doesn't draw")), "{opts:?}"); + } + // What can't be drawn names no layer of its own to pick. + let lone = + "0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 0 IMAGE 8 only_images 0 ENDSEC 0 EOF".split_whitespace().collect::>().join("\n"); + assert_eq!(layers("a.dxf", lone.as_bytes()).unwrap(), ["0"]); } + /// A DXF from (code, value) pairs. fn dxf(pairs: &[(i32, &str)]) -> Vec { pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() } @@ -1973,6 +1997,7 @@ mod tests { let layers = read("a.dxf", &bytes, &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Line(vec![vec![Coord::new(0., 0.), Coord::new(2., 2.)]]))); assert_eq!(layers[0].1.messages.texts().collect::>(), ["1 vertex without Y was left out of spline paths"]); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedGeometry)); assert_eq!(layers[0].1.skipped, 0); } } @@ -2037,6 +2062,7 @@ mod tests { layers[0].1.messages.texts().collect::>(), [format!("{count} short HATCH boundary {subject} left out of polygons")] ); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedRing)); assert_eq!(layers[0].1.skipped, 0); } } @@ -2146,6 +2172,7 @@ mod tests { layers[0].1.messages.texts().collect::>(), ["1 entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out"] ); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); } // Losses follow the two surviving block copies; the paper-space and filtered copy stay quiet. let text = "0 SECTION 2 BLOCKS 0 BLOCK 2 B 0 SPLINE 71 3 11 0 21 0 11 1 11 2 21 2 0 ENDBLK 0 ENDSEC diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 1fafb54987..fac1f36964 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -373,6 +373,8 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result } let said_before = report.messages.len(); let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?; + // What reading the system said, which assumes a system only for a geometry read in it. + let crs_said = said_before..report.messages.len(); // A WKT that couldn't be read (or converted) is read as longitude/latitude, and said so; // a geographic one gives no system and says nothing. let mut unread_code = crs.is_none() @@ -426,6 +428,17 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result if let Some(c) = crs.filter(|_| to_lonlat.is_some()) { ds.held_in = c; } + // An answer without a geometry places nothing in the system it couldn't read: said, not as + // assumed. + if !any_geometry && !crs_said.is_empty() { + let said = std::mem::replace(&mut report.messages, crate::loss::Notes::new()); + for (i, mut note) in said.into_iter().enumerate() { + if crs_said.contains(&i) && note.loss == Some(crate::loss::LossCode::AssumedCrs) { + note.loss = None; + } + report.messages.push(note); + } + } let losses = Losses { // Assumed, so said: an answer that names no coordinate system. no_crs: any_geometry && code.is_none() && wkt.is_none(), diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 0984838962..0701237bc8 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -453,6 +453,20 @@ fn lengths_in_several_fields_keep_their_order() { assert!(report.messages.is_empty(), "{:?}", report.messages); } +/// A WKT RustGIS can't read is assumed to be longitude/latitude only for an answer with a +/// geometry read in it: one without places nothing there. +#[test] +fn an_unreadable_wkt_is_assumed_only_with_a_geometry() { + let wkt: &[u8] = b"PROJCS[\"nonsense\"]"; + let assumed = |features: &[u8]| { + let bytes = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), features.to_vec()]); + let (_, report) = read(&bytes, "t").unwrap(); + report.messages.iter().filter(|m| m.contains("read as longitude/latitude")).map(|m| m.loss).collect::>() + }; + assert_eq!(assumed(&feature(&[geometry(&[], &[1, 2])])), [Some(crate::loss::LossCode::AssumedCrs)]); + assert_eq!(assumed(&feature(&[])), [None]); +} + #[test] fn a_wkt_that_isnt_utf8_is_said() { let wkt = b"GEOGCS[\"GCS_WGS_1984\xff\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]"; diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 494337429e..91465d4715 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2928,11 +2928,11 @@ pub(crate) fn read_rows( 0 => {} 1 => report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedValue, - format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry"), + format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry, or is left out if it held nothing else"), )), n => report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedValue, - format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry"), + format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry, or are left out if they held nothing else"), )), } } diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index a32d3ad553..8aa8dbfd2b 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -76,7 +76,8 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> }; message.push_str(&format!("; {what}")); } - report.messages.push(message); + // Each error cell's value is read as empty: a value lost. + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, message)); } if rounded > 0 { report.messages.push(crate::loss::Note::loss( @@ -812,7 +813,9 @@ mod tests { assert_eq!(ds.features.len(), 2); assert_eq!(ds.features.iter().filter(|f| f.geometry.is_none()).count(), 1); assert!( - report.messages.says("1 value in 'wkt' isn't a date and was read as empty, so its row has no geometry"), + report.messages.says( + "1 value in 'wkt' isn't a date and was read as empty, so its row has no geometry, or is left out if it held nothing else" + ), "{:?}", report.messages ); @@ -838,7 +841,8 @@ mod tests { let error = r#"#DIV/0!"#; let book = xlsx(&[("S", &[&["id", "note", "other"], &["7", error, "kept"], &["8", error, error], &["9", "", ""]])]); let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap(); - assert_eq!(report.messages, ["3 spreadsheet error cells were read as empty, in 'note', 'other'"]); + assert_eq!(report.messages.texts().collect::>(), ["3 spreadsheet error cells were read as empty, in 'note', 'other'"]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); assert_eq!(report.skipped, 0); let attrs: Vec<_> = ds.features.iter().map(|f| f.attrs.clone()).collect(); use crate::Value::{Int, Null, Text}; @@ -859,7 +863,7 @@ mod tests { } else { vec!["1 spreadsheet error cell was read as empty, in 'B'; 1 erroneous heading was named by its column letter, 'B'"] }; - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); } } @@ -879,7 +883,7 @@ mod tests { } else { vec!["2 spreadsheet error cells were read as empty, in 'id', 'note'; 1 otherwise empty row with error cells was omitted"] }; - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); } } diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index bdfe144f56..af15695003 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -626,16 +626,19 @@ const UNSUPPORTED_LDIDS: &[(u8, &str)] = &[ (0x97, "10029, Mac Central European"), ]; -/// Three records make a limit-one read genuinely sampled; names and values use the same bytes. -/// `notes` is what a read of the whole file says. A source read in place says those of opening -/// when it opens, and the count of values (`places: …`) with them once it is read whole. -/// An encoding RustGIS falls back to (a `.cpg` or code page it can't use) is said as assumed. -fn encoding_assumed(notes: &rustgis_data::loss::Notes) { +/// An encoding RustGIS falls back to is said as assumed: a code page it can't use. A `.cpg` it +/// can't use is assumed only when there is no code page (`ldid` 0) to give the encoding instead. +fn encoding_assumed(notes: &rustgis_data::loss::Notes, ldid: u8) { for note in notes.iter().filter(|n| n.contains("; using ")) { - assert_eq!(note.loss, Some(rustgis_data::loss::LossCode::AssumedEncoding), "{note:?}"); + let assumed = note.contains("unsupported .dbf code page") || ldid == 0; + let code = assumed.then_some(rustgis_data::loss::LossCode::AssumedEncoding); + assert_eq!(note.loss, code, "{note:?}"); } } +/// Three records make a limit-one read genuinely sampled; names and values use the same bytes. +/// `notes` is what a read of the whole file says. A source read in place says those of opening +/// when it opens, and the count of values (`places: …`) with them once it is read whole. fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, notes: &[&str]) { let files = named_parts(text, text, ldid, cpg, 3); let check = |ds: &Dataset, rows: usize| { @@ -651,7 +654,7 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, check(&layers[0].0, 3); assert_eq!(layers[0].1.skipped, 0); assert_eq!(texts(&layers[0].1.messages), notes, "LDID {ldid:02X} ZIP notes"); - encoding_assumed(&layers[0].1.messages); + encoding_assumed(&layers[0].1.messages, ldid); #[cfg(not(target_arch = "wasm32"))] { use rustgis_data::source::{FeatureSource, Request}; @@ -664,12 +667,12 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, check(&ds, 3); assert_eq!(report.skipped, 0); assert_eq!(texts(&report.messages), notes, "LDID {ldid:02X} loose-file notes"); - encoding_assumed(&report.messages); + encoding_assumed(&report.messages, ldid); let src = open_shp(&path, "places").unwrap(); assert_eq!(src.info().fields[0].name, expected, "LDID {ldid:02X} streamed field name"); let opening: Vec<&str> = notes.iter().copied().filter(|n| !n.starts_with("places: ")).collect(); assert_eq!(texts(&src.info().notes), opening, "LDID {ldid:02X} streamed notes"); - encoding_assumed(&src.info().notes); + encoding_assumed(&src.info().notes, ldid); let whole: Vec = notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); assert_eq!(texts(&rustgis_data::source::materialize(&src).unwrap().1.messages), whole, "LDID {ldid:02X} whole read in place"); diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index d1fc84e0f9..f752812bf8 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -1000,7 +1000,10 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< { return Err(std::io::Error::other(format!("native spreadsheet collection notice: {report:?}"))); } - if errors && report.messages != ["1 spreadsheet error cell was read as empty, in 'note'"] { + if errors + && (report.messages.texts().collect::>() != ["1 spreadsheet error cell was read as empty, in 'note'"] + || report.messages[0].loss != Some(LossCode::DroppedValue)) + { return Err(std::io::Error::other(format!("native spreadsheet error notice: {report:?}"))); } if report.skipped != 0 From a6f64b18ec790b36cd9e7469ba7502e034d737a1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 04:26:32 -0600 Subject: [PATCH 03/12] fix(data): undrawable DXF entities cost their walk a step on each copy (#2371) --- crates/data/src/dxf.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index d2eb6fc070..bc5a502f6e 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1407,11 +1407,10 @@ fn emit( out.capped = true; return Ok(()); } - // Every placement costs a step, drawn or not: nested arrays of empty or filtered blocks - // can't make the walk run on. What can't be drawn is only counted, and costs none. - if !lost { - out.steps += 1; - } + // Every placement costs a step, drawn, counted or not: nested arrays of empty, filtered or + // undrawable blocks can't make the walk run on (an undrawable entity is walked once per + // copy). + out.steps += 1; if out.steps > MAX_STEPS { out.overworked = true; return Ok(()); @@ -1944,6 +1943,23 @@ mod tests { assert_eq!(layers("a.dxf", lone.as_bytes()).unwrap(), ["0"]); } + /// What can't be drawn still costs its walk a step on each copy, so an array of a block of + /// undrawable entities stops at the step limit, said, rather than running on. + #[test] + fn undrawable_entities_meet_the_step_limit() { + let images = "0 IMAGE ".repeat(100); + let text = format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 B {images}0 ENDBLK 0 BLOCK 2 A 0 INSERT 2 B 70 100 71 100 44 1 45 1 0 ENDBLK 0 ENDSEC \ + 0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 0 INSERT 2 A 10 1 20 1 70 10 44 1 0 ENDSEC 0 EOF" + ) + .split_whitespace() + .collect::>() + .join("\n"); + let layers = read("a.dxf", text.as_bytes(), &Options::default()).unwrap(); + let said = layers[0].1.messages.iter().find(|m| m.contains("place more than")).unwrap(); + assert_eq!(said.loss, Some(crate::loss::LossCode::DroppedOverLimit)); + } + /// A DXF from (code, value) pairs. fn dxf(pairs: &[(i32, &str)]) -> Vec { pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() From 6c6f823437a408c9741a30c2b4ab9b709f4ac1d2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 04:50:36 -0600 Subject: [PATCH 04/12] fix(data): the asked system's notes keep assumed.crs, a page without geometry says its WKT's text plain, and an unreadable .cpg falls back as an unusable one (#2371) --- crates/data/src/dbf.rs | 9 ++++----- crates/data/src/esripbf.rs | 8 ++++++-- crates/data/src/esripbf/tests.rs | 5 +++++ crates/data/src/ogc.rs | 17 ++++++++++------- 4 files changed, 25 insertions(+), 14 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 9e685f20b3..2910ca7b55 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -436,11 +436,10 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) - match try_read_cpg(path) { Ok(bytes) => bytes, Err(e) => { - // Whether the .dbf supplies the encoding isn't known yet: said, not as assumed. - notes.push(crate::loss::Note::plain(format!( - "could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable" - ))); - None + // Why it can't be used; what the encoding falls back to, and whether that is assumed, + // is said with the `.dbf`'s code page in hand ([`encoding`]), as for one that can't be. + notes.push(crate::loss::Note::plain(format!("could not read the .cpg ({e})"))); + Some(Vec::new()) } } } diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index fac1f36964..09b49dd8d1 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -361,6 +361,9 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result // read in its place. If the replaced bytes break the WKT, it can't be told whether the WKT // would have won, so that's said too. The WKT is looked at only when it isn't UTF-8, as this // runs for every page. + // What reading the system says (its WKT's text, and what it assumes) holds only for a + // geometry read in it. + let said_before = report.messages.len(); if !wkt_utf8 && (code.and_then(crs_of_code).is_none() || esri_wkt_over_code(code, wkt.as_deref()).is_some() @@ -371,7 +374,6 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result "the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", )); } - let said_before = report.messages.len(); let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?; // What reading the system said, which assumes a system only for a geometry read in it. let crs_said = said_before..report.messages.len(); @@ -433,7 +435,9 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result if !any_geometry && !crs_said.is_empty() { let said = std::mem::replace(&mut report.messages, crate::loss::Notes::new()); for (i, mut note) in said.into_iter().enumerate() { - if crs_said.contains(&i) && note.loss == Some(crate::loss::LossCode::AssumedCrs) { + if crs_said.contains(&i) + && matches!(note.loss, Some(crate::loss::LossCode::AssumedCrs | crate::loss::LossCode::ChangedEncoding)) + { note.loss = None; } report.messages.push(note); diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 0701237bc8..e5dde3ba3c 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -476,6 +476,11 @@ fn a_wkt_that_isnt_utf8_is_said() { report.messages.first().map(|m| m.as_str()), Some("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD") ); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::ChangedEncoding)); + // On a page with no geometry, nothing is placed in the system: said, without a code. + let rows = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), feature(&[])]); + let (_, report) = read(&rows, "t").unwrap(); + assert_eq!(report.messages.first().map(|m| m.loss), Some(None), "{:?}", report.messages); // Unused when a code RustGIS knows names the system: nothing to say. let with_code = answer(&[ message(8, &[number(1, 4326), message(5, wkt)].concat()), diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 6121c5e634..8ea6a95aaf 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4591,14 +4591,16 @@ impl Pages { ds.crs = Some(asked); let asked = asked.label(); if std::mem::take(&mut losses.no_crs) { - report - .messages - .push(format!("the answer names no coordinate system; coordinates are read in {asked}, the system asked for")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("the answer names no coordinate system; coordinates are read in {asked}, the system asked for"), + )); } if let Some(code) = losses.unusable_code.take() { - report - .messages - .push(format!("coordinate system {code} can't be used; coordinates are read in {asked}, the system asked for")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("coordinate system {code} can't be used; coordinates are read in {asked}, the system asked for"), + )); } // One it names that RustGIS can't use (a code, a WKT): read as asked too (as a // GeoJSON answer's is), and its message says so. @@ -6368,7 +6370,8 @@ mod tests { report .messages .iter() - .any(|m| m.as_str() == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for"), + .any(|m| m.as_str() == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for" + && m.loss == Some(crate::loss::LossCode::AssumedCrs)), "{:?}", report.messages ); From 74729238f1683613e7589c2642f3b77036980d2b Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 05:14:12 -0600 Subject: [PATCH 05/12] fix(data): workbook rows left out whole are their own dropped.feature notice, and assumed.encoding's help covers a drawing (#2371) --- crates/data/src/loss.rs | 2 +- crates/data/src/sheets.rs | 13 +++++++++---- docs/cli.md | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 56337b6939..433e05a021 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -138,7 +138,7 @@ loss_codes! { AssumedEncoding => ( "assumed.encoding", Assumed, - "Give the file's encoding in a form RustGIS reads, such as a .cpg file beside a Shapefile naming UTF-8 or its Windows code page." + "Give the file's encoding in a form RustGIS reads: for a Shapefile, a .cpg beside it naming UTF-8 or its Windows code page; for a drawing, its $DWGCODEPAGE." ), } diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 8aa8dbfd2b..2a84da1999 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -68,16 +68,17 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> }; message.push_str(&format!("; {what}, {}", crate::io::named_fields(&fields, &g.header_error_cells))); } + // Each error cell's value is read as empty: a value lost. + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, message)); + // A row with nothing but error cells is left out whole: a row lost, said on its own. if g.empty_error_rows > 0 { let what = if g.empty_error_rows == 1 { "1 otherwise empty row with error cells was omitted".to_string() } else { format!("{} otherwise empty rows with error cells were omitted", g.empty_error_rows) }; - message.push_str(&format!("; {what}")); + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, what)); } - // Each error cell's value is read as empty: a value lost. - report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, message)); } if rounded > 0 { report.messages.push(crate::loss::Note::loss( @@ -881,9 +882,13 @@ mod tests { let expected = if cell.is_empty() { vec![] } else { - vec!["2 spreadsheet error cells were read as empty, in 'id', 'note'; 1 otherwise empty row with error cells was omitted"] + vec!["2 spreadsheet error cells were read as empty, in 'id', 'note'", "1 otherwise empty row with error cells was omitted"] }; assert_eq!(report.messages.texts().collect::>(), expected); + if !expected.is_empty() { + use crate::loss::LossCode::{DroppedFeature, DroppedValue}; + assert_eq!(report.messages.iter().map(|m| m.loss).collect::>(), [Some(DroppedValue), Some(DroppedFeature)]); + } } } diff --git a/docs/cli.md b/docs/cli.md index 3a9fde50bf..07a35147aa 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -176,7 +176,7 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. | | `assumed.null-marker` | Write the value another way if the text Null is meant as text, not as an empty value. | | `assumed.crs` | Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). | -| `assumed.encoding` | Give the file's encoding in a form RustGIS reads, such as a .cpg file beside a Shapefile naming UTF-8 or its Windows code page. | +| `assumed.encoding` | Give the file's encoding in a form RustGIS reads: for a Shapefile, a .cpg beside it naming UTF-8 or its Windows code page; for a drawing, its $DWGCODEPAGE. | Not every loss has a code yet: losses still reported without one don't stop a strict run. From ab32cdfd3b9fb5c2aa29a6d1c07cec70616019fe Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 05:42:07 -0600 Subject: [PATCH 06/12] fix(data): DXF counts what it can't draw by block, layer and kind instead of keeping it, and joined pages say every unusable code (#2371) --- crates/data/src/dxf.rs | 119 ++++++++++++++++++------------- crates/data/src/esripbf.rs | 23 +++++- crates/data/src/esripbf/tests.rs | 20 ++++++ crates/data/src/loss.rs | 2 +- crates/data/src/ogc.rs | 5 +- docs/cli.md | 2 +- 6 files changed, 117 insertions(+), 54 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index bc5a502f6e..0727edbeb5 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -371,10 +371,6 @@ enum Shape { constant_z: bool, }, Insert(Insert), - /// An entity that can't be drawn: one RustGIS doesn't draw (by kind) or can't read. Kept in - /// its place so it is counted only where it would have been drawn: not in a block the - /// drawing never places, and once for each placement of one it does. - Lost(Option), } impl Shape { @@ -1165,8 +1161,17 @@ struct Drawing { layers: HashMap, blocks: HashMap)>, entities: Vec, + /// The entities that can't be drawn, counted by where they would have been, so they are + /// counted only where drawn: the model's and paper space's (`lost`), and each block's, + /// once for each placement of it (`block_lost`, by lower-cased name). + lost: LostCounts, + block_lost: HashMap, } +/// Entities that can't be drawn, counted by layer (as written, lower-cased), paper space, and +/// kind: one RustGIS doesn't draw (its name), or one it can't read (`None`). +type LostCounts = BTreeMap<(String, String, bool, Option), usize>; + /// The magnitude of an ACI color index (negative means its layer is off). The one signed /// integer without a positive counterpart is malformed and must not overflow while reading. /// When encountered in a layer definition or drawn entity it refuses the drawing rather than @@ -1177,7 +1182,10 @@ fn color_magnitude(color: i64) -> Result { /// Reads the records of each section. fn drawing(records: &[Record]) -> Result { - let mut d = Drawing { layers: HashMap::new(), blocks: HashMap::new(), entities: Vec::new() }; + let mut d = + Drawing { layers: HashMap::new(), blocks: HashMap::new(), entities: Vec::new(), lost: BTreeMap::new(), block_lost: HashMap::new() }; + // What can't be drawn in the block being read. + let mut block_lost = LostCounts::new(); let mut section = ""; // The block being read: name, base point, entities. let mut block: Option<(String, P3, Vec)> = None; @@ -1210,13 +1218,18 @@ fn drawing(records: &[Record]) -> Result { if r.kind == "BLOCK" { let name = g.s(2).map(str::trim).unwrap_or("").to_string(); block = Some((name, g.pt(10).unwrap_or([0.0; 3]), Vec::new())); + block_lost = LostCounts::new(); continue; } if r.kind == "ENDBLK" { if let Some((name, base, ents)) = block.take() && !name.is_empty() { - d.blocks.insert(name.to_ascii_lowercase(), (base, ents)); + let key = name.to_ascii_lowercase(); + if !block_lost.is_empty() { + d.block_lost.insert(key.clone(), std::mem::take(&mut block_lost)); + } + d.blocks.insert(key, (base, ents)); } continue; } @@ -1238,28 +1251,22 @@ fn drawing(records: &[Record]) -> Result { if matches!(r.kind, "SEQEND" | "VERTEX") || (r.kind == "ATTDEF" && g.i(70).unwrap_or(0) & 2 == 0) { continue; } - // What can't be drawn stays in its place, counted where it would be drawn. - let lost = |shape: Shape| Ent { - kind: "LOST", - layer: g.s(8).map(str::trim).unwrap_or("0").to_string(), - layer_key: g.s(8).map(str::trim).unwrap_or("0").to_ascii_lowercase(), - // Not color-validated: nothing of it is drawn. - color: 256, - linetype: None, - text: None, - paper: g.i(67) == Some(1), - height: None, - rotation: None, - shape, - loss: PathLoss::default(), + // What can't be drawn is counted where it would be drawn: in its block, or in the + // model or paper space. + let mut count_lost = |kind: Option| { + let layer = g.s(8).map(str::trim).unwrap_or("0"); + let key = (layer.to_string(), layer.to_ascii_lowercase(), g.i(67) == Some(1), kind); + let counts = match &block { + Some(_) if section == "BLOCKS" => Some(&mut block_lost), + _ if section == "ENTITIES" => Some(&mut d.lost), + _ => None, + }; + if let Some(counts) = counts { + *counts.entry(key).or_insert(0) += 1; + } }; let Some(kind) = kind_name(r.kind) else { - let e = lost(Shape::Lost(Some(r.kind.to_string()))); - match &mut block { - Some((_, _, ents)) if section == "BLOCKS" => ents.push(e), - _ if section == "ENTITIES" => d.entities.push(e), - _ => {} - } + count_lost(Some(r.kind.to_string())); continue; }; let mut loss = PathLoss::default(); @@ -1267,12 +1274,7 @@ fn drawing(records: &[Record]) -> Result { // Entity builders use Option for malformed data; cancellation must escape as an error. crate::progress::check()?; let Some(shape) = shape else { - let e = lost(Shape::Lost(None)); - match &mut block { - Some((_, _, ents)) if section == "BLOCKS" => ents.push(e), - _ if section == "ENTITIES" => d.entities.push(e), - _ => {} - } + count_lost(None); continue; }; let text = match kind { @@ -1390,6 +1392,7 @@ fn has_varying_z<'a>(mut points: impl Iterator, first: Option fn emit( d: &Drawing, ents: &[Ent], + lost: Option<&LostCounts>, xf: &Xf, from: Inherit, depth: usize, @@ -1397,13 +1400,38 @@ fn emit( opts: &Options, out: &mut Out, ) -> Result<()> { + // What can't be drawn here, counted as a drawn entity would be placed: a step each, in paper + // space only when that is drawn, and on the layer asked for (layer 0 in a block takes the + // INSERT's). + for ((layer, _, paper, kind), &n) in lost.into_iter().flatten() { + crate::progress::check()?; + out.steps = out.steps.saturating_add(n); + if out.steps > MAX_STEPS { + out.overworked = true; + return Ok(()); + } + if depth == 0 && *paper && !opts.paper_space { + out.paper += n; + continue; + } + let layer = match from.layer { + Some(l) if layer == "0" => l, + _ => layer.as_str(), + }; + if opts.layer.is_some_and(|want| !layer.eq_ignore_ascii_case(want)) { + continue; + } + match kind { + Some(k) => *out.unread.entry(k.clone()).or_insert(0) += n, + None => out.bad += n, + } + } for e in ents { crate::progress::check()?; if out.vertex_capped { return Ok(()); } - let lost = matches!(e.shape, Shape::Lost(_)); - if out.count >= MAX_FEATURES && !lost { + if out.count >= MAX_FEATURES { out.capped = true; return Ok(()); } @@ -1473,7 +1501,7 @@ fn emit( loss: PathLoss::default(), }) .collect(); - emit(d, &drawn, xf, from, depth + 1, stack, opts, out)?; + emit(d, &drawn, None, xf, from, depth + 1, stack, opts, out)?; continue; } out.cut += 1; @@ -1506,7 +1534,8 @@ fn emit( block: Some(ins.block.as_str()), paper: from.paper || e.paper, }; - emit(d, inner, &xf.then(&local), inner_from, depth + 1, stack, opts, out)?; + let lost = stack.last().and_then(|k| d.block_lost.get(k)); + emit(d, inner, lost, &xf.then(&local), inner_from, depth + 1, stack, opts, out)?; if out.capped || out.overworked || out.vertex_capped { stack.pop(); out.copies = outer; @@ -1523,21 +1552,13 @@ fn emit( { continue; } - // An entity that can't be drawn, here where it would have been: counted, by kind. - if let Shape::Lost(kind) = &e.shape { - match kind { - Some(k) => *out.unread.entry(k.clone()).or_insert(0) += 1, - None => out.bad += 1, - } - continue; - } // Every coordinate placed is charged before it is built: a large polyline in a block // inserted many times can't fill the memory. let n = match &e.shape { Shape::Point(_) => 1, Shape::Line { points: ps, .. } | Shape::Polygon(ps) => ps.len(), Shape::Rings { rings: rs, .. } => rs.iter().map(Vec::len).sum(), - Shape::Insert(_) | Shape::Lost(_) => 0, + Shape::Insert(_) => 0, }; if out.vertices.saturating_add(n) > MAX_TOTAL_VERTICES { out.vertex_capped = true; @@ -1598,7 +1619,7 @@ fn emit( let varying = has_varying_z(kept.flatten(), first, *constant_z && preserves_z); (g, first, 2, varying) } - Shape::Insert(_) | Shape::Lost(_) => continue, + Shape::Insert(_) => continue, }; let Some(geometry) = geometry else { out.cut += 1; @@ -1673,7 +1694,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result> { add(name, key); } // What can't be drawn names no layer to pick. - for e in d.entities.iter().filter(|e| !matches!(e.shape, Shape::Lost(_))) { + for e in &d.entities { add(&e.layer, &e.layer_key); } for (_, ents) in d.blocks.values() { - for e in ents.iter().filter(|e| e.layer != "0" && !matches!(e.shape, Shape::Lost(_))) { + for e in ents.iter().filter(|e| e.layer != "0") { add(&e.layer, &e.layer_key); } } diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 09b49dd8d1..9958b29a5b 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -142,6 +142,8 @@ pub struct Losses { /// The coordinate system code an answer with features with a geometry names and RustGIS /// can't use, without a WKT (read as longitude/latitude). pub unusable_code: Option, + /// Pages joined after the first that named another code RustGIS can't use. + pub other_unusable: usize, } impl Losses { @@ -155,7 +157,23 @@ impl Losses { self.unprojected = self.unprojected.saturating_add(other.unprojected); self.with_zm = self.with_zm.saturating_add(other.with_zm); self.beyond = self.beyond.saturating_add(other.beyond); - self.unusable_code = self.unusable_code.or(other.unusable_code); + match (self.unusable_code, other.unusable_code) { + (Some(a), Some(b)) if a != b => self.other_unusable += 1 + other.other_unusable, + (None, b) => { + self.unusable_code = b; + self.other_unusable += other.other_unusable; + } + _ => self.other_unusable += other.other_unusable, + } + } + + /// The pages that named another code RustGIS can't use, as the notice for the first adds them. + pub fn others_said(&self) -> String { + match self.other_unusable { + 0 => String::new(), + 1 => " (and another page names a code it can't use either)".to_string(), + n => format!(" (and {n} other pages name codes it can't use either)"), + } } /// What they say, one message per kind (as [`read`] says them). @@ -171,7 +189,7 @@ impl Losses { if let Some(code) = self.unusable_code { out.push(crate::loss::Note::loss( crate::loss::LossCode::AssumedCrs, - format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude"), + format!("coordinate system {code} can't be used{}; coordinates are read as longitude/latitude", self.others_said()), )); } if self.unreadable > 0 { @@ -448,6 +466,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result no_crs: any_geometry && code.is_none() && wkt.is_none(), unread_code: any_geometry && unread_code, unusable_code: unusable_code.filter(|_| any_geometry), + other_unusable: 0, unreadable: tally.unreadable, not_utf8: tally.not_utf8, flat_rings: tally.flat_rings, diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index e5dde3ba3c..9f619e340f 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -799,3 +799,23 @@ fn a_wkt_is_taken_from_the_text_room_at_its_size_once_read() { assert!(spatial_reference(&reference, &mut Tally { text_room: 13, ..Tally::default() }).is_err()); assert!(spatial_reference(&reference, &mut Tally { text_room: 14, ..Tally::default() }).is_ok()); } + +/// Pages joined that name different codes RustGIS can't use say the first and how many others, +/// so every page's assumption is said; the same code again adds nothing. +#[test] +fn joined_pages_say_every_unusable_code() { + let page = |code| Losses { unusable_code: Some(code), ..Losses::default() }; + let mut all = page(999_999); + all.add(&page(999_999)); + all.add(&page(888_888)); + all.add(&page(777_777)); + let said: Vec<_> = all.messages().iter().map(|m| (m.as_str().to_string(), m.loss)).collect(); + assert_eq!( + said, + [( + "coordinate system 999999 can't be used (and 2 other pages name codes it can't use either); coordinates are read as longitude/latitude" + .to_string(), + Some(crate::loss::LossCode::AssumedCrs) + )] + ); +} diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 433e05a021..58e7ba2fcb 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -138,7 +138,7 @@ loss_codes! { AssumedEncoding => ( "assumed.encoding", Assumed, - "Give the file's encoding in a form RustGIS reads: for a Shapefile, a .cpg beside it naming UTF-8 or its Windows code page; for a drawing, its $DWGCODEPAGE." + "Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8." ), } diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 8ea6a95aaf..2a85247964 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4599,7 +4599,10 @@ impl Pages { if let Some(code) = losses.unusable_code.take() { report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::AssumedCrs, - format!("coordinate system {code} can't be used; coordinates are read in {asked}, the system asked for"), + format!( + "coordinate system {code} can't be used{}; coordinates are read in {asked}, the system asked for", + losses.others_said() + ), )); } // One it names that RustGIS can't use (a code, a WKT): read as asked too (as a diff --git a/docs/cli.md b/docs/cli.md index 07a35147aa..08674c5006 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -176,7 +176,7 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. | | `assumed.null-marker` | Write the value another way if the text Null is meant as text, not as an empty value. | | `assumed.crs` | Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). | -| `assumed.encoding` | Give the file's encoding in a form RustGIS reads: for a Shapefile, a .cpg beside it naming UTF-8 or its Windows code page; for a drawing, its $DWGCODEPAGE. | +| `assumed.encoding` | Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. | Not every loss has a code yet: losses still reported without one don't stop a strict run. From 4a7fd99ba9d0ee529234a6a5847fa00405827efe Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 06:06:30 -0600 Subject: [PATCH 07/12] fix(data): a workbook row of only serial-60 dates is said as omitted (#2371) --- crates/data/src/sheets.rs | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 2a84da1999..98655e543c 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -80,6 +80,17 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, what)); } } + if g.empty_phantom_rows > 0 { + let what = if g.empty_phantom_rows == 1 { + "1 row was omitted, as its only values were serial-60 dates (a day that never was), read as empty".to_string() + } else { + format!( + "{} rows were omitted, as their only values were serial-60 dates (a day that never was), read as empty", + g.empty_phantom_rows + ) + }; + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, what)); + } if rounded > 0 { report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::ChangedRounded, @@ -119,6 +130,8 @@ struct Grid { empty_error_rows: usize, /// Per column that isn't one of dates, the serial-60 cells read as empty. phantom_dates: Vec, + /// Rows left out because their only values were serial-60 dates, read as empty. + empty_phantom_rows: usize, } fn grid(bytes: &[u8], sheet: Option<&str>) -> Result { @@ -234,11 +247,14 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< .collect::>(); (row, cells, had_error, phantom) }); - let mut empty_error_rows = 0; - let mut keep = |(_, cells, had_error, _): &(usize, Vec, bool, Vec)| { + let (mut empty_error_rows, mut empty_phantom_rows) = (0, 0); + let mut keep = |(_, cells, had_error, phantom): &(usize, Vec, bool, Vec)| { let nonempty = cells.iter().any(|c| !c.trim().is_empty()); if !nonempty && *had_error { empty_error_rows += 1; + } else if !nonempty && !phantom.is_empty() { + // A row whose only values were serial-60 dates, read as empty: left out whole. + empty_phantom_rows += 1; } nonempty }; @@ -275,7 +291,19 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< .filter(keep) .map(|(_, cells, _, _)| cells) .collect(); - Ok(Grid { names, pick, headers, rows, dates, rounded_dates, error_cells, header_error_cells, empty_error_rows, phantom_dates }) + Ok(Grid { + names, + pick, + headers, + rows, + dates, + rounded_dates, + error_cells, + header_error_cells, + empty_error_rows, + empty_phantom_rows, + phantom_dates, + }) } /// Check every ZIP member before calamine opens it, without suffix or case filters. ODS @@ -834,6 +862,8 @@ mod tests { let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); assert_eq!(ds.features.len(), 1); assert!(report.messages.iter().any(|m| m.contains("1 value in 'wkt' isn't a date")), "{:?}", report.messages); + let row = report.messages.iter().find(|m| m.contains("row was omitted")).unwrap(); + assert_eq!(row.loss, Some(crate::loss::LossCode::DroppedFeature)); } /// Multiple errors in one column and another column count once each; blank cells don't. From 9f08011ecb097fc6caf8caf0d46c89529fb362be Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 06:25:39 -0600 Subject: [PATCH 08/12] fix(data): a DXF block defined again replaces what the earlier one couldn't draw (#2371) --- crates/data/src/dxf.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 0727edbeb5..3ec5ea9651 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1225,8 +1225,12 @@ fn drawing(records: &[Record]) -> Result { if let Some((name, base, ents)) = block.take() && !name.is_empty() { + // A block defined again replaces the earlier one, and what it couldn't + // draw with it. let key = name.to_ascii_lowercase(); - if !block_lost.is_empty() { + if block_lost.is_empty() { + d.block_lost.remove(&key); + } else { d.block_lost.insert(key.clone(), std::mem::take(&mut block_lost)); } d.blocks.insert(key, (base, ents)); @@ -1947,6 +1951,10 @@ mod tests { .collect::>() }; assert!(said(&drawing("")).is_empty(), "a block never placed loses nothing"); + // A block defined again without them: the later definition is the one placed. + let redefined = + drawing("0 INSERT 2 B 10 5 20 5").replacen("ENDSEC", "BLOCK\n2\nB\n0\nPOINT\n10\n2\n20\n2\n0\nENDBLK\n0\nENDSEC", 1); + assert!(said(&redefined).is_empty(), "{:?}", said(&redefined)); assert_eq!( said(&drawing("0 INSERT 2 B 10 5 20 5 0 INSERT 2 B 10 9 20 9")), [("entities RustGIS doesn't draw were left out: 2 IMAGE".to_string(), Some(crate::loss::LossCode::DroppedFeature))] From 99e51478cd478648089bef5ead07adbb0e3562c1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 06:50:50 -0600 Subject: [PATCH 09/12] fix(data): serial-60 rows are counted as omitted below the heading only, and DXF's counts key a layer once (#2371) --- crates/data/src/dxf.rs | 10 +++++----- crates/data/src/sheets.rs | 19 ++++++++++++++----- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 3ec5ea9651..cdfafa7d77 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1168,9 +1168,9 @@ struct Drawing { block_lost: HashMap, } -/// Entities that can't be drawn, counted by layer (as written, lower-cased), paper space, and -/// kind: one RustGIS doesn't draw (its name), or one it can't read (`None`). -type LostCounts = BTreeMap<(String, String, bool, Option), usize>; +/// Entities that can't be drawn, counted by layer (as written; compared ignoring case), paper +/// space, and kind: one RustGIS doesn't draw (its name), or one it can't read (`None`). +type LostCounts = BTreeMap<(String, bool, Option), usize>; /// The magnitude of an ACI color index (negative means its layer is off). The one signed /// integer without a positive counterpart is malformed and must not overflow while reading. @@ -1259,7 +1259,7 @@ fn drawing(records: &[Record]) -> Result { // model or paper space. let mut count_lost = |kind: Option| { let layer = g.s(8).map(str::trim).unwrap_or("0"); - let key = (layer.to_string(), layer.to_ascii_lowercase(), g.i(67) == Some(1), kind); + let key = (layer.to_string(), g.i(67) == Some(1), kind); let counts = match &block { Some(_) if section == "BLOCKS" => Some(&mut block_lost), _ if section == "ENTITIES" => Some(&mut d.lost), @@ -1407,7 +1407,7 @@ fn emit( // What can't be drawn here, counted as a drawn entity would be placed: a step each, in paper // space only when that is drawn, and on the layer asked for (layer 0 in a block takes the // INSERT's). - for ((layer, _, paper, kind), &n) in lost.into_iter().flatten() { + for ((layer, paper, kind), &n) in lost.into_iter().flatten() { crate::progress::check()?; out.steps = out.steps.saturating_add(n); if out.steps > MAX_STEPS { diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 98655e543c..20183112a4 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -248,13 +248,10 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< (row, cells, had_error, phantom) }); let (mut empty_error_rows, mut empty_phantom_rows) = (0, 0); - let mut keep = |(_, cells, had_error, phantom): &(usize, Vec, bool, Vec)| { + let mut keep = |(_, cells, had_error, _): &(usize, Vec, bool, Vec)| { let nonempty = cells.iter().any(|c| !c.trim().is_empty()); if !nonempty && *had_error { empty_error_rows += 1; - } else if !nonempty && !phantom.is_empty() { - // A row whose only values were serial-60 dates, read as empty: left out whole. - empty_phantom_rows += 1; } nonempty }; @@ -281,7 +278,12 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< }) .collect(); let rows = rows - .inspect(|(_, _, _, phantom)| { + .inspect(|(_, cells, had_error, phantom)| { + // A data row whose only values were serial-60 dates, read as empty: left out whole + // (one with error cells too is said with those). + if !had_error && !phantom.is_empty() && cells.iter().all(|c| c.trim().is_empty()) { + empty_phantom_rows += 1; + } for k in phantom { if let Some(n) = phantom_dates.get_mut(*k) { *n += 1; @@ -864,6 +866,13 @@ mod tests { assert!(report.messages.iter().any(|m| m.contains("1 value in 'wkt' isn't a date")), "{:?}", report.messages); let row = report.messages.iter().find(|m| m.contains("row was omitted")).unwrap(); assert_eq!(row.loss, Some(crate::loss::LossCode::DroppedFeature)); + // One above the heading is no data row: nothing of it is said. + let above = xlsx(&[("Places", &[&["", phantom], &["name", "wkt"], &["a", "POINT (1 2)"]])]); + let mut entries = crate::zip::read(&above).unwrap(); + entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); + assert_eq!(ds.features.len(), 1); + assert!(!report.messages.iter().any(|m| m.contains("omitted") || m.contains("isn't a date")), "{:?}", report.messages); } /// Multiple errors in one column and another column count once each; blank cells don't. From af5c9cf4c4b18b53048bf46539331d22e1f552ca Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 07:16:09 -0600 Subject: [PATCH 10/12] fix(data): DXF's undrawable entities cost steps only in a placed block (#2371) --- crates/data/src/dxf.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index cdfafa7d77..0375716d05 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1404,15 +1404,19 @@ fn emit( opts: &Options, out: &mut Out, ) -> Result<()> { - // What can't be drawn here, counted as a drawn entity would be placed: a step each, in paper - // space only when that is drawn, and on the layer asked for (layer 0 in a block takes the - // INSERT's). + // What can't be drawn here, counted as a drawn entity would be placed: in a block, a step + // each; in paper space only when that is drawn; and on the layer asked for (layer 0 in a block + // takes the INSERT's). for ((layer, paper, kind), &n) in lost.into_iter().flatten() { crate::progress::check()?; - out.steps = out.steps.saturating_add(n); - if out.steps > MAX_STEPS { - out.overworked = true; - return Ok(()); + // In a block, each copy walks these again, so each is a step; the model's are counted + // once, and cost the drawable entities after them nothing. + if depth > 0 { + out.steps = out.steps.saturating_add(n); + if out.steps > MAX_STEPS { + out.overworked = true; + return Ok(()); + } } if depth == 0 && *paper && !opts.paper_space { out.paper += n; From 59f79474ef14eca99ffc247b0a0d5cda25b4e791 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 07:41:20 -0600 Subject: [PATCH 11/12] fix(data): workbook rows left out whole are counted below the heading only (#2371) --- crates/data/src/sheets.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 20183112a4..29175910a2 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -248,15 +248,9 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< (row, cells, had_error, phantom) }); let (mut empty_error_rows, mut empty_phantom_rows) = (0, 0); - let mut keep = |(_, cells, had_error, _): &(usize, Vec, bool, Vec)| { - let nonempty = cells.iter().any(|c| !c.trim().is_empty()); - if !nonempty && *had_error { - empty_error_rows += 1; - } - nonempty - }; + let keep = |(_, cells, _, _): &(usize, Vec, bool, Vec)| cells.iter().any(|c| !c.trim().is_empty()); // The first row with anything in it names the columns. - let (header_row, headers, _, _) = rows.by_ref().find(&mut keep).unwrap_or_default(); + let (header_row, headers, _, _) = rows.by_ref().find(keep).unwrap_or_default(); if headers.is_empty() { return Err(DataError::Format(format!("sheet '{pick}' is empty"))); } @@ -279,10 +273,14 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< .collect(); let rows = rows .inspect(|(_, cells, had_error, phantom)| { - // A data row whose only values were serial-60 dates, read as empty: left out whole - // (one with error cells too is said with those). - if !had_error && !phantom.is_empty() && cells.iter().all(|c| c.trim().is_empty()) { - empty_phantom_rows += 1; + // A data row left out whole, below the heading: one whose only values were error + // cells, or serial-60 dates, read as empty (one with both is said with the errors). + if cells.iter().all(|c| c.trim().is_empty()) { + if *had_error { + empty_error_rows += 1; + } else if !phantom.is_empty() { + empty_phantom_rows += 1; + } } for k in phantom { if let Some(n) = phantom_dates.get_mut(*k) { @@ -873,6 +871,14 @@ mod tests { let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); assert_eq!(ds.features.len(), 1); assert!(!report.messages.iter().any(|m| m.contains("omitted") || m.contains("isn't a date")), "{:?}", report.messages); + // Nor is one there with an error cell besides: no row of the data is left out. + let error = r#"#DIV/0!"#; + let mixed = xlsx(&[("Places", &[&[error, phantom], &["name", "wkt"], &["a", "POINT (1 2)"]])]); + let mut entries = crate::zip::read(&mixed).unwrap(); + entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); + assert_eq!(ds.features.len(), 1); + assert!(!report.messages.iter().any(|m| m.contains("omitted")), "{:?}", report.messages); } /// Multiple errors in one column and another column count once each; blank cells don't. From 2d9f223ee27b4431423c6d003319cd9a6c4fa43f Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 08:28:25 -0600 Subject: [PATCH 12/12] fix(data): workbook error cells are counted below the heading only, and an erroneous heading is said on its own (#2371) --- crates/data/src/esripbf.rs | 2 ++ crates/data/src/sheets.rs | 53 +++++++++++++++++++------------------- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 9958b29a5b..5f403bd4da 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -465,6 +465,8 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result // Assumed, so said: an answer that names no coordinate system. no_crs: any_geometry && code.is_none() && wkt.is_none(), unread_code: any_geometry && unread_code, + // A page without geometry places nothing in the code it names, so says nothing of it, + // unlike a WKT it can't read, which is said (plainly) as what the answer holds. unusable_code: unusable_code.filter(|_| any_geometry), other_unusable: 0, unreadable: tally.unreadable, diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 29175910a2..7967084a71 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -54,20 +54,21 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> let (ds, mut report) = read_rows(&g.headers, &g.rows, 0, &title, opts, Some((&g.dates, &g.phantom_dates)))?; let errors: usize = g.error_cells.iter().sum(); let rounded: usize = g.rounded_dates.iter().sum(); + let headings: usize = g.header_error_cells.iter().sum(); let fields: Vec = - if errors > 0 || rounded > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] }; + if errors > 0 || rounded > 0 || headings > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] }; + // A heading that is an error is named by its column letter: the column's name, not its data. + if headings > 0 { + let what = if headings == 1 { + "1 erroneous heading was named by its column letter".to_string() + } else { + format!("{headings} erroneous headings were named by their column letters") + }; + report.messages.push(format!("{what}, {}", crate::io::named_fields(&fields, &g.header_error_cells))); + } if errors > 0 { let what = if errors == 1 { "1 spreadsheet error cell was".to_string() } else { format!("{errors} spreadsheet error cells were") }; - let mut message = format!("{what} read as empty, in {}", crate::io::named_fields(&fields, &g.error_cells)); - let headings: usize = g.header_error_cells.iter().sum(); - if headings > 0 { - let what = if headings == 1 { - "1 erroneous heading was named by its column letter".to_string() - } else { - format!("{headings} erroneous headings were named by their column letters") - }; - message.push_str(&format!("; {what}, {}", crate::io::named_fields(&fields, &g.header_error_cells))); - } + let message = format!("{what} read as empty, in {}", crate::io::named_fields(&fields, &g.error_cells)); // Each error cell's value is read as empty: a value lost. report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, message)); // A row with nothing but error cells is left out whole: a row lost, said on its own. @@ -224,18 +225,17 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< // empty when it was all the row held. let mut phantom_dates = vec![0usize; w]; let mut error_cells = vec![0usize; w]; + // Error cells too are counted below the heading only: a title row's error is no cell of the + // table. let mut rows = range.rows().enumerate().map(|(row, r)| { - let mut had_error = false; + let mut errors: Vec = Vec::new(); let mut phantom: Vec = Vec::new(); let cells = r .iter() .enumerate() .map(|(k, d)| match (d, dates.get(k)) { (Data::Error(_), _) => { - had_error = true; - if let Some(n) = error_cells.get_mut(k) { - *n += 1; - } + errors.push(k); String::new() } (Data::DateTime(t), Some(None)) if is_phantom_day(t) => { @@ -245,10 +245,10 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< _ => cell(d), }) .collect::>(); - (row, cells, had_error, phantom) + (row, cells, errors, phantom) }); let (mut empty_error_rows, mut empty_phantom_rows) = (0, 0); - let keep = |(_, cells, _, _): &(usize, Vec, bool, Vec)| cells.iter().any(|c| !c.trim().is_empty()); + let keep = |(_, cells, _, _): &(usize, Vec, Vec, Vec)| cells.iter().any(|c| !c.trim().is_empty()); // The first row with anything in it names the columns. let (header_row, headers, _, _) = rows.by_ref().find(keep).unwrap_or_default(); if headers.is_empty() { @@ -272,11 +272,16 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< }) .collect(); let rows = rows - .inspect(|(_, cells, had_error, phantom)| { + .inspect(|(_, cells, errors, phantom)| { + for k in errors { + if let Some(n) = error_cells.get_mut(*k) { + *n += 1; + } + } // A data row left out whole, below the heading: one whose only values were error // cells, or serial-60 dates, read as empty (one with both is said with the errors). if cells.iter().all(|c| c.trim().is_empty()) { - if *had_error { + if !errors.is_empty() { empty_error_rows += 1; } else if !phantom.is_empty() { empty_phantom_rows += 1; @@ -878,7 +883,7 @@ mod tests { entries.push(("xl/styles.xml".into(), br#""#.to_vec())); let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); assert_eq!(ds.features.len(), 1); - assert!(!report.messages.iter().any(|m| m.contains("omitted")), "{:?}", report.messages); + assert!(!report.messages.iter().any(|m| m.contains("omitted") || m.contains("error cell")), "{:?}", report.messages); } /// Multiple errors in one column and another column count once each; blank cells don't. @@ -904,11 +909,7 @@ mod tests { let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap(); assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::>(), ["id", "B"]); assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Text("kept".into())]); - let expected = if heading.is_empty() { - vec![] - } else { - vec!["1 spreadsheet error cell was read as empty, in 'B'; 1 erroneous heading was named by its column letter, 'B'"] - }; + let expected = if heading.is_empty() { vec![] } else { vec!["1 erroneous heading was named by its column letter, 'B'"] }; assert_eq!(report.messages.texts().collect::>(), expected); } }