From ffc4bc220d8eb678a7f24662effb359f1f6dd7e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 04:22:24 -0500 Subject: [PATCH 1/7] feat(layout): leave out or set up a publication's grid, scale bar and north arrow --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/layout.rs | 4 +- .../engine/src/cmd/layout/publication/mod.rs | 128 ++++++---- .../src/cmd/layout/publication/parts.rs | 115 +++++++++ .../src/cmd/layout/publication/placement.rs | 4 +- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 17 ++ crates/engine/src/tests.rs | 3 + .../src/tests/layout_publication_parts.rs | 223 ++++++++++++++++++ docs/maintaining.md | 5 + docs/user-guide/layouts.md | 8 + schema/fixtures/layout_publication_parts.rgis | 1 + schema/project.schema.json | 6 +- 13 files changed, 459 insertions(+), 58 deletions(-) create mode 100644 crates/engine/src/cmd/layout/publication/parts.rs create mode 100644 crates/engine/src/tests/layout_publication_parts.rs create mode 100644 schema/fixtures/layout_publication_parts.rgis diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 261d473822..b655b5697b 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -296,7 +296,7 @@ layout.import path? text? layout.move name? layout? to layout.new name? page? orientation? width? height? template? layout.page layout? page? orientation? width? height? decimal? color? -layout.publication profile? extent? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? legendBox? style? accent? arrangement? coverage? +layout.publication profile? extent? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? grid? scaleBar? legendBox? style? accent? arrangement? coverage? layout.remove name? layout? layout.removeElement layout? element layout.rename name? layout? newName diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b4209979bf..ea8b8dc799 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -80,7 +80,9 @@ pub fn commands() -> Vec { r#""colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "#, r#""veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "#, r#""contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "#, - r#""northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "#, + r#""northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none" | {"show"?: "auto" | "always", "style"?, "fill"?, "outline"? as layout.update takes a north arrow's}, "#, + r#""grid"?: "none" (no grid on the map frame, and no label strips inside it) | {a frame grid's options as layout.addElement takes them: type, crs, step, short, mgrs, color, width, labels, labelSize, style, tickLength, format, hemisphere, edges, labelOrientation} over the default graticule (its step by the extent, labelled left and bottom, on a sheet all round); the label strips follow its labels, edges and labelSize, and without a graticule the default reference names none and {grid} in a text reads "—", "#, + r#""scaleBar"?: "none" | {a scale bar's options as layout.update takes them: style, units, divisions, color, fill, textSize, decimals, subdivisions, divisionsBeforeZero, labelPosition, unitLabel, unitLabelPosition, fit} (none on a globe shown whole, whatever is asked), "#, r#""legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "#, r#""style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "#, r#""accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "#, diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 655f4d4332..8395b13f41 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -6,6 +6,8 @@ mod arrangement; pub use arrangement::*; mod coverage; pub(in crate::cmd::layout) use coverage::*; +mod parts; +use parts::*; mod placement; pub(crate) use placement::*; mod sheet; @@ -109,8 +111,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let one = |k: &str| texts_of(p, k).map(|t| t.map(|t| t.join(" ")).filter(|t| !t.trim().is_empty())); let (title, subtitle, note) = (one("title")?, one("subtitle")?, one("note")?); let sources = texts_of(p, "sources")?.unwrap_or_default(); - let reference = - texts_of(p, "reference")?.unwrap_or_else(|| vec!["Projection: {projection}".into(), "Datum: {datum} · Graticule: {grid}".into()]); + let reference = texts_of(p, "reference")?; // An empty author leaves the line out; none given, the default. let author = match texts_of(p, "author")? { None => Some(PUBLICATION_DEFAULT_CREDIT.to_string()), @@ -122,7 +123,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let colorbar = publication_colorbar(p)?; let may_veil = publication_veil(p)?; let context_in_legend = publication_flag(p, "contextInLegend")?.unwrap_or(false); - let north_arrow = publication_north_arrow(p)?; + let (north_arrow, mut arrow_kind) = publication_north_arrow(p)?; let legend_box_always = publication_legend_box(p)?; // A style or an accent that isn't text is refused, as an unknown one is, rather than left out. for k in ["style", "accent"] { @@ -161,8 +162,32 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let (page_w, page_h) = (profile.width, profile.height); let heading = |i: usize, or: &str| headings.get(i).cloned().unwrap_or_else(|| or.to_string()); let (projection, datum) = projection_and_datum(s); - let step = grid_step(&extent); - let fill = |t: &str| t.replace("{projection}", &projection).replace("{datum}", &datum).replace("{grid}", &step_text(step)); + // A sheet's sizes follow its short side (A4's 210 mm is 1); a figure keeps its texts at their + // printed size, whatever its width. + let k = if sheet { page_w.min(page_h) / 210.0 } else { 1.0 }; + // So do its legend's rows, its scale bar's and graticule's labels and the strips those take + // inside the frame (#2581): A4's sizes times k, within the 4 to 100 points a text size takes + // on every sheet size (k from 0.70 on A5 to 4.0 on A0). + let (legend_pt, bar_pt, grid_pt) = (rustgis_map::layout::LEGEND_TEXT_PT * k, SCALE_BAR_TEXT_PT * k, GRID_LABEL_PT * k); + // Labels along the left and bottom edges of a figure's frame, along all four of a sheet's, + // unless "grid" says otherwise. + let edges = GridEdges { top: sheet, bottom: true, left: true, right: sheet }; + let grid = publication_grid(p, Grid { step: grid_step(&extent), edges, label_size: grid_pt, ..Grid::default() })?; + let mut scale_kind = publication_scale_bar(p, bar_pt)?; + // The step of the frame's graticule: none without a grid, or with a measured one. + let step = grid.as_ref().filter(|g| g.kind == GridKind::Graticule).map(|g| g.step); + // The edges that carry labels, and the strips they take inside the frame. + let labelled = + grid.as_ref().filter(|g| g.labels).map_or(GridEdges { top: false, bottom: false, left: false, right: false }, |g| g.edges); + let strip_scale = grid.as_ref().map_or(k, |g| k * (g.label_size / grid_pt)); + let room_side = if labelled.left || labelled.right { LABEL_ROOM_SIDE * strip_scale } else { 0.0 }; + let room_end = if labelled.top || labelled.bottom { LABEL_ROOM_END * strip_scale } else { 0.0 }; + let reference = reference.unwrap_or_else(|| { + let datum = if step.is_some() { "Datum: {datum} · Graticule: {grid}" } else { "Datum: {datum}" }; + vec!["Projection: {projection}".into(), datum.into()] + }); + let step_said = step.map_or_else(|| "—".to_string(), step_text); + let fill = |t: &str| t.replace("{projection}", &projection).replace("{datum}", &datum).replace("{grid}", &step_said); // Text is measured as it is drawn: bold as bold, and the tokens the layout fills only when it // draws (`{date}`, `{scale}`…) as wide as a typical value of theirs. let (map_name, crs) = (s.map().name.clone(), s.map().projection.label()); @@ -237,14 +262,6 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // whatever a pass below frees, so never moved: over the map (`true`) or under everything, // each before the rest of its side. let mut page_wide: Vec<(String, (f64, f64, f64, f64), ElementKind, bool)> = Vec::new(); - // A sheet's sizes follow its short side (A4's 210 mm is 1); a figure keeps its texts at their - // printed size, whatever its width. - let k = if sheet { page_w.min(page_h) / 210.0 } else { 1.0 }; - // So do its legend's rows, its scale bar's and graticule's labels and the strips those take - // inside the frame (#2581): A4's sizes times k, within the 4 to 100 points a text size takes - // on every sheet size (k from 0.70 on A5 to 4.0 on A0). - let (legend_pt, bar_pt, grid_pt) = (rustgis_map::layout::LEGEND_TEXT_PT * k, SCALE_BAR_TEXT_PT * k, GRID_LABEL_PT * k); - let (room_side, room_end) = (LABEL_ROOM_SIDE * k, LABEL_ROOM_END * k); // The sources and the reference that have something in them, each its heading in `head_pt` and // lines in `body_pt`, `tw` wide. Each one's elements keep their names (`Sources`, `Reference`) // whatever its heading reads, the heading filled and wrapped like the rest. @@ -748,11 +765,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } else { (fy, column, h) }; - // The extent fits within the graticule's label strips (drawn inside the frame along its - // labelled edges), on both sides so it stays centred, and its labels cover none of it. - let edges = GridEdges { top: sheet, bottom: true, left: true, right: sheet }; - let strip_w = if edges.left || edges.right { 2.0 * room_side } else { 0.0 }; - let strip_h = if edges.top || edges.bottom { 2.0 * room_end } else { 0.0 }; + // The extent fits within the grid's label strips (drawn inside the frame along its labelled + // edges), on both sides so it stays centred, and its labels cover none of it. + let (strip_w, strip_h) = (2.0 * room_side, 2.0 * room_end); if fw - strip_w < fw / 2.0 || fh - strip_h < fh / 2.0 { warnings.push("the frame is too small to keep its graticule's labels off the map's edges: they may cover them".into()); } @@ -776,7 +791,6 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu fit_scale(s.map(), &extent, inner_w, inner_h).ok_or("the extent can't be drawn on the map's projection")? }; let scale = round_scale(scale); - let grid = Grid { step, edges, label_size: grid_pt, ..Grid::default() }; // A name given past the limit is refused, as layout.new refuses it, not cut (#2639). let given = crate::cmd::within("name", "a layout's name", ps(p, "name").unwrap_or("Publication").trim(), crate::cmd::MAX_NAME)?; let (name, name_cut) = unique_name(s, "New Publication Layout", "the name given", &given); @@ -797,7 +811,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu center, scale, shape: FrameShape::Rectangle, - grid: Some(grid), + grid: grid.clone(), extent_of: None, extent_color: rustgis_map::layout::INDICATOR_COLOR, extent_width: rustgis_map::layout::INDICATOR_WIDTH, @@ -824,7 +838,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu room_end } }; - let (left, right, top, bottom) = (room(edges.left, true), room(edges.right, true), room(edges.top, false), room(edges.bottom, false)); + let (left, right, top, bottom) = + (room(labelled.left, true), room(labelled.right, true), room(labelled.top, false), room(labelled.bottom, false)); let (aw, ah) = if sheet { (8.0 * k, 12.0 * k) } else { (5.0, 7.5) }; // The locator: a globe (a copy of the map's polygon layers on the globe, its diameter nearly // the frame's) or the surrounding region on the map itself, the area outlined on either by @@ -1025,20 +1040,25 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu sizes = None; warnings.push("a WMS or WMTS layer's legend picture is still loading: the legend has a fixed size to fit by hand".into()); } - let (sh, nh) = (if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); + // A scale bar given a larger text than the sheet's gets the height for it. + let text_growth = match &scale_kind { + Some(ElementKind::ScaleBar { text_size, .. }) => (text_size / bar_pt).max(1.0), + _ => 1.0, + }; + let (sh, nh) = (if sheet { 8.0 * k } else { 6.0 } * text_growth, pitch(small_pt) + 0.5); // The scale bar's box at a scale: the size of its bar and labels and of the scale under them, // with the padding (#1379). The bar is the one a box 30 % of the frame's width (25 mm at least) // would draw, which sets its length and divisions. The box is the narrowest that draws that same // bar: the renderer gives a bar at most 85 % of its box, so the box is at least the bar's length // over 0.85. - let mut scale_bar = ElementKind::scale_bar(frame); - if let ElementKind::ScaleBar { text_size, .. } = &mut scale_bar { - *text_size = bar_pt; + if let Some(ElementKind::ScaleBar { frame: of, .. }) = &mut scale_kind { + *of = frame; } + // Nothing, without a scale bar. let scale_box = |ground_per_pt: f64, scale: f64| { + let Some(bar) = &scale_kind else { return (0.0, 0.0) }; let text = ("{scale}", small_pt, false); - let w = scale_box_width(ground_per_pt, scale, fw, &scale_bar, comma, text); - (w, sh + nh) + (scale_box_width(ground_per_pt, scale, fw, bar, comma, text), sh + nh) }; let ground_per_pt = |s: &Session, center: Coord, scale: f64| { s.map().ground_res_at(&rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0)) @@ -1056,9 +1076,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu if arrow { surrounds.push((Surround::Arrow, aw, ah)); } else if north_arrow.is_none() { - warnings.push(format!( - "no north arrow: the extent spans {CONTINENTAL_DEG:.0}° or more, where the graticule gives north; \"northArrow\": \"always\" draws one" - )); + let north = if step.is_some() { "where the graticule gives north" } else { "where one arrow can't point north across the frame" }; + warnings + .push(format!("no north arrow: the extent spans {CONTINENTAL_DEG:.0}° or more, {north}; \"northArrow\": \"always\" draws one")); } // The topmost visible raster with a colour scale that the legend doesn't list by its classes // gets a colorbar, under the legend in its box (a map whose theme is a raster on a ramp has its @@ -1112,10 +1132,12 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // Its width is set once the frame's centre and scale are settled, below; nothing reads it before. // A globe seen whole has none: its scale holds at its centre only, falling to nothing at its // rim, so a bar would read true nowhere else (#2337). - if whole_globe { - warnings.push("no scale bar: the map shows the whole globe, whose scale holds at its centre only".into()); - } else { - surrounds.push((Surround::Scale, 0.0, sh + nh)); + if scale_kind.is_some() { + if whole_globe { + warnings.push("no scale bar: the map shows the whole globe, whose scale holds at its centre only".into()); + } else { + surrounds.push((Surround::Scale, 0.0, sh + nh)); + } } // A corner's rectangle for a surround `w` × `h`. let at = |corner: usize, w: f64, h: f64| { @@ -1708,7 +1730,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } if let Some(r) = spot_of(Surround::Arrow) { placed.push(("north arrow", r)); - l.add("North Arrow", r, ElementKind::north_arrow(frame)); + if let ElementKind::NorthArrow { frame: of, .. } = &mut arrow_kind { + *of = frame; + } + l.add("North Arrow", r, arrow_kind); } // In a panel, the legend under the locator, as tall as it needs within what is left. let legend_rect = match column { @@ -1734,7 +1759,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let legend_bare = legend_rect.filter(|_| column.is_none() && !style.cards() && veiled.is_none() && !legend_box_always).is_some_and(|r| { covered(r) == 0.0 - && !graticule_crosses(s, center, scale, (fw, fh), (r.0 - fx, r.1 - fy, r.2, r.3), step) + // A measured grid's lines aren't traced, so the box stays under one. + && grid.as_ref().is_none_or(|_| { + step.is_some_and(|step| !graticule_crosses(s, center, scale, (fw, fh), (r.0 - fx, r.1 - fy, r.2, r.3), step)) + }) && crate::render::layout::frame_plain_under(s.map_mut(), center, scale, (fw, fh), (r.0 - fx, r.1 - fy, r.2, r.3), 384) }); if let Some(r) = legend_rect { @@ -1802,10 +1830,11 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu ); } } - if let Some((sx, sy, w, h)) = spot_of(Surround::Scale) { + let mut bar_id = None; + if let (Some((sx, sy, w, h)), Some(bar)) = (spot_of(Surround::Scale), scale_kind) { placed.push(("scale bar", (sx, sy, w, h))); l.add("Scale Box", (sx, sy, w, sh + nh), surround_box(paper)); - l.add("Scale Bar", (sx, sy, w, sh), scale_bar); + bar_id = Some(l.add("Scale Bar", (sx, sy, w, sh), bar)); l.add("Scale", (sx, sy + sh, w, nh), pub_text(Broken::from(vec!["{scale}".to_string()]), small_pt, ink, false, TextAlign::Center)); } // What placing couldn't avoid: a surround over the map's drawing while a clearly freer corner @@ -1872,6 +1901,15 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu s.notify(cut, false); } say_layout_text_statistics(s, i); + // What a scale bar or a grid asked for in other than its default look loses or has to say. + let asked = |key: &str| p.get(key).is_some_and(Value::is_object); + if let Some(bar) = bar_id.filter(|_| asked("scaleBar")) { + let losses: Vec<_> = text_fit_loss(s, i, bar).into_iter().collect(); + warnings.extend(rustgis_render::layout::scale_bar_fit_notices(&losses)); + } + if let Some(crs) = p.get("grid").and_then(|g| g.get("crs")).and_then(Value::as_str) { + crate::cmd::say_crs_note(s, crs); + } let locator = locator_map.map(|(map, ..)| map); Ok( json!({"layout": i, "name": name, "profile": profile.id, "page": [w, h], "scale": scale, "grid": step, "locator": locator, "style": style.code(), "arrangement": arrangement_used, "legendColumns": legend_cols, "mapShift": [map_shift.0, map_shift.1], "veiled": veiled.is_some(), "legendBox": legend_rect.is_some() && !legend_bare, "elements": elements, "moved": moved, "coverage": coverage_written, "warnings": warnings}), @@ -1918,20 +1956,6 @@ pub(in crate::cmd::layout) fn publication_flag(p: &Value, key: &str) -> Result Result, String> { - match p.get("northArrow").filter(|v| !v.is_null()) { - None => Ok(None), - Some(v) => match v.as_str().map(str::trim) { - Some("auto") => Ok(None), - Some("always") => Ok(Some(true)), - Some("none") => Ok(Some(false)), - _ => Err("northArrow is \"auto\", \"always\" or \"none\"".into()), - }, - } -} - /// The span in degrees, on its longer side, from which a publication's extent is continental: its /// graticule's meridians then turn too far across the frame for one north arrow to point north /// everywhere, and they give north themselves (#1379). diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs new file mode 100644 index 0000000000..d8da57b1d1 --- /dev/null +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -0,0 +1,115 @@ +//! The parts of a publication a call can leave out or set up (#3094): `"none"`, or an object of +//! the options its element takes elsewhere. + +use super::*; + +/// A frame grid's options, as `layout.addElement` takes them. +const GRID_KEYS: &[&str] = &[ + "type", + "crs", + "step", + "short", + "mgrs", + "color", + "width", + "labels", + "labelSize", + "style", + "tickLength", + "format", + "hemisphere", + "edges", + "labelOrientation", +]; + +/// A scale bar's options, as `layout.update` takes them. +const SCALE_BAR_PART_KEYS: &[&str] = &[ + "style", + "units", + "divisions", + "color", + "fill", + "textSize", + "decimals", + "subdivisions", + "divisionsBeforeZero", + "labelPosition", + "unitLabel", + "unitLabelPosition", + "fit", +]; + +/// A north arrow's: when it is drawn, and its look as `layout.update` takes it. +const NORTH_ARROW_KEYS: &[&str] = &["show", "style", "fill", "outline"]; + +/// The options object `v` given as `key`, without its `null`s, which leave the default; a key +/// not in `keys` is refused. +fn options(key: &str, v: &Value, keys: &[&str]) -> Result, String> { + let Some(given) = v.as_object() else { return Ok(None) }; + let given: serde_json::Map = given.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(); + if let Some(other) = given.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(format!("{key} takes no \"{other}\" (it reads {})", keys.join(", "))); + } + Ok(Some(Value::Object(given))) +} + +/// The part `key` of `p`, `default` unless given: `None` for `"none"`, else `default` with what +/// `set` reads from its options. +fn part(p: &Value, key: &str, keys: &[&str], default: T, set: impl FnOnce(&Value, T) -> Result) -> Result, String> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(Some(default)) }; + if v.as_str().is_some_and(|t| t.trim() == "none") { + return Ok(None); + } + match options(key, v, keys)? { + Some(o) => set(&o, default).map(Some), + None => Err(format!("{key} is \"none\" or an object with any of {}", keys.join(", "))), + } +} + +/// The map frame's grid: `default` with the `"grid"` options over it, or none. A graticule given +/// no step keeps the default's, which the reference text says. +pub(super) fn publication_grid(p: &Value, default: Grid) -> Result, String> { + let step = default.step; + part(p, "grid", GRID_KEYS, default, |o, base| { + let mut grid = grid_params(o, base)?; + if grid.kind == GridKind::Graticule && grid.step <= 0.0 { + grid.step = step; + } + Ok(grid) + }) +} + +/// The scale bar, its text `text_pt` points unless `"scaleBar"` says otherwise, or none. Its +/// frame is set once there is one. +pub(super) fn publication_scale_bar(p: &Value, text_pt: f64) -> Result, String> { + let mut default = ElementKind::scale_bar(0); + if let ElementKind::ScaleBar { text_size, .. } = &mut default { + *text_size = text_pt; + } + part(p, "scaleBar", SCALE_BAR_PART_KEYS, default, |o, base| Ok(restyle(&base, o)?.unwrap_or(base))) +} + +/// When a publication draws its north arrow, and the arrow: `Some(true)` always ("always"), +/// `Some(false)` never ("none"), `None` left to the extent ("auto", the default: none at a +/// continental span, #1379). An object gives its look, with "show" for when. Its frame is set once +/// there is one. +pub(super) fn publication_north_arrow(p: &Value) -> Result<(Option, ElementKind), String> { + let refused = || format!("northArrow is \"auto\", \"always\" or \"none\", or an object with any of {}", NORTH_ARROW_KEYS.join(", ")); + let arrow = ElementKind::north_arrow(0); + let Some(v) = p.get("northArrow").filter(|v| !v.is_null()) else { return Ok((None, arrow)) }; + if let Some(o) = options("northArrow", v, NORTH_ARROW_KEYS)? { + let show = match o.get("show").map(|v| v.as_str().map(str::trim)) { + None | Some(Some("auto")) => None, + Some(Some("always")) => Some(true), + Some(_) => return Err("northArrow's show is \"auto\" or \"always\"; \"northArrow\": \"none\" leaves it out".into()), + }; + let arrow = restyle(&arrow, &o)?.unwrap_or(arrow); + return Ok((show, arrow)); + } + match v.as_str().map(str::trim) { + Some("auto") => Ok((None, arrow)), + Some("always") => Ok((Some(true), arrow)), + Some("none") => Ok((Some(false), arrow)), + _ => Err(refused()), + } +} diff --git a/crates/engine/src/cmd/layout/publication/placement.rs b/crates/engine/src/cmd/layout/publication/placement.rs index 110af59308..5e305ab23a 100644 --- a/crates/engine/src/cmd/layout/publication/placement.rs +++ b/crates/engine/src/cmd/layout/publication/placement.rs @@ -106,8 +106,8 @@ pub(crate) fn veil_panel( // The locator and the arrow side by side, with a gap between them only when both are there. let between = if locator.is_some() && arrow.is_some() { gap } else { 0.0 }; let top = (locator.map_or(0.0, |side| side + between) + aw, locator.unwrap_or(0.0).max(ah)); - // The gap over the scale bar only when something sits above it. - let lead = if top.1 > 0.0 { gap } else { 0.0 }; + // The gap over the scale bar only when there is one and something sits above it. + let lead = if top.1 > 0.0 && scale.1 > 0.0 { gap } else { 0.0 }; let group = (top.0.max(scale.0), top.1 + lead + scale.1); let beside = legend.0 + gap + group.0 <= bw && legend.1.max(group.1) <= bh; let over = legend.0.max(group.0) <= bw && legend.1 + gap + group.1 <= bh; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index fc29430599..8464683d4c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -125,6 +125,7 @@ pub const CAPABILITIES: &[&str] = &[ "tile-resampling", "layout-page-color", "layout-text-statistics", + "layout-publication-parts", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 144fcbdba1..71498136e5 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -183,8 +183,24 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("tile-resampling", command_resamples_tiles), ("layout-page-color", command_colours_the_page), ("layout-text-statistics", command_uses_text_statistics), + ("layout-publication-parts", command_sets_publication_parts), ]; +/// A saved `layout.publication` that leaves out or sets up its grid, scale bar or north arrow +/// (#3094): an older reader ignores `grid` and `scaleBar`, making the default sheet, and refuses +/// a `northArrow` object. `null` and an object giving nothing ask for the default. +fn command_sets_publication_parts(id: &str, params: &Value) -> bool { + let sets = |v: &Value| v.as_object().is_none_or(|o| o.values().any(|v| !v.is_null())); + match id { + "layout.publication" => { + ["grid", "scaleBar"].into_iter().any(|k| params.get(k).is_some_and(|v| !v.is_null() && sets(v))) + || params.get("northArrow").is_some_and(|v| v.is_object() && sets(v)) + } + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_publication_parts)), + _ => false, + } +} + /// A saved `labels.placement` that has a class remove duplicates, read as the command reads it /// (#2847): an older reader runs it without the key, saying nothing, so every label would show. /// False or null is what an older reader keeps. @@ -1373,6 +1389,7 @@ mod tests { (&["tile-resampling"], "map.addTiles", json!({"resampling": "nearest"})), (&["layout-page-color"], "layout.page", json!({"color": "#0B1B2B"})), (&["layout-text-statistics"], "layout.addElement", json!({"kind": "text", "text": "{count:Cities}"})), + (&["layout-publication-parts"], "layout.publication", json!({"grid": "none"})), // An SVG image is a picture marker as well, in a node as in a saved command. (&["picture-markers", "svg-markers"], "layer.marker", json!({"image": svg})), (&[], "buffer", json!({"input": "Cities", "distance": 1})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e373d11c5c..fc48da918d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -103,6 +103,9 @@ mod layout_title; #[path = "tests/layout_removed_layer.rs"] mod layout_removed_layer; +#[path = "tests/layout_publication_parts.rs"] +mod layout_publication_parts; + #[path = "tests/sde_connections.rs"] mod sde_connections; diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs new file mode 100644 index 0000000000..eab94d3cbb --- /dev/null +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -0,0 +1,223 @@ +//! A publication's grid, scale bar and north arrow left out or set up by `layout.publication` +//! (#3094). + +use super::*; +use rustgis_map::layout::{ArrowStyle, Element, ElementKind, GRID_LABEL_PT, Grid, GridKind, ScaleBarStyle, ScaleUnits}; + +/// An A4 sheet of open sea with `parts` added to the call: with nothing to cover, each surround +/// stays in its home corner. +fn sheet(parts: Value) -> (Session, Value) { + let mut s = world(); + let r = publish(&mut s, parts).unwrap(); + (s, r) +} + +fn publish(s: &mut Session, parts: Value) -> Result { + let mut p = json!({"profile": "a4-portrait", "extent": [-30.0, -30.0, -20.0, -22.0]}); + p.as_object_mut().unwrap().extend(parts.as_object().unwrap().clone()); + s.run("layout.publication", &p) +} + +fn find<'a>(s: &'a Session, name: &str) -> Option<&'a Element> { + s.project.layouts[0].elements.iter().find(|e| e.name == name) +} + +fn grid(s: &Session) -> Option { + match &find(s, "Map Frame").unwrap().kind { + ElementKind::MapFrame { grid, .. } => grid.clone(), + k => panic!("{k:?}"), + } +} + +/// Every text of the layout, its lines joined. +fn texts(s: &Session) -> String { + let text = |e: &Element| match &e.kind { + ElementKind::Text { text, .. } => Some(text.replace('\n', " ")), + _ => None, + }; + s.project.layouts[0].elements.iter().filter_map(text).collect::>().join(" | ") +} + +/// The room from the north arrow to the frame's right edge: the margin, and the grid's label strip. +fn right_room(s: &Session) -> f64 { + let (frame, arrow) = (find(s, "Map Frame").unwrap(), find(s, "North Arrow").unwrap()); + frame.x + frame.w - (arrow.x + arrow.w) +} + +/// The margin of an A4 sheet's surrounds from its frame's edge, in mm. +const MARGIN: f64 = 4.0; + +#[test] +fn a_publication_given_empty_parts_is_the_default_one() { + let elements = |parts: Value| serde_json::to_value(&sheet(parts).0.project.layouts[0].elements).unwrap(); + let default = elements(json!({})); + assert_eq!(elements(json!({"grid": null, "scaleBar": null, "northArrow": null})), default); + assert_eq!(elements(json!({"grid": {}, "scaleBar": {}, "northArrow": {}})), default); + assert_eq!(elements(json!({"grid": {"step": null}, "scaleBar": {"textSize": null}, "northArrow": {"show": null}})), default); +} + +#[test] +fn a_publication_without_a_grid_keeps_no_label_strips_and_names_no_graticule() { + let (s, r) = sheet(json!({"grid": "none"})); + assert_eq!(grid(&s), None); + assert_eq!(r["grid"], Value::Null); + assert!(!texts(&s).contains("Graticule") && texts(&s).contains("Datum:"), "{}", texts(&s)); + assert!((right_room(&s) - MARGIN).abs() < 1e-6, "{}", right_room(&s)); + let (default, _) = sheet(json!({})); + assert!(right_room(&default) > MARGIN + 1.0); +} + +#[test] +fn a_grid_token_typed_by_the_caller_says_a_dash_without_a_graticule() { + let (s, _) = sheet(json!({"grid": "none", "reference": ["Lines every {grid}"]})); + assert!(texts(&s).contains("Lines every —"), "{}", texts(&s)); +} + +#[test] +fn a_publication_grid_takes_its_step_and_the_reference_says_it() { + let (s, r) = sheet(json!({"grid": {"step": 5}})); + assert_eq!(grid(&s).unwrap().step, 5.0); + assert_eq!(r["grid"], json!(5.0)); + assert!(texts(&s).contains("Graticule: 5°"), "{}", texts(&s)); +} + +#[test] +fn a_publication_measured_grid_picks_its_step_and_is_not_called_a_graticule() { + let (s, r) = sheet(json!({"grid": {"type": "measured"}})); + let g = grid(&s).unwrap(); + assert_eq!((g.kind, g.step), (GridKind::Measured, 0.0)); + assert_eq!(r["grid"], Value::Null); + assert!(!texts(&s).contains("Graticule"), "{}", texts(&s)); +} + +#[test] +fn a_publication_grid_keeps_label_strips_only_where_it_labels() { + let strip = right_room(&sheet(json!({})).0) - MARGIN; + let (unlabelled, _) = sheet(json!({"grid": {"labels": false}})); + assert!(grid(&unlabelled).is_some()); + assert!((right_room(&unlabelled) - MARGIN).abs() < 1e-6); + let (bottom, _) = sheet(json!({"grid": {"edges": ["bottom"]}})); + assert!((right_room(&bottom) - MARGIN).abs() < 1e-6); + let (frame, bar) = (find(&bottom, "Map Frame").unwrap(), find(&bottom, "Scale").unwrap()); + assert!(frame.y + frame.h - (bar.y + bar.h) > MARGIN + 1.0); + let (big, _) = sheet(json!({"grid": {"labelSize": 2.0 * GRID_LABEL_PT}})); + assert!((right_room(&big) - MARGIN - 2.0 * strip).abs() < 1e-6, "{} {strip}", right_room(&big)); +} + +#[test] +fn a_publication_without_a_scale_bar_leaves_the_other_surrounds_in_place() { + let (default, _) = sheet(json!({})); + let (s, r) = sheet(json!({"scaleBar": "none"})); + for name in ["Scale Box", "Scale Bar", "Scale"] { + assert!(find(&s, name).is_none(), "{name}"); + } + for name in ["North Arrow", "Legend Box"] { + let at = |s: &Session| find(s, name).map(|e| (e.x, e.y, e.w, e.h)); + assert_eq!(at(&s), at(&default), "{name}"); + } + assert!(!r["warnings"].to_string().contains("scale bar"), "{}", r["warnings"]); +} + +#[test] +fn a_publication_scale_bar_takes_its_options_and_its_box_is_sized_for_it() { + let (s, _) = sheet(json!({"scaleBar": {"units": "miles", "style": "line", "divisions": 3}})); + let bar = find(&s, "Scale Bar").unwrap(); + assert!( + matches!(bar.kind, ElementKind::ScaleBar { units: ScaleUnits::Miles, style: ScaleBarStyle::Line, divisions: 3, .. }), + "{:?}", + bar.kind + ); + assert_eq!(find(&s, "Scale Box").unwrap().w, bar.w); +} + +#[test] +fn a_publication_scale_bar_given_a_larger_text_gets_the_height_for_it() { + let (default, _) = sheet(json!({})); + let (s, r) = sheet(json!({"scaleBar": {"textSize": 14}})); + let bar = find(&s, "Scale Bar").unwrap(); + assert!(matches!(bar.kind, ElementKind::ScaleBar { text_size, .. } if text_size == 14.0), "{:?}", bar.kind); + assert!(bar.h > find(&default, "Scale Bar").unwrap().h); + assert!(!r["warnings"].to_string().contains("scale bar"), "{}", r["warnings"]); +} + +#[test] +fn a_whole_globe_publication_has_no_scale_bar_whatever_its_options() { + let mut s = world(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + let r = s.run("layout.publication", &json!({"scaleBar": {"units": "miles"}})).unwrap(); + assert!(find(&s, "Scale Bar").is_none()); + assert!(r["warnings"].to_string().contains("no scale bar: the map shows the whole globe"), "{}", r["warnings"]); + let r = s.run("layout.publication", &json!({"scaleBar": "none"})).unwrap(); + assert!(!r["warnings"].to_string().contains("no scale bar"), "{}", r["warnings"]); +} + +#[test] +fn a_publication_north_arrow_takes_its_style_and_when_to_show() { + let (s, _) = sheet(json!({"northArrow": {"style": "compass"}})); + assert!(matches!(find(&s, "North Arrow").unwrap().kind, ElementKind::NorthArrow { style: ArrowStyle::Compass, .. })); + // A continental span draws none unless asked "always". + let wide = |arrow: Value| { + let mut s = world(); + s.run("layout.publication", &json!({"extent": [-60.0, -30.0, -20.0, 0.0], "northArrow": arrow})).unwrap(); + find(&s, "North Arrow").map(|e| e.kind.clone()) + }; + assert_eq!(wide(json!({"style": "star"})), None); + assert_eq!(wide(json!("auto")), None); + assert!(wide(json!("always")).is_some()); + let shown = wide(json!({"show": "always", "style": "star"})); + assert!(matches!(shown, Some(ElementKind::NorthArrow { style: ArrowStyle::Star, .. })), "{shown:?}"); + assert!(find(&sheet(json!({"northArrow": "none"})).0, "North Arrow").is_none()); +} + +#[test] +fn a_publication_part_given_wrong_is_refused_and_nothing_is_made() { + for (parts, said) in [ + (json!({"grid": {"style": "wavy"}}), "unknown grid style"), + (json!({"grid": {"foo": 1}}), "grid takes no \"foo\""), + (json!({"grid": 5}), "grid is \"none\""), + (json!({"grid": true}), "grid is \"none\""), + (json!({"scaleBar": {"units": "parsecs"}}), "unknown units"), + (json!({"scaleBar": {"step": 1}}), "scaleBar takes no \"step\""), + (json!({"scaleBar": "auto"}), "scaleBar is \"none\""), + (json!({"northArrow": {"show": "none"}}), "northArrow's show"), + (json!({"northArrow": {"style": "x"}}), "unknown north arrow style"), + (json!({"northArrow": {"size": 2}}), "northArrow takes no \"size\""), + (json!({"northArrow": "yes"}), "northArrow is \"auto\""), + ] { + let mut s = world(); + let maps = s.project.maps.len(); + let err = publish(&mut s, parts.clone()).unwrap_err(); + assert!(err.contains(said), "{parts}: {err}"); + assert_eq!((s.project.layouts.len(), s.project.maps.len()), (0, maps), "{parts}"); + } +} + +#[test] +fn a_saved_publication_that_sets_a_part_requires_its_capability() { + let requires = |params: Value| { + let mut s = world(); + s.project + .models + .push(serde_json::from_value(json!({"name": "Sheet", "steps": [{"tool": "layout.publication", "params": params}]})).unwrap()); + serde_json::to_value(&s.project).unwrap()["requires"].to_string().contains("layout-publication-parts") + }; + for params in [ + json!({"grid": "none"}), + json!({"grid": {"step": 5}}), + json!({"scaleBar": "none"}), + json!({"scaleBar": {"units": "miles"}}), + json!({"northArrow": {"style": "star"}}), + ] { + assert!(requires(params.clone()), "{params}"); + } + for params in [json!({}), json!({"grid": null, "scaleBar": {}}), json!({"northArrow": "always"}), json!({"northArrow": {"show": null}})] + { + assert!(!requires(params.clone()), "{params}"); + } +} + +#[test] +fn the_publication_parts_fixture_opens_and_keeps_its_requirement() { + let fixture = crate::Project::from_json(include_str!("../../../../schema/fixtures/layout_publication_parts.rgis")).unwrap(); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["layout-publication-parts"])); +} diff --git a/docs/maintaining.md b/docs/maintaining.md index a417d00820..2000e730a6 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -342,6 +342,11 @@ transformation the definition can't hold, or no definition. An older reader refu instead of misplacing the layer. Others need nothing: an older reader opens them by the definition and, saving them again, drops only the WKT. +A saved `layout.publication` that leaves out or sets up a part of the sheet (`grid` or +`scaleBar` as `"none"` or an object that gives something, or `northArrow` as such an object, +#3094) requires `layout-publication-parts`, so an older reader refuses it instead of making the +default sheet. `null`, `{}` and the north arrow's `"auto"`, `"always"` and `"none"` need nothing. + ## New dependencies A proposal for a dependency answers: diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 0af58791e4..dcb74d8ad8 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -141,6 +141,14 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu centred as near it as fits, and a warning says where. With an `extent`, a sheet on the globe is laid out as on a flat map. In any frame on the globe, the light space around the globe is room for the surrounds, as the blank page is. + - **Grid, scale bar and north arrow**: `"grid"`, `"scaleBar"` and `"northArrow"` each take + `"none"` to leave that part out, or an object with its options, and a key the part doesn't + read is refused. `"grid"` takes a frame grid's options (`{"step": 5}`, + `{"type": "measured"}`, `{"edges": ["bottom"]}`); the strips inside the frame follow its + labels, edges and `labelSize`, and without a graticule the default reference text names none + (a `{grid}` you type reads `—`). `"scaleBar"` takes a scale bar's options + (`{"units": "miles", "style": "line"}`), its box growing with a larger `textSize`. + `"northArrow"` also takes `{"show": "auto"|"always", "style", "fill", "outline"}`. - **Legend box**: over the map, the legend's box is left clear where the map shows nothing under it but its light plain paper or water: no layer, label, context layer, basemap shape or graticule line, no web tiles, and no veil. Dark basemaps keep a white backing so the dark legend text diff --git a/schema/fixtures/layout_publication_parts.rgis b/schema/fixtures/layout_publication_parts.rgis new file mode 100644 index 0000000000..3c8024fc9d --- /dev/null +++ b/schema/fixtures/layout_publication_parts.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Publication parts","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[{"name":"Plain sheet","steps":[{"tool":"layout.publication","params":{"grid":"none","scaleBar":{"units":"miles"}}}]}],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[],"requires":["layout-publication-parts"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index ebc9065646..a4e299ef29 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1286,7 +1286,8 @@ "label-duplicates", "tile-resampling", "layout-page-color", - "layout-text-statistics" + "layout-text-statistics", + "layout-publication-parts" ], "type": "string" }, @@ -1401,7 +1402,8 @@ "label-duplicates", "tile-resampling", "layout-page-color", - "layout-text-statistics" + "layout-text-statistics", + "layout-publication-parts" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From a460d03cfe09609003c19cd01037024e2b063ebf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 04:26:46 -0500 Subject: [PATCH 2/7] docs(assistant): name the publication's grid, scale bar and north arrow options --- crates/assistant/skills/print-layout/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index 0e2c092285..d89aff30f0 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -10,7 +10,7 @@ description: Make a printable page layout — map frame, title, legend, north ar (a page size alone, `"a4"`, `"letter"`, `"legal"`, `"tabloid"`, `"a5"` to `"a0"`, for a sheet turned to the area's shape, or with its orientation, `"a4-portrait"`, `"letter-landscape"`, … to choose; `"figure-1col"`, `"thesis-full"`, … for a figure), the `"extent"` to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`, a `"locator"` (`"globe"`: the visible polygon layers held in the project, not streamed ones, over the basemap; `"inset"` or `"none"`; when omitted, `"globe"` on a sheet and `"none"` on a figure), and `"decimal": ","` for a map in a language with a decimal comma. A sheet's `"style"` arranges it: `"classic"` (the default), `"banner"`, `"panel"`, `"editorial"`, `"modular"` or `"poster"` (for a poster-like sheet), with an `"accent"` colour as `"#RRGGBB"`. Its surrounds (locator, north arrow, legend, scale bar) start from an `"arrangement"` (`"classic"`, `"mirrored"`, `"legendRight"`, `"legendTop"`, or a corner for each; `"best"`, the default, tries the user's favourite, set with `layout.arrangement`, and the others), and one over the data moves to the freest place in the frame, the largest first (the legend, as a rule); read its `"arrangement"`, `"moved"` and `"warnings"`. It places the frame at a round scale, the - graticule, legend (a long one in up to three columns), scale bar and north arrow, and wraps the footer. Its result lists every element's id and name + graticule, legend (a long one in up to three columns), scale bar and north arrow, and wraps the footer. `"grid"`, `"scaleBar"` and `"northArrow"` take `"none"` to leave that part out, or an object of its options (the grid's `"step"` or `"type"`, the bar's `"units"` or `"style"`, the arrow's `"style"` and `"show"`). Its result lists every element's id and name (`"elements"`), so skip to step 5 to adjust them. Otherwise, `layout.new` `{"name": N, "page": "letter"|"a4"|…, "orientation": "landscape"|"portrait"}` creates the layout and opens it. From 46e544cec1e86ce449aada645095b042e24b884c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 04:39:10 -0500 Subject: [PATCH 3/7] refactor(layout): share the scale bar's keys and say publication sizes are absolute --- crates/engine/src/cmd/layout.rs | 4 ++-- .../engine/src/cmd/layout/publication/mod.rs | 11 +++++----- .../src/cmd/layout/publication/parts.rs | 21 +++---------------- crates/engine/src/cmd/layout/update.rs | 9 ++++---- .../src/tests/layout_publication_parts.rs | 17 +++++++++++++++ docs/user-guide/layouts.md | 3 ++- 6 files changed, 34 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index ea8b8dc799..6e8fb31062 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -81,8 +81,8 @@ pub fn commands() -> Vec { r#""veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "#, r#""contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "#, r#""northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none" | {"show"?: "auto" | "always", "style"?, "fill"?, "outline"? as layout.update takes a north arrow's}, "#, - r#""grid"?: "none" (no grid on the map frame, and no label strips inside it) | {a frame grid's options as layout.addElement takes them: type, crs, step, short, mgrs, color, width, labels, labelSize, style, tickLength, format, hemisphere, edges, labelOrientation} over the default graticule (its step by the extent, labelled left and bottom, on a sheet all round); the label strips follow its labels, edges and labelSize, and without a graticule the default reference names none and {grid} in a text reads "—", "#, - r#""scaleBar"?: "none" | {a scale bar's options as layout.update takes them: style, units, divisions, color, fill, textSize, decimals, subdivisions, divisionsBeforeZero, labelPosition, unitLabel, unitLabelPosition, fit} (none on a globe shown whole, whatever is asked), "#, + r#""grid"?: "none" (no grid on the map frame, and no label strips inside it) | {a frame grid's options as layout.addElement takes them: type, crs, step, short, mgrs, color, width, labels, labelSize, style, tickLength, format, hemisphere, edges, labelOrientation} over the default graticule (its step by the extent, labelled left and bottom, on a sheet all round); the label strips follow its labels, edges and labelSize (in points as given, not scaled with the sheet), and without a graticule the default reference names none and {grid} in a text reads "—", "#, + r#""scaleBar"?: "none" | {a scale bar's options as layout.update takes them: style, units, divisions, color, fill, textSize, decimals, subdivisions, divisionsBeforeZero, labelPosition, unitLabel, unitLabelPosition, fit; textSize in points as given, not scaled with the sheet} (none on a globe shown whole, whatever is asked), "#, r#""legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "#, r#""style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "#, r#""accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "#, diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 8395b13f41..fdd5fd6d22 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -183,8 +183,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let room_side = if labelled.left || labelled.right { LABEL_ROOM_SIDE * strip_scale } else { 0.0 }; let room_end = if labelled.top || labelled.bottom { LABEL_ROOM_END * strip_scale } else { 0.0 }; let reference = reference.unwrap_or_else(|| { - let datum = if step.is_some() { "Datum: {datum} · Graticule: {grid}" } else { "Datum: {datum}" }; - vec!["Projection: {projection}".into(), datum.into()] + let line = if step.is_some() { "Datum: {datum} · Graticule: {grid}" } else { "Datum: {datum}" }; + vec!["Projection: {projection}".into(), line.into()] }); let step_said = step.map_or_else(|| "—".to_string(), step_text); let fill = |t: &str| t.replace("{projection}", &projection).replace("{datum}", &datum).replace("{grid}", &step_said); @@ -769,7 +769,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // edges), on both sides so it stays centred, and its labels cover none of it. let (strip_w, strip_h) = (2.0 * room_side, 2.0 * room_end); if fw - strip_w < fw / 2.0 || fh - strip_h < fh / 2.0 { - warnings.push("the frame is too small to keep its graticule's labels off the map's edges: they may cover them".into()); + warnings.push("the frame is too small to keep its grid's labels off the map's edges: they may cover them".into()); } let (inner_w, inner_h) = ((fw - strip_w).max(fw / 2.0), (fh - strip_h).max(fh / 2.0)); let (center, scale) = if whole_globe { @@ -821,7 +821,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu pitch: 0.0, }, ); - // Over the map, clear of the graticule's labels (drawn inside the frame along its labelled + // Over the map, clear of the grid's labels (drawn inside the frame along its labelled // edges): the north arrow, the legend sized to what it lists, the scale bar with the numeric // scale under it, and the locator, each on a pale box. Each takes the corner where it covers // the least of what the map draws; by default (and when it makes no difference) the locator at @@ -1045,7 +1045,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu Some(ElementKind::ScaleBar { text_size, .. }) => (text_size / bar_pt).max(1.0), _ => 1.0, }; - let (sh, nh) = (if sheet { 8.0 * k } else { 6.0 } * text_growth, pitch(small_pt) + 0.5); + let bar_h = if sheet { 8.0 * k } else { 6.0 }; + let (sh, nh) = (bar_h * text_growth, pitch(small_pt) + 0.5); // The scale bar's box at a scale: the size of its bar and labels and of the scale under them, // with the padding (#1379). The bar is the one a box 30 % of the frame's width (25 mm at least) // would draw, which sets its length and divisions. The box is the narrowest that draws that same diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index d8da57b1d1..f3ad7f80ec 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -22,23 +22,6 @@ const GRID_KEYS: &[&str] = &[ "labelOrientation", ]; -/// A scale bar's options, as `layout.update` takes them. -const SCALE_BAR_PART_KEYS: &[&str] = &[ - "style", - "units", - "divisions", - "color", - "fill", - "textSize", - "decimals", - "subdivisions", - "divisionsBeforeZero", - "labelPosition", - "unitLabel", - "unitLabelPosition", - "fit", -]; - /// A north arrow's: when it is drawn, and its look as `layout.update` takes it. const NORTH_ARROW_KEYS: &[&str] = &["show", "style", "fill", "outline"]; @@ -86,7 +69,9 @@ pub(super) fn publication_scale_bar(p: &Value, text_pt: f64) -> Result = SCALE_BAR_LOOK_KEYS.iter().chain(&SCALE_BAR_KEYS).copied().collect(); + part(p, "scaleBar", &keys, default, |o, base| Ok(restyle(&base, o)?.unwrap_or(base))) } /// When a publication draws its north arrow, and the arrow: `Some(true)` always ("always"), diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 8ddeb28114..6c647b2b18 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -2,6 +2,9 @@ use super::*; +/// A scale bar's keys beyond its details ([`SCALE_BAR_KEYS`]). +pub(in crate::cmd::layout) const SCALE_BAR_LOOK_KEYS: [&str; 7] = ["style", "units", "divisions", "color", "fill", "textSize", "decimals"]; + /// A north arrow or scale bar with the options in `p` over `kind`'s; `None` for other elements /// or when `p` has none. A bad value is an error, leaving nothing changed. pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result, String> { @@ -38,11 +41,7 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result { - if ["style", "units", "divisions", "color", "fill", "textSize", "decimals"] - .iter() - .chain(SCALE_BAR_KEYS.iter()) - .all(|k| p.get(k).is_none()) - { + if SCALE_BAR_LOOK_KEYS.iter().chain(SCALE_BAR_KEYS.iter()).all(|k| p.get(k).is_none()) { return Ok(None); } let style = match ps(p, "style") { diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index eab94d3cbb..060fb2f878 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -221,3 +221,20 @@ fn the_publication_parts_fixture_opens_and_keeps_its_requirement() { let fixture = crate::Project::from_json(include_str!("../../../../schema/fixtures/layout_publication_parts.rgis")).unwrap(); assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["layout-publication-parts"])); } + +#[test] +fn a_publication_scale_bar_too_large_for_the_sheet_says_it_does_not_fit() { + let (_, r) = sheet(json!({"scaleBar": {"textSize": 100}})); + assert!(r["warnings"].to_string().contains("Scale bar \\\"Scale Bar\\\""), "{}", r["warnings"]); +} + +#[test] +fn a_publication_grid_says_what_its_typed_coordinate_system_loses() { + let mut s = world(); + // UTM 17N on NAD 27, bound to WGS 84 by an NTv2 grid, which isn't applied. + let crs = r#"BOUNDCRS[SOURCECRS[PROJCRS["unknown",BASEGEOGCRS["unknown",DATUM["North American Datum 1927",ELLIPSOID["Clarke 1866",6378206.4,294.978698213898,LENGTHUNIT["metre",1]],ID["EPSG",6267]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]]],CONVERSION["UTM zone 17N",METHOD["Transverse Mercator",ID["EPSG",9807]],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8801]],PARAMETER["Longitude of natural origin",-81,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1],ID["EPSG",8805]],PARAMETER["False easting",500000,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",0,LENGTHUNIT["metre",1],ID["EPSG",8807]],ID["EPSG",16017]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1,ID["EPSG",9001]]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1,ID["EPSG",9001]]]]],TARGETCRS[GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["latitude",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["longitude",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4326]]],ABRIDGEDTRANSFORMATION["unknown to WGS84",METHOD["NTv2",ID["EPSG",9615]],PARAMETERFILE["Latitude and longitude difference file","conus",ID["EPSG",8656]]]]"#; + let mark = s.notice_mark(); + publish(&mut s, json!({"grid": {"type": "measured", "crs": crs}})).unwrap(); + let said = s.notices_since(mark); + assert!(said.iter().any(|n| n.text.starts_with("crs: ")), "{said:?}"); +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index dcb74d8ad8..af4c860a2a 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -147,7 +147,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu `{"type": "measured"}`, `{"edges": ["bottom"]}`); the strips inside the frame follow its labels, edges and `labelSize`, and without a graticule the default reference text names none (a `{grid}` you type reads `—`). `"scaleBar"` takes a scale bar's options - (`{"units": "miles", "style": "line"}`), its box growing with a larger `textSize`. + (`{"units": "miles", "style": "line"}`), its box growing with a larger `textSize`. A `textSize` or `labelSize` you give is in points + as written: unlike the defaults, it isn't scaled with the sheet. `"northArrow"` also takes `{"show": "auto"|"always", "style", "fill", "outline"}`. - **Legend box**: over the map, the legend's box is left clear where the map shows nothing under it but its light plain paper or water: no layer, label, context layer, basemap shape or graticule From 50ef8911f4568c65c6fa90998ee34dc331552bab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 04:55:59 -0500 Subject: [PATCH 4/7] fix(layout): say a publication's grid crs note only for a measured grid --- crates/engine/src/cmd/layout/publication/mod.rs | 4 +++- .../engine/src/tests/layout_publication_parts.rs | 14 ++++++++++---- docs/maintaining.md | 3 ++- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index fdd5fd6d22..8ec3177f7c 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1908,7 +1908,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let losses: Vec<_> = text_fit_loss(s, i, bar).into_iter().collect(); warnings.extend(rustgis_render::layout::scale_bar_fit_notices(&losses)); } - if let Some(crs) = p.get("grid").and_then(|g| g.get("crs")).and_then(Value::as_str) { + // Only a measured grid reads its coordinate system. + let measured = grid.as_ref().is_some_and(|g| g.kind == GridKind::Measured); + if let Some(crs) = p.get("grid").and_then(|g| g.get("crs")).and_then(Value::as_str).filter(|_| measured) { crate::cmd::say_crs_note(s, crs); } let locator = locator_map.map(|(map, ..)| map); diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 060fb2f878..175990a731 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -207,6 +207,8 @@ fn a_saved_publication_that_sets_a_part_requires_its_capability() { json!({"scaleBar": "none"}), json!({"scaleBar": {"units": "miles"}}), json!({"northArrow": {"style": "star"}}), + // Any object: an older reader refuses one. + json!({"northArrow": {"show": "auto"}}), ] { assert!(requires(params.clone()), "{params}"); } @@ -233,8 +235,12 @@ fn a_publication_grid_says_what_its_typed_coordinate_system_loses() { let mut s = world(); // UTM 17N on NAD 27, bound to WGS 84 by an NTv2 grid, which isn't applied. let crs = r#"BOUNDCRS[SOURCECRS[PROJCRS["unknown",BASEGEOGCRS["unknown",DATUM["North American Datum 1927",ELLIPSOID["Clarke 1866",6378206.4,294.978698213898,LENGTHUNIT["metre",1]],ID["EPSG",6267]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]]],CONVERSION["UTM zone 17N",METHOD["Transverse Mercator",ID["EPSG",9807]],PARAMETER["Latitude of natural origin",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8801]],PARAMETER["Longitude of natural origin",-81,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["Scale factor at natural origin",0.9996,SCALEUNIT["unity",1],ID["EPSG",8805]],PARAMETER["False easting",500000,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",0,LENGTHUNIT["metre",1],ID["EPSG",8807]],ID["EPSG",16017]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1,ID["EPSG",9001]]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1,ID["EPSG",9001]]]]],TARGETCRS[GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["latitude",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["longitude",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4326]]],ABRIDGEDTRANSFORMATION["unknown to WGS84",METHOD["NTv2",ID["EPSG",9615]],PARAMETERFILE["Latitude and longitude difference file","conus",ID["EPSG",8656]]]]"#; - let mark = s.notice_mark(); - publish(&mut s, json!({"grid": {"type": "measured", "crs": crs}})).unwrap(); - let said = s.notices_since(mark); - assert!(said.iter().any(|n| n.text.starts_with("crs: ")), "{said:?}"); + let mut said = |grid: Value| { + let mark = s.notice_mark(); + publish(&mut s, json!({"grid": grid})).unwrap(); + s.notices_since(mark).iter().any(|n| n.text.starts_with("crs: ")) + }; + assert!(said(json!({"type": "measured", "crs": crs}))); + // A graticule draws degrees and reads no coordinate system: nothing of it is lost. + assert!(!said(json!({"crs": crs}))); } diff --git a/docs/maintaining.md b/docs/maintaining.md index 2000e730a6..5b7d873ea0 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -345,7 +345,8 @@ definition and, saving them again, drops only the WKT. A saved `layout.publication` that leaves out or sets up a part of the sheet (`grid` or `scaleBar` as `"none"` or an object that gives something, or `northArrow` as such an object, #3094) requires `layout-publication-parts`, so an older reader refuses it instead of making the -default sheet. `null`, `{}` and the north arrow's `"auto"`, `"always"` and `"none"` need nothing. +default sheet. `null`, `{}` and the north arrow given as the text `"auto"`, `"always"` or `"none"` +need nothing. ## New dependencies From 9200235feefaeb9ad20239ff8da89b5f1fd191f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 05:00:20 -0500 Subject: [PATCH 5/7] fix(layout): refuse an unknown publication key set to null, and require the capability for any north arrow object --- crates/engine/src/cmd/layout/publication/parts.rs | 2 +- .../engine/src/cmd/layout/publication/placement.rs | 14 ++++++++------ crates/engine/src/project_capabilities.rs | 5 +++-- crates/engine/src/tests.rs | 2 ++ .../engine/src/tests/layout_publication_parts.rs | 6 ++++-- docs/maintaining.md | 8 ++++---- 6 files changed, 22 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index f3ad7f80ec..cbea6b699f 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -29,10 +29,10 @@ const NORTH_ARROW_KEYS: &[&str] = &["show", "style", "fill", "outline"]; /// not in `keys` is refused. fn options(key: &str, v: &Value, keys: &[&str]) -> Result, String> { let Some(given) = v.as_object() else { return Ok(None) }; - let given: serde_json::Map = given.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(); if let Some(other) = given.keys().find(|k| !keys.contains(&k.as_str())) { return Err(format!("{key} takes no \"{other}\" (it reads {})", keys.join(", "))); } + let given: serde_json::Map = given.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(); Ok(Some(Value::Object(given))) } diff --git a/crates/engine/src/cmd/layout/publication/placement.rs b/crates/engine/src/cmd/layout/publication/placement.rs index 5e305ab23a..6777b51f36 100644 --- a/crates/engine/src/cmd/layout/publication/placement.rs +++ b/crates/engine/src/cmd/layout/publication/placement.rs @@ -109,17 +109,19 @@ pub(crate) fn veil_panel( // The gap over the scale bar only when there is one and something sits above it. let lead = if top.1 > 0.0 && scale.1 > 0.0 { gap } else { 0.0 }; let group = (top.0.max(scale.0), top.1 + lead + scale.1); - let beside = legend.0 + gap + group.0 <= bw && legend.1.max(group.1) <= bh; - let over = legend.0.max(group.0) <= bw && legend.1 + gap + group.1 <= bh; + // Nothing to keep the legend apart from, without a surround to group. + let apart = if group.0 > 0.0 || group.1 > 0.0 { gap } else { 0.0 }; + let beside = legend.0 + apart + group.0 <= bw && legend.1.max(group.1) <= bh; + let over = legend.0.max(group.0) <= bw && legend.1 + apart + group.1 <= bh; if !beside && !over { return None; } let (legend_at, group_at) = if beside && (bw >= bh || !over) { - let (x, y) = (bx + (bw - legend.0 - gap - group.0) / 2.0, by + (bh - legend.1.max(group.1)) / 2.0); - ((x, y), (x + legend.0 + gap, y)) + let (x, y) = (bx + (bw - legend.0 - apart - group.0) / 2.0, by + (bh - legend.1.max(group.1)) / 2.0); + ((x, y), (x + legend.0 + apart, y)) } else { - let (x, y) = (bx + (bw - legend.0.max(group.0)) / 2.0, by + (bh - legend.1 - gap - group.1) / 2.0); - ((x, y + group.1 + gap), (x, y)) + let (x, y) = (bx + (bw - legend.0.max(group.0)) / 2.0, by + (bh - legend.1 - apart - group.1) / 2.0); + ((x, y + group.1 + apart), (x, y)) }; Some(( (legend_at.0, legend_at.1, legend.0, legend.1), diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 71498136e5..a3fd0cadf5 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -188,13 +188,14 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ /// A saved `layout.publication` that leaves out or sets up its grid, scale bar or north arrow /// (#3094): an older reader ignores `grid` and `scaleBar`, making the default sheet, and refuses -/// a `northArrow` object. `null` and an object giving nothing ask for the default. +/// any `northArrow` object. `null`, and a grid or scale bar object giving nothing, ask for the +/// default. fn command_sets_publication_parts(id: &str, params: &Value) -> bool { let sets = |v: &Value| v.as_object().is_none_or(|o| o.values().any(|v| !v.is_null())); match id { "layout.publication" => { ["grid", "scaleBar"].into_iter().any(|k| params.get(k).is_some_and(|v| !v.is_null() && sets(v))) - || params.get("northArrow").is_some_and(|v| v.is_object() && sets(v)) + || params.get("northArrow").is_some_and(Value::is_object) } "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_publication_parts)), _ => false, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fc48da918d..656f8a32fe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -15606,6 +15606,8 @@ fn a_veil_panel_groups_the_surrounds_by_the_bands_shape() { let (l, locator, _, b) = veil_panel((0.0, 0.0, 90.0, 130.0), legend, Some(40.0), arrow, scale, 3.0).unwrap(); assert!(l.1 >= b.1 + b.3 && locator.unwrap().0 == b.0, "under it: {l:?} {b:?}"); assert!(veil_panel((0.0, 0.0, 60.0, 60.0), legend, Some(40.0), arrow, scale, 3.0).is_none()); + // With nothing to group beside it, a legend the size of the band fits it: no gap is kept. + assert!(veil_panel((0.0, 0.0, legend.0, legend.1), legend, None, None, (0.0, 0.0), 3.0).is_some()); assert!(veil_panel((0.0, 0.0, 160.0, 70.0), legend, None, arrow, scale, 3.0).unwrap().1.is_none()); // With no north arrow (a continental extent, #1379), the locator stands alone over the scale bar. let (_, locator, a, b) = veil_panel((0.0, 0.0, 160.0, 70.0), legend, Some(40.0), None, scale, 3.0).unwrap(); diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 175990a731..bd0ddb7762 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -174,6 +174,7 @@ fn a_publication_part_given_wrong_is_refused_and_nothing_is_made() { for (parts, said) in [ (json!({"grid": {"style": "wavy"}}), "unknown grid style"), (json!({"grid": {"foo": 1}}), "grid takes no \"foo\""), + (json!({"grid": {"stepp": null}}), "grid takes no \"stepp\""), (json!({"grid": 5}), "grid is \"none\""), (json!({"grid": true}), "grid is \"none\""), (json!({"scaleBar": {"units": "parsecs"}}), "unknown units"), @@ -209,11 +210,12 @@ fn a_saved_publication_that_sets_a_part_requires_its_capability() { json!({"northArrow": {"style": "star"}}), // Any object: an older reader refuses one. json!({"northArrow": {"show": "auto"}}), + json!({"northArrow": {}}), + json!({"northArrow": {"show": null}}), ] { assert!(requires(params.clone()), "{params}"); } - for params in [json!({}), json!({"grid": null, "scaleBar": {}}), json!({"northArrow": "always"}), json!({"northArrow": {"show": null}})] - { + for params in [json!({}), json!({"grid": null, "scaleBar": {}}), json!({"northArrow": "always"}), json!({"northArrow": null})] { assert!(!requires(params.clone()), "{params}"); } } diff --git a/docs/maintaining.md b/docs/maintaining.md index 5b7d873ea0..da788e7588 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -343,10 +343,10 @@ instead of misplacing the layer. Others need nothing: an older reader opens them definition and, saving them again, drops only the WKT. A saved `layout.publication` that leaves out or sets up a part of the sheet (`grid` or -`scaleBar` as `"none"` or an object that gives something, or `northArrow` as such an object, -#3094) requires `layout-publication-parts`, so an older reader refuses it instead of making the -default sheet. `null`, `{}` and the north arrow given as the text `"auto"`, `"always"` or `"none"` -need nothing. +`scaleBar` as `"none"` or an object that gives something, or `northArrow` as any object, #3094) +requires `layout-publication-parts`, so an older reader refuses it instead of making the default +sheet or failing on the object. `null`, a `grid` or `scaleBar` of `{}`, and the north arrow given +as the text `"auto"`, `"always"` or `"none"` need nothing. ## New dependencies From f9ce082ec15b7243530eac5ff73fa0daee8d9e8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 05:08:47 -0500 Subject: [PATCH 6/7] refactor(layout): take a publication's grid keys from layout.addElement's list --- crates/assistant/skills/print-layout/SKILL.md | 2 +- .../src/cmd/layout/publication/parts.rs | 24 ++++--------------- .../src/tests/layout_publication_parts.rs | 1 + 3 files changed, 6 insertions(+), 21 deletions(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index d89aff30f0..0f2567be78 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -10,7 +10,7 @@ description: Make a printable page layout — map frame, title, legend, north ar (a page size alone, `"a4"`, `"letter"`, `"legal"`, `"tabloid"`, `"a5"` to `"a0"`, for a sheet turned to the area's shape, or with its orientation, `"a4-portrait"`, `"letter-landscape"`, … to choose; `"figure-1col"`, `"thesis-full"`, … for a figure), the `"extent"` to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`, a `"locator"` (`"globe"`: the visible polygon layers held in the project, not streamed ones, over the basemap; `"inset"` or `"none"`; when omitted, `"globe"` on a sheet and `"none"` on a figure), and `"decimal": ","` for a map in a language with a decimal comma. A sheet's `"style"` arranges it: `"classic"` (the default), `"banner"`, `"panel"`, `"editorial"`, `"modular"` or `"poster"` (for a poster-like sheet), with an `"accent"` colour as `"#RRGGBB"`. Its surrounds (locator, north arrow, legend, scale bar) start from an `"arrangement"` (`"classic"`, `"mirrored"`, `"legendRight"`, `"legendTop"`, or a corner for each; `"best"`, the default, tries the user's favourite, set with `layout.arrangement`, and the others), and one over the data moves to the freest place in the frame, the largest first (the legend, as a rule); read its `"arrangement"`, `"moved"` and `"warnings"`. It places the frame at a round scale, the - graticule, legend (a long one in up to three columns), scale bar and north arrow, and wraps the footer. `"grid"`, `"scaleBar"` and `"northArrow"` take `"none"` to leave that part out, or an object of its options (the grid's `"step"` or `"type"`, the bar's `"units"` or `"style"`, the arrow's `"style"` and `"show"`). Its result lists every element's id and name + graticule, legend (a long one in up to three columns), scale bar and north arrow, and wraps the footer. `"grid"`, `"scaleBar"` and `"northArrow"` take `"none"` to leave that part out, or an object of its options (the grid's `"step"` or `"type"`, the bar's `"units"` or `"style"`, the arrow's `"style"`, `"fill"`, `"outline"` and `"show"`). Its result lists every element's id and name (`"elements"`), so skip to step 5 to adjust them. Otherwise, `layout.new` `{"name": N, "page": "letter"|"a4"|…, "orientation": "landscape"|"portrait"}` creates the layout and opens it. diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index cbea6b699f..c458784024 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -3,25 +3,6 @@ use super::*; -/// A frame grid's options, as `layout.addElement` takes them. -const GRID_KEYS: &[&str] = &[ - "type", - "crs", - "step", - "short", - "mgrs", - "color", - "width", - "labels", - "labelSize", - "style", - "tickLength", - "format", - "hemisphere", - "edges", - "labelOrientation", -]; - /// A north arrow's: when it is drawn, and its look as `layout.update` takes it. const NORTH_ARROW_KEYS: &[&str] = &["show", "style", "fill", "outline"]; @@ -53,7 +34,10 @@ fn part(p: &Value, key: &str, keys: &[&str], default: T, set: impl FnOnce(&Va /// no step keeps the default's, which the reference text says. pub(super) fn publication_grid(p: &Value, default: Grid) -> Result, String> { let step = default.step; - part(p, "grid", GRID_KEYS, default, |o, base| { + // A frame grid's options as `layout.addElement` takes them, without the keys that say which + // element and frame it is, and `off`, which `"none"` says here. + let keys: Vec<&str> = ADD_GRID_KEYS.iter().copied().filter(|k| !["layout", "kind", "frame", "off"].contains(k)).collect(); + part(p, "grid", &keys, default, |o, base| { let mut grid = grid_params(o, base)?; if grid.kind == GridKind::Graticule && grid.step <= 0.0 { grid.step = step; diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index bd0ddb7762..ec2ad61355 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -175,6 +175,7 @@ fn a_publication_part_given_wrong_is_refused_and_nothing_is_made() { (json!({"grid": {"style": "wavy"}}), "unknown grid style"), (json!({"grid": {"foo": 1}}), "grid takes no \"foo\""), (json!({"grid": {"stepp": null}}), "grid takes no \"stepp\""), + (json!({"grid": {"off": true}}), "grid takes no \"off\""), (json!({"grid": 5}), "grid is \"none\""), (json!({"grid": true}), "grid is \"none\""), (json!({"scaleBar": {"units": "parsecs"}}), "unknown units"), From ee214cc761b34a4c654f5e056ba8c836fd9cf7cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 05:29:50 -0500 Subject: [PATCH 7/7] fix(layout): refuse a publication grid key the grid's kind doesn't read --- crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/cmd/layout/publication/mod.rs | 4 +--- crates/engine/src/cmd/layout/publication/parts.rs | 9 +++++++++ crates/engine/src/tests/layout_publication_parts.rs | 9 +++++++-- docs/user-guide/layouts.md | 3 ++- 5 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 6e8fb31062..3007d3005f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -81,7 +81,7 @@ pub fn commands() -> Vec { r#""veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "#, r#""contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "#, r#""northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none" | {"show"?: "auto" | "always", "style"?, "fill"?, "outline"? as layout.update takes a north arrow's}, "#, - r#""grid"?: "none" (no grid on the map frame, and no label strips inside it) | {a frame grid's options as layout.addElement takes them: type, crs, step, short, mgrs, color, width, labels, labelSize, style, tickLength, format, hemisphere, edges, labelOrientation} over the default graticule (its step by the extent, labelled left and bottom, on a sheet all round); the label strips follow its labels, edges and labelSize (in points as given, not scaled with the sheet), and without a graticule the default reference names none and {grid} in a text reads "—", "#, + r#""grid"?: "none" (no grid on the map frame, and no label strips inside it) | {a frame grid's options as layout.addElement takes them: type, crs, step, short, mgrs, color, width, labels, labelSize, style, tickLength, format, hemisphere, edges, labelOrientation; a graticule takes no crs, short or mgrs, a measured grid no format or hemisphere} over the default graticule (its step by the extent, labelled left and bottom, on a sheet all round); the label strips follow its labels, edges and labelSize (in points as given, not scaled with the sheet), and without a graticule the default reference names none and {grid} in a text reads "—", "#, r#""scaleBar"?: "none" | {a scale bar's options as layout.update takes them: style, units, divisions, color, fill, textSize, decimals, subdivisions, divisionsBeforeZero, labelPosition, unitLabel, unitLabelPosition, fit; textSize in points as given, not scaled with the sheet} (none on a globe shown whole, whatever is asked), "#, r#""legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "#, r#""style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "#, diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 8ec3177f7c..fdd5fd6d22 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1908,9 +1908,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let losses: Vec<_> = text_fit_loss(s, i, bar).into_iter().collect(); warnings.extend(rustgis_render::layout::scale_bar_fit_notices(&losses)); } - // Only a measured grid reads its coordinate system. - let measured = grid.as_ref().is_some_and(|g| g.kind == GridKind::Measured); - if let Some(crs) = p.get("grid").and_then(|g| g.get("crs")).and_then(Value::as_str).filter(|_| measured) { + if let Some(crs) = p.get("grid").and_then(|g| g.get("crs")).and_then(Value::as_str) { crate::cmd::say_crs_note(s, crs); } let locator = locator_map.map(|(map, ..)| map); diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index c458784024..95e535108a 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -39,6 +39,15 @@ pub(super) fn publication_grid(p: &Value, default: Grid) -> Result, let keys: Vec<&str> = ADD_GRID_KEYS.iter().copied().filter(|k| !["layout", "kind", "frame", "off"].contains(k)).collect(); part(p, "grid", &keys, default, |o, base| { let mut grid = grid_params(o, base)?; + // The keys only the other kind of grid reads: a graticule draws degrees, a measured grid + // its system's units. + let (kind, unread): (&str, &[&str]) = match grid.kind { + GridKind::Graticule => ("a graticule", &["crs", "short", "mgrs"]), + GridKind::Measured => ("a measured grid", &["format", "hemisphere"]), + }; + if let Some(key) = unread.iter().find(|key| o.get(**key).is_some()) { + return Err(format!("grid takes no \"{key}\" for {kind}")); + } if grid.kind == GridKind::Graticule && grid.step <= 0.0 { grid.step = step; } diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index ec2ad61355..8da02376ea 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -176,6 +176,12 @@ fn a_publication_part_given_wrong_is_refused_and_nothing_is_made() { (json!({"grid": {"foo": 1}}), "grid takes no \"foo\""), (json!({"grid": {"stepp": null}}), "grid takes no \"stepp\""), (json!({"grid": {"off": true}}), "grid takes no \"off\""), + // A graticule draws degrees: it reads no coordinate system. + // Keys only the other kind of grid reads. + (json!({"grid": {"crs": "EPSG:32723"}}), "grid takes no \"crs\" for a graticule"), + (json!({"grid": {"type": "graticule", "short": true}}), "grid takes no \"short\" for a graticule"), + (json!({"grid": {"type": "measured", "format": "dms"}}), "grid takes no \"format\" for a measured grid"), + (json!({"grid": {"type": "measured", "hemisphere": false}}), "grid takes no \"hemisphere\" for a measured grid"), (json!({"grid": 5}), "grid is \"none\""), (json!({"grid": true}), "grid is \"none\""), (json!({"scaleBar": {"units": "parsecs"}}), "unknown units"), @@ -244,6 +250,5 @@ fn a_publication_grid_says_what_its_typed_coordinate_system_loses() { s.notices_since(mark).iter().any(|n| n.text.starts_with("crs: ")) }; assert!(said(json!({"type": "measured", "crs": crs}))); - // A graticule draws degrees and reads no coordinate system: nothing of it is lost. - assert!(!said(json!({"crs": crs}))); + assert!(!said(json!({"type": "measured", "crs": "EPSG:32723"}))); } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index af4c860a2a..d6312ece67 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -144,7 +144,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu - **Grid, scale bar and north arrow**: `"grid"`, `"scaleBar"` and `"northArrow"` each take `"none"` to leave that part out, or an object with its options, and a key the part doesn't read is refused. `"grid"` takes a frame grid's options (`{"step": 5}`, - `{"type": "measured"}`, `{"edges": ["bottom"]}`); the strips inside the frame follow its + `{"type": "measured"}`, `{"edges": ["bottom"]}`; a graticule takes no `crs`, `short` or `mgrs`, + and a measured grid no `format` or `hemisphere`); the strips inside the frame follow its labels, edges and `labelSize`, and without a graticule the default reference text names none (a `{grid}` you type reads `—`). `"scaleBar"` takes a scale bar's options (`{"units": "miles", "style": "line"}`), its box growing with a larger `textSize`. A `textSize` or `labelSize` you give is in points