From 88fcac658a3c93033c1be24f459e4b36c40a115a Mon Sep 17 00:00:00 2001 From: choupeanut Date: Thu, 5 Nov 2026 14:14:33 +0800 Subject: [PATCH] fix(layout): refuse a colour the element kind doesn't have (#1455) layout.addElement and layout.update accepted color, fill and outline for every element kind and dropped those a kind doesn't draw without a word. They are now refused before anything changes, naming the kinds that take them, as font and radius already are; null still means not given. Adding a rectangle, ellipse or circle also takes outline now (color as the fallback), as layout.update already did. --- crates/engine/src/cmd/layout.rs | 51 ++++++++++++++-- crates/engine/src/tests.rs | 105 ++++++++++++++++++++++++++++++++ docs/user-guide/layouts.md | 4 ++ 3 files changed, 156 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b53ea41c09..56efde6929 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -88,10 +88,10 @@ pub fn commands() -> Vec { r#"{"layout"?, "shape"?: "rectangle"|"circle"|"ellipse"|"polygon"|"lasso", "points"?: [[u, v], …] (polygon/lasso, 0..1 across the frame), "map"?: name, "x"?, "y"?, "w"?, "h"?: mm}"#, ), C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).params( - r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA", "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "orientation"?: "horizontal"|"vertical" (colorbar), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible one), "field"?, "label"?, "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system, as ArcGIS Pro's measured grid), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "labels"?: bool, "style"?: "lines"|"ticks"|"linesAndTicks" (grid) or "classic"|"compass"|"triangle"|"star" (northArrow) or "alternating"|"stepped"|"line" (scaleBar), "tickLength"?: mm, "format"?: "decimal"|"dms", "hemisphere"?: bool (N/S/E/W rather than a sign), "edges"?: ["top","bottom","left","right"] (labelled edges), "labelOrientation"?: "horizontal"|"vertical", "off"?: bool (grid; options not given keep the grid's), "outline"?: "#RRGGBB" (northArrow), "units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "divisions"?: 1..10 (scaleBar), "x"?, "y"?, "w"?, "h"?: mm}"##, + r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; refused for other kinds), "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "orientation"?: "horizontal"|"vertical" (colorbar), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; refused for other kinds), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible one), "field"?, "label"?, "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system, as ArcGIS Pro's measured grid), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "labels"?: bool, "style"?: "lines"|"ticks"|"linesAndTicks" (grid) or "classic"|"compass"|"triangle"|"star" (northArrow) or "alternating"|"stepped"|"line" (scaleBar), "tickLength"?: mm, "format"?: "decimal"|"dms", "hemisphere"?: bool (N/S/E/W rather than a sign), "edges"?: ["top","bottom","left","right"] (labelled edges), "labelOrientation"?: "horizontal"|"vertical", "off"?: bool (grid; options not given keep the grid's), "outline"?: "#RRGGBB" (northArrow, or a rectangle's, ellipse's or circle's outline instead of color; refused for other kinds), "units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "divisions"?: 1..10 (scaleBar), "x"?, "y"?, "w"?, "h"?: mm}"##, ), C::new("layout.update", "Element Properties", "Publish › Element", update).params( - r##"{"layout"?, "element": id, "x"?, "y"?, "w"?, "h"?: mm, "name"?, "visible"?, "locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "text"?, "size"?, "color"? (text, line), "bold"?, "italic"?, "align"?, "letterSpacing"?, "font"?: "sans"|"serif"|an installed font family's name, "fallback"?: "sans"|"serif" (text, as in layout.addElement; refused for other elements), "title"?, "allClasses"?: bool (legend), "hideOther"?: bool (legend), "exclude"?: [layer names] (legend; [] lists every layer again), "orientation"?, "ticks"?, "tickSide"?, "reverse"?: (colorbar), "style"?: (northArrow, scaleBar), "fill"?, "outline"? (northArrow, rectangle, ellipse; for a rectangle or ellipse, color sets it when outline is not given), "radius"?: mm (rectangle: rounded corners), "width"?: points (rectangle, ellipse, line), "dir"?, "head"?, "angle"?, "length"? (line: turned or sized about its centre, then moved by any x or y; dir does not come with angle or length), "units"?, "divisions"? (scaleBar), "map"?, "scale"?, "center"?: [lon, lat], "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85), "grid"?: {grid options as in layout.addElement} | false (map frame), "extentIndicator"?: {"color"?, "width"?: points} | false (map frame: its extent indicator's style, or removes it), "layer"?: (colorbar: "" for the top visible raster), "field"?, "rows"?}"##, + r##"{"layout"?, "element": id, "x"?, "y"?, "w"?, "h"?: mm, "name"?, "visible"?, "locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "text"?, "size"?, "color"? (text, line, rectangle, ellipse: its outline; refused for other elements), "bold"?, "italic"?, "align"?, "letterSpacing"?, "font"?: "sans"|"serif"|an installed font family's name, "fallback"?: "sans"|"serif" (text, as in layout.addElement; refused for other elements), "title"?, "allClasses"?: bool (legend), "hideOther"?: bool (legend), "exclude"?: [layer names] (legend; [] lists every layer again), "orientation"?, "ticks"?, "tickSide"?, "reverse"?: (colorbar), "style"?: (northArrow, scaleBar), "fill"?, "outline"? (northArrow, rectangle, ellipse; refused for other elements; for a rectangle or ellipse, color sets the outline when outline is not given), "radius"?: mm (rectangle: rounded corners), "width"?: points (rectangle, ellipse, line), "dir"?, "head"?, "angle"?, "length"? (line: turned or sized about its centre, then moved by any x or y; dir does not come with angle or length), "units"?, "divisions"? (scaleBar), "map"?, "scale"?, "center"?: [lon, lat], "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85), "grid"?: {grid options as in layout.addElement} | false (map frame), "extentIndicator"?: {"color"?, "width"?: points} | false (map frame: its extent indicator's style, or removes it), "layer"?: (colorbar: "" for the top visible raster), "field"?, "rows"?}"##, ), C::new("layout.guides", "Guides", "Publish › Page Setup", guides).params( r#"{"layout"?, "x"?: [mm] (vertical guides, from the page's left edge), "y"?: [mm] (horizontal guides, from its top edge), "clear"?: bool (remove every guide first)}"#, @@ -2227,6 +2227,19 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { if kind != "rectangle" && p.get("radius").is_some_and(|v| !v.is_null()) { return Err(ONLY_RECTANGLE_RADIUS.into()); } + if !matches!(kind, "text" | "dynamicText" | "rectangle" | "ellipse" | "circle" | "line" | "arrow" | "extentIndicator" | "grid") + && gives(p, "color") + { + return Err(ONLY_COLOR_ADDED.into()); + } + if !matches!(kind, "northArrow" | "rectangle" | "ellipse" | "circle") { + if gives(p, "fill") { + return Err(ONLY_FILL.into()); + } + if gives(p, "outline") { + return Err(ONLY_OUTLINE.into()); + } + } let i = index(s, p)?; let image = if kind == "picture" { Some(super::graphics::picture(p)?) } else { None }; let layer_name = |s: &Session, l: &Layout, frame: u32| -> Result { @@ -2333,7 +2346,7 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { "rectangle" => { let k = ElementKind::Rectangle { fill: color(p, "fill", Rgba::new(0, 0, 0, 0))?, - outline: color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?, + outline: color(p, "outline", color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?)?, width: shape_width(p, 1.0)?.clamp(0.0, 50.0), radius: corner_radius(p, 0.0)?, }; @@ -2347,7 +2360,7 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { "ellipse" | "circle" => { let k = ElementKind::Ellipse { fill: color(p, "fill", Rgba::new(0, 0, 0, 0))?, - outline: color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?, + outline: color(p, "outline", color(p, "color", Rgba::rgb(0x22, 0x22, 0x22))?)?, width: shape_width(p, 1.0)?.clamp(0.0, 50.0), }; // A circle is an ellipse in a square box. @@ -2628,6 +2641,19 @@ const ONLY_TEXT_FONT: &str = "only text elements take a font or a fallback"; /// them as applied. const ONLY_RECTANGLE_RADIUS: &str = "only a rectangle rounds its corners"; +/// Colours are refused for the elements that don't draw them, as a family is, so a script doesn't +/// take them as applied: "color" is a text's, a line's or an outline's (a rectangle's, an +/// ellipse's), added also an extent indicator's or a grid's. +const ONLY_COLOR_ADDED: &str = "only text, lines, arrows, rectangles, ellipses, circles, extent indicators and grids take a color"; +const ONLY_COLOR_UPDATED: &str = "only text, lines, arrows, rectangles, ellipses and circles take a color"; +const ONLY_FILL: &str = "only north arrows, rectangles, ellipses and circles take a fill"; +const ONLY_OUTLINE: &str = "only north arrows, rectangles, ellipses and circles take an outline"; + +/// Whether `p` gives `k`: `null` is not given. +fn gives(p: &Value, k: &str) -> bool { + p.get(k).is_some_and(|v| !v.is_null()) +} + /// Whether `p` gives a `font` or a `fallback`, which only text elements take. fn gives_font(p: &Value) -> bool { ["font", "fallback"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) @@ -2981,6 +3007,23 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { ), None => None, }; + let kind_now = s.project.layouts.get(li).and_then(|l| l.element(id)).map(|e| &e.kind); + if gives(p, "color") + && !matches!( + kind_now, + Some(ElementKind::Text { .. } | ElementKind::Line { .. } | ElementKind::Rectangle { .. } | ElementKind::Ellipse { .. }) + ) + { + return Err(ONLY_COLOR_UPDATED.into()); + } + if !matches!(kind_now, Some(ElementKind::NorthArrow { .. } | ElementKind::Rectangle { .. } | ElementKind::Ellipse { .. })) { + if gives(p, "fill") { + return Err(ONLY_FILL.into()); + } + if gives(p, "outline") { + return Err(ONLY_OUTLINE.into()); + } + } let col = match ps(p, "color") { Some(c) => Some(Rgba::from_hex(c).ok_or("color must be #RRGGBB or #RRGGBBAA")?), None => None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 606d28eea8..20ad7965de 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5751,6 +5751,111 @@ fn layout_surrounds_take_cartographic_options() { /// A colorbar shows a raster's colour scale on a layout (#326): added and edited through /// commands, checked against the frame's map, and saved with the layout. +#[test] +fn layout_colours_are_refused_for_elements_without_them() { + use rustgis_map::Rgba; + use rustgis_map::layout::ElementKind; + let mut s = world(); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap(); + let layouts = |s: &Session| serde_json::to_string(&s.project.layouts).unwrap(); + let find = |s: &Session, code: &str| s.project.layouts[0].elements.iter().find(|e| e.kind.code() == code).unwrap().id; + let frame = find(&s, "mapFrame"); + 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"), + ("scaleBar", "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"), + ("scaleBar", "fill", "take a fill"), + ("text", "fill", "take a fill"), + ("line", "fill", "take a fill"), + ("grid", "fill", "take a fill"), + ("legend", "outline", "take an outline"), + ("scaleBar", "outline", "take an outline"), + ("text", "outline", "take an outline"), + ("line", "outline", "take an outline"), + ("extentIndicator", "outline", "take an outline"), + ]; + for (kind, key, said) in refused { + let before = layouts(&s); + let e = s.run("layout.addElement", &json!({"kind": kind, key: red})).unwrap_err(); + assert!(e.contains(said) && layouts(&s) == before, "{kind} {key}: {e}"); + // null is not given. + let mut p = json!({"kind": kind}); + p[key] = Value::Null; + let after = s.run("layout.addElement", &p); + assert!(after.as_ref().err().is_none_or(|e| !e.contains("take a")), "{kind} {key} null: {after:?}"); + } + let before = layouts(&s); + let e = s.run("layout.addElement", &json!({"kind": "picture", "color": red})).unwrap_err(); + assert!(e.contains("take a color") && layouts(&s) == before, "{e}"); + for (kind, key) in [ + ("text", "color"), + ("dynamicText", "color"), + ("line", "color"), + ("arrow", "color"), + ("rectangle", "color"), + ("ellipse", "color"), + ("circle", "color"), + ("grid", "color"), + ("northArrow", "fill"), + ("northArrow", "outline"), + ("rectangle", "fill"), + ("rectangle", "outline"), + ("ellipse", "fill"), + ("circle", "outline"), + ] { + s.run("layout.addElement", &json!({"kind": kind, key: red})).unwrap_or_else(|e| panic!("{kind} {key}: {e}")); + } + let id = s.run("layout.addElement", &json!({"kind": "extentIndicator", "of": find(&s, "mapFrame"), "color": red})); + // Only one map frame in the template: the indicator needs another, so it is refused for that. + assert!(id.as_ref().err().is_none_or(|e| e.contains("another map frame")), "{id:?}"); + // A rectangle's outline is its "outline", else its "color". + let r = + s.run("layout.addElement", &json!({"kind": "rectangle", "outline": "#112233", "color": red})).unwrap()["element"].as_u64().unwrap(); + let outline = |s: &Session, id: u64| match &s.project.layouts[0].element(id as u32).unwrap().kind { + ElementKind::Rectangle { outline, .. } | ElementKind::Ellipse { outline, .. } => *outline, + k => panic!("{k:?}"), + }; + assert_eq!(outline(&s, r), Rgba::rgb(0x11, 0x22, 0x33)); + // Updated: the same, the element unchanged when refused. + let legend = s.run("layout.addElement", &json!({"kind": "legend"})).unwrap()["element"].as_u64().unwrap(); + 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(scale), "color", "take a color"), + (u64::from(frame), "color", "take a color"), + (table, "color", "take a color"), + (legend, "fill", "take a fill"), + (u64::from(scale), "fill", "take a fill"), + (table, "fill", "take a fill"), + (legend, "outline", "take an outline"), + (u64::from(frame), "outline", "take an outline"), + ] { + let before = layouts(&s); + let e = s.run("layout.update", &json!({"element": el, key: red, "name": "Renamed"})).unwrap_err(); + assert!(e.contains(said) && layouts(&s) == before, "{el} {key}: {e}"); + s.run("layout.update", &json!({"element": el, key: null})).unwrap(); + } + let arrow = find(&s, "northArrow"); + let e = s.run("layout.update", &json!({"element": arrow, "color": red})).unwrap_err(); + assert!(e.contains("take a color"), "{e}"); + for (el, key) in [(u64::from(arrow), "fill"), (u64::from(arrow), "outline"), (r, "fill"), (r, "outline"), (r, "color")] { + s.run("layout.update", &json!({"element": el, key: red})).unwrap_or_else(|e| panic!("{el} {key}: {e}")); + } + let text = find(&s, "text"); + s.run("layout.update", &json!({"element": text, "color": red})).unwrap(); + let ElementKind::Text { color, .. } = &s.project.layouts[0].element(text).unwrap().kind else { panic!() }; + assert_eq!(*color, Rgba::rgb(0xB9, 0x1C, 0x1C)); + let e = s.run("layout.update", &json!({"element": text, "fill": red})).unwrap_err(); + assert!(e.contains("take a fill"), "{e}"); +} + #[test] fn layout_colorbars_follow_a_raster() { use rustgis_map::layout::{ElementKind, Orientation, TickSide}; diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 2b3d645a4e..ac86fb4462 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -203,6 +203,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu rounded corners (`"radius"`, in mm), and a line's colour, width, arrowheads and angle. From a command: `layout.addElement={"kind":"line","dir":"falling","color":"#C0392B","width":2}`. + A colour goes only to the elements that draw it, and is refused for the others: `color` is a + text's, a line's or arrow's, or a shape's outline (as is `outline`, which wins when both are + given), and, when adding, an extent indicator's or a grid's; `fill` and `outline` are a north + arrow's and a shape's. A scale bar, legend, picture, table and the like take none. - **Arrows**: **Arrow** adds an arrow pointing right. Drag the round handle above a selected arrow or line to turn it about its centre: it snaps to level, upright and diagonal within 3°, and **Shift** turns it in 15° steps. **Angle** in its properties sets it exactly (0° points right,