From 37273164ed64a33ccb4c6c196a64eb1548356e44 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 00:26:20 -0300 Subject: [PATCH 1/7] feat(layout): size a publication's scale bar box to its bar (#1379) The box was 30 % of the frame's width (25 mm at least), and the bar the renderer draws in it often took half of that. The box is now the narrowest that draws the same bar (length, unit, divisions), its last label and the numeric scale included; the bar's length rule doesn't change. It is measured again at each scale the veil tries. rustgis_render::layout::scale_bar_width_pt gives that width, sharing the bar's plan with the renderer. Part of #1379. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 50 +++++++++++++---- crates/engine/src/tests.rs | 11 ++++ crates/render/src/layout.rs | 99 +++++++++++++++++++++++++++------ docs/user-guide/layouts.md | 2 +- 4 files changed, 133 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 8db7a5bf89..b0c7893997 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1825,7 +1825,28 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { sizes = None; warnings.push("a WMS or WMTS layer's legend picture is still loading: the legend has a fixed size to fit by hand".into()); } - let (sw, sh, nh) = ((fw * 0.3).max(25.0), if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); + let (sh, nh) = (if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); + // The scale bar's box at a scale: the size of its bar and labels and of the scale under them, + // with the padding (#1379). The bar is the one a box 30 % of the frame's width (25 mm at least) + // draws: that rule picks its length and divisions, and the box is the narrowest that draws it + // the same, so at least the bar's length over the share of a box the renderer gives a bar. + let bar_kind = match ElementKind::scale_bar(frame) { + ElementKind::ScaleBar { units, divisions, .. } => Some((units, divisions)), + _ => None, + }; + let scale_box = |ground_per_pt: f64, scale: f64| { + let (widest, pt) = ((fw * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); + let bar_w = bar_kind + .and_then(|kind| crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt, kind, comma, 1.5 * pt)) + .map_or(widest, |w| w / pt); + let ratio = rustgis_map::graphics::scale_ratio(scale); + let ratio = if comma { ratio.replace(',', ".") } else { ratio }; + let text_w = crate::render::report::width_mm(&ratio, small_pt as f32, false) + 2.0; + (bar_w.max(text_w).min(widest), sh + nh) + }; + let ground_per_pt = |s: &Session, center: Coord, scale: f64| { + s.map().ground_res_at(&rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0)) + }; let pad = 2.0; // The surrounds to place: what each is and its size (the arrangement gives its corner). let mut surrounds: Vec<(Surround, f64, f64)> = Vec::new(); @@ -1846,6 +1867,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { if content_h > 0.0 && !legend_in_column { surrounds.push((Surround::Legend, (content_w + 2.0 * pad).min(fw * 0.45), (content_h + 2.0 * pad).min(fh * 0.6))); } + let (sw, _) = scale_box(ground_per_pt(s, center, scale), scale); surrounds.push((Surround::Scale, sw, sh + nh)); // A corner's rectangle for a surround `w` × `h`. let at = |corner: usize, w: f64, h: f64| { @@ -1899,12 +1921,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { 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)); + let (locator_side, arrow_size) = (size_of(Surround::Locator).map(|x| x.0), size_of(Surround::Arrow)); // 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?); + // their places; the scale bar's box `scale_bar` is the one at the scale tried. + let grouped = |clip: Rect, from: usize, known: &[(f64, f64); MAX_LEGEND_COLUMNS], scale_bar: (f64, f64)| { + let arrow = arrow_size?; (from..known.len()).find_map(|i| { bands_around(clip) .iter() @@ -1957,6 +1978,7 @@ 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 tried_bar = scale_box(ground_per_pt(s, centred, tried), tried); // 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); @@ -2062,7 +2084,7 @@ 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, here).map(|(i, _)| i) } else { Some(n) }) else { continue }; + let Some(n) = (if veil { grouped(clip, n, here, tried_bar).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)); @@ -2098,6 +2120,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { 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)); } + // The scale bar's box too: the bar a scale draws differs. + let bar_box = scale_box(ground_per_pt(s, center, scale), scale); + if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Scale) { + (entry.1, entry.2) = bar_box; + } } } } @@ -2247,7 +2274,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // 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, 0, &known) + && let Some((i, (legend_place, locator_place, arrow_place, scale_place))) = + grouped(clip, 0, &known, scale_box(ground_per_pt(s, center, scale), scale)) { legend_cols = i + 1; (cw, ch) = known[i]; @@ -2415,9 +2443,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } if let Some((sx, sy, w, h)) = spot_of(Surround::Scale) { placed.push(("scale bar", (sx, sy, w, h))); - l.add("Scale Box", (sx, sy, sw, sh + nh), surround_box(paper)); - l.add("Scale Bar", (sx, sy, sw, sh), ElementKind::scale_bar(frame)); - l.add("Scale", (sx, sy + sh, sw, nh), pub_text("{scale}".into(), small_pt, ink, false, TextAlign::Center)); + l.add("Scale Box", (sx, sy, w, sh + nh), surround_box(paper)); + l.add("Scale Bar", (sx, sy, w, sh), ElementKind::scale_bar(frame)); + l.add("Scale", (sx, sy + sh, w, nh), pub_text("{scale}".into(), small_pt, ink, false, TextAlign::Center)); } // What placing couldn't avoid: a surround over the map's drawing while a clearly freer corner // went to another (more surrounds than free corners), or two overlapping (a frame too small diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9e8af949e2..f86b27aa44 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6979,6 +6979,7 @@ fn publication_layouts_fit_their_pages() { std::fs::create_dir_all(&dir).unwrap(); let mut s = world(); let piaui = json!([-46.8, -11.6, -38.5, -2.2]); + let mut narrower = 0; let long = "NDVI: MOD13Q1 v6.1 (NASA LP DAAC), 16-day composites at 250 m, read through the Brazil Data Cube (INPE) and averaged to 1 km"; let profiles = [ @@ -7026,6 +7027,15 @@ fn publication_layouts_fit_their_pages() { let (a, b) = (named("Legend Box"), named("Scale Box")); let apart = a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y; assert!(apart, "{profile}: the legend reaches the scale bar"); + // The scale bar's box is the size of its bar (#1379): at most the 30 % of the frame (25 mm + // at least) it used to take, and its bar the length that width draws. + let bar = named("Scale Bar"); + let widest = (frame.w * 0.3).max(25.0); + let per_mm = scale * rustgis_map::layout::PAPER_M_PER_PT * rustgis_map::layout::PT_PER_MM; + let drawn = |w: f64| rustgis_geom::nice_distance(per_mm * w * 0.85); + assert!(b.w <= widest + 1e-9 && bar.w == b.w, "{profile}: a {} mm box for a {} mm bar, {widest} mm at most", b.w, bar.w); + assert_eq!(drawn(b.w), drawn(widest), "{profile}: the bar in a {} mm box", b.w); + narrower += usize::from(b.w < widest - 1.0); // A round scale, two significant figures, at which the extent still fits. let unit = 10f64.powf(scale.log10().floor() - 1.0); assert!(((scale / unit) - (scale / unit).round()).abs() < 1e-6, "{profile}: 1:{scale}"); @@ -7078,6 +7088,7 @@ fn publication_layouts_fit_their_pages() { assert!(std::fs::metadata(&png).unwrap().len() > 1000, "{profile}"); } assert_eq!(s.project.layouts.len(), profiles.len(), "a layout each, the earlier ones untouched"); + assert!(narrower > 0, "no profile's scale bar box is narrower than 30 % of its frame"); // A long title wraps within the frame, and pushes the map down; the result names every // element for layout.update. let r = s.run("layout.publication", &json!({"extent": piaui, "title": long})).unwrap(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index cf7b89660f..1e8409810e 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1448,6 +1448,54 @@ fn scale_number(v: f64, step: f64) -> String { if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } } +/// The share of its element's width a scale bar's length may take. +const BAR_SHARE: f64 = 0.85; +/// A scale bar's labels' size, and how far its bar starts in from the element's left edge (px). +const BAR_LABEL_PT: f32 = 8.0; +const BAR_INSET: f32 = 2.0; + +/// What a scale bar counts: its whole length in its unit, that unit in metres and its abbreviation. +#[derive(Clone, Copy, Debug, PartialEq)] +struct BarPlan { + total: f64, + unit_m: f64, + abbr: &'static str, +} + +/// The bar a scale bar draws in an element `width_pt` points wide at `ground_per_pt` ground metres +/// a point: the roundest length within [`BAR_SHARE`] of the width. `None` when it draws none. +fn bar_plan(ground_per_pt: f64, width_pt: f64, units: ScaleUnits) -> Option { + if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && width_pt.is_finite()) { + return None; + } + let room_m = ground_per_pt * width_pt * BAR_SHARE; + let (unit_m, abbr) = units.resolve(rustgis_geom::nice_distance(room_m)); + let total = rustgis_geom::nice_distance(room_m / unit_m); + (total > 0.0).then_some(BarPlan { total, unit_m, abbr }) +} + +/// A scale bar's label at division `i` of `divisions`, the last with the unit. +fn bar_label(total: f64, divisions: usize, i: usize, abbr: &str, comma: bool) -> String { + let v = decimal(scale_number(total * i as f64 / divisions as f64, total / divisions as f64), comma); + if i == divisions { format!("{v} {abbr}") } else { v } +} + +/// The narrowest element, in points, in which a scale bar draws the same bar as in one `width_pt` +/// wide (its length, unit and divisions), its last label and `pad_pt` after it included, so a box +/// can be the size of its bar (#1379). `width_pt` when no narrower one draws that bar; `None` when +/// it draws none. +pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, usize), comma: bool, pad_pt: f64) -> Option { + let (units, divisions) = bar; + let plan = bar_plan(ground_per_pt, width_pt, units)?; + let divisions = divisions.clamp(1, rustgis_map::layout::MAX_SCALE_DIVISIONS); + let len = plan.total * plan.unit_m / ground_per_pt; + let last = bar_label(plan.total, divisions, divisions, plan.abbr, comma); + let half = f64::from(text::measure(&last, BAR_LABEL_PT, false)) / 2.0; + // A hair over the share the bar takes, so a rounding doesn't pick the next shorter length. + let w = (len / BAR_SHARE * (1.0 + 1e-6)).max(f64::from(BAR_INSET) + len + half + pad_pt); + Some(if w < width_pt && bar_plan(ground_per_pt, w, units) == Some(plan) { w } else { width_pt }) +} + /// A scale bar filling most of the element's width, in `units`, with `divisions` labelled steps. /// `ground_per_pt` is ground metres per logical point of paper; `colors` are its lines, dark /// divisions and labels, then the alternating bar's light divisions. @@ -1462,19 +1510,11 @@ fn scale_bar( ) { let (units, divisions, style) = bar; let (dark, light) = colors; - if !(ground_per_pt.is_finite() && ground_per_pt > 0.0) { - return; - } let divisions = divisions.clamp(1, rustgis_map::layout::MAX_SCALE_DIVISIONS); - let room_m = ground_per_pt * r.width() as f64 / ppp * 0.85; - let (unit_m, abbr) = units.resolve(rustgis_geom::nice_distance(room_m)); - let total = rustgis_geom::nice_distance(room_m / unit_m); - if total <= 0.0 { - return; - } + let Some(BarPlan { total, unit_m, abbr }) = bar_plan(ground_per_pt, f64::from(r.width()) / ppp, units) else { return }; let len = (total * unit_m / ground_per_pt * ppp) as f32; let bar_h = (r.height() * 0.28).min(6.0 * ppp as f32); - let (x0, y0) = (r.x() + 2.0, r.y() + r.height() * 0.62 - bar_h / 2.0); + let (x0, y0) = (r.x() + BAR_INSET, r.y() + r.height() * 0.62 - bar_h / 2.0); let seg = len / divisions as f32; let line = Stroke { width: 0.6 * ppp as f32, ..Stroke::default() }; let stroke = |pm: &mut Canvas, pts: &[(f32, f32)], w: &Stroke| { @@ -1520,15 +1560,10 @@ fn scale_bar( } // Labels at the divisions, the last with the unit; one that would touch its neighbour is left // out (never the ends). - let px = 8.0 * 1.33 * ppp as f32; + let px = BAR_LABEL_PT * 1.33 * ppp as f32; let ty = y0 - px * 0.7; let gap = 3.0 * ppp as f32; - let labels: Vec<(f32, String)> = (0..=divisions) - .map(|i| { - let v = decimal(scale_number(total * i as f64 / divisions as f64, total / divisions as f64), comma); - (x0 + seg * i as f32, if i == divisions { format!("{v} {abbr}") } else { v }) - }) - .collect(); + let labels: Vec<(f32, String)> = (0..=divisions).map(|i| (x0 + seg * i as f32, bar_label(total, divisions, i, abbr, comma))).collect(); let half = |s: &str| text::measure(s, px / 1.33, false) / 2.0; let last = labels.last().map(|(x, s)| x - half(s)).unwrap_or(f32::MAX); let mut right = f32::MIN; @@ -4555,6 +4590,36 @@ Elaboração: RustGIS", } } + /// The narrowest element for a scale bar draws the very bar a wider one does, labels and all, + /// within itself (#1379). + #[test] + fn a_scale_bar_draws_the_same_in_its_narrowest_element() { + let draw = |ground: f64, width: f32| { + let mut pm = Pixmap::new(320, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, width, 60.0).unwrap(); + let colors = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); + crate::canvas::with_canvas(&mut pm, |c| { + scale_bar(c, r, ground, (ScaleUnits::Auto, 4, ScaleBarStyle::Alternating), colors, 1.0, true) + }); + pm + }; + // 20 km on a bar of 300 points takes two thirds of it; 10 km at 37.2 m a point, a third. + for (ground, narrower_than) in [(100.0, 260.0), (37.2, 190.0), (78.4, 300.0)] { + let w = scale_bar_width_pt(ground, 300.0, (ScaleUnits::Auto, 4), true, 4.0).unwrap(); + assert!(w < narrower_than, "{ground} m a point: {w} points"); + let (wide, narrow) = (draw(ground, 300.0), draw(ground, w as f32)); + assert_eq!(wide.data(), narrow.data(), "{ground} m a point: the same bar in {w} points"); + let past = + (w.ceil() as u32..320).flat_map(|x| (0..60).map(move |y| (x, y))).filter(|&(x, y)| narrow.pixel(x, y).is_some_and(ink)); + assert_eq!(past.count(), 0, "{ground} m a point: nothing drawn past {w} points"); + } + assert_eq!(scale_bar_width_pt(0.0, 300.0, (ScaleUnits::Auto, 4), false, 4.0), None); + // Miles count in other lengths: the box still draws the same bar. + let w = scale_bar_width_pt(100.0, 300.0, (ScaleUnits::Miles, 4), false, 4.0).unwrap(); + assert!(w <= 300.0 && bar_plan(100.0, w, ScaleUnits::Miles) == bar_plan(100.0, 300.0, ScaleUnits::Miles)); + } + #[test] fn scale_bars_draw_in_their_colours() { let mut pm = Pixmap::new(300, 60).unwrap(); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 0b0d62b08f..4d66cd1343 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -32,7 +32,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu take inside the frame. A graticule's step follows the extent (2° for a state, 15′ for a city), with labels on every edge of a sheet. The north arrow, the legend (sized to what it lists), the scale bar with the numeric scale - under it and the locator sit in the frame's corners, clear of the graticule's + under it (in a box the size of the bar) and the locator sit in the frame's corners, clear of the graticule's labels. The **arrangement** says which corner is each one's. `classic` (the default favourite) puts the locator at the top left, the arrow at the top right, the legend at the bottom left and the scale at the bottom right. `mirrored` swaps left and right, `legendRight` swaps the legend and From e900ca33d8f2ac0473fc242ec1cdd8e033ca0a35 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 01:53:17 -0300 Subject: [PATCH 2/7] fix(layout): measure the scale bar's box where the frame is drawn (#1379) Review round 1 on #1826: the box is measured again at the centre and scale the frame ends up drawn at, moved or not, and each veiled candidate checks its group with the box at its own centre. The numeric scale's width comes from scale_ratio_text, which {scale} uses too; the test compares the bar's unit and length; comment, names and docs tidied. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 31 ++++++++++++++++--------------- crates/engine/src/tests.rs | 7 ++++++- crates/render/src/layout.rs | 11 +++++++++-- docs/user-guide/layouts.md | 4 ++-- 4 files changed, 33 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b0c7893997..3c5ad0bfca 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1828,19 +1828,19 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let (sh, nh) = (if sheet { 8.0 * k } else { 6.0 }, pitch(small_pt) + 0.5); // The scale bar's box at a scale: the size of its bar and labels and of the scale under them, // with the padding (#1379). The bar is the one a box 30 % of the frame's width (25 mm at least) - // draws: that rule picks its length and divisions, and the box is the narrowest that draws it - // the same, so at least the bar's length over the share of a box the renderer gives a bar. + // would draw, which sets its length and divisions. The box is the narrowest that draws that same + // bar: the renderer gives a bar at most 85 % of its box, so the box is at least the bar's length + // over 0.85. let bar_kind = match ElementKind::scale_bar(frame) { ElementKind::ScaleBar { units, divisions, .. } => Some((units, divisions)), _ => None, }; let scale_box = |ground_per_pt: f64, scale: f64| { - let (widest, pt) = ((fw * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); + let (widest, pt_per_mm) = ((fw * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); let bar_w = bar_kind - .and_then(|kind| crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt, kind, comma, 1.5 * pt)) - .map_or(widest, |w| w / pt); - let ratio = rustgis_map::graphics::scale_ratio(scale); - let ratio = if comma { ratio.replace(',', ".") } else { ratio }; + .and_then(|kind| crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt_per_mm, kind, comma, 1.5 * pt_per_mm)) + .map_or(widest, |w| w / pt_per_mm); + let ratio = crate::render::layout::scale_ratio_text(scale, comma); let text_w = crate::render::report::width_mm(&ratio, small_pt as f32, false) + 2.0; (bar_w.max(text_w).min(widest), sh + nh) }; @@ -1978,7 +1978,6 @@ 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 tried_bar = scale_box(ground_per_pt(s, centred, tried), tried); // 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); @@ -2083,8 +2082,10 @@ 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, here, tried_bar).map(|(i, _)| i) } else { Some(n) }) else { continue }; + // Under a veil the whole group has to fit, not the legend alone, the scale bar's box + // as drawn there. + let bar_box = scale_box(ground_per_pt(s, there, tried), tried); + let Some(n) = (if veil { grouped(clip, n, here, bar_box).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)); @@ -2120,14 +2121,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { 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)); } - // The scale bar's box too: the bar a scale draws differs. - let bar_box = scale_box(ground_per_pt(s, center, scale), scale); - if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Scale) { - (entry.1, entry.2) = bar_box; - } } } } + // The scale bar's box as the frame is drawn, moved or at another scale or not. + let bar_box = scale_box(ground_per_pt(s, center, scale), scale); + if let Some(entry) = surrounds.iter_mut().find(|x| x.0 == Surround::Scale) { + (entry.1, entry.2) = bar_box; + } // 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)| { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f86b27aa44..96b823f13e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7031,8 +7031,13 @@ fn publication_layouts_fit_their_pages() { // at least) it used to take, and its bar the length that width draws. let bar = named("Scale Bar"); let widest = (frame.w * 0.3).max(25.0); + // The bar a box `w` wide draws, as the renderer picks it: its unit, then its length in it. let per_mm = scale * rustgis_map::layout::PAPER_M_PER_PT * rustgis_map::layout::PT_PER_MM; - let drawn = |w: f64| rustgis_geom::nice_distance(per_mm * w * 0.85); + let drawn = |w: f64| { + let room = per_mm * w * 0.85; + let (unit, abbr) = rustgis_map::layout::ScaleUnits::Auto.resolve(rustgis_geom::nice_distance(room)); + (rustgis_geom::nice_distance(room / unit), abbr) + }; assert!(b.w <= widest + 1e-9 && bar.w == b.w, "{profile}: a {} mm box for a {} mm bar, {widest} mm at most", b.w, bar.w); assert_eq!(drawn(b.w), drawn(widest), "{profile}: the bar in a {} mm box", b.w); narrower += usize::from(b.w < widest - 1.0); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 1e8409810e..6be70a5249 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -577,6 +577,12 @@ fn attribution_inset((w, h): (f32, f32), tw: f32, labels: &[(Edge, [f32; 4])]) - (bottom, right) } +/// A scale as `{scale}` prints it: `1:6,300,000`, or `1:6.300.000` with a decimal comma. +pub fn scale_ratio_text(scale: f64, comma: bool) -> String { + let ratio = rustgis_map::graphics::scale_ratio(scale); + if comma { decimal(ratio, true) } else { ratio } +} + /// Expands layout text tokens: the page ones here, the map ones from the first frame. pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, rustgis_map::Camera)>) -> String { // The frame's scale, worked out once for both its forms below. @@ -584,7 +590,7 @@ pub fn expand(t: &str, layout: &Layout, info: &PageInfo, frame: Option<(&Map, ru // A layout with a decimal comma prints its scale with points between thousands: put in first, // so a page or layout name holding "{scale}" isn't read as the token. let t = match scale { - Some(scale) if layout.decimal_comma => t.replace("{scale}", &decimal(rustgis_map::graphics::scale_ratio(scale), true)), + Some(scale) if layout.decimal_comma => t.replace("{scale}", &scale_ratio_text(scale, true)), _ => t.to_string(), }; let t = t @@ -1450,7 +1456,8 @@ fn scale_number(v: f64, step: f64) -> String { /// The share of its element's width a scale bar's length may take. const BAR_SHARE: f64 = 0.85; -/// A scale bar's labels' size, and how far its bar starts in from the element's left edge (px). +/// A scale bar's labels' size, and how far its bar starts in from the element's left edge, in +/// pixels: at most as many points at a pixel a point or more, which [`scale_bar_width_pt`] counts. const BAR_LABEL_PT: f32 = 8.0; const BAR_INSET: f32 = 2.0; diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 4d66cd1343..b52a21a614 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -32,8 +32,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu take inside the frame. A graticule's step follows the extent (2° for a state, 15′ for a city), with labels on every edge of a sheet. The north arrow, the legend (sized to what it lists), the scale bar with the numeric scale - under it (in a box the size of the bar) and the locator sit in the frame's corners, clear of the graticule's - labels. The **arrangement** says which corner is each one's. `classic` (the default favourite) puts the + under it (in a box the size of the bar) and the locator sit in the frame's corners, clear of + the graticule's labels. The **arrangement** says which corner is each one's. `classic` (the default favourite) puts the locator at the top left, the arrow at the top right, the legend at the bottom left and the scale at the bottom right. `mirrored` swaps left and right, `legendRight` swaps the legend and the scale, and `legendTop` swaps the legend and the locator. `"arrangement"` also takes a From c11b877d84e2711768fb9c636b694948f5028743 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 04:12:11 -0300 Subject: [PATCH 3/7] fix(layout): scale bar box: print-density margin, measured again on a frame's new scale (#1379) Reviews on #1826: the narrowed box keeps a ten-thousandth over the bar's threshold, so an export's f32 rectangle can't pick a shorter bar (tested near an A2 sheet's right edge at 300 and 600 dpi); and layout.update ("scale" or "w" of the frame) and layout.frameZoom measure a publication's scale bar box again, on the side of the frame it is nearer, so the last label and the written scale stay inside it. The width is one function, shared with layout.publication; the surround's first width is a placeholder, and each veiled candidate measures its box only under the veil. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 69 +++++++++++++++++++++++++++------ crates/engine/src/tests.rs | 13 +++++++ crates/render/src/layout.rs | 26 ++++++++++++- 3 files changed, 95 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 3c5ad0bfca..5718d1dd73 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1836,13 +1836,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; let scale_box = |ground_per_pt: f64, scale: f64| { - let (widest, pt_per_mm) = ((fw * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); - let bar_w = bar_kind - .and_then(|kind| crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt_per_mm, kind, comma, 1.5 * pt_per_mm)) - .map_or(widest, |w| w / pt_per_mm); - let ratio = crate::render::layout::scale_ratio_text(scale, comma); - let text_w = crate::render::report::width_mm(&ratio, small_pt as f32, false) + 2.0; - (bar_w.max(text_w).min(widest), sh + nh) + let w = bar_kind.map_or((fw * 0.3).max(25.0), |bar| scale_box_width(ground_per_pt, scale, fw, bar, comma, small_pt)); + (w, sh + nh) }; let ground_per_pt = |s: &Session, center: Coord, scale: f64| { s.map().ground_res_at(&rustgis_map::layout::frame_camera(s.map(), center, scale, 0.0, 0.0)) @@ -1867,8 +1862,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { if content_h > 0.0 && !legend_in_column { surrounds.push((Surround::Legend, (content_w + 2.0 * pad).min(fw * 0.45), (content_h + 2.0 * pad).min(fh * 0.6))); } - let (sw, _) = scale_box(ground_per_pt(s, center, scale), scale); - surrounds.push((Surround::Scale, sw, sh + nh)); + // Its width is set once the frame's centre and scale are settled, below; nothing reads it before. + surrounds.push((Surround::Scale, 0.0, sh + nh)); // A corner's rectangle for a surround `w` × `h`. let at = |corner: usize, w: f64, h: f64| { let x = if corner.is_multiple_of(2) { fx + left } else { fx + fw - right - w }; @@ -2084,8 +2079,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let Some(n) = need(room) else { continue }; // Under a veil the whole group has to fit, not the legend alone, the scale bar's box // as drawn there. - let bar_box = scale_box(ground_per_pt(s, there, tried), tried); - let Some(n) = (if veil { grouped(clip, n, here, bar_box).map(|(i, _)| i) } else { Some(n) }) else { continue }; + let in_group = |s: &Session| grouped(clip, n, here, scale_box(ground_per_pt(s, there, tried), tried)); + let Some(n) = (if veil { in_group(s).map(|(i, _)| i) } else { Some(n) }) else { continue }; if found.is_none_or(|(fewest, most)| n < fewest || (n == fewest && room.0 * room.1 > most)) { found = Some((n, room.0 * room.1)); (center, scale, coverage, map_shift) = (there, tried, Some(moved), (dx, dy)); @@ -3892,12 +3887,63 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { if let Some(text) = p.get("grid").and_then(|grid| grid.get("crs")).and_then(Value::as_str) { super::say_crs_note(s, text); } + // A frame drawn at another scale or width: a publication's scale bar box measured again. + let frame = s.project.layouts.get(li).and_then(|l| l.element(id)).map(|e| &e.kind); + if matches!(frame, Some(ElementKind::MapFrame { .. })) && ["scale", "w"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + refit_scale_box(s, li, id); + } if let Some(w) = font_told { return Ok(json!({"warning": w})); } Ok(Value::Null) } +/// The width (mm) of a publication's scale bar box (#1379), for a frame `frame_w` mm wide at +/// `scale` and `ground_per_pt` ground metres a point: the bar a box 30 % of the frame's width (25 +/// mm at least) would draw sets its length and divisions, and the box is the narrowest that draws +/// that same bar (at least its length over the 85 % of a box the renderer gives a bar), its last +/// label included, and holds the scale written under it in `text_pt`. +fn scale_box_width(ground_per_pt: f64, scale: f64, frame_w: f64, bar: (ScaleUnits, usize), comma: bool, text_pt: f64) -> f64 { + let (widest, pt_per_mm) = ((frame_w * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); + let bar_w = crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt_per_mm, bar, comma, 1.5 * pt_per_mm) + .map_or(widest, |w| w / pt_per_mm); + let ratio = crate::render::layout::scale_ratio_text(scale, comma); + let text_w = crate::render::report::width_mm(&ratio, text_pt as f32, false) + 2.0; + bar_w.max(text_w).min(widest) +} + +/// A publication's scale bar box measured again after its frame's scale or width changed (#1379): +/// the "Scale Box", the "Scale Bar" of `frame` and the "Scale" under it, as a publication lays them +/// out (one place, one width, none locked), take the width that bar and scale now need, kept on the +/// side of the frame they are nearer. A layout without them, or with them moved apart, is left as +/// it is. +fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { + let Some(l) = s.project.layouts.get(li) else { return }; + let Some(fr) = l.element(frame) else { return }; + let ElementKind::MapFrame { map, center, scale, .. } = &fr.kind else { return }; + let Some(m) = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)) else { return }; + let ground_per_pt = m.ground_res_at(&rustgis_map::layout::frame_camera(m, *center, *scale, 0.0, 0.0)); + let named = |name: &str| l.elements.iter().find(|e| e.name == name); + let (Some(boxed), Some(bar), Some(text)) = (named("Scale Box"), named("Scale Bar"), named("Scale")) else { return }; + let (ElementKind::ScaleBar { frame: of, units, divisions, .. }, ElementKind::Text { size, .. }) = (&bar.kind, &text.kind) else { + return; + }; + let together = [bar, text].iter().all(|e| (e.x - boxed.x).abs() < 1e-6 && (e.w - boxed.w).abs() < 1e-6 && !e.locked); + if *of != frame || !together || boxed.locked { + return; + } + let w = scale_box_width(ground_per_pt, *scale, fr.w, (*units, *divisions), l.decimal_comma, *size); + let x = if boxed.x + boxed.w / 2.0 > fr.x + fr.w / 2.0 { boxed.x + boxed.w - w } else { boxed.x }; + let ids = [boxed.id, bar.id, text.id]; + if let Some(l) = s.project.layouts.get_mut(li) { + for id in ids { + if let Some(e) = l.element_mut(id) { + (e.x, e.w) = (x, w); + } + } + } +} + /// Points a frame at an extent. fn set_frame(s: &mut Session, li: usize, frame: u32, e: &Extent) -> Result<(), String> { let l = s.project.layouts.get(li).ok_or("no layout")?; @@ -3953,6 +3999,7 @@ fn frame_zoom(s: &mut Session, p: &Value) -> CmdResult { } o => return Err(format!("unknown zoom '{o}'")), } + refit_scale_box(s, li, frame); Ok(json!({"element": frame})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 96b823f13e..57758eed2d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7094,6 +7094,19 @@ fn publication_layouts_fit_their_pages() { } assert_eq!(s.project.layouts.len(), profiles.len(), "a layout each, the earlier ones untouched"); assert!(narrower > 0, "no profile's scale bar box is narrower than 30 % of its frame"); + // The frame drawn at another scale: the box is measured again, its scale written in it and + // the box, bar and scale one width (#1379). + let li = s.project.layouts.len() - 1; + let frame = s.project.layouts[li].elements.iter().find(|e| e.kind.code() == "mapFrame").map(|e| e.id).unwrap(); + for scale in [40_000_000.0, 1_500_000.0] { + s.run("layout.update", &json!({"layout": li, "element": frame, "scale": scale})).unwrap(); + let l = &s.project.layouts[li]; + let named = |n: &str| l.elements.iter().find(|e| e.name == n).unwrap(); + let (b, bar, text) = (named("Scale Box"), named("Scale Bar"), named("Scale")); + let ElementKind::Text { size, .. } = &text.kind else { panic!() }; + let written = crate::render::report::width_mm(&rustgis_map::graphics::scale_ratio(scale), *size as f32, false); + assert!(written < b.w && bar.w == b.w && text.w == b.w && bar.x == b.x, "1:{scale}: {written} mm of text in a {} mm box", b.w); + } // A long title wraps within the frame, and pushes the map down; the result names every // element for layout.update. let r = s.run("layout.publication", &json!({"extent": piaui, "title": long})).unwrap(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 6be70a5249..fb107c26c8 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1498,8 +1498,10 @@ pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, u let len = plan.total * plan.unit_m / ground_per_pt; let last = bar_label(plan.total, divisions, divisions, plan.abbr, comma); let half = f64::from(text::measure(&last, BAR_LABEL_PT, false)) / 2.0; - // A hair over the share the bar takes, so a rounding doesn't pick the next shorter length. - let w = (len / BAR_SHARE * (1.0 + 1e-6)).max(f64::from(BAR_INSET) + len + half + pad_pt); + // A little over the share the bar takes, so the f32 rectangle an export rebuilds the width + // from (its error growing with the element's place on the page) doesn't pick the next shorter + // length: a ten-thousandth, 0.003 mm on a 30 mm box. + let w = (len / BAR_SHARE * (1.0 + 1e-4)).max(f64::from(BAR_INSET) + len + half + pad_pt); Some(if w < width_pt && bar_plan(ground_per_pt, w, units) == Some(plan) { w } else { width_pt }) } @@ -4599,6 +4601,26 @@ Elaboração: RustGIS", /// The narrowest element for a scale bar draws the very bar a wider one does, labels and all, /// within itself (#1379). + /// The narrowest element keeps its bar where an export rebuilds it from an f32 rectangle: near + /// an A2 sheet's right edge, at 300 and 600 dpi (#1379). + #[test] + fn a_scale_bar_keeps_its_bar_near_the_right_edge_at_print_density() { + let pt_per_mm = 72.0 / 25.4; + for i in 0..400 { + let ground = 10f64.powf(-1.0 + 4.0 * f64::from(i) / 400.0); + for widest_mm in [25.0, 63.0, 126.0] { + let w_pt = scale_bar_width_pt(ground, widest_mm * pt_per_mm, (ScaleUnits::Auto, 4), false, 4.0).unwrap(); + let plan = bar_plan(ground, w_pt, ScaleUnits::Auto); + for (x_mm, dpi) in [(380.0, 300.0), (560.0, 300.0), (380.0, 600.0), (560.0, 600.0)] { + let (k, ppp) = (dpi / 25.4, dpi / 72.0); + let r = Rect::from_xywh((x_mm * k) as f32, 0.0, (w_pt / pt_per_mm * k) as f32, 10.0).unwrap(); + let drawn = bar_plan(ground, f64::from(r.width()) / ppp, ScaleUnits::Auto); + assert_eq!(drawn, plan, "{ground} m a point, {widest_mm} mm at most, x {x_mm} mm, {dpi} dpi"); + } + } + } + } + #[test] fn a_scale_bar_draws_the_same_in_its_narrowest_element() { let draw = |ground: f64, width: f32| { From dec485f24b6f1609793ff1768dc1e2afc6ae620d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 07:04:20 -0300 Subject: [PATCH 4/7] fix(layout): scale box refit: its own text, kept off the other surrounds (#1379) Reviews on #1826 (claude-review and CodeRabbit's first): measured again after a frame's new scale, the scale bar box takes the width of the text actually under the bar, its {scale} filled and bold as drawn (spaced-out text or another font is left alone); a box that would then cover the legend, locator or north arrow stays as it was, which is said. The print-density test places boxes with the export's own point conversion, the test checks the stored text after each update, and the width's parameters name their units. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 53 ++++++++++++++++++++++++++------- crates/engine/src/tests.rs | 41 +++++++++++++++++++++---- crates/render/src/layout.rs | 6 ++-- 3 files changed, 81 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 5718d1dd73..fe2184590e 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1836,7 +1836,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; let scale_box = |ground_per_pt: f64, scale: f64| { - let w = bar_kind.map_or((fw * 0.3).max(25.0), |bar| scale_box_width(ground_per_pt, scale, fw, bar, comma, small_pt)); + let text = ("{scale}", small_pt, false); + let w = bar_kind.map_or((fw * 0.3).max(25.0), |bar| scale_box_width(ground_per_pt, scale, fw, bar, comma, text)); (w, sh + nh) }; let ground_per_pt = |s: &Session, center: Coord, scale: f64| { @@ -3902,21 +3903,28 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { /// `scale` and `ground_per_pt` ground metres a point: the bar a box 30 % of the frame's width (25 /// mm at least) would draw sets its length and divisions, and the box is the narrowest that draws /// that same bar (at least its length over the 85 % of a box the renderer gives a bar), its last -/// label included, and holds the scale written under it in `text_pt`. -fn scale_box_width(ground_per_pt: f64, scale: f64, frame_w: f64, bar: (ScaleUnits, usize), comma: bool, text_pt: f64) -> f64 { - let (widest, pt_per_mm) = ((frame_w * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); +/// label included, and holds the text written under it: `text` (its `{scale}` filled), in +/// `text_pt` points, bold or not. +fn scale_box_width(ground_per_pt: f64, scale: f64, frame_w_mm: f64, bar: (ScaleUnits, usize), comma: bool, text: (&str, f64, bool)) -> f64 { + let (text, text_pt, bold) = text; + let (widest, pt_per_mm) = ((frame_w_mm * 0.3).max(25.0), rustgis_map::layout::PT_PER_MM); let bar_w = crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt_per_mm, bar, comma, 1.5 * pt_per_mm) .map_or(widest, |w| w / pt_per_mm); - let ratio = crate::render::layout::scale_ratio_text(scale, comma); - let text_w = crate::render::report::width_mm(&ratio, text_pt as f32, false) + 2.0; + let written = text.replace("{scale}", &crate::render::layout::scale_ratio_text(scale, comma)); + let text_w = written.lines().map(|line| crate::render::report::width_mm(line, text_pt as f32, bold)).fold(0.0, f64::max) + 2.0; bar_w.max(text_w).min(widest) } +/// What a publication places over its map, which a scale bar box measured again must stay off. +const PLACED_OVER_MAP: [&str; 3] = ["Legend Box", "Locator", "North Arrow"]; + /// A publication's scale bar box measured again after its frame's scale or width changed (#1379): /// the "Scale Box", the "Scale Bar" of `frame` and the "Scale" under it, as a publication lays them -/// out (one place, one width, none locked), take the width that bar and scale now need, kept on the -/// side of the frame they are nearer. A layout without them, or with them moved apart, is left as -/// it is. +/// out (one place, one width, none locked), take the width that bar and the text under it (its +/// tokens filled, measured as drawn) now need, kept on the side of the frame they are nearer. A +/// layout without them, with them moved apart, or with that text spaced out or in another font +/// (which the width can't be measured for) is left as it is. A box that would then cover the +/// legend, locator or north arrow, which it didn't, stays as it was, which is said. fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { let Some(l) = s.project.layouts.get(li) else { return }; let Some(fr) = l.element(frame) else { return }; @@ -3925,15 +3933,38 @@ fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { let ground_per_pt = m.ground_res_at(&rustgis_map::layout::frame_camera(m, *center, *scale, 0.0, 0.0)); let named = |name: &str| l.elements.iter().find(|e| e.name == name); let (Some(boxed), Some(bar), Some(text)) = (named("Scale Box"), named("Scale Bar"), named("Scale")) else { return }; - let (ElementKind::ScaleBar { frame: of, units, divisions, .. }, ElementKind::Text { size, .. }) = (&bar.kind, &text.kind) else { + let ( + ElementKind::ScaleBar { frame: of, units, divisions, .. }, + ElementKind::Text { text: written, size, bold, letter_spacing, font, font_name, .. }, + ) = (&bar.kind, &text.kind) + else { return; }; + if *letter_spacing != 0.0 || *font != FontFamily::Sans || font_name.is_some() { + return; + } let together = [bar, text].iter().all(|e| (e.x - boxed.x).abs() < 1e-6 && (e.w - boxed.w).abs() < 1e-6 && !e.locked); if *of != frame || !together || boxed.locked { return; } - let w = scale_box_width(ground_per_pt, *scale, fr.w, (*units, *divisions), l.decimal_comma, *size); + let w = scale_box_width(ground_per_pt, *scale, fr.w, (*units, *divisions), l.decimal_comma, (written, *size, *bold)); let x = if boxed.x + boxed.w / 2.0 > fr.x + fr.w / 2.0 { boxed.x + boxed.w - w } else { boxed.x }; + let covers = |(x, w): (f64, f64), e: &rustgis_map::layout::Element| { + x < e.x + e.w && e.x < x + w && boxed.y < e.y + e.h && e.y < boxed.y + boxed.h + }; + let newly = l + .elements + .iter() + .filter(|e| PLACED_OVER_MAP.contains(&e.name.as_str()) && e.visible) + .find(|e| covers((x, w), e) && !covers((boxed.x, boxed.w), e)) + .map(|e| e.name.to_lowercase().replace(" box", "")); + if let Some(what) = newly { + s.notify( + format!("the scale bar's box would now cover the {what}, so it is left as it was: run layout.publication again to place them"), + false, + ); + return; + } let ids = [boxed.id, bar.id, text.id]; if let Some(l) = s.project.layouts.get_mut(li) { for id in ids { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 57758eed2d..6ff4d54b08 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6968,6 +6968,11 @@ fn layout_colorbars_follow_a_raster() { assert_eq!(s.project.layouts[0].element(id).map(|e| e.visible), Some(true), "undo brings it back"); } +/// The middle of a layout's frame, across. +fn frame_x_mid(s: &Session, li: usize, frame: u32) -> f64 { + s.project.layouts[li].element(frame).map(|e| e.x + e.w / 2.0).unwrap() +} + /// `layout.publication` (#682): every profile builds a layout that fits its page, the map frame /// at a round scale that still fits the extent, the footer boxed in two columns below the map /// with long lines wrapped, the tokens filled from the map; a figure leaves its title to the @@ -7098,15 +7103,39 @@ fn publication_layouts_fit_their_pages() { // the box, bar and scale one width (#1379). let li = s.project.layouts.len() - 1; let frame = s.project.layouts[li].elements.iter().find(|e| e.kind.code() == "mapFrame").map(|e| e.id).unwrap(); - for scale in [40_000_000.0, 1_500_000.0] { + // The scale written there is its `{scale}` token, filled from the frame as it is drawn; a text + // of one's own around it is measured too. + let id_of = |s: &Session, n: &str| s.project.layouts[li].elements.iter().find(|e| e.name == n).map(|e| e.id).unwrap(); + let scale_text = id_of(&s, "Scale"); + for (scale, text) in [(40_000_000.0, "{scale}"), (1_500_000.0, "{scale}"), (25_000_000.0, "Escala aproximada {scale}")] { + s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": text})).unwrap(); s.run("layout.update", &json!({"layout": li, "element": frame, "scale": scale})).unwrap(); let l = &s.project.layouts[li]; let named = |n: &str| l.elements.iter().find(|e| e.name == n).unwrap(); - let (b, bar, text) = (named("Scale Box"), named("Scale Bar"), named("Scale")); - let ElementKind::Text { size, .. } = &text.kind else { panic!() }; - let written = crate::render::report::width_mm(&rustgis_map::graphics::scale_ratio(scale), *size as f32, false); - assert!(written < b.w && bar.w == b.w && text.w == b.w && bar.x == b.x, "1:{scale}: {written} mm of text in a {} mm box", b.w); - } + let (b, bar, written) = (named("Scale Box"), named("Scale Bar"), named("Scale")); + let ElementKind::Text { text: stored, size, .. } = &written.kind else { panic!() }; + assert_eq!(stored, text); + let filled = stored.replace("{scale}", &crate::render::layout::scale_ratio_text(scale, l.decimal_comma)); + let Some(ElementKind::MapFrame { scale: drawn, .. }) = l.element(frame).map(|e| &e.kind) else { panic!() }; + assert_eq!(*drawn, scale); + let wide = crate::render::report::width_mm(&filled, *size as f32, false); + assert!(wide < b.w && bar.w == b.w && written.w == b.w && bar.x == b.x, "{filled}: {wide} mm of text in a {} mm box", b.w); + } + // A box that would now cover the north arrow stays as it was, which is said: from a narrow + // box, a long text makes it grow towards the arrow put beside it. + s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": "{scale}"})).unwrap(); + s.run("layout.update", &json!({"layout": li, "element": frame, "scale": 1_500_000.0})).unwrap(); + let (b, arrow) = (id_of(&s, "Scale Box"), id_of(&s, "North Arrow")); + let boxed = s.project.layouts[li].element(b).cloned().unwrap(); + // Beside it on the side it grows to: the left one when it keeps its right edge. + let x = if boxed.x + boxed.w / 2.0 > frame_x_mid(&s, li, frame) { boxed.x - 5.5 } else { boxed.x + boxed.w + 0.5 }; + s.run("layout.update", &json!({"layout": li, "element": arrow, "x": x, "y": boxed.y, "w": 5.0, "h": 5.0})).unwrap(); + s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": "Escala gráfica aproximada da folha {scale}"})).unwrap(); + let mark = s.notices.len(); + s.run("layout.update", &json!({"layout": li, "element": frame, "scale": 30_000_000.0})).unwrap(); + let after = s.project.layouts[li].element(b).cloned().unwrap(); + assert_eq!((after.x, after.w), (boxed.x, boxed.w), "the box stays"); + assert!(s.notices[mark..].iter().any(|n| n.text.contains("would now cover the north arrow")), "said"); // A long title wraps within the frame, and pushes the map down; the result names every // element for layout.update. let r = s.run("layout.publication", &json!({"extent": piaui, "title": long})).unwrap(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index fb107c26c8..ffe85bafd6 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -4605,14 +4605,16 @@ Elaboração: RustGIS", /// an A2 sheet's right edge, at 300 and 600 dpi (#1379). #[test] fn a_scale_bar_keeps_its_bar_near_the_right_edge_at_print_density() { - let pt_per_mm = 72.0 / 25.4; + // As an export places an element: page mm at `k` pixels a mm, `ppp` pixels a point. + let pt_per_mm = rustgis_map::layout::PT_PER_MM; for i in 0..400 { let ground = 10f64.powf(-1.0 + 4.0 * f64::from(i) / 400.0); for widest_mm in [25.0, 63.0, 126.0] { let w_pt = scale_bar_width_pt(ground, widest_mm * pt_per_mm, (ScaleUnits::Auto, 4), false, 4.0).unwrap(); let plan = bar_plan(ground, w_pt, ScaleUnits::Auto); for (x_mm, dpi) in [(380.0, 300.0), (560.0, 300.0), (380.0, 600.0), (560.0, 600.0)] { - let (k, ppp) = (dpi / 25.4, dpi / 72.0); + let k = dpi / 25.4; + let ppp = k / pt_per_mm; let r = Rect::from_xywh((x_mm * k) as f32, 0.0, (w_pt / pt_per_mm * k) as f32, 10.0).unwrap(); let drawn = bar_plan(ground, f64::from(r.width()) / ppp, ScaleUnits::Auto); assert_eq!(drawn, plan, "{ground} m a point, {widest_mm} mm at most, x {x_mm} mm, {dpi} dpi"); From 6fc049d9ea56835a6d77c5a79eaafbdd4fa7dd4a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 12:26:13 -0300 Subject: [PATCH 5/7] fix(layout): scale box refit fills the text's tokens; a warning that can be acted on (#1379) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviews on #1826: the text under the bar is measured with every token filled as the page draws it ({date}, {map}…), not {scale} alone; text naming a map series page isn't refitted. The overlap warning says what can be done: move or widen the box by hand, or make the layout again. A test's doc comment back above its own test. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 17 +++++++++++------ crates/engine/src/tests.rs | 13 +++++++++++-- crates/render/src/layout.rs | 4 ++-- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index fe2184590e..39c5f559d1 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3921,9 +3921,10 @@ const PLACED_OVER_MAP: [&str; 3] = ["Legend Box", "Locator", "North Arrow"]; /// A publication's scale bar box measured again after its frame's scale or width changed (#1379): /// the "Scale Box", the "Scale Bar" of `frame` and the "Scale" under it, as a publication lays them /// out (one place, one width, none locked), take the width that bar and the text under it (its -/// tokens filled, measured as drawn) now need, kept on the side of the frame they are nearer. A -/// layout without them, with them moved apart, or with that text spaced out or in another font -/// (which the width can't be measured for) is left as it is. A box that would then cover the +/// tokens filled as the page draws them, measured as drawn) now need, kept on the side of the +/// frame they are nearer. A layout without them, with them moved apart, with that text spaced out +/// or in another font, or naming a map series page (which differs from page to page) is left as +/// it is. A box that would then cover the /// legend, locator or north arrow, which it didn't, stays as it was, which is said. fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { let Some(l) = s.project.layouts.get(li) else { return }; @@ -3940,14 +3941,18 @@ fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { else { return; }; - if *letter_spacing != 0.0 || *font != FontFamily::Sans || font_name.is_some() { + if *letter_spacing != 0.0 || *font != FontFamily::Sans || font_name.is_some() || (l.series.is_some() && written.contains("{page")) { return; } + // Its tokens filled as the page draws them, `{scale}` from the frame. + let info = crate::render::layout::PageInfo { page: 1, pages: 1, page_name: String::new() }; + let cam = rustgis_map::layout::frame_camera(m, *center, *scale, 0.0, 0.0); + let filled = crate::render::layout::expand(written, l, &info, Some((m, cam))); let together = [bar, text].iter().all(|e| (e.x - boxed.x).abs() < 1e-6 && (e.w - boxed.w).abs() < 1e-6 && !e.locked); if *of != frame || !together || boxed.locked { return; } - let w = scale_box_width(ground_per_pt, *scale, fr.w, (*units, *divisions), l.decimal_comma, (written, *size, *bold)); + let w = scale_box_width(ground_per_pt, *scale, fr.w, (*units, *divisions), l.decimal_comma, (&filled, *size, *bold)); let x = if boxed.x + boxed.w / 2.0 > fr.x + fr.w / 2.0 { boxed.x + boxed.w - w } else { boxed.x }; let covers = |(x, w): (f64, f64), e: &rustgis_map::layout::Element| { x < e.x + e.w && e.x < x + w && boxed.y < e.y + e.h && e.y < boxed.y + boxed.h @@ -3960,7 +3965,7 @@ fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { .map(|e| e.name.to_lowercase().replace(" box", "")); if let Some(what) = newly { s.notify( - format!("the scale bar's box would now cover the {what}, so it is left as it was: run layout.publication again to place them"), + format!("the scale bar's box would now cover the {what}, so it is left as it was: move or widen it by hand, or make the layout again with layout.publication"), false, ); return; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6ff4d54b08..2d9163a70b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7107,7 +7107,12 @@ fn publication_layouts_fit_their_pages() { // of one's own around it is measured too. let id_of = |s: &Session, n: &str| s.project.layouts[li].elements.iter().find(|e| e.name == n).map(|e| e.id).unwrap(); let scale_text = id_of(&s, "Scale"); - for (scale, text) in [(40_000_000.0, "{scale}"), (1_500_000.0, "{scale}"), (25_000_000.0, "Escala aproximada {scale}")] { + for (scale, text) in [ + (40_000_000.0, "{scale}"), + (1_500_000.0, "{scale}"), + (25_000_000.0, "Escala aproximada {scale}"), + (2_500_000.0, "{scale} · {map} · {date}"), + ] { s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": text})).unwrap(); s.run("layout.update", &json!({"layout": li, "element": frame, "scale": scale})).unwrap(); let l = &s.project.layouts[li]; @@ -7115,7 +7120,11 @@ fn publication_layouts_fit_their_pages() { let (b, bar, written) = (named("Scale Box"), named("Scale Bar"), named("Scale")); let ElementKind::Text { text: stored, size, .. } = &written.kind else { panic!() }; assert_eq!(stored, text); - let filled = stored.replace("{scale}", &crate::render::layout::scale_ratio_text(scale, l.decimal_comma)); + let ElementKind::MapFrame { map, .. } = &l.element(frame).unwrap().kind else { panic!() }; + let filled = stored + .replace("{scale}", &crate::render::layout::scale_ratio_text(scale, l.decimal_comma)) + .replace("{map}", map) + .replace("{date}", "0000-00-00"); let Some(ElementKind::MapFrame { scale: drawn, .. }) = l.element(frame).map(|e| &e.kind) else { panic!() }; assert_eq!(*drawn, scale); let wide = crate::render::report::width_mm(&filled, *size as f32, false); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index ffe85bafd6..9d1181905c 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -4599,8 +4599,6 @@ Elaboração: RustGIS", } } - /// The narrowest element for a scale bar draws the very bar a wider one does, labels and all, - /// within itself (#1379). /// The narrowest element keeps its bar where an export rebuilds it from an f32 rectangle: near /// an A2 sheet's right edge, at 300 and 600 dpi (#1379). #[test] @@ -4623,6 +4621,8 @@ Elaboração: RustGIS", } } + /// The narrowest element for a scale bar draws the very bar a wider one does, labels and all, + /// within itself (#1379). #[test] fn a_scale_bar_draws_the_same_in_its_narrowest_element() { let draw = |ground: f64, width: f32| { From cceaa6461d738e9f60ece90e491a538dfd5c642a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 12:57:42 -0300 Subject: [PATCH 6/7] fix(layout): refit only the scale box of the frame the page fills its text from (#1379) Reviews on #1826: the page fills a text's map tokens from its first map frame, so a scale bar of another frame isn't measured again against a text drawn from a different map. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 39c5f559d1..be90bcc4de 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3923,8 +3923,8 @@ const PLACED_OVER_MAP: [&str; 3] = ["Legend Box", "Locator", "North Arrow"]; /// out (one place, one width, none locked), take the width that bar and the text under it (its /// tokens filled as the page draws them, measured as drawn) now need, kept on the side of the /// frame they are nearer. A layout without them, with them moved apart, with that text spaced out -/// or in another font, or naming a map series page (which differs from page to page) is left as -/// it is. A box that would then cover the +/// or in another font, naming a map series page (which differs from page to page), or of a frame +/// other than the first (whose map the page fills the text from) is left as it is. A box that would then cover the /// legend, locator or north arrow, which it didn't, stays as it was, which is said. fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { let Some(l) = s.project.layouts.get(li) else { return }; @@ -3941,7 +3941,12 @@ fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { else { return; }; - if *letter_spacing != 0.0 || *font != FontFamily::Sans || font_name.is_some() || (l.series.is_some() && written.contains("{page")) { + if *letter_spacing != 0.0 + || *font != FontFamily::Sans + || font_name.is_some() + || (l.series.is_some() && written.contains("{page")) + || l.first_frame() != Some(frame) + { return; } // Its tokens filled as the page draws them, `{scale}` from the frame. From 76405b7126b4566100aba72723d9178c498f9fb7 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 13:21:32 -0300 Subject: [PATCH 7/7] fix(layout): keep a scale box widened by hand for a long text (#1379) Review on #1826: a frame's new scale wrote a box widened by hand for a text longer than the widest box a publication gives back to that width, clipping the text. Such a box now keeps its width. The refit's doc says a change to the text or bar alone doesn't measure the box again. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 20 ++++++++++++++++---- crates/engine/src/tests.rs | 11 ++++++++++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index be90bcc4de..72e5c19605 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3911,8 +3911,13 @@ fn scale_box_width(ground_per_pt: f64, scale: f64, frame_w_mm: f64, bar: (ScaleU let bar_w = crate::render::layout::scale_bar_width_pt(ground_per_pt, widest * pt_per_mm, bar, comma, 1.5 * pt_per_mm) .map_or(widest, |w| w / pt_per_mm); let written = text.replace("{scale}", &crate::render::layout::scale_ratio_text(scale, comma)); - let text_w = written.lines().map(|line| crate::render::report::width_mm(line, text_pt as f32, bold)).fold(0.0, f64::max) + 2.0; - bar_w.max(text_w).min(widest) + bar_w.max(scale_text_mm(&written, text_pt, bold)).min(widest) +} + +/// The width (mm) a scale bar box gives the text under its bar, its tokens filled: its longest +/// line in `text_pt` points, bold or not, and a millimetre each side. +fn scale_text_mm(text: &str, text_pt: f64, bold: bool) -> f64 { + text.lines().map(|line| crate::render::report::width_mm(line, text_pt as f32, bold)).fold(0.0, f64::max) + 2.0 } /// What a publication places over its map, which a scale bar box measured again must stay off. @@ -3924,8 +3929,11 @@ const PLACED_OVER_MAP: [&str; 3] = ["Legend Box", "Locator", "North Arrow"]; /// tokens filled as the page draws them, measured as drawn) now need, kept on the side of the /// frame they are nearer. A layout without them, with them moved apart, with that text spaced out /// or in another font, naming a map series page (which differs from page to page), or of a frame -/// other than the first (whose map the page fills the text from) is left as it is. A box that would then cover the -/// legend, locator or north arrow, which it didn't, stays as it was, which is said. +/// other than the first (whose map the page fills the text from) is left as it is; so is a text +/// longer than the widest box a publication gives (a box widened by hand for it keeps its width). +/// A change to the text or the bar alone doesn't measure the box again; the next change of the +/// frame's scale or width does. A box that would then cover the legend, locator or north arrow, +/// which it didn't, stays as it was, which is said. fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { let Some(l) = s.project.layouts.get(li) else { return }; let Some(fr) = l.element(frame) else { return }; @@ -3957,6 +3965,10 @@ fn refit_scale_box(s: &mut Session, li: usize, frame: u32) { if *of != frame || !together || boxed.locked { return; } + // A text longer than the widest box a publication gives: a width set by hand for it is kept. + if scale_text_mm(&filled, *size, *bold) > (fr.w * 0.3).max(25.0) { + return; + } let w = scale_box_width(ground_per_pt, *scale, fr.w, (*units, *divisions), l.decimal_comma, (&filled, *size, *bold)); let x = if boxed.x + boxed.w / 2.0 > fr.x + fr.w / 2.0 { boxed.x + boxed.w - w } else { boxed.x }; let covers = |(x, w): (f64, f64), e: &rustgis_map::layout::Element| { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2d9163a70b..7c8af968a7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7139,12 +7139,21 @@ fn publication_layouts_fit_their_pages() { // Beside it on the side it grows to: the left one when it keeps its right edge. let x = if boxed.x + boxed.w / 2.0 > frame_x_mid(&s, li, frame) { boxed.x - 5.5 } else { boxed.x + boxed.w + 0.5 }; s.run("layout.update", &json!({"layout": li, "element": arrow, "x": x, "y": boxed.y, "w": 5.0, "h": 5.0})).unwrap(); - s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": "Escala gráfica aproximada da folha {scale}"})).unwrap(); + s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": "Escala aproximada da folha {scale}"})).unwrap(); let mark = s.notices.len(); s.run("layout.update", &json!({"layout": li, "element": frame, "scale": 30_000_000.0})).unwrap(); let after = s.project.layouts[li].element(b).cloned().unwrap(); assert_eq!((after.x, after.w), (boxed.x, boxed.w), "the box stays"); assert!(s.notices[mark..].iter().any(|n| n.text.contains("would now cover the north arrow")), "said"); + // A text longer than the widest box, its box widened by hand for it: the width is kept. + s.run("layout.update", &json!({"layout": li, "element": arrow, "x": 0.0, "y": 0.0})).unwrap(); + let long = "Escala aproximada da folha impressa em papel de formato A4 {scale}"; + s.run("layout.update", &json!({"layout": li, "element": scale_text, "text": long})).unwrap(); + for name in ["Scale Box", "Scale Bar", "Scale"] { + s.run("layout.update", &json!({"layout": li, "element": id_of(&s, name), "w": 120.0})).unwrap(); + } + s.run("layout.update", &json!({"layout": li, "element": frame, "scale": 12_000_000.0})).unwrap(); + assert_eq!(s.project.layouts[li].element(b).map(|e| e.w), Some(120.0), "the width set by hand"); // A long title wraps within the frame, and pushes the map down; the result names every // element for layout.update. let r = s.run("layout.publication", &json!({"extent": piaui, "title": long})).unwrap();