Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
120 changes: 118 additions & 2 deletions crates/engine/src/cmd/group_file.rs
Original file line number Diff line number Diff line change
@@ -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, …]}`.
Expand All @@ -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};
Expand Down Expand Up @@ -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<LayerGroup>, Vec<Layer>), 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"]}))?;
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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<u32> = 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<Vec<rustgis_data::loss::Note>, String> {
let (_, layers) = saved_group(s, p)?;
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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<u8>, Option<String>), 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<Layer> = 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<GroupFile, String> {
let file: GroupFile = serde_json::from_str(text).map_err(|e| format!("not a RustGIS layer file: {e}"))?;
Expand Down Expand Up @@ -355,6 +416,61 @@ mod tests {
assert_eq!(said(&s, from), Vec::<String>::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();
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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() {
Expand Down
30 changes: 24 additions & 6 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -72,8 +78,8 @@ pub fn commands() -> Vec<C> {
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);
Expand Down Expand Up @@ -491,11 +497,11 @@ pub fn package_text(bytes: &[u8]) -> Result<String, String> {
/// 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()
Expand Down Expand Up @@ -532,6 +538,12 @@ fn left_linked<'a>(what: &str, maps: impl IntoIterator<Item = &'a Map>) -> 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<String> {
if names.is_empty() {
return None;
}
Expand All @@ -540,7 +552,7 @@ fn left_linked<'a>(what: &str, maps: impl IntoIterator<Item = &'a Map>) -> 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()
))
}
Expand Down Expand Up @@ -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")?)?
Expand All @@ -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();
Expand Down Expand Up @@ -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<T: crate::durable::Durable>(
pub(crate) fn durable_bytes_with<T: crate::durable::Durable>(
s: &mut Session,
value: T,
write: impl FnOnce(&T) -> Result<Vec<u8>, String>,
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/layer_copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>, Vec<LayerGroup>), String> {
pub(crate) fn copy_selection(input: &impl super::InputSource, p: &Value) -> Result<(Vec<u32>, Vec<LayerGroup>), String> {
let context = input.input_context();
let s = &context;
let mut ids: Vec<u32> = Vec::new();
Expand Down
4 changes: 3 additions & 1 deletion crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
22 changes: 22 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1484,6 +1484,28 @@ pub(crate) fn layer_file_within(layer: &Layer, out: Output<'_>) -> Result<Vec<u8
out.json(&Item { format: FORMAT, requires, value: layer })
}

/// A layer file holding a group (#2870): `groups` and their `layers`, requiring `layer-group`
/// and what each layer requires in a layer file of its own, each once.
pub(crate) fn group_file_within(groups: &[rustgis_map::LayerGroup], layers: &[Layer], out: Output<'_>) -> Result<Vec<u8>, 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 {
Expand Down
22 changes: 22 additions & 0 deletions crates/engine/tests/integration/portable_projects/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = 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");
}
5 changes: 5 additions & 0 deletions crates/ui-egui/src/panes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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}));
Expand Down
Loading
Loading