From 621f4b55dc9536714e1d00f362ec4e6488583d40 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 07:56:21 -0300 Subject: [PATCH 01/12] feat(layout): when no shape of the legend fits, move the map aside, then veil what lies outside the extent (#1379) A follow-up to #1494. These run only when no shape of the legend fits the largest rectangle the map leaves free; a map where one fits comes out as before. - The map moves within the frame's slack, the asked extent still inside, so the room on both its sides joins (`mapShift` in the answer). - A polygon layer in one colour with no labels, beside a layer drawn by classes or a raster, is context, as layers that only outline are. - On a continuous map with a long legend, what is outside the extent gets a white veil and counts as free; the surrounds group in its widest band (`veiled`, `arrangement: "veil"`, and a warning). A sheet may go to up to half the scale for it, which is warned; figures keep theirs. - `"veil": false` keeps the map unveiled and at its scale. - A legend cut short of its neighbours costs more than any move. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 330 +++++++++++++++++++++++++++----- crates/engine/src/tests.rs | 72 +++++++ crates/render/src/layout.rs | 69 ++++++- docs/user-guide/layouts.md | 11 +- 4 files changed, 431 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 54227953c2..b37e81d7f8 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -29,7 +29,7 @@ pub fn commands() -> Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale gets one, under the legend in its box) | "none" (no colorbar, and the legend's box has no room for one), "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite and each arrangement by name laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale gets one, under the legend in its box) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite and each arrangement by name laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.arrangement", "Favourite Arrangement", "Publish › Layout", arrangement).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"favourite"?: "classic" (the locator top left, the north arrow top right, the legend bottom left, the scale bar bottom right) | "mirrored" | "legendRight" | "legendTop" | {"locator", "northArrow", "legend", "scaleBar": "top-left"|"top-right"|"bottom-left"|"bottom-right", each a corner of its own}} → the favourite arrangement of publication layouts (kept with the app's preferences), its corners and the arrangements by name; with no favourite given, it is only shown"#, @@ -467,6 +467,12 @@ fn texts_of(p: &Value, k: &str) -> Result>, String> { /// The extent's height over its width on the active map's projection, along its edges. fn aspect(s: &Session, e: &Extent) -> Option { + let ext = projected_extent(s, e); + (ext.width() > 0.0 && ext.height() > 0.0).then(|| ext.height() / ext.width()) +} + +/// A lon/lat extent's bounds on the map's projection, from points along its edges. +fn projected_extent(s: &Session, e: &Extent) -> Extent { let flat = s.map().flat(); let mut ext = Extent::EMPTY; for i in 0..=32 { @@ -478,7 +484,7 @@ fn aspect(s: &Session, e: &Extent) -> Option { } } } - (ext.width() > 0.0 && ext.height() > 0.0).then(|| ext.height() / ext.width()) + ext } /// `t` in capitals, its `{tokens}` as they are: the layout fills a token (`{date}`) when it draws @@ -668,6 +674,41 @@ pub(crate) fn largest_free_cells(gw: usize, cells: &[bool], (c0, r0, c1, r1): (u best } +/// The surrounds of a veiled map grouped in a band of its veil: the locator with the north arrow at +/// its right and the scale bar under them, beside the legend or over it, whichever the band's shape +/// suits, centred in it. Gives the legend's, locator's, arrow's and scale bar's places; `None` when +/// they don't fit either way. +pub(crate) fn veil_panel( + band: Rect, + legend: (f64, f64), + locator: Option, + arrow: (f64, f64), + scale: (f64, f64), + gap: f64, +) -> Option<(Rect, Option, Rect, Rect)> { + let (bx, by, bw, bh) = band; + let top = (locator.map_or(0.0, |side| side + gap) + arrow.0, locator.unwrap_or(0.0).max(arrow.1)); + let group = (top.0.max(scale.0), top.1 + gap + scale.1); + let beside = legend.0 + gap + group.0 <= bw && legend.1.max(group.1) <= bh; + let over = legend.0.max(group.0) <= bw && legend.1 + gap + group.1 <= bh; + if !beside && !over { + return None; + } + let (legend_at, group_at) = if beside && (bw >= bh || !over) { + let (x, y) = (bx + (bw - legend.0 - gap - group.0) / 2.0, by + (bh - legend.1.max(group.1)) / 2.0); + ((x, y), (x + legend.0 + gap, y)) + } else { + let (x, y) = (bx + (bw - legend.0.max(group.0)) / 2.0, by + (bh - legend.1 - gap - group.1) / 2.0); + ((x, y + group.1 + gap), (x, y)) + }; + Some(( + (legend_at.0, legend_at.1, legend.0, legend.1), + locator.map(|side| (group_at.0, group_at.1, side, side)), + (group_at.0 + group.0 - arrow.0, group_at.1, arrow.0, arrow.1), + (group_at.0, group_at.1 + top.1 + gap, scale.0, scale.1), + )) +} + /// A publication layout's colorbar's height, in mm: its title, the bar and its labels. const COLORBAR_MM: f64 = 15.0; @@ -944,6 +985,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let comma = decimal_mark(p)?.unwrap_or(false); let locator = publication_locator(p, sheet)?; let colorbar = publication_colorbar(p)?; + let may_veil = publication_veil(p)?; // A style or an accent that isn't text is refused, as an unknown one is, rather than left out. for k in ["style", "accent"] { if p.get(k).is_some_and(|v| !v.is_null() && !v.is_string()) { @@ -1751,37 +1793,6 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } let (sw, sh, nh) = ((fw * 0.3).max(25.0), if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); let pad = 2.0; - // What the map draws where, on a grid of the frame (its basemap left out). The map - // itself is drawn for it, on purpose, as the screen draws it: a grid of 384 cells, a small part - // of what exporting the sheet draws; a streamed layer draws what it holds and starts reading - // the frame's area in the background (which the export reads anyway); web tiles aren't fetched. - let coverage = crate::render::layout::frame_coverage(s.map_mut(), center, scale, fw, fh, 384); - // Its cells summed from the top left (a summed-area table), so a rectangle's count is four - // lookups, however large: the search off the corners tries thousands. - let sums: Option<(usize, usize, Vec)> = coverage.as_ref().map(|(gw, gh, cells)| { - let (gw, gh) = (*gw as usize, *gh as usize); - let mut t = vec![0u32; (gw + 1) * (gh + 1)]; - for r in 0..gh { - for c in 0..gw { - let v = u32::from(cells.get(r * gw + c).copied().unwrap_or(false)); - t[(r + 1) * (gw + 1) + c + 1] = v + t[r * (gw + 1) + c + 1] + t[(r + 1) * (gw + 1) + c] - t[r * (gw + 1) + c]; - } - } - (gw, gh, t) - }); - // The share of a rectangle (in page mm) over the frame's drawn cells. - let covered = |(x, y, w, h): (f64, f64, f64, f64)| -> f64 { - let Some((gw, gh, t)) = &sums else { return 0.0 }; - let (gw, gh) = (*gw, *gh); - let col = |v: f64| ((v - fx) / fw * gw as f64).floor().clamp(0.0, gw as f64) as usize; - let row = |v: f64| ((v - fy) / fh * gh as f64).floor().clamp(0.0, gh as f64) as usize; - let (c0, r0) = (col(x).min(gw.saturating_sub(1)), row(y).min(gh.saturating_sub(1))); - let (c1, r1) = (col(x + w).max(c0 + 1).min(gw), row(y + h).max(r0 + 1).min(gh)); - let n = (c1 - c0) * (r1 - r0); - let at = |r: usize, c: usize| f64::from(t[r * (gw + 1) + c]); - let drawn = at(r1, c1) - at(r0, c1) - at(r1, c0) + at(r0, c0); - if n == 0 { 0.0 } else { drawn / n as f64 } - }; // The surrounds to place: what each is and its size (the arrangement gives its corner). let mut surrounds: Vec<(Surround, f64, f64)> = Vec::new(); if locator_map.is_some() && column.is_none() { @@ -1816,6 +1827,185 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { Surround::Scale => "scale bar", }; let area = (fx + left, fy + top, fx + fw - right, fy + fh - bottom); + // What the map draws where, on a grid of the frame (its basemap left out). The map + // itself is drawn for it, on purpose, as the screen draws it: a grid of 384 cells, a small part + // of what exporting the sheet draws; a streamed layer draws what it holds and starts reading + // the frame's area in the background (which the export reads anyway); web tiles aren't fetched. + let coverage = crate::render::layout::frame_coverage(s.map_mut(), center, scale, fw, fh, 384); + // The legend's whole box, around its rows and the colorbar under them. + 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); + // The largest rectangle a coverage leaves free inside the graticule's margins, in mm. + let free_room = |(gw, gh, cells): &(u32, u32, Vec)| { + 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) + }; + // When no shape of the legend fits the room the map leaves, the map moves as far as the asked + // extent stays in the frame, towards the edge that joins the room on both its sides. Failing + // that, on a continuous map (drawn over most of the extent and running on past it) with a long + // legend (a short one sits over the map as well as ever), what is outside the extent is veiled, + // and counts as room; and failing that, the map is drawn at up to half the scale, for a band of + // it. Failing all those, it stays as it was (#1379). + let (mut center, mut scale, mut coverage, mut map_shift) = (center, scale, coverage, (0.0, 0.0)); + let mut veiled: Option = None; + // The bands of the veil around an extent's place on the page, the widest first, short of the + // extent by the gap the surrounds keep in a group. + const GROUP_GAP: f64 = 3.0; + let bands_around = |clip: Rect| { + let (clip_right, clip_below) = (clip.0 + clip.2 + GROUP_GAP, clip.1 + clip.3 + GROUP_GAP); + let mut bands = [ + (area.0, area.1, clip.0 - GROUP_GAP - area.0, area.3 - area.1), + (clip_right, area.1, area.2 - clip_right, area.3 - area.1), + (area.0, area.1, area.2 - area.0, clip.1 - GROUP_GAP - area.1), + (area.0, clip_below, area.2 - area.0, area.3 - clip_below), + ]; + bands.sort_by(|a, b| (b.2 * b.3).total_cmp(&(a.2 * a.3))); + bands + }; + let size_of = |kind: Surround| surrounds.iter().find(|x| x.0 == kind).map(|x| (x.1, x.2)); + let (locator_side, arrow_size, scale_size) = + (size_of(Surround::Locator).map(|x| x.0), size_of(Surround::Arrow), size_of(Surround::Scale)); + // The fewest columns from `from` up in which the surrounds group in a band around `clip`, with + // their places. + let grouped = |clip: Rect, from: usize, known: &[(f64, f64); MAX_LEGEND_COLUMNS]| { + let (arrow, scale_bar) = (arrow_size?, scale_size?); + (from..known.len()).find_map(|i| { + bands_around(clip) + .iter() + .find_map(|band| veil_panel(*band, whole(known[i]), locator_side, arrow, scale_bar, GROUP_GAP)) + .map(|places| (i, places)) + }) + }; + if let Some(known) = sizes.filter(|_| column.is_none() && content_h > 0.0) { + let need = |room: (f64, f64)| known.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1); + let flat = s.map().flat(); + let asked = projected_extent(s, &extent); + let at = flat.forward_checked(center).filter(|_| !asked.is_empty()); + if let Some(at) = at.filter(|_| coverage.as_ref().is_some_and(|c| need(free_room(c)).is_none())) { + let (centred, asked_scale) = (center, scale); + let continuous = coverage.as_ref().is_some_and(|(gw, gh, cells)| { + let mm = 1000.0 * flat.ground_per_unit(asked.center()) * s.map().body().ratio() / asked_scale; + let (half_w, half_h) = (asked.width() * mm / 2.0, asked.height() * mm / 2.0); + let (gw, gh) = (*gw as usize, *gh as usize); + let (mut inside, mut inside_drawn, mut outside, mut outside_drawn) = (0usize, 0usize, 0usize, 0usize); + for (i, drawn) in cells.iter().enumerate() { + let x = ((i % gw) as f64 + 0.5) / gw as f64 * fw - fw / 2.0; + let y = ((i / gw) as f64 + 0.5) / gh as f64 * fh - fh / 2.0; + if x.abs() <= half_w && y.abs() <= half_h { + inside += 1; + inside_drawn += usize::from(*drawn); + } else { + outside += 1; + outside_drawn += usize::from(*drawn); + } + } + whole(known[0]).1 > fh * 0.25 + && inside > 0 + && inside_drawn * 5 >= inside * 4 + && (outside == 0 || outside_drawn * 10 >= outside * 3) + }); + // `"veil": false` keeps the map unveiled, and so at its scale. + let continuous = continuous && may_veil; + let passes = [(1.0, false), (1.0, true), (1.25, true), (1.5, true), (2.0, true)]; + // A figure keeps its scale: its size is fixed, and a smaller scale costs it the most. + for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { + let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; + let mm = 1000.0 * flat.ground_per_unit(asked.center()) * s.map().body().ratio() / tried; + let slack_x = ((fw - left - right - asked.width() * mm) / 2.0).max(0.0); + let slack_y = ((fh - top - bottom - asked.height() * mm) / 2.0).max(0.0); + let mut found: Option<(usize, f64)> = None; + for (dx, dy) in [(0.0, 0.0), (slack_x, 0.0), (-slack_x, 0.0), (0.0, slack_y), (0.0, -slack_y)] { + // Centred with no veil at the asked scale is what has no room; a shift of nothing + // is centred. + let still = dx == 0.0 && dy == 0.0; + if (still && !veil) || (!still && dx.abs() + dy.abs() < 1.0) { + continue; + } + let (cx, cy) = (at.x - dx / mm, at.y + dy / mm); + let there = if still { Some(centred) } else { flat.inverse(Coord::new(cx, cy)) }; + let Some(there) = there else { continue }; + let Some(mut moved) = crate::render::layout::frame_coverage(s.map_mut(), there, tried, fw, fh, 384) else { continue }; + // The extent on the page: what is outside it is free once veiled. + let clip = ( + fx + fw / 2.0 + (asked.min_x - cx) * mm, + fy + fh / 2.0 - (asked.max_y - cy) * mm, + asked.width() * mm, + asked.height() * mm, + ); + if veil { + let (gw, gh) = (moved.0 as usize, moved.1 as usize); + for (i, cell) in moved.2.iter_mut().enumerate() { + let x = fx + ((i % gw) as f64 + 0.5) / gw as f64 * fw; + let y = fy + ((i / gw) as f64 + 0.5) / gh as f64 * fh; + *cell &= x >= clip.0 && x <= clip.0 + clip.2 && y >= clip.1 && y <= clip.1 + clip.3; + } + } + let room = free_room(&moved); + let Some(n) = need(room) else { continue }; + // Under a veil the whole group has to fit, not the legend alone. + let Some(n) = (if veil { grouped(clip, n, &known).map(|(i, _)| i) } else { Some(n) }) else { continue }; + if found.is_none_or(|(fewest, most)| n < fewest || (n == fewest && room.0 * room.1 > most)) { + found = Some((n, room.0 * room.1)); + (center, scale, coverage, map_shift) = (there, tried, Some(moved), (dx, dy)); + veiled = veil.then_some(clip); + } + } + if found.is_some() { + break; + } + } + if scale != asked_scale { + warnings.push(format!("the map is drawn at 1:{scale:.0}, not 1:{asked_scale:.0}, to leave the legend room")); + // A wider view can draw more classes, and a streamed layer has its features read. + let render_scale = crate::render::layout::frame_render_scale(s.map(), center, scale); + let view = crate::render::View { + width: fw * rustgis_map::layout::PT_PER_MM, + height: fh * rustgis_map::layout::PT_PER_MM, + pixels_per_point: 1.0, + camera: rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0), + sky: false, + }; + let lonlat = crate::render::view_lonlat(s.map(), &view); + s.map_mut().sync_sources(&lonlat, render_scale, true); + sizes = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]); + if let Some(wider) = sizes { + (cw, ch) = wider[0]; + let (w, h) = whole(wider[0]); + if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Legend) { + (entry.1, entry.2) = (w.min(fw * 0.45), h.min(fh * 0.6)); + } + } + } + } + } + // Its cells summed from the top left (a summed-area table), so a rectangle's count is four + // lookups, however large: the search off the corners tries thousands. + let sums: Option<(usize, usize, Vec)> = coverage.as_ref().map(|(gw, gh, cells)| { + let (gw, gh) = (*gw as usize, *gh as usize); + let mut t = vec![0u32; (gw + 1) * (gh + 1)]; + for r in 0..gh { + for c in 0..gw { + let v = u32::from(cells.get(r * gw + c).copied().unwrap_or(false)); + t[(r + 1) * (gw + 1) + c + 1] = v + t[r * (gw + 1) + c + 1] + t[(r + 1) * (gw + 1) + c] - t[r * (gw + 1) + c]; + } + } + (gw, gh, t) + }); + // The share of a rectangle (in page mm) over the frame's drawn cells. + let covered = |(x, y, w, h): (f64, f64, f64, f64)| -> f64 { + let Some((gw, gh, t)) = &sums else { return 0.0 }; + let (gw, gh) = (*gw, *gh); + let col = |v: f64| ((v - fx) / fw * gw as f64).floor().clamp(0.0, gw as f64) as usize; + let row = |v: f64| ((v - fy) / fh * gh as f64).floor().clamp(0.0, gh as f64) as usize; + let (c0, r0) = (col(x).min(gw.saturating_sub(1)), row(y).min(gh.saturating_sub(1))); + let (c1, r1) = (col(x + w).max(c0 + 1).min(gw), row(y + h).max(r0 + 1).min(gh)); + let n = (c1 - c0) * (r1 - r0); + let at = |r: usize, c: usize| f64::from(t[r * (gw + 1) + c]); + let drawn = at(r1, c1) - at(r0, c1) - at(r1, c0) + at(r0, c0); + if n == 0 { 0.0 } else { drawn / n as f64 } + }; // 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 @@ -1873,9 +2063,11 @@ 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)); + // A legend cut short of its neighbours loses rows, which costs half the frame, more than any + // move, and ten times what it loses, so an arrangement that keeps them wins, also by moving + // the legend itself; a rounding error costs nothing. + let lost = legend_at.map_or(0.0, |(_, lw, lh)| legend.0 * legend.1 - lw * lh); + let cut = if lost > 1.0 { fw * fh / 2.0 + 10.0 * lost } else { 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::>()); @@ -1899,18 +2091,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // 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 free = coverage.as_ref().map(free_room); let fits = free.and_then(|(rw, rh)| sizes.iter().position(|size| whole(*size).0 <= rw && whole(*size).1 <= rh)); // One column too, when the rectangle holds what the box a legend starts with cuts. 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) { @@ -1934,7 +2119,51 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } (cw, ch) = sizes[legend_cols - 1]; } - let (homes, (legend_at, spots, moved, _)) = best; + let (homes, (legend_at, mut spots, mut moved, _)) = best; + // A veiled map has its surrounds grouped in the widest band of the veil that takes them, in the + // fewest columns that do, rather than each in a corner of its own. + let mut arrangement_used = arrangement_name(homes); + if let (Some(clip), Some(known)) = (veiled, sizes) + && let Some((i, (legend_place, locator_place, arrow_place, scale_place))) = grouped(clip, legend_cols - 1, &known) + { + legend_cols = i + 1; + (cw, ch) = known[i]; + for (kind, r) in spots.iter_mut() { + *r = match kind { + Surround::Legend => legend_place, + Surround::Locator => locator_place.unwrap_or(*r), + Surround::Arrow => arrow_place, + Surround::Scale => scale_place, + }; + } + moved.clear(); + arrangement_used = "veil"; + } + if let Some(ElementKind::MapFrame { center: at, scale: drawn_at, .. }) = l.element_mut(frame).map(|e| &mut e.kind) { + (*at, *drawn_at) = (center, scale); + } + // The veil over the frame and under its surrounds, in four bands around the extent, and the + // extent's outline: it covers what the map draws there, which is said. + if let Some((x, y, w, h)) = veiled { + warnings.push( + "what the map draws outside the extent is veiled, for the legend's room, and the surrounds sit there: \"veil\": false leaves it unveiled" + .into(), + ); + let (x0, y0) = (x.max(fx), y.max(fy)); + let (x1, y1) = ((x + w).min(fx + fw), (y + h).min(fy + fh)); + let veil = || pub_card(Rgba::new(255, 255, 255, 150), Rgba::new(0, 0, 0, 0), 0.0, 0.0); + for (name, band) in [ + ("Veil Above", (fx, fy, fw, y0 - fy)), + ("Veil Below", (fx, y1, fw, fy + fh - y1)), + ("Veil Left", (fx, y0, x0 - fx, y1 - y0)), + ("Veil Right", (x1, y0, fx + fw - x1, y1 - y0)), + ] { + if band.2 > 0.0 && band.3 > 0.0 { + l.add(name, band, veil()); + } + } + l.add("Extent Outline", (x0, y0, x1 - x0, y1 - y0), pub_card(Rgba::new(0, 0, 0, 0), Rgba::rgb(0x2B, 0x26, 0x20), 0.8, 0.0)); + } 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\"" @@ -2095,7 +2324,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), "legendColumns": legend_cols, "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_used, "legendColumns": legend_cols, "mapShift": [map_shift.0, map_shift.1], "veiled": veiled.is_some(), "elements": elements, "moved": moved, "warnings": warnings}), ) } @@ -4024,6 +4253,15 @@ fn publication_colorbar(p: &Value) -> Result { } } +/// Whether the publication may veil what lies outside the extent when nothing else leaves its +/// legend room: `true` (the default) or `false`. +fn publication_veil(p: &Value) -> Result { + match p.get("veil").filter(|v| !v.is_null()) { + None => Ok(true), + Some(v) => v.as_bool().ok_or_else(|| "veil is true or false".into()), + } +} + /// Parses the publication's locator choice with the sheet-specific default. fn publication_locator(p: &Value, sheet: bool) -> Result { Ok(match p.get("locator").filter(|v| !v.is_null()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fa33d2ba1b..7809be5ba1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7633,6 +7633,78 @@ fn a_publication_without_a_colorbar_sizes_the_legend_box_to_the_legend() { let _ = std::fs::remove_file(&path); } +/// A veiled map's surrounds group in a band: beside each other in a wide one, one over the other in +/// a tall one, nowhere when they don't fit. +#[test] +fn a_veil_panel_groups_the_surrounds_by_the_bands_shape() { + use crate::cmd::layout::veil_panel; + let (legend, arrow, scale) = ((80.0, 50.0), (8.0, 12.0), (60.0, 10.0)); + let (l, locator, a, b) = veil_panel((0.0, 0.0, 160.0, 70.0), legend, Some(40.0), arrow, scale, 3.0).unwrap(); + assert!(l.0 + l.2 <= locator.unwrap().0, "beside it: {l:?} {locator:?}"); + assert!(a.0 + a.2 <= l.0 + 160.0 && b.1 >= locator.unwrap().1 + 40.0, "{a:?} {b:?}"); + let (l, locator, _, b) = veil_panel((0.0, 0.0, 90.0, 130.0), legend, Some(40.0), arrow, scale, 3.0).unwrap(); + assert!(l.1 >= b.1 + b.3 && locator.unwrap().0 == b.0, "under it: {l:?} {b:?}"); + assert!(veil_panel((0.0, 0.0, 60.0, 60.0), legend, Some(40.0), arrow, scale, 3.0).is_none()); + assert!(veil_panel((0.0, 0.0, 160.0, 70.0), legend, None, arrow, scale, 3.0).unwrap().1.is_none()); +} + +/// With no room for any shape of the legend on either side of a centred map, the map moves towards +/// an edge, the asked extent still in the frame, and the legend takes the room that joins. With room +/// already, it stays centred. +#[test] +fn a_publication_map_moves_aside_for_a_legend_with_no_room() { + let dir = std::env::temp_dir().join(format!("rustgis-map-shift-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("a_layer_name.geojson"); + let json = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": + {"type": "Polygon", "coordinates": [[[0.0, 0.0], [15.0, 0.0], [15.0, 10.0], [0.0, 10.0], [0.0, 0.0]]]}}]}); + std::fs::write(&path, json.to_string()).unwrap(); + let laid = |layers: usize, extent: Value| { + 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!({"profile": "a4-landscape", "extent": extent, "author": "", "locator": "none"})).unwrap(); + (r["legendColumns"].as_u64().unwrap(), r["mapShift"][0].as_f64().unwrap(), r["mapShift"][1].as_f64().unwrap(), r["moved"].clone()) + }; + let (_, x, y, _) = laid(3, json!([-5, -5, 20, 15])); + assert_eq!((x, y), (0.0, 0.0), "a short legend has room"); + let (columns, x, y, _) = laid(30, json!([0, 0, 15, 10])); + assert!(x.abs() > 5.0 && y == 0.0, "moved sideways: {x}, {y}"); + assert_eq!(columns, 1, "one column beside the map"); + // A map running on past the extent: what is outside it is veiled, at the asked scale while the + // frame leaves a band of it wide enough, and at a smaller one otherwise. + let on_past = |extent: Value, veil: Value| { + let mut s = Session::new(Project::default()); + for _ in 0..12 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let p = json!({"profile": "a4-landscape", "extent": extent, "author": "", "locator": "none", "veil": veil}); + let r = s.run("layout.publication", &p).unwrap(); + let smaller = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("to leave the legend room")); + let veils = r["elements"].as_array().unwrap().iter().filter(|e| e["name"].as_str().unwrap().starts_with("Veil")).count(); + assert_eq!(r["arrangement"] == "veil", r["veiled"].as_bool().unwrap(), "{r}"); + let said = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("outside the extent is veiled")); + assert_eq!(said, r["veiled"].as_bool().unwrap(), "the veil is said, and only then: {r}"); + (r["veiled"].as_bool().unwrap(), smaller, veils > 0, r["scale"].as_f64().unwrap()) + }; + let (veiled, smaller, veils, _) = on_past(json!([7, 4, 9, 6]), Value::Null); + assert_eq!((veiled, smaller, veils), (true, false, true), "a narrow extent in a wide frame"); + let (veiled, smaller, veils, scale) = on_past(json!([5, 4, 8.7, 6]), Value::Null); + assert_eq!((veiled, smaller, veils), (true, true, true), "an extent the frame's shape"); + // `"veil": false` keeps the map as it is drawn: no veil, and the scale it was asked at. + let (veiled, smaller, veils, asked) = on_past(json!([5, 4, 8.7, 6]), json!(false)); + assert_eq!((veiled, smaller, veils), (false, false, false)); + assert!(asked < scale, "1:{asked} against the veil's 1:{scale}"); + assert_eq!(on_past(json!([7, 4, 9, 6]), json!(true)).0, true, "true is the default"); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + let bad = s.run("layout.publication", &json!({"profile": "a4-landscape", "veil": "no"})).unwrap_err(); + assert!(bad.contains("veil is true or false"), "{bad}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_publication_legend_too_long_goes_into_columns() { use rustgis_map::layout::ElementKind; diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index b9524ecf2d..85dfca182d 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2007,11 +2007,24 @@ fn only_outlines(l: &rustgis_map::Layer) -> bool { && l.extrusion.is_none() } +/// Whether a layer fills its polygons in one colour, with no labels and nothing else: beside a layer +/// drawn by classes or a raster it is context too, such as the neighbouring states in grey. +fn plain_fill(l: &rustgis_map::Layer) -> bool { + l.geometry_type() == GeometryType::Polygon + && !l.labels.enabled + && !l.has_fills() + && matches!(&l.renderer, rustgis_map::Renderer::Single(_)) + && 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 /// 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 draws at that scale. 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 is shown, and those that +/// fill them in one colour ([`plain_fill`]) beside a layer drawn by classes or a raster. 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, @@ -2050,7 +2063,9 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: 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() + let classes = + map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); + map.layers.iter().filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l)))).map(|l| l.id).collect() }; for l in map.layers.iter_mut().filter(|l| outlines.contains(&l.id)) { l.visible = false; @@ -2771,6 +2786,54 @@ mod tests { shown }; assert!(drawn_alone > beside, "{drawn_alone} of {beside}"); + let l = map.layers.iter_mut().find(|l| l.id == border).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Polygon, 0)); + assert!(plain_fill(l), "one colour"); + l.labels.enabled = true; + assert!(!plain_fill(l), "labels make it more than context"); + } + + /// A polygon layer in one colour is context beside a layer drawn by classes, and what the map + /// shows when all its layers are in one colour. + #[test] + fn frame_coverage_leaves_out_one_colour_fills_beside_classes() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + 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 mut map = Map::new("m"); + let mut square = Dataset::new("states", 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 states = map.add_dataset(square); + let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); + let far = map.add_dataset(d); + let with_states = count(&mut map); + let s = |c| rustgis_map::Symbol::default_for(GeometryType::Point, c); + if let Some(l) = map.layers.iter_mut().find(|l| l.id == far) { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("c".to_string(), s(0))], + other: s(1), + 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 beside_classes = count(&mut map); + assert!(beside_classes > 0 && beside_classes < with_states, "{beside_classes} of {with_states}"); + assert!(map.layer(states).is_some_and(|l| l.visible), "shown again"); } /// 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 3fd9bc4ba8..59f1a70c49 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -63,8 +63,15 @@ 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, nor do polygon layers in one colour with no labels beside a layer drawn by + classes or a raster. When no shape of the legend fits, the map moves towards an edge, as far as + the asked extent stays in the frame, so the room on both its sides joins (the answer's + `mapShift`, in mm). On a map that runs on past the extent, with a long legend, what is outside + the extent is then veiled, with the surrounds grouped in its widest band (the answer's `veiled`, + and `arrangement` `"veil"`, and a warning), at up to half the scale on a sheet when the frame + leaves too little of it, which the result says too. The veil and the surrounds are ordinary + elements, to move or delete as any other; `"veil": false` leaves the map unveiled and at its + scale. If the legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by hand. - **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 6896eedb844e63075868e275b302fa9a6331267c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 08:31:23 -0300 Subject: [PATCH 02/12] test(layout): assert! for a bool, as clippy asks Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9401d92e72..ea5eaea120 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7697,7 +7697,7 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { let (veiled, smaller, veils, asked) = on_past(json!([5, 4, 8.7, 6]), json!(false)); assert_eq!((veiled, smaller, veils), (false, false, false)); assert!(asked < scale, "1:{asked} against the veil's 1:{scale}"); - assert_eq!(on_past(json!([7, 4, 9, 6]), json!(true)).0, true, "true is the default"); + assert!(on_past(json!([7, 4, 9, 6]), json!(true)).0, "true, as by default"); let mut s = Session::new(Project::default()); s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); let bad = s.run("layout.publication", &json!({"profile": "a4-landscape", "veil": "no"})).unwrap_err(); From c15c1d80cdffda12b3899310ddcca99d4530e1cb Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 08:57:41 -0300 Subject: [PATCH 03/12] fix(layout): one drawing per scale in the map's search, the legend's sizes kept, a study area counted (#1379) Review round 1 of #1725: - Each scale the search tries is drawn once, wide enough for every move, and each move's coverage cut from it (`crop_cells`): at most four more drawings, not 24. On a 14 MB geology map, 2.5 s became 0.7 s. - The legend is measured once per scale tried, and the chosen sizes are the ones laid out, so the veil's final grouping finds the group the search found. - The grouping places the legend when the corners left it out, and the "left out" warning looks at what was placed. - A one-colour layer is context only when it runs on past the frame; one inside it, such as a study area, is what the map shows. - The docs paragraph rewrapped. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 106 ++++++++++++++++++++++---------- crates/engine/src/tests.rs | 36 +++++++++++ crates/render/src/layout.rs | 44 ++++++++----- docs/user-guide/layouts.md | 20 +++--- 4 files changed, 152 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b37e81d7f8..7e9a647a6b 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -674,6 +674,23 @@ pub(crate) fn largest_free_cells(gw: usize, cells: &[bool], (c0, r0, c1, r1): (u best } +/// The part of a coverage grid of a page `wide` (mm) that a frame `size` (mm) with its top left at +/// `at` (mm, from the wide page's top left) covers, to the nearest cell, as a grid of its own; a +/// frame reaching past the wide page is held inside it. +pub(crate) fn crop_cells( + (gw, gh, cells): &(u32, u32, Vec), + wide: (f64, f64), + at: (f64, f64), + size: (f64, f64), +) -> (u32, u32, Vec) { + let (gw, gh) = ((*gw as usize).max(1), (*gh as usize).max(1)); + let (cell_w, cell_h) = (wide.0 / gw as f64, wide.1 / gh as f64); + let (w, h) = (((size.0 / cell_w).round() as usize).clamp(1, gw), ((size.1 / cell_h).round() as usize).clamp(1, gh)); + let (c0, r0) = (((at.0 / cell_w).round().max(0.0) as usize).min(gw - w), ((at.1 / cell_h).round().max(0.0) as usize).min(gh - h)); + let out = (r0..r0 + h).flat_map(|r| (c0..c0 + w).map(move |c| cells.get(r * gw + c).copied().unwrap_or(false))).collect(); + (w as u32, h as u32, out) +} + /// The surrounds of a veiled map grouped in a band of its veil: the locator with the north arrow at /// its right and the scale bar under them, beside the legend or over it, whichever the band's shape /// suits, centred in it. Gives the legend's, locator's, arrow's and scale bar's places; `None` when @@ -1909,12 +1926,43 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // `"veil": false` keeps the map unveiled, and so at its scale. let continuous = continuous && may_veil; let passes = [(1.0, false), (1.0, true), (1.25, true), (1.5, true), (2.0, true)]; + // Each scale's frame is drawn once, wide enough for every move, and each move's frame + // cut from it: a move is a translation on the page. So the search draws the map once per + // scale it tries (at most four times), not once per place. Its legend is measured at + // that scale, once, and those sizes are the ones laid out. + let mut drawn: Option<(f64, Option<(u32, u32, Vec)>, Option<[(f64, f64); MAX_LEGEND_COLUMNS]>)> = None; + let mut chosen = known; // A figure keeps its scale: its size is fixed, and a smaller scale costs it the most. for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; let mm = 1000.0 * flat.ground_per_unit(asked.center()) * s.map().body().ratio() / tried; let slack_x = ((fw - left - right - asked.width() * mm) / 2.0).max(0.0); let slack_y = ((fh - top - bottom - asked.height() * mm) / 2.0).max(0.0); + let wide = (fw + 2.0 * slack_x, fh + 2.0 * slack_y); + if drawn.as_ref().is_none_or(|d| d.0 != tried) { + // A smaller scale can draw more classes, and a streamed layer has its features + // read for the wider view. + let here = if tried == asked_scale { + Some(known) + } else { + let render_scale = crate::render::layout::frame_render_scale(s.map(), centred, tried); + let view = crate::render::View { + width: wide.0 * rustgis_map::layout::PT_PER_MM, + height: wide.1 * rustgis_map::layout::PT_PER_MM, + pixels_per_point: 1.0, + camera: rustgis_map::layout::frame_camera(s.map(), centred, tried, 0.0, 0.0), + sky: false, + }; + let lonlat = crate::render::view_lonlat(s.map(), &view); + s.map_mut().sync_sources(&lonlat, render_scale, true); + crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]) + }; + let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; + let whole_frame = crate::render::layout::frame_coverage(s.map_mut(), centred, tried, wide.0, wide.1, cells); + drawn = Some((tried, whole_frame, here)); + } + let Some((_, Some(whole_frame), Some(here))) = &drawn else { continue }; + let need = |room: (f64, f64)| here.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1); let mut found: Option<(usize, f64)> = None; for (dx, dy) in [(0.0, 0.0), (slack_x, 0.0), (-slack_x, 0.0), (0.0, slack_y), (0.0, -slack_y)] { // Centred with no veil at the asked scale is what has no room; a shift of nothing @@ -1926,7 +1974,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (cx, cy) = (at.x - dx / mm, at.y + dy / mm); let there = if still { Some(centred) } else { flat.inverse(Coord::new(cx, cy)) }; let Some(there) = there else { continue }; - let Some(mut moved) = crate::render::layout::frame_coverage(s.map_mut(), there, tried, fw, fh, 384) else { continue }; + // The frame moved east by `dx` and south by `dy` is the wide one's part that far + // west and north of its middle. + let mut moved = crop_cells(whole_frame, wide, (slack_x - dx, slack_y - dy), (fw, fh)); // The extent on the page: what is outside it is free once veiled. let clip = ( fx + fw / 2.0 + (asked.min_x - cx) * mm, @@ -1945,11 +1995,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let room = free_room(&moved); let Some(n) = need(room) else { continue }; // Under a veil the whole group has to fit, not the legend alone. - let Some(n) = (if veil { grouped(clip, n, &known).map(|(i, _)| i) } else { Some(n) }) else { continue }; + let Some(n) = (if veil { grouped(clip, n, here).map(|(i, _)| i) } else { Some(n) }) else { continue }; if found.is_none_or(|(fewest, most)| n < fewest || (n == fewest && room.0 * room.1 > most)) { found = Some((n, room.0 * room.1)); (center, scale, coverage, map_shift) = (there, tried, Some(moved), (dx, dy)); veiled = veil.then_some(clip); + chosen = *here; } } if found.is_some() { @@ -1958,24 +2009,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } if scale != asked_scale { warnings.push(format!("the map is drawn at 1:{scale:.0}, not 1:{asked_scale:.0}, to leave the legend room")); - // A wider view can draw more classes, and a streamed layer has its features read. - let render_scale = crate::render::layout::frame_render_scale(s.map(), center, scale); - let view = crate::render::View { - width: fw * rustgis_map::layout::PT_PER_MM, - height: fh * rustgis_map::layout::PT_PER_MM, - pixels_per_point: 1.0, - camera: rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0), - sky: false, - }; - let lonlat = crate::render::view_lonlat(s.map(), &view); - s.map_mut().sync_sources(&lonlat, render_scale, true); - sizes = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]); - if let Some(wider) = sizes { - (cw, ch) = wider[0]; - let (w, h) = whole(wider[0]); - if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Legend) { - (entry.1, entry.2) = (w.min(fw * 0.45), h.min(fh * 0.6)); - } + sizes = Some(chosen); + (cw, ch) = chosen[0]; + let (w, h) = whole(chosen[0]); + if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Legend) { + (entry.1, entry.2) = (w.min(fw * 0.45), h.min(fh * 0.6)); } } } @@ -2119,22 +2157,28 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } (cw, ch) = sizes[legend_cols - 1]; } - let (homes, (legend_at, mut spots, mut moved, _)) = best; + let (homes, (_, mut spots, mut moved, _)) = best; // A veiled map has its surrounds grouped in the widest band of the veil that takes them, in the - // fewest columns that do, rather than each in a corner of its own. + // fewest columns that do, rather than each in a corner of its own. The search found that group + // with these very sizes, so it is found again; the legend goes there too when the corners left + // it no room. let mut arrangement_used = arrangement_name(homes); if let (Some(clip), Some(known)) = (veiled, sizes) - && let Some((i, (legend_place, locator_place, arrow_place, scale_place))) = grouped(clip, legend_cols - 1, &known) + && let Some((i, (legend_place, locator_place, arrow_place, scale_place))) = grouped(clip, 0, &known) { legend_cols = i + 1; (cw, ch) = known[i]; - for (kind, r) in spots.iter_mut() { - *r = match kind { - Surround::Legend => legend_place, - Surround::Locator => locator_place.unwrap_or(*r), - Surround::Arrow => arrow_place, - Surround::Scale => scale_place, - }; + for (kind, place) in [ + (Surround::Legend, Some(legend_place)), + (Surround::Locator, locator_place), + (Surround::Arrow, Some(arrow_place)), + (Surround::Scale, Some(scale_place)), + ] { + let Some(place) = place.filter(|_| surrounds.iter().any(|x| x.0 == kind)) else { continue }; + match spots.iter_mut().find(|(k, _)| *k == kind) { + Some(spot) => spot.1 = place, + None => spots.push((kind, place)), + } } moved.clear(); arrangement_used = "veil"; @@ -2164,7 +2208,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } l.add("Extent Outline", (x0, y0, x1 - x0, y1 - y0), pub_card(Rgba::new(0, 0, 0, 0), Rgba::rgb(0x2B, 0x26, 0x20), 0.8, 0.0)); } - if surrounds.iter().any(|x| x.0 == Surround::Legend) && legend_at.is_none() { + if surrounds.iter().any(|x| x.0 == Surround::Legend) && !spots.iter().any(|(kind, _)| *kind == Surround::Legend) { 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\"" .into(), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ea5eaea120..4eeed310de 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7633,6 +7633,42 @@ fn a_publication_without_a_colorbar_sizes_the_legend_box_to_the_legend() { let _ = std::fs::remove_file(&path); } +/// A moved frame's coverage cut from one drawn wide enough for every move is the coverage of the +/// moved frame drawn on its own, give or take the cells along the edges of what it draws. +#[test] +fn a_moved_frames_coverage_is_cut_from_the_wide_one() { + use crate::cmd::layout::crop_cells; + use crate::render::layout::frame_coverage; + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_geom::Coord; + let mut map = rustgis_map::Map::new("m"); + let mut d = Dataset::new("shape", GeometryType::Polygon, Vec::new()); + // An L, so a cut from the wrong side or the wrong way up doesn't match. + let ring = [(-0.3, -0.3), (0.4, -0.3), (0.4, -0.1), (-0.1, -0.1), (-0.1, 0.35), (-0.3, 0.35), (-0.3, -0.3)]; + d.push(Some(Geometry::Polygon(vec![vec![ring.map(|(x, y)| Coord::new(x, y)).to_vec()]])), Vec::new()); + map.add_dataset(d); + let (scale, (fw, fh), (sx, sy)): (f64, (f64, f64), (f64, f64)) = (1_000_000.0, (60.0, 40.0), (20.0, 15.0)); + let wide = (fw + 2.0 * sx, fh + 2.0 * sy); + let centre = Coord::new(0.0, 0.0); + let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; + let whole = frame_coverage(&mut map, centre, scale, wide.0, wide.1, cells).unwrap(); + let flat = map.flat(); + let at = flat.forward_checked(centre).unwrap(); + let mm = 1000.0 * flat.ground_per_unit(at) * map.body().ratio() / scale; + for (dx, dy) in [(sx, 0.0), (-sx, 0.0), (0.0, sy), (0.0, -sy)] { + let cut = crop_cells(&whole, wide, (sx - dx, sy - dy), (fw, fh)); + let there = flat.inverse(Coord::new(at.x - dx / mm, at.y + dy / mm)).unwrap(); + let own = frame_coverage(&mut map, there, scale, fw, fh, 384).unwrap(); + assert_eq!((cut.0, cut.1), (own.0, own.1), "the same grid"); + let drawn = own.2.iter().filter(|c| **c).count(); + let differ = cut.2.iter().zip(&own.2).filter(|(a, b)| a != b).count(); + assert!(drawn > 100 && differ * 10 < drawn, "moved by {dx}, {dy}: {differ} of {drawn} cells differ"); + } + // A frame reaching past the wide page is held inside it. + let held = crop_cells(&whole, wide, (-50.0, 1e9), (fw, fh)); + assert_eq!(held.2.len(), (held.0 * held.1) as usize); +} + /// A veiled map's surrounds group in a band: beside each other in a wide one, one over the other in /// a tall one, nowhere when they don't fit. #[test] diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 85dfca182d..b58cb553e4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2023,8 +2023,10 @@ fn plain_fill(l: &rustgis_map::Layer) -> bool { /// 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, and those that -/// fill them in one colour ([`plain_fill`]) beside a layer drawn by classes or a raster. For keeping a -/// layout's surrounds off what its map shows. `None` when the frame can't be drawn. +/// fill them in one colour ([`plain_fill`]) beside a layer drawn by classes or a raster, when they +/// run on past the frame, as neighbouring states do: one inside it, such as a study area, is what +/// the map shows. 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, @@ -2035,7 +2037,7 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: return None; } let (w, h) = (w_mm * PT_PER_MM, h_mm * PT_PER_MM); - let ppp = f64::from(cells.clamp(8, 512)) / w.max(h); + let ppp = f64::from(cells.clamp(8, 1024)) / w.max(h); let view = View { width: w, height: h, pixels_per_point: ppp, camera: frame_camera(map, center, scale, 0.0, 0.0), sky: false }; // Put back when this ends, a panic in the drawing included. struct Aside<'a> { @@ -2065,7 +2067,16 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: } else { let classes = map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); - map.layers.iter().filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l)))).map(|l| l.id).collect() + let frame = crate::view_lonlat(map, &view); + let past_the_frame = |l: &rustgis_map::Layer| { + let e = l.shown_extent(); + !e.is_empty() && (e.min_x < frame.min_x || e.max_x > frame.max_x || e.min_y < frame.min_y || e.max_y > frame.max_y) + }; + map.layers + .iter() + .filter(|l| l.visible && (only_outlines(l) || (classes && plain_fill(l) && past_the_frame(l)))) + .map(|l| l.id) + .collect() }; for l in map.layers.iter_mut().filter(|l| outlines.contains(&l.id)) { l.visible = false; @@ -2793,8 +2804,8 @@ mod tests { assert!(!plain_fill(l), "labels make it more than context"); } - /// A polygon layer in one colour is context beside a layer drawn by classes, and what the map - /// shows when all its layers are in one colour. + /// A polygon layer in one colour running on past the frame is context beside a layer drawn by + /// classes; one inside the frame, such as a study area, is what the map shows. #[test] fn frame_coverage_leaves_out_one_colour_fills_beside_classes() { use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; @@ -2803,14 +2814,16 @@ mod tests { cells.iter().filter(|c| **c).count() }; let mut map = Map::new("m"); - let mut square = Dataset::new("states", 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 states = map.add_dataset(square); + let square = |name: &str, r: f64| { + let mut d = Dataset::new(name, GeometryType::Polygon, Vec::new()); + d.push( + Some(Geometry::Polygon(vec![vec![[(-r, -r), (r, -r), (r, r), (-r, r), (-r, -r)].map(|(x, y)| Coord::new(x, y)).to_vec()]])), + Vec::new(), + ); + d + }; + // About 0.9° across the frame: the states run on past it. + let states = map.add_dataset(square("states", 2.0)); let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); let far = map.add_dataset(d); @@ -2834,6 +2847,9 @@ mod tests { let beside_classes = count(&mut map); assert!(beside_classes > 0 && beside_classes < with_states, "{beside_classes} of {with_states}"); assert!(map.layer(states).is_some_and(|l| l.visible), "shown again"); + map.add_dataset(square("study area", 0.1)); + let with_study_area = count(&mut map); + assert!(with_study_area > beside_classes, "a one-colour layer inside the frame counts: {with_study_area} of {beside_classes}"); } /// 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 59f1a70c49..3ebe4516bf 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -63,15 +63,17 @@ 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, nor do polygon layers in one colour with no labels beside a layer drawn by - classes or a raster. When no shape of the legend fits, the map moves towards an edge, as far as - the asked extent stays in the frame, so the room on both its sides joins (the answer's - `mapShift`, in mm). On a map that runs on past the extent, with a long legend, what is outside - the extent is then veiled, with the surrounds grouped in its widest band (the answer's `veiled`, - and `arrangement` `"veil"`, and a warning), at up to half the scale on a sheet when the frame - leaves too little of it, which the result says too. The veil and the surrounds are ordinary - elements, to move or delete as any other; `"veil": false` leaves the map unveiled and at its - scale. If the legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by hand. + nothing else is shown, nor do polygon layers in one colour with no labels that run on past the + frame, such as neighbouring states, beside a layer drawn by classes or a raster. When no shape + of the legend fits, the map moves towards an edge, as far as the asked extent stays in the + frame, so the room on both its sides joins (the answer's `mapShift`, in mm). On a map that runs + on past the extent, with a long legend, what is outside the extent is then veiled, with the + surrounds grouped in its widest band (the answer's `veiled`, and `arrangement` `"veil"`, and a + warning), at up to half the scale on a sheet when the frame leaves too little of it, which the + result says too. The veil and the surrounds are ordinary elements, to move or delete as any + other; `"veil": false` leaves the map unveiled and at its scale. If the legend or colorbar + cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a + fixed-size legend to adjust by hand. - **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 7fd85a8f92fb6a432a315ae2bd08b2131c549e5a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 09:25:03 -0300 Subject: [PATCH 04/12] fix(layout): a map moved in its frame is said, and a scale whose legend is still loading isn't tried (#1379) Review round 2 of #1725: - A move aside changes what the frame shows past the extent; it was only in `mapShift`. A warning now gives its distance and side. - At a smaller scale, a read still running or a legend picture still loading left the legend measured short. That scale is now skipped and the result says so, as the asked scale already did. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 32 ++++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 20 ++++++++++++++------ docs/user-guide/layouts.md | 16 ++++++++-------- 3 files changed, 50 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 7e9a647a6b..d78da64169 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1932,6 +1932,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // that scale, once, and those sizes are the ones laid out. let mut drawn: Option<(f64, Option<(u32, u32, Vec)>, Option<[(f64, f64); MAX_LEGEND_COLUMNS]>)> = None; let mut chosen = known; + let mut unknown_at: Option = None; // A figure keeps its scale: its size is fixed, and a smaller scale costs it the most. for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; @@ -1941,7 +1942,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let wide = (fw + 2.0 * slack_x, fh + 2.0 * slack_y); if drawn.as_ref().is_none_or(|d| d.0 != tried) { // A smaller scale can draw more classes, and a streamed layer has its features - // read for the wider view. + // read for the wider view. While one is still reading there, or a legend picture + // still loading, the classes aren't known: that scale isn't tried, which is said. let here = if tried == asked_scale { Some(known) } else { @@ -1954,11 +1956,17 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { sky: false, }; let lonlat = crate::render::view_lonlat(s.map(), &view); - s.map_mut().sync_sources(&lonlat, render_scale, true); - crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]) + let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + if reading || crate::render::layout::tile_legends_pending(s.map(), render_scale, &[]) { + unknown_at.get_or_insert(tried); + None + } else { + crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]) + } }; let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; - let whole_frame = crate::render::layout::frame_coverage(s.map_mut(), centred, tried, wide.0, wide.1, cells); + let whole_frame = + here.and_then(|_| crate::render::layout::frame_coverage(s.map_mut(), centred, tried, wide.0, wide.1, cells)); drawn = Some((tried, whole_frame, here)); } let Some((_, Some(whole_frame), Some(here))) = &drawn else { continue }; @@ -2007,6 +2015,22 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { break; } } + if let Some(at_scale) = unknown_at { + warnings.push(format!( + "the map isn't tried at 1:{at_scale:.0} for the legend's room: a layer there is still reading, or a legend picture still loading" + )); + } + // A move changes what the frame shows past the extent, so it is said, as the veil and + // the scale are. + if map_shift != (0.0, 0.0) { + let (dx, dy) = map_shift; + let (by, way) = + if dx != 0.0 { (dx, if dx > 0.0 { "right" } else { "left" }) } else { (dy, if dy > 0.0 { "down" } else { "up" }) }; + warnings.push(format!( + "the map is moved {:.0} mm {way} in its frame (\"mapShift\"), the extent still whole, for the legend's room", + by.abs() + )); + } if scale != asked_scale { warnings.push(format!("the map is drawn at 1:{scale:.0}, not 1:{asked_scale:.0}, to leave the legend room")); sizes = Some(chosen); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4eeed310de..fb37058b90 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6687,9 +6687,12 @@ fn publication_layouts_fit_their_pages() { assert!(reference.contains("Web Mercator") && reference.contains("WGS 84") && reference.contains("2°"), "{reference}"); assert!(text("Author").unwrap().contains("{date}"), "the date stays a token the layout fills"); // Nothing said but, over the sample world's land, the surrounds sharing its one corner - // of sea (placement has its own test). + // of sea, or the map moved in its frame for the legend (placement has its own tests). let said: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); - assert!(said.len() <= 1 && said.iter().all(|w| w.contains("on what the map shows")), "{profile}: {r}"); + assert!( + said.len() <= 2 && said.iter().all(|w| w.contains("on what the map shows") || w.contains("in its frame")), + "{profile}: {r}" + ); } else { assert!(text("Title").is_none() && text("Sources").is_none(), "{profile}: a figure's texts are its caption's"); assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("caption")), "{r}"); @@ -7702,12 +7705,17 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { } let r = s.run("layout.publication", &json!({"profile": "a4-landscape", "extent": extent, "author": "", "locator": "none"})).unwrap(); - (r["legendColumns"].as_u64().unwrap(), r["mapShift"][0].as_f64().unwrap(), r["mapShift"][1].as_f64().unwrap(), r["moved"].clone()) + let said = + r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).find(|w| w.contains("in its frame")).map(String::from); + (r["legendColumns"].as_u64().unwrap(), r["mapShift"][0].as_f64().unwrap(), r["mapShift"][1].as_f64().unwrap(), said) }; - let (_, x, y, _) = laid(3, json!([-5, -5, 20, 15])); + let (_, x, y, said) = laid(3, json!([-5, -5, 20, 15])); assert_eq!((x, y), (0.0, 0.0), "a short legend has room"); - let (columns, x, y, _) = laid(30, json!([0, 0, 15, 10])); + assert_eq!(said, None, "a map left centred isn't said to move"); + let (columns, x, y, said) = laid(30, json!([0, 0, 15, 10])); assert!(x.abs() > 5.0 && y == 0.0, "moved sideways: {x}, {y}"); + let said = said.expect("a move is said"); + assert!(said.contains(&format!("{:.0} mm {}", x.abs(), if x > 0.0 { "right" } else { "left" })), "{said}"); assert_eq!(columns, 1, "one column beside the map"); // A map running on past the extent: what is outside it is veiled, at the asked scale while the // frame leaves a band of it wide enough, and at a smaller one otherwise. @@ -7718,7 +7726,7 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { } let p = json!({"profile": "a4-landscape", "extent": extent, "author": "", "locator": "none", "veil": veil}); let r = s.run("layout.publication", &p).unwrap(); - let smaller = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("to leave the legend room")); + let smaller = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("the map is drawn at 1:")); let veils = r["elements"].as_array().unwrap().iter().filter(|e| e["name"].as_str().unwrap().starts_with("Veil")).count(); assert_eq!(r["arrangement"] == "veil", r["veiled"].as_bool().unwrap(), "{r}"); let said = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("outside the extent is veiled")); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 3ebe4516bf..f28a6cfdb9 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -66,14 +66,14 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu nothing else is shown, nor do polygon layers in one colour with no labels that run on past the frame, such as neighbouring states, beside a layer drawn by classes or a raster. When no shape of the legend fits, the map moves towards an edge, as far as the asked extent stays in the - frame, so the room on both its sides joins (the answer's `mapShift`, in mm). On a map that runs - on past the extent, with a long legend, what is outside the extent is then veiled, with the - surrounds grouped in its widest band (the answer's `veiled`, and `arrangement` `"veil"`, and a - warning), at up to half the scale on a sheet when the frame leaves too little of it, which the - result says too. The veil and the surrounds are ordinary elements, to move or delete as any - other; `"veil": false` leaves the map unveiled and at its scale. If the legend or colorbar - cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a - fixed-size legend to adjust by hand. + frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, and a + warning). On a map that runs on past the extent, with a long legend, what is outside the extent + is then veiled, with the surrounds grouped in its widest band (the answer's `veiled`, and + `arrangement` `"veil"`, and a warning), at up to half the scale on a sheet when the frame leaves + too little of it, which the result says too. The veil and the surrounds are ordinary elements, + to move or delete as any other; `"veil": false` leaves the map unveiled and at its scale. If the + legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer + still loading gets a fixed-size legend to adjust by hand. - **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 5c7809671295c6bbb392e917540ff8c8f077dbd4 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 09:59:08 -0300 Subject: [PATCH 05/12] fix(layout): a move keeps the extent inside each side's own margin; publication says why it runs on the UI thread (#1379) Review round 3 of #1725: - A figure labels only its left and bottom edges, so its margins differ. The move limit used their mean, which put the extent's edge about 3 to 4.5 mm into the labels' room. Each direction now has its own limit; the wide drawing reaches the farther one. - `fn publication`'s doc comment says it runs on the UI thread with no Cancel, why, and that the search adds at most four drawings. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 19 ++++++++++++++++--- crates/engine/src/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index d78da64169..9fc88ebd24 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -963,6 +963,13 @@ fn landscape_suits(aspect: f64, short: f64, long: f64, style: Style) -> bool { /// round scale, with a graticule, legend, scale bar and north arrow; a sheet adds a frame, title, /// subtitle and a footer of two boxed columns (sources, cartographic reference) with a note and /// authorship under them, each text wrapped to its box with the layout's own font. +/// +/// It runs on the UI thread, with no Cancel, as on `main` before the veil: it adds a layout (and +/// may add a locator map) to the project the window shows, and its work is a bounded number of +/// coarse drawings of the map, not a loop over files or requests. Placing the surrounds draws the +/// frame once on a grid of 384 cells; when no shape of the legend fits, the search draws it at +/// most four times more, once per scale it tries (#1379; the whole command took about 0.7 s on a +/// 14 MB geology map). fn publication(s: &mut Session, p: &Value) -> CmdResult { let (auto, profile) = publication_profile(p)?; let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); @@ -1937,8 +1944,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; let mm = 1000.0 * flat.ground_per_unit(asked.center()) * s.map().body().ratio() / tried; - let slack_x = ((fw - left - right - asked.width() * mm) / 2.0).max(0.0); - let slack_y = ((fh - top - bottom - asked.height() * mm) / 2.0).max(0.0); + // How far the extent, centred, can go each way and stay inside that side's margin + // (a figure labels only its left and bottom edges, so they differ). + let (half_w, half_h) = (asked.width() * mm / 2.0, asked.height() * mm / 2.0); + let to = |margin: f64, half_frame: f64, half_extent: f64| (half_frame - margin - half_extent).max(0.0); + let (to_left, to_right) = (to(left, fw / 2.0, half_w), to(right, fw / 2.0, half_w)); + let (to_top, to_bottom) = (to(top, fh / 2.0, half_h), to(bottom, fh / 2.0, half_h)); + // The wide drawing is centred as the frame is, so it reaches the farther way on both. + let (slack_x, slack_y) = (to_left.max(to_right), to_top.max(to_bottom)); let wide = (fw + 2.0 * slack_x, fh + 2.0 * slack_y); if drawn.as_ref().is_none_or(|d| d.0 != tried) { // A smaller scale can draw more classes, and a streamed layer has its features @@ -1972,7 +1985,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let Some((_, Some(whole_frame), Some(here))) = &drawn else { continue }; let need = |room: (f64, f64)| here.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1); let mut found: Option<(usize, f64)> = None; - for (dx, dy) in [(0.0, 0.0), (slack_x, 0.0), (-slack_x, 0.0), (0.0, slack_y), (0.0, -slack_y)] { + for (dx, dy) in [(0.0, 0.0), (to_right, 0.0), (-to_left, 0.0), (0.0, to_bottom), (0.0, -to_top)] { // Centred with no veil at the asked scale is what has no room; a shift of nothing // is centred. let still = dx == 0.0 && dy == 0.0; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fb37058b90..bef3365cfc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7698,6 +7698,7 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { let json = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[0.0, 0.0], [15.0, 0.0], [15.0, 10.0], [0.0, 10.0], [0.0, 0.0]]]}}]}); std::fs::write(&path, json.to_string()).unwrap(); + let mut checked = 0; let laid = |layers: usize, extent: Value| { let mut s = Session::new(Project::default()); for _ in 0..layers { @@ -7746,6 +7747,29 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); let bad = s.run("layout.publication", &json!({"profile": "a4-landscape", "veil": "no"})).unwrap_err(); assert!(bad.contains("veil is true or false"), "{bad}"); + // A figure labels only its left and bottom edges, so its margins differ side to side: a move + // keeps the extent inside each side's own margin, off the graticule's labels, whatever the + // other side's. + for (profile, extent) in + [("figure-2col", json!([7, 4, 9, 6])), ("figure-2col", json!([6, 4, 9, 6])), ("thesis-half", json!([7, 4, 9, 6]))] + { + let mut s = Session::new(Project::default()); + for _ in 0..12 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let r = s.run("layout.publication", &json!({"profile": profile, "extent": extent, "author": ""})).unwrap(); + let l = s.project.layouts.last().unwrap(); + let el = |name: &str| l.elements.iter().find(|e| e.name == name).map(|e| (e.x, e.y, e.w, e.h)); + let (Some(frame), Some(outline)) = (el("Map Frame"), el("Extent Outline")) else { continue }; + let (left, bottom) = (2.0 + 9.0, 2.0 + 6.0); + assert!(outline.0 >= frame.0 + left - 0.5, "{profile} {extent}: {outline:?} in the left labels' room of {frame:?}: {r}"); + assert!( + outline.1 + outline.3 <= frame.1 + frame.3 - bottom + 0.5, + "{profile} {extent}: {outline:?} in the bottom labels' room: {r}" + ); + checked += 1; + } + assert!(checked > 0, "a figure is veiled"); let _ = std::fs::remove_dir_all(&dir); } From e57877024713442429b9830083cc26766a19fe86 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 10:58:30 -0300 Subject: [PATCH 06/12] fix(layout): the veil stops at the graticule's labels; one-colour context judged on the frame asked for (#1379) Review round 4 of #1725: - The veil ran to the frame's edges, over the graticule's labels drawn in the frame's picture, which came out washed at 60% white (reproduced in the PNG and a test). It now stops at the label-free area; the strips under the labels stay unveiled, which the warning and docs say. Bands thinner than half a millimetre are left out. - The search's wide drawing judged which one-colour layers run past the frame on itself; `frame_coverage_judged_on` judges them on the frame asked for, so every move's cut leaves out the same layers. - `fn publication`'s doc gives the actual reason it runs on the UI thread. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 39 ++++++++++++++----------- crates/engine/src/tests.rs | 9 ++++++ crates/render/src/layout.rs | 52 +++++++++++++++++++++++++++++++-- docs/user-guide/layouts.md | 13 +++++---- 4 files changed, 88 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 9fc88ebd24..c114afcda3 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -964,12 +964,12 @@ fn landscape_suits(aspect: f64, short: f64, long: f64, style: Style) -> bool { /// subtitle and a footer of two boxed columns (sources, cartographic reference) with a note and /// authorship under them, each text wrapped to its box with the layout's own font. /// -/// It runs on the UI thread, with no Cancel, as on `main` before the veil: it adds a layout (and -/// may add a locator map) to the project the window shows, and its work is a bounded number of -/// coarse drawings of the map, not a loop over files or requests. Placing the surrounds draws the -/// frame once on a grid of 384 cells; when no shape of the legend fits, the search draws it at -/// most four times more, once per scale it tries (#1379; the whole command took about 0.7 s on a -/// 14 MB geology map). +/// It runs on the UI thread, with no Cancel, as it did before the veil: none of the background +/// paths (tools, exports, commands that make a raster, models and scripts on a copy) takes a +/// command that adds a layout, and a locator map, to the project yet. Its cost grows with the +/// map's features: placing the surrounds draws the frame once on a grid of 384 cells, and when no +/// shape of the legend fits, the search draws it at most four times more, once per scale it tries +/// (#1379; the whole command took about 0.7 s on a 14 MB geology map, 0.2 s before the search). fn publication(s: &mut Session, p: &Value) -> CmdResult { let (auto, profile) = publication_profile(p)?; let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); @@ -1978,8 +1978,10 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } }; let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; - let whole_frame = - here.and_then(|_| crate::render::layout::frame_coverage(s.map_mut(), centred, tried, wide.0, wide.1, cells)); + // What is context is judged on the frame asked for, not the wide drawing, so + // every move's cut leaves out the same layers. + let whole_frame = here + .and_then(|_| crate::render::layout::frame_coverage_judged_on(s.map_mut(), centred, tried, wide, (fw, fh), cells)); drawn = Some((tried, whole_frame, here)); } let Some((_, Some(whole_frame), Some(here))) = &drawn else { continue }; @@ -2224,22 +2226,25 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { (*at, *drawn_at) = (center, scale); } // The veil over the frame and under its surrounds, in four bands around the extent, and the - // extent's outline: it covers what the map draws there, which is said. + // extent's outline: it covers what the map draws there, which is said. It stops at the + // graticule's labels, drawn in the frame's own picture under it, so they stay as dark as on an + // unveiled map; the map under them stays unveiled, which is said too. if let Some((x, y, w, h)) = veiled { warnings.push( - "what the map draws outside the extent is veiled, for the legend's room, and the surrounds sit there: \"veil\": false leaves it unveiled" + "what the map draws outside the extent is veiled, for the legend's room, but for the strips under the graticule's labels, and the surrounds sit there: \"veil\": false leaves it unveiled" .into(), ); - let (x0, y0) = (x.max(fx), y.max(fy)); - let (x1, y1) = ((x + w).min(fx + fw), (y + h).min(fy + fh)); + let (x0, y0) = (x.max(area.0), y.max(area.1)); + let (x1, y1) = ((x + w).min(area.2), (y + h).min(area.3)); let veil = || pub_card(Rgba::new(255, 255, 255, 150), Rgba::new(0, 0, 0, 0), 0.0, 0.0); for (name, band) in [ - ("Veil Above", (fx, fy, fw, y0 - fy)), - ("Veil Below", (fx, y1, fw, fy + fh - y1)), - ("Veil Left", (fx, y0, x0 - fx, y1 - y0)), - ("Veil Right", (x1, y0, fx + fw - x1, y1 - y0)), + ("Veil Above", (area.0, area.1, area.2 - area.0, y0 - area.1)), + ("Veil Below", (area.0, y1, area.2 - area.0, area.3 - y1)), + ("Veil Left", (area.0, y0, x0 - area.0, y1 - y0)), + ("Veil Right", (x1, y0, area.2 - x1, y1 - y0)), ] { - if band.2 > 0.0 && band.3 > 0.0 { + // A band thinner than half a millimetre (a rounding) is left out. + if band.2 > 0.5 && band.3 > 0.5 { l.add(name, band, veil()); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bef3365cfc..0ad2048d1f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7767,6 +7767,15 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { outline.1 + outline.3 <= frame.1 + frame.3 - bottom + 0.5, "{profile} {extent}: {outline:?} in the bottom labels' room: {r}" ); + // The veil stops at the graticule's labels, so they stay as dark as on an unveiled map. + for veil in l.elements.iter().filter(|e| e.name.starts_with("Veil")) { + assert!( + veil.x >= frame.0 + left - 1e-6 && veil.y + veil.h <= frame.1 + frame.3 - bottom + 1e-6, + "{profile}: {} over the labels: {:?} in {frame:?}", + veil.name, + (veil.x, veil.y, veil.w, veil.h) + ); + } checked += 1; } assert!(checked > 0, "a figure is veiled"); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index b58cb553e4..abada441fa 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2033,7 +2033,21 @@ fn plain_fill(l: &rustgis_map::Layer) -> bool { /// however it ends, as is a label lock waiting to be filled, which the coarse drawing would /// otherwise fill. pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: f64, cells: u32) -> Option<(u32, u32, Vec)> { - if !(w_mm > 0.0 && h_mm > 0.0) { + frame_coverage_judged_on(map, center, scale, (w_mm, h_mm), (w_mm, h_mm), cells) +} + +/// [`frame_coverage`] of a frame `size` (mm), with what runs on past the frame judged on a frame +/// `judged` (mm) with the same centre: a drawing wider than the frame asked for, cut for frames +/// moved inside it, leaves out the same one-colour layers as that frame does. +pub fn frame_coverage_judged_on( + map: &mut Map, + center: Coord, + scale: f64, + (w_mm, h_mm): (f64, f64), + judged: (f64, f64), + cells: u32, +) -> Option<(u32, u32, Vec)> { + if !(w_mm > 0.0 && h_mm > 0.0 && judged.0 > 0.0 && judged.1 > 0.0) { return None; } let (w, h) = (w_mm * PT_PER_MM, h_mm * PT_PER_MM); @@ -2067,7 +2081,8 @@ pub fn frame_coverage(map: &mut Map, center: Coord, scale: f64, w_mm: f64, h_mm: } else { let classes = map.layers.iter().any(|l| map.draws_at(l, at) && (l.is_raster() || !matches!(&l.renderer, rustgis_map::Renderer::Single(_)))); - let frame = crate::view_lonlat(map, &view); + let judged_view = View { width: judged.0 * PT_PER_MM, height: judged.1 * PT_PER_MM, ..view }; + let frame = crate::view_lonlat(map, &judged_view); let past_the_frame = |l: &rustgis_map::Layer| { let e = l.shown_extent(); !e.is_empty() && (e.min_x < frame.min_x || e.max_x > frame.max_x || e.min_y < frame.min_y || e.max_y > frame.max_y) @@ -2850,6 +2865,39 @@ mod tests { map.add_dataset(square("study area", 0.1)); let with_study_area = count(&mut map); assert!(with_study_area > beside_classes, "a one-colour layer inside the frame counts: {with_study_area} of {beside_classes}"); + + // A drawing three times the frame's width, judged on the frame: a layer running past the + // frame but not past the drawing is context in both, and one inside the frame is counted. + let mut map = Map::new("m"); + let neighbour = map.add_dataset(square("neighbour", 0.6)); + let far = { + let mut d = Dataset::new("far", GeometryType::Point, vec![Field::new("g", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(-0.3, -0.3))), vec![Value::Text("c".into())]); + map.add_dataset(d) + }; + if let Some(l) = map.layers.iter_mut().find(|l| l.id == far) { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("c".to_string(), s(0))], + other: s(1), + 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 drawn = |map: &mut Map, judged: (f64, f64)| { + let (.., cells) = frame_coverage_judged_on(map, Coord::new(0.0, 0.0), 1_000_000.0, (300.0, 300.0), judged, 192).unwrap(); + cells.iter().filter(|c| **c).count() + }; + let on_the_drawing = drawn(&mut map, (300.0, 300.0)); + let on_the_frame = drawn(&mut map, (100.0, 100.0)); + assert!(on_the_frame < on_the_drawing / 4, "the neighbour is context on the frame: {on_the_frame} of {on_the_drawing}"); + assert!(map.layer(neighbour).is_some_and(|l| l.visible), "shown again"); } /// 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 f28a6cfdb9..2f795e1061 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -68,12 +68,13 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu of the legend fits, the map moves towards an edge, as far as the asked extent stays in the frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, and a warning). On a map that runs on past the extent, with a long legend, what is outside the extent - is then veiled, with the surrounds grouped in its widest band (the answer's `veiled`, and - `arrangement` `"veil"`, and a warning), at up to half the scale on a sheet when the frame leaves - too little of it, which the result says too. The veil and the surrounds are ordinary elements, - to move or delete as any other; `"veil": false` leaves the map unveiled and at its scale. If the - legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer - still loading gets a fixed-size legend to adjust by hand. + is then veiled, but for the strips under the graticule's labels, with the surrounds grouped in + its widest band (the answer's `veiled`, and `arrangement` `"veil"`, and a warning), at up to + half the scale on a sheet when the frame leaves too little of it, which the result says too. The + veil and the surrounds are ordinary elements, to move or delete as any other; `"veil": false` + leaves the map unveiled and at its scale. If the legend or colorbar cannot fit, the result warns + about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by + hand. - **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 5371a1e0508466819693651cd781ab4472dfe4d4 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 14:09:36 -0300 Subject: [PATCH 07/12] fix(layout): "moved" names the surrounds in the veil's band; the search reads the wide view at the asked scale too (#1379) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A veiled map left "moved" empty although its surrounds left their corners for the veil's band; each one off its corner is named now. - At the asked scale the search drew the wide view from the frame's own read (half the frame past it, in degrees), which a stretched projection outgrows: in Web Mercator at 60°N a streamed point at 17°N inside the wide drawing wasn't read. Every scale tried reads its wide view first; one still reading isn't tried, and the warning says so. - Tests: the arrow kept inside the veil band and clear of the legend and locator; a veiled figure without its outline fails, an unveiled one has none, and both veiled figures are checked. - Docs: the move comes first, the veil only when no move makes room, and neither leaves the map centred and unveiled; the doc comment gives the cost with streamed layers. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 58 ++++++++++++++++++++------------- crates/engine/src/tests.rs | 48 +++++++++++++++++++++++++-- docs/user-guide/layouts.md | 18 +++++----- 3 files changed, 90 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index c114afcda3..df59927c71 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -968,8 +968,10 @@ fn landscape_suits(aspect: f64, short: f64, long: f64, style: Style) -> bool { /// paths (tools, exports, commands that make a raster, models and scripts on a copy) takes a /// command that adds a layout, and a locator map, to the project yet. Its cost grows with the /// map's features: placing the surrounds draws the frame once on a grid of 384 cells, and when no -/// shape of the legend fits, the search draws it at most four times more, once per scale it tries -/// (#1379; the whole command took about 0.7 s on a 14 MB geology map, 0.2 s before the search). +/// shape of the legend fits, the search draws it at most four times more, once per scale it tries, +/// each time on a view wider than the frame that a streamed layer is read for, waited for here +/// (#1379; the whole command took about 0.7 s on a 14 MB geology map, 0.2 s before the search, and +/// 0.9 s with its layers read in place). fn publication(s: &mut Session, p: &Value) -> CmdResult { let (auto, profile) = publication_profile(p)?; let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); @@ -1954,29 +1956,31 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (slack_x, slack_y) = (to_left.max(to_right), to_top.max(to_bottom)); let wide = (fw + 2.0 * slack_x, fh + 2.0 * slack_y); if drawn.as_ref().is_none_or(|d| d.0 != tried) { - // A smaller scale can draw more classes, and a streamed layer has its features - // read for the wider view. While one is still reading there, or a legend picture - // still loading, the classes aren't known: that scale isn't tried, which is said. - let here = if tried == asked_scale { - Some(known) - } else { - let render_scale = crate::render::layout::frame_render_scale(s.map(), centred, tried); - let view = crate::render::View { - width: wide.0 * rustgis_map::layout::PT_PER_MM, - height: wide.1 * rustgis_map::layout::PT_PER_MM, - pixels_per_point: 1.0, - camera: rustgis_map::layout::frame_camera(s.map(), centred, tried, 0.0, 0.0), - sky: false, - }; - let lonlat = crate::render::view_lonlat(s.map(), &view); - let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); - if reading || crate::render::layout::tile_legends_pending(s.map(), render_scale, &[]) { + // A streamed layer has its features read for the wide view, at the asked scale + // too (the frame's read reaches past the frame by half its size in degrees, + // which the wide view outgrows where the projection stretches, as Web Mercator + // does far from the equator), and a smaller scale can draw more classes. While + // one is still reading there, or a legend picture still loading, what the map + // draws there isn't known: that scale isn't tried, which is said. + let render_scale = crate::render::layout::frame_render_scale(s.map(), centred, tried); + let view = crate::render::View { + width: wide.0 * rustgis_map::layout::PT_PER_MM, + height: wide.1 * rustgis_map::layout::PT_PER_MM, + pixels_per_point: 1.0, + camera: rustgis_map::layout::frame_camera(s.map(), centred, tried, 0.0, 0.0), + sky: false, + }; + let lonlat = crate::render::view_lonlat(s.map(), &view); + let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + let here = + if reading || (tried != asked_scale && crate::render::layout::tile_legends_pending(s.map(), render_scale, &[])) { unknown_at.get_or_insert(tried); None + } else if tried == asked_scale { + Some(known) } else { crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]) - } - }; + }; let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; // What is context is judged on the frame asked for, not the wide drawing, so // every move's cut leaves out the same layers. @@ -2032,7 +2036,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } if let Some(at_scale) = unknown_at { warnings.push(format!( - "the map isn't tried at 1:{at_scale:.0} for the legend's room: a layer there is still reading, or a legend picture still loading" + "the map isn't moved or veiled at 1:{at_scale:.0} for the legend's room: a layer there is still reading, or a legend picture still loading" )); } // A move changes what the frame shows past the extent, so it is said, as the veil and @@ -2219,7 +2223,15 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { None => spots.push((kind, place)), } } - moved.clear(); + // "moved" names each surround off its corner, the group's places judged as any other. + moved = spots + .iter() + .filter(|(kind, r)| { + let home = at(homes[home_slot(*kind)], r.2, r.3); + (home.0 - r.0).abs() > 0.5 || (home.1 - r.1).abs() > 0.5 + }) + .map(|(kind, _)| named(*kind)) + .collect(); arrangement_used = "veil"; } if let Some(ElementKind::MapFrame { center: at, scale: drawn_at, .. }) = l.element_mut(frame).map(|e| &mut e.kind) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0ad2048d1f..3d2a5066da 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7672,6 +7672,34 @@ fn a_moved_frames_coverage_is_cut_from_the_wide_one() { assert_eq!(held.2.len(), (held.0 * held.1) as usize); } +/// The move search draws the map wider than its frame, at the asked scale too, and a streamed +/// layer is read for all of that: read for the frame alone (half as wide again on each side, in +/// degrees), it misses what a move shows past that, as in Web Mercator far from the equator. +#[test] +fn a_publication_reads_streamed_layers_for_the_move_searchs_wide_drawing() { + let dir = std::env::temp_dir().join(format!("rustgis-wide-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (fill, points) = (dir.join("fill.geojson"), dir.join("far.geojson")); + let square = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": + {"type": "Polygon", "coordinates": [[[-20.0, 10.0], [60.0, 10.0], [60.0, 85.0], [-20.0, 85.0], [-20.0, 10.0]]]}}]}); + std::fs::write(&fill, square.to_string()).unwrap(); + let point = |lat: f64| json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [20.0, lat]}}); + std::fs::write(&points, json!({"type": "FeatureCollection", "features": [point(60.0), point(17.0)]}).to_string()).unwrap(); + let mut s = Session::new(Project::default()); + for _ in 0..30 { + s.run("layer.addData", &json!({"path": fill.display().to_string()})).unwrap(); + } + s.run("layer.addData", &json!({"path": points.display().to_string(), "stream": true, "name": "Far"})).unwrap(); + let p = json!({"profile": "a4-portrait", "extent": [0, 58, 40, 62], "author": "", "locator": "none", "veil": false}); + let r = s.run("layout.publication", &p).unwrap(); + let far = s.map().layers.iter().find(|l| l.name == "Far").unwrap(); + // The frame (180 × 243.5 mm at 1:16,000,000) is read down to 20°N; the wide drawing, with the + // room to move the extent up, reaches about 13°N. + let held: Vec = far.dataset.features.iter().filter_map(|f| f.geometry.as_ref()).map(|g| g.extent().min_y).collect(); + assert!(held.contains(&17.0), "the point at 17°N, in the wide drawing, is read: {held:?} {r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A veiled map's surrounds group in a band: beside each other in a wide one, one over the other in /// a tall one, nowhere when they don't fit. #[test] @@ -7680,7 +7708,10 @@ fn a_veil_panel_groups_the_surrounds_by_the_bands_shape() { let (legend, arrow, scale) = ((80.0, 50.0), (8.0, 12.0), (60.0, 10.0)); let (l, locator, a, b) = veil_panel((0.0, 0.0, 160.0, 70.0), legend, Some(40.0), arrow, scale, 3.0).unwrap(); assert!(l.0 + l.2 <= locator.unwrap().0, "beside it: {l:?} {locator:?}"); - assert!(a.0 + a.2 <= l.0 + 160.0 && b.1 >= locator.unwrap().1 + 40.0, "{a:?} {b:?}"); + assert!(a.0 + a.2 <= 160.0 && b.1 >= locator.unwrap().1 + 40.0, "{a:?} {b:?}"); + let apart = + |p: (f64, f64, f64, f64), q: (f64, f64, f64, f64)| p.0 + p.2 <= q.0 || q.0 + q.2 <= p.0 || p.1 + p.3 <= q.1 || q.1 + q.3 <= p.1; + assert!(apart(a, l) && apart(a, (locator.unwrap().0, locator.unwrap().1, 40.0, 40.0)), "the arrow clear: {a:?} {l:?} {locator:?}"); let (l, locator, _, b) = veil_panel((0.0, 0.0, 90.0, 130.0), legend, Some(40.0), arrow, scale, 3.0).unwrap(); assert!(l.1 >= b.1 + b.3 && locator.unwrap().0 == b.0, "under it: {l:?} {b:?}"); assert!(veil_panel((0.0, 0.0, 60.0, 60.0), legend, Some(40.0), arrow, scale, 3.0).is_none()); @@ -7732,6 +7763,10 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { assert_eq!(r["arrangement"] == "veil", r["veiled"].as_bool().unwrap(), "{r}"); let said = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("outside the extent is veiled")); assert_eq!(said, r["veiled"].as_bool().unwrap(), "the veil is said, and only then: {r}"); + // The surrounds grouped in the veil's band left their corners, and "moved" names them. + if r["veiled"] == json!(true) { + assert!(!r["moved"].as_array().unwrap().is_empty(), "the grouped surrounds are named as moved: {r}"); + } (r["veiled"].as_bool().unwrap(), smaller, veils > 0, r["scale"].as_f64().unwrap()) }; let (veiled, smaller, veils, _) = on_past(json!([7, 4, 9, 6]), Value::Null); @@ -7760,7 +7795,14 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { let r = s.run("layout.publication", &json!({"profile": profile, "extent": extent, "author": ""})).unwrap(); let l = s.project.layouts.last().unwrap(); let el = |name: &str| l.elements.iter().find(|e| e.name == name).map(|e| (e.x, e.y, e.w, e.h)); - let (Some(frame), Some(outline)) = (el("Map Frame"), el("Extent Outline")) else { continue }; + // An unveiled map has no outline of its extent; a veiled one has both. + if r["veiled"] == json!(false) { + assert!(el("Extent Outline").is_none(), "{profile} {extent}: an outline with no veil: {r}"); + continue; + } + let (Some(frame), Some(outline)) = (el("Map Frame"), el("Extent Outline")) else { + panic!("{profile} {extent}: veiled, with no Map Frame or Extent Outline: {r}"); + }; let (left, bottom) = (2.0 + 9.0, 2.0 + 6.0); assert!(outline.0 >= frame.0 + left - 0.5, "{profile} {extent}: {outline:?} in the left labels' room of {frame:?}: {r}"); assert!( @@ -7778,7 +7820,7 @@ fn a_publication_map_moves_aside_for_a_legend_with_no_room() { } checked += 1; } - assert!(checked > 0, "a figure is veiled"); + assert_eq!(checked, 2, "both figures of the narrow extent are veiled"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 2f795e1061..cd44a5e018 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -65,14 +65,16 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu fill and no labels, such as neighbouring borders, don't count as what the map draws here, unless nothing else is shown, nor do polygon layers in one colour with no labels that run on past the frame, such as neighbouring states, beside a layer drawn by classes or a raster. When no shape - of the legend fits, the map moves towards an edge, as far as the asked extent stays in the - frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, and a - warning). On a map that runs on past the extent, with a long legend, what is outside the extent - is then veiled, but for the strips under the graticule's labels, with the surrounds grouped in - its widest band (the answer's `veiled`, and `arrangement` `"veil"`, and a warning), at up to - half the scale on a sheet when the frame leaves too little of it, which the result says too. The - veil and the surrounds are ordinary elements, to move or delete as any other; `"veil": false` - leaves the map unveiled and at its scale. If the legend or colorbar cannot fit, the result warns + of the legend fits, the map is first moved towards an edge, as far as the asked extent stays in + the frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, + and a warning). Only when no move makes room for it, a map that runs on past the extent, with a + long legend, is veiled: what is outside the extent, but for the strips under the graticule's + labels, with the surrounds grouped in the veil's widest band (the answer's `veiled`, + `arrangement` `"veil"` and `moved`, and a warning), at up to half the scale on a sheet when the + frame leaves too little of it, which the result says too. When neither makes room, the map stays + centred and unveiled, and the legend is laid out as above. The veil and the surrounds are + ordinary elements, to move or delete as any other; `"veil": false` leaves the map unveiled and + at its scale. If the legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by hand. - **Decimal comma**: `"decimal": ","` prints the graticule, scale bar and colorbar numbers and From 8bc10f86be7f45c30883e9e7ddd9c2e5f5128dbc Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 14:24:16 -0300 Subject: [PATCH 08/12] docs(layout): say when a map counts as continuous for the veil (#1379) At the asked scale, 80% of the extent's part of the frame and 30% of the rest drawn (context layers not counted), and a one-column legend taller than a quarter of the frame; a sparser map stays unveiled. Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/layouts.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index cd44a5e018..ec61bd8274 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -67,14 +67,16 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu frame, such as neighbouring states, beside a layer drawn by classes or a raster. When no shape of the legend fits, the map is first moved towards an edge, as far as the asked extent stays in the frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, - and a warning). Only when no move makes room for it, a map that runs on past the extent, with a - long legend, is veiled: what is outside the extent, but for the strips under the graticule's - labels, with the surrounds grouped in the veil's widest band (the answer's `veiled`, - `arrangement` `"veil"` and `moved`, and a warning), at up to half the scale on a sheet when the - frame leaves too little of it, which the result says too. When neither makes room, the map stays - centred and unveiled, and the legend is laid out as above. The veil and the surrounds are - ordinary elements, to move or delete as any other; `"veil": false` leaves the map unveiled and - at its scale. If the legend or colorbar cannot fit, the result warns + and a warning). Only when no move makes room for it, a continuous map with a long legend is + veiled: at the asked scale, at least 80% of the extent's part of the frame and 30% of the rest + are drawn (not counting the layers just named), and the legend in one column is taller than a + quarter of the frame; a sparser map stays unveiled. The veil covers what is outside the extent, + but for the strips under the graticule's labels, and the surrounds group in its widest band (the + answer's `veiled`, `arrangement` `"veil"` and `moved`, and a warning), at up to half the scale + on a sheet when the frame leaves too little of it, which the result says too. When neither makes + room, the map stays centred and unveiled, and the legend is laid out as above. The veil and the + surrounds are ordinary elements, to move or delete as any other; `"veil": false` leaves the map + unveiled and at its scale. If the legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by hand. - **Decimal comma**: `"decimal": ","` prints the graticule, scale bar and colorbar numbers and From 5612ff9a7802f07daa93276b489f227237d38f5e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 15:07:33 -0300 Subject: [PATCH 09/12] fix(layout): a moved frame places the extent at its own centre's ground scale (#1379) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A frame is drawn at its centre's ground scale, which a move up or down changes where the projection stretches. The search placed the extent with the asked centre's scale, so in Web Mercator at 57-61°N the veil's hole and outline sat 12 mm off the extent drawn, and at 23-19°S the extent ran past the frame's bottom edge, though said to stay whole. Each candidate now places the extent at the moved centre's scale; one that leaves it out of its margins there isn't made; and one whose scale would shift a corner of the frame more than half a millimetre has its coverage drawn on its own instead of cut from the wide drawing (so the Brazil Albers move is kept). Test: a map moved about 85 mm north and south of the equator draws the extent whole and under its outline. Docs: the veil follows the extent's bounding box in the map's projection, so a curved extent keeps the box's corners outside it unveiled. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 37 +++++++++++++---- crates/engine/src/tests.rs | 73 +++++++++++++++++++++++++++++++++ docs/user-guide/layouts.md | 27 ++++++------ 3 files changed, 116 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index df59927c71..b45aaf325f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -969,7 +969,8 @@ fn landscape_suits(aspect: f64, short: f64, long: f64, style: Style) -> bool { /// command that adds a layout, and a locator map, to the project yet. Its cost grows with the /// map's features: placing the surrounds draws the frame once on a grid of 384 cells, and when no /// shape of the legend fits, the search draws it at most four times more, once per scale it tries, -/// each time on a view wider than the frame that a streamed layer is read for, waited for here +/// each time on a view wider than the frame that a streamed layer is read for, waited for here, +/// and where the projection stretches, up to four moved frames per scale on their own /// (#1379; the whole command took about 0.7 s on a 14 MB geology map, 0.2 s before the search, and /// 0.9 s with its layers read in place). fn publication(s: &mut Session, p: &Value) -> CmdResult { @@ -2001,16 +2002,34 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (cx, cy) = (at.x - dx / mm, at.y + dy / mm); let there = if still { Some(centred) } else { flat.inverse(Coord::new(cx, cy)) }; let Some(there) = there else { continue }; - // The frame moved east by `dx` and south by `dy` is the wide one's part that far - // west and north of its middle. - let mut moved = crop_cells(whole_frame, wide, (slack_x - dx, slack_y - dy), (fw, fh)); - // The extent on the page: what is outside it is free once veiled. + // A frame is drawn at its own centre's ground scale, which a move changes where + // the projection stretches (Web Mercator's, with the latitude; a conic's, a + // little): the extent is placed on the page at the moved centre's scale, and a + // move that leaves it out of its margins there isn't made. The frame moved east + // by `dx` and south by `dy` is the wide one's part that far west and north of + // its middle while that scale moves a corner of it half a millimetre at most; + // past that, it is drawn on its own (what is context then judged on itself). + let here_mm = mm * flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(asked.center()); let clip = ( - fx + fw / 2.0 + (asked.min_x - cx) * mm, - fy + fh / 2.0 - (asked.max_y - cy) * mm, - asked.width() * mm, - asked.height() * mm, + fx + fw / 2.0 + (asked.min_x - cx) * here_mm, + fy + fh / 2.0 - (asked.max_y - cy) * here_mm, + asked.width() * here_mm, + asked.height() * here_mm, ); + let kept_whole = clip.0 >= fx + left - 0.5 + && clip.1 >= fy + top - 0.5 + && clip.0 + clip.2 <= fx + fw - right + 0.5 + && clip.1 + clip.3 <= fy + fh - bottom + 0.5; + if !still && !kept_whole { + continue; + } + let drift = (1.0 - flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(at)).abs() * fw.hypot(fh) / 2.0; + let mut moved = if drift <= 0.5 { + crop_cells(whole_frame, wide, (slack_x - dx, slack_y - dy), (fw, fh)) + } else { + let Some(own) = crate::render::layout::frame_coverage(s.map_mut(), there, tried, fw, fh, 384) else { continue }; + own + }; if veil { let (gw, gh) = (moved.0 as usize, moved.1 as usize); for (i, cell) in moved.2.iter_mut().enumerate() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3d2a5066da..f741616611 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7636,6 +7636,79 @@ fn a_publication_without_a_colorbar_sizes_the_legend_box_to_the_legend() { let _ = std::fs::remove_file(&path); } +/// A moved frame is drawn at its own centre's ground scale (Web Mercator's changes with the +/// latitude), so the extent drawn there is where the search placed it: whole in the frame, under +/// its outline, north and south of the equator. +#[test] +fn a_publication_map_moved_off_its_latitude_draws_the_extent_where_it_was_placed() { + use rustgis_geom::{Coord, Extent}; + let dir = std::env::temp_dir().join(format!("rustgis-move-latitude-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (name, fill, extent) in [ + ("north", [-30.0, 35.0, 70.0, 82.0], [10.0, 57.0, 30.0, 61.0]), + ("south", [-75.0, -40.0, -25.0, 5.0], [-52.0, -23.0, -40.0, -19.0]), + ] { + let path = dir.join(format!("{name}.geojson")); + let [w, s0, e, n] = fill; + let ring = json!([[[w, s0], [e, s0], [e, n], [w, n], [w, s0]]]); + let fc = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": ring}}]}); + std::fs::write(&path, fc.to_string()).unwrap(); + let mut s = Session::new(Project::default()); + for _ in 0..30 { + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + } + let r = s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "author": "", "locator": "none"})).unwrap(); + let l = s.project.layouts.last().unwrap(); + let frame = l.elements.iter().find(|e| e.name == "Map Frame").unwrap(); + let rustgis_map::layout::ElementKind::MapFrame { center, scale, .. } = &frame.kind else { + panic!("{name}: the Map Frame is no map frame") + }; + let pt = rustgis_map::layout::PT_PER_MM; + let cam = rustgis_map::layout::frame_camera(s.map(), *center, *scale, 0.0, 0.0); + // The extent's edges as the frame draws them, in mm on the page. + let asked = Extent::new(extent[0], extent[1], extent[2], extent[3]); + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for i in 0..=32 { + let t = f64::from(i) / 32.0; + let (x, y) = (asked.min_x + asked.width() * t, asked.min_y + asked.height() * t); + for c in [Coord::new(x, asked.min_y), Coord::new(x, asked.max_y), Coord::new(asked.min_x, y), Coord::new(asked.max_x, y)] { + let Some(m) = s.map().to_map(c) else { continue }; + let (sx, sy) = cam.to_screen(m, frame.w * pt, frame.h * pt); + (x0, y0, x1, y1) = (x0.min(sx / pt), y0.min(sy / pt), x1.max(sx / pt), y1.max(sy / pt)); + } + } + let drawn = (frame.x + x0, frame.y + y0, frame.x + x1, frame.y + y1); + assert!( + drawn.0 >= frame.x - 0.5 + && drawn.1 >= frame.y - 0.5 + && drawn.2 <= frame.x + frame.w + 0.5 + && drawn.3 <= frame.y + frame.h + 0.5, + "{name}: the extent drawn at {drawn:?} isn't whole in the frame ({}, {}, {}, {}): {r}", + frame.x, + frame.y, + frame.w, + frame.h + ); + // The outline follows the extent as drawn, but where the margins clip it. + if let Some(o) = l.elements.iter().find(|e| e.name == "Extent Outline") { + let margin = 15.0; + for (side, at, want, edge) in [ + ("left", o.x, drawn.0, frame.x), + ("top", o.y, drawn.1, frame.y), + ("right", o.x + o.w, drawn.2, frame.x + frame.w), + ("bottom", o.y + o.h, drawn.3, frame.y + frame.h), + ] { + assert!( + (at - want).abs() <= 0.5 || (at - edge).abs() <= margin, + "{name}: the outline's {side} at {at:.1}, the extent's at {want:.1}: {r}" + ); + } + } + eprintln!("{name}: shift {} veiled {} scale {}", r["mapShift"], r["veiled"], r["scale"]); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A moved frame's coverage cut from one drawn wide enough for every move is the coverage of the /// moved frame drawn on its own, give or take the cells along the edges of what it draws. #[test] diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index ec61bd8274..872fd2e52a 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -67,18 +67,21 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu frame, such as neighbouring states, beside a layer drawn by classes or a raster. When no shape of the legend fits, the map is first moved towards an edge, as far as the asked extent stays in the frame, so the room on both its sides joins (the answer's `mapShift`, in mm right and down, - and a warning). Only when no move makes room for it, a continuous map with a long legend is - veiled: at the asked scale, at least 80% of the extent's part of the frame and 30% of the rest - are drawn (not counting the layers just named), and the legend in one column is taller than a - quarter of the frame; a sparser map stays unveiled. The veil covers what is outside the extent, - but for the strips under the graticule's labels, and the surrounds group in its widest band (the - answer's `veiled`, `arrangement` `"veil"` and `moved`, and a warning), at up to half the scale - on a sheet when the frame leaves too little of it, which the result says too. When neither makes - room, the map stays centred and unveiled, and the legend is laid out as above. The veil and the - surrounds are ordinary elements, to move or delete as any other; `"veil": false` leaves the map - unveiled and at its scale. If the legend or colorbar cannot fit, the result warns - about clipping or resizing. A streamed layer still loading gets a fixed-size legend to adjust by - hand. + and a warning). Where the projection stretches, as Web Mercator does away from the equator, the + moved frame is drawn at its new centre's ground scale, and the extent has to stay whole at that + scale. Only when no move makes room for it, a continuous map with a long legend is veiled: at + the asked scale, at least 80% of the extent's part of the frame and 30% of the rest are drawn + (not counting the layers just named), and the legend in one column is taller than a quarter of + the frame; a sparser map stays unveiled. The veil covers what is outside the extent's bounding + box in the map's projection, but for the strips under the graticule's labels (so an extent whose + edges curve there, as in a conic or polar projection, keeps the box's corners outside it + unveiled), and the surrounds group in its widest band (the answer's `veiled`, `arrangement` + `"veil"` and `moved`, and a warning), at up to half the scale on a sheet when the frame leaves + too little of it, which the result says too. When neither makes room, the map stays centred and + unveiled, and the legend is laid out as above. The veil and the surrounds are ordinary elements, + to move or delete as any other; `"veil": false` leaves the map unveiled and at its scale. If the + legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer + still loading gets a fixed-size legend to adjust by hand. - **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 3ce8718b97043b77af2f3d239511efb91896fef9 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 15:33:09 -0300 Subject: [PATCH 10/12] test(layout): moved frames read every streamed feature they draw; docs: the legend box and rounded scales (#1379) - The latitude test adds a streamed column of points to both cases, which move over 80 mm and so have their coverage drawn on their own: every point the moved frame draws is read. Each case is asserted moved up or down by over 40 mm and veiled, and a missing outline fails it. - Docs: the height test takes the legend's box, its colorbar included; the smaller scale is about half at most, each one rounded up to two significant figures. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 35 ++++++++++++++++++++++++++++++++++- docs/user-guide/layouts.md | 23 ++++++++++++----------- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f741616611..64db96a4b8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7657,7 +7657,19 @@ fn a_publication_map_moved_off_its_latitude_draws_the_extent_where_it_was_placed for _ in 0..30 { s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); } + // A streamed column of points down the middle, every quarter degree. + let lon = (extent[0] + extent[2]) / 2.0; + let column: Vec = (0..).map(|i| s0 + 0.25 * f64::from(i)).take_while(|lat| *lat <= n).collect(); + let points = dir.join(format!("{name}_points.geojson")); + let features: Vec = column + .iter() + .map(|lat| json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [lon, lat]}})) + .collect(); + std::fs::write(&points, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + s.run("layer.addData", &json!({"path": points.display().to_string(), "stream": true, "name": "Column"})).unwrap(); let r = s.run("layout.publication", &json!({"profile": "a4-portrait", "extent": extent, "author": "", "locator": "none"})).unwrap(); + // Both move far up or down, off the asked centre's latitude, and are veiled. + assert!(r["mapShift"][1].as_f64().unwrap().abs() > 40.0 && r["veiled"] == json!(true), "{name}: moved up or down, veiled: {r}"); let l = s.project.layouts.last().unwrap(); let frame = l.elements.iter().find(|e| e.name == "Map Frame").unwrap(); let rustgis_map::layout::ElementKind::MapFrame { center, scale, .. } = &frame.kind else { @@ -7665,6 +7677,26 @@ fn a_publication_map_moved_off_its_latitude_draws_the_extent_where_it_was_placed }; let pt = rustgis_map::layout::PT_PER_MM; let cam = rustgis_map::layout::frame_camera(s.map(), *center, *scale, 0.0, 0.0); + // Every streamed point the frame draws was read before the search drew it. + let held: Vec = s + .map() + .layers + .iter() + .find(|l| l.name == "Column") + .unwrap() + .dataset + .features + .iter() + .filter_map(|f| f.geometry.as_ref()) + .map(|g| g.extent().min_y) + .collect(); + for lat in &column { + let Some(m) = s.map().to_map(Coord::new(lon, *lat)) else { continue }; + let (_, sy) = cam.to_screen(m, frame.w * pt, frame.h * pt); + if (0.0..=frame.h * pt).contains(&sy) { + assert!(held.contains(lat), "{name}: the point at {lat}°, {:.1} mm down the frame, isn't read: {held:?}", sy / pt); + } + } // The extent's edges as the frame draws them, in mm on the page. let asked = Extent::new(extent[0], extent[1], extent[2], extent[3]); let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); @@ -7690,7 +7722,8 @@ fn a_publication_map_moved_off_its_latitude_draws_the_extent_where_it_was_placed frame.h ); // The outline follows the extent as drawn, but where the margins clip it. - if let Some(o) = l.elements.iter().find(|e| e.name == "Extent Outline") { + { + let o = l.elements.iter().find(|e| e.name == "Extent Outline").unwrap_or_else(|| panic!("{name}: no Extent Outline: {r}")); let margin = 15.0; for (side, at, want, edge) in [ ("left", o.x, drawn.0, frame.x), diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 872fd2e52a..88e99e3b44 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -71,17 +71,18 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu moved frame is drawn at its new centre's ground scale, and the extent has to stay whole at that scale. Only when no move makes room for it, a continuous map with a long legend is veiled: at the asked scale, at least 80% of the extent's part of the frame and 30% of the rest are drawn - (not counting the layers just named), and the legend in one column is taller than a quarter of - the frame; a sparser map stays unveiled. The veil covers what is outside the extent's bounding - box in the map's projection, but for the strips under the graticule's labels (so an extent whose - edges curve there, as in a conic or polar projection, keeps the box's corners outside it - unveiled), and the surrounds group in its widest band (the answer's `veiled`, `arrangement` - `"veil"` and `moved`, and a warning), at up to half the scale on a sheet when the frame leaves - too little of it, which the result says too. When neither makes room, the map stays centred and - unveiled, and the legend is laid out as above. The veil and the surrounds are ordinary elements, - to move or delete as any other; `"veil": false` leaves the map unveiled and at its scale. If the - legend or colorbar cannot fit, the result warns about clipping or resizing. A streamed layer - still loading gets a fixed-size legend to adjust by hand. + (not counting the layers just named), and the legend's box in one column, its colorbar included, + is taller than a quarter of the frame; a sparser map stays unveiled. The veil covers what is + outside the extent's bounding box in the map's projection, but for the strips under the + graticule's labels (so an extent whose edges curve there, as in a conic or polar projection, + keeps the box's corners outside it unveiled), and the surrounds group in its widest band (the + answer's `veiled`, `arrangement` `"veil"` and `moved`, and a warning), at up to about half the + scale on a sheet (each scale tried is rounded up to two significant figures) when the frame + leaves too little of it, which the result says too. When neither makes room, the map stays + centred and unveiled, and the legend is laid out as above. The veil and the surrounds are + ordinary elements, to move or delete as any other; `"veil": false` leaves the map unveiled and + at its scale. If the legend or colorbar cannot fit, the result warns about clipping or resizing. + A streamed layer still loading gets a fixed-size legend to adjust by hand. - **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 412357674fa19d0c8fec42ea62bd35c5d752ddc2 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 15:56:24 -0300 Subject: [PATCH 11/12] perf(layout): a moved frame is drawn on its own only past a cell's drift, and once (#1379) Measured on the 14 MB Minas Gerais geology map in Web Mercator: two moves whose scale drift barely passed 0.5 mm cost about 0.47 s in A4 landscape, and the veil pass drew the portrait's move a second time. The threshold is now one cell of the coverage grid, which the cut is exact to anyway, and each moved frame drawn on its own is kept by scale and move. The Albers maps never take this branch. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b45aaf325f..eb6cf0de1e 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -970,7 +970,8 @@ fn landscape_suits(aspect: f64, short: f64, long: f64, style: Style) -> bool { /// map's features: placing the surrounds draws the frame once on a grid of 384 cells, and when no /// shape of the legend fits, the search draws it at most four times more, once per scale it tries, /// each time on a view wider than the frame that a streamed layer is read for, waited for here, -/// and where the projection stretches, up to four moved frames per scale on their own +/// and where the projection stretches, up to four moved frames per scale on their own (in Web +/// Mercator, the two moved up and down) /// (#1379; the whole command took about 0.7 s on a 14 MB geology map, 0.2 s before the search, and /// 0.9 s with its layers read in place). fn publication(s: &mut Session, p: &Value) -> CmdResult { @@ -1943,6 +1944,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let mut drawn: Option<(f64, Option<(u32, u32, Vec)>, Option<[(f64, f64); MAX_LEGEND_COLUMNS]>)> = None; let mut chosen = known; let mut unknown_at: Option = None; + // Moved frames drawn on their own (below), by scale and move: a pass with the veil + // tries the same moves as the one before it. + let mut own_drawn: Vec<((f64, f64, f64), (u32, u32, Vec))> = Vec::new(); // A figure keeps its scale: its size is fixed, and a smaller scale costs it the most. for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; @@ -2007,8 +2011,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // little): the extent is placed on the page at the moved centre's scale, and a // move that leaves it out of its margins there isn't made. The frame moved east // by `dx` and south by `dy` is the wide one's part that far west and north of - // its middle while that scale moves a corner of it half a millimetre at most; - // past that, it is drawn on its own (what is context then judged on itself). + // its middle while that scale moves a corner of it one cell of the coverage grid + // at most, which the cut is exact to anyway; past that, it is drawn on its own + // (what is context then judged on itself), once. let here_mm = mm * flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(asked.center()); let clip = ( fx + fw / 2.0 + (asked.min_x - cx) * here_mm, @@ -2024,10 +2029,13 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { continue; } let drift = (1.0 - flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(at)).abs() * fw.hypot(fh) / 2.0; - let mut moved = if drift <= 0.5 { + let mut moved = if drift <= fw.max(fh) / 384.0 { crop_cells(whole_frame, wide, (slack_x - dx, slack_y - dy), (fw, fh)) + } else if let Some((_, own)) = own_drawn.iter().find(|(key, _)| *key == (tried, dx, dy)) { + own.clone() } else { let Some(own) = crate::render::layout::frame_coverage(s.map_mut(), there, tried, fw, fh, 384) else { continue }; + own_drawn.push(((tried, dx, dy), own.clone())); own }; if veil { From 24d15283b00dc394f1b5cd2732e63c0d762677d4 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 16:56:08 -0300 Subject: [PATCH 12/12] fix(layout): a smaller scale whose legend can't be measured is said, not skipped silently (#1379) legend_sizes_mm reads a chunked source whole for its legend; when that fails at a smaller scale, the pass was dropped with no warning. Reproduced with a Shapefile drawn by classes, shown only below the asked scale, whose files are gone: the map stayed centred and unveiled with no warning. That scale now sets unknown_at, and the warning names a source that can't be read through. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 10 +++++-- crates/engine/src/tests.rs | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index eb6cf0de1e..3a60f6d3d8 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1984,7 +1984,13 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } else if tried == asked_scale { Some(known) } else { - crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]) + // A legend that can't be measured there (a source that can't be read + // through) leaves that scale untried too, which is said. + let measured = crate::render::layout::legend_sizes_mm(s.map_mut(), render_scale, false, false, &[]); + if measured.is_none() { + unknown_at.get_or_insert(tried); + } + measured }; let cells = (384.0 * wide.0.max(wide.1) / fw.max(fh)).round() as u32; // What is context is judged on the frame asked for, not the wide drawing, so @@ -2063,7 +2069,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } if let Some(at_scale) = unknown_at { warnings.push(format!( - "the map isn't moved or veiled at 1:{at_scale:.0} for the legend's room: a layer there is still reading, or a legend picture still loading" + "the map isn't moved or veiled at 1:{at_scale:.0} for the legend's room: a layer there is still reading, a legend picture still loading, or a layer's source can't be read through (exporting says why)" )); } // A move changes what the frame shows past the extent, so it is said, as the veil and diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 64db96a4b8..8442818ee8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7636,6 +7636,58 @@ fn a_publication_without_a_colorbar_sizes_the_legend_box_to_the_legend() { let _ = std::fs::remove_file(&path); } +/// A smaller scale whose legend can't be measured (a streamed layer shown only there, whose file is +/// gone) isn't tried, and the result says so. +#[test] +fn a_publication_says_a_smaller_scale_whose_legend_cant_be_measured() { + let dir = std::env::temp_dir().join(format!("rustgis-unmeasured-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (fill, gone) = (dir.join("fill.geojson"), dir.join("gone.shp")); + let square = |w: f64, s0: f64, e: f64, n: f64| { + json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"k": "a"}, "geometry": + {"type": "Polygon", "coordinates": [[[w, s0], [e, s0], [e, n], [w, n], [w, s0]]]}}]}) + }; + std::fs::write(&fill, square(0.0, 0.0, 15.0, 10.0).to_string()).unwrap(); + // A shapefile: its legend is read from the whole source, a chunk at a time. + { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + use rustgis_geom::Coord; + let mut d = Dataset::new("gone", GeometryType::Polygon, vec![Field::new("k", FieldType::Text)]); + let ring = [(1.0, 1.0), (14.0, 1.0), (14.0, 9.0), (1.0, 9.0), (1.0, 1.0)]; + d.push(Some(Geometry::Polygon(vec![vec![ring.map(|(x, y)| Coord::new(x, y)).to_vec()]])), vec![Value::Text("a".into())]); + rustgis_data::io::write_path(&d, &gone).unwrap(); + } + let mut s = Session::new(Project::default()); + for _ in 0..12 { + s.run("layer.addData", &json!({"path": fill.display().to_string()})).unwrap(); + } + let p = json!({"profile": "a4-landscape", "extent": [5, 4, 8.7, 6], "author": "", "locator": "none"}); + let asked = s + .run( + "layout.publication", + &json!({"profile": "a4-landscape", "extent": [5, 4, 8.7, 6], "author": "", "locator": "none", "veil": false}), + ) + .unwrap()["scale"] + .as_f64() + .unwrap(); + let id = s.run("layer.addData", &json!({"path": gone.display().to_string(), "stream": true, "name": "Gone"})).unwrap()["layer"] + .as_u64() + .unwrap(); + // Drawn by classes, which the legend reads the whole source for; shown only at scales smaller + // than the one asked for; then its files are gone. + s.run("layer.symbology", &json!({"layer": id, "type": "unique", "field": "k"})).unwrap(); + s.run("layer.scaleRange", &json!({"layer": id, "max": asked * 1.1})).unwrap(); + for ext in ["shp", "shx", "dbf"] { + let _ = std::fs::remove_file(gone.with_extension(ext)); + } + assert!(!gone.exists(), "the shapefile is gone"); + let r = s.run("layout.publication", &p).unwrap(); + let said = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).any(|w| w.contains("isn't moved or veiled at 1:")); + assert!(said, "the scale not tried is said: {r}"); + assert!(r["warnings"].to_string().contains("can't be read through"), "and why: {r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A moved frame is drawn at its own centre's ground scale (Web Mercator's changes with the /// latitude), so the extent drawn there is where the search placed it: whole in the frame, under /// its outline, north and south of the equator.