From 17350636079a2b13fce720520e34c01ac21d52fc Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 22:44:04 -0600 Subject: [PATCH 1/3] fix(engine): window, series, tool-input and clip loss notices keep their codes (#2371) --- crates/engine/src/cmd/embeddings.rs | 65 +++++++++++++++------- crates/engine/src/cmd/gp.rs | 34 +++++++++++- crates/engine/src/cmd/imagery.rs | 32 +++++++++-- crates/engine/src/cmd/layer.rs | 7 ++- crates/engine/src/cmd/stac_bands.rs | 83 +++++++++++++++++----------- crates/engine/src/cmd/zarr.rs | 14 +++-- crates/engine/src/lib.rs | 9 +++ crates/engine/src/tests.rs | 72 +++++++++++++++++++++++- crates/geolibre/src/lib.rs | 64 +++++++++++++++------ crates/geolibre/src/tests.rs | 55 +++++++++++++++++- crates/ui-egui/src/workspacepanes.rs | 4 +- 11 files changed, 348 insertions(+), 91 deletions(-) diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index 64647c8917..236e607d94 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -10,6 +10,8 @@ use std::collections::BTreeMap; +#[cfg(not(target_arch = "wasm32"))] +use rustgis_data::loss::{LossCode, Note}; use rustgis_data::{Geometry, GeometryType, raster}; use rustgis_map::raster::RasterLayer; use serde_json::{Value, json}; @@ -823,14 +825,15 @@ pub(crate) fn similarity_work(s: &Session, p: &Value) -> Result = searched.into_iter().map(Note::plain).collect(); let file = files.first().ok_or("AlphaEarth has no file there")?; let w = read_window(file, area, cell)?; notes.extend(w.notes()); let r = &w.raster; // A reference with no embedding fails with what its layer said. let (reference, missed) = reference(r, &points).map_err(|e| with_notes(e, &taken))?; - notes.extend(taken); + notes.extend(taken.into_iter().map(Note::plain)); notes.extend(missed_points(missed, points.len())); let band = similarity_band(r, &reference)?; let name = name.unwrap_or_else(|| format!("AlphaEarth {year} similarity")); @@ -860,7 +863,8 @@ pub(crate) fn change_work(s: &Session, p: &Value) -> Result = searched.into_iter().map(Note::plain).collect(); let (Some(a), Some(b)) = (files.first(), files.get(1)) else { return Err("AlphaEarth has no files there".into()) }; let a = read_window(a, area, cell)?; let b = read_window(b, area, cell)?; @@ -879,7 +883,7 @@ const IN_THE_BROWSER: &str = "AlphaEarth's similarity and change are worked out /// The made raster, kept as a GeoTIFF, with what to say of it once it is added (by its name on /// the map) and what the command answers besides. #[cfg(not(target_arch = "wasm32"))] -fn made_saying(r: rustgis_data::raster::Raster, notes: Vec, extra: Value) -> Result { +fn made_saying(r: rustgis_data::raster::Raster, notes: Vec, extra: Value) -> Result { let bytes = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; let name = r.name.clone(); let layer = RasterLayer::from_written(r, format!("{name}.tif"), bytes); @@ -888,7 +892,7 @@ fn made_saying(r: rustgis_data::raster::Raster, notes: Vec, extra: Value let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok()); let added = id.and_then(|id| s.map().layer(id)).map_or(said, |l| l.name.clone()); for note in notes { - s.notify(format!("{added}: {note}"), false); + s.say(note.prefixed(&added)); } }); Ok(super::workflows::made_layer(name, layer, Some(extra), Some(then))) @@ -956,26 +960,36 @@ fn pick_tile(found: &emb::SeriesFound, years: &[i32]) -> Result<(Vec, St /// are on one grid, so the second's says the same; anything it adds is said too, by its year), /// and what each file's header left out, by year: once, for both, when both left it out. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn two_years_notes(a: &super::layer::WindowRaster, b: &super::layer::WindowRaster, (from, to): (i32, i32)) -> Vec { - let mut notes = a.read_notes(); +pub(crate) fn two_years_notes(a: &super::layer::WindowRaster, b: &super::layer::WindowRaster, (from, to): (i32, i32)) -> Vec { + let mut notes: Vec = a.read_notes().into_iter().map(Note::plain).collect(); for n in b.read_notes() { - if !notes.contains(&n) { - notes.push(format!("the {to} file: {n}")); + if !notes.iter().any(|known| known.text == n) { + notes.push(Note::plain(format!("the {to} file: {n}"))); } } - for l in a.raster.lost.texts() { - let both = b.raster.lost.says(l); - notes.push(if both { format!("the {from} and {to} files: {l}") } else { format!("the {from} file: {l}") }); + for l in a.raster.lost.iter() { + let both = b.raster.lost.says(&l.text); + notes.push(if both { + l.clone().prefixed(&format!("the {from} and {to} files")) + } else { + l.clone().prefixed(&format!("the {from} file")) + }); } - notes.extend(b.raster.lost.texts().filter(|l| !a.raster.lost.says(l)).map(|l| format!("the {to} file: {l}"))); + notes.extend(b.raster.lost.iter().filter(|l| !a.raster.lost.says(&l.text)).map(|l| l.clone().prefixed(&format!("the {to} file")))); notes } -/// What a similarity says of its reference points that have no embedding in the area read. +/// What a similarity says of its reference points that have no embedding in the area read: left +/// out of the reference, so a loss. #[cfg(not(target_arch = "wasm32"))] -fn missed_points(missed: usize, of: usize) -> Option { +fn missed_points(missed: usize, of: usize) -> Option { (missed > 0).then(|| { - format!("{missed} of the {of} reference points have no embedding in the area read (outside it, or no data there) and were left out") + Note::loss( + LossCode::DroppedFeature, + format!( + "{missed} of the {of} reference points have no embedding in the area read (outside it, or no data there) and were left out" + ), + ) }) } @@ -1519,22 +1533,31 @@ mod tests { // Reference points with no embedding: said with a count, nothing when all have one. assert_eq!(missed_points(0, 3), None); assert_eq!( - missed_points(1, 3).as_deref(), - Some("1 of the 3 reference points have no embedding in the area read (outside it, or no data there) and were left out") + missed_points(1, 3), + Some(Note::loss( + LossCode::DroppedFeature, + "1 of the 3 reference points have no embedding in the area read (outside it, or no data there) and were left out" + )) ); // What the work says is said once its raster is added, under the layer's name; a raster // with nothing to say adds none. let mut s = Session::new(Project::default()); let r = quantised([[1.0; 3]; 4]); - let made = |name: &str, notes: Vec| { + let made = |name: &str, notes: Vec| { let raster = rustgis_analysis::rasterops::derive(&r, name, vec![vec![0.5; 4]]).unwrap(); made_saying(raster, notes, json!({"year": 2024})).unwrap() }; let mark = s.notice_mark(); - let v = super::super::workflows::add_made(&mut s, made("Sim", notes.clone())).unwrap(); + let mut with_loss: Vec = notes.iter().map(Note::from).collect(); + with_loss.extend(missed_points(2, 5)); + let v = super::super::workflows::add_made(&mut s, made("Sim", with_loss)).unwrap(); assert_eq!(v["year"], 2024); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert_eq!(said.iter().filter(|n| n.starts_with("Sim: ")).count(), 5, "{said:?}"); + assert_eq!(said.iter().filter(|n| n.starts_with("Sim: ")).count(), 6, "{said:?}"); + // The loss keeps its code under the layer's name; the others are ordinary notices. + let coded: Vec<_> = s.notices_since(mark).iter().filter_map(|n| n.loss().map(|c| (c, n.text.clone()))).collect(); + assert_eq!(coded.len(), 1, "{coded:?}"); + assert!(coded[0].0 == LossCode::DroppedFeature && coded[0].1.starts_with("Sim: 2 of the 5 reference points"), "{coded:?}"); let mark = s.notice_mark(); super::super::workflows::add_made(&mut s, made("Clean", Vec::new())).unwrap(); assert!(!s.notices_since(mark).iter().any(|n| n.text.starts_with("Clean: "))); diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index d30058c052..aa3a3e2c3d 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -534,19 +534,21 @@ pub fn plugin_start(s: &mut Session, tool: &str, params: &Value) -> Result) { + for loss in lost { + publish_tool_loss(s, loss.code, &format!("{tool}: {}", loss.text), false); + } +} + /// Publishes a typed loss, retaining it through rollback when a file has already been delivered. fn publish_tool_loss(s: &mut Session, code: LossCode, text: &str, written: bool) { let mark = s.notice_mark(); @@ -4183,6 +4192,27 @@ fn publish_tool_loss(s: &mut Session, code: LossCode, text: &str, written: bool) mod file_tests { use super::*; + #[test] + fn a_plugin_tools_input_losses_are_said_with_their_codes() { + let mut s = Session::new(crate::Project::default()); + let mark = s.notice_mark(); + say_input_losses(&mut s, "Make Points", Vec::new()); + assert!(s.notices_since(mark).is_empty(), "a clean read says nothing"); + let lost = vec![ + LossMessage { code: LossCode::DroppedFeature, text: "Sites: 2 rows couldn't be read and were left out".into() }, + LossMessage { code: LossCode::DroppedValue, text: "Sites: 1 value isn't a date and was read as empty, in 'day'".into() }, + ]; + say_input_losses(&mut s, "Make Points", lost); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.loss(), n.text.clone())).collect(); + assert_eq!( + said, + [ + (Some(LossCode::DroppedFeature), "Make Points: Sites: 2 rows couldn't be read and were left out".to_string()), + (Some(LossCode::DroppedValue), "Make Points: Sites: 1 value isn't a date and was read as empty, in 'day'".to_string()), + ] + ); + } + #[test] fn raster_to_pmtiles_queues_the_archive_without_changing_the_map() { use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 0f5d7cfd98..d125a5f1cb 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1777,17 +1777,34 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result 0 { - messages.push(format!("{pl}: skipped {skipped} feature(s) with invalid polygon geometry")); + notes.push(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedFeature, + format!("{pl}: skipped {skipped} feature(s) with invalid polygon geometry"), + )); } if !failed_parts.is_empty() { - messages.push(format!( - "{pl}: skipped {} polygon part(s) that could not be projected onto the raster grid; valid parts were retained", - failed_parts.len() + notes.push(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedGeometry, + format!( + "{pl}: skipped {} polygon part(s) that could not be projected onto the raster grid; valid parts were retained", + failed_parts.len() + ), )); } - super::workflows::made(clipped, (!messages.is_empty()).then(|| json!({"messages": messages}))) + let messages: Vec<&str> = notes.iter().map(|n| n.text.as_str()).collect(); + let extra = (!messages.is_empty()).then(|| json!({"messages": messages})); + let then: Option = (!notes.is_empty()).then(|| { + Box::new(move |s: &mut Session, _: &mut Value| { + for note in notes { + s.say(note); + } + }) as super::workflows::Then + }); + super::workflows::made_then(clipped, extra, then) })) } "clip" => { @@ -2701,6 +2718,9 @@ fn clip_window( } // Some of the values rounded when the file was read may be in the window: how many isn't known. out.keep_rounded_mark(r); + // What reading the input left out (a colour table, metadata) is left out of the clip too: said, + // with its code, as the clip is added. + out.lost = r.lost.clone(); Ok(out) } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c21b95c18a..563b698caa 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6742,9 +6742,10 @@ pub(crate) struct WindowRaster { impl WindowRaster { /// What to say of the read, in order, and what its raster left out (`lost`: what the header /// holds but isn't read, values past `f32`'s range), for a caller that makes another raster - /// from it and so doesn't add this one (whose `lost` the layer would say). - pub(crate) fn notes(&self) -> Vec { - self.read_notes().into_iter().chain(self.raster.lost.texts().map(String::from)).collect() + /// from it and so doesn't add this one (whose `lost` the layer would say). The read's own notes + /// are plain (the box's edges are empty ground, not data left out); `lost` keeps its codes. + pub(crate) fn notes(&self) -> Vec { + self.read_notes().into_iter().map(rustgis_data::loss::Note::plain).chain(self.raster.lost.iter().cloned()).collect() } /// What to say of the read alone (its size and level, a cell size finer than the file's, the diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 4d6cdc832f..7ff7d6f0a6 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -65,6 +65,7 @@ mod desktop { use std::collections::BTreeSet; use std::sync::atomic::{AtomicBool, Ordering}; + use rustgis_data::loss::{LossCode, Note}; use rustgis_data::raster::Raster; use rustgis_map::{Ramp, RasterLayer, RasterRenderer, Stretch}; use serde_json::{Value, json}; @@ -429,24 +430,25 @@ mod desktop { /// naming every band of the files it is for and how many files. The notes of a kind differ by a /// number or an edge name from file to file, so they are matched by [`note_kind`], and each file's /// own wording is kept; a file counts once for a kind, however many of its notes are of it. - pub(super) fn merge_notes(files: &[(Vec, Vec)]) -> Vec { - let mut merged: Vec<(String, Vec, Vec, usize)> = Vec::new(); + pub(super) fn merge_notes(files: &[(Vec, Vec)]) -> Vec { + // A notice's kind, and the code it has: a coded note is never merged with a plain one. + let mut merged: Vec<((String, Option), Vec, Vec, usize)> = Vec::new(); for (whos, notes) in files { - let mut counted: Vec = Vec::new(); + let mut counted: Vec<(String, Option)> = Vec::new(); for n in notes { - let kind = note_kind(n); + let kind = (note_kind(&n.text), n.loss); let first = !counted.contains(&kind); match merged.iter_mut().find(|(k, ..)| *k == kind) { Some((_, texts, bands, files)) => { - if !texts.contains(n) { - texts.push(n.clone()); + if !texts.contains(&n.text) { + texts.push(n.text.clone()); } if first { bands.extend(whos.iter().cloned()); *files += 1; } } - None => merged.push((kind.clone(), vec![n.clone()], whos.clone(), 1)), + None => merged.push((kind.clone(), vec![n.text.clone()], whos.clone(), 1)), } if first { counted.push(kind); @@ -455,8 +457,9 @@ mod desktop { } merged .into_iter() - .map(|(_, texts, bands, files)| { - format!("{} ({files} file{}): {}", bands.join(", "), if files == 1 { "" } else { "s" }, texts.join("; ")) + .map(|((_, loss), texts, bands, files)| Note { + text: format!("{} ({files} file{}): {}", bands.join(", "), if files == 1 { "" } else { "s" }, texts.join("; ")), + loss, }) .collect() } @@ -469,7 +472,7 @@ mod desktop { hrefs: &[String], bbox: [f64; 4], cell: (f64, bool), - ) -> Result<(Raster, Vec), String> { + ) -> Result<(Raster, Vec), String> { // One read for a file, whichever of its bands are wanted (the first to want it sets the count), and // every band of the file is read, so the count asked is the file's, not the band's place. // The cost grows with the file's band count (a 13-band file is about 13 times the bytes @@ -485,7 +488,7 @@ mod desktop { let read = read_windows(&files, bbox, cell)?; // What each file's read said, merged into one notice for a kind (see [`merge_notes`]). let mut windows: Vec<(String, WindowRaster)> = Vec::new(); - let mut said: Vec<(Vec, Vec)> = Vec::new(); + let mut said: Vec<(Vec, Vec)> = Vec::new(); for ((href, _), w) in files.into_iter().zip(read) { let whos: Vec = picked.iter().zip(channels).zip(hrefs).filter(|(_, h)| **h == href).map(|((_, c), _)| c.clone()).collect(); @@ -535,7 +538,7 @@ mod desktop { /// the catalog's scale and offset applied. A cell with no value in any is no data in all. The rows /// are worked one after another on this thread (about 4 million cell transforms a band at the /// default window, which is brief), looking at Cancel and counting progress on each. - pub(super) fn stack(name: &str, channels: &[String], sources: &[(&Raster, &sb::Band)]) -> Result<(Raster, Vec), String> { + pub(super) fn stack(name: &str, channels: &[String], sources: &[(&Raster, &sb::Band)]) -> Result<(Raster, Vec), String> { let (Some((first, _)), true) = (sources.first(), sources.len() >= 2) else { return Err("a stack needs at least two bands".into()) }; if sources.iter().any(|(r, _)| r.crs != first.crs) { return Err("the bands are in different coordinate systems: they can't be put on one grid".into()); @@ -598,7 +601,7 @@ mod desktop { channels.join(", ") )); } - let mut notes = Vec::new(); + let mut notes: Vec = Vec::new(); // The window reader rounds whole numbers past 2^24 and doubles to 32-bit floats: said once, by band. let rounded: Vec<&str> = sources .iter() @@ -607,9 +610,12 @@ mod desktop { .map(|(_, c)| c.as_str()) .collect(); if !rounded.is_empty() { - notes.push(format!( - "{} read with values rounded to 32-bit floats (whole numbers past 16,777,216, or more digits than a 32-bit float holds): the stacked values are the rounded ones", - rounded.join(", ") + notes.push(Note::loss( + LossCode::ChangedRounded, + format!( + "{} read with values rounded to 32-bit floats (whole numbers past 16,777,216, or more digits than a 32-bit float holds): the stacked values are the rounded ones", + rounded.join(", ") + ), )); } // A band taken from a colour image (the item has no file of its own for it) is not in the @@ -623,11 +629,11 @@ mod desktop { .map(|((_, b), who)| format!("{who} (band {} of {})", b.index, b.asset)) .collect(); if !from_colour.is_empty() && !one_image { - notes.push(format!( + notes.push(Note::plain(format!( "{} {} taken from a file of several bands, as the item has no file of its own: the values may not be in the units of the other bands (a colour image's are 8-bit)", from_colour.join(", "), if from_colour.len() == 1 { "is" } else { "are" } - )); + ))); } // Integer files the catalog gives no scale for are used as stored: not reflectance, which the // indices' constants and a colour mixed with scaled bands assume. One notice, naming them. @@ -638,10 +644,10 @@ mod desktop { .map(|((r, _), who)| format!("{who} ({})", r.data_type)) .collect(); if !unscaled.is_empty() { - notes.push(format!( + notes.push(Note::plain(format!( "{} have no scale in the catalog, so their integer values are used as stored, not as reflectance: an index, or a colour mixing them with scaled bands, will be off", unscaled.join(", ") - )); + ))); } let size = finest.transform.pixel_width.abs(); let resampled: Vec<&str> = sources @@ -651,14 +657,14 @@ mod desktop { .map(|(_, c)| c.as_str()) .collect(); if !resampled.is_empty() { - notes.push(format!( + notes.push(Note::plain(format!( "{} read on a coarser grid than the finest of the bands, and put on it by nearest cell", resampled.join(", ") - )); + ))); } if left > 0 { let share = left as f64 * 100.0 / (w * h).max(1) as f64; - notes.push(format!("{left} cells ({share:.1}%) have no value in at least one band (no data, or outside a band's window) and are no data in every band")); + notes.push(Note::plain(format!("{left} cells ({share:.1}%) have no value in at least one band (no data, or outside a band's window) and are no data in every band"))); } let mut raster = rustgis_analysis::rasterops::derive(finest, name, bands)?; for (b, c) in raster.bands.iter_mut().zip(channels) { @@ -669,7 +675,7 @@ mod desktop { /// The made raster, kept as a GeoTIFF and drawn as red, green and blue, with what to say of it /// once it is added (by its name on the map) and what the command answers besides. - fn made_saying(raster: Raster, notes: Vec, extra: Value) -> Result { + fn made_saying(raster: Raster, notes: Vec, extra: Value) -> Result { // The encode is one step with no look inside it: Cancel is looked at before it. rustgis_data::progress::check().map_err(|e| e.to_string())?; let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; @@ -681,12 +687,12 @@ mod desktop { } /// What to say of a made layer once it is added: each note, by the layer's name on the map. - fn noted(name: String, notes: Vec) -> Then { + fn noted(name: String, notes: Vec) -> Then { Box::new(move |s: &mut Session, v: &mut Value| { let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok()); let added = id.and_then(|id| s.map().layer(id)).map_or(name, |l| l.name.clone()); for note in notes { - s.notify(format!("{added}: {note}"), false); + s.say(note.prefixed(&added)); } }) } @@ -698,6 +704,7 @@ mod desktop { mod tests { use super::desktop::{auto_cell, index_look, note_kind, read_windows, stack}; use crate::render::rustgis_tiles::stac::bands::Band; + use rustgis_data::loss::{LossCode, Note}; use rustgis_data::raster::{ColorHint, GeoTransform, Raster, crs::Crs}; use serde_json::json; @@ -897,7 +904,7 @@ mod tests { // Two bands from colour images are one notice naming both; all from one image (the units agree) say nothing. let three: Vec = vec!["nir".into(), "red".into(), "green".into()]; let (_, notes) = stack("s", &three, &[(&a, &band(1.0, 0.0)), (&a, &colour(1)), (&a, &colour(1))]).unwrap(); - let said: Vec<&String> = notes.iter().filter(|n| n.contains("several bands")).collect(); + let said: Vec<&Note> = notes.iter().filter(|n| n.contains("several bands")).collect(); assert!(said.len() == 1 && said[0].contains("red (band 1 of visual), green (band 1 of visual) are taken"), "{notes:?}"); let (_, same) = stack("s", &names, &[(&a, &colour(1)), (&a, &colour(1))]).unwrap(); assert!(!same.iter().any(|n| n.contains("several bands")), "one image: {same:?}"); @@ -1172,8 +1179,9 @@ mod tests { let mut lossy = grid(2, 2, 0.0001, vec![1000.0; 4]); lossy.rounded = vec![3]; let (_, notes) = stack("s", &names, &[(&clean, &band(1.0, 0.0)), (&lossy, &band(1.0, 0.0))]).unwrap(); - let said: Vec<&String> = notes.iter().filter(|n| n.contains("rounded")).collect(); + let said: Vec<&Note> = notes.iter().filter(|n| n.contains("rounded")).collect(); assert!(said.len() == 1 && said[0].starts_with("red read with values rounded"), "{notes:?}"); + assert_eq!(said[0].loss, Some(LossCode::ChangedRounded)); let (_, none) = stack("s", &names, &[(&clean, &band(1.0, 0.0)), (&clean, &band(1.0, 0.0))]).unwrap(); assert!(!none.iter().any(|n| n.contains("rounded")), "{none:?}"); } @@ -1181,14 +1189,15 @@ mod tests { #[test] fn the_notes_of_the_files_are_one_notice_for_a_kind_counting_each_file_once() { use super::desktop::merge_notes; - let edges = |e: &str| format!("the box reaches past the file's {e} edge(s): the window is cut to the file"); + let edges = |e: &str| Note::plain(format!("the box reaches past the file's {e} edge(s): the window is cut to the file")); let pieces = - "3 piece(s) of the box's edges not followed to a quarter of a pixel: the window may fall short of a bent edge".to_string(); + Note::plain("3 piece(s) of the box's edges not followed to a quarter of a pixel: the window may fall short of a bent edge"); let w = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::>(); // Two files whose edge notes name different edges: one notice, two files, both wordings kept. let two = merge_notes(&[(w(&["red"]), vec![edges("north")]), (w(&["green", "blue"]), vec![edges("south")])]); assert_eq!(two.len(), 1, "{two:?}"); - assert!(two[0].starts_with("red, green, blue (2 files): ") && two[0].contains("north") && two[0].contains("south"), "{two:?}"); + assert!(two[0].text.starts_with("red, green, blue (2 files): ") && two[0].contains("north") && two[0].contains("south"), "{two:?}"); + assert_eq!(two[0].loss, None); // A file with two notes of one kind counts once, its bands listed once. let once = merge_notes(&[(w(&["red"]), vec![edges("north"), edges("east")])]); assert_eq!(once.len(), 1); @@ -1196,6 +1205,18 @@ mod tests { // Different kinds stay apart; a clean run says nothing. assert_eq!(merge_notes(&[(w(&["red"]), vec![edges("north"), pieces])]).len(), 2); assert!(merge_notes(&[(w(&["red"]), Vec::new()), (w(&["green"]), Vec::new())]).is_empty()); + // The same words as a coded and as a plain note are two notices, each keeping its code. + let rounded = |code: Option| Note { text: "values rounded to 32-bit floats".into(), loss: code }; + let split = merge_notes(&[ + (w(&["red"]), vec![rounded(Some(LossCode::ChangedRounded))]), + (w(&["green"]), vec![rounded(None)]), + (w(&["blue"]), vec![rounded(Some(LossCode::ChangedRounded))]), + ]); + assert_eq!(split.len(), 2, "{split:?}"); + let coded = split.iter().find(|n| n.loss == Some(LossCode::ChangedRounded)).unwrap(); + assert!(coded.starts_with("red, blue (2 files): "), "{split:?}"); + let plain = split.iter().find(|n| n.loss.is_none()).unwrap(); + assert!(plain.starts_with("green (1 file): "), "{split:?}"); } #[test] diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 002d8a8465..36b8647de6 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -7,6 +7,8 @@ use std::collections::HashMap; #[cfg(not(target_arch = "wasm32"))] use std::path::Path; +#[cfg(not(target_arch = "wasm32"))] +use rustgis_data::loss::{LossCode, Note}; use rustgis_data::raster::{self, Crs, zarr}; use rustgis_map::raster::RasterLayer; #[cfg(not(target_arch = "wasm32"))] @@ -1611,7 +1613,7 @@ fn series(s: &mut Session, p: &Value) -> CmdResult { let mut notes = Vec::new(); let series = series_start(s, p)?.read(&mut notes); for n in notes { - s.warn(n); + s.say_warning(n); } series } @@ -1663,7 +1665,7 @@ impl SeriesRun { /// Reads the series under `control`: its count is the steps read of those asked, and Cancel /// stops it before its next batch of reads, with no series. Gives the series as `zarr.series` /// answers it, and what reading it said, which a read that fails said too. - pub fn run(&self, control: &std::sync::Arc) -> (Result, Vec) { + pub fn run(&self, control: &std::sync::Arc) -> (Result, Vec) { let mut notes = Vec::new(); let series = rustgis_analysis::run_under("Time Series at a Point", control, || self.read(&mut notes)); (series, notes) @@ -1671,7 +1673,7 @@ impl SeriesRun { /// Reads the series on this thread, looking at the run's Cancel (if any) between batches; /// what reading it says goes in `notes` as it is found, so an error after it doesn't lose it. - fn read(&self, notes: &mut Vec) -> Result { + fn read(&self, notes: &mut Vec) -> Result { let (lon, lat) = (self.lon, self.lat); let mut src = self.src.clone(); let check = &mut |_: usize| rustgis_data::progress::check().map_err(|_| "cancelled".to_string()); @@ -1715,7 +1717,7 @@ impl SeriesRun { // A typed system is only a fallback. Invalid text wasn't used on degree axes either. let typed = if given.is_none() { src.crs.as_deref().and_then(|text| Crs::parse(text).ok()) } else { None }; if let Some(note) = zarr::lonlat_assumption(given.as_ref().map(|(c, _)| *c), typed) { - notes.push(format!("{var}: {note}")); + notes.push(Note::loss(LossCode::AssumedCrs, format!("{var}: {note}"))); } } let crs = if lonlat { @@ -1727,12 +1729,12 @@ impl SeriesRun { // Read as `parse_crs` reads it, its note said with the series'. let crs = Crs::parse(text)?; if let Some(note) = raster::wkt::typed_crs_note(text, crs) { - notes.push(format!("crs: {note}")); + notes.push(Note::loss(LossCode::ApproximatedDatum, format!("crs: {note}"))); } crs }; if let Some((_, Some(note))) = given { - notes.push(format!("{var}: {note}")); + notes.push(Note::loss(LossCode::ApproximatedDatum, format!("{var}: {note}"))); } let m = crs .transformer()? diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 07a6d66ec1..8317b20c80 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3443,6 +3443,15 @@ impl Session { } } + /// [`Session::say`] for a read that always warned: a note that reports a loss as that loss, with + /// its code, any other as a warning ([`Session::warn`]), not information. + pub fn say_warning(&mut self, note: rustgis_data::loss::Note) { + match note.loss { + Some(code) => self.notify_loss(code, note.text.into()), + None => self.warn(note.text), + } + } + /// [`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) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6ea0405be9..d76a1b7745 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49887,11 +49887,17 @@ fn raster_projection_failures_are_reported_for_zonal_statistics_and_clipping() { let mut s = world(); let gt = GeoTransform { origin_x: 500_000.0, origin_y: 4_500_000.0, pixel_width: 1_000.0, pixel_height: -1_000.0 }; - let raster = Raster::new("utm", 10, 10, vec![vec![7.0; 100]], gt, Crs::Epsg(32617), None, ColorHint::Gray, "Float32").unwrap(); + let mut raster = Raster::new("utm", 10, 10, vec![vec![7.0; 100]], gt, Crs::Epsg(32617), None, ColorHint::Gray, "Float32").unwrap(); + // What reading the raster left out is left out of its clip too, and said with its code. + raster.lost.push(rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedValue, "3 values past the range were left out")); let ring: Vec<_> = [(1.0, 1.0), (9.0, 1.0), (9.0, 9.0), (1.0, 9.0)] .into_iter() .map(|(x, y)| raster.transformer().to_lonlat(gt.to_world(x, y)).unwrap()) .collect(); + let small: Vec<_> = [(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)] + .into_iter() + .map(|(x, y)| raster.transformer().to_lonlat(gt.to_world(x, y)).unwrap()) + .collect(); let invalid = vec![Coord::new(-81.0, 100.0), Coord::new(-80.0, 100.0), Coord::new(-80.0, 101.0)]; assert!(raster.transformer().from_lonlat(invalid[0]).is_none()); s.map_mut().add_raster("utm", rustgis_map::RasterLayer::from_path(raster, "utm.tif")); @@ -49906,8 +49912,35 @@ fn raster_projection_failures_are_reported_for_zonal_statistics_and_clipping() { assert_eq!(out.value(0, out.field_index("utm_count").unwrap()), &rustgis_data::Value::Int(64)); assert_eq!(out.value(0, out.field_index("utm_mean").unwrap()), &rustgis_data::Value::Float(7.0)); + use rustgis_data::loss::LossCode; + let mark = s.notice_mark(); let clip = s.run("raster.process", &json!({"layer": "utm", "operation": "clip", "polygon": "parts", "name": "clipped"})).unwrap(); assert!(clip["messages"].to_string().contains("skipped 1 polygon part(s)"), "{clip}"); + // The same failures are said as notices with their codes, and the raster's own loss is carried on. + let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.loss(), n.text.clone())).collect(); + assert!(said.iter().any(|(code, t)| *code == Some(LossCode::DroppedGeometry) && t.contains("skipped 1 polygon part(s)")), "{said:?}"); + assert!( + said.iter().any(|(code, t)| *code == Some(LossCode::DroppedValue) && t == "clipped: 3 values past the range were left out"), + "{said:?}" + ); + // Features with no polygon to clip by are skipped, counted and said as dropped features. + let mut mixed = Dataset::new("mixed", GeometryType::Polygon, vec![]); + mixed.push(Some(Geometry::Polygon(vec![vec![small.clone()]])), vec![]); + mixed.push(None, vec![]); + s.map_mut().add_layer(rustgis_map::Layer::new(0, mixed)); + let mark = s.notice_mark(); + let clip = s.run("raster.process", &json!({"layer": "utm", "operation": "clip", "polygon": "mixed", "name": "clipped2"})).unwrap(); + assert!(clip["messages"].to_string().contains("skipped 1 feature(s)"), "{clip}"); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.loss(), n.text.clone())).collect(); + assert!(said.iter().any(|(c, t)| *c == Some(LossCode::DroppedFeature) && t.contains("skipped 1 feature(s)")), "{said:?}"); + // A clean clip says nothing of a skip. + let mut clean = Dataset::new("clean", GeometryType::Polygon, vec![]); + clean.push(Some(Geometry::Polygon(vec![vec![small.clone()]])), vec![]); + s.map_mut().add_layer(rustgis_map::Layer::new(0, clean)); + let mark = s.notice_mark(); + let clip = s.run("raster.process", &json!({"layer": "utm", "operation": "clip", "polygon": "clean", "name": "clipped3"})).unwrap(); + assert!(clip.get("messages").is_none(), "{clip}"); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("skipped")), "{:?}", s.notices_since(mark)); let data = s.map().layer_by_name("clipped").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap(); assert_eq!((data.width, data.height), (8, 8)); } @@ -51882,9 +51915,28 @@ fn a_window_read_for_another_raster_says_what_its_header_left_out() { // A change says what each year's file left out, by its year, and once for both when both left // it out; the read, the same for both, once. use crate::cmd::embeddings::two_years_notes; - let lossy = read_window_raster(&WindowAsked::of(&format!("{lossy}/lossy.tif"), [10.0, 45.0, 10.5, 45.5], None, 1), &stop).unwrap(); + let lossy_url = lossy; + let lossy = read_window_raster(&WindowAsked::of(&format!("{lossy_url}/lossy.tif"), [10.0, 45.0, 10.5, 45.5], None, 1), &stop).unwrap(); let said = two_years_notes(&w, &lossy, (2017, 2025)); assert!(said.iter().any(|n| n.starts_with("the 2025 file: its colour table has 384 entries")), "{said:?}"); + // A loss the header's reader codes keeps its code through both reads' notes and the year prefix. + use rustgis_data::loss::{LossCode, Note}; + let mut lossy_coded = + read_window_raster(&WindowAsked::of(&format!("{lossy_url}/lossy.tif"), [10.0, 45.0, 10.5, 45.5], None, 1), &stop).unwrap(); + lossy_coded.raster.lost.push(Note::loss(LossCode::ChangedRounded, "values past f32's range were rounded")); + assert!(lossy_coded.notes().iter().any(|n| n.loss == Some(LossCode::ChangedRounded) && n.text.contains("rounded"))); + assert!(w.notes().iter().all(|n| n.loss.is_none()), "a clean file codes nothing"); + let said_coded = two_years_notes(&w, &lossy_coded, (2017, 2025)); + assert!( + said_coded.iter().any(|n| n.loss == Some(LossCode::ChangedRounded) && n.text.starts_with("the 2025 file: values past")), + "{said_coded:?}" + ); + assert!(said_coded.iter().filter(|n| n.loss.is_some()).count() == 1, "{said_coded:?}"); + let both = two_years_notes(&lossy_coded, &lossy_coded, (2017, 2025)); + assert!( + both.iter().any(|n| n.loss == Some(LossCode::ChangedRounded) && n.text.starts_with("the 2017 and 2025 files: values past")), + "{both:?}" + ); assert!(!said.iter().any(|n| n.starts_with("the 2017")), "{said:?}"); assert_eq!(said.iter().filter(|n| n.contains("window of the full image")).count(), 1, "{said:?}"); let said = two_years_notes(&lossy, &w, (2017, 2025)); @@ -60517,10 +60569,24 @@ fn a_zarr_series_says_its_notes_though_the_read_fails() { let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(err.as_ref().is_err_and(|e| e.contains("outside")), "{err:?}"); assert!(said.iter().any(|n| n.contains("WGS 84")), "the grid note is said: {said:?}"); + // The assumption is a loss with its code, said as one by the script's command. + let coded: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("WGS 84")).map(|n| n.loss()).collect(); + assert_eq!(coded, [Some(rustgis_data::loss::LossCode::AssumedCrs)]); let (read, notes) = crate::cmd::zarr::series_start(&s, &outside).unwrap().run(&rustgis_analysis::control::Control::stoppable()); let _ = std::fs::remove_dir_all(dir); assert!(read.as_ref().is_err_and(|e| e.contains("outside")), "{read:?}"); assert!(notes.iter().any(|n| n.contains("WGS 84")), "the pane gets the note too: {notes:?}"); + // The pane gets the code with the text, and says it as a loss. + assert!(notes.iter().all(|n| n.loss == Some(rustgis_data::loss::LossCode::AssumedCrs)), "{notes:?}"); + let mark = s.notice_mark(); + for n in notes { + s.say_warning(n); + } + assert_eq!(s.notices_since(mark).iter().map(|n| n.loss()).collect::>(), [Some(rustgis_data::loss::LossCode::AssumedCrs)]); + // A plain note stays a warning with no code. + s.say_warning(rustgis_data::loss::Note::plain("just so")); + let last = s.notices_since(mark).last().cloned().unwrap(); + assert!(last.loss().is_none() && last.text == "just so", "{last:?}"); } /// A point's series read off the window (opengeos/RustGIS#2282): `SeriesRun::run` gives what @@ -60561,7 +60627,7 @@ fn a_zarr_series_read_off_the_window_stops_between_batches() { assert_eq!(series["dates"], answer["dates"]); assert_eq!(series["values"][129], json!(12908.0)); // What reading it said, for the app to say as the command does: the grid taken as WGS 84. - assert!(notes.iter().any(|n| n.contains("WGS 84")), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains("WGS 84") && n.loss == Some(rustgis_data::loss::LossCode::AssumedCrs)), "{notes:?}"); assert_eq!(control.progress(), Some((130, 130))); // Its looks at Cancel, counted on a whole run. let (p, _log) = serve(); diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index dd9ba4c55b..40f4424777 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -36,6 +36,7 @@ use std::path::Path; use std::sync::Mutex; use rustgis_analysis::{Inputs, Output, OutputLayer, ParamKind, ParamSpec, ToolResult, ToolSpec}; +use rustgis_data::loss::{LossCode, LossMessage, Note}; use rustgis_data::raster::{Crs, Transformer}; use rustgis_data::{Coord, Dataset, Extent, Geometry}; use serde_json::{Value, json}; @@ -458,8 +459,8 @@ pub struct Job { /// (file name, layer name) for each declared output. outputs: Vec<(String, String)>, crs: Crs, - /// Problems found while staging that don't stop the run. - notes: Vec, + /// Problems found while staging that don't stop the run; a loss keeps its code to [`finish`]. + notes: Vec, } impl Job { @@ -535,7 +536,10 @@ fn stage(inputs: &dyn Inputs, value: &str, data: Data, tf: &Transformer, job: &m } let (bytes, lost) = vector_bytes(ds, inputs.selection(value), job.crs, tf)?; if lost > 0 { - job.notes.push(format!("{value}: {lost} features lie outside the working coordinate system and were passed without geometry")); + job.notes.push(Note::loss( + LossCode::DroppedGeometry, + format!("{value}: {lost} features lie outside the working coordinate system and were passed without geometry"), + )); } return Ok(job.stage(value, "geojson", bytes)); } @@ -772,7 +776,7 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu { let (order, note) = calculator_order(expression, list, inputs).map_err(|e| format!("{}: {e}", spec.name))?; list = order; - job.notes.extend(note.map(|n| format!("{}: {n}", spec.name))); + job.notes.extend(note.map(|n| Note::plain(format!("{}: {n}", spec.name)))); } let files = list.into_iter().map(|n| stage(inputs, n, p.data, &tf, &mut job)).collect::, _>>()?; if !files.is_empty() { @@ -813,17 +817,25 @@ fn prepare_with(spec: &ToolSpec, meta: &Meta, inputs: &dyn Inputs, params: &Valu } // One notice per kind, with a count. if !renamed.is_empty() { - job.notes.push(format!("{}: {} output name(s) in use already, so numbered: {}", spec.name, renamed.len(), renamed.join(", "))); + job.notes.push(Note::plain(format!( + "{}: {} output name(s) in use already, so numbered: {}", + spec.name, + renamed.len(), + renamed.join(", ") + ))); } if shortened { - job.notes.push(format!("{}: the output name is cut to fit each output's own name within {MAX_OUTPUT_NAME} characters", spec.name)); + job.notes.push(Note::plain(format!( + "{}: the output name is cut to fit each output's own name within {MAX_OUTPUT_NAME} characters", + spec.name + ))); } Ok(job) } /// The layer name given in [`OUTPUT`], trimmed, or `None` for the tool's own name. Cut to /// [`MAX_OUTPUT_NAME`] characters, which is said. -fn output_name(spec: &ToolSpec, params: &Value, notes: &mut Vec) -> Result, String> { +fn output_name(spec: &ToolSpec, params: &Value, notes: &mut Vec) -> Result, String> { let name = match params.get(OUTPUT) { None | Some(Value::Null) => return Ok(None), Some(Value::String(s)) => s.trim(), @@ -834,7 +846,9 @@ fn output_name(spec: &ToolSpec, params: &Value, notes: &mut Vec) -> Resu } let n = name.chars().count(); if n > MAX_OUTPUT_NAME { - notes.push(format!("{}: the output name is cut from {n} to {MAX_OUTPUT_NAME} characters", spec.name)); + // Plain: the layer's name is the tool's own naming, not data a file or layer holds, and the + // fix for a cut (a format that holds more text) isn't one for a name. + notes.push(Note::plain(format!("{}: the output name is cut from {n} to {MAX_OUTPUT_NAME} characters", spec.name))); } Ok(Some(name.chars().take(MAX_OUTPUT_NAME).collect())) } @@ -1005,7 +1019,7 @@ fn load( job: &Job, dir: Option<&Path>, messages: &mut Vec, - losses: &mut Vec, + losses: &mut Vec, ) -> Option { let mut ext = Path::new(file_name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); // A tool whose manifest calls its vector output a raster writes GeoJSON into the `.tif` it is @@ -1035,7 +1049,7 @@ fn load( match ext.as_str() { "tif" | "tiff" | "asc" => match rustgis_data::raster::read_bytes(file_name, bytes) { Ok(grey) => { - let bytes = if ext == "asc" { bytes.to_vec() } else { colours_split(&grey, bytes, layer_name, messages) }; + let bytes = if ext == "asc" { bytes.to_vec() } else { colours_split(&grey, bytes, layer_name, messages, losses) }; Some(OutputLayer::Raster { name: layer_name.to_string(), file_name: file_name.to_string(), bytes }) } Err(e) => { @@ -1056,7 +1070,7 @@ fn load( for note in report.messages { let note = note.prefixed(layer_name); match note.loss { - Some(code) => losses.push(rustgis_data::loss::LossMessage { code, text: note.text }), + Some(code) => losses.push(LossMessage { code, text: note.text }), None => messages.push(note.text), } } @@ -1128,7 +1142,13 @@ fn load( /// `0xAABBGGRR`, as Panchromatic Sharpening writes by default) rewritten as red, green, blue and /// alpha byte bands before anything holds it as `f32`, which drops the red byte (#2594), and said; /// any other as the tool wrote it. `grey` is the file as read. -fn colours_split(grey: &rustgis_data::raster::Raster, bytes: &[u8], layer_name: &str, messages: &mut Vec) -> Vec { +fn colours_split( + grey: &rustgis_data::raster::Raster, + bytes: &[u8], + layer_name: &str, + messages: &mut Vec, + losses: &mut Vec, +) -> Vec { use rustgis_data::raster::geotiff; match geotiff::unpack_rgba(grey, bytes).and_then(|r| r.map(|r| geotiff::write_all(&r)).transpose()) { Ok(Some(rgba)) => { @@ -1136,7 +1156,13 @@ fn colours_split(grey: &rustgis_data::raster::Raster, bytes: &[u8], layer_name: "{layer_name}: its one band of packed colours (alpha, blue, green and red bytes) was split into red, green and blue bands, see-through where alpha is 0 or the pixel is no-data" )); // What reading the tool's file left out, which the rewritten file no longer shows. - messages.extend(grey.lost.texts().map(|l| format!("{layer_name}: {l}"))); + for note in grey.lost.iter().cloned() { + let note = note.prefixed(layer_name); + match note.loss { + Some(code) => losses.push(LossMessage { code, text: note.text }), + None => messages.push(note.text), + } + } rgba } Ok(None) => bytes.to_vec(), @@ -1213,11 +1239,17 @@ pub fn finish(job: &Job, files: &[(String, Vec)], lines: &[String], dir: Opt } _ => serde_json::Map::new(), }; - let mut messages = job.notes.clone(); + let mut messages = Vec::new(); + let mut losses = Vec::new(); + for note in job.notes.iter().cloned() { + match note.loss { + Some(code) => losses.push(LossMessage { code, text: note.text }), + None => messages.push(note.text), + } + } messages.extend(lines.into_iter().take(40).map(str::to_string)); let mut layers = Vec::new(); - let mut losses = Vec::new(); for (file, name) in &job.outputs { // A tool may pick its own extension (a shapefile for a vector output). let stem = Path::new(file).file_stem(); @@ -1248,7 +1280,7 @@ pub fn finish(job: &Job, files: &[(String, Vec)], lines: &[String], dir: Opt let text: String = text.chars().take(2000).collect(); messages.push(format!("{}: {text}", label_of(k))); } - if layers.is_empty() && messages.is_empty() { + if layers.is_empty() && messages.is_empty() && losses.is_empty() { messages.push(format!("{} finished without output", job.name)); } ToolResult { losses, output: Output::Layers(layers), messages } diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index 41e1abb9e6..d88b9e7e7d 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -220,7 +220,7 @@ fn outputs_are_named_by_the_output_field() { let params = rustgis_analysis::resolve_params(&spec2, &json!({"dem": "dem", "output": "Taken"})).unwrap(); let both = prepare_with(&spec2, &meta2, &fg, ¶ms).unwrap(); assert_eq!(both.outputs.iter().map(|(_, n)| n.as_str()).collect::>(), ["Taken streams 2", "Taken basins 2"]); - let numbered_notes: Vec<&String> = both.notes.iter().filter(|n| n.contains("numbered")).collect(); + let numbered_notes: Vec<&Note> = both.notes.iter().filter(|n| n.contains("numbered")).collect(); assert!(matches!(numbered_notes[..], [n] if n.contains("2 output name(s)")), "{:?}", both.notes); // A long name whose output name is taken: the number goes after the output's name, which is // kept whole (review). @@ -932,3 +932,56 @@ fn a_vector_written_into_a_tif_comes_back_as_a_vector() { assert!(matches!(junk.output, Output::Layers(ref l) if l.is_empty())); assert!(junk.messages.iter().any(|m| m.starts_with("Flowpaths:")), "{:?}", junk.messages); } + +/// Features that lie outside the working coordinate system are passed without geometry, which is +/// a loss with its code, and a clean input says nothing; `finish` hands the code on as a +/// `LossMessage` and keeps the plain notes as messages (the native and browser runners both end +/// in `finish`). +#[test] +fn features_passed_without_geometry_keep_their_code_to_the_result() { + let mut f = Fixture::new(); + let crs = Crs::from_epsg(32617).unwrap(); + let tf = crs.transformer().unwrap(); + let mut job = Job { + tool: "buffer".into(), + name: "Buffer".into(), + files: Vec::new(), + args: Vec::new(), + outputs: Vec::new(), + crs, + notes: Vec::new(), + }; + stage(&f, "pts", Data::Vector, &tf, &mut job).unwrap(); + assert!(job.notes.is_empty(), "a clean layer says nothing: {:?}", job.notes); + // A point with no place in the zone (no coordinates to give it). + f.points.features.push(Feature { + id: 2, + geometry: Some(Geometry::Point(Coord::new(f64::NAN, f64::NAN))), + attrs: vec![rustgis_data::Value::Int(2)], + }); + stage(&f, "pts", Data::Vector, &tf, &mut job).unwrap(); + let [note] = &job.notes[..] else { panic!("one notice: {:?}", job.notes) }; + assert_eq!(note.loss, Some(LossCode::DroppedGeometry)); + assert!(note.text.starts_with("pts: 1 features lie outside the working coordinate system"), "{note:?}"); + job.notes.push(Note::plain("Buffer: the output name is cut")); + let r = finish(&job, &[], &[], None); + assert_eq!(r.losses.len(), 1, "{:?}", r.losses); + assert_eq!(r.losses[0].code, LossCode::DroppedGeometry); + assert!(r.losses[0].text.contains("passed without geometry"), "{:?}", r.losses); + assert_eq!(r.messages, ["Buffer: the output name is cut"], "the coded note is not said twice"); +} + +/// What reading a packed-colour output left out is said after the split with its code when it has +/// one, and as a plain message when it has none. +#[test] +fn what_reading_a_split_colour_output_left_out_keeps_its_code() { + let tiff = u32_tiff([0xFF0A_141E, 0xFF00_0001, 0, 0xFFFF_FFFF], None, false); + let mut grey = rustgis_data::raster::read_bytes("output.tif", &tiff).unwrap(); + grey.lost.push(Note::loss(LossCode::ChangedRounded, "values were rounded")); + grey.lost.push(Note::plain("a table was left out")); + let (mut messages, mut losses) = (Vec::new(), Vec::new()); + colours_split(&grey, &tiff, "Sharpened", &mut messages, &mut losses); + assert_eq!(losses, [LossMessage { code: LossCode::ChangedRounded, text: "Sharpened: values were rounded".into() }]); + assert!(messages.iter().any(|m| m == "Sharpened: a table was left out"), "{messages:?}"); + assert!(!messages.iter().any(|m| m.contains("rounded")), "{messages:?}"); +} diff --git a/crates/ui-egui/src/workspacepanes.rs b/crates/ui-egui/src/workspacepanes.rs index d8647a8def..721ac3c47e 100644 --- a/crates/ui-egui/src/workspacepanes.rs +++ b/crates/ui-egui/src/workspacepanes.rs @@ -508,7 +508,7 @@ pub struct SeriesReading { /// A series read on its thread, as `zarr.series` answers it, and what reading it said (a read /// that fails said it too). #[cfg(not(target_arch = "wasm32"))] -pub type SeriesResult = (Result, Vec); +pub type SeriesResult = (Result, Vec); /// Starts reading the series at `at` under the Time Series pane's layer on a thread of its own: a /// wrong request is said at once, and the read lands through [`land_series`]. @@ -566,7 +566,7 @@ pub fn land_series(app: &mut RustGisApp) -> bool { // What reading it said, though it then failed; not for a read that was cancelled. if !cancelled { for n in notes { - app.session.warn(n); + app.session.say_warning(n); } } match res { From 4e8be1dc30e490e1e6559c8eeae5bfab51ff82eb Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 23:19:26 -0600 Subject: [PATCH 2/3] fix(engine): a Zarr series says a system's notes only of the system it reads in, plain as the raster read --- crates/engine/src/cmd/zarr.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 36b8647de6..73c04673d2 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -1728,13 +1728,19 @@ impl SeriesRun { let text = src.crs.as_deref().ok_or("the store doesn't say its coordinate system; give \"crs\" (such as EPSG:3035)")?; // Read as `parse_crs` reads it, its note said with the series'. let crs = Crs::parse(text)?; + // Plain, as the raster read says it (`crs_lost`): it can join a formula chosen for + // compatibility with a shift not applied, so its count isn't one of losses only. if let Some(note) = raster::wkt::typed_crs_note(text, crs) { - notes.push(Note::loss(LossCode::ApproximatedDatum, format!("crs: {note}"))); + notes.push(Note::plain(format!("crs: {note}"))); } crs }; - if let Some((_, Some(note))) = given { - notes.push(Note::loss(LossCode::ApproximatedDatum, format!("{var}: {note}"))); + // Said only of the system the series reads in: a longitude/latitude grid declared in a + // projected system reads in WGS 84, which the note above says. + if let Some((c, Some(note))) = given + && (!lonlat || c.is_geographic()) + { + notes.push(Note::plain(format!("{var}: {note}"))); } let m = crs .transformer()? From 0a3ff2a499883fa743a72c18f12b9ee99f85ab70 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 23:50:24 -0600 Subject: [PATCH 3/3] fix(engine): a GeoLibre run says its inputs' losses as it starts; a clip doesn't repeat its input's --- crates/engine/src/cmd/gp.rs | 10 +++++++++- crates/engine/src/cmd/imagery.rs | 5 ++--- crates/engine/src/tests.rs | 9 +++------ 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index aa3a3e2c3d..d968a558b1 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -395,7 +395,15 @@ pub fn external_start(s: &mut Session, tool: &str, params: &Value) -> Result = [(1.0, 1.0), (9.0, 1.0), (9.0, 9.0), (1.0, 9.0)] .into_iter() @@ -49916,13 +49916,10 @@ fn raster_projection_failures_are_reported_for_zonal_statistics_and_clipping() { let mark = s.notice_mark(); let clip = s.run("raster.process", &json!({"layer": "utm", "operation": "clip", "polygon": "parts", "name": "clipped"})).unwrap(); assert!(clip["messages"].to_string().contains("skipped 1 polygon part(s)"), "{clip}"); - // The same failures are said as notices with their codes, and the raster's own loss is carried on. + // The same failures are said as notices with their codes; the raster's own loss isn't repeated. let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.loss(), n.text.clone())).collect(); assert!(said.iter().any(|(code, t)| *code == Some(LossCode::DroppedGeometry) && t.contains("skipped 1 polygon part(s)")), "{said:?}"); - assert!( - said.iter().any(|(code, t)| *code == Some(LossCode::DroppedValue) && t == "clipped: 3 values past the range were left out"), - "{said:?}" - ); + assert!(!said.iter().any(|(_, t)| t.contains("3 values past the range")), "{said:?}"); // Features with no polygon to clip by are skipped, counted and said as dropped features. let mut mixed = Dataset::new("mixed", GeometryType::Polygon, vec![]); mixed.push(Some(Geometry::Polygon(vec![vec![small.clone()]])), vec![]);