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
80 changes: 58 additions & 22 deletions crates/engine/src/cmd/layout.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ pub const CAPABILITIES: &[&str] = &[
"tabulate-intersection-unit",
"layout-element-background",
"picture-markers",
"layout-element-ink",
];
/// The most entries a document's `requires` may list: past it the document is refused without
/// the rest being read.
Expand Down
86 changes: 86 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ impl Project {
{
required.push("layout-element-background");
}
if !required.contains(&"layout-element-ink") && self.layouts.iter().any(|l| l.elements.iter().any(|e| e.kind.ink().is_some())) {
required.push("layout-element-ink");
}
required
}

Expand All @@ -85,6 +88,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("tabulate-intersection-unit", command_uses_tabulate_unit),
("layout-element-background", command_uses_element_background),
("picture-markers", command_uses_picture_marker),
("layout-element-ink", command_uses_element_ink),
];

/// A layout command that gives an element a background: an older reader warns that it ignores
Expand All @@ -93,11 +97,37 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
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()),
"layout.import" => imported_layout_uses(params, "\"background\"", |e| e.background.is_some()),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_element_background)),
_ => false,
}
}

/// A layout command that gives a legend, colorbar, table or chart an ink (#2257). Only an
/// imported layout's: an older reader refuses "color" on those elements in `layout.addElement`
/// and `layout.update`, so such a command fails there instead of losing the ink.
fn command_uses_element_ink(id: &str, params: &Value) -> bool {
match id {
"layout.import" => imported_layout_uses(params, "\"color\"", |e| e.kind.ink().is_some()),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_element_ink)),
_ => false,
}
}

/// Whether a `layout.import` carries its layout as `"text"` with an element `uses`: an older
/// reader reads it without the keys it doesn't know. One read from a `"path"` is a layout file,
/// which carries no format header yet (#2277). Every save asks, so a text without the feature's
/// `key` (a saved layout writes it only when set) isn't read through, unless it has a backslash:
/// JSON may spell the key with escapes (`"\u0063olor"`).
fn imported_layout_uses(params: &Value, key: &str, uses: fn(&rustgis_map::layout::Element) -> bool) -> bool {
params
.get("text")
.and_then(Value::as_str)
.filter(|t| t.contains(key) || t.contains('\\'))
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
.and_then(|t| serde_json::from_str::<rustgis_map::layout::Layout>(t).ok())
.is_some_and(|l| l.elements.iter().any(uses))
}

/// 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> {
COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(steps, graph, uses).then_some(name)).collect()
Expand Down Expand Up @@ -456,6 +486,62 @@ mod tests {
assert_eq!(saved["requires"], json!(["layout-element-background"]));
}

/// A legend's, colorbar's, table's or chart's ink is required where it is saved, so an older
/// reader refuses the project instead of drawing them dark grey and saving them so (#2257).
/// A saved command that sets one needs nothing: an older reader refuses its "color".
#[test]
fn element_ink_capability_follows_saved_layouts() {
let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_element_ink.rgis")).unwrap();
let saved = serde_json::to_value(&fixture).unwrap();
assert_eq!(saved["requires"], json!(["layout-element-ink"]));
let inks = |p: &Project| p.layouts[0].elements.iter().map(|e| e.kind.ink()).collect::<Vec<_>>();
let reopened = Project::from_json(&saved.to_string()).unwrap();
assert_eq!(inks(&reopened), inks(&fixture));
assert_eq!(inks(&fixture).iter().filter(|i| i.is_some()).count(), 4, "{:?}", inks(&fixture));
let mut clean = fixture;
for e in &mut clean.layouts[0].elements {
if let Some(ink) = e.kind.ink_mut() {
*ink = None;
}
}
let base = serde_json::to_value(&clean).unwrap();
assert!(base.get("requires").is_none(), "default inks need nothing");
let mut document = base.clone();
document["tasks"] = json!([{"name": "Task", "steps": [{"title": "Ink", "command": "layout.update", "params": {"element": 2, "color": "#FFFFFF"}}]}]);
assert!(serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap().get("requires").is_none());
// A layout imported from its text keeps unknown keys out in an older reader, so a saved
// import of one with an ink or a background needs them; one without, or from a path, doesn't.
let layout = &saved["layouts"][0];
let mut plain = layout.clone();
for e in plain["elements"].as_array_mut().unwrap() {
if let Some(kind) = e["kind"].as_object_mut().and_then(|k| k.values_mut().next()).and_then(Value::as_object_mut) {
kind.remove("color");
}
}
let mut boxed = plain.clone();
boxed["elements"][1]["background"] = json!({"fill": [255, 255, 255, 255]});
for (params, required) in [
(json!({"text": layout.to_string()}), json!(["layout-element-ink"])),
// The same key spelled with an escape is the same key.
(json!({"text": layout.to_string().replace("\"color\"", "\"\\u0063olor\"")}), json!(["layout-element-ink"])),
(json!({"text": boxed.to_string()}), json!(["layout-element-background"])),
(json!({"text": plain.to_string()}), Value::Null),
(json!({"path": "inks.rgislayout"}), Value::Null),
(json!({"text": "not a layout"}), Value::Null),
] {
let script = format!("layout.import= {params}");
for value in [
json!([{"name": "Task", "steps": [{"title": "Import", "command": "layout.import", "params": params}]}]),
json!([{"name": "Script", "steps": [{"title": "Import", "command": "script.run", "params": {"script": script}}]}]),
] {
let mut document = base.clone();
document["tasks"] = value;
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
assert_eq!(saved.get("requires").cloned().unwrap_or(Value::Null), required, "{params}");
}
}
}

#[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
68 changes: 63 additions & 5 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9057,9 +9057,6 @@ fn layout_colours_are_refused_for_elements_without_them() {
let red = "#B91C1C";
// Added: a kind without the colour is refused, nothing added; with it, it is applied.
let refused = [
("legend", "color", "only text, lines"),
("table", "color", "only text, lines"),
("colorbar", "color", "only text, lines"),
("northArrow", "color", "only text, lines"),
("legend", "fill", "take a fill"),
("table", "fill", "take a fill"),
Expand Down Expand Up @@ -9095,6 +9092,9 @@ fn layout_colours_are_refused_for_elements_without_them() {
("circle", "color"),
("grid", "color"),
("scaleBar", "color"),
("legend", "color"),
("colorbar", "color"),
("table", "color"),
("scaleBar", "fill"),
("northArrow", "fill"),
("northArrow", "outline"),
Expand Down Expand Up @@ -9125,9 +9125,7 @@ fn layout_colours_are_refused_for_elements_without_them() {
let scale = find(&s, "scaleBar");
let table = s.run("layout.addElement", &json!({"kind": "table"})).unwrap()["element"].as_u64().unwrap();
for (el, key, said) in [
(legend, "color", "take a color"),
(u64::from(frame), "color", "take a color"),
(table, "color", "take a color"),
(legend, "fill", "take a fill"),
(table, "fill", "take a fill"),
(legend, "outline", "take an outline"),
Expand Down Expand Up @@ -33212,6 +33210,66 @@ fn layout_element_backgrounds_from_commands() {
assert!(s.project.layouts.last().unwrap().elements.iter().all(|e| e.kind.takes_background() || e.background.is_none()));
}

/// A legend, colorbar, table or chart takes an ink (#2257): added with it, changed, given the
/// default again with null, undone and kept by a copy and a save; a bad colour is refused with
/// nothing changed, and on a locked element a null is a change too.
#[test]
fn layout_element_inks_from_commands() {
use rustgis_map::Rgba;
let mut s = world();
s.run("layout.new", &json!({"name": "L"})).unwrap();
let li = s.active_layout.unwrap();
let ink = |s: &Session, id: u32| s.project.layouts[li].element(id).unwrap().kind.ink();
let white = Rgba::rgb(255, 255, 255);
let mut added = Vec::new();
for p in [
json!({"kind": "legend", "color": "#FFFFFF"}),
json!({"kind": "colorbar", "color": "#FFFFFF"}),
json!({"kind": "table", "layer": "Countries", "color": "#FFFFFF"}),
json!({"kind": "chart", "layer": "Countries", "field": "pop_est", "color": "#FFFFFF"}),
] {
let id = s.run("layout.addElement", &p).unwrap_or_else(|e| panic!("{p}: {e}"))["element"].as_u64().unwrap() as u32;
assert_eq!(ink(&s, id), Some(white), "{p}");
added.push(id);
}
// None given, or null: the default dark grey.
for p in [json!({"kind": "legend"}), json!({"kind": "table", "layer": "Countries", "color": null})] {
let id = s.run("layout.addElement", &p).unwrap()["element"].as_u64().unwrap() as u32;
assert_eq!(ink(&s, id), None, "{p}");
}
let legend = added[0];
s.run("layout.update", &json!({"element": legend, "color": "#33445580"})).unwrap();
assert_eq!(ink(&s, legend), Some(Rgba::new(0x33, 0x44, 0x55, 0x80)));
// A change of something else keeps it; a copy and a save keep it.
s.run("layout.update", &json!({"element": legend, "title": "Key"})).unwrap();
assert_eq!(ink(&s, legend), Some(Rgba::new(0x33, 0x44, 0x55, 0x80)));
let copy = s.run("layout.duplicateElement", &json!({"element": legend})).unwrap()["element"].as_u64().unwrap() as u32;
assert_eq!(ink(&s, copy), ink(&s, legend));
let back: rustgis_map::layout::Layout = serde_json::from_str(&serde_json::to_string(&s.project.layouts[li]).unwrap()).unwrap();
assert_eq!(back, s.project.layouts[li]);
// null gives the default again, and undo brings the ink back.
s.run("layout.update", &json!({"element": legend, "color": null})).unwrap();
assert_eq!(ink(&s, legend), None);
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(ink(&s, legend), Some(Rgba::new(0x33, 0x44, 0x55, 0x80)));
// Refused, and nothing changes.
let before = s.project.layouts[li].clone();
for (cmd, p) in [
("layout.update", json!({"element": added[2], "color": "white"})),
("layout.update", json!({"element": added[3], "color": 7, "x": 1})),
("layout.addElement", json!({"kind": "colorbar", "color": "#12"})),
] {
let err = s.run(cmd, &p).unwrap_err();
assert!(err.contains("color must be"), "{p}: {err}");
}
assert_eq!(s.project.layouts[li], before);
// Locked, a colour and a null are both changes.
s.run("layout.update", &json!({"element": legend, "locked": true})).unwrap();
for p in [json!({"element": legend, "color": "#000000"}), json!({"element": legend, "color": null})] {
assert!(s.run("layout.update", &p).is_err_and(|e| e.contains("locked")), "{p}");
}
}

#[test]
fn locked_layout_elements_take_no_change_until_unlocked() {
use rustgis_map::layout::ElementKind;
Expand Down
76 changes: 75 additions & 1 deletion crates/map/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,8 +841,12 @@ fn is_one_column(columns: &usize) -> bool {
*columns == 1
}

/// The dark grey a scale bar draws in by default, and a legend, colorbar, table or chart without
/// an ink of its own ([`ElementKind::ink`]).
pub const INK: Rgba = Rgba::rgb(0x22, 0x22, 0x22);

fn ink() -> Rgba {
Rgba::rgb(0x22, 0x22, 0x22)
INK
}

fn white() -> Rgba {
Expand Down Expand Up @@ -973,6 +977,10 @@ pub enum ElementKind {
/// keeps its name everywhere else. A layer not in it shows its name.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
labels: BTreeMap<String, String>,
/// The colour of its text and lines (#2257); none, the dark grey of [`INK`]. Left out
/// when none, so layouts saved before keep their bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<Rgba>,
},
/// The colour scale of a raster layer in a frame's map: a gradient bar for a stretch, steps
/// for classes, a block per value for unique values and colour tables (#326).
Expand All @@ -997,6 +1005,10 @@ pub enum ElementKind {
/// the top of a vertical one (the bottom by default).
#[serde(default)]
reverse: bool,
/// The colour of its text and lines (#2257); none, the dark grey of [`INK`]. Left out
/// when none, so layouts saved before keep their bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<Rgba>,
},
/// Text; dynamic tokens (`{page}`, `{date}`, `{scale}`…) expand when drawn.
Text {
Expand Down Expand Up @@ -1039,6 +1051,10 @@ pub enum ElementKind {
layer: String,
#[serde(default = "rows")]
rows: usize,
/// The colour of its text and lines (#2257); none, the dark grey of [`INK`]. Left out
/// when none, so layouts saved before keep their bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<Rgba>,
},
/// A bar chart of a numeric field of a layer in a frame's map, one bar per feature.
Chart {
Expand All @@ -1048,6 +1064,10 @@ pub enum ElementKind {
/// Bars are labelled with this field, if set.
#[serde(default)]
label: Option<String>,
/// The colour of its labels and title (#2257); none, the dark grey of [`INK`]. Its bars
/// keep their own colour. Left out when none, so layouts saved before keep their bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<Rgba>,
},
/// A rectangle drawn on the page (a neatline or a backdrop). `width` is the outline's, in
/// points (0: none).
Expand Down Expand Up @@ -1166,6 +1186,34 @@ impl ElementKind {
!matches!(self, ElementKind::MapFrame { .. })
}

/// Whether an element of this kind takes an ink (#2257): a legend, colorbar, table or chart,
/// whose text and lines are otherwise dark grey. The other kinds' colours are their own options.
pub fn takes_ink(&self) -> bool {
matches!(self, ElementKind::Legend { .. } | ElementKind::Colorbar { .. } | ElementKind::Table { .. } | ElementKind::Chart { .. })
}

/// Its ink, when it [takes one](ElementKind::takes_ink) and has one; `None` draws in [`INK`].
pub fn ink(&self) -> Option<Rgba> {
match self {
ElementKind::Legend { color, .. }
| ElementKind::Colorbar { color, .. }
| ElementKind::Table { color, .. }
| ElementKind::Chart { color, .. } => *color,
_ => None,
}
}

/// Its ink to change, when it [takes one](ElementKind::takes_ink).
pub fn ink_mut(&mut self) -> Option<&mut Option<Rgba>> {
match self {
ElementKind::Legend { color, .. }
| ElementKind::Colorbar { color, .. }
| ElementKind::Table { color, .. }
| ElementKind::Chart { color, .. } => Some(color),
_ => None,
}
}

/// The map frame this element belongs to.
pub fn frame(&self) -> Option<u32> {
match self {
Expand Down Expand Up @@ -2437,4 +2485,30 @@ mod tests {
assert_eq!(l.hit(36.0, 45.0), None, "past the padding");
assert_eq!(l.element(t).unwrap().background_box(), (37.0, 37.0, 26.0, 16.0));
}

/// A legend's, colorbar's, table's or chart's ink (#2257): none in a layout saved before it,
/// not written when none, and read back when set. Other kinds have none to set.
#[test]
fn inks_are_saved_and_read_back() {
let text = r#"{"name":"x","width":100,"height":100,"elements":[
{"id":1,"name":"f","x":0,"y":0,"w":50,"h":50,"kind":{"MapFrame":{"map":"M","center":{"x":0,"y":0},"scale":1000000}}},
{"id":2,"name":"l","x":0,"y":0,"w":10,"h":10,"kind":{"Legend":{"frame":1,"title":"L"}}},
{"id":3,"name":"c","x":0,"y":0,"w":10,"h":10,"kind":{"Colorbar":{"frame":1}}},
{"id":4,"name":"t","x":0,"y":0,"w":10,"h":10,"kind":{"Table":{"frame":1,"layer":"A"}}},
{"id":5,"name":"g","x":0,"y":0,"w":10,"h":10,"kind":{"Chart":{"frame":1,"layer":"A","field":"n"}}}]}"#;
let mut l: Layout = serde_json::from_str(text).unwrap_or_else(|e| panic!("{e}"));
assert!(l.elements[1..].iter().all(|e| e.kind.takes_ink() && e.kind.ink().is_none()), "the default ink in an older layout");
assert!(!l.elements[0].kind.takes_ink(), "a map frame has no ink");
let saved = serde_json::to_string(&l).unwrap();
assert!(!saved.contains("\"color\""), "none is not written: {saved}");
let white = Rgba::new(255, 255, 255, 230);
for e in &mut l.elements[1..] {
*e.kind.ink_mut().unwrap() = Some(white);
}
let back: Layout = serde_json::from_str(&serde_json::to_string(&l).unwrap()).unwrap();
assert!(back.elements[1..].iter().all(|e| e.kind.ink() == Some(white)), "{back:?}");
assert_eq!(back, l);
let mut text = ElementKind::text("t", 12.0, Rgba::rgb(0, 0, 0), false);
assert!(!text.takes_ink() && text.ink_mut().is_none(), "a text's colour is its own option");
}
}
Loading
Loading