diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 6f55c6684a..e9ef743a27 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -2110,7 +2110,7 @@ fn item_output_within( (name.clone(), super::deeplearning::package_within(s, &json!({"model": name}), out)?) } "hostedImagery" => { - let name = ps(p, "layer").unwrap_or("tiles").to_string(); + let name = super::given_layer_name(s.map(), p, "layer")?.unwrap_or("tiles").to_string(); (format!("{name}_tiles"), super::deeplearning::hosted_within(s, p, out)?.0) } k if super::sharing::KINDS.iter().any(|x| x.0 == k) => { diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 0e6c6ead30..0bfe360240 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -244,7 +244,7 @@ pub fn commands() -> Vec { r##""length"?: mm (line, arrow), "##, r##""image"?: base64, "##, r##""path"?: picture file (picture: read, and remembered as its file, so a picture whose image goes missing names it and layout.update can read it again; an address is refused, and image and path together; refused in the browser, which has no file paths: give its image; refused for other kinds), "##, - r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists; profile: a raster layer held whole, not read in place, default the top one shown), "##, + r##""layer"?: name|id (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists; profile: a raster layer held whole, not read in place, default the top one shown), "##, r##""field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "##, r##""label"?: a field (chart: each bar's label when not grouped), "##, r##""group"?: a field (chart: a bar per value of this field, its statistic of field over that value's features; blank values make one "(blank)" bar; default none, a bar per feature), "##, @@ -384,7 +384,7 @@ pub fn commands() -> Vec { r##""extentNumbers"?: bool (map frame: numbers its extent indicators 1, 2, 3… in their order, each in its outline's colour at the outline's centre; none where that centre is off the frame or behind a globe's horizon, for an outline in a clear colour, or for a frame with no outline, one showing the whole globe; refused for other elements), "##, r##""border"?: {"color"?: "#RRGGBB"|"#RRGGBBAA", "width"?: points, 0 to 20, 0 for none} | null (map frame: the outline along its shape, default #303030 and 0.8, the keys not given keeping theirs; null gives the default back; refused for other elements), "##, r##""section"?: {"name": the section line it changes, "newName"?, "direction"?, "at"?, "color"?, "width"?, "dash"? ([] or null for solid), as in layout.addElement, the keys not given keeping theirs, "remove"?: true to remove it} (map frame; refused for other elements), "##, - r##""layer"?: (colorbar: "" for the top visible raster with a colour scale, not drawn by classes), "##, + r##""layer"?: name|id (colorbar: "" for the top visible raster with a colour scale, not drawn by classes), "##, r##""field"?, "##, r##""label"?, "##, r##""group"?, "##, diff --git a/crates/engine/src/cmd/layout/chart.rs b/crates/engine/src/cmd/layout/chart.rs index dc40013040..ed1266f19e 100644 --- a/crates/engine/src/cmd/layout/chart.rs +++ b/crates/engine/src/cmd/layout/chart.rs @@ -90,6 +90,15 @@ pub(in crate::cmd::layout) fn given_name<'a>(p: &'a Value, k: &str, names: &str) } } +/// The layer given as `layer` in `map`, by its name, its id or its id as text (#3509), when it's +/// given (and not null): an error when it's neither text nor a number. +pub(in crate::cmd::layout) fn given_layer_in<'a>(map: &'a rustgis_map::Map, p: &'a Value, names: &str) -> Result, String> { + match p.get("layer") { + Some(Value::String(_) | Value::Number(_)) => crate::cmd::given_layer_name(map, p, "layer"), + _ => given_name(p, "layer", names), + } +} + /// A choice given as `k` by name, when it's given (and not null): an error when it isn't one of /// `names`. pub(in crate::cmd::layout) fn given_choice(p: &Value, k: &str, from: fn(&str) -> Option, names: &str) -> Result, String> { diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index d46b0affa5..c32fbe562a 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -561,7 +561,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu } "colorbar" => { let frame = frame_of(l, p)?; - let named = given_name(p, "layer", "a raster layer's name")?; + let named = given_layer_in(frame_map(s, l, frame)?, p, "a raster layer's name")?; let layer = colorbar_layer(s, l, frame, named)?; let title = match given_name(p, "title", "text")? { Some(t) => crate::cmd::within("title", "a colorbar's title", t, 200)?, diff --git a/crates/engine/src/cmd/layout/inputs.rs b/crates/engine/src/cmd/layout/inputs.rs index 4005e82001..eae87f4a9a 100644 --- a/crates/engine/src/cmd/layout/inputs.rs +++ b/crates/engine/src/cmd/layout/inputs.rs @@ -16,13 +16,18 @@ pub(in crate::cmd::layout) fn frame_layer_name( _ => return Err("no such frame".into()), }; let m = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(&map)).ok_or_else(|| format!("no map '{map}'"))?; - let found = match given_name(p, "layer", "a feature layer's name")? { + let found = match given_layer_in(m, p, "a feature layer's name")? { Some(n) => m.layer_by_name(n), None => m.layers.iter().find(|l| !l.is_raster() && !l.graphics), }; found.map(|l| l.name.clone()).ok_or_else(|| "no such layer in the frame's map".to_string()) } +/// Whether `layer` names a layer: an id, or text that isn't empty. +fn gives_layer(p: &Value) -> bool { + p.get("layer").is_some_and(|v| v.is_number() || v.as_str().is_some_and(|n| !n.trim().is_empty())) +} + /// Resolves a frame's stored map literally; missing frame maps are errors here. pub(in crate::cmd::layout) fn frame_map<'a>( input: &'a impl crate::cmd::InputSource, @@ -119,7 +124,7 @@ pub(in crate::cmd::layout) fn element_inputs(input: &crate::cmd::InputContext<'_ let name = frame_layer_name(input, layout, frame, p)?; inputs.extend(crate::cmd::Inputs::named(map, [name.as_str()])?); } else if kind == "colorbar" { - if let Some(name) = colorbar_layer(input, layout, frame, ps(p, "layer"))? { + if let Some(name) = colorbar_layer(input, layout, frame, given_layer_in(map, p, "a raster layer's name")?)? { inputs.extend(crate::cmd::Inputs::named(map, [name.as_str()])?); } } else { @@ -231,13 +236,14 @@ pub(in crate::cmd::layout) fn update_inputs(input: &crate::cmd::InputContext<'_> } match l.element(id).map(|e| &e.kind) { Some(ElementKind::MapFrame { .. }) if ps(p, "map").is_some() => inputs.maps.push(added_frame_map(input, p)?.instance_id()), - Some(ElementKind::Colorbar { frame, .. }) if ps(p, "layer").is_some_and(|n| !n.trim().is_empty()) => { - if let Some(name) = colorbar_layer(input, l, *frame, ps(p, "layer"))? { + Some(ElementKind::Colorbar { frame, .. }) if gives_layer(p) => { + let named = given_layer_in(frame_map(input, l, *frame)?, p, "a raster layer's name")?; + if let Some(name) = colorbar_layer(input, l, *frame, named)? { inputs.extend(crate::cmd::Inputs::named(frame_map(input, l, *frame)?, [name.as_str()])?); } } // A profile's new raster (#2863 part 2). - Some(ElementKind::Profile(profile)) if ps(p, "layer").is_some_and(|n| !n.trim().is_empty()) => { + Some(ElementKind::Profile(profile)) if gives_layer(p) => { let map = frame_map(input, l, profile.frame)?; let name = added_profile_layer(map, p)?; inputs.extend(crate::cmd::Inputs::named(map, [name.as_str()])?); diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs index 4d6dfdb579..8ed67bdbb3 100644 --- a/crates/engine/src/cmd/layout/profile.rs +++ b/crates/engine/src/cmd/layout/profile.rs @@ -117,7 +117,7 @@ fn profile_params(s: &Session, l: &Layout, p: &Value, mut base: Profile) -> Resu } } } - if let Some(n) = given_name(p, "layer", "a raster layer's name")? { + if let Some(n) = given_layer_in(map, p, "a raster layer's name")? { base.layer = profile_layer(map, n)?; } if let Some(v) = given_num(p, "band", "a band number from 1")? { @@ -333,7 +333,7 @@ pub(in crate::cmd::layout) fn profiles_follow_section(l: &mut Layout, frame: u32 /// The raster layer `layout.addElement` reads for a profile, for its inputs: the one given, else the /// top one its frame's map shows that it can read. pub(in crate::cmd::layout) fn added_profile_layer(map: &Map, p: &Value) -> Result { - match given_name(p, "layer", "a raster layer's name")? { + match given_layer_in(map, p, "a raster layer's name")? { Some(n) => profile_layer(map, n), None => first_profile_layer(map), } diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 610b370882..2c8968922a 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -256,10 +256,15 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { let l = s.project.layouts.get(li).ok_or("no layout")?; match l.element(id).map(|e| &e.kind) { Some(ElementKind::Colorbar { frame, .. }) => { - let layer = match given_name(p, "layer", "a raster layer's name")? { - Some(n) if n.trim().is_empty() => Some(None), - Some(n) => Some(colorbar_layer(s, l, *frame, Some(n))?), + // The frame's map is read only for a layer given: a colorbar whose map is gone still + // takes its other changes, and empty sets it back to the map's default. + let layer = match p.get("layer").filter(|v| !v.is_null()) { None => None, + Some(Value::String(n)) if n.trim().is_empty() => Some(None), + Some(_) => { + let named = given_layer_in(frame_map(s, l, *frame)?, p, "a raster layer's name")?; + Some(colorbar_layer(s, l, *frame, named)?) + } }; Some((layer, orientation(p)?, tick_side(p)?, ticks(p)?)) } @@ -1101,8 +1106,8 @@ pub(in crate::cmd::layout) fn checked_update( let l = s.project.layouts.get(li).ok_or("no layout")?; let e = l.element(id).ok_or_else(|| format!("no element {id}"))?; let new_layer = match &e.kind { - ElementKind::Table { .. } | ElementKind::Chart { .. } => given_name(p, "layer", "a feature layer's name")?, - _ => None, + ElementKind::Table { .. } | ElementKind::Chart { .. } => p.get("layer").is_some_and(|v| !v.is_null()), + _ => false, }; let new_field = match &e.kind { ElementKind::Chart { .. } => given_name(p, "field", "a field's name")?, @@ -1112,13 +1117,14 @@ pub(in crate::cmd::layout) fn checked_update( let columns = matches!(e.kind, ElementKind::Table { .. }) && (gives(p, "fields") || gives(p, "sort")); match (&e.kind, new_layer, new_field) { (ElementKind::Table { frame, layer, .. } | ElementKind::Chart { frame, layer, .. }, nl, nf) - if nl.is_some() || nf.is_some() || columns => + if nl || nf.is_some() || columns => { let map = match l.element(*frame).map(|f| &f.kind) { Some(ElementKind::MapFrame { map, .. }) => map.clone(), _ => return Err("the element's map frame is gone".into()), }; let m = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(&map)).ok_or_else(|| format!("no map '{map}'"))?; + let nl = if nl { given_layer_in(m, p, "a feature layer's name")? } else { None }; let target = m .layer_by_name(nl.unwrap_or(layer)) .filter(|l| !l.is_raster()) diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index f15f605d60..23403bf02c 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -632,6 +632,7 @@ pub(crate) fn given_layer_name<'a>(map: &'a rustgis_map::Map, p: &'a Value, key: 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)), + Some(v) if !v.is_null() && !v.is_number() => Err(format!("{key} is a layer's name or id")), _ => given_layer(map, p, key).transpose()?.map(|l| own_name(map, l)).transpose(), } } diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 1a6f39cfc0..55e164fbcb 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -164,9 +164,12 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .view(), C::new("share.saveWebMap", "Save Web Map", "Publish › Manage", |s, p| update_item(s, p, "webMap", ps(p, "map"))).inputs(update_web_map_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).when(need_items).params(MANAGE), - C::new("share.replaceWebLayer", "Replace Web Layer", "Publish › Manage", |s, p| update_item(s, p, "webLayer", ps(p, "layer"))).inputs(update_layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("share.replaceWebLayer", "Replace Web Layer", "Publish › Manage", |s, p| { + let layer = super::given_layer_name(s.map(), p, "layer")?.map(str::to_string); + update_item(s, p, "webLayer", layer.as_deref()) + }).inputs(update_layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .when(need_items) - .params(r#"{"item"?: id|name (default: the last web layer), "layer"?: the layer replacing it (default: the one it was made from)}"#), + .params(r#"{"item"?: id|name (default: the last web layer), "layer"?: name|id of the layer replacing it (default: the one it was made from)}"#), C::new("share.dataStore", "Data Stores", "Publish › Manage", data_store).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"name"?, "path"?: folder, "remove"?: name (no parameters: list them)}"#), C::new("share.upload", "Upload File", "Publish › Manage", upload).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"path": file, "store"?: name (default: the first data store)}"#), C::new("share.saveWebScene", "Save Web Scene", "Publish › Manage", |s, p| update_item(s, p, "webScene", ps(p, "map"))).inputs(update_web_scene_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).when(need_items).params(MANAGE), @@ -1869,7 +1872,7 @@ fn update_web_scene_inputs(input: &super::InputContext<'_>, p: &Value) -> Result } /// Binds a managed feature layer even when the request omits its source. fn update_layer_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { - update_source_inputs(input, p, "webLayer", ps(p, "layer")) + update_source_inputs(input, p, "webLayer", super::given_layer_name(input.map(), p, "layer")?) } /// Binds the managed chart's stored relationship selection and saved path. fn update_links_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 52fd95e569..785ca73e4f 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -49,7 +49,7 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"mode": "none"|"distance", "distance"?: metres from the view's centre}"#), C::new("map.terrain", "Terrain", "View › Scene", terrain).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r##"{"layer"?: a DEM raster layer (heights in metres; without layer or tiles, and no terrain yet, the active layer when it is a raster) | "tiles"?: elevation tile URL with {z}/{x}/{y}, "encoding"?: "terrarium"|"mapbox" (tiles; default terrarium), "exaggeration"?: 0 to 20 (default 1, or the terrain's), "block"?: a block diagram {"extent"?: "layer" (the DEM's extent, default) | [xmin, ymin, xmax, ymax] in map units (needed over tiles), "depth"?: metres from the lowest ground to the base (default half the relief, at least 100), "walls"?: "#RRGGBB" (default #C8B89A) | {"color"?: "#RRGGBB" (default #C8B89A), "layer"?: a polygon layer that holds all its features (not one read a view at a time; it may be hidden): its symbology colours the walls where its polygons meet the block's edge, and the walls are color off its polygons, "top"?: a band along the walls' top, soil over rock {"layer": a polygon layer as the walls' layer: its solid fill where its polygons meet the block's edge (no band off them), "thickness": metres down from the ground before exaggeration (schematic) | {"field": a numeric field of the layer holding each polygon's metres (no band under one without a value over 0)}}, or false}, "shape"?: "box" (default) | "circle" (the largest circle in the box, its walls round it) | {"layer": a polygon layer, "where"?: sql (picks its polygons, as a definition query)} (the ground inside the polygons, each hole a well with its own walls and its floor at the base, the box round them: no extent), "radius"?: a circle's radius in map units (default: the largest in the box), "water"?: the terrain's water shown in the walls' section {"depth"?: metres from the level to the floor, "field"?: a numeric field of the water layer holding each one's depth, "bed"?: a raster layer of the bed's heights in metres on the DEM's datum (the floor where it has data, never above the level; elsewhere the field's depth or the depth)} (one of them needed), or false}, keys left out stay as the block had them and null puts one back to its default (a new block takes the defaults), and the block's "water" is given whole each time, replacing the old, or false to take it off (default: as it was), "water"?: water bodies drawn flat at their level {"layer": a polygon layer, "level"?: a numeric field of levels in metres (default: each polygon's lowest height along its shore), "glint"?: 0 to 1, how brightly a tilted view's water shines where it reflects the sun toward the eye (default 0.3; 0: none), "shore"?: 0 to 1, how dark the band along the water's shore is at the outline, fading a few pixels inside it (default 0.35; 0: none)}, or false to take it off (default: as it was), "off"?: true}"##, + r##"{"layer"?: a DEM raster layer name|id (heights in metres; without layer or tiles, and no terrain yet, the active layer when it is a raster) | "tiles"?: elevation tile URL with {z}/{x}/{y}, "encoding"?: "terrarium"|"mapbox" (tiles; default terrarium), "exaggeration"?: 0 to 20 (default 1, or the terrain's), "block"?: a block diagram {"extent"?: "layer" (the DEM's extent, default) | [xmin, ymin, xmax, ymax] in map units (needed over tiles), "depth"?: metres from the lowest ground to the base (default half the relief, at least 100), "walls"?: "#RRGGBB" (default #C8B89A) | {"color"?: "#RRGGBB" (default #C8B89A), "layer"?: a polygon layer that holds all its features (not one read a view at a time; it may be hidden): its symbology colours the walls where its polygons meet the block's edge, and the walls are color off its polygons, "top"?: a band along the walls' top, soil over rock {"layer": a polygon layer as the walls' layer: its solid fill where its polygons meet the block's edge (no band off them), "thickness": metres down from the ground before exaggeration (schematic) | {"field": a numeric field of the layer holding each polygon's metres (no band under one without a value over 0)}}, or false}, "shape"?: "box" (default) | "circle" (the largest circle in the box, its walls round it) | {"layer": a polygon layer, "where"?: sql (picks its polygons, as a definition query)} (the ground inside the polygons, each hole a well with its own walls and its floor at the base, the box round them: no extent), "radius"?: a circle's radius in map units (default: the largest in the box), "water"?: the terrain's water shown in the walls' section {"depth"?: metres from the level to the floor, "field"?: a numeric field of the water layer holding each one's depth, "bed"?: a raster layer of the bed's heights in metres on the DEM's datum (the floor where it has data, never above the level; elsewhere the field's depth or the depth)} (one of them needed), or false}, keys left out stay as the block had them and null puts one back to its default (a new block takes the defaults), and the block's "water" is given whole each time, replacing the old, or false to take it off (default: as it was), "water"?: water bodies drawn flat at their level {"layer": a polygon layer, "level"?: a numeric field of levels in metres (default: each polygon's lowest height along its shore), "glint"?: 0 to 1, how brightly a tilted view's water shines where it reflects the sun toward the eye (default 0.3; 0: none), "shore"?: 0 to 1, how dark the band along the water's shore is at the outline, fading a few pixels inside it (default 0.35; 0: none)}, or false to take it off (default: as it was), "off"?: true}"##, ), C::new("map.exportOrbit", "Export Orbit", "View › Scene", |s, p| super::exports::write_here(s, p, "map.exportOrbit")).inputs(orbit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() @@ -653,7 +653,7 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { } None => None, }; - let source = match (ps(p, "layer"), ps(p, "tiles")) { + let source = match (super::given_layer_name(s.map(), p, "layer")?, ps(p, "tiles")) { (Some(_), Some(_)) => return Err("give a layer or tiles, not both".into()), (Some(name), None) => { let l = s.map().layer_by_name(name).ok_or_else(|| format!("no layer '{name}'"))?; diff --git a/crates/engine/src/tests/layer_ids.rs b/crates/engine/src/tests/layer_ids.rs index 9a8abf3217..4d8f2cd82c 100644 --- a/crates/engine/src/tests/layer_ids.rs +++ b/crates/engine/src/tests/layer_ids.rs @@ -24,10 +24,20 @@ fn by_name_and_id(pick: fn(&Session, u32) -> u32, setup: &[(&str, Value)], comma let mut p = params.clone(); p["layer"] = layer; let answer = s.run(command, &p).unwrap(); - json!({"answer": answer, "layouts": s.project.layouts, "reports": s.project.reports}) + json!({"answer": answer, "layouts": s.project.layouts, "reports": s.project.reports, "rasters": rasters(&s)}) }) } +/// Each raster layer's name, size, grid and the sum of its pixels: what a command that makes or +/// edits a raster changes. +fn rasters(s: &Session) -> Value { + let of = |r: &rustgis_data::raster::Raster| { + let sum: f64 = r.bands.iter().flat_map(|b| &b.data).filter(|v| v.is_finite()).map(|v| f64::from(*v)).sum(); + json!([r.width, r.height, format!("{:?}", r.transform), sum]) + }; + s.map().layers.iter().filter_map(|l| Some(json!([l.name, of(l.raster.as_ref()?.data.as_ref()?)]))).collect() +} + fn dem(_: &Session, dem: u32) -> u32 { dem } @@ -130,7 +140,8 @@ fn a_suitability_criterion_takes_its_raster_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() + let answer = s.run("analysis.suitability", &json!({"criteria": [criterion], "name": "suits"})).unwrap(); + json!([answer, rasters(&s)]) }); assert_eq!(named, by_id); } @@ -197,3 +208,125 @@ fn a_layout_series_and_a_report_refuse_an_id_whose_name_another_layer_has() { s.run(command, &by_found).unwrap(); } } + +/// Part 3: layout elements, terrain and shared items that read `layer` as a map layer's name. +fn layout() -> [(&'static str, Value); 1] { + [("layout.new", json!({"page": "a4", "template": "map"}))] +} + +#[test] +fn layout_elements_take_their_layer_by_id() { + for (pick, params) in [ + (countries as fn(&Session, u32) -> u32, json!({"kind": "table"})), + (countries, json!({"kind": "chart", "field": "pop_est"})), + (dem, json!({"kind": "colorbar"})), + ] { + let [named, by_id] = by_name_and_id(pick, &layout(), "layout.addElement", params.clone()); + assert_eq!(named, by_id, "{params}"); + } +} + +/// What `layout.update` leaves when it moves an added element to the layer `pick` gives, by +/// name and then by id. +fn updated_by_name_and_id(pick: fn(&Session, u32) -> u32, kind: &str) -> [Value; 2] { + [false, true].map(|by_id| { + let (mut s, dem) = with_dem(); + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + let element = s.run("layout.addElement", &json!({"kind": kind})).unwrap()["element"].clone(); + let id = pick(&s, dem); + let layer = if by_id { json!(id) } else { json!(s.map().layer(id).unwrap().name) }; + s.run("layout.update", &json!({"element": element, "layer": layer})).unwrap(); + json!(s.project.layouts) + }) +} + +fn cities(s: &Session, _: u32) -> u32 { + s.map().layer_by_name("Cities").unwrap().id +} + +#[test] +fn a_layout_update_moves_an_element_to_a_layer_given_by_id() { + for (pick, kind) in [(cities as fn(&Session, u32) -> u32, "table"), (cities, "chart"), (dem, "colorbar")] { + let [named, by_id] = updated_by_name_and_id(pick, kind); + assert_eq!(named, by_id, "{kind}"); + } +} + +#[test] +fn terrain_takes_its_elevation_raster_by_id() { + let [named, by_id] = by_name_and_id(dem, &[], "map.terrain", json!({})); + assert_eq!(named, by_id); + let (mut s, dem) = with_dem(); + let by_text = s.run("map.terrain", &json!({"layer": dem.to_string()})).unwrap(); + assert_eq!(by_text, named["answer"]); + let error = s.run("map.terrain", &json!({"layer": 9999})).unwrap_err(); + assert!(error.contains("no layer with id 9999"), "{error}"); +} + +#[test] +fn a_web_layer_is_replaced_from_a_layer_given_by_id() { + let zip = std::env::temp_dir().join(format!("rustgis-3509-web-{}.zip", std::process::id())).to_string_lossy().into_owned(); + let share = [("share.webLayer", json!({"layer": "Countries", "path": zip}))]; + let [named, by_id] = by_name_and_id(cities, &share, "share.replaceWebLayer", json!({})); + let _ = std::fs::remove_file(&zip); + assert_eq!(named, by_id); +} + +#[test] +fn hosted_tiles_are_named_after_a_raster_given_by_id() { + let (mut s, dem) = with_dem(); + let name = s.map().layer(dem).unwrap().name.clone(); + let (file, _) = crate::cmd::items::item_bytes(&mut s, "hostedImagery", &json!({"layer": dem, "maxZoom": 8})).unwrap(); + assert!(file.starts_with(&format!("{name}_tiles")), "{file}"); +} + +#[test] +fn a_layout_profile_takes_its_raster_by_id() { + let [named, by_id] = [false, true].map(|by_id| { + let (mut s, dem) = with_dem(); + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + let frame = s.project.layouts[0].first_frame().unwrap(); + s.run("layout.update", &json!({"element": frame, "center": [10.02, 45.02], "scale": 1e5})).unwrap(); + s.run("layout.addElement", &json!({"kind": "section", "at": [10.02, 45.02]})).unwrap(); + let layer = if by_id { json!(dem) } else { json!(s.map().layer(dem).unwrap().name) }; + let added = s.run("layout.addElement", &json!({"kind": "profile", "layer": layer})).unwrap(); + s.run("layout.update", &json!({"element": added["element"], "layer": layer})).unwrap(); + json!(s.project.layouts) + }); + assert_eq!(named, by_id); +} + +#[test] +fn a_colorbar_whose_map_is_gone_still_takes_changes_beside_its_layer() { + let (mut s, _) = with_dem(); + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + let bar = s.run("layout.addElement", &json!({"kind": "colorbar"})).unwrap()["element"].clone(); + let gone = s.map().name.clone(); + s.run("map.new", &json!({"name": "Other"})).unwrap(); + s.run("map.remove", &json!({"name": gone})).unwrap(); + s.run("layout.update", &json!({"element": bar, "title": "Height"})).unwrap(); + // An empty layer still sets it back to the map's default. + s.run("layout.update", &json!({"element": bar, "layer": ""})).unwrap(); +} + +#[test] +fn a_layer_that_is_neither_text_nor_a_number_is_refused() { + let (mut s, _) = with_dem(); + let zip = std::env::temp_dir().join(format!("rustgis-3509-kinds-{}.zip", std::process::id())).to_string_lossy().into_owned(); + s.run("share.webLayer", &json!({"layer": "Countries", "path": zip})).unwrap(); + for v in [json!(true), json!([]), json!({})] { + for command in ["map.terrain", "share.replaceWebLayer", "raster.measure"] { + let error = s.run(command, &json!({"layer": v, "kind": "distance", "points": LINE})).unwrap_err(); + assert!(error.contains("layer is a layer's name or id"), "{command} {v}: {error}"); + } + } + let _ = std::fs::remove_file(&zip); +} + +#[test] +fn terrain_refuses_an_id_whose_name_another_layer_has() { + // Terrain refuses a name two layers have on its own; the id is refused before it gets there. + let (mut s, _, other) = twice_named("dem", json!({"fileName": "dem.tif", "data": dem_b64()})); + let error = s.run("map.terrain", &json!({"layer": other})).unwrap_err(); + assert!(error.contains("two layers are named 'dem'"), "{error}"); +} diff --git a/crates/engine/src/tests/layout_typed_values.rs b/crates/engine/src/tests/layout_typed_values.rs index 07c5baadd6..460a6642cb 100644 --- a/crates/engine/src/tests/layout_typed_values.rs +++ b/crates/engine/src/tests/layout_typed_values.rs @@ -47,6 +47,12 @@ fn refused(s: &mut Session, command: &str, params: Value, said: &str) { assert_eq!(s.undo_label(), undo, "{params}"); } +/// What refusing `v` given as `key` says: a number given as `layer` is a layer's id (#3509), +/// and the map has no layer 17. +fn said_of(key: &str, v: &Value) -> String { + if key == "layer" && v.is_number() { "no layer with id 17".into() } else { format!("{key} is ") } +} + fn wrong() -> [Value; 4] { [json!(17), json!(true), json!([]), json!({})] } @@ -162,12 +168,13 @@ fn a_colorbar_or_legend_value_of_the_wrong_type_is_refused() { for (kind, element, key) in keys.into_iter().chain([("colorbar", bar, "title"), ("legend", legend, "title")]) { // A number is what ticks takes: text that isn't one stands in for it. let v = if key == "ticks" && v.is_number() { json!("many") } else { v.clone() }; + let said = said_of(key, &v); let mut add = json!({"kind": kind}); add[key] = v.clone(); - refused(&mut s, "layout.addElement", add, &format!("{key} is ")); + refused(&mut s, "layout.addElement", add, &said); let mut update = json!({"element": element}); update[key] = v.clone(); - refused(&mut s, "layout.update", update, &format!("{key} is ")); + refused(&mut s, "layout.update", update, &said); } } // The title beside it isn't changed either. @@ -243,12 +250,13 @@ fn a_table_or_chart_layer_field_or_rows_of_the_wrong_type_is_refused() { let bad = if key == "rows" { vec![json!(2.5), json!(-3), json!("many"), json!(true), json!([]), json!({})] } else { wrong().to_vec() }; for v in bad { + let said = said_of(key, &v); let mut add = json!({"kind": kind}); add[key] = v.clone(); - refused(&mut s, "layout.addElement", add, &format!("{key} is ")); + refused(&mut s, "layout.addElement", add, &said); let mut update = json!({"element": element}); update[key] = v; - refused(&mut s, "layout.update", update, &format!("{key} is ")); + refused(&mut s, "layout.update", update, &said); } } }