diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 28372e9887..2b884c6e24 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -169,11 +169,11 @@ impl Engine { if !selected && found.is_streamed() { // Source metadata was reported when this layer opened. A fresh whole read may // discover further notes, which must survive this boundary without replaying those. - let opened_notes: Vec = found + let opened_notes: Vec = found .source .as_ref() .and_then(|source| source.info()) - .map(|info| info.notes.iter().map(|note| format!("{}: {note}", info.name)).collect()) + .map(|info| info.notes.iter().map(|note| note.clone().prefixed(&info.name)).collect()) .unwrap_or_default(); let (ds, report) = found.load_all_reported().map_err(|e| format!("{}: {e}", found.name))?; let name = found.name.clone(); @@ -183,7 +183,7 @@ impl Engine { n => session.warn(format!("{name}: {n} rows couldn't be read and were left out")), } for message in report.messages.into_iter().filter(|message| !opened_notes.contains(message)) { - session.notify(message, false); + session.say(message); } if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{name} as GeoJSON")) { session.notify(note, false); diff --git a/crates/data/src/citygml/tests.rs b/crates/data/src/citygml/tests.rs index 1c99b89fad..e5257913d3 100644 --- a/crates/data/src/citygml/tests.rs +++ b/crates/data/src/citygml/tests.rs @@ -60,7 +60,7 @@ fn building(id: &str, inner: &str) -> String { } fn messages_of(out: &[(Dataset, ReadReport)]) -> Vec { - out.iter().flat_map(|(_, r)| r.messages.clone()).collect() + out.iter().flat_map(|(_, r)| r.messages.texts().map(str::to_string).collect::>()).collect() } fn says(out: &[(Dataset, ReadReport)], text: &str) -> bool { diff --git a/crates/data/src/cityjson/tests.rs b/crates/data/src/cityjson/tests.rs index 1ca36f1d49..46e191736b 100644 --- a/crates/data/src/cityjson/tests.rs +++ b/crates/data/src/cityjson/tests.rs @@ -32,7 +32,7 @@ fn box_shell() -> Json { } fn messages_of(out: &[(Dataset, ReadReport)]) -> Vec { - out.iter().flat_map(|(_, r)| r.messages.clone()).collect() + out.iter().flat_map(|(_, r)| r.messages.texts().map(str::to_string).collect::>()).collect() } fn says(out: &[(Dataset, ReadReport)], text: &str) -> bool { diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index b670570f84..b5e51e6c7c 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1636,9 +1636,9 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result>() .join("\n"); let layers = read("a.dxf", text.as_bytes(), &Options { crs: Some(Crs::from_epsg(4269).unwrap()), ..Options::default() }).unwrap(); - let messages: Vec<&str> = layers.iter().flat_map(|(_, report)| &report.messages).map(String::as_str).collect(); + let messages: Vec<&str> = layers.iter().flat_map(|(_, report)| &report.messages).map(|m| m.as_str()).collect(); assert_eq!(messages.len(), 1); assert!(messages[0].starts_with("1 features couldn't be converted from ")); assert!(!messages[0].contains("without Y")); @@ -2461,7 +2461,14 @@ mod tests { e.max_y, kinds.join(" "), t.elapsed(), - layers[0].1.messages.iter().filter(|m| !m.contains("coordinate system")).cloned().collect::>().join(" | ") + layers[0] + .1 + .messages + .iter() + .filter(|m| !m.contains("coordinate system")) + .map(|m| m.as_str()) + .collect::>() + .join(" | ") ); } Err(e) => println!("{name}\tERR\t{e}"), @@ -2918,7 +2925,7 @@ mod tests { ); } let notes: Vec<&str> = - layers.iter().flat_map(|(_, r)| &r.messages).filter(|m| m.contains("POLYLINE")).map(String::as_str).collect(); + layers.iter().flat_map(|(_, r)| &r.messages).filter(|m| m.contains("POLYLINE")).map(|m| m.as_str()).collect(); assert_eq!(notes, ["4 unreadable POLYLINE vertices were left out of their lines"]); let no_blocks = read("placed.dxf", text.as_bytes(), &Options { blocks: false, ..opts }).unwrap(); assert_eq!(no_blocks.len(), 1); @@ -2980,7 +2987,7 @@ mod tests { assert_eq!(lines.value(i, 8), &Value::Float(z)); } let notes: Vec<&str> = - layers.iter().flat_map(|(_, r)| &r.messages).filter(|m| m.contains("varying Z")).map(String::as_str).collect(); + layers.iter().flat_map(|(_, r)| &r.messages).filter(|m| m.contains("varying Z")).map(|m| m.as_str()).collect(); assert_eq!(notes, ["2 features lost varying Z coordinates; only the elevation attribute is kept"]); let no_blocks = read("placed.dxf", text.as_bytes(), &Options { blocks: false, ..opts }).unwrap(); assert_eq!(no_blocks.len(), 1); @@ -3299,7 +3306,7 @@ mod tests { assert_eq!(layers.iter().map(|(ds, _)| ds.features.len()).sum::(), 1); assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(0.0, 0.0)))); assert!(layers.iter().all(|(ds, r)| !ds.zm_dropped && r.messages.iter().all(|m| !m.contains("varying Z")))); - let messages: Vec<&str> = layers.iter().flat_map(|(_, r)| &r.messages).map(String::as_str).collect(); + let messages: Vec<&str> = layers.iter().flat_map(|(_, r)| &r.messages).map(|m| m.as_str()).collect(); assert_eq!(messages.len(), 1); assert!(messages[0].starts_with("1 features couldn't be converted from "), "{messages:?}"); } diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 0b1e707d3f..cec58a9b96 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -319,7 +319,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result || esri_wkt_over_code(code, wkt.as_deref()).is_some() || !wkt.as_deref().is_some_and(crate::raster::wkt::parses)) { - report.messages.push("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD".into()); + report.messages.push("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"); } let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?; if crs.is_none() diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 2a7cc14fec..5243e46fd7 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -434,7 +434,7 @@ fn a_wkt_that_isnt_utf8_is_said() { let bytes = answer(&[message(8, &message(5, wkt)), transform(false, 1.0, 0.0, 0.0), feature(&[geometry(&[], &[1, 2])])]); let (_, report) = read(&bytes, "t").unwrap(); assert_eq!( - report.messages.first().map(String::as_str), + 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") ); // Unused when a code RustGIS knows names the system: nothing to say. diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index f3c58fcc42..183f6dd9a9 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -76,7 +76,7 @@ pub struct Exported { pub date_messages: Vec, /// What reading the source lost or assumed besides the counts above /// ([`crate::source::Batch::notes`]), said as they are. - pub read_notes: Vec, + pub read_notes: crate::loss::Notes, } /// The rows a definition query excluded, or why the stored query could not be applied. @@ -251,7 +251,7 @@ fn write_chunks_as( let mut unread_dates = Vec::new(); let mut rounded_dates = Vec::new(); let mut null_text = Vec::new(); - let mut read_notes = Vec::new(); + let mut read_notes = crate::loss::Notes::new(); let mut not_utf8 = Vec::new(); let mut utc_dates = Vec::new(); let mut fine_dates = Vec::new(); diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 49fb502412..5e44f7f763 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -67,7 +67,7 @@ impl Runs { count: Some(ds.features.len() as u64), crs: "EPSG:4326".into(), indexed: false, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }; Runs { @@ -100,7 +100,7 @@ impl FeatureSource for Runs { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } @@ -246,7 +246,7 @@ fn a_streamed_export_writes_what_a_whole_export_writes() { fine_dates: if ext == "gpkg" { crate::io::fine_dates(whole.features.iter(), &whole.fields) } else { Vec::new() }, written_values: if ext == "fgb" { crate::io::written_values(whole.features.iter(), &whole.fields) } else { Vec::new() }, date_messages: Vec::new(), - read_notes: Vec::new(), + read_notes: Default::default(), }; assert_eq!(streamed, expected, "{what}"); let (a, b) = (read_back(&a), read_back(&b)); diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index f14b9aad65..d6ed830db9 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -181,7 +181,7 @@ pub fn read(name: &str, open: &dyn Fn(&str) -> Result>>, layer: O }); } // A note several layers share is said once. - let mut said: Vec = Vec::new(); + let mut said: Vec = Vec::new(); for (_, report) in &mut out.layers { report.messages.retain(|m| !said.contains(m)); said.extend(report.messages.iter().cloned()); @@ -443,7 +443,7 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { report.messages.push(format!( diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index 6845338e55..170319d5c5 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -690,14 +690,18 @@ fn planetary_systems_are_said_or_refused() { let mut report = ReadReport::default(); let (crs, t) = esri_crs(None, Some(gcs), &mut report).unwrap(); assert!(crs.is_some_and(Crs::is_planetary) && t.is_some()); - assert_eq!(report.messages.iter().filter(|m| body(m)).count(), 1, "{:?}", report.messages); + assert_eq!(report.messages.iter().filter(|m| body(&m.text)).count(), 1, "{:?}", report.messages); let e = esri_crs(None, Some(&unread(gcs)), &mut ReadReport::default()).err().unwrap().to_string(); assert!(e.contains("belongs to another body than the Earth") && e.contains("Unheard_Of"), "{e}"); let earth = r#"GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]"#; let mut report = ReadReport::default(); let (crs, t) = esri_crs(None, Some(&unread(earth)), &mut report).unwrap(); assert!(crs.is_none() && t.is_none()); - assert!(report.messages.iter().any(|m| m.contains("Unheard_Of")) && !report.messages.iter().any(body), "{:?}", report.messages); + assert!( + report.messages.iter().any(|m| m.contains("Unheard_Of")) && !report.messages.iter().any(|m| body(&m.text)), + "{:?}", + report.messages + ); } /// #1677: an EPSG code is used as a `.prj`'s own `AUTHORITY` is: when the WKT gives no shift to WGS @@ -820,7 +824,7 @@ fn a_code_gives_way_to_its_wkts_shift_or_body() { let mut report = ReadReport::default(); let (crs, _) = esri_crs(Some(code), Some(mars), &mut report).unwrap(); assert!(crs.is_some_and(Crs::is_planetary), "{code}: {crs:?}"); - assert_eq!(report.messages.iter().filter(|m| body(m)).count(), 1, "{code}: {:?}", report.messages); + assert_eq!(report.messages.iter().filter(|m| body(&m.text)).count(), 1, "{code}: {:?}", report.messages); // A method no one knows (Bonne is read, as PROJ 9.8.1 reads it). let unread = format!( r#"PROJCS["Unheard_Of",{mars},PROJECTION["Unheard_Of"],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",30.0],UNIT["Meter",1.0]]"# diff --git a/crates/data/src/georss.rs b/crates/data/src/georss.rs index 2776caa5b5..a8c27fdece 100644 --- a/crates/data/src/georss.rs +++ b/crates/data/src/georss.rs @@ -204,7 +204,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } else { format!("{lost_holes} holes in polygons were unreadable and left out") }; - report.losses.push(crate::loss::LossMessage { code: crate::loss::LossCode::DroppedRing, text: what }); + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedRing, what)); } // What the file as a whole said goes with its first layer only. let out: Vec<(Dataset, ReadReport)> = layers @@ -319,14 +319,15 @@ mod tests { assert_eq!(lossy[0].0.features.len(), 1); assert!(lossy[0].0.features[0].geometry.is_some()); assert!( - lossy[0].1.losses.iter().any(|m| m.code == crate::loss::LossCode::DroppedRing && m.text.contains("1 hole in a polygon was unreadable and left out")), + lossy[0].1.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedRing) + && m.text.contains("1 hole in a polygon was unreadable and left out")), "{:?}", lossy[0].1.messages ); let clean = read("clean.rss", feed("45.2 -110.2 45.8 -110.2 45.8 -110.8 45.2 -110.2").as_bytes()).unwrap(); assert_eq!(clean[0].0.features.len(), 1); - assert!(clean[0].1.losses.is_empty()); + assert!(clean[0].1.messages.iter().all(|m| m.loss.is_none())); let multi = r#" @@ -339,7 +340,11 @@ mod tests { "#; let lossy_multi = read("multi.rss", multi.as_bytes()).unwrap(); assert!( - lossy_multi[0].1.losses.iter().any(|m| m.text.contains("2 holes in polygons were unreadable and left out")), + lossy_multi[0] + .1 + .messages + .iter() + .any(|m| m.loss.is_some() && m.text.contains("2 holes in polygons were unreadable and left out")), "{:?}", lossy_multi[0].1.messages ); @@ -355,7 +360,11 @@ mod tests { "#; let mixed_lossy = read("mixed.rss", mixed.as_bytes()).unwrap(); assert!( - mixed_lossy[0].1.losses.iter().any(|m| m.text.contains("1 hole in a polygon was unreadable and left out")), + mixed_lossy[0] + .1 + .messages + .iter() + .any(|m| m.loss.is_some() && m.text.contains("1 hole in a polygon was unreadable and left out")), "{:?}", mixed_lossy[0].1.messages ); diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index e99095b83b..972b92a18b 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -732,7 +732,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> )); } if file_srs.is_none() && outside { - rep.messages.push("the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude".into()); + rep.messages.push("the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude"); } // Said with the layer it happened in, which may be the only one added. if kind.lost > 0 { @@ -1000,7 +1000,7 @@ mod tests { let layers = read("p.gml", gml.as_bytes()).unwrap(); let (ds, rep) = &layers[0]; assert_eq!((ds.features.len(), rep.skipped), (2, 0)); - let said: Vec<&String> = rep.messages.iter().filter(|m| m.contains("or surface patch")).collect(); + let said: Vec<&crate::loss::Note> = rep.messages.iter().filter(|m| m.contains("or surface patch")).collect(); assert_eq!(said.len(), 1, "{:?}", rep.messages); assert!(said[0].contains(": 1 ring or surface patch of a geometry was left out"), "{said:?}"); assert!(rep.messages.iter().any(|m| m.contains(": 1 part of multi-geometries")), "{:?}", rep.messages); @@ -1047,7 +1047,7 @@ mod tests { let (ds, rep) = &layers[0]; assert_eq!((ds.features.len(), rep.skipped), (2, 0)); assert!(matches!(&ds.features[1].geometry, Some(Geometry::Line(l)) if l.len() == 2)); - let said: Vec<&String> = rep.messages.iter().filter(|m| m.contains("multi-geometries")).collect(); + let said: Vec<&crate::loss::Note> = rep.messages.iter().filter(|m| m.contains("multi-geometries")).collect(); assert_eq!(said, ["m: 1 part of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)"]); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 183af52178..c5a60512d5 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1771,7 +1771,9 @@ impl Collector { if report.skipped > 0 { report.messages.push(format!("{} features had unreadable geometry", report.skipped)); } - let declared = declared_crs(root, &mut report.messages)?; + let mut said = Vec::new(); + let declared = declared_crs(root, &mut said)?; + report.messages.extend(said); let mut unconverted = 0usize; // Only features kept count toward the heights dropped. let mut zm = 0usize; @@ -3645,7 +3647,7 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result 0 { @@ -4015,7 +4017,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio } ds.crs_incomplete = unconverted > 0; if unconverted > 0 && converted == 0 { - report.messages.push("no shape could be converted to longitude/latitude: the .prj doesn't seem to match the coordinates".into()); + report.messages.push("no shape could be converted to longitude/latitude: the .prj doesn't seem to match the coordinates"); } else if unconverted > 0 { report.messages.push(format!("{unconverted} shapes couldn't be converted to longitude/latitude and have no geometry")); } @@ -6462,7 +6464,7 @@ mod tests { }; let (wells, flat) = (shp("wells.shp", true), shp("flat.shp", false)); let (ds, rep) = read_path(&wells).unwrap(); - assert!(ds.zm_dropped && rep.messages.contains(&crate::zm_note(Some(1))), "{:?}", rep.messages); + assert!(ds.zm_dropped && rep.messages.says(&crate::zm_note(Some(1))), "{:?}", rep.messages); assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 2.0)))); let (ds, rep) = read_path(&flat).unwrap(); assert!(!ds.zm_dropped && !said(&rep)); @@ -8147,7 +8149,7 @@ mod tests { } shp }; - let said = |m: &[String]| m.iter().any(|m| m.contains("isn't a number")); + let said = |m: &[crate::loss::Note]| m.iter().any(|m| m.contains("isn't a number")); let bad = write("bad.shp", &[(f64::NAN, 20.0), (11.0, 21.0), (f64::INFINITY, 22.0)]); let (ds, rep) = read_path(&bad).unwrap(); assert_eq!(ds.features.len(), 3, "the features are kept"); @@ -8157,10 +8159,8 @@ mod tests { assert_eq!(ds.geometry_type, GeometryType::Point); assert_eq!(ds.unsaved_coordinates(), 0); assert!( - rep.messages.contains( - &"bad: 2 shape(s) have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry" - .to_string() - ), + rep.messages + .says("bad: 2 shape(s) have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry"), "{:?}", rep.messages ); @@ -8690,7 +8690,7 @@ mod tests { // A long list of skipped members names the first ones and counts the rest. let layers = read_zip("x.zip", &crate::zip::write(&mifs(MAX_ZIP_LAYERS + 25)).unwrap()).unwrap(); let note = &layers[0].1.messages[0]; - assert!(note.contains("m51.mif") && !note.contains("m52.mif") && note.ends_with("; and 5 more"), "{note}"); + assert!(note.contains("m51.mif") && !note.contains("m52.mif") && note.ends_with("; and 5 more"), "{note:?}"); } /// A Shapefile's loose files picked or dropped together are zipped into one, which reads as a diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 00c40ee7c9..08fe365ae0 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -871,7 +871,7 @@ mod tests { ]]])) ); assert!(layers.iter().all(|l| l.dataset.features[0].attrs[0] == Value::Text("kept".into()))); - let messages: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(String::as_str)).collect(); + let messages: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(|m| m.as_str())).collect(); assert_eq!( messages, [ @@ -1021,7 +1021,7 @@ mod tests { // have none. assert!(layers[0].dataset.zm_dropped && layers[1].dataset.zm_dropped && !layers[2].dataset.zm_dropped); let said = format!("trip lines: {}", crate::zm_note(Some(1))); - assert!(layers[1].report.messages.contains(&said), "{:?}", layers[1].report.messages); + assert!(layers[1].report.messages.says(&said), "{:?}", layers[1].report.messages); // The ground overlay has no box: it can't be laid out. let (overlays, undrawn, over_budget) = ground_overlays("t.kml", DOC.as_bytes()).unwrap(); assert_eq!((overlays.len(), undrawn, over_budget), (0, 1, 0)); diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 4e7813a336..aeba0300cf 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -76,7 +76,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result report .messages - .push("the file doesn't say its coordinate system (give \"crs\", such as EPSG:2263): coordinates are kept as they are".into()), + .push("the file doesn't say its coordinate system (give \"crs\", such as EPSG:2263): coordinates are kept as they are"), } let mut skipped = 0usize; let mut missing_parcels = 0usize; diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index a91387650b..ad59d7b853 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -695,9 +695,8 @@ impl Serialize for Dataset { #[derive(Clone, Debug, Default, PartialEq)] pub struct ReadReport { pub skipped: usize, - pub messages: Vec, - /// Classified losses to publish alongside the ordinary messages. - pub losses: Vec, + /// What the read says, each loss with its code ([`loss::Note`]). + pub messages: loss::Notes, /// The files read and the rows read from them, when the read recorded them /// ([`sync::FileSync::around`]): what a layer kept in the project compares with its source /// before writing edits back. @@ -713,13 +712,6 @@ pub struct ReadReport { pub extrusion: Option, } -impl ReadReport { - /// All report messages in their text form for consumers that do not carry loss codes. - pub fn into_messages(self) -> impl Iterator { - self.messages.into_iter().chain(self.losses.into_iter().map(|loss| loss.text)) - } -} - /// An extrusion a reader suggests for a layer of polygons: heights from one field, on a base from /// another. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 4149d044ba..ccf1150602 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -97,10 +97,255 @@ pub struct LossMessage { pub text: String, } +/// Something a reader, writer or tool says, and the loss it reports, if any: the code travels +/// with the text wherever the text goes, to the notice that says it. +/// +/// It has no `Display` and turns into no `String`, so a code isn't dropped by formatting the note +/// or passing it on as text: [`Note::prefixed`] and [`Note::map_text`] keep it. The words alone +/// ([`Note::text`], [`Note::as_str`], [`Notes::texts`]) are for sinks that show or store text +/// only, such as a manifest or a refusal's message; a note read through them loses its code. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Note { + pub text: String, + pub loss: Option, +} + +impl Note { + /// A note that reports a loss. + pub fn loss(code: LossCode, text: impl Into) -> Self { + Self { text: text.into(), loss: Some(code) } + } + + /// A note that reports no loss. + pub fn plain(text: impl Into) -> Self { + Self { text: text.into(), loss: None } + } + + /// The same note, its text after `prefix: ` (the layer or file it is about). + pub fn prefixed(self, prefix: &str) -> Self { + Self { text: format!("{prefix}: {}", self.text), loss: self.loss } + } + + /// The same note, its text changed by `f` (a qualifier added). + pub fn map_text(self, f: impl FnOnce(String) -> String) -> Self { + Self { text: f(self.text), loss: self.loss } + } + + pub fn as_str(&self) -> &str { + &self.text + } + + pub fn contains(&self, pattern: &str) -> bool { + self.text.contains(pattern) + } + + pub fn starts_with(&self, pattern: &str) -> bool { + self.text.starts_with(pattern) + } + + pub fn ends_with(&self, pattern: &str) -> bool { + self.text.ends_with(pattern) + } +} + +impl From for Note { + fn from(text: String) -> Self { + Self::plain(text) + } +} + +impl From<&str> for Note { + fn from(text: &str) -> Self { + Self::plain(text) + } +} + +impl From<&String> for Note { + fn from(text: &String) -> Self { + Self::plain(text.as_str()) + } +} + +impl From for Note { + fn from(loss: LossMessage) -> Self { + Self::loss(loss.code, loss.text) + } +} + +/// A plain note equals its words; a note that reports a loss equals no plain text. +impl PartialEq for Note { + fn eq(&self, other: &str) -> bool { + self.loss.is_none() && self.text == other + } +} + +impl PartialEq<&str> for Note { + fn eq(&self, other: &&str) -> bool { + self == *other + } +} + +impl PartialEq for Note { + fn eq(&self, other: &String) -> bool { + self == other.as_str() + } +} + +/// What a reader, a source or a write says, in order: plain text pushed onto it stays plain, and +/// a [`Note::loss`] keeps its code. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Notes(Vec); + +impl Notes { + pub fn new() -> Self { + Self(Vec::new()) + } + + pub fn push(&mut self, note: impl Into) { + self.0.push(note.into()); + } + + pub fn insert(&mut self, at: usize, note: impl Into) { + self.0.insert(at, note.into()); + } + + pub fn retain(&mut self, keep: impl FnMut(&Note) -> bool) { + self.0.retain(keep); + } + + pub fn clear(&mut self) { + self.0.clear(); + } + + pub fn truncate(&mut self, len: usize) { + self.0.truncate(len); + } + + pub fn drain(&mut self, range: impl std::ops::RangeBounds) -> std::vec::Drain<'_, Note> { + self.0.drain(range) + } + + pub fn dedup(&mut self) { + self.0.dedup(); + } + + pub fn pop(&mut self) -> Option { + self.0.pop() + } + + /// Their words alone, without their codes: for a sink that shows or stores text only. + pub fn texts(&self) -> impl Iterator { + self.0.iter().map(Note::as_str) + } + + /// Whether one of them has the text `text`, whatever its code: a match by wording alone, + /// where `==` with a string matches a plain note only. + pub fn says(&self, text: &str) -> bool { + self.0.iter().any(|n| n.text == text) + } + + /// Each, its text after `prefix: `. + pub fn prefixed(self, prefix: &str) -> Self { + Self(self.0.into_iter().map(|n| n.prefixed(prefix)).collect()) + } + + pub fn into_vec(self) -> Vec { + self.0 + } +} + +impl std::ops::Deref for Notes { + type Target = [Note]; + fn deref(&self) -> &[Note] { + &self.0 + } +} + +impl> Extend for Notes { + fn extend>(&mut self, notes: I) { + self.0.extend(notes.into_iter().map(Into::into)); + } +} + +impl> FromIterator for Notes { + fn from_iter>(notes: I) -> Self { + Self(notes.into_iter().map(Into::into).collect()) + } +} + +impl> From> for Notes { + fn from(notes: Vec) -> Self { + notes.into_iter().collect() + } +} + +impl IntoIterator for Notes { + type Item = Note; + type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> IntoIterator for &'a Notes { + type Item = &'a Note; + type IntoIter = std::slice::Iter<'a, Note>; + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl PartialEq<[S; N]> for Notes +where + Note: PartialEq, +{ + fn eq(&self, other: &[S; N]) -> bool { + self.0.len() == N && self.0.iter().zip(other).all(|(a, b)| a == b) + } +} + +impl PartialEq<&[S]> for Notes +where + Note: PartialEq, +{ + fn eq(&self, other: &&[S]) -> bool { + self.0.len() == other.len() && self.0.iter().zip(other.iter()).all(|(a, b)| a == b) + } +} + +impl PartialEq> for Notes +where + Note: PartialEq, +{ + fn eq(&self, other: &Vec) -> bool { + self.0.len() == other.len() && self.0.iter().zip(other).all(|(a, b)| a == b) + } +} + #[cfg(test)] mod tests { use super::*; + /// A plain note equals its words and a coded one no plain words; prefixing, rewording, + /// collecting and extending keep a code; `says` matches by wording alone. + #[test] + fn notes_keep_their_codes() { + let plain = Note::plain("3 rows left out"); + let coded = Note::loss(LossCode::DroppedRing, "1 ring left out"); + assert_eq!(plain, "3 rows left out"); + assert_ne!(coded, "1 ring left out"); + assert_eq!(coded.clone().prefixed("a.rss"), Note::loss(LossCode::DroppedRing, "a.rss: 1 ring left out")); + assert_eq!(coded.clone().map_text(|t| format!("{t}, in the view")).loss, Some(LossCode::DroppedRing)); + let mut notes: Notes = ["first"].into_iter().collect(); + notes.push(coded.clone()); + notes.extend([plain.clone()]); + assert_eq!(notes.iter().map(|n| n.loss).collect::>(), [None, Some(LossCode::DroppedRing), None]); + assert!(notes.says("1 ring left out") && !notes.says("1 ring")); + assert_eq!(notes.clone().prefixed("x")[1], Note::loss(LossCode::DroppedRing, "x: 1 ring left out")); + assert_ne!(notes, ["first", "1 ring left out", "3 rows left out"]); + assert_eq!(Notes::from(vec![String::from("a")]), ["a"]); + } + #[test] fn codes_are_unique_and_named_after_their_kind() { for (i, code) in LossCode::ALL.iter().enumerate() { diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index cddb2cdf0b..39de9e8bd2 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -354,7 +354,7 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe report.messages.push(e); } if !columns.is_empty() && mid.is_none() { - report.messages.push("no .mid file next to the .mif: the attributes are empty".into()); + report.messages.push("no .mid file next to the .mif: the attributes are empty"); } // The rows, one per object. let mut rows: Vec> = Vec::new(); diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 5c085e2142..307368be2f 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -671,7 +671,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> if osm.capped { report .messages - .push("the extract is larger than RustGIS reads at once: the rest is left out (use a smaller extract; on the desktop, files over 256 MB open through GDAL when it is installed)".into()); + .push("the extract is larger than RustGIS reads at once: the rest is left out (use a smaller extract; on the desktop, files over 256 MB open through GDAL when it is installed)"); } if missing > 0 { report.messages.push(format!("{missing} ways or relations refer to nodes or ways the file doesn't hold")); diff --git a/crates/data/src/publish/json.rs b/crates/data/src/publish/json.rs index 9d9ccdd42d..d0ac422ea5 100644 --- a/crates/data/src/publish/json.rs +++ b/crates/data/src/publish/json.rs @@ -37,9 +37,10 @@ pub fn geojson(ds: &Dataset, path: &Path, synced: &Synced) -> Result // What the read skipped or said can't be rewritten: refused with what it said, rather than // taken for rows the layer added, removed or reordered. if report.skipped > 0 || !report.messages.is_empty() { - let mut said = report.messages.clone(); + let mut said: Vec<&str> = report.messages.texts().collect(); + let skipped = format!("{} features couldn't be read", report.skipped); if said.is_empty() { - said.push(format!("{} features couldn't be read", report.skipped)); + said.push(&skipped); } return Err(refused(path, format!("reading it isn't lossless ({}), so a rewrite wouldn't keep the file", said.join("; ")))); } diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 3dfcf59a01..531bce1624 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -797,7 +797,7 @@ mod tests { assert_eq!(ds.features.len(), 2); assert_eq!(ds.features.iter().filter(|f| f.geometry.is_none()).count(), 1); assert!( - report.messages.contains(&"1 value in 'wkt' isn't a date and was read as empty, so its row has no geometry".to_string()), + report.messages.says("1 value in 'wkt' isn't a date and was read as empty, so its row has no geometry"), "{:?}", report.messages ); diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index b0a40b7937..73f2ba4267 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -196,7 +196,7 @@ pub fn open_now(remote: Arc) -> Result { count: Some(count), crs: held.label(), indexed: true, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }; if first.as_ref().is_some_and(|p| p.losses.with_zm > 0) { @@ -206,7 +206,7 @@ pub fn open_now(remote: Arc) -> Result { // the other sources, and each read says what its own features lost ([`Batch::notes`]). info.notes.extend(first.iter().flat_map(|p| p.report.messages.iter().cloned())); if !sample { - info.notes.push("its queries don't take standardized SQL, so a view holding more features than are drawn shows the first ones by object id rather than a sample of all of them".into()); + info.notes.push("its queries don't take standardized SQL, so a view holding more features than are drawn shows the first ones by object id rather than a sample of all of them"); } Ok(ArcgisSource { remote, query, info, oid, oid_at, page: std::sync::atomic::AtomicUsize::new(page), sample, held, to_lonlat, out_sr }) } @@ -600,7 +600,7 @@ impl ArcgisSource { let matched = if complete { features.len() as u64 } else { matched }; let mut notes = self.notes(losses, view.is_some()); notes.extend(shortfall(short)); - Ok(Batch { features, matched, complete, skipped, notes, ..Batch::default() }) + Ok(Batch { features, matched, complete, skipped, notes: notes.into(), ..Batch::default() }) } /// A count's answer, or `None` when it isn't fetched yet (noted as missing). @@ -824,7 +824,7 @@ impl FeatureSource for ArcgisSource { let mut notes = self.notes(losses, view.is_some()); let short = total.saturating_sub(received); notes.extend(shortfall(short)); - Ok(Batch { matched: visited, complete: short == 0, skipped, notes, ..Batch::default() }) + Ok(Batch { matched: visited, complete: short == 0, skipped, notes: notes.into(), ..Batch::default() }) } } } diff --git a/crates/data/src/source/arcgis/tests.rs b/crates/data/src/source/arcgis/tests.rs index a61d38c164..06b014f609 100644 --- a/crates/data/src/source/arcgis/tests.rs +++ b/crates/data/src/source/arcgis/tests.rs @@ -559,7 +559,7 @@ fn a_materialized_layer_says_each_loss_once() { let src = open_blocking(&query).unwrap(); let (ds, report) = crate::source::materialize(&src).unwrap(); assert_eq!(ds.features.len(), FEATURES as usize); - let said: Vec<&String> = report.messages.iter().filter(|m| m.contains(want)).collect(); + let said: Vec<&crate::loss::Note> = report.messages.iter().filter(|m| m.contains(want)).collect(); assert_eq!(said.len(), 1, "{host}: {:?}", report.messages); } let (query, _) = service("live-once-clean.test", 30, true, None); diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 02f28089e1..1684fe934b 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -277,7 +277,7 @@ impl FgbSource { crs: reproject.info_crs(), // The crate's index search assumes the default node size; other files are scanned. indexed: h.index_node_size() == flatgeobuf::packed_r_tree::PackedRTree::DEFAULT_NODE_SIZE && count > 0, - notes, + notes: notes.into(), zm_dropped: false, }; info.note_columns( diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index 0402ea51f5..b6e956cff8 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -394,7 +394,7 @@ pub fn convert_one(src: &Path, layer: &str, family: Option, crs: Option< #[derive(Debug)] pub struct FreshConverted { pub path: PathBuf, - pub notes: Vec, + pub notes: crate::loss::Notes, /// A successful read confirmed that this declared layer contains no features. pub empty: bool, pub zm_dropped: bool, @@ -483,7 +483,7 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option = fresh.notes.iter().filter(|n| n.to_ascii_lowercase().contains("integer overflow")).collect(); + let overflow: Vec<_> = fresh.notes.iter().filter(|n| n.text.to_ascii_lowercase().contains("integer overflow")).collect(); if lossy { assert_eq!(overflow.len(), 1, "{:?}", fresh.notes); assert!(overflow[0].ends_with("(3 occurrence(s))"), "{overflow:?}"); diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 93bc358a99..932b1b7dba 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -272,7 +272,7 @@ impl GeoJsonSource { count: Some((scan.places.len() - failed.len()) as u64), crs: reproject.label(), indexed: false, - notes, + notes: notes.into(), zm_dropped: false, }; // Features the declared system can't convert are left out, and so are their heights. @@ -426,7 +426,7 @@ impl FeatureSource for GeoJsonSource { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 97fd4b5eb7..e7b1706127 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -308,7 +308,7 @@ impl GpkgSource { // (`SourceInfo::coordinate_system`), as a Shapefile's .prj does (#1476). crs: reproject.info_crs(), indexed: rtree.is_some(), - notes, + notes: notes.into(), zm_dropped: false, }; let file = Some((path.to_path_buf(), id)); @@ -322,7 +322,7 @@ impl GpkgSource { Some((z, m)) if z == 2 || m == 2 => match src.peek_zm() { Some(true) => src.info.drop_zm(None), Some(false) => {} - None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep".into()), + None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep"), }, _ => {} } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 2a8c428d4c..ad1721491e 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -222,7 +222,7 @@ impl GpkgMemSource { // (`SourceInfo::coordinate_system`), as a Shapefile's .prj does (#1476). crs: reproject.info_crs(), indexed: false, - notes, + notes: notes.into(), zm_dropped: false, }; let mut src = GpkgMemSource { info, db, table, geom_col, field_cols, reproject }; @@ -245,7 +245,7 @@ impl GpkgMemSource { match src.peek_zm() { Some(true) => src.info.drop_zm(None), Some(false) => {} - None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep".into()), + None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep"), } } Ok(src) @@ -422,7 +422,7 @@ impl FeatureSource for GpkgMemSource { unread_dates, rounded_dates, null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } diff --git a/crates/data/src/source/lidar.rs b/crates/data/src/source/lidar.rs index e3ec5a3f76..20a02393ee 100644 --- a/crates/data/src/source/lidar.rs +++ b/crates/data/src/source/lidar.rs @@ -33,7 +33,8 @@ impl LidarSource { let Dataset { name, geometry_type, fields, features, crs_incomplete, .. } = ds; let extent = features.iter().filter_map(|f| f.geometry.as_ref()).fold(Extent::EMPTY, |e, g| e.union(&g.extent())); // The reader's messages start with the layer's name, which the source's notes add. - let notes = report.messages.iter().map(|m| m.strip_prefix(&format!("{name}: ")).unwrap_or(m).to_string()).collect(); + let prefix = format!("{name}: "); + let notes = report.messages.into_iter().map(|m| m.map_text(|t| t.strip_prefix(&prefix).map(str::to_string).unwrap_or(t))).collect(); let info = SourceInfo { name, format: "LiDAR", @@ -93,7 +94,7 @@ impl FeatureSource for LidarSource { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3a4bc5026e..28ee0adae2 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -173,7 +173,7 @@ pub struct SourceInfo { pub indexed: bool, /// Things worth telling whoever adds the source (an unknown coordinate system read as /// longitude/latitude, tables left out). - pub notes: Vec, + pub notes: crate::loss::Notes, /// The source has Z or M values, which reading drops (see [`Dataset::zm_dropped`]). pub zm_dropped: bool, } @@ -257,7 +257,7 @@ pub struct Batch { pub null_text: Vec, /// What else the read lost or assumed, one note per kind with its count (values that don't fit /// their field, rings without area): said as they are. - pub notes: Vec, + pub notes: crate::loss::Notes, /// Text values of a Shapefile that aren't valid in the encoding they were read in /// ([`FeatureSource::text_encoding`]), so hold U+FFFD in place of those bytes, counted for each /// field by its position. Said by [`not_utf8_note`]. @@ -723,18 +723,17 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, let unread_dates = unread_dates_note(&info.fields, &unread_dates); let mut report = ReadReport { skipped: skipped + src.skipped_at_open(), - messages: info.notes.iter().map(|n| format!("{}: {n}", info.name)).collect(), + messages: info.notes.clone().prefixed(&info.name), synced: None, unread_dates: unread_dates.clone(), rounded_dates: rounded.clone(), extrusion: None, - losses: Vec::new(), }; let null_text = null_text_note(&info.fields, &null_text); let not_utf8 = not_utf8_note(&info.fields, ¬_utf8, src.text_encoding()); - report.messages.extend( - unread_dates.into_iter().chain(rounded).chain(null_text).chain(notes).chain(not_utf8).map(|n| format!("{}: {n}", info.name)), - ); + report.messages.extend(unread_dates.into_iter().chain(rounded).chain(null_text).map(|n| format!("{}: {n}", info.name))); + report.messages.extend(notes.prefixed(&info.name)); + report.messages.extend(not_utf8.into_iter().map(|n| format!("{}: {n}", info.name))); if ds.geometry_type == GeometryType::None && let Some(g) = ds.features.iter().find_map(|f| f.geometry.as_ref()) { diff --git a/crates/data/src/source/mysql.rs b/crates/data/src/source/mysql.rs index 297a259942..ce713b2274 100644 --- a/crates/data/src/source/mysql.rs +++ b/crates/data/src/source/mysql.rs @@ -824,7 +824,7 @@ impl MysqlSource { count: None, crs: if srid == 0 { "EPSG:4326".into() } else { format!("EPSG:{srid}") }, indexed: false, - notes, + notes: notes.into(), zm_dropped: false, }, conn, @@ -843,7 +843,7 @@ impl MysqlSource { if src.info.count != Some(0) { src.info.extent = src.measure(); if src.info.extent.is_empty() { - src.info.notes.push("the table's extent couldn't be measured in time: zooming to the layer does nothing".into()); + src.info.notes.push("the table's extent couldn't be measured in time: zooming to the layer does nothing"); } } Ok(src) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 0f23118234..06bd3dd13b 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -315,7 +315,7 @@ impl ParquetSource { count, crs: reproject.label(), indexed: covering.is_some(), - notes, + notes: notes.into(), zm_dropped: false, }; info.note_columns( @@ -347,7 +347,7 @@ impl ParquetSource { match src.peek_zm() { Some(true) => src.info.drop_zm(None), Some(false) => {} - None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep".into()), + None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep"), } } if src.info.geometry_type == GeometryType::None { @@ -692,7 +692,7 @@ impl FeatureSource for ParquetSource { unread_dates, rounded_dates, null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 739359e70f..715cd88972 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -995,7 +995,7 @@ impl PostgisSource { count: None, crs: if srid == 0 { "EPSG:4326".into() } else { format!("EPSG:{srid}") }, indexed: false, - notes, + notes: notes.into(), zm_dropped: false, }, conn, @@ -1034,7 +1034,7 @@ impl PostgisSource { match zm { Some(true) => src.info.drop_zm(None), Some(false) => {} - None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep".into()), + None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep"), } Ok(src) } @@ -1790,7 +1790,7 @@ mod tests { count: None, crs: "EPSG:4326".into(), indexed: false, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }, conn: Arc::new(Conn { diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index aff36cb0a6..da2b7e3416 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -198,7 +198,7 @@ impl ShpSource { // (`SourceInfo::coordinate_system`) as a whole read does. crs: reproject.crs.definition_text(), indexed: index.indexed(), - notes, + notes: notes.into(), zm_dropped: false, }; // PointZ … MultiPointM: the header's type says every shape carries Z or M values. diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 38d95f382a..1147c71ffe 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -668,7 +668,7 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( let r = Reproject::from_crs(crs, &mut Vec::new()); assert!(r.extent_from_lonlat(&view).is_none(), "the view's edge is refused"); const SAID: &str = "have a coordinate that isn't a number under a bounding box that is one"; - let said = |notes: &[String]| notes.iter().filter(|n| n.contains(SAID)).cloned().collect::>(); + let said = |notes: &[crate::loss::Note]| notes.iter().filter(|n| n.contains(SAID)).map(|n| n.text.clone()).collect::>(); let reads = |src: &dyn FeatureSource| { let read = src.read(&Request { extent: Some(view), ..Request::all() }).unwrap(); let mut kept = 0; @@ -722,7 +722,7 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { p }; const SAID: &str = "have a coordinate that isn't a number under a bounding box that is one"; - let said = |notes: &[String]| notes.iter().filter(|n| n.contains(SAID)).cloned().collect::>(); + let said = |notes: &[crate::loss::Note]| notes.iter().filter(|n| n.contains(SAID)).map(|n| n.text.clone()).collect::>(); let chunk_notes = |src: &dyn FeatureSource, extent| { let batch = src.visit_chunks(extent, 1 << 20, &mut |_| Ok(())).unwrap(); (batch.skipped, said(&batch.notes)) diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 9f0b02d426..46a6c915d0 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -892,7 +892,7 @@ impl SqlServerSource { count: None, crs: if srid == 0 { "EPSG:4326".into() } else { format!("EPSG:{srid}") }, indexed: false, - notes, + notes: notes.into(), zm_dropped: false, }, conn, @@ -909,7 +909,7 @@ impl SqlServerSource { if src.info.count != Some(0) { src.info.extent = src.measure(); if src.info.extent.is_empty() { - src.info.notes.push("the table's extent couldn't be measured in time: zooming to the layer does nothing".into()); + src.info.notes.push("the table's extent couldn't be measured in time: zooming to the layer does nothing"); } src.check_zm(); } @@ -1398,7 +1398,7 @@ mod tests { count: Some(3), crs: "EPSG:4326".into(), indexed: false, - notes: vec![], + notes: Default::default(), zm_dropped: false, }; note_zm(&mut info, probe); @@ -1590,7 +1590,7 @@ mod tests { let zm = open(&zm_name); let flat = open(&flat_name); run(&format!("DROP TABLE dbo.{zm_name}; DROP TABLE dbo.{flat_name}")); - assert!(zm.zm_dropped && zm.notes.contains(&crate::zm_note(Some(2))), "{:?}", zm.notes); + assert!(zm.zm_dropped && zm.notes.says(&crate::zm_note(Some(2))), "{:?}", zm.notes); assert!(!flat.zm_dropped && !flat.notes.iter().any(|n| n.contains("Z or M")), "{:?}", flat.notes); } } diff --git a/crates/data/src/source/sqlserver_gdb.rs b/crates/data/src/source/sqlserver_gdb.rs index 5b0a24ab34..447ccff021 100644 --- a/crates/data/src/source/sqlserver_gdb.rs +++ b/crates/data/src/source/sqlserver_gdb.rs @@ -437,7 +437,7 @@ pub fn read_table(conn: &Conn, item: &Item, limit: usize) -> Result<(Dataset, Re }) .collect(); let unread_dates = crate::source::unread_dates_note(&fields, &unread); - let mut report = ReadReport { messages: reading.notes.clone(), unread_dates: unread_dates.clone(), ..Default::default() }; + let mut report = ReadReport { messages: reading.notes.clone().into(), unread_dates: unread_dates.clone(), ..Default::default() }; report.messages.extend(unread_dates); report.messages.extend(left_out_note(&left_out)); let count_sql = format!("SELECT COUNT_BIG(*) FROM {} t", reading.from); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 62d3714c87..1fd2d08b02 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -734,7 +734,7 @@ fn materialize_refuses_oversized_and_incomplete_sources() { count: Some(MAX_LIMIT as u64 + 1), crs: "EPSG:4326".into(), indexed: false, - notes: vec![], + notes: Default::default(), zm_dropped: false, }, batch: None, @@ -811,7 +811,7 @@ fn geoparquet_planetary_systems_are_said_or_refused() { let p = d.join("mars.parquet"); write_parquet_typed(&p, false, &mars("GeographicCRS", 49900, "east")); let src = open_path(&p, None).unwrap(); - assert_eq!(src.info().notes.iter().filter(|m| body(m)).count(), 1, "{:?}", src.info().notes); + assert_eq!(src.info().notes.iter().filter(|m| body(&m.text)).count(), 1, "{:?}", src.info().notes); assert!(!src.info().notes.iter().any(|m| m.contains("no EPSG code")), "{:?}", src.info().notes); let (ds, _) = materialize(src.as_ref()).unwrap(); assert_eq!( @@ -841,7 +841,7 @@ fn geoparquet_planetary_systems_are_said_or_refused() { // Earth one. write_parquet_typed(&p, false, &no_id(mars("GeographicCRS", 49900, "east"))); let notes = open_path(&p, None).unwrap().info().notes.clone(); - let said: Vec<&String> = notes.iter().filter(|m| body(m)).collect(); + let said: Vec<&crate::loss::Note> = notes.iter().filter(|m| body(&m.text)).collect(); assert_eq!(said.len(), 1, "{notes:?}"); assert!(said[0].contains("as only its ellipsoid says") && !said[0].contains("code"), "{said:?}"); write_parquet_typed(&p, false, r#"["Point"],"crs":{"type":"GeographicCRS","name":"WGS 84","id":{"authority":"EPSG","code":4326}}"#); @@ -888,7 +888,7 @@ fn geoparquet_planetary_systems_are_said_or_refused() { ] { write_parquet_typed(&p, false, &axes(kind, id, &cs)); let src = open_path(&p, None).unwrap_or_else(|e| panic!("{kind} {cs} {id}: {e}")); - assert_eq!(src.info().notes.iter().filter(|m| body(m)).count(), 1, "{kind} {cs} {id}: {:?}", src.info().notes); + assert_eq!(src.info().notes.iter().filter(|m| body(&m.text)).count(), 1, "{kind} {cs} {id}: {:?}", src.info().notes); let (ds, _) = materialize(src.as_ref()).unwrap(); assert_eq!(ds.features.len(), points().len()); } @@ -897,7 +897,7 @@ fn geoparquet_planetary_systems_are_said_or_refused() { for cs in [lonlat(r#""radian""#, r#""radian""#), xyz.to_string()] { write_parquet_typed(&p, false, &axes("GeographicCRS", "", &cs).replace("3396190", "6378137")); let notes = open_path(&p, None).unwrap().info().notes.clone(); - assert!(!notes.iter().any(body), "{notes:?}"); + assert!(!notes.iter().any(|m| body(&m.text)), "{notes:?}"); } } @@ -1198,7 +1198,10 @@ fn custom_srs_reads(path: &Path) -> Vec<(Option, Vec)> { .into_iter() .map(|src| { let batch = src.read(&Request::all()).unwrap(); - (lonlat_of(src, batch.features.first().and_then(|f| f.geometry.clone())), src.info().notes.clone()) + ( + lonlat_of(src, batch.features.first().and_then(|f| f.geometry.clone())), + src.info().notes.texts().map(str::to_string).collect(), + ) }) .collect() } @@ -1421,7 +1424,10 @@ fn fgb_reads(path: &Path) -> Vec<(Option, Vec)> { .into_iter() .map(|src| { let batch = src.read(&Request::all()).unwrap(); - (lonlat_of(src.as_ref(), batch.features.first().and_then(|f| f.geometry.clone())), src.info().notes.clone()) + ( + lonlat_of(src.as_ref(), batch.features.first().and_then(|f| f.geometry.clone())), + src.info().notes.texts().map(str::to_string).collect(), + ) }) .collect() } @@ -2671,7 +2677,7 @@ fn geojson_in_place_rejects_partial_collections_with_a_notice() { let (ds, streamed_report) = materialize(&src).unwrap(); assert_eq!(ds.features, whole.features); assert_eq!(streamed_report.skipped, report.skipped); - assert_eq!(streamed_report.messages, report.messages.iter().map(|m| format!("x: {m}")).collect::>()); + assert_eq!(streamed_report.messages, report.messages.clone().prefixed("x")); } std::fs::remove_file(p).unwrap(); } @@ -2753,7 +2759,7 @@ fn geojson_paths(file: &str, text: &str) -> (Dataset, Vec, String) { assert_eq!(inplace.crs_incomplete, whole.crs_incomplete, "{file}"); assert_eq!(inplace.geometry_type, whole.geometry_type, "{file}"); assert_eq!(report.skipped, in_report.skipped, "{file}"); - let strip = |m: &Vec| m.iter().map(|m| m.trim_start_matches("x: ").to_string()).collect::>(); + let strip = |m: &crate::loss::Notes| m.iter().map(|m| m.text.trim_start_matches("x: ").to_string()).collect::>(); assert_eq!(strip(&report.messages), strip(&in_report.messages), "{file}"); // The extent a source says is that of the features it reads (those that convert). assert_eq!(src.info().extent, whole.lonlat_extent(), "{file}"); @@ -2764,7 +2770,7 @@ fn geojson_paths(file: &str, text: &str) -> (Dataset, Vec, String) { let src = geojson::GeoJsonSource::open_with(&p, "x", crate::io::BYTES_FLOOR).unwrap(); // In longitude/latitude, for the tests to say where its features are: it holds them in its // declared system, as the file does. - (whole.in_lonlat().unwrap().into_owned(), report.messages, src.info().crs.clone()) + (whole.in_lonlat().unwrap().into_owned(), report.messages.texts().map(str::to_string).collect(), src.info().crs.clone()) } fn in_arnhem(e: &Extent) -> bool { @@ -3606,7 +3612,7 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { #[test] fn declared_z_and_m_are_said_and_counted() { let d = tempfile::tempdir().unwrap(); - let says = |info: &SourceInfo| info.zm_dropped && info.notes.contains(&crate::zm_note(Some(600))); + let says = |info: &SourceInfo| info.zm_dropped && info.notes.says(&crate::zm_note(Some(600))); let quiet = |info: &SourceInfo| !info.zm_dropped && !info.notes.iter().any(|n| n.contains("Z or M")); let gpkg = d.path().join("grid.gpkg"); @@ -3619,7 +3625,7 @@ fn declared_z_and_m_are_said_and_counted() { assert!(says(&info), "{:?}", info.notes); // The web reader doesn't scan for the count, and says so without one. let info = mem(&gpkg).info().clone(); - assert!(info.zm_dropped && info.notes.contains(&crate::zm_note(None)), "{:?}", info.notes); + assert!(info.zm_dropped && info.notes.says(&crate::zm_note(None)), "{:?}", info.notes); let parquet = d.path().join("grid.parquet"); write_parquet_typed(&parquet, false, r#"["Point"]"#); @@ -3630,7 +3636,7 @@ fn declared_z_and_m_are_said_and_counted() { // Some types with Z, some without: said, without a count. write_parquet_typed(&parquet, false, r#"["Point", "Point Z"]"#); let info = open_path(&parquet, None).unwrap().info().clone(); - assert!(info.zm_dropped && info.notes.contains(&crate::zm_note(None)), "{:?}", info.notes); + assert!(info.zm_dropped && info.notes.says(&crate::zm_note(None)), "{:?}", info.notes); } /// A GeoParquet whose columns RustGIS has no field type for (a decimal too wide for a 64-bit @@ -3866,10 +3872,7 @@ fn geopackage_dates_are_written_and_read_as_dates() { // The moment is kept, at UTC. let utc = vec![day("2026-03-05"), at("2026-03-05T12:30:00Z")]; assert_eq!(read, [utc, rows[1].to_vec(), null.clone(), null.clone(), null.clone(), vec![day("2026-01-01"), Value::Null]]); - assert!( - report.messages.contains(&"permits: 2 values aren't dates and were read as empty, in 'issued', 'seen'".to_string()), - "{report:?}" - ); + assert!(report.messages.says("permits: 2 values aren't dates and were read as empty, in 'issued', 'seen'"), "{report:?}"); } // The export says the text it wrote in a date field that isn't a date, and a date-time with a // time in one, which reads back empty too. diff --git a/crates/data/src/topojson.rs b/crates/data/src/topojson.rs index a2bd52fd55..b5c42be68a 100644 --- a/crates/data/src/topojson.rs +++ b/crates/data/src/topojson.rs @@ -594,7 +594,7 @@ mod tests { /// them. fn zm_said(text: &str) -> (bool, Vec) { let (ds, rep) = read("z.topojson", text).unwrap().remove(0); - (ds.zm_dropped, rep.messages) + (ds.zm_dropped, rep.messages.texts().map(str::to_string).collect()) } #[test] @@ -668,7 +668,7 @@ mod tests { fn a_height_that_isnt_a_number_is_said() { let said = |text: &str| -> Vec { let (_, rep) = read("h.topojson", text).unwrap().remove(0); - rep.messages.into_iter().filter(|m| m.contains("read without a height")).collect() + rep.messages.texts().filter(|m| m.contains("read without a height")).map(str::to_string).collect() }; let lossy = r#"{"type":"Topology","objects":{"o":{"type":"GeometryCollection","geometries":[ {"type":"Point","coordinates":[1,2,"10"]},{"type":"MultiPoint","coordinates":[[1,2,true],[3,4,5]]},{"type":"LineString","arcs":[0]}]}}, @@ -851,7 +851,7 @@ mod tests { {"type":"Point","coordinates":[1,2,3]}]}},"arcs":[[[0,0,9],[1,1,9]]]}"#; let (ds, rep) = read("z.topojson", text).unwrap().remove(0); assert_eq!(rep.skipped, 0); - assert!(ds.zm_dropped && rep.messages.contains(&crate::zm_note(Some(1))), "{:?}", rep.messages); + assert!(ds.zm_dropped && rep.messages.says(&crate::zm_note(Some(1))), "{:?}", rep.messages); } #[test] diff --git a/crates/data/tests/integration/planetary_crs.rs b/crates/data/tests/integration/planetary_crs.rs index 838dbbe002..cf7d0daab9 100644 --- a/crates/data/tests/integration/planetary_crs.rs +++ b/crates/data/tests/integration/planetary_crs.rs @@ -37,8 +37,25 @@ const ANOTHER_BODY: &str = "belongs to another body than the Earth"; const WGS84: &str = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]"#; /// The notice for an Earth definition read in place of another body's IAU code. -fn earth_over_iau_notes(messages: &[String]) -> Vec<&String> { - messages.iter().filter(|m| m.contains("is another body's, but its definition is the Earth's")).collect() +/// A reader's notes or a raster's losses, as text. +trait Said { + fn said(&self) -> &str; +} + +impl Said for String { + fn said(&self) -> &str { + self + } +} + +impl Said for rustgis_data::loss::Note { + fn said(&self) -> &str { + &self.text + } +} + +fn earth_over_iau_notes(messages: &[T]) -> Vec<&T> { + messages.iter().filter(|m| m.said().contains("is another body's, but its definition is the Earth's")).collect() } /// Olympus Mons and Jezero crater (planetocentric, east positive). @@ -68,12 +85,12 @@ fn shapefile(dir: &Path, name: &str, native: [(f64, f64); 2], prj: &str) -> Path dir.join(format!("{name}.shp")) } -fn planetary_notes(messages: &[String]) -> Vec<&String> { - messages.iter().filter(|m| m.contains(ANOTHER_BODY)).collect() +fn planetary_notes(messages: &[T]) -> Vec<&T> { + messages.iter().filter(|m| m.said().contains(ANOTHER_BODY)).collect() } -fn datum_notes(messages: &[String]) -> Vec<&String> { - messages.iter().filter(|m| m.contains("few hundred metres")).collect() +fn datum_notes(messages: &[T]) -> Vec<&T> { + messages.iter().filter(|m| m.said().contains("few hundred metres")).collect() } #[test] @@ -261,7 +278,9 @@ fn planetographic_systems_without_east_axes_are_refused() { let path = shapefile(dir.path(), "earth_west", LONLAT, &west); let (ds, report) = io::read_path(&path).unwrap(); assert_eq!(points(&ds), LONLAT.map(|(x, y)| Coord::new(x, y)).to_vec()); - let said = |notes: &[String]| notes.iter().filter(|m| m.contains("west or south") && m.contains("read as longitude/latitude")).count(); + let said = |notes: &[rustgis_data::loss::Note]| { + notes.iter().filter(|m| m.contains("west or south") && m.contains("read as longitude/latitude")).count() + }; assert_eq!(said(&report.messages), 1, "{:?}", report.messages); assert!(planetary_notes(&report.messages).is_empty(), "{:?}", report.messages); let src = source::open_path(&path, None).unwrap(); diff --git a/crates/data/tests/integration/projection_methods.rs b/crates/data/tests/integration/projection_methods.rs index 529221c317..76572e5fb6 100644 --- a/crates/data/tests/integration/projection_methods.rs +++ b/crates/data/tests/integration/projection_methods.rs @@ -70,7 +70,7 @@ fn read_prj(prj: &str, x: f64, y: f64) -> (Option, Vec) { Some(Geometry::Point(c)) => Some(c), _ => None, }; - (at, report.messages) + (at, report.messages.texts().map(str::to_string).collect()) } /// A 2×2 GeoTIFF whose top-left corner is at `corner`, in a user-defined projection: coordinate diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 5bc2be4bd4..f25d5875dc 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -107,7 +107,7 @@ fn cut(s: &mut Session, _: &Value) -> CmdResult { /// The features to paste: GeoJSON text when given, with what its reader says it left out, else /// the clipboard. -fn clip(s: &Session, p: &Value) -> Result<(Dataset, Vec), String> { +fn clip(s: &Session, p: &Value) -> Result<(Dataset, rustgis_data::loss::Notes), String> { match ps(p, "text").map(str::trim).filter(|t| !t.is_empty()) { Some(t) if t.len() > MAX_TEXT => Err("the pasted text is too large".into()), Some(t) => { @@ -115,10 +115,10 @@ fn clip(s: &Session, p: &Value) -> Result<(Dataset, Vec), String> { // longitude/latitude. let (ds, report) = rustgis_data::io::read_geojson(t, "Pasted").map_err(|e| format!("the pasted text isn't GeoJSON features: {e}"))?; - let said = report.into_messages().map(|m| format!("Pasted text: {m}")).collect(); + let said = report.messages.prefixed("Pasted text"); if ds.features.is_empty() { Err("the pasted text has no features".into()) } else { Ok((ds, said)) } } - None => s.clipboard.as_ref().map(|c| (c.data.clone(), Vec::new())).ok_or_else(|| "nothing has been copied".to_string()), + None => s.clipboard.as_ref().map(|c| (c.data.clone(), Default::default())).ok_or_else(|| "nothing has been copied".to_string()), } } @@ -236,8 +236,8 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { super::design::apply(s, id, (first..first + n).map(|r| super::design::Change { before: None, row: Some(r) }).collect())?; s.map_mut().layers.iter_mut().filter(|o| o.id != id).for_each(|o| o.selection.clear()); s.notify(format!("Pasted {n} features into {name}"), false); - for notice in said.into_iter().chain(notices) { - s.notify(notice, false); + for notice in said.into_iter().chain(notices.into_iter().map(rustgis_data::loss::Note::plain)) { + s.say(notice); } Ok(json!({"pasted": n, "layer": id})) } @@ -251,7 +251,7 @@ fn paste_special(s: &mut Session, p: &Value) -> CmdResult { let n = ds.features.len(); let id = super::layer::add_dataset(s, ds); for m in said { - s.notify(m, false); + s.say(m); } Ok(json!({"pasted": n, "layer": id})) } diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 821f3dfce6..113e1088af 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -14,7 +14,8 @@ use crate::{CmdResult, Session}; /// was exported, unless `then` says it). pub struct Wrote { pub(crate) answer: Value, - pub(crate) notes: Vec, + /// What it says once written, each loss with its code. + pub(crate) notes: rustgis_data::loss::Notes, /// Drawing diagnostics available before the session finalizer, with their original severity. pub(crate) diagnostics: Vec<(rustgis_data::diagnostics::Severity, String)>, /// Source failures to report if delivery cannot update their live layers. @@ -35,7 +36,12 @@ pub struct Wrote { impl Wrote { fn completion_notes(&self) -> Vec { - self.notes.iter().chain(self.diagnostics.iter().map(|(_, text)| text)).chain(&self.refused_notes).cloned().collect() + self.notes + .texts() + .chain(self.diagnostics.iter().map(|(_, text)| text.as_str())) + .chain(self.refused_notes.iter().map(String::as_str)) + .map(str::to_string) + .collect() } } @@ -135,9 +141,9 @@ fn said(s: &mut Session, wrote: Wrote) -> CmdResult { } for note in notes { if written_path.is_some() { - s.notify_written(note); + s.say_written(note); } else { - s.notify(note, false); + s.say(note); } } if let Some(then) = then { @@ -261,7 +267,7 @@ pub(crate) fn drawn( }); Ok(Wrote { answer, - notes: Vec::new(), + notes: Default::default(), diagnostics: notices, refused_notes, written_path, @@ -469,7 +475,7 @@ mod tests { answer: serde_json::json!({"path": "x"}), diagnostics: Vec::new(), refused_notes: Vec::new(), - notes: vec!["Exported x".into()], + notes: ["Exported x"].into_iter().collect(), written_path: Some("x".into()), then: None, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index d8586493f9..7e02296365 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -74,14 +74,14 @@ pub(crate) fn package(s: &mut Session, p: &Value) -> Result<(String, Vec), S s.keep_field_floors(); let (name, bytes, notes) = made?; for note in notes { - s.notify(note, false); + s.say(note); } Ok((name, bytes)) } /// Construction notes describe the delivered package, so callers emit them after delivery. -pub(crate) fn package_output(s: &mut Session, p: &Value) -> Result<(String, Vec, Vec), String> { - let mut notes = Vec::new(); +pub(crate) fn package_output(s: &mut Session, p: &Value) -> Result<(String, Vec, rustgis_data::loss::Notes), String> { + let mut notes = rustgis_data::loss::Notes::new(); let (name, bytes) = build_package(s, p, &mut notes)?; Ok((name, bytes, notes)) } @@ -106,10 +106,10 @@ fn legacy_user(s: &Session) -> Result<(), String> { /// `notes`, said once the package has been delivered. Cancel is checked between streamed /// chunks, tile archives and the encoding steps. A single archive read or ZIP compression /// runs through before the next check. -fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result<(String, Vec), String> { +fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Notes) -> Result<(String, Vec), String> { use rustgis_data::progress; progress::check().map_err(|e| e.to_string())?; - let mut losses = Vec::new(); + let mut losses = rustgis_data::loss::Notes::new(); let mut archive_errors = Vec::new(); // Each is notified as an error as soon as it is met, and a copy of its text is kept for the // recipient's manifest. @@ -286,7 +286,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< let package = s.project.field_origin.as_ref().map(|o| o.package.clone()).unwrap_or_default(); match s.project.field_origin.as_ref().filter(|_| package.is_empty()) { Some(origin) if origin.generation.is_empty() => losses.push( - "The field package goes back as a whole map with no return check: it was made before packages had one, so Bring Back can't tell it from a copy already brought back, and bringing it back may undo or repeat what came home since".into(), + "The field package goes back as a whole map with no return check: it was made before packages had one, so Bring Back can't tell it from a copy already brought back, and bringing it back may undo or repeat what came home since", ), Some(_) => losses.push(WHOLE_MAP.replace("{why}", "the package was made before packages had an identity of their own")), None => {} @@ -317,7 +317,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< if !s.project.origin_id.is_empty() { return Err("the field package has an incomplete origin identity; legacy recovery cannot override it".into()); } - notes.push("Legacy field return: its origin is unverified; bring it back only with an explicitly verified legacyArea in the home project".into()); + notes.push("Legacy field return: its origin is unverified; bring it back only with an explicitly verified legacyArea in the home project"); } s.project.field_origin.clone() } else { @@ -349,11 +349,9 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< })?; } if assigned_identity { - notes.push( - "Assigned this legacy offline area an origin identity: save the home project before sending the field package".into(), - ); + notes.push("Assigned this legacy offline area an origin identity: save the home project before sending the field package"); } else if gave_generation { - notes.push("Gave this offline area a return check: save the home project before sending the field package".into()); + notes.push("Gave this offline area a return check: save the home project before sending the field package"); } let home_area = s.project.offline_areas.get(ai).ok_or("the offline area was not found")?; Some(crate::project::FieldOrigin { @@ -574,8 +572,8 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result, + losses: &mut rustgis_data::loss::Notes, ) -> Result, String> { let mut copied = Vec::new(); let mut omitted = Vec::new(); @@ -678,7 +676,7 @@ fn copy_stream( layer: &mut rustgis_map::Layer, extent: rustgis_data::Extent, budget: usize, - losses: &mut Vec, + losses: &mut rustgis_data::loss::Notes, ) -> Result, String> { use rustgis_data::{Feature, progress, source}; let eligible = layer.source.as_ref().is_some_and(|s| s.linked_file().is_some() || s.embedded.is_some()); @@ -760,7 +758,8 @@ fn copy_stream( source::rounded_dates_note(&info.fields, &batch.rounded_dates), source::null_text_note(&info.fields, &batch.null_text), ]; - losses.extend(info.notes.iter().chain(&batch.notes).chain(counted.iter().flatten()).map(|note| format!("{}: {note}", layer.name))); + losses.extend(info.notes.iter().chain(&batch.notes).cloned().map(|note| note.prefixed(&layer.name))); + losses.extend(counted.iter().flatten().map(|note| format!("{}: {note}", layer.name))); dataset.crs_incomplete = src.lost_to_crs() || (info.format == "Shapefile" && batch.skipped > 0); dataset.features = rows.into(); if dataset.geometry_type == rustgis_data::GeometryType::None @@ -780,12 +779,13 @@ fn copy_stream( /// Only portable, redacted summaries go into the archive. Keep the list within the receiver's /// diagnostic limits even when a project has thousands of missing layers. -fn manifest_bytes(errors: &[String], losses: &[String]) -> Result, String> { +fn manifest_bytes(errors: &[String], losses: &rustgis_data::loss::Notes) -> Result, String> { let total = errors.len() + losses.len(); if total == 0 { return Ok(Vec::new()); } - let mut notes: Vec<_> = errors.iter().chain(losses).take(MAX_NOTICES).map(|s| Session::redacted(s).into_string()).collect(); + let mut notes: Vec<_> = + errors.iter().map(String::as_str).chain(losses.texts()).take(MAX_NOTICES).map(|s| Session::redacted(s).into_string()).collect(); // JSON can grow when text has escapes. Drop the tail and count it if the byte limit is hit. loop { let mut candidate = notes.clone(); @@ -1795,7 +1795,7 @@ mod tests { let mark = home.notice_mark(); let extent = rustgis_data::Extent::new(0.0, 0.0, 2.0, 2.0); let mut oversized = home.map().clone(); - let mut omissions = Vec::new(); + let mut omissions = rustgis_data::loss::Notes::new(); assert!(copy_streams(&mut oversized, extent, 0, &mut omissions).unwrap().is_empty()); assert!(oversized.layer_by_name("Streamed").is_none()); assert!(omissions.iter().any(|n| n.contains("1 feature(s) in the offline area") && n.contains("budget")), "{omissions:?}"); diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index e7f528467b..db40af40fe 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1371,27 +1371,32 @@ fn map_inputs<'a>(s: &'a Session, spec: Option<&rustgis_analysis::ToolSpec>, par /// whole, and the rows of each layer it runs on. It reads, so a background run does this on its /// thread. fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> Result, String> { - let (full, mut messages) = streamed_inputs(&snap.map, spec, params)?; - let losses = Vec::new(); - #[cfg(not(target_arch = "wasm32"))] - let (mut full, mut losses) = (full, losses); + let (full, said) = streamed_inputs(&snap.map, spec, params)?; + let (mut messages, mut losses) = (Vec::new(), Vec::new()); + for m in said { + match m.loss { + Some(code) => losses.push(LossMessage { code, text: m.text }), + None => messages.push(m.text), + } + } + let mut full = full; #[cfg(not(target_arch = "wasm32"))] if let Some(spec) = spec.filter(|t| rustgis_analysis::TOOLS.iter().any(|builtin| std::ptr::eq(builtin, *t))) { for parameter in spec.params.iter().filter(|p| p.kind == rustgis_analysis::ParamKind::VectorLayers) { for name in rustgis_analysis::layer_list(params.get(parameter.name).unwrap_or(&Value::Null))? { if vector_file_input(spec, &snap.map, name) && !full.contains_key(name) { let (dataset, report) = rustgis_data::io::read_path(std::path::Path::new(name)).map_err(|e| format!("{name}: {e}"))?; - messages.extend(report.messages.into_iter().map(|message| format!("{name}: {message}"))); - losses.extend( - report.losses.into_iter().map(|loss| LossMessage { code: loss.code, text: format!("{name}: {}", loss.text) }), - ); + for message in report.messages.prefixed(name) { + match message.loss { + Some(code) => losses.push(LossMessage { code, text: message.text }), + None => messages.push(message.text), + } + } full.insert(name.to_string(), dataset); } } } } - #[cfg(target_arch = "wasm32")] - let mut full = full; let work = work_inputs(&snap.map, &snap.tables, spec, params, &mut full, &mut messages)?; let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?; narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?; @@ -1504,9 +1509,9 @@ fn streamed_inputs( map: &rustgis_map::Map, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value, -) -> Result<(std::collections::HashMap, Vec), String> { +) -> Result<(std::collections::HashMap, rustgis_data::loss::Notes), String> { let mut full = std::collections::HashMap::new(); - let mut said = Vec::new(); + let mut said = rustgis_data::loss::Notes::new(); for n in layer_names(spec, params) { let key = n.to_ascii_lowercase(); if full.contains_key(&key) { @@ -2391,9 +2396,7 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc { - let messages = report.messages.into_iter().map(|text| (text, None)); - let losses = report.losses.into_iter().map(|loss| (loss.text, Some(loss.code))); - for (msg, code) in messages.chain(losses) { + for (msg, code) in report.messages.into_iter().map(|m| (m.text, m.loss)) { item_reader_warnings.push(format!("{target}: {msg}")); reader_warnings.push((target.clone(), msg, code)); } diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index 9ca394a372..9d110ce744 100644 --- a/crates/engine/src/cmd/gpkg.rs +++ b/crates/engine/src/cmd/gpkg.rs @@ -90,7 +90,7 @@ fn add_layer(s: &mut Session, p: &Value) -> CmdResult { let versions = versions_of(&editable.features, &Default::default(), &read); ds.features = editable.features.into(); for note in &info.notes { - s.notify(format!("{name}: {note}"), false); + s.say(note.clone().prefixed(&name)); } if (n as u64) < editable.matched { s.notify( @@ -347,7 +347,7 @@ fn save_edits(s: &mut Session, p: &Value) -> CmdResult { pub(super) struct Candidate { pub dataset: rustgis_data::Dataset, pub edit: rustgis_map::source::GpkgEdit, - pub notes: Vec, + pub notes: rustgis_data::loss::Notes, pub matched: u64, } @@ -398,7 +398,7 @@ pub(super) fn read_candidate(name: &str, edit: &rustgis_map::source::GpkgEdit) - notes.push(note); } if !editable.writable { - notes.push("the file is read-only, so edits can't be saved to it".into()); + notes.push("the file is read-only, so edits can't be saved to it"); } Ok(Candidate { dataset: ds, edit: baseline, notes, matched: editable.matched }) } @@ -425,7 +425,7 @@ fn discard_edits(s: &mut Session, p: &Value) -> CmdResult { l.touch_geometry(); l.touch_replacement(); for note in notes { - s.notify(format!("{name}: {note}"), false); + s.say(note.prefixed(&name)); } s.notify(format!("{name}: edits discarded; {n} rows loaded again from {}", edit.table), false); Ok(json!({"features": n, "matched": matched})) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 98dd080950..b67bbf0f8e 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -1699,14 +1699,14 @@ pub const ITEMS: &[(&str, &str, &str)] = &[ pub fn item_bytes(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec), String> { let (name, bytes, notes) = item_output(s, kind, p)?; for note in notes { - s.notify(note, false); + s.say(note); } Ok((name, bytes)) } /// Builds an item and returns construction-loss notes for publication only after delivery. -pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec, Vec), String> { - let mut construction_notes = match kind { +pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec, rustgis_data::loss::Notes), String> { + let mut construction_notes: rustgis_data::loss::Notes = (match kind { "map" => { let m = saved_map(s, p)?; s.constructions.output_notes(m.layers.iter().map(|l| (m.instance_id(), l)))? @@ -1723,7 +1723,8 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve "mapPackage" | "fieldPackage" => s.constructions.output_notes(s.map().layers.iter().map(|l| (s.map().instance_id(), l)))?, "gpPackage" => s.constructions.output_notes(gp_result_layers(s).into_iter().map(|(m, l)| (m.instance_id(), l)))?, _ => Vec::new(), - }; + }) + .into(); let (name, bytes) = match kind { "map" => { let map = saved_map(s, p)?; @@ -1799,14 +1800,14 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve let id = s.layer_id(p)?; let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); let (text, notes) = obj_text(s, p)?; - construction_notes = notes; + construction_notes = notes.into(); (name, text.into_bytes()) } "stl" => { let id = s.layer_id(p)?; let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); let (bytes, _, notes) = stl_bytes(s, p)?; - construction_notes = notes; + construction_notes = notes.into(); (name, bytes) } "report" | "reportTemplate" => { @@ -1837,7 +1838,7 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve } k if super::sharing::KINDS.iter().any(|x| x.0 == k) => { let (name, bytes, _, notes) = super::sharing::share_output(s, k, p)?; - construction_notes = notes; + construction_notes = notes.into(); super::sharing::note_label_classes(s, k, p); super::sharing::note_export(s, k, p, &name); (name, bytes) @@ -1855,7 +1856,7 @@ pub(crate) fn save_item(s: &mut Session, kind: &str, p: &Value) -> CmdResult { let (_, bytes, notes) = item_output(s, kind, p)?; rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; for note in notes { - s.notify(note, false); + s.say(note); } s.retain_written_notices(written); Ok(json!({"path": path, "bytes": bytes.len()})) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7035248b36..9c09de6aeb 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1835,10 +1835,10 @@ pub(crate) fn add_photos_to(s: &mut Session, name: &str, zoom: Option, fee feed(&mut reader); let (ds, report) = reader.finish(); for m in &report.messages { - s.notify(m.clone(), false); + s.say(m.clone()); } if ds.features.is_empty() { - return Err(report.messages.first().cloned().unwrap_or_else(|| "no photo with a GPS position".into())); + return Err(report.messages.first().map(|m| m.text.clone()).unwrap_or_else(|| "no photo with a GPS position".into())); } // The reader took no more than there is room for; `take` keeps that so if it ever changes. let added = ds.features.len().min(room); @@ -2822,7 +2822,11 @@ fn add_picked( }) .map(|(_, r)| { let mut said = r.report.clone(); - said.messages.drain(..usize::from(r.dataset.zm_dropped).min(said.messages.len())); + // The layer's own Z/M note leads its messages; it is said by that layer. A note + // that reports another loss is never taken for it. + if r.dataset.zm_dropped && said.messages.first().is_some_and(|n| n.loss.is_none()) { + said.messages.drain(..1); + } (r.dataset.source.clone(), said) }) .collect(); @@ -2833,7 +2837,6 @@ fn add_picked( for (source, said) in file_wide { if let Some(kept) = reads.iter_mut().find(|r| r.dataset.source == source) { kept.report.messages.extend(said.messages); - kept.report.losses.extend(said.losses); kept.report.skipped += said.skipped; } } @@ -3412,7 +3415,7 @@ fn add_source_read( } let unique = unique_name(s, &name); for n in &info.notes { - s.notify(format!("{unique}: {n}"), false); + s.say(n.clone().prefixed(&unique)); } let id = s.map_mut().add_streamed(unique.clone(), layer); if let Some(l) = s.map_mut().layer_mut(id) { @@ -3446,11 +3449,10 @@ fn add_source_read( // The source names itself by its file (a DuckDB result's cache file); the layer has the // name the user knows. let shown = s.map().layer(id).map_or_else(|| info.name.clone(), |l| l.name.clone()); + let prefix = format!("{}: ", info.name); for m in report.messages { - match m.strip_prefix(&format!("{}: ", info.name)) { - Some(rest) => s.notify(format!("{shown}: {rest}"), false), - None => s.notify(m, false), - } + // As the layer is named: its name may differ from the source's. + s.say(m.map_text(|t| t.strip_prefix(&prefix).map_or_else(|| t.clone(), |rest| format!("{shown}: {rest}")))); } } } @@ -5732,7 +5734,7 @@ fn add_remote(s: &mut Session, p: &Value, url: &str, src: Box = None; - let mut losses = std::collections::BTreeMap::<(String, String), ConversionLoss>::new(); + // By provider and kind, and by the loss code the notes carry, which the summary keeps. + let mut losses = std::collections::BTreeMap::<(String, String, Option<&'static str>), (ConversionLoss, Option)>::new(); for l in s.project.maps.iter_mut().flat_map(|m| &mut m.layers) { let Some(source) = l.source.as_mut() else { continue }; if let Some(note) = source.take_conversion_fallback() { @@ -249,6 +251,8 @@ pub(crate) fn say_conversion_fallbacks(s: &mut Session) { } let mut seen = std::collections::BTreeSet::new(); for note in source.take_conversion_notes() { + let code = note.loss; + let note = note.text; // Source layer names and feature counts vary within a loss kind. Count affected // layers once each and total leading feature/row counts across those layers. let kind = [ @@ -264,9 +268,9 @@ pub(crate) fn say_conversion_fallbacks(s: &mut Session) { // An unlisted GDAL warning, without its per-layer occurrence count. .unwrap_or_else(|| note.rsplit_once(" (").filter(|(_, tail)| tail.ends_with("occurrence(s))")).map_or(¬e, |(base, _)| base)); let provider = note.split_once(": ").map_or("", |(provider, _)| provider); - let key = (provider.to_owned(), kind.to_owned()); + let key = (provider.to_owned(), kind.to_owned(), code.map(|c| c.spec().id)); if seen.insert(key.clone()) { - losses.entry(key).and_modify(|loss| loss.add(¬e)).or_insert_with(|| ConversionLoss::new(&l.name, note)); + losses.entry(key).and_modify(|(loss, _)| loss.add(¬e)).or_insert_with(|| (ConversionLoss::new(&l.name, note), code)); } } } @@ -278,8 +282,8 @@ pub(crate) fn say_conversion_fallbacks(s: &mut Session) { }; s.notify(text, false); } - for loss in losses.into_values() { - s.notify(loss.notice(), false); + for (loss, code) in losses.into_values() { + s.say(rustgis_data::loss::Note { text: loss.notice(), loss: code }); } } diff --git a/crates/engine/src/cmd/publish.rs b/crates/engine/src/cmd/publish.rs index dd5721ded3..5a866315d7 100644 --- a/crates/engine/src/cmd/publish.rs +++ b/crates/engine/src/cmd/publish.rs @@ -90,7 +90,7 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result Result Result<(), String> { let notes = info.notes.clone(); let moved = s.map_mut().layer_mut(id).ok_or("the layer no longer exists")?.replace_source(*new); reset_labels(s, id, moved); + let name = s.map().layer(id).map_or_else(|| "Layer".to_string(), |l| l.name.clone()); for note in notes { - s.notify(format!("{}: {note}", s.map().layer(id).map_or("Layer", |l| l.name.as_str())), false); + s.say(note.prefixed(&name)); } } Candidate::Editable(new) => { @@ -383,8 +388,9 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> { l.selection.clear(); l.touch_geometry(); reset_labels(s, id, moved); + let name = s.map().layer(id).map_or_else(|| "Layer".to_string(), |l| l.name.clone()); for note in notes { - s.notify(format!("{}: {note}", s.map().layer(id).map_or("Layer", |l| l.name.as_str())), false); + s.say(note.prefixed(&name)); } } } diff --git a/crates/engine/src/cmd/service_group.rs b/crates/engine/src/cmd/service_group.rs index facfc7634b..22a5c674b9 100644 --- a/crates/engine/src/cmd/service_group.rs +++ b/crates/engine/src/cmd/service_group.rs @@ -243,7 +243,7 @@ fn read(s: &mut Session, p: &Value) -> Result<(Value, Vec<(ServiceChild, Dataset // Empty collections remain visible as children and can acquire geometry on refresh. dataset.source = Some(url.to_string()); for message in report.messages { - s.notify(message, false); + s.say(message); } reads.push(( ServiceChild { diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 32ea216a56..26f72b0f8f 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -647,17 +647,19 @@ pub fn read_date_notes(file: &str, layer: &str, lost: &rustgis_map::Unreadable) /// The complete diagnostics from a whole read made for an export, including metadata losses /// discovered by a temporary source opening that the live layer never received. -pub fn read_notes(file: &str, layer: &str, lost: &rustgis_map::Unreadable) -> Vec { - read_date_notes(file, layer, lost).into_iter().chain(lost.messages.iter().map(|n| format!("{file}: {n}"))).collect() +pub fn read_notes(file: &str, layer: &str, lost: &rustgis_map::Unreadable) -> rustgis_data::loss::Notes { + let mut notes: rustgis_data::loss::Notes = read_date_notes(file, layer, lost).into_iter().collect(); + notes.extend(lost.messages.iter().cloned().map(|n| n.prefixed(file))); + notes } /// A counted source Z/M diagnostic replaces only the equivalent generic export warning. /// Resident/older layers and custom providers without that diagnostic keep their warning. -pub fn coalesce_read_zm(notes: &mut Vec, file: &str, ds: &rustgis_data::Dataset, lost: &rustgis_map::Unreadable) { +pub fn coalesce_read_zm(notes: &mut rustgis_data::loss::Notes, file: &str, ds: &rustgis_data::Dataset, lost: &rustgis_map::Unreadable) { if lost.zm_noted && let Some(generic) = rustgis_data::zm_export_note([ds], file) { - notes.retain(|note| note != &generic); + notes.retain(|note| note.text != generic); } } @@ -725,7 +727,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk // Counted as the chunks were written, as the layer holds none of them. let unfit = rustgis_data::source::parquet::unfit_note(&layer.fields, &e.unfit, path); let moved = rustgis_data::web_mercator_moved_note(path, &layer.name, e.beyond_web_mercator); - let mut dates: Vec = rustgis_data::source::unread_dates_note(&layer.fields, &e.unread_dates) + let mut dates: rustgis_data::loss::Notes = rustgis_data::source::unread_dates_note(&layer.fields, &e.unread_dates) .map(|n| format!("{path}: {}: {n} (empty in the export)", layer.name)) .into_iter() .collect(); @@ -747,7 +749,9 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk dates.extend(rustgis_data::io::fgb_empty_dates_note(&layer.fields, &e.written_values, path)); } dates.extend(e.date_messages.iter().map(|n| format!("{path}: {n}"))); - dates.extend(e.read_notes.iter().map(|n| format!("{path}: {}: {n} when read for the export", layer.name))); + dates.extend( + e.read_notes.iter().map(|n| n.clone().map_text(|t| format!("{path}: {}: {t} when read for the export", layer.name))), + ); let mut format_notes = e.csv.notes(&ds.fields, path); format_notes.extend(e.csv.coordinates_note_in(&ds.fields, path, crs)); // Text that reading the file back changes: CSV reads a blank cell as null; KML and GPX trim @@ -773,7 +777,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk // as they're written (`e.beyond_web_mercator`), and its source's extent only serves the // out-of-place check. A raster layer's extent is its raster's, which the file doesn't hold. let extent = if chunks.is_some() { l.extent() } else { ds.lonlat_extent() }; - let mut notes = rustgis_data::export_notes([(ds, extent)], path, crs); + let mut notes: rustgis_data::loss::Notes = rustgis_data::export_notes([(ds, extent)], path, crs).into(); coalesce_read_zm(&mut notes, path, ds, &unreadable); if asked.is_none() { notes.extend(rustgis_data::io::default_export_note(ds, path)); @@ -795,7 +799,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk dbf_notes.extend(rustgis_data::io::dates_as_text_note(&ds.fields, path)); // FlatGeobuf, KML, GPX and Shapefile hold features with geometry only (a Shapefile, only // geometry it can draw, of the layer's kind). - let mut said = Vec::new(); + let mut said = rustgis_data::loss::Notes::new(); said.extend(rustgis_data::io::left_out_note(path, &ext, left_out)); said.extend(format_notes); if skipped > 0 { diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index bffdef6461..848e7786b8 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -197,7 +197,7 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result let written_path = Some(path.clone()); Ok(Wrote { answer, - notes, + notes: notes.into(), diagnostics: Vec::new(), refused_notes, written_path, diff --git a/crates/engine/src/cmd/stac_area.rs b/crates/engine/src/cmd/stac_area.rs index a4c6f58125..cac0cbfb07 100644 --- a/crates/engine/src/cmd/stac_area.rs +++ b/crates/engine/src/cmd/stac_area.rs @@ -31,7 +31,11 @@ fn area_cmd(s: &mut Session, p: &Value) -> CmdResult { fn from_file(s: &mut Session, path: &str) -> Result, String> { let (geometries, messages) = read_geometries(path)?; for m in messages { - s.warn(m); + // An ordinary note warns; a loss says its code too. + match m.loss { + Some(_) => s.say(m), + None => s.warn(m.text), + } } Ok(geometries) } @@ -39,12 +43,12 @@ fn from_file(s: &mut Session, path: &str) -> Result, String> { /// A file's features' geometries and what the reader says of it (each naming the file). Needs no /// session, so the app reads a large file on a thread of its own. #[cfg(not(target_arch = "wasm32"))] -fn read_geometries(path: &str) -> Result<(Vec, Vec), String> { +fn read_geometries(path: &str) -> Result<(Vec, rustgis_data::loss::Notes), String> { let (ds, report) = rustgis_data::io::read_path(std::path::Path::new(path)).map_err(|e| format!("{path}: {e}"))?; if ds.features.len() > area::MAX_FEATURES { return Err(format!("{path} has more than {} features: simplify it or use a bounding box", area::MAX_FEATURES)); } - let mut messages: Vec = report.into_messages().map(|m| format!("{path}: {m}")).collect(); + let mut messages = report.messages.prefixed(path); // The search area is in longitude/latitude; a file in another system is read in its own. let ds = ds.in_lonlat().map_err(|e| format!("{path}: {e}"))?; let geometries: Vec = ds.features.iter().filter_map(|f| f.geometry.clone()).collect(); @@ -58,7 +62,7 @@ fn read_geometries(path: &str) -> Result<(Vec, Vec), String> { } #[cfg(target_arch = "wasm32")] -fn read_geometries(_path: &str) -> Result<(Vec, Vec), String> { +fn read_geometries(_path: &str) -> Result<(Vec, rustgis_data::loss::Notes), String> { Err("in the web app, choose the search area's file with Home › Add › Web Data › STAC Search".into()) } @@ -66,7 +70,7 @@ fn read_geometries(_path: &str) -> Result<(Vec, Vec), String> pub struct Loaded { pub geometry: Geometry, /// The notices: what the reader and the merge left out, one per kind. - pub notices: Vec, + pub notices: rustgis_data::loss::Notes, } /// Reads a file and merges its features by the search area's rules (no buffer: that is applied @@ -80,7 +84,7 @@ pub fn load_file(path: &str) -> Result { /// where they came from) and what the merge left out. The merge has no Cancel check inside it /// (one dissolve of at most [`area::MAX_FEATURES`] features), so the app runs it on a thread of /// its own and drops the answer when the user cancels. -pub fn merge_loaded(geometries: &[Geometry], mut notices: Vec) -> Result { +pub fn merge_loaded(geometries: &[Geometry], mut notices: rustgis_data::loss::Notes) -> Result { let area = area::merge(geometries)?.ok_or("there is no point, line or polygon to search with")?; notices.extend(notes(&area)); Ok(Loaded { geometry: area.geometry, notices }) @@ -374,15 +378,15 @@ mod tests { #[test] fn merging_loaded_geometries_says_what_it_leaves_out_and_clean_input_says_nothing() { - let clean = merge_loaded(&[point(1.0, 2.0), point(3.0, 4.0)], Vec::new()).unwrap(); + let clean = merge_loaded(&[point(1.0, 2.0), point(3.0, 4.0)], Default::default()).unwrap(); assert!(clean.notices.is_empty(), "{:?}", clean.notices); assert!(matches!(clean.geometry, Geometry::MultiPoint(_) | Geometry::Point(_))); // A polygon and a point: only the polygon is kept, and it is said once. - let mixed = merge_loaded(&[square(), point(5.0, 5.0)], vec!["file.geojson: a note".into()]).unwrap(); + let mixed = merge_loaded(&[square(), point(5.0, 5.0)], ["file.geojson: a note"].into_iter().collect()).unwrap(); assert!(matches!(mixed.geometry, Geometry::Polygon(_))); assert_eq!(mixed.notices.len(), 2, "{:?}", mixed.notices); assert!(mixed.notices.iter().any(|n| n.contains("lower dimension"))); - assert!(merge_loaded(&[], Vec::new()).is_err()); + assert!(merge_loaded(&[], Default::default()).is_err()); } #[test] diff --git a/crates/engine/src/cmd/whole.rs b/crates/engine/src/cmd/whole.rs index 97aa0dd617..94f74606eb 100644 --- a/crates/engine/src/cmd/whole.rs +++ b/crates/engine/src/cmd/whole.rs @@ -31,7 +31,7 @@ pub(crate) struct Unread { rows: usize, dates: Option, rounded: Option, - messages: Vec, + messages: rustgis_data::loss::Notes, } impl Whole { @@ -90,15 +90,17 @@ impl Unread { s.notify(format!("{}: {rounded}", self.layer), false); } for message in &self.messages { - s.notify(message.clone(), false); + s.say(message.clone()); } } /// What [`Unread::say`] says, as lines: for a tool's messages. - pub(crate) fn lines(&self) -> Vec { + pub(crate) fn lines(&self) -> rustgis_data::loss::Notes { let rows = (self.rows > 0).then(|| unread_notice(&self.layer, self.rows)); let dates = [&self.dates, &self.rounded].into_iter().flatten().map(|n| format!("{}: {n}", self.layer)); - rows.into_iter().chain(dates).chain(self.messages.iter().cloned()).collect() + let mut lines: rustgis_data::loss::Notes = rows.into_iter().chain(dates).collect(); + lines.extend(self.messages.iter().cloned()); + lines } /// `error`, with the rows left out when there were any: they may be why it failed. @@ -234,13 +236,13 @@ mod tests { "sites".into(), Unreadable { dates: Some("1 value isn't a date and was read as empty, in 'day'".into()), - messages: vec!["source: conversion left out 2 source features".into()], + messages: ["source: conversion left out 2 source features"].into_iter().collect(), ..Default::default() }, ); let mut session = Session::new(crate::Project::new("notices")); unread.say(&mut session); - assert_eq!(session.notices.iter().map(|n| &n.text).collect::>(), unread.lines().iter().collect::>()); + assert_eq!(session.notices.iter().map(|n| n.text.as_str()).collect::>(), unread.lines().texts().collect::>()); assert_eq!(session.notices.len(), 2); assert_eq!(unread.lines().iter().filter(|n| n.contains("conversion left out 2")).count(), 1); assert!(Unread::of("clean".into(), Unreadable::default()).lines().is_empty()); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index da1cae86bc..b5c3e85dd4 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2124,7 +2124,8 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result Result Result 0 { diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index a4311a3601..14cb15e4c4 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -254,7 +254,7 @@ pub fn commands() -> Vec { super::field::forget_new_areas(s, had); return Err(format!("{path}: {e}")); } - for note in notes { s.notify(note, false); } + for note in notes { s.say(note); } // A return written spends its package (only a field project's own identity). #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index de17a1526b..29b4d17548 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2753,7 +2753,7 @@ impl Session { // Streamed vector windows land after project opening too. Check each installed read // once, keeping the same counted notice channel as retained resident expressions. let mut landed = Vec::new(); - let mut dates = Vec::new(); + let mut dates: Vec = Vec::new(); let mut not_utf8 = Vec::new(); let mut source_errors = Vec::new(); let mut source_error_count = 0; @@ -2777,22 +2777,22 @@ impl Session { // Values in date fields that weren't dates, once for a layer read in place. let (unread, rounded) = layer.source.as_mut().map(|source| source.take_unread_dates()).unwrap_or_default(); if let Some(note) = unread { - dates.push(format!( + dates.push(rustgis_data::loss::Note::plain(format!( "{}: some values in its date fields aren't dates and show as empty (Load All Features counts them all); so far, {note}", layer.name - )); + ))); } if let Some(note) = rounded { - dates.push(format!( + dates.push(rustgis_data::loss::Note::plain(format!( "{}: some date-times in it have digits past the microsecond and are rounded (Load All Features counts them all); so far, {note}", layer.name - )); + ))); } if let Some(note) = layer.source.as_mut().and_then(|source| source.take_null_text()) { - dates.push(format!( + dates.push(rustgis_data::loss::Note::plain(format!( "{}: some text values written as Null in it show as empty (Load All Features counts them all); so far, {note}", layer.name - )); + ))); } if let Some(note) = layer.source.as_mut().and_then(|source| source.take_not_utf8()) { not_utf8.push(notice_text::NoticeText::format( @@ -2802,7 +2802,7 @@ impl Session { } // What else the map's reads of it lost or assumed, each kind once for its opening. for note in layer.source.as_mut().map(|source| source.take_read_notes()).unwrap_or_default() { - dates.push(format!("{}: {note}", layer.name)); + dates.push(note.prefixed(&layer.name)); } if layer.source.as_mut().is_some_and(|source| source.take_display_window()) { landed.push(&*layer); @@ -2813,7 +2813,7 @@ impl Session { self.notify(message, false); } for note in dates { - self.notify(note, false); + self.say(note); } for note in not_utf8 { self.notify_text(note, false); @@ -3347,6 +3347,23 @@ impl Session { self.publish_text(text, if error { Severity::Error } else { Severity::Info }, None); } + /// Says what a reader, a source, a write or a tool said: a note that reports a loss as that + /// loss, with its code ([`Session::notify_loss`]), any other as an ordinary notice. + pub fn say(&mut self, note: rustgis_data::loss::Note) { + match note.loss { + Some(code) => self.notify_loss(code, note.text.into()), + None => self.notify(note.text, false), + } + } + + /// [`Session::say`] for what a committed external write said, which restoring a project + /// cannot undo ([`Session::notify_written`]). + pub(crate) fn say_written(&mut self, note: rustgis_data::loss::Note) { + let mark = self.notice_mark(); + self.say(note); + self.retain_written_notices(mark); + } + /// Reports loss from an in-memory result, with text for translated interfaces. pub(crate) fn notify_loss(&mut self, code: rustgis_data::loss::LossCode, text: notice_text::NoticeText) { self.publish_text(text, rustgis_data::diagnostics::Severity::Warning, Some(code)); diff --git a/crates/engine/src/tests/archive_render_revision.rs b/crates/engine/src/tests/archive_render_revision.rs index 9e3ac34599..25c0709e60 100644 --- a/crates/engine/src/tests/archive_render_revision.rs +++ b/crates/engine/src/tests/archive_render_revision.rs @@ -113,7 +113,7 @@ fn paused_map(path: &std::path::Path, kind: TileKind) -> (Map, render::View, mps count: Some(1), crs: "EPSG:4326".into(), indexed: true, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }; let id = map.add_dataset(ds.clone()); diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index c4f8b87150..82c9dbf8f0 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -662,7 +662,7 @@ fn permission_policy_export_worker_keeps_its_initiating_owner() { let error = export_land(&mut s, started, wrote).unwrap_err(); assert!(error.contains("Published ") && error.contains("record wasn't updated"), "{error}"); for note in notes { - assert!(s.notices_since(mark).iter().any(|n| n.text.contains(¬e)), "missing {note}: {error}"); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains(¬e.text)), "missing {note:?}: {error}"); } assert_eq!(s.map().layer(id).unwrap().synced, synced, "the revoked finalizer must not update the layer"); let (disk, _) = rustgis_data::io::read_path(&shp).unwrap(); diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index 42731d2bd1..ed5be48e26 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -1205,7 +1205,7 @@ fn xml_losses_keep_data_and_reach_command() { "a.xml" => landxml::read(c.file, bytes, None).unwrap(), other => panic!("unexpected XML fixture {other}"), }; - let messages: Vec<_> = native.iter().flat_map(|(_, r)| r.messages.iter().cloned()).collect(); + let messages: Vec = native.iter().flat_map(|(_, r)| r.messages.texts().map(str::to_string)).collect(); let expected = if c.file.ends_with("kml") || c.file.ends_with("kmz") || c.file.ends_with("gpx") { format!("a: {words}") } else { diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 7793bcf2cf..6068463f82 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -160,7 +160,7 @@ pub struct Unreadable { pub rounded: Option, /// Other reader diagnostics, already qualified by their source. Date diagnostics stay in /// their typed fields above so consumers can describe what an export did to them once. - pub messages: Vec, + pub messages: rustgis_data::loss::Notes, /// `messages` contains the source's Z/M loss diagnostic. An export can keep that more /// specific report instead of also emitting its generic already-dropped-Z/M warning. pub zm_noted: bool, @@ -902,11 +902,11 @@ impl Layer { if let Some(info) = copy.info() { ds.zm_dropped |= info.zm_dropped; for note in &info.notes { - let message = format!("{}: {note}", info.name); + let message = note.clone().prefixed(&info.name); if !report.messages.contains(&message) { report.messages.push(message); } - zm_noted |= info.zm_dropped && reader_noted_zm(note); + zm_noted |= info.zm_dropped && reader_noted_zm(¬e.text); } } ds.name = self.dataset.name.clone(); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index bd7051d48c..a952b4f266 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -138,7 +138,7 @@ pub struct SourceLayer { conversion_fallback: Option, /// Losses from a conversion actually performed while opening, consumed once by its caller. #[serde(skip)] - conversion_notes_unsaid: Vec, + conversion_notes_unsaid: rustgis_data::loss::Notes, /// Values in date fields a view read found weren't dates ([`Batch::unread_dates`]), until /// said by [`SourceLayer::take_unread_dates`]; once said, later reads aren't counted again. /// Kept for each window read ([`Tally`]): a window read again replaces its counts. @@ -168,7 +168,7 @@ pub struct SourceLayer { /// What else view reads lost or assumed ([`Batch::notes`]), until said by /// [`SourceLayer::take_read_notes`]. #[serde(skip)] - read_notes: Vec, + read_notes: rustgis_data::loss::Notes, /// The kinds of note view reads of this opening have given ([`note_kind`]): each is said once, /// with the count of the read that first gave it, not again on each redraw. #[serde(skip)] @@ -918,9 +918,14 @@ impl SourceLayer { /// their counts ([`note_kind`]: a number starting the note or a clause, before a space); notes /// that differ in any other number or word are kinds of their own. Past [`READ_NOTE_KINDS`] /// kinds, one last note says there are more. - pub fn saw_read_notes(&mut self, notes: &[String]) { - for note in notes.iter().filter(|n| !n.trim().is_empty()) { - let kind = note_kind(note); + pub fn saw_read_notes(&mut self, notes: &[rustgis_data::loss::Note]) { + for note in notes.iter().filter(|n| !n.text.trim().is_empty()) { + // A kind is its wording without its counts, and its loss code: a coded note isn't + // folded into a plain one that reads the same. + let kind = match note.loss { + Some(code) => format!("{}\u{1f}{}", note_kind(¬e.text), code.spec().id), + None => note_kind(¬e.text), + }; if self.read_note_kinds.contains(&kind) { continue; } @@ -941,7 +946,7 @@ impl SourceLayer { /// What view reads said they lost or assumed ([`Batch::notes`]) and haven't said yet, each /// kind once for the opening ([`SourceLayer::saw_read_notes`]). - pub fn take_read_notes(&mut self) -> Vec { + pub fn take_read_notes(&mut self) -> rustgis_data::loss::Notes { std::mem::take(&mut self.read_notes) } @@ -1025,7 +1030,7 @@ impl SourceLayer { } let mut new = SourceLayer { shapefile_crs: self.shapefile_crs, limit: self.limit, byte_budget: self.byte_budget, ..Default::default() }; - let mut conversion_notes = Vec::new(); + let mut conversion_notes = rustgis_data::loss::Notes::new(); let declared_empty; let conversion_zm_dropped; if let Some(g) = &self.gdal { @@ -1649,7 +1654,7 @@ impl SourceLayer { } /// Takes diagnostics only from a fresh conversion performed by [`Self::open`]. - pub fn take_conversion_notes(&mut self) -> Vec { + pub fn take_conversion_notes(&mut self) -> rustgis_data::loss::Notes { std::mem::take(&mut self.conversion_notes_unsaid) } @@ -2121,7 +2126,7 @@ mod tests { let handle = rustgis_data::source::open_shared("converted.fgb", bytes.clone(), None).unwrap(); let mut source = super::SourceLayer::from_bytes("converted.fgb", bytes, None, handle); let mut info = source.info().unwrap().clone(); - info.notes.push("conversion left out 2 source features".into()); + info.notes.push("conversion left out 2 source features"); info.zm_dropped = true; source.conversion_info = Some(info); let mut layer = crate::Layer::new(1, Dataset::new("layer", GeometryType::Point, Vec::new())); @@ -2245,16 +2250,18 @@ mod tests { #[test] fn view_read_notes_are_said_once_for_each_kind() { let mut source = super::SourceLayer::default(); - let note = |n: usize| format!("{n} of the shapes read (a sample of the layer, which may hold more) have a NaN"); - source.saw_read_notes(&[note(3), String::new(), " ".into()]); + let note = |n: usize| { + rustgis_data::loss::Note::plain(format!("{n} of the shapes read (a sample of the layer, which may hold more) have a NaN")) + }; + source.saw_read_notes(&[note(3), "".into(), " ".into()]); source.saw_read_notes(&[note(5)]); assert_eq!(source.take_read_notes(), [note(3)]); source.saw_read_notes(&[note(12), "7 values cut".into()]); assert_eq!(source.take_read_notes(), ["7 values cut"]); assert!(source.take_read_notes().is_empty()); // A source with endless kinds of note says the first ones, then one note that there are more. - let many: Vec = (0..2 * super::READ_NOTE_KINDS) - .map(|k| format!("kind {}: 1", char::from(b'a' + (k % 26) as u8).to_string().repeat(k / 26 + 1))) + let many: Vec = (0..2 * super::READ_NOTE_KINDS) + .map(|k| format!("kind {}: 1", char::from(b'a' + (k % 26) as u8).to_string().repeat(k / 26 + 1)).into()) .collect(); source.saw_read_notes(&many); source.saw_read_notes(&many); @@ -2266,6 +2273,18 @@ mod tests { assert_eq!(source.take_read_notes(), [note(4)]); } + /// A note that reports a loss isn't folded into a plain one that reads the same: its code + /// is said too, once. + #[test] + fn a_coded_read_note_is_its_own_kind() { + use rustgis_data::loss::{LossCode, Note}; + let mut source = super::SourceLayer::default(); + let plain = Note::plain("2 rings left out"); + let coded = Note::loss(LossCode::DroppedRing, "3 rings left out"); + source.saw_read_notes(&[plain.clone(), coded.clone(), coded.clone()]); + assert_eq!(source.take_read_notes(), [plain, coded]); + } + /// Only counts make two notes one kind: notes differing in another number stay apart. #[test] fn a_read_note_kind_folds_counts_only() { @@ -2284,6 +2303,7 @@ mod tests { "EPSG:4326: 3 shape(s) left out".into(), "EPSG:3857: 3 shape(s) left out".into(), ]; + let notes = notes.map(rustgis_data::loss::Note::plain); source.saw_read_notes(¬es); let said = source.take_read_notes(); let expected = [¬es[0], ¬es[2], ¬es[4], ¬es[5], ¬es[6], ¬es[7], ¬es[8], ¬es[9]]; @@ -2358,7 +2378,7 @@ mod tests { #[test] fn opening_conversion_notes_are_runtime_only_and_taken_once() { let note = "GDAL: 2 features of another geometry type were left out"; - let mut source = super::SourceLayer { conversion_notes_unsaid: vec![note.into()], ..Default::default() }; + let mut source = super::SourceLayer { conversion_notes_unsaid: [note].into_iter().collect(), ..Default::default() }; let saved = serde_json::to_value(&source).unwrap(); assert!(saved.get("conversion_notes_unsaid").is_none()); let mut restored: super::SourceLayer = serde_json::from_value(saved).unwrap(); diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 29b9a7c776..c2711b1b29 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -27,7 +27,7 @@ impl FeatureSource for Chunks { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } @@ -84,7 +84,7 @@ fn streamed_kind(layer: &Layer, size: usize, native: bool) -> Layer { count: Some(ds.features.len() as u64), crs: if native { "EPSG:3857".into() } else { "EPSG:4326".into() }, indexed: true, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }; let mut l = layer.clone(); @@ -111,7 +111,7 @@ fn complete_chunks_preserve_painter_order_filters_transparency_labels_and_select unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } @@ -874,7 +874,7 @@ fn pitched_mixed_sources_keep_windows_and_pending_on_the_owner() { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }) } @@ -1716,7 +1716,7 @@ fn a_stopped_frame_reads_no_further_chunk_and_leaves_its_source_unfailed() { count: Some(ds.features.len() as u64), crs: "EPSG:4326".into(), indexed: true, - notes: Vec::new(), + notes: Default::default(), zm_dropped: false, }; let stop = Arc::new(AtomicBool::new(false)); diff --git a/crates/tiles/src/embeddings.rs b/crates/tiles/src/embeddings.rs index 36b10132c6..bdfab9fa9a 100644 --- a/crates/tiles/src/embeddings.rs +++ b/crates/tiles/src/embeddings.rs @@ -927,7 +927,7 @@ mod tests { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }; let t = aef_tiles(&fields, &batch, 2021, [-123.0, 40.0, -122.0, 41.0]); @@ -994,7 +994,7 @@ mod tests { unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), - notes: Vec::new(), + notes: Default::default(), not_utf8: Vec::new(), }; let f = aef_series(&fields, &batch, (2017, 2025), [-43.0, -20.9, -42.9, -20.8]); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fbc315dd34..8883a7e9b7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4739,7 +4739,7 @@ impl RustGisApp { // Not handed over (the failure is said): the area made for it goes too. if self.download(&name, bytes) { for note in notes { - self.session.notify(note, false); + self.session.say(note); } } else { rustgis_engine::cmd::field::forget_new_areas(&mut self.session, areas); @@ -4754,7 +4754,7 @@ impl RustGisApp { return Err(e.to_string()); } for note in notes { - self.session.notify(note, false); + self.session.say(note); } self.session.notify(i18n::fmt("Saved {name}", &[("name", &path)]), false); } @@ -5232,9 +5232,10 @@ impl RustGisApp { let ext = download_ext; // The features written, read whole, give their own extent, in longitude/latitude // (not a raster's, or the one a streamed layer's source declares). - let mut notes = rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs); + let mut notes: rustgis_engine::data::loss::Notes = + rustgis_engine::data::export_notes([(ds.as_ref(), ds.lonlat_extent())], &name, crs).into(); rustgis_engine::cmd::share::coalesce_read_zm(&mut notes, &name, &ds, &lost); - let mut dbf_notes = Vec::new(); + let mut dbf_notes = rustgis_engine::data::loss::Notes::new(); if ext == "zip" { dbf_notes.extend(io::shapefile_names_note(&ds.fields, &name)); dbf_notes.extend(io::shapefile_values_notes(&ds, &name)); @@ -5260,8 +5261,12 @@ impl RustGisApp { } if self.download(&name, bytes) { rustgis_engine::cmd::share::notify_export_query(&mut self.session, &name, &layer_name, &query_report); - for note in notes.into_iter().chain(dbf_notes).chain(construction_notes) { - self.session.notify(note, false); + for note in notes + .into_iter() + .chain(dbf_notes) + .chain(construction_notes.into_iter().map(rustgis_engine::data::loss::Note::plain)) + { + self.session.say(note); } } } diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index de854acb04..e9ce4629a5 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -1574,7 +1574,7 @@ fn add_selected(app: &mut RustGisApp) { match rustgis_engine::cmd::stac_area::selected_geometries(&app.session, &json!({})) { Ok((geometries, notes)) => { let what = tl!("the selected features").to_string(); - start_loading(app, what, move || rustgis_engine::cmd::stac_area::merge_loaded(&geometries, notes)); + start_loading(app, what, move || rustgis_engine::cmd::stac_area::merge_loaded(&geometries, notes.into())); } Err(e) => app.ui.stac.error = Some(e), } @@ -1626,7 +1626,11 @@ fn land(app: &mut RustGisApp, answer: Result) { match answer { Ok(loaded) => { for n in loaded.notices { - app.session.warn(n); + // An ordinary note warns; a loss says its code too. + match n.loss { + Some(_) => app.session.say(n), + None => app.session.warn(n.text), + } } push_part(app, loaded.geometry); } @@ -2904,8 +2908,10 @@ mod tests { assert!(app.ui.stac.error.is_some() && app.ui.stac.loading.is_none()); app.ui.stac.error = None; // A mixed answer lands its notices, then its part. - let answer = - rustgis_engine::cmd::stac_area::merge_loaded(&[rectangle([0.0, 0.0, 1.0, 1.0]), Geometry::Point(at(5.0, 5.0))], Vec::new()); + let answer = rustgis_engine::cmd::stac_area::merge_loaded( + &[rectangle([0.0, 0.0, 1.0, 1.0]), Geometry::Point(at(5.0, 5.0))], + Default::default(), + ); let before = app.session.notice_mark(); land(&mut app, answer); assert_eq!(app.ui.stac.parts.len(), 1);