From a6d3f2c7e20fb80cc0b891a0611c9831f5586e75 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 15 Nov 2026 01:10:54 -0300 Subject: [PATCH 1/6] feat(layout): context layers out of a publication's legend, and no north arrow at a continental span (#1379) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Items 5 and 6 of #1379's "Left to do": - The layers the placement already takes as context around the data (polygons only outlined; one-colour polygons running on past the frame beside a layer drawn by classes or a raster) are left out of the publication's legend too, and a warning names them. "contextInLegend": true lists them. render::layout::context_layers is the one rule both use. - An extent spanning 20° or more on its longer side gets no north arrow: the graticule gives north there. A warning says so; "northArrow": "always" draws one and "none" leaves it out at any span. A veiled map's group is laid out without it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 111 +++++++++++++++++++++++++++----- crates/engine/src/tests.rs | 108 ++++++++++++++++++++++++++++++- crates/render/src/layout.rs | 47 ++++++++------ docs/user-guide/layouts.md | 8 +++ 4 files changed, 238 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 03143809e5..40baae691a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -32,7 +32,7 @@ pub fn commands() -> Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "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), "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), "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), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "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), "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), "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), "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", "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), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.arrangement", "Favourite Arrangement", "Publish › Layout", arrangement).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"favourite"?: "classic" (the locator top left, the north arrow top right, the legend bottom left, the scale bar bottom right) | "mirrored" | "legendRight" | "legendTop" | {"locator", "northArrow", "legend", "scaleBar": "top-left"|"top-right"|"bottom-left"|"bottom-right", each a corner of its own} | a saved arrangement's name, "save"?: a name (1 to 40 characters, not a built-in one nor "best", "favourite", "custom" or "veil"; one saved under it already, case aside, is replaced) to save "arrangement" under (at most 20 saved), "arrangement"?: what "save" saves: an arrangement by name, or a corner for each surround as "favourite" takes them (refused without "save"), "remove"?: a saved arrangement's name (a favourite named after it keeps its corners, unless "favourite" gives another)} → the favourite arrangement of publication layouts and those saved by name (kept with the app's preferences), the favourite's corners, the arrangements by name and the saved ones' corners; a removal, then a save, then the favourite; with none of them given, they are only shown"#, @@ -697,18 +697,21 @@ pub(crate) fn crop_cells( /// The surrounds of a veiled map grouped in a band of its veil: the locator with the north arrow at /// its right and the scale bar under them, beside the legend or over it, whichever the band's shape -/// suits, centred in it. Gives the legend's, locator's, arrow's and scale bar's places; `None` when -/// they don't fit either way. +/// suits, centred in it. Gives the legend's, locator's, arrow's and scale bar's places (the locator's +/// and the arrow's when there is one); `None` when they don't fit either way. pub(crate) fn veil_panel( band: Rect, legend: (f64, f64), locator: Option, - arrow: (f64, f64), + arrow: Option<(f64, f64)>, scale: (f64, f64), gap: f64, -) -> Option<(Rect, Option, Rect, Rect)> { +) -> Option<(Rect, Option, Option, Rect)> { let (bx, by, bw, bh) = band; - let top = (locator.map_or(0.0, |side| side + gap) + arrow.0, locator.unwrap_or(0.0).max(arrow.1)); + let (aw, ah) = arrow.unwrap_or((0.0, 0.0)); + // 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)); let group = (top.0.max(scale.0), top.1 + gap + 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; @@ -725,7 +728,7 @@ pub(crate) fn veil_panel( Some(( (legend_at.0, legend_at.1, legend.0, legend.1), locator.map(|side| (group_at.0, group_at.1, side, side)), - (group_at.0 + group.0 - arrow.0, group_at.1, arrow.0, arrow.1), + arrow.map(|(aw, ah)| (group_at.0 + group.0 - aw, group_at.1, aw, ah)), (group_at.0, group_at.1 + top.1 + gap, scale.0, scale.1), )) } @@ -1180,6 +1183,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let locator = publication_locator(p, sheet)?; 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)?; // 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"] { if p.get(k).is_some_and(|v| !v.is_null() && !v.is_string()) { @@ -1984,7 +1989,36 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { }; let lonlat = crate::render::view_lonlat(s.map(), &view); let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); - let mut sizes = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, (&[], &Default::default())); + // Context around the data (neighbouring borders, the states around in one colour), which the + // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). + // A name is left out only when every shown layer under it is context: the legend leaves layers + // out by name. + let context: Vec = if context_in_legend { + Vec::new() + } else { + let ids = crate::render::layout::context_layers(s.map(), center, scale, (fw, fh)); + let map = s.map(); + let shown: Vec<&rustgis_map::Layer> = + map.layers.iter().filter(|l| map.shows(l) && crate::render::layout::legend_lists(l)).collect(); + let mut names: Vec = Vec::new(); + for l in shown.iter().filter(|l| ids.contains(&l.id)) { + let all = shown.iter().filter(|o| o.name.eq_ignore_ascii_case(&l.name)).all(|o| ids.contains(&o.id)); + if all && !names.iter().any(|n| n.eq_ignore_ascii_case(&l.name)) { + names.push(l.name.clone()); + } + } + names + }; + if !context.is_empty() { + warnings.push(format!( + "the legend leaves out {} context layer{} around the data ({}): \"contextInLegend\": true lists {}", + context.len(), + if context.len() == 1 { "" } else { "s" }, + context.join(", "), + if context.len() == 1 { "it" } else { "them" } + )); + } + let mut sizes = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, (&context, &Default::default())); let (mut cw, mut ch) = match sizes { Some(sizes) => sizes[0], None => { @@ -2028,7 +2062,17 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { if locator_map.is_some() && column.is_none() { surrounds.push((Surround::Locator, side, side)); } - surrounds.push((Surround::Arrow, aw, ah)); + // At a continental span the graticule's lines give north, and one arrow can't point north + // across the whole frame: none, unless "northArrow": "always" (#1379). Said, as any surround + // left out is. + let arrow = north_arrow.unwrap_or(extent_span_deg(&extent) < CONTINENTAL_DEG); + 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" + )); + } // 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 // key there, which the legend's rows don't give): an RGB composite over a DEM leaves it to the @@ -2114,11 +2158,10 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // The fewest columns from `from` up in which the surrounds group in a band around `clip`, with // their places; the scale bar's box `scale_bar` is the one at the scale tried. let grouped = |clip: Rect, from: usize, known: &[(f64, f64); MAX_LEGEND_COLUMNS], scale_bar: (f64, f64)| { - let arrow = arrow_size?; (from..known.len()).find_map(|i| { bands_around(clip) .iter() - .find_map(|band| veil_panel(*band, whole(known[i]), locator_side, arrow, scale_bar, GROUP_GAP)) + .find_map(|band| veil_panel(*band, whole(known[i]), locator_side, arrow_size, scale_bar, GROUP_GAP)) .map(|places| (i, places)) }) }; @@ -2202,8 +2245,13 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } 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_mm(s.map_mut(), render_scale, false, false, (&[], &Default::default())); + let measured = crate::render::layout::legend_sizes_mm( + s.map_mut(), + render_scale, + false, + false, + (&context, &Default::default()), + ); if measured.is_none() { unknown_at.get_or_insert(tried); } @@ -2473,7 +2521,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { for (kind, place) in [ (Surround::Legend, Some(legend_place)), (Surround::Locator, locator_place), - (Surround::Arrow, Some(arrow_place)), + (Surround::Arrow, arrow_place), (Surround::Scale, Some(scale_place)), ] { let Some(place) = place.filter(|_| surrounds.iter().any(|x| x.0 == kind)) else { continue }; @@ -2610,7 +2658,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { title: String::new(), all_classes: false, hide_other: false, - exclude: Vec::new(), + exclude: context.clone(), columns: legend_cols, labels: Default::default(), }, @@ -5300,6 +5348,39 @@ fn publication_colorbar(p: &Value) -> Result { } } +/// A publication's `key` given as `true` or `false`; `None` when it isn't given. +fn publication_flag(p: &Value, key: &str) -> Result, String> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| format!("{key} is true or false")), + } +} + +/// A publication's north arrow: `Some(true)` always drawn ("always"), `Some(false)` never ("none"), +/// `None` left to the extent ("auto", the default: none at a continental span, #1379). +fn publication_north_arrow(p: &Value) -> 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). +pub(crate) const CONTINENTAL_DEG: f64 = 20.0; + +/// An extent's span in degrees on its longer side, its width as long at its middle latitude. +pub(crate) fn extent_span_deg(e: &Extent) -> f64 { + let mid = ((e.min_y + e.max_y) / 2.0).to_radians(); + e.height().max(e.width() * mid.cos()) +} + /// Whether the publication may veil what lies outside the extent when nothing else leaves its /// legend room: `true` (the default) or `false`. fn publication_veil(p: &Value) -> Result { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4b5b00cd2f..ce8fa4119d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8737,10 +8737,15 @@ fn publication_layouts_fit_their_pages() { assert!(reference.contains("Web Mercator") && reference.contains("WGS 84") && reference.contains("2°"), "{reference}"); assert!(text("Author").unwrap().contains("{date}"), "the date stays a token the layout fills"); // Nothing said but, over the sample world's land, the surrounds sharing its one corner - // of sea, or the map moved in its frame for the legend (placement has its own tests). + // of sea, the map moved in its frame for the legend (placement has its own tests), or + // the lakes in one colour beside the countries by classes left out of the legend as + // context (#1379). let said: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); assert!( - said.len() <= 2 && said.iter().all(|w| w.contains("on what the map shows") || w.contains("in its frame")), + said.len() <= 3 + && said.iter().all(|w| w.contains("on what the map shows") + || w.contains("in its frame") + || w.contains("context layer around the data (Lakes)")), "{profile}: {r}" ); } else { @@ -9733,6 +9738,98 @@ fn a_publication_legend_takes_the_columns_that_fit_the_free_rectangle() { let _ = std::fs::remove_dir_all(&dir); } +/// Context around the data is left out of a publication's legend, which a warning names (#1379): +/// a layer that only outlines its polygons, and one in one colour running on past the frame beside +/// a layer drawn by classes. A study area in one colour inside the frame is data, and stays listed. +/// `"contextInLegend": true` lists them all; a choice that isn't true or false is refused. +#[test] +fn a_publication_legend_leaves_out_context_layers() { + let dir = std::env::temp_dir().join(format!("rustgis-legend-context-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let square = |[w, s, e, n]: [f64; 4], k: &str| { + json!({"type": "Feature", "properties": {"k": k}, "geometry": + {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n], [w, n], [w, s]]]}}) + }; + let file = |name: &str, features: Vec| { + let path = dir.join(name); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + path.display().to_string() + }; + let data = file("data.geojson", vec![square([0.0, 0.0, 5.0, 10.0], "a"), square([5.0, 0.0, 10.0, 10.0], "b")]); + let around = file("around.geojson", vec![square([-30.0, -30.0, 40.0, 40.0], "x")]); + let border = file("border.geojson", vec![square([1.0, 1.0, 9.0, 9.0], "x")]); + let study = file("study.geojson", vec![square([2.0, 2.0, 4.0, 4.0], "x")]); + let laid = |extra: Value| { + let mut s = Session::new(Project::default()); + for path in [&around, &data, &study, &border] { + s.run("layer.addData", &json!({"path": path})).unwrap(); + } + s.run("layer.symbology", &json!({"layer": "data", "type": "unique", "field": "k"})).unwrap(); + s.run("layer.color", &json!({"layer": "border", "color": "#00000000"})).unwrap(); + let mut p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.run("layout.publication", &p)?; + let layout = s.project.layouts.last().unwrap(); + let exclude = layout + .elements + .iter() + .find_map(|e| match &e.kind { + rustgis_map::layout::ElementKind::Legend { exclude, .. } => Some(exclude.clone()), + _ => None, + }) + .expect("a legend"); + let said = + r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).find(|w| w.contains("context layer")).map(String::from); + Ok::<_, String>((exclude, said)) + }; + let (mut exclude, said) = laid(json!({})).unwrap(); + exclude.sort(); + assert_eq!(exclude, ["around", "border"], "the context, not the data nor the study area"); + let said = said.expect("said"); + assert!(said.contains("2 context layers") && said.contains("around") && said.contains("border"), "{said}"); + let (exclude, said) = laid(json!({"contextInLegend": true})).unwrap(); + assert!(exclude.is_empty() && said.is_none(), "{exclude:?} {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); +} + +/// A publication whose extent spans 20° or more has no north arrow: its graticule gives north, +/// and one arrow can't point north across the whole frame, which a warning says (#1379). +/// `"northArrow": "always"` draws one, `"none"` leaves it out at any span, and an unknown choice is +/// refused. An extent's width counts as long as it is at its middle latitude. +#[test] +fn a_publication_has_no_north_arrow_at_a_continental_span() { + use crate::cmd::layout::extent_span_deg; + assert!(extent_span_deg(&rustgis_geom::Extent::new(0.0, 60.0, 40.0, 62.0)) < 20.0, "40° of longitude at 61°N is under 20°"); + assert!(extent_span_deg(&rustgis_geom::Extent::new(-82.0, -56.5, -34.5, 13.0)) >= 20.0); + let path = std::env::temp_dir().join(format!("rustgis-north-{}.geojson", std::process::id())); + std::fs::write( + &path, + json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": + {"type": "Polygon", "coordinates": [[[-80.0, -55.0], [-35.0, -55.0], [-35.0, 12.0], [-80.0, 12.0], [-80.0, -55.0]]]}}]}) + .to_string(), + ) + .unwrap(); + let laid = |extent: Value, choice: Value| { + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + let r = s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "author": "", "northArrow": choice}))?; + let arrows = r["elements"].as_array().unwrap().iter().filter(|e| e["name"] == "North Arrow").count(); + let said = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with("no north arrow")); + Ok::<_, String>((arrows, said)) + }; + let continent = json!([-82, -56.5, -34.5, 13]); + assert_eq!(laid(continent.clone(), Value::Null).unwrap(), (0, true), "none on a continent, and said"); + assert_eq!(laid(continent.clone(), json!("auto")).unwrap(), (0, true)); + assert_eq!(laid(continent.clone(), json!("always")).unwrap(), (1, false)); + assert_eq!(laid(json!([-50, -20, -40, -10]), Value::Null).unwrap(), (1, false), "one on a smaller extent"); + assert_eq!(laid(json!([-50, -20, -40, -10]), json!("none")).unwrap(), (0, false), "asked for: not said"); + let bad = laid(continent, json!("north")).unwrap_err(); + assert!(bad.contains("northArrow is \"auto\", \"always\" or \"none\""), "{bad}"); + let _ = std::fs::remove_file(&path); +} + /// `"colorbar": "none"` leaves a raster's colorbar out of a publication, and its room in the /// legend's box with it: the box is the legend's height plus its padding (#1680). An unknown /// choice is refused. @@ -10325,8 +10422,9 @@ fn a_publication_reads_streamed_layers_for_the_move_searchs_wide_drawing() { #[test] fn a_veil_panel_groups_the_surrounds_by_the_bands_shape() { use crate::cmd::layout::veil_panel; - let (legend, arrow, scale) = ((80.0, 50.0), (8.0, 12.0), (60.0, 10.0)); + let (legend, arrow, scale) = ((80.0, 50.0), Some((8.0, 12.0)), (60.0, 10.0)); let (l, locator, a, b) = veil_panel((0.0, 0.0, 160.0, 70.0), legend, Some(40.0), arrow, scale, 3.0).unwrap(); + let a = a.unwrap(); assert!(l.0 + l.2 <= locator.unwrap().0, "beside it: {l:?} {locator:?}"); assert!(a.0 + a.2 <= 160.0 && b.1 >= locator.unwrap().1 + 40.0, "{a:?} {b:?}"); let apart = @@ -10336,6 +10434,10 @@ fn a_veil_panel_groups_the_surrounds_by_the_bands_shape() { 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()); 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(); + assert!(a.is_none(), "no place for an arrow there isn't: {a:?}"); + assert_eq!(locator.unwrap().0, b.0, "the locator over the scale bar: {locator:?} {b:?}"); } /// With no room for any shape of the legend on either side of a centred map, the map moves towards diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d3832f3c21..0deed6f577 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2322,6 +2322,34 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: frame_coverage_judged_on(map, center, scale, (w_mm, h_mm), (w_mm, h_mm), cells) } +/// The visible layers a frame showing `map` at 1:`scale` around `center` takes as context around +/// its data, by id: those that only outline their polygons ([`only_outlines`]) unless nothing else +/// is shown, and those that fill them in one colour ([`plain_fill`]) beside a layer drawn by classes +/// or a raster, when they run on past a frame `judged` (mm) wide and tall, as neighbouring states +/// do. [`frame_coverage`] leaves them out of what the map draws; a publication's legend leaves them +/// out too (#1379). +pub fn context_layers(map: &Map, center: Coord, scale: f64, judged: (f64, f64)) -> Vec { + let at = frame_render_scale(map, center, scale); + if map.layers.iter().filter(|l| map.draws_at(l, at)).all(only_outlines) { + return Vec::new(); + } + let classes = + map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); + let judged_view = View { + width: judged.0 * PT_PER_MM, + height: judged.1 * PT_PER_MM, + pixels_per_point: 1.0, + camera: frame_camera(map, center, scale, 0.0, 0.0), + sky: false, + }; + let frame = crate::view_lonlat(map, &judged_view); + let past_the_frame = |l: &rustgis_map::Layer| { + let e = l.shown_extent(); + !e.is_empty() && (e.min_x < frame.min_x || e.max_x > frame.max_x || e.min_y < frame.min_y || e.max_y > frame.max_y) + }; + map.layers.iter().filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l) && past_the_frame(l)))).map(|l| l.id).collect() +} + /// [`frame_coverage`] of a frame `size` (mm), with what runs on past the frame judged on a frame /// `judged` (mm) with the same centre: a drawing wider than the frame asked for, cut for frames /// moved inside it, leaves out the same one-colour layers as that frame does. @@ -2361,24 +2389,7 @@ pub fn frame_coverage_judged_on( self.map.label_lock_line_anchors = std::mem::take(&mut self.anchors); } } - let at = frame_render_scale(map, center, scale); - let outlines: Vec = if map.layers.iter().filter(|l| map.draws_at(l, at)).all(only_outlines) { - Vec::new() - } else { - let classes = - map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); - let judged_view = View { width: judged.0 * PT_PER_MM, height: judged.1 * PT_PER_MM, ..view }; - let frame = crate::view_lonlat(map, &judged_view); - let past_the_frame = |l: &rustgis_map::Layer| { - let e = l.shown_extent(); - !e.is_empty() && (e.min_x < frame.min_x || e.max_x > frame.max_x || e.min_y < frame.min_y || e.max_y > frame.max_y) - }; - map.layers - .iter() - .filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l) && past_the_frame(l)))) - .map(|l| l.id) - .collect() - }; + let outlines = context_layers(map, center, scale, judged); for l in map.layers.iter_mut().filter(|l| outlines.contains(&l.id)) { l.visible = false; } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 6cd0a4d34e..08f8380f4b 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -100,6 +100,14 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu ordinary elements, to move or delete as any other; `"veil": false` leaves the map unveiled and at its scale. If the legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by hand. + - **Context and north**: the layers the placement takes as context around the data (polygons + only outlined, and polygons in one colour that run on past the frame beside a layer drawn by + classes or a raster) are left out of the legend too, which a warning names; + `"contextInLegend": true` lists them. A name is left out only when every layer shown under it + is context. When the extent spans 20° or more on its longer side (its width taken at its middle + latitude), the layout has no north arrow: the graticule gives north there, and one arrow can't + point north across the whole frame. A warning says so; `"northArrow": "always"` draws one, and + `"none"` leaves it out at any span. - **Decimal comma**: `"decimal": ","` prints the graticule, scale bar and colorbar numbers and `{scale}` with a decimal comma and points between thousands (`0,05`, `1:6.300.000`). `layout.page={"decimal": ","}` sets it on any layout; `"."` restores decimal points. From 18096fa51f3a0463bd5fe006f35304399f8cccde Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 15 Nov 2026 01:54:09 -0300 Subject: [PATCH 2/6] fix(layout): review round 1 on context out of the legend (#1379) - The legend's context is judged again at each scale the legend search draws the map at, as the placement judges it there, and the legend takes the one at the scale settled on; the warning names that one. - A name a web tile layer has is never left out (the legend leaves layers out by name, tiles included). - The width a long legend may take reserves the north arrow's only when there is one. - The test covers a context layer sharing its name with a data layer. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 77 +++++++++++++++++++-------------- crates/engine/src/tests.rs | 13 ++++-- 2 files changed, 55 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 40baae691a..50db59ef8c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1993,31 +1993,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). // A name is left out only when every shown layer under it is context: the legend leaves layers // out by name. - let context: Vec = if context_in_legend { - Vec::new() - } else { - let ids = crate::render::layout::context_layers(s.map(), center, scale, (fw, fh)); - let map = s.map(); - let shown: Vec<&rustgis_map::Layer> = - map.layers.iter().filter(|l| map.shows(l) && crate::render::layout::legend_lists(l)).collect(); - let mut names: Vec = Vec::new(); - for l in shown.iter().filter(|l| ids.contains(&l.id)) { - let all = shown.iter().filter(|o| o.name.eq_ignore_ascii_case(&l.name)).all(|o| ids.contains(&o.id)); - if all && !names.iter().any(|n| n.eq_ignore_ascii_case(&l.name)) { - names.push(l.name.clone()); - } - } - names + // Context around the data (neighbouring borders, the states around in one colour), which the + // 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. + let context_at = |s: &Session, center: Coord, scale: f64| { + if context_in_legend { Vec::new() } else { legend_context(s.map(), center, scale, (fw, fh)) } }; - if !context.is_empty() { - warnings.push(format!( - "the legend leaves out {} context layer{} around the data ({}): \"contextInLegend\": true lists {}", - context.len(), - if context.len() == 1 { "" } else { "s" }, - context.join(", "), - if context.len() == 1 { "it" } else { "them" } - )); - } + let mut context = context_at(s, center, scale); let mut sizes = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, (&context, &Default::default())); let (mut cw, mut ch) = match sizes { Some(sizes) => sizes[0], @@ -2200,8 +2183,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // cut from it: a move is a translation on the page. So the search draws the map once per // scale it tries (at most four times), not once per place. Its legend is measured at // that scale, once, and those sizes are the ones laid out. - let mut drawn: Option<(f64, Option<(u32, u32, Vec)>, Option<[(f64, f64); MAX_LEGEND_COLUMNS]>)> = None; - let mut chosen = known; + type Drawn = (f64, Option<(u32, u32, Vec)>, Option<[(f64, f64); MAX_LEGEND_COLUMNS]>, Vec); + let mut drawn: Option = None; + let (mut chosen, mut chosen_context) = (known, context.clone()); let mut unknown_at: Option = None; // Moved frames drawn on their own (below), by scale and move: a pass with the veil // tries the same moves as the one before it. @@ -2236,6 +2220,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { }; let lonlat = crate::render::view_lonlat(s.map(), &view); let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + 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, &[])) { unknown_at.get_or_insert(tried); @@ -2250,7 +2235,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { render_scale, false, false, - (&context, &Default::default()), + (&here_context, &Default::default()), ); if measured.is_none() { unknown_at.get_or_insert(tried); @@ -2262,9 +2247,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // every move's cut leaves out the same layers. let whole_frame = here .and_then(|_| crate::render::layout::frame_coverage_judged_on(s.map_mut(), centred, tried, wide, (fw, fh), cells)); - drawn = Some((tried, whole_frame, here)); + drawn = Some((tried, whole_frame, here, here_context)); } - let Some((_, Some(whole_frame), Some(here))) = &drawn else { continue }; + let Some((_, Some(whole_frame), Some(here), here_context)) = &drawn else { continue }; let need = |room: (f64, f64)| here.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1); let mut found: Option<(usize, f64)> = None; for (dx, dy) in [(0.0, 0.0), (to_right, 0.0), (-to_left, 0.0), (0.0, to_bottom), (0.0, -to_top)] { @@ -2327,7 +2312,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { found = Some((n, room.0 * room.1)); (center, scale, coverage, map_shift) = (there, tried, Some(moved), (dx, dy)); veiled = veil.then_some(clip); - chosen = *here; + (chosen, chosen_context) = (*here, here_context.clone()); } } if found.is_some() { @@ -2352,7 +2337,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } if scale != asked_scale { warnings.push(format!("the map is drawn at 1:{scale:.0}, not 1:{asked_scale:.0}, to leave the legend room")); - sizes = Some(chosen); + (sizes, context) = (Some(chosen), chosen_context); (cw, ch) = chosen[0]; let (w, h) = whole(chosen[0]); if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Legend) { @@ -2361,6 +2346,15 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } } } + if !context.is_empty() { + warnings.push(format!( + "the legend leaves out {} context layer{} around the data ({}): \"contextInLegend\": true lists {}", + context.len(), + if context.len() == 1 { "" } else { "s" }, + context.join(", "), + if context.len() == 1 { "it" } else { "them" } + )); + } // The scale bar's box as the frame is drawn, moved or at another scale or not. let bar_box = scale_box(ground_per_pt(s, center, scale), scale); if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Scale) { @@ -2480,7 +2474,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let shown = |laid: &Laid, (w, h): (f64, f64)| laid.0.map_or(0.0, |(_, lw, lh)| (lw / w).min(1.0) * (lh / h).min(1.0)); let long = whole(sizes[0]).1 > fh * 0.25; let mut score = (shown(&best.1, whole(sizes[0])), best.1.3.1); - let wide = fw - left - right - 2.0 - aw; + let wide = fw - left - right - 2.0 - arrow_size.map_or(0.0, |(w, _)| w); let free = coverage.as_ref().map(free_room); let fits = free.and_then(|(rw, rh)| sizes.iter().position(|size| whole(*size).0 <= rw && whole(*size).1 <= rh)); // One column too, when the rectangle holds what the box a legend starts with cuts. @@ -5348,6 +5342,25 @@ fn publication_colorbar(p: &Value) -> Result { } } +/// The names a publication's legend leaves out as context around the data: the layers the placement +/// takes as context in a frame `size` (mm) showing `map` at 1:`scale` around `center` +/// ([`crate::render::layout::context_layers`], #1379). The legend leaves layers out by name, so a +/// name is left out only when every layer it would list under that name is context, and no web +/// tile layer has it. +fn legend_context(map: &Map, center: Coord, scale: f64, size: (f64, f64)) -> Vec { + let ids = crate::render::layout::context_layers(map, center, scale, size); + let shown: Vec<&rustgis_map::Layer> = map.layers.iter().filter(|l| map.shows(l) && crate::render::layout::legend_lists(l)).collect(); + let mut names: Vec = Vec::new(); + for l in shown.iter().filter(|l| ids.contains(&l.id)) { + let same = |name: &str| name.eq_ignore_ascii_case(&l.name); + let all = shown.iter().filter(|o| same(&o.name)).all(|o| ids.contains(&o.id)); + if all && !map.tiles.iter().any(|t| same(&t.name)) && !names.iter().any(|n| same(n)) { + names.push(l.name.clone()); + } + } + names +} + /// A publication's `key` given as `true` or `false`; `None` when it isn't given. fn publication_flag(p: &Value, key: &str) -> Result, String> { match p.get(key).filter(|v| !v.is_null()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ce8fa4119d..a9f3588562 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9740,8 +9740,9 @@ fn a_publication_legend_takes_the_columns_that_fit_the_free_rectangle() { /// Context around the data is left out of a publication's legend, which a warning names (#1379): /// a layer that only outlines its polygons, and one in one colour running on past the frame beside -/// a layer drawn by classes. A study area in one colour inside the frame is data, and stays listed. -/// `"contextInLegend": true` lists them all; a choice that isn't true or false is refused. +/// a layer drawn by classes. A study area in one colour inside the frame is data, and stays listed, +/// and so does a context layer sharing its name. `"contextInLegend": true` lists them all; a choice +/// that isn't true or false is refused. #[test] fn a_publication_legend_leaves_out_context_layers() { let dir = std::env::temp_dir().join(format!("rustgis-legend-context-{}", std::process::id())); @@ -9764,10 +9765,14 @@ fn a_publication_legend_leaves_out_context_layers() { for path in [&around, &data, &study, &border] { s.run("layer.addData", &json!({"path": path})).unwrap(); } + // The study area under the name of the context layer around: that name stays listed. + if extra.get("mixed").is_some() { + s.run("layer.rename", &json!({"layer": "study", "name": "around"})).unwrap(); + } s.run("layer.symbology", &json!({"layer": "data", "type": "unique", "field": "k"})).unwrap(); s.run("layer.color", &json!({"layer": "border", "color": "#00000000"})).unwrap(); let mut p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); - p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone().into_iter().filter(|(k, _)| k != "mixed")); let r = s.run("layout.publication", &p)?; let layout = s.project.layouts.last().unwrap(); let exclude = layout @@ -9787,6 +9792,8 @@ fn a_publication_legend_leaves_out_context_layers() { assert_eq!(exclude, ["around", "border"], "the context, not the data nor the study area"); let said = said.expect("said"); assert!(said.contains("2 context layers") && said.contains("around") && said.contains("border"), "{said}"); + let (exclude, said) = laid(json!({"mixed": true})).unwrap(); + 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:?}"); let bad = laid(json!({"contextInLegend": "yes"})).unwrap_err(); From 5d943163960ca9f2327619e6c61749fdbab36a33 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 15 Nov 2026 03:35:55 -0300 Subject: [PATCH 3/6] test(layout): the footer test keeps the sample's lakes in its legend (#1379) a_publication_footer_lines_up_with_its_legend needs a legend that starts between 45 % and 70 % of the frame; its names were chosen with the lakes listed. Without them the rows rebalance across the two columns, and with Linux's fonts no name landed there. The test now passes "contextInLegend": true. Also drops a duplicated comment. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 4 ---- crates/engine/src/tests.rs | 6 ++++-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 50db59ef8c..7270c473fd 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1991,10 +1991,6 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); // Context around the data (neighbouring borders, the states around in one colour), which the // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). - // A name is left out only when every shown layer under it is context: the legend leaves layers - // out by name. - // Context around the data (neighbouring borders, the states around in one colour), which the - // 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. let context_at = |s: &Session, center: Coord, scale: f64| { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e4ee0b177e..a8d23fce20 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47328,7 +47328,9 @@ fn the_footer_lines_up_with_a_legend_at_the_right() { /// `layout.publication` itself lines the footer's right column up with a legend placed at the /// right (#1379): with `"arrangement": "legendRight"` and a legend wide enough to start between -/// 45 % and 70 % of the frame's width, the Reference Box starts where the Legend Box does. +/// 45 % and 70 % of the frame's width, the Reference Box starts where the Legend Box does. The +/// sample's lakes stay listed (`"contextInLegend": true`): the legend's widths these names give +/// are measured with them. #[test] fn a_publication_footer_lines_up_with_its_legend() { let piaui = json!([-46.8, -11.6, -38.5, -2.2]); @@ -47344,7 +47346,7 @@ fn a_publication_footer_lines_up_with_its_legend() { s.run("layer.rename", &json!({"layer": "Countries", "name": name})).unwrap(); s.run( "layout.publication", - &json!({"profile": "a4-portrait", "extent": piaui, "arrangement": "legendRight", "author": "", "sources": "Natural Earth"}), + &json!({"profile": "a4-portrait", "extent": piaui, "arrangement": "legendRight", "author": "", "sources": "Natural Earth", "contextInLegend": true}), ) .unwrap(); let l = s.project.layouts.last().unwrap(); From b8b12b3c5d6226d9986f8bbb0d06b366cc94e81d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 15 Nov 2026 04:11:05 -0300 Subject: [PATCH 4/6] fix(layout): a veiled group with neither locator nor arrow keeps no gap over its scale bar (#1379) With no north arrow (a continental extent) and no locator (a figure's default), veil_panel still reserved the gap over the scale bar, so a band just tall enough was refused and the bar sat 3 mm low. The gap is now taken only when something sits above the bar. Also rewords the comment on when the arrow's omission is said. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 10 ++++++---- crates/engine/src/tests.rs | 5 +++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 7270c473fd..d0e0f2cb2c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -712,7 +712,9 @@ 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)); - let group = (top.0.max(scale.0), top.1 + gap + scale.1); + // The gap over the scale bar only when something sits above it. + let lead = if top.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; if !beside && !over { @@ -729,7 +731,7 @@ pub(crate) fn veil_panel( (legend_at.0, legend_at.1, legend.0, legend.1), locator.map(|side| (group_at.0, group_at.1, side, side)), arrow.map(|(aw, ah)| (group_at.0 + group.0 - aw, group_at.1, aw, ah)), - (group_at.0, group_at.1 + top.1 + gap, scale.0, scale.1), + (group_at.0, group_at.1 + top.1 + lead, scale.0, scale.1), )) } @@ -2042,8 +2044,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { surrounds.push((Surround::Locator, side, side)); } // At a continental span the graticule's lines give north, and one arrow can't point north - // across the whole frame: none, unless "northArrow": "always" (#1379). Said, as any surround - // left out is. + // across the whole frame: none, unless "northArrow": "always" (#1379). Left out so, it is said; + // "northArrow": "none" asks for it, so isn't. let arrow = north_arrow.unwrap_or(extent_span_deg(&extent) < CONTINENTAL_DEG); if arrow { surrounds.push((Surround::Arrow, aw, ah)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a8d23fce20..4f3c32b3fc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -10449,6 +10449,11 @@ fn a_veil_panel_groups_the_surrounds_by_the_bands_shape() { let (_, locator, a, b) = veil_panel((0.0, 0.0, 160.0, 70.0), legend, Some(40.0), None, scale, 3.0).unwrap(); assert!(a.is_none(), "no place for an arrow there isn't: {a:?}"); assert_eq!(locator.unwrap().0, b.0, "the locator over the scale bar: {locator:?} {b:?}"); + // With neither, the scale bar heads its group, with no gap over it: a band just as tall as the + // legend and the bar one over the other takes them. + let (l, locator, a, b) = veil_panel((0.0, 0.0, 80.0, 63.0), legend, None, None, scale, 3.0).unwrap(); + assert!(locator.is_none() && a.is_none(), "{locator:?} {a:?}"); + assert_eq!((b.1, l.1), (0.0, 13.0), "the bar at the band's top, the legend under it: {b:?} {l:?}"); } /// With no room for any shape of the legend on either side of a centred map, the map moves towards From 482ed8bb4228e7807abfb1550a1977eda37b0449 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 15 Nov 2026 04:55:29 -0300 Subject: [PATCH 5/6] fix(layout): a moved frame drawn on its own gives the legend its own context (#1379) Where the projection stretches, a moved frame is drawn on its own and the placement judges what is context there; the legend kept the context judged on the centred frame, so a layer that is data in the moved frame could be left out of its legend. Each such candidate now keeps the legend's context and sizes measured there (measured again only when the context differs), and the winner's are the legend's, a move at the asked scale included. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 47 ++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index d0e0f2cb2c..fab7f65220 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2187,7 +2187,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let mut unknown_at: Option = None; // Moved frames drawn on their own (below), by scale and move: a pass with the veil // tries the same moves as the one before it. - let mut own_drawn: Vec<((f64, f64, f64), (u32, u32, Vec))> = Vec::new(); + // With the legend's context judged there, and its sizes with that context. + type Own = ((f64, f64, f64), (u32, u32, Vec), Vec, [(f64, f64); MAX_LEGEND_COLUMNS]); + let mut own_drawn: Vec = Vec::new(); // A figure keeps its scale: its size is fixed, and a smaller scale costs it the most. for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; @@ -2248,7 +2250,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { drawn = Some((tried, whole_frame, here, here_context)); } let Some((_, Some(whole_frame), Some(here), here_context)) = &drawn else { continue }; - let need = |room: (f64, f64)| here.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1); + let need = |sizes: &[(f64, f64); MAX_LEGEND_COLUMNS], room: (f64, f64)| { + sizes.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1) + }; let mut found: Option<(usize, f64)> = None; for (dx, dy) in [(0.0, 0.0), (to_right, 0.0), (-to_left, 0.0), (0.0, to_bottom), (0.0, -to_top)] { // Centred with no veil at the asked scale is what has no room; a shift of nothing @@ -2267,7 +2271,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // by `dx` and south by `dy` is the wide one's part that far west and north of // its middle while that scale moves a corner of it one cell of the coverage grid // at most, which the cut is exact to anyway; past that, it is drawn on its own - // (what is context then judged on itself), once. + // (what is context then judged on itself, for the legend too), once. let here_mm = mm * flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(asked.center()); let clip = ( fx + fw / 2.0 + (asked.min_x - cx) * here_mm, @@ -2283,14 +2287,29 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { continue; } let drift = (1.0 - flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(at)).abs() * fw.hypot(fh) / 2.0; - let mut moved = if drift <= fw.max(fh) / 384.0 { - crop_cells(whole_frame, wide, (slack_x - dx, slack_y - dy), (fw, fh)) - } else if let Some((_, own)) = own_drawn.iter().find(|(key, _)| *key == (tried, dx, dy)) { - own.clone() + let (mut moved, legend_sizes, legend_context) = if drift <= fw.max(fh) / 384.0 { + (crop_cells(whole_frame, wide, (slack_x - dx, slack_y - dy), (fw, fh)), *here, here_context.clone()) + } else if let Some((_, own, own_context, own_sizes)) = own_drawn.iter().find(|o| o.0 == (tried, dx, dy)) { + (own.clone(), *own_sizes, own_context.clone()) } else { let Some(own) = crate::render::layout::frame_coverage(s.map_mut(), there, tried, fw, fh, 384) else { continue }; - own_drawn.push(((tried, dx, dy), own.clone())); - own + let own_context = context_at(s, there, tried); + let own_sizes = if own_context == *here_context { + *here + } else { + let at_there = crate::render::layout::frame_render_scale(s.map(), there, tried); + let measured = crate::render::layout::legend_sizes_mm( + s.map_mut(), + at_there, + false, + false, + (&own_context, &Default::default()), + ); + let Some(measured) = measured else { continue }; + measured + }; + own_drawn.push(((tried, dx, dy), own.clone(), own_context.clone(), own_sizes)); + (own, own_sizes, own_context) }; if veil { let (gw, gh) = (moved.0 as usize, moved.1 as usize); @@ -2301,16 +2320,16 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } } let room = free_room(&moved); - let Some(n) = need(room) else { continue }; + let Some(n) = need(&legend_sizes, room) else { continue }; // Under a veil the whole group has to fit, not the legend alone, the scale bar's box // as drawn there. - let in_group = |s: &Session| grouped(clip, n, here, scale_box(ground_per_pt(s, there, tried), tried)); + let in_group = |s: &Session| grouped(clip, n, &legend_sizes, scale_box(ground_per_pt(s, there, tried), tried)); let Some(n) = (if veil { in_group(s).map(|(i, _)| i) } else { Some(n) }) else { continue }; if found.is_none_or(|(fewest, most)| n < fewest || (n == fewest && room.0 * room.1 > most)) { found = Some((n, room.0 * room.1)); (center, scale, coverage, map_shift) = (there, tried, Some(moved), (dx, dy)); veiled = veil.then_some(clip); - (chosen, chosen_context) = (*here, here_context.clone()); + (chosen, chosen_context) = (legend_sizes, legend_context); } } if found.is_some() { @@ -2335,6 +2354,10 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } if scale != asked_scale { warnings.push(format!("the map is drawn at 1:{scale:.0}, not 1:{asked_scale:.0}, to leave the legend room")); + } + // The legend as measured where the map settled: at another scale, or moved to where + // the context is judged apart. + if scale != asked_scale || chosen_context != context { (sizes, context) = (Some(chosen), chosen_context); (cw, ch) = chosen[0]; let (w, h) = whole(chosen[0]); From 57fa9848f7b67f1d2a5e61e911ecf3e23a8f2eca Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 15 Nov 2026 05:22:01 -0300 Subject: [PATCH 6/6] fix(layout): a moved frame whose legend can't be measured is said, not skipped silently (#1379) The moved-frame candidate drawn on its own, whose legend couldn't be measured with its own context, was dropped without setting unknown_at, so the "isn't moved or veiled" warning stayed silent. It now records the scale, as the scale-level path does. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 6d5e3694a4..8599de893a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2313,7 +2313,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { false, (&own_context, &Default::default()), ); - let Some(measured) = measured else { continue }; + // A legend that can't be measured there leaves that move untried, which is + // said, as at a scale. + let Some(measured) = measured else { + unknown_at.get_or_insert(tried); + continue; + }; measured }; own_drawn.push(((tried, dx, dy), own.clone(), own_context.clone(), own_sizes));