diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 74d1bc35bb..fc2c70b296 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -219,7 +219,7 @@ layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpa layer.addDatabase database password? layer? crs? name? stream? layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? layer.addEncodedPolyline polyline precision? name? -layer.addLayerFile path? text? data? +layer.addLayerFile path? text? data? group? to? layer.addPhotos paths? folder? name? layer.addSample name layer.addSql sql name? database? password? crs? stream? ran? diff --git a/crates/engine/src/cmd/group_file.rs b/crates/engine/src/cmd/group_file.rs new file mode 100644 index 0000000000..ba09afce79 --- /dev/null +++ b/crates/engine/src/cmd/group_file.rs @@ -0,0 +1,368 @@ +//! Layer files holding a group (#2870): the group, its subgroups and their layers, added back +//! whole by Add Layer File, Add Data and a drop, as Paste Layers places a copied group. +//! +//! The file has a layer file's header and lists in place of the one layer: +//! `{"format": 2, "requires": ["layer-group", …], "groups": [LayerGroup, …], "layers": [Layer, …]}`. +//! The layers are in drawing order (top first); a group's `children` are ids of `layers`, and a +//! subgroup's `parent` is one of `groups`. + +use std::collections::{HashMap, HashSet}; + +use rustgis_map::{Layer, LayerGroup, MAX_GROUP_DEPTH, MAX_GROUPS}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::layer_copy::{LayerClip, pasted_what}; +use crate::render::rustgis_tiles::address::Reach; +use crate::{CmdResult, Session}; + +/// The capability a layer file holding a group requires, so a release that reads only one layer +/// refuses it by that name. +pub(crate) const LAYER_GROUP: &str = "layer-group"; + +/// Only whether the file lists groups and requires [`LAYER_GROUP`], read without keeping them. +#[derive(Deserialize)] +struct Shape { + #[serde(default)] + groups: Option, + #[serde(default)] + requires: Vec, +} + +/// A layer file holding a group. +#[derive(Deserialize)] +struct GroupFile { + groups: Vec, + #[serde(default)] + layers: Vec, +} + +/// Whether `text`, a layer file, holds a group (lists `groups` and requires [`LAYER_GROUP`]) +/// rather than one layer. A map file lists its groups too, but never requires it. +pub(crate) fn holds_group(text: &str) -> bool { + !text.trim_start().starts_with('[') + && serde_json::from_str::(text).is_ok_and(|h| h.groups.is_some() && h.requires.iter().any(|r| r == LAYER_GROUP)) +} + +/// The layers of a group file, as Import Styles takes them, with what reading their labels and +/// pictures changed said. +pub(crate) fn layers_for_styles(s: &mut Session, text: &str) -> Result, String> { + let file = read(text)?; + for notice in crate::project::label_losses::group_file_notices(text, &file.layers, outermost(&file), false) { + s.notify(notice, false); + } + for notice in crate::project::picture_notices(&file.layers, []) { + s.notify_text(notice, false); + } + Ok(file.layers) +} + +/// Adds a layer file holding a group to the map in view, all of it or none: into `p`'s +/// `"group"`, or at its position `"to"` (the top by default), with the addresses it names held +/// within `reach` ([`Session::file_reach`]). +pub(crate) fn add_within(s: &mut Session, text: &str, reach: Reach, p: &Value) -> CmdResult { + crate::project::check_format(text, "layer file")?; + let mut file = read(text)?; + let label_notices = crate::project::label_losses::group_file_notices(text, &file.layers, outermost(&file), true); + let picture_notices = crate::project::picture_notices(&file.layers, []); + // A binding in a file is no authority to use a login here. + for l in &mut file.layers { + crate::s3_connections::clear_bindings(l.addresses_mut()); + crate::project::clear_login_bindings(l.addresses_mut()); + } + // Before anything they name is read (the repair after placing them reads it). + let named = crate::received::hold(file.layers.iter_mut().flat_map(Layer::addresses_mut), reach); + let what = format!("the layer file of '{}'", outermost(&file)); + let mi = s.project.active_map; + let placed = super::layer_copy::place(s, mi, LayerClip { layers: file.layers, groups: file.groups }, p)?; + for notice in label_notices { + s.notify(notice, false); + } + for notice in picture_notices { + s.notify_text(notice, false); + } + named.say(s, &what); + // Guides are followed along the map's layers, so they are audited where they went. + let guides = s.project.maps.get(mi).map(|m| crate::project::label_losses::added_guide_notices(m, &placed.layers)); + for notice in guides.unwrap_or_default() { + s.notify(notice, false); + } + s.notify(format!("Added {}", pasted_what(placed.layers.len(), placed.groups.len())), false); + placed.say(s, "Add Layer File"); + super::layer::settle_added(s, &placed.layers); + Ok(json!({"layers": placed.layers, "groups": placed.groups, "unmasked": placed.unmasked})) +} + +/// The group file in `text`, refused whole when it is damaged. +fn read(text: &str) -> Result { + let file: GroupFile = serde_json::from_str(text).map_err(|e| format!("not a RustGIS layer file: {e}"))?; + check(&file).map_err(|e| format!("the layer file is damaged: {e}"))?; + Ok(file) +} + +/// The name of the file's first outermost group, which notices name it by. +fn outermost(file: &GroupFile) -> &str { + file.groups.iter().find(|g| g.parent.is_none()).map_or("group", |g| g.name.as_str()) +} + +/// Refuses a group file whose groups and layers don't make a tree a map can hold: an id twice, a +/// group holding a layer the file lacks or one another group holds, a parent that's missing or +/// in a loop, more than [`MAX_GROUPS`] groups or more than [`MAX_GROUP_DEPTH`] levels. +fn check(file: &GroupFile) -> Result<(), String> { + if file.groups.len() > MAX_GROUPS { + return Err(format!("it holds {} groups, and a map holds at most {MAX_GROUPS}", file.groups.len())); + } + if file.groups.is_empty() && file.layers.is_empty() { + return Err("it holds no groups and no layers".into()); + } + let mut layers = HashSet::new(); + for l in &file.layers { + if !layers.insert(l.id) { + return Err(format!("two layers have the id {}", l.id)); + } + if l.dataset.source.as_deref().is_some_and(|source| source.starts_with("geolibre-pending:")) { + return Err("a layer file cannot contain runtime GeoLibre download reservations".into()); + } + } + let mut parents: HashMap> = HashMap::new(); + for g in &file.groups { + if parents.insert(g.id, g.parent).is_some() { + return Err(format!("two groups have the id {}", g.id)); + } + } + let mut held = HashSet::new(); + for g in &file.groups { + for c in &g.children { + if !layers.contains(c) { + return Err(format!("the group '{}' holds layer {c}, which isn't in the file", g.name)); + } + if !held.insert(*c) { + return Err(format!("layer {c} is in two groups")); + } + } + // Up to the top, each group once, at most MAX_GROUP_DEPTH levels. + let mut chain = vec![g.id]; + let mut up = g.parent; + while let Some(p) = up { + let Some(next) = parents.get(&p) else { + return Err(format!("the group '{}' is in group {p}, which isn't in the file", g.name)); + }; + if chain.contains(&p) { + return Err(format!("the group '{}' is inside itself", g.name)); + } + chain.push(p); + if chain.len() > MAX_GROUP_DEPTH { + return Err(format!("its groups nest more than {MAX_GROUP_DEPTH} levels deep")); + } + up = *next; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Project; + + /// The sample project, with Cities and Countries in a group Places, Countries in a subgroup + /// Borders, Cities masked by Countries. + fn sample() -> Session { + let mut s = Session::new(Project::default()); + s.run("project.sample", &Value::Null).unwrap(); + s.run("group.add", &json!({"name": "Places", "layers": ["Cities", "Countries"]})).unwrap(); + s.run("group.add", &json!({"name": "Borders", "layers": ["Countries"], "parent": "Places"})).unwrap(); + s.run("layer.mask", &json!({"layer": "Cities", "mask": "Countries"})).unwrap(); + s + } + + /// The group file of `s`'s groups and their layers, as part 2 will write it. + fn group_file(s: &Session) -> Value { + let m = s.map(); + let ids: Vec = m.groups.iter().flat_map(|g| g.children.iter().copied()).collect(); + let layers: Vec<&Layer> = m.layers.iter().filter(|l| ids.contains(&l.id)).collect(); + json!({"format": 2, "requires": [LAYER_GROUP], "groups": m.groups, "layers": layers}) + } + + fn names(s: &Session) -> Vec { + s.map().layers.iter().map(|l| l.name.clone()).collect() + } + + /// A group file comes back whole, nested as saved, at the top of the map, in one undo step; + /// names the map has get " copy", and the mask follows its layer. + #[test] + fn a_group_file_is_added_whole() { + let mut s = sample(); + let file = group_file(&s); + s.map_mut().groups.iter_mut().for_each(|g| { + g.transparency = 30.0; + g.expanded = false; + }); + let before = names(&s); + let r = s.run("layer.addLayerFile", &json!({"text": file.to_string()})).unwrap(); + assert_eq!((r["layers"].as_array().map(Vec::len), r["groups"].as_array().map(Vec::len)), (Some(2), Some(2))); + assert_eq!( + s.notices.iter().rev().find(|n| n.text.starts_with("Added")).map(|n| n.text.as_str()), + Some("Added 2 groups and 2 layers") + ); + let m = s.map(); + assert_eq!(names(&s)[..2], ["Cities copy", "Countries copy"]); + let cities = m.layer_by_name("Cities copy").unwrap(); + let countries = m.layer_by_name("Countries copy").unwrap(); + assert_eq!(cities.mask.as_deref(), Some("Countries copy")); + let places = m.group_of(cities.id).unwrap(); + let borders = m.group_of(countries.id).unwrap(); + assert_eq!((places.name.as_str(), borders.name.as_str(), borders.parent), ("Places copy", "Borders copy", Some(places.id))); + // As saved, not as the map's groups are now. + assert_eq!((places.transparency, places.expanded), (0.0, true)); + assert_eq!(s.active_layer, Some(cities.id)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!((names(&s), s.map().groups.len()), (before, 2)); + } + + /// Add Data and a drop (`layer.addData` on the path) read it too, and `"group"` places it + /// inside a group of the map. + #[test] + fn a_group_file_is_added_by_add_data_and_into_a_group() { + let mut s = sample(); + let path = std::env::temp_dir().join(format!("rustgis-2870-{}.rgislyr", std::process::id())); + std::fs::write(&path, group_file(&s).to_string()).unwrap(); + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("layer.addData", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!((names(&s), s.map().groups.len()), (vec!["Cities".to_string(), "Countries".into()], 2)); + s.run("group.add", &json!({"name": "Base"})).unwrap(); + let r = s.run("layer.addLayerFile", &json!({"path": path.to_string_lossy(), "group": "Base"})).unwrap(); + let m = s.map(); + let base = m.groups.iter().find(|g| g.name == "Base").unwrap().id; + let outer = r["groups"][0].as_u64().and_then(|g| m.group(u32::try_from(g).ok()?)).unwrap(); + assert_eq!((outer.name.as_str(), outer.parent), ("Places copy", Some(base))); + // A layer file of one layer takes no group or position. + let one = serde_json::to_string(m.layers.first().unwrap()).unwrap(); + let e = s.run("layer.addLayerFile", &json!({"text": one, "to": 0})).unwrap_err(); + assert!(e.contains("holds a group"), "{e}"); + std::fs::remove_file(&path).ok(); + } + + /// A damaged file, or one past the map's limits, adds none of its layers. + #[test] + fn a_damaged_group_file_adds_nothing() { + let mut s = sample(); + let file = group_file(&s); + let id = |v: &Value| v.as_u64().unwrap(); + let (places, borders) = (id(&file["groups"][0]["id"]), id(&file["groups"][1]["id"])); + let damage = |f: &dyn Fn(&mut Value)| { + let mut v = file.clone(); + f(&mut v); + v + }; + let cases = [ + (damage(&|v| v["groups"][0]["children"] = json!([999_999])), "isn't in the file"), + (damage(&|v| v["groups"][0]["children"] = v["groups"][1]["children"].clone()), "in two groups"), + (damage(&|v| v["groups"][0]["parent"] = json!(borders)), "inside itself"), + (damage(&|v| v["groups"][1]["parent"] = json!(999_999)), "isn't in the file"), + (damage(&|v| v["groups"][1]["id"] = json!(places)), "two groups"), + (damage(&|v| v["layers"][1]["id"] = v["layers"][0]["id"].clone()), "two layers"), + (json!({"format": 2, "requires": [LAYER_GROUP], "groups": [], "layers": []}), "no groups and no layers"), + (json!({"format": 2, "requires": [LAYER_GROUP, "a-later-thing"], "groups": []}), "a-later-thing"), + ]; + let mut cases = cases.to_vec(); + // Nine groups, each in the one before. + let deep: Vec = + (1..=9).map(|i| json!({"id": i, "name": format!("G{i}"), "parent": if i > 1 { json!(i - 1) } else { Value::Null }})).collect(); + cases.push((json!({"format": 2, "requires": [LAYER_GROUP], "groups": deep}), "levels deep")); + let before = (names(&s), s.map().groups.len()); + for (text, said) in cases { + let e = s.run("layer.addLayerFile", &json!({"text": text.to_string()})).unwrap_err(); + assert!(e.contains(said), "{said}: {e}"); + assert_eq!((names(&s), s.map().groups.len()), before); + } + // Into a group eight levels deep, with the file's two: past the levels. + for i in 0..6 { + let parent = if i == 0 { "Borders".to_string() } else { format!("L{i}") }; + s.run("group.add", &json!({"name": format!("L{}", i + 1), "parent": parent})).unwrap(); + } + let e = s.run("layer.addLayerFile", &json!({"text": file.to_string(), "group": "L6"})).unwrap_err(); + assert!(e.contains("levels deep"), "{e}"); + } + + /// A map file with a group is not a layer file: Add Layer File refuses it as before and the + /// map stays as it was, and Import Styles reads it as a map file. + #[test] + fn a_map_file_with_groups_is_not_a_group_file() { + let mut s = sample(); + let map = String::from_utf8(crate::project::map_file_bytes(s.map()).unwrap()).unwrap(); + let before = (names(&s), s.map().groups.len()); + assert!(s.run("layer.addLayerFile", &json!({"text": map})).is_err()); + assert_eq!((names(&s), s.map().groups.len()), before); + assert!(s.run("style.import", &json!({"text": map})).is_ok()); + } + + /// What reading a group file's labels changes is said, counted and named by its group, when + /// it is added and when its styles are imported; a clean file says nothing of it. + #[test] + fn a_group_file_says_what_reading_its_labels_changed() { + let mut s = sample(); + let clean = group_file(&s); + let mut lossy = clean.clone(); + lossy["layers"][0]["labels"]["weight"] = json!(99); + lossy["layers"][1]["labels"]["weight"] = json!(2.5); + let said = |s: &Session, from: usize| -> Vec { + s.notices[from..].iter().map(|n| n.text.clone()).filter(|t| t.contains("while opening the layer file")).collect() + }; + for command in ["layer.addLayerFile", "style.import"] { + let from = s.notices.len(); + s.run(command, &json!({"text": clean.to_string()})).unwrap(); + assert_eq!(said(&s, from), Vec::::new(), "{command}"); + let from = s.notices.len(); + s.run(command, &json!({"text": lossy.to_string()})).unwrap(); + assert_eq!( + said(&s, from), + ["Places: 2 label weight(s) not a whole number from 0 to 10 adjusted while opening the layer file"], + "{command}" + ); + } + } + + /// A label guide along a layer the map it goes to doesn't have is said, as for a map file; + /// one along a line layer it has, nothing. + #[test] + fn a_guide_the_map_lacks_is_said() { + let mut s = sample(); + let cities = s.map().layer_by_name("Cities").unwrap().id; + let guide = |s: &mut Session, along: &str| { + let along = rustgis_map::symbology::LabelGuide { layer: along.into(), field: None }; + s.map_mut().layer_mut(cities).unwrap().labels.default.guide = Some(along); + group_file(s).to_string() + }; + let said = |s: &Session, from: usize| -> Vec { + s.notices[from..].iter().map(|n| n.text.clone()).filter(|t| t.contains("label guide")).collect() + }; + let missing = guide(&mut s, "Rivers"); + s.run("map.new", &json!({"name": "Second"})).unwrap(); + let from = s.notices.len(); + s.run("layer.addLayerFile", &json!({"text": missing})).unwrap(); + assert_eq!(said(&s, from), ["1 label guide(s) along 'Rivers', not a line layer of the map, are placed as without it"]); + assert_eq!( + s.map().layer_by_name("Cities").unwrap().labels.default.guide.as_ref().map(|g| g.layer.as_str()), + Some("Rivers"), + "kept" + ); + // Along a line layer the map has, nothing is said. + let line = rustgis_data::Dataset::new("Rivers", rustgis_data::GeometryType::Polyline, Vec::new()); + s.map_mut().add_layer(Layer::new(0, line)); + let from = s.notices.len(); + s.run("layer.addLayerFile", &json!({"text": missing})).unwrap(); + assert_eq!(said(&s, from), Vec::::new()); + } + + /// Import Styles takes the styles of every feature layer in a group file. + #[test] + fn styles_are_imported_from_a_group_file() { + let mut s = sample(); + let file = group_file(&s); + let r = s.run("style.import", &json!({"text": file.to_string()})).unwrap(); + assert_eq!(r["imported"], json!(2)); + let styles: Vec<&str> = s.project.styles.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(styles, ["Cities", "Countries"]); + } +} diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 31af72ce57..ab89ed51a6 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -77,9 +77,16 @@ pub fn commands() -> Vec { C::new("layer.addLayerFile", "Add Layer File", "Home › Add", |s, p| { let text = read_text(p)?; let reach = s.file_reach(p); + // A file holding a group places it as Paste Layers does (#2870). + if super::group_file::holds_group(&text) { + return super::group_file::add_within(s, &text, reach, p); + } + if ["group", "to"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())) { + return Err("group and to place the layers of a layer file that holds a group; this one holds one layer".into()); + } super::layer::add_layer_text_within(s, &text, reach) }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) - .params(r#"{"path"?: "*.rgislyr", "text"?: layer file JSON, "data"?: base64 file}"#), + .params(r#"{"path"?: "*.rgislyr", "text"?: layer file JSON, "data"?: base64 file, "group"?: name|id (a file holding a group: into that group, at its top), "to"?: position (a file holding a group: 0 = top, the default)}"#), // Styles. C::new("style.new", "New Style", "Style › Styles", |s, p| { let id = s.layer_id(p)?; @@ -718,7 +725,9 @@ fn add_file_styles(s: &mut Session, what: &str, items: Vec) -> usize fn import_styles(s: &mut Session, p: &Value) -> CmdResult { let text = read_text(p)?; crate::project::check_format(&text, "layer file, map file or project")?; - let layers: Vec = if let Ok(l) = serde_json::from_str::(&text) { + let layers: Vec = if super::group_file::holds_group(&text) { + super::group_file::layers_for_styles(s, &text)? + } else if let Ok(l) = serde_json::from_str::(&text) { for notice in crate::project::label_losses::layer_notices(&text, &l, false) { s.notify(notice, false); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a670435610..d210730ff0 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -4737,6 +4737,9 @@ pub(crate) fn add_layer_text(s: &mut Session, text: &str) -> CmdResult { /// ([`Session::file_reach`]). pub(crate) fn add_layer_text_within(s: &mut Session, text: &str, reach: crate::render::rustgis_tiles::address::Reach) -> CmdResult { crate::project::check_format(text, "layer file")?; + if super::group_file::holds_group(text) { + return super::group_file::add_within(s, text, reach, &Value::Null); + } let mut layer: rustgis_map::Layer = serde_json::from_str(text).map_err(|e| format!("not a RustGIS layer file: {e}"))?; if layer.dataset.source.as_deref().is_some_and(|source| source.starts_with("geolibre-pending:")) { return Err("a layer file cannot contain runtime GeoLibre download reservations".into()); @@ -4761,6 +4764,14 @@ pub(crate) fn add_layer_text_within(s: &mut Session, text: &str, reach: crate::r layer.name = format!("{base} ({i})"); } let id = s.map_mut().add_layer(layer); + settle_added(s, &[id]); + s.active_layer = Some(id); + Ok(json!({"layer": id})) +} + +/// Settles layers `ids` just added to the map in view from a layer file: the project repaired +/// around them, the databases they read resolved, and what reading their rasters left out said. +pub(crate) fn settle_added(s: &mut Session, ids: &[u32]) { super::connections::clear_active(); for notice in s.project.normalize_text() { s.notify_text(notice, false); @@ -4768,24 +4779,24 @@ pub(crate) fn add_layer_text_within(s: &mut Session, text: &str, reach: crate::r super::connections::restore_active(s); s.wait_in_place_reads(); super::project::say_conversion_fallbacks(s); - // Only the database the added layer reads can change here. - let keys: Vec<_> = s.map().layer(id).and_then(|l| l.source.as_ref()).map(super::connections::layer_keys).unwrap_or_default(); + // Only the databases the added layers read can change here. + let m = s.map(); + let keys: Vec<_> = ids.iter().filter_map(|id| m.layer(*id)?.source.as_ref()).flat_map(super::connections::layer_keys).collect(); super::connections::resolve_keys(s, &keys); crate::s3_connections::resolve_project_s3(s); super::connections::note_waiting(s); - s.active_layer = Some(id); - // What reading its raster left out is said, as for a raster added (one still read in the + // What reading their rasters left out is said, as for a raster added (one still read in the // background isn't here yet). - let lost: Vec = s - .map() - .layer(id) - .and_then(|l| Some((&l.name, l.raster.as_ref()?.data.as_ref()?))) - .map(|(name, d)| d.lost.iter().map(|l| l.clone().prefixed(name)).collect()) - .unwrap_or_default(); + let m = s.map(); + let lost: Vec = ids + .iter() + .filter_map(|id| m.layer(*id)) + .filter_map(|l| Some((&l.name, l.raster.as_ref()?.data.as_ref()?))) + .flat_map(|(name, d)| d.lost.iter().map(|l| l.clone().prefixed(name))) + .collect(); for l in lost { s.say(l); } - Ok(json!({"layer": id})) } /// The most polylines added at once. diff --git a/crates/engine/src/cmd/layer_copy.rs b/crates/engine/src/cmd/layer_copy.rs index 701673ce62..68aa385570 100644 --- a/crates/engine/src/cmd/layer_copy.rs +++ b/crates/engine/src/cmd/layer_copy.rs @@ -101,7 +101,7 @@ fn unique_group_name(m: &Map, name: &str) -> (String, bool) { /// What a paste added, as its notice says it: "2 layers", "1 group and 3 layers", "1 group" (an /// empty group copied). -fn pasted_what(layers: usize, groups: usize) -> String { +pub(crate) fn pasted_what(layers: usize, groups: usize) -> String { let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; match (groups, layers) { (0, n) => count(n, "layer", "layers"), @@ -113,6 +113,47 @@ fn pasted_what(layers: usize, groups: usize) -> String { fn paste(s: &mut Session, p: &Value) -> CmdResult { let clip = s.layer_clipboard.clone().ok_or("no layers have been copied")?; let mi = super::navigate::map_at(s, p)?; + let placed = place(s, mi, clip, p)?; + // Said, as a paste from the Browser can go to a map out of view. + s.notify(format!("Pasted {} into {}", pasted_what(placed.layers.len(), placed.groups.len()), placed.map), false); + placed.say(s, "Paste Layers"); + Ok(json!({"map": placed.map, "layers": placed.layers, "groups": placed.groups, "unmasked": placed.unmasked})) +} + +/// What [`place`] added: to which map, the layers' ids in drawing order, the groups' ids +/// (outermost first), the layers whose masks were cleared, and how many names were cut. +pub(crate) struct Placed { + pub map: String, + pub layers: Vec, + pub groups: Vec, + pub unmasked: Vec, + names_cut: usize, +} + +impl Placed { + /// Says the names cut and the masks lost, after the notice of what was added (`what`: the + /// command). + pub(crate) fn say(&self, s: &mut Session, what: &str) { + let (map, names_cut) = (&self.map, self.names_cut); + if names_cut > 0 { + s.notify( + format!("{what}: {names_cut} copied name(s) cut so \" copy\" and a number fit in {} characters", super::MAX_NAME), + false, + ); + } + match self.unmasked.as_slice() { + [] => {} + [one] => s.notify(format!("{one} lost its mask: {map} has no polygon layer by that name"), false), + many => s.notify(format!("{} lost their masks: {map} has no polygon layers by those names", many.join(", ")), false), + } + } +} + +/// Places `clip`'s layers and groups in map `mi` as Paste Layers does (#2870 shares it): into +/// `p`'s `"group"` at its top, or at its position `"to"` (the top by default); a name the map +/// has gets " copy", and a mask follows its layer when that came too ([`Placed::say`] says +/// what that changed). +pub(crate) fn place(s: &mut Session, mi: usize, clip: LayerClip, p: &Value) -> Result { let m = s.project.maps.get(mi).ok_or("no such map")?; let into = match p.get("group") { None | Some(Value::Null) => None, @@ -213,20 +254,7 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult { { s.active_layer = Some(*first); } - // Said, as a paste from the Browser can go to a map out of view. - s.notify(format!("Pasted {} into {map}", pasted_what(pasted.len(), group_ids.len())), false); - if names_cut > 0 { - s.notify( - format!("Paste Layers: {names_cut} copied name(s) cut so \" copy\" and a number fit in {} characters", super::MAX_NAME), - false, - ); - } - match unmasked.as_slice() { - [] => {} - [one] => s.notify(format!("{one} lost its mask: {map} has no polygon layer by that name"), false), - many => s.notify(format!("{} lost their masks: {map} has no polygon layers by those names", many.join(", ")), false), - } - Ok(json!({"map": map, "layers": pasted, "groups": group_ids, "unmasked": unmasked})) + Ok(Placed { map, layers: pasted, groups: group_ids, unmasked, names_cut }) } /// Resolves explicit layer lists and expanded groups with copy's precise active-layer fallback. diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index d6f9f4a93d..e4a32eee91 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -27,6 +27,7 @@ pub mod gp; pub mod gpkg; pub mod graphics; pub mod group; +pub(crate) mod group_file; pub mod history; pub mod imagery; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 475b0d7080..f90a55baf6 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -95,6 +95,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-element-background", SIZE_BY_CAPABILITY, "picture-markers", + crate::cmd::group_file::LAYER_GROUP, "graticule-mgrs", "graticule-on-top", "graticule-color", diff --git a/crates/engine/src/project_label_losses.rs b/crates/engine/src/project_label_losses.rs index 0e74efa62c..90d35c4919 100644 --- a/crates/engine/src/project_label_losses.rs +++ b/crates/engine/src/project_label_losses.rs @@ -519,22 +519,25 @@ pub(crate) fn map_notices(text: &str, map: &rustgis_map::Map, diagrams: bool) -> /// (matched by place, not by value), or on a perpendicular label (square to its line where one is /// near). fn unfollowed_guides<'a>(maps: impl Iterator) -> Vec<(ReadPart, String)> { + unfollowed_guides_of(maps.flat_map(|m| m.layers.iter().map(move |l| (m, l)))) +} + +/// [`unfollowed_guides`] for the layers `labelled`, each with the map it is in. +fn unfollowed_guides_of<'a>(labelled: impl Iterator) -> Vec<(ReadPart, String)> { use rustgis_data::GeometryType; let (mut streamed, mut missing, mut fields, mut square) = (Vec::new(), Vec::new(), Vec::new(), 0usize); - for map in maps { - for labelled in &map.layers { - for (c, g) in labelled.labels.in_order().filter_map(|c| Some((c, c.guide.as_ref()?))) { - match map.layer_by_name(&g.layer) { - Some(l) if l.source.is_some() => streamed.push(&g.layer), - Some(l) if l.has_geometry(GeometryType::Polyline) => { - if let Some(f) = g.field.as_ref().filter(|f| [l, labelled].iter().any(|l| l.dataset.field_index(f).is_none())) { - fields.push(f); - } + for (map, labelled) in labelled { + for (c, g) in labelled.labels.in_order().filter_map(|c| Some((c, c.guide.as_ref()?))) { + match map.layer_by_name(&g.layer) { + Some(l) if l.source.is_some() => streamed.push(&g.layer), + Some(l) if l.has_geometry(GeometryType::Polyline) => { + if let Some(f) = g.field.as_ref().filter(|f| [l, labelled].iter().any(|l| l.dataset.field_index(f).is_none())) { + fields.push(f); } - _ => missing.push(&g.layer), } - square += usize::from(c.placement == rustgis_map::LabelPlacement::Perpendicular); + _ => missing.push(&g.layer), } + square += usize::from(c.placement == rustgis_map::LabelPlacement::Perpendicular); } } let named = |mut v: Vec<&String>| { @@ -568,6 +571,25 @@ fn unfollowed_guides<'a>(maps: impl Iterator) -> Ve notices.into_iter().map(|m| (ReadPart::Labels, m)).collect() } +/// What the label guides of the layers `ids`, just added to `map` from a layer file holding a +/// group (#2870), can't follow there, as a map file's are audited. +pub(crate) fn added_guide_notices(map: &rustgis_map::Map, ids: &[u32]) -> Vec { + let labelled = ids.iter().filter_map(|id| map.layer(*id)).map(|l| (map, l)); + unfollowed_guides_of(labelled).into_iter().map(|(_, m)| m).collect() +} + +/// The same audit for a layer file holding a group (#2870), whose `layers` are read as a map +/// file's are; `name` is the group's. +pub(crate) fn group_file_notices(text: &str, layers: &[rustgis_map::Layer], name: &str, diagrams: bool) -> Vec { + let Ok(raw) = serde_json::from_str::(text) else { return only(hidden(layers.iter()), diagrams) }; + let mut notices = count(raw.layers.iter(), layers.iter().map(|l| &l.labels), name, "the layer file"); + if diagrams { + notices.extend(refused_reference_scales(raw.layers.iter())); + } + notices.extend(hidden(layers.iter())); + only(notices, diagrams) +} + /// The same audit for a layer file read on its own. pub(crate) fn layer_notices(text: &str, layer: &rustgis_map::Layer, diagrams: bool) -> Vec { let Ok(raw) = serde_json::from_str::(text) else { return only(hidden(std::iter::once(layer)), diagrams) }; diff --git a/docs/maintaining.md b/docs/maintaining.md index 365d6f858f..118a9beb0f 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -141,6 +141,10 @@ an older reader must refuse them rather than fail on the marker or lose it. Wher is an SVG, they also require `svg-markers`: a reader of PNG and JPEG markers only would draw it as a circle and refuse the command that sets it. +A layer file holding a group (#2870) lists `groups` and `layers` in place of the one layer and +requires `layer-group`, so a reader of one layer refuses it by that name rather than as damaged. +Add Layer File, Add Data and a drop place it as Paste Layers places a copied group. + Projects, model files and web tools that save a percent-slope function require `slope-percent`: an older reader must refuse them rather than run the saved function in degrees. Project requirements also cover executable task steps, replayable history and notebook command cells. diff --git a/schema/project.schema.json b/schema/project.schema.json index 0632be1eb9..7c2cd0c728 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1256,6 +1256,7 @@ "layout-element-background", "classified-point-size", "picture-markers", + "layer-group", "graticule-mgrs", "graticule-on-top", "graticule-color", @@ -1385,6 +1386,7 @@ "layout-element-background", "classified-point-size", "picture-markers", + "layer-group", "graticule-mgrs", "graticule-on-top", "graticule-color",