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/src/cmd/diagram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ mod tests {
"1 diagram(s) that could not be read or named no field removed",
"1 diagram category(ies) with a blank field name",
"1 diagram category(ies) repeating an earlier field kept",
"1 layout element(s) with a value out of range, a repeated id, an over-long name or a missing map frame reference repaired while opening the project (in \"Poster\")",
"1 layout element(s) with a value out of range, a repeated id, an over-long name, a missing map frame reference or a background on a map frame repaired while opening the project (in \"Poster\")",
] {
assert!(said.iter().any(|t| t.contains(text)), "{text}: {said:?}");
}
Expand Down
98 changes: 88 additions & 10 deletions crates/engine/src/cmd/layout.rs

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub const CAPABILITIES: &[&str] = &[
"slope-percent",
"table-export-order",
"tabulate-intersection-unit",
"layout-element-background",
];
/// The most entries a document's `requires` may list: past it the document is refused without
/// the rest being read.
Expand Down Expand Up @@ -2176,7 +2177,7 @@ pub(crate) fn layout_notices(
let adjusted = total(|r| r.elements_adjusted);
if adjusted > 0 {
notices.push(format!(
"{name}: {adjusted} layout element(s) with a value out of range, a repeated id, an over-long name or a missing map frame reference repaired {when} (in {})",
"{name}: {adjusted} layout element(s) with a value out of range, a repeated id, an over-long name, a missing map frame reference or a background on a map frame repaired {when} (in {})",
layout_names(repairs, |r| r.elements_adjusted)
));
}
Expand Down
80 changes: 78 additions & 2 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ impl Project {
{
required.push("table-export-order");
}
// Saved layouts as well as saved commands: an older reader keeps neither.
if !required.contains(&"layout-element-background")
&& self.layouts.iter().any(|l| l.elements.iter().any(|e| e.background.is_some()))
{
required.push("layout-element-background");
}
required
}

Expand All @@ -68,8 +74,22 @@ impl Project {
}

type CommandCheck = fn(&str, &Value) -> bool;
const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] =
&[("slope-percent", command_uses_percent_slope), ("tabulate-intersection-unit", command_uses_tabulate_unit)];
const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("slope-percent", command_uses_percent_slope),
("tabulate-intersection-unit", command_uses_tabulate_unit),
("layout-element-background", command_uses_element_background),
];

/// A layout command that gives an element a background: an older reader warns that it ignores
/// the key and makes the element without one. `null` only takes a background away, which an
/// older reader's elements never have.
fn command_uses_element_background(id: &str, params: &Value) -> bool {
match id {
"layout.addElement" | "layout.update" => params.get("background").is_some_and(|b| !b.is_null()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug (confidence ~55%): layout.import with inline text is not covered by this predicate.

layout.import takes {"text": …} (the same layout JSON as a .rgislayout file, see cmd/layout.rs import). A saved task step, script line, notebook cell or history entry that imports a layout with a background inline therefore saves without layout-element-background, and an older reader would replay it and silently drop the background. That is the loss the capability exists to prevent, and it is a saved command, not a layout file, so the .rgislayout gap the docs accept does not cover it. A {"path": …} import can't be seen at save time and stays with that accepted gap.

A conservative fix is to treat any inline text that mentions a background as requiring the capability (over-requiring is safe; the cost is one refused older read):

Suggested change
"layout.addElement" | "layout.update" => params.get("background").is_some_and(|b| !b.is_null()),
"layout.addElement" | "layout.update" => params.get("background").is_some_and(|b| !b.is_null()),
"layout.import" => params.get("text").and_then(Value::as_str).is_some_and(|t| t.contains("\"background\"")),

Please add a test next to element_background_capability_follows_saved_layouts with a saved layout.import step whose text carries a background (requires) and one whose text has none (doesn't).

"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_element_background)),
_ => false,
}
}

/// Require only executable payloads being saved: graph files omit steps, web tools omit graphs.
pub(crate) fn model_capabilities(steps: &[ModelStep], graph: Option<&ModelGraph>) -> Vec<&'static str> {
Expand Down Expand Up @@ -325,6 +345,62 @@ mod tests {
assert!(serde_json::to_value(&project).unwrap().get("requires").is_none());
}

/// A layout element's background is required where it is saved, so an older reader refuses
/// the project instead of opening it and saving it again without the background.
#[test]
fn element_background_capability_follows_saved_layouts() {
let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_element_background.rgis")).unwrap();
let saved = serde_json::to_value(&fixture).unwrap();
assert_eq!(saved["requires"], json!(["layout-element-background"]));
let reopened = Project::from_json(&saved.to_string()).unwrap();
let backgrounds = |p: &Project| p.layouts[0].elements.iter().map(|e| e.background).collect::<Vec<_>>();
assert_eq!(backgrounds(&reopened), backgrounds(&fixture));
assert!(backgrounds(&fixture)[1].is_some_and(|b| b.padding == 1.5));
let mut clean = fixture;
for e in &mut clean.layouts[0].elements {
e.background = None;
}
assert!(serde_json::to_value(&clean).unwrap().get("requires").is_none());
// A saved command that gives an element a background needs it too; one that takes it
// away or sets none doesn't.
let base = serde_json::to_value(&clean).unwrap();
for (background, required) in
[(Some(json!({"fill": "#FFFFFF"})), true), (Some(json!({})), true), (Some(Value::Null), false), (None, false)]
{
let mut params = json!({"element": 2, "x": 5});
if let Some(b) = background {
params["background"] = b;
}
let script = format!("# Panel\nlayout.update= {params}");
for (field, value) in [
("tasks", json!([{"name": "Task", "steps": [{"title": "Panel", "command": "layout.update", "params": params}]}])),
(
"tasks",
json!([{"name": "Script", "steps": [{"title": "Panel", "command": "script.run", "params": {"script": script}}]}]),
),
("notebooks", json!([{"name": "Notebook", "cells": [{"kind": "code", "source": script}]}])),
(
"gp_history",
json!([{"tool": "Panel", "params": {}, "command": ["layout.addElement", params], "ok": true, "messages": [], "millis": 0}]),
),
] {
let mut document = base.clone();
document[field] = value;
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
if required {
assert_eq!(saved["requires"], json!(["layout-element-background"]), "{field} {params}");
} else {
assert!(saved.get("requires").is_none(), "{field} {params}");
}
}
}
// Both a saved background and a saved command: listed once.
let mut both = saved.clone();
both["tasks"] = json!([{"name": "Task", "steps": [{"title": "Panel", "command": "layout.update", "params": {"element": 2, "background": {}}}]}]);
let saved = serde_json::to_value(Project::from_json(&both.to_string()).unwrap()).unwrap();
assert_eq!(saved["requires"], json!(["layout-element-background"]));
}

#[test]
fn field_identity_is_preserved_and_required_in_a_plain_saved_project() {
let project = Project::from_json(include_str!("../../../schema/fixtures/field_origin.rgis")).unwrap();
Expand Down
80 changes: 80 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32720,6 +32720,86 @@ fn layout_elements_duplicate_offset_on_top_and_undo() {
assert!(s.project.layouts[li].element(id).is_none(), "undone");
}

/// An element's background (#2257) from commands: given when added, its keys changed one at a time
/// (the others kept), copied with the element, taken away with null, and refused on a map frame,
/// a grid or an extent indicator, on a locked element, and when it isn't a box of known keys.
#[test]
fn layout_element_backgrounds_from_commands() {
use rustgis_map::Rgba;
use rustgis_map::layout::Background;
let mut s = world();
s.run("layout.new", &json!({"name": "L"})).unwrap();
let li = s.active_layout.unwrap();
let frame = s.project.layouts[li].first_frame().unwrap();
let background = |s: &Session, id: u32| s.project.layouts[li].element(id).unwrap().background;
let added = s
.run(
"layout.addElement",
&json!({"kind": "text", "text": "Title", "x": 10, "y": 10, "background": {"fill": "#FFFFFFCC", "padding": 1.5}}),
)
.unwrap();
let title = added["element"].as_u64().unwrap() as u32;
assert_eq!(background(&s, title), Some(Background { padding: 1.5, ..Background::filled(Rgba::new(255, 255, 255, 204)) }));
// A key changed alone keeps the others; an empty box is the default one.
s.run("layout.update", &json!({"element": title, "background": {"outline": "#000000", "width": 0.5, "radius": 2}})).unwrap();
let b = background(&s, title).unwrap();
assert_eq!((b.fill, b.outline, b.width, b.radius, b.padding), (Rgba::new(255, 255, 255, 204), Rgba::rgb(0, 0, 0), 0.5, 2.0, 1.5));
let legend = s.project.layouts[li].elements.iter().find(|e| e.name == "Legend").unwrap().id;
s.run("layout.update", &json!({"element": legend, "background": {}})).unwrap();
assert_eq!(background(&s, legend), Some(Background::filled(Rgba::rgb(255, 255, 255))));
// Past their limits, the numbers are held to them.
s.run("layout.update", &json!({"element": legend, "background": {"padding": 1e9}})).unwrap();
assert_eq!(background(&s, legend).unwrap().padding, rustgis_map::layout::MAX_BACKGROUND_PADDING);
// A copy keeps it; null takes it away, and undo brings it back.
let copy = s.run("layout.duplicateElement", &json!({"element": title})).unwrap()["element"].as_u64().unwrap() as u32;
assert_eq!(background(&s, copy), background(&s, title));
s.run("layout.update", &json!({"element": title, "background": null})).unwrap();
assert_eq!(background(&s, title), None);
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(background(&s, title), Some(b));
// A map frame takes none, so taking it away changes nothing.
s.run("layout.update", &json!({"element": frame, "background": null})).unwrap();
assert_eq!(background(&s, frame), None);
// Refused, and nothing changes.
let before = s.project.layouts[li].clone();
for (p, said) in [
(json!({"element": frame, "background": {"fill": "#FFFFFF"}}), "map frame"),
(json!({"element": title, "background": "#FFFFFF"}), "an object"),
(json!({"element": title, "background": {"colour": "#FFFFFF"}}), "'colour'"),
(json!({"element": title, "background": {"fill": "white"}}), "fill must be"),
(json!({"element": title, "background": {"padding": -1}}), "padding is millimetres"),
(json!({"element": title, "background": {"width": "thick"}}), "width is points"),
] {
let err = s.run("layout.update", &p).unwrap_err();
assert!(err.contains(said), "{p}: {err}");
}
for kind in [json!({"kind": "grid"}), json!({"kind": "extentIndicator", "of": frame})] {
let mut p = kind.clone();
p["background"] = json!({"fill": "#FFFFFF"});
let err = s.run("layout.addElement", &p).unwrap_err();
assert!(err.contains("map frame"), "{p}: {err}");
}
assert_eq!(s.project.layouts[li], before);
// Locked, its background is a change like any other, null too.
s.run("layout.update", &json!({"element": title, "locked": true})).unwrap();
for p in [json!({"element": title, "background": {"fill": "#000000"}}), json!({"element": title, "background": null})] {
assert!(s.run("layout.update", &p).is_err_and(|e| e.contains("locked")), "{p}");
}
assert_eq!(background(&s, title), Some(b));
// A hand-edited file with a background on its map frame says it was taken off; a clean one
// says nothing.
let mut file = serde_json::to_value(&s.project.layouts[li]).unwrap();
let said = |s: &Session| s.notices.iter().filter(|n| n.text.contains("a background on a map frame")).count();
let quiet = s.notices.len();
s.run("layout.import", &json!({"text": file.to_string()})).unwrap();
assert_eq!(s.notices.len(), quiet, "{:?}", s.notices);
let held = file["elements"].as_array_mut().unwrap().iter_mut().find(|e| e["id"] == json!(frame)).unwrap();
held["background"] = json!({"fill": [255, 255, 255, 255]});
s.run("layout.import", &json!({"text": file.to_string()})).unwrap();
assert_eq!(said(&s), 1, "{:?}", s.notices);
assert!(s.project.layouts.last().unwrap().elements.iter().all(|e| e.kind.takes_background() || e.background.is_none()));
}

#[test]
fn locked_layout_elements_take_no_change_until_unlocked() {
use rustgis_map::layout::ElementKind;
Expand Down
Loading
Loading