From 492b280cf60c82b1180207c9a73b33b319b5a096 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 18:31:43 -0600 Subject: [PATCH 01/16] fix(data): close silent and uncoded loss reporting gaps --- ROADMAP.md | 8 +- apps/rustgis-cli/tests/integration/strict.rs | 27 ++ crates/analysis/src/tools.rs | 21 +- crates/data/src/dxf.rs | 241 ++++++++++++++++-- crates/data/src/filegdb.rs | 2 +- crates/data/src/filegdb/tests.rs | 1 + crates/data/src/io.rs | 46 +++- crates/data/src/loss.rs | 22 +- crates/data/src/sheets.rs | 17 ++ crates/data/src/sheets/xlsb.rs | 83 ++++++ crates/data/src/source/mod.rs | 7 +- crates/data/src/source/parquet/declared.rs | 6 +- crates/data/src/source/sqlserver_gdb.rs | 16 +- crates/data/src/source/tests.rs | 7 +- crates/engine/src/cmd/imagery.rs | 16 +- crates/engine/src/tests.rs | 4 +- .../engine/testdata/reading-losses/README.md | 14 +- .../tests/integration/never_silent_reading.rs | 63 +++-- docs/user-guide/loss-codes.md | 36 ++- 19 files changed, 537 insertions(+), 100 deletions(-) create mode 100644 crates/data/src/sheets/xlsb.rs diff --git a/ROADMAP.md b/ROADMAP.md index b5df85b253..4d7c1d7178 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -69,11 +69,9 @@ The shared pieces the everyday workflow stands on. ### Correct results A result is right, or RustGIS says what it lost or assumed ([AGENTS.md](AGENTS.md#never-silent)). -- Known silent losses: DXF polyface faces with missing vertices and unreadable supplied Z outside 3D POLYLINE vertices; and the text - reader loss listed as `Silent` in `crates/engine/tests/integration/never_silent_reading.rs`: - attribute fields/values in XLSB short-cell workbooks (the original SheetJS 0.18.5 clean - workbook retains its point but no attributes, without a notice). A fix makes - its case `Said` or `Imported` _(open)_. +- Known silent losses still to cover: DXF unreadable extrusion Z (group 230), short polyface + faces and the polyface vertex-record cap; XLSB cached formula errors (`BrtFmlaError`) and + rich inline strings (`BrtCellRString`) skipped by the workbook reader _(open)_. - Lossy sample files in `never_silent_reading.rs` for the readers it doesn't cover yet: remaining distinct loss families and parser paths (see the finite [coverage inventory](crates/engine/testdata/reading-losses/README.md#coverage-boundaries)). It covers GeoJSON, TopoJSON, CSV, diff --git a/apps/rustgis-cli/tests/integration/strict.rs b/apps/rustgis-cli/tests/integration/strict.rs index cf824c358d..2defae5dbd 100644 --- a/apps/rustgis-cli/tests/integration/strict.rs +++ b/apps/rustgis-cli/tests/integration/strict.rs @@ -137,3 +137,30 @@ fn explain_says_what_a_code_means_and_what_to_do_offline() { assert!(!unknown.status.success()); assert!(String::from_utf8_lossy(&unknown.stderr).contains("not a loss code")); } + +/// Previously plain notices must now stop a strict run and accept only their matching allowance. +#[test] +fn strict_classifies_csv_protection_and_xy_crs_assumptions() { + for (property, value, command, code) in [ + ("=label", "safe", r#"data.convert={"format":"csv","layer":"points"}"#, "changed.field-name"), + ("label", "=SUM(A1)", r#"data.convert={"format":"csv","layer":"points"}"#, "changed.csv-guard"), + ("label", "safe", r#"gp.run={"tool":"xyTableToPoint","params":{"input":"points","x":"x","y":"y"}}"#, "assumed.crs"), + ] { + let mut properties = serde_json::json!({"x": 1, "y": 2}); + properties[property] = serde_json::json!(value); + let geojson = serde_json::json!({"type":"FeatureCollection", "features":[{"type":"Feature", "geometry":{"type":"Point","coordinates":[1,2]}, "properties":properties}]}); + let add = format!("layer.addDataText={}", serde_json::json!({"fileName":"points.geojson", "text":geojson.to_string()})); + for allow in [false, true] { + let mut args = vec!["--strict", "--cmd", &add, "--cmd", command]; + if allow { + args.extend(["--allow", code]); + } + let out = cli(&args); + let error = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(if allow { 0 } else { 3 }), "{code}: {error}"); + if !allow { + assert!(error.contains(code), "{error}"); + } + } + } +} diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 2c3e9b55ef..15ffe05396 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -4691,10 +4691,13 @@ fn xy_table_to_point(inp: &dyn Inputs, p: &Json) -> Result { }); } let mut messages = vec![format!("XY Table To Point: {placed} points")]; + let mut losses: Vec = Vec::new(); if crs_text.is_empty() { - messages.push("XY Table To Point: WGS 84 (EPSG:4326) was assumed because no coordinate system was given".into()); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::AssumedCrs, + text: "XY Table To Point: WGS 84 (EPSG:4326) was assumed because no coordinate system was given".into(), + }); } - let mut losses: Vec = Vec::new(); messages.extend(crs_note.map(|note| format!("XY Table To Point: its coordinate system: {note}"))); // A row without numbers had no place to lose; one whose numbers have no place in the system // has lost it. @@ -13967,12 +13970,15 @@ mod tests { assert_eq!(run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat", "crs": 3857})).unwrap_err(), "crs must be text"); let r = run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat"})).unwrap(); + assert_eq!(r.losses[0].code, rustgis_data::loss::LossCode::AssumedCrs); + let explicit = run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat", "crs": "EPSG:4326"})).unwrap(); + assert!(!explicit.losses.iter().any(|n| n.code == rustgis_data::loss::LossCode::AssumedCrs)); // Rows without numbers lose nothing; the one off the globe loses its place. assert_eq!( said(&r)[1..], [ - "XY Table To Point: WGS 84 (EPSG:4326) was assumed because no coordinate system was given", "3 of 7 rows have no numbers in both fields; they are in the table without a point", + "AssumedCrs: XY Table To Point: WGS 84 (EPSG:4326) was assumed because no coordinate system was given", "DroppedGeometry: 1 of 7 rows have coordinates with no place in EPSG:4326; they are in the table without a point" ] ); @@ -14015,7 +14021,14 @@ mod tests { // Points in longitude/latitude are held there, with no system of their own, as before. for (crs, assumed) in [("", true), (" ", true), ("EPSG:4326", false)] { let r = run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat", "crs": crs})).unwrap(); - assert_eq!(r.messages.iter().filter(|m| m.contains("WGS 84 (EPSG:4326) was assumed")).count(), usize::from(assumed), "{crs:?}"); + assert_eq!( + r.losses + .iter() + .filter(|m| m.code == rustgis_data::loss::LossCode::AssumedCrs && m.text.contains("WGS 84 (EPSG:4326) was assumed")) + .count(), + usize::from(assumed), + "{crs:?}" + ); let lonlat = layer(r); assert_eq!((lonlat.coord_crs(), lonlat.crs), (Crs::LonLat, None)); } diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 0375716d05..9b3cae23c2 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -424,6 +424,8 @@ struct PathLoss { missing_y: u64, invalid_z: u64, short_rings: u64, + missing_faces: u64, + unreadable_z: u64, } impl PathLoss { @@ -433,6 +435,8 @@ impl PathLoss { self.missing_y = self.missing_y.saturating_add(other.missing_y); self.invalid_z = self.invalid_z.saturating_add(other.invalid_z); self.short_rings = self.short_rings.saturating_add(other.short_rings); + self.missing_faces = self.missing_faces.saturating_add(other.missing_faces); + self.unreadable_z = self.unreadable_z.saturating_add(other.unreadable_z); } } @@ -658,6 +662,11 @@ fn plain_text(s: &str) -> String { /// Cancellation also stops the Option-based builders; the caller checks and propagates it. fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) -> Option { let ocs = Xf::ocs(g.extrusion()); + if !(kind == "POLYLINE" && g.i(70).unwrap_or(0) & (8 | 64) != 0) { + loss.unreadable_z += + g.p.iter().filter(|(c, v)| (if kind == "INSERT" { *c == 30 } else { (30..=38).contains(c) }) && num(v).is_none()).count() + as u64; + } Some(match kind { "POINT" => Shape::Point(g.pt(10)?), "LINE" => Shape::line(vec![g.pt(10)?, g.pt(11)?]), @@ -696,7 +705,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - "POLYLINE" => { let flags = g.i(70).unwrap_or(0); if flags & 64 != 0 { - return polyface(vertices); + return polyface(vertices, loss); } if flags & 16 != 0 { // A polygon mesh: its rows as lines would be clutter; left out. @@ -829,7 +838,8 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - Some((20, y)) => num(y)?, _ => return None, }; - pts.push([x, y, 0.0]); + let z = it.clone().nth(1).filter(|(c, _)| *c == 30).and_then(|(_, z)| num(z)).unwrap_or(0.0); + pts.push([x, y, z]); } } Shape::line(pts) @@ -909,7 +919,8 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - Some((21, y)) => num(y)?, _ => return None, }; - pts.push([x, y, 0.0]); + let z = it.clone().nth(1).filter(|(c, _)| *c == 31).and_then(|(_, z)| num(z)).unwrap_or(0.0); + pts.push([x, y, z]); } } if g.i(71).unwrap_or(0) & 2 != 0 @@ -969,22 +980,37 @@ fn measure(v: f64) -> String { } /// A polyface mesh's faces as polygons (its VERTEX records: positions, then faces by index). -fn polyface(vertices: &[Record]) -> Option { +fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { let mut pos: Vec = Vec::new(); let mut faces: Vec> = Vec::new(); - for v in vertices.iter().take(MAX_VERTICES) { + for (index, v) in vertices.iter().take(MAX_VERTICES).enumerate() { + if index % 1024 == 0 { + crate::progress::check().ok()?; + } let g = G { p: &v.groups }; let flags = g.i(70).unwrap_or(0); if flags & 64 != 0 { + loss.unreadable_z += g.p.iter().filter(|(c, v)| *c == 30 && num(v).is_none()).count() as u64; pos.push(g.pt(10)?); } else if flags & 128 != 0 { - let ring: Vec = [71, 72, 73, 74] - .iter() - .filter_map(|c| g.i(*c)) - .filter(|i| *i != 0) - .filter_map(|i| usize::try_from(i.unsigned_abs()).ok()) - .filter_map(|i| pos.get(i.checked_sub(1)?).copied()) - .collect(); + let mut ring = Vec::new(); + let mut missing = false; + for c in [71, 72, 73, 74] { + if g.s(c).is_some() && g.i(c).is_none() { + missing = true; + continue; + } + let Some(i) = g.i(c).filter(|i| *i != 0) else { continue }; + let point = usize::try_from(i.unsigned_abs()).ok().and_then(|i| pos.get(i.checked_sub(1)?)); + match point { + Some(p) => ring.push(*p), + None => missing = true, + } + } + if missing { + loss.missing_faces += 1; + continue; + } if ring.len() >= 3 { let mut r = ring; if let Some(f) = r.first().copied() { @@ -1155,11 +1181,18 @@ fn append(ring: &mut Vec, mut piece: Vec) { ring.extend(piece); } +/// A block's placement and entities; an unreadable supplied base height is checked only if used. +struct Block { + base: P3, + entities: Vec, + invalid_z: bool, +} + /// A drawing's layers (name → colour, linetype) and blocks (name → base point and entities). struct Drawing { /// Lower-cased name → the name as written, colour, linetype. layers: HashMap, - blocks: 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, @@ -1188,7 +1221,7 @@ fn drawing(records: &[Record]) -> Result { 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; + let mut block: Option<(String, Block)> = None; let mut i = 0usize; while let Some(r) = records.get(i) { crate::progress::check()?; @@ -1217,12 +1250,19 @@ fn drawing(records: &[Record]) -> Result { if section == "BLOCKS" { 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 = Some(( + name, + Block { + base: g.pt(10).unwrap_or([0.0; 3]), + entities: Vec::new(), + invalid_z: g.s(30).is_some() && g.f(30).is_none(), + }, + )); block_lost = LostCounts::new(); continue; } if r.kind == "ENDBLK" { - if let Some((name, base, ents)) = block.take() + if let Some((name, body)) = block.take() && !name.is_empty() { // A block defined again replaces the earlier one, and what it couldn't @@ -1233,7 +1273,7 @@ fn drawing(records: &[Record]) -> Result { } else { d.block_lost.insert(key.clone(), std::mem::take(&mut block_lost)); } - d.blocks.insert(key, (base, ents)); + d.blocks.insert(key, body); } continue; } @@ -1304,7 +1344,7 @@ fn drawing(records: &[Record]) -> Result { loss, }; match &mut block { - Some((_, _, ents)) if section == "BLOCKS" => ents.push(e), + Some((_, body)) if section == "BLOCKS" => body.entities.push(e), _ if section == "ENTITIES" => d.entities.push(e), _ => {} } @@ -1323,6 +1363,8 @@ struct Inherit<'a> { color: Option, linetype: Option<&'a str>, block: Option<&'a str>, + /// An unreadable base/insertion height on the path; ignored for unselected or undrawn content. + invalid_z: bool, paper: bool, } @@ -1489,13 +1531,14 @@ fn emit( out.cut += 1; continue; } - let Some((base, inner)) = d.blocks.get(&key) else { + let Some(Block { base, entities: inner, invalid_z }) = d.blocks.get(&key) else { // A dimension without its block: the lines and text it describes. if !ins.fallback.is_empty() { let drawn: Vec = ins .fallback .iter() - .map(|s| Ent { + .enumerate() + .map(|(i, s)| Ent { kind: e.kind, layer: e.layer.clone(), layer_key: e.layer_key.clone(), @@ -1506,7 +1549,7 @@ fn emit( rotation: None, paper: e.paper, shape: s.clone(), - loss: PathLoss::default(), + loss: if i == 0 { e.loss } else { PathLoss::default() }, }) .collect(); emit(d, &drawn, None, xf, from, depth + 1, stack, opts, out)?; @@ -1540,6 +1583,7 @@ fn emit( color: Some(color), linetype: linetype().or(from.linetype), block: Some(ins.block.as_str()), + invalid_z: from.invalid_z || *invalid_z || (e.kind == "INSERT" && e.loss.unreadable_z > 0), paper: from.paper || e.paper, }; let lost = stack.last().and_then(|k| d.block_lost.get(k)); @@ -1576,6 +1620,11 @@ fn emit( let preserves_z = xf.0[2][0] == 0.0 && xf.0[2][1] == 0.0; let tr = |ps: &[P3]| -> Vec { ps.iter().map(|p| xf.apply(*p)).collect() }; let mut loss = e.loss; + if from.invalid_z { + return Err(DataError::Format( + "a placed block has an unreadable supplied Z value; correct its base or insertion height before importing".into(), + )); + } let (geometry, first, target, varying_z) = match &e.shape { Shape::Point(p) => { let p = xf.apply(*p); @@ -1701,7 +1750,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result Result 0 + && let Some((_, report)) = layers.first_mut() + { + let what = if recovered.unreadable_z == 1 { "value" } else { "values" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedZm, + format!("{} unreadable supplied Z {what} could not be kept", recovered.unreadable_z), + )); + } if recovered.unreadable_vertices > 0 && let Some((_, report)) = layers.first_mut() { @@ -1920,7 +1987,7 @@ pub fn layers(file_name: &str, bytes: &[u8]) -> Result> { for e in &d.entities { add(&e.layer, &e.layer_key); } - for (_, ents) in d.blocks.values() { + for Block { entities: ents, .. } in d.blocks.values() { for e in ents.iter().filter(|e| e.layer != "0") { add(&e.layer, &e.layer_key); } @@ -2052,6 +2119,134 @@ mod tests { } } + /// A missing face reference must not turn a four-vertex face into a different triangle. + #[test] + fn loss_coverage_polyface_missing_vertex() { + for bad in [false, true] { + let bytes = dxf(&[ + (0, "SECTION"), + (2, "ENTITIES"), + (0, "POLYLINE"), + (70, "64"), + (0, "VERTEX"), + (70, "64"), + (10, "0"), + (20, "0"), + (0, "VERTEX"), + (70, "64"), + (10, "1"), + (20, "0"), + (0, "VERTEX"), + (70, "64"), + (10, "0"), + (20, "1"), + (0, "VERTEX"), + (70, "128"), + (71, "1"), + (72, "2"), + (73, "3"), + (0, "VERTEX"), + (70, "128"), + (71, "1"), + (72, "2"), + (73, "3"), + (74, if bad { "99" } else { "0" }), + (0, "SEQEND"), + (0, "ENDSEC"), + (0, "EOF"), + ]); + let layers = read("a.dxf", &bytes, &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + let Some(Geometry::Polygon(polys)) = &layers[0].0.features[0].geometry else { panic!("polygon") }; + assert_eq!(polys.iter().map(Vec::len).sum::(), if bad { 1 } else { 2 }); + let notes: Vec<_> = layers[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedRing)).collect(); + assert_eq!(notes.len(), usize::from(bad)); + if bad { + assert_eq!(notes[0].text, "1 polyface face with a missing vertex was left out"); + } + } + } + + /// A supplied unreadable height is distinct from an omitted optional height. + #[test] + fn loss_coverage_unreadable_entity_height() { + for z in [None, Some("0"), Some("bad")] { + let mut pairs = vec![(0, "SECTION"), (2, "ENTITIES"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "1")]; + if let Some(z) = z { + pairs.push((30, z)); + } + pairs.extend([(0, "ENDSEC"), (0, "EOF")]); + let layers = read("a.dxf", &dxf(&pairs), &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(1., 1.)]]))); + let notes: Vec<_> = layers[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedZm)).collect(); + assert_eq!(notes.len(), usize::from(z == Some("bad"))); + if z == Some("bad") { + assert_eq!(notes[0].text, "1 unreadable supplied Z value could not be kept"); + } + } + } + + /// LEADER heights must reach the shared elevation/height-loss reporting, not become zero early. + #[test] + fn leader_and_mline_keep_supplied_height_for_reporting() { + for (kind, x, y, z) in [("LEADER", 10, 20, 30), ("MLINE", 11, 21, 31)] { + let bytes = dxf(&[ + (0, "SECTION"), + (2, "ENTITIES"), + (0, kind), + (x, "0"), + (y, "0"), + (z, "5"), + (x, "1"), + (y, "1"), + (z, "5"), + (0, "ENDSEC"), + (0, "EOF"), + ]); + let layers = read("a.dxf", &bytes, &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(layers[0].0.value(0, 8), &Value::Float(5.0)); + assert!(layers[0].1.messages.is_empty()); + } + } + + /// Only placements which actually draw a selected child validate their base/insertion height. + #[test] + fn malformed_block_heights_are_refused_only_when_used() { + for (base, insert) in [("bad", "0"), ("0", "bad")] { + let text = format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 b 10 0 20 0 30 {base} 0 LINE 8 0 10 0 20 0 11 1 21 1 0 ENDBLK 0 ENDSEC 0 SECTION 2 ENTITIES 0 POINT 8 safe 10 2 20 2 0 INSERT 8 placed 2 b 10 0 20 0 30 {insert} 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let opts = Options { crs: Some(Crs::LonLat), ..Options::default() }; + assert!(read("a.dxf", bytes.as_bytes(), &opts).unwrap_err().to_string().contains("unreadable supplied Z value")); + assert!(layers("a.dxf", bytes.as_bytes()).is_ok()); + assert!(read("a.dxf", bytes.as_bytes(), &Options { blocks: false, ..opts }).is_ok()); + assert!(read("a.dxf", bytes.as_bytes(), &Options { layer: Some("safe"), ..opts }).is_ok()); + } + } + + /// A dimension uses its available block, so unused fallback heights must not refuse it. + #[test] + fn dimension_ignores_unused_fallback_heights() { + let text = "0 SECTION 2 BLOCKS 0 BLOCK 2 b 10 0 20 0 0 LINE 8 0 10 0 20 0 11 1 21 1 0 ENDBLK 0 ENDSEC 0 SECTION 2 ENTITIES 0 DIMENSION 2 b 10 0 20 0 11 1 21 1 31 bad 13 0 23 0 14 2 24 0 0 ENDSEC 0 EOF"; + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(got[0].0.features.len(), 1); + assert!(got[0].1.messages.is_empty()); + // Without the block, its three lines and text point share one source loss. + let fallback = bytes.replace("DIMENSION\n2\nb\n", "DIMENSION\n2\nmissing\n"); + for bad in [false, true] { + let bytes = if bad { fallback.clone() } else { fallback.replace("31\nbad\n", "31\n0\n") }; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(got.iter().map(|(ds, _)| ds.features.len()).sum::(), 4); + let notes: Vec<_> = + got.iter().flat_map(|(_, report)| report.messages.iter()).filter(|n| n.text.contains("unreadable supplied Z")).collect(); + assert_eq!(notes.len(), usize::from(bad)); + if bad { + assert_eq!(notes[0].text, "1 unreadable supplied Z value could not be kept"); + } + } + } + /// Invalid supplied Z is unreadable only on the 3D path; omission still means zero. #[test] fn supplied_invalid_3d_vertex_z_is_omitted_but_optional_z_stays_zero() { diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 64208d69b9..70d24d9340 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -372,7 +372,7 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result = ds.fields.iter().map(|f| f.name.clone()).collect(); assert!(matches!(&ds.features[0].geometry, Some(Geometry::Polygon(_))), "{:?}", ds.features[0].geometry); assert_eq!(report.skipped, 0, "{report:?}"); + assert!(report.messages.iter().all(|n| n.loss == Some(crate::loss::LossCode::DroppedColumn))); (names, report.messages.texts().map(str::to_string).collect::>()) }; // One binary field: the values after it keep their place. diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 68d8e50c76..2064477a9d 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -6520,10 +6520,13 @@ fn csv_guarded_headers_note(fields: &[Field], target: &str) -> Option format!("; 1 of them now has the same header as another field: {}", clashes.join(", ")), n => format!("; {n} of them now have the same header as another field: {}", clashes.join(", ")), }; - Some(crate::loss::Note::plain(format!( - "{target}: CSV prefixed {count} {names} with an apostrophe for spreadsheet protection ({}); {pronoun} back with that prefix{clash}", - guarded.join(", ") - ))) + Some(crate::loss::Note::loss( + crate::loss::LossCode::ChangedFieldName, + format!( + "{target}: CSV prefixed {count} {names} with an apostrophe for spreadsheet protection ({}); {pronoun} back with that prefix{clash}", + guarded.join(", ") + ), + )) } /// Notice for CSV/WKT CSV text cells prefixed with an apostrophe for spreadsheet protection. @@ -6541,9 +6544,10 @@ fn csv_guarded_cells_note(fields: &[Field], guarded: &[usize], target: &str) -> .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) .collect::>() .join(", "); - Some(crate::loss::Note::plain(format!( - "{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}" - ))) + Some(crate::loss::Note::loss( + crate::loss::LossCode::ChangedCsvGuard, + format!("{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}"), + )) } /// As [`export_losses_notes`], for an export written in `crs`. @@ -7311,6 +7315,30 @@ mod tests { use super::*; use std::io::Write; + /// CSV and WKT CSV share header protection, including collisions with an existing guarded name. + #[test] + fn loss_coverage_csv_guard_classification() { + for ext in ["csv", "wkt"] { + let mut ds = Dataset::new("a", GeometryType::None, vec![Field::new("plain", FieldType::Text)]); + ds.push(None, vec![Value::Text("safe".into())]); + assert!(export_losses_notes(&ds, ext, None, "a").unwrap().is_empty()); + ds.fields[0].name = "=x".into(); + ds.features[0].attrs[0] = Value::Text("=SUM(A1)".into()); + ds.fields.push(Field::new("\'=x", FieldType::Text)); + ds.features[0].attrs.push(Value::Text("safe".into())); + let notes = export_losses_notes(&ds, ext, None, "a").unwrap(); + assert_eq!(notes.len(), 2); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::ChangedFieldName)); + assert!(notes[0].text.contains("prefixed 1 field name")); + assert!(notes[0].text.contains("same header as another field")); + assert_eq!(notes[1].loss, Some(crate::loss::LossCode::ChangedCsvGuard)); + assert!(notes[1].text.contains("prefixed 1 text value")); + let written = if ext == "csv" { to_csv(&ds).unwrap() } else { crate::interop::to_wkt_csv(&ds).unwrap() }; + assert!(written.contains("'=x"), "{written}"); + assert!(written.contains("'=SUM(A1)"), "{written}"); + } + } + /// A Shapefile's `.dbf` header holds the day it was written, which `dbase` takes from `time`'s /// clock: std's unless `time`'s `wasm-bindgen` feature is on, and std's clock panics on /// wasm32-unknown-unknown, so every Shapefile export stopped the web app with no message @@ -10131,9 +10159,11 @@ mod tests { ds.push(None, vec![Value::Text("-007".into()), Value::Text("=SUM(A1)".into())]); assert!(to_csv(&ds).unwrap().ends_with("'-007,'=SUM(A1)\n")); assert_eq!( - export_losses_notes(&ds, "csv", None, "tiger.csv").unwrap(), + export_losses_notes(&ds, "csv", None, "tiger.csv").unwrap().texts().collect::>(), ["tiger.csv: CSV prefixed 2 text values with an apostrophe for spreadsheet protection in 'INTPTLAT' (1), 'INTPTLON' (1)"] ); + let notes = export_losses_notes(&ds, "csv", None, "tiger.csv").unwrap(); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::ChangedCsvGuard)); } #[test] diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index b29a8c3042..aa218910b7 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -83,6 +83,18 @@ loss_codes! { "A date-time was written to a date field, which keeps only the day, so the time of day was lost.", "Write to a date-time field to keep the time of day.", ), + DroppedColumn => ( + "dropped.column", + Dropped, + "A column was left out because its type cannot be held, such as binary values or an additional geometry column.", + "Keep the source file; convert the needed columns to supported types or read them with a tool that supports their types." + ), + DroppedCopyright => ( + "dropped.copyright", + Dropped, + "An input raster's copyright differs from the first input's and was not kept in the mosaic.", + "Keep the source credits and include the required attribution when sharing the mosaic." + ), DroppedValue => ( "dropped.value", Dropped, @@ -131,6 +143,12 @@ loss_codes! { "RustGIS read only part of the data because it is past a size limit.", "Read less at once, such as by filtering or clipping the source first, or keep fewer fields (columns) in it." ), + ChangedCsvGuard => ( + "changed.csv-guard", + Changed, + "CSV text was prefixed with an apostrophe to protect against spreadsheet formula execution.", + "Keep the protective prefix when opening CSV in a spreadsheet; use GeoPackage when exact text must be stored without a prefix." + ), ChangedTruncated => ( "changed.truncated", Changed, @@ -140,8 +158,8 @@ loss_codes! { ChangedFieldName => ( "changed.field-name", Changed, - "A field name was changed to fit the format it was written to.", - "Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage." + "A field name was changed to fit the format it was written to, or prefixed with an apostrophe for CSV spreadsheet protection.", + "Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage. For CSV, use names that do not need spreadsheet protection." ), ChangedCut => ( "changed.cut", diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index e43e3c84cb..f214871389 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -12,6 +12,7 @@ use crate::{DataError, Dataset, Field, FieldType, ReadReport, Result}; mod biff; mod ods; +mod xlsb; /// Spreadsheet file types. pub const EXTENSIONS: &[&str] = &["xlsx", "xlsm", "xlsb", "xls", "ods"]; @@ -345,6 +346,7 @@ fn check_expansion(bytes: &[u8]) -> Result { let is_ods = entries .iter() .any(|(name, data)| name.eq_ignore_ascii_case("mimetype") && data.starts_with(b"application/vnd.oasis.opendocument.spreadsheet")); + xlsb::check(&entries)?; for (name, data) in entries { crate::progress::check()?; if is_ods && name.eq_ignore_ascii_case("content.xml") { @@ -739,6 +741,21 @@ mod tests { use super::*; use crate::Value; + /// The independent short-cell fixture must be refused, never imported without attributes. + #[test] + fn loss_coverage_xlsb_short_cells() { + let clean = include_bytes!("../../engine/testdata/reading-losses/book-clean.xlsb"); + let short = include_bytes!("../../engine/testdata/reading-losses/book-short.xlsb"); + let (ds, report) = read(clean, "a", None, &Default::default()).unwrap(); + assert_eq!(ds.fields.len(), 2); + assert_eq!(ds.value(0, 0), &crate::Value::Int(7)); + assert!(report.messages.is_empty()); + let error = read(short, "a", None, &Default::default()).unwrap_err().to_string(); + assert!(error.contains("unsupported XLSB short-cell records"), "{error}"); + assert!(sheet_names(short).unwrap_err().to_string().contains("short-cell")); + assert!(columns(short, None, None).unwrap_err().to_string().contains("short-cell")); + } + #[test] fn dates_and_letters() { assert_eq!(excel_date(45_000.0, false), "2023-03-15"); diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs new file mode 100644 index 0000000000..8c70edd637 --- /dev/null +++ b/crates/data/src/sheets/xlsb.rs @@ -0,0 +1,83 @@ +//! Refuse unsupported short-cell records before the workbook reader can omit attributes. +//! Record framing follows [MS-XLSB] §2.1.4 (not the undocumented short-cell payloads): +//! . + +use crate::{DataError, Result}; + +/// Checks binary worksheet streams before any workbook entry point can omit their cells. +/// A worksheet starts with BrtBeginSheet (129). Inspecting the framing, rather than content-type +/// declarations, also covers a workbook whose declarations are absent or name a different type. +/// This uses existing ZIP buffers, skips payloads without copying and looks at Cancel per record. +/// All worksheet streams are checked, including ones a caller did not select. +pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { + if !entries.iter().any(|(name, _)| name.eq_ignore_ascii_case("xl/workbook.bin")) { + return Ok(()); + } + for (name, data) in entries { + crate::progress::check()?; + if !data.starts_with(&[0x81, 0x01]) { + continue; + } + check_sheet(data).map_err(|e| match e { + DataError::Cancelled => e, + DataError::Unsupported(reason) => DataError::Unsupported(format!("spreadsheet part '{name}': {reason}")), + _ => DataError::Format(format!("spreadsheet part '{name}': {e}")), + })?; + } + Ok(()) +} + +/// Reads a bounded base-128 integer, refusing a truncated or overlong record header. +fn number(data: &mut &[u8], most: usize) -> Result { + let mut value = 0; + for i in 0..most { + let (&byte, rest) = data.split_first().ok_or_else(damaged)?; + *data = rest; + value |= usize::from(byte & 0x7f) << (i * 7); + if byte & 0x80 == 0 { + return Ok(value); + } + } + Err(damaged()) +} + +fn damaged() -> DataError { + DataError::Format("an XLSB record is cut short or has an invalid length".into()) +} + +/// Only record boundaries are interpreted; bytes resembling a record inside cell data are ignored. +fn check_sheet(mut data: &[u8]) -> Result<()> { + while !data.is_empty() { + crate::progress::check()?; + let kind = number(&mut data, 2)?; + let size = number(&mut data, 4)?; + if kind == 146 { + return Ok(()); + } + if (0x0c..=0x12).contains(&kind) { + return Err(DataError::Unsupported( + "unsupported XLSB short-cell records; no data was imported. Save the workbook as XLSX and open that copy".into(), + )); + } + data = data.get(size..).ok_or_else(damaged)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reserved short-cell IDs are refused at record boundaries, never by matching payload bytes. + #[test] + fn framing_does_not_scan_payloads_and_refuses_truncated_headers() { + for kind in 0x0c..=0x12 { + assert!(check_sheet(&[kind, 0]).unwrap_err().to_string().contains("short-cell")); + check_sheet(&[6, 2, kind, 0]).unwrap(); + } + check_sheet(&[0x92, 0x01, 0, 6, 0xff]).unwrap(); + for bytes in [&[0x81][..], &[0x81, 0x80], &[6, 0x80], &[6, 2, 0], &[6, 0xff, 0xff, 0xff, 0xff]] { + assert!(check_sheet(bytes).unwrap_err().to_string().contains("cut short")); + } + } +} diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index ceaca371b4..29d03f4697 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -207,7 +207,7 @@ impl SourceInfo { /// The note of some columns a reader left out, counting them and naming the first 12 with their /// kind ("photo (binary)"): `what` says it for one column, then for several. `None` when there /// are none. -pub(crate) fn columns_note(cols: &[(String, String)], what: [&str; 2]) -> Option { +pub(crate) fn columns_note(cols: &[(String, String)], what: [&str; 2]) -> Option { const NAMED: usize = 12; let [one, several] = what; let n = cols.len(); @@ -218,7 +218,10 @@ pub(crate) fn columns_note(cols: &[(String, String)], what: [&str; 2]) -> Option }; let named: Vec = cols.iter().take(NAMED).map(|(name, kind)| format!("{name} ({kind})")).collect(); let more = if n > NAMED { format!(" and {} more", n - NAMED) } else { String::new() }; - Some(format!("{n} column{} {what}: {}{more}", if n == 1 { "" } else { "s" }, named.join(", "))) + Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedColumn, + format!("{n} column{} {what}: {}{more}", if n == 1 { "" } else { "s" }, named.join(", ")), + )) } /// A read: the features intersecting `extent` (longitude/latitude; `None` = all), at most `limit`. diff --git a/crates/data/src/source/parquet/declared.rs b/crates/data/src/source/parquet/declared.rs index adbb1371da..8a8a9f5172 100644 --- a/crates/data/src/source/parquet/declared.rs +++ b/crates/data/src/source/parquet/declared.rs @@ -799,18 +799,18 @@ mod tests { // A native type over a usual name without one. let s = open(&[("geom", None), ("shape", utm())], UTM, &[]); assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap()); - assert_eq!(notes(&s), [(None, left("geom", "binary"))]); + assert_eq!(notes(&s), [(Some(LossCode::DroppedColumn), left("geom", "binary"))]); // Several: a usual name, else the first, saying which. for (names, read, other) in [(["a", "geom"], "geom", "a"), (["b", "a"], "b", "a")] { let columns = names.map(|n| (n, if n == read { utm() } else { geometry(None) })); let s = open(&columns, UTM, &[]); assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap(), "{names:?}"); let which = format!("it has 2 geometry columns and nothing says which is the main one: '{read}' is read"); - assert_eq!(notes(&s), [(None, which), (None, left(other, "geometry"))]); + assert_eq!(notes(&s), [(None, which), (Some(LossCode::DroppedColumn), left(other, "geometry"))]); } // The metadata's primary column, whatever the others are. let s = open(&[("a", utm()), ("geometry", None)], DEGREES, &[geo("1.0.0", json!({}))]); - assert_eq!((s.coord_crs(), notes(&s)), (Crs::LonLat, vec![(None, left("a", "geometry"))])); + assert_eq!((s.coord_crs(), notes(&s)), (Crs::LonLat, vec![(Some(LossCode::DroppedColumn), left("a", "geometry"))])); // A usual name alone, and none. assert_eq!(notes(&open(&[("the_geom", None)], DEGREES, &[])), []); assert!(ParquetSource::open_bytes(file(&[("shape", None)], DEGREES, &[]), "t").is_err()); diff --git a/crates/data/src/source/sqlserver_gdb.rs b/crates/data/src/source/sqlserver_gdb.rs index 447ccff021..215f0f1506 100644 --- a/crates/data/src/source/sqlserver_gdb.rs +++ b/crates/data/src/source/sqlserver_gdb.rs @@ -390,16 +390,17 @@ fn table_select(reading: &Reading, columns: &[(String, String)], limit: usize) - } /// What to say about the columns a table read leaves out, naming the first few. -fn left_out_note(columns: &[String]) -> Option { +fn left_out_note(columns: &[String]) -> Option { const NAMED: usize = 8; let names = columns.iter().take(NAMED).map(String::as_str).collect::>().join(", "); let more = columns.len().saturating_sub(NAMED); let more = if more > 0 { format!(" and {more} more") } else { String::new() }; - match columns.len() { - 0 => None, - 1 => Some(format!("1 column of a type that isn't read (binary, row version or spatial) is left out: {names}")), - n => Some(format!("{n} columns of a type that isn't read (binary, row version or spatial) are left out: {names}{more}")), - } + let text = match columns.len() { + 0 => return None, + 1 => format!("1 column of a type that isn't read (binary, row version or spatial) is left out: {names}"), + n => format!("{n} columns of a type that isn't read (binary, row version or spatial) are left out: {names}{more}"), + }; + Some(crate::loss::Note::loss(crate::loss::LossCode::DroppedColumn, text)) } /// A registered non-spatial table loaded whole (through its versioned view when versioned), at @@ -781,9 +782,10 @@ mod tests { let (fields, sql, left_out) = table_select(&reading, &columns, 50); assert_eq!(left_out, ["SHAPE", "RAW"]); assert_eq!( - left_out_note(&left_out).as_deref(), + left_out_note(&left_out).as_ref().map(crate::loss::Note::as_str), Some("2 columns of a type that isn't read (binary, row version or spatial) are left out: SHAPE, RAW") ); + assert_eq!(left_out_note(&left_out).unwrap().loss, Some(crate::loss::LossCode::DroppedColumn)); assert_eq!(left_out_note(&[]), None, "a table read whole says nothing"); let many: Vec = (0..10).map(|n| format!("B{n}")).collect(); assert!(left_out_note(&many).is_some_and(|note| note.starts_with("10 columns") && note.ends_with("B7 and 2 more"))); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 5efb02bcff..0e18731245 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4113,6 +4113,7 @@ fn geoparquet_columns_not_kept_or_read_as_numbers_are_said() { // Read in place: the source's notes, which adding the layer gives as notices. let src = open_path(&path, None).unwrap(); let info = src.info(); + assert_eq!(info.notes[0].loss, Some(crate::loss::LossCode::DroppedColumn)); assert_eq!(info.notes.texts().collect::>(), vec![left_out.to_string()]); let names: Vec<&str> = info.fields.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["name", "seen", "logged", "day"]); @@ -4161,6 +4162,7 @@ fn flatgeobuf_binary_columns_are_said_and_left_out() { let note = "1 column of a type RustGIS has no field for was left out: blob (binary)"; let src = open_path(&path, None).unwrap(); assert_eq!(src.info().notes.texts().collect::>(), vec![note.to_string()]); + assert_eq!(src.info().notes[0].loss, Some(crate::loss::LossCode::DroppedColumn)); let names: Vec<&str> = src.info().fields.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["name", "value"]); let (ds, report) = materialize(src.as_ref()).unwrap(); @@ -4195,7 +4197,10 @@ fn geopackage_blob_columns_are_said_and_left_out() { let bytes = Shared(Arc::new(std::fs::read(path).unwrap())); let mem = gpkg_mem::GpkgMemSource::open_shared(bytes, None).unwrap(); let sql = open_path(path, None).unwrap(); - let said = |s: &dyn FeatureSource| s.info().notes.texts().map(str::to_string).collect::>(); + let said = |s: &dyn FeatureSource| { + assert!(s.info().notes.iter().all(|n| n.loss == Some(crate::loss::LossCode::DroppedColumn))); + s.info().notes.texts().map(str::to_string).collect::>() + }; assert_eq!(said(&mem), said(sql.as_ref()), "the browser's reader says what the desktop's does"); let fields: Vec = sql.info().fields.iter().map(|f| f.name.clone()).collect(); assert_eq!(mem.info().fields, sql.info().fields); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 3cf5643a5a..c3f3598b60 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -2447,7 +2447,7 @@ impl Tiles { /// The mosaic, named `given` or after its first input; what it has to say goes to `notes`. Its /// inputs' rows are counted, each band's, and Cancel is looked at about every [`MOSAIC_PIECE`] /// cells copied; measuring the result ([`Raster::new`]'s statistics) doesn't look. - fn join(self, given: String, notes: &mut Notes) -> Result { + fn join(self, given: String, notes: &mut Notes, losses: &mut Vec) -> Result { let Tiles { rs, places, from: (c0, r0), to: (c1, r1), .. } = self; let first = rs.first().ok_or("a mosaic needs two or more rasters")?; let (w, h) = (c1 - c0, r1 - r0); @@ -2519,11 +2519,14 @@ impl Tiles { .map(|r| { ( r.name.clone(), - rustgis_data::loss::Note::plain("its copyright differs from the first input's and is not kept in the mosaic"), + rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedCopyright, + "its copyright differs from the first input's and is not kept in the mosaic", + ), ) }) .collect(); - notes.extend(super::raster::loss_lines(credits).into_iter().map(|n| (n.text, false))); + losses.extend(super::raster::loss_lines(credits)); // Cells rounded when an input was read may be among those the mosaic keeps. out.keep_rounded_marks(rs.iter().map(|r| &**r)); let other: Vec<&str> = @@ -2604,12 +2607,13 @@ pub(crate) fn mosaic_rasters_work(s: &Session, p: &Value) -> Result, Vec<_>) = super::raster::loss_lines(lost).into_iter().partition(|n| n.loss.is_some()); + let (mut coded, plain): (Vec<_>, Vec<_>) = super::raster::loss_lines(lost).into_iter().partition(|n| n.loss.is_some()); let mut notes: Notes = plain.into_iter().map(|n| (n.text, false)).collect(); - let coded_said: Vec = coded.iter().map(|n| n.text.clone()).collect(); + let mut coded_said: Vec = coded.iter().map(|n| n.text.clone()).collect(); let made = (|| -> Result { // The inputs are let go of once joined, before the file is written. - let out = tiles.join(given, &mut notes)?; + let out = tiles.join(given, &mut notes, &mut coded)?; + coded_said = coded.iter().map(|n| n.text.clone()).collect(); let name = out.name.clone(); // Written beside it, the file is put in its place as the layer is added: a run cancelled // before then leaves the file there as it was. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d5e17b9e72..ede78ddcdc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33226,7 +33226,9 @@ fn raster_export_paths_report_band_class_and_credit_changes() { let mark = s.notice_mark(); let out = s.run("raster.mosaic", &json!({"inputs": ["Metadata", second], "name": "rights"})).unwrap(); assert_eq!(out_raster(&s, &out).copyright.as_deref(), Some("© Owner")); - assert_eq!(s.notices_since(mark).iter().any(|n| n.text.contains("copyright differs")), changed, "{:?}", s.notices_since(mark)); + let credits: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("copyright differs")).collect(); + assert_eq!(credits.len(), usize::from(changed)); + assert!(credits.iter().all(|n| n.loss == Some(rustgis_data::loss::LossCode::DroppedCopyright))); } std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/testdata/reading-losses/README.md b/crates/engine/testdata/reading-losses/README.md index 80be65ca31..0405edb685 100644 --- a/crates/engine/testdata/reading-losses/README.md +++ b/crates/engine/testdata/reading-losses/README.md @@ -115,24 +115,24 @@ headers, WKT and numeric ID. This check uses a parser independent of RustGIS. No macros, formulas or external links are included. The original SheetJS 0.18.5 short-cell worksheet, retained in `book-short.xlsb`, -pins a known reader gap: native -`sheets::read` retains `POINT(1 2)` but returns no attribute fields or values, -including the source `id=7`, with zero skipped rows and no messages. Its short -cell records are paired with the full-record `book-clean.xlsb`; both native and -command imports must retain exactly the point with no attribute fields/values or notices. +pins an unsupported record layout. Previously its point survived but all attributes disappeared. +The workbook is now refused before import, column discovery or sheet-name listing, with a +message to save it as XLSX. The full-record `book-clean.xlsb` still imports without a notice. | Files (`.xls` and `.xlsb` unless stated) | WKT | Current loss classification | | --- | --- | --- | | `book-clean` | `POINT(1 2)` | None; no native or command notice | | `book-z` | `POINT Z(1 2 3)` | Imports with a Z/M-loss notice | | `book-collection` | `GEOMETRYCOLLECTION(POINT(1 2),POINT(3 4))` | Imported: one WKT value loses later non-empty members; the first remains | -| `book-short.xlsb` (paired with `book-clean.xlsb`) | `POINT(1 2)` | Silent: all attribute fields and values are lost | +| `book-short.xlsb` (paired with `book-clean.xlsb`) | `POINT(1 2)` | Refused: unsupported XLSB short-cell records | The height/member pairs must retain exactly one point at (1, 2), integer `id=7`, text `note=Null` and both field names/types, through `sheets::read` and `layer.addData`. Native checks require zero skipped rows, the expected height flag and exactly one Z/M message for the height variant (none otherwise). Valid lossy fixtures must import. Dates, error cells, other sheets and broader type/encoding fidelity are not certified. +Known XLSB losses beyond the short-cell refusal are cached formula errors (`BrtFmlaError`) +and rich inline strings (`BrtCellRString`), which the workbook reader currently skips silently. ## Feature-service PBF @@ -215,7 +215,7 @@ but not covered here, not necessarily a known bug. CRS assumptions remain separa | LAS/LAZ | None in this paired corpus | Sampling, dimensions/attributes; geometry members/holes inapplicable | | XLSX | WKT Z/members, error-valued attribute | M, other geometry, dates/formulas/names/encoding | | ODS / XLS (distinct workbook parsers) | WKT Z/members in each | M, other geometry, dates/errors/names/encoding | -| XLSB | WKT Z/members with full cell records; short-cell attribute loss | Pinned silent short-cell loss; M, other geometry, dates/errors/names/encoding remain gaps | +| XLSB | WKT Z/members with full cell records; short-cell attribute loss | Pinned short-cell refusal; M, other geometry, dates/errors/names/encoding remain gaps | | XLSM | Shared XLSX OOXML implementation only | No distinct fixture; macros and macro fidelity untested | | Generic ZIP | Delegates to inner readers; KMZ covered above | Other wrapper parity | diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index d177290642..858e63e5b1 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -6,9 +6,8 @@ //! that says the loss (holds the case's words), or be refused saying it. Notices both give (a DXF //! drawing without a coordinate system, say) cancel out, so a case asks only about its loss. //! -//! Losses no reader says yet are listed as [`Expect::Silent`] with what is lost. They are the -//! roadmap's known silent losses (ROADMAP.md › Correct results); a reader that starts saying one -//! fails here until the case is moved to [`Expect::Said`], so the list only shrinks. Exports have +//! Each pinned loss is imported with a notice or refused with an explanation. The roadmap +//! lists other known losses and coverage gaps; this corpus does not certify completeness. Exports have //! their own test, `never_silent_roundtrip.rs`; `read_routes.rs` reads these files by every route. //! //! The table includes text, CityJSON, CityGML, KMZ, GeoPackage, FlatGeobuf, GeoParquet, FileGDB, @@ -27,10 +26,8 @@ enum Expect { Imported(&'static str), /// Imports successfully and identifies the loss with a code, in a notice holding these words. Classified(LossCode, &'static str), - /// Loses it without a notice today, still adding a layer: what is lost. - Silent(&'static str), } -use Expect::{Imported, Said, Silent}; +use Expect::{Imported, Said}; /// Independent dBASE III table: one text field and one date, with no encoding ambiguity. /// Only the date changes: a valid February day or a nonexistent one, read as Null. @@ -536,6 +533,17 @@ pub(super) fn cases(fixture_dir: &std::path::Path) -> Vec { ), ]; + out.extend([ + case("DXF: an unreadable supplied height", "a.dxf", + dxf(&["0 LINE 10 0 20 0 30 0 11 1 21 1"]), + dxf(&["0 LINE 10 0 20 0 30 bad 11 1 21 1"]), + Expect::Classified(LossCode::DroppedZm, "1 unreadable supplied Z value could not be kept")), + case("DXF: a polyface face with a missing vertex", "a.dxf", + dxf(&["0 POLYLINE 70 64 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 0 VERTEX 70 128 71 1 72 2 73 3 0 VERTEX 70 128 71 1 72 2 73 3 74 0 0 SEQEND"]), + dxf(&["0 POLYLINE 70 64 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 0 VERTEX 70 128 71 1 72 2 73 3 0 VERTEX 70 128 71 1 72 2 73 3 74 99 0 SEQEND"]), + Expect::Classified(LossCode::DroppedRing, "1 polyface face with a missing vertex was left out")), + ]); + out.extend([ case( "XLSX: a height in WKT", @@ -604,7 +612,7 @@ pub(super) fn cases(fixture_dir: &std::path::Path) -> Vec { "a.xlsb", include_bytes!("../../testdata/reading-losses/book-clean.xlsb"), include_bytes!("../../testdata/reading-losses/book-short.xlsb"), - Silent("the point remains but all attribute fields and values are lost"), + Said("unsupported XLSB short-cell records"), ), case( "XLSB: a WKT geometry collection's later members", @@ -810,13 +818,12 @@ fn check_shapefile_xy(ds: &rustgis_engine::data::Dataset, shape_type: Option Ok(()) } -/// Workbooks retain the point and two attributes except the pinned XLSB short-cell loss, -/// which retains the point but drops every attribute field and value. -fn check_workbook(ds: &rustgis_engine::data::Dataset, short_cells: bool) -> std::io::Result<()> { +/// Workbooks which import retain the point and two attributes; unsupported short cells are refused. +fn check_workbook(ds: &rustgis_engine::data::Dataset) -> std::io::Result<()> { use rustgis_engine::data::{Field, FieldType, Geometry, Value}; use rustgis_engine::geom::Coord; - let fields = if short_cells { vec![] } else { vec![Field::new("id", FieldType::Integer), Field::new("note", FieldType::Text)] }; - let attrs = if short_cells { vec![] } else { vec![Value::Int(7), Value::Null] }; + let fields = vec![Field::new("id", FieldType::Integer), Field::new("note", FieldType::Text)]; + let attrs = vec![Value::Int(7), Value::Null]; if ds.fields != fields || ds.features.len() != 1 || ds.features[0].geometry != Some(Geometry::Point(Coord::new(1.0, 2.0))) @@ -1000,10 +1007,10 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< return Err(std::io::Error::other("native Shapefile fixture skipped a record")); } } - if rustgis_engine::data::sheets::is_sheet_name(file) { + if rustgis_engine::data::sheets::is_sheet_name(file) && !short_cells { let (native, report) = rustgis_engine::data::sheets::read(content, "a", None, &Default::default()) .map_err(|e| std::io::Error::other(format!("native spreadsheet fixture: {e}")))?; - check_workbook(&native, short_cells)?; + check_workbook(&native)?; let height = content == include_bytes!("../../testdata/reading-losses/book-z.xlsx") || content == include_bytes!("../../testdata/reading-losses/book-z.ods") || content == include_bytes!("../../testdata/reading-losses/book-z.xls") @@ -1112,7 +1119,7 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< if s.map().layers.len() != 1 || !s.project.tables.is_empty() { return Err(std::io::Error::other("spreadsheet fixture didn't add exactly one layer")); } - check_workbook(&s.map().layers[0].dataset, short_cells)?; + check_workbook(&s.map().layers[0].dataset)?; if (content == include_bytes!("../../testdata/reading-losses/book-clean.xlsx") || content == include_bytes!("../../testdata/reading-losses/book-clean.ods") || content == include_bytes!("../../testdata/reading-losses/book-clean.xls") @@ -1232,18 +1239,10 @@ fn a_reading_that_loses_something_says_so() { Said(words) | Imported(words) if clean.iter().any(|(text, _)| text.contains(words)) => { failures.push(format!("{name}: the clean file says the loss it doesn't have ({words:?}): {clean:?}")) } - Imported(_) if !added => { - failures.push(format!("{name}: the valid lossy fixture was refused instead of imported: {new:?}")) - } + Imported(_) if !added => failures.push(format!("{name}: the valid lossy fixture was refused instead of imported: {new:?}")), Said(words) | Imported(words) if !new.iter().any(|(text, _)| text.contains(words)) => { failures.push(format!("{name}: not said: nothing new holds {words:?}; new: {new:?}; the clean file said {clean:?}")) } - Silent(lost) if !new.is_empty() => failures.push(format!( - "{name}: a new notice ({new:?}): if it says that {lost}, make the case Said; if not, change the lossy file so it gives only that loss" - )), - Silent(lost) if !added => { - failures.push(format!("{name}: the lossy file added no layer and said nothing, more than this case's loss ({lost})")) - } _ => {} } } @@ -1323,3 +1322,19 @@ fn dxf_code(message: &str) -> Option { None } } + +/// ZIP layer picking must retain drawing-wide unreadable heights beside the per-layer varying-Z note. +#[test] +fn zip_layer_pick_keeps_unreadable_z_notice() { + use base64::Engine; + let text = dxf(&["0 LINE 8 0 10 0 20 0 30 1 11 1 21 1 31 2", "0 3DFACE 8 0 10 0 20 0 30 bad 11 1 21 0 12 0 22 1"]); + let bytes = rustgis_engine::data::zip::write(&[("drawing.dxf".into(), text.into_bytes())]).unwrap(); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("layer.addDataBytes", &json!({"fileName":"drawing.zip", "data":base64::engine::general_purpose::STANDARD.encode(bytes), "layer":"polygons", "crs":"EPSG:4326"})).unwrap(); + assert_eq!(s.map().layers.len(), 1); + assert!(matches!(s.map().layers[0].dataset.features[0].geometry, Some(rustgis_engine::data::Geometry::Polygon(_)))); + let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("unreadable supplied Z")).collect(); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].loss(), Some(LossCode::DroppedZm)); +} diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index cfcae733db..32ccfe70a1 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -28,7 +28,7 @@ A map service offered legend pictures that RustGIS does not show, so they were l A polygon ring was left out. Rings that could not be read, or that have no area, are skipped, and a format with no holes keeps only the outer edge of each polygon. -**Where you see it:** reading GeoRSS, GML or MapInfo data, or feature service answers in PBF; exporting polygons to GPX (their holes are left out). +**Where you see it:** reading GeoRSS, GML, DXF or MapInfo data, or feature service answers in PBF; exporting polygons to GPX (their holes are left out). **What to do:** Correct the unreadable polygon ring in the source, or write to a format that holds holes, such as GeoPackage. @@ -48,6 +48,22 @@ A date-time was written to a date field, which keeps only the day, so the time o **What to do:** Write to a date-time field to keep the time of day. +### `dropped.column` { #dropped.column } + +A column was left out because its type cannot be held, such as binary values or an additional geometry column. + +**Where you see it:** reading FileGDB, GeoPackage, FlatGeobuf or GeoParquet data, or a SQL Server geodatabase table. + +**What to do:** Keep the source file; convert the needed columns to supported types or read them with a tool that supports their types. + +### `dropped.copyright` { #dropped.copyright } + +An input raster's copyright differs from the first input's and was not kept in the mosaic. + +**Where you see it:** Mosaic Rasters. + +**What to do:** Keep the source credits and include the required attribution when sharing the mosaic. + ### `dropped.value` { #dropped.value } A value could not be kept and was read or written as empty (null). Examples are spreadsheet error cells, text in a date or yes/no column, and a result that is not a number. @@ -68,7 +84,7 @@ A calculation gave no result for some rows, so the field was left empty there. T Z (height) or M (measure) values were not kept. RustGIS keeps x and y only. -**Where you see it:** reading KML, CSV or WKT, or a table read through DuckDB or GDAL; exporting a layer whose Z or M values were dropped when it was read. +**Where you see it:** reading KML, CSV, WKT or DXF, or a table read through DuckDB or GDAL; exporting a layer whose Z or M values were dropped when it was read. **What to do:** Keep the source file where heights or measures matter: RustGIS keeps x and y only. @@ -116,6 +132,14 @@ RustGIS read only part of the data because it is past a size limit. Changed means data is still there but was altered, such as cut short or rounded. +### `changed.csv-guard` { #changed.csv-guard } + +CSV text was prefixed with an apostrophe to protect against spreadsheet formula execution. + +**Where you see it:** exporting CSV or WKT CSV. The CSV contains the prefix; RustGIS removes a recognized formula guard when reading the text back. + +**What to do:** Keep the protective prefix when opening CSV in a spreadsheet; use GeoPackage when exact text must be stored without a prefix. + ### `changed.truncated` { #changed.truncated } A number lost its fractional part because the field holds whole numbers. @@ -126,11 +150,11 @@ A number lost its fractional part because the field holds whole numbers. ### `changed.field-name` { #changed.field-name } -A field name was changed to fit the format it was written to. +A field name was changed to fit the format it was written to, or prefixed with an apostrophe for CSV spreadsheet protection. -**Where you see it:** exporting to Shapefile or GeoPackage. +**Where you see it:** exporting to Shapefile, GeoPackage, CSV or WKT CSV. -**What to do:** Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage. +**What to do:** Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage. For CSV, use names that do not need spreadsheet protection. ### `changed.cut` { #changed.cut } @@ -210,7 +234,7 @@ data. The file does not say which coordinate system its coordinates are in, or says one RustGIS cannot use, so RustGIS read them as longitude and latitude (WGS 84). -**Where you see it:** reading a Shapefile with an unusable .prj file, GeoPackage, GeoParquet, PostGIS or SQL Server data, Zarr stores and point-cloud files. +**Where you see it:** XY Table To Point; reading a Shapefile with an unusable .prj file, GeoPackage, GeoParquet, PostGIS or SQL Server data, Zarr stores and point-cloud files. **What to do:** Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). From 0587add33b06a5b208e1303cd1825cd9822af134 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 20:02:24 -0600 Subject: [PATCH 02/16] fix(data): validate consumed DXF heights and XLSB framing --- crates/data/src/dxf.rs | 123 +++++++++++++++++++++++++-------- crates/data/src/sheets/xlsb.rs | 28 +++++++- 2 files changed, 118 insertions(+), 33 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 9b3cae23c2..03238b4a48 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -658,19 +658,23 @@ fn plain_text(s: &str) -> String { out.split_whitespace().collect::>().join(" ") } +/// Reads a coordinate selected by the entity's representation, counting an unreadable supplied +/// height only when its XY point is usable. An omitted optional Z is the format's zero, not a loss. +fn used_point(g: &G, x: i32, loss: &mut PathLoss) -> Option { + let point = g.pt(x)?; + loss.unreadable_z += u64::from(g.s(x + 20).is_some() && g.f(x + 20).is_none()); + Some(point) +} + /// Reads one record as an entity (POLYLINE with its VERTEX records). `None` when it can't be read. /// Cancellation also stops the Option-based builders; the caller checks and propagates it. fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) -> Option { let ocs = Xf::ocs(g.extrusion()); - if !(kind == "POLYLINE" && g.i(70).unwrap_or(0) & (8 | 64) != 0) { - loss.unreadable_z += - g.p.iter().filter(|(c, v)| (if kind == "INSERT" { *c == 30 } else { (30..=38).contains(c) }) && num(v).is_none()).count() - as u64; - } Some(match kind { - "POINT" => Shape::Point(g.pt(10)?), - "LINE" => Shape::line(vec![g.pt(10)?, g.pt(11)?]), + "POINT" => Shape::Point(used_point(g, 10, loss)?), + "LINE" => Shape::line(vec![used_point(g, 10, loss)?, used_point(g, 11, loss)?]), "LWPOLYLINE" => { + loss.unreadable_z += u64::from(g.s(38).is_some() && g.f(38).is_none()); let z = g.f(38).unwrap_or(0.0); let mut vs: Vec<(P3, f64)> = Vec::new(); let mut tail = false; @@ -712,7 +716,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - return None; } let three_d = flags & 8 != 0; - let z = g.pt(10).map(|p| p[2]).unwrap_or(0.0); + let z = if three_d { 0.0 } else { used_point(g, 10, loss).map(|p| p[2]).unwrap_or(0.0) }; let curved = flags & 6 != 0; let mut vs = Vec::new(); for (index, v) in vertices.iter().enumerate() { @@ -747,11 +751,11 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - Shape::line(if three_d { pts } else { pts.into_iter().map(|p| ocs.apply(p)).collect() }) } "CIRCLE" => { - let (c, r) = (g.pt(10)?, g.f(40)?); + let (c, r) = (used_point(g, 10, loss)?, g.f(40)?); Shape::line(arc([c[0], c[1]], r, 0.0, TAU, c[2]).into_iter().map(|p| ocs.apply(p)).collect()) } "ARC" => { - let (c, r) = (g.pt(10)?, g.f(40)?); + let (c, r) = (used_point(g, 10, loss)?, g.f(40)?); let (s, e) = (g.f(50).unwrap_or(0.0), g.f(51).unwrap_or(360.0)); Shape::line( arc([c[0], c[1]], r, s.rem_euclid(360.0).to_radians(), sweep(s, e, 360.0).to_radians(), c[2]) @@ -761,7 +765,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - ) } "ELLIPSE" => { - let (c, major) = (g.pt(10)?, g.pt(11)?); + let (c, major) = (used_point(g, 10, loss)?, used_point(g, 11, loss)?); let ratio = g.f(40).unwrap_or(1.0); let minor = cross(unit(g.extrusion()), major).map(|v| v * ratio); let s = g.f(41).unwrap_or(0.0).rem_euclid(TAU); @@ -838,7 +842,9 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - Some((20, y)) => num(y)?, _ => return None, }; - let z = it.clone().nth(1).filter(|(c, _)| *c == 30).and_then(|(_, z)| num(z)).unwrap_or(0.0); + let supplied = it.clone().nth(1).filter(|(c, _)| *c == 30).map(|(_, z)| z); + loss.unreadable_z += u64::from(supplied.is_some_and(|z| num(z).is_none())); + let z = supplied.and_then(|z| num(z)).unwrap_or(0.0); pts.push([x, y, z]); } } @@ -850,15 +856,15 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - // length). let vertical = if kind == "TEXT" { g.i(73) } else { g.i(74) }; let justified = g.i(72).unwrap_or(0) != 0 || vertical.unwrap_or(0) != 0; - let p = if justified { g.pt(11).or_else(|| g.pt(10))? } else { g.pt(10)? }; + let p = if justified { used_point(g, 11, loss).or_else(|| used_point(g, 10, loss))? } else { used_point(g, 10, loss)? }; Shape::Point(ocs.apply(p)) } - "MTEXT" => Shape::Point(g.pt(10)?), + "MTEXT" => Shape::Point(used_point(g, 10, loss)?), "SOLID" | "TRACE" => { - let (a, b, c) = (g.pt(10)?, g.pt(11)?, g.pt(12)?); + let (a, b, c) = (used_point(g, 10, loss)?, used_point(g, 11, loss)?, used_point(g, 12, loss)?); // A solid's corners zigzag: 1, 2, then 4 and 3. let mut ring = vec![a, b]; - match g.pt(13) { + match used_point(g, 13, loss) { Some(d) if d != c => ring.extend([d, c]), _ => ring.push(c), } @@ -866,9 +872,9 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - Shape::Polygon(ring.into_iter().map(|p| ocs.apply(p)).collect()) } "3DFACE" => { - let (a, b, c) = (g.pt(10)?, g.pt(11)?, g.pt(12)?); + let (a, b, c) = (used_point(g, 10, loss)?, used_point(g, 11, loss)?, used_point(g, 12, loss)?); let mut ring = vec![a, b, c]; - if let Some(d) = g.pt(13).filter(|d| *d != c) { + if let Some(d) = used_point(g, 13, loss).filter(|d| *d != c) { ring.push(d); } ring.push(a); @@ -880,7 +886,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - }, "INSERT" => Shape::Insert(Insert { block: g.s(2)?.trim().to_string(), - at: g.pt(10).unwrap_or([0.0; 3]), + at: used_point(g, 10, loss).unwrap_or([0.0; 3]), scale: [g.f(41).unwrap_or(1.0), g.f(42).unwrap_or(1.0), g.f(43).unwrap_or(1.0)], rotation: g.f(50).unwrap_or(0.0), extrusion: g.extrusion(), @@ -893,7 +899,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - }), // A dimension draws its (anonymous) block, already placed in the drawing's coordinates. "DIMENSION" => { - let (fallback, fallback_text) = dimension(g); + let (fallback, fallback_text) = dimension(g, loss); Shape::Insert(Insert { block: g.s(2).map(str::trim).unwrap_or("").to_string(), at: [0.0; 3], @@ -919,7 +925,9 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - Some((21, y)) => num(y)?, _ => return None, }; - let z = it.clone().nth(1).filter(|(c, _)| *c == 31).and_then(|(_, z)| num(z)).unwrap_or(0.0); + let supplied = it.clone().nth(1).filter(|(c, _)| *c == 31).map(|(_, z)| z); + loss.unreadable_z += u64::from(supplied.is_some_and(|z| num(z).is_none())); + let z = supplied.and_then(|z| num(z)).unwrap_or(0.0); pts.push([x, y, z]); } } @@ -937,9 +945,11 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - /// What a linear dimension (rotated or aligned, types 0 and 1) draws: its dimension line through /// point 10, extension lines from the measured points 13 and 14, and its text at point 11 (the /// text given, else the length measured). Other dimensions draw nothing without their block. -fn dimension(g: &G) -> (Vec, Option) { +fn dimension(g: &G, loss: &mut PathLoss) -> (Vec, Option) { let kind = g.i(70).unwrap_or(0) & 7; - let (Some(p10), Some(p13), Some(p14)) = (g.pt(10), g.pt(13), g.pt(14)) else { return (Vec::new(), None) }; + let (Some(p10), Some(p13), Some(p14)) = (used_point(g, 10, loss), used_point(g, 13, loss), used_point(g, 14, loss)) else { + return (Vec::new(), None); + }; if kind > 1 { return (Vec::new(), None); } @@ -967,7 +977,7 @@ fn dimension(g: &G) -> (Vec, Option) { _ => measure(length), }; let mut shapes = vec![Shape::line(vec![a, b]), Shape::line(vec![p13, a]), Shape::line(vec![p14, b])]; - if let Some(t) = g.pt(11) { + if let Some(t) = used_point(g, 11, loss) { shapes.push(Shape::Point(t)); } (shapes, Some(text)) @@ -1062,7 +1072,7 @@ impl Cursor<'_, '_> { /// A HATCH's boundary paths as rings (polyline paths with bulges, or edges: lines, arcs, elliptic /// arcs and splines), in its object coordinates at its elevation. fn hatch(g: &G, loss: &mut PathLoss) -> Option>> { - let z = g.pt(10).map(|p| p[2]).unwrap_or(0.0); + let z = used_point(g, 10, loss).map(|p| p[2]).unwrap_or(0.0); let mut cur = Cursor { p: g.p, at: 0 }; let paths = cur.count(91)?; let mut rings: Vec> = Vec::new(); @@ -1620,11 +1630,6 @@ fn emit( let preserves_z = xf.0[2][0] == 0.0 && xf.0[2][1] == 0.0; let tr = |ps: &[P3]| -> Vec { ps.iter().map(|p| xf.apply(*p)).collect() }; let mut loss = e.loss; - if from.invalid_z { - return Err(DataError::Format( - "a placed block has an unreadable supplied Z value; correct its base or insertion height before importing".into(), - )); - } let (geometry, first, target, varying_z) = match &e.shape { Shape::Point(p) => { let p = xf.apply(*p); @@ -1682,6 +1687,11 @@ fn emit( out.cut += 1; continue; }; + if from.invalid_z { + return Err(DataError::Format( + "a placed block has an unreadable supplied Z value; correct its base or insertion height before importing".into(), + )); + } let attrs = vec![ Value::Text(layer.to_string()), Value::Text(e.kind.to_string()), @@ -2247,6 +2257,59 @@ mod tests { } } + /// Unused alignment coordinates are not losses; selected unreadable heights still are. + #[test] + fn selected_text_heights_only_report_consumed_values() { + for kind in ["TEXT", "ATTRIB", "ATTDEF"] { + for (alignment, first_z, second_z, lost) in + [("0", "0", "bad", false), ("1", "bad", "0", false), ("0", "bad", "0", true), ("1", "0", "bad", true)] + { + let bytes = dxf(&[ + (0, "SECTION"), + (2, "ENTITIES"), + (0, kind), + (70, "2"), + (1, "a"), + (72, alignment), + (10, "1"), + (20, "2"), + (30, first_z), + (11, "3"), + (21, "4"), + (31, second_z), + (0, "ENDSEC"), + (0, "EOF"), + ]); + let got = read("a.dxf", &bytes, &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + let point = if alignment == "0" { Coord::new(1.0, 2.0) } else { Coord::new(3.0, 4.0) }; + assert_eq!(got[0].0.features[0].geometry, Some(Geometry::Point(point)), "{kind}"); + assert_eq!(got[0].0.value(0, 8), &Value::Float(0.0)); + let notes: Vec<_> = got[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedZm)).collect(); + assert_eq!(notes.len(), usize::from(lost), "{kind} {alignment} {first_z} {second_z}"); + if lost { + assert_eq!(notes[0].text, "1 unreadable supplied Z value could not be kept"); + } + } + } + } + + /// A rejected child must not turn its unused block height into a drawing-wide refusal. + #[test] + fn rejected_block_children_do_not_validate_unused_heights() { + for z in ["0", "bad"] { + let text = format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 b 10 0 20 0 30 {z} 0 LEADER 8 0 10 0 20 0 0 ENDBLK 0 ENDSEC 0 SECTION 2 ENTITIES 0 POINT 8 safe 10 2 20 2 0 INSERT 8 placed 2 b 10 0 20 0 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].0.features.len(), 1); + assert_eq!(got[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(2.0, 2.0)))); + assert_eq!(got[0].1.skipped, 1); + assert!(!got[0].1.messages.iter().any(|n| n.loss == Some(crate::loss::LossCode::DroppedZm))); + } + } + /// Invalid supplied Z is unreadable only on the 3D path; omission still means zero. #[test] fn supplied_invalid_3d_vertex_z_is_omitted_but_optional_z_stays_zero() { diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index 8c70edd637..2639a24234 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -27,14 +27,15 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { Ok(()) } -/// Reads a bounded base-128 integer, refusing a truncated or overlong record header. +/// Reads the bounded base-128 type or size field. The final byte contributes only its low seven +/// bits; the size field's fourth-byte high bit is ignored (MS-XLSB 2.1.4), not a fifth-byte marker. fn number(data: &mut &[u8], most: usize) -> Result { let mut value = 0; for i in 0..most { let (&byte, rest) = data.split_first().ok_or_else(damaged)?; *data = rest; value |= usize::from(byte & 0x7f) << (i * 7); - if byte & 0x80 == 0 { + if byte & 0x80 == 0 || i + 1 == most { return Ok(value); } } @@ -54,6 +55,8 @@ fn check_sheet(mut data: &[u8]) -> Result<()> { if kind == 146 { return Ok(()); } + // calamine 0.38 skips these short-cell encodings without yielding their values. + // Refuse this unsupported layout even when the workbook itself is valid. if (0x0c..=0x12).contains(&kind) { return Err(DataError::Unsupported( "unsupported XLSB short-cell records; no data was imported. Save the workbook as XLSX and open that copy".into(), @@ -68,7 +71,26 @@ fn check_sheet(mut data: &[u8]) -> Result<()> { mod tests { use super::*; - /// Reserved short-cell IDs are refused at record boundaries, never by matching payload bytes. + /// MS-XLSB 2.1.4 ignores the last size byte's high bit; both encodings retain the workbook. + #[test] + fn four_byte_record_sizes_ignore_the_last_high_bit() { + let clean = include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb"); + for last in [0, 0x80] { + let mut entries = crate::zip::read(clean).unwrap(); + let sheet = &mut entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + let at = sheet.windows(3).position(|b| b == [0x91, 0x01, 0]).unwrap(); + sheet.splice(at + 2..at + 3, [0x80, 0x80, 0x80, last]); + let bytes = crate::zip::write(&entries).unwrap(); + let (ds, report) = crate::sheets::read(&bytes, "a", None, &Default::default()).unwrap(); + assert_eq!(ds.fields, [crate::Field::new("id", crate::FieldType::Integer), crate::Field::new("note", crate::FieldType::Text)]); + assert_eq!(ds.features.len(), 1); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert_eq!(ds.features[0].geometry, Some(crate::Geometry::Point(rustgis_geom::Coord::new(1.0, 2.0)))); + assert!(report.messages.is_empty()); + } + } + + /// Unsupported short-cell IDs are refused at record boundaries, never by matching payload bytes. #[test] fn framing_does_not_scan_payloads_and_refuses_truncated_headers() { for kind in 0x0c..=0x12 { From fcc5ced8e4576e4f364cc34feec1448138ce7029 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 20:53:25 -0600 Subject: [PATCH 03/16] fix(data): group DXF losses and distinguish unreadable heights --- crates/data/src/dxf.rs | 76 +++++++++++++++++-- crates/data/src/io.rs | 2 +- crates/data/src/loss.rs | 6 ++ .../tests/integration/never_silent_reading.rs | 5 +- docs/user-guide/loss-codes.md | 8 ++ 5 files changed, 88 insertions(+), 9 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 03238b4a48..b7481c6c12 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1933,14 +1933,12 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 && let Some((_, report)) = layers.first_mut() { let what = if recovered.unreadable_z == 1 { "value" } else { "values" }; report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedZm, + crate::loss::LossCode::DroppedUnreadableZ, format!("{} unreadable supplied Z {what} could not be kept", recovered.unreadable_z), )); } @@ -1967,6 +1965,22 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result format!("{file_name}: nothing RustGIS draws"), })); } + // DXF diagnostics count each cause in their own units. Keep those counts together when + // several causes share a code, instead of issuing several notices of the same kind. + for (_, report) in &mut layers { + let mut grouped: Vec = Vec::new(); + for note in std::mem::take(&mut report.messages) { + if let Some(code) = note.loss + && let Some(previous) = grouped.iter_mut().find(|n| n.loss == Some(code)) + { + previous.text.push_str("; "); + previous.text.push_str(¬e.text); + } else { + grouped.push(note); + } + } + report.messages = grouped.into(); + } Ok(layers) } @@ -2176,6 +2190,49 @@ mod tests { } } + /// Mixed causes keep their own counts, with one notice per loss code and distinct height causes. + #[test] + fn mixed_losses_are_grouped_by_code() { + for bad in [false, true] { + let height = if bad { "bad" } else { "0" }; + let face = if bad { "99" } else { "0" }; + let short = if bad { "2 10 0 20 0 10 2 20 0" } else { "3 10 0 20 0 10 2 20 0 10 0 20 2" }; + let text = format!( + "0 SECTION 2 ENTITIES + 0 LINE 10 0 20 0 30 1 11 1 21 1 31 2 + 0 3DFACE 10 0 20 0 30 {height} 11 1 21 0 12 0 22 1 + 0 POLYLINE 70 64 + 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 + 0 VERTEX 70 128 71 1 72 2 73 3 + 0 VERTEX 70 128 71 1 72 2 73 3 74 {face} 0 SEQEND + 0 HATCH 91 2 92 2 72 0 73 1 93 3 10 0 20 0 10 2 20 0 10 0 20 2 + 92 2 72 0 73 1 93 {short} + 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let layers = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + let notes = &layers[0].1.messages; + assert_eq!(notes.len(), if bad { 3 } else { 1 }); + for code in crate::loss::LossCode::ALL { + assert!(notes.iter().filter(|n| n.loss == Some(*code)).count() <= 1, "{code:?}: {notes:?}"); + } + let varying: Vec<_> = notes.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedZm)).collect(); + assert_eq!(varying.len(), 1); + assert!(varying[0].text.contains("1 feature lost varying Z")); + let unreadable: Vec<_> = notes.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedUnreadableZ)).collect(); + let rings: Vec<_> = notes.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedRing)).collect(); + assert_eq!(unreadable.len(), usize::from(bad)); + assert_eq!(rings.len(), usize::from(bad)); + if bad { + assert_eq!(unreadable[0].text, "1 unreadable supplied Z value could not be kept"); + assert_eq!( + rings[0].text, + "1 polyface face with a missing vertex was left out; 1 short HATCH boundary ring was left out of polygons" + ); + } + } + } + /// A supplied unreadable height is distinct from an omitted optional height. #[test] fn loss_coverage_unreadable_entity_height() { @@ -2187,7 +2244,7 @@ mod tests { pairs.extend([(0, "ENDSEC"), (0, "EOF")]); let layers = read("a.dxf", &dxf(&pairs), &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(1., 1.)]]))); - let notes: Vec<_> = layers[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedZm)).collect(); + let notes: Vec<_> = layers[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedUnreadableZ)).collect(); assert_eq!(notes.len(), usize::from(z == Some("bad"))); if z == Some("bad") { assert_eq!(notes[0].text, "1 unreadable supplied Z value could not be kept"); @@ -2284,7 +2341,8 @@ mod tests { let point = if alignment == "0" { Coord::new(1.0, 2.0) } else { Coord::new(3.0, 4.0) }; assert_eq!(got[0].0.features[0].geometry, Some(Geometry::Point(point)), "{kind}"); assert_eq!(got[0].0.value(0, 8), &Value::Float(0.0)); - let notes: Vec<_> = got[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedZm)).collect(); + let notes: Vec<_> = + got[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedUnreadableZ)).collect(); assert_eq!(notes.len(), usize::from(lost), "{kind} {alignment} {first_z} {second_z}"); if lost { assert_eq!(notes[0].text, "1 unreadable supplied Z value could not be kept"); @@ -2306,7 +2364,13 @@ mod tests { assert_eq!(got[0].0.features.len(), 1); assert_eq!(got[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(2.0, 2.0)))); assert_eq!(got[0].1.skipped, 1); - assert!(!got[0].1.messages.iter().any(|n| n.loss == Some(crate::loss::LossCode::DroppedZm))); + assert!( + !got[0] + .1 + .messages + .iter() + .any(|n| matches!(n.loss, Some(crate::loss::LossCode::DroppedZm | crate::loss::LossCode::DroppedUnreadableZ))) + ); } } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 2064477a9d..65e2bab0a3 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -7324,7 +7324,7 @@ mod tests { assert!(export_losses_notes(&ds, ext, None, "a").unwrap().is_empty()); ds.fields[0].name = "=x".into(); ds.features[0].attrs[0] = Value::Text("=SUM(A1)".into()); - ds.fields.push(Field::new("\'=x", FieldType::Text)); + ds.fields.push(Field::new("'=x", FieldType::Text)); ds.features[0].attrs.push(Value::Text("safe".into())); let notes = export_losses_notes(&ds, ext, None, "a").unwrap(); assert_eq!(notes.len(), 2); diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index aa218910b7..74c3ad8d57 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -113,6 +113,12 @@ loss_codes! { "Z (height) or M (measure) values were not kept. RustGIS keeps x and y only.", "Keep the source file where heights or measures matter: RustGIS keeps x and y only." ), + DroppedUnreadableZ => ( + "dropped.unreadable-z", + Dropped, + "A supplied height could not be read and was replaced with zero. This differs from a readable height dropped when keeping only XY coordinates.", + "Correct the unreadable height in the source drawing, or remove it if zero is intended." + ), DroppedCrsName => ( "dropped.crs-name", Dropped, diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index 858e63e5b1..aecc1d68f1 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -537,7 +537,7 @@ pub(super) fn cases(fixture_dir: &std::path::Path) -> Vec { case("DXF: an unreadable supplied height", "a.dxf", dxf(&["0 LINE 10 0 20 0 30 0 11 1 21 1"]), dxf(&["0 LINE 10 0 20 0 30 bad 11 1 21 1"]), - Expect::Classified(LossCode::DroppedZm, "1 unreadable supplied Z value could not be kept")), + Expect::Classified(LossCode::DroppedUnreadableZ, "1 unreadable supplied Z value could not be kept")), case("DXF: a polyface face with a missing vertex", "a.dxf", dxf(&["0 POLYLINE 70 64 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 0 VERTEX 70 128 71 1 72 2 73 3 0 VERTEX 70 128 71 1 72 2 73 3 74 0 0 SEQEND"]), dxf(&["0 POLYLINE 70 64 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 0 VERTEX 70 128 71 1 72 2 73 3 0 VERTEX 70 128 71 1 72 2 73 3 74 99 0 SEQEND"]), @@ -1336,5 +1336,6 @@ fn zip_layer_pick_keeps_unreadable_z_notice() { assert!(matches!(s.map().layers[0].dataset.features[0].geometry, Some(rustgis_engine::data::Geometry::Polygon(_)))); let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("unreadable supplied Z")).collect(); assert_eq!(notes.len(), 1); - assert_eq!(notes[0].loss(), Some(LossCode::DroppedZm)); + assert_eq!(notes[0].loss(), Some(LossCode::DroppedUnreadableZ)); + assert!(!s.notices_since(mark).iter().any(|n| n.loss() == Some(LossCode::DroppedZm))); } diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 32ccfe70a1..7c382514d7 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -88,6 +88,14 @@ Z (height) or M (measure) values were not kept. RustGIS keeps x and y only. **What to do:** Keep the source file where heights or measures matter: RustGIS keeps x and y only. +### `dropped.unreadable-z` { #dropped.unreadable-z } + +A supplied height could not be read and was replaced with zero. This differs from a readable height dropped when keeping only XY coordinates. + +**Where you see it:** reading DXF. + +**What to do:** Correct the unreadable height in the source drawing, or remove it if zero is intended. + ### `dropped.crs-name` { #dropped.crs-name } A coordinate system's name or definition could not be written with the data, so the file holds the coordinates without it. From 4312d761457fd0674ed876b3e4671b3968621b91 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 21:26:23 -0600 Subject: [PATCH 04/16] docs(data): distinguish omitted geometry column recovery --- crates/data/src/loss.rs | 4 ++-- docs/user-guide/loss-codes.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 74c3ad8d57..870733eedb 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -86,8 +86,8 @@ loss_codes! { DroppedColumn => ( "dropped.column", Dropped, - "A column was left out because its type cannot be held, such as binary values or an additional geometry column.", - "Keep the source file; convert the needed columns to supported types or read them with a tool that supports their types." + "A column was left out because its type cannot be held, or because only one geometry column is read.", + "Keep the source file. Convert unsupported columns to supported types or use a reader that supports them. Export additional geometry columns as separate layers before importing them." ), DroppedCopyright => ( "dropped.copyright", diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 7c382514d7..584aa40faf 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -50,11 +50,11 @@ A date-time was written to a date field, which keeps only the day, so the time o ### `dropped.column` { #dropped.column } -A column was left out because its type cannot be held, such as binary values or an additional geometry column. +A column was left out because its type cannot be held, or because only one geometry column is read. **Where you see it:** reading FileGDB, GeoPackage, FlatGeobuf or GeoParquet data, or a SQL Server geodatabase table. -**What to do:** Keep the source file; convert the needed columns to supported types or read them with a tool that supports their types. +**What to do:** Keep the source file. Convert unsupported columns to supported types or use a reader that supports them. Export additional geometry columns as separate layers before importing them. ### `dropped.copyright` { #dropped.copyright } From ae4e56412f7db9b376fef6f0abfdba3c638dfb0f Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 21:35:52 -0600 Subject: [PATCH 05/16] fix(data): validate supplied DXF placement coordinates --- crates/data/src/dxf.rs | 81 +++++++++++++++++++++++++++++++++++------- 1 file changed, 68 insertions(+), 13 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index b7481c6c12..ba0a3482dc 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -666,6 +666,15 @@ fn used_point(g: &G, x: i32, loss: &mut PathLoss) -> Option { Some(point) } +/// A block base or insertion point defaults missing axes to zero, but rejects supplied unreadable +/// XY. An unreadable Z is counted and validated when a selected child actually uses the placement. +fn placement_point(g: &G, loss: &mut PathLoss) -> Option { + let x = g.s(10).map_or(Some(0.0), num)?; + let y = g.s(20).map_or(Some(0.0), num)?; + loss.unreadable_z += u64::from(g.s(30).is_some() && g.f(30).is_none()); + Some([x, y, g.f(30).unwrap_or(0.0)]) +} + /// Reads one record as an entity (POLYLINE with its VERTEX records). `None` when it can't be read. /// Cancellation also stops the Option-based builders; the caller checks and propagates it. fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) -> Option { @@ -886,7 +895,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - }, "INSERT" => Shape::Insert(Insert { block: g.s(2)?.trim().to_string(), - at: used_point(g, 10, loss).unwrap_or([0.0; 3]), + at: placement_point(g, loss)?, scale: [g.f(41).unwrap_or(1.0), g.f(42).unwrap_or(1.0), g.f(43).unwrap_or(1.0)], rotation: g.f(50).unwrap_or(0.0), extrusion: g.extrusion(), @@ -1191,11 +1200,11 @@ fn append(ring: &mut Vec, mut piece: Vec) { ring.extend(piece); } -/// A block's placement and entities; an unreadable supplied base height is checked only if used. +/// A block's placement and entities; an unreadable supplied base coordinate is checked only if used. struct Block { base: P3, entities: Vec, - invalid_z: bool, + invalid_placement: bool, } /// A drawing's layers (name → colour, linetype) and blocks (name → base point and entities). @@ -1260,12 +1269,14 @@ fn drawing(records: &[Record]) -> Result { if section == "BLOCKS" { if r.kind == "BLOCK" { let name = g.s(2).map(str::trim).unwrap_or("").to_string(); + let mut loss = PathLoss::default(); + let base = placement_point(&g, &mut loss); block = Some(( name, Block { - base: g.pt(10).unwrap_or([0.0; 3]), + base: base.unwrap_or([0.0; 3]), entities: Vec::new(), - invalid_z: g.s(30).is_some() && g.f(30).is_none(), + invalid_placement: base.is_none() || loss.unreadable_z > 0, }, )); block_lost = LostCounts::new(); @@ -1373,8 +1384,8 @@ struct Inherit<'a> { color: Option, linetype: Option<&'a str>, block: Option<&'a str>, - /// An unreadable base/insertion height on the path; ignored for unselected or undrawn content. - invalid_z: bool, + /// An unreadable base/insertion coordinate on the path; ignored for unselected or undrawn content. + invalid_placement: bool, paper: bool, } @@ -1541,7 +1552,7 @@ fn emit( out.cut += 1; continue; } - let Some(Block { base, entities: inner, invalid_z }) = d.blocks.get(&key) else { + let Some(Block { base, entities: inner, invalid_placement }) = d.blocks.get(&key) else { // A dimension without its block: the lines and text it describes. if !ins.fallback.is_empty() { let drawn: Vec = ins @@ -1593,7 +1604,7 @@ fn emit( color: Some(color), linetype: linetype().or(from.linetype), block: Some(ins.block.as_str()), - invalid_z: from.invalid_z || *invalid_z || (e.kind == "INSERT" && e.loss.unreadable_z > 0), + invalid_placement: from.invalid_placement || *invalid_placement || (e.kind == "INSERT" && e.loss.unreadable_z > 0), paper: from.paper || e.paper, }; let lost = stack.last().and_then(|k| d.block_lost.get(k)); @@ -1687,9 +1698,9 @@ fn emit( out.cut += 1; continue; }; - if from.invalid_z { + if from.invalid_placement { return Err(DataError::Format( - "a placed block has an unreadable supplied Z value; correct its base or insertion height before importing".into(), + "a placed block has an unreadable supplied coordinate; correct its base or insertion point before importing".into(), )); } let attrs = vec![ @@ -1760,7 +1771,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>().join("\n") + "\n"; + let result = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }); + if base && based.is_none() { + assert!(result.unwrap_err().to_string().contains("unreadable supplied coordinate"), "{point}"); + continue; + } + let layers = result.unwrap(); + assert_eq!(layers.len(), 1); + let (ds, report) = &layers[0]; + let mut expected = vec![Some(Geometry::Point(Coord::new(9.0, 9.0)))]; + if let Some([x, y]) = if base { based } else { inserted } { + expected.push(Some(Geometry::Point(Coord::new(x, y)))); + } + assert_eq!(ds.features.iter().map(|f| f.geometry.clone()).collect::>(), expected, "base={base} {point}"); + let skipped = usize::from(inserted.is_none()); + assert_eq!(report.skipped, skipped); + assert_eq!(report.messages.len(), skipped); + if skipped > 0 { + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); + assert!(report.messages[0].text.starts_with("1 entities couldn't be read or placed")); + } + } + } + } + /// A supplied unreadable height is distinct from an omitted optional height. #[test] fn loss_coverage_unreadable_entity_height() { @@ -2284,7 +2339,7 @@ mod tests { ); let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; let opts = Options { crs: Some(Crs::LonLat), ..Options::default() }; - assert!(read("a.dxf", bytes.as_bytes(), &opts).unwrap_err().to_string().contains("unreadable supplied Z value")); + assert!(read("a.dxf", bytes.as_bytes(), &opts).unwrap_err().to_string().contains("unreadable supplied coordinate")); assert!(layers("a.dxf", bytes.as_bytes()).is_ok()); assert!(read("a.dxf", bytes.as_bytes(), &Options { blocks: false, ..opts }).is_ok()); assert!(read("a.dxf", bytes.as_bytes(), &Options { layer: Some("safe"), ..opts }).is_ok()); From 4b896d36722da7ad98220c672a7da4863e804f55 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 22:18:47 -0600 Subject: [PATCH 06/16] fix(data): scope XLSB preflight to supported worksheets --- crates/data/src/dxf.rs | 7 ++-- crates/data/src/sheets/xlsb.rs | 62 ++++++++++++++++++++++++++++++++-- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index ba0a3482dc..b0552ce0ac 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1840,7 +1840,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>().join("\n"); @@ -2596,7 +2597,9 @@ mod tests { assert_eq!(layers[0].1.skipped, 1); assert_eq!( 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"] + [ + "1 entities couldn't be read or placed (unreadable coordinates or polyface faces, 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)); } diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index 2639a24234..ca59af50a5 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -5,8 +5,9 @@ use crate::{DataError, Result}; /// Checks binary worksheet streams before any workbook entry point can omit their cells. -/// A worksheet starts with BrtBeginSheet (129). Inspecting the framing, rather than content-type -/// declarations, also covers a workbook whose declarations are absent or name a different type. +/// calamine 0.38 accepts worksheet targets only in `xl/worksheets/` (Xlsb::read_workbook). +/// Other targets are refused before any cells are read. Match that boundary, independently of +/// content-type declarations, so unrelated binary parts are never mistaken for worksheets. /// This uses existing ZIP buffers, skips payloads without copying and looks at Cancel per record. /// All worksheet streams are checked, including ones a caller did not select. pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { @@ -15,7 +16,9 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { } for (name, data) in entries { crate::progress::check()?; - if !data.starts_with(&[0x81, 0x01]) { + if !name.get(..14).is_some_and(|prefix| prefix.replace('\\', "/").eq_ignore_ascii_case("xl/worksheets/")) + || !data.starts_with(&[0x81, 0x01]) + { continue; } check_sheet(data).map_err(|e| match e { @@ -71,6 +74,59 @@ fn check_sheet(mut data: &[u8]) -> Result<()> { mod tests { use super::*; + /// Unrelated binary parts are not worksheets; renamed supported sheets still get checked. + #[test] + fn worksheet_guard_matches_the_readers_supported_paths() { + for short in [false, true] { + let original: &[u8] = if short { + include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb") + } else { + include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") + }; + for folder in ["worksheets", "elsewhere"] { + let mut entries = crate::zip::read(original).unwrap(); + let target = format!("{folder}/renamed.bin"); + let sheet = entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap(); + sheet.0 = format!("xl/{target}"); + let rels = &mut entries.iter_mut().find(|(name, _)| name == "xl/_rels/workbook.bin.rels").unwrap().1; + *rels = String::from_utf8(rels.clone()).unwrap().replace("worksheets/sheet1.bin", &target).into_bytes(); + let types = &mut entries.iter_mut().find(|(name, _)| name == "[Content_Types].xml").unwrap().1; + *types = String::from_utf8(types.clone()) + .unwrap() + .replace("/xl/worksheets/sheet1.bin", &format!("/xl/{target}")) + .replace( + "", + "", + ) + .into_bytes(); + // An opaque unused part can have these bytes without being an XLSB record stream. + entries.push(("xl/embeddings/object1.bin".into(), vec![0x81, 0x01, 0x80])); + let bytes = crate::zip::write(&entries).unwrap(); + let result = crate::sheets::read(&bytes, "a", None, &Default::default()); + if folder != "worksheets" { + // calamine 0.38 refuses this path before reading cells; no attributes can slip by. + let error = result.unwrap_err().to_string(); + assert!(error.contains("Cannot detect file format"), "{error}"); + let direct = calamine::open_workbook_from_rs::, _>(std::io::Cursor::new(bytes.as_slice())); + let error = direct.err().unwrap().to_string(); + assert!(error.contains("BoundSheet8:dt"), "{error}"); + } else if short { + assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records")); + } else { + let (ds, report) = result.unwrap(); + assert_eq!( + ds.fields, + [crate::Field::new("id", crate::FieldType::Integer), crate::Field::new("note", crate::FieldType::Text)] + ); + assert_eq!(ds.features.len(), 1); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert_eq!(ds.features[0].geometry, Some(crate::Geometry::Point(rustgis_geom::Coord::new(1.0, 2.0)))); + assert!(report.messages.is_empty()); + } + } + } + } + /// MS-XLSB 2.1.4 ignores the last size byte's high bit; both encodings retain the workbook. #[test] fn four_byte_record_sizes_ignore_the_last_high_bit() { From 94509f11f51b20184e271174f6330922fc3eb718 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 00:00:46 -0600 Subject: [PATCH 07/16] fix(data): preserve loss reporting across filtered and encoded inputs --- crates/data/src/dxf.rs | 145 +++++++++++++++++++++++++++++-- crates/data/src/esripbf.rs | 14 ++- crates/data/src/esripbf/tests.rs | 8 +- crates/data/src/loss.rs | 4 +- crates/data/src/sheets/xlsb.rs | 43 +++++++-- docs/user-guide/loss-codes.md | 6 +- 6 files changed, 190 insertions(+), 30 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index b0552ce0ac..ad1e4d6713 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -227,6 +227,9 @@ fn records(text: &str) -> Result<(Vec>, Option)> { let said = format!("line {}: '{}' isn't a DXF group code: the drawing is read up to it", line - 1, crate::io::cut(code, 40)); return Ok((out, Some(said))); }; + if code == 999 { + continue; // DXF comments do not interrupt coordinate groups or record boundaries. + } if code == 0 { let kind = value.trim(); if kind == "EOF" { @@ -384,7 +387,7 @@ impl Shape { struct Insert { block: String, /// Insertion point, scale, rotation (degrees) and extrusion, in the insert's object coordinates. - at: P3, + at: Option, scale: P3, rotation: f64, extrusion: P3, @@ -895,7 +898,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - }, "INSERT" => Shape::Insert(Insert { block: g.s(2)?.trim().to_string(), - at: placement_point(g, loss)?, + at: placement_point(g, loss), scale: [g.f(41).unwrap_or(1.0), g.f(42).unwrap_or(1.0), g.f(43).unwrap_or(1.0)], rotation: g.f(50).unwrap_or(0.0), extrusion: g.extrusion(), @@ -911,7 +914,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - let (fallback, fallback_text) = dimension(g, loss); Shape::Insert(Insert { block: g.s(2).map(str::trim).unwrap_or("").to_string(), - at: [0.0; 3], + at: Some([0.0; 3]), scale: [1.0; 3], rotation: 0.0, extrusion: [0.0, 0.0, 1.0], @@ -1002,6 +1005,7 @@ fn measure(v: f64) -> String { fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { let mut pos: Vec = Vec::new(); let mut faces: Vec> = Vec::new(); + let mut unreadable_z = Vec::new(); for (index, v) in vertices.iter().take(MAX_VERTICES).enumerate() { if index % 1024 == 0 { crate::progress::check().ok()?; @@ -1009,20 +1013,24 @@ fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { let g = G { p: &v.groups }; let flags = g.i(70).unwrap_or(0); if flags & 64 != 0 { - loss.unreadable_z += g.p.iter().filter(|(c, v)| *c == 30 && num(v).is_none()).count() as u64; pos.push(g.pt(10)?); + unreadable_z.push(g.s(30).is_some() && g.f(30).is_none()); } else if flags & 128 != 0 { let mut ring = Vec::new(); let mut missing = false; + let mut referenced = Vec::new(); for c in [71, 72, 73, 74] { if g.s(c).is_some() && g.i(c).is_none() { missing = true; continue; } let Some(i) = g.i(c).filter(|i| *i != 0) else { continue }; - let point = usize::try_from(i.unsigned_abs()).ok().and_then(|i| pos.get(i.checked_sub(1)?)); - match point { - Some(p) => ring.push(*p), + let index = usize::try_from(i.unsigned_abs()).ok().and_then(|i| i.checked_sub(1)); + match index.and_then(|i| pos.get(i).map(|p| (i, p))) { + Some((index, p)) => { + ring.push(*p); + referenced.push(index); + } None => missing = true, } } @@ -1031,6 +1039,14 @@ fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { continue; } if ring.len() >= 3 { + for index in referenced { + if let Some(bad) = unreadable_z.get_mut(index) + && *bad + { + loss.unreadable_z += 1; + *bad = false; + } + } let mut r = ring; if let Some(f) = r.first().copied() { r.push(f); @@ -1386,6 +1402,8 @@ struct Inherit<'a> { block: Option<&'a str>, /// An unreadable base/insertion coordinate on the path; ignored for unselected or undrawn content. invalid_placement: bool, + /// A supplied unreadable INSERT XY; count selected children rather than drawing at the origin. + rejected: bool, paper: bool, } @@ -1593,7 +1611,7 @@ fn emit( for r in 0..rows { for c in 0..cols { let local = Xf::ocs(ins.extrusion) - .then(&Xf::translate(ins.at)) + .then(&Xf::translate(ins.at.unwrap_or([0.0; 3]))) .then(&Xf::rotate_z(ins.rotation)) .then(&Xf::translate([c as f64 * ins.col_space, r as f64 * ins.row_space, 0.0])) .then(&Xf::scale(ins.scale)) @@ -1605,8 +1623,11 @@ fn emit( linetype: linetype().or(from.linetype), block: Some(ins.block.as_str()), invalid_placement: from.invalid_placement || *invalid_placement || (e.kind == "INSERT" && e.loss.unreadable_z > 0), + rejected: from.rejected || ins.at.is_none(), paper: from.paper || e.paper, }; + // INSERT's own bad Z is carried by the placement flag, then refused only + // when a selected child uses it; charging e.loss again would duplicate it. 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 { @@ -1625,6 +1646,10 @@ fn emit( { continue; } + if from.rejected { + 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 { @@ -1771,7 +1796,16 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(got[0].0.features[0].geometry, Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]]))); + assert_eq!(got[0].0.value(0, 8), &Value::Float(if height == "bad" { 0.0 } else { 5.0 })); + let notes = &got[0].1.messages; + assert_eq!(notes.len(), usize::from(height == "bad")); + if height == "bad" { + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedUnreadableZ)); + assert_eq!(notes[0].text, "2 unreadable supplied Z values could not be kept"); + } + } + } + } + + /// Rejected placements keep their selected child-layer context through nesting and arrays. + #[test] + fn rejected_inserts_count_selected_children() { + for bad in [false, true] { + for layer in ["roads", "water", "safe"] { + let x = if bad { "bad" } else { "10" }; + let text = format!( + "0 SECTION 2 BLOCKS + 0 BLOCK 2 child 0 POINT 8 roads 10 1 20 2 0 POINT 8 water 10 3 20 4 0 ENDBLK + 0 BLOCK 2 parent 0 INSERT 2 child 0 ENDBLK 0 ENDSEC + 0 SECTION 2 ENTITIES 0 POINT 8 roads 10 9 20 9 0 POINT 8 water 10 9 20 9 0 POINT 8 safe 10 9 20 9 + 0 INSERT 2 parent 10 {x} 20 0 70 2 44 5 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let got = + read("a.dxf", bytes.as_bytes(), &Options { layer: Some(layer), crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(got.len(), 1); + let (ds, report) = &got[0]; + let affected = layer != "safe"; + assert_eq!(ds.features.len(), if !bad && affected { 3 } else { 1 }); + assert_eq!(report.skipped, if bad && affected { 2 } else { 0 }); + assert_eq!(report.messages.len(), usize::from(bad && affected)); + if bad && affected { + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); + assert!(report.messages[0].text.starts_with("2 entities couldn't be read or placed")); + } + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(9.0, 9.0)))); + if !bad && affected { + let (x, y) = if layer == "roads" { (11.0, 2.0) } else { (13.0, 4.0) }; + assert_eq!(ds.features[1].geometry, Some(Geometry::Point(Coord::new(x, y)))); + assert_eq!(ds.features[2].geometry, Some(Geometry::Point(Coord::new(x + 5.0, y)))); + } + } + } + } + + /// An unreadable polyface height counts once, only when a retained face references its vertex. + #[test] + fn polyface_height_counts_only_referenced_vertices() { + for height in ["0", "bad"] { + for mode in ["unused", "dropped", "used"] { + let extra = match mode { + "dropped" => "0 VERTEX 70 128 71 1 72 4 73 99", + "used" => "0 VERTEX 70 128 71 1 72 2 73 4 0 VERTEX 70 128 71 1 72 3 73 4", + _ => "", + }; + let text = format!( + "0 SECTION 2 ENTITIES 0 POLYLINE 70 64 + 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 + 0 VERTEX 70 64 10 1 20 1 30 {height} 0 VERTEX 70 128 71 1 72 2 73 3 {extra} + 0 SEQEND 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + let Some(Geometry::Polygon(polys)) = &got[0].0.features[0].geometry else { panic!("polygon") }; + assert_eq!(polys.iter().map(Vec::len).sum::(), if mode == "used" { 3 } else { 1 }); + let notes: Vec<_> = + got[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedUnreadableZ)).collect(); + assert_eq!(notes.len(), usize::from(height == "bad" && mode == "used")); + if !notes.is_empty() { + assert_eq!(notes[0].text, "1 unreadable supplied Z value could not be kept"); + } + assert_eq!( + got[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedRing)).count(), + usize::from(mode == "dropped") + ); + } + } + } + /// Mixed causes keep their own counts, with one notice per loss code and distinct height causes. #[test] fn mixed_losses_are_grouped_by_code() { diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 5f403bd4da..c5fb2d4d38 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -356,17 +356,15 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result columns.push(Some((fields.len(), read_as))); fields.push(Field { name, ty: read_as.field_type(), alias }); } + let mut omitted = Vec::new(); if repeated > 0 { - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!("{repeated} fields repeat an earlier field's name and are left out"), - )); + omitted.push(format!("{repeated} fields repeat an earlier field's name and are left out")); } if not_read > 0 { - 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"), - )); + omitted.push(format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out")); + } + if !omitted.is_empty() { + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedColumn, omitted.join("; "))); } if unknown > 0 { report.messages.push(format!("{unknown} fields have a type RustGIS doesn't know; their values are read as text")); diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 9f619e340f..71c32a2805 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -326,12 +326,14 @@ fn repeated_names_and_unread_field_types_are_left_out_and_said() { assert_eq!( 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 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); + assert_eq!( + report.messages.iter().map(|m| m.loss).collect::>(), + [Some(crate::loss::LossCode::DroppedColumn), Some(crate::loss::LossCode::DroppedValue)] + ); // A table: no geometry type, no geometry. assert_eq!(ds.geometry_type, GeometryType::None); } diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 870733eedb..c723d23595 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -86,8 +86,8 @@ loss_codes! { DroppedColumn => ( "dropped.column", Dropped, - "A column was left out because its type cannot be held, or because only one geometry column is read.", - "Keep the source file. Convert unsupported columns to supported types or use a reader that supports them. Export additional geometry columns as separate layers before importing them." + "A column was left out because its type cannot be held, its name repeats an earlier column's, or only one geometry column is read.", + "Keep the source file. Convert unsupported columns to supported types or use a reader that supports them. Give repeated columns distinct names. Export additional geometry columns as separate layers before importing them." ), DroppedCopyright => ( "dropped.copyright", diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index ca59af50a5..11a0b28bf1 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -16,9 +16,11 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { } for (name, data) in entries { crate::progress::check()?; - if !name.get(..14).is_some_and(|prefix| prefix.replace('\\', "/").eq_ignore_ascii_case("xl/worksheets/")) - || !data.starts_with(&[0x81, 0x01]) - { + let path = name.replace('\\', "/").to_ascii_lowercase(); + // Relationship metadata lives beside worksheet streams but is XML, not cell records. + let relationship = + path.rsplit_once('/').is_some_and(|(dir, leaf)| dir.rsplit('/').next() == Some("_rels") && leaf.ends_with(".rels")); + if !path.starts_with("xl/worksheets/") || relationship { continue; } check_sheet(data).map_err(|e| match e { @@ -74,6 +76,33 @@ fn check_sheet(mut data: &[u8]) -> Result<()> { mod tests { use super::*; + /// Record framing, rather than one byte spelling, decides which worksheet data is refused. + #[test] + fn worksheet_headers_do_not_bypass_short_cell_checks() { + for short in [false, true] { + let original: &[u8] = if short { + include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb") + } else { + include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") + }; + for prefix in [[0x81, 0x01], [0x81, 0x81], [0x93, 0x01]] { + let mut entries = crate::zip::read(original).unwrap(); + let sheet = &mut entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + sheet.get_mut(..2).unwrap().copy_from_slice(&prefix); + let bytes = crate::zip::write(&entries).unwrap(); + let result = crate::sheets::read(&bytes, "a", None, &Default::default()); + if short { + assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records"), "{prefix:?}"); + } else { + let (ds, report) = result.unwrap(); + assert_eq!(ds.fields.len(), 2); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert!(report.messages.is_empty()); + } + } + } + } + /// Unrelated binary parts are not worksheets; renamed supported sheets still get checked. #[test] fn worksheet_guard_matches_the_readers_supported_paths() { @@ -83,7 +112,7 @@ mod tests { } else { include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") }; - for folder in ["worksheets", "elsewhere"] { + for folder in ["worksheets", "worksheets/nested", "elsewhere"] { let mut entries = crate::zip::read(original).unwrap(); let target = format!("{folder}/renamed.bin"); let sheet = entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap(); @@ -101,9 +130,13 @@ mod tests { .into_bytes(); // An opaque unused part can have these bytes without being an XLSB record stream. entries.push(("xl/embeddings/object1.bin".into(), vec![0x81, 0x01, 0x80])); + entries.push(( + format!("xl/{folder}/_rels/renamed.bin.rels"), + br#""#.to_vec(), + )); let bytes = crate::zip::write(&entries).unwrap(); let result = crate::sheets::read(&bytes, "a", None, &Default::default()); - if folder != "worksheets" { + if folder == "elsewhere" { // calamine 0.38 refuses this path before reading cells; no attributes can slip by. let error = result.unwrap_err().to_string(); assert!(error.contains("Cannot detect file format"), "{error}"); diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 584aa40faf..9c947c927b 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -50,11 +50,11 @@ A date-time was written to a date field, which keeps only the day, so the time o ### `dropped.column` { #dropped.column } -A column was left out because its type cannot be held, or because only one geometry column is read. +A column was left out because its type cannot be held, its name repeats an earlier column's, or only one geometry column is read. -**Where you see it:** reading FileGDB, GeoPackage, FlatGeobuf or GeoParquet data, or a SQL Server geodatabase table. +**Where you see it:** reading FileGDB, GeoPackage, FlatGeobuf, GeoParquet or feature-service PBF data, or a SQL Server geodatabase table. -**What to do:** Keep the source file. Convert unsupported columns to supported types or use a reader that supports them. Export additional geometry columns as separate layers before importing them. +**What to do:** Keep the source file. Convert unsupported columns to supported types or use a reader that supports them. Give repeated columns distinct names. Export additional geometry columns as separate layers before importing them. ### `dropped.copyright` { #dropped.copyright } From 0b8e3e7c56c5714fcd3024c99980c6a060b22f58 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 00:44:55 -0600 Subject: [PATCH 08/16] fix(data): distinguish missing and unreadable optional DXF points --- crates/data/src/dxf.rs | 91 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 3 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index ad1e4d6713..39cb1f7977 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -669,6 +669,12 @@ fn used_point(g: &G, x: i32, loss: &mut PathLoss) -> Option { Some(point) } +/// An optional point may be absent. Once any of its axes is supplied, its XY must be readable; +/// the outer Option rejects malformed input, while the inner one preserves the format's omission. +fn optional_used_point(g: &G, x: i32, loss: &mut PathLoss) -> Option> { + if [x, x + 10, x + 20].into_iter().all(|code| g.s(code).is_none()) { Some(None) } else { used_point(g, x, loss).map(Some) } +} + /// A block base or insertion point defaults missing axes to zero, but rejects supplied unreadable /// XY. An unreadable Z is counted and validated when a selected child actually uses the placement. fn placement_point(g: &G, loss: &mut PathLoss) -> Option { @@ -868,7 +874,14 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - // length). let vertical = if kind == "TEXT" { g.i(73) } else { g.i(74) }; let justified = g.i(72).unwrap_or(0) != 0 || vertical.unwrap_or(0) != 0; - let p = if justified { used_point(g, 11, loss).or_else(|| used_point(g, 10, loss))? } else { used_point(g, 10, loss)? }; + let p = if justified { + match optional_used_point(g, 11, loss)? { + Some(point) => point, + None => used_point(g, 10, loss)?, + } + } else { + used_point(g, 10, loss)? + }; Shape::Point(ocs.apply(p)) } "MTEXT" => Shape::Point(used_point(g, 10, loss)?), @@ -876,7 +889,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - let (a, b, c) = (used_point(g, 10, loss)?, used_point(g, 11, loss)?, used_point(g, 12, loss)?); // A solid's corners zigzag: 1, 2, then 4 and 3. let mut ring = vec![a, b]; - match used_point(g, 13, loss) { + match optional_used_point(g, 13, loss)? { Some(d) if d != c => ring.extend([d, c]), _ => ring.push(c), } @@ -886,7 +899,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - "3DFACE" => { let (a, b, c) = (used_point(g, 10, loss)?, used_point(g, 11, loss)?, used_point(g, 12, loss)?); let mut ring = vec![a, b, c]; - if let Some(d) = used_point(g, 13, loss).filter(|d| *d != c) { + if let Some(d) = optional_used_point(g, 13, loss)?.filter(|d| *d != c) { ring.push(d); } ring.push(a); @@ -2235,6 +2248,78 @@ mod tests { } } + /// Omitted or repeated fourth corners make triangles; supplied malformed ones omit the face. + #[test] + fn optional_face_corners_distinguish_omitted_from_unreadable() { + for kind in ["SOLID", "TRACE", "3DFACE"] { + let c = if kind == "3DFACE" { Coord::new(2.0, 2.0) } else { Coord::new(0.0, 2.0) }; + let fourth = if kind == "3DFACE" { "13 0 23 2" } else { "13 2 23 2" }; + let duplicate = if kind == "3DFACE" { "13 2 23 2" } else { "13 0 23 2" }; + for (point, bad, quad) in [ + ("", false, false), + (fourth, false, true), + (duplicate, false, false), + ("13 bad 23 2", true, false), + ("13 2 23 bad", true, false), + ("23 2", true, false), + ] { + let text = format!( + "0 SECTION 2 ENTITIES 0 POINT 10 9 20 9 0 {kind} 10 0 20 0 11 2 21 0 12 {} 22 {} {point} 0 ENDSEC 0 EOF", + c.x, c.y + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + let polygons: Vec<_> = got + .iter() + .flat_map(|(ds, _)| ds.features.iter()) + .filter_map(|f| match &f.geometry { + Some(Geometry::Polygon(p)) => Some(p), + _ => None, + }) + .collect(); + assert_eq!(polygons.len(), usize::from(!bad), "{kind} {point}"); + assert_eq!(got[0].1.skipped, usize::from(bad)); + assert_eq!(got[0].1.messages.len(), usize::from(bad)); + if bad { + assert_eq!(got[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); + } else { + let corners = if quad { + vec![Coord::new(0.0, 0.0), Coord::new(2.0, 0.0), Coord::new(2.0, 2.0), Coord::new(0.0, 2.0), Coord::new(0.0, 0.0)] + } else { + vec![Coord::new(0.0, 0.0), Coord::new(2.0, 0.0), c, Coord::new(0.0, 0.0)] + }; + assert_eq!(polygons[0], &vec![vec![corners]]); + } + } + } + } + + /// Only an absent alignment point falls back; unselected alignment data remains unused. + #[test] + fn text_alignment_distinguishes_omitted_from_unreadable() { + for kind in ["TEXT", "ATTRIB", "ATTDEF"] { + for justified in [false, true] { + for (point, bad) in [("", false), ("11 2 21 3", false), ("11 bad 21 3", true), ("11 2 21 bad", true), ("21 3", true)] { + let align = usize::from(justified); + let text = + format!("0 SECTION 2 ENTITIES 0 POINT 10 9 20 9 0 {kind} 70 2 1 a 72 {align} 10 5 20 6 {point} 0 ENDSEC 0 EOF"); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + let skipped = justified && bad; + assert_eq!(got[0].0.features.len(), if skipped { 1 } else { 2 }, "{kind} {justified} {point}"); + assert_eq!(got[0].1.skipped, usize::from(skipped)); + assert_eq!(got[0].1.messages.len(), usize::from(skipped)); + if skipped { + assert_eq!(got[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); + } else { + let expected = if justified && !point.is_empty() { Coord::new(2.0, 3.0) } else { Coord::new(5.0, 6.0) }; + assert_eq!(got[0].0.features[1].geometry, Some(Geometry::Point(expected))); + } + } + } + } + } + /// Group 999 never separates coordinate axes or hides the supplied LEADER/MLINE height. #[test] fn leader_and_mline_ignore_comments_between_axes() { From be17432a901fa60e5635e1f503feb4cd42f6ceb6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 01:10:04 -0600 Subject: [PATCH 09/16] fix(data): check referenced XLSB parts through sheet data --- crates/data/src/sheets/xlsb.rs | 157 ++++++++++++++++++++++++++++----- 1 file changed, 137 insertions(+), 20 deletions(-) diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index 11a0b28bf1..00d4b16d8c 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -2,27 +2,53 @@ //! Record framing follows [MS-XLSB] §2.1.4 (not the undocumented short-cell payloads): //! . +use std::collections::HashMap; + use crate::{DataError, Result}; -/// Checks binary worksheet streams before any workbook entry point can omit their cells. -/// calamine 0.38 accepts worksheet targets only in `xl/worksheets/` (Xlsb::read_workbook). -/// Other targets are refused before any cells are read. Match that boundary, independently of -/// content-type declarations, so unrelated binary parts are never mistaken for worksheets. -/// This uses existing ZIP buffers, skips payloads without copying and looks at Cancel per record. -/// All worksheet streams are checked, including ones a caller did not select. +/// Checks the sheet parts named by the workbook's bundle records and relationship targets. +/// ZIP names are normalized as calamine's lookup is; a worksheet's extension never determines +/// whether it is checked. Unreferenced parts, including genuine relationship XML, are not cells. +/// Existing ZIP buffers are borrowed; the index and relationship strings scale with package +/// metadata rather than cell count. Every record and XML event looks at Cancel. pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { - if !entries.iter().any(|(name, _)| name.eq_ignore_ascii_case("xl/workbook.bin")) { + if !entries.iter().any(|(name, _)| name.eq_ignore_ascii_case("xl/workbook.bin") || name.eq_ignore_ascii_case(r"xl\workbook.bin")) { return Ok(()); } + let mut parts = HashMap::new(); for (name, data) in entries { crate::progress::check()?; - let path = name.replace('\\', "/").to_ascii_lowercase(); - // Relationship metadata lives beside worksheet streams but is XML, not cell records. - let relationship = - path.rsplit_once('/').is_some_and(|(dir, leaf)| dir.rsplit('/').next() == Some("_rels") && leaf.ends_with(".rels")); - if !path.starts_with("xl/worksheets/") || relationship { + parts.insert(part_name(name), (name.as_str(), data.as_slice())); + } + let Some((_, mut workbook)) = parts.get("xl/workbook.bin").copied() else { return Ok(()) }; + let targets = match parts.get("xl/_rels/workbook.bin.rels") { + Some((_, data)) => relationships(data)?, + None => HashMap::new(), + }; + while let Some((kind, payload)) = record(&mut workbook)? { + crate::progress::check()?; + if kind == 144 { + // BrtEndBundleShs: calamine stops reading sheet declarations here too. + break; + } + if kind != 156 { + // BrtBundleSh continue; } + let length = payload.get(8..12).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_le_bytes).ok_or_else(damaged)?; + if length == u32::MAX { + continue; + } + let end = (length as usize).checked_mul(2).and_then(|n| n.checked_add(12)).ok_or_else(damaged)?; + let id = encoding_rs::UTF_16LE.decode(payload.get(12..end).ok_or_else(damaged)?).0; + let target = targets.get(id.as_ref()).ok_or_else(|| DataError::Format("an XLSB sheet has no workbook relationship".into()))?; + // These are the three sheet directories the pinned reader accepts. Other targets are + // refused by it before reading cells; chart/dialog paths can still contain cell records. + if !matches!(target.split('/').next(), Some("worksheets" | "chartsheets" | "dialogsheets")) { + continue; + } + let path = part_name(&format!("xl/{target}")); + let (name, data) = parts.get(&path).ok_or_else(|| DataError::Format("an XLSB sheet part is missing".into()))?; check_sheet(data).map_err(|e| match e { DataError::Cancelled => e, DataError::Unsupported(reason) => DataError::Unsupported(format!("spreadsheet part '{name}': {reason}")), @@ -32,6 +58,62 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { Ok(()) } +/// The same ZIP path key used by the workbook reader, retaining neither payloads nor file copies. +fn part_name(name: &str) -> String { + name.replace('\\', "/").to_ascii_lowercase() +} + +/// Resolves workbook relationship IDs with the existing streaming XML reader. No namespace +/// tree or recursion is built; target strings are decoded without interpreting them as URLs. +fn relationships(data: &[u8]) -> Result> { + use quick_xml::{XmlVersion, events::Event}; + let mut reader = quick_xml::Reader::from_reader(data); + let mut targets = HashMap::new(); + loop { + crate::progress::check()?; + let event = reader.read_event().map_err(|e| DataError::Format(format!("XLSB workbook relationships: {e}")))?; + match event { + Event::Start(element) | Event::Empty(element) if element.name().as_ref() == "Relationship" => { + let mut id = None; + let mut target = None; + for attribute in element.attributes() { + let attribute = attribute.map_err(|e| DataError::Format(format!("XLSB workbook relationships: {e}")))?; + if matches!(attribute.key.as_ref(), "Id" | "Target") { + let value = attribute + .normalized_value(XmlVersion::Implicit1_0) + .map_err(|e| DataError::Format(format!("XLSB workbook relationships: {e}")))? + .into_owned(); + if attribute.key.as_ref() == "Id" { + id = Some(value); + } else { + target = Some(value); + } + } + } + if let (Some(id), Some(target)) = (id, target) { + targets.insert(id, target); + } + } + Event::Eof => break, + _ => {} + } + } + Ok(targets) +} + +/// Borrows one bounded record payload and advances to the next boundary without scanning inside it. +fn record<'a>(data: &mut &'a [u8]) -> Result> { + if data.is_empty() { + return Ok(None); + } + let kind = number(data, 2)?; + let size = number(data, 4)?; + let bytes = *data; + let payload = bytes.get(..size).ok_or_else(damaged)?; + *data = bytes.get(size..).ok_or_else(damaged)?; + Ok(Some((kind, payload))) +} + /// Reads the bounded base-128 type or size field. The final byte contributes only its low seven /// bits; the size field's fourth-byte high bit is ignored (MS-XLSB 2.1.4), not a fifth-byte marker. fn number(data: &mut &[u8], most: usize) -> Result { @@ -53,11 +135,14 @@ fn damaged() -> DataError { /// Only record boundaries are interpreted; bytes resembling a record inside cell data are ignored. fn check_sheet(mut data: &[u8]) -> Result<()> { - while !data.is_empty() { + let mut in_data = false; + while let Some((kind, _)) = record(&mut data)? { crate::progress::check()?; - let kind = number(&mut data, 2)?; - let size = number(&mut data, 4)?; - if kind == 146 { + if kind == 145 { + // BrtBeginSheetData + in_data = true; + } else if kind == 146 && in_data { + // BrtEndSheetData return Ok(()); } // calamine 0.38 skips these short-cell encodings without yielding their values. @@ -67,7 +152,6 @@ fn check_sheet(mut data: &[u8]) -> Result<()> { "unsupported XLSB short-cell records; no data was imported. Save the workbook as XLSX and open that copy".into(), )); } - data = data.get(size..).ok_or_else(damaged)?; } Ok(()) } @@ -112,9 +196,16 @@ mod tests { } else { include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") }; - for folder in ["worksheets", "worksheets/nested", "elsewhere"] { + for (folder, leaf) in [ + ("worksheets", "renamed.bin"), + ("worksheets/nested", "renamed.bin"), + ("worksheets/_rels", "renamed.bin.rels"), + ("chartsheets", "renamed.bin"), + ("dialogsheets", "renamed.bin"), + ("elsewhere", "renamed.bin"), + ] { let mut entries = crate::zip::read(original).unwrap(); - let target = format!("{folder}/renamed.bin"); + let target = format!("{folder}/{leaf}"); let sheet = entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap(); sheet.0 = format!("xl/{target}"); let rels = &mut entries.iter_mut().find(|(name, _)| name == "xl/_rels/workbook.bin.rels").unwrap().1; @@ -130,6 +221,7 @@ mod tests { .into_bytes(); // An opaque unused part can have these bytes without being an XLSB record stream. entries.push(("xl/embeddings/object1.bin".into(), vec![0x81, 0x01, 0x80])); + entries.push(("xl/worksheets/unused.bin".into(), vec![0x81, 0x01, 0x80])); entries.push(( format!("xl/{folder}/_rels/renamed.bin.rels"), br#""#.to_vec(), @@ -160,6 +252,31 @@ mod tests { } } + /// An end marker before sheet data cannot hide cells the workbook reader still consumes. + #[test] + fn early_end_marker_does_not_bypass_short_cell_checks() { + for short in [false, true] { + let original: &[u8] = if short { + include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb") + } else { + include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") + }; + let mut entries = crate::zip::read(original).unwrap(); + let sheet = &mut entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + sheet.splice(..0, [0x92, 0x01, 0]); + let bytes = crate::zip::write(&entries).unwrap(); + let result = crate::sheets::read(&bytes, "a", None, &Default::default()); + if short { + assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records")); + } else { + let (ds, report) = result.unwrap(); + assert_eq!(ds.fields.len(), 2); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert!(report.messages.is_empty()); + } + } + } + /// MS-XLSB 2.1.4 ignores the last size byte's high bit; both encodings retain the workbook. #[test] fn four_byte_record_sizes_ignore_the_last_high_bit() { @@ -186,7 +303,7 @@ mod tests { assert!(check_sheet(&[kind, 0]).unwrap_err().to_string().contains("short-cell")); check_sheet(&[6, 2, kind, 0]).unwrap(); } - check_sheet(&[0x92, 0x01, 0, 6, 0xff]).unwrap(); + check_sheet(&[0x91, 0x01, 0, 0x92, 0x01, 0, 6, 0xff]).unwrap(); for bytes in [&[0x81][..], &[0x81, 0x80], &[6, 0x80], &[6, 2, 0], &[6, 0xff, 0xff, 0xff, 0xff]] { assert!(check_sheet(bytes).unwrap_err().to_string().contains("cut short")); } From f94160b451d2f457db8adca4d9ef5dcf0c7327f2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 01:52:24 -0600 Subject: [PATCH 10/16] fix(data): match XLSB reader lookup and cell boundaries --- crates/data/src/dxf.rs | 3 +- crates/data/src/sheets/xlsb.rs | 144 +++++++++++++++++++++++++++------ 2 files changed, 120 insertions(+), 27 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 39cb1f7977..a2a80cb4eb 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -386,7 +386,8 @@ impl Shape { #[derive(Clone, Debug)] struct Insert { block: String, - /// Insertion point, scale, rotation (degrees) and extrusion, in the insert's object coordinates. + /// Insertion point in object coordinates; None rejects this placement and counts its children. + /// Scale, rotation (degrees) and extrusion also use the insert's object coordinates. at: Option, scale: P3, rotation: f64, diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index 00d4b16d8c..31121701d5 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -21,7 +21,8 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { parts.insert(part_name(name), (name.as_str(), data.as_slice())); } let Some((_, mut workbook)) = parts.get("xl/workbook.bin").copied() else { return Ok(()) }; - let targets = match parts.get("xl/_rels/workbook.bin.rels") { + // Unlike binary parts, calamine opens workbook relationships by their exact ZIP name. + let targets = match entries.iter().rev().find(|(name, _)| name == "xl/_rels/workbook.bin.rels") { Some((_, data)) => relationships(data)?, None => HashMap::new(), }; @@ -42,8 +43,8 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { let end = (length as usize).checked_mul(2).and_then(|n| n.checked_add(12)).ok_or_else(damaged)?; let id = encoding_rs::UTF_16LE.decode(payload.get(12..end).ok_or_else(damaged)?).0; let target = targets.get(id.as_ref()).ok_or_else(|| DataError::Format("an XLSB sheet has no workbook relationship".into()))?; - // These are the three sheet directories the pinned reader accepts. Other targets are - // refused by it before reading cells; chart/dialog paths can still contain cell records. + // Only these three first path segments pass the pinned reader's sheet-type check. + // It refuses every other target before cells are read, including leading / or ./ paths. if !matches!(target.split('/').next(), Some("worksheets" | "chartsheets" | "dialogsheets")) { continue; } @@ -66,7 +67,7 @@ fn part_name(name: &str) -> String { /// Resolves workbook relationship IDs with the existing streaming XML reader. No namespace /// tree or recursion is built; target strings are decoded without interpreting them as URLs. fn relationships(data: &[u8]) -> Result> { - use quick_xml::{XmlVersion, events::Event}; + use quick_xml::{escape::unescape, events::Event}; let mut reader = quick_xml::Reader::from_reader(data); let mut targets = HashMap::new(); loop { @@ -78,16 +79,15 @@ fn relationships(data: &[u8]) -> Result> { let mut target = None; for attribute in element.attributes() { let attribute = attribute.map_err(|e| DataError::Format(format!("XLSB workbook relationships: {e}")))?; - if matches!(attribute.key.as_ref(), "Id" | "Target") { - let value = attribute - .normalized_value(XmlVersion::Implicit1_0) - .map_err(|e| DataError::Format(format!("XLSB workbook relationships: {e}")))? - .into_owned(); - if attribute.key.as_ref() == "Id" { - id = Some(value); - } else { - target = Some(value); - } + if attribute.key.as_ref() == "Id" { + // calamine compares the raw ID with the workbook's UTF-16 key. + id = Some(attribute.value.into_owned()); + } else if attribute.key.as_ref() == "Target" { + target = Some( + unescape(&attribute.value) + .map_err(|e| DataError::Format(format!("XLSB workbook relationships: {e}")))? + .into_owned(), + ); } } if let (Some(id), Some(target)) = (id, target) { @@ -135,14 +135,30 @@ fn damaged() -> DataError { /// Only record boundaries are interpreted; bytes resembling a record inside cell data are ignored. fn check_sheet(mut data: &[u8]) -> Result<()> { - let mut in_data = false; + let (mut dimensions, mut in_data) = (false, false); + let mut skip_until = None; while let Some((kind, _)) = record(&mut data)? { crate::progress::check()?; - if kind == 145 { - // BrtBeginSheetData - in_data = true; - } else if kind == 146 && in_data { - // BrtEndSheetData + // Match XlsbCellsReader's search: dimensions first, then data after view/AC/column + // blocks. Markers skipped in either search cannot terminate the later cell stream. + if !dimensions { + dimensions = kind == 0x94; + } else if !in_data { + if let Some(end) = skip_until { + if kind == end { + skip_until = None; + } + } else if kind == 0x91 { + in_data = true; + } else { + skip_until = match kind { + 0x85 => Some(0x86), + 0x25 => Some(0x26), + 0x186 => Some(0x187), + _ => None, + }; + } + } else if kind == 0x92 { return Ok(()); } // calamine 0.38 skips these short-cell encodings without yielding their values. @@ -252,9 +268,48 @@ mod tests { } } - /// An end marker before sheet data cannot hide cells the workbook reader still consumes. + /// Case aliases of relationship parts cannot redirect preflight from the reader's exact part. #[test] - fn early_end_marker_does_not_bypass_short_cell_checks() { + fn relationship_part_lookup_matches_the_reader() { + let clean = crate::zip::read(include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb")).unwrap(); + let clean_sheet = &clean.iter().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + for short in [false, true] { + let original: &[u8] = if short { + include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb") + } else { + include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") + }; + for variant_last in [false, true] { + let mut entries = crate::zip::read(original).unwrap(); + let rels = &entries.iter().find(|(name, _)| name == "xl/_rels/workbook.bin.rels").unwrap().1; + let variant = ( + "XL/_RELS/WORKBOOK.BIN.RELS".into(), + String::from_utf8(rels.clone()).unwrap().replace("sheet1.bin", "other.bin").into_bytes(), + ); + if variant_last { + entries.push(variant); + } else { + entries.insert(0, variant); + } + entries.push(("xl/worksheets/other.bin".into(), clean_sheet.clone())); + let bytes = crate::zip::write(&entries).unwrap(); + let result = crate::sheets::read(&bytes, "a", None, &Default::default()); + if short { + assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records")); + } else { + let (ds, report) = result.unwrap(); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert!(report.messages.is_empty()); + } + } + } + } + + /// Escaped relationship IDs remain distinct, as they do in the workbook reader's raw lookup. + #[test] + fn relationship_ids_match_the_readers_raw_keys() { + let clean = crate::zip::read(include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb")).unwrap(); + let clean_sheet = &clean.iter().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; for short in [false, true] { let original: &[u8] = if short { include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb") @@ -262,21 +317,58 @@ mod tests { include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") }; let mut entries = crate::zip::read(original).unwrap(); - let sheet = &mut entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; - sheet.splice(..0, [0x92, 0x01, 0]); + let rels = &mut entries.iter_mut().find(|(name, _)| name == "xl/_rels/workbook.bin.rels").unwrap().1; + *rels = String::from_utf8(rels.clone()) + .unwrap() + .replace("", r#""#) + .into_bytes(); + entries.push(("xl/worksheets/other.bin".into(), clean_sheet.clone())); let bytes = crate::zip::write(&entries).unwrap(); let result = crate::sheets::read(&bytes, "a", None, &Default::default()); if short { assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records")); } else { let (ds, report) = result.unwrap(); - assert_eq!(ds.fields.len(), 2); assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); assert!(report.messages.is_empty()); } } } + /// Markers before dimensions or inside skipped metadata cannot hide cells the reader consumes. + #[test] + fn early_end_marker_does_not_bypass_short_cell_checks() { + for short in [false, true] { + let original: &[u8] = if short { + include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb") + } else { + include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") + }; + for (before_dimensions, prefix) in [ + (true, &[0x92, 0x01, 0][..]), + (true, &[0x91, 0x01, 0, 0x92, 0x01, 0][..]), + (false, &[0x85, 0x01, 0, 0x91, 0x01, 0, 0x92, 0x01, 0, 0x86, 0x01, 0][..]), + (false, &[0x25, 0, 0x91, 0x01, 0, 0x92, 0x01, 0, 0x26, 0][..]), + (false, &[0x86, 0x03, 0, 0x91, 0x01, 0, 0x92, 0x01, 0, 0x87, 0x03, 0][..]), + ] { + let mut entries = crate::zip::read(original).unwrap(); + let sheet = &mut entries.iter_mut().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + let at = if before_dimensions { 0 } else { sheet.windows(3).position(|b| b == [0x91, 0x01, 0]).unwrap() }; + sheet.splice(at..at, prefix.iter().copied()); + let bytes = crate::zip::write(&entries).unwrap(); + let result = crate::sheets::read(&bytes, "a", None, &Default::default()); + if short { + assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records")); + } else { + let (ds, report) = result.unwrap(); + assert_eq!(ds.fields.len(), 2); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert!(report.messages.is_empty()); + } + } + } + } + /// MS-XLSB 2.1.4 ignores the last size byte's high bit; both encodings retain the workbook. #[test] fn four_byte_record_sizes_ignore_the_last_high_bit() { @@ -303,7 +395,7 @@ mod tests { assert!(check_sheet(&[kind, 0]).unwrap_err().to_string().contains("short-cell")); check_sheet(&[6, 2, kind, 0]).unwrap(); } - check_sheet(&[0x91, 0x01, 0, 0x92, 0x01, 0, 6, 0xff]).unwrap(); + check_sheet(&[0x94, 0x01, 0, 0x91, 0x01, 0, 0x92, 0x01, 0, 6, 0xff]).unwrap(); for bytes in [&[0x81][..], &[0x81, 0x80], &[6, 0x80], &[6, 2, 0], &[6, 0xff, 0xff, 0xff, 0xff]] { assert!(check_sheet(bytes).unwrap_err().to_string().contains("cut short")); } From 58d11393acfa04ec0bae159e339645fd98658811 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 03:09:10 -0600 Subject: [PATCH 11/16] fix(data): classify TIFF copyright losses on read and export --- crates/data/src/loss.rs | 8 ++++---- crates/data/src/raster/cog.rs | 15 ++++++++++++++- crates/data/src/raster/geotiff.rs | 14 +++++++++++++- crates/data/src/raster/mod.rs | 8 ++++++++ crates/engine/src/cmd/raster.rs | 14 +++++++++----- crates/engine/src/cmd/share.rs | 12 +++++++++--- crates/engine/src/tests.rs | 6 ++++++ docs/user-guide/loss-codes.md | 12 ++++++------ 8 files changed, 69 insertions(+), 20 deletions(-) diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index c723d23595..2f2add709d 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -92,8 +92,8 @@ loss_codes! { DroppedCopyright => ( "dropped.copyright", Dropped, - "An input raster's copyright differs from the first input's and was not kept in the mosaic.", - "Keep the source credits and include the required attribution when sharing the mosaic." + "Copyright text could not be read or written in a raster's tag, or differs from the first input's and was not kept in the mosaic.", + "Keep the source credits and include the required attribution when sharing the raster." ), DroppedValue => ( "dropped.value", @@ -182,8 +182,8 @@ loss_codes! { ChangedEncoding => ( "changed.encoding", Changed, - "Text that is not valid in the encoding it was read with was read with a replacement character in its place.", - "Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8." + "Text could not be represented in its source or destination encoding, so replacement characters or equivalent ASCII text were used.", + "Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8. TIFF copyright tags hold ASCII only; keep the original credits with the exported file." ), ChangedRounded => ( "changed.rounded", diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index bed6e247ce..b32b6ded95 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -411,7 +411,7 @@ fn read_layout(r: Sparse) -> Result { let copyright = match super::geotiff::copyright_of(tag(&mut dec, Tag::Copyright)?) { Ok(c) => c, Err(said) => { - lost.push(said); + lost.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedCopyright, said)); None } }; @@ -1231,6 +1231,19 @@ pub(crate) mod tests { let file = super::super::cogwrite::write(&r, 0).unwrap(); let credited = layout_of(file.clone()); assert_eq!(credited.copyright.as_deref(), Some("Example Survey")); + // A supplied tag of the wrong TIFF type is omitted and classified on both read routes. + let mut bad = file.clone(); + let ifd = u32::from_le_bytes(bad[4..8].try_into().unwrap()) as usize; + let n = u16::from_le_bytes(bad[ifd..ifd + 2].try_into().unwrap()) as usize; + let entry = (0..n).map(|i| ifd + 2 + i * 12).find(|&e| bad[e..e + 2] == 33432u16.to_le_bytes()).unwrap(); + bad[entry + 2..entry + 4].copy_from_slice(&1u16.to_le_bytes()); + let omitted = layout_of(bad.clone()); + assert!(omitted.copyright.is_none()); + let full = super::super::geotiff::read(std::io::Cursor::new(bad), "bad").unwrap(); + for notes in [&omitted.lost, &full.lost] { + let note = notes.iter().find(|n| n.text.starts_with("its Copyright tag:")).unwrap(); + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedCopyright)); + } // Everything but the tag's own bytes held: the layout asks for them rather than say the // copyright is lost, and reads it once they are in. let at = file.windows(14).position(|w| w == b"Example Survey").unwrap(); diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 9b9e5c1333..dafa66f65b 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1780,7 +1780,7 @@ fn read_image( // doesn't read as text is left out, and said. let (copyright, copyright_lost) = match copyright_tag(&mut dec) { Ok(c) => (c, None), - Err(e) => (None, Some(e)), + Err(e) => (None, Some(crate::loss::Note::loss(crate::loss::LossCode::DroppedCopyright, e))), }; let spp = samples(&mut dec); let full_alpha = extra_alpha(&mut dec); @@ -2900,6 +2900,14 @@ mod tests { super::super::tag_text_note("\0\n").as_deref(), Some("the credits hold nothing a Copyright tag can, so the file has none") ); + for (text, code) in [ + ("© a\nb ü", Some(crate::loss::LossCode::ChangedEncoding)), + ("\0\n", Some(crate::loss::LossCode::DroppedCopyright)), + ("plain", None), + ("", None), + ] { + assert_eq!(super::super::tag_text_loss(text).and_then(|n| n.loss), code); + } let mut blank = small(); blank.copyright = Some("\0\n".into()); assert_eq!(read(std::io::Cursor::new(write(&blank, 0).unwrap()), "none").unwrap().copyright, None); @@ -2913,6 +2921,10 @@ mod tests { } let odd = read(std::io::Cursor::new(buf.into_inner()), "odd").unwrap(); assert_eq!(odd.copyright, None); + assert_eq!( + odd.lost.iter().find(|n| n.text.starts_with("its Copyright tag:")).unwrap().loss, + Some(crate::loss::LossCode::DroppedCopyright) + ); assert!(odd.lost.iter().any(|l| l.starts_with("its Copyright tag: it isn't ASCII text")), "{:?}", odd.lost); assert_eq!(super::super::tag_text("a\nb\u{85}c ü"), "a b c ?"); // A scan (a TIFF with no GeoTIFF tags) keeps it too. diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 7e07700611..9760c01f33 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -887,6 +887,14 @@ pub fn tag_text_note(s: &str) -> Option { (!parts.is_empty()).then(|| format!("the Copyright tag holds ASCII only, so it is written with {}", parts.join(", "))) } +/// The export's copyright notice with its loss code: an omitted tag differs from text +/// represented with substitutions in ASCII. The text-only API remains [`tag_text_note`]. +pub fn tag_text_loss(s: &str) -> Option { + let text = tag_text_note(s)?; + let code = if tag_text(s).is_empty() { crate::loss::LossCode::DroppedCopyright } else { crate::loss::LossCode::ChangedEncoding }; + Some(crate::loss::Note::loss(code, text)) +} + /// How many of the names [`gdal_metadata_of`] writes for `bands` hold a character XML can't (a /// control character), which is written as a space: for a writer to say. pub fn gdal_metadata_changed(r: &Raster, bands: &[usize]) -> usize { diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 4e27a13943..c17914df82 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1485,6 +1485,9 @@ pub fn geotiff_bytes(s: &mut Session, p: &Value) -> Result<(String, Vec), St if !note.is_empty() { s.notify(format!("Exported {}.tif{note}", r.name), false); } + if let Some(note) = r.copyright.as_deref().and_then(raster::tag_text_loss) { + s.say(note.prefixed(&format!("{}.tif", r.name))); + } Ok((r.name.clone(), bytes)) } @@ -1622,11 +1625,16 @@ fn wrote_geotiff( if let (Some(o), Some(c)) = (v.as_object_mut(), cog) { o.insert("cog".into(), json!({"overviews": c.levels.len().saturating_sub(1), "bigTiff": c.big, "bytes": c.bytes})); } + let mut notes = rustgis_data::loss::Notes::new(); + if let Some(note) = r.copyright.as_deref().and_then(raster::tag_text_loss) { + notes.push(note.prefixed(path)); + } + notes.push(format!("Exported {path}{note}")); Ok(super::exports::Wrote { answer: v, diagnostics: Vec::new(), refused_notes: Vec::new(), - notes: [format!("Exported {path}{note}")].into_iter().collect(), + notes, written_path: Some(path.to_string()), download: None, then: None, @@ -1679,10 +1687,6 @@ fn geotiff_note(r: &Raster, bi: usize, cog: bool, band_hint: &str) -> Result 0 { note.push_str(&format!("; {spaced} band or class name(s) held control characters, written as spaces")); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 9b471029bb..11b472fc8a 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -567,6 +567,7 @@ fn geotiff_work( Ok(Box::new(move || { let mut notices = notices; let mut held = None; + let mut copyright_loss = None; let written = (|| { let placed = rustgis_render::render_placed(&mut map, &view)?; rustgis_data::progress::check().map_err(|e| e.to_string())?; @@ -605,12 +606,12 @@ fn geotiff_work( } if let Some(c) = &r.copyright { out["copyright"] = json!(c); - if let Some(note) = rustgis_data::raster::tag_text_note(c) { + if let Some(note) = rustgis_data::raster::tag_text_loss(c) { // Quoted (control characters escaped, so a service's credits can't reach a // terminal raw) and cut short: the answer holds them whole. let shown: String = c.chars().take(CREDITS_SHOWN).collect(); let more = if c.chars().count() > CREDITS_SHOWN { "…" } else { "" }; - notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {shown:?}{more})"))); + copyright_loss = Some(note.map_text(|text| format!("{path}: {text} (the credits: {shown:?}{more})"))); } } Ok(out) @@ -619,7 +620,12 @@ fn geotiff_work( if written.is_ok() { notices.splice(0..0, sized); } - super::exports::drawn(std::slice::from_ref(&map), notices, written, path).map(|wrote| Wrote { download: held, ..wrote }) + super::exports::drawn(std::slice::from_ref(&map), notices, written, path).map(|mut wrote| { + if let Some(note) = copyright_loss { + wrote.notes.insert(0, note); + } + Wrote { download: held, ..wrote } + }) })) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ede78ddcdc..54192410bd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33197,6 +33197,9 @@ fn raster_export_paths_report_band_class_and_credit_changes() { ] { assert!(notes.contains(text), "missing {text}: {notes}"); } + let credits: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("Copyright tag holds ASCII")).collect(); + assert_eq!(credits.len(), 1); + assert_eq!(credits[0].loss, Some(rustgis_data::loss::LossCode::ChangedEncoding)); let written = rustgis_data::raster::read_bytes("written.tif", bytes).unwrap(); assert_eq!(written.band_count(), 3); assert_eq!(written.bands[0].name, "red name"); @@ -60814,6 +60817,9 @@ fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { "{:?}", s.notices ); + let credits: Vec<_> = s.notices.iter().filter(|n| n.text.contains("Copyright tag holds ASCII")).collect(); + assert_eq!(credits.len(), 1); + assert_eq!(credits[0].loss, Some(rustgis_data::loss::LossCode::ChangedEncoding)); // The tiles had all come: nothing says the picture has gaps. assert!(!s.notices.iter().any(|n| n.text.contains("export again once")), "{:?}", s.notices); // The middle pixel is the tile's red. diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 9c947c927b..d586525032 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -58,11 +58,11 @@ A column was left out because its type cannot be held, its name repeats an earli ### `dropped.copyright` { #dropped.copyright } -An input raster's copyright differs from the first input's and was not kept in the mosaic. +Copyright text could not be read or written in a raster's tag, or differs from the first input's and was not kept in the mosaic. -**Where you see it:** Mosaic Rasters. +**Where you see it:** reading a GeoTIFF or COG; exporting a raster or map as GeoTIFF or COG; Mosaic Rasters. -**What to do:** Keep the source credits and include the required attribution when sharing the mosaic. +**What to do:** Keep the source credits and include the required attribution when sharing the raster. ### `dropped.value` { #dropped.value } @@ -182,11 +182,11 @@ Longitude and latitude on a body other than the Earth were written as Earth coor ### `changed.encoding` { #changed.encoding } -Text that is not valid in the encoding it was read with was read with a replacement character in its place. +Text could not be represented in its source or destination encoding, so replacement characters or equivalent ASCII text were used. -**Where you see it:** reading a Shapefile or dBASE file, a DXF drawing, or feature service answers in PBF. +**Where you see it:** reading a Shapefile or dBASE file, a DXF drawing, or feature service answers in PBF; exporting copyright text in a GeoTIFF or COG. -**What to do:** Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8. +**What to do:** Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8. TIFF copyright tags hold ASCII only; keep the original credits with the exported file. ### `changed.rounded` { #changed.rounded } From 39284ce769495162a3b9324fba0c68418cc9d9b0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 08:15:06 -0600 Subject: [PATCH 12/16] fix(data): count short polyface faces in loss reports --- ROADMAP.md | 4 ++-- crates/data/src/dxf.rs | 34 ++++++++++++++++++---------------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 4d7c1d7178..6263b7538c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -69,8 +69,8 @@ The shared pieces the everyday workflow stands on. ### Correct results A result is right, or RustGIS says what it lost or assumed ([AGENTS.md](AGENTS.md#never-silent)). -- Known silent losses still to cover: DXF unreadable extrusion Z (group 230), short polyface - faces and the polyface vertex-record cap; XLSB cached formula errors (`BrtFmlaError`) and +- Known silent losses still to cover: DXF unreadable extrusion Z (group 230) and the polyface + vertex-record cap; XLSB cached formula errors (`BrtFmlaError`) and rich inline strings (`BrtCellRString`) skipped by the workbook reader _(open)_. - Lossy sample files in `never_silent_reading.rs` for the readers it doesn't cover yet: remaining distinct loss families and parser paths (see the finite diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index a2a80cb4eb..ec45e9797e 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -428,7 +428,7 @@ struct PathLoss { missing_y: u64, invalid_z: u64, short_rings: u64, - missing_faces: u64, + unreadable_faces: u64, unreadable_z: u64, } @@ -439,7 +439,7 @@ impl PathLoss { self.missing_y = self.missing_y.saturating_add(other.missing_y); self.invalid_z = self.invalid_z.saturating_add(other.invalid_z); self.short_rings = self.short_rings.saturating_add(other.short_rings); - self.missing_faces = self.missing_faces.saturating_add(other.missing_faces); + self.unreadable_faces = self.unreadable_faces.saturating_add(other.unreadable_faces); self.unreadable_z = self.unreadable_z.saturating_add(other.unreadable_z); } } @@ -1048,8 +1048,8 @@ fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { None => missing = true, } } - if missing { - loss.missing_faces += 1; + if missing || ring.len() < 3 { + loss.unreadable_faces += 1; continue; } if ring.len() >= 3 { @@ -1738,9 +1738,10 @@ fn emit( continue; }; if from.invalid_placement { - return Err(DataError::Format( - "a placed block has an unreadable supplied coordinate; correct its base or insertion point before importing".into(), - )); + return Err(DataError::Format(format!( + "cannot place block {:?}: its placement path has an unreadable supplied coordinate; correct the block base or insertion point before importing", + from.block.unwrap_or("unknown") + ))); } let attrs = vec![ Value::Text(layer.to_string()), @@ -1948,9 +1949,9 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = layers[0].1.messages.iter().filter(|n| n.loss == Some(crate::loss::LossCode::DroppedRing)).collect(); assert_eq!(notes.len(), usize::from(bad)); if bad { - assert_eq!(notes[0].text, "1 polyface face with a missing vertex was left out"); + assert_eq!(notes[0].text, "1 polyface face with missing or too few vertices was left out"); } } } @@ -2451,7 +2452,7 @@ mod tests { assert_eq!(unreadable[0].text, "1 unreadable supplied Z value could not be kept"); assert_eq!( rings[0].text, - "1 polyface face with a missing vertex was left out; 1 short HATCH boundary ring was left out of polygons" + "1 polyface face with missing or too few vertices was left out; 1 short HATCH boundary ring was left out of polygons" ); } } @@ -2552,7 +2553,8 @@ mod tests { ); let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; let opts = Options { crs: Some(Crs::LonLat), ..Options::default() }; - assert!(read("a.dxf", bytes.as_bytes(), &opts).unwrap_err().to_string().contains("unreadable supplied coordinate")); + let error = read("a.dxf", bytes.as_bytes(), &opts).unwrap_err().to_string(); + assert!(error.contains("unreadable supplied coordinate") && error.contains("block \"b\""), "{error}"); assert!(layers("a.dxf", bytes.as_bytes()).is_ok()); assert!(read("a.dxf", bytes.as_bytes(), &Options { blocks: false, ..opts }).is_ok()); assert!(read("a.dxf", bytes.as_bytes(), &Options { layer: Some("safe"), ..opts }).is_ok()); From 74b3ebc09f19b248b23059fcb9a792666ffc70f0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 09:30:24 -0600 Subject: [PATCH 13/16] test(engine): align the polyface loss notice expectation --- crates/engine/tests/integration/never_silent_reading.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index aecc1d68f1..d95ac27509 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -541,7 +541,7 @@ pub(super) fn cases(fixture_dir: &std::path::Path) -> Vec { case("DXF: a polyface face with a missing vertex", "a.dxf", dxf(&["0 POLYLINE 70 64 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 0 VERTEX 70 128 71 1 72 2 73 3 0 VERTEX 70 128 71 1 72 2 73 3 74 0 0 SEQEND"]), dxf(&["0 POLYLINE 70 64 0 VERTEX 70 64 10 0 20 0 0 VERTEX 70 64 10 1 20 0 0 VERTEX 70 64 10 0 20 1 0 VERTEX 70 128 71 1 72 2 73 3 0 VERTEX 70 128 71 1 72 2 73 3 74 99 0 SEQEND"]), - Expect::Classified(LossCode::DroppedRing, "1 polyface face with a missing vertex was left out")), + Expect::Classified(LossCode::DroppedRing, "1 polyface face with missing or too few vertices was left out")), ]); out.extend([ From 039804d74130a21446faf86da7b4bedb4e31a090 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 11:20:29 -0600 Subject: [PATCH 14/16] fix(data): report polyface caps and reject duplicate XLSB parts --- ROADMAP.md | 3 +- crates/data/src/dxf.rs | 78 +++++++++++++++++++++++++--------- crates/data/src/sheets/xlsb.rs | 37 +++++++++++++++- 3 files changed, 95 insertions(+), 23 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6263b7538c..bc90a6afc2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -69,8 +69,7 @@ The shared pieces the everyday workflow stands on. ### Correct results A result is right, or RustGIS says what it lost or assumed ([AGENTS.md](AGENTS.md#never-silent)). -- Known silent losses still to cover: DXF unreadable extrusion Z (group 230) and the polyface - vertex-record cap; XLSB cached formula errors (`BrtFmlaError`) and +- Known silent losses still to cover: DXF unreadable extrusion Z (group 230); XLSB cached formula errors (`BrtFmlaError`) and rich inline strings (`BrtCellRString`) skipped by the workbook reader _(open)_. - Lossy sample files in `never_silent_reading.rs` for the readers it doesn't cover yet: remaining distinct loss families and parser paths (see the finite diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index ec45e9797e..20fbb59049 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1017,6 +1017,7 @@ fn measure(v: f64) -> String { /// A polyface mesh's faces as polygons (its VERTEX records: positions, then faces by index). fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { + loss.capped += vertices.len().saturating_sub(MAX_VERTICES) as u64; let mut pos: Vec = Vec::new(); let mut faces: Vec> = Vec::new(); let mut unreadable_z = Vec::new(); @@ -1052,24 +1053,22 @@ fn polyface(vertices: &[Record], loss: &mut PathLoss) -> Option { loss.unreadable_faces += 1; continue; } - if ring.len() >= 3 { - for index in referenced { - if let Some(bad) = unreadable_z.get_mut(index) - && *bad - { - loss.unreadable_z += 1; - *bad = false; - } - } - let mut r = ring; - if let Some(f) = r.first().copied() { - r.push(f); + for index in referenced { + if let Some(bad) = unreadable_z.get_mut(index) + && *bad + { + loss.unreadable_z += 1; + *bad = false; } - faces.push(r); } + let mut r = ring; + if let Some(f) = r.first().copied() { + r.push(f); + } + faces.push(r); } } - (!faces.is_empty()).then_some(Shape::Rings { rings: faces, constant_z: false }) + (!faces.is_empty() || loss.capped > 0).then_some(Shape::Rings { rings: faces, constant_z: false }) } /// A cursor over a record's groups, read in order (HATCH boundary paths). @@ -1432,6 +1431,8 @@ struct Out { /// Sparse recovery metadata, indexed before CRS filtering in each geometry layer. losses: [Vec<(usize, PathLoss)>; 3], capped: bool, + /// Capped records of selected polyfaces which yielded no geometry. + discarded_cap: u64, cut: usize, /// Entity placements visited so far ([`MAX_STEPS`]), and whether the budget ran out. steps: usize, @@ -1734,6 +1735,7 @@ fn emit( Shape::Insert(_) => continue, }; let Some(geometry) = geometry else { + out.discarded_cap = out.discarded_cap.saturating_add(loss.capped); out.cut += 1; continue; }; @@ -1799,6 +1801,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = Vec::new(); let mut varying_count = 0usize; - let mut recovered = PathLoss::default(); + let mut recovered = PathLoss { capped: out.discarded_cap, ..PathLoss::default() }; for ((mut ds, flags), losses) in [out.points, out.lines, out.polygons].into_iter().zip(out.varying_z).zip(out.losses) { if ds.features.is_empty() { continue; @@ -1957,8 +1960,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>(), - [format!("{} polyline path coordinates were left out at the per-entity vertex limit", (vertices - kept_segments) * 36,)] + [format!( + "{} DXF vertex records or generated coordinates were left out at the per-entity vertex limit", + (vertices - kept_segments) * 36, + )] ); } @@ -2203,6 +2209,38 @@ mod tests { } } + /// A generated boundary fixture exercises the real cap without keeping a large asset. + #[test] + fn polyface_vertex_record_cap_is_counted() { + let opts = Options { crs: Some(Crs::LonLat), ..Options::default() }; + for (over, retained_face) in [(false, true), (true, true), (true, false)] { + let mut text = String::from("0\nSECTION\n2\nENTITIES\n0\nPOINT\n10\n3\n20\n3\n0\nPOLYLINE\n70\n64\n"); + text.push_str("0\nVERTEX\n70\n64\n10\n0\n20\n0\n0\nVERTEX\n70\n64\n10\n1\n20\n0\n0\nVERTEX\n70\n64\n10\n0\n20\n1\n"); + let face = "0\nVERTEX\n70\n128\n71\n1\n72\n2\n73\n3\n"; + if retained_face { + text.push_str(face); + } + for _ in 3 + usize::from(retained_face)..MAX_VERTICES { + text.push_str("0\nVERTEX\n70\n64\n10\n0\n20\n0\n"); + } + if over { + text.push_str(if retained_face { "0\nVERTEX\n70\n64\n10\n0\n20\n0\n" } else { face }); + } + text.push_str("0\nSEQEND\n0\nENDSEC\n0\nEOF\n"); + let layers = read("a.dxf", text.as_bytes(), &opts).unwrap(); + let notices: Vec<_> = layers + .iter() + .flat_map(|(_, r)| r.messages.iter()) + .filter(|n| n.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .collect(); + assert_eq!(notices.len(), usize::from(over)); + if over { + assert!(notices[0].text.starts_with("1 ") && notices[0].text.contains("per-entity vertex limit")); + } + assert_eq!(layers.iter().map(|(d, _)| d.features.len()).sum::(), 1 + usize::from(retained_face)); + } + } + /// A missing face reference must not turn a four-vertex face into a different triangle. #[test] fn loss_coverage_polyface_missing_vertex() { @@ -2777,9 +2815,9 @@ mod tests { assert_eq!( layers[0].1.messages.texts().collect::>(), [format!( - "{} polyline path {} left out at the per-entity vertex limit", + "{} DXF vertex {} left out at the per-entity vertex limit", total - held, - if total - held == 1 { "coordinate was" } else { "coordinates were" } + if total - held == 1 { "record or generated coordinate was" } else { "records or generated coordinates were" } )] ); assert_eq!(layers[0].1.skipped, 0); diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index 31121701d5..9f92edd686 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -2,7 +2,7 @@ //! Record framing follows [MS-XLSB] §2.1.4 (not the undocumented short-cell payloads): //! . -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use crate::{DataError, Result}; @@ -16,8 +16,16 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { return Ok(()); } let mut parts = HashMap::new(); + // Duplicate exact names change the unique-name ordering used by calamine's ZIP cache. + // Refuse that ambiguity rather than check a different payload from the reader. + let mut exact_names = HashSet::new(); for (name, data) in entries { crate::progress::check()?; + if !exact_names.insert(name.as_str()) { + return Err(DataError::Unsupported(format!( + "repeated XLSB package part {name:?}; save a copy of the workbook as XLSX and open that copy" + ))); + } parts.insert(part_name(name), (name.as_str(), data.as_slice())); } let Some((_, mut workbook)) = parts.get("xl/workbook.bin").copied() else { return Ok(()) }; @@ -268,6 +276,33 @@ mod tests { } } + /// Ordinary case aliases follow the reader; repeated exact names must not reorder that lookup. + #[test] + fn binary_aliases_and_duplicate_names_cannot_bypass_preflight() { + let clean = crate::zip::read(include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb")).unwrap(); + let short = crate::zip::read(include_bytes!("../../../engine/testdata/reading-losses/book-short.xlsb")).unwrap(); + let clean_sheet = &clean.iter().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + let short_sheet = &short.iter().find(|(name, _)| name == "xl/worksheets/sheet1.bin").unwrap().1; + for (alias_short, duplicate) in [(false, false), (true, false), (true, true)] { + let mut entries = short.clone(); + entries.push(("XL/Worksheets/Sheet1.bin".into(), if alias_short { short_sheet.clone() } else { clean_sheet.clone() })); + if duplicate { + entries.push(("xl/worksheets/sheet1.bin".into(), clean_sheet.clone())); + } + let bytes = crate::zip::write(&entries).unwrap(); + let result = crate::sheets::read(&bytes, "a", None, &Default::default()); + if duplicate { + assert!(result.unwrap_err().to_string().contains("repeated XLSB package part")); + } else if alias_short { + assert!(result.unwrap_err().to_string().contains("unsupported XLSB short-cell records")); + } else { + let (ds, report) = result.unwrap(); + assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Null]); + assert!(report.messages.is_empty()); + } + } + } + /// Case aliases of relationship parts cannot redirect preflight from the reader's exact part. #[test] fn relationship_part_lookup_matches_the_reader() { From fb9cf6cb6498e5f916a9e7d08941ff00f9039e50 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 12:05:20 -0600 Subject: [PATCH 15/16] fix(data): report unreadable dimension fallback labels --- crates/data/src/dxf.rs | 43 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 20fbb59049..16a72b4e84 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -362,6 +362,8 @@ impl Xf { #[derive(Clone, Debug)] enum Shape { Point(P3), + /// A supplied fallback label with unreadable coordinates, counted only when used. + UnreadablePoint, /// `constant_z` records a construction proof, not a comparison of rounded samples. Line { points: Vec, @@ -1003,8 +1005,10 @@ fn dimension(g: &G, loss: &mut PathLoss) -> (Vec, Option) { _ => measure(length), }; let mut shapes = vec![Shape::line(vec![a, b]), Shape::line(vec![p13, a]), Shape::line(vec![p14, b])]; - if let Some(t) = used_point(g, 11, loss) { - shapes.push(Shape::Point(t)); + match optional_used_point(g, 11, loss) { + Some(Some(t)) => shapes.push(Shape::Point(t)), + Some(None) => {} + None => shapes.push(Shape::UnreadablePoint), } (shapes, Some(text)) } @@ -1671,7 +1675,7 @@ fn emit( 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::UnreadablePoint => 0, }; if out.vertices.saturating_add(n) > MAX_TOTAL_VERTICES { out.vertex_capped = true; @@ -1682,6 +1686,10 @@ fn emit( let tr = |ps: &[P3]| -> Vec { ps.iter().map(|p| xf.apply(*p)).collect() }; let mut loss = e.loss; let (geometry, first, target, varying_z) = match &e.shape { + Shape::UnreadablePoint => { + out.bad += 1; + continue; + } Shape::Point(p) => { let p = xf.apply(*p); (finite(&[p]).then(|| Geometry::Point(xy(p))), Some(p), 0, false) @@ -2038,6 +2046,8 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>().join("\n") + "\n"; + let opts = Options { crs: Some(Crs::LonLat), ..Options::default() }; + let got = read("a.dxf", bytes.as_bytes(), &opts).unwrap(); + assert_eq!(got.iter().map(|(d, _)| d.features.len()).sum::(), 1 + if exists { 1 } else { count }); + let notes: Vec<_> = got + .iter() + .flat_map(|(_, r)| r.messages.iter()) + .filter(|n| n.loss == Some(crate::loss::LossCode::DroppedFeature)) + .collect(); + assert_eq!(notes.len(), if exists { 0 } else { skipped }); + assert_eq!(got[0].1.skipped, if exists { 0 } else { skipped }); + let filtered = read("a.dxf", bytes.as_bytes(), &Options { layer: Some("safe"), ..opts }).unwrap(); + assert_eq!(filtered[0].0.features.len(), 1); + assert!(filtered[0].1.messages.is_empty()); + } + } + } + /// A dimension uses its available block, so unused fallback heights must not refuse it. #[test] fn dimension_ignores_unused_fallback_heights() { From 4f75a6ac19fdb1f8bd65800a9a1fd27e540c2e08 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 12:46:54 -0600 Subject: [PATCH 16/16] fix(data): preserve header heights and reject unreadable insert transforms --- crates/data/src/dxf.rs | 96 +++++++++++++++++++++++++++++++--- crates/data/src/sheets/xlsb.rs | 6 ++- 2 files changed, 93 insertions(+), 9 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 16a72b4e84..fef0cc4ec8 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -672,6 +672,24 @@ fn used_point(g: &G, x: i32, loss: &mut PathLoss) -> Option { Some(point) } +/// A constant elevation consumes only its Z group, independently of unused header XY. +fn used_elevation(g: &G, code: i32, loss: &mut PathLoss) -> f64 { + loss.unreadable_z += u64::from(g.s(code).is_some() && g.f(code).is_none()); + g.f(code).unwrap_or(0.0) +} + +/// Invalid supplied transforms reject the placed children rather than silently using defaults. +fn insert_point(g: &G, loss: &mut PathLoss) -> Option { + let point = placement_point(g, loss)?; + if [41, 42, 43, 50].into_iter().any(|c| g.s(c).is_some() && g.f(c).is_none()) + || [70, 71].into_iter().any(|c| g.s(c).is_some() && g.i(c).is_none()) + || [(44, 70), (45, 71)].into_iter().any(|(c, n)| g.i(n).unwrap_or(1) > 1 && g.s(c).is_some() && g.f(c).is_none()) + { + return None; + } + Some(point) +} + /// An optional point may be absent. Once any of its axes is supplied, its XY must be readable; /// the outer Option rejects malformed input, while the inner one preserves the format's omission. fn optional_used_point(g: &G, x: i32, loss: &mut PathLoss) -> Option> { @@ -737,7 +755,7 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - return None; } let three_d = flags & 8 != 0; - let z = if three_d { 0.0 } else { used_point(g, 10, loss).map(|p| p[2]).unwrap_or(0.0) }; + let z = if three_d { 0.0 } else { used_elevation(g, 30, loss) }; let curved = flags & 6 != 0; let mut vs = Vec::new(); for (index, v) in vertices.iter().enumerate() { @@ -914,12 +932,12 @@ fn entity(kind: &'static str, g: &G, vertices: &[Record], loss: &mut PathLoss) - }, "INSERT" => Shape::Insert(Insert { block: g.s(2)?.trim().to_string(), - at: placement_point(g, loss), + at: insert_point(g, loss), scale: [g.f(41).unwrap_or(1.0), g.f(42).unwrap_or(1.0), g.f(43).unwrap_or(1.0)], rotation: g.f(50).unwrap_or(0.0), extrusion: g.extrusion(), - cols: usize::try_from(g.i(70).unwrap_or(1)).unwrap_or(1).max(1), - rows: usize::try_from(g.i(71).unwrap_or(1)).unwrap_or(1).max(1), + cols: usize::try_from(g.i(70).unwrap_or(1).max(1)).unwrap_or(usize::MAX), + rows: usize::try_from(g.i(71).unwrap_or(1).max(1)).unwrap_or(usize::MAX), col_space: g.f(44).unwrap_or(0.0), row_space: g.f(45).unwrap_or(0.0), fallback: Vec::new(), @@ -1114,7 +1132,7 @@ impl Cursor<'_, '_> { /// A HATCH's boundary paths as rings (polyline paths with bulges, or edges: lines, arcs, elliptic /// arcs and splines), in its object coordinates at its elevation. fn hatch(g: &G, loss: &mut PathLoss) -> Option>> { - let z = used_point(g, 10, loss).map(|p| p[2]).unwrap_or(0.0); + let z = used_elevation(g, 30, loss); let mut cur = Cursor { p: g.p, at: 0 }; let paths = cur.count(91)?; let mut rings: Vec> = Vec::new(); @@ -1900,7 +1918,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>().join("\n") + "\n"; + let got = read("a.dxf", bytes.as_bytes(), &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); + assert_eq!(got[0].0.value(0, 8), &Value::Float(z), "{kind} {xy} {height}"); + let notes: Vec<_> = got.iter().flat_map(|(_, r)| r.messages.iter()).collect(); + assert_eq!(notes.len(), usize::from(lossy), "{kind} {xy} {height}"); + if lossy { + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedUnreadableZ)); + } + } + } + } + } + + /// Supplied transform parameters cannot silently become defaults; selected children are counted. + #[test] + fn unreadable_insert_transform_parameters_are_counted() { + for code in [41, 42, 43, 50, 44, 45, 70, 71] { + for bad in [false, true] { + let value = if bad { + "bad" + } else if code == 50 { + "0" + } else { + "1" + }; + let array = if code == 44 { + "70 2" + } else if code == 45 { + "71 2" + } else { + "" + }; + let copies = if matches!(code, 44 | 45) { 2 } else { 1 }; + let text = format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 b 0 LINE 8 roads 10 1 20 1 11 2 21 2 0 ENDBLK 0 ENDSEC 0 SECTION 2 ENTITIES 0 POINT 8 safe 10 3 20 3 0 INSERT 2 b {array} {code} {value} 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().join("\n") + "\n"; + let opts = Options { crs: Some(Crs::LonLat), ..Options::default() }; + let got = read("a.dxf", bytes.as_bytes(), &opts).unwrap(); + assert_eq!(got.iter().map(|(d, _)| d.features.len()).sum::(), 1 + if bad { 0 } else { copies }, "{code}"); + assert_eq!(got[0].1.skipped, if bad { copies } else { 0 }, "{code}"); + let notes: Vec<_> = got.iter().flat_map(|(_, r)| r.messages.iter()).collect(); + assert_eq!(notes.len(), usize::from(bad), "{code}"); + if bad { + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedFeature)); + } + let safe = read("a.dxf", bytes.as_bytes(), &Options { layer: Some("safe"), ..opts }).unwrap(); + assert!(safe[0].1.messages.is_empty()); + } + } + } + /// A supplied unreadable fallback label is counted only when that representation is used. #[test] fn dimension_fallback_reports_unreadable_text_point() { @@ -2888,7 +2970,7 @@ mod tests { assert_eq!( layers[0].1.messages.texts().collect::>(), [ - "1 entities couldn't be read or placed (unreadable coordinates or polyface faces, missing blocks, blocks nested too deep or in a cycle) and were left out" + "1 entities couldn't be read or placed (unreadable coordinates, placement parameters or polyface faces, 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)); diff --git a/crates/data/src/sheets/xlsb.rs b/crates/data/src/sheets/xlsb.rs index 9f92edd686..9685e1057e 100644 --- a/crates/data/src/sheets/xlsb.rs +++ b/crates/data/src/sheets/xlsb.rs @@ -22,6 +22,7 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { for (name, data) in entries { crate::progress::check()?; if !exact_names.insert(name.as_str()) { + let name = crate::io::cut(name, 160); return Err(DataError::Unsupported(format!( "repeated XLSB package part {name:?}; save a copy of the workbook as XLSX and open that copy" ))); @@ -58,10 +59,11 @@ pub(super) fn check(entries: &[(String, Vec)]) -> Result<()> { } let path = part_name(&format!("xl/{target}")); let (name, data) = parts.get(&path).ok_or_else(|| DataError::Format("an XLSB sheet part is missing".into()))?; + let shown = crate::io::cut(name, 160); check_sheet(data).map_err(|e| match e { DataError::Cancelled => e, - DataError::Unsupported(reason) => DataError::Unsupported(format!("spreadsheet part '{name}': {reason}")), - _ => DataError::Format(format!("spreadsheet part '{name}': {e}")), + DataError::Unsupported(reason) => DataError::Unsupported(format!("spreadsheet part {shown:?}: {reason}")), + _ => DataError::Format(format!("spreadsheet part {shown:?}: {e}")), })?; } Ok(())