From 835f80a769f3e60b8940e020ff137ef31b178582 Mon Sep 17 00:00:00 2001 From: Josh Date: Sat, 21 Nov 2026 20:45:59 -0700 Subject: [PATCH 01/11] fix(layout): a colorbar draws only the title lines that fit in it, and a publication reserves no more than its box (#2493) Follow-up to #2610, for the review points left when it was merged. - A colorbar drew a title line whose middle was within a line of its bottom, as a text element does, so a second line could sit below the element unreported. It now draws a line only when the room it takes ends inside the colorbar (the first line always, as a one-line title always was), and the page's cut-off check counts the rest by the same rule (colorbar_title_drawn). - A publication reserved the colorbar's full wrapped height, while the legend's box over the map is never placed taller than 60% of the frame, so the placement could move, veil or scale the map for room the box can't have. The reserved height is now capped there (no lower than a colorbar's own height); the lines past it are said as cut off. - The Colorbar element's Title bullet in the layouts guide gets a subject. --- crates/engine/src/cmd/layout.rs | 7 ++++- crates/render/src/layout.rs | 56 ++++++++++++++++++++++----------- docs/user-guide/layouts.md | 4 +-- 3 files changed, 45 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 802179d06c..746d789e3c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2189,7 +2189,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let base_w = if sheet { 50.0 * k } else { 40.0 }; let bar_w = base_w.max(bar.as_deref().map_or(0.0, crate::render::layout::colorbar_title_width_mm).min(title_room)); let bar_h = bar.as_deref().map_or(COLORBAR_MM, |title| colorbar_mm(title, bar_w.min(title_room))); - let bar_part = if bar.is_some() { bar_h + if ch > 0.0 { 2.0 } else { 0.0 } } else { 0.0 }; + let bar_gap = if ch > 0.0 { 2.0 } else { 0.0 }; + // Over the map the box is never placed taller than 60% of the frame, so the title's lines + // count only up to that (a colorbar's own height, as before, at the least): the map isn't + // moved, veiled or scaled for room the box can't have. The lines past it are said as cut off. + let bar_h = if column.is_none() { bar_h.min(fh * 0.6 - 2.0 * pad - ch - bar_gap).max(COLORBAR_MM) } else { bar_h }; + let bar_part = if bar.is_some() { bar_h + bar_gap } else { 0.0 }; let (content_w, content_h) = (if bar.is_some() { cw.max(bar_w) } else { cw }, ch + bar_part); let legend_in_column = column.is_some(); if content_h > 0.0 && !legend_in_column { diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index e95a3aa17e..c1ae91ed5e 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -252,7 +252,8 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option .filter_map(|e| { // At least a pixel each way, as the page draws it. let r = Rect::from_xywh((e.x * k) as f32, (e.y * k) as f32, ((e.w * k) as f32).max(1.0), ((e.h * k) as f32).max(1.0))?; - let (s, size, face, align, spacing, rotation, title, broken) = match &e.kind { + // `fits`: how many of its lines the element draws, when it decides that itself. + let (s, size, face, align, spacing, rotation, title, broken, fits) = match &e.kind { ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap } if color.a() > 0 => { @@ -260,12 +261,12 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option let s = expand(t, layout, info, first); // Its lines as they are drawn: a wrapped text's, broken to its box. let s = if *wrap { wrapped(&s, e.w, *size, style) } else { s }; - (s, *size as f32, style.face, *align, *letter_spacing as f32, *rotation as f32, false, *wrap) + (s, *size as f32, style.face, *align, *letter_spacing as f32, *rotation as f32, false, *wrap, None) } ElementKind::Legend { title, frame, .. } => { let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; map_index(maps, map)?; - (title.clone(), 12.0, text::Face { bold: true, ..Default::default() }, TextAlign::Left, 0.0, 0.0, true, false) + (title.clone(), 12.0, text::Face { bold: true, ..Default::default() }, TextAlign::Left, 0.0, 0.0, true, false, None) } // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its // frame's map has a raster with a colour scale (else it draws a placeholder). @@ -275,8 +276,10 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option rustgis_map::layout::colorbar_layer(m, layer.as_deref()) .and_then(|l| l.raster.as_ref()) .and_then(rustgis_map::layout::color_scale)?; - let s = colorbar_title_lines(title, e.w).join("\n"); - (s, COLORBAR_TITLE_PT as f32, colorbar_title_style().face, TextAlign::Left, 0.0, 0.0, false, true) + let lines = colorbar_title_lines(title, e.w); + let fits = colorbar_title_drawn(lines.len(), r.y(), r.bottom(), COLORBAR_TITLE_PT as f32 * 1.33 * ppp); + let s = lines.join("\n"); + (s, COLORBAR_TITLE_PT as f32, colorbar_title_style().face, TextAlign::Left, 0.0, 0.0, false, true, Some(fits)) } _ => return None, }; @@ -287,7 +290,10 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option let lines = std::iter::once(s.as_str()).filter(|_| title).chain(s.lines().filter(|_| !title)); let (mut cut, mut left_out, mut below_box, mut past_limit) = (false, 0, false, false); for (i, line) in lines.enumerate() { - let drawn = i < 200 && (title || cy <= r.bottom() + px); + let drawn = match fits { + Some(n) => i < n, + None => i < 200 && (title || cy <= r.bottom() + px), + }; // A line not drawn is only looked at for a letter, as a wrapped text tells its // ink ([`crate::report::wrap_lines`]): a long text isn't shaped past its box. if !drawn { @@ -3368,14 +3374,13 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { let (mut top, bottom) = (r.y(), r.y() + r.height()); if !bar.title.is_empty() { let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; - // Wrapped to the element's width (#2493), its lines drawn as a text element's are: while - // a line's middle is within a line of the element's bottom, and at most 200. Those left - // out are said with the page's cut-off texts ([`text_losses`]). + // Wrapped to the element's width (#2493), its lines drawn as long as they fit in it + // ([`colorbar_title_drawn`]). Those left out are said with the page's cut-off texts + // ([`text_losses`]). let lines = colorbar_title_lines(bar.title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM)); - let line_y = |i: usize| top + tpx * (0.6 + 1.25 * i as f32); - let drawn = lines.iter().take(200).enumerate().take_while(|(i, _)| line_y(*i) <= bottom + tpx).count(); + let drawn = colorbar_title_drawn(lines.len(), top, bottom, tpx); for (i, line) in lines.iter().take(drawn).enumerate() { - text::text_at(pm, line, r.x(), line_y(i), tpx, dark, true, text::Align::Left, false); + text::text_at(pm, line, r.x(), top + tpx * (0.6 + 1.25 * i as f32), tpx, dark, true, text::Align::Left, false); } top += tpx * (1.4 + 1.25 * drawn.saturating_sub(1) as f32); } @@ -3566,6 +3571,15 @@ pub fn colorbar_title_lines(title: &str, width: f64) -> Vec { wrapped(title, width, COLORBAR_TITLE_PT, colorbar_title_style()).lines().map(str::to_string).collect() } +/// How many of a colorbar's `lines` of title it draws in an element from `top` to `bottom` +/// (pixels), its title at `px` pixels (#2493): the first always, as a title of one line always +/// was; each further one only when the room it takes ends inside the element; at most 200. The +/// page's cut-off check ([`text_losses`]) counts the rest the same way. +fn colorbar_title_drawn(lines: usize, top: f32, bottom: f32, px: f32) -> usize { + let further = (1..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= bottom + 0.5).count(); + usize::from(lines > 0) + further +} + /// The distance between two lines of text at `size` points, in mm, as [`text_block`] sets them. pub fn line_pitch_mm(size: f64) -> f64 { size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 @@ -7141,23 +7155,24 @@ Elaboração: RustGIS", assert!(line(10 + pitch + 3), "a second line of title"); } - /// A colorbar too short for its title's lines draws those that fit, as a text element does, - /// not lines spilling down the page, and the page's cut-off check says the rest are left out; - /// one tall enough says nothing (#2493). + /// A colorbar too short for its title's lines draws those that fit inside it, not lines past + /// its bottom, and the page's cut-off check says the rest are left out; one tall enough says + /// nothing (#2493). #[test] fn a_colorbars_title_lines_past_its_bottom_are_left_out_and_said() { let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(200, 200, 200), Rgba::rgb(230, 230, 230)] }; let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; let bar = Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - // 100 px wide, four lines or more; 20 px high, two of them centred within a line of its - // bottom. A third would be centred at 10 + 12 × (0.6 + 2 × 1.25) = 47. + // 100 px wide, four lines or more; 20 px high, the first only: a second's room would end + // at 10 + 12 × (1.4 + 1.25) = 41.8, past its bottom at 30 (where it would be centred at + // 32, within a line of it, as a text element's line may be). assert!(colorbar_title_lines(title, 100.0 / PT_PER_MM).len() >= 4); let mut c = Canvas::new(300, 200).unwrap(); colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 20.0).unwrap(), &scale, &bar, 1.0); let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120); let lowest = (0..200).rev().find(|y| (0..300).any(|x| dark(x, *y))); - assert!(lowest.is_some_and(|y| y < 45), "ink down to {lowest:?}"); + assert!(lowest.is_some_and(|y| y <= 30), "ink down to {lowest:?}, past the colorbar's bottom at 30"); // On a page, in a frame whose map has a raster on a ramp. let map = ramp_map( rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, @@ -7183,7 +7198,10 @@ Elaboração: RustGIS", let info = PageInfo::default(); let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); assert_eq!(losses.len(), 1, "the short colorbar's title is cut"); - assert!(losses[0].id == id && losses[0].left_out >= 2 && losses[0].below_box, "{} left out", losses[0].left_out); + // 6 mm high: the first line only, every other one said. + let lines = colorbar_title_lines(title, 25.0).len(); + assert!(lines >= 3 && losses[0].id == id && losses[0].below_box, "{lines} lines"); + assert_eq!(losses[0].left_out, lines - 1); l.element_mut(id).unwrap().h = 40.0; assert!(text_losses(&l, std::slice::from_ref(&map), 96.0, &info).is_empty(), "tall enough for every line"); } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index e2a7bf69cc..8c030b888c 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -364,8 +364,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu tables. Its properties pick the **Layer** (unless one is picked, the top visible raster with a colour scale, not drawn by classes: a legend lists a land cover's classes, and a colorbar added over a map with only such rasters draws an empty placeholder and says so), the - **Title** (the units, such as `Elevation (m)`; the layer's name to start with; one wider than the colorbar - wraps at spaces onto more lines, the bar under them), the + **Title** (the units, such as `Elevation (m)`; the layer's name to start with; a title wider than the colorbar + wraps at spaces onto more lines, with the bar under them), the **Orientation**, which side the **Labels** go on, how many **Ticks** a gradient labels (2 to 21, the ends included) and **Reverse** (high values first). An RGB raster or a hillshade without a tint has no colour scale and shows a placeholder, as does a picked layer that was From 51450da58beb6b12ac15b45d60e2c83836ac8798 Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:20:12 +0000 Subject: [PATCH 02/11] fix(layout): keep a publication's legend rows beside a capped colorbar Over the map, a colorbar's title is capped to what the box can hold under 60% of the frame. The cap was worked out once from the legend's pre-selection row height, so a multi-column legend could pass the fit test with too little room for its rows, and the final placement gave the colorbar its full title height, leaving the rows none. The reservation now follows each candidate's own rows in the fit test and in the placement, and the placement keeps the chosen rows' height. A title keeps its full measured height whenever the box fits. The shorter-colorbar warning compares against the height actually drawn. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/engine/src/cmd/layout.rs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 8df9662618..4168a90136 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2190,13 +2190,17 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { }; let base_w = if sheet { 50.0 * k } else { 40.0 }; let bar_w = base_w.max(bar.as_deref().map_or(0.0, crate::render::layout::colorbar_title_width_mm).min(title_room)); - let bar_h = bar.as_deref().map_or(COLORBAR_MM, |title| colorbar_mm(title, bar_w.min(title_room))); + let bar_measured = bar.as_deref().map_or(COLORBAR_MM, |title| colorbar_mm(title, bar_w.min(title_room))); let bar_gap = if ch > 0.0 { 2.0 } else { 0.0 }; // Over the map the box is never placed taller than 60% of the frame, so the title's lines - // count only up to that (a colorbar's own height, as before, at the least): the map isn't - // moved, veiled or scaled for room the box can't have. The lines past it are said as cut off. - let bar_h = if column.is_none() { bar_h.min(fh * 0.6 - 2.0 * pad - ch - bar_gap).max(COLORBAR_MM) } else { bar_h }; - let bar_part = if bar.is_some() { bar_h + bar_gap } else { 0.0 }; + // count only up to that, less the rows of the legend beside them (a colorbar's own height, as + // before, at the least): the map isn't moved, veiled or scaled for room the box can't have, and + // each candidate's rows keep their height (the fit test and the placement below). The lines past + // it are said as cut off. + let over_map = column.is_none(); + let cap = |rows_h: f64| (fh * 0.6 - 2.0 * pad - rows_h - bar_gap).max(COLORBAR_MM); + let bar_reserve = |rows_h: f64| if over_map { bar_measured.min(cap(rows_h)) } else { bar_measured }; + let bar_part = if bar.is_some() { bar_reserve(ch) + bar_gap } else { 0.0 }; let (content_w, content_h) = (if bar.is_some() { cw.max(bar_w) } else { cw }, ch + bar_part); let legend_in_column = column.is_some(); if content_h > 0.0 && !legend_in_column { @@ -2230,7 +2234,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // the frame's area in the background (which the export reads anyway); web tiles aren't fetched. let coverage = crate::render::layout::frame_coverage(s.map_mut(), center, scale, fw, fh, 384); // The legend's whole box, around its rows and the colorbar under them. - let whole = |(w, h): (f64, f64)| ((if bar.is_some() { w.max(bar_w) } else { w }) + 2.0 * pad, h + bar_part + 2.0 * pad); + // A candidate's colorbar reservation follows its own rows, which its column count sets. + let whole = |(w, h): (f64, f64)| { + let part = if bar.is_some() { bar_reserve(h) + bar_gap } else { 0.0 }; + ((if bar.is_some() { w.max(bar_w) } else { w }) + 2.0 * pad, h + part + 2.0 * pad) + }; // The largest rectangle a coverage leaves free inside the graticule's margins, in mm. let free_room = |(gw, gh, cells): &(u32, u32, Vec)| { let (gw, gh) = (*gw as usize, *gh as usize); @@ -2838,11 +2846,14 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // the colorbar asked for (the rows in more columns): fewer lines leave the rows more room. let (ix, iy, iw, ih) = (r.0 + pad, r.1 + pad, lw - 2.0 * pad, lh - 2.0 * pad); let bar_need = bar.as_deref().map_or(0.0, |title| colorbar_mm(title, iw)); - let bar_fit = bar_need.min(ih); - let rows_h = (ih - bar_fit - if bar.is_some() { bar_part - bar_h } else { 0.0 }).max(0.0); + // Over the map the colorbar leaves the rows the height they were sized to (`ch`, the chosen + // column count's), so a title past the box's cap is cut short rather than taking the rows. + let bar_fit = if over_map { bar_need.min((ih - ch - bar_gap).max(0.0)) } else { bar_need.min(ih) }; + let rows_h = (ih - bar_fit - if bar.is_some() { bar_gap } else { 0.0 }).max(0.0); warnings.extend(legend_fit_warnings(legend_cols, (cw, ch), (iw, rows_h)).into_iter().map(String::from)); + let short = bar_need > bar_fit + LEGEND_FIT_MM; // In a column the colorbar takes the column's width, as its rows do. - if let Some(layer) = bar.as_deref().filter(|_| (base_w > iw + LEGEND_FIT_MM && !legend_in_column) || bar_need > ih + LEGEND_FIT_MM) + if let Some(layer) = bar.as_deref().filter(|_| (base_w > iw + LEGEND_FIT_MM && !legend_in_column) || short) { warnings.push(format!("the legend's box is smaller than the colorbar of '{layer}': it is drawn narrower or shorter")); } From da5f796565ef9daaccbedeb9cde4dd98ce3cb757 Mon Sep 17 00:00:00 2001 From: Josh Date: Sat, 21 Nov 2026 22:19:16 -0700 Subject: [PATCH 03/11] style(layout): rustfmt the capped colorbar's warning check --- crates/engine/src/cmd/layout.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 4168a90136..95aa5942d7 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2853,8 +2853,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { warnings.extend(legend_fit_warnings(legend_cols, (cw, ch), (iw, rows_h)).into_iter().map(String::from)); let short = bar_need > bar_fit + LEGEND_FIT_MM; // In a column the colorbar takes the column's width, as its rows do. - if let Some(layer) = bar.as_deref().filter(|_| (base_w > iw + LEGEND_FIT_MM && !legend_in_column) || short) - { + if let Some(layer) = bar.as_deref().filter(|_| (base_w > iw + LEGEND_FIT_MM && !legend_in_column) || short) { warnings.push(format!("the legend's box is smaller than the colorbar of '{layer}': it is drawn narrower or shorter")); } if ch > 0.0 && rows_h >= 1.0 { From c5f00b4c17cd2e0033ac4111d33dfeb84be118dd Mon Sep 17 00:00:00 2001 From: Josh Date: Sun, 22 Nov 2026 00:19:41 -0700 Subject: [PATCH 04/11] fix(layout): a colorbar keeps its own height beside the rows, and its bar keeps its labels under a long title (#2493) Review round on #2638. - Over the map, the colorbar now takes at least a colorbar's own height (15 mm) while the box has it. Rows that fill the box are cut and said by the legend's fit warning, rather than the bar getting no height and no colour ramp. - A colorbar's title now stops short of the bar's own room (a 3-point bar with its ticks and 8-point labels): a long title no longer takes the room the labels need, so they aren't dropped without a word. The page's cut-off check counts the held-back lines by the same limit. - The allocation is one function, colorbar_fit, tested directly. --- crates/engine/src/cmd/layout.rs | 15 ++++++++--- crates/engine/src/tests.rs | 19 +++++++++++++ crates/render/src/layout.rs | 47 +++++++++++++++++++++++++++------ 3 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 95aa5942d7..1834186181 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -791,6 +791,17 @@ pub(crate) fn veil_panel( /// its labels. const COLORBAR_MM: f64 = 15.0; +/// The height a publication gives its colorbar in a legend's box `ih` mm high inside, in mm, +/// when its title needs `need` (#2493). Over the map it leaves the rows the room they were sized +/// to (`rows`, with the gap above the colorbar), so a title past the box's cap is cut short +/// rather than taking them; but never below a colorbar's own height while the box has it, so +/// the bar isn't lost to rows that fill the box: those are cut and said instead (#2638). In a +/// side column it takes what it needs of the box. +pub(crate) fn colorbar_fit(need: f64, ih: f64, rows: f64, over_map: bool) -> f64 { + let ih = ih.max(0.0); + if over_map { need.min((ih - rows).max(COLORBAR_MM.min(ih))) } else { need.min(ih) } +} + /// A publication layout's colorbar's height, in mm, `width` mm wide: [`COLORBAR_MM`] and a line's /// pitch more for each line its title wraps to past the first (#2493). fn colorbar_mm(title: &str, width: f64) -> f64 { @@ -2846,9 +2857,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // the colorbar asked for (the rows in more columns): fewer lines leave the rows more room. let (ix, iy, iw, ih) = (r.0 + pad, r.1 + pad, lw - 2.0 * pad, lh - 2.0 * pad); let bar_need = bar.as_deref().map_or(0.0, |title| colorbar_mm(title, iw)); - // Over the map the colorbar leaves the rows the height they were sized to (`ch`, the chosen - // column count's), so a title past the box's cap is cut short rather than taking the rows. - let bar_fit = if over_map { bar_need.min((ih - ch - bar_gap).max(0.0)) } else { bar_need.min(ih) }; + let bar_fit = colorbar_fit(bar_need, ih, ch + bar_gap, over_map); let rows_h = (ih - bar_fit - if bar.is_some() { bar_gap } else { 0.0 }).max(0.0); warnings.extend(legend_fit_warnings(legend_cols, (cw, ch), (iw, rows_h)).into_iter().map(String::from)); let short = bar_need > bar_fit + LEGEND_FIT_MM; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4a026cc68..cbf3928411 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -13768,6 +13768,25 @@ fn a_publications_colorbar_title_stays_in_the_legends_box() { let _ = std::fs::remove_dir_all(&dir); } +/// A publication's colorbar takes what its title needs, leaving the legend's rows the room they +/// were sized to over the map, but never less than a colorbar's own height while the box has it: +/// rows that fill the box are cut and said, not the bar (#2638). +#[test] +fn a_publications_colorbar_keeps_its_own_height_beside_rows() { + use crate::cmd::layout::colorbar_fit; + // Room to spare: what the title needs. + assert_eq!(colorbar_fit(30.0, 56.0, 22.0, true), 30.0); + // A title past the cap: what the rows leave it. + assert_eq!(colorbar_fit(75.0, 56.0, 22.0, true), 34.0); + // Rows that fill the box (one 69.85 mm row and the gap): the colorbar keeps its 15 mm. + assert_eq!(colorbar_fit(20.0, 56.0, 71.85, true), 15.0); + // A box shorter than a colorbar: all of it, and none of a box with no room. + assert_eq!(colorbar_fit(20.0, 10.0, 9.0, true), 10.0); + assert_eq!(colorbar_fit(20.0, -1.0, 9.0, true), 0.0); + // In a side column: what it needs of the box. + assert_eq!(colorbar_fit(75.0, 56.0, 22.0, false), 56.0); +} + /// Series page labels and dynamic text share the row-number fallback for null and blank names. #[test] fn map_series_empty_names_use_row_numbers() { diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index a1fd49a532..40818fbec8 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -279,7 +279,8 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option .and_then(|l| l.raster.as_ref()) .and_then(rustgis_map::layout::color_scale)?; let lines = colorbar_title_lines(title, e.w); - let fits = colorbar_title_drawn(lines.len(), r.y(), r.bottom(), COLORBAR_TITLE_PT as f32 * 1.33 * ppp); + let limit = r.bottom() - colorbar_bar_room(ppp); + let fits = colorbar_title_drawn(lines.len(), r.y(), limit, COLORBAR_TITLE_PT as f32 * 1.33 * ppp); let s = lines.join("\n"); (s, COLORBAR_TITLE_PT as f32, colorbar_title_style().face, TextAlign::Left, 0.0, 0.0, false, true, Some(fits)) } @@ -3486,7 +3487,7 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { // ([`colorbar_title_drawn`]). Those left out are said with the page's cut-off texts // ([`text_losses`]). let lines = colorbar_title_lines(bar.title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM)); - let drawn = colorbar_title_drawn(lines.len(), top, bottom, tpx); + let drawn = colorbar_title_drawn(lines.len(), top, bottom - colorbar_bar_room(ppp), tpx); for (i, line) in lines.iter().take(drawn).enumerate() { text::text_at(pm, line, r.x(), top + tpx * (0.6 + 1.25 * i as f32), tpx, dark, true, text::Align::Left, false); } @@ -3679,15 +3680,23 @@ pub fn colorbar_title_lines(title: &str, width: f64) -> Vec { wrapped(title, width, COLORBAR_TITLE_PT, colorbar_title_style()).lines().map(str::to_string).collect() } -/// How many of a colorbar's `lines` of title it draws in an element from `top` to `bottom` -/// (pixels), its title at `px` pixels (#2493): the first always, as a title of one line always -/// was; each further one only when the room it takes ends inside the element; at most 200. The -/// page's cut-off check ([`text_losses`]) counts the rest the same way. -fn colorbar_title_drawn(lines: usize, top: f32, bottom: f32, px: f32) -> usize { - let further = (1..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= bottom + 0.5).count(); +/// How many of a colorbar's `lines` of title it draws in an element from `top` (pixels), its +/// title at `px` pixels (#2493): the first always, as a title of one line always was; each +/// further one only when the room it takes ends by `limit`, the element's bottom less the bar's +/// own room ([`colorbar_bar_room`]), so the bar keeps its labels; at most 200. The page's +/// cut-off check ([`text_losses`]) counts the rest the same way. +fn colorbar_title_drawn(lines: usize, top: f32, limit: f32, px: f32) -> usize { + let further = (1..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= limit + 0.5).count(); usize::from(lines > 0) + further } +/// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638): a bar of +/// 3 points with its ticks and 8-point labels under it, as [`colorbar`] lays them out. A title +/// stops short of it, so its lines never leave the bar without its labels. +fn colorbar_bar_room(ppp: f32) -> f32 { + (8.0 * 1.33 * 1.2 + 2.5 + 1.5 + 3.0) * ppp +} + /// The distance between two lines of text at `size` points, in mm, as [`text_block`] sets them. pub fn line_pitch_mm(size: f64) -> f64 { size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 @@ -7284,6 +7293,28 @@ Elaboração: RustGIS", assert!(line(10 + pitch + 3), "a second line of title"); } + /// A colorbar's title stops short of the bar's own room, so a long title never leaves the bar + /// without its tick labels: the bar ends above them, its labels under it (#2638). Before, the + /// title's second line took the room, and the bar filled the element's bottom with no labels. + #[test] + fn a_colorbars_long_title_leaves_its_bar_room_for_labels() { + // A red-to-blue bar, so its pixels are told apart from the grey text. + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; + let bar = + Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + // 100 × 40 px: room for two lines of title, but then only 8 px of bar, with no labels. + let mut c = Canvas::new(300, 200).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 40.0).unwrap(), &scale, &bar, 1.0); + let px = |x: u32, y: u32| c.pixmap().pixel(x, y); + let coloured = + |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 200 && p.green() < 90 && p.red().abs_diff(p.blue()) > 60)); + let dark = |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120)); + assert!((26..36).any(coloured), "the bar under the title"); + assert!(!(44..50).any(coloured), "the bar ends above its labels, not at the element's bottom"); + assert!((40..50).any(dark), "its labels under it"); + } + /// A colorbar too short for its title's lines draws those that fit inside it, not lines past /// its bottom, and the page's cut-off check says the rest are left out; one tall enough says /// nothing (#2493). From d3fa888f81c3ad59bc87243261c1267413690ec0 Mon Sep 17 00:00:00 2001 From: Josh Date: Sun, 22 Nov 2026 01:01:15 -0700 Subject: [PATCH 05/11] fix(layout): a colorbar draws a title line only where its bar keeps room for its labels (#2493) Review round on #2638. The title's first line was always drawn, and a further line was let in with half a pixel of slack, so a short colorbar could still leave its bar too little room and drop its tick labels without a word. Each title line, the first too, is now drawn only when the bar keeps its full room under it, with no slack. A colorbar too short for both holds its title back, and the page's cut-off check says so, counting by the same rule. --- crates/render/src/layout.rs | 38 ++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 40818fbec8..69b367c323 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -3681,13 +3681,12 @@ pub fn colorbar_title_lines(title: &str, width: f64) -> Vec { } /// How many of a colorbar's `lines` of title it draws in an element from `top` (pixels), its -/// title at `px` pixels (#2493): the first always, as a title of one line always was; each -/// further one only when the room it takes ends by `limit`, the element's bottom less the bar's -/// own room ([`colorbar_bar_room`]), so the bar keeps its labels; at most 200. The page's -/// cut-off check ([`text_losses`]) counts the rest the same way. +/// title at `px` pixels (#2493): each line only when the room it takes ends by `limit`, the +/// element's bottom less the bar's own room ([`colorbar_bar_room`]), the first too, so the bar +/// always keeps its labels (#2638); at most 200. The page's cut-off check ([`text_losses`]) +/// counts the lines left out the same way, so a colorbar too short for its title says so. fn colorbar_title_drawn(lines: usize, top: f32, limit: f32, px: f32) -> usize { - let further = (1..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= limit + 0.5).count(); - usize::from(lines > 0) + further + (0..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= limit).count() } /// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638): a bar of @@ -7315,6 +7314,23 @@ Elaboração: RustGIS", assert!((40..50).any(dark), "its labels under it"); } + /// A colorbar's title lines are drawn only where the bar keeps its own room under them, the + /// first too, with no slack: the bar never loses its labels to them (#2638). At 12 px a line, + /// the first needs 16.8 px and each further one 15 more, over the bar's 19.8. + #[test] + fn a_colorbars_title_lines_leave_the_bar_its_room() { + let (px, room) = (COLORBAR_TITLE_PT as f32 * 1.33, colorbar_bar_room(1.0)); + for (height, lines) in [(20.0, 0), (36.0, 0), (37.0, 1), (51.2, 1), (52.0, 2), (200.0, 5)] { + assert_eq!(colorbar_title_drawn(5, 0.0, height - room, px), lines, "{height} px"); + } + // Whatever the height, the lines drawn leave the bar its room. + for h in 0..300 { + let h = h as f32 * 0.5; + let n = colorbar_title_drawn(5, 0.0, h - room, px); + assert!(n == 0 || px * (1.4 + 1.25 * (n - 1) as f32) + room <= h, "{h} px: {n} lines"); + } + } + /// A colorbar too short for its title's lines draws those that fit inside it, not lines past /// its bottom, and the page's cut-off check says the rest are left out; one tall enough says /// nothing (#2493). @@ -7324,9 +7340,9 @@ Elaboração: RustGIS", let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; let bar = Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; - // 100 px wide, four lines or more; 20 px high, the first only: a second's room would end - // at 10 + 12 × (1.4 + 1.25) = 41.8, past its bottom at 30 (where it would be centred at - // 32, within a line of it, as a text element's line may be). + // 100 px wide, four lines or more; 20 px high, no line: the first's room would end at + // 10 + 12 × 1.4 = 26.8, leaving the bar less than its own 19.8 (a second would be centred + // at 32, within a line of the bottom at 30, as a text element's line may be). assert!(colorbar_title_lines(title, 100.0 / PT_PER_MM).len() >= 4); let mut c = Canvas::new(300, 200).unwrap(); colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 20.0).unwrap(), &scale, &bar, 1.0); @@ -7358,10 +7374,10 @@ Elaboração: RustGIS", let info = PageInfo::default(); let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); assert_eq!(losses.len(), 1, "the short colorbar's title is cut"); - // 6 mm high: the first line only, every other one said. + // 6 mm high: no room for a line of title over the bar's own: every line said. let lines = colorbar_title_lines(title, 25.0).len(); assert!(lines >= 3 && losses[0].id == id && losses[0].below_box, "{lines} lines"); - assert_eq!(losses[0].left_out, lines - 1); + assert_eq!(losses[0].left_out, lines); l.element_mut(id).unwrap().h = 40.0; assert!(text_losses(&l, std::slice::from_ref(&map), 96.0, &info).is_empty(), "tall enough for every line"); } From b43ed595972551bb7157f37879a972c0281da81e Mon Sep 17 00:00:00 2001 From: Josh Date: Sun, 22 Nov 2026 01:40:41 -0700 Subject: [PATCH 06/11] fix(layout): a colorbar whose title is held back starts its bar at its top (#2493) Review round on #2638: when no line of the title fit over the bar's own room, the colorbar still moved its bar down by a line's room, so the bar lost its labels anyway. A title held back whole now takes no room. --- crates/render/src/layout.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 69b367c323..f0c8205b1a 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -3491,7 +3491,10 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { for (i, line) in lines.iter().take(drawn).enumerate() { text::text_at(pm, line, r.x(), top + tpx * (0.6 + 1.25 * i as f32), tpx, dark, true, text::Align::Left, false); } - top += tpx * (1.4 + 1.25 * drawn.saturating_sub(1) as f32); + // A title held back whole takes no room: the bar starts at the element's top. + if drawn > 0 { + top += tpx * (1.4 + 1.25 * (drawn - 1) as f32); + } } // Where each block or sample sits along the bar (0 low to 1 high), and the labels with theirs. let (blocks, labels): (Vec, Vec<(f32, String)>) = match scale { @@ -7314,6 +7317,29 @@ Elaboração: RustGIS", assert!((40..50).any(dark), "its labels under it"); } + /// A colorbar too short for a line of title over its bar holds the title back, and the bar + /// then starts at the element's top, keeping its labels: a title not drawn takes no room + /// (#2638). Before, the bar was pushed down by the room of a line never drawn, and lost them. + #[test] + fn a_colorbar_whose_title_is_held_back_keeps_its_labels() { + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let title = "Precipitação média mensal JAXA GSMaP (mm/mês), jan–mar 2025"; + let bar = + Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; + // 100 × 30 px, from y = 10 to 40: a line of title (16.8 px) and the bar's own room + // (19.8) don't both fit, so no line is drawn. + assert_eq!(colorbar_title_drawn(4, 10.0, 40.0 - colorbar_bar_room(1.0), COLORBAR_TITLE_PT as f32 * 1.33), 0); + let mut c = Canvas::new(300, 200).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 30.0).unwrap(), &scale, &bar, 1.0); + let px = |x: u32, y: u32| c.pixmap().pixel(x, y); + let coloured = + |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 200 && p.green() < 90 && p.red().abs_diff(p.blue()) > 60)); + let dark = |y: u32| (10..110).any(|x| px(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120)); + assert!((11..15).any(coloured), "the bar at the element's top"); + assert!(!(35..40).any(coloured), "the bar ends above its labels"); + assert!((30..40).any(dark), "its labels under it"); + } + /// A colorbar's title lines are drawn only where the bar keeps its own room under them, the /// first too, with no slack: the bar never loses its labels to them (#2638). At 12 px a line, /// the first needs 16.8 px and each further one 15 more, over the bar's 19.8. From 0fd0e0487177dc82b0ec7baf82f1cea5f88f661c Mon Sep 17 00:00:00 2001 From: Josh Date: Sun, 22 Nov 2026 02:21:04 -0700 Subject: [PATCH 07/11] fix(layout): a vertical colorbar's title needs only a bar's thickness under it (#2493) Review round on #2638: the room kept under a colorbar's title was a horizontal bar's label band, but a vertical colorbar has its labels at its side. A short vertical colorbar held back a title that fit and said it was cut off. Its title now needs only 3 points of bar under it, in the drawing and in the page's cut-off check alike. --- crates/render/src/layout.rs | 60 ++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index f0c8205b1a..d0fb9575a7 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -272,14 +272,14 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option } // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its // frame's map has a raster with a colour scale (else it draws a placeholder). - ElementKind::Colorbar { frame, layer, title, .. } if !title.is_empty() => { + ElementKind::Colorbar { frame, layer, title, orientation, .. } if !title.is_empty() => { let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; let m = maps.get(map_index(maps, map)?)?; rustgis_map::layout::colorbar_layer(m, layer.as_deref()) .and_then(|l| l.raster.as_ref()) .and_then(rustgis_map::layout::color_scale)?; let lines = colorbar_title_lines(title, e.w); - let limit = r.bottom() - colorbar_bar_room(ppp); + let limit = r.bottom() - colorbar_bar_room(ppp, *orientation); let fits = colorbar_title_drawn(lines.len(), r.y(), limit, COLORBAR_TITLE_PT as f32 * 1.33 * ppp); let s = lines.join("\n"); (s, COLORBAR_TITLE_PT as f32, colorbar_title_style().face, TextAlign::Left, 0.0, 0.0, false, true, Some(fits)) @@ -3487,7 +3487,7 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { // ([`colorbar_title_drawn`]). Those left out are said with the page's cut-off texts // ([`text_losses`]). let lines = colorbar_title_lines(bar.title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM)); - let drawn = colorbar_title_drawn(lines.len(), top, bottom - colorbar_bar_room(ppp), tpx); + let drawn = colorbar_title_drawn(lines.len(), top, bottom - colorbar_bar_room(ppp, bar.orientation), tpx); for (i, line) in lines.iter().take(drawn).enumerate() { text::text_at(pm, line, r.x(), top + tpx * (0.6 + 1.25 * i as f32), tpx, dark, true, text::Align::Left, false); } @@ -3692,11 +3692,15 @@ fn colorbar_title_drawn(lines: usize, top: f32, limit: f32, px: f32) -> usize { (0..lines.min(200)).take_while(|i| top + px * (1.4 + 1.25 * *i as f32) <= limit).count() } -/// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638): a bar of -/// 3 points with its ticks and 8-point labels under it, as [`colorbar`] lays them out. A title -/// stops short of it, so its lines never leave the bar without its labels. -fn colorbar_bar_room(ppp: f32) -> f32 { - (8.0 * 1.33 * 1.2 + 2.5 + 1.5 + 3.0) * ppp +/// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638), as +/// [`colorbar`] lays it out: a horizontal bar of 3 points with its ticks and 8-point labels under +/// it; a vertical one, whose labels are at its side, 3 points of bar. A title stops short of it, +/// so its lines never leave the bar without its labels. +fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { + match orientation { + Orientation::Horizontal => (8.0 * 1.33 * 1.2 + 2.5 + 1.5 + 3.0) * ppp, + Orientation::Vertical => 3.0 * ppp, + } } /// The distance between two lines of text at `size` points, in mm, as [`text_block`] sets them. @@ -7317,6 +7321,39 @@ Elaboração: RustGIS", assert!((40..50).any(dark), "its labels under it"); } + /// A vertical colorbar's labels are at its side, so its title needs only a bar's thickness + /// under it, not a horizontal bar's label band (#2638): a vertical colorbar 8 mm high draws + /// its one-line title and says nothing, where a horizontal one holds it back and says so. + #[test] + fn a_vertical_colorbar_keeps_a_title_that_fits_beside_its_labels() { + let map = ramp_map( + rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, + rustgis_map::raster::Stretch::MinMax, + ); + let info = PageInfo::default(); + for (orientation, cut) in [(Orientation::Vertical, false), (Orientation::Horizontal, true)] { + let mut l = Layout::new("Page", 120.0, 90.0); + let frame = l.add( + "Frame", + (60.0, 60.0, 50.0, 25.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let kind = ElementKind::Colorbar { + frame, + layer: None, + title: "Elevation (m)".into(), + orientation, + ticks: 5, + tick_side: TickSide::End, + reverse: false, + color: None, + }; + l.add("Colorbar", (5.0, 5.0, 25.0, 8.0), kind); + let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); + assert_eq!(losses.len() == 1, cut, "{orientation:?}: {losses:?}"); + } + } + /// A colorbar too short for a line of title over its bar holds the title back, and the bar /// then starts at the element's top, keeping its labels: a title not drawn takes no room /// (#2638). Before, the bar was pushed down by the room of a line never drawn, and lost them. @@ -7328,7 +7365,10 @@ Elaboração: RustGIS", Bar { title, orientation: Orientation::Horizontal, ticks: 3, side: TickSide::End, reverse: false, comma: false, ink: INK }; // 100 × 30 px, from y = 10 to 40: a line of title (16.8 px) and the bar's own room // (19.8) don't both fit, so no line is drawn. - assert_eq!(colorbar_title_drawn(4, 10.0, 40.0 - colorbar_bar_room(1.0), COLORBAR_TITLE_PT as f32 * 1.33), 0); + assert_eq!( + colorbar_title_drawn(4, 10.0, 40.0 - colorbar_bar_room(1.0, Orientation::Horizontal), COLORBAR_TITLE_PT as f32 * 1.33), + 0 + ); let mut c = Canvas::new(300, 200).unwrap(); colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 30.0).unwrap(), &scale, &bar, 1.0); let px = |x: u32, y: u32| c.pixmap().pixel(x, y); @@ -7345,7 +7385,7 @@ Elaboração: RustGIS", /// the first needs 16.8 px and each further one 15 more, over the bar's 19.8. #[test] fn a_colorbars_title_lines_leave_the_bar_its_room() { - let (px, room) = (COLORBAR_TITLE_PT as f32 * 1.33, colorbar_bar_room(1.0)); + let (px, room) = (COLORBAR_TITLE_PT as f32 * 1.33, colorbar_bar_room(1.0, Orientation::Horizontal)); for (height, lines) in [(20.0, 0), (36.0, 0), (37.0, 1), (51.2, 1), (52.0, 2), (200.0, 5)] { assert_eq!(colorbar_title_drawn(5, 0.0, height - room, px), lines, "{height} px"); } From 9cca57860c3c76743b35f094c303690ee164b0ad Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:20:41 +0000 Subject: [PATCH 08/11] fix(layout): say when a legend's colorbar is left out A publication's legend box can have no height left inside its frame. The colorbar is then not drawn at all, but the notice said only that it was drawn narrower or shorter. The notice now says the colorbar is left out in that case. The other cases keep their wording. Review threads on #2638: the colorbar title and bar room, the first title line and the vertical room are already handled by earlier commits and are answered on the threads. The vertical end-label case and the quality points are left for a maintainer. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/engine/src/cmd/layout.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 72c147630a..1eb313bf70 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2889,7 +2889,12 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { let short = bar_need > bar_fit + LEGEND_FIT_MM; // In a column the colorbar takes the column's width, as its rows do. if let Some(layer) = bar.as_deref().filter(|_| (base_w > iw + LEGEND_FIT_MM && !legend_in_column) || short) { - warnings.push(format!("the legend's box is smaller than the colorbar of '{layer}': it is drawn narrower or shorter")); + // With no height left in the box the bar is not drawn at all, so the notice says so. + if bar_fit > 0.0 { + warnings.push(format!("the legend's box is smaller than the colorbar of '{layer}': it is drawn narrower or shorter")); + } else { + warnings.push(format!("the legend's box has no room for the colorbar of '{layer}': it is left out")); + } } if ch > 0.0 && rows_h >= 1.0 { l.add( From 77029d7bfbe359693f81475b02ccf712b9074e03 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 10:56:23 -0500 Subject: [PATCH 09/11] fix(layout): a colorbar keeps room for its labels, and says when it can't (#2493) Review threads on #2638. A vertical colorbar's end labels are centred on its bar's ends, so 3 pixels of bar under the title let a short one draw its title and drop both end labels without a word. Its title now leaves two labels' height, so the inset keeps them inside the element. A colorbar too short for its labels at all (a horizontal one under about 5 mm, a vertical one under about 4.5 mm, with or without a title) dropped them silently. The page's cut-off check now reports it, as it does a cramped scale bar, by the rule the drawing uses (colorbar_labels_fit). --- crates/render/src/layout.rs | 108 +++++++++++++++++++++++++++++------- 1 file changed, 88 insertions(+), 20 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 07873f2524..6c4b6d7dd1 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -272,7 +272,8 @@ pub struct TextLoss { /// the line past the 200 drawn ([`wrapped`]). pub at_least: bool, /// Some of them are left out below its box, among the first 200: a taller box or a smaller - /// text draws them. + /// text draws them. Also set, with no line counted, when a scale bar's or a colorbar's labels + /// don't fit its box. pub below_box: bool, /// Some of them come past the 200 lines a text draws, whatever its box: only splitting the /// text draws them. @@ -352,6 +353,8 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option off_page, }); } + // A colorbar's labels left out for want of height, said with its title (#2638). + let mut labels_cut = false; // `fits`: how many of its lines the element draws, when it decides that itself. let (s, size, face, align, spacing, rotation, title, broken, fits) = match &e.kind { ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap } @@ -372,15 +375,22 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option } // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its // frame's map has a raster with a colour scale (else it draws a placeholder). - ElementKind::Colorbar { frame, layer, title, orientation, .. } if !title.is_empty() => { + // Its labels, too, when the element is too short for them under its title (#2638). + ElementKind::Colorbar { frame, layer, title, orientation, .. } => { let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; let m = maps.get(map_index(maps, map)?)?; rustgis_map::layout::colorbar_layer(m, layer.as_deref()) .and_then(|l| l.raster.as_ref()) .and_then(rustgis_map::layout::color_scale)?; - let lines = colorbar_title_lines(title, e.w); + let lines = if title.is_empty() { Vec::new() } else { colorbar_title_lines(title, e.w) }; + let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; let limit = r.bottom() - colorbar_bar_room(ppp, *orientation); - let fits = colorbar_title_drawn(lines.len(), r.y(), limit, COLORBAR_TITLE_PT as f32 * 1.33 * ppp); + let fits = colorbar_title_drawn(lines.len(), r.y(), limit, tpx); + let title_room = if fits > 0 { tpx * (1.4 + 1.25 * (fits - 1) as f32) } else { 0.0 }; + labels_cut = !colorbar_labels_fit(r.height() - title_room, ppp, *orientation); + if lines.is_empty() && !labels_cut { + return None; + } let s = lines.join("\n"); (s, COLORBAR_TITLE_PT as f32, colorbar_title_style().face, TextAlign::Left, 0.0, 0.0, false, true, Some(fits)) } @@ -431,7 +441,16 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option } // A wrapped text ends at the line past the 200 drawn ([`wrapped`]): it may go on. let at_least = broken && s.lines().nth(200).is_some(); - (cut || off_page).then(|| TextLoss { id: e.id, name: e.name.clone(), left_out, at_least, below_box, past_limit, off_page }) + below_box |= labels_cut; + (cut || off_page || labels_cut).then(|| TextLoss { + id: e.id, + name: e.name.clone(), + left_out, + at_least, + below_box, + past_limit, + off_page, + }) }) .collect() } @@ -3742,10 +3761,12 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { } else { let ends = labels.first().map(|(_, s)| width(s)).unwrap_or(0.0).max(labels.last().map(|(_, s)| width(s)).unwrap_or(0.0)); let inset = (ends / 2.0).min(r.width() * 0.25); - // Too short for its labels (left out below), the bar fills the element. - let bh = match bottom - top - px * 1.2 - tick - gap { - h if h >= 3.0 * ppp => h, - _ => bottom - top, + // Too short for its labels (left out below, and said by [`text_losses`]), the bar fills + // the element. + let bh = if colorbar_labels_fit(bottom - top, ppp, Orientation::Horizontal) { + bottom - top - px * 1.2 - tick - gap + } else { + bottom - top }; let by = if bar.side == TickSide::Start { bottom - bh } else { top }; (r.x() + inset, by, (r.width() - 2.0 * inset).max(1.0), bh) @@ -3900,13 +3921,27 @@ fn colorbar_title_drawn(lines: usize, top: f32, limit: f32, px: f32) -> usize { } /// The least room a colorbar's bar takes under its title, in pixels at `ppp` (#2638), as -/// [`colorbar`] lays it out: a horizontal bar of 3 points with its ticks and 8-point labels under -/// it; a vertical one, whose labels are at its side, 3 points of bar. A title stops short of it, +/// [`colorbar`] lays it out: a horizontal bar 3 pixels thick (at 96 dpi) with its ticks and +/// 8-point labels under it; a vertical one, whose labels are at its side, two labels' height, so +/// its end labels, centred on the bar's ends, stay inside the element. A title stops short of it, /// so its lines never leave the bar without its labels. fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { match orientation { Orientation::Horizontal => (8.0 * 1.33 * 1.2 + 2.5 + 1.5 + 3.0) * ppp, - Orientation::Vertical => 3.0 * ppp, + Orientation::Vertical => 2.0 * 8.0 * 1.33 * ppp, + } +} + +/// Whether a colorbar's bar `h` pixels high, at `ppp`, has room for its labels as [`colorbar`] +/// places them (#2638): a horizontal one leaves 3 pixels of bar over its ticks and labels, else +/// the bar fills the element and its labels are left out; a vertical one insets its ends by half +/// a label, at most a quarter of its height, and a label past the element by more than a pixel +/// is left out. One rule for the drawing and the page's cut-off check ([`text_losses`]). +fn colorbar_labels_fit(h: f32, ppp: f32, orientation: Orientation) -> bool { + let px = 8.0 * 1.33 * ppp; + match orientation { + Orientation::Horizontal => h - px * 1.2 - 2.5 * ppp - 1.5 * ppp >= 3.0 * ppp, + Orientation::Vertical => (px / 2.0).min(h * 0.25) >= px / 2.0 - 1.0, } } @@ -7540,17 +7575,28 @@ Elaboração: RustGIS", assert!((40..50).any(dark), "its labels under it"); } - /// A vertical colorbar's labels are at its side, so its title needs only a bar's thickness - /// under it, not a horizontal bar's label band (#2638): a vertical colorbar 8 mm high draws - /// its one-line title and says nothing, where a horizontal one holds it back and says so. + /// A vertical colorbar's end labels are centred on its bar's ends, so its title leaves the bar + /// two labels' height (#2638): a vertical colorbar 25 px high (6.6 mm at 96 dpi) holds its + /// one-line title back and says so, its bar keeping both end labels, and one 12 mm high draws + /// the title and says nothing. A vertical colorbar too short for its end labels says so even + /// with no title, and a horizontal one too short for its labels under its bar, too. #[test] - fn a_vertical_colorbar_keeps_a_title_that_fits_beside_its_labels() { + fn a_vertical_colorbars_title_leaves_room_for_its_end_labels() { let map = ramp_map( rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, rustgis_map::raster::Stretch::MinMax, ); let info = PageInfo::default(); - for (orientation, cut) in [(Orientation::Vertical, false), (Orientation::Horizontal, true)] { + let mm = 25.4 / 96.0; + // (orientation, title, height in mm, a loss said, title lines left out) + for (orientation, title, h, said, left_out) in [ + (Orientation::Vertical, "Elevation (m)", 25.0 * mm, true, 1), + (Orientation::Vertical, "Elevation (m)", 12.0, false, 0), + (Orientation::Vertical, "", 12.0 * mm, true, 0), + (Orientation::Vertical, "", 25.0 * mm, false, 0), + (Orientation::Horizontal, "", 15.0 * mm, true, 0), + (Orientation::Horizontal, "", 25.0 * mm, false, 0), + ] { let mut l = Layout::new("Page", 120.0, 90.0); let frame = l.add( "Frame", @@ -7560,17 +7606,39 @@ Elaboração: RustGIS", let kind = ElementKind::Colorbar { frame, layer: None, - title: "Elevation (m)".into(), + title: title.into(), orientation, ticks: 5, tick_side: TickSide::End, reverse: false, color: None, }; - l.add("Colorbar", (5.0, 5.0, 25.0, 8.0), kind); + l.add("Colorbar", (5.0, 5.0, 25.0, h), kind); let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); - assert_eq!(losses.len() == 1, cut, "{orientation:?}: {losses:?}"); + let case = format!("{orientation:?} {title:?} {h:.1} mm: {losses:?}"); + assert_eq!(losses.len() == 1, said, "{case}"); + if let Some(loss) = losses.first() { + assert!(loss.below_box && loss.left_out == left_out, "{case}"); + } } + // As drawn: 25 px high, the title held back, both end labels inside the element. + let scale = ColorScale::Ramp { lo: 0.0, hi: 10.0, colors: vec![Rgba::rgb(220, 30, 30), Rgba::rgb(30, 30, 220)] }; + let bar = Bar { + title: "Elevation (m)", + orientation: Orientation::Vertical, + ticks: 2, + side: TickSide::End, + reverse: false, + comma: false, + ink: INK, + }; + let mut c = Canvas::new(200, 100).unwrap(); + colorbar(&mut c, Rect::from_xywh(10.0, 10.0, 100.0, 25.0).unwrap(), &scale, &bar, 1.0); + let dark = |x: u32, y: u32| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 128 && p.red() < 120 && p.blue() < 120); + // The labels stand to the bar's right, past its ticks: ink near its top end and its bottom. + let label_ink = |ys: std::ops::Range| ys.into_iter().any(|y| (60..110).any(|x| dark(x, y))); + assert!(label_ink(10..20), "the top end's label"); + assert!(label_ink(26..36), "the bottom end's label"); } /// A colorbar too short for a line of title over its bar holds the title back, and the bar From dc112ca97536eb8d6f17a35a1937fe42ffbb9f66 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 11:15:47 -0500 Subject: [PATCH 10/11] Address Claude review feedback - A colorbar cut off gets its own advice in clipped_text_notice (a taller colorbar or a shorter title, so its title lines and tick labels fit) instead of a text's "add line breaks": its title already wraps, and a tick label isn't fixed by a line break. --- crates/render/src/layout.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 6c4b6d7dd1..2f3c56ddf4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -480,8 +480,13 @@ pub fn clipped_text_notice(layout: &Layout, clipped: &[(u32, String)]) -> Option .collect::>(); // Scale bars alone: their labels are no text to break (#2581). let bars = clipped.iter().all(|(id, _)| matches!(layout.element(*id).map(|e| &e.kind), Some(ElementKind::ScaleBar { .. }))); + // Colorbars alone: their titles already wrap, and a tick label isn't fixed by a line break + // (#2638). + let colorbars = clipped.iter().all(|(id, _)| matches!(layout.element(*id).map(|e| &e.kind), Some(ElementKind::Colorbar { .. }))); let advice = if bars { "make the scale bar larger or move it inside the page, or reduce its text size" + } else if colorbars { + "make the colorbar taller or its title shorter, so its title lines and tick labels fit" } else if wraps.contains(&Some(false)) { "resize or move the text, reduce its size, add line breaks, or turn on Wrap to the box" } else if wraps.iter().all(|w| *w == Some(true)) { @@ -7619,6 +7624,9 @@ Elaboração: RustGIS", assert_eq!(losses.len() == 1, said, "{case}"); if let Some(loss) = losses.first() { assert!(loss.below_box && loss.left_out == left_out, "{case}"); + // Its own advice, not a text's line breaks. + let note = clipped_text_notice(&l, &[(loss.id, loss.name.clone())]).unwrap_or_default(); + assert!(note.contains("make the colorbar taller"), "{case}: {note}"); } } // As drawn: 25 px high, the title held back, both end labels inside the element. From 3c7f75093464312dad39cf13023ca95dcd19ba67 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 12:17:57 -0500 Subject: [PATCH 11/11] Address Claude review feedback - A colorbar's labels left out because they would spill out of its element are now said whatever the reason: too short, or too narrow for the labels beside a vertical bar. The layout is one function, colorbar_plan, which the drawing and the page's cut-off check both use, so they can't disagree; it replaces the height-only colorbar_labels_fit. --- crates/render/src/layout.rs | 218 +++++++++++++++++++++--------------- 1 file changed, 130 insertions(+), 88 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2f3c56ddf4..f75f1d94b9 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -375,19 +375,27 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option } // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its // frame's map has a raster with a colour scale (else it draws a placeholder). - // Its labels, too, when the element is too short for them under its title (#2638). - ElementKind::Colorbar { frame, layer, title, orientation, .. } => { + // Its labels, too, when they would spill out of the element (#2638), as the colorbar + // lays them out ([`colorbar_plan`]). + ElementKind::Colorbar { frame, layer, title, orientation, ticks, tick_side, reverse, .. } => { let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; let m = maps.get(map_index(maps, map)?)?; - rustgis_map::layout::colorbar_layer(m, layer.as_deref()) + let scale = rustgis_map::layout::colorbar_layer(m, layer.as_deref()) .and_then(|l| l.raster.as_ref()) .and_then(rustgis_map::layout::color_scale)?; + let bar = Bar { + title, + orientation: *orientation, + ticks: *ticks, + side: *tick_side, + reverse: *reverse, + comma: layout.decimal_comma, + ink: INK, + }; + let plan = colorbar_plan(r, &scale, &bar, ppp); let lines = if title.is_empty() { Vec::new() } else { colorbar_title_lines(title, e.w) }; - let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; - let limit = r.bottom() - colorbar_bar_room(ppp, *orientation); - let fits = colorbar_title_drawn(lines.len(), r.y(), limit, tpx); - let title_room = if fits > 0 { tpx * (1.4 + 1.25 * (fits - 1) as f32) } else { 0.0 }; - labels_cut = !colorbar_labels_fit(r.height() - title_room, ppp, *orientation); + let fits = plan.title.len(); + labels_cut = plan.spilled > 0; if lines.is_empty() && !labels_cut { return None; } @@ -3705,23 +3713,40 @@ fn tick_labels(lo: f64, hi: f64, n: usize) -> Vec<(f64, String)> { values.into_iter().map(|v| (v, format!("{:.*}", decimals, (v * k).round() / k + 0.0))).collect() } -/// A colorbar: the bar, ticks and labels along it, and its title above. -fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { - let ppp = ppp as f32; - let dark = bar.ink; +/// A colorbar laid out in its element ([`colorbar_plan`]): what [`colorbar`] draws, and what the +/// page's cut-off check ([`text_losses`]) says of it, from one layout. +struct ColorbarPlan { + /// The title's lines drawn, each with the middle of its line (pixels). + title: Vec<(String, f32)>, + /// The bar's blocks or samples, low to high, and its rectangle (x, y, width, height). + blocks: Vec, + rect: (f32, f32, f32, f32), + /// The bar runs down the page, and from high to low along it (its start is left or top). + vertical: bool, + flip: bool, + /// The labels drawn: each one's text, its tick's two ends, where it is drawn, and whether + /// centred on it (else from its left). + labels: Vec<(String, [(f32, f32); 2], (f32, f32), bool)>, + /// Labels left out because they would spill out of the element (#2638), not those thinned + /// for clearing the one before: a short or narrow element, or one with no room for a bar. + spilled: usize, +} + +/// A colorbar in `r` at `ppp` (#2638): its title's lines that fit over the bar's own room +/// ([`colorbar_title_drawn`]), the bar, leaving room for the labels on their side and for the end +/// labels to stand past its ends, and each label drawn only if it clears the one before and stays +/// inside the element. +fn colorbar_plan(r: Rect, scale: &ColorScale, bar: &Bar, ppp: f32) -> ColorbarPlan { let px = 8.0 * 1.33 * ppp; let width = |s: &str| text::measure(s, px / 1.33, false); let (mut top, bottom) = (r.y(), r.y() + r.height()); + let mut title = Vec::new(); if !bar.title.is_empty() { let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; - // Wrapped to the element's width (#2493), its lines drawn as long as they fit in it - // ([`colorbar_title_drawn`]). Those left out are said with the page's cut-off texts - // ([`text_losses`]). + // Wrapped to the element's width (#2493). let lines = colorbar_title_lines(bar.title, f64::from(r.width()) / (f64::from(ppp) * PT_PER_MM)); let drawn = colorbar_title_drawn(lines.len(), top, bottom - colorbar_bar_room(ppp, bar.orientation), tpx); - for (i, line) in lines.iter().take(drawn).enumerate() { - text::text_at(pm, line, r.x(), top + tpx * (0.6 + 1.25 * i as f32), tpx, dark, true, text::Align::Left, false); - } + title = lines.into_iter().take(drawn).enumerate().map(|(i, line)| (line, top + tpx * (0.6 + 1.25 * i as f32))).collect(); // A title held back whole takes no room: the bar starts at the element's top. if drawn > 0 { top += tpx * (1.4 + 1.25 * (drawn - 1) as f32); @@ -3748,15 +3773,20 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { (v.iter().map(|(_, c)| *c).collect(), labels) } }; - if blocks.is_empty() || r.width() < 2.0 || bottom - top < 2.0 { - return; + let vertical = bar.orientation == Orientation::Vertical; + let flip = if vertical { !bar.reverse } else { bar.reverse }; + let mut plan = ColorbarPlan { title, blocks: Vec::new(), rect: (0.0, 0.0, 0.0, 0.0), vertical, flip, labels: Vec::new(), spilled: 0 }; + if blocks.is_empty() { + return plan; + } + // No room for a bar: none is drawn, nor its labels. + if r.width() < 2.0 || bottom - top < 2.0 { + plan.spilled = labels.len(); + return plan; } let labels: Vec<(f32, String)> = labels.into_iter().map(|(at, s)| (at, decimal(s, bar.comma))).collect(); let tick = 2.5 * ppp; let gap = 1.5 * ppp; - let vertical = bar.orientation == Orientation::Vertical; - // The bar's rectangle, leaving room for the labels on their side and for the end labels to - // stand past the bar's ends. let (bx, by, bw, bh) = if vertical { let label_w = labels.iter().map(|(_, s)| width(s)).fold(0.0f32, f32::max); let bw = (r.width() - label_w - tick - gap).clamp(2.0 * ppp, (r.width() * 0.45).max(2.0 * ppp)).min(r.width()); @@ -3766,69 +3796,91 @@ fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { } else { let ends = labels.first().map(|(_, s)| width(s)).unwrap_or(0.0).max(labels.last().map(|(_, s)| width(s)).unwrap_or(0.0)); let inset = (ends / 2.0).min(r.width() * 0.25); - // Too short for its labels (left out below, and said by [`text_losses`]), the bar fills - // the element. - let bh = if colorbar_labels_fit(bottom - top, ppp, Orientation::Horizontal) { - bottom - top - px * 1.2 - tick - gap - } else { - bottom - top + // Too short for its labels (left out below, and said), the bar fills the element. + let bh = match bottom - top - px * 1.2 - tick - gap { + h if h >= 3.0 * ppp => h, + _ => bottom - top, }; let by = if bar.side == TickSide::Start { bottom - bh } else { top }; (r.x() + inset, by, (r.width() - 2.0 * inset).max(1.0), bh) }; + plan.blocks = blocks; + plan.rect = (bx, by, bw, bh); let len = if vertical { bh } else { bw }; - // Distance along the bar from its start (left or top) for a position from low to high. - let flip = if vertical { !bar.reverse } else { bar.reverse }; let along = |t: f32| if flip { (1.0 - t) * len } else { t * len }; - let n = blocks.len(); - for (i, c) in blocks.iter().enumerate() { - let (a, b) = (along(i as f32 / n as f32), along((i + 1) as f32 / n as f32)); - let (s0, s1) = (a.min(b), a.max(b)); - // A touch longer than its share, so neighbours leave no seam. - let rect = if vertical { Rect::from_xywh(bx, by + s0, bw, s1 - s0 + 0.6) } else { Rect::from_xywh(bx + s0, by, s1 - s0 + 0.6, bh) }; - if let Some(rect) = rect.and_then(|q| q.intersect(&Rect::from_xywh(bx, by, bw, bh)?)) { - pm.fill_rect(rect, &paint(*c, 1.0), Transform::identity(), None); - } - } - let line = Stroke { width: 0.6 * ppp, ..Stroke::default() }; - if let Some(b) = Rect::from_xywh(bx, by, bw, bh) { - pm.stroke_path(&PathBuilder::from_rect(b), &paint(dark, 1.0), &line, Transform::identity(), None); - } // A label (and its tick) is left out where it would spill out of a short or narrow element. let inside = |x: f32, y: f32, w: f32, h: f32| x >= r.x() - 1.0 && y >= r.y() - 1.0 && x + w <= r.right() + 1.0 && y + h <= r.bottom() + 1.0; // Labels in order along the bar, each drawn only if it clears the one before. let mut last_end = f32::NEG_INFINITY; - let mut ordered: Vec<(f32, &String)> = labels.iter().map(|(t, s)| (along(t.clamp(0.0, 1.0)), s)).collect(); + let mut ordered: Vec<(f32, String)> = labels.into_iter().map(|(t, s)| (along(t.clamp(0.0, 1.0)), s)).collect(); ordered.sort_by(|a, b| a.0.total_cmp(&b.0)); for (d, label) in ordered { - let extent = if vertical { px } else { width(label) }; + let lw = width(&label); + let extent = if vertical { px } else { lw }; if d - extent / 2.0 < last_end + gap { continue; } last_end = d + extent / 2.0; - let mut pb = PathBuilder::new(); - if vertical { + let (tick_ends, at, centred, fits) = if vertical { let (y, x0) = (by + d, if bar.side == TickSide::Start { bx } else { bx + bw }); let x1 = if bar.side == TickSide::Start { x0 - tick } else { x0 + tick }; - pb.move_to(x0, y); - pb.line_to(x1, y); - let lx = if bar.side == TickSide::Start { x1 - gap - width(label) } else { x1 + gap }; - if !inside(lx, y - px / 2.0, width(label), px) { - continue; - } - text::text_at(pm, label, lx, y, px, dark, false, text::Align::Left, false); + let lx = if bar.side == TickSide::Start { x1 - gap - lw } else { x1 + gap }; + ([(x0, y), (x1, y)], (lx, y), false, inside(lx, y - px / 2.0, lw, px)) } else { let (x, y0) = (bx + d, if bar.side == TickSide::Start { by } else { by + bh }); let y1 = if bar.side == TickSide::Start { y0 - tick } else { y0 + tick }; - pb.move_to(x, y0); - pb.line_to(x, y1); let ly = if bar.side == TickSide::Start { y1 - gap - px * 0.5 } else { y1 + gap + px * 0.5 }; - if !inside(x - width(label) / 2.0, ly - px / 2.0, width(label), px) { - continue; - } - text::text_at(pm, label, x, ly, px, dark, false, text::Align::Center, false); + ([(x, y0), (x, y1)], (x, ly), true, inside(x - lw / 2.0, ly - px / 2.0, lw, px)) + }; + if fits { + plan.labels.push((label, tick_ends, at, centred)); + } else { + plan.spilled += 1; + } + } + plan +} + +/// A colorbar: the bar, ticks and labels along it, and its title above, as [`colorbar_plan`] lays +/// them out. Title lines and labels left out are said with the page's cut-off texts +/// ([`text_losses`]). +fn colorbar(pm: &mut Canvas, r: Rect, scale: &ColorScale, bar: &Bar, ppp: f64) { + let ppp = ppp as f32; + let dark = bar.ink; + let px = 8.0 * 1.33 * ppp; + let plan = colorbar_plan(r, scale, bar, ppp); + let tpx = COLORBAR_TITLE_PT as f32 * 1.33 * ppp; + for (line, y) in &plan.title { + text::text_at(pm, line, r.x(), *y, tpx, dark, true, text::Align::Left, false); + } + if plan.blocks.is_empty() { + return; + } + let (bx, by, bw, bh) = plan.rect; + let len = if plan.vertical { bh } else { bw }; + let along = |t: f32| if plan.flip { (1.0 - t) * len } else { t * len }; + let n = plan.blocks.len(); + for (i, c) in plan.blocks.iter().enumerate() { + let (a, b) = (along(i as f32 / n as f32), along((i + 1) as f32 / n as f32)); + let (s0, s1) = (a.min(b), a.max(b)); + // A touch longer than its share, so neighbours leave no seam. + let rect = + if plan.vertical { Rect::from_xywh(bx, by + s0, bw, s1 - s0 + 0.6) } else { Rect::from_xywh(bx + s0, by, s1 - s0 + 0.6, bh) }; + if let Some(rect) = rect.and_then(|q| q.intersect(&Rect::from_xywh(bx, by, bw, bh)?)) { + pm.fill_rect(rect, &paint(*c, 1.0), Transform::identity(), None); } + } + let line = Stroke { width: 0.6 * ppp, ..Stroke::default() }; + if let Some(b) = Rect::from_xywh(bx, by, bw, bh) { + pm.stroke_path(&PathBuilder::from_rect(b), &paint(dark, 1.0), &line, Transform::identity(), None); + } + for (label, [(x0, y0), (x1, y1)], (x, y), centred) in &plan.labels { + let align = if *centred { text::Align::Center } else { text::Align::Left }; + text::text_at(pm, label, *x, *y, px, dark, false, align, false); + let mut pb = PathBuilder::new(); + pb.move_to(*x0, *y0); + pb.line_to(*x1, *y1); if let Some(p) = pb.finish() { pm.stroke_path(&p, &paint(dark, 1.0), &line, Transform::identity(), None); } @@ -3937,19 +3989,6 @@ fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { } } -/// Whether a colorbar's bar `h` pixels high, at `ppp`, has room for its labels as [`colorbar`] -/// places them (#2638): a horizontal one leaves 3 pixels of bar over its ticks and labels, else -/// the bar fills the element and its labels are left out; a vertical one insets its ends by half -/// a label, at most a quarter of its height, and a label past the element by more than a pixel -/// is left out. One rule for the drawing and the page's cut-off check ([`text_losses`]). -fn colorbar_labels_fit(h: f32, ppp: f32, orientation: Orientation) -> bool { - let px = 8.0 * 1.33 * ppp; - match orientation { - Orientation::Horizontal => h - px * 1.2 - 2.5 * ppp - 1.5 * ppp >= 3.0 * ppp, - Orientation::Vertical => (px / 2.0).min(h * 0.25) >= px / 2.0 - 1.0, - } -} - /// The distance between two lines of text at `size` points, in mm, as [`text_block`] sets them. pub fn line_pitch_mm(size: f64) -> f64 { size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 @@ -7583,24 +7622,27 @@ Elaboração: RustGIS", /// A vertical colorbar's end labels are centred on its bar's ends, so its title leaves the bar /// two labels' height (#2638): a vertical colorbar 25 px high (6.6 mm at 96 dpi) holds its /// one-line title back and says so, its bar keeping both end labels, and one 12 mm high draws - /// the title and says nothing. A vertical colorbar too short for its end labels says so even - /// with no title, and a horizontal one too short for its labels under its bar, too. + /// the title and says nothing. A vertical colorbar too short for its end labels, or too narrow + /// for its labels beside the bar, says so even with no title, and a horizontal one too short + /// for its labels under its bar, too. #[test] - fn a_vertical_colorbars_title_leaves_room_for_its_end_labels() { + fn a_colorbars_labels_left_out_are_said() { let map = ramp_map( rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Thermal, invert: false }, rustgis_map::raster::Stretch::MinMax, ); let info = PageInfo::default(); let mm = 25.4 / 96.0; - // (orientation, title, height in mm, a loss said, title lines left out) - for (orientation, title, h, said, left_out) in [ - (Orientation::Vertical, "Elevation (m)", 25.0 * mm, true, 1), - (Orientation::Vertical, "Elevation (m)", 12.0, false, 0), - (Orientation::Vertical, "", 12.0 * mm, true, 0), - (Orientation::Vertical, "", 25.0 * mm, false, 0), - (Orientation::Horizontal, "", 15.0 * mm, true, 0), - (Orientation::Horizontal, "", 25.0 * mm, false, 0), + // (orientation, title, width and height in mm, a loss said, title lines left out) + for (orientation, title, w, h, said, left_out) in [ + (Orientation::Vertical, "Elevation (m)", 25.0, 25.0 * mm, true, 1), + (Orientation::Vertical, "Elevation (m)", 25.0, 12.0, false, 0), + (Orientation::Vertical, "", 25.0, 12.0 * mm, true, 0), + (Orientation::Vertical, "", 25.0, 25.0 * mm, false, 0), + // Too narrow for its labels beside the bar: they're left out, and said. + (Orientation::Vertical, "", 2.0, 25.0, true, 0), + (Orientation::Horizontal, "", 25.0, 15.0 * mm, true, 0), + (Orientation::Horizontal, "", 25.0, 25.0 * mm, false, 0), ] { let mut l = Layout::new("Page", 120.0, 90.0); let frame = l.add( @@ -7618,9 +7660,9 @@ Elaboração: RustGIS", reverse: false, color: None, }; - l.add("Colorbar", (5.0, 5.0, 25.0, h), kind); + l.add("Colorbar", (5.0, 5.0, w, h), kind); let losses = text_losses(&l, std::slice::from_ref(&map), 96.0, &info); - let case = format!("{orientation:?} {title:?} {h:.1} mm: {losses:?}"); + let case = format!("{orientation:?} {title:?} {w:.1} × {h:.1} mm: {losses:?}"); assert_eq!(losses.len() == 1, said, "{case}"); if let Some(loss) = losses.first() { assert!(loss.below_box && loss.left_out == left_out, "{case}");