diff --git a/crates/engine/src/cmd/group_file.rs b/crates/engine/src/cmd/group_file.rs index 89769f7fd6..b374413c7e 100644 --- a/crates/engine/src/cmd/group_file.rs +++ b/crates/engine/src/cmd/group_file.rs @@ -287,6 +287,27 @@ mod tests { assert_eq!((names(&s), s.map().groups.len()), (before, 2)); } + /// A file need not keep a group's layers together (a hand-edited one): its layers are added in + /// the file's order and each group's gathered (by Add Layer File's repair of the map, as when a + /// project opens), so the group's layers end up together (#3353). + #[test] + fn a_group_file_with_a_group_split_by_another_layer_adds_it_together() { + let mut s = sample(); + let mut file = group_file(&s); + let rivers = serde_json::to_value(s.map().layer_by_name("Rivers").unwrap()).unwrap(); + let layers = file["layers"].as_array().cloned().unwrap(); + assert_eq!(layers.len(), 2); + file["layers"] = json!([layers[0].clone(), rivers, layers[1].clone()]); + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("layer.addLayerFile", &json!({"text": file.to_string()})).unwrap(); + let m = s.map(); + let places = m.groups.iter().find(|g| g.name == "Places").map(|g| g.id).unwrap(); + let inside: Vec = + m.layers.iter().enumerate().filter(|(_, l)| m.group_layers(places).contains(&l.id)).map(|(i, _)| i).collect(); + assert_eq!(inside.len(), 2, "{:?}", names(&s)); + assert_eq!(inside.last().copied(), inside.first().map(|i| i + 1), "the group's layers stay together: {:?}", names(&s)); + } + /// Add Data and a drop (`layer.addData` on the path) read it too, and `"group"` places it /// inside a group of the map. #[test] diff --git a/crates/engine/src/cmd/layer_copy.rs b/crates/engine/src/cmd/layer_copy.rs index 4ee9a565f5..30581638c1 100644 --- a/crates/engine/src/cmd/layer_copy.rs +++ b/crates/engine/src/cmd/layer_copy.rs @@ -262,6 +262,13 @@ pub(crate) fn place(s: &mut Session, mi: usize, clip: LayerClip, p: &Value) -> R new_groups.insert(old, gid); group_ids.push(gid); } + // Adding a group gathers its layers before its subgroups exist, which can reorder them: the + // copied order is put back, then each group (outermost first) gathered again, as a clipboard or + // layer file that splits a group with another layer would leave it split. A no-op otherwise. + m.restore_order(&pasted); + for g in &group_ids { + m.gather_group(*g); + } let map = m.name.clone(); if mi == s.project.active_map && let Some(first) = pasted.first() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9ec6a43f0b..a7c15a37cd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47539,6 +47539,114 @@ fn a_copied_group_pastes_with_its_subgroups() { assert_eq!(m.group_layers(target).len(), 4); } +/// Pasting a group (or adding a group's layer file) keeps the drawing order when a subgroup sits +/// between the parent's own layers (#3353): adding the parent first gathered its layers before the +/// subgroup existed, dropping the subgroup's layers below the parent's later ones. +#[test] +fn a_pasted_group_keeps_its_layers_in_drawing_order_around_a_subgroup() { + let mut s = world(); + // The sample has four layers: a fifth, a copy of one, for the deeper arrangement. + let mut extra = s.map().layers[0].clone(); + extra.name = "Extra".into(); + extra.dataset.name = "Extra".into(); + s.map_mut().add_layer(extra); + let n: Vec = s.map().layers.iter().map(|l| l.name.clone()).take(5).collect(); + assert_eq!(n.len(), 5); + let names = |m: &rustgis_map::Map| m.layers.iter().map(|l| l.name.clone()).collect::>(); + let members = |m: &rustgis_map::Map, g: &str| -> Vec { + let id = m.groups.iter().find(|x| x.name == g).map(|x| x.id).unwrap(); + m.group_layers(id).iter().filter_map(|l| m.layer(*l)).map(|l| l.name.clone()).collect() + }; + let nested = |s: &mut Session| { + s.run("group.add", &json!({"name": "P", "layers": [&n[0], &n[1], &n[2], &n[3], &n[4]]})).unwrap(); + s.run("group.add", &json!({"name": "Q", "parent": "P", "layers": [&n[1], &n[2], &n[3]]})).unwrap(); + s.run("group.add", &json!({"name": "R", "parent": "Q", "layers": [&n[2]]})).unwrap(); + }; + // The issue's arrangement: P holds A, Q (with B) and C. + s.run("group.add", &json!({"name": "P", "layers": [&n[0], &n[1], &n[2]]})).unwrap(); + s.run("group.add", &json!({"name": "Q", "parent": "P", "layers": [&n[1]]})).unwrap(); + s.run("layer.copy", &json!({"group": "P"})).unwrap(); + s.run("map.new", &json!({"name": "Second"})).unwrap(); + let r = s.run("layer.paste", &Value::Null).unwrap(); + assert_eq!(names(s.map()), n[..3], "pasted in the copied order"); + assert_eq!(r["layers"].as_array().map(Vec::len), Some(3)); + let m = s.map(); + assert_eq!((m.groups.len(), members(m, "P")), (2, n[..3].to_vec())); + assert_eq!(members(m, "Q"), [n[1].clone()]); + // One undo step takes the paste back. + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.map().layers.is_empty()); + // A deeper arrangement: a subgroup inside the subgroup, between two layers of each level. + let mut s = world(); + let mut extra = s.map().layers[0].clone(); + extra.name = "Extra".into(); + extra.dataset.name = "Extra".into(); + s.map_mut().add_layer(extra); + nested(&mut s); + assert_eq!(names(s.map())[..5], n[..]); + s.run("layer.copy", &json!({"group": "P"})).unwrap(); + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("layer.paste", &Value::Null).unwrap(); + let m = s.map(); + assert_eq!(names(m), n[..]); + assert_eq!(members(m, "P"), n[..]); + assert_eq!(members(m, "Q"), n[1..4]); + assert_eq!(members(m, "R"), [n[2].clone()]); + // A group file added back, which places the same way. + let path = std::env::temp_dir().join(format!("rustgis-3353-{}.rgislyr", std::process::id())); + let at = path.to_string_lossy().to_string(); + s.run("map.activate", &json!({"name": s.project.maps[0].name.clone()})).unwrap(); + s.run("layer.save", &json!({"group": "P", "path": at})).unwrap(); + s.run("map.new", &json!({"name": "Third"})).unwrap(); + s.run("layer.addLayerFile", &json!({"path": at})).unwrap(); + let _ = std::fs::remove_file(&path); + let m = s.map(); + assert_eq!(names(m), n[..]); + assert_eq!((members(m, "Q"), members(m, "R")), (n[1..4].to_vec(), vec![n[2].clone()])); +} + +/// A layer pasted into a group that has layers of its own goes in at the group's top, above them; +/// a clipboard that holds a group's layers apart (only a hand-built one can) is gathered (#3353). +#[test] +fn a_paste_gathers_a_group_a_foreign_layer_splits_and_goes_in_at_the_top_of_a_group() { + let mut s = world(); + let m = s.map(); + let (a, x, b) = (m.layers[0].name.clone(), m.layers[1].name.clone(), m.layers[2].name.clone()); + let names = + |m: &rustgis_map::Map, ids: &[u32]| m.layers.iter().filter(|l| ids.contains(&l.id)).map(|l| l.name.clone()).collect::>(); + // Into a group with layers of its own: above them, in the order copied. + s.run("group.add", &json!({"name": "G", "layers": [&b]})).unwrap(); + s.run("layer.copy", &json!({"layer": [&a, &x]})).unwrap(); + s.run("layer.paste", &json!({"group": "G"})).unwrap(); + let m = s.map(); + let g = m.groups.iter().find(|g| g.name == "G").map(|g| g.id).unwrap(); + let inside = names(m, &m.group_layers(g)); + assert_eq!(inside, [format!("{a} copy"), format!("{x} copy"), b.clone()]); + // A clipboard with a group's layers apart: P holds the first and last, the middle one is its own. + let mut s = world(); + s.run("group.add", &json!({"name": "P", "layers": [&a, &b]})).unwrap(); + s.run("layer.copy", &json!({"group": "P", "layer": [&x]})).unwrap(); + if let Some(clip) = s.layer_clipboard.as_mut() { + let at = |clip: &crate::cmd::layer_copy::LayerClip, n: &str| clip.layers.iter().position(|l| l.name == n).unwrap(); + let (mid, last) = (at(clip, &x), at(clip, &b)); + clip.layers.swap(mid, last); + let order: Vec<&str> = clip.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(order, [a.as_str(), x.as_str(), b.as_str()]); + } + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("layer.paste", &Value::Null).unwrap(); + let m = s.map(); + let p = m.groups.iter().find(|g| g.name == "P").map(|g| g.id).unwrap(); + let spots: Vec = m.layers.iter().enumerate().filter(|(_, l)| m.group_layers(p).contains(&l.id)).map(|(i, _)| i).collect(); + assert_eq!(spots.len(), 2); + assert_eq!( + spots.last().copied(), + spots.first().map(|i| i + 1), + "P's layers stay together: {:?}", + m.layers.iter().map(|l| &l.name).collect::>() + ); +} + /// Large elevation models come as tiles in a projected coordinate system (#155): mosaic them on /// their own grid, clip by a polygon layer, share one stretch, and say when a raster is an overview. #[test] diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index da663228d6..588f60ac17 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -3206,6 +3206,34 @@ impl Map { self.settle_tiles(); } + /// Puts the layers `ids` back in this order, in the places they now take in the drawing + /// order, the other layers staying where they are (#3353). An id this map lacks is ignored, a + /// repeated one counts at its first place, and a layer not in `ids` is never moved. + pub fn restore_order(&mut self, ids: &[u32]) { + let mut rank: std::collections::HashMap = std::collections::HashMap::new(); + for (i, id) in ids.iter().enumerate() { + rank.entry(*id).or_insert(i); + } + let slots: Vec = self.layers.iter().enumerate().filter(|(_, l)| rank.contains_key(&l.id)).map(|(i, _)| i).collect(); + let rank_at = |layers: &[Layer], i: usize| layers.get(i).and_then(|l| rank.get(&l.id)).copied().unwrap_or(usize::MAX); + if slots.windows(2).all(|w| match w { + [a, b] => rank_at(&self.layers, *a) <= rank_at(&self.layers, *b), + _ => true, + }) { + return; + } + // Moving: the tile layers drawn over them keep their place. + self.release_tiles(ids); + // `slots` are ascending indices of layers that exist: taken out from the highest down they + // are all in range, and put back from the lowest up each is at most the length so far. + let mut run: Vec = slots.iter().rev().map(|i| self.layers.remove(*i)).collect(); + run.sort_by_key(|l| rank.get(&l.id).copied().unwrap_or(usize::MAX)); + for (slot, layer) in slots.into_iter().zip(run) { + self.layers.insert(slot, layer); + } + self.settle_tiles(); + } + /// Makes a project file's groups whole (#836): a parent that is the group itself, missing, /// in a loop or past [`MAX_GROUP_DEPTH`] levels is dropped (the group goes to the top /// level), and each group's layers are gathered together, the outermost groups first. @@ -4395,6 +4423,44 @@ mod tests { layer } + #[test] + fn restore_order_reorders_only_the_listed_layers_in_their_places() { + let mut m = Map::new("m"); + let ids: Vec = + ["a", "b", "c", "d", "e"].iter().map(|n| m.add_layer(Layer::new(0, Dataset::new(*n, GeometryType::Point, vec![])))).collect(); + let names = |m: &Map| m.layers.iter().map(|l| l.name.as_str()).collect::(); + let at = |n: &str| m.layers.iter().find(|l| l.name == n).map(|l| l.id).unwrap_or(0); + assert_eq!(names(&m), "edcba", "added on top"); + let (a, b, c, d, e) = (at("a"), at("b"), at("c"), at("d"), at("e")); + // The layers listed, in the places they take now (the first, third and last); d and b stay. + m.restore_order(&[a, c, e]); + assert_eq!(names(&m), "adcbe"); + // Already in order, nothing listed, ids the map lacks, a repeated id: nothing breaks. + for list in [vec![a, c, e], vec![], vec![999, 1000], vec![c, c, 999]] { + m.restore_order(&list); + assert_eq!(names(&m), "adcbe", "{list:?}"); + } + assert_eq!(m.layers.len(), ids.len()); + // A tile layer drawn over a layer that stays keeps it; one over a layer that moves is + // handed to the next one down that stays (as `release_tiles` does), so none is lost. + let url = "https://a.tile.example.com/{z}/{x}/{y}.png"; + let mut over_b = tiles::TileLayer::new("OverB", tiles::TileKind::Raster, url); + over_b.over = Some(b); + let mut over_a = tiles::TileLayer::new("OverA", tiles::TileKind::Raster, url); + over_a.over = Some(a); + m.tiles.extend([over_b, over_a]); + m.restore_order(&[e, c, a]); + assert_eq!(names(&m), "edcba"); + let over = |m: &Map, n: &str| m.tiles.iter().find(|t| t.name == n).map(|t| t.over); + assert_eq!( + (over(&m, "OverB"), over(&m, "OverA")), + (Some(Some(b)), Some(Some(d))), + "{:?}", + m.tiles.iter().map(|t| (&t.name, t.over)).collect::>() + ); + assert_eq!(m.tiles.len(), 2); + } + #[test] fn linked_source_schema_additions_reach_views_whole_reads_and_exports() { let mut layer = linked_schema_layer(&["rank"], &["rank", "download"]);