diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index d9059172c9..2910ca7b55 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -148,21 +148,35 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No if let Some(encoding) = DbfEncoding::from_name(label) { return encoding; } - notes.push("Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"); + } + // A `.cpg` that can't be used: the file's own language driver gives the encoding, and then + // nothing is assumed; without one it is UTF-8, assumed. One that names a code page RustGIS + // can't read is said below, as assumed, on its own. + let page = (ldid != 0).then(|| ldid_code_page(ldid)).flatten(); + let resolved = page.and_then(DbfEncoding::from_number); + if cpg.is_some() { + let text = "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"; + notes.push(if ldid == 0 { + crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, text) + } else { + crate::loss::Note::plain(text) + }); } // No language driver: UTF-8, as it always was, without a note. if ldid == 0 { return DbfEncoding::Utf8; } - let page = ldid_code_page(ldid); - if let Some(encoding) = page.and_then(DbfEncoding::from_number) { + if let Some(encoding) = resolved { return encoding; } let named = page.map_or_else(String::new, |p| match page_name(p) { Some(name) => format!(" (code page {p}, {name})"), None => format!(" (code page {p})"), }); - notes.push(format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedEncoding, + format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"), + )); DbfEncoding::Utf8 } @@ -422,8 +436,10 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) - match try_read_cpg(path) { Ok(bytes) => bytes, Err(e) => { - notes.push(format!("could not read the .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable")); - None + // Why it can't be used; what the encoding falls back to, and whether that is assumed, + // is said with the `.dbf`'s code page in hand ([`encoding`]), as for one that can't be. + notes.push(crate::loss::Note::plain(format!("could not read the .cpg ({e})"))); + Some(Vec::new()) } } } @@ -585,10 +601,15 @@ mod tests { fn a_page_rustgis_cant_decode_is_named_in_the_note() { let mut notes = crate::loss::Notes::new(); assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8)); - assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"]); + assert_eq!( + notes.texts().collect::>(), + ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"] + ); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); let mut notes = crate::loss::Notes::new(); encoding(None, 0xFF, &mut notes); - assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); + assert_eq!(notes.texts().collect::>(), ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); } /// Text is read as UTF-8 unless another encoding is named, with none named, with UTF-8 named diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index eba292ec31..0375716d05 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -91,7 +91,7 @@ fn is_binary(bytes: &[u8]) -> bool { /// The text of a drawing and what had to be assumed to read it: UTF-8 (AutoCAD 2007 and later), /// else the ANSI code page its header names ([`code_page`], the `$DWGCODEPAGE` of older drawings), /// else Latin-1. -fn decode(bytes: &[u8]) -> (Cow<'_, str>, Option) { +fn decode(bytes: &[u8]) -> (Cow<'_, str>, Option) { if let Ok(s) = std::str::from_utf8(bytes) { return (Cow::Borrowed(s), None); } @@ -103,14 +103,21 @@ fn decode(bytes: &[u8]) -> (Cow<'_, str>, Option) { ), None => "the drawing's text isn't UTF-8 and it names no code page ($DWGCODEPAGE): it is read as Latin-1, so non-ASCII text (such as layer names) may be wrong".to_string(), }; - return (Cow::Owned(bytes.iter().map(|&b| char::from(b)).collect()), Some(said)); + // Read in an encoding it doesn't name: assumed. + return ( + Cow::Owned(bytes.iter().map(|&b| char::from(b)).collect()), + Some(crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, said)), + ); }; let (text, _) = encoding.decode_without_bom_handling(bytes); let lost = text.matches('\u{fffd}').count(); let said = (lost > 0).then(|| { - format!( - "{lost} characters of the drawing's text couldn't be read as {} (its code page): they are drawn as a replacement character", - encoding.name() + crate::loss::Note::loss( + crate::loss::LossCode::ChangedEncoding, + format!( + "{lost} characters of the drawing's text couldn't be read as {} (its code page): they are drawn as a replacement character", + encoding.name() + ), ) }); (text, said) @@ -1154,12 +1161,17 @@ struct Drawing { layers: HashMap, blocks: HashMap)>, entities: Vec, - /// Entities not drawn, by kind. - unread: BTreeMap, - /// Entities that couldn't be read. - bad: usize, + /// The entities that can't be drawn, counted by where they would have been, so they are + /// counted only where drawn: the model's and paper space's (`lost`), and each block's, + /// once for each placement of it (`block_lost`, by lower-cased name). + lost: LostCounts, + block_lost: HashMap, } +/// Entities that can't be drawn, counted by layer (as written; compared ignoring case), paper +/// space, and kind: one RustGIS doesn't draw (its name), or one it can't read (`None`). +type LostCounts = BTreeMap<(String, bool, Option), usize>; + /// The magnitude of an ACI color index (negative means its layer is off). The one signed /// integer without a positive counterpart is malformed and must not overflow while reading. /// When encountered in a layer definition or drawn entity it refuses the drawing rather than @@ -1170,7 +1182,10 @@ fn color_magnitude(color: i64) -> Result { /// Reads the records of each section. fn drawing(records: &[Record]) -> Result { - let mut d = Drawing { layers: HashMap::new(), blocks: HashMap::new(), entities: Vec::new(), unread: BTreeMap::new(), bad: 0 }; + let mut d = + Drawing { layers: HashMap::new(), blocks: HashMap::new(), entities: Vec::new(), lost: BTreeMap::new(), block_lost: HashMap::new() }; + // What can't be drawn in the block being read. + let mut block_lost = LostCounts::new(); let mut section = ""; // The block being read: name, base point, entities. let mut block: Option<(String, P3, Vec)> = None; @@ -1203,13 +1218,22 @@ fn drawing(records: &[Record]) -> Result { if r.kind == "BLOCK" { let name = g.s(2).map(str::trim).unwrap_or("").to_string(); block = Some((name, g.pt(10).unwrap_or([0.0; 3]), Vec::new())); + block_lost = LostCounts::new(); continue; } if r.kind == "ENDBLK" { if let Some((name, base, ents)) = block.take() && !name.is_empty() { - d.blocks.insert(name.to_ascii_lowercase(), (base, ents)); + // A block defined again replaces the earlier one, and what it couldn't + // draw with it. + let key = name.to_ascii_lowercase(); + if block_lost.is_empty() { + d.block_lost.remove(&key); + } else { + d.block_lost.insert(key.clone(), std::mem::take(&mut block_lost)); + } + d.blocks.insert(key, (base, ents)); } continue; } @@ -1231,8 +1255,22 @@ fn drawing(records: &[Record]) -> Result { if matches!(r.kind, "SEQEND" | "VERTEX") || (r.kind == "ATTDEF" && g.i(70).unwrap_or(0) & 2 == 0) { continue; } + // What can't be drawn is counted where it would be drawn: in its block, or in the + // model or paper space. + let mut count_lost = |kind: Option| { + let layer = g.s(8).map(str::trim).unwrap_or("0"); + let key = (layer.to_string(), g.i(67) == Some(1), kind); + let counts = match &block { + Some(_) if section == "BLOCKS" => Some(&mut block_lost), + _ if section == "ENTITIES" => Some(&mut d.lost), + _ => None, + }; + if let Some(counts) = counts { + *counts.entry(key).or_insert(0) += 1; + } + }; let Some(kind) = kind_name(r.kind) else { - *d.unread.entry(r.kind.to_string()).or_insert(0) += 1; + count_lost(Some(r.kind.to_string())); continue; }; let mut loss = PathLoss::default(); @@ -1240,7 +1278,7 @@ fn drawing(records: &[Record]) -> Result { // Entity builders use Option for malformed data; cancellation must escape as an error. crate::progress::check()?; let Some(shape) = shape else { - d.bad += 1; + count_lost(None); continue; }; let text = match kind { @@ -1314,6 +1352,9 @@ struct Out { vertex_capped: bool, /// The copies the arrays above make together on the current nesting path. copies: usize, + /// Entities placed that RustGIS doesn't draw, by kind, and that couldn't be read. + unread: BTreeMap, + bad: usize, } fn fields() -> Vec { @@ -1355,6 +1396,7 @@ fn has_varying_z<'a>(mut points: impl Iterator, first: Option fn emit( d: &Drawing, ents: &[Ent], + lost: Option<&LostCounts>, xf: &Xf, from: Inherit, depth: usize, @@ -1362,6 +1404,36 @@ fn emit( opts: &Options, out: &mut Out, ) -> Result<()> { + // What can't be drawn here, counted as a drawn entity would be placed: in a block, a step + // each; in paper space only when that is drawn; and on the layer asked for (layer 0 in a block + // takes the INSERT's). + for ((layer, paper, kind), &n) in lost.into_iter().flatten() { + crate::progress::check()?; + // In a block, each copy walks these again, so each is a step; the model's are counted + // once, and cost the drawable entities after them nothing. + if depth > 0 { + out.steps = out.steps.saturating_add(n); + if out.steps > MAX_STEPS { + out.overworked = true; + return Ok(()); + } + } + if depth == 0 && *paper && !opts.paper_space { + out.paper += n; + continue; + } + let layer = match from.layer { + Some(l) if layer == "0" => l, + _ => layer.as_str(), + }; + if opts.layer.is_some_and(|want| !layer.eq_ignore_ascii_case(want)) { + continue; + } + match kind { + Some(k) => *out.unread.entry(k.clone()).or_insert(0) += n, + None => out.bad += n, + } + } for e in ents { crate::progress::check()?; if out.vertex_capped { @@ -1371,8 +1443,9 @@ fn emit( out.capped = true; return Ok(()); } - // Every placement costs a step, drawn or not: nested arrays of empty or filtered blocks - // can't make the walk run on. + // Every placement costs a step, drawn, counted or not: nested arrays of empty, filtered or + // undrawable blocks can't make the walk run on (an undrawable entity is walked once per + // copy). out.steps += 1; if out.steps > MAX_STEPS { out.overworked = true; @@ -1436,7 +1509,7 @@ fn emit( loss: PathLoss::default(), }) .collect(); - emit(d, &drawn, xf, from, depth + 1, stack, opts, out)?; + emit(d, &drawn, None, xf, from, depth + 1, stack, opts, out)?; continue; } out.cut += 1; @@ -1469,7 +1542,8 @@ fn emit( block: Some(ins.block.as_str()), paper: from.paper || e.paper, }; - emit(d, inner, &xf.then(&local), inner_from, depth + 1, stack, opts, out)?; + let lost = stack.last().and_then(|k| d.block_lost.get(k)); + emit(d, inner, lost, &xf.then(&local), inner_from, depth + 1, stack, opts, out)?; if out.capped || out.overworked || out.vertex_capped { stack.pop(); out.copies = outer; @@ -1624,16 +1698,19 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result = d.unread.iter().map(|(k, n)| format!("{n} {k}")).collect(); - report.messages.push(format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", "))); + if !out.unread.is_empty() { + let kinds: Vec = out.unread.iter().map(|(k, n)| format!("{n} {k}")).collect(); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", ")), + )); } - let skipped = d.bad + out.cut; + let skipped = out.bad + out.cut; report.skipped = skipped; if skipped > 0 { - report.messages.push(format!( - "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" + ), )); } let transformer = match opts.crs.filter(|c| *c != Crs::LonLat) { @@ -1741,20 +1826,35 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { let subject = if count == 1 { single } else { plural }; - report.messages.push(format!("{count} {subject} {reason}")); + report.messages.push(crate::loss::Note::loss(code, format!("{count} {subject} {reason}"))); } } } @@ -1775,7 +1875,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result Result> { for (key, (name, _, _)) in &d.layers { add(name, key); } + // What can't be drawn names no layer to pick. for e in &d.entities { add(&e.layer, &e.layer_key); } @@ -1829,6 +1933,66 @@ pub fn layers(file_name: &str, bytes: &[u8]) -> Result> { mod tests { use super::*; + /// An entity RustGIS doesn't draw, or can't read, is counted where it would have been drawn: + /// not at all in a block the drawing never places, and once for each placement of one it does. + #[test] + fn lost_entities_are_counted_where_they_would_be_drawn() { + let drawing = |inserts: &str| { + format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 B 0 IMAGE 0 POINT 10 1 20 1 0 ENDBLK 0 ENDSEC 0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 {inserts} 0 ENDSEC 0 EOF" + ) + .split_whitespace() + .collect::>() + .join("\n") + }; + let said = |text: &str| { + let layers = read("a.dxf", text.as_bytes(), &Options::default()).unwrap(); + layers + .iter() + .flat_map(|(_, r)| r.messages.iter()) + .filter(|m| m.contains("doesn't draw")) + .map(|m| (m.as_str().to_string(), m.loss)) + .collect::>() + }; + assert!(said(&drawing("")).is_empty(), "a block never placed loses nothing"); + // A block defined again without them: the later definition is the one placed. + let redefined = + drawing("0 INSERT 2 B 10 5 20 5").replacen("ENDSEC", "BLOCK\n2\nB\n0\nPOINT\n10\n2\n20\n2\n0\nENDBLK\n0\nENDSEC", 1); + assert!(said(&redefined).is_empty(), "{:?}", said(&redefined)); + assert_eq!( + said(&drawing("0 INSERT 2 B 10 5 20 5 0 INSERT 2 B 10 9 20 9")), + [("entities RustGIS doesn't draw were left out: 2 IMAGE".to_string(), Some(crate::loss::LossCode::DroppedFeature))] + ); + // Blocks left out, or a layer not asked for: their contents aren't drawn, so nothing of + // them is lost. + let placed = drawing("0 INSERT 2 B 8 x 10 5 20 5"); + for opts in [Options { blocks: false, ..Options::default() }, Options { layer: Some("0"), ..Options::default() }] { + let layers = read("a.dxf", placed.as_bytes(), &opts).unwrap(); + assert!(!layers.iter().flat_map(|(_, r)| r.messages.iter()).any(|m| m.contains("doesn't draw")), "{opts:?}"); + } + // What can't be drawn names no layer of its own to pick. + let lone = + "0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 0 IMAGE 8 only_images 0 ENDSEC 0 EOF".split_whitespace().collect::>().join("\n"); + assert_eq!(layers("a.dxf", lone.as_bytes()).unwrap(), ["0"]); + } + + /// What can't be drawn still costs its walk a step on each copy, so an array of a block of + /// undrawable entities stops at the step limit, said, rather than running on. + #[test] + fn undrawable_entities_meet_the_step_limit() { + let images = "0 IMAGE ".repeat(100); + let text = format!( + "0 SECTION 2 BLOCKS 0 BLOCK 2 B {images}0 ENDBLK 0 BLOCK 2 A 0 INSERT 2 B 70 100 71 100 44 1 45 1 0 ENDBLK 0 ENDSEC \ + 0 SECTION 2 ENTITIES 0 POINT 10 0 20 0 0 INSERT 2 A 10 1 20 1 70 10 44 1 0 ENDSEC 0 EOF" + ) + .split_whitespace() + .collect::>() + .join("\n"); + let layers = read("a.dxf", text.as_bytes(), &Options::default()).unwrap(); + let said = layers[0].1.messages.iter().find(|m| m.contains("place more than")).unwrap(); + assert_eq!(said.loss, Some(crate::loss::LossCode::DroppedOverLimit)); + } + /// A DXF from (code, value) pairs. fn dxf(pairs: &[(i32, &str)]) -> Vec { pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() @@ -1856,7 +2020,7 @@ mod tests { assert_eq!(parts[0][0].first(), Some(&Coord::new(0., 0.))); assert_eq!(layers[0].1.skipped, 0); assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), [format!("{} polyline path coordinates were left out at the per-entity vertex limit", (vertices - kept_segments) * 36,)] ); } @@ -1882,6 +2046,7 @@ mod tests { let layers = read("a.dxf", &bytes, &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Line(vec![vec![Coord::new(0., 0.), Coord::new(2., 2.)]]))); assert_eq!(layers[0].1.messages.texts().collect::>(), ["1 vertex without Y was left out of spline paths"]); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedGeometry)); assert_eq!(layers[0].1.skipped, 0); } } @@ -1910,7 +2075,11 @@ mod tests { let Some(Geometry::Line(parts)) = &layers[0].0.features[0].geometry else { panic!("line") }; assert_eq!(parts[0].len(), if lost { 2 } else { 3 }); assert_eq!(layers[0].0.value(0, 8), &Value::Float(0.)); - assert_eq!(layers[0].1.messages, if lost { vec!["1 POLYLINE vertex with unreadable supplied Z was left out"] } else { vec![] }); + assert_eq!( + layers[0].1.messages.texts().collect::>(), + if lost { vec!["1 POLYLINE vertex with unreadable supplied Z was left out"] } else { vec![] } + ); + assert!(layers[0].1.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedGeometry))); assert_eq!(layers[0].1.skipped, 0); } } @@ -1942,6 +2111,7 @@ mod tests { layers[0].1.messages.texts().collect::>(), [format!("{count} short HATCH boundary {subject} left out of polygons")] ); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedRing)); assert_eq!(layers[0].1.skipped, 0); } } @@ -2013,7 +2183,7 @@ mod tests { let held = parts[0].len(); let total = MAX_VERTICES + tail.len() + if bulge { 35 } else { 0 }; assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), [format!( "{} polyline path {} left out at the per-entity vertex limit", total - held, @@ -2051,6 +2221,7 @@ mod tests { layers[0].1.messages.texts().collect::>(), ["1 entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out"] ); + assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); } // Losses follow the two surviving block copies; the paper-space and filtered copy stay quiet. let text = "0 SECTION 2 BLOCKS 0 BLOCK 2 B 0 SPLINE 71 3 11 0 21 0 11 1 11 2 21 2 0 ENDBLK 0 ENDSEC diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 1287b0cd58..5f403bd4da 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -139,6 +139,11 @@ pub struct Losses { pub with_zm: usize, /// Places that convert to beyond longitude/latitude (the answer's system may not fit them). pub beyond: usize, + /// The coordinate system code an answer with features with a geometry names and RustGIS + /// can't use, without a WKT (read as longitude/latitude). + pub unusable_code: Option, + /// Pages joined after the first that named another code RustGIS can't use. + pub other_unusable: usize, } impl Losses { @@ -152,6 +157,23 @@ impl Losses { self.unprojected = self.unprojected.saturating_add(other.unprojected); self.with_zm = self.with_zm.saturating_add(other.with_zm); self.beyond = self.beyond.saturating_add(other.beyond); + match (self.unusable_code, other.unusable_code) { + (Some(a), Some(b)) if a != b => self.other_unusable += 1 + other.other_unusable, + (None, b) => { + self.unusable_code = b; + self.other_unusable += other.other_unusable; + } + _ => self.other_unusable += other.other_unusable, + } + } + + /// The pages that named another code RustGIS can't use, as the notice for the first adds them. + pub fn others_said(&self) -> String { + match self.other_unusable { + 0 => String::new(), + 1 => " (and another page names a code it can't use either)".to_string(), + n => format!(" (and {n} other pages name codes it can't use either)"), + } } /// What they say, one message per kind (as [`read`] says them). @@ -163,17 +185,33 @@ impl Losses { "the answer names no coordinate system; coordinates are read as longitude/latitude", )); } + // Said only when a geometry was read in it: assumed, then. + if let Some(code) = self.unusable_code { + out.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("coordinate system {code} can't be used{}; coordinates are read as longitude/latitude", self.others_said()), + )); + } if self.unreadable > 0 { - out.push(format!("{} values don't fit their field's type and are left empty", self.unreadable)); + out.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{} values don't fit their field's type and are left empty", self.unreadable), + )); } if self.not_utf8 > 0 { - out.push(format!( - "{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", - self.not_utf8 + out.push(crate::loss::Note::loss( + crate::loss::LossCode::ChangedEncoding, + format!( + "{} values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", + self.not_utf8 + ), )); } if self.flat_rings > 0 { - out.push(format!("{} polygon rings have no area and are left out", self.flat_rings)); + out.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedRing, + format!("{} polygon rings have no area and are left out", self.flat_rings), + )); } if self.unprojected > 0 { out.push(format!( @@ -319,10 +357,16 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result fields.push(Field { name, ty: read_as.field_type(), alias }); } if repeated > 0 { - report.messages.push(format!("{repeated} fields repeat an earlier field's name and are left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{repeated} fields repeat an earlier field's name and are left out"), + )); } if not_read > 0 { - report.messages.push(format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{not_read} fields hold geometries, blobs or rasters, which aren't read, and are left out"), + )); } if unknown > 0 { report.messages.push(format!("{unknown} fields have a type RustGIS doesn't know; their values are read as text")); @@ -335,6 +379,9 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result // read in its place. If the replaced bytes break the WKT, it can't be told whether the WKT // would have won, so that's said too. The WKT is looked at only when it isn't UTF-8, as this // runs for every page. + // What reading the system says (its WKT's text, and what it assumes) holds only for a + // geometry read in it. + let said_before = report.messages.len(); if !wkt_utf8 && (code.and_then(crs_of_code).is_none() || esri_wkt_over_code(code, wkt.as_deref()).is_some() @@ -345,8 +392,9 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result "the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", )); } - let said_before = report.messages.len(); let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?; + // What reading the system said, which assumes a system only for a geometry read in it. + let crs_said = said_before..report.messages.len(); // A WKT that couldn't be read (or converted) is read as longitude/latitude, and said so; // a geographic one gives no system and says nothing. let mut unread_code = crs.is_none() @@ -354,13 +402,15 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result .messages .get(said_before..) .is_some_and(|m| m.iter().any(|m| m.ends_with("; coordinates are read as longitude/latitude"))); + // Said with the page's losses, once it is known that a geometry was read in it. + let mut unusable_code = None; if crs.is_none() && wkt.is_none() && let Some(code) = code && crate::filegdb::crs_of_code(code) != Some(crate::raster::Crs::LonLat) { unread_code = true; - report.messages.push(format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude")); + unusable_code = Some(code); } let layer_type = match shape_kind { @@ -398,10 +448,27 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result if let Some(c) = crs.filter(|_| to_lonlat.is_some()) { ds.held_in = c; } + // An answer without a geometry places nothing in the system it couldn't read: said, not as + // assumed. + if !any_geometry && !crs_said.is_empty() { + let said = std::mem::replace(&mut report.messages, crate::loss::Notes::new()); + for (i, mut note) in said.into_iter().enumerate() { + if crs_said.contains(&i) + && matches!(note.loss, Some(crate::loss::LossCode::AssumedCrs | crate::loss::LossCode::ChangedEncoding)) + { + note.loss = None; + } + report.messages.push(note); + } + } let losses = Losses { // Assumed, so said: an answer that names no coordinate system. no_crs: any_geometry && code.is_none() && wkt.is_none(), unread_code: any_geometry && unread_code, + // A page without geometry places nothing in the code it names, so says nothing of it, + // unlike a WKT it can't read, which is said (plainly) as what the answer holds. + unusable_code: unusable_code.filter(|_| any_geometry), + other_unusable: 0, unreadable: tally.unreadable, not_utf8: tally.not_utf8, flat_rings: tally.flat_rings, diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index df3daaa899..9f619e340f 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -147,7 +147,8 @@ fn a_ring_without_area_is_left_out_and_said() { let (ds, report) = read(&bytes, "t").unwrap(); let Some(Geometry::Polygon(polygons)) = &ds.features[0].geometry else { panic!("not a polygon") }; assert_eq!(polygons.len(), 1); - assert_eq!(report.messages, ["1 polygon rings have no area and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["1 polygon rings have no area and are left out"]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedRing)); } #[test] @@ -237,6 +238,11 @@ fn an_unknown_coordinate_system_is_said() { report.messages.texts().collect::>(), ["coordinate system 999999 can't be used; coordinates are read as longitude/latitude"] ); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::AssumedCrs)); + // An answer with no geometry places nothing in it: nothing assumed, nothing said. + let rows = answer(&[message(8, &number(1, 999_999)), transform(false, 1.0, 0.0, 0.0), feature(&[])]); + let (_, report) = read(&rows, "t").unwrap(); + assert!(!report.messages.iter().any(|m| m.contains("can't be used")), "{:?}", report.messages); } #[test] @@ -286,8 +292,9 @@ fn text_that_isnt_utf8_is_read_with_replacements_and_said() { assert_eq!(ds.fields[0].name, "N\u{FFFD}AME"); assert_eq!(ds.features[0].attrs, [Value::Text("a\u{FFFD}b".into())]); assert_eq!(ds.features[1].attrs, [Value::Text("ok".into())]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::ChangedEncoding)); assert_eq!( - report.messages, + report.messages.texts().collect::>(), ["2 values, field names or aliases aren't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"] ); } @@ -317,13 +324,14 @@ fn repeated_names_and_unread_field_types_are_left_out_and_said() { assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::>(), ["NAME", "COUNT"]); assert_eq!(ds.features[0].attrs, [Value::Text("a".into()), Value::Null]); assert_eq!( - report.messages, + report.messages.texts().collect::>(), [ "1 fields repeat an earlier field's name and are left out", "1 fields hold geometries, blobs or rasters, which aren't read, and are left out", "1 values don't fit their field's type and are left empty", ] ); + assert!(report.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedValue)), "{:?}", report.messages); // A table: no geometry type, no geometry. assert_eq!(ds.geometry_type, GeometryType::None); } @@ -445,6 +453,20 @@ fn lengths_in_several_fields_keep_their_order() { assert!(report.messages.is_empty(), "{:?}", report.messages); } +/// A WKT RustGIS can't read is assumed to be longitude/latitude only for an answer with a +/// geometry read in it: one without places nothing there. +#[test] +fn an_unreadable_wkt_is_assumed_only_with_a_geometry() { + let wkt: &[u8] = b"PROJCS[\"nonsense\"]"; + let assumed = |features: &[u8]| { + let bytes = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), features.to_vec()]); + let (_, report) = read(&bytes, "t").unwrap(); + report.messages.iter().filter(|m| m.contains("read as longitude/latitude")).map(|m| m.loss).collect::>() + }; + assert_eq!(assumed(&feature(&[geometry(&[], &[1, 2])])), [Some(crate::loss::LossCode::AssumedCrs)]); + assert_eq!(assumed(&feature(&[])), [None]); +} + #[test] fn a_wkt_that_isnt_utf8_is_said() { let wkt = b"GEOGCS[\"GCS_WGS_1984\xff\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]"; @@ -454,6 +476,11 @@ fn a_wkt_that_isnt_utf8_is_said() { report.messages.first().map(|m| m.as_str()), Some("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD") ); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::ChangedEncoding)); + // On a page with no geometry, nothing is placed in the system: said, without a code. + let rows = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), feature(&[])]); + let (_, report) = read(&rows, "t").unwrap(); + assert_eq!(report.messages.first().map(|m| m.loss), Some(None), "{:?}", report.messages); // Unused when a code RustGIS knows names the system: nothing to say. let with_code = answer(&[ message(8, &[number(1, 4326), message(5, wkt)].concat()), @@ -704,7 +731,7 @@ fn a_repeated_field_of_an_unknown_type_is_only_said_left_out() { let bytes = answer(&[field("NAME", 4), field("name", 17), feature(&[text("a"), uint(5)])]); let (ds, report) = read(&bytes, "t").unwrap(); assert_eq!(ds.fields.len(), 1); - assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["1 fields repeat an earlier field's name and are left out"]); } #[test] @@ -713,10 +740,13 @@ fn a_left_out_field_whose_name_isnt_utf8_is_only_said_left_out() { let repeat = message(13, &[message(1, b"N\xffame"), number(2, 4)].concat()); let bytes = answer(&[field("N\u{FFFD}AME", 4), repeat, feature(&[text("a"), text("b")])]); let (_, report) = read(&bytes, "t").unwrap(); - assert_eq!(report.messages, ["1 fields repeat an earlier field's name and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["1 fields repeat an earlier field's name and are left out"]); let geometry = message(13, &[message(1, b"G\xff"), number(2, 7)].concat()); let (_, report) = read(&answer(&[field("NAME", 4), geometry, feature(&[text("a")])]), "t").unwrap(); - assert_eq!(report.messages, ["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"]); + assert_eq!( + report.messages.texts().collect::>(), + ["1 fields hold geometries, blobs or rasters, which aren't read, and are left out"] + ); } #[test] @@ -769,3 +799,23 @@ fn a_wkt_is_taken_from_the_text_room_at_its_size_once_read() { assert!(spatial_reference(&reference, &mut Tally { text_room: 13, ..Tally::default() }).is_err()); assert!(spatial_reference(&reference, &mut Tally { text_room: 14, ..Tally::default() }).is_ok()); } + +/// Pages joined that name different codes RustGIS can't use say the first and how many others, +/// so every page's assumption is said; the same code again adds nothing. +#[test] +fn joined_pages_say_every_unusable_code() { + let page = |code| Losses { unusable_code: Some(code), ..Losses::default() }; + let mut all = page(999_999); + all.add(&page(999_999)); + all.add(&page(888_888)); + all.add(&page(777_777)); + let said: Vec<_> = all.messages().iter().map(|m| (m.as_str().to_string(), m.loss)).collect(); + assert_eq!( + said, + [( + "coordinate system 999999 can't be used (and 2 other pages name codes it can't use either); coordinates are read as longitude/latitude" + .to_string(), + Some(crate::loss::LossCode::AssumedCrs) + )] + ); +} diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 6db7769c20..91465d4715 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2922,12 +2922,18 @@ pub(crate) fn read_rows( // so its row has no geometry, said here. if let Some(w) = wkt { let column = headers.get(w).map_or("", |h| h.trim()); + // The values read as empty, below the heading: each a value lost, and with it its row's + // geometry. match workbook.and_then(|(_, empty)| empty.get(w)).copied().unwrap_or(0) { 0 => {} - 1 => report.messages.push(format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry")), - n => report - .messages - .push(format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry")), + 1 => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry, or is left out if it held nothing else"), + )), + n => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry, or are left out if they held nothing else"), + )), } } let (mut bad_wkt, mut zm_rows, mut collection_rows) = (0usize, 0usize, 0usize); diff --git a/crates/data/src/lidar.rs b/crates/data/src/lidar.rs index bdd838999c..6d5ca8a037 100644 --- a/crates/data/src/lidar.rs +++ b/crates/data/src/lidar.rs @@ -360,9 +360,10 @@ fn read_points(mut r: R, name: &str, crs: Option MAX_DECOMPRESSED { - report - .messages - .push(format!("{name}: only its first {MAX_DECOMPRESSED} of {total} points are read (use a smaller extract for the rest)")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{name}: only its first {MAX_DECOMPRESSED} of {total} points are read (use a smaller extract for the rest)"), + )); } let read = laz_points(&mut r, &h, &vlr.data, readable, stride, &mut points, &mut brightest)?; if read < readable { diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 77d99f7e44..58e7ba2fcb 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -135,6 +135,11 @@ loss_codes! { Assumed, "Give the coordinate system the coordinates are in (\"crs\" when adding the data, or Define Projection)." ), + AssumedEncoding => ( + "assumed.encoding", + Assumed, + "Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8." + ), } impl LossCode { diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 724e595ddf..2a85247964 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4591,9 +4591,19 @@ impl Pages { ds.crs = Some(asked); let asked = asked.label(); if std::mem::take(&mut losses.no_crs) { - report - .messages - .push(format!("the answer names no coordinate system; coordinates are read in {asked}, the system asked for")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("the answer names no coordinate system; coordinates are read in {asked}, the system asked for"), + )); + } + if let Some(code) = losses.unusable_code.take() { + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!( + "coordinate system {code} can't be used{}; coordinates are read in {asked}, the system asked for", + losses.others_said() + ), + )); } // One it names that RustGIS can't use (a code, a WKT): read as asked too (as a // GeoJSON answer's is), and its message says so. @@ -6363,7 +6373,8 @@ mod tests { report .messages .iter() - .any(|m| m.as_str() == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for"), + .any(|m| m.as_str() == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for" + && m.loss == Some(crate::loss::LossCode::AssumedCrs)), "{:?}", report.messages ); @@ -7127,7 +7138,7 @@ mod tests { pages = match pages.join_page(page) { Step::Fetch(p) => *p, Step::Decoded(_, report, None) => { - assert_eq!(report.messages, ["5 polygon rings have no area and are left out"]); + assert_eq!(report.messages.texts().collect::>(), ["5 polygon rings have no area and are left out"]); break; } other => panic!("{other:?}"), diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 495010e739..7967084a71 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -54,29 +54,43 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> let (ds, mut report) = read_rows(&g.headers, &g.rows, 0, &title, opts, Some((&g.dates, &g.phantom_dates)))?; let errors: usize = g.error_cells.iter().sum(); let rounded: usize = g.rounded_dates.iter().sum(); + let headings: usize = g.header_error_cells.iter().sum(); let fields: Vec = - if errors > 0 || rounded > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] }; + if errors > 0 || rounded > 0 || headings > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] }; + // A heading that is an error is named by its column letter: the column's name, not its data. + if headings > 0 { + let what = if headings == 1 { + "1 erroneous heading was named by its column letter".to_string() + } else { + format!("{headings} erroneous headings were named by their column letters") + }; + report.messages.push(format!("{what}, {}", crate::io::named_fields(&fields, &g.header_error_cells))); + } if errors > 0 { let what = if errors == 1 { "1 spreadsheet error cell was".to_string() } else { format!("{errors} spreadsheet error cells were") }; - let mut message = format!("{what} read as empty, in {}", crate::io::named_fields(&fields, &g.error_cells)); - let headings: usize = g.header_error_cells.iter().sum(); - if headings > 0 { - let what = if headings == 1 { - "1 erroneous heading was named by its column letter".to_string() - } else { - format!("{headings} erroneous headings were named by their column letters") - }; - message.push_str(&format!("; {what}, {}", crate::io::named_fields(&fields, &g.header_error_cells))); - } + let message = format!("{what} read as empty, in {}", crate::io::named_fields(&fields, &g.error_cells)); + // Each error cell's value is read as empty: a value lost. + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, message)); + // A row with nothing but error cells is left out whole: a row lost, said on its own. if g.empty_error_rows > 0 { let what = if g.empty_error_rows == 1 { "1 otherwise empty row with error cells was omitted".to_string() } else { format!("{} otherwise empty rows with error cells were omitted", g.empty_error_rows) }; - message.push_str(&format!("; {what}")); + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, what)); } - report.messages.push(message); + } + if g.empty_phantom_rows > 0 { + let what = if g.empty_phantom_rows == 1 { + "1 row was omitted, as its only values were serial-60 dates (a day that never was), read as empty".to_string() + } else { + format!( + "{} rows were omitted, as their only values were serial-60 dates (a day that never was), read as empty", + g.empty_phantom_rows + ) + }; + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, what)); } if rounded > 0 { report.messages.push(crate::loss::Note::loss( @@ -117,6 +131,8 @@ struct Grid { empty_error_rows: usize, /// Per column that isn't one of dates, the serial-60 cells read as empty. phantom_dates: Vec, + /// Rows left out because their only values were serial-60 dates, read as empty. + empty_phantom_rows: usize, } fn grid(bytes: &[u8], sheet: Option<&str>) -> Result { @@ -205,42 +221,36 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< // Serial 60 is the 1900 system's 1900-02-29, a day that never was. A column of dates reads it // as one that isn't a date (null, and counted); in a column of other things it is read as // empty and counted here, as it would not be text of a day. + // Counted for the rows below the heading, each a value read as empty: kept, or left out as + // empty when it was all the row held. let mut phantom_dates = vec![0usize; w]; let mut error_cells = vec![0usize; w]; + // Error cells too are counted below the heading only: a title row's error is no cell of the + // table. let mut rows = range.rows().enumerate().map(|(row, r)| { - let mut had_error = false; + let mut errors: Vec = Vec::new(); + let mut phantom: Vec = Vec::new(); let cells = r .iter() .enumerate() .map(|(k, d)| match (d, dates.get(k)) { (Data::Error(_), _) => { - had_error = true; - if let Some(n) = error_cells.get_mut(k) { - *n += 1; - } + errors.push(k); String::new() } (Data::DateTime(t), Some(None)) if is_phantom_day(t) => { - if let Some(n) = phantom_dates.get_mut(k) { - *n += 1; - } + phantom.push(k); String::new() } _ => cell(d), }) .collect::>(); - (row, cells, had_error) + (row, cells, errors, phantom) }); - let mut empty_error_rows = 0; - let mut keep = |(_, cells, had_error): &(usize, Vec, bool)| { - let nonempty = cells.iter().any(|c| !c.trim().is_empty()); - if !nonempty && *had_error { - empty_error_rows += 1; - } - nonempty - }; + let (mut empty_error_rows, mut empty_phantom_rows) = (0, 0); + let keep = |(_, cells, _, _): &(usize, Vec, Vec, Vec)| cells.iter().any(|c| !c.trim().is_empty()); // The first row with anything in it names the columns. - let (header_row, headers, _) = rows.by_ref().find(&mut keep).unwrap_or_default(); + let (header_row, headers, _, _) = rows.by_ref().find(keep).unwrap_or_default(); if headers.is_empty() { return Err(DataError::Format(format!("sheet '{pick}' is empty"))); } @@ -261,8 +271,44 @@ fn grid_unguarded(mut wb: Sheets>, sheet: Option<&str>) -> Result< if h.trim().is_empty() { column_letter(first_col + i) } else { h.trim().to_string() } }) .collect(); - let rows = rows.filter(keep).map(|(_, cells, _)| cells).collect(); - Ok(Grid { names, pick, headers, rows, dates, rounded_dates, error_cells, header_error_cells, empty_error_rows, phantom_dates }) + let rows = rows + .inspect(|(_, cells, errors, phantom)| { + for k in errors { + if let Some(n) = error_cells.get_mut(*k) { + *n += 1; + } + } + // A data row left out whole, below the heading: one whose only values were error + // cells, or serial-60 dates, read as empty (one with both is said with the errors). + if cells.iter().all(|c| c.trim().is_empty()) { + if !errors.is_empty() { + empty_error_rows += 1; + } else if !phantom.is_empty() { + empty_phantom_rows += 1; + } + } + for k in phantom { + if let Some(n) = phantom_dates.get_mut(*k) { + *n += 1; + } + } + }) + .filter(keep) + .map(|(_, cells, _, _)| cells) + .collect(); + Ok(Grid { + names, + pick, + headers, + rows, + dates, + rounded_dates, + error_cells, + header_error_cells, + empty_error_rows, + empty_phantom_rows, + phantom_dates, + }) } /// Check every ZIP member before calamine opens it, without suffix or case filters. ODS @@ -801,12 +847,43 @@ mod tests { assert_eq!(ds.features.len(), 2); assert_eq!(ds.features.iter().filter(|f| f.geometry.is_none()).count(), 1); assert!( - report.messages.says("1 value in 'wkt' isn't a date and was read as empty, so its row has no geometry"), + report.messages.says( + "1 value in 'wkt' isn't a date and was read as empty, so its row has no geometry, or is left out if it held nothing else" + ), "{:?}", report.messages ); + let said = report.messages.iter().find(|m| m.contains("isn't a date")).unwrap(); + assert_eq!(said.loss, Some(crate::loss::LossCode::DroppedValue)); let (_, report) = book("POINT (3 4)"); assert!(!report.messages.iter().any(|m| m.contains("isn't a date")), "{:?}", report.messages); + // A row whose only value is serial 60 in the WKT column is left out as empty, and its value + // read as empty is said. + let phantom = r#"60"#; + let empty = xlsx(&[("Places", &[&["name", "wkt"], &["a", "POINT (1 2)"], &["", phantom]])]); + let mut entries = crate::zip::read(&empty).unwrap(); + entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let opts = CsvOptions { wkt: Some("wkt".into()), ..CsvOptions::default() }; + let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); + assert_eq!(ds.features.len(), 1); + assert!(report.messages.iter().any(|m| m.contains("1 value in 'wkt' isn't a date")), "{:?}", report.messages); + let row = report.messages.iter().find(|m| m.contains("row was omitted")).unwrap(); + assert_eq!(row.loss, Some(crate::loss::LossCode::DroppedFeature)); + // One above the heading is no data row: nothing of it is said. + let above = xlsx(&[("Places", &[&["", phantom], &["name", "wkt"], &["a", "POINT (1 2)"]])]); + let mut entries = crate::zip::read(&above).unwrap(); + entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); + assert_eq!(ds.features.len(), 1); + assert!(!report.messages.iter().any(|m| m.contains("omitted") || m.contains("isn't a date")), "{:?}", report.messages); + // Nor is one there with an error cell besides: no row of the data is left out. + let error = r#"#DIV/0!"#; + let mixed = xlsx(&[("Places", &[&[error, phantom], &["name", "wkt"], &["a", "POINT (1 2)"]])]); + let mut entries = crate::zip::read(&mixed).unwrap(); + entries.push(("xl/styles.xml".into(), br#""#.to_vec())); + let (ds, report) = read(&crate::zip::write(&entries).unwrap(), "places", None, &opts).unwrap(); + assert_eq!(ds.features.len(), 1); + assert!(!report.messages.iter().any(|m| m.contains("omitted") || m.contains("error cell")), "{:?}", report.messages); } /// Multiple errors in one column and another column count once each; blank cells don't. @@ -815,7 +892,8 @@ mod tests { let error = r#"#DIV/0!"#; let book = xlsx(&[("S", &[&["id", "note", "other"], &["7", error, "kept"], &["8", error, error], &["9", "", ""]])]); let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap(); - assert_eq!(report.messages, ["3 spreadsheet error cells were read as empty, in 'note', 'other'"]); + assert_eq!(report.messages.texts().collect::>(), ["3 spreadsheet error cells were read as empty, in 'note', 'other'"]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); assert_eq!(report.skipped, 0); let attrs: Vec<_> = ds.features.iter().map(|f| f.attrs.clone()).collect(); use crate::Value::{Int, Null, Text}; @@ -831,12 +909,8 @@ mod tests { let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap(); assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::>(), ["id", "B"]); assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Text("kept".into())]); - let expected = if heading.is_empty() { - vec![] - } else { - vec!["1 spreadsheet error cell was read as empty, in 'B'; 1 erroneous heading was named by its column letter, 'B'"] - }; - assert_eq!(report.messages, expected); + let expected = if heading.is_empty() { vec![] } else { vec!["1 erroneous heading was named by its column letter, 'B'"] }; + assert_eq!(report.messages.texts().collect::>(), expected); } } @@ -854,9 +928,13 @@ mod tests { let expected = if cell.is_empty() { vec![] } else { - vec!["2 spreadsheet error cells were read as empty, in 'id', 'note'; 1 otherwise empty row with error cells was omitted"] + vec!["2 spreadsheet error cells were read as empty, in 'id', 'note'", "1 otherwise empty row with error cells was omitted"] }; - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); + if !expected.is_empty() { + use crate::loss::LossCode::{DroppedFeature, DroppedValue}; + assert_eq!(report.messages.iter().map(|m| m.loss).collect::>(), [Some(DroppedValue), Some(DroppedFeature)]); + } } } diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 4f4cfd2e16..af15695003 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -626,6 +626,16 @@ const UNSUPPORTED_LDIDS: &[(u8, &str)] = &[ (0x97, "10029, Mac Central European"), ]; +/// An encoding RustGIS falls back to is said as assumed: a code page it can't use. A `.cpg` it +/// can't use is assumed only when there is no code page (`ldid` 0) to give the encoding instead. +fn encoding_assumed(notes: &rustgis_data::loss::Notes, ldid: u8) { + for note in notes.iter().filter(|n| n.contains("; using ")) { + let assumed = note.contains("unsupported .dbf code page") || ldid == 0; + let code = assumed.then_some(rustgis_data::loss::LossCode::AssumedEncoding); + assert_eq!(note.loss, code, "{note:?}"); + } +} + /// Three records make a limit-one read genuinely sampled; names and values use the same bytes. /// `notes` is what a read of the whole file says. A source read in place says those of opening /// when it opens, and the count of values (`places: …`) with them once it is read whole. @@ -644,6 +654,7 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, check(&layers[0].0, 3); assert_eq!(layers[0].1.skipped, 0); assert_eq!(texts(&layers[0].1.messages), notes, "LDID {ldid:02X} ZIP notes"); + encoding_assumed(&layers[0].1.messages, ldid); #[cfg(not(target_arch = "wasm32"))] { use rustgis_data::source::{FeatureSource, Request}; @@ -656,10 +667,12 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, check(&ds, 3); assert_eq!(report.skipped, 0); assert_eq!(texts(&report.messages), notes, "LDID {ldid:02X} loose-file notes"); + encoding_assumed(&report.messages, ldid); let src = open_shp(&path, "places").unwrap(); assert_eq!(src.info().fields[0].name, expected, "LDID {ldid:02X} streamed field name"); let opening: Vec<&str> = notes.iter().copied().filter(|n| !n.starts_with("places: ")).collect(); assert_eq!(texts(&src.info().notes), opening, "LDID {ldid:02X} streamed notes"); + encoding_assumed(&src.info().notes, ldid); let whole: Vec = notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); assert_eq!(texts(&rustgis_data::source::materialize(&src).unwrap().1.messages), whole, "LDID {ldid:02X} whole read in place"); diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index d1fc84e0f9..f752812bf8 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -1000,7 +1000,10 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< { return Err(std::io::Error::other(format!("native spreadsheet collection notice: {report:?}"))); } - if errors && report.messages != ["1 spreadsheet error cell was read as empty, in 'note'"] { + if errors + && (report.messages.texts().collect::>() != ["1 spreadsheet error cell was read as empty, in 'note'"] + || report.messages[0].loss != Some(LossCode::DroppedValue)) + { return Err(std::io::Error::other(format!("native spreadsheet error notice: {report:?}"))); } if report.skipped != 0 diff --git a/docs/cli.md b/docs/cli.md index 1f01b59b65..08674c5006 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -176,6 +176,7 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. | | `assumed.null-marker` | Write the value another way if the text Null is meant as text, not as an empty value. | | `assumed.crs` | Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). | +| `assumed.encoding` | Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. | Not every loss has a code yet: losses still reported without one don't stop a strict run.