diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 140c932c64..e716c160cc 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -1190,16 +1190,7 @@ fn cli() -> ExitCode { Ok(()) } "explain" => { - // The common options (`--threads 2`, `--use-saved-secrets`) are taken, and their values. - let mut words = Vec::new(); - let mut rest = args.iter().skip(1); - while let Some(arg) = rest.next() { - if VALUE_FLAGS.contains(&arg.as_str()) { - rest.next(); - } else if !arg.starts_with("--") { - words.push(arg.as_str()); - } - } + let words = explain_words(&args)?; match words.as_slice() { [] => explain(None), [code] => explain(Some(code)), @@ -1345,10 +1336,38 @@ fn cli() -> ExitCode { } } +/// The words `explain` is given (`args` from the subcommand on): the common options +/// (`--threads 2`, `--threads=2`, `--use-saved-secrets`, `--no-plugins`) are taken, and their +/// values; any other option is refused, so a typo isn't passed over without a word. +fn explain_words(args: &[String]) -> Result, String> { + const COMMON: &[&str] = &["--use-saved-secrets", "--no-plugins"]; + let mut words = Vec::new(); + let mut rest = args.iter().skip(1); + while let Some(arg) = rest.next() { + let joined = arg.split_once('=').is_some_and(|(flag, _)| VALUE_FLAGS.contains(&flag)); + if VALUE_FLAGS.contains(&arg.as_str()) { + rest.next(); + } else if !arg.starts_with("--") { + words.push(arg.as_str()); + } else if !joined && !COMMON.contains(&arg.as_str()) { + return Err(format!("explain: unknown option {arg}")); + } + } + Ok(words) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn explain_refuses_an_unknown_option_and_takes_the_common_ones() { + let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(explain_words(&args(&["explain", "--strcit", "dropped.value"])), Err("explain: unknown option --strcit".into())); + assert_eq!(explain_words(&args(&["explain", "--threads", "2", "dropped.value"])), Ok(vec!["dropped.value"])); + assert_eq!(explain_words(&args(&["explain", "--threads=2", "--use-saved-secrets", "--no-plugins"])), Ok(vec![])); + } + #[test] fn ask_takes_up_to_four_pictures_and_says_what_it_refuses() { // A 1 × 1 PNG. diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index f187aaa6b2..6e0ff14a1c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -17571,7 +17571,7 @@ mod tests { assert!(!one.messages.iter().any(|m| m.contains("uses the raster projection"))); assert!(said(&one).iter().any(|m| m == "2 zone feature(s) had no polygon with an area and were excluded"), "{:?}", said(&one)); assert!( - said(&one).iter().any(|m| m == "DroppedGeometry: 1 zone feature(s) had invalid polygon geometry and were excluded"), + said(&one).iter().any(|m| m == "DroppedFeature: 1 zone feature(s) had invalid polygon geometry and were excluded"), "{:?}", said(&one) ); diff --git a/crates/analysis/src/tools/tabulate_area.rs b/crates/analysis/src/tools/tabulate_area.rs index dc8bd854f7..79198da0cf 100644 --- a/crates/analysis/src/tools/tabulate_area.rs +++ b/crates/analysis/src/tools/tabulate_area.rs @@ -117,8 +117,9 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu } let mut losses = Vec::new(); if unreadable > 0 { + // A whole feature left out, coded as the clip codes the same loss. losses.push(LossMessage { - code: LossCode::DroppedGeometry, + code: LossCode::DroppedFeature, text: format!("{unreadable} zone feature(s) had invalid polygon geometry and were excluded"), }); } diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index c4e9924b8e..b29a8c3042 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -93,7 +93,7 @@ loss_codes! { "dropped.calculation-result", Dropped, "A calculation gave no result for some rows, so the field was left empty there. The input may have no place that can be given in longitude and latitude, or the result may be too large to hold.", - "Correct the expression or check the input rows named in the notice." + "Check the rows the notice names (or its expression, for a calculated field)." ), DroppedZm => ( "dropped.zm", diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 43babe5221..7e07700611 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1350,18 +1350,34 @@ impl Raster { if wrapped < w { wrapped } else { c } } + /// The width in columns of a geographic grid spanning exactly one turn of 360°, whose columns + /// go round (its last is next to its first); `None` for any other grid. Its span is compared, + /// rather than truncating `360 / pixel_width`: a regional grid can end partway through that + /// column. The map's relief and [`Raster::bilinear`] both read across the seam by it. + pub fn full_turn_width(&self) -> Option { + let span = f64::from(self.width) * self.transform.pixel_width.abs(); + (self.transformer.is_geographic() && (span - 360.0).abs() <= 360.0 * 16.0 * f64::EPSILON).then_some(i64::from(self.width)) + } + /// The value of `band` at a longitude/latitude point, read bilinearly between the four cell /// centres around it, in the raster's own system: the nearest cell's where one of the four is /// no-data or off the grid, and `None` where that one is too. A grid stored from 0 to 360° is - /// read at a western longitude in its columns past 180° ([`Raster::wrap_col`]). The elevation profiles read - /// this (`profile.*`, and a layout's profiles beside a map frame, #2863). + /// read at a western longitude in its columns past 180° ([`Raster::wrap_col`]); a geographic + /// grid spanning exactly one turn is read across its seam, between its last column and its + /// first, as the map draws it. The elevation profiles read this (`profile.*`, and a layout's + /// profiles beside a map frame, #2863). pub fn bilinear(&self, band: usize, lonlat: Coord) -> Option { let w = self.transformer.from_lonlat(lonlat)?; let (x, y) = self.transform.to_pixel(w); let (x, y) = (self.wrap_col(x) - 0.5, y - 0.5); let (c0, r0) = (x.floor() as i64, y.floor() as i64); let (fx, fy) = (x - c0 as f64, y - r0 as f64); - let v = |c: i64, r: i64| self.value(band, c, r).map(f64::from); + // One turn wide: its columns go round. + let turn = self.full_turn_width(); + let v = |c: i64, r: i64| { + let c = turn.map_or(c, |w| if c < 0 || c >= w { c.rem_euclid(w) } else { c }); + self.value(band, c, r).map(f64::from) + }; match (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)) { (Some(a), Some(b), Some(c), Some(d)) => { Some(a * (1.0 - fx) * (1.0 - fy) + b * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy) @@ -2810,6 +2826,31 @@ pub(crate) mod tests { assert!(at(-100.1).is_some_and(|v| (v - 519.8).abs() < 1e-6), "259.9°: {:?}", at(-100.1)); } + /// A grid one turn wide is read across its seam: between its last column's centre and 360° + /// (or its first column's centre and 0°), the blend of its last and first columns, not the + /// nearest cell's value. + #[test] + fn a_grid_one_turn_wide_is_read_bilinearly_across_its_seam() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 90.0, pixel_width: 90.0, pixel_height: -90.0 }; + let row = [10.0, 20.0, 30.0, 40.0]; + let data = row.iter().chain(&row).copied().collect(); + let r = Raster::new("g", 4, 2, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let at = |lon: f64| r.bilinear(0, Coord::new(lon, 0.0)); + // A quarter of a cell past the last column's centre (315°), and a quarter short of the + // first's (45°). + for (lon, blend) in [(-22.5, 32.5), (337.5, 32.5), (22.5, 17.5)] { + assert!(at(lon).is_some_and(|v| (v - blend).abs() < 1e-9), "{lon}: {:?}", at(lon)); + } + // Inside, as before. + assert!(at(90.0).is_some_and(|v| (v - 15.0).abs() < 1e-9), "{:?}", at(90.0)); + // A grid short of a turn keeps the nearest cell there. + let gt = GeoTransform { pixel_width: 80.0, ..gt }; + let short = + Raster::new("s", 4, 2, vec![row.iter().chain(&row).copied().collect()], gt, Crs::LonLat, None, ColorHint::Gray, "Float32") + .unwrap(); + assert_eq!(short.bilinear(0, Coord::new(5.0, 0.0)), Some(10.0)); + } + #[test] fn geographic_extent_uses_greenwich_not_the_native_prime_meridian() { let crs = Crs::parse("+proj=longlat +datum=WGS84 +pm=paris +no_defs").unwrap(); diff --git a/crates/data/src/source/remote.rs b/crates/data/src/source/remote.rs index 3e147fba15..39dfe55cc6 100644 --- a/crates/data/src/source/remote.rs +++ b/crates/data/src/source/remote.rs @@ -665,6 +665,14 @@ pub fn forget_file(url: &str) { files().lock().unwrap_or_else(|e| e.into_inner()).retain(|r| r.url != url); } +/// Forgets the fetched parts of every file of `urls`, going through the files once for them all. +pub fn forget_files(urls: &std::collections::HashSet) { + if urls.is_empty() { + return; + } + files().lock().unwrap_or_else(|e| e.into_inner()).retain(|r| !urls.contains(&r.url)); +} + /// The error a read that needs bytes gives (it runs again once they are fetched). pub fn need() -> DataError { DataError::Format(NEED.into()) @@ -1004,6 +1012,19 @@ pub(crate) mod testing { mod tests { use super::*; + /// Forgetting files together drops each of them and keeps the others. + #[test] + fn forgetting_files_together_drops_each_and_keeps_the_rest() { + let urls = ["https://forget-files.test/a.fgb", "https://forget-files.test/b.fgb", "https://forget-files.test/c.fgb"]; + for url in urls { + file(url); + } + forget_files(&std::collections::HashSet::from([urls[0].to_string(), urls[1].to_string()])); + let held: Vec = files().lock().unwrap().iter().map(|r| r.url.clone()).filter(|u| u.contains("forget-files.test")).collect(); + assert_eq!(held, [urls[2]]); + forget_file(urls[2]); + } + #[test] fn held_ranges_and_late_publications_are_revoked() { crate::login_address::set_validator(testing::validate_login); diff --git a/crates/engine/src/cmd/catalogs.rs b/crates/engine/src/cmd/catalogs.rs index 2ea856d91c..91247285a5 100644 --- a/crates/engine/src/cmd/catalogs.rs +++ b/crates/engine/src/cmd/catalogs.rs @@ -11,7 +11,7 @@ use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { vec![ C::new("overture.add", "Add Overture Maps Data", "Home › Add › Web Data", overture_add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"theme": "buildings"|"places"|"transportation"|"divisions"|"base"|"addresses", "type"?: "the theme's type (building, building_part; place; segment, connector; division_area, division, division_boundary; land_use, land, land_cover, water, infrastructure, bathymetry; address)", "release"?: "such as 2026-09-23.1 (default: the latest)", "bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "tiles"?: bool (the whole world as map tiles, from the theme's PMTiles archive, instead of the features in view), "files"?: [the files' GeoParquet addresses, when already found and opened (the app's background requests)]} (in a plugin's command in the app the files are left to download: it answers pending, with the layers already in, and the command runs again once they are added; see docs/plugins.md)"#, + r#"{"theme": "buildings"|"places"|"transportation"|"divisions"|"base"|"addresses", "type"?: "the theme's type (building, building_part; place; segment, connector; division_area, division, division_boundary; land_use, land, land_cover, water, infrastructure, bathymetry; address)", "release"?: "such as 2026-09-23.1 (default: the latest)", "bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "tiles"?: bool (the whole world as map tiles, from the theme's PMTiles archive, instead of the features in view), "files"?: [the files' GeoParquet addresses, when already found and opened (the app's background requests)]}"#, ), C::new("sourcecoop.products", "List Source Cooperative Products", "Home › Add › Web Data", sourcecoop_products).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)) .view() diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 9d33bdac7e..20b2ad146b 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -185,7 +185,7 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { let mut keep = placed.into_iter(); src.features.retain_rows(|_| keep.next().unwrap_or(true)); if src.features.is_empty() { - return Err(format!("Paste: the copied feature(s) have a place {} ({}) can't hold", l.name, own.label())); + return Err(format!("Paste: the copied feature(s) have a place that layer {} ({}) can't hold", l.name, own.label())); } } // Ids for every feature the layer takes (one of another shape is left out below), above every id diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 211c2bf768..98db9d3f11 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -3161,6 +3161,12 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option Json { + json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat, "located": e.lon.is_finite() && e.lat.is_finite()}) +} + /// Checks every topology rule; the errors are kept for the Error Inspector. The work grows with /// the layers, so the desktop app checks them on a thread of its own first ([`topology_ahead`]), /// with the status bar's progress and **Cancel**, and the command takes that check as it lands; @@ -3169,12 +3175,6 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option Json { - json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat, "located": e.lon.is_finite() && e.lat.is_finite()}) -} - fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { let tol = topology_tolerance(p); let inputs = topology_checks(s); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index b457d3a638..c69d5f5b4b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -846,9 +846,6 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { Ok(i) => (Value::Int(i), Cut::None, None), Err(_) => match (decimal_text(t.trim()), t.trim().parse::()) { (Some((v, cut)), Ok(f)) => (v, cut, Some(f)), - // A word the decimal reader takes ("inf", "NaN") isn't a number written as text: - // null, and said so, as not a number. - // A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one. // A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one, and // digits past those it holds (`9007199254740993e0`) are rounded. (None, Ok(f)) if f.is_finite() || t.bytes().any(|b| b.is_ascii_digit()) => match whole(f) { @@ -856,6 +853,8 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { (v @ Value::Int(_), Cut::None, x) if !rustgis_data::io::double_holds(t.trim()) => (v, Cut::Rounded, x), held => held, }, + // A word the decimal reader takes ("inf", "NaN") isn't a number written as text: + // null, and said so, as not a number. (None, Ok(f)) if f.is_infinite() => (Value::Null, Cut::NotFinite, None), (None, Ok(_)) => (Value::Null, Cut::NotANumber, None), _ => (Value::parse(&t, ty), Cut::None, None), diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index bc5dbd2967..49c09969ad 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -388,6 +388,13 @@ const CJK_PENDING: &str = "CJK font folder scan is still running; try exporting /// What is said of an export during which that scan started. const CJK_STARTED: &str = "CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing."; +/// `build`'s result, and whether a CJK font folder scan started while it ran: watched only for a +/// `command` that draws with installed fonts ([`uses_fonts`]). The caller says [`CJK_STARTED`] +/// when one did. +fn built_with_fonts(command: &str, build: impl FnOnce() -> T) -> (T, bool) { + if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(build) } else { (build(), false) } +} + #[cfg(test)] thread_local! { static TEST_CJK_SCAN_PENDING: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -421,12 +428,8 @@ pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult let control = if s.stoppable { rustgis_analysis::control::Control::stoppable() } else { rustgis_analysis::control::Control::new() }; let (mut wrote, pending_cjk) = crate::render::rustgis_tiles::cache::with_still(still, || { let work = start(s, &p)?; - if uses_fonts(command) { - let (res, hit) = rustgis_render::fonts::track_pending_cjk(|| written_under(name, &control, work)); - Ok::<_, String>((res?, hit)) - } else { - Ok((written_under(name, &control, work)?, false)) - } + let (res, hit) = built_with_fonts(command, || written_under(name, &control, work)); + Ok::<_, String>((res?, hit)) })?; if pending_cjk { wrote.diagnostics.push((rustgis_data::diagnostics::Severity::Warning, CJK_STARTED.into())); @@ -484,8 +487,7 @@ pub(crate) fn file_command( let mark = s.notice_mark(); let path = super::ps(p, "path").ok_or("path is required")?; let out = Output { path, room: None }; - let (made, pending_cjk) = - if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(|| build(s, out)) } else { (build(s, out), false) }; + let (made, pending_cjk) = built_with_fonts(command, || build(s, out)); let made = made?; rustgis_data::io::write_atomic(std::path::Path::new(path), &made.bytes).map_err(|e| format!("{path}: {e}"))?; for note in made.notes { @@ -523,8 +525,7 @@ pub(crate) fn download_command( let out = Output { path: &name, room: s.download_room()? }; // What making the file says waits with it. let (made, held) = s.holding_notices(|s| { - let (made, pending_cjk) = - if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(|| build(s, out)) } else { (build(s, out), false) }; + let (made, pending_cjk) = built_with_fonts(command, || build(s, out)); let mut made = made?; for note in std::mem::take(&mut made.notes) { s.say(note); diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index a2ab0c4003..d74cf53b2c 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2265,7 +2265,7 @@ fn inputs_in( // Counted over each whole layer, before the run's rows are narrowed to a selection: some may // be rows the tool doesn't read, so it isn't a coded loss. said.push(rustgis_data::loss::Note::plain(format!( - "{name}: {n} feature(s) of {layers} have a place that can't be given in longitude/latitude, so the tool reads them without their geometry" + "{name}: {n} feature(s) of {layers} have a place that can't be given in longitude/latitude, so any of them the tool reads have no geometry" ))); } if !bent.is_empty() { diff --git a/crates/engine/src/cmd/graphics.rs b/crates/engine/src/cmd/graphics.rs index de5b9e43a7..2d060ef9bf 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -129,11 +129,21 @@ fn points(p: &Value, plane: &Plane) -> Result<(Vec, usize), String> { Ok(plane.clamped(given)) } -/// Says that `n` points of a graphic were placed at 85°, where a Web Mercator map stops. -fn say_clamped(s: &mut Session, n: usize) { - if n > 0 { - s.notify(format!("{n} point(s) of the graphic past 85° latitude were placed at 85°: a Web Mercator map can't show a pole"), false); +/// Says that `n` points of a graphic (those given, or of the ring or curve built through them) +/// were placed at ±85°: built in Web Mercator (the default plane), which can't show a pole, or on a +/// view of a map that stops there ([`Plane::lat_max`]). +fn say_clamped(s: &mut Session, n: usize, plane: &Plane) { + if n == 0 { + return; } + let why = match plane { + Plane::Mercator => { + "built in Web Mercator, which can't show a pole (\"frame\": \"view\" keeps them where given on a map that shows one)" + } + Plane::View { .. } => "built on the map's view, which stops there", + }; + let m = plane.lat_max(); + s.notify(format!("{n} point(s) of the graphic beyond ±{m}° latitude were placed at ±{m}°: {why}"), false); } fn need(pts: &[Coord], n: usize, shape: &str) -> Result<(), String> { @@ -230,13 +240,28 @@ impl Plane { pts.iter().map(|c| self.to(*c).ok_or_else(|| format!("a point of the {shape} isn't on the map"))).collect() } - fn all_back(&self, pts: impl IntoIterator, shape: &str) -> Result, String> { - pts.into_iter().map(|v| self.back(v).ok_or_else(|| format!("the {shape} reaches past the map's projection"))).collect() + /// `pts` in the plane read back in longitude/latitude, kept within [`Plane::lat_max`] as the + /// points given are (a ring round a point near 85° can reach past it), and how many were moved + /// further than a round trip's rounding (a corner given at 85° may read back a hair past it). + fn all_back(&self, pts: impl IntoIterator, shape: &str) -> Result<(Vec, usize), String> { + let m = self.lat_max(); + let mut moved = 0; + let back = pts + .into_iter() + .map(|v| { + let c = self.back(v).ok_or_else(|| format!("the {shape} reaches past the map's projection"))?; + let y = c.y.clamp(-m, m); + moved += usize::from((y - c.y).abs() > 1e-9); + Ok(Coord::new(c.x, y)) + }) + .collect::, String>>()?; + Ok((back, moved)) } } -/// A smooth curve through the points (Catmull-Rom), in the plane. -fn curve(pts: &[Coord], plane: &Plane) -> Result, String> { +/// A smooth curve through the points (Catmull-Rom), in the plane, and how many of its points +/// were moved within its latitude ([`Plane::all_back`]). +fn curve(pts: &[Coord], plane: &Plane) -> Result<(Vec, usize), String> { let m = plane.all_to(pts, "curve")?; let n = m.len(); let at = |i: isize| m.get(i.clamp(0, n as isize - 1) as usize).copied().unwrap_or_default(); @@ -258,15 +283,17 @@ fn curve(pts: &[Coord], plane: &Plane) -> Result, String> { plane.all_back(out, "curve") } -/// An ellipse inscribed in the box between two corners in the plane, drawn round there. -fn ellipse(a: Coord, b: Coord, plane: &Plane, shape: &str) -> Result, String> { +/// An ellipse inscribed in the box between two corners in the plane, drawn round there, and how +/// many of its points were moved within its latitude ([`Plane::all_back`]). +fn ellipse(a: Coord, b: Coord, plane: &Plane, shape: &str) -> Result<(Vec, usize), String> { let (cx, cy) = ((a.x + b.x) / 2.0, (a.y + b.y) / 2.0); let (rx, ry) = ((a.x - b.x).abs() / 2.0, (a.y - b.y).abs() / 2.0); let around = (0..72).map(|i| { let t = i as f64 / 72.0 * std::f64::consts::TAU; Coord::new(cx + rx * t.cos(), cy + ry * t.sin()) }); - Ok(ring(plane.all_back(around, shape)?)) + let (pts, moved) = plane.all_back(around, shape)?; + Ok((ring(pts), moved)) } /// Two corners in the plane, refused when they share a side. @@ -284,7 +311,18 @@ fn corners(pts: &[Coord], plane: &Plane, shape: &str) -> Result<(Coord, Coord), /// A picture is a box of longitudes and latitudes in every plane: it is drawn upright on the /// map over its box there. pub fn geometry(shape: &str, pts: Vec, plane: &Plane) -> Result { - Ok(match shape { + built(shape, pts, plane).map(|(g, _)| g) +} + +/// [`geometry`], and how many points of the ring or curve built were moved within the plane's +/// latitude ([`Plane::all_back`]), to say with those given. +fn built(shape: &str, pts: Vec, plane: &Plane) -> Result<(Geometry, usize), String> { + let mut moved = 0; + let mut count = |(pts, n): (Vec, usize)| { + moved += n; + pts + }; + let g = match shape { "point" | "text" => Geometry::Point(*pts.first().ok_or("a point needs a location")?), "line" | "freehand" => { need(&pts, 2, shape)?; @@ -292,7 +330,7 @@ pub fn geometry(shape: &str, pts: Vec, plane: &Plane) -> Result { need(&pts, 2, shape)?; - Geometry::Line(vec![curve(&pts, plane)?]) + Geometry::Line(vec![count(curve(&pts, plane)?)]) } "polygon" | "lasso" => { need(&pts, 3, shape)?; @@ -302,7 +340,7 @@ pub fn geometry(shape: &str, pts: Vec, plane: &Plane) -> Result { let (a, b) = ends(&pts, shape)?; @@ -325,14 +363,15 @@ pub fn geometry(shape: &str, pts: Vec, plane: &Plane) -> Result { let (a, b) = corners(&pts, plane, shape)?; - Geometry::Polygon(vec![vec![ellipse(a, b, plane, shape)?]]) + Geometry::Polygon(vec![vec![count(ellipse(a, b, plane, shape)?)]]) } other => return Err(format!("unknown shape '{other}'")), - }) + }; + Ok((g, moved)) } /// The outline a shape dragged between `pts` takes on the map (`"frame": "view"`), in @@ -399,11 +438,15 @@ fn color(p: &Value, k: &str) -> Result, String> { } } -/// The picture's bytes as base64, from `image` or a file `path`. +/// The picture's bytes as base64, from `image` or a file `path`. A path that is an address is +/// refused before anything is read, and a file that can't be read is named by its name only, as +/// the layout commands name it: the path given could hold folders or a login, which would reach +/// the refusal, the notice and the Assistant's tool result. pub(crate) fn picture(p: &Value) -> Result { match (ps(p, "image"), ps(p, "path")) { (Some(b), _) => checked_picture(b.trim().to_string()), - (None, Some(path)) => picture_file(path, path), + (None, Some(path)) if rustgis_map::layout::picture_path_is_address(path) => Err(super::layout::PICTURE_ADDRESS.into()), + (None, Some(path)) => picture_file(path, super::layout::picture_named(path)), (None, None) => Err("a picture needs an image or a path".into()), } } @@ -493,8 +536,9 @@ fn add(s: &mut Session, p: &Value) -> CmdResult { return Err(format!("unknown shape '{shape}'")); } let plane = Plane::of(s, p)?; - let (pts, clamped) = points(p, &plane)?; - let g = geometry(&shape, pts, &plane)?; + let (pts, given) = points(p, &plane)?; + let (g, of_ring) = built(&shape, pts, &plane)?; + let clamped = given + of_ring; let text = ps(p, "text").map(|t| super::within("text", "a graphic's text", t, 2000)).transpose()?; if shape == "text" && text.as_deref().is_none_or(|t| t.trim().is_empty()) { return Err("text is required".into()); @@ -536,7 +580,7 @@ fn add(s: &mut Session, p: &Value) -> CmdResult { } } l.touch_geometry(); - say_clamped(s, clamped); + say_clamped(s, clamped, &plane); Ok(json!({"layer": id, "row": row, "shape": shape})) } @@ -573,11 +617,11 @@ fn edit(s: &mut Session, p: &Value) -> CmdResult { // As the map shows it: a point at 88° on a polar map stays there. let plane = Plane::view(s); let (pts, clamped) = points(p, &plane)?; - Some((geometry(&kind, pts, &plane)?, clamped)) + Some((geometry(&kind, pts, &plane)?, clamped, plane)) } None => None, }; - if let Some((g, clamped)) = placed { + if let Some((g, clamped, plane)) = placed { let held = super::design::held_places(s, id, &[], &[&g]); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; // Placed in longitude/latitude, written in the layer's own coordinates. @@ -586,7 +630,7 @@ fn edit(s: &mut Session, p: &Value) -> CmdResult { ft.geometry = Some(g); } l.touch_geometry(); - say_clamped(s, clamped); + say_clamped(s, clamped, &plane); // A null is no style, as `restyle` reads it: placed with only nulls, it is just placed. let styled = ["text", "fill", "outline", "width", "size", "fontSize", "bold", "italic", "align", "letterSpacing"] .iter() diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index 2941e3661f..8a3c5a14db 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -34,6 +34,9 @@ pub(crate) const BLOCK: (u32, u32) = (BLOCK_COLUMNS, cogwrite::TILE); /// layer reading a file in place holds of it (`rustgis_tiles::cog::raster::overview_level`), so /// it holds the same overview once the project is opened again. const OVERVIEW_SAMPLES: usize = if cfg!(test) { 1 << 16 } else { 2 << 20 }; +// Outside tests the writer keeps the overview the reader picks (the tests lower the writer's). +#[cfg(not(test))] +const _: () = assert!(OVERVIEW_SAMPLES == crate::render::rustgis_tiles::cog::raster::OVERVIEW_SAMPLES); /// The cells around a block a raster function reads with it (`function`): none for one that works /// cell by cell, one for one over a cell's eight neighbours. `None` for one that doesn't work in diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 083d198097..62b243002f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -4871,7 +4871,7 @@ fn read_sheet(p: &Value, file_name: &str, bytes: &[u8]) -> Result<(rustgis_data: /// given. pub(crate) fn csv_options(p: &Value) -> Result, String> { let text = |k: &str| ps(p, k).map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); - let (x, y, wkt, crs, delimiter) = (text("x"), text("y"), text("wkt"), text("crs"), ps(p, "delimiter")); + let (x, y, wkt, crs, delimiter) = (text("x"), text("y"), text("wkt"), text("crs"), ps(p, "delimiter").filter(|d| !d.is_empty())); if x.is_none() && y.is_none() && wkt.is_none() && crs.is_none() && delimiter.is_none() { return Ok(None); } @@ -4886,10 +4886,11 @@ fn zip_options(p: &Value, crs: Option) -> Result) -> Result, String> { match d { - None => Ok(None), + None | Some("") => Ok(None), Some("\\t" | "tab" | "\t") => Ok(Some(b'\t')), Some(d) if d.len() == 1 && d.is_ascii() && !d.starts_with(['"', '\n', '\r']) => Ok(d.bytes().next()), Some(d) => Err(format!("delimiter '{d}': give one character, such as ; or \\t")), @@ -8611,7 +8612,7 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult { ); } if group.cut > 0 { - s.notify(format!("The group's label was cut to at most {MAX_LABEL} characters; {} were left out", group.cut), false); + s.notify(format!("The group's label was cut to at most {MAX_LABEL} characters; {} characters were left out", group.cut), false); } if group.relabelled > 0 { s.notify( diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index fcf3484f75..9f50648aef 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -27,6 +27,7 @@ use crate::{CmdResult, CommandSpec as C, Session}; mod chart; use chart::*; mod elements; +pub use elements::add_element_reads_frame; pub(crate) use elements::*; mod export; pub(in crate::cmd) use export::chart_notice_lines_in; @@ -49,6 +50,7 @@ mod picture; pub(crate) use picture::gives_picture; pub(in crate::cmd) use picture::say_pictures_not_drawn; use picture::*; +pub(in crate::cmd) use picture::{PICTURE_ADDRESS, picture_named}; mod page; use page::*; mod profile; @@ -194,7 +196,7 @@ pub fn commands() -> Vec { concat!( r##"{"layout"?, "##, r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid"|"section" (a section line over a map frame, named at both ends, A and A', up to 26 a frame; as a grid or an extentIndicator, it adds no element: the reply's "element" is its frame, the one layout.update changes it on with "section", and "section" its name)|"profile" (a raster's profile along a section line of the frame, beside the frame on the side the line runs along, lined up with it: each sample is read at its point of the page line, through the frame's projection, so the curve is straight across from the place it comes from; its box is the frame's side, which it follows when the frame is moved or resized; a tilted frame, one on the globe, or a raster read in place draws none, which a notice and exports say), "##, - r##""frame"?: element id (default: the first map frame), "##, + r##""frame"?: element id (default: the first map frame; read by a northArrow, scaleBar, legend, colorbar, table, chart, grid, extentIndicator, section or profile; other kinds ignore it, and say so), "##, r##""of"?: frame id (extentIndicator: the frame to outline, with "color" and "width" in points, default red and 2, or for a frame's first one the look it kept from indicators removed; a frame outlines up to 16 others, and giving one it outlines already restyles that outline), "##, r##""text"? (a text's words; {count:Layer}, {sum:Layer:field}, {mean:Layer:field}, {min:Layer:field} and {max:Layer:field} show the layer's figure, as {scale} shows the scale: of the first map frame's map, over the features the layer's definition query keeps, with the layout's decimal mark; one with no figure shows as written and says why), "##, r##""size"?, "##, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 58ee23f2f5..5a6e427f0d 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -801,6 +801,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu } say_held(s, "Add Element", held); say_name_ignored(s, p, kind); + say_frame_ignored(s, p, kind); let mut out = json!({"element": id}); if let Some(w) = warning { out["warning"] = json!(w); @@ -879,6 +880,15 @@ fn say_name_ignored(s: &mut Session, p: &Value, kind: &str) { } } +/// Says a `frame` given a kind with no frame to read it for is ignored: taken rather than refused, +/// as every release before took it with every kind (the ribbon sent one, and recorded steps may +/// still), but not passed over without a word. +fn say_frame_ignored(s: &mut Session, p: &Value, kind: &str) { + if gives(p, "frame") && !add_element_reads_frame(kind) { + s.notify(format!("Add Element ignores \"frame\": {kind} isn't drawn from a map frame"), false); + } +} + /// What a `direction` or an `at` given for an element that isn't a section is told. const ONLY_SECTION: &str = "only sections take a direction and a place (at)"; /// What `layout.addElement` takes for a section. @@ -1043,11 +1053,20 @@ pub(in crate::cmd::layout) const ADD_GRID_KEYS: &[&str] = &[ ]; /// Keys `layout.addElement` takes of any kind though a kind may not read them, so its error does not -/// list them: `frame`, which the ribbon sends with every kind (a text, picture, rectangle, ellipse, -/// circle, line or arrow has no frame to read it for, so it is dropped there still), and `name`, -/// which a kind that isn't a section says it ignores (`say_name_ignored`) rather than refuses. +/// list them: `name`, which a kind that isn't a section says it ignores (`say_name_ignored`) rather +/// than refuses, and `frame`, which a text, picture, rectangle, ellipse, circle, line or arrow has +/// no frame to read for: it says so (`say_frame_ignored`), as steps recorded when the ribbon sent +/// it with every kind still give it. The ribbon now sends it only to the kinds that read it +/// ([`add_element_reads_frame`]). const ADD_ACCEPTED_KEYS: &[&str] = &["frame", "name"]; +/// Whether `layout.addElement` reads a `frame` for an element of `kind`: a north arrow, scale bar, +/// legend, colorbar, table, chart, grid, extent indicator, section or profile does; the others +/// ignore one, and say so. +pub fn add_element_reads_frame(kind: &str) -> bool { + added_keys(kind).is_none_or(|(_, keys)| keys.contains(&"frame")) +} + /// Keys read by `layout.addElement` for a north arrow (#3074). const ADD_NORTH_ARROW_KEYS: &[&str] = &["layout", "kind", "frame", "x", "y", "w", "h", "background", "style", "fill", "outline"]; @@ -1564,8 +1583,28 @@ mod tests { let mut p = base; p["kind"] = json!(kind); p["layout"] = json!(0); + if super::add_element_reads_frame(kind) { + p["frame"] = json!(frame); + } + s.run("layout.addElement", &p).unwrap_or_else(|e| panic!("{kind}: {e}")); + } + + // A frame given a kind that has none to read it for (as steps recorded from the ribbon + // give it) is taken and said to be ignored; one given a kind that reads it says nothing. + for (kind, base, _) in added_kinds() { + let mut p = base; + p["kind"] = json!(kind); p["frame"] = json!(frame); + let mark = s.notice_mark(); s.run("layout.addElement", &p).unwrap_or_else(|e| panic!("{kind}: {e}")); + let ignored = s.notices_since(mark).iter().any(|n| n.text.contains("ignores \"frame\"")); + assert_eq!(ignored, !super::add_element_reads_frame(kind), "{kind}"); + } + for kind in ["northArrow", "scaleBar", "legend", "colorbar", "table", "chart", "grid", "extentIndicator", "section", "profile"] { + assert!(super::add_element_reads_frame(kind), "{kind}"); + } + for kind in ["text", "dynamicText", "picture", "rectangle", "ellipse", "circle", "line", "arrow"] { + assert!(!super::add_element_reads_frame(kind), "{kind}"); } // Null counts as not given. diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index a7beea6403..9c2740d79d 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -11,7 +11,7 @@ pub(in crate::cmd::layout) const PICTURE_PATH: &str = "path is the path of a PNG pub(in crate::cmd::layout) const PICTURE_IMAGE: &str = "image is a PNG or JPEG image in base64"; /// A `path` that is an address, which is never tried as a file nor fetched, and never repeated /// (it could carry a login). -pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from a file on this computer, not an address"; +pub(in crate::cmd) const PICTURE_ADDRESS: &str = "a picture is read from a file on this computer, not an address"; /// A `path` given in the browser. pub(in crate::cmd::layout) const PICTURE_PATH_IN_BROWSER: &str = "a picture's path can't be read in the browser, which has no file paths: give its image"; @@ -82,6 +82,15 @@ fn picture_path_param_in(p: &Value, web: bool) -> Result, String> { } } +/// What a refusal calls the picture file at `path`: its name, never its folders or a login +/// ([`rustgis_map::layout::picture_file_name`]), or [`PICTURE_FILE_UNNAMED`] when it has none, or +/// one with a control or direction character, which would break or reorder the refusal. +pub(in crate::cmd) fn picture_named(path: &str) -> &str { + rustgis_map::layout::picture_file_name(path) + .filter(|name| name.chars().all(|c| rustgis_data::io::dbf_notice_char(c) == c)) + .unwrap_or(PICTURE_FILE_UNNAMED) +} + /// Whether a command gives a picture an `image` or a `path` (present and not null). pub(crate) fn gives_picture(p: &Value) -> bool { ["image", "path"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) @@ -118,11 +127,7 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result return Err(PICTURE_IMAGE.into()), (None, Some(path)) => { - // A name with a control or direction character would break or reorder the refusal. - let named = rustgis_map::layout::picture_file_name(path) - .filter(|name| name.chars().all(|c| rustgis_data::io::dbf_notice_char(c) == c)) - .unwrap_or(PICTURE_FILE_UNNAMED); - let image = crate::cmd::graphics::picture_file(path, named)?; + let image = crate::cmd::graphics::picture_file(path, picture_named(path))?; let kept = rustgis_map::layout::picture_source_kept(path); GivenPicture { image, source: kept.then(|| path.to_string()), unremembered: !kept, given_image: false } } diff --git a/crates/engine/src/cmd/layout/text.rs b/crates/engine/src/cmd/layout/text.rs index 6641d1d5c1..b978cc994a 100644 --- a/crates/engine/src/cmd/layout/text.rs +++ b/crates/engine/src/cmd/layout/text.rs @@ -2,37 +2,40 @@ use super::*; -/// For each layout, the map its `{map}` texts name: the one its first map frame shows, as the -/// project names it; None when that frame or its map is gone. -pub(crate) fn maps_layouts_name(project: &crate::project::Project) -> Vec> { +/// For each layout, the map its `{map}` texts name: the id of its first map frame and the map it +/// shows, as the project names it; None when that frame or its map is gone. +pub(crate) fn maps_layouts_name(project: &crate::project::Project) -> Vec> { let named = |l: &Layout| { let frame = l.first_frame().and_then(|id| l.element(id))?; let ElementKind::MapFrame { map, .. } = &frame.kind else { return None }; - crate::render::layout::map_index(&project.maps, map).and_then(|i| project.maps.get(i)).map(|m| m.name.clone()) + crate::render::layout::map_index(&project.maps, map).and_then(|i| project.maps.get(i)).map(|m| (frame.id, m.name.clone())) }; project.layouts.iter().map(named).collect() } /// Says which `{map}` texts a change (`before` it, [`maps_layouts_name`], layouts in the same /// order) left naming another map or none: `{map}` follows the layout's first map frame, which -/// is the lowest in the drawing order, so removing or reordering frames can change it. One -/// notice for each, with the count. -pub(crate) fn say_map_texts(s: &mut Session, before: &[Option]) { +/// is the lowest in the drawing order, so removing or reordering frames can change it, and +/// renaming its map renames it. One notice for each, with the count. +pub(crate) fn say_map_texts(s: &mut Session, before: &[Option<(u32, String)>]) { let after = maps_layouts_name(&s.project); - let (mut empty, mut moved) = (Vec::new(), Vec::new()); + let (mut empty, mut moved, mut renamed) = (Vec::new(), Vec::new(), Vec::new()); // The layouts whose first frame shows another map, or none: their texts' layer statistics // (#2853) are read from it. let mut figures = Vec::new(); for (i, (l, (was, now))) in s.project.layouts.iter().zip(before.iter().zip(&after)).enumerate() { - let Some(was) = was else { continue }; - if now.as_ref().is_none_or(|now| !now.eq_ignore_ascii_case(was)) { + let Some((was_frame, was)) = was else { continue }; + if now.as_ref().is_none_or(|(_, now)| !now.eq_ignore_ascii_case(was)) { figures.push(i); } let n = l.elements.iter().filter(|e| matches!(&e.kind, ElementKind::Text { text, .. } if text.contains("{map}"))).count(); match now { _ if n == 0 => {} None => empty.push((l.name.as_str(), n)), - Some(now) if !now.eq_ignore_ascii_case(was) => moved.push((l.name.as_str(), n, now.as_str())), + // The same frame showing another name: its map was renamed (a map's frame follows its + // renames, and no other map takes a name one has), not another frame made first. + Some((frame, now)) if !now.eq_ignore_ascii_case(was) && frame == was_frame => renamed.push((l.name.as_str(), n, now.as_str())), + Some((_, now)) if !now.eq_ignore_ascii_case(was) => moved.push((l.name.as_str(), n, now.as_str())), Some(_) => {} } } @@ -46,8 +49,22 @@ pub(crate) fn say_map_texts(s: &mut Session, before: &[Option]) { let mut said = Vec::new(); if let Some(whose) = notice { let have = if n == 1 { "has" } else { "have" }; - said.push(format!("{whose} {have} no map frame showing a map to name, so {{map}} draws empty")); + said.push(format!("{whose} {have} no first map frame showing a map in the project, so {{map}} draws empty")); } + let n: usize = renamed.iter().map(|(_, n, _)| n).sum(); + let notice = match renamed.as_slice() { + [] => None, + [(name, _, map)] => { + Some(format!("Layout '{name}': its map is now named '{map}', so {} {} it", texts(n), if n == 1 { "names" } else { "name" })) + } + more => Some(format!( + "{} layouts: their map was renamed, so {} {} it by its new name", + more.len(), + texts(n), + if n == 1 { "names" } else { "name" } + )), + }; + said.extend(notice); let n: usize = moved.iter().map(|(_, n, _)| n).sum(); let notice = match moved.as_slice() { [] => None, diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 8f12728d39..82992c7238 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -183,8 +183,8 @@ pub fn checked(url: &str) -> Result { const INTERNET_ONLY: &str = "plugins fetch only from the internet, not this computer or the local network"; impl Session { - /// The widest reach a service or catalogue the caller names (`url`, the address discovery - /// starts from) is read within. A plugin reaches only the internet, as its own `host.fetch` + /// How far discovery may reach from a service or catalogue the caller names (`url`, the + /// address discovery starts from). A plugin reaches only the internet, as its own `host.fetch` /// does: under its authority an address on this computer or the local network is refused, /// and one on the internet starts discovery within the internet, so the documents read from /// it, the text the plugin supplies for it and everything they name are held there too. Any diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index dad50b4897..e3d2d6a8b8 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -1992,8 +1992,8 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option Result { use crate::render::rustgis_tiles::cog; @@ -961,7 +962,7 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { } // The first file's header gives the coordinate system, the grid and its overviews. let first = by_day.values().flatten().next().map(|(h, ..)| h.clone()).ok_or("no file to read")?; - let info = values_header(&first)?; + let info = values_header(&first, &uncancelled())?; let layout = &info.layout; if layout.transform.pixel_height > 0.0 { return Err(crate::sources::message_with_address(&first, "stored bottom up, which a trend doesn't read yet")); @@ -1071,7 +1072,7 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { let mut probed = 0; while !covered && probed < COVER_PROBES { let Some(h) = others.next() else { break }; - covered = covers(&*values_header(h)?); + covered = covers(&*values_header(h, &uncancelled())?); probed += 1; } // Tiles beyond the probes are left to the reading, which leaves what none covers empty. @@ -1182,10 +1183,22 @@ fn mask_values( /// A file's header for reading its values (a cube's windows, its range's sample): a GeoTIFF in /// strips too, whose windows are read strip by strip (#2592). Cached per address, as -/// [`info_blocking`](crate::render::rustgis_tiles::cog::info_blocking) caches it. +/// [`info_blocking`](crate::render::rustgis_tiles::cog::info_blocking) caches it. A wait for the +/// header stops when `cancel` is set; a caller with no Cancel to hand passes a fresh flag and says +/// so in its doc comment. #[cfg(not(target_arch = "wasm32"))] -fn values_header(href: &str) -> Result, String> { - crate::render::rustgis_tiles::cog::window_info_until(href, &std::sync::atomic::AtomicBool::new(false)) +fn values_header( + href: &str, + cancel: &std::sync::atomic::AtomicBool, +) -> Result, String> { + crate::render::rustgis_tiles::cog::window_info_until(href, cancel) +} + +/// The flag given [`values_header`] by a caller with no Cancel to hand: the first read of a +/// file's header is one step Cancel doesn't interrupt there. +#[cfg(not(target_arch = "wasm32"))] +fn uncancelled() -> std::sync::atomic::AtomicBool { + std::sync::atomic::AtomicBool::new(false) } /// The level of a file whose pixels are nearest `size` across, by ratio. @@ -1199,7 +1212,8 @@ fn level_near(layout: &rustgis_data::raster::cog::Layout, size: f64) -> usize { impl StacCube { /// Where a band window's pixels (as [`mask_window`](Self::mask_window) takes them) fall in /// the mask file `href`: its header, the level read, and each column's and row's pixel of it - /// (`None` off the file). Only the header is read, cached per address. + /// (`None` off the file). Only the header is read, cached per address; its first read is a + /// step Cancel doesn't interrupt. fn mask_place( &self, href: &str, @@ -1208,7 +1222,7 @@ impl StacCube { rows: (u32, u32), ) -> Result { use super::cube_mask::nearest; - let info = values_header(href)?; + let info = values_header(href, &uncancelled())?; if info.layout.crs != self.crs { return Err(crate::sources::message_with_address(href, "a mask in another coordinate system than its band")); } @@ -1341,7 +1355,10 @@ impl super::cube::TimeCube for StacCube { let (sx, sy) = ((x1 - x0) / f64::from(gw), (y1 - y0).abs() / f64::from(gh)); let mut clear = vec![false; gw as usize * gh as usize]; for (href, stored) in files.iter().filter_map(|f| f.3.as_ref()) { - let info = values_header(href)?; + let info = match values_header(href, cancel) { + Err(_) if cancel.load(Relaxed) => return Err("cancelled".into()), + header => header?, + }; if info.layout.crs != self.crs { return Err(crate::sources::message_with_address(href, "a mask in another coordinate system than its band")); } @@ -1409,7 +1426,8 @@ impl super::cube::TimeCube for StacCube { #[cfg(not(target_arch = "wasm32"))] impl StacCube { /// [`TimeCube::slice_of`](super::cube::TimeCube::slice_of), or with `decided` - /// [`TimeCube::first_slice_of`](super::cube::TimeCube::first_slice_of). + /// [`TimeCube::first_slice_of`](super::cube::TimeCube::first_slice_of). The first read of a + /// file's header is a step Cancel doesn't interrupt. fn read_slice( &self, i: usize, @@ -1437,7 +1455,7 @@ impl StacCube { for (href, scale, fill, mask, more) in files { // Cached per address for the process (`with_info`, a failure too, for a while), so a // file's header is fetched once however many pieces and dates read it. - let info = values_header(href)?; + let info = values_header(href, &uncancelled())?; if info.layout.crs != self.crs { return Err(crate::sources::message_with_address(href, "in another coordinate system than the first file")); } @@ -1524,7 +1542,7 @@ impl StacCube { let read = if b == 0 { cog::read_values_blocking(&info, href, self.level, 0, cols, rows)? } else { - let bi = values_header(bh)?; + let bi = values_header(bh, &uncancelled())?; let same = bi.layout.crs == self.crs && bi.layout.levels.get(self.level).is_some_and(|l| { (l.width, l.height) == (lv.width, lv.height) && offset_in(&grid, &bi.layout.transform_of(l)) == Some((dx, dy)) @@ -1947,7 +1965,8 @@ const SAMPLE_SIDE: u32 = 512; /// panel sets one: the newest file of up to four of its tiles (spread over them), each read at its /// finest overview no larger than 512 pixels a side (the middle of its coarsest one otherwise), /// its values scaled as its metadata says, its codes for no value left out, and the 2nd to 98th -/// percentiles of them all ([`cubes::percentile_range`]). +/// percentiles of them all ([`cubes::percentile_range`]). The first read of a file's header is a +/// step Cancel doesn't interrupt. #[cfg(not(target_arch = "wasm32"))] fn sample_range( tiles: &std::collections::BTreeMap>, @@ -1963,7 +1982,7 @@ fn sample_range( let mut values = Vec::new(); for href in picked { let fetch_href = crate::service_logins::fetch_url(anonymous, href); - let info = values_header(&fetch_href)?; + let info = values_header(&fetch_href, &uncancelled())?; let l = &info.layout; if l.palette.is_some() { return Ok(Sample::Classes); diff --git a/crates/engine/src/cmd/table_stats.rs b/crates/engine/src/cmd/table_stats.rs index c1eccebbd8..3b85391acf 100644 --- a/crates/engine/src/cmd/table_stats.rs +++ b/crates/engine/src/cmd/table_stats.rs @@ -141,10 +141,9 @@ struct Numbers { count: usize, nulls: usize, skipped: usize, - /// How many of `count` are whole numbers, and how many of those are past 2^53. + /// How many of `count` are whole numbers. ints: usize, - big: usize, - /// Of those, the ones a decimal can't hold, so rounded however the others add up. + /// Of those, the ones past 2^53 a decimal can't hold, so rounded however the others add up. inexact: usize, sum: f64, wide_sum: WideSum, @@ -175,9 +174,9 @@ impl Numbers { } } - /// Whether the sum the answer gives is off by half a unit or more: rounded at the scale of the - /// whole numbers past 2^53, as decimals alone never round a sum this far (0.1 + 0.2 isn't). - /// The sum given is the running one, or the exact one where that overflowed. + /// Whether the sum the answer gives is off by half a unit or more, as a decimal holds no + /// fraction past 2^53. Decimals alone can be off this much too; 0.1 + 0.2 is off by far less, + /// so it isn't said. The sum given is the running one, or the exact one where that overflowed. fn sum_rounded(&self) -> bool { let given = if self.sum.is_finite() { self.sum } else { self.wide_sum.total() }; given.is_finite() && self.wide_sum.off_by(given).abs() >= 0.5 @@ -187,7 +186,6 @@ impl Numbers { self.add_float(i as f64); self.ints += 1; if i.unsigned_abs() > EXACT_IN_F64 { - self.big += 1; // One a decimal still holds exactly (2^54) is rounded only as the sum adds it up. self.inexact += usize::from((i as f64) as i128 != i128::from(i)); } @@ -288,7 +286,7 @@ fn resolve(s: &Session, p: &Value) -> Result { struct Done { answer: Value, /// What the count left out or rounded, each with its code: every one is a real loss. - notices: Vec, + notices: Vec, } /// Counts column `t.column` of `ds` over its rows, looking at Cancel as it goes (see @@ -382,7 +380,7 @@ fn gather(ds: &Dataset, t: &Target) -> Result { notices.push(Note::loss( LossCode::ChangedRounded, format!( - "{}: the sum and mean of '{}' are rounded by half a unit or more, as a decimal number holds no fraction past 2^53", + "{}: the sum of '{}' is rounded by half a unit or more, as a decimal number holds no fraction past 2^53", t.layer, f.name ), )); diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index fef80bc372..1e228fd7b9 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -17,7 +17,7 @@ const TILE_ROLES: &[crate::ParamRole] = &[crate::ParamRole { key: "legend", role pub fn commands() -> Vec { vec![ C::new("map.addTiles", "Add Tile Layer", "Home › Add", add).roles(TILE_ROLES).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials: the tile layer is marked so and never takes a login)}"#, + r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default; a PMTiles or MBTiles archive whose header isn't read yet, as a web one's usually isn't, is refused it here: add it without resampling and set it through map.setTiles once it shows), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials: the tile layer is marked so and never takes a login)}"#, ), C::new("map.removeTiles", "Remove Tile Layer", "Home › Add", remove).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: text, "index"?: number, "id"?: catalog id} (removes every tile layer when none is given)"#), @@ -910,7 +910,8 @@ fn sampling_code(r: rustgis_map::raster::Resampling) -> &'static str { const NOT_PICTURES: &str = "resampling is for a layer of picture tiles, not vector tiles or a style"; /// Refused for an archive whose header isn't read yet: it may hold vector tiles. -const NOT_KNOWN_YET: &str = "this archive is still being read: set its resampling once it shows on the map"; +const NOT_KNOWN_YET: &str = + "this archive is still being read: add it without resampling, then set its resampling with map.setTiles once it shows on the map"; /// Refused unless `t` is known to draw pictures: a vector layer, style or archive draws shapes, /// and an archive not read yet might (a setting it would ignore isn't kept). diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index bb6ac005a0..7da6985838 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -316,8 +316,8 @@ impl Drop for RunReads { } /// Runs `work` (command `name`'s) so the raster layers read in place it reads are read from their -/// file ([`Input::read`]), each file read once for the run, and adds to what is said once its -/// raster is added each that was read from an overview, or with values rounded. +/// file ([`Input::read`]), each file read once for the run, and, once its raster is added, says +/// which of them were read from an overview or with values rounded. pub(crate) fn reading_files(name: &str, work: impl FnOnce() -> Result) -> Result { #[cfg(target_arch = "wasm32")] { @@ -586,8 +586,9 @@ pub(crate) fn made_or_ran(s: &mut Session, p: &Value, command: &str) -> CmdResul #[cfg(not(target_arch = "wasm32"))] /// A command that makes a raster ([`IN_BACKGROUND`]), started to make it on another thread -/// ([`RasterRun::run`]) while the session goes on: its inputs are read now (cheaply: the pixels -/// are shared), and [`raster_land`] hands the raster to the command, which adds it with undo and +/// ([`RasterRun::run`]) while the session goes on: its inputs are taken now (cheaply: the pixels +/// are shared), and a layer read in place from a file is read on the run's thread as the work +/// runs ([`reading_files`]); [`raster_land`] hands the raster to the command, which adds it with undo and /// history when run again with `ran` (#1291 step 3). pub struct RasterRun { pub id: u64, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index afb4312b6f..e47f7dc8e1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -431,7 +431,7 @@ pub(crate) fn in_place_overview(d: &rustgis_data::raster::Raster, tools_read_fil let (w, h) = (d.width, d.height); Some(if tools_read_file { format!( - "read in place: the map draws its {fw} × {fh} pixels as it needs them, and geoprocessing tools and the commands that make a raster read the file (at the finest level they can hold, GeoLibre tools whole), while statistics, histograms, plugin tools, Build Mosaic, Train Deep Learning Model and other raster commands read a {w} × {h} overview" + "read in place: the map draws its {fw} × {fh} pixels as it needs them, and geoprocessing tools and the commands that make a raster read the file (at the finest level they can hold, GeoLibre tools whole), while statistics, histograms, plugin tools, Build Mosaic, Train Deep Learning Model, Polygons to Raster's template grid and other raster commands read a {w} × {h} overview" ) } else { format!( diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 15c5480620..74c1e5f9d3 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -326,9 +326,33 @@ fn command_adds_kept_class_order(id: &str, params: &Value) -> bool { } } -/// Whether saved JSON text holds a Unique Values renderer that keeps its class order. +/// Whether JSON text could hide a key from the text pre-filters below: only a `\uXXXX` escape +/// can spell one of their keys' characters (letters, `_`, `{`, `:`) another way, as no short +/// escape (`\"`, `\\`, `\/`, `\n`, …) gives one, and a key's own quotes are never escaped. Inside +/// a string's JSON (a saved step's inline project) that escape's backslash is itself escaped, so +/// any run of backslashes before the `u` counts, as long as four hex digits follow. A Windows path +/// (`C:\\Users\\me`) or an escaped quote, which nearly every saved project holds, doesn't send it +/// to a full parse. +fn may_hide_a_key(text: &str) -> bool { + text.match_indices("\\u").any(|(i, _)| text.get(i + 2..i + 6).is_some_and(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))) +} + +/// Whether saved JSON text holds a Unique Values renderer that keeps its class order. Parsed when +/// the key shows, may be hidden ([`may_hide_a_key`]), or a saved step's base64 `data` may hold it +/// ([`names_data`]). fn text_keeps_class_order(text: &str) -> bool { - (text.contains("keep_order") || text.contains('\\')) && serde_json::from_str::(text).is_ok_and(|v| holds_kept_class_order(&v)) + (text.contains("keep_order") || may_hide_a_key(text) || names_data(text)) + && serde_json::from_str::(text).is_ok_and(|v| holds_kept_class_order(&v)) +} + +/// Whether JSON text holds a `data` key, written plain (`"data"`) or inside a string's JSON at any +/// depth (`\"data\"`, `\\\"data\\\"`, …): `data` and then a quote after any run of backslashes. +fn names_data(text: &str) -> bool { + // A key is quoted on both sides, so `metadata"` or `rawdata"` don't count. + text.match_indices("data").any(|(i, _)| { + text.get(..i).is_some_and(|before| before.ends_with('"')) + && text.get(i + 4..).is_some_and(|rest| rest.trim_start_matches('\\').starts_with('"')) + }) } /// A saved `labels.placement` that has a class remove duplicates, read as the command reads it @@ -413,7 +437,7 @@ fn command_uses_text_statistics(id: &str, params: &Value) -> bool { "presentation.import" => crate::cmd::items::inline_text(params) .ok() .flatten() - .filter(|t| STATISTIC_KEYS.iter().any(|key| t.contains(key)) || t.contains('\\')) + .filter(|t| STATISTIC_KEYS.iter().any(|key| t.contains(key)) || may_hide_a_key(t)) .and_then(|t| serde_json::from_str::(&t).ok()) .is_some_and(|p| presentation_uses_text_statistics(&p)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_text_statistics)), @@ -1095,7 +1119,7 @@ fn imported_layout(params: &Value, keys: &[&str]) -> Option(&t).ok()) } @@ -1533,7 +1557,12 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static /// Whether saving `project` serializes any [`rustgis_data::raster::Crs`] requiring `crs-wkt`, /// inspected directly across all `Crs`-bearing fields without double-serializing the project. -/// Every container struct is destructured exhaustively so adding a `Crs`-bearing field is a compile error. +/// The project's own fields, and those of each `Layer` and `SourceLayer`, are destructured +/// exhaustively, so a field added there is a compile error until it is looked at. The containers +/// those match with `_` (layouts, reports, models, a layer's raster or database link, …) are +/// assumed to hold no `Crs`-typed field: their coordinate systems are strings or +/// `#[serde(skip)]`. `crs_wkt_direct_walk_matches_saves_wkt_across_all_fields` checks the walk +/// against [`rustgis_data::raster::crs::saves_wkt`]. fn project_needs_wkt(project: &Project) -> bool { let Project { first_layer: _, @@ -2194,6 +2223,52 @@ mod tests { assert!(needs(json!({"text": sorted})).is_empty()); } + /// A key hidden behind a `\u` escape is still found: the text pre-filter parses text that + /// holds one. A Windows path's escaped backslashes and an escaped quote don't send it to a + /// parse (#3385 review). + #[test] + fn a_key_hidden_by_an_escape_still_requires_its_capability() { + let needs = |text: &str| model_capabilities(&[ModelStep { tool: "style.add".into(), params: json!({"text": text}) }], None); + let style = kept_order_style(); + let hidden = style.replace("\"keep_order\"", "\"\\u006beep_order\""); + assert_ne!(hidden, style); + assert_eq!(needs(&hidden), ["unique-keep-order"]); + assert!(may_hide_a_key(r#"{"a":"\u006b"}"#)); + assert!(may_hide_a_key(r#"{"a":"\\\u006b"}"#), "an escaped backslash, then an escape"); + assert!(may_hide_a_key(r#"{"t":"{\\u006beep_order:true}"}"#), "an escape inside a string's JSON"); + assert!(!may_hide_a_key(r#"{"path":"C:\\Users\\me\\unique.rgis","say":"\"quoted\""}"#)); + assert!(!may_hide_a_key("{}")); + } + + /// A project text whose saved step adds a kept-order style from base64 `data`, with no + /// `keep_order` written out and only a Windows path's backslashes, still requires it (#3433 + /// review): the pre-filter lets a `data` key through to the parse. + #[test] + fn a_step_adding_a_kept_order_style_by_data_requires_it_without_the_key_written() { + use base64::Engine; + let data = base64::engine::general_purpose::STANDARD.encode(kept_order_style()); + let step = json!({"title": "C:\\styles", "command": "style.add", "params": {"data": data}}); + let text = json!({"tasks": [{"name": "Add", "steps": [step]}]}).to_string(); + assert!(!text.contains("keep_order") && !may_hide_a_key(&text), "{text}"); + let needs = |text: &str| model_capabilities(&[ModelStep { tool: "project.openText".into(), params: json!({"text": text}) }], None); + assert_eq!(needs(&text), ["unique-keep-order"]); + // Nested as a string inside another project's step, its `data` key is escaped. + let outer = + json!({"tasks": [{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]}) + .to_string(); + assert!(!outer.contains("keep_order"), "{outer}"); + assert_eq!(needs(&outer), ["unique-keep-order"]); + // Two levels deeper still, its `data` key is escaped seven backslashes deep. + let open = |text: &str| { + json!({"tasks": [{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]}) + .to_string() + }; + let deepest = open(&open(&outer)); + assert!(!deepest.contains("keep_order") && !deepest.contains("data\\\\\\\"") && names_data(&deepest), "{deepest}"); + assert_eq!(needs(&deepest), ["unique-keep-order"]); + assert!(names_data(r#"{"data":1}"#) && !names_data(r#"{"database":1,"metadata":2,"rawdata":3}"#)); + } + /// So does a saved `style.import`, `layer.addLayerFile`, `map.import` or `project.openText` /// whose inline layer, map or project keeps one, a file without its header included: an older /// reader would take the renderer with the classes sorted (#3367 and #3385 reviews). diff --git a/crates/engine/src/roles.rs b/crates/engine/src/roles.rs index f50dabe36e..1ace0f106c 100644 --- a/crates/engine/src/roles.rs +++ b/crates/engine/src/roles.rs @@ -418,7 +418,7 @@ fn document(kind: Document, v: &Value, depth: usize, report: &mut Report) -> Opt let Some(text) = v.as_str().filter(|s| s.len() as u64 <= crate::project::max_bytes()) else { return invalid(v, report) }; // One this RustGIS wouldn't read, or would rewrite without what it doesn't know, stays as // written. Only project and map readers read format 2 and refuse a document for what it - // requires; for the others it is a format past `FORMAT` (also 2 now). A task's and a model's + // requires; for the others it is a format past `FORMAT`. A task's and a model's // readers do look at `requires`, so their cleaned copies keep it (`task_document` puts it and // `format` back; `model_document` keeps its envelope). if crate::project::kept_as_written(text, matches!(kind, Document::Project | Document::Map)) { @@ -457,8 +457,8 @@ fn text_document(text: &str, depth: u }) } -/// A task document is cleaned through the typed task, as it always was (a key the task doesn't -/// have is not kept), and then `format` and `requires` are put back from the document: `task.import` +/// A task document is cleaned through the typed task, as it always was, and then `format`, +/// `requires` and the keys the task doesn't have are put back from the document: `task.import` /// reads them (it refuses a newer format and what `requires` lists that this RustGIS doesn't know), /// and the typed copy has neither. Neither is a place for a credential, so a document whose header /// holds one is withheld whole (`[parameters withheld]`, which no replay reads as a task), as a @@ -471,18 +471,76 @@ fn task_document(text: &str, depth: usize) -> Result<(String, Report), String> { return Ok((WITHHELD.into(), report)); } let (clean, report) = text_document::(text, depth)?; + // Keys this RustGIS doesn't know (a newer one may have added them) are kept, written again or + // not, unless one of them holds a credential: then the document is withheld whole, as one + // whose header holds one is, since the typed task never looks there (a stray `token` beside + // the steps). + let typed = + serde_json::to_value(serde_json::from_str::(text).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + let mut stray = Vec::new(); + strays(&original, &typed, &header, &mut stray); + if stray.iter().any(holds_credential) { + return Ok((WITHHELD.into(), Report { withheld: report.withheld.saturating_add(1), ..report })); + } if clean == text { return Ok((clean, report)); } let mut rewritten: Value = serde_json::from_str(&clean).map_err(|e| e.to_string())?; - if let (Some(from), Some(to)) = (original.as_object(), rewritten.as_object_mut()) { - for key in header { - if let Some(value) = from.get(key) { - to.insert(key.into(), value.clone()); + put_back_strays(&original, &typed, &mut rewritten); + Ok((rewritten.to_string(), report)) +} + +/// Whether `v` or anything in it holds a credential: a secret-named key, an address or a PEM key +/// ([`crate::sources::holds_secret`]), or a credential's name (`token=…`) anywhere in any of its +/// strings, however long (unlike [`suspicious`], which reads a string's first 65,536 words). +fn holds_credential(v: &Value) -> bool { + crate::sources::holds_secret(v) + || match v { + Value::String(s) => s + .split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '%'))) + .any(|word| !word.is_empty() && rustgis_data::address::secret_key(word)), + Value::Object(o) => o.values().any(holds_credential), + Value::Array(a) => a.iter().any(holds_credential), + _ => false, + } +} + +/// Puts the keys of task document `original` that its typed copy `typed` doesn't have, beside the +/// steps and in each step, back into `rewritten` (the typed copy cleaned). Those are the only +/// places they can be: a step's `params` is kept whole by the typed task, and cleaned there. +fn put_back_strays(original: &Value, typed: &Value, rewritten: &mut Value) { + fn missing(from: &Value, typed: &Value, to: &mut Value) { + let (Some(from), Some(typed), Some(to)) = (from.as_object(), typed.as_object(), to.as_object_mut()) else { return }; + for (k, v) in from.iter().filter(|(k, _)| !typed.contains_key(*k)) { + to.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + missing(original, typed, rewritten); + let steps = |v: &Value| v.get("steps").and_then(Value::as_array).cloned().unwrap_or_default(); + let (from, kinds) = (steps(original), steps(typed)); + if let Some(to) = rewritten.get_mut("steps").and_then(Value::as_array_mut) { + for ((from, typed), to) in from.iter().zip(&kinds).zip(to.iter_mut()) { + missing(from, typed, to); + } + } +} + +/// Each key of `original` that `typed` (its typed copy, serialized) doesn't have, at every depth +/// but for the top-level keys in `besides`, as an object of that key and its value (so a +/// credential's key name counts), added to `out`. +fn strays(original: &Value, typed: &Value, besides: &[&str], out: &mut Vec) { + match (original, typed) { + (Value::Object(o), Value::Object(t)) => { + for (k, v) in o.iter().filter(|(k, _)| !besides.contains(&k.as_str())) { + match t.get(k) { + Some(tv) => strays(v, tv, &[], out), + None => out.push(Value::Object(serde_json::Map::from_iter([(k.clone(), v.clone())]))), + } } } + (Value::Array(o), Value::Array(t)) => o.iter().zip(t).for_each(|(v, tv)| strays(v, tv, &[], out)), + _ => {} } - Ok((rewritten.to_string(), report)) } /// Model import has two envelopes; keeps the envelope's other fields and cleans only its model. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 893a2ffc98..984ec812f1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13139,17 +13139,17 @@ fn layer_group_classes_says_when_it_cuts_the_label() { // 150 + ", " + 150. let said = group(&mut s, None); assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].contains("102 were left out"), "{said:?}"); + assert!(said[0].contains("102 characters were left out"), "{said:?}"); let said = group(&mut s, Some("y".repeat(250))); assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].contains("50 were left out"), "{said:?}"); + assert!(said[0].contains("50 characters were left out"), "{said:?}"); assert!(group(&mut s, Some(" short ".into())).is_empty()); // Control characters at the ends are spaces, trimmed before anything is cut. assert!(group(&mut s, Some(format!("{}A", "\0".repeat(201)))).is_empty()); // A space left at the cut goes too: the label is shorter than the most, and the count says so. let said = group(&mut s, Some(format!("{} z", "y".repeat(199)))); assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].contains("at most 200") && said[0].contains("2 were left out"), "{said:?}"); + assert!(said[0].contains("at most 200") && said[0].contains("2 characters were left out"), "{said:?}"); } /// A group made while No Fill hides the fills comes back from Restore Fill with one opacity. @@ -23530,6 +23530,17 @@ fn a_plugin_cannot_discover_a_service_off_the_internet() { assert!(e.contains(url) && e.contains("plugins fetch only from the internet, not this computer or the local network"), "{op}: {e}"); } assert!(s.map().layers.iter().all(|l| l.name != "Parcels" && l.name != "roads"), "nothing was added"); + // A group the user imported from this computer: a plugin's refresh reads its service again, + // and is refused there too, the group left as it was. + let server = ogc_server::Server::group_fixture(); + let root = server.root(); + let group = s.run("service.import", &json!({"url": root})).unwrap()["group"].clone(); + let layers = |s: &Session| s.map().layers.iter().map(|l| (l.id, l.name.clone())).collect::>(); + let before = layers(&s); + let e = forward(&mut s, id, "service.refresh", json!({"group": group})).unwrap_err(); + let host = root.split("://").nth(1).and_then(|r| r.split('/').next()).unwrap_or_default().to_string(); + assert!(e.contains(&host) && e.contains("plugins fetch only from the internet, not this computer or the local network"), "{e}"); + assert_eq!(layers(&s), before, "the group's layers are unchanged"); rustgis_plugins::unload(id); } @@ -58007,6 +58018,8 @@ fn stl_point_cubes_stay_in_the_positive_octant() { #[test] fn stl_leaves_out_lines_and_skips_flat_triangles_and_says_so() { + // A side of 2^-24 degrees. + const E: f64 = 1.0 / 16_777_216.0; let mut s = mesh_session(json!([ mesh_feature(square(0.0, false), 0.0), mesh_feature(json!({"type": "LineString", "coordinates": [[0.0, 0.02], [0.01, 0.02]]}), 5.0), @@ -58021,9 +58034,16 @@ fn stl_leaves_out_lines_and_skips_flat_triangles_and_says_so() { json!({"type": "Polygon", "coordinates": [[[0.06, 0.0], [0.07, 0.0], [0.070_000_000_01, 0.0], [0.07, 0.01], [0.06, 0.01], [0.06, 0.0]]]}), 30.0 ), + // Flat, with a tiny area far from the origin: counted among those left out. This pins the + // area taken from the ring's first vertex; taken from the origin, the rounding of terms + // near 128 × 64 would swamp an area of 2^-48 and leave it uncounted. + mesh_feature( + json!({"type": "Polygon", "coordinates": [[[128.0, 64.0], [128.0 + E, 64.0], [128.0 + E, 64.0 + E], [128.0, 64.0 + E], [128.0, 64.0]]]}), + 0.0 + ), ])); let (_, bytes) = crate::cmd::items::item_bytes(&mut s, "stl", &json!({"heightField": "h"})).unwrap(); - // The flat square and the flat point are left out, not written as two coincident caps; the + // The flat squares and the flat point are left out, not written as two coincident caps; the // point of 20 m makes a cube of 12, and the square's 1 µm edge, one point in 32-bit floats, // gives zero-area triangles (4 of its 16) that are skipped. let tris = stl_triangles(&bytes); @@ -58031,7 +58051,7 @@ fn stl_leaves_out_lines_and_skips_flat_triangles_and_says_so() { let said = |part: &str| s.notices.iter().any(|n| n.text.contains(part)); let lost = |part: &str| s.notices.iter().any(|n| n.text.contains(part) && n.loss() == Some(rustgis_data::loss::LossCode::DroppedFeature)); - assert!(lost("Left out 2 polygon(s) and point(s) of zero height")); + assert!(lost("Left out 3 polygon(s) and point(s) of zero height")); assert!(lost("left out 1 polyline")); assert!(said("zero-area")); assert!(said("no units")); diff --git a/crates/engine/src/tests/graphics_frames.rs b/crates/engine/src/tests/graphics_frames.rs index 3da4f08d24..cf9c973ab2 100644 --- a/crates/engine/src/tests/graphics_frames.rs +++ b/crates/engine/src/tests/graphics_frames.rs @@ -203,7 +203,7 @@ fn a_drag_previews_and_adds_within_85_degrees_on_a_web_mercator_map_and_says_so( assert_eq!(outline, ring_of(&s, &r)); assert!(outline.iter().all(|c| c.y <= 85.0) && outline.iter().any(|c| c.y == 85.0), "{outline:?}"); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(said.iter().any(|t| t.contains("placed at 85°")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("placed at ±85°: built on the map's view, which stops there")), "{said:?}"); let mark = s.notice_mark(); let below = [Coord::new(0.0, 80.0), Coord::new(1.0, 84.5)]; let outline = crate::cmd::graphics::dragged_outline(&s, "rectangle", &below).unwrap(); @@ -212,3 +212,27 @@ fn a_drag_previews_and_adds_within_85_degrees_on_a_web_mercator_map_and_says_so( assert!(outline.iter().any(|c| (c.y - 84.5).abs() < 1e-9), "{outline:?}"); assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("85°"))); } + +#[test] +fn a_mercator_circle_whose_ring_reaches_past_85_degrees_is_kept_within_and_says_how_many() { + // Centre (0, 84), edge (30, 84): a radius in Web Mercator that takes the ring's top to about + // 86°. Its points past 85° are placed at 85°, and one notice gives their count. + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let r = s.run("graphics.add", &json!({"shape": "circle", "points": [[0.0, 84.0], [30.0, 84.0]]})).unwrap(); + let ring = ring_of(&s, &r); + assert!(ring.iter().all(|c| c.y <= 85.0), "{ring:?}"); + let past = ring.iter().take(72).filter(|c| c.y == 85.0).count(); + assert!(past > 0, "{ring:?}"); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("85°")).collect(); + assert_eq!( + said, + [format!( + "{past} point(s) of the graphic beyond ±85° latitude were placed at ±85°: built in Web Mercator, which can't show a pole (\"frame\": \"view\" keeps them where given on a map that shows one)" + )] + ); + // Well below 85°: nothing moved, nothing said. + let mark = s.notice_mark(); + s.run("graphics.add", &json!({"shape": "circle", "points": [[0.0, 40.0], [10.0, 40.0]]})).unwrap(); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("85°"))); +} diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 95dc3e9274..c298038db3 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -559,10 +559,15 @@ fn a_refused_picture_file_is_named_by_its_name_never_the_path_given() { assert!(state(&s) == before, "{command} {path} changed the layout"); } } - // Map graphics name the path given, as they always have. + // Map graphics name the file by its name too, never the folders or a login in the path given. let missing = at("missing.png"); let e = s.run("graphics.add", &json!({"shape": "picture", "points": [[0, 0], [1, 1]], "path": missing})).unwrap_err(); - assert_eq!(e, format!("{missing}: {}", system(&missing))); + assert_eq!(e, format!("missing.png: {}", system(&missing))); + for path in ["user:secret@example.invalid/x.png", "https://user:secret@example.invalid/x.png", "user:secret@example.invalid:/x.png"] { + let e = s.run("graphics.add", &json!({"shape": "picture", "points": [[0, 0], [1, 1]], "path": path})).unwrap_err(); + assert!(!e.contains("secret") && !e.contains("example.invalid"), "{path}: {e}"); + assert_eq!(e, "a picture is read from a file on this computer, not an address", "{path}"); + } } /// A path the rule doesn't keep: the picture is read, its file not remembered, and that is said. diff --git a/crates/engine/src/tests/layout_title.rs b/crates/engine/src/tests/layout_title.rs index c534d4f660..08e7943246 100644 --- a/crates/engine/src/tests/layout_title.rs +++ b/crates/engine/src/tests/layout_title.rs @@ -247,7 +247,7 @@ fn removing_the_last_map_frame_says_how_many_map_texts_draw_empty() { assert_eq!(map_notices(&mut s, "layout.removeElement", json!({"element": frames[0]})), Vec::::new()); assert_eq!( map_notices(&mut s, "layout.removeElement", json!({"element": frames[1]})), - ["Layout 'Sheet': 2 texts with {map} have no map frame showing a map to name, so {map} draws empty"] + ["Layout 'Sheet': 2 texts with {map} have no first map frame showing a map in the project, so {map} draws empty"] ); // Said when it happens, not again. let title = id(&s, 0, "Title"); @@ -275,7 +275,7 @@ fn removing_the_map_a_layout_names_says_its_map_texts_draw_empty() { assert_eq!(map_notices(&mut s, "map.remove", json!({"name": "Spare"})), Vec::::new()); assert_eq!( map_notices(&mut s, "map.remove", json!({"name": "Detail"})), - ["Layout 'Sheet': 1 text with {map} has no map frame showing a map to name, so {map} draws empty"] + ["Layout 'Sheet': 1 text with {map} has no first map frame showing a map in the project, so {map} draws empty"] ); assert_eq!(drawn_lines(&s, 0, "Title"), [""]); assert_eq!(s.map().name, first); @@ -290,7 +290,7 @@ fn removing_a_map_two_layouts_name_says_so_once() { s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); assert_eq!( map_notices(&mut s, "map.remove", json!({"name": "Detail"})), - ["2 layouts: 2 texts with {map} have no map frame showing a map to name, so {map} draws empty"] + ["2 layouts: 2 texts with {map} have no first map frame showing a map in the project, so {map} draws empty"] ); } @@ -306,7 +306,7 @@ fn removing_an_offline_area_and_its_map_says_the_map_texts_draw_empty() { s.project.offline_areas.push(serde_json::from_value(area).unwrap()); assert_eq!( map_notices(&mut s, "offline.remove", json!({"name": "Crew"})), - ["Layout 'Sheet': 1 text with {map} has no map frame showing a map to name, so {map} draws empty"] + ["Layout 'Sheet': 1 text with {map} has no first map frame showing a map in the project, so {map} draws empty"] ); } @@ -338,3 +338,35 @@ fn reordering_or_removing_frames_says_when_map_texts_name_another_map() { ["Layout 'Sheet': its first map frame, the lowest in the drawing order, now shows 'Detail', so 1 text with {map} names it"] ); } + +/// With the first frame's map gone, a second frame still showing a map doesn't name it: the +/// notice says the *first* frame shows none, not that the layout needs another frame. +#[test] +fn removing_the_first_frames_map_names_the_first_frame_though_another_shows_a_map() { + let mut s = world(); + let first = s.map().name.clone(); + s.run("map.new", &json!({"name": "Detail"})).unwrap(); + s.run("map.activate", &json!({"name": &first})).unwrap(); + s.run("layout.new", &json!({"page": "a4", "template": "map", "name": "Sheet"})).unwrap(); + s.run("layout.addFrame", &json!({"map": "Detail", "x": 10, "y": 10, "w": 40, "h": 30})).unwrap(); + assert_eq!( + map_notices(&mut s, "map.remove", json!({"name": &first})), + ["Layout 'Sheet': 1 text with {map} has no first map frame showing a map in the project, so {map} draws empty"] + ); +} + +/// Removing an offline area whose map is the only one keeps it as "… (kept)", and the frame +/// follows: the texts name it by its new name, said as a rename, not as another frame made first. +#[test] +fn removing_an_offline_area_that_keeps_its_map_says_the_map_was_renamed() { + let mut s = world(); + let first = s.map().name.clone(); + s.run("map.rename", &json!({"name": "Crew (offline)"})).unwrap(); + s.run("layout.new", &json!({"page": "a4", "template": "map", "name": "Sheet"})).unwrap(); + let extent = rustgis_geom::Extent::new(0.0, 0.0, 1.0, 1.0); + let area = json!({"name": "Crew", "map": first, "extent": extent, "created": 0.0, "data": s.project.maps[0]}); + s.project.offline_areas.push(serde_json::from_value(area).unwrap()); + let said = map_notices(&mut s, "offline.remove", json!({"name": "Crew"})); + assert_eq!(said, ["Layout 'Sheet': its map is now named 'Crew (kept)', so 1 text with {map} names it"]); + assert_eq!(drawn_lines(&s, 0, "Title"), ["Crew (kept)"]); +} diff --git a/crates/engine/src/tests/table_statistics.rs b/crates/engine/src/tests/table_statistics.rs index 45230cbcf0..b41f28582a 100644 --- a/crates/engine/src/tests/table_statistics.rs +++ b/crates/engine/src/tests/table_statistics.rs @@ -148,13 +148,14 @@ fn whole_numbers_added_with_decimals_past_2_53_say_how_many_are_rounded() { let mut s = layer_of("w", fields.clone(), vec![vec![V::Int(5)], vec![V::Float(0.5)], vec![V::Int(1 << 54)]]); let mark = s.notice_mark(); assert_eq!(stats(&mut s, json!({"layer": "w", "field": "x"}))["sum"], ((1_i64 << 54) + 4) as f64); - let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.contains("are rounded"), n.loss())).collect(); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.contains("the sum of 'x' is rounded"), n.loss())).collect(); assert_eq!(said, [(true, Some(rustgis_data::loss::LossCode::ChangedRounded))]); let mut s = layer_of("w", fields.clone(), vec![vec![V::Float(0.0)], vec![V::Int(1 << 54)]]); let mark = s.notice_mark(); stats(&mut s, json!({"layer": "w", "field": "x"})); assert!(s.notices_since(mark).is_empty(), "an exact sum says nothing"); - // Decimals alone round a sum only as decimals do, which isn't said: the big ones cancel. + // Big whole numbers that cancel leave a sum of decimals rounded only as decimals round, which + // isn't said. let cancel = vec![vec![V::Int(1 << 54)], vec![V::Int(-(1 << 54))], vec![V::Float(0.1)], vec![V::Float(0.2)]]; let mut s = layer_of("w", fields.clone(), cancel); let mark = s.notice_mark(); diff --git a/crates/engine/src/tests/task_files.rs b/crates/engine/src/tests/task_files.rs index 7a081dcdca..a97dd89642 100644 --- a/crates/engine/src/tests/task_files.rs +++ b/crates/engine/src/tests/task_files.rs @@ -152,31 +152,80 @@ fn a_recorded_task_import_keeps_the_check_when_its_text_is_cleaned() { assert!(clean.is_none() && report.unchecked == 0); } -/// A recorded `task.import` is cleaned through the typed task as it always was: a key the task -/// doesn't have, with a credential in it, isn't kept beside the cleaned steps. Only `format` and -/// `requires` are put back from the document. +/// A recorded `task.import` whose step holds a credential is written again from the typed task, +/// with the credential cleaned out; `format`, `requires` and the keys this RustGIS doesn't know +/// (beside the steps and in a step) are put back. A stray key holding a credential withholds the +/// whole text instead. #[test] -fn a_recorded_task_import_keeps_only_its_envelope_beside_the_typed_clean() { +fn a_recorded_task_import_keeps_its_envelope_and_newer_keys_beside_the_typed_clean() { const SECRET: &str = "RGSYNTH_stray_key_20261124"; let mut task = bare(); task["requires"] = json!(["label-weight"]); task["format"] = json!(crate::project::READ_FORMAT); - task["token"] = json!(SECRET); - task["extra"] = json!({"password": SECRET}); + task["color"] = json!("#336699"); // A credential in a step makes the document change, so it is written again from the typed task. - task["steps"] = - json!([{"title": "Add", "command": "layer.addUrl", "params": {"url": format!("https://h.invalid/a.geojson?token={SECRET}")}}]); + task["steps"] = json!([{"title": "Add", "command": "layer.addUrl", "icon": "globe", "params": {"url": format!("https://h.invalid/a.geojson?token={SECRET}")}}]); let (clean, report) = crate::roles::command("task.import", &json!({"text": task.to_string()}), 0); let cleaned = clean.expect("the credential is cleaned out of the text"); let cleaned = cleaned["text"].as_str().unwrap(); assert!(!cleaned.contains(SECRET), "{cleaned}"); - assert_eq!(report.unchecked, 0); + assert_eq!((report.unchecked, report.withheld), (0, 0)); let kept: Value = serde_json::from_str(cleaned).unwrap(); let mut keys: Vec<&String> = kept.as_object().unwrap().keys().collect(); keys.sort(); - assert_eq!(keys, ["description", "format", "name", "requires", "steps"], "{cleaned}"); + assert_eq!(keys, ["color", "description", "format", "name", "requires", "steps"], "{cleaned}"); assert_eq!(kept["requires"], json!(["label-weight"])); assert_eq!(kept["format"], json!(crate::project::READ_FORMAT)); + assert_eq!(kept["steps"][0]["icon"], json!("globe"), "{cleaned}"); + // A stray key holding a credential, beside a step credential: withheld whole. + task["token"] = json!(SECRET); + let (clean, report) = crate::roles::command("task.import", &json!({"text": task.to_string()}), 0); + let cleaned = clean.expect("withheld"); + assert!(!cleaned["text"].as_str().unwrap().contains(SECRET), "{cleaned}"); + assert_eq!(report.withheld, 1); +} + +/// A key the task doesn't have, in a document no step credential rewrites, is kept as written (a +/// newer RustGIS may have added it), unless it holds a credential: a `token` beside the steps, or +/// inside one, withholds the whole text, which replays as no task. A document of only the task's +/// keys and its header is kept byte for byte. +#[test] +fn a_recorded_task_import_withholds_a_stray_key_holding_a_credential() { + const SECRET: &str = "RGSYNTH_stray_unchanged_20261129"; + let mut top = bare(); + top["requires"] = json!(["label-weight"]); + top["token"] = json!(SECRET); + let mut in_step = bare(); + in_step["steps"][0]["token"] = json!(SECRET); + // An assignment in a stray key's text, nested, under a name that isn't a secret's. + let mut assigned = bare(); + assigned["notes"] = json!({"lines": [format!("token={SECRET}")]}); + // One past the first 65,536 words of a long text. + let mut late = bare(); + late["notes"] = json!(format!("{} token={SECRET}", "word ".repeat(70_000))); + for task in [top, in_step, assigned, late] { + let (clean, report) = crate::roles::command("task.import", &json!({"text": task.to_string()}), 0); + let params = clean.unwrap_or_else(|| panic!("{task}: kept as written, stray key and all")); + let cleaned = params["text"].as_str().unwrap(); + assert!(!cleaned.contains(SECRET), "{cleaned}"); + assert_eq!(report.withheld, 1, "{task}"); + let mut s = Session::new(Project::default()); + assert!(import(&mut s, cleaned).is_err(), "{cleaned}"); + } + // A key a newer RustGIS added, holding no credential: kept as written. + let mut newer = bare(); + newer["steps"][0]["icon"] = json!("zoom"); + newer["color"] = json!("#336699"); + let (clean, report) = crate::roles::command("task.import", &json!({"text": newer.to_string()}), 0); + assert!(clean.is_none() && report.withheld == 0, "{clean:?}"); + // Known keys only, with a header and without a description: no change. + let mut known = bare(); + known["requires"] = json!(["label-weight"]); + known["format"] = json!(crate::project::READ_FORMAT); + known.as_object_mut().unwrap().remove("description"); + known["steps"][0].as_object_mut().unwrap().remove("params"); + let (clean, report) = crate::roles::command("task.import", &json!({"text": known.to_string()}), 0); + assert!(clean.is_none() && report.withheld == 0, "{clean:?}"); } /// What a recorded `task.import` keeps of `requires` and `format` is only what carries no credential: diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 13f0a9ebe0..e626385840 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -88,7 +88,7 @@ fn red_difference(a: &tiny_skia::Pixmap, b: &tiny_skia::Pixmap) -> f64 { } /// Added past the size held whole, the file is read in place: the layer holds the 512 overview, -/// says so (and that geoprocessing tools read the file), and draws zoomed in as the file held whole +/// says so (and that geoprocessing tools and the commands that make a raster read the file), and draws zoomed in as the file held whole /// does, its single-pixel checks and all; drawn from the overview it holds, the checks are gone. #[test] fn a_large_local_tiled_geotiff_draws_its_full_image_zoomed_in() { @@ -114,6 +114,7 @@ fn a_large_local_tiled_geotiff_draws_its_full_image_zoomed_in() { assert!( notes.iter().any(|n| n.starts_with("checks: read in place: the map draws its 1024 × 1024 pixels") && n.contains("geoprocessing tools and the commands that make a raster read the file") + && n.contains("Polygons to Raster's template grid") && n.contains("read a 512 × 512 overview")), "{notes:?}" ); @@ -588,7 +589,8 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { let rl = raster(&s, "index"); assert!(rl.tiled, "the result is read in place from its file"); assert_eq!(rl.path.as_deref(), Some(file.display().to_string().as_str())); - // It holds the file's overview the reader picks, as when the project is opened again. + // It holds the overview the writer keeps (`in_blocks::OVERVIEW_SAMPLES`, lowered in tests; in a + // release build the reader picks the same one, both being `2 << 20`). assert_eq!(rl.data.as_ref().map(|r| (r.width, r.overview)), Some((500, Some((1000, 1000))))); same(&rustgis_data::raster::read_path(&file).unwrap(), "written"); let notes = said(&s, mark); diff --git a/crates/engine/src/tests/unplaced_gp.rs b/crates/engine/src/tests/unplaced_gp.rs index 11f7de1a91..3b763d7eba 100644 --- a/crates/engine/src/tests/unplaced_gp.rs +++ b/crates/engine/src/tests/unplaced_gp.rs @@ -73,7 +73,7 @@ fn run(s: &mut Session, cmd: &str, p: serde_json::Value) -> (serde_json::Value, assert!( s.notices_since(mark) .iter() - .filter(|n| n.text.contains("can't be given in") && !n.text.contains("so the tool reads them")) + .filter(|n| n.text.contains("can't be given in") && !n.text.contains("so any of them the tool reads have no geometry")) .all(|n| n.loss().is_some()), "{cmd}: {said:?}" ); @@ -104,7 +104,11 @@ fn a_tool_reads_a_feature_it_cant_place_without_its_geometry_and_says_so() { let said = tool_said(&out, notes); if far { assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].contains("1 feature(s) of 'lines' (1)") && said[0].contains("without their geometry"), "{}", said[0]); + assert!( + said[0].contains("1 feature(s) of 'lines' (1)") && said[0].contains("so any of them the tool reads have no geometry"), + "{}", + said[0] + ); } else { assert!(said.is_empty(), "{said:?}"); } diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index bc944ab3e0..ad30c62195 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -94,8 +94,10 @@ impl Budget { self.room_said = false; } - /// Keep a contiguous history around the current state. Count a shared allocation only at its - /// highest-priority owner, so the estimate falls only once its last snapshot is evicted. + /// Keep a contiguous history around the current state. Count each step's rows and rasters + /// (pixels and embedded files); a shared allocation is counted only at its highest-priority + /// owner, and what the open project holds costs nothing, so the estimate falls only once its + /// last snapshot is evicted. pub(crate) fn trim(&mut self, live: &Project, undo: &mut Vec, redo: &mut Vec) -> Option { let mut seen: HashSet<_> = rows(live).map(|features| features.allocation_key().as_ptr() as usize).collect(); seen.extend(self.readers.allocations().iter().map(|key| key.as_ptr() as usize)); diff --git a/crates/engine/tests/integration/zip_columns.rs b/crates/engine/tests/integration/zip_columns.rs index 5934cadec3..4f4df672d7 100644 --- a/crates/engine/tests/integration/zip_columns.rs +++ b/crates/engine/tests/integration/zip_columns.rs @@ -158,9 +158,12 @@ fn a_zips_picked_layer_keeps_the_zips_notices() { } #[test] -fn a_zip_given_x_without_y_or_both_kinds_of_geometry_is_refused_or_said() { +fn a_zip_given_x_without_y_or_wkt_with_xy_is_refused() { let bytes = members(false); - for p in [json!({"x": "LongitudeOR"}), json!({"x": "LongitudeOR", "y": "LatitudeOR", "wkt": "LongitudeOR"})] { + for (p, said) in [ + (json!({"x": "LongitudeOR"}), "give both the x and the y column"), + (json!({"x": "LongitudeOR", "y": "LatitudeOR", "wkt": "LongitudeOR"}), "give x and y columns, or a WKT column, not both"), + ] { let mut s = Session::new(Project::default()); let dir = unique_dir(); std::fs::create_dir_all(&dir).unwrap(); @@ -170,10 +173,28 @@ fn a_zip_given_x_without_y_or_both_kinds_of_geometry_is_refused_or_said() { q["path"] = json!(path); let ran = s.run("layer.addData", &q); let _ = std::fs::remove_dir_all(&dir); - assert!(ran.is_err(), "{ran:?}"); + assert!(ran.as_ref().is_err_and(|e| e.contains(said)), "{ran:?}"); } } +/// A blank `delimiter` (a form field left empty) is none given: the zip, and a CSV, read as they +/// do without one, not refused as a delimiter that isn't one character. +#[test] +fn a_blank_delimiter_reads_as_none_given() { + let (s, _) = add("path", &members(false), json!({"x": "LongitudeOR", "y": "LatitudeOR", "delimiter": ""})); + let (without, _) = add("path", &members(false), columns()); + assert_eq!(shape(&s), shape(&without)); + let dir = unique_dir(); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("p.csv"); + std::fs::write(&path, "id;lon;lat\n1;10;20\n2;11;21\n").unwrap(); + let mut s = Session::new(Project::default()); + let ran = s.run("layer.addData", &json!({"path": path, "delimiter": "", "x": "lon", "y": "lat"})); + let _ = std::fs::remove_dir_all(&dir); + assert!(ran.is_ok(), "{ran:?}"); + assert_eq!(shape(&s).0, [("p".to_string(), 2)]); +} + #[test] fn a_zips_columns_notice_goes_with_a_picked_layer_that_is_not_the_first() { let (s, said) = add("path", &members(true), json!({"x": "LongitudeOR", "y": "LatitudeOR", "layer": "2024"})); diff --git a/crates/render/src/layout/profile.rs b/crates/render/src/layout/profile.rs index ba3a3a0d98..91bfd097d3 100644 --- a/crates/render/src/layout/profile.rs +++ b/crates/render/src/layout/profile.rs @@ -16,7 +16,7 @@ pub struct ProfileSamples { pub metres: Vec, /// The band's value at each sample; `None` where it has no data. pub values: Vec>, - /// The section line's length in the raster's cells, when it is more than the samples read + /// About the section line's length in the raster's cells, when it is more than the samples read /// ([`MAX_PROFILE_SAMPLES`]). pub cells: Option, } @@ -30,7 +30,7 @@ impl ProfileSamples { } } -/// How many points of the line a profile probes to count the raster's cells it crosses. +/// How many points of the line a profile probes to measure its length in the raster's cells. const CELL_PROBES: usize = 64; /// A profile's frame, section line and raster in `layout` over `maps`, and what it reads along @@ -90,7 +90,7 @@ pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(Pr let (x, y) = swap((along, across)); cam.try_to_map(x, y, fw, fh).and_then(|m| map.to_lonlat(m)).filter(|c| c.x.is_finite() && c.y.is_finite()) }; - // The cells the line crosses, counted along it in the raster's own grid. + // About the line's length in the raster's cells, measured along it in the raster's own grid. let cell = |c: Coord| r.transformer().from_lonlat(c).map(|w| r.transform.to_pixel(w)); let probes: Vec<(f64, f64)> = (0..=CELL_PROBES).filter_map(|i| lonlat(a + (b - a) * i as f64 / CELL_PROBES as f64).and_then(cell)).collect(); diff --git a/crates/render/src/layout/section.rs b/crates/render/src/layout/section.rs index fa6675da6e..2293aac6e1 100644 --- a/crates/render/src/layout/section.rs +++ b/crates/render/src/layout/section.rs @@ -151,6 +151,10 @@ pub fn sections_not_drawn(layout: &Layout, maps: &[Map]) -> Vec { let mut gaps = Vec::new(); for e in layout.elements.iter().filter(|e| e.visible) { let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, sections, .. } = &e.kind else { continue }; + // Most frames have none: no map to look up, no camera to build. + if sections.is_empty() { + continue; + } let shown = map_index(maps, map).and_then(|i| maps.get(i)).map(|m| (m, frame_camera(m, *center, *scale, *bearing, *pitch))); let size = (e.w * PT_PER_MM, e.h * PT_PER_MM); gaps.extend(sections.iter().filter_map(|s| { diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 7124421885..a6515c14bf 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -68,11 +68,10 @@ fn direct_of(r: &Raster, place: Place) -> Option { map.to(r.crs).ok() } -/// A whole geographic turn has exactly this many columns. Compare the grid's span rather -/// than truncating `360 / pixel_width`: a regional grid can end partway through that column. +/// A whole geographic turn has exactly this many columns ([`Raster::full_turn_width`], which the +/// profiles' bilinear reads share). pub(crate) fn full_turn_width(r: &Raster) -> Option { - let span = f64::from(r.width) * r.transform.pixel_width.abs(); - (r.transformer().is_geographic() && (span - 360.0).abs() <= 360.0 * 16.0 * f64::EPSILON).then_some(i64::from(r.width)) + r.full_turn_width() } /// The value of `band` at a pixel, unless it is no data, masked or outside the grid. diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 0e4a6134f7..a4efa42c3b 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -1189,8 +1189,8 @@ fn forgotten_as(url: &str) -> &str { /// Forgets every resource of `resources` ([`forgotten_as`]) as [`forget`] does, and every cached /// answer whose canonical resource is one of `bases`. The cached answers are gone through once for -/// all of them; the archives, COG tiles and remote files of each resource are forgotten one -/// resource at a time, each going through its own cache. Reads under way are kept, and [`request`] +/// all of them, and so are the archives, COG tiles and remote files, each cache once. Reads under +/// way are kept, and [`request`] /// and [`peek_from`] refuse what they complete under a wider reach. fn forget_resources(resources: &std::collections::HashSet, bases: &std::collections::HashSet) { // First: a tile answered from here on is dropped, and one answered before goes with the rest. @@ -1207,11 +1207,9 @@ fn forget_resources(resources: &std::collections::HashSet, bases: &std:: }); c.bytes = c.slots.values().map(Slot::bytes).sum(); drop(c); - for url in resources { - crate::pmtiles::forget_archive(url); - crate::cog::forget_file(url); - rustgis_data::source::remote::forget_file(url); - } + crate::pmtiles::forget_archives(resources); + crate::cog::forget_files(resources); + rustgis_data::source::remote::forget_files(resources); // Map tiles made from a service's pictures, kept only while one is missing or on its way, // and their plans: all are made again (those kept in the cache stay till `clear`). crate::warp::forget(); diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 3ea5aa9d9a..4e34530855 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -348,6 +348,16 @@ pub(crate) fn forget_file(url: &str) { forget_file_in(&mut tiles().lock().unwrap_or_else(|e| e.into_inner()), url); } +/// [`forget_file`] for every file of `urls`, going through each cache once for them all. +pub(crate) fn forget_files(urls: &std::collections::HashSet) { + if urls.is_empty() { + return; + } + infos().lock().unwrap_or_else(|e| e.into_inner()).retain(|u, s| !urls.contains(u) || matches!(s, State::Loading(..))); + raster::forget_failed_where(|u| urls.contains(u)); + forget_files_in(&mut tiles().lock().unwrap_or_else(|e| e.into_inner()), |u| urls.contains(u)); +} + /// Forgets what was read of a GeoTIFF on this computer ([`is_local_file`]), so its header and /// tiles are read again from the file as it is now: it is added or reloaded after it may have /// been written again. Nothing for a web address, whose reads follow the tile cache's. @@ -359,16 +369,21 @@ pub fn forget_local_file(url: &str) { /// Forgets a file's tiles kept (not those loading) from `t`. fn forget_file_in(t: &mut Tiles, url: &str) { + forget_files_in(t, |u| u == url); +} + +/// Forgets the tiles kept (not those loading) from `t` of every file `of` picks. +fn forget_files_in(t: &mut Tiles, of: impl Fn(&str) -> bool) { let mut freed = 0; t.map.retain(|(u, _, _), s| match s { - TileState::Ready(_, n, _, _) if u == url => { + TileState::Ready(_, n, _, _) if of(u) => { freed += *n; false } _ => true, }); t.samples = t.samples.saturating_sub(freed); - t.order.retain(|_, (u, _, _)| u != url); + t.order.retain(|_, (u, _, _)| !of(u)); } /// A file's info: `Ok(None)` while it is being read (asking for it starts the read). diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index 9151cba842..73d34dbd1e 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -16,7 +16,7 @@ use web_time::Instant; use super::{AT_ONCE, BUDGET, Bands, Info, RETRY, TileState, fetch_all, get_tile, split, tiles, with_info}; /// The most samples (every band) of the overview a layer holds. -const OVERVIEW_SAMPLES: usize = if cfg!(target_arch = "wasm32") { 1 << 20 } else { 2 << 20 }; +pub const OVERVIEW_SAMPLES: usize = if cfg!(target_arch = "wasm32") { 1 << 20 } else { 2 << 20 }; /// The most chunks read for it. const OVERVIEW_CHUNKS: usize = 512; /// The most chunks of the coarsest level, held when no level fits [`OVERVIEW_SAMPLES`] (a file @@ -276,6 +276,11 @@ pub(super) fn forget_failed(file: Option<&str>) { forget_failed_in(&mut failed().lock().unwrap_or_else(|e| e.into_inner()), file); } +/// Forgets the failed tiles of every file `of` picks. +pub(super) fn forget_failed_where(of: impl Fn(&str) -> bool) { + failed().lock().unwrap_or_else(|e| e.into_inner()).retain(|(u, _, _), _| !of(u)); +} + fn forget_failed_in(f: &mut HashMap<(String, usize, u32), Instant>, file: Option<&str>) { match file { None => f.clear(), diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index ce0e2b0b09..5ada2004dd 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -592,14 +592,22 @@ pub(crate) fn forget() { } /// Forgets what was read of one archive (its header, and its directories), but not a read under -/// way: a failed read is made again with whatever login now signs the archive's address. +/// way: a failed read is made again with whatever login now signs the archive's address. The +/// app forgets them together ([`forget_archives`]). +#[cfg(test)] pub(crate) fn forget_archive(archive: &str) { - let mut all = archives().lock().unwrap_or_else(|e| e.into_inner()); - if all.get(archive).is_some_and(|s| !matches!(s, State::Loading(_))) { - all.remove(archive); + forget_archives(&std::collections::HashSet::from([archive.to_string()])); +} + +/// Forgets what was read of each archive of `archives_of` (its header, and its directories), but +/// not a read under way, going through each cache once for them all: a failed read is made again +/// with whatever login now signs the archive's address. +pub(crate) fn forget_archives(archives_of: &std::collections::HashSet) { + if archives_of.is_empty() { + return; } - drop(all); - leaves().lock().unwrap_or_else(|e| e.into_inner()).retain(|(a, _), l| a != archive || matches!(l, Leaf::Loading(_))); + archives().lock().unwrap_or_else(|e| e.into_inner()).retain(|a, s| !archives_of.contains(a) || matches!(s, State::Loading(_))); + leaves().lock().unwrap_or_else(|e| e.into_inner()).retain(|(a, _), l| !archives_of.contains(a) || matches!(l, Leaf::Loading(_))); } /// Pending callbacks are returned for disposal outside the revision lock: dropping a tile's diff --git a/crates/ui-egui/src/diagnosticlog.rs b/crates/ui-egui/src/diagnosticlog.rs index 3f1ae9cc3e..811f6d842d 100644 --- a/crates/ui-egui/src/diagnosticlog.rs +++ b/crates/ui-egui/src/diagnosticlog.rs @@ -125,10 +125,13 @@ fn run_heading(ui: &mut Ui, app: &mut RustGisApp, record: &Record, t: &Tokens) { ui.horizontal_wrapped(|ui| { ui.label(RichText::new(time(record.timestamp_ms)).small().monospace().color(t.text_dim)); if let Some(steps) = steps { - let hover = if steps == 1 { - tl!("Takes back this command's changes").to_string() - } else { - crate::i18n::fmt("Takes back this command's changes and the {n} after it", &[("n", &(steps - 1).to_string())]) + let hover = match steps { + 1 => tl!("Takes back this command's changes").to_string(), + 2 => tl!("Takes back this command's changes and those of the command after it").to_string(), + _ => crate::i18n::fmt( + "Takes back this command's changes and those of the {n} commands after it", + &[("n", &(steps - 1).to_string())], + ), }; // One history jump at a time: Undo History's own, or another message's. let free = app.ui.history_jump.is_none(); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 70c0418312..213e26ec2a 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5811,7 +5811,8 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { // The label typed, or the values joined while none is. let typed: Option = ui.data(|d| d.get_temp(label_key)); // Sent whole: the command cuts a long one and says so. - let mut label = typed.unwrap_or_else(|| ticked.join(", ")); + let joined = ticked.join(", "); + let mut label = typed.unwrap_or_else(|| joined.clone()); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Group as")).size(11.5).color(t.text)); // The button at the right, the label in the room left of it. @@ -5827,8 +5828,13 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { Err(e) => app.session.notify(e, true), } } - let edit = egui::TextEdit::singleline(&mut label).char_limit(MAX_LABEL).desired_width(ui.available_width()); - if ui.add(edit).on_hover_text(tl!("Legend label of the group")).changed() { + // Emptied, the command labels the group with the values joined: shown as + // the hint, so the box and the legend agree. + let edit = egui::TextEdit::singleline(&mut label) + .char_limit(MAX_LABEL) + .hint_text(joined.as_str()) + .desired_width(ui.available_width()); + if ui.add(edit).on_hover_text(tl!("Legend label of the group (blank: the values joined)")).changed() { ui.data_mut(|d| d.insert_temp(label_key, label)); } }); diff --git a/crates/ui-egui/src/pluginpanel.rs b/crates/ui-egui/src/pluginpanel.rs index ed1176ada1..c527f0afe8 100644 --- a/crates/ui-egui/src/pluginpanel.rs +++ b/crates/ui-egui/src/pluginpanel.rs @@ -1476,6 +1476,8 @@ mod tests { /// A plugin's command adding data by address doesn't wait for it: the app downloads it off /// the frame, as the browser does, and the layer lands as the plugin asked for it (#1144). + // The engine's hook letting plugins reach the test server exists only in debug test builds. + #[cfg(debug_assertions)] #[test] fn a_plugin_adds_data_by_address_off_the_frame() { // The plugin's downloads come from this computer (a test server or address). @@ -1525,6 +1527,8 @@ mod tests { } /// The real deferred request and probe loop refuse a withdrawn plugin before a fallback send. + // The engine's hook letting plugins reach the test server exists only in debug test builds. + #[cfg(debug_assertions)] #[test] fn permission_policy_plugin_deferred_probe_refuses_before_fallback() { // The plugin's downloads come from this computer (a test server or address). @@ -1600,6 +1604,8 @@ mod tests { /// A GeoTIFF asked for as a scan keeps only its pixels: the app downloads it whole, once, /// without first reading its header to see whether it could be read in place. + // The engine's hook letting plugins reach the test server exists only in debug test builds. + #[cfg(debug_assertions)] #[test] fn a_scan_by_address_is_downloaded_whole_without_a_probe() { // The plugin's downloads come from this computer (a test server or address). @@ -1650,6 +1656,8 @@ mod tests { /// A plugin's command asking for a window of a cloud-optimised GeoTIFF doesn't wait for it: /// the app reads it off the frame, adds it when it lands, and runs the command again, whose /// `layer.addUrl` answers what was added (#1330). + // The engine's hook letting plugins reach the test server exists only in debug test builds. + #[cfg(debug_assertions)] #[test] fn a_plugin_reads_a_window_off_the_frame() { // The plugin's downloads come from this computer (a test server or address). diff --git a/crates/ui-egui/src/pluginstart.rs b/crates/ui-egui/src/pluginstart.rs index a5cfe5b0e7..640931a210 100644 --- a/crates/ui-egui/src/pluginstart.rs +++ b/crates/ui-egui/src/pluginstart.rs @@ -206,6 +206,8 @@ mod tests { } /// Queued plugins leave owned URL requests to the app; string zoom options survive delivery. + // The engine's hook letting plugins reach the test server exists only in debug test builds. + #[cfg(debug_assertions)] #[test] fn queued_plugin_downloads_keep_their_claim_and_zoom() { // The plugin's downloads come from this computer (a test server or address). diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index d2317c47fa..715bd4b085 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3426,7 +3426,9 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) { let frame = layout_frame(app); let add = |app: &mut RustGisApp, mut p: Value| { p["layout"] = json!(li); - if let Some(f) = frame { + // Only to a kind that reads it: the others refuse a frame. + let kind = p["kind"].as_str().unwrap_or_default(); + if let Some(f) = frame.filter(|_| rustgis_engine::cmd::layout::add_element_reads_frame(kind)) { p["frame"] = json!(f); } match app.run("layout.addElement", p) { diff --git a/docs/plugins.md b/docs/plugins.md index 57376c1ca8..04867cc26e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -789,13 +789,16 @@ that needs it left out. address taken from the one before, runs once per step, up to 64 times. The browser follows redirects itself, and the server must allow requests from web pages (CORS). -The commands a plugin runs follow the same rule. A web address it gives one that connects (the -`url` of `stac.search`, `portal.add`, `layer.addUrl`, `map.addTiles` or `osm.download`, a portal's -address, a service or catalogue to discover) must be on the internet, or the command is refused -before anything is read. Every request such a command makes connects only to the internet, +The commands a plugin runs follow the same rule. A web address it gives one as a parameter that +connects (the `url` of `stac.search`, `portal.add`, `layer.addUrl`, `map.addTiles` or +`osm.download`, a portal's address, a service or catalogue to discover) must be on the internet, +or the command is refused before anything is read; an address inside another parameter is refused +when it is read, naming it, as every request such a command makes connects only to the internet, wherever its name resolves: the address itself, the requests made from it (a listing, a search, the next page), those a saved connection sends, and the documents read from it, any `text` the -plugin supplies and everything they name. +plugin supplies and everything they name. A catalogue's answer is the exception to naming: its +links to this computer or the local network (in a document read from the internet, or `text` the +plugin supplies) are left out of the records and counted in the answer's `notes`, not named. Use `host::call("host.fetch", json!({"url": url}))` in the Rust SDK, or `host::call("host.fetch", json!({"url": url, "json": false}))` for the text only. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 3841f5f7d3..5b2fd90843 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -7,8 +7,10 @@ Turn editing on (also offered in the dialog), enter X and Y, optionally a name, **Add Point** or press ++enter++. Leave the coordinate system blank for longitude/latitude in decimal degrees or degrees, minutes and seconds, or enter a system such as `EPSG:3857` for numeric eastings and northings. Enter `map` to use the map's current flat projection, -or a layer's name to use that layer's coordinate system. Otherwise, changing the map's -display projection does not change the entered coordinates' meaning. +or a layer's name to use that layer's coordinate system. A layer name is looked up before a +system code, so a layer named `EPSG:3857` makes `EPSG:3857` mean that layer's system; rename +such a layer to enter the code. Otherwise, changing the map's display projection does not +change the entered coordinates' meaning. The dialog stays open and clears X, Y and Name after success; ++esc++ closes it when its fields have focus or no other work owns the key. On the map, Escape still cancels a sketch. @@ -20,25 +22,25 @@ an existing layer has no such field. Each addition, including a new layer, is on The same operation is available through Command Search and `edit.addPoint`, for example: `edit.addPoint {"x":14.3,"y":-41.2,"name":"Survey"}`. -**Edit › Create** draws new points, lines and polygons into the layer selected in Layers: -click once for a point, or click each vertex and double-click to finish a line or polygon -(++esc++ cancels). **Delete** (++delete++) removes the selected features across the map's layers. -Edit attributes in the attribute table (++ctrl+t++): double-click a cell -to change it. **Data › Data Design** (and **Data › Fields**) adds and deletes fields and calculates a -field from an expression; **Calculate Geometry** (in the attribute table's toolbar) fills a new or -existing numeric field with each feature's area, perimeter, length or X/Y coordinate, in the units -you choose, for all features or the selected ones. Length and perimeter include feet and miles; -area includes square feet (`ft2`), acres (`ac`) and square miles (`mi2`). An unrecognized -`edit.calculateGeometry` unit is refused with the valid unit keys for the chosen property. A feature -with a place that can't be given in longitude/latitude (one far past where its layer's own system -reaches) is left empty, and a notice counts them. -Every edit is one undo step. Areas, perimeters and lengths measure on the WGS 84 ellipsoid, the same measure as the network tools and the Measure panel (Spatial Join still -measures on the sphere). A ring with a full-turn edge, -180° to 180° along a parallel that the -ring reaches down one meridian and leaves back up the other (a globe-wide band, or a cap closed -along the pole), counts that whole parallel, as long as the ring's turns leave it closed around -the globe; an edge from 180° to -180° anywhere else is a seam along the antimeridian (a polygon -split there), so a 1° cell written that way is the cell. A ring winding around a pole is measured as the region it -traces, where [Geoprocessing](analysis.md#geoprocessing-tools) gives the smaller polar cap. +**Edit › Create** draws new points, lines and polygons into the layer selected in Layers: click once +for a point, or click each vertex and double-click to finish a line or polygon (++esc++ cancels). +**Delete** (++delete++) removes the selected features across the map's layers. Edit attributes in +the attribute table (++ctrl+t++): double-click a cell to change it. **Data › Data Design** (and +**Data › Fields**) adds and deletes fields and calculates a field from an expression; **Calculate +Geometry** (in the attribute table's toolbar) fills a new or existing numeric field with each +feature's area, perimeter, length or X/Y coordinate, in the units you choose, for all features or +the selected ones. Length and perimeter include feet and miles; area includes square feet (`ft2`), +acres (`ac`) and square miles (`mi2`). An unrecognized `edit.calculateGeometry` unit is refused with +the valid unit keys for the chosen property. A feature with a place that can't be given in +longitude/latitude (one far past where its layer's own system reaches) is left empty, and a notice +counts them. Every edit is one undo step. Areas, perimeters and lengths measure on the WGS 84 +ellipsoid, the same measure as the network tools and the Measure panel (Spatial Join still measures +on the sphere). A ring with a full-turn edge, -180° to 180° along a parallel that the ring reaches +down one meridian and leaves back up the other (a globe-wide band, or a cap closed along the pole), +counts that whole parallel, as long as the ring's turns leave it closed around the globe; an edge +from 180° to -180° anywhere else is a seam along the antimeridian (a polygon split there), so a 1° +cell written that way is the cell. A ring winding around a pole is measured as the region it traces, +where [Geoprocessing](analysis.md#geoprocessing-tools) gives the smaller polar cap. Undo (++ctrl+z++) and Redo (++ctrl+y++ or ++ctrl+shift+z++) restore project changes, not just feature edits; use ++cmd++ instead of ++ctrl++ on macOS. While typing in a text field, those @@ -81,61 +83,57 @@ of the live map's measurement units. The entered numbers are interpreted in the you click **Move**, **Constant** or **Apply elevation**. The current elevation stays in effect while you edit the value or choose units; click **Apply elevation** to apply the new inputs. -- **Modify**: move the selected features by distances east and north, rotate them, scale them, - merge them (polygons are unioned), explode multipart features, split a line where you click, - and flip line direction. A single point turns and scales on itself, so Rotate and Scale leave - points (text graphics included) as they are: with only points selected they change nothing, - say so, and add no undo step. Edit › Tools lists every editing tool. - In a layer held in a projected system (UTM, a national grid; not Web Mercator, another world - projection or a geographic system), Move, Rotate and Scale work in the layer's own coordinates, - as the analysis tools do: Move steps the distances east and north along its grid, measured flat - in its unit (so in UTM a kilometre on the grid is between about 0.999 and 1.0004 km on the - ground, and its north is grid north; Ground to grid below corrects ground distances and - directions to it), following the system's axes when they point west, south or north first; Rotate turns clockwise - with grid north up, and Scale scales, about the middle of the feature's extent there. A Move - whose selection spans layers in more than one system (or some in one and some in - longitude/latitude; graphics don't count) moves them all as below, so places they share stay - together, and says so. Rotate and Scale turn each feature about its own middle anyway, so - they take each layer's own grid even then. The rest of this paragraph, about Web Mercator and - the ground, is for the other layers. - A selected feature with a place that can't be given in longitude/latitude (one far past where - its layer's own system reaches) is left as it is by Move, Rotate and Scale, Split and Cut - Polygon (in a layer edited in its own grid, each of these changes it with the rest), and a - notice counts them by layer; Flip Line flips it in the layer's own coordinates. An edit of that - one feature (a vertex, a shape conversion; Reshape, Trace or Merge with it, outside a layer - edited in its own grid) is refused, naming the layer and the feature; Set Geometry gives it a - new shape, and Delete removes it. - Beyond 85.05°, where Web Mercator stops, Move, Rotate and Scale work on the ground: a feature - that reaches beyond it, or that the edit would take beyond it, moves rigidly, together with the - selected features sharing a vertex with it (their center goes the distance and direction asked, - along the ground and across a pole if that's the way, and the rest turn with the world around - it), and turns or scales about its own center. Within ±85.05° an edit is made in Web Mercator, as - before (where a long move north covers less ground than asked, and Rotate and Scale turn about - the middle of the feature's extent), so an edit that just stays within 85.05° and one that just - passes it can land far apart. Only the vertices move rigidly: edges stay straight in longitude - and latitude between them, so long edges bend, the more so the nearer the pole one end is than - the other, and far less for moves north–south than east–west: an edge from 87° to 89° bends - 333 m for each kilometer moved east; one from 89.5° to 89.99° bends much more. Add vertices along them first to keep their shape. A moved - feature's longitudes run on from where they were written, past ±180° if it crosses there (to - 188°, say, rather than −172°), as within ±85.05°; one carried more than halfway around a pole - is written within half a turn of where it was. - Rotate and Scale use each feature's own center, so selected neighbors sharing a corner can - separate at that corner. - Right by a pole a move's directions turn quickly with its center's place: a center at - the pole takes "east" from the prime meridian (toward 90°E), one a meter away from its own - longitude. The whole edit is refused, and nothing changes, when a selected line or polygon - edited on the ground reaches a pole (so moving every feature of a world layer fails while - Antarctica is selected), spans 180° of longitude or more in one edge, or would be carried onto - or around a pole, or when the edit would move a feature more than 10,000 km on the ground or - carry a vertex more than 10,000 km from the center it's edited about. A move of no distance - leaves features beyond 85.05° as they are. Moving neighbors one at a time, one within ±85.05° - and one beyond, can leave their shared corners apart, by about the distance moved times +- **Modify**: move the selected features by distances east and north, rotate them, scale them, merge + them (polygons are unioned), explode multipart features, split a line where you click, and flip + line direction. A single point turns and scales on itself, so Rotate and Scale leave points (text + graphics included) as they are: with only points selected they change nothing, say so, and add no + undo step. Edit › Tools lists every editing tool. In a layer held in a projected system (UTM, a + national grid; not Web Mercator, another world projection or a geographic system), Move, Rotate + and Scale work in the layer's own coordinates, as the analysis tools do: Move steps the distances + east and north along its grid, measured flat in its unit (so in UTM a kilometre on the grid is + between about 0.999 and 1.0004 km on the ground, and its north is grid north; Ground to grid below + corrects ground distances and directions to it), following the system's axes when they point west, + south or north first; Rotate turns clockwise with grid north up, and Scale scales, about the + middle of the feature's extent there. A Move whose selection spans layers in more than one system + (or some in one and some in longitude/latitude; graphics don't count) moves them all as below, so + places they share stay together, and says so. Rotate and Scale turn each feature about its own + middle anyway, so they take each layer's own grid even then. The rest of this paragraph, about Web + Mercator and the ground, is for the other layers. A selected feature with a place that can't be + given in longitude/latitude (one far past where its layer's own system reaches) is left as it is + by Move, Rotate and Scale, Split and Cut Polygon (in a layer edited in its own grid, each of these + changes it with the rest), and a notice counts them by layer; Flip Line flips it in the layer's + own coordinates. An edit of that one feature (a vertex, a shape conversion; Reshape, Trace or + Merge with it, outside a layer edited in its own grid) is refused, naming the layer and the + feature; Set Geometry gives it a new shape, and Delete removes it. Beyond 85.05°, where Web + Mercator stops, Move, Rotate and Scale work on the ground: a feature that reaches beyond it, or + that the edit would take beyond it, moves rigidly, together with the selected features sharing a + vertex with it (their center goes the distance and direction asked, along the ground and across a + pole if that's the way, and the rest turn with the world around it), and turns or scales about its + own center. Within ±85.05° an edit is made in Web Mercator, as before (where a long move north + covers less ground than asked, and Rotate and Scale turn about the middle of the feature's + extent), so an edit that just stays within 85.05° and one that just passes it can land far apart. + Only the vertices move rigidly: edges stay straight in longitude and latitude between them, so + long edges bend, the more so the nearer the pole one end is than the other, and far less for moves + north–south than east–west: an edge from 87° to 89° bends 333 m for each kilometer moved east; one + from 89.5° to 89.99° bends much more. Add vertices along them first to keep their shape. A moved + feature's longitudes run on from where they were written, past ±180° if it crosses there (to 188°, + say, rather than −172°), as within ±85.05°; one carried more than halfway around a pole is written + within half a turn of where it was. Rotate and Scale use each feature's own center, so selected + neighbors sharing a corner can separate at that corner. Right by a pole a move's directions turn + quickly with its center's place: a center at the pole takes "east" from the prime meridian (toward + 90°E), one a meter away from its own longitude. The whole edit is refused, and nothing changes, + when a selected line or polygon edited on the ground reaches a pole (so moving every feature of a + world layer fails while Antarctica is selected), spans 180° of longitude or more in one edge, or + would be carried onto or around a pole, or when the edit would move a feature more than 10,000 km + on the ground or carry a vertex more than 10,000 km from the center it's edited about. A move of + no distance leaves features beyond 85.05° as they are. Moving neighbors one at a time, one within + ±85.05° and one beyond, can leave their shared corners apart, by about the distance moved times 2·sin(Δλ/2), Δλ being the corner's longitude from the center of the one moved on the ground (a tenth of it 6° away, half of it 30° away): select them together. Split cuts beyond 85.05° where it's asked: where the point or the line reaches beyond it, at the line's point nearest on the - ground (once a split has worked out a million distances along segments near the point, a - segment counts as near as the nearest point found on it so far, its nearer end at first, and the - split says how many lines it cut that way, or left whole when that point was an end). + ground (once a split has worked out a million distances along segments near the point, a segment + counts as near as the nearest point found on it so far, its nearer end at first, and the split + says how many lines it cut that way, or left whole when that point was an end). - **On a layer's own segments:** in a layer held in a projected system (as for Move above), Cut Polygon, Reshape, Split, Merge and Trace work on its segments as they run straight in its own coordinates. The line drawn (or the point Split is given) is converted into them, a point @@ -154,50 +152,50 @@ you edit the value or choose units; click **Apply elevation** to apply the new i succeeds, a notice says how many selected features the line didn't cut (`missed` in the result). A line that cuts none of them gives an error instead. `edit.cutPolygon={"line": {"type": "LineString", "coordinates": [[0.3, -1], [0.3, 2]]}}`. -- **Reshape** (Edit › Tools, or the Editing pane): select one line or polygon, then draw a line - that leaves its edge and comes back to it. For a polygon, the stretch of boundary between the - line's first and last crossings is replaced by the line, keeping whichever of the two possible - shapes is larger. A hole left wholly outside the new boundary goes with the part reshaped away, - and a notice says how many (`holesRemoved` in the result). A reshape that would make the - boundary cross itself, or a hole cross its outer ring, is refused. For a line, the stretch between two crossings is replaced. A drawn - line that crosses only once replaces the shorter end, so start on the line and draw out to - extend or redirect an end (`edit.reshape={"line": …}`). -- **Trace** (Edit › Features): while drawing a feature, a cut or a reshape, click a point on a - line or polygon edge, then another point on the same edge. The sketch follows the edge between - them, going the shorter way round a ring; click a point partway to go the other way. Turn on - snapping so clicks land exactly on the edge. From scripts, - `edit.trace={"from": [lon, lat], "to": [lon, lat]}` returns the path along the nearest edge - passing within the snapping tolerance of both points (`"layer"` keeps the search to one layer; - add `"row"` to trace a given feature), and how far each point was from the edge (`fromOffM`, `toOffM`, in Web Mercator metres, which - run longer than ground metres away from the equator; for a layer held in a projected system, - in metres of its grid). -- **Edit Vertices** (Edit › Features): reshape the selected features on the map. Their vertices - show as square handles and each edge has a round midpoint handle. Drag a vertex to move it; - drag a midpoint, or click an edge, to insert a vertex; click a vertex and press ++delete++ to - remove it (a line keeps at least two vertices, a polygon ring three). The handles sit where - the map draws the vertices. On a map in the layer's own coordinate system they are its stored - coordinates: a vertex you drag is written where you let go, in the layer's coordinates, and - every other vertex stays exactly as stored. On another map, a selected feature with a place - that can't be given in longitude/latitude (see [Places with no longitude/latitude](data-formats.md#places-with-no-longitudelatitude)) - gets no handles, and a notice says so once, naming it or counting them; on a map in its - layer's own system it gets its handles. Clicking elsewhere - selects the feature there (++shift++ adds it). Multipart features and polygon holes work the - same way, dragged vertices snap when snapping is on, and each move, insertion or deletion is - one undo step. ++esc++ finishes. From scripts and the command line, `edit.vertex` does the - same to one vertex, given in longitude/latitude (`lon`, `lat`) or in the layer's own - coordinates (`x`, `y`), and `edit.setGeometry` (Set Geometry) replaces a feature's whole shape. +- **Reshape** (Edit › Tools, or the Editing pane): select one line or polygon, then draw a line that + leaves its edge and comes back to it. For a polygon, the stretch of boundary between the line's + first and last crossings is replaced by the line, keeping whichever of the two possible shapes is + larger. A hole left wholly outside the new boundary goes with the part reshaped away, and a notice + says how many (`holesRemoved` in the result). A reshape that would make the boundary cross itself, + or a hole cross its outer ring, is refused. For a line, the stretch between two crossings is + replaced. A drawn line that crosses only once replaces the shorter end, so start on the line and + draw out to extend or redirect an end (`edit.reshape={"line": …}`). +- **Trace** (Edit › Features): while drawing a feature, a cut or a reshape, click a point on a line + or polygon edge, then another point on the same edge. The sketch follows the edge between them, + going the shorter way round a ring; click a point partway to go the other way. Turn on snapping so + clicks land exactly on the edge. From scripts, `edit.trace={"from": [lon, lat], "to": [lon, lat]}` + returns the path along the nearest edge passing within the snapping tolerance of both points + (`"layer"` keeps the search to one layer; add `"row"` to trace a given feature), and how far each + point was from the edge (`fromOffM`, `toOffM`, in Web Mercator metres, which run longer than + ground metres away from the equator; for a layer held in a projected system, in metres of its + grid). +- **Edit Vertices** (Edit › Features): reshape the selected features on the map. Their vertices show + as square handles and each edge has a round midpoint handle. Drag a vertex to move it; drag a + midpoint, or click an edge, to insert a vertex; click a vertex and press ++delete++ to remove it + (a line keeps at least two vertices, a polygon ring three). The handles sit where the map draws + the vertices. On a map in the layer's own coordinate system they are its stored coordinates: a + vertex you drag is written where you let go, in the layer's coordinates, and every other vertex + stays exactly as stored. On another map, a selected feature with a place that can't be given in + longitude/latitude (see [Places with no + longitude/latitude](data-formats.md#places-with-no-longitudelatitude)) gets no handles, and a + notice says so once, naming it or counting them; on a map in its layer's own system it gets its + handles. Clicking elsewhere selects the feature there (++shift++ adds it). Multipart features and + polygon holes work the same way, dragged vertices snap when snapping is on, and each move, + insertion or deletion is one undo step. ++esc++ finishes. From scripts and the command line, + `edit.vertex` does the same to one vertex, given in longitude/latitude (`lon`, `lat`) or in the + layer's own coordinates (`x`, `y`), and `edit.setGeometry` (Set Geometry) replaces a feature's + whole shape. - **Feature templates**: named default values for new features, made from a selected feature; the Create tool uses the chosen template. - **Snapping** (**Edit › Snapping**): new and dragged vertices snap to nearby vertices, edges and - line ends of visible feature layers at the current scale (magenta marker; graphics and rasters - are not targets). Vertices and ends take priority over edges within the tolerance. Snapping - starts off; its vertex, edge and end options start on. Both Point features and individual - MultiPoint members use the vertex option; they supply neither edges nor line ends. Dragging - a Point or MultiPoint member excludes its entire source feature. The tolerance is how near, in screen - pixels, a vertex must come to snap (10 by default, 1 to 100): - `edit.snapping={"on": true, "tolerancePx": 12, "edge": false}` (without `"on"` it toggles - snapping, even when other options are supplied). `edit.snap={"lon":12.5,"lat":41.9}` queries - the current snap target without editing a feature. + line ends of visible feature layers at the current scale (magenta marker; graphics and rasters are + not targets). Vertices and ends take priority over edges within the tolerance. Snapping starts + off; its vertex, edge and end options start on. Both Point features and individual MultiPoint + members use the vertex option; they supply neither edges nor line ends. Dragging a Point or + MultiPoint member excludes its entire source feature. The tolerance is how near, in screen pixels, + a vertex must come to snap (10 by default, 1 to 100): `edit.snapping={"on": true, "tolerancePx": + 12, "edge": false}` (without `"on"` it toggles snapping, even when other options are supplied). + `edit.snap={"lon":12.5,"lat":41.9}` queries the current snap target without editing a feature. - **Settings**: **Show Vertices** marks the vertices of the selected features even when Edit Vertices isn't on (`edit.settings={"showVertices": true}`). - **Elevation**: new features get a `z` attribute, constant or sampled from a raster surface at @@ -256,37 +254,37 @@ image coordinates may appear elliptical on the map; a rectangle may appear skewe not resampled by this choice, and shapes are not clipped to its boundary. Choose **Web Mercator grid metres** explicitly to draw in map coordinates instead; those are not -ground-distance metres. Choosing **No image** restores that grid. When the target layer is held -in a projected system with an EPSG code (UTM, a national grid; not Web Mercator, another world -projection or a geographic system), that choice is the **Layer's own grid** instead: one grid -unit per unit of the layer's system, y down (a grid x is the system's x and a grid y minus its y, -whichever way its axes point), and a shape built -in it is written in the layer's own coordinates as built, with no conversion. Web Mercator grid -metres are then not offered for new shapes; a command takes them with `"frame": {"epsg": 3857}`. Under Edit, the same choices -are in Editing → New shape grid when a circle or rotated box tool is active. Grid changes affect -new shapes; existing shapes retain their own construction grid when moved, resized or rotated. -Undo/Redo retain those constructions within the session. - -On desktop, header reads run in the background with progress and Cancel. Changing images, -switching to Web Mercator (or the layer's own grid) or using **Cancel Grid Read** stops only that lookup and preserves -unrelated queued work. The status-bar Cancel retains its queue-wide behaviour. Pixel-based +ground-distance metres. Choosing **No image** restores that grid. When the target layer is held in a +projected system with an EPSG code (UTM, a national grid; not Web Mercator, another world projection +or a geographic system), that choice is the **Layer's own grid** instead: one grid unit per unit of +the layer's system, y down (a grid x is the system's x and a grid y minus its y, whichever way its +axes point), and a shape built in it is written in the layer's own coordinates as built, with no +conversion. Web Mercator grid metres are then not offered for new shapes; a command takes them with +`"frame": {"epsg": 3857}`. Under Edit, the same choices are in Editing → New shape grid when a +circle or rotated box tool is active. Grid changes affect new shapes; existing shapes retain their +own construction grid when moved, resized or rotated. Undo/Redo retain those constructions within +the session. + +On desktop, header reads run in the background with progress and Cancel. Changing images, switching +to Web Mercator (or the layer's own grid) or using **Cancel Grid Read** stops only that lookup and +preserves unrelated queued work. The status-bar Cancel retains its queue-wide behaviour. Pixel-based drawing waits for a valid grid; a failed or cancelled read never silently substitutes map metres. After changing a source file externally, reload the image layer first, then use **Reload Grid**. Original-pixel drawing and conversion share the same [source checks](#image-source-checks). Removing/replacing an image invalidates its cached grid. Local and embedded GeoTIFFs are supported; download remote originals first. In the browser, upload the original GeoTIFF. Other local formats -(including PNG, JPEG, ASCII grids and GDAL-converted images) are refused with guidance to export -the image as a GeoTIFF and add that file; reloading the unsupported source cannot supply its grid. -Construction grids require a supported EPSG coordinate system. Unsupported or custom systems -are refused during the grid read; choose a supported image or **Web Mercator grid metres** (the **Layer's own grid** on a layer that has one). -Changing projects or maps clears the old image binding, keeps pixel mode selected and reports a -warning. Drawing stays blocked until you choose an image again or explicitly choose Web Mercator -grid metres (or the layer's own grid); opening the pane does not clear the warning. -An image removed from the map keeps its last name as **Unavailable image**. Pixel drawing stays -blocked and **Reload Grid** is disabled until the image is restored or another image is chosen. -Choose **No image** to return explicitly to Web Mercator grid metres (or the layer's own grid). -**Original Image Grid** in Command Search reports the active image's original dimensions and -EPSG coordinate system in a notice, while keeping the Annotate pane open. +(including PNG, JPEG, ASCII grids and GDAL-converted images) are refused with guidance to export the +image as a GeoTIFF and add that file; reloading the unsupported source cannot supply its grid. +Construction grids require a supported EPSG coordinate system. Unsupported or custom systems are +refused during the grid read; choose a supported image or **Web Mercator grid metres** (the +**Layer's own grid** on a layer that has one). Changing projects or maps clears the old image +binding, keeps pixel mode selected and reports a warning. Drawing stays blocked until you choose an +image again or explicitly choose Web Mercator grid metres (or the layer's own grid); opening the +pane does not clear the warning. An image removed from the map keeps its last name as **Unavailable +image**. Pixel drawing stays blocked and **Reload Grid** is disabled until the image is restored or +another image is chosen. Choose **No image** to return explicitly to Web Mercator grid metres (or +the layer's own grid). **Original Image Grid** in Command Search reports the active image's original +dimensions and EPSG coordinate system in a notice, while keeping the Annotate pane open. Space or middle-drag pans; releasing Space keeps the drawing tool. Use the selected object's existing handles, Undo/Redo, and **Export GeoJSON…**. **Shape details** is collapsed by default; @@ -366,31 +364,32 @@ rules continue to apply. Box tools do not create annotation or class fields. completed move, resize, rotation or deletion is undoable. ++esc++ cancels a held gesture; press it again to leave the tool. -The interactive tool starts in the layer's own grid when it has one (see -[Annotating an image](#annotating-an-image)), and otherwise in Web Mercator grid metres, **not -ground metres**; angles run clockwise from grid east. `edit.addBox` without `box.frame` uses -Web Mercator grid metres, as before; `"frame": {"epsg": 32632}` builds in that system's own grid -(the layer's own when it is held in it). Activating the interactive tool, including through `tool.set`, requires -an untilted, non-globe Earth view. The geometry commands (`edit.addBox`, `edit.updateBox` and -`edit.deleteBox`) work independently of the map's projection and pitch, using the construction -grid on an Earth map. Boxes crossing the antimeridian, the polar editing limit, and unsupported -projection or datum transformations are refused. The grid is frozen for an existing box. -Scripts can supply an original image grid -from `raster::geotiff::read_image_grid` through `rustgis_engine::box_edit::Frame::from_grid`; -then the box dimensions and centre are original image pixels, including for rotated/skewed -GeoTIFFs. This does not bind a layer to an image or save image metadata. - -Construction is kept only in the current session. An independent vertex edit disables the -box handles rather than silently fitting a new box; undo restores them. Saving/reopening or -sharing GeoJSON leaves **ordinary polygons** and ordinary feature properties. In-session edits -preserve feature identity; import uses the normal GeoJSON reader. Copy/paste transfers ordinary polygon geometry and attributes, not construction parameters; -the original keeps its constrained handles. There is no automatic recognition of imported polygons. Use **Edit Vertices** to edit those polygons. -**Export Features** (`share.exportLayer`) includes one counted note explaining that box -construction does not round-trip. Explicit project saves/downloads, map/layer files, project -and map packages, data conversions and feature-bearing web shares report the same loss. -Source polygons contain four transformed corners joined by straight edges; curved grid edges -are approximated. The target format may further approximate or omit geometry: CSV writes -representative points and GPX does not retain polygon areas, with their own format-specific notes. +The interactive tool starts in the layer's own grid when it has one (see [Annotating an +image](#annotating-an-image)), and otherwise in Web Mercator grid metres, **not ground metres**; +angles run clockwise from grid east. `edit.addBox` without `box.frame` uses Web Mercator grid +metres, as before; `"frame": {"epsg": 32632}` builds in that system's own grid (the layer's own when +it is held in it). Activating the interactive tool, including through `tool.set`, requires an +untilted, non-globe Earth view. The geometry commands (`edit.addBox`, `edit.updateBox` and +`edit.deleteBox`) work independently of the map's projection and pitch, using the construction grid +on an Earth map. Boxes crossing the antimeridian, the polar editing limit, and unsupported +projection or datum transformations are refused. The grid is frozen for an existing box. Scripts can +supply an original image grid from `raster::geotiff::read_image_grid` through +`rustgis_engine::box_edit::Frame::from_grid`; then the box dimensions and centre are original image +pixels, including for rotated/skewed GeoTIFFs. This does not bind a layer to an image or save image +metadata. + +Construction is kept only in the current session. An independent vertex edit disables the box +handles rather than silently fitting a new box; undo restores them. Saving/reopening or sharing +GeoJSON leaves **ordinary polygons** and ordinary feature properties. In-session edits preserve +feature identity; import uses the normal GeoJSON reader. Copy/paste transfers ordinary polygon +geometry and attributes, not construction parameters; the original keeps its constrained handles. +There is no automatic recognition of imported polygons. Use **Edit Vertices** to edit those +polygons. **Export Features** (`share.exportLayer`) includes one counted note explaining that box +construction does not round-trip. Explicit project saves/downloads, map/layer files, project and map +packages, data conversions and feature-bearing web shares report the same loss. Source polygons +contain four transformed corners joined by straight edges; curved grid edges are approximated. The +target format may further approximate or omit geometry: CSV writes representative points and GPX +does not retain polygon areas, with their own format-specific notes. Commands use the same editing and undo paths. The follow-up examples assume `edit.addBox` returned `{"row":0,...}`; replace `0` with the returned row when the layer already has features. @@ -404,13 +403,13 @@ edit.deleteBox={"layer":"Training polygons","row":0} ``` `attributes` names must already exist in the layer. `edit.updateBox` and `edit.deleteBox` also -accept `featureId` to refuse a stale row. `edit.boxInfo` returns the current construction; -updates keep its frame when `box.frame` is omitted, and preserve the feature's identity/attributes. +accept `featureId` to refuse a stale row. `edit.boxInfo` returns the current construction; updates +keep its frame when `box.frame` is omitted, and preserve the feature's identity/attributes. `edit.updateBox` changes only the shape and rejects an `attributes` parameter; use `edit.setValue` -to change attribute values. -An optional `box.frame` holds `epsg`, original `width`/`height` and the full GDAL-order `affine` array. Only recognised EPSG -frames with supported datum transformations are accepted. These parameters are command input, -not GeoJSON properties or a new saved-file representation. +to change attribute values. An optional `box.frame` holds `epsg`, original `width`/`height` and the +full GDAL-order `affine` array. Only recognised EPSG frames with supported datum transformations are +accepted. These parameters are command input, not GeoJSON properties or a new saved-file +representation. ### Circles @@ -418,8 +417,8 @@ On a loaded polygon layer, turn **Edit › Edit** on and choose **Edit › Featu This creates ordinary feature polygons, independently of the annotation workflow or graphics. The existing **Editing** pane opens with centre X/Y, radius and polygon tolerance controls. -- Drag from the centre to the edge to create a circle. Drag inside an existing circle to select and move - it, or drag its round radius handle to resize with the centre fixed. +- Drag from the centre to the edge to create a circle. Drag inside an existing circle to select and + move it, or drag its round radius handle to resize with the centre fixed. - Click to select, ++alt++-click to cycle overlaps, ++shift++-click to extend the selection. ++ctrl++/++cmd++-drag forces a new circle over existing features. - Hold ++space++ and drag, or middle-drag, to pan; releasing ++space++ keeps Circle active. @@ -427,21 +426,21 @@ The existing **Editing** pane opens with centre X/Y, radius and polygon toleranc - Each completed gesture is one undo step. ++esc++ cancels the preview before another press leaves the tool. Templates, ordinary attributes and edit rules work as for other features. -The interactive tool uses the same flat Earth view and frozen construction grids as Rotated -Box: the layer's own grid when it has one, else **Web Mercator grid metres, not ground -metres**; `edit.addCircle` without `circle.frame` uses Web Mercator grid metres, as before. Scripts may -supply `circle.frame` from an original GeoTIFF grid via `box_edit::Frame::from_grid`; centre, -radius and tolerance then use original image pixels, including rotated or skewed grids. -A pixel circle may look elliptical on the map. Geometry commands remain view-independent. -Antimeridian crossings, polar editing limits and unsupported transformations are refused. +The interactive tool uses the same flat Earth view and frozen construction grids as Rotated Box: the +layer's own grid when it has one, else **Web Mercator grid metres, not ground metres**; +`edit.addCircle` without `circle.frame` uses Web Mercator grid metres, as before. Scripts may supply +`circle.frame` from an original GeoTIFF grid via `box_edit::Frame::from_grid`; centre, radius and +tolerance then use original image pixels, including rotated or skewed grids. A pixel circle may look +elliptical on the map. Geometry commands remain view-independent. Antimeridian crossings, polar +editing limits and unsupported transformations are refused. The exact centre/radius are session-only. Geometry is regenerated with 32–2048 straight edges; -`tolerance` (command default **0.25 grid units**) bounds the local-circle sagitta **before projection**, -not error in geographic coordinates or ground distance. New mouse-drawn circles choose the -larger of 0.25 grid units and radius/10000; this value is shown in the pane and preserved by -moves and resizes. Requests needing more than 2048 edges -are refused; increase tolerance or reduce radius. Commands report the edge count and approximation. -Changing a radius does not repeatedly rescale old vertices. +`tolerance` (command default **0.25 grid units**) bounds the local-circle sagitta **before +projection**, not error in geographic coordinates or ground distance. New mouse-drawn circles choose +the larger of 0.25 grid units and radius/10000; this value is shown in the pane and preserved by +moves and resizes. Requests needing more than 2048 edges are refused; increase tolerance or reduce +radius. Commands report the edge count and approximation. Changing a radius does not repeatedly +rescale old vertices. Exported GeoJSON holds only ordinary polygons and feature properties. **Export Features** reports a counted circle-construction/approximation note, separately from any box or format @@ -490,12 +489,12 @@ rolls back the whole edit. A successful command is one undo step. As with `edit. same-position command still runs the rules and records an edit, even if `modified` is zero. Undo retains cumulative edit counts. Streamed layers require **Load All Features** first. -This moves coincident **vertices**, not every shared boundary. For a boundary stored as P–Q -on one polygon and P–R–Q on its neighbour, moving Q moves the two stored Q vertices but leaves -R in place. It does not remap intermediate vertices, insert missing ones or refuse the edit -because vertex densities differ; the two boundaries can separate. There is no tolerance or -nearby-coordinate matching. Use the `mustNotOverlap` and `mustNotHaveGaps` topology rules, then -**Edit › Manage Edits › Topology › Error Inspector (validate)** (`topology.validate`) to inspect a coverage. +This moves coincident **vertices**, not every shared boundary. For a boundary stored as P–Q on one +polygon and P–R–Q on its neighbour, moving Q moves the two stored Q vertices but leaves R in place. +It does not remap intermediate vertices, insert missing ones or refuse the edit because vertex +densities differ; the two boundaries can separate. There is no tolerance or nearby-coordinate +matching. Use the `mustNotOverlap` and `mustNotHaveGaps` topology rules, then **Edit › Manage Edits +› Topology › Error Inspector (validate)** (`topology.validate`) to inspect a coverage. ### Distance units in commands @@ -525,14 +524,14 @@ attribute edits, Calculate Field): ## Clipboard and pop-ups -Copy (++ctrl+c++) and Cut (++ctrl+x++) take selected features from one layer: the active layer -if it has a selection, otherwise the first layer with selected features. Paste (++ctrl+v++) -adds them to the layer selected in Layers, matching fields by name and converting values to the -destination field types; unmatched fields stay empty. Geometry types must match. A feature with a -place the destination layer's coordinate system can't hold is left out, and a notice counts them. -**Paste Special** adds them as a new layer instead. Copied features also go on the system clipboard as GeoJSON, so -they can be pasted into another RustGIS window or a text editor, and GeoJSON copied elsewhere -pastes into RustGIS. **Copy Path** copies the selected layer's data source path. +Copy (++ctrl+c++) and Cut (++ctrl+x++) take selected features from one layer: the active layer if it +has a selection, otherwise the first layer with selected features. Paste (++ctrl+v++) adds them to +the layer selected in Layers, matching fields by name and converting values to the destination field +types; unmatched fields stay empty. Geometry types must match. A feature with a place the +destination layer's coordinate system can't hold is left out, and a notice counts them. **Paste +Special** adds them as a new layer instead. Copied features also go on the system clipboard as +GeoJSON, so they can be pasted into another RustGIS window or a text editor, and GeoJSON copied +elsewhere pastes into RustGIS. **Copy Path** copies the selected layer's data source path. Whole-layer copying is separate: use **Copy Layer** or **Copy Group** and **Paste Layer** in the Layers pane's context menus to preserve symbology and other layer settings, including when @@ -566,41 +565,41 @@ such as `image_page_url` or `image_credit` stay links or text in the list. A picture from RustGIS's own asset server (`https://assets.rustgis.app/…`) is fetched as the pop-up opens. A picture from any other server isn't: the pop-up shows **Show Picture** and the server's name, and fetches nothing until you click it, because the request tells that server that someone -opened the data (see [Privacy](../privacy.md)). A spinner shows while a picture is fetched. PNG, JPEG, -WebP and GIF pictures of up to 4 MB and 2048 × 2048 pixels are shown (on every platform; any other -format, such as BMP or TIFF, shows "Picture unavailable: … pictures aren't supported"); the last 16 addresses' pictures are kept for the -session, so opening the pop-up again shows the picture without asking again; they are forgotten with -the web layers' cached tiles (signing out of ArcGIS, a login that ends, **Reload Web Layers**). When -one can't be shown, the pop-up says why ("Picture unavailable: …": the server's answer, a network -error, a server that stops sending it, not a picture, a picture format that isn't supported, too -large) and doesn't ask again; its address stays a link. A plain `http://` picture, or one on this -computer or the local network, is never fetched. In the web app the picture's server must allow it -to be read from another site (CORS); many photo sites do, some don't. It must also give the picture -at that address: the web app refuses a redirect, as it does for every download. +opened the data (see [Privacy](../privacy.md)). A spinner shows while a picture is fetched. PNG, +JPEG, WebP and GIF pictures of up to 4 MB and 2048 × 2048 pixels are shown (on every platform; any +other format, such as BMP or TIFF, shows "Picture unavailable: … pictures aren't supported"); the +last 16 addresses' pictures are kept for the session, so opening the pop-up again shows the picture +without asking again; they are forgotten with the web layers' cached tiles (signing out of ArcGIS, a +login that ends, **Reload Web Layers**). When one can't be shown, the pop-up says why ("Picture +unavailable: …": the server's answer, a network error, a server that stops sending it, not a +picture, a picture format that isn't supported, too large) and doesn't ask again; its address stays +a link. A plain `http://` picture, or one on this computer or the local network, is never fetched. +In the web app the picture's server must allow it to be read from another site (CORS); many photo +sites do, some don't. It must also give the picture at that address: the web app refuses a redirect, +as it does for every download. The topmost and visible modes also identify the features of vector tile layers under the click: PMTiles and MBTiles archives and vector tiles added as data (not catalog basemaps or MapLibre styles), beneath the map's own layers. Each shows its tile layer and source layer (`firenze › buildings`) and its attributes; tile features can't be selected or zoomed to. -They ask WMS layers too (WMS tile layers that are shown and, as far as their service's -capabilities say, queryable): RustGIS sends the service a standard GetFeatureInfo request for the -point (WMS 1.3.0 or 1.1.1, as in the layer's address), asking for GeoJSON when it offers it, else -GML, other XML, plain text or HTML. While it asks, the pop-up says "Asking the map service…". -When something else is under the click, it waits up to 4 seconds for every layer asked to answer, -then shows the features found and answered together, in drawing order; answers that come later -join it as they arrive. When nothing else is, it waits until an answer has features, and closes -once every layer asked has answered (or failed) without any. -When the service answers with an error in that format (swisstopo's MapServer can't write some of -its layers as GeoJSON, but answers them in GML), RustGIS asks again in the next format it offers, -and keeps asking that layer in it for the rest of the session. -Topmost asks only the highest WMS layer that can be asked at the point (one that covers it and is -queryable), and only when it is drawn over the feature found, or nothing was found; its features -then take that feature's place. A project doesn't save the request: a WMS layer from a project reads its service's -capabilities again on its first click (once for all the map's layers from that service), so until -then Topmost takes it as one that can be asked. -`identify` lists the requests in `featureInfo`, and `identify.featureInfo` reads an answer (or, on -the command line, asks the service and waits). +They ask WMS layers too (WMS tile layers that are shown and, as far as their service's capabilities +say, queryable): RustGIS sends the service a standard GetFeatureInfo request for the point (WMS +1.3.0 or 1.1.1, as in the layer's address), asking for GeoJSON when it offers it, else GML, other +XML, plain text or HTML. While it asks, the pop-up says "Asking the map service…". When something +else is under the click, it waits up to 4 seconds for every layer asked to answer, then shows the +features found and answered together, in drawing order; answers that come later join it as they +arrive. When nothing else is, it waits until an answer has features, and closes once every layer +asked has answered (or failed) without any. When the service answers with an error in that format +(swisstopo's MapServer can't write some of its layers as GeoJSON, but answers them in GML), RustGIS +asks again in the next format it offers, and keeps asking that layer in it for the rest of the +session. Topmost asks only the highest WMS layer that can be asked at the point (one that covers it +and is queryable), and only when it is drawn over the feature found, or nothing was found; its +features then take that feature's place. A project doesn't save the request: a WMS layer from a +project reads its service's capabilities again on its first click (once for all the map's layers +from that service), so until then Topmost takes it as one that can be asked. `identify` lists the +requests in `featureInfo`, and `identify.featureInfo` reads an answer (or, on the command line, asks +the service and waits). A tile layer's row in Layers can be clicked to select it, as a map layer's can (`map.selectTiles`; no map layer is active then, and clicking one ends it). With **Selected in Layers**, a click on @@ -622,17 +621,17 @@ space preserves the selection but offers no conversion target. Circle and Rotate clear the selection on empty space, ready to draw another shape. Drawing and measurement tools keep their current selection when opening the map menu. -1. Choose Circle or Rotated Box and a construction grid. The shape defaults to the active - Circle or Rotated Box tool when opening conversion; other tools default to Circle. The default is the layer's own grid when - it has one (as for drawing), else **Web Mercator grid metres**, not ground metres, also for - `edit.previewShapeConversion` without `frame` (`"frame": {"epsg": 3857}` asks for Web - Mercator there). Choose an open GeoTIFF to fit in its **original image pixels**, - preserving the source affine transform, including rotation and shear, rather than using a - display overview. Local GeoTIFFs and embedded/browser-uploaded GeoTIFFs are supported; remote - original grids must be downloaded and added first. An unreadable or unsupported source gives - an error, without falling back to a different grid. - The same [image source checks](#image-source-checks) apply. If asked to reload, use - **Reload Data** on the image, then retry **Preview Conversion** or **Convert Now**. +1. Choose Circle or Rotated Box and a construction grid. The shape defaults to the active Circle or + Rotated Box tool when opening conversion; other tools default to Circle. The default is the + layer's own grid when it has one (as for drawing), else **Web Mercator grid metres**, not ground + metres, also for `edit.previewShapeConversion` without `frame` (`"frame": {"epsg": 3857}` asks + for Web Mercator there). Choose an open GeoTIFF to fit in its **original image pixels**, + preserving the source affine transform, including rotation and shear, rather than using a display + overview. Local GeoTIFFs and embedded/browser-uploaded GeoTIFFs are supported; remote original + grids must be downloaded and added first. An unreadable or unsupported source gives an error, + without falling back to a different grid. The same [image source checks](#image-source-checks) + apply. If asked to reload, use **Reload Data** on the image, then retry **Preview Conversion** or + **Convert Now**. 2. For a quick conversion, click **Convert Now** to fit and apply using the chosen shape and grid, without a preview or another confirmation. Alternatively, click **Preview Conversion** to show an orange outline without changing the feature or undo history, review or adjust the @@ -678,10 +677,10 @@ edit.previewShapeConversion={"layer":"Annotations","row":0,"kind":"rotatedBox"," Pass that command's complete answer as `preview` to `edit.applyShapeConversion={"preview":…,"confirm":true}` in the **same live session**. Preview is -read-only and does not grant consent to Apply. Preview tokens cannot be reused after reopening -a project; saved workflows must obtain a fresh preview. Omit `image` to use Web Mercator, or supply `frame` -with the same EPSG, dimensions and affine fields accepted by `edit.addBox` (image and frame are -mutually exclusive). Preview may read a source file and therefore declares the Files permission. -Synchronous API callers must invoke fitting off their own UI thread. On the phone the commands -are usable through its existing command interface; the desktop-style right-click menu is not a -new touch-bar destination. +read-only and does not grant consent to Apply. Preview tokens cannot be reused after reopening a +project; saved workflows must obtain a fresh preview. Omit `image` and `frame` to use the layer's +own grid when it has one, else Web Mercator, or supply `frame` with the same EPSG, dimensions and +affine fields accepted by `edit.addBox` (image and frame are mutually exclusive). Preview may read a +source file and therefore declares the Files permission. Synchronous API callers must invoke fitting +off their own UI thread. On the phone the commands are usable through its existing command +interface; the desktop-style right-click menu is not a new touch-bar destination. diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index e11be7d63d..f2e40e3d07 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -130,14 +130,14 @@ Messages are collected even while the pane is closed. The newest entries appear command's messages sit under its name, what it worked on (a layer or table) and the UTC time of its latest message; a message no command said shows its own time and source (such as Network). -A message that reports lost data is laid out like a compiler's: its severity and -[loss code](loss-codes.md) (`Warning [changed.truncated] data changed`), the message, then -**What happened** and **What to do** for that code. Both are built into RustGIS, so -they read offline; **More in the guide** opens the code's entry. **Undo to before this** takes -the project back to before that command, and the changes after it, while Undo still reaches it. Expand **Technical +A message that reports lost data is laid out like a compiler's: its severity and [loss +code](loss-codes.md) (`Warning [changed.truncated] data changed`), the message, then **What +happened** and **What to do** for that code. Both are built into RustGIS, so they read offline; +**More in the guide** opens the code's entry. **Undo to before this** takes the project back to +before that command, and the changes after it, while Undo still reaches it. Expand **Technical details** for failed requests: their address, method, observed HTTP status and duration when -available. Native connection failures and timeouts are identified when the transport knows -them; an opaque browser failure does not claim a status or a specific DNS, CORS, or connection cause. +available. Native connection failures and timeouts are identified when the transport knows them; an +opaque browser failure does not claim a status or a specific DNS, CORS, or connection cause. Use **All**, **Errors**, **Warnings**, **Info**, **Network failures** or **Data losses** to filter the history (**Network failures** also lists the notes below about omitted absences). **Copy diagnostics** diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 24569aa917..25f8ce4998 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -62,7 +62,7 @@ A calculation gave no result for some rows, so the field was left empty there. T **Where you see it:** Calculate Field; Calculate Geometry Attributes; table statistics; Profile Along Selected Lines. -**What to do:** Correct the expression or check the input rows named in the notice. +**What to do:** Check the rows the notice names (or its expression, for a calculated field). ### `dropped.zm` { #dropped.zm }