diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 8db7a5bf89..72e5c19605 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1825,7 +1825,24 @@ 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) + // 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 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| { + 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,7 +1863,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))); } - 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 }; @@ -1899,12 +1917,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() @@ -2061,8 +2078,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).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 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)); @@ -2101,6 +2120,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } } } + // 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)| { @@ -2247,7 +2271,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 +2440,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 @@ -3863,12 +3888,115 @@ 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 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 written = text.replace("{scale}", &crate::render::layout::scale_ratio_text(scale, comma)); + 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. +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 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; 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 }; + 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 { 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() + || (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. + 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; + } + // 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| { + 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: move or widen it by hand, or make the layout again with layout.publication"), + false, + ); + return; + } + 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")?; @@ -3924,6 +4052,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 9e8af949e2..7c8af968a7 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 @@ -6979,6 +6984,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 +7032,20 @@ 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); + // 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| { + 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); // 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 +7098,62 @@ 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"); + // 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(); + // 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}"), + (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]; + let named = |n: &str| l.elements.iter().find(|e| e.name == n).unwrap(); + 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 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); + 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 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(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index cf7b89660f..9d1181905c 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 @@ -1448,6 +1454,57 @@ 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, 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; + +/// 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 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 }) +} + /// 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 +1519,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 +1569,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 +4599,58 @@ Elaboração: RustGIS", } } + /// 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() { + // 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 = 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"); + } + } + } + } + + /// 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..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 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