diff --git a/Cargo.toml b/Cargo.toml index 08d96bef30..2ada285a55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ serde = { version = "1", features = ["derive", "rc"] } # float_roundtrip: projects must read back the exact coordinates they wrote, or source-edit # baselines (row hashes) see every reopened row as changed. serde_json = { version = "1", features = ["raw_value", "float_roundtrip"] } +serde_ignored = "0.1" sha2 = "0.11" # JSON Schema of the project file, generated from the saved types (`cargo xtask schema`); only # behind the `schema` features, so the app, the browser build and the packages never compile it. diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index a32d71a83e..140c932c64 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -213,20 +213,42 @@ impl Strict { } } +/// Why [`run_strict`] stops the run: the message, and the result of the command when it ran but +/// [`Strict::check`] stopped the run after it (its effect happened, so a `--cmd` prints it). +struct Stop { + /// The result of a command that succeeded before the run was stopped. + kept: Option, + message: String, +} + +impl From for Stop { + /// A failure with no result kept. + fn from(message: String) -> Self { + Stop { kept: None, message } + } +} + +impl From for String { + /// The message alone, where the result isn't printed (a load, `--save`). + fn from(stop: Stop) -> Self { + stop.message + } +} + /// [`run`], then [`Strict::check`] when the run is strict: after a failure too, as a failed /// command still reports the losses that outlive its rollback (a counted omission). -fn run_strict(s: &mut Session, strict: Option<&Strict>, id: &str, p: Value) -> Result { +fn run_strict(s: &mut Session, strict: Option<&Strict>, id: &str, p: Value) -> Result { let before = strict.map(|_| s.losses_given().to_vec()); let out = run(s, id, p); if let (Some(strict), Some(before)) = (strict, before) && let Err(said) = strict.check(s, &before, id) { return Err(match out { - Err(e) => format!("{e}\n{said}"), - Ok(_) => said, + Err(e) => Stop::from(format!("{e}\n{said}")), + Ok(kept) => Stop { kept: Some(kept), message: said }, }); } - out + Ok(out?) } fn is_project(path: &str) -> bool { @@ -1293,10 +1315,18 @@ fn cli() -> ExitCode { Some((id, json)) => (id, serde_json::from_str(json).map_err(|e| format!("{id}: bad JSON: {e}"))?), None => (c.as_str(), Value::Null), }; - let out = run_strict(&mut s, strict, id, p)?; - if !out.is_null() { + // A command that ran before a strict stop has its result printed too: its + // effect (a file written) happened. + let (out, stop) = match run_strict(&mut s, strict, id, p) { + Ok(out) => (Some(out), None), + Err(stop) => (stop.kept, Some(stop.message)), + }; + if let Some(out) = out.filter(|out| !out.is_null()) { print(&out); } + if let Some(stop) = stop { + return Err(stop); + } } } if let Some(p) = opt(&args, "--save") { diff --git a/apps/rustgis-cli/tests/integration/strict.rs b/apps/rustgis-cli/tests/integration/strict.rs index 1a723cea67..cf824c358d 100644 --- a/apps/rustgis-cli/tests/integration/strict.rs +++ b/apps/rustgis-cli/tests/integration/strict.rs @@ -78,6 +78,8 @@ fn a_strict_run_stops_at_a_command_that_loses_data() { assert!(err.contains("stopped after edit.calculateField") && err.contains("changed.truncated (1 notice)"), "{err}"); let printed = String::from_utf8_lossy(&out.stdout); assert!(!printed.contains("\"cores\""), "the command after it didn't run: {printed}"); + // The command the run stopped after did run: its result is printed before the stop. + assert!(printed.trim_end().ends_with("\"rows\": 2\n}"), "the stopping command's result: {printed}"); } /// A failed command still reports the losses its rollback can't take back (a counted omission): diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index da83928b7b..926d18479f 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -977,9 +977,10 @@ pub struct Similarity { /// Rows ranked by how close their numeric attributes are to a row's (z-scored Euclidean /// distance over `fields`), nearest first, excluding the row itself. Counts progress and checks -/// Cancel between rows and within wide vectors. The stable library sort is one indivisible step, -/// checked immediately before and after; equal-distance rows keep their original order. -/// Non-finite standardization statistics are refused before ranking any candidates. +/// Cancel between rows and within wide vectors. Only the `n` nearest so far are kept (a heap of +/// `n` entries however many rows the layer has; `data.similar` takes `n` up to 1,000); sorting +/// those at the end is one indivisible step, checked immediately before and after. Equal-distance rows keep their original +/// order. Non-finite standardization statistics are refused before ranking any candidates. pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result { use crate::control; control::begin(ds.features.len().saturating_mul(fields.len().saturating_mul(3).saturating_add(1))); @@ -1036,7 +1037,8 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result::with_capacity(n.min(ds.features.len()).saturating_add(1)); let mut skipped = 0; for r in 0..ds.features.len() { control::check()?; @@ -1057,17 +1059,51 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result>()? .sqrt(); - out.push((r, distance)); + let ranked = Ranked { distance, row: r }; + if nearest.len() < n { + nearest.push(ranked); + } else if let Some(mut top) = nearest.peek_mut() + && ranked < *top + { + *top = ranked; + } } } control::check()?; - out.sort_by(|a, b| a.1.total_cmp(&b.1)); + let out: Vec<(usize, f64)> = nearest.into_sorted_vec().into_iter().map(|r| (r.row, r.distance)).collect(); control::check()?; - out.truncate(n); control::finish(); Ok(Similarity { matches: out, skipped }) } +/// A candidate of [`similar`], ordered by distance (`total_cmp`), then by row, as a stable sort by +/// distance of rows taken in order leaves them. +#[derive(Clone, Copy, Debug)] +struct Ranked { + distance: f64, + row: usize, +} + +impl Ord for Ranked { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.distance.total_cmp(&other.distance).then(self.row.cmp(&other.row)) + } +} + +impl PartialOrd for Ranked { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for Ranked { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == std::cmp::Ordering::Equal + } +} + +impl Eq for Ranked {} + fn radius_scale(at: Coord) -> f64 { 1.0 / at.y.to_radians().cos().max(0.01) } @@ -1770,6 +1806,28 @@ mod tests { assert!(control.looked() > 0); } + /// The bounded ranking keeps exactly what a full stable sort by distance, cut to `n`, keeps: + /// the same rows, in the same order (ties by row), with the same distance bits. + #[test] + fn similar_keeps_the_n_nearest_as_a_full_sort_would() { + let mut ds = Dataset::new("v", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + // Values 0..5 repeated: many candidates at each distance from row 0. + for i in 0..40 { + ds.push(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![Value::Int(i % 5)]); + } + let all = similar(&ds, 0, &[0], usize::MAX).unwrap_or_else(|e| panic!("{e}")).matches; + assert_eq!(all.len(), 39); + let mut reference = all.clone(); + reference.sort_by_key(|(row, _)| *row); + reference.sort_by(|a, b| a.1.total_cmp(&b.1)); + let bits = |v: &[(usize, f64)]| v.iter().map(|(r, d)| (*r, d.to_bits())).collect::>(); + assert_eq!(bits(&all), bits(&reference)); + for n in [0, 1, 5, 8, 12, 39, 100] { + let got = similar(&ds, 0, &[0], n).unwrap_or_else(|e| panic!("{e}")).matches; + assert_eq!(bits(&got), bits(&reference[..n.min(reference.len())]), "n = {n}"); + } + } + #[test] fn routes_points_profiles_and_similarity() { // A square of roads with a slow diagonal. diff --git a/crates/data/src/ogc/dataset.rs b/crates/data/src/ogc/dataset.rs index 46ba131033..92c26905f6 100644 --- a/crates/data/src/ogc/dataset.rs +++ b/crates/data/src/ogc/dataset.rs @@ -122,7 +122,7 @@ impl DatasetDiscovery { /// A snapshot of counted omissions, including partial listings and failed traversals. pub fn notes(&self) -> Vec { - self.omissions.iter().map(|(reason, count)| format!("{count} {reason}")).collect() + self.omissions.iter().map(|(reason, count)| counted(*count, reason)).collect() } /// Adds counts for known work abandoned by a terminal discovery error or budget. A document @@ -141,7 +141,7 @@ impl DatasetDiscovery { }; *left.entry(kind).or_default() += count; } - notes.extend(left.into_iter().map(|(kind, count)| format!("{count} {kind} were left out: dataset discovery stopped"))); + notes.extend(left.into_iter().map(|(kind, count)| counted(count, &format!("{kind} were left out: dataset discovery stopped")))); notes } @@ -605,3 +605,22 @@ impl DatasetDiscovery { service.layers.push(candidate.layer); } } + +/// `count` and `reason` ("tileset documents were left out: …"), in the singular for one: the first +/// "s were " of every reason, a regular plural, becomes " was " ("1 tileset document was left out"). +fn counted(count: usize, reason: &str) -> String { + match reason.split_once("s were ") { + Some((what, why)) if count == 1 => format!("1 {what} was {why}"), + _ => format!("{count} {reason}"), + } +} + +#[cfg(test)] +mod tests { + #[test] + fn one_omission_is_said_in_the_singular_and_two_in_the_plural() { + let reason = "tileset documents were left out: no usable JSON link"; + assert_eq!(super::counted(1, reason), "1 tileset document was left out: no usable JSON link"); + assert_eq!(super::counted(2, reason), "2 tileset documents were left out: no usable JSON link"); + } +} diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index f2e715f1b6..bed6e247ce 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -408,17 +408,10 @@ fn read_layout(r: Sparse) -> Result { lost.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, super::geotiff::NO_EPSG_GEOGRAPHIC)); } // Its bytes asked for when not read yet, as the other tags' are. - let copyright = match tag(&mut dec, Tag::Copyright)? { - Ok(None) => None, - Ok(Some(v)) => match v.into_string() { - Ok(c) => Some(c.trim().to_string()), - Err(e) => { - lost.push(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out")); - None - } - }, - Err(e) => { - lost.push(format!("its Copyright tag: it can't be read ({e}), so it is left out")); + let copyright = match super::geotiff::copyright_of(tag(&mut dec, Tag::Copyright)?) { + Ok(c) => c, + Err(said) => { + lost.push(said); None } }; diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 9d7d18b1c4..f5f4e33449 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -345,7 +345,15 @@ pub(crate) const NO_EPSG_GEOGRAPHIC: &str = /// The file's Copyright tag, trimmed, or why it is left out (`Err`); `Ok(None)` without one. pub(crate) fn copyright_tag(dec: &mut Decoder) -> std::result::Result, String> { - match dec.find_tag(Tag::Copyright).map(|v| v.map(|v| v.into_string())) { + copyright_of(dec.find_tag(Tag::Copyright)) +} + +/// The Copyright tag as `found` (however it was read): trimmed, or why it is left out (`Err`); +/// `Ok(None)` without one. Shared by a whole read and the in-place layout's (`cog::read_layout`). +pub(crate) fn copyright_of( + found: std::result::Result, impl std::fmt::Display>, +) -> std::result::Result, String> { + match found.map(|v| v.map(|v| v.into_string())) { Ok(None) => Ok(None), Ok(Some(Ok(c))) => Ok(Some(c.trim().to_string())), Ok(Some(Err(e))) => Err(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out")), diff --git a/crates/data/tests/integration/datum_grids.rs b/crates/data/tests/datum_grids.rs similarity index 100% rename from crates/data/tests/integration/datum_grids.rs rename to crates/data/tests/datum_grids.rs diff --git a/crates/data/tests/integration/main.rs b/crates/data/tests/integration/main.rs index 3531f65f12..1e7ae09df4 100644 --- a/crates/data/tests/integration/main.rs +++ b/crates/data/tests/integration/main.rs @@ -1,7 +1,6 @@ //! Consolidated integration tests (one binary per crate to cut link time in CI). mod date_properties; -mod datum_grids; #[cfg(not(target_arch = "wasm32"))] mod extent_query_properties; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index e3b615c617..e972447f4e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -18,7 +18,7 @@ tiny-skia = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } # The keys a project file has that this version doesn't read, to say what opening it left out. -serde_ignored = "0.1" +serde_ignored = { workspace = true } log = { workspace = true } web-time = { workspace = true } base64 = { workspace = true } diff --git a/crates/engine/src/cmd/connections.rs b/crates/engine/src/cmd/connections.rs index 42d09b2732..2038461ffb 100644 --- a/crates/engine/src/cmd/connections.rs +++ b/crates/engine/src/cmd/connections.rs @@ -68,7 +68,7 @@ pub fn commands() -> Vec { ), C::new("connection.forgetPassword", "Forget Saved Password", "Home › Add › Data Sources", forget_password).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)).view().params(r#"{"id": "a database connection's id or name"}"#), C::new("connection.test", "Test Connection", "Home › Add › Data Sources", test).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)).view().params( - r#"{"id"?: "a connection's id or name", "kind"?: "postgres"|"mysql"|"sqlserver"|"service"|"wms"|"wmts"|"wfs"|"wcs"|"ogcapi"|"arcgis"|"csw"|"stac"|"s3", "name"?: text, "group"?: text, "address"?: text, "options"?: "an unsaved connection, as connection.new (when no id)", "auth"?: text, "user"?: text, "keyName"?: "as connection.new (when no id)", "password"?: "for a named database, authentication refusal restores prior session credentials; a later listing failure keeps the new password; never persisted. A saved web service's: as connection.login (logs in first)", "apiKey"?: "a saved web service's, as connection.login (logs in first)", "allowInsecure"?: "as connection.login", "accessKeyId"?: text, "secretAccessKey"?: text, "sessionToken"?: "as connection.login (logs in first)", "probe"?: "true: only the address the test reads, {fetch} (null for databases, which their driver tests), with tile: {zoom, vector} for an XYZ sample", "answer"?: "non-database kinds only, not XYZ tiles: fetched text (including S3 bucket or object listing XML) that address returned, parsed without a request (no network request then); databases ignore answer and test through their driver"} (a direct XYZ test returns result: {kind: "xyz", tile: [z,x,y], status: "received" or "missing"}; missing is not a pass) → a database's result has {count, layers}, and for an Esri enterprise geodatabase on SQL Server geodatabase: {owner, release, note? (when its catalog or its list of spatial columns was cut short)}, or geodatabaseProblem: why its catalog couldn't be read"#, + r#"{"id"?: "a connection's id or name", "kind"?: "postgres"|"mysql"|"sqlserver"|"service"|"wms"|"wmts"|"wfs"|"wcs"|"ogcapi"|"arcgis"|"csw"|"stac"|"s3", "name"?: text, "group"?: text, "address"?: text, "options"?: "an unsaved connection, as connection.new (when no id)", "auth"?: text, "user"?: text, "keyName"?: "as connection.new (when no id)", "password"?: "for a named database, authentication refusal restores prior session credentials; a later listing failure keeps the new password; never persisted. A saved web service's: as connection.login (logs in first)", "apiKey"?: "a saved web service's, as connection.login (logs in first)", "allowInsecure"?: "as connection.login", "accessKeyId"?: text, "secretAccessKey"?: text, "sessionToken"?: "as connection.login (logs in first)", "probe"?: "true: only the address the test reads, {fetch} (null for databases, which their driver tests), with tile: {zoom, vector} for an XYZ sample", "answer"?: "non-database kinds only, not XYZ tiles: fetched text (including S3 bucket or object listing XML) that address returned, parsed without a request (no network request then); databases ignore answer and test through their driver"} (a direct XYZ test returns result: {kind: "xyz", tile: [z,x,y], status: "received" or "missing"}; missing is not a pass; desktop only: in the browser a direct XYZ test is refused, so pass probe and fetch the tile in the app) → a database's result has {count, layers}, and for an Esri enterprise geodatabase on SQL Server geodatabase: {owner, release, note? (when its catalog or its list of spatial columns was cut short)}, or geodatabaseProblem: why its catalog couldn't be read"#, ), C::new("connection.browse", "Browse Connection", "Home › Add › Data Sources", browse::browse).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)).view().params( r#"{"id": "a connection's id or name", "node"?: "a child's node, as a listing gives it (the connection's top level when absent)", "probe"?: "true: only the address this level reads, {fetch} (null: read without a fetch, or by the database driver); an S3 connection logs in first, as connection.test does", "answer"?: "what that address returned, when the app fetched it", "documents"?: [{"url": "a further document a listing asked for (next)", "text": "its answer"}]} → {connection, node, children: [{key, name, what, detail?, node? (browse it), children? (listed already), add? {command, params}: the command that adds it}], truncated?, matched?, notes?, service? {url, type}, next? (fetch it, then ask again with answer and documents)}. Database roots list schemas; open a schema node to list its tables. A geodatabase's root lists feature datasets, feature classes, tables and other spatial tables (open a feature dataset node to list its classes); if its catalog couldn't be read, the database browses as plain SQL Server, with a note."#, @@ -1374,7 +1374,7 @@ fn test_xyz(s: &mut Session, p: &Value, c: &Connection, mut out: Value, sample: return Err(tile_test::TEXT_ANSWER.into()); } #[cfg(target_arch = "wasm32")] - return Err("An XYZ sample tile must be fetched by the app.".into()); + return Err("In the browser, an XYZ sample tile must be fetched by the app: test with probe: true".into()); #[cfg(not(target_arch = "wasm32"))] { use crate::render::rustgis_tiles::cache; diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 15459ccde4..211c2bf768 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -269,7 +269,7 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: // (`WriteLosses`), and its type. let (cuts, unread) = calculation_rules(&l.design, &mut l.dataset, &metadata, &rows, 0); // Validation (`refusal`), against each row's state before the first edit. - let constraints = constraint_rules(&l.design, &metadata); + let (constraints, unread_constraints) = constraint_rules(&l.design, &metadata); let mut original = HashMap::new(); if !l.design.domains.is_empty() || !l.design.contingent.is_empty() { // A row edited more than once still validates against its state before the first edit. @@ -356,6 +356,17 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: false, ); } + // Said only for an edit with rows: one with none (a deletion) checks nothing anyway. + if !rows.is_empty() && !unread_constraints.is_empty() { + s.notify( + format!( + "{layer}: {} constraint rule(s) skipped because they no longer read, so edits weren't checked against them: {}", + unread_constraints.len(), + unread_constraints.join(", ") + ), + false, + ); + } Ok(()) } @@ -402,20 +413,24 @@ pub(crate) fn calculation_rules( (cuts, unread) } -/// `design`'s constraint rules that read against `metadata` (the layer's fields): name, -/// expression as written, and parsed. +/// A constraint rule that reads: its name, its expression as written, and parsed. +pub(crate) type ConstraintRule = (String, String, rustgis_data::query::Expr); + +/// `design`'s constraint rules that read against `metadata` (the layer's fields), and the names +/// of those that no longer read (a hand-edited file, one past the length limit from an earlier +/// version, a field gone), which are skipped and for the caller to say. pub(crate) fn constraint_rules( design: &rustgis_map::design::Design, metadata: &rustgis_data::Dataset, -) -> Vec<(String, String, rustgis_data::query::Expr)> { - design - .rules - .iter() - .filter(|r| r.kind == RuleKind::Constraint) - .filter_map(|rule| { - rustgis_data::query::parse(&rule.expression, metadata).ok().map(|e| (rule.name.clone(), rule.expression.clone(), e)) - }) - .collect() +) -> (Vec, Vec) { + let (mut read, mut unread) = (Vec::new(), Vec::new()); + for rule in design.rules.iter().filter(|r| r.kind == RuleKind::Constraint) { + match rustgis_data::query::parse(&rule.expression, metadata) { + Ok(e) => read.push((rule.name.clone(), rule.expression.clone(), e)), + Err(_) => unread.push(rule.name.clone()), + } + } + (read, unread) } /// The error an edit of row `r` of `ds` is refused with, by the first of `design`'s checks it @@ -3173,7 +3188,7 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { #[cfg(not(target_arch = "wasm32"))] if ahead.is_none() && !inputs.is_empty() && s.statistics_window_thread == Some(std::thread::current().id()) { return Err( - "Topology validation needs the desktop background read queue; run Error Inspector or a direct MCP topology.validate request" + "Topology validation needs the desktop background read queue; run Error Inspector or a direct MCP topology.validate request. In desktop scripts, run file or network setup separately before the validating script." .into(), ); } @@ -3279,18 +3294,8 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { details.push(NoticeText::format("{layer}: {error}", [("layer", input.layer.clone().into()), ("error", error.clone().into())])); } } - if !seen.is_empty() { - let more = seen.len() - details.len(); - let mut layers = NoticeText::list(details); - if more > 0 { - layers = NoticeText::format("{layers}; {count} more layers", [("layers", layers), ("count", more.to_string().into())]); - } - let key = if seen.len() == 1 { - "{count} layer with an unreadable definition query; reading without that query: {layers}" - } else { - "{count} layers with unreadable definition queries; reading without those queries: {layers}" - }; - s.notify_text(NoticeText::format(key, [("count", seen.len().to_string().into()), ("layers", layers)]), false); + if let Some(notice) = NoticeText::unreadable_queries(seen.len(), details) { + s.notify_text(notice, false); } Ok(json!({"errors": n, "first": out, "incomplete": incomplete})) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 50c24f0217..b457d3a638 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1948,7 +1948,8 @@ pub fn preview_calculation( // The layer's fields, which its rules are read against, and its constraint rules. let prepared = ruled.map(|d| { let metadata = rustgis_data::Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone()); - let constraints = super::design::constraint_rules(d, &metadata); + // Those that no longer read are said by the edit itself, not by this preview. + let (constraints, _) = super::design::constraint_rules(d, &metadata); (d, metadata, constraints) }); // What the layer's rules leave in `field` of `row` with `value` written (the value and what diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 212c97836b..38d8446506 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -324,7 +324,7 @@ fn build_package( if !photos.missing.is_empty() { let named = &photos.missing; losses.push(format!( - "{} photo(s) a photos field names aren't files on this computer by their full path, so they stayed out of the field package: {}", + "{} photo(s) a photos field names aren't on this computer (or aren't named by a full path), so they stayed out of the field package: {}", named.len(), some_of(named) )); @@ -1337,7 +1337,12 @@ fn unpacked_index(folder: &Path, package: &str) -> Result d.next().is_some(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(e) => return Err(format!("{}: {e}", folder.display())), + }; return if photos { Err(format!("{}: missing beside the photos", file.display())) } else { Ok(std::collections::HashMap::new()) }; } let bytes = crate::project::read_file(&file, MAX_INDEX)?; @@ -2875,7 +2880,7 @@ mod tests { assert!(entries.iter().any(|(n, b)| n == "photos/home-00002.jpg" && b == b"of a feature deleted in the field")); // The two named that aren't files here (one by no full path) are counted, for the sender // and the crew. - let expected = "2 photo(s) a photos field names aren't files on this computer by their full path"; + let expected = "2 photo(s) a photos field names aren't on this computer (or aren't named by a full path)"; let said: Vec = home.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert_eq!(said.iter().filter(|t| t.starts_with(expected) && t.contains("relative.jpg")).count(), 1, "{said:?}"); let unpacked = temp.path().join("field"); @@ -3054,6 +3059,33 @@ mod tests { assert!(said.iter().any(|t| t.starts_with("The photo index of the field package this map came from couldn't be read")), "{said:?}"); } + /// The photos folder of an unpacked package removed by hand since: sending back says the + /// photo isn't on this device, as for any absent file, not that the photo index is damaged. + #[test] + fn a_removed_photos_folder_is_no_photos_not_a_damaged_index() { + let temp = Temp::new("photos-gone"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let photo = temp.path().join("site.jpg"); + std::fs::write(&photo, b"a picture").unwrap(); + home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": photo.display().to_string()})).unwrap(); + let (_, out) = package(&mut home, &json!({"name": "Gone", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); + let unpacked = temp.path().join("field"); + let text = unpack_into(&out, &unpacked).unwrap().0; + let mut field = opened(project_in(&text, &unpacked).unwrap()); + field.opened_package = Some(temp.path().join("sent.rgisfield")); + let there = unpacked.join("photos").join("home-00001.jpg"); + field.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": there.display().to_string()})).unwrap(); + std::fs::remove_dir_all(unpacked.join("photos")).unwrap(); + let mark = field.notice_mark(); + package(&mut field, &Value::Null).unwrap(); + let said: Vec = field.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(!said.iter().any(|t| t.contains("couldn't be read")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("aren't on this device")), "{said:?}"); + } + /// Unpacked into a folder whose name isn't UTF-8, a photo from home keeps its name at home /// (no path the project holds can name the unpacked file), and that is said: the way back then /// sees no edit in it. Apple's file system refuses such a name, so this runs on other Unix diff --git a/crates/engine/src/cmd/field_changes.rs b/crates/engine/src/cmd/field_changes.rs index 452ae8fe1a..6a6f39c2fb 100644 --- a/crates/engine/src/cmd/field_changes.rs +++ b/crates/engine/src/cmd/field_changes.rs @@ -731,7 +731,8 @@ pub(crate) fn list(map: &rustgis_map::Map, package: &str) -> Result = theirs.features.rows().enumerate().filter(|(_, r)| wanted.contains(&r.id())).map(|(i, r)| (r.id(), i)).collect(); let mut at: HashMap = HashMap::new(); - // A feature added in the field keeps its id while home doesn't use it: a replacement for one - // that home uses is taken above every id the field added, so it never takes a free one. + // A feature added in the field keeps its id when it is above every id the source layer had or + // keeps new ones above, and no row uses it ([`id_at_home`]); otherwise it takes the next free + // one above every id the field added and home has, so it never takes a free one below them. let mut top = lc.added.iter().copied().max().unwrap_or(0).max(sl.dataset.features.highest_id()); for (i, r) in sl.dataset.features.rows().enumerate() { top = top.max(r.id()); @@ -1146,11 +1148,13 @@ pub(crate) fn id_at_home(own: u64, home_top: u64, taken: bool, top: u64, layer: Ok((id, renumbered)) } -/// The refusal when a feature added in the field needs a new id and none is left above the -/// layer's highest (`u64::MAX`): the command fails, and the project is put back as it was. +/// The refusal when a feature added offline or in the field needs a new id and none below +/// `i64::MAX` (the largest a GeoPackage or PostGIS feature can have) is left above the highest id +/// the layer and the added features have: the command (Bring Back or Sync) fails, and the project +/// is put back as it was. Worded for either command, as both reach it through [`id_at_home`]. pub(crate) fn exhausted(layer: &str) -> String { format!( - "cannot bring back layer '{layer}': a feature added in the field needs an id below {}, the largest a GeoPackage or PostGIS feature can have, and none is left above the layer's highest. Nothing was changed", + "layer '{layer}': a feature added offline or in the field needs an id below {}, the largest a GeoPackage or PostGIS feature can have, and none is left above the highest id the layer and the added features have. Nothing was changed", i64::MAX ) } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 3d5181bc1a..085323169a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -555,8 +555,8 @@ pub fn plugin_start(s: &mut Session, tool: &str, params: &Value) -> Result let closing = ring.then(|| part.first().zip(part.last())).flatten().filter(|(a, b)| a != b).map(|(a, b)| (*b, *a)); part.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).chain(closing) } + /// The edges of a part as [`edges`] gives them, by the indices of their two ends. + fn edge_ends(part: &[Coord], ring: bool) -> impl Iterator { + let n = part.len(); + let closing = (ring && n > 0 && part.first() != part.last()).then(|| (n - 1, 0)); + (1..n).map(|i| (i - 1, i)).chain(closing) + } let (to_lonlat, into, back) = (original.lonlat_conversion()?, Crs::LonLat.to(work)?, work.to(Crs::LonLat)?); let (mut n, mut far) = (0usize, 0.0f64); for (i, (f, c)) in original.features.rows().zip(converted.features.rows()).enumerate() { @@ -2313,8 +2321,21 @@ pub(crate) fn bent_edges(original: &Dataset, converted: &Dataset, work: Crs) -> } let (Some(g), Some(h)) = (f.geometry(), c.geometry()) else { continue }; for ((part, ring), (held, _)) in parts(g).into_iter().zip(parts(h)) { - for ((a, b), (c0, c1)) in edges(part, ring).zip(edges(held, ring)) { - let (Some(a), Some(b)) = (to_lonlat.point(a), to_lonlat.point(b)) else { continue }; + // Each vertex converted once, not once for each edge it ends, keeping only the last + // one converted and the first (for a ring's closing edge): the edges come in order. + let first = part.first().and_then(|c| to_lonlat.point(*c)); + let mut last: Option<(usize, Option)> = None; + let mut at = |i: usize| match last { + _ if i == 0 => first, + Some((j, ll)) if j == i => ll, + _ => { + let ll = part.get(i).and_then(|c| to_lonlat.point(*c)); + last = Some((i, ll)); + ll + } + }; + for ((ia, ib), (c0, c1)) in edge_ends(part, ring).zip(edges(held, ring)) { + let (Some(a), Some(b)) = (at(ia), at(ib)) else { continue }; let (pa, pb) = (lonlat_to_plane(a), lonlat_to_plane(b)); // (Also skipped: a length that is no number, a coordinate being missing.) let length = (pb.x - pa.x).hypot(pb.y - pa.y); @@ -2783,6 +2804,8 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc 0 { s.notify(format!("folder '{folder}': {unreadable} unreadable directory entries skipped"), true); } + if special > 0 { + s.notify(format!("folder '{folder}': {special} special file(s) (not regular files) skipped"), false); + } files.sort(); targets.extend(files); } @@ -3626,8 +3652,8 @@ pub(crate) fn execute( #[cfg(not(target_arch = "wasm32"))] let control = current.as_ref().unwrap_or(control); let t0 = now_ms(); - // A look at Cancel as the work's own are (counted for a test's control): a model's or script's - // tool on the copy stops here when cancelled between steps. + // A look at Cancel, counted as the work's own checks are (for a test's control): a model's or + // script's tool on the copy stops here when cancelled between steps. if rustgis_data::progress::Probe::cancelled(control.as_ref()) { let e = format!("{} was cancelled before it started", spec.name); return apply_with(s, run_of(t0), kept(), Err(e), 0, opts); diff --git a/crates/engine/src/cmd/group_file.rs b/crates/engine/src/cmd/group_file.rs index ec458cd1e9..b57107c6ba 100644 --- a/crates/engine/src/cmd/group_file.rs +++ b/crates/engine/src/cmd/group_file.rs @@ -148,7 +148,8 @@ pub(crate) fn output_within(s: &mut Session, p: &Value, out: Output<'_>) -> Resu let mut budget = super::items::MAX_EMBED; let layers: Vec = layers.into_iter().map(|l| super::items::embed_layer(l, &mut budget)).collect(); let linked: Vec<&str> = layers.iter().filter(|l| l.linked_file().is_some()).map(|l| l.name.as_str()).collect(); - let linked = super::items::linked_said("Save Layer File", "the layer file", &linked); + let edited: Vec<&str> = layers.iter().filter(|l| l.edits_saved_outside()).map(|l| l.name.as_str()).collect(); + let linked = super::items::linked_said("Save Layer File", "the layer file", &linked, &edited); let name = groups.first().map(|g| g.name.clone()).unwrap_or_default(); let bytes = super::items::durable_bytes_with(s, layers, |layers| crate::project::group_file_within(&groups, layers, out))?; Ok((name, bytes, linked)) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 7993e5fdfd..a2de77b360 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -531,30 +531,48 @@ const MAX_LINKED_NAMED: usize = 5; /// package is delivered: the desktop app builds it before its Save dialog, the browser before its /// download. fn left_linked<'a>(what: &str, maps: impl IntoIterator) -> Option { - let names: Vec<&str> = maps - .into_iter() - .flat_map(|m| { - let layers = m.layers.iter().filter(|l| l.linked_file().is_some()).map(|l| l.name.as_str()); - layers.chain(m.tiles.iter().filter(|t| t.archive_file().is_some()).map(|t| t.name.as_str())) - }) - .collect(); - linked_said(what, "the package", &names) + let (mut names, mut edited) = (Vec::new(), Vec::new()); + for m in maps { + names.extend(m.layers.iter().filter(|l| l.linked_file().is_some()).map(|l| l.name.as_str())); + names.extend(m.tiles.iter().filter(|t| t.archive_file().is_some()).map(|t| t.name.as_str())); + edited.extend(m.layers.iter().filter(|l| l.edits_saved_outside()).map(|l| l.name.as_str())); + } + linked_said(what, "the package", &names, &edited) } -/// What [`left_linked`] says of the layers `names` left linked to files outside `holder` (the -/// package, or a layer file holding a group, #2870); `None` when there are none. -pub(crate) fn linked_said(what: &str, holder: &str, names: &[&str]) -> Option { - if names.is_empty() { - return None; - } +/// `names`, at most [`MAX_LINKED_NAMED`] of them listed and the rest counted. +fn listed(names: &[&str]) -> String { let mut listed = names[..names.len().min(MAX_LINKED_NAMED)].join(", "); if names.len() > MAX_LINKED_NAMED { listed.push_str(&format!(" and {} more", names.len() - MAX_LINKED_NAMED)); } - Some(format!( - "{what}: {} layer(s) stay linked to files outside {holder}, so it opens without them on another computer: {listed}", - names.len() - )) + listed +} + +/// What [`left_linked`] says of the layers `names` left linked to files outside `holder` (the +/// package, or a layer file holding a group, #2870), and of those `edited` that hold their +/// features but save their edits to a GeoPackage outside it ([`rustgis_map::Layer::edits_saved_outside`]); +/// `None` when there are none. +pub(crate) fn linked_said(what: &str, holder: &str, names: &[&str], edited: &[&str]) -> Option { + let linked = (!names.is_empty()).then(|| { + format!( + "{} layer(s) stay linked to files outside {holder}, so it opens without them on another computer: {}", + names.len(), + listed(names) + ) + }); + let saved = (!edited.is_empty()).then(|| { + format!( + "{} layer(s) edited from a GeoPackage keep their features but save their edits to a file outside {holder}, so Save Edits needs that file on another computer: {}", + edited.len(), + listed(edited) + ) + }); + match (linked, saved) { + (None, None) => None, + (Some(one), None) | (None, Some(one)) => Some(format!("{what}: {one}")), + (Some(linked), Some(saved)) => Some(format!("{what}: {linked}; {saved}")), + } } /// The most maps one `map.import` adds. @@ -1088,10 +1106,11 @@ pub(super) fn layer_template(s: &mut Session, p: &Value) -> CmdResult { }; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(title); let mut ds = Dataset::new(name, gt, fields); - // Held in the project's coordinate system, when it has one (#2032 C3a). + // Held in the project's coordinate system, when it has one (#2032 C3a), named as its own + // unless that is longitude/latitude, which a dataset names as none (`Dataset::crs`). // One that doesn't convert to longitude/latitude, which the map draws through, is said. if let Some(crs) = s.project.coordinate_system - && let Err(e) = ds.hold_as(crs, Some(crs)) + && let Err(e) = ds.hold_as(crs, (crs != rustgis_data::raster::Crs::LonLat).then_some(crs)) { s.notify(format!("Layer '{name}' is held in longitude/latitude, not the project's coordinate system: {e}"), false); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5b908de2d..5671433851 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MiB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), @@ -5566,7 +5566,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { } } -/// The most octets a `"bytes"` range may ask for (64 MB): a record of a model's file, not the file. +/// The most octets a `"bytes"` range may ask for (64 MiB): a record of a model's file, not the file. pub const MAX_RANGE: u64 = 64 << 20; /// The range `layer.addUrl` is asked for (`"bytes": [first, last]`, octets counted from 0, both @@ -5596,7 +5596,7 @@ pub fn byte_range(p: &Value, url: &str) -> Result, String> { return Err(format!("\"bytes\": the first octet ({first}) comes after the last ({last})")); } if last - first >= MAX_RANGE { - return Err(format!("\"bytes\": {} octets asked for, more than a range may have (64 MB)", (last - first).saturating_add(1))); + return Err(format!("\"bytes\": {} octets asked for, more than a range may have (64 MiB)", (last - first).saturating_add(1))); } let path = url.split(['?', '#']).next().unwrap_or(url); if !rustgis_data::raster::grib::is_grib_name(path) { @@ -7930,18 +7930,29 @@ 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' {layers} {names} removed, so their labels are placed as auto until a layer of that name comes back"), - false, - ); + let said = if count == 1 { + format!( + "Labels: the line layer {names} that perpendicular labels are square to was removed, so their labels are placed as auto until a layer of that name comes back" + ) + } else { + format!( + "Labels: {count} line layers {names} that perpendicular labels are square to were removed, so their labels are placed as auto until a layer of that name comes back" + ) + }; + s.notify(said, false); } if !guided.is_empty() { let (count, names) = (guided.len(), guided.join(", ")); - s.notify( - format!("Labels: {count} guide layer(s) {names} removed, so the labels they guided are placed as without them until a layer of that name comes back"), - false, - ); + let said = if count == 1 { + format!( + "Labels: the guide layer {names} was removed, so the labels it guided are placed as without it until a layer of that name comes back" + ) + } else { + format!( + "Labels: {count} guide layers {names} were removed, so the labels they guided are placed as without them until a layer of that name comes back" + ) + }; + s.notify(said, false); } } diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 6301dccfea..e338ec4288 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -147,13 +147,22 @@ pub(in crate::cmd::layout) fn element_background(p: &Value, current: Option Result { match p.get("radius").filter(|v| !v.is_null()) { None => Ok(d), - Some(v) => { - v.as_f64().filter(|r| r.is_finite() && *r >= 0.0).map(|r| r.min(50.0)).ok_or_else(|| "radius is millimetres, 0 or more".into()) - } + Some(v) => v + .as_f64() + .filter(|r| r.is_finite() && *r >= 0.0) + .map(|r| r.min(MAX_CORNER_RADIUS)) + .ok_or_else(|| "radius is millimetres, 0 or more".into()), } } @@ -201,13 +210,13 @@ pub(in crate::cmd::layout) fn held_to_limits(p: &Value, shape: Option) -> }; if let Some(shape) = shape { if let Some(w) = f(p, "width") { - let least = if shape == Shape::Line { 0.1 } else { 0.0 }; - hold("width", w, w.clamp(least, 50.0), if shape == Shape::Line { "0.1 to 50 points" } else { "0 to 50 points" }); + let (least, most) = if shape == Shape::Line { LINE_WIDTH } else { SHAPE_WIDTH }; + hold("width", w, w.clamp(least, most), &format!("{least} to {most} points")); } if shape == Shape::Rectangle && let Some(r) = p.get("radius").and_then(Value::as_f64).filter(|r| r.is_finite() && *r >= 0.0) { - hold("radius", r, r.min(50.0), "up to 50 mm"); + hold("radius", r, r.min(MAX_CORNER_RADIUS), &format!("up to {MAX_CORNER_RADIUS} mm")); } } if let Some(w) = p.get("barOutline").and_then(|o| f(o, "width")) { @@ -574,7 +583,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu let k = ElementKind::Rectangle { fill: color(p, "fill", Rgba::new(0, 0, 0, 0))?, outline: color(p, "outline", color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?)?, - width: shape_width(p, 1.0)?.clamp(0.0, 50.0), + width: shape_width(p, 1.0)?.clamp(SHAPE_WIDTH.0, SHAPE_WIDTH.1), radius: corner_radius(p, 0.0)?, dash: element_dash(p)?.flatten(), }; @@ -589,7 +598,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu let k = ElementKind::Ellipse { fill: color(p, "fill", Rgba::new(0, 0, 0, 0))?, outline: color(p, "outline", color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?)?, - width: shape_width(p, 1.0)?.clamp(0.0, 50.0), + width: shape_width(p, 1.0)?.clamp(SHAPE_WIDTH.0, SHAPE_WIDTH.1), dash: element_dash(p)?.flatten(), }; // A circle is an ellipse in a square box. @@ -602,7 +611,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu let arrow = kind == "arrow"; let head = line_head(p, if arrow { LineHead::End } else { LineHead::None })?; let color = color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?; - let width = shape_width(p, if arrow { 1.5 } else { 1.0 })?.clamp(0.1, 50.0); + let width = shape_width(p, if arrow { 1.5 } else { 1.0 })?.clamp(LINE_WIDTH.0, LINE_WIDTH.1); let dash = element_dash(p)?.flatten(); let len = (pw.min(ph) * 0.4).max(10.0); let name = if head == LineHead::None { "Line" } else { "Arrow" }; diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index bbdd617ed5..e63eae3ce5 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -123,7 +123,7 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result { ElementKind::Rectangle { fill, outline, width, radius: corner_radius(p, *radius)?, dash } @@ -138,7 +138,7 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result Ok(None), diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index aaab639e1f..92e19268fc 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -1083,8 +1083,10 @@ pub(crate) struct FirstLayerWatch { } /// The coordinate system a layer says it is in: a raster's, or the one a feature layer was read -/// in. `None` for a layer whose file named none: a feature layer taken for longitude/latitude, a -/// raster read as WGS 84 because its coordinates look like degrees, a scan not yet placed. +/// in. `None` for a feature layer in longitude/latitude, whether its file named WGS 84 or nothing +/// (a reader leaves `Dataset::crs` empty for it), a raster read as WGS 84 because its coordinates +/// look like degrees, and a scan not yet placed. A raster that names WGS 84 or another system in +/// degrees gives that. pub fn layer_system(l: &rustgis_map::Layer) -> Option { match &l.raster { Some(r) => r.data.as_ref().filter(|d| d.georeferenced && !d.crs_assumed).map(|d| d.crs), diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 354c51f54c..84676bf4ba 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -1378,7 +1378,12 @@ fn check_fields( } report.approximated( name, - format!("its classes by the expression `{}`, which doesn't fit the layer ({why}): every feature drawn {drawn}", by.qgis), + format!( + "its classes by the expression `{}`, which doesn't fit the layer ({why}): every feature drawn {drawn}", + // Redacted whole before it is cut (`qgis::set_redactor`), so a login it holds can't + // be cut past the redactor. + rustgis_map::qgis::quoted_expression(&by.qgis) + ), ); } // The style's boolean categories, matching values as they print: by an expression, a diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 1b9d9fef15..28a294a04d 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -290,7 +290,8 @@ pub(crate) fn in_background(command: &str) -> Option<&'static str> { /// Why `command` can't be read ahead. pub(crate) fn not_in_background(command: &str) -> String { - format!("{command} doesn't prepare background work") + let those: Vec<&str> = IN_BACKGROUND.iter().map(|(c, _)| *c).collect(); + format!("{command} doesn't prepare background work; those that do: {}, and table edits", those.join(", ")) } /// Picks work only for an already admitted command, retaining its exact streamed-source opening. diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 51f02109c2..dad50b4897 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -366,7 +366,14 @@ fn read_documents_with( }; parse(text.as_bytes(), read_within) } else if left { - let Some(read) = s.left_document(&address).map_err(|e| crate::sources::message_with_address(original, &e))? else { + // A refusal here ends the discovery as the loop's other failures do: the layers found + // so far are kept, and what the dataset discovery left out is said. Named by the + // document refused, as a parse error is. + let read = match s.left_document(&address) { + Ok(read) => read, + Err(e) => return result.failed(s, crate::sources::message_with_address(&address, &e), dataset.as_ref()), + }; + let Some(read) = read else { result.next = Some(address); result.dataset_notes(dataset.as_ref()); return Ok(result); @@ -1335,9 +1342,11 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis // A layer the listing left out, and why (a collection of 3D Tiles, say). let quoted = format!("'{}'", want.to_lowercase()); let left_out = |n: &&String| n.contains(rustgis_data::ogc::LEFT_OUT_3D) && n.to_lowercase().contains("ed); - match found.service.notes.iter().find(left_out) { - Some(why) => crate::sources::message_with_address(url, &format!("no layer '{want}': {why}")), - None => not_listed(url, "layer", want, &found.service), + match (found.service.notes.iter().find(left_out), &found.error) { + (Some(why), _) => crate::sources::message_with_address(url, &format!("no layer '{want}': {why}")), + // Discovery stopped before reaching it: the refusal that stopped it, not just "no layer". + (None, Some(error)) => format!("no layer '{want}' among those found before the discovery stopped: {error}"), + (None, None) => not_listed(url, "layer", want, &found.service), } })?; let capability_crossed = source.crossed_origin; diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index c01f0c1db2..ab276e49fa 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -38,6 +38,14 @@ struct Input { _retained: crate::undo_memory::ReadRows, } +/// A non-negative whole number, given as an integer or as an integral float (`1.0`, as some +/// clients send); `None` for a negative, fractional, non-finite or non-number value. +fn whole(value: &Value) -> Option { + value.as_u64().or_else(|| { + value.as_f64().filter(|f| f.is_finite() && *f >= 0.0 && f.fract() == 0.0 && *f <= f64::from(u32::MAX)).map(|f| f as u64) + }) +} + impl Input { /// Resolves the reference and schema without traversing features. Selection supplies only /// its first row when no explicit reference is given. @@ -47,7 +55,7 @@ impl Input { let row = match p.get("row") { None | Some(Value::Null) => *l.selection.first().ok_or("select a feature (or give row)")?, Some(value) => { - let row = value.as_u64().ok_or("row must be a non-negative whole number")?; + let row = whole(value).ok_or("row must be a non-negative whole number")?; usize::try_from(row).map_err(|_| "no such row")? } }; @@ -60,9 +68,7 @@ impl Input { } let count = match p.get("count") { None | Some(Value::Null) => 10, - Some(value) => { - value.as_u64().filter(|count| (1..=1000).contains(count)).ok_or("count must be a whole number from 1 to 1000")? - } + Some(value) => whole(value).filter(|count| (1..=1000).contains(count)).ok_or("count must be a whole number from 1 to 1000")?, } as usize; let select = super::b(p, "select").unwrap_or(true); let visibility = select.then(|| Visibility { @@ -197,7 +203,7 @@ fn gather(input: &Input) -> Result { let excluded = matched - rows.len(); if excluded > 0 { notices.push(NoticeText::format( - "{n} features aren't drawn (the layer's definition query, time window or display filters hide them), and aren't selected", + "{n} of the returned matches and reference aren't drawn (the layer's definition query, time window or display filters hide them), so they aren't selected", [("n", excluded.to_string().into())], )); } diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index cc4aff9c8f..7681804b85 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -303,6 +303,19 @@ fn walk(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"lon": c.x, "lat": c.y})) } +/// The keys of `map.terrain`'s `"block"` object, which its refusals list (and the help reads). +const BLOCK_KEYS: &[&str] = &["extent", "depth", "walls", "shape", "radius", "water"]; +/// The keys of a block's `"walls"` object. +const WALLS_KEYS: &[&str] = &["color", "layer", "top"]; +/// The keys of a block's `"water"` object. +const BLOCK_WATER_KEYS: &[&str] = &["depth", "field", "bed"]; +/// The keys of a block's walls' `"top"` object. +const TOP_KEYS: &[&str] = &["layer", "thickness"]; +/// The keys of a block's `"shape"` object. +const SHAPE_KEYS: &[&str] = &["layer", "where"]; +/// The keys of `map.terrain`'s `"water"` object. +const WATER_KEYS: &[&str] = &["layer", "level", "glint", "shore"]; + /// A block diagram's settings (#1914) from `map.terrain`'s `"block"` object: the shape read here, /// the values checked by [`rustgis_map::view::TerrainBlock::check`] (as a saved project's are), /// and the walls' layer as the water's is ([`polygon_layer`]). @@ -314,8 +327,8 @@ fn terrain_block( base: Option<&rustgis_map::view::TerrainBlock>, ) -> Result { use rustgis_map::view::{BLOCK_WALLS, BlockShape}; - if let Some(k) = b.keys().find(|k| !matches!(k.as_str(), "extent" | "depth" | "walls" | "shape" | "radius" | "water")) { - return Err(format!("block has no '{k}' (extent, depth, walls, shape, radius, water)")); + if let Some(k) = b.keys().find(|k| !BLOCK_KEYS.contains(&k.as_str())) { + return Err(format!("block has no '{k}' ({})", BLOCK_KEYS.join(", "))); } let mut extent = match b.get("extent") { None => base.and_then(|b| b.extent), @@ -349,8 +362,8 @@ fn terrain_block( None => (kept_color, kept_layer, kept_top), Some(Value::Null) => (BLOCK_WALLS, None, None), Some(Value::Object(w)) => { - if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "color" | "layer" | "top")) { - return Err(format!("block's walls has no '{k}' (color, layer, top)")); + if let Some(k) = w.keys().find(|k| !WALLS_KEYS.contains(&k.as_str())) { + return Err(format!("block's walls has no '{k}' ({})", WALLS_KEYS.join(", "))); } let layer = match w.get("layer") { None => kept_layer, @@ -375,8 +388,8 @@ fn terrain_block( None => base.and_then(|b| b.water.clone()), Some(Value::Null | Value::Bool(false)) => None, Some(Value::Object(w)) => { - if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "depth" | "field" | "bed")) { - return Err(format!("block's water has no '{k}' (depth, field, bed)")); + if let Some(k) = w.keys().find(|k| !BLOCK_WATER_KEYS.contains(&k.as_str())) { + return Err(format!("block's water has no '{k}' ({})", BLOCK_WATER_KEYS.join(", "))); } let depth = match w.get("depth") { None | Some(Value::Null) => None, @@ -465,8 +478,8 @@ const WALLS_TOP: &str = /// [`rustgis_map::view::TerrainBlock::check`]) or `{"field"}`, a numeric field of that layer. fn walls_top_band(s: &Session, t: &serde_json::Map) -> Result { use rustgis_map::view::BandThickness; - if let Some(k) = t.keys().find(|k| !matches!(k.as_str(), "layer" | "thickness")) { - return Err(format!("block's walls' top has no '{k}' (layer, thickness)")); + if let Some(k) = t.keys().find(|k| !TOP_KEYS.contains(&k.as_str())) { + return Err(format!("block's walls' top has no '{k}' ({})", TOP_KEYS.join(", "))); } let name = t.get("layer").and_then(Value::as_str).ok_or(WALLS_TOP)?; let layer = polygon_layer(s, name, "block's walls' top", "the units the band shows")?; @@ -494,8 +507,8 @@ fn walls_top_band(s: &Session, t: &serde_json::Map) -> Result) -> Result { - if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "layer" | "where")) { - return Err(format!("block's shape has no '{k}' (layer, where)")); + if let Some(k) = o.keys().find(|k| !SHAPE_KEYS.contains(&k.as_str())) { + return Err(format!("block's shape has no '{k}' ({})", SHAPE_KEYS.join(", "))); } let name = o.get("layer").and_then(Value::as_str).ok_or("block's shape needs a layer: a polygon layer of the outline")?; let name = polygon_layer(s, name, "block's shape", "the outline the block is cut to")?; @@ -566,8 +579,8 @@ fn polygon_layer(s: &Session, name: &str, what: &str, holds: &str) -> Result) -> Result { - if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "layer" | "level" | "glint" | "shore")) { - return Err(format!("water has no '{k}' (layer, level, glint, shore)")); + if let Some(k) = w.keys().find(|k| !WATER_KEYS.contains(&k.as_str())) { + return Err(format!("water has no '{k}' ({})", WATER_KEYS.join(", "))); } let name = w.get("layer").and_then(Value::as_str).ok_or("water needs a layer: a polygon layer of water bodies")?; let name = polygon_layer(s, name, "water", "water bodies")?; @@ -612,23 +625,13 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { s.map_mut().view.terrain = None; return Ok(json!({"terrain": null})); } - // Left out, the block stays as it was; an object changes only the keys it gives (`true` is one - // with none); false or null takes it off. - let base = s.map().view.terrain.as_ref().and_then(|t| t.block.clone()); - let block = match p.get("block") { - None => None, - Some(Value::Null | Value::Bool(false)) => Some(None), - Some(Value::Bool(true)) => Some(Some(terrain_block(s, &serde_json::Map::new(), base.as_ref())?)), - Some(Value::Object(b)) => Some(Some(terrain_block(s, b, base.as_ref())?)), - Some(_) => return Err("block is an object (extent, depth, walls, shape, radius, water), or false to take it off".into()), - }; // Left out (or null, as for the exaggeration), the water stays as it was; false takes it off // (#1915). let water = match p.get("water") { None | Some(Value::Null) => None, Some(Value::Bool(false)) => Some(None), Some(Value::Object(w)) => Some(Some(terrain_water(s, w)?)), - Some(_) => return Err("water is an object (layer, level, glint, shore), or false to take it off".into()), + Some(_) => return Err(format!("water is an object ({}), or false to take it off", WATER_KEYS.join(", "))), }; let exaggeration = match p.get("exaggeration").filter(|v| !v.is_null()) { Some(_) => { @@ -672,6 +675,19 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { let l = s.active_layer.and_then(|id| s.map().layer(id)).filter(|l| l.raster.is_some())?; Some(TerrainSource::Layer(l.name.clone())) }); + // Left out, the block stays as it was; an object changes only the keys it gives (`true` is one + // with none); false or null takes it off. What it is merged onto is the old block as this call + // keeps it: one cut to the old DEM's extent is dropped on a switch to elevation tiles (below), + // so none of its settings carry into the new block. + let to_tiles = matches!(source, Some(TerrainSource::Tiles { .. })); + let base = s.map().view.terrain.as_ref().and_then(|t| t.block.clone()).filter(|b| b.own_box() || !to_tiles); + let block = match p.get("block") { + None => None, + Some(Value::Null | Value::Bool(false)) => Some(None), + Some(Value::Bool(true)) => Some(Some(terrain_block(s, &serde_json::Map::new(), base.as_ref())?)), + Some(Value::Object(b)) => Some(Some(terrain_block(s, b, base.as_ref())?)), + Some(_) => return Err(format!("block is an object ({}), or false to take it off", BLOCK_KEYS.join(", "))), + }; // Relief shows on a tilted Web Mercator map only (the globe and other projections stay flat). let mercator = matches!(s.map().projection, rustgis_map::Projection::WebMercator); let flat = s.map().camera.pitch.abs() < 0.5; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index e417065ffb..bb6ac005a0 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -637,6 +637,10 @@ pub fn raster_start(s: &mut Session, command: &str, p: &Value) -> Result) -> Result { @@ -646,16 +650,18 @@ pub(crate) fn raster_start_raw(s: &mut Session, op: crate::policy::Authorized= MAX_RASTER_RUNS { + return Err("too many Analysis runs are under way: wait for one to finish".into()); + } let current = continuation.clone(); let still = std::sync::Arc::new(move || current.check().is_ok()); let work = crate::render::rustgis_tiles::cache::with_still(still, || start(s, p))?; s.next_pending = s.next_pending.wrapping_add(1); let id = s.next_pending; - // One runs at a time from the app; a few are kept, apart from the downloads' list, so no - // number of downloads meanwhile pushes a run out. - if s.raster_runs.len() >= 8 { - s.raster_runs.remove(0); - } s.raster_runs.push((id, continuation.clone())); Ok(RasterRun { id, name, work, map: s.map().instance_id(), continuation, capture_inputs: s.log.on() }) } @@ -2389,11 +2395,10 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { let name = out_name(p, format!("Route on {}", l.name))?; let cost = ps(p, "costField").map(|n| l.dataset.field_index(n).ok_or_else(|| format!("no field named '{n}'"))).transpose()?; let resolved = l.resolve_rows(&l.dataset, rustgis_map::rows::Policy::Query, None)?; - let query_notice = resolved.query_error.map(|error| { - crate::notice_text::NoticeText::format( - "1 layer with an unreadable definition query; reading without that query: {layer}: {error}", - [("layer", l.name.clone().into()), ("error", error.into())], - ) + let query_notice = resolved.query_error.and_then(|error| { + use crate::notice_text::NoticeText; + let detail = NoticeText::format("{layer}: {error}", [("layer", l.name.clone().into()), ("error", error.into())]); + NoticeText::unreadable_queries(1, vec![detail]) }); let rows: Vec = match resolved.rows { rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), @@ -2504,19 +2509,8 @@ fn neighborhood(s: &mut Session, p: &Value) -> CmdResult { super::select::set(s, id, rows, super::select::Mode::Add); } } - if query_error_count > 0 { - use crate::notice_text::NoticeText; - let key = if query_error_count == 1 { - "{count} layer with an unreadable definition query; reading without that query: {layers}" - } else { - "{count} layers with unreadable definition queries; reading without those queries: {layers}" - }; - let more = query_error_count - query_errors.len(); - let mut layers = NoticeText::list(query_errors); - if more > 0 { - layers = NoticeText::format("{layers}; {count} more layers", [("layers", layers), ("count", more.to_string().into())]); - } - s.notify_text(NoticeText::format(key, [("count", query_error_count.to_string().into()), ("layers", layers)]), false); + if let Some(notice) = crate::notice_text::NoticeText::unreadable_queries(query_error_count, query_errors) { + s.notify_text(notice, false); } Ok(json!({"radiusKm": radius / 1000.0, "layers": out})) } @@ -2531,11 +2525,10 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { } let name = out_name(p, format!("{}_simulated", l.name))?; let resolved = l.resolve_rows(&l.dataset, rustgis_map::rows::Policy::SelectionAndQuery, None)?; - let query_notice = resolved.query_error.map(|error| { - crate::notice_text::NoticeText::format( - "1 layer with an unreadable definition query; reading without that query: {layer}: {error}", - [("layer", l.name.clone().into()), ("error", error.into())], - ) + let query_notice = resolved.query_error.and_then(|error| { + use crate::notice_text::NoticeText; + let detail = NoticeText::format("{layer}: {error}", [("layer", l.name.clone().into()), ("error", error.into())]); + NoticeText::unreadable_queries(1, vec![detail]) }); let rows: Vec = match resolved.rows { rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index c64f5f6996..cc94375c7a 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -981,12 +981,13 @@ pub(crate) fn sync_error(layer: &str, e: String) -> String { /// Copies the edits `edited` holds of offline area `ai` (its offline map, here or from a field /// package) back to the area's source map, as [`offline_sync`] describes, and refreshes the area. /// -/// A feature added offline keeps its id when the source doesn't use it, so the next sync of the -/// same copy (a field package's phone keeps its ids) finds it again as the same feature. One whose -/// id is taken gets a fresh one, counted in `renumbered` (a field package's Bring Back says it; an -/// offline map here is renewed from the source after the sync, so it has the new id): a later sync -/// of a copy that kept the old id finds it under it, so the source's copy is deleted and the -/// area's added again (no feature twice, but a new id, and a change made to it here meanwhile is +/// A feature added offline keeps its id when it is above every id the source layer had or keeps new +/// ones above, and no row uses it ([`super::field_changes::id_at_home`]), so the next sync of the +/// same copy (a field package's phone keeps its ids) finds it again as the same feature. Otherwise +/// it takes the next free one above them, counted in `renumbered` (a field package's Bring Back +/// says it; an offline map here is renewed from the source after the sync, so it has the new id): a +/// later sync of a copy that kept the old id finds it under it, so the source's copy is deleted and +/// the area's added again (no feature twice, but a new id, and a change made to it here meanwhile is /// said as a conflict). /// /// Each conflict's losing version is kept on the area ([`keep_conflicts`]), named by `package`, the diff --git a/crates/engine/src/durable.rs b/crates/engine/src/durable.rs index d9f4e4d606..f5abda7273 100644 --- a/crates/engine/src/durable.rs +++ b/crates/engine/src/durable.rs @@ -322,7 +322,7 @@ impl<'a> Prepare<'a> { )); } let count = conflicts.iter().flat_map(|c| &c.values).filter(|(_, v)| v.is_non_finite()).count(); - let place = crate::notice_text::NoticeText::format("offline area {name}'s conflicts", [("name", format!("'{area}'").into())]); + let place = crate::notice_text::NoticeText::format("the conflicts of offline area {name}", [("name", format!("'{area}'").into())]); self.record_numbers(count, place); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6e3542cb10..eef54fabd7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1477,6 +1477,9 @@ impl Session { // Every panic an incident with a reference, whatever embeds the session (the apps, Python, // MCP): installed once, before the hook that was there (a crash log) runs. rustgis_data::incident::install(); + // A QGIS expression a note quotes cut short is redacted whole first, so a login it holds + // can't be cut past the redactor (`rustgis_map::qgis::quoted_expression`). + rustgis_map::qgis::set_redactor(|text| Session::redacted(text).into_string()); // The engine's tests never add Shapefile indexes to the user's cache (#1230). #[cfg(all(test, not(target_arch = "wasm32")))] rustgis_data::source::shp::use_temporary_index_dir(); @@ -3870,8 +3873,10 @@ impl Session { /// How many loss notices this session has given for each code, including those the notice /// queue no longer keeps: compare two of these to learn what a run lost, however much it said. - /// A failed command's losses are taken back with its changes, except counted losses - /// ([`Session::notify_counted`]), which outlive its rollback, and one whose notice the queue + /// A failed command that is rolled back takes back the losses of the notices it withdraws, but + /// keeps those of its errors and of its notices of committed writes; a failed command that + /// isn't rolled back (a read-only one) keeps them all. Counted losses + /// ([`Session::notify_counted`]) outlive any rollback, and so does one whose notice the queue /// had already let go: which of those described a committed write isn't kept, so it stays /// counted, erring towards a loss. pub fn losses_given(&self) -> &[(rustgis_data::loss::LossCode, u64)] { diff --git a/crates/engine/src/notice_text.rs b/crates/engine/src/notice_text.rs index 1d5f1becef..9689292842 100644 --- a/crates/engine/src/notice_text.rs +++ b/crates/engine/src/notice_text.rs @@ -58,6 +58,28 @@ impl NoticeText { }) } + /// One notice for `total` layers whose definition query no longer reads, naming the given + /// `details` (callers keep at most five) and counting the rest as "1 more layer" or + /// "{count} more layers". `None` when no layer failed. + pub(crate) fn unreadable_queries(total: usize, details: Vec) -> Option { + if total == 0 { + return None; + } + let more = total.saturating_sub(details.len()); + let mut layers = Self::list(details); + if more == 1 { + layers = Self::format("{layers}; 1 more layer", [("layers", layers)]); + } else if more > 1 { + layers = Self::format("{layers}; {count} more layers", [("layers", layers), ("count", more.to_string().into())]); + } + let key = if total == 1 { + "{count} layer with an unreadable definition query; reading without that query: {layers}" + } else { + "{count} layers with unreadable definition queries; reading without those queries: {layers}" + }; + Some(Self::format(key, [("count", total.to_string().into()), ("layers", layers)])) + } + /// Renders trusted templates through the front end's formatter; literal data bypasses it. pub(crate) fn render(&self, format: &impl Fn(&str, &[(&str, &str)]) -> String) -> String { match self { @@ -126,6 +148,17 @@ mod tests { Ok(()) } + /// A QGIS expression quoted cut short is redacted whole first: a secret that starts before the + /// 80th character and runs past it isn't left in by halves. + #[test] + fn a_quoted_expression_is_redacted_before_it_is_cut() { + let _session = crate::Session::new(crate::Project::default()); + let expr = format!("\"name\" = '{}https://e.invalid/d?token=NOT_A_REAL_SECRET_VALUE_PAST_EIGHTY'", "a".repeat(30)); + let quoted = rustgis_map::qgis::quoted_expression(&expr); + assert!(!quoted.contains("NOT_A_R"), "{quoted}"); + assert!(quoted.starts_with("\"name\" = 'aaa"), "{quoted}"); + } + #[test] fn inserted_names_are_never_read_as_more_placeholders() { let text = diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 532f649453..8afc75b14e 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1170,11 +1170,27 @@ fn script_uses(script: &str, uses: impl Fn(&str, &Value) -> bool) -> bool { .any(|line| crate::script_line(line).is_some_and(|parsed| parsed.is_ok_and(|(id, params)| command_uses(&uses, &id, ¶ms)))) } -/// `uses` on a saved command and, for a `model.run` given its graph inline, on each of the graph's -/// tool nodes as on a saved model's steps (#2758): that graph is in no saved model, so nothing -/// else reads it, and an older reader would run its nodes with the option dropped. +/// `uses` on a saved command and, for a command given a model's graph inline (`model.run`, +/// `model.new`, `model.save`), on each of the graph's tool nodes as on a saved model's steps +/// (#2758), and for `model.new` given its `steps` inline, on each step: that graph or those steps +/// are in no saved model, so nothing else reads them, and an older reader would replay them with +/// the option dropped. fn command_uses(uses: &impl Fn(&str, &Value) -> bool, id: &str, params: &Value) -> bool { - uses(id, params) || (id == "model.run" && inline_graph_uses(params, uses)) + uses(id, params) + || (matches!(id, "model.run" | "model.new" | "model.save") && inline_graph_uses(params, uses)) + || (id == "model.new" && inline_steps_uses(params, uses)) +} + +/// A `model.new`'s inline `steps` read as it reads them: an array of `{tool, params}`, at most +/// `MAX_NODES` (more is refused there, so needs nothing), each checked by the leaf check only, and +/// one naming `script.run` skipped, as for a graph's node ([`inline_graph_uses`]). +fn inline_steps_uses(params: &Value, uses: &impl Fn(&str, &Value) -> bool) -> bool { + params.get("steps").and_then(Value::as_array).filter(|steps| steps.len() <= crate::model::MAX_NODES).is_some_and(|steps| { + steps.iter().any(|step| { + let tool = step.get("tool").and_then(Value::as_str).unwrap_or(""); + tool != "script.run" && uses(tool, step.get("params").unwrap_or(&Value::Null)) + }) + }) } /// A graph read as the run reads it (`model::graph_from_json_counted`): an object with `nodes`, at @@ -1854,13 +1870,18 @@ mod tests { /// notebook cell and a recorded command: what a project saves as `requires` for each (`None`: /// no header). fn saved_requires_of_inline_graph(run: &Value) -> Vec> { - let script = format!("# Run\nmodel.run {run}"); + saved_requires_of_inline("model.run", run) + } + + /// `command` with `run` as its parameters, saved as [`saved_requires_of_inline_graph`] saves it. + fn saved_requires_of_inline(command: &str, run: &Value) -> Vec> { + let script = format!("# Run\n{command} {run}"); let base = serde_json::to_value(Project::default()).unwrap(); [ - ("tasks", json!([{"name": "Task", "steps": [{"title": "Run", "command": "model.run", "params": run}]}])), + ("tasks", json!([{"name": "Task", "steps": [{"title": "Run", "command": command, "params": run}]}])), ("tasks", json!([{"name": "Script", "steps": [{"title": "Run", "command": "script.run", "params": {"script": script}}]}])), ("notebooks", json!([{"name": "Notebook", "cells": [{"kind": "code", "source": script}]}])), - ("gp_history", json!([{"tool": "Run", "params": {}, "command": ["model.run", run], "ok": true, "messages": [], "millis": 0}])), + ("gp_history", json!([{"tool": "Run", "params": {}, "command": [command, run], "ok": true, "messages": [], "millis": 0}])), ] .into_iter() .map(|(field, value)| { @@ -1904,6 +1925,21 @@ mod tests { } } + /// `model.new` and `model.save` take a graph inline too, and `model.new` its steps: each + /// requires what its tools do, in every container; the default option, nothing. + #[test] + fn an_inline_graph_or_steps_of_model_new_or_save_requires_what_its_tools_do() { + for (system, expected) in [("H3", Some(json!(["dggs-system"]))), ("A5", None)] { + let graph = graph_of_one_tool("a5Grid", json!({"system": system})); + let steps = json!({"steps": [{"tool": "a5Grid", "params": {"system": system}}]}); + for (command, params) in [("model.new", &graph), ("model.save", &graph), ("model.new", &steps)] { + for (index, saved) in saved_requires_of_inline(command, params).into_iter().enumerate() { + assert_eq!(saved, expected, "{command} {params} in container {index}"); + } + } + } + } + /// A node of an inline graph is checked as a step of a saved model is, by every capability: one /// sample for each entry of `COMMAND_CAPABILITIES`, each requiring exactly its own name, so an /// entry added later without a sample fails here. The walk takes a node's id and parameters as @@ -2262,7 +2298,7 @@ mod tests { let mut edges = nodes_with_last(2, h3()); edges["graph"]["edges"] = json!(vec![json!({"from": "j", "to": "h", "toPort": "input"}); MAX_EDGES + 1]); all(edges, None, "more connections than a run takes"); - // A node that is itself a `model.run`, nested to the depth the project's JSON allows (128). + // A node that is itself a `model.run`, nested 24 levels deep. let mut nested = graph_of_one_tool("a5Grid", json!({"system": "H3"})); for _ in 0..24 { nested = json!({"graph": {"nodes": [{"id": "m", "kind": "tool", "tool": "model.run", "params": nested}]}}); @@ -2275,14 +2311,21 @@ mod tests { cycle = json!({"graph": {"nodes": [{"id": "s", "kind": "tool", "tool": "script.run", "params": {"script": script}}]}}); } all(cycle, None, "a script node is not read into"); - // A script of as many graph lines as a script takes. + // A script of as many graph lines as a script takes, the last one needing it: every line is + // read. One line more puts that one past what a script takes, so it isn't read. let line = format!("model.run {}", graph_of_one_tool("buffer", json!({}))); - let script = vec![line; crate::cmd::workflows::MAX_SCRIPT_LINES].join("\n"); - let base = serde_json::to_value(Project::default()).unwrap(); - let mut document = base; - document["tasks"] = json!([{"name": "T", "steps": [{"title": "Run", "command": "script.run", "params": {"script": script}}]}]); - let project = Project::from_json(&document.to_string()).unwrap(); - assert!(serde_json::to_value(&project).unwrap().get("requires").is_none()); + let last = format!("model.run {}", graph_of_one_tool("a5Grid", json!({"system": "H3"}))); + let saved = |lines: usize| { + let mut script = vec![line.clone(); lines - 1]; + script.push(last.clone()); + let mut document = serde_json::to_value(Project::default()).unwrap(); + let params = json!({"script": script.join("\n")}); + document["tasks"] = json!([{"name": "T", "steps": [{"title": "Run", "command": "script.run", "params": params}]}]); + let project = Project::from_json(&document.to_string()).unwrap(); + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + assert_eq!(saved(crate::cmd::workflows::MAX_SCRIPT_LINES), Some(json!(["dggs-system"]))); + assert_eq!(saved(crate::cmd::workflows::MAX_SCRIPT_LINES + 1), None); } /// All replayable project containers require non-default options only when requested. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13d763f9ca..94d706ea23 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1232,9 +1232,13 @@ fn simulation_respects_selected_polygons_and_the_definition_query() { if query == "missing = 1" { assert!(notices[0].text.contains("Polygons {error}") && notices[0].text.contains("missing"), "{notices:?}"); let translated = notices[0].translated(|key, args| { - assert_eq!(key, "1 layer with an unreadable definition query; reading without that query: {layer}: {error}"); - assert_eq!(args.iter().find(|(key, _)| *key == "layer").map(|(_, value)| *value), Some("Polygons {error}")); - assert!(args.iter().any(|(key, value)| *key == "error" && value.contains("missing"))); + if key == "{layer}: {error}" { + assert_eq!(args.iter().find(|(key, _)| *key == "layer").map(|(_, value)| *value), Some("Polygons {error}")); + assert!(args.iter().any(|(key, value)| *key == "error" && value.contains("missing"))); + } else { + assert_eq!(key, "{count} layer with an unreadable definition query; reading without that query: {layers}"); + assert_eq!(args.iter().find(|(key, _)| *key == "count").map(|(_, value)| *value), Some("1")); + } key.to_string() }); assert!(translated.is_some(), "the query fallback must retain a translatable template"); @@ -1283,8 +1287,11 @@ fn route_reports_unreadable_query_and_keeps_query_only_network() { assert!( notices[0] .translated(|key, args| { - assert_eq!(key, "1 layer with an unreadable definition query; reading without that query: {layer}: {error}"); - assert_eq!(args.iter().find(|(key, _)| *key == "layer").map(|(_, value)| *value), Some("Roads {error}")); + if key == "{layer}: {error}" { + assert_eq!(args.iter().find(|(key, _)| *key == "layer").map(|(_, value)| *value), Some("Roads {error}")); + } else { + assert_eq!(key, "{count} layer with an unreadable definition query; reading without that query: {layers}"); + } key.to_string() }) .is_some() @@ -1360,6 +1367,27 @@ fn neighborhood_reports_unreadable_queries_and_keeps_query_only_search() { } } +/// Six layers with unreadable queries name five and count the last one in the singular. +#[test] +fn six_unreadable_queries_count_one_more_layer() { + use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; + let mut s = Session::new(Project::default()); + for i in 0..6 { + let mut ds = Dataset::new(format!("Road {i}"), GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![]); + let id = s.map_mut().add_dataset(ds); + s.map_mut().layer_mut(id).unwrap().definition_query = Some("missing = 1".into()); + } + let mark = s.notice_mark(); + s.run("analysis.neighborhood", &json!({"lon": 0, "lat": 0, "radius": 100})).unwrap(); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1); + let text = ¬ices[0].text; + assert!(text.starts_with("6 layers with unreadable definition queries"), "{text}"); + assert!(text.ends_with("; 1 more layer"), "{text}"); + assert!(!text.contains("1 more layers"), "{text}"); +} + /// The fallback count covers every searched layer, while the recursive diagnostic list stays /// bounded and says how many layer details it omitted. #[test] @@ -3862,6 +3890,30 @@ fn a_calculation_past_the_length_limit_is_refused_by_rules_and_calculate_field() assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("rule(s)")), "{:?}", s.notices_since(mark)); } +/// A constraint rule that no longer reads (one past the length limit, from an earlier version or a +/// hand-edited file) is skipped by an edit and said once; a constraint that reads says nothing. +#[test] +fn a_constraint_rule_that_no_longer_reads_is_said_when_an_edit_skips_it() { + let mut s = numbered_points(&[1]); + let id = s.map().layer_by_name("Herds").unwrap().id; + let rule = |expression: String| rustgis_map::design::AttributeRule { + name: "Long".into(), + kind: rustgis_map::design::RuleKind::Constraint, + field: String::new(), + expression, + }; + s.map_mut().layer_mut(id).unwrap().design.rules.push(rule(format!("'{}'", "a".repeat(rustgis_data::query::MAX_LEN - 1)))); + let mark = s.notice_mark(); + s.run("edit.setValue", &json!({"layer": "Herds", "row": 0, "field": "n", "value": 2})).unwrap(); + let said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).filter(|t| t.contains("no longer read")).collect(); + assert_eq!(said, ["Herds: 1 constraint rule(s) skipped because they no longer read, so edits weren't checked against them: Long"]); + // A constraint that reads, and holds: nothing said. + s.map_mut().layer_mut(id).unwrap().design.rules = vec![rule("n > 0".into())]; + let mark = s.notice_mark(); + s.run("edit.setValue", &json!({"layer": "Herds", "row": 0, "field": "n", "value": 3})).unwrap(); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("no longer read")), "{:?}", s.notices_since(mark)); +} + /// A layer of points read from GeoJSON, one for each value given, in that order: the integer /// field `n` holds it, the text field `code` its digits, the text field `name` "h" and them. fn numbered_points(values: &[i64]) -> Session { @@ -6156,7 +6208,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 'Rivers' removed"), "{notes:?}"); + assert!(notes[0].contains("the line layer 'Rivers' that perpendicular labels are square to was 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")); } @@ -6211,7 +6263,7 @@ fn labels_are_guided_along_a_line_layer() { let mark = s.notices_given(); s.run("layer.remove", &json!({"layer": "Waters"})).unwrap(); let said: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("guide layer")).map(|n| n.text.clone()).collect(); - assert!(said.len() == 1 && said[0].contains("1 guide layer(s) 'Waters' removed"), "{said:?}"); + assert!(said.len() == 1 && said[0].contains("the guide layer 'Waters' was removed"), "{said:?}"); place(&mut s, "Lakes", Value::Null).unwrap(); assert_eq!(guide(&s), None); let said = |v: &Value| { @@ -8942,8 +8994,8 @@ fn hostile_params_never_panic(shard: usize) { // unchanged and catches any row, attribute or geometry mutation. l.dataset.features.clone(), l.selection.len(), - l.labels.enabled, - l.labels.default.field.len(), + l.renderer.clone(), + l.labels.clone(), l.definition_query.as_deref().map(str::len), ) }) @@ -12366,6 +12418,13 @@ fn a_terrain_block_object_changes_only_the_keys_it_gives() { s.run("map.terrain", &json!({"block": false})).unwrap(); let b = block(s.run("map.terrain", &json!({"block": {"depth": 200}})).unwrap()); assert_eq!((b["extent_from"].as_str(), &b["walls"], b["depth"].as_f64()), (Some("layer"), &json!("#C8B89A"), Some(200.0))); + // On a switch to elevation tiles, a block given in the call isn't merged onto one cut to the + // DEM's extent, which the switch drops: none of its settings carry over. (One cut to polygons + // has a box of its own, so it carries over, settings and shape, as without a block given.) + let tiles = "https://e.com/{z}/{x}/{y}.png"; + s.run("map.terrain", &json!({"layer": dem, "block": {"extent": null, "depth": 50, "walls": "#806040"}})).unwrap(); + let b = block(s.run("map.terrain", &json!({"tiles": tiles, "block": {"extent": inside}})).unwrap()); + assert_eq!((&b["walls"], b["depth"].as_f64()), (&json!("#C8B89A"), None), "{b}"); } #[test] @@ -21770,7 +21829,7 @@ fn saving_kept_conflicts_counts_numbers_written_as_null_and_refuses_bad_shapes() let (done, notices) = said(&mut s); assert!(done.is_ok(), "{done:?}"); assert!( - notices.iter().any(|n| n.contains("1 attribute value(s)") && n.contains("offline area 'Fieldwork''s conflicts")), + notices.iter().any(|n| n.contains("1 attribute value(s)") && n.contains("the conflicts of offline area 'Fieldwork'")), "{notices:?}" ); let before = std::fs::read(&path).unwrap(); @@ -55619,8 +55678,8 @@ fn a_grib_files_byte_range_is_added_as_the_file() { (json!({"url": format!("{base}/a.tif"), "bytes": [0, 9]}), "a range of another format isn't a file"), (json!({"url": format!("{base}/a.tif"), "bytes": [0, 9], "format": "grib"}), "the address names a.tif"), (json!({"url": grb, "bytes": [9, 0]}), "comes after the last"), - (json!({"url": grb, "bytes": [0, 64 << 20]}), "more than a range may have (64 MB)"), - (json!({"url": grb, "bytes": [0, u64::MAX]}), "more than a range may have (64 MB)"), + (json!({"url": grb, "bytes": [0, 64 << 20]}), "more than a range may have (64 MiB)"), + (json!({"url": grb, "bytes": [0, u64::MAX]}), "more than a range may have (64 MiB)"), (json!({"url": grb, "bytes": "0-9"}), "two octet offsets"), (json!({"url": grb, "bytes": [0, 9], "format": "tiff"}), "the one format a byte range is read as"), (json!({"url": grb, "format": "grib"}), "\"format\" goes with \"bytes\""), @@ -56671,6 +56730,22 @@ fn background_raster_function_says_unread_keep() { assert_eq!(said(&s), 2, "{:?}", s.notices.last()); } +/// Past the eight runs kept waiting to land, a ninth is refused rather than forgetting the +/// oldest, which then still waits for its raster. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_ninth_waiting_raster_run_is_refused_and_the_first_still_waits() { + use crate::cmd::workflows::{raster_start, raster_waiting}; + let mut s = world(); + s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": dem_b64()})).unwrap(); + let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); + let p = json!({"layer": dem, "function": "slope"}); + let runs: Vec<_> = (0..8).map(|_| raster_start(&mut s, "raster.function", &p).unwrap()).collect(); + let e = raster_start(&mut s, "raster.function", &p).err().unwrap(); + assert_eq!(e, "too many Analysis runs are under way: wait for one to finish"); + assert!(runs.iter().all(|r| raster_waiting(&s, r.id)), "every earlier run still waits"); +} + /// Viewshed and Interpolate made on another thread, as the Analysis pane runs them (#1291 step 3): /// the raster handed over (`ran`) is the one the command makes here, a cancelled run is an error /// saying so, and a run whose project was closed meanwhile adds nothing. @@ -57183,10 +57258,13 @@ fn raster_tools_run_on_another_thread() { // The answer is the added layer's, whatever else the command says. assert!(there["width"].is_u64() && there["bands"].is_u64(), "{command}: {there}"); let run = raster_start(&mut s, command, &p).unwrap(); + let id = run.id; let control = Control::new(); control.cancel(); let e = run.run(&control).err().unwrap(); assert!(e.contains("was cancelled"), "{command}: {e}"); + // Forgotten, as the desktop forgets a run that failed. + crate::cmd::workflows::raster_abandon(&mut s, id); } // Their inputs are read when they start: a missing one is refused then. assert!(raster_start(&mut s, "raster.change", &json!({"before": dem, "after": "nowhere"})).err().unwrap().contains("nowhere")); @@ -57268,9 +57346,11 @@ fn a_mosaic_made_on_another_thread_is_the_one_made_here() { let files = || std::fs::read_dir(&dir).unwrap().count(); let before = files(); let run = raster_start(&mut s, "raster.mosaic", &p).unwrap(); + let dropped = run.id; let mark = s.notice_mark(); let made = std::thread::spawn(move || run.run(&Control::new())).join().unwrap().unwrap(); drop(made); + crate::cmd::workflows::raster_abandon(&mut s, dropped); assert!(file.is_none() || std::fs::read(&path_there).unwrap() == b"before", "{inputs}"); assert_eq!(files(), before, "{inputs}: a staged file was left"); let run = raster_start(&mut s, "raster.mosaic", &p).unwrap(); @@ -57310,7 +57390,13 @@ fn a_mosaic_made_on_another_thread_is_the_one_made_here() { assert!(here.contains(why), "{p}: {here}"); let there = match raster_start(&mut s, "raster.mosaic", &p) { Err(e) => (e, false), - Ok(run) => (std::thread::spawn(move || run.run(&Control::new())).join().unwrap().err().unwrap(), true), + Ok(run) => { + let id = run.id; + let e = std::thread::spawn(move || run.run(&Control::new())).join().unwrap().err().unwrap(); + // Forgotten, as the desktop forgets a run that failed. + crate::cmd::workflows::raster_abandon(&mut s, id); + (e, true) + } }; assert_eq!(there, (here, starts), "{p}"); assert_eq!(s.map().layers.len(), layers, "{p}"); @@ -64984,7 +65070,7 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { assert_eq!(notices.len(), 1 + usize::from(excluded > 0) + usize::from(unreadable)); assert!(notices.iter().any(|n| n.text.starts_with("Candidate features skipped: 1"))); if excluded > 0 { - assert!(notices.iter().any(|n| n.text.starts_with(&format!("{excluded} features aren't drawn")))); + assert!(notices.iter().any(|n| n.text.starts_with(&format!("{excluded} of the returned matches and reference aren't drawn")))); } if unreadable { assert!( @@ -65005,7 +65091,7 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { let mark = s.notice_mark(); assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); - assert!(s.notices_since(mark).iter().any(|n| n.text.starts_with("2 features aren't drawn"))); + assert!(s.notices_since(mark).iter().any(|n| n.text.starts_with("2 of the returned matches and reference aren't drawn"))); let l = s.map_mut().layer_mut(id).unwrap(); l.display_filters[0].where_ = "missing = 1".into(); l.display_filters.push(rustgis_map::effects::DisplayFilter { @@ -65333,6 +65419,12 @@ fn similar_rejects_invalid_rows_without_selecting() { params["row"] = row; assert_eq!(s.run("data.similar", ¶ms).unwrap(), expected); } + // An integral float, as some clients send, is the same row as the integer. + let mut whole = params.clone(); + whole["row"] = json!(1); + let expected = s.run("data.similar", &whole).unwrap(); + whole["row"] = json!(1.0); + assert_eq!(s.run("data.similar", &whole).unwrap(), expected); } /// Invalid counts must be refused rather than silently changing the requested ranking size. @@ -65341,7 +65433,7 @@ fn similar_rejects_invalid_counts_without_selecting() { let (mut s, id) = similar_lifecycle_session(); s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); let depth = s.undo_depth(); - for count in [json!(0), json!(1001), json!(-1), json!("2"), json!(1.5)] { + for count in [json!(0), json!(0.0), json!(1001), json!(-1), json!("2"), json!(1.5)] { let error = s.run("data.similar", &json!({"layer":id,"row":0,"count":count,"fields":["n"]})).unwrap_err(); assert!(error.contains("count"), "{count}: {error}"); assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); @@ -65356,6 +65448,11 @@ fn similar_rejects_invalid_counts_without_selecting() { params["count"] = json!(count); assert_eq!(s.run("data.similar", ¶ms).unwrap()["similar"].as_array().unwrap().len(), count.min(2)); } + // An integral float, as some clients send, is the same count as the integer. + params["count"] = json!(5); + let five = s.run("data.similar", ¶ms).unwrap(); + params["count"] = json!(5.0); + assert_eq!(s.run("data.similar", ¶ms).unwrap(), five); } #[cfg(not(target_arch = "wasm32"))] @@ -66031,3 +66128,50 @@ fn headless_session_run_emits_cjk_scan_notice_only_when_lossy() { assert!(still_pending, "copy session must not consume the CJK scan summary once UI owns it"); } } + +/// `gp.batch` says a `folder` that isn't text, once, and still runs its `inputs`; a folder given +/// as text says nothing of the kind. +#[test] +fn gp_batch_says_a_folder_that_is_not_text() { + let mut s = world(); + let said = |s: &Session, mark: u64| s.notices_since(mark).iter().filter(|n| n.text.contains("'folder' must be a string")).count(); + let mark = s.notice_mark(); + let r = s.run("gp.batch", &json!({"tool": "repairGeometry", "inputs": ["Cities"], "folder": 5, "params": {}})).unwrap(); + assert_eq!(r["succeeded"], 1, "{r}"); + assert_eq!(said(&s, mark), 1, "{:?}", s.notices_since(mark)); + // A folder of its own, empty: given as text, it is read as a folder (and ignored beside inputs). + let root = std::env::temp_dir().join(format!("rustgis-batch-text-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let mark = s.notice_mark(); + let folder = root.display().to_string(); + s.run("gp.batch", &json!({"tool": "repairGeometry", "inputs": ["Cities"], "folder": folder, "params": {}})).unwrap(); + assert_eq!(said(&s, mark), 0, "{:?}", s.notices_since(mark)); + let _ = std::fs::remove_dir_all(&root); +} + +/// A folder batch counts entries that are neither files, folders nor links (a socket here) as +/// special files, not as unreadable entries; a folder of files alone says neither. +#[cfg(unix)] +#[test] +fn gp_batch_says_special_files_in_a_folder_apart_from_unreadable_entries() { + let root = std::env::temp_dir().join(format!("rustgis-batch-special-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let point = + r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#; + std::fs::write(root.join("a.geojson"), point).unwrap(); + let folder = root.display().to_string(); + let run = |s: &mut Session| { + let mark = s.notice_mark(); + s.run("gp.batch", &json!({"tool": "repairGeometry", "folder": folder, "params": {}})).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>() + }; + let mut s = Session::new(Project::default()); + let clean = run(&mut s); + assert!(!clean.iter().any(|n| n.contains("special file") || n.contains("unreadable")), "{clean:?}"); + let _socket = std::os::unix::net::UnixListener::bind(root.join("s.sock")).unwrap(); + let said = run(&mut s); + assert!(said.iter().any(|n| n.contains("1 special file(s) (not regular files) skipped")), "{said:?}"); + assert!(!said.iter().any(|n| n.contains("unreadable")), "{said:?}"); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/engine/src/tests/ogc_dataset.rs b/crates/engine/src/tests/ogc_dataset.rs index d159a28dd4..6ae4f51a12 100644 --- a/crates/engine/src/tests/ogc_dataset.rs +++ b/crates/engine/src/tests/ogc_dataset.rs @@ -93,7 +93,7 @@ fn ogc_dataset_stopped_discovery_counts_a_pending_tilejson_source_once() { for command in ["service.layers", "service.add"] { let error = session.run(command, ¶ms).unwrap_err(); assert!(error.contains("metadata budget"), "{error}"); - assert!(error.contains("1 TileJSON source checks were left out: dataset discovery stopped"), "{error}"); + assert!(error.contains("1 TileJSON source check was left out: dataset discovery stopped"), "{error}"); } } @@ -122,10 +122,10 @@ fn ogc_dataset_rejected_landing_links_never_guess_a_template() { .unwrap() .iter() .filter_map(Value::as_str) - .filter(|n| n.contains("tileset documents were left out")) + .filter(|n| n.contains("tileset document")) .collect::>(); assert_eq!(omitted.len(), 1, "{listing}"); - assert!(omitted[0].starts_with("1 tileset documents were left out")); + assert!(omitted[0].starts_with("1 tileset document was left out")); assert!(omitted[0].contains(reason), "{listing}"); } } @@ -252,7 +252,7 @@ fn ogc_dataset_unusable_style_catalogues_are_counted() { assert!(listing["next"].is_null(), "{listing}"); let notes = listing["notes"].as_array().unwrap(); if styles.is_some() { - assert_eq!(notes, &[json!("1 style catalogues were left out: no usable JSON link")], "{listing}"); + assert_eq!(notes, &[json!("1 style catalogue was left out: no usable JSON link")], "{listing}"); } else { assert!(notes.is_empty(), "{listing}"); } @@ -331,7 +331,7 @@ fn ogc_dataset_styles_use_advertised_projection_and_native_web_parity() { assert_eq!(native["count"], 1, "{native}"); assert_eq!(native["layers"][0]["name"], "rd-name"); assert_eq!(native["layers"][0]["offer"]["type"], "style"); - assert!(native["notes"].as_array().unwrap().iter().any(|n| n.as_str().unwrap().starts_with("1 styles were left out"))); + assert!(native["notes"].as_array().unwrap().iter().any(|n| n.as_str().unwrap().starts_with("1 style was left out"))); let requests = server.requests().len(); assert_eq!(requests, docs.len()); #[cfg(not(target_arch = "wasm32"))] @@ -412,7 +412,7 @@ fn ogc_dataset_styles_require_templates_allowed_from_the_tileset_document() { assert!(notes.is_empty(), "{listing}"); } else { assert!( - notes.iter().any(|n| n.as_str().unwrap().starts_with("1 tilesets were left out: disallowed template addresses")), + notes.iter().any(|n| n.as_str().unwrap().starts_with("1 tileset was left out: disallowed template addresses")), "{listing}" ); params["layer"] = json!("roads"); @@ -503,7 +503,7 @@ fn ogc_dataset_shared_documents_keep_independent_offers() { .as_array() .unwrap() .iter() - .any(|n| n.as_str().unwrap().starts_with("1 dataset documents were left out: repeated addresses")), + .any(|n| n.as_str().unwrap().starts_with("1 dataset document was left out: repeated addresses")), "{native}" ); let requests = server.requests(); @@ -757,7 +757,7 @@ fn ogc_dataset_linked_scheme_declarations_are_checked() { } else { assert_eq!(notes.len(), 1, "{listing}"); assert!( - notes[0].as_str().unwrap().starts_with("1 tilesets were left out: unsupported or undeclared tile matrix set"), + notes[0].as_str().unwrap().starts_with("1 tileset was left out: unsupported or undeclared tile matrix set"), "{listing}" ); } @@ -884,9 +884,9 @@ fn ogc_dataset_failed_discovery_keeps_prior_omission_counts() { for command in ["service.layers", "service.add"] { let error = session.run(command, ¶ms).unwrap_err(); assert!(error.contains("metadata budget"), "{error}"); - assert!(error.contains("1 tileset documents were left out: dataset discovery stopped"), "{error}"); - assert!(error.contains("1 style catalogues were left out: dataset discovery stopped"), "{error}"); - assert_eq!(error.contains("1 tilesets were left out"), omitted, "{error}"); + assert!(error.contains("1 tileset document was left out: dataset discovery stopped"), "{error}"); + assert!(error.contains("1 style catalogue was left out: dataset discovery stopped"), "{error}"); + assert_eq!(error.contains("1 tileset was left out"), omitted, "{error}"); #[cfg(not(target_arch = "wasm32"))] { use crate::cmd::reads::{read_ahead, read_land}; @@ -933,7 +933,7 @@ fn ogc_dataset_map_tiles_reject_declared_coverage_and_unknown_types() { assert!(notes.is_empty(), "{listing}"); } else { assert_eq!(notes.len(), 1, "{listing}"); - assert!(notes[0].as_str().unwrap().starts_with("1 tilesets were left out"), "{listing}"); + assert!(notes[0].as_str().unwrap().starts_with("1 tileset was left out"), "{listing}"); } } } diff --git a/crates/engine/src/tests/project_crs.rs b/crates/engine/src/tests/project_crs.rs index 3e9b3d9091..4ebc0dd1d3 100644 --- a/crates/engine/src/tests/project_crs.rs +++ b/crates/engine/src/tests/project_crs.rs @@ -168,6 +168,29 @@ fn a_layer_without_a_system_of_its_own_gives_none() { assert_eq!(s.project.coordinate_system, None); } +/// A feature layer whose file names WGS 84 (a Shapefile's `.prj`) is read in longitude/latitude +/// with no system of its own, as one that names none, so it gives none; a later projected layer +/// gives its system (docs/user-guide/maps.md). +#[test] +fn a_feature_layer_in_wgs84_gives_none_and_a_later_projected_one_gives_its_system() { + let (dir, lv95) = lv95_file("wgs84-first"); + let shp = dir.join("places.shp"); + let mut w = Session::new(Project::default()); + w.run("layer.template", &json!({"template": "points", "name": "Places"})).unwrap(); + w.map_mut().editing.settings.enabled = true; + w.run("edit.addFeature", &json!({"layer": "Places", "geometry": {"type": "Point", "coordinates": [7.43863, 46.95108]}})).unwrap(); + w.run("share.exportLayer", &json!({"layer": "Places", "path": shp})).unwrap(); + let prj = std::fs::read_to_string(dir.join("places.prj")).unwrap(); + assert!(prj.contains("WGS"), "the .prj names WGS 84: {prj}"); + let mut s = Session::new(Project::default()); + s.run("project.coordinateSystem", &json!({"fromFirstLayer": true})).unwrap(); + s.run("layer.addData", &json!({"path": shp})).unwrap(); + assert_eq!(s.project.coordinate_system, None); + s.run("layer.addData", &json!({"path": lv95, "name": "Bern"})).unwrap(); + assert_eq!(s.project.coordinate_system, Some(LV95)); + std::fs::remove_dir_all(&dir).ok(); +} + /// An ASCII grid of 4 × 3 cells at (x, y), 0.5 units a side. fn grid(dir: &std::path::Path, name: &str, x: f64, y: f64, prj: Option) -> std::path::PathBuf { let path = dir.join(format!("{name}.asc")); diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 19a2cb6e80..13f0a9ebe0 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -196,6 +196,25 @@ fn a_file_that_fits_or_has_a_sidecar_is_held_whole() { assert!(!raster(&s, "checks").tiled, "a sidecar keeps it whole"); } +/// A large tiled file whose header reports a loss (here a geographic system without an EPSG +/// code, read as WGS 84) is held whole, not read in place, and says its loss; the clean case is +/// `a_large_local_tiled_geotiff_draws_its_full_image_zoomed_in`. +#[test] +fn a_large_tiled_file_with_a_lossy_header_is_held_whole_and_says_so() { + use rustgis_data::raster::cog::{Example, example_with}; + let d = dir("lossy"); + let path = d.join("lossy.tif"); + std::fs::write(&path, example_with(&Example { size: 1024, tile: 512, no_epsg: true, ..Example::default() })).unwrap(); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + assert!(!raster(&s, "lossy").tiled, "a lossy header keeps it whole"); + let said = said(&s, mark); + assert!(!said.iter().any(|n| n.contains("read in place")), "{said:?}"); + assert!(said.iter().any(|n| n.contains("read as longitude/latitude on WGS 84")), "{said:?}"); +} + /// How each kind of run reads a raster layer read in place from its file: a built-in tool's run /// reads the file, a plugin's reads the overview the layer holds and says so, and a suite tool /// (which stages the file by its path) neither reads nor says anything. A layer held whole is diff --git a/crates/engine/testdata/reading-losses/README.md b/crates/engine/testdata/reading-losses/README.md index e42fc706d1..7fa19af4c3 100644 --- a/crates/engine/testdata/reading-losses/README.md +++ b/crates/engine/testdata/reading-losses/README.md @@ -149,6 +149,12 @@ OID `id=7` and string `name=Place`. `feature-xy.pbf` (100 bytes) is clean. `hasM`, a third coordinate 37, and that component's unit scale/zero translation. The clean file serves both pairs. This tests separate dimension flags, not renamed files. +| File | Bytes | SHA-256 | +|---|---|---| +| `feature-xy.pbf` | 100 | `c02aea6cf56166128686f1a6c8034844739965a64a823f60b04e2464b9e8744f` | +| `feature-xyz.pbf` | 121 | `f0fec1f171e722353b82905c467a3371d98e32e807f4a073ac1018bdd393e463` | +| `feature-xym.pbf` | 121 | `bf2bb92583b29a78993694e108260d86b9bebcb00b474c4a175e8a8524fe437e` | + The corpus checks exact geometry, feature ID, field names/types and attributes through `esripbf::read` and `layer.addData`, with no skipped features. The native and command messages must be exactly the one-feature Z/M drop message for XYZ/XYM and absent for XY. diff --git a/crates/engine/tests/integration/portable_projects/packages.rs b/crates/engine/tests/integration/portable_projects/packages.rs index 0dec75dba9..7f03167f1b 100644 --- a/crates/engine/tests/integration/portable_projects/packages.rs +++ b/crates/engine/tests/integration/portable_projects/packages.rs @@ -139,3 +139,22 @@ fn a_group_layer_file_names_the_layers_it_leaves_linked() { let raster = m.layers.iter().find_map(|l| l.raster.as_ref()).unwrap(); assert!(raster.embedded.is_some() && raster.path.is_none(), "embedded, not linked"); } + +/// A layer opened for editing from a GeoPackage holds its features but keeps the file's path to +/// save its edits back to, so a package names it as saving its edits outside; a copied layer +/// beside it isn't named. +#[test] +fn a_layer_edited_from_a_geopackage_is_named_as_left_linked() { + let f = Fixture::new("package-gpkg-edit"); + let path = f.file("edits.gpkg"); + gpkg_file(&path, &["sites"]); + rusqlite::Connection::open(&path).unwrap().execute("UPDATE gpkg_contents SET last_change = '2026-01-01T00:00:00.000Z'", []).unwrap(); + let mut s = session(); + s.run("project.sample", &serde_json::Value::Null).unwrap(); + s.run("gpkg.addLayer", &json!({"path": path, "table": "sites", "name": "Sites"})).unwrap(); + let said = package(&mut s, &f, "project.package", json!({})); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("Package Project: 1 layer(s) edited from a GeoPackage keep their features"), "{}", said[0]); + assert!(!said[0].contains("stay linked"), "{}", said[0]); + assert!(said[0].ends_with(": Sites"), "{}", said[0]); +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 8c584b1038..b1923bc42b 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -564,6 +564,14 @@ impl Layer { p.filter(|p| paths::is_local(p)) } + /// Whether the layer holds its features but saves its edits to a local file: one opened for + /// editing from a GeoPackage on this computer, with no linked file of its own + /// ([`Layer::linked_file`]). A package or layer file that holds the layer says so: it opens + /// with the features, but Save Edits needs that file. + pub fn edits_saved_outside(&self) -> bool { + self.linked_file().is_none() && self.gpkg.as_ref().is_some_and(|g| paths::is_local(&g.path)) + } + /// The dataset within the linked container. pub fn linked_table(&self) -> Option<&str> { self.raster.as_ref().and_then(|r| r.subdataset.as_deref()).or_else(|| { diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 012d58a81d..524822c82e 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -267,6 +267,32 @@ pub struct CategoriesBy { pub first: Option<(crate::symbology::Symbol, Vec, Vec)>, } +/// What redacts a note's text before [`quoted_expression`] cuts it: set by the engine, which knows +/// the logins to take out ([`set_redactor`]); none, and the text is cut as it is. +static REDACTOR: std::sync::OnceLock String> = std::sync::OnceLock::new(); + +/// Sets what [`quoted_expression`] redacts with, once for the process (a later call changes +/// nothing): a note is redacted again when it is published, but a login cut in two there would no +/// longer be recognised. +pub fn set_redactor(redact: fn(&str) -> String) { + let _ = REDACTOR.set(redact); +} + +/// A style's expression as a note quotes it: trimmed, redacted whole ([`set_redactor`]), then cut +/// to 80 characters with `…` when longer (one too long to read is longer than the expression +/// limit, so isn't quoted whole). Without a redactor one that would be cut isn't quoted at all +/// (fails closed): whole, the note is redacted when it is published, but cut it might not be. +pub fn quoted_expression(expr: &str) -> String { + let redacted = REDACTOR.get().map(|redact| redact(expr.trim())); + let e = redacted.as_deref().unwrap_or(expr).trim(); + let shown: String = e.chars().take(80).collect(); + match (shown.len() < e.len(), redacted.is_some()) { + (false, _) => shown, + (true, true) => format!("{shown}…"), + (true, false) => "…".to_string(), + } +} + /// Renames the Unique Values class `from` of `r` to `to`, with its label, strokes and fills; /// `false` (nothing renamed) when there is no such class or another class is already `to`. pub fn rename_class(r: &mut Renderer, from: &str, to: &str) -> bool { diff --git a/crates/map/src/qgis/renderer.rs b/crates/map/src/qgis/renderer.rs index 2f8dcaac6a..64662b4067 100644 --- a/crates/map/src/qgis/renderer.rs +++ b/crates/map/src/qgis/renderer.rs @@ -168,9 +168,7 @@ fn categorized(r: Node, layer: &str, style: &mut Style, report: &mut Report, sym "as nothing: no category is drawn" }; // (Quoted up to 80 characters: one too long to read is longer than `expr::MAX_LEN`.) - let a = attr.trim(); - let shown: String = a.chars().take(80).collect(); - let shown = if shown.len() < a.len() { format!("{shown}…") } else { shown }; + let shown = super::quoted_expression(attr); report.approximated( layer, format!("its classes by the expression `{shown}`, empty or too long to read: every feature drawn {drawn}"), diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 47550b3f57..21e831ee3d 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -3975,3 +3975,11 @@ fn layers_past_the_limit_are_coded_only_when_one_holds_data() { assert_eq!(past(memory), Some(None), "a memory layer opens empty: plain"); assert_eq!(past(vector), Some(Some(rustgis_data::loss::LossCode::DroppedFeature))); } + +/// Without a redactor (no engine session in this process), an expression that would be cut isn't +/// quoted at all, while a short one is quoted whole, as its note is redacted when published. +#[test] +fn a_quoted_expression_fails_closed_without_a_redactor() { + assert_eq!(super::quoted_expression(" \"a\" = 1 "), "\"a\" = 1"); + assert_eq!(super::quoted_expression(&"x".repeat(81)), "…"); +} diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 670fce03b1..3e4f64a0de 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -822,7 +822,7 @@ impl From<&Window> for WindowKey { struct Tally { windows: Vec<(WindowKey, Vec)>, /// Counts of windows past [`WINDOWS_COUNTED`], added up as they come. - // ponytail: past 64 windows between two notice passes a window read again adds up as before; + // Known limit: past 64 windows between two notice passes a window read again adds up as before; // keep rows' identity in `Batch` to count exactly. rest: Vec, } diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 131b149008..3ea5aa9d9a 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -577,8 +577,9 @@ fn read(url: &str, at: u64, len: u64, ceiling: crate::address::Reach, done: Done done(Err(e)); return; } - // Read on the fetch workers, as a web address's ranges are, never on the frame; not kept - // in the tile cache, as the file is at hand. + // Read on the fetch workers, as a web address's ranges are, never on the frame; its byte + // ranges aren't kept in the byte cache, as the file is at hand (its decoded tiles are, as + // a web address's). crate::cache::fetch_local(format!("{url}{RANGE}{at}-{end}"), done); return; } @@ -3402,8 +3403,16 @@ mod tests { #[test] fn a_local_geotiff_is_read_in_place_from_its_file() { let _turn = crate::cache::turn(); - let dir = std::env::temp_dir().join(format!("rustgis-cog-local-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + /// The test's folder, removed when it goes, whether the test passed. + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let held = Dir(std::env::temp_dir().join(format!("rustgis-cog-local-{}", std::process::id()))); + let dir = &held.0; + std::fs::create_dir_all(dir).unwrap(); let path = dir.join("local.tif"); std::fs::write(&path, cog::example(512, 128)).unwrap(); let url = path.display().to_string(); @@ -3466,7 +3475,6 @@ mod tests { let fresh = new_rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); assert_eq!(fresh.bands[0][1], 1.0, "pixel (1, 0) of the file, not the stale tile"); forget_local_file(&url); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index 765cfdfdab..9151cba842 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -164,10 +164,15 @@ fn read_overview(info: Arc, url: String, done: Box before, + (Some(_), Some(_)) => return Err(format!("{url}: the file changed while its overview was read: read it again")), + _ => { + return Err(format!( + "{url}: its modification details can't be read, so its overview can't be checked against the file: read it again" + )); + } }; // The revision checked, recorded as is (not the file's again). r.set_source_revision(revision); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 48d66ce9f4..6ddfa6c0d5 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -524,6 +524,8 @@ pub fn land_job(app: &mut RustGisApp) -> bool { // Likewise: its project was closed, so the raster it is making has nowhere to go. if !workflows::raster_waiting(&app.session, *id) { job.control.cancel(); + // Forgotten, so it holds no place among the runs kept waiting. + workflows::raster_abandon(&mut app.session, *id); let name = job.name; let section = job.section; app.workflow.job = None; @@ -564,7 +566,11 @@ pub fn land_job(app: &mut RustGisApp) -> bool { show_job(app, job.section, result); } Ok(false) => dropped(app, job.section, job.name), - Err(e) => show_job(app, job.section, Err(e)), + Err(e) => { + // It can't land now: forgotten, so it holds no place among the runs kept. + workflows::raster_abandon(&mut app.session, id); + show_job(app, job.section, Err(e)); + } }, Some(Err(e)) => { workflows::raster_abandon(&mut app.session, id); diff --git a/crates/ui-egui/src/conflictsui.rs b/crates/ui-egui/src/conflictsui.rs index eff1075675..c6633feeee 100644 --- a/crates/ui-egui/src/conflictsui.rs +++ b/crates/ui-egui/src/conflictsui.rs @@ -152,9 +152,11 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { if let Some(i) = dismiss { // The indexes are those of the list as it was drawn, in this state of the project. let state = app.session.state(); - let _ = app.run("offline.dismissConflicts", json!({"name": form.name, "conflicts": [i], "state": state})); - } else if all { - let _ = app.run("offline.dismissConflicts", json!({"name": form.name})); + if let Err(e) = app.run("offline.dismissConflicts", json!({"name": form.name, "conflicts": [i], "state": state})) { + app.session.notify(e, true); + } + } else if all && let Err(e) = app.run("offline.dismissConflicts", json!({"name": form.name})) { + app.session.notify(e, true); } if open { app.dialogs.conflicts = Some(form); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6f46962c5c..9fe9e24815 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3330,18 +3330,13 @@ fn coordinate_system(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) -> boo let first = app.session.map().layers.iter().find_map(|l| rustgis_engine::cmd::project::layer_system(l).map(|c| (c, l.name.clone()))); let offers = [ - ( - tl!("Use the project's"), - project.ok_or_else(|| tl!("The project has no coordinate system (Project Properties)").to_string()), - "useProject", - ), + (tl!("Use the project's"), project.ok_or_else(|| tl!("The project has no coordinate system (Project Properties)").to_string())), ( tl!("Use the first layer's"), first.map(|(c, _)| c).ok_or_else(|| tl!("No layer of the map has a coordinate system of its own").to_string()), - "useFirstLayer", ), ]; - for (label, crs, _) in offers { + for (label, crs) in offers { let projection = crs.and_then(|c| map_projection_for(c).map(|p| (c, p))); let r = ui.add_enabled(projection.is_ok(), egui::Button::new(label)); let r = match &projection { diff --git a/docs/cli.md b/docs/cli.md index 1c1bfa985c..a21dc8cd0e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -145,7 +145,9 @@ and before `--save`. That command, including a failed one, has already run: a fi project `--save` wrote when the save itself reported the loss, is already there. Standard error lists each loss by code, with how many notices reported it (each notice says how much it lost) and what to do about it. Other failures -still exit with status 1. +still exit with status 1. The check runs after each top-level `--cmd`, and after each `--data` or +`--project` load and `--save`, so the steps inside one `script.run` or `model.run` aren't stopped +one by one: a script runs to its end, and the stop comes after it. Repeat `--allow` to accept the losses a job expects, by kind (`dropped`, `changed`, `approximated` or `assumed`) or by code: diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index c9be0e8a53..f7cd3a09c7 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -701,7 +701,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | -| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"` (desktop and command line), only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. Keys for other kinds of address (`"crs"`, `"layer"`, `"x"`, `"y"` and the like) are refused with a box. Values past the range of 32-bit floats are counted over the box's cells; in a record downloaded whole the notice says they are the whole record's. In the app, and for a plugin's command it runs, the rows are read off the frame, listed in the status bar with how much has come and a Cancel, as a download is; each request waits at most a minute. | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MiB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"` (desktop and command line), only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. Keys for other kinds of address (`"crs"`, `"layer"`, `"x"`, `"y"` and the like) are refused with a box. Values past the range of 32-bit floats are counted over the box's cells; in a record downloaded whole the notice says they are the whole record's. In the app, and for a plugin's command it runs, the rows are read off the frame, listed in the status bar with how much has come and a Cancel, as a download is; each request waits at most a minute. | | SRTM height tile | `.hgt` | Add Data, or upload (desktop and browser) | One 1° tile of 16-bit heights in meters, 1201 × 1201 (3 arc-seconds), 3601 × 3601 (1 arc-second) or 7201 × 7201 (0.5 arc-second), read natively; a tile larger than the memory budget (a 0.5 arc-second tile in the browser) is read at every second sample or fewer, each kept sample still at its cell's center. The file name places it (`N37W122.hgt` is the tile whose south-west corner is 37°N, 122°W; an upload keeps its name), so a file whose name isn't a tile's, or whose size is neither grid's, is refused. Samples sit on the whole-degree lines, so each is a cell centered on its point and the layer reaches half a cell past the tile's edges. WGS 84; voids (−32768) are no data, and a notice counts them. Heights are above the EGM96 geoid (mean sea level), not the ellipsoid, and a notice says so once as the layer is added. SRTM and DTED files hold one band and give their own coordinates (read as WGS 84; a DTED file naming another datum says so), so a `"crs"` or `"layer"` given for one (or kept by a project saved when these files went through GDAL) is ignored, and a notice says so. | | DTED | `.dt0`, `.dt1`, `.dt2` | Add Data, or upload (desktop and browser) | DTED levels 0, 1 and 2, read natively per MIL-PRF-89020B: the UHL header gives the south-west post, the spacing (wider in longitude at high latitudes) and the counts. Posts are cells centered on them, as for SRTM. Voids (−32767) are no data and counted in a notice. In a two's-complement file, a void stored as 0x8001 reads as −1 m and no notice counts it; a height of −1 m stored as 0xFFFF reads as no data. A column whose record lacks its 0xAA sentinel is read as no data, and a notice counts those columns; a whole cell whose longitude counts number its columns from 1 rather than 0 is read by place, and a notice counts those columns; a file with any other longitude count that doesn't match its place (leading columns left out, counts offset, or a stray count), or a record whose latitude count isn't 0, is refused, naming the record, since its heights would land in the wrong place; a column whose checksum doesn't match its heights (some producers write them wrongly) is read as stored, and a notice counts those too. Heights some producers write in two's complement rather than signed magnitude (those that would read below −16000 m) are read as two's complement, and counted in a notice. A complete cell cut short opens with its missing columns as no data, and says so. A partial cell is read in the full-grid layout of CD-ROM files, its missing posts as voids; one in the magnetic-tape layout is refused when its DSI counts only the lines that have heights. A tape cell with a height on every line counts the whole cell too, but its file is shorter than the full grid's, so it's refused as well; a partial cell cut short is refused the same way, since the two can't be told apart. The level is the one the DSI record names (the extension's when it names none, and a notice says when the two differ). A spacing other than the specification's for the level and latitude, a DSI record that disagrees with the UHL, or a horizontal datum other than WGS 84 is said. The vertical datum (EGM96, or mean sea level) is said once, as for SRTM. | | Rasters GDAL reads | `.img`, `.dem`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. | diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 0a639b998d..feb5be347b 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -213,13 +213,14 @@ marked as sent in that folder: a package comes back once, so opening it again, e keeps no copy and says so; make a new one for more edits. If the return file is lost after **Send Field Package**, sending again goes back as a whole map, which the computer may refuse once another package of the area has come back, so keep the return file until the computer has it. The copy of a -package opened but never sent stays in that folder until it is removed by hand. **Send Field Package** compares the map with that copy and sends -the list of changes with the map. A package opened on a device that doesn't keep its rows (the -browser, or a field project copied to another device) goes back as a whole map, and the phone says -so: Bring Back then compares the map with the area as it was last synced, and refuses it if the area -has been brought back or synced since the package was made. A package made before packages carried -that return check has none: it comes back with a notice, and can undo or repeat what came home -since. +package opened but never sent stays in that folder until it is removed by hand. + +**Send Field Package** compares the map with that copy and sends the list of changes with the map. A +package opened on a device that doesn't keep its rows (the browser, or a field project copied to +another device) goes back as a whole map, and the phone says so: Bring Back then compares the map +with the area as it was last synced, and refuses it if the area has been brought back or synced +since the package was made. A package made before packages carried that return check has none: it +comes back with a notice, and can undo or repeat what came home since. Where a change meets one made on the computer since the package was made: diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 6a4805a1c2..d3779a970b 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -959,10 +959,11 @@ coordinates, so outputs and exports stay in longitude/latitude in it. layer added from data (**Home › Add**: a file, a URL, a service, a database; or a map imported, an offline map opened, layers pasted) that says what system it is in (a raster's, or a file's such as a GeoPackage's or a Shapefile's `.prj`), and says so; Undo -takes it back with the layer. A tool's output gives none. A layer that names no system, taken for -longitude/latitude, gives none, nor does a raster read as WGS 84 because its coordinates look like -degrees; one that names WGS 84 or another system in degrees gives that, and new maps then stay in -Web Mercator. A raster read in place gives its system once its pixels have arrived, at the next +takes it back with the layer. A tool's output gives none. A feature layer in WGS 84 gives none, +whether its file names it or names no system and it is taken for longitude/latitude, so a later +layer in a projected system gives its own; nor does a raster read as WGS 84 because its coordinates +look like degrees. A raster that names WGS 84 or another system in degrees gives that, and new maps +then stay in Web Mercator. A raster read in place gives its system once its pixels have arrived, at the next change to the project. The setting and the option are saved with the project; an older RustGIS refuses a project that has them (it needs `project-crs`) rather than saving it again without them.