diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 68aad49e0c..e2b5fa040c 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -460,8 +460,9 @@ pub fn resolve_params(spec: &ToolSpec, params: &Value) -> Result /// The keys of `params` that `spec` doesn't read, for an error that a required parameter is /// missing (#2307): a misspelled key is the likely reason, and a failed run's warnings are taken /// back, so the error says it: " (given 'clips', which Clip doesn't read)". Empty when there are -/// none. Bounded as [`quoted_keys`] bounds them. -fn unread(spec: &ToolSpec, params: &Value) -> String { +/// none. Bounded as [`quoted_keys`] bounds them. A caller adding it to an error the tool gave +/// checks for this exact text, so it isn't said twice. +pub fn unread(spec: &ToolSpec, params: &Value) -> String { let Some(given) = params.as_object() else { return String::new() }; let unknown: Vec<&str> = given.keys().map(String::as_str).filter(|k| !is_expected_key(spec, params, k)).collect(); if unknown.is_empty() { diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 8e96cd3803..c4e435be1d 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -143,14 +143,6 @@ impl FgbSource { Self::new(f, Input::Path(path.to_path_buf(), None), name) } - /// Opens a private conversion, keeping its files alive for every shared reader. - #[cfg(not(target_arch = "wasm32"))] - pub fn open_owned_path(path: &Path, name: &str, workspace: Arc) -> Result { - let mut source = Self::open_path(path, name)?; - source._workspace = Some(workspace); - Ok(source) - } - pub fn open_bytes(bytes: Vec, name: &str) -> Result { Self::open_shared(super::Shared(Arc::new(bytes)), name) } diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 547c6e0e67..5bdeb4a18d 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -91,12 +91,6 @@ impl ParquetSource { Ok(source) } - /// Opens a private conversion, keeping its files alive for every shared reader. - #[cfg(not(target_arch = "wasm32"))] - pub fn open_owned_path(path: &Path, name: &str, workspace: Arc) -> Result { - Self::open_converted_path(path, name, None, Some(workspace)) - } - pub fn open_bytes(bytes: Vec, name: &str) -> Result { Self::open_shared(super::Shared(Arc::new(bytes)), name) } diff --git a/crates/data/src/topojson.rs b/crates/data/src/topojson.rs index 91bf98a902..a2bd52fd55 100644 --- a/crates/data/src/topojson.rs +++ b/crates/data/src/topojson.rs @@ -48,6 +48,31 @@ fn position(p: &Json) -> Option { Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, extra]) } +/// Whether a position's third member is there but is neither a number nor null (`"10"`, `true`): +/// the position is read without a height, which [`read`] counts. Null is no height, written on +/// purpose (before a measure, `[x, y, null, m]`). +fn height_unread(p: &Json) -> bool { + p.as_array().and_then(|a| a.get(2)).is_some_and(|z| !z.is_number() && !z.is_null()) +} + +/// The positions of a geometry's points (Point, MultiPoint, and those of a GeometryCollection's +/// members, at most four collections deep) whose height [`height_unread`]. +fn point_heights_unread(g: &Json, depth: usize) -> usize { + let coords = g.get("coordinates"); + let own = match g.get("type").and_then(Json::as_str) { + Some("Point") => coords.map_or(0, |c| usize::from(height_unread(c))), + Some("MultiPoint") => coords.and_then(Json::as_array).map_or(0, |a| a.iter().filter(|p| height_unread(p)).count()), + _ => 0, + }; + let collection = g.get("type").and_then(Json::as_str) == Some("GeometryCollection"); + let nested = if collection && depth < 4 { + g.get("geometries").and_then(Json::as_array).into_iter().flatten().map(|m| point_heights_unread(m, depth + 1)).sum() + } else { + 0 + }; + own.saturating_add(nested) +} + /// "1 geometry" or "2 geometries": `n` and the word for one or for several. fn counted(n: usize, one: &str, several: &str) -> String { if n == 1 { format!("1 {one}") } else { format!("{n} {several}") } @@ -103,6 +128,9 @@ struct Topology { arcs: Vec>>, /// By arc, the positions inside a plain arc that couldn't be read and were left out of it. arcs_lost: Vec, + /// By arc, the positions read without a height their third member gave as something other + /// than a number ([`height_unread`]). + arcs_heights_unread: Vec, transform: Option<([f64; 2], [f64; 2])>, /// Coordinates still allowed to be rebuilt, across all objects. A geometry is checked whole /// and counted ([`Topology::need`]) before any arc is copied, so only geometries kept use it, @@ -331,7 +359,7 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result Result Result positions.len() - p.len(), _ => 0, }); + // Only the positions the arc keeps: one left out is counted as left out, not as read. + arcs_heights_unread.push(if pts.is_some() { + positions.iter().filter(|p| position(p).is_some() && height_unread(p)).count() + } else { + 0 + }); arcs.push(pts); } - let mut topo = Topology { arcs, arcs_lost, transform, budget }; + let mut topo = Topology { arcs, arcs_lost, arcs_heights_unread, transform, budget }; let objects = v.get("objects").and_then(Json::as_object).ok_or_else(|| DataError::Format(format!("{file_name}: no objects")))?; let mut out = Vec::new(); for (name, obj) in objects.iter().take(MAX_OBJECTS) { @@ -392,7 +427,7 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result = members .into_iter() @@ -404,6 +439,7 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result { arcs_used(g, 0, &mut used); + point_heights = point_heights.saturating_add(point_heights_unread(g, 0)); geometry } Err(Unreadable) => { @@ -457,6 +493,13 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result 0 { + rep.messages.push(format!( + "{} with a third member that isn't a number read without a height", + counted(heights, "position", "positions") + )); + } if no_list { rep.messages.push(format!("object {name} is a geometry collection without a list of geometries: nothing in it was read")); } @@ -619,6 +662,32 @@ mod tests { assert_eq!(rep.skipped, 0); } + /// A third member that isn't a number (text, true) is read without a height, counted in one + /// notice per layer, for points and arcs alike; numeric heights, or none, say nothing. + #[test] + 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() + }; + 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]}]}}, +"arcs":[[[0,0,"a"],[1,1,2],[2,2,"b"]]]}"#; + assert_eq!(said(lossy), ["4 positions with a third member that isn't a number read without a height"]); + let clean = r#"{"type":"Topology","objects":{"o":{"type":"GeometryCollection","geometries":[ +{"type":"Point","coordinates":[1,2,10]},{"type":"Point","coordinates":[1,2,null]},{"type":"LineString","arcs":[0]}]}}, +"arcs":[[[0,0,1],[1,1]]]}"#; + assert!(said(clean).is_empty()); + // A position left out of its arc isn't also read without a height; a member of a Point + // (not a collection) isn't read, so isn't counted either. + let left_out = r#"{"type":"Topology","objects":{"o":{"type":"Point","coordinates":[0,0], +"geometries":[{"type":"Point","coordinates":[3,4,"bad"]}]},"p":{"type":"LineString","arcs":[0]}}, +"arcs":[[[0,0],[null,1,"bad"],[2,2]]]}"#; + for (_, rep) in read("h.topojson", left_out).unwrap() { + assert!(!rep.messages.iter().any(|m| m.contains("read without a height")), "{:?}", rep.messages); + } + } + #[test] fn a_plain_position_not_read_is_left_out_of_its_arc_and_said() { // Plain coordinates aren't deltas: the arc keeps its other positions, and the file says diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 514469ff61..5874b529e7 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -52,12 +52,13 @@ url = { workspace = true } # Generated layers for the never-silent round trip (tests/never_silent_roundtrip.rs). proptest = { workspace = true } -# Time slider animations as GIFs (exported by the desktop app only). +# Random field-package identities; in the browser through its JavaScript crypto. [target.'cfg(target_arch = "wasm32")'.dependencies] getrandom = { version = "0.4", features = ["wasm_js"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] getrandom = "0.4" +# Time slider animations as GIFs (exported by the desktop app only). image = { workspace = true, features = ["gif"] } # The live PostGIS tests make their own tables, and change rows as someone else would. diff --git a/crates/engine/src/box_edit.rs b/crates/engine/src/box_edit.rs index 5f50eb9e4f..fd6fcbb598 100644 --- a/crates/engine/src/box_edit.rs +++ b/crates/engine/src/box_edit.rs @@ -265,7 +265,7 @@ pub(crate) fn delete_box(s: &mut Session, p: &Value) -> CmdResult { return Err("the feature changed during this edit".into()); } let layer = s.map_mut().layer_mut(id).ok_or("no layer")?; - let before = layer.dataset.features.remove(row); + let before = layer.dataset.features.remove_row(row).ok_or("no such feature")?; layer.selection = layer.selection.iter().copied().filter(|r| *r != row).map(|r| if r > row { r - 1 } else { r }).collect(); layer.touch_geometry(); crate::cmd::design::apply(s, id, vec![crate::cmd::design::Change { before: Some(before), row: None }])?; diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index e395ba6298..0bbcbdc4f6 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -293,8 +293,9 @@ fn training(s: &Session, p: &Value) -> Result { }; let epochs = epochs as usize; // Without a name given, a new model never replaces one: it gets a name of its own. - let (name, auto) = match ps(p, "model") { - Some(_) => (name(&json!({"name": p.get("model")}), format!("{}_model", r.name))?, None), + // A blank name is none given: it gets a name of its own too. + let (name, auto) = match ps(p, "model").map(str::trim).filter(|m| !m.is_empty()) { + Some(m) => (super::within("model", "a model's name", m, 200)?, None), None => { let base = format!("{}_model", r.name); (free_name(s, &base), Some(base)) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index c6a5cf34b3..80ac2c497e 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -1725,12 +1725,7 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { super::at_most("subtypes", "a field", list, 1000)?; for v in list { let code = v.get("code").and_then(Json::as_i64).ok_or("each subtype has an integer code")?; - let name = super::within( - "a subtype's name", - "a subtype's name", - v.get("name").and_then(Json::as_str).ok_or("each subtype has a name")?, - 200, - )?; + let name = super::within("name", "a subtype's name", v.get("name").and_then(Json::as_str).ok_or("each subtype has a name")?, 200)?; let defaults: Vec<(String, Value)> = v .get("defaults") .and_then(Json::as_object) diff --git a/crates/engine/src/cmd/diagram.rs b/crates/engine/src/cmd/diagram.rs index e596abaa23..09d31f5c8a 100644 --- a/crates/engine/src/cmd/diagram.rs +++ b/crates/engine/src/cmd/diagram.rs @@ -245,8 +245,9 @@ pub(crate) fn hidden_notice(s: &mut Session, id: u32) { } } -/// What [`hidden_notice`] says about `l`, or `None` when its diagram (if any) shows: also given -/// for each such layer a project, map file or layer file opens with. +/// What [`hidden_notice`] says about `l`, or `None` when its diagram (if any) shows. Opening a +/// project, map file or layer file checks only whether this is `Some`, counting such layers by +/// kind in one notice each; this text isn't shown there. pub(crate) fn hidden_text(l: &rustgis_map::Layer) -> Option { l.diagram.as_ref()?; // A name read from a file may be any length. @@ -579,10 +580,7 @@ mod tests { let mark = full.notices.len(); full.run("map.import", &json!({"text": map})).unwrap(); let said: Vec<&str> = full.notices[mark..].iter().map(|n| n.text.as_str()).collect(); - assert!( - said.iter().any(|t| t.contains("1 layout(s) beyond the 200 a project holds removed while checking the project")), - "{said:?}" - ); + assert!(said.iter().any(|t| t.contains("1 layout(s) beyond the 200 a project holds removed while importing the map")), "{said:?}"); // A map import takes the layers' diagrams, so says what reading them changed. let mut damaged_map: serde_json::Value = serde_json::from_str(&map).unwrap(); let layer = damaged_map["layers"].as_array_mut().unwrap().iter_mut().find(|l| l["id"] == json!(id)).unwrap(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 2ca4440d8f..c7ca21046b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -349,7 +349,8 @@ pub(crate) fn validate(g: &Geometry) -> Result<(), String> { /// `v` as a value of a `ty` field. A date-time into a date field is the day it shows. A number goes into a number field as it is, not through the /// text it shows (which rounds a decimal to six places); a decimal, or text written as one, into a /// whole-number field loses its fraction (toward zero); a whole number past 2^53 into a decimal -/// field is the nearest decimal. Not a number is null. Other values go through their text (a +/// field is the nearest decimal. Not a number, and an infinity in a whole-number field, are null. +/// Other values go through their text (a /// decimal into a text field as it's shown, to six places), and what the field can't hold is /// null. A number past the 64-bit range is held at the range's end, as it was; [`coerce_cut`], for /// callers that say what was cut, makes it null instead. @@ -370,8 +371,11 @@ pub(crate) enum Cut { Fraction, /// All of it: a number past the 64-bit range is null. Range, - /// All of it: not a number (NaN) is null. + /// All of it: not a number (NaN), or a word read as one, is null. NotANumber, + /// All of it: an infinity, given as a number or as text ("inf"), is null in a field that + /// holds only finite numbers. + NotFinite, /// A date-time's time of day or zone: a date field keeps its day. Time, } @@ -382,6 +386,7 @@ pub(crate) struct Cuts { fractions: usize, past: usize, not_numbers: usize, + not_finite: usize, times: usize, } @@ -392,6 +397,7 @@ impl Cuts { Cut::Fraction => self.fractions += 1, Cut::Range => self.past += 1, Cut::NotANumber => self.not_numbers += 1, + Cut::NotFinite => self.not_finite += 1, Cut::Time => self.times += 1, } } @@ -420,6 +426,10 @@ impl Cuts { let are = if self.not_numbers == 1 { "isn't a number" } else { "aren't numbers" }; out.push((LossCode::DroppedValue, format!("{by}: '{field}' is null for {} that {are}", results(self.not_numbers)))); } + if self.not_finite > 0 { + let are = if self.not_finite == 1 { "isn't a finite number" } else { "aren't finite numbers" }; + out.push((LossCode::DroppedValue, format!("{by}: '{field}' is null for {} that {are}", results(self.not_finite)))); + } if self.times > 0 { let their = if self.times == 1 { "its" } else { "their" }; out.push((LossCode::DroppedTime, format!("{by}: '{field}' holds dates, so {} kept only {their} day", results(self.times)))); @@ -537,7 +547,7 @@ impl WriteLosses { /// in a whole-number field. pub(crate) fn coerce_cut(v: Value, ty: FieldType) -> (Value, Cut) { if ty == FieldType::Double && non_finite_input(&v, ty) { - return (Value::Null, Cut::NotANumber); + return (Value::Null, if infinite(&v) { Cut::NotFinite } else { Cut::NotANumber }); } let (v, cut, _) = convert(v, ty); (v, cut) @@ -554,11 +564,21 @@ pub(crate) fn non_finite_input(value: &Value, ty: FieldType) -> bool { } } +/// Whether a number, or a number written as text, is an infinity (not NaN). +fn infinite(value: &Value) -> bool { + match value { + Value::Float(f) => f.is_infinite(), + Value::Text(text) => text.trim().parse::().is_ok_and(f64::is_infinite), + _ => false, + } +} + /// [`coerce_cut`], and for a number past the range the decimal it was read as. fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { match (v, ty) { (Value::Null, _) => (Value::Null, Cut::None, None), (Value::Int(i), FieldType::Integer) => (Value::Int(i), Cut::None, None), + (Value::Float(f), FieldType::Integer) if f.is_infinite() => (Value::Null, Cut::NotFinite, None), (Value::Float(f), FieldType::Integer) => whole(f), (Value::Float(f), FieldType::Double) => (Value::Float(f), Cut::None, None), (Value::Int(i), FieldType::Double) => (Value::Float(i as f64), Cut::None, None), @@ -577,6 +597,7 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { // A word the decimal reader takes ("inf", "NaN") isn't a number written as text: // null, and said so, as not a number. (None, Ok(f)) if f.is_finite() || t.bytes().any(|b| b.is_ascii_digit()) => whole(f), + (None, Ok(f)) if f.is_infinite() => (Value::Null, Cut::NotFinite, None), (None, Ok(_)) => (Value::Null, Cut::NotANumber, None), _ => (Value::parse(&t, ty), Cut::None, None), }, @@ -1817,7 +1838,8 @@ mod tests { fn coerce_takes_not_a_number_as_null() { assert_eq!(coerce_cut(Value::Float(f64::NAN), FieldType::Integer), (Value::Null, Cut::NotANumber)); assert_eq!(coerce(Value::Float(f64::NAN), FieldType::Integer), Value::Null); - assert_eq!(coerce_cut(Value::Float(f64::INFINITY), FieldType::Integer), (Value::Null, Cut::Range)); + assert_eq!(coerce_cut(Value::Float(f64::INFINITY), FieldType::Integer), (Value::Null, Cut::NotFinite)); + assert_eq!(coerce(Value::Float(f64::INFINITY), FieldType::Integer), Value::Null); assert_eq!(coerce(Value::Float(-1e30), FieldType::Integer), Value::Int(i64::MIN)); assert_eq!(coerce(Value::Float(0.1 + 0.2), FieldType::Double), Value::Float(0.1 + 0.2)); // Text past the range, whole or decimal: null where it's said, at the range's end elsewhere. @@ -1843,6 +1865,16 @@ mod tests { cuts = Cuts::default(); cuts.add(Cut::NotANumber); assert_eq!(cuts.notices("Rule", "n"), ["Rule: 'n' is null for 1 result that isn't a number"]); + // An infinity is said as not finite, not as not a number; NaN stays not a number. + assert_eq!(coerce_cut(Value::Float(f64::INFINITY), FieldType::Double), (Value::Null, Cut::NotFinite)); + assert_eq!(coerce_cut(text("-inf"), FieldType::Double), (Value::Null, Cut::NotFinite)); + assert_eq!(coerce_cut(text("inf"), FieldType::Integer), (Value::Null, Cut::NotFinite)); + assert_eq!(coerce_cut(Value::Float(f64::NAN), FieldType::Double), (Value::Null, Cut::NotANumber)); + assert_eq!(coerce_cut(text("NaN"), FieldType::Integer), (Value::Null, Cut::NotANumber)); + cuts = Cuts::default(); + cuts.add(Cut::NotFinite); + cuts.add(Cut::NotFinite); + assert_eq!(cuts.notices("Calculate Field", "d"), ["Calculate Field: 'd' is null for 2 results that aren't finite numbers"]); } /// Every form the earlier calculator read gives the same stored values through the diff --git a/crates/engine/src/cmd/effects.rs b/crates/engine/src/cmd/effects.rs index 4d08fa839e..5a83fb75e1 100644 --- a/crates/engine/src/cmd/effects.rs +++ b/crates/engine/src/cmd/effects.rs @@ -107,7 +107,7 @@ pub fn commands() -> Vec { .effects(crate::policy::Effects::NONE) .when(need_polygons) .params( - r#"{"layer"?: name|id | [name|id] (default: the active layer; a list is set alike in one step, or refused whole), "type": "none"|"height"|"field", "field"?: numeric field (metres), "height"?: metres, "factor"?: number}"#, + r#"{"layer"?: name|id | [name|id] (default: the active layer; a list is set alike in one step, or refused whole), "type": "none"|"height"|"field", "field"?: a numeric field's name (its values are metres), "height"?: metres, "factor"?: number}"#, ), C::new("layer.faces", "Faces", "Style › Faces", |s, p| { let (cull, light) = (b(p, "culling"), b(p, "lighting")); @@ -143,7 +143,7 @@ pub fn commands() -> Vec { .roles(&[]) .effects(crate::policy::Effects::NONE) .when(need_polygons) - .params(r#"{"layer"?: name|id | [name|id] (as layer.extrusion), "field"?: numeric field (metres; null or "" clears it), "base"?: metres (0 to 10,000,000)}"#), + .params(r#"{"layer"?: name|id | [name|id] (as layer.extrusion), "field"?: a numeric field's name (its values are metres; null or "" clears it), "base"?: metres (0 to 10,000,000)}"#), ] } @@ -158,12 +158,7 @@ fn display_filters(s: &mut Session, p: &Value) -> CmdResult { rustgis_data::query::parse(w, ds)?; let scale = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0); filters.push(DisplayFilter { - name: super::within( - "a filter's name", - "a display filter's name", - v.get("name").and_then(Value::as_str).unwrap_or("Filter"), - 100, - )?, + name: super::within("name", "a display filter's name", v.get("name").and_then(Value::as_str).unwrap_or("Filter"), 100)?, min_scale: scale("minScale"), max_scale: scale("maxScale"), where_: w.to_string(), diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index d3305aebd2..a7acaaf165 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -135,7 +135,7 @@ fn said(s: &mut Session, wrote: Wrote) -> CmdResult { } for note in notes { if written_path.is_some() { - s.notify_written(note, false); + s.notify_written(note); } else { s.notify(note, false); } @@ -261,7 +261,7 @@ pub(crate) fn drawn( // already reported above retain their screen markers, so this cannot duplicate them. s.notice_landed_pixels(); written?; - s.notify_written(format!("Exported {path}"), false); + s.notify_written(format!("Exported {path}")); Ok(()) }); Ok(Wrote { diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 2a65aa3e5c..750ec1fbb4 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -106,8 +106,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result< progress::check().map_err(|e| e.to_string())?; let mut losses = Vec::new(); let mut archive_errors = Vec::new(); - // These used to be errors as soon as the sender hit them, even if the write later failed. - // Keep a second copy of the text for the recipient's manifest. + // 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. let mut archive_error = |s: &mut Session, text: String| { s.notify(text.clone(), true); archive_errors.push(text); @@ -468,10 +468,9 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result MAX_BATCH_ITEMS { return Err(format!( - "{} inputs is more than a batch runs (at most {MAX_BATCH_ITEMS}); split it into smaller batches", + "{} inputs are more than a batch runs (at most {MAX_BATCH_ITEMS}); split it into smaller batches", targets.len() )); } @@ -2608,19 +2608,13 @@ pub(crate) fn run_step(s: &mut Session, tool: &str, params: &Value) -> CmdResult /// `error` with the keys of `params` that `spec` doesn't read after it — " (given 'unit', which /// Buffer doesn't read)" — unless it says them already (a refused parameter's does). fn saying_unread(spec: &rustgis_analysis::ToolSpec, params: &Value, error: String) -> String { - if error.ends_with("doesn't read)") { + // The same text the tool adds to a refused parameter's error, made once: an error that ends + // in it says it already. + let unread = rustgis_analysis::unread(spec, params); + if unread.is_empty() || error.ends_with(&unread) { return error; } - let unknown: Vec<&str> = params - .as_object() - .into_iter() - .flat_map(|m| m.keys().map(String::as_str)) - .filter(|k| !rustgis_analysis::is_expected_key(spec, params, k)) - .collect(); - if unknown.is_empty() { - return error; - } - format!("{error} (given {}, which {} doesn't read)", rustgis_analysis::quoted_keys(unknown), spec.name) + format!("{error}{unread}") } /// The control a tool run in the session takes: where a person at a terminal can stop it with @@ -2905,7 +2899,7 @@ fn file_delivered(s: &mut Session, p: &Value) -> CmdResult { } for message in &file.record.messages { if file.record.ok { - s.notify_written(message.clone(), false); + s.notify_written(message.clone()); } else { s.notify(message.clone(), true); } @@ -3191,7 +3185,7 @@ fn apply_with( if let Some(code) = code { publish_tool_loss(s, *code, message, wrote_file); } else if wrote_file { - s.notify_written(message.clone(), false); + s.notify_written(message.clone()); } else { s.notify(message.clone(), false); } @@ -4400,7 +4394,7 @@ mod batch_tests { std::fs::write(&txt, "skip me").unwrap(); let mut s = Session::new(crate::Project::default()); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -4413,7 +4407,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["total"], 3); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("1 unsupported files skipped"))); let _ = std::fs::remove_dir_all(root); @@ -4894,7 +4888,7 @@ mod batch_tests { #[test] fn batch_run_lossy_inputs_notified() { let mut s = test_session(); - let mark = s.notices.len(); + let mark = s.notice_mark(); // Lossy input: empty string and non-string in array, plus non-object params let res = s .run( @@ -4909,13 +4903,13 @@ mod batch_tests { assert_eq!(res["total"], 1); assert_eq!(res["succeeded"], 1); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("3 invalid input(s) skipped"))); assert!(notices.iter().any(|n| n.text.contains("'params' must be an object"))); // Clean input says nothing let mut s2 = test_session(); - let mark2 = s2.notices.len(); + let mark2 = s2.notice_mark(); let _ = s2 .run( "gp.batch", @@ -4926,7 +4920,7 @@ mod batch_tests { }), ) .unwrap(); - let notices2 = &s2.notices[mark2..]; + let notices2 = s2.notices_since(mark2); assert!( !notices2.iter().any(|n| n.text.contains("skipped") || n.text.contains("invalid") || n.text.contains("params")), "clean input must give no skip notices: {notices2:?}" @@ -5176,7 +5170,7 @@ mod batch_tests { let ds = Dataset::new("L1", rustgis_data::GeometryType::Point, Vec::new()); s.map_mut().add_layer(rustgis_map::Layer::new(0, ds)); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s.run( "gp.batch", &json!({ @@ -5187,7 +5181,7 @@ mod batch_tests { let err = res.unwrap_err(); assert!(err.contains("Batch 'test:empty_output' failed")); assert!(err.contains("custom message from empty tool")); - assert!(s.notices[mark..].iter().any(|n| n.text.contains("1 failed (L1)"))); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("1 failed (L1)"))); } fn empty_output_multi_message_runner( @@ -5351,7 +5345,7 @@ mod batch_tests { std::fs::write(&f1, sample_geojson).unwrap(); let mut s = Session::new(crate::Project::default()); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5364,7 +5358,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 1); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(!notices.iter().any(|n| n.text.contains("both 'inputs' and 'folder'"))); let _ = std::fs::remove_dir_all(root); @@ -5378,7 +5372,7 @@ mod batch_tests { s.map_mut().add_layer(rustgis_map::Layer::new(10, pre1)); s.map_mut().add_layer(rustgis_map::Layer::new(11, pre2)); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5391,7 +5385,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 1); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("1 output name(s) collided and were renamed"))); } @@ -5525,7 +5519,7 @@ mod batch_tests { ds.push_next(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(10.0, 20.0))), vec![rustgis_data::Value::Int(100)]); s.map_mut().add_layer(rustgis_map::Layer::new(0, ds)); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5538,7 +5532,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 1); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!( !notices.iter().any(|n| n.text.contains("params.output is ignored")), "tool without output param must not emit 'params.output is ignored' notice: {notices:?}" @@ -5583,7 +5577,7 @@ mod batch_tests { #[test] fn batch_run_aggregates_tool_messages() { let mut s = test_session(); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5596,7 +5590,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 2); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("2 item(s) reported messages (Buffer: 1 features at 10 Kilometers (×2))"))); } @@ -5612,7 +5606,7 @@ mod batch_tests { l2.push_next(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(16.0, 26.0))), Vec::new()); s.map_mut().add_layer(rustgis_map::Layer::new(1, l2)); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5625,7 +5619,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 2); - let recent: Vec<_> = s.notices[mark..].iter().filter(|n| n.text.contains("reported messages")).collect(); + let recent: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("reported messages")).collect(); assert_eq!(recent.len(), 1, "must emit exactly one tool messages notice: {recent:?}"); assert_eq!( recent[0].text, @@ -5645,7 +5639,7 @@ mod batch_tests { l2.push_next(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(16.0, 26.0))), Vec::new()); s.map_mut().add_layer(rustgis_map::Layer::new(1, l2)); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5658,7 +5652,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 2); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); let msg_notice = notices.iter().find(|n| n.text.contains("reported messages")).unwrap(); assert!(msg_notice.text.contains("Buffer: 1 features at 10 Kilometers")); assert!(msg_notice.text.contains("Buffer: 2 features at 10 Kilometers")); @@ -5667,7 +5661,7 @@ mod batch_tests { #[test] fn batch_run_null_options_emit_no_spurious_notices() { let mut s = test_session(); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5683,7 +5677,7 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 1); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!( !notices.iter().any(|n| n.text.contains("must be an object") || n.text.contains("both 'inputs' and 'folder'") @@ -5692,7 +5686,7 @@ mod batch_tests { "null options must not emit spurious notices: {notices:?}" ); - let mark2 = s.notices.len(); + let mark2 = s.notice_mark(); let res2 = s .run( "gp.batch", @@ -5709,7 +5703,7 @@ mod batch_tests { .unwrap(); assert_eq!(res2["succeeded"], 1); - let notices2 = &s.notices[mark2..]; + let notices2 = s.notices_since(mark2); assert!( !notices2.iter().any(|n| n.text.contains("output is ignored") || n.text.contains("is replaced by the batch inputs")), "null param fields must not emit spurious notices: {notices2:?}" @@ -5773,7 +5767,7 @@ mod batch_tests { #[test] fn batch_run_unrecognised_option_emits_notice() { let mut s = test_session(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5791,7 +5785,7 @@ mod batch_tests { // Clean call emits no unrecognised option notice let mut s_clean = test_session(); - let mark_clean = s_clean.notices.len() as u64; + let mark_clean = s_clean.notice_mark(); let res_clean = s_clean .run( "gp.batch", @@ -5814,7 +5808,7 @@ mod batch_tests { #[test] fn batch_run_unrecognised_param_in_params_emits_notice() { let mut s = test_session(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -5834,7 +5828,7 @@ mod batch_tests { // Clean call emits no unrecognised notice let mut s_clean = test_session(); - let mark_clean = s_clean.notices.len() as u64; + let mark_clean = s_clean.notice_mark(); let res_clean = s_clean .run( "gp.batch", @@ -5865,12 +5859,12 @@ mod batch_tests { }; let buffer = "Buffer ignores 'unit' (it reads input, distance, units, dissolve, output)"; let mut s = test_session(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 100, "unit": "Miles"}})).unwrap(); assert_eq!(said(&s, mark), [buffer]); // The run is as before: the default units, which its own message names. assert!(s.notices_since(mark).iter().any(|n| n.text.contains("at 100 Kilometers"))); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 100, "units": "Miles"}})).unwrap(); assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); // The name the tool dialog puts beside a table's id (`input_name`) isn't taken for a stray; @@ -5890,7 +5884,7 @@ mod batch_tests { let stray = ignored_params(buffer_spec, &json!({"input": "Cities", "distance": 1, "distance_name": "x"})).unwrap(); assert!(stray.starts_with("Buffer ignores 'distance_name'"), "{stray}"); // Many keys: the first five, sorted, each cut to 40 characters, then how many more. - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let long = "x".repeat(60); let mut params = json!({"input": "Cities", "distance": 1, "a": 1, "b": 1, "c": 1, "d": 1, "e": 1, "f": 1}); params[&long] = json!(1); @@ -5898,11 +5892,11 @@ mod batch_tests { let got = said(&s, mark); assert_eq!(got.len(), 1, "{got:?}"); assert!(got[0].starts_with("Buffer ignores 'a', 'b', 'c', 'd', 'e', 2 more"), "{got:?}"); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 1, &long: 1}})).unwrap(); assert!(said(&s, mark)[0].contains(&format!("'{}…'", "x".repeat(40))), "{:?}", said(&s, mark)); // A control character in a key reaches no terminal as it is. - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 1, "a\n\u{1b}[31mb": 1}})).unwrap(); assert!(said(&s, mark)[0].starts_with("Buffer ignores 'a??[31mb'"), "{:?}", said(&s, mark)); // A run refused for want of a parameter that was misspelled says which key it didn't read, @@ -5925,12 +5919,12 @@ mod batch_tests { assert!(e.contains("(given 'clips', which Clip doesn't read)"), "{e}"); assert_eq!(e.matches("'clips'").count(), 1, "said once: {e}"); // A command that runs a tool for its own parameters says a stray key once, as a command. - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.spatialJoin", &json!({"target": "Cities", "join": "Parks", "prefx": "j_"})).unwrap(); let got = said(&s, mark); assert!(got.len() == 1 && got[0].starts_with("gp.spatialJoin ignores 'prefx'"), "{got:?}"); // It declares every key its tool reads, so those aren't taken for strays. - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let join = json!({"target": "Cities", "join": "Parks", "match": "Within a distance", "distance": 5000, "units": "Miles", "distanceField": "d"}); s.run("gp.spatialJoin", &join).unwrap(); assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); @@ -5945,11 +5939,11 @@ mod batch_tests { let e = s.run("gp.run", &json!({"tool": "zonalStats", "params": {"layer": "Cities", "polygons": "Parks"}})).unwrap_err(); assert!(e.ends_with("'Input Raster' is required (given 'layer', which Zonal Statistics doesn't read)"), "{e}"); // A run started in the background says it too, before its work. - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let _run = tool_start(&mut s, "buffer", &json!({"input": "Cities", "distance": 100, "unit": "Miles"})).unwrap(); assert_eq!(said(&s, mark), [buffer]); // A batch says it once, its own way, not once per item as well. - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.batch", &json!({"tool": "buffer", "inputs": ["Cities"], "params": {"distance": 10, "unit": "Miles"}})).unwrap(); assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); assert!(s.notices_since(mark).iter().any(|n| n.text.contains("unrecognised parameter(s) ignored in 'params' (unit)"))); @@ -5961,7 +5955,7 @@ mod batch_tests { let warnings = v["warnings"].as_array().unwrap(); assert_eq!(warnings.len(), 1, "{v}"); assert_eq!((warnings[0]["code"].as_str(), warnings[0]["message"].as_str()), (Some("unknown-param"), Some(buffer)), "{v}"); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("model.run", &json!({"name": "Typo"})).unwrap(); assert_eq!(said(&s, mark), [buffer]); s.run("model.new", &json!({"name": "Clean", "steps": [{"tool": "buffer", "params": {"input": "Cities", "distance": 100}}]})) @@ -5985,7 +5979,7 @@ mod batch_tests { {"tool": "buffer", "params": {"input": "%1", "distance": 10, "unit": "Miles"}} ]); s.run("model.new", &json!({"name": "Twice", "steps": twice})).unwrap(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("model.run", &json!({"name": "Twice"})).unwrap(); assert_eq!(said(&s, mark), [format!("{buffer} (in 2 steps)")]); // A failing step after an ignoring one: the error carries the warning, and no warning @@ -5995,7 +5989,7 @@ mod batch_tests { {"tool": "buffer", "params": {"distance": 10}} ]); s.run("model.new", &json!({"name": "Stops", "steps": stops})).unwrap(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let e = s.run("model.run", &json!({"name": "Stops"})).unwrap_err(); assert!(e.starts_with("step 2 (buffer)"), "{e}"); assert!(e.ends_with(&format!("; {buffer}")), "{e}"); @@ -6005,7 +5999,7 @@ mod batch_tests { #[test] fn batch_run_params_batch_param_overwritten_notified() { let mut s = test_session(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6025,7 +6019,7 @@ mod batch_tests { // Clean call without batch_param in params gives no replacement notice let mut s_clean = test_session(); - let mark_clean = s_clean.notices.len() as u64; + let mark_clean = s_clean.notice_mark(); let res_clean = s_clean .run( "gp.batch", @@ -6049,7 +6043,7 @@ mod batch_tests { let mut s = test_session(); // Both param and batch_param - let mark1 = s.notices.len() as u64; + let mark1 = s.notice_mark(); let res1 = s .run( "gp.batch", @@ -6071,7 +6065,7 @@ mod batch_tests { // Clean call with only param let mut s_clean1 = test_session(); - let mark_clean1 = s_clean1.notices.len() as u64; + let mark_clean1 = s_clean1.notice_mark(); let res_clean1 = s_clean1 .run( "gp.batch", @@ -6092,7 +6086,7 @@ mod batch_tests { // Both outputPattern and output_pattern let mut s2 = test_session(); - let mark2 = s2.notices.len() as u64; + let mark2 = s2.notice_mark(); let res2 = s2 .run( "gp.batch", @@ -6114,7 +6108,7 @@ mod batch_tests { // Clean call with only outputPattern let mut s_clean2 = test_session(); - let mark_clean2 = s_clean2.notices.len() as u64; + let mark_clean2 = s_clean2.notice_mark(); let res_clean2 = s_clean2 .run( "gp.batch", @@ -6153,7 +6147,7 @@ mod batch_tests { ds_join.push_next(None, vec![rustgis_data::Value::Text("01".into())]); s.project.add_table(ds_join); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6326,7 +6320,7 @@ mod batch_tests { #[test] fn blank_folder_beside_inputs_is_not_reported() { let mut s = test_session(); - let mark = s.notices.len() as u64; + let mark = s.notice_mark(); s.run("gp.batch", &json!({"tool": "buffer", "inputs": ["Cities"], "folder": " ", "params": {"distance": 1}})).unwrap(); assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("both 'inputs' and 'folder'"))); } @@ -6350,7 +6344,7 @@ mod batch_tests { std::fs::write(&f2, r#"{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[1.0,2.0]},"properties":{}}]}"#).unwrap(); let mut s = Session::new(crate::Project::default()); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6367,7 +6361,7 @@ mod batch_tests { let outputs = res["outputs"].as_array().unwrap(); assert_eq!(outputs.len(), 1); assert_eq!(outputs[0].as_str().unwrap(), "sample_buffer"); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(!notices.iter().any(|n| n.text.contains("collided and were renamed"))); let _ = std::fs::remove_dir_all(root); @@ -6384,7 +6378,7 @@ mod batch_tests { write_test_shapefile(&root.join("test.shp")); let mut s = Session::new(crate::Project::default()); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6396,7 +6390,7 @@ mod batch_tests { ) .unwrap(); assert_eq!(res["total"], 1); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!( !notices.iter().any(|n| n.text.contains("unsupported files skipped")), "shapefile companion files must not be reported as unsupported: {notices:?}" @@ -6404,7 +6398,7 @@ mod batch_tests { std::fs::write(root.join("notes.txt"), b"some notes").unwrap(); let mut s2 = Session::new(crate::Project::default()); - let mark2 = s2.notices.len(); + let mark2 = s2.notice_mark(); let res2 = s2 .run( "gp.batch", @@ -6416,7 +6410,7 @@ mod batch_tests { ) .unwrap(); assert_eq!(res2["total"], 1); - let notices2 = &s2.notices[mark2..]; + let notices2 = s2.notices_since(mark2); assert!( notices2.iter().any(|n| n.text.contains("1 unsupported files skipped")), "exactly 1 unsupported file (notes.txt) should be reported: {notices2:?}" @@ -6467,7 +6461,7 @@ mod batch_tests { let mut s = test_session(); s.map_mut().add_raster("Elevation", rustgis_map::RasterLayer::from_path(raster, "test.tif")); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6480,11 +6474,11 @@ mod batch_tests { .unwrap(); assert_eq!(res["succeeded"], 2); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("1 raster layer(s) left out of '*' (it runs vector layers)"))); let mut s2 = test_session(); - let mark2 = s2.notices.len(); + let mark2 = s2.notice_mark(); let _ = s2 .run( "gp.batch", @@ -6495,7 +6489,7 @@ mod batch_tests { }), ) .unwrap(); - let notices2 = &s2.notices[mark2..]; + let notices2 = s2.notices_since(mark2); assert!(!notices2.iter().any(|n| n.text.contains("raster layer(s)"))); } @@ -6651,7 +6645,7 @@ mod batch_tests { let mut s = Session::new(crate::Project::default()); let padded = format!(" {} ", f1.display()); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6666,7 +6660,7 @@ mod batch_tests { assert_eq!(res["succeeded"], 1); let outputs = res["outputs"].as_array().unwrap(); assert_eq!(outputs[0], "cities_buffer"); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("1 file path(s) trimmed of surrounding whitespace"))); let _ = std::fs::remove_dir_all(root); @@ -6803,7 +6797,7 @@ mod batch_tests { .collect(); let mut s = Session::new(crate::Project::default()); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -6827,7 +6821,7 @@ mod batch_tests { } // Notices aggregated into a single notice per warning kind without truncating later files - let notice = s.notices[mark..].iter().find(|n| n.text.contains("Z or M")).unwrap(); + let notice = s.notices_since(mark).iter().find(|n| n.text.contains("Z or M")).unwrap(); assert!(notice.text.starts_with("gp.batch: 4 inputs (")); assert!(notice.text.contains("file_1.geojson")); assert!(notice.text.contains("file_2.geojson")); @@ -7009,7 +7003,7 @@ mod batch_tests { notes_layer.graphics = true; s.map_mut().add_layer(notes_layer); - let mark = s.notices.len(); + let mark = s.notice_mark(); let res = s .run( "gp.batch", @@ -7025,7 +7019,7 @@ mod batch_tests { let outputs = res["outputs"].as_array().unwrap(); assert_eq!(outputs.len(), 1); assert_eq!(outputs[0], "Rivers_buffer"); - let notices = &s.notices[mark..]; + let notices = s.notices_since(mark); assert!(notices.iter().any(|n| n.text.contains("1 graphics layer(s) left out of '*'"))); let mut s_empty = Session::new(crate::Project::default()); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 71aa948f85..d422a70da0 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1717,19 +1717,32 @@ fn edge_pixels(r: &Raster, e: &Extent) -> Option> { }) } -/// The columns and rows of a raster under a longitude/latitude box, or `None` when it misses -/// (or can't be placed on it, [`edge_pixels`]). -fn pixel_window(r: &Raster, e: &Extent) -> Option<(std::ops::Range, std::ops::Range)> { +/// What [`pixel_window`] says of a polygon whose box misses the raster. +const OUTSIDE_THE_RASTER: &str = "the polygon is outside the raster"; + +/// The columns and rows of a raster under a longitude/latitude box; an error when it misses, or +/// when the raster's coordinate system can't place the box's edge on it ([`edge_pixels`]). +fn pixel_window(r: &Raster, e: &Extent) -> Result<(std::ops::Range, std::ops::Range), String> { + let pixels = edge_pixels(r, e).ok_or_else(|| { + let b = r.extent(); + let misses = e.max_x < b.min_x || e.min_x > b.max_x || e.max_y < b.min_y || e.min_y > b.max_y; + if misses { + OUTSIDE_THE_RASTER.to_string() + } else { + format!("{}'s coordinate system can't place the polygon's edge on the raster", r.name) + } + })?; let (mut c0, mut r0, mut c1, mut r1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for (c, rr) in edge_pixels(r, e)? { + for (c, rr) in pixels { (c0, r0, c1, r1) = (c0.min(c), r0.min(rr), c1.max(c), r1.max(rr)); } if c0 > c1 || c1 < 0.0 || r1 < 0.0 || c0 > f64::from(r.width) || r0 > f64::from(r.height) { - return None; + return Err(OUTSIDE_THE_RASTER.into()); } - let cols = (c0.floor().max(0.0) as u32).min(r.width)..(c1.ceil().max(0.0) as u32 + 1).min(r.width); - let rows = (r0.floor().max(0.0) as u32).min(r.height)..(r1.ceil().max(0.0) as u32 + 1).min(r.height); - Some((cols, rows)) + // A far edge past u32's range saturates there; the step past it mustn't overflow. + let cols = (c0.floor().max(0.0) as u32).min(r.width)..(c1.ceil().max(0.0) as u32).saturating_add(1).min(r.width); + let rows = (r0.floor().max(0.0) as u32).min(r.height)..(r1.ceil().max(0.0) as u32).saturating_add(1).min(r.height); + Ok((cols, rows)) } fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { @@ -1766,7 +1779,7 @@ fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { let mut bands = copied(&r)?; let mut n = 0usize; // Only the pixels under the polygon's box are visited. - let (cols, rows) = pixel_window(&r, &e).ok_or("the polygon is outside the raster")?; + let (cols, rows) = pixel_window(&r, &e)?; let tr = r.transformer(); for row in rows { for col in cols.clone() { @@ -1926,7 +1939,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { let mut cells = Vec::new(); let mut e = Extent::EMPTY; pts.iter().for_each(|c| e.expand(*c)); - let (cols, rows) = pixel_window(d, &e).ok_or("the polygon is outside the raster")?; + let (cols, rows) = pixel_window(d, &e)?; let tr = d.transformer(); for row in rows.map(i64::from) { for col in cols.clone().map(i64::from) { @@ -2489,3 +2502,23 @@ fn robinson_pixel_window_keeps_the_equatorial_edges() { assert!(f64::from(rows.start) <= row && f64::from(rows.end) >= row); } } + +/// A polygon off the raster is said to be outside it; one its coordinate system can't place (on +/// the equator past 90° from a UTM zone's meridian) is said to be that, not outside the raster. +#[test] +fn pixel_window_tells_a_miss_from_a_place_it_cant_take() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform}; + let transform = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; + let r = Raster::new("small", 100, 100, vec![vec![1.0; 10_000]], transform, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + assert_eq!(pixel_window(&r, &Extent::new(50.0, 50.0, 51.0, 51.0)).unwrap_err(), OUTSIDE_THE_RASTER); + // A box reaching billions of pixels past the raster is the raster's part, without overflow. + let tiny = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1e-8, pixel_height: -1e-8 }; + let r2 = Raster::new("tiny", 100, 100, vec![vec![1.0; 10_000]], tiny, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + assert_eq!(pixel_window(&r2, &Extent::new(0.0, -80.0, 170.0, 1.0)).unwrap(), (0..100, 0..100)); + // UTM zone 17 refuses places on the equator more than 90° from its meridian (#1925). + let crs = Crs::from_epsg(32617).unwrap(); + let transform = GeoTransform { origin_x: -9_000_000.0, origin_y: 9_000_000.0, pixel_width: 100_000.0, pixel_height: -100_000.0 }; + let r = Raster::new("zone", 180, 180, vec![vec![1.0; 32_400]], transform, crs, None, ColorHint::Gray, "Float32").unwrap(); + let e = pixel_window(&r, &Extent::new(-170.0, -10.0, 10.0, 10.0)).unwrap_err(); + assert!(e.contains("coordinate system can't place the polygon's edge"), "{e}"); +} diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 189f7b3b27..3979117a93 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -312,7 +312,9 @@ pub fn commands() -> Vec { } let kept = name.chars().count() - if i > 1 { format!(" {i}").chars().count() } else { 0 }; if kept < base.chars().count() { - s.notify(format!("New Task: a task has that name already, so the name given is cut to {kept} characters to fit \" {i}\""), false); + // `task.import` adds its task through this command, and is named as itself. + let title = if b(p, "imported").unwrap_or(false) { "Import Task" } else { "New Task" }; + s.notify(format!("{title}: a task has that name already, so the name given is cut to {kept} characters to fit \" {i}\""), false); } s.project.tasks.push(Task { name: name.clone(), description, steps }); Ok(json!({"task": name})) @@ -324,8 +326,8 @@ pub fn commands() -> Vec { return Err(format!("'{}' can't be a task step", step.command)); } let t = task_mut(s, p)?; - if t.steps.len() >= 200 { - return Err("a task has at most 200 steps".into()); + if t.steps.len() >= MAX_TASK_STEPS { + return Err(format!("a task has at most {MAX_TASK_STEPS} steps")); } t.steps.push(step); Ok(json!({"steps": t.steps.len()})) @@ -580,7 +582,8 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { } // Repair what was read (rasters reopen, cameras clamp); the sources that read S3 wait for // the saved connection that is to read them. - for notice in s.project.normalize_text() { + let when = if s.project.maps.len().saturating_sub(first_map) == 1 { "while importing the map" } else { "while importing the maps" }; + for notice in s.project.normalize_after(when) { s.notify_text(notice, false); } super::connections::restore_active(s); @@ -1135,7 +1138,7 @@ fn export_3d(s: &mut Session, p: &Value) -> CmdResult { s.notify(note, false); } s.retain_written_notices(written); - s.notify_written(format!("Exported {path}"), false); + s.notify_written(format!("Exported {path}")); return Ok(json!({ "path": path, "bytes": bytes.len(), "triangles": report.triangles, "skippedDegenerate": report.degenerate, "linesDropped": report.lines, "capsFanned": report.fanned, @@ -1147,7 +1150,7 @@ fn export_3d(s: &mut Session, p: &Value) -> CmdResult { s.notify(note, false); } s.retain_written_notices(written); - s.notify_written(format!("Exported {path}"), false); + s.notify_written(format!("Exported {path}")); Ok(json!({"path": path, "bytes": obj.len()})) } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3f39ae7c58..0a85cd2782 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -810,6 +810,8 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { // The mapping's own where it is of the same field, else the field's range. let had = l.size_by.as_ref().filter(|h| l.dataset.field_index(&h.field) == Some(fi)); let (min, max) = (min.or(had.map(|h| h.min)), max.or(had.map(|h| h.max))); + // Both bounds from the field's own range: a field with one value has no spread to scale over. + let both_from_range = min.is_none() && max.is_none(); let range = if min.is_none() || max.is_none() { // A streamed layer holds the view's features only, so their range would be the view's. if l.is_streamed() { @@ -832,6 +834,9 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { }; let min = min.or(range.map(|r| r.0)).ok_or_else(|| format!("'{field}' has no numeric values: give min and max"))?; let max = max.or(range.map(|r| r.1)).ok_or_else(|| format!("'{field}' has no numeric values: give min and max"))?; + if max <= min && both_from_range { + return Err(format!("'{field}' has the same value ({min}) in every row, so give min and max")); + } if max <= min { return Err(format!("max ({max}) must be above min ({min})")); } @@ -3250,7 +3255,7 @@ fn add_source_read( .into_iter() .map(|(kind, count)| { if kind == "attributes" { - format!("{count} attribute-only tables not added: GeoPackage attribute tables are not supported") + format!("{count} attribute-only table(s) not added: GeoPackage attribute tables are not supported") } else if kind == "features" { format!("{count} feature table(s) not added: no geometry column is registered") } else { @@ -4690,7 +4695,16 @@ fn read_delimited( /// which may be a sidecar of the requested file. fn whole_read_error(path: &str, error: rustgis_data::DataError) -> String { let message = error.to_string(); - if rustgis_data::io::file_size_error_args(&message).is_some() { message } else { format!("{path}: {message}") } + if rustgis_data::io::file_size_error_args(&message).is_some() || message.starts_with(&format!("{path}:")) { + return message; + } + // A reader that names the file by its name alone (the delimited and gzip readers) is named + // once, by the path given. + let file = Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path); + match message.strip_prefix(file).filter(|rest| rest.starts_with(':')) { + Some(rest) => format!("{path}{rest}"), + None => format!("{path}: {message}"), + } } /// Reads local/uploaded delimited bytes with the same options and CRS notices on every path. @@ -5609,7 +5623,11 @@ pub(crate) fn cog_tile_where(t: &rustgis_map::tiles::TileLayer, address: &str) - Some((_, rest)) => rest.split_once('/').map_or("", |(_, path)| path), None => address, }; - let file: String = path.rsplit(['/', '\\']).next().unwrap_or_default().chars().take(80).collect(); + let whole = path.rsplit(['/', '\\']).next().unwrap_or_default(); + let mut file: String = whole.chars().take(80).collect(); + if whole.chars().nth(80).is_some() { + file.push('…'); + } if file.is_empty() { t.name.clone() } else { format!("{} ({file})", t.name) } } @@ -6937,8 +6955,9 @@ fn square_labels_follow_removal(s: &mut Session, names: &[String]) { } if !squared.is_empty() { let (count, names) = (squared.len(), squared.join(", ")); + let layers = if count == 1 { "line layer" } else { "line layers" }; s.notify( - format!("Labels: {count} perpendicular labels' line layer(s) {names} removed, so their labels are placed as auto until a layer of that name comes back"), + format!("Labels: {count} perpendicular labels' {layers} {names} removed, so their labels are placed as auto until a layer of that name comes back"), false, ); } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index de240c9114..af7c62d0c1 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -6129,9 +6129,6 @@ pub(crate) fn import(s: &mut Session, text: &str) -> CmdResult { ); } let name = l.name.clone(); - if s.project.layouts.len() >= crate::project::MAX_LAYOUTS { - return Err(format!("a project holds at most {} layouts; remove one first", crate::project::MAX_LAYOUTS)); - } s.project.layouts.push(l); let i = s.project.layouts.len() - 1; s.active_layout = Some(i); diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index e10af903c0..8aa650cca7 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -1108,8 +1108,8 @@ pub fn new_bookmark_name(map: &Map) -> String { pub(crate) const MAX_BOOKMARK_NAME: usize = 120; const MAX_DESCRIPTION: usize = 2_000; -/// Most bookmarks a map keeps. -pub(crate) const MAX_BOOKMARKS: usize = 10_000; +/// Most bookmarks a map keeps: as many as a QGIS project import reads. +pub(crate) use rustgis_map::qgis::MAX_BOOKMARKS; /// The map's bookmarks as a bookmarks file. Places are lon/lat and metres per pixel, so they /// open in the same place on a map in any projection. diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 1dd5ea35b6..9e92d0ed2a 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -452,7 +452,7 @@ fn layers_of(s: &Session) -> Value { "id": l.id, "name": l.name, "raster": l.is_raster(), "visible": l.visible, "geometry": format!("{:?}", l.dataset.geometry_type), "features": l.dataset.features.len(), "selected": l.selection.len(), "active": Some(l.id) == active, - "extent": super::project::bbox(l.extent()), "transparency": l.transparency, + "extent": super::project::bbox(l.extent()), "transparency": super::project::percent(l.transparency), "crs": layer_crs(l).map(crs_name), "group": s.map().group_of(l.id).map(|g| g.name.as_str()), "fields": l.dataset.fields.iter().map(|f| json!({"name": f.name, "type": format!("{:?}", f.ty)})).collect::>(), @@ -497,13 +497,13 @@ fn map_crs(m: &rustgis_map::Map) -> Result { .and_then(|n| n.parse::().ok()) .or_else(|| rustgis_data::raster::crs::vn2000_epsg(&label).map(u32::from)) .and_then(Crs::from_epsg); - epsg.ok_or_else(|| format!("{label} has no EPSG code, so GeoJSON can't name it; use an EPSG code")) + epsg.ok_or_else(|| format!("{label} isn't a coordinate system RustGIS can name in GeoJSON; use an EPSG code")) } } } /// The system `host.features` was asked for with `crs`: `None` for WGS 84 (absent, or named so), -/// `"layer"` the layer's own, `"map"` the map's, else an EPSG code (`"EPSG:32637"` or `32637`). +/// `"layer"` the layer's own, `"map"` the map's, else an EPSG code (`"EPSG:32637"` or `"32637"`). /// Never WKT or a PROJ string: reading one registers a system in the process-wide table, which /// any plugin (the request needs no permission) could fill, and the answer names an EPSG code /// anyway. Every refusal starts with `crs:`. @@ -605,7 +605,7 @@ impl Bridge<'_> { } // Its geometry is longitude/latitude (above); `crs` stays the layer's, as the system it // was read in, which `export_error` reads. - let ds = rustgis_data::Dataset { + let mut ds = rustgis_data::Dataset { name: l.name.clone(), geometry_type: l.dataset.geometry_type, fields: l.dataset.fields.clone(), @@ -618,12 +618,11 @@ impl Bridge<'_> { held_in: rustgis_data::raster::Crs::LonLat, shown_in: None, }; - let mut ds = ds; let mut member = None; if let Some(crs) = target { // Only a system `host.addLayer` can read back is named, so a round trip works. if crs.epsg() == 0 { - return Err(format!("crs: {} has no EPSG code, so GeoJSON can't name it; use an EPSG code", crs.label())); + return Err(format!("crs: {} isn't a coordinate system RustGIS can name in GeoJSON; use an EPSG code", crs.label())); } if crs.is_geocentric() { return Err(format!( diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 949d9efdf2..c4ae5269a4 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -123,7 +123,7 @@ fn export_log(s: &mut Session, p: &Value) -> CmdResult { rustgis_data::io::write_atomic_with(&path, |w| s.log.write(w, format == "csv")).map_err(|e| format!("{}: {e}", path.display()))?; // Entries dropped past the log's limits aren't in the file: said. let dropped = s.log.dropped_said().map(|d| format!("; not in it: {d}")).unwrap_or_default(); - s.notify_written(format!("Exported the session log ({n} entries) to {}{dropped}", path.display()), false); + s.notify_written(format!("Exported the session log ({n} entries) to {}{dropped}", path.display())); Ok(json!({"path": path.display().to_string(), "entries": n, "format": format})) } @@ -762,6 +762,9 @@ fn write(s: &mut Session, path: PathBuf) -> CmdResult { let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); return Err(if ext == crate::project::PACKAGE_EXTENSION { "a project saves to a .rgis file; Package Project (project.package) writes a .rgispkg package".into() + } else if ext.is_empty() || ext == crate::project::EXTENSION { + // `foo.` and `a.rgis.` end in a bare dot; `atlas.rgis/` names a folder. + "a project saves to a .rgis file".into() } else { format!("a project saves to a .rgis file, not a .{ext} one") }); @@ -772,7 +775,7 @@ fn write(s: &mut Session, path: PathBuf) -> CmdResult { s.mark_saved(); s.edit_counts.clear(); let written = s.notice_mark(); - s.notify_written(format!("Saved {}", path.display()), false); + s.notify_written(format!("Saved {}", path.display())); crate::durable::notify(s, &report); for note in construction_notes { s.notify(note, false); @@ -854,6 +857,14 @@ fn parse_tool(p: &Value) -> Result { Tool::from_code(name).ok_or_else(|| format!("unknown tool '{name}'")) } +/// A transparency (or any `f32` setting) for JSON, rounded to 4 decimals: widened as it is, 33.3 +/// would read 33.299999237060547 to the Assistant and plugins. +pub(crate) fn percent(v: f32) -> Value { + let wide = f64::from(v); + let rounded = (wide * 10_000.0).round() / 10_000.0; + json!(if rounded.is_finite() { rounded } else { wide }) +} + /// A longitude/latitude extent as `[west, south, east, north]`, or null when there is none. pub(crate) fn bbox(e: rustgis_geom::Extent) -> Value { // Rounded outwards, so the bounds still hold every coordinate. @@ -910,7 +921,7 @@ fn info(s: &mut Session, p: &Value) -> CmdResult { }; if let Some(o) = v.as_object_mut() { o.insert("group".into(), json!(m.group_of(l.id).map(|g| g.name.as_str()))); - o.insert("transparency".into(), json!(l.transparency)); + o.insert("transparency".into(), json!(percent(l.transparency))); o.insert("source".into(), json!(source(l))); o.insert("extent".into(), bbox(l.extent())); if !fields { @@ -955,7 +966,7 @@ fn info(s: &mut Session, p: &Value) -> CmdResult { "activeLayer": active, "layers": layers, "groups": m.groups.iter().map(|g| json!({ - "id": g.id, "name": g.name, "visible": g.visible, "transparency": g.transparency, + "id": g.id, "name": g.name, "visible": g.visible, "transparency": percent(g.transparency), "minScale": g.min_scale, "maxScale": g.max_scale, "layers": g.children, "parent": g.parent, })).collect::>(), // Web tile layers (XYZ, WMS, vector tiles, styles, archives), each drawn over the map layer diff --git a/crates/engine/src/cmd/publish.rs b/crates/engine/src/cmd/publish.rs index 9760eaba96..92041cc332 100644 --- a/crates/engine/src/cmd/publish.rs +++ b/crates/engine/src/cmd/publish.rs @@ -139,7 +139,7 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result s.warn(format!("{said} was written, but {name} changed while it was: add the file again to compare them")), } - s.notify_written(format!("Published {name} to {said}"), false); + s.notify_written(format!("Published {name} to {said}")); s.retain_written_notices(mark); Ok(()) }); @@ -253,9 +253,14 @@ fn sync_state(s: &mut Session, p: &Value) -> CmdResult { /// Whether `path` names a file on this computer a record is made for: a Shapefile or `.geojson` /// file, not an address, a database or a network share (`\\host\share`, `//host/share`, /// `/\host\share`, `\\?\UNC\host\share`). Windows' long form of a local path (`\\?\C:\…`) is one -/// on this computer. The desktop's Layers pane marks the same layers this publishes. +/// on this computer. A `file://` address isn't one: the record's file is opened by the path as +/// written, so the path checked here is the one opened. The desktop's Layers pane marks the same +/// layers this publishes. pub fn local_file(path: &str) -> bool { - let b = rustgis_map::paths::local_path(path).as_bytes(); + if rustgis_map::paths::local_path(path) != path { + return false; + } + let b = path.as_bytes(); let sep = |i: usize| b.get(i).is_some_and(|c| matches!(c, b'/' | b'\\')); // Windows takes any two leading separators, of either kind, for a network share, unless they // begin the long form of a path on a drive. diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 5a2141144e..99c622578c 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -4,7 +4,7 @@ //! (`rustgis_map::qgis::Report`). use rustgis_geom::{Coord, Extent}; -use rustgis_map::qgis::{self, NoteKind, Report, Source}; +use rustgis_map::qgis::{self, NoteKind, Report, Source, listed}; use serde_json::{Value, json}; use super::{need_layer, ps}; @@ -85,18 +85,18 @@ fn marker_images() -> impl FnMut(&str) -> Result<(String, f32), &'static str> { /// 20,000 pixels a side within 512 MiB, as `layer.marker` does. fn marker_image(source: &str, read: &mut usize) -> Result<(String, f32), &'static str> { use base64::Engine; - use rustgis_map::symbology::MAX_PICTURE_BYTES; + use rustgis_map::symbology::MAX_PICTURE_BYTES as MARKER_PICTURE_BYTES; const TOO_LARGE: &str = "whose image is past 2 MiB of base64"; const NOT_AN_IMAGE: &str = "whose image isn't a PNG or JPEG RustGIS reads"; let b64 = match source.strip_prefix("base64:") { // Past the limit, refused before it is copied, and charged as a file past it is. - Some(b64) if b64.trim().len() > MAX_PICTURE_BYTES => { - *read += MAX_PICTURE_BYTES; + Some(b64) if b64.trim().len() > MARKER_PICTURE_BYTES => { + *read += MARKER_PICTURE_BYTES; return Err(TOO_LARGE); } Some(b64) => b64.trim().to_string(), // Base64 is 4 characters for 3 bytes. - None => match super::graphics::read_picture_file(source, MAX_PICTURE_BYTES / 4 * 3) { + None => match super::graphics::read_picture_file(source, MARKER_PICTURE_BYTES / 4 * 3) { Ok(bytes) if bytes.is_empty() => return Err(NOT_AN_IMAGE), Ok(bytes) => base64::engine::general_purpose::STANDARD.encode(bytes), Err(e) => { @@ -116,7 +116,7 @@ fn marker_image(source: &str, read: &mut usize) -> Result<(String, f32), &'stati if b64.is_empty() { return Err("with no image"); } - if b64.len() > MAX_PICTURE_BYTES { + if b64.len() > MARKER_PICTURE_BYTES { return Err(TOO_LARGE); } // As `layer.marker` checks one: one kept already decodes into the drawing's cache. @@ -1689,13 +1689,6 @@ fn add_relations(s: &mut Session, project: &qgis::Project, came_in: &[CameIn], r destination_key, }); } - let listed = |names: &[&str]| { - let mut text = names.iter().take(8).copied().collect::>().join(", "); - if names.len() > 8 { - text.push_str(", …"); - } - format!("{}: {text}", names.len()) - }; if !missing.is_empty() { report.skipped("", format!("its relations between layers that didn't come in or haven't the fields ({})", listed(&missing))); } @@ -1864,13 +1857,6 @@ fn add_bookmarks(s: &mut Session, project: &qgis::Project, report: &mut Report) m.bookmarks.push(rustgis_map::Bookmark::new(name, m.camera)); } m.camera = view; - let listed = |names: &[&str]| { - let mut text = names.iter().take(8).copied().collect::>().join(", "); - if names.len() > 8 { - text.push_str(", …"); - } - format!("{}: {text}", names.len()) - }; if !none.is_empty() { report.skipped("", format!("its bookmarks with no coordinate system, in a project without one ({})", listed(&none))); } diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index e9b945051e..da45449c83 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1194,7 +1194,7 @@ pub(super) fn write_and_report(s: &mut Session, r: &Raster, bi: usize, cog: bool let wrote = write_geotiff_with_guidance(r, bi, cog, path, "export the resulting layer with share.exportRaster and give \"band\" for another")?; for note in wrote.notes { - s.notify_written(note, false); + s.notify_written(note); } Ok(wrote.answer) } diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 35bef65a9f..0a457aca58 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -288,7 +288,7 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu "edit.previewShapeConversion" => ("Preview Shape Conversion", crate::shape_conversion::ahead(s, params), None), "table.statistics" => ("Column Statistics", super::table_stats::stats_ahead(s, params), None), "layer.sizeBy" => ("Size by Field", super::layer::size_by_ahead(s, params), None), - _ => return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service listings, topology, Source File State, Column Statistics and Size by Field prepare background work".into()), + _ => return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service listings, topology, Source File State, Read Original Image Grid, Preview Shape Conversion, Column Statistics and Size by Field prepare background work".into()), }; let name = work.as_ref().map_or(name, |work| work.name); let table = super::edit::table_edit_in_background(spec.id) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 84fc34d5b9..37e98af4be 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -715,28 +715,44 @@ fn advertised_template_with( withheld: &mut u32, mut read: impl FnMut(&str) -> Result, String>, ) -> AdvertisedTemplate { + let read = |doc: &str| Ok::<_, std::convert::Infallible>(read(doc).map_err(|e| crate::sources::message_with_address(doc, &e))); + match walk_template(source, list, vector, withheld, read) { + Ok(out) => out, + Err(never) => match never {}, + } +} + +/// The walk [`advertised_template_with`] and [`left_template`] share: at most two documents from +/// `list`, each read by `read` (its body, or why it couldn't be read; `Err` stops the walk), keeping +/// every foreign hop and counting the addresses whose query was withheld. A fallback to the +/// standard tile address comes back as the notice to give, in `fallback`. +fn walk_template, E>( + source: &str, + list: &str, + vector: bool, + withheld: &mut u32, + mut read: impl FnMut(&str) -> Result, E>, +) -> Result { use rustgis_data::ogc::{TilesStep, resolve_tiles}; let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None }; let mut doc = list.to_string(); - // Each fallback is said, as [`left_template`] says it. for _ in 0..2 { let shown = crate::sources::address_in_message(&doc); if let Err(e) = crate::render::rustgis_tiles::address::check(&doc, Some(list)) { let e = crate::sources::message_with_address(&doc, &e); out.fallback = Some(format!("{shown}: this tile set document was refused, so the standard tile address is used: {e}")); - return out; + return Ok(out); } - let body = match read(&doc) { + let body = match read(&doc)? { Ok(body) => body, Err(e) => { - let e = crate::sources::message_with_address(&doc, &e); out.fallback = Some(format!("{shown}: its tile sets couldn't be read, so the standard tile address is used: {e}")); - return out; + return Ok(out); } }; - let Some(resolved) = resolve_tiles(list, &doc, &body, vector) else { + let Some(resolved) = resolve_tiles(list, &doc, body.as_ref(), vector) else { out.fallback = Some(format!("{shown}: it names no tiles of this layer, so the standard tile address is used")); - return out; + return Ok(out); }; *withheld = withheld.saturating_add(resolved.withheld_addresses); match resolved.step { @@ -750,7 +766,7 @@ fn advertised_template_with( out.fallback = Some(format!("{shown}: its tile template was refused, so the standard tile address is used: {e}")); } } - return out; + return Ok(out); } TilesStep::Next(next) => { out.crossed_origin |= crosses_origin(&doc, &next); @@ -763,7 +779,7 @@ fn advertised_template_with( "{}: its tile sets lead on past two documents, so the standard tile address is used", crate::sources::address_in_message(list) )); - out + Ok(out) } /// What [`left_template`] has: the template, or the document it waits for. @@ -772,62 +788,34 @@ enum LeftTemplate { Waiting(String), } +/// Why [`left_template`]'s walk stopped before it had a template or a fallback. +enum LeftStop { + /// The document it waits for. + Waiting(String), + /// The command fails. + Failed(String), +} + /// [`advertised_template`] read off the frame. It keeps every foreign hop and counts the addresses /// whose query was withheld, as that does. A document that can't be asked for now (too many being /// read) fails the command, as it does for the capabilities: it wasn't read, so it doesn't fall /// back to the standard tile address. Every fallback to that address is said. fn left_template(s: &mut Session, source: &str, list: &str, vector: bool, withheld: &mut u32) -> Result { - use rustgis_data::ogc::{TilesStep, resolve_tiles}; - let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None }; - let mut doc = list.to_string(); - for _ in 0..2 { - let shown = crate::sources::address_in_message(&doc); - if let Err(e) = crate::render::rustgis_tiles::address::check(&doc, Some(list)) { - let e = crate::sources::message_with_address(&doc, &e); - s.notify(format!("{shown}: this tile set document was refused, so the standard tile address is used: {e}"), false); - return Ok(LeftTemplate::Read(out)); - } - let Some(read) = s.left_document(&doc)? else { return Ok(LeftTemplate::Waiting(doc)) }; - let body = match read { - Ok(body) => body, - Err(e) => { - s.notify(format!("{shown}: its tile sets couldn't be read, so the standard tile address is used: {e}"), false); - return Ok(LeftTemplate::Read(out)); - } - }; - let Some(resolved) = resolve_tiles(list, &doc, &body, vector) else { - s.notify(format!("{shown}: it names no tiles of this layer, so the standard tile address is used"), false); - return Ok(LeftTemplate::Read(out)); - }; - *withheld = withheld.saturating_add(resolved.withheld_addresses); - match resolved.step { - TilesStep::Template(t) => { - out.crossed_origin |= crosses_origin(&doc, &t); - match checked_template(list, &t) { - Ok(t) => out.template = Some(t), - // (Its error names the template, which may carry keys.) - Err(e) => { - let e = crate::sources::message_with_address(&t, &e); - s.notify(format!("{shown}: its tile template was refused, so the standard tile address is used: {e}"), false); - } - } - return Ok(LeftTemplate::Read(out)); - } - TilesStep::Next(next) => { - out.crossed_origin |= crosses_origin(&doc, &next); - // Resolved against the document read, never the original login. - doc = next; + let read = |doc: &str| match s.left_document(doc) { + Err(e) => Err(LeftStop::Failed(e)), + Ok(None) => Err(LeftStop::Waiting(doc.to_string())), + Ok(Some(read)) => Ok(read), + }; + match walk_template(source, list, vector, withheld, read) { + Ok(mut out) => { + if let Some(text) = out.fallback.take() { + s.notify(text, false); } + Ok(LeftTemplate::Read(out)) } + Err(LeftStop::Waiting(doc)) => Ok(LeftTemplate::Waiting(doc)), + Err(LeftStop::Failed(e)) => Err(e), } - s.notify( - format!( - "{}: its tile sets lead on past two documents, so the standard tile address is used", - crate::sources::address_in_message(list) - ), - false, - ); - Ok(LeftTemplate::Read(out)) } /// In the browser nothing waits: the app reads the template itself and passes it as `"tiles"`. diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 48c22fb32f..77f278fe7b 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -112,7 +112,7 @@ fn table_write_notes(path: &str, gpkg: &GpkgTable, default: &str, table: &GpkgWr fn report_table(s: &mut Session, path: &str, gpkg: &GpkgTable, default: &str, table: Option, out: &mut Value) { let Some(table) = table else { return }; for note in table_write_notes(path, gpkg, default, &table) { - s.notify_written(note, false); + s.notify_written(note); } if gpkg.mode != GpkgMode::NewFile { let (reread, failed) = @@ -641,7 +641,7 @@ pub(crate) fn layer_work(s: &Session, p: &Value) -> Result { /// ([`rustgis_map::Unreadable`]). Every export of a layer read in place says them, the browser's /// download too. pub fn read_date_notes(file: &str, layer: &str, lost: &rustgis_map::Unreadable) -> Vec { - let empty = lost.dates.iter().map(|n| format!("{file}: {layer}: {n}, so they're empty in the export")); + let empty = lost.dates.iter().map(|n| format!("{file}: {layer}: {n} (empty in the export)")); empty.chain(lost.rounded.iter().map(|n| format!("{file}: {layer}: {n} when read for the export"))).collect() } @@ -722,7 +722,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk 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) - .map(|n| format!("{path}: {}: {n}, so they're empty in the export", layer.name)) + .map(|n| format!("{path}: {}: {n} (empty in the export)", layer.name)) .into_iter() .collect(); dates.extend( @@ -731,7 +731,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk ); dates.extend( rustgis_data::source::null_text_note(&layer.fields, &e.null_text) - .map(|n| format!("{path}: {}: {n}, so they're empty in the export", layer.name)), + .map(|n| format!("{path}: {}: {n} (empty in the export)", layer.name)), ); dates.extend(rustgis_data::source::not_utf8_note(&layer.fields, &e.not_utf8).map(|n| format!("{path}: {}: {n}", layer.name))); dates.extend(rustgis_data::io::utc_dates_note(&layer.fields, &e.utc_dates, path)); @@ -743,7 +743,8 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk dates.extend(e.read_notes.iter().map(|n| format!("{path}: {}: {n} when read for the export", layer.name))); let mut format_notes = e.csv.notes(&ds.fields, path); format_notes.extend(e.csv.coordinates_note(&ds.fields, path)); - // CSV readers trim text or read blanks as null. + // Text that reading the file back changes: CSV reads a blank cell as null; KML and GPX trim + // their values. format_notes.extend(e.text.notes(&ds.fields, path)); (e.written, e.left_out, e.skipped, table, unfit, e.null_numbers, moved, format_notes, dates) } diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 78d598baa2..3ee97c8782 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -179,16 +179,15 @@ pub fn commands() -> Vec { crate::model::check_file(&v)?; let name = v["name"].as_str().unwrap_or("Tool").chars().take(200).collect::(); // A model file (`*.model.json`) holds a graph; a web tool its steps. - let mark = s.notice_mark(); let imported = if let Some(graph) = v.get("graph") { s.run("model.new", &json!({"name": name, "graph": graph, "imported": true}))? } else { - let steps = v.get("steps").cloned().ok_or("not a RustGIS model or web tool (no graph or steps)")?; + let steps = v.get("steps").cloned().ok_or(crate::model::NOT_A_MODEL)?; s.run("model.new", &json!({"name": name, "steps": steps, "imported": true}))? }; // A name `model.new` cut to tell it apart is said once, by it (#1923), unless this cut // it first: `model.new` saw only the first 200 characters, so that cut is said here. - let said = s.notices_since(mark).iter().any(|n| n.text.starts_with("ModelBuilder: a model has that name already")); + let said = imported.get("cut").and_then(Value::as_bool).unwrap_or(false); let cut_here = v["name"].as_str().is_some_and(|n| n.chars().count() > 200); if (cut_here || !said) && v.get("name").map_or(Some("Tool"), Value::as_str) != imported.get("model").and_then(Value::as_str) { // A cut to the 200 says how much it cut. @@ -394,7 +393,7 @@ fn share(s: &mut Session, p: &Value, kind: &str) -> CmdResult { } }; let written = s.notice_mark(); - s.notify_written(format!("Shared {name} to {path}"), false); + s.notify_written(format!("Shared {name} to {path}")); // After it, so the status bar, which shows the last notice, keeps saying it. note_label_classes(s, kind, p); note_export(s, kind, p, &path); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index ce64d92a5a..6335c9d478 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -745,7 +745,9 @@ fn new_model(s: &mut Session, p: &Value) -> CmdResult { s.project.models.push(Model { name: name.clone(), steps, graph }); notify_graph_dropped(s, dropped); let kept = name.chars().count() - if i > 1 { format!(" {i}").chars().count() } else { 0 }; - if kept < length { + // Said here, and in the result (`"cut"`), so a caller doesn't say it again. + let cut = kept < length; + if cut { s.notify( format!("ModelBuilder: a model has that name already, so the name given is cut to {kept} characters to fit \" {i}\""), false, @@ -772,7 +774,11 @@ fn new_model(s: &mut Session, p: &Value) -> CmdResult { false, ); } - Ok(json!({"model": name, "steps": n})) + let mut answer = json!({"model": name, "steps": n}); + if cut { + answer["cut"] = json!(true); + } + Ok(answer) } /// The model a command names (or the last one), or the graph it passes: its name, graph and @@ -2096,7 +2102,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result Result Result<(String, Vec), String> { }; let target = ps(p, "path").unwrap_or(&ds.name); let mut notes = rustgis_data::export_notes([(ds, ds.lonlat_extent())], target, rustgis_data::raster::Crs::LonLat); - // CSV holds a point a row, GPX a name for each feature and no areas; reading text back trims it or reads blanks as null. + // CSV holds a point a row, GPX a name for each feature and no areas; reading text back, CSV reads blanks as null and KML and GPX trim it. notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target).map_err(|e| e.to_string())?); // KML and GPX hold features with geometry only. if let ext @ ("kml" | "gpx") = format { diff --git a/crates/engine/src/connections.rs b/crates/engine/src/connections.rs index 23572f84d6..34e7770b97 100644 --- a/crates/engine/src/connections.rs +++ b/crates/engine/src/connections.rs @@ -162,42 +162,13 @@ impl Kept { /// classified on the original object first, beside the others and `address` (the one a row /// keeps apart from them): a bare `key` is a secret beside a web address, and an address /// holding a secret doesn't stop being one. Only then are the classified entries removed. - fn without_secrets(&mut self, mut o: Map, address: &str) -> Map { - // Count address-bearing siblings once; unknown preference fields are not capped. - let addresses = - o.iter().filter(|(k, v)| !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, 0)).count(); - let beside = web_address(&Value::String(address.into()), 0); - let secret: BTreeSet = o - .iter() - .filter(|(k, v)| { - let mut probe = Map::new(); - probe.insert((*k).clone(), (*v).clone()); - let own_address = !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, 0); - if beside || addresses > usize::from(own_address) { - probe.insert("\u{1}beside".into(), "https://a".into()); - } - sources::holds_secret(&Value::Object(probe)) - }) - .map(|(k, _)| k.clone()) - .collect(); - self.secrets += secret.len(); - o.retain(|k, _| !secret.contains(k)); + fn without_secrets(&mut self, o: Map, address: &str) -> Map { + let (o, secrets) = sources::without_secrets(o, sources::web_address(&Value::String(address.into()), 0)); + self.secrets += secrets; o } } -/// Whether `v` is, or holds, a web address (not under a file's `data` or `text`). -fn web_address(v: &Value, depth: usize) -> bool { - match v { - Value::String(t) => t.trim_start().get(..4).is_some_and(|p| p.eq_ignore_ascii_case("http")), - Value::Object(o) if depth < 4 => { - o.iter().any(|(k, v)| !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, depth + 1)) - } - Value::Array(a) if depth < 4 => a.iter().any(|v| web_address(v, depth + 1)), - _ => false, - } -} - /// A refused row may still name a credential in opaque metadata. Inspect it using that name /// without adding the rejected definition to the process-wide registry. fn holds_query_secret(row: &Value) -> bool { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5a2f420f50..3652a39df7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2700,7 +2700,7 @@ impl Session { } if let Some(note) = layer.source.as_mut().and_then(|source| source.take_not_utf8()) { not_utf8.push(notice_text::NoticeText::format( - "{name}: some text values in it aren't valid UTF-8 (Load All Features counts them all); so far, {note}", + "{name}: so far, {note} (Load All Features counts them all)", [("name", layer.name.clone().into()), ("note", note.into())], )); } @@ -2839,9 +2839,8 @@ impl Session { /// Says once a session that native HTTPS trusts the bundled Mozilla roots, as a Linux or BSD /// system with no CA certificates and no `SSL_CERT_FILE` or `SSL_CERT_DIR` makes it /// ([`rustgis_data::http::bundled_roots`]): the trust source was assumed, not the system's. - /// Checked after each command and each frame, as the clients are first made when a request is. - /// Says, once a session, that native HTTPS fell back to the bundled CA roots, if it did. Run - /// with [`Session::notice_landed_rasters`]; a reader of the notices that runs no command (the + /// Checked after each command and each frame (with [`Session::notice_landed_rasters`]), as the + /// clients are first made when a request is; a reader of the notices that runs no command (the /// Python package) calls it first, as a client made on a background thread chooses the trust. #[cfg(not(target_arch = "wasm32"))] pub fn notice_trust(&mut self) { @@ -2943,9 +2942,9 @@ impl Session { /// A notice about a file or database write that has committed, not a pending delivery or /// an in-memory edit. It follows the ordinary redaction, bounds and diagnostics path, but /// survives a later enclosing command's rollback. - pub(crate) fn notify_written(&mut self, text: impl Into, error: bool) { + pub(crate) fn notify_written(&mut self, text: impl Into) { let mark = self.notice_mark(); - self.notify(text, error); + self.notify(text, false); self.retain_written_notices(mark); } diff --git a/crates/engine/src/model.rs b/crates/engine/src/model.rs index d4042bb4a5..45dc309a62 100644 --- a/crates/engine/src/model.rs +++ b/crates/engine/src/model.rs @@ -355,12 +355,19 @@ pub fn new_id(g: &ModelGraph, prefix: &str) -> String { (1..).map(|i| format!("{prefix}{i}")).find(|id| !g.nodes.iter().any(|n| &n.id == id)).unwrap_or_else(|| prefix.to_string()) } +/// The parts of a step's input-port value: for a port that takes many layers, each name between +/// `;`s, trimmed, blanks left out; for one that takes one, the whole value, trimmed. +fn port_parts(value: &str, many: bool) -> impl Iterator { + value.split(move |c| many && c == ';').map(str::trim).filter(move |part| !many || !part.is_empty()) +} + /// A graph from steps run in order (`%n` for step n's output): an input node for each layer -/// the steps read, a tool node per step, laid out. -pub fn steps_to_graph(steps: &[ModelStep]) -> ModelGraph { +/// the steps read, a tool node per step, laid out. Only [`checked_steps_to_graph`] calls it, which +/// refuses steps past the graph's limits first. +pub(crate) fn steps_to_graph(steps: &[ModelStep]) -> ModelGraph { let mut g = ModelGraph::default(); let mut inputs: HashMap = HashMap::new(); - for (i, st) in steps.iter().take(MAX_NODES / 2).enumerate() { + for (i, st) in steps.iter().enumerate() { let id = format!("t{}", i + 1); let mut params = match &st.params { Value::Object(o) => o.clone(), @@ -369,8 +376,7 @@ pub fn steps_to_graph(steps: &[ModelStep]) -> ModelGraph { let node = ModelNode { id: id.clone(), kind: ModelNodeKind::Tool, tool: Some(st.tool.clone()), ..Default::default() }; for port in input_ports(&node) { let Some(v) = params.get(port.id).and_then(Value::as_str).map(str::to_string) else { continue }; - let parts: Vec<&str> = if port.many { v.split(';').map(str::trim).filter(|x| !x.is_empty()).collect() } else { vec![v.trim()] }; - for part in parts { + for part in port_parts(&v, port.many) { let from = match part.strip_prefix('%').and_then(|n| n.parse::().ok()) { Some(n) if (1..=i).contains(&n) => format!("t{n}"), Some(_) => continue, @@ -417,10 +423,7 @@ pub fn checked_steps_to_graph(steps: &[ModelStep]) -> Result let node = ModelNode { tool: Some(step.tool.clone()), kind: ModelNodeKind::Tool, ..Default::default() }; for port in input_ports(&node) { let Some(value) = step.params.get(port.id).and_then(Value::as_str) else { continue }; - for part in value.split(|c| port.many && c == ';').map(str::trim) { - if port.many && part.is_empty() { - continue; - } + for part in port_parts(value, port.many) { match part.strip_prefix('%').and_then(|n| n.parse::().ok()) { Some(n) if !(1..=index).contains(&n) => { return Err(format!( @@ -884,6 +887,9 @@ struct ImportItem { extra: HashMap, } +/// What a file that is no model or web tool is refused with. +pub(crate) const NOT_A_MODEL: &str = "not a RustGIS model or web tool (no graph or steps)"; + /// Check declared versions, required capabilities (`requires`, as a project's; see /// [`crate::project::CAPABILITIES`]) and model contents before import can discard data. Missing /// versions are legacy files. The stricter field checks apply only to file import. @@ -895,7 +901,7 @@ pub(crate) fn check_file(v: &Value) -> Result<(), String> { let tool = v.get("steps").is_some() || v.get("format").and_then(Value::as_str) == Some("RustGIS web tool"); // Some other file (GeoJSON, a project) is said to be one, not told to update RustGIS. if !model && !tool { - return Err("not a RustGIS model or web tool (no graph or steps)".into()); + return Err(NOT_A_MODEL.into()); } if let Some(version) = v.get("version") { let supported = if model { version.as_str() == Some(FILE_VERSION) } else { version.as_u64() == Some(WEB_TOOL_VERSION) }; @@ -905,7 +911,8 @@ pub(crate) fn check_file(v: &Value) -> Result<(), String> { } crate::project::check_requires(v.get("requires"), "model or web tool", "import")?; if graph.is_none() && v.get("steps").is_none() { - return Err("not a RustGIS model or web tool (no graph or steps)".into()); + // Identified as one by its schema or format above, but holding neither. + return Err("a RustGIS model or web tool with neither graph nor steps".into()); } if graph.is_some() && v.get("steps").is_some() { return Err("a model file cannot contain both a graph and steps. Choose one representation before importing it.".into()); diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 40df2fe427..cd2d565959 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -173,7 +173,7 @@ impl Session { | "layer.sizeBy" ) && crate::cmd::edit::table_edit_in_background(command).is_none() { - return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service reads, topology, Source File State, Column Statistics and Size by Field prepare background work".into()); + return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service reads, topology, Source File State, Read Original Image Grid, Preview Shape Conversion, Column Statistics and Size by Field prepare background work".into()); } let mut params = params.as_object().cloned().ok_or("read parameters must be an object")?; // Scoped previews retain the raw invocation that was approved. Their admitted owner diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 058b8e74e5..0e3471d3c0 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1302,7 +1302,13 @@ impl Project { /// The same repairs with deferred translation for session-owned interface notices. pub(crate) fn normalize_text(&mut self) -> Vec { - self.repair(false).into_iter().map(|(_, n)| n).collect() + self.normalize_after("while checking the project") + } + + /// [`Project::normalize_text`] after something was added to the project, its notices saying + /// `when` the repairs were made ("while importing the map"). + pub(crate) fn normalize_after(&mut self, when: &'static str) -> Vec { + self.repair(false, when).into_iter().map(|(_, n)| n).collect() } /// [`Project::normalize`] for a project read from its file, which also opens its plain COG @@ -1312,12 +1318,13 @@ impl Project { /// as it is. Returns a notice for each kind of change that removed, cut or renamed /// something, with the part of the project it is about. pub(crate) fn normalize_opened(&mut self) -> Vec<(ReadPart, NoticeText)> { - self.repair(true) + self.repair(true, "while opening the project") } /// Reports removed or shortened content, renamed items and repaired group display settings - /// with their affected part. Table ids absent from older formats are filled in for compatibility. - fn repair(&mut self, opened: bool) -> Vec<(ReadPart, NoticeText)> { + /// with their affected part, each saying `when` it was made. Table ids absent from older + /// formats are filled in for compatibility. + fn repair(&mut self, opened: bool, when: &'static str) -> Vec<(ReadPart, NoticeText)> { if self.maps.is_empty() { self.maps.push(Map::new("Map")); } @@ -1350,7 +1357,6 @@ impl Project { repairs.push((l.name.clone(), r)); } } - let when = if opened { "while opening the project" } else { "while checking the project" }; let mut notices: Vec<(ReadPart, NoticeText)> = layout_notices(&self.name, when, layouts_dropped, &repairs).into_iter().map(|n| (ReadPart::Layouts, n.into())).collect(); let mut done = Repaired::default(); @@ -1761,7 +1767,12 @@ impl Project { if let Some(limit) = map_limit { p.maps.truncate(limit); } - let repair_notices = if normalize { p.normalize_opened() } else { Vec::new() }; + // Maps imported from a project are read as it opens, and said as imported. + let repair_notices = match (normalize, map_limit) { + (false, _) => Vec::new(), + (true, None) => p.normalize_opened(), + (true, Some(_)) => p.repair(true, "while importing the maps"), + }; p.read_notices = label_losses::notices_for_maps(text, &p, map_limit.is_some())?.into_iter().map(|(part, text)| (part, text.into())).collect(); p.read_notices.extend(repair_notices); @@ -2013,7 +2024,6 @@ pub(crate) const ALL_PARTS: [ReadPart; 7] = [ /// The most layouts a project keeps (`layout.*` commands refuse to make more). pub(crate) const MAX_LAYOUTS: usize = 200; -/// The layouts named in a notice, the first few of them. /// A name cut to 100 characters for a notice, so a long one can't crowd out the count (a /// notice too long is withheld whole). pub(crate) fn short_name(name: &str) -> String { @@ -2023,6 +2033,7 @@ pub(crate) fn short_name(name: &str) -> String { } } +/// The layouts named in a notice, the first few of them. fn layout_names( repairs: &[(String, rustgis_map::layout::LayoutRepairs)], of: impl Fn(&rustgis_map::layout::LayoutRepairs) -> usize, diff --git a/crates/engine/src/project_label_losses.rs b/crates/engine/src/project_label_losses.rs index 7f95e29a3d..a7d56f1dc8 100644 --- a/crates/engine/src/project_label_losses.rs +++ b/crates/engine/src/project_label_losses.rs @@ -63,6 +63,9 @@ impl<'de> Deserialize<'de> for MoveCount { #[derive(Default, Deserialize)] struct Class { + /// The class's name as written (a missing one is "Default", as the reader takes it). + #[serde(default)] + name: Option, #[serde(default)] moved: MoveCount, #[serde(default)] @@ -81,6 +84,9 @@ struct Class { #[derive(Default, Deserialize)] struct Labels { + /// The Default class's name as written. + #[serde(default)] + name: Option, #[serde(default)] moved: MoveCount, #[serde(default)] @@ -180,6 +186,55 @@ fn damaged_flag(value: Option<&serde_json::Value>) -> bool { value.is_some_and(|v| !v.is_boolean() && !v.is_null()) } +/// What reading a layer's label classes drops or cuts (see `From for Labeling`). +#[derive(Default)] +struct ClassLosses { + /// Class names longer than [`rustgis_map::symbology::MAX_LABEL_CLASS_NAME`], cut to it. + cut: usize, + /// Classes past [`rustgis_map::symbology::MAX_LABEL_CLASSES`], dropped. + excess: usize, + /// Classes with no name, or the name of an earlier class or of Default, dropped. + unnamed_or_repeated: usize, +} + +impl ClassLosses { + /// Replays the reader's class rules on one layer's raw labels and adds what they drop or cut. + fn add(&mut self, labels: &Labels) { + use rustgis_map::symbology::{DEFAULT_LABEL_CLASS, MAX_LABEL_CLASS_NAME, MAX_LABEL_CLASSES, label_class_name}; + let raw_name = |n: &Option| match n { + None => DEFAULT_LABEL_CLASS.to_string(), + Some(v) => v.as_str().unwrap_or_default().to_string(), + }; + let mut cut = |raw: &str| { + if raw.trim().chars().count() > MAX_LABEL_CLASS_NAME { + self.cut = self.cut.saturating_add(1); + } + }; + let raw_default = raw_name(&labels.name); + cut(&raw_default); + let mut default = label_class_name(&raw_default); + if default.is_empty() { + default = DEFAULT_LABEL_CLASS.into(); + } + let mut kept: Vec = Vec::new(); + for class in &labels.classes { + if kept.len() >= MAX_LABEL_CLASSES { + self.excess = self.excess.saturating_add(1); + continue; + } + let raw = raw_name(&class.name); + cut(&raw); + let name = label_class_name(&raw); + let same = |n: &str| n.eq_ignore_ascii_case(&name); + if name.is_empty() || same(&default) || kept.iter().any(|o| same(o)) { + self.unnamed_or_repeated = self.unnamed_or_repeated.saturating_add(1); + } else { + kept.push(name); + } + } + } +} + /// Count what the raw layers hold against what the read labels kept; one notice per kind, each /// naming the item read (`name`) and what it was (`what`: "the project", "the map file", ...). fn count<'a>( @@ -188,12 +243,15 @@ fn count<'a>( name: &str, what: &str, ) -> Vec<(ReadPart, String)> { + let name = crate::project::short_name(name); + let mut classes = ClassLosses::default(); let (mut moves, mut callouts, mut offsets, mut flags, mut squares, mut stretches) = (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); let mut guides = 0usize; let mut diagrams = rustgis_map::diagram::DiagramAudit::default(); for layer in raw { diagrams = diagrams.plus(layer.diagram); let labels = &layer.labels; + classes.add(labels); moves = moves.saturating_add(labels.moved.0); callouts = callouts.saturating_add(usize::from(adjusted_callout(labels.callout.as_ref()))); offsets = offsets.saturating_add(usize::from(adjusted_line_offset(labels.line_offset.as_ref()))); @@ -239,9 +297,29 @@ fn count<'a>( if stretches > 0 { messages.push(format!("{name}: {stretches} label stretch setting(s) out of range or not a number adjusted while opening {what}")); } + if classes.cut > 0 { + messages.push(format!( + "{name}: {} label class name(s) longer than {} characters cut to that length while opening {what}", + classes.cut, + rustgis_map::symbology::MAX_LABEL_CLASS_NAME + )); + } + if classes.excess > 0 { + messages.push(format!( + "{name}: {} label class(es) past the {} a layer holds dropped while opening {what}", + classes.excess, + rustgis_map::symbology::MAX_LABEL_CLASSES + )); + } + if classes.unnamed_or_repeated > 0 { + messages.push(format!( + "{name}: {} label class(es) with no name, or the name of an earlier class or of Default, dropped while opening {what}", + classes.unnamed_or_repeated + )); + } let mut messages: Vec<(ReadPart, String)> = messages.into_iter().map(|m| (ReadPart::Labels, m)).collect(); let mut found = Vec::new(); - diagram_messages(diagrams, name, what, &mut found); + diagram_messages(diagrams, &name, what, &mut found); messages.extend(found.into_iter().map(|m| (ReadPart::Diagrams, m))); messages } diff --git a/crates/engine/src/shape_conversion.rs b/crates/engine/src/shape_conversion.rs index 1582f05699..6f92f4d943 100644 --- a/crates/engine/src/shape_conversion.rs +++ b/crates/engine/src/shape_conversion.rs @@ -257,7 +257,7 @@ pub(crate) fn preview(s: &mut Session, p: &Value) -> CmdResult { let ready = crate::cmd::reads::take::(s, "shapeConversion"); #[cfg(not(target_arch = "wasm32"))] if ready.is_none() && s.statistics_window_thread == Some(std::thread::current().id()) { - return Err("shape fitting needs the desktop background preview queue; use Convert to or a direct MCP preview request".into()); + return Err("shape fitting needs the desktop background preview queue; use Convert Polygon to Shape… (its Preview Conversion), or ask for edit.previewShapeConversion through MCP".into()); } let done = if let Some(a) = ready { let l = s.map().layer(t.layer).ok_or("no layer")?; diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index ab8688e623..43d0100c91 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -88,32 +88,42 @@ impl Kept { /// keeps apart from them): a bare `key` is a secret beside a web address, and an address /// holding a secret doesn't stop being one; `known` is the row's known details (its `extra`), a /// sibling too. Only then are the classified entries removed. - fn without_secrets(&mut self, mut o: Map, address: &str, known: &Value) -> Map { - // Count address-bearing siblings once; unknown preference fields are not capped. - let addresses = - o.iter().filter(|(k, v)| !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, 0)).count(); + fn without_secrets(&mut self, o: Map, address: &str, known: &Value) -> Map { let beside = web_address(&Value::String(address.into()), 0) || web_address(known, 0); - let secret: BTreeSet = o - .iter() - .filter(|(k, v)| { - let mut probe = Map::new(); - probe.insert((*k).clone(), (*v).clone()); - let own_address = !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, 0); - if beside || addresses > usize::from(own_address) { - probe.insert("\u{1}beside".into(), "https://a".into()); - } - holds_secret(&Value::Object(probe)) - }) - .map(|(k, _)| k.clone()) - .collect(); - self.secrets += secret.len(); - o.retain(|k, _| !secret.contains(k)); + let (o, secrets) = without_secrets(o, beside); + self.secrets += secrets; o } } +/// The entries of `o` without a password, key or token, and how many were left out. Every entry +/// is classified on the original object first, beside the others: a bare `key` is a secret beside +/// a web address (another entry, or one outside `o` when `beside`), and an address holding a +/// secret doesn't stop being one. Only then are the classified entries removed. +pub(crate) fn without_secrets(mut o: Map, beside: bool) -> (Map, usize) { + // Count address-bearing siblings once; unknown preference fields are not capped. + let addresses = + o.iter().filter(|(k, v)| !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, 0)).count(); + let secret: BTreeSet = o + .iter() + .filter(|(k, v)| { + let mut probe = Map::new(); + probe.insert((*k).clone(), (*v).clone()); + let own_address = !k.eq_ignore_ascii_case("data") && !k.eq_ignore_ascii_case("text") && web_address(v, 0); + if beside || addresses > usize::from(own_address) { + probe.insert("\u{1}beside".into(), "https://a".into()); + } + holds_secret(&Value::Object(probe)) + }) + .map(|(k, _)| k.clone()) + .collect(); + let left_out = secret.len(); + o.retain(|k, _| !secret.contains(k)); + (o, left_out) +} + /// Whether `v` is, or holds, a web address (not under a file's `data` or `text`). -fn web_address(v: &Value, depth: usize) -> bool { +pub(crate) fn web_address(v: &Value, depth: usize) -> bool { match v { Value::String(t) => t.trim_start().get(..4).is_some_and(|p| p.eq_ignore_ascii_case("http")), Value::Object(o) if depth < 4 => { @@ -206,6 +216,11 @@ impl Sources { } _ if holds_secret(&row) => s.kept.secrets += 1, read => { + // A readable row past the cap is still the first of its identity, so a + // later repeat of it is said as repeated, not counted past the cap again. + if let Some((_, source, _)) = &read { + seen.insert(identity(&source.kind, &source.address)); + } s.kept.over += usize::from(read.is_some()); s.kept.rows.entry(list).or_default().push(row); } @@ -1355,6 +1370,12 @@ MIIE let stored: Vec = (0..MAX_KEPT).map(|i| json!({"kind": "file", "name": "", "address": format!("/{i}.csv")})).collect(); s.merge(Sources::from_json(&json!({ "favourites": stored }).to_string())); assert!(s.unread().iter().any(|t| t.contains("past the lists' limits")), "{:?}", s.unread()); + // A row past the limit counts once: its repeat is said as repeated, not past the limit. + let mut over: Vec = (0..MAX_KEPT).map(|i| json!({"kind": "file", "name": "", "address": format!("/{i}.csv")})).collect(); + over.extend([json!({"kind": "file", "name": "", "address": "/x.csv"}), json!({"kind": "file", "name": "", "address": "/x.csv"})]); + let s = Sources::from_json(&json!({ "saved": over }).to_string()); + assert_eq!((s.kept.over, s.kept.repeated), (1, 1)); + assert!(s.unread().iter().any(|t| t.starts_with("1 saved data source is past the lists' limits")), "{:?}", s.unread()); // A repeat past the limit is dropped, not kept as an overflow row. A bound address is the // bare one's identity: forgetting by either form removes a kept over-limit row of it, never // an unreadable row that merely shares the address. @@ -1371,7 +1392,8 @@ MIIE full.push(json!({"kind": "future", "name": "", "address": twin})); full.push(json!({"kind": " url ", "name": 5, "address": twin})); let mut s = Sources::from_json(&json!({"saved": full}).to_string()); - assert_eq!(s.kept.over, 2, "{:?}", s.unread()); + // The twin repeats the bound row's identity, past the limit as it is: said as repeated. + assert_eq!((s.kept.over, s.kept.repeated), (1, 1), "{:?}", s.unread()); let generation = s.generation; // Only kept rows go: that is still a removal, and the pane must still save. assert!(s.forget("saved", "url", &twin).unwrap() && s.generation != generation); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4a026cc68..b1f758c5c6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1719,7 +1719,7 @@ fn a_streamed_shapefile_says_null_markers_once_and_in_its_exports() { assert_eq!(notes.len(), usize::from(said), "{name} {command}: {:?}", s.notices_since(mark)); if said { assert!( - notes[0].ends_with("zoning: 1 value written as Null was read as empty, in 'ZONING', so they're empty in the export"), + notes[0].ends_with("zoning: 1 value written as Null was read as empty, in 'ZONING' (empty in the export)"), "{}", notes[0] ); @@ -2009,7 +2009,7 @@ fn an_export_says_what_its_whole_read_did_to_dates() { assert_eq!( crate::cmd::share::read_date_notes("out.geojson", "Sites", &lost), [ - "out.geojson: Sites: 1 value isn't a date and was read as empty, in 'day', so they're empty in the export", + "out.geojson: Sites: 1 value isn't a date and was read as empty, in 'day' (empty in the export)", "out.geojson: Sites: 1 date-time was rounded to the microsecond, as more digits than that aren't kept, in 'at' when read for the export", ] ); @@ -2690,6 +2690,20 @@ fn a_streamed_layer_needs_bounds_for_its_size_mapping() { assert!(s.map().layers[0].size_by.is_some()); } +/// A field with one value in every row, with no bounds given, says so rather than comparing +/// bounds that weren't given; a bound given is still compared with the other. +#[test] +fn sizing_by_a_field_with_one_value_asks_for_bounds() { + let mut s = world(); + s.run("layer.symbology", &json!({"layer": "Cities", "type": "unique", "field": "name"})).unwrap(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "flat", "type": "double"})).unwrap(); + s.run("edit.calculateField", &json!({"layer": "Cities", "field": "flat", "expression": "5"})).unwrap(); + let err = s.run("layer.sizeBy", &json!({"layer": "Cities", "field": "flat"})).unwrap_err(); + assert_eq!(err, "'flat' has the same value (5) in every row, so give min and max"); + let err = s.run("layer.sizeBy", &json!({"layer": "Cities", "field": "flat", "min": 5})).unwrap_err(); + assert!(err.contains("max (5) must be above min (5)"), "{err}"); +} + /// `layer.sizeBy` sizes a classified point layer by a field, keeping what it isn't given, refusing /// what doesn't fit (without an undo step), and is undone and removed like any style. #[test] @@ -5008,7 +5022,7 @@ fn removing_a_perpendicular_label_line_says_so() { s.run("layer.remove", &json!({"layer": "Rivers"})).unwrap(); let notes = said(&s, mark); assert_eq!(notes.len(), 1, "{notes:?}"); - assert!(notes[0].contains("1 perpendicular labels' line layer(s) 'Rivers' removed"), "{notes:?}"); + assert!(notes[0].contains("1 perpendicular labels' line layer 'Rivers' removed"), "{notes:?}"); let c = s.map().layer_by_name("Cities").unwrap().labels.default.clone(); assert_eq!((c.placement, c.square_to.unwrap().layer.as_str()), (crate::map::LabelPlacement::Perpendicular, "Rivers")); } @@ -5620,6 +5634,11 @@ fn save_refuses_a_path_that_isnt_a_project_file() { assert!(e.contains("a .rgis file, not a .geojson one"), "{e}"); let e = s.run("project.save", &json!({"path": dir.join("data.GPKG")})).unwrap_err(); assert!(e.contains("not a .gpkg one"), "{e}"); + // A bare trailing dot, or a folder named like a project, is refused without naming an extension. + for odd in ["foo.", "a.rgis.", "atlas.rgis/"] { + let e = s.run("project.saveAs", &json!({"path": format!("{}/{odd}", dir.display())})).unwrap_err(); + assert_eq!(e, "a project saves to a .rgis file", "{odd}"); + } let package = dir.join("atlas.rgispkg"); let e = s.run("project.saveAs", &json!({"path": package})).unwrap_err(); assert!(e.contains("project.package"), "{e}"); @@ -7961,6 +7980,51 @@ fn line_labels_fit_their_line_with_a_word_list() { assert_eq!(class(&s), (LabelFit::Off, Default::default())); } +/// Opening a project says how many label classes it cut or dropped: a name over the length a +/// class keeps, a class with no name or the name of one before it, and the classes past the cap; +/// classes that read as written say nothing. +#[test] +fn opening_says_which_label_classes_it_cut_or_dropped() { + let mut s = world(); + s.run("labels.class.add", &json!({"layer": "Cities", "name": "Big", "where": "pop_max > 5000000"})).unwrap(); + let text = serde_json::to_string(&s.project).unwrap(); + let said = |v: &Value| { + let s = Session::new(Project::from_json(&v.to_string()).unwrap()); + s.notices.iter().filter(|n| n.text.contains("label class")).map(|n| n.text.clone()).collect::>() + }; + let clean: Value = serde_json::from_str(&text).unwrap(); + assert!(said(&clean).is_empty(), "{:?}", said(&clean)); + let mut damaged = clean.clone(); + let cities = damaged["maps"][0]["layers"].as_array_mut().unwrap().iter_mut().find(|l| l["name"] == "Cities").unwrap(); + let classes = cities["labels"]["classes"].as_array_mut().unwrap(); + let mut long = classes[0].clone(); + long["name"] = json!("x".repeat(101)); + let mut repeat = classes[0].clone(); + repeat["name"] = json!("BIG"); + classes.push(long); + classes.push(repeat); + let loaded = Project::from_json(&damaged.to_string()).unwrap(); + let kept = &loaded.maps[0].layer_by_name("Cities").unwrap().labels.classes; + assert_eq!(kept.len(), 2, "the repeat is dropped"); + let notes = said(&damaged); + assert_eq!(notes.len(), 2, "{notes:?}"); + assert!(notes.iter().any(|n| n.contains("1 label class name(s) longer than 100 characters cut")), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains("1 label class(es) with no name, or the name of an earlier class")), "{notes:?}"); + let classes = + damaged["maps"][0]["layers"].as_array_mut().unwrap().iter_mut().find(|l| l["name"] == "Cities").unwrap()["labels"]["classes"] + .as_array_mut() + .unwrap(); + let template = classes[0].clone(); + classes.truncate(1); + for i in 0..rustgis_map::symbology::MAX_LABEL_CLASSES + 2 { + let mut c = template.clone(); + c["name"] = json!(format!("c{i}")); + classes.push(c); + } + let notes = said(&damaged); + assert!(notes.iter().any(|n| n.contains("3 label class(es) past the 64 a layer holds dropped")), "{notes:?}"); +} + /// How much of its line a fitted label is spread over (#2265): `stretch` on the text symbol, /// brought into 0.1 to 1, null for the default, junk refused, and kept with the project (one /// that doesn't read is none, and opening says so with a count; in range or null says nothing). @@ -8615,6 +8679,26 @@ fn imported_items_report_content_cuts() { } } +/// What repairing imported maps changed is said as done while importing them, not while opening or +/// checking the project: maps from a project file, and a single map file alike. +#[test] +fn imported_map_repairs_say_they_were_made_while_importing() { + let mut p = Project::default(); + p.maps[0].groups.push(rustgis_map::LayerGroup::new("Broken group")); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("map.import", &json!({"text": serde_json::to_string(&p).unwrap()})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("layer group(s)")).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("removed while importing the maps"), "{said:?}"); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("map.import", &json!({"text": serde_json::to_string(&p.maps[0]).unwrap()})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("layer group(s)")).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("removed while importing the map "), "{said:?}"); +} + /// Map imports audit retained maps only, and a usable tile still reports discarded dated content. #[test] fn imported_maps_scope_repairs_and_tiles_report_content_cuts() { @@ -11310,12 +11394,12 @@ fn publication_layouts_fit_their_pages() { // Beside it on the side it grows to: the left one when it keeps its right edge. let x = if boxed.x + boxed.w / 2.0 > frame_x_mid(&s, li, frame) { boxed.x - 5.5 } else { boxed.x + boxed.w + 0.5 }; s.run("layout.update", &json!({"layout": li, "element": arrow, "x": x, "y": boxed.y, "w": 5.0, "h": 5.0})).unwrap(); - let mark = s.notices.len(); + let mark = s.notice_mark(); s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": "Escala aproximada da folha {scale}"})).unwrap(); s.run("layout.update", &json!({"layout": li, "element": frame, "scale": 30_000_000.0})).unwrap(); let after = s.project.layouts[li].element(b).cloned().unwrap(); assert_eq!((after.x, after.w), (boxed.x, boxed.w), "the box stays"); - assert!(s.notices[mark..].iter().any(|n| n.text.contains("would now cover the north arrow")), "said"); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("would now cover the north arrow")), "said"); // A text longer than the widest box, its box widened by hand for it: the width is kept. s.run("layout.update", &json!({"layout": li, "element": arrow, "x": 0.0, "y": 0.0})).unwrap(); let long = "Escala aproximada da folha impressa em papel de formato A4 {scale}"; @@ -15248,12 +15332,12 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { // missing ground is. let walled = run(&mut s, &dems[1], heights); let walled_across = walled["acrossNoData"].as_u64().unwrap(); - let mark = s.notices.len(); + let mark = s.notice_mark(); let v = run(&mut s, &dems[0], heights); let across = v["acrossNoData"].as_u64().unwrap(); assert!(across > 100 && across <= v["visibleCells"].as_u64().unwrap(), "{heights}: {v}"); assert!(walled_across > 0 && walled_across + 100 < across, "{heights}: {walled_across} of {across}"); - let said: Vec<&str> = s.notices[mark..].iter().map(|n| n.text.as_str()).collect(); + let said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); assert!( said.iter().any(|t| t.contains(&format!("{across} cell(s) of the viewshed were seen across ground with no data"))), "{heights}: {said:?}" @@ -15289,9 +15373,9 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { s.run("layer.addDataBytes", &json!({"fileName": "globe.tif", "data": data})).unwrap(); let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); let said = |s: &mut Session, p: Value| { - let mark = s.notices.len(); + let mark = s.notice_mark(); s.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("{p}: {e}")); - s.notices[mark..].iter().map(|n| n.text.clone()).collect::>() + s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>() }; let seam = "rays don't cross its east–west edge"; // By the edge with no radius (the whole raster): the seam is said. @@ -15748,13 +15832,13 @@ fn analysis_workflows_models_scripts_and_raster_functions() { // Bilinear heights read the ground between cells: on this hill and wall they see at least // what the nearest cells do (a cell nearer the top no longer stands in for the ground), and // little more. Any other name, or a value that isn't one, is refused, saying which there are. - let mark = s.notices.len(); + let mark = s.notice_mark(); let b = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2, "heights": "Bilinear"})).unwrap(); let (near, bil) = (v["visibleCells"].as_u64().unwrap(), b["visibleCells"].as_u64().unwrap()); assert!(bil >= near && bil <= near + near / 10, "nearest {near}, bilinear {bil}"); // A DEM with every cell holding data: nothing to say about ground with none, and the answer // says none. - assert!(s.notices[mark..].is_empty(), "{:?}", s.notices[mark..].iter().map(|n| &n.text).collect::>()); + assert!(s.notices_since(mark).is_empty(), "{:?}", s.notices_since(mark).iter().map(|n| &n.text).collect::>()); for a in [&v, &b] { assert_eq!((&a["acrossNoData"], &a["readNearest"]), (&json!(0), &json!(0)), "{a}"); } @@ -17791,7 +17875,7 @@ fn plugin_host_features_refuses_what_it_can_not_place_with_crs_errors() { ds.name = "Sinu".into(); s.map_mut().add_dataset(ds); let e = ask(&mut s, "Sinu", "layer").unwrap_err(); - assert!(e.contains("crs:") && e.contains("no EPSG code"), "{e}"); + assert!(e.contains("crs:") && e.contains("can name in GeoJSON"), "{e}"); // `host.layers` still names it (not the null of an unread raster). let layers = forward(&mut s, "eng-crs-no", "host.layers", json!({})).unwrap(); let sinu = layers.as_array().unwrap().iter().find(|l| l["name"] == "Sinu").unwrap(); @@ -17799,7 +17883,7 @@ fn plugin_host_features_refuses_what_it_can_not_place_with_crs_errors() { // "map" on a projection with no EPSG code is refused, and nothing is registered for it. s.run("map.projection", &json!({"type": "robinson"})).unwrap(); let e = ask(&mut s, "P", "map").unwrap_err(); - assert!(e.contains("crs:") && e.contains("no EPSG code"), "{e}"); + assert!(e.contains("crs:") && e.contains("can name in GeoJSON"), "{e}"); s.run("map.projection", &json!({"type": "EPSG:3857"})).unwrap(); // Geocentric targets can't carry a third coordinate. let e = ask(&mut s, "P", "EPSG:4978").unwrap_err(); @@ -25372,7 +25456,7 @@ fn geopackage_attribute_tables_are_not_silently_omitted() { ); let notes = skipped(&s); assert_eq!(notes.len(), 1, "bytes={bytes}: {notes:?}"); - assert!(notes[0].contains("2 attribute-only tables") && notes[0].contains("mixed.gpkg"), "{notes:?}"); + assert!(notes[0].contains("2 attribute-only table(s)") && notes[0].contains("mixed.gpkg"), "{notes:?}"); assert!(s.notices.iter().any(|n| n.text.contains("1 tiles table(s) not added")), "bytes={bytes}: {:?}", s.notices); } // Selecting one feature table deliberately does not claim to add the whole file. @@ -26877,9 +26961,9 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { }; s.map_mut().add_dataset(named(layer("Names", GeometryType::Point, clean))); let said = |s: &mut Session, id: &str, p: Value| { - let mark = s.notices.len(); + let mark = s.notice_mark(); s.run(id, &p).unwrap(); - s.notices[mark..].iter().map(|n| n.text.clone()).filter(|t| !t.starts_with("Exported ")).collect::>() + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| !t.starts_with("Exported ")).collect::>() }; let out = |name: &str| dir.join(name).display().to_string(); let n = said(&mut s, "share.exportLayer", json!({"layer": "Areas", "path": out("areas.csv")})); @@ -27689,8 +27773,8 @@ fn derived_multiband_rasters_keep_every_band_in_the_project() { std::fs::remove_dir_all(dir).unwrap(); } -/// An ASCII grid whose `.prj` can't be read is added in longitude/latitude, and adding it says so; -/// one whose `.prj` is read says nothing of it. +/// Equidistant Cylindrical typed as WKT, on a layer's inputs (Define Projection, a CSV's `crs`, +/// an export), says which formula it is read with, once; typed by its EPSG code it says nothing. #[test] fn projection_review_typed_layer_inputs_report_the_formula_choice() { let wkt = include_str!("../../data/src/raster/wkt2_corpus.tsv") @@ -27892,6 +27976,8 @@ fn ascii_grid_reports_declared_method_1028_compatibility() { std::fs::remove_dir_all(dir).unwrap(); } +/// An ASCII grid whose `.prj` can't be read is added in longitude/latitude, and adding it says so; +/// one whose `.prj` is read says nothing of it. #[test] fn an_ascii_grid_s_unread_prj_is_said_when_added() { let dir = std::env::temp_dir().join(format!("rustgis-engine-asc-prj-{}", std::process::id())); @@ -28018,10 +28104,10 @@ fn a_system_without_an_epsg_code_is_exported_in_its_own_system() { let own = s.map().layers.iter().find(|l| l.name == "sites").and_then(|l| l.dataset.crs).unwrap(); assert_eq!(own.epsg(), 0, "the .prj has no authority: {}", own.label()); for file in ["sites.gpkg", "sites.fgb", "again.shp"] { - let mark = s.notices.len(); + let mark = s.notice_mark(); let r = s.run("share.exportLayer", &json!({"layer": "sites", "path": path(file)})).unwrap(); assert_eq!(r["crs"], own.label(), "{file}"); - let said: Vec<_> = s.notices[mark..].iter().map(|n| n.text.clone()).filter(|t| !t.starts_with("Exported ")).collect(); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| !t.starts_with("Exported ")).collect(); assert!(said.is_empty(), "{file}: {said:?}"); // Added back, the point is where it was and the layer is in the same system. let r = s.run("layer.addData", &json!({"path": path(file)})).unwrap(); @@ -28035,10 +28121,10 @@ fn a_system_without_an_epsg_code_is_exported_in_its_own_system() { let gnomonic = "+proj=gnom +lat_0=35 +lon_0=-90 +datum=WGS84 +units=m +no_defs"; s.run("layer.addData", &json!({"path": path("sites.csv"), "name": "far", "x": "longitude", "y": "latitude", "crs": gnomonic})).unwrap(); for file in ["far.gpkg", "far.fgb"] { - let mark = s.notices.len(); + let mark = s.notice_mark(); let r = s.run("share.exportLayer", &json!({"layer": "far", "path": path(file)})).unwrap(); assert_eq!(r["crs"], "EPSG:4326", "{file}"); - let said: Vec<_> = s.notices[mark..].iter().map(|n| n.text.clone()).collect(); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.contains("WGS 84") && t.contains(file) && t.contains("far")), "{file}: {said:?}"); } let _ = std::fs::remove_dir_all(&dir); @@ -42308,13 +42394,13 @@ fn legends_label_layers() { Some(ElementKind::Legend { labels, .. }) if labels.get("Rivers").is_some_and(|l| l == "Rios principais") )); let cut_notice = - |s: &Session, from: usize| s.notices[from..].iter().filter(|n| n.text.contains("legend labels cut to their limits")).count(); + |s: &Session, from: u64| s.notices_since(from).iter().filter(|n| n.text.contains("legend labels cut to their limits")).count(); assert_eq!(cut_notice(&s, 0), 0, "nothing was cut"); // A layout file with a label longer than a legend keeps is read with it cut, and says so. let mut text: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); let legend = text["elements"].as_array_mut().unwrap().iter_mut().find(|e| e["id"] == json!(id)).unwrap(); legend["kind"]["Legend"]["labels"]["Rivers"] = json!("x".repeat(rustgis_map::layout::MAX_LEGEND_LABEL_CHARS + 50)); - let mark = s.notices.len(); + let mark = s.notice_mark(); s.run("layout.import", &json!({"text": text.to_string()})).unwrap(); assert_eq!(cut_notice(&s, mark), 1); assert!(matches!( @@ -42325,7 +42411,7 @@ fn legends_label_layers() { // says so. let legend = text["elements"].as_array_mut().unwrap().iter_mut().find(|e| e["id"] == json!(id)).unwrap(); legend["kind"]["Legend"]["labels"] = json!({"Rivers": "Rios", "rivers": "rios", "Lakes": "Lagos"}); - let mark = s.notices.len(); + let mark = s.notice_mark(); s.run("layout.import", &json!({"text": text.to_string()})).unwrap(); assert_eq!(cut_notice(&s, mark), 1); assert!(matches!( @@ -42337,8 +42423,8 @@ fn legends_label_layers() { // (The imported layout is the active one now; the rest goes to the first.) // The label follows its layer renamed, and goes with it removed, so a later layer of that // name isn't labelled unasked. - let lost = |s: &Session, from: usize| s.notices[from..].iter().filter(|n| n.text.contains("lost its label")).count(); - let mark = s.notices.len(); + let lost = |s: &Session, from: u64| s.notices_since(from).iter().filter(|n| n.text.contains("lost its label")).count(); + let mark = s.notice_mark(); s.run("layer.rename", &json!({"layer": "Rivers", "name": "Hidrografia"})).unwrap(); assert_eq!(labels(&s, id), [pair("Hidrografia", "Rios principais"), pair("Lakes", "Lagos")]); s.run("layer.remove", &json!({"layer": "Lakes"})).unwrap(); @@ -42349,7 +42435,7 @@ fn legends_label_layers() { // Its label is dropped, and said once for the four legends that had it (this one and the // three layouts imported above); following a rename or a removal is not. assert_eq!(lost(&s, mark), 1); - assert!(s.notices[mark..].iter().any(|n| n.text.contains("'Hidrografia', renamed 'Cities', lost its label in 4 legend(s)"))); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("'Hidrografia', renamed 'Cities', lost its label in 4 legend(s)"))); assert!(labels(&s, id).is_empty()); // A WMS or WMTS layer is labelled by name too. let wms = json!({"url": "https://maps.example.org/wms/{bbox-epsg-3857}", "name": "Soils", "overlay": true, "legend": "https://maps.example.org/legend.png"}); @@ -49185,11 +49271,12 @@ fn calculate_field_keeps_decimals_and_says_what_whole_numbers_cut() { // it, though as a decimal it rounds to -2^63, which is i64::MIN. texts(&mut s, ["-9223372036854775809", "-9223372036854775900", "+9223372036854775808"]); assert_eq!(calc(&mut s, "i", "t2"), (vec![past("3 results")], vec![V::Null; 3])); - // Words the decimal reader takes aren't numbers written as text: null, said as not numbers, - // not as past the range; a number too large for a decimal is past it. + // Words the decimal reader takes aren't numbers written as text: null, said as not a number + // or not finite, not as past the range; a number too large for a decimal is past it. texts(&mut s, ["NaN", "inf", "1e400"]); - let not_numbers = "Calculate Field: 'i' is null for 2 results that aren't numbers".to_string(); - assert_eq!(calc(&mut s, "i", "t2"), (vec![past("1 result"), not_numbers], vec![V::Null; 3])); + let not_numbers = "Calculate Field: 'i' is null for 1 result that isn't a number".to_string(); + let not_finite = "Calculate Field: 'i' is null for 1 result that isn't a finite number".to_string(); + assert_eq!(calc(&mut s, "i", "t2"), (vec![past("1 result"), not_numbers, not_finite], vec![V::Null; 3])); // With an exponent, text is read as a decimal: 0.25 loses its fraction, 3 is whole; "-" is // no number. texts(&mut s, ["2.5e-1", "3e0", "-"]); @@ -54250,12 +54337,12 @@ fn arrangements_are_saved_by_name() { let r = s.run("layout.arrangement", &json!({"save": "Copy", "arrangement": "mirrored"})).unwrap(); assert_eq!(r["saved"]["Copy"]["locator"], "top-right", "{r}"); // "arrangement" with "save" is read, not said to be ignored. - let mark = s.notices.len(); + let mark = s.notice_mark(); s.run("layout.arrangement", &json!({"save": "Print", "arrangement": "classic"})).unwrap(); assert!( - !s.notices[mark..].iter().any(|n| n.text.contains("ignores")), + !s.notices_since(mark).iter().any(|n| n.text.contains("ignores")), "{:?}", - s.notices[mark..].iter().map(|n| &n.text).collect::>() + s.notices_since(mark).iter().map(|n| &n.text).collect::>() ); s.run("layout.arrangement", &json!({"remove": "Print"})).unwrap(); // Taken by name, case aside, and named in the answer as it is kept. @@ -57244,3 +57331,47 @@ fn row_resolver_buffer_and_both_clip_inputs() { } } } + +/// A dated cloud-optimised GeoTIFF's file is named in its notices cut to 80 characters, and a cut +/// name ends in an ellipsis so it doesn't pass for the whole one. +#[test] +fn a_cog_tile_notice_marks_a_cut_file_name() { + let mut tile = rustgis_map::tiles::TileLayer::new("Dated", rustgis_map::tiles::TileKind::Cog, "https://example.com/a.tif"); + tile.time_url = Some("https://example.com/{date}.tif".into()); + let long = format!("https://example.com/{}.tif", "n".repeat(100)); + let said = crate::cmd::layer::cog_tile_where(&tile, &long); + assert!(said.ends_with("…)"), "{said}"); + assert_eq!(said.chars().filter(|c| *c == 'n').count(), 80, "{said}"); + assert_eq!(crate::cmd::layer::cog_tile_where(&tile, "https://example.com/short.tif"), "Dated (short.tif)"); +} + +/// A `file://` address isn't a local file a record is made for: the record's file is opened by +/// the path as written, so a path that passes the check is the path opened. +#[test] +fn a_file_address_is_not_a_local_file_to_publish() { + assert!(!crate::cmd::publish::local_file("file:///tmp/a.shp")); + assert!(!crate::cmd::publish::local_file("file:///C:/data/a.shp")); + assert!(crate::cmd::publish::local_file("/tmp/a.shp")); +} + +/// A delimited file that doesn't read is named once in the error, not by its path and again by +/// its name. +#[test] +fn an_unread_delimited_file_is_named_once() { + let dir = std::env::temp_dir().join(format!("rustgis-dat-named-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("summary.dat"); + std::fs::write(&path, b"just one column\nand another line\n").unwrap(); + let mut s = world(); + let e = s.run("layer.addData", &json!({"path": path})).unwrap_err(); + assert_eq!(e.matches("summary.dat").count(), 1, "{e}"); + assert!(e.contains("not recognised as delimited text"), "{e}"); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A transparency is given to the Assistant and plugins as set, not widened with f32 noise. +#[test] +fn a_transparency_reads_back_without_float_noise() { + assert_eq!(crate::cmd::project::percent(33.3), json!(33.3)); + assert_eq!(crate::cmd::project::percent(0.0), json!(0.0)); +} diff --git a/crates/engine/src/tests/write_notices.rs b/crates/engine/src/tests/write_notices.rs index 9a97b97b03..3acb75d0ec 100644 --- a/crates/engine/src/tests/write_notices.rs +++ b/crates/engine/src/tests/write_notices.rs @@ -351,7 +351,7 @@ fn write_notices_keep_the_ordinary_queue_bounded_and_marks_consistent() { s.notify("rolled-back edit", false); s.guarded("Inner", true, |s| { for i in 0..250 { - s.notify_written(format!("committed {i}"), false); + s.notify_written(format!("committed {i}")); } Err("inner failed".into()) })?; diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 22db0bfde5..92c77a530b 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -32,7 +32,7 @@ use crate::symbology::{Labeling, LineStroke, MarkerRotation, Picture, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; pub use source::{MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, is_drive_relative, is_relative}; -pub use structure::{MAX_BOOKMARKS, MAX_RELATIONS, ProjectBookmark, ProjectRelation}; +pub use structure::{MAX_BOOKMARKS, MAX_RELATIONS, ProjectBookmark, ProjectRelation, listed}; /// The most XML nodes a project or style is read with (a large project's file is some hundred /// thousand). @@ -1010,13 +1010,6 @@ fn project_notes(root: Node, report: &mut Report) { /// `effects`: the groups whose blending mode, draw effect is left out), and a drawing order of /// its own. fn group_notes(tree: &Tree, blended: &[String], effects: &[String], report: &mut Report) { - let listed = |names: &[&str]| { - let mut text = names.iter().take(8).copied().collect::>().join(", "); - if names.len() > 8 { - text.push_str(", …"); - } - format!("{}: {text}", names.len()) - }; if tree.folded > 0 { report.approximated( "", diff --git a/crates/map/src/qgis/structure.rs b/crates/map/src/qgis/structure.rs index b98b12d560..db6ddbc80b 100644 --- a/crates/map/src/qgis/structure.rs +++ b/crates/map/src/qgis/structure.rs @@ -5,7 +5,7 @@ use roxmltree::Node; use super::{Report, child, crs_of}; -/// The most bookmarks and relations an import reads. +/// The most bookmarks and relations an import reads; also the most bookmarks a map keeps. pub const MAX_BOOKMARKS: usize = 10_000; pub const MAX_RELATIONS: usize = 10_000; @@ -331,7 +331,7 @@ fn polygon_extent(wkt: &str) -> Option<[f64; 4]> { } /// Up to eight names, comma-separated, after their count. -fn listed(names: &[&str]) -> String { +pub fn listed(names: &[&str]) -> String { let mut text = names.iter().take(8).copied().collect::>().join(", "); if names.len() > 8 { text.push_str(", …"); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 66eea2f6c2..4014f5d8d6 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -1703,7 +1703,7 @@ fn trend(app: &mut RustGisApp, ui: &mut Ui, rasters: &[String]) { pub fn land_trend(app: &mut RustGisApp) -> bool { use std::sync::atomic::Ordering; let Some(r) = &app.workflow.trend.running else { return false }; - let Some(res) = r.result.lock().ok().and_then(|mut g| g.take()) else { return true }; + let Some(res) = r.result.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { return true }; let mut p = r.params.clone(); // A run the user cancelled stops quietly: no error for it. let cancelled = r.cancel.load(Ordering::Relaxed); diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index e386da7af3..1a638f292d 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -316,7 +316,7 @@ fn saved_accounts(app: &mut RustGisApp) -> Vec { #[cfg(not(target_arch = "wasm32"))] fn poll_sign_in(app: &mut RustGisApp, ctx: &egui::Context) { let Some((checking, slot)) = app.assistant.sign_in_read.as_ref() else { return }; - let Some(read) = slot.lock().ok().and_then(|mut s| s.take()) else { return }; + let Some(read) = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { return }; let checking = checking.clone(); app.assistant.sign_in_read = None; let Some(cfg) = app.assistant.agent.as_ref().map(|a| a.config.clone()).filter(Config::login) else { return }; @@ -559,7 +559,7 @@ fn sync_sign_in(app: &mut RustGisApp, ctx: &egui::Context) { } fn take(slot: &Reply) -> Option> { - slot.lock().ok().and_then(|mut s| s.take()) + slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() } /// Ends the agent threads on this computer (with every process they started), and the relay if @@ -718,7 +718,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } } #[cfg(not(target_arch = "wasm32"))] - if let Some(r) = app.assistant.signout.as_ref().and_then(|s| s.lock().ok().and_then(|mut s| s.take())) { + if let Some(r) = app.assistant.signout.as_ref().and_then(|s| s.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take()) { app.assistant.signout = None; if r.is_err() { app.assistant.login_error = Some( diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3e383aadd9..4613f48ade 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5187,7 +5187,7 @@ impl RustGisApp { dbf_notes.push(format!("{name}: {} rows couldn't be read and were left out", lost.rows)); } dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.name, &lost)); - // CSV holds a point a row, GPX a name for each feature and no areas; reading text back trims it or reads blanks as null. + // CSV holds a point a row, GPX a name for each feature and no areas; reading text back, CSV reads blanks as null and KML and GPX trim it. dbf_notes.extend(io::export_losses_notes(&ds, &ext, io::name_field(&ds), &name).map_err(|e| e.to_string())?); drop(ds); if let Some(note) = io::left_out_note(&name, &ext, left_out) { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index fa9e138008..83f88bbd54 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3377,7 +3377,7 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { return; } // An install that just finished: use the runner, and remember it. - let finished = app.gp.install.as_ref().and_then(|st| st.lock().ok().and_then(|mut s| s.result.take())); + let finished = app.gp.install.as_ref().and_then(|st| st.lock().unwrap_or_else(std::sync::PoisonError::into_inner).result.take()); if let Some(result) = finished { app.gp.install = None; match result.and_then(|path| app.run("gp.setGeolibre", json!({"path": path})).map(|_| path)) { @@ -3559,7 +3559,7 @@ fn geolibre_language(app: &mut RustGisApp, ui: &mut Ui) { // One download at a time, whatever the language now: a second one would take the first's // place, and the first's result (or failure) would never be shown. if let Some((_, slot)) = &app.gp.language_download { - let done = slot.lock().ok().and_then(|mut r| r.take()); + let done = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); match done { // A pack that names none of these tools (made for another runner version) would leave // them in English under Remove translations, without a word. diff --git a/crates/ui-egui/src/pluginsui.rs b/crates/ui-egui/src/pluginsui.rs index 583353111a..faee7af5de 100644 --- a/crates/ui-egui/src/pluginsui.rs +++ b/crates/ui-egui/src/pluginsui.rs @@ -278,7 +278,7 @@ pub(crate) fn fetch(app: &RustGisApp, url: &str, limit: usize, ctx: Option Option, String>> { - slot.lock().ok().and_then(|mut s| s.take()) + slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() } /// Whether the web app keeps installed plugins in its preferences (the desktop keeps them in diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rs index 126a6a59ef..5f578f32db 100644 --- a/crates/ui-egui/src/update.rs +++ b/crates/ui-egui/src/update.rs @@ -368,12 +368,19 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { app.update.result = Some(r.and_then(|body| parse_release(&body))); } #[cfg(not(target_arch = "wasm32"))] - if let Install::Downloading { version, slot, .. } = &app.update.install - && let Some(r) = slot.lock().ok().and_then(|mut s| s.take()) - { + let landed = match &app.update.install { + // A worker that panicked holding the slot still leaves what it put there. + Install::Downloading { version, slot, .. } => { + let taken = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + taken.map(|r| (version.clone(), r)) + } + _ => None, + }; + #[cfg(not(target_arch = "wasm32"))] + if let Some((version, r)) = landed { app.update.install = match r { - Ok(saved) => Install::Ready { version: version.clone(), saved, at_exit: false }, - Err(error) => Install::Failed { version: version.clone(), error, installing: false }, + Ok(saved) => Install::Ready { version, saved, at_exit: false }, + Err(error) => Install::Failed { version, error, installing: false }, }; } let current = env!("CARGO_PKG_VERSION"); diff --git a/crates/ui-egui/src/workspacepanes.rs b/crates/ui-egui/src/workspacepanes.rs index f5e8e52e5a..387f04c312 100644 --- a/crates/ui-egui/src/workspacepanes.rs +++ b/crates/ui-egui/src/workspacepanes.rs @@ -560,7 +560,7 @@ pub fn land_series(app: &mut RustGisApp) -> bool { app.ws.message = Some((tl!("The time series was stopped: another project was opened").to_string(), false)); return false; } - let Some((res, notes)) = r.result.lock().ok().and_then(|mut g| g.take()) else { return true }; + let Some((res, notes)) = r.result.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { return true }; let cancelled = r.control.is_cancelled(); app.ws.series_reading = None; // What reading it said, though it then failed; not for a read that was cancelled. @@ -628,7 +628,7 @@ fn area_under(line: &[egui::Pos2], base: f32, colour: Color32) -> egui::Mesh { pub fn land_summary(app: &mut RustGisApp) -> bool { use std::sync::atomic::Ordering; let Some(r) = &app.ws.reducing else { return false }; - let Some(res) = r.result.lock().ok().and_then(|mut g| g.take()) else { return true }; + let Some(res) = r.result.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { return true }; let (root, variable, name, id) = (r.run.root.clone(), r.run.variable.clone(), r.run.name.clone(), r.id); // A run the user cancelled stops quietly: no error for it. let cancelled = r.cancel.load(Ordering::Relaxed); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1920cb81f4..bf57ef029d 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -318,15 +318,18 @@ gp.batch={"tool":"buffer","inputs":["Cities","Rivers"],"outputPattern":"{input}_ - `"folder"`: on desktop and the command line, a folder whose `.shp`, `.geojson`, `.json`, `.gpkg`, `.fgb`, `.parquet`, `.geoparquet`, `.kml`, `.kmz`, `.gpx` and `.csv` files are run over in file-name order (byte order, so ASCII capitals come before lowercase letters). Subfolders and symbolic links are skipped, with a count. + A folder with more than 10,000 supported files is refused; split it into smaller folders. - `"outputPattern"` (or `"output_pattern"`): the name of each output layer, `"{input}_{tool}"` by default, where `{input}` is the layer's name or the file's name without its extension and `{tool}` the tool's id. It must include `{input}`. A name already taken gets a number (`_2`). Tools that change a layer in place or select features keep their own names. - `"params"`: the parameters every run shares. The batch input replaces a value given there for - the input parameter, with a notice. + the input parameter, and for the other names the tool reads it under (such as Join Field's + `target` beside `target_layer`), with a notice naming them. - `"param"` (or `"batch_param"`): the parameter each input goes to; by default the tool's first layer parameter, else `"input"`. +A batch runs at most 10,000 inputs; more are refused, so split them into smaller batches. One input failing doesn't stop the others. The result counts what `"succeeded"` and `"failed"`, names the `"outputs"` (layers or tables) and lists each failure in `"errors"`, with one notice for the failures. If every input fails, the batch is an error naming each input and why. What a