From 0bf4d1dd1f50f924a3ab489ccf7d6bd0be83aa5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 12:23:47 -0500 Subject: [PATCH 1/7] feat(layout): leave out a publication's legend or set its title, columns and layers --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/layout.rs | 1 + crates/engine/src/cmd/layout/legend.rs | 8 +- .../engine/src/cmd/layout/publication/mod.rs | 84 ++++----- .../src/cmd/layout/publication/parts.rs | 70 +++++++ crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 14 ++ crates/engine/src/tests.rs | 6 + .../src/tests/layout_publication_parts.rs | 173 ++++++++++++++++++ crates/render/src/layout/legend.rs | 6 + docs/maintaining.md | 4 + docs/user-guide/layouts.md | 4 + .../fixtures/layout_publication_legend.rgis | 1 + schema/project.schema.json | 6 +- 14 files changed, 331 insertions(+), 49 deletions(-) create mode 100644 schema/fixtures/layout_publication_legend.rgis diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index d0a77aac3a..8689c5babe 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? grid? scaleBar? legendBox? style? paper? kicker? accent? arrangement? coverage? +layout.publication profile? extent? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? grid? scaleBar? legend? legendBox? style? paper? kicker? 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 ed9e60be24..d8b9d65599 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -85,6 +85,7 @@ pub fn commands() -> Vec { 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; 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#""legend"?: "none" (no legend; a colorbar keeps its box) | {"title"?: text, "columns"?: 1 to 6 (that many; the placement picks 1 to 3 otherwise), "exclude"?: [layer names] (left out besides the context ones)}, "#, 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) | "edge" (the map from one side of the page to the other with no border, a kicker and the title over it, the footer with no boxes under a thin rule) (a sheet's arrangement; figures leave it to the caption), "#, r##""paper"?: "#RRGGBB" (an edge sheet's page colour, as layout.page's "color"; white by default; on a dark one its texts are light), "##, diff --git a/crates/engine/src/cmd/layout/legend.rs b/crates/engine/src/cmd/layout/legend.rs index 9a1a6f05ac..d2d9613cb2 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -350,11 +350,15 @@ pub(in crate::cmd::layout) fn legend_exclude( p: &Value, ) -> Result>, String> { let Some(v) = p.get("exclude").filter(|v| !v.is_null()) else { return Ok(None) }; + excluded_layers(legend_map(input, l, frame)?, v).map(Some) +} + +/// The layers of `map` that `v`, a legend's `exclude`, names, as the map spells them, each once. +pub(in crate::cmd::layout) fn excluded_layers(map: &Map, v: &Value) -> Result, String> { let names = v.as_array().ok_or("exclude is a list of layer names")?; if names.len() > rustgis_map::layout::MAX_LEGEND_EXCLUDED { return Err(format!("a legend leaves out at most {} layers", rustgis_map::layout::MAX_LEGEND_EXCLUDED)); } - let map = legend_map(input, l, frame)?; let mut out: Vec = Vec::new(); for n in names { let n = n.as_str().ok_or("exclude is a list of layer names")?; @@ -363,7 +367,7 @@ pub(in crate::cmd::layout) fn legend_exclude( out.push(name.clone()); } } - Ok(Some(out)) + Ok(out) } /// The map a legend's frame shows. diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index c778f9126d..fa751a3e41 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -126,6 +126,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let may_veil = publication_veil(p)?; let context_in_legend = publication_flag(p, "contextInLegend")?.unwrap_or(false); let (north_arrow, mut arrow_kind) = publication_north_arrow(p)?; + let legend = publication_legend(p, s.map())?; 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"] { @@ -1084,18 +1085,24 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). // It is judged again at each other scale the search below draws the map at, as the placement // judges it there, and the legend takes the one at the scale settled on. + // Those "legend" already asks to leave out aren't among them, so the warning doesn't offer to + // list them; without a legend there are none. let context_at = |s: &Session, center: Coord, scale: f64| { - if context_in_legend { Vec::new() } else { legend_context(s.map(), center, scale, (fw, fh)) } + let Some(legend) = legend.as_ref().filter(|_| !context_in_legend) else { return Vec::new() }; + let mut context = legend_context(s.map(), center, scale, (fw, fh)); + context.retain(|c| !legend.exclude.iter().any(|n| n.eq_ignore_ascii_case(c))); + context }; + // The legend's sizes at a render scale: nothing without one. + let legend_sizes = |s: &mut Session, scale: f64, context: &[String]| match &legend { + None => Some([(0.0, 0.0); PUBLICATION_LEGEND_COLUMNS]), + Some(legend) => legend.sizes(s.map_mut(), scale, context, legend_pt), + }; + // Whether a legend picture still loading keeps its size at a render scale unknown. + let pictures_pending = + |s: &Session, scale: f64| legend.as_ref().is_some_and(|l| crate::render::layout::tile_legends_pending(s.map(), scale, &l.exclude)); let mut context = context_at(s, center, scale); - let mut sizes = crate::render::layout::legend_sizes_in_columns_mm::( - s.map_mut(), - render_scale, - false, - false, - (false, legend_pt), - (&context, &Default::default()), - ); + let mut sizes = legend_sizes(s, render_scale, &context); let (mut cw, mut ch) = match sizes { Some(sizes) => sizes[0], None => { @@ -1104,12 +1111,12 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu (fw * 0.3, fh * 0.25) } }; - let listed = s.map().layers.iter().any(|l| s.map().shows(l) && crate::render::layout::legend_lists(l)); + let listed = legend.is_some() && s.map().layers.iter().any(|l| s.map().shows(l) && crate::render::layout::legend_lists(l)); if reading && listed { (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); sizes = None; warnings.push("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand".into()); - } else if crate::render::layout::tile_legends_pending(s.map(), render_scale, &[]) { + } else if pictures_pending(s, render_scale) { // Not waited for: a slow legend server would hold the command up. (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); sizes = None; @@ -1361,28 +1368,20 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let reading = s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); let here_context = if tried == asked_scale { context.clone() } else { context_at(s, centred, tried) }; - let here = - if reading || (tried != asked_scale && crate::render::layout::tile_legends_pending(s.map(), render_scale, &[])) { + let here = if (reading && legend.is_some()) || (tried != asked_scale && pictures_pending(s, render_scale)) { + unknown_at.get_or_insert(tried); + None + } else if tried == asked_scale { + Some(known) + } else { + // A legend that can't be measured there (a source that can't be read + // through) leaves that scale untried too, which is said. + let measured = legend_sizes(s, render_scale, &here_context); + if measured.is_none() { unknown_at.get_or_insert(tried); - None - } else if tried == asked_scale { - Some(known) - } else { - // A legend that can't be measured there (a source that can't be read - // through) leaves that scale untried too, which is said. - let measured = crate::render::layout::legend_sizes_in_columns_mm::( - s.map_mut(), - render_scale, - false, - false, - (false, legend_pt), - (&here_context, &Default::default()), - ); - if measured.is_none() { - unknown_at.get_or_insert(tried); - } - measured - }; + } + measured + }; let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; // What is context is judged on the frame asked for, not the wide drawing, so // every move's cut leaves out the same layers. @@ -1463,14 +1462,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu *here } else { let at_there = crate::render::layout::frame_render_scale(s.map(), there, tried); - let measured = crate::render::layout::legend_sizes_in_columns_mm::( - s.map_mut(), - at_there, - false, - false, - (false, legend_pt), - (&own_context, &Default::default()), - ); + let measured = legend_sizes(s, at_there, &own_context); // A legend that can't be measured there leaves that move untried, which is // said, as at a scale. let Some(measured) = measured else { @@ -1735,6 +1727,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu .collect(); arrangement_used = "veil".into(); } + // A legend asked for some columns takes them, whichever of the equal sizes was picked. + if let Some(columns) = legend.as_ref().and_then(|l| l.columns) { + legend_cols = columns; + } if let Some(ElementKind::MapFrame { center: at, scale: drawn_at, .. }) = l.element_mut(frame).map(|e| &mut e.kind) { (*at, *drawn_at) = (center, scale); } @@ -1871,17 +1867,17 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu warnings.push(format!("the legend's box has no room for the colorbar of '{layer}': it is left out")); } } - if ch > 0.0 && rows_h >= 1.0 { + if let Some(legend) = legend.as_ref().filter(|_| ch > 0.0 && rows_h >= 1.0) { l.add( "Legend", (ix, iy, iw, rows_h), ElementKind::Legend { frame, - title: String::new(), + title: legend.title.clone(), all_classes: false, hide_other: false, show_no_data: false, - exclude: context.clone(), + exclude: legend.left_out(&context), columns: legend_cols, labels: Default::default(), color: None, @@ -1989,7 +1985,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } 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}), + 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.as_ref().map(|_| 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}), ) } diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index 95e535108a..6de05709d2 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -91,3 +91,73 @@ pub(super) fn publication_north_arrow(p: &Value) -> Result<(Option, Elemen _ => Err(refused()), } } + +/// A legend's: its title, its columns and the layers it leaves out. +const LEGEND_KEYS: &[&str] = &["title", "columns", "exclude"]; + +/// What `"legend"` sets of a publication's legend; the default has no title, takes the columns the +/// placement picks and leaves out no layer but the context ones. +#[derive(Default)] +pub(super) struct PublicationLegend { + pub(super) title: String, + pub(super) columns: Option, + /// The layers asked to be left out, as `map` spells them. + pub(super) exclude: Vec, +} + +/// The legend of a publication of `map`, as `"legend"` sets it up, or none. +pub(super) fn publication_legend(p: &Value, map: &Map) -> Result, String> { + part(p, "legend", LEGEND_KEYS, PublicationLegend::default(), |o, base| { + let title = match o.get("title") { + None => base.title, + Some(v) => crate::cmd::within("title", "a legend's title", v.as_str().ok_or("title is text")?, 200)?, + }; + let exclude = o.get("exclude").map(|v| excluded_layers(map, v)).transpose()?.unwrap_or_default(); + Ok(PublicationLegend { title, columns: legend_columns_param(o)?, exclude }) + }) +} + +impl PublicationLegend { + /// The layers the legend leaves out: the `context` ones, none of them among those asked, and + /// those asked. + pub(super) fn left_out(&self, context: &[String]) -> Vec { + [context, &self.exclude].concat() + } + + /// The legend's size in each number of columns the placement tries, in mm, its text `text_pt` + /// points, at the renderer's scale denominator `scale`, with its title when it has rows. A + /// legend asked for some columns has that size in every one, so the placement has no other to + /// pick. `None` when a complete source can't be read. + pub(super) fn sizes( + &self, + map: &mut Map, + scale: f64, + context: &[String], + text_pt: f64, + ) -> Option<[(f64, f64); PUBLICATION_LEGEND_COLUMNS]> { + use crate::render::layout::{LegendAsked, legend_size_asked_mm, legend_sizes_in_columns_mm}; + let exclude = self.left_out(context); + let labels = Default::default(); + let sizes = match self.columns { + None => legend_sizes_in_columns_mm(map, scale, false, false, (false, text_pt), (&exclude, &labels))?, + Some(columns) => { + let asked = LegendAsked { + all_classes: false, + hide_other: false, + show_no_data: false, + layer_names: true, + text_size: text_pt, + exclude: &exclude, + labels: &labels, + }; + [legend_size_asked_mm(map, scale, &asked, columns)?; PUBLICATION_LEGEND_COLUMNS] + } + }; + if self.title.is_empty() { + return Some(sizes); + } + let title_w = crate::render::layout::legend_title_width_mm(&self.title, text_pt); + let title_h = crate::render::layout::legend_title_mm(text_pt); + Some(sizes.map(|(w, h)| if h > 0.0 { (w.max(title_w), h + title_h) } else { (w, h) })) + } +} diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 27179ae2e0..9f35a89626 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -127,6 +127,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-page-color", "layout-text-statistics", "layout-publication-parts", + "layout-publication-legend", ]; /// 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 8003aa1b04..176d942748 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -185,6 +185,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-page-color", command_colours_the_page), ("layout-text-statistics", command_uses_text_statistics), ("layout-publication-parts", command_sets_publication_parts), + ("layout-publication-legend", command_sets_publication_legend), ]; /// A saved `layout.publication` that leaves out or sets up its grid, scale bar or north arrow @@ -203,6 +204,18 @@ fn command_sets_publication_parts(id: &str, params: &Value) -> bool { } } +/// A saved `layout.publication` that leaves out or sets up its legend (#3095): an older reader +/// ignores `legend`, making the default one. `null`, and an object giving nothing, ask for it. +fn command_sets_publication_legend(id: &str, params: &Value) -> bool { + match id { + "layout.publication" => { + params.get("legend").is_some_and(|v| !v.is_null() && v.as_object().is_none_or(|o| o.values().any(|v| !v.is_null()))) + } + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_publication_legend)), + _ => 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. @@ -1431,6 +1444,7 @@ mod tests { (&["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"})), + (&["layout-publication-legend"], "layout.publication", json!({"legend": "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 9ffe4835be..cb7faa6212 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -15594,6 +15594,12 @@ fn a_publication_legend_leaves_out_context_layers() { assert_eq!(exclude, ["border"], "a name a data layer shares stays: {said:?}"); let (exclude, said) = laid(json!({"contextInLegend": true})).unwrap(); assert!(exclude.is_empty() && said.is_none(), "{exclude:?} {said:?}"); + // One asked to be left out isn't named: "contextInLegend" wouldn't list it. + let (mut exclude, said) = laid(json!({"legend": {"exclude": ["Border"]}})).unwrap(); + exclude.sort(); + assert_eq!(exclude, ["around", "border"]); + let said = said.expect("said"); + assert!(said.contains("1 context layer around the data (around)"), "{said}"); let bad = laid(json!({"contextInLegend": "yes"})).unwrap_err(); assert!(bad.contains("contextInLegend is true or false"), "{bad}"); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 9093d2af94..bdb836e2d2 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -256,3 +256,176 @@ fn a_publication_grid_says_what_its_typed_coordinate_system_loses() { assert!(said(json!({"type": "measured", "crs": crs}))); assert!(!said(json!({"type": "measured", "crs": "EPSG:32723"}))); } + +/// The columns, title and layers left out of the layout's legend. +fn legend(s: &Session) -> (usize, String, Vec) { + match &find(s, "Legend").unwrap().kind { + ElementKind::Legend { columns, title, exclude, .. } => (*columns, title.clone(), exclude.clone()), + k => panic!("{k:?}"), + } +} + +/// The name of a sample layer the legend lists. +fn listed(s: &Session) -> String { + s.map().layers.iter().find(|l| s.map().shows(l) && crate::render::layout::legend_lists(l)).unwrap().name.clone() +} + +/// A path for a file of this test run. +fn temp(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("rustgis-3095-{}-{:?}-{name}", std::process::id(), std::thread::current().id())) +} + +/// An A4 sheet of the sample map with a raster on a colour ramp over it, which gets a colorbar. +fn with_colorbar(parts: Value) -> (Session, Value) { + let tif = temp("ramp.tif"); + std::fs::write(&tif, rustgis_data::raster::cog::example(256, 128)).unwrap(); + let mut s = world(); + s.run("layer.addData", &json!({"path": tif.display().to_string()})).unwrap(); + let r = publish(&mut s, parts).unwrap(); + (s, r) +} + +#[test] +fn a_publication_without_a_legend_has_no_legend_and_no_box() { + let (s, r) = sheet(json!({"legend": "none", "colorbar": "none"})); + assert!(find(&s, "Legend").is_none() && find(&s, "Legend Box").is_none()); + assert_eq!(r["legendColumns"], Value::Null); + assert_eq!(r["legendBox"], json!(false)); + assert!(!r["warnings"].to_string().contains("legend"), "{}", r["warnings"]); +} + +#[test] +fn a_publication_without_a_legend_keeps_the_colorbar_in_its_box() { + let (s, r) = with_colorbar(json!({"legend": "none"})); + assert!(find(&s, "Legend").is_none()); + let (bx, bar) = (find(&s, "Legend Box").unwrap(), find(&s, "Colorbar").unwrap()); + let (default, _) = with_colorbar(json!({})); + assert!(bx.h < find(&default, "Legend Box").unwrap().h, "{}", bx.h); + assert!(bar.y >= bx.y && bar.y + bar.h <= bx.y + bx.h + 1e-6); + assert_eq!(r["legendColumns"], Value::Null); +} + +#[test] +fn a_publication_legend_takes_its_columns() { + for n in [1, 2, rustgis_map::layout::MAX_LEGEND_COLUMNS] { + for style in ["classic", "panel"] { + let (s, r) = sheet(json!({"legend": {"columns": n}, "style": style})); + assert_eq!(legend(&s).0, n, "{style} {n}"); + assert_eq!(r["legendColumns"], json!(n), "{style} {n}"); + } + } +} + +#[test] +fn a_publication_legend_keeps_its_columns_on_a_veiled_map() { + let mut s = Session::new(Project::default()); + let fill = [-30.0, 35.0, 70.0, 82.0]; + let [w, so, e, n] = fill; + let ring = json!([[[w, so], [e, so], [e, n], [w, n], [w, so]]]); + let fc = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": ring}}]}); + let path = temp("fill.geojson"); + std::fs::write(&path, fc.to_string()).unwrap(); + for _ in 0..30 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let features: Vec = (0..) + .map(|i| so + 0.25 * f64::from(i)) + .take_while(|lat| *lat <= 61.0) + .map(|lat| json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [20.0, lat]}})) + .collect(); + let points = temp("points.geojson"); + std::fs::write(&points, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + s.run("layer.addData", &json!({"path": points.display().to_string(), "stream": true, "name": "Column"})).unwrap(); + let r = s + .run( + "layout.publication", + &json!({"profile": "a4-portrait", "extent": [10.0, 57.0, 30.0, 61.0], "author": "", "locator": "none", "legend": {"columns": 2}}), + ) + .unwrap(); + assert_eq!(r["veiled"], json!(true), "{r}"); + assert_eq!((legend(&s).0, r["legendColumns"].as_u64()), (2, Some(2)), "{r}"); +} + +#[test] +fn a_publication_legend_leaves_out_the_layers_asked() { + let name = listed(&world()); + let (s, _) = sheet(json!({"legend": {"exclude": [name.to_uppercase(), name.clone()]}})); + let out = legend(&s).2; + assert_eq!(out.iter().filter(|n| **n == name).count(), 1, "{out:?}"); + let (default, _) = sheet(json!({})); + assert!(legend(&default).2.iter().all(|n| out.contains(n)), "{out:?}"); + assert!(find(&s, "Legend Box").unwrap().h < find(&default, "Legend Box").unwrap().h); +} + +#[test] +fn a_publication_legend_title_is_drawn_and_the_box_grows_to_hold_it() { + let (default, _) = sheet(json!({})); + let (s, _) = sheet(json!({"legend": {"title": "Leyenda"}})); + assert_eq!(legend(&s).1, "Leyenda"); + let (bx, was) = (find(&s, "Legend Box").unwrap(), find(&default, "Legend Box").unwrap()); + let title = crate::render::layout::legend_title_mm(rustgis_map::layout::LEGEND_TEXT_PT); + assert!((bx.h - was.h - title).abs() < 1e-6, "{} {} {title}", bx.h, was.h); + let long = "A legend title much wider than any of its rows"; + let (wide, _) = sheet(json!({"legend": {"title": long}})); + let wanted = crate::render::layout::legend_title_width_mm(long, rustgis_map::layout::LEGEND_TEXT_PT); + assert!(find(&wide, "Legend").unwrap().w >= wanted - 1e-6, "{wanted}"); +} + +#[test] +fn a_publication_legend_given_nothing_is_the_default_one() { + let elements = |parts: Value| serde_json::to_value(&sheet(parts).0.project.layouts[0].elements).unwrap(); + let default = elements(json!({})); + for legend in [json!(null), json!({}), json!({"title": null, "columns": null, "exclude": null}), json!({"title": "", "exclude": []})] { + assert_eq!(elements(json!({"legend": legend})), default, "{legend}"); + } +} + +#[test] +fn a_publication_legend_given_wrong_is_refused_and_nothing_is_made() { + let most = rustgis_map::layout::MAX_LEGEND_COLUMNS; + let columns = format!("columns is a whole number from 1 to {most}"); + for (given, said) in [ + (json!({"columns": 0}), columns.as_str()), + (json!({"columns": most + 1}), columns.as_str()), + (json!({"columns": "2"}), columns.as_str()), + (json!({"exclude": ["Nowhere"]}), "no layer 'Nowhere'"), + (json!({"exclude": "Cities"}), "exclude is a list of layer names"), + (json!({"exclude": [1]}), "exclude is a list of layer names"), + (json!({"title": 5}), "title is text"), + (json!({"title": "x".repeat(201)}), "title is 201 characters"), + (json!({"labels": {}}), "legend takes no \"labels\" (it reads title, columns, exclude)"), + (json!({"allClasses": true}), "legend takes no \"allClasses\""), + (json!({"hideOther": true}), "legend takes no \"hideOther\""), + (json!(5), "legend is \"none\""), + (json!(true), "legend is \"none\""), + (json!("auto"), "legend is \"none\""), + ] { + let mut s = world(); + let maps = s.project.maps.len(); + let err = publish(&mut s, json!({"legend": given})).unwrap_err(); + assert!(err.contains(said), "{given}: {err}"); + assert_eq!((s.project.layouts.len(), s.project.maps.len()), (0, maps), "{given}"); + } +} + +#[test] +fn a_saved_publication_that_sets_its_legend_requires_its_capability() { + let requires = |legend: Value| { + let mut s = world(); + let step = json!({"tool": "layout.publication", "params": {"legend": legend}}); + s.project.models.push(serde_json::from_value(json!({"name": "Sheet", "steps": [step]})).unwrap()); + serde_json::to_value(&s.project).unwrap()["requires"].to_string().contains("layout-publication-legend") + }; + for legend in [json!("none"), json!({"title": "Key"}), json!({"columns": 2}), json!({"exclude": ["Cities"]})] { + assert!(requires(legend.clone()), "{legend}"); + } + for legend in [json!(null), json!({}), json!({"title": null, "columns": null})] { + assert!(!requires(legend.clone()), "{legend}"); + } +} + +#[test] +fn the_publication_legend_fixture_opens_and_keeps_its_requirement() { + let fixture = crate::Project::from_json(include_str!("../../../../schema/fixtures/layout_publication_legend.rgis")).unwrap(); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["layout-publication-legend"])); +} diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index 8e18060de4..7c9bac3122 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -1319,6 +1319,12 @@ pub fn legend_fitted_mm( }) } +/// The width in mm [`legend`] draws `title` in, in a legend whose text is `text_size` points +/// (#3095). +pub fn legend_title_width_mm(title: &str, text_size: f64) -> f64 { + f64::from(text::measure(title, LEGEND_TITLE_PT * legend_size(text_size), true)) / PT_PER_MM +} + /// The height in mm [`legend`] gives a title above its rows, which [`legend_sizes_mm`] leaves out, /// in a legend whose text is `text_size` points (#2581). pub fn legend_title_mm(text_size: f64) -> f64 { diff --git a/docs/maintaining.md b/docs/maintaining.md index d4c03b4e49..328f179d1e 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -357,6 +357,10 @@ requires `layout-publication-parts`, so an older reader refuses it instead of ma 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. +A saved `layout.publication` that leaves out or sets up its legend (`legend` as `"none"` or an +object that gives something, #3095) requires `layout-publication-legend`, so an older reader +refuses it instead of making the default legend. `null` and a `legend` of `{}` 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 27c18088ac..d955d81cf4 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -155,6 +155,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (`{"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**: `"legend": "none"` leaves it out, and a raster's colorbar keeps its box. + `{"title": "Key", "columns": 2, "exclude": ["Rivers"]}` gives it a title (its box grows to + hold it), a fixed number of columns (1 to 6; otherwise the placement picks 1 to 3) and layers + to leave out besides the context ones. An unknown layer or key is refused. - **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_legend.rgis b/schema/fixtures/layout_publication_legend.rgis new file mode 100644 index 0000000000..209a0e4616 --- /dev/null +++ b/schema/fixtures/layout_publication_legend.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Publication legend","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":"Keyed sheet","steps":[{"tool":"layout.publication","params":{"legend":{"title":"Key","columns":2}}}]}],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[],"requires":["layout-publication-legend"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 987e8deb7f..e2ec0c42d3 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1288,7 +1288,8 @@ "tile-resampling", "layout-page-color", "layout-text-statistics", - "layout-publication-parts" + "layout-publication-parts", + "layout-publication-legend" ], "type": "string" }, @@ -1405,7 +1406,8 @@ "tile-resampling", "layout-page-color", "layout-text-statistics", - "layout-publication-parts" + "layout-publication-parts", + "layout-publication-legend" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From 651fff3c52c4e2d79279e7225f9c3c49ff604c21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 12:44:04 -0500 Subject: [PATCH 2/7] fix(layout): a blank legend title is none, and a title with nothing to list is said --- .../engine/src/cmd/layout/publication/mod.rs | 3 ++ .../src/cmd/layout/publication/parts.rs | 2 ++ crates/engine/src/project_capabilities.rs | 6 ++-- .../src/tests/layout_publication_parts.rs | 28 +++++++++++++++++-- docs/maintaining.md | 3 +- 5 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index fa751a3e41..a9e5247908 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1765,6 +1765,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu .into(), ); } + if ch <= 0.0 && legend.as_ref().is_some_and(|l| !l.title.is_empty()) { + warnings.push("the legend lists nothing, so it is left out, its title with it".into()); + } let mut placed: Vec<(&'static str, (f64, f64, f64, f64))> = Vec::new(); let spot_of = |what: Surround| spots.iter().find(|(kind, _)| *kind == what).map(|(_, r)| *r); // In a column, at its top, centred across it; otherwise in its corner over the map. diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index 6de05709d2..30076c0064 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -112,6 +112,8 @@ pub(super) fn publication_legend(p: &Value, map: &Map) -> Result base.title, Some(v) => crate::cmd::within("title", "a legend's title", v.as_str().ok_or("title is text")?, 200)?, }; + // A blank title is none, rather than an empty line over the rows. + let title = if title.trim().is_empty() { String::new() } else { title }; let exclude = o.get("exclude").map(|v| excluded_layers(map, v)).transpose()?.unwrap_or_default(); Ok(PublicationLegend { title, columns: legend_columns_param(o)?, exclude }) }) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 176d942748..9d8dd96775 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -205,11 +205,13 @@ fn command_sets_publication_parts(id: &str, params: &Value) -> bool { } /// A saved `layout.publication` that leaves out or sets up its legend (#3095): an older reader -/// ignores `legend`, making the default one. `null`, and an object giving nothing, ask for it. +/// ignores `legend`, making the default one. `null`, and an object giving nothing (each key +/// `null`, a blank title or an empty list), ask for it. fn command_sets_publication_legend(id: &str, params: &Value) -> bool { + let nothing = |v: &Value| v.is_null() || v.as_str().is_some_and(|t| t.trim().is_empty()) || v.as_array().is_some_and(Vec::is_empty); match id { "layout.publication" => { - params.get("legend").is_some_and(|v| !v.is_null() && v.as_object().is_none_or(|o| o.values().any(|v| !v.is_null()))) + params.get("legend").is_some_and(|v| !v.is_null() && v.as_object().is_none_or(|o| !o.values().all(nothing))) } "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_publication_legend)), _ => false, diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index bdb836e2d2..0aed3510b5 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -282,6 +282,7 @@ fn with_colorbar(parts: Value) -> (Session, Value) { let mut s = world(); s.run("layer.addData", &json!({"path": tif.display().to_string()})).unwrap(); let r = publish(&mut s, parts).unwrap(); + let _ = std::fs::remove_file(tif); (s, r) } @@ -325,6 +326,7 @@ fn a_publication_legend_keeps_its_columns_on_a_veiled_map() { let fc = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": ring}}]}); let path = temp("fill.geojson"); std::fs::write(&path, fc.to_string()).unwrap(); + // Thirty layers make a legend too long for the room the map leaves, so the map is veiled. for _ in 0..30 { s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); } @@ -342,6 +344,9 @@ fn a_publication_legend_keeps_its_columns_on_a_veiled_map() { &json!({"profile": "a4-portrait", "extent": [10.0, 57.0, 30.0, 61.0], "author": "", "locator": "none", "legend": {"columns": 2}}), ) .unwrap(); + for file in [path, points] { + let _ = std::fs::remove_file(file); + } assert_eq!(r["veiled"], json!(true), "{r}"); assert_eq!((legend(&s).0, r["legendColumns"].as_u64()), (2, Some(2)), "{r}"); } @@ -371,11 +376,28 @@ fn a_publication_legend_title_is_drawn_and_the_box_grows_to_hold_it() { assert!(find(&wide, "Legend").unwrap().w >= wanted - 1e-6, "{wanted}"); } +#[test] +fn a_publication_legend_title_with_nothing_to_list_says_it_is_left_out() { + let w = world(); + let all: Vec<&str> = w.map().layers.iter().map(|l| l.name.as_str()).collect(); + let (s, r) = sheet(json!({"legend": {"title": "Key", "exclude": all}})); + assert!(find(&s, "Legend").is_none()); + assert!(r["warnings"].to_string().contains("the legend lists nothing"), "{}", r["warnings"]); + let (_, r) = sheet(json!({"legend": {"exclude": all}})); + assert!(!r["warnings"].to_string().contains("the legend lists nothing"), "{}", r["warnings"]); +} + #[test] fn a_publication_legend_given_nothing_is_the_default_one() { let elements = |parts: Value| serde_json::to_value(&sheet(parts).0.project.layouts[0].elements).unwrap(); let default = elements(json!({})); - for legend in [json!(null), json!({}), json!({"title": null, "columns": null, "exclude": null}), json!({"title": "", "exclude": []})] { + for legend in [ + json!(null), + json!({}), + json!({"title": null, "columns": null, "exclude": null}), + json!({"title": "", "exclude": []}), + json!({"title": " "}), + ] { assert_eq!(elements(json!({"legend": legend})), default, "{legend}"); } } @@ -419,7 +441,9 @@ fn a_saved_publication_that_sets_its_legend_requires_its_capability() { for legend in [json!("none"), json!({"title": "Key"}), json!({"columns": 2}), json!({"exclude": ["Cities"]})] { assert!(requires(legend.clone()), "{legend}"); } - for legend in [json!(null), json!({}), json!({"title": null, "columns": null})] { + for legend in + [json!(null), json!({}), json!({"title": null, "columns": null}), json!({"title": ""}), json!({"title": " ", "exclude": []})] + { assert!(!requires(legend.clone()), "{legend}"); } } diff --git a/docs/maintaining.md b/docs/maintaining.md index 328f179d1e..b7109cfc15 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -359,7 +359,8 @@ as the text `"auto"`, `"always"` or `"none"` need nothing. A saved `layout.publication` that leaves out or sets up its legend (`legend` as `"none"` or an object that gives something, #3095) requires `layout-publication-legend`, so an older reader -refuses it instead of making the default legend. `null` and a `legend` of `{}` need nothing. +refuses it instead of making the default legend. `null`, a `legend` of `{}`, a blank `title` and +an empty `exclude` need nothing. ## New dependencies From 55cc4a5b9eefc14c768c8fa42c8eca80fffa0ce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 13:02:01 -0500 Subject: [PATCH 3/7] fix(layout): a publication legend title wider than its box is named in the warning --- crates/engine/src/cmd/layout/publication/mod.rs | 11 ++++++++++- crates/engine/src/project_capabilities.rs | 4 ++-- crates/engine/src/tests/layout_publication_parts.rs | 13 +++++++++++++ docs/user-guide/layouts.md | 3 ++- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index a9e5247908..d1ba072f54 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1859,7 +1859,16 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let bar_need = bar.as_deref().map_or(0.0, |title| colorbar_mm(title, iw)); let bar_fit = colorbar_fit(bar_need, ih, ch + bar_gap, over_map); let rows_h = (ih - bar_fit - if bar.is_some() { bar_gap } else { 0.0 }).max(0.0); - warnings.extend(legend_fit_warnings(LegendFit::Manual, legend_cols, overflows((cw, ch), (iw, rows_h)))); + let (mut too_wide, too_tall) = overflows((cw, ch), (iw, rows_h)); + // A title wider than the box is named: the width past it is the title's, unless the rows + // are wider still. + let title = legend.as_ref().map(|l| l.title.as_str()).filter(|t| ch > 0.0 && !t.is_empty()); + let title_w = title.map_or(0.0, |t| crate::render::layout::legend_title_width_mm(t, legend_pt)); + if title_w > iw + LEGEND_FIT_MM { + warnings.push("the legend's title is wider than its box: shorten it".into()); + too_wide &= cw > title_w + LEGEND_FIT_MM; + } + warnings.extend(legend_fit_warnings(LegendFit::Manual, legend_cols, (too_wide, too_tall))); let short = bar_need > bar_fit + LEGEND_FIT_MM; // In a column the colorbar takes the column's width, as its rows do. if let Some(layer) = bar.as_deref().filter(|_| (base_w > iw + LEGEND_FIT_MM && !legend_in_column) || short) { diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 9d8dd96775..54dd7e43ef 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -205,8 +205,8 @@ fn command_sets_publication_parts(id: &str, params: &Value) -> bool { } /// A saved `layout.publication` that leaves out or sets up its legend (#3095): an older reader -/// ignores `legend`, making the default one. `null`, and an object giving nothing (each key -/// `null`, a blank title or an empty list), ask for it. +/// ignores `legend`, making the default one. `null` and an object giving nothing (each key +/// `null`, a blank title or an empty list) ask for that default, so they require nothing. fn command_sets_publication_legend(id: &str, params: &Value) -> bool { let nothing = |v: &Value| v.is_null() || v.as_str().is_some_and(|t| t.trim().is_empty()) || v.as_array().is_some_and(Vec::is_empty); match id { diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 0aed3510b5..0fd11b7409 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -453,3 +453,16 @@ fn the_publication_legend_fixture_opens_and_keeps_its_requirement() { let fixture = crate::Project::from_json(include_str!("../../../../schema/fixtures/layout_publication_legend.rgis")).unwrap(); assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["layout-publication-legend"])); } + +#[test] +fn a_publication_legend_title_wider_than_its_box_is_named() { + let long = "A very long legend title ".repeat(8); + for (columns, style) in [(1, "classic"), (2, "classic"), (1, "panel")] { + let (_, r) = sheet(json!({"legend": {"title": long, "columns": columns}, "style": style})); + let said = r["warnings"].to_string(); + assert!(said.contains("the legend's title is wider than its box: shorten it"), "{columns} {style}: {said}"); + assert!(!said.contains("columns are wider") && !said.contains("ends of long labels"), "{columns} {style}: {said}"); + } + let (_, r) = sheet(json!({"legend": {"title": "Key"}})); + assert!(!r["warnings"].to_string().contains("wider than its box"), "{}", r["warnings"]); +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index d955d81cf4..2b1f7589c9 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -158,7 +158,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu - **Legend**: `"legend": "none"` leaves it out, and a raster's colorbar keeps its box. `{"title": "Key", "columns": 2, "exclude": ["Rivers"]}` gives it a title (its box grows to hold it), a fixed number of columns (1 to 6; otherwise the placement picks 1 to 3) and layers - to leave out besides the context ones. An unknown layer or key is refused. + to leave out besides the context ones. A title wider than the box is said in a warning. An + unknown layer or key is refused. - **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 From 869a7dca4da4b2067da22ab82bd9c5a0bf4304c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 13:07:30 -0500 Subject: [PATCH 4/7] fix(layout): a publication legend waits for no layer it leaves out and keeps the asked ones first --- .../engine/src/cmd/layout/publication/mod.rs | 6 +++- .../src/cmd/layout/publication/parts.rs | 7 +++-- .../src/tests/layout_publication_parts.rs | 31 +++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index d1ba072f54..18eae4c906 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1111,7 +1111,11 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu (fw * 0.3, fh * 0.25) } }; - let listed = legend.is_some() && s.map().layers.iter().any(|l| s.map().shows(l) && crate::render::layout::legend_lists(l)); + // Whether a layer the legend isn't asked to leave out may have rows in it. + let listed = legend.as_ref().is_some_and(|legend| { + let asked_out = |name: &str| legend.exclude.iter().any(|n| n.eq_ignore_ascii_case(name)); + s.map().layers.iter().any(|l| s.map().shows(l) && crate::render::layout::legend_lists(l) && !asked_out(&l.name)) + }); if reading && listed { (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); sizes = None; diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index 30076c0064..080779a2cc 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -120,10 +120,11 @@ pub(super) fn publication_legend(p: &Value, map: &Map) -> Result Vec { - [context, &self.exclude].concat() + [&self.exclude, context].concat() } /// The legend's size in each number of columns the placement tries, in mm, its text `text_pt` diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 0fd11b7409..33dfce3026 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -466,3 +466,34 @@ fn a_publication_legend_title_wider_than_its_box_is_named() { let (_, r) = sheet(json!({"legend": {"title": "Key"}})); assert!(!r["warnings"].to_string().contains("wider than its box"), "{}", r["warnings"]); } + +#[test] +fn a_publication_legend_does_not_wait_for_a_layer_it_leaves_out() { + // A raster read in place from a host that never answers: still reading throughout. + let host = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let mut s = Session::new(Project::default()); + let address = format!("http://{}/depth.tif", host.local_addr().unwrap()); + let mut raster = rustgis_map::raster::RasterLayer::opening_in_place(address); + // Drawn by classes, so the legend would list it. + raster.style.renderer = rustgis_map::raster::RasterRenderer::Colormap; + s.map_mut().add_raster("Depth".to_string(), raster); + let mut said = |legend: Value| { + let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "colorbar": "none", "legend": legend}); + s.run("layout.publication", &p).unwrap()["warnings"].to_string() + }; + let waited = said(json!({"title": "Key"})); + assert!(waited.contains("classes aren't known yet"), "{waited}"); + let left_out = said(json!({"title": "Key", "exclude": ["Depth"]})); + assert!(!left_out.contains("classes aren't known yet") && left_out.contains("the legend lists nothing"), "{left_out}"); +} + +#[test] +fn a_publication_legend_lists_the_layers_asked_to_leave_out_first() { + // A loaded project keeps the first `MAX_LEGEND_EXCLUDED` names: those asked come first. + let mut s = world(); + let name = "Cities".to_string(); + s.run("layout.publication", &json!({"extent": [0, 40, 20, 55], "legend": {"exclude": [name.clone()]}})).unwrap(); + let out = legend(&s).2; + assert!(out.len() > 1, "a context layer too: {out:?}"); + assert_eq!(out[0], name); +} From 63d1b9f5773c5bfb22211bdeebca78caca369a52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 14:39:46 -0500 Subject: [PATCH 5/7] fix(layout): a publication without a legend still waits for a layer before moving the map --- .../engine/src/cmd/layout/publication/mod.rs | 2 +- .../src/tests/layout_publication_parts.rs | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index a618a69e40..26612621a4 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1423,7 +1423,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let reading = s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); let here_context = if tried == asked_scale { context.clone() } else { context_at(s, centred, tried) }; - let here = if (reading && legend.is_some()) || (tried != asked_scale && pictures_pending(s, render_scale)) { + let here = if reading || (tried != asked_scale && pictures_pending(s, render_scale)) { unknown_at.get_or_insert(tried); None } else if tried == asked_scale { diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 33dfce3026..4ddb60316a 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -497,3 +497,37 @@ fn a_publication_legend_lists_the_layers_asked_to_leave_out_first() { assert!(out.len() > 1, "a context layer too: {out:?}"); assert_eq!(out[0], name); } + +#[test] +fn a_publication_without_a_legend_still_waits_for_a_layer_before_moving_the_map() { + // Land drawn by classes filling the frame leaves the colorbar's box no free room, so the search + // runs. + let ring = json!([[[-30.0, -30.0], [40.0, -30.0], [40.0, 40.0], [-30.0, 40.0], [-30.0, -30.0]]]); + let land = temp("land.geojson"); + let tif = temp("scale.tif"); + let fc = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"k": "a"}, "geometry": {"type": "Polygon", "coordinates": ring}}]}); + std::fs::write(&land, fc.to_string()).unwrap(); + std::fs::write(&tif, rustgis_data::raster::cog::example(256, 128)).unwrap(); + let mut s = Session::new(Project::default()); + for path in [&land, &tif] { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let name = s.map().layers.iter().find(|l| l.raster.is_none()).unwrap().name.clone(); + s.run("layer.symbology", &json!({"layer": name, "type": "unique", "field": "k"})).unwrap(); + // A raster read in place from a host that never answers: still reading throughout. + let host = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = format!("http://{}/depth.tif", host.local_addr().unwrap()); + let mut raster = rustgis_map::raster::RasterLayer::opening_in_place(address); + raster.style.renderer = rustgis_map::raster::RasterRenderer::Colormap; + s.map_mut().add_raster("Depth".to_string(), raster); + // The land over the ramp, which keeps its colorbar from under it. + s.run("layer.move", &json!({"layer": name, "to": 0})).unwrap(); + let p = json!({"profile": "a4-portrait", "extent": [0, 0, 20, 20], "author": "", "locator": "none", "legend": "none"}); + let r = s.run("layout.publication", &p).unwrap(); + for file in [land, tif] { + let _ = std::fs::remove_file(file); + } + assert!(find(&s, "Colorbar").is_some(), "{r}"); + assert!(r["warnings"].to_string().contains("a layer there is still reading"), "{r}"); + assert_eq!((r["mapShift"][0].as_f64(), r["veiled"].as_bool()), (Some(0.0), Some(false)), "{r}"); +} From 096440e1cc9b6dcfedcb5f9343568d5199768ad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 14:59:40 -0500 Subject: [PATCH 6/7] fix(layout): a publication legend whose rows are wider than its box says so under a wider title --- crates/engine/src/cmd/layout.rs | 2 +- .../engine/src/cmd/layout/publication/mod.rs | 9 ++++++- .../src/cmd/layout/publication/parts.rs | 24 ++++++++++++++----- .../src/tests/layout_publication_parts.rs | 10 ++++++++ docs/user-guide/layouts.md | 3 ++- 5 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 3414229b6f..88b063e0ac 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -85,7 +85,7 @@ pub fn commands() -> Vec { 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; 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#""legend"?: "none" (no legend; a colorbar keeps its box) | {"title"?: text, "columns"?: 1 to 6 (that many; the placement picks 1 to 3 otherwise), "exclude"?: [layer names] (left out besides the context ones)}, "#, + r#""legend"?: "none" (no legend; a colorbar keeps its box, and the answer's "legendColumns" is null) | {"title"?: text, "columns"?: 1 to 6 (that many; the placement picks 1 to 3 otherwise), "exclude"?: [layer names] (left out besides the context ones)}, "#, 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) | "edge" (the map from one side of the page to the other with no border, a kicker and the title over it, the footer with no boxes under a thin rule) (a sheet's arrangement; figures leave it to the caption), "#, r##""paper"?: "#RRGGBB" (an edge sheet's page colour, as layout.page's "color"; white by default; on a dark one its texts are light), "##, diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 26612621a4..7f4d47c18a 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1921,7 +1921,14 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let title_w = title.map_or(0.0, |t| crate::render::layout::legend_title_width_mm(t, legend_pt)); if title_w > iw + LEGEND_FIT_MM { warnings.push("the legend's title is wider than its box: shorten it".into()); - too_wide &= cw > title_w + LEGEND_FIT_MM; + // `cw` holds the title's width too: where the title is the widest, the rows are + // measured on their own. Rows of unknown size aren't said to be wider. + if let Some(legend) = legend.as_ref().filter(|_| cw <= title_w + LEGEND_FIT_MM) { + let at = crate::render::layout::frame_render_scale(s.map(), center, scale); + let rows = sizes.and_then(|_| legend.rows_sizes(s.map_mut(), at, &context, legend_pt)); + let column = legend_cols.min(PUBLICATION_LEGEND_COLUMNS) - 1; + too_wide = rows.is_some_and(|rows| rows[column].0 > iw + LEGEND_FIT_MM); + } } warnings.extend(legend_fit_warnings(LegendFit::Manual, legend_cols, (too_wide, too_tall))); let short = bar_need > bar_fit + LEGEND_FIT_MM; diff --git a/crates/engine/src/cmd/layout/publication/parts.rs b/crates/engine/src/cmd/layout/publication/parts.rs index 080779a2cc..2b370d896b 100644 --- a/crates/engine/src/cmd/layout/publication/parts.rs +++ b/crates/engine/src/cmd/layout/publication/parts.rs @@ -137,6 +137,23 @@ impl PublicationLegend { scale: f64, context: &[String], text_pt: f64, + ) -> Option<[(f64, f64); PUBLICATION_LEGEND_COLUMNS]> { + let sizes = self.rows_sizes(map, scale, context, text_pt)?; + if self.title.is_empty() { + return Some(sizes); + } + let title_w = crate::render::layout::legend_title_width_mm(&self.title, text_pt); + let title_h = crate::render::layout::legend_title_mm(text_pt); + Some(sizes.map(|(w, h)| if h > 0.0 { (w.max(title_w), h + title_h) } else { (w, h) })) + } + + /// [`PublicationLegend::sizes`] of the rows alone, without the title. + pub(super) fn rows_sizes( + &self, + map: &mut Map, + scale: f64, + context: &[String], + text_pt: f64, ) -> Option<[(f64, f64); PUBLICATION_LEGEND_COLUMNS]> { use crate::render::layout::{LegendAsked, legend_size_asked_mm, legend_sizes_in_columns_mm}; let exclude = self.left_out(context); @@ -156,11 +173,6 @@ impl PublicationLegend { [legend_size_asked_mm(map, scale, &asked, columns)?; PUBLICATION_LEGEND_COLUMNS] } }; - if self.title.is_empty() { - return Some(sizes); - } - let title_w = crate::render::layout::legend_title_width_mm(&self.title, text_pt); - let title_h = crate::render::layout::legend_title_mm(text_pt); - Some(sizes.map(|(w, h)| if h > 0.0 { (w.max(title_w), h + title_h) } else { (w, h) })) + Some(sizes) } } diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index 4ddb60316a..ebcfa05f80 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -531,3 +531,13 @@ fn a_publication_without_a_legend_still_waits_for_a_layer_before_moving_the_map( assert!(r["warnings"].to_string().contains("a layer there is still reading"), "{r}"); assert_eq!((r["mapShift"][0].as_f64(), r["veiled"].as_bool()), (Some(0.0), Some(false)), "{r}"); } + +#[test] +fn a_publication_legend_wider_than_its_box_is_said_under_a_wider_title_too() { + // Six columns in a side column don't fit it, and the title is wider than they are. + let long = "A very long legend title ".repeat(8); + let (_, r) = sheet(json!({"legend": {"title": long, "columns": 6}, "style": "panel"})); + let said = r["warnings"].to_string(); + assert!(said.contains("the legend's title is wider than its box"), "{said}"); + assert!(said.contains("the legend's columns are wider than its box"), "{said}"); +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index d2b922d9f4..353259e311 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -159,7 +159,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (`{"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**: `"legend": "none"` leaves it out, and a raster's colorbar keeps its box. + - **Legend**: `"legend": "none"` leaves it out, and a raster's colorbar keeps its box; the answer's + `legendColumns` is then `null`. `{"title": "Key", "columns": 2, "exclude": ["Rivers"]}` gives it a title (its box grows to hold it), a fixed number of columns (1 to 6; otherwise the placement picks 1 to 3) and layers to leave out besides the context ones. A title wider than the box is said in a warning. An From 7bb56320c06b9eba5e28d98aa0c1317bfb080c83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 27 Nov 2026 15:55:41 -0500 Subject: [PATCH 7/7] fix(layout): a publication warns of no raster its legend does not key --- .../engine/src/cmd/layout/publication/mod.rs | 5 +++- .../src/tests/layout_publication_parts.rs | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 7f4d47c18a..d31776abef 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -1237,7 +1237,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu } // A colour table whose values can't be known (too many to list) gives the legend no class, and // the sheet no key for it; classes from an overview may miss a rare one: said, not left out. - warnings.extend(raster_key_notices(s.map(), &[], false)); + // Of the rasters the legend keys: none without one. + if let Some(legend) = &legend { + warnings.extend(raster_key_notices(s.map(), &legend.exclude, false)); + } // A page of cards gives the locator in its column a card of the column's width, and the legend // under it one as wide. let card = style == Style::Modular && column.is_some(); diff --git a/crates/engine/src/tests/layout_publication_parts.rs b/crates/engine/src/tests/layout_publication_parts.rs index ebcfa05f80..28407ece7c 100644 --- a/crates/engine/src/tests/layout_publication_parts.rs +++ b/crates/engine/src/tests/layout_publication_parts.rs @@ -541,3 +541,27 @@ fn a_publication_legend_wider_than_its_box_is_said_under_a_wider_title_too() { assert!(said.contains("the legend's title is wider than its box"), "{said}"); assert!(said.contains("the legend's columns are wider than its box"), "{said}"); } + +#[test] +fn a_publication_legend_says_nothing_of_a_raster_it_does_not_key() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + // A colour table over more values than a legend can list. + let mut s = Session::new(Project::default()); + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 0.5, pixel_height: -0.5 }; + let z: Vec = (0..400u16).map(f32::from).collect(); + let r = Raster::new("many", 20, 20, vec![z], gt, Crs::LonLat, None, ColorHint::Palette(vec![[0, 0, 0, 255]; 400]), "UInt16").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + let mut layer = rustgis_map::RasterLayer::from_bytes(r, "many.tif".to_string(), bytes); + layer.style.renderer = rustgis_map::RasterRenderer::Colormap; + crate::cmd::raster::add_raster(&mut s, "many", layer).unwrap(); + let mut said = |legend: Value| { + let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "legend": legend}); + s.run("layout.publication", &p).unwrap()["warnings"].to_string() + }; + let keyed = said(json!(null)); + assert!(keyed.contains("have no key in the legend: many"), "{keyed}"); + for legend in [json!("none"), json!({"exclude": ["many"]})] { + let w = said(legend.clone()); + assert!(!w.contains("have no key in the legend"), "{legend}: {w}"); + } +}