From cdb1a33d8e6becf2fe95be17879a92c170526346 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 1 Dec 2026 09:18:33 -0300 Subject: [PATCH 1/2] fix(engine): imagery and raster workflow commands take a layer id (#3509 part 2) Commands that read `layer` as a raster's (or polygon layer's) name now read an id, or an id as text, as that layer's name: every command that goes through imagery::raster_name, raster.rasterize, raster.measure, raster.function(Chain), analysis.viewshed, analysis.lineOfSight and the suitability criteria. info.infographic refuses an unknown id given as text, as it does the number. Part of #3509. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/deeplearning.rs | 12 +++--- crates/engine/src/cmd/imagery.rs | 56 ++++++++++++------------ crates/engine/src/cmd/mod.rs | 11 +++++ crates/engine/src/cmd/workflows.rs | 32 +++++++------- crates/engine/src/cmd/workspace.rs | 3 +- crates/engine/src/tests/layer_ids.rs | 61 +++++++++++++++++++++++++++ 6 files changed, 124 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index 583533cb0e..d2d65c1d5c 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -70,9 +70,9 @@ pub fn commands() -> Vec { Ok(r) }).inputs(training_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_raster) - .params(r#"{"layer": raster, "training": polygon layer, "classField": field naming each polygon's class, "bands"?: [1-based], "hidden"?: [units per hidden layer] (default [32, 16]), "epochs"?: 1..500 (default 60), "model"?: name}"#), + .params(r#"{"layer": raster name|id, "training": polygon layer, "classField": field naming each polygon's class, "bands"?: [1-based], "hidden"?: [units per hidden layer] (default [32, 16]), "epochs"?: 1..500 (default 60), "model"?: name}"#), C::new("dl.classify", "Deep Learning Tools", "Imagery › Image Classification", classify).inputs(classify_inputs).roles(&[]).effects(crate::policy::Effects::NONE).when(need_raster).params( - r#"{"layer": raster, "model"?: a trained model's name, "training"?: polygon layer, "classField"?: field, "bands"?: [1-based], "hidden"?: [units], "epochs"?: 1..500 (without a model: train one first, as dl.train), "name"?: output, "ran"?: (internal: classes the app has worked out)}"#, + r#"{"layer": raster name|id, "model"?: a trained model's name, "training"?: polygon layer, "classField"?: field, "bands"?: [1-based], "hidden"?: [units], "epochs"?: 1..500 (without a model: train one first, as dl.train), "name"?: output, "ran"?: (internal: classes the app has worked out)}"#, ), C::new("dl.package", "Deep Learning Package", "Publish › Package", |s, p| { super::exports::file_command(s, "dl.package", p, |s, out| { @@ -120,7 +120,7 @@ pub fn commands() -> Vec { .when(need_model) .params(r#"{"model": name}"#), C::new("imagery.hostedImagery", "Create Hosted Imagery", "Imagery › Imagery Sharing", hosted).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().when(need_raster).params( - r#"{"layer": raster, "path": "*.zip" (z/x/y.png tiles, tiles.json and a viewer page), "minZoom"?: 0..22, "maxZoom"?: 0..22 (default: the raster's resolution)}"#, + r#"{"layer": raster name|id, "path": "*.zip" (z/x/y.png tiles, tiles.json and a viewer page), "minZoom"?: 0..22, "maxZoom"?: 0..22 (default: the raster's resolution)}"#, ), ] } @@ -448,7 +448,7 @@ pub fn hosted_bytes(s: &mut Session, p: &Value) -> Result<(Vec, Value), Stri /// its room. pub(super) fn hosted_within(s: &mut Session, p: &Value, out: super::exports::Output<'_>) -> Result<(Vec, Value), String> { let r = raster(s, p)?; - let lname = ps(p, "layer").unwrap_or_default().to_string(); + let lname = super::imagery::raster_name(s.map(), p)?.to_string(); let mut layer = s.map().layer_by_name(&lname).cloned().ok_or("no such layer")?; // Tiled even when hidden on the map. layer.visible = true; @@ -579,7 +579,7 @@ onwheel=e=>{{const nz=Math.max(minZ,Math.min(maxZ,z+(e.deltaY<0?1:-1)));if(nz!== /// Binds both raster and training polygons through their shared literal selectors. fn training_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; - super::Inputs::named(s.map(), [super::imagery::raster_name(p)?, super::imagery::training_name(p)?]) + super::Inputs::named(s.map(), [super::imagery::raster_name(s.map(), p)?, super::imagery::training_name(p)?]) } /// Follows classification's training-or-saved-model branch without copying trained weights. fn classify_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { @@ -587,7 +587,7 @@ fn classify_inputs(input: &super::InputContext<'_>, p: &Value) -> Result String { pub fn commands() -> Vec { vec![ C::new("raster.georeference", "Georeference", "Imagery › Alignment", georeference).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minX, minY, maxX, maxY] in degrees, or in crs when given, | "view" (the map view, in the map's own system on a flat map of the Earth, so the raster fills the view as drawn); not with transform, "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326; with transform only, not with an extent), "crs"?: the output's (default pointsCrs); with an extent of four numbers, their system and the result's, "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF); resampling, cellSize, name and path with transform only}"#, + r#"{"layer": raster name|id, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minX, minY, maxX, maxY] in degrees, or in crs when given, | "view" (the map view, in the map's own system on a flat map of the Earth, so the raster fills the view as drawn); not with transform, "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326; with transform only, not with an extent), "crs"?: the output's (default pointsCrs); with an extent of four numbers, their system and the result's, "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF); resampling, cellSize, name and path with transform only}"#, ), C::new("raster.project", "Project Raster", "Analyze › Raster", project_raster).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": raster name|id, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to, "ran"?: (internal: a raster the app has worked out)}"#, + r#"{"layer": polygon layer name|id (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to, "ran"?: (internal: a raster the app has worked out)}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( @@ -63,26 +63,26 @@ pub fn commands() -> Vec { .params(r#"{"before": raster, "after": raster, "band"?: 1-based, "method"?: "difference"|"ratio"|"percent", "name"?, "ran"?: (internal: a raster the app has worked out)}"#), C::new("raster.spectral", "Spectral Analysis", "Imagery › Image Analysis", spectral).inputs(spectral_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"layer": raster, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of the pixels in every part of its selected or first polygon)}"#), + .params(r#"{"layer": raster name|id, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of the pixels in every part of its selected or first polygon)}"#), C::new("raster.classify", "Classification Wizard", "Imagery › Image Classification", |s, p| { super::workflows::made_or_ran(s, p, "raster.classify") }).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": raster, "classes"?: 2..50, "bands"?: [1-based], "name"?: output, "ran"?: (internal: classes the app has worked out)}"#), + .params(r#"{"layer": raster name|id, "classes"?: 2..50, "bands"?: [1-based], "name"?: output, "ran"?: (internal: classes the app has worked out)}"#), C::new("raster.classifySupervised", "Classification Tools", "Imagery › Image Classification", supervised).inputs(supervised_inputs).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": raster, "training": polygon layer, "classField": field, "bands"?: [1-based], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), + .params(r#"{"layer": raster name|id, "training": polygon layer, "classField": field, "bands"?: [1-based], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), C::new("raster.index", "Indices", "Imagery › Imagery Tools", index).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": raster, "index": "ndvi"|"ndwi"|"savi"|"nbr"|"ndbi"|"evi", "red"?, "green"?, "blue"?, "nir"?, "swir"?: band numbers, "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, + r#"{"layer": raster name|id, "index": "ndvi"|"ndwi"|"savi"|"nbr"|"ndbi"|"evi", "red"?, "green"?, "blue"?, "nir"?, "swir"?: band numbers, "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("raster.process", "Process", "Analyze › Raster", process).inputs(process_inputs).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": raster, "operation": "clip"|"resample", "extent"?: [minLon, minLat, maxLon, maxLat] (clip; the view when omitted), "polygon"?: polygon layer (clip to its selected or all polygons; cells outside become no-data, or see-through in a raster with alpha or a three-band colour one without no-data), "selectedOnly"?: bool (clip to selected polygons when true, all when false), "factor"?: n (resample: n×n pixels become one), "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), + .params(r#"{"layer": raster name|id, "operation": "clip"|"resample", "extent"?: [minLon, minLat, maxLon, maxLat] (clip; the view when omitted), "polygon"?: polygon layer (clip to its selected or all polygons; cells outside become no-data, or see-through in a raster with alpha or a three-band colour one without no-data), "selectedOnly"?: bool (clip to selected polygons when true, all when false), "factor"?: n (resample: n×n pixels become one), "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), C::new("raster.mosaic", "Mosaic Rasters", "Analyze › Raster", raster_mosaic).inputs(mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( r#"{"inputs": [raster layer or file path, …] (two or more, in one coordinate system and cell size; where they overlap the first wins), "name"?: output, "path"?: GeoTIFF to write the mosaic to, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("raster.editPixels", "Pixel Editor", "Imagery › Imagery Tools", edit_pixels).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": raster, "polygon": [[lon, lat], …], "value"?: number (no-data when omitted), "band"?: 1-based (all when omitted)}"#), + .params(r#"{"layer": raster name|id, "polygon": [[lon, lat], …], "value"?: number (no-data when omitted), "band"?: 1-based (all when omitted)}"#), // Measurements are session results, not project changes: no undo step. C::new("raster.measure", "Mensuration Tools", "Imagery › Mensuration", measure).inputs(measure_inputs).roles(&[]).effects(crate::policy::Effects::NONE).view().params( - r#"{"layer"?: elevation raster, "kind": "distance"|"area"|"height"|"volume", "points": [[lon, lat], …], "base"?: metres (volume)}"#, + r#"{"layer"?: elevation raster name|id, "kind": "distance"|"area"|"height"|"volume", "points": [[lon, lat], …], "base"?: metres (volume)}"#, ), C::new("raster.measurements", "Results", "Imagery › Mensuration", |s, p| { if b(p, "clear").unwrap_or(false) { @@ -122,7 +122,7 @@ pub fn commands() -> Vec { C::new("imagery.mosaic", "Build Mosaic", "Imagery › Ortho Mapping", mosaic).inputs(workspace_mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": workspace, "ran"?: (internal: a raster the app has worked out)}"#), C::new("imagery.mesh", "Export Mesh", "Imagery › Reality Mapping", mesh).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"layer": elevation raster, "path"?: "*.obj" (the text is returned without one), "step"?: pixels between vertices}"#), + .params(r#"{"layer": elevation raster name|id, "path"?: "*.obj" (the text is returned without one), "step"?: pixels between vertices}"#), ] } @@ -133,13 +133,13 @@ fn raster_named(input: &impl super::InputSource, n: &str) -> Result, } pub(crate) fn raster(s: &Session, p: &Value) -> Result, String> { - raster_named(s, raster_name(p)?) + raster_named(s, raster_name(s.map(), p)?) } /// The raster layer `p` names, for a command that makes its raster in the background: a layer /// read in place from a file is read from it as the work runs ([`super::workflows::Input`]). pub(crate) fn input(s: &Session, p: &Value) -> Result { - super::workflows::Input::of(s, raster_name(p)?) + super::workflows::Input::of(s, raster_name(s.map(), p)?) } /// The output's name the parameters give, else `d`; one over 200 characters is refused (#1888). @@ -248,7 +248,7 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec>) /// Fits a north-up longitude/latitude grid to control points (least squares, separately in x /// and y), or stretches the raster over an extent. fn georeference(s: &mut Session, p: &Value) -> CmdResult { - let layer = ps(p, "layer").ok_or("layer is required")?.to_string(); + let layer = raster_name(s.map(), p)?.to_string(); let r = raster(s, p)?; if p.get("transform").is_some_and(|v| !v.is_null()) { // A transform fits control points: an extent given beside it would be passed over. @@ -577,7 +577,7 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { /// field's class table is added. pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result { super::exports::no_layer_file(s, p)?; - let ln = rasterize_name(p)?; + let ln = rasterize_name(s.map(), p)?; let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; let ds = &l.dataset; if ds.geometry_type != GeometryType::Polygon { @@ -2847,7 +2847,7 @@ fn pixel_window(r: &Raster, e: &Extent) -> Result<(std::ops::Range, std::op } fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { - let layer = ps(p, "layer").ok_or("layer is required")?.to_string(); + let layer = raster_name(s.map(), p)?.to_string(); let r = raster(s, p)?; r.require_coordinates()?; let ring: Vec = p @@ -2948,7 +2948,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { } let pts: Vec = given.iter().map(point).collect::>()?; let kind = ps(p, "kind").ok_or("kind is required")?; - let dem = ps(p, "layer").map(|n| raster_named(s, n)).transpose()?; + let dem = super::given_layer_name(s.map(), p, "layer")?.map(|n| raster_named(s, n)).transpose()?; // A scan's heights would be read at the made-up place it is laid. if let Some(d) = &dem { d.require_coordinates()?; @@ -3491,11 +3491,11 @@ fn write_surface(w: &mut dyn std::io::Write, r: &Raster, step: i64) -> Result<(u /// The literal raster/secondary inputs used by this module, without reading any pixels/files. fn raster_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; - super::Inputs::named(s.map(), [raster_name(p)?]) + super::Inputs::named(s.map(), [raster_name(s.map(), p)?]) } /// Measures distance and area without a raster, or binds the explicitly selected elevation raster. fn measure_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { - super::Inputs::named(input.map(), ps(p, "layer")) + super::Inputs::named(input.map(), super::given_layer_name(input.map(), p, "layer")?) } /// Binds both literal before/after rasters used by change detection. fn change_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { @@ -3505,31 +3505,31 @@ fn change_inputs(input: &super::InputContext<'_>, p: &Value) -> Result, p: &Value) -> Result { let s = input; - super::Inputs::named(s.map(), std::iter::once(raster_name(p)?).chain(spectral_zone(p))) + super::Inputs::named(s.map(), std::iter::once(raster_name(s.map(), p)?).chain(spectral_zone(p))) } /// Binds the primary raster and the actual training polygon selector. fn supervised_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; - super::Inputs::named(s.map(), [raster_name(p)?, training_name(p)?]) + super::Inputs::named(s.map(), [raster_name(s.map(), p)?, training_name(p)?]) } /// Binds a clip polygon only when the selected processing operation consumes one. fn process_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; let clip = clip_polygon(p); - super::Inputs::named(s.map(), std::iter::once(raster_name(p)?).chain(clip)) + super::Inputs::named(s.map(), std::iter::once(raster_name(s.map(), p)?).chain(clip)) } /// Binds the grid template when present, otherwise the optional extent layer. fn project_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; - super::Inputs::named(s.map(), std::iter::once(raster_name(p)?).chain(project_grid(p)?.or_else(|| project_extent_name(p)))) + super::Inputs::named(s.map(), std::iter::once(raster_name(s.map(), p)?).chain(project_grid(p)?.or_else(|| project_extent_name(p)))) } /// The rasterizer's literal vector selector, shared with pure dependency planning. -fn rasterize_name(p: &Value) -> Result<&str, String> { - ps(p, "layer").ok_or("layer is required: a polygon layer".into()) +fn rasterize_name<'a>(map: &'a rustgis_map::Map, p: &'a Value) -> Result<&'a str, String> { + super::given_layer_name(map, p, "layer")?.ok_or("layer is required: a polygon layer".into()) } /// Binds the exact vector selector and only the grid or extent the rasterizer consumes. fn rasterize_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { - let mut inputs = super::Inputs::named(input.map(), [rasterize_name(p)?])?; + let mut inputs = super::Inputs::named(input.map(), [rasterize_name(input.map(), p)?])?; if let Some(name) = project_grid(p)?.or_else(|| project_extent_name(p)) { inputs.extend(super::Inputs::named(input.map(), [name])?); } @@ -3562,8 +3562,8 @@ fn workspace_mosaic_inputs(input: &super::InputContext<'_>, p: &Value) -> Result } /// The literal primary raster selector shared by handlers and their pure input metadata. -pub(crate) fn raster_name(p: &Value) -> Result<&str, String> { - ps(p, "layer").ok_or("layer is required".into()) +pub(crate) fn raster_name<'a>(map: &'a rustgis_map::Map, p: &'a Value) -> Result<&'a str, String> { + super::given_layer_name(map, p, "layer")?.ok_or("layer is required".into()) } /// The literal training polygons used by imagery and deep learning. pub(crate) fn training_name(p: &Value) -> Result<&str, String> { diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index e2c6b2ccec..304ed2f31a 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -624,6 +624,17 @@ pub(crate) fn given_layer<'a>(map: &'a rustgis_map::Map, p: &Value, key: &str) - _ => return None, }) } +/// The name of the layer `p[key]` gives, for a command that looks a layer up by name: an id, or +/// an id as text, reads as that layer's name (#3509); other text is passed on as given. +pub(crate) fn given_layer_name<'a>(map: &'a rustgis_map::Map, p: &'a Value, key: &str) -> Result, String> { + match p.get(key) { + Some(Value::String(s)) if map.layer_by_name(s).is_none() => { + Ok(Some(s.parse::().ok().and_then(|id| map.layer(id)).map_or(s.as_str(), |l| l.name.as_str()))) + } + Some(Value::String(s)) => Ok(Some(s)), + _ => given_layer(map, p, key).transpose().map(|l| l.map(|l| l.name.as_str())), + } +} /// Only scalar choices a pure owner transition can model without running a handler. #[derive(Clone, Copy)] pub(crate) struct Selection { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 1f24557c94..ec04fb73e7 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -57,17 +57,17 @@ pub fn commands() -> Vec { C::new("script.run", "Run Script", "Analyze › Geoprocessing", run_script).roles(&[crate::ParamRole { key: "script", role: crate::Role::Script }]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Automation)) .params(r#"{"script": "one command per line: id {json}; # comments"}"#), C::new("raster.function", "Raster Functions", "Analyze › Raster", raster_function).inputs(function_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": raster, "function": "slope"|"aspect"|"hillshade"|"ndvi"|"bandMath"|"remap"|"threshold"|"resample", "units"?: "degrees"|"percent" (slope only; default degrees; percent is 100 × tan(angle in radians)), "band"?: 1-based, "expression"?: "(b4-b3)/(b4+b3)", "ranges"?: [[lo, hi, value]] (lo inclusive, hi exclusive; [21, 22, 1] maps integer class 21 to 1), "value"?: number, "keep"?: bool (remap: keep unmatched cells), "nir"?, "red"?: band numbers (ndvi; default 4 and 3), "azimuth"?, "altitude"?, "zFactor"?, "target"?: raster (resample onto its grid), "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, + r#"{"layer": raster name|id, "function": "slope"|"aspect"|"hillshade"|"ndvi"|"bandMath"|"remap"|"threshold"|"resample", "units"?: "degrees"|"percent" (slope only; default degrees; percent is 100 × tan(angle in radians)), "band"?: 1-based, "expression"?: "(b4-b3)/(b4+b3)", "ranges"?: [[lo, hi, value]] (lo inclusive, hi exclusive; [21, 22, 1] maps integer class 21 to 1), "value"?: number, "keep"?: bool (remap: keep unmatched cells), "nir"?, "red"?: band numbers (ndvi; default 4 and 3), "azimuth"?, "altitude"?, "zFactor"?, "target"?: raster (resample onto its grid), "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("raster.functionChain", "Function Editor", "Analyze › Raster", function_chain).inputs(chain_inputs).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": raster, "steps": [{"function", … (as raster.function; slope units: "degrees" (default) or "percent")}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), + .params(r#"{"layer": raster name|id, "steps": [{"function", … (as raster.function; slope units: "degrees" (default) or "percent")}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), C::new("analysis.suitability", "Suitability Modeler", "Analyze › Workflows", suitability).inputs(suitability_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"criteria": [{"layer": raster, "band"?: 1-based, "ranges": [[lo, hi, score]] (lo inclusive, hi exclusive; [21, 22, 1] scores integer class 21 as 1), "weight": number}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, + r#"{"criteria": [{"layer": raster name|id, "band"?: 1-based, "ranges": [[lo, hi, score]] (lo inclusive, hi exclusive; [21, 22, 1] scores integer class 21 as 1), "weight": number}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("analysis.viewshed", "Visibility Analysis", "Analyze › Workflows", viewshed).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, 0 to 10,000 (default 1.7), "radius"?: metres (default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), + .params(r#"{"layer": elevation raster name|id, "lon", "lat", "band"?: 1-based, "height"?: observer metres, 0 to 10,000 (default 1.7), "radius"?: metres (default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), C::new("analysis.lineOfSight", "Line Of Sight", "Analyze › Workflows", line_of_sight).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": elevation raster, "from": [lon, lat], "to": [lon, lat], "band"?: 1-based, "observerHeight"?: m, "targetHeight"?: m, "name"?: output}"#, + r#"{"layer": elevation raster name|id, "from": [lon, lat], "to": [lon, lat], "band"?: 1-based, "observerHeight"?: m, "targetHeight"?: m, "name"?: output}"#, ), C::new("analysis.interpolate", "Geostatistical Wizard", "Analyze › Workflows", interpolate).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": points, "field": numeric field, "crs"?: projected coordinate system ("EPSG:32616") to make it in (default the environment's, else the layer's projected system, else degrees; "EPSG:4326" for degrees), "cellSize"?: in degrees, or in the units of the crs, "power"?: 2, "neighbors"?: 12, "name"?: output, "ran"?: (internal: a surface the app has worked out)}"#, @@ -1787,7 +1787,7 @@ fn raster_function(s: &mut Session, p: &Value) -> CmdResult { /// What a raster function reads of the session, and the work that applies it. fn function_work(s: &Session, p: &Value) -> Result { - let src = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; + let src = raster_of(s, super::imagery::raster_name(s.map(), p)?)?; let target = resample_target(s, p)?; let name = out_name(p, format!("{}_{}", src.held().name, ps(p, "function").unwrap_or("")))?; let defaults = s.raster_defaults.clone(); @@ -1969,7 +1969,7 @@ fn function_chain(s: &mut Session, p: &Value) -> CmdResult { /// What a chain of raster functions reads of the session (its raster, and each resample's /// target), and the work that applies them. fn function_chain_work(s: &Session, p: &Value) -> Result { - let src = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; + let src = raster_of(s, super::imagery::raster_name(s.map(), p)?)?; let mut steps = p.get("steps").and_then(Value::as_array).ok_or("steps is required")?.clone(); if steps.is_empty() || steps.len() > 20 { return Err("give 1 to 20 steps".into()); @@ -2073,10 +2073,10 @@ fn suitability_work(s: &Session, p: &Value) -> Result { if crit.is_empty() || crit.len() > 20 { return Err("give 1 to 20 criteria".into()); } - let first = raster_of(s, criterion_layer(crit.first().ok_or("give 1 to 20 criteria")?)?)?; + let first = raster_of(s, criterion_layer(s.map(), crit.first().ok_or("give 1 to 20 criteria")?)?)?; let mut criteria = Vec::new(); for c in crit { - let r = raster_of(s, criterion_layer(c)?)?; + let r = raster_of(s, criterion_layer(s.map(), c)?)?; let band = band_of(c, r.held())?; let ranges: Vec<(f64, f64, f64)> = c .get("ranges") @@ -2131,7 +2131,7 @@ fn viewshed(s: &mut Session, p: &Value) -> CmdResult { /// What a viewshed reads of the session, and the work that makes it. fn viewshed_work(s: &Session, p: &Value) -> Result { - let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; + let dem = raster_of(s, super::imagery::raster_name(s.map(), p)?)?; let at = Coord::new(f(p, "lon").ok_or("lon is required")?, f(p, "lat").ok_or("lat is required")?); let band = band_of(p, dem.held())?; // A radius given is checked here; the raster's own reach is taken as the work reads it. @@ -2236,7 +2236,7 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { /// split where it turns visible or hidden, with its profile. On the app's thread, so a layer read /// in place from a file is read from the overview it holds. fn line_of_sight(s: &mut Session, p: &Value) -> CmdResult { - let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?.held; + let dem = raster_of(s, super::imagery::raster_name(s.map(), p)?)?.held; let name = out_name(p, "Line of Sight".into())?; let (a, b2) = (point(p, "from")?, point(p, "to")?); let band = band_of(p, &dem)?; @@ -2965,20 +2965,20 @@ fn resample_target_name(p: &Value) -> Result, String> { /// Binds the actual primary raster and conditional resampling template. fn function_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; - super::Inputs::named(s.map(), [ps(p, "layer").ok_or("layer is required")?].into_iter().chain(resample_target_name(p)?)) + super::Inputs::named(s.map(), [super::imagery::raster_name(s.map(), p)?].into_iter().chain(resample_target_name(p)?)) } /// Collects each function's actual target choice in step order. fn chain_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let s = input; - let mut names = vec![ps(p, "layer").ok_or("layer is required")?]; + let mut names = vec![super::imagery::raster_name(s.map(), p)?]; for step in p.get("steps").and_then(Value::as_array).ok_or("steps is required")? { names.extend(resample_target_name(step)?); } super::Inputs::named(s.map(), names) } /// Parses the literal raster selector used by each suitability criterion. -fn criterion_layer(p: &Value) -> Result<&str, String> { - ps(p, "layer").ok_or_else(|| "each criterion names a raster layer".into()) +fn criterion_layer<'a>(map: &'a rustgis_map::Map, p: &'a Value) -> Result<&'a str, String> { + super::given_layer_name(map, p, "layer")?.ok_or_else(|| "each criterion names a raster layer".into()) } /// Binds the same ordered criterion raster names used by the suitability executor. fn suitability_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { @@ -2988,7 +2988,7 @@ fn suitability_inputs(input: &super::InputContext<'_>, p: &Value) -> Result, _>>()?; super::Inputs::named(s.map(), names) } diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 754c896f22..fc34b2fb04 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -715,8 +715,9 @@ pub fn diagnostics(s: &Session) -> Value { fn infographic(s: &mut Session, p: &Value) -> CmdResult { // A layer's id, or its id as text, reads as its name (#3509); a name the map lacks still - // gives no cards. + // gives no cards, but an id it lacks is refused. let only = match (super::given_layer(s.map(), p, "layer"), ps(p, "layer")) { + (Some(Err(_)), Some(name)) if name.parse::().is_ok() => return Err(format!("no layer with id {name}")), (Some(Err(_)), Some(name)) => Some(name.to_string()), (found, _) => found.transpose()?.map(|l| l.name.clone()), }; diff --git a/crates/engine/src/tests/layer_ids.rs b/crates/engine/src/tests/layer_ids.rs index 1ffb04de7e..ddd0135189 100644 --- a/crates/engine/src/tests/layer_ids.rs +++ b/crates/engine/src/tests/layer_ids.rs @@ -90,3 +90,64 @@ fn an_infographic_takes_its_layer_by_id_or_id_as_text() { // A name the map lacks still gives no cards. assert_eq!(s.run("info.infographic", &json!({"layer": "Nowhere"})).unwrap()["layers"], json!([])); } + +/// Part 2: the imagery and raster workflow commands that read `layer` as a raster's name. +const LINE: [[f64; 2]; 2] = [[10.0015, 45.0195], [10.0385, 45.0195]]; + +/// A file for `imagery.hostedImagery` to write its tiles to. +fn hosted_zip() -> String { + std::env::temp_dir().join(format!("rustgis-3509-{}.zip", std::process::id())).to_string_lossy().into_owned() +} + +#[test] +fn raster_commands_take_the_raster_id_layer_add_data_answered() { + let square = json!([[10.005, 45.005], [10.015, 45.005], [10.015, 45.015], [10.005, 45.015]]); + for (command, params) in [ + ("raster.function", json!({"function": "slope", "name": "out"})), + ("raster.functionChain", json!({"steps": [{"function": "slope"}], "name": "out"})), + ("analysis.lineOfSight", json!({"from": LINE[0], "to": LINE[1]})), + ("analysis.viewshed", json!({"lon": 10.02, "lat": 45.02, "name": "out"})), + ("raster.measure", json!({"kind": "distance", "points": LINE})), + ("imagery.mesh", json!({"step": 8})), + ("imagery.hostedImagery", json!({"path": hosted_zip(), "maxZoom": 8})), + ("raster.editPixels", json!({"polygon": square, "value": 1})), + ] { + let [named, by_id] = by_name_and_id(dem, &[], command, params); + assert_eq!(named, by_id, "{command}"); + } +} + +#[test] +fn polygons_rasterize_from_a_layer_given_by_id() { + let params = json!({"value": 1, "cellSize": 5, "crs": "EPSG:4326", "name": "out"}); + let [named, by_id] = by_name_and_id(countries, &[], "raster.rasterize", params); + assert_eq!(named, by_id); +} + +#[test] +fn a_suitability_criterion_takes_its_raster_by_id() { + let [named, by_id] = [false, true].map(|by_id| { + let (mut s, dem) = with_dem(); + let layer = if by_id { json!(dem) } else { json!(s.map().layer(dem).unwrap().name) }; + let criterion = json!({"layer": layer, "ranges": [[-1000, 100000, 1]], "weight": 1}); + s.run("analysis.suitability", &json!({"criteria": [criterion], "name": "suits"})).unwrap() + }); + assert_eq!(named, by_id); +} + +#[test] +fn an_unknown_raster_id_is_said_as_such() { + let (mut s, _) = with_dem(); + for (command, params) in [ + ("raster.function", json!({"layer": 9999, "function": "slope"})), + ("analysis.lineOfSight", json!({"layer": 9999, "from": LINE[0], "to": LINE[1]})), + ("raster.measure", json!({"layer": 9999, "kind": "distance", "points": LINE})), + ("imagery.mesh", json!({"layer": 9999})), + ("raster.rasterize", json!({"layer": 9999, "value": 1})), + ("analysis.suitability", json!({"criteria": [{"layer": 9999, "ranges": [[0, 1, 1]], "weight": 1}]})), + ("info.infographic", json!({"layer": "9999"})), + ] { + let error = s.run(command, ¶ms).unwrap_err(); + assert!(error.contains("no layer with id 9999"), "{command}: {error}"); + } +} From 667e686ef297af76b6e8746c6ef6a0d4f84484ac Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 1 Dec 2026 10:09:35 -0300 Subject: [PATCH 2/2] fix(engine): refuse a layer id whose name an earlier layer has (#3509 part 2) Commands that find their layer again by name (the imagery and raster workflow commands, layout.series, report.*) would act on the first of two layers of the same name when given the second one's id. Such an id is now refused, saying which name is shared. Part of #3509. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout/series.rs | 2 +- crates/engine/src/cmd/mod.rs | 14 ++++++-- crates/engine/src/cmd/report.rs | 8 ++--- crates/engine/src/tests/layer_ids.rs | 46 ++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/layout/series.rs b/crates/engine/src/cmd/layout/series.rs index f8ffe9b4a2..920375feeb 100644 --- a/crates/engine/src/cmd/layout/series.rs +++ b/crates/engine/src/cmd/layout/series.rs @@ -34,7 +34,7 @@ pub(in crate::cmd::layout) fn series(s: &mut Session, p: &Value) -> CmdResult { .ok_or_else(|| format!("no field '{fl}'"))?, None => layer.labels.default.field.clone(), }; - let layer = layer.name.clone(); + let layer = crate::cmd::own_name(m, layer)?.to_string(); let margin = f(p, "margin").unwrap_or(0.1).clamp(0.0, 5.0); if let Some(l) = s.project.layouts.get_mut(li) { l.series = Some(MapSeries { frame, layer, name_field, margin, page: 0 }); diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 304ed2f31a..f15f605d60 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -629,10 +629,20 @@ pub(crate) fn given_layer<'a>(map: &'a rustgis_map::Map, p: &Value, key: &str) - pub(crate) fn given_layer_name<'a>(map: &'a rustgis_map::Map, p: &'a Value, key: &str) -> Result, String> { match p.get(key) { Some(Value::String(s)) if map.layer_by_name(s).is_none() => { - Ok(Some(s.parse::().ok().and_then(|id| map.layer(id)).map_or(s.as_str(), |l| l.name.as_str()))) + s.parse::().ok().and_then(|id| map.layer(id)).map_or(Ok(Some(s.as_str())), |l| own_name(map, l).map(Some)) } Some(Value::String(s)) => Ok(Some(s)), - _ => given_layer(map, p, key).transpose().map(|l| l.map(|l| l.name.as_str())), + _ => given_layer(map, p, key).transpose()?.map(|l| own_name(map, l)).transpose(), + } +} +/// `layer`'s name, for a command that finds its layer again by name: refused when an earlier +/// layer of `map` has the same name, as the name would find that one instead (#3509). +pub(crate) fn own_name<'a>(map: &rustgis_map::Map, layer: &'a rustgis_map::Layer) -> Result<&'a str, String> { + match map.layer_by_name(&layer.name) { + Some(found) if found.id != layer.id => { + Err(format!("two layers are named '{}': rename one, or give a layer whose name is its own", layer.name)) + } + _ => Ok(&layer.name), } } /// Only scalar choices a pure owner transition can model without running a handler. diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index b1b38bb8e4..3aa1315bad 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1602,11 +1602,11 @@ pub(super) fn named_elsewhere(s: &Session, name: &str) -> bool { fn given_layer_map<'a>(input: &'a impl super::InputSource, p: &Value) -> Option> { let context = input.input_context(); let map = context.map(); + // A report finds its layer again by name: an id's layer must be the one its name finds. + let by_id = || super::given_layer(map, p, "layer").map(|l| l.and_then(|l| super::own_name(map, l).map(|_| (map, l)))); match p.get("layer")? { - Value::String(name) => { - find_layer_map(input, name).map(Ok).or_else(|| super::given_layer(map, p, "layer").map(|l| l.map(|l| (map, l)))) - } - Value::Number(_) => super::given_layer(map, p, "layer").map(|l| l.map(|l| (map, l))), + Value::String(name) => find_layer_map(input, name).map(Ok).or_else(by_id), + Value::Number(_) => by_id(), _ => None, } } diff --git a/crates/engine/src/tests/layer_ids.rs b/crates/engine/src/tests/layer_ids.rs index ddd0135189..9a8abf3217 100644 --- a/crates/engine/src/tests/layer_ids.rs +++ b/crates/engine/src/tests/layer_ids.rs @@ -151,3 +151,49 @@ fn an_unknown_raster_id_is_said_as_such() { assert!(error.contains("no layer with id 9999"), "{command}: {error}"); } } + +/// The sample world and dem with a second layer added, then renamed to `name`: the map then has +/// two layers of that name. Gives the session, the layer a name finds and the other one's id. +fn twice_named(name: &str, data: Value) -> (Session, u32, u32) { + let (mut s, _) = with_dem(); + let added = s.run("layer.addDataBytes", &data).unwrap(); + let id = added["layer"].as_u64().unwrap() as u32; + s.run("layer.rename", &json!({"layer": id, "name": name})).unwrap(); + let found = s.map().layer_by_name(name).unwrap().id; + let other = + s.map().layers.iter().map(|l| l.id).find(|i| *i != found && s.map().layer(*i).unwrap().name.eq_ignore_ascii_case(name)).unwrap(); + (s, found, other) +} + +#[test] +fn an_id_whose_name_another_layer_has_is_refused_where_the_name_is_looked_up() { + let (mut s, found, other) = twice_named("dem", json!({"fileName": "dem.tif", "data": dem_b64()})); + let square = json!([[10.005, 45.005], [10.015, 45.005], [10.015, 45.015], [10.005, 45.015]]); + for layer in [json!(other), json!(other.to_string())] { + let error = s.run("raster.editPixels", &json!({"layer": layer, "polygon": square, "value": 1})).unwrap_err(); + assert!(error.contains("two layers are named 'dem'"), "{error}"); + } + // The layer the name finds is the one the id gives. + s.run("raster.editPixels", &json!({"layer": found, "polygon": square, "value": 1})).unwrap(); +} + +#[test] +fn a_layout_series_and_a_report_refuse_an_id_whose_name_another_layer_has() { + use base64::Engine as _; + let square = json!([[[10.0, 45.0], [10.01, 45.0], [10.01, 45.01], [10.0, 45.01], [10.0, 45.0]]]); + let places = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"name": "a"}, "geometry": {"type": "Polygon", "coordinates": square}}, + ]}); + let data = base64::engine::general_purpose::STANDARD.encode(places.to_string()); + let (mut s, found, other) = twice_named("Countries", json!({"fileName": "places.geojson", "data": data})); + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + for (command, params) in [("layout.series", json!({"nameField": "name"})), ("report.new", json!({"name": "A", "fields": ["name"]}))] { + let mut by_other = params.clone(); + by_other["layer"] = json!(other); + let error = s.run(command, &by_other).unwrap_err(); + assert!(error.contains("two layers are named 'Countries'"), "{command}: {error}"); + let mut by_found = params; + by_found["layer"] = json!(found); + s.run(command, &by_found).unwrap(); + } +}