From bb1b4cd7143938981533750516540ab414bd4d1b Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 5 Nov 2026 23:25:30 -0300 Subject: [PATCH 1/6] feat(layout): a legend in up to three columns, and publication layouts use them for long legends (#1379) A legend's "columns" goes from 1 to 3, in layout.addElement, layout.update and the Format pane. layout.publication finds the largest rectangle the map leaves free and takes the fewest columns that fit it; when none fits, a long or cut legend is tried in more. Polygons with no fill and no labels don't count as what the map draws, unless nothing else is shown. Co-Authored-By: Claude Opus 5.5 --- crates/assistant/skills/print-layout/SKILL.md | 2 +- crates/engine/src/cmd/layout.rs | 196 +++++++-- crates/engine/src/tests.rs | 157 +++++++ crates/map/src/layout.rs | 15 + crates/render/src/layout.rs | 389 +++++++++++++++--- crates/render/src/stream_tests.rs | 2 +- crates/render/src/svg.rs | 4 +- crates/ui-egui/src/layoutview.rs | 16 +- docs/user-guide/layouts.md | 14 +- 9 files changed, 707 insertions(+), 88 deletions(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index ef59ef2696..858fb1857a 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -10,7 +10,7 @@ description: Make a printable page layout — map frame, title, legend, north ar (`"a4"`, `"a3"` or `"a2"` for a sheet turned to the area's shape, or `"a4-portrait"`, `"a3-landscape"`, … to choose; `"figure-1col"`, `"thesis-full"`, … for a figure), the `"extent"` to fit, and the texts: `"title"`, `"subtitle"`, `"sources"`, `"note"`, a `"locator"` (`"globe"`: the visible polygon layers held in the project, not streamed ones, over the basemap; `"inset"` or `"none"`; when omitted, `"globe"` on a sheet and `"none"` on a figure), and `"decimal": ","` for a map in a language with a decimal comma. A sheet's `"style"` arranges it: `"classic"` (the default), `"banner"`, `"panel"`, `"editorial"`, `"modular"` or `"poster"` (for a poster-like sheet), with an `"accent"` colour as `"#RRGGBB"`. Its surrounds (locator, north arrow, legend, scale bar) start from an `"arrangement"` (`"classic"`, `"mirrored"`, `"legendRight"`, `"legendTop"`, or a corner for each; `"best"`, the default, tries the user's favourite, set with `layout.arrangement`, and the others), and one over the data moves to the freest place in the frame, the largest first (the legend, as a rule); read its `"arrangement"`, `"moved"` and `"warnings"`. It places the frame at a round scale, the - graticule, legend, scale bar and north arrow, and wraps the footer. Its result lists every element's id and name + graticule, legend (a long one in up to three columns), scale bar and north arrow, and wraps the footer. Its result lists every element's id and name (`"elements"`), so skip to step 5 to adjust them. Otherwise, `layout.new` `{"name": N, "page": "letter"|"a4"|…, "orientation": "landscape"|"portrait"}` creates the layout and opens it. diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index ab8a50c24a..3e8cbe37de 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -7,8 +7,8 @@ use rustgis_geom::{Coord, Extent}; use rustgis_map::Rgba; use rustgis_map::layout::{ Arrange, ArrowStyle, CoordFormat, ElementKind, FontFamily, FrameShape, Grid, GridEdges, GridKind, GridStyle, Guides, Layout, LineDir, - LineHead, MAX_COLORBAR_TICKS, MAX_GRID_WIDTH, MAX_GUIDES, MAX_SCALE_DIVISIONS, MAX_TICK_MM, MIN_ELEMENT_MM, MapSeries, Orientation, - PAGES, ScaleBarStyle, ScaleUnits, TextAlign, TickSide, fit_scale, line_angle, line_at_angle, line_length, + LineHead, MAX_COLORBAR_TICKS, MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, MAX_SCALE_DIVISIONS, MAX_TICK_MM, MIN_ELEMENT_MM, + MapSeries, Orientation, PAGES, ScaleBarStyle, ScaleUnits, TextAlign, TickSide, fit_scale, line_angle, line_at_angle, line_length, }; use serde_json::{Value, json}; @@ -88,10 +88,10 @@ pub fn commands() -> Vec { r#"{"layout"?, "shape"?: "rectangle"|"circle"|"ellipse"|"polygon"|"lasso", "points"?: [[u, v], …] (polygon/lasso, 0..1 across the frame), "map"?: name, "x"?, "y"?, "w"?, "h"?: mm}"#, ), C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).params( - r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA", "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "orientation"?: "horizontal"|"vertical" (colorbar), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible one), "field"?, "label"?, "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system, as ArcGIS Pro's measured grid), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "labels"?: bool, "style"?: "lines"|"ticks"|"linesAndTicks" (grid) or "classic"|"compass"|"triangle"|"star" (northArrow) or "alternating"|"stepped"|"line" (scaleBar), "tickLength"?: mm, "format"?: "decimal"|"dms", "hemisphere"?: bool (N/S/E/W rather than a sign), "edges"?: ["top","bottom","left","right"] (labelled edges), "labelOrientation"?: "horizontal"|"vertical", "off"?: bool (grid; options not given keep the grid's), "outline"?: "#RRGGBB" (northArrow), "units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "divisions"?: 1..10 (scaleBar, whose "color" is its lines, dark divisions and labels, default #222222), "x"?, "y"?, "w"?, "h"?: mm}"##, + r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA", "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "columns"?: 1..3 (legend: the columns its rows are laid in; default 1), "orientation"?: "horizontal"|"vertical" (colorbar), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible one), "field"?, "label"?, "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system, as ArcGIS Pro's measured grid), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "labels"?: bool, "style"?: "lines"|"ticks"|"linesAndTicks" (grid) or "classic"|"compass"|"triangle"|"star" (northArrow) or "alternating"|"stepped"|"line" (scaleBar), "tickLength"?: mm, "format"?: "decimal"|"dms", "hemisphere"?: bool (N/S/E/W rather than a sign), "edges"?: ["top","bottom","left","right"] (labelled edges), "labelOrientation"?: "horizontal"|"vertical", "off"?: bool (grid; options not given keep the grid's), "outline"?: "#RRGGBB" (northArrow), "units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "divisions"?: 1..10 (scaleBar, whose "color" is its lines, dark divisions and labels, default #222222), "x"?, "y"?, "w"?, "h"?: mm}"##, ), C::new("layout.update", "Element Properties", "Publish › Element", update).params( - r##"{"layout"?, "element": id, "x"?, "y"?, "w"?, "h"?: mm, "name"?, "visible"?, "locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "text"?, "size"?, "color"? (text, line; scaleBar: its lines, dark divisions and labels), "bold"?, "italic"?, "align"?, "letterSpacing"?, "font"?: "sans"|"serif"|an installed font family's name, "fallback"?: "sans"|"serif" (text, as in layout.addElement; refused for other elements), "title"?, "allClasses"?: bool (legend), "hideOther"?: bool (legend), "exclude"?: [layer names] (legend; [] lists every layer again), "orientation"?, "ticks"?, "tickSide"?, "reverse"?: (colorbar), "style"?: (northArrow, scaleBar), "fill"?, "outline"? (northArrow, rectangle, ellipse; for a rectangle or ellipse, color sets it when outline is not given; a scaleBar's fill is the alternating bar's light divisions), "radius"?: mm (rectangle: rounded corners), "width"?: points (rectangle, ellipse, line), "dir"?, "head"?, "angle"?, "length"? (line: turned or sized about its centre, then moved by any x or y; dir does not come with angle or length), "units"?, "divisions"? (scaleBar), "map"?, "scale"?, "center"?: [lon, lat], "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85), "grid"?: {grid options as in layout.addElement} | false (map frame), "extentIndicator"?: {"color"?, "width"?: points} | false (map frame: its extent indicator's style, or removes it), "layer"?: (colorbar: "" for the top visible raster), "field"?, "rows"?}"##, + r##"{"layout"?, "element": id, "x"?, "y"?, "w"?, "h"?: mm, "name"?, "visible"?, "locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "text"?, "size"?, "color"? (text, line; scaleBar: its lines, dark divisions and labels), "bold"?, "italic"?, "align"?, "letterSpacing"?, "font"?: "sans"|"serif"|an installed font family's name, "fallback"?: "sans"|"serif" (text, as in layout.addElement; refused for other elements), "title"?, "allClasses"?: bool (legend), "hideOther"?: bool (legend), "exclude"?: [layer names] (legend; [] lists every layer again), "columns"?: 1..3 (legend), "orientation"?, "ticks"?, "tickSide"?, "reverse"?: (colorbar), "style"?: (northArrow, scaleBar), "fill"?, "outline"? (northArrow, rectangle, ellipse; for a rectangle or ellipse, color sets it when outline is not given; a scaleBar's fill is the alternating bar's light divisions), "radius"?: mm (rectangle: rounded corners), "width"?: points (rectangle, ellipse, line), "dir"?, "head"?, "angle"?, "length"? (line: turned or sized about its centre, then moved by any x or y; dir does not come with angle or length), "units"?, "divisions"? (scaleBar), "map"?, "scale"?, "center"?: [lon, lat], "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85), "grid"?: {grid options as in layout.addElement} | false (map frame), "extentIndicator"?: {"color"?, "width"?: points} | false (map frame: its extent indicator's style, or removes it), "layer"?: (colorbar: "" for the top visible raster), "field"?, "rows"?}"##, ), C::new("layout.guides", "Guides", "Publish › Page Setup", guides).params( r#"{"layout"?, "x"?: [mm] (vertical guides, from the page's left edge), "y"?: [mm] (horizontal guides, from its top edge), "clear"?: bool (remove every guide first)}"#, @@ -298,7 +298,14 @@ pub(crate) fn new_layout(s: &mut Session, p: &Value) -> CmdResult { l.add( "Legend", (side, m + 16.0, sw, fh * 0.6), - ElementKind::Legend { frame, title: "Legend".into(), all_classes: false, hide_other: false, exclude: Vec::new() }, + ElementKind::Legend { + frame, + title: "Legend".into(), + all_classes: false, + hide_other: false, + exclude: Vec::new(), + columns: 1, + }, ); l.add("North Arrow", (side + sw / 2.0 - 8.0, m + 16.0 + fh * 0.62, 16.0, 24.0), ElementKind::north_arrow(frame)); l.add("Scale Bar", (side, m + 16.0 + fh * 0.62 + 28.0, sw, 12.0), ElementKind::scale_bar(frame)); @@ -618,6 +625,41 @@ pub(crate) fn legend_room( Some((w.min(room_w.max(MIN_LEGEND_MM)), h.min(room_h.max(MIN_LEGEND_MM)))) } +/// Whether a publication legend laid out in more columns beats it in fewer, each as the share of it +/// shown and the area (mm²) the surrounds leave over the drawing: it shows more of itself, or as +/// much and covers at least a quarter less, as a low wide box does above a map's data (#1379). +pub(crate) fn more_columns_win((shown, over): (f64, f64), (best_shown, best_over): (f64, f64)) -> bool { + shown > best_shown + 1e-6 || (shown > best_shown - 1e-6 && over < 0.75 * best_over) +} + +/// The width and height, in cells, of the largest rectangle with no drawn cell in +/// `(c0, r0, c1, r1)` of a grid `gw` cells wide, its cells row by row: where a legend's shape can +/// go (#1379). +pub(crate) fn largest_free_cells(gw: usize, cells: &[bool], (c0, r0, c1, r1): (usize, usize, usize, usize)) -> (usize, usize) { + let mut heights = vec![0usize; c1.saturating_sub(c0) + 1]; + let (mut best, mut stack) = ((0, 0), Vec::::new()); + for r in r0..r1 { + for c in c0..c1 { + let free = !cells.get(r * gw + c).copied().unwrap_or(true); + heights[c - c0] = if free { heights[c - c0] + 1 } else { 0 }; + } + // Each column's height from this row up: the widest run at least that high, by a stack of + // rising heights. The last entry stays 0, so every run ends. + stack.clear(); + for i in 0..heights.len() { + while let Some(&top) = stack.last().filter(|&&top| heights[top] >= heights[i]) { + stack.pop(); + let wide = stack.last().map_or(i, |&left| i - left - 1); + if wide * heights[top] > best.0 * best.1 { + best = (wide, heights[top]); + } + } + stack.push(i); + } + } + best +} + /// A publication layout's colorbar's height, in mm: its title, the bar and its labels. const COLORBAR_MM: f64 = 15.0; @@ -1726,8 +1768,9 @@ 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 cw, mut ch) = match crate::render::layout::legend_size_mm(s.map_mut(), render_scale, false, false, &[]) { - Some(size) => size, + let mut sizes = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]); + let (mut cw, mut ch) = match sizes { + Some(sizes) => sizes[0], None => { // A complete source that can't be read: the export says why; the legend is sized by hand. warnings.push("a layer's source couldn't be read through, so the legend has a fixed size; exporting says why".into()); @@ -1737,10 +1780,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let listed = s.map().layers.iter().any(|l| s.map().shows(l) && !l.graphics && !l.is_raster()); 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, &[]) { // 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; warnings.push("a WMS or WMTS layer's legend picture is still loading: the legend has a fixed size to fit by hand".into()); } let (sw, sh, nh) = ((fw * 0.3).max(25.0), if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); @@ -1809,18 +1854,22 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { Surround::Scale => "scale bar", }; let area = (fx + left, fy + top, fx + fw - right, fy + fh - bottom); - // An arrangement laid out (#1379): each surround over the map in its own corner, the legend - // short of the surrounds beside and above or below it (`None` when the locator leaves it too - // small, so it is left out); then, the largest first, each one covering what the map draws there - // leaves it for the freest place in the frame, clear of those placed before it ([`free_spot`]), - // when that covers less, and one whose corner a larger one took leaves it in any case. Data - // everywhere alike leaves nowhere better: it stays. Gives the legend's corner and size, each - // surround's place, the ones moved, and the area (mm²) of those moved and of what still covers - // the drawing. + // An arrangement laid out (#1379), the legend's box `legend` at most: each surround over the map + // in its own corner, the legend short of the surrounds beside and above or below it (`None` when + // the locator leaves it too small, so it is left out); then, the largest first, each one covering + // what the map draws there leaves it for the freest place in the frame, clear of those placed + // before it ([`free_spot`]), when that covers less, and one whose corner a larger one took leaves + // it in any case. Data everywhere alike leaves nowhere better: it stays. Gives the legend's corner + // and size, each surround's place, the ones moved, and the area (mm²) of those moved and of what + // still covers the drawing. type Laid = (Option<(usize, f64, f64)>, Vec<(Surround, Rect)>, Vec<&'static str>, (f64, f64)); - let lay_out = |homes: Homes| -> Laid { - let corner_of = - |what: Surround| surrounds.iter().find(|(kind, ..)| *kind == what).map(|&(kind, w, h)| (homes[home_slot(kind)], w, h)); + let lay_out = |homes: Homes, legend: (f64, f64)| -> Laid { + let corner_of = |what: Surround| { + surrounds.iter().find(|(kind, ..)| *kind == what).map(|&(kind, w, h)| { + let (w, h) = if kind == Surround::Legend { legend } else { (w, h) }; + (homes[home_slot(kind)], w, h) + }) + }; let legend_at = corner_of(Surround::Legend).and_then(|(corner, w, h)| { let other = |c: usize| surrounds.iter().find(|&&(kind, ..)| homes[home_slot(kind)] == c).copied(); let beside = other(corner ^ 1).map(|(kind, ow, _)| (kind, ow)); @@ -1862,19 +1911,67 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // A legend left out costs the whole frame, more than any move, so an arrangement that keeps // it always wins over one that drops it. let dropped = if surrounds.iter().any(|x| x.0 == Surround::Legend) && legend_at.is_none() { fw * fh } else { 0.0 }; + // A legend cut short of its neighbours costs ten times what it loses, so one that keeps its + // rows beats moving another surround. + let cut = legend_at.map_or(0.0, |(_, lw, lh)| 10.0 * (legend.0 * legend.1 - lw * lh).max(0.0)); // Surrounds left over each other (nowhere clear for one a larger one's corner took) cost ten // times their overlap, so an arrangement that keeps them apart wins. let clash = 10.0 * overlap_area(&spots.iter().map(|(_, r)| *r).collect::>()); - (legend_at, spots, moved, (shifted + dropped + clash, over)) + (legend_at, spots, moved, (shifted + dropped + cut + clash, over)) }; // Each arrangement tried laid out, and one picked ([`pick_arrangement`]): the least area moved // off its corners (so a north arrow moved costs less than a legend), then the least left over // the drawing, the first tried (the favourite) on a tie. Every arrangement fills the same four // corners, so it is what goes where that differs. A single arrangement asked for is the one // laid out. - let mut laid: Vec<(Homes, Laid)> = tries.iter().map(|h| (*h, lay_out(*h))).collect(); - let chosen = pick_arrangement(&laid.iter().map(|(_, l)| l.3).collect::>()).map(|i| laid.swap_remove(i)); - let (homes, (legend_at, spots, moved, _)) = chosen.unwrap_or_else(|| (ARRANGEMENTS[0].1, lay_out(ARRANGEMENTS[0].1))); + let arranged = |legend: (f64, f64)| -> (Homes, Laid) { + let mut laid: Vec<(Homes, Laid)> = tries.iter().map(|h| (*h, lay_out(*h, legend))).collect(); + let chosen = pick_arrangement(&laid.iter().map(|(_, l)| l.3).collect::>()).map(|i| laid.swap_remove(i)); + chosen.unwrap_or_else(|| (ARRANGEMENTS[0].1, lay_out(ARRANGEMENTS[0].1, legend))) + }; + let at_most_one = surrounds.iter().find(|x| x.0 == Surround::Legend).map_or((0.0, 0.0), |x| (x.1, x.2)); + let mut legend_cols = 1; + let mut best = arranged(at_most_one); + // The legend takes the fewest columns that fit the largest rectangle the map leaves free + // (#1379). Past those, or when none fits, a long one is tried in more, up to the width beside + // the north arrow, when in fewer it is cut or over what the map draws. One in a side column + // stays in one: that column is about as wide as its rows. + if let Some(sizes) = sizes.filter(|_| column.is_none() && content_h > 0.0) { + let whole = |(w, h): (f64, f64)| ((if bar.is_some() { w.max(bar_w) } else { w }) + 2.0 * pad, h + bar_part + 2.0 * pad); + 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 free = coverage.as_ref().map(|(gw, gh, cells)| { + let (gw, gh) = (*gw as usize, *gh as usize); + let col = |v: f64| ((v - fx) / fw * gw as f64).clamp(0.0, gw as f64) as usize; + let row = |v: f64| ((v - fy) / fh * gh as f64).clamp(0.0, gh as f64) as usize; + let (cw, ch) = largest_free_cells(gw, cells, (col(area.0), row(area.1), col(area.2), row(area.3))); + (cw as f64 * fw / gw as f64, ch as f64 * fh / gh as f64) + }); + let fits = free.and_then(|(rw, rh)| sizes.iter().position(|size| whole(*size).0 <= rw && whole(*size).1 <= rh)); + if let Some(i) = fits.filter(|i| *i > 0) { + let (w, h) = whole(sizes[i]); + let more = arranged((w.min(wide), h.min(fh * 0.6))); + let new = (shown(&more.1, (w, h)), more.1.3.1); + if new.0 >= score.0 - 1e-6 { + (legend_cols, best, score) = (i + 1, more, new); + } + } + for (i, size) in sizes.iter().enumerate().skip(legend_cols) { + if score.0 > 1.0 - 1e-6 && (!long || score.1 <= LEAK * fw * fh) { + break; + } + let (w, h) = whole(*size); + let more = arranged((w.min(wide), h.min(fh * 0.6))); + let new = (shown(&more.1, (w, h)), more.1.3.1); + if more_columns_win(new, score) { + (legend_cols, best, score) = (i + 1, more, new); + } + } + (cw, ch) = sizes[legend_cols - 1]; + } + let (homes, (legend_at, spots, moved, _)) = best; if surrounds.iter().any(|x| x.0 == Surround::Legend) && legend_at.is_none() { warnings.push( "the frame leaves the legend no room beside the locator, so it is left out: give the map more room, or set \"locator\": \"none\"" @@ -1953,7 +2050,16 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // A box sized to its content, less the padding again, can come out a rounding error // short of it: that still fits. const FIT_MM: f64 = 1e-6; - if ch > 0.0 && (cw > iw + FIT_MM || ch > rows_h + FIT_MM) { + let (too_wide, too_tall) = (ch > 0.0 && cw > iw + FIT_MM, ch > rows_h + FIT_MM); + if legend_cols > 1 { + // Its columns close up rather than leave one out. + if too_wide { + warnings.push("the legend's columns are wider than its box: they close up, long labels run into the next, and the last column's past the box".into()); + } + if too_tall { + warnings.push("the legend lists more than fits its corner: its last rows are left out".into()); + } + } else if ch > 0.0 && (too_wide || too_tall) { warnings.push("the legend lists more than fits its corner: its last rows or the ends of long labels are left out".into()); } // In a column the colorbar takes the column's width, as its rows do. @@ -1964,7 +2070,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { l.add( "Legend", (ix, iy, iw, rows_h), - ElementKind::Legend { frame, title: String::new(), all_classes: false, hide_other: false, exclude: Vec::new() }, + ElementKind::Legend { + frame, + title: String::new(), + all_classes: false, + hide_other: false, + exclude: Vec::new(), + columns: legend_cols, + }, ); } if let Some(layer) = &bar { @@ -2030,7 +2143,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { s.active_layout = Some(i); 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_name(homes), "elements": elements, "moved": moved, "warnings": warnings}), + json!({"layout": i, "name": name, "profile": profile.id, "page": [w, h], "scale": scale, "grid": step, "locator": locator, "style": style.code(), "arrangement": arrangement_name(homes), "legendColumns": legend_cols, "elements": elements, "moved": moved, "warnings": warnings}), ) } @@ -2217,11 +2330,26 @@ pub(crate) fn color(p: &Value, k: &str, d: Rgba) -> Result { } } +const ONLY_LEGEND_COLUMNS: &str = "only legends have columns"; + +/// The `"columns"` a legend is given, refused outside 1 to [`MAX_LEGEND_COLUMNS`]. +fn legend_columns_param(p: &Value) -> Result, String> { + let Some(v) = p.get("columns").filter(|v| !v.is_null()) else { return Ok(None) }; + v.as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=MAX_LEGEND_COLUMNS).contains(n)) + .map(Some) + .ok_or_else(|| format!("columns is a whole number from 1 to {MAX_LEGEND_COLUMNS}")) +} + fn add_element(s: &mut Session, p: &Value) -> CmdResult { let kind = ps(p, "kind").ok_or("kind is required")?; if kind != "legend" && p.get("exclude").is_some_and(|v| !v.is_null()) { return Err("only legends leave layers out".into()); } + if kind != "legend" && p.get("columns").is_some_and(|v| !v.is_null()) { + return Err(ONLY_LEGEND_COLUMNS.into()); + } // A family is a text's: refused elsewhere, as a legend's left-out layers are, so a script // doesn't take it as applied. if !matches!(kind, "text" | "dynamicText") && gives_font(p) { @@ -2263,7 +2391,12 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { let all_classes = b(p, "allClasses").unwrap_or(false); let hide_other = b(p, "hideOther").unwrap_or(false); let exclude = legend_exclude(s, l, frame, p)?.unwrap_or_default(); - ("Legend", place(p, l, (pw - 70.0, 45.0, 60.0, 80.0))?, ElementKind::Legend { frame, title, all_classes, hide_other, exclude }) + let columns = legend_columns_param(p)?.unwrap_or(1); + ( + "Legend", + place(p, l, (pw - 70.0, 45.0, 60.0, 80.0))?, + ElementKind::Legend { frame, title, all_classes, hide_other, exclude, columns }, + ) } "colorbar" => { let frame = frame_of(l, p)?; @@ -3025,6 +3158,12 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { _ => None, } }; + let new_columns = legend_columns_param(p)?; + if new_columns.is_some() + && !matches!(s.project.layouts.get(li).and_then(|l| l.element(id)).map(|e| &e.kind), Some(ElementKind::Legend { .. })) + { + return Err(ONLY_LEGEND_COLUMNS.into()); + } let l = active(s, p)?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; let num = |k: &str, lo: f64, hi: f64| f(p, k).map(|v| v.clamp(lo, hi)); @@ -3085,10 +3224,13 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { *bold = v; } } - ElementKind::Legend { title, all_classes, hide_other, exclude, .. } => { + ElementKind::Legend { title, all_classes, hide_other, exclude, columns, .. } => { if let Some(names) = new_exclude { *exclude = names; } + if let Some(n) = new_columns { + *columns = n; + } if let Some(t) = ps(p, "title") { *title = t.chars().take(200).collect(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 73ea97f26e..8cfd5b29c7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6853,6 +6853,163 @@ fn a_publication_legend_sized_to_its_rows_fits_them() { let _ = std::fs::remove_dir_all(&dir); } +/// A publication legend too long for its corner goes into columns, the fewest that hold it (#1379), +/// and past three says what it leaves out; a short one stays in one, saved as it always was. +/// The largest rectangle with nothing drawn, inside the part of the grid asked for. +#[test] +fn the_largest_free_rectangle_of_a_grid() { + use crate::cmd::layout::largest_free_cells; + let grid = |rows: &[&str]| -> Vec { rows.iter().flat_map(|r| r.chars().map(|c| c == '#')).collect() }; + let cells = grid(&["....#.", "....#.", "##..#.", "##...."]); + assert_eq!(largest_free_cells(6, &cells, (0, 0, 6, 4)), (4, 2)); + // Inside a part of it: the columns and rows outside don't count. + assert_eq!(largest_free_cells(6, &cells, (2, 2, 6, 4)), (2, 2)); + // A wide run under a taller narrow one, and the other way round. + assert_eq!(largest_free_cells(3, &grid(&["#.#", "#.#", "..."]), (0, 0, 3, 3)), (1, 3)); + assert_eq!(largest_free_cells(4, &grid(&["#..#", "....", "...."]), (0, 0, 4, 3)), (4, 2)); + // All drawn, all free, nothing asked for. + assert_eq!(largest_free_cells(2, &grid(&["##", "##"]), (0, 0, 2, 2)), (0, 0)); + assert_eq!(largest_free_cells(2, &grid(&["..", ".."]), (0, 0, 2, 2)), (2, 2)); + assert_eq!(largest_free_cells(2, &grid(&["..", ".."]), (1, 1, 1, 1)), (0, 0)); +} + +/// A long legend takes the fewest columns that fit the largest rectangle the map leaves free: data +/// along the bottom of the frame leaves a wide band above it, too low for one column. Layers that +/// only outline their polygons don't take that room. +#[test] +fn a_publication_legend_takes_the_columns_that_fit_the_free_rectangle() { + let dir = std::env::temp_dir().join(format!("rustgis-legend-free-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let polygon = |name: &str, [w, s, e, n]: [f64; 4]| { + let path = dir.join(name); + let json = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": + {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n], [w, n], [w, s]]]}}]}); + std::fs::write(&path, json.to_string()).unwrap(); + path.display().to_string() + }; + let low = polygon("low.geojson", [0.0, 0.0, 10.0, 6.5]); + let border = polygon("border.geojson", [1.0, 7.0, 9.0, 9.0]); + let columns = |outline: bool| { + let mut s = Session::new(Project::default()); + for _ in 0..24 { + s.run("layer.addData", &json!({"path": low})).unwrap(); + } + if outline { + s.run("layer.addData", &json!({"path": border})).unwrap(); + s.run("layer.color", &json!({"layer": "border", "color": "#00000000"})).unwrap(); + } + let r = s + .run("layout.publication", &json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "author": "", "locator": "none"})) + .unwrap(); + (r["legendColumns"].as_u64().unwrap(), s.map().layers.iter().all(|l| l.visible)) + }; + assert_eq!(columns(false), (2, true)); + assert_eq!(columns(true), (2, true), "the border doesn't count, and is shown again"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_publication_legend_too_long_goes_into_columns() { + use rustgis_map::layout::ElementKind; + let dir = std::env::temp_dir().join(format!("rustgis-legend-columns-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.geojson"); + std::fs::write( + &path, + r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[4,4],[6,4],[6,6],[4,6],[4,4]]]}}]}"#, + ) + .unwrap(); + // Filling the frame below 60% of its height: a long legend in one column would cover it, and two + // sit above it. A short one stays in one, whatever it covers. + let low = dir.join("low.geojson"); + std::fs::write( + &low, + r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[0,0],[10,0],[10,6],[0,6],[0,0]]]}}]}"#, + ) + .unwrap(); + // Labels too long for two columns side by side: they close up, and it says so. + let mut s = Session::new(Project::default()); + for i in 0..60 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + s.run( + "layer.rename", + &json!({"layer": "a", "name": format!("{i} a layer's name long enough to take more than half of the frame's width")}), + ) + .unwrap(); + } + let r = s.run("layout.publication", &json!({"extent": [0, 0, 10, 10], "author": "", "locator": "none"})).unwrap(); + assert!(r["legendColumns"].as_u64().unwrap() > 1, "{r}"); + assert!(r["warnings"].to_string().contains("run into the next"), "{r}"); + for (layers, columns) in [(3, 1), (30, 2)] { + let mut s = Session::new(Project::default()); + for _ in 0..layers { + s.run("layer.addData", &json!({"path": low.display().to_string()})).unwrap(); + } + let r = s.run("layout.publication", &json!({"extent": [0, 0, 10, 10], "author": "", "locator": "none"})).unwrap(); + assert_eq!(r["legendColumns"], columns, "{layers} layers: {r}"); + } + for (layers, columns, cut) in [(3, 1, false), (60, 3, false), (100, 3, false), (200, 3, true)] { + let mut s = Session::new(Project::default()); + for _ in 0..layers { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let r = s.run("layout.publication", &json!({"extent": [0, 0, 10, 10], "author": "", "locator": "none"})).unwrap(); + assert_eq!(r["legendColumns"], columns, "{layers} layers: {r}"); + assert_eq!(r["warnings"].to_string().contains("more than fits"), cut, "{layers} layers: {r}"); + let l = s.project.layouts.last().unwrap(); + let legend = l.elements.iter().find(|e| matches!(e.kind, ElementKind::Legend { .. })).unwrap(); + assert!(matches!(legend.kind, ElementKind::Legend { columns: c, .. } if c == columns), "{:?}", legend.kind); + assert_eq!(serde_json::to_string(&legend.kind).unwrap().contains("columns"), columns > 1); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// A publication legend takes another column to show more of itself, or as much and cover at least +/// a quarter less of what the map draws. +#[test] +fn more_columns_win_by_showing_more_or_covering_less() { + use crate::cmd::layout::more_columns_win; + assert!(more_columns_win((1.0, 500.0), (0.6, 0.0)), "more shown, whatever it covers"); + assert!(!more_columns_win((0.6, 0.0), (1.0, 500.0)), "less shown, whatever it covers"); + assert!(more_columns_win((1.0, 300.0), (1.0, 500.0)), "as much shown, covering 40% less"); + assert!(!more_columns_win((1.0, 400.0), (1.0, 500.0)), "only 20% less"); + assert!(!more_columns_win((1.0, 0.0), (1.0, 0.0)), "nothing to gain"); +} + +/// `"columns"` on a legend: given and changed, refused outside 1 to 3 and on anything else. +#[test] +fn a_legend_takes_columns_from_one_to_three() { + use rustgis_map::layout::ElementKind; + let mut s = Session::new(Project::default()); + s.run("layout.new", &json!({"template": "map"})).unwrap(); + let columns = |s: &Session, id: u64| match s.project.layouts[0].element(id as u32).map(|e| &e.kind) { + Some(ElementKind::Legend { columns, .. }) => *columns, + other => panic!("{other:?}"), + }; + let added = s.run("layout.addElement", &json!({"kind": "legend"})).unwrap(); + let id = added["element"].as_u64().unwrap(); + assert_eq!(columns(&s, id), 1); + let two = s.run("layout.addElement", &json!({"kind": "legend", "columns": 2})).unwrap(); + assert_eq!(columns(&s, two["element"].as_u64().unwrap()), 2); + s.run("layout.update", &json!({"element": id, "columns": 3})).unwrap(); + assert_eq!(columns(&s, id), 3); + s.run("layout.update", &json!({"element": id, "title": "Key"})).unwrap(); + assert_eq!(columns(&s, id), 3, "another change leaves them"); + for bad in [json!(0), json!(4), json!(1.5), json!("2"), json!(-1)] { + assert!(s.run("layout.update", &json!({"element": id, "columns": bad})).unwrap_err().contains("1 to 3"), "{bad}"); + assert!(s.run("layout.addElement", &json!({"kind": "legend", "columns": bad})).unwrap_err().contains("1 to 3"), "{bad}"); + } + assert_eq!(columns(&s, id), 3); + let err = s.run("layout.addElement", &json!({"kind": "northArrow", "columns": 2})).unwrap_err(); + assert!(err.contains("only legends"), "{err}"); + let arrow = s.run("layout.addElement", &json!({"kind": "northArrow"})).unwrap(); + let err = s.run("layout.update", &json!({"element": arrow["element"], "columns": 2})).unwrap_err(); + assert!(err.contains("only legends"), "{err}"); + // A layout saved before them has one. + let old: ElementKind = serde_json::from_str(r#"{"Legend":{"frame":1,"title":"L"}}"#).unwrap(); + assert!(matches!(old, ElementKind::Legend { columns: 1, .. }), "{old:?}"); +} + /// A publication layout keys a raster theme with a colorbar: the topmost visible raster drawn on a /// ramp gets one at the bottom of the legend's box; a map of vectors only gets none. #[test] diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index cf2add9906..f2c98b891b 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -793,6 +793,17 @@ fn divisions() -> usize { 4 } +/// The most columns a legend lays its rows in. +pub const MAX_LEGEND_COLUMNS: usize = 3; + +fn one_column() -> usize { + 1 +} + +fn is_one_column(columns: &usize) -> bool { + *columns == 1 +} + fn ink() -> Rgba { Rgba::rgb(0x22, 0x22, 0x22) } @@ -912,6 +923,10 @@ pub enum ElementKind { /// highlight, a basemap-like layer. Empty, it lists every layer it would otherwise. #[serde(default, skip_serializing_if = "Vec::is_empty")] exclude: Vec, + /// The columns its rows are laid in, 1 to [`MAX_LEGEND_COLUMNS`], under its title: as even + /// as they can be, a layer's name staying with the row under it. + #[serde(default = "one_column", skip_serializing_if = "is_one_column")] + columns: usize, }, /// The colour scale of a raster layer in a frame's map: a gradient bar for a stretch, steps /// for classes, a block per value for unique values and colour tables (#326). diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 8d973c6f05..9cef7c0351 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -5,8 +5,8 @@ use crate::Canvas; use rustgis_data::GeometryType; use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ - ArrowStyle, ColorScale, ElementKind, FrameShape, Grid, GridKind, Layout, LineHead, Orientation, PT_PER_MM, ScaleBarStyle, ScaleUnits, - TextAlign, TickSide, frame_camera, + ArrowStyle, ColorScale, ElementKind, FrameShape, Grid, GridKind, Layout, LineHead, MAX_LEGEND_COLUMNS, Orientation, PT_PER_MM, + ScaleBarStyle, ScaleUnits, TextAlign, TickSide, frame_camera, }; use rustgis_map::symbology::LegendEntry; use rustgis_map::{Map, Rgba}; @@ -272,14 +272,14 @@ fn draw_page( scale_bar(&mut pm, r, map.ground_res_at(&cam), bar, (*color, *fill), ppp, layout.decimal_comma); } } - ElementKind::Legend { frame: f, title, all_classes, hide_other, exclude } => { + ElementKind::Legend { frame: f, title, all_classes, hide_other, exclude, columns } => { if let Some(&(_, mi, cam, ..)) = frame(*f) && let Some(map) = maps.get(mi) { let drawn = (!*all_classes).then(|| shown.iter().find(|(id, _)| id == f).map(|(_, v)| v.as_slice()).unwrap_or(&[])); let scale = map.ground_res_at(&cam) / rustgis_geom::PIXEL_M; wait_for_tile_legends(map, scale, exclude); - legend(&mut pm, r, map, title, drawn, LegendOptions { hide_other: *hide_other, exclude, scale }, ppp); + legend(&mut pm, r, map, (title, *columns), drawn, LegendOptions { hide_other: *hide_other, exclude, scale }, ppp); } } ElementKind::Colorbar { frame: f, layer, title, orientation, ticks, tick_side, reverse } => { @@ -1280,6 +1280,66 @@ impl LegendRow<'_> { _ => LEGEND_ROW.max(self.symbol_side(scale)), } } + + /// Its width beside a column of swatches `column` points wide ([`swatch_column`]), in points. + fn width(&self, column: f32) -> f32 { + match self { + LegendRow::Plain(l) => column + 6.0 + text::measure(&l.name, 9.0, false), + LegendRow::Head(name) => text::measure(name, 9.0, true), + LegendRow::Class(_, en) => column + 12.0 + text::measure(&en.label, 8.5, false), + LegendRow::Picture(p) => 6.0 + picture_size(p).0, + } + } +} + +/// Rows at 1:`scale` laid into at most `columns` columns `limit` points high: the row each column +/// starts at, and whether they all fit. A layer's name stays with the row under it; a row taller +/// than `limit` has a column to itself, and the last column takes what is left. +fn flow(rows: &[LegendRow], columns: usize, limit: f32, scale: f64) -> (Vec, bool) { + // A thousandth of a row's slack, as the rows have when drawn. + let limit = limit + LEGEND_ROW * 1e-3; + let (mut starts, mut used, mut fits, mut i) = (vec![0], 0.0f32, true, 0); + while i < rows.len() { + let end = if matches!(rows[i], LegendRow::Head(_)) { (i + 2).min(rows.len()) } else { i + 1 }; + let part: f32 = rows[i..end].iter().map(|row| row.height(scale)).sum(); + if used > 0.0 && used + part > limit && starts.len() < columns { + starts.push(i); + used = 0.0; + } + used += part; + fits &= used <= limit; + i = end; + } + (starts, fits) +} + +/// The rows at 1:`scale` laid into at most `columns` columns as evenly as they go: where each +/// starts ([`flow`]), and the height of the tallest, in points. +fn balanced(rows: &[LegendRow], columns: usize, scale: f64) -> (Vec, f32) { + let total: f32 = rows.iter().map(|row| row.height(scale)).sum(); + let (mut low, mut high) = (total / columns as f32, total); + for _ in 0..24 { + let middle = (low + high) / 2.0; + if flow(rows, columns, middle, scale).1 { + high = middle; + } else { + low = middle; + } + } + let starts = flow(rows, columns, high, scale).0; + let tallest = column_parts(rows, &starts).map(|part| part.iter().map(|row| row.height(scale)).sum()).fold(0.0f32, f32::max); + (starts, tallest) +} + +/// The rows of each column, from where they start. +fn column_parts<'r, 'a>(rows: &'r [LegendRow<'a>], starts: &'r [usize]) -> impl Iterator]> { + starts.iter().enumerate().map(|(k, &start)| &rows[start..starts.get(k + 1).copied().unwrap_or(rows.len())]) +} + +/// The widest of a column's `rows` at 1:`scale`, in points. +fn widest(rows: &[LegendRow], scale: f64) -> f32 { + let column = swatch_column(rows, scale); + rows.iter().map(|row| row.width(column)).fold(0.0, f32::max) } /// The stacked strokes a legend's class row draws: its class's own, else its layer's, as @@ -1374,10 +1434,14 @@ fn wait_for_tile_legends(map: &Map, scale: f64, exclude: &[String]) { /// side of a legend's point symbol, in points. const MAX_LEGEND_SIDE: u32 = 2048; +/// A legend's text colour. +const LEGEND_TEXT: Rgba = Rgba::rgb(0x22, 0x22, 0x22); /// A legend row's height, in points. const LEGEND_ROW: f32 = 15.0; /// A legend swatch's width, in points. const LEGEND_SWATCH: f32 = 16.0; +/// The room between a legend's columns, in points. +const LEGEND_COLUMN_GAP: f32 = 10.0; /// The rows of the legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the /// frame draws: only the layers listed there, with their classes. Without, every class of every @@ -1439,21 +1503,53 @@ fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts rows } -/// The legend of a frame's map: its rows ([`legend_rows`]) from the top, as many as fit. -fn legend(pm: &mut Canvas, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32, Vec)]>, opts: LegendOptions, ppp: f64) { +/// The legend of a frame's map: its title, and its rows ([`legend_rows`]) under it in `columns` +/// columns, each as wide as its widest row. As even as they go in the height the box leaves; in +/// less, each is filled in turn and the last rows are left out. In a box too narrow they close up, +/// so that none is left out for it: long labels run into the next, and the last column's past the +/// box, as a long label does in one column. +fn legend( + pm: &mut Canvas, + r: Rect, + map: &Map, + (title, columns): (&str, usize), + drawn: Option<&[(u32, Vec)]>, + opts: LegendOptions, + ppp: f64, +) { let ppp = ppp as f32; - let dark = Rgba::rgb(0x22, 0x22, 0x22); let mut y = r.y(); - let line = LEGEND_ROW * ppp; if !title.is_empty() { - text::text_at(pm, title, r.x(), y + line / 2.0, 12.0 * 1.33 * ppp, dark, true, text::Align::Left, false); + let line = LEGEND_ROW * ppp; + text::text_at(pm, title, r.x(), y + line / 2.0, 12.0 * 1.33 * ppp, LEGEND_TEXT, true, text::Align::Left, false); y += line * 1.3; } let rows = legend_rows(map, drawn, &opts); - let sw = swatch_column(&rows, opts.scale) * ppp; - let mut rows = rows.into_iter().peekable(); + let columns = columns.clamp(1, MAX_LEGEND_COLUMNS); + let starts = flow(&rows, columns, balanced(&rows, columns, opts.scale).1.min((r.bottom() - y) / ppp), opts.scale).0; + let across = (column_parts(&rows, &starts).map(|part| widest(part, opts.scale)).sum::() + + LEGEND_COLUMN_GAP * (starts.len() - 1) as f32) + * ppp; + let close_up = if across > r.width() { r.width() / across } else { 1.0 }; + let mut x = r.x(); + for (k, part) in column_parts(&rows, &starts).enumerate() { + // The last has the rest of the box's width. + let right = if k + 1 < starts.len() { x + widest(part, opts.scale) * ppp * close_up } else { r.right() }; + let Some(column) = Rect::from_ltrb(x, y, right, r.bottom()) else { break }; + legend_column(pm, column, part, map, &opts, ppp); + x = right + LEGEND_COLUMN_GAP * ppp * close_up; + } +} + +/// A column of a legend: its rows from the top of `r`, as many as fit. +fn legend_column(pm: &mut Canvas, r: Rect, rows: &[LegendRow], map: &Map, opts: &LegendOptions, ppp: f32) { + let dark = LEGEND_TEXT; + let mut y = r.y(); + let line = LEGEND_ROW * ppp; + let sw = swatch_column(rows, opts.scale) * ppp; + let mut rows = rows.iter().peekable(); while let Some(row) = rows.next() { - if let LegendRow::Picture(p) = &row { + if let LegendRow::Picture(p) = row { match &**p { rustgis_tiles::cache::Payload::Image(pic) => match legend_picture(pm, r, y, pic, ppp) { Some((h, true)) => y += h, @@ -1497,7 +1593,7 @@ fn legend(pm: &mut Canvas, r: Rect, map: &Map, title: &str, drawn: Option<&[(u32 text::text_at(pm, name, r.x(), y + line / 2.0, 9.0 * 1.33 * ppp, dark, true, text::Align::Left, false); } LegendRow::Class(l, en) => { - swatch(pm, (r.x() + 6.0 * ppp, y, sw, height), l, (&en.symbol, row_strokes(l, &en)), map.layer_opacity(l), opts.scale, ppp); + swatch(pm, (r.x() + 6.0 * ppp, y, sw, height), l, (&en.symbol, row_strokes(l, en)), map.layer_opacity(l), opts.scale, ppp); text::text_at( pm, &en.label, @@ -1553,40 +1649,50 @@ fn legend_picture(pm: &mut Canvas, r: Rect, y: f32, pic: &Pixmap, ppp: f32) -> O Some((rows * k, (rows as u32) == pic.height())) } -/// The size a legend with no title takes, in mm (width, height): its rows as [`legend`] draws -/// them, the classes a frame shows at the renderer's scale denominator `scale` (as the layout -/// finds it for a frame, a complete source read through as [`render`] reads it), or every class -/// with `all_classes`. For sizing a legend to its content. `None` when a complete source can't be -/// read, as [`render`] then draws no page. A WMS or WMTS layer's legend picture still on its way -/// isn't waited for, nor counted ([`tile_legends_pending`] says whether one is). -pub fn legend_size_mm(map: &mut Map, scale: f64, all_classes: bool, hide_other: bool, exclude: &[String]) -> Option<(f64, f64)> { +/// The size a legend with no title takes in one column, in two and so on, in mm (width, height): +/// its rows as [`legend`] draws them, the classes a frame shows at the renderer's scale denominator +/// `scale` (as the layout finds it for a frame, a complete source read through as [`render`] reads +/// it), or every class with `all_classes`. For sizing a legend to its content. `None` when a +/// complete source can't be read, as [`render`] then draws no page. A WMS or WMTS layer's legend +/// picture still on its way isn't waited for, nor counted ([`tile_legends_pending`] says whether +/// one is). +pub fn legend_sizes_mm( + map: &mut Map, + scale: f64, + all_classes: bool, + hide_other: bool, + exclude: &[String], +) -> Option<[(f64, f64); MAX_LEGEND_COLUMNS]> { let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale)?) }; let rows = legend_rows(map, drawn.as_deref(), &LegendOptions { hide_other, exclude, scale }); - let column = swatch_column(&rows, scale); - let width = rows - .iter() - .map(|row| match row { - LegendRow::Plain(l) => column + 6.0 + text::measure(&l.name, 9.0, false), - LegendRow::Head(name) => text::measure(name, 9.0, true), - LegendRow::Class(_, en) => column + 12.0 + text::measure(&en.label, 8.5, false), - LegendRow::Picture(p) => 6.0 + picture_size(p).0, - }) - .fold(0.0f32, f32::max); let mm = 25.4 / 96.0; - let height: f32 = rows.iter().map(|row| row.height(scale)).sum(); - Some((f64::from(width) * mm, f64::from(height) * mm)) + Some(std::array::from_fn(|i| { + let (starts, height) = balanced(&rows, i + 1, scale); + let width: f32 = + column_parts(&rows, &starts).map(|part| widest(part, scale)).sum::() + LEGEND_COLUMN_GAP * (starts.len() - 1) as f32; + (f64::from(width) * mm, f64::from(height) * mm) + })) } /// The renderer's scale denominator for a frame showing `map` at paper scale 1:`scale` (the one -/// [`legend_size_mm`] takes). +/// [`legend_sizes_mm`] takes). pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { let cam = frame_camera(map, center, scale, 0.0, 0.0); map.ground_res_at(&cam) / rustgis_geom::PIXEL_M } +/// Whether a layer only outlines its polygons, with no fill and no labels: context around a map's +/// data, such as the neighbouring states' borders, which a surround can sit on. +fn only_outlines(l: &rustgis_map::Layer) -> bool { + l.geometry_type() == GeometryType::Polygon + && !l.labels.enabled + && matches!(&l.renderer, rustgis_map::Renderer::Single(s) if s.fill.0[3] == 0) +} + /// Where a frame showing `map` at 1:`scale` draws its layers: a grid of about `cells` cells across /// the frame's longer side, row by row from the top, each `true` where a layer (or its labels) -/// drew. The basemap is left out, so the frame's background isn't counted. For keeping a +/// drew. The basemap is left out, so the frame's background isn't counted, and so are layers that +/// only outline their polygons ([`only_outlines`]) unless nothing else is shown. For keeping a /// layout's surrounds off what its map shows. `None` when the frame can't be drawn. /// /// The map itself is drawn, not a copy of it (every layer's features): its basemap, web tiles @@ -1607,10 +1713,14 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: graticule: bool, lock: Option>, anchors: std::collections::HashMap, + outlines: Vec, map: &'a mut Map, } impl Drop for Aside<'_> { fn drop(&mut self) { + for l in self.map.layers.iter_mut().filter(|l| self.outlines.contains(&l.id)) { + l.visible = true; + } self.map.basemap = self.basemap; self.map.tiles = std::mem::take(&mut self.tiles); self.map.graticule = self.graticule; @@ -1618,7 +1728,16 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: self.map.label_lock_line_anchors = std::mem::take(&mut self.anchors); } } + let outlines: Vec = if map.layers.iter().filter(|l| map.shows(l)).all(only_outlines) { + Vec::new() + } else { + map.layers.iter().filter(|l| l.visible && only_outlines(l)).map(|l| l.id).collect() + }; + for l in map.layers.iter_mut().filter(|l| outlines.contains(&l.id)) { + l.visible = false; + } let aside = Aside { + outlines, basemap: std::mem::replace(&mut map.basemap, rustgis_map::Basemap::Blank), tiles: std::mem::take(&mut map.tiles), graticule: std::mem::replace(&mut map.graticule, false), @@ -2150,7 +2269,9 @@ mod tests { let mut pm = Pixmap::new(300, 400).unwrap(); pm.fill(tiny_skia::Color::WHITE); let opts = LegendOptions { hide_other: false, exclude, scale }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, width, 400.0).unwrap(), map, "", None, opts, 1.0)); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, width, 400.0).unwrap(), map, ("", 1), None, opts, 1.0) + }); let hits: Vec = (0..pm.height()) .flat_map(|y| (0..pm.width()).map(move |x| (x, y))) .filter(|&(x, y)| pm.pixel(x, y).is_some_and(|p| p.red() > 200 && p.green() < 60)) @@ -2163,7 +2284,7 @@ mod tests { assert!(ink > 200 * 200, "the picture is drawn: {ink} px"); assert!(right < 6 + 256, "a pixel a point: {right}"); // Its name's row and the picture, 256 points down and 6 + 256 across. - let (w, h) = legend_size_mm(&mut map, 1e6, false, false, &[]).unwrap(); + let (w, h) = legend_sizes_mm(&mut map, 1e6, false, false, &[]).unwrap()[0]; let mm = 25.4 / 96.0; assert!((w - 262.0 * mm).abs() < 1e-6 && (h - (f64::from(LEGEND_ROW) + 256.0) * mm).abs() < 1e-6, "{w} × {h} mm"); let (_, right) = red(&map, 100.0, &[], 1e6); @@ -2180,7 +2301,7 @@ mod tests { let mut pm = Pixmap::new(70, 200).unwrap(); pm.fill(tiny_skia::Color::WHITE); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 70.0, 200.0).unwrap(), &map, "", None, opts, 1.0)); + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 70.0, 200.0).unwrap(), &map, ("", 1), None, opts, 1.0)); let red_rows = (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(|p| p.red() > 200 && p.green() < 60))).count(); assert!(red_rows >= 2 * 63, "both pictures, {red_rows} rows"); @@ -2215,7 +2336,7 @@ mod tests { let mut pm = Pixmap::new(300, 15).unwrap(); pm.fill(tiny_skia::Color::WHITE); crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, "", None, opts, 1.0) + legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, ("", 1), None, opts, 1.0) }); assert!(pm.pixels().iter().all(|p| p.red() > 200 && p.green() > 200), "no heading alone"); map.tiles.truncate(1); @@ -2223,6 +2344,168 @@ mod tests { assert_eq!(red(&map, 300.0, &[], 1e6).0, 0, "hidden"); } + /// A layer that only outlines its polygons isn't counted as drawn, unless nothing else is shown, + /// and it is shown again after; one with labels is more than an outline. + #[test] + fn frame_coverage_leaves_out_layers_that_only_outline() { + use rustgis_data::{Dataset, Geometry}; + let count = |map: &mut Map| { + let (.., cells) = frame_coverage(map, Coord::new(0.0, 0.0), 1_000_000.0, 100.0, 100.0, 64).unwrap(); + cells.iter().filter(|c| **c).count() + }; + let point = || { + let mut d = Dataset::new("far", GeometryType::Point, Vec::new()); + d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), Vec::new()); + d + }; + let mut map = Map::new("m"); + let mut square = Dataset::new("border", GeometryType::Polygon, Vec::new()); + square.push( + Some(Geometry::Polygon(vec![vec![ + [(-0.2, -0.2), (0.2, -0.2), (0.2, 0.2), (-0.2, 0.2), (-0.2, -0.2)].map(|(x, y)| Coord::new(x, y)).to_vec(), + ]])), + Vec::new(), + ); + let border = map.add_dataset(square); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == border) { + let outline = rustgis_map::Symbol::default_for(GeometryType::Polygon, 0); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill: Rgba::new(0, 0, 0, 0), ..outline }); + } + assert!(count(&mut map) > 0, "alone, it is what the map shows"); + map.add_dataset(point()); + let beside = count(&mut map); + assert!(map.layer(border).is_some_and(|l| l.visible), "shown again"); + let mut alone = Map::new("m"); + alone.add_dataset(point()); + assert_eq!(beside, count(&mut alone), "only the point counts"); + let l = map.layers.iter_mut().find(|l| l.id == border).unwrap(); + assert!(only_outlines(l)); + l.labels.enabled = true; + assert!(!only_outlines(l), "labels make it more than an outline"); + } + + /// A legend's rows go into columns: as even as they go, a layer's name with the row under it, + /// and in a box too short each filled in turn; one column draws as it always has. + #[test] + fn a_legends_rows_go_into_columns() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let mut map = Map::new("m"); + let mut d = Dataset::new("pts", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("c0".into())]); + let pts = map.add_dataset(d); + let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == pts) { + // The layer's name, 30 classes and the other values: 32 rows. + let classes = (0u32..30).map(|i| (format!("c{i}"), s(i))).collect(); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes, + other: s(31), + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + let opts = || LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; + let rows = legend_rows(&map, None, &opts()); + assert_eq!(rows.len(), 32); + assert_eq!(balanced(&rows, 1, 1e6), (vec![0], 32.0 * LEGEND_ROW)); + assert_eq!(balanced(&rows, 2, 1e6), (vec![0, 16], 16.0 * LEGEND_ROW)); + assert_eq!(balanced(&rows, 3, 1e6).1, 11.0 * LEGEND_ROW); + assert_eq!(balanced(&[], 3, 1e6), (vec![0], 0.0)); + // Too short for them all: each filled in turn, and the last holds what fits of the rest. + let (starts, fits) = flow(&rows, 3, 5.0 * LEGEND_ROW, 1e6); + assert_eq!((starts, fits), (vec![0, 5, 10], false)); + // A layer's name isn't left at the foot of a column; the last, with none under it, can be. + let heads = [LegendRow::Head("a"), LegendRow::Head("b"), LegendRow::Head("c"), LegendRow::Head("d"), LegendRow::Head("e")]; + assert_eq!(flow(&heads, 3, 3.0 * LEGEND_ROW, 1e6), (vec![0, 2], true)); + + let sizes = legend_sizes_mm(&mut map, 1e6, true, false, &[]).unwrap(); + let row = f64::from(LEGEND_ROW) * 25.4 / 96.0; + for (size, rows) in sizes.iter().zip([32.0, 16.0, 11.0]) { + assert!((size.1 - rows * row).abs() < 1e-6, "{size:?} for {rows} rows"); + } + assert!(sizes[0].0 < sizes[1].0 && sizes[1].0 < sizes[2].0, "{sizes:?}"); + + // How far right and down the legend draws in a box, and how many pixels. + let ink = |columns: usize, w: f32, h: f32| { + let mut pm = Pixmap::new(500, 500).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, w, h).unwrap(), &map, ("", columns), None, opts(), 1.0); + }); + let dark = |x, y| pm.pixel(x, y).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); + let right = (0..500).filter(|&x| (0..500).any(|y| dark(x, y))).max().unwrap_or(0); + let down = (0..500).filter(|&y| (0..500).any(|x| dark(x, y))).max().unwrap_or(0); + (right, down) + }; + let mm_pt = 96.0 / 25.4; + let (right1, down1) = ink(1, 500.0, 500.0); + let (right2, down2) = ink(2, 500.0, 500.0); + let (right3, down3) = ink(3, 500.0, 500.0); + assert!(f64::from(down1) > 31.0 * sizes[0].1 / 32.0 * mm_pt, "{down1}"); + assert!(f64::from(down2) <= sizes[1].1 * mm_pt && down2 > down3, "{down2} then {down3}"); + assert!(right1 < right2 && right2 < right3, "{right1}, {right2}, {right3}"); + assert!(f64::from(right3) <= sizes[2].0 * mm_pt + 1.0, "{right3} across {:?}", sizes[2]); + // A value out of range, from a file edited by hand, draws what the nearest would. + assert_eq!(ink(0, 500.0, 500.0), (right1, down1)); + assert_eq!(ink(9, 500.0, 500.0), (right3, down3)); + // A box too narrow for the columns closes them up: the last still starts inside it, past + // where the first two end in a box of their own. + let narrow = f64::from(right3) as f32 * 0.8; + let (right_narrow, down_narrow) = ink(3, narrow, 500.0); + assert!(f64::from(right_narrow) < f64::from(right3) && right_narrow > right1, "{right_narrow} of {right3}"); + // Moved sideways, the letters' lowest edge can land a pixel higher; a lost row would be 15. + assert!(down_narrow.abs_diff(down3) < LEGEND_ROW as u32 / 2, "no row left out: {down_narrow} of {down3}"); + } + + /// The widest class label of `rows`, in points. + fn widest_label(rows: &[LegendRow]) -> f32 { + rows.iter().map(|row| row.width(0.0) - 12.0).fold(0.0, f32::max) + } + + /// A large point symbol makes its row taller and widens its column's symbols only: the columns + /// balance what the rows take, and the other column stays as narrow as its labels let it. + #[test] + fn a_legends_columns_hold_large_point_symbols() { + let small = rustgis_map::Symbol { size: 4.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let classes = + (0u32..10).map(|i| (format!("c{i}"), rustgis_map::Symbol { size: if i < 2 { 40.0 } else { 4.0 }, ..small })).collect(); + let map = point_legend_map(|l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes, + other: small, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + }); + let opts = LegendOptions { hide_other: true, exclude: &[], scale: 1e6 }; + let rows = legend_rows(&map, None, &opts); + let tall = rows[1].height(1e6); + assert!(tall > 2.0 * LEGEND_ROW, "{tall}"); + // The name and the two large symbols, then the eight small ones: counted row by row, these + // would be split at the middle. + let (starts, height) = balanced(&rows, 2, 1e6); + assert_eq!(starts, vec![0, 3], "{height}"); + assert_eq!(height, 8.0 * LEGEND_ROW); + let parts: Vec<_> = column_parts(&rows, &starts).collect(); + assert!(widest(parts[1], 1e6) < widest(parts[0], 1e6) - 20.0, "{} and {}", widest(parts[0], 1e6), widest(parts[1], 1e6)); + // In one column, the small rows' labels line up with the large symbols' as before. + assert_eq!(widest(&rows, 1e6), widest(parts[0], 1e6).max(swatch_column(&rows, 1e6) + 12.0 + widest_label(parts[1]))); + } + #[test] fn legends_leave_out_what_the_frame_does_not_draw() { use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; @@ -2254,7 +2537,9 @@ mod tests { let mut pm = Pixmap::new(300, 400).unwrap(); pm.fill(tiny_skia::Color::WHITE); let opts = LegendOptions { hide_other, exclude, scale: 1e6 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), map, "", drawn, opts, 1.0)); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), map, ("", 1), drawn, opts, 1.0) + }); (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) }; let depth = |map: &Map, drawn: Option<&[(u32, Vec)]>, hide_other: bool| depth_without(map, drawn, hide_other, &[]); @@ -2278,7 +2563,7 @@ mod tests { c, Rect::from_xywh(0.0, 0.0, 300.0, 400.0).unwrap(), map, - "", + ("", 1), drawn, LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }, 1.0, @@ -2287,14 +2572,14 @@ mod tests { (0..pm.width()).filter(|&x| (0..pm.height()).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))).max().unwrap_or(0) }; for (all_classes, ink, right) in [(false, shown, reach(&map, Some(&drawn))), (true, all, reach(&map, None))] { - let (w, h) = legend_size_mm(&mut map, 1e6, all_classes, false, &[]).unwrap(); + let (w, h) = legend_sizes_mm(&mut map, 1e6, all_classes, false, &[]).unwrap()[0]; let (ink, right) = (f64::from(ink) * 25.4 / 96.0, f64::from(right) * 25.4 / 96.0); assert!(w > 0.0 && ink <= h && h - ink < row, "{ink} mm drawn in {h} mm"); // The widths in the same units as the drawing: the ink ends within the width measured, // short of it by no more than a glyph's side bearing. assert!(right <= w + 0.3 && right > w - 1.5, "{right} mm drawn across {w} mm"); } - assert!((legend_size_mm(&mut map, 1e6, false, false, &[]).unwrap().1 - 2.0 * row).abs() < 1e-9); + assert!((legend_sizes_mm(&mut map, 1e6, false, false, &[]).unwrap()[0].1 - 2.0 * row).abs() < 1e-9); // A layer the legend leaves out (by name, any case) isn't listed, drawn or not. let name = map.layer(pts).unwrap().name.to_uppercase(); assert_eq!(depth_without(&map, Some(&drawn), false, std::slice::from_ref(&name)), 0, "its only drawn layer left out"); @@ -3143,7 +3428,7 @@ mod tests { let mut pm = Pixmap::new(200, 200).unwrap(); pm.fill(tiny_skia::Color::WHITE); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), map, "", None, opts, 1.0)); + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 200.0).unwrap(), map, ("", 1), None, opts, 1.0)); pm } @@ -3152,7 +3437,7 @@ mod tests { fn recorded_legend(map: &Map, side: u32) -> Pixmap { let mut c = Canvas::recording(side, side).unwrap(); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; - legend(&mut c, Rect::from_xywh(0.0, 0.0, side as f32, side as f32).unwrap(), map, "", None, opts, 1.0); + legend(&mut c, Rect::from_xywh(0.0, 0.0, side as f32, side as f32).unwrap(), map, ("", 1), None, opts, 1.0); let (_, _, items) = c.into_drawing().unwrap().finish(); let mut pm = Pixmap::new(side, side).unwrap(); pm.fill(tiny_skia::Color::WHITE); @@ -3359,13 +3644,13 @@ mod tests { let label = f64::from(6.0 + text::measure("pts", 9.0, false)); // An ordinary symbol keeps the row and the swatch's column. let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(10.0))); - let (w, h) = legend_size_mm(&mut map, 1e6, true, false, &[]).unwrap(); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, &[]).unwrap(); assert!((h - f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); // Its width within a rounding: it is summed in f32, past a name as wide as its font makes it. assert!((w - (f64::from(LEGEND_SWATCH) + label) * mm).abs() < 1e-4, "{w} mm"); // One of 40 pt reaches 24 pt from its point: 48 pt each way. let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(40.0))); - let (w, h) = legend_size_mm(&mut map, 1e6, true, false, &[]).unwrap(); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, &[]).unwrap(); assert!((h - 48.0 * mm).abs() < 1e-6, "{h} mm"); assert!((w - (48.0 + label) * mm).abs() < 1e-4, "{w} mm"); assert!(same_corner(&point_legend(&map), &drawn_point(&s(40.0), &[], (24.0, 24.0), 1.0), 48, 48)); @@ -3374,11 +3659,11 @@ mod tests { pm.fill(tiny_skia::Color::WHITE); let blank = pm.clone(); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; - crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 47.0).unwrap(), &map, "", None, opts, 1.0)); + crate::canvas::with_canvas(&mut pm, |c| legend(c, Rect::from_xywh(0.0, 0.0, 200.0, 47.0).unwrap(), &map, ("", 1), None, opts, 1.0)); assert!(pm.data() == blank.data()); // A size no page could hold stays a size a legend can take. let mut map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s(f32::MAX))); - let (w, h) = legend_size_mm(&mut map, 1e6, true, false, &[]).unwrap(); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, false, &[]).unwrap(); assert!(w.is_finite() && h.is_finite(), "{w} × {h} mm"); } @@ -3434,7 +3719,7 @@ mod tests { let map = point_legend_map(|l| l.renderer = rustgis_map::Renderer::Single(s)); let mut c = Canvas::recording(2100, 2100).unwrap(); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; - legend(&mut c, Rect::from_xywh(0.5, 0.5, 2099.0, 2099.0).unwrap(), &map, "", None, opts, 1.0); + legend(&mut c, Rect::from_xywh(0.5, 0.5, 2099.0, 2099.0).unwrap(), &map, ("", 1), None, opts, 1.0); let (_, _, items) = c.into_drawing().unwrap().finish(); let mut pm = Pixmap::new(2100, 2100).unwrap(); pm.fill(tiny_skia::Color::WHITE); @@ -3561,7 +3846,7 @@ mod tests { pm.fill(tiny_skia::Color::WHITE); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(0.0, 0.0, 2100.0, 2100.0).unwrap(), &map, "", None, opts, 1.0) + legend(c, Rect::from_xywh(0.0, 0.0, 2100.0, 2100.0).unwrap(), &map, ("", 1), None, opts, 1.0) }); // Drawn, and recorded for a vector export, where only its clip cuts it. for pm in [pm, recorded_legend(&map, 2100)] { @@ -3590,7 +3875,7 @@ mod tests { pm.fill(tiny_skia::Color::WHITE); let opts = LegendOptions { hide_other: false, exclude: &[], scale: 1e6 }; crate::canvas::with_canvas(&mut pm, |c| { - legend(c, Rect::from_xywh(-50.0, -50.0, 2100.0, 2100.0).unwrap(), &map, "", None, opts, 1.0) + legend(c, Rect::from_xywh(-50.0, -50.0, 2100.0, 2100.0).unwrap(), &map, ("", 1), None, opts, 1.0) }); // Its box runs from -50 to 1998: every corner of the canvas is in it. for (x, y) in [(5, 5), (295, 5), (5, 295), (295, 295)] { @@ -3620,7 +3905,7 @@ mod tests { }; }); // The layer's name over the class: a row of 15 and one of 48, 6 + 48 + 6 before its label. - let (w, h) = legend_size_mm(&mut map, 1e6, true, true, &[]).unwrap(); + let [(w, h), ..] = legend_sizes_mm(&mut map, 1e6, true, true, &[]).unwrap(); assert!((h - f64::from(LEGEND_ROW + 48.0) * mm).abs() < 1e-6, "{h} mm"); assert!((w - f64::from(48.0 + 12.0 + text::measure("a", 8.5, false)) * mm).abs() < 1e-4, "{w} mm"); } diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 3f68e16eda..28decc3ebe 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -543,7 +543,7 @@ fn layout_export_keeps_all_drawn_legend_classes() { page.add( "legend", (90.0, 0.0, 45.0, 95.0), - ElementKind::Legend { frame, title: "classes".into(), all_classes: false, hide_other: false, exclude: vec![] }, + ElementKind::Legend { frame, title: "classes".into(), all_classes: false, hide_other: false, exclude: vec![], columns: 1 }, ); let expected = layout::render(&page, &mut [base.clone()], 96.0, &layout::PageInfo::default()).unwrap(); for size in [1, 3, 20] { diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 4a6488bfdc..42dde168c0 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -340,7 +340,7 @@ mod tests { layout.add( "Legend", (10.0, 10.0, 40.0, 30.0), - ElementKind::Legend { frame, title: "Map legend".into(), all_classes: true, hide_other: false, exclude: vec![] }, + ElementKind::Legend { frame, title: "Map legend".into(), all_classes: true, hide_other: false, exclude: vec![], columns: 1 }, ); assert_eq!(picture_dpi(&layout, 600.0, |e| !written_as_svg(e)), 600.0); // A frame and an inset filling an A0 page that is already drawn at its pixel limit. @@ -371,7 +371,7 @@ mod tests { let legend = layout.add( "Legend", (10.0, 10.0, 40.0, 30.0), - ElementKind::Legend { frame, title: "Map legend".into(), all_classes: true, hide_other: false, exclude: vec![] }, + ElementKind::Legend { frame, title: "Map legend".into(), all_classes: true, hide_other: false, exclude: vec![], columns: 1 }, ); let info = PageInfo::default(); let (svg, pictured) = layout_svg(&layout, &mut maps, 72.0, &info).unwrap(); diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index d8256ecd8b..1bda84b2a1 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -7,8 +7,8 @@ use egui::{Align2, Color32, CornerRadius, CursorIcon, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use rustgis_engine::map::layout::{ Arrange, ArrowStyle, CoordFormat, ElementKind, Grid, GridKind, GridStyle, Layout, LineHead, MAX_COLORBAR_TICKS, MAX_FRAME_SCALE, - MAX_GRID_WIDTH, MAX_SCALE_DIVISIONS, MAX_TICK_MM, MIN_FRAME_SCALE, Orientation, PT_PER_MM, ScaleBarStyle, ScaleUnits, TickSide, - frame_camera, line_angle, line_length, + MAX_GRID_WIDTH, MAX_LEGEND_COLUMNS, MAX_SCALE_DIVISIONS, MAX_TICK_MM, MIN_FRAME_SCALE, Orientation, PT_PER_MM, ScaleBarStyle, + ScaleUnits, TickSide, frame_camera, line_angle, line_length, }; use serde_json::{Value, json}; @@ -1524,7 +1524,7 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { match &e.kind { // Its text, size, colour and boldness: the shared form, below the grid. ElementKind::Text { .. } => {} - ElementKind::Legend { title, all_classes, hide_other, .. } => { + ElementKind::Legend { title, all_classes, hide_other, columns, .. } => { let input_label = ui.label(tl!("Title")); if let Some(tt) = text_field(app, ui, (li, id, "title"), title, false, input_label.id) { update(app, json!({"title": tt})); @@ -1543,6 +1543,16 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { update(app, json!({"hideOther": hide})); } ui.end_row(); + let input_label = ui.label(tl!("Columns")); + let mut n = *columns as u64; + let drag = Dragged::lend(ui, drag_key("columns"), &mut n); + let r = ui + .add(egui::DragValue::new(&mut n).update_while_editing(false).range(1..=MAX_LEGEND_COLUMNS as u64)) + .labelled_by(input_label.id); + if drag.settled(ui, &r, &mut n) && n as usize != *columns { + update(app, json!({"columns": n})); + } + ui.end_row(); } ElementKind::Colorbar { frame, layer, title, orientation, ticks, tick_side, reverse } => { let input_label = ui.label(tl!("Title")); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index aa19f4c52b..07fa0cfb24 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -56,8 +56,13 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu alike, such as a context layer filling the frame, isn't worth a warning); two that overlap (a frame too small) are said too. The top visible raster gets a colorbar beneath the vector legend if its renderer has a colour - scale; RGB and untinted hillshade do not. If the legend or colorbar cannot fit, the result - warns about clipping or resizing. A streamed layer still loading gets a fixed-size legend + scale; RGB and untinted hillshade do not. The legend takes the fewest columns, up to three, + that fit the largest rectangle the map leaves free; when none fits, a long one is laid in more + when that shows more of it, or as much while covering at least a quarter less of what the map + draws (the answer's `legendColumns`); in a side column it stays in one. Polygon layers with no + fill and no labels, such as neighbouring borders, don't count as what the map draws here, unless + nothing else is shown. 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. - **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`). @@ -166,6 +171,11 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (`"allClasses": true`) to list every class of every visible layer instead, and **Hide other values** (`"hideOther": true`) to leave `` out of the legend in either mode (the features it stands for are still drawn). + - **Columns** (`"columns"`, 1 to 3): its rows side by side under its title, as even as they go, + each column as wide as its widest row, with its own column of symbols, and a layer's name + staying with the row under it. The box keeps its size, so widen it for the columns: in a box + too narrow they close up and long labels run into the next or past the box, and a box too + short fills each column in turn and leaves out the last rows. - **Point symbols**: a point layer's symbol is drawn as the map draws it: its marker or the stacked marks of its class or layer, its size and outline, the transparency of the layer and its groups, and its reference scale at the frame's scale, unturned. A row has one symbol, so From 10e380474e4e07aa9092e5ed4843977ab4d07480 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 5 Nov 2026 23:40:48 -0300 Subject: [PATCH 2/6] fix(layout): a hatch, a fill by expression, diagrams or extrusion are more than an outline No Fill counts as having no fill whatever the renderer; a transparent symbol under stacked fills doesn't. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout.rs | 29 +++++++++++++++++++++++++++-- docs/user-guide/layouts.md | 5 ++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 9cef7c0351..2ba9c9f307 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1682,11 +1682,20 @@ pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { } /// Whether a layer only outlines its polygons, with no fill and no labels: context around a map's -/// data, such as the neighbouring states' borders, which a surround can sit on. +/// data, such as the neighbouring states' borders, which a surround can sit on. No Fill counts, +/// whatever the renderer; a transparent symbol under stacked fills such as a hatch, a fill by +/// expression, diagrams or extrusion are more than an outline. fn only_outlines(l: &rustgis_map::Layer) -> bool { + use rustgis_map::NoFill; + let hollow = l.no_fill == Some(NoFill::Override) + || (l.fill_layers.is_empty() + && (l.no_fill == Some(NoFill::Symbols) || matches!(&l.renderer, rustgis_map::Renderer::Single(s) if s.fill.0[3] == 0))); l.geometry_type() == GeometryType::Polygon && !l.labels.enabled - && matches!(&l.renderer, rustgis_map::Renderer::Single(s) if s.fill.0[3] == 0) + && hollow + && l.symbol_by.fill.is_none() + && l.diagram.is_none() + && l.extrusion.is_none() } /// Where a frame showing `map` at 1:`scale` draws its layers: a grid of about `cells` cells across @@ -2382,6 +2391,22 @@ mod tests { assert!(only_outlines(l)); l.labels.enabled = true; assert!(!only_outlines(l), "labels make it more than an outline"); + l.labels.enabled = false; + l.fill_layers = vec![rustgis_map::fills::FillLayer::default()]; + assert!(!only_outlines(l), "a stacked fill draws inside it"); + l.no_fill = Some(rustgis_map::NoFill::Symbols); + assert!(!only_outlines(l), "No Fill's symbols leave a stacked fill drawn"); + l.no_fill = Some(rustgis_map::NoFill::Override); + assert!(only_outlines(l), "No Fill's override is the fill that hides the rest"); + l.no_fill = None; + l.fill_layers.clear(); + l.symbol_by.fill = Some("'#ff0000'".into()); + assert!(!only_outlines(l), "a fill by expression draws inside it"); + l.symbol_by.fill = None; + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Polygon, 0)); + assert!(!only_outlines(l), "a filled symbol"); + l.no_fill = Some(rustgis_map::NoFill::Symbols); + assert!(only_outlines(l), "No Fill counts as no fill"); } /// A legend's rows go into columns: as even as they go, a layer's name with the row under it, diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 07fa0cfb24..19ed5d1df1 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -61,9 +61,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu when that shows more of it, or as much while covering at least a quarter less of what the map draws (the answer's `legendColumns`); in a side column it stays in one. Polygon layers with no fill and no labels, such as neighbouring borders, don't count as what the map draws here, unless - nothing else is shown. 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. + nothing else is shown. 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. - **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 6c88eae472298f4e9b6799b9c3250ec5ec8b14a1 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 6 Nov 2026 09:10:59 -0300 Subject: [PATCH 3/6] fix(layout): review round on legend columns (#1379) - A legend left out reports one column: a longer layout that also leaves it out no longer replaces the search's best. - A legend that one column shows whole in the free rectangle stays in one, past the 45% and 60% a legend's box starts with. - A saved layout's legend columns are clamped to 1 to 3. - A layer's name isn't drawn alone at the foot of a column. - A class's stacked fill is more than an outline in frame coverage. - Frame coverage decides what else draws at the frame's scale, not whatever is ticked on: outlines beside a layer out of scale are what the map shows. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 9 ++-- crates/engine/src/tests.rs | 87 +++++++++++++++++++++++++++++++++ crates/map/src/layout.rs | 3 +- crates/render/src/layout.rs | 54 +++++++++++++++++--- 4 files changed, 142 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 3e8cbe37de..b1cf6e88a3 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1950,11 +1950,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { (cw as f64 * fw / gw as f64, ch as f64 * fh / gh as f64) }); let fits = free.and_then(|(rw, rh)| sizes.iter().position(|size| whole(*size).0 <= rw && whole(*size).1 <= rh)); - if let Some(i) = fits.filter(|i| *i > 0) { + // One column too, when the rectangle holds what the box a legend starts with cuts. + if let Some(i) = fits.filter(|i| *i > 0 || whole(sizes[0]).0 > at_most_one.0 + 1e-6 || whole(sizes[0]).1 > at_most_one.1 + 1e-6) { let (w, h) = whole(sizes[i]); - let more = arranged((w.min(wide), h.min(fh * 0.6))); + let more = arranged((w.min(wide), h)); let new = (shown(&more.1, (w, h)), more.1.3.1); - if new.0 >= score.0 - 1e-6 { + if more.1.0.is_some() && new.0 >= score.0 - 1e-6 { (legend_cols, best, score) = (i + 1, more, new); } } @@ -1965,7 +1966,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (w, h) = whole(*size); let more = arranged((w.min(wide), h.min(fh * 0.6))); let new = (shown(&more.1, (w, h)), more.1.3.1); - if more_columns_win(new, score) { + if more.1.0.is_some() && more_columns_win(new, score) { (legend_cols, best, score) = (i + 1, more, new); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8cfd5b29c7..2441fccc80 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6964,6 +6964,83 @@ fn a_publication_legend_too_long_goes_into_columns() { let _ = std::fs::remove_dir_all(&dir); } +/// A legend that one column shows whole, in a free rectangle wider than the legend's usual box, stays +/// in one: a second column would only widen the box. A long one too, in a rectangle taller than that +/// box. +#[test] +fn a_publication_legend_that_fits_whole_stays_in_one_column() { + let dir = std::env::temp_dir().join(format!("rustgis-legend-whole-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let polygon = |name: &str, [w, s, e, n]: [f64; 4]| { + let path = dir.join(name); + let json = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": + {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n], [w, n], [w, s]]]}}]}); + std::fs::write(&path, json.to_string()).unwrap(); + path.display().to_string() + }; + let low = polygon("low.geojson", [0.0, 0.0, 10.0, 6.0]); + let mut s = Session::new(Project::default()); + for name in ["first", "second", "a layer's name long enough to take a little over the share of the frame's width a legend starts with"] + { + s.run("layer.addData", &json!({"path": low})).unwrap(); + s.run("layer.rename", &json!({"layer": "low", "name": name})).unwrap(); + } + let p = json!({"profile": "a4-landscape", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); + let r = s.run("layout.publication", &p).unwrap(); + assert_eq!(r["legendColumns"], 1, "{r}"); + let l = s.project.layouts.last().unwrap(); + let legend = l.elements.iter().find(|e| e.name == "Legend Box").unwrap(); + let frame = l.element(l.first_frame().unwrap()).unwrap(); + assert!(legend.w > 0.45 * frame.w, "the whole of its width: {r}"); + assert!(!r["warnings"].to_string().contains("more than fits"), "{r}"); + + let left = polygon("left.geojson", [0.0, 0.0, 3.0, 10.0]); + let mut s = Session::new(Project::default()); + for _ in 0..28 { + s.run("layer.addData", &json!({"path": left})).unwrap(); + } + let p = json!({"profile": "a4-landscape", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); + let r = s.run("layout.publication", &p).unwrap(); + assert_eq!(r["legendColumns"], 1, "{r}"); + let l = s.project.layouts.last().unwrap(); + let legend = l.elements.iter().find(|e| e.name == "Legend Box").unwrap(); + let frame = l.element(l.first_frame().unwrap()).unwrap(); + assert!(legend.h > 0.6 * frame.h, "the whole of its height: {r}"); + assert!(!r["warnings"].to_string().contains("more than fits"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A legend left out isn't in any columns, whatever the frame leaves free. +#[test] +fn a_publication_legend_left_out_has_one_column() { + let dir = std::env::temp_dir().join(format!("rustgis-legend-out-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.geojson"); + std::fs::write( + &path, + r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[4.8,4.8],[5.2,4.8],[5.2,5.2],[4.8,5.2],[4.8,4.8]]]}}]}"#, + ) + .unwrap(); + let mut checked = false; + for layers in [6, 8, 10, 12, 16, 20, 30, 40, 80] { + let mut s = Session::new(Project::default()); + for _ in 0..layers { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + for n in 1..120 { + let sources: Vec = (0..n).map(|i| format!("Source {i}: a line long enough to take a line of its own")).collect(); + let p = json!({"profile": "a4-landscape", "extent": [0, 0, 10, 10], "sources": sources, "arrangement": "classic"}); + let Ok(r) = s.run("layout.publication", &p) else { break }; + if r["warnings"].to_string().contains("the frame leaves the legend no room beside the locator") { + assert_eq!(r["legendColumns"], 1, "{layers} layers, {n} lines: {r}"); + checked = true; + } + } + } + assert!(checked, "no sheet left the legend out"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A publication legend takes another column to show more of itself, or as much and cover at least /// a quarter less of what the map draws. #[test] @@ -7005,9 +7082,19 @@ fn a_legend_takes_columns_from_one_to_three() { let arrow = s.run("layout.addElement", &json!({"kind": "northArrow"})).unwrap(); let err = s.run("layout.update", &json!({"element": arrow["element"], "columns": 2})).unwrap_err(); assert!(err.contains("only legends"), "{err}"); + let err = s.run("layout.update", &json!({"element": 999, "columns": 2})).unwrap_err(); + assert!(err.contains("no element 999"), "{err}"); // A layout saved before them has one. let old: ElementKind = serde_json::from_str(r#"{"Legend":{"frame":1,"title":"L"}}"#).unwrap(); assert!(matches!(old, ElementKind::Legend { columns: 1, .. }), "{old:?}"); + // A value out of range, from a file edited by hand, is saved as the nearest. + for (given, kept) in [(0, 1), (999, 3)] { + let mut l = s.project.layouts[0].clone(); + let Some(ElementKind::Legend { columns, .. }) = l.element_mut(id as u32).map(|e| &mut e.kind) else { panic!() }; + *columns = given; + l.clamp(); + assert!(matches!(l.element(id as u32).map(|e| &e.kind), Some(ElementKind::Legend { columns, .. }) if *columns == kept), "{given}"); + } } /// A publication layout keys a raster theme with a colorbar: the topmost visible raster drawn on a diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index f2c98b891b..8cafe6e66a 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -1333,10 +1333,11 @@ impl Layout { g.width = finite_or(g.width, grid_width()).clamp(0.0, MAX_GRID_WIDTH); } } - ElementKind::Legend { exclude, .. } => { + ElementKind::Legend { exclude, columns, .. } => { // Names stay whole: a layer's own name isn't cut, and a cut one would no // longer match it. exclude.truncate(MAX_LEGEND_EXCLUDED); + *columns = (*columns).clamp(1, MAX_LEGEND_COLUMNS); } ElementKind::Text { text, size, letter_spacing, .. } => { *size = finite_or(*size, 12.0).clamp(*crate::graphics::FONT_SIZE.start(), *crate::graphics::FONT_SIZE.end()); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2ba9c9f307..200cf4c12e 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1573,6 +1573,13 @@ fn legend_column(pm: &mut Canvas, r: Rect, rows: &[LegendRow], map: &Map, opts: { break; } + // A layer's name only with room for the class under it. + if let (LegendRow::Head(_), Some(next)) = (&row, rows.peek()) + && matches!(next, LegendRow::Class(..)) + && y + height + next.height(opts.scale) * ppp > r.bottom() + line * 1e-3 + { + break; + } match row { LegendRow::Plain(l) => { let s = l.renderer.symbol_for(&l.dataset, 0); @@ -1683,12 +1690,12 @@ pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { /// Whether a layer only outlines its polygons, with no fill and no labels: context around a map's /// data, such as the neighbouring states' borders, which a surround can sit on. No Fill counts, -/// whatever the renderer; a transparent symbol under stacked fills such as a hatch, a fill by -/// expression, diagrams or extrusion are more than an outline. +/// whatever the renderer; a transparent symbol under stacked fills such as a hatch (the layer's or a +/// class's), a fill by expression, diagrams or extrusion are more than an outline. fn only_outlines(l: &rustgis_map::Layer) -> bool { use rustgis_map::NoFill; let hollow = l.no_fill == Some(NoFill::Override) - || (l.fill_layers.is_empty() + || (!l.has_fills() && (l.no_fill == Some(NoFill::Symbols) || matches!(&l.renderer, rustgis_map::Renderer::Single(s) if s.fill.0[3] == 0))); l.geometry_type() == GeometryType::Polygon && !l.labels.enabled @@ -1701,8 +1708,8 @@ fn only_outlines(l: &rustgis_map::Layer) -> bool { /// Where a frame showing `map` at 1:`scale` draws its layers: a grid of about `cells` cells across /// the frame's longer side, row by row from the top, each `true` where a layer (or its labels) /// drew. The basemap is left out, so the frame's background isn't counted, and so are layers that -/// only outline their polygons ([`only_outlines`]) unless nothing else is shown. For keeping a -/// layout's surrounds off what its map shows. `None` when the frame can't be drawn. +/// only outline their polygons ([`only_outlines`]) unless nothing else draws at that scale. For +/// keeping a layout's surrounds off what its map shows. `None` when the frame can't be drawn. /// /// The map itself is drawn, not a copy of it (every layer's features): its basemap, web tiles /// (a background, like the basemap) and graticule are set aside for the drawing and put back, @@ -1737,7 +1744,8 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: self.map.label_lock_line_anchors = std::mem::take(&mut self.anchors); } } - let outlines: Vec = if map.layers.iter().filter(|l| map.shows(l)).all(only_outlines) { + 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 { map.layers.iter().filter(|l| l.visible && only_outlines(l)).map(|l| l.id).collect() @@ -2407,6 +2415,38 @@ mod tests { assert!(!only_outlines(l), "a filled symbol"); l.no_fill = Some(rustgis_map::NoFill::Symbols); assert!(only_outlines(l), "No Fill counts as no fill"); + let symbol = rustgis_map::Symbol::default_for(GeometryType::Polygon, 0); + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".into(), symbol)], + other: symbol, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: [("a".to_string(), vec![rustgis_map::fills::FillLayer::default()])].into(), + other_fills: Vec::new(), + expression: None, + }; + assert!(!only_outlines(l), "No Fill's symbols leave a class's stacked fill drawn"); + l.no_fill = Some(rustgis_map::NoFill::Override); + assert!(only_outlines(l), "the override hides that too"); + l.no_fill = None; + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { + fill: Rgba::new(0, 0, 0, 0), + ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) + }); + + // A layer out of scale at the frame's scale draws nothing there: the outline is all it shows. + let drawn_alone = { + let far = map.layers.iter().find(|l| l.id != border).map(|l| l.id).unwrap(); + map.layers.iter_mut().find(|l| l.id == far).unwrap().min_scale = Some(1.0); + let shown = count(&mut map); + map.layers.iter_mut().find(|l| l.id == far).unwrap().min_scale = None; + shown + }; + assert!(drawn_alone > beside, "{drawn_alone} of {beside}"); } /// A legend's rows go into columns: as even as they go, a layer's name with the row under it, @@ -2487,6 +2527,8 @@ mod tests { assert!(f64::from(right_narrow) < f64::from(right3) && right_narrow > right1, "{right_narrow} of {right3}"); // Moved sideways, the letters' lowest edge can land a pixel higher; a lost row would be 15. assert!(down_narrow.abs_diff(down3) < LEGEND_ROW as u32 / 2, "no row left out: {down_narrow} of {down3}"); + // A box with room for a layer's name and not for the row under it draws neither. + assert_eq!(ink(1, 500.0, LEGEND_ROW * 1.5), (0, 0), "a name alone at the foot"); } /// The widest class label of `rows`, in points. From 25432604a910bd3ab45fecdfbb3d598342d23f2b Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 6 Nov 2026 09:38:15 -0300 Subject: [PATCH 4/6] fix(layout): a legend given columns says what its box loses (#1379) layout.update and layout.addElement left a hand-made legend's lost rows or closed-up columns unsaid, against AGENTS.md's Never silent. Given "columns", they now warn with the check and words layout.publication uses. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 64 ++++++++++++++++++++++++--------- crates/engine/src/tests.rs | 43 ++++++++++++++++++++++ crates/render/src/layout.rs | 5 +++ docs/user-guide/layouts.md | 2 ++ 4 files changed, 98 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b1cf6e88a3..104b8be62e 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2048,23 +2048,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (ix, iy, iw, ih) = (r.0 + pad, r.1 + pad, lw - 2.0 * pad, lh - 2.0 * pad); let bar_fit = if bar.is_some() { bar_h.min(ih) } else { 0.0 }; let rows_h = (ih - bar_fit - if bar.is_some() { bar_part - bar_h } else { 0.0 }).max(0.0); - // A box sized to its content, less the padding again, can come out a rounding error - // short of it: that still fits. - const FIT_MM: f64 = 1e-6; - let (too_wide, too_tall) = (ch > 0.0 && cw > iw + FIT_MM, ch > rows_h + FIT_MM); - if legend_cols > 1 { - // Its columns close up rather than leave one out. - if too_wide { - warnings.push("the legend's columns are wider than its box: they close up, long labels run into the next, and the last column's past the box".into()); - } - if too_tall { - warnings.push("the legend lists more than fits its corner: its last rows are left out".into()); - } - } else if ch > 0.0 && (too_wide || too_tall) { - warnings.push("the legend lists more than fits its corner: its last rows or the ends of long labels are left out".into()); - } + warnings.extend(legend_fit_warnings(legend_cols, (cw, ch), (iw, rows_h)).into_iter().map(String::from)); // In a column the colorbar takes the column's width, as its rows do. - if bar.is_some() && ((bar_w > iw + FIT_MM && !legend_in_column) || bar_h > ih + FIT_MM) { + if bar.is_some() && ((bar_w > iw + LEGEND_FIT_MM && !legend_in_column) || bar_h > ih + LEGEND_FIT_MM) { warnings.push("the legend's box is smaller than the colorbar: it is drawn narrower or shorter".into()); } if ch > 0.0 && rows_h >= 1.0 { @@ -2333,6 +2319,46 @@ pub(crate) fn color(p: &Value, k: &str, d: Rgba) -> Result { const ONLY_LEGEND_COLUMNS: &str = "only legends have columns"; +/// A box sized to its content, less the padding again, can come out a rounding error short of it: +/// that still fits. +const LEGEND_FIT_MM: f64 = 1e-6; + +/// What a legend's rows `size` in `columns` columns lose in a box `room`, in mm, each said once. +fn legend_fit_warnings(columns: usize, (w, h): (f64, f64), (room_w, room_h): (f64, f64)) -> Vec<&'static str> { + let (too_wide, too_tall) = (h > 0.0 && w > room_w + LEGEND_FIT_MM, h > room_h + LEGEND_FIT_MM); + let mut said = Vec::new(); + if columns > 1 { + // Its columns close up rather than leave one out. + if too_wide { + said.push("the legend's columns are wider than its box: they close up, long labels run into the next, and the last column's past the box"); + } + if too_tall { + said.push("the legend lists more than fits its box: its last rows are left out"); + } + } else if h > 0.0 && (too_wide || too_tall) { + said.push("the legend lists more than fits its box: its last rows or the ends of long labels are left out"); + } + said +} + +/// Says what a legend given `"columns"` loses in its box, as `layout.publication` does for its own. +fn say_legend_fit(s: &mut Session, li: usize, id: u32) { + let Some(l) = s.project.layouts.get(li) else { return }; + let Some(e) = l.element(id) else { return }; + let ElementKind::Legend { frame, title, all_classes, hide_other, exclude, columns } = &e.kind else { return }; + let Some(ElementKind::MapFrame { map, center, scale, .. }) = l.element(*frame).map(|f| &f.kind) else { return }; + let (room_w, room_h) = (e.w, e.h - if title.is_empty() { 0.0 } else { crate::render::layout::legend_title_mm() }); + let (all_classes, hide_other, exclude, columns) = (*all_classes, *hide_other, exclude.clone(), *columns); + let (name, center, scale) = (map.clone(), *center, *scale); + let Some(map) = s.project.maps.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&name)) else { return }; + let at = crate::render::layout::frame_render_scale(map, center, scale); + let Some(sizes) = crate::render::layout::legend_sizes_mm(map, at, all_classes, hide_other, &exclude) else { return }; + let size = sizes[columns.clamp(1, MAX_LEGEND_COLUMNS) - 1]; + for said in legend_fit_warnings(columns, size, (room_w, room_h)) { + s.warn(said); + } +} + /// The `"columns"` a legend is given, refused outside 1 to [`MAX_LEGEND_COLUMNS`]. fn legend_columns_param(p: &Value) -> Result, String> { let Some(v) = p.get("columns").filter(|v| !v.is_null()) else { return Ok(None) }; @@ -2574,6 +2600,9 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { }; let l = s.project.layouts.get_mut(i).ok_or("no layout")?; let id = l.add(name, rect, k); + if p.get("columns").is_some_and(|v| !v.is_null()) { + say_legend_fit(s, i, id); + } let mut out = json!({"element": id}); if let Some(w) = warning { out["warning"] = json!(w); @@ -3307,6 +3336,9 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { } _ => {} } + if new_columns.is_some() { + say_legend_fit(s, li, id); + } if let Some(w) = font_told { return Ok(json!({"warning": w})); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2441fccc80..58e5fa30c0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7097,6 +7097,49 @@ fn a_legend_takes_columns_from_one_to_three() { } } +/// A legend given `"columns"` says when its box doesn't hold them, and only then. +#[test] +fn a_legends_columns_say_when_its_box_is_too_small() { + let dir = std::env::temp_dir().join(format!("rustgis-legend-box-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a.geojson"); + std::fs::write( + &path, + r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[4,4],[6,4],[6,6],[4,6],[4,4]]]}}]}"#, + ) + .unwrap(); + let mut s = Session::new(Project::default()); + for _ in 0..12 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + s.run("layout.new", &json!({"template": "map"})).unwrap(); + let said = |s: &Session, mark: u64| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>().join(" | "); + // One big enough: nothing to say, added or changed. + let mark = s.notice_mark(); + let added = s.run("layout.addElement", &json!({"kind": "legend", "columns": 2, "x": 10, "y": 10, "w": 150, "h": 150})).unwrap(); + let id = added["element"].as_u64().unwrap(); + s.run("layout.update", &json!({"element": id, "columns": 3})).unwrap(); + s.run("layout.update", &json!({"element": id, "columns": 1})).unwrap(); + assert_eq!(said(&s, mark), ""); + // Too short: its last rows are left out. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "h": 15, "columns": 2})).unwrap(); + assert!(said(&s, mark).contains("its last rows are left out"), "{}", said(&s, mark)); + // Too narrow: its columns close up. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "w": 12, "h": 150, "columns": 3})).unwrap(); + assert!(said(&s, mark).contains("they close up"), "{}", said(&s, mark)); + // Added too small, in one column. + let mark = s.notice_mark(); + s.run("layout.addElement", &json!({"kind": "legend", "columns": 1, "x": 10, "y": 10, "w": 150, "h": 15})).unwrap(); + assert!(said(&s, mark).contains("its last rows or the ends of long labels are left out"), "{}", said(&s, mark)); + // No title leaves its rows the height it would take. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "w": 150, "h": 150, "title": "", "columns": 2})).unwrap(); + assert_eq!(said(&s, mark), ""); + let _ = std::fs::remove_dir_all(&dir); +} + /// A publication layout keys a raster theme with a colorbar: the topmost visible raster drawn on a /// ramp gets one at the bottom of the legend's box; a map of vectors only gets none. #[test] diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 200cf4c12e..b2a4a341e4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1681,6 +1681,11 @@ pub fn legend_sizes_mm( })) } +/// The height in mm [`legend`] gives a title above its rows, which [`legend_sizes_mm`] leaves out. +pub fn legend_title_mm() -> f64 { + f64::from(LEGEND_ROW) * 1.3 * 25.4 / 96.0 +} + /// The renderer's scale denominator for a frame showing `map` at paper scale 1:`scale` (the one /// [`legend_sizes_mm`] takes). pub fn frame_render_scale(map: &Map, center: Coord, scale: f64) -> f64 { diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 19ed5d1df1..e4a9a509e0 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -175,6 +175,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu staying with the row under it. The box keeps its size, so widen it for the columns: in a box too narrow they close up and long labels run into the next or past the box, and a box too short fills each column in turn and leaves out the last rows. + Giving `"columns"` says when its box loses rows or closes the columns up; resizing the box + afterwards doesn't. - **Point symbols**: a point layer's symbol is drawn as the map draws it: its marker or the stacked marks of its class or layer, its size and outline, the transparency of the layer and its groups, and its reference scale at the frame's scale, unturned. A row has one symbol, so From 24327c04901f521d39fcf0da84365bb411d4b687 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 6 Nov 2026 10:26:34 -0300 Subject: [PATCH 5/6] fix(layout): one column draws as before; a legend in columns says more of what its box loses (#1379) - A layer's name waits for room for its class only in columns: a legend in one column draws it alone at its foot, as it does on main. - A legend in columns is checked again when its box, title or listed layers change, not only when "columns" is given; a move isn't checked. - A fit check that can't run says so: a frame with no map of this project, or a source that can't be read through. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 31 +++++++++++++---- crates/engine/src/tests.rs | 28 ++++++++++++++++ crates/render/src/layout.rs | 59 ++++++++++++++++++++++++--------- docs/user-guide/layouts.md | 5 +-- 4 files changed, 99 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 104b8be62e..67ab036cb4 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2341,18 +2341,29 @@ fn legend_fit_warnings(columns: usize, (w, h): (f64, f64), (room_w, room_h): (f6 said } -/// Says what a legend given `"columns"` loses in its box, as `layout.publication` does for its own. +/// Says what a legend loses in its box, as `layout.publication` does for its own, or that it can't +/// tell. fn say_legend_fit(s: &mut Session, li: usize, id: u32) { let Some(l) = s.project.layouts.get(li) else { return }; let Some(e) = l.element(id) else { return }; let ElementKind::Legend { frame, title, all_classes, hide_other, exclude, columns } = &e.kind else { return }; - let Some(ElementKind::MapFrame { map, center, scale, .. }) = l.element(*frame).map(|f| &f.kind) else { return }; + let shown = match l.element(*frame).map(|f| &f.kind) { + Some(ElementKind::MapFrame { map, center, scale, .. }) => Some((map.clone(), *center, *scale)), + _ => None, + }; let (room_w, room_h) = (e.w, e.h - if title.is_empty() { 0.0 } else { crate::render::layout::legend_title_mm() }); let (all_classes, hide_other, exclude, columns) = (*all_classes, *hide_other, exclude.clone(), *columns); - let (name, center, scale) = (map.clone(), *center, *scale); - let Some(map) = s.project.maps.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&name)) else { return }; + let found = shown + .and_then(|(name, center, scale)| Some((s.project.maps.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&name))?, center, scale))); + let Some((map, center, scale)) = found else { + s.warn("the legend's frame shows no map of this project, so the legend lists nothing"); + return; + }; let at = crate::render::layout::frame_render_scale(map, center, scale); - let Some(sizes) = crate::render::layout::legend_sizes_mm(map, at, all_classes, hide_other, &exclude) else { return }; + let Some(sizes) = crate::render::layout::legend_sizes_mm(map, at, all_classes, hide_other, &exclude) else { + s.warn("a layer's source couldn't be read through, so the legend's fit in its box wasn't checked; exporting says why"); + return; + }; let size = sizes[columns.clamp(1, MAX_LEGEND_COLUMNS) - 1]; for said in legend_fit_warnings(columns, size, (room_w, room_h)) { s.warn(said); @@ -3336,7 +3347,15 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { } _ => {} } - if new_columns.is_some() { + // A legend in columns is told again when its box or what it lists changes; a move changes neither. + let in_columns = matches!(&e.kind, ElementKind::Legend { columns, .. } if *columns > 1); + let refitted = f(p, "w").is_some() + || f(p, "h").is_some() + || ps(p, "title").is_some() + || b(p, "allClasses").is_some() + || b(p, "hideOther").is_some() + || p.get("exclude").is_some_and(|v| !v.is_null()); + if new_columns.is_some() || (in_columns && refitted) { say_legend_fit(s, li, id); } if let Some(w) = font_told { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 58e5fa30c0..aa057cfa6d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7137,6 +7137,34 @@ fn a_legends_columns_say_when_its_box_is_too_small() { let mark = s.notice_mark(); s.run("layout.update", &json!({"element": id, "w": 150, "h": 150, "title": "", "columns": 2})).unwrap(); assert_eq!(said(&s, mark), ""); + // In columns, its box or what it lists changing without "columns": told, and told nothing when + // it still fits or only moves. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "h": 15})).unwrap(); + assert!(said(&s, mark).contains("its last rows are left out"), "{}", said(&s, mark)); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "x": 20})).unwrap(); + assert_eq!(said(&s, mark), ""); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "allClasses": true})).unwrap(); + assert!(said(&s, mark).contains("its last rows are left out"), "{}", said(&s, mark)); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "h": 150})).unwrap(); + s.run("layout.update", &json!({"element": id, "hideOther": true})).unwrap(); + assert_eq!(said(&s, mark), ""); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "w": 12})).unwrap(); + assert!(said(&s, mark).contains("they close up"), "{}", said(&s, mark)); + // In one column a change of its box says nothing, as before columns. + s.run("layout.update", &json!({"element": id, "w": 150, "h": 150, "columns": 1})).unwrap(); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "h": 15})).unwrap(); + assert_eq!(said(&s, mark), ""); + // A frame whose map is gone: said rather than left unchecked. + s.project.maps[0].name = "Elsewhere".into(); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "columns": 2})).unwrap(); + assert!(said(&s, mark).contains("shows no map of this project"), "{}", said(&s, mark)); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index b2a4a341e4..92e9d3076b 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1536,13 +1536,14 @@ fn legend( // The last has the rest of the box's width. let right = if k + 1 < starts.len() { x + widest(part, opts.scale) * ppp * close_up } else { r.right() }; let Some(column) = Rect::from_ltrb(x, y, right, r.bottom()) else { break }; - legend_column(pm, column, part, map, &opts, ppp); + legend_column(pm, column, part, columns > 1, map, &opts, ppp); x = right + LEGEND_COLUMN_GAP * ppp * close_up; } } -/// A column of a legend: its rows from the top of `r`, as many as fit. -fn legend_column(pm: &mut Canvas, r: Rect, rows: &[LegendRow], map: &Map, opts: &LegendOptions, ppp: f32) { +/// A column of a legend: its rows from the top of `r`, as many as fit. With `name_with_class`, a +/// layer's name only with room for the class under it, as [`flow`] keeps them together. +fn legend_column(pm: &mut Canvas, r: Rect, rows: &[LegendRow], name_with_class: bool, map: &Map, opts: &LegendOptions, ppp: f32) { let dark = LEGEND_TEXT; let mut y = r.y(); let line = LEGEND_ROW * ppp; @@ -1573,8 +1574,7 @@ fn legend_column(pm: &mut Canvas, r: Rect, rows: &[LegendRow], map: &Map, opts: { break; } - // A layer's name only with room for the class under it. - if let (LegendRow::Head(_), Some(next)) = (&row, rows.peek()) + if let (true, LegendRow::Head(_), Some(next)) = (name_with_class, &row, rows.peek()) && matches!(next, LegendRow::Class(..)) && y + height + next.height(opts.scale) * ppp > r.bottom() + line * 1e-3 { @@ -2532,8 +2532,6 @@ mod tests { assert!(f64::from(right_narrow) < f64::from(right3) && right_narrow > right1, "{right_narrow} of {right3}"); // Moved sideways, the letters' lowest edge can land a pixel higher; a lost row would be 15. assert!(down_narrow.abs_diff(down3) < LEGEND_ROW as u32 / 2, "no row left out: {down_narrow} of {down3}"); - // A box with room for a layer's name and not for the row under it draws neither. - assert_eq!(ink(1, 500.0, LEGEND_ROW * 1.5), (0, 0), "a name alone at the foot"); } /// The widest class label of `rows`, in points. @@ -2541,14 +2539,9 @@ mod tests { rows.iter().map(|row| row.width(0.0) - 12.0).fold(0.0, f32::max) } - /// A large point symbol makes its row taller and widens its column's symbols only: the columns - /// balance what the rows take, and the other column stays as narrow as its labels let it. - #[test] - fn a_legends_columns_hold_large_point_symbols() { - let small = rustgis_map::Symbol { size: 4.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; - let classes = - (0u32..10).map(|i| (format!("c{i}"), rustgis_map::Symbol { size: if i < 2 { 40.0 } else { 4.0 }, ..small })).collect(); - let map = point_legend_map(|l| { + /// A point layer in Unique Values, for a legend's rows. + fn classed_point_map(classes: Vec<(String, rustgis_map::Symbol)>, small: rustgis_map::Symbol) -> Map { + point_legend_map(|l| { l.renderer = rustgis_map::Renderer::Unique { field: "g".into(), classes, @@ -2562,7 +2555,41 @@ mod tests { other_fills: Vec::new(), expression: None, }; - }); + }) + } + + /// A box one row tall: in one column a layer's name is drawn alone, as it always was; in more, + /// it waits for room for the class under it, and the first column stays blank. + #[test] + fn a_layers_name_stays_with_its_class_only_in_columns() { + let small = rustgis_map::Symbol::default_for(GeometryType::Point, 0); + let classes = (0u32..4).map(|i| (format!("c{i}"), small)).collect(); + let map = classed_point_map(classes, small); + let opts = || LegendOptions { hide_other: true, exclude: &[], scale: 1e6 }; + let rows = legend_rows(&map, None, &opts()); + let (starts, _) = flow(&rows, 2, LEGEND_ROW, 1e6); + assert_eq!(starts, vec![0, 2]); + let first = widest(column_parts(&rows, &starts).next().unwrap(), 1e6); + let drawn_in_first = |columns: usize| { + let mut pm = Pixmap::new(300, 15).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| { + legend(c, Rect::from_xywh(0.0, 0.0, 300.0, LEGEND_ROW).unwrap(), &map, ("", columns), None, opts(), 1.0); + }); + (0..first as u32).any(|x| (0..15).any(|y| pm.pixel(x, y).is_some_and(|p| p.red() < 200))) + }; + assert!(drawn_in_first(1), "one column draws the name alone"); + assert!(!drawn_in_first(2), "two columns keep it with its class"); + } + + /// A large point symbol makes its row taller and widens its column's symbols only: the columns + /// balance what the rows take, and the other column stays as narrow as its labels let it. + #[test] + fn a_legends_columns_hold_large_point_symbols() { + let small = rustgis_map::Symbol { size: 4.0, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Point, 0) }; + let classes = + (0u32..10).map(|i| (format!("c{i}"), rustgis_map::Symbol { size: if i < 2 { 40.0 } else { 4.0 }, ..small })).collect(); + let map = classed_point_map(classes, small); let opts = LegendOptions { hide_other: true, exclude: &[], scale: 1e6 }; let rows = legend_rows(&map, None, &opts); let tall = rows[1].height(1e6); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index e4a9a509e0..82d77bf8af 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -175,8 +175,9 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu staying with the row under it. The box keeps its size, so widen it for the columns: in a box too narrow they close up and long labels run into the next or past the box, and a box too short fills each column in turn and leaves out the last rows. - Giving `"columns"` says when its box loses rows or closes the columns up; resizing the box - afterwards doesn't. + Giving `"columns"`, or changing the box or what a legend in columns lists, says when its box + loses rows or closes the columns up. A legend in one column is told so only when given + `"columns"`. - **Point symbols**: a point layer's symbol is drawn as the map draws it: its marker or the stacked marks of its class or layer, its size and outline, the transparency of the layer and its groups, and its reference scale at the frame's scale, unturned. A row has one symbol, so From 7874bd90d51cef975d6e4d80800479eba3457939 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 6 Nov 2026 11:52:09 -0300 Subject: [PATCH 6/6] fix(layout): a legend with no rows has nothing to lose in its box (#1379) A titled legend in columns with nothing listed, in a box shorter than its title, was told its last rows are left out. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 5 +++-- crates/engine/src/tests.rs | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 67ab036cb4..8f17455a41 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2325,7 +2325,8 @@ const LEGEND_FIT_MM: f64 = 1e-6; /// What a legend's rows `size` in `columns` columns lose in a box `room`, in mm, each said once. fn legend_fit_warnings(columns: usize, (w, h): (f64, f64), (room_w, room_h): (f64, f64)) -> Vec<&'static str> { - let (too_wide, too_tall) = (h > 0.0 && w > room_w + LEGEND_FIT_MM, h > room_h + LEGEND_FIT_MM); + // With no rows there is nothing to lose, in a box shorter than its title too. + let (too_wide, too_tall) = (h > 0.0 && w > room_w + LEGEND_FIT_MM, h > 0.0 && h > room_h + LEGEND_FIT_MM); let mut said = Vec::new(); if columns > 1 { // Its columns close up rather than leave one out. @@ -2335,7 +2336,7 @@ fn legend_fit_warnings(columns: usize, (w, h): (f64, f64), (room_w, room_h): (f6 if too_tall { said.push("the legend lists more than fits its box: its last rows are left out"); } - } else if h > 0.0 && (too_wide || too_tall) { + } else if too_wide || too_tall { said.push("the legend lists more than fits its box: its last rows or the ends of long labels are left out"); } said diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aa057cfa6d..87e305c6cf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7160,6 +7160,14 @@ fn a_legends_columns_say_when_its_box_is_too_small() { let mark = s.notice_mark(); s.run("layout.update", &json!({"element": id, "h": 15})).unwrap(); assert_eq!(said(&s, mark), ""); + // Nothing listed: nothing to lose, in a box shorter than its title too. + let mut empty = Session::new(Project::default()); + empty.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + empty.run("layout.new", &json!({"template": "map"})).unwrap(); + let mark = empty.notice_mark(); + let p = json!({"kind": "legend", "columns": 2, "exclude": ["a"], "x": 10, "y": 10, "w": 150, "h": 1}); + empty.run("layout.addElement", &p).unwrap(); + assert_eq!(said(&empty, mark), ""); // A frame whose map is gone: said rather than left unchecked. s.project.maps[0].name = "Elsewhere".into(); let mark = s.notice_mark();