diff --git a/ROADMAP.md b/ROADMAP.md index b5df85b253..bc90a6afc2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -69,11 +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: 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); 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..fef0cc4ec8 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" { @@ -359,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, @@ -383,8 +388,9 @@ impl Shape { #[derive(Clone, Debug)] struct Insert { block: String, - /// Insertion point, scale, rotation (degrees) and extrusion, in the insert's object coordinates. - at: P3, + /// 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, extrusion: P3, @@ -424,6 +430,8 @@ struct PathLoss { missing_y: u64, invalid_z: u64, short_rings: u64, + unreadable_faces: u64, + unreadable_z: u64, } impl PathLoss { @@ -433,6 +441,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.unreadable_faces = self.unreadable_faces.saturating_add(other.unreadable_faces); + self.unreadable_z = self.unreadable_z.saturating_add(other.unreadable_z); } } @@ -654,14 +664,56 @@ 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) +} + +/// 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> { + 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 { + 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 { let ocs = Xf::ocs(g.extrusion()); 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; @@ -696,14 +748,14 @@ 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. 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_elevation(g, 30, loss) }; let curved = flags & 6 != 0; let mut vs = Vec::new(); for (index, v) in vertices.iter().enumerate() { @@ -738,11 +790,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]) @@ -752,7 +804,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); @@ -829,7 +881,10 @@ 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 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]); } } Shape::line(pts) @@ -840,15 +895,22 @@ 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 { + 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(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 optional_used_point(g, 13, loss)? { Some(d) if d != c => ring.extend([d, c]), _ => ring.push(c), } @@ -856,9 +918,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) = optional_used_point(g, 13, loss)?.filter(|d| *d != c) { ring.push(d); } ring.push(a); @@ -870,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: g.pt(10).unwrap_or([0.0; 3]), + 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(), @@ -883,10 +945,10 @@ 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], + at: Some([0.0; 3]), scale: [1.0; 3], rotation: 0.0, extrusion: [0.0, 0.0, 1.0], @@ -909,7 +971,10 @@ 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 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]); } } if g.i(71).unwrap_or(0) & 2 != 0 @@ -926,9 +991,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); } @@ -956,8 +1023,10 @@ 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) { - 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)) } @@ -969,32 +1038,59 @@ 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 { + loss.capped += vertices.len().saturating_sub(MAX_VERTICES) as u64; let mut pos: Vec = Vec::new(); let mut faces: Vec> = Vec::new(); - for v in vertices.iter().take(MAX_VERTICES) { + let mut unreadable_z = Vec::new(); + 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 { pos.push(g.pt(10)?); + unreadable_z.push(g.s(30).is_some() && g.f(30).is_none()); } 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(); - if ring.len() >= 3 { - let mut r = ring; - if let Some(f) = r.first().copied() { - r.push(f); + 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 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, + } + } + if missing || ring.len() < 3 { + loss.unreadable_faces += 1; + continue; + } + 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). @@ -1036,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 = g.pt(10).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(); @@ -1155,11 +1251,18 @@ fn append(ring: &mut Vec, mut piece: Vec) { ring.extend(piece); } +/// A block's placement and entities; an unreadable supplied base coordinate is checked only if used. +struct Block { + base: P3, + entities: Vec, + invalid_placement: 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 +1291,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 +1320,21 @@ 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())); + let mut loss = PathLoss::default(); + let base = placement_point(&g, &mut loss); + block = Some(( + name, + Block { + base: base.unwrap_or([0.0; 3]), + entities: Vec::new(), + invalid_placement: base.is_none() || loss.unreadable_z > 0, + }, + )); 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 +1345,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 +1416,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 +1435,10 @@ struct Inherit<'a> { color: Option, linetype: Option<&'a str>, 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, } @@ -1337,6 +1453,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, @@ -1489,13 +1607,14 @@ fn emit( out.cut += 1; continue; } - let Some((base, inner)) = 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 .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 +1625,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)?; @@ -1529,7 +1648,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)) @@ -1540,8 +1659,12 @@ fn emit( color: Some(color), 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 { @@ -1560,13 +1683,17 @@ 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 { 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; @@ -1577,6 +1704,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) @@ -1630,9 +1761,16 @@ fn emit( Shape::Insert(_) => continue, }; let Some(geometry) = geometry else { + out.discarded_cap = out.discarded_cap.saturating_add(loss.capped); out.cut += 1; continue; }; + if from.invalid_placement { + 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()), Value::Text(e.kind.to_string()), @@ -1689,6 +1827,7 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result 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; @@ -1829,10 +1977,17 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> 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::DroppedUnreadableZ, + format!("{} unreadable supplied Z {what} could not be kept", recovered.unreadable_z), + )); + } if recovered.unreadable_vertices > 0 && let Some((_, report)) = layers.first_mut() { @@ -1890,6 +2054,24 @@ 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); + // Combined causes have separate counts and units in their text. + previous.tally = None; + } else { + grouped.push(note); + } + } + report.messages = grouped.into(); + } Ok(layers) } @@ -1920,7 +2102,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); } @@ -2021,7 +2203,10 @@ mod tests { assert_eq!(layers[0].1.skipped, 0); assert_eq!( layers[0].1.messages.texts().collect::>(), - [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, + )] ); } @@ -2052,6 +2237,570 @@ 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() { + for (third, fourth, bad) in [("3", "0", false), ("0", "0", true), ("3", "99", 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, third), + (74, fourth), + (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 missing or too few vertices was left out"); + } + } + } + + /// 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() { + for (kind, x, y, z) in [("LEADER", 10, 20, 30), ("MLINE", 11, 21, 31)] { + for height in ["5", "bad"] { + let text = format!( + "0 SECTION 2 ENTITIES 0 {kind} {x} 0 999 between {y} 0 999 height {z} {height} + {x} 1 999 between {y} 1 999 height {z} {height} 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[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() { + 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 missing or too few vertices was left out; 1 short HATCH boundary ring was left out of polygons" + ); + } + } + } + + /// Missing placement axes default to zero; supplied unreadable axes never place a block there. + #[test] + fn unreadable_placement_xy_never_draws_at_origin() { + for base in [false, true] { + for (point, inserted, based) in [ + ("", Some([1.0, 2.0]), Some([1.0, 2.0])), + ("10 0 20 0", Some([1.0, 2.0]), Some([1.0, 2.0])), + ("10 3 20 4", Some([4.0, 6.0]), Some([-2.0, -2.0])), + ("10 bad 20 0", None, None), + ("10 0 20 bad", None, None), + ("20 bad", None, None), + ("10 3", Some([4.0, 2.0]), Some([-2.0, 2.0])), + ("20 4", Some([1.0, 6.0]), Some([1.0, -2.0])), + ] { + let (base_point, insert_point) = if base { (point, "") } else { ("", point) }; + let text = format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 b {base_point} 0 POINT 10 1 20 2 0 ENDBLK 0 ENDSEC + 0 SECTION 2 ENTITIES 0 POINT 8 safe 10 9 20 9 0 INSERT 8 placed 2 b {insert_point} 0 ENDSEC 0 EOF" + ); + let bytes = text.split_whitespace().collect::>().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() { + 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::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"); + } + } + } + + /// 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() }; + 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()); + } + } + + /// Constant header height is independent of the unused header XY coordinates. + #[test] + fn header_elevations_do_not_depend_on_unused_xy() { + for kind in ["POLYLINE", "HATCH"] { + for xy in ["10 bad 20 bad", "10 0 20 0", ""] { + for (height, z, lossy) in [("30 5", 5.0, false), ("30 bad", 0.0, true), ("", 0.0, false)] { + let body = if kind == "HATCH" { + "91 1 92 2 72 0 73 1 93 3 10 0 20 0 10 2 20 0 10 0 20 2" + } else { + "0 VERTEX 10 0 20 0 0 VERTEX 10 2 20 2 0 SEQEND" + }; + let text = format!("0 SECTION 2 ENTITIES 0 {kind} {xy} {height} {body} 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.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() { + for exists in [false, true] { + for (point, count, skipped) in [("11 1 21 1", 4, 0), ("11 bad 21 1", 3, 1), ("21 bad", 3, 1), ("", 3, 0)] { + let block = if exists { "0 SECTION 2 BLOCKS 0 BLOCK 2 b 0 LINE 10 0 20 0 11 1 21 1 0 ENDBLK 0 ENDSEC" } else { "" }; + let text = format!( + "{block} 0 SECTION 2 ENTITIES 0 POINT 8 safe 10 3 20 3 0 DIMENSION 2 b 8 dim 10 0 20 1 13 0 23 0 14 2 24 0 {point} 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 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() { + 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"); + } + } + } + + /// 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::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"); + } + } + } + } + + /// 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| matches!(n.loss, Some(crate::loss::LossCode::DroppedZm | crate::loss::LossCode::DroppedUnreadableZ))) + ); + } + } + /// 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() { @@ -2185,9 +2934,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); @@ -2211,6 +2960,7 @@ mod tests { "0 SPLINE 71 3 11 0 21 0 11 1", "0 POLYLINE 70 8 0 VERTEX 10 0 20 0 30 bad 0 VERTEX 10 1 20 1 0 SEQEND", "0 HATCH 91 1 92 2 72 0 73 1 93 2 10 0 20 0 10 1 20 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 99 0 SEQEND", ] { let text = format!("0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 {body} 0 ENDSEC 0 EOF").split_whitespace().collect::>().join("\n"); @@ -2219,7 +2969,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, 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/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/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..65e2bab0a3 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..2f2add709d 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, 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", + Dropped, + "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", Dropped, @@ -101,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, @@ -131,6 +149,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 +164,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", @@ -158,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/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..9685e1057e --- /dev/null +++ b/crates/data/src/sheets/xlsb.rs @@ -0,0 +1,440 @@ +//! 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 std::collections::{HashMap, HashSet}; + +use crate::{DataError, Result}; + +/// 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") || name.eq_ignore_ascii_case(r"xl\workbook.bin")) { + 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()) { + 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" + ))); + } + parts.insert(part_name(name), (name.as_str(), data.as_slice())); + } + let Some((_, mut workbook)) = parts.get("xl/workbook.bin").copied() else { return Ok(()) }; + // 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(), + }; + 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()))?; + // 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; + } + 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 {shown:?}: {reason}")), + _ => DataError::Format(format!("spreadsheet part {shown:?}: {e}")), + })?; + } + 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::{escape::unescape, 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 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) { + 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 { + 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 || i + 1 == most { + 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<()> { + let (mut dimensions, mut in_data) = (false, false); + let mut skip_until = None; + while let Some((kind, _)) = record(&mut data)? { + crate::progress::check()?; + // 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. + // 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(), + )); + } + } + Ok(()) +} + +#[cfg(test)] +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() { + 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, 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}/{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; + *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])); + entries.push(("xl/worksheets/unused.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 == "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}"); + 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()); + } + } + } + } + + /// 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() { + 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") + } else { + include_bytes!("../../../engine/testdata/reading-losses/book-clean.xlsb") + }; + let mut entries = crate::zip::read(original).unwrap(); + 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.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() { + 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 { + assert!(check_sheet(&[kind, 0]).unwrap_err().to_string().contains("short-cell")); + check_sheet(&[6, 2, kind, 0]).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")); + } + } +} 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/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 d5e17b9e72..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"); @@ -33226,7 +33229,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(); } @@ -60812,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/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..d95ac27509 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::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"]), + Expect::Classified(LossCode::DroppedRing, "1 polyface face with missing or too few vertices 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,20 @@ 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::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 cfcae733db..d586525032 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, its name repeats an earlier column's, or only one geometry column is read. + +**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. Give repeated columns distinct names. Export additional geometry columns as separate layers before importing them. + +### `dropped.copyright` { #dropped.copyright } + +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:** 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 raster. + ### `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,10 +84,18 @@ 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. +### `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. @@ -116,6 +140,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 +158,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 } @@ -150,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 } @@ -210,7 +242,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).