diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 594adb834d..59fbc614bc 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -269,7 +269,7 @@ layer.remove layer? layer.rename layer? name layer.repairSource layer? path table? layer.restoreFill layer? -layer.save layer? path +layer.save layer? group? path layer.scaleRange layer? min? max? layer.select layer? mode? layer.selectable layer? on? diff --git a/crates/engine/src/cmd/group_file.rs b/crates/engine/src/cmd/group_file.rs index ba09afce79..ec458cd1e9 100644 --- a/crates/engine/src/cmd/group_file.rs +++ b/crates/engine/src/cmd/group_file.rs @@ -1,5 +1,6 @@ -//! 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. +//! Layer files holding a group (#2870): the group, its subgroups and their layers, saved by +//! `layer.save` with `"group"` (the group's Save Group File…) and 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, …]}`. @@ -12,6 +13,7 @@ use rustgis_map::{Layer, LayerGroup, MAX_GROUP_DEPTH, MAX_GROUPS}; use serde::Deserialize; use serde_json::{Value, json}; +use super::exports::Output; use super::layer_copy::{LayerClip, pasted_what}; use crate::render::rustgis_tiles::address::Reach; use crate::{CmdResult, Session}; @@ -93,6 +95,65 @@ pub(crate) fn add_within(s: &mut Session, text: &str, reach: Reach, p: &Value) - Ok(json!({"layers": placed.layers, "groups": placed.groups, "unmasked": placed.unmasked})) } +/// Whether `layer.save` is given a group to save in place of a layer. +pub(crate) fn saves_group(p: &Value) -> bool { + p.get("group").is_some_and(|v| !v.is_null()) +} + +/// The groups `p` names with their subgroups, outermost first, and their layers in drawing +/// order, as Copy Group takes them: copied without their selection, the outermost groups at the +/// top level. +fn saved_group(s: &Session, p: &Value) -> Result<(Vec, Vec), String> { + if p.get("layer").is_some_and(|v| !v.is_null()) { + return Err("give a layer or a group to save, not both".into()); + } + // Copy Group takes the active layer when no group is named: a save names one. + if p.get("group").and_then(Value::as_array).is_some_and(Vec::is_empty) { + return Err("name the group to save".into()); + } + let (ids, mut groups) = super::layer_copy::copy_selection(s, &json!({"group": p["group"]}))?; + let m = s.map(); + let layers = ids + .iter() + .filter_map(|id| m.layer(*id)) + .map(|l| { + let mut l = l.clone(); + l.selection.clear(); + l.synced = None; + l + }) + .collect(); + let saved: HashSet = groups.iter().map(|g| g.id).collect(); + for g in &mut groups { + g.parent = g.parent.filter(|p| saved.contains(p)); + } + Ok((groups, layers)) +} + +/// What saving the group `p` names says of its layers under construction. +pub(crate) fn construction_notes(s: &Session, p: &Value) -> Result, String> { + let (_, layers) = saved_group(s, p)?; + let m = s.map(); + s.constructions.output_notes(layers.iter().filter_map(|l| m.layer(l.id)).map(|l| (m.instance_id(), l))) +} + +/// The layer file of the group `p` names, for the file `out` describes: its name (the outermost +/// group's), its bytes, and what it says of the layers left linked to files outside it. Local +/// rasters are embedded within one budget for the whole file, as a map file's are. +pub(crate) fn output_within(s: &mut Session, p: &Value, out: Output<'_>) -> Result<(String, Vec, Option), String> { + let (groups, layers) = saved_group(s, p)?; + if layers.iter().any(|l| l.dataset.source.as_deref().is_some_and(|source| source.starts_with("geolibre-pending:"))) { + return Err("a layer of the group is still downloading; wait for it to finish before saving".into()); + } + let mut budget = super::items::MAX_EMBED; + let layers: Vec = layers.into_iter().map(|l| super::items::embed_layer(l, &mut budget)).collect(); + let linked: Vec<&str> = layers.iter().filter(|l| l.linked_file().is_some()).map(|l| l.name.as_str()).collect(); + let linked = super::items::linked_said("Save Layer File", "the layer file", &linked); + let name = groups.first().map(|g| g.name.clone()).unwrap_or_default(); + let bytes = super::items::durable_bytes_with(s, layers, |layers| crate::project::group_file_within(&groups, layers, out))?; + Ok((name, bytes, linked)) +} + /// 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}"))?; @@ -355,6 +416,61 @@ mod tests { assert_eq!(said(&s, from), Vec::::new()); } + /// Save Group File writes the group, its subgroups and their layers, which add back whole; + /// a subgroup saved alone is at the top level of its file. + #[test] + fn a_saved_group_adds_back_whole() { + let mut s = sample(); + let path = std::env::temp_dir().join(format!("rustgis-2870-save-{}.rgislyr", std::process::id())); + let at = path.to_string_lossy().to_string(); + let read = |path: &std::path::Path| -> Value { serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() }; + let groups = |file: &Value| -> Vec<(String, bool)> { + file["groups"].as_array().unwrap().iter().map(|g| (g["name"].as_str().unwrap().to_string(), g["parent"].is_null())).collect() + }; + s.run("layer.save", &json!({"group": "Places", "path": at})).unwrap(); + let file = read(&path); + assert_eq!((file["format"].clone(), file["requires"][0].clone()), (json!(2), json!(LAYER_GROUP))); + assert_eq!(groups(&file), [("Places".to_string(), true), ("Borders".to_string(), false)]); + let layers: Vec<&str> = file["layers"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(layers, ["Cities", "Countries"]); + // Back in another map, as it was. + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("layer.addLayerFile", &json!({"path": at})).unwrap(); + assert_eq!(names(&s), ["Cities", "Countries"]); + let m = s.map(); + let borders = m.group_of(m.layer_by_name("Countries").unwrap().id).unwrap(); + let places = borders.parent.and_then(|p| m.group(p)).map(|g| g.name.as_str()); + assert_eq!((borders.name.as_str(), places), ("Borders", Some("Places"))); + assert_eq!(m.layer_by_name("Cities").unwrap().mask.as_deref(), Some("Countries")); + s.run("layer.save", &json!({"group": "Borders", "path": at})).unwrap(); + assert_eq!(groups(&read(&path)), [("Borders".to_string(), true)]); + std::fs::remove_file(&path).ok(); + for bad in [json!({"group": "Borders", "layer": "Cities", "path": at}), json!({"group": "Nowhere", "path": at})] { + assert!(s.run("layer.save", &bad).is_err(), "{bad}"); + } + assert!(!path.exists(), "nothing written when refused"); + } + + /// A group is saved with no layer active, as scripts call it; an empty list of groups is + /// refused, not taken for the active layer, and an empty group is saved. + #[test] + fn a_group_is_saved_without_an_active_layer_and_an_empty_list_is_refused() { + let mut s = sample(); + let path = std::env::temp_dir().join(format!("rustgis-2870-active-{}.rgislyr", std::process::id())); + let at = path.to_string_lossy().to_string(); + s.active_layer = None; + s.run("layer.save", &json!({"group": "Places", "path": at})).unwrap(); + std::fs::remove_file(&path).unwrap(); + s.active_layer = s.map().layers.first().map(|l| l.id); + assert!(s.run("layer.save", &json!({"group": [], "path": at})).is_err()); + assert!(!path.exists(), "nothing written"); + s.run("group.add", &json!({"name": "Empty"})).unwrap(); + s.run("layer.save", &json!({"group": "Empty", "path": at})).unwrap(); + let file: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!((file["groups"].as_array().map(Vec::len), file["layers"].clone()), (Some(1), json!([]))); + std::fs::remove_file(&path).ok(); + } + /// Import Styles takes the styles of every feature layer in a group file. #[test] fn styles_are_imported_from_a_group_file() { diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index ab89ed51a6..54ea061ad1 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -23,6 +23,12 @@ fn max_file() -> u64 { crate::project::max_bytes() } +/// Save Layer File saves the active layer, or a group (#2870) with none active: only a map with +/// neither has nothing to save. Saving a layer without one active is refused by its own step. +fn need_layer_or_group(s: &Session) -> Option<&'static str> { + if s.map().groups.is_empty() { need_layer(s) } else { None } +} + /// The most steps a task takes (`task.new`). const MAX_TASK_STEPS: usize = 200; @@ -72,8 +78,8 @@ pub fn commands() -> Vec { C::new("map.import", "Import", "Command Search", import_maps).roles(&[crate::ParamRole { key: "text", role: crate::Role::Document(crate::Document::Map) }]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"path": "*.rgismap|*.rgis|*.rgispkg" | "text": map file JSON | "data": base64 file}"#), C::new("layer.save", "Save Layer File", "Publish › Save As", |s, p| save_item(s, "layer.save", "layer", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .when(need_layer) - .params(r#"{"layer"?, "path": "*.rgislyr"}"#), + .when(need_layer_or_group) + .params(r#"{"layer"?, "group"?: name|id (the group with its subgroups and their layers, in place of a layer), "path": "*.rgislyr"}"#), C::new("layer.addLayerFile", "Add Layer File", "Home › Add", |s, p| { let text = read_text(p)?; let reach = s.file_reach(p); @@ -491,11 +497,11 @@ pub fn package_text(bytes: &[u8]) -> Result { /// Most raster bytes embedded in one map, layer or package file, all rasters together. They're /// base64'd into JSON (a third larger), which must stay within what packages can be read back /// with (`zip::MAX_TOTAL`). -const MAX_EMBED: u64 = rustgis_data::zip::MAX_TOTAL as u64 / 2; +pub(crate) const MAX_EMBED: u64 = rustgis_data::zip::MAX_TOTAL as u64 / 2; /// A raster layer with its file embedded (so the copy stands alone), within what's left of /// `budget`. A file that doesn't fit stays linked by its path. -fn embed_layer(mut l: Layer, budget: &mut u64) -> Layer { +pub(crate) fn embed_layer(mut l: Layer, budget: &mut u64) -> Layer { if let Some(rl) = &mut l.raster && rl.embedded.is_none() && let Some(path) = rl.path.clone() @@ -532,6 +538,12 @@ fn left_linked<'a>(what: &str, maps: impl IntoIterator) -> Optio layers.chain(m.tiles.iter().filter(|t| t.archive_file().is_some()).map(|t| t.name.as_str())) }) .collect(); + linked_said(what, "the package", &names) +} + +/// What [`left_linked`] says of the layers `names` left linked to files outside `holder` (the +/// package, or a layer file holding a group, #2870); `None` when there are none. +pub(crate) fn linked_said(what: &str, holder: &str, names: &[&str]) -> Option { if names.is_empty() { return None; } @@ -540,7 +552,7 @@ fn left_linked<'a>(what: &str, maps: impl IntoIterator) -> Optio listed.push_str(&format!(" and {} more", names.len() - MAX_LINKED_NAMED)); } Some(format!( - "{what}: {} layer(s) stay linked to files outside the package, so it opens without them on another computer: {listed}", + "{what}: {} layer(s) stay linked to files outside {holder}, so it opens without them on another computer: {listed}", names.len() )) } @@ -1950,6 +1962,7 @@ fn item_output_within( let m = saved_map(s, p)?; s.constructions.output_notes(m.layers.iter().map(|l| (m.instance_id(), l)))? } + "layer" if super::group_file::saves_group(p) => super::group_file::construction_notes(s, p)?, "layer" => { let id = s.layer_id(p)?; s.constructions.export_notes(s.map().instance_id(), s.map().layer(id).ok_or("no such layer")?)? @@ -1972,6 +1985,11 @@ fn item_output_within( let name = map.name.clone(); (name, durable_bytes_with(s, map, |map| crate::project::map_file_within(map, out))?) } + "layer" if super::group_file::saves_group(p) => { + let (name, bytes, linked) = super::group_file::output_within(s, p, out)?; + construction_notes.extend(linked); + (name, bytes) + } "layer" => { let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("no such layer")?.clone(); @@ -2100,7 +2118,7 @@ pub(crate) fn save_item(s: &mut Session, command: &str, kind: &str, p: &Value) - } /// Serializes an item through its document writer, after the same durable-field transaction. -fn durable_bytes_with( +pub(crate) fn durable_bytes_with( s: &mut Session, value: T, write: impl FnOnce(&T) -> Result, String>, diff --git a/crates/engine/src/cmd/layer_copy.rs b/crates/engine/src/cmd/layer_copy.rs index 68aa385570..e738f4b5c3 100644 --- a/crates/engine/src/cmd/layer_copy.rs +++ b/crates/engine/src/cmd/layer_copy.rs @@ -258,7 +258,7 @@ pub(crate) fn place(s: &mut Session, mi: usize, clip: LayerClip, p: &Value) -> R } /// Resolves explicit layer lists and expanded groups with copy's precise active-layer fallback. -fn copy_selection(input: &impl super::InputSource, p: &Value) -> Result<(Vec, Vec), String> { +pub(crate) fn copy_selection(input: &impl super::InputSource, p: &Value) -> Result<(Vec, Vec), String> { let context = input.input_context(); let s = &context; let mut ids: Vec = Vec::new(); diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 0e70439cdb..6ab0c850fa 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -14,9 +14,11 @@ use crate::render::rustgis_tiles::address::Reach; mod capabilities; #[path = "project_label_losses.rs"] pub(crate) mod label_losses; +pub(crate) use capabilities::{ + group_file_within, layer_file_within, layout_file_within, map_file_within, model_capabilities, task_capabilities, +}; #[cfg(test)] pub(crate) use capabilities::{layer_file_bytes, map_file_bytes}; -pub(crate) use capabilities::{layer_file_within, layout_file_within, map_file_within, model_capabilities, task_capabilities}; /// A map export cannot keep runtime-only download reservations, even in a larger project. pub(crate) fn ensure_map_imports_complete(map: &Map) -> Result<(), String> { diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 9bc2d6926b..9068e2542a 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1484,6 +1484,28 @@ pub(crate) fn layer_file_within(layer: &Layer, out: Output<'_>) -> Result) -> Result, String> { + #[derive(Serialize)] + struct GroupFile<'a> { + format: u32, + requires: Vec<&'static str>, + groups: &'a [rustgis_map::LayerGroup], + layers: &'a [Layer], + } + let mut requires = vec![crate::cmd::group_file::LAYER_GROUP]; + for l in layers { + let wkt = l.needs_wkt().then_some("crs-wkt"); + for name in layer_capabilities(l).into_iter().chain(wkt) { + if !requires.contains(&name) { + requires.push(name); + } + } + } + out.json(&GroupFile { format: FORMAT, requires, groups, layers }) +} + /// Only executable export options require the capability, not fields in unrelated data. /// Models and web tools run analysis tools, so cannot execute share.exportTable. fn command_uses_table_export_order(id: &str, params: &serde_json::Value) -> bool { diff --git a/crates/engine/tests/integration/portable_projects/packages.rs b/crates/engine/tests/integration/portable_projects/packages.rs index 9111b7d335..0dec75dba9 100644 --- a/crates/engine/tests/integration/portable_projects/packages.rs +++ b/crates/engine/tests/integration/portable_projects/packages.rs @@ -117,3 +117,25 @@ fn offline_areas_in_a_project_package_are_counted_too() { assert_eq!(said.len(), 1, "{said:?}"); assert!(said[0].starts_with("Package Project: 6 layer(s) stay linked"), "{}", said[0]); } + +/// A layer file holding a group (#2870) embeds its local rasters and names the layers it leaves +/// linked, as a package does; it adds back whole in another session. +#[test] +fn a_group_layer_file_names_the_layers_it_leaves_linked() { + let f = Fixture::new("group-file-linked"); + let (mut s, Layers { cities, countries, dem }) = populated(&f); + s.run("group.add", &json!({"name": "Base", "layers": [cities, countries, dem]})).unwrap(); + let path = f.file("out/base.rgislyr"); + let mark = s.notice_mark(); + s.run("layer.save", &json!({"group": "Base", "path": path})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("outside the layer file")).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("Save Layer File: 2 layer(s) stay linked to files outside the layer file"), "{}", said[0]); + assert!(said[0].ends_with(": Countries, Cities"), "the raster is embedded: {}", said[0]); + let mut other = session(); + let r = other.run("layer.addLayerFile", &json!({"path": path})).unwrap(); + assert_eq!((r["layers"].as_array().map(Vec::len), r["groups"].as_array().map(Vec::len)), (Some(3), Some(1))); + let m = other.map(); + let raster = m.layers.iter().find_map(|l| l.raster.as_ref()).unwrap(); + assert!(raster.embedded.is_some() && raster.path.is_none(), "embedded, not linked"); +} diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 19edf08f6f..79c6d5caaf 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -1468,6 +1468,11 @@ fn layer_group_row( let _ = app.run("layer.paste", json!({"group": group.id})); ui.close(); } + // The group, its subgroups and their layers, in one layer file (#2870). + if ui.button(tl!("Save Group File…")).clicked() { + let _ = app.run("ui.saveItem", json!({"kind": "layer", "group": group.id})); + ui.close(); + } ui.separator(); if ui.button(tl!("Ungroup")).clicked() { let _ = app.run("group.ungroup", json!({"group": group.id})); diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index cf024a9d75..cbfe5c071e 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -2028,6 +2028,7 @@ RustGIS saves pieces of a project as files you can share and reuse: | --- | --- | --- | --- | | Map file (a map with its data) | `.rgismap` | Publish › Save As › Map File | Command Search (`map.import`), or drop it on the window | | Layer file (a layer with its symbology) | `.rgislyr` | Publish › Save As › Layer File | Add Data | +| Layer file of a group (the group, its subgroups and their layers) | `.rgislyr` | Save Group File… in the group's menu in the Layers pane | Add Data, Add Layer File, or drop it on the window | | Styles (saved symbology) | `.rgisstyle` | Style › Styles › New Style, then Publish › Save As › Style Items | Style › Styles › Add Style File | | [Color ramps](cartography.md#custom-color-ramps) | `.rgisramp` (also reads QGIS `.xml`/`.qml`, GDAL color `.txt` and GMT `.cpt`) | Publish › Save As › Color Ramps, or by hand | Style › Styles › Add Color Ramp File | | Project template (the setup without features) | `.rgistemplate` | Publish › Save As, or Command Search (`project.saveTemplate`) | Command Search (`project.fromTemplate`) | @@ -2050,6 +2051,15 @@ layer file, map file or project. Data › Layer Templates adds empty layers with which also lists the project's layouts, styles and tasks. A task's steps each run a command; New Task From History turns the geoprocessing history into a task you can replay. +A layer file of a group is for a base shared by many maps (towns, roads, rivers, boundaries): +the layers are saved as a layer file saves one, features inside and local rasters embedded within +one budget for the whole file (a package's), and the layers left linked to files outside it are +named. Added, the groups come in nested as saved, with their visibility, transparency, +visibility ranges and folding, at the top of the map in one undo step; a name the map has gets +" copy", as when pasting. They are copies: later changes to the file don't reach the project. +Scripts use `layer.save` with `"group"` and `layer.addLayerFile` (`"group"` or `"to"` place it +elsewhere). + Saved projects, templates, map and layer files, and packages remove recognized credentials from supported addresses and recognized executable parameters. The open project keeps its credentials. Removal notices describe what a shared workflow or video will need again; an unchecked-content notice